3ca2b0dbaedd0ba2a13930359a9f341978784c7c
1 #define __NR_FILTER_CPP__
3 /*
4 * SVG filters rendering
5 *
6 * Author:
7 * Niko Kiirala <niko@kiirala.com>
8 *
9 * Copyright (C) 2006-2008 Niko Kiirala
10 *
11 * Released under GNU GPL, read the file 'COPYING' for more information
12 */
14 #include <glib.h>
15 #include <cmath>
16 #include <cstring>
17 #include <string>
19 #include "display/nr-filter.h"
20 #include "display/nr-filter-primitive.h"
21 #include "display/nr-filter-slot.h"
22 #include "display/nr-filter-types.h"
23 #include "display/nr-filter-units.h"
25 #include "display/nr-filter-blend.h"
26 #include "display/nr-filter-composite.h"
27 #include "display/nr-filter-convolve-matrix.h"
28 #include "display/nr-filter-colormatrix.h"
29 #include "display/nr-filter-component-transfer.h"
30 #include "display/nr-filter-diffuselighting.h"
31 #include "display/nr-filter-displacement-map.h"
32 #include "display/nr-filter-flood.h"
33 #include "display/nr-filter-gaussian.h"
34 #include "display/nr-filter-image.h"
35 #include "display/nr-filter-merge.h"
36 #include "display/nr-filter-morphology.h"
37 #include "display/nr-filter-offset.h"
38 #include "display/nr-filter-specularlighting.h"
39 #include "display/nr-filter-tile.h"
40 #include "display/nr-filter-turbulence.h"
42 #include "display/nr-arena.h"
43 #include "display/nr-arena-item.h"
44 #include "libnr/nr-pixblock.h"
45 #include "libnr/nr-blit.h"
46 #include <2geom/matrix.h>
47 #include <2geom/rect.h>
48 #include "svg/svg-length.h"
49 #include "sp-filter-units.h"
50 #include "preferences.h"
52 #if defined (SOLARIS) && (SOLARIS == 8)
53 #include "round.h"
54 using Inkscape::round;
55 #endif
57 namespace Inkscape {
58 namespace Filters {
60 using Geom::X;
61 using Geom::Y;
63 static Geom::OptRect get_item_bbox(NRArenaItem const *item) {
64 Geom::Rect item_bbox;
65 if (item->item_bbox) {
66 item_bbox = *(item->item_bbox);
67 } else {
68 // Bounding box might not exist, so create a dummy one.
69 Geom::Point zero(0, 0);
70 item_bbox = Geom::Rect(zero, zero);
71 }
72 if (item_bbox.min()[X] > item_bbox.max()[X]
73 || item_bbox.min()[Y] > item_bbox.max()[Y])
74 {
75 // In case of negative-size bbox, return an empty OptRect
76 return Geom::OptRect();
77 }
78 return Geom::OptRect(item_bbox);
79 }
81 Filter::Filter()
82 {
83 _primitive_count = 0;
84 _primitive_table_size = 1;
85 _primitive = new FilterPrimitive*[1];
86 _primitive[0] = NULL;
87 //_primitive_count = 1;
88 //_primitive[0] = new FilterGaussian;
89 _common_init();
90 }
92 Filter::Filter(int n)
93 {
94 _primitive_count = 0;
95 _primitive_table_size = (n > 0) ? n : 1; // we guarantee there is at least 1(one) filter slot
96 _primitive = new FilterPrimitive*[_primitive_table_size];
97 for ( int i = 0 ; i < _primitive_table_size ; i++ ) {
98 _primitive[i] = NULL;
99 }
100 _common_init();
101 }
103 void Filter::_common_init() {
104 _slot_count = 1;
105 // Having "not set" here as value means the output of last filter
106 // primitive will be used as output of this filter
107 _output_slot = NR_FILTER_SLOT_NOT_SET;
109 // These are the default values for filter region,
110 // as specified in SVG standard
111 // NB: SVGLength.set takes prescaled percent values: -.10 means -10%
112 _region_x.set(SVGLength::PERCENT, -.10, 0);
113 _region_y.set(SVGLength::PERCENT, -.10, 0);
114 _region_width.set(SVGLength::PERCENT, 1.20, 0);
115 _region_height.set(SVGLength::PERCENT, 1.20, 0);
117 // Filter resolution, negative value here stands for "automatic"
118 _x_pixels = -1.0;
119 _y_pixels = -1.0;
121 _filter_units = SP_FILTER_UNITS_OBJECTBOUNDINGBOX;
122 _primitive_units = SP_FILTER_UNITS_USERSPACEONUSE;
123 }
125 Filter::~Filter()
126 {
127 clear_primitives();
128 delete[] _primitive;
129 }
132 int Filter::render(NRArenaItem const *item, NRPixBlock *pb)
133 {
134 if (!_primitive[0]) {
135 // TODO: Should clear the input buffer instead of just returning
136 return 1;
137 }
139 FilterQuality const filterquality = (FilterQuality)item->arena->filterquality;
140 int const blurquality = item->arena->blurquality;
142 Geom::Matrix trans = item->ctm;
143 FilterSlot slot(_slot_count, item);
144 slot.set_quality(filterquality);
145 slot.set_blurquality(blurquality);
147 Geom::Rect item_bbox;
148 {
149 Geom::OptRect maybe_bbox = get_item_bbox(item);
150 if (maybe_bbox.isEmpty()) {
151 // Code below needs a bounding box
152 return 1;
153 }
154 item_bbox = *maybe_bbox;
155 }
157 Geom::Rect filter_area = filter_effect_area(item_bbox);
158 if (item_bbox.hasZeroArea()) {
159 // It's no use to try and filter an empty object.
160 return 1;
161 }
163 FilterUnits units(_filter_units, _primitive_units);
164 units.set_ctm(trans);
165 units.set_item_bbox(item_bbox);
166 units.set_filter_area(filter_area);
168 // TODO: with filterRes of 0x0 should return an empty image
169 std::pair<double,double> resolution
170 = _filter_resolution(filter_area, trans, filterquality);
171 units.set_resolution(resolution.first, resolution.second);
172 if (_x_pixels > 0) {
173 units.set_automatic_resolution(false);
174 }
175 else {
176 units.set_automatic_resolution(true);
177 }
179 units.set_paraller(false);
180 for (int i = 0 ; i < _primitive_count ; i++) {
181 if (_primitive[i]->get_input_traits() & TRAIT_PARALLER) {
182 units.set_paraller(true);
183 break;
184 }
185 }
187 slot.set_units(units);
189 NRPixBlock *in = new NRPixBlock;
190 nr_pixblock_setup_fast(in, pb->mode, pb->area.x0, pb->area.y0,
191 pb->area.x1, pb->area.y1, true);
192 if (in->size != NR_PIXBLOCK_SIZE_TINY && in->data.px == NULL) {
193 g_warning("Inkscape::Filters::Filter::render: failed to reserve temporary buffer");
194 return 0;
195 }
196 nr_blit_pixblock_pixblock(in, pb);
197 in->empty = FALSE;
198 slot.set(NR_FILTER_SOURCEGRAPHIC, in);
200 // Check that we are rendering a non-empty area
201 in = slot.get(NR_FILTER_SOURCEGRAPHIC);
202 if (in->area.x1 - in->area.x0 <= 0 || in->area.y1 - in->area.y0 <= 0) {
203 if (in->area.x1 - in->area.x0 < 0 || in->area.y1 - in->area.y0 < 0) {
204 g_warning("Inkscape::Filters::Filter::render: negative area! (%d, %d) (%d, %d)",
205 in->area.x0, in->area.y0, in->area.x1, in->area.y1);
206 }
207 return 0;
208 }
209 in = NULL; // in is now handled by FilterSlot, we should not touch it
211 for (int i = 0 ; i < _primitive_count ; i++) {
212 _primitive[i]->render(slot, units);
213 }
215 slot.get_final(_output_slot, pb);
217 // Take note of the amount of used image slots
218 // -> next time this filter is rendered, we can reserve enough slots
219 // immediately
220 _slot_count = slot.get_slot_count();
221 return 0;
222 }
224 void Filter::area_enlarge(NRRectL &bbox, NRArenaItem const *item) const {
225 for (int i = 0 ; i < _primitive_count ; i++) {
226 if (_primitive[i]) _primitive[i]->area_enlarge(bbox, item->ctm);
227 }
228 /*
229 TODO: something. See images at the bottom of filters.svg with medium-low
230 filtering quality.
232 Inkscape::Preferences *prefs = Inkscape::Preferences::get();
233 FilterQuality const filterquality = (FilterQuality)prefs->getInt("/options/filterquality/value");
235 if (_x_pixels <= 0 && (filterquality == FILTER_QUALITY_BEST ||
236 filterquality == FILTER_QUALITY_BETTER)) {
237 return;
238 }
240 Geom::Rect item_bbox;
241 Geom::OptRect maybe_bbox = get_item_bbox(item);
242 if (maybe_bbox.isEmpty()) {
243 // Code below needs a bounding box
244 return;
245 }
246 item_bbox = *maybe_bbox;
248 std::pair<double,double> res_low
249 = _filter_resolution(item_bbox, item->ctm, filterquality);
250 //std::pair<double,double> res_full
251 // = _filter_resolution(item_bbox, item->ctm, FILTER_QUALITY_BEST);
252 double pixels_per_block = fmax(item_bbox.width() / res_low.first,
253 item_bbox.height() / res_low.second);
254 bbox.x0 -= (int)pixels_per_block;
255 bbox.x1 += (int)pixels_per_block;
256 bbox.y0 -= (int)pixels_per_block;
257 bbox.y1 += (int)pixels_per_block;
258 */
259 }
261 void Filter::bbox_enlarge(NRRectL &bbox) {
262 // Modifying empty bounding boxes confuses rest of the renderer, so
263 // let's not do that.
264 if (bbox.x0 > bbox.x1 || bbox.y0 > bbox.y1) return;
266 /* TODO: this is wrong. Should use bounding box in user coordinates
267 * and find its extents in display coordinates. */
268 Geom::Point min(bbox.x0, bbox.y0);
269 Geom::Point max(bbox.x1, bbox.y1);
270 Geom::Rect tmp_bbox(min, max);
272 Geom::Rect enlarged = filter_effect_area(tmp_bbox);
274 bbox.x0 = (NR::ICoord)enlarged.min()[X];
275 bbox.y0 = (NR::ICoord)enlarged.min()[Y];
276 bbox.x1 = (NR::ICoord)enlarged.max()[X];
277 bbox.y1 = (NR::ICoord)enlarged.max()[Y];
278 }
280 Geom::Rect Filter::filter_effect_area(Geom::Rect const &bbox)
281 {
282 Geom::Point minp, maxp;
283 double len_x = bbox.max()[X] - bbox.min()[X];
284 double len_y = bbox.max()[Y] - bbox.min()[Y];
285 /* TODO: fetch somehow the object ex and em lengths */
286 _region_x.update(12, 6, len_x);
287 _region_y.update(12, 6, len_y);
288 _region_width.update(12, 6, len_x);
289 _region_height.update(12, 6, len_y);
290 if (_filter_units == SP_FILTER_UNITS_OBJECTBOUNDINGBOX) {
291 if (_region_x.unit == SVGLength::PERCENT) {
292 minp[X] = bbox.min()[X] + _region_x.computed;
293 } else {
294 minp[X] = bbox.min()[X] + _region_x.computed * len_x;
295 }
296 if (_region_width.unit == SVGLength::PERCENT) {
297 maxp[X] = minp[X] + _region_width.computed;
298 } else {
299 maxp[X] = minp[X] + _region_width.computed * len_x;
300 }
302 if (_region_y.unit == SVGLength::PERCENT) {
303 minp[Y] = bbox.min()[Y] + _region_y.computed;
304 } else {
305 minp[Y] = bbox.min()[Y] + _region_y.computed * len_y;
306 }
307 if (_region_height.unit == SVGLength::PERCENT) {
308 maxp[Y] = minp[Y] + _region_height.computed;
309 } else {
310 maxp[Y] = minp[Y] + _region_height.computed * len_y;
311 }
312 } else if (_filter_units == SP_FILTER_UNITS_USERSPACEONUSE) {
313 /* TODO: make sure bbox and fe region are in same coordinate system */
314 minp[X] = _region_x.computed;
315 maxp[X] = minp[X] + _region_width.computed;
316 minp[Y] = _region_y.computed;
317 maxp[Y] = minp[Y] + _region_height.computed;
318 } else {
319 g_warning("Error in Inkscape::Filters::Filter::bbox_enlarge: unrecognized value of _filter_units");
320 }
321 Geom::Rect area(minp, maxp);
322 return area;
323 }
325 /* Constructor table holds pointers to static methods returning filter
326 * primitives. This table is indexed with FilterPrimitiveType, so that
327 * for example method in _constructor[NR_FILTER_GAUSSIANBLUR]
328 * returns a filter object of type Inkscape::Filters::FilterGaussian.
329 */
330 typedef FilterPrimitive*(*FilterConstructor)();
331 static FilterConstructor _constructor[NR_FILTER_ENDPRIMITIVETYPE];
333 void Filter::_create_constructor_table()
334 {
335 // Constructor table won't change in run-time, so no need to recreate
336 static bool created = false;
337 if(created) return;
339 /* Some filter classes are not implemented yet.
340 Some of them still have only boilerplate code.*/
341 _constructor[NR_FILTER_BLEND] = &FilterBlend::create;
342 _constructor[NR_FILTER_COLORMATRIX] = &FilterColorMatrix::create;
343 _constructor[NR_FILTER_COMPONENTTRANSFER] = &FilterComponentTransfer::create;
344 _constructor[NR_FILTER_COMPOSITE] = &FilterComposite::create;
345 _constructor[NR_FILTER_CONVOLVEMATRIX] = &FilterConvolveMatrix::create;
346 _constructor[NR_FILTER_DIFFUSELIGHTING] = &FilterDiffuseLighting::create;
347 _constructor[NR_FILTER_DISPLACEMENTMAP] = &FilterDisplacementMap::create;
348 _constructor[NR_FILTER_FLOOD] = &FilterFlood::create;
349 _constructor[NR_FILTER_GAUSSIANBLUR] = &FilterGaussian::create;
350 _constructor[NR_FILTER_IMAGE] = &FilterImage::create;
351 _constructor[NR_FILTER_MERGE] = &FilterMerge::create;
352 _constructor[NR_FILTER_MORPHOLOGY] = &FilterMorphology::create;
353 _constructor[NR_FILTER_OFFSET] = &FilterOffset::create;
354 _constructor[NR_FILTER_SPECULARLIGHTING] = &FilterSpecularLighting::create;
355 _constructor[NR_FILTER_TILE] = &FilterTile::create;
356 _constructor[NR_FILTER_TURBULENCE] = &FilterTurbulence::create;
357 created = true;
358 }
360 /** Helper method for enlarging table of filter primitives. When new
361 * primitives are added, but we have no space for them, this function
362 * makes some more space.
363 */
364 void Filter::_enlarge_primitive_table() {
365 FilterPrimitive **new_tbl = new FilterPrimitive*[_primitive_table_size * 2];
366 for (int i = 0 ; i < _primitive_count ; i++) {
367 new_tbl[i] = _primitive[i];
368 }
369 _primitive_table_size *= 2;
370 for (int i = _primitive_count ; i < _primitive_table_size ; i++) {
371 new_tbl[i] = NULL;
372 }
373 if(_primitive != NULL) {
374 delete[] _primitive;
375 } else {
376 g_warning("oh oh");
377 }
378 _primitive = new_tbl;
379 }
381 int Filter::add_primitive(FilterPrimitiveType type)
382 {
383 _create_constructor_table();
385 // Check that we can create a new filter of specified type
386 if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
387 return -1;
388 if (!_constructor[type]) return -1;
389 FilterPrimitive *created = _constructor[type]();
391 // If there is no space for new filter primitive, enlarge the table
392 if (_primitive_count >= _primitive_table_size) {
393 _enlarge_primitive_table();
394 }
396 _primitive[_primitive_count] = created;
397 int handle = _primitive_count;
398 _primitive_count++;
399 return handle;
400 }
402 int Filter::replace_primitive(int target, FilterPrimitiveType type)
403 {
404 _create_constructor_table();
406 // Check that target is valid primitive inside this filter
407 if (target < 0) return -1;
408 if (target >= _primitive_count) return -1;
409 if (!_primitive[target]) return -1;
411 // Check that we can create a new filter of specified type
412 if (type < 0 || type >= NR_FILTER_ENDPRIMITIVETYPE)
413 return -1;
414 if (!_constructor[type]) return -1;
415 FilterPrimitive *created = _constructor[type]();
417 // If there is no space for new filter primitive, enlarge the table
418 if (_primitive_count >= _primitive_table_size) {
419 _enlarge_primitive_table();
420 }
422 delete _primitive[target];
423 _primitive[target] = created;
424 return target;
425 }
427 FilterPrimitive *Filter::get_primitive(int handle) {
428 if (handle < 0 || handle >= _primitive_count) return NULL;
429 return _primitive[handle];
430 }
432 void Filter::clear_primitives()
433 {
434 for (int i = 0 ; i < _primitive_count ; i++) {
435 if (_primitive[i]) delete _primitive[i];
436 }
437 _primitive_count = 0;
438 }
440 void Filter::set_x(SVGLength const &length)
441 {
442 if (length._set)
443 _region_x = length;
444 }
445 void Filter::set_y(SVGLength const &length)
446 {
447 if (length._set)
448 _region_y = length;
449 }
450 void Filter::set_width(SVGLength const &length)
451 {
452 if (length._set)
453 _region_width = length;
454 }
455 void Filter::set_height(SVGLength const &length)
456 {
457 if (length._set)
458 _region_height = length;
459 }
461 void Filter::set_resolution(double const pixels) {
462 if (pixels > 0) {
463 _x_pixels = pixels;
464 _y_pixels = pixels;
465 }
466 }
468 void Filter::set_resolution(double const x_pixels, double const y_pixels) {
469 if (x_pixels >= 0 && y_pixels >= 0) {
470 _x_pixels = x_pixels;
471 _y_pixels = y_pixels;
472 }
473 }
475 void Filter::reset_resolution() {
476 _x_pixels = -1;
477 _y_pixels = -1;
478 }
480 int Filter::_resolution_limit(FilterQuality const quality) const {
481 int limit = -1;
482 switch (quality) {
483 case FILTER_QUALITY_WORST:
484 limit = 32;
485 break;
486 case FILTER_QUALITY_WORSE:
487 limit = 64;
488 break;
489 case FILTER_QUALITY_NORMAL:
490 limit = 256;
491 break;
492 case FILTER_QUALITY_BETTER:
493 case FILTER_QUALITY_BEST:
494 default:
495 break;
496 }
497 return limit;
498 }
500 std::pair<double,double> Filter::_filter_resolution(
501 Geom::Rect const &area, Geom::Matrix const &trans,
502 FilterQuality const filterquality) const
503 {
504 std::pair<double,double> resolution;
505 if (_x_pixels > 0) {
506 double y_len;
507 if (_y_pixels > 0) {
508 y_len = _y_pixels;
509 } else {
510 y_len = (_x_pixels * (area.max()[Y] - area.min()[Y]))
511 / (area.max()[X] - area.min()[X]);
512 }
513 resolution.first = _x_pixels;
514 resolution.second = y_len;
515 } else {
516 Geom::Point origo = area.min();
517 origo *= trans;
518 Geom::Point max_i(area.max()[X], area.min()[Y]);
519 max_i *= trans;
520 Geom::Point max_j(area.min()[X], area.max()[Y]);
521 max_j *= trans;
522 double i_len = sqrt((origo[X] - max_i[X]) * (origo[X] - max_i[X])
523 + (origo[Y] - max_i[Y]) * (origo[Y] - max_i[Y]));
524 double j_len = sqrt((origo[X] - max_j[X]) * (origo[X] - max_j[X])
525 + (origo[Y] - max_j[Y]) * (origo[Y] - max_j[Y]));
526 int limit = _resolution_limit(filterquality);
527 if (limit > 0 && (i_len > limit || j_len > limit)) {
528 double aspect_ratio = i_len / j_len;
529 if (i_len > j_len) {
530 i_len = limit;
531 j_len = i_len / aspect_ratio;
532 }
533 else {
534 j_len = limit;
535 i_len = j_len * aspect_ratio;
536 }
537 }
538 resolution.first = i_len;
539 resolution.second = j_len;
540 }
541 return resolution;
542 }
544 } /* namespace Filters */
545 } /* namespace Inkscape */
547 /*
548 Local Variables:
549 mode:c++
550 c-file-style:"stroustrup"
551 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
552 indent-tabs-mode:nil
553 fill-column:99
554 End:
555 */
556 // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:encoding=utf-8:textwidth=99 :