rsvg-filter.c 161 KB
Newer Older
1 2
/* -*- Mode: C; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/* vim: set sw=4 sts=4 expandtab: */
3
/*
4
   rsvg-filter.c: Provides filters
5

6
   Copyright (C) 2004 Caleb Moore
7

8 9 10 11
   This program is free software; you can redistribute it and/or
   modify it under the terms of the GNU Library General Public License as
   published by the Free Software Foundation; either version 2 of the
   License, or (at your option) any later version.
12

13 14 15 16
   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Library General Public License for more details.
17

18 19 20 21
   You should have received a copy of the GNU Library General Public
   License along with this program; if not, write to the
   Free Software Foundation, Inc., 59 Temple Place - Suite 330,
   Boston, MA 02111-1307, USA.
22

23
   Author: Caleb Moore <c.moore@student.unsw.edu.au>
24 25
*/

Dom Lachowicz's avatar
Dom Lachowicz committed
26 27
#include "config.h"

28 29 30 31
#include "rsvg-private.h"
#include "rsvg-filter.h"
#include "rsvg-styles.h"
#include "rsvg-css.h"
32
#include "rsvg-cairo-render.h"
33

Dom Lachowicz's avatar
Dom Lachowicz committed
34
#include <string.h>
35 36

#include <math.h>
Dom Lachowicz's avatar
Dom Lachowicz committed
37

38 39 40 41

/*************************************************************/
/*************************************************************/

Caleb Michael Moore's avatar
Caleb Michael Moore committed
42 43
typedef struct _RsvgFilterPrimitiveOutput RsvgFilterPrimitiveOutput;

44
struct _RsvgFilterPrimitiveOutput {
45
    cairo_surface_t *surface;
46
    RsvgIRect bounds;
Caleb Michael Moore's avatar
Caleb Michael Moore committed
47 48
};

49 50
typedef struct _RsvgFilterContext RsvgFilterContext;

51 52 53 54
struct _RsvgFilterContext {
    gint width, height;
    RsvgFilter *filter;
    GHashTable *results;
55 56
    cairo_surface_t *source_surface;
    cairo_surface_t *bg_surface;
57
    RsvgFilterPrimitiveOutput lastresult;
Christian Persch's avatar
Christian Persch committed
58 59
    cairo_matrix_t affine;
    cairo_matrix_t paffine;
60 61
    int channelmap[4];
    RsvgDrawingCtx *ctx;
62 63 64 65
};

typedef struct _RsvgFilterPrimitive RsvgFilterPrimitive;

66 67
/* We don't have real subclassing here.  If you derive something from
 * RsvgFilterPrimitive, and don't need any special code to free your
68 69
 * RsvgFilterPrimitiveFoo structure, you can just pass rsvg_filter_primitive_free
 * to rsvg_rust_cnode_new() for the destructor.  Otherwise, create a custom destructor like this:
70 71
 *
 *    static void
72
 *    rsvg_filter_primitive_foo_free (gpointer impl)
73
 *    {
74
 *        RsvgFilterPrimitiveFoo *foo = impl;
75 76 77 78 79
 *
 *        g_free (foo->my_custom_stuff);
 *        g_free (foo->more_custom_stuff);
 *        ... etc ...
 *
80
 *        rsvg_filter_primitive_free (impl);
81 82 83
 *    }
 *
 * That last call to rsvg_filter_primitive_free() will free the base RsvgFilterPrimitive's own fields,
84
 * and your whole structure itself, via g_free().
85
 */
86 87
struct _RsvgFilterPrimitive {
    RsvgLength x, y, width, height;
88 89 90 91
    gboolean x_specified;
    gboolean y_specified;
    gboolean width_specified;
    gboolean height_specified;
92 93 94
    GString *in;
    GString *result;

95
    void (*render) (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx);
96 97 98 99 100
};

/*************************************************************/
/*************************************************************/

101
static void
102
rsvg_filter_primitive_free (gpointer impl)
103
{
104
    RsvgFilterPrimitive *primitive = impl;
105 106 107 108

    g_string_free (primitive->in, TRUE);
    g_string_free (primitive->result, TRUE);

109
    g_free (primitive);
110 111
}

112 113 114 115 116 117
static void
filter_primitive_set_x_y_width_height_atts (RsvgFilterPrimitive *prim, RsvgPropertyBag *atts)
{
    const char *value;

    if ((value = rsvg_property_bag_lookup (atts, "x"))) {
118
        prim->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL);
119 120 121
        prim->x_specified = TRUE;
    }
    if ((value = rsvg_property_bag_lookup (atts, "y"))) {
122
        prim->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL);
123 124 125
        prim->y_specified = TRUE;
    }
    if ((value = rsvg_property_bag_lookup (atts, "width"))) {
126
        prim->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL);
127 128 129
        prim->width_specified = TRUE;
    }
    if ((value = rsvg_property_bag_lookup (atts, "height"))) {
130
        prim->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL);
131 132 133 134
        prim->height_specified = TRUE;
    }
}

135
static void
136
rsvg_filter_primitive_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx)
137
{
138
    primitive->render (node, primitive, ctx);
139 140
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
141
static RsvgIRect
142 143 144
rsvg_filter_primitive_get_bounds (RsvgFilterPrimitive * self, RsvgFilterContext * ctx)
{
    RsvgBbox box, otherbox;
Christian Persch's avatar
Christian Persch committed
145
    cairo_matrix_t affine;
146

Christian Persch's avatar
Christian Persch committed
147 148 149
    cairo_matrix_init_identity (&affine);
    rsvg_bbox_init (&box, &affine);
    rsvg_bbox_init (&otherbox, &ctx->affine);
150 151
    otherbox.virgin = 0;
    if (ctx->filter->filterunits == objectBoundingBox)
152
        rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.);
153 154 155 156
    otherbox.rect.x = rsvg_length_normalize (&ctx->filter->x, ctx->ctx);
    otherbox.rect.y = rsvg_length_normalize (&ctx->filter->y, ctx->ctx);
    otherbox.rect.width = rsvg_length_normalize (&ctx->filter->width, ctx->ctx);
    otherbox.rect.height = rsvg_length_normalize (&ctx->filter->height, ctx->ctx);
157
    if (ctx->filter->filterunits == objectBoundingBox)
158
        rsvg_drawing_ctx_pop_view_box (ctx->ctx);
159 160 161

    rsvg_bbox_insert (&box, &otherbox);

162 163
    if (self != NULL) {
        if (self->x_specified || self->y_specified || self->width_specified || self->height_specified) {
Christian Persch's avatar
Christian Persch committed
164
            rsvg_bbox_init (&otherbox, &ctx->paffine);
165 166
            otherbox.virgin = 0;
            if (ctx->filter->primitiveunits == objectBoundingBox)
167
                rsvg_drawing_ctx_push_view_box (ctx->ctx, 1., 1.);
168
            if (self->x_specified)
169
                otherbox.rect.x = rsvg_length_normalize (&self->x, ctx->ctx);
170
            else
Christian Persch's avatar
Christian Persch committed
171
                otherbox.rect.x = 0;
172
            if (self->y_specified)
173
                otherbox.rect.y = rsvg_length_normalize (&self->y, ctx->ctx);
174
            else
Christian Persch's avatar
Christian Persch committed
175
                otherbox.rect.y = 0;
176 177 178 179 180 181 182

            if (self->width_specified || self->height_specified) {
                double curr_vbox_w, curr_vbox_h;

                rsvg_drawing_ctx_get_view_box_size (ctx->ctx, &curr_vbox_w, &curr_vbox_h);

                if (self->width_specified)
183
                    otherbox.rect.width = rsvg_length_normalize (&self->width, ctx->ctx);
184 185 186 187
                else
                    otherbox.rect.width = curr_vbox_w;

                if (self->height_specified)
188
                    otherbox.rect.height = rsvg_length_normalize (&self->height, ctx->ctx);
189 190 191 192
                else
                    otherbox.rect.height = curr_vbox_h;
            }

193
            if (ctx->filter->primitiveunits == objectBoundingBox)
194
                rsvg_drawing_ctx_pop_view_box (ctx->ctx);
195 196
            rsvg_bbox_clip (&box, &otherbox);
        }
197
    }
198

Christian Persch's avatar
Christian Persch committed
199
    rsvg_bbox_init (&otherbox, &affine);
200
    otherbox.virgin = 0;
Christian Persch's avatar
Christian Persch committed
201 202 203 204
    otherbox.rect.x = 0;
    otherbox.rect.y = 0;
    otherbox.rect.width = ctx->width;
    otherbox.rect.height = ctx->height;
205 206
    rsvg_bbox_clip (&box, &otherbox);
    {
Christian Persch's avatar
Christian Persch committed
207 208 209
        RsvgIRect output = { box.rect.x, box.rect.y,
            box.rect.x + box.rect.width,
            box.rect.y + box.rect.height
210 211 212
        };
        return output;
    }
213 214
}

215 216
static cairo_surface_t *
_rsvg_image_surface_new (int width, int height)
217
{
218
    cairo_surface_t *surface;
219

220 221
    surface = cairo_image_surface_create (CAIRO_FORMAT_ARGB32, width, height);
    if (cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
222 223
        cairo_surface_destroy (surface);
        return NULL;
224
    }
225

226
    return surface;
227 228 229
}

static guchar
230
get_interp_pixel (guchar * src, gdouble ox, gdouble oy, guchar ch, RsvgIRect boundarys,
231
                  guint rowstride)
232 233 234 235
{
    double xmod, ymod;
    double dist1, dist2, dist3, dist4;
    double c, c1, c2, c3, c4;
236
    double fox, foy, cox, coy;
237 238 239 240 241 242 243 244 245

    xmod = fmod (ox, 1.0);
    ymod = fmod (oy, 1.0);

    dist1 = (1 - xmod) * (1 - ymod);
    dist2 = (xmod) * (1 - ymod);
    dist3 = (xmod) * (ymod);
    dist4 = (1 - xmod) * (ymod);

246 247 248 249 250 251 252
    fox = floor (ox);
    foy = floor (oy);
    cox = ceil (ox);
    coy = ceil (oy);

    if (fox <= boundarys.x0 || fox >= boundarys.x1 ||
        foy <= boundarys.y0 || foy >= boundarys.y1)
253 254
        c1 = 0;
    else
255
        c1 = src[(guint) foy * rowstride + (guint) fox * 4 + ch];
256

257 258
    if (cox <= boundarys.x0 || cox >= boundarys.x1 ||
        foy <= boundarys.y0 || foy >= boundarys.y1)
259 260
        c2 = 0;
    else
261
        c2 = src[(guint) foy * rowstride + (guint) cox * 4 + ch];
262

263 264
    if (cox <= boundarys.x0 || cox >= boundarys.x1 ||
        coy <= boundarys.y0 || coy >= boundarys.y1)
265 266
        c3 = 0;
    else
267
        c3 = src[(guint) coy * rowstride + (guint) cox * 4 + ch];
268

269 270
    if (fox <= boundarys.x0 || fox >= boundarys.x1 ||
        coy <= boundarys.y0 || coy >= boundarys.y1)
271 272
        c4 = 0;
    else
273
        c4 = src[(guint) coy * rowstride + (guint) fox * 4 + ch];
274 275 276 277

    c = (c1 * dist1 + c2 * dist2 + c3 * dist3 + c4 * dist4) / (dist1 + dist2 + dist3 + dist4);

    return (guchar) c;
278 279 280
}

static void
281
rsvg_filter_fix_coordinate_system (RsvgFilterContext * ctx, RsvgState * state, RsvgBbox *bbox)
282 283 284
{
    int x, y, height, width;

285 286 287 288
    x = bbox->rect.x;
    y = bbox->rect.y;
    width = bbox->rect.width;
    height = bbox->rect.height;
289

290 291
    ctx->width = cairo_image_surface_get_width (ctx->source_surface);
    ctx->height = cairo_image_surface_get_height (ctx->source_surface);
292

Christian Persch's avatar
Christian Persch committed
293
    ctx->affine = state->affine;
294
    if (ctx->filter->filterunits == objectBoundingBox) {
Christian Persch's avatar
Christian Persch committed
295 296 297
        cairo_matrix_t affine;
        cairo_matrix_init (&affine, width, 0, 0, height, x, y);
        cairo_matrix_multiply (&ctx->affine, &affine, &ctx->affine);
298
    }
Christian Persch's avatar
Christian Persch committed
299
    ctx->paffine = state->affine;
300
    if (ctx->filter->primitiveunits == objectBoundingBox) {
Christian Persch's avatar
Christian Persch committed
301 302 303
        cairo_matrix_t affine;
        cairo_matrix_init (&affine, width, 0, 0, height, x, y);
        cairo_matrix_multiply (&ctx->paffine, &affine, &ctx->paffine);
304
    }
305 306
}

307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332
static gboolean
rectangle_intersect (gint ax, gint ay, gint awidth, gint aheight,
                     gint bx, gint by, gint bwidth, gint bheight,
                     gint *rx, gint *ry, gint *rwidth, gint *rheight)
{
    gint rx1, ry1, rx2, ry2;

    rx1 = MAX (ax, bx);
    ry1 = MAX (ay, by);
    rx2 = MIN (ax + awidth, bx + bwidth);
    ry2 = MIN (ay + aheight, by + bheight);

    if (rx2 > rx1 && ry2 > ry1) {
        *rx = rx1;
        *ry = ry1;
        *rwidth = rx2 - rx1;
        *rheight = ry2 - ry1;

        return TRUE;
    } else {
        *rx = *ry = *rwidth = *rheight = 0;

        return FALSE;
    }
}

333
static void
334 335 336 337 338 339 340 341
rsvg_alpha_blt (cairo_surface_t *src,
                gint srcx,
                gint srcy,
                gint srcwidth,
                gint srcheight,
                cairo_surface_t *dst,
                gint dstx,
                gint dsty)
342
{
343 344 345 346
    gint src_surf_width, src_surf_height;
    gint dst_surf_width, dst_surf_height;
    gint src_clipped_x, src_clipped_y, src_clipped_width, src_clipped_height;
    gint dst_clipped_x, dst_clipped_y, dst_clipped_width, dst_clipped_height;
347 348 349
    gint x, y, srcrowstride, dstrowstride, sx, sy, dx, dy;
    guchar *src_pixels, *dst_pixels;

350 351
    g_assert (cairo_image_surface_get_format (src) == CAIRO_FORMAT_ARGB32);
    g_assert (cairo_image_surface_get_format (dst) == CAIRO_FORMAT_ARGB32);
352

353
    cairo_surface_flush (src);
354

355 356
    src_surf_width  = cairo_image_surface_get_width (src);
    src_surf_height = cairo_image_surface_get_height (src);
357

358 359
    dst_surf_width  = cairo_image_surface_get_width (dst);
    dst_surf_height = cairo_image_surface_get_height (dst);
360

361 362 363 364
    if (!rectangle_intersect (0, 0, src_surf_width, src_surf_height,
                              srcx, srcy, srcwidth, srcheight,
                              &src_clipped_x, &src_clipped_y, &src_clipped_width, &src_clipped_height))
        return; /* source rectangle is not in source surface */
365

366 367 368 369
    if (!rectangle_intersect (0, 0, dst_surf_width, dst_surf_height,
                              dstx, dsty, src_clipped_width, src_clipped_height,
                              &dst_clipped_x, &dst_clipped_y, &dst_clipped_width, &dst_clipped_height))
        return; /* dest rectangle is not in dest surface */
370

371 372
    srcrowstride = cairo_image_surface_get_stride (src);
    dstrowstride = cairo_image_surface_get_stride (dst);
373

374 375
    src_pixels = cairo_image_surface_get_data (src);
    dst_pixels = cairo_image_surface_get_data (dst);
376

377 378
    for (y = 0; y < dst_clipped_height; y++)
        for (x = 0; x < dst_clipped_width; x++) {
379 380
            guint a, c, ad, cd, ar, cr, i;

381 382 383 384
            sx = x + src_clipped_x;
            sy = y + src_clipped_y;
            dx = x + dst_clipped_x;
            dy = y + dst_clipped_y;
385 386 387 388 389 390 391 392 393 394 395 396 397 398
            a = src_pixels[4 * sx + sy * srcrowstride + 3];

            if (a) {
                ad = dst_pixels[4 * dx + dy * dstrowstride + 3];
                ar = a + ad * (255 - a) / 255;
                dst_pixels[4 * dx + dy * dstrowstride + 3] = ar;
                for (i = 0; i < 3; i++) {
                    c = src_pixels[4 * sx + sy * srcrowstride + i];
                    cd = dst_pixels[4 * dx + dy * dstrowstride + i];
                    cr = c + cd * (255 - a) / 255;
                    dst_pixels[4 * dx + dy * dstrowstride + i] = cr;
                }
            }
        }
399 400

    cairo_surface_mark_dirty (dst);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
401 402
}

403
static gboolean
404
rsvg_art_affine_image (cairo_surface_t *img,
405
                       cairo_surface_t *intermediate,
406 407
                       cairo_matrix_t *affine,
                       double w,
408
                       double h)
409
{
Christian Persch's avatar
Christian Persch committed
410
    cairo_matrix_t inv_affine, raw_inv_affine;
411 412 413 414 415 416 417 418 419 420 421 422 423 424
    gint intstride;
    gint basestride;
    gint basex, basey;
    gdouble fbasex, fbasey;
    gdouble rawx, rawy;
    guchar *intpix;
    guchar *basepix;
    gint i, j, k, basebpp, ii, jj;
    gboolean has_alpha;
    gdouble pixsum[4];
    gboolean xrunnoff, yrunnoff;
    gint iwidth, iheight;
    gint width, height;

425
    g_assert (cairo_image_surface_get_format (intermediate) == CAIRO_FORMAT_ARGB32);
426

427 428
    cairo_surface_flush (img);

429 430 431 432
    width = cairo_image_surface_get_width (img);
    height = cairo_image_surface_get_height (img);
    iwidth = cairo_image_surface_get_width (intermediate);
    iheight = cairo_image_surface_get_height (intermediate);
433

434 435 436 437 438 439
    has_alpha = cairo_image_surface_get_format (img) == CAIRO_FORMAT_ARGB32;

    basestride = cairo_image_surface_get_stride (img);
    intstride = cairo_image_surface_get_stride (intermediate);
    basepix = cairo_image_surface_get_data (img);
    intpix = cairo_image_surface_get_data (intermediate);
440 441
    basebpp = has_alpha ? 4 : 3;

Christian Persch's avatar
Christian Persch committed
442 443
    raw_inv_affine = *affine;
    if (cairo_matrix_invert (&raw_inv_affine) != CAIRO_STATUS_SUCCESS)
444
      return FALSE;
445

Christian Persch's avatar
Christian Persch committed
446 447 448
    cairo_matrix_init_scale (&inv_affine, w, h);
    cairo_matrix_multiply (&inv_affine, &inv_affine, affine);
    if (cairo_matrix_invert (&inv_affine) != CAIRO_STATUS_SUCCESS)
449
      return FALSE;
450 451 452 453

    /*apply the transformation */
    for (i = 0; i < iwidth; i++)
        for (j = 0; j < iheight; j++) {
Christian Persch's avatar
Christian Persch committed
454 455 456 457
            fbasex = (inv_affine.xx * (double) i + inv_affine.xy * (double) j +
                      inv_affine.x0) * (double) width;
            fbasey = (inv_affine.yx * (double) i + inv_affine.yy * (double) j +
                      inv_affine.y0) * (double) height;
458 459
            basex = floor (fbasex);
            basey = floor (fbasey);
Christian Persch's avatar
Christian Persch committed
460 461
            rawx = raw_inv_affine.xx * i + raw_inv_affine.xy * j + raw_inv_affine.x0;
            rawy = raw_inv_affine.yx * i + raw_inv_affine.yy * j + raw_inv_affine.y0;
462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497
            if (rawx < 0 || rawy < 0 || rawx >= w ||
                rawy >= h || basex < 0 || basey < 0 || basex >= width || basey >= height) {
                for (k = 0; k < 4; k++)
                    intpix[i * 4 + j * intstride + k] = 0;
            } else {
                if (basex < 0 || basex + 1 >= width)
                    xrunnoff = TRUE;
                else
                    xrunnoff = FALSE;
                if (basey < 0 || basey + 1 >= height)
                    yrunnoff = TRUE;
                else
                    yrunnoff = FALSE;
                for (k = 0; k < basebpp; k++)
                    pixsum[k] = 0;
                for (ii = 0; ii < 2; ii++)
                    for (jj = 0; jj < 2; jj++) {
                        if (basex + ii < 0 || basey + jj < 0
                            || basex + ii >= width || basey + jj >= height);
                        else {
                            for (k = 0; k < basebpp; k++) {
                                pixsum[k] +=
                                    (double) basepix[basebpp * (basex + ii) +
                                                     (basey + jj) * basestride + k]
                                    * (xrunnoff ? 1 : fabs (fbasex - (double) (basex + (1 - ii))))
                                    * (yrunnoff ? 1 : fabs (fbasey - (double) (basey + (1 - jj))));
                            }
                        }
                    }
                for (k = 0; k < basebpp; k++)
                    intpix[i * 4 + j * intstride + k] = pixsum[k];
                if (!has_alpha)
                    intpix[i * 4 + j * intstride + 3] = 255;
            }

        }
498 499 500 501 502 503

    /* Don't need cairo_surface_mark_dirty(intermediate) here since
     * the only caller does further work and then calls that himself.
     */

    return TRUE;
Caleb Michael Moore's avatar
Caleb Michael Moore committed
504 505
}

506
static void
507
rsvg_filter_free_pair (gpointer value)
508
{
509
    RsvgFilterPrimitiveOutput *output;
510

511
    output = (RsvgFilterPrimitiveOutput *) value;
512
    cairo_surface_destroy (output->surface);
513
    g_free (output);
514 515
}

516 517 518 519
static void
rsvg_filter_context_free (RsvgFilterContext * ctx)
{
    if (!ctx)
520
        return;
521

522 523
    if (ctx->bg_surface)
        cairo_surface_destroy (ctx->bg_surface);
524 525 526 527

    g_free (ctx);
}

528 529 530
static gboolean
node_is_filter_primitive (RsvgNode *node)
{
531
    RsvgNodeType type = rsvg_node_get_type (node);
532 533 534 535

    return type > RSVG_NODE_TYPE_FILTER_PRIMITIVE_FIRST && type < RSVG_NODE_TYPE_FILTER_PRIMITIVE_LAST;
}

536 537 538 539 540
static gboolean
render_child_if_filter_primitive (RsvgNode *node, gpointer data)
{
    RsvgFilterContext *filter_ctx = data;

541 542 543 544 545 546
    if (node_is_filter_primitive (node)) {
        RsvgFilterPrimitive *primitive;

        primitive = rsvg_rust_cnode_get_impl (node);
        rsvg_filter_primitive_render (node, primitive, filter_ctx);
    }
547 548 549 550

    return TRUE;
}

551
/**
552
 * rsvg_filter_render:
553
 * @node: a pointer to the filter node to use
554
 * @source: the a #cairo_surface_t of type %CAIRO_SURFACE_TYPE_IMAGE
555 556
 * @context: the context
 *
557 558 559
 * Create a new surface applied the filter. This function will create
 * a context for itself, set up the coordinate systems execute all its
 * little primatives and then clean up its own mess.
560
 *
561
 * Returns: (transfer full): a new #cairo_surface_t
562
 **/
563
cairo_surface_t *
564
rsvg_filter_render (RsvgNode *filter_node,
565
                    cairo_surface_t *source,
566 567
                    RsvgDrawingCtx *context,
                    RsvgBbox *bounds,
568
                    char *channelmap)
569
{
570
    RsvgFilter *filter;
571 572
    RsvgFilterContext *ctx;
    guint i;
573 574 575 576 577
    cairo_surface_t *output;

    g_return_val_if_fail (source != NULL, NULL);
    g_return_val_if_fail (cairo_surface_get_type (source) == CAIRO_SURFACE_TYPE_IMAGE, NULL);

578 579
    g_assert (rsvg_node_get_type (filter_node) == RSVG_NODE_TYPE_FILTER);
    filter = rsvg_rust_cnode_get_impl (filter_node);
580 581 582

    ctx = g_new0 (RsvgFilterContext, 1);
    ctx->filter = filter;
583 584
    ctx->source_surface = source;
    ctx->bg_surface = NULL;
585 586
    ctx->results = g_hash_table_new_full (g_str_hash, g_str_equal, g_free, rsvg_filter_free_pair);
    ctx->ctx = context;
587

588
    rsvg_filter_fix_coordinate_system (ctx, rsvg_current_state (context), bounds);
589

Christian Persch's avatar
Christian Persch committed
590
    ctx->lastresult.surface = cairo_surface_reference (source);
591
    ctx->lastresult.bounds = rsvg_filter_primitive_get_bounds (NULL, ctx);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
592

593 594
    for (i = 0; i < 4; i++)
        ctx->channelmap[i] = channelmap[i] - '0';
595

596
    rsvg_node_foreach_child (filter_node, render_child_if_filter_primitive, ctx);
597

598
    output = ctx->lastresult.surface;
599

600
    g_hash_table_destroy (ctx->results);
601

602
    rsvg_filter_context_free (ctx);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
603

604
    return output;
605 606 607
}

/**
608
 * rsvg_filter_store_result:
609 610 611 612 613 614 615 616
 * @name: The name of the result
 * @result: The pointer to the result
 * @ctx: the context that this was called in
 *
 * Puts the new result into the hash for easy finding later, also
 * Stores it as the last result
 **/
static void
617
rsvg_filter_store_output (GString * name, RsvgFilterPrimitiveOutput result, RsvgFilterContext * ctx)
618
{
619 620
    RsvgFilterPrimitiveOutput *store;

621
    cairo_surface_destroy (ctx->lastresult.surface);
622

623
    store = g_new0 (RsvgFilterPrimitiveOutput, 1);
624 625
    *store = result;

626 627
    if (name->str[0] != '\0') {
        cairo_surface_reference (result.surface);        /* increments the references for the table */
628 629 630
        g_hash_table_insert (ctx->results, g_strdup (name->str), store);
    }

631
    cairo_surface_reference (result.surface);    /* increments the references for the last result */
632
    ctx->lastresult = result;
633 634
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
635
static void
636 637 638
rsvg_filter_store_result (GString * name,
                          cairo_surface_t *surface,
                          RsvgFilterContext * ctx)
639 640 641 642 643 644
{
    RsvgFilterPrimitiveOutput output;
    output.bounds.x0 = 0;
    output.bounds.y0 = 0;
    output.bounds.x1 = ctx->width;
    output.bounds.y1 = ctx->height;
645
    output.surface = surface;
646 647

    rsvg_filter_store_output (name, output, ctx);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
648 649
}

650 651 652
static cairo_surface_t *
surface_get_alpha (cairo_surface_t *source,
                   RsvgFilterContext * ctx)
653
{
654 655 656
    guchar *data;
    guchar *pbdata;
    gsize i, pbsize;
657
    cairo_surface_t *surface;
658

Christian Persch's avatar
Christian Persch committed
659 660 661
    if (source == NULL)
        return NULL;

662 663
    cairo_surface_flush (source);

664
    pbsize = cairo_image_surface_get_width (source) *
665
             cairo_image_surface_get_height (source);
666

667 668
    surface = _rsvg_image_surface_new (cairo_image_surface_get_width (source),
                                       cairo_image_surface_get_height (source));
Christian Persch's avatar
Christian Persch committed
669 670
    if (surface == NULL)
        return NULL;
671

672 673
    data = cairo_image_surface_get_data (surface);
    pbdata = cairo_image_surface_get_data (source);
674

675
    /* FIXMEchpe: rewrite this into nested width, height loops */
676 677 678
    for (i = 0; i < pbsize; i++)
        data[i * 4 + ctx->channelmap[3]] = pbdata[i * 4 + ctx->channelmap[3]];

679 680
    cairo_surface_mark_dirty (surface);
    return surface;
681 682
}

683
static cairo_surface_t *
684 685
rsvg_compile_bg (RsvgDrawingCtx * ctx)
{
686
    RsvgCairoRender *render = RSVG_CAIRO_RENDER (ctx->render);
687
    cairo_surface_t *surface;
688
    cairo_t *cr;
689 690
    GList *i;

691
    surface = _rsvg_image_surface_new (render->width, render->height);
Christian Persch's avatar
Christian Persch committed
692 693
    if (surface == NULL)
        return NULL;
694 695 696 697 698 699 700 701 702 703 704 705 706

    cr = cairo_create (surface);

    for (i = g_list_last (render->cr_stack); i != NULL; i = g_list_previous (i)) {
        cairo_t *draw = i->data;
        gboolean nest = draw != render->initial_cr;
        cairo_set_source_surface (cr, cairo_get_target (draw),
                                  nest ? 0 : -render->offset_x,
                                  nest ? 0 : -render->offset_y);
        cairo_paint (cr);
    }

    cairo_destroy (cr);
707 708

    return surface;
709 710
}

711 712
/**
 * rsvg_filter_get_bg:
713
 *
714
 * Returns: (transfer none) (nullable): a #cairo_surface_t, or %NULL
715 716
 */
static cairo_surface_t *
717 718
rsvg_filter_get_bg (RsvgFilterContext * ctx)
{
719 720
    if (!ctx->bg_surface)
        ctx->bg_surface = rsvg_compile_bg (ctx->ctx);
721

722
    return ctx->bg_surface;
723 724
}

725
/**
726
 * rsvg_filter_get_result:
727
 * @name: The name of the surface
728
 * @ctx: the context that this was called in
729 730 731
 *
 * Gets a surface for a primitive
 *
732
 * Returns: (nullable): a pointer to the result that the name refers to, a special
733
 * surface if the name is a special keyword or %NULL if nothing was found
734
 **/
Caleb Michael Moore's avatar
Caleb Michael Moore committed
735 736
static RsvgFilterPrimitiveOutput
rsvg_filter_get_result (GString * name, RsvgFilterContext * ctx)
737
{
738 739 740 741 742
    RsvgFilterPrimitiveOutput output;
    RsvgFilterPrimitiveOutput *outputpointer;
    output.bounds.x0 = output.bounds.x1 = output.bounds.y0 = output.bounds.y1 = 0;

    if (!strcmp (name->str, "SourceGraphic")) {
743
        output.surface = cairo_surface_reference (ctx->source_surface);
744 745
        return output;
    } else if (!strcmp (name->str, "BackgroundImage")) {
Christian Persch's avatar
Christian Persch committed
746 747 748
        output.surface = rsvg_filter_get_bg (ctx);
        if (output.surface)
            cairo_surface_reference (output.surface);
749
        return output;
750
    } else if (!strcmp (name->str, "") || !strcmp (name->str, "none")) {
751
        output = ctx->lastresult;
752
        cairo_surface_reference (output.surface);
753 754
        return output;
    } else if (!strcmp (name->str, "SourceAlpha")) {
755
        output.surface = surface_get_alpha (ctx->source_surface, ctx);
756 757
        return output;
    } else if (!strcmp (name->str, "BackgroundAlpha")) {
758
        output.surface = surface_get_alpha (rsvg_filter_get_bg (ctx), ctx);
759 760 761 762 763 764 765
        return output;
    }

    outputpointer = (RsvgFilterPrimitiveOutput *) (g_hash_table_lookup (ctx->results, name->str));

    if (outputpointer != NULL) {
        output = *outputpointer;
766
        cairo_surface_reference (output.surface);
767 768 769
        return output;
    }

770
    output.surface = NULL;
771
    return output;
Caleb Michael Moore's avatar
Caleb Michael Moore committed
772
}
773

774
static cairo_surface_t *
Caleb Michael Moore's avatar
Caleb Michael Moore committed
775 776
rsvg_filter_get_in (GString * name, RsvgFilterContext * ctx)
{
777 778 779 780 781 782 783 784
    cairo_surface_t *surface;

    surface = rsvg_filter_get_result (name, ctx).surface;
    if (surface == NULL || cairo_surface_status (surface) != CAIRO_STATUS_SUCCESS) {
        return NULL;
    }

    return surface;
785 786
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
787
static void
788
rsvg_filter_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts)
789
{
790
    RsvgFilter *filter = impl;
791 792
    const char *value;

793 794 795 796 797
    if ((value = rsvg_property_bag_lookup (atts, "filterUnits"))) {
        if (!strcmp (value, "userSpaceOnUse"))
            filter->filterunits = userSpaceOnUse;
        else
            filter->filterunits = objectBoundingBox;
798
    }
799 800 801 802 803 804 805 806 807 808 809 810 811 812
    if ((value = rsvg_property_bag_lookup (atts, "primitiveUnits"))) {
        if (!strcmp (value, "objectBoundingBox"))
            filter->primitiveunits = objectBoundingBox;
        else
            filter->primitiveunits = userSpaceOnUse;
    }
    if ((value = rsvg_property_bag_lookup (atts, "x")))
        filter->x = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL);
    if ((value = rsvg_property_bag_lookup (atts, "y")))
        filter->y = rsvg_length_parse (value, LENGTH_DIR_VERTICAL);
    if ((value = rsvg_property_bag_lookup (atts, "width")))
        filter->width = rsvg_length_parse (value, LENGTH_DIR_HORIZONTAL);
    if ((value = rsvg_property_bag_lookup (atts, "height")))
        filter->height = rsvg_length_parse (value, LENGTH_DIR_VERTICAL);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
813 814
}

815 816 817 818 819 820 821 822 823 824 825 826 827 828
static void
rsvg_filter_draw (RsvgNode *node, gpointer impl, RsvgDrawingCtx *ctx, int dominate)
{
    /* nothing; filters are drawn in rsvg-cairo-draw.c */
}

static void
rsvg_filter_free (gpointer impl)
{
    RsvgFilter *filter = impl;

    g_free (filter);
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
829
/**
830
 * rsvg_new_filter:
Caleb Michael Moore's avatar
Caleb Michael Moore committed
831 832 833 834
 *
 * Creates a blank filter and assigns default values to everything
 **/
RsvgNode *
835
rsvg_new_filter (const char *element_name, RsvgNode *parent)
Caleb Michael Moore's avatar
Caleb Michael Moore committed
836
{
837
    RsvgFilter *filter;
838

839
    filter = g_new0 (RsvgFilter, 1);
840 841
    filter->filterunits = objectBoundingBox;
    filter->primitiveunits = userSpaceOnUse;
842 843 844 845
    filter->x = rsvg_length_parse ("-10%", LENGTH_DIR_HORIZONTAL);
    filter->y = rsvg_length_parse ("-10%", LENGTH_DIR_VERTICAL);
    filter->width = rsvg_length_parse ("120%", LENGTH_DIR_HORIZONTAL);
    filter->height = rsvg_length_parse ("120%", LENGTH_DIR_VERTICAL);
846 847 848 849 850 851 852 853

    return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER,
                                parent,
                                rsvg_state_new (),
                                filter,
                                rsvg_filter_set_atts,
                                rsvg_filter_draw,
                                rsvg_filter_free);
854 855 856 857 858
}

/*************************************************************/
/*************************************************************/

859 860 861 862 863
typedef enum {
    normal, multiply, screen, darken, lighten, softlight,
    hardlight, colordodge, colorburn, overlay, exclusion,
    difference
} RsvgFilterPrimitiveBlendMode;
864 865

typedef struct _RsvgFilterPrimitiveBlend RsvgFilterPrimitiveBlend;
866 867 868 869
struct _RsvgFilterPrimitiveBlend {
    RsvgFilterPrimitive super;
    RsvgFilterPrimitiveBlendMode mode;
    GString *in2;
870 871
};

872
static void
873 874
rsvg_filter_blend (RsvgFilterPrimitiveBlendMode mode,
                   cairo_surface_t *in,
875
                   cairo_surface_t *in2,
876 877
                   cairo_surface_t* output,
                   RsvgIRect boundarys,
878
                   int *channelmap)
879 880 881 882 883 884 885
{
    guchar i;
    gint x, y;
    gint rowstride, rowstride2, rowstrideo, height, width;
    guchar *in_pixels;
    guchar *in2_pixels;
    guchar *output_pixels;
886 887 888 889

    cairo_surface_flush (in);
    cairo_surface_flush (in2);

890 891 892 893 894
    height = cairo_image_surface_get_height (in);
    width = cairo_image_surface_get_width (in);
    rowstride = cairo_image_surface_get_stride (in);
    rowstride2 = cairo_image_surface_get_stride (in2);
    rowstrideo = cairo_image_surface_get_stride (output);
895

896 897 898
    output_pixels = cairo_image_surface_get_data (output);
    in_pixels = cairo_image_surface_get_data (in);
    in2_pixels = cairo_image_surface_get_data (in2);
899 900 901 902

    if (boundarys.x0 < 0)
        boundarys.x0 = 0;
    if (boundarys.y0 < 0)
903
        boundarys.y0 = 0;
904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987
    if (boundarys.x1 >= width)
        boundarys.x1 = width;
    if (boundarys.y1 >= height)
        boundarys.y1 = height;

    for (y = boundarys.y0; y < boundarys.y1; y++)
        for (x = boundarys.x0; x < boundarys.x1; x++) {
            double qr, cr, qa, qb, ca, cb, bca, bcb;
            int ch;

            qa = (double) in_pixels[4 * x + y * rowstride + channelmap[3]] / 255.0;
            qb = (double) in2_pixels[4 * x + y * rowstride2 + channelmap[3]] / 255.0;
            qr = 1 - (1 - qa) * (1 - qb);
            cr = 0;
            for (ch = 0; ch < 3; ch++) {
                i = channelmap[ch];
                ca = (double) in_pixels[4 * x + y * rowstride + i] / 255.0;
                cb = (double) in2_pixels[4 * x + y * rowstride2 + i] / 255.0;
                /*these are the ca and cb that are used in the non-standard blend functions */
                bcb = (1 - qa) * cb + ca;
                bca = (1 - qb) * ca + cb;
                switch (mode) {
                case normal:
                    cr = (1 - qa) * cb + ca;
                    break;
                case multiply:
                    cr = (1 - qa) * cb + (1 - qb) * ca + ca * cb;
                    break;
                case screen:
                    cr = cb + ca - ca * cb;
                    break;
                case darken:
                    cr = MIN ((1 - qa) * cb + ca, (1 - qb) * ca + cb);
                    break;
                case lighten:
                    cr = MAX ((1 - qa) * cb + ca, (1 - qb) * ca + cb);
                    break;
                case softlight:
                    if (bcb < 0.5)
                        cr = 2 * bca * bcb + bca * bca * (1 - 2 * bcb);
                    else
                        cr = sqrt (bca) * (2 * bcb - 1) + (2 * bca) * (1 - bcb);
                    break;
                case hardlight:
                    if (cb < 0.5)
                        cr = 2 * bca * bcb;
                    else
                        cr = 1 - 2 * (1 - bca) * (1 - bcb);
                    break;
                case colordodge:
                    if (bcb == 1)
                        cr = 1;
                    else
                        cr = MIN (bca / (1 - bcb), 1);
                    break;
                case colorburn:
                    if (bcb == 0)
                        cr = 0;
                    else
                        cr = MAX (1 - (1 - bca) / bcb, 0);
                    break;
                case overlay:
                    if (bca < 0.5)
                        cr = 2 * bca * bcb;
                    else
                        cr = 1 - 2 * (1 - bca) * (1 - bcb);
                    break;
                case exclusion:
                    cr = bca + bcb - 2 * bca * bcb;
                    break;
                case difference:
                    cr = abs (bca - bcb);
                    break;
                }
                cr *= 255.0;
                if (cr > 255)
                    cr = 255;
                if (cr < 0)
                    cr = 0;
                output_pixels[4 * x + y * rowstrideo + i] = (guchar) cr;

            }
            output_pixels[4 * x + y * rowstrideo + channelmap[3]] = qr * 255.0;
        }
988

989 990
    cairo_surface_mark_dirty (output);
}
991 992

static void
993
rsvg_filter_primitive_blend_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx)
994
{
995
    RsvgFilterPrimitiveBlend *blend = (RsvgFilterPrimitiveBlend *) primitive;
996
    RsvgIRect boundarys;
997
    cairo_surface_t *output, *in, *in2;
998

999
    boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx);
1000

1001
    in = rsvg_filter_get_in (primitive->in, ctx);
Christian Persch's avatar
Christian Persch committed
1002 1003 1004
    if (in == NULL)
      return;

1005
    in2 = rsvg_filter_get_in (blend->in2, ctx);
Christian Persch's avatar
Christian Persch committed
1006 1007 1008 1009
    if (in2 == NULL) {
        cairo_surface_destroy (in);
        return;
    }
1010

1011 1012
    output = _rsvg_image_surface_new (cairo_image_surface_get_width (in),
                                      cairo_image_surface_get_height (in));
Christian Persch's avatar
Christian Persch committed
1013 1014 1015 1016 1017
    if (output == NULL) {
        cairo_surface_destroy (in);
        cairo_surface_destroy (in2);
        return;
    }
1018

1019
    rsvg_filter_blend (blend->mode, in, in2, output, boundarys, ctx->channelmap);
1020

1021
    rsvg_filter_store_result (primitive->result, output, ctx);
1022

1023 1024 1025
    cairo_surface_destroy (in);
    cairo_surface_destroy (in2);
    cairo_surface_destroy (output);
1026 1027 1028
}

static void
1029
rsvg_filter_primitive_blend_free (gpointer impl)
1030
{
1031 1032
    RsvgFilterPrimitiveBlend *blend = impl;

1033 1034
    g_string_free (blend->in2, TRUE);

1035
    rsvg_filter_primitive_free (impl);
1036 1037
}

Caleb Michael Moore's avatar
Caleb Michael Moore committed
1038
static void
1039
rsvg_filter_primitive_blend_set_atts (RsvgNode *node, gpointer impl, RsvgHandle *handle, RsvgPropertyBag *atts)
1040
{
1041
    RsvgFilterPrimitiveBlend *filter = impl;
1042 1043
    const char *value;

1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054
    if ((value = rsvg_property_bag_lookup (atts, "mode"))) {
        if (!strcmp (value, "multiply"))
            filter->mode = multiply;
        else if (!strcmp (value, "screen"))
            filter->mode = screen;
        else if (!strcmp (value, "darken"))
            filter->mode = darken;
        else if (!strcmp (value, "lighten"))
            filter->mode = lighten;
        else
            filter->mode = normal;
1055
    }
1056 1057 1058 1059 1060 1061 1062 1063
    if ((value = rsvg_property_bag_lookup (atts, "in")))
        g_string_assign (filter->super.in, value);
    if ((value = rsvg_property_bag_lookup (atts, "in2")))
        g_string_assign (filter->in2, value);
    if ((value = rsvg_property_bag_lookup (atts, "result")))
        g_string_assign (filter->super.result, value);

    filter_primitive_set_x_y_width_height_atts ((RsvgFilterPrimitive *) filter, atts);
Caleb Michael Moore's avatar
Caleb Michael Moore committed
1064 1065 1066
}

RsvgNode *
1067
rsvg_new_filter_primitive_blend (const char *element_name, RsvgNode *parent)
Caleb Michael Moore's avatar
Caleb Michael Moore committed
1068
{
1069
    RsvgFilterPrimitiveBlend *filter;
1070

1071
    filter = g_new0 (RsvgFilterPrimitiveBlend, 1);
1072 1073 1074 1075
    filter->mode = normal;
    filter->super.in = g_string_new ("none");
    filter->in2 = g_string_new ("none");
    filter->super.result = g_string_new ("none");
1076
    filter->super.render = rsvg_filter_primitive_blend_render;
1077 1078 1079 1080 1081 1082 1083 1084

    return rsvg_rust_cnode_new (RSVG_NODE_TYPE_FILTER_PRIMITIVE_BLEND,
                                parent,
                                rsvg_state_new (),
                                filter,
                                rsvg_filter_primitive_blend_set_atts,
                                rsvg_filter_draw,
                                rsvg_filter_primitive_blend_free);
1085 1086 1087 1088 1089 1090 1091
}

/*************************************************************/
/*************************************************************/

typedef struct _RsvgFilterPrimitiveConvolveMatrix RsvgFilterPrimitiveConvolveMatrix;

1092 1093 1094 1095 1096 1097
typedef enum {
    EDGE_MODE_DUPLICATE,
    EDGE_MODE_WRAP,
    EDGE_MODE_NONE
} EdgeMode;

1098 1099 1100 1101 1102 1103 1104 1105 1106
struct _RsvgFilterPrimitiveConvolveMatrix {
    RsvgFilterPrimitive super;
    double *KernelMatrix;
    double divisor;
    gint orderx, ordery;
    double dx, dy;
    double bias;
    gint targetx, targety;
    gboolean preservealpha;
1107
    EdgeMode edgemode;
1108 1109 1110
};

static void
1111
rsvg_filter_primitive_convolve_matrix_render (RsvgNode *node, RsvgFilterPrimitive *primitive, RsvgFilterContext *ctx)
1112
{
1113 1114
    RsvgFilterPrimitiveConvolveMatrix *convolve = (RsvgFilterPrimitiveConvolveMatrix *) primitive;

1115 1116 1117 1118 1119 1120 1121 1122 1123
    guchar ch;
    gint x, y;
    gint i, j;
    gint rowstride, height, width;
    RsvgIRect boundarys;

    guchar *in_pixels;
    guchar *output_pixels;

1124
    cairo_surface_t *output, *in;
1125 1126 1127 1128 1129 1130 1131 1132

    gint sx, sy, kx, ky;
    guchar sval;
    double kval, sum, dx, dy, targetx, targety;
    int umch;

    gint tempresult;

1133
    boundarys = rsvg_filter_primitive_get_bounds (primitive, ctx);
1134

1135
    in = rsvg_filter_get_in (primitive->in, ctx);
Christian Persch's avatar
Christian Persch committed
1136 1137 1138
    if (in == NULL)
        return;

1139 1140
    cairo_surface_flush (in);

1141
    in_pixels = cairo_image_surface_get_data (in);
1142

1143 1144
    height = cairo_image_surface_get_height (in);
    width = cairo_image_surface_get_width (in);
1145

1146 1147
    targetx = convolve->targetx * ctx->paffine.xx;
    targety = convolve->targety * ctx->paffine.yy;
1148

1149 1150 1151
    if (convolve->dx != 0 || convolve->dy != 0) {
        dx = convolve->dx * ctx->paffine.xx;
        dy = convolve->dy * ctx->paffine.yy;
1152 1153 1154
    } else
        dx = dy = 1;

1155
    rowstride = cairo_image_surface_get_stride (in);
1156

1157
    output = _rsvg_image_surface_new (width, height);
Christian Persch's avatar
Christian Persch committed
1158 1159 1160 1161 1162
    if (output == NULL) {
        cairo_surface_destroy (in);
        return;
    }

1163
    output_pixels = cairo_image_surface_get_data (output);
1164

1165
    for (y = boundarys.y0; y < boundarys.y1; y++) {
1166
        for (x = boundarys.x0; x < boundarys.x1; x++) {
1167
            for (umch = 0; umch < 3 + !convolve->preservealpha; umch++) {
1168 1169
                ch = ctx->channelmap[umch];
                sum = 0;
1170
                for (i = 0; i < convolve->ordery; i++) {
1171
                    for (j = 0; j < convolve->orderx; j++) {
1172 1173 1174
                        int alpha;
                        sx = x - targetx + j * dx;
                        sy = y - targety + i * dy;
1175
                        if (convolve->edgemode == EDGE_MODE_DUPLICATE) {
1176 1177 1178 1179 1180 1181 1182 1183
                            if (sx < boundarys.x0)
                                sx = boundarys.x0;
                            if (sx >= boundarys.x1)
                                sx = boundarys.x1 - 1;
                            if (sy < boundarys.y0)
                                sy = boundarys.y0;
                            if (sy >= boundarys.y1)
                                sy = boundarys.y1 - 1;
1184
                        } else if (convolve->edgemode == EDGE_MODE_WRAP) {
1185 1186 1187 1188 1189 1190
                            if (sx < boundarys.x0 || (sx >= boundarys.x1))
                                sx = boundarys.x0 + (sx - boundarys.x0) %
                                    (boundarys.x1 - boundarys.x0);
                            if (sy < boundarys.y0 || (sy >= boundarys.y1))
                                sy = boundarys.y0 + (sy - boundarys.y0) %
                                    (boundarys.y1 - boundarys.y0);
1191
                        } else if (convolve->edgemode == EDGE_MODE_NONE) {
1192 1193 1194
                            if (sx < boundarys.x0 || (sx >= boundarys.x1) ||
                                sy < boundarys.y0 || (sy >= boundarys.y1))
                                continue;
1195 1196 1197
                        } else {
                            g_assert_not_reached ();
                        }
1198

1199 1200
                        kx = convolve->orderx - j - 1;
                        ky = convolve->ordery - i - 1;
1201 1202 1203 1204 1205 1206 1207
                        alpha = in_pixels[4 * sx + sy * rowstride + 3];
                        if (ch == 3)
                            sval = alpha;
                        else if (alpha)
                            sval = in_pixels[4 * sx + sy * rowstride + ch] * 255 / alpha;
                        else
                            sval = 0;
1208
                        kval = convolve->KernelMatrix[kx + ky * convolve->orderx];
1209 1210
                        sum += (double) sval *kval;
                    }
1211 1212
                }

1213
                tempresult = sum / convolve->divisor + convolve->bias;
1214 1215 1216 1217 1218 1219 1220 1221

                if (tempresult > 255)
                    tempresult = 255;
                if (tempresult < 0)
                    tempresult = 0;

                output_pixels[4 * x + y * rowstride + ch] = tempresult;
            }
1222
            if (convolve->preservealpha)
1223 1224 1225 1226 1227 1228 1229 1230 1231
                output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] =
                    in_pixels[4 * x + y * rowstride + ctx->channelmap[3]];
            for (umch = 0; umch < 3; umch++) {
                ch = ctx->channelmap[umch];
                output_pixels[4 * x + y * rowstride + ch] =
                    output_pixels[4 * x + y * rowstride + ch] *
                    output_pixels[4 * x + y * rowstride + ctx->channelmap[3]] / 255;
            }
        }
1232
    }
1233 1234 1235

    cairo_surface_mark_dirty (output);

1236
    rsvg_filter_store_result (primitive->result, output, ctx);
1237

1238 1239
    cairo_surface_destroy (in);
    cairo_surface_destroy (output);
1240 1241 1242
}

static void
1243
rsvg_filter_primitive_convolve_matrix_free (gpointer impl)
1244
{
1245
    RsvgFilterPrimitiveConvolveMatrix *convolve = impl;