@patrick91/stickers 0.0.0-stage → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,1411 @@
1
+ /*
2
+ * sticker-engine.js — peelable, draggable stickers for a whole scrolling page. No dependencies.
3
+ *
4
+ * One WebGL2 canvas is laid over the document. Every sticker is drawn on it, anchored to an
5
+ * element in your layout, so stickers scroll, wrap and resize with the page. A visitor can peel
6
+ * one off, carry it anywhere on the page and stick it down again.
7
+ *
8
+ * const engine = new StickerEngine();
9
+ * engine.add({ image: loadedImg, anchor: someElement, width: 160, rotation: -6, finish: 'gloss' });
10
+ *
11
+ * `image` is anything drawImage() accepts, with a transparent background. The white die-cut
12
+ * border, the bevel, the shadows and the hit area all come from its alpha channel.
13
+ *
14
+ * How one sticker is drawn (a single fragment shader, per pixel):
15
+ * shadow contact shadow, lift shadow, and the shadow of the peeled flap
16
+ * vinyl white die-cut shape = artwork alpha grown by `border` (a distance field)
17
+ * ink the artwork
18
+ * vinyl ...or another stock: holographic, clear, glitter, mirror, brushed metal, kraft, and so on
19
+ * laminate gloss bands mirrored from a virtual ceiling
20
+ * residue under all of that, at the spot a sticker was first stuck: the faint ghost it leaves behind
21
+ * the flap everything beyond the fold line, wrapped round a cylinder of radius R and laid
22
+ * back over the sticker, adhesive side up
23
+ */
24
+
25
+ const VERT = `#version 300 es
26
+ in vec2 aPos;
27
+ uniform vec4 uRect;
28
+ uniform mat3 uM;
29
+ uniform vec2 uView;
30
+ out vec2 vL;
31
+ out vec2 vP;
32
+ void main() {
33
+ vec2 l = mix(uRect.xy, uRect.zw, aPos);
34
+ vec3 p = uM * vec3(l, 1.0);
35
+ vL = l;
36
+ vP = p.xy;
37
+ vec2 c = p.xy / uView * 2.0 - 1.0;
38
+ gl_Position = vec4(c.x, -c.y, 0.0, 1.0);
39
+ }`;
40
+
41
+ const FRAG = `#version 300 es
42
+ precision highp float;
43
+ in vec2 vL; // sticker-local position, css px, origin at centre
44
+ in vec2 vP; // page position, css px
45
+ out vec4 fragColor;
46
+
47
+ uniform sampler2D uArt; // artwork, premultiplied
48
+ uniform sampler2D uSdf; // r: signed distance to die-cut edge (px, <0 inside), gb: outward gradient
49
+ uniform sampler2D uMirror; // optional, unpremultiplied reflection frame
50
+ uniform vec3 uMirrorMap; // source UV per local px on each axis, and horizontal direction (0 = off)
51
+ uniform vec2 uSize; // local size covered by the textures
52
+ uniform vec3 uFold; // fold line: n.xy (unit, points at the peeled side), offset
53
+ uniform float uR; // curl radius
54
+ uniform float uLift; // height of the whole sticker above the page
55
+ uniform vec2 uSh; // shadow offset per unit of height (local space)
56
+ uniform vec3 uL; // light direction (local space, z up)
57
+ uniform vec2 uRot; // cos, sin of local -> page rotation
58
+ uniform vec2 uOff; // canvas px -> viewport px
59
+ uniform vec2 uEnv; // environment shift (pointer parallax)
60
+ uniform vec4 uFin; // gloss, material kind, grain, show-through
61
+ uniform vec3 uPtr; // pointer in viewport px, and whether there is one
62
+ uniform float uGlow; // how dark the surroundings are, 0..1
63
+ uniform float uTrim; // 1: no border, so the sticker ends exactly where the artwork does
64
+ uniform vec3 uPaper;
65
+ uniform vec3 uBack;
66
+ uniform float uShadow;
67
+ uniform float uAlpha;
68
+ uniform vec4 uLay; // layer switches: shadow, vinyl, ink, laminate
69
+ uniform float uPx; // local px per device px
70
+ uniform float uSeed;
71
+ uniform float uMark; // > 0: draw what the sticker left behind instead of the sticker
72
+ uniform float uGround; // brightness of the surface under it, 0..1
73
+
74
+ const float PI = 3.14159265359;
75
+ const float RISE = 0.2; // how steeply the loose flap climbs away from the fold
76
+ const vec3 GLOW = vec3(0.32, 1.0, 0.48); // phosphor green
77
+ const float HALO = 48.0; // how far a glowing sticker's light reaches over the page, px
78
+
79
+ float hash(vec2 p) {
80
+ p = fract(p * vec2(123.34, 456.21));
81
+ p += dot(p, p + 45.32);
82
+ return fract(p.x * p.y);
83
+ }
84
+ float vnoise(vec2 p) {
85
+ vec2 i = floor(p), f = fract(p);
86
+ f = f * f * (3.0 - 2.0 * f);
87
+ return mix(mix(hash(i), hash(i + vec2(1.0, 0.0)), f.x),
88
+ mix(hash(i + vec2(0.0, 1.0)), hash(i + vec2(1.0, 1.0)), f.x), f.y);
89
+ }
90
+
91
+ vec3 shape(vec2 q) {
92
+ vec2 uv = q / uSize + 0.5;
93
+ vec2 cuv = clamp(uv, 0.0, 1.0);
94
+ vec3 t = texture(uSdf, cuv).rgb;
95
+ t.r += length((uv - cuv) * uSize);
96
+ return t;
97
+ }
98
+ float cover(float d) { return clamp(0.5 - d / (1.5 * uPx), 0.0, 1.0); }
99
+ float soft(float d, float w) { return 1.0 - smoothstep(-w, w, d); }
100
+
101
+ // Distance along the sheet (measured from the fold line) of the adhesive-side point
102
+ // seen at signed distance x from the fold line.
103
+ float upperDist(float x, float R) {
104
+ return x <= 0.0 ? PI * R - x : R * (PI - asin(clamp(x / R, 0.0, 1.0)));
105
+ }
106
+ float flapHeight(float d, float R) {
107
+ return d < PI * R ? R * (1.0 - cos(d / R)) : 2.0 * R + RISE * (d - PI * R);
108
+ }
109
+ float flapOcc(vec2 a, float w, float R, out float d) {
110
+ vec2 n = uFold.xy;
111
+ float x = dot(a, n) - uFold.z;
112
+ d = upperDist(x, R);
113
+ vec2 m = a - n * x + n * d;
114
+ return soft(shape(m).r, w) * (1.0 - smoothstep(R - w, R + w, x));
115
+ }
116
+ // Shadow the flap casts on a receiver that sits 'below' px under the flat part.
117
+ float flapShadow(vec2 r, float below, float R) {
118
+ float d;
119
+ flapOcc(r - uSh * (2.0 * R + below), 1.0, R, d);
120
+ float z = min(flapHeight(d, R), 2.0 * R + 46.0) + below;
121
+ float c = flapOcc(r - uSh * z, 1.0 + 0.3 * z, R, d);
122
+ return c * mix(1.0, 0.6, clamp(z / 70.0, 0.0, 1.0));
123
+ }
124
+ float lowerOcc(vec2 a, float w, float R) {
125
+ float x = dot(a, uFold.xy) - uFold.z;
126
+ return soft(shape(a).r, w) * (1.0 - smoothstep(-w, w, x - R * 0.6));
127
+ }
128
+
129
+ vec2 toPage(vec2 v) { return vec2(uRot.x * v.x - uRot.y * v.y, uRot.y * v.x + uRot.x * v.y); }
130
+
131
+ // Where the mirror reflection of the viewer's line of sight lands on a virtual ceiling.
132
+ vec2 ceilingHit(vec3 N, float height) {
133
+ vec3 Rv = vec3(2.0 * N.z * N.xy, 2.0 * N.z * N.z - 1.0);
134
+ return vP + uOff + toPage(Rv.xy) / max(Rv.z, 0.22) * height + uEnv;
135
+ }
136
+
137
+ float fbm(vec2 p) {
138
+ float a = 0.5, f = 0.0;
139
+ for (int i = 0; i < 4; i++) { f += a * vnoise(p); p = mat2(1.6, 1.2, -1.2, 1.6) * p + 17.1; a *= 0.5; }
140
+ return f / 0.9375;
141
+ }
142
+ vec3 spectrum(float t) { return 0.5 + 0.5 * cos(6.28318 * (t + vec3(0.0, 0.33, 0.67))); }
143
+
144
+ // The stock a sticker is cut from: its colour at material point m. glint is light it throws
145
+ // back on top of that (sparkles, retroreflection, glow). Ink is printed over it and is not opaque.
146
+ vec3 stock(int kind, vec2 m, vec3 Nw, out vec3 glint) {
147
+ glint = vec3(0.0);
148
+ if (kind == 0 || kind == 2) return uPaper;
149
+ vec2 hh = ceilingHit(Nw, 1500.0) + uEnv * 1.6;
150
+ if (kind == 1) { // holographic: slow liquid colour that drifts with the view
151
+ vec2 w = m * 0.012 + uSeed;
152
+ float flow = fbm(w + 1.6 * vec2(fbm(w * 1.4 + 3.1), fbm(w * 1.4 + 8.7)));
153
+ float ph = flow * 1.7 + dot(hh, vec2(0.8, 0.6)) / 560.0;
154
+ return vec3(0.74, 0.8, 0.9) + vec3(0.26, 0.22, 0.14) * cos(6.28318 * (ph + vec3(0.0, 0.3, 0.62)));
155
+ }
156
+ if (kind == 3) { // glitter: silver with coloured specks that wink on and off
157
+ vec2 g = m / 7.4, id = floor(g), f = fract(g);
158
+ float r0 = hash(id + uSeed), r1 = hash(id + uSeed + 4.7), r2 = hash(id + uSeed + 9.1);
159
+ float rad = 0.2 + 0.24 * r0;
160
+ float spot = (1.0 - smoothstep(rad * 0.6, rad, length(f - 0.25 - 0.5 * vec2(r1, r2)))) * step(0.34, hash(id + uSeed + 2.2));
161
+ float tw = 0.5 + 0.5 * cos(6.28318 * (r0 * 5.0 + dot(hh, vec2(0.6, -0.8)) / 170.0));
162
+ vec3 hue = spectrum(m.y / 170.0 + r1 * 0.22 + dot(hh, vec2(0.2, 0.5)) / 900.0);
163
+ glint = spot * (0.16 + 0.84 * tw * tw) * mix(vec3(1.0), hue, 0.86);
164
+ return vec3(0.7, 0.71, 0.73) + 0.14 * (0.5 + 0.5 * cos(6.28318 * dot(hh, vec2(0.8, 0.6)) / 700.0));
165
+ }
166
+ if (kind == 4) { // mirror: chrome, a soft room bent by every ripple
167
+ vec2 hit = ceilingHit(normalize(Nw + vec3(Nw.xy * 1.6, 0.0)), 460.0);
168
+ float room = 0.5 + 0.5 * sin(hit.x * 0.0046 + 1.1 * sin(hit.y * 0.0042));
169
+ // a sheet this thin is never flat, so some of the room's dark always lands on it somewhere
170
+ float bow = 0.5 + 0.5 * sin(dot(m, vec2(0.013, 0.024)) + dot(hit, vec2(0.004, 0.0028)) + uSeed);
171
+ vec3 chrome = mix(vec3(0.46, 0.51, 0.6), vec3(0.98, 0.99, 1.0), smoothstep(0.18, 0.82, 0.45 * room + 0.55 * bow));
172
+ if (uMirrorMap.z == 0.0) return chrome;
173
+ // An upright, cover-fit image for the flat part; the peel bends it towards the chrome.
174
+ vec2 uv = 0.5 + toPage(vL) * uMirrorMap.xy * 0.90 + toPage(Nw.xy) * 0.56;
175
+ uv.x = 0.5 + (uv.x - 0.5) * uMirrorMap.z;
176
+ float inset = min(min(uv.x, uv.y), 1.0 - max(uv.x, uv.y));
177
+ vec4 frame = textureLod(uMirror, uv, 0.0); // no mipmaps; and this runs only where the sticker is
178
+ return mix(chrome, frame.rgb * 0.95 + 0.015, frame.a * 0.96 * smoothstep(-0.06, 0.01, inset));
179
+ }
180
+ if (kind == 5) { // pixie dust: fine shimmer over bands of pastel
181
+ vec2 id = floor(m * 1.15);
182
+ float r0 = hash(id + uSeed), r1 = hash(id + uSeed + 5.5);
183
+ float tw = pow(0.5 + 0.5 * cos(6.28318 * (r1 * 6.0 + dot(hh, vec2(0.7, -0.6)) / 110.0)), 5.0);
184
+ glint = vec3(tw * step(0.55, r0) * 0.55);
185
+ return mix(vec3(0.84), spectrum(m.y / 150.0 + uSeed * 0.1 + dot(hh, vec2(0.3, 0.9)) / 800.0), 0.42) * (0.84 + 0.22 * r0);
186
+ }
187
+ if (kind == 6) { // brushed aluminium: long grain, highlight smeared across it
188
+ float grain = 0.6 * vnoise(vec2(m.x * 0.03, m.y * 2.4) + uSeed) + 0.4 * vnoise(vec2(m.x * 0.1, m.y * 5.5) + uSeed * 2.0);
189
+ float band = 0.5 + 0.5 * cos(6.28318 * dot(ceilingHit(Nw, 540.0), toPage(vec2(0.0, 1.0))) / 430.0 + (grain - 0.5) * 1.4);
190
+ return vec3(0.62, 0.64, 0.67) * (0.82 + 0.26 * grain) + 0.24 * band * band;
191
+ }
192
+ if (kind == 7) { // prismatic: tiles of eight facets, each leaning its own way
193
+ vec2 g = m / 15.0, id = floor(g), f = fract(g) - 0.5;
194
+ float facet = floor((atan(f.y, f.x) / 6.28318 + 0.5 + mod(id.x + id.y, 2.0) * 0.0625) * 8.0) / 8.0;
195
+ vec2 lean = vec2(cos(6.28318 * facet), sin(6.28318 * facet));
196
+ vec2 h2 = ceilingHit(normalize(Nw + vec3(lean * 0.2, 0.0)), 800.0) + uEnv * 1.2;
197
+ float t = dot(h2, vec2(0.8, 0.6)) / 460.0;
198
+ return mix(vec3(0.6), vec3(0.98), 0.5 + 0.5 * cos(6.28318 * t)) * mix(vec3(1.0), spectrum(t * 0.6 + facet), 0.12);
199
+ }
200
+ if (kind == 8) { // reflective: glass beads throw light straight back at its source, the pointer
201
+ float bead = hash(floor(m * 1.7) + uSeed);
202
+ vec2 d = vP + uOff - uPtr.xy;
203
+ glint = vec3(uPtr.z * exp(-dot(d, d) / 26000.0) * (0.35 + 0.75 * bead));
204
+ return vec3(0.84, 0.85, 0.86) * (0.9 + 0.14 * bead);
205
+ }
206
+ if (kind == 9) { // kraft paper: brown, fibrous, flecked
207
+ float fibre = 0.55 * fbm(vec2(m.x * 0.45, m.y * 0.07) + uSeed) + 0.45 * fbm(m * 0.8 + uSeed + 5.0);
208
+ return vec3(0.74, 0.57, 0.38) * (0.86 + 0.26 * fibre) - 0.1 * step(0.985, hash(floor(m * 1.2) + uSeed));
209
+ }
210
+ // glow in the dark: light green by day. At night it gives back little of the room's light and has its own, never quite even
211
+ glint = uGlow * GLOW * 0.62 * (0.93 + 0.08 * vnoise(m * 0.028 + uSeed) + 0.06 * vnoise(m * 0.075 - uSeed));
212
+ return mix(vec3(0.82, 0.95, 0.78), vec3(0.36, 0.4, 0.36), uGlow);
213
+ }
214
+
215
+ // How much of the phosphor's light the ink around material point p lets out, 0..1.
216
+ float glowNear(vec2 p, float lod) {
217
+ vec4 ink = textureLod(uArt, p / uSize + 0.5, lod);
218
+ vec3 through = uTrim > 0.5 ? ink.rgb / max(ink.a, 0.05) : ink.rgb + 1.0 - ink.a; // borderless: the stock ends with the artwork
219
+ return min(min(through.r, through.g), through.b);
220
+ }
221
+
222
+ // raw is the artwork at m, sampled by the caller: this runs only for pixels the sticker covers,
223
+ // and a mipmapped lookup needs every pixel of its 2x2 block to take part.
224
+ vec4 shadeFront(vec2 m, vec3 N, vec3 s, vec4 raw, float flapSh) {
225
+ int kind = int(uFin.y + 0.5);
226
+ // the laminate is never perfectly flat
227
+ vec2 wv = vec2(vnoise(m * 0.03 + uSeed), vnoise(m * 0.03 + uSeed + 31.7)) - 0.5;
228
+ vec3 Nw = normalize(N + vec3(wv * 0.05, 0.0));
229
+
230
+ vec3 glint;
231
+ vec3 mat = stock(kind, m, Nw, glint);
232
+ vec4 ink = raw * uLay.z;
233
+ vec3 through = ink.rgb + 1.0 - ink.a; // what the ink lets through of the stock beneath
234
+ // borderless: the artwork's own edge is the cut, so a soft edge pixel is less sticker, not thinner ink
235
+ float body = mix(1.0, raw.a, uTrim);
236
+ if (uTrim > 0.5) through = mix(vec3(1.0), raw.rgb / max(raw.a, 0.001), uLay.z);
237
+ vec4 c = mix(ink, vec4(mat * through, 1.0) * body, uLay.y);
238
+ glint *= through * uLay.y;
239
+ float bare = min(min(through.r, through.g), through.b); // 1 where the ink lets all of the stock through: none, or white
240
+ // clear film: only the ink is really there, and with no white underneath it the page shows through it too
241
+ if (kind == 2) c = ink * mix(1.0, 0.62, uLay.y) + vec4(vec3(0.045), 0.05) * (1.0 - ink.a) * uLay.y * (1.0 - uTrim);
242
+
243
+ float dif = dot(Nw, uL) / uL.z;
244
+ float lit = mix(1.0, clamp(dif, 0.3, 1.5), 0.55);
245
+ // die-cut edge catches or loses light depending on which way it faces
246
+ float edge = smoothstep(-2.2, -0.2, s.r);
247
+ float facing = dot(s.gb, normalize(uL.xy));
248
+ lit *= 1.0 + edge * (0.10 * facing - 0.03);
249
+ lit *= 1.0 - 0.5 * flapSh;
250
+ if (kind == 10) lit = mix(lit, 1.0, 0.7 * uGlow * bare); // glowing stock is not at the mercy of the room
251
+ vec3 rgb = c.rgb * lit + glint * c.a;
252
+ // and its light blooms over the ink next to it
253
+ if (kind == 10) rgb += uGlow * GLOW * 0.3 * glowNear(m, 4.5) * (1.0 - bare) * uLay.y * c.a;
254
+
255
+ rgb += (hash(floor(m * 2.0) + uSeed) - 0.5) * uFin.z * c.a;
256
+
257
+ // gloss: soft strip lights on the ceiling, mirrored in the laminate
258
+ vec2 hit = ceilingHit(Nw, 540.0);
259
+ float b1 = pow(0.5 + 0.5 * cos(6.28318 * dot(hit, vec2(0.78, 0.62)) / 640.0), 5.0);
260
+ float b2 = 0.62 + 0.38 * cos(6.28318 * dot(hit, vec2(-0.55, 0.83)) / 1500.0 + 1.3);
261
+ float b3 = 0.5 + 0.5 * cos(6.28318 * dot(hit, vec2(0.78, 0.62)) / 1280.0 + 2.2);
262
+ float fres = pow(1.0 - Nw.z, 2.0);
263
+ float g = uFin.x * uLay.w * (b1 * b2 * 0.24 + b3 * 0.05 + fres * (0.2 + 0.5 * b1));
264
+ float film = uLay.w * max(body - c.a, 0.0); // bare laminate: clear stock, or the top layer of the exploded view
265
+ float clear = kind == 2 ? 1.0 : 0.0;
266
+ float a = c.a + film * clamp(mix(0.1, 0.03, clear) + g * 2.0 + 0.16 * edge, 0.0, 1.0);
267
+ rgb += g * (c.a - rgb) + film * (vec3(0.07, 0.09, 0.11) * mix(1.0, 0.35, clear) + g * 2.0 + edge * (0.1 + 0.08 * facing));
268
+ return vec4(rgb, a);
269
+ }
270
+
271
+ vec4 shadeBack(vec2 m, vec3 N) {
272
+ float dif = dot(N, uL) / uL.z;
273
+ float lit = mix(0.7, 1.0, clamp(dif, 0.0, 1.0)) + 0.07 * clamp(dif - 1.0, 0.0, 1.0);
274
+ lit *= mix(0.76, 1.0, smoothstep(0.0, 0.6, N.z));
275
+ vec4 art = texture(uArt, m / uSize + 0.5);
276
+ vec3 hv = normalize(uL + vec3(0.0, 0.0, 1.0));
277
+ float spec = pow(max(dot(N, hv), 0.0), 18.0) * 0.06;
278
+ if (int(uFin.y + 0.5) == 2) { // clear film from behind: the print, a little milky, and frosted adhesive
279
+ vec4 o = vec4((art.rgb * 0.84 + 0.1 * art.a) * lit, art.a);
280
+ o += vec4(vec3(0.8, 0.84, 0.88), 1.0) * 0.17 * (1.0 - art.a) * (1.0 - uTrim);
281
+ o.rgb += spec * 2.0;
282
+ return o;
283
+ }
284
+ vec3 c = uBack * lit;
285
+ c *= mix(vec3(1.0), art.rgb + (1.0 - art.a), uFin.w);
286
+ c += (hash(floor(m * 1.7) + uSeed) - 0.5) * 0.02;
287
+ return vec4(c + spec, 1.0) * mix(1.0, art.a, uTrim);
288
+ }
289
+
290
+ // What a sticker leaves behind, as on a laptop lid: a soft, even ghost of its shape, a touch
291
+ // stronger where the edge sat and where the print was dark, so you can tell which one it was.
292
+ vec4 residue(vec2 q) {
293
+ vec3 s = shape(q);
294
+ float depth = -s.r;
295
+ float inside = smoothstep(0.6, 5.5, depth); // soft edge, kept wholly under the sticker
296
+ if (inside <= 0.0) return vec4(0.0);
297
+ float rim = 1.0 - smoothstep(3.0, 15.0, depth);
298
+ float cloud = fbm(q * 0.022 + uSeed); // slow unevenness, like a lid that has seen some use
299
+ vec4 art = textureLod(uArt, q / uSize + 0.5, 3.0); // the artwork, well out of focus
300
+ float ink = art.a - dot(art.rgb, vec3(0.299, 0.587, 0.114));
301
+ float light = step(0.45, uGround); // pale ground darkens, dark ground lightens
302
+ float amount = (0.03 + 0.02 * rim + 0.024 * ink) * (0.78 + 0.44 * cloud) * mix(1.35, 1.0, light);
303
+ vec3 tone = mix(vec3(0.93, 0.93, 0.95), vec3(0.36, 0.37, 0.4), light);
304
+ return vec4(tone, 1.0) * amount * inside;
305
+ }
306
+
307
+ void main() {
308
+ if (uMark > 0.0) { fragColor = residue(vL) * uMark * uAlpha; return; }
309
+ vec2 n = uFold.xy;
310
+ float R = max(uR, 0.001);
311
+ vec2 q = vL;
312
+ float x = dot(q, n) - uFold.z; // > 0 on the peeled side of the fold line
313
+ vec2 qf = q - n * x;
314
+ float t = clamp(x / R, 0.0, 1.0);
315
+ float ct = sqrt(1.0 - t * t);
316
+ float rim = x <= 0.0 ? 1.0 : 1.0 - smoothstep(R - 1.5 * uPx, R, x);
317
+
318
+ // lower sheet: still flat, or the first quarter turn of the curl (printed side up)
319
+ vec2 mL = x <= 0.0 ? q : qf + n * (R * asin(t));
320
+ vec3 nL = x <= 0.0 ? vec3(0.0, 0.0, 1.0) : vec3(-n * t, ct);
321
+ vec3 sL = shape(mL);
322
+ float cL = cover(sL.r);
323
+ vec4 raw = texture(uArt, mL / uSize + 0.5);
324
+
325
+ float H = max(uLift, 0.0);
326
+ // upper sheet: the rest of the curl and the loose flap (adhesive side up). A sticker lying flat
327
+ // has its fold line far off (see _draw), so it has neither, and casts no flap shadow.
328
+ vec4 back = vec4(0.0);
329
+ float s3 = 0.0, flapSh = 0.0;
330
+ if (uFold.z < 5e4) {
331
+ float dU = upperDist(x, R);
332
+ vec2 mU = qf + n * dU;
333
+ float slope = RISE * smoothstep(0.0, 2.0 * R, -x);
334
+ vec3 nU = x <= 0.0 ? normalize(vec3(n * slope, 1.0)) : vec3(n * t, ct);
335
+ float cU = cover(shape(mU).r) * uLay.y;
336
+ back = shadeBack(mU, nU) * cU;
337
+ s3 = flapShadow(q, H, R) * 0.38;
338
+ flapSh = flapShadow(q, 0.0, R) * uLay.x;
339
+ }
340
+
341
+ float s1 = lowerOcc(q - uSh * (H + 1.2), 1.3 + 0.5 * H, R) * mix(0.42, 0.27, clamp(H / 24.0, 0.0, 1.0));
342
+ float s2 = lowerOcc(q, 3.5 + 0.5 * H, R) * 0.13 * (1.0 - clamp(H / 14.0, 0.0, 1.0));
343
+ float sh = 1.0 - (1.0 - s1) * (1.0 - s2) * (1.0 - s3);
344
+ int kind = int(uFin.y + 0.5);
345
+ if (kind == 2) sh *= mix(0.3, 1.0, textureLod(uArt, (q - uSh * (H + 1.2)) / uSize + 0.5, 2.5).a); // clear film barely casts one
346
+ vec4 col = vec4(0.0, 0.0, 0.0, sh * uShadow * uLay.x);
347
+
348
+ // most of the quad is shadow or nothing: shade the sticker only where it covers the pixel
349
+ vec4 sheet = vec4(0.0);
350
+ if (cL > 0.0) sheet = shadeFront(mL, nL, sL, raw, flapSh) * cL;
351
+ sheet = (sheet * (1.0 - back.a) + back) * rim;
352
+ // its light spills onto the page: a tight rim and a wide faint one, as much as the ink at the
353
+ // nearest edge lets out, and only from the part still stuck down: the shape on this side of the fold
354
+ // (sL follows the curl, so past it every pixel would map back inside the sticker and glow in full).
355
+ // It shines from the printed side, so this is faint: enough to tell it is lit, not enough to light the page
356
+ if (kind == 10) {
357
+ float d = max(max(shape(q).r, x), 0.0);
358
+ // the nearest point of the edge, found from inside the distance field: past it the gradient is only an echo
359
+ vec2 cq = clamp(q, -0.5 * uSize, 0.5 * uSize);
360
+ vec3 sc = texture(uSdf, cq / uSize + 0.5).rgb;
361
+ vec2 e = cq - sc.gb * max(sc.r, 0.0);
362
+ float near = 0.065 * exp(-d / 4.5) * glowNear(e - sc.gb * 4.0, 4.0);
363
+ // the far light is the whole sticker's: its artwork in a handful of texels, so nothing in it can make a seam
364
+ vec2 ts = vec2(textureSize(uArt, 0));
365
+ float far = 0.03 * exp(-d / 16.0) * (1.0 - smoothstep(0.5 * HALO, HALO, d)) * glowNear(cq, log2(max(ts.x, ts.y)) - 1.5);
366
+ // a layer over the shadow, as opaque as its brightest channel: a premultiplied pixel brighter than its
367
+ // alpha is not a colour, and a browser that clips it to one leaves the light only where the shadow is
368
+ vec3 light = uGlow * GLOW * (near + far) * uLay.y;
369
+ float la = max(light.r, max(light.g, light.b));
370
+ col = vec4(light, la) + col * (1.0 - la);
371
+ }
372
+ col = col * (1.0 - sheet.a) + sheet;
373
+ fragColor = col * uAlpha;
374
+ }`;
375
+
376
+ // ---------------------------------------------------------------- maths
377
+
378
+ const clamp = (v, a, b) => Math.min(b, Math.max(a, v));
379
+ const smooth = (a, b, v) => { const t = clamp((v - a) / (b - a), 0, 1); return t * t * (3 - 2 * t); };
380
+ const INF = 1e20;
381
+
382
+ // Felzenszwalb & Huttenlocher squared distance transform, one line at a time.
383
+ function edt1d(grid, offset, stride, n, f, v, z) {
384
+ // A line of one value comes out unchanged. Outside the artwork's box most lines are.
385
+ let same = 1;
386
+ while (same < n && grid[offset + same * stride] === grid[offset]) same++;
387
+ if (same === n) return;
388
+ v[0] = 0; z[0] = -INF; z[1] = INF; f[0] = grid[offset];
389
+ for (let q = 1, k = 0, s = 0; q < n; q++) {
390
+ f[q] = grid[offset + q * stride];
391
+ const q2 = q * q;
392
+ do { const r = v[k]; s = (f[q] - f[r] + q2 - r * r) / (2 * (q - r)); } while (s <= z[k] && --k > -1);
393
+ k++; v[k] = q; z[k] = s; z[k + 1] = INF;
394
+ }
395
+ for (let q = 0, k = 0; q < n; q++) {
396
+ while (z[k + 1] < q) k++;
397
+ const r = v[k], d = q - r;
398
+ grid[offset + q * stride] = f[r] + d * d;
399
+ }
400
+ }
401
+ function edt(grid, w, h) {
402
+ const n = Math.max(w, h);
403
+ const f = new Float64Array(n), z = new Float64Array(n + 1), v = new Uint16Array(n);
404
+ for (let x = 0; x < w; x++) edt1d(grid, x, w, h, f, v, z);
405
+ for (let y = 0; y < h; y++) edt1d(grid, y * w, 1, w, f, v, z);
406
+ }
407
+ // Signed distance (in cells, negative inside) from an anti-aliased coverage map. Growing the shape by
408
+ // `grow` cells or shrinking it by `shrink` needs the distance right only that far from the edge, and
409
+ // given a cell or more, each makes it exact there rather than next to the edge. Growing needs no
410
+ // distance inside, so cells inside read 0, and it takes one distance transform rather than two.
411
+ function signedDistance(cov, w, h, grow = 0, shrink = 0) {
412
+ const n = w * h, outer = new Float64Array(n), inner = new Float64Array(n), out = new Float32Array(n);
413
+ const far = grow >= 1, deep = shrink >= 1;
414
+ for (let i = 0; i < n; i++) {
415
+ let a = cov[i];
416
+ // Only a pixel with a neighbour across the 0.5 line holds the edge. Anything else, such as the
417
+ // middle of artwork drawn at 98% opacity, is wholly inside or outside, however soft its alpha.
418
+ const x = i % w, side = a >= 0.5;
419
+ if ((x === 0 || (cov[i - 1] >= 0.5) === side) && (x === w - 1 || (cov[i + 1] >= 0.5) === side) &&
420
+ (i < w || (cov[i - w] >= 0.5) === side) && (i >= n - w || (cov[i + w] >= 0.5) === side)) a = side ? 1 : 0;
421
+ if (a >= 1) { outer[i] = 0; inner[i] = INF; }
422
+ else if (a <= 0) { outer[i] = INF; inner[i] = 0; }
423
+ else {
424
+ // The edge is d past this cell's middle, so a point r further out is r + d from the edge, and
425
+ // one r further in is r - d. The transform reads sqrt(r² + seed): a seed of d² is right next
426
+ // to the cell, but far off it drops d, and an outline grown or shrunk that far follows the
427
+ // cells, with a bump at each one. Seeds of 2·grow·d − d² and −2·shrink·d − d² are right where
428
+ // r + d = grow and r − d = shrink.
429
+ const d = 0.5 - a;
430
+ outer[i] = far ? 2 * grow * d - d * d : d > 0 ? d * d : 0;
431
+ inner[i] = deep ? -2 * shrink * d - d * d : d < 0 ? d * d : 0;
432
+ }
433
+ }
434
+ edt(outer, w, h);
435
+ if (far) { for (let i = 0; i < n; i++) out[i] = Math.sqrt(Math.max(0, outer[i])); return out; }
436
+ edt(inner, w, h);
437
+ for (let i = 0; i < n; i++) out[i] = Math.sqrt(outer[i]) - Math.sqrt(Math.max(0, inner[i]));
438
+ return out;
439
+ }
440
+
441
+ // Background connected to an edge is outside the sticker. The other clear areas
442
+ // are holes: make them stock without touching the artwork texture.
443
+ export function fillEnclosedCoverage(cov, width, height) {
444
+ const outside = new Uint8Array(cov.length), queue = new Uint32Array(cov.length);
445
+ let tail = 0;
446
+ function visit(i) {
447
+ if (outside[i] || cov[i] >= 1) return;
448
+ outside[i] = 1;
449
+ queue[tail++] = i;
450
+ }
451
+
452
+ for (let x = 0; x < width; x++) {
453
+ visit(x);
454
+ visit((height - 1) * width + x);
455
+ }
456
+ for (let y = 1; y < height - 1; y++) {
457
+ visit(y * width);
458
+ visit(y * width + width - 1);
459
+ }
460
+ for (let head = 0; head < tail; head++) {
461
+ const i = queue[head], x = i % width;
462
+ if (x > 0) visit(i - 1);
463
+ if (x + 1 < width) visit(i + 1);
464
+ if (i >= width) visit(i - width);
465
+ if (i + width < cov.length) visit(i + width);
466
+ }
467
+
468
+ // Visit the outer anti-aliased fringe too, so only the inner bevels disappear.
469
+ for (let i = 0; i < cov.length; i++) if (!outside[i]) cov[i] = 1;
470
+ }
471
+
472
+ function convexHull(pts) {
473
+ pts.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
474
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
475
+ const lo = [], up = [];
476
+ for (const p of pts) { while (lo.length > 1 && cross(lo[lo.length - 2], lo[lo.length - 1], p) <= 0) lo.pop(); lo.push(p); }
477
+ for (let i = pts.length - 1; i >= 0; i--) { const p = pts[i]; while (up.length > 1 && cross(up[up.length - 2], up[up.length - 1], p) <= 0) up.pop(); up.push(p); }
478
+ lo.pop(); up.pop();
479
+ return lo.concat(up);
480
+ }
481
+
482
+ // kind: 0 vinyl, 1 holographic, 2 transparent, 3 glitter, 4 mirror, 5 pixie dust, 6 brushed aluminium,
483
+ // 7 prismatic, 8 reflective, 9 kraft, 10 glow in the dark. tack: 0 lifts easily ... 1 clings.
484
+ const FINISHES = {
485
+ gloss: { kind: 0, gloss: 1, grain: 0.012 },
486
+ matte: { kind: 0, gloss: 0.16, grain: 0.04 },
487
+ holo: { kind: 1, gloss: 0.85, grain: 0.01 },
488
+ transparent: { kind: 2, gloss: 1.1, grain: 0 },
489
+ glitter: { kind: 3, gloss: 0.7, grain: 0.01 },
490
+ mirror: { kind: 4, gloss: 1.3, grain: 0 },
491
+ pixie: { kind: 5, gloss: 0.6, grain: 0.02 },
492
+ brushed: { kind: 6, gloss: 0.45, grain: 0.012 },
493
+ prismatic: { kind: 7, gloss: 0.8, grain: 0.008 },
494
+ reflective: { kind: 8, gloss: 0.3, grain: 0.03 },
495
+ kraft: { kind: 9, gloss: 0.05, grain: 0.05, back: [0.84, 0.73, 0.57] },
496
+ glow: { kind: 10, gloss: 0.8, grain: 0.012 },
497
+ 'low-tack': { kind: 0, gloss: 1, grain: 0.012, tack: 0 },
498
+ 'hi-tack': { kind: 0, gloss: 1, grain: 0.012, tack: 1 },
499
+ };
500
+ FINISHES.vinyl = FINISHES.gloss;
501
+
502
+ // ---------------------------------------------------------------- sticker
503
+
504
+ export class Sticker {
505
+ constructor(engine, def) {
506
+ this.engine = engine;
507
+ this.id = def.id || null;
508
+ this.width = def.width || 160;
509
+ this.border = def.border == null ? 7 : def.border;
510
+ const named = typeof def.finish === 'string' ? def.finish : def.finish && def.finish.base;
511
+ this.finish = Object.assign({}, FINISHES.gloss, FINISHES[named], typeof def.finish === 'object' ? def.finish : null);
512
+ this.tack = this.finish.tack == null ? 0.5 : clamp(this.finish.tack, 0, 1);
513
+ this.cut = def.cut || 'contour';
514
+ this.fillHoles = this.cut === 'contour' && def.fillHoles === true;
515
+ this.paper = def.paper || [0.992, 0.992, 0.984];
516
+ this.back = def.back || this.finish.back || [0.925, 0.92, 0.905];
517
+ this.showThrough = def.showThrough || 0;
518
+ this.anchor = def.anchor || null;
519
+ this.baseRot = (def.rotation || 0) * Math.PI / 180;
520
+ const off = def.offset || [0, 0, 0];
521
+ this.ox = off[0] || 0; this.oy = off[1] || 0; // where the visitor left it, relative to home
522
+ this.rot = this.baseRot + (off[2] || 0) * Math.PI / 180;
523
+ this.hx = def.x || 0; this.hy = def.y || 0; // home: centre of the anchor element, document px
524
+ this.x = this.hx + this.ox; this.y = this.hy + this.oy;
525
+ this.scale = 1;
526
+ this.hidden = false;
527
+ this.age = engine.reduced ? 1 : 0;
528
+ this.seed = Math.random() * 50;
529
+
530
+ this.state = 'idle'; // idle | peel | held | fly
531
+ this.lift = engine.reduced ? 0 : 20; this.liftV = 0;
532
+ this.fx = 0; this.fy = 0; this.fvx = 0; this.fvy = 0; // fold vector: direction * peeled length (local)
533
+ this.nx = 1; this.ny = 0;
534
+ this.gx = 0; this.gy = 0; // grabbed point (local)
535
+ this.p0x = 0; this.p0y = 0;
536
+ this.floor = 0; this.floorNx = 0; this.floorNy = 0;
537
+ this.pvx = 0; this.pvy = 0; this.pvvx = 0; this.pvvy = 0;
538
+ this.rotV = 0; this.rot0 = this.rot; this.heldT = 0;
539
+ this.hint = null;
540
+ this.ground = 1; // brightness of the page under its home, for the residue mark
541
+ this.fly = null;
542
+
543
+ this.shape = null;
544
+ this.setImage(def.image);
545
+ }
546
+
547
+ /** Offset from home as [dx, dy, extra rotation in degrees]. */
548
+ get offset() { return [Math.round(this.ox), Math.round(this.oy), Math.round((this.rot - this.baseRot) * 1800 / Math.PI) / 10]; }
549
+
550
+ setImage(image) {
551
+ const iw = image.naturalWidth || image.videoWidth || image.width, ih = image.naturalHeight || image.videoHeight || image.height;
552
+ const engine = this.engine, src = image instanceof HTMLImageElement ? image.currentSrc || image.src : '';
553
+ // Stickers cut the same way from the same image file share one shape: its outline and both textures.
554
+ const key = src ? [src, image.crossOrigin, iw, ih, this.width, this.border, this.cut, this.fillHoles].join(' ') : null;
555
+ let shape = key && engine._shapes.get(key);
556
+ if (!shape) {
557
+ const w = this.width, h = w * ih / iw;
558
+ const pad = this.border + 10;
559
+ const W = w + pad * 2, H = h + pad * 2;
560
+ const ts = Math.min(engine.texScale, 2048 / Math.max(W, H));
561
+ const cv = document.createElement('canvas');
562
+ cv.width = Math.round(W * ts); cv.height = Math.round(H * ts);
563
+ const g = cv.getContext('2d');
564
+ g.imageSmoothingQuality = 'high';
565
+ g.drawImage(image, pad * ts, pad * ts, w * ts, h * ts);
566
+ shape = { key, refs: 0, w, h, W, H, canvas: cv, texArt: null, texSdf: null };
567
+ this._buildShape(shape);
568
+ engine._upload(shape);
569
+ if (key) engine._shapes.set(key, shape);
570
+ }
571
+ shape.refs++;
572
+ if (this.shape) engine._unref(this.shape);
573
+ this.shape = shape;
574
+ const { w, h } = shape;
575
+ this.w = w; this.h = h; this.W = shape.W; this.H = shape.H;
576
+ this.rMax = clamp(Math.min(w, h) * 0.09, 7, 22) * this.byTack(1.5, 1, 0.8);
577
+ this.hoverLift = clamp(Math.min(w, h) * 0.1, 8, 17) * this.byTack(1.8, 1, 0.45);
578
+ engine.invalidate();
579
+ }
580
+
581
+ /** A value for a low-tack, an ordinary and a hi-tack sticker, blended by this one's tack. */
582
+ byTack(low, mid, high) { const t = this.tack; return t < 0.5 ? low + (mid - low) * t * 2 : mid + (high - mid) * (t - 0.5) * 2; }
583
+
584
+ // Die-cut outline: grow the artwork's alpha by `border`, rounding inside corners too.
585
+ _buildShape(shape) {
586
+ const { canvas, w, h, W, H } = shape;
587
+ // A borderless cut runs right along the artwork's edge, so it needs a finer outline than a bordered
588
+ // one. A long, thin sticker gets as many cells as a 4:3 one, rather than a few rows of large ones.
589
+ const side = this.border <= 0 ? 420 : 240, cw = canvas.width, ch = canvas.height;
590
+ const k = Math.min(1, Math.max(side / Math.max(cw, ch), side * Math.sqrt(0.75 / (cw * ch))));
591
+ const gw = Math.max(8, Math.round(canvas.width * k)), gh = Math.max(8, Math.round(canvas.height * k));
592
+ const small = document.createElement('canvas');
593
+ small.width = gw; small.height = gh;
594
+ const g = small.getContext('2d', { willReadFrequently: true });
595
+ g.imageSmoothingQuality = 'high';
596
+ g.drawImage(canvas, 0, 0, gw, gh);
597
+ const px = g.getImageData(0, 0, gw, gh).data; // throws for a cross-origin image served without CORS
598
+ const n = gw * gh, cell = W / gw;
599
+ const cov = new Float32Array(n);
600
+ for (let i = 0; i < n; i++) cov[i] = px[i * 4 + 3] / 255;
601
+ if (this.cut !== 'contour') {
602
+ // cut to a plain shape that fills the artwork's box, whatever the artwork's own outline
603
+ const rx = w / 2, ry = h / 2, corner = this.cut === 'rounded' ? Math.min(rx, ry) * 0.24 : 0;
604
+ for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
605
+ const lx = ((x + 0.5) / gw - 0.5) * W, ly = ((y + 0.5) / gh - 0.5) * H;
606
+ let d;
607
+ if (this.cut === 'circle') d = (Math.hypot(lx / rx, ly / ry) - 1) * Math.min(rx, ry);
608
+ else { const qx = Math.abs(lx) - rx + corner, qy = Math.abs(ly) - ry + corner; d = Math.hypot(Math.max(qx, 0), Math.max(qy, 0)) + Math.min(Math.max(qx, qy), 0) - corner; }
609
+ cov[y * gw + x] = clamp(0.5 - d / cell, 0, 1);
610
+ }
611
+ }
612
+ const round = this.border <= 0 ? 0 : Math.max(2, this.border * 0.7); // with no border there is nothing to round into
613
+ const grow = (this.border + round) / cell;
614
+ const d1 = signedDistance(cov, gw, gh, grow);
615
+ for (let i = 0; i < n; i++) cov[i] = clamp(0.5 - d1[i] + grow, 0, 1);
616
+ if (this.fillHoles) fillEnclosedCoverage(cov, gw, gh);
617
+ const d2 = signedDistance(cov, gw, gh, 0, round / cell);
618
+ const sd = new Float32Array(n);
619
+ // A borderless contour normally clips to artwork alpha. Filled holes need the stock mask instead.
620
+ const trim = shape.trim = this.border <= 0 && this.cut === 'contour' && !this.fillHoles;
621
+ const inset = trim ? -0.8 : 0;
622
+ for (let i = 0; i < n; i++) sd[i] = d2[i] * cell + round + inset;
623
+
624
+ const tex = new Float32Array(n * 4), edge = [];
625
+ for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
626
+ const i = y * gw + x;
627
+ const l = sd[y * gw + Math.max(0, x - 1)], r = sd[y * gw + Math.min(gw - 1, x + 1)];
628
+ const u = sd[Math.max(0, y - 1) * gw + x], d = sd[Math.min(gh - 1, y + 1) * gw + x];
629
+ const dx = r - l, dy = d - u, len = Math.sqrt(dx * dx + dy * dy) || 1; // Math.hypot is several times slower
630
+ tex[i * 4] = sd[i]; tex[i * 4 + 1] = dx / len; tex[i * 4 + 2] = dy / len;
631
+ if (sd[i] <= 0 && (l > 0 || r > 0 || u > 0 || d > 0))
632
+ edge.push([((x + 0.5) / gw - 0.5) * W, ((y + 0.5) / gh - 0.5) * H]);
633
+ }
634
+ Object.assign(shape, { sd, gw, gh, sdfTex: tex, hull: convexHull(edge), reach: Math.hypot(W, H) / 2 });
635
+ }
636
+
637
+ // Signed distance and outward direction at a local point.
638
+ sample(lx, ly) {
639
+ const { gw, gh, sd } = this.shape;
640
+ const at = (x, y) => {
641
+ const fx = clamp((x / this.W + 0.5) * gw - 0.5, 0, gw - 1.001), fy = clamp((y / this.H + 0.5) * gh - 0.5, 0, gh - 1.001);
642
+ const ix = fx | 0, iy = fy | 0, tx = fx - ix, ty = fy - iy, i = iy * gw + ix;
643
+ return (sd[i] * (1 - tx) + sd[i + 1] * tx) * (1 - ty) + (sd[i + gw] * (1 - tx) + sd[i + gw + 1] * tx) * ty;
644
+ };
645
+ const out = Math.hypot(Math.max(0, Math.abs(lx) - this.W / 2), Math.max(0, Math.abs(ly) - this.H / 2));
646
+ const e = 2;
647
+ return [at(lx, ly) + out, at(lx + e, ly) - at(lx - e, ly), at(lx, ly + e) - at(lx, ly - e)];
648
+ }
649
+
650
+ // Furthest the die-cut shape reaches in direction (nx, ny).
651
+ support(nx, ny) {
652
+ let m = -INF;
653
+ for (const p of this.shape.hull) { const d = p[0] * nx + p[1] * ny; if (d > m) m = d; }
654
+ return m;
655
+ }
656
+
657
+ radius(tau) { return this.rMax * (1 - Math.exp(-tau / (2.4 * this.rMax))); }
658
+ get tau() { return Math.hypot(this.fx, this.fy); }
659
+ get size() { return this.scale; }
660
+ get renderSize() { return this.scale * (1 + 0.0035 * this.lift); }
661
+
662
+ toLocal(px, py) {
663
+ const c = Math.cos(this.rot), s = Math.sin(this.rot), k = this.renderSize;
664
+ const dx = (px - this.x) / k, dy = (py - this.y) / k;
665
+ return [c * dx + s * dy, -s * dx + c * dy];
666
+ }
667
+ toLocalVec(dx, dy) {
668
+ const c = Math.cos(this.rot), s = Math.sin(this.rot), k = this.size;
669
+ return [(c * dx + s * dy) / k, (-s * dx + c * dy) / k];
670
+ }
671
+ contains(px, py, slop) {
672
+ if (this.hidden || this.age < 0.5) return false;
673
+ const l = this.toLocal(px, py);
674
+ if (Math.abs(l[0]) > this.W / 2 + 12 || Math.abs(l[1]) > this.H / 2 + 12) return false;
675
+ return this.sample(l[0], l[1])[0] <= (slop || 0);
676
+ }
677
+ }
678
+
679
+ // ---------------------------------------------------------------- engine
680
+
681
+ const DEFAULTS = {
682
+ light: [-0.38, -0.56, 0.74], // direction to the light (x right, y down, z towards the viewer)
683
+ shadowSlope: [0.3, 0.52], // shadow offset per px of height
684
+ shadow: 0.55, // shadow opacity; raise it on dark pages
685
+ maxDpr: 2,
686
+ detachAt: 0.74, // fraction of the sticker that must be peeled before it lets go
687
+ liftHeight: 15,
688
+ hoverPeel: true, // an edge lifts towards a hovering mouse
689
+ touchHold: 170, // ms a finger must rest on a sticker before it grabs (0 = at once, but then it blocks scrolling)
690
+ zIndex: 30,
691
+ overscan: 240, // px the canvas extends above and below the viewport
692
+ persist: null, // localStorage key; stickers with an id remember where they were left
693
+ residue: 1, // strength of the mark a sticker leaves where it was first stuck; 0 turns it off
694
+ gyroscope: false, // highlights slide as a phone or tablet tilts; iOS asks for permission on the first tap
695
+ };
696
+
697
+ export class StickerEngine {
698
+ constructor(options) {
699
+ this.opts = Object.assign({}, DEFAULTS, options);
700
+ this.stickers = [];
701
+ this._shapes = new Map(); // shared shapes by artwork and cut, see Sticker#setImage
702
+ this.pointer = { cx: 0, cy: 0, x: 0, y: 0, type: 'mouse', seen: false };
703
+ this.env = { x: 0, y: 0 };
704
+ this.tilt = { x: 0, y: 0, rest: null };
705
+ this.mirror = { texture: null, source: null, width: 0, height: 0, flipX: false };
706
+ this.active = null; this.hover = null; this.pointerId = null; this.pending = null;
707
+ this.explode = 0; this.explodeTarget = 0;
708
+ this.onHover = null; this.onChange = null;
709
+ this.reduced = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
710
+ this.dpr = Math.min(this.opts.maxDpr, window.devicePixelRatio || 1);
711
+ this.texScale = Math.max(2, this.dpr) * 1.3;
712
+ this.win = { top: 0, w: 0, h: 0 };
713
+ this.docW = 1; this.docH = 1; this.origin = { x: 0, y: 0 };
714
+ this._tx = 0; this._ty = 0; this._vw = 0; this._vh = 0;
715
+ this._dirty = true; this._raf = 0; this._off = []; this._eatClick = false; this._redraw = true; this._lit = false;
716
+ this.saved = {};
717
+ if (this.opts.persist) { try { this.saved = JSON.parse(localStorage.getItem(this.opts.persist) || '{}') || {}; } catch (_) {} }
718
+
719
+ const z = this.opts.zIndex;
720
+ const cv = this.canvas = document.createElement('canvas');
721
+ cv.setAttribute('aria-hidden', 'true');
722
+ cv.style.cssText = `position:absolute;left:0;top:0;pointer-events:none;display:block;z-index:${z}`;
723
+ // While the pointer is over a sticker this invisible sheet takes the events, so the page underneath does not react.
724
+ const ct = this.catcher = document.createElement('div');
725
+ ct.setAttribute('aria-hidden', 'true');
726
+ ct.style.cssText = `position:fixed;inset:0;z-index:${z};pointer-events:none;touch-action:none;user-select:none;-webkit-user-select:none;-webkit-touch-callout:none`;
727
+
728
+ const gl = this.gl = cv.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: false });
729
+ this.ok = !!gl;
730
+ this._tick = this._tick.bind(this);
731
+ if (!gl) return;
732
+ document.body.append(cv, ct);
733
+ try {
734
+ this._initGL();
735
+ this._listen();
736
+ this.invalidate();
737
+ } catch (error) {
738
+ this.destroy();
739
+ throw error;
740
+ }
741
+ }
742
+
743
+ destroy() {
744
+ cancelAnimationFrame(this._raf);
745
+ clearTimeout(this._holdTimer);
746
+ for (const off of this._off) off();
747
+ this._off = [];
748
+ if (this._ro) this._ro.disconnect();
749
+ this.mirror.source = null;
750
+ if (this.gl) {
751
+ this.gl.deleteTexture(this.mirror.texture);
752
+ const shapes = new Set(this._shapes.values());
753
+ for (const s of this.stickers) shapes.add(s.shape);
754
+ for (const shape of shapes) this._free(shape);
755
+ const lose = this.gl.getExtension('WEBGL_lose_context');
756
+ if (lose) lose.loseContext();
757
+ }
758
+ this.stickers = [];
759
+ this.canvas.remove(); this.catcher.remove();
760
+ this._selectable(true);
761
+ this.ok = false;
762
+ }
763
+
764
+ _initGL() {
765
+ const gl = this.gl;
766
+ const sh = (type, src) => {
767
+ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
768
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
769
+ return s;
770
+ };
771
+ const p = gl.createProgram();
772
+ gl.attachShader(p, sh(gl.VERTEX_SHADER, VERT)); gl.attachShader(p, sh(gl.FRAGMENT_SHADER, FRAG));
773
+ gl.linkProgram(p);
774
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
775
+ gl.useProgram(p);
776
+ this.u = {};
777
+ const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
778
+ for (let i = 0; i < n; i++) { const name = gl.getActiveUniform(p, i).name; this.u[name] = gl.getUniformLocation(p, name); }
779
+ const buf = gl.createBuffer();
780
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
781
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
782
+ const loc = gl.getAttribLocation(p, 'aPos');
783
+ gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
784
+ gl.uniform1i(this.u.uArt, 0); gl.uniform1i(this.u.uSdf, 1);
785
+ gl.uniform1i(this.u.uMirror, 2);
786
+ this._maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
787
+ const mirror = this.mirror;
788
+ mirror.texture = gl.createTexture();
789
+ mirror.width = mirror.height = 0;
790
+ gl.activeTexture(gl.TEXTURE2);
791
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
792
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
793
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
794
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
795
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
796
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
797
+ if (mirror.source) this.setMirrorSource(mirror.source, { flipX: mirror.flipX });
798
+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
799
+ gl.clearColor(0, 0, 0, 0);
800
+ }
801
+
802
+ _upload(shape) {
803
+ const gl = this.gl;
804
+ if (!gl) return;
805
+ if (!shape.texArt) { shape.texArt = gl.createTexture(); shape.texSdf = gl.createTexture(); }
806
+ gl.activeTexture(gl.TEXTURE0);
807
+ gl.bindTexture(gl.TEXTURE_2D, shape.texArt);
808
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
809
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, shape.canvas);
810
+ gl.generateMipmap(gl.TEXTURE_2D);
811
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
812
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
813
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
814
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
815
+ gl.bindTexture(gl.TEXTURE_2D, shape.texSdf);
816
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
817
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, shape.gw, shape.gh, 0, gl.RGBA, gl.FLOAT, shape.sdfTex);
818
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
819
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
820
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
821
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
822
+ shape.sdfTex = null;
823
+ this.invalidate();
824
+ }
825
+
826
+ // A shape no sticker uses any more is kept until the next frame, so artwork that is removed and
827
+ // added again at once, as a framework does when a prop changes, finds it still there.
828
+ _unref(shape) {
829
+ if (--shape.refs > 0) return;
830
+ if (shape.key) this.invalidate(); else this._free(shape);
831
+ }
832
+ _free(shape) { if (this.gl) { this.gl.deleteTexture(shape.texArt); this.gl.deleteTexture(shape.texSdf); } }
833
+
834
+ // ------------------------------------------------------------ public
835
+
836
+ /** Add a sticker. `image` must be loaded; `anchor` is the element whose centre is the sticker's home. */
837
+ add(def) {
838
+ const saved = def.id && this.saved[def.id];
839
+ const s = new Sticker(this, saved ? Object.assign({}, def, { offset: saved }) : def);
840
+ s.ground = this._groundOf(s.anchor);
841
+ this.stickers.push(s);
842
+ this.invalidate();
843
+ return s;
844
+ }
845
+
846
+ remove(s) {
847
+ const i = this.stickers.indexOf(s);
848
+ if (i < 0) return;
849
+ if (this.active === s) this._release();
850
+ if (this.hover === s) this._setHover(null);
851
+ if (this.pending && this.pending.s === s) this._cancelPending();
852
+ this.stickers.splice(i, 1);
853
+ this._unref(s.shape);
854
+ this.invalidate();
855
+ }
856
+
857
+ /** Send every sticker (or one) back to where the layout put it. */
858
+ reset(sticker) {
859
+ const list = sticker ? [sticker] : this.stickers;
860
+ list.forEach((s, i) => {
861
+ if (this.active === s) this._release();
862
+ if (this.reduced) { s.ox = 0; s.oy = 0; s.rot = s.baseRot; s.state = 'idle'; return; }
863
+ s.state = 'fly';
864
+ s.fly = { ox: s.ox, oy: s.oy, r: s.rot, t: -i * 0.035, d: 0.5 };
865
+ });
866
+ this._save();
867
+ this.invalidate();
868
+ }
869
+
870
+ /** Tip every sticker back and pull its layers apart (shadow, vinyl, ink, laminate). */
871
+ setExploded(on) {
872
+ this.explodeTarget = on ? 1 : 0;
873
+ if (this.reduced) this.explode = this.explodeTarget;
874
+ this._release(); this._setHover(null);
875
+ this.invalidate();
876
+ }
877
+
878
+ /** Upload a caller-owned image or frame for the mirror material. No capture or playback here. */
879
+ setMirrorSource(source, { flipX = false } = {}) {
880
+ const gl = this.gl, mirror = this.mirror;
881
+ if (source === null) {
882
+ mirror.source = null;
883
+ if (mirror.width > 0 && this.ok && !gl.isContextLost()) {
884
+ gl.activeTexture(gl.TEXTURE2);
885
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
886
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
887
+ }
888
+ mirror.width = mirror.height = 0;
889
+ this.invalidate();
890
+ return true;
891
+ }
892
+
893
+ if (!this.ok || gl.isContextLost() || !mirror.texture) return false;
894
+ const width = source.videoWidth ?? source.naturalWidth ?? source.width;
895
+ const height = source.videoHeight ?? source.naturalHeight ?? source.height;
896
+ if (!width || !height || width > this._maxTextureSize || height > this._maxTextureSize
897
+ || source.complete === false || (source.videoWidth !== undefined && source.readyState < 2)) return false;
898
+
899
+ gl.activeTexture(gl.TEXTURE2);
900
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
901
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
902
+ try {
903
+ if (mirror.width === width && mirror.height === height) {
904
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, source);
905
+ } else {
906
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
907
+ }
908
+ } catch (_) {
909
+ // E.g. a tainted canvas or video served without CORS.
910
+ return false;
911
+ }
912
+ Object.assign(mirror, { source, width, height, flipX });
913
+ this.invalidate();
914
+ return true;
915
+ }
916
+
917
+ toFront(s) {
918
+ const i = this.stickers.indexOf(s);
919
+ if (i >= 0 && i < this.stickers.length - 1) { this.stickers.splice(i, 1); this.stickers.push(s); }
920
+ }
921
+
922
+ invalidate() { this._redraw = true; this._wake(); }
923
+ // A frame that only draws if something on screen changed, see _tick.
924
+ _wake() { if (!this._raf && this.ok) this._raf = requestAnimationFrame(this._tick); }
925
+
926
+ hitTest(x, y, slop) {
927
+ for (let i = this.stickers.length - 1; i >= 0; i--) if (this.stickers[i].contains(x, y, slop)) return this.stickers[i];
928
+ return null;
929
+ }
930
+
931
+ // ------------------------------------------------------------ page geometry
932
+
933
+ // The canvas is a window a little taller than the viewport, positioned in the document so it
934
+ // scrolls with the page. Each frame it is moved to wherever the viewport is and redrawn.
935
+ // Brightness (0..1) of the first opaque background behind an element.
936
+ _groundOf(el) {
937
+ if (!this._probe) { const c = document.createElement('canvas'); c.width = c.height = 1; this._probe = c.getContext('2d', { willReadFrequently: true }); }
938
+ const g = this._probe;
939
+ for (let node = el || document.body; node && node.nodeType === 1; node = node.parentElement) {
940
+ const colour = getComputedStyle(node).backgroundColor;
941
+ if (!colour || colour === 'transparent') continue;
942
+ g.clearRect(0, 0, 1, 1); g.fillStyle = '#000'; g.fillStyle = colour; g.fillRect(0, 0, 1, 1);
943
+ const d = g.getImageData(0, 0, 1, 1).data;
944
+ if (d[3] > 127) return (0.299 * d[0] + 0.587 * d[1] + 0.114 * d[2]) / 255;
945
+ }
946
+ return getComputedStyle(document.documentElement).colorScheme.indexOf('dark') >= 0 && window.matchMedia('(prefers-color-scheme: dark)').matches ? 0.07 : 1;
947
+ }
948
+
949
+ _measure() {
950
+ for (const s of this.stickers) s.ground = this._groundOf(s.anchor);
951
+ const de = document.documentElement, cv = this.canvas;
952
+ cv.style.display = 'none'; // so the canvas itself does not hold the page open
953
+ this.docH = Math.max(de.scrollHeight, de.clientHeight); this.docW = de.clientWidth;
954
+ cv.style.display = 'block';
955
+ const r = cv.getBoundingClientRect();
956
+ this.origin.x = r.left + window.scrollX - this._tx; this.origin.y = r.top + window.scrollY - this._ty;
957
+ this.dpr = Math.min(this.opts.maxDpr, window.devicePixelRatio || 1);
958
+ // phone toolbars change innerHeight while scrolling; only ever grow until the width changes
959
+ if (window.innerWidth !== this._vw) { this._vw = window.innerWidth; this._vh = window.innerHeight; }
960
+ else this._vh = Math.max(this._vh, window.innerHeight);
961
+ }
962
+
963
+ _placeWindow(sy) {
964
+ const cv = this.canvas, win = this.win;
965
+ const h = Math.min(this._vh + 2 * this.opts.overscan, this.docH), w = this.docW;
966
+ const top = clamp(sy - this.opts.overscan, 0, Math.max(0, this.docH - h));
967
+ const pw = Math.round(w * this.dpr), ph = Math.round(h * this.dpr);
968
+ if (cv.width !== pw || cv.height !== ph) { cv.width = pw; cv.height = ph; cv.style.width = w + 'px'; cv.style.height = h + 'px'; this._redraw = true; }
969
+ const tx = -this.origin.x, ty = top - this.origin.y;
970
+ if (tx !== this._tx || ty !== this._ty) { cv.style.transform = `translate(${tx}px,${ty}px)`; this._tx = tx; this._ty = ty; this._redraw = true; }
971
+ win.top = top; win.w = w; win.h = h;
972
+ }
973
+
974
+ // ------------------------------------------------------------ input
975
+
976
+ _listen() {
977
+ const on = (target, type, fn, opt) => { target.addEventListener(type, fn, opt); this._off.push(() => target.removeEventListener(type, fn, opt)); };
978
+ const cap = { capture: true }, lazy = { capture: true, passive: true }, eager = { capture: true, passive: false };
979
+ on(window, 'pointerdown', (e) => this._down(e), cap);
980
+ on(window, 'pointermove', (e) => this._move(e), lazy);
981
+ on(window, 'pointerup', (e) => this._up(e), cap);
982
+ on(window, 'deviceorientation', (e) => this._tilt(e));
983
+ // iOS only reports orientation once asked, and it can only be asked from a tap
984
+ const orientation = window.DeviceOrientationEvent;
985
+ if (orientation && typeof orientation.requestPermission === 'function') {
986
+ const ask = (e) => {
987
+ if (e.pointerType !== 'touch' || !this.opts.gyroscope) return;
988
+ window.removeEventListener('pointerup', ask, true);
989
+ orientation.requestPermission().catch(() => {});
990
+ };
991
+ on(window, 'pointerup', ask, cap);
992
+ }
993
+ on(window, 'pointercancel', (e) => this._up(e, true), cap);
994
+ on(window, 'touchstart', (e) => { if (this.active || (!this.opts.touchHold && this._touchHit(e))) e.preventDefault(); }, eager);
995
+ on(window, 'touchmove', (e) => { if (this.active && e.cancelable) e.preventDefault(); }, eager);
996
+ on(window, 'contextmenu', (e) => { if (this.active || this.pending) e.preventDefault(); }, cap);
997
+ on(window, 'click', (e) => { if (this._eatClick) { this._eatClick = false; e.preventDefault(); e.stopPropagation(); } }, cap);
998
+ on(window, 'scroll', () => this.invalidate(), lazy);
999
+ on(window, 'resize', () => { this._dirty = true; this.invalidate(); });
1000
+ on(window, 'blur', () => this._release());
1001
+ // a theme switch changes the ground the marks sit on
1002
+ const retheme = () => { this._dirty = true; this.invalidate(); };
1003
+ const scheme = window.matchMedia('(prefers-color-scheme: dark)');
1004
+ if (scheme.addEventListener) on(scheme, 'change', retheme);
1005
+ if (window.MutationObserver) {
1006
+ const watch = this._watch = new MutationObserver(retheme);
1007
+ watch.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] });
1008
+ this._off.push(() => watch.disconnect());
1009
+ }
1010
+ on(document.documentElement, 'pointerleave', () => { this.pointer.seen = false; if (!this.active) this._setHover(null); this.invalidate(); });
1011
+ on(this.canvas, 'webglcontextlost', (e) => e.preventDefault());
1012
+ on(this.canvas, 'webglcontextrestored', () => {
1013
+ this._initGL();
1014
+ for (const [key, shape] of this._shapes) if (!shape.refs) this._shapes.delete(key);
1015
+ const rebuilt = new Set();
1016
+ for (const s of this.stickers) {
1017
+ if (rebuilt.has(s.shape)) continue;
1018
+ rebuilt.add(s.shape);
1019
+ s.shape.texArt = s.shape.texSdf = null; s._buildShape(s.shape); this._upload(s.shape);
1020
+ }
1021
+ });
1022
+ if (window.ResizeObserver) {
1023
+ this._ro = new ResizeObserver(() => { this._dirty = true; this.invalidate(); });
1024
+ this._ro.observe(document.documentElement); this._ro.observe(document.body);
1025
+ }
1026
+ }
1027
+
1028
+ _point(e) {
1029
+ const p = this.pointer;
1030
+ p.cx = e.clientX; p.cy = e.clientY; p.x = e.clientX + window.scrollX; p.y = e.clientY + window.scrollY;
1031
+ p.type = e.pointerType || 'mouse'; p.seen = true;
1032
+ }
1033
+ // How far the device has tilted from the way it is usually held, in screen axes. The resting
1034
+ // angle follows the device over a few seconds, so only turning it moves the highlights.
1035
+ _tilt(e) {
1036
+ if (!this.opts.gyroscope || e.beta == null || e.gamma == null) return;
1037
+ const a = ((screen.orientation && screen.orientation.angle) || 0) * Math.PI / 180, c = Math.cos(a), n = Math.sin(a);
1038
+ const x = e.gamma * c + e.beta * n, y = e.beta * c - e.gamma * n, T = this.tilt;
1039
+ if (!T.rest) { T.rest = { x, y, t: e.timeStamp }; return; }
1040
+ const k = 1 - Math.exp(-Math.max(0, e.timeStamp - T.rest.t) / 3000);
1041
+ T.rest.x += (x - T.rest.x) * k; T.rest.y += (y - T.rest.y) * k; T.rest.t = e.timeStamp;
1042
+ // 25 degrees of tilt slides the highlights about half a screen
1043
+ const px = this._vw * 0.31 / 25;
1044
+ T.x = clamp(x - T.rest.x, -40, 40) * px; T.y = clamp(y - T.rest.y, -40, 40) * px;
1045
+ this.invalidate();
1046
+ }
1047
+ _touchHit(e) { const t = e.changedTouches[0]; return !!t && !this.explodeTarget && !!this.hitTest(t.clientX + window.scrollX, t.clientY + window.scrollY, 7); }
1048
+ _selectable(on) {
1049
+ const st = document.documentElement.style;
1050
+ st.userSelect = on ? '' : 'none'; st.webkitUserSelect = on ? '' : 'none';
1051
+ // Not a theme change, so it needs no re-measure; pass on anything else that changed meanwhile.
1052
+ if (this._watch && this._watch.takeRecords().some(r => r.attributeName !== 'style')) { this._dirty = true; this.invalidate(); }
1053
+ }
1054
+
1055
+ _setHover(s) {
1056
+ if (s === this.hover) return;
1057
+ this.hover = s;
1058
+ this._cursor();
1059
+ if (this.onHover) this.onHover(s);
1060
+ }
1061
+ _cursor() {
1062
+ const on = !!(this.active || this.hover);
1063
+ this.catcher.style.pointerEvents = on ? 'auto' : 'none';
1064
+ this.catcher.style.cursor = this.active ? 'grabbing' : on ? 'grab' : '';
1065
+ }
1066
+
1067
+ _down(e) {
1068
+ if (this.explodeTarget || this.active || this.pending || e.button > 0 || e.isPrimary === false) return;
1069
+ this._point(e);
1070
+ const touch = e.pointerType === 'touch';
1071
+ const s = this.hitTest(this.pointer.x, this.pointer.y, touch ? 7 : 1);
1072
+ if (!s) return;
1073
+ if (touch && this.opts.touchHold > 0) {
1074
+ // A finger might be starting a scroll. Only grab if it rests on the sticker for a moment.
1075
+ this.pending = { s, id: e.pointerId, cx: e.clientX, cy: e.clientY, t: performance.now() };
1076
+ this._selectable(false);
1077
+ this._holdTimer = setTimeout(() => { const p = this.pending; if (p) { this.pending = null; this._grab(p.s, p.id); } }, this.opts.touchHold);
1078
+ return;
1079
+ }
1080
+ if (e.cancelable) e.preventDefault();
1081
+ this._grab(s, e.pointerId);
1082
+ }
1083
+
1084
+ _grab(s, pointerId) {
1085
+ const P = this.pointer;
1086
+ this.pointerId = pointerId;
1087
+ this.active = s;
1088
+ try { this.catcher.setPointerCapture(pointerId); } catch (_) {}
1089
+ s.floor = s.state === 'idle' ? s.tau : 0; s.floorNx = s.nx; s.floorNy = s.ny;
1090
+ s.state = 'peel'; s.fly = null; s.hint = null;
1091
+ s.p0x = P.x; s.p0y = P.y; s.pull = null;
1092
+ [s.gx, s.gy] = s.toLocal(P.x, P.y);
1093
+ if (P.type === 'touch' && !this.reduced) s.liftV += 90; // a small jump tells the finger it has it
1094
+ this.toFront(s);
1095
+ this._selectable(false);
1096
+ this._setHover(s); this._cursor();
1097
+ this.invalidate();
1098
+ }
1099
+
1100
+ _cancelPending() { clearTimeout(this._holdTimer); this.pending = null; this._selectable(true); }
1101
+
1102
+ _move(e) {
1103
+ const p = this.pending;
1104
+ if (p && e.pointerId === p.id && Math.hypot(e.clientX - p.cx, e.clientY - p.cy) > 9) this._cancelPending();
1105
+ if (this.active && e.pointerId !== this.pointerId) return;
1106
+ this._point(e);
1107
+ this._wake();
1108
+ }
1109
+
1110
+ _up(e, cancelled) {
1111
+ const p = this.pending;
1112
+ if (p && e.pointerId === p.id) {
1113
+ this._cancelPending();
1114
+ // a tap: lift a corner for a moment to show the sticker can be peeled
1115
+ if (!cancelled && !this.reduced) { const l = p.s.toLocal(this.pointer.x, this.pointer.y); p.s.hint = { t: 0, lx: l[0], ly: l[1] }; this.invalidate(); }
1116
+ }
1117
+ if (this.active && e.pointerId === this.pointerId) { this._eatClick = true; setTimeout(() => { this._eatClick = false; }, 60); this._release(); }
1118
+ }
1119
+
1120
+ _release() {
1121
+ const s = this.active;
1122
+ if (!s) return;
1123
+ this.active = null;
1124
+ try { this.catcher.releasePointerCapture(this.pointerId); } catch (_) {}
1125
+ this.pointerId = null;
1126
+ const moved = s.state === 'held';
1127
+ if (moved) {
1128
+ // it stays where it was dropped, as an offset from its home in the layout
1129
+ s.x = clamp(s.x, 8, this.docW - 8); s.y = clamp(s.y, 8, this.docH - 8);
1130
+ s.ox = s.x - s.hx; s.oy = s.y - s.hy;
1131
+ }
1132
+ s.state = 'idle'; s.rotV = 0; s.floor = 0;
1133
+ this._selectable(true);
1134
+ if (this.pointer.type === 'touch') this._setHover(null);
1135
+ this._cursor();
1136
+ if (moved) { this._save(); if (this.onChange) this.onChange(s); }
1137
+ this.invalidate();
1138
+ }
1139
+
1140
+ _save() {
1141
+ if (!this.opts.persist) return;
1142
+ const out = {};
1143
+ for (const s of this.stickers) if (s.id) { const o = s.state === 'fly' ? [0, 0, 0] : s.offset; if (o[0] || o[1] || o[2]) out[s.id] = o; }
1144
+ this.saved = out;
1145
+ try { localStorage.setItem(this.opts.persist, JSON.stringify(out)); } catch (_) {}
1146
+ }
1147
+
1148
+ _detach(s) {
1149
+ const c = Math.cos(s.rot), n = Math.sin(s.rot), k = s.renderSize;
1150
+ s.state = 'held'; s.heldT = 0; s.rot0 = s.rot; s.rotV = 0;
1151
+ s.pvx = s.x + (c * s.gx - n * s.gy) * k; s.pvy = s.y + (n * s.gx + c * s.gy) * k;
1152
+ s.pvvx = 0; s.pvvy = 0;
1153
+ }
1154
+
1155
+ // ------------------------------------------------------------ simulation
1156
+
1157
+ // Follow the anchor element: its centre is home, its width sets the scale.
1158
+ _sync(s, sx, sy) {
1159
+ if (s.anchor) {
1160
+ const r = s.anchor.getBoundingClientRect();
1161
+ const { hx, hy, scale, hidden } = s;
1162
+ s.hidden = r.width === 0;
1163
+ if (!s.hidden) { s.hx = r.left + r.width / 2 + sx; s.hy = r.top + r.height / 2 + sy; s.scale = r.width / s.width; }
1164
+ if (s.hx !== hx || s.hy !== hy || s.scale !== scale || s.hidden !== hidden) this._redraw = true; // the layout moved it
1165
+ }
1166
+ if (s.state === 'idle' || s.state === 'peel') { s.x = s.hx + s.ox; s.y = s.hy + s.oy; }
1167
+ }
1168
+
1169
+ _step(s, dt) {
1170
+ const P = this.pointer;
1171
+ let tx = 0, ty = 0;
1172
+ if (s.age < 1) s.age = Math.min(1, s.age + dt / 0.16);
1173
+
1174
+ if (s.state === 'peel') {
1175
+ // The pointer has dragged the grabbed point by `delta`. Fold the sticker so the trailing
1176
+ // edge lifts; once the grabbed point itself is off the page it follows the pointer.
1177
+ const d = s.toLocalVec(P.x - s.p0x, P.y - s.p0y);
1178
+ let delta = Math.hypot(d[0], d[1]);
1179
+ // The first few pixels of a drag pick the way it peels. Pulling back the other way lays
1180
+ // the flap down again rather than peeling the opposite edge.
1181
+ if (!s.pull && delta > 4) s.pull = [-d[0] / delta, -d[1] / delta];
1182
+ if (s.pull) delta = Math.max(0, -(d[0] * s.pull[0] + d[1] * s.pull[1]));
1183
+ if (delta > 0.5) {
1184
+ const len = Math.hypot(d[0], d[1]), nx = -d[0] / len, ny = -d[1] / len;
1185
+ const far = s.support(nx, ny), near = s.support(-nx, -ny);
1186
+ const inset = Math.max(0, far - (s.gx * nx + s.gy * ny));
1187
+ let tau = s.tau;
1188
+ for (let i = 0; i < 5; i++) tau = inset + 0.5 * (delta + Math.PI * s.radius(tau));
1189
+ tau = Math.min(s.byTack(1.6, 1.15, 0.85) * delta, tau);
1190
+ tau = Math.max(tau, s.floor * Math.max(0, nx * s.floorNx + ny * s.floorNy));
1191
+ tx = nx * tau; ty = ny * tau;
1192
+ if (tau > s.byTack(0.48, this.opts.detachAt, 0.93) * (far + near)) this._detach(s);
1193
+ } else { tx = s.floorNx * s.floor; ty = s.floorNy * s.floor; }
1194
+ } else if (s.state === 'idle' && !this.explodeTarget && !this.reduced) {
1195
+ // an edge lifts towards a hovering mouse, or for a moment after a tap
1196
+ let at = null, amount = 0;
1197
+ if (s.hint) {
1198
+ s.hint.t += dt;
1199
+ if (s.hint.t > 0.7) s.hint = null; else { at = [s.hint.lx, s.hint.ly]; amount = 1.5 * Math.sin(Math.PI * Math.min(1, s.hint.t / 0.55)); }
1200
+ } else if (this.hover === s && !this.active && this.opts.hoverPeel && P.type !== 'touch') { at = s.toLocal(P.x, P.y); amount = 1; }
1201
+ if (at) {
1202
+ const [sd, gx, gy] = s.sample(at[0], at[1]);
1203
+ const e = s.hint ? 1 : smooth(Math.min(s.w, s.h) * 0.36, 0, -sd), len = Math.hypot(gx, gy);
1204
+ if (e > 0.01 && len > 1e-4) { tx = gx / len * e * amount * s.hoverLift; ty = gy / len * e * amount * s.hoverLift; }
1205
+ }
1206
+ }
1207
+
1208
+ if (s.state === 'peel') {
1209
+ const k = 1 - Math.exp(-dt * s.byTack(60, 42, 13)); // a clingy sticker gives way slowly
1210
+ s.fx += (tx - s.fx) * k; s.fy += (ty - s.fy) * k; s.fvx = 0; s.fvy = 0;
1211
+ } else {
1212
+ const w = s.state === 'held' ? 17 : s.byTack(11, 15, 24), z = 0.86;
1213
+ for (let i = 0; i < 2; i++) {
1214
+ const h = dt / 2;
1215
+ s.fvx += (w * w * (tx - s.fx) - 2 * z * w * s.fvx) * h; s.fvy += (w * w * (ty - s.fy) - 2 * z * w * s.fvy) * h;
1216
+ s.fx += s.fvx * h; s.fy += s.fvy * h;
1217
+ }
1218
+ }
1219
+ const tau = s.tau;
1220
+ if (tau > 0.02) { s.nx = s.fx / tau; s.ny = s.fy / tau; }
1221
+
1222
+ let liftTarget = s.state === 'held' ? this.opts.liftHeight : 0;
1223
+ if (s.state === 'fly') {
1224
+ const f = s.fly;
1225
+ f.t += dt;
1226
+ const t = clamp(f.t / f.d, 0, 1), e = 1 - t * t * (3 - 2 * t);
1227
+ s.ox = f.ox * e; s.oy = f.oy * e; s.rot = s.baseRot + (f.r - s.baseRot) * e;
1228
+ s.x = s.hx + s.ox; s.y = s.hy + s.oy;
1229
+ liftTarget = f.t > 0 && t < 0.8 ? this.opts.liftHeight : 0;
1230
+ if (t >= 1) { s.state = 'idle'; s.fly = null; }
1231
+ }
1232
+ {
1233
+ const w = liftTarget > 0 ? 17 : 25, z = liftTarget > 0 ? 0.8 : 0.5;
1234
+ for (let i = 0; i < 2; i++) {
1235
+ const h = dt / 2;
1236
+ s.liftV += (w * w * (liftTarget - s.lift) - 2 * z * w * s.liftV) * h;
1237
+ s.lift += s.liftV * h;
1238
+ }
1239
+ }
1240
+
1241
+ if (s.state === 'held') {
1242
+ // the grabbed point is pulled to the pointer; the rest swings behind it
1243
+ s.heldT += dt;
1244
+ const w = 20 + 30 * clamp(s.heldT / 0.35, 0, 1), z = 0.82;
1245
+ const px = clamp(P.cx, 6, this._vw - 6) + window.scrollX, py = clamp(P.cy, 6, window.innerHeight - 6) + window.scrollY;
1246
+ const k = s.size;
1247
+ for (let i = 0; i < 2; i++) {
1248
+ const h = dt / 2;
1249
+ s.pvvx += (w * w * (px - s.pvx) - 2 * z * w * s.pvvx) * h; s.pvvy += (w * w * (py - s.pvy) - 2 * z * w * s.pvvy) * h;
1250
+ s.pvx += s.pvvx * h; s.pvy += s.pvvy * h;
1251
+ const c = Math.cos(s.rot), n = Math.sin(s.rot);
1252
+ const rx = -(c * s.gx - n * s.gy), ry = -(n * s.gx + c * s.gy);
1253
+ const torque = (ry * s.pvvx - rx * s.pvvy) / k;
1254
+ s.rotV += (torque * 4.2e-4 - 2 * 0.5 * 12 * s.rotV - 144 * (s.rot - s.rot0)) * h;
1255
+ s.rot = clamp(s.rot + s.rotV * h, s.rot0 - 0.4, s.rot0 + 0.4);
1256
+ }
1257
+ const c = Math.cos(s.rot), n = Math.sin(s.rot), kr = s.renderSize;
1258
+ s.x = s.pvx - (c * s.gx - n * s.gy) * kr; s.y = s.pvy - (n * s.gx + c * s.gy) * kr;
1259
+ }
1260
+
1261
+ const settling = Math.abs(tx - s.fx) + Math.abs(ty - s.fy) > 0.03 || Math.abs(s.fvx) + Math.abs(s.fvy) > 0.5
1262
+ || Math.abs(liftTarget - s.lift) > 0.02 || Math.abs(s.liftV) > 0.3 || s.age < 1 || !!s.hint;
1263
+ if (!settling && s.state === 'idle') { s.fx = tx; s.fy = ty; s.fvx = s.fvy = 0; s.lift = liftTarget; s.liftV = 0; }
1264
+ return settling || s.state === 'held' || s.state === 'fly';
1265
+ }
1266
+
1267
+ _tick(now) {
1268
+ this._raf = 0;
1269
+ if (!this.ok) return;
1270
+ for (const [key, shape] of this._shapes) if (!shape.refs) { this._shapes.delete(key); this._free(shape); }
1271
+ let dt = (now - (this._last || now)) / 1000;
1272
+ this._last = now;
1273
+ if (!(dt > 0) || dt > 0.1) dt = 1 / 60;
1274
+ dt = Math.min(dt, 1 / 30);
1275
+ let busy = false;
1276
+
1277
+ if (this._dirty) { this._dirty = false; this._measure(); }
1278
+ const sx = window.scrollX, sy = window.scrollY, P = this.pointer;
1279
+ P.x = P.cx + sx; P.y = P.cy + sy;
1280
+ for (const s of this.stickers) this._sync(s, sx, sy);
1281
+ const hover = this.hover;
1282
+ if (!this.active && !this.explodeTarget && P.type !== 'touch') this._setHover(P.seen ? this.hitTest(P.x, P.y, 1) : null);
1283
+
1284
+ // highlights slide a little as the device tilts, as if the viewer moved their head
1285
+ // read the option every frame so turning it off settles the highlights back
1286
+ if (!this.opts.gyroscope) { this.tilt.x = this.tilt.y = 0; this.tilt.rest = null; }
1287
+ const ex = this.tilt.x, ey = this.tilt.y;
1288
+ const k = this.reduced ? 1 : 1 - Math.exp(-dt * 9);
1289
+ this.env.x += (ex - this.env.x) * k; this.env.y += (ey - this.env.y) * k;
1290
+ if (Math.abs(ex - this.env.x) + Math.abs(ey - this.env.y) > 0.4) busy = true;
1291
+
1292
+ if (this.explode !== this.explodeTarget) {
1293
+ this.explode += (this.explodeTarget - this.explode) * (1 - Math.exp(-dt * 9));
1294
+ if (Math.abs(this.explode - this.explodeTarget) < 0.002) this.explode = this.explodeTarget; else busy = true;
1295
+ }
1296
+ for (const s of this.stickers) if (this._step(s, dt)) busy = true;
1297
+ this._placeWindow(sy);
1298
+ // A pointer moving over bare page changes nothing on screen, unless a reflective sticker in view
1299
+ // follows it. Every other reason for a frame comes through invalidate().
1300
+ if (this._redraw || busy || this.active || this.hover || this.hover !== hover || this._lit) {
1301
+ this._redraw = false;
1302
+ this._render(sx, sy);
1303
+ }
1304
+ if (busy) this.invalidate();
1305
+ }
1306
+
1307
+ // ------------------------------------------------------------ drawing
1308
+
1309
+ _render(sx, sy) {
1310
+ const gl = this.gl, win = this.win, e = this.explode;
1311
+ gl.viewport(0, 0, this.canvas.width, this.canvas.height);
1312
+ gl.clear(gl.COLOR_BUFFER_BIT);
1313
+ gl.uniform2f(this.u.uView, win.w, win.h);
1314
+ gl.uniform2f(this.u.uOff, -sx, win.top - sy); // canvas px -> viewport px, where the lights are fixed
1315
+ gl.uniform2f(this.u.uEnv, this.env.x, this.env.y);
1316
+ gl.uniform3f(this.u.uPtr, this.pointer.cx, this.pointer.cy, this.pointer.seen ? 1 : 0);
1317
+ gl.uniform1f(this.u.uShadow, this.opts.shadow);
1318
+ // marks first, so every sticker sits on top of them
1319
+ if (this.opts.residue > 0) for (const s of this.stickers) {
1320
+ if (s.hidden) continue;
1321
+ const home = s.state === 'idle' && s.tau < 0.02 && s.lift < 0.5 && Math.abs(s.ox) + Math.abs(s.oy) < 0.5 && Math.abs(s.rot - s.baseRot) < 0.002 && e < 0.002;
1322
+ if ((home && s.age >= 1) || s.tack < 0.02) continue; // hidden under its own sticker, or a low-tack one that leaves nothing
1323
+ const reach = (s.shape.reach + 4) * s.scale;
1324
+ if (s.hy + reach < win.top || s.hy - reach > win.top + win.h) continue;
1325
+ this._drawMark(s);
1326
+ }
1327
+ gl.uniform1f(this.u.uMark, 0);
1328
+ this._lit = false;
1329
+ for (const s of this.stickers) {
1330
+ if (s.hidden) continue;
1331
+ const reach = (s.shape.reach + 60 + 2.5 * s.tau) * s.scale + 80 * e;
1332
+ if (s.y + reach < win.top || s.y - reach > win.top + win.h) continue;
1333
+ if (s.finish.kind === 8) this._lit = true; // lit by the pointer
1334
+ if (e < 0.002) { this._draw(s, 0, 0, 0, null); continue; }
1335
+ const gap = 40 * s.size * e;
1336
+ this._draw(s, e, 1.5 * gap, 6 * e, [1, 0, 0, 0]);
1337
+ this._draw(s, e, 0.5 * gap, 2 * e, [0.5 * e + (1 - e), 1, 1 - e, 1 - e]);
1338
+ this._draw(s, e, -0.5 * gap, 2 * e, [0.4 * e, 0, e, 0]);
1339
+ this._draw(s, e, -1.5 * gap, 2 * e, [0.3 * e, 0, 0, e]);
1340
+ }
1341
+ }
1342
+
1343
+ _drawMark(s) {
1344
+ const gl = this.gl, u = this.u;
1345
+ const k = s.scale, c = Math.cos(s.baseRot), n = Math.sin(s.baseRot);
1346
+ gl.uniformMatrix3fv(u.uM, false, [c * k, n * k, 0, -n * k, c * k, 0, s.hx, s.hy - this.win.top, 1]);
1347
+ gl.uniform4f(u.uRect, -s.W / 2, -s.H / 2, s.W / 2, s.H / 2);
1348
+ gl.uniform2f(u.uSize, s.W, s.H);
1349
+ const L = this.opts.light;
1350
+ gl.uniform3f(u.uL, c * L[0] + n * L[1], -n * L[0] + c * L[1], L[2]);
1351
+ gl.uniform2f(u.uRot, c, n);
1352
+ gl.uniform1f(u.uAlpha, s.age);
1353
+ gl.uniform1f(u.uPx, 1 / (this.dpr * k));
1354
+ gl.uniform1f(u.uSeed, s.seed);
1355
+ gl.uniform1f(u.uMark, this.opts.residue * s.byTack(0, 1, 1.9));
1356
+ gl.uniform1f(u.uGround, s.ground);
1357
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, s.shape.texArt);
1358
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, s.shape.texSdf);
1359
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
1360
+ }
1361
+
1362
+ _draw(s, e, dy, extraLift, layers) {
1363
+ const gl = this.gl, u = this.u;
1364
+ const k = s.renderSize, c = Math.cos(s.rot), n = Math.sin(s.rot);
1365
+ // local -> canvas. In exploded view the page plane is seen from an angle (an affine squash).
1366
+ const yaw = -0.5 * e, cy = Math.cos(yaw), sy = Math.sin(yaw), squash = 1 - 0.46 * e;
1367
+ const a = c * k, b = n * k, cc = -n * k, d = c * k;
1368
+ gl.uniformMatrix3fv(u.uM, false, [cy * a - sy * b, (sy * a + cy * b) * squash, 0, cy * cc - sy * d, (sy * cc + cy * d) * squash, 0, s.x, s.y - this.win.top + dy, 1]);
1369
+
1370
+ const tau = e > 0.002 ? 0 : s.tau;
1371
+ const R = s.radius(tau);
1372
+ const lift = s.lift + extraLift;
1373
+ // Room around the texture for what spills out of it. Lying flat, the shadow stays inside the
1374
+ // texture's 10px padding; a peeled flap's shadow and a glowing sticker's light reach far beyond.
1375
+ const wide = tau > 0.3 || s.finish.kind === 10;
1376
+ const margin = (wide ? 34 : 4) + 2.6 * Math.max(0, lift) + (tau > 0.3 ? 1.3 * tau + 3 * R + 24 : 0) + (s.finish.kind === 10 ? 18 : 0);
1377
+ gl.uniform4f(u.uRect, -s.W / 2 - margin, -s.H / 2 - margin, s.W / 2 + margin, s.H / 2 + margin);
1378
+ gl.uniform2f(u.uSize, s.W, s.H);
1379
+ if (tau > 0.02) gl.uniform3f(u.uFold, s.nx, s.ny, s.support(s.nx, s.ny) - tau);
1380
+ else gl.uniform3f(u.uFold, 1, 0, 1e5);
1381
+ gl.uniform1f(u.uR, R);
1382
+ gl.uniform1f(u.uLift, lift);
1383
+ const L = this.opts.light, S = this.opts.shadowSlope;
1384
+ gl.uniform3f(u.uL, c * L[0] + n * L[1], -n * L[0] + c * L[1], L[2]);
1385
+ gl.uniform2f(u.uSh, c * S[0] + n * S[1], -n * S[0] + c * S[1]);
1386
+ gl.uniform2f(u.uRot, c, n);
1387
+ gl.uniform4f(u.uFin, s.finish.gloss, s.finish.kind, s.finish.grain, s.showThrough);
1388
+ if (s.finish.kind === 4) {
1389
+ const { width, height, flipX } = this.mirror;
1390
+ if (width) {
1391
+ const w = s.w + 2 * s.border, h = s.h + 2 * s.border;
1392
+ const ca = Math.abs(c), sa = Math.abs(n);
1393
+ const cover = Math.max((ca * w + sa * h) / width, (sa * w + ca * h) / height);
1394
+ gl.uniform3f(u.uMirrorMap, 1 / (width * cover), 1 / (height * cover), flipX ? -1 : 1);
1395
+ } else {
1396
+ gl.uniform3f(u.uMirrorMap, 0, 0, 0);
1397
+ }
1398
+ }
1399
+ gl.uniform1f(u.uGlow, 1 - smooth(0.15, 0.5, s.ground));
1400
+ gl.uniform1f(u.uTrim, s.shape.trim ? 1 : 0);
1401
+ gl.uniform3fv(u.uPaper, s.paper);
1402
+ gl.uniform3fv(u.uBack, s.back);
1403
+ gl.uniform1f(u.uAlpha, s.age);
1404
+ gl.uniform4fv(u.uLay, layers || [1, 1, 1, 1]);
1405
+ gl.uniform1f(u.uPx, 1 / (this.dpr * k * (1 - 0.3 * e)));
1406
+ gl.uniform1f(u.uSeed, s.seed);
1407
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, s.shape.texArt);
1408
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, s.shape.texSdf);
1409
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
1410
+ }
1411
+ }