diff options
| author | Krzysztof Kosi??ski <tweenk.pl@gmail.com> | 2011-06-20 19:33:57 +0000 |
|---|---|---|
| committer | Krzysztof Kosiński <tweenk.pl@gmail.com> | 2011-06-20 19:33:57 +0000 |
| commit | a39e3c37a508f9a389fc55270ae0336ad2f76f0e (patch) | |
| tree | 952db81c3238005e975f21845734444bba28ff40 /src/display | |
| parent | Measure Tool: support measuring of text elements (without having to manually ... (diff) | |
| parent | Fix outline view (diff) | |
| download | inkscape-a39e3c37a508f9a389fc55270ae0336ad2f76f0e.tar.gz inkscape-a39e3c37a508f9a389fc55270ae0336ad2f76f0e.zip | |
Merge Cairo rendering branch
(bzr r10326)
Diffstat (limited to 'src/display')
96 files changed, 5262 insertions, 6876 deletions
diff --git a/src/display/Makefile_insert b/src/display/Makefile_insert index 370e28d6d..fc7c8e9ab 100644 --- a/src/display/Makefile_insert +++ b/src/display/Makefile_insert @@ -4,35 +4,23 @@ display/canvas-arena.$(OBJEXT): helper/sp-marshal.h display/sp-canvas.$(OBJEXT): helper/sp-marshal.h ink_common_sources += \ - display/nr-3dutils.h \ - display/nr-3dutils.cpp \ - display/nr-arena-forward.h \ - display/nr-arena.cpp \ - display/nr-arena.h \ - display/nr-arena-item.cpp \ - display/nr-arena-item.h \ - display/nr-arena-group.cpp \ - display/nr-arena-group.h \ - display/nr-arena-image.cpp \ - display/nr-arena-image.h \ - display/nr-arena-shape.cpp \ - display/nr-arena-shape.h \ - display/nr-arena-glyphs.cpp \ - display/nr-arena-glyphs.h \ + display/cairo-templates.h \ + display/cairo-utils.cpp \ + display/cairo-utils.h \ display/canvas-arena.cpp \ display/canvas-arena.h \ + display/canvas-axonomgrid.cpp \ + display/canvas-axonomgrid.h \ display/canvas-bpath.cpp \ display/canvas-bpath.h \ display/canvas-grid.cpp \ display/canvas-grid.h \ - display/canvas-axonomgrid.cpp \ - display/canvas-axonomgrid.h \ display/canvas-temporary-item.cpp \ display/canvas-temporary-item.h \ display/canvas-temporary-item-list.cpp \ display/canvas-temporary-item-list.h \ - display/canvas-text.h \ display/canvas-text.cpp \ + display/canvas-text.h \ display/curve.cpp \ display/curve.h \ display/gnome-canvas-acetate.cpp \ @@ -41,43 +29,32 @@ ink_common_sources += \ display/grayscale.h \ display/guideline.cpp \ display/guideline.h \ - display/nr-plain-stuff-gdk.cpp \ - display/nr-plain-stuff-gdk.h \ - display/nr-plain-stuff.cpp \ - display/nr-plain-stuff.h \ - display/nr-svgfonts.cpp \ - display/nr-svgfonts.h \ - display/rendermode.h \ - display/snap-indicator.cpp \ - display/snap-indicator.h \ - display/sodipodi-ctrl.cpp \ - display/sodipodi-ctrl.h \ - display/sodipodi-ctrlrect.cpp \ - display/sodipodi-ctrlrect.h \ - display/sp-canvas-group.h \ - display/sp-canvas-item.h \ - display/sp-canvas-util.cpp \ - display/sp-canvas-util.h \ - display/sp-canvas.cpp \ - display/sp-canvas.h \ - display/sp-ctrlline.cpp \ - display/sp-ctrlline.h \ - display/sp-ctrlpoint.cpp \ - display/sp-ctrlpoint.h \ - display/sp-ctrlquadr.cpp \ - display/sp-ctrlquadr.h \ - display/nr-filter.cpp \ - display/nr-filter.h \ + display/nr-3dutils.cpp \ + display/nr-3dutils.h \ + display/nr-arena.cpp \ + display/nr-arena-forward.h \ + display/nr-arena-glyphs.cpp \ + display/nr-arena-glyphs.h \ + display/nr-arena-group.cpp \ + display/nr-arena-group.h \ + display/nr-arena.h \ + display/nr-arena-image.cpp \ + display/nr-arena-image.h \ + display/nr-arena-item.cpp \ + display/nr-arena-item.h \ + display/nr-arena-shape.cpp \ + display/nr-arena-shape.h \ display/nr-filter-blend.cpp \ display/nr-filter-blend.h \ display/nr-filter-colormatrix.cpp \ display/nr-filter-colormatrix.h \ display/nr-filter-component-transfer.cpp \ display/nr-filter-component-transfer.h \ - display/nr-filter-composite.h \ display/nr-filter-composite.cpp \ + display/nr-filter-composite.h \ display/nr-filter-convolve-matrix.cpp \ display/nr-filter-convolve-matrix.h \ + display/nr-filter.cpp \ display/nr-filter-diffuselighting.cpp \ display/nr-filter-diffuselighting.h \ display/nr-filter-displacement-map.cpp \ @@ -86,8 +63,7 @@ ink_common_sources += \ display/nr-filter-flood.h \ display/nr-filter-gaussian.cpp \ display/nr-filter-gaussian.h \ - display/nr-filter-getalpha.cpp \ - display/nr-filter-getalpha.h \ + display/nr-filter.h \ display/nr-filter-image.cpp \ display/nr-filter-image.h \ display/nr-filter-merge.cpp \ @@ -106,21 +82,35 @@ ink_common_sources += \ display/nr-filter-tile.h \ display/nr-filter-turbulence.cpp \ display/nr-filter-turbulence.h \ - display/nr-filter-pixops.h \ display/nr-filter-types.h \ - display/nr-filter-units.h \ display/nr-filter-units.cpp \ - display/nr-filter-utils.h \ + display/nr-filter-units.h \ display/nr-filter-utils.cpp \ - display/pixblock-scaler.cpp \ - display/pixblock-scaler.h \ - display/pixblock-transform.cpp \ - display/pixblock-transform.h \ - display/inkscape-cairo.cpp \ - display/inkscape-cairo.h \ - display/nr-light.h \ + display/nr-filter-utils.h \ display/nr-light.cpp \ - display/nr-light-types.h + display/nr-light.h \ + display/nr-light-types.h \ + display/nr-style.cpp \ + display/nr-style.h \ + display/nr-svgfonts.cpp \ + display/nr-svgfonts.h \ + display/rendermode.h \ + display/snap-indicator.cpp \ + display/snap-indicator.h \ + display/sodipodi-ctrl.cpp \ + display/sodipodi-ctrl.h \ + display/sodipodi-ctrlrect.cpp \ + display/sodipodi-ctrlrect.h \ + display/sp-canvas.cpp \ + display/sp-canvas.h \ + display/sp-canvas-util.cpp \ + display/sp-canvas-util.h \ + display/sp-ctrlline.cpp \ + display/sp-ctrlline.h \ + display/sp-ctrlpoint.cpp \ + display/sp-ctrlpoint.h \ + display/sp-ctrlquadr.cpp \ + display/sp-ctrlquadr.h # ###################### # ### CxxTest stuff #### diff --git a/src/display/cairo-templates.h b/src/display/cairo-templates.h new file mode 100644 index 000000000..a79f58548 --- /dev/null +++ b/src/display/cairo-templates.h @@ -0,0 +1,689 @@ +/** + * @file + * @brief Cairo software blending templates + *//* + * Authors: + * Krzysztof Kosiński <tweenk.pl@gmail.com> + * + * Copyright (C) 2010 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef SEEN_INKSCAPE_DISPLAY_CAIRO_TEMPLATES_H +#define SEEN_INKSCAPE_DISPLAY_CAIRO_TEMPLATES_H + +#ifdef HAVE_OPENMP +#include <omp.h> +#include "preferences.h" +// single-threaded operation if the number of pixels is below this threshold +static const int OPENMP_THRESHOLD = 2048; +#endif + +#include <algorithm> +#include <cairo.h> +#include <glib.h> +#include <math.h> +#include "display/nr-3dutils.h" +#include "display/cairo-utils.h" + +/** + * @brief Blend two surfaces using the supplied functor. + * This template blends two Cairo image surfaces using a blending functor that takes + * two 32-bit ARGB pixel values and returns a modified 32-bit pixel value. + * Differences in input surface formats are handled transparently. In future, this template + * will also handle software fallback for GL surfaces. */ +template <typename Blend> +void ink_cairo_surface_blend(cairo_surface_t *in1, cairo_surface_t *in2, cairo_surface_t *out, Blend blend) +{ + cairo_surface_flush(in1); + cairo_surface_flush(in2); + + // ASSUMPTIONS + // 1. Cairo ARGB32 surface strides are always divisible by 4 + // 2. We can only receive CAIRO_FORMAT_ARGB32 or CAIRO_FORMAT_A8 surfaces + // 3. Both surfaces are of the same size + // 4. Output surface is ARGB32 if at least one input is ARGB32 + + int w = cairo_image_surface_get_width(in2); + int h = cairo_image_surface_get_height(in2); + int stride1 = cairo_image_surface_get_stride(in1); + int stride2 = cairo_image_surface_get_stride(in2); + int strideout = cairo_image_surface_get_stride(out); + int bpp1 = cairo_image_surface_get_format(in1) == CAIRO_FORMAT_A8 ? 1 : 4; + int bpp2 = cairo_image_surface_get_format(in2) == CAIRO_FORMAT_A8 ? 1 : 4; + int bppout = std::max(bpp1, bpp2); + + // Check whether we can loop over pixels without taking stride into account. + bool fast_path = true; + fast_path &= (stride1 == w * bpp1); + fast_path &= (stride2 == w * bpp2); + fast_path &= (strideout == w * bppout); + + int limit = w * h; + + guint32 *const in1_data = (guint32*) cairo_image_surface_get_data(in1); + guint32 *const in2_data = (guint32*) cairo_image_surface_get_data(in2); + guint32 *const out_data = (guint32*) cairo_image_surface_get_data(out); + + // NOTE + // OpenMP probably doesn't help much here. + // It would be better to render more than 1 tile at a time. + #if HAVE_OPENMP + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int num_threads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); + #endif + + // The number of code paths here is evil. + if (bpp1 == 4) { + if (bpp2 == 4) { + if (fast_path) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + *(out_data + i) = blend(*(in1_data + i), *(in2_data + i)); + } + } else { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint32 *in1_p = in1_data + i * stride1/4; + guint32 *in2_p = in2_data + i * stride2/4; + guint32 *out_p = out_data + i * strideout/4; + for (int j = 0; j < w; ++j) { + *out_p = blend(*in1_p, *in2_p); + ++in1_p; ++in2_p; ++out_p; + } + } + } + } else { + // bpp2 == 1 + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint32 *in1_p = in1_data + i * stride1/4; + guint8 *in2_p = reinterpret_cast<guint8*>(in2_data) + i * stride2; + guint32 *out_p = out_data + i * strideout/4; + for (int j = 0; j < w; ++j) { + guint32 in2_px = *in2_p; + in2_px <<= 24; + *out_p = blend(*in1_p, in2_px); + ++in1_p; ++in2_p; ++out_p; + } + } + } + } else { + if (bpp2 == 4) { + // bpp1 == 1 + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint8 *in1_p = reinterpret_cast<guint8*>(in1_data) + i * stride1; + guint32 *in2_p = in2_data + i * stride2/4; + guint32 *out_p = out_data + i * strideout/4; + for (int j = 0; j < w; ++j) { + guint32 in1_px = *in1_p; + in1_px <<= 24; + *out_p = blend(in1_px, *in2_p); + ++in1_p; ++in2_p; ++out_p; + } + } + } else { + // bpp1 == 1 && bpp2 == 1 + if (fast_path) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + guint8 *in1_p = reinterpret_cast<guint8*>(in1_data) + i; + guint8 *in2_p = reinterpret_cast<guint8*>(in2_data) + i; + guint8 *out_p = reinterpret_cast<guint8*>(out_data) + i; + guint32 in1_px = *in1_p; in1_px <<= 24; + guint32 in2_px = *in2_p; in2_px <<= 24; + guint32 out_px = blend(in1_px, in2_px); + *out_p = out_px >> 24; + } + } else { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint8 *in1_p = reinterpret_cast<guint8*>(in1_data) + i * stride1; + guint8 *in2_p = reinterpret_cast<guint8*>(in2_data) + i * stride2; + guint8 *out_p = reinterpret_cast<guint8*>(out_data) + i * strideout; + for (int j = 0; j < w; ++j) { + guint32 in1_px = *in1_p; in1_px <<= 24; + guint32 in2_px = *in2_p; in2_px <<= 24; + guint32 out_px = blend(in1_px, in2_px); + *out_p = out_px >> 24; + ++in1_p; ++in2_p; ++out_p; + } + } + } + } + } + + cairo_surface_mark_dirty(out); +} + +template <typename Filter> +void ink_cairo_surface_filter(cairo_surface_t *in, cairo_surface_t *out, Filter filter) +{ + cairo_surface_flush(in); + + // ASSUMPTIONS + // 1. Cairo ARGB32 surface strides are always divisible by 4 + // 2. We can only receive CAIRO_FORMAT_ARGB32 or CAIRO_FORMAT_A8 surfaces + // 3. Surfaces have the same dimensions + // 4. Output surface is A8 if input is A8 + + int w = cairo_image_surface_get_width(in); + int h = cairo_image_surface_get_height(in); + int stridein = cairo_image_surface_get_stride(in); + int strideout = cairo_image_surface_get_stride(out); + int bppin = cairo_image_surface_get_format(in) == CAIRO_FORMAT_A8 ? 1 : 4; + int bppout = cairo_image_surface_get_format(out) == CAIRO_FORMAT_A8 ? 1 : 4; + int limit = w * h; + + // Check whether we can loop over pixels without taking stride into account. + bool fast_path = true; + fast_path &= (stridein == w * bppin); + fast_path &= (strideout == w * bppout); + + guint32 *const in_data = (guint32*) cairo_image_surface_get_data(in); + guint32 *const out_data = (guint32*) cairo_image_surface_get_data(out); + + #if HAVE_OPENMP + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int num_threads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); + #endif + + // this is provided just in case, to avoid problems with strict aliasing rules + if (in == out) { + if (bppin == 4) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + *(in_data + i) = filter(*(in_data + i)); + } + } else { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + guint8 *in_p = reinterpret_cast<guint8*>(in_data) + i; + guint32 in_px = *in_p; in_px <<= 24; + guint32 out_px = filter(in_px); + *in_p = out_px >> 24; + } + } + cairo_surface_mark_dirty(out); + return; + } + + if (bppin == 4) { + if (bppout == 4) { + // bppin == 4, bppout == 4 + if (fast_path) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + *(out_data + i) = filter(*(in_data + i)); + } + } else { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint32 *in_p = in_data + i * stridein/4; + guint32 *out_p = out_data + i * strideout/4; + for (int j = 0; j < w; ++j) { + *out_p = filter(*in_p); + ++in_p; ++out_p; + } + } + } + } else { + // bppin == 4, bppout == 1 + // we use this path with COLORMATRIX_LUMINANCETOALPHA + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint32 *in_p = in_data + i * stridein/4; + guint8 *out_p = reinterpret_cast<guint8*>(out_data) + i * strideout; + for (int j = 0; j < w; ++j) { + guint32 out_px = filter(*in_p); + *out_p = out_px >> 24; + ++in_p; ++out_p; + } + } + } + } else { + // bppin == 1, bppout == 1 + // Note: there is no path for bppin == 1, bppout == 4 because it is useless + if (fast_path) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < limit; ++i) { + guint8 *in_p = reinterpret_cast<guint8*>(in_data) + i; + guint8 *out_p = reinterpret_cast<guint8*>(out_data) + i; + guint32 in_px = *in_p; in_px <<= 24; + guint32 out_px = filter(in_px); + *out_p = out_px >> 24; + } + } else { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = 0; i < h; ++i) { + guint8 *in_p = reinterpret_cast<guint8*>(in_data) + i * stridein; + guint8 *out_p = reinterpret_cast<guint8*>(out_data) + i * strideout; + for (int j = 0; j < w; ++j) { + guint32 in_px = *in_p; in_px <<= 24; + guint32 out_px = filter(in_px); + *out_p = out_px >> 24; + ++in_p; ++out_p; + } + } + } + } + cairo_surface_mark_dirty(out); +} + + +/** + * @brief Synthesize surface pixels based on their position. + * This template accepts a functor that gets called with the x and y coordinates of the pixels, + * given as integers. + * @param out Output surface + * @param out_area The region of the output surface that should be synthesized + * @param synth Synthesis functor */ +template <typename Synth> +void ink_cairo_surface_synthesize(cairo_surface_t *out, cairo_rectangle_t const &out_area, Synth synth) +{ + // ASSUMPTIONS + // 1. Cairo ARGB32 surface strides are always divisible by 4 + // 2. We can only receive CAIRO_FORMAT_ARGB32 or CAIRO_FORMAT_A8 surfaces + + int w = out_area.width; + int h = out_area.height; + int strideout = cairo_image_surface_get_stride(out); + int bppout = cairo_image_surface_get_format(out) == CAIRO_FORMAT_A8 ? 1 : 4; + // NOTE: fast path is not used, because we would need 2 divisions to get pixel indices + + unsigned char *out_data = cairo_image_surface_get_data(out); + + #if HAVE_OPENMP + int limit = w * h; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + int num_threads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); + #endif + + if (bppout == 4) { + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = out_area.y; i < h; ++i) { + guint32 *out_p = reinterpret_cast<guint32*>(out_data + i * strideout); + for (int j = out_area.x; j < w; ++j) { + *out_p = synth(j, i); + ++out_p; + } + } + } else { + // bppout == 1 + #if HAVE_OPENMP + #pragma omp parallel for if(limit > OPENMP_THRESHOLD) num_threads(num_threads) + #endif + for (int i = out_area.y; i < h; ++i) { + guint8 *out_p = out_data + i * strideout; + for (int j = out_area.x; j < w; ++j) { + guint32 out_px = synth(j, i); + *out_p = out_px >> 24; + ++out_p; + } + } + } + cairo_surface_mark_dirty(out); +} + +template <typename Synth> +void ink_cairo_surface_synthesize(cairo_surface_t *out, Synth synth) +{ + int w = cairo_image_surface_get_width(out); + int h = cairo_image_surface_get_height(out); + + cairo_rectangle_t area; + area.x = 0; + area.y = 0; + area.width = w; + area.height = h; + + ink_cairo_surface_synthesize(out, area, synth); +} + +struct SurfaceSynth { + SurfaceSynth(cairo_surface_t *surface) + : _px(cairo_image_surface_get_data(surface)) + , _w(cairo_image_surface_get_width(surface)) + , _h(cairo_image_surface_get_height(surface)) + , _stride(cairo_image_surface_get_stride(surface)) + , _alpha(cairo_surface_get_content(surface) == CAIRO_CONTENT_ALPHA) + { + cairo_surface_flush(surface); + } + + guint32 pixelAt(int x, int y) const { + if (_alpha) { + unsigned char *px = _px + y*_stride + x; + return *px << 24; + } else { + unsigned char *px = _px + y*_stride + x*4; + return *reinterpret_cast<guint32*>(px); + } + } + guint32 alphaAt(int x, int y) const { + if (_alpha) { + unsigned char *px = _px + y*_stride + x; + return *px; + } else { + unsigned char *px = _px + y*_stride + x*4; + guint32 p = *reinterpret_cast<guint32*>(px); + return (p & 0xff000000) >> 24; + } + } + + // retrieve a pixel value with bilinear interpolation + guint32 pixelAt(double x, double y) const { + if (_alpha) { + return alphaAt(x, y) << 24; + } + + double xf = floor(x), yf = floor(y); + int xi = xf, yi = yf; + guint32 xif = round((x - xf) * 255), yif = round((y - yf) * 255); + guint32 p00, p01, p10, p11; + + unsigned char *pxi = _px + yi*_stride + xi*4; + guint32 *pxu = reinterpret_cast<guint32*>(pxi); + guint32 *pxl = reinterpret_cast<guint32*>(pxi + _stride); + p00 = *pxu; p10 = *(pxu + 1); + p01 = *pxl; p11 = *(pxl + 1); + + guint32 comp[4]; + + for (unsigned i = 0; i < 4; ++i) { + guint32 shift = i*8; + guint32 mask = 0xff << shift; + guint32 c00 = (p00 & mask) >> shift; + guint32 c10 = (p10 & mask) >> shift; + guint32 c01 = (p01 & mask) >> shift; + guint32 c11 = (p11 & mask) >> shift; + + guint32 iu = (255-xif) * c00 + xif * c10; + guint32 il = (255-xif) * c01 + xif * c11; + comp[i] = (255-yif) * iu + yif * il; + comp[i] = (comp[i] + (255*255/2)) / (255*255); + } + + guint32 result = comp[0] | (comp[1] << 8) | (comp[2] << 16) | (comp[3] << 24); + return result; + } + + // retrieve an alpha value with bilinear interpolation + guint32 alphaAt(double x, double y) const { + double xf = floor(x), yf = floor(y); + int xi = xf, yi = yf; + guint32 xif = round((x - xf) * 255), yif = round((y - yf) * 255); + guint32 p00, p01, p10, p11; + if (_alpha) { + unsigned char *pxu = _px + yi*_stride + xi; + unsigned char *pxl = pxu + _stride; + p00 = *pxu; p10 = *(pxu + 1); + p01 = *pxl; p11 = *(pxl + 1); + } else { + unsigned char *pxi = _px + yi*_stride + xi*4; + guint32 *pxu = reinterpret_cast<guint32*>(pxi); + guint32 *pxl = reinterpret_cast<guint32*>(pxi + _stride); + p00 = (*pxu & 0xff000000) >> 24; p10 = (*(pxu + 1) & 0xff000000) >> 24; + p01 = (*pxl & 0xff000000) >> 24; p11 = (*(pxl + 1) & 0xff000000) >> 24; + } + guint32 iu = (255-xif) * p00 + xif * p10; + guint32 il = (255-xif) * p01 + xif * p11; + guint32 result = (255-yif) * iu + yif * il; + result = (result + (255*255/2)) / (255*255); + return result; + } + + // compute surface normal at given coordinates using 3x3 Sobel gradient filter + NR::Fvector surfaceNormalAt(int x, int y, double scale) const { + // Below there are some multiplies by zero. They will be optimized out. + // Do not remove them, because they improve readability. + // NOTE: fetching using alphaAt is slightly lazy. + NR::Fvector normal; + double fx = -scale/255.0, fy = -scale/255.0; + normal[Z_3D] = 1.0; + if (G_UNLIKELY(x == 0)) { + // leftmost column + if (G_UNLIKELY(y == 0)) { + // upper left corner + fx *= (2.0/3.0); + fy *= (2.0/3.0); + double p00 = alphaAt(x,y), p10 = alphaAt(x+1, y), + p01 = alphaAt(x,y+1), p11 = alphaAt(x+1, y+1); + normal[X_3D] = + -2.0 * p00 +2.0 * p10 + -1.0 * p01 +1.0 * p11; + normal[Y_3D] = + -2.0 * p00 -1.0 * p10 + +2.0 * p01 +1.0 * p11; + } else if (G_UNLIKELY(y == (_h - 1))) { + // lower left corner + fx *= (2.0/3.0); + fy *= (2.0/3.0); + double p00 = alphaAt(x,y-1), p10 = alphaAt(x+1, y-1), + p01 = alphaAt(x,y ), p11 = alphaAt(x+1, y); + normal[X_3D] = + -1.0 * p00 +1.0 * p10 + -2.0 * p01 +2.0 * p11; + normal[Y_3D] = + -2.0 * p00 -1.0 * p10 + +2.0 * p01 +1.0 * p11; + } else { + // leftmost column + fx *= (1.0/2.0); + fy *= (1.0/3.0); + double p00 = alphaAt(x, y-1), p10 = alphaAt(x+1, y-1), + p01 = alphaAt(x, y ), p11 = alphaAt(x+1, y ), + p02 = alphaAt(x, y+1), p12 = alphaAt(x+1, y+1); + normal[X_3D] = + -1.0 * p00 +1.0 * p10 + -2.0 * p01 +2.0 * p11 + -1.0 * p02 +1.0 * p12; + normal[Y_3D] = + -2.0 * p00 -1.0 * p10 + +0.0 * p01 +0.0 * p11 // this will be optimized out + +2.0 * p02 +1.0 * p12; + } + } else if (G_UNLIKELY(x == (_w - 1))) { + // rightmost column + if (G_UNLIKELY(y == 0)) { + // top right corner + fx *= (2.0/3.0); + fy *= (2.0/3.0); + double p00 = alphaAt(x-1,y), p10 = alphaAt(x, y), + p01 = alphaAt(x-1,y+1), p11 = alphaAt(x, y+1); + normal[X_3D] = + -2.0 * p00 +2.0 * p10 + -1.0 * p01 +1.0 * p11; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 + +1.0 * p01 +2.0 * p11; + } else if (G_UNLIKELY(y == (_h - 1))) { + // bottom right corner + fx *= (2.0/3.0); + fy *= (2.0/3.0); + double p00 = alphaAt(x-1,y-1), p10 = alphaAt(x, y-1), + p01 = alphaAt(x-1,y ), p11 = alphaAt(x, y); + normal[X_3D] = + -1.0 * p00 +1.0 * p10 + -2.0 * p01 +2.0 * p11; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 + +1.0 * p01 +2.0 * p11; + } else { + // rightmost column + fx *= (1.0/2.0); + fy *= (1.0/3.0); + double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), + p01 = alphaAt(x-1, y ), p11 = alphaAt(x, y ), + p02 = alphaAt(x-1, y+1), p12 = alphaAt(x, y+1); + normal[X_3D] = + -1.0 * p00 +1.0 * p10 + -2.0 * p01 +2.0 * p11 + -1.0 * p02 +1.0 * p12; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 + +0.0 * p01 +0.0 * p11 + +1.0 * p02 +2.0 * p12; + } + } else { + // interior + if (G_UNLIKELY(y == 0)) { + // top row + fx *= (1.0/3.0); + fy *= (1.0/2.0); + double p00 = alphaAt(x-1, y ), p10 = alphaAt(x, y ), p20 = alphaAt(x+1, y ), + p01 = alphaAt(x-1, y+1), p11 = alphaAt(x, y+1), p21 = alphaAt(x+1, y+1); + normal[X_3D] = + -2.0 * p00 +0.0 * p10 +2.0 * p20 + -1.0 * p01 +0.0 * p11 +1.0 * p21; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 -1.0 * p20 + +1.0 * p01 +2.0 * p11 +1.0 * p21; + } else if (G_UNLIKELY(y == (_h - 1))) { + // bottom row + fx *= (1.0/3.0); + fy *= (1.0/2.0); + double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), p20 = alphaAt(x+1, y-1), + p01 = alphaAt(x-1, y ), p11 = alphaAt(x, y ), p21 = alphaAt(x+1, y ); + normal[X_3D] = + -1.0 * p00 +0.0 * p10 +1.0 * p20 + -2.0 * p01 +0.0 * p11 +2.0 * p21; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 -1.0 * p20 + +1.0 * p01 +2.0 * p11 +1.0 * p21; + } else { + // interior pixels + // note: p11 is actually unused, so we don't fetch its value + fx *= (1.0/4.0); + fy *= (1.0/4.0); + double p00 = alphaAt(x-1, y-1), p10 = alphaAt(x, y-1), p20 = alphaAt(x+1, y-1), + p01 = alphaAt(x-1, y ), p11 = 0.0, p21 = alphaAt(x+1, y ), + p02 = alphaAt(x-1, y+1), p12 = alphaAt(x, y+1), p22 = alphaAt(x+1, y+1); + normal[X_3D] = + -1.0 * p00 +0.0 * p10 +1.0 * p20 + -2.0 * p01 +0.0 * p11 +2.0 * p21 + -1.0 * p02 +0.0 * p12 +1.0 * p22; + normal[Y_3D] = + -1.0 * p00 -2.0 * p10 -1.0 * p20 + +0.0 * p01 +0.0 * p11 +0.0 * p21 + +1.0 * p02 +2.0 * p12 +1.0 * p22; + } + } + normal[X_3D] *= fx; + normal[Y_3D] *= fy; + NR::normalize_vector(normal); + return normal; + } + + unsigned char *_px; + int _w, _h, _stride; + bool _alpha; +}; + +/* +// simple pixel accessor for image surface that handles different edge wrapping modes +class PixelAccessor { +public: + typedef PixelAccessor self; + enum EdgeMode { + EDGE_PAD, + EDGE_WRAP, + EDGE_ZERO + }; + + PixelAccessor(cairo_surface_t *s, EdgeMode e) + : _surface(s) + , _px(cairo_image_surface_get_data(s)) + , _x(0), _y(0) + , _w(cairo_image_surface_get_width(s)) + , _h(cairo_image_surface_get_height(s)) + , _stride(cairo_image_surface_get_stride(s)) + , _edge_mode(e) + , _alpha(cairo_image_surface_get_format(s) == CAIRO_FORMAT_A8) + {} + + guint32 pixelAt(int x, int y) { + // This is a lot of ifs for a single pixel access. However, branch prediction + // should help us a lot, as the result of ifs is always the same for a single image. + int real_x = x, real_y = y; + switch (_edge_mode) { + case EDGE_PAD: + real_x = CLAMP(x, 0, _w-1); + real_y = CLAMP(y, 0, _h-1); + break; + case EDGE_WRAP: + real_x %= _w; + real_y %= _h; + break; + case EDGE_ZERO: + default: + if (x < 0 || x >= _w || y < 0 || y >= _h) + return 0; + break; + } + if (_alpha) { + return *(_px + real_y*_stride + real_x) << 24; + } else { + guint32 *px = reinterpret_cast<guint32*>(_px +real_y*_stride + real_x*4); + return *px; + } + } +private: + cairo_surface_t *_surface; + guint8 *_px; + int _x, _y, _w, _h, _stride; + EdgeMode _edge_mode; + bool _alpha; +};*/ + +// Some helpers for pixel manipulation +G_GNUC_CONST inline gint32 +pxclamp(gint32 v, gint32 low, gint32 high) { + // NOTE: it is possible to write a "branchless" clamping operation. + // However, it will be slower than this function, because the code below + // is compiled to conditional moves. + if (v < low) return low; + if (v > high) return high; + return v; +} + +#endif +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/src/display/cairo-utils.cpp b/src/display/cairo-utils.cpp new file mode 100644 index 000000000..90f65c33e --- /dev/null +++ b/src/display/cairo-utils.cpp @@ -0,0 +1,700 @@ +/* + * Helper functions to use cairo with inkscape + * + * Copyright (C) 2007 bulia byak + * Copyright (C) 2008 Johan Engelen + * + * Released under GNU GPL + * + */ + +#ifdef HAVE_CONFIG_H +# include <config.h> +#endif + +#include "display/cairo-utils.h" + +#include <stdexcept> +#include <2geom/pathvector.h> +#include <2geom/bezier-curve.h> +#include <2geom/hvlinesegment.h> +#include <2geom/affine.h> +#include <2geom/point.h> +#include <2geom/path.h> +#include <2geom/transforms.h> +#include <2geom/sbasis-to-bezier.h> +#include "color.h" +#include "helper/geom-curves.h" + +namespace Inkscape { + +CairoGroup::CairoGroup(cairo_t *_ct) : ct(_ct), pushed(false) {} +CairoGroup::~CairoGroup() { + if (pushed) { + cairo_pattern_t *p = cairo_pop_group(ct); + cairo_pattern_destroy(p); + } +} +void CairoGroup::push() { + cairo_push_group(ct); + pushed = true; +} +void CairoGroup::push_with_content(cairo_content_t content) { + cairo_push_group_with_content(ct, content); + pushed = true; +} +cairo_pattern_t *CairoGroup::pop() { + if (pushed) { + cairo_pattern_t *ret = cairo_pop_group(ct); + pushed = false; + return ret; + } else { + throw std::logic_error("Cairo group popped without pushing it first"); + } +} +Cairo::RefPtr<Cairo::Pattern> CairoGroup::popmm() { + if (pushed) { + cairo_pattern_t *ret = cairo_pop_group(ct); + Cairo::RefPtr<Cairo::Pattern> retmm(new Cairo::Pattern(ret, true)); + pushed = false; + return retmm; + } else { + throw std::logic_error("Cairo group popped without pushing it first"); + } +} +void CairoGroup::pop_to_source() { + if (pushed) { + cairo_pop_group_to_source(ct); + pushed = false; + } +} + +CairoContext::CairoContext(cairo_t *obj, bool ref) + : Cairo::Context(obj, ref) +{} + +void CairoContext::transform(Geom::Affine const &m) +{ + cairo_matrix_t cm; + cm.xx = m[0]; + cm.xy = m[2]; + cm.x0 = m[4]; + cm.yx = m[1]; + cm.yy = m[3]; + cm.y0 = m[5]; + cairo_transform(cobj(), &cm); +} + +void CairoContext::set_source_rgba32(guint32 color) +{ + double red = SP_RGBA32_R_F(color); + double gre = SP_RGBA32_G_F(color); + double blu = SP_RGBA32_B_F(color); + double alp = SP_RGBA32_A_F(color); + cairo_set_source_rgba(cobj(), red, gre, blu, alp); +} + +void CairoContext::append_path(Geom::PathVector const &pv) +{ + feed_pathvector_to_cairo(cobj(), pv); +} + +Cairo::RefPtr<CairoContext> CairoContext::create(Cairo::RefPtr<Cairo::Surface> const &target) +{ + cairo_t *ct = cairo_create(target->cobj()); + Cairo::RefPtr<CairoContext> ret(new CairoContext(ct, true)); + return ret; +} + +} // namespace Inkscape + +/* + * Can be called recursively. + * If optimize_stroke == false, the view Rect is not used. + */ +static void +feed_curve_to_cairo(cairo_t *cr, Geom::Curve const &c, Geom::Affine const & trans, Geom::Rect view, bool optimize_stroke) +{ + if( is_straight_curve(c) ) + { + Geom::Point end_tr = c.finalPoint() * trans; + if (!optimize_stroke) { + cairo_line_to(cr, end_tr[0], end_tr[1]); + } else { + Geom::Rect swept(c.initialPoint()*trans, end_tr); + if (swept.intersects(view)) { + cairo_line_to(cr, end_tr[0], end_tr[1]); + } else { + cairo_move_to(cr, end_tr[0], end_tr[1]); + } + } + } + else if(Geom::QuadraticBezier const *quadratic_bezier = dynamic_cast<Geom::QuadraticBezier const*>(&c)) { + std::vector<Geom::Point> points = quadratic_bezier->points(); + points[0] *= trans; + points[1] *= trans; + points[2] *= trans; + Geom::Point b1 = points[0] + (2./3) * (points[1] - points[0]); + Geom::Point b2 = b1 + (1./3) * (points[2] - points[0]); + if (!optimize_stroke) { + cairo_curve_to(cr, b1[0], b1[1], b2[0], b2[1], points[2][0], points[2][1]); + } else { + Geom::Rect swept(points[0], points[2]); + swept.expandTo(points[1]); + if (swept.intersects(view)) { + cairo_curve_to(cr, b1[0], b1[1], b2[0], b2[1], points[2][0], points[2][1]); + } else { + cairo_move_to(cr, points[2][0], points[2][1]); + } + } + } + else if(Geom::CubicBezier const *cubic_bezier = dynamic_cast<Geom::CubicBezier const*>(&c)) { + std::vector<Geom::Point> points = cubic_bezier->points(); + //points[0] *= trans; // don't do this one here for fun: it is only needed for optimized strokes + points[1] *= trans; + points[2] *= trans; + points[3] *= trans; + if (!optimize_stroke) { + cairo_curve_to(cr, points[1][0], points[1][1], points[2][0], points[2][1], points[3][0], points[3][1]); + } else { + points[0] *= trans; // didn't transform this point yet + Geom::Rect swept(points[0], points[3]); + swept.expandTo(points[1]); + swept.expandTo(points[2]); + if (swept.intersects(view)) { + cairo_curve_to(cr, points[1][0], points[1][1], points[2][0], points[2][1], points[3][0], points[3][1]); + } else { + cairo_move_to(cr, points[3][0], points[3][1]); + } + } + } +// else if(Geom::SVGEllipticalArc const *svg_elliptical_arc = dynamic_cast<Geom::SVGEllipticalArc *>(c)) { +// //TODO: get at the innards and spit them out to cairo +// } + else { + //this case handles sbasis as well as all other curve types + Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); + + //recurse to convert the new path resulting from the sbasis to svgd + for(Geom::Path::iterator iter = sbasis_path.begin(); iter != sbasis_path.end(); ++iter) { + feed_curve_to_cairo(cr, *iter, trans, view, optimize_stroke); + } + } +} + + +/** Feeds path-creating calls to the cairo context translating them from the Path */ +static void +feed_path_to_cairo (cairo_t *ct, Geom::Path const &path) +{ + if (path.empty()) + return; + + cairo_move_to(ct, path.initialPoint()[0], path.initialPoint()[1] ); + + for(Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { + feed_curve_to_cairo(ct, *cit, Geom::identity(), Geom::Rect(), false); // optimize_stroke is false, so the view rect is not used + } + + if (path.closed()) { + cairo_close_path(ct); + } +} + +/** Feeds path-creating calls to the cairo context translating them from the Path, with the given transform and shift */ +static void +feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) +{ + if (!area) + return; + if (path.empty()) + return; + + // Transform all coordinates to coords within "area" + Geom::Point shift = area->min(); + Geom::Rect view = *area; + view.expandBy (stroke_width); + view = view * (Geom::Affine)Geom::Translate(-shift); + // Pass transformation to feed_curve, so that we don't need to create a whole new path. + Geom::Affine transshift(trans * Geom::Translate(-shift)); + + Geom::Point initial = path.initialPoint() * transshift; + cairo_move_to(ct, initial[0], initial[1] ); + + for(Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { + feed_curve_to_cairo(ct, *cit, transshift, view, optimize_stroke); + } + + if (path.closed()) { + if (!optimize_stroke) { + cairo_close_path(ct); + } else { + cairo_line_to(ct, initial[0], initial[1]); + /* We cannot use cairo_close_path(ct) here because some parts of the path may have been + clipped and not drawn (maybe the before last segment was outside view area), which + would result in closing the "subpath" after the last interruption, not the entire path. + + However, according to cairo documentation: + The behavior of cairo_close_path() is distinct from simply calling cairo_line_to() with the equivalent coordinate + in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, + there is a line join connecting the final and initial segments of the sub-path. + + The correct fix will be possible when cairo introduces methods for moving without + ending/starting subpaths, which we will use for skipping invisible segments; then we + will be able to use cairo_close_path here. This issue also affects ps/eps/pdf export, + see bug 168129 + */ + } + } +} + +/** Feeds path-creating calls to the cairo context translating them from the PathVector, with the given transform and shift + * One must have done cairo_new_path(ct); before calling this function. */ +void +feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) +{ + if (!area) + return; + if (pathv.empty()) + return; + + for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) { + feed_path_to_cairo(ct, *it, trans, area, optimize_stroke, stroke_width); + } +} + +/** Feeds path-creating calls to the cairo context translating them from the PathVector + * One must have done cairo_new_path(ct); before calling this function. */ +void +feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv) +{ + if (pathv.empty()) + return; + + for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) { + feed_path_to_cairo(ct, *it); + } +} + +void +ink_cairo_set_source_rgba32(cairo_t *ct, guint32 rgba) +{ + cairo_set_source_rgba(ct, SP_RGBA32_R_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_B_F(rgba), SP_RGBA32_A_F(rgba)); +} + +void +ink_cairo_set_source_color(cairo_t *ct, SPColor const &c, double opacity) +{ + cairo_set_source_rgba(ct, c.v.c[0], c.v.c[1], c.v.c[2], opacity); +} + +void ink_matrix_to_2geom(Geom::Affine &m, cairo_matrix_t const &cm) +{ + m[0] = cm.xx; + m[2] = cm.xy; + m[4] = cm.x0; + m[1] = cm.yx; + m[3] = cm.yy; + m[5] = cm.y0; +} + +void ink_matrix_to_cairo(cairo_matrix_t &cm, Geom::Affine const &m) +{ + cm.xx = m[0]; + cm.xy = m[2]; + cm.x0 = m[4]; + cm.yx = m[1]; + cm.yy = m[3]; + cm.y0 = m[5]; +} + +void +ink_cairo_transform(cairo_t *ct, Geom::Affine const &m) +{ + cairo_matrix_t cm; + ink_matrix_to_cairo(cm, m); + cairo_transform(ct, &cm); +} + +void +ink_cairo_pattern_set_matrix(cairo_pattern_t *cp, Geom::Affine const &m) +{ + cairo_matrix_t cm; + ink_matrix_to_cairo(cm, m); + cairo_pattern_set_matrix(cp, &cm); +} + +void +ink_cairo_set_source_argb32_pixbuf(cairo_t *ct, GdkPixbuf *pb, double x, double y) +{ + cairo_surface_t *pbs = ink_cairo_surface_create_for_argb32_pixbuf(pb); + cairo_set_source_surface(ct, pbs, x, y); + cairo_surface_destroy(pbs); +} + +cairo_surface_t * +ink_cairo_surface_create_for_argb32_pixbuf(GdkPixbuf *pb) +{ + guchar *data = gdk_pixbuf_get_pixels(pb); + int w = gdk_pixbuf_get_width(pb); + int h = gdk_pixbuf_get_height(pb); + int stride = gdk_pixbuf_get_rowstride(pb); + + cairo_surface_t *pbs = cairo_image_surface_create_for_data( + data, CAIRO_FORMAT_ARGB32, w, h, stride); + return pbs; +} + +/** @brief Create an exact copy of a surface. + * Creates a surface that has the same type, content type, dimensions and contents + * as the specified surface. */ +cairo_surface_t * +ink_cairo_surface_copy(cairo_surface_t *s) +{ + cairo_surface_t *ns = ink_cairo_surface_create_identical(s); + + if (cairo_surface_get_type(s) == CAIRO_SURFACE_TYPE_IMAGE) { + // use memory copy instead of using a Cairo context + cairo_surface_flush(s); + int stride = cairo_image_surface_get_stride(s); + int h = cairo_image_surface_get_height(s); + memcpy(cairo_image_surface_get_data(ns), cairo_image_surface_get_data(s), stride * h); + cairo_surface_mark_dirty(ns); + } else { + // generic implementation + cairo_t *ct = cairo_create(ns); + cairo_set_source_surface(ct, s, 0, 0); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); + } + + return ns; +} + +/** @brief Create a surface that differs only in pixel content. + * Creates a surface that has the same type, content type and dimensions + * as the specified surface. Pixel contents are not copied. */ +cairo_surface_t * +ink_cairo_surface_create_identical(cairo_surface_t *s) +{ + cairo_surface_t *ns = ink_cairo_surface_create_same_size(s, cairo_surface_get_content(s)); + return ns; +} + +cairo_surface_t * +ink_cairo_surface_create_same_size(cairo_surface_t *s, cairo_content_t c) +{ + cairo_surface_t *ns = cairo_surface_create_similar(s, c, + ink_cairo_surface_get_width(s), ink_cairo_surface_get_height(s)); + return ns; +} + +/** @brief Extract the alpha channel into a new surface. + * Creates a surface with a content type of CAIRO_CONTENT_ALPHA that contains + * the alpha values of pixels from @a s. */ +cairo_surface_t * +ink_cairo_extract_alpha(cairo_surface_t *s) +{ + cairo_surface_t *alpha = ink_cairo_surface_create_same_size(s, CAIRO_CONTENT_ALPHA); + + cairo_t *ct = cairo_create(alpha); + cairo_set_source_surface(ct, s, 0, 0); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); + + return alpha; +} + +cairo_surface_t * +ink_cairo_surface_create_output(cairo_surface_t *image, cairo_surface_t *bg) +{ + cairo_content_t imgt = cairo_surface_get_content(image); + cairo_content_t bgt = cairo_surface_get_content(bg); + cairo_surface_t *out = NULL; + + if (bgt == CAIRO_CONTENT_ALPHA && imgt == CAIRO_CONTENT_ALPHA) { + out = ink_cairo_surface_create_identical(bg); + } else { + out = ink_cairo_surface_create_same_size(bg, CAIRO_CONTENT_COLOR_ALPHA); + } + + return out; +} + +void +ink_cairo_surface_blit(cairo_surface_t *src, cairo_surface_t *dest) +{ + if (cairo_surface_get_type(src) == CAIRO_SURFACE_TYPE_IMAGE && + cairo_surface_get_type(dest) == CAIRO_SURFACE_TYPE_IMAGE && + cairo_image_surface_get_format(src) == cairo_image_surface_get_format(dest) && + cairo_image_surface_get_height(src) == cairo_image_surface_get_height(dest) && + cairo_image_surface_get_width(src) == cairo_image_surface_get_width(dest) && + cairo_image_surface_get_stride(src) == cairo_image_surface_get_stride(dest)) + { + // use memory copy instead of using a Cairo context + cairo_surface_flush(src); + int stride = cairo_image_surface_get_stride(src); + int h = cairo_image_surface_get_height(src); + memcpy(cairo_image_surface_get_data(dest), cairo_image_surface_get_data(src), stride * h); + cairo_surface_mark_dirty(dest); + } else { + // generic implementation + cairo_t *ct = cairo_create(dest); + cairo_set_source_surface(ct, src, 0, 0); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); + } +} + +int +ink_cairo_surface_get_width(cairo_surface_t *surface) +{ + // For now only image surface is handled. + // Later add others, e.g. cairo-gl + assert(cairo_surface_get_type(surface) == CAIRO_SURFACE_TYPE_IMAGE); + return cairo_image_surface_get_width(surface); +} +int +ink_cairo_surface_get_height(cairo_surface_t *surface) +{ + assert(cairo_surface_get_type(surface) == CAIRO_SURFACE_TYPE_IMAGE); + return cairo_image_surface_get_height(surface); +} + +static int ink_cairo_surface_average_color_internal(cairo_surface_t *surface, double &rf, double &gf, double &bf, double &af) +{ + rf = gf = bf = af = 0.0; + cairo_surface_flush(surface); + int width = cairo_image_surface_get_width(surface); + int height = cairo_image_surface_get_height(surface); + int stride = cairo_image_surface_get_stride(surface); + unsigned char *data = cairo_image_surface_get_data(surface); + + /* TODO convert this to OpenMP somehow */ + for (int y = 0; y < height; ++y, data += stride) { + for (int x = 0; x < width; ++x) { + guint32 px = *reinterpret_cast<guint32*>(data + 4*x); + EXTRACT_ARGB32(px, a,r,g,b) + rf += r / 255.0; + gf += g / 255.0; + bf += b / 255.0; + af += a / 255.0; + } + } + return width * height; +} + +guint32 ink_cairo_surface_average_color(cairo_surface_t *surface) +{ + double rf,gf,bf,af; + ink_cairo_surface_average_color_premul(surface, rf,gf,bf,af); + guint32 r = round(rf * 255); + guint32 g = round(gf * 255); + guint32 b = round(bf * 255); + guint32 a = round(af * 255); + ASSEMBLE_ARGB32(px, a,r,g,b); + return px; +} + +void ink_cairo_surface_average_color(cairo_surface_t *surface, double &r, double &g, double &b, double &a) +{ + int count = ink_cairo_surface_average_color_internal(surface, r,g,b,a); + + r /= a; + g /= a; + b /= a; + a /= count; + + r = CLAMP(r, 0.0, 1.0); + g = CLAMP(g, 0.0, 1.0); + b = CLAMP(b, 0.0, 1.0); + a = CLAMP(a, 0.0, 1.0); +} + +void ink_cairo_surface_average_color_premul(cairo_surface_t *surface, double &r, double &g, double &b, double &a) +{ + int count = ink_cairo_surface_average_color_internal(surface, r,g,b,a); + + r /= count; + g /= count; + b /= count; + a /= count; + + r = CLAMP(r, 0.0, 1.0); + g = CLAMP(g, 0.0, 1.0); + b = CLAMP(b, 0.0, 1.0); + a = CLAMP(a, 0.0, 1.0); +} + +cairo_pattern_t * +ink_cairo_pattern_create_checkerboard() +{ + int const w = 6; + int const h = 6; + + cairo_surface_t *s = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, 2*w, 2*h); + + cairo_t *ct = cairo_create(s); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_set_source_rgb(ct, 0.75, 0.75, 0.75); + cairo_paint(ct); + cairo_set_source_rgb(ct, 0.5, 0.5, 0.5); + cairo_rectangle(ct, 0, 0, w, h); + cairo_rectangle(ct, w, h, w, h); + cairo_fill(ct); + cairo_destroy(ct); + + cairo_pattern_t *p = cairo_pattern_create_for_surface(s); + cairo_pattern_set_extend(p, CAIRO_EXTEND_REPEAT); + cairo_pattern_set_filter(p, CAIRO_FILTER_NEAREST); + + cairo_surface_destroy(s); + return p; +} + +/* The following two functions use "from" instead of "to", because when you write: + val1 = argb32_from_pixbuf(val1); + the name of the format is closer to the value in that format. */ + +guint32 argb32_from_pixbuf(guint32 c) +{ + guint32 o = 0; +#if G_BYTE_ORDER == G_LITTLE_ENDIAN + guint32 a = (c & 0xff000000) >> 24; +#else + guint32 a = (c & 0x000000ff); +#endif + if (a != 0) { + // extract color components +#if G_BYTE_ORDER == G_LITTLE_ENDIAN + guint32 r = (c & 0x000000ff); + guint32 g = (c & 0x0000ff00) >> 8; + guint32 b = (c & 0x00ff0000) >> 16; +#else + guint32 r = (c & 0xff000000) >> 24; + guint32 g = (c & 0x00ff0000) >> 16; + guint32 b = (c & 0x0000ff00) >> 8; +#endif + // premultiply + r = premul_alpha(r, a); + b = premul_alpha(b, a); + g = premul_alpha(g, a); + // combine into output + o = (a << 24) | (r << 16) | (g << 8) | (b); + } + return o; +} + +guint32 pixbuf_from_argb32(guint32 c) +{ + guint32 a = (c & 0xff000000) >> 24; + if (a == 0) return 0; + + // extract color components + guint32 r = (c & 0x00ff0000) >> 16; + guint32 g = (c & 0x0000ff00) >> 8; + guint32 b = (c & 0x000000ff); + // unpremultiply; adding a/2 gives correct rounding + // (taken from Cairo sources) + r = (r * 255 + a/2) / a; + b = (b * 255 + a/2) / a; + g = (g * 255 + a/2) / a; + // combine into output +#if G_BYTE_ORDER == G_LITTLE_ENDIAN + guint32 o = (r) | (g << 8) | (b << 16) | (a << 24); +#else + guint32 o = (r << 24) | (g << 16) | (b << 8) | (a); +#endif + return o; +} + +/** + * @brief Convert pixel data from GdkPixbuf format to ARGB. + * This will convert pixel data from GdkPixbuf format to Cairo's native pixel format. + * This involves premultiplying alpha and shuffling around the channels. + * Pixbuf data must have an alpha channel, otherwise the results are undefined + * (usually a segfault). + */ +void +convert_pixels_pixbuf_to_argb32(guchar *data, int w, int h, int stride) +{ + for (int i = 0; i < h; ++i) { + guint32 *px = reinterpret_cast<guint32*>(data + i*stride); + for (int j = 0; j < w; ++j) { + *px = argb32_from_pixbuf(*px); + ++px; + } + } +} + +/** + * @brief Convert pixel data from ARGB to GdkPixbuf format. + * This will convert pixel data from GdkPixbuf format to Cairo's native pixel format. + * This involves premultiplying alpha and shuffling around the channels. + */ +void +convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int stride) +{ + for (int i = 0; i < h; ++i) { + guint32 *px = reinterpret_cast<guint32*>(data + i*stride); + for (int j = 0; j < w; ++j) { + *px = pixbuf_from_argb32(*px); + ++px; + } + } +} + +/** + * @brief Converts GdkPixbuf's data to premultiplied ARGB. + * This function will convert a GdkPixbuf in place into Cairo's native pixel format. + * Note that this is a hack intended to save memory. When the pixbuf is in Cairo's format, + * using it with GTK will result in corrupted drawings. + */ +void +convert_pixbuf_normal_to_argb32(GdkPixbuf *pb) +{ + convert_pixels_pixbuf_to_argb32( + gdk_pixbuf_get_pixels(pb), + gdk_pixbuf_get_width(pb), + gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); +} + +/** + * @brief Converts GdkPixbuf's data back to its native format. + * Once this is done, the pixbuf can be used with GTK again. + */ +void +convert_pixbuf_argb32_to_normal(GdkPixbuf *pb) +{ + convert_pixels_argb32_to_pixbuf( + gdk_pixbuf_get_pixels(pb), + gdk_pixbuf_get_width(pb), + gdk_pixbuf_get_height(pb), + gdk_pixbuf_get_rowstride(pb)); +} + +guint32 argb32_from_rgba(guint32 in) +{ + guint32 r, g, b, a; + a = (in & 0x000000ff); + r = premul_alpha((in & 0xff000000) >> 24, a); + g = premul_alpha((in & 0x00ff0000) >> 16, a); + b = premul_alpha((in & 0x0000ff00) >> 8, a); + ASSEMBLE_ARGB32(px, a, r, g, b) + return px; +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/src/display/cairo-utils.h b/src/display/cairo-utils.h new file mode 100644 index 000000000..0c2ac2dd6 --- /dev/null +++ b/src/display/cairo-utils.h @@ -0,0 +1,153 @@ +/** + * @file + * @brief Cairo integration helpers + *//* + * Authors: + * Krzysztof Kosiński <tweenk.pl@gmail.com> + * + * Copyright (C) 2010 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef SEEN_INKSCAPE_DISPLAY_CAIRO_UTILS_H +#define SEEN_INKSCAPE_DISPLAY_CAIRO_UTILS_H + +#include <glib.h> +#include <gdk-pixbuf/gdk-pixbuf.h> +#include <cairomm/cairomm.h> +#include <2geom/forward.h> + +struct SPColor; + +namespace Inkscape { + +/** @brief RAII idiom for Cairo groups. + * Groups are temporary surfaces used when rendering e.g. masks and opacity. + * Use this class to ensure that each group push is matched with a pop. */ +class CairoGroup { +public: + CairoGroup(cairo_t *_ct); + ~CairoGroup(); + void push(); + void push_with_content(cairo_content_t content); + cairo_pattern_t *pop(); + Cairo::RefPtr<Cairo::Pattern> popmm(); + void pop_to_source(); +private: + cairo_t *ct; + bool pushed; +}; + +/** @brief RAII idiom for Cairo state saving */ +class CairoSave { +public: + CairoSave(cairo_t *_ct, bool save=false) + : ct(_ct) + , saved(save) + { + if (save) { + cairo_save(ct); + } + } + void save() { + if (!saved) { + cairo_save(ct); + saved = true; + } + } + ~CairoSave() { + if (saved) + cairo_restore(ct); + } +private: + cairo_t *ct; + bool saved; +}; + +/** @brief Cairo context with Inkscape-specific operations */ +class CairoContext : public Cairo::Context { +public: + CairoContext(cairo_t *obj, bool ref = false); + + void transform(Geom::Affine const &m); + void set_source_rgba32(guint32 color); + void append_path(Geom::PathVector const &pv); + + static Cairo::RefPtr<CairoContext> create(Cairo::RefPtr<Cairo::Surface> const &target); +}; + +} // namespace Inkscape + +void ink_cairo_set_source_color(cairo_t *ct, SPColor const &color, double opacity); +void ink_cairo_set_source_rgba32(cairo_t *ct, guint32 rgba); +void ink_cairo_transform(cairo_t *ct, Geom::Affine const &m); +void ink_cairo_pattern_set_matrix(cairo_pattern_t *cp, Geom::Affine const &m); +void ink_cairo_set_source_argb32_pixbuf(cairo_t *ct, GdkPixbuf *pb, double x, double y); + +void ink_matrix_to_2geom(Geom::Affine &, cairo_matrix_t const &); +void ink_matrix_to_cairo(cairo_matrix_t &, Geom::Affine const &); + +cairo_surface_t *ink_cairo_surface_copy(cairo_surface_t *s); +cairo_surface_t *ink_cairo_surface_create_identical(cairo_surface_t *s); +cairo_surface_t *ink_cairo_surface_create_same_size(cairo_surface_t *s, cairo_content_t c); +cairo_surface_t *ink_cairo_extract_alpha(cairo_surface_t *s); +cairo_surface_t *ink_cairo_surface_create_output(cairo_surface_t *image, cairo_surface_t *bg); +void ink_cairo_surface_blit(cairo_surface_t *src, cairo_surface_t *dest); +int ink_cairo_surface_get_width(cairo_surface_t *surface); +int ink_cairo_surface_get_height(cairo_surface_t *surface); +guint32 ink_cairo_surface_average_color(cairo_surface_t *surface); +void ink_cairo_surface_average_color(cairo_surface_t *surface, double &r, double &g, double &b, double &a); +void ink_cairo_surface_average_color_premul(cairo_surface_t *surface, double &r, double &g, double &b, double &a); + +cairo_pattern_t *ink_cairo_pattern_create_checkerboard(); + +void convert_pixels_pixbuf_to_argb32(guchar *data, int w, int h, int rs); +void convert_pixels_argb32_to_pixbuf(guchar *data, int w, int h, int rs); +void convert_pixbuf_normal_to_argb32(GdkPixbuf *); +void convert_pixbuf_argb32_to_normal(GdkPixbuf *); +cairo_surface_t *ink_cairo_surface_create_for_argb32_pixbuf(GdkPixbuf *pb); + +G_GNUC_CONST guint32 argb32_from_pixbuf(guint32 in); +G_GNUC_CONST guint32 pixbuf_from_argb32(guint32 in); +/** Convert a pixel in 0xRRGGBBAA format to Cairo ARGB32 format. */ +G_GNUC_CONST guint32 argb32_from_rgba(guint32 in); + + +G_GNUC_CONST inline guint32 +premul_alpha(guint32 color, guint32 alpha) +{ + guint32 temp = alpha * color + 128; + return (temp + (temp >> 8)) >> 8; +} +G_GNUC_CONST inline guint32 +unpremul_alpha(guint32 color, guint32 alpha) +{ + // NOTE: you must check for alpha != 0 yourself. + return (255 * color + alpha/2) / alpha; +} + +// TODO: move those to 2Geom +void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width); +void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv); + +#define EXTRACT_ARGB32(px,a,r,g,b) \ + guint32 a, r, g, b; \ + a = ((px) & 0xff000000) >> 24; \ + r = ((px) & 0x00ff0000) >> 16; \ + g = ((px) & 0x0000ff00) >> 8; \ + b = ((px) & 0x000000ff); + +#define ASSEMBLE_ARGB32(px,a,r,g,b) \ + guint32 px = (a << 24) | (r << 16) | (g << 8) | b; + +#endif +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/src/display/canvas-arena.cpp b/src/display/canvas-arena.cpp index 8436a3b99..72062ce99 100644 --- a/src/display/canvas-arena.cpp +++ b/src/display/canvas-arena.cpp @@ -10,15 +10,15 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <libnr/nr-blit.h> #include <gtk/gtk.h> -#include <display/sp-canvas-util.h> +#include "display/display-forward.h" +#include "display/sp-canvas-util.h" #include "helper/sp-marshal.h" -#include <display/nr-arena.h> -#include <display/nr-arena-group.h> -#include <display/canvas-arena.h> -#include <display/inkscape-cairo.h> +#include "display/nr-arena.h" +#include "display/nr-arena-group.h" +#include "display/canvas-arena.h" +#include "display/cairo-utils.h" enum { ARENA_EVENT, @@ -188,6 +188,7 @@ sp_canvas_arena_render (SPCanvasItem *item, SPCanvasBuf *buf) gint bw, bh; SPCanvasArena *arena = SP_CANVAS_ARENA (item); + //SPCanvas *canvas = item->canvas; nr_arena_item_invoke_update (arena->root, NULL, &arena->gc, NR_ARENA_ITEM_STATE_BBOX | NR_ARENA_ITEM_STATE_RENDER, @@ -200,28 +201,17 @@ sp_canvas_arena_render (SPCanvasItem *item, SPCanvasBuf *buf) if ((bw < 1) || (bh < 1)) return; NRRectL area; - NRPixBlock cb; area.x0 = buf->rect.x0; area.y0 = buf->rect.y0; area.x1 = buf->rect.x1; area.y1 = buf->rect.y1; - nr_pixblock_setup_extern (&cb, NR_PIXBLOCK_MODE_R8G8B8A8P, area.x0, area.y0, area.x1, area.y1, - buf->buf, - buf->buf_rowstride, - FALSE, FALSE); - - cb.visible_area = buf->visible_rect; - cairo_t *ct = nr_create_cairo_context (&area, &cb); - nr_arena_item_invoke_render (ct, arena->root, &area, &cb, 0); - - cairo_surface_t *cst = cairo_get_target(ct); - cairo_destroy (ct); - cairo_surface_finish (cst); - cairo_surface_destroy (cst); - - nr_pixblock_release (&cb); + sp_canvas_prepare_buffer(buf); + cairo_save(buf->ct); + cairo_translate(buf->ct, -area.x0, -area.y0); + nr_arena_item_invoke_render (buf->ct, arena->root, &area, NULL, 0); + cairo_restore(buf->ct); } static double @@ -368,22 +358,15 @@ sp_canvas_arena_set_sticky (SPCanvasArena *ca, gboolean sticky) } void -sp_canvas_arena_render_pixblock (SPCanvasArena *ca, NRPixBlock *pb) +sp_canvas_arena_render_surface (SPCanvasArena *ca, cairo_surface_t *surface, NRRectL const &r) { - NRRectL area; - g_return_if_fail (ca != NULL); g_return_if_fail (SP_IS_CANVAS_ARENA (ca)); - /* fixme: */ - pb->empty = FALSE; - - area.x0 = pb->area.x0; - area.y0 = pb->area.y0; - area.x1 = pb->area.x1; - area.y1 = pb->area.y1; - - nr_arena_item_invoke_render (NULL, ca->root, &area, pb, 0); + cairo_t *ct = cairo_create(surface); + cairo_translate(ct, -r.x0, -r.y0); + nr_arena_item_invoke_render (ct, ca->root, &r, NULL, 0); + cairo_destroy(ct); } diff --git a/src/display/canvas-arena.h b/src/display/canvas-arena.h index 90be5f9e3..ef065a03b 100644 --- a/src/display/canvas-arena.h +++ b/src/display/canvas-arena.h @@ -13,8 +13,11 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "sp-canvas-item.h" -#include "nr-arena-item.h" +#include <cairo.h> +#include <2geom/rect.h> +#include "display/sp-canvas.h" +#include "display/sp-canvas-item.h" +#include "display/nr-arena-item.h" G_BEGIN_DECLS @@ -55,7 +58,7 @@ GtkType sp_canvas_arena_get_type (void); void sp_canvas_arena_set_pick_delta (SPCanvasArena *ca, gdouble delta); void sp_canvas_arena_set_sticky (SPCanvasArena *ca, gboolean sticky); -void sp_canvas_arena_render_pixblock (SPCanvasArena *ca, NRPixBlock *pb); +void sp_canvas_arena_render_surface (SPCanvasArena *ca, cairo_surface_t *surface, NRRectL const &area); G_END_DECLS diff --git a/src/display/canvas-axonomgrid.cpp b/src/display/canvas-axonomgrid.cpp index 845c4e077..a9893f09d 100644 --- a/src/display/canvas-axonomgrid.cpp +++ b/src/display/canvas-axonomgrid.cpp @@ -15,25 +15,24 @@ * For example: the line drawing code should not be here. There _must_ be a function somewhere else that can provide this functionality... */ -#include "sp-canvas-util.h" -#include "canvas-axonomgrid.h" -#include "util/mathfns.h" #include "2geom/line.h" -#include <libnr/nr-pixops.h> - +#include "desktop.h" #include "canvas-grid.h" #include "desktop-handles.h" +#include "display/cairo-utils.h" +#include "display/canvas-axonomgrid.h" +#include "display/canvas-grid.h" +#include "display/display-forward.h" +#include "display/sp-canvas-util.h" +#include "document.h" #include "helper/units.h" -#include "svg/svg-color.h" -#include "xml/node-event-vector.h" -#include "sp-object.h" - -#include "sp-namedview.h" #include "inkscape.h" -#include "desktop.h" - -#include "document.h" #include "preferences.h" +#include "sp-namedview.h" +#include "sp-object.h" +#include "svg/svg-color.h" +#include "util/mathfns.h" +#include "xml/node-event-vector.h" #define SAFE_SETPIXEL //undefine this when it is certain that setpixel is never called with invalid params @@ -45,37 +44,6 @@ enum Dim3 { X=0, Y, Z }; static double deg_to_rad(double deg) { return deg*M_PI/180.0;} - -/** - \brief This function renders a pixel on a particular buffer. - - The topleft of the buffer equals - ( rect.x0 , rect.y0 ) in screen coordinates - ( 0 , 0 ) in setpixel coordinates - The bottomright of the buffer equals - ( rect.x1 , rect,y1 ) in screen coordinates - ( rect.x1 - rect.x0 , rect.y1 - rect.y0 ) in setpixel coordinates -*/ -static void -sp_caxonomgrid_setpixel (SPCanvasBuf *buf, gint x, gint y, guint32 rgba) -{ -#ifdef SAFE_SETPIXEL - if ( (x >= buf->rect.x0) && (x < buf->rect.x1) && (y >= buf->rect.y0) && (y < buf->rect.y1) ) { -#endif - guint r, g, b, a; - r = NR_RGBA32_R (rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - guchar * p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); -#ifdef SAFE_SETPIXEL - } -#endif -} - /** \brief This function renders a line on a particular canvas buffer, using Bresenham's line drawing function. @@ -85,6 +53,12 @@ sp_caxonomgrid_setpixel (SPCanvasBuf *buf, gint x, gint y, guint32 rgba) static void sp_caxonomgrid_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 rgba) { + cairo_move_to(buf->ct, 0.5 + x0, 0.5 + y0); + cairo_line_to(buf->ct, 0.5 + x1, 0.5 + y1); + ink_cairo_set_source_rgba32(buf->ct, rgba); + cairo_stroke(buf->ct); + +#if 0 int dy = y1 - y0; int dx = x1 - x0; int stepx, stepy; @@ -118,30 +92,19 @@ sp_caxonomgrid_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, g sp_caxonomgrid_setpixel(buf, x0, y0, rgba); } } - +#endif } static void sp_grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba) { - if ((x >= buf->rect.x0) && (x < buf->rect.x1)) { - guint r, g, b, a; - gint y0, y1, y; - guchar *p; - r = NR_RGBA32_R(rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - y0 = MAX (buf->rect.y0, ys); - y1 = MIN (buf->rect.y1, ye + 1); - p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; - for (y = y0; y < y1; y++) { - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); - p += buf->buf_rowstride; - } - } + if ((x < buf->rect.x0) || (x >= buf->rect.x1)) + return; + + cairo_move_to(buf->ct, 0.5 + x, 0.5 + ys); + cairo_line_to(buf->ct, 0.5 + x, 0.5 + ye); + ink_cairo_set_source_rgba32(buf->ct, rgba); + cairo_stroke(buf->ct); } namespace Inkscape { @@ -561,6 +524,11 @@ CanvasAxonomGrid::Render (SPCanvasBuf *buf) _empcolor = empcolor; } + cairo_save(buf->ct); + cairo_translate(buf->ct, -buf->rect.x0, -buf->rect.y0); + cairo_set_line_width(buf->ct, 1.0); + cairo_set_line_cap(buf->ct, CAIRO_LINE_CAP_SQUARE); + // gc = gridcoordinates (the coordinates calculated from the grids origin 'grid->ow'. // sc = screencoordinates ( for example "buf->rect.x0" is in screencoordinates ) // bc = buffer patch coordinates @@ -658,6 +626,8 @@ CanvasAxonomGrid::Render (SPCanvasBuf *buf) sp_caxonomgrid_drawline (buf, x0, y0, x1, y1, _empcolor); } } + + cairo_restore(buf->ct); } CanvasAxonomGridSnapper::CanvasAxonomGridSnapper(CanvasAxonomGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d) diff --git a/src/display/canvas-bpath.cpp b/src/display/canvas-bpath.cpp index 725a1d0ff..f86743744 100644 --- a/src/display/canvas-bpath.cpp +++ b/src/display/canvas-bpath.cpp @@ -15,19 +15,17 @@ #endif #include <sstream> #include <string.h> -#include <desktop.h> +#include "desktop.h" #include "color.h" -#include "sp-canvas-util.h" -#include "inkscape-cairo.h" -#include "canvas-bpath.h" #include "display/sp-canvas-group.h" +#include "display/sp-canvas-util.h" +#include "display/canvas-bpath.h" +#include "display/display-forward.h" #include "display/curve.h" -#include "display/inkscape-cairo.h" -#include "libnr/nr-pixops.h" +#include "display/cairo-utils.h" #include "helper/geom.h" - void nr_pixblock_render_bpath_rgba (Shape* theS,uint32_t color,NRRectL &area,char* destBuf,int stride); static void sp_canvas_bpath_class_init (SPCanvasBPathClass *klass); @@ -139,8 +137,6 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) { SPCanvasBPath *cbp = SP_CANVAS_BPATH (item); - sp_canvas_prepare_buffer(buf); - Geom::Rect area (Geom::Point(buf->rect.x0, buf->rect.y0), Geom::Point(buf->rect.x1, buf->rect.y1)); if ( !cbp->curve || @@ -154,33 +150,29 @@ sp_canvas_bpath_render (SPCanvasItem *item, SPCanvasBuf *buf) bool dofill = ((cbp->fill_rgba & 0xff) != 0); bool dostroke = ((cbp->stroke_rgba & 0xff) != 0); - cairo_set_tolerance(buf->ct, 1.25); // low quality, but good enough for canvas items + cairo_set_tolerance(buf->ct, 0.5); cairo_new_path(buf->ct); - if (!dofill) - feed_pathvector_to_cairo (buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, true, 1); - else - feed_pathvector_to_cairo (buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, false, 1); + feed_pathvector_to_cairo (buf->ct, cbp->curve->get_pathvector(), cbp->affine, area, + /* optimized_stroke = */ !dofill, 1); if (dofill) { // RGB / BGR - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cbp->fill_rgba), SP_RGBA32_G_F(cbp->fill_rgba), SP_RGBA32_R_F(cbp->fill_rgba), SP_RGBA32_A_F(cbp->fill_rgba)); + ink_cairo_set_source_rgba32(buf->ct, cbp->fill_rgba); cairo_set_fill_rule(buf->ct, cbp->fill_rule == SP_WIND_RULE_EVENODD? CAIRO_FILL_RULE_EVEN_ODD : CAIRO_FILL_RULE_WINDING); - if (dostroke) - cairo_fill_preserve(buf->ct); - else - cairo_fill(buf->ct); + cairo_fill_preserve(buf->ct); } if (dostroke) { - // RGB / BGR - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cbp->stroke_rgba), SP_RGBA32_G_F(cbp->stroke_rgba), SP_RGBA32_R_F(cbp->stroke_rgba), SP_RGBA32_A_F(cbp->stroke_rgba)); + ink_cairo_set_source_rgba32(buf->ct, cbp->stroke_rgba); cairo_set_line_width(buf->ct, 1); if (cbp->dashes[0] != 0 && cbp->dashes[1] != 0) { cairo_set_dash (buf->ct, cbp->dashes, 2, 0); } cairo_stroke(buf->ct); + } else { + cairo_new_path(buf->ct); } } @@ -192,12 +184,12 @@ sp_canvas_bpath_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_ if ( !cbp->curve || ((cbp->stroke_rgba & 0xff) == 0 && (cbp->fill_rgba & 0xff) == 0 ) || cbp->curve->get_segment_count() < 1) - return NR_HUGE; + return Geom::infinity(); double width = 0.5; Geom::Rect viewbox = item->canvas->getViewbox(); viewbox.expandBy (width); - double dist = NR_HUGE; + double dist = Geom::infinity(); pathv_matrix_point_bbox_wind_distance(cbp->curve->get_pathvector(), cbp->affine, p, NULL, NULL, &dist, 0.5, &viewbox); if (dist <= 1.0) { diff --git a/src/display/canvas-grid.cpp b/src/display/canvas-grid.cpp index 79bfc31ad..82ea036f6 100644 --- a/src/display/canvas-grid.cpp +++ b/src/display/canvas-grid.cpp @@ -12,25 +12,26 @@ * Don't be shy to correct things. */ -#include "sp-canvas-group.h" +#include "desktop.h" #include "sp-canvas-util.h" #include "util/mathfns.h" -#include "libnr/nr-pixops.h" +#include "display-forward.h" #include "desktop-handles.h" +#include "display/cairo-utils.h" +#include "display/canvas-axonomgrid.h" +#include "display/canvas-grid.h" +#include "display/display-forward.h" +#include "display/sp-canvas-util.h" +#include "display/sp-canvas-group.h" +#include "document.h" #include "helper/units.h" -#include "svg/svg-color.h" -#include "xml/node-event-vector.h" -#include "sp-object.h" - -#include "sp-namedview.h" #include "inkscape.h" -#include "desktop.h" - -#include "../document.h" #include "preferences.h" - -#include "canvas-grid.h" -#include "canvas-axonomgrid.h" +#include "sp-namedview.h" +#include "sp-object.h" +#include "svg/svg-color.h" +#include "util/mathfns.h" +#include "xml/node-event-vector.h" using Inkscape::DocumentUndo; @@ -831,65 +832,86 @@ CanvasXYGrid::Update (Geom::Affine const &affine, unsigned int /*flags*/) static void grid_hline (SPCanvasBuf *buf, gint y, gint xs, gint xe, guint32 rgba) { - if ((y >= buf->rect.y0) && (y < buf->rect.y1)) { - guint r, g, b, a; - gint x0, x1, x; - guchar *p; - r = NR_RGBA32_R (rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - x0 = MAX (buf->rect.x0, xs); - x1 = MIN (buf->rect.x1, xe + 1); - p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4; - for (x = x0; x < x1; x++) { - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); - p += 4; - } + if ((y < buf->rect.y0) || (y >= buf->rect.y1)) + return; + + cairo_move_to(buf->ct, 0.5 + xs, 0.5 + y); + cairo_line_to(buf->ct, 0.5 + xe, 0.5 + y); + ink_cairo_set_source_rgba32(buf->ct, rgba); + cairo_stroke(buf->ct); +#if 0 + guint r, g, b, a; + gint x0, x1, x; + guchar *p; + r = NR_RGBA32_R (rgba); + g = NR_RGBA32_G (rgba); + b = NR_RGBA32_B (rgba); + a = NR_RGBA32_A (rgba); + x0 = MAX (buf->rect.x0, xs); + x1 = MIN (buf->rect.x1, xe + 1); + p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4; + for (x = x0; x < x1; x++) { + p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); + p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); + p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); + p += 4; } +#endif } static void grid_vline (SPCanvasBuf *buf, gint x, gint ys, gint ye, guint32 rgba) { - if ((x >= buf->rect.x0) && (x < buf->rect.x1)) { - guint r, g, b, a; - gint y0, y1, y; - guchar *p; - r = NR_RGBA32_R(rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - y0 = MAX (buf->rect.y0, ys); - y1 = MIN (buf->rect.y1, ye + 1); - p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; - for (y = y0; y < y1; y++) { - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); - p += buf->buf_rowstride; - } + if ((x < buf->rect.x0) || (x >= buf->rect.x1)) + return; + + cairo_move_to(buf->ct, 0.5 + x, 0.5 + ys); + cairo_line_to(buf->ct, 0.5 + x, 0.5 + ye); + ink_cairo_set_source_rgba32(buf->ct, rgba); + cairo_stroke(buf->ct); + #if 0 + guint r, g, b, a; + gint y0, y1, y; + guchar *p; + r = NR_RGBA32_R(rgba); + g = NR_RGBA32_G (rgba); + b = NR_RGBA32_B (rgba); + a = NR_RGBA32_A (rgba); + y0 = MAX (buf->rect.y0, ys); + y1 = MIN (buf->rect.y1, ye + 1); + p = buf->buf + (y0 - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; + for (y = y0; y < y1; y++) { + p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); + p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); + p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); + p += buf->buf_rowstride; } + #endif } static void grid_dot (SPCanvasBuf *buf, gint x, gint y, guint32 rgba) { - if ( (y >= buf->rect.y0) && (y < buf->rect.y1) - && (x >= buf->rect.x0) && (x < buf->rect.x1) ) { - guint r, g, b, a; - guchar *p; - r = NR_RGBA32_R (rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); - } + if ( (y < buf->rect.y0) || (y >= buf->rect.y1) + || (x < buf->rect.x0) || (x >= buf->rect.x1) ) + return; + + cairo_rectangle(buf->ct, x, y, 1, 1); + ink_cairo_set_source_rgba32(buf->ct, rgba); + cairo_fill(buf->ct); + +#if 0 + guint r, g, b, a; + guchar *p; + r = NR_RGBA32_R (rgba); + g = NR_RGBA32_G (rgba); + b = NR_RGBA32_B (rgba); + a = NR_RGBA32_A (rgba); + p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; + p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); + p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); + p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); +#endif } void @@ -910,6 +932,11 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) _empcolor = empcolor; } + cairo_save(buf->ct); + cairo_translate(buf->ct, -buf->rect.x0, -buf->rect.y0); + cairo_set_line_width(buf->ct, 1.0); + cairo_set_line_cap(buf->ct, CAIRO_LINE_CAP_SQUARE); + if (!render_dotted) { gint ylinenum; gdouble y; @@ -961,6 +988,7 @@ CanvasXYGrid::Render (SPCanvasBuf *buf) } } + cairo_restore(buf->ct); } CanvasXYGridSnapper::CanvasXYGridSnapper(CanvasXYGrid *grid, SnapManager *sm, Geom::Coord const d) : LineSnapper(sm, d) diff --git a/src/display/canvas-text.cpp b/src/display/canvas-text.cpp index 70196b307..54cbe5da8 100644 --- a/src/display/canvas-text.cpp +++ b/src/display/canvas-text.cpp @@ -13,19 +13,19 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "sp-canvas-util.h" -#include "canvas-text.h" -#include "display/inkscape-cairo.h" -#include <sstream> -#include <string.h> -#include "desktop.h" - #ifdef HAVE_CONFIG_H # include "config.h" #endif -#include <color.h> -#include <libnr/nr-pixops.h> +#include <sstream> +#include <string.h> + +#include "display-forward.h" +#include "sp-canvas-util.h" +#include "canvas-text.h" +#include "display/cairo-utils.h" +#include "desktop.h" +#include "color.h" static void sp_canvastext_class_init (SPCanvasTextClass *klass); static void sp_canvastext_init (SPCanvasText *canvastext); @@ -123,13 +123,11 @@ sp_canvastext_render (SPCanvasItem *item, SPCanvasBuf *buf) cairo_set_font_size(buf->ct, cl->fontsize); cairo_text_path(buf->ct, cl->text); - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cl->rgba_stroke), SP_RGBA32_G_F(cl->rgba_stroke), SP_RGBA32_R_F(cl->rgba_stroke), SP_RGBA32_A_F(cl->rgba_stroke)); + ink_cairo_set_source_rgba32(buf->ct, cl->rgba_stroke); cairo_set_line_width (buf->ct, 2.0); cairo_stroke_preserve(buf->ct); - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(cl->rgba), SP_RGBA32_G_F(cl->rgba), SP_RGBA32_R_F(cl->rgba), SP_RGBA32_A_F(cl->rgba)); + ink_cairo_set_source_rgba32(buf->ct, cl->rgba); cairo_fill(buf->ct); - - cairo_new_path(buf->ct); } static void diff --git a/src/display/display-forward.h b/src/display/display-forward.h new file mode 100644 index 000000000..bc7013214 --- /dev/null +++ b/src/display/display-forward.h @@ -0,0 +1,32 @@ +#ifndef SEEN_DISPLAY_DISPLAY_FORWARD_H +#define SEEN_DISPLAY_DISPLAY_FORWARD_H + +#include <glib-object.h> + +struct SPCanvas; +struct SPCanvasClass; +struct SPCanvasItem; +typedef struct _SPCanvasItemClass SPCanvasItemClass; +struct SPCanvasGroup; +struct SPCanvasGroupClass; +class SPCurve; + +namespace Inkscape { +namespace Display { + class TemporaryItem; + class TemporaryItemList; +} +} + +#endif /* !SEEN_DISPLAY_DISPLAY_FORWARD_H */ + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 : diff --git a/src/display/grayscale.cpp b/src/display/grayscale.cpp index 37f2b255c..745a08c1e 100644 --- a/src/display/grayscale.cpp +++ b/src/display/grayscale.cpp @@ -21,14 +21,22 @@ namespace Grayscale { +/* Original values from Johan: +const float red_factor = 0.3; +const float green_factor = 0.59; +const float blue_factor = 0.11; +*/ + +// Values below are from the SVG specification +const float red_factor = 0.2125; +const float green_factor = 0.7154; +const float blue_factor = 0.0721; + guint32 process(guint32 rgba) { return process(SP_RGBA32_R_U(rgba), SP_RGBA32_G_U(rgba), SP_RGBA32_B_U(rgba), SP_RGBA32_A_U(rgba)); } guint32 process(guchar r, guchar g, guchar b, guchar a) { - float red_factor = 0.3; - float green_factor = 0.59; - float blue_factor = 0.11; /** To reduce banding in gradients, this calculation is tweaked a bit * by outputing blue+1 or red+1 or both. The luminance is calculated diff --git a/src/display/grayscale.h b/src/display/grayscale.h index d7092687c..fe0d75cad 100644 --- a/src/display/grayscale.h +++ b/src/display/grayscale.h @@ -19,10 +19,6 @@ namespace Grayscale { guint32 process(guchar r, guchar g, guchar b, guchar a); guchar luminance(guchar r, guchar g, guchar b); - const float red_factor = 0.3; - const float green_factor = 0.59; - const float blue_factor = 0.11; - bool activeDesktopIsGrayscale(); }; diff --git a/src/display/guideline.cpp b/src/display/guideline.cpp index abfec250f..c761fa74e 100644 --- a/src/display/guideline.cpp +++ b/src/display/guideline.cpp @@ -13,15 +13,11 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ - -#include <libnr/nr-pixops.h> #include <2geom/transforms.h> #include "sp-canvas-util.h" #include "sp-ctrlpoint.h" #include "guideline.h" -#include "cairo.h" -#include "inkscape-cairo.h" -#include "color.h" +#include "display/cairo-utils.h" static void sp_guideline_class_init(SPGuideLineClass *c); static void sp_guideline_init(SPGuideLine *guideline); @@ -109,74 +105,37 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) SPGuideLine const *gl = SP_GUIDELINE (item); - sp_canvas_prepare_buffer(buf); - cairo_t* ctx = nr_create_cairo_context_canvasbuf (NULL /*area*/, buf); //this function ignores the "area" parameter - cairo_set_font_size (ctx, 10); - cairo_set_line_width (ctx, 10); - /// @todo uh??! why must the order of these arguments be reversed? bgra instead of rgba! - cairo_set_source_rgba (ctx, SP_RGBA32_B_F(gl->rgba), SP_RGBA32_G_F(gl->rgba), SP_RGBA32_R_F(gl->rgba), SP_RGBA32_A_F(gl->rgba)); - - unsigned int const r = NR_RGBA32_R (gl->rgba); - unsigned int const g = NR_RGBA32_G (gl->rgba); - unsigned int const b = NR_RGBA32_B (gl->rgba); - unsigned int const a = NR_RGBA32_A (gl->rgba); + cairo_save(buf->ct); + cairo_translate(buf->ct, -buf->rect.x0, -buf->rect.y0); + ink_cairo_set_source_rgba32(buf->ct, gl->rgba); + cairo_set_line_width(buf->ct, 1); + cairo_set_line_cap(buf->ct, CAIRO_LINE_CAP_SQUARE); + cairo_set_font_size(buf->ct, 10); int px = (int) Inkscape::round(gl->point_on_line[Geom::X]); int py = (int) Inkscape::round(gl->point_on_line[Geom::Y]); - if (gl->is_vertical()) { - if (px < buf->rect.x0 || px >= buf->rect.x1) { - return; - } - - int p0 = buf->rect.y0; - int p1 = buf->rect.y1; - int step = buf->buf_rowstride; - unsigned char *d = buf->buf + 4 * (px - buf->rect.x0); - - for (int p = p0; p < p1; p++) { - d[0] = NR_COMPOSEN11_1111(r, a, d[0]); - d[1] = NR_COMPOSEN11_1111(g, a, d[1]); - d[2] = NR_COMPOSEN11_1111(b, a, d[2]); - d += step; - } - - if (gl->label){ - cairo_move_to(ctx, px - buf->rect.x0 + 5, py - buf->rect.y0); - cairo_rotate(ctx, 3.1415/2); - cairo_show_text(ctx, gl->label); - } + if (gl->label) { + cairo_save(buf->ct); + cairo_translate(buf->ct, px, py); + cairo_rotate(buf->ct, atan2(gl->normal_to_line[Geom::X], gl->normal_to_line[Geom::Y])); + cairo_translate(buf->ct, 0, -5); + cairo_move_to(buf->ct, 0, 0); + cairo_show_text(buf->ct, gl->label); + cairo_restore(buf->ct); + } + if (gl->is_vertical()) { + int position = (int) Inkscape::round(gl->point_on_line[Geom::X]); + cairo_move_to(buf->ct, position + 0.5, buf->rect.y0 + 0.5); + cairo_line_to(buf->ct, position + 0.5, buf->rect.y1 - 0.5); + cairo_stroke(buf->ct); } else if (gl->is_horizontal()) { - if (py < buf->rect.y0 || py >= buf->rect.y1) { - return; - } - - int p0 = buf->rect.x0; - int p1 = buf->rect.x1; - int step = 4; - unsigned char *d = buf->buf + (py - buf->rect.y0) * buf->buf_rowstride; - - for (int p = p0; p < p1; p++) { - d[0] = NR_COMPOSEN11_1111(r, a, d[0]); - d[1] = NR_COMPOSEN11_1111(g, a, d[1]); - d[2] = NR_COMPOSEN11_1111(b, a, d[2]); - d += step; - } - - if (gl->label){ - cairo_move_to(ctx, px - buf->rect.x0, py - buf->rect.y0 - 5); - cairo_show_text(ctx, gl->label); - } - + int position = (int) Inkscape::round(gl->point_on_line[Geom::Y]); + cairo_move_to(buf->ct, buf->rect.x0 + 0.5, position + 0.5); + cairo_line_to(buf->ct, buf->rect.x1 - 0.5, position + 0.5); + cairo_stroke(buf->ct); } else { - - if (gl->label){ - cairo_move_to(ctx, px - buf->rect.x0 + 5, py - buf->rect.y0); - cairo_rotate(ctx, atan2(gl->normal_to_line[Geom::X], gl->normal_to_line[Geom::Y])); - cairo_show_text(ctx, gl->label); - } - // render angled line, once intersection has been detected, draw from there. Geom::Point parallel_to_line( gl->normal_to_line[Geom::Y], /*should be minus, but inverted y axis*/ gl->normal_to_line[Geom::X]); @@ -187,7 +146,7 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) // intersects with left vertical! double y_intersect_right = (buf->rect.x1 - gl->point_on_line[Geom::X]) * parallel_to_line[Geom::Y] / parallel_to_line[Geom::X] + gl->point_on_line[Geom::Y]; sp_guideline_drawline (buf, buf->rect.x0, static_cast<gint>(round(y_intersect_left)), buf->rect.x1, static_cast<gint>(round(y_intersect_right)), gl->rgba); - return; + goto end; } //try to intersect with right vertical of rect @@ -195,7 +154,7 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) if ( (y_intersect_right >= buf->rect.y0) && (y_intersect_right <= buf->rect.y1) ) { // intersects with right vertical! sp_guideline_drawline (buf, buf->rect.x1, static_cast<gint>(round(y_intersect_right)), buf->rect.x0, static_cast<gint>(round(y_intersect_left)), gl->rgba); - return; + goto end; } //try to intersect with top horizontal of rect @@ -204,7 +163,7 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) // intersects with top horizontal! double x_intersect_bottom = (buf->rect.y1 - gl->point_on_line[Geom::Y]) * parallel_to_line[Geom::X] / parallel_to_line[Geom::Y] + gl->point_on_line[Geom::X]; sp_guideline_drawline (buf, static_cast<gint>(round(x_intersect_top)), buf->rect.y0, static_cast<gint>(round(x_intersect_bottom)), buf->rect.y1, gl->rgba); - return; + goto end; } //try to intersect with bottom horizontal of rect @@ -212,9 +171,11 @@ static void sp_guideline_render(SPCanvasItem *item, SPCanvasBuf *buf) if ( (x_intersect_top >= buf->rect.x0) && (x_intersect_top <= buf->rect.x1) ) { // intersects with bottom horizontal! sp_guideline_drawline (buf, static_cast<gint>(round(x_intersect_bottom)), buf->rect.y1, static_cast<gint>(round(x_intersect_top)), buf->rect.y0, gl->rgba); - return; + goto end; } } + end: + cairo_restore(buf->ct); } static void sp_guideline_update(SPCanvasItem *item, Geom::Affine const &affine, unsigned int flags) @@ -247,7 +208,7 @@ static double sp_guideline_point(SPCanvasItem *item, Geom::Point p, SPCanvasItem SPGuideLine *gl = SP_GUIDELINE (item); if (!gl->sensitive) { - return NR_HUGE; + return Geom::infinity(); } *actual_item = item; @@ -320,82 +281,12 @@ void sp_guideline_delete(SPGuideLine *gl) gtk_object_destroy(GTK_OBJECT(gl)); } -//########################################################## -// Line rendering -#define SAFE_SETPIXEL //undefine this when it is certain that setpixel is never called with invalid params - -/** - \brief This function renders a pixel on a particular buffer. - - The topleft of the buffer equals - ( rect.x0 , rect.y0 ) in screen coordinates - ( 0 , 0 ) in setpixel coordinates - The bottomright of the buffer equals - ( rect.x1 , rect,y1 ) in screen coordinates - ( rect.x1 - rect.x0 , rect.y1 - rect.y0 ) in setpixel coordinates -*/ static void -sp_guideline_setpixel (SPCanvasBuf *buf, gint x, gint y, guint32 rgba) +sp_guideline_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 /*rgba*/) { -#ifdef SAFE_SETPIXEL - if ( (x >= buf->rect.x0) && (x < buf->rect.x1) && (y >= buf->rect.y0) && (y < buf->rect.y1) ) { -#endif - guint r, g, b, a; - r = NR_RGBA32_R (rgba); - g = NR_RGBA32_G (rgba); - b = NR_RGBA32_B (rgba); - a = NR_RGBA32_A (rgba); - guchar * p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x - buf->rect.x0) * 4; - p[0] = NR_COMPOSEN11_1111 (r, a, p[0]); - p[1] = NR_COMPOSEN11_1111 (g, a, p[1]); - p[2] = NR_COMPOSEN11_1111 (b, a, p[2]); -#ifdef SAFE_SETPIXEL - } -#endif -} - -/** - \brief This function renders a line on a particular canvas buffer, - using Bresenham's line drawing function. - http://www.cs.unc.edu/~mcmillan/comp136/Lecture6/Lines.html - Coordinates are interpreted as SCREENcoordinates -*/ -static void -sp_guideline_drawline (SPCanvasBuf *buf, gint x0, gint y0, gint x1, gint y1, guint32 rgba) -{ - int dy = y1 - y0; - int dx = x1 - x0; - int stepx, stepy; - - if (dy < 0) { dy = -dy; stepy = -1; } else { stepy = 1; } - if (dx < 0) { dx = -dx; stepx = -1; } else { stepx = 1; } - dy <<= 1; // dy is now 2*dy - dx <<= 1; // dx is now 2*dx - - sp_guideline_setpixel(buf, x0, y0, rgba); - if (dx > dy) { - int fraction = dy - (dx >> 1); // same as 2*dy - dx - while (x0 != x1) { - if (fraction >= 0) { - y0 += stepy; - fraction -= dx; // same as fraction -= 2*dx - } - x0 += stepx; - fraction += dy; // same as fraction -= 2*dy - sp_guideline_setpixel(buf, x0, y0, rgba); - } - } else { - int fraction = dx - (dy >> 1); - while (y0 != y1) { - if (fraction >= 0) { - x0 += stepx; - fraction -= dy; - } - y0 += stepy; - fraction += dx; - sp_guideline_setpixel(buf, x0, y0, rgba); - } - } + cairo_move_to(buf->ct, x0 + 0.5, y0 + 0.5); + cairo_line_to(buf->ct, x1 + 0.5, y1 + 0.5); + cairo_stroke(buf->ct); } /* diff --git a/src/display/inkscape-cairo.cpp b/src/display/inkscape-cairo.cpp deleted file mode 100644 index 4fc492ba8..000000000 --- a/src/display/inkscape-cairo.cpp +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Helper functions to use cairo with inkscape - * - * Copyright (C) 2007 bulia byak - * Copyright (C) 2008 Johan Engelen - * - * Released under GNU GPL - * - */ - -#include <cairo.h> - -#ifdef HAVE_CONFIG_H -# include <config.h> -#endif - -#include <libnr/nr-pixblock.h> -#include <libnr/nr-convert2geom.h> -#include "../style.h" -#include "nr-arena.h" -#include "sp-canvas.h" -#include <2geom/pathvector.h> -#include <2geom/bezier-curve.h> -#include <2geom/hvlinesegment.h> -#include <2geom/affine.h> -#include <2geom/point.h> -#include <2geom/path.h> -#include <2geom/transforms.h> -#include <2geom/sbasis-to-bezier.h> -#include "helper/geom-curves.h" - -/** Creates a cairo context to render to the given pixblock on the given area */ -cairo_t * -nr_create_cairo_context_for_data (NRRectL *area, NRRectL *buf_area, unsigned char *px, unsigned int rowstride) -{ - if (!nr_rect_l_test_intersect_ptr(buf_area, area)) - return NULL; - - NRRectL clip; - nr_rect_l_intersect (&clip, buf_area, area); - unsigned char *dpx = px + (clip.y0 - buf_area->y0) * rowstride + 4 * (clip.x0 - buf_area->x0); - int width = area->x1 - area->x0; - int height = area->y1 - area->y0; - // even though cairo cannot draw in nonpremul mode, select ARGB32 for R8G8B8A8N as the closest; later eliminate R8G8B8A8N everywhere - cairo_surface_t* cst = cairo_image_surface_create_for_data - (dpx, - CAIRO_FORMAT_ARGB32, - width, - height, - rowstride); - cairo_t *ct = cairo_create (cst); - - return ct; -} - -/** Creates a cairo context to render to the given SPCanvasBuf on the given area */ -cairo_t * -nr_create_cairo_context_canvasbuf (NRRectL */*area*/, SPCanvasBuf *b) -{ - return nr_create_cairo_context_for_data (&(b->rect), &(b->rect), b->buf, b->buf_rowstride); -} - - -/** Creates a cairo context to render to the given NRPixBlock on the given area */ -cairo_t * -nr_create_cairo_context (NRRectL *area, NRPixBlock *pb) -{ - return nr_create_cairo_context_for_data (area, &(pb->area), NR_PIXBLOCK_PX (pb), pb->rs); -} - -/* - * Can be called recursively. - * If optimize_stroke == false, the view Rect is not used. - */ -static void -feed_curve_to_cairo(cairo_t *cr, Geom::Curve const &c, Geom::Affine const & trans, Geom::Rect view, bool optimize_stroke) -{ - if( is_straight_curve(c) ) - { - Geom::Point end_tr = c.finalPoint() * trans; - if (!optimize_stroke) { - cairo_line_to(cr, end_tr[0], end_tr[1]); - } else { - Geom::Rect swept(c.initialPoint()*trans, end_tr); - if (swept.intersects(view)) { - cairo_line_to(cr, end_tr[0], end_tr[1]); - } else { - cairo_move_to(cr, end_tr[0], end_tr[1]); - } - } - } - else if(Geom::QuadraticBezier const *quadratic_bezier = dynamic_cast<Geom::QuadraticBezier const*>(&c)) { - std::vector<Geom::Point> points = quadratic_bezier->points(); - points[0] *= trans; - points[1] *= trans; - points[2] *= trans; - Geom::Point b1 = points[0] + (2./3) * (points[1] - points[0]); - Geom::Point b2 = b1 + (1./3) * (points[2] - points[0]); - if (!optimize_stroke) { - cairo_curve_to(cr, b1[0], b1[1], b2[0], b2[1], points[2][0], points[2][1]); - } else { - Geom::Rect swept(points[0], points[2]); - swept.expandTo(points[1]); - if (swept.intersects(view)) { - cairo_curve_to(cr, b1[0], b1[1], b2[0], b2[1], points[2][0], points[2][1]); - } else { - cairo_move_to(cr, points[2][0], points[2][1]); - } - } - } - else if(Geom::CubicBezier const *cubic_bezier = dynamic_cast<Geom::CubicBezier const*>(&c)) { - std::vector<Geom::Point> points = cubic_bezier->points(); - //points[0] *= trans; // don't do this one here for fun: it is only needed for optimized strokes - points[1] *= trans; - points[2] *= trans; - points[3] *= trans; - if (!optimize_stroke) { - cairo_curve_to(cr, points[1][0], points[1][1], points[2][0], points[2][1], points[3][0], points[3][1]); - } else { - points[0] *= trans; // didn't transform this point yet - Geom::Rect swept(points[0], points[3]); - swept.expandTo(points[1]); - swept.expandTo(points[2]); - if (swept.intersects(view)) { - cairo_curve_to(cr, points[1][0], points[1][1], points[2][0], points[2][1], points[3][0], points[3][1]); - } else { - cairo_move_to(cr, points[3][0], points[3][1]); - } - } - } -// else if(Geom::SVGEllipticalArc const *svg_elliptical_arc = dynamic_cast<Geom::SVGEllipticalArc *>(c)) { -// //TODO: get at the innards and spit them out to cairo -// } - else { - //this case handles sbasis as well as all other curve types - Geom::Path sbasis_path = Geom::cubicbezierpath_from_sbasis(c.toSBasis(), 0.1); - - //recurse to convert the new path resulting from the sbasis to svgd - for(Geom::Path::iterator iter = sbasis_path.begin(); iter != sbasis_path.end(); ++iter) { - feed_curve_to_cairo(cr, *iter, trans, view, optimize_stroke); - } - } -} - - -/** Feeds path-creating calls to the cairo context translating them from the Path */ -static void -feed_path_to_cairo (cairo_t *ct, Geom::Path const &path) -{ - if (path.empty()) - return; - - cairo_move_to(ct, path.initialPoint()[0], path.initialPoint()[1] ); - - for(Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { - feed_curve_to_cairo(ct, *cit, Geom::identity(), Geom::Rect(), false); // optimize_stroke is false, so the view rect is not used - } - - if (path.closed()) { - cairo_close_path(ct); - } -} - -/** Feeds path-creating calls to the cairo context translating them from the Path, with the given transform and shift */ -static void -feed_path_to_cairo (cairo_t *ct, Geom::Path const &path, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) -{ - if (!area) - return; - if (path.empty()) - return; - - // Transform all coordinates to coords within "area" - Geom::Point shift = area->min(); - Geom::Rect view = *area; - view.expandBy (stroke_width); - view = view * (Geom::Affine)Geom::Translate(-shift); - // Pass transformation to feed_curve, so that we don't need to create a whole new path. - Geom::Affine transshift(trans * Geom::Translate(-shift)); - - Geom::Point initial = path.initialPoint() * transshift; - cairo_move_to(ct, initial[0], initial[1] ); - - for(Geom::Path::const_iterator cit = path.begin(); cit != path.end_open(); ++cit) { - feed_curve_to_cairo(ct, *cit, transshift, view, optimize_stroke); - } - - if (path.closed()) { - if (!optimize_stroke) { - cairo_close_path(ct); - } else { - cairo_line_to(ct, initial[0], initial[1]); - /* We cannot use cairo_close_path(ct) here because some parts of the path may have been - clipped and not drawn (maybe the before last segment was outside view area), which - would result in closing the "subpath" after the last interruption, not the entire path. - - However, according to cairo documentation: - The behavior of cairo_close_path() is distinct from simply calling cairo_line_to() with the equivalent coordinate - in the case of stroking. When a closed sub-path is stroked, there are no caps on the ends of the sub-path. Instead, - there is a line join connecting the final and initial segments of the sub-path. - - The correct fix will be possible when cairo introduces methods for moving without - ending/starting subpaths, which we will use for skipping invisible segments; then we - will be able to use cairo_close_path here. This issue also affects ps/eps/pdf export, - see bug 168129 - */ - } - } -} - -/** Feeds path-creating calls to the cairo context translating them from the PathVector, with the given transform and shift - * One must have done cairo_new_path(ct); before calling this function. */ -void -feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width) -{ - if (!area) - return; - if (pathv.empty()) - return; - - for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) { - feed_path_to_cairo(ct, *it, trans, area, optimize_stroke, stroke_width); - } -} - -/** Feeds path-creating calls to the cairo context translating them from the PathVector - * One must have done cairo_new_path(ct); before calling this function. */ -void -feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv) -{ - if (pathv.empty()) - return; - - for(Geom::PathVector::const_iterator it = pathv.begin(); it != pathv.end(); ++it) { - feed_path_to_cairo(ct, *it); - } -} - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/inkscape-cairo.h b/src/display/inkscape-cairo.h deleted file mode 100644 index 4133661fe..000000000 --- a/src/display/inkscape-cairo.h +++ /dev/null @@ -1,37 +0,0 @@ -#ifndef __INKSCAPE_CAIRO_H__ -#define __INKSCAPE_CAIRO_H__ - -/* - * Helper functions to use cairo with inkscape - * - * Copyright (C) 2007 bulia byak - * Copyright (C) 2008 Johan Engelen - * - * Released under GNU GPL - * - */ - -#include <2geom/forward.h> -#include <cairo/cairo.h> -#include <boost/optional.hpp> -#include "libnr/nr-rect.h" - -struct NRPixBlock; -class SPCanvasBuf; - -cairo_t *nr_create_cairo_context_canvasbuf (NRRectL *area, SPCanvasBuf *b); -cairo_t *nr_create_cairo_context (NRRectL *area, NRPixBlock *pb); -void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv, Geom::Affine trans, Geom::OptRect area, bool optimize_stroke, double stroke_width); -void feed_pathvector_to_cairo (cairo_t *ct, Geom::PathVector const &pathv); - -#endif -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-3dutils.cpp b/src/display/nr-3dutils.cpp index c5e7b4c1b..eb6858374 100644 --- a/src/display/nr-3dutils.cpp +++ b/src/display/nr-3dutils.cpp @@ -11,134 +11,15 @@ #include <glib/gmessages.h> -#include "libnr/nr-pixblock.h" #include "display/nr-3dutils.h" #include <cmath> +#include <2geom/point.h> +#include <2geom/affine.h> namespace NR { -#define BEGIN 0 // TOP or LEFT -#define MIDDLE 1 -#define END 2 // BOTTOM or RIGHT - -#define START(v) ((v)==BEGIN? 1 : 0) -#define FINISH(v) ((v)==END? 1 : 2) - -signed char K_X[3][3][3][3] = { - //K_X[TOP] - { - //K_X[TOP][LEFT] - { - { 0, 0, 0}, - { 0, -2, 2}, - { 0, -1, 1} - }, - { - { 0, 0, 0}, - {-2, 0, 2}, - {-1, 0, 1} - }, - { - { 0, 0, 0}, - {-2, 2, 0}, - {-1, 1, 0} - } - }, - //K_X[MIDDLE] - { - //K_X[MIDDLE][LEFT] - { - { 0, -1, 1}, - { 0, -2, 2}, - { 0, -1, 1} - }, - { - {-1, 0, 1}, - {-2, 0, 2}, - {-1, 0, 1} - }, - { - {-1, 1, 0}, - {-2, 2, 0}, - {-1, 1, 0} - } - }, - //K_X[BOTTOM] - { - //K_X[BOTTOM][LEFT] - { - { 0, -1, 1}, - { 0, -2, 2}, - { 0, 0, 0} - }, - { - {-1, 0, 1}, - {-2, 0, 2}, - { 0, 0, 0} - }, - { - {-1, 1, 0}, - {-2, 2, 0}, - { 0, 0, 0} - } - } -}; - -//K_Y is obtained by transposing K_X globally and each of its components - -gdouble FACTOR_X[3][3] = { - {2./3, 1./3, 2./3}, - {1./2, 1./4, 1./2}, - {2./3, 1./3, 2./3} -}; - -//FACTOR_Y is obtained by transposing FACTOR_X - -inline -int get_carac(int i, int len, int delta) { - if (i < delta) - return BEGIN; - else if (i > len - 1 - delta) - return END; - else - return MIDDLE; -} - -//assumes in is RGBA -//should be made more resistant -void compute_surface_normal(Fvector &N, gdouble ss, NRPixBlock *in, int i, int j, int dx, int dy) { - int w = in->area.x1 - in->area.x0; - int h = in->area.y1 - in->area.y0; - int k, l, alpha_idx, alpha_idx_y; - int x_carac, y_carac; - gdouble alpha; - gdouble accu_x; - gdouble accu_y; - unsigned char *data = NR_PIXBLOCK_PX (in); - g_assert(NR_PIXBLOCK_BPP(in) == 4); - x_carac = get_carac(j, w, dx); //LEFT, MIDDLE or RIGHT - y_carac = get_carac(i, h, dy); //TOP, MIDDLE or BOTTOM - alpha_idx = 4*(i*w + j); - accu_x = 0; - accu_y = 0; - for (k = START(y_carac); k <= FINISH(y_carac); k++) { - alpha_idx_y = alpha_idx + 4*(k-1)*dy*w; - for (l = START(x_carac); l <= FINISH(x_carac); l++) { - alpha = (data + alpha_idx_y + 4*dx*(l-1))[3]; - accu_x += K_X[y_carac][x_carac][k][l] * alpha; - accu_y += K_X[x_carac][y_carac][l][k] * alpha; - } - } - ss /= 255.0; // Correction for scale of pixel values - N[X_3D] = -ss * FACTOR_X[y_carac][x_carac] * accu_x / dx; - N[Y_3D] = -ss * FACTOR_X[x_carac][y_carac] * accu_y / dy; - N[Z_3D] = 1.0; - normalize_vector(N); - //std::cout << "(" << N[X_3D] << ", " << N[Y_3D] << ", " << N[Z_3D] << ")" << std::endl; -} - void convert_coord(gdouble &x, gdouble &y, gdouble &z, Geom::Affine const &trans) { - Point p = Point(x, y); + Geom::Point p = Geom::Point(x, y); p *= trans; x = p[Geom::X]; y = p[Geom::Y]; diff --git a/src/display/nr-3dutils.h b/src/display/nr-3dutils.h index e19651ac8..44cb371e6 100644 --- a/src/display/nr-3dutils.h +++ b/src/display/nr-3dutils.h @@ -28,12 +28,24 @@ namespace NR { /** * a type of 3 gdouble components vectors */ -typedef gdouble Fvector[3]; +struct Fvector { + Fvector() { + v[0] = v[1] = v[2] = 0.0; + } + Fvector(double x, double y, double z) { + v[0] = x; + v[1] = y; + v[2] = z; + } + double v[3]; + double &operator[](unsigned i) { return v[i]; } + double operator[](unsigned i) const { return v[i]; } +}; /** * The eye vector */ -const static Fvector EYE_VECTOR = {0, 0, 1}; +const static Fvector EYE_VECTOR(0, 0, 1); /** * returns the euclidian norm of the vector v @@ -69,22 +81,6 @@ gdouble scalar_product(const Fvector &a, const Fvector &b); void normalized_sum(Fvector &r, const Fvector &a, const Fvector &b); /** - * Computes the unit suface normal vector of surface given by "in" at (i, j) - * and store it into N. "in" is a (NRPixBlock *) in mode RGBA but only the alpha - * channel is considered as a bump map. ss is the altitude when for the alpha - * value 255. dx and dy are the deltas used to compute in our discrete setting - * - * \param N a reference to a Fvector in which we store the unit surface normal - * \param ss the surface scale - * \param in a NRPixBlock * whose alpha channel codes the surface - * \param i the x coordinate of the point at which we compute the normal - * \param j the y coordinate of the point at which we compute the normal - * \param dx the delta used in the x coordinate - * \param dy the delta used in the y coordinate - */ -void compute_surface_normal(Fvector &N, gdouble ss, NRPixBlock *in, int i, int j, int dx, int dy); - -/** * Applies the transformation matrix to (x, y, z). This function assumes that * trans[0] = trans[3]. x and y are transformed according to trans, z is * multiplied by trans[0]. diff --git a/src/display/nr-arena-glyphs.cpp b/src/display/nr-arena-glyphs.cpp index a67812d8f..facb5e9c6 100644 --- a/src/display/nr-arena-glyphs.cpp +++ b/src/display/nr-arena-glyphs.cpp @@ -1,5 +1,3 @@ -#define __NR_ARENA_GLYPHS_C__ - /* * RGBA display list system for inkscape * @@ -16,22 +14,18 @@ #ifdef HAVE_CONFIG_H # include <config.h> #endif -#include <libnr/nr-blit.h> -#include <libnr/nr-convert2geom.h> +#include "libnr/nr-convert2geom.h" #include <2geom/affine.h> -#include "../style.h" -#include "nr-arena.h" -#include "nr-arena-glyphs.h" +#include "style.h" +#include "display/nr-arena.h" +#include "display/nr-arena-glyphs.h" #include <cairo.h> -#include "inkscape-cairo.h" -#include "display/grayscale.h" -#include "sp-paint-server.h" +#include "display/cairo-utils.h" +#include "helper/geom.h" #ifdef test_glyph_liv #include "../display/canvas-bpath.h" -#include <libnrtype/font-instance.h> -#include <libnrtype/raster-glyph.h> -#include <libnrtype/RasterFont.h> +#include "libnrtype/font-instance.h" // defined in nr-arena-shape.cpp void nr_pixblock_render_shape_mask_or(NRPixBlock &m, Shape *theS); @@ -46,7 +40,7 @@ static void nr_arena_glyphs_init(NRArenaGlyphs *glyphs); static void nr_arena_glyphs_finalize(NRObject *object); static guint nr_arena_glyphs_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, guint reset); -static guint nr_arena_glyphs_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb); +static guint nr_arena_glyphs_clip(cairo_t *ct, NRArenaItem *item, NRRectL *area); static NRArenaItem *nr_arena_glyphs_pick(NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); static NRArenaItemClass *glyphs_parent_class; @@ -88,13 +82,9 @@ nr_arena_glyphs_class_init(NRArenaGlyphsClass *klass) static void nr_arena_glyphs_init(NRArenaGlyphs *glyphs) { - glyphs->style = NULL; glyphs->g_transform.setIdentity(); glyphs->font = NULL; glyphs->glyph = 0; - - glyphs->rfont = NULL; - glyphs->sfont = NULL; glyphs->x = glyphs->y = 0.0; } @@ -103,132 +93,70 @@ nr_arena_glyphs_finalize(NRObject *object) { NRArenaGlyphs *glyphs = static_cast<NRArenaGlyphs *>(object); - if (glyphs->rfont) { - glyphs->rfont->Unref(); - glyphs->rfont=NULL; - } - if (glyphs->sfont) { - glyphs->sfont->Unref(); - glyphs->sfont=NULL; - } - if (glyphs->font) { glyphs->font->Unref(); glyphs->font=NULL; } - if (glyphs->style) { - sp_style_unref(glyphs->style); - glyphs->style = NULL; - } - ((NRObjectClass *) glyphs_parent_class)->finalize(object); } static guint nr_arena_glyphs_update(NRArenaItem *item, NRRectL */*area*/, NRGC *gc, guint /*state*/, guint /*reset*/) { - NRArenaGlyphs *glyphs; - raster_font *rfont; - - glyphs = NR_ARENA_GLYPHS(item); + NRArenaGlyphs *glyphs = NR_ARENA_GLYPHS(item); + NRArenaGlyphsGroup *ggroup = NR_ARENA_GLYPHS_GROUP(item->parent); - if (!glyphs->font || !glyphs->style) + if (!glyphs->font || !ggroup->style) return NR_ARENA_ITEM_STATE_ALL; - if ((glyphs->style->fill.isNone()) && (glyphs->style->stroke.isNone())) + if (ggroup->nrstyle.fill.type == NRStyle::PAINT_NONE && ggroup->nrstyle.stroke.type == NRStyle::PAINT_NONE) return NR_ARENA_ITEM_STATE_ALL; - NRRect bbox; - bbox.x0 = bbox.y0 = NR_HUGE; - bbox.x1 = bbox.y1 = -NR_HUGE; - - float const scale = gc->transform.descrim(); - - if (!glyphs->style->fill.isNone()) { - Geom::Affine t; - t = glyphs->g_transform * gc->transform; - glyphs->x = t[4]; - glyphs->y = t[5]; - t[4]=0; - t[5]=0; - rfont = glyphs->font->RasterFont(t, 0); - if (glyphs->rfont) glyphs->rfont->Unref(); - glyphs->rfont = rfont; - - if (glyphs->style->stroke.isNone() || fabs(glyphs->style->stroke_width.computed * scale) <= 0.01) { // Optimization: do fill bbox only if there's no stroke - NRRect narea; - if ( glyphs->rfont ) glyphs->rfont->BBox(glyphs->glyph, &narea); - bbox.x0 = narea.x0 + glyphs->x; - bbox.y0 = narea.y0 + glyphs->y; - bbox.x1 = narea.x1 + glyphs->x; - bbox.y1 = narea.y1 + glyphs->y; + Geom::OptRect b; + Geom::Affine t = glyphs->g_transform * gc->transform; + glyphs->x = t[4]; + glyphs->y = t[5]; + + b = bounds_exact_transformed(*glyphs->font->PathVector(glyphs->glyph), t); + if (b && ggroup->nrstyle.stroke.type != NRStyle::PAINT_NONE) { + float width, scale; + scale = gc->transform.descrim(); + width = MAX(0.125, ggroup->nrstyle.stroke_width * scale); + if ( fabs(ggroup->nrstyle.stroke_width * scale) > 0.01 ) { // FIXME: this is always true + b->expandBy(width); } - } - - if (!glyphs->style->stroke.isNone()) { - /* Build state data */ - Geom::Affine t; - t = glyphs->g_transform * gc->transform; - glyphs->x = t[4]; - glyphs->y = t[5]; - t[4]=0; - t[5]=0; - - if ( fabs(glyphs->style->stroke_width.computed * scale) > 0.01 ) { // sinon c'est 0=oon veut pas de bord - font_style nstyl; - nstyl.transform = t; - nstyl.stroke_width=MAX(0.125, glyphs->style->stroke_width.computed * scale); - if ( glyphs->style->stroke_linecap.computed == SP_STROKE_LINECAP_BUTT ) nstyl.stroke_cap=butt_straight; - if ( glyphs->style->stroke_linecap.computed == SP_STROKE_LINECAP_ROUND ) nstyl.stroke_cap=butt_round; - if ( glyphs->style->stroke_linecap.computed == SP_STROKE_LINECAP_SQUARE ) nstyl.stroke_cap=butt_square; - if ( glyphs->style->stroke_linejoin.computed == SP_STROKE_LINEJOIN_MITER ) nstyl.stroke_join=join_pointy; - if ( glyphs->style->stroke_linejoin.computed == SP_STROKE_LINEJOIN_ROUND ) nstyl.stroke_join=join_round; - if ( glyphs->style->stroke_linejoin.computed == SP_STROKE_LINEJOIN_BEVEL ) nstyl.stroke_join=join_straight; - nstyl.stroke_miter_limit = glyphs->style->stroke_miterlimit.value; - nstyl.nbDash=0; - nstyl.dash_offset = 0; - nstyl.dashes=NULL; - if ( glyphs->style->stroke_dash.n_dash > 0 ) { - nstyl.dash_offset = glyphs->style->stroke_dash.offset * scale; - nstyl.nbDash=glyphs->style->stroke_dash.n_dash; - nstyl.dashes=(double*)malloc(nstyl.nbDash*sizeof(double)); - for (int i = 0; i < nstyl.nbDash; i++) nstyl.dashes[i]= glyphs->style->stroke_dash.dash[i] * scale; - } - rfont = glyphs->font->RasterFont( nstyl); - if ( nstyl.dashes ) free(nstyl.dashes); - if (glyphs->sfont) glyphs->sfont->Unref(); - glyphs->sfont = rfont; - - NRRect narea; - if ( glyphs->sfont ) glyphs->sfont->BBox(glyphs->glyph, &narea); - narea.x0-=nstyl.stroke_width; - narea.y0-=nstyl.stroke_width; - narea.x1+=nstyl.stroke_width; - narea.y1+=nstyl.stroke_width; - bbox.x0 = narea.x0 + glyphs->x; - bbox.y0 = narea.y0 + glyphs->y; - bbox.x1 = narea.x1 + glyphs->x; - bbox.y1 = narea.y1 + glyphs->y; + // those pesky miters, now + float miterMax = width * ggroup->nrstyle.miter_limit; + if ( miterMax > 0.01 ) { + // grunt mode. we should compute the various miters instead + // (one for each point on the curve) + b->expandBy(miterMax); } } - if (nr_rect_d_test_empty(bbox)) return NR_ARENA_ITEM_STATE_ALL; - item->bbox.x0 = static_cast<NR::ICoord>(floor(bbox.x0)); - item->bbox.y0 = static_cast<NR::ICoord>(floor(bbox.y0)); - item->bbox.x1 = static_cast<NR::ICoord>(ceil (bbox.x1)); - item->bbox.y1 = static_cast<NR::ICoord>(ceil (bbox.y1)); + if (b) { + item->bbox.x0 = static_cast<NR::ICoord>(floor(b->left())); + item->bbox.y0 = static_cast<NR::ICoord>(floor(b->top())); + item->bbox.x1 = static_cast<NR::ICoord>(ceil (b->right())); + item->bbox.y1 = static_cast<NR::ICoord>(ceil (b->bottom())); + } else { + item->bbox.x0 = 0; + item->bbox.y0 = 0; + item->bbox.x1 = -1; + item->bbox.y1 = -1; + } return NR_ARENA_ITEM_STATE_ALL; } static guint -nr_arena_glyphs_clip(NRArenaItem *item, NRRectL */*area*/, NRPixBlock */*pb*/) +nr_arena_glyphs_clip(cairo_t *ct, NRArenaItem *item, NRRectL */*area*/) { NRArenaGlyphs *glyphs; glyphs = NR_ARENA_GLYPHS(item); - if (!glyphs->font ) return item->state; + if (!glyphs->font) return item->state; /* TODO : render to greyscale pixblock provided for clipping */ @@ -243,7 +171,6 @@ nr_arena_glyphs_pick(NRArenaItem *item, Geom::Point p, gdouble delta, unsigned i glyphs = NR_ARENA_GLYPHS(item); if (!glyphs->font ) return NULL; - if (!glyphs->style) return NULL; double const x = p[Geom::X]; double const y = p[Geom::Y]; @@ -275,53 +202,13 @@ nr_arena_glyphs_set_path(NRArenaGlyphs *glyphs, SPCurve */*curve*/, unsigned int nr_arena_item_request_update(NR_ARENA_ITEM(glyphs), NR_ARENA_ITEM_STATE_ALL, FALSE); } -void -nr_arena_glyphs_set_style(NRArenaGlyphs *glyphs, SPStyle *style) -{ - nr_return_if_fail(glyphs != NULL); - nr_return_if_fail(NR_IS_ARENA_GLYPHS(glyphs)); - - if (style) sp_style_ref(style); - if (glyphs->style) sp_style_unref(glyphs->style); - glyphs->style = style; - - nr_arena_item_request_update(NR_ARENA_ITEM(glyphs), NR_ARENA_ITEM_STATE_ALL, FALSE); -} - -static guint -nr_arena_glyphs_fill_mask(NRArenaGlyphs *glyphs, NRRectL *area, NRPixBlock *m) -{ - /* fixme: area == m->area, so merge these */ - - NRArenaItem *item = NR_ARENA_ITEM(glyphs); - - if (glyphs->rfont && nr_rect_l_test_intersect_ptr(area, &item->bbox)) { - raster_glyph *g = glyphs->rfont->GetGlyph(glyphs->glyph); - if ( g ) g->Blit(Geom::Point(glyphs->x, glyphs->y), *m); - } - - return item->state; -} - -static guint -nr_arena_glyphs_stroke_mask(NRArenaGlyphs *glyphs, NRRectL *area, NRPixBlock *m) -{ - NRArenaItem *item = NR_ARENA_ITEM(glyphs); - if (glyphs->sfont && nr_rect_l_test_intersect_ptr(area, &item->bbox)) { - raster_glyph *g=glyphs->sfont->GetGlyph(glyphs->glyph); - if ( g ) g->Blit(Geom::Point(glyphs->x, glyphs->y),*m); - } - - return item->state; -} - static void nr_arena_glyphs_group_class_init(NRArenaGlyphsGroupClass *klass); static void nr_arena_glyphs_group_init(NRArenaGlyphsGroup *group); static void nr_arena_glyphs_group_finalize(NRObject *object); static guint nr_arena_glyphs_group_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, guint reset); static unsigned int nr_arena_glyphs_group_render(cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int flags); -static unsigned int nr_arena_glyphs_group_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb); +static unsigned int nr_arena_glyphs_group_clip(cairo_t *ct, NRArenaItem *item, NRRectL *area); static NRArenaItem *nr_arena_glyphs_group_pick(NRArenaItem *item, Geom::Point p, gdouble delta, unsigned int sticky); static NRArenaGroupClass *group_parent_class; @@ -366,10 +253,7 @@ nr_arena_glyphs_group_init(NRArenaGlyphsGroup *group) { group->style = NULL; group->paintbox.x0 = group->paintbox.y0 = 0.0F; - group->paintbox.x1 = group->paintbox.y1 = 1.0F; - - group->fill_painter = NULL; - group->stroke_painter = NULL; + group->paintbox.x1 = group->paintbox.y1 = -1.0F; } static void @@ -377,16 +261,6 @@ nr_arena_glyphs_group_finalize(NRObject *object) { NRArenaGlyphsGroup *group=static_cast<NRArenaGlyphsGroup *>(object); - if (group->fill_painter) { - sp_painter_free(group->fill_painter); - group->fill_painter = NULL; - } - - if (group->stroke_painter) { - sp_painter_free(group->stroke_painter); - group->stroke_painter = NULL; - } - if (group->style) { sp_style_unref(group->style); group->style = NULL; @@ -400,34 +274,7 @@ nr_arena_glyphs_group_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint s { NRArenaGlyphsGroup *group = NR_ARENA_GLYPHS_GROUP(item); - if (group->fill_painter) { - sp_painter_free(group->fill_painter); - group->fill_painter = NULL; - } - - if (group->stroke_painter) { - sp_painter_free(group->stroke_painter); - group->stroke_painter = NULL; - } - - item->render_opacity = TRUE; - if (group->style->fill.isPaintserver()) { - group->fill_painter = sp_paint_server_painter_new(SP_STYLE_FILL_SERVER(group->style), - gc->transform, gc->parent->transform, - &group->paintbox); - item->render_opacity = FALSE; - } - - if (group->style->stroke.isPaintserver()) { - group->stroke_painter = sp_paint_server_painter_new(SP_STYLE_STROKE_SERVER(group->style), - gc->transform, gc->parent->transform, - &group->paintbox); - item->render_opacity = FALSE; - } - - if ( item->render_opacity == TRUE && !group->style->stroke.isNone() && !group->style->fill.isNone() ) { - item->render_opacity=FALSE; - } + group->nrstyle.update(); if (((NRArenaItemClass *) group_parent_class)->update) return ((NRArenaItemClass *) group_parent_class)->update(item, area, gc, state, reset); @@ -443,155 +290,81 @@ nr_arena_glyphs_group_render(cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPi NRArenaGroup *group = NR_ARENA_GROUP(item); NRArenaGlyphsGroup *ggroup = NR_ARENA_GLYPHS_GROUP(item); - SPStyle const *style = ggroup->style; - guint ret = item->state; - bool print_colors_preview = (item->arena->colorrendermode == Inkscape::COLORRENDERMODE_PRINT_COLORS_PREVIEW); - bool grayscale = (item->arena->colorrendermode == Inkscape::COLORRENDERMODE_GRAYSCALE); + if (!ct) return item->state; if (item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE) { - if (!ct) - return item->state; - guint32 rgba = item->arena->outlinecolor; - // FIXME: we use RGBA buffers but cairo writes BGRA (on i386), so we must cheat - // by setting color channels in the "wrong" order - cairo_set_source_rgba(ct, SP_RGBA32_B_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_R_F(rgba), SP_RGBA32_A_F(rgba)); + ink_cairo_set_source_rgba32(ct, rgba); cairo_set_tolerance(ct, 1.25); // low quality, but good enough for outline mode + NRRect temp(area->x0, area->y0, area->x1, area->y1); + Geom::OptRect area_2geom = temp.upgrade_2geom(); + for (child = group->children; child != NULL; child = child->next) { NRArenaGlyphs *g = NR_ARENA_GLYPHS(child); Geom::PathVector const * pathv = g->font->PathVector(g->glyph); + Geom::Affine transform = g->g_transform * group->ctm; cairo_new_path(ct); - Geom::Affine transform = g->g_transform * group->ctm; - feed_pathvector_to_cairo (ct, *pathv, transform, to_2geom((pb->area).upgrade()), false, 0); + ink_cairo_transform(ct, transform); + feed_pathvector_to_cairo (ct, *pathv); cairo_fill(ct); - pb->empty = FALSE; } - return ret; + return item->state; } + // NOTE: this is very similar to nr-arena-shape.cpp; the only difference is path feeding + bool has_stroke, has_fill; + cairo_save(ct); + ink_cairo_transform(ct, ggroup->ctm); - /* Fill */ - if (!style->fill.isNone() || item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE) { - NRPixBlock m; - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); - } - - m.visible_area = pb->visible_area; - - /* Render children fill mask */ - for (child = group->children; child != NULL; child = child->next) { - ret = nr_arena_glyphs_fill_mask(NR_ARENA_GLYPHS(child), area, &m); - if (!(ret & NR_ARENA_ITEM_STATE_RENDER)) { - nr_pixblock_release(&m); - return ret; - } - } + has_fill = ggroup->nrstyle.prepareFill(ct, &ggroup->paintbox); + has_stroke = ggroup->nrstyle.prepareStroke(ct, &ggroup->paintbox); - /* Composite into buffer */ - if (style->fill.isPaintserver()) { - if (ggroup->fill_painter) { - nr_arena_render_paintserver_fill(pb, area, ggroup->fill_painter, SP_SCALE24_TO_FLOAT(style->fill_opacity.value), &m); - } - } else if (style->fill.isColor() || item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE) { - guint32 rgba; - if (item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE) { - // In outline mode, render fill only, using outlinecolor - rgba = item->arena->outlinecolor; - } else if ( item->render_opacity ) { - rgba = style->fill.value.color.toRGBA32( SP_SCALE24_TO_FLOAT(style->fill_opacity.value) * - SP_SCALE24_TO_FLOAT(style->opacity.value) ); - } else { - rgba = style->fill.value.color.toRGBA32( SP_SCALE24_TO_FLOAT(style->fill_opacity.value) ); - } - - if (print_colors_preview) { - nr_arena_separate_color_plates(&rgba); - } else if (grayscale) { - rgba = Grayscale::process(rgba); - } - - nr_blit_pixblock_mask_rgba32(pb, &m, rgba); - pb->empty = FALSE; - } - - nr_pixblock_release(&m); - } - - /* Stroke */ - if (!style->stroke.isNone() && !(item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE)) { - NRPixBlock m; - guint32 rgba; - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); + if (has_fill || has_stroke) { + for (NRArenaItem *child = ggroup->children; child != NULL; child = child->next) { + NRArenaGlyphs *g = NR_ARENA_GLYPHS(child); + Geom::PathVector const &pathv = *g->font->PathVector(g->glyph); - // if memory allocation failed, abort - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); + cairo_save(ct); + ink_cairo_transform(ct, g->g_transform); + feed_pathvector_to_cairo(ct, pathv); + cairo_restore(ct); } - m.visible_area = pb->visible_area; - /* Render children stroke mask */ - for (child = group->children; child != NULL; child = child->next) { - ret = nr_arena_glyphs_stroke_mask(NR_ARENA_GLYPHS(child), area, &m); - if (!(ret & NR_ARENA_ITEM_STATE_RENDER)) { - nr_pixblock_release(&m); - return ret; - } + if (has_fill) { + ggroup->nrstyle.applyFill(ct); + cairo_fill_preserve(ct); } - /* Composite into buffer */ - if (style->stroke.isPaintserver()) { - if (ggroup->stroke_painter) { - nr_arena_render_paintserver_fill(pb, area, ggroup->stroke_painter, SP_SCALE24_TO_FLOAT(style->stroke_opacity.value), &m); - } - } else if (style->stroke.isColor()) { - if ( item->render_opacity ) { - rgba = style->stroke.value.color.toRGBA32( SP_SCALE24_TO_FLOAT(style->stroke_opacity.value) * - SP_SCALE24_TO_FLOAT(style->opacity.value) ); - } else { - rgba = style->stroke.value.color.toRGBA32( SP_SCALE24_TO_FLOAT(style->stroke_opacity.value) ); - } - - if (print_colors_preview) { - nr_arena_separate_color_plates(&rgba); - } else if (grayscale) { - rgba = Grayscale::process(rgba); - } - - nr_blit_pixblock_mask_rgba32(pb, &m, rgba); - pb->empty = FALSE; - } else { - // nothing + if (has_stroke) { + ggroup->nrstyle.applyStroke(ct); + cairo_stroke_preserve(ct); } - nr_pixblock_release(&m); - } + cairo_new_path(ct); // clear path + } // has fill or stroke pattern + cairo_restore(ct); - return ret; + return item->state; } static unsigned int -nr_arena_glyphs_group_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb) +nr_arena_glyphs_group_clip(cairo_t *ct, NRArenaItem *item, NRRectL *area) { - NRArenaGroup *group = NR_ARENA_GROUP(item); + //NRArenaGroup *group = NR_ARENA_GROUP(item); guint ret = item->state; /* Render children fill mask */ + /* for (NRArenaItem *child = group->children; child != NULL; child = child->next) { ret = nr_arena_glyphs_fill_mask(NR_ARENA_GLYPHS(child), area, pb); if (!(ret & NR_ARENA_ITEM_STATE_RENDER)) return ret; - } + }*/ return ret; } @@ -638,7 +411,6 @@ nr_arena_glyphs_group_add_component(NRArenaGlyphsGroup *sg, font_instance *font, nr_arena_item_append_child(NR_ARENA_ITEM(group), new_arena); nr_arena_item_unref(new_arena); nr_arena_glyphs_set_path(NR_ARENA_GLYPHS(new_arena), NULL, FALSE, font, glyph, &transform); - nr_arena_glyphs_set_style(NR_ARENA_GLYPHS(new_arena), sg->style); } } @@ -648,16 +420,11 @@ nr_arena_glyphs_group_set_style(NRArenaGlyphsGroup *sg, SPStyle *style) nr_return_if_fail(sg != NULL); nr_return_if_fail(NR_IS_ARENA_GLYPHS_GROUP(sg)); - NRArenaGroup *group = NR_ARENA_GROUP(sg); - if (style) sp_style_ref(style); if (sg->style) sp_style_unref(sg->style); sg->style = style; - for (NRArenaItem *child = group->children; child != NULL; child = child->next) { - nr_return_if_fail(NR_IS_ARENA_GLYPHS(child)); - nr_arena_glyphs_set_style(NR_ARENA_GLYPHS(child), sg->style); - } + sg->nrstyle.set(style); nr_arena_item_request_update(NR_ARENA_ITEM(sg), NR_ARENA_ITEM_STATE_ALL, FALSE); } @@ -675,9 +442,8 @@ nr_arena_glyphs_group_set_paintbox(NRArenaGlyphsGroup *gg, NRRect const *pbox) gg->paintbox.x1 = pbox->x1; gg->paintbox.y1 = pbox->y1; } else { - /* fixme: We kill warning, although not sure what to do here (Lauris) */ gg->paintbox.x0 = gg->paintbox.y0 = 0.0F; - gg->paintbox.x1 = gg->paintbox.y1 = 256.0F; + gg->paintbox.x1 = gg->paintbox.y1 = -1.0F; } nr_arena_item_request_update(NR_ARENA_ITEM(gg), NR_ARENA_ITEM_STATE_ALL, FALSE); diff --git a/src/display/nr-arena-glyphs.h b/src/display/nr-arena-glyphs.h index b56a9f56c..c43095cb2 100644 --- a/src/display/nr-arena-glyphs.h +++ b/src/display/nr-arena-glyphs.h @@ -18,9 +18,10 @@ #define NR_IS_ARENA_GLYPHS(obj) (NR_CHECK_INSTANCE_TYPE ((obj), NR_TYPE_ARENA_GLYPHS)) #include "libnrtype/nrtype-forward.h" - +#include "display/display-forward.h" #include "forward.h" #include "display/nr-arena-item.h" +#include "display/nr-style.h" #define test_glyph_liv @@ -32,22 +33,12 @@ NRType nr_arena_glyphs_get_type (void); struct NRArenaGlyphs : public NRArenaItem { /* Glyphs data */ - SPStyle *style; Geom::Affine g_transform; + font_instance *font; gint glyph; - - raster_font *rfont; - raster_font *sfont; float x, y; -// Geom::Affine cached_tr; -// Shape *cached_shp; -// bool cached_shp_dirty; -// bool cached_style_dirty; - -// Shape *stroke_shp; - static NRArenaGlyphs *create(NRArena *arena) { NRArenaGlyphs *obj=reinterpret_cast<NRArenaGlyphs *>(nr_object_new(NR_TYPE_ARENA_GLYPHS)); obj->init(arena); @@ -79,11 +70,8 @@ typedef struct NRArenaGlyphsGroupClass NRArenaGlyphsGroupClass; NRType nr_arena_glyphs_group_get_type (void); struct NRArenaGlyphsGroup : public NRArenaGroup { - //SPStyle *style; NRRect paintbox; - /* State data */ - SPPainter *fill_painter; - SPPainter *stroke_painter; + NRStyle nrstyle; static NRArenaGlyphsGroup *create(NRArena *arena) { NRArenaGlyphsGroup *obj=reinterpret_cast<NRArenaGlyphsGroup *>(nr_object_new(NR_TYPE_ARENA_GLYPHS_GROUP)); diff --git a/src/display/nr-arena-group.cpp b/src/display/nr-arena-group.cpp index 6c6043b2c..97f92d02d 100644 --- a/src/display/nr-arena-group.cpp +++ b/src/display/nr-arena-group.cpp @@ -14,12 +14,10 @@ #include "display/nr-arena-group.h" #include "display/nr-filter.h" -#include "display/nr-filter-gaussian.h" #include "display/nr-filter-types.h" #include "style.h" #include "sp-filter.h" #include "sp-filter-reference.h" -#include "sp-gaussian-blur.h" #include "filters/blend.h" #include "display/nr-filter-blend.h" #include "helper/geom.h" @@ -35,7 +33,7 @@ static void nr_arena_group_set_child_position (NRArenaItem *item, NRArenaItem *c static unsigned int nr_arena_group_update (NRArenaItem *item, NRRectL *area, NRGC *gc, unsigned int state, unsigned int reset); static unsigned int nr_arena_group_render (cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int flags); -static unsigned int nr_arena_group_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb); +static unsigned int nr_arena_group_clip (cairo_t *ct, NRArenaItem *item, NRRectL *area); static NRArenaItem *nr_arena_group_pick (NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); static NRArenaItemClass *parent_class; @@ -233,7 +231,7 @@ nr_arena_group_render (cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock } static unsigned int -nr_arena_group_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb) +nr_arena_group_clip (cairo_t *ct, NRArenaItem *item, NRRectL *area) { NRArenaGroup *group = NR_ARENA_GROUP (item); @@ -241,7 +239,7 @@ nr_arena_group_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb) /* Just compose children into parent buffer */ for (NRArenaItem *child = group->children; child != NULL; child = child->next) { - ret = nr_arena_item_invoke_clip (child, area, pb); + ret = nr_arena_item_invoke_clip (ct, child, area); if (ret & NR_ARENA_ITEM_STATE_INVALID) break; } diff --git a/src/display/nr-arena-image.cpp b/src/display/nr-arena-image.cpp index 6539ae4d2..cb1bc5849 100644 --- a/src/display/nr-arena-image.cpp +++ b/src/display/nr-arena-image.cpp @@ -12,20 +12,15 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <libnr/nr-compose-transform.h> #include <2geom/transforms.h> -#include <libnr/nr-blit.h> #include "../preferences.h" #include "nr-arena-image.h" #include "style.h" +#include "display/cairo-utils.h" #include "display/nr-arena.h" #include "display/nr-filter.h" -#include "display/nr-filter-gaussian.h" #include "sp-filter.h" #include "sp-filter-reference.h" -#include "sp-gaussian-blur.h" -#include "filters/blend.h" -#include "display/nr-filter-blend.h" int nr_arena_image_x_sample = 1; int nr_arena_image_y_sample = 1; @@ -42,6 +37,7 @@ static void nr_arena_image_finalize (NRObject *object); static unsigned int nr_arena_image_update (NRArenaItem *item, NRRectL *area, NRGC *gc, unsigned int state, unsigned int reset); static unsigned int nr_arena_image_render (cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int flags); static NRArenaItem *nr_arena_image_pick (NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); +static Geom::Rect nr_arena_image_rect (NRArenaImage *image); static NRArenaItemClass *parent_class; @@ -82,14 +78,11 @@ nr_arena_image_class_init (NRArenaImageClass *klass) static void nr_arena_image_init (NRArenaImage *image) { - image->px = NULL; - - image->pxw = image->pxh = image->pxrs = 0; - image->x = image->y = 0.0; - image->width = 256.0; - image->height = 256.0; - - image->grid2px.setIdentity(); + image->pixbuf = NULL; + image->ctm.setIdentity(); + image->clipbox = Geom::Rect(); + image->ox = image->oy = 0.0; + image->sx = image->sy = 1.0; image->style = 0; image->render_opacity = TRUE; @@ -100,7 +93,12 @@ nr_arena_image_finalize (NRObject *object) { NRArenaImage *image = NR_ARENA_IMAGE (object); - image->px = NULL; + if (image->pixbuf != NULL) { + g_object_unref(image->pixbuf); + cairo_surface_destroy(image->surface); + } + if (image->style) + sp_style_unref(image->style); ((NRObjectClass *) parent_class)->finalize (object); } @@ -108,54 +106,24 @@ nr_arena_image_finalize (NRObject *object) static unsigned int nr_arena_image_update( NRArenaItem *item, NRRectL */*area*/, NRGC *gc, unsigned int /*state*/, unsigned int /*reset*/ ) { - Geom::Affine grid2px; - // clear old bbox nr_arena_item_request_render(item); NRArenaImage *image = NR_ARENA_IMAGE (item); /* Copy affine */ - grid2px = gc->transform.inverse(); - double hscale, vscale; // todo: replace with Geom::Scale - if (image->px) { - hscale = image->pxw / image->width; - vscale = image->pxh / image->height; - } else { - hscale = 1.0; - vscale = 1.0; - } - - image->grid2px[0] = grid2px[0] * hscale; - image->grid2px[2] = grid2px[2] * hscale; - image->grid2px[4] = grid2px[4] * hscale; - image->grid2px[1] = grid2px[1] * vscale; - image->grid2px[3] = grid2px[3] * vscale; - image->grid2px[5] = grid2px[5] * vscale; - - image->grid2px[4] -= image->x * hscale; - image->grid2px[5] -= image->y * vscale; + image->ctm = gc->transform; /* Calculate bbox */ - if (image->px) { + if (image->pixbuf) { NRRect bbox; - bbox.x0 = image->x; - bbox.y0 = image->y; - bbox.x1 = image->x + image->width; - bbox.y1 = image->y + image->height; - - image->c00 = (Geom::Point(bbox.x0, bbox.y0) * gc->transform); - image->c01 = (Geom::Point(bbox.x0, bbox.y1) * gc->transform); - image->c10 = (Geom::Point(bbox.x1, bbox.y0) * gc->transform); - image->c11 = (Geom::Point(bbox.x1, bbox.y1) * gc->transform); + Geom::Rect r = nr_arena_image_rect(image) * gc->transform; - nr_rect_d_matrix_transform (&bbox, &bbox, gc->transform); - - item->bbox.x0 = static_cast<NR::ICoord>(floor(bbox.x0)); // Floor gives the coordinate in which the point resides - item->bbox.y0 = static_cast<NR::ICoord>(floor(bbox.y0)); - item->bbox.x1 = static_cast<NR::ICoord>(ceil (bbox.x1)); // Ceil gives the first coordinate beyond the point - item->bbox.y1 = static_cast<NR::ICoord>(ceil (bbox.y1)); + item->bbox.x0 = floor(r.left()); // Floor gives the coordinate in which the point resides + item->bbox.y0 = floor(r.top()); + item->bbox.x1 = ceil(r.right()); // Ceil gives the first coordinate beyond the point + item->bbox.y1 = ceil(r.bottom()); } else { item->bbox.x0 = (int) gc->transform[4]; item->bbox.y0 = (int) gc->transform[5]; @@ -166,78 +134,63 @@ nr_arena_image_update( NRArenaItem *item, NRRectL */*area*/, NRGC *gc, unsigned return NR_ARENA_ITEM_STATE_ALL; } -#define FBITS 12 -#define b2i (image->grid2px) - static unsigned int -nr_arena_image_render( cairo_t *ct, NRArenaItem *item, NRRectL */*area*/, NRPixBlock *pb, unsigned int /*flags*/ ) +nr_arena_image_render( cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int /*flags*/ ) { - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - nr_arena_image_x_sample = prefs->getInt("/options/bitmapoversample/value", 1); - nr_arena_image_y_sample = nr_arena_image_x_sample; + if (!ct) + return item->state; bool outline = (item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); NRArenaImage *image = NR_ARENA_IMAGE (item); - Geom::Affine d2s; - - d2s[0] = b2i[0]; - d2s[1] = b2i[1]; - d2s[2] = b2i[2]; - d2s[3] = b2i[3]; - d2s[4] = b2i[0] * pb->area.x0 + b2i[2] * pb->area.y0 + b2i[4]; - d2s[5] = b2i[1] * pb->area.x0 + b2i[3] * pb->area.y0 + b2i[5]; - if (!outline) { + if (!image->pixbuf) return item->state; - if (!image->px) return item->state; + // FIXME: at the moment gdk_cairo_set_source_pixbuf creates an ARGB copy + // of the pixbuf. Fix this in Cairo and/or GDK. + cairo_save(ct); + ink_cairo_transform(ct, image->ctm); - guint32 Falpha = item->opacity; - if (Falpha < 1) return item->state; + cairo_new_path(ct); + cairo_rectangle(ct, image->clipbox.left(), image->clipbox.top(), + image->clipbox.width(), image->clipbox.height()); + cairo_clip(ct); - unsigned char * dpx = NR_PIXBLOCK_PX (pb); - int const drs = pb->rs; - int const dw = pb->area.x1 - pb->area.x0; - int const dh = pb->area.y1 - pb->area.y0; + cairo_translate(ct, image->ox, image->oy); + cairo_scale(ct, image->sx, image->sy); - unsigned char * spx = image->px; - int const srs = image->pxrs; - int const sw = image->pxw; - int const sh = image->pxh; + cairo_set_source_surface(ct, image->surface, 0, 0); - if (pb->mode == NR_PIXBLOCK_MODE_R8G8B8) { - /* fixme: This is not implemented yet (Lauris) */ - /* nr_R8G8B8_R8G8B8_R8G8B8A8_N_TRANSFORM (dpx, dw, dh, drs, spx, sw, sh, srs, d2s, Falpha, nr_arena_image_x_sample, nr_arena_image_y_sample); */ - } else if (pb->mode == NR_PIXBLOCK_MODE_R8G8B8A8P) { - nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM (dpx, dw, dh, drs, spx, sw, sh, srs, d2s, Falpha, nr_arena_image_x_sample, nr_arena_image_y_sample); - } else if (pb->mode == NR_PIXBLOCK_MODE_R8G8B8A8N) { - nr_R8G8B8A8_N_R8G8B8A8_N_R8G8B8A8_N_TRANSFORM (dpx, dw, dh, drs, spx, sw, sh, srs, d2s, Falpha, nr_arena_image_x_sample, nr_arena_image_y_sample); + cairo_matrix_t tt; + Geom::Affine total; + cairo_get_matrix(ct, &tt); + ink_matrix_to_2geom(total, tt); + + if (total.expansionX() > 1.0 || total.expansionY() > 1.0) { + cairo_pattern_t *p = cairo_get_source(ct); + cairo_pattern_set_filter(p, CAIRO_FILTER_NEAREST); } - pb->empty = FALSE; + cairo_paint_with_alpha(ct, ((double) item->opacity) / 255.0); + cairo_restore(ct); } else { // outline; draw a rect instead - - if (!ct) - return item->state; - + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); guint32 rgba = prefs->getInt("/options/wireframecolors/images", 0xff0000ff); - // FIXME: we use RGBA buffers but cairo writes BGRA (on i386), so we must cheat - // by setting color channels in the "wrong" order - cairo_set_source_rgba(ct, SP_RGBA32_B_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_R_F(rgba), SP_RGBA32_A_F(rgba)); - cairo_set_line_width(ct, 0.5); + cairo_save(ct); + ink_cairo_transform(ct, image->ctm); + cairo_new_path(ct); - Geom::Point shift(pb->area.x0, pb->area.y0); - Geom::Point c00 = image->c00 - shift; - Geom::Point c01 = image->c01 - shift; - Geom::Point c11 = image->c11 - shift; - Geom::Point c10 = image->c10 - shift; + Geom::Rect r = nr_arena_image_rect (image); + Geom::Point c00 = r.corner(0); + Geom::Point c01 = r.corner(3); + Geom::Point c11 = r.corner(2); + Geom::Point c10 = r.corner(1); cairo_move_to (ct, c00[Geom::X], c00[Geom::Y]); - // the box cairo_line_to (ct, c10[Geom::X], c10[Geom::Y]); cairo_line_to (ct, c11[Geom::X], c11[Geom::Y]); @@ -247,12 +200,12 @@ nr_arena_image_render( cairo_t *ct, NRArenaItem *item, NRRectL */*area*/, NRPixB cairo_line_to (ct, c11[Geom::X], c11[Geom::Y]); cairo_move_to (ct, c10[Geom::X], c10[Geom::Y]); cairo_line_to (ct, c01[Geom::X], c01[Geom::Y]); + cairo_restore(ct); + cairo_set_line_width(ct, 0.5); + ink_cairo_set_source_rgba32(ct, rgba); cairo_stroke(ct); - - pb->empty = FALSE; } - return item->state; } @@ -282,33 +235,47 @@ nr_arena_image_pick( NRArenaItem *item, Geom::Point p, double delta, unsigned in { NRArenaImage *image = NR_ARENA_IMAGE (item); - if (!image->px) return NULL; + if (!image->pixbuf) return NULL; bool outline = (item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); if (outline) { + Geom::Rect r = nr_arena_image_rect (image); + + Geom::Point c00 = r.corner(0); + Geom::Point c01 = r.corner(3); + Geom::Point c11 = r.corner(2); + Geom::Point c10 = r.corner(1); // frame - if (distance_to_segment (p, image->c00, image->c10) < delta) return item; - if (distance_to_segment (p, image->c10, image->c11) < delta) return item; - if (distance_to_segment (p, image->c11, image->c01) < delta) return item; - if (distance_to_segment (p, image->c01, image->c00) < delta) return item; + if (distance_to_segment (p, c00, c10) < delta) return item; + if (distance_to_segment (p, c10, c11) < delta) return item; + if (distance_to_segment (p, c11, c01) < delta) return item; + if (distance_to_segment (p, c01, c00) < delta) return item; // diagonals - if (distance_to_segment (p, image->c00, image->c11) < delta) return item; - if (distance_to_segment (p, image->c10, image->c01) < delta) return item; + if (distance_to_segment (p, c00, c11) < delta) return item; + if (distance_to_segment (p, c10, c01) < delta) return item; return NULL; } else { - unsigned char *const pixels = image->px; - int const width = image->pxw; - int const height = image->pxh; - int const rowstride = image->pxrs; - Geom::Point tp = p * image->grid2px; - int const ix = (int)(tp[Geom::X]); - int const iy = (int)(tp[Geom::Y]); + unsigned char *const pixels = gdk_pixbuf_get_pixels(image->pixbuf); + int const width = gdk_pixbuf_get_width(image->pixbuf); + int const height = gdk_pixbuf_get_height(image->pixbuf); + int const rowstride = gdk_pixbuf_get_rowstride(image->pixbuf); + + Geom::Point tp = p * image->ctm.inverse(); + Geom::Rect r = nr_arena_image_rect(image); + + if (!r.contains(tp)) + return NULL; + + double vw = width * image->sx; + double vh = height * image->sy; + int ix = floor((tp[Geom::X] - image->ox) / vw * width); + int iy = floor((tp[Geom::Y] - image->oy) / vh * height); if ((ix < 0) || (iy < 0) || (ix >= width) || (iy >= height)) return NULL; @@ -319,32 +286,79 @@ nr_arena_image_pick( NRArenaItem *item, Geom::Point p, double delta, unsigned in } } +Geom::Rect +nr_arena_image_rect (NRArenaImage *image) +{ + Geom::Rect r = image->clipbox; + + if (image->pixbuf) { + double pw = gdk_pixbuf_get_width(image->pixbuf); + double ph = gdk_pixbuf_get_height(image->pixbuf); + double vw = pw * image->sx; + double vh = ph * image->sy; + Geom::Point p(image->ox, image->oy); + Geom::Point wh(vw, vh); + Geom::Rect view(p, p+wh); + Geom::OptRect res = Geom::intersect(r, view); + r = res ? *res : r; + } + + return r; +} + /* Utility */ void -nr_arena_image_set_pixels (NRArenaImage *image, unsigned char const *px, unsigned int pxw, unsigned int pxh, unsigned int pxrs) +nr_arena_image_set_argb32_pixbuf (NRArenaImage *image, GdkPixbuf *pb) +{ + nr_return_if_fail (image != NULL); + nr_return_if_fail (NR_IS_ARENA_IMAGE (image)); + + // when done in this order, it won't break if pb == image->pixbuf and the refcount is 1 + if (pb != NULL) { + g_object_ref (pb); + } + if (image->pixbuf != NULL) { + g_object_unref(image->pixbuf); + cairo_surface_destroy(image->surface); + } + image->pixbuf = pb; + image->surface = pb ? ink_cairo_surface_create_for_argb32_pixbuf(pb) : NULL; + + nr_arena_item_request_update (NR_ARENA_ITEM (image), NR_ARENA_ITEM_STATE_ALL, FALSE); +} + +void +nr_arena_image_set_clipbox (NRArenaImage *image, Geom::Rect const &clip) +{ + nr_return_if_fail (image != NULL); + nr_return_if_fail (NR_IS_ARENA_IMAGE (image)); + + image->clipbox = clip; + + nr_arena_item_request_update (NR_ARENA_ITEM (image), NR_ARENA_ITEM_STATE_ALL, FALSE); +} + +void +nr_arena_image_set_origin (NRArenaImage *image, Geom::Point const &origin) { nr_return_if_fail (image != NULL); nr_return_if_fail (NR_IS_ARENA_IMAGE (image)); - image->px = (unsigned char *) px; - image->pxw = pxw; - image->pxh = pxh; - image->pxrs = pxrs; + image->ox = origin[Geom::X]; + image->oy = origin[Geom::Y]; nr_arena_item_request_update (NR_ARENA_ITEM (image), NR_ARENA_ITEM_STATE_ALL, FALSE); } void -nr_arena_image_set_geometry (NRArenaImage *image, double x, double y, double width, double height) +nr_arena_image_set_scale (NRArenaImage *image, double sx, double sy) { nr_return_if_fail (image != NULL); nr_return_if_fail (NR_IS_ARENA_IMAGE (image)); - image->x = x; - image->y = y; - image->width = width; - image->height = height; + image->sx = sx; + image->sy = sy; nr_arena_item_request_update (NR_ARENA_ITEM (image), NR_ARENA_ITEM_STATE_ALL, FALSE); } diff --git a/src/display/nr-arena-image.h b/src/display/nr-arena-image.h index c8d1525dc..6fa9223dd 100644 --- a/src/display/nr-arena-image.h +++ b/src/display/nr-arena-image.h @@ -13,28 +13,25 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include <gdk-pixbuf/gdk-pixbuf.h> +#include <2geom/rect.h> +#include "nr-arena-item.h" +#include "style.h" + #define NR_TYPE_ARENA_IMAGE (nr_arena_image_get_type ()) #define NR_ARENA_IMAGE(o) (NR_CHECK_INSTANCE_CAST ((o), NR_TYPE_ARENA_IMAGE, NRArenaImage)) #define NR_IS_ARENA_IMAGE(o) (NR_CHECK_INSTANCE_TYPE ((o), NR_TYPE_ARENA_IMAGE)) -#include "nr-arena-item.h" -#include "style.h" - NRType nr_arena_image_get_type (void); struct NRArenaImage : public NRArenaItem { - unsigned char *px; - unsigned int pxw; - unsigned int pxh; - unsigned int pxrs; - - double x, y; - double width, height; + GdkPixbuf *pixbuf; + cairo_surface_t *surface; - Geom::Point c00, c01, c11, c10; // all 4 corners of the image, for outline mode rect - - /* From GRID to PIXELS */ - Geom::Affine grid2px; + Geom::Affine ctm; + Geom::Rect clipbox; + double ox, oy; + double sx, sy; SPStyle *style; @@ -49,10 +46,11 @@ struct NRArenaImageClass { NRArenaItemClass parent_class; }; -void nr_arena_image_set_pixels (NRArenaImage *image, unsigned char const *px, unsigned int pxw, unsigned int pxh, unsigned int pxrs); -void nr_arena_image_set_geometry (NRArenaImage *image, double x, double y, double width, double height); +void nr_arena_image_set_argb32_pixbuf (NRArenaImage *image, GdkPixbuf *pb); void nr_arena_image_set_style (NRArenaImage *image, SPStyle *style); - +void nr_arena_image_set_clipbox (NRArenaImage *image, Geom::Rect const &clip); +void nr_arena_image_set_origin (NRArenaImage *image, Geom::Point const &origin); +void nr_arena_image_set_scale (NRArenaImage *image, double sx, double sy); #endif diff --git a/src/display/nr-arena-item.cpp b/src/display/nr-arena-item.cpp index 6a5b7b5ba..8787c1033 100644 --- a/src/display/nr-arena-item.cpp +++ b/src/display/nr-arena-item.cpp @@ -17,9 +17,10 @@ #include <cstring> #include <string> +#include <cairomm/cairomm.h> -#include <libnr/nr-blit.h> -#include <libnr/nr-pixops.h> +#include "display/cairo-utils.h" +#include "display/cairo-templates.h" #include "nr-arena.h" #include "nr-arena-item.h" #include "gc-core.h" @@ -83,6 +84,7 @@ nr_arena_item_init (NRArenaItem *item) memset (&item->bbox, 0, sizeof (item->bbox)); memset (&item->drawbox, 0, sizeof (item->drawbox)); item->transform = NULL; + item->ctm.setIdentity(); item->opacity = 255; item->render_opacity = FALSE; @@ -104,6 +106,11 @@ nr_arena_item_private_finalize (NRObject *object) item->px = NULL; item->transform = NULL; + if (item->clip) + nr_arena_item_detach(item, item->clip); + if (item->mask) + nr_arena_item_detach(item, item->mask); + ((NRObjectClass *) (parent_class))->finalize (object); } @@ -258,12 +265,15 @@ nr_arena_item_invoke_update (NRArenaItem *item, NRRectL *area, NRGC *gc, if (item->state & NR_ARENA_ITEM_STATE_INVALID) return item->state; - // get a copy of bbox - memcpy(&item->drawbox, &item->bbox, sizeof(item->bbox)); - /* Enlarge the drawbox to contain filter effects */ - if (item->filter && filter) { - item->filter->bbox_enlarge (item->drawbox); + if (item->filter && filter && item->item_bbox) { + item->drawbox.x0 = item->item_bbox->min()[Geom::X]; + item->drawbox.y0 = item->item_bbox->min()[Geom::Y]; + item->drawbox.x1 = item->item_bbox->max()[Geom::X]; + item->drawbox.y1 = item->item_bbox->max()[Geom::Y]; + item->filter->compute_drawbox (item, item->drawbox); + } else { + memcpy(&item->drawbox, &item->bbox, sizeof(item->bbox)); } // fixme: to fix the display glitches, in outline mode bbox must be a combination of // full item bbox and its clip and mask (after we have the API to get these) @@ -301,11 +311,16 @@ nr_arena_item_invoke_update (NRArenaItem *item, NRRectL *area, NRGC *gc, return item->state; } -/** - * Render item to pixblock. - * - * \return Has NR_ARENA_ITEM_STATE_RENDER set on success. - */ +struct MaskLuminanceToAlpha { + guint32 operator()(guint32 in) { + EXTRACT_ARGB32(in, a, r, g, b) + // the operation of unpremul -> luminance-to-alpha -> multiply by alpha + // is equivalent to luminance-to-alpha on premultiplied color values + // original computation in double: r*0.2125 + g*0.7154 + b*0.0721 + guint32 ao = r*109 + g*366 + b*37; // coeffs add up to 512 + return ((ao + 256) << 15) & 0xff000000; // equivalent to ((ao + 256) / 512) << 24 + } +}; unsigned int nr_arena_item_invoke_render (cairo_t *ct, NRArenaItem *item, NRRectL const *area, @@ -314,13 +329,13 @@ nr_arena_item_invoke_render (cairo_t *ct, NRArenaItem *item, NRRectL const *area bool outline = (item->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); bool filter = (item->arena->rendermode != Inkscape::RENDERMODE_OUTLINE && item->arena->rendermode != Inkscape::RENDERMODE_NO_FILTERS); - bool print_colors = (item->arena->colorrendermode == Inkscape::COLORRENDERMODE_PRINT_COLORS_PREVIEW); nr_return_val_if_fail (item != NULL, NR_ARENA_ITEM_STATE_INVALID); nr_return_val_if_fail (NR_IS_ARENA_ITEM (item), NR_ARENA_ITEM_STATE_INVALID); nr_return_val_if_fail (item->state & NR_ARENA_ITEM_STATE_BBOX, item->state); + if (!ct) return item->state; #ifdef NR_ARENA_ITEM_VERBOSE g_message ("Invoke render %p on %p: %d %d - %d %d, %d %d - %d %d", item, pb, @@ -334,6 +349,8 @@ nr_arena_item_invoke_render (cairo_t *ct, NRArenaItem *item, NRRectL const *area if (!item->visible) return item->state | NR_ARENA_ITEM_STATE_RENDER; + // carea is the bounding box for intermediate rendering. + // NOTE: carea might be larger than area, because of filter effects. NRRectL carea; nr_rect_l_intersect (&carea, area, &item->drawbox); if (nr_rect_l_test_empty(carea)) @@ -344,272 +361,152 @@ nr_arena_item_invoke_render (cairo_t *ct, NRArenaItem *item, NRRectL const *area } if (outline) { - // No caching in outline mode for now; investigate if it really gives any advantage with cairo. - // Also no attempts to clip anything; just render everything: item, clip, mask - // First, render the object itself - unsigned int state = NR_ARENA_ITEM_VIRTUAL (item, render) (ct, item, &carea, pb, flags); - if (state & NR_ARENA_ITEM_STATE_INVALID) { - /* Clean up and return error */ - item->state |= NR_ARENA_ITEM_STATE_INVALID; - return item->state; - } - - // render clip and mask, if any - guint32 saved_rgba = item->arena->outlinecolor; // save current outline color - // render clippath as an object, using a different color - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - if (item->clip) { - item->arena->outlinecolor = prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff); // green clips - NR_ARENA_ITEM_VIRTUAL (item->clip, render) (ct, item->clip, &carea, pb, flags); - } - // render mask as an object, using a different color - if (item->mask) { - item->arena->outlinecolor = prefs->getInt("/options/wireframecolors/masks", 0x0000ffff); // blue masks - NR_ARENA_ITEM_VIRTUAL (item->mask, render) (ct, item->mask, &carea, pb, flags); - } - item->arena->outlinecolor = saved_rgba; // restore outline color + // No caching in outline mode for now; investigate if it really gives any advantage with cairo. + // Also no attempts to clip anything; just render everything: item, clip, mask + // First, render the object itself + unsigned int state = NR_ARENA_ITEM_VIRTUAL (item, render) (ct, item, &carea, pb, flags); + if (state & NR_ARENA_ITEM_STATE_INVALID) { + /* Clean up and return error */ + item->state |= NR_ARENA_ITEM_STATE_INVALID; + return item->state; + } - return item->state | NR_ARENA_ITEM_STATE_RENDER; - } + // render clip and mask, if any + guint32 saved_rgba = item->arena->outlinecolor; // save current outline color + // render clippath as an object, using a different color + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + if (item->clip) { + item->arena->outlinecolor = prefs->getInt("/options/wireframecolors/clips", 0x00ff00ff); // green clips + NR_ARENA_ITEM_VIRTUAL (item->clip, render) (ct, item->clip, &carea, pb, flags); + } + // render mask as an object, using a different color + if (item->mask) { + item->arena->outlinecolor = prefs->getInt("/options/wireframecolors/masks", 0x0000ffff); // blue masks + NR_ARENA_ITEM_VIRTUAL (item->mask, render) (ct, item->mask, &carea, pb, flags); + } + item->arena->outlinecolor = saved_rgba; // restore outline color - NRPixBlock cpb; - if (item->px) { - /* Has cache pixblock, render this and return */ - nr_pixblock_setup_extern (&cpb, NR_PIXBLOCK_MODE_R8G8B8A8P, - /* fixme: This probably cannot overflow, because we render only if visible */ - /* fixme: and pixel cache is there only for small items */ - /* fixme: But this still needs extra check (Lauris) */ - item->drawbox.x0, item->drawbox.y0, - item->drawbox.x1, item->drawbox.y1, - item->px, - 4 * (item->drawbox.x1 - item->drawbox.x0), FALSE, - FALSE); - nr_blit_pixblock_pixblock (pb, &cpb); - nr_pixblock_release (&cpb); - pb->empty = FALSE; return item->state | NR_ARENA_ITEM_STATE_RENDER; } - NRPixBlock *dpb = pb; - - /* Setup cache if we can */ - if ((!(flags & NR_ARENA_ITEM_RENDER_NO_CACHE)) && - (carea.x0 <= item->drawbox.x0) && (carea.y0 <= item->drawbox.y0) && - (carea.x1 >= item->drawbox.x1) && (carea.y1 >= item->drawbox.y1) && - (((item->drawbox.x1 - item->drawbox.x0) * (item->drawbox.y1 - - item->drawbox.y0)) <= 4096)) { - // Item drawbox is fully in renderable area and size is acceptable - carea.x0 = item->drawbox.x0; - carea.y0 = item->drawbox.y0; - carea.x1 = item->drawbox.x1; - carea.y1 = item->drawbox.y1; - item->px = - new (GC::ATOMIC) unsigned char[4 * (carea.x1 - carea.x0) * - (carea.y1 - carea.y0)]; - nr_pixblock_setup_extern (&cpb, NR_PIXBLOCK_MODE_R8G8B8A8P, carea.x0, - carea.y0, carea.x1, carea.y1, item->px, - 4 * (carea.x1 - carea.x0), TRUE, TRUE); - cpb.visible_area = pb->visible_area; - dpb = &cpb; - // Set nocache flag for downstream rendering - flags |= NR_ARENA_ITEM_RENDER_NO_CACHE; - } + using namespace Inkscape; - /* Determine, whether we need temporary buffer */ - if (item->clip || item->mask - || ((item->opacity != 255) && !item->render_opacity) - || (item->filter && filter) || item->background_new) { - - /* Setup and render item buffer */ - NRPixBlock ipb; - nr_pixblock_setup_fast (&ipb, NR_PIXBLOCK_MODE_R8G8B8A8P, - carea.x0, carea.y0, carea.x1, carea.y1, - TRUE); - - // if memory allocation failed, abort render - if (ipb.size != NR_PIXBLOCK_SIZE_TINY && ipb.data.px == NULL) { - nr_pixblock_release (&ipb); - return (item->state); - } + // clipping and masks + unsigned int state; - /* If background access is used, save the pixblock address. - * This address is set to NULL at the end of this block */ - if (item->background_new) { - item->background_pb = &ipb; - } + cairo_t *this_ct = ct; + NRRectL *this_area = const_cast<NRRectL*>(area); - ipb.visible_area = pb->visible_area; - if (item->filter && filter) { - item->filter->area_enlarge (ipb.visible_area, item); - } + bool needs_intermediate_rendering = false; + bool &nir = needs_intermediate_rendering; + bool needs_opacity = (item->opacity != 255 && !item->render_opacity); + + // this item needs an intermediate rendering if: + nir |= (item->mask != NULL); // 1. it has a mask + nir |= (item->filter != NULL && filter); // 2. it has a filter + nir |= needs_opacity; // 3. it is non-opaque + + double opacity = static_cast<double>(item->opacity) / 255.0; + + if (needs_intermediate_rendering) { + cairo_surface_t *intermediate = cairo_surface_create_similar( + cairo_get_target(ct), CAIRO_CONTENT_COLOR_ALPHA, + carea.x1 - carea.x0, carea.y1 - carea.y0); + this_ct = cairo_create(intermediate); + cairo_translate(this_ct, -carea.x0, -carea.y0); + this_area = &carea; + cairo_surface_destroy(intermediate); // the surface will be held in memory by this_ct + } else { + cairo_reference(this_ct); + } + + // The pipeline needs to be different for filters. + // First we render the item into an intermediate surface. Then the filter rotates + // the surface to user coordinates (if necessary) and runs the rendering. + // Once that's done we retrieve the result, rotating it back to screen coords. + // Clipping and masking happens after the filter result is ready. + if (item->filter && filter) { + } + + Cairo::Context cct(this_ct, true); + Cairo::Context base_ct(ct); + Cairo::RefPtr<Cairo::Pattern> mask; + CairoSave clipsave(ct); // RAII for save / restore + CairoGroup maskgroup(this_ct); // RAII for push_group / pop_group + CairoGroup drawgroup(this_ct); + CairoGroup maskopacitygroup(this_ct); - unsigned int state = NR_ARENA_ITEM_VIRTUAL (item, render) (ct, item, &carea, &ipb, flags); + // always clip the base context, not the one on the intermediate surface + // this is because filters must be done before clipping + if (item->clip) { + clipsave.save(); + state = nr_arena_item_invoke_clip(ct, item->clip, const_cast<NRRectL*>(area)); if (state & NR_ARENA_ITEM_STATE_INVALID) { - /* Clean up and return error */ - nr_pixblock_release (&ipb); - if (dpb != pb) - nr_pixblock_release (dpb); item->state |= NR_ARENA_ITEM_STATE_INVALID; return item->state; } - ipb.empty = FALSE; - - /* Run filtering, if a filter is set for this object */ - if (item->filter && filter) { - item->filter->render (item, &ipb); - } + base_ct.clip(); + } - if (item->clip || item->mask) { - /* Setup mask pixblock */ - NRPixBlock mpb; - nr_pixblock_setup_fast (&mpb, NR_PIXBLOCK_MODE_A8, carea.x0, - carea.y0, carea.x1, carea.y1, TRUE); - - if (mpb.data.px != NULL) { // if memory allocation was successful - - mpb.visible_area = pb->visible_area; - /* Do clip if needed */ - if (item->clip) { - state = nr_arena_item_invoke_clip (item->clip, &carea, &mpb); - if (state & NR_ARENA_ITEM_STATE_INVALID) { - /* Clean up and return error */ - nr_pixblock_release (&mpb); - nr_pixblock_release (&ipb); - if (dpb != pb) - nr_pixblock_release (dpb); - item->state |= NR_ARENA_ITEM_STATE_INVALID; - return item->state; - } - mpb.empty = FALSE; - } - /* Do mask if needed */ - if (item->mask) { - NRPixBlock tpb; - /* Set up yet another temporary pixblock */ - nr_pixblock_setup_fast (&tpb, NR_PIXBLOCK_MODE_R8G8B8A8N, - carea.x0, carea.y0, carea.x1, - carea.y1, TRUE); - - if (tpb.data.px != NULL) { // if memory allocation was successful - - tpb.visible_area = pb->visible_area; - unsigned int state = NR_ARENA_ITEM_VIRTUAL (item->mask, render) (ct, item->mask, &carea, &tpb, flags); - if (state & NR_ARENA_ITEM_STATE_INVALID) { - /* Clean up and return error */ - nr_pixblock_release (&tpb); - nr_pixblock_release (&mpb); - nr_pixblock_release (&ipb); - if (dpb != pb) - nr_pixblock_release (dpb); - item->state |= NR_ARENA_ITEM_STATE_INVALID; - return item->state; - } - /* Composite with clip */ - if (item->clip) { - int x, y; - for (y = carea.y0; y < carea.y1; y++) { - unsigned char *s, *d; - s = NR_PIXBLOCK_PX (&tpb) + (y - - carea.y0) * tpb.rs; - d = NR_PIXBLOCK_PX (&mpb) + (y - - carea.y0) * mpb.rs; - for (x = carea.x0; x < carea.x1; x++) { - // See below for calculation - unsigned int m; - m = NR_PREMUL_112 ( (NR_PREMUL_112 (s[0], 54) + - NR_PREMUL_112 (s[1], 183) + - NR_PREMUL_112 (s[2], 19) ) >> 8, s[3]); - d[0] = FAST_DIV_ROUND < 255 * 255 > ( NR_PREMUL_123 (d[0], m)); - s += 4; - d += 1; - } - } - } else { - int x, y; - for (y = carea.y0; y < carea.y1; y++) { - unsigned char *s, *d; - s = NR_PIXBLOCK_PX (&tpb) + (y - - carea.y0) * tpb.rs; - d = NR_PIXBLOCK_PX (&mpb) + (y - - carea.y0) * mpb.rs; - for (x = carea.x0; x < carea.x1; x++) { - unsigned int m; - // m = NR_PREMUL_112 (s[0] + s[1] + s[2], s[3]); - // d[0] = FAST_DIV_ROUND < 3 * 255 > (m); - // Must use luminance to alpha from feColorMatrix. - // This is an approximation, optimized(?) for speed. - // 0.2125 * 256 = 54.4000 - // 0.7154 * 256 = 183.1424 - // 0.0721 * 256 = 18.4576 - m = NR_PREMUL_112 ( (NR_PREMUL_112 (s[0], 54) + - NR_PREMUL_112 (s[1], 183) + - NR_PREMUL_112 (s[2], 19) ) >> 8, s[3]); - d[0] = FAST_DIV_ROUND < 255 > (m); - s += 4; - d += 1; - } - } - mpb.empty = FALSE; - } - } - nr_pixblock_release (&tpb); - } - /* Multiply with opacity if needed */ - if ((item->opacity != 255) && !item->render_opacity - ) { - int x, y; - unsigned int a; - a = item->opacity; - for (y = carea.y0; y < carea.y1; y++) { - unsigned char *d; - d = NR_PIXBLOCK_PX (&mpb) + (y - carea.y0) * mpb.rs; - for (x = carea.x0; x < carea.x1; x++) { - d[0] = NR_PREMUL_111 (d[0], a); - d += 1; - } - } - } - /* Compose rendering pixblock int destination */ - nr_blit_pixblock_pixblock_mask (dpb, &ipb, &mpb); - } - nr_pixblock_release (&mpb); - } else { - if (item->render_opacity) { // opacity was already rendered in, just copy to dpb here - nr_blit_pixblock_pixblock(dpb, &ipb); - } else { // copy while multiplying by opacity - nr_blit_pixblock_pixblock_alpha (dpb, &ipb, item->opacity); - } + // render mask on the intermediate context and store it + if (item->mask) { + maskgroup.push_with_content(CAIRO_CONTENT_COLOR_ALPHA); + // handle opacity of a masked object by composing it with the mask + if (needs_opacity) { + maskopacitygroup.push(); } - nr_pixblock_release (&ipb); - dpb->empty = FALSE; - /* This pointer wouldn't be valid outside this block, so clear it */ - item->background_pb = NULL; - } else { - /* Just render */ - unsigned int state = NR_ARENA_ITEM_VIRTUAL (item, render) (ct, item, &carea, dpb, flags); + state = NR_ARENA_ITEM_VIRTUAL (item->mask, render) (this_ct, item->mask, this_area, pb, flags); if (state & NR_ARENA_ITEM_STATE_INVALID) { - /* Clean up and return error */ - if (dpb != pb) - nr_pixblock_release (dpb); item->state |= NR_ARENA_ITEM_STATE_INVALID; return item->state; } - dpb->empty = FALSE; + if (needs_opacity) { + maskopacitygroup.pop_to_source(); + cct.paint_with_alpha(opacity); + } + mask = maskgroup.popmm(); + // convert luminance to alpha + cairo_pattern_t *p = mask->cobj(); + cairo_surface_t *s; + cairo_pattern_get_surface(p, &s); + ink_cairo_surface_filter(s, s, MaskLuminanceToAlpha()); } - if (dpb != pb) { - /* Have to blit from cache */ - nr_blit_pixblock_pixblock (pb, dpb); - nr_pixblock_release (dpb); - pb->empty = FALSE; - item->state |= NR_ARENA_ITEM_STATE_IMAGE; + // render the object (possibly to the intermediate surface) + state = NR_ARENA_ITEM_VIRTUAL (item, render) (this_ct, item, this_area, pb, flags); + if (state & NR_ARENA_ITEM_STATE_INVALID) { + /* Clean up and return error */ + item->state |= NR_ARENA_ITEM_STATE_INVALID; + return item->state; + } + + // apply filter + if (item->filter && filter) { + item->filter->render(item, ct, area, this_ct, &carea); + } + + if (needs_intermediate_rendering) { + cairo_surface_t *intermediate = cairo_get_target(this_ct); + cairo_set_source_surface(ct, intermediate, carea.x0, carea.y0); + if (mask) { + cairo_mask(ct, mask->cobj()); + // opacity of masked objects is handled by premultiplying the mask + } else { + // opacity of non-masked objects must be rendered explicitly + if (needs_opacity) { + cairo_paint_with_alpha(ct, opacity); + } else { + cairo_paint(ct); + } + } + cairo_set_source_rgba(ct,0,0,0,0); } return item->state | NR_ARENA_ITEM_STATE_RENDER; } unsigned int -nr_arena_item_invoke_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb) +nr_arena_item_invoke_clip (cairo_t *ct, NRArenaItem *item, NRRectL *area) { nr_return_val_if_fail (item != NULL, NR_ARENA_ITEM_STATE_INVALID); nr_return_val_if_fail (NR_IS_ARENA_ITEM (item), @@ -618,12 +515,12 @@ nr_arena_item_invoke_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb) * NR_ARENA_ITEM_STATE_CLIP (and showed a warning on the console); * anyone know why we stopped doing so? */ - nr_return_val_if_fail ((pb->area.x1 - pb->area.x0) >= + /*nr_return_val_if_fail ((pb->area.x1 - pb->area.x0) >= (area->x1 - area->x0), NR_ARENA_ITEM_STATE_INVALID); nr_return_val_if_fail ((pb->area.y1 - pb->area.y0) >= (area->y1 - area->y0), - NR_ARENA_ITEM_STATE_INVALID); + NR_ARENA_ITEM_STATE_INVALID);*/ #ifdef NR_ARENA_ITEM_VERBOSE printf ("Invoke clip by %p: %d %d - %d %d, item bbox %d %d - %d %d\n", @@ -635,7 +532,7 @@ nr_arena_item_invoke_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb) /* Need render that item */ if (((NRArenaItemClass *) NR_OBJECT_GET_CLASS (item))->clip) { return ((NRArenaItemClass *) NR_OBJECT_GET_CLASS (item))-> - clip (item, area, pb); + clip (ct, item, area); } } @@ -663,7 +560,8 @@ nr_arena_item_invoke_pick (NRArenaItem *item, Geom::Point p, double delta, if (((x + delta) >= item->bbox.x0) && ((x - delta) < item->bbox.x1) && - ((y + delta) >= item->bbox.y0) && ((y - delta) < item->bbox.y1)) { + ((y + delta) >= item->bbox.y0) && ((y - delta) < item->bbox.y1)) + { if (((NRArenaItemClass *) NR_OBJECT_GET_CLASS (item))->pick) return ((NRArenaItemClass *) NR_OBJECT_GET_CLASS (item))-> pick (item, p, delta, sticky); @@ -872,13 +770,7 @@ nr_arena_item_set_item_bbox (NRArenaItem *item, Geom::OptRect &bbox) NRPixBlock * nr_arena_item_get_background (NRArenaItem const *item) { - if (item->background_new) { - return item->background_pb; - } else if (item->parent) { - return nr_arena_item_get_background (item->parent); - } else { - return NULL; - } + return NULL; } /* Helpers */ diff --git a/src/display/nr-arena-item.h b/src/display/nr-arena-item.h index ff9965b85..0fc4cbe48 100644 --- a/src/display/nr-arena-item.h +++ b/src/display/nr-arena-item.h @@ -1,6 +1,3 @@ -#ifndef __NR_ARENA_ITEM_H__ -#define __NR_ARENA_ITEM_H__ - /* * RGBA display list system for inkscape * @@ -13,6 +10,21 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifndef SEEN_DISPLAY_NR_ARENA_ITEM_H +#define SEEN_DISPLAY_NR_ARENA_ITEM_H + +#include <cairo.h> +#include <2geom/affine.h> +#include "libnr/nr-rect-l.h" +#include "libnr/nr-object.h" +#include "gc-soft-ptr.h" +#include "nr-arena-forward.h" + +namespace Inkscape { +namespace Filters { +class Filter; +} } + #define NR_TYPE_ARENA_ITEM (nr_arena_item_get_type ()) #define NR_ARENA_ITEM(o) (NR_CHECK_INSTANCE_CAST ((o), NR_TYPE_ARENA_ITEM, NRArenaItem)) #define NR_IS_ARENA_ITEM(o) (NR_CHECK_INSTANCE_TYPE ((o), NR_TYPE_ARENA_ITEM)) @@ -52,15 +64,6 @@ #define NR_ARENA_ITEM_RENDER_NO_CACHE (1 << 0) -#include <2geom/affine.h> -#include <libnr/nr-rect-l.h> -#include <libnr/nr-pixblock.h> -#include <libnr/nr-object.h> -#include "gc-soft-ptr.h" -#include "nr-arena-forward.h" -#include "display/nr-filter.h" -#include <cairo.h> - struct NRGC { NRGC(NRGC const *p) : parent(p) {} NRGC const *parent; @@ -84,35 +87,22 @@ struct NRArenaItem : public NRObject { /* Opacity itself */ unsigned int opacity : 8; - /* Key for secondary rendering */ - unsigned int key; - - /* BBox in grid coordinates */ - NRRectL bbox; - /* Redraw area in grid coordinates = bbox filter-enlarged and clipped/masked */ - NRRectL drawbox; - /* BBox in item coordinates - this should be a bounding box as - * specified in SVG standard. Required by filters. */ - Geom::OptRect item_bbox; - /* Our affine */ - Geom::Affine *transform; - /* Clip item */ - NRArenaItem *clip; - /* Mask item */ - NRArenaItem *mask; - /* Filter to be applied after rendering this object, NULL if none */ - Inkscape::Filters::Filter *filter; - /* Rendered buffer */ - unsigned char *px; - - /* Single data member */ - void *data; - - /* Current Transformation Matrix */ - Geom::Affine ctm; - - /* These hold background buffer state for filter rendering */ - NRPixBlock *background_pb; + unsigned int key; ///< Some SPItems can have more than one NRArenaItem, + ///this value is a hack used to distinguish between them + + NRRectL bbox; ///< Bounding box in pixel grid coordinates; (0,0) is at page origin + NRRectL drawbox; ///< Bounding box enlarged by filters, shrinked by clips and masks + Geom::OptRect item_bbox; ///< Bounding box in item coordinates, required by filters + Geom::Affine *transform; ///< Incremental transform of this item, as given by the transform= attribute + Geom::Affine ctm; ///< Total transform from pixel grid to item coords + NRArenaItem *clip; ///< Clipping path + NRArenaItem *mask; ///< Mask + Inkscape::Filters::Filter *filter; ///< Filter + unsigned char *px; ///< Render cache; unused + + void *data; ///< Anonymous data member - this is used to associate SPItems with arena items + + NRPixBlock *background_pb; ///< Background for filters; unused bool background_new; void init(NRArena *arena) { @@ -129,7 +119,7 @@ struct NRArenaItemClass : public NRObjectClass { unsigned int (* update) (NRArenaItem *item, NRRectL *area, NRGC *gc, unsigned int state, unsigned int reset); unsigned int (* render) (cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int flags); - unsigned int (* clip) (NRArenaItem *item, NRRectL *area, NRPixBlock *pb); + unsigned int (* clip) (cairo_t *ct, NRArenaItem *item, NRRectL *area); NRArenaItem * (* pick) (NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); }; @@ -159,7 +149,7 @@ unsigned int nr_arena_item_invoke_update (NRArenaItem *item, NRRectL *area, NRGC unsigned int nr_arena_item_invoke_render(cairo_t *ct, NRArenaItem *item, NRRectL const *area, NRPixBlock *pb, unsigned int flags); -unsigned int nr_arena_item_invoke_clip (NRArenaItem *item, NRRectL *area, NRPixBlock *pb); +unsigned int nr_arena_item_invoke_clip (cairo_t *ct, NRArenaItem *item, NRRectL *area); NRArenaItem *nr_arena_item_invoke_pick (NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); void nr_arena_item_request_update (NRArenaItem *item, unsigned int reset, unsigned int propagate); @@ -194,8 +184,7 @@ NRArenaItem *nr_arena_item_detach (NRArenaItem *parent, NRArenaItem *child); #define NR_ARENA_ITEM_SET_KEY(i,k) (((NRArenaItem *) (i))->key = (k)) #define NR_ARENA_ITEM_GET_KEY(i) (((NRArenaItem *) (i))->key) - -#endif /* !__NR_ARENA_ITEM_H__ */ +#endif /* !SEEN_DISPLAY_NR_ARENA_ITEM_H */ /* Local Variables: diff --git a/src/display/nr-arena-shape.cpp b/src/display/nr-arena-shape.cpp index 33a218e99..f278413b2 100644 --- a/src/display/nr-arena-shape.cpp +++ b/src/display/nr-arena-shape.cpp @@ -10,41 +10,30 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include <cairo.h> #include <glib.h> #include <fenv.h> #include <typeinfo> -#include <cairo.h> +#include <2geom/curves.h> +#include <2geom/pathvector.h> #include <2geom/svg-path.h> #include <2geom/svg-path-parser.h> -#include <2geom/pathvector.h> -#include <2geom/curves.h> -#include "display/sp-canvas.h" +#include "display/cairo-utils.h" #include "display/canvas-arena.h" +#include "display/curve.h" #include "display/nr-arena.h" #include "display/nr-arena-shape.h" -#include "display/curve.h" -#include "display/grayscale.h" -#include "libnr/nr-pixops.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-convert2geom.h" -#include "livarot/Path.h" -#include "livarot/float-line.h" -#include "livarot/int-line.h" -#include "style.h" -#include "inkscape-cairo.h" -#include "helper/geom.h" +#include "display/nr-filter.h" #include "helper/geom-curves.h" +#include "helper/geom.h" +#include "libnr/nr-convert2geom.h" +#include "preferences.h" #include "sp-filter.h" #include "sp-filter-reference.h" -#include "display/nr-filter.h" -#include "preferences.h" - +#include "style.h" #include "svg/svg.h" -//int showRuns=0; -void nr_pixblock_render_shape_mask_or(NRPixBlock &m,Shape* theS); - static void nr_arena_shape_class_init(NRArenaShapeClass *klass); static void nr_arena_shape_init(NRArenaShape *shape); static void nr_arena_shape_finalize(NRObject *object); @@ -56,7 +45,7 @@ static void nr_arena_shape_set_child_position(NRArenaItem *item, NRArenaItem *ch static guint nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, guint reset); static unsigned int nr_arena_shape_render(cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock *pb, unsigned int flags); -static guint nr_arena_shape_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb); +static guint nr_arena_shape_clip(cairo_t *ct, NRArenaItem *item, NRRectL *area); static NRArenaItem *nr_arena_shape_pick(NRArenaItem *item, Geom::Point p, double delta, unsigned int sticky); static NRArenaItemClass *shape_parent_class; @@ -111,26 +100,13 @@ nr_arena_shape_init(NRArenaShape *shape) shape->style = NULL; shape->paintbox.x0 = shape->paintbox.y0 = 0.0F; shape->paintbox.x1 = shape->paintbox.y1 = 256.0F; - - shape->ctm.setIdentity(); - shape->fill_painter = NULL; - shape->stroke_painter = NULL; - shape->cached_fill = NULL; - shape->cached_stroke = NULL; - shape->cached_fpartialy = false; - shape->cached_spartialy = false; - shape->fill_shp = NULL; - shape->stroke_shp = NULL; - shape->delayed_shp = false; + shape->path = NULL; shape->approx_bbox.x0 = shape->approx_bbox.y0 = 0; shape->approx_bbox.x1 = shape->approx_bbox.y1 = 0; - shape->cached_fctm.setIdentity(); - shape->cached_sctm.setIdentity(); shape->markers = NULL; - shape->last_pick = NULL; shape->repick_after = 0; } @@ -140,15 +116,10 @@ nr_arena_shape_finalize(NRObject *object) { NRArenaShape *shape = (NRArenaShape *) object; - if (shape->fill_shp) delete shape->fill_shp; - if (shape->stroke_shp) delete shape->stroke_shp; - if (shape->cached_fill) delete shape->cached_fill; - if (shape->cached_stroke) delete shape->cached_stroke; - if (shape->fill_painter) sp_painter_free(shape->fill_painter); - if (shape->stroke_painter) sp_painter_free(shape->stroke_painter); - + if (shape->path) cairo_path_destroy(shape->path); if (shape->style) sp_style_unref(shape->style); if (shape->curve) shape->curve->unref(); + shape->last_pick = NULL; ((NRObjectClass *) shape_parent_class)->finalize(object); } @@ -227,10 +198,6 @@ nr_arena_shape_set_child_position(NRArenaItem *item, NRArenaItem *child, NRArena nr_arena_item_request_render(child); } -void nr_arena_shape_update_stroke(NRArenaShape *shape, NRGC* gc, NRRectL *area); -void nr_arena_shape_update_fill(NRArenaShape *shape, NRGC *gc, NRRectL *area, bool force_shape = false); -void nr_arena_shape_add_bboxes(NRArenaShape* shape, Geom::OptRect &bbox); - /** * Updates the arena shape 'item' and all of its children, including the markers. */ @@ -243,6 +210,7 @@ nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, g unsigned int beststate = NR_ARENA_ITEM_STATE_ALL; + // update markers unsigned int newstate; for (NRArenaItem *child = shape->markers; child != NULL; child = child->next) { newstate = nr_arena_item_invoke_update(child, area, gc, state, reset); @@ -251,7 +219,6 @@ nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, g if (!(state & NR_ARENA_ITEM_STATE_RENDER)) { /* We do not have to create rendering structures */ - shape->ctm = gc->transform; if (state & NR_ARENA_ITEM_STATE_BBOX) { if (shape->curve) { boundingbox = bounds_exact_transformed(shape->curve->get_pathvector(), gc->transform); @@ -274,29 +241,36 @@ nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, g } shape->delayed_shp=true; - shape->ctm = gc->transform; boundingbox = Geom::OptRect(); bool outline = (NR_ARENA_ITEM(shape)->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); + // clear Cairo data to force update + shape->nrstyle.update(); + if (shape->path) { + cairo_path_destroy(shape->path); + shape->path = NULL; + } + if (shape->curve) { boundingbox = bounds_exact_transformed(shape->curve->get_pathvector(), gc->transform); - if (boundingbox && (shape->_stroke.paint.type() != NRArenaShape::Paint::NONE || outline)) { + if (boundingbox && (shape->nrstyle.stroke.type != NRStyle::PAINT_NONE || outline)) { float width, scale; scale = gc->transform.descrim(); - width = MAX(0.125, shape->_stroke.width * scale); - if ( fabs(shape->_stroke.width * scale) > 0.01 ) { // sinon c'est 0=oon veut pas de bord + width = MAX(0.125, shape->nrstyle.stroke_width * scale); + if ( fabs(shape->nrstyle.stroke_width * scale) > 0.01 ) { // FIXME: this is always true boundingbox->expandBy(width); } // those pesky miters, now - float miterMax=width*shape->_stroke.mitre_limit; + float miterMax = width * shape->nrstyle.miter_limit; if ( miterMax > 0.01 ) { - // grunt mode. we should compute the various miters instead (one for each point on the curve) + // grunt mode. we should compute the various miters instead + // (one for each point on the curve) boundingbox->expandBy(miterMax); } } - } + } /// \todo just write item->bbox = boundingbox if (boundingbox) { @@ -309,88 +283,17 @@ nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, g } if ( area && nr_rect_l_test_intersect_ptr(area, &shape->approx_bbox) ) shape->delayed_shp=false; - /* Release state data */ - if (shape->fill_shp) { - delete shape->fill_shp; - shape->fill_shp = NULL; - } - if (shape->stroke_shp) { - delete shape->stroke_shp; - shape->stroke_shp = NULL; - } - if (shape->fill_painter) { - sp_painter_free(shape->fill_painter); - shape->fill_painter = NULL; - } - if (shape->stroke_painter) { - sp_painter_free(shape->stroke_painter); - shape->stroke_painter = NULL; - } + // TODO: compute a better bounding box that respects miters + item->bbox = shape->approx_bbox; if (!shape->curve || !shape->style || shape->curve->is_empty() || - (( shape->_fill.paint.type() == NRArenaShape::Paint::NONE ) && - ( shape->_stroke.paint.type() == NRArenaShape::Paint::NONE && !outline) )) + (( shape->nrstyle.fill.type != NRStyle::PAINT_NONE ) && + ( shape->nrstyle.stroke.type != NRStyle::PAINT_NONE && !outline) )) { - item->bbox = shape->approx_bbox; - return NR_ARENA_ITEM_STATE_ALL; - } - - /* Build state data */ - if ( shape->delayed_shp ) { - item->bbox=shape->approx_bbox; - } else { - nr_arena_shape_update_stroke(shape, gc, area); - nr_arena_shape_update_fill(shape, gc, area); - - boundingbox = Geom::OptRect(); - nr_arena_shape_add_bboxes(shape, boundingbox); - - /// \todo just write shape->approx_bbox = boundingbox - if (boundingbox) { - shape->approx_bbox.x0 = static_cast<NR::ICoord>(floor((*boundingbox)[0][0])); - shape->approx_bbox.y0 = static_cast<NR::ICoord>(floor((*boundingbox)[1][0])); - shape->approx_bbox.x1 = static_cast<NR::ICoord>(ceil ((*boundingbox)[0][1])); - shape->approx_bbox.y1 = static_cast<NR::ICoord>(ceil ((*boundingbox)[1][1])); - } else { - shape->approx_bbox = NR_RECT_L_EMPTY; - } - } - - if (!boundingbox) + //item->bbox = shape->approx_bbox; return NR_ARENA_ITEM_STATE_ALL; - - /// \todo just write item->bbox = boundingbox - item->bbox.x0 = static_cast<NR::ICoord>(floor((*boundingbox)[0][0])); - item->bbox.y0 = static_cast<NR::ICoord>(floor((*boundingbox)[1][0])); - item->bbox.x1 = static_cast<NR::ICoord>(ceil ((*boundingbox)[0][1])); - item->bbox.y1 = static_cast<NR::ICoord>(ceil ((*boundingbox)[1][1])); - - item->render_opacity = TRUE; - if ( shape->_fill.paint.type() == NRArenaShape::Paint::SERVER ) { - if (gc && gc->parent) { - shape->fill_painter = sp_paint_server_painter_new(shape->_fill.paint.server(), - gc->transform, gc->parent->transform, - &shape->paintbox); - } - item->render_opacity = FALSE; - } - if ( shape->_stroke.paint.type() == NRArenaShape::Paint::SERVER ) { - if (gc && gc->parent) { - shape->stroke_painter = sp_paint_server_painter_new(shape->_stroke.paint.server(), - gc->transform, gc->parent->transform, - &shape->paintbox); - } - item->render_opacity = FALSE; - } - if ( (shape->_fill.paint.type() != NRArenaShape::Paint::NONE && - shape->_stroke.paint.type() != NRArenaShape::Paint::NONE) - || (shape->markers) - ) - { - // don't merge item opacity with paint opacity if there is a stroke on the fill, or markers on stroke - item->render_opacity = FALSE; } if (beststate & NR_ARENA_ITEM_STATE_BBOX) { @@ -402,328 +305,9 @@ nr_arena_shape_update(NRArenaItem *item, NRRectL *area, NRGC *gc, guint state, g return NR_ARENA_ITEM_STATE_ALL; } -int matrix_is_isometry(Geom::Affine p) { - Geom::Affine tp; - // transposition - tp[0]=p[0]; - tp[1]=p[2]; - tp[2]=p[1]; - tp[3]=p[3]; - for (int i = 4; i < 6; i++) // shut valgrind up :) - tp[i] = p[i] = 0; - Geom::Affine isom = tp*p; // A^T * A = adjunct? - // Is the adjunct nearly an identity function? - if (isom.isTranslation(0.01)) { - // the transformation is an isometry -> no need to recompute - // the uncrossed polygon - if ( p.det() < 0 ) - return -1; - else - return 1; - } - return 0; -} - -static bool is_inner_area(NRRectL const &outer, NRRectL const &inner) { - return (outer.x0 <= inner.x0 && outer.y0 <= inner.y0 && outer.x1 >= inner.x1 && outer.y1 >= inner.y1); -} - -/* returns true if the pathvector has a region that needs fill. - * is for optimizing purposes, so should be fast and can falsely return true. - * CANNOT falsely return false. */ -static bool has_inner_area(Geom::PathVector const & pv) { - // return false for the cases where there is surely no region to be filled - if (pv.empty()) - return false; - - if ( (pv.size() == 1) && (pv.front().size() <= 1) ) { - // vector has only one path with only one segment, see if that's a non-curve segment: that would mean no internal region - if ( is_straight_curve(pv.front().front()) ) - { - return false; - } - } - - return true; //too costly to see if it has region to be filled, so return true. -} - -/** force_shape is used for clipping paths, when we need the shape for clipping even if it's not filled */ -void -nr_arena_shape_update_fill(NRArenaShape *shape, NRGC *gc, NRRectL *area, bool force_shape) -{ - if ((shape->_fill.paint.type() != NRArenaShape::Paint::NONE || force_shape) && - has_inner_area(shape->curve->get_pathvector()) ) { - - Geom::Affine cached_to_new = Geom::identity(); - int isometry = 0; - if ( shape->cached_fill ) { - if (shape->cached_fctm == gc->transform) { - isometry = 2; // identity - } else { - cached_to_new = shape->cached_fctm.inverse() * gc->transform; - isometry = matrix_is_isometry(cached_to_new); - } - if (0 != isometry && !is_inner_area(shape->cached_farea, *area)) - isometry = 0; - } - if ( isometry == 0 ) { - if ( shape->cached_fill == NULL ) shape->cached_fill=new Shape; - shape->cached_fill->Reset(); - - Path* thePath=new Path; - Shape* theShape=new Shape; - { - Geom::Affine tempMat(gc->transform); - thePath->LoadPathVector(shape->curve->get_pathvector(), tempMat, true); - } - - if (is_inner_area(*area, NR_ARENA_ITEM(shape)->bbox)) { - thePath->Convert(1.0); - shape->cached_fpartialy = false; - } else { - thePath->Convert(area, 1.0); - shape->cached_fpartialy = true; - } - - thePath->Fill(theShape, 0); - - if ( shape->_fill.rule == NRArenaShape::EVEN_ODD ) { - shape->cached_fill->ConvertToShape(theShape, fill_oddEven); - // alternatively, this speeds up rendering of oddeven shapes but disables AA :( - //shape->cached_fill->Copy(theShape); - } else { - shape->cached_fill->ConvertToShape(theShape, fill_nonZero); - } - shape->cached_fctm=gc->transform; - shape->cached_farea = *area; - delete theShape; - delete thePath; - if ( shape->fill_shp == NULL ) - shape->fill_shp = new Shape; - - shape->fill_shp->Copy(shape->cached_fill); - - } else if ( 2 == isometry ) { - if ( shape->fill_shp == NULL ) { - shape->fill_shp = new Shape; - shape->fill_shp->Copy(shape->cached_fill); - } - } else { - - if ( shape->fill_shp == NULL ) - shape->fill_shp = new Shape; - - shape->fill_shp->Reset(shape->cached_fill->numberOfPoints(), - shape->cached_fill->numberOfEdges()); - for (int i = 0; i < shape->cached_fill->numberOfPoints(); i++) - shape->fill_shp->AddPoint(to_2geom(shape->cached_fill->getPoint(i).x) * cached_to_new); - if ( isometry == 1 ) { - for (int i = 0; i < shape->cached_fill->numberOfEdges(); i++) - shape->fill_shp->AddEdge(shape->cached_fill->getEdge(i).st, - shape->cached_fill->getEdge(i).en); - } else if ( isometry == -1 ) { // need to flip poly. - for (int i = 0; i < shape->cached_fill->numberOfEdges(); i++) - shape->fill_shp->AddEdge(shape->cached_fill->getEdge(i).en, - shape->cached_fill->getEdge(i).st); - } - shape->fill_shp->ForceToPolygon(); - shape->fill_shp->needPointsSorting(); - shape->fill_shp->needEdgesSorting(); - } - shape->delayed_shp |= shape->cached_fpartialy; - } -} - -void -nr_arena_shape_update_stroke(NRArenaShape *shape,NRGC* gc, NRRectL *area) -{ - SPStyle* style = shape->style; - - float const scale = gc->transform.descrim(); - - bool outline = (NR_ARENA_ITEM(shape)->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); - - if (outline) { - // cairo does not need the livarot path for rendering - return; - } - - // after switching normal stroke rendering to cairo too, optimize this: lower tolerance, disregard dashes - // (since it will only be used for picking, not for rendering) - - if (outline || - ((shape->_stroke.paint.type() != NRArenaShape::Paint::NONE) && - ( fabs(shape->_stroke.width * scale) > 0.01 ))) { // sinon c'est 0=oon veut pas de bord - - float style_width = MAX(0.125, shape->_stroke.width * scale); - float width; - if (outline) { - width = 0.5; // 1 pixel wide, independent of zoom - } else { - width = style_width; - } - - Geom::Affine cached_to_new = Geom::identity(); - - int isometry = 0; - if ( shape->cached_stroke ) { - if (shape->cached_sctm == gc->transform) { - isometry = 2; // identity - } else { - cached_to_new = shape->cached_sctm.inverse() * gc->transform; - isometry = matrix_is_isometry(cached_to_new); - } - if (0 != isometry && !is_inner_area(shape->cached_sarea, *area)) - isometry = 0; - if (0 != isometry && width != shape->cached_width) { - // if this happens without setting style, we have just switched to outline or back - isometry = 0; - } - } - - if ( isometry == 0 ) { - if ( shape->cached_stroke == NULL ) shape->cached_stroke=new Shape; - shape->cached_stroke->Reset(); - Path* thePath = new Path; - Shape* theShape = new Shape; - { - Geom::Affine tempMat( gc->transform ); - thePath->LoadPathVector(shape->curve->get_pathvector(), tempMat, true); - } - - // add some padding to the rendering area, so clipped path does not go into a render area - NRRectL padded_area = *area; - padded_area.x0 -= (NR::ICoord)width; - padded_area.x1 += (NR::ICoord)width; - padded_area.y0 -= (NR::ICoord)width; - padded_area.y1 += (NR::ICoord)width; - if ((style->stroke_dash.n_dash && !outline) || is_inner_area(padded_area, NR_ARENA_ITEM(shape)->bbox)) { - thePath->Convert((outline) ? 4.0 : 1.0); - shape->cached_spartialy = false; - } - else { - thePath->Convert(&padded_area, (outline) ? 4.0 : 1.0); - shape->cached_spartialy = true; - } - - if (style->stroke_dash.n_dash && !outline) { - thePath->DashPolylineFromStyle(style, scale, 1.0); - } - - ButtType butt=butt_straight; - switch (shape->_stroke.cap) { - case NRArenaShape::BUTT_CAP: - butt = butt_straight; - break; - case NRArenaShape::ROUND_CAP: - butt = butt_round; - break; - case NRArenaShape::SQUARE_CAP: - butt = butt_square; - break; - } - JoinType join=join_straight; - switch (shape->_stroke.join) { - case NRArenaShape::MITRE_JOIN: - join = join_pointy; - break; - case NRArenaShape::ROUND_JOIN: - join = join_round; - break; - case NRArenaShape::BEVEL_JOIN: - join = join_straight; - break; - } - - if (outline) { - butt = butt_straight; - join = join_straight; - } - - thePath->Stroke(theShape, false, 0.5*width, join, butt, - 0.5*width*shape->_stroke.mitre_limit); - - - if (outline) { - // speeds it up, but uses evenodd for the stroke shape (which does not matter for 1-pixel wide outline) - shape->cached_stroke->Copy(theShape); - } else { - shape->cached_stroke->ConvertToShape(theShape, fill_nonZero); - } - - shape->cached_width = width; - - shape->cached_sctm=gc->transform; - shape->cached_sarea = *area; - delete thePath; - delete theShape; - if ( shape->stroke_shp == NULL ) shape->stroke_shp=new Shape; - - shape->stroke_shp->Copy(shape->cached_stroke); - - } else if ( 2 == isometry ) { - if ( shape->stroke_shp == NULL ) { - shape->stroke_shp=new Shape; - shape->stroke_shp->Copy(shape->cached_stroke); - } - } else { - if ( shape->stroke_shp == NULL ) - shape->stroke_shp=new Shape; - shape->stroke_shp->Reset(shape->cached_stroke->numberOfPoints(), shape->cached_stroke->numberOfEdges()); - for (int i = 0; i < shape->cached_stroke->numberOfPoints(); i++) - shape->stroke_shp->AddPoint(to_2geom(shape->cached_stroke->getPoint(i).x) * cached_to_new); - if ( isometry == 1 ) { - for (int i = 0; i < shape->cached_stroke->numberOfEdges(); i++) - shape->stroke_shp->AddEdge(shape->cached_stroke->getEdge(i).st, - shape->cached_stroke->getEdge(i).en); - } else if ( isometry == -1 ) { - for (int i = 0; i < shape->cached_stroke->numberOfEdges(); i++) - shape->stroke_shp->AddEdge(shape->cached_stroke->getEdge(i).en, - shape->cached_stroke->getEdge(i).st); - } - shape->stroke_shp->ForceToPolygon(); - shape->stroke_shp->needPointsSorting(); - shape->stroke_shp->needEdgesSorting(); - } - shape->delayed_shp |= shape->cached_spartialy; - } -} - - -void -nr_arena_shape_add_bboxes(NRArenaShape* shape, Geom::OptRect &bbox) -{ - /* TODO: are these two if's mutually exclusive? ( i.e. "shape->stroke_shp <=> !shape->fill_shp" ) - * if so, then this can be written much more compact ! */ - - if ( shape->stroke_shp ) { - Shape *larger = shape->stroke_shp; - larger->CalcBBox(); - larger->leftX = floor(larger->leftX); - larger->rightX = ceil(larger->rightX); - larger->topY = floor(larger->topY); - larger->bottomY = ceil(larger->bottomY); - Geom::Rect stroke_bbox( Geom::Interval(larger->leftX, larger->rightX), - Geom::Interval(larger->topY, larger->bottomY) ); - bbox.unionWith(stroke_bbox); - } - - if ( shape->fill_shp ) { - Shape *larger = shape->fill_shp; - larger->CalcBBox(); - larger->leftX = floor(larger->leftX); - larger->rightX = ceil(larger->rightX); - larger->topY = floor(larger->topY); - larger->bottomY = ceil(larger->bottomY); - Geom::Rect fill_bbox( Geom::Interval(larger->leftX, larger->rightX), - Geom::Interval(larger->topY, larger->bottomY) ); - bbox.unionWith(fill_bbox); - } -} - // cairo outline rendering: static unsigned int -cairo_arena_shape_render_outline(cairo_t *ct, NRArenaItem *item, Geom::OptRect area) +cairo_arena_shape_render_outline(cairo_t *ct, NRArenaItem *item, Geom::OptRect /*area*/) { NRArenaShape *shape = NR_ARENA_SHAPE(item); @@ -731,107 +315,21 @@ cairo_arena_shape_render_outline(cairo_t *ct, NRArenaItem *item, Geom::OptRect a return item->state; guint32 rgba = NR_ARENA_ITEM(shape)->arena->outlinecolor; - // FIXME: we use RGBA buffers but cairo writes BGRA (on i386), so we must cheat - // by setting color channels in the "wrong" order - cairo_set_source_rgba(ct, SP_RGBA32_B_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_R_F(rgba), SP_RGBA32_A_F(rgba)); + cairo_save(ct); + ink_cairo_transform(ct, shape->ctm); + feed_pathvector_to_cairo (ct, shape->curve->get_pathvector()); + cairo_restore(ct); + cairo_save(ct); + ink_cairo_set_source_rgba32(ct, rgba); cairo_set_line_width(ct, 0.5); cairo_set_tolerance(ct, 1.25); // low quality, but good enough for outline mode - cairo_new_path(ct); - - feed_pathvector_to_cairo (ct, shape->curve->get_pathvector(), shape->ctm, area, true, 0); - cairo_stroke(ct); + cairo_restore(ct); return item->state; } -// cairo stroke rendering (flat color only so far!): -// works on canvas, but wrongs the colors in nonpremul buffers: icons and png export -// (need to switch them to premul before this can be enabled) -void -cairo_arena_shape_render_stroke(NRArenaItem *item, NRRectL *area, NRPixBlock *pb) -{ - NRArenaShape *shape = NR_ARENA_SHAPE(item); - SPStyle const *style = shape->style; - - float const scale = shape->ctm.descrim(); - - if (fabs(shape->_stroke.width * scale) < 0.01) - return; - - cairo_t *ct = nr_create_cairo_context (area, pb); - - if (!ct) - return; - - guint32 rgba; - if ( item->render_opacity ) { - rgba = shape->_stroke.paint.color().toRGBA32( shape->_stroke.opacity * - SP_SCALE24_TO_FLOAT(style->opacity.value) ); - } else { - rgba = shape->_stroke.paint.color().toRGBA32( shape->_stroke.opacity ); - } - - // FIXME: we use RGBA buffers but cairo writes BGRA (on i386), so we must cheat - // by setting color channels in the "wrong" order - cairo_set_source_rgba(ct, SP_RGBA32_B_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_R_F(rgba), SP_RGBA32_A_F(rgba)); - - float style_width = MAX(0.125, shape->_stroke.width * scale); - cairo_set_line_width(ct, style_width); - - switch (shape->_stroke.cap) { - case NRArenaShape::BUTT_CAP: - cairo_set_line_cap(ct, CAIRO_LINE_CAP_BUTT); - break; - case NRArenaShape::ROUND_CAP: - cairo_set_line_cap(ct, CAIRO_LINE_CAP_ROUND); - break; - case NRArenaShape::SQUARE_CAP: - cairo_set_line_cap(ct, CAIRO_LINE_CAP_SQUARE); - break; - } - switch (shape->_stroke.join) { - case NRArenaShape::MITRE_JOIN: - cairo_set_line_join(ct, CAIRO_LINE_JOIN_MITER); - break; - case NRArenaShape::ROUND_JOIN: - cairo_set_line_join(ct, CAIRO_LINE_JOIN_ROUND); - break; - case NRArenaShape::BEVEL_JOIN: - cairo_set_line_join(ct, CAIRO_LINE_JOIN_BEVEL); - break; - } - - cairo_set_miter_limit (ct, style->stroke_miterlimit.value); - - if (style->stroke_dash.n_dash) { - NRVpathDash dash; - dash.offset = style->stroke_dash.offset * scale; - dash.n_dash = style->stroke_dash.n_dash; - dash.dash = g_new(double, dash.n_dash); - for (int i = 0; i < dash.n_dash; i++) { - dash.dash[i] = style->stroke_dash.dash[i] * scale; - } - cairo_set_dash (ct, dash.dash, dash.n_dash, dash.offset); - g_free(dash.dash); - } - - cairo_set_tolerance(ct, 0.1); - cairo_new_path(ct); - - feed_pathvector_to_cairo (ct, shape->curve->get_pathvector(), shape->ctm, to_2geom(area->upgrade()), true, style_width); - - cairo_stroke(ct); - - cairo_surface_t *cst = cairo_get_target(ct); - cairo_destroy (ct); - cairo_surface_finish (cst); - cairo_surface_destroy (cst); - - pb->empty = FALSE; -} - /** * Renders the item. Markers are just composed into the parent buffer. */ @@ -842,150 +340,51 @@ nr_arena_shape_render(cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock if (!shape->curve) return item->state; if (!shape->style) return item->state; + if (!ct) return item->state; + + // skip if not within bounding box + if (!nr_rect_l_test_intersect_ptr(area, &item->bbox)) { + return item->state; + } bool outline = (NR_ARENA_ITEM(shape)->arena->rendermode == Inkscape::RENDERMODE_OUTLINE); - bool print_colors_preview = (NR_ARENA_ITEM(shape)->arena->colorrendermode == Inkscape::COLORRENDERMODE_PRINT_COLORS_PREVIEW); - bool grayscale = (NR_ARENA_ITEM(shape)->arena->colorrendermode == Inkscape::COLORRENDERMODE_GRAYSCALE); if (outline) { // cairo outline rendering - pb->empty = FALSE; - unsigned int ret = cairo_arena_shape_render_outline (ct, item, to_2geom((&pb->area)->upgrade())); + NRRect temp(area->x0, area->y0, area->x1, area->y1); + unsigned int ret = cairo_arena_shape_render_outline (ct, item, temp.upgrade_2geom()); if (ret & NR_ARENA_ITEM_STATE_INVALID) return ret; } else { - - if ( shape->delayed_shp ) { - if ( nr_rect_l_test_intersect_ptr(area, &item->bbox) ) { - NRGC tempGC(NULL); - tempGC.transform=shape->ctm; - shape->delayed_shp = false; - nr_arena_shape_update_stroke(shape,&tempGC,&pb->visible_area); - nr_arena_shape_update_fill(shape,&tempGC,&pb->visible_area); -/* NRRect bbox; - bbox.x0 = bbox.y0 = bbox.x1 = bbox.y1 = 0.0; - nr_arena_shape_add_bboxes(shape,bbox); - item->bbox.x0 = (gint32)(bbox.x0 - 1.0F); - item->bbox.y0 = (gint32)(bbox.y0 - 1.0F); - item->bbox.x1 = (gint32)(bbox.x1 + 1.0F); - item->bbox.y1 = (gint32)(bbox.y1 + 1.0F); - shape->approx_bbox=item->bbox;*/ - } else { - return item->state; - } - } - - SPStyle const *style = shape->style; - - if (shape->fill_shp) { - NRPixBlock m; - guint32 rgba; - - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort render - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); - } - - m.visible_area = pb->visible_area; - nr_pixblock_render_shape_mask_or(m,shape->fill_shp); - m.empty = FALSE; - - if (shape->_fill.paint.type() == NRArenaShape::Paint::NONE) { - // do not render fill in any way - } else if (shape->_fill.paint.type() == NRArenaShape::Paint::COLOR) { - - const SPColor* fill_color = &shape->_fill.paint.color(); - if ( item->render_opacity ) { - rgba = fill_color->toRGBA32( shape->_fill.opacity * - SP_SCALE24_TO_FLOAT(style->opacity.value) ); - } else { - rgba = fill_color->toRGBA32( shape->_fill.opacity ); + bool has_stroke, has_fill; + // we assume the context has no path + cairo_save(ct); + ink_cairo_transform(ct, shape->ctm); + + // update fill and stroke paints. + // this cannot be done during nr_arena_shape_update, because we need a Cairo context + // to render svg:pattern + has_fill = shape->nrstyle.prepareFill(ct, &shape->paintbox); + has_stroke = shape->nrstyle.prepareStroke(ct, &shape->paintbox); + has_stroke &= (shape->nrstyle.stroke_width != 0); + + if (has_fill || has_stroke) { + // TODO: remove segments outside of bbox when no dashes present + feed_pathvector_to_cairo(ct, shape->curve->get_pathvector()); + if (has_fill) { + shape->nrstyle.applyFill(ct); + cairo_fill_preserve(ct); } - - if (print_colors_preview) { - nr_arena_separate_color_plates(&rgba); - } else if (grayscale) { - rgba = Grayscale::process(rgba); - } - - nr_blit_pixblock_mask_rgba32(pb, &m, rgba); - pb->empty = FALSE; - } else if (shape->_fill.paint.type() == NRArenaShape::Paint::SERVER) { - if (shape->fill_painter) { - nr_arena_render_paintserver_fill(pb, area, shape->fill_painter, shape->_fill.opacity, &m); + if (has_stroke) { + shape->nrstyle.applyStroke(ct); + cairo_stroke_preserve(ct); } - } - - nr_pixblock_release(&m); + cairo_new_path(ct); // clear path + } // has fill or stroke pattern + cairo_restore(ct); } - if (shape->stroke_shp && shape->_stroke.paint.type() == NRArenaShape::Paint::COLOR) { - - // cairo_arena_shape_render_stroke(item, area, pb); - - guint32 rgba; - NRPixBlock m; - - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort render - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); - } - - m.visible_area = pb->visible_area; - nr_pixblock_render_shape_mask_or(m, shape->stroke_shp); - m.empty = FALSE; - - const SPColor* stroke_color = &shape->_stroke.paint.color(); - if ( item->render_opacity ) { - rgba = stroke_color->toRGBA32( shape->_stroke.opacity * - SP_SCALE24_TO_FLOAT(style->opacity.value) ); - } else { - rgba = stroke_color->toRGBA32( shape->_stroke.opacity ); - } - - if (print_colors_preview) { - nr_arena_separate_color_plates(&rgba); - } else if (grayscale) { - rgba = Grayscale::process(rgba); - } - - nr_blit_pixblock_mask_rgba32(pb, &m, rgba); - pb->empty = FALSE; - - nr_pixblock_release(&m); - - } else if (shape->stroke_shp && shape->_stroke.paint.type() == NRArenaShape::Paint::SERVER) { - - NRPixBlock m; - - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort render - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); - } - - m.visible_area = pb->visible_area; - nr_pixblock_render_shape_mask_or(m, shape->stroke_shp); - m.empty = FALSE; - - if (shape->stroke_painter) { - nr_arena_render_paintserver_fill(pb, area, shape->stroke_painter, shape->_stroke.opacity, &m); - } - - nr_pixblock_release(&m); - } - - } // non-cairo non-outline branch - - /* Render markers into parent buffer */ + // marker rendering for (NRArenaItem *child = shape->markers; child != NULL; child = child->next) { unsigned int ret = nr_arena_item_invoke_render(ct, child, area, pb, flags); if (ret & NR_ARENA_ITEM_STATE_INVALID) return ret; @@ -995,88 +394,18 @@ nr_arena_shape_render(cairo_t *ct, NRArenaItem *item, NRRectL *area, NRPixBlock } -// cairo clipping: this basically works except for the stride-must-be-divisible-by-4 cairo bug; -// reenable this when the bug is fixed and remove the rest of this function -// TODO -#if defined(DEADCODE) && !defined(DEADCODE) -static guint -cairo_arena_shape_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb) -{ - NRArenaShape *shape = NR_ARENA_SHAPE(item); - if (!shape->curve) return item->state; - - cairo_t *ct = nr_create_cairo_context (area, pb); - - if (!ct) - return item->state; - - cairo_set_source_rgba(ct, 0, 0, 0, 1); - - cairo_new_path(ct); - - feed_pathvector_to_cairo (ct, shape->curve->get_pathvector(), shape->ctm, (area)->upgrade(), false, 0); - - cairo_fill(ct); - - cairo_surface_t *cst = cairo_get_target(ct); - cairo_destroy (ct); - cairo_surface_finish (cst); - cairo_surface_destroy (cst); - - pb->empty = FALSE; - - return item->state; -} -#endif //defined(DEADCODE) && !defined(DEADCODE) - - static guint -nr_arena_shape_clip(NRArenaItem *item, NRRectL *area, NRPixBlock *pb) +nr_arena_shape_clip(cairo_t *ct, NRArenaItem *item, NRRectL *area) { - //return cairo_arena_shape_clip(item, area, pb); - + // NOTE: for now this is incorrect, because it doesn't honor clip-rule, + // and will be incorrect for nested clipping paths. NRArenaShape *shape = NR_ARENA_SHAPE(item); if (!shape->curve) return item->state; - if ( shape->delayed_shp || shape->fill_shp == NULL) { // we need a fill shape no matter what - if ( nr_rect_l_test_intersect_ptr(area, &item->bbox) ) { - NRGC tempGC(NULL); - tempGC.transform=shape->ctm; - shape->delayed_shp = false; - nr_arena_shape_update_fill(shape, &tempGC, &pb->visible_area, true); - } else { - return item->state; - } - } - - if ( shape->fill_shp ) { - NRPixBlock m; - - /* fixme: We can OR in one step (Lauris) */ - nr_pixblock_setup_fast(&m, NR_PIXBLOCK_MODE_A8, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort - if (m.size != NR_PIXBLOCK_SIZE_TINY && m.data.px == NULL) { - nr_pixblock_release (&m); - return (item->state); - } - - m.visible_area = pb->visible_area; - nr_pixblock_render_shape_mask_or(m,shape->fill_shp); - - for (int y = area->y0; y < area->y1; y++) { - unsigned char *s, *d; - s = NR_PIXBLOCK_PX(&m) + (y - area->y0) * m.rs; - d = NR_PIXBLOCK_PX(pb) + (y - area->y0) * pb->rs; - for (int x = area->x0; x < area->x1; x++) { - *d = NR_COMPOSEA_111(*s, *d); - d ++; - s ++; - } - } - nr_pixblock_release(&m); - pb->empty = FALSE; - } + cairo_save(ct); + ink_cairo_transform(ct, shape->ctm); + feed_pathvector_to_cairo(ct, shape->curve->get_pathvector()); + cairo_restore(ct); return item->state; } @@ -1107,17 +436,17 @@ nr_arena_shape_pick(NRArenaItem *item, Geom::Point p, double delta, unsigned int double width; if (outline) { width = 0.5; - } else if (shape->_stroke.paint.type() != NRArenaShape::Paint::NONE && shape->_stroke.opacity > 1e-3) { + } else if (shape->nrstyle.stroke.type != NRStyle::PAINT_NONE && shape->nrstyle.stroke.opacity > 1e-3) { float const scale = shape->ctm.descrim(); - width = MAX(0.125, shape->_stroke.width * scale) / 2; + width = MAX(0.125, shape->nrstyle.stroke_width * scale) / 2; } else { width = 0; } - double dist = NR_HUGE; + double dist = Geom::infinity(); int wind = 0; - bool needfill = (shape->_fill.paint.type() != NRArenaShape::Paint::NONE - && shape->_fill.opacity > 1e-3 && !outline); + bool needfill = (shape->nrstyle.fill.type != NRStyle::PAINT_NONE + && shape->nrstyle.fill.opacity > 1e-3 && !outline); if (item->arena->canvasarena) { Geom::Rect viewbox = item->arena->canvasarena->item.canvas->getViewbox(); @@ -1184,18 +513,6 @@ void nr_arena_shape_set_path(NRArenaShape *shape, SPCurve *curve,bool justTrans) g_return_if_fail(shape != NULL); g_return_if_fail(NR_IS_ARENA_SHAPE(shape)); - if ( justTrans == false ) { - // dirty cached versions - if ( shape->cached_fill ) { - delete shape->cached_fill; - shape->cached_fill=NULL; - } - if ( shape->cached_stroke ) { - delete shape->cached_stroke; - shape->cached_stroke=NULL; - } - } - nr_arena_item_request_render(NR_ARENA_ITEM(shape)); if (shape->curve) { @@ -1211,61 +528,6 @@ void nr_arena_shape_set_path(NRArenaShape *shape, SPCurve *curve,bool justTrans) nr_arena_item_request_update(NR_ARENA_ITEM(shape), NR_ARENA_ITEM_STATE_ALL, FALSE); } -void NRArenaShape::setFill(SPPaintServer *server) { - _fill.paint.set(server); - _invalidateCachedFill(); -} - -void NRArenaShape::setFill(SPColor const &color) { - _fill.paint.set(color); - _invalidateCachedFill(); -} - -void NRArenaShape::setFillOpacity(double opacity) { - _fill.opacity = opacity; - _invalidateCachedFill(); -} - -void NRArenaShape::setFillRule(NRArenaShape::FillRule rule) { - _fill.rule = rule; - _invalidateCachedFill(); -} - -void NRArenaShape::setStroke(SPPaintServer *server) { - _stroke.paint.set(server); - _invalidateCachedStroke(); -} - -void NRArenaShape::setStroke(SPColor const &color) { - _stroke.paint.set(color); - _invalidateCachedStroke(); -} - -void NRArenaShape::setStrokeOpacity(double opacity) { - _stroke.opacity = opacity; - _invalidateCachedStroke(); -} - -void NRArenaShape::setStrokeWidth(double width) { - _stroke.width = width; - _invalidateCachedStroke(); -} - -void NRArenaShape::setMitreLimit(double limit) { - _stroke.mitre_limit = limit; - _invalidateCachedStroke(); -} - -void NRArenaShape::setLineCap(NRArenaShape::CapType cap) { - _stroke.cap = cap; - _invalidateCachedStroke(); -} - -void NRArenaShape::setLineJoin(NRArenaShape::JoinType join) { - _stroke.join = join; - _invalidateCachedStroke(); -} - /** nr_arena_shape_set_style * * Unrefs any existing style and ref's to the given one, then requests an update of the arena @@ -1275,81 +537,13 @@ nr_arena_shape_set_style(NRArenaShape *shape, SPStyle *style) { g_return_if_fail(shape != NULL); g_return_if_fail(NR_IS_ARENA_SHAPE(shape)); + g_return_if_fail(style != NULL); - if (style) sp_style_ref(style); + sp_style_ref(style); if (shape->style) sp_style_unref(shape->style); shape->style = style; - if ( style->fill.isPaintserver() ) { - shape->setFill(style->getFillPaintServer()); - } else if ( style->fill.isColor() ) { - shape->setFill(style->fill.value.color); - } else if ( style->fill.isNone() ) { - shape->setFill(NULL); - } else { - g_assert_not_reached(); - } - shape->setFillOpacity(SP_SCALE24_TO_FLOAT(style->fill_opacity.value)); - switch (style->fill_rule.computed) { - case SP_WIND_RULE_EVENODD: { - shape->setFillRule(NRArenaShape::EVEN_ODD); - break; - } - case SP_WIND_RULE_NONZERO: { - shape->setFillRule(NRArenaShape::NONZERO); - break; - } - default: { - g_assert_not_reached(); - } - } - - if ( style->stroke.isPaintserver() ) { - shape->setStroke(style->getStrokePaintServer()); - } else if ( style->stroke.isColor() ) { - shape->setStroke(style->stroke.value.color); - } else if ( style->stroke.isNone() ) { - shape->setStroke(NULL); - } else { - g_assert_not_reached(); - } - shape->setStrokeWidth(style->stroke_width.computed); - shape->setStrokeOpacity(SP_SCALE24_TO_FLOAT(style->stroke_opacity.value)); - switch (style->stroke_linecap.computed) { - case SP_STROKE_LINECAP_ROUND: { - shape->setLineCap(NRArenaShape::ROUND_CAP); - break; - } - case SP_STROKE_LINECAP_SQUARE: { - shape->setLineCap(NRArenaShape::SQUARE_CAP); - break; - } - case SP_STROKE_LINECAP_BUTT: { - shape->setLineCap(NRArenaShape::BUTT_CAP); - break; - } - default: { - g_assert_not_reached(); - } - } - switch (style->stroke_linejoin.computed) { - case SP_STROKE_LINEJOIN_ROUND: { - shape->setLineJoin(NRArenaShape::ROUND_JOIN); - break; - } - case SP_STROKE_LINEJOIN_BEVEL: { - shape->setLineJoin(NRArenaShape::BEVEL_JOIN); - break; - } - case SP_STROKE_LINEJOIN_MITER: { - shape->setLineJoin(NRArenaShape::MITRE_JOIN); - break; - } - default: { - g_assert_not_reached(); - } - } - shape->setMitreLimit(style->stroke_miterlimit.value); + shape->nrstyle.set(style); //if shape has a filter if (style->filter.set && style->getFilter()) { @@ -1395,118 +589,6 @@ void NRArenaShape::setPaintBox(Geom::Rect const &pbox) nr_arena_item_request_update(this, NR_ARENA_ITEM_STATE_ALL, FALSE); } -static void -shape_run_A8_OR(raster_info &dest,void */*data*/,int st,float vst,int en,float ven) -{ - if ( st >= en ) return; - if ( vst < 0 ) vst=0; - if ( vst > 1 ) vst=1; - if ( ven < 0 ) ven=0; - if ( ven > 1 ) ven=1; - float sv=vst; - float dv=ven-vst; - int len=en-st; - unsigned char* d=(unsigned char*)dest.buffer; - d+=(st-dest.startPix); - if ( fabs(dv) < 0.001 ) { - if ( vst > 0.999 ) { - /* Simple copy */ - while (len > 0) { - d[0] = 255; - d += 1; - len -= 1; - } - } else { - sv*=256; - unsigned int c0_24=(int)sv; - c0_24&=0xFF; - while (len > 0) { - /* Draw */ - d[0] = NR_COMPOSEA_111(c0_24,d[0]); - d += 1; - len -= 1; - } - } - } else { - if ( en <= st+1 ) { - sv=0.5*(vst+ven); - sv*=256; - unsigned int c0_24=(int)sv; - c0_24&=0xFF; - /* Draw */ - d[0] = NR_COMPOSEA_111(c0_24,d[0]); - } else { - dv/=len; - sv+=0.5*dv; // correction trapezoidale - sv*=16777216; - dv*=16777216; - int c0_24 = static_cast<int>(CLAMP(sv, 0, 16777216)); - int s0_24 = static_cast<int>(dv); - while (len > 0) { - unsigned int ca; - /* Draw */ - ca = c0_24 >> 16; - if ( ca > 255 ) ca=255; - d[0] = NR_COMPOSEA_111(ca,d[0]); - d += 1; - c0_24 += s0_24; - c0_24 = CLAMP(c0_24, 0, 16777216); - len -= 1; - } - } - } -} - -void nr_pixblock_render_shape_mask_or(NRPixBlock &m,Shape* theS) -{ - theS->CalcBBox(); - float l = theS->leftX, r = theS->rightX, t = theS->topY, b = theS->bottomY; - int il,ir,it,ib; - il=(int)floor(l); - ir=(int)ceil(r); - it=(int)floor(t); - ib=(int)ceil(b); - - if ( il >= m.area.x1 || ir <= m.area.x0 || it >= m.area.y1 || ib <= m.area.y0 ) return; - if ( il < m.area.x0 ) il=m.area.x0; - if ( it < m.area.y0 ) it=m.area.y0; - if ( ir > m.area.x1 ) ir=m.area.x1; - if ( ib > m.area.y1 ) ib=m.area.y1; - - /* This is the FloatLigne version. See svn (prior to Apr 2006) for versions using BitLigne or direct BitLigne. */ - int curPt; - float curY; - theS->BeginQuickRaster(curY, curPt); - - FloatLigne *theI = new FloatLigne(); - IntLigne *theIL = new IntLigne(); - - theS->DirectQuickScan(curY, curPt, (float) it, true, 1.0); - - char *mdata = (char*)m.data.px; - if ( m.size == NR_PIXBLOCK_SIZE_TINY ) mdata=(char*)m.data.p; - uint32_t *ligStart = ((uint32_t*)(mdata + ((il - m.area.x0) + m.rs * (it - m.area.y0)))); - for (int y = it; y < ib; y++) { - theI->Reset(); - theS->QuickScan(curY, curPt, ((float)(y+1)), theI, 1.0); - theI->Flatten(); - theIL->Copy(theI); - - raster_info dest; - dest.startPix=il; - dest.endPix=ir; - dest.sth=il; - dest.stv=y; - dest.buffer=ligStart; - theIL->Raster(dest, NULL, shape_run_A8_OR); - ligStart=((uint32_t*)(((char*)ligStart)+m.rs)); - } - theS->EndQuickRaster(); - delete theI; - delete theIL; -} - - /* Local Variables: mode:c++ diff --git a/src/display/nr-arena-shape.h b/src/display/nr-arena-shape.h index e00993901..2ee0d24c8 100644 --- a/src/display/nr-arena-shape.h +++ b/src/display/nr-arena-shape.h @@ -17,133 +17,30 @@ #define NR_ARENA_SHAPE(obj) (NR_CHECK_INSTANCE_CAST ((obj), NR_TYPE_ARENA_SHAPE, NRArenaShape)) #define NR_IS_ARENA_SHAPE(obj) (NR_CHECK_INSTANCE_TYPE ((obj), NR_TYPE_ARENA_SHAPE)) -#include "display/canvas-bpath.h" +#include <cairo.h> +#include "display/display-forward.h" #include "forward.h" -#include "sp-paint-server.h" #include "nr-arena-item.h" - -#include "../color.h" - -#include "../livarot/Shape.h" +#include "nr-style.h" NRType nr_arena_shape_get_type (void); struct NRArenaShape : public NRArenaItem { - class Paint { - public: - enum Type { - NONE, - COLOR, - SERVER - }; - - Paint() : _type(NONE), _color(0), _server(NULL) {} - Paint(Paint const &p) { _assign(p); } - virtual ~Paint() { clear(); } - - Type type() const { return _type; } - SPPaintServer *server() const { return _server; } - SPColor const &color() const { return _color; } - - Paint &operator=(Paint const &p) { - set(p); - return *this; - } - - void set(Paint const &p) { - clear(); - _assign(p); - } - void set(SPColor const &color) { - clear(); - _type = COLOR; - _color = color; - } - void set(SPPaintServer *server) { - clear(); - if (server) { - _type = SERVER; - _server = server; - sp_object_ref(_server, NULL); - } - } - void clear() { - if ( _type == SERVER ) { - sp_object_unref(_server, NULL); - _server = NULL; - } - _type = NONE; - } - - private: - Type _type; - SPColor _color; - SPPaintServer *_server; - - void _assign(Paint const &p) { - _type = p._type; - _server = p._server; - _color = p._color; - if (_server) { - sp_object_ref(_server, NULL); - } - } - }; - - enum FillRule { - EVEN_ODD, - NONZERO - }; - - enum CapType { - ROUND_CAP, - SQUARE_CAP, - BUTT_CAP - }; - - enum JoinType { - ROUND_JOIN, - BEVEL_JOIN, - MITRE_JOIN - }; - /* Shape data */ SPCurve *curve; SPStyle *style; + NRStyle nrstyle; NRRect paintbox; - /* State data */ - Geom::Affine ctm; - - SPPainter *fill_painter; - SPPainter *stroke_painter; - // the 2 cached polygons, for rasterizations uses - Shape *fill_shp; - Shape *stroke_shp; - // the stroke width of stroke_shp, to detect when it changes (on normal/outline switching) and rebuild - float cached_width; + + cairo_path_t *path; + // delayed_shp=true means the *_shp polygons are not computed yet // they'll be computed on demand in *_render(), *_pick() or *_clip() // the goal is to not uncross polygons that are outside the viewing region bool delayed_shp; // approximate bounding box, for the case when the polygons have been delayed NRRectL approx_bbox; - // cache for transformations: cached_fill and cached_stroke are - // polygons computed for the cached_fctm and cache_sctm respectively - // when the transformation changes interactively (tracked by the - // SP_OBJECT_USER_MODIFIED_FLAG_B), we check if it's an isometry wrt - // the cached ctm. if it's an isometry, just apply it to the cached - // polygon to get the *_shp polygon. Otherwise, recompute so this - // works fine for translation and rotation, but not scaling and - // skewing - Geom::Affine cached_fctm; - Geom::Affine cached_sctm; - NRRectL cached_farea; - NRRectL cached_sarea; - bool cached_fpartialy; - bool cached_spartialy; - - Shape *cached_fill; - Shape *cached_stroke; + /* Markers */ NRArenaItem *markers; @@ -157,54 +54,7 @@ struct NRArenaShape : public NRArenaItem { return obj; } - void setFill(SPPaintServer *server); - void setFill(SPColor const &color); - void setFillOpacity(double opacity); - void setFillRule(FillRule rule); - - void setStroke(SPPaintServer *server); - void setStroke(SPColor const &color); - void setStrokeOpacity(double opacity); - void setStrokeWidth(double width); - void setLineCap(CapType cap); - void setLineJoin(JoinType join); - void setMitreLimit(double limit); - void setPaintBox(Geom::Rect const &pbox); - - void _invalidateCachedFill() { - if (cached_fill) { - delete cached_fill; - cached_fill = NULL; - } - } - void _invalidateCachedStroke() { - if (cached_stroke) { - delete cached_stroke; - cached_stroke = NULL; - } - } - - struct Style { - Style() : opacity(0.0) {} - Paint paint; - double opacity; - }; - struct FillStyle : public Style { - FillStyle() : rule(EVEN_ODD) {} - FillRule rule; - } _fill; - struct StrokeStyle : public Style { - StrokeStyle() - : cap(ROUND_CAP), join(ROUND_JOIN), - width(0.0), mitre_limit(0.0) - {} - - CapType cap; - JoinType join; - double width; - double mitre_limit; - } _stroke; }; struct NRArenaShapeClass { diff --git a/src/display/nr-arena.cpp b/src/display/nr-arena.cpp index 147269727..43edb6918 100644 --- a/src/display/nr-arena.cpp +++ b/src/display/nr-arena.cpp @@ -16,8 +16,6 @@ #include "nr-arena.h" #include "nr-filter-gaussian.h" #include "nr-filter-types.h" -#include <libnr/nr-blit.h> -#include "sp-paint-server.h" #include "preferences.h" #include "color.h" @@ -135,41 +133,6 @@ nr_arena_request_render_rect (NRArena *arena, NRRectL *area) } } -void -nr_arena_render_paintserver_fill (NRPixBlock *pb, NRRectL *area, SPPainter *painter, float opacity, NRPixBlock *mask) -{ - NRPixBlock cb, cb_opa; - nr_pixblock_setup_fast (&cb, NR_PIXBLOCK_MODE_R8G8B8A8N, area->x0, area->y0, area->x1, area->y1, TRUE); - nr_pixblock_setup_fast (&cb_opa, NR_PIXBLOCK_MODE_R8G8B8A8N, area->x0, area->y0, area->x1, area->y1, TRUE); - - // if memory allocation failed, abort - if ((cb.size != NR_PIXBLOCK_SIZE_TINY && cb.data.px == NULL) || (cb_opa.size != NR_PIXBLOCK_SIZE_TINY && cb_opa.data.px == NULL)) { - return; - } - - cb.visible_area = pb->visible_area; - cb_opa.visible_area = pb->visible_area; - - /* Need separate gradient buffer (lauris)*/ - // do the filling - painter->fill (painter, &cb); - cb.empty = FALSE; - - // do the fill-opacity and mask composite - if (opacity < 1.0) { - nr_blit_pixblock_pixblock_alpha (&cb_opa, &cb, (int) floor (255 * opacity)); - cb_opa.empty = FALSE; - nr_blit_pixblock_pixblock_mask (pb, &cb_opa, mask); - } else { - nr_blit_pixblock_pixblock_mask (pb, &cb, mask); - } - - pb->empty = FALSE; - - nr_pixblock_release (&cb); - nr_pixblock_release (&cb_opa); -} - /** set arena to offscreen mode rendering will be exact diff --git a/src/display/nr-arena.h b/src/display/nr-arena.h index 402bc198f..1c8216434 100644 --- a/src/display/nr-arena.h +++ b/src/display/nr-arena.h @@ -64,8 +64,6 @@ void nr_arena_request_update (NRArena *arena, NRArenaItem *item); void nr_arena_request_render_rect (NRArena *arena, NRRectL *area); void nr_arena_set_renderoffscreen (NRArena *arena); -void nr_arena_render_paintserver_fill (NRPixBlock *pb, NRRectL *area, SPPainter *painter, float opacity, NRPixBlock *mask); - void nr_arena_separate_color_plates(guint32* rgba); #endif diff --git a/src/display/nr-filter-blend.cpp b/src/display/nr-filter-blend.cpp index a0f074dc9..3cec479fa 100644 --- a/src/display/nr-filter-blend.cpp +++ b/src/display/nr-filter-blend.cpp @@ -15,15 +15,17 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifdef HAVE_CONFIG_H +#include "config.h" +#endif + +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter-blend.h" -#include "display/nr-filter-pixops.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-types.h" -#include "display/nr-filter-units.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixops.h" +#include "preferences.h" namespace Inkscape { namespace Filters { @@ -42,77 +44,6 @@ namespace Filters { * cb = Color (RGB) at a given pixel for image B - premultiplied */ -/* - * These blending equations given in SVG standard are for color values - * in the range 0..1. As these values are stored as unsigned char values, - * they need some reworking. An unsigned char value can be thought as - * 0.8 fixed point representation of color value. This is how I've - * ended up with these equations here. - */ - -// Set alpha / opacity. This line is same for all the blending modes, -// so let's save some copy-pasting. -#define SET_ALPHA r[3] = NR_NORMALIZE_21((255 * 255) - (255 - a[3]) * (255 - b[3])) - -// cr = (1 - qa) * cb + ca -inline void -blend_normal(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_COMPOSEPPP_1111(a[0],a[3],b[0]); - r[1] = NR_COMPOSEPPP_1111(a[1],a[3],b[1]); - r[2] = NR_COMPOSEPPP_1111(a[2],a[3],b[2]); - SET_ALPHA; -} - -// cr = (1-qa)*cb + (1-qb)*ca + ca*cb -inline void -blend_multiply(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21((255 - a[3]) * b[0] + (255 - b[3]) * a[0] - + a[0] * b[0]); - r[1] = NR_NORMALIZE_21((255 - a[3]) * b[1] + (255 - b[3]) * a[1] - + a[1] * b[1]); - r[2] = NR_NORMALIZE_21((255 - a[3]) * b[2] + (255 - b[3]) * a[2] - + a[2] * b[2]); - SET_ALPHA; -} - -// cr = cb + ca - ca * cb -inline void -blend_screen(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21((b[0] + a[0]) * 255 - a[0] * b[0]); - r[1] = NR_NORMALIZE_21((b[1] + a[1]) * 255 - a[1] * b[1]); - r[2] = NR_NORMALIZE_21((b[2] + a[2]) * 255 - a[2] * b[2]); - SET_ALPHA; -} - -// cr = Min ((1 - qa) * cb + ca, (1 - qb) * ca + cb) -inline void -blend_darken(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(std::min(NR_COMPOSEPPP_1112(a[0],a[3],b[0]), - NR_COMPOSEPPP_1112(b[0],b[3],a[0]))); - r[1] = NR_NORMALIZE_21(std::min(NR_COMPOSEPPP_1112(a[1],a[3],b[1]), - NR_COMPOSEPPP_1112(b[1],b[3],a[1]))); - r[2] = NR_NORMALIZE_21(std::min(NR_COMPOSEPPP_1112(a[2],a[3],b[2]), - NR_COMPOSEPPP_1112(b[2],b[3],a[2]))); - SET_ALPHA; -} - -// cr = Max ((1 - qa) * cb + ca, (1 - qb) * ca + cb) -inline void -blend_lighten(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(std::max(NR_COMPOSEPPP_1112(a[0],a[3],b[0]), - NR_COMPOSEPPP_1112(b[0],b[3],a[0]))); - r[1] = NR_NORMALIZE_21(std::max(NR_COMPOSEPPP_1112(a[1],a[3],b[1]), - NR_COMPOSEPPP_1112(b[1],b[3],a[1]))); - r[2] = NR_NORMALIZE_21(std::max(NR_COMPOSEPPP_1112(a[2],a[3],b[2]), - NR_COMPOSEPPP_1112(b[2],b[3],a[2]))); - SET_ALPHA; -} - FilterBlend::FilterBlend() : _blend_mode(BLEND_NORMAL), _input2(NR_FILTER_SLOT_NOT_SET) @@ -125,81 +56,144 @@ FilterPrimitive * FilterBlend::create() { FilterBlend::~FilterBlend() {} -int FilterBlend::render(FilterSlot &slot, FilterUnits const & /*units*/) { - NRPixBlock *in1 = slot.get(_input); - NRPixBlock *in2 = slot.get(_input2); - NRPixBlock *original_in1 = in1; - NRPixBlock *original_in2 = in2; - NRPixBlock *out; - - // Bail out if either one of source images is missing - if (!in1 || !in2) { - g_warning("Missing source image for feBlend (in=%d in2=%d)", _input, _input2); - return 1; - } +// cr = (1-qa)*cb + (1-qb)*ca + ca*cb +struct BlendMultiply { + guint32 operator()(guint32 in1, guint32 in2) + { + EXTRACT_ARGB32(in1, aa, ra, ga, ba) + EXTRACT_ARGB32(in2, ab, rb, gb, bb) + + guint32 ao = 255*255 - (255-aa)*(255-ab); ao = (ao + 127) / 255; + guint32 ro = (255-aa)*rb + (255-ab)*ra + ra*rb; ro = (ro + 127) / 255; + guint32 go = (255-aa)*gb + (255-ab)*ga + ga*gb; go = (go + 127) / 255; + guint32 bo = (255-aa)*bb + (255-ab)*ba + ba*bb; bo = (bo + 127) / 255; - out = new NRPixBlock; - NRRectL out_area; - nr_rect_l_union(&out_area, &in1->area, &in2->area); - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8P, - out_area.x0, out_area.y0, out_area.x1, out_area.y1, - true); - - // Blending modes are defined for premultiplied RGBA values, - // thus convert them to that format before blending - if (in1->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - in1 = new NRPixBlock; - nr_pixblock_setup_fast(in1, NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in1->area.x0, original_in1->area.y0, - original_in1->area.x1, original_in1->area.y1, - false); - nr_blit_pixblock_pixblock(in1, original_in1); + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; } - if (in2->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - in2 = new NRPixBlock; - nr_pixblock_setup_fast(in2, NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in2->area.x0, original_in2->area.y0, - original_in2->area.x1, original_in2->area.y1, - false); - nr_blit_pixblock_pixblock(in2, original_in2); +}; + +// cr = cb + ca - ca * cb +struct BlendScreen { + guint32 operator()(guint32 in1, guint32 in2) + { + EXTRACT_ARGB32(in1, aa, ra, ga, ba) + EXTRACT_ARGB32(in2, ab, rb, gb, bb) + + guint32 ao = 255*255 - (255-aa)*(255-ab); ao = (ao + 127) / 255; + guint32 ro = 255*(rb + ra) - ra * rb; ro = (ro + 127) / 255; + guint32 go = 255*(gb + ga) - ga * gb; go = (go + 127) / 255; + guint32 bo = 255*(bb + ba) - ba * bb; bo = (bo + 127) / 255; + + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; } +}; + +// cr = Min ((1 - qa) * cb + ca, (1 - qb) * ca + cb) +struct BlendDarken { + guint32 operator()(guint32 in1, guint32 in2) + { + EXTRACT_ARGB32(in1, aa, ra, ga, ba) + EXTRACT_ARGB32(in2, ab, rb, gb, bb) + + guint32 ao = 255*255 - (255-aa)*(255-ab); ao = (ao + 127) / 255; + guint32 ro = std::min((255-aa)*rb + 255*ra, (255-ab)*ra + 255*rb); ro = (ro + 127) / 255; + guint32 go = std::min((255-aa)*gb + 255*ga, (255-ab)*ga + 255*gb); go = (go + 127) / 255; + guint32 bo = std::min((255-aa)*bb + 255*ba, (255-ab)*ba + 255*bb); bo = (bo + 127) / 255; - /* pixops_mix is defined in display/nr-filter-pixops.h - * It mixes the two input images with the function given as template - * and places the result in output image. - */ - switch (_blend_mode) { - case BLEND_MULTIPLY: - pixops_mix<blend_multiply>(*out, *in1, *in2); - break; - case BLEND_SCREEN: - pixops_mix<blend_screen>(*out, *in1, *in2); - break; - case BLEND_DARKEN: - pixops_mix<blend_darken>(*out, *in1, *in2); - break; - case BLEND_LIGHTEN: - pixops_mix<blend_lighten>(*out, *in1, *in2); - break; - case BLEND_NORMAL: - default: - pixops_mix<blend_normal>(*out, *in1, *in2); - break; + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; } +}; - if (in1 != original_in1) { - nr_pixblock_release(in1); - delete in1; +// cr = Max ((1 - qa) * cb + ca, (1 - qb) * ca + cb) +struct BlendLighten { + guint32 operator()(guint32 in1, guint32 in2) + { + EXTRACT_ARGB32(in1, aa, ra, ga, ba) + EXTRACT_ARGB32(in2, ab, rb, gb, bb) + + guint32 ao = 255*255 - (255-aa)*(255-ab); ao = (ao + 127) / 255; + guint32 ro = std::max((255-aa)*rb + 255*ra, (255-ab)*ra + 255*rb); ro = (ro + 127) / 255; + guint32 go = std::max((255-aa)*gb + 255*ga, (255-ab)*ga + 255*gb); go = (go + 127) / 255; + guint32 bo = std::max((255-aa)*bb + 255*ba, (255-ab)*ba + 255*bb); bo = (bo + 127) / 255; + + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; } - if (in2 != original_in2) { - nr_pixblock_release(in2); - delete in2; +}; + +/* +struct BlendAlpha +static inline void blend_alpha(guint32 in1, guint32 in2, guint32 *out) +{ + EXTRACT_ARGB32(in1, a1, a2, a3, a4); + EXTRACT_ARGB32(in2, b1, b2, b3, b4); + + guint32 o1 = 255*255 - (255-a1)*(255-b1); o1 = (o1+127) / 255; + guint32 o2 = 255*255 - (255-a2)*(255-b2); o2 = (o2+127) / 255; + guint32 o3 = 255*255 - (255-a3)*(255-b3); o3 = (o3+127) / 255; + guint32 o4 = 255*255 - (255-a4)*(255-b4); o4 = (o4+127) / 255; + + ASSEMBLE_ARGB32(pxout, o1, o2, o3, o4); + *out = pxout; +} +*/ + +void FilterBlend::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input1 = slot.getcairo(_input); + cairo_surface_t *input2 = slot.getcairo(_input2); + + cairo_content_t ct1 = cairo_surface_get_content(input1); + cairo_content_t ct2 = cairo_surface_get_content(input2); + + // input2 is the "background" image + // out should be ARGB32 if any of the inputs is ARGB32 + cairo_surface_t *out = ink_cairo_surface_create_output(input1, input2); + + if ((ct1 == CAIRO_CONTENT_ALPHA && ct2 == CAIRO_CONTENT_ALPHA) + || _blend_mode == BLEND_NORMAL) + { + ink_cairo_surface_blit(input2, out); + cairo_t *out_ct = cairo_create(out); + cairo_set_source_surface(out_ct, input1, 0, 0); + cairo_paint(out_ct); + cairo_destroy(out_ct); + } else { + // blend mode != normal and at least 1 surface is not pure alpha + + // TODO: convert to Cairo blending operators once we start using the 1.10 series + switch (_blend_mode) { + case BLEND_MULTIPLY: + ink_cairo_surface_blend(input1, input2, out, BlendMultiply()); + break; + case BLEND_SCREEN: + ink_cairo_surface_blend(input1, input2, out, BlendScreen()); + break; + case BLEND_DARKEN: + ink_cairo_surface_blend(input1, input2, out, BlendDarken()); + break; + case BLEND_LIGHTEN: + ink_cairo_surface_blend(input1, input2, out, BlendLighten()); + break; + case BLEND_NORMAL: + default: + // this was handled before + g_assert_not_reached(); + break; + } } - out->empty = FALSE; slot.set(_output, out); + cairo_surface_destroy(out); +} - return 0; +bool FilterBlend::can_handle_affine(Geom::Affine const &) +{ + // blend is a per-pixel primitive and is immutable under transformations + return true; } void FilterBlend::set_input(int slot) { diff --git a/src/display/nr-filter-blend.h b/src/display/nr-filter-blend.h index 254653566..64b3c9284 100644 --- a/src/display/nr-filter-blend.h +++ b/src/display/nr-filter-blend.h @@ -18,8 +18,6 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { @@ -39,7 +37,8 @@ public: static FilterPrimitive *create(); virtual ~FilterBlend(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); + virtual bool can_handle_affine(Geom::Affine const &); virtual void set_input(int slot); virtual void set_input(int input, int slot); diff --git a/src/display/nr-filter-colormatrix.cpp b/src/display/nr-filter-colormatrix.cpp index 54d5dfd69..7eb2fa2e9 100644 --- a/src/display/nr-filter-colormatrix.cpp +++ b/src/display/nr-filter-colormatrix.cpp @@ -10,11 +10,13 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "display/nr-filter-colormatrix.h" -#include "display/nr-filter-units.h" -#include "display/nr-filter-utils.h" -#include "libnr/nr-blit.h" #include <math.h> +#include <algorithm> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" +#include "display/nr-filter-colormatrix.h" +#include "display/nr-filter-slot.h" +#include <2geom/math-utils.h> namespace Inkscape { namespace Filters { @@ -30,169 +32,160 @@ FilterPrimitive * FilterColorMatrix::create() { FilterColorMatrix::~FilterColorMatrix() {} -int FilterColorMatrix::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feColorMatrix (in=%d)", _input); - return 1; +struct ColorMatrixMatrix { + ColorMatrixMatrix(std::vector<double> const &values) { + unsigned limit = std::min(static_cast<size_t>(20), values.size()); + for (unsigned i = 0; i < limit; ++i) { + if (i % 5 == 4) { + _v[i] = round(values[i]*255*255); + } else { + _v[i] = round(values[i]*255); + } + } + for (unsigned i = limit; i < 20; ++i) { + _v[i] = 0; + } } - NRPixBlock *out = new NRPixBlock; - if ((type==COLORMATRIX_SATURATE || type==COLORMATRIX_HUEROTATE) && in->mode != NR_PIXBLOCK_MODE_R8G8B8A8N) { - // saturate and hueRotate do not touch the alpha channel and are linear (per-pixel) operations, so no premultiplied -> non-premultiplied operation is necessary - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8P, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); - } else { - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8N, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); + guint32 operator()(guint32 in) { + EXTRACT_ARGB32(in, a, r, g, b) + // we need to un-premultiply alpha values for this type of matrix + // TODO: unpremul can be ignored if there is an identity mapping on the alpha channel + if (a != 0) { + r = unpremul_alpha(r, a); + g = unpremul_alpha(g, a); + b = unpremul_alpha(b, a); + } + + gint32 ro = r*_v[0] + g*_v[1] + b*_v[2] + a*_v[3] + _v[4]; + gint32 go = r*_v[5] + g*_v[6] + b*_v[7] + a*_v[8] + _v[9]; + gint32 bo = r*_v[10] + g*_v[11] + b*_v[12] + a*_v[13] + _v[14]; + gint32 ao = r*_v[15] + g*_v[16] + b*_v[17] + a*_v[18] + _v[19]; + ro = (pxclamp(ro, 0, 255*255) + 127) / 255; + go = (pxclamp(go, 0, 255*255) + 127) / 255; + bo = (pxclamp(bo, 0, 255*255) + 127) / 255; + ao = (pxclamp(ao, 0, 255*255) + 127) / 255; + + ro = premul_alpha(ro, ao); + go = premul_alpha(go, ao); + bo = premul_alpha(bo, ao); + + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; + } +private: + gint32 _v[20]; +}; + +struct ColorMatrixSaturate { + ColorMatrixSaturate(double v_in) { + // clamp parameter instead of clamping color values + double v = CLAMP(v_in, 0.0, 1.0); + _v[0] = 0.213+0.787*v; _v[1] = 0.715-0.715*v; _v[2] = 0.072-0.072*v; + _v[3] = 0.213-0.213*v; _v[4] = 0.715+0.285*v; _v[5] = 0.072-0.072*v; + _v[6] = 0.213-0.213*v; _v[7] = 0.715-0.715*v; _v[8] = 0.072+0.928*v; } - // this primitive is defined for non-premultiplied RGBA values, - // thus convert them to that format - // However, since not all operations care, the input is only transformed if necessary. - bool free_in_on_exit = false; - if (in->mode != out->mode) { - NRPixBlock *original_in = in; - in = new NRPixBlock; - nr_pixblock_setup_fast(in, out->mode, - original_in->area.x0, original_in->area.y0, - original_in->area.x1, original_in->area.y1, - true); - nr_blit_pixblock_pixblock(in, original_in); - free_in_on_exit = true; + guint32 operator()(guint32 in) { + EXTRACT_ARGB32(in, a, r, g, b) + + // Note: this cannot be done in fixed point, because the loss of precision + // causes overflow for some values of v + guint32 ro = r*_v[0] + g*_v[1] + b*_v[2] + 0.5; + guint32 go = r*_v[3] + g*_v[4] + b*_v[5] + 0.5; + guint32 bo = r*_v[6] + g*_v[7] + b*_v[8] + 0.5; + + ASSEMBLE_ARGB32(pxout, a, ro, go, bo) + return pxout; + } +private: + double _v[9]; +}; + +struct ColorMatrixHueRotate { + ColorMatrixHueRotate(double v) { + double sinhue, coshue; + Geom::sincos(v * M_PI/180.0, sinhue, coshue); + + _v[0] = round((0.213 +0.787*coshue -0.213*sinhue)*255); + _v[1] = round((0.715 -0.715*coshue -0.715*sinhue)*255); + _v[2] = round((0.072 -0.072*coshue +0.928*sinhue)*255); + + _v[3] = round((0.213 -0.213*coshue +0.143*sinhue)*255); + _v[4] = round((0.715 +0.285*coshue +0.140*sinhue)*255); + _v[5] = round((0.072 -0.072*coshue -0.283*sinhue)*255); + + _v[6] = round((0.213 -0.213*coshue -0.787*sinhue)*255); + _v[7] = round((0.715 -0.715*coshue +0.715*sinhue)*255); + _v[8] = round((0.072 +0.928*coshue +0.072*sinhue)*255); + } + guint32 operator()(guint32 in) { + EXTRACT_ARGB32(in, a, r, g, b) + gint32 maxpx = a*255; + gint32 ro = r*_v[0] + g*_v[1] + b*_v[2]; + gint32 go = r*_v[3] + g*_v[4] + b*_v[5]; + gint32 bo = r*_v[6] + g*_v[7] + b*_v[8]; + ro = (pxclamp(ro, 0, maxpx) + 127) / 255; + go = (pxclamp(go, 0, maxpx) + 127) / 255; + bo = (pxclamp(bo, 0, maxpx) + 127) / 255; + + ASSEMBLE_ARGB32(pxout, a, ro, go, bo) + return pxout; + } +private: + gint32 _v[9]; +}; + +struct ColorMatrixLuminanceToAlpha { + guint32 operator()(guint32 in) { + // original computation in double: r*0.2125 + g*0.7154 + b*0.0721 + EXTRACT_ARGB32(in, a, r, g, b) + // unpremultiply color values + if (a != 0) { + r = unpremul_alpha(r, a); + g = unpremul_alpha(g, a); + b = unpremul_alpha(b, a); + } + guint32 ao = r*54 + g*182 + b*18; + return ((ao + 127) / 255) << 24; } +}; - unsigned char *in_data = NR_PIXBLOCK_PX(in); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - unsigned char r,g,b,a; - int x,y,x0,y0,x1,y1,i; - x0=in->area.x0; - y0=in->area.y0; - x1=in->area.x1; - y1=in->area.y1; - - switch(type){ - case COLORMATRIX_MATRIX: - { - if (values.size()!=20) { - g_warning("ColorMatrix: values parameter error. Wrong size: %i.", static_cast<int>(values.size())); - return -1; - } - double a04 = 255*values[4]; - double a14 = 255*values[9]; - double a24 = 255*values[14]; - double a34 = 255*values[19]; - for (x=x0;x<x1;x++){ - for (y=y0;y<y1;y++){ - i = ((x-x0) + (x1-x0)*(y-y0))*4; - r = in_data[i]; - g = in_data[i+1]; - b = in_data[i+2]; - a = in_data[i+3]; - out_data[i] = CLAMP_D_TO_U8( r*values[0] + g*values[1] + b*values[2] + a*values[3] + a04 ); // CLAMP includes rounding! - out_data[i+1] = CLAMP_D_TO_U8( r*values[5] + g*values[6] + b*values[7] + a*values[8] + a14 ); - out_data[i+2] = CLAMP_D_TO_U8( r*values[10] + g*values[11] + b*values[12] + a*values[13] + a24 ); - out_data[i+3] = CLAMP_D_TO_U8( r*values[15] + g*values[16] + b*values[17] + a*values[18] + a34 ); - } - } - } - break; - case COLORMATRIX_SATURATE: - { - double v = std::max(0.0,std::min(1.0,value)); // The standard says it should be between 0 and 1, and clamping it here makes it unnecessary to clamp the color values. - double a00 = 0.213+0.787*v, a01 = 0.715-0.715*v, a02 = 0.072-0.072*v; - double a10 = 0.213-0.213*v, a11 = 0.715+0.285*v, a12 = 0.072-0.072*v; - double a20 = 0.213-0.213*v, a21 = 0.715-0.715*v, a22 = 0.072+0.928*v; - for (x=x0;x<x1;x++){ - for (y=y0;y<y1;y++){ - i = ((x-x0) + (x1-x0)*(y-y0))*4; - r = in_data[i]; - g = in_data[i+1]; - b = in_data[i+2]; - a = in_data[i+3]; - out_data[i] = static_cast<unsigned char>( r*a00 + g*a01 + b*a02 + .5 ); - out_data[i+1] = static_cast<unsigned char>( r*a10 + g*a11 + b*a12 + .5 ); - out_data[i+2] = static_cast<unsigned char>( r*a20 + g*a21 + b*a22 + .5 ); - out_data[i+3] = a; - } - } - } - break; - case COLORMATRIX_HUEROTATE: - { - double coshue = cos(value * M_PI/180.0); - double sinhue = sin(value * M_PI/180.0); - double a00 = 0.213 + coshue*( 0.787) + sinhue*(-0.213); - double a01 = 0.715 + coshue*(-0.715) + sinhue*(-0.715); - double a02 = 0.072 + coshue*(-0.072) + sinhue*( 0.928); - double a10 = 0.213 + coshue*(-0.213) + sinhue*( 0.143); - double a11 = 0.715 + coshue*( 0.285) + sinhue*( 0.140); - double a12 = 0.072 + coshue*(-0.072) + sinhue*(-0.283); - double a20 = 0.213 + coshue*(-0.213) + sinhue*(-0.787); - double a21 = 0.715 + coshue*(-0.715) + sinhue*( 0.715); - double a22 = 0.072 + coshue*( 0.928) + sinhue*( 0.072); - if (in->mode==NR_PIXBLOCK_MODE_R8G8B8A8P) { - // Although it does not change the alpha channel, it can give "out-of-bound" results, and in this case the bound is determined by the alpha channel - for (x=x0;x<x1;x++){ - for (y=y0;y<y1;y++){ - i = ((x-x0) + (x1-x0)*(y-y0))*4; - r = in_data[i]; - g = in_data[i+1]; - b = in_data[i+2]; - a = in_data[i+3]; - - out_data[i] = static_cast<unsigned char>(std::max(0.0,std::min((double)a, r*a00 + g*a01 + b*a02 + .5 ))); - out_data[i+1] = static_cast<unsigned char>(std::max(0.0,std::min((double)a, r*a10 + g*a11 + b*a12 + .5 ))); - out_data[i+2] = static_cast<unsigned char>(std::max(0.0,std::min((double)a, r*a20 + g*a21 + b*a22 + .5 ))); - out_data[i+3] = a; - } - } - } else { - for (x=x0;x<x1;x++){ - for (y=y0;y<y1;y++){ - i = ((x-x0) + (x1-x0)*(y-y0))*4; - r = in_data[i]; - g = in_data[i+1]; - b = in_data[i+2]; - a = in_data[i+3]; - - out_data[i] = CLAMP_D_TO_U8( r*a00 + g*a01 + b*a02); - out_data[i+1] = CLAMP_D_TO_U8( r*a10 + g*a11 + b*a12); - out_data[i+2] = CLAMP_D_TO_U8( r*a20 + g*a21 + b*a22); - out_data[i+3] = a; - } - } - } - } - break; - case COLORMATRIX_LUMINANCETOALPHA: - for (x=x0;x<x1;x++){ - for (y=y0;y<y1;y++){ - i = ((x-x0) + (x1-x0)*(y-y0))*4; - r = in_data[i]; - g = in_data[i+1]; - b = in_data[i+2]; - out_data[i] = 0; - out_data[i+1] = 0; - out_data[i+2] = 0; - out_data[i+3] = static_cast<unsigned char>( r*0.2125 + g*0.7154 + b*0.0721 + .5 ); - } - } - break; - case COLORMATRIX_ENDTYPE: - break; +void FilterColorMatrix::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + cairo_surface_t *out = NULL; + if (type == COLORMATRIX_LUMINANCETOALPHA) { + out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_ALPHA); + } else { + out = ink_cairo_surface_create_identical(input); } - if (free_in_on_exit) { - nr_pixblock_release(in); - delete in; + switch (type) { + case COLORMATRIX_MATRIX: + ink_cairo_surface_filter(input, out, ColorMatrixMatrix(values)); + break; + case COLORMATRIX_SATURATE: + ink_cairo_surface_filter(input, out, ColorMatrixSaturate(value)); + break; + case COLORMATRIX_HUEROTATE: + ink_cairo_surface_filter(input, out, ColorMatrixHueRotate(value)); + break; + case COLORMATRIX_LUMINANCETOALPHA: + ink_cairo_surface_filter(input, out, ColorMatrixLuminanceToAlpha()); + break; + case COLORMATRIX_ENDTYPE: + default: + break; } - out->empty = FALSE; slot.set(_output, out); - return 0; + cairo_surface_destroy(out); +} + +bool FilterColorMatrix::can_handle_affine(Geom::Affine const &) +{ + return true; } void FilterColorMatrix::area_enlarge(NRRectL &/*area*/, Geom::Affine const &/*trans*/) @@ -207,7 +200,7 @@ void FilterColorMatrix::set_value(gdouble v){ value = v; } -void FilterColorMatrix::set_values(std::vector<gdouble> &v){ +void FilterColorMatrix::set_values(std::vector<gdouble> const &v){ values = v; } diff --git a/src/display/nr-filter-colormatrix.h b/src/display/nr-filter-colormatrix.h index 7a2395f5d..df851e0aa 100644 --- a/src/display/nr-filter-colormatrix.h +++ b/src/display/nr-filter-colormatrix.h @@ -12,14 +12,15 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include <vector> +#include <2geom/forward.h> #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" -#include<vector> namespace Inkscape { namespace Filters { +class FilterSlot; + enum FilterColorMatrixType { COLORMATRIX_MATRIX, COLORMATRIX_SATURATE, @@ -34,11 +35,13 @@ public: static FilterPrimitive *create(); virtual ~FilterColorMatrix(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); + virtual bool can_handle_affine(Geom::Affine const &); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); + virtual void set_type(FilterColorMatrixType type); virtual void set_value(gdouble value); - virtual void set_values(std::vector<gdouble> &values); + virtual void set_values(std::vector<gdouble> const &values); private: std::vector<gdouble> values; gdouble value; diff --git a/src/display/nr-filter-component-transfer.cpp b/src/display/nr-filter-component-transfer.cpp index 3fe8cbf4a..80bc07df8 100644 --- a/src/display/nr-filter-component-transfer.cpp +++ b/src/display/nr-filter-component-transfer.cpp @@ -10,13 +10,11 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "display/nr-filter-component-transfer.h" -#include "display/nr-filter-units.h" -#include "display/nr-filter-utils.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixops.h" #include <math.h> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" +#include "display/nr-filter-component-transfer.h" +#include "display/nr-filter-slot.h" namespace Inkscape { namespace Filters { @@ -32,170 +30,278 @@ FilterPrimitive * FilterComponentTransfer::create() { FilterComponentTransfer::~FilterComponentTransfer() {} -int FilterComponentTransfer::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in = slot.get(_input); +struct ComponentTransfer { + ComponentTransfer(guint32 color) + : _shift(color * 8) + , _mask(0xff << _shift) + {} +protected: + guint32 _shift; + guint32 _mask; +}; + +template <bool alpha> +struct ComponentTransferTable; + +template <> +struct ComponentTransferTable<false> : public ComponentTransfer { + ComponentTransferTable(guint32 color, std::vector<double> const &values) + : ComponentTransfer(color) + , _v(values.size()) + { + for (unsigned i = 0; i< values.size(); ++i) { + _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); + } + } + guint32 operator()(guint32 in) { + guint32 component = (in & _mask) >> _shift; + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return in; + + component = (255 * component + alpha/2) / alpha; + guint32 k = (_v.size() - 1) * component; + guint32 dx = k % 255; k /= 255; + component = _v[k]*255 + (_v[k+1] - _v[k])*dx; + component = (component + 127) / 255; + component = premul_alpha(component, alpha); + return (in & ~_mask) | (component << _shift); + } +private: + std::vector<guint32> _v; +}; + +template <> +struct ComponentTransferTable<true> { + ComponentTransferTable(std::vector<double> const &values) + : _v(values.size()) + { + for (unsigned i = 0; i< values.size(); ++i) { + _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); + } + } + guint32 operator()(guint32 in) { + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return in; + + guint32 k = (_v.size() - 1) * alpha; + guint32 dx = k % 255; k /= 255; + alpha = _v[k]*255 + (_v[k+1] - _v[k])*dx; + alpha = (alpha + 127) / 255; + return (in & 0x00ffffff) | (alpha << 24); + } +private: + std::vector<guint32> _v; +}; + +template <bool alpha> +struct ComponentTransferDiscrete; + +template <> +struct ComponentTransferDiscrete<false> : public ComponentTransfer { + ComponentTransferDiscrete(guint32 color, std::vector<double> const &values) + : ComponentTransfer(color) + , _v(values.size()) + { + for (unsigned i = 0; i< values.size(); ++i) { + _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); + } + } + guint32 operator()(guint32 in) { + guint32 component = (in & _mask) >> _shift; + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return in; + + component = (255 * component + alpha/2) / alpha; + guint32 k = (_v.size() - 1) * component / 255; + component = _v[k]; + component = premul_alpha(component, alpha); + return (in & ~_mask) | (component << _shift); + } +private: + std::vector<guint32> _v; +}; + +template <> +struct ComponentTransferDiscrete<true> { + ComponentTransferDiscrete(std::vector<double> const &values) + : _v(values.size()) + { + for (unsigned i = 0; i< values.size(); ++i) { + _v[i] = round(CLAMP(values[i], 0.0, 1.0) * 255); + } + } + guint32 operator()(guint32 in) { + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return in; + + guint32 k = (_v.size() - 1) * alpha / 255; + alpha = _v[k]; + return (in & 0x00ffffff) | (alpha << 24); + } +private: + std::vector<guint32> _v; +}; + +template <bool alpha> +struct ComponentTransferLinear; + +template <> +struct ComponentTransferLinear<false> : public ComponentTransfer { + ComponentTransferLinear(guint32 color, double intercept, double slope) + : ComponentTransfer(color) + , _intercept(round(intercept*255*255)) + , _slope(round(slope*255)) + {} + guint32 operator()(guint32 in) { + gint32 component = (in & _mask) >> _shift; + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return 0; - if (!in) { - g_warning("Missing source image for feComponentTransfer (in=%d)", _input); - return 1; + // TODO: this can probably be reduced to something simpler + component = (255 * component + alpha/2) / alpha; + component = pxclamp(_slope * component + _intercept, 0, 255*255); + component = (component + 127) / 255; + component = premul_alpha(component, alpha); + return (in & ~_mask) | (component << _shift); } +private: + gint32 _intercept; + gint32 _slope; +}; - int x0=in->area.x0; - int x1=in->area.x1; - int y0=in->area.y0; - int y1=in->area.y1; - - // this primitive is defined for RGBA values, - // thus convert them to that format before blending - bool free_in_on_exit = false; - if (in->mode != NR_PIXBLOCK_MODE_R8G8B8A8N && in->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - NRPixBlock *original_in = in; - in = new NRPixBlock; - nr_pixblock_setup_fast(in, NR_PIXBLOCK_MODE_R8G8B8A8N, - original_in->area.x0, original_in->area.y0, - original_in->area.x1, original_in->area.y1, - false); - nr_blit_pixblock_pixblock(in, original_in); - free_in_on_exit = true; +template <> +struct ComponentTransferLinear<true> { + ComponentTransferLinear(double intercept, double slope) + : _intercept(round(intercept*255*255)) + , _slope(round(slope*255)) + {} + guint32 operator()(guint32 in) { + gint32 alpha = (in & 0xff000000) >> 24; + alpha = pxclamp(_slope * alpha + _intercept, 0, 255*255); + alpha = (alpha + 127) / 255; + return (in & 0x00ffffff) | (alpha << 24); } - bool premultiplied = in->mode == NR_PIXBLOCK_MODE_R8G8B8A8P; - - NRPixBlock *out = new NRPixBlock; - nr_pixblock_setup_fast(out, in->mode, x0, y0, x1, y1, true); - - unsigned char *in_data = NR_PIXBLOCK_PX(in); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - - (void)in_data; - (void)out_data; - - int size = 4 * (y1-y0) * (x1-x0); - int i; - - int color=4; - while(color-->0) { - int _vsize = tableValues[color].size(); - double _intercept = intercept[color]; - double _slope = slope[color]; - double _amplitude = amplitude[color]; - double _exponent = exponent[color]; - double _offset = offset[color]; - switch(type[color]){ - case COMPONENTTRANSFER_TYPE_IDENTITY: - for(i=color;i<size;i+=4){ - out_data[i]=in_data[i]; - } - break; - case COMPONENTTRANSFER_TYPE_TABLE: - if (_vsize<=1){ - if (_vsize==1) { - g_warning("A component transfer table has to have at least two values."); - } - for(i=color;i<size;i+=4){ - out_data[i]=in_data[i]; - } - } else { - if (!premultiplied || color==3) { - std::vector<gdouble> _tableValues(tableValues[color]); - // Scale by 255 and add .5 to avoid having to add it later for rounding purposes - // Note that this means that CLAMP_D_TO_U8 cannot be used here (as it includes rounding!) - for(i=0;i<_vsize;i++) { - _tableValues[i] = std::max(0.,std::min(255.,255*_tableValues[i])) + .5; - } - for(i=color;i<size;i+=4){ - int k = FAST_DIVIDE<255>((_vsize-1) * in_data[i]); - double dx = ((_vsize-1) * in_data[i])/255.0 - k; - out_data[i] = static_cast<unsigned char>(_tableValues[k] + dx * (_tableValues[k+1] - _tableValues[k])); - } - } else { - std::vector<gdouble> _tableValues(tableValues[color]); - for(i=0;i<_vsize;i++) { - _tableValues[i] = std::max(0.,std::min(1.,_tableValues[i])); - } - for(i=color;i<size;i+=4){ - if (in_data[i+3-color]==0) continue; - int k = ((_vsize-1) * in_data[i]) / in_data[i+3-color]; - double dx = ((_vsize-1) * in_data[i]) / (double)in_data[i+3-color] - k; - out_data[i] = CLAMP_D_TO_U8_ALPHA(out_data[i+3-color] * (_tableValues[k] + dx * (_tableValues[k+1] - _tableValues[k])), out_data[i+3-color]); // CLAMP includes rounding! - } - } - } - break; - case COMPONENTTRANSFER_TYPE_DISCRETE: - if (_vsize==0){ - for(i=color;i<size;i+=4){ - out_data[i] = in_data[i]; - } - } else { - if (!premultiplied || color==3) { - std::vector<unsigned char> _tableValues(_vsize); - // Convert to unsigned char - for(i=0;i<_vsize;i++) { - _tableValues[i] = CLAMP_D_TO_U8(255*tableValues[color][i]); - } - for(i=color;i<size;i+=4){ - int k = FAST_DIVIDE<255>((_vsize-1) * in_data[i]); - out_data[i] = _tableValues[k]; - } - } else { - std::vector<gdouble> _tableValues(tableValues[color]); - for(i=0;i<_vsize;i++) { - _tableValues[i] = std::max(0.,std::min(1.,_tableValues[i])); - } - for(i=color;i<size;i+=4){ - if (in_data[i+3-color]==0) continue; - int k = ((_vsize-1) * in_data[i]) / in_data[i+3-color]; - out_data[i] = CLAMP_D_TO_U8_ALPHA(out_data[i+3-color] * _tableValues[k], out_data[i+3-color]); - } - } - } - break; - case COMPONENTTRANSFER_TYPE_LINEAR: - if (!premultiplied || color==3) { - _intercept = 255*_intercept; - for(i=color;i<size;i+=4){ - out_data[i] = CLAMP_D_TO_U8(_slope * in_data[i] + _intercept); // CLAMP includes rounding! - } - } else { - for(i=color;i<size;i+=4){ - if (in_data[i+3-color]==0) continue; - double out = _slope * in_data[i] / in_data[i+3-color] + _intercept; - out_data[i] = CLAMP_D_TO_U8_ALPHA(out_data[i+3-color] * out, out_data[i+3-color]); - } - } - break; - case COMPONENTTRANSFER_TYPE_GAMMA: - if (!premultiplied || color==3) { - _amplitude *= pow(255.0, -_exponent+1); // The input should be divided by 255, then exponentiated and then multiplied by 255 again, instead the amplitude is modified accordingly. - _offset = 255*_offset; - for(i=color;i<size;i+=4){ - out_data[i] = CLAMP_D_TO_U8(_amplitude * pow((double)in_data[i], _exponent) + _offset); - } - } else { - for(i=color;i<size;i+=4){ - if (in_data[i+3-color]==0) continue; - double out = _amplitude * pow((double)in_data[i] / in_data[i+3-color], _exponent) + _offset; - out_data[i] = CLAMP_D_TO_U8_ALPHA(out_data[i+3-color] * out, out_data[i+3-color]); - } - } - break; - case COMPONENTTRANSFER_TYPE_ERROR: - //TODO: report an error here - g_warning("Component tranfer type \"error\"."); - break; - default: - g_warning("Invalid tranfer type %d.", type[color]); +private: + gint32 _intercept; + gint32 _slope; +}; + +template <bool alpha> +struct ComponentTransferGamma; + +template <> +struct ComponentTransferGamma<false> : public ComponentTransfer { + ComponentTransferGamma(guint32 color, double amplitude, double exponent, double offset) + : ComponentTransfer(color) + , _amplitude(amplitude) + , _exponent(exponent) + , _offset(offset) + {} + guint32 operator()(guint32 in) { + double component = (in & _mask) >> _shift; + guint32 alpha = (in & 0xff000000) >> 24; + if (alpha == 0) return 0; + + double alphaf = alpha; + component /= alphaf; + component = _amplitude * pow(component, _exponent) + _offset; + guint32 cpx = pxclamp(component * alphaf, 0, 255); + return (in & ~_mask) | (cpx << _shift); + } +private: + double _amplitude; + double _exponent; + double _offset; +}; + +template <> +struct ComponentTransferGamma<true> { + ComponentTransferGamma(double amplitude, double exponent, double offset) + : _amplitude(amplitude) + , _exponent(exponent) + , _offset(offset) + {} + guint32 operator()(guint32 in) { + double alpha = (in & 0xff000000) >> 24; + alpha /= 255.0; + alpha = _amplitude * pow(alpha, _exponent) + _offset; + guint32 cpx = pxclamp(alpha * 255.0, 0, 255); + return (in & 0x00ffffff) | (cpx << 24); + } +private: + double _amplitude; + double _exponent; + double _offset; +}; + +void FilterComponentTransfer::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); + //cairo_surface_t *outtemp = ink_cairo_surface_create_identical(out); + ink_cairo_surface_blit(input, out); + + // parameters: R = 0, G = 1, B = 2, A = 3 + // Cairo: R = 2, G = 1, B = 0, A = 3 + for (unsigned i = 0; i < 3; ++i) { + guint32 color = 2 - i; + switch (type[i]) { + case COMPONENTTRANSFER_TYPE_TABLE: + ink_cairo_surface_filter(out, out, + ComponentTransferTable<false>(color, tableValues[i])); + break; + case COMPONENTTRANSFER_TYPE_DISCRETE: + ink_cairo_surface_filter(out, out, + ComponentTransferDiscrete<false>(color, tableValues[i])); + break; + case COMPONENTTRANSFER_TYPE_LINEAR: + ink_cairo_surface_filter(out, out, + ComponentTransferLinear<false>(color, intercept[i], slope[i])); + break; + case COMPONENTTRANSFER_TYPE_GAMMA: + ink_cairo_surface_filter(out, out, + ComponentTransferGamma<false>(color, amplitude[i], exponent[i], offset[i])); + break; + case COMPONENTTRANSFER_TYPE_ERROR: + case COMPONENTTRANSFER_TYPE_IDENTITY: + default: + break; } + //ink_cairo_surface_blit(out, outtemp); } - if (free_in_on_exit) { - nr_pixblock_release(in); - delete in; + // fast paths for alpha channel + switch (type[3]) { + case COMPONENTTRANSFER_TYPE_TABLE: + ink_cairo_surface_filter(out, out, + ComponentTransferTable<true>(tableValues[3])); + break; + case COMPONENTTRANSFER_TYPE_DISCRETE: + ink_cairo_surface_filter(out, out, + ComponentTransferDiscrete<true>(tableValues[3])); + break; + case COMPONENTTRANSFER_TYPE_LINEAR: + ink_cairo_surface_filter(out, out, + ComponentTransferLinear<true>(intercept[3], slope[3])); + break; + case COMPONENTTRANSFER_TYPE_GAMMA: + ink_cairo_surface_filter(out, out, + ComponentTransferGamma<true>(amplitude[3], exponent[3], offset[3])); + break; + case COMPONENTTRANSFER_TYPE_ERROR: + case COMPONENTTRANSFER_TYPE_IDENTITY: + default: + break; } - out->empty = FALSE; slot.set(_output, out); - return 0; + cairo_surface_destroy(out); + //cairo_surface_destroy(outtemp); +} + +bool FilterComponentTransfer::can_handle_affine(Geom::Affine const &) +{ + return true; } void FilterComponentTransfer::area_enlarge(NRRectL &/*area*/, Geom::Affine const &/*trans*/) diff --git a/src/display/nr-filter-component-transfer.h b/src/display/nr-filter-component-transfer.h index 65b4d4079..89bc61403 100644 --- a/src/display/nr-filter-component-transfer.h +++ b/src/display/nr-filter-component-transfer.h @@ -12,14 +12,14 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" #include <vector> +#include "display/nr-filter-primitive.h" namespace Inkscape { namespace Filters { +class FilterSlot; + enum FilterComponentTransferType { COMPONENTTRANSFER_TYPE_IDENTITY, COMPONENTTRANSFER_TYPE_TABLE, @@ -35,7 +35,8 @@ public: static FilterPrimitive *create(); virtual ~FilterComponentTransfer(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); + virtual bool can_handle_affine(Geom::Affine const &); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); FilterComponentTransferType type[4]; diff --git a/src/display/nr-filter-composite.cpp b/src/display/nr-filter-composite.cpp index 41175ee07..d4cf47af4 100644 --- a/src/display/nr-filter-composite.cpp +++ b/src/display/nr-filter-composite.cpp @@ -12,77 +12,11 @@ #include <cmath> #include "2geom/isnan.h" -#include "filters/composite.h" +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter-composite.h" -#include "display/nr-filter-pixops.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" -#include "display/nr-filter-utils.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-pixops.h" - -inline void -composite_over(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_COMPOSEPPP_1111(a[0],a[3],b[0]); - r[1] = NR_COMPOSEPPP_1111(a[1],a[3],b[1]); - r[2] = NR_COMPOSEPPP_1111(a[2],a[3],b[2]); - r[3] = NR_COMPOSEPPP_1111(a[3],a[3],b[3]); -} - -inline void -composite_in(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(a[0] * b[3]); - r[1] = NR_NORMALIZE_21(a[1] * b[3]); - r[2] = NR_NORMALIZE_21(a[2] * b[3]); - r[3] = NR_NORMALIZE_21(a[3] * b[3]); -} - -inline void -composite_out(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(a[0] * (255 - b[3])); - r[1] = NR_NORMALIZE_21(a[1] * (255 - b[3])); - r[2] = NR_NORMALIZE_21(a[2] * (255 - b[3])); - r[3] = NR_NORMALIZE_21(a[3] * (255 - b[3])); -} - -inline void -composite_atop(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(a[0] * b[3] + b[0] * (255 - a[3])); - r[1] = NR_NORMALIZE_21(a[1] * b[3] + b[1] * (255 - a[3])); - r[2] = NR_NORMALIZE_21(a[2] * b[3] + b[2] * (255 - a[3])); - r[3] = b[3]; -} - -inline void -composite_xor(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = NR_NORMALIZE_21(a[0] * (255 - b[3]) + b[0] * (255 - a[3])); - r[1] = NR_NORMALIZE_21(a[1] * (255 - b[3]) + b[1] * (255 - a[3])); - r[2] = NR_NORMALIZE_21(a[2] * (255 - b[3]) + b[2] * (255 - a[3])); - r[3] = NR_NORMALIZE_21(a[3] * (255 - b[3]) + b[3] * (255 - a[3])); -} - -// BUGBUG / TODO -// This makes arithmetic compositing non re-entrant and non thread safe. -static int arith_k1, arith_k2, arith_k3, arith_k4; -inline void -composite_arithmetic(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - using Inkscape::Filters::clamp3; - r[0] = NR_NORMALIZE_31(clamp3(arith_k1 * a[0] * b[0] - + arith_k2 * a[0] + arith_k3 * b[0] + arith_k4)); - r[1] = NR_NORMALIZE_31(clamp3(arith_k1 * a[1] * b[1] - + arith_k2 * a[1] + arith_k3 * b[1] + arith_k4)); - r[2] = NR_NORMALIZE_31(clamp3(arith_k1 * a[2] * b[2] - + arith_k2 * a[2] + arith_k3 * b[2] + arith_k4)); - r[3] = NR_NORMALIZE_31(clamp3(arith_k1 * a[3] * b[3] - + arith_k2 * a[3] + arith_k3 * b[3] + arith_k4)); -} namespace Inkscape { namespace Filters { @@ -99,85 +33,77 @@ FilterPrimitive * FilterComposite::create() { FilterComposite::~FilterComposite() {} -int FilterComposite::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in1 = slot.get(_input); - NRPixBlock *in2 = slot.get(_input2); - NRPixBlock *original_in1 = in1; - NRPixBlock *original_in2 = in2; - NRPixBlock *out; - - // Bail out if either one of source images is missing - if (!in1 || !in2) { - g_warning("Missing source image for feComposite (in=%d in2=%d)", _input, _input2); - return 1; - } - - out = new NRPixBlock; - NRRectL out_area; - nr_rect_l_union(&out_area, &in1->area, &in2->area); - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8P, - out_area.x0, out_area.y0, out_area.x1, out_area.y1, - true); - - // Blending modes are defined for premultiplied RGBA values, - // thus convert them to that format before blending - if (in1->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - in1 = nr_pixblock_new_fast(NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in1->area.x0, original_in1->area.y0, - original_in1->area.x1, original_in1->area.y1, - false); - nr_blit_pixblock_pixblock(in1, original_in1); - } - if (in2->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - in2 = nr_pixblock_new_fast(NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in2->area.x0, original_in2->area.y0, - original_in2->area.x1, original_in2->area.y1, - false); - nr_blit_pixblock_pixblock(in2, original_in2); +struct ComposeArithmetic { + ComposeArithmetic(double k1, double k2, double k3, double k4) + : _k1(round(k1 * 255)) + , _k2(round(k2 * 255*255)) + , _k3(round(k3 * 255*255)) + , _k4(round(k4 * 255*255*255)) + {} + guint32 operator()(guint32 in1, guint32 in2) { + EXTRACT_ARGB32(in1, aa, ra, ga, ba) + EXTRACT_ARGB32(in2, ab, rb, gb, bb) + + gint32 ao = _k1*aa*ab + _k2*aa + _k3*ab + _k4; + gint32 ro = _k1*ra*rb + _k2*ra + _k3*rb + _k4; + gint32 go = _k1*ga*gb + _k2*ga + _k3*gb + _k4; + gint32 bo = _k1*ba*bb + _k2*ba + _k3*bb + _k4; + + ao = (pxclamp(ao, 0, 255*255*255) + (255*255/2)) / (255*255); + ro = (pxclamp(ro, 0, 255*255*255) + (255*255/2)) / (255*255); + go = (pxclamp(go, 0, 255*255*255) + (255*255/2)) / (255*255); + bo = (pxclamp(bo, 0, 255*255*255) + (255*255/2)) / (255*255); + + ASSEMBLE_ARGB32(pxout, ao, ro, go, bo) + return pxout; } +private: + gint32 _k1, _k2, _k3, _k4; +}; - /* pixops_mix is defined in display/nr-filter-pixops.h - * It mixes the two input images with the function given as template - * and places the result in output image. - */ - switch (op) { +void FilterComposite::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input1 = slot.getcairo(_input); + cairo_surface_t *input2 = slot.getcairo(_input2); + + cairo_surface_t *out = ink_cairo_surface_create_output(input1, input2); + + if (op == COMPOSITE_ARITHMETIC) { + ink_cairo_surface_blend(input1, input2, out, ComposeArithmetic(k1, k2, k3, k4)); + } else { + ink_cairo_surface_blit(input2, out); + cairo_t *ct = cairo_create(out); + cairo_set_source_surface(ct, input1, 0, 0); + switch(op) { case COMPOSITE_IN: - pixops_mix<composite_in>(*out, *in1, *in2); + cairo_set_operator(ct, CAIRO_OPERATOR_IN); break; case COMPOSITE_OUT: - pixops_mix<composite_out>(*out, *in1, *in2); + cairo_set_operator(ct, CAIRO_OPERATOR_OUT); break; case COMPOSITE_ATOP: - pixops_mix<composite_atop>(*out, *in1, *in2); + cairo_set_operator(ct, CAIRO_OPERATOR_ATOP); break; case COMPOSITE_XOR: - pixops_mix<composite_xor>(*out, *in1, *in2); - break; - case COMPOSITE_ARITHMETIC: - arith_k1 = (int)round(k1 * 255); - arith_k2 = (int)round(k2 * 255 * 255); - arith_k3 = (int)round(k3 * 255 * 255); - arith_k4 = (int)round(k4 * 255 * 255 * 255); - pixops_mix<composite_arithmetic>(*out, *in1, *in2); + cairo_set_operator(ct, CAIRO_OPERATOR_XOR); break; - case COMPOSITE_DEFAULT: case COMPOSITE_OVER: + case COMPOSITE_DEFAULT: default: - pixops_mix<composite_over>(*out, *in1, *in2); + // OVER is the default operator break; + } + cairo_paint(ct); + cairo_destroy(ct); } - if (in1 != original_in1) { - nr_pixblock_free(in1); - } - if (in2 != original_in2) { - nr_pixblock_free(in2); - } - - out->empty = FALSE; slot.set(_output, out); + cairo_surface_destroy(out); +} - return 0; +bool FilterComposite::can_handle_affine(Geom::Affine const &) +{ + return true; } void FilterComposite::set_input(int input) { diff --git a/src/display/nr-filter-composite.h b/src/display/nr-filter-composite.h index 45114a92c..930898830 100644 --- a/src/display/nr-filter-composite.h +++ b/src/display/nr-filter-composite.h @@ -26,7 +26,8 @@ public: static FilterPrimitive *create(); virtual ~FilterComposite(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &); + virtual bool can_handle_affine(Geom::Affine const &); virtual void set_input(int input); virtual void set_input(int input, int slot); diff --git a/src/display/nr-filter-convolve-matrix.cpp b/src/display/nr-filter-convolve-matrix.cpp index f5cc7175a..06e28b074 100644 --- a/src/display/nr-filter-convolve-matrix.cpp +++ b/src/display/nr-filter-convolve-matrix.cpp @@ -10,10 +10,13 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include <vector> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter-convolve-matrix.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" -#include <vector> namespace Inkscape { namespace Filters { @@ -28,186 +31,139 @@ FilterPrimitive * FilterConvolveMatrix::create() { FilterConvolveMatrix::~FilterConvolveMatrix() {} -template<bool PREMULTIPLIED, bool PRESERVE_ALPHA, bool X_LOWER, bool X_UPPER, bool Y_LOWER, bool Y_UPPER> -static inline void convolve2D_XY(unsigned int const x, unsigned int const y, unsigned char *const out_data, unsigned char const *const in_data, unsigned int const width, unsigned int const height, double const *const kernel, unsigned int const orderX, unsigned int const orderY, unsigned int const targetX, unsigned int const targetY, double const bias) { - double result_R = 0; - double result_G = 0; - double result_B = 0; - double result_A = 0; - - unsigned int iBegin = Y_LOWER ? targetY-y : 0; // Note that to prevent signed/unsigned problems this requires that y<=targetY (which is true) - unsigned int iEnd = Y_UPPER ? height+targetY-y : orderY; // And this requires that y<=height+targetY (which is trivially true), in addition it should be true that height+targetY-y<=orderY (or equivalently y>=height+targetY-orderY, which is true) - unsigned int jBegin = X_LOWER ? targetX-x : 0; - unsigned int jEnd = X_UPPER ? width+targetX-x : orderX; - - for (unsigned int i=iBegin; i<iEnd; i++){ - for (unsigned int j=jBegin; j<jEnd; j++){ - unsigned int index = 4*( x - targetX + j + width*(y - targetY + i) ); - unsigned int kernel_index = orderX-j-1 + orderX*(orderY-i-1); - double k = PREMULTIPLIED ? kernel[kernel_index] : in_data[index+3] * kernel[kernel_index]; - result_R += in_data[index+0] * k; - result_G += in_data[index+1] * k; - result_B += in_data[index+2] * k; - result_A += in_data[index+3] * kernel[kernel_index]; +enum PreserveAlphaMode { + PRESERVE_ALPHA, + NO_PRESERVE_ALPHA +}; + +template <PreserveAlphaMode preserve_alpha> +struct ConvolveMatrix : public SurfaceSynth { + ConvolveMatrix(cairo_surface_t *s, int targetX, int targetY, int orderX, int orderY, + double divisor, double bias, std::vector<double> const &kernel) + : SurfaceSynth(s) + , _kernel(kernel.size()) + , _targetX(targetX) + , _targetY(targetY) + , _orderX(orderX) + , _orderY(orderY) + , _bias(bias) + { + for (unsigned i = 0; i < _kernel.size(); ++i) { + _kernel[i] = kernel[i] / divisor; } - } - - unsigned int const out_index = 4*( x + width*y ); - if (PRESERVE_ALPHA) { - out_data[out_index+3] = in_data[out_index+3]; - } else if (PREMULTIPLIED) { - out_data[out_index+3] = CLAMP_D_TO_U8(result_A + 255*bias); - } else { - out_data[out_index+3] = CLAMP_D_TO_U8(result_A + bias); - } - if (PREMULTIPLIED) { - out_data[out_index+0] = CLAMP_D_TO_U8_ALPHA(result_R + out_data[out_index+3]*bias, out_data[out_index+3]); // CLAMP includes rounding! - out_data[out_index+1] = CLAMP_D_TO_U8_ALPHA(result_G + out_data[out_index+3]*bias, out_data[out_index+3]); - out_data[out_index+2] = CLAMP_D_TO_U8_ALPHA(result_B + out_data[out_index+3]*bias, out_data[out_index+3]); - } else if (out_data[out_index+3]==0) { - out_data[out_index+0] = 0; // TODO: Is there a more sensible value that can be used here? - out_data[out_index+1] = 0; - out_data[out_index+2] = 0; - } else { - out_data[out_index+0] = CLAMP_D_TO_U8(result_R / out_data[out_index+3] + bias); // CLAMP includes rounding! - out_data[out_index+1] = CLAMP_D_TO_U8(result_G / out_data[out_index+3] + bias); - out_data[out_index+2] = CLAMP_D_TO_U8(result_B / out_data[out_index+3] + bias); - } -} - -template<bool PREMULTIPLIED, bool PRESERVE_ALPHA, bool Y_LOWER, bool Y_UPPER> -static inline void convolve2D_Y(unsigned int const y, unsigned char *const out_data, unsigned char const *const in_data, unsigned int const width, unsigned int const height, double const *const kernel, unsigned int const orderX, unsigned int const orderY, unsigned int const targetX, unsigned int const targetY, double const bias) { - // See convolve2D below for rationale. - - unsigned int const lowerEnd = std::min(targetX,width); - unsigned int const upperBegin = width - std::min<unsigned int>(width,orderX - 1u - targetX); - unsigned int const midXBegin = std::min(lowerEnd,upperBegin); - unsigned int const midXEnd = std::max(lowerEnd,upperBegin); - - for (unsigned int x=0; x<midXBegin; x++) { - convolve2D_XY<PREMULTIPLIED,PRESERVE_ALPHA,true,false,Y_LOWER,Y_UPPER>(x, y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } - if (lowerEnd==upperBegin) { - // Do nothing, empty mid section - } else if (lowerEnd<upperBegin) { - // In the middle no bounds have to be adjusted - for (unsigned int x=midXBegin; x<midXEnd; x++) { - convolve2D_XY<PREMULTIPLIED,PRESERVE_ALPHA,false,false,Y_LOWER,Y_UPPER>(x, y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); + // the matrix is given rotated 180 degrees + // which corresponds to reverse element order + std::reverse(_kernel.begin(), _kernel.end()); + } + + guint32 operator()(int x, int y) const { + int startx = std::max(0, x - _targetX); + int starty = std::max(0, y - _targetY); + int endx = std::min(_w, startx + _orderX); + int endy = std::min(_h, starty + _orderY); + int limitx = endx - startx; + int limity = endy - starty; + double suma = 0.0, sumr = 0.0, sumg = 0.0, sumb = 0.0; + + for (int i = 0; i < limity; ++i) { + for (int j = 0; j < limitx; ++j) { + guint32 px = pixelAt(startx + j, starty + i); + double coeff = _kernel[i * _orderX + j]; + EXTRACT_ARGB32(px, a,r,g,b) + + sumr += r * coeff; + sumg += g * coeff; + sumb += b * coeff; + if (preserve_alpha == NO_PRESERVE_ALPHA) { + suma += a * coeff; + } + } } - } else { - // In the middle both bounds have to be adjusted - for (unsigned int x=midXBegin; x<midXEnd; x++) { - convolve2D_XY<PREMULTIPLIED,PRESERVE_ALPHA,true,true,Y_LOWER,Y_UPPER>(x, y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); + if (preserve_alpha == PRESERVE_ALPHA) { + suma = alphaAt(x, y); + } else { + suma += _bias * 255; } + + guint32 ao = pxclamp(round(suma), 0, 255); + guint32 ro = pxclamp(round(sumr + ao * _bias), 0, ao); + guint32 go = pxclamp(round(sumg + ao * _bias), 0, ao); + guint32 bo = pxclamp(round(sumb + ao * _bias), 0, ao); + ASSEMBLE_ARGB32(pxout, ao,ro,go,bo); + return pxout; } - for (unsigned int x=midXEnd; x<width; x++) { - convolve2D_XY<PREMULTIPLIED,PRESERVE_ALPHA,false,true,Y_LOWER,Y_UPPER>(x, y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } -} -template<bool PREMULTIPLIED, bool PRESERVE_ALPHA> -static void convolve2D(unsigned char *const out_data, unsigned char const *const in_data, unsigned int const width, unsigned int const height, double const *const kernel, unsigned int const orderX, unsigned int const orderY, unsigned int const targetX, unsigned int const targetY, double const _bias) { - double const bias = PREMULTIPLIED ? _bias : 255*_bias; // If we're using non-premultiplied values the bias is always multiplied by 255. +private: + std::vector<double> _kernel; + int _targetX, _targetY, _orderX, _orderY; + double _bias; +}; - // For the middle section it should hold that (for all i such that 0<=i<orderY): - // 0 <= y - targetY + i < height - // targetY <= y && y < height + targetY - orderY + 1 - // In other words, for y<targetY i's lower bound needs to be adjusted and for y>=height+targetY-orderY+1 i's upper bound needs to be adjusted. +void FilterConvolveMatrix::render_cairo(FilterSlot &slot) +{ + static bool bias_warning = false; + static bool edge_warning = false; - unsigned int const lowerEnd = std::min(targetY,height); - unsigned int const upperBegin = height - std::min<unsigned int>(height,orderY - 1u - targetY); - unsigned int const midYBegin = std::min(lowerEnd,upperBegin); - unsigned int const midYEnd = std::max(lowerEnd,upperBegin); + cairo_surface_t *input = slot.getcairo(_input); - for (unsigned int y=0; y<midYBegin; y++) { - convolve2D_Y<PREMULTIPLIED,PRESERVE_ALPHA,true,false>(y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } - if (lowerEnd==upperBegin) { - // Do nothing, empty mid section - } else if (lowerEnd<upperBegin) { - // In the middle no bounds have to be adjusted - for (unsigned int y=midYBegin; y<midYEnd; y++) { - convolve2D_Y<PREMULTIPLIED,PRESERVE_ALPHA,false,false>(y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } - } else { - // In the middle both bounds have to be adjusted - for (unsigned int y=midYBegin; y<midYEnd; y++) { - convolve2D_Y<PREMULTIPLIED,PRESERVE_ALPHA,true,true>(y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } - } - for (unsigned int y=midYEnd; y<height; y++) { - convolve2D_Y<PREMULTIPLIED,PRESERVE_ALPHA,false,true>(y, out_data, in_data, width, height, kernel, orderX, orderY, targetX, targetY, bias); - } -} - -int FilterConvolveMatrix::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feConvolveMatrix (in=%d)", _input); - return 1; - } if (orderX<=0 || orderY<=0) { g_warning("Empty kernel!"); - return 1; + return; } if (targetX<0 || targetX>=orderX || targetY<0 || targetY>=orderY) { g_warning("Invalid target!"); - return 1; + return; } if (kernelMatrix.size()!=(unsigned int)(orderX*orderY)) { - g_warning("kernelMatrix does not have orderX*orderY elements!"); - return 1; - } - - if (bias!=0) { - g_warning("It is unknown whether Inkscape's implementation of bias in feConvolveMatrix is correct!"); - // The SVG specification implies that feConvolveMatrix is defined for premultiplied colors (which makes sense). - // It also says that bias should simply be added to the result for each color (without taking the alpha into account) - // However, it also says that one purpose of bias is "to have .5 gray value be the zero response of the filter". - // It seems sensible to indeed support the latter behaviour instead of the former, but this does appear to go against the standard. + //g_warning("kernelMatrix does not have orderX*orderY elements!"); + return; + } + + cairo_surface_t *out = ink_cairo_surface_create_identical(input); + + if (bias!=0 && !bias_warning) { + g_warning("It is unknown whether Inkscape's implementation of bias in feConvolveMatrix " + "is correct!"); + bias_warning = true; + // The SVG specification implies that feConvolveMatrix is defined for premultiplied + // colors (which makes sense). It also says that bias should simply be added to the result + // for each color (without taking the alpha into account). However, it also says that one + // purpose of bias is "to have .5 gray value be the zero response of the filter". + // It seems sensible to indeed support the latter behaviour instead of the former, + // but this does appear to go against the standard. // Note that Batik simply does not support bias!=0 } - if (edgeMode!=CONVOLVEMATRIX_EDGEMODE_NONE) { + if (edgeMode!=CONVOLVEMATRIX_EDGEMODE_NONE && !edge_warning) { g_warning("Inkscape only supports edgeMode=\"none\" (and a filter uses a different one)!"); - // Note that to properly support edgeMode the interaction with area_enlarge should be well understood (and probably something needs to change) - // area_enlarge should NOT let Inkscape enlarge the area beyond the filter area, it should only enlarge the rendered area if a part of the object is rendered to make it overlapping (enough) with adjacent parts. + edge_warning = true; } - NRPixBlock *out = new NRPixBlock; + //guint32 *in_data = reinterpret_cast<guint32*>(cairo_image_surface_get_data(input)); + //guint32 *out_data = reinterpret_cast<guint32*>(cairo_image_surface_get_data(out)); - nr_pixblock_setup_fast(out, in->mode, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); - - unsigned char *in_data = NR_PIXBLOCK_PX(in); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - - unsigned int const width = in->area.x1 - in->area.x0; - unsigned int const height = in->area.y1 - in->area.y0; + //int width = cairo_image_surface_get_width(input); + //int height = cairo_image_surface_get_height(input); // Set up predivided kernel matrix - std::vector<double> kernel(kernelMatrix); + /*std::vector<double> kernel(kernelMatrix); for(size_t i=0; i<kernel.size(); i++) { kernel[i] /= divisor; // The code that creates this object makes sure that divisor != 0 - } + }*/ - if (in->mode==NR_PIXBLOCK_MODE_R8G8B8A8P) { - if (preserveAlpha) { - convolve2D<true,true>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, targetX, targetY, bias); - } else { - convolve2D<true,false>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, targetX, targetY, bias); - } + if (preserveAlpha) { + //convolve2D<true>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, + // targetX, targetY, bias); + ink_cairo_surface_synthesize(out, ConvolveMatrix<PRESERVE_ALPHA>(input, + targetX, targetY, orderX, orderY, divisor, bias, kernelMatrix)); } else { - if (preserveAlpha) { - convolve2D<false,true>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, targetX, targetY, bias); - } else { - convolve2D<false,false>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, targetX, targetY, bias); - } + //convolve2D<false>(out_data, in_data, width, height, &kernel.front(), orderX, orderY, + // targetX, targetY, bias); + ink_cairo_surface_synthesize(out, ConvolveMatrix<NO_PRESERVE_ALPHA>(input, + targetX, targetY, orderX, orderY, divisor, bias, kernelMatrix)); } - out->empty = FALSE; slot.set(_output, out); - return 0; + cairo_surface_destroy(out); } void FilterConvolveMatrix::set_targetX(int coord) { @@ -256,10 +212,6 @@ void FilterConvolveMatrix::area_enlarge(NRRectL &area, Geom::Affine const &/*tra area.y1 += orderY - targetY - 1; } -FilterTraits FilterConvolveMatrix::get_input_traits() { - return TRAIT_PARALLER; -} - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-convolve-matrix.h b/src/display/nr-filter-convolve-matrix.h index 50d97f1a0..d13738260 100644 --- a/src/display/nr-filter-convolve-matrix.h +++ b/src/display/nr-filter-convolve-matrix.h @@ -13,14 +13,14 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" #include "libnr/nr-rect-l.h" #include <vector> namespace Inkscape { namespace Filters { +class FilterSlot; + enum FilterConvolveMatrixEdgeMode { CONVOLVEMATRIX_EDGEMODE_DUPLICATE, CONVOLVEMATRIX_EDGEMODE_WRAP, @@ -34,9 +34,8 @@ public: static FilterPrimitive *create(); virtual ~FilterConvolveMatrix(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); void set_targetY(int coord); void set_targetX(int coord); diff --git a/src/display/nr-filter-diffuselighting.cpp b/src/display/nr-filter-diffuselighting.cpp index 8e764f6d4..0a46a5c86 100644 --- a/src/display/nr-filter-diffuselighting.cpp +++ b/src/display/nr-filter-diffuselighting.cpp @@ -4,26 +4,25 @@ * Authors: * Niko Kiirala <niko@kiirala.com> * Jean-Rene Reinhard <jr@komite.net> + * Krzysztof Kosiński <tweenk.pl@gmail.com> * - * Copyright (C) 2007 authors + * Copyright (C) 2007-2010 Authors * * Released under GNU GPL, read the file 'COPYING' for more information */ #include <glib/gmessages.h> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-3dutils.h" #include "display/nr-arena-item.h" #include "display/nr-filter-diffuselighting.h" -#include "display/nr-filter-getalpha.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" #include "display/nr-light.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" #include "libnr/nr-rect-l.h" -#include "color.h" namespace Inkscape { namespace Filters { @@ -43,146 +42,134 @@ FilterPrimitive * FilterDiffuseLighting::create() { FilterDiffuseLighting::~FilterDiffuseLighting() {} -int FilterDiffuseLighting::render(FilterSlot &slot, FilterUnits const &units) { - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feDiffuseLighting (in=%d)", _input); - return 1; +struct DiffuseLight : public SurfaceSynth { + DiffuseLight(cairo_surface_t *bumpmap, double scale, double kd) + : SurfaceSynth(bumpmap) + , _scale(scale) + , _kd(kd) + {} + +protected: + guint32 diffuseLighting(int x, int y, NR::Fvector const &light, NR::Fvector const &light_components) { + NR::Fvector normal = surfaceNormalAt(x, y, _scale); + double k = _kd * NR::scalar_product(normal, light); + + guint32 r = CLAMP_D_TO_U8(k * light_components[LIGHT_RED]); + guint32 g = CLAMP_D_TO_U8(k * light_components[LIGHT_GREEN]); + guint32 b = CLAMP_D_TO_U8(k * light_components[LIGHT_BLUE]); + + ASSEMBLE_ARGB32(pxout, 255,r,g,b) + return pxout; + } + double _scale, _kd; +}; + +struct DiffuseDistantLight : public DiffuseLight { + DiffuseDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, + double scale, double diffuse_constant) + : DiffuseLight(bumpmap, scale, diffuse_constant) + { + DistantLight dl(light, color); + dl.light_vector(_lightv); + dl.light_components(_light_components); } - NRPixBlock *out = new NRPixBlock; - - int w = in->area.x1 - in->area.x0; - int h = in->area.y1 - in->area.y0; - int x0 = in->area.x0; - int y0 = in->area.y0; - int i, j; - //As long as FilterRes and kernel unit is not supported we hardcode the - //default value - int dx = 1; //TODO setup - int dy = 1; //TODO setup - //surface scale - Geom::Affine trans = units.get_matrix_primitiveunits2pb(); - gdouble ss = surfaceScale * trans[0]; - gdouble kd = diffuseConstant; //diffuse lighting constant - - NR::Fvector L, N, LC; - gdouble inter; - - nr_pixblock_setup_fast(out, in->mode, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); - unsigned char *data_i = NR_PIXBLOCK_PX (in); - unsigned char *data_o = NR_PIXBLOCK_PX (out); - //No light, nothing to do + guint32 operator()(int x, int y) { + return diffuseLighting(x, y, _lightv, _light_components); + } +private: + NR::Fvector _lightv, _light_components; +}; + +struct DiffusePointLight : public DiffuseLight { + DiffusePointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, + Geom::Affine const &trans, double scale, double diffuse_constant, double x0, double y0) + : DiffuseLight(bumpmap, scale, diffuse_constant) + , _light(light, color, trans) + , _x0(x0) + , _y0(y0) + { + _light.light_components(_light_components); + } + + guint32 operator()(int x, int y) { + NR::Fvector light; + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + return diffuseLighting(x, y, light, _light_components); + } +private: + PointLight _light; + NR::Fvector _light_components; + double _x0, _y0; +}; + +struct DiffuseSpotLight : public DiffuseLight { + DiffuseSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, + Geom::Affine const &trans, double scale, double diffuse_constant, double x0, double y0) + : DiffuseLight(bumpmap, scale, diffuse_constant) + , _light(light, color, trans) + , _x0(x0) + , _y0(y0) + {} + + guint32 operator()(int x, int y) { + NR::Fvector light, light_components; + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_components(light_components, light); + return diffuseLighting(x, y, light, light_components); + } +private: + SpotLight _light; + double _x0, _y0; +}; + +void FilterDiffuseLighting::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); + + Geom::Rect slot_area = slot.get_slot_area(); + Geom::Point p = slot_area.min(); + Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); + double x0 = p[Geom::X], y0 = p[Geom::Y]; + double scale = surfaceScale * trans.descrim(); + switch (light_type) { - case DISTANT_LIGHT: - //the light vector is constant - { - DistantLight *dl = new DistantLight(light.distant, lighting_color); - dl->light_vector(L); - dl->light_components(LC); - //finish the work - for (i = 0, j = 0; i < w*h; i++) { - NR::compute_surface_normal(N, ss, in, i / w, i % w, dx, dy); - inter = kd * NR::scalar_product(N, L); - - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_RED]); // CLAMP includes rounding! - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_GREEN]); - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_BLUE]); - data_o[j++] = 255; - } - out->empty = FALSE; - delete dl; - } - break; - case POINT_LIGHT: - { - PointLight *pl = new PointLight(light.point, lighting_color, trans); - pl->light_components(LC); - //TODO we need a reference to the filter to determine primitiveUnits - //if objectBoundingBox is used, use a different matrix for light_vector - // UPDATE: trans is now correct matrix from primitiveUnits to - // pixblock coordinates - //finish the work - for (i = 0, j = 0; i < w*h; i++) { - NR::compute_surface_normal(N, ss, in, i / w, i % w, dx, dy); - pl->light_vector(L, - i % w + x0, - i / w + y0, - ss * (double) data_i[4*i+3]/ 255); - inter = kd * NR::scalar_product(N, L); - - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_RED]); - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_GREEN]); - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_BLUE]); - data_o[j++] = 255; - } - out->empty = FALSE; - delete pl; - } - break; - case SPOT_LIGHT: - { - SpotLight *sl = new SpotLight(light.spot, lighting_color, trans); - //TODO we need a reference to the filter to determine primitiveUnits - //if objectBoundingBox is used, use a different matrix for light_vector - // UPDATE: trans is now correct matrix from primitiveUnits to - // pixblock coordinates - //finish the work - for (i = 0, j = 0; i < w*h; i++) { - NR::compute_surface_normal(N, ss, in, i / w, i % w, dx, dy); - sl->light_vector(L, - i % w + x0, - i / w + y0, - ss * (double) data_i[4*i+3]/ 255); - sl->light_components(LC, L); - inter = kd * NR::scalar_product(N, L); - - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_RED]); - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_GREEN]); - data_o[j++] = CLAMP_D_TO_U8(inter * LC[LIGHT_BLUE]); - data_o[j++] = 255; - } - out->empty = FALSE; - delete sl; - } - break; - //else unknown light source, doing nothing - case NO_LIGHT: - default: - { - if (light_type != NO_LIGHT) - g_warning("unknown light source %d", light_type); - for (i = 0; i < w*h; i++) { - data_o[4*i+3] = 255; - } - out->empty = false; - } + case DISTANT_LIGHT: + ink_cairo_surface_synthesize(out, + DiffuseDistantLight(input, light.distant, lighting_color, scale, diffuseConstant)); + break; + case POINT_LIGHT: + ink_cairo_surface_synthesize(out, + DiffusePointLight(input, light.point, lighting_color, trans, scale, diffuseConstant, x0, y0)); + break; + case SPOT_LIGHT: + ink_cairo_surface_synthesize(out, + DiffuseSpotLight(input, light.spot, lighting_color, trans, scale, diffuseConstant, x0, y0)); + break; + default: { + cairo_t *ct = cairo_create(out); + cairo_set_source_rgba(ct, 0,0,0,1); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); + } break; } - - //finishing + slot.set(_output, out); - //nr_pixblock_release(in); - //delete in; - return 0; + cairo_surface_destroy(out); } void FilterDiffuseLighting::area_enlarge(NRRectL &area, Geom::Affine const &trans) { // TODO: support kernelUnitLength - double scalex = std::fabs(trans[0]) + std::fabs(trans[1]); - double scaley = std::fabs(trans[2]) + std::fabs(trans[3]); - - //FIXME: no +2 should be there!... (noticable only for big scales at big zoom factor) - area.x0 -= (int)(scalex) + 2; - area.x1 += (int)(scalex) + 2; - area.y0 -= (int)(scaley) + 2; - area.y1 += (int)(scaley) + 2; -} -FilterTraits FilterDiffuseLighting::get_input_traits() { - return TRAIT_PARALLER; + // We expand the area by 1 in every direction to avoid artifacts on tile edges. + // However, it means that edge pixels will be incorrect. + area.x0 -= 1; + area.x1 += 1; + area.y0 -= 1; + area.y1 += 1; } } /* namespace Filters */ diff --git a/src/display/nr-filter-diffuselighting.h b/src/display/nr-filter-diffuselighting.h index f540bf4a5..6e39242f6 100644 --- a/src/display/nr-filter-diffuselighting.h +++ b/src/display/nr-filter-diffuselighting.h @@ -18,16 +18,22 @@ #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" -#include "filters/distantlight.h" -#include "filters/pointlight.h" -#include "filters/spotlight.h" -#include "color.h" + +class SPFeDistantLight; +class SPFePointLight; +class SPFeSpotLight; namespace Inkscape { namespace Filters { class FilterDiffuseLighting : public FilterPrimitive { public: + FilterDiffuseLighting(); + static FilterPrimitive *create(); + virtual ~FilterDiffuseLighting(); + virtual void render_cairo(FilterSlot &slot); + virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); + union { SPFeDistantLight *distant; SPFePointLight *point; @@ -37,13 +43,6 @@ public: gdouble diffuseConstant; gdouble surfaceScale; guint32 lighting_color; - - FilterDiffuseLighting(); - static FilterPrimitive *create(); - virtual ~FilterDiffuseLighting(); - virtual int render(FilterSlot &slot, FilterUnits const &units); - virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); private: }; diff --git a/src/display/nr-filter-displacement-map.cpp b/src/display/nr-filter-displacement-map.cpp index d71a691ef..fdaf2c887 100644 --- a/src/display/nr-filter-displacement-map.cpp +++ b/src/display/nr-filter-displacement-map.cpp @@ -9,11 +9,11 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter-displacement-map.h" #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixops.h" namespace Inkscape { namespace Filters { @@ -28,6 +28,7 @@ FilterPrimitive * FilterDisplacementMap::create() { FilterDisplacementMap::~FilterDisplacementMap() {} +#if 0 struct pixel_t { unsigned char channels[4]; inline unsigned char operator[](int c) const { return channels[c]; } @@ -147,7 +148,65 @@ static void performDisplacement(NRPixBlock const* texture, NRPixBlock const* map } } } +#endif + +struct Displace { + Displace(cairo_surface_t *texture, cairo_surface_t *map, + unsigned xch, unsigned ych, double scalex, double scaley) + : _texture(texture) + , _map(map) + , _xch(xch) + , _ych(ych) + , _scalex(scalex/255.0) + , _scaley(scaley/255.0) + {} + guint32 operator()(int x, int y) { + guint32 mappx = _map.pixelAt(x, y); + guint32 a = (mappx & 0xff000000) >> 24; + guint32 xpx = 0, ypx = 0; + double xtex = x, ytex = y; + if (a) { + guint32 xshift = _xch * 8, yshift = _ych * 8; + xpx = (mappx & (0xff << xshift)) >> xshift; + ypx = (mappx & (0xff << yshift)) >> yshift; + if (_xch != 3) xpx = unpremul_alpha(xpx, a); + if (_ych != 3) ypx = unpremul_alpha(ypx, a); + xtex += _scalex * (xpx - 127.5); + ytex += _scaley * (ypx - 127.5); + } + + if (xtex >= 0 && xtex < (_texture._w - 1) && + ytex >= 0 && ytex < (_texture._h - 1)) + { + return _texture.pixelAt(xtex, ytex); + } else { + return 0; + } + } +private: + SurfaceSynth _texture; + SurfaceSynth _map; + unsigned _xch, _ych; + double _scalex, _scaley; +}; + +void FilterDisplacementMap::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *texture = slot.getcairo(_input); + cairo_surface_t *map = slot.getcairo(_input2); + cairo_surface_t *out = ink_cairo_surface_create_identical(texture); + + Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); + double scalex = scale * trans.expansionX(); + double scaley = scale * trans.expansionY(); + + ink_cairo_surface_synthesize(out, Displace(texture, map, Xchannel, Ychannel, scalex, scaley)); + + slot.set(_output, out); + cairo_surface_destroy(out); +} +/* int FilterDisplacementMap::render(FilterSlot &slot, FilterUnits const &units) { NRPixBlock *texture = slot.get(_input); NRPixBlock *map = slot.get(_input2); @@ -212,7 +271,7 @@ int FilterDisplacementMap::render(FilterSlot &slot, FilterUnits const &units) { out->empty = FALSE; slot.set(_output, out); return 0; -} +}*/ void FilterDisplacementMap::set_input(int slot) { _input = slot; @@ -233,8 +292,26 @@ void FilterDisplacementMap::set_channel_selector(int s, FilterDisplacementMapCha return; } - if (s == 0) Xchannel = channel; - if (s == 1) Ychannel = channel; + // channel numbering: + // a = 3, r = 2, g = 1, b = 0 + // this way we can get the component value using: + // component = (color & (ch*8)) >> (ch*8) + unsigned ch = 4; + switch (channel) { + case DISPLACEMENTMAP_CHANNEL_ALPHA: + ch = 3; break; + case DISPLACEMENTMAP_CHANNEL_RED: + ch = 2; break; + case DISPLACEMENTMAP_CHANNEL_GREEN: + ch = 1; break; + case DISPLACEMENTMAP_CHANNEL_BLUE: + ch = 0; break; + default: break; + } + if (ch == 4) return; + + if (s == 0) Xchannel = ch; + if (s == 1) Ychannel = ch; } void FilterDisplacementMap::area_enlarge(NRRectL &area, Geom::Affine const &trans) @@ -252,10 +329,6 @@ void FilterDisplacementMap::area_enlarge(NRRectL &area, Geom::Affine const &tran area.y1 += (int)(scaley)+2; } -FilterTraits FilterDisplacementMap::get_input_traits() { - return TRAIT_PARALLER; -} - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-displacement-map.h b/src/display/nr-filter-displacement-map.h index 1dad1873a..aec4b7eb6 100644 --- a/src/display/nr-filter-displacement-map.h +++ b/src/display/nr-filter-displacement-map.h @@ -31,15 +31,13 @@ public: virtual void set_input(int input, int slot); virtual void set_scale(double s); virtual void set_channel_selector(int s, FilterDisplacementMapChannelSelector channel); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); private: double scale; int _input2; - FilterDisplacementMapChannelSelector Xchannel; - FilterDisplacementMapChannelSelector Ychannel; + unsigned Xchannel, Ychannel; }; } /* namespace Filters */ diff --git a/src/display/nr-filter-flood.cpp b/src/display/nr-filter-flood.cpp index eb1cf13a6..a015d3f1f 100644 --- a/src/display/nr-filter-flood.cpp +++ b/src/display/nr-filter-flood.cpp @@ -14,10 +14,12 @@ # include "config.h" #endif +#include "display/cairo-utils.h" #include "display/nr-filter-flood.h" -#include "display/nr-filter-utils.h" +#include "display/nr-filter-slot.h" #include "svg/svg-icc-color.h" #include "svg/svg-color.h" +#include "color.h" namespace Inkscape { namespace Filters { @@ -32,67 +34,40 @@ FilterPrimitive * FilterFlood::create() { FilterFlood::~FilterFlood() {} -int FilterFlood::render(FilterSlot &slot, FilterUnits const &units) { -//g_message("rendering feflood"); - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feFlood (in=%d)", _input); - return 1; +void FilterFlood::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + + double r = SP_RGBA32_R_F(color); + double g = SP_RGBA32_G_F(color); + double b = SP_RGBA32_B_F(color); + double a = opacity; + + #if ENABLE_LCMS + if (icc) { + guchar ru, gu, bu; + icc_color_to_sRGB(icc, &ru, &gu, &bu); + r = SP_COLOR_U_TO_F(ru); + g = SP_COLOR_U_TO_F(gu); + b = SP_COLOR_U_TO_F(bu); } + #endif - // Region being drawn on screen in screen coordinates. - int x0 = in->area.x0, y0 = in->area.y0; - int x1 = in->area.x1, y1 = in->area.y1; - int w = x1 - x0; - - // Set up pix block - NRPixBlock *out = new NRPixBlock; - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8N, x0, y0, x1, y1, true); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - - // Get RGBA values. - unsigned char r,g,b,a; - r = CLAMP_D_TO_U8((color >> 24) % 256); - g = CLAMP_D_TO_U8((color >> 16) % 256); - b = CLAMP_D_TO_U8((color >> 8) % 256); - a = CLAMP_D_TO_U8(opacity*255); - -#if ENABLE_LCMS - icc_color_to_sRGB(icc, &r, &g, &b); - //g_message("result: r:%d g:%d b:%d", r, g, b); -#endif //ENABLE_LCMS - - // Only fill primitive subregion - - // Get subregion in user units - Geom::Rect fp = filter_primitive_area( units ); - - // Need to convert to pixbuff units - Geom::Rect fp_pb = fp * units.get_matrix_user2pb(); - - // Make sure we are in pixbuff area - int fp_x0 = fp_pb.min()[Geom::X]; - int fp_x1 = fp_pb.max()[Geom::X]; - int fp_y0 = fp_pb.min()[Geom::Y]; - int fp_y1 = fp_pb.max()[Geom::Y]; - if( fp_x0 < x0 ) fp_x0 = x0; - if( fp_x1 > x1 ) fp_x1 = x1; - if( fp_y0 < y0 ) fp_y0 = y0; - if( fp_y1 > y1 ) fp_y1 = y1; - - // Do fill - for (int x=fp_x0; x < fp_x1; x++){ - for (int y=fp_y0; y < fp_y1; y++){ - out_data[ 4*((x - x0) + w*(y - y0)) ] = r; - out_data[ 4*((x - x0) + w*(y - y0)) + 1 ] = g; - out_data[ 4*((x - x0) + w*(y - y0)) + 2 ] = b; - out_data[ 4*((x - x0) + w*(y - y0)) + 3 ] = a; - } - } + cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); + cairo_t *ct = cairo_create(out); + cairo_set_source_rgba(ct, r, g, b, a); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); - out->empty = FALSE; slot.set(_output, out); - return 0; + cairo_surface_destroy(out); +} + +bool FilterFlood::can_handle_affine(Geom::Affine const &) +{ + // flood is a per-pixel primitive and is immutable under transformations + return true; } void FilterFlood::set_color(guint32 c) { diff --git a/src/display/nr-filter-flood.h b/src/display/nr-filter-flood.h index ebb7d4506..6db90d439 100644 --- a/src/display/nr-filter-flood.h +++ b/src/display/nr-filter-flood.h @@ -13,9 +13,8 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" -#include "svg/svg-color.h" + +class SVGICCColor; namespace Inkscape { namespace Filters { @@ -25,11 +24,12 @@ public: FilterFlood(); static FilterPrimitive *create(); virtual ~FilterFlood(); - + + virtual void render_cairo(FilterSlot &slot); + virtual bool can_handle_affine(Geom::Affine const &); virtual void set_opacity(double o); virtual void set_color(guint32 c); virtual void set_icc(SVGICCColor *icc_color); - virtual int render(FilterSlot &slot, FilterUnits const &units); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); private: double opacity; diff --git a/src/display/nr-filter-gaussian.cpp b/src/display/nr-filter-gaussian.cpp index 9b83c8647..326c37160 100644 --- a/src/display/nr-filter-gaussian.cpp +++ b/src/display/nr-filter-gaussian.cpp @@ -27,12 +27,12 @@ #include "2geom/isnan.h" +#include "display/cairo-utils.h" #include "display/nr-filter-primitive.h" #include "display/nr-filter-gaussian.h" #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" +#include "display/nr-filter-slot.h" #include <2geom/affine.h> #include "util/fixed_point.h" #include "preferences.h" @@ -82,24 +82,24 @@ static inline Tt round_cast(Ts v) { static Ts const rndoffset(.5); return static_cast<Tt>(v+rndoffset); } - +/* template<> inline unsigned char round_cast(double v) { // This (fast) rounding method is based on: // http://stereopsis.com/sree/fpu2006.html -#if G_BYTE_ORDER==G_LITTLE_ENDIAN
- double const dmr = 6755399441055744.0;
- v = v + dmr;
+#if G_BYTE_ORDER==G_LITTLE_ENDIAN + double const dmr = 6755399441055744.0; + v = v + dmr; return ((unsigned char*)&v)[0]; #elif G_BYTE_ORDER==G_BIG_ENDIAN - double const dmr = 6755399441055744.0;
- v = v + dmr;
+ double const dmr = 6755399441055744.0; + v = v + dmr; return ((unsigned char*)&v)[7]; #else static double const rndoffset(.5); - return static_cast<unsigned char>(v+rndoffset);
-#endif
-} + return static_cast<unsigned char>(v+rndoffset); +#endif +}*/ template<typename Tt, typename Ts> static inline Tt clip_round_cast(Ts const v) { @@ -142,7 +142,7 @@ FilterGaussian::~FilterGaussian() static int _effect_area_scr(double const deviation) { - return (int)std::ceil(deviation * 3.0); + return (int)std::ceil(std::fabs(deviation) * 3.0); } static void @@ -223,21 +223,6 @@ _effect_subsample_step_log2(double const deviation, int const quality) return stepsize_l2; } -/** - * Sanity check function for indexing pixblocks. - * Catches reading and writing outside the pixblock area. - * When enabled, decreases filter rendering speed massively. - */ -static inline void -_check_index(NRPixBlock const * const pb, int const location, int const line) -{ - if (false) { - int max_loc = pb->rs * (pb->area.y1 - pb->area.y0); - if (location < 0 || location >= max_loc) - g_warning("Location %d out of bounds (0 ... %d) at line %d", location, max_loc, line); - } -} - static void calcFilter(double const sigma, double b[N]) { assert(N==3); std::complex<double> const d1_org(1.40098, 1.00236); @@ -315,6 +300,14 @@ filter2D_IIR(PT *const dest, int const dstr1, int const dstr2, int const n1, int const n2, IIRValue const b[N+1], double const M[N*N], IIRValue *const tmpdata[], int const num_threads) { +#if G_BYTE_ORDER == G_LITTLE_ENDIAN + static unsigned int const alpha_PC = PC-1; + #define PREMUL_ALPHA_LOOP for(unsigned int c=0; c<PC-1; ++c) +#else + static unsigned int const alpha_PC = 0; + #define PREMUL_ALPHA_LOOP for(unsigned int c=1; c<PC; ++c) +#endif + #if HAVE_OPENMP #pragma omp parallel for num_threads(num_threads) #else @@ -350,8 +343,8 @@ filter2D_IIR(PT *const dest, int const dstr1, int const dstr2, calcTriggsSdikaInitialization<PC>(M, u, iplus, iplus, b[0], v); dstimg -= dstr1; if ( PREMULTIPLIED_ALPHA ) { - dstimg[PC-1] = clip_round_cast<PT>(v[0][PC-1]); - for(unsigned int c=0; c<PC-1; c++) dstimg[c] = clip_round_cast_varmax<PT>(v[0][c], v[0][PC-1], dstimg[PC-1]); + dstimg[alpha_PC] = clip_round_cast<PT>(v[0][alpha_PC]); + PREMUL_ALPHA_LOOP dstimg[c] = clip_round_cast_varmax<PT>(v[0][c], v[0][alpha_PC], dstimg[alpha_PC]); } else { for(unsigned int c=0; c<PC; c++) dstimg[c] = clip_round_cast<PT>(v[0][c]); } @@ -365,8 +358,8 @@ filter2D_IIR(PT *const dest, int const dstr1, int const dstr2, } dstimg -= dstr1; if ( PREMULTIPLIED_ALPHA ) { - dstimg[PC-1] = clip_round_cast<PT>(v[0][PC-1]); - for(unsigned int c=0; c<PC-1; c++) dstimg[c] = clip_round_cast_varmax<PT>(v[0][c], v[0][PC-1], dstimg[PC-1]); + dstimg[alpha_PC] = clip_round_cast<PT>(v[0][alpha_PC]); + PREMUL_ALPHA_LOOP dstimg[c] = clip_round_cast_varmax<PT>(v[0][c], v[0][alpha_PC], dstimg[alpha_PC]); } else { for(unsigned int c=0; c<PC; c++) dstimg[c] = clip_round_cast<PT>(v[0][c]); } @@ -481,401 +474,196 @@ filter2D_FIR(PT *const dst, int const dstr1, int const dstr2, } } -template<typename PT, unsigned int PC> static void -downsample(PT *const dst, int const dstr1, int const dstr2, int const dn1, int const dn2, - PT const *const src, int const sstr1, int const sstr2, int const sn1, int const sn2, - int const step1_l2, int const step2_l2) +gaussian_pass_IIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, + IIRValue **tmpdata, int num_threads) { - unsigned int const divisor_l2 = step1_l2+step2_l2; // step1*step2=2^(step1_l2+step2_l2) - unsigned int const round_offset = (1<<divisor_l2)/2; - int const step1 = 1<<step1_l2; - int const step2 = 1<<step2_l2; - int const step1_2 = step1/2; - int const step2_2 = step2/2; - for(int dc2 = 0 ; dc2 < dn2 ; dc2++) { - int const sc2_begin = (dc2<<step2_l2)-step2_2; - int const sc2_end = sc2_begin+step2; - for(int dc1 = 0 ; dc1 < dn1 ; dc1++) { - int const sc1_begin = (dc1<<step1_l2)-step1_2; - int const sc1_end = sc1_begin+step1; - unsigned int sum[PC]; - std::fill_n(sum, PC, 0); - for(int sc2 = sc2_begin ; sc2 < sc2_end ; sc2++) { - for(int sc1 = sc1_begin ; sc1 < sc1_end ; sc1++) { - for(unsigned int ch = 0 ; ch < PC ; ch++) { - sum[ch] += src[clip(sc2,0,sn2-1)*sstr2+clip(sc1,0,sn1-1)*sstr1+ch]; - } - } - } - for(unsigned int ch = 0 ; ch < PC ; ch++) { - dst[dc2*dstr2+dc1*dstr1+ch] = static_cast<PT>((sum[ch]+round_offset)>>divisor_l2); - } - } + // Filter variables + IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point) + double bf[N]; // computed filter coefficients + double M[N*N]; // matrix used for initialization procedure (has to be double) + + // Compute filter + calcFilter(deviation, bf); + for(size_t i=0; i<N; i++) bf[i] = -bf[i]; + b[0] = 1; // b[0] == alpha (scaling coefficient) + for(size_t i=0; i<N; i++) { + b[i+1] = bf[i]; + b[0] -= b[i+1]; } + + // Compute initialization matrix + calcTriggsSdikaM(bf, M); + + int stride = cairo_image_surface_get_stride(src); + int w = cairo_image_surface_get_width(src); + int h = cairo_image_surface_get_height(src); + if (d != Geom::X) std::swap(w, h); + + // Filter + switch (cairo_image_surface_get_format(src)) { + case CAIRO_FORMAT_A8: ///< Grayscale + filter2D_IIR<unsigned char,1,false>( + cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, + cairo_image_surface_get_data(src), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, + w, h, b, M, tmpdata, num_threads); + break; + case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA + filter2D_IIR<unsigned char,4,true>( + cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, + cairo_image_surface_get_data(src), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, + w, h, b, M, tmpdata, num_threads); + break; + default: + assert(false); + }; } -template<typename PT, unsigned int PC> static void -upsample(PT *const dst, int const dstr1, int const dstr2, unsigned int const dn1, unsigned int const dn2, - PT const *const src, int const sstr1, int const sstr2, unsigned int const sn1, unsigned int const sn2, - unsigned int const step1_l2, unsigned int const step2_l2) +gaussian_pass_FIR(Geom::Dim2 d, double deviation, cairo_surface_t *src, cairo_surface_t *dest, + int num_threads) { - assert(((sn1-1)<<step1_l2)>=dn1 && ((sn2-1)<<step2_l2)>=dn2); // The last pixel of the source image should fall outside the destination image - unsigned int const divisor_l2 = step1_l2+step2_l2; // step1*step2=2^(step1_l2+step2_l2) - unsigned int const round_offset = (1<<divisor_l2)/2; - unsigned int const step1 = 1<<step1_l2; - unsigned int const step2 = 1<<step2_l2; - for ( unsigned int sc2 = 0 ; sc2 < sn2-1 ; sc2++ ) { - unsigned int const dc2_begin = (sc2 << step2_l2); - unsigned int const dc2_end = std::min(dn2, dc2_begin+step2); - for ( unsigned int sc1 = 0 ; sc1 < sn1-1 ; sc1++ ) { - unsigned int const dc1_begin = (sc1 << step1_l2); - unsigned int const dc1_end = std::min(dn1, dc1_begin+step1); - for ( unsigned int byte = 0 ; byte < PC ; byte++) { - - // get 4 values at the corners of the pixel from src - PT a00 = src[sstr2* sc2 + sstr1* sc1 + byte]; - PT a10 = src[sstr2* sc2 + sstr1*(sc1+1) + byte]; - PT a01 = src[sstr2*(sc2+1) + sstr1* sc1 + byte]; - PT a11 = src[sstr2*(sc2+1) + sstr1*(sc1+1) + byte]; - - // initialize values for linear interpolation - unsigned int a0 = a00*step2/*+a01*0*/; - unsigned int a1 = a10*step2/*+a11*0*/; - - // iterate over the rectangle to be interpolated - for ( unsigned int dc2 = dc2_begin ; dc2 < dc2_end ; dc2++ ) { - - // prepare linear interpolation for this row - unsigned int a = a0*step1/*+a1*0*/+round_offset; - - for ( unsigned int dc1 = dc1_begin ; dc1 < dc1_end ; dc1++ ) { - - // simple linear interpolation - dst[dstr2*dc2 + dstr1*dc1 + byte] = static_cast<PT>(a>>divisor_l2); - - // compute a = a0*(ix-1)+a1*(xi+1)+round_offset - a = a - a0 + a1; - } - - // compute a0 = a00*(iy-1)+a01*(yi+1) and similar for a1 - a0 = a0 - a00 + a01; - a1 = a1 - a10 + a11; - } - } - } - } + int scr_len = _effect_area_scr(deviation); + // Filter kernel for x direction + FIRValue kernel[scr_len+1]; + _make_kernel(kernel, deviation); + + int stride = cairo_image_surface_get_stride(src); + int w = cairo_image_surface_get_width(src); + int h = cairo_image_surface_get_height(src); + if (d != Geom::X) std::swap(w, h); + + // Filter (x) + switch (cairo_image_surface_get_format(src)) { + case CAIRO_FORMAT_A8: ///< Grayscale + filter2D_FIR<unsigned char,1>( + cairo_image_surface_get_data(dest), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, + cairo_image_surface_get_data(src), d == Geom::X ? 1 : stride, d == Geom::X ? stride : 1, + w, h, kernel, scr_len, num_threads); + break; + case CAIRO_FORMAT_ARGB32: ///< Premultiplied 8 bit RGBA + filter2D_FIR<unsigned char,4>( + cairo_image_surface_get_data(dest), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, + cairo_image_surface_get_data(src), d == Geom::X ? 4 : stride, d == Geom::X ? stride : 4, + w, h, kernel, scr_len, num_threads); + break; + default: + assert(false); + }; } -int FilterGaussian::render(FilterSlot &slot, FilterUnits const &units) +void FilterGaussian::render_cairo(FilterSlot &slot) { - // TODO: Meaningful return values? (If they're checked at all.) - - /* in holds the input pixblock */ - NRPixBlock *original_in = slot.get(_input); - - /* If to either direction, the standard deviation is zero or - * input image is not defined, - * a transparent black image should be returned. */ - if (_deviation_x <= 0 || _deviation_y <= 0 || original_in == NULL) { - NRPixBlock *src = original_in; - if (src == NULL) { - g_warning("Missing source image for feGaussianBlur (in=%d)", _input); - // A bit guessing here, but source graphic is likely to be of - // right size - src = slot.get(NR_FILTER_SOURCEGRAPHIC); - } - NRPixBlock *out = new NRPixBlock; - nr_pixblock_setup_fast(out, src->mode, src->area.x0, src->area.y0, - src->area.x1, src->area.y1, true); - if (out->size != NR_PIXBLOCK_SIZE_TINY && out->data.px != NULL) { - out->empty = false; - slot.set(_output, out); - } - return 0; + cairo_surface_t *in = slot.getcairo(_input); + if (!in) return; + + // zero deviation = transparent black as output + if (_deviation_x <= 0 || _deviation_y <= 0) { + cairo_surface_t *blank = ink_cairo_surface_create_identical(in); + slot.set(_output, blank); + cairo_surface_destroy(blank); + return; } - // Gaussian blur is defined to operate on non-premultiplied color values. - // So, convert the input first it uses non-premultiplied color values. - // And please note that this should not be done AFTER resampling, as resampling a non-premultiplied image - // does not simply yield a non-premultiplied version of the resampled premultiplied image!!! - NRPixBlock *in = original_in; - if (in->mode == NR_PIXBLOCK_MODE_R8G8B8A8N) { - in = nr_pixblock_new_fast(NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in->area.x0, original_in->area.y0, - original_in->area.x1, original_in->area.y1, - false); - if (!in) { - // ran out of memory - return 0; - } - nr_blit_pixblock_pixblock(in, original_in); + Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); + + int w_orig = ink_cairo_surface_get_width(in); + int h_orig = ink_cairo_surface_get_height(in); + double deviation_x_orig = _deviation_x * trans.expansionX(); + double deviation_y_orig = _deviation_y * trans.expansionY(); + cairo_format_t fmt = cairo_image_surface_get_format(in); + int bytes_per_pixel = 0; + switch (fmt) { + case CAIRO_FORMAT_A8: + bytes_per_pixel = 1; break; + case CAIRO_FORMAT_ARGB32: + default: + bytes_per_pixel = 4; break; } - Geom::Affine trans = units.get_matrix_primitiveunits2pb(); - - // Some common constants - int const width_org = in->area.x1-in->area.x0, height_org = in->area.y1-in->area.y0; - double const deviation_x_org = _deviation_x * trans.expansionX(); - double const deviation_y_org = _deviation_y * trans.expansionY(); - int const PC = NR_PIXBLOCK_BPP(in); #if HAVE_OPENMP Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int const NTHREADS = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); + int threads = prefs->getIntLimited("/options/threading/numthreads", omp_get_num_procs(), 1, 256); #else - int const NTHREADS = 1; -#endif // HAVE_OPENMP + int threads = 1; +#endif - // Subsampling constants - int const quality = slot.get_blurquality(); - int const x_step_l2 = _effect_subsample_step_log2(deviation_x_org, quality); - int const y_step_l2 = _effect_subsample_step_log2(deviation_y_org, quality); - int const x_step = 1<<x_step_l2; - int const y_step = 1<<y_step_l2; - bool const resampling = x_step > 1 || y_step > 1; - int const width = resampling ? static_cast<int>(ceil(static_cast<double>(width_org)/x_step))+1 : width_org; - int const height = resampling ? static_cast<int>(ceil(static_cast<double>(height_org)/y_step))+1 : height_org; - double const deviation_x = deviation_x_org / x_step; - double const deviation_y = deviation_y_org / y_step; - int const scr_len_x = _effect_area_scr(deviation_x); - int const scr_len_y = _effect_area_scr(deviation_y); + int quality = slot.get_blurquality(); + int x_step = 1 << _effect_subsample_step_log2(deviation_x_orig, quality); + int y_step = 1 << _effect_subsample_step_log2(deviation_y_orig, quality); + bool resampling = x_step > 1 || y_step > 1; + int w_downsampled = resampling ? static_cast<int>(ceil(static_cast<double>(w_orig)/x_step))+1 : w_orig; + int h_downsampled = resampling ? static_cast<int>(ceil(static_cast<double>(h_orig)/y_step))+1 : h_orig; + double deviation_x = deviation_x_orig / x_step; + double deviation_y = deviation_y_orig / y_step; + int scr_len_x = _effect_area_scr(deviation_x); + int scr_len_y = _effect_area_scr(deviation_y); // Decide which filter to use for X and Y // This threshold was determined by trial-and-error for one specific machine, // so there's a good chance that it's not optimal. // Whatever you do, don't go below 1 (and preferrably not even below 2), as // the IIR filter gets unstable there. - bool const use_IIR_x = deviation_x > 3; - bool const use_IIR_y = deviation_y > 3; - - // new buffer for the subsampled output - NRPixBlock *out = new NRPixBlock; - nr_pixblock_setup_fast(out, in->mode, in->area.x0/x_step, in->area.y0/y_step, - in->area.x0/x_step+width, in->area.y0/y_step+height, true); - if (out->size != NR_PIXBLOCK_SIZE_TINY && out->data.px == NULL) { - // alas, we've accomplished a lot, but ran out of memory - so abort - if (in != original_in) nr_pixblock_free(in); - delete out; - return 0; - } + bool use_IIR_x = deviation_x > 3; + bool use_IIR_y = deviation_y > 3; + // Temporary storage for IIR filter // NOTE: This can be eliminated, but it reduces the precision a bit - IIRValue * tmpdata[NTHREADS]; - std::fill_n(tmpdata, NTHREADS, (IIRValue*)0); + IIRValue * tmpdata[threads]; + std::fill_n(tmpdata, threads, (IIRValue*)0); if ( use_IIR_x || use_IIR_y ) { - for(int i=0; i<NTHREADS; i++) { - tmpdata[i] = new IIRValue[std::max(width,height)*PC]; - if (tmpdata[i] == NULL) { - if (in != original_in) nr_pixblock_free(in); - nr_pixblock_release(out); - while(i-->0) { - delete[] tmpdata[i]; - } - delete out; - return 0; - } + for(int i = 0; i < threads; ++i) { + tmpdata[i] = new IIRValue[std::max(w_downsampled,h_downsampled)*bytes_per_pixel]; } } - // Resampling (if necessary), goes from in -> out (setting ssin to out if used) - NRPixBlock *ssin = in; - if ( resampling ) { - ssin = out; - // Downsample - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - downsample<unsigned char,1>(NR_PIXBLOCK_PX(out), 1, out->rs, width, height, NR_PIXBLOCK_PX(in), 1, in->rs, width_org, height_org, x_step_l2, y_step_l2); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - downsample<unsigned char,3>(NR_PIXBLOCK_PX(out), 3, out->rs, width, height, NR_PIXBLOCK_PX(in), 3, in->rs, width_org, height_org, x_step_l2, y_step_l2); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // downsample<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, width, height, NR_PIXBLOCK_PX(in), 4, in->rs, width_org, height_org, x_step_l2, y_step_l2); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - downsample<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, width, height, NR_PIXBLOCK_PX(in), 4, in->rs, width_org, height_org, x_step_l2, y_step_l2); - break; - default: - assert(false); - }; + cairo_surface_t *downsampled = NULL; + if (resampling) { + downsampled = cairo_surface_create_similar(in, cairo_surface_get_content(in), + w_downsampled, h_downsampled); + cairo_t *ct = cairo_create(downsampled); + cairo_scale(ct, static_cast<double>(w_downsampled)/w_orig, static_cast<double>(h_downsampled)/h_orig); + cairo_set_source_surface(ct, in, 0, 0); + cairo_paint(ct); + cairo_destroy(ct); + } else { + downsampled = ink_cairo_surface_copy(in); } + cairo_surface_flush(downsampled); - // Horizontal filtering, goes from ssin -> out (ssin might be equal to out, but these algorithms can be used in-place) - if (use_IIR_x) { - // Filter variables - IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point) - double bf[N]; // computed filter coefficients - double M[N*N]; // matrix used for initialization procedure (has to be double) - - // Compute filter (x) - calcFilter(deviation_x, bf); - for(size_t i=0; i<N; i++) bf[i] = -bf[i]; - b[0] = 1; // b[0] == alpha (scaling coefficient) - for(size_t i=0; i<N; i++) { - b[i+1] = bf[i]; - b[0] -= b[i+1]; + if (scr_len_x > 0) { + if (use_IIR_x) { + gaussian_pass_IIR(Geom::X, deviation_x, downsampled, downsampled, tmpdata, threads); + } else { + gaussian_pass_FIR(Geom::X, deviation_x, downsampled, downsampled, threads); } - - // Compute initialization matrix (x) - calcTriggsSdikaM(bf, M); - - // Filter (x) - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - filter2D_IIR<unsigned char,1,false>(NR_PIXBLOCK_PX(out), 1, out->rs, NR_PIXBLOCK_PX(ssin), 1, ssin->rs, width, height, b, M, tmpdata, NTHREADS); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - filter2D_IIR<unsigned char,3,false>(NR_PIXBLOCK_PX(out), 3, out->rs, NR_PIXBLOCK_PX(ssin), 3, ssin->rs, width, height, b, M, tmpdata, NTHREADS); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // filter2D_IIR<unsigned char,4,false>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, b, M, tmpdata, NTHREADS); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - filter2D_IIR<unsigned char,4,true >(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, b, M, tmpdata, NTHREADS); - break; - default: - assert(false); - }; - } else if ( scr_len_x > 0 ) { // !use_IIR_x - // Filter kernel for x direction - FIRValue kernel[scr_len_x+1]; - _make_kernel(kernel, deviation_x); - - // Filter (x) - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - filter2D_FIR<unsigned char,1>(NR_PIXBLOCK_PX(out), 1, out->rs, NR_PIXBLOCK_PX(ssin), 1, ssin->rs, width, height, kernel, scr_len_x, NTHREADS); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - filter2D_FIR<unsigned char,3>(NR_PIXBLOCK_PX(out), 3, out->rs, NR_PIXBLOCK_PX(ssin), 3, ssin->rs, width, height, kernel, scr_len_x, NTHREADS); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, kernel, scr_len_x, NTHREADS); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), 4, out->rs, NR_PIXBLOCK_PX(ssin), 4, ssin->rs, width, height, kernel, scr_len_x, NTHREADS); - break; - default: - assert(false); - }; - } else if ( out != ssin ) { // out can be equal to ssin if resampling is used - nr_blit_pixblock_pixblock(out, ssin); } - // Vertical filtering, goes from out -> out - if (use_IIR_y) { - // Filter variables - IIRValue b[N+1]; // scaling coefficient + filter coefficients (can be 10.21 fixed point) - double bf[N]; // computed filter coefficients - double M[N*N]; // matrix used for initialization procedure (has to be double) - - // Compute filter (y) - calcFilter(deviation_y, bf); - for(size_t i=0; i<N; i++) bf[i] = -bf[i]; - b[0] = 1; // b[0] == alpha (scaling coefficient) - for(size_t i=0; i<N; i++) { - b[i+1] = bf[i]; - b[0] -= b[i+1]; + if (scr_len_y > 0) { + if (use_IIR_y) { + gaussian_pass_IIR(Geom::Y, deviation_y, downsampled, downsampled, tmpdata, threads); + } else { + gaussian_pass_FIR(Geom::Y, deviation_y, downsampled, downsampled, threads); } - - // Compute initialization matrix (y) - calcTriggsSdikaM(bf, M); - - // Filter (y) - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - filter2D_IIR<unsigned char,1,false>(NR_PIXBLOCK_PX(out), out->rs, 1, NR_PIXBLOCK_PX(out), out->rs, 1, height, width, b, M, tmpdata, NTHREADS); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - filter2D_IIR<unsigned char,3,false>(NR_PIXBLOCK_PX(out), out->rs, 3, NR_PIXBLOCK_PX(out), out->rs, 3, height, width, b, M, tmpdata, NTHREADS); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // filter2D_IIR<unsigned char,4,false>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, b, M, tmpdata, NTHREADS); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - filter2D_IIR<unsigned char,4,true >(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, b, M, tmpdata, NTHREADS); - break; - default: - assert(false); - }; - } else if ( scr_len_y > 0 ) { // !use_IIR_y - // Filter kernel for y direction - FIRValue kernel[scr_len_y+1]; - _make_kernel(kernel, deviation_y); - - // Filter (y) - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - filter2D_FIR<unsigned char,1>(NR_PIXBLOCK_PX(out), out->rs, 1, NR_PIXBLOCK_PX(out), out->rs, 1, height, width, kernel, scr_len_y, NTHREADS); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - filter2D_FIR<unsigned char,3>(NR_PIXBLOCK_PX(out), out->rs, 3, NR_PIXBLOCK_PX(out), out->rs, 3, height, width, kernel, scr_len_y, NTHREADS); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, kernel, scr_len_y, NTHREADS); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - filter2D_FIR<unsigned char,4>(NR_PIXBLOCK_PX(out), out->rs, 4, NR_PIXBLOCK_PX(out), out->rs, 4, height, width, kernel, scr_len_y, NTHREADS); - break; - default: - assert(false); - }; } - for(int i=0; i<NTHREADS; i++) { - delete[] tmpdata[i]; // deleting a nullptr has no effect, so this is safe - } - - // Upsampling, stores (the upsampled) out using slot.set(_output, ...) - if ( !resampling ) { - // No upsampling needed - out->empty = FALSE; - slot.set(_output, out); + cairo_surface_mark_dirty(downsampled); + if (resampling) { + cairo_surface_t *upsampled = cairo_surface_create_similar(downsampled, cairo_surface_get_content(downsampled), + w_orig, h_orig); + cairo_t *ct = cairo_create(upsampled); + cairo_scale(ct, static_cast<double>(w_orig)/w_downsampled, static_cast<double>(h_orig)/h_downsampled); + cairo_set_source_surface(ct, downsampled, 0, 0); + cairo_paint(ct); + cairo_destroy(ct); + + slot.set(_output, upsampled); + cairo_surface_destroy(upsampled); + cairo_surface_destroy(downsampled); } else { - // New buffer for the final output, same resolution as the in buffer - NRPixBlock *finalout = new NRPixBlock; - nr_pixblock_setup_fast(finalout, in->mode, in->area.x0, in->area.y0, - in->area.x1, in->area.y1, true); - if (finalout->size != NR_PIXBLOCK_SIZE_TINY && finalout->data.px == NULL) { - // alas, we've accomplished a lot, but ran out of memory - so abort - if (in != original_in) nr_pixblock_free(in); - nr_pixblock_release(out); - delete out; - return 0; - } - - // Upsample - switch(in->mode) { - case NR_PIXBLOCK_MODE_A8: ///< Grayscale - upsample<unsigned char,1>(NR_PIXBLOCK_PX(finalout), 1, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 1, out->rs, width, height, x_step_l2, y_step_l2); - break; - case NR_PIXBLOCK_MODE_R8G8B8: ///< 8 bit RGB - upsample<unsigned char,3>(NR_PIXBLOCK_PX(finalout), 3, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 3, out->rs, width, height, x_step_l2, y_step_l2); - break; - //case NR_PIXBLOCK_MODE_R8G8B8A8N: ///< Normal 8 bit RGBA - // upsample<unsigned char,4>(NR_PIXBLOCK_PX(finalout), 4, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 4, out->rs, width, height, x_step_l2, y_step_l2); - // break; - case NR_PIXBLOCK_MODE_R8G8B8A8P: ///< Premultiplied 8 bit RGBA - upsample<unsigned char,4>(NR_PIXBLOCK_PX(finalout), 4, finalout->rs, width_org, height_org, NR_PIXBLOCK_PX(out), 4, out->rs, width, height, x_step_l2, y_step_l2); - break; - default: - assert(false); - }; - - // We don't need the out buffer anymore - nr_pixblock_release(out); - delete out; - - // The final out buffer gets returned - finalout->empty = FALSE; - slot.set(_output, finalout); + slot.set(_output, downsampled); + cairo_surface_destroy(downsampled); } - - // If we downsampled the input, clean up the downsampled data - if (in != original_in) nr_pixblock_free(in); - - return 0; } void FilterGaussian::area_enlarge(NRRectL &area, Geom::Affine const &trans) @@ -891,8 +679,13 @@ void FilterGaussian::area_enlarge(NRRectL &area, Geom::Affine const &trans) area.y1 += area_max; } -FilterTraits FilterGaussian::get_input_traits() { - return TRAIT_PARALLER; +bool FilterGaussian::can_handle_affine(Geom::Affine const &) +{ + // Previously we tried to be smart and return true for rotations. + // However, the transform passed here is NOT the total transform + // from filter user space to screen. + // TODO: fix this, or replace can_handle_affine() with isotropic(). + return false; } void FilterGaussian::set_deviation(double deviation) diff --git a/src/display/nr-filter-gaussian.h b/src/display/nr-filter-gaussian.h index 87d74ac63..811502016 100644 --- a/src/display/nr-filter-gaussian.h +++ b/src/display/nr-filter-gaussian.h @@ -14,12 +14,8 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" -#include "libnr/nr-pixblock.h" #include <2geom/forward.h> -#include "libnr/nr-rect-l.h" +#include "display/nr-filter-primitive.h" enum { BLUR_QUALITY_BEST = 2, @@ -38,9 +34,9 @@ public: static FilterPrimitive *create(); virtual ~FilterGaussian(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &m); - virtual FilterTraits get_input_traits(); + virtual bool can_handle_affine(Geom::Affine const &m); /** * Set the standard deviation value for gaussian blur. Deviation along diff --git a/src/display/nr-filter-getalpha.cpp b/src/display/nr-filter-getalpha.cpp deleted file mode 100644 index 7b5e2a101..000000000 --- a/src/display/nr-filter-getalpha.cpp +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Functions for extracting alpha channel from NRPixBlocks. - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2007 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "display/nr-filter-getalpha.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" - -namespace Inkscape { -namespace Filters { - -NRPixBlock *filter_get_alpha(NRPixBlock *src) -{ - NRPixBlock *dst = new NRPixBlock; - nr_pixblock_setup_fast(dst, NR_PIXBLOCK_MODE_R8G8B8A8P, - src->area.x0, src->area.y0, - src->area.x1, src->area.y1, false); - if (!dst || (dst->size != NR_PIXBLOCK_SIZE_TINY && dst->data.px == NULL)) { - g_warning("Memory allocation failed in filter_get_alpha"); - delete dst; - return NULL; - } - nr_blit_pixblock_pixblock(dst, src); - - unsigned char *data = NR_PIXBLOCK_PX(dst); - int end = dst->rs * (dst->area.y1 - dst->area.y0); - for (int i = 0 ; i < end ; i += 4) { - data[i + 0] = 0; - data[i + 1] = 0; - data[i + 2] = 0; - } - dst->empty = false; - - return dst; -} - -} /* namespace Filters */ -} /* namespace Inkscape */ - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-filter-getalpha.h b/src/display/nr-filter-getalpha.h deleted file mode 100644 index e279494b1..000000000 --- a/src/display/nr-filter-getalpha.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef __NR_FILTER_GETALPHA_H__ -#define __NR_FILTER_GETALPHA_H__ - -/* - * Functions for extracting alpha channel from NRPixBlocks. - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2007 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "libnr/nr-pixblock.h" - -namespace Inkscape { -namespace Filters { - -NRPixBlock *filter_get_alpha(NRPixBlock *src); - -} /* namespace Filters */ -} /* namespace Inkscape */ - -#endif /* __NR_FILTER_GETALPHA_H__ */ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-filter-image.cpp b/src/display/nr-filter-image.cpp index 9ecec69bf..0cb7901b3 100644 --- a/src/display/nr-filter-image.cpp +++ b/src/display/nr-filter-image.cpp @@ -12,25 +12,23 @@ */ #include "document.h" #include "sp-item.h" +#include "display/cairo-utils.h" #include "display/nr-arena.h" #include "display/nr-arena-item.h" #include "display/nr-filter.h" #include "display/nr-filter-image.h" #include "display/nr-filter-units.h" -#include "libnr/nr-compose-transform.h" #include "libnr/nr-rect-l.h" -#include "preferences.h" -#include "svg/svg-length.h" -#include "enums.h" namespace Inkscape { namespace Filters { -FilterImage::FilterImage() : - SVGElem(0), - document(0), - feImageHref(0), - image_pixbuf(0) +FilterImage::FilterImage() + : SVGElem(0) + , document(0) + , feImageHref(0) + , image_surface(0) + , broken_ref(false) { } FilterPrimitive * FilterImage::create() { @@ -39,76 +37,95 @@ FilterPrimitive * FilterImage::create() { FilterImage::~FilterImage() { - if (feImageHref) g_free(feImageHref); + if (feImageHref) + g_free(feImageHref); } -int FilterImage::render(FilterSlot &slot, FilterUnits const &units) { - if (!feImageHref) return 0; - - NRPixBlock* pb = NULL; - bool free_pb_on_exit = false; - - if(from_element){ - if (!SVGElem) return 0; - - // prep the document +void FilterImage::render_cairo(FilterSlot &slot) +{ + if (!feImageHref) + return; + + //cairo_surface_t *input = slot.getcairo(_input); + + Geom::Affine m = slot.get_units().get_matrix_user2filterunits().inverse(); + Geom::Point bbox_00 = Geom::Point(0,0) * m; + Geom::Point bbox_w0 = Geom::Point(1,0) * m; + Geom::Point bbox_0h = Geom::Point(0,1) * m; + double bbox_width = Geom::distance(bbox_00, bbox_w0); + double bbox_height = Geom::distance(bbox_00, bbox_0h); + + + // feImage is suppose to use the same parameters as a normal SVG image. + // If a width or height is set to zero, the image is not suppose to be displayed. + // This does not seem to be what Firefox or Opera does, nor does the W3C displacement + // filter test expect this behavior. If the width and/or height are zero, we use + // the width and height of the object bounding box. + if( feImageWidth == 0 ) feImageWidth = bbox_width; + if( feImageHeight == 0 ) feImageHeight = bbox_height; + + if (from_element) { + if (!SVGElem) return; + + // TODO: do not recreate the rendering tree every time + // TODO: the entire thing is a hack, we should give filter primitives an "update" method + // like the one for NRArenaItems document->ensureUpToDate(); + NRArena* arena = NRArena::create(); + Geom::OptRect optarea = SVGElem->getBounds(Geom::identity()); + if (!optarea) return; + unsigned const key = SPItem::display_key_new(1); NRArenaItem* ai = SVGElem->invoke_show(arena, key, SP_ITEM_SHOW_DISPLAY); + if (!ai) { g_warning("feImage renderer: error creating NRArenaItem for SVG Element"); nr_object_unref((NRObject *) arena); - return 0; + return; } - pb = new NRPixBlock; - free_pb_on_exit = true; - - Geom::OptRect area = SVGElem->getBounds(Geom::identity()); - - NRRectL rect; - rect.x0=area->min()[Geom::X]; - rect.x1=area->max()[Geom::X]; - rect.y0=area->min()[Geom::Y]; - rect.y1=area->max()[Geom::Y]; - - width = (int)(rect.x1-rect.x0); - height = (int)(rect.y1-rect.y0); - rowstride = 4*width; - has_alpha = true; - - if (image_pixbuf) g_free(image_pixbuf); - image_pixbuf = g_try_new(unsigned char, 4L * width * height); - if(image_pixbuf != NULL) - { - memset(image_pixbuf, 0x00, 4 * width * height); - - NRGC gc(NULL); - /* Update to renderable state */ - double sf = 1.0; - Geom::Affine t(Geom::Scale(sf, sf)); - nr_arena_item_set_transform(ai, &t); - gc.transform.setIdentity(); - nr_arena_item_invoke_update( ai, NULL, &gc, - NR_ARENA_ITEM_STATE_ALL, - NR_ARENA_ITEM_STATE_NONE ); - nr_pixblock_setup_extern(pb, NR_PIXBLOCK_MODE_R8G8B8A8N, - (int)rect.x0, (int)rect.y0, (int)rect.x1, (int)rect.y1, - image_pixbuf, 4 * width, FALSE, FALSE ); - - nr_arena_item_invoke_render(NULL, ai, &rect, pb, NR_ARENA_ITEM_RENDER_NO_CACHE); - } - else - { - g_warning("FilterImage::render: not enough memory to create pixel buffer. Need %ld.", 4L * width * height); - } + Geom::Rect area = *optarea; + Geom::Affine pu2pb = slot.get_units().get_matrix_primitiveunits2pb(); + + double scaleX = feImageWidth / area.width(); + double scaleY = feImageHeight / area.height(); + + Geom::Rect sa = slot.get_slot_area(); + cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + sa.width(), sa.height()); + cairo_t *ct = cairo_create(out); + cairo_translate(ct, -sa.min()[Geom::X], -sa.min()[Geom::Y]); + ink_cairo_transform(ct, pu2pb); // we are now in primitive units + cairo_translate(ct, feImageX, feImageY); + cairo_scale(ct, scaleX, scaleY); + + NRRectL render_rect; + render_rect.x0 = floor(area.left()); + render_rect.y0 = floor(area.top()); + render_rect.x1 = ceil(area.right()); + render_rect.y1 = ceil(area.bottom()); + cairo_translate(ct, render_rect.x0, render_rect.y0); + + // Update to renderable state + NRGC gc(NULL); + Geom::Affine t = Geom::identity(); + nr_arena_item_set_transform(ai, &t); + gc.transform.setIdentity(); + nr_arena_item_invoke_update(ai, NULL, &gc, + NR_ARENA_ITEM_STATE_ALL, + NR_ARENA_ITEM_STATE_NONE); + nr_arena_item_invoke_render(ct, ai, &render_rect, NULL, NR_ARENA_ITEM_RENDER_NO_CACHE); SVGElem->invoke_hide(key); - nr_object_unref((NRObject *) arena); - } + nr_object_unref((NRObject*) arena); + slot.set(_output, out); + cairo_surface_destroy(out); + return; + } - if (!image_pixbuf){ + if (!image && !broken_ref) { + broken_ref = true; try { /* TODO: If feImageHref is absolute, then use that (preferably handling the * case that it's not a file URI). Otherwise, go up the tree looking @@ -127,190 +144,92 @@ int FilterImage::render(FilterSlot &slot, FilterUnits const &units) { if ( !g_file_test( fullname, G_FILE_TEST_EXISTS ) ) { // Should display Broken Image png. g_warning("FilterImage::render: Can not find: %s", feImageHref ); + return; } image = Gdk::Pixbuf::create_from_file(fullname); if( fullname != feImageHref ) g_free( fullname ); } catch (const Glib::FileError & e) { - g_warning("caught Glib::FileError in FilterImage::render %i", e.code() ); - return 0; + g_warning("caught Glib::FileError in FilterImage::render: %s", e.what().data() ); + return; } catch (const Gdk::PixbufError & e) { - g_warning("Gdk::PixbufError in FilterImage::render: %i", e.code() ); - return 0; + g_warning("Gdk::PixbufError in FilterImage::render: %s", e.what().data() ); + return; } - if ( !image ) return 0; + if ( !image ) return; - // Native size of image - width = image->get_width(); - height = image->get_height(); - rowstride = image->get_rowstride(); - image_pixbuf = image->get_pixels(); - has_alpha = image->get_has_alpha(); - } + broken_ref = false; - // Viewport is filter primitive area (in user coordinates). - Geom::Rect vp = filter_primitive_area( units ); - double feImageX = vp.min()[Geom::X]; - double feImageY = vp.min()[Geom::Y]; - double feImageWidth = vp.width(); - double feImageHeight = vp.height(); - - // Now that we have the viewport, we must map image inside. - // Partially copied from sp-image.cpp. - - // Do nothing if preserveAspectRatio is "none". - if( aspect_align != SP_ASPECT_NONE ) { - - // Check aspect ratio of image vs. viewport - double feAspect = feImageHeight/feImageWidth; - double aspect = (double)height/(double)width; - bool ratio = (feAspect < aspect); - - double ax, ay; // Align side - switch( aspect_align ) { - case SP_ASPECT_XMIN_YMIN: - ax = 0.0; - ay = 0.0; - break; - case SP_ASPECT_XMID_YMIN: - ax = 0.5; - ay = 0.0; - break; - case SP_ASPECT_XMAX_YMIN: - ax = 1.0; - ay = 0.0; - break; - case SP_ASPECT_XMIN_YMID: - ax = 0.0; - ay = 0.5; - break; - case SP_ASPECT_XMID_YMID: - ax = 0.5; - ay = 0.5; - break; - case SP_ASPECT_XMAX_YMID: - ax = 1.0; - ay = 0.5; - break; - case SP_ASPECT_XMIN_YMAX: - ax = 0.0; - ay = 1.0; - break; - case SP_ASPECT_XMID_YMAX: - ax = 0.5; - ay = 1.0; - break; - case SP_ASPECT_XMAX_YMAX: - ax = 1.0; - ay = 1.0; - break; - default: - ax = 0.0; - ay = 0.0; - break; + bool has_alpha = image->get_has_alpha(); + if (!has_alpha) { + image = image->add_alpha(false, 0, 0, 0); } - if( aspect_clip == SP_ASPECT_SLICE ) { - // image clipped by viewbox - - if( ratio ) { - // clip top/bottom - feImageY -= ay * (feImageWidth * aspect - feImageHeight); - feImageHeight = feImageWidth * aspect; - } else { - // clip sides - feImageX -= ax * (feImageHeight / aspect - feImageWidth); - feImageWidth = feImageHeight / aspect; - } + // Native size of image + //width = image->get_width(); + //height = image->get_height(); + //rowstride = image->get_rowstride(); - } else { - // image fits into viewbox - - if( ratio ) { - // fit to height - feImageX += ax * (feImageWidth - feImageHeight / aspect ); - feImageWidth = feImageHeight / aspect; - } else { - // fit to width - feImageY += ay * (feImageHeight - feImageWidth * aspect); - feImageHeight = feImageWidth * aspect; - } - } - } + convert_pixbuf_normal_to_argb32(image->gobj()); - // Set up user coordinates to pix block transforms - double scaleX = width/feImageWidth; - double scaleY = height/feImageHeight; - Geom::Affine unit_trans = units.get_matrix_user2pb().inverse(); - - // Region being drawn on screen. Corresponds to Filter Region in current screen coordinates. - // Note, that the screen is refreshed in horizontal slices with y-axis inverted. - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feImage (in=%d)", _input); - return 1; - } - int x0 = in->area.x0, y0 = in->area.y0; - int x1 = in->area.x1, y1 = in->area.y1; - int w = x1 - x0; - - Geom::Affine d2s = Geom::Translate(x0, y0) * unit_trans * Geom::Translate(-feImageX,-feImageY) * Geom::Scale(scaleX, scaleY); - - // Set up pix block - NRPixBlock *out = new NRPixBlock; - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8P, x0, y0, x1, y1, true); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - int nr_arena_image_x_sample = prefs->getInt("/options/bitmapoversample/value", 1); - int nr_arena_image_y_sample = nr_arena_image_x_sample; - - - if (has_alpha) { - nr_R8G8B8A8_P_R8G8B8A8_P_R8G8B8A8_N_TRANSFORM(out_data, x1-x0, y1-y0, 4*w, image_pixbuf, width, height, rowstride, d2s, 255, nr_arena_image_x_sample, nr_arena_image_y_sample); - } else { - for (int x=x0; x < x1; x++){ - for (int y=y0; y < y1; y++){ - //TODO: use interpolation - // Temporarily add 0.5 so we sample center of "cell" - double indexX = scaleX * (((x+0.5) * unit_trans[0] + unit_trans[4]) - feImageX); - double indexY = scaleY * (((y+0.5) * unit_trans[3] + unit_trans[5]) - feImageY); - - // coordx == 0 and coordy == 0 must be included, but we protect - // against negative numbers which round up to 0 with (int). - int coordx = ( indexX >= 0 ? int( indexX ) : -1 ); - int coordy = ( indexY >= 0 ? int( indexY ) : -1 ); - if (coordx >= 0 && coordx < width && coordy >= 0 && coordy < height){ - out_data[4*((x - x0)+w*(y - y0)) ] = (unsigned char) image_pixbuf[3*coordx + rowstride*coordy ]; //Red - out_data[4*((x - x0)+w*(y - y0)) + 1] = (unsigned char) image_pixbuf[3*coordx + rowstride*coordy + 1]; //Green - out_data[4*((x - x0)+w*(y - y0)) + 2] = (unsigned char) image_pixbuf[3*coordx + rowstride*coordy + 2]; //Blue - out_data[4*((x - x0)+w*(y - y0)) + 3] = 255; //Alpha - } - } - } - } - if (free_pb_on_exit) { - nr_pixblock_release(pb); - delete pb; + image_surface = cairo_image_surface_create_for_data(image->get_pixels(), + CAIRO_FORMAT_ARGB32, image->get_width(), image->get_height(), image->get_rowstride()); } - out->empty = FALSE; + Geom::Rect sa = slot.get_slot_area(); + cairo_surface_t *out = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, + sa.width(), sa.height()); + + cairo_t *ct = cairo_create(out); + cairo_translate(ct, -sa.min()[Geom::X], -sa.min()[Geom::Y]); + // now ct is in pb coordinates + ink_cairo_transform(ct, slot.get_units().get_matrix_primitiveunits2pb()); + // now ct is in the coordinates of feImageX etc. + + // TODO: add preserveAspectRatio support here + + double scaleX = feImageWidth / image->get_width(); + double scaleY = feImageHeight / image->get_height(); + + cairo_translate(ct, feImageX, feImageY); + cairo_scale(ct, scaleX, scaleY); + cairo_set_source_surface(ct, image_surface, 0, 0); + cairo_paint(ct); + cairo_destroy(ct); + slot.set(_output, out); - return 0; +} + +bool FilterImage::can_handle_affine(Geom::Affine const &) +{ + return true; } void FilterImage::set_href(const gchar *href){ if (feImageHref) g_free (feImageHref); feImageHref = (href) ? g_strdup (href) : NULL; + + if (image_surface) { + cairo_surface_destroy(image_surface); + } + image.reset(); + broken_ref = false; } void FilterImage::set_document(SPDocument *doc){ document = doc; } +void FilterImage::set_region(SVGLength x, SVGLength y, SVGLength width, SVGLength height) { + feImageX=x.computed; + feImageY=y.computed; + feImageWidth=width.computed; + feImageHeight=height.computed; +} + void FilterImage::set_align( unsigned int align ) { aspect_align = align; } @@ -319,10 +238,6 @@ void FilterImage::set_clip( unsigned int clip ) { aspect_clip = clip; } -FilterTraits FilterImage::get_input_traits() { - return TRAIT_PARALLER; -} - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-image.h b/src/display/nr-filter-image.h index ecbc9597d..0651109ec 100644 --- a/src/display/nr-filter-image.h +++ b/src/display/nr-filter-image.h @@ -27,10 +27,11 @@ public: static FilterPrimitive *create(); virtual ~FilterImage(); - virtual int render(FilterSlot &slot, FilterUnits const &units); - virtual FilterTraits get_input_traits(); + virtual void render_cairo(FilterSlot &slot); + virtual bool can_handle_affine(Geom::Affine const &); void set_document( SPDocument *document ); void set_href(const gchar *href); + void set_region(SVGLength x, SVGLength y, SVGLength width, SVGLength height); void set_align( unsigned int align ); void set_clip( unsigned int clip ); bool from_element; @@ -39,12 +40,11 @@ public: private: SPDocument *document; gchar *feImageHref; - guint8* image_pixbuf; Glib::RefPtr<Gdk::Pixbuf> image; - int width, height, rowstride; - unsigned int aspect_align : 4; - unsigned int aspect_clip : 1; - bool has_alpha; + cairo_surface_t *image_surface; + float feImageX, feImageY, feImageWidth, feImageHeight; + unsigned int aspect_align, aspect_clip; + bool broken_ref; }; } /* namespace Filters */ diff --git a/src/display/nr-filter-merge.cpp b/src/display/nr-filter-merge.cpp index 971dcb80f..51d3975cb 100644 --- a/src/display/nr-filter-merge.cpp +++ b/src/display/nr-filter-merge.cpp @@ -9,28 +9,11 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include <cmath> #include <vector> - -#include "2geom/isnan.h" -#include "filters/merge.h" +#include "display/cairo-utils.h" #include "display/nr-filter-merge.h" -#include "display/nr-filter-pixops.h" #include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-pixops.h" - -inline void -composite_over(unsigned char *r, unsigned char const *a, unsigned char const *b) -{ - r[0] = a[0] + NR_NORMALIZE_21(b[0] * (255 - a[3])); - r[1] = a[1] + NR_NORMALIZE_21(b[1] * (255 - a[3])); - r[2] = a[2] + NR_NORMALIZE_21(b[2] * (255 - a[3])); - r[3] = a[3] + NR_NORMALIZE_21(b[3] * (255 - a[3])); -} namespace Inkscape { namespace Filters { @@ -46,70 +29,42 @@ FilterPrimitive * FilterMerge::create() { FilterMerge::~FilterMerge() {} -int FilterMerge::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in[_input_image.size()]; - NRPixBlock *original_in[_input_image.size()]; - - for (unsigned int i = 0 ; i < _input_image.size() ; i++) { - in[i] = slot.get(_input_image[i]); - original_in[i] = in[i]; - } - - NRPixBlock *out; - - // Bail out if one of source images is missing - for (unsigned int i = 0 ; i < _input_image.size() ; i++) { - bool missing = false; - if (!in[i]) { - g_warning("Missing source image for feMerge (number=%d slot=%d)", i, _input_image[i]); - missing = true; - } - if (missing) return 1; - } - - out = new NRPixBlock; - NRRectL out_area = in[0]->area; - for (unsigned int i = 1 ; i < _input_image.size() ; i++) { - nr_rect_l_union(&out_area, &out_area, &in[i]->area); - } - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8P, - out_area.x0, out_area.y0, out_area.x1, out_area.y1, - true); - - // Merge is defined for premultiplied RGBA values, thus convert them to - // that format before blending - for (unsigned int i = 0 ; i < _input_image.size() ; i++) { - if (in[i]->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - in[i] = new NRPixBlock; - nr_pixblock_setup_fast(in[i], NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in[i]->area.x0, - original_in[i]->area.y0, - original_in[i]->area.x1, - original_in[i]->area.y1, - false); - nr_blit_pixblock_pixblock(in[i], original_in[i]); +void FilterMerge::render_cairo(FilterSlot &slot) +{ + if (_input_image.size() == 0) return; + + // output is RGBA if at least one input is RGBA + bool rgba32 = false; + cairo_surface_t *out = NULL; + for (std::vector<int>::iterator i = _input_image.begin(); i != _input_image.end(); ++i) { + cairo_surface_t *in = slot.getcairo(*i); + if (cairo_surface_get_content(in) == CAIRO_CONTENT_COLOR_ALPHA) { + out = ink_cairo_surface_create_identical(in); + rgba32 = true; + break; } } - /* pixops_mix is defined in display/nr-filter-pixops.h - * It mixes the two input images with the function given as template - * and places the result in output image. - */ - for (unsigned int i = 0 ; i < _input_image.size() ; i++) { - pixops_mix<composite_over>(*out, *in[i], *out); + if (!rgba32) { + out = ink_cairo_surface_create_identical(slot.getcairo(_input_image[0])); } + cairo_t *out_ct = cairo_create(out); - for (unsigned int i = 0 ; i < _input_image.size() ; i++) { - if (in[i] != original_in[i]) { - nr_pixblock_release(in[i]); - delete in[i]; - } + for (std::vector<int>::iterator i = _input_image.begin(); i != _input_image.end(); ++i) { + cairo_surface_t *in = slot.getcairo(*i); + cairo_set_source_surface(out_ct, in, 0, 0); + cairo_paint(out_ct); } - out->empty = FALSE; + cairo_destroy(out_ct); slot.set(_output, out); + cairo_surface_destroy(out); +} - return 0; +bool FilterMerge::can_handle_affine(Geom::Affine const &) +{ + // Merge is a per-pixel primitive and is immutable under transformations + return true; } void FilterMerge::set_input(int slot) { diff --git a/src/display/nr-filter-merge.h b/src/display/nr-filter-merge.h index 715f20d83..263fc8026 100644 --- a/src/display/nr-filter-merge.h +++ b/src/display/nr-filter-merge.h @@ -13,11 +13,7 @@ */ #include <vector> - -#include "filters/merge.h" #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { @@ -28,7 +24,8 @@ public: static FilterPrimitive *create(); virtual ~FilterMerge(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &); + virtual bool can_handle_affine(Geom::Affine const &); virtual void set_input(int input); virtual void set_input(int input, int slot); diff --git a/src/display/nr-filter-morphology.cpp b/src/display/nr-filter-morphology.cpp index ceb2a2b9d..c79667d3e 100644 --- a/src/display/nr-filter-morphology.cpp +++ b/src/display/nr-filter-morphology.cpp @@ -10,9 +10,12 @@ */ #include <cmath> +#include <algorithm> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter-morphology.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" -#include "libnr/nr-blit.h" namespace Inkscape { namespace Filters { @@ -28,94 +31,126 @@ FilterPrimitive * FilterMorphology::create() { FilterMorphology::~FilterMorphology() {} -int FilterMorphology::render(FilterSlot &slot, FilterUnits const &units) { - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feMorphology (in=%d)", _input); - return 1; - } - - NRPixBlock *out = new NRPixBlock; - - // this primitive is defined for premultiplied RGBA values, - // thus convert them to that format - bool free_in_on_exit = false; - if (in->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - NRPixBlock *original_in = in; - in = new NRPixBlock; - nr_pixblock_setup_fast(in, NR_PIXBLOCK_MODE_R8G8B8A8P, - original_in->area.x0, original_in->area.y0, - original_in->area.x1, original_in->area.y1, - true); - nr_blit_pixblock_pixblock(in, original_in); - free_in_on_exit = true; - } +enum MorphologyOp { + ERODE, + DILATE +}; + +namespace { + +/* This performs one "half" of the morphology operation by calculating + * the componentwise extreme in the specified axis with the given radius. + * Performing the operation one axis at a time gives us a MASSIVE performance boost + * at large morphology radii. Extreme of row extremes is equal to the extreme + * of components, so this doesn't change the result. */ +template <MorphologyOp OP, Geom::Dim2 axis> +struct Morphology : public SurfaceSynth { + Morphology(cairo_surface_t *in, double xradius) + : SurfaceSynth(in) + , _radius(round(xradius)) + {} + guint32 operator()(int x, int y) { + int start, end; + if (axis == Geom::X) { + start = std::max(0, x - _radius); + end = std::min(x + _radius + 1, _w); + } else { + start = std::max(0, y - _radius); + end = std::min(y + _radius + 1, _h); + } - Geom::Affine p2pb = units.get_matrix_primitiveunits2pb(); - int const xradius = (int)round(this->xradius * p2pb.expansionX()); - int const yradius = (int)round(this->yradius * p2pb.expansionY()); - - int x0=in->area.x0; - int y0=in->area.y0; - int x1=in->area.x1; - int y1=in->area.y1; - int w=x1-x0, h=y1-y0; - int x, y, i, j; - int rmax,gmax,bmax,amax; - int rmin,gmin,bmin,amin; - - nr_pixblock_setup_fast(out, in->mode, x0, y0, x1, y1, true); - - unsigned char *in_data = NR_PIXBLOCK_PX(in); - unsigned char *out_data = NR_PIXBLOCK_PX(out); - - for(x = 0 ; x < w ; x++){ - for(y = 0 ; y < h ; y++){ - rmin = gmin = bmin = amin = 255; - rmax = gmax = bmax = amax = 0; - for(i = x - xradius ; i < x + xradius ; i++){ - if (i < 0 || i >= w) continue; - for(j = y - yradius ; j < y + yradius ; j++){ - if (j < 0 || j >= h) continue; - if(in_data[4*(i + w*j)]>rmax) rmax = in_data[4*(i + w*j)]; - if(in_data[4*(i + w*j)+1]>gmax) gmax = in_data[4*(i + w*j)+1]; - if(in_data[4*(i + w*j)+2]>bmax) bmax = in_data[4*(i + w*j)+2]; - if(in_data[4*(i + w*j)+3]>amax) amax = in_data[4*(i + w*j)+3]; - - if(in_data[4*(i + w*j)]<rmin) rmin = in_data[4*(i + w*j)]; - if(in_data[4*(i + w*j)+1]<gmin) gmin = in_data[4*(i + w*j)+1]; - if(in_data[4*(i + w*j)+2]<bmin) bmin = in_data[4*(i + w*j)+2]; - if(in_data[4*(i + w*j)+3]<amin) amin = in_data[4*(i + w*j)+3]; + guint32 ao = (OP == DILATE ? 0 : 255); + guint32 ro = (OP == DILATE ? 0 : 255); + guint32 go = (OP == DILATE ? 0 : 255); + guint32 bo = (OP == DILATE ? 0 : 255); + + if (_alpha) { + ao = (OP == DILATE ? 0 : 0xff000000); + for (int i = start; i < end; ++i) { + guint32 px = (axis == Geom::X ? pixelAt(i, y) : pixelAt(x, i)); + if (OP == DILATE) { + if (px > ao) ao = px; + } else { + if (px < ao) ao = px; } } - if (Operator==MORPHOLOGY_OPERATOR_DILATE){ - out_data[4*(x + w*y)]=rmax; - out_data[4*(x + w*y)+1]=gmax; - out_data[4*(x + w*y)+2]=bmax; - out_data[4*(x + w*y)+3]=amax; - } else { - out_data[4*(x + w*y)]=rmin; - out_data[4*(x + w*y)+1]=gmin; - out_data[4*(x + w*y)+2]=bmin; - out_data[4*(x + w*y)+3]=amin; + return ao; + } else { + for (int i = start; i < end; ++i) { + guint32 px = (axis == Geom::X ? pixelAt(i, y) : pixelAt(x, i)); + EXTRACT_ARGB32(px, a,r,g,b); + + // this will be compiled to conditional moves; + // the operator comparison will be evaluated at compile time. + // therefore there will be no branching in this loop + if (OP == DILATE) { + if (a > ao) ao = a; + if (r > ro) ro = r; + if (g > go) go = g; + if (b > bo) bo = b; + } else { + if (a < ao) ao = a; + if (r < ro) ro = r; + if (g < go) go = g; + if (b < bo) bo = b; + } + + // TODO: verify whether this check gives any speedup. + if (OP == ERODE && a == 0) break; } + + ASSEMBLE_ARGB32(pxout, ao,ro,go,bo) + return pxout; } } +private: + int _radius; +}; + +} // end anonymous namespace - if (free_in_on_exit) { - nr_pixblock_release(in); - delete in; +void FilterMorphology::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + + if (xradius == 0.0 || yradius == 0.0) { + // output is transparent black + cairo_surface_t *out = ink_cairo_surface_create_identical(input); + slot.set(_output, out); + cairo_surface_destroy(out); + return; } - out->empty = FALSE; + Geom::Affine p2pb = slot.get_units().get_matrix_primitiveunits2pb(); + double xr = xradius * p2pb.expansionX(); + double yr = yradius * p2pb.expansionY(); + + cairo_surface_t *interm = ink_cairo_surface_create_identical(input); + + if (Operator == MORPHOLOGY_OPERATOR_DILATE) { + ink_cairo_surface_synthesize(interm, Morphology<DILATE, Geom::X>(input, xr)); + } else { + ink_cairo_surface_synthesize(interm, Morphology<ERODE, Geom::X>(input, xr)); + } + + cairo_surface_t *out = ink_cairo_surface_create_identical(input); + + if (Operator == MORPHOLOGY_OPERATOR_DILATE) { + ink_cairo_surface_synthesize(out, Morphology<DILATE, Geom::Y>(interm, yr)); + } else { + ink_cairo_surface_synthesize(out, Morphology<ERODE, Geom::Y>(interm, yr)); + } + + cairo_surface_destroy(interm); + slot.set(_output, out); - return 0; + cairo_surface_destroy(out); } void FilterMorphology::area_enlarge(NRRectL &area, Geom::Affine const &trans) { - int const enlarge_x = (int)std::ceil(this->xradius * (std::fabs(trans[0]) + std::fabs(trans[1]))); - int const enlarge_y = (int)std::ceil(this->yradius * (std::fabs(trans[2]) + std::fabs(trans[3]))); + int enlarge_x = ceil(xradius * trans.expansionX()); + int enlarge_y = ceil(yradius * trans.expansionY()); area.x0 -= enlarge_x; area.x1 += enlarge_x; @@ -135,10 +170,6 @@ void FilterMorphology::set_yradius(double y){ yradius = y; } -FilterTraits FilterMorphology::get_input_traits() { - return TRAIT_PARALLER; -} - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-morphology.h b/src/display/nr-filter-morphology.h index c8d8b2f50..5924085d9 100644 --- a/src/display/nr-filter-morphology.h +++ b/src/display/nr-filter-morphology.h @@ -13,12 +13,12 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" namespace Inkscape { namespace Filters { +class FilterSlot; + enum FilterMorphologyOperator { MORPHOLOGY_OPERATOR_ERODE, MORPHOLOGY_OPERATOR_DILATE, @@ -31,9 +31,8 @@ public: static FilterPrimitive *create(); virtual ~FilterMorphology(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); void set_operator(FilterMorphologyOperator &o); void set_xradius(double x); void set_yradius(double y); diff --git a/src/display/nr-filter-offset.cpp b/src/display/nr-filter-offset.cpp index 7c924b7b7..3b0f83841 100644 --- a/src/display/nr-filter-offset.cpp +++ b/src/display/nr-filter-offset.cpp @@ -9,11 +9,10 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include "display/cairo-utils.h" #include "display/nr-filter-offset.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" #include "libnr/nr-rect-l.h" namespace Inkscape { @@ -33,37 +32,29 @@ FilterPrimitive * FilterOffset::create() { FilterOffset::~FilterOffset() {} -int FilterOffset::render(FilterSlot &slot, FilterUnits const &units) { - NRPixBlock *in = slot.get(_input); - // Bail out if source image is missing - if (!in) { - g_warning("Missing source image for feOffset (in=%d)", _input); - return 1; - } - - NRPixBlock *out = new NRPixBlock; +void FilterOffset::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *in = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_identical(in); + cairo_t *ct = cairo_create(out); - Geom::Affine trans = units.get_matrix_primitiveunits2pb(); + Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); Geom::Point offset(dx, dy); offset *= trans; offset[X] -= trans[4]; offset[Y] -= trans[5]; - nr_pixblock_setup_fast(out, in->mode, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); - nr_blit_pixblock_pixblock(out, in); + cairo_set_source_surface(ct, in, offset[X], offset[Y]); + cairo_paint(ct); + cairo_destroy(ct); - out->area.x0 += static_cast<NR::ICoord>(offset[X]); - out->area.y0 += static_cast<NR::ICoord>(offset[Y]); - out->area.x1 += static_cast<NR::ICoord>(offset[X]); - out->area.y1 += static_cast<NR::ICoord>(offset[Y]); - out->visible_area = out->area; - - out->empty = FALSE; slot.set(_output, out); + cairo_surface_destroy(out); +} - return 0; +bool FilterOffset::can_handle_affine(Geom::Affine const &) +{ + return true; } void FilterOffset::set_dx(double amount) { @@ -82,15 +73,15 @@ void FilterOffset::area_enlarge(NRRectL &area, Geom::Affine const &trans) offset[Y] -= trans[5]; if (offset[X] > 0) { - area.x0 -= static_cast<NR::ICoord>(offset[X]); + area.x0 -= ceil(offset[X]); } else { - area.x1 -= static_cast<NR::ICoord>(offset[X]); + area.x1 -= floor(offset[X]); } if (offset[Y] > 0) { - area.y0 -= static_cast<NR::ICoord>(offset[Y]); + area.y0 -= ceil(offset[Y]); } else { - area.y1 -= static_cast<NR::ICoord>(offset[Y]); + area.y1 -= floor(offset[Y]); } } diff --git a/src/display/nr-filter-offset.h b/src/display/nr-filter-offset.h index a78450e17..09c57f803 100644 --- a/src/display/nr-filter-offset.h +++ b/src/display/nr-filter-offset.h @@ -26,8 +26,9 @@ public: static FilterPrimitive *create(); virtual ~FilterOffset(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); + virtual bool can_handle_affine(Geom::Affine const &); void set_dx(double amount); void set_dy(double amount); diff --git a/src/display/nr-filter-pixops.h b/src/display/nr-filter-pixops.h deleted file mode 100644 index afd9e98bd..000000000 --- a/src/display/nr-filter-pixops.h +++ /dev/null @@ -1,104 +0,0 @@ -#ifndef __NR_FILTER_PIXOPS_H__ -#define __NR_FILTER_PIXOPS_H__ - -#include "libnr/nr-pixblock.h" -#include <algorithm> - -/* - * Per-pixel image manipulation functions. - * These can be used by all filter primitives, which combine two images on - * per-pixel basis. These are at least feBlend, feComposite and feMerge. - * - * Authors: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2007 authors - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -namespace Inkscape { -namespace Filters { - -/** - * Mixes the two input images using the function given as template. - * The result is placed in out. - * The mixing function should have the following type: - * void mix(unsigned char *result, unsigned char const *in1, - * unsigned char const *in2); - * Each of the parameters for mix-function is a pointer to four bytes of data, - * giving the RGBA values for that pixel. The mix function must only access - * the four bytes beginning at a pointer given as parameter. - */ -/* - * The implementation is in a header file because of the template. It has to - * be in the same compilation unit as the code using it. Otherwise, linking - * the program will not succeed. - */ -template <void(*blend)(unsigned char *cr, unsigned char const *ca, unsigned char const *cb)> -void pixops_mix(NRPixBlock &out, NRPixBlock &in1, NRPixBlock &in2) { - unsigned char *in1_data = NR_PIXBLOCK_PX(&in1); - unsigned char *in2_data = NR_PIXBLOCK_PX(&in2); - unsigned char *out_data = NR_PIXBLOCK_PX(&out); - unsigned char zero_rgba[4] = {0, 0, 0, 0}; - - // Possible scenarios (omitting cases where an interval is empty and those which are the same by interchanging 1 and 2): - // 01020, 01320, 01310 (no overlap, partial overlap, full overlap) - int out_y0 = out.area.y0; - int out_y1 = std::max(out.area.y1,out_y0); // Enforce sanity - int in1_y0 = std::min(std::max(in1.area.y0,out_y0),out_y1); - int in2_y0 = std::min(std::max(in2.area.y0,out_y0),out_y1); - int in1_y1 = std::min(std::max(in1.area.y1,in1_y0),out_y1); - int in2_y1 = std::min(std::max(in2.area.y1,in2_y0),out_y1); - int min_in_y0 = std::min(in1_y0,in2_y0); - int max_in_y0 = std::max(in1_y0,in2_y0); - int min_in_y1 = std::min(in1_y1,in2_y1); - int max_in_y1 = std::max(in1_y1,in2_y1); - int const yBound[6] = {out_y0, min_in_y0, std::min(max_in_y0,min_in_y1), std::max(max_in_y0,min_in_y1), max_in_y1, out_y1}; - bool const in1_zero_y[5] = {true, in1_y0>yBound[1], in1_y0>yBound[2] || in1_y1<=yBound[2], in1_y1<=yBound[3], true}; - bool const in2_zero_y[5] = {true, in2_y0>yBound[1], in2_y0>yBound[2] || in2_y1<=yBound[2], in2_y1<=yBound[3], true}; - - int out_x0 = out.area.x0; - int out_x1 = std::max(out.area.x1,out_x0); - int in1_x0 = std::min(std::max(in1.area.x0,out_x0),out_x1); - int in2_x0 = std::min(std::max(in2.area.x0,out_x0),out_x1); - int in1_x1 = std::min(std::max(in1.area.x1,in1_x0),out_x1); - int in2_x1 = std::min(std::max(in2.area.x1,in2_x0),out_x1); - int min_in_x0 = std::min(in1_x0,in2_x0); - int max_in_x0 = std::max(in1_x0,in2_x0); - int min_in_x1 = std::min(in1_x1,in2_x1); - int max_in_x1 = std::max(in1_x1,in2_x1); - int const xBound[6] = {out_x0, min_in_x0, std::min(max_in_x0,min_in_x1), std::max(max_in_x0,min_in_x1), max_in_x1, out_x1}; - bool const in1_zero_x[5] = {true, in1_x0>xBound[1], in1_x0>xBound[2] || in1_x1<=xBound[2], in1_x1<=xBound[3], true}; - bool const in2_zero_x[5] = {true, in2_x0>xBound[1], in2_x0>xBound[2] || in2_x1<=xBound[2], in2_x1<=xBound[3], true}; - - for (int yr = 0 ; yr < 5 ; yr++) { - for(int y = yBound[yr] ; y < yBound[yr+1] ; y++) { - int out_line = (y - out.area.y0) * out.rs; - int in1_line = (y - in1.area.y0) * in1.rs; - int in2_line = (y - in2.area.y0) * in2.rs; - for (int xr = 0 ; xr < 5 ; xr++) { - for(int x = xBound[xr] ; x < xBound[xr+1] ; x++) { - blend(out_data + out_line + 4 * (x - out.area.x0), - (in1_zero_x[xr]||in1_zero_y[yr]) ? zero_rgba : (in1_data + in1_line + 4 * (x - in1.area.x0)), - (in2_zero_x[xr]||in2_zero_y[yr]) ? zero_rgba : (in2_data + in2_line + 4 * (x - in2.area.x0))); - } - } - } - } -} - -} /* namespace Filters */ -} /* namespace Inkscape */ - -#endif // __NR_FILTER_PIXOPS_H_ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-filter-primitive.cpp b/src/display/nr-filter-primitive.cpp index 1af86ec3e..b544d6df0 100644 --- a/src/display/nr-filter-primitive.cpp +++ b/src/display/nr-filter-primitive.cpp @@ -13,8 +13,8 @@ */ #include "display/nr-filter-primitive.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-types.h" -#include "libnr/nr-pixblock.h" #include "svg/svg-length.h" namespace Inkscape { @@ -48,6 +48,13 @@ FilterPrimitive::~FilterPrimitive() // Nothing to do here } +void FilterPrimitive::render_cairo(FilterSlot &slot) +{ + // passthrough + cairo_surface_t *in = slot.getcairo(_input); + slot.set(_output, in); +} + void FilterPrimitive::area_enlarge(NRRectL &/*area*/, Geom::Affine const &/*m*/) { // This doesn't need to do anything by default diff --git a/src/display/nr-filter-primitive.h b/src/display/nr-filter-primitive.h index 0e8df3813..dd7363d76 100644 --- a/src/display/nr-filter-primitive.h +++ b/src/display/nr-filter-primitive.h @@ -1,6 +1,3 @@ -#ifndef __NR_FILTER_PRIMITIVE_H__ -#define __NR_FILTER_PRIMITIVE_H__ - /* * SVG filters rendering * @@ -11,15 +8,20 @@ * * Released under GNU GPL, read the file 'COPYING' for more information */ +#ifndef SEEN_NR_FILTER_PRIMITIVE_H +#define SEEN_NR_FILTER_PRIMITIVE_H -#include "display/nr-filter-slot.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-rect-l.h" +#include <2geom/forward.h> #include "svg/svg-length.h" +struct NRRectL; + namespace Inkscape { namespace Filters { +class FilterSlot; +class FilterUnits; + /* * Different filter effects need different types of inputs. This is what * traits are used for: one can specify, what special restrictions @@ -43,7 +45,8 @@ public: FilterPrimitive(); virtual ~FilterPrimitive(); - virtual int render(FilterSlot &slot, FilterUnits const &units) = 0; + virtual void render_cairo(FilterSlot &slot); + virtual int render(FilterSlot &slot, FilterUnits const &units) { return 0; } virtual void area_enlarge(NRRectL &area, Geom::Affine const &m); /** @@ -108,6 +111,20 @@ public: */ virtual FilterTraits get_input_traits(); + /** @brief Indicate whether the filter primitive can handle the given affine. + * + * Results of some filter primitives depend on the coordinate system used when rendering. + * A gaussian blur with equal x and y deviation will remain unchanged by rotations. + * Per-pixel filters like color matrix and blend will not change regardless of + * the transformation. + * + * When any filter returns false, filter rendering is performed on an intermediate surface + * with edges parallel to the axes of the user coordinate system. This means + * the matrices from FilterUnits will contain at most a (possibly non-uniform) scale + * and a translation. When all primitives of the filter return false, the rendering is + * performed in display coordinate space and no intermediate surface is used. */ + virtual bool can_handle_affine(Geom::Affine const &) { return false; } + protected: int _input; int _output; diff --git a/src/display/nr-filter-skeleton.cpp b/src/display/nr-filter-skeleton.cpp index c17bee1d4..0c455a818 100644 --- a/src/display/nr-filter-skeleton.cpp +++ b/src/display/nr-filter-skeleton.cpp @@ -22,9 +22,9 @@ */ #include "display/nr-filter-skeleton.h" +#include "display/cairo-utils.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" -#include "libnr/nr-pixblock.h" namespace Inkscape { namespace Filters { @@ -39,17 +39,17 @@ FilterPrimitive * FilterSkeleton::create() { FilterSkeleton::~FilterSkeleton() {} -int FilterSkeleton::render(FilterSlot &slot, - FilterUnits const &/*units*/) { - //NRPixBlock *in = slot.get(_input); - NRPixBlock *out = new NRPixBlock(); +void FilterSkeleton::render_cairo(FilterSlot &slot) { + cairo_surface_t *in = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_identical(in); + cairo_t *ct = cairo_create(out); - /* Insert rendering code here */ +// cairo_set_source_surface(ct, in, offset[X], offset[Y]); +// cairo_paint(ct); +// cairo_destroy(ct); - out->empty = FALSE; slot.set(_output, out); - - return 0; + cairo_surface_destroy(out); } } /* namespace Filters */ diff --git a/src/display/nr-filter-skeleton.h b/src/display/nr-filter-skeleton.h index a03004be1..049c0df80 100644 --- a/src/display/nr-filter-skeleton.h +++ b/src/display/nr-filter-skeleton.h @@ -37,7 +37,7 @@ public: static FilterPrimitive *create(); virtual ~FilterSkeleton(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); private: diff --git a/src/display/nr-filter-slot.cpp b/src/display/nr-filter-slot.cpp index b019b194f..ce07ff086 100644 --- a/src/display/nr-filter-slot.cpp +++ b/src/display/nr-filter-slot.cpp @@ -14,317 +14,219 @@ #include <assert.h> #include <string.h> +#include <2geom/transforms.h> +#include "display/cairo-utils.h" #include "display/nr-arena-item.h" #include "display/nr-filter-types.h" #include "display/nr-filter-gaussian.h" #include "display/nr-filter-slot.h" -#include "display/nr-filter-getalpha.h" #include "display/nr-filter-units.h" -#include "display/pixblock-scaler.h" -#include "display/pixblock-transform.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-blit.h" - -__attribute__ ((const)) -inline static int _max4(const double a, const double b, - const double c, const double d) { - double ret = a; - if (b > ret) ret = b; - if (c > ret) ret = c; - if (d > ret) ret = d; - return (int)round(ret); -} - -__attribute__ ((const)) -inline static int _min4(const double a, const double b, - const double c, const double d) { - double ret = a; - if (b < ret) ret = b; - if (c < ret) ret = c; - if (d < ret) ret = d; - return (int)round(ret); -} - -__attribute__ ((const)) -inline static int _max2(const double a, const double b) { - if (a > b) - return (int)round(a); - else - return (int)round(b); -} - -__attribute__ ((const)) -inline static int _min2(const double a, const double b) { - if (a > b) - return (int)round(b); - else - return (int)round(a); -} namespace Inkscape { namespace Filters { -FilterSlot::FilterSlot(int slots, NRArenaItem const *item) - : _last_out(-1), - filterquality(FILTER_QUALITY_BEST), - blurquality(BLUR_QUALITY_BEST), - _arena_item(item) +FilterSlot::FilterSlot(NRArenaItem *item, cairo_t *bgct, NRRectL const *bgarea, + cairo_surface_t *graphic, NRRectL const *graphicarea, FilterUnits const &u) + : _item(item) + , _source_graphic(graphic) + , _background_ct(bgct) + , _source_graphic_area(graphicarea) + , _background_area(bgarea) + , _units(u) + , _last_out(NR_FILTER_SOURCEGRAPHIC) + , filterquality(FILTER_QUALITY_BEST) + , blurquality(BLUR_QUALITY_BEST) { - _slots.reserve((slots > 0) ? slots : 2); + using Geom::X; + using Geom::Y; + + // compute slot bbox + Geom::Rect bbox( + Geom::Point(_source_graphic_area->x0, _source_graphic_area->y0), + Geom::Point(_source_graphic_area->x1, _source_graphic_area->y1)); + + Geom::Affine trans = _units.get_matrix_display2pb(); + Geom::Rect bbox_trans = bbox * trans; + Geom::Point min = bbox_trans.min(); + _slot_x = min[X]; + _slot_y = min[Y]; + + if (trans.isTranslation()) { + _slot_w = _source_graphic_area->x1 - _source_graphic_area->x0; + _slot_h = _source_graphic_area->y1 - _source_graphic_area->y0; + } else { + _slot_w = ceil(bbox_trans.width()); + _slot_h = ceil(bbox_trans.height()); + } } FilterSlot::~FilterSlot() { - for (unsigned int i = 0 ; i < _slots.size() ; i++) { - if (_slots[i].owned) { - nr_pixblock_release(_slots[i].pb); - delete _slots[i].pb; - } + for (SlotMap::iterator i = _slots.begin(); i != _slots.end(); ++i) { + cairo_surface_destroy(i->second); } } -FilterSlot::slot_entry_t::~slot_entry_t() +cairo_surface_t *FilterSlot::getcairo(int slot_nr) { - // It's a bad idea to destruct pixblocks here, as this will also be called upon resizing _slots -} + if (slot_nr == NR_FILTER_SLOT_NOT_SET) + slot_nr = _last_out; -NRPixBlock *FilterSlot::get(int slot_nr) -{ - int index = _get_index(slot_nr); - assert(index >= 0); + SlotMap::iterator s = _slots.find(slot_nr); /* If we didn't have the specified image, but we could create it * from the other information we have, let's do that */ - if (_slots[index].pb == NULL - && (slot_nr == NR_FILTER_SOURCEALPHA + if (s == _slots.end() + && (slot_nr == NR_FILTER_SOURCEGRAPHIC + || slot_nr == NR_FILTER_SOURCEALPHA || slot_nr == NR_FILTER_BACKGROUNDIMAGE || slot_nr == NR_FILTER_BACKGROUNDALPHA || slot_nr == NR_FILTER_FILLPAINT || slot_nr == NR_FILTER_STROKEPAINT)) { - /* If needed, fetch background */ - if (slot_nr == NR_FILTER_BACKGROUNDIMAGE) { - NRPixBlock *pb; - pb = nr_arena_item_get_background(_arena_item); - if (pb) { - pb->empty = false; - this->set(NR_FILTER_BACKGROUNDIMAGE, pb, false); - } else { - NRPixBlock *source = this->get(NR_FILTER_SOURCEGRAPHIC); - pb = new NRPixBlock(); - if (!pb) return NULL; // Allocation failed - nr_pixblock_setup_fast(pb, source->mode, - source->area.x0, source->area.y0, - source->area.x1, source->area.y1, true); - if (pb->size != NR_PIXBLOCK_SIZE_TINY && pb->data.px == NULL) { - // allocation failed - delete pb; - return NULL; - } - pb->empty = FALSE; - this->set(NR_FILTER_BACKGROUNDIMAGE, pb); - } - } else if (slot_nr == NR_FILTER_SOURCEALPHA) { - /* If only a alpha channel is needed, strip it from full image */ - NRPixBlock *src = get(NR_FILTER_SOURCEGRAPHIC); - NRPixBlock *sa = filter_get_alpha(src); - set(NR_FILTER_SOURCEALPHA, sa); - } else if (slot_nr == NR_FILTER_BACKGROUNDALPHA) { - NRPixBlock *src = get(NR_FILTER_BACKGROUNDIMAGE); - NRPixBlock *ba = filter_get_alpha(src); - set(NR_FILTER_BACKGROUNDALPHA, ba); - } else if (slot_nr == NR_FILTER_FILLPAINT) { - /* When a paint is needed, fetch it from arena item */ - // TODO - } else if (slot_nr == NR_FILTER_STROKEPAINT) { - // TODO + switch (slot_nr) { + case NR_FILTER_SOURCEGRAPHIC: { + cairo_surface_t *tr = _get_transformed_source_graphic(); + _set_internal(NR_FILTER_SOURCEGRAPHIC, tr); + cairo_surface_destroy(tr); + } break; + case NR_FILTER_BACKGROUNDIMAGE: { + cairo_surface_t *bg = _get_transformed_background(); + _set_internal(NR_FILTER_BACKGROUNDIMAGE, bg); + cairo_surface_destroy(bg); + } break; + case NR_FILTER_SOURCEALPHA: { + cairo_surface_t *src = getcairo(NR_FILTER_SOURCEGRAPHIC); + cairo_surface_t *alpha = ink_cairo_extract_alpha(src); + _set_internal(NR_FILTER_SOURCEALPHA, alpha); + cairo_surface_destroy(alpha); + } break; + case NR_FILTER_BACKGROUNDALPHA: { + cairo_surface_t *src = getcairo(NR_FILTER_BACKGROUNDIMAGE); + cairo_surface_t *ba = ink_cairo_extract_alpha(src); + _set_internal(NR_FILTER_BACKGROUNDALPHA, ba); + cairo_surface_destroy(ba); + } break; + case NR_FILTER_FILLPAINT: //TODO + case NR_FILTER_STROKEPAINT: //TODO + default: + break; } + s = _slots.find(slot_nr); } - if (_slots[index].pb) { - _slots[index].pb->empty = false; + if (s == _slots.end()) { + // create empty surface + cairo_surface_t *empty = cairo_surface_create_similar( + _source_graphic, cairo_surface_get_content(_source_graphic), + _slot_w, _slot_h); + _set_internal(slot_nr, empty); + cairo_surface_destroy(empty); + s = _slots.find(slot_nr); } - - assert(slot_nr == NR_FILTER_SLOT_NOT_SET ||_slots[index].number == slot_nr); - return _slots[index].pb; + return s->second; } -void FilterSlot::get_final(int slot_nr, NRPixBlock *result) { - NRPixBlock *final_usr = get(slot_nr); - Geom::Affine trans = units.get_matrix_pb2display(); - - int size = (result->area.x1 - result->area.x0) - * (result->area.y1 - result->area.y0) - * NR_PIXBLOCK_BPP(result); - memset(NR_PIXBLOCK_PX(result), 0, size); +cairo_surface_t *FilterSlot::_get_transformed_source_graphic() +{ + Geom::Affine trans = _units.get_matrix_display2pb(); - if (fabs(trans[1]) > 1e-6 || fabs(trans[2]) > 1e-6) { - if (filterquality == FILTER_QUALITY_BEST) { - NR::transform_bicubic(result, final_usr, trans); - } else { - NR::transform_nearest(result, final_usr, trans); - } - } else if (fabs(trans[0] - 1) > 1e-6 || fabs(trans[3] - 1) > 1e-6) { - NR::scale_bicubic(result, final_usr, trans); - } else { - nr_blit_pixblock_pixblock(result, final_usr); + if (trans.isTranslation()) { + cairo_surface_reference(_source_graphic); + return _source_graphic; } -} -void FilterSlot::set(int slot_nr, NRPixBlock *pb, bool takeOwnership) -{ - /* Unnamed slot is for saving filter primitive results, when parameter - * 'result' is not set. Only the filter immediately after this one - * can access unnamed results, so we don't have to worry about overwriting - * previous results in filter chain. On the other hand, we may not - * overwrite any other image with this one, because they might be - * accessed later on. */ - int index = ((slot_nr != NR_FILTER_SLOT_NOT_SET) - ? _get_index(slot_nr) - : _get_index(NR_FILTER_UNNAMED_SLOT)); - assert(index >= 0); - // Unnamed slot is only for Inkscape::Filters::FilterSlot internal use. - assert(slot_nr != NR_FILTER_UNNAMED_SLOT); - assert(slot_nr == NR_FILTER_SLOT_NOT_SET ||_slots[index].number == slot_nr); - - if (slot_nr == NR_FILTER_SOURCEGRAPHIC || slot_nr == NR_FILTER_BACKGROUNDIMAGE) { - Geom::Affine trans = units.get_matrix_display2pb(); - if (fabs(trans[1]) > 1e-6 || fabs(trans[2]) > 1e-6) { - NRPixBlock *trans_pb = new NRPixBlock; - int x0 = pb->area.x0; - int y0 = pb->area.y0; - int x1 = pb->area.x1; - int y1 = pb->area.y1; - int min_x = _min4(trans[0] * x0 + trans[2] * y0 + trans[4], - trans[0] * x0 + trans[2] * y1 + trans[4], - trans[0] * x1 + trans[2] * y0 + trans[4], - trans[0] * x1 + trans[2] * y1 + trans[4]); - int max_x = _max4(trans[0] * x0 + trans[2] * y0 + trans[4], - trans[0] * x0 + trans[2] * y1 + trans[4], - trans[0] * x1 + trans[2] * y0 + trans[4], - trans[0] * x1 + trans[2] * y1 + trans[4]); - int min_y = _min4(trans[1] * x0 + trans[3] * y0 + trans[5], - trans[1] * x0 + trans[3] * y1 + trans[5], - trans[1] * x1 + trans[3] * y0 + trans[5], - trans[1] * x1 + trans[3] * y1 + trans[5]); - int max_y = _max4(trans[1] * x0 + trans[3] * y0 + trans[5], - trans[1] * x0 + trans[3] * y1 + trans[5], - trans[1] * x1 + trans[3] * y0 + trans[5], - trans[1] * x1 + trans[3] * y1 + trans[5]); - - nr_pixblock_setup_fast(trans_pb, pb->mode, - min_x, min_y, - max_x, max_y, true); - if (trans_pb->size != NR_PIXBLOCK_SIZE_TINY && trans_pb->data.px == NULL) { - /* TODO: this gets hit occasionally. Worst case scenario: - * images are exported in horizontal stripes. One stripe - * is not too high, but can get thousands of pixels wide. - * Rotate this 45 degrees -> _huge_ image */ - g_warning("Memory allocation failed in Inkscape::Filters::FilterSlot::set (transform)"); - if (takeOwnership) { - nr_pixblock_release(pb); - delete pb; - } - return; - } - if (filterquality == FILTER_QUALITY_BEST) { - NR::transform_bicubic(trans_pb, pb, trans); - } else { - NR::transform_nearest(trans_pb, pb, trans); - } - if (takeOwnership) { - nr_pixblock_release(pb); - delete pb; - } - takeOwnership = true; - pb = trans_pb; - } else if (fabs(trans[0] - 1) > 1e-6 || fabs(trans[3] - 1) > 1e-6) { - NRPixBlock *trans_pb = new NRPixBlock; - - int x0 = pb->area.x0; - int y0 = pb->area.y0; - int x1 = pb->area.x1; - int y1 = pb->area.y1; - int min_x = _min2(trans[0] * x0 + trans[4], - trans[0] * x1 + trans[4]); - int max_x = _max2(trans[0] * x0 + trans[4], - trans[0] * x1 + trans[4]); - int min_y = _min2(trans[3] * y0 + trans[5], - trans[3] * y1 + trans[5]); - int max_y = _max2(trans[3] * y0 + trans[5], - trans[3] * y1 + trans[5]); - - nr_pixblock_setup_fast(trans_pb, pb->mode, - min_x, min_y, max_x, max_y, true); - if (trans_pb->size != NR_PIXBLOCK_SIZE_TINY && trans_pb->data.px == NULL) { - g_warning("Memory allocation failed in Inkscape::Filters::FilterSlot::set (scaling)"); - if (takeOwnership) { - nr_pixblock_release(pb); - delete pb; - } - return; - } - NR::scale_bicubic(trans_pb, pb, trans); - if (takeOwnership) { - nr_pixblock_release(pb); - delete pb; - } - takeOwnership = true; - pb = trans_pb; - } - } + cairo_surface_t *tsg = cairo_surface_create_similar( + _source_graphic, cairo_surface_get_content(_source_graphic), + _slot_w, _slot_h); + cairo_t *tsg_ct = cairo_create(tsg); - if(_slots[index].owned) { - nr_pixblock_release(_slots[index].pb); - delete _slots[index].pb; - } - _slots[index].pb = pb; - _slots[index].owned = takeOwnership; - _last_out = index; + cairo_translate(tsg_ct, -_slot_x, -_slot_y); + ink_cairo_transform(tsg_ct, trans); + cairo_translate(tsg_ct, _source_graphic_area->x0, _source_graphic_area->y0); + cairo_set_source_surface(tsg_ct, _source_graphic, 0, 0); + cairo_set_operator(tsg_ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(tsg_ct); + cairo_destroy(tsg_ct); + + return tsg; } -int FilterSlot::get_slot_count() +cairo_surface_t *FilterSlot::_get_transformed_background() { - return _slots.size(); + Geom::Affine trans = _units.get_matrix_display2pb(); + + cairo_surface_t *bg = cairo_get_target(_background_ct); + cairo_surface_t *tbg = cairo_surface_create_similar( + bg, cairo_surface_get_content(bg), + _slot_w, _slot_h); + cairo_t *tbg_ct = cairo_create(tbg); + + cairo_translate(tbg_ct, -_slot_x, -_slot_y); + ink_cairo_transform(tbg_ct, trans); + cairo_translate(tbg_ct, _background_area->x0, _background_area->y0); + cairo_set_source_surface(tbg_ct, bg, 0, 0); + cairo_set_operator(tbg_ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(tbg_ct); + cairo_destroy(tbg_ct); + + return tbg; } -NRArenaItem const* FilterSlot::get_arenaitem() +cairo_surface_t *FilterSlot::get_result(int res) { - return _arena_item; + Geom::Affine trans = _units.get_matrix_pb2display(); + if (trans.isIdentity()) { + cairo_surface_t *result = getcairo(res); + cairo_surface_reference(result); + return result; + } + + cairo_surface_t *r = cairo_surface_create_similar(_source_graphic, + cairo_surface_get_content(_source_graphic), + _source_graphic_area->x1 - _source_graphic_area->x0, + _source_graphic_area->y1 - _source_graphic_area->y0); + cairo_t *r_ct = cairo_create(r); + + cairo_translate(r_ct, -_source_graphic_area->x0, -_source_graphic_area->y0); + ink_cairo_transform(r_ct, trans); + cairo_translate(r_ct, _slot_x, _slot_y); + cairo_set_source_surface(r_ct, getcairo(res), 0, 0); + cairo_set_operator(r_ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(r_ct); + cairo_destroy(r_ct); + + return r; } -int FilterSlot::_get_index(int slot_nr) +void FilterSlot::_set_internal(int slot_nr, cairo_surface_t *surface) { - assert(slot_nr >= 0 || - slot_nr == NR_FILTER_SLOT_NOT_SET || - slot_nr == NR_FILTER_SOURCEGRAPHIC || - slot_nr == NR_FILTER_SOURCEALPHA || - slot_nr == NR_FILTER_BACKGROUNDIMAGE || - slot_nr == NR_FILTER_BACKGROUNDALPHA || - slot_nr == NR_FILTER_FILLPAINT || - slot_nr == NR_FILTER_STROKEPAINT || - slot_nr == NR_FILTER_UNNAMED_SLOT); - - if (slot_nr == NR_FILTER_SLOT_NOT_SET) { - return _last_out; - } + // destroy after referencing + // this way assigning a surface to a slot it already occupies will not cause errors + cairo_surface_reference(surface); - /* Search, if the slot already exists */ - for (int i = 0 ; i < (int)_slots.size() ; i++) { - if (_slots[i].number == slot_nr) { - return i; - } + SlotMap::iterator s = _slots.find(slot_nr); + if (s != _slots.end()) { + cairo_surface_destroy(s->second); } - /* If the slot doesn't already exist, create it */ - slot_entry_t entry; - entry.number = slot_nr; - _slots.push_back(entry); - return (int)_slots.size()-1; + _slots[slot_nr] = surface; } -void FilterSlot::set_units(FilterUnits const &units) { - this->units = units; +void FilterSlot::set(int slot_nr, cairo_surface_t *surface) +{ + g_return_if_fail(surface != NULL); + + if (slot_nr == NR_FILTER_SLOT_NOT_SET) + slot_nr = NR_FILTER_UNNAMED_SLOT; + + _set_internal(slot_nr, surface); + _last_out = slot_nr; +} + +int FilterSlot::get_slot_count() +{ + return _slots.size(); } void FilterSlot::set_quality(FilterQuality const q) { @@ -339,6 +241,13 @@ int FilterSlot::get_blurquality(void) { return blurquality; } +Geom::Rect FilterSlot::get_slot_area() const { + Geom::Point p(_slot_x, _slot_y); + Geom::Point dim(_slot_w, _slot_h); + Geom::Rect r(p, p+dim); + return r; +} + } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-slot.h b/src/display/nr-filter-slot.h index 871d80a8e..3b08743ed 100644 --- a/src/display/nr-filter-slot.h +++ b/src/display/nr-filter-slot.h @@ -14,10 +14,10 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ -#include "libnr/nr-pixblock.h" +#include <map> +#include <cairo.h> #include "display/nr-filter-types.h" #include "display/nr-filter-units.h" -#include <vector> struct NRArenaItem; @@ -26,14 +26,9 @@ namespace Filters { class FilterSlot { public: - /** Creates a new FilterSlot object. - * First parameter specifies the amount of slots this SilterSlot - * should reserve beforehand. If a negative number is given, - * two slots will be reserved. - * Second parameter specifies the arena item, which should be used - * for background accesses from filters. - */ - FilterSlot(int slots, NRArenaItem const *item); + /** Creates a new FilterSlot object. */ + FilterSlot(NRArenaItem *item, cairo_t *bgct, NRRectL const *bgarea, + cairo_surface_t *graphic, NRRectL const *graphicarea, FilterUnits const &u); /** Destroys the FilterSlot object and all its contents */ virtual ~FilterSlot(); @@ -43,37 +38,22 @@ public: * NR_FILTER_SOURCEGRAPHIC, NR_FILTER_SOURCEALPHA, * NR_FILTER_BACKGROUNDIMAGE, NR_FILTER_BACKGROUNDALPHA, * NR_FILTER_FILLPAINT, NR_FILTER_SOURCEPAINT. - * If the defined filter slot is not set before, this function - * returns NULL. Also, that filter slot is created in process. - */ - NRPixBlock *get(int slot); - - /** Gets the final result from this filter. - * The result is fetched from the specified slot, see description of - * method get for valid values. The pixblock 'result' will be modified - * to contain the result image, ready to be used in the rest of rendering - * pipeline */ - void get_final(int slot, NRPixBlock *result); + cairo_surface_t *getcairo(int slot); /** Sets or re-sets the pixblock associated with given slot. * If there was a pixblock already assigned with this slot, * that pixblock is destroyed. - * Pixblocks passed to this function should be considered - * managed by this FilterSlot object if takeOwnership==true. - * Pixblocks passed to this function should be reserved with - * c++ -style new-operator (if managed by FilterSlot). */ - void set(int slot, NRPixBlock *pb, bool takeOwnership=true); + void set(int slot, cairo_surface_t *s); + + cairo_surface_t *get_result(int slot_nr); /** Returns the number of slots in use. */ int get_slot_count(); - /** arenaitem getter method*/ - NRArenaItem const* get_arenaitem(); - /** Sets the unit system to be used for the internal images. */ - void set_units(FilterUnits const &units); + //void set_units(FilterUnits const &units); /** Sets the filtering quality. Affects used interpolation methods */ void set_quality(FilterQuality const q); @@ -84,30 +64,36 @@ public: /** Gets the gaussian filtering quality. Affects used interpolation methods */ int get_blurquality(void); -private: - struct slot_entry_t { - NRPixBlock* pb; - int number; - bool owned; - slot_entry_t() : pb(0), number(NR_FILTER_SLOT_NOT_SET), owned(false) {} - ~slot_entry_t(); - }; - std::vector<slot_entry_t> _slots; + FilterUnits const &get_units() const { return _units; } + Geom::Rect get_slot_area() const; + NRRectL const &get_sg_area() const { return *_source_graphic_area; } +private: + typedef std::map<int, cairo_surface_t *> SlotMap; + SlotMap _slots; + NRArenaItem *_item; + + //Geom::Rect _source_bbox; ///< bounding box of source graphic surface + //Geom::Rect _intermediate_bbox; ///< bounding box of intermediate surfaces + +// NRRectL _slot_area; + int _slot_w, _slot_h; + double _slot_x, _slot_y; + cairo_surface_t *_source_graphic; + cairo_t *_background_ct; + NRRectL const *_source_graphic_area; + NRRectL const *_background_area; ///< needed to extract background + FilterUnits const &_units; int _last_out; - FilterQuality filterquality; - int blurquality; - NRArenaItem const *_arena_item; - - FilterUnits units; + cairo_surface_t *_get_transformed_source_graphic(); + cairo_surface_t *_get_transformed_background(); + cairo_surface_t *_get_fill_paint(); + cairo_surface_t *_get_stroke_paint(); - /** Returns the table index of given slot. If that slot does not exist, - * it is created. Table index can be used to read the correct - * pixblock from _slot */ - int _get_index(int slot); + void _set_internal(int slot, cairo_surface_t *s); }; } /* namespace Filters */ diff --git a/src/display/nr-filter-specularlighting.cpp b/src/display/nr-filter-specularlighting.cpp index 8ecee24e6..eddab36a1 100644 --- a/src/display/nr-filter-specularlighting.cpp +++ b/src/display/nr-filter-specularlighting.cpp @@ -13,18 +13,15 @@ #include <glib/gmessages.h> #include <cmath> +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-3dutils.h" -#include "display/nr-arena-item.h" #include "display/nr-filter-specularlighting.h" -#include "display/nr-filter-getalpha.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" #include "display/nr-light.h" -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" #include "libnr/nr-rect-l.h" -#include "color.h" namespace Inkscape { namespace Filters { @@ -45,20 +42,139 @@ FilterPrimitive * FilterSpecularLighting::create() { FilterSpecularLighting::~FilterSpecularLighting() {} -//Investigating Phong Lighting model we should not take N.H but -//R.E which equals to 2*N.H^2 - 1 -//replace the second line by -//gdouble scal = scalar_product((N), (H)); scal = 2 * scal * scal - 1; -//to get the expected formula -#define COMPUTE_INTER(inter, H, N, ks, speculaExponent) \ -do {\ - gdouble scal = NR::scalar_product((N), (H)); \ - if (scal <= 0)\ - (inter) = 0;\ - else\ - (inter) = (ks) * std::pow(scal, (specularExponent));\ -}while(0) +struct SpecularLight : public SurfaceSynth { + SpecularLight(cairo_surface_t *bumpmap, double scale, double specular_constant, + double specular_exponent) + : SurfaceSynth(bumpmap) + , _scale(scale) + , _ks(specular_constant) + , _exp(specular_exponent) + {} +protected: + guint32 specularLighting(int x, int y, NR::Fvector const &halfway, NR::Fvector const &light_components) { + NR::Fvector normal = surfaceNormalAt(x, y, _scale); + double sp = NR::scalar_product(normal, halfway); + double k = sp <= 0.0 ? 0.0 : _ks * pow(sp, _exp); + guint32 r = CLAMP_D_TO_U8(k * light_components[LIGHT_RED]); + guint32 g = CLAMP_D_TO_U8(k * light_components[LIGHT_GREEN]); + guint32 b = CLAMP_D_TO_U8(k * light_components[LIGHT_BLUE]); + guint32 a = std::max(std::max(r, g), b); + + r = premul_alpha(r, a); + g = premul_alpha(g, a); + b = premul_alpha(b, a); + + ASSEMBLE_ARGB32(pxout, a,r,g,b) + return pxout; + } + double _scale, _ks, _exp; +}; + +struct SpecularDistantLight : public SpecularLight { + SpecularDistantLight(cairo_surface_t *bumpmap, SPFeDistantLight *light, guint32 color, + double scale, double specular_constant, double specular_exponent) + : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) + { + DistantLight dl(light, color); + NR::Fvector lv; + dl.light_vector(lv); + dl.light_components(_light_components); + NR::normalized_sum(_halfway, lv, NR::EYE_VECTOR); + } + guint32 operator()(int x, int y) { + return specularLighting(x, y, _halfway, _light_components); + } +private: + NR::Fvector _halfway, _light_components; +}; + +struct SpecularPointLight : public SpecularLight { + SpecularPointLight(cairo_surface_t *bumpmap, SPFePointLight *light, guint32 color, + Geom::Affine const &trans, double scale, double specular_constant, + double specular_exponent, double x0, double y0) + : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) + , _light(light, color, trans) + , _x0(x0) + , _y0(y0) + { + _light.light_components(_light_components); + } + + guint32 operator()(int x, int y) { + NR::Fvector light, halfway; + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + NR::normalized_sum(halfway, light, NR::EYE_VECTOR); + return specularLighting(x, y, halfway, _light_components); + } +private: + PointLight _light; + NR::Fvector _light_components; + double _x0, _y0; +}; + +struct SpecularSpotLight : public SpecularLight { + SpecularSpotLight(cairo_surface_t *bumpmap, SPFeSpotLight *light, guint32 color, + Geom::Affine const &trans, double scale, double specular_constant, + double specular_exponent, double x0, double y0) + : SpecularLight(bumpmap, scale, specular_constant, specular_exponent) + , _light(light, color, trans) + , _x0(x0) + , _y0(y0) + {} + + guint32 operator()(int x, int y) { + NR::Fvector light, halfway, light_components; + _light.light_vector(light, _x0 + x, _y0 + y, _scale * alphaAt(x, y)/255.0); + _light.light_components(light_components, light); + NR::normalized_sum(halfway, light, NR::EYE_VECTOR); + return specularLighting(x, y, halfway, light_components); + } +private: + SpotLight _light; + double _x0, _y0; +}; + +void FilterSpecularLighting::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); + + Geom::Affine trans = slot.get_units().get_matrix_primitiveunits2pb(); + Geom::Point p = slot.get_slot_area().min(); + double x0 = p[Geom::X]; + double y0 = p[Geom::Y]; + double scale = surfaceScale * trans.descrim(); + double ks = specularConstant; + double se = specularExponent; + + switch (light_type) { + case DISTANT_LIGHT: + ink_cairo_surface_synthesize(out, + SpecularDistantLight(input, light.distant, lighting_color, scale, ks, se)); + break; + case POINT_LIGHT: + ink_cairo_surface_synthesize(out, + SpecularPointLight(input, light.point, lighting_color, trans, scale, ks, se, x0, y0)); + break; + case SPOT_LIGHT: + ink_cairo_surface_synthesize(out, + SpecularSpotLight(input, light.spot, lighting_color, trans, scale, ks, se, x0, y0)); + break; + default: { + cairo_t *ct = cairo_create(out); + cairo_set_source_rgba(ct, 0,0,0,1); + cairo_set_operator(ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(ct); + cairo_destroy(ct); + } break; + } + + slot.set(_output, out); + cairo_surface_destroy(out); +} + +/* int FilterSpecularLighting::render(FilterSlot &slot, FilterUnits const &units) { NRPixBlock *in = slot.get(_input); if (!in) { @@ -186,23 +302,16 @@ int FilterSpecularLighting::render(FilterSlot &slot, FilterUnits const &units) { //nr_pixblock_release(in); //delete in; return 0; -} +}*/ void FilterSpecularLighting::area_enlarge(NRRectL &area, Geom::Affine const &trans) { // TODO: support kernelUnitLength - double scalex = std::fabs(trans[0]) + std::fabs(trans[1]); - double scaley = std::fabs(trans[2]) + std::fabs(trans[3]); - - //FIXME: no +2 should be there!... (noticable only for big scales at big zoom factor) - area.x0 -= (int)(scalex) + 2; - area.x1 += (int)(scalex) + 2; - area.y0 -= (int)(scaley) + 2; - area.y1 += (int)(scaley) + 2; -} -FilterTraits FilterSpecularLighting::get_input_traits() { - return TRAIT_PARALLER; + area.x0 -= 1; + area.x1 += 1; + area.y0 -= 1; + area.y1 += 1; } } /* namespace Filters */ diff --git a/src/display/nr-filter-specularlighting.h b/src/display/nr-filter-specularlighting.h index 7c278df89..2fcb02588 100644 --- a/src/display/nr-filter-specularlighting.h +++ b/src/display/nr-filter-specularlighting.h @@ -16,18 +16,24 @@ #include <gdk/gdk.h> #include "display/nr-light-types.h" #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" -#include "filters/distantlight.h" -#include "filters/pointlight.h" -#include "filters/spotlight.h" -#include "color.h" + +class SPFeDistantLight; +class SPFePointLight; +class SPFeSpotLight; namespace Inkscape { namespace Filters { - + +class FilterSlot; + class FilterSpecularLighting : public FilterPrimitive { public: + FilterSpecularLighting(); + static FilterPrimitive *create(); + virtual ~FilterSpecularLighting(); + virtual void render_cairo(FilterSlot &slot); + virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); + union { SPFeDistantLight *distant; SPFePointLight *point; @@ -38,13 +44,6 @@ public: gdouble specularConstant; gdouble specularExponent; guint32 lighting_color; - - FilterSpecularLighting(); - static FilterPrimitive *create(); - virtual ~FilterSpecularLighting(); - virtual int render(FilterSlot &slot, FilterUnits const &units); - virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); private: }; diff --git a/src/display/nr-filter-tile.cpp b/src/display/nr-filter-tile.cpp index b1ca5d191..b88386638 100644 --- a/src/display/nr-filter-tile.cpp +++ b/src/display/nr-filter-tile.cpp @@ -10,6 +10,7 @@ */ #include "display/nr-filter-tile.h" +#include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" namespace Inkscape { @@ -17,7 +18,6 @@ namespace Filters { FilterTile::FilterTile() { - g_warning("FilterTile::render not implemented."); } FilterPrimitive * FilterTile::create() { @@ -27,40 +27,24 @@ FilterPrimitive * FilterTile::create() { FilterTile::~FilterTile() {} -int FilterTile::render(FilterSlot &slot, FilterUnits const &/*units*/) { - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feTile (in=%d)", _input); - return 1; - } - - NRPixBlock *out = new NRPixBlock; - - nr_pixblock_setup_fast(out, in->mode, - in->area.x0, in->area.y0, in->area.x1, in->area.y1, - true); - - unsigned char *in_data = NR_PIXBLOCK_PX(in); - unsigned char *out_data = NR_PIXBLOCK_PX(out); +void FilterTile::render_cairo(FilterSlot &slot) +{ + static bool tile_warning = false; //IMPLEMENT ME! - g_warning("Renderer for feTile is not implemented."); - (void)in_data; - (void)out_data; + if (!tile_warning) { + g_warning("Renderer for feTile is not implemented."); + tile_warning = true; + } - out->empty = FALSE; - slot.set(_output, out); - return 0; + cairo_surface_t *in = slot.getcairo(_input); + slot.set(_output, in); } void FilterTile::area_enlarge(NRRectL &/*area*/, Geom::Affine const &/*trans*/) { } -FilterTraits FilterTile::get_input_traits() { - return TRAIT_PARALLER; -} - } /* namespace Filters */ } /* namespace Inkscape */ diff --git a/src/display/nr-filter-tile.h b/src/display/nr-filter-tile.h index 4a2a0dddc..5c0a3e553 100644 --- a/src/display/nr-filter-tile.h +++ b/src/display/nr-filter-tile.h @@ -13,22 +13,20 @@ */ #include "display/nr-filter-primitive.h" -#include "display/nr-filter-slot.h" -#include "display/nr-filter-units.h" -#include "libnr/nr-rect-l.h" namespace Inkscape { namespace Filters { +class FilterSlot; + class FilterTile : public FilterPrimitive { public: FilterTile(); static FilterPrimitive *create(); virtual ~FilterTile(); - virtual int render(FilterSlot &slot, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); virtual void area_enlarge(NRRectL &area, Geom::Affine const &trans); - virtual FilterTraits get_input_traits(); }; } /* namespace Filters */ diff --git a/src/display/nr-filter-turbulence.cpp b/src/display/nr-filter-turbulence.cpp index a91de0460..6aa435715 100644 --- a/src/display/nr-filter-turbulence.cpp +++ b/src/display/nr-filter-turbulence.cpp @@ -17,30 +17,293 @@ * Released under GNU GPL version 2 (or later), read the file 'COPYING' for more information */ -#include "display/nr-arena-item.h" +#include "display/cairo-templates.h" +#include "display/cairo-utils.h" #include "display/nr-filter.h" #include "display/nr-filter-turbulence.h" #include "display/nr-filter-units.h" #include "display/nr-filter-utils.h" #include "libnr/nr-rect-l.h" -#include "libnr/nr-blit.h" #include <math.h> namespace Inkscape { namespace Filters{ +class TurbulenceGenerator { +public: + TurbulenceGenerator() + : _wrapx(0) + , _wrapy(0) + , _wrapw(0) + , _wraph(0) + , _inited(false) + {} + + void init(long seed, Geom::Rect const &tile, Geom::Point const &freq, bool stitch, + bool fractalnoise, int octaves) + { + // setup random number generator + _setupSeed(seed); + + // set values + _tile = tile; + _baseFreq = freq; + _stitchTiles = stitch; + _fractalnoise = fractalnoise; + _octaves = octaves; + + int i; + for (int k = 0; k < 4; ++k) { + for (i = 0; i < BSize; ++i) { + _latticeSelector[i] = i; + + _gradient[i][k][0] = static_cast<double>(_random() % (BSize*2) - BSize) / BSize; + _gradient[i][k][1] = static_cast<double>(_random() % (BSize*2) - BSize) / BSize; + + // normalize gradient + double s = hypot(_gradient[i][k][0], _gradient[i][k][1]); + _gradient[i][k][0] /= s; + _gradient[i][k][1] /= s; + } + } + while (--i) { + // shuffle lattice selectors + int j = _random() % BSize; + std::swap(_latticeSelector[i], _latticeSelector[j]); + } + + // fill out the remaining part of the gradient + for (i = 0; i < BSize + 2; ++i) + { + _latticeSelector[BSize + i] = _latticeSelector[i]; + + for(int k = 0; k < 4; ++k) { + _gradient[BSize + i][k][0] = _gradient[i][k][0]; + _gradient[BSize + i][k][1] = _gradient[i][k][1]; + } + } + + // When stitching tiled turbulence, the frequencies must be adjusted + // so that the tile borders will be continuous. + if (_stitchTiles) { + if (_baseFreq[Geom::X] != 0.0) + { + double freq = _baseFreq[Geom::X]; + double lo = floor(_tile.width() * freq) / _tile.width(); + double hi = ceil(_tile.width() * freq) / _tile.width(); + _baseFreq[Geom::X] = freq / lo < hi / freq ? lo : hi; + } + if (_baseFreq[Geom::Y] != 0.0) + { + double freq = _baseFreq[Geom::Y]; + double lo = floor(_tile.height() * freq) / _tile.height(); + double hi = ceil(_tile.height() * freq) / _tile.height(); + _baseFreq[Geom::Y] = freq / lo < hi / freq ? lo : hi; + } + + _wrapw = _tile.width() * _baseFreq[Geom::X] + 0.5; + _wraph = _tile.height() * _baseFreq[Geom::Y] + 0.5; + _wrapx = _tile.left() * _baseFreq[Geom::X] + PerlinOffset + _wrapw; + _wrapy = _tile.top() * _baseFreq[Geom::Y] + PerlinOffset + _wraph; + } + _inited = true; + } + + G_GNUC_PURE + guint32 turbulencePixel(Geom::Point const &p) const { + int wrapx = _wrapx, wrapy = _wrapy, wrapw = _wrapw, wraph = _wraph; + + double pixel[4]; + double x = p[Geom::X] * _baseFreq[Geom::X]; + double y = p[Geom::Y] * _baseFreq[Geom::Y]; + double ratio = 1.0; + + for (int k = 0; k < 4; ++k) + pixel[k] = 0.0; + + for(int octave = 0; octave < _octaves; ++octave) + { + double tx = x + PerlinOffset; + double bx = floor(tx); + double rx0 = tx - bx, rx1 = rx0 - 1.0; + int bx0 = bx, bx1 = bx0 + 1; + + double ty = y + PerlinOffset; + double by = floor(ty); + double ry0 = ty - by, ry1 = ry0 - 1.0; + int by0 = by, by1 = by0 + 1; + + if (_stitchTiles) { + if (bx0 >= wrapx) bx0 -= wrapw; + if (bx1 >= wrapx) bx1 -= wrapw; + if (by0 >= wrapy) by0 -= wraph; + if (by1 >= wrapy) by1 -= wraph; + } + bx0 &= BMask; + bx1 &= BMask; + by0 &= BMask; + by1 &= BMask; + + int i = _latticeSelector[bx0]; + int j = _latticeSelector[bx1]; + int b00 = _latticeSelector[i + by0]; + int b01 = _latticeSelector[i + by1]; + int b10 = _latticeSelector[j + by0]; + int b11 = _latticeSelector[j + by1]; + + double sx = _scurve(rx0); + double sy = _scurve(ry0); + + double result[4]; + // channel numbering: R=0, G=1, B=2, A=3 + for (int k = 0; k < 4; ++k) { + double const *qxa = _gradient[b00][k]; + double const *qxb = _gradient[b10][k]; + double a = _lerp(sx, rx0 * qxa[0] + ry0 * qxa[1], + rx1 * qxb[0] + ry0 * qxb[1]); + double const *qya = _gradient[b01][k]; + double const *qyb = _gradient[b11][k]; + double b = _lerp(sx, rx0 * qya[0] + ry1 * qya[1], + rx1 * qyb[0] + ry1 * qyb[1]); + result[k] = _lerp(sy, a, b); + } + + if (_fractalnoise) { + for (int k = 0; k < 4; ++k) + pixel[k] += result[k] / ratio; + } else { + for (int k = 0; k < 4; ++k) + pixel[k] += fabs(result[k]) / ratio; + } + + x *= 2; + y *= 2; + ratio *= 2; + + if(_stitchTiles) + { + // Update stitch values. Subtracting PerlinOffset before the multiplication and + // adding it afterward simplifies to subtracting it once. + wrapw *= 2; + wraph *= 2; + wrapx = wrapx*2 - PerlinOffset; + wrapy = wrapy*2 - PerlinOffset; + } + } + + if (_fractalnoise) { + guint32 r = CLAMP_D_TO_U8((pixel[0]*255.0 + 255.0) / 2); + guint32 g = CLAMP_D_TO_U8((pixel[1]*255.0 + 255.0) / 2); + guint32 b = CLAMP_D_TO_U8((pixel[2]*255.0 + 255.0) / 2); + guint32 a = CLAMP_D_TO_U8((pixel[3]*255.0 + 255.0) / 2); + r = premul_alpha(r, a); + g = premul_alpha(g, a); + b = premul_alpha(b, a); + ASSEMBLE_ARGB32(pxout, a,r,g,b); + return pxout; + } else { + guint32 r = CLAMP_D_TO_U8(pixel[0]*255.0); + guint32 g = CLAMP_D_TO_U8(pixel[1]*255.0); + guint32 b = CLAMP_D_TO_U8(pixel[2]*255.0); + guint32 a = CLAMP_D_TO_U8(pixel[3]*255.0); + r = premul_alpha(r, a); + g = premul_alpha(g, a); + b = premul_alpha(b, a); + ASSEMBLE_ARGB32(pxout, a,r,g,b); + return pxout; + } + } + + //G_GNUC_PURE + /*guint32 turbulencePixel(Geom::Point const &p) const { + if (!_fractalnoise) { + guint32 r = CLAMP_D_TO_U8(turbulence(0, p)*255.0); + guint32 g = CLAMP_D_TO_U8(turbulence(1, p)*255.0); + guint32 b = CLAMP_D_TO_U8(turbulence(2, p)*255.0); + guint32 a = CLAMP_D_TO_U8(turbulence(3, p)*255.0); + r = premul_alpha(r, a); + g = premul_alpha(g, a); + b = premul_alpha(b, a); + ASSEMBLE_ARGB32(pxout, a,r,g,b); + return pxout; + } else { + guint32 r = CLAMP_D_TO_U8((turbulence(0, p)*255.0 + 255.0) / 2); + guint32 g = CLAMP_D_TO_U8((turbulence(1, p)*255.0 + 255.0) / 2); + guint32 b = CLAMP_D_TO_U8((turbulence(2, p)*255.0 + 255.0) / 2); + guint32 a = CLAMP_D_TO_U8((turbulence(3, p)*255.0 + 255.0) / 2); + r = premul_alpha(r, a); + g = premul_alpha(g, a); + b = premul_alpha(b, a); + ASSEMBLE_ARGB32(pxout, a,r,g,b); + return pxout; + } + }*/ + + bool ready() const { return _inited; } + void dirty() { _inited = false; } + +private: + void _setupSeed(long seed) { + _seed = seed; + if (_seed <= 0) _seed = -(_seed % (RAND_m - 1)) + 1; + if (_seed > RAND_m - 1) _seed = RAND_m - 1; + } + long _random() { + /* Produces results in the range [1, 2**31 - 2]. + * Algorithm is: r = (a * r) mod m + * where a = 16807 and m = 2**31 - 1 = 2147483647 + * See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988 + * To test: the algorithm should produce the result 1043618065 + * as the 10,000th generated number if the original seed is 1. */ + _seed = RAND_a * (_seed % RAND_q) - RAND_r * (_seed / RAND_q); + if (_seed <= 0) _seed += RAND_m; + return _seed; + } + static inline double _scurve(double t) { + return t * t * (3.0 - 2.0*t); + } + static inline double _lerp(double t, double a, double b) { + return a + t * (b-a); + } + + // random number generator constants + static long const + RAND_m = 2147483647, // 2**31 - 1 + RAND_a = 16807, // 7**5; primitive root of m + RAND_q = 127773, // m / a + RAND_r = 2836; // m % a + + // other constants + static int const + BSize = 0x100, + BMask = 0xff; + static double const + PerlinOffset = 4096.0; + + Geom::Rect _tile; + Geom::Point _baseFreq; + int _latticeSelector[2*BSize + 2]; + double _gradient[2*BSize + 2][4][2]; + long _seed; + int _octaves; + bool _stitchTiles; + int _wrapx, _wrapy, _wrapw, _wraph; + bool _inited; + bool _fractalnoise; +}; + FilterTurbulence::FilterTurbulence() -: XbaseFrequency(0), - YbaseFrequency(0), - numOctaves(1), - seed(0), - updated(false), - updated_area(NR::IPoint(), NR::IPoint()), - pix(NULL), - fTileWidth(10), //guessed - fTileHeight(10), //guessed - fTileX(1), //guessed - fTileY(1) //guessed + : gen(new TurbulenceGenerator()) + , XbaseFrequency(0) + , YbaseFrequency(0) + , numOctaves(1) + , seed(0) + , updated(false) + , updated_area(NR::IPoint(), NR::IPoint()) + , fTileWidth(10) //guessed + , fTileHeight(10) //guessed + , fTileX(1) //guessed + , fTileY(1) //guessed { } @@ -50,305 +313,79 @@ FilterPrimitive * FilterTurbulence::create() { FilterTurbulence::~FilterTurbulence() { - if (pix) { - nr_pixblock_release(pix); - delete pix; - } + delete gen; } void FilterTurbulence::set_baseFrequency(int axis, double freq){ if (axis==0) XbaseFrequency=freq; if (axis==1) YbaseFrequency=freq; + gen->dirty(); } void FilterTurbulence::set_numOctaves(int num){ - numOctaves=num; + numOctaves = num; + gen->dirty(); } void FilterTurbulence::set_seed(double s){ - seed=s; + seed = s; + gen->dirty(); } void FilterTurbulence::set_stitchTiles(bool st){ - stitchTiles=st; + stitchTiles = st; + gen->dirty(); } void FilterTurbulence::set_type(FilterTurbulenceType t){ - type=t; + type = t; + gen->dirty(); } void FilterTurbulence::set_updated(bool u){ - updated=u; } -void FilterTurbulence::render_area(NRPixBlock *pix, NR::IRect &full_area, FilterUnits const &units) { - const int bbox_x0 = full_area.min()[NR::X]; - const int bbox_y0 = full_area.min()[NR::Y]; - const int bbox_x1 = full_area.max()[NR::X]; - const int bbox_y1 = full_area.max()[NR::Y]; - - Geom::Affine unit_trans = units.get_matrix_primitiveunits2pb().inverse(); - - double point[2]; - - unsigned char *pb = NR_PIXBLOCK_PX(pix); - - if (type==TURBULENCE_TURBULENCE){ - for (int y = std::max(bbox_y0, pix->area.y0); y < std::min(bbox_y1, pix->area.y1); y++){ - int out_line = (y - pix->area.y0) * pix->rs; - point[1] = y * unit_trans[3] + unit_trans[5]; - for (int x = std::max(bbox_x0, pix->area.x0); x < std::min(bbox_x1, pix->area.x1); x++){ - int out_pos = out_line + 4 * (x - pix->area.x0); - point[0] = x * unit_trans[0] + unit_trans[4]; - pb[out_pos] = CLAMP_D_TO_U8( turbulence(0,point)*255 ); // CLAMP includes rounding! - pb[out_pos + 1] = CLAMP_D_TO_U8( turbulence(1,point)*255 ); - pb[out_pos + 2] = CLAMP_D_TO_U8( turbulence(2,point)*255 ); - pb[out_pos + 3] = CLAMP_D_TO_U8( turbulence(3,point)*255 ); - } - } - } else { - for (int y = std::max(bbox_y0, pix->area.y0); y < std::min(bbox_y1, pix->area.y1); y++){ - int out_line = (y - pix->area.y0) * pix->rs; - point[1] = y * unit_trans[3] + unit_trans[5]; - for (int x = std::max(bbox_x0, pix->area.x0); x < std::min(bbox_x1, pix->area.x1); x++){ - int out_pos = out_line + 4 * (x - pix->area.x0); - point[0] = x * unit_trans[0] + unit_trans[4]; - pb[out_pos] = CLAMP_D_TO_U8( ((turbulence(0,point)*255) +255)/2 ); - pb[out_pos + 1] = CLAMP_D_TO_U8( ((turbulence(1,point)*255)+255)/2 ); - pb[out_pos + 2] = CLAMP_D_TO_U8( ((turbulence(2,point)*255) +255)/2 ); - pb[out_pos + 3] = CLAMP_D_TO_U8( ((turbulence(3,point)*255) +255)/2 ); - } - } +struct Turbulence { + Turbulence(TurbulenceGenerator const &gen, Geom::Affine const &trans, int x0, int y0) + : _gen(gen) + , _trans(trans) + , _x0(x0), _y0(y0) + {} + guint32 operator()(int x, int y) { + Geom::Point point(x + _x0, y + _y0); + point *= _trans; + return _gen.turbulencePixel(point); } +private: + TurbulenceGenerator const &_gen; + Geom::Affine _trans; + int _x0, _y0; +}; - pix->empty = FALSE; -} - -void FilterTurbulence::update_pixbuffer(NR::IRect &area, FilterUnits const &units) { - int bbox_x0 = area.min()[NR::X]; - int bbox_y0 = area.min()[NR::Y]; - int bbox_x1 = area.max()[NR::X]; - int bbox_y1 = area.max()[NR::Y]; - - TurbulenceInit((long)seed); - - if (!pix){ - pix = new NRPixBlock; - nr_pixblock_setup_fast(pix, NR_PIXBLOCK_MODE_R8G8B8A8N, bbox_x0, bbox_y0, bbox_x1, bbox_y1, true); - } - else if (bbox_x0 != pix->area.x0 || bbox_y0 != pix->area.y0 || - bbox_x1 != pix->area.x1 || bbox_y1 != pix->area.y1) - { - /* TODO: release-setup cycle not actually needed, if pixblock - * width and height don't change */ - nr_pixblock_release(pix); - nr_pixblock_setup_fast(pix, NR_PIXBLOCK_MODE_R8G8B8A8N, bbox_x0, bbox_y0, bbox_x1, bbox_y1, true); - } - - /* This limits pre-rendered turbulence to two megapixels. This is - * arbitary limit and could be something other, too. - * If bigger area is needed, visible area is rendered on demand. */ - if (!pix || (pix->size != NR_PIXBLOCK_SIZE_TINY && pix->data.px == NULL) || - ((bbox_x1 - bbox_x0) * (bbox_y1 - bbox_y0) > 2*1024*1024)) { - pix_data = NULL; - return; +void FilterTurbulence::render_cairo(FilterSlot &slot) +{ + cairo_surface_t *input = slot.getcairo(_input); + cairo_surface_t *out = ink_cairo_surface_create_same_size(input, CAIRO_CONTENT_COLOR_ALPHA); + + if (!gen->ready()) { + Geom::Point ta(fTileX, fTileY); + Geom::Point tb(fTileX + fTileWidth, fTileY + fTileHeight); + gen->init(seed, Geom::Rect(ta, tb), + Geom::Point(XbaseFrequency, YbaseFrequency), stitchTiles, + type == TURBULENCE_FRACTALNOISE, numOctaves); } - render_area(pix, area, units); - - pix_data = NR_PIXBLOCK_PX(pix); - - updated=true; - updated_area = area; -} + Geom::Affine unit_trans = slot.get_units().get_matrix_primitiveunits2pb().inverse(); + Geom::Rect slot_area = slot.get_slot_area(); + double x0 = slot_area.min()[Geom::X]; + double y0 = slot_area.min()[Geom::Y]; -int FilterTurbulence::render(FilterSlot &slot, FilterUnits const &units) { - NR::IRect area = units.get_pixblock_filterarea_paraller(); - // TODO: could be faster - updated_area only has to be same size as area - if (!updated || updated_area != area) update_pixbuffer(area, units); + ink_cairo_surface_synthesize(out, Turbulence(*gen, unit_trans, x0, y0)); - NRPixBlock *in = slot.get(_input); - if (!in) { - g_warning("Missing source image for feTurbulence (in=%d)", _input); - return 1; - } + cairo_surface_mark_dirty(out); - NRPixBlock *out = new NRPixBlock; - int x0 = in->area.x0, y0 = in->area.y0; - int x1 = in->area.x1, y1 = in->area.y1; - nr_pixblock_setup_fast(out, NR_PIXBLOCK_MODE_R8G8B8A8N, x0, y0, x1, y1, true); - - if (pix_data) { - /* If pre-rendered output of whole filter area exists, just copy it. */ - nr_blit_pixblock_pixblock(out, pix); - } else { - /* No pre-rendered output, render the required area here. */ - render_area(out, area, units); - } - - out->empty = FALSE; slot.set(_output, out); - return 0; -} - -long FilterTurbulence::Turbulence_setup_seed(long lSeed) -{ - if (lSeed <= 0) lSeed = -(lSeed % (RAND_m - 1)) + 1; - if (lSeed > RAND_m - 1) lSeed = RAND_m - 1; - return lSeed; -} - -long FilterTurbulence::TurbulenceRandom(long lSeed) -{ - long result; - result = RAND_a * (lSeed % RAND_q) - RAND_r * (lSeed / RAND_q); - if (result <= 0) result += RAND_m; - return result; -} - -void FilterTurbulence::TurbulenceInit(long lSeed) -{ - double s; - int i, j, k; - lSeed = Turbulence_setup_seed(lSeed); - for(k = 0; k < 4; k++) - { - for(i = 0; i < BSize; i++) - { - uLatticeSelector[i] = i; - for (j = 0; j < 2; j++) - fGradient[k][i][j] = (double)(((lSeed = TurbulenceRandom(lSeed)) % (BSize + BSize)) - BSize) / BSize; - s = double(sqrt(fGradient[k][i][0] * fGradient[k][i][0] + fGradient[k][i][1] * fGradient[k][i][1])); - fGradient[k][i][0] /= s; - fGradient[k][i][1] /= s; - } - } - while(--i) - { - k = uLatticeSelector[i]; - uLatticeSelector[i] = uLatticeSelector[j = (lSeed = TurbulenceRandom(lSeed)) % BSize]; - uLatticeSelector[j] = k; - } - for(i = 0; i < BSize + 2; i++) - { - uLatticeSelector[BSize + i] = uLatticeSelector[i]; - for(k = 0; k < 4; k++) - for(j = 0; j < 2; j++) - fGradient[k][BSize + i][j] = fGradient[k][i][j]; - } -} - -double FilterTurbulence::TurbulenceNoise2(int nColorChannel, double vec[2], StitchInfo *pStitchInfo) -{ - int bx0, bx1, by0, by1, b00, b10, b01, b11; - double rx0, rx1, ry0, ry1, *q, sx, sy, a, b, t, u, v; - int i, j; - t = vec[0] + PerlinN; - bx0 = (int)t; - bx1 = bx0+1; - rx0 = t - (int)t; - rx1 = rx0 - 1.0f; - t = vec[1] + PerlinN; - by0 = (int)t; - by1 = by0+1; - ry0 = t - (int)t; - ry1 = ry0 - 1.0f; - // If stitching, adjust lattice points accordingly. - if(pStitchInfo != NULL) - { - if(bx0 >= pStitchInfo->nWrapX) - bx0 -= pStitchInfo->nWidth; - if(bx1 >= pStitchInfo->nWrapX) - bx1 -= pStitchInfo->nWidth; - if(by0 >= pStitchInfo->nWrapY) - by0 -= pStitchInfo->nHeight; - if(by1 >= pStitchInfo->nWrapY) - by1 -= pStitchInfo->nHeight; - } - bx0 &= BM; - bx1 &= BM; - by0 &= BM; - by1 &= BM; - i = uLatticeSelector[bx0]; - j = uLatticeSelector[bx1]; - b00 = uLatticeSelector[i + by0]; - b10 = uLatticeSelector[j + by0]; - b01 = uLatticeSelector[i + by1]; - b11 = uLatticeSelector[j + by1]; - sx = double(s_curve(rx0)); - sy = double(s_curve(ry0)); - q = fGradient[nColorChannel][b00]; u = rx0 * q[0] + ry0 * q[1]; - q = fGradient[nColorChannel][b10]; v = rx1 * q[0] + ry0 * q[1]; - a = turb_lerp(sx, u, v); - q = fGradient[nColorChannel][b01]; u = rx0 * q[0] + ry1 * q[1]; - q = fGradient[nColorChannel][b11]; v = rx1 * q[0] + ry1 * q[1]; - b = turb_lerp(sx, u, v); - return turb_lerp(sy, a, b); -} - -double FilterTurbulence::turbulence(int nColorChannel, double *point) -{ - StitchInfo stitch; - StitchInfo *pStitchInfo = NULL; // Not stitching when NULL. - // Adjust the base frequencies if necessary for stitching. - if(stitchTiles) - { - // When stitching tiled turbulence, the frequencies must be adjusted - // so that the tile borders will be continuous. - if(XbaseFrequency != 0.0) - { - double fLoFreq = double(floor(fTileWidth * XbaseFrequency)) / fTileWidth; - double fHiFreq = double(ceil(fTileWidth * XbaseFrequency)) / fTileWidth; - if(XbaseFrequency / fLoFreq < fHiFreq / XbaseFrequency) - XbaseFrequency = fLoFreq; - else - XbaseFrequency = fHiFreq; - } - if(YbaseFrequency != 0.0) - { - double fLoFreq = double(floor(fTileHeight * YbaseFrequency)) / fTileHeight; - double fHiFreq = double(ceil(fTileHeight * YbaseFrequency)) / fTileHeight; - if(YbaseFrequency / fLoFreq < fHiFreq / YbaseFrequency) - YbaseFrequency = fLoFreq; - else - YbaseFrequency = fHiFreq; - } - // Set up TurbulenceInitial stitch values. - pStitchInfo = &stitch; - stitch.nWidth = int(fTileWidth * XbaseFrequency + 0.5f); - stitch.nWrapX = int(fTileX * XbaseFrequency + PerlinN + stitch.nWidth); - stitch.nHeight = int(fTileHeight * YbaseFrequency + 0.5f); - stitch.nWrapY = int(fTileY * YbaseFrequency + PerlinN + stitch.nHeight); - } - double fSum = 0.0f; - double vec[2]; - vec[0] = point[0] * XbaseFrequency; - vec[1] = point[1] * YbaseFrequency; - double ratio = 1; - for(int nOctave = 0; nOctave < numOctaves; nOctave++) - { - if(type==TURBULENCE_FRACTALNOISE) - fSum += double(TurbulenceNoise2(nColorChannel, vec, pStitchInfo) / ratio); - else - fSum += double(fabs(TurbulenceNoise2(nColorChannel, vec, pStitchInfo)) / ratio); - vec[0] *= 2; - vec[1] *= 2; - ratio *= 2; - if(pStitchInfo != NULL) - { - // Update stitch values. Subtracting PerlinN before the multiplication and - // adding it afterward simplifies to subtracting it once. - stitch.nWidth *= 2; - stitch.nWrapX = 2 * stitch.nWrapX - PerlinN; - stitch.nHeight *= 2; - stitch.nWrapY = 2 * stitch.nWrapY - PerlinN; - } - } - return fSum; -} - -FilterTraits FilterTurbulence::get_input_traits() { - return TRAIT_PARALLER; + cairo_surface_destroy(out); } } /* namespace Filters */ diff --git a/src/display/nr-filter-turbulence.h b/src/display/nr-filter-turbulence.h index ee870f758..50161b6be 100644 --- a/src/display/nr-filter-turbulence.h +++ b/src/display/nr-filter-turbulence.h @@ -21,6 +21,7 @@ * Released under GNU GPL, read the file 'COPYING' for more information */ +#include <2geom/point.h> #include "display/nr-filter-primitive.h" #include "display/nr-filter-slot.h" #include "display/nr-filter-units.h" @@ -35,32 +36,7 @@ enum FilterTurbulenceType { TURBULENCE_ENDTYPE }; -struct StitchInfo -{ - int nWidth; // How much to subtract to wrap for stitching. - int nHeight; - int nWrapX; // Minimum value to wrap. - int nWrapY; -}; - -/* Produces results in the range [1, 2**31 - 2]. -Algorithm is: r = (a * r) mod m -where a = 16807 and m = 2**31 - 1 = 2147483647 -See [Park & Miller], CACM vol. 31 no. 10 p. 1195, Oct. 1988 -To test: the algorithm should produce the result 1043618065 -as the 10,000th generated number if the original seed is 1. -*/ -#define RAND_m 2147483647 /* 2**31 - 1 */ -#define RAND_a 16807 /* 7**5; primitive root of m */ -#define RAND_q 127773 /* m / a */ -#define RAND_r 2836 /* m % a */ -#define BSize 0x100 -#define BM 0xff -#define PerlinN 0x1000 -#define NP 12 /* 2^PerlinN */ -#define NM 0xfff -#define s_curve(t) ( t * t * (3. - 2. * t) ) -#define turb_lerp(t, a, b) ( a + t * (b - a) ) +class TurbulenceGenerator; class FilterTurbulence : public FilterPrimitive { public: @@ -68,9 +44,7 @@ public: static FilterPrimitive *create(); virtual ~FilterTurbulence(); - virtual int render(FilterSlot &slot, FilterUnits const &units); - void update_pixbuffer(NR::IRect &area, FilterUnits const &units); - void render_area(NRPixBlock *pix, NR::IRect &full_area, FilterUnits const &units); + virtual void render_cairo(FilterSlot &slot); void set_baseFrequency(int axis, double freq); void set_numOctaves(int num); @@ -78,14 +52,11 @@ public: void set_stitchTiles(bool st); void set_type(FilterTurbulenceType t); void set_updated(bool u); - virtual FilterTraits get_input_traits(); private: - long Turbulence_setup_seed(long lSeed); - long TurbulenceRandom(long lSeed); - void TurbulenceInit(long lSeed); - double TurbulenceNoise2(int nColorChannel, double vec[2], StitchInfo *pStitchInfo); - double turbulence(int nColorChannel, double *point); + TurbulenceGenerator *gen; + + void turbulenceInit(long seed); double XbaseFrequency, YbaseFrequency; int numOctaves; @@ -94,17 +65,14 @@ private: FilterTurbulenceType type; bool updated; NR::IRect updated_area; - NRPixBlock *pix; unsigned char *pix_data; - int uLatticeSelector[BSize + BSize + 2]; - double fGradient[4][BSize + BSize + 2][2]; - double fTileWidth; double fTileHeight; double fTileX; double fTileY; + }; } /* namespace Filters */ diff --git a/src/display/nr-filter-units.h b/src/display/nr-filter-units.h index b78e102cd..2fc3e5533 100644 --- a/src/display/nr-filter-units.h +++ b/src/display/nr-filter-units.h @@ -13,8 +13,6 @@ */ #include "sp-filter-units.h" -#include "libnr/nr-matrix.h" -#include "libnr/nr-rect.h" #include "libnr/nr-rect-l.h" #include <2geom/affine.h> #include <2geom/rect.h> @@ -22,6 +20,18 @@ namespace Inkscape { namespace Filters { +/* Notes: + * - "filter units" is a coordinate system where the filter region is contained + * between (0,0) and (1,1). Do not confuse this with the filterUnits property + * - "primitive units" is the coordinate system in which all lengths and distances + * in the filter definition should be interpreted. They are affected by the value + * of the primitiveUnits attribute + * - "pb" is the coordinate system in which filter rendering happens. + * It might be aligned with user or screen coordinates depending on + * the filter primitives used in the filter. + * - "display" are world coordinates of the canvas - pixel grid coordinates + * of the drawing area translated so that (0,0) corresponds to the document origin + */ class FilterUnits { public: FilterUnits(); diff --git a/src/display/nr-filter.cpp b/src/display/nr-filter.cpp index 85815c31a..55190b00c 100644 --- a/src/display/nr-filter.cpp +++ b/src/display/nr-filter.cpp @@ -15,6 +15,7 @@ #include <cmath> #include <cstring> #include <string> +#include <cairo.h> #include "display/nr-filter.h" #include "display/nr-filter-primitive.h" @@ -41,8 +42,6 @@ #include "display/nr-arena.h" #include "display/nr-arena-item.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-blit.h" #include <2geom/affine.h> #include <2geom/rect.h> #include "svg/svg-length.h" @@ -60,43 +59,14 @@ namespace Filters { using Geom::X; using Geom::Y; -static Geom::OptRect get_item_bbox(NRArenaItem const *item) { - Geom::Rect item_bbox; - if (item->item_bbox) { - item_bbox = *(item->item_bbox); - } else { - // Bounding box might not exist, so create a dummy one. - Geom::Point zero(0, 0); - item_bbox = Geom::Rect(zero, zero); - } - if (item_bbox.min()[X] > item_bbox.max()[X] - || item_bbox.min()[Y] > item_bbox.max()[Y]) - { - // In case of negative-size bbox, return an empty OptRect - return Geom::OptRect(); - } - return Geom::OptRect(item_bbox); -} - Filter::Filter() { - _primitive_count = 0; - _primitive_table_size = 1; - _primitive = new FilterPrimitive*[1]; - _primitive[0] = NULL; - //_primitive_count = 1; - //_primitive[0] = new FilterGaussian; _common_init(); } Filter::Filter(int n) { - _primitive_count = 0; - _primitive_table_size = (n > 0) ? n : 1; // we guarantee there is at least 1(one) filter slot - _primitive = new FilterPrimitive*[_primitive_table_size]; - for ( int i = 0 ; i < _primitive_table_size ; i++ ) { - _primitive[i] = NULL; - } + if (n > 0) _primitive.reserve(n); _common_init(); } @@ -125,51 +95,56 @@ void Filter::_common_init() { Filter::~Filter() { clear_primitives(); - delete[] _primitive; } -int Filter::render(NRArenaItem const *item, NRPixBlock *pb) +int Filter::render(NRArenaItem const *item, cairo_t *bgct, NRRectL const *bgarea, cairo_t *graphic, NRRectL const *area) { - if (!_primitive[0]) { - // TODO: Should clear the input buffer instead of just returning - return 1; + if (_primitive.empty()) { + // when no primitives are defined, clear source graphic + cairo_set_source_rgba(graphic, 0,0,0,0); + cairo_set_operator(graphic, CAIRO_OPERATOR_SOURCE); + cairo_paint(graphic); + cairo_set_operator(graphic, CAIRO_OPERATOR_OVER); + return 1; } FilterQuality const filterquality = (FilterQuality)item->arena->filterquality; int const blurquality = item->arena->blurquality; Geom::Affine trans = item->ctm; - FilterSlot slot(_slot_count, item); - slot.set_quality(filterquality); - slot.set_blurquality(blurquality); Geom::Rect item_bbox; { - Geom::OptRect maybe_bbox = get_item_bbox(item); + Geom::OptRect maybe_bbox = item->item_bbox; if (maybe_bbox.isEmpty()) { // Code below needs a bounding box return 1; } item_bbox = *maybe_bbox; } - - Geom::Rect filter_area = filter_effect_area(item_bbox); if (item_bbox.hasZeroArea()) { // It's no use to try and filter an empty object. return 1; } + Geom::Rect filter_area = filter_effect_area(item_bbox); FilterUnits units(_filter_units, _primitive_units); units.set_ctm(trans); units.set_item_bbox(item_bbox); units.set_filter_area(filter_area); - // TODO: with filterRes of 0x0 should return an empty image std::pair<double,double> resolution = _filter_resolution(filter_area, trans, filterquality); - if(!(resolution.first > 0 && resolution.second > 0)) - return 1; + if (!(resolution.first > 0 && resolution.second > 0)) { + // zero resolution - clear source graphic and return + cairo_set_source_rgba(graphic, 0,0,0,0); + cairo_set_operator(graphic, CAIRO_OPERATOR_SOURCE); + cairo_paint(graphic); + cairo_set_operator(graphic, CAIRO_OPERATOR_OVER); + return 1; + } + units.set_resolution(resolution.first, resolution.second); if (_x_pixels > 0) { units.set_automatic_resolution(false); @@ -179,47 +154,29 @@ int Filter::render(NRArenaItem const *item, NRPixBlock *pb) } units.set_paraller(false); - for (int i = 0 ; i < _primitive_count ; i++) { - if (_primitive[i]->get_input_traits() & TRAIT_PARALLER) { + Geom::Affine pbtrans = units.get_matrix_display2pb(); + for (unsigned i = 0 ; i < _primitive.size() ; i++) { + if (!_primitive[i]->can_handle_affine(pbtrans)) { units.set_paraller(true); break; } } - slot.set_units(units); - - NRPixBlock *in = new NRPixBlock; - nr_pixblock_setup_fast(in, pb->mode, pb->area.x0, pb->area.y0, - pb->area.x1, pb->area.y1, true); - if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) { - g_warning("Inkscape::Filters::Filter::render: failed to reserve temporary buffer"); - return 0; - } - nr_blit_pixblock_pixblock(in, pb); - in->empty = FALSE; - slot.set(NR_FILTER_SOURCEGRAPHIC, in); - - // Check that we are rendering a non-empty area - in = slot.get(NR_FILTER_SOURCEGRAPHIC); - if (in->area.x1 - in->area.x0 <= 0 || in->area.y1 - in->area.y0 <= 0) { - if (in->area.x1 - in->area.x0 < 0 || in->area.y1 - in->area.y0 < 0) { - g_warning("Inkscape::Filters::Filter::render: negative area! (%d, %d) (%d, %d)", - in->area.x0, in->area.y0, in->area.x1, in->area.y1); - } - return 0; - } - in = NULL; // in is now handled by FilterSlot, we should not touch it + FilterSlot slot(const_cast<NRArenaItem*>(item), bgct, bgarea, cairo_get_target(graphic), area, units); + slot.set_quality(filterquality); + slot.set_blurquality(blurquality); - for (int i = 0 ; i < _primitive_count ; i++) { - _primitive[i]->render(slot, units); + for (unsigned i = 0 ; i < _primitive.size() ; i++) { + _primitive[i]->render_cairo(slot); } - slot.get_final(_output_slot, pb); + cairo_surface_t *result = slot.get_result(_output_slot); + cairo_set_source_surface(graphic, result, area->x0, area->y0); + cairo_set_operator(graphic, CAIRO_OPERATOR_SOURCE); + cairo_paint(graphic); + cairo_set_operator(graphic, CAIRO_OPERATOR_OVER); + cairo_surface_destroy(result); - // Take note of the amount of used image slots - // -> next time this filter is rendered, we can reserve enough slots - // immediately - _slot_count = slot.get_slot_count(); return 0; } @@ -232,9 +189,10 @@ void Filter::set_primitive_units(SPFilterUnits unit) { } void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const { - for (int i = 0 ; i < _primitive_count ; i++) { + for (unsigned i = 0 ; i < _primitive.size() ; i++) { if (_primitive[i]) _primitive[i]->area_enlarge(bbox, item->ctm); } + /* TODO: something. See images at the bottom of filters.svg with medium-low filtering quality. @@ -248,7 +206,7 @@ void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const { } Geom::Rect item_bbox; - Geom::OptRect maybe_bbox = get_item_bbox(item); + Geom::OptRect maybe_bbox = item->item_bbox; if (maybe_bbox.isEmpty()) { // Code below needs a bounding box return; @@ -268,30 +226,29 @@ void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const { */ } -void Filter::bbox_enlarge(NRRectL &bbox) { +void Filter::compute_drawbox(NRArenaItem const *item, NRRectL &item_bbox) { // Modifying empty bounding boxes confuses rest of the renderer, so // let's not do that. - if (bbox.x0 > bbox.x1 || bbox.y0 > bbox.y1) return; + if (item_bbox.x0 > item_bbox.x1 || item_bbox.y0 > item_bbox.y1) return; - /* TODO: this is wrong. Should use bounding box in user coordinates - * and find its extents in display coordinates. */ - Geom::Point min(bbox.x0, bbox.y0); - Geom::Point max(bbox.x1, bbox.y1); + Geom::Point min(item_bbox.x0, item_bbox.y0); + Geom::Point max(item_bbox.x1, item_bbox.y1); Geom::Rect tmp_bbox(min, max); Geom::Rect enlarged = filter_effect_area(tmp_bbox); + enlarged = enlarged * item->ctm; - bbox.x0 = (NR::ICoord)enlarged.min()[X]; - bbox.y0 = (NR::ICoord)enlarged.min()[Y]; - bbox.x1 = (NR::ICoord)enlarged.max()[X]; - bbox.y1 = (NR::ICoord)enlarged.max()[Y]; + item_bbox.x0 = (NR::ICoord) floor(enlarged.min()[X]); + item_bbox.y0 = (NR::ICoord) floor(enlarged.min()[Y]); + item_bbox.x1 = (NR::ICoord) ceil(enlarged.max()[X]); + item_bbox.y1 = (NR::ICoord) ceil(enlarged.max()[Y]); } Geom::Rect Filter::filter_effect_area(Geom::Rect const &bbox) { Geom::Point minp, maxp; - double len_x = bbox.max()[X] - bbox.min()[X]; - double len_y = bbox.max()[Y] - bbox.min()[Y]; + double len_x = bbox.width(); + double len_y = bbox.height(); /* TODO: fetch somehow the object ex and em lengths */ _region_x.update(12, 6, len_x); _region_y.update(12, 6, len_y); @@ -367,27 +324,6 @@ void Filter::_create_constructor_table() created = true; } -/** Helper method for enlarging table of filter primitives. When new - * primitives are added, but we have no space for them, this function - * makes some more space. - */ -void Filter::_enlarge_primitive_table() { - FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2]; - for (int i = 0 ; i < _primitive_count ; i++) { - new_tbl[i] = _primitive[i]; - } - _primitive_table_size *= 2; - for (int i = _primitive_count ; i < _primitive_table_size ; i++) { - new_tbl[i] = NULL; - } - if(_primitive != NULL) { - delete[] _primitive; - } else { - g_warning("oh oh"); - } - _primitive = new_tbl; -} - int Filter::add_primitive(FilterPrimitiveType type) { _create_constructor_table(); @@ -398,14 +334,8 @@ int Filter::add_primitive(FilterPrimitiveType type) if (!_constructor[type]) return -1; FilterPrimitive *created = _constructor[type](); - // If there is no space for new filter primitive, enlarge the table - if (_primitive_count >= _primitive_table_size) { - _enlarge_primitive_table(); - } - - _primitive[_primitive_count] = created; - int handle = _primitive_count; - _primitive_count++; + int handle = _primitive.size(); + _primitive.push_back(created); return handle; } @@ -415,8 +345,7 @@ int Filter::replace_primitive(int target, FilterPrimitiveType type) // Check that target is valid primitive inside this filter if (target < 0) return -1; - if (target >= _primitive_count) return -1; - if (!_primitive[target]) return -1; + if (static_cast<unsigned>(target) >= _primitive.size()) return -1; // Check that we can create a new filter of specified type if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE) @@ -424,27 +353,22 @@ int Filter::replace_primitive(int target, FilterPrimitiveType type) if (!_constructor[type]) return -1; FilterPrimitive *created = _constructor[type](); - // If there is no space for new filter primitive, enlarge the table - if (_primitive_count >= _primitive_table_size) { - _enlarge_primitive_table(); - } - delete _primitive[target]; _primitive[target] = created; return target; } FilterPrimitive *Filter::get_primitive(int handle) { - if (handle < 0 || handle >= _primitive_count) return NULL; + if (handle < 0 || handle >= static_cast<int>(_primitive.size())) return NULL; return _primitive[handle]; } void Filter::clear_primitives() { - for (int i = 0 ; i < _primitive_count ; i++) { - if (_primitive[i]) delete _primitive[i]; + for (unsigned i = 0 ; i < _primitive.size() ; i++) { + delete _primitive[i]; } - _primitive_count = 0; + _primitive.clear(); } void Filter::set_x(SVGLength const &length) diff --git a/src/display/nr-filter.h b/src/display/nr-filter.h index ae5f96420..e1d4c10e5 100644 --- a/src/display/nr-filter.h +++ b/src/display/nr-filter.h @@ -13,10 +13,9 @@ */ //#include "display/nr-arena-item.h" +#include <cairo.h> #include "display/nr-filter-primitive.h" #include "display/nr-filter-types.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-matrix.h" #include "libnr/nr-rect.h" #include "svg/svg-length.h" #include "sp-filter-units.h" @@ -29,7 +28,12 @@ namespace Filters { class Filter : public Inkscape::GC::Managed<> { public: - int render(NRArenaItem const *item, NRPixBlock *pb); + /** Given background state from @a bgct and an intermediate rendering from the surface + * backing @a graphic, modify the contents of the surface backing @a graphic to represent + * the results of filter rendering. @a bgarea and @a area specify bounding boxes + * of both surfaces in world coordinates; Cairo contexts are assumed to be in default state + * (0,0 = surface origin, no path, OVER operator) */ + int render(NRArenaItem const *item, cairo_t *bgct, NRRectL const *bgarea, cairo_t *graphic, NRRectL const *area); /** * Creates a new filter primitive under this filter object. @@ -147,10 +151,11 @@ public: */ void area_enlarge(NRRectL &area, NRArenaItem const *item) const; /** - * Given an object bounding box, this function enlarges it so that - * it contains the filter effect area. + * Given an item bounding box (in user coords), this function enlarges it + * to contain the filter effects region and transforms it to screen + * coordinates */ - void bbox_enlarge(NRRectL &bbox); + void compute_drawbox(NRArenaItem const *item, NRRectL &item_bbox); /** * Returns the filter effects area in user coordinate system. * The given bounding box should be a bounding box as specified in @@ -170,9 +175,7 @@ public: virtual ~Filter(); private: - int _primitive_count; - int _primitive_table_size; - + std::vector<FilterPrimitive*> _primitive; /** Amount of image slots used, when this filter was rendered last time */ int _slot_count; @@ -194,10 +197,7 @@ private: SPFilterUnits _filter_units; SPFilterUnits _primitive_units; - FilterPrimitive ** _primitive; - void _create_constructor_table(); - void _enlarge_primitive_table(); void _common_init(); int _resolution_limit(FilterQuality const quality) const; std::pair<double,double> _filter_resolution(Geom::Rect const &area, diff --git a/src/display/nr-light.cpp b/src/display/nr-light.cpp index 74d83da70..65912470d 100644 --- a/src/display/nr-light.cpp +++ b/src/display/nr-light.cpp @@ -13,12 +13,12 @@ #include <cmath> -#include "libnr/nr-pixops.h" #include "display/nr-light.h" #include "display/nr-3dutils.h" #include "filters/distantlight.h" #include "filters/pointlight.h" #include "filters/spotlight.h" +#include "color.h" namespace Inkscape { namespace Filters { @@ -38,9 +38,9 @@ void DistantLight::light_vector(NR::Fvector &v) { } void DistantLight::light_components(NR::Fvector &lc) { - lc[LIGHT_RED] = NR_RGBA32_R(color); - lc[LIGHT_GREEN] = NR_RGBA32_G(color); - lc[LIGHT_BLUE] = NR_RGBA32_B(color); + lc[LIGHT_RED] = SP_RGBA32_R_U(color); + lc[LIGHT_GREEN] = SP_RGBA32_G_U(color); + lc[LIGHT_BLUE] = SP_RGBA32_B_U(color); } PointLight::PointLight(SPFePointLight *light, guint32 lighting_color, const Geom::Affine &trans) { @@ -61,9 +61,9 @@ void PointLight::light_vector(NR::Fvector &v, gdouble x, gdouble y, gdouble z) { } void PointLight::light_components(NR::Fvector &lc) { - lc[LIGHT_RED] = NR_RGBA32_R(color); - lc[LIGHT_GREEN] = NR_RGBA32_G(color); - lc[LIGHT_BLUE] = NR_RGBA32_B(color); + lc[LIGHT_RED] = SP_RGBA32_R_U(color); + lc[LIGHT_GREEN] = SP_RGBA32_G_U(color); + lc[LIGHT_BLUE] = SP_RGBA32_B_U(color); } SpotLight::SpotLight(SPFeSpotLight *light, guint32 lighting_color, const Geom::Affine &trans) { @@ -101,9 +101,9 @@ void SpotLight::light_components(NR::Fvector &lc, const NR::Fvector &L) { spmod = 0; else spmod = std::pow(spmod, speExp); - lc[LIGHT_RED] = spmod * NR_RGBA32_R(color); - lc[LIGHT_GREEN] = spmod * NR_RGBA32_G(color); - lc[LIGHT_BLUE] = spmod * NR_RGBA32_B(color); + lc[LIGHT_RED] = spmod * SP_RGBA32_R_U(color); + lc[LIGHT_GREEN] = spmod * SP_RGBA32_G_U(color); + lc[LIGHT_BLUE] = spmod * SP_RGBA32_B_U(color); } } /* namespace Filters */ diff --git a/src/display/nr-plain-stuff-gdk.cpp b/src/display/nr-plain-stuff-gdk.cpp deleted file mode 100644 index d5b43f4ea..000000000 --- a/src/display/nr-plain-stuff-gdk.cpp +++ /dev/null @@ -1,46 +0,0 @@ -#define __NR_PLAIN_STUFF_GDK_C__ - -/* - * Miscellaneous simple rendering utilities - * - * Author: - * Lauris Kaplinski <lauris@ximian.com> - * - * Copyright (C) 2001 Lauris Kaplinski and Ximian, Inc. - * - * Released under GNU GPL - */ - -#include <libnr/nr-pixblock-pattern.h> -#include "nr-plain-stuff.h" -#include "nr-plain-stuff-gdk.h" - -void -nr_gdk_draw_rgba32_solid (GdkDrawable *drawable, GdkGC *gc, gint x, gint y, gint w, gint h, guint32 rgba) -{ - NRPixBlock pb; - - nr_pixblock_setup_fast (&pb, NR_PIXBLOCK_MODE_R8G8B8A8N, 0, 0, w, h, FALSE); - - nr_render_rgba32_rgb (NR_PIXBLOCK_PX (&pb), w, h, pb.rs, x, y, rgba); - gdk_draw_rgb_image (drawable, gc, x, y, w, h, GDK_RGB_DITHER_MAX, NR_PIXBLOCK_PX (&pb), pb.rs); - - nr_pixblock_release (&pb); -} - -void -nr_gdk_draw_gray_garbage (GdkDrawable *drawable, GdkGC *gc, gint x, gint y, gint w, gint h) -{ - for (gint yy = y; yy < y + h; yy += 64) { - for (gint xx = x; xx < x + w; xx += 64) { - NRPixBlock pb; - gint ex = MIN (xx + 64, x + w); - gint ey = MIN (yy + 64, y + h); - nr_pixblock_setup_fast (&pb, NR_PIXBLOCK_MODE_R8G8B8, xx, yy, ex, ey, FALSE); - nr_pixblock_render_gray_noise (&pb, NULL); - gdk_draw_rgb_image (drawable, gc, xx, yy, ex - xx, ey - yy, GDK_RGB_DITHER_NONE, NR_PIXBLOCK_PX (&pb), pb.rs); - nr_pixblock_release (&pb); - } - } -} - diff --git a/src/display/nr-plain-stuff-gdk.h b/src/display/nr-plain-stuff-gdk.h deleted file mode 100644 index bff54a81f..000000000 --- a/src/display/nr-plain-stuff-gdk.h +++ /dev/null @@ -1,32 +0,0 @@ -#ifndef __NR_PLAIN_STUFF_GDK_H__ -#define __NR_PLAIN_STUFF_GDK_H__ - -/* - * Miscellaneous simple rendering utilities - * - * Author: - * Lauris Kaplinski <lauris@ximian.com> - * - * Copyright (C) 2001 Lauris Kaplinski and Ximian, Inc. - * - * Released under GNU GPL - */ - -#include <gdk/gdk.h> - -void nr_gdk_draw_rgba32_solid (GdkDrawable *drawable, GdkGC *gc, gint x, gint y, gint w, gint h, guint32 rgba); - -void nr_gdk_draw_gray_garbage (GdkDrawable *drawable, GdkGC *gc, gint x, gint y, gint w, gint h); - -#endif - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-plain-stuff.cpp b/src/display/nr-plain-stuff.cpp deleted file mode 100644 index 62a61102e..000000000 --- a/src/display/nr-plain-stuff.cpp +++ /dev/null @@ -1,94 +0,0 @@ -#define __NR_PLAIN_STUFF_C__ - -/* - * Miscellaneous simple rendering utilities - * - * Author: - * Lauris Kaplinski <lauris@ximian.com> - * - * Copyright (C) 2001 Lauris Kaplinski and Ximian, Inc. - * - * Released under GNU GPL - */ - -#include <glib/gmessages.h> -#include <libnr/nr-pixops.h> -#include "nr-plain-stuff.h" - -#define NR_DEFAULT_CHECKERSIZEP2 2 -#define NR_DEFAULT_CHECKERCOLOR0 0xbfbfbfff -#define NR_DEFAULT_CHECKERCOLOR1 0x808080ff - -void -nr_render_checkerboard_rgb (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff) -{ - g_return_if_fail (px != NULL); - - nr_render_checkerboard_rgb_custom (px, w, h, rs, xoff, yoff, NR_DEFAULT_CHECKERCOLOR0, NR_DEFAULT_CHECKERCOLOR1, NR_DEFAULT_CHECKERSIZEP2); -} - -void -nr_render_checkerboard_rgb_custom (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff, guint32 c0, guint32 c1, gint sizep2) -{ - gint x, y, m; - guint r0, g0, b0; - guint r1, g1, b1; - - g_return_if_fail (px != NULL); - g_return_if_fail (sizep2 >= 0); - g_return_if_fail (sizep2 <= 8); - - xoff &= 0x1ff; - yoff &= 0x1ff; - m = 0x1 << sizep2; - r0 = NR_RGBA32_R (c0); - g0 = NR_RGBA32_G (c0); - b0 = NR_RGBA32_B (c0); - r1 = NR_RGBA32_R (c1); - g1 = NR_RGBA32_G (c1); - b1 = NR_RGBA32_B (c1); - - for (y = 0; y < h; y++) { - guchar *p; - p = px; - for (x = 0; x < w; x++) { - if (((x + xoff) ^ (y + yoff)) & m) { - *p++ = r0; - *p++ = g0; - *p++ = b0; - } else { - *p++ = r1; - *p++ = g1; - *p++ = b1; - } - } - px += rs; - } -} - -void -nr_render_rgba32_rgb (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff, guint32 c) -{ - guint32 c0, c1; - gint a, r, g, b, cr, cg, cb; - - g_return_if_fail (px != NULL); - - r = NR_RGBA32_R (c); - g = NR_RGBA32_G (c); - b = NR_RGBA32_B (c); - a = NR_RGBA32_A (c); - - cr = NR_COMPOSEN11_1111 (r, a, NR_RGBA32_R (NR_DEFAULT_CHECKERCOLOR0)); - cg = NR_COMPOSEN11_1111 (g, a, NR_RGBA32_G (NR_DEFAULT_CHECKERCOLOR0)); - cb = NR_COMPOSEN11_1111 (b, a, NR_RGBA32_B (NR_DEFAULT_CHECKERCOLOR0)); - c0 = (cr << 24) | (cg << 16) | (cb << 8) | 0xff; - - cr = NR_COMPOSEN11_1111 (r, a, NR_RGBA32_R (NR_DEFAULT_CHECKERCOLOR1)); - cg = NR_COMPOSEN11_1111 (g, a, NR_RGBA32_G (NR_DEFAULT_CHECKERCOLOR1)); - cb = NR_COMPOSEN11_1111 (b, a, NR_RGBA32_B (NR_DEFAULT_CHECKERCOLOR1)); - c1 = (cr << 24) | (cg << 16) | (cb << 8) | 0xff; - - nr_render_checkerboard_rgb_custom (px, w, h, rs, xoff, yoff, c0, c1, NR_DEFAULT_CHECKERSIZEP2); -} - diff --git a/src/display/nr-plain-stuff.h b/src/display/nr-plain-stuff.h deleted file mode 100644 index 457442312..000000000 --- a/src/display/nr-plain-stuff.h +++ /dev/null @@ -1,33 +0,0 @@ -#ifndef __NR_PLAIN_STUFF_H__ -#define __NR_PLAIN_STUFF_H__ - -/* - * Miscellaneous simple rendering utilities - * - * Author: - * Lauris Kaplinski <lauris@ximian.com> - * - * Copyright (C) 2001 Lauris Kaplinski and Ximian, Inc. - * - * Released under GNU GPL - */ - -#include <glib/gtypes.h> - -void nr_render_checkerboard_rgb (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff); -void nr_render_checkerboard_rgb_custom (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff, guint32 c0, guint32 c1, gint sizep2); - -void nr_render_rgba32_rgb (guchar *px, gint w, gint h, gint rs, gint xoff, gint yoff, guint32 c); - -#endif - -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/nr-style.cpp b/src/display/nr-style.cpp new file mode 100644 index 000000000..72fa0c444 --- /dev/null +++ b/src/display/nr-style.cpp @@ -0,0 +1,218 @@ +/** + * @file + * @brief Style information for rendering + *//* + * Authors: + * Krzysztof Kosiński <tweenk.pl@gmail.com> + * + * Copyright (C) 2010 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#include "display/nr-style.h" +#include "style.h" +#include "sp-paint-server.h" +#include "display/canvas-bpath.h" // contains SPStrokeJoinType, SPStrokeCapType etc. (WTF!) + +void NRStyle::Paint::clear() +{ + if (server) { + sp_object_unref(server, NULL); + server = NULL; + } + type = PAINT_NONE; +} + +void NRStyle::Paint::set(SPColor const &c) +{ + clear(); + type = PAINT_COLOR; + color = c; +} + +void NRStyle::Paint::set(SPPaintServer *ps) +{ + clear(); + if (ps) { + type = PAINT_SERVER; + server = ps; + sp_object_ref(server, NULL); + } +} + +NRStyle::NRStyle() + : fill() + , stroke() + , stroke_width(0.0) + , miter_limit(0.0) + , n_dash(0) + , dash(NULL) + , dash_offset(0.0) + , fill_rule(CAIRO_FILL_RULE_EVEN_ODD) + , line_cap(CAIRO_LINE_CAP_BUTT) + , line_join(CAIRO_LINE_JOIN_MITER) + , fill_pattern(NULL) + , stroke_pattern(NULL) +{} + +NRStyle::~NRStyle() +{ + if (fill_pattern) cairo_pattern_destroy(fill_pattern); + if (stroke_pattern) cairo_pattern_destroy(stroke_pattern); + if (dash) delete dash; +} + +void NRStyle::set(SPStyle *style) +{ + if ( style->fill.isPaintserver() ) { + fill.set(style->getFillPaintServer()); + } else if ( style->fill.isColor() ) { + fill.set(style->fill.value.color); + } else if ( style->fill.isNone() ) { + fill.clear(); + } else { + g_assert_not_reached(); + } + fill.opacity = SP_SCALE24_TO_FLOAT(style->fill_opacity.value); + + switch (style->fill_rule.computed) { + case SP_WIND_RULE_EVENODD: + fill_rule = CAIRO_FILL_RULE_EVEN_ODD; + break; + case SP_WIND_RULE_NONZERO: + fill_rule = CAIRO_FILL_RULE_WINDING; + break; + default: + g_assert_not_reached(); + } + + if ( style->stroke.isPaintserver() ) { + stroke.set(style->getStrokePaintServer()); + } else if ( style->stroke.isColor() ) { + stroke.set(style->stroke.value.color); + } else if ( style->stroke.isNone() ) { + stroke.clear(); + } else { + g_assert_not_reached(); + } + stroke.opacity = SP_SCALE24_TO_FLOAT(style->stroke_opacity.value); + stroke_width = style->stroke_width.computed; + switch (style->stroke_linecap.computed) { + case SP_STROKE_LINECAP_ROUND: + line_cap = CAIRO_LINE_CAP_ROUND; + break; + case SP_STROKE_LINECAP_SQUARE: + line_cap = CAIRO_LINE_CAP_SQUARE; + break; + case SP_STROKE_LINECAP_BUTT: + line_cap = CAIRO_LINE_CAP_BUTT; + break; + default: + g_assert_not_reached(); + } + switch (style->stroke_linejoin.computed) { + case SP_STROKE_LINEJOIN_ROUND: + line_join = CAIRO_LINE_JOIN_ROUND; + break; + case SP_STROKE_LINEJOIN_BEVEL: + line_join = CAIRO_LINE_JOIN_BEVEL; + break; + case SP_STROKE_LINEJOIN_MITER: + line_join = CAIRO_LINE_JOIN_MITER; + break; + default: + g_assert_not_reached(); + } + miter_limit = style->stroke_miterlimit.value; + + if (dash) delete [] dash; + + n_dash = style->stroke_dash.n_dash; + if (n_dash != 0) { + dash_offset = style->stroke_dash.offset; + dash = new double[n_dash]; + for (unsigned int i = 0; i < n_dash; ++i) { + dash[i] = style->stroke_dash.dash[i]; + } + } else { + dash_offset = 0.0; + dash = NULL; + } + + update(); +} + +bool NRStyle::prepareFill(cairo_t *ct, NRRect *paintbox) +{ + // update fill pattern + if (!fill_pattern) { + switch (fill.type) { + case PAINT_SERVER: + fill_pattern = sp_paint_server_create_pattern(fill.server, ct, paintbox, fill.opacity); + break; + case PAINT_COLOR: { + SPColor const &c = fill.color; + fill_pattern = cairo_pattern_create_rgba( + c.v.c[0], c.v.c[1], c.v.c[2], fill.opacity); + } break; + default: break; + } + } + if (!fill_pattern) return false; + return true; +} + +void NRStyle::applyFill(cairo_t *ct) +{ + cairo_set_source(ct, fill_pattern); + cairo_set_fill_rule(ct, fill_rule); +} + +bool NRStyle::prepareStroke(cairo_t *ct, NRRect *paintbox) +{ + if (!stroke_pattern) { + switch (stroke.type) { + case PAINT_SERVER: + stroke_pattern = sp_paint_server_create_pattern(stroke.server, ct, paintbox, stroke.opacity); + break; + case PAINT_COLOR: { + SPColor const &c = stroke.color; + stroke_pattern = cairo_pattern_create_rgba( + c.v.c[0], c.v.c[1], c.v.c[2], stroke.opacity); + } break; + default: break; + } + } + if (!stroke_pattern) return false; + return true; +} + +void NRStyle::applyStroke(cairo_t *ct) +{ + cairo_set_source(ct, stroke_pattern); + cairo_set_line_width(ct, stroke_width); + cairo_set_line_cap(ct, line_cap); + cairo_set_line_join(ct, line_join); + cairo_set_miter_limit(ct, miter_limit); + cairo_set_dash(ct, dash, n_dash, dash_offset); +} + +void NRStyle::update() +{ + // force pattern update + if (fill_pattern) cairo_pattern_destroy(fill_pattern); + if (stroke_pattern) cairo_pattern_destroy(stroke_pattern); + fill_pattern = NULL; + stroke_pattern = NULL; +} + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/src/display/nr-style.h b/src/display/nr-style.h new file mode 100644 index 000000000..e741e46b4 --- /dev/null +++ b/src/display/nr-style.h @@ -0,0 +1,81 @@ +/** + * @file + * @brief Style information for rendering + *//* + * Authors: + * Krzysztof Kosiński <tweenk.pl@gmail.com> + * + * Copyright (C) 2010 Authors + * Released under GNU GPL, read the file 'COPYING' for more information + */ + +#ifndef SEEN_INKSCAPE_DISPLAY_NR_ARENA_STYLE_H +#define SEEN_INKSCAPE_DISPLAY_NR_ARENA_STYLE_H + +#include <cairo.h> +#include "color.h" + +class SPColor; +class SPPaintServer; +class SPStyle; +struct NRRect; + +struct NRStyle { + NRStyle(); + ~NRStyle(); + + void set(SPStyle *); + bool prepareFill(cairo_t *ct, NRRect *paintbox); + bool prepareStroke(cairo_t *ct, NRRect *paintbox); + void applyFill(cairo_t *ct); + void applyStroke(cairo_t *ct); + void update(); + + enum PaintType { + PAINT_NONE, + PAINT_COLOR, + PAINT_SERVER + }; + + struct Paint { + Paint() : type(PAINT_NONE), color(0), server(NULL), opacity(1.0) {} + ~Paint() { clear(); } + + PaintType type; + SPColor color; + SPPaintServer *server; + float opacity; + + void clear(); + void set(SPColor const &c); + void set(SPPaintServer *ps); + }; + + Paint fill; + Paint stroke; + float stroke_width; + float miter_limit; + unsigned int n_dash; + double *dash; + float dash_offset; + cairo_fill_rule_t fill_rule; + cairo_line_cap_t line_cap; + cairo_line_join_t line_join; + + cairo_pattern_t *fill_pattern; + cairo_pattern_t *stroke_pattern; +}; + +#endif + + +/* + Local Variables: + mode:c++ + c-file-style:"stroustrup" + c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) + indent-tabs-mode:nil + fill-column:99 + End: +*/ +// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 : diff --git a/src/display/nr-svgfonts.cpp b/src/display/nr-svgfonts.cpp index cf23ee5d5..8869274d4 100644 --- a/src/display/nr-svgfonts.cpp +++ b/src/display/nr-svgfonts.cpp @@ -14,21 +14,21 @@ #include <2geom/pathvector.h> #include <2geom/transforms.h> -#include "../style.h" #include <cairo.h> #include <vector> +#include "style.h" #include "svg/svg.h" -#include "inkscape-cairo.h" -#include "nr-svgfonts.h" -#include "../sp-path.h" -#include "../sp-object-group.h" -#include "../sp-use.h" -#include "../sp-use-reference.h" -#include "curve.h" +#include "display/cairo-utils.h" +#include "display/nr-svgfonts.h" +#include "display/nr-svgfonts.h" +#include "sp-path.h" +#include "sp-object-group.h" +#include "sp-use.h" +#include "sp-use-reference.h" +#include "display/curve.h" #include "xml/repr.h" #include "sp-font-face.h" - //*************************// // UserFont Implementation // //*************************// diff --git a/src/display/pixblock-scaler.cpp b/src/display/pixblock-scaler.cpp deleted file mode 100644 index 5af5230d8..000000000 --- a/src/display/pixblock-scaler.cpp +++ /dev/null @@ -1,299 +0,0 @@ -#define __NR_PIXBLOCK_SCALER_CPP__ - -/* - * Functions for blitting pixblocks using scaling - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2006,2009 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include <glib.h> -#include <cmath> -#if defined (SOLARIS) && (SOLARIS == 8) -#include "round.h" -using Inkscape::round; -#endif -using std::floor; - -#include "display/nr-filter-utils.h" -#include "libnr/nr-pixblock.h" -#include "libnr/nr-blit.h" -#include <2geom/forward.h> - -namespace NR { - -struct RGBA { - double r, g, b, a; -}; - -/** Calculates cubically interpolated value of the four given pixel values. - * The pixel values should be from four adjacent pixels in source image or - * four adjacent interpolated values. len should be the x- or y-coordinate - * (depending on interpolation direction) of the center of the target pixel - * in source image coordinates. - */ -__attribute__ ((const)) -inline static double sample(double const a, double const b, - double const c, double const d, - double const len) -{ - double lena = 1.5 + (len - round(len)); - double lenb = 0.5 + (len - round(len)); - double lenc = 0.5 - (len - round(len)); - double lend = 1.5 - (len - round(len)); - double const f = -0.5; // corresponds to cubic Hermite spline - double sum = 0; - sum += ((((f * lena) - 5.0 * f) * lena + 8.0 * f) * lena - 4 * f) * a; - sum += (((f + 2.0) * lenb - (f + 3.0)) * lenb * lenb + 1.0) * b; - sum += (((f + 2.0) * lenc - (f + 3.0)) * lenc * lenc + 1.0) * c; - sum += ((((f * lend) - 5.0 * f) * lend + 8.0 * f) * lend - 4 * f) * d; - - return sum; -} - -/** - * Sanity check function for indexing pixblocks. - * Catches reading and writing outside the pixblock area. - * When enabled, decreases filter rendering speed massively. - */ -inline static void _check_index(NRPixBlock const * const pb, int const location, int const line) -{ - if(false) { - int max_loc = pb->rs * (pb->area.y1 - pb->area.y0); - if (location < 0 || (location + 4) > max_loc) - g_warning("Location %d out of bounds (0 ... %d) at line %d", location, max_loc, line); - } -} - -static void scale_bicubic_rgba(NRPixBlock *to, NRPixBlock *from, - Geom::Affine const &trans) -{ - if (NR_PIXBLOCK_BPP(from) != 4 || NR_PIXBLOCK_BPP(to) != 4) { - g_warning("A non-32-bpp image passed to scale_bicubic_rgba: scaling aborted."); - return; - } - - bool free_from_on_exit = false; - if (from->mode != to->mode){ - NRPixBlock *o_from = from; - from = new NRPixBlock; - nr_pixblock_setup_fast(from, to->mode, o_from->area.x0, o_from->area.y0, o_from->area.x1, o_from->area.y1, false); - nr_blit_pixblock_pixblock(from, o_from); - free_from_on_exit = true; - } - - // Precalculate sizes of source and destination pixblocks - int from_width = from->area.x1 - from->area.x0; - int from_height = from->area.y1 - from->area.y0; - int to_width = to->area.x1 - to->area.x0; - int to_height = to->area.y1 - to->area.y0; - - // from_step: when advancing one pixel in destination image, - // how much we should advance in source image - double from_stepx = 1.0 / trans[0]; - double from_stepy = 1.0 / trans[3]; - double from_diffx = from_stepx * (-trans[4]); - double from_diffy = from_stepy * (-trans[5]); - from_diffx = (to->area.x0 * from_stepx + from_diffx) - from->area.x0; - from_diffy = (to->area.y0 * from_stepy + from_diffy) - from->area.y0; - - // Loop through every pixel of destination image, a line at a time - for (int to_y = 0 ; to_y < to_height ; to_y++) { - double from_y = (to_y + 0.5) * from_stepy + from_diffy; - // Pre-calculate beginning of the four horizontal lines, from - // which we should read - int from_line[4]; - for (int i = 0 ; i < 4 ; i++) { - int fy_line = (int)round(from_y) + i - 2; - if (fy_line >= 0) { - if (fy_line < from_height) { - from_line[i] = fy_line * from->rs; - } else { - from_line[i] = (from_height - 1) * from->rs; - } - } else { - from_line[i] = 0; - } - } - // Loop through this horizontal line in destination image - // For every pixel, calculate the color of pixel with - // bicubic interpolation and set the pixel value in destination image - for (int to_x = 0 ; to_x < to_width ; to_x++) { - double from_x = (to_x + 0.5) * from_stepx + from_diffx; - RGBA line[4]; - for (int i = 0 ; i < 4 ; i++) { - int k = (int)round(from_x) + i - 2; - if (k < 0) k = 0; - if (k >= from_width) k = from_width - 1; - k *= 4; - _check_index(from, from_line[0] + k, __LINE__); - _check_index(from, from_line[1] + k, __LINE__); - _check_index(from, from_line[2] + k, __LINE__); - _check_index(from, from_line[3] + k, __LINE__); - line[i].r = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k], - NR_PIXBLOCK_PX(from)[from_line[1] + k], - NR_PIXBLOCK_PX(from)[from_line[2] + k], - NR_PIXBLOCK_PX(from)[from_line[3] + k], - from_y); - line[i].g = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 1], - from_y); - line[i].b = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 2], - from_y); - line[i].a = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 3], - from_y); - } - RGBA result; - result.r = round(sample(line[0].r, line[1].r, line[2].r, line[3].r, - from_x)); - result.g = round(sample(line[0].g, line[1].g, line[2].g, line[3].g, - from_x)); - result.b = round(sample(line[0].b, line[1].b, line[2].b, line[3].b, - from_x)); - result.a = round(sample(line[0].a, line[1].a, line[2].a, line[3].a, - from_x)); - - _check_index(to, to_y * to->rs + to_x * 4, __LINE__); - - using Inkscape::Filters::clamp; - using Inkscape::Filters::clamp_alpha; - if (to->mode == NR_PIXBLOCK_MODE_R8G8B8A8P) { - /* Clamp the colour channels to range from 0 to result.a to - * make sure, we don't exceed 100% per colour channel with - * images that have premultiplied alpha */ - - int const alpha = clamp((int)result.a); - - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4] - = clamp_alpha((int)result.r, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 1] - = clamp_alpha((int)result.g, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 2] - = clamp_alpha((int)result.b, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 3] = alpha; - } else { - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4] - = clamp((int)result.r); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 1] - = clamp((int)result.g); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 2] - = clamp((int)result.b); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 3] - = clamp((int)result.a); - } - } - } - if (free_from_on_exit) { - nr_pixblock_release(from); - delete from; - } - -} - -void scale_bicubic_alpha(NRPixBlock *to, NRPixBlock *from, - Geom::Affine const &trans) -{ - if (NR_PIXBLOCK_BPP(from) != 1 || NR_PIXBLOCK_BPP(to) != 1) { - g_warning("A non-8-bpp image passed to scale_bicubic_alpha: scaling aborted."); - return; - } - - // Precalculate sizes of source and destination pixblocks - int from_width = from->area.x1 - from->area.x0; - int from_height = from->area.y1 - from->area.y0; - int to_width = to->area.x1 - to->area.x0; - int to_height = to->area.y1 - to->area.y0; - - // from_step: when advancing one pixel in destination image, - // how much we should advance in source image - double from_stepx = 1.0 / trans[0]; - double from_stepy = 1.0 / trans[3]; - double from_diffx = from_stepx * (-trans[4]); - double from_diffy = from_stepy * (-trans[5]); - from_diffx = (to->area.x0 * from_stepx + from_diffx) - from->area.x0; - from_diffy = (to->area.y0 * from_stepy + from_diffy) - from->area.y0; - - // Loop through every pixel of destination image, a line at a time - for (int to_y = 0 ; to_y < to_height ; to_y++) { - double from_y = (to_y + 0.5) * from_stepy - from_diffy; - // Pre-calculate beginning of the four horizontal lines, from - // which we should read - int from_line[4]; - for (int i = 0 ; i < 4 ; i++) { - int fy_line = (int)round(from_y) + i - 2; - if (fy_line >= 0) { - if (fy_line < from_height) { - from_line[i] = fy_line * from->rs; - } else { - from_line[i] = (from_height - 1) * from->rs; - } - } else { - from_line[i] = 0; - } - } - // Loop through this horizontal line in destination image - // For every pixel, calculate the color of pixel with - // bicubic interpolation and set the pixel value in destination image - for (int to_x = 0 ; to_x < to_width ; to_x++) { - double from_x = (to_x + 0.5) * from_stepx - from_diffx; - double line[4]; - for (int i = 0 ; i < 4 ; i++) { - int k = (int)round(from_x) + i - 2; - if (k < 0) k = 0; - if (k >= from_width) k = from_width - 1; - _check_index(from, from_line[0] + k, __LINE__); - _check_index(from, from_line[1] + k, __LINE__); - _check_index(from, from_line[2] + k, __LINE__); - _check_index(from, from_line[3] + k, __LINE__); - line[i] = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k], - NR_PIXBLOCK_PX(from)[from_line[1] + k], - NR_PIXBLOCK_PX(from)[from_line[2] + k], - NR_PIXBLOCK_PX(from)[from_line[3] + k], - from_y); - } - int result; - result = (int)round(sample(line[0], line[1], line[2], line[3], - from_x)); - - _check_index(to, to_y * to->rs + to_x, __LINE__); - - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x] - = Inkscape::Filters::clamp(result); - } - } -} - -void scale_bicubic(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans) -{ - if (NR_PIXBLOCK_BPP(to) == 4 && NR_PIXBLOCK_BPP(from) == 4) { - scale_bicubic_rgba(to, from, trans); - } else if (NR_PIXBLOCK_BPP(to) == 1 && NR_PIXBLOCK_BPP(from) == 1) { - scale_bicubic_alpha(to, from, trans); - } else { - g_warning("NR::scale_bicubic: unsupported bitdepths for scaling: to %d, from %d", NR_PIXBLOCK_BPP(to), NR_PIXBLOCK_BPP(from)); - } -} - -} /* namespace NR */ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/pixblock-scaler.h b/src/display/pixblock-scaler.h deleted file mode 100644 index ff9613ab8..000000000 --- a/src/display/pixblock-scaler.h +++ /dev/null @@ -1,40 +0,0 @@ -#ifndef __NR_PIXBLOCK_SCALER_H__ -#define __NR_PIXBLOCK_SCALER_H__ - -/* - * Functions for blitting pixblocks using scaling - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2006 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "libnr/nr-pixblock.h" -#include <2geom/forward.h> - -namespace NR { - -/** Blits the second pixblock to the first. - * Image in source pixblock is scaled to the size of destination pixblock - * using bicubic interpolation. - * Source pixblock is not modified in process. - * Only works for 32-bpp images. - */ -void scale_bicubic(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans); - -} /* namespace NR */ - -#endif // __NR_PIXBLOCK_SCALER_H__ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/pixblock-transform.cpp b/src/display/pixblock-transform.cpp deleted file mode 100644 index 5d5b8a9cf..000000000 --- a/src/display/pixblock-transform.cpp +++ /dev/null @@ -1,279 +0,0 @@ -#define __NR_PIXBLOCK_SCALER_CPP__ - -/* - * Functions for blitting pixblocks using matrix transformation - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2006,2009 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include <glib.h> -#include <cmath> -#if defined (SOLARIS) && (SOLARIS == 8) -#include "round.h" -using Inkscape::round; -#endif -using std::floor; - -#include "display/nr-filter-utils.h" - -#include "libnr/nr-blit.h" -#include "libnr/nr-pixblock.h" -#include <2geom/affine.h> - -namespace NR { - -struct RGBA { - double r, g, b, a; -}; -struct RGBAi { - int r, g, b, a; -}; - -/** - * Sanity check function for indexing pixblocks. - * Catches reading and writing outside the pixblock area. - * When enabled, decreases filter rendering speed massively. - */ -inline void _check_index(NRPixBlock const * const pb, int const location, int const line) -{ - if(false) { - int max_loc = pb->rs * (pb->area.y1 - pb->area.y0); - if (location < 0 || (location + 4) > max_loc) - g_warning("Location %d out of bounds (0 ... %d) at line %d", location, max_loc, line); - } -} - -void transform_nearest(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans) -{ - if (NR_PIXBLOCK_BPP(from) != 4 || NR_PIXBLOCK_BPP(to) != 4) { - g_warning("A non-32-bpp image passed to transform_nearest: scaling aborted."); - return; - } - - bool free_from_on_exit = false; - if (from->mode != to->mode){ - NRPixBlock *o_from = from; - from = new NRPixBlock; - nr_pixblock_setup_fast(from, to->mode, o_from->area.x0, o_from->area.y0, o_from->area.x1, o_from->area.y1, false); - nr_blit_pixblock_pixblock(from, o_from); - free_from_on_exit = true; - } - - // Precalculate sizes of source and destination pixblocks - int from_width = from->area.x1 - from->area.x0; - int from_height = from->area.y1 - from->area.y0; - int to_width = to->area.x1 - to->area.x0; - int to_height = to->area.y1 - to->area.y0; - - Geom::Affine itrans = trans.inverse(); - - // Loop through every pixel of destination image, a line at a time - for (int to_y = 0 ; to_y < to_height ; to_y++) { - for (int to_x = 0 ; to_x < to_width ; to_x++) { - RGBAi result = {0,0,0,0}; - - int from_x = (int)floor(itrans[0] * (to_x + 0.5 + to->area.x0) - + itrans[2] * (to_y + 0.5 + to->area.y0) - + itrans[4]); - from_x -= from->area.x0; - int from_y = (int)floor(itrans[1] * (to_x + 0.5 + to->area.x0) - + itrans[3] * (to_y + 0.5 + to->area.y0) - + itrans[5]); - from_y -= from->area.y0; - - if (from_x >= 0 && from_x < from_width - && from_y >= 0 && from_y < from_height) { - _check_index(from, from_y * from->rs + from_x * 4, __LINE__); - result.r = NR_PIXBLOCK_PX(from)[from_y * from->rs + from_x * 4]; - result.g = NR_PIXBLOCK_PX(from)[from_y * from->rs + from_x * 4 + 1]; - result.b = NR_PIXBLOCK_PX(from)[from_y * from->rs + from_x * 4 + 2]; - result.a = NR_PIXBLOCK_PX(from)[from_y * from->rs + from_x * 4 + 3]; - } - - _check_index(to, to_y * to->rs + to_x * 4, __LINE__); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4] = result.r; - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 1] = result.g; - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 2] = result.b; - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 3] = result.a; - } - } - if (free_from_on_exit) { - nr_pixblock_release(from); - delete from; - } -} - -/** Calculates cubically interpolated value of the four given pixel values. - * The pixel values should be from four adjacent pixels in source image or - * four adjacent interpolated values. len should be the x- or y-coordinate - * (depending on interpolation direction) of the center of the target pixel - * in source image coordinates. - */ -__attribute__ ((const)) -inline static double sample(double const a, double const b, - double const c, double const d, - double const len) -{ - double lena = 1.5 + (len - round(len)); - double lenb = 0.5 + (len - round(len)); - double lenc = 0.5 - (len - round(len)); - double lend = 1.5 - (len - round(len)); - double const f = -0.5; // corresponds to cubic Hermite spline - double sum = 0; - sum += ((((f * lena) - 5.0 * f) * lena + 8.0 * f) * lena - 4 * f) * a; - sum += (((f + 2.0) * lenb - (f + 3.0)) * lenb * lenb + 1.0) * b; - sum += (((f + 2.0) * lenc - (f + 3.0)) * lenc * lenc + 1.0) * c; - sum += ((((f * lend) - 5.0 * f) * lend + 8.0 * f) * lend - 4 * f) * d; - - return sum; -} - -void transform_bicubic(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans) -{ - if (NR_PIXBLOCK_BPP(from) != 4 || NR_PIXBLOCK_BPP(to) != 4) { - g_warning("A non-32-bpp image passed to transform_bicubic: scaling aborted."); - return; - } - - bool free_from_on_exit = false; - if (from->mode != to->mode){ - NRPixBlock *o_from = from; - from = new NRPixBlock; - nr_pixblock_setup_fast(from, to->mode, o_from->area.x0, o_from->area.y0, o_from->area.x1, o_from->area.y1, false); - nr_blit_pixblock_pixblock(from, o_from); - free_from_on_exit = true; - } - - if (from->mode != NR_PIXBLOCK_MODE_R8G8B8A8P) { - // TODO: Fix this... (The problem is that for interpolation non-premultiplied colors should be premultiplied...) - g_warning("transform_bicubic does not properly support non-premultiplied images"); - } - - // Precalculate sizes of source and destination pixblocks - int from_width = from->area.x1 - from->area.x0; - int from_height = from->area.y1 - from->area.y0; - int to_width = to->area.x1 - to->area.x0; - int to_height = to->area.y1 - to->area.y0; - - Geom::Affine itrans = trans.inverse(); - - // Loop through every pixel of destination image, a line at a time - for (int to_y = 0 ; to_y < to_height ; to_y++) { - for (int to_x = 0 ; to_x < to_width ; to_x++) { - double from_x = itrans[0] * (to_x + 0.5 + to->area.x0) - + itrans[2] * (to_y + 0.5 + to->area.y0) - + itrans[4] - from->area.x0; - double from_y = itrans[1] * (to_x + 0.5 + to->area.x0) - + itrans[3] * (to_y + 0.5 + to->area.y0) - + itrans[5] - from->area.y0; - - if (from_x < 0 || from_x >= from_width || - from_y < 0 || from_y >= from_height) { - continue; - } - - RGBA line[4]; - - int from_line[4]; - for (int i = 0 ; i < 4 ; i++) { - int fy_line = (int)round(from_y) + i - 2; - if (fy_line >= 0) { - if (fy_line < from_height) { - from_line[i] = fy_line * from->rs; - } else { - from_line[i] = (from_height - 1) * from->rs; - } - } else { - from_line[i] = 0; - } - } - - for (int i = 0 ; i < 4 ; i++) { - int k = (int)round(from_x) + i - 2; - if (k < 0) k = 0; - if (k >= from_width) k = from_width - 1; - k *= 4; - _check_index(from, from_line[0] + k, __LINE__); - _check_index(from, from_line[1] + k, __LINE__); - _check_index(from, from_line[2] + k, __LINE__); - _check_index(from, from_line[3] + k, __LINE__); - line[i].r = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k], - NR_PIXBLOCK_PX(from)[from_line[1] + k], - NR_PIXBLOCK_PX(from)[from_line[2] + k], - NR_PIXBLOCK_PX(from)[from_line[3] + k], - from_y); - line[i].g = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 1], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 1], - from_y); - line[i].b = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 2], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 2], - from_y); - line[i].a = sample(NR_PIXBLOCK_PX(from)[from_line[0] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[1] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[2] + k + 3], - NR_PIXBLOCK_PX(from)[from_line[3] + k + 3], - from_y); - } - RGBA result; - result.r = round(sample(line[0].r, line[1].r, line[2].r, line[3].r, - from_x)); - result.g = round(sample(line[0].g, line[1].g, line[2].g, line[3].g, - from_x)); - result.b = round(sample(line[0].b, line[1].b, line[2].b, line[3].b, - from_x)); - result.a = round(sample(line[0].a, line[1].a, line[2].a, line[3].a, - from_x)); - - using Inkscape::Filters::clamp; - using Inkscape::Filters::clamp_alpha; - _check_index(to, to_y * to->rs + to_x * 4, __LINE__); - if (to->mode == NR_PIXBLOCK_MODE_R8G8B8A8P) { - /* Make sure, none of the RGB channels exceeds 100% intensity - * in premultiplied output */ - int const alpha = clamp((int)result.a); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4] = - clamp_alpha((int)result.r, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 1] = - clamp_alpha((int)result.g, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 2] = - clamp_alpha((int)result.b, alpha); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 3] = alpha; - } else { - /* Clamp the output to unsigned char range */ - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4] - = clamp((int)result.r); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 1] - = clamp((int)result.g); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 2] - = clamp((int)result.b); - NR_PIXBLOCK_PX(to)[to_y * to->rs + to_x * 4 + 3] - = clamp((int)result.a); - } - } - } - if (free_from_on_exit) { - nr_pixblock_release(from); - delete from; - } -} - -} /* namespace NR */ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/pixblock-transform.h b/src/display/pixblock-transform.h deleted file mode 100644 index b73435fdf..000000000 --- a/src/display/pixblock-transform.h +++ /dev/null @@ -1,35 +0,0 @@ -#ifndef __NR_PIXBLOCK_TRANSFORM_H__ -#define __NR_PIXBLOCK_TRANSFORM_H__ - -/* - * Functions for blitting pixblocks using matrix transfomation - * - * Author: - * Niko Kiirala <niko@kiirala.com> - * - * Copyright (C) 2006 Niko Kiirala - * - * Released under GNU GPL, read the file 'COPYING' for more information - */ - -#include "libnr/nr-pixblock.h" -#include <2geom/forward.h> - -namespace NR { - -void transform_nearest(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans); -void transform_bicubic(NRPixBlock *to, NRPixBlock *from, Geom::Affine const &trans); - -} /* namespace NR */ - -#endif // __NR_PIXBLOCK_TRANSFORM_H__ -/* - Local Variables: - mode:c++ - c-file-style:"stroustrup" - c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) - indent-tabs-mode:nil - fill-column:99 - End: -*/ -// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 : diff --git a/src/display/sodipodi-ctrl.cpp b/src/display/sodipodi-ctrl.cpp index 202fc206e..5e939ffee 100644 --- a/src/display/sodipodi-ctrl.cpp +++ b/src/display/sodipodi-ctrl.cpp @@ -11,7 +11,7 @@ #include <2geom/transforms.h> #include "sp-canvas-util.h" #include "sodipodi-ctrl.h" -#include "libnr/nr-pixops.h" +#include "display/cairo-utils.h" enum { ARG_0, @@ -125,7 +125,7 @@ sp_ctrl_destroy (GtkObject *object) ctrl = SP_CTRL (object); if (ctrl->cache) { - g_free(ctrl->cache); + delete[] ctrl->cache; ctrl->cache = NULL; } @@ -175,11 +175,12 @@ sp_ctrl_set_arg (GtkObject *object, GtkArg *arg, guint arg_id) sp_canvas_item_request_update (item); break; - case ARG_FILL_COLOR: - ctrl->fill_color = GTK_VALUE_INT (*arg); + case ARG_FILL_COLOR: { + guint32 fill = GTK_VALUE_INT (*arg); + ctrl->fill_color = fill; ctrl->build = FALSE; sp_canvas_item_request_update (item); - break; + } break; case ARG_STROKED: ctrl->stroked = GTK_VALUE_BOOL (*arg); @@ -187,11 +188,12 @@ sp_ctrl_set_arg (GtkObject *object, GtkArg *arg, guint arg_id) sp_canvas_item_request_update (item); break; - case ARG_STROKE_COLOR: - ctrl->stroke_color = GTK_VALUE_INT (*arg); + case ARG_STROKE_COLOR: { + guint32 stroke = GTK_VALUE_INT (*arg); + ctrl->stroke_color = stroke; ctrl->build = FALSE; sp_canvas_item_request_update (item); - break; + } break; case ARG_PIXBUF: pixbuf = (GdkPixbuf*)(GTK_VALUE_POINTER (*arg)); @@ -297,52 +299,56 @@ sp_ctrl_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **actual_item) static void sp_ctrl_build_cache (SPCtrl *ctrl) { - guchar * p, *q; + guint32 *p, *q; gint size, x, y, z, s, a, side, c; - guint8 fr, fg, fb, fa, sr, sg, sb, sa; + guint32 stroke_color, fill_color; if (ctrl->filled) { - fr = (ctrl->fill_color >> 24) & 0xff; - fg = (ctrl->fill_color >> 16) & 0xff; - fb = (ctrl->fill_color >> 8) & 0xff; - fa = (ctrl->fill_color) & 0xff; + if (ctrl->mode == SP_CTRL_MODE_XOR) { + fill_color = ctrl->fill_color; + } else { + fill_color = argb32_from_rgba(ctrl->fill_color); + } } else { - fr = 0x00; fg = 0x00; fb = 0x00; fa = 0x00; + fill_color = 0; } if (ctrl->stroked) { - sr = (ctrl->stroke_color >> 24) & 0xff; - sg = (ctrl->stroke_color >> 16) & 0xff; - sb = (ctrl->stroke_color >> 8) & 0xff; - sa = (ctrl->stroke_color) & 0xff; + if (ctrl->mode == SP_CTRL_MODE_XOR) { + stroke_color = ctrl->stroke_color; + } else { + stroke_color = argb32_from_rgba(ctrl->stroke_color); + } } else { - sr = fr; sg = fg; sb = fb; sa = fa; + stroke_color = fill_color; } side = (ctrl->span * 2 +1); - c = ctrl->span ; - size = (side) * (side) * 4; + c = ctrl->span; + size = side * side; if (side < 2) return; - if (ctrl->cache) - g_free (ctrl->cache); - ctrl->cache = (guchar*)g_malloc (size); + if (ctrl->cache) delete[] ctrl->cache; + ctrl->cache = new guint32[size]; switch (ctrl->shape) { case SP_CTRL_SHAPE_SQUARE: p = ctrl->cache; + // top edge for (x=0; x < side; x++) { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; + *p++ = stroke_color; } + // middle for (y = 2; y < side; y++) { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; + *p++ = stroke_color; // stroke at first and last pixel for (x=2; x < side; x++) { - *p++ = fr; *p++ = fg; *p++ = fb; *p++ = fa; + *p++ = fill_color; // fill in the middle } - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; + *p++ = stroke_color; } + // bottom edge for (x=0; x < side; x++) { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; + *p++ = stroke_color; } ctrl->build = TRUE; break; @@ -352,19 +358,20 @@ sp_ctrl_build_cache (SPCtrl *ctrl) for (y = 0; y < side; y++) { z = abs (c - y); for (x = 0; x < z; x++) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; + *p++ = 0; } - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; x++; + *p++ = stroke_color; x++; for (; x < side - z -1; x++) { - *p++ = fr; *p++ = fg; *p++ = fb; *p++ = fa; + *p++ = fill_color; } if (z != c) { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; x++; + *p++ = stroke_color; x++; } for (; x < side; x++) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; + *p++ = 0; } } + ctrl->build = TRUE; break; case SP_CTRL_SHAPE_CIRCLE: @@ -376,28 +383,28 @@ sp_ctrl_build_cache (SPCtrl *ctrl) z = (gint)(0.0 + sqrt ((c+.4)*(c+.4) - a*a)); x = 0; while (x < c-z) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; - *q-- = 0x00; *q-- = 0x00; *q-- = 0x00; *q-- = 0x00; + *p++ = 0; + *q-- = 0; x++; } do { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; - *q-- = sa; *q-- = sb; *q-- = sg; *q-- = sr; + *p++ = stroke_color; + *q-- = stroke_color; x++; } while (x < c-s); while (x < MIN(c+s+1, c+z)) { - *p++ = fr; *p++ = fg; *p++ = fb; *p++ = fa; - *q-- = fa; *q-- = fb; *q-- = fg; *q-- = fr; + *p++ = fill_color; + *q-- = fill_color; x++; } do { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; - *q-- = sa; *q-- = sb; *q-- = sg; *q-- = sr; + *p++ = stroke_color; + *q-- = stroke_color; x++; } while (x <= c+z); while (x < side) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; - *q-- = 0x00; *q-- = 0x00; *q-- = 0x00; *q-- = 0x00; + *p++ = 0; + *q-- = 0; x++; } s = z; @@ -410,17 +417,17 @@ sp_ctrl_build_cache (SPCtrl *ctrl) for (y = 0; y < side; y++) { z = abs (c - y); for (x = 0; x < c-z; x++) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; + *p++ = 0; } - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; x++; + *p++ = stroke_color; x++; for (; x < c + z; x++) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; + *p++ = 0; } if (z != 0) { - *p++ = sr; *p++ = sg; *p++ = sb; *p++ = sa; x++; + *p++ = stroke_color; x++; } for (; x < side; x++) { - *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; *p++ = 0x00; + *p++ = 0; } } ctrl->build = TRUE; @@ -433,28 +440,19 @@ sp_ctrl_build_cache (SPCtrl *ctrl) px = gdk_pixbuf_get_pixels (ctrl->pixbuf); rs = gdk_pixbuf_get_rowstride (ctrl->pixbuf); for (y = 0; y < side; y++){ - unsigned char *s, *d; + guint32 *d; + unsigned char *s; s = px + y * rs; - d = ctrl->cache + 4 * side * y; + d = ctrl->cache + side * y; for (x = 0; x < side; x++) { if (s[3] < 0x80) { - d[0] = 0x00; - d[1] = 0x00; - d[2] = 0x00; - d[3] = 0x00; + *d++ = 0; } else if (s[0] < 0x80) { - d[0] = sr; - d[1] = sg; - d[2] = sb; - d[3] = sa; + *d++ = stroke_color; } else { - d[0] = fr; - d[1] = fg; - d[2] = fb; - d[3] = fa; + *d++ = fill_color; } s += 4; - d += 4; } } } else { @@ -466,16 +464,13 @@ sp_ctrl_build_cache (SPCtrl *ctrl) case SP_CTRL_SHAPE_IMAGE: if (ctrl->pixbuf) { guint r = gdk_pixbuf_get_rowstride (ctrl->pixbuf); - guchar * pix; - q = gdk_pixbuf_get_pixels (ctrl->pixbuf); + guint32 *px; + guchar *data = gdk_pixbuf_get_pixels (ctrl->pixbuf); p = ctrl->cache; for (y = 0; y < side; y++){ - pix = q + (y * r); + px = reinterpret_cast<guint32*>(data + y * r); for (x = 0; x < side; x++) { - *p++ = *pix++; - *p++ = *pix++; - *p++ = *pix++; - *p++ = *pix++; + *p++ = *px++; } } } else { @@ -487,65 +482,84 @@ sp_ctrl_build_cache (SPCtrl *ctrl) default: break; } - } -// composite background, foreground, alpha for xor mode -#define COMPOSE_X(b,f,a) ( FAST_DIVIDE<255>( ((guchar) b) * ((guchar) (0xff - a)) + ((guchar) ((b ^ ~f) + b/4 - (b>127? 63 : 0))) * ((guchar) a) ) ) -// composite background, foreground, alpha for color mode -#define COMPOSE_N(b,f,a) ( FAST_DIVIDE<255>( ((guchar) b) * ((guchar) (0xff - a)) + ((guchar) f) * ((guchar) a) ) ) +static inline guint32 compose_xor(guint32 bg, guint32 fg, guint32 a) +{ + guint32 c = bg * (255-a) + (((bg ^ ~fg) + (bg >> 2) - (bg > 127 ? 63 : 0)) & 255) * a; + return (c + 127) / 255; +} static void sp_ctrl_render (SPCanvasItem *item, SPCanvasBuf *buf) { - gint y0, y1, y, x0,x1,x; - guchar *p, *q, a; + //gint y0, y1, y, x0,x1,x; + //guchar *p, *q, a; SPCtrl *ctrl = SP_CTRL (item); if (!ctrl->defined) return; if ((!ctrl->filled) && (!ctrl->stroked)) return; - sp_canvas_prepare_buffer (buf); - // the control-image is rendered into ctrl->cache if (!ctrl->build) { sp_ctrl_build_cache (ctrl); } - // then we render from ctrl->cache - y0 = MAX (ctrl->box.y0, buf->rect.y0); - y1 = MIN (ctrl->box.y1, buf->rect.y1 - 1); - x0 = MAX (ctrl->box.x0, buf->rect.x0); - x1 = MIN (ctrl->box.x1, buf->rect.x1 - 1); - - bool colormode; - - for (y = y0; y <= y1; y++) { - p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride + (x0 - buf->rect.x0) * 4; - q = ctrl->cache + ((y - ctrl->box.y0) * (ctrl->span*2+1) + (x0 - ctrl->box.x0)) * 4; - for (x = x0; x <= x1; x++) { - a = *(q + 3); - // 00000000 is the only way to get invisible; all other colors with alpha 00 are treated as mode_color with alpha ff - colormode = false; - if (a == 0x00 && !(q[0] == 0x00 && q[1] == 0x00 && q[2] == 0x00)) { - a = 0xff; - colormode = true; - } - if (ctrl->mode == SP_CTRL_MODE_COLOR || colormode) { - p[0] = COMPOSE_N (p[0], q[0], a); - p[1] = COMPOSE_N (p[1], q[1], a); - p[2] = COMPOSE_N (p[2], q[2], a); - q += 4; - p += 4; - } else if (ctrl->mode == SP_CTRL_MODE_XOR) { - p[0] = COMPOSE_X (p[0], q[0], a); - p[1] = COMPOSE_X (p[1], q[1], a); - p[2] = COMPOSE_X (p[2], q[2], a); - q += 4; - p += 4; + int w, h; + w = h = (ctrl->span * 2 +1); + + // The code below works even when the target is not an image surface + if (ctrl->mode == SP_CTRL_MODE_XOR) { + // 1. Copy the affected part of output to a temporary surface + cairo_surface_t *work = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, w, h); + cairo_t *cr = cairo_create(work); + cairo_translate(cr, -ctrl->box.x0, -ctrl->box.y0); + cairo_set_source_surface(cr, cairo_get_target(buf->ct), buf->rect.x0, buf->rect.y0); + cairo_paint(cr); + cairo_destroy(cr); + + // 2. Composite the control on a temporary surface + cairo_surface_flush(work); + int strideb = cairo_image_surface_get_stride(work); + unsigned char *pxb = cairo_image_surface_get_data(work); + guint32 *p = ctrl->cache; + for (int i=0; i<h; ++i) { + guint32 *pb = reinterpret_cast<guint32*>(pxb + i*strideb); + for (int j=0; j<w; ++j) { + guint32 cc = *p++; + guint32 ac = cc & 0xff; + if (ac == 0 && cc != 0) { + *pb++ = argb32_from_rgba(cc | 0x000000ff); + } else { + EXTRACT_ARGB32(*pb, ab,rb,gb,bb) + guint32 ro = compose_xor(rb, (cc & 0xff000000) >> 24, ac); + guint32 go = compose_xor(gb, (cc & 0x00ff0000) >> 16, ac); + guint32 bo = compose_xor(bb, (cc & 0x0000ff00) >> 8, ac); + ASSEMBLE_ARGB32(px, ab,ro,go,bo) + *pb++ = px; + } } } + cairo_surface_mark_dirty(work); + + // 3. Replace the affected part of output with contents of temporary surface + cairo_save(buf->ct); + cairo_set_source_surface(buf->ct, work, + ctrl->box.x0 - buf->rect.x0, ctrl->box.y0 - buf->rect.y0); + cairo_rectangle(buf->ct, ctrl->box.x0 - buf->rect.x0, ctrl->box.y0 - buf->rect.y0, w, h); + cairo_clip(buf->ct); + cairo_set_operator(buf->ct, CAIRO_OPERATOR_SOURCE); + cairo_paint(buf->ct); + cairo_restore(buf->ct); + cairo_surface_destroy(work); + } else { + cairo_surface_t *cache = cairo_image_surface_create_for_data( + reinterpret_cast<unsigned char*>(ctrl->cache), CAIRO_FORMAT_ARGB32, w, h, w*4); + cairo_set_source_surface(buf->ct, cache, + ctrl->box.x0 - buf->rect.x0, ctrl->box.y0 - buf->rect.y0); + cairo_paint(buf->ct); + cairo_surface_destroy(cache); } ctrl->shown = TRUE; } diff --git a/src/display/sodipodi-ctrl.h b/src/display/sodipodi-ctrl.h index 71061b450..3bf0889c7 100644 --- a/src/display/sodipodi-ctrl.h +++ b/src/display/sodipodi-ctrl.h @@ -49,7 +49,7 @@ struct SPCtrl : public SPCanvasItem { bool _moved; NRRectL box; /* NB! x1 & y1 are included */ - guchar *cache; + guint32 *cache; GdkPixbuf * pixbuf; void moveto(Geom::Point const p); diff --git a/src/display/sodipodi-ctrlrect.cpp b/src/display/sodipodi-ctrlrect.cpp index 380039798..592d45bc0 100644 --- a/src/display/sodipodi-ctrlrect.cpp +++ b/src/display/sodipodi-ctrlrect.cpp @@ -17,7 +17,7 @@ #include "sp-canvas-util.h" #include "sodipodi-ctrlrect.h" -#include "libnr/nr-pixops.h" +#include "display/cairo-utils.h" /* * Currently we do not have point method, as it should always be painted @@ -83,7 +83,7 @@ static void sp_ctrlrect_destroy(GtkObject *object) (* GTK_OBJECT_CLASS(parent_class)->destroy)(object); } } - +#if 0 /* FIXME: use definitions from somewhere else */ #define RGBA_R(v) ((v) >> 24) #define RGBA_G(v) (((v) >> 16) & 0xff) @@ -153,6 +153,7 @@ static void sp_ctrlrect_area(SPCanvasBuf *buf, gint xs, gint ys, gint xe, gint y } } } +#endif static void sp_ctrlrect_render(SPCanvasItem *item, SPCanvasBuf *buf) { @@ -188,13 +189,38 @@ void CtrlRect::init() void CtrlRect::render(SPCanvasBuf *buf) { + static double const dashes[2] = {4.0, 4.0}; + if ((_area.x0 != 0 || _area.x1 != 0 || _area.y0 != 0 || _area.y1 != 0) && (_area.x0 < buf->rect.x1) && (_area.y0 < buf->rect.y1) && ((_area.x1 + _shadow_size) >= buf->rect.x0) && - ((_area.y1 + _shadow_size) >= buf->rect.y0)) { - sp_canvas_prepare_buffer(buf); + ((_area.y1 + _shadow_size) >= buf->rect.y0)) + { + cairo_save(buf->ct); + cairo_translate(buf->ct, -buf->rect.x0, -buf->rect.y0); + cairo_set_line_width(buf->ct, 1); + if (_dashed) cairo_set_dash(buf->ct, dashes, 2, 0); + cairo_rectangle(buf->ct, 0.5 + _area.x0, 0.5 + _area.y0, + _area.x1 - _area.x0, _area.y1 - _area.y0); + if (_has_fill) { + ink_cairo_set_source_rgba32(buf->ct, _fill_color); + cairo_fill_preserve(buf->ct); + } + ink_cairo_set_source_rgba32(buf->ct, _border_color); + cairo_stroke(buf->ct); + + if (_shadow_size > 0) { + ink_cairo_set_source_rgba32(buf->ct, _shadow_color); + cairo_rectangle(buf->ct, 1 + _area.x1, _area.y0 + _shadow_size, + _shadow_size, _area.y1 - _area.y0 + 1); // right shadow + cairo_rectangle(buf->ct, _area.x0 + _shadow_size, 1 + _area.y1, + _area.x1 - _area.x0 - _shadow_size + 1, _shadow_size); + cairo_fill(buf->ct); + } + cairo_restore(buf->ct); +#if 0 /* Top */ sp_ctrlrect_hline(buf, _area.y0, _area.x0, _area.x1, _border_color, _dashed); /* Bottom */ @@ -216,6 +242,7 @@ void CtrlRect::render(SPCanvasBuf *buf) sp_ctrlrect_area(buf, _area.x0 + 1, _area.y0 + 1, _area.x1 - 1, _area.y1 - 1, _fill_color); } +#endif } } diff --git a/src/display/sp-canvas-util.cpp b/src/display/sp-canvas-util.cpp index 7eac32e2d..186609e49 100644 --- a/src/display/sp-canvas-util.cpp +++ b/src/display/sp-canvas-util.cpp @@ -13,12 +13,10 @@ */ -#include <string.h> // for memset #include <2geom/affine.h> -#include "libnr/nr-pixops.h" -#include "sp-canvas-item.h" #include "sp-canvas-util.h" - +#include "sp-canvas-item.h" +#include "sp-canvas.h" void sp_canvas_update_bbox (SPCanvasItem *item, int x1, int y1, int x2, int y2) @@ -43,38 +41,13 @@ sp_canvas_item_reset_bounds (SPCanvasItem *item) void sp_canvas_prepare_buffer (SPCanvasBuf *buf) { - if (buf->is_empty) { - sp_canvas_clear_buffer(buf); - buf->is_empty = false; - } -} - -void -sp_canvas_clear_buffer (SPCanvasBuf *buf) -{ - unsigned char r, g, b; - - r = (buf->bg_color >> 16) & 0xff; - g = (buf->bg_color >> 8) & 0xff; - b = buf->bg_color & 0xff; - - if ((r != g) || (r != b)) { - int x, y; - for (y = buf->rect.y0; y < buf->rect.y1; y++) { - unsigned char *p; - p = buf->buf + (y - buf->rect.y0) * buf->buf_rowstride; - for (x = buf->rect.x0; x < buf->rect.x1; x++) { - *p++ = r; - *p++ = g; - *p++ = b; - } - } - } else { + /*if (buf->is_empty) { int y; for (y = buf->rect.y0; y < buf->rect.y1; y++) { - memset (buf->buf + (y - buf->rect.y0) * buf->buf_rowstride, r, 4 * (buf->rect.x1 - buf->rect.x0)); + memset (buf->buf + (y - buf->rect.y0) * buf->buf_rowstride, 0, 4 * (buf->rect.x1 - buf->rect.x0)); } - } + buf->is_empty = false; + }*/ } Geom::Affine sp_canvas_item_i2p_affine (SPCanvasItem * item) diff --git a/src/display/sp-canvas-util.h b/src/display/sp-canvas-util.h index f0aa15cb9..41e085a5c 100644 --- a/src/display/sp-canvas-util.h +++ b/src/display/sp-canvas-util.h @@ -21,11 +21,6 @@ void sp_canvas_update_bbox (SPCanvasItem *item, int x1, int y1, int x2, int y2); void sp_canvas_item_reset_bounds (SPCanvasItem *item); void sp_canvas_prepare_buffer (SPCanvasBuf *buf); -/* fill buffer with background color */ - -void -sp_canvas_clear_buffer (SPCanvasBuf * buf); - /* get i2p (item to parent) affine transformation as general 6-element array */ Geom::Affine sp_canvas_item_i2p_affine (SPCanvasItem * item); diff --git a/src/display/sp-canvas.cpp b/src/display/sp-canvas.cpp index e2220282d..c84452c07 100644 --- a/src/display/sp-canvas.cpp +++ b/src/display/sp-canvas.cpp @@ -15,21 +15,18 @@ */ #ifdef HAVE_CONFIG_H -# include "config.h" +# include <config.h> #endif -#include <libnr/nr-pixblock.h> - #include <gtk/gtk.h> - #include <gtkmm.h> #include "helper/sp-marshal.h" #include <helper/recthull.h> +#include "display-forward.h" +#include <2geom/affine.h> #include "display/sp-canvas.h" #include "display/sp-canvas-group.h" -#include <2geom/affine.h> -#include "libnr/nr-convex-hull.h" #include "preferences.h" #include "inkscape.h" #include "sodipodi-ctrlrect.h" @@ -37,8 +34,7 @@ #include "color-profile-fns.h" #endif // ENABLE_LCMS #include "display/rendermode.h" -#include "libnr/nr-blit.h" -#include "display/inkscape-cairo.h" +#include "display/cairo-utils.h" #include "debug/gdk-event-latency-tracker.h" #include "desktop.h" #include "sp-namedview.h" @@ -315,7 +311,7 @@ sp_canvas_item_invoke_point (SPCanvasItem *item, Geom::Point p, SPCanvasItem **a if (SP_CANVAS_ITEM_GET_CLASS (item)->point) return SP_CANVAS_ITEM_GET_CLASS (item)->point (item, p, actual_item); - return NR_HUGE; + return Geom::infinity(); } /** @@ -1629,17 +1625,12 @@ sp_canvas_paint_single_buffer (SPCanvas *canvas, int x0, int y0, int x1, int y1, { GtkWidget *widget = GTK_WIDGET (canvas); - SPCanvasBuf buf; - if (canvas->rendermode != Inkscape::RENDERMODE_OUTLINE) { - buf.buf = nr_pixelstore_256K_new (FALSE, 0); - } else { - buf.buf = nr_pixelstore_1M_new (FALSE, 0); - } - // Mark the region clean sp_canvas_mark_rect(canvas, x0, y0, x1, y1, 0); - buf.buf_rowstride = sw * 4; + SPCanvasBuf buf; + buf.buf = NULL; + buf.buf_rowstride = 0; buf.rect.x0 = x0; buf.rect.y0 = y0; buf.rect.x1 = x1; @@ -1648,114 +1639,75 @@ sp_canvas_paint_single_buffer (SPCanvas *canvas, int x0, int y0, int x1, int y1, buf.visible_rect.y0 = draw_y1; buf.visible_rect.x1 = draw_x2; buf.visible_rect.y1 = draw_y2; - GdkColor *color = &widget->style->bg[GTK_STATE_NORMAL]; - buf.bg_color = (((color->red & 0xff00) << 8) - | (color->green & 0xff00) - | (color->blue >> 8)); buf.is_empty = true; - - buf.ct = nr_create_cairo_context_canvasbuf (&(buf.visible_rect), &buf); + //buf.ct = gdk_cairo_create(widget->window); + + // create temporary surface + int w = x1 - x0; + int h = y1 - y0; + cairo_surface_t *imgs = cairo_image_surface_create(CAIRO_FORMAT_ARGB32, x1 - x0, y1 - y0); + buf.ct = cairo_create(imgs); + //cairo_translate(buf.ct, -x0, -y0); + + // fix coordinates, clip all drawing to the tile and clear the background + //cairo_translate(buf.ct, x0 - canvas->x0, y0 - canvas->y0); + //cairo_rectangle(buf.ct, 0, 0, x1 - x0, y1 - y0); + //cairo_set_line_width(buf.ct, 3); + //cairo_set_source_rgba(buf.ct, 1.0, 0.0, 0.0, 0.1); + //cairo_stroke_preserve(buf.ct); + //cairo_clip(buf.ct); + + gdk_cairo_set_source_color(buf.ct, &widget->style->bg[GTK_STATE_NORMAL]); + cairo_set_operator(buf.ct, CAIRO_OPERATOR_SOURCE); + //cairo_rectangle(buf.ct, 0, 0, x1 - x0, y1 - y0); + cairo_paint(buf.ct); + cairo_set_operator(buf.ct, CAIRO_OPERATOR_OVER); if (canvas->root->flags & SP_CANVAS_ITEM_VISIBLE) { SP_CANVAS_ITEM_GET_CLASS (canvas->root)->render (canvas->root, &buf); } -#if ENABLE_LCMS - cmsHTRANSFORM transf = 0; - Inkscape::Preferences *prefs = Inkscape::Preferences::get(); - bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display"); - if ( fromDisplay ) { - transf = Inkscape::colorprofile_get_display_per( canvas->cms_key ? *(canvas->cms_key) : "" ); - } else { - transf = Inkscape::colorprofile_get_display_transform(); - } -#endif // ENABLE_LCMS + // output to X + cairo_destroy(buf.ct); - if (buf.is_empty) { #if ENABLE_LCMS - if ( transf && canvas->enable_cms_display_adj ) { - cmsDoTransform( transf, &buf.bg_color, &buf.bg_color, 1 ); + if (canvas->enable_cms_display_adj) { + cmsHTRANSFORM transf = 0; + Inkscape::Preferences *prefs = Inkscape::Preferences::get(); + bool fromDisplay = prefs->getBool( "/options/displayprofile/from_display"); + if ( fromDisplay ) { + transf = Inkscape::colorprofile_get_display_per( canvas->cms_key ? *(canvas->cms_key) : "" ); + } else { + transf = Inkscape::colorprofile_get_display_transform(); } -#endif // ENABLE_LCMS - gdk_rgb_gc_set_foreground (canvas->pixmap_gc, buf.bg_color); - gdk_draw_rectangle (SP_CANVAS_WINDOW (canvas), - canvas->pixmap_gc, - TRUE, - x0 - canvas->x0, y0 - canvas->y0, - x1 - x0, y1 - y0); - } else { - -#if ENABLE_LCMS - if ( transf && canvas->enable_cms_display_adj ) { - for ( gint yy = 0; yy < (y1 - y0); yy++ ) { - guchar* p = buf.buf + (buf.buf_rowstride * yy); - cmsDoTransform( transf, p, p, (x1 - x0) ); + + if (transf) { + cairo_surface_flush(imgs); + unsigned char *px = cairo_image_surface_get_data(imgs); + int stride = cairo_image_surface_get_stride(imgs); + for (int i=0; i<h; ++i) { + unsigned char *row = px + i*stride; + cmsDoTransform(transf, row, row, w); } + cairo_surface_mark_dirty(imgs); } -#endif // ENABLE_LCMS - -// Now we only need to output the prepared pixmap to the actual screen, and this define chooses one -// of the two ways to do it. The cairo way is direct and straightforward, but unfortunately -// noticeably slower. I asked Carl Worth but he was unable so far to suggest any specific reason -// for this slowness. So, for now we use the oldish method: squeeze out 32bpp buffer to 24bpp and -// use gdk_draw_rgb_image_dithalign, for unfortunately gdk can only handle 24 bpp, which cairo -// cannot handle at all. Still, this way is currently faster even despite the blit with squeeze. - -///#define CANVAS_OUTPUT_VIA_CAIRO - -#ifdef CANVAS_OUTPUT_VIA_CAIRO - - buf.cst = cairo_image_surface_create_for_data ( - buf.buf, - CAIRO_FORMAT_ARGB32, // unpacked, i.e. 32 bits! one byte is unused - x1 - x0, y1 - y0, - buf.buf_rowstride - ); - cairo_t *window_ct = gdk_cairo_create(SP_CANVAS_WINDOW (canvas)); - cairo_set_source_surface (window_ct, buf.cst, x0 - canvas->x0, y0 - canvas->y0); - cairo_paint (window_ct); - cairo_destroy (window_ct); - cairo_surface_finish (buf.cst); - cairo_surface_destroy (buf.cst); - -#else - - NRPixBlock b3; - nr_pixblock_setup_fast (&b3, NR_PIXBLOCK_MODE_R8G8B8, x0, y0, x1, y1, TRUE); - - NRPixBlock b4; - nr_pixblock_setup_extern (&b4, NR_PIXBLOCK_MODE_R8G8B8A8P, x0, y0, x1, y1, - buf.buf, - buf.buf_rowstride, - FALSE, FALSE); - - // this does the 32->24 squishing, using an assembler routine: - nr_blit_pixblock_pixblock (&b3, &b4); - - gdk_draw_rgb_image_dithalign (SP_CANVAS_WINDOW (canvas), - canvas->pixmap_gc, - x0 - canvas->x0, y0 - canvas->y0, - x1 - x0, y1 - y0, - GDK_RGB_DITHER_MAX, - NR_PIXBLOCK_PX(&b3), - sw * 3, - x0 - canvas->x0, y0 - canvas->y0); - - nr_pixblock_release (&b3); - nr_pixblock_release (&b4); -#endif } +#endif // ENABLE_LCMS - cairo_surface_t *cst = cairo_get_target(buf.ct); - cairo_destroy (buf.ct); - cairo_surface_finish (cst); - cairo_surface_destroy (cst); + cairo_t *xct = gdk_cairo_create(widget->window); + cairo_translate(xct, x0 - canvas->x0, y0 - canvas->y0); + cairo_rectangle(xct, 0, 0, x1-x0, y1-y0); + cairo_clip(xct); + cairo_set_source_surface(xct, imgs, 0, 0); + cairo_set_operator(xct, CAIRO_OPERATOR_SOURCE); + cairo_paint(xct); + cairo_destroy(xct); + cairo_surface_destroy(imgs); - if (canvas->rendermode != Inkscape::RENDERMODE_OUTLINE) { - nr_pixelstore_256K_free (buf.buf); - } else { - nr_pixelstore_1M_free (buf.buf); - } + //cairo_surface_t *cst = cairo_get_target(buf.ct); + //cairo_destroy (buf.ct); + //cairo_surface_finish (cst); + //cairo_surface_destroy (cst); } struct PaintRectSetup { @@ -1815,11 +1767,21 @@ sp_canvas_paint_rect_internal (PaintRectSetup const *setup, NRRectL this_rect) if (bw * bh < setup->max_pixels) { // We are small enough + /*GdkRectangle r; + r.x = this_rect.x0 - setup->canvas->x0; + r.y = this_rect.y0 - setup->canvas->y0; + r.width = this_rect.x1 - this_rect.x0; + r.height = this_rect.y1 - this_rect.y0; + + GdkWindow *window = GTK_WIDGET(setup->canvas)->window; + gdk_window_begin_paint_rect(window, &r);*/ + sp_canvas_paint_single_buffer (setup->canvas, this_rect.x0, this_rect.y0, this_rect.x1, this_rect.y1, setup->big_rect.x0, setup->big_rect.y0, setup->big_rect.x1, setup->big_rect.y1, bw); + //gdk_window_end_paint(window); return 1; } diff --git a/src/display/sp-canvas.h b/src/display/sp-canvas.h index e151911dc..7a6b3295e 100644 --- a/src/display/sp-canvas.h +++ b/src/display/sp-canvas.h @@ -56,18 +56,16 @@ enum { }; /** - * The canvas buf contains the actual pixels. + * Structure used when rendering canvas items. */ -struct SPCanvasBuf{ - guchar *buf; - int buf_rowstride; +struct SPCanvasBuf { + cairo_t *ct; NRRectL rect; NRRectL visible_rect; - /// Background color, given as 0xrrggbb - guint32 bg_color; - // If empty, ignore contents of buffer and use a solid area of bg_color + + unsigned char *buf; + int buf_rowstride; bool is_empty; - cairo_t *ct; }; G_END_DECLS diff --git a/src/display/sp-ctrlline.cpp b/src/display/sp-ctrlline.cpp index ef71c0a16..6c763abdf 100644 --- a/src/display/sp-ctrlline.cpp +++ b/src/display/sp-ctrlline.cpp @@ -19,14 +19,15 @@ * */ -#include "sp-canvas-util.h" -#include "sp-ctrlline.h" - #ifdef HAVE_CONFIG_H # include "config.h" #endif -#include <color.h> -#include "display/inkscape-cairo.h" + +#include "display/sp-ctrlline.h" +#include "display/display-forward.h" +#include "display/sp-canvas-util.h" +#include "display/cairo-utils.h" +#include "color.h" static void sp_ctrlline_class_init (SPCtrlLineClass *klass); @@ -105,11 +106,7 @@ sp_ctrlline_render (SPCanvasItem *item, SPCanvasBuf *buf) if (cl->s == cl->e) return; - sp_canvas_prepare_buffer (buf); - - guint32 rgba = cl->rgba; - cairo_set_source_rgba(buf->ct, SP_RGBA32_B_F(rgba), SP_RGBA32_G_F(rgba), SP_RGBA32_R_F(rgba), SP_RGBA32_A_F(rgba)); - + ink_cairo_set_source_rgba32(buf->ct, cl->rgba); cairo_set_line_width(buf->ct, 1); cairo_new_path(buf->ct); diff --git a/src/display/sp-ctrlpoint.cpp b/src/display/sp-ctrlpoint.cpp index 9f2ecb937..c33cdeeb9 100644 --- a/src/display/sp-ctrlpoint.cpp +++ b/src/display/sp-ctrlpoint.cpp @@ -18,7 +18,7 @@ # include "config.h" #endif #include <color.h> -#include "display/inkscape-cairo.h" +#include "display/cairo-utils.h" static void sp_ctrlpoint_class_init (SPCtrlPointClass *klass); diff --git a/src/display/sp-ctrlquadr.cpp b/src/display/sp-ctrlquadr.cpp index 1ed8d62b8..0701d0b10 100644 --- a/src/display/sp-ctrlquadr.cpp +++ b/src/display/sp-ctrlquadr.cpp @@ -12,10 +12,13 @@ #ifdef HAVE_CONFIG_H # include "config.h" #endif -#include "sp-canvas-util.h" + +#include "display-forward.h" #include "sp-canvas-item.h" +#include "sp-canvas.h" +#include "sp-canvas-util.h" #include "sp-ctrlquadr.h" -#include "display/inkscape-cairo.h" +#include "display/cairo-utils.h" #include "color.h" struct SPCtrlQuadr : public SPCanvasItem{ diff --git a/src/display/testnr.cpp b/src/display/testnr.cpp deleted file mode 100644 index 3a3478d28..000000000 --- a/src/display/testnr.cpp +++ /dev/null @@ -1,24 +0,0 @@ -#include <gtk/gtk.h> -#include "sp-arena.h" - -int -main (int argc, char ** argv) -{ - GtkWidget * w, * c; - - gtk_init (&argc, &argv); - - w = gtk_window_new (GTK_WINDOW_TOPLEVEL); - - c = sp_arena_new (); - gtk_widget_show (c); - - gtk_container_add (GTK_CONTAINER (w), c); - - gtk_widget_show (w); - - gtk_main (); - - return 0; -} - |
