@pixerate/editor 0.266.1 → 0.267.0

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.
Files changed (117) hide show
  1. package/dist/agent/index.cjs +8 -4
  2. package/dist/agent/index.js +6 -2
  3. package/dist/animation-editor/controller.d.cts +8 -0
  4. package/dist/animation-editor/controller.d.ts +8 -0
  5. package/dist/animation-editor/effect-tools.d.cts +1 -1
  6. package/dist/animation-editor/effect-tools.d.ts +1 -1
  7. package/dist/animation-editor/index.cjs +172 -105
  8. package/dist/animation-editor/index.js +91 -24
  9. package/dist/brushes/index.cjs +59 -59
  10. package/dist/brushes/index.js +5 -5
  11. package/dist/brushes/profiles.d.cts +6 -1
  12. package/dist/brushes/profiles.d.ts +6 -1
  13. package/dist/{brushstrokeRender-FSUWXUZY.cjs → brushstrokeRender-L7JYRR2R.cjs} +16 -16
  14. package/dist/{brushstrokeRender-KD453OBX.js → brushstrokeRender-NLFPEBGI.js} +4 -4
  15. package/dist/canvas/brushTypes.d.cts +12 -0
  16. package/dist/canvas/brushTypes.d.ts +12 -0
  17. package/dist/canvas/brushstroke.d.cts +1 -1
  18. package/dist/canvas/brushstroke.d.ts +1 -1
  19. package/dist/canvas/drawController.d.cts +19 -4
  20. package/dist/canvas/drawController.d.ts +19 -4
  21. package/dist/canvas/index.cjs +144 -105
  22. package/dist/canvas/index.js +46 -7
  23. package/dist/{chunk-XORJ7UZO.cjs → chunk-3VHH6V67.cjs} +13 -12
  24. package/dist/{chunk-T2LDTEXK.js → chunk-4IDUYB45.js} +2217 -56
  25. package/dist/chunk-7UKFXXWL.js +802 -0
  26. package/dist/chunk-ADMRNWR7.js +340 -0
  27. package/dist/{chunk-CIJBSUM5.js → chunk-AGNUD5BI.js} +2 -2
  28. package/dist/{chunk-WLUVZKVD.cjs → chunk-DT4YQUGT.cjs} +32 -32
  29. package/dist/{chunk-DXYHQ2VN.js → chunk-EF7LZAXQ.js} +1 -1
  30. package/dist/chunk-EXB2EGBE.cjs +802 -0
  31. package/dist/{chunk-4ODRXQRW.js → chunk-EYSHTYLG.js} +1 -1
  32. package/dist/{chunk-R44Y3EFS.js → chunk-FGJHJIMN.js} +8 -336
  33. package/dist/{chunk-AQZQWXEU.cjs → chunk-G7NHE2VD.cjs} +35 -35
  34. package/dist/{chunk-XC6DPRYI.js → chunk-GSTSZPSR.js} +154 -949
  35. package/dist/{chunk-VRK322ZC.cjs → chunk-HIO6E7LC.cjs} +2 -2
  36. package/dist/{chunk-TOID45I2.cjs → chunk-J2TNIZ55.cjs} +1 -1
  37. package/dist/{chunk-YHDHFJUC.cjs → chunk-J5VQYK7T.cjs} +217 -1012
  38. package/dist/{chunk-3C33YTNN.js → chunk-JGWVZPT6.js} +2 -2
  39. package/dist/{chunk-ACFSFUQH.js → chunk-JL6YH5WD.js} +4 -0
  40. package/dist/{chunk-3SBLVGOM.cjs → chunk-LA5Y4ETA.cjs} +23 -23
  41. package/dist/{chunk-MVUQSK5J.cjs → chunk-LHPEG5AU.cjs} +107 -435
  42. package/dist/{chunk-DOZ6F2K2.js → chunk-NSETJI74.js} +3 -2
  43. package/dist/{chunk-XRXFVRGY.cjs → chunk-OKHKA43L.cjs} +2364 -203
  44. package/dist/{chunk-LK4SXL3V.js → chunk-OSEXT7JL.js} +1 -1
  45. package/dist/{chunk-PE6YJMQT.cjs → chunk-PFHJS4HE.cjs} +20 -19
  46. package/dist/{chunk-ZQI3WUPP.js → chunk-QCLY5SFS.js} +12 -0
  47. package/dist/{chunk-7KNW3WXZ.cjs → chunk-QEVLRLUN.cjs} +63 -0
  48. package/dist/{chunk-OTN6VB5S.cjs → chunk-RDFHWAHL.cjs} +5 -1
  49. package/dist/{chunk-6JL2D5SG.js → chunk-VE6UKYQ2.js} +3 -2
  50. package/dist/{chunk-RFJZGTHA.cjs → chunk-XVOP3CGQ.cjs} +9 -9
  51. package/dist/{chunk-EZOJBP4D.js → chunk-YIC6MAJ2.js} +1 -1
  52. package/dist/chunk-YZWM6ZIP.cjs +340 -0
  53. package/dist/{chunk-472INMWH.js → chunk-ZA7L5YJB.js} +63 -0
  54. package/dist/{chunk-YBC3RKT2.cjs → chunk-ZGXJ7BTR.cjs} +13 -1
  55. package/dist/commands/builtins.d.cts +12 -1
  56. package/dist/commands/builtins.d.ts +12 -1
  57. package/dist/commands/index.cjs +2 -2
  58. package/dist/commands/index.js +1 -1
  59. package/dist/image-editor/controller.d.cts +1 -1
  60. package/dist/image-editor/controller.d.ts +1 -1
  61. package/dist/image-editor/index.cjs +837 -833
  62. package/dist/image-editor/index.js +105 -101
  63. package/dist/paint/index.cjs +5 -3
  64. package/dist/paint/index.js +46 -44
  65. package/dist/paint-editor/controller.d.cts +5 -3
  66. package/dist/paint-editor/controller.d.ts +5 -3
  67. package/dist/paint-editor/index.cjs +832 -2295
  68. package/dist/paint-editor/index.js +285 -1748
  69. package/dist/paint-editor/path-samples.d.cts +2 -0
  70. package/dist/paint-editor/path-samples.d.ts +2 -0
  71. package/dist/paint-editor/presence.d.cts +20 -1
  72. package/dist/paint-editor/presence.d.ts +20 -1
  73. package/dist/stickers/helpers.d.cts +2 -0
  74. package/dist/stickers/helpers.d.ts +2 -0
  75. package/dist/stickers/index.cjs +41 -35
  76. package/dist/stickers/index.js +22 -16
  77. package/dist/stickers/types.d.cts +4 -2
  78. package/dist/stickers/types.d.ts +4 -2
  79. package/dist/tools/conformance.d.cts +8 -0
  80. package/dist/tools/conformance.d.ts +8 -0
  81. package/dist/tools/index.cjs +6 -2
  82. package/dist/tools/index.js +5 -1
  83. package/dist/vector/backdrop.d.cts +13 -0
  84. package/dist/vector/backdrop.d.ts +13 -0
  85. package/dist/vector/brushstroke.d.cts +54 -7
  86. package/dist/vector/brushstroke.d.ts +54 -7
  87. package/dist/vector/brushstrokeMedia.d.cts +96 -0
  88. package/dist/vector/brushstrokeMedia.d.ts +96 -0
  89. package/dist/vector/controller.d.cts +17 -3
  90. package/dist/vector/controller.d.ts +17 -3
  91. package/dist/vector/index.cjs +1846 -1386
  92. package/dist/vector/index.d.cts +2 -0
  93. package/dist/vector/index.d.ts +2 -0
  94. package/dist/vector/index.js +517 -57
  95. package/dist/vector/render.d.cts +6 -0
  96. package/dist/vector/render.d.ts +6 -0
  97. package/dist/vector/types.d.cts +14 -0
  98. package/dist/vector/types.d.ts +14 -0
  99. package/package.json +1 -1
  100. package/skills/pixerate-animation-editor/SKILL.md +1 -0
  101. package/skills/pixerate-brushes/SKILL.md +2 -2
  102. package/skills/pixerate-brushes-design/SKILL.md +7 -4
  103. package/skills/pixerate-brushes-design/evals/port-to-vector.json +8 -8
  104. package/skills/pixerate-canvas/SKILL.md +11 -1
  105. package/skills/pixerate-image-editor/SKILL.md +19 -64
  106. package/skills/pixerate-image-editor/references/color-management.md +2 -1
  107. package/skills/pixerate-image-editor/references/free-transform.md +12 -0
  108. package/skills/pixerate-image-editor/references/layer-effects.md +10 -0
  109. package/skills/pixerate-image-editor/references/painting.md +17 -0
  110. package/skills/pixerate-image-editor/references/photoshop-files.md +1 -1
  111. package/skills/pixerate-image-editor/references/shapes-and-type.md +14 -0
  112. package/skills/pixerate-image-editor/references/smart-objects.md +10 -0
  113. package/skills/pixerate-paint-editor/SKILL.md +8 -4
  114. package/skills/pixerate-paint-editor/references/wet-media.md +9 -0
  115. package/skills/pixerate-vector/SKILL.md +16 -6
  116. package/skills/pixerate-vector/references/best-practices.md +1 -0
  117. package/skills/pixerate-vector/references/commands.md +19 -0
@@ -7,7 +7,11 @@ import {
7
7
  listPresets,
8
8
  normalizeBrushSpec,
9
9
  resolveBrush
10
- } from "./chunk-CIJBSUM5.js";
10
+ } from "./chunk-AGNUD5BI.js";
11
+ import {
12
+ editorStampOf,
13
+ stampCoverage
14
+ } from "./chunk-JL6YH5WD.js";
11
15
  import {
12
16
  parseProvenance
13
17
  } from "./chunk-M6DNZNVY.js";
@@ -52,12 +56,71 @@ import {
52
56
  import {
53
57
  brushColourHex
54
58
  } from "./chunk-DVPQFMH6.js";
59
+ import {
60
+ DEFAULT_FLOW,
61
+ DEFAULT_WET_PARAMS,
62
+ FLAT,
63
+ PIGMENT_UNIT,
64
+ WET_TILE,
65
+ WetMedium,
66
+ WetWorld,
67
+ createWetGpuEngine,
68
+ findWebGpu,
69
+ flowField,
70
+ moveWetSnapshot,
71
+ normalizeFlow,
72
+ normalizeTilt,
73
+ normalizeWetParams,
74
+ pigmentOf
75
+ } from "./chunk-GSTSZPSR.js";
55
76
  import {
56
77
  BrushstrokeCache,
57
78
  GRAIN_PATTERNS,
79
+ PaperGrain,
58
80
  brushstrokeDataUrl,
81
+ brushstrokeSamples,
82
+ grainCatch,
59
83
  isBrushstrokeBrush
60
84
  } from "./chunk-TXFWZ5ZJ.js";
85
+ import {
86
+ CoverageMap,
87
+ EMPTY_MIXER_LOAD,
88
+ PaintExchange,
89
+ PaintGradientSampler,
90
+ SmudgeTip,
91
+ TileMedium,
92
+ blenderDab,
93
+ createBlenderScratch,
94
+ dabRect,
95
+ exchangeRates,
96
+ loadMixer,
97
+ mixerRates,
98
+ parsePaintSource,
99
+ rasterizeDab,
100
+ readPaintSource,
101
+ resolvePaintGradient,
102
+ scalePaintGradient
103
+ } from "./chunk-GCVFEPJG.js";
104
+ import {
105
+ rand01,
106
+ randSigned
107
+ } from "./chunk-4D6KP5BV.js";
108
+ import {
109
+ BRUSHSTROKE_MAX_SCALE,
110
+ BRUSHSTROKE_MIN_SCALE
111
+ } from "./chunk-ODBT55Q7.js";
112
+ import {
113
+ mixPigment8
114
+ } from "./chunk-IRSTHLQQ.js";
115
+ import {
116
+ TILE,
117
+ TiledSurface,
118
+ emptySurface,
119
+ readRegion,
120
+ tileKey,
121
+ translateSurface,
122
+ writeRegion
123
+ } from "./chunk-HVVR5PZW.js";
61
124
  import {
62
125
  oklabToRgb,
63
126
  rgbToOklab
@@ -2320,7 +2383,7 @@ function vectorStrokeParts(path, style) {
2320
2383
  const cap = capExtent(style, width);
2321
2384
  const tipMode = style.arrowAlign === "tip";
2322
2385
  const trims = contours.map(() => [0, 0]);
2323
- const place2 = (end, contour, ci) => {
2386
+ const place3 = (end, contour, ci) => {
2324
2387
  const kind = end === "start" ? style.startArrow : style.endArrow;
2325
2388
  if (!kind || contour.closed) return;
2326
2389
  const hw = arrowheadWeight(style, end);
@@ -2341,8 +2404,8 @@ function vectorStrokeParts(path, style) {
2341
2404
  }
2342
2405
  heads.push({ end, kind, tip, dir, inset, path: arrowheadPath(kind, tip, dir, hw) });
2343
2406
  };
2344
- place2("start", first, 0);
2345
- place2("end", last, contours.length - 1);
2407
+ place3("start", first, 0);
2408
+ place3("end", last, contours.length - 1);
2346
2409
  if (!tipMode || !heads.length) return { align, line: path, drawWidth, heads };
2347
2410
  const trimmed = contours.map((c, i) => {
2348
2411
  const [s0, s1] = trims[i];
@@ -2534,17 +2597,1834 @@ function vectorExtrudeFaces(path, params) {
2534
2597
  return order.map((i) => faces[i].face);
2535
2598
  }
2536
2599
 
2600
+ // src/paint-editor/effect-paint.ts
2601
+ var EFFECT_STRIP_HEIGHT = 256;
2602
+ var EFFECT_MAP_REPEATS = ["repeat", "mirror", "clamp"];
2603
+ function effectPaintSize(p, canvas) {
2604
+ return p.map ? { width: p.map.length, height: EFFECT_STRIP_HEIGHT } : { width: canvas.width, height: canvas.height };
2605
+ }
2606
+ function readEffectStrokeMap(raw) {
2607
+ if (raw === void 0 || raw === null || raw.by === "canvas") return void 0;
2608
+ const r = raw;
2609
+ if (r.by !== "stroke") throw new Error(`map.by ${JSON.stringify(r.by)} is not a mapping; use "canvas" (fixed to the canvas) or "stroke" (along each stroke).`);
2610
+ const length2 = r.length === void 0 ? 300 : Number(r.length);
2611
+ if (!(Number.isFinite(length2) && length2 >= 16 && length2 <= 4096)) throw new Error(`map.length ${JSON.stringify(r.length)} is out of range; use 16..4096 px of stroke per repeat.`);
2612
+ const repeat = r.repeat === void 0 ? "repeat" : r.repeat;
2613
+ if (!EFFECT_MAP_REPEATS.includes(repeat)) throw new Error(`map.repeat ${JSON.stringify(r.repeat)} is not a repeat mode; use ${EFFECT_MAP_REPEATS.join(", ")}.`);
2614
+ return { by: "stroke", length: Math.round(length2), repeat };
2615
+ }
2616
+ function stripIndex(img, map, dab, x, y) {
2617
+ const ca = Math.cos(dab.direction);
2618
+ const sa = Math.sin(dab.direction);
2619
+ const dx = x - dab.x;
2620
+ const dy = y - dab.y;
2621
+ let u = (dab.travel + dx * ca - dy * sa) / map.length;
2622
+ if (map.repeat === "clamp") u = Math.min(1, Math.max(0, u));
2623
+ else if (map.repeat === "mirror") {
2624
+ const m = (u % 2 + 2) % 2;
2625
+ u = m > 1 ? 2 - m : m;
2626
+ } else u = (u % 1 + 1) % 1;
2627
+ const v2 = Math.min(1, Math.max(0, ((dx * sa + dy * ca) / Math.max(0.5, dab.radius) + 1) / 2));
2628
+ const px = Math.min(img.width - 1, Math.floor(u * img.width));
2629
+ const py = Math.min(img.height - 1, Math.floor(v2 * img.height));
2630
+ return (py * img.width + px) * 4;
2631
+ }
2632
+ function effectPaintKey(p) {
2633
+ return JSON.stringify({ type: "effect", effect: p.effect, provider: p.provider, values: p.values, time: p.time, ...p.map ? { map: p.map } : {} });
2634
+ }
2635
+ function isPaintEffectPaint(raw) {
2636
+ return Boolean(raw) && typeof raw === "object" && raw.type === "effect";
2637
+ }
2638
+ function readMapLeniently(raw) {
2639
+ try {
2640
+ return readEffectStrokeMap(raw);
2641
+ } catch {
2642
+ return void 0;
2643
+ }
2644
+ }
2645
+ function readPaintEffectPaint(raw) {
2646
+ if (!isPaintEffectPaint(raw)) return null;
2647
+ const r = raw;
2648
+ if (typeof r.effect !== "string" || !r.effect || !r.values || typeof r.values !== "object" || Array.isArray(r.values)) return null;
2649
+ return {
2650
+ type: "effect",
2651
+ effect: r.effect,
2652
+ provider: typeof r.provider === "string" ? r.provider : "",
2653
+ values: JSON.parse(JSON.stringify(r.values)),
2654
+ time: typeof r.time === "number" && Number.isFinite(r.time) && r.time > 0 ? r.time : 0,
2655
+ ...readMapLeniently(r.map) ? { map: readMapLeniently(r.map) } : {},
2656
+ ...r.live === true ? { live: true } : {}
2657
+ };
2658
+ }
2659
+ function sampleEffectField(img, rect, vals, field, dab) {
2660
+ const { width, height, data } = img;
2661
+ if (img.map && dab) {
2662
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
2663
+ for (let xx = 0; xx < rect.width; xx++, k++) {
2664
+ const i = stripIndex(img, img.map, dab, rect.x + xx + 0.5, rect.y + yy + 0.5);
2665
+ const f = k * 3;
2666
+ const a = data[i + 3];
2667
+ if (a < 255) vals[k] *= a / 255;
2668
+ field[f] = data[i] / 255;
2669
+ field[f + 1] = data[i + 1] / 255;
2670
+ field[f + 2] = data[i + 2] / 255;
2671
+ }
2672
+ }
2673
+ return;
2674
+ }
2675
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
2676
+ const y = rect.y + yy;
2677
+ const inY = y >= 0 && y < height;
2678
+ for (let xx = 0; xx < rect.width; xx++, k++) {
2679
+ const x = rect.x + xx;
2680
+ const f = k * 3;
2681
+ if (!inY || x < 0 || x >= width) {
2682
+ vals[k] = 0;
2683
+ field[f] = field[f + 1] = field[f + 2] = 0;
2684
+ continue;
2685
+ }
2686
+ const i = (y * width + x) * 4;
2687
+ const a = data[i + 3];
2688
+ if (a < 255) vals[k] *= a / 255;
2689
+ field[f] = data[i] / 255;
2690
+ field[f + 1] = data[i + 1] / 255;
2691
+ field[f + 2] = data[i + 2] / 255;
2692
+ }
2693
+ }
2694
+ }
2695
+ function sampleEffectAt(img, x, y, out, dab) {
2696
+ if (img.map && dab) {
2697
+ const i2 = stripIndex(img, img.map, dab, x, y);
2698
+ out[0] = img.data[i2] / 255;
2699
+ out[1] = img.data[i2 + 1] / 255;
2700
+ out[2] = img.data[i2 + 2] / 255;
2701
+ return img.data[i2 + 3] / 255;
2702
+ }
2703
+ const px = Math.floor(x);
2704
+ const py = Math.floor(y);
2705
+ if (px < 0 || py < 0 || px >= img.width || py >= img.height) return 0;
2706
+ const i = (py * img.width + px) * 4;
2707
+ out[0] = img.data[i] / 255;
2708
+ out[1] = img.data[i + 1] / 255;
2709
+ out[2] = img.data[i + 2] / 255;
2710
+ return img.data[i + 3] / 255;
2711
+ }
2712
+ function effectDabField(img, rect, cov, centre, mixed, field, steps = 0, dab = null) {
2713
+ sampleEffectField(img, rect, cov, field, dab);
2714
+ const d0 = mixed[0] - centre[0];
2715
+ const d1 = mixed[1] - centre[1];
2716
+ const d2 = mixed[2] - centre[2];
2717
+ const n = rect.width * rect.height;
2718
+ for (let k = 0; k < n; k++) {
2719
+ if (steps) cov[k] = Math.round(cov[k] * steps) / steps;
2720
+ const f = k * 3;
2721
+ field[f] = Math.min(1, Math.max(0, field[f] + d0));
2722
+ field[f + 1] = Math.min(1, Math.max(0, field[f + 1] + d1));
2723
+ field[f + 2] = Math.min(1, Math.max(0, field[f + 2] + d2));
2724
+ }
2725
+ }
2726
+
2727
+ // src/paint-editor/stamp-tip.ts
2728
+ var samplers = /* @__PURE__ */ new WeakMap();
2729
+ function stampSampler(ref, art) {
2730
+ let kind = null;
2731
+ try {
2732
+ kind = editorStampOf(ref.includes(":") ? ref : `editor:${ref}`);
2733
+ } catch {
2734
+ return null;
2735
+ }
2736
+ if (kind) {
2737
+ const k = kind;
2738
+ return (u, v2, seed) => stampCoverage(k, u, v2, seed);
2739
+ }
2740
+ const a = art?.(ref);
2741
+ if (!a || !(a.width > 0 && a.height > 0)) return null;
2742
+ const hit = samplers.get(a);
2743
+ if (hit) return hit;
2744
+ const { width: w, height: h, data } = a;
2745
+ const scale3 = Math.max(w, h) / 2;
2746
+ const alpha = (x, y) => x < 0 || y < 0 || x >= w || y >= h ? 0 : data[(y * w + x) * 4 + 3] / 255;
2747
+ const sampler = (u, v2) => {
2748
+ const x = u * scale3 + w / 2 - 0.5;
2749
+ const y = v2 * scale3 + h / 2 - 0.5;
2750
+ const x0 = Math.floor(x);
2751
+ const y0 = Math.floor(y);
2752
+ const fx = x - x0;
2753
+ const fy = y - y0;
2754
+ return (alpha(x0, y0) * (1 - fx) + alpha(x0 + 1, y0) * fx) * (1 - fy) + (alpha(x0, y0 + 1) * (1 - fx) + alpha(x0 + 1, y0 + 1) * fx) * fy;
2755
+ };
2756
+ samplers.set(a, sampler);
2757
+ return sampler;
2758
+ }
2759
+ function stampDabRect(d) {
2760
+ const r = Math.max(0.5, d.radius) * Math.SQRT2 + 1.5;
2761
+ const x0 = Math.floor(d.x - r);
2762
+ const y0 = Math.floor(d.y - r);
2763
+ return { x: x0, y: y0, width: Math.ceil(d.x + r) - x0, height: Math.ceil(d.y + r) - y0 };
2764
+ }
2765
+ function rasterizeStampDab(d, sample, seed, rect, out) {
2766
+ const w = rect.width;
2767
+ const h = rect.height;
2768
+ out.fill(0, 0, w * h);
2769
+ const r = Math.max(0.5, d.radius);
2770
+ const ro = Math.min(1, Math.max(0.05, d.roundness));
2771
+ const sn = Math.sin(d.angle);
2772
+ const cs = Math.cos(d.angle);
2773
+ const ss = r < 6 ? 3 : 1;
2774
+ for (let yy = 0; yy < h; yy++) {
2775
+ for (let xx = 0; xx < w; xx++) {
2776
+ let sum = 0;
2777
+ for (let sy = 0; sy < ss; sy++) {
2778
+ for (let sx = 0; sx < ss; sx++) {
2779
+ const dx = rect.x + xx + (sx + 0.5) / ss - d.x;
2780
+ const dy = rect.y + yy + (sy + 0.5) / ss - d.y;
2781
+ const u = (dx * cs - dy * sn) / r;
2782
+ const v2 = (dx * sn + dy * cs) / (r * ro);
2783
+ if (u > -1.05 && u < 1.05 && v2 > -1.05 && v2 < 1.05) sum += sample(u, v2, seed);
2784
+ }
2785
+ }
2786
+ const val = sum / (ss * ss);
2787
+ if (val > 0) out[yy * w + xx] = Math.min(1, val) * d.alpha;
2788
+ }
2789
+ }
2790
+ }
2791
+ function brushStickerRefs(brush) {
2792
+ const refs = brush.engine === "sticker" ? [...brush.sticker.stamps] : brush.engine === "particle" ? [...brush.particle.dotTextures] : brush.engine === "dab" && brush.stamp ? [brush.stamp] : [];
2793
+ return [...new Set(refs.filter((r) => r.includes(":") && !r.startsWith("editor:")))];
2794
+ }
2795
+ function sprayDroplets(d, spray, seed) {
2796
+ const count = 1 + Math.round(spray.density * 31);
2797
+ const key = d.index * 131 + Math.round(d.travel * 8);
2798
+ const out = [];
2799
+ for (let i = 0; i < count; i++) {
2800
+ const n = key * 64 + i;
2801
+ const a = rand01(seed, n, 61) * Math.PI * 2;
2802
+ const rr = Math.sqrt(rand01(seed, n, 67)) * d.radius;
2803
+ out.push({ ...d, x: d.x + Math.cos(a) * rr, y: d.y + Math.sin(a) * rr, radius: Math.max(0.5, d.radius * spray.size * (0.6 + 0.8 * rand01(seed, n, 71))), roundness: 1, angle: rand01(seed, n, 73) * Math.PI * 2 });
2804
+ }
2805
+ return out;
2806
+ }
2807
+
2808
+ // src/paint-editor/paper.ts
2809
+ var PAPER_FAMILIES = ["watercolor", "drawing", "pastel", "canvas", "panel", "smooth"];
2810
+ var unit2 = (v2, d) => typeof v2 === "number" && Number.isFinite(v2) ? Math.min(1, Math.max(0, v2)) : d;
2811
+ var clampNum = (v2, lo, hi, d) => typeof v2 === "number" && Number.isFinite(v2) ? Math.min(hi, Math.max(lo, v2)) : d;
2812
+ var HEX = /^#[0-9a-f]{6}$/i;
2813
+ var tuning = (contrast = 1, invert2 = false) => ({ contrast, invert: invert2 });
2814
+ function preset(id, name, family, pattern, color2, o) {
2815
+ return {
2816
+ preset: id,
2817
+ name,
2818
+ family,
2819
+ pattern,
2820
+ seed: o.seed ?? 1,
2821
+ color: color2,
2822
+ scale: o.scale ?? 1,
2823
+ tiling: "mirror",
2824
+ depth: o.depth,
2825
+ shading: o.shading ?? 0.5,
2826
+ dry: tuning(o.contrast ?? 1),
2827
+ wet: tuning(1),
2828
+ absorption: o.absorption,
2829
+ permeability: o.permeability,
2830
+ roughness: o.roughness,
2831
+ ...o.backlight ? { backlight: o.backlight, backlightColor: o.backlightColor ?? "#fff1d6" } : {}
2832
+ };
2833
+ }
2834
+ var PAPER_LIBRARY = [
2835
+ preset("cold-pressed", "Cold pressed watercolour", "watercolor", "cold-pressed", "#f7f3ea", { depth: 0.5, absorption: 0.7, permeability: 0.5, roughness: 0.6 }),
2836
+ preset("hot-pressed", "Hot pressed watercolour", "watercolor", "hot-pressed", "#f8f6ef", { depth: 0.25, absorption: 0.55, permeability: 0.4, roughness: 0.25 }),
2837
+ preset("rough-watercolor", "Rough watercolour", "watercolor", "rough", "#f5f0e4", { depth: 0.75, absorption: 0.8, permeability: 0.6, roughness: 0.85 }),
2838
+ preset("cartridge", "Cartridge", "drawing", "vellum", "#fbfaf6", { depth: 0.3, absorption: 0.4, permeability: 0.3, roughness: 0.35 }),
2839
+ preset("laid", "Laid paper", "drawing", "laid", "#f3ecdc", { depth: 0.45, absorption: 0.45, permeability: 0.35, roughness: 0.45 }),
2840
+ preset("ingres", "Charcoal paper", "drawing", "ingres", "#ede6d6", { depth: 0.6, absorption: 0.4, permeability: 0.3, roughness: 0.65 }),
2841
+ preset("sanded-pastel", "Sanded pastel paper", "pastel", "sanded", "#d8cfc0", { depth: 0.7, absorption: 0.3, permeability: 0.2, roughness: 0.9, shading: 0.35 }),
2842
+ preset("pastel-card", "Grey pastel card", "pastel", "sanded", "#9c978e", { depth: 0.55, absorption: 0.3, permeability: 0.2, roughness: 0.75, scale: 1.5, shading: 0.3 }),
2843
+ preset("cotton-canvas", "Cotton canvas", "canvas", "canvas", "#efe9dc", { depth: 0.55, absorption: 0.35, permeability: 0.25, roughness: 0.6 }),
2844
+ preset("fine-linen", "Fine linen", "canvas", "linen", "#e9e2d2", { depth: 0.45, absorption: 0.3, permeability: 0.25, roughness: 0.5 }),
2845
+ preset("gesso", "Gesso panel", "panel", "gesso", "#f6f4ef", { depth: 0.35, absorption: 0.2, permeability: 0.15, roughness: 0.4 }),
2846
+ preset("smooth", "Smooth bristol", "smooth", "smooth", "#ffffff", { depth: 0, absorption: 0.3, permeability: 0.2, roughness: 0.05, shading: 0 }),
2847
+ // Backlit: smooth paper on a lightbox, for glazes that glow like stained glass.
2848
+ preset("stained-glass", "Stained glass (backlit)", "smooth", "smooth", "#ffffff", { depth: 0, absorption: 0.35, permeability: 0.25, roughness: 0.05, shading: 0, backlight: 0.8, backlightColor: "#fff1d6" })
2849
+ ];
2850
+ var DEFAULT_PAPER = PAPER_LIBRARY[0];
2851
+ function paperPreset(id) {
2852
+ const p = PAPER_LIBRARY.find((x) => x.preset === id);
2853
+ return p ? clonePaper(p) : void 0;
2854
+ }
2855
+ function clonePaper(p) {
2856
+ return { ...p, dry: { ...p.dry }, wet: { ...p.wet }, ...p.offset ? { offset: { ...p.offset } } : {} };
2857
+ }
2858
+ function readOffset(raw, d) {
2859
+ const o = raw && typeof raw === "object" ? raw : null;
2860
+ const x = o && typeof o.x === "number" && Number.isFinite(o.x) ? Math.round(o.x) : d?.x ?? 0;
2861
+ const y = o && typeof o.y === "number" && Number.isFinite(o.y) ? Math.round(o.y) : d?.y ?? 0;
2862
+ return x || y ? { offset: { x, y } } : {};
2863
+ }
2864
+ function readTuning(raw, d) {
2865
+ const r = raw && typeof raw === "object" ? raw : {};
2866
+ return { contrast: clampNum(r.contrast, 0, 3, d.contrast), invert: typeof r.invert === "boolean" ? r.invert : d.invert };
2867
+ }
2868
+ function normalizePaper(raw = {}, base) {
2869
+ const r = raw;
2870
+ const b = base ?? (typeof r.preset === "string" ? paperPreset(r.preset) : void 0) ?? clonePaper(DEFAULT_PAPER);
2871
+ return {
2872
+ preset: typeof r.preset === "string" && r.preset ? r.preset : b.preset,
2873
+ name: typeof r.name === "string" && r.name.trim() ? r.name.trim() : b.name,
2874
+ family: PAPER_FAMILIES.includes(r.family) ? r.family : b.family,
2875
+ pattern: GRAIN_PATTERNS.includes(r.pattern) ? r.pattern : b.pattern,
2876
+ seed: typeof r.seed === "number" && Number.isFinite(r.seed) ? Math.round(Math.abs(r.seed)) % 2147483647 : b.seed,
2877
+ color: typeof r.color === "string" && HEX.test(r.color) ? r.color.toLowerCase() : b.color,
2878
+ scale: clampNum(r.scale, 0.25, 8, b.scale),
2879
+ tiling: r.tiling === "repeat" || r.tiling === "mirror" ? r.tiling : b.tiling,
2880
+ depth: unit2(r.depth, b.depth),
2881
+ shading: unit2(r.shading, b.shading),
2882
+ dry: readTuning(r.dry, b.dry),
2883
+ wet: readTuning(r.wet, b.wet),
2884
+ absorption: unit2(r.absorption, b.absorption),
2885
+ permeability: unit2(r.permeability, b.permeability),
2886
+ roughness: unit2(r.roughness, b.roughness),
2887
+ ...unit2(r.metallic, b.metallic ?? 0) > 0 ? { metallic: unit2(r.metallic, b.metallic ?? 0) } : {},
2888
+ ...unit2(r.backlight, b.backlight ?? 0) > 0 ? { backlight: unit2(r.backlight, b.backlight ?? 0) } : {},
2889
+ ...typeof r.backlightColor === "string" && HEX.test(r.backlightColor) ? { backlightColor: r.backlightColor.toLowerCase() } : b.backlightColor ? { backlightColor: b.backlightColor } : {},
2890
+ ...readOffset(r.offset, b.offset)
2891
+ };
2892
+ }
2893
+ function hexToRgb8(hex) {
2894
+ const n = parseInt(hex.slice(1, 7), 16);
2895
+ return [n >> 16 & 255, n >> 8 & 255, n & 255];
2896
+ }
2897
+ function renderPaper(paper, rect, grain = new PaperGrain(paper), light) {
2898
+ const [r, g, b] = hexToRgb8(paper.color);
2899
+ const out = new Uint8ClampedArray(rect.width * rect.height * 4);
2900
+ const shade = grain.flat ? 0 : paper.shading * 0.16;
2901
+ const metal = light ? paper.metallic ?? 0 : 0;
2902
+ let hx = 0;
2903
+ let hy = 0;
2904
+ let hz = 1;
2905
+ if (metal > 0 && light) {
2906
+ const az = light.azimuth * Math.PI / 180;
2907
+ const el = light.elevation * Math.PI / 180;
2908
+ const lx = Math.cos(el) * Math.sin(az);
2909
+ const ly = -Math.cos(el) * Math.cos(az);
2910
+ const lz = Math.sin(el) + 1;
2911
+ const n = Math.hypot(lx, ly, lz);
2912
+ hx = lx / n;
2913
+ hy = ly / n;
2914
+ hz = lz / n;
2915
+ }
2916
+ for (let y = 0; y < rect.height; y++) {
2917
+ for (let x = 0; x < rect.width; x++) {
2918
+ const i = (y * rect.width + x) * 4;
2919
+ const px = rect.x + x + 0.5;
2920
+ const py = rect.y + y + 0.5;
2921
+ const k = shade ? 1 - shade * (1 - grain.at(px, py)) : 1;
2922
+ let spec = 0;
2923
+ if (metal > 0) {
2924
+ const gx = (grain.at(px + 1, py) - grain.at(px - 1, py)) * 4;
2925
+ const gy = (grain.at(px, py + 1) - grain.at(px, py - 1)) * 4;
2926
+ const nl = Math.hypot(gx, gy, 1);
2927
+ const nh = Math.max(0, (-gx * hx - gy * hy + hz) / nl);
2928
+ spec = metal * Math.pow(nh, 24) * 0.9;
2929
+ }
2930
+ out[i] = Math.min(255, r * k * (1 - 0.25 * metal) + spec * (r * 0.6 + 102));
2931
+ out[i + 1] = Math.min(255, g * k * (1 - 0.25 * metal) + spec * (g * 0.6 + 102));
2932
+ out[i + 2] = Math.min(255, b * k * (1 - 0.25 * metal) + spec * (b * 0.6 + 102));
2933
+ out[i + 3] = 255;
2934
+ }
2935
+ }
2936
+ return out;
2937
+ }
2938
+
2939
+ // src/paint-editor/engine.ts
2940
+ function penOrientation(p) {
2941
+ if (typeof p.altitude === "number" && Number.isFinite(p.altitude)) {
2942
+ const altitude = Math.min(Math.PI / 2, Math.max(0, p.altitude));
2943
+ const azimuth = typeof p.azimuth === "number" && Number.isFinite(p.azimuth) ? p.azimuth : 0;
2944
+ return { altitude, azimuth };
2945
+ }
2946
+ const hasX = typeof p.tiltX === "number" && Number.isFinite(p.tiltX);
2947
+ const hasY = typeof p.tiltY === "number" && Number.isFinite(p.tiltY);
2948
+ if (!hasX && !hasY) return null;
2949
+ return tiltToOrientation(hasX ? p.tiltX : 0, hasY ? p.tiltY : 0);
2950
+ }
2951
+ function tiltToOrientation(tiltX, tiltY) {
2952
+ const clampT = (v2) => Math.min(89.999, Math.max(-89.999, v2));
2953
+ const tx = Math.tan(clampT(tiltX) * Math.PI / 180);
2954
+ const ty = Math.tan(clampT(tiltY) * Math.PI / 180);
2955
+ const r = Math.hypot(tx, ty);
2956
+ if (r < 1e-9) return { altitude: Math.PI / 2, azimuth: 0 };
2957
+ let azimuth = Math.atan2(ty, tx);
2958
+ if (azimuth < 0) azimuth += 2 * Math.PI;
2959
+ return { altitude: Math.atan(1 / r), azimuth };
2960
+ }
2961
+ var pressureOf = (p) => typeof p.pressure === "number" && Number.isFinite(p.pressure) ? Math.min(1, Math.max(0, p.pressure)) : 1;
2962
+ var PenSmoother = class {
2963
+ pos = null;
2964
+ pressure = null;
2965
+ a;
2966
+ ap;
2967
+ constructor(position, pressure) {
2968
+ this.a = 1 - Math.min(0.95, Math.max(0, position));
2969
+ this.ap = 1 - Math.min(0.95, Math.max(0, pressure));
2970
+ }
2971
+ push(p) {
2972
+ const pr = pressureOf(p);
2973
+ if (!this.pos) {
2974
+ this.pos = { x: p.x, y: p.y };
2975
+ this.pressure = pr;
2976
+ return p;
2977
+ }
2978
+ this.pos = { x: this.pos.x + (p.x - this.pos.x) * this.a, y: this.pos.y + (p.y - this.pos.y) * this.a };
2979
+ this.pressure = this.pressure + (pr - this.pressure) * this.ap;
2980
+ return { ...p, x: this.pos.x, y: this.pos.y, pressure: this.pressure };
2981
+ }
2982
+ /** Where the smoothed position is now (or `null` before the first sample). */
2983
+ get position() {
2984
+ return this.pos;
2985
+ }
2986
+ };
2987
+ var IDENTITY_COPY = { map: (p) => p, linear: [1, 0, 0, 1] };
2988
+ var FULL_SPEED = 2.5;
2989
+ var PenDabWalker = class {
2990
+ constructor(brush, seed = 0, linear = [1, 0, 0, 1]) {
2991
+ this.brush = brush;
2992
+ this.seed = seed;
2993
+ this.linear = linear;
2994
+ }
2995
+ brush;
2996
+ seed;
2997
+ linear;
2998
+ last = null;
2999
+ nextAt = 0;
3000
+ pendingFirst = null;
3001
+ index = 0;
3002
+ dir = 0;
3003
+ lastT = null;
3004
+ firstT = null;
3005
+ speed = null;
3006
+ travelled = 0;
3007
+ sample(p) {
3008
+ const o = penOrientation(p);
3009
+ let speed = null;
3010
+ let time = null;
3011
+ if (this.last) this.travelled += Math.hypot(p.x - this.last.x, p.y - this.last.y);
3012
+ if (typeof p.t === "number" && Number.isFinite(p.t)) {
3013
+ if (this.firstT === null) this.firstT = p.t;
3014
+ time = p.t - this.firstT;
3015
+ if (this.last && this.lastT !== null && p.t > this.lastT) {
3016
+ const v2 = Math.hypot(p.x - this.last.x, p.y - this.last.y) / (p.t - this.lastT);
3017
+ this.speed = this.speed === null ? v2 : this.speed + (v2 - this.speed) * 0.35;
3018
+ }
3019
+ this.lastT = p.t;
3020
+ speed = this.speed ?? 0;
3021
+ }
3022
+ return {
3023
+ x: p.x,
3024
+ y: p.y,
3025
+ pressure: pressureOf(p),
3026
+ lean: o ? 1 - o.altitude / (Math.PI / 2) : 0,
3027
+ azimuth: o ? o.azimuth : 0,
3028
+ twist: typeof p.twist === "number" && Number.isFinite(p.twist) ? p.twist : null,
3029
+ speed,
3030
+ travel: this.travelled,
3031
+ time
3032
+ };
3033
+ }
3034
+ diameter(s) {
3035
+ const tip = this.brush.tip;
3036
+ const dyn = this.brush.dynamics;
3037
+ let d = tip.size;
3038
+ if (tip.pressureSize) d *= dyn.minSize + (1 - dyn.minSize) * s.pressure;
3039
+ d *= 1 + dyn.tiltSize * s.lean * 1.5;
3040
+ if (s.speed !== null && dyn.velocitySize) d *= Math.max(0.05, 1 + dyn.velocitySize * Math.min(1, s.speed / FULL_SPEED) * (dyn.velocitySize < 0 ? 0.85 : 1));
3041
+ return d;
3042
+ }
3043
+ stepLen(s) {
3044
+ return Math.max(0.5, Math.max(1, this.diameter(s)) * Math.max(0.01, this.brush.tip.spacing));
3045
+ }
3046
+ /** A rasterizer angle (CCW, y up) mapped through this copy's linear part. */
3047
+ mapAngle(theta) {
3048
+ const [a, b, c, d] = this.linear;
3049
+ if (a === 1 && b === 0 && c === 0 && d === 1) return theta;
3050
+ const vx = Math.cos(theta);
3051
+ const vy = -Math.sin(theta);
3052
+ return Math.atan2(-(c * vx + d * vy), a * vx + b * vy);
3053
+ }
3054
+ dab(s) {
3055
+ const { tip, dynamics: dyn, rotation } = this.brush;
3056
+ const i = this.index++;
3057
+ const seed = this.seed;
3058
+ let diameter = this.diameter(s);
3059
+ if (dyn.sizeJitter) diameter *= Math.max(0.05, 1 + dyn.sizeJitter * randSigned(seed, i, 1 /* Size */));
3060
+ const base = tip.angle * Math.PI / 180;
3061
+ let angle;
3062
+ if (rotation === "stroke") angle = this.dir + base;
3063
+ else if (rotation === "barrel" && s.twist !== null) angle = this.mapAngle(base - s.twist * Math.PI / 180);
3064
+ else if (dyn.tiltRoundness > 0 && s.lean > 0.02) angle = this.mapAngle(base - s.azimuth);
3065
+ else angle = this.mapAngle(base);
3066
+ if (dyn.angleJitter) angle += dyn.angleJitter * Math.PI * randSigned(seed, i, 2 /* Angle */);
3067
+ let opacity = tip.pressureOpacity ? s.pressure : 1;
3068
+ opacity *= 1 - dyn.tiltOpacity * s.lean * 0.8;
3069
+ if (s.speed !== null && dyn.velocityOpacity) opacity *= Math.max(0, 1 + dyn.velocityOpacity * (Math.min(1, s.speed / FULL_SPEED) - 0.5));
3070
+ if (dyn.opacityJitter) opacity *= 1 - dyn.opacityJitter * (randSigned(seed, i, 3 /* Opacity */) * 0.5 + 0.5);
3071
+ const flow = tip.flow * (1 - dyn.pressureFlow + dyn.pressureFlow * s.pressure);
3072
+ let { x, y } = s;
3073
+ if (dyn.scatter) {
3074
+ const off = dyn.scatter * diameter * randSigned(seed, i, 4 /* Scatter */);
3075
+ x += Math.sin(this.dir) * off;
3076
+ y += Math.cos(this.dir) * off;
3077
+ }
3078
+ return {
3079
+ x,
3080
+ y,
3081
+ radius: Math.max(0.5, diameter / 2),
3082
+ alpha: Math.min(1, Math.max(0, flow)),
3083
+ opacity: Math.min(1, Math.max(0, opacity)),
3084
+ angle,
3085
+ roundness: Math.min(1, Math.max(0.01, tip.roundness * (1 - dyn.tiltRoundness * s.lean * 0.8))),
3086
+ pressure: s.pressure,
3087
+ direction: this.dir,
3088
+ index: i,
3089
+ travel: s.travel,
3090
+ time: s.time,
3091
+ lean: s.lean,
3092
+ speed: s.speed
3093
+ };
3094
+ }
3095
+ push(p, out) {
3096
+ const a = this.last;
3097
+ const s = this.sample(p);
3098
+ if (!a) {
3099
+ this.last = s;
3100
+ this.pendingFirst = s;
3101
+ this.nextAt = this.stepLen(s);
3102
+ return;
3103
+ }
3104
+ const dx = s.x - a.x;
3105
+ const dy = s.y - a.y;
3106
+ const len2 = Math.hypot(dx, dy);
3107
+ if (len2 > 1e-9) this.dir = Math.atan2(-dy, dx);
3108
+ if (this.pendingFirst) {
3109
+ out.push(this.dab(this.pendingFirst));
3110
+ this.pendingFirst = null;
3111
+ }
3112
+ if (len2 > 1e-9) {
3113
+ while (this.nextAt <= len2 + 1e-9) {
3114
+ const f = Math.min(1, this.nextAt / len2);
3115
+ const lerp4 = (u, v2) => u + (v2 - u) * f;
3116
+ const q = {
3117
+ x: a.x + dx * f,
3118
+ y: a.y + dy * f,
3119
+ pressure: lerp4(a.pressure, s.pressure),
3120
+ lean: lerp4(a.lean, s.lean),
3121
+ azimuth: lerpAngle(a.azimuth, s.azimuth, f),
3122
+ twist: a.twist !== null && s.twist !== null ? lerpDegrees(a.twist, s.twist, f) : s.twist,
3123
+ speed: a.speed !== null && s.speed !== null ? lerp4(a.speed, s.speed) : s.speed,
3124
+ travel: a.travel + this.nextAt,
3125
+ time: a.time !== null && s.time !== null ? lerp4(a.time, s.time) : s.time
3126
+ };
3127
+ out.push(this.dab(q));
3128
+ this.nextAt += this.stepLen(q);
3129
+ }
3130
+ this.nextAt -= len2;
3131
+ }
3132
+ this.last = s;
3133
+ }
3134
+ finish(out) {
3135
+ if (this.pendingFirst) {
3136
+ out.push(this.dab(this.pendingFirst));
3137
+ this.pendingFirst = null;
3138
+ }
3139
+ }
3140
+ };
3141
+ function lerpAngle(a, b, t) {
3142
+ let d = b - a;
3143
+ while (d > Math.PI) d -= 2 * Math.PI;
3144
+ while (d < -Math.PI) d += 2 * Math.PI;
3145
+ return a + d * t;
3146
+ }
3147
+ function lerpDegrees(a, b, t) {
3148
+ let d = b - a;
3149
+ while (d > 180) d -= 360;
3150
+ while (d < -180) d += 360;
3151
+ return a + d * t;
3152
+ }
3153
+ var DryStroke = class {
3154
+ constructor(brush, options) {
3155
+ this.brush = brush;
3156
+ this.options = options;
3157
+ this.stamp = brush.stamp ? stampSampler(brush.stamp, options.stampArt) : null;
3158
+ this.smoother = new PenSmoother(brush.tip.smoothing, brush.pressureSmoothing);
3159
+ this.copies = options.copies?.length ? options.copies : [IDENTITY_COPY];
3160
+ this.walkers = this.copies.map((c, i) => new PenDabWalker(brush, (options.seed ?? 0) + i * 7919 | 0, c.linear));
3161
+ this.depth = options.grain && !options.grain.flat ? Math.min(1, Math.max(0, options.paperDepth * brush.grain)) : 0;
3162
+ }
3163
+ brush;
3164
+ options;
3165
+ coverage = new CoverageMap();
3166
+ dabCount = 0;
3167
+ smoother;
3168
+ walkers;
3169
+ copies;
3170
+ depth;
3171
+ buf = new Float32Array(0);
3172
+ field = new Float32Array(0);
3173
+ lastRaw = null;
3174
+ lastFed = null;
3175
+ /** The stamp tip's shape, or `null` for the round computed tip. */
3176
+ stamp;
3177
+ /** Feeds raw pen samples; returns the document rectangles the new dabs touched. */
3178
+ push(points) {
3179
+ const dabs = [];
3180
+ for (const raw of points) {
3181
+ this.lastRaw = raw;
3182
+ const p = this.smoother.push(raw);
3183
+ this.lastFed = p;
3184
+ this.copies.forEach((c, i) => this.walkers[i].push(c.map(p), dabs));
3185
+ }
3186
+ return this.paint(dabs);
3187
+ }
3188
+ /** Ends the stroke: the smoothed path catches up with the last raw sample; a single tap paints one dab. */
3189
+ finish() {
3190
+ const dabs = [];
3191
+ const raw = this.lastRaw;
3192
+ const fed = this.lastFed;
3193
+ if (raw && fed && (raw.x !== fed.x || raw.y !== fed.y)) this.copies.forEach((c, i) => this.walkers[i].push(c.map({ ...raw, pressure: fed.pressure }), dabs));
3194
+ for (const w of this.walkers) w.finish(dabs);
3195
+ return this.paint(dabs);
3196
+ }
3197
+ paint(dabs) {
3198
+ const rects = [];
3199
+ const spray = this.brush.spray;
3200
+ const seed = this.options.seed ?? 0;
3201
+ for (const d of dabs) {
3202
+ if (!spray) {
3203
+ this.mark(d, d, rects);
3204
+ continue;
3205
+ }
3206
+ for (const drop of sprayDroplets(d, spray, seed)) this.mark(drop, d, rects);
3207
+ }
3208
+ return rects;
3209
+ }
3210
+ /** Lays one mark (a dab, or a spray droplet of dab `d`): the round tip or the stamp, the paper grain, effect paint. */
3211
+ mark(m, d, rects) {
3212
+ const hardness = this.brush.tip.hardness;
3213
+ const grain = this.options.grain;
3214
+ const rect = this.stamp ? stampDabRect(m) : dabRect(m, hardness);
3215
+ const n = rect.width * rect.height;
3216
+ if (this.buf.length < n) this.buf = new Float32Array(n);
3217
+ const vals = this.buf.subarray(0, n);
3218
+ if (this.stamp) rasterizeStampDab(m, this.stamp, d.index, rect, vals);
3219
+ else rasterizeDab(m, hardness, rect, vals);
3220
+ if (this.depth > 0 && grain) {
3221
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3222
+ const y = rect.y + yy + 0.5;
3223
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3224
+ if (vals[k] > 0) vals[k] *= grainCatch(grain.at(rect.x + xx + 0.5, y), this.depth, d.pressure);
3225
+ }
3226
+ }
3227
+ }
3228
+ let field = null;
3229
+ if (this.options.effect) {
3230
+ if (this.field.length < n * 3) this.field = new Float32Array(n * 3);
3231
+ field = this.field.subarray(0, n * 3);
3232
+ sampleEffectField(this.options.effect, rect, vals, field, d);
3233
+ }
3234
+ this.coverage.accumulate(rect, vals, m.opacity, null, field);
3235
+ rects.push(rect);
3236
+ this.dabCount++;
3237
+ }
3238
+ };
3239
+ function mixerTip(brush) {
3240
+ return { ...brush.tip, smoothing: 0, pressureSize: brush.tip.pressureSize };
3241
+ }
3242
+ function toStrokePoint(p) {
3243
+ return { x: p.x, y: p.y, pressure: pressureOf(p), ...typeof p.t === "number" ? { t: p.t } : {} };
3244
+ }
3245
+
3246
+ // src/paint-editor/dab-stroke.ts
3247
+ var GRADIENT_STEPS = 32;
3248
+ function multiColorPalette(mc, color2, secondary) {
3249
+ if (mc.colors.length >= 2) {
3250
+ return mc.colors.map((h) => {
3251
+ const n = parseInt(h.slice(1), 16);
3252
+ return [(n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255];
3253
+ });
3254
+ }
3255
+ return [[...color2], [...secondary]];
3256
+ }
3257
+ function soften(f, softness) {
3258
+ if (softness >= 1) return f;
3259
+ const w = Math.max(1e-3, softness);
3260
+ return Math.min(1, Math.max(0, (f - 0.5) / w + 0.5));
3261
+ }
3262
+ function mixRgb(a, b, t, mixing) {
3263
+ if (t <= 0) return [...a];
3264
+ if (t >= 1) return [...b];
3265
+ if (mixing === "pigment") {
3266
+ const o = [0, 0, 0];
3267
+ const q = (v2) => Math.round(Math.min(1, Math.max(0, v2)) * 255);
3268
+ mixPigment8(q(a[0]), q(a[1]), q(a[2]), q(b[0]), q(b[1]), q(b[2]), t, o);
3269
+ return [o[0], o[1], o[2]];
3270
+ }
3271
+ return [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
3272
+ }
3273
+ function multiColorGradient(palette, softness, mixing) {
3274
+ const n = palette.length;
3275
+ const out = [];
3276
+ for (let j = 0; j < GRADIENT_STEPS; j++) {
3277
+ const f = j / (GRADIENT_STEPS - 1) * (n - 1);
3278
+ const i = Math.min(n - 2, Math.floor(f));
3279
+ out.push(mixRgb(palette[i], palette[i + 1], soften(f - i, softness), mixing));
3280
+ }
3281
+ return out;
3282
+ }
3283
+ function multiColorForDab(mc, palette, index, seed, mixing) {
3284
+ const n = palette.length;
3285
+ if (mc.order === "random") {
3286
+ const run = Math.floor(index / mc.length);
3287
+ return [...palette[Math.min(n - 1, Math.floor(rand01(seed, run, 11) * n))]];
3288
+ }
3289
+ const f = index / mc.length % n;
3290
+ const i = Math.floor(f);
3291
+ return mixRgb(palette[i], palette[(i + 1) % n], soften(f - i, mc.softness), mixing);
3292
+ }
3293
+ var PaintDabStroke = class {
3294
+ constructor(brush, options) {
3295
+ this.brush = brush;
3296
+ this.options = options;
3297
+ this.stamp = brush.engine === "dab" && brush.stamp ? stampSampler(brush.stamp, options.stampArt) : null;
3298
+ this.smoother = new PenSmoother(brush.tip.smoothing, brush.pressureSmoothing);
3299
+ this.copies = options.copies?.length ? options.copies : [IDENTITY_COPY];
3300
+ const exchanging = brush.engine === "mixer" || brush.engine === "dab";
3301
+ const rates = brush.engine === "mixer" ? mixerRates(brush.mixer) : exchangeRates(brush.behavior.pickup, brush.behavior.mix, 1, brush.behavior.mixing);
3302
+ this.mixing = brush.engine === "mixer" ? brush.mixer.mixing : brush.behavior.mixing;
3303
+ this.states = this.copies.map((c, i) => ({
3304
+ walker: new PenDabWalker(brush, (options.seed ?? 0) + i * 7919 | 0, c.linear),
3305
+ exchange: exchanging ? new PaintExchange(rates, options.load) : null,
3306
+ smudge: brush.engine === "smudge" ? new SmudgeTip(brush.smudge, brush.tip.size * (1 + brush.dynamics.tiltSize * 1.5)) : null
3307
+ }));
3308
+ this.medium = new TileMedium(options.target, brush.engine === "dab" ? { blend: brush.tip.blend } : {});
3309
+ this.depth = options.grain && !options.grain.flat ? Math.min(1, Math.max(0, options.paperDepth * brush.grain)) : 0;
3310
+ this.coverage = brush.engine === "dab" ? new CoverageMap() : null;
3311
+ this.sampler = exchanging && options.paint ? new PaintGradientSampler(options.paint, options.seed ?? 0) : null;
3312
+ const table = this.sampler?.acrossTip ? this.sampler.tipTable(GRADIENT_STEPS) : null;
3313
+ this.gradient = table ? table.map((e) => e.rgb) : null;
3314
+ this.gradientAlpha = table && table.some((e) => e.alpha < 1) ? table.map((e) => e.alpha) : null;
3315
+ this.scratch = brush.engine === "blender" ? createBlenderScratch() : null;
3316
+ }
3317
+ brush;
3318
+ options;
3319
+ dabCount = 0;
3320
+ smoother;
3321
+ copies;
3322
+ states;
3323
+ medium;
3324
+ depth;
3325
+ coverage;
3326
+ sampler;
3327
+ sample = { rgb: [0, 0, 0], alpha: 1 };
3328
+ gradient;
3329
+ /** Opacity across the tip (`across-tip` gradients with opacity stops), or `null`. */
3330
+ gradientAlpha;
3331
+ alphaCov = new Float32Array(0);
3332
+ fieldLut = [];
3333
+ scratch;
3334
+ mixing;
3335
+ tip = new Float32Array(0);
3336
+ cov = new Float32Array(0);
3337
+ field = new Float32Array(0);
3338
+ paint = [0, 0, 0];
3339
+ lastRaw = null;
3340
+ lastFed = null;
3341
+ /** The stamp tip's shape (dab brushes), or `null` for the round computed tip. */
3342
+ stamp;
3343
+ /** What copy 0's brush carries after the dabs so far (mixer and wet-capable dab brushes). */
3344
+ get load() {
3345
+ return this.states[0].exchange?.load ?? null;
3346
+ }
3347
+ push(points) {
3348
+ const rects = [];
3349
+ for (const raw of points) {
3350
+ this.lastRaw = raw;
3351
+ const p = this.smoother.push(raw);
3352
+ this.lastFed = p;
3353
+ this.copies.forEach((c, i) => {
3354
+ const dabs = [];
3355
+ this.states[i].walker.push(c.map(p), dabs);
3356
+ this.paintDabs(i, dabs, rects);
3357
+ });
3358
+ }
3359
+ return rects;
3360
+ }
3361
+ /** Ends the stroke: the smoothed path catches up with the last raw sample; a tap paints one dab. */
3362
+ finish() {
3363
+ const rects = [];
3364
+ const raw = this.lastRaw;
3365
+ const fed = this.lastFed;
3366
+ this.copies.forEach((c, i) => {
3367
+ const dabs = [];
3368
+ if (raw && fed && (raw.x !== fed.x || raw.y !== fed.y)) this.states[i].walker.push(c.map({ ...raw, pressure: fed.pressure }), dabs);
3369
+ this.states[i].walker.finish(dabs);
3370
+ this.paintDabs(i, dabs, rects);
3371
+ });
3372
+ return rects;
3373
+ }
3374
+ paintDabs(copy, dabs, rects) {
3375
+ const spray = this.brush.engine === "dab" ? this.brush.spray : null;
3376
+ for (const d of spray ? dabs.flatMap((dab) => sprayDroplets(dab, spray, (this.options.seed ?? 0) + copy * 7919)) : dabs) {
3377
+ const rect = this.stamp ? stampDabRect(d) : dabRect(d, this.brush.tip.hardness);
3378
+ if (rect.width <= 0 || rect.height <= 0) continue;
3379
+ this.dab(copy, d, rect);
3380
+ rects.push(rect);
3381
+ this.dabCount++;
3382
+ }
3383
+ }
3384
+ /** The tip's pure coverage (`tip`) and, with grain, what the paper catches of it (`cov`). */
3385
+ rasterize(d, rect) {
3386
+ const n = rect.width * rect.height;
3387
+ if (this.tip.length < n) {
3388
+ this.tip = new Float32Array(n);
3389
+ this.cov = new Float32Array(n);
3390
+ }
3391
+ const tip = this.tip.subarray(0, n);
3392
+ tip.fill(0);
3393
+ if (this.stamp) rasterizeStampDab({ ...d, alpha: 1 }, this.stamp, d.index, rect, tip);
3394
+ else rasterizeDab({ ...d, alpha: 1 }, this.brush.tip.hardness, rect, tip);
3395
+ if (!(this.depth > 0 && this.options.grain)) return { tip, cov: tip };
3396
+ const cov = this.cov.subarray(0, n);
3397
+ const grain = this.options.grain;
3398
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3399
+ const y = rect.y + yy + 0.5;
3400
+ for (let xx = 0; xx < rect.width; xx++, k++) cov[k] = tip[k] > 0 ? tip[k] * grainCatch(grain.at(rect.x + xx + 0.5, y), this.depth, d.pressure) : 0;
3401
+ }
3402
+ return { tip, cov };
3403
+ }
3404
+ dab(copy, d, rect) {
3405
+ const brush = this.brush;
3406
+ const { tip, cov } = this.rasterize(d, rect);
3407
+ const st = this.states[copy];
3408
+ if (brush.engine === "blender") {
3409
+ blenderDab(this.medium, rect, cov, d.opacity * d.alpha * brush.tip.opacity, d.radius, brush.blender, this.scratch);
3410
+ return;
3411
+ }
3412
+ if (brush.engine === "smudge") {
3413
+ st.smudge.dab(this.medium, { x: d.x, y: d.y, radius: d.radius, opacity: d.opacity * d.alpha * brush.tip.opacity }, rect, cov);
3414
+ return;
3415
+ }
3416
+ const ex = st.exchange;
3417
+ ex.pickUp(this.medium.sample(rect, tip));
3418
+ let flow = 1;
3419
+ if (this.options.effect) {
3420
+ const rgb = [0, 0, 0];
3421
+ flow = sampleEffectAt(this.options.effect, d.x, d.y, rgb, d);
3422
+ ex.setReservoirColor(rgb[0], rgb[1], rgb[2]);
3423
+ } else if (this.sampler && !this.gradient) {
3424
+ const g = this.sampler.dab(d, this.sample);
3425
+ ex.setReservoirColor(g.rgb[0], g.rgb[1], g.rgb[2]);
3426
+ flow = g.alpha;
3427
+ }
3428
+ let field = null;
3429
+ let total;
3430
+ let laid = cov;
3431
+ if (this.gradient) {
3432
+ total = this.tipField(ex, d, rect);
3433
+ field = this.field;
3434
+ if (this.gradientAlpha) laid = this.tipAlpha(d, rect, cov);
3435
+ } else total = ex.paint(this.paint);
3436
+ if (total > 0 && flow > 0) {
3437
+ if (this.coverage) this.depositWithCeiling(d, rect, laid, field, ex, flow);
3438
+ else {
3439
+ const dep = Math.min(1, total) * d.alpha * brush.tip.opacity * d.opacity * flow;
3440
+ if (dep > 0) this.medium.deposit(rect, laid, dep, this.paint, ex.paintPigment, field);
3441
+ }
3442
+ }
3443
+ ex.drain();
3444
+ }
3445
+ /** Fills `this.field` with the tip gradient (mixed with the carried paint) per pixel; returns the paint weight. */
3446
+ tipField(ex, d, rect) {
3447
+ const g = this.gradient;
3448
+ const lut = this.fieldLut;
3449
+ let total = 0;
3450
+ for (let j = 0; j < g.length; j++) {
3451
+ ex.setReservoirColor(g[j][0], g[j][1], g[j][2]);
3452
+ const out = lut[j] ?? [0, 0, 0];
3453
+ total = ex.paint(out);
3454
+ lut[j] = out;
3455
+ }
3456
+ const n = rect.width * rect.height;
3457
+ if (this.field.length < n * 3) this.field = new Float32Array(n * 3);
3458
+ const f = this.field;
3459
+ const nx = Math.sin(d.direction);
3460
+ const ny = Math.cos(d.direction);
3461
+ const r = Math.max(0.5, d.radius);
3462
+ const last = g.length - 1;
3463
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3464
+ const py = rect.y + yy + 0.5 - d.y;
3465
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3466
+ const u = ((rect.x + xx + 0.5 - d.x) * nx + py * ny) / r;
3467
+ const j = Math.min(last, Math.max(0, Math.round((u + 1) / 2 * last)));
3468
+ f[k * 3] = lut[j][0];
3469
+ f[k * 3 + 1] = lut[j][1];
3470
+ f[k * 3 + 2] = lut[j][2];
3471
+ }
3472
+ }
3473
+ return total;
3474
+ }
3475
+ /** `cov` scaled by the gradient's opacity across the tip. */
3476
+ tipAlpha(d, rect, cov) {
3477
+ const a = this.gradientAlpha;
3478
+ const n = rect.width * rect.height;
3479
+ if (this.alphaCov.length < n) this.alphaCov = new Float32Array(n);
3480
+ const out = this.alphaCov.subarray(0, n);
3481
+ const nx = Math.sin(d.direction);
3482
+ const ny = Math.cos(d.direction);
3483
+ const r = Math.max(0.5, d.radius);
3484
+ const last = a.length - 1;
3485
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3486
+ const py = rect.y + yy + 0.5 - d.y;
3487
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3488
+ const u = ((rect.x + xx + 0.5 - d.x) * nx + py * ny) / r;
3489
+ out[k] = cov[k] * a[Math.min(last, Math.max(0, Math.round((u + 1) / 2 * last)))];
3490
+ }
3491
+ }
3492
+ return out;
3493
+ }
3494
+ /** A dab brush's deposit: only what this dab adds to the stroke's coverage, under its opacity ceiling. */
3495
+ depositWithCeiling(d, rect, cov, field, ex, flow = 1) {
3496
+ const map = this.coverage;
3497
+ const n = rect.width * rect.height;
3498
+ const before = new Float32Array(n);
3499
+ const vals = new Float32Array(n);
3500
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3501
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3502
+ if (cov[k] <= 0) continue;
3503
+ before[k] = map.get(rect.x + xx, rect.y + yy);
3504
+ vals[k] = cov[k] * d.alpha * flow;
3505
+ }
3506
+ }
3507
+ map.accumulate(rect, vals, d.opacity);
3508
+ const o = this.brush.tip.opacity;
3509
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3510
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3511
+ if (cov[k] <= 0) {
3512
+ vals[k] = 0;
3513
+ continue;
3514
+ }
3515
+ const c0 = before[k] * o;
3516
+ const c1 = map.get(rect.x + xx, rect.y + yy) * o;
3517
+ vals[k] = c1 > c0 && c0 < 1 ? (c1 - c0) / (1 - c0) : 0;
3518
+ }
3519
+ }
3520
+ this.medium.deposit(rect, vals, 1, this.paint, ex.paintPigment, field);
3521
+ }
3522
+ };
3523
+
3524
+ // src/paint-editor/wet.ts
3525
+ var STROKE_WATER = 0.9;
3526
+ var STROKE_MASS = PIGMENT_UNIT * 2.5;
3527
+ var STROKE_LIGHT = 1.5;
3528
+ var COVERAGE_STEPS = 4096;
3529
+ function union(a, b) {
3530
+ if (!a) return { ...b };
3531
+ const x = Math.min(a.x, b.x);
3532
+ const y = Math.min(a.y, b.y);
3533
+ return { x, y, width: Math.max(a.x + a.width, b.x + b.width) - x, height: Math.max(a.y + a.height, b.y + b.height) - y };
3534
+ }
3535
+ function wetPaperInput(paper) {
3536
+ const grain = new PaperGrain(paper, "wet");
3537
+ const flat = grain.flat;
3538
+ return {
3539
+ absorption: paper.absorption,
3540
+ permeability: paper.permeability,
3541
+ roughness: flat ? 0 : paper.roughness,
3542
+ color: hexToRgb8(paper.color),
3543
+ heightAt: flat ? () => 0.5 : (x, y) => grain.at(x, y)
3544
+ };
3545
+ }
3546
+ var WetStrokeDriver = class {
3547
+ constructor(init) {
3548
+ this.init = init;
3549
+ const brush = init.brush;
3550
+ this.smoother = new PenSmoother(brush.tip.smoothing, brush.pressureSmoothing);
3551
+ const copies = init.copies.length ? init.copies : [IDENTITY_COPY];
3552
+ const wet = brush.wet;
3553
+ const spacing = Math.max(0.02, brush.tip.spacing);
3554
+ const perDab = Math.min(1, spacing * 1.2);
3555
+ const thin = wet.thinner;
3556
+ this.medium = new WetMedium(init.world, init.laneId, {
3557
+ water: STROKE_WATER * Math.min(1, wet.water * (1 + thin)) * perDab,
3558
+ mass: STROKE_MASS * wet.pigment * (1 - 0.6 * thin) * perDab,
3559
+ body: wet.body * (1 - thin),
3560
+ light: 0
3561
+ });
3562
+ this.lightBase = wet.tool === "paint" ? STROKE_LIGHT * brush.light.amount * (1 - 0.6 * thin) * perDab : 0;
3563
+ const rates = exchangeRates(brush.behavior.pickup, brush.behavior.mix, wet.load, brush.behavior.mixing);
3564
+ this.states = copies.map((c, i) => ({
3565
+ walker: new PenDabWalker(brush, init.seed + i * 7919 | 0, c.linear),
3566
+ exchange: wet.tool === "paint" ? new PaintExchange(rates, init.load) : null,
3567
+ last: null
3568
+ }));
3569
+ this.copies = copies;
3570
+ this.depth = init.grain && !init.grain.flat ? Math.min(1, Math.max(0, init.paperDepth * brush.grain)) : 0;
3571
+ const g = init.paint ?? null;
3572
+ this.sampler = g ? new PaintGradientSampler(g.map.by === "across-tip" ? { ...g, map: { by: "distance", length: 300, repeat: "mirror" } } : g, init.seed) : null;
3573
+ }
3574
+ init;
3575
+ dabCount = 0;
3576
+ bounds = null;
3577
+ /** The world's clock at which each raw point was applied (recorded with the stroke). */
3578
+ steps = [];
3579
+ smoother;
3580
+ states;
3581
+ medium;
3582
+ queue = [];
3583
+ finishing = false;
3584
+ finished = false;
3585
+ lastRaw = null;
3586
+ lastFed = null;
3587
+ tip = new Float32Array(0);
3588
+ cov = new Float32Array(0);
3589
+ paint = [0, 0, 0];
3590
+ centre = [0, 0, 0];
3591
+ depth;
3592
+ lightBase;
3593
+ sampler;
3594
+ sample = { rgb: [0, 0, 0], alpha: 1 };
3595
+ copies;
3596
+ /** What copy 0's brush carries after the dabs so far. */
3597
+ get load() {
3598
+ return this.states[0].exchange?.load ?? null;
3599
+ }
3600
+ /** Whether every point (and the end) has been applied. */
3601
+ get done() {
3602
+ return this.finished;
3603
+ }
3604
+ /** Adds raw points; applies them now unless a batch is running. Returns where pixels changed. */
3605
+ push(points) {
3606
+ for (const p of points) this.queue.push(p);
3607
+ return this.flush();
3608
+ }
3609
+ /** Asks for the end; it happens now unless a batch is running (then at the next `flush`). */
3610
+ finish() {
3611
+ this.finishing = true;
3612
+ return this.flush();
3613
+ }
3614
+ /** Applies waiting points (and the end, when asked) if the world is between batches. */
3615
+ flush() {
3616
+ const rects = [];
3617
+ if (this.init.world.busy || this.finished) return rects;
3618
+ while (this.queue.length) {
3619
+ const raw = this.queue.shift();
3620
+ this.steps.push(this.init.world.clock);
3621
+ this.lastRaw = raw;
3622
+ const p = this.smoother.push(raw);
3623
+ this.lastFed = p;
3624
+ this.copies.forEach((c, i) => {
3625
+ const dabs = [];
3626
+ this.states[i].walker.push(c.map(p), dabs);
3627
+ this.applyDabs(i, dabs, rects);
3628
+ });
3629
+ }
3630
+ if (this.finishing) {
3631
+ const raw = this.lastRaw;
3632
+ const fed = this.lastFed;
3633
+ this.copies.forEach((c, i) => {
3634
+ const dabs = [];
3635
+ if (raw && fed && (raw.x !== fed.x || raw.y !== fed.y)) this.states[i].walker.push(c.map({ ...raw, pressure: fed.pressure }), dabs);
3636
+ this.states[i].walker.finish(dabs);
3637
+ this.applyDabs(i, dabs, rects);
3638
+ });
3639
+ this.finished = true;
3640
+ }
3641
+ for (const r of rects) this.bounds = union(this.bounds, r);
3642
+ return rects;
3643
+ }
3644
+ applyDabs(copy, dabs, rects) {
3645
+ for (const d of dabs) {
3646
+ const rect = dabRect(d, this.init.brush.tip.hardness);
3647
+ if (rect.width <= 0 || rect.height <= 0) continue;
3648
+ this.dab(copy, d, rect);
3649
+ rects.push(rect);
3650
+ this.dabCount++;
3651
+ }
3652
+ }
3653
+ /** The tip's coverage over `rect`, with the grain, quantised. */
3654
+ coverage(d, rect) {
3655
+ const n = rect.width * rect.height;
3656
+ if (this.tip.length < n) {
3657
+ this.tip = new Float32Array(n);
3658
+ this.cov = new Float32Array(n);
3659
+ }
3660
+ const tip = this.tip.subarray(0, n);
3661
+ const cov = this.cov.subarray(0, n);
3662
+ tip.fill(0);
3663
+ rasterizeDab({ ...d, alpha: 1 }, this.init.brush.tip.hardness, rect, tip);
3664
+ const grain = this.depth > 0 ? this.init.grain : null;
3665
+ const mask = this.init.mask;
3666
+ for (let yy = 0, k = 0; yy < rect.height; yy++) {
3667
+ for (let xx = 0; xx < rect.width; xx++, k++) {
3668
+ if (mask && tip[k] > 0) {
3669
+ const mx = rect.x + xx;
3670
+ const my = rect.y + yy;
3671
+ tip[k] *= mx >= 0 && my >= 0 && mx < mask.width && my < mask.height ? mask.data[my * mask.width + mx] / 255 : 0;
3672
+ }
3673
+ let v2 = tip[k];
3674
+ if (v2 > 0 && grain) v2 *= grainCatch(grain.at(rect.x + xx + 0.5, rect.y + yy + 0.5), this.depth, d.pressure);
3675
+ tip[k] = Math.round(tip[k] * COVERAGE_STEPS) / COVERAGE_STEPS;
3676
+ cov[k] = Math.round(v2 * COVERAGE_STEPS) / COVERAGE_STEPS;
3677
+ }
3678
+ }
3679
+ return { tip, cov };
3680
+ }
3681
+ dab(copy, d, rect) {
3682
+ const { world, laneId, brush } = this.init;
3683
+ const wet = brush.wet;
3684
+ const st = this.states[copy];
3685
+ const { tip, cov } = this.coverage(d, rect);
3686
+ const k = Math.round(Math.min(1, d.alpha * d.opacity * brush.tip.opacity) * COVERAGE_STEPS) / COVERAGE_STEPS;
3687
+ if (!(k > 0)) return;
3688
+ switch (wet.tool) {
3689
+ case "paint": {
3690
+ const ex = st.exchange;
3691
+ this.medium.options.light = this.lightBase * (brush.light.pressure ? d.pressure : 1);
3692
+ let flow = 1;
3693
+ const effect = this.init.effect;
3694
+ if (effect) {
3695
+ sampleEffectAt(effect, d.x, d.y, this.centre, d);
3696
+ ex.setReservoirColor(this.centre[0], this.centre[1], this.centre[2]);
3697
+ } else if (this.sampler) {
3698
+ const g = this.sampler.dab(d, this.sample);
3699
+ ex.setReservoirColor(g.rgb[0], g.rgb[1], g.rgb[2]);
3700
+ flow = g.alpha;
3701
+ }
3702
+ ex.pickUp(this.medium.sample(rect, tip));
3703
+ const total = ex.paint(this.paint);
3704
+ if (total > 0 && flow > 0 && effect) {
3705
+ const ec = cov.slice();
3706
+ const field = new Float32Array(ec.length * 3);
3707
+ effectDabField(effect, rect, ec, this.centre, this.paint, field, COVERAGE_STEPS, d);
3708
+ this.medium.deposit(rect, ec, Math.min(1, total) * k, this.paint, null, field);
3709
+ } else if (total > 0 && flow > 0) this.medium.deposit(rect, cov, Math.min(1, total) * k * flow, this.paint, null);
3710
+ else world.paint(laneId, rect, cov, this.medium.options.water * k, null);
3711
+ ex.drain();
3712
+ if (wet.rewet > 0) world.rewet(laneId, rect, cov, wet.rewet * k * 0.15, this.init.paperColor);
3713
+ break;
3714
+ }
3715
+ case "water": {
3716
+ world.paint(laneId, rect, cov, this.medium.options.water * k * (wet.water > 0 ? 1 : 0), null);
3717
+ if (wet.rewet > 0) world.rewet(laneId, rect, cov, wet.rewet * k * 0.15, this.init.paperColor);
3718
+ break;
3719
+ }
3720
+ case "dry":
3721
+ world.remove(laneId, rect, cov, wet.strength * 0.35 * k, 0, 0, wet.strength * 0.35 * k);
3722
+ break;
3723
+ case "blow": {
3724
+ const s = wet.strength * 0.08 * k;
3725
+ world.push(laneId, rect, cov, Math.cos(d.direction) * s, -Math.sin(d.direction) * s);
3726
+ break;
3727
+ }
3728
+ case "blend":
3729
+ world.blend(laneId, rect, cov, wet.strength * k);
3730
+ break;
3731
+ case "smudge": {
3732
+ if (st.last) world.drag(laneId, rect, cov, d.x - st.last.x, d.y - st.last.y, wet.strength * k);
3733
+ break;
3734
+ }
3735
+ case "blot":
3736
+ world.remove(laneId, rect, cov, wet.strength * 0.8 * k, wet.strength * 0.6 * k, wet.strength * 0.15 * k, wet.strength * 0.5 * k);
3737
+ break;
3738
+ }
3739
+ st.last = d;
3740
+ }
3741
+ };
3742
+ var WET_MEDIUM_PARAMS = {
3743
+ watercolor: {},
3744
+ gouache: { viscosity: 0.45, evaporation: 0.1, edgeDarkening: 0.15, granulation: 0.1, bloom: 0.1, bleed: 0.15, pickup: 0.5, pigmentWeight: 0.5 },
3745
+ oil: { viscosity: 0.95, evaporation: 0.03, edgeDarkening: 0, granulation: 0, bloom: 0, bleed: 0.08, pickup: 0.6, fixture: 0.02, pigmentWeight: 0.8 }
3746
+ };
3747
+ var WET_GPU_MODES = ["auto", "off"];
3748
+ var GPU_LEAD = 16;
3749
+ var DISPLAY_TILES_PER_TICK = 24;
3750
+ var PaintWetLayers = class {
3751
+ constructor(host, options = {}) {
3752
+ this.host = host;
3753
+ this.options = options;
3754
+ this.speed = Math.max(1, Math.min(2e3, options.speed ?? 120));
3755
+ this.undoMemory = Math.max(0, options.undoMemory ?? 512 * 1024 * 1024);
3756
+ this.gpuMode = options.gpu === "off" ? "off" : "auto";
3757
+ this.gpuMinTiles = Math.max(1, Math.floor(options.gpuMinTiles ?? 16));
3758
+ }
3759
+ host;
3760
+ options;
3761
+ world = null;
3762
+ tilt = { ...FLAT };
3763
+ settings = /* @__PURE__ */ new Map();
3764
+ paused = false;
3765
+ /** Wet strokes dry as soon as they end (one undo step with the stroke). */
3766
+ instantDry = false;
3767
+ speed;
3768
+ overlay = false;
3769
+ undoMemory;
3770
+ /** The live wet stroke, if any. */
3771
+ driver = null;
3772
+ lastTick = null;
3773
+ ticking = null;
3774
+ stepsOwed = 0;
3775
+ displaying = null;
3776
+ leadAt = 0;
3777
+ gpuMode;
3778
+ gpuMinTiles;
3779
+ gpu = null;
3780
+ gpuSupport = null;
3781
+ gpuStarting = null;
3782
+ // --- Engine B ------------------------------------------------------------------
3783
+ /** Starts the GPU engine for the world (once; it may turn out unavailable). */
3784
+ startGpu() {
3785
+ if (this.gpuMode === "off" || this.gpu || this.gpuStarting || this.gpuSupport) return;
3786
+ const provider = this.options.gpuProvider === void 0 ? findWebGpu() : this.options.gpuProvider;
3787
+ this.gpuStarting = createWetGpuEngine(provider).then(({ engine, support }) => {
3788
+ this.gpuSupport = support;
3789
+ if (!engine) return;
3790
+ if (this.gpuMode === "off" || !this.world) {
3791
+ engine.destroy();
3792
+ this.gpuSupport = null;
3793
+ return;
3794
+ }
3795
+ this.gpu = engine;
3796
+ this.world.gpuMinTiles = this.gpuMinTiles;
3797
+ this.world.attachGpu(engine);
3798
+ }).finally(() => {
3799
+ this.gpuStarting = null;
3800
+ this.host.changed();
3801
+ });
3802
+ }
3803
+ /** Resolves once the GPU engine has started or turned out unavailable. */
3804
+ async gpuReady() {
3805
+ if (this.gpuStarting) await this.gpuStarting;
3806
+ return this.engineInfo();
3807
+ }
3808
+ /** `auto`: use the GPU for large wet areas when there is one; `off`: the CPU only. */
3809
+ setGpu(mode, minTiles) {
3810
+ if (minTiles !== void 0) {
3811
+ this.gpuMinTiles = Math.max(1, Math.floor(minTiles));
3812
+ if (this.world) this.world.gpuMinTiles = this.gpuMinTiles;
3813
+ }
3814
+ if (mode === this.gpuMode) return this.engineInfo();
3815
+ this.gpuMode = mode;
3816
+ if (mode === "off") {
3817
+ this.world?.attachGpu(null);
3818
+ this.gpu?.destroy();
3819
+ this.gpu = null;
3820
+ this.gpuSupport = null;
3821
+ } else if (this.world) this.startGpu();
3822
+ return this.engineInfo();
3823
+ }
3824
+ engineInfo() {
3825
+ const w = this.world;
3826
+ const base = { mode: this.gpuMode, adapter: this.gpuSupport?.adapter ?? null, maxTiles: this.gpuSupport?.maxSlots ?? 0, minTiles: this.gpuMinTiles, activeTiles: w?.activeTiles() ?? 0, cpu: this.backend() };
3827
+ if (this.gpuMode === "off") return { ...base, state: "off", reason: "Forced to the CPU." };
3828
+ if (this.gpuStarting) return { ...base, state: "starting", reason: null };
3829
+ if (w?.gpuError) return { ...base, state: "failed", reason: w.gpuError };
3830
+ if (this.gpuSupport && !this.gpuSupport.supported) return { ...base, state: "unavailable", reason: this.gpuSupport.reason };
3831
+ if (!this.gpu) return { ...base, state: "not-started", reason: "Starts with the first wet stroke." };
3832
+ if (w?.gpuActive) return { ...base, state: "active", reason: null };
3833
+ return { ...base, state: "standby", reason: `The GPU takes over at ${this.gpuMinTiles} wet tiles (256 px).` };
3834
+ }
3835
+ /** The world (made on first use, at the canvas size). */
3836
+ ensureWorld() {
3837
+ const { width, height } = this.host.canvas();
3838
+ if (this.world && (this.world.width !== width || this.world.height !== height)) {
3839
+ if (this.world.laneIds().length) throw new Error("The wet world is the wrong size; dry the paint before resizing the canvas.");
3840
+ this.dropWorld();
3841
+ }
3842
+ if (!this.world) this.world = this.makeWorld(width, height, this.host.paper());
3843
+ return this.world;
3844
+ }
3845
+ makeWorld(width, height, paper) {
3846
+ const world = new WetWorld(width, height, wetPaperInput(paper), { kernel: this.options.kernel, threads: this.options.threads });
3847
+ world.setTilt(this.tilt);
3848
+ world.gpuMinTiles = this.gpuMinTiles;
3849
+ if (this.gpu) world.attachGpu(this.gpu);
3850
+ else this.startGpu();
3851
+ return world;
3852
+ }
3853
+ /**
3854
+ * Whether `extend` can keep the wet paint when the canvas grows by `left` / `top` on those
3855
+ * sides: the shift has to be whole wet tiles (256 px), and no wet stroke may be live.
3856
+ */
3857
+ canExtend(left2, top) {
3858
+ return left2 % WET_TILE === 0 && top % WET_TILE === 0 && !this.driver;
3859
+ }
3860
+ /**
3861
+ * Keeps the wet paint while the canvas grows to `width`×`height` by `left` / `top` on those
3862
+ * sides (`canExtend` must hold): the world is made again at the new size with every wet layer
3863
+ * moved by (left, top), still wet, its base and flow map with it; `paper` is the new
3864
+ * document's paper (its grain moved with the paint). Wet settings' flow centres move too. The
3865
+ * caller shows the layers again (`syncDisplays`) once the document is the new size.
3866
+ */
3867
+ extend(width, height, left2, top, paper) {
3868
+ if (!this.canExtend(left2, top)) throw new Error("Wet paint only moves by whole 256 px tiles, between strokes.");
3869
+ for (const [id, s] of this.settings) if (s.flow.center) this.settings.set(id, { ...s, flow: { ...s.flow, center: { x: s.flow.center.x + left2, y: s.flow.center.y + top } } });
3870
+ const old = this.world;
3871
+ const snap = old?.laneIds().length ? old.snapshot() : null;
3872
+ this.dropWorld();
3873
+ this.lastTick = null;
3874
+ this.stepsOwed = 0;
3875
+ if (!old || !snap) return;
3876
+ const moved = moveWetSnapshot(snap, old, { width, height }, left2, top, (l) => {
3877
+ const flow = this.settings.get(l.id)?.flow;
3878
+ return {
3879
+ base: translateSurface(l.base, left2, top),
3880
+ ...l.light ? { light: translateSurface(l.light, left2, top) } : {},
3881
+ flow: l.flow && flow && flow.kind !== "none" ? flowField(flow, width, height) : l.flow
3882
+ };
3883
+ });
3884
+ this.world = this.makeWorld(width, height, paper);
3885
+ this.world.restore(moved);
3886
+ }
3887
+ /** Whether any layer (or `layerId`) has wet paint. */
3888
+ isWet(layerId) {
3889
+ const w = this.world;
3890
+ if (!w) return false;
3891
+ if (layerId !== void 0) return w.hasLane(layerId) && w.isActive(layerId);
3892
+ return w.laneIds().some((id) => w.isActive(id));
3893
+ }
3894
+ /** Layers holding a wet layer (wet or drying). */
3895
+ wetLayerIds() {
3896
+ return this.world?.laneIds() ?? [];
3897
+ }
3898
+ /** Whether a batch is running (edits wait). */
3899
+ get busy() {
3900
+ return Boolean(this.world?.busy);
3901
+ }
3902
+ /** Resolves when no batch is running. */
3903
+ async idle() {
3904
+ while (this.ticking) await this.ticking;
3905
+ }
3906
+ settingsOf(layerId, medium = "watercolor") {
3907
+ let s = this.settings.get(layerId);
3908
+ if (!s) {
3909
+ s = { params: normalizeWetParams(WET_MEDIUM_PARAMS[medium], DEFAULT_WET_PARAMS), flow: { ...DEFAULT_FLOW } };
3910
+ this.settings.set(layerId, s);
3911
+ }
3912
+ return s;
3913
+ }
3914
+ /** Puts a layer in the world (its current pixels become the base under the wet paint). */
3915
+ ensureLane(layerId, medium) {
3916
+ const w = this.ensureWorld();
3917
+ if (!w.hasLane(layerId)) {
3918
+ const base = this.host.layerSurface(layerId) ?? new TiledSurface(4, /* @__PURE__ */ new Map(), 0);
3919
+ const s = this.settingsOf(layerId, medium);
3920
+ w.ensureLane(layerId, { params: s.params, base, light: this.host.layerLight(layerId) });
3921
+ const { width, height } = this.host.canvas();
3922
+ if (s.flow.kind !== "none") w.setFlow(layerId, flowField(s.flow, width, height), s.flow.strength);
3923
+ }
3924
+ return w;
3925
+ }
3926
+ setParams(layerId, update) {
3927
+ const s = this.settingsOf(layerId);
3928
+ s.params = normalizeWetParams(update, s.params);
3929
+ if (this.world?.hasLane(layerId)) this.world.setParams(layerId, s.params);
3930
+ return { ...s.params };
3931
+ }
3932
+ setFlow(layerId, update) {
3933
+ const s = this.settingsOf(layerId);
3934
+ s.flow = normalizeFlow(update, s.flow);
3935
+ if (this.world?.hasLane(layerId)) {
3936
+ const { width, height } = this.host.canvas();
3937
+ this.world.setFlow(layerId, flowField(s.flow, width, height), s.flow.strength);
3938
+ }
3939
+ return { ...s.flow };
3940
+ }
3941
+ setTilt(update) {
3942
+ this.tilt = normalizeTilt(update, this.tilt);
3943
+ this.world?.setTilt(this.tilt);
3944
+ return { ...this.tilt };
3945
+ }
3946
+ /** The paper changed. */
3947
+ paperChanged() {
3948
+ this.world?.setPaper(wetPaperInput(this.host.paper()));
3949
+ }
3950
+ /** A layer as tools describe it. */
3951
+ info(layerId) {
3952
+ const s = this.settingsOf(layerId);
3953
+ const st = this.world?.hasLane(layerId) ? this.world.stats(layerId) : null;
3954
+ return {
3955
+ layerId,
3956
+ wet: Boolean(st && st.wetCells > 0),
3957
+ wetCells: st?.wetCells ?? 0,
3958
+ wetBounds: st?.wetBounds ?? null,
3959
+ activeTiles: st?.activeTiles ?? 0,
3960
+ params: { ...s.params },
3961
+ flow: { ...s.flow }
3962
+ };
3963
+ }
3964
+ backend() {
3965
+ return this.world?.backend() ?? null;
3966
+ }
3967
+ /** Shows the current wet pixels (at most `maxTiles` reshaded per layer). */
3968
+ syncDisplays(maxTiles = Infinity) {
3969
+ const w = this.world;
3970
+ if (!w) return [];
3971
+ const surfaces = /* @__PURE__ */ new Map();
3972
+ const rects = [];
3973
+ for (const id of w.laneIds()) {
3974
+ const d = w.display(id, maxTiles);
3975
+ if (this.host.layerSurface(id) !== d.surface) surfaces.set(id, d.surface);
3976
+ rects.push(...d.changed);
3977
+ }
3978
+ this.syncLights();
3979
+ if (surfaces.size) this.host.updateSurfaces(surfaces, rects);
3980
+ return rects;
3981
+ }
3982
+ /** Like `syncDisplays`, shading on the GPU when Engine B is active (all stale tiles at once). */
3983
+ async syncDisplaysGpu(maxCpuTiles, lead = false) {
3984
+ const w = this.world;
3985
+ if (!w) return [];
3986
+ const surfaces = /* @__PURE__ */ new Map();
3987
+ const rects = [];
3988
+ for (const id of w.laneIds()) {
3989
+ const d = await w.displayGpu(id, maxCpuTiles, lead);
3990
+ if (!w.hasLane(id)) continue;
3991
+ if (this.host.layerSurface(id) !== d.surface) surfaces.set(id, d.surface);
3992
+ rects.push(...d.changed);
3993
+ }
3994
+ this.syncLights();
3995
+ if (surfaces.size) this.host.updateSurfaces(surfaces, rects);
3996
+ return rects;
3997
+ }
3998
+ /** Shows each wet layer's live light paint (the light under it with the wet light shaded in). */
3999
+ syncLights() {
4000
+ const w = this.world;
4001
+ if (!w) return;
4002
+ const lights = /* @__PURE__ */ new Map();
4003
+ for (const id of w.laneIds()) {
4004
+ const l = w.lightDisplay(id);
4005
+ if (l && this.host.layerLight(id) !== l) lights.set(id, l);
4006
+ }
4007
+ if (lights.size) this.host.updateLights(lights);
4008
+ }
4009
+ /** Drops the wet layers whose paint has all dried (they become ordinary pixel layers). */
4010
+ retireDry() {
4011
+ const w = this.world;
4012
+ if (!w) return;
4013
+ for (const id of w.laneIds()) {
4014
+ if (w.isActive(id) || this.driver?.init.laneId === id) continue;
4015
+ const base = w.getBase(id);
4016
+ const light = w.isLit(id) ? w.getLight(id) : null;
4017
+ w.removeLane(id);
4018
+ if (light && this.host.layerLight(id) !== light) this.host.updateLights(/* @__PURE__ */ new Map([[id, light]]));
4019
+ this.host.updateSurfaces(/* @__PURE__ */ new Map([[id, base]]), []);
4020
+ }
4021
+ }
4022
+ /**
4023
+ * Advances time by the wall clock (`now` in ms, e.g. `performance.now()`): `speed` steps per
4024
+ * second, at most `maxSteps` per call. Call it every frame; it does nothing while paused or dry.
4025
+ * Resolves when the steps are done and the display is up to date.
4026
+ */
4027
+ tick(now, maxSteps = 8) {
4028
+ if (this.ticking) {
4029
+ this.leadFrame(now);
4030
+ return this.ticking;
4031
+ }
4032
+ if (this.displaying) return this.displaying;
4033
+ const last = this.lastTick;
4034
+ this.lastTick = now;
4035
+ const w = this.world;
4036
+ if (!w || this.paused || last === null) {
4037
+ this.flushDriver();
4038
+ return Promise.resolve();
4039
+ }
4040
+ if (!w.isActive()) {
4041
+ this.flushDriver();
4042
+ this.retireDry();
4043
+ return Promise.resolve();
4044
+ }
4045
+ const lead = w.gpuActive && !this.driver;
4046
+ w.gpuLeadMode = lead;
4047
+ const most = lead ? Math.max(maxSteps, GPU_LEAD) : maxSteps;
4048
+ this.stepsOwed = Math.min(most * 4, this.stepsOwed + (now - last) / 1e3 * this.speed);
4049
+ const n = Math.min(most, Math.floor(this.stepsOwed));
4050
+ this.leadAt = now;
4051
+ if (n < 1) {
4052
+ this.flushDriver();
4053
+ return Promise.resolve();
4054
+ }
4055
+ this.stepsOwed -= n;
4056
+ const run = (async () => {
4057
+ try {
4058
+ await w.step(n);
4059
+ } finally {
4060
+ this.ticking = null;
4061
+ }
4062
+ this.flushDriver();
4063
+ if (w.gpuActive) {
4064
+ const shading = this.syncDisplaysGpu(DISPLAY_TILES_PER_TICK).then(() => void 0);
4065
+ this.displaying = shading;
4066
+ try {
4067
+ await shading;
4068
+ } finally {
4069
+ this.displaying = null;
4070
+ }
4071
+ } else this.syncDisplays(DISPLAY_TILES_PER_TICK);
4072
+ this.retireDry();
4073
+ this.host.changed();
4074
+ })();
4075
+ this.ticking = run;
4076
+ return run;
4077
+ }
4078
+ /** Lead mode: steps the GPU on by the time since the last frame (within the running batch) and shows it. */
4079
+ leadFrame(now) {
4080
+ const w = this.world;
4081
+ if (!w || this.displaying || this.driver || !w.gpuLeading) return;
4082
+ const k = Math.max(1, Math.round((now - this.leadAt) / 1e3 * this.speed));
4083
+ if (!w.gpuLead(k)) return;
4084
+ this.leadAt = now;
4085
+ const shading = this.syncDisplaysGpu(0, true).then(() => this.host.changed());
4086
+ this.displaying = shading;
4087
+ void shading.finally(() => {
4088
+ if (this.displaying === shading) this.displaying = null;
4089
+ });
4090
+ }
4091
+ flushDriver() {
4092
+ const d = this.driver;
4093
+ if (!d || !this.world) return;
4094
+ const rects = d.flush();
4095
+ if (rects.length) this.syncDisplays(DISPLAY_TILES_PER_TICK);
4096
+ if (d.done) this.onDriverDone?.(d);
4097
+ }
4098
+ /** Called when a live stroke that ended mid-batch has finished applying. */
4099
+ onDriverDone = null;
4100
+ /** Steps `steps` times now (agents, tests). Returns the steps run. */
4101
+ async advance(steps) {
4102
+ await this.idle();
4103
+ const w = this.world;
4104
+ if (!w) return 0;
4105
+ await w.ready;
4106
+ await this.idle();
4107
+ const start = w.clock;
4108
+ const n = Math.max(0, Math.floor(steps));
4109
+ const job = (async () => {
4110
+ try {
4111
+ await w.step(n);
4112
+ } finally {
4113
+ this.ticking = null;
4114
+ }
4115
+ })();
4116
+ this.ticking = job;
4117
+ await job;
4118
+ if (w.gpuActive) await this.syncDisplaysGpu(Infinity);
4119
+ else this.syncDisplays();
4120
+ this.retireDry();
4121
+ return w.clock - start;
4122
+ }
4123
+ /**
4124
+ * Dries at once (everything settles where it is), on one layer or all, optionally only in a
4125
+ * rectangle. Returns the layers and rectangles that dried.
4126
+ */
4127
+ dry(layerId, rect) {
4128
+ const w = this.world;
4129
+ if (!w) return [];
4130
+ const ids = layerId !== void 0 ? w.hasLane(layerId) ? [layerId] : [] : w.laneIds();
4131
+ const out = [];
4132
+ for (const id of ids) out.push({ layerId: id, bounds: w.dry(id, rect) });
4133
+ this.syncDisplays();
4134
+ this.retireDry();
4135
+ return out;
4136
+ }
4137
+ /** The layer's light paint with all its wet paint dried (`null` without a wet layer or light), without changing anything. */
4138
+ bakedLight(layerId) {
4139
+ const w = this.world;
4140
+ if (!w?.hasLane(layerId) || !w.isLit(layerId)) return null;
4141
+ return w.bakedLight(layerId);
4142
+ }
4143
+ /** The layer's pixels with all its wet paint dried (deterministic), without changing anything. */
4144
+ bakedSurface(layerId) {
4145
+ const w = this.world;
4146
+ if (!w?.hasLane(layerId)) return null;
4147
+ return w.bakedSurface(layerId);
4148
+ }
4149
+ /** A snapshot of the world for undo (`null` when there is none). */
4150
+ snapshot() {
4151
+ const w = this.world;
4152
+ if (!w || !w.laneIds().length) return null;
4153
+ return w.snapshot();
4154
+ }
4155
+ /** Puts a snapshot back (`null`: no wet layers). Returns the layer surfaces it implies. */
4156
+ restore(snap) {
4157
+ if (!snap) {
4158
+ if (this.world) for (const id of this.world.laneIds()) this.world.removeLane(id);
4159
+ return;
4160
+ }
4161
+ const { width, height } = this.host.canvas();
4162
+ if (this.world && (this.world.width !== width || this.world.height !== height)) this.dropWorld();
4163
+ this.ensureWorld().restore(snap);
4164
+ this.syncDisplays();
4165
+ }
4166
+ dropWorld() {
4167
+ this.world?.destroy();
4168
+ this.world = null;
4169
+ this.driver = null;
4170
+ }
4171
+ /** Forgets everything wet (a new canvas, a resize, opening a document). */
4172
+ reset() {
4173
+ this.world?.destroy();
4174
+ this.world = null;
4175
+ this.driver = null;
4176
+ this.settings.clear();
4177
+ this.lastTick = null;
4178
+ this.stepsOwed = 0;
4179
+ }
4180
+ /** Water overlay tiles (RGBA) over a document rectangle, for the view. */
4181
+ waterOverlay(rect) {
4182
+ const w = this.world;
4183
+ if (!w) return [];
4184
+ const out = [];
4185
+ const tx0 = Math.max(0, Math.floor(rect.x / TILE));
4186
+ const ty0 = Math.max(0, Math.floor(rect.y / TILE));
4187
+ const tx1 = Math.floor((rect.x + rect.width - 1) / TILE);
4188
+ const ty1 = Math.floor((rect.y + rect.height - 1) / TILE);
4189
+ for (let ty = ty0; ty <= ty1; ty++)
4190
+ for (let tx = tx0; tx <= tx1; tx++) {
4191
+ let merged = null;
4192
+ for (const id of w.laneIds()) {
4193
+ const t = w.waterOverlay(id, tx, ty);
4194
+ if (!t) continue;
4195
+ if (!merged) merged = t;
4196
+ else for (let i = 3; i < t.length; i += 4) merged[i] = Math.max(merged[i], t[i]);
4197
+ }
4198
+ if (merged) out.push({ tx, ty, data: merged });
4199
+ }
4200
+ return out;
4201
+ }
4202
+ destroy() {
4203
+ this.world?.destroy();
4204
+ this.world = null;
4205
+ this.gpu?.destroy();
4206
+ this.gpu = null;
4207
+ }
4208
+ };
4209
+ function wetPigmentOf(hex, body) {
4210
+ const [r, g, b] = hexToRgb8(hex);
4211
+ return Array.from(pigmentOf([r / 255, g / 255, b / 255], body));
4212
+ }
4213
+
4214
+ // src/vector/brushstrokeMedia.ts
4215
+ var VECTOR_WET_STEPS = 120;
4216
+ function vectorMediaEngine(brush) {
4217
+ if (brush.engine === "wet") return brush.wet.tool === "paint" ? "wet" : null;
4218
+ return brush.engine === "mixer" || brush.engine === "smudge" || brush.engine === "blender" ? brush.engine : null;
4219
+ }
4220
+ var usesVectorBackdrop = (engine) => engine === "mixer" || engine === "smudge" || engine === "blender";
4221
+ var finite2 = (v2) => typeof v2 === "number" && Number.isFinite(v2);
4222
+ function place(input, brush, options, pad = 0) {
4223
+ const samples = brushstrokeSamples(input);
4224
+ if (!samples.length) return null;
4225
+ for (const s of samples) if (!finite2(s.x) || !finite2(s.y)) throw new Error("Brushstroke samples need finite x and y.");
4226
+ let scale3 = finite2(options.scale) && options.scale > 0 ? Math.min(BRUSHSTROKE_MAX_SCALE, Math.max(BRUSHSTROKE_MIN_SCALE, options.scale)) : 1;
4227
+ let x0 = Infinity, y0 = Infinity, x1 = -Infinity, y1 = -Infinity;
4228
+ for (const s of samples) {
4229
+ x0 = Math.min(x0, s.x);
4230
+ y0 = Math.min(y0, s.y);
4231
+ x1 = Math.max(x1, s.x);
4232
+ y1 = Math.max(y1, s.y);
4233
+ }
4234
+ const reach = brush.tip.size * (1 + 1.5 * brush.dynamics.tiltSize) / 2 + 2 + pad;
4235
+ const maxPixels = finite2(options.maxPixels) && options.maxPixels > 0 ? options.maxPixels : 4096 * 4096;
4236
+ const area = (x1 - x0 + 2 * reach) * (y1 - y0 + 2 * reach);
4237
+ if (area * scale3 * scale3 > maxPixels) scale3 = Math.max(BRUSHSTROKE_MIN_SCALE, Math.sqrt(maxPixels / area));
4238
+ const rect = { x: Math.floor((x0 - reach) * scale3), y: Math.floor((y0 - reach) * scale3), width: 0, height: 0 };
4239
+ rect.width = Math.max(1, Math.ceil((x1 + reach) * scale3) - rect.x);
4240
+ rect.height = Math.max(1, Math.ceil((y1 + reach) * scale3) - rect.y);
4241
+ const points = samples.map((s) => ({ ...s, x: s.x * scale3 - rect.x, y: s.y * scale3 - rect.y }));
4242
+ if (options.closed && points.length > 2) points.push({ ...points[0] });
4243
+ const sized = { ...brush, pressureSmoothing: 0, tip: { ...brush.tip, size: brush.tip.size * scale3, smoothing: 0 } };
4244
+ const [r, g, b, a] = options.color;
4245
+ const hex = "#" + [r, g, b].map((v2) => Math.round(Math.min(255, Math.max(0, v2))).toString(16).padStart(2, "0")).join("");
4246
+ const source = options.paint ?? null;
4247
+ const paint = source?.type === "gradient" ? resolvePaintGradient(scalePaintGradient(source, scale3), { paint: hex, secondary: "#ffffff" }) : null;
4248
+ const color2 = source?.type === "color" ? hexRgb(source.color) : [r / 255, g / 255, b / 255];
4249
+ return { points, brush: sized, rect, scale: scale3, color: color2, alpha: Math.min(1, Math.max(0, a / 255)), paint };
4250
+ }
4251
+ function hexRgb(hex) {
4252
+ const n = parseInt(hex.slice(1), 16);
4253
+ return [(n >> 16 & 255) / 255, (n >> 8 & 255) / 255, (n & 255) / 255];
4254
+ }
4255
+ var EMPTY = { image: { width: 0, height: 0, data: new Uint8ClampedArray(0) }, bounds: null, scale: 1, dabs: 0 };
4256
+ function cropped(data, placed, dabs, keep) {
4257
+ const { width: w, height: h } = placed.rect;
4258
+ let cx0 = w, cy0 = h, cx1 = -1, cy1 = -1;
4259
+ for (let y = 0; y < h; y++) {
4260
+ for (let x = 0; x < w; x++) {
4261
+ const i = (y * w + x) * 4;
4262
+ if (keep ? !keep(i) : data[i + 3] === 0) continue;
4263
+ if (x < cx0) cx0 = x;
4264
+ if (x > cx1) cx1 = x;
4265
+ if (y < cy0) cy0 = y;
4266
+ if (y > cy1) cy1 = y;
4267
+ }
4268
+ }
4269
+ if (cx1 < 0) return { ...EMPTY, scale: placed.scale, dabs };
4270
+ const cw = cx1 - cx0 + 1;
4271
+ const ch = cy1 - cy0 + 1;
4272
+ const out = new Uint8ClampedArray(cw * ch * 4);
4273
+ for (let y = 0; y < ch; y++) {
4274
+ for (let x = 0; x < cw; x++) {
4275
+ const i = ((y + cy0) * w + x + cx0) * 4;
4276
+ if (keep && !keep(i)) continue;
4277
+ const o = (y * cw + x) * 4;
4278
+ out[o] = data[i];
4279
+ out[o + 1] = data[i + 1];
4280
+ out[o + 2] = data[i + 2];
4281
+ out[o + 3] = placed.alpha < 1 ? Math.round(data[i + 3] * placed.alpha) : data[i + 3];
4282
+ }
4283
+ }
4284
+ const s = placed.scale;
4285
+ return { image: { width: cw, height: ch, data: out }, bounds: { x: (placed.rect.x + cx0) / s, y: (placed.rect.y + cy0) / s, width: cw / s, height: ch / s }, scale: s, dabs };
4286
+ }
4287
+ var WetBrushstrokeJob = class {
4288
+ constructor(input, brush, options, steps = VECTOR_WET_STEPS) {
4289
+ this.steps = steps;
4290
+ if (vectorMediaEngine(brush) !== "wet") throw new Error(`'${brush.name}' is not a wet paint brush.`);
4291
+ this.placed = place(input, brush, options, brush.tip.size * 0.25);
4292
+ if (!this.placed) {
4293
+ this.world = null;
4294
+ this.dabs = 0;
4295
+ this.final = EMPTY;
4296
+ return;
4297
+ }
4298
+ const { rect, points } = this.placed;
4299
+ this.world = new WetWorld(rect.width, rect.height, wetPaperInput(DEFAULT_PAPER), { kernel: "typescript", threads: 0 });
4300
+ const medium = this.placed.brush.wet.medium ?? "watercolor";
4301
+ this.world.ensureLane("s", { params: WET_MEDIUM_PARAMS[medium] ?? {} });
4302
+ const color2 = this.placed.color;
4303
+ const driver = new WetStrokeDriver({
4304
+ world: this.world,
4305
+ laneId: "s",
4306
+ brush: this.placed.brush,
4307
+ color: color2,
4308
+ load: { reservoir: [...color2], amount: 1, pickup: null },
4309
+ grain: null,
4310
+ paperDepth: 0,
4311
+ paperColor: [255, 255, 255],
4312
+ seed: options.seed ?? 0,
4313
+ copies: [],
4314
+ paint: this.placed.paint
4315
+ });
4316
+ driver.push(points);
4317
+ driver.finish();
4318
+ this.dabs = driver.dabCount;
4319
+ }
4320
+ steps;
4321
+ world;
4322
+ placed;
4323
+ dabs;
4324
+ done = 0;
4325
+ final = null;
4326
+ /** Steps run so far. */
4327
+ get progress() {
4328
+ return this.done;
4329
+ }
4330
+ get finished() {
4331
+ return this.final !== null;
4332
+ }
4333
+ /** Runs steps until `budgetMs` has passed (at least one) or all have run. Returns whether it is finished. */
4334
+ run(budgetMs = Infinity) {
4335
+ if (this.final || !this.world) return true;
4336
+ const start = Date.now();
4337
+ while (this.done < this.steps) {
4338
+ this.world.stepSync(1);
4339
+ this.done++;
4340
+ if (Date.now() - start >= budgetMs) break;
4341
+ }
4342
+ if (this.done >= this.steps) {
4343
+ this.final = this.bake();
4344
+ this.destroy();
4345
+ }
4346
+ return this.final !== null;
4347
+ }
4348
+ /** The paint dried where it is now (step 0: as laid). */
4349
+ image() {
4350
+ return this.final ?? this.bake();
4351
+ }
4352
+ /** The settled image: runs the remaining steps now. */
4353
+ settled() {
4354
+ this.run();
4355
+ return this.final;
4356
+ }
4357
+ destroy() {
4358
+ this.world?.destroy();
4359
+ }
4360
+ bake() {
4361
+ if (!this.world || !this.placed) return EMPTY;
4362
+ const { width, height } = this.placed.rect;
4363
+ const data = readRegion(this.world.bakedSurface("s"), { x: 0, y: 0, width, height });
4364
+ return cropped(data, this.placed, this.dabs);
4365
+ }
4366
+ };
4367
+ function renderWetBrushstroke(input, brush, options) {
4368
+ return new WetBrushstrokeJob(input, brush, options).settled();
4369
+ }
4370
+ function vectorBackdropRect(input, brush, options) {
4371
+ const placed = place(input, brush, options);
4372
+ return placed ? { rect: placed.rect, scale: placed.scale } : null;
4373
+ }
4374
+ function renderBackdropBrushstroke(input, brush, options) {
4375
+ const engine = vectorMediaEngine(brush);
4376
+ if (!usesVectorBackdrop(engine)) throw new Error(`'${brush.name}' is not a Mixer Brush, smudge or blender.`);
4377
+ const placed = place(input, brush, options);
4378
+ if (!placed) return EMPTY;
4379
+ const { rect } = placed;
4380
+ const area = { x: 0, y: 0, width: rect.width, height: rect.height };
4381
+ const before = options.backdrop ? options.backdrop(rect, placed.scale) : new Uint8ClampedArray(rect.width * rect.height * 4);
4382
+ if (before.length !== rect.width * rect.height * 4) throw new Error(`The backdrop must be ${rect.width}\xD7${rect.height} RGBA pixels.`);
4383
+ const cached = options.cache?.(before);
4384
+ const hit = cached?.get();
4385
+ if (hit) return hit;
4386
+ const base = writeRegion(emptySurface(4), area, before);
4387
+ const live = /* @__PURE__ */ new Map();
4388
+ const target = {
4389
+ offset: { x: 0, y: 0 },
4390
+ lockTransparency: false,
4391
+ selection: null,
4392
+ readTile: (tx, ty) => live.get(tileKey(tx, ty)) ?? base.tiles.get(tileKey(tx, ty))?.data ?? null,
4393
+ writeTile: (tx, ty) => {
4394
+ const key = tileKey(tx, ty);
4395
+ let t = live.get(key);
4396
+ if (!t) live.set(key, t = base.tiles.get(key) ? new Uint8ClampedArray(base.tiles.get(key).data) : new Uint8ClampedArray(TILE * TILE * 4));
4397
+ return t;
4398
+ }
4399
+ };
4400
+ const color2 = placed.color;
4401
+ const load = placed.brush.engine === "mixer" && placed.brush.loadsColor ? loadMixer(EMPTY_MIXER_LOAD, color2) : EMPTY_MIXER_LOAD;
4402
+ const stroke = new PaintDabStroke(placed.brush, { target, color: color2, secondary: [1, 1, 1], load, grain: null, paperDepth: 0, seed: options.seed ?? 0, paint: placed.paint });
4403
+ stroke.push(placed.points);
4404
+ stroke.finish();
4405
+ const after = new Uint8ClampedArray(rect.width * rect.height * 4);
4406
+ const tiles = new Map(base.tiles);
4407
+ for (const [key, data] of live) tiles.set(key, { data, uniform: null });
4408
+ readRegion(new TiledSurface(4, tiles), area, after);
4409
+ const result = cropped(after, placed, stroke.dabCount, (i) => after[i] !== before[i] || after[i + 1] !== before[i + 1] || after[i + 2] !== before[i + 2] || after[i + 3] !== before[i + 3]);
4410
+ cached?.set(result);
4411
+ return result;
4412
+ }
4413
+
2537
4414
  // src/vector/brushstroke.ts
2538
4415
  var VECTOR_BRUSHSTROKE_SCALE = 2;
2539
4416
  var PRESETS = listPresets(VECTOR_PROFILE).map((spec) => BUILTIN_BRUSHES.find((b) => b.id === spec.id));
2540
4417
  function admitted(spec) {
2541
4418
  try {
2542
4419
  const brush = normalizeBrushSpec(spec);
2543
- return checkBrush(brush, VECTOR_PROFILE).ok && isBrushstrokeBrush(resolveBrush(brush)) ? brush : null;
4420
+ return checkBrush(brush, VECTOR_PROFILE).ok && isVectorBrushstrokeEngine(resolveBrush(brush)) ? brush : null;
2544
4421
  } catch {
2545
4422
  return null;
2546
4423
  }
2547
4424
  }
4425
+ function isVectorBrushstrokeEngine(brush) {
4426
+ return brush.engine === "dab" && isBrushstrokeBrush(brush) || vectorMediaEngine(brush) !== null;
4427
+ }
2548
4428
  function vectorBrushstrokeBrushes(user = []) {
2549
4429
  const out = [...PRESETS];
2550
4430
  for (const raw of user) {
@@ -2567,10 +4447,10 @@ function vectorBrushstrokeBrushError(id, user = []) {
2567
4447
  if (vectorBrushstrokeBrush(id)) return null;
2568
4448
  const saved = user.find((b) => b.id === id);
2569
4449
  const ids = vectorBrushstrokeBrushes(user).map((b) => b.id);
2570
- const reasons = (b) => checkBrush(b, VECTOR_PROFILE).issues.filter((i) => i.severity === "error").map((i) => `${i.reason} ${i.fix}`).join(" ") || "it is not a dry dab brush.";
4450
+ const reasons = (b) => checkBrush(b, VECTOR_PROFILE).issues.filter((i) => i.severity === "error").map((i) => `${i.reason} ${i.fix}`).join(" ") || "its engine does not paint brushstrokes.";
2571
4451
  if (saved) return admitted(saved) ? null : `Brush "${id}" (${saved.name}) can't paint a brushstroke: ${reasons(saved)} Use one of: ${ids.join(", ")}.`;
2572
- const preset = BRUSH_PRESETS.find((b) => b.id === id);
2573
- if (preset) return `Brush "${id}" (${preset.name}) can't paint a brushstroke: ${reasons(preset)} Use one of: ${ids.join(", ")}.`;
4452
+ const preset2 = BRUSH_PRESETS.find((b) => b.id === id);
4453
+ if (preset2) return `Brush "${id}" (${preset2.name}) can't paint a brushstroke: ${reasons(preset2)} Use one of: ${ids.join(", ")}.`;
2574
4454
  return `Unknown brush "${id}". ${closest(id, ids)}Use one of: ${ids.join(", ")} (vector.listBrushes lists them).`;
2575
4455
  }
2576
4456
  function vectorBrushstrokeDefaultColour(id, user = [], scheme = "light") {
@@ -2594,6 +4474,8 @@ function sanitizeVectorBrushstroke(value, user = []) {
2594
4474
  }
2595
4475
  const seed = sanitizeSeed(r.seed);
2596
4476
  if (seed !== void 0) out.seed = seed;
4477
+ const paint = readVectorBrushstrokePaint(r.paint);
4478
+ if (paint) out.paint = paint;
2597
4479
  if (r.paper === null) out.paper = null;
2598
4480
  else {
2599
4481
  const paper = sanitizeVectorBrushstrokePaper(r.paper);
@@ -2601,9 +4483,24 @@ function sanitizeVectorBrushstroke(value, user = []) {
2601
4483
  }
2602
4484
  return out;
2603
4485
  }
4486
+ var TIMED_MAPPINGS = ["velocity", "time"];
4487
+ function vectorBrushstrokePaintError(paint) {
4488
+ let source;
4489
+ try {
4490
+ source = parsePaintSource(paint, "paint");
4491
+ } catch (e) {
4492
+ return e.message;
4493
+ }
4494
+ if (source.type === "gradient" && TIMED_MAPPINGS.includes(source.map.by)) return `paint.map.by "${source.map.by}" needs timed samples, which vector paths do not have; use distance, pressure, tilt, direction, across-tip or random.`;
4495
+ return null;
4496
+ }
4497
+ function readVectorBrushstrokePaint(value) {
4498
+ if (value === void 0 || value === null || vectorBrushstrokePaintError(value)) return null;
4499
+ return readPaintSource(value);
4500
+ }
2604
4501
  var VECTOR_BRUSHSTROKE_MAX_SEED = 2147483647;
2605
- var finite2 = (v2) => typeof v2 === "number" && Number.isFinite(v2);
2606
- var sanitizeSeed = (v2) => finite2(v2) ? Math.min(VECTOR_BRUSHSTROKE_MAX_SEED, Math.max(0, Math.round(v2))) : void 0;
4502
+ var finite3 = (v2) => typeof v2 === "number" && Number.isFinite(v2);
4503
+ var sanitizeSeed = (v2) => finite3(v2) ? Math.min(VECTOR_BRUSHSTROKE_MAX_SEED, Math.max(0, Math.round(v2))) : void 0;
2607
4504
  function sanitizeVectorBrushstrokePaper(value) {
2608
4505
  if (!value || typeof value !== "object") return null;
2609
4506
  const r = value;
@@ -2611,8 +4508,8 @@ function sanitizeVectorBrushstrokePaper(value) {
2611
4508
  if (typeof r.pattern === "string" && GRAIN_PATTERNS.includes(r.pattern)) out.pattern = r.pattern;
2612
4509
  const seed = sanitizeSeed(r.seed);
2613
4510
  if (seed !== void 0) out.seed = seed;
2614
- if (finite2(r.scale) && r.scale > 0) out.scale = Math.min(8, Math.max(0.25, r.scale));
2615
- if (finite2(r.depth)) out.depth = Math.min(1, Math.max(0, r.depth));
4511
+ if (finite3(r.scale) && r.scale > 0) out.scale = Math.min(8, Math.max(0.25, r.scale));
4512
+ if (finite3(r.depth)) out.depth = Math.min(1, Math.max(0, r.depth));
2616
4513
  return Object.keys(out).length ? out : null;
2617
4514
  }
2618
4515
  function vectorBrushstrokeCharacterError(brush) {
@@ -2625,8 +4522,8 @@ function vectorBrushstrokeCharacterError(brush) {
2625
4522
  if (extra.length) return `paper has unknown field ${extra.map((k) => `"${k}"`).join(", ")}: use pattern, seed, scale, depth.`;
2626
4523
  if (r.pattern !== void 0 && !GRAIN_PATTERNS.includes(r.pattern)) return `Unknown paper pattern "${String(r.pattern)}": use one of ${GRAIN_PATTERNS.join(", ")}.`;
2627
4524
  if (r.seed !== void 0 && !(Number.isInteger(r.seed) && r.seed >= 0 && r.seed <= VECTOR_BRUSHSTROKE_MAX_SEED)) return `paper.seed must be an integer from 0 to ${VECTOR_BRUSHSTROKE_MAX_SEED}.`;
2628
- if (r.scale !== void 0 && !(finite2(r.scale) && r.scale >= 0.25 && r.scale <= 8)) return "paper.scale must be from 0.25 to 8 (1 is the pattern's natural size).";
2629
- if (r.depth !== void 0 && !(finite2(r.depth) && r.depth >= 0 && r.depth <= 1)) return "paper.depth must be from 0 to 1.";
4525
+ if (r.scale !== void 0 && !(finite3(r.scale) && r.scale >= 0.25 && r.scale <= 8)) return "paper.scale must be from 0.25 to 8 (1 is the pattern's natural size).";
4526
+ if (r.depth !== void 0 && !(finite3(r.depth) && r.depth >= 0 && r.depth <= 1)) return "paper.depth must be from 0 to 1.";
2630
4527
  return null;
2631
4528
  }
2632
4529
  function randomVectorBrushstrokeSeed() {
@@ -2639,29 +4536,240 @@ function vectorBrushstrokeReach(layer) {
2639
4536
  if (!isVectorBrushstrokeLayer(layer)) return 0;
2640
4537
  return (layer.brush.size ?? vectorBrushstrokeBrushOf(layer.brush).tip.size) / 2;
2641
4538
  }
4539
+ var backdropSource = null;
4540
+ function setVectorBackdropSource(source) {
4541
+ backdropSource = source;
4542
+ }
4543
+ var hex22 = (v2) => Math.round(Math.min(1, Math.max(0, v2)) * 255).toString(16).padStart(2, "0");
4544
+ function gradientPaint(g, map) {
4545
+ const stops = sortedVectorGradientStops(g);
4546
+ const exact2 = stops.length >= 2 && stops.length <= 16 && !g.smoothness && (g.interpolation ?? "srgb") === "srgb" && stops.every((s) => parseVectorColor(s.color));
4547
+ if (exact2) {
4548
+ return {
4549
+ type: "gradient",
4550
+ space: "srgb",
4551
+ map,
4552
+ stops: stops.map((s) => {
4553
+ const c = parseVectorColor(s.color);
4554
+ const opacity = Math.min(1, Math.max(0, (s.opacity ?? 1) * c[3]));
4555
+ const midpoint = s.midpoint !== void 0 && s.midpoint !== 0.5 ? Math.min(0.95, Math.max(0.05, s.midpoint)) : void 0;
4556
+ return { offset: Math.min(1, Math.max(0, s.offset)), color: `#${hex22(c[0])}${hex22(c[1])}${hex22(c[2])}`, ...opacity < 1 ? { opacity } : {}, ...midpoint !== void 0 ? { midpoint } : {} };
4557
+ })
4558
+ };
4559
+ }
4560
+ const ramp = vectorGradientRamp(g);
4561
+ const n = 16;
4562
+ return {
4563
+ type: "gradient",
4564
+ space: "srgb",
4565
+ map,
4566
+ stops: Array.from({ length: n }, (_, i) => {
4567
+ const t = i / (n - 1);
4568
+ const c = ramp ? ramp.sample(t) : [0, 0, 0, 1];
4569
+ return { offset: t, color: `#${hex22(c[0])}${hex22(c[1])}${hex22(c[2])}`, ...c[3] < 1 ? { opacity: Math.max(0, c[3]) } : {} };
4570
+ })
4571
+ };
4572
+ }
4573
+ var REPEAT = { pad: "clamp", repeat: "repeat", reflect: "mirror" };
4574
+ function strokePaintOf(node, layer, brush, length2) {
4575
+ const engine = vectorMediaEngine(brush);
4576
+ if (engine === "smudge" || engine === "blender") return { color: [0, 0, 0, 255], paint: null, within: null };
4577
+ const solid = vectorPaintSolid(layer.paint) ?? "#000000";
4578
+ const c = parseVectorColor(solid) ?? [0, 0, 0, 1];
4579
+ const color2 = [c[0] * 255, c[1] * 255, c[2] * 255, c[3] * 255].map(Math.round);
4580
+ if (layer.brush.paint) return { color: color2, paint: layer.brush.paint, within: null };
4581
+ const g = layer.paint;
4582
+ if (isVectorGradient(g) && g.stops?.length) {
4583
+ const mode = g.strokeMode ?? "within";
4584
+ if (mode === "along") return { color: [color2[0], color2[1], color2[2], 255], paint: gradientPaint(g, { by: "distance", length: Math.max(1, length2), repeat: REPEAT[g.spread ?? "pad"], unit: "px" }), within: null };
4585
+ if (mode === "across") return { color: [color2[0], color2[1], color2[2], 255], paint: gradientPaint(g, { by: "across-tip" }), within: null };
4586
+ if (engine === "mixer") return { color: [color2[0], color2[1], color2[2], 255], paint: gradientPaint(g, { by: "distance", length: Math.max(1, length2), repeat: REPEAT[g.spread ?? "pad"] }), within: null };
4587
+ const b = bezierPathBounds(subpathsToBezier(node.subpaths));
4588
+ return { color: [255, 255, 255, 255], paint: null, within: { gradient: g, bounds: b ? { x: b.minX, y: b.minY, width: b.maxX - b.minX, height: b.maxY - b.minY } : null } };
4589
+ }
4590
+ if (brush.paint && !TIMED_MAPPINGS.includes(brush.paint.map.by)) return { color: color2, paint: brush.paint, within: null };
4591
+ return { color: color2, paint: null, within: null };
4592
+ }
4593
+ function recoloured(stroke, within) {
4594
+ if (!stroke.bounds) return stroke;
4595
+ const ramp = vectorGradientRamp(within.gradient);
4596
+ if (!ramp) return stroke;
4597
+ const lut = Array.from({ length: 256 }, (_, i) => ramp.sample(i / 255));
4598
+ const { width, height, data } = stroke.image;
4599
+ const out = new Uint8ClampedArray(data);
4600
+ const { x: bx, y: by } = stroke.bounds;
4601
+ const s = stroke.scale;
4602
+ for (let y = 0; y < height; y++) {
4603
+ for (let x = 0; x < width; x++) {
4604
+ const i = (y * width + x) * 4;
4605
+ if (!out[i + 3]) continue;
4606
+ const t = vectorGradientTAt(within.gradient, within.bounds, { x: bx + (x + 0.5) / s, y: by + (y + 0.5) / s });
4607
+ const col = lut[Math.round(Math.min(1, Math.max(0, t)) * 255)];
4608
+ out[i] = Math.round(out[i] * col[0]);
4609
+ out[i + 1] = Math.round(out[i + 1] * col[1]);
4610
+ out[i + 2] = Math.round(out[i + 2] * col[2]);
4611
+ out[i + 3] = Math.round(out[i + 3] * col[3]);
4612
+ }
4613
+ }
4614
+ return { ...stroke, image: { width, height, data: out } };
4615
+ }
4616
+ function hash(s, h = 2166136261) {
4617
+ for (let i = 0; i < s.length; i++) {
4618
+ h ^= s.charCodeAt(i);
4619
+ h = Math.imul(h, 16777619) >>> 0;
4620
+ }
4621
+ return h;
4622
+ }
4623
+ function hashBytes(b, h = 2166136261) {
4624
+ for (let i = 0; i < b.length; i++) {
4625
+ h ^= b[i];
4626
+ h = Math.imul(h, 16777619) >>> 0;
4627
+ }
4628
+ return h;
4629
+ }
4630
+ function mediaKey(input, brush, options) {
4631
+ const path = JSON.stringify(input);
4632
+ return `${hash(path).toString(16)}:${path.length}:${hash(JSON.stringify([brush, options])).toString(16)}`;
4633
+ }
4634
+ var Lru = class {
4635
+ constructor(capacity) {
4636
+ this.capacity = capacity;
4637
+ }
4638
+ capacity;
4639
+ map = /* @__PURE__ */ new Map();
4640
+ get(key) {
4641
+ const v2 = this.map.get(key);
4642
+ if (v2 !== void 0) {
4643
+ this.map.delete(key);
4644
+ this.map.set(key, v2);
4645
+ }
4646
+ return v2;
4647
+ }
4648
+ has(key) {
4649
+ return this.map.has(key);
4650
+ }
4651
+ set(key, value) {
4652
+ this.map.delete(key);
4653
+ this.map.set(key, value);
4654
+ while (this.map.size > this.capacity) this.map.delete(this.map.keys().next().value);
4655
+ }
4656
+ };
4657
+ var WET_SLICE_MS = 12;
4658
+ var wetSettled = new Lru(128);
4659
+ var wetInstant = /* @__PURE__ */ new Map();
4660
+ var wetJobs = /* @__PURE__ */ new Map();
4661
+ var settleListeners = /* @__PURE__ */ new Set();
4662
+ var wetTimer = null;
4663
+ var wetGeneration = 0;
4664
+ function wetFinished(key, job) {
4665
+ wetGeneration++;
4666
+ wetSettled.set(key, job.image());
4667
+ wetJobs.delete(key);
4668
+ wetInstant.delete(key);
4669
+ }
4670
+ function notifySettled() {
4671
+ for (const fn of [...settleListeners]) fn();
4672
+ }
4673
+ function scheduleWet() {
4674
+ if (wetTimer || !wetJobs.size) return;
4675
+ wetTimer = setTimeout(() => {
4676
+ wetTimer = null;
4677
+ const first = wetJobs.entries().next().value;
4678
+ if (first && first[1].run(WET_SLICE_MS)) {
4679
+ wetFinished(first[0], first[1]);
4680
+ notifySettled();
4681
+ }
4682
+ scheduleWet();
4683
+ }, 0);
4684
+ }
4685
+ function onVectorBrushstrokesSettled(listener) {
4686
+ settleListeners.add(listener);
4687
+ return () => settleListeners.delete(listener);
4688
+ }
4689
+ function vectorBrushstrokesSettling() {
4690
+ return wetJobs.size;
4691
+ }
4692
+ function settleVectorBrushstrokes() {
4693
+ const n = wetJobs.size;
4694
+ if (!n) return 0;
4695
+ for (const [key, job] of [...wetJobs]) {
4696
+ job.run();
4697
+ wetFinished(key, job);
4698
+ }
4699
+ notifySettled();
4700
+ return n;
4701
+ }
4702
+ function wetImage(input, brush, options, settle, pending) {
4703
+ const key = mediaKey(input, brush, options);
4704
+ const done = wetSettled.get(key);
4705
+ if (done) return done;
4706
+ let job = wetJobs.get(key);
4707
+ if (settle === "now") {
4708
+ job ??= new WetBrushstrokeJob(input, brush, options);
4709
+ job.run();
4710
+ wetFinished(key, job);
4711
+ return wetSettled.get(key);
4712
+ }
4713
+ if (!job) {
4714
+ job = new WetBrushstrokeJob(input, brush, options);
4715
+ wetJobs.set(key, job);
4716
+ wetInstant.set(key, job.image());
4717
+ scheduleWet();
4718
+ }
4719
+ pending.push(key);
4720
+ return wetInstant.get(key) ?? job.image();
4721
+ }
2642
4722
  var cache = new BrushstrokeCache(256);
4723
+ var backdropResults = new Lru(64);
2643
4724
  var urls = /* @__PURE__ */ new WeakMap();
2644
4725
  var layerCache = /* @__PURE__ */ new WeakMap();
2645
- function vectorBrushstrokeImages(node, layer) {
4726
+ var sameDeps = (a, b) => a === b || !!a && !!b && a.length === b.length && a.every((v2, i) => v2 === b[i]);
4727
+ function vectorBrushstrokeImages(node, layer, context = {}) {
2646
4728
  if (!isVectorBrushstrokeLayer(layer)) return [];
4729
+ const preset2 = vectorBrushstrokeBrushOf(layer.brush);
4730
+ const engine = vectorMediaEngine(preset2);
4731
+ const settle = context.settle ?? "async";
4732
+ const document2 = context.document ?? null;
4733
+ const index = (node.strokes ?? []).indexOf(layer);
4734
+ const source = usesVectorBackdrop(engine) && backdropSource ? backdropSource(document2, node, Math.max(0, index), settle) : null;
4735
+ const deps = source ? [...source.deps, wetGeneration] : null;
2647
4736
  let byLayer = layerCache.get(node);
2648
4737
  const hit = byLayer?.get(layer);
2649
- if (hit) return hit;
2650
- const preset = vectorBrushstrokeBrushOf(layer.brush);
2651
- const brush = layer.brush.size ? { ...preset, tip: { ...preset.tip, size: layer.brush.size } } : preset;
2652
- const solid = vectorPaintSolid(layer.paint) ?? "#000000";
2653
- const c = parseVectorColor(solid) ?? [0, 0, 0, 1];
2654
- const color2 = [c[0] * 255, c[1] * 255, c[2] * 255, c[3] * 255].map(Math.round);
4738
+ const stale = hit && (hit.pending.length && hit.pending.some((k) => wetSettled.has(k)) || settle === "now" && !hit.settled);
4739
+ if (hit && sameDeps(hit.deps, deps) && !stale) return hit.images;
4740
+ const brush = layer.brush.size ? { ...preset2, tip: { ...preset2.tip, size: layer.brush.size } } : preset2;
2655
4741
  const { seed, paper } = layer.brush;
2656
4742
  const character = seed !== void 0 ? { character: { seed, origin: { x: 0, y: 0 }, unit: 1, ...paper !== void 0 ? { paper } : {} } } : {};
2657
4743
  const out = [];
4744
+ const pending = [];
2658
4745
  for (const sp of node.subpaths) {
2659
4746
  if (sp.anchors.length < 2) continue;
2660
4747
  for (const contour of pathToContours(subpathsToBezier([sp]))) {
2661
4748
  const ring = flattenChain(closeContour(contour, contour.closed), 0.25);
2662
4749
  if (contour.closed && ring.length > 2) ring.push(ring[0]);
2663
4750
  if (ring.length < 2) continue;
2664
- const stroke = cache.render({ points: ring.map(([x, y]) => ({ x, y })), ...layer.brush.pressure ? { pressure: layer.brush.pressure } : {} }, brush, { scale: VECTOR_BRUSHSTROKE_SCALE, color: color2, maxPixels: 2048 * 2048, ...character });
4751
+ let length2 = 0;
4752
+ for (let i = 1; i < ring.length; i++) length2 += Math.hypot(ring[i][0] - ring[i - 1][0], ring[i][1] - ring[i - 1][1]);
4753
+ const input = { points: ring.map(([x, y]) => ({ x, y })), ...layer.brush.pressure ? { pressure: layer.brush.pressure } : {} };
4754
+ const sp2 = strokePaintOf(node, layer, brush, length2);
4755
+ const options = { scale: VECTOR_BRUSHSTROKE_SCALE, color: sp2.color, paint: sp2.paint, seed: seed ?? 0, maxPixels: 2048 * 2048 };
4756
+ let stroke;
4757
+ if (engine === "wet") stroke = wetImage(input, brush, { ...options, maxPixels: 1024 * 1024 }, settle, pending);
4758
+ else if (engine) {
4759
+ const key = mediaKey(input, brush, options);
4760
+ stroke = renderBackdropBrushstroke(input, brush, {
4761
+ ...options,
4762
+ backdrop: source?.backdrop ?? null,
4763
+ cache: (bytes) => {
4764
+ const k = `${key}:${hashBytes(bytes).toString(16)}`;
4765
+ return { get: () => backdropResults.get(k), set: (img) => backdropResults.set(k, img) };
4766
+ }
4767
+ });
4768
+ } else {
4769
+ const { paint, ...rest } = options;
4770
+ stroke = cache.render(input, brush, { ...rest, ...paint ? { paint } : {}, ...character });
4771
+ }
4772
+ if (sp2.within) stroke = recoloured(stroke, sp2.within);
2665
4773
  if (!stroke.bounds) continue;
2666
4774
  let href = urls.get(stroke);
2667
4775
  if (!href) urls.set(stroke, href = brushstrokeDataUrl(stroke));
@@ -2669,7 +4777,7 @@ function vectorBrushstrokeImages(node, layer) {
2669
4777
  }
2670
4778
  }
2671
4779
  if (!byLayer) layerCache.set(node, byLayer = /* @__PURE__ */ new Map());
2672
- byLayer.set(layer, out);
4780
+ byLayer.set(layer, { images: out, deps, pending, settled: settle === "now" || !pending.length && !deps });
2673
4781
  return out;
2674
4782
  }
2675
4783
 
@@ -2964,13 +5072,13 @@ function subsOf(path) {
2964
5072
  return pathToContours(path).map((c) => ({ segs: closeContour(c).filter((s) => !degenerate(s)).map(raise), closed: c.closed })).filter((s) => s.segs.length > 0);
2965
5073
  }
2966
5074
  var subsToPath = (subs) => contoursToPath(subs.map((s) => ({ segments: s.segs, closed: s.closed })));
2967
- var unit2 = (x, y) => {
5075
+ var unit3 = (x, y) => {
2968
5076
  const l = Math.hypot(x, y);
2969
5077
  return l > 1e-12 && Number.isFinite(l) ? [x / l, y / l] : null;
2970
5078
  };
2971
5079
  function startTangent(s) {
2972
5080
  for (let i = 1; i < s.length; i++) {
2973
- const u = unit2(s[i][0] - s[0][0], s[i][1] - s[0][1]);
5081
+ const u = unit3(s[i][0] - s[0][0], s[i][1] - s[0][1]);
2974
5082
  if (u) return u;
2975
5083
  }
2976
5084
  return [1, 0];
@@ -2978,7 +5086,7 @@ function startTangent(s) {
2978
5086
  function endTangent(s) {
2979
5087
  const end = s[s.length - 1];
2980
5088
  for (let i = s.length - 2; i >= 0; i--) {
2981
- const u = unit2(end[0] - s[i][0], end[1] - s[i][1]);
5089
+ const u = unit3(end[0] - s[i][0], end[1] - s[i][1]);
2982
5090
  if (u) return u;
2983
5091
  }
2984
5092
  return [1, 0];
@@ -2987,7 +5095,7 @@ function tangentAt(s, t) {
2987
5095
  if (t <= 1e-9) return startTangent(s);
2988
5096
  if (t >= 1 - 1e-9) return endTangent(s);
2989
5097
  const d = segmentDerivative(s, t);
2990
- return unit2(d[0], d[1]) ?? startTangent(s);
5098
+ return unit3(d[0], d[1]) ?? startTangent(s);
2991
5099
  }
2992
5100
  var perp2 = (v2) => [-v2[1], v2[0]];
2993
5101
  function effectPathLength(path) {
@@ -3211,7 +5319,7 @@ function resample(sub5, m) {
3211
5319
  let tan = tout;
3212
5320
  if (prev !== null) {
3213
5321
  const tin = endTangent(segs[prev]);
3214
- tan = unit2(tin[0] + tout[0], tin[1] + tout[1]) ?? tout;
5322
+ tan = unit3(tin[0] + tout[0], tin[1] + tout[1]) ?? tout;
3215
5323
  }
3216
5324
  out.push({ p: segs[j][0], tan, lenPrev: prev === null ? 0 : lens[prev] / m, lenNext: piece });
3217
5325
  } else {
@@ -3269,17 +5377,17 @@ function splitmix(x) {
3269
5377
  z = (z ^ z >> 27n) * 0x94d049bb133111ebn & MASK64;
3270
5378
  return z ^ z >> 31n;
3271
5379
  }
3272
- function hash(seed, idx, t) {
5380
+ function hash3(seed, idx, t) {
3273
5381
  const h = splitmix(splitmix(splitmix(seed) ^ idx) ^ BigInt.asUintN(64, BigInt(t)));
3274
5382
  return Number(h >> 11n) / 2 ** 53 * 2 - 1;
3275
5383
  }
3276
5384
  function noise(seed, idx, t) {
3277
5385
  const i = Math.floor(t);
3278
5386
  const f = t - i;
3279
- const p0 = hash(seed, idx, i - 1);
3280
- const p1 = hash(seed, idx, i);
3281
- const p2 = hash(seed, idx, i + 1);
3282
- const p3 = hash(seed, idx, i + 2);
5387
+ const p0 = hash3(seed, idx, i - 1);
5388
+ const p1 = hash3(seed, idx, i);
5389
+ const p2 = hash3(seed, idx, i + 1);
5390
+ const p3 = hash3(seed, idx, i + 2);
3283
5391
  const v2 = 0.5 * (2 * p1 + (-p0 + p2) * f + (2 * p0 - 5 * p1 + 4 * p2 - p3) * f * f + (-p0 + 3 * p1 - 3 * p2 + p3) * f * f * f);
3284
5392
  return Math.min(1, Math.max(-1, v2));
3285
5393
  }
@@ -3544,11 +5652,11 @@ function vectorFrameChildMatrix(resizing, box, from, to) {
3544
5652
  const sy = box.height > 1e-9 ? (y1 - y0) / box.height : 1;
3545
5653
  return [sx, 0, 0, sy, x0 - sx * box.x, y0 - sy * box.y];
3546
5654
  }
3547
- var finite3 = (v2) => typeof v2 === "number" && Number.isFinite(v2);
5655
+ var finite4 = (v2) => typeof v2 === "number" && Number.isFinite(v2);
3548
5656
  function sanitizeVectorFrame(value) {
3549
5657
  if (!value || typeof value !== "object") return null;
3550
5658
  const r = value;
3551
- if (!finite3(r.x) || !finite3(r.y) || !finite3(r.width) || !finite3(r.height) || r.width < 0 || r.height < 0) return null;
5659
+ if (!finite4(r.x) || !finite4(r.y) || !finite4(r.width) || !finite4(r.height) || r.width < 0 || r.height < 0) return null;
3552
5660
  const out = { x: r.x, y: r.y, width: r.width, height: r.height };
3553
5661
  if (typeof r.fill === "string" || r.fill && typeof r.fill === "object") out.fill = r.fill;
3554
5662
  if (r.clip === false) out.clip = false;
@@ -4196,7 +6304,7 @@ function vectorMaskSummary(node) {
4196
6304
  enabled: node.children[0].visible !== false
4197
6305
  };
4198
6306
  }
4199
- var place = (path, m) => isIdentityMatrix(m) ? path : transformBezierPath(path, m);
6307
+ var place2 = (path, m) => isIdentityMatrix(m) ? path : transformBezierPath(path, m);
4200
6308
  function vectorMaskRegionShapes(node, type, parent = IDENTITY_MATRIX, self = true) {
4201
6309
  if (!self && node.visible === false) return [];
4202
6310
  if (isVectorFrame(node)) node = vectorFrameDrawn(node);
@@ -4214,17 +6322,17 @@ function vectorMaskRegionShapes(node, type, parent = IDENTITY_MATRIX, self = tru
4214
6322
  function regionOfPath(path, style, type, m) {
4215
6323
  if (!path.length) return [];
4216
6324
  const fillRule = style.fillRule ?? "nonzero";
4217
- if (type === "clip") return [{ path: place(path, m), fillRule }];
6325
+ if (type === "clip") return [{ path: place2(path, m), fillRule }];
4218
6326
  const out = [];
4219
6327
  let filled = false;
4220
6328
  for (const l of vectorPaintLayerNodes(style)) {
4221
6329
  if (!l.drawn) continue;
4222
6330
  if (l.kind === "fill") {
4223
- if (!filled) out.push({ path: place(path, m), fillRule });
6331
+ if (!filled) out.push({ path: place2(path, m), fillRule });
4224
6332
  filled = true;
4225
6333
  } else if ((l.node.strokeWidth ?? 1) > 0) {
4226
6334
  const area = vectorStrokeOutlinePath(path, l.node);
4227
- if (area.length) out.push({ path: place(area, m), fillRule: "nonzero" });
6335
+ if (area.length) out.push({ path: place2(area, m), fillRule: "nonzero" });
4228
6336
  }
4229
6337
  }
4230
6338
  return out;
@@ -6208,8 +8316,8 @@ function sanitizeVectorLens(value) {
6208
8316
  if (spec.color !== null) out.color = typeof r.color === "string" && parseVectorColor(r.color) ? r.color : spec.color;
6209
8317
  return out;
6210
8318
  }
6211
- var hex22 = (v2) => Math.round(Math.min(1, Math.max(0, v2)) * 255).toString(16).padStart(2, "0");
6212
- var formatRgba = (c) => c[3] >= 1 ? `#${hex22(c[0])}${hex22(c[1])}${hex22(c[2])}` : `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${Math.round(c[3] * 1e3) / 1e3})`;
8319
+ var hex23 = (v2) => Math.round(Math.min(1, Math.max(0, v2)) * 255).toString(16).padStart(2, "0");
8320
+ var formatRgba = (c) => c[3] >= 1 ? `#${hex23(c[0])}${hex23(c[1])}${hex23(c[2])}` : `rgba(${Math.round(c[0] * 255)}, ${Math.round(c[1] * 255)}, ${Math.round(c[2] * 255)}, ${Math.round(c[3] * 1e3) / 1e3})`;
6213
8321
  var luma = (c) => 0.2126 * c[0] + 0.7152 * c[1] + 0.0722 * c[2];
6214
8322
  var mix = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t, a[3]];
6215
8323
  var HEAT = [
@@ -6631,15 +8739,15 @@ var BERN_INV = [
6631
8739
  [0, 0, 0, 1]
6632
8740
  ];
6633
8741
  var pct = (v2) => typeof v2 === "number" && Number.isFinite(v2) ? Math.min(1, Math.max(-1, v2 / 100)) : 0;
6634
- function warpPresetMesh(preset, bounds) {
6635
- if (!WARP_STYLES.includes(preset.style)) return null;
8742
+ function warpPresetMesh(preset2, bounds) {
8743
+ if (!WARP_STYLES.includes(preset2.style)) return null;
6636
8744
  const { x, y, width: w, height: h } = bounds;
6637
8745
  if (!(w > 0 && h > 0)) return null;
6638
- const b = pct(preset.bend);
6639
- const hd = pct(preset.horizontal);
6640
- const vd = pct(preset.vertical);
8746
+ const b = pct(preset2.bend);
8747
+ const hd = pct(preset2.horizontal);
8748
+ const vd = pct(preset2.vertical);
6641
8749
  if (b === 0 && hd === 0 && vd === 0) return null;
6642
- const grid = warpPresetGrid(preset.style, b, hd, vd, preset.orientation === "vertical", h / w);
8750
+ const grid = warpPresetGrid(preset2.style, b, hd, vd, preset2.orientation === "vertical", h / w);
6643
8751
  return { us: [0, 1], vs: [0, 1], points: grid.flat().map((p) => ({ x: x + p[0] * w, y: y + p[1] * h })) };
6644
8752
  }
6645
8753
  var warpMeshColumns = (m) => 3 * (m.us.length - 1) + 1;
@@ -7308,8 +9416,8 @@ var VECTOR_EFFECT_PARAM_SPECS = {
7308
9416
  var cloneMesh = (m) => ({ us: m.us.slice(), vs: m.vs.slice(), points: m.points.map((p) => ({ x: p.x, y: p.y })) });
7309
9417
  function vectorEnvelopeMesh(params, bounds) {
7310
9418
  if (params.style === "mesh") return params.mesh ?? identityWarpMesh(bounds, params.columns, params.rows);
7311
- const preset = warpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);
7312
- return preset ? resizeWarpMesh(preset, params.columns, params.rows) : identityWarpMesh(bounds, params.columns, params.rows);
9419
+ const preset2 = warpPresetMesh({ style: params.style, bend: params.bend, horizontal: params.horizontal, vertical: params.vertical, orientation: params.orientation }, bounds);
9420
+ return preset2 ? resizeWarpMesh(preset2, params.columns, params.rows) : identityWarpMesh(bounds, params.columns, params.rows);
7313
9421
  }
7314
9422
  function vectorEnvelopeMap(params, bounds) {
7315
9423
  if (!bounds || !(bounds.width > 0 && bounds.height > 0)) return null;
@@ -8295,7 +10403,7 @@ var add4 = (a, b) => ({ x: a.x + b.x, y: a.y + b.y });
8295
10403
  var sub4 = (a, b) => ({ x: a.x - b.x, y: a.y - b.y });
8296
10404
  var scale2 = (a, k) => ({ x: a.x * k, y: a.y * k });
8297
10405
  var left = (d) => ({ x: d.y, y: -d.x });
8298
- var unit3 = (v2) => {
10406
+ var unit4 = (v2) => {
8299
10407
  const l = Math.hypot(v2.x, v2.y);
8300
10408
  return l > 1e-12 ? { x: v2.x / l, y: v2.y / l } : { x: 1, y: 0 };
8301
10409
  };
@@ -8352,7 +10460,7 @@ function vectorStrokeGradientDefs(g, id, node, options = {}) {
8352
10460
  for (let i = 0; i < segCount; i++) {
8353
10461
  const a = pts[i];
8354
10462
  const b = pts[(i + 1) % n];
8355
- dirs.push(unit3(sub4(b, a)));
10463
+ dirs.push(unit4(sub4(b, a)));
8356
10464
  lengths.push(lengths[i] + Math.hypot(b.x - a.x, b.y - a.y));
8357
10465
  }
8358
10466
  const total = lengths[segCount];
@@ -8710,7 +10818,7 @@ function vectorDocumentToSvg(doc, options = {}) {
8710
10818
  for (const l of layers) {
8711
10819
  if (l.kind === "stroke" && isVectorBrushstrokeLayer(l.layer)) {
8712
10820
  lines.push(`${indent(depth + 1)}<g data-vector-part="brushstroke" data-vector-layer="${l.index}"${layerAttrs(l.layer)}>`);
8713
- for (const im of vectorBrushstrokeImages(node, l.layer)) lines.push(`${indent(depth + 2)}<image href="${im.href}" x="${num3(im.x)}" y="${num3(im.y)}" width="${num3(im.width)}" height="${num3(im.height)}" preserveAspectRatio="none"/>`);
10821
+ for (const im of vectorBrushstrokeImages(node, l.layer, { document: doc, settle: "now" })) lines.push(`${indent(depth + 2)}<image href="${im.href}" x="${num3(im.x)}" y="${num3(im.y)}" width="${num3(im.width)}" height="${num3(im.height)}" preserveAspectRatio="none"/>`);
8714
10822
  lines.push(`${indent(depth + 1)}</g>`);
8715
10823
  continue;
8716
10824
  }
@@ -9666,9 +11774,9 @@ function parseVectorSvg(svg, options = {}) {
9666
11774
  const symbolId = symbolFor(target);
9667
11775
  if (!symbolId) return null;
9668
11776
  const own = json2(el.attrs["data-vector-instance"]);
9669
- const place2 = multiplyMatrices(translateMatrix(length(el.attrs.x), length(el.attrs.y)), m);
11777
+ const place3 = multiplyMatrices(translateMatrix(length(el.attrs.x), length(el.attrs.y)), m);
9670
11778
  const node = { id: idFor(el), type: "instance", ...meta, symbolId, ...own?.scaleStrokes === false ? { scaleStrokes: false } : {}, ...own?.overrides ? { overrides: own.overrides } : {} };
9671
- return isIdentityMatrix(place2) ? node : { ...node, transform: place2 };
11779
+ return isIdentityMatrix(place3) ? node : { ...node, transform: place3 };
9672
11780
  };
9673
11781
  const ownInstance = (g, m, meta) => {
9674
11782
  const raw = json2(g.attrs["data-vector-instance"]);
@@ -9677,7 +11785,7 @@ function parseVectorSvg(svg, options = {}) {
9677
11785
  const symbolId = sym2 ? symbolFor(sym2) : raw.symbolId;
9678
11786
  if (!symbolId) return null;
9679
11787
  const t = Array.isArray(raw.transform) && raw.transform.length === 6 && raw.transform.every(Number.isFinite) ? raw.transform : IDENTITY_MATRIX;
9680
- const place2 = multiplyMatrices(t, m);
11788
+ const place3 = multiplyMatrices(t, m);
9681
11789
  const drawn = g.children.find((c) => c.name === "g");
9682
11790
  const effects = sanitizeVectorEffects(raw.effects);
9683
11791
  const node = {
@@ -9700,7 +11808,7 @@ function parseVectorSvg(svg, options = {}) {
9700
11808
  if (drawn.attrs.display === "none") node.visible = false;
9701
11809
  usedIds.add(node.id);
9702
11810
  }
9703
- return isIdentityMatrix(place2) ? node : { ...node, transform: place2 };
11811
+ return isIdentityMatrix(place3) ? node : { ...node, transform: place3 };
9704
11812
  };
9705
11813
  const visit2 = (el, style, matrix) => {
9706
11814
  const out = [];
@@ -10843,19 +12951,72 @@ export {
10843
12951
  shadeVectorColor,
10844
12952
  vectorPathRings,
10845
12953
  vectorExtrudeFaces,
12954
+ EFFECT_STRIP_HEIGHT,
12955
+ EFFECT_MAP_REPEATS,
12956
+ effectPaintSize,
12957
+ readEffectStrokeMap,
12958
+ effectPaintKey,
12959
+ isPaintEffectPaint,
12960
+ readPaintEffectPaint,
12961
+ sampleEffectField,
12962
+ sampleEffectAt,
12963
+ effectDabField,
12964
+ stampSampler,
12965
+ brushStickerRefs,
12966
+ PAPER_FAMILIES,
12967
+ PAPER_LIBRARY,
12968
+ DEFAULT_PAPER,
12969
+ paperPreset,
12970
+ clonePaper,
12971
+ normalizePaper,
12972
+ hexToRgb8,
12973
+ renderPaper,
12974
+ penOrientation,
12975
+ tiltToOrientation,
12976
+ PenSmoother,
12977
+ IDENTITY_COPY,
12978
+ PenDabWalker,
12979
+ DryStroke,
12980
+ mixerTip,
12981
+ toStrokePoint,
12982
+ multiColorPalette,
12983
+ multiColorGradient,
12984
+ multiColorForDab,
12985
+ PaintDabStroke,
12986
+ wetPaperInput,
12987
+ WetStrokeDriver,
12988
+ WET_MEDIUM_PARAMS,
12989
+ WET_GPU_MODES,
12990
+ GPU_LEAD,
12991
+ PaintWetLayers,
12992
+ wetPigmentOf,
12993
+ VECTOR_WET_STEPS,
12994
+ vectorMediaEngine,
12995
+ usesVectorBackdrop,
12996
+ WetBrushstrokeJob,
12997
+ renderWetBrushstroke,
12998
+ vectorBackdropRect,
12999
+ renderBackdropBrushstroke,
10846
13000
  VECTOR_BRUSHSTROKE_SCALE,
13001
+ isVectorBrushstrokeEngine,
10847
13002
  vectorBrushstrokeBrushes,
10848
13003
  vectorBrushstrokeBrush,
10849
13004
  vectorBrushstrokeBrushOf,
10850
13005
  vectorBrushstrokeBrushError,
10851
13006
  vectorBrushstrokeDefaultColour,
10852
13007
  sanitizeVectorBrushstroke,
13008
+ vectorBrushstrokePaintError,
13009
+ readVectorBrushstrokePaint,
10853
13010
  VECTOR_BRUSHSTROKE_MAX_SEED,
10854
13011
  sanitizeVectorBrushstrokePaper,
10855
13012
  vectorBrushstrokeCharacterError,
10856
13013
  randomVectorBrushstrokeSeed,
10857
13014
  isVectorBrushstrokeLayer,
10858
13015
  vectorBrushstrokeReach,
13016
+ setVectorBackdropSource,
13017
+ onVectorBrushstrokesSettled,
13018
+ vectorBrushstrokesSettling,
13019
+ settleVectorBrushstrokes,
10859
13020
  vectorBrushstrokeImages,
10860
13021
  VECTOR_STROKE_SETTING_KEYS,
10861
13022
  VECTOR_BLEND_MODE_LABELS,