imagescript 3.7.0 → 3.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +46 -97
- package/THIRD_PARTY_NOTICES.md +101 -1
- package/dist/animation-encoder.d.ts +62 -0
- package/dist/animation-encoder.js +204 -0
- package/dist/animation.d.ts +32 -2
- package/dist/animation.js +14 -3
- package/dist/codecs/gif.js +58 -64
- package/dist/codecs/jpeg.js +54 -32
- package/dist/codecs/png.js +135 -43
- package/dist/codecs/sharpyuv.js +150 -0
- package/dist/codecs/vp8-enc-dsp.js +9 -1
- package/dist/codecs/vp8.js +21 -17
- package/dist/codecs/vp8l.js +1 -1
- package/dist/codecs/webp.js +36 -26
- package/dist/codecs/zlib.js +20 -0
- package/dist/image.d.ts +27 -3
- package/dist/image.js +54 -15
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1 -0
- package/dist/render/filter.js +939 -0
- package/dist/render/shape.js +12 -6
- package/dist/render/svg.js +1140 -36
- package/dist/render/text.js +9 -9
- package/dist/util/optimize.js +208 -62
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/render/svg.js
CHANGED
|
@@ -1,34 +1,45 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
/*!
|
|
2
|
+
* SVG renderer supporting a static subset of SVG 1.1/2:
|
|
3
|
+
* shapes, paths, transforms, nested svg/use/symbol, presentation attributes, inline styles and simple
|
|
4
|
+
* <style> sheets (type, class and id selectors), solid colors, linear and radial gradients, patterns, strokes
|
|
5
|
+
* (joins, caps, dashes), markers, opacity, clip paths, luminance masks, images in data URIs (rasters decoded by
|
|
6
|
+
* the caller, SVGs and SVGZs) and filters (all primitives, see filter.ts).
|
|
7
|
+
* Not supported: text, external images, animation and scripting.
|
|
8
|
+
* How patterns are rendered (a tile in device resolution, its filtering) and their reference cycles broken, and how
|
|
9
|
+
* images are fitted and sampled follows resvg/usvg, the markers (their placement and orientation,
|
|
10
|
+
* crates/usvg/src/parser/marker.rs) are ported from usvg (https://github.com/linebender/resvg; Copyright 2017 the
|
|
11
|
+
* Resvg Authors, MIT License, see THIRD_PARTY_NOTICES.md)
|
|
12
|
+
*/
|
|
13
|
+
import { decode as decodeUTF8, encode as encodeUTF8 } from "../util/utf8.js";
|
|
14
|
+
import { base64 } from "../util/bytes.js";
|
|
15
|
+
import { gunzip } from "../codecs/zlib.js";
|
|
16
|
+
import { applyFilter } from "./filter.js";
|
|
17
|
+
const UNSUPPORTED = new Set(['text', 'filter', 'pattern', 'marker', 'foreignObject', 'script', 'style', 'title', 'desc', 'metadata',
|
|
3
18
|
'defs', 'clipPath', 'mask', 'linearGradient', 'radialGradient', 'stop', 'symbol', 'font', 'font-face', 'animate', 'animateTransform', 'animateMotion', 'set']);
|
|
4
19
|
const INHERITED = new Set(['fill', 'fill-opacity', 'fill-rule', 'stroke', 'stroke-width', 'stroke-opacity', 'stroke-linecap', 'stroke-linejoin',
|
|
5
|
-
'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'color', 'visibility', 'clip-rule', 'font-size'
|
|
20
|
+
'stroke-miterlimit', 'stroke-dasharray', 'stroke-dashoffset', 'color', 'visibility', 'clip-rule', 'font-size', 'marker-start', 'marker-mid',
|
|
21
|
+
'marker-end', 'image-rendering', 'color-interpolation-filters']);
|
|
6
22
|
const SWITCHABLE = new Set(['svg', 'g', 'a', 'switch', 'use', 'path', 'rect', 'circle', 'ellipse', 'line', 'polyline', 'polygon', 'text', 'image', 'foreignObject']);
|
|
7
|
-
const PROPERTIES = new Set([...INHERITED, 'opacity', 'display', 'clip-path', 'mask', 'stop-color', 'stop-opacity', 'transform'
|
|
23
|
+
const PROPERTIES = new Set([...INHERITED, 'opacity', 'display', 'clip-path', 'mask', 'stop-color', 'stop-opacity', 'transform', 'filter', 'flood-color',
|
|
24
|
+
'flood-opacity', 'lighting-color']);
|
|
8
25
|
const DEFAULTS = {
|
|
9
26
|
'fill': 'black', 'fill-opacity': '1', 'fill-rule': 'nonzero', 'stroke': 'none', 'stroke-width': '1', 'stroke-opacity': '1',
|
|
10
27
|
'stroke-linecap': 'butt', 'stroke-linejoin': 'miter', 'stroke-miterlimit': '4', 'stroke-dasharray': 'none', 'stroke-dashoffset': '0',
|
|
11
28
|
'color': 'black', 'visibility': 'visible', 'clip-rule': 'nonzero', 'font-size': '16', 'opacity': '1', 'display': 'inline',
|
|
12
|
-
'stop-color': 'black', 'stop-opacity': '1'
|
|
29
|
+
'stop-color': 'black', 'stop-opacity': '1', 'marker-start': 'none', 'marker-mid': 'none', 'marker-end': 'none',
|
|
30
|
+
'image-rendering': 'auto', 'filter': 'none', 'flood-color': 'black', 'flood-opacity': '1', 'color-interpolation-filters': 'linearRGB',
|
|
31
|
+
'lighting-color': 'white'
|
|
13
32
|
};
|
|
14
33
|
const SAMPLES = 16;
|
|
15
|
-
export function render(source, mode, size) {
|
|
34
|
+
export function render(source, mode, size, images = new Map()) {
|
|
16
35
|
if (typeof source !== 'string')
|
|
17
36
|
source = decodeUTF8(source);
|
|
18
37
|
const root = parseXML(source).children.find(node => node.name === 'svg' && node.svg);
|
|
19
38
|
if (!root)
|
|
20
39
|
throw new Error('SVG: no <svg> element');
|
|
21
40
|
const doc = new Document(root);
|
|
22
|
-
|
|
23
|
-
const
|
|
24
|
-
if (value === undefined || value === 'auto')
|
|
25
|
-
return fallback;
|
|
26
|
-
if (/%\s*$/.test(value))
|
|
27
|
-
return fallback * parseFloat(value) / 100;
|
|
28
|
-
return parseLength(value, null, 16);
|
|
29
|
-
};
|
|
30
|
-
const width = lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100);
|
|
31
|
-
const height = lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100);
|
|
41
|
+
doc.images = images;
|
|
42
|
+
const { width, height } = documentSize(root);
|
|
32
43
|
if (!(width > 0) || !(height > 0))
|
|
33
44
|
throw new Error('SVG: invalid dimensions');
|
|
34
45
|
let outWidth, outHeight;
|
|
@@ -47,16 +58,103 @@ export function render(source, mode, size) {
|
|
|
47
58
|
outWidth = Math.max(1, outWidth);
|
|
48
59
|
outHeight = Math.max(1, outHeight);
|
|
49
60
|
const canvas = new Layer(outWidth, outHeight);
|
|
50
|
-
|
|
51
|
-
const rootStyle = doc.computeStyle(root, null);
|
|
52
|
-
if (rootStyle.transform)
|
|
53
|
-
matrix0 = multiply(matrix0, parseTransform(rootStyle.transform));
|
|
54
|
-
if (viewBox)
|
|
55
|
-
matrix0 = multiply(matrix0, viewBoxTransform(viewBox, width, height, root.attrs.preserveAspectRatio));
|
|
56
|
-
const viewport = viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height };
|
|
57
|
-
doc.renderNode(root, { matrix: matrix0, style: null, viewport, layer: canvas, depth: 0 }, true);
|
|
61
|
+
doc.renderRoot([outWidth / width, 0, 0, outHeight / height, 0, 0], canvas, 0);
|
|
58
62
|
return { width: outWidth, height: outHeight, pixels: canvas.toRGBA() };
|
|
59
63
|
}
|
|
64
|
+
function documentSize(root) {
|
|
65
|
+
const viewBox = parseViewBox(root.attrs.viewBox);
|
|
66
|
+
const lengthOf = (value, fallback) => {
|
|
67
|
+
if (value === undefined || value === 'auto')
|
|
68
|
+
return fallback;
|
|
69
|
+
if (/%\s*$/.test(value))
|
|
70
|
+
return fallback * parseFloat(value) / 100;
|
|
71
|
+
return parseLength(value, null, 16);
|
|
72
|
+
};
|
|
73
|
+
return { width: lengthOf(root.attrs.width, viewBox ? viewBox[2] : 100), height: lengthOf(root.attrs.height, viewBox ? viewBox[3] : 100) };
|
|
74
|
+
}
|
|
75
|
+
function premultiplied(image) {
|
|
76
|
+
if (image.premultiplied)
|
|
77
|
+
return image.premultiplied;
|
|
78
|
+
const { pixels } = image, d = new Float32Array(pixels.length);
|
|
79
|
+
for (let i = 0; i < pixels.length; i += 4) {
|
|
80
|
+
const a = pixels[i + 3] / 255;
|
|
81
|
+
d[i] = pixels[i] / 255 * a;
|
|
82
|
+
d[i + 1] = pixels[i + 1] / 255 * a;
|
|
83
|
+
d[i + 2] = pixels[i + 2] / 255 * a;
|
|
84
|
+
d[i + 3] = a;
|
|
85
|
+
}
|
|
86
|
+
return image.premultiplied = d;
|
|
87
|
+
}
|
|
88
|
+
const RASTER_TYPES = /^image\/(png|jpe?g|gif|webp)$/;
|
|
89
|
+
function dataURI(href) {
|
|
90
|
+
const m = /^\s*data:([^,]*),([\s\S]*)$/i.exec(href);
|
|
91
|
+
if (!m)
|
|
92
|
+
return null;
|
|
93
|
+
const meta = m[1].split(';').map(part => part.trim());
|
|
94
|
+
const type = (meta[0] || 'text/plain').toLowerCase();
|
|
95
|
+
try {
|
|
96
|
+
if (meta.slice(1).some(part => part.toLowerCase() === 'base64'))
|
|
97
|
+
return { type, data: base64(m[2].replace(/\s+/g, '').replace(/%([0-9a-f]{2})/gi, (_, h) => String.fromCharCode(parseInt(h, 16)))) };
|
|
98
|
+
return { type, data: encodeUTF8(decodeURIComponent(m[2])) };
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
function svgText(data) {
|
|
105
|
+
return decodeUTF8(data[0] === 0x1f && data[1] === 0x8b ? gunzip(data, 1 << 26) : data);
|
|
106
|
+
}
|
|
107
|
+
function isRaster(data) {
|
|
108
|
+
return (data[0] === 0x89 && data[1] === 0x50) || (data[0] === 0xff && data[1] === 0xd8) || (data[0] === 0x47 && data[1] === 0x49 && data[2] === 0x46)
|
|
109
|
+
|| (data[0] === 0x52 && data[1] === 0x49 && data[8] === 0x57 && data[9] === 0x45);
|
|
110
|
+
}
|
|
111
|
+
function nestedSvg(href) {
|
|
112
|
+
const uri = dataURI(href);
|
|
113
|
+
if (!uri || (uri.type !== 'image/svg+xml' && (uri.type !== 'text/plain' || isRaster(uri.data))))
|
|
114
|
+
return null;
|
|
115
|
+
try {
|
|
116
|
+
const root = parseXML(svgText(uri.data)).children.find(node => node.name === 'svg' && node.svg);
|
|
117
|
+
if (!root)
|
|
118
|
+
return null;
|
|
119
|
+
const { width, height } = documentSize(root);
|
|
120
|
+
return width > 0 && height > 0 ? { width, height, document: new Document(root) } : null;
|
|
121
|
+
}
|
|
122
|
+
catch {
|
|
123
|
+
return null;
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
export function embeddedImages(source) {
|
|
127
|
+
const found = [], seen = new Set();
|
|
128
|
+
const visit = (text, depth) => {
|
|
129
|
+
let root;
|
|
130
|
+
try {
|
|
131
|
+
root = parseXML(text());
|
|
132
|
+
}
|
|
133
|
+
catch {
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const stack = [root];
|
|
137
|
+
while (stack.length) {
|
|
138
|
+
const node = stack.pop();
|
|
139
|
+
stack.push(...node.children);
|
|
140
|
+
if ((node.name !== 'image' && node.name !== 'feImage') || !node.svg)
|
|
141
|
+
continue;
|
|
142
|
+
const href = (node.attrs.href || node.attrs['xlink:href'] || '').trim();
|
|
143
|
+
if (seen.has(href))
|
|
144
|
+
continue;
|
|
145
|
+
seen.add(href);
|
|
146
|
+
const uri = dataURI(href);
|
|
147
|
+
if (!uri)
|
|
148
|
+
continue;
|
|
149
|
+
if (RASTER_TYPES.test(uri.type) || (uri.type === 'text/plain' && isRaster(uri.data)))
|
|
150
|
+
found.push({ href, data: uri.data });
|
|
151
|
+
else if ((uri.type === 'image/svg+xml' || uri.type === 'text/plain') && depth < 8)
|
|
152
|
+
visit(() => svgText(uri.data), depth + 1);
|
|
153
|
+
}
|
|
154
|
+
};
|
|
155
|
+
visit(() => typeof source === 'string' ? source : decodeUTF8(source), 0);
|
|
156
|
+
return found;
|
|
157
|
+
}
|
|
60
158
|
const SVG_NS = 'http://www.w3.org/2000/svg';
|
|
61
159
|
function parseXML(text) {
|
|
62
160
|
const root = { name: '#root', attrs: {}, children: [], text: '', svg: false };
|
|
@@ -362,11 +460,13 @@ function validProperty(name, value) {
|
|
|
362
460
|
|| /^url\(/.test(value) || parseColor(value) !== null;
|
|
363
461
|
case 'color':
|
|
364
462
|
case 'stop-color':
|
|
463
|
+
case 'flood-color':
|
|
365
464
|
return value === 'currentColor' || value === 'inherit' || parseColor(value) !== null;
|
|
366
465
|
case 'opacity':
|
|
367
466
|
case 'fill-opacity':
|
|
368
467
|
case 'stroke-opacity':
|
|
369
468
|
case 'stop-opacity':
|
|
469
|
+
case 'flood-opacity':
|
|
370
470
|
return value === 'inherit' || parseStrictNumber(value) !== null;
|
|
371
471
|
default:
|
|
372
472
|
return true;
|
|
@@ -374,16 +474,18 @@ function validProperty(name, value) {
|
|
|
374
474
|
}
|
|
375
475
|
const MAX_INSTANCES = 100000;
|
|
376
476
|
const MAX_DASHES = 1000000;
|
|
477
|
+
const MAX_TILE = 4096 * 1024;
|
|
377
478
|
class Document {
|
|
378
|
-
instances;
|
|
479
|
+
budget = { instances: 0 };
|
|
379
480
|
ids;
|
|
380
481
|
active;
|
|
381
482
|
root;
|
|
382
483
|
rules;
|
|
484
|
+
images = new Map();
|
|
485
|
+
nested = new Map();
|
|
383
486
|
constructor(root) {
|
|
384
487
|
this.ids = new Map();
|
|
385
488
|
this.active = new Set();
|
|
386
|
-
this.instances = 0;
|
|
387
489
|
const styles = [];
|
|
388
490
|
const stack = [root];
|
|
389
491
|
while (stack.length) {
|
|
@@ -399,6 +501,59 @@ class Document {
|
|
|
399
501
|
}
|
|
400
502
|
this.root = root;
|
|
401
503
|
this.rules = parseStyleSheet(styles.join('\n'));
|
|
504
|
+
for (const name of ['fill', 'stroke'])
|
|
505
|
+
this.breakPatternCycles(name);
|
|
506
|
+
this.breakImageCycles();
|
|
507
|
+
}
|
|
508
|
+
breakImageCycles() {
|
|
509
|
+
const stack = [this.root];
|
|
510
|
+
while (stack.length) {
|
|
511
|
+
const node = stack.pop();
|
|
512
|
+
stack.push(...node.children);
|
|
513
|
+
if (node.name !== 'feImage' || !node.parent || !node.parent.attrs.id)
|
|
514
|
+
continue;
|
|
515
|
+
const href = this.href(node)?.trim(), target = href?.startsWith('#') ? this.reference(href) : null;
|
|
516
|
+
if (!target)
|
|
517
|
+
continue;
|
|
518
|
+
const inline = target.attrs.style ? parseDeclarations(target.attrs.style) : null;
|
|
519
|
+
const filter = inline?.important.filter ?? inline?.normal.filter ?? target.attrs.filter;
|
|
520
|
+
if (filter && [...filter.matchAll(/url\(\s*['"]?#([^'")\s]+)/g)].some(m => m[1] === node.parent?.attrs.id))
|
|
521
|
+
this.unpaint(target, 'filter');
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
breakPatternCycles(name) {
|
|
525
|
+
const paintOf = (node) => {
|
|
526
|
+
const inline = node.attrs.style ? parseDeclarations(node.attrs.style) : null;
|
|
527
|
+
return inline?.important[name] ?? inline?.normal[name] ?? node.attrs[name];
|
|
528
|
+
};
|
|
529
|
+
const descendants = (node) => {
|
|
530
|
+
const list = [], stack = [...node.children];
|
|
531
|
+
while (stack.length) {
|
|
532
|
+
const n = stack.shift();
|
|
533
|
+
list.push(n);
|
|
534
|
+
stack.unshift(...n.children);
|
|
535
|
+
}
|
|
536
|
+
return list;
|
|
537
|
+
};
|
|
538
|
+
const patterns = descendants(this.root).filter(node => node.name === 'pattern');
|
|
539
|
+
for (const pattern of patterns) {
|
|
540
|
+
for (const node of descendants(pattern)) {
|
|
541
|
+
const linked = this.reference(paintOf(node));
|
|
542
|
+
if (!linked)
|
|
543
|
+
continue;
|
|
544
|
+
if (linked === pattern)
|
|
545
|
+
this.unpaint(node, name);
|
|
546
|
+
else
|
|
547
|
+
for (const inner of descendants(linked))
|
|
548
|
+
if (this.reference(paintOf(inner)) === pattern)
|
|
549
|
+
this.unpaint(inner, name);
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
unpaint(node, name) {
|
|
554
|
+
node.attrs[name] = 'none';
|
|
555
|
+
if (node.attrs.style)
|
|
556
|
+
node.attrs.style += `;${name}:none !important`;
|
|
402
557
|
}
|
|
403
558
|
reference(value) {
|
|
404
559
|
if (!value)
|
|
@@ -414,9 +569,13 @@ class Document {
|
|
|
414
569
|
return node.computed;
|
|
415
570
|
const own = {};
|
|
416
571
|
const apply = (declarations) => {
|
|
417
|
-
for (const name in declarations)
|
|
418
|
-
if (
|
|
572
|
+
for (const name in declarations) {
|
|
573
|
+
if (name === 'marker')
|
|
574
|
+
for (const kind of ['marker-start', 'marker-mid', 'marker-end'])
|
|
575
|
+
own[kind] = declarations[name];
|
|
576
|
+
else if (validProperty(name, declarations[name]))
|
|
419
577
|
own[name] = declarations[name];
|
|
578
|
+
}
|
|
420
579
|
};
|
|
421
580
|
const presentation = {};
|
|
422
581
|
for (const name in node.attrs)
|
|
@@ -471,8 +630,8 @@ class Document {
|
|
|
471
630
|
renderNode(node, context, root = false) {
|
|
472
631
|
if (!node.svg || UNSUPPORTED.has(node.name) || context.depth > 32 || !this.passesConditions(node))
|
|
473
632
|
return;
|
|
474
|
-
if (context.instanced && ++this.instances > MAX_INSTANCES)
|
|
475
|
-
throw new Error(`SVG: more than ${MAX_INSTANCES} elements rendered through <use> references`);
|
|
633
|
+
if (context.instanced && ++this.budget.instances > MAX_INSTANCES)
|
|
634
|
+
throw new Error(`SVG: more than ${MAX_INSTANCES} elements rendered through <use> references or embedded SVGs`);
|
|
476
635
|
const style = this.computeStyle(node, context.style);
|
|
477
636
|
if (style.display === 'none')
|
|
478
637
|
return;
|
|
@@ -488,8 +647,11 @@ class Document {
|
|
|
488
647
|
return;
|
|
489
648
|
const clipping = clip && !this.active.has(clip);
|
|
490
649
|
const masking = mask && !this.active.has(mask);
|
|
491
|
-
const
|
|
492
|
-
|
|
650
|
+
const filters = style.filter && style.filter !== 'none' ? this.filtersOf(node, style, context.viewport) : null;
|
|
651
|
+
if (filters === 'invalid')
|
|
652
|
+
return;
|
|
653
|
+
const drawContent = (layer, contentMatrix = matrix) => {
|
|
654
|
+
const ctx = { ...context, matrix: contentMatrix, style, layer, depth: context.depth + 1 };
|
|
493
655
|
switch (node.name) {
|
|
494
656
|
case 'svg': return root ? this.renderChildren(node, ctx) : this.renderNestedSvg(node, ctx);
|
|
495
657
|
case 'g':
|
|
@@ -501,13 +663,18 @@ class Document {
|
|
|
501
663
|
return;
|
|
502
664
|
}
|
|
503
665
|
case 'use': return this.renderUse(node, ctx);
|
|
666
|
+
case 'image': return this.renderImage(node, ctx);
|
|
504
667
|
default: {
|
|
505
668
|
const path = shapePath(node, ctx.viewport, parseNumber(style['font-size'], 16));
|
|
506
|
-
if (path)
|
|
507
|
-
|
|
669
|
+
if (!path)
|
|
670
|
+
return;
|
|
671
|
+
this.paintPath(path, node, ctx);
|
|
672
|
+
if (style.visibility === 'visible')
|
|
673
|
+
this.renderMarkers(path, node, ctx);
|
|
508
674
|
}
|
|
509
675
|
}
|
|
510
676
|
};
|
|
677
|
+
const draw = filters && filters.length ? (layer) => this.filtered(filters, matrix, layer, drawContent) : (layer) => drawContent(layer);
|
|
511
678
|
if (opacity >= 1 && !clipping && !masking)
|
|
512
679
|
return draw(context.layer);
|
|
513
680
|
const layer = new Layer(context.layer.width, context.layer.height);
|
|
@@ -597,6 +764,75 @@ class Document {
|
|
|
597
764
|
target.computed = computed;
|
|
598
765
|
target.computedParent = computedParent;
|
|
599
766
|
}
|
|
767
|
+
renderImage(node, ctx) {
|
|
768
|
+
const style = ctx.style;
|
|
769
|
+
const image = this.imageOf(node, ctx.viewport);
|
|
770
|
+
if (!image || style.visibility !== 'visible')
|
|
771
|
+
return;
|
|
772
|
+
const { raster, nested, intrinsic, x, y, width, height } = image;
|
|
773
|
+
const aspect = node.attrs.preserveAspectRatio || 'xMidYMid meet';
|
|
774
|
+
const matrix = multiply(ctx.matrix, multiply([1, 0, 0, 1, x, y], viewBoxTransform([0, 0, intrinsic.width, intrinsic.height], width, height, aspect)));
|
|
775
|
+
const draw = (layer) => {
|
|
776
|
+
if (nested) {
|
|
777
|
+
nested.document.images = this.images;
|
|
778
|
+
nested.document.budget = this.budget;
|
|
779
|
+
nested.document.renderRoot(matrix, layer, ctx.depth + 1, true);
|
|
780
|
+
return;
|
|
781
|
+
}
|
|
782
|
+
const pixels = raster;
|
|
783
|
+
const inverse = invert(matrix);
|
|
784
|
+
const coverage = inverse && rasterize([transformPoints([0, 0, pixels.width, 0, pixels.width, pixels.height, 0, pixels.height], matrix)], false, layer.width, layer.height);
|
|
785
|
+
if (!coverage)
|
|
786
|
+
return;
|
|
787
|
+
const rendering = style['image-rendering'];
|
|
788
|
+
const translated = Math.abs(matrix[0] - 1) < 1e-6 && Math.abs(matrix[3] - 1) < 1e-6 && matrix[1] === 0 && matrix[2] === 0;
|
|
789
|
+
const filter = translated || /^(optimizeSpeed|crisp-edges|pixelated)$/i.test(rendering || '') ? 0 : rendering === 'smooth' ? 1 : 2;
|
|
790
|
+
layer.fill(coverage, sampler(premultiplied(pixels), pixels.width, pixels.height, inverse, false, filter, 1));
|
|
791
|
+
};
|
|
792
|
+
if (/\bslice\s*$/.test(aspect))
|
|
793
|
+
this.clipped(ctx, x, y, width, height, draw);
|
|
794
|
+
else
|
|
795
|
+
draw(ctx.layer);
|
|
796
|
+
}
|
|
797
|
+
imageOf(node, viewport) {
|
|
798
|
+
const href = this.href(node)?.trim();
|
|
799
|
+
if (!href)
|
|
800
|
+
return null;
|
|
801
|
+
const raster = this.images.get(href);
|
|
802
|
+
let nested = null;
|
|
803
|
+
if (!raster) {
|
|
804
|
+
if (!this.nested.has(href))
|
|
805
|
+
this.nested.set(href, nestedSvg(href));
|
|
806
|
+
nested = this.nested.get(href);
|
|
807
|
+
}
|
|
808
|
+
if (!raster && !nested)
|
|
809
|
+
return null;
|
|
810
|
+
const intrinsic = raster || nested;
|
|
811
|
+
const given = (name) => node.attrs[name] !== undefined && node.attrs[name].trim() !== 'auto';
|
|
812
|
+
const x = parseLength(node.attrs.x, viewport, 16, 'x'), y = parseLength(node.attrs.y, viewport, 16, 'y');
|
|
813
|
+
let width = given('width') ? parseLength(node.attrs.width, viewport, 16, 'x') : intrinsic.width;
|
|
814
|
+
let height = given('height') ? parseLength(node.attrs.height, viewport, 16, 'y') : intrinsic.height;
|
|
815
|
+
if (given('width') && !given('height'))
|
|
816
|
+
height = intrinsic.height * width / intrinsic.width;
|
|
817
|
+
else if (given('height') && !given('width'))
|
|
818
|
+
width = intrinsic.width * height / intrinsic.height;
|
|
819
|
+
if (!(width > 0) || !(height > 0))
|
|
820
|
+
return null;
|
|
821
|
+
return { raster, nested, intrinsic, x, y, width, height };
|
|
822
|
+
}
|
|
823
|
+
renderRoot(matrix, layer, depth, instanced = false) {
|
|
824
|
+
const { root } = this;
|
|
825
|
+
const viewBox = parseViewBox(root.attrs.viewBox);
|
|
826
|
+
const { width, height } = documentSize(root);
|
|
827
|
+
let matrix0 = matrix;
|
|
828
|
+
const rootStyle = this.computeStyle(root, null);
|
|
829
|
+
if (rootStyle.transform)
|
|
830
|
+
matrix0 = multiply(matrix0, parseTransform(rootStyle.transform));
|
|
831
|
+
if (viewBox)
|
|
832
|
+
matrix0 = multiply(matrix0, viewBoxTransform(viewBox, width, height, root.attrs.preserveAspectRatio));
|
|
833
|
+
const viewport = viewBox ? { width: viewBox[2], height: viewBox[3] } : { width, height };
|
|
834
|
+
this.renderNode(root, { matrix: matrix0, style: null, viewport, layer, depth, instanced }, true);
|
|
835
|
+
}
|
|
600
836
|
paintPath(path, node, ctx) {
|
|
601
837
|
const { matrix, layer } = ctx;
|
|
602
838
|
const style = ctx.style;
|
|
@@ -627,6 +863,78 @@ class Document {
|
|
|
627
863
|
layer.fill(coverage, stroke);
|
|
628
864
|
}
|
|
629
865
|
}
|
|
866
|
+
renderMarkers(path, node, ctx) {
|
|
867
|
+
const style = ctx.style;
|
|
868
|
+
for (let p = node.parent; p; p = p.parent)
|
|
869
|
+
if (p.name === 'clipPath')
|
|
870
|
+
return;
|
|
871
|
+
const kinds = ['marker-start', 'marker-mid', 'marker-end'];
|
|
872
|
+
if (kinds.every(kind => !style[kind] || style[kind] === 'none'))
|
|
873
|
+
return;
|
|
874
|
+
const segments = markerSegments(path);
|
|
875
|
+
if (segments.length < 2)
|
|
876
|
+
return;
|
|
877
|
+
for (let k = 0; k < 3; k++) {
|
|
878
|
+
const marker = this.reference(style[kinds[k]]);
|
|
879
|
+
if (!marker || marker.name !== 'marker' || this.active.has(marker))
|
|
880
|
+
continue;
|
|
881
|
+
const units = marker.attrs.markerUnits === 'userSpaceOnUse' ? 1 : parseLength(style['stroke-width'], ctx.viewport, 16, 'diagonal');
|
|
882
|
+
if (!(units > 0))
|
|
883
|
+
continue;
|
|
884
|
+
const length = (name, axis, fallback) => marker.attrs[name] === undefined ? fallback : parseLength(marker.attrs[name], ctx.viewport, 16, axis);
|
|
885
|
+
const refX = length('refX', 'x', 0), refY = length('refY', 'y', 0);
|
|
886
|
+
const width = length('markerWidth', 'x', 3), height = length('markerHeight', 'y', 3);
|
|
887
|
+
if (!(width > 0) || !(height > 0))
|
|
888
|
+
continue;
|
|
889
|
+
const viewBox = parseViewBox(marker.attrs.viewBox);
|
|
890
|
+
const viewBoxMatrix = viewBox ? viewBoxTransform(viewBox, width, height, marker.attrs.preserveAspectRatio) : [1, 0, 0, 1, 0, 0];
|
|
891
|
+
const sx = Math.hypot(viewBoxMatrix[0], viewBoxMatrix[1]), sy = Math.hypot(viewBoxMatrix[2], viewBoxMatrix[3]);
|
|
892
|
+
const inverse = invert(viewBoxMatrix);
|
|
893
|
+
if (!inverse)
|
|
894
|
+
continue;
|
|
895
|
+
const clip = /^(visible|auto)$/.test(marker.attrs.overflow?.trim() || '') ? null
|
|
896
|
+
: transformPoints([0, 0, width, height], inverse);
|
|
897
|
+
const orient = (marker.attrs.orient || '').trim();
|
|
898
|
+
const fixed = orient === 'auto' || orient === 'auto-start-reverse' ? null : parseAngle(orient);
|
|
899
|
+
const markerStyle = this.styleOf(marker);
|
|
900
|
+
const draw = (x, y, index) => {
|
|
901
|
+
let angle = fixed ?? vertexAngle(segments, index);
|
|
902
|
+
if (orient === 'auto-start-reverse' && index === 0)
|
|
903
|
+
angle = (angle + 180) % 360;
|
|
904
|
+
let matrix = multiply(ctx.matrix, [1, 0, 0, 1, x, y]);
|
|
905
|
+
if (angle) {
|
|
906
|
+
const r = angle * Math.PI / 180, cos = Math.cos(r), sin = Math.sin(r);
|
|
907
|
+
matrix = multiply(matrix, [cos, sin, -sin, cos, 0, 0]);
|
|
908
|
+
}
|
|
909
|
+
matrix = multiply(matrix, [sx * units, 0, 0, sy * units, -refX * sx * units, -refY * sy * units]);
|
|
910
|
+
const inner = { ...ctx, matrix, style: markerStyle, depth: ctx.depth + 1, viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport };
|
|
911
|
+
this.active.add(marker);
|
|
912
|
+
if (!clip)
|
|
913
|
+
this.renderChildren(marker, inner);
|
|
914
|
+
else
|
|
915
|
+
this.clipped(inner, Math.min(clip[0], clip[2]), Math.min(clip[1], clip[3]), Math.abs(clip[2] - clip[0]), Math.abs(clip[3] - clip[1]), layer => this.renderChildren(marker, { ...inner, layer }));
|
|
916
|
+
this.active.delete(marker);
|
|
917
|
+
};
|
|
918
|
+
if (k === 0) {
|
|
919
|
+
if (segments[0].type === 'M')
|
|
920
|
+
draw(segments[0].x, segments[0].y, 0);
|
|
921
|
+
}
|
|
922
|
+
else if (k === 1) {
|
|
923
|
+
for (let i = 1; i < segments.length - 1; i++)
|
|
924
|
+
if (segments[i].type !== 'Z')
|
|
925
|
+
draw(segments[i].x, segments[i].y, i);
|
|
926
|
+
}
|
|
927
|
+
else {
|
|
928
|
+
const i = segments.length - 1, last = segments[i];
|
|
929
|
+
if (last.type === 'L' || last.type === 'C')
|
|
930
|
+
draw(last.x, last.y, i);
|
|
931
|
+
else if (last.type === 'Z') {
|
|
932
|
+
const start = subpathStart(segments, i);
|
|
933
|
+
draw(start.x, start.y, i);
|
|
934
|
+
}
|
|
935
|
+
}
|
|
936
|
+
}
|
|
937
|
+
}
|
|
630
938
|
paint(value, style, bbox, matrix, opacityValue, ctx) {
|
|
631
939
|
if (!value || value === 'none')
|
|
632
940
|
return null;
|
|
@@ -640,6 +948,11 @@ class Document {
|
|
|
640
948
|
if (gradient !== undefined || !fallback)
|
|
641
949
|
return gradient || null;
|
|
642
950
|
}
|
|
951
|
+
if (server && server.name === 'pattern') {
|
|
952
|
+
const pattern = this.pattern(server, bbox, matrix, opacity, ctx);
|
|
953
|
+
if (pattern !== undefined || !fallback)
|
|
954
|
+
return pattern || null;
|
|
955
|
+
}
|
|
643
956
|
color = fallback;
|
|
644
957
|
if (!color || color === 'none')
|
|
645
958
|
return null;
|
|
@@ -767,6 +1080,500 @@ class Document {
|
|
|
767
1080
|
const c = stops[stops.length - 1].color;
|
|
768
1081
|
return solidPaint([c[0], c[1], c[2], c[3] * opacity]);
|
|
769
1082
|
}
|
|
1083
|
+
patternAttributes(node) {
|
|
1084
|
+
const attrs = {};
|
|
1085
|
+
let content = null;
|
|
1086
|
+
const names = ['x', 'y', 'width', 'height', 'patternUnits', 'patternContentUnits', 'patternTransform', 'viewBox', 'preserveAspectRatio'];
|
|
1087
|
+
for (let current = node, depth = 0; current && depth < 16 && current.name === 'pattern'; current = this.reference(this.href(current)), depth++) {
|
|
1088
|
+
for (const name of names)
|
|
1089
|
+
if (attrs[name] === undefined && current.attrs[name] !== undefined)
|
|
1090
|
+
attrs[name] = current.attrs[name];
|
|
1091
|
+
if (!content && current.children.some(child => child.svg))
|
|
1092
|
+
content = current;
|
|
1093
|
+
}
|
|
1094
|
+
return { attrs, content };
|
|
1095
|
+
}
|
|
1096
|
+
pattern(node, bbox, matrix, opacity, ctx) {
|
|
1097
|
+
if (this.active.has(node))
|
|
1098
|
+
return null;
|
|
1099
|
+
const { attrs, content } = this.patternAttributes(node);
|
|
1100
|
+
const objectBox = attrs.patternUnits !== 'userSpaceOnUse';
|
|
1101
|
+
const contentBox = attrs.patternContentUnits === 'objectBoundingBox';
|
|
1102
|
+
const viewBox = parseViewBox(attrs.viewBox);
|
|
1103
|
+
if ((objectBox || (contentBox && !viewBox)) && (!bbox || bbox.width <= 0 || bbox.height <= 0))
|
|
1104
|
+
return null;
|
|
1105
|
+
const box = bbox || { x: 0, y: 0, width: 0, height: 0 };
|
|
1106
|
+
const coordinate = (name, axis) => {
|
|
1107
|
+
const value = attrs[name];
|
|
1108
|
+
if (!objectBox)
|
|
1109
|
+
return value === undefined ? 0 : parseLength(value, ctx.viewport, 16, axis);
|
|
1110
|
+
const fraction = value === undefined ? 0 : /%\s*$/.test(value) ? parseFloat(value) / 100 : parseNumber(value, 0);
|
|
1111
|
+
return axis === 'x' ? box.x + fraction * box.width : box.y + fraction * box.height;
|
|
1112
|
+
};
|
|
1113
|
+
const tx = coordinate('x', 'x'), ty = coordinate('y', 'y');
|
|
1114
|
+
const tw = coordinate('width', 'x') - (objectBox ? box.x : 0), th = coordinate('height', 'y') - (objectBox ? box.y : 0);
|
|
1115
|
+
if (!(tw > 0) || !(th > 0) || !content)
|
|
1116
|
+
return null;
|
|
1117
|
+
let patternMatrix = matrix, rotated = matrix[1] !== 0 || matrix[2] !== 0;
|
|
1118
|
+
if (attrs.patternTransform) {
|
|
1119
|
+
const transform = parseTransform(attrs.patternTransform), transformed = multiply(patternMatrix, transform);
|
|
1120
|
+
if (invert(transformed)) {
|
|
1121
|
+
patternMatrix = transformed;
|
|
1122
|
+
rotated ||= transform[1] !== 0 || transform[2] !== 0;
|
|
1123
|
+
}
|
|
1124
|
+
}
|
|
1125
|
+
const inverse = invert(patternMatrix);
|
|
1126
|
+
if (!inverse)
|
|
1127
|
+
return null;
|
|
1128
|
+
let sx = Math.hypot(patternMatrix[0], patternMatrix[1]), sy = Math.hypot(patternMatrix[2], patternMatrix[3]);
|
|
1129
|
+
const reduce = Math.min(1, Math.sqrt(MAX_TILE / (tw * sx * th * sy)));
|
|
1130
|
+
sx *= reduce;
|
|
1131
|
+
sy *= reduce;
|
|
1132
|
+
const width = Math.max(1, Math.round(tw * sx)), height = Math.max(1, Math.round(th * sy));
|
|
1133
|
+
let contentMatrix = [sx, 0, 0, sy, 0, 0];
|
|
1134
|
+
if (viewBox)
|
|
1135
|
+
contentMatrix = multiply(contentMatrix, viewBoxTransform(viewBox, tw, th, attrs.preserveAspectRatio));
|
|
1136
|
+
else if (contentBox)
|
|
1137
|
+
contentMatrix = multiply(contentMatrix, [box.width, 0, 0, box.height, 0, 0]);
|
|
1138
|
+
const tile = new Layer(width, height);
|
|
1139
|
+
this.active.add(node);
|
|
1140
|
+
this.renderChildren(content, { ...ctx, matrix: contentMatrix, style: this.styleOf(content), layer: tile, depth: ctx.depth + 1,
|
|
1141
|
+
viewport: viewBox ? { width: viewBox[2], height: viewBox[3] } : ctx.viewport });
|
|
1142
|
+
this.active.delete(node);
|
|
1143
|
+
if (tile.x1 <= tile.x0)
|
|
1144
|
+
return null;
|
|
1145
|
+
const translated = !rotated && patternMatrix[0] > 0 && patternMatrix[3] > 0;
|
|
1146
|
+
return sampler(tile.data, width, height, multiply([sx, 0, 0, sy, -tx * sx, -ty * sy], inverse), true, translated ? 0 : 2, opacity);
|
|
1147
|
+
}
|
|
1148
|
+
filtered(filters, matrix, target, draw) {
|
|
1149
|
+
const sx = Math.hypot(matrix[0], matrix[1]), sy = Math.hypot(matrix[2], matrix[3]);
|
|
1150
|
+
if (!(sx > 0) || !(sy > 0))
|
|
1151
|
+
return;
|
|
1152
|
+
const rest = [matrix[0] / sx, matrix[1] / sx, matrix[2] / sy, matrix[3] / sy, 0, 0];
|
|
1153
|
+
const restInverse = invert(rest);
|
|
1154
|
+
if (!restInverse)
|
|
1155
|
+
return;
|
|
1156
|
+
const scaled = multiply(restInverse, matrix);
|
|
1157
|
+
let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
|
|
1158
|
+
for (const { rect } of filters) {
|
|
1159
|
+
const p = transformPoints([rect.x, rect.y, rect.x + rect.width, rect.y, rect.x + rect.width, rect.y + rect.height, rect.x, rect.y + rect.height], scaled);
|
|
1160
|
+
for (let i = 0; i < 8; i += 2) {
|
|
1161
|
+
x0 = Math.min(x0, p[i]);
|
|
1162
|
+
x1 = Math.max(x1, p[i]);
|
|
1163
|
+
y0 = Math.min(y0, p[i + 1]);
|
|
1164
|
+
y1 = Math.max(y1, p[i + 1]);
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
const canvas = transformPoints([0, 0, target.width, 0, target.width, target.height, 0, target.height], restInverse);
|
|
1168
|
+
const cx0 = Math.min(canvas[0], canvas[2], canvas[4], canvas[6]) - 2 * target.width, cy0 = Math.min(canvas[1], canvas[3], canvas[5], canvas[7]) - 2 * target.height;
|
|
1169
|
+
const cx1 = Math.max(canvas[0], canvas[2], canvas[4], canvas[6]) + 2 * target.width, cy1 = Math.max(canvas[1], canvas[3], canvas[5], canvas[7]) + 2 * target.height;
|
|
1170
|
+
let lx = Math.floor(x0), ly = Math.floor(y0);
|
|
1171
|
+
let lw = Math.max(1, Math.ceil(x1 - x0)), lh = Math.max(1, Math.ceil(y1 - y0));
|
|
1172
|
+
const left = Math.max(lx, Math.floor(cx0)), top = Math.max(ly, Math.floor(cy0));
|
|
1173
|
+
lw = Math.min(lx + lw, Math.ceil(cx1)) - left;
|
|
1174
|
+
lh = Math.min(ly + lh, Math.ceil(cy1)) - top;
|
|
1175
|
+
lx = left;
|
|
1176
|
+
ly = top;
|
|
1177
|
+
if (lw <= 0 || lh <= 0 || lw * lh > 1 << 26)
|
|
1178
|
+
return;
|
|
1179
|
+
const shifted = multiply([1, 0, 0, 1, -lx, -ly], scaled);
|
|
1180
|
+
const layer = new Layer(lw, lh);
|
|
1181
|
+
draw(layer, shifted);
|
|
1182
|
+
const pixmap = layer.toPixmap();
|
|
1183
|
+
for (const filter of filters)
|
|
1184
|
+
applyFilter(filter, shifted, pixmap);
|
|
1185
|
+
const result = Layer.fromPixmap(pixmap);
|
|
1186
|
+
if (result.x1 <= result.x0)
|
|
1187
|
+
return;
|
|
1188
|
+
if (rest[0] === 1 && rest[1] === 0 && rest[2] === 0 && rest[3] === 1) {
|
|
1189
|
+
target.blit(result, lx, ly);
|
|
1190
|
+
return;
|
|
1191
|
+
}
|
|
1192
|
+
const place = multiply(rest, [1, 0, 0, 1, lx, ly]);
|
|
1193
|
+
const inverse = invert(place);
|
|
1194
|
+
const coverage = inverse && rasterize([transformPoints([0, 0, lw, 0, lw, lh, 0, lh], place)], false, target.width, target.height);
|
|
1195
|
+
if (coverage)
|
|
1196
|
+
target.fill(coverage, sampler(result.data, lw, lh, inverse, false, 1, 1));
|
|
1197
|
+
}
|
|
1198
|
+
filtersOf(node, style, viewport) {
|
|
1199
|
+
const value = (style.filter || '').trim();
|
|
1200
|
+
const items = [...value.matchAll(/url\([^)]*\)|[a-z-]+\([^)]*\)/gi)];
|
|
1201
|
+
if (value.replace(/url\([^)]*\)|[a-z-]+\([^)]*\)/gi, '').trim())
|
|
1202
|
+
return [];
|
|
1203
|
+
const bbox = this.objectBoundingBox(node, viewport);
|
|
1204
|
+
const filters = [];
|
|
1205
|
+
let invalid = false;
|
|
1206
|
+
for (const [item] of items) {
|
|
1207
|
+
if (/^url\(/i.test(item)) {
|
|
1208
|
+
const target = this.reference(item);
|
|
1209
|
+
const filter = target && target.name === 'filter' ? this.filterOf(target, bbox, viewport) : 'invalid';
|
|
1210
|
+
if (filter === 'invalid')
|
|
1211
|
+
invalid = true;
|
|
1212
|
+
else if (filter === null)
|
|
1213
|
+
return null;
|
|
1214
|
+
else
|
|
1215
|
+
filters.push(filter);
|
|
1216
|
+
continue;
|
|
1217
|
+
}
|
|
1218
|
+
const filter = this.filterFunction(item, style, bbox, viewport);
|
|
1219
|
+
if (filter === 'invalid')
|
|
1220
|
+
return [];
|
|
1221
|
+
if (filter)
|
|
1222
|
+
filters.push(filter);
|
|
1223
|
+
}
|
|
1224
|
+
return !filters.length && invalid ? 'invalid' : filters;
|
|
1225
|
+
}
|
|
1226
|
+
objectBoundingBox(node, viewport) {
|
|
1227
|
+
const path = shapePath(node, viewport, 16);
|
|
1228
|
+
const box = path ? boundingBox(flatten(path, 0.1)) : this.groupBoundingBox(node, viewport);
|
|
1229
|
+
return box && box.width > 0 && box.height > 0 ? box : null;
|
|
1230
|
+
}
|
|
1231
|
+
filterOf(node, bbox, viewport) {
|
|
1232
|
+
const attribute = (name) => {
|
|
1233
|
+
for (let current = node, depth = 0; current && current.name === 'filter' && depth < 16; current = this.reference(this.href(current)), depth++)
|
|
1234
|
+
if (current.attrs[name] !== undefined)
|
|
1235
|
+
return current.attrs[name];
|
|
1236
|
+
return undefined;
|
|
1237
|
+
};
|
|
1238
|
+
const objectBox = attribute('filterUnits') !== 'userSpaceOnUse';
|
|
1239
|
+
const primitiveBox = attribute('primitiveUnits') === 'objectBoundingBox';
|
|
1240
|
+
const length = (n, name, axis, box) => {
|
|
1241
|
+
const v = n === node ? attribute(name) : n.attrs[name];
|
|
1242
|
+
if (v === undefined)
|
|
1243
|
+
return null;
|
|
1244
|
+
if (box)
|
|
1245
|
+
return /%\s*$/.test(v) ? parseFloat(v) / 100 : parseNumber(v, NaN);
|
|
1246
|
+
return parseLength(v, viewport, 16, axis);
|
|
1247
|
+
};
|
|
1248
|
+
let rect = {
|
|
1249
|
+
x: length(node, 'x', 'x', objectBox) ?? (objectBox ? -0.1 : -0.1 * viewport.width),
|
|
1250
|
+
y: length(node, 'y', 'y', objectBox) ?? (objectBox ? -0.1 : -0.1 * viewport.height),
|
|
1251
|
+
width: length(node, 'width', 'x', objectBox) ?? (objectBox ? 1.2 : 1.2 * viewport.width),
|
|
1252
|
+
height: length(node, 'height', 'y', objectBox) ?? (objectBox ? 1.2 : 1.2 * viewport.height)
|
|
1253
|
+
};
|
|
1254
|
+
if (!(rect.width > 0) || !(rect.height > 0))
|
|
1255
|
+
return 'invalid';
|
|
1256
|
+
if (objectBox) {
|
|
1257
|
+
if (!bbox)
|
|
1258
|
+
return 'invalid';
|
|
1259
|
+
rect = { x: bbox.x + rect.x * bbox.width, y: bbox.y + rect.y * bbox.height, width: rect.width * bbox.width, height: rect.height * bbox.height };
|
|
1260
|
+
}
|
|
1261
|
+
let holder = null;
|
|
1262
|
+
for (let current = node, depth = 0; current && depth < 16; current = this.reference(this.href(current)), depth++) {
|
|
1263
|
+
if (current.name !== 'filter')
|
|
1264
|
+
return 'invalid';
|
|
1265
|
+
if (current.children.some(child => child.svg)) {
|
|
1266
|
+
holder = current;
|
|
1267
|
+
break;
|
|
1268
|
+
}
|
|
1269
|
+
}
|
|
1270
|
+
if (!holder)
|
|
1271
|
+
return 'invalid';
|
|
1272
|
+
if (primitiveBox && !bbox)
|
|
1273
|
+
return 'invalid';
|
|
1274
|
+
const scale = primitiveBox && bbox ? [bbox.width, bbox.height] : [1, 1];
|
|
1275
|
+
const primitives = [];
|
|
1276
|
+
const names = new Set();
|
|
1277
|
+
let index = 1;
|
|
1278
|
+
for (const child of holder.children) {
|
|
1279
|
+
if (!child.svg)
|
|
1280
|
+
continue;
|
|
1281
|
+
const fx = length(child, 'x', 'x', primitiveBox), fy = length(child, 'y', 'y', primitiveBox);
|
|
1282
|
+
const fw = length(child, 'width', 'x', primitiveBox), fh = length(child, 'height', 'y', primitiveBox);
|
|
1283
|
+
let region;
|
|
1284
|
+
if ((child.name === 'feFlood' || child.name === 'feImage') && primitiveBox && bbox) {
|
|
1285
|
+
region = { x: bbox.x + (fx ?? 0) * bbox.width, y: bbox.y + (fy ?? 0) * bbox.height, width: (fw ?? 1) * bbox.width, height: (fh ?? 1) * bbox.height };
|
|
1286
|
+
}
|
|
1287
|
+
else if (primitiveBox) {
|
|
1288
|
+
region = { x: rect.x + (fx ?? 0) * rect.width, y: rect.y + (fy ?? 0) * rect.height, width: (fw ?? 1) * rect.width, height: (fh ?? 1) * rect.height };
|
|
1289
|
+
}
|
|
1290
|
+
else
|
|
1291
|
+
region = { x: fx ?? rect.x, y: fy ?? rect.y, width: fw ?? rect.width, height: fh ?? rect.height };
|
|
1292
|
+
if (!(region.width > 0) || !(region.height > 0))
|
|
1293
|
+
break;
|
|
1294
|
+
const kind = this.primitiveKind(child, scale, primitives, region, viewport);
|
|
1295
|
+
if (kind === undefined)
|
|
1296
|
+
continue;
|
|
1297
|
+
if (kind === null)
|
|
1298
|
+
return null;
|
|
1299
|
+
let result = child.attrs.result;
|
|
1300
|
+
if (result !== undefined) {
|
|
1301
|
+
names.add(result);
|
|
1302
|
+
index++;
|
|
1303
|
+
}
|
|
1304
|
+
else {
|
|
1305
|
+
do
|
|
1306
|
+
result = `result${index++}`;
|
|
1307
|
+
while (names.has(result));
|
|
1308
|
+
}
|
|
1309
|
+
const interpolation = this.styleOf(child)['color-interpolation-filters'];
|
|
1310
|
+
primitives.push({ rect: region, linear: interpolation !== 'sRGB', result, kind });
|
|
1311
|
+
}
|
|
1312
|
+
return primitives.length ? { rect, primitives } : 'invalid';
|
|
1313
|
+
}
|
|
1314
|
+
primitiveKind(node, scale, primitives, region, viewport) {
|
|
1315
|
+
const input = (name) => {
|
|
1316
|
+
const value = node.attrs[name]?.trim();
|
|
1317
|
+
const previous = primitives.length ? { result: primitives[primitives.length - 1].result } : 'SourceGraphic';
|
|
1318
|
+
if (value === undefined)
|
|
1319
|
+
return previous;
|
|
1320
|
+
if (value === 'SourceGraphic' || value === 'SourceAlpha')
|
|
1321
|
+
return value;
|
|
1322
|
+
if (/^(BackgroundImage|BackgroundAlpha|FillPaint|StrokePaint)$/.test(value))
|
|
1323
|
+
return 'SourceGraphic';
|
|
1324
|
+
return primitives.some(p => p.result === value) ? { result: value } : previous;
|
|
1325
|
+
};
|
|
1326
|
+
const number = (name, fallback) => parsePlainNumber(node.attrs[name]) ?? fallback;
|
|
1327
|
+
const deviation = (fallback) => {
|
|
1328
|
+
const list = parseNumberList(node.attrs.stdDeviation ?? fallback);
|
|
1329
|
+
const [x, y] = list.length === 1 ? [list[0], list[0]] : list.length === 2 ? list : [0, 0];
|
|
1330
|
+
return [Math.max(0, x * scale[0]) || 0, Math.max(0, y * scale[1]) || 0];
|
|
1331
|
+
};
|
|
1332
|
+
const flood = () => {
|
|
1333
|
+
const style = this.styleOf(node);
|
|
1334
|
+
const c = parseColor(style['flood-color'] === 'currentColor' ? style.color : style['flood-color']) || [0, 0, 0, 1];
|
|
1335
|
+
return { color: [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)], opacity: c[3] * clamp01(parseNumber(style['flood-opacity'], 1)) };
|
|
1336
|
+
};
|
|
1337
|
+
switch (node.name) {
|
|
1338
|
+
case 'feGaussianBlur': {
|
|
1339
|
+
const [sx, sy] = deviation('0 0');
|
|
1340
|
+
return { type: 'blur', input: input('in'), sx, sy };
|
|
1341
|
+
}
|
|
1342
|
+
case 'feOffset':
|
|
1343
|
+
return { type: 'offset', input: input('in'), dx: number('dx', 0) * scale[0], dy: number('dy', 0) * scale[1] };
|
|
1344
|
+
case 'feFlood':
|
|
1345
|
+
return { type: 'flood', ...flood() };
|
|
1346
|
+
case 'feComposite': {
|
|
1347
|
+
const operator = /^(in|out|atop|xor|lighter|arithmetic)$/.test(node.attrs.operator?.trim() || '') ? node.attrs.operator.trim() : 'over';
|
|
1348
|
+
return { type: 'composite', operator, k: ['k1', 'k2', 'k3', 'k4'].map(k => number(k, 0)), input: input('in'), input2: input('in2') };
|
|
1349
|
+
}
|
|
1350
|
+
case 'feMerge':
|
|
1351
|
+
return { type: 'merge', inputs: node.children.filter(child => child.svg).map(child => this.mergeInput(child, primitives)) };
|
|
1352
|
+
case 'feDropShadow': {
|
|
1353
|
+
const [sx, sy] = deviation('2 2');
|
|
1354
|
+
return { type: 'dropShadow', input: input('in'), dx: number('dx', 2) * scale[0], dy: number('dy', 2) * scale[1], sx, sy, ...flood() };
|
|
1355
|
+
}
|
|
1356
|
+
case 'feColorMatrix':
|
|
1357
|
+
return { type: 'colorMatrix', input: input('in'), matrix: colorMatrixOf(node) };
|
|
1358
|
+
case 'feComponentTransfer': {
|
|
1359
|
+
const functions = [null, null, null, null];
|
|
1360
|
+
for (const child of node.children) {
|
|
1361
|
+
const k = ['feFuncR', 'feFuncG', 'feFuncB', 'feFuncA'].indexOf(child.name);
|
|
1362
|
+
if (k >= 0 && child.svg)
|
|
1363
|
+
functions[k] = transferOf(child, functions[k]);
|
|
1364
|
+
}
|
|
1365
|
+
return { type: 'componentTransfer', input: input('in'), functions };
|
|
1366
|
+
}
|
|
1367
|
+
case 'feTile':
|
|
1368
|
+
return { type: 'tile', input: input('in') };
|
|
1369
|
+
case 'feConvolveMatrix': {
|
|
1370
|
+
const convolution = convolutionOf(node);
|
|
1371
|
+
return convolution ? { type: 'convolve', input: input('in'), ...convolution } : { type: 'flood', color: [0, 0, 0], opacity: 0 };
|
|
1372
|
+
}
|
|
1373
|
+
case 'feBlend': {
|
|
1374
|
+
const mode = node.attrs.mode?.trim() || 'normal';
|
|
1375
|
+
const modes = /^(normal|multiply|screen|overlay|darken|lighten|color-dodge|color-burn|hard-light|soft-light|difference|exclusion|hue|saturation|color|luminosity)$/;
|
|
1376
|
+
return { type: 'blend', mode: modes.test(mode) ? mode : 'normal', input: input('in'), input2: input('in2') };
|
|
1377
|
+
}
|
|
1378
|
+
case 'feMorphology': {
|
|
1379
|
+
let rx = scale[0], ry = scale[1];
|
|
1380
|
+
const list = node.attrs.radius === undefined ? null : parseStrictNumberList(node.attrs.radius);
|
|
1381
|
+
if (list) {
|
|
1382
|
+
let [x, y] = list.length === 2 ? list : list.length === 1 ? [list[0], list[0]] : [0, 0];
|
|
1383
|
+
if (x === 0 && y === 0)
|
|
1384
|
+
x = y = 1;
|
|
1385
|
+
if (x === 0)
|
|
1386
|
+
x = 1;
|
|
1387
|
+
if (y === 0)
|
|
1388
|
+
y = 1;
|
|
1389
|
+
if (x >= 0 && y >= 0) {
|
|
1390
|
+
rx = x * scale[0];
|
|
1391
|
+
ry = y * scale[1];
|
|
1392
|
+
}
|
|
1393
|
+
}
|
|
1394
|
+
return { type: 'morphology', dilate: node.attrs.operator?.trim() === 'dilate', rx, ry, input: input('in') };
|
|
1395
|
+
}
|
|
1396
|
+
case 'feTurbulence': {
|
|
1397
|
+
const list = node.attrs.baseFrequency === undefined ? null : parseStrictNumberList(node.attrs.baseFrequency);
|
|
1398
|
+
let [fx, fy] = list && list.length === 2 ? list : list && list.length === 1 ? [list[0], list[0]] : [0, 0];
|
|
1399
|
+
if (!(fx >= 0 && fy >= 0))
|
|
1400
|
+
fx = fy = 0;
|
|
1401
|
+
const octaves = Math.max(0, number('numOctaves', 1));
|
|
1402
|
+
return { type: 'turbulence', fx, fy, octaves: Math.round(octaves), seed: Math.trunc(number('seed', 0)), stitch: node.attrs.stitchTiles?.trim() === 'stitch',
|
|
1403
|
+
fractal: node.attrs.type?.trim() === 'fractalNoise' };
|
|
1404
|
+
}
|
|
1405
|
+
case 'feDiffuseLighting':
|
|
1406
|
+
case 'feSpecularLighting': {
|
|
1407
|
+
const transparent = { type: 'flood', color: [0, 0, 0], opacity: 0 };
|
|
1408
|
+
const source = node.children.find(child => child.svg && /^fe(Distant|Point|Spot)Light$/.test(child.name));
|
|
1409
|
+
const specular = node.name === 'feSpecularLighting', exponent = number('specularExponent', 1);
|
|
1410
|
+
if (!source || (specular && !(exponent >= 1 && exponent <= 128)))
|
|
1411
|
+
return transparent;
|
|
1412
|
+
const at = (name) => parsePlainNumber(source.attrs[name]) ?? 0;
|
|
1413
|
+
let light;
|
|
1414
|
+
if (source.name === 'feDistantLight')
|
|
1415
|
+
light = { type: 'distant', azimuth: at('azimuth'), elevation: at('elevation') };
|
|
1416
|
+
else if (source.name === 'fePointLight')
|
|
1417
|
+
light = { type: 'point', x: at('x'), y: at('y'), z: at('z') };
|
|
1418
|
+
else {
|
|
1419
|
+
const e = parsePlainNumber(source.attrs.specularExponent);
|
|
1420
|
+
light = { type: 'spot', x: at('x'), y: at('y'), z: at('z'), atX: at('pointsAtX'), atY: at('pointsAtY'), atZ: at('pointsAtZ'),
|
|
1421
|
+
exponent: e !== null && e > 0 ? e : 1, cone: parsePlainNumber(source.attrs.limitingConeAngle) };
|
|
1422
|
+
}
|
|
1423
|
+
const style = this.styleOf(node), value = style['lighting-color'];
|
|
1424
|
+
const c = (value === 'currentColor' ? parseColor(style.color) : parseColor(value)) || [1, 1, 1, 1];
|
|
1425
|
+
return { type: 'lighting', specular, input: input('in'), surfaceScale: number('surfaceScale', 1),
|
|
1426
|
+
constant: number(specular ? 'specularConstant' : 'diffuseConstant', 1), exponent, color: [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)], light };
|
|
1427
|
+
}
|
|
1428
|
+
case 'feImage':
|
|
1429
|
+
return this.feImage(node, region, viewport);
|
|
1430
|
+
case 'feDisplacementMap': {
|
|
1431
|
+
const channel = (name) => {
|
|
1432
|
+
const index = ['R', 'G', 'B'].indexOf(node.attrs[name]?.trim() ?? '');
|
|
1433
|
+
return index < 0 ? 3 : index;
|
|
1434
|
+
};
|
|
1435
|
+
return { type: 'displacement', input: input('in'), input2: input('in2'), scale: number('scale', 0) * (scale[0] + scale[1]) / 2,
|
|
1436
|
+
xChannel: channel('xChannelSelector'), yChannel: channel('yChannelSelector') };
|
|
1437
|
+
}
|
|
1438
|
+
default:
|
|
1439
|
+
return undefined;
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
feImage(node, region, viewport) {
|
|
1443
|
+
const href = this.href(node)?.trim();
|
|
1444
|
+
const target = href && href.startsWith('#') ? this.reference(href) : null;
|
|
1445
|
+
const transparent = { type: 'flood', color: [0, 0, 0], opacity: 0 };
|
|
1446
|
+
if (!href)
|
|
1447
|
+
return transparent;
|
|
1448
|
+
if (this.active.has(node))
|
|
1449
|
+
return null;
|
|
1450
|
+
if (href.startsWith('#') && (!target || !SWITCHABLE.has(target.name) && target.name !== 'g'))
|
|
1451
|
+
return transparent;
|
|
1452
|
+
const image = target ? null : { name: 'image', svg: true, text: '', children: [], parent: node.parent,
|
|
1453
|
+
attrs: { href, x: '0', y: '0', width: String(region.width), height: String(region.height), preserveAspectRatio: node.attrs.preserveAspectRatio || 'xMidYMid meet' } };
|
|
1454
|
+
if (image && !this.imageOf(image, viewport))
|
|
1455
|
+
return transparent;
|
|
1456
|
+
return {
|
|
1457
|
+
type: 'image',
|
|
1458
|
+
draw: (matrix, width, height) => {
|
|
1459
|
+
const layer = new Layer(width, height);
|
|
1460
|
+
this.active.add(node);
|
|
1461
|
+
const parentStyle = (target || node).parent && (target || node).parent.name !== '#root' ? this.styleOf((target || node).parent) : null;
|
|
1462
|
+
const ctx = { matrix, style: parentStyle, viewport, layer, depth: 16 };
|
|
1463
|
+
if (target)
|
|
1464
|
+
this.renderNode(target, ctx);
|
|
1465
|
+
else
|
|
1466
|
+
this.renderImage(image, { ...ctx, style: this.computeStyle(image, this.styleOf(node)) });
|
|
1467
|
+
this.active.delete(node);
|
|
1468
|
+
return layer.toPixmap();
|
|
1469
|
+
}
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
mergeInput(node, primitives) {
|
|
1473
|
+
const value = node.attrs.in?.trim();
|
|
1474
|
+
const previous = primitives.length ? { result: primitives[primitives.length - 1].result } : 'SourceGraphic';
|
|
1475
|
+
if (value === undefined)
|
|
1476
|
+
return previous;
|
|
1477
|
+
if (value === 'SourceGraphic' || value === 'SourceAlpha')
|
|
1478
|
+
return value;
|
|
1479
|
+
if (/^(BackgroundImage|BackgroundAlpha|FillPaint|StrokePaint)$/.test(value))
|
|
1480
|
+
return 'SourceGraphic';
|
|
1481
|
+
return primitives.some(p => p.result === value) ? { result: value } : previous;
|
|
1482
|
+
}
|
|
1483
|
+
filterFunction(item, style, bbox, viewport) {
|
|
1484
|
+
const m = /^([a-z-]+)\(([^)]*)\)$/i.exec(item);
|
|
1485
|
+
if (!m)
|
|
1486
|
+
return 'invalid';
|
|
1487
|
+
const name = m[1].toLowerCase(), args = m[2].trim();
|
|
1488
|
+
const amount = (fallback) => {
|
|
1489
|
+
if (!args)
|
|
1490
|
+
return fallback;
|
|
1491
|
+
const v = /%$/.test(args) ? parseStrictNumber(args.slice(0, -1)) : parseStrictNumber(args);
|
|
1492
|
+
if (v === null || v < 0)
|
|
1493
|
+
return null;
|
|
1494
|
+
return /%$/.test(args) ? v / 100 : v;
|
|
1495
|
+
};
|
|
1496
|
+
const fontSize = parseNumber(style['font-size'], 16);
|
|
1497
|
+
const length = (v) => /%$/.test(v) ? NaN : parseLength(v, viewport, fontSize, 'x');
|
|
1498
|
+
let kind;
|
|
1499
|
+
if (name === 'blur') {
|
|
1500
|
+
const d = args ? length(args) : 0;
|
|
1501
|
+
if (!(d >= 0))
|
|
1502
|
+
return 'invalid';
|
|
1503
|
+
kind = { type: 'blur', input: 'SourceGraphic', sx: d, sy: d };
|
|
1504
|
+
}
|
|
1505
|
+
else if (name === 'drop-shadow') {
|
|
1506
|
+
if (args.includes(',') && !/\([^)]*,/.test(args))
|
|
1507
|
+
return 'invalid';
|
|
1508
|
+
const parts = args.match(/[a-z]+\([^)]*\)|#[0-9a-f]+|[^\s]+/gi) || [];
|
|
1509
|
+
const lengths = [];
|
|
1510
|
+
let color = null;
|
|
1511
|
+
for (const part of parts) {
|
|
1512
|
+
const c = part === 'currentColor' ? parseColor(style.color) : parseColor(part);
|
|
1513
|
+
if (c && !/^[+-]?[\d.]/.test(part))
|
|
1514
|
+
color = c;
|
|
1515
|
+
else
|
|
1516
|
+
lengths.push(length(part));
|
|
1517
|
+
}
|
|
1518
|
+
if (lengths.length < 2 || lengths.length > 3 || lengths.some(l => !isFinite(l)))
|
|
1519
|
+
return 'invalid';
|
|
1520
|
+
const c = color || parseColor(style.color) || [0, 0, 0, 1];
|
|
1521
|
+
kind = { type: 'dropShadow', input: 'SourceGraphic', dx: lengths[0], dy: lengths[1], sx: Math.max(0, lengths[2] || 0), sy: Math.max(0, lengths[2] || 0),
|
|
1522
|
+
color: [Math.round(c[0] * 255), Math.round(c[1] * 255), Math.round(c[2] * 255)], opacity: c[3] };
|
|
1523
|
+
}
|
|
1524
|
+
else if (name === 'hue-rotate') {
|
|
1525
|
+
const angle = args ? parseAngleStrict(args) : 0;
|
|
1526
|
+
if (angle === null)
|
|
1527
|
+
return 'invalid';
|
|
1528
|
+
kind = { type: 'colorMatrix', input: 'SourceGraphic', matrix: { type: 'hueRotate', angle } };
|
|
1529
|
+
}
|
|
1530
|
+
else {
|
|
1531
|
+
const a = amount(1);
|
|
1532
|
+
if (a === null)
|
|
1533
|
+
return 'invalid';
|
|
1534
|
+
const one = Math.min(a, 1), inv = 1 - one;
|
|
1535
|
+
switch (name) {
|
|
1536
|
+
case 'grayscale':
|
|
1537
|
+
kind = { type: 'colorMatrix', input: 'SourceGraphic', matrix: { type: 'matrix', values: [0.2126 + 0.7874 * inv, 0.7152 - 0.7152 * inv, 0.0722 - 0.0722 * inv, 0, 0,
|
|
1538
|
+
0.2126 - 0.2126 * inv, 0.7152 + 0.2848 * inv, 0.0722 - 0.0722 * inv, 0, 0, 0.2126 - 0.2126 * inv, 0.7152 - 0.7152 * inv, 0.0722 + 0.9278 * inv, 0, 0,
|
|
1539
|
+
0, 0, 0, 1, 0] } };
|
|
1540
|
+
break;
|
|
1541
|
+
case 'sepia':
|
|
1542
|
+
kind = { type: 'colorMatrix', input: 'SourceGraphic', matrix: { type: 'matrix', values: [0.393 + 0.607 * inv, 0.769 - 0.769 * inv, 0.189 - 0.189 * inv, 0, 0,
|
|
1543
|
+
0.349 - 0.349 * inv, 0.686 + 0.314 * inv, 0.168 - 0.168 * inv, 0, 0, 0.272 - 0.272 * inv, 0.534 - 0.534 * inv, 0.131 + 0.869 * inv, 0, 0,
|
|
1544
|
+
0, 0, 0, 1, 0] } };
|
|
1545
|
+
break;
|
|
1546
|
+
case 'saturate':
|
|
1547
|
+
kind = { type: 'colorMatrix', input: 'SourceGraphic', matrix: { type: 'saturate', value: a } };
|
|
1548
|
+
break;
|
|
1549
|
+
case 'invert': {
|
|
1550
|
+
const table = { type: 'table', values: [one, 1 - one] };
|
|
1551
|
+
kind = { type: 'componentTransfer', input: 'SourceGraphic', functions: [table, table, table, null] };
|
|
1552
|
+
break;
|
|
1553
|
+
}
|
|
1554
|
+
case 'opacity':
|
|
1555
|
+
kind = { type: 'componentTransfer', input: 'SourceGraphic', functions: [null, null, null, { type: 'table', values: [0, one] }] };
|
|
1556
|
+
break;
|
|
1557
|
+
case 'brightness': {
|
|
1558
|
+
const linear = { type: 'linear', slope: a, intercept: 0 };
|
|
1559
|
+
kind = { type: 'componentTransfer', input: 'SourceGraphic', functions: [linear, linear, linear, null] };
|
|
1560
|
+
break;
|
|
1561
|
+
}
|
|
1562
|
+
case 'contrast': {
|
|
1563
|
+
const linear = { type: 'linear', slope: a, intercept: -0.5 * a + 0.5 };
|
|
1564
|
+
kind = { type: 'componentTransfer', input: 'SourceGraphic', functions: [linear, linear, linear, null] };
|
|
1565
|
+
break;
|
|
1566
|
+
}
|
|
1567
|
+
default:
|
|
1568
|
+
return 'invalid';
|
|
1569
|
+
}
|
|
1570
|
+
}
|
|
1571
|
+
if (!bbox)
|
|
1572
|
+
return null;
|
|
1573
|
+
const f = kind.type === 'dropShadow' || kind.type === 'blur' ? [-0.5, 2] : [-0.1, 1.2];
|
|
1574
|
+
const rect = { x: bbox.x + f[0] * bbox.width, y: bbox.y + f[0] * bbox.height, width: f[1] * bbox.width, height: f[1] * bbox.height };
|
|
1575
|
+
return { rect, primitives: [{ rect, linear: false, result: 'result', kind }] };
|
|
1576
|
+
}
|
|
770
1577
|
clipMask(clip, node, matrix, context) {
|
|
771
1578
|
const { width, height } = context.layer;
|
|
772
1579
|
const alpha = new Float32Array(width * height);
|
|
@@ -834,7 +1641,9 @@ class Document {
|
|
|
834
1641
|
groupBoundingBox(node, viewport) {
|
|
835
1642
|
let box = null;
|
|
836
1643
|
const visit = (n, matrix) => {
|
|
837
|
-
const
|
|
1644
|
+
const image = n.name === 'image' ? this.imageOf(n, viewport) : null;
|
|
1645
|
+
const path = image ? [['M', image.x, image.y], ['L', image.x + image.width, image.y], ['L', image.x + image.width, image.y + image.height],
|
|
1646
|
+
['L', image.x, image.y + image.height], ['Z']] : shapePath(n, viewport, 16);
|
|
838
1647
|
if (path) {
|
|
839
1648
|
const points = flatten(path, 0.1).map(p => transformPoints(p.points, matrix));
|
|
840
1649
|
const b = boundingBox(points.map(p => ({ points: p })));
|
|
@@ -910,7 +1719,264 @@ class Document {
|
|
|
910
1719
|
return values;
|
|
911
1720
|
}
|
|
912
1721
|
}
|
|
1722
|
+
function markerSegments(path) {
|
|
1723
|
+
const segments = [];
|
|
1724
|
+
let mx = 0, my = 0;
|
|
1725
|
+
const push = (type, x, y, x1 = 0, y1 = 0, x2 = 0, y2 = 0) => {
|
|
1726
|
+
segments.push({ type, x, y, x1, y1, x2, y2 });
|
|
1727
|
+
};
|
|
1728
|
+
for (const [command, ...v] of path) {
|
|
1729
|
+
const last = segments[segments.length - 1];
|
|
1730
|
+
if (command === 'M') {
|
|
1731
|
+
if (last && last.type === 'M')
|
|
1732
|
+
segments.pop();
|
|
1733
|
+
push('M', mx = v[0], my = v[1]);
|
|
1734
|
+
}
|
|
1735
|
+
else if (command === 'Z') {
|
|
1736
|
+
if (last && last.type !== 'Z' && last.type !== 'M')
|
|
1737
|
+
push('Z', mx, my);
|
|
1738
|
+
}
|
|
1739
|
+
else {
|
|
1740
|
+
if (!last || last.type === 'Z')
|
|
1741
|
+
push('M', mx, my);
|
|
1742
|
+
if (command === 'L')
|
|
1743
|
+
push('L', v[0], v[1]);
|
|
1744
|
+
else
|
|
1745
|
+
push('C', v[4], v[5], v[0], v[1], v[2], v[3]);
|
|
1746
|
+
}
|
|
1747
|
+
}
|
|
1748
|
+
if (segments.length && segments[segments.length - 1].type === 'M')
|
|
1749
|
+
segments.pop();
|
|
1750
|
+
return segments;
|
|
1751
|
+
}
|
|
1752
|
+
function subpathStart(segments, index) {
|
|
1753
|
+
for (let i = index - 1; i >= 0; i--)
|
|
1754
|
+
if (segments[i].type === 'M')
|
|
1755
|
+
return segments[i];
|
|
1756
|
+
return { type: 'M', x: 0, y: 0, x1: 0, y1: 0, x2: 0, y2: 0 };
|
|
1757
|
+
}
|
|
1758
|
+
function previousVertex(segments, index) {
|
|
1759
|
+
const previous = segments[index - 1];
|
|
1760
|
+
return previous.type === 'Z' ? subpathStart(segments, index) : previous;
|
|
1761
|
+
}
|
|
1762
|
+
function near(a, b) {
|
|
1763
|
+
return Math.abs(a - b) <= 4 * 1.1920929e-7 * Math.max(Math.abs(a), Math.abs(b));
|
|
1764
|
+
}
|
|
1765
|
+
function normalizeAngle(rad) {
|
|
1766
|
+
const v = rad % (Math.PI * 2);
|
|
1767
|
+
return v < 0 ? v + Math.PI * 2 : v;
|
|
1768
|
+
}
|
|
1769
|
+
function bisector(x1, y1, x2, y2, x3, y3, x4, y4) {
|
|
1770
|
+
const incoming = normalizeAngle(Math.atan2(y2 - y1, x2 - x1)), outgoing = normalizeAngle(Math.atan2(y4 - y3, x4 - x3));
|
|
1771
|
+
const d = (outgoing - incoming) / 2;
|
|
1772
|
+
let angle = incoming + d;
|
|
1773
|
+
if (Math.abs(d) > Math.PI / 2)
|
|
1774
|
+
angle -= Math.PI;
|
|
1775
|
+
return normalizeAngle(angle) * 180 / Math.PI;
|
|
1776
|
+
}
|
|
1777
|
+
function lineAngle(x1, y1, x2, y2) {
|
|
1778
|
+
return bisector(x1, y1, x2, y2, x1, y1, x2, y2);
|
|
1779
|
+
}
|
|
1780
|
+
function curvesAngle(px, py, cx1, cy1, x, y, cx2, cy2, nx, ny) {
|
|
1781
|
+
if (near(cx1, x) && near(cy1, y))
|
|
1782
|
+
return bisector(px, py, x, y, x, y, cx2, cy2);
|
|
1783
|
+
if (near(x, cx2) && near(y, cy2))
|
|
1784
|
+
return bisector(cx1, cy1, x, y, x, y, nx, ny);
|
|
1785
|
+
return bisector(cx1, cy1, x, y, x, y, cx2, cy2);
|
|
1786
|
+
}
|
|
1787
|
+
function vertexAngle(segments, index) {
|
|
1788
|
+
if (index === 0) {
|
|
1789
|
+
const [m, s] = segments;
|
|
1790
|
+
if (m.type !== 'M')
|
|
1791
|
+
return 0;
|
|
1792
|
+
if (s.type === 'L')
|
|
1793
|
+
return lineAngle(m.x, m.y, s.x, s.y);
|
|
1794
|
+
if (s.type === 'C')
|
|
1795
|
+
return near(m.x, s.x1) && near(m.y, s.y1) ? lineAngle(m.x, m.y, s.x, s.y) : lineAngle(m.x, m.y, s.x1, s.y1);
|
|
1796
|
+
return 0;
|
|
1797
|
+
}
|
|
1798
|
+
if (index === segments.length - 1) {
|
|
1799
|
+
const a = segments[index - 1], b = segments[index];
|
|
1800
|
+
if (b.type === 'L') {
|
|
1801
|
+
const prev = previousVertex(segments, index);
|
|
1802
|
+
return lineAngle(prev.x, prev.y, b.x, b.y);
|
|
1803
|
+
}
|
|
1804
|
+
if (b.type === 'C')
|
|
1805
|
+
return near(b.x2, b.x) && near(b.y2, b.y) ? lineAngle(b.x1, b.y1, b.x, b.y) : lineAngle(b.x2, b.y2, b.x, b.y);
|
|
1806
|
+
if (b.type === 'Z') {
|
|
1807
|
+
const next = subpathStart(segments, index);
|
|
1808
|
+
if (a.type === 'L')
|
|
1809
|
+
return lineAngle(a.x, a.y, next.x, next.y);
|
|
1810
|
+
if (a.type === 'C') {
|
|
1811
|
+
const prev = previousVertex(segments, index);
|
|
1812
|
+
return curvesAngle(prev.x, prev.y, a.x2, a.y2, a.x, a.y, next.x, next.y, next.x, next.y);
|
|
1813
|
+
}
|
|
1814
|
+
}
|
|
1815
|
+
return 0;
|
|
1816
|
+
}
|
|
1817
|
+
const a = segments[index], b = segments[index + 1];
|
|
1818
|
+
if (a.type === 'M') {
|
|
1819
|
+
if (b.type === 'L')
|
|
1820
|
+
return lineAngle(a.x, a.y, b.x, b.y);
|
|
1821
|
+
if (b.type === 'C')
|
|
1822
|
+
return lineAngle(a.x, a.y, b.x1, b.y1);
|
|
1823
|
+
return 0;
|
|
1824
|
+
}
|
|
1825
|
+
if (a.type === 'Z')
|
|
1826
|
+
return 0;
|
|
1827
|
+
const prev = previousVertex(segments, index);
|
|
1828
|
+
if (b.type === 'L') {
|
|
1829
|
+
if (a.type === 'L')
|
|
1830
|
+
return bisector(prev.x, prev.y, a.x, a.y, a.x, a.y, b.x, b.y);
|
|
1831
|
+
return curvesAngle(prev.x, prev.y, a.x2, a.y2, a.x, a.y, b.x, b.y, b.x, b.y);
|
|
1832
|
+
}
|
|
1833
|
+
if (b.type === 'C') {
|
|
1834
|
+
if (a.type === 'L')
|
|
1835
|
+
return curvesAngle(prev.x, prev.y, prev.x, prev.y, a.x, a.y, b.x1, b.y1, b.x, b.y);
|
|
1836
|
+
return curvesAngle(prev.x, prev.y, a.x2, a.y2, a.x, a.y, b.x1, b.y1, b.x, b.y);
|
|
1837
|
+
}
|
|
1838
|
+
if (b.type === 'M') {
|
|
1839
|
+
if (a.type === 'L')
|
|
1840
|
+
return lineAngle(prev.x, prev.y, a.x, a.y);
|
|
1841
|
+
return near(a.x, a.x2) && near(a.y, a.y2) ? lineAngle(prev.x, prev.y, a.x, a.y) : lineAngle(a.x2, a.y2, a.x, a.y);
|
|
1842
|
+
}
|
|
1843
|
+
const next = subpathStart(segments, index);
|
|
1844
|
+
if (a.type === 'L')
|
|
1845
|
+
return bisector(prev.x, prev.y, a.x, a.y, a.x, a.y, next.x, next.y);
|
|
1846
|
+
return lineAngle(prev.x, prev.y, next.x, next.y);
|
|
1847
|
+
}
|
|
1848
|
+
function parseAngle(value) {
|
|
1849
|
+
const m = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/i.exec(value);
|
|
1850
|
+
if (!m)
|
|
1851
|
+
return 0;
|
|
1852
|
+
const n = parseFloat(m[1]), unit = (m[2] || 'deg').toLowerCase();
|
|
1853
|
+
return unit === 'grad' ? n * 0.9 : unit === 'rad' ? n * 180 / Math.PI : unit === 'turn' ? n * 360 : n;
|
|
1854
|
+
}
|
|
1855
|
+
function colorMatrixOf(node) {
|
|
1856
|
+
const type = node.attrs.type?.trim(), values = node.attrs.values;
|
|
1857
|
+
const list = values === undefined ? null : parseStrictNumberList(values);
|
|
1858
|
+
if (type === 'saturate' && list)
|
|
1859
|
+
return { type: 'saturate', value: list.length ? clamp01(list[0]) : 1 };
|
|
1860
|
+
if (type === 'hueRotate' && list)
|
|
1861
|
+
return { type: 'hueRotate', angle: list.length ? list[0] : 0 };
|
|
1862
|
+
if (type === 'luminanceToAlpha')
|
|
1863
|
+
return { type: 'luminanceToAlpha' };
|
|
1864
|
+
if (type !== 'saturate' && type !== 'hueRotate' && list && list.length === 20)
|
|
1865
|
+
return { type: 'matrix', values: list };
|
|
1866
|
+
return { type: 'matrix', values: [1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0] };
|
|
1867
|
+
}
|
|
1868
|
+
function transferOf(node, current) {
|
|
1869
|
+
const number = (name, fallback) => parsePlainNumber(node.attrs[name]) ?? fallback;
|
|
1870
|
+
switch (node.attrs.type?.trim()) {
|
|
1871
|
+
case 'identity': return null;
|
|
1872
|
+
case 'table':
|
|
1873
|
+
case 'discrete':
|
|
1874
|
+
return { type: node.attrs.type.trim(), values: node.attrs.tableValues === undefined ? [] : parseStrictNumberList(node.attrs.tableValues) || [] };
|
|
1875
|
+
case 'linear': return { type: 'linear', slope: number('slope', 1), intercept: number('intercept', 0) };
|
|
1876
|
+
case 'gamma': return { type: 'gamma', amplitude: number('amplitude', 1), exponent: number('exponent', 1), offset: number('offset', 0) };
|
|
1877
|
+
default: return current;
|
|
1878
|
+
}
|
|
1879
|
+
}
|
|
1880
|
+
function convolutionOf(node) {
|
|
1881
|
+
let columns = 3, rows = 3;
|
|
1882
|
+
if (node.attrs.order !== undefined) {
|
|
1883
|
+
const list = parseNumberList(node.attrs.order);
|
|
1884
|
+
const x = list.length ? Math.trunc(list[0]) : 3, y = list.length > 1 ? Math.trunc(list[1]) : x;
|
|
1885
|
+
if (x > 0 && y > 0) {
|
|
1886
|
+
columns = x;
|
|
1887
|
+
rows = y;
|
|
1888
|
+
}
|
|
1889
|
+
}
|
|
1890
|
+
const list = node.attrs.kernelMatrix === undefined ? null : parseStrictNumberList(node.attrs.kernelMatrix);
|
|
1891
|
+
const kernel = list && list.length === columns * rows ? list : [];
|
|
1892
|
+
let sum = Math.round(kernel.reduce((a, b) => a + b, 0) * 1e6) / 1e6;
|
|
1893
|
+
if (Math.abs(sum) < 1e-6)
|
|
1894
|
+
sum = 1;
|
|
1895
|
+
const divisor = parsePlainNumber(node.attrs.divisor) ?? sum;
|
|
1896
|
+
if (Math.abs(divisor) < 1e-6)
|
|
1897
|
+
return null;
|
|
1898
|
+
const target = (name, order) => {
|
|
1899
|
+
const v = parsePlainNumber(node.attrs[name]);
|
|
1900
|
+
const t = Math.trunc(v === null ? Math.floor(order / 2) : v);
|
|
1901
|
+
return t >= 0 && t < order ? t : null;
|
|
1902
|
+
};
|
|
1903
|
+
const targetX = target('targetX', columns), targetY = target('targetY', rows);
|
|
1904
|
+
if (targetX === null || targetY === null || kernel.length !== columns * rows)
|
|
1905
|
+
return null;
|
|
1906
|
+
const edge = node.attrs.edgeMode?.trim();
|
|
1907
|
+
return { columns, rows, targetX, targetY, kernel, divisor, bias: parsePlainNumber(node.attrs.bias) ?? 0, edge: edge === 'none' || edge === 'wrap' ? edge : 'duplicate',
|
|
1908
|
+
preserveAlpha: node.attrs.preserveAlpha?.trim() === 'true' };
|
|
1909
|
+
}
|
|
1910
|
+
function parseAngleStrict(value) {
|
|
1911
|
+
const m = /^([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)(deg|grad|rad|turn)?$/i.exec(value.trim());
|
|
1912
|
+
return m && (m[2] || parseFloat(m[1]) === 0) ? parseAngle(value.trim()) : null;
|
|
1913
|
+
}
|
|
1914
|
+
function parsePlainNumber(value) {
|
|
1915
|
+
return value !== undefined && /^[+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?$/i.test(value.trim()) ? parseFloat(value) : null;
|
|
1916
|
+
}
|
|
1917
|
+
function parseStrictNumberList(value) {
|
|
1918
|
+
const items = value.trim().split(/\s*,\s*|\s+/).filter(Boolean), list = items.map(item => parsePlainNumber(item));
|
|
1919
|
+
return list.some(v => v === null) ? null : list;
|
|
1920
|
+
}
|
|
913
1921
|
const TRANSPARENT = [0, 0, 0, 0];
|
|
1922
|
+
function sampler(d, width, height, matrix, repeat, filter, opacity) {
|
|
1923
|
+
const color = [0, 0, 0, 0];
|
|
1924
|
+
const wx = new Float64Array(4), wy = new Float64Array(4), xs = new Int32Array(4), ys = new Int32Array(4);
|
|
1925
|
+
const wrap = (v, n) => repeat ? v - Math.floor(v / n) * n : v < 0 ? 0 : v >= n ? n - 1 : v;
|
|
1926
|
+
const weights = (t, w) => {
|
|
1927
|
+
if (filter === 1) {
|
|
1928
|
+
w[0] = w[3] = 0;
|
|
1929
|
+
w[1] = 1 - t;
|
|
1930
|
+
w[2] = t;
|
|
1931
|
+
return;
|
|
1932
|
+
}
|
|
1933
|
+
const s = 1 - t;
|
|
1934
|
+
w[0] = (7 / 18 * s - 6 / 18) * s * s;
|
|
1935
|
+
w[1] = ((-21 / 18 * s + 27 / 18) * s + 9 / 18) * s + 1 / 18;
|
|
1936
|
+
w[2] = ((-21 / 18 * t + 27 / 18) * t + 9 / 18) * t + 1 / 18;
|
|
1937
|
+
w[3] = (7 / 18 * t - 6 / 18) * t * t;
|
|
1938
|
+
};
|
|
1939
|
+
const [m0, m1, m2, m3, m4, m5] = matrix;
|
|
1940
|
+
return (px, py) => {
|
|
1941
|
+
const u = m0 * px + m2 * py + m4 - 0.5, v = m1 * px + m3 * py + m5 - 0.5;
|
|
1942
|
+
let r = 0, g = 0, b = 0, a = 0;
|
|
1943
|
+
if (filter === 0) {
|
|
1944
|
+
const i = (Math.floor(wrap(v + 0.5, height)) * width + Math.floor(wrap(u + 0.5, width))) * 4;
|
|
1945
|
+
r = d[i];
|
|
1946
|
+
g = d[i + 1];
|
|
1947
|
+
b = d[i + 2];
|
|
1948
|
+
a = d[i + 3];
|
|
1949
|
+
}
|
|
1950
|
+
else {
|
|
1951
|
+
const x0 = Math.floor(u), y0 = Math.floor(v);
|
|
1952
|
+
weights(u - x0, wx);
|
|
1953
|
+
weights(v - y0, wy);
|
|
1954
|
+
for (let k = 0; k < 4; k++) {
|
|
1955
|
+
xs[k] = Math.floor(wrap(x0 - 1 + k, width));
|
|
1956
|
+
ys[k] = Math.floor(wrap(y0 - 1 + k, height)) * width;
|
|
1957
|
+
}
|
|
1958
|
+
for (let j = 0; j < 4; j++)
|
|
1959
|
+
for (let k = 0; k < 4; k++) {
|
|
1960
|
+
const f = wy[j] * wx[k];
|
|
1961
|
+
if (!f)
|
|
1962
|
+
continue;
|
|
1963
|
+
const i = (ys[j] + xs[k]) * 4;
|
|
1964
|
+
r += d[i] * f;
|
|
1965
|
+
g += d[i + 1] * f;
|
|
1966
|
+
b += d[i + 2] * f;
|
|
1967
|
+
a += d[i + 3] * f;
|
|
1968
|
+
}
|
|
1969
|
+
a = clamp01(a);
|
|
1970
|
+
}
|
|
1971
|
+
if (a <= 1e-6)
|
|
1972
|
+
return TRANSPARENT;
|
|
1973
|
+
color[0] = clamp01(r / a);
|
|
1974
|
+
color[1] = clamp01(g / a);
|
|
1975
|
+
color[2] = clamp01(b / a);
|
|
1976
|
+
color[3] = a * opacity;
|
|
1977
|
+
return color;
|
|
1978
|
+
};
|
|
1979
|
+
}
|
|
914
1980
|
function solidPaint(color) {
|
|
915
1981
|
const paint = () => color;
|
|
916
1982
|
paint.solid = color;
|
|
@@ -998,6 +2064,43 @@ class Layer {
|
|
|
998
2064
|
}
|
|
999
2065
|
}
|
|
1000
2066
|
}
|
|
2067
|
+
toPixmap() {
|
|
2068
|
+
const d = this.data, out = new Uint8Array(d.length);
|
|
2069
|
+
for (let i = 0; i < d.length; i++)
|
|
2070
|
+
out[i] = Math.round(clamp01(d[i]) * 255);
|
|
2071
|
+
return { width: this.width, height: this.height, data: out };
|
|
2072
|
+
}
|
|
2073
|
+
static fromPixmap(p) {
|
|
2074
|
+
const layer = new Layer(p.width, p.height), d = layer.data;
|
|
2075
|
+
let painted = false;
|
|
2076
|
+
for (let i = 0; i < d.length; i++) {
|
|
2077
|
+
d[i] = p.data[i] / 255;
|
|
2078
|
+
if (p.data[i])
|
|
2079
|
+
painted = true;
|
|
2080
|
+
}
|
|
2081
|
+
if (painted)
|
|
2082
|
+
layer.extend(0, 0, p.width, p.height);
|
|
2083
|
+
return layer;
|
|
2084
|
+
}
|
|
2085
|
+
blit(layer, ox, oy) {
|
|
2086
|
+
const s = layer.data, d = this.data;
|
|
2087
|
+
const x0 = Math.max(0, ox), y0 = Math.max(0, oy), x1 = Math.min(this.width, ox + layer.width), y1 = Math.min(this.height, oy + layer.height);
|
|
2088
|
+
if (x1 <= x0 || y1 <= y0)
|
|
2089
|
+
return;
|
|
2090
|
+
this.extend(x0, y0, x1, y1);
|
|
2091
|
+
for (let y = y0; y < y1; y++)
|
|
2092
|
+
for (let x = x0; x < x1; x++) {
|
|
2093
|
+
const i = (y * this.width + x) * 4, j = ((y - oy) * layer.width + x - ox) * 4;
|
|
2094
|
+
const a = s[j + 3];
|
|
2095
|
+
if (a <= 0)
|
|
2096
|
+
continue;
|
|
2097
|
+
const inv = 1 - a;
|
|
2098
|
+
d[i] = s[j] + d[i] * inv;
|
|
2099
|
+
d[i + 1] = s[j + 1] + d[i + 1] * inv;
|
|
2100
|
+
d[i + 2] = s[j + 2] + d[i + 2] * inv;
|
|
2101
|
+
d[i + 3] = a + d[i + 3] * inv;
|
|
2102
|
+
}
|
|
2103
|
+
}
|
|
1001
2104
|
composite(layer, opacity, mask) {
|
|
1002
2105
|
if (layer.x1 <= layer.x0)
|
|
1003
2106
|
return;
|
|
@@ -1373,7 +2476,8 @@ function arcToCubics(path, x1, y1, rx, ry, rotation, large, sweep, x2, y2) {
|
|
|
1373
2476
|
delta -= 2 * Math.PI;
|
|
1374
2477
|
else if (sweep && delta < 0)
|
|
1375
2478
|
delta += 2 * Math.PI;
|
|
1376
|
-
const
|
|
2479
|
+
const perTurn = Math.max(Math.pow(1.1163 * Math.max(rx, ry) / 0.1, 1 / 6), 3.999999);
|
|
2480
|
+
const segments = Math.max(1, Math.ceil(perTurn * Math.abs(delta) / (2 * Math.PI)));
|
|
1377
2481
|
const step = delta / segments;
|
|
1378
2482
|
const k = 4 / 3 * Math.tan(step / 4);
|
|
1379
2483
|
const point = (t) => [cx + rx * Math.cos(t) * cos - ry * Math.sin(t) * sin, cy + rx * Math.cos(t) * sin + ry * Math.sin(t) * cos];
|