@patrick91/stickers 0.0.0-stage → 0.2.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.
@@ -0,0 +1,1397 @@
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. With outsideOnly,
408
+ // cells inside the shape read 0 instead, and it takes one distance transform rather than two.
409
+ function signedDistance(cov, w, h, outsideOnly) {
410
+ const n = w * h, outer = new Float64Array(n), inner = new Float64Array(n), out = new Float32Array(n);
411
+ for (let i = 0; i < n; i++) {
412
+ let a = cov[i];
413
+ // Only a pixel with a neighbour across the 0.5 line holds the edge. Anything else, such as the
414
+ // middle of artwork drawn at 98% opacity, is wholly inside or outside, however soft its alpha.
415
+ const x = i % w, side = a >= 0.5;
416
+ if ((x === 0 || (cov[i - 1] >= 0.5) === side) && (x === w - 1 || (cov[i + 1] >= 0.5) === side) &&
417
+ (i < w || (cov[i - w] >= 0.5) === side) && (i >= n - w || (cov[i + w] >= 0.5) === side)) a = side ? 1 : 0;
418
+ if (a >= 1) { outer[i] = 0; inner[i] = INF; }
419
+ else if (a <= 0) { outer[i] = INF; inner[i] = 0; }
420
+ else { const d = 0.5 - a; outer[i] = d > 0 ? d * d : 0; inner[i] = d < 0 ? d * d : 0; }
421
+ }
422
+ edt(outer, w, h);
423
+ if (outsideOnly) { for (let i = 0; i < n; i++) out[i] = Math.sqrt(outer[i]); return out; }
424
+ edt(inner, w, h);
425
+ for (let i = 0; i < n; i++) out[i] = Math.sqrt(outer[i]) - Math.sqrt(inner[i]);
426
+ return out;
427
+ }
428
+
429
+ // Background connected to an edge is outside the sticker. The other clear areas
430
+ // are holes: make them stock without touching the artwork texture.
431
+ export function fillEnclosedCoverage(cov, width, height) {
432
+ const outside = new Uint8Array(cov.length), queue = new Uint32Array(cov.length);
433
+ let tail = 0;
434
+ function visit(i) {
435
+ if (outside[i] || cov[i] >= 1) return;
436
+ outside[i] = 1;
437
+ queue[tail++] = i;
438
+ }
439
+
440
+ for (let x = 0; x < width; x++) {
441
+ visit(x);
442
+ visit((height - 1) * width + x);
443
+ }
444
+ for (let y = 1; y < height - 1; y++) {
445
+ visit(y * width);
446
+ visit(y * width + width - 1);
447
+ }
448
+ for (let head = 0; head < tail; head++) {
449
+ const i = queue[head], x = i % width;
450
+ if (x > 0) visit(i - 1);
451
+ if (x + 1 < width) visit(i + 1);
452
+ if (i >= width) visit(i - width);
453
+ if (i + width < cov.length) visit(i + width);
454
+ }
455
+
456
+ // Visit the outer anti-aliased fringe too, so only the inner bevels disappear.
457
+ for (let i = 0; i < cov.length; i++) if (!outside[i]) cov[i] = 1;
458
+ }
459
+
460
+ function convexHull(pts) {
461
+ pts.sort((a, b) => a[0] - b[0] || a[1] - b[1]);
462
+ const cross = (o, a, b) => (a[0] - o[0]) * (b[1] - o[1]) - (a[1] - o[1]) * (b[0] - o[0]);
463
+ const lo = [], up = [];
464
+ 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); }
465
+ 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); }
466
+ lo.pop(); up.pop();
467
+ return lo.concat(up);
468
+ }
469
+
470
+ // kind: 0 vinyl, 1 holographic, 2 transparent, 3 glitter, 4 mirror, 5 pixie dust, 6 brushed aluminium,
471
+ // 7 prismatic, 8 reflective, 9 kraft, 10 glow in the dark. tack: 0 lifts easily ... 1 clings.
472
+ const FINISHES = {
473
+ gloss: { kind: 0, gloss: 1, grain: 0.012 },
474
+ matte: { kind: 0, gloss: 0.16, grain: 0.04 },
475
+ holo: { kind: 1, gloss: 0.85, grain: 0.01 },
476
+ transparent: { kind: 2, gloss: 1.1, grain: 0 },
477
+ glitter: { kind: 3, gloss: 0.7, grain: 0.01 },
478
+ mirror: { kind: 4, gloss: 1.3, grain: 0 },
479
+ pixie: { kind: 5, gloss: 0.6, grain: 0.02 },
480
+ brushed: { kind: 6, gloss: 0.45, grain: 0.012 },
481
+ prismatic: { kind: 7, gloss: 0.8, grain: 0.008 },
482
+ reflective: { kind: 8, gloss: 0.3, grain: 0.03 },
483
+ kraft: { kind: 9, gloss: 0.05, grain: 0.05, back: [0.84, 0.73, 0.57] },
484
+ glow: { kind: 10, gloss: 0.8, grain: 0.012 },
485
+ 'low-tack': { kind: 0, gloss: 1, grain: 0.012, tack: 0 },
486
+ 'hi-tack': { kind: 0, gloss: 1, grain: 0.012, tack: 1 },
487
+ };
488
+ FINISHES.vinyl = FINISHES.gloss;
489
+
490
+ // ---------------------------------------------------------------- sticker
491
+
492
+ export class Sticker {
493
+ constructor(engine, def) {
494
+ this.engine = engine;
495
+ this.id = def.id || null;
496
+ this.width = def.width || 160;
497
+ this.border = def.border == null ? 7 : def.border;
498
+ const named = typeof def.finish === 'string' ? def.finish : def.finish && def.finish.base;
499
+ this.finish = Object.assign({}, FINISHES.gloss, FINISHES[named], typeof def.finish === 'object' ? def.finish : null);
500
+ this.tack = this.finish.tack == null ? 0.5 : clamp(this.finish.tack, 0, 1);
501
+ this.cut = def.cut || 'contour';
502
+ this.fillHoles = this.cut === 'contour' && def.fillHoles === true;
503
+ this.paper = def.paper || [0.992, 0.992, 0.984];
504
+ this.back = def.back || this.finish.back || [0.925, 0.92, 0.905];
505
+ this.showThrough = def.showThrough || 0;
506
+ this.anchor = def.anchor || null;
507
+ this.baseRot = (def.rotation || 0) * Math.PI / 180;
508
+ const off = def.offset || [0, 0, 0];
509
+ this.ox = off[0] || 0; this.oy = off[1] || 0; // where the visitor left it, relative to home
510
+ this.rot = this.baseRot + (off[2] || 0) * Math.PI / 180;
511
+ this.hx = def.x || 0; this.hy = def.y || 0; // home: centre of the anchor element, document px
512
+ this.x = this.hx + this.ox; this.y = this.hy + this.oy;
513
+ this.scale = 1;
514
+ this.hidden = false;
515
+ this.age = engine.reduced ? 1 : 0;
516
+ this.seed = Math.random() * 50;
517
+
518
+ this.state = 'idle'; // idle | peel | held | fly
519
+ this.lift = engine.reduced ? 0 : 20; this.liftV = 0;
520
+ this.fx = 0; this.fy = 0; this.fvx = 0; this.fvy = 0; // fold vector: direction * peeled length (local)
521
+ this.nx = 1; this.ny = 0;
522
+ this.gx = 0; this.gy = 0; // grabbed point (local)
523
+ this.p0x = 0; this.p0y = 0;
524
+ this.floor = 0; this.floorNx = 0; this.floorNy = 0;
525
+ this.pvx = 0; this.pvy = 0; this.pvvx = 0; this.pvvy = 0;
526
+ this.rotV = 0; this.rot0 = this.rot; this.heldT = 0;
527
+ this.hint = null;
528
+ this.ground = 1; // brightness of the page under its home, for the residue mark
529
+ this.fly = null;
530
+
531
+ this.shape = null;
532
+ this.setImage(def.image);
533
+ }
534
+
535
+ /** Offset from home as [dx, dy, extra rotation in degrees]. */
536
+ get offset() { return [Math.round(this.ox), Math.round(this.oy), Math.round((this.rot - this.baseRot) * 1800 / Math.PI) / 10]; }
537
+
538
+ setImage(image) {
539
+ const iw = image.naturalWidth || image.videoWidth || image.width, ih = image.naturalHeight || image.videoHeight || image.height;
540
+ const engine = this.engine, src = image instanceof HTMLImageElement ? image.currentSrc || image.src : '';
541
+ // Stickers cut the same way from the same image file share one shape: its outline and both textures.
542
+ const key = src ? [src, image.crossOrigin, iw, ih, this.width, this.border, this.cut, this.fillHoles].join(' ') : null;
543
+ let shape = key && engine._shapes.get(key);
544
+ if (!shape) {
545
+ const w = this.width, h = w * ih / iw;
546
+ const pad = this.border + 10;
547
+ const W = w + pad * 2, H = h + pad * 2;
548
+ const ts = Math.min(engine.texScale, 2048 / Math.max(W, H));
549
+ const cv = document.createElement('canvas');
550
+ cv.width = Math.round(W * ts); cv.height = Math.round(H * ts);
551
+ const g = cv.getContext('2d');
552
+ g.imageSmoothingQuality = 'high';
553
+ g.drawImage(image, pad * ts, pad * ts, w * ts, h * ts);
554
+ shape = { key, refs: 0, w, h, W, H, canvas: cv, texArt: null, texSdf: null };
555
+ this._buildShape(shape);
556
+ engine._upload(shape);
557
+ if (key) engine._shapes.set(key, shape);
558
+ }
559
+ shape.refs++;
560
+ if (this.shape) engine._unref(this.shape);
561
+ this.shape = shape;
562
+ const { w, h } = shape;
563
+ this.w = w; this.h = h; this.W = shape.W; this.H = shape.H;
564
+ this.rMax = clamp(Math.min(w, h) * 0.09, 7, 22) * this.byTack(1.5, 1, 0.8);
565
+ this.hoverLift = clamp(Math.min(w, h) * 0.1, 8, 17) * this.byTack(1.8, 1, 0.45);
566
+ engine.invalidate();
567
+ }
568
+
569
+ /** A value for a low-tack, an ordinary and a hi-tack sticker, blended by this one's tack. */
570
+ byTack(low, mid, high) { const t = this.tack; return t < 0.5 ? low + (mid - low) * t * 2 : mid + (high - mid) * (t - 0.5) * 2; }
571
+
572
+ // Die-cut outline: grow the artwork's alpha by `border`, rounding inside corners too.
573
+ _buildShape(shape) {
574
+ const { canvas, w, h, W, H } = shape;
575
+ // a borderless cut runs right along the artwork's edge, so it needs a finer outline than a bordered one
576
+ const k = Math.min(1, (this.border <= 0 ? 420 : 240) / Math.max(canvas.width, canvas.height));
577
+ const gw = Math.max(8, Math.round(canvas.width * k)), gh = Math.max(8, Math.round(canvas.height * k));
578
+ const small = document.createElement('canvas');
579
+ small.width = gw; small.height = gh;
580
+ const g = small.getContext('2d', { willReadFrequently: true });
581
+ g.imageSmoothingQuality = 'high';
582
+ g.drawImage(canvas, 0, 0, gw, gh);
583
+ const px = g.getImageData(0, 0, gw, gh).data; // throws for a cross-origin image served without CORS
584
+ const n = gw * gh, cell = W / gw;
585
+ const cov = new Float32Array(n);
586
+ for (let i = 0; i < n; i++) cov[i] = px[i * 4 + 3] / 255;
587
+ if (this.cut !== 'contour') {
588
+ // cut to a plain shape that fills the artwork's box, whatever the artwork's own outline
589
+ const rx = w / 2, ry = h / 2, corner = this.cut === 'rounded' ? Math.min(rx, ry) * 0.24 : 0;
590
+ for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
591
+ const lx = ((x + 0.5) / gw - 0.5) * W, ly = ((y + 0.5) / gh - 0.5) * H;
592
+ let d;
593
+ if (this.cut === 'circle') d = (Math.hypot(lx / rx, ly / ry) - 1) * Math.min(rx, ry);
594
+ 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; }
595
+ cov[y * gw + x] = clamp(0.5 - d / cell, 0, 1);
596
+ }
597
+ }
598
+ const round = this.border <= 0 ? 0 : Math.max(2, this.border * 0.7); // with no border there is nothing to round into
599
+ // Growing by half a cell or more covers every cell inside the artwork fully, however deep it is.
600
+ const d1 = signedDistance(cov, gw, gh, (this.border + round) / cell >= 0.5);
601
+ for (let i = 0; i < n; i++) cov[i] = clamp(0.5 - (d1[i] * cell - (this.border + round)) / cell, 0, 1);
602
+ if (this.fillHoles) fillEnclosedCoverage(cov, gw, gh);
603
+ const d2 = signedDistance(cov, gw, gh);
604
+ const sd = new Float32Array(n);
605
+ // A borderless contour normally clips to artwork alpha. Filled holes need the stock mask instead.
606
+ const trim = shape.trim = this.border <= 0 && this.cut === 'contour' && !this.fillHoles;
607
+ const inset = trim ? -0.8 : 0;
608
+ for (let i = 0; i < n; i++) sd[i] = d2[i] * cell + round + inset;
609
+
610
+ const tex = new Float32Array(n * 4), edge = [];
611
+ for (let y = 0; y < gh; y++) for (let x = 0; x < gw; x++) {
612
+ const i = y * gw + x;
613
+ const l = sd[y * gw + Math.max(0, x - 1)], r = sd[y * gw + Math.min(gw - 1, x + 1)];
614
+ const u = sd[Math.max(0, y - 1) * gw + x], d = sd[Math.min(gh - 1, y + 1) * gw + x];
615
+ const dx = r - l, dy = d - u, len = Math.sqrt(dx * dx + dy * dy) || 1; // Math.hypot is several times slower
616
+ tex[i * 4] = sd[i]; tex[i * 4 + 1] = dx / len; tex[i * 4 + 2] = dy / len;
617
+ if (sd[i] <= 0 && (l > 0 || r > 0 || u > 0 || d > 0))
618
+ edge.push([((x + 0.5) / gw - 0.5) * W, ((y + 0.5) / gh - 0.5) * H]);
619
+ }
620
+ Object.assign(shape, { sd, gw, gh, sdfTex: tex, hull: convexHull(edge), reach: Math.hypot(W, H) / 2 });
621
+ }
622
+
623
+ // Signed distance and outward direction at a local point.
624
+ sample(lx, ly) {
625
+ const { gw, gh, sd } = this.shape;
626
+ const at = (x, y) => {
627
+ 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);
628
+ const ix = fx | 0, iy = fy | 0, tx = fx - ix, ty = fy - iy, i = iy * gw + ix;
629
+ return (sd[i] * (1 - tx) + sd[i + 1] * tx) * (1 - ty) + (sd[i + gw] * (1 - tx) + sd[i + gw + 1] * tx) * ty;
630
+ };
631
+ const out = Math.hypot(Math.max(0, Math.abs(lx) - this.W / 2), Math.max(0, Math.abs(ly) - this.H / 2));
632
+ const e = 2;
633
+ return [at(lx, ly) + out, at(lx + e, ly) - at(lx - e, ly), at(lx, ly + e) - at(lx, ly - e)];
634
+ }
635
+
636
+ // Furthest the die-cut shape reaches in direction (nx, ny).
637
+ support(nx, ny) {
638
+ let m = -INF;
639
+ for (const p of this.shape.hull) { const d = p[0] * nx + p[1] * ny; if (d > m) m = d; }
640
+ return m;
641
+ }
642
+
643
+ radius(tau) { return this.rMax * (1 - Math.exp(-tau / (2.4 * this.rMax))); }
644
+ get tau() { return Math.hypot(this.fx, this.fy); }
645
+ get size() { return this.scale; }
646
+ get renderSize() { return this.scale * (1 + 0.0035 * this.lift); }
647
+
648
+ toLocal(px, py) {
649
+ const c = Math.cos(this.rot), s = Math.sin(this.rot), k = this.renderSize;
650
+ const dx = (px - this.x) / k, dy = (py - this.y) / k;
651
+ return [c * dx + s * dy, -s * dx + c * dy];
652
+ }
653
+ toLocalVec(dx, dy) {
654
+ const c = Math.cos(this.rot), s = Math.sin(this.rot), k = this.size;
655
+ return [(c * dx + s * dy) / k, (-s * dx + c * dy) / k];
656
+ }
657
+ contains(px, py, slop) {
658
+ if (this.hidden || this.age < 0.5) return false;
659
+ const l = this.toLocal(px, py);
660
+ if (Math.abs(l[0]) > this.W / 2 + 12 || Math.abs(l[1]) > this.H / 2 + 12) return false;
661
+ return this.sample(l[0], l[1])[0] <= (slop || 0);
662
+ }
663
+ }
664
+
665
+ // ---------------------------------------------------------------- engine
666
+
667
+ const DEFAULTS = {
668
+ light: [-0.38, -0.56, 0.74], // direction to the light (x right, y down, z towards the viewer)
669
+ shadowSlope: [0.3, 0.52], // shadow offset per px of height
670
+ shadow: 0.55, // shadow opacity; raise it on dark pages
671
+ maxDpr: 2,
672
+ detachAt: 0.74, // fraction of the sticker that must be peeled before it lets go
673
+ liftHeight: 15,
674
+ hoverPeel: true, // an edge lifts towards a hovering mouse
675
+ touchHold: 170, // ms a finger must rest on a sticker before it grabs (0 = at once, but then it blocks scrolling)
676
+ zIndex: 30,
677
+ overscan: 240, // px the canvas extends above and below the viewport
678
+ persist: null, // localStorage key; stickers with an id remember where they were left
679
+ residue: 1, // strength of the mark a sticker leaves where it was first stuck; 0 turns it off
680
+ gyroscope: false, // highlights slide as a phone or tablet tilts; iOS asks for permission on the first tap
681
+ };
682
+
683
+ export class StickerEngine {
684
+ constructor(options) {
685
+ this.opts = Object.assign({}, DEFAULTS, options);
686
+ this.stickers = [];
687
+ this._shapes = new Map(); // shared shapes by artwork and cut, see Sticker#setImage
688
+ this.pointer = { cx: 0, cy: 0, x: 0, y: 0, type: 'mouse', seen: false };
689
+ this.env = { x: 0, y: 0 };
690
+ this.tilt = { x: 0, y: 0, rest: null };
691
+ this.mirror = { texture: null, source: null, width: 0, height: 0, flipX: false };
692
+ this.active = null; this.hover = null; this.pointerId = null; this.pending = null;
693
+ this.explode = 0; this.explodeTarget = 0;
694
+ this.onHover = null; this.onChange = null;
695
+ this.reduced = !!(window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);
696
+ this.dpr = Math.min(this.opts.maxDpr, window.devicePixelRatio || 1);
697
+ this.texScale = Math.max(2, this.dpr) * 1.3;
698
+ this.win = { top: 0, w: 0, h: 0 };
699
+ this.docW = 1; this.docH = 1; this.origin = { x: 0, y: 0 };
700
+ this._tx = 0; this._ty = 0; this._vw = 0; this._vh = 0;
701
+ this._dirty = true; this._raf = 0; this._off = []; this._eatClick = false; this._redraw = true; this._lit = false;
702
+ this.saved = {};
703
+ if (this.opts.persist) { try { this.saved = JSON.parse(localStorage.getItem(this.opts.persist) || '{}') || {}; } catch (_) {} }
704
+
705
+ const z = this.opts.zIndex;
706
+ const cv = this.canvas = document.createElement('canvas');
707
+ cv.setAttribute('aria-hidden', 'true');
708
+ cv.style.cssText = `position:absolute;left:0;top:0;pointer-events:none;display:block;z-index:${z}`;
709
+ // While the pointer is over a sticker this invisible sheet takes the events, so the page underneath does not react.
710
+ const ct = this.catcher = document.createElement('div');
711
+ ct.setAttribute('aria-hidden', 'true');
712
+ 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`;
713
+
714
+ const gl = this.gl = cv.getContext('webgl2', { alpha: true, premultipliedAlpha: true, antialias: false });
715
+ this.ok = !!gl;
716
+ this._tick = this._tick.bind(this);
717
+ if (!gl) return;
718
+ document.body.append(cv, ct);
719
+ try {
720
+ this._initGL();
721
+ this._listen();
722
+ this.invalidate();
723
+ } catch (error) {
724
+ this.destroy();
725
+ throw error;
726
+ }
727
+ }
728
+
729
+ destroy() {
730
+ cancelAnimationFrame(this._raf);
731
+ clearTimeout(this._holdTimer);
732
+ for (const off of this._off) off();
733
+ this._off = [];
734
+ if (this._ro) this._ro.disconnect();
735
+ this.mirror.source = null;
736
+ if (this.gl) {
737
+ this.gl.deleteTexture(this.mirror.texture);
738
+ const shapes = new Set(this._shapes.values());
739
+ for (const s of this.stickers) shapes.add(s.shape);
740
+ for (const shape of shapes) this._free(shape);
741
+ const lose = this.gl.getExtension('WEBGL_lose_context');
742
+ if (lose) lose.loseContext();
743
+ }
744
+ this.stickers = [];
745
+ this.canvas.remove(); this.catcher.remove();
746
+ this._selectable(true);
747
+ this.ok = false;
748
+ }
749
+
750
+ _initGL() {
751
+ const gl = this.gl;
752
+ const sh = (type, src) => {
753
+ const s = gl.createShader(type); gl.shaderSource(s, src); gl.compileShader(s);
754
+ if (!gl.getShaderParameter(s, gl.COMPILE_STATUS)) throw new Error(gl.getShaderInfoLog(s));
755
+ return s;
756
+ };
757
+ const p = gl.createProgram();
758
+ gl.attachShader(p, sh(gl.VERTEX_SHADER, VERT)); gl.attachShader(p, sh(gl.FRAGMENT_SHADER, FRAG));
759
+ gl.linkProgram(p);
760
+ if (!gl.getProgramParameter(p, gl.LINK_STATUS)) throw new Error(gl.getProgramInfoLog(p));
761
+ gl.useProgram(p);
762
+ this.u = {};
763
+ const n = gl.getProgramParameter(p, gl.ACTIVE_UNIFORMS);
764
+ for (let i = 0; i < n; i++) { const name = gl.getActiveUniform(p, i).name; this.u[name] = gl.getUniformLocation(p, name); }
765
+ const buf = gl.createBuffer();
766
+ gl.bindBuffer(gl.ARRAY_BUFFER, buf);
767
+ gl.bufferData(gl.ARRAY_BUFFER, new Float32Array([0, 0, 1, 0, 0, 1, 1, 1]), gl.STATIC_DRAW);
768
+ const loc = gl.getAttribLocation(p, 'aPos');
769
+ gl.enableVertexAttribArray(loc); gl.vertexAttribPointer(loc, 2, gl.FLOAT, false, 0, 0);
770
+ gl.uniform1i(this.u.uArt, 0); gl.uniform1i(this.u.uSdf, 1);
771
+ gl.uniform1i(this.u.uMirror, 2);
772
+ this._maxTextureSize = gl.getParameter(gl.MAX_TEXTURE_SIZE);
773
+ const mirror = this.mirror;
774
+ mirror.texture = gl.createTexture();
775
+ mirror.width = mirror.height = 0;
776
+ gl.activeTexture(gl.TEXTURE2);
777
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
778
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
779
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
780
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
781
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
782
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
783
+ if (mirror.source) this.setMirrorSource(mirror.source, { flipX: mirror.flipX });
784
+ gl.enable(gl.BLEND); gl.blendFunc(gl.ONE, gl.ONE_MINUS_SRC_ALPHA);
785
+ gl.clearColor(0, 0, 0, 0);
786
+ }
787
+
788
+ _upload(shape) {
789
+ const gl = this.gl;
790
+ if (!gl) return;
791
+ if (!shape.texArt) { shape.texArt = gl.createTexture(); shape.texSdf = gl.createTexture(); }
792
+ gl.activeTexture(gl.TEXTURE0);
793
+ gl.bindTexture(gl.TEXTURE_2D, shape.texArt);
794
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, true);
795
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, shape.canvas);
796
+ gl.generateMipmap(gl.TEXTURE_2D);
797
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR_MIPMAP_LINEAR);
798
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
799
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
800
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
801
+ gl.bindTexture(gl.TEXTURE_2D, shape.texSdf);
802
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
803
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA16F, shape.gw, shape.gh, 0, gl.RGBA, gl.FLOAT, shape.sdfTex);
804
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
805
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
806
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
807
+ gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
808
+ shape.sdfTex = null;
809
+ this.invalidate();
810
+ }
811
+
812
+ // A shape no sticker uses any more is kept until the next frame, so artwork that is removed and
813
+ // added again at once, as a framework does when a prop changes, finds it still there.
814
+ _unref(shape) {
815
+ if (--shape.refs > 0) return;
816
+ if (shape.key) this.invalidate(); else this._free(shape);
817
+ }
818
+ _free(shape) { if (this.gl) { this.gl.deleteTexture(shape.texArt); this.gl.deleteTexture(shape.texSdf); } }
819
+
820
+ // ------------------------------------------------------------ public
821
+
822
+ /** Add a sticker. `image` must be loaded; `anchor` is the element whose centre is the sticker's home. */
823
+ add(def) {
824
+ const saved = def.id && this.saved[def.id];
825
+ const s = new Sticker(this, saved ? Object.assign({}, def, { offset: saved }) : def);
826
+ s.ground = this._groundOf(s.anchor);
827
+ this.stickers.push(s);
828
+ this.invalidate();
829
+ return s;
830
+ }
831
+
832
+ remove(s) {
833
+ const i = this.stickers.indexOf(s);
834
+ if (i < 0) return;
835
+ if (this.active === s) this._release();
836
+ if (this.hover === s) this._setHover(null);
837
+ if (this.pending && this.pending.s === s) this._cancelPending();
838
+ this.stickers.splice(i, 1);
839
+ this._unref(s.shape);
840
+ this.invalidate();
841
+ }
842
+
843
+ /** Send every sticker (or one) back to where the layout put it. */
844
+ reset(sticker) {
845
+ const list = sticker ? [sticker] : this.stickers;
846
+ list.forEach((s, i) => {
847
+ if (this.active === s) this._release();
848
+ if (this.reduced) { s.ox = 0; s.oy = 0; s.rot = s.baseRot; s.state = 'idle'; return; }
849
+ s.state = 'fly';
850
+ s.fly = { ox: s.ox, oy: s.oy, r: s.rot, t: -i * 0.035, d: 0.5 };
851
+ });
852
+ this._save();
853
+ this.invalidate();
854
+ }
855
+
856
+ /** Tip every sticker back and pull its layers apart (shadow, vinyl, ink, laminate). */
857
+ setExploded(on) {
858
+ this.explodeTarget = on ? 1 : 0;
859
+ if (this.reduced) this.explode = this.explodeTarget;
860
+ this._release(); this._setHover(null);
861
+ this.invalidate();
862
+ }
863
+
864
+ /** Upload a caller-owned image or frame for the mirror material. No capture or playback here. */
865
+ setMirrorSource(source, { flipX = false } = {}) {
866
+ const gl = this.gl, mirror = this.mirror;
867
+ if (source === null) {
868
+ mirror.source = null;
869
+ if (mirror.width > 0 && this.ok && !gl.isContextLost()) {
870
+ gl.activeTexture(gl.TEXTURE2);
871
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
872
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, 1, 1, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
873
+ }
874
+ mirror.width = mirror.height = 0;
875
+ this.invalidate();
876
+ return true;
877
+ }
878
+
879
+ if (!this.ok || gl.isContextLost() || !mirror.texture) return false;
880
+ const width = source.videoWidth ?? source.naturalWidth ?? source.width;
881
+ const height = source.videoHeight ?? source.naturalHeight ?? source.height;
882
+ if (!width || !height || width > this._maxTextureSize || height > this._maxTextureSize
883
+ || source.complete === false || (source.videoWidth !== undefined && source.readyState < 2)) return false;
884
+
885
+ gl.activeTexture(gl.TEXTURE2);
886
+ gl.bindTexture(gl.TEXTURE_2D, mirror.texture);
887
+ gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, false);
888
+ try {
889
+ if (mirror.width === width && mirror.height === height) {
890
+ gl.texSubImage2D(gl.TEXTURE_2D, 0, 0, 0, gl.RGBA, gl.UNSIGNED_BYTE, source);
891
+ } else {
892
+ gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, source);
893
+ }
894
+ } catch (_) {
895
+ // E.g. a tainted canvas or video served without CORS.
896
+ return false;
897
+ }
898
+ Object.assign(mirror, { source, width, height, flipX });
899
+ this.invalidate();
900
+ return true;
901
+ }
902
+
903
+ toFront(s) {
904
+ const i = this.stickers.indexOf(s);
905
+ if (i >= 0 && i < this.stickers.length - 1) { this.stickers.splice(i, 1); this.stickers.push(s); }
906
+ }
907
+
908
+ invalidate() { this._redraw = true; this._wake(); }
909
+ // A frame that only draws if something on screen changed, see _tick.
910
+ _wake() { if (!this._raf && this.ok) this._raf = requestAnimationFrame(this._tick); }
911
+
912
+ hitTest(x, y, slop) {
913
+ for (let i = this.stickers.length - 1; i >= 0; i--) if (this.stickers[i].contains(x, y, slop)) return this.stickers[i];
914
+ return null;
915
+ }
916
+
917
+ // ------------------------------------------------------------ page geometry
918
+
919
+ // The canvas is a window a little taller than the viewport, positioned in the document so it
920
+ // scrolls with the page. Each frame it is moved to wherever the viewport is and redrawn.
921
+ // Brightness (0..1) of the first opaque background behind an element.
922
+ _groundOf(el) {
923
+ if (!this._probe) { const c = document.createElement('canvas'); c.width = c.height = 1; this._probe = c.getContext('2d', { willReadFrequently: true }); }
924
+ const g = this._probe;
925
+ for (let node = el || document.body; node && node.nodeType === 1; node = node.parentElement) {
926
+ const colour = getComputedStyle(node).backgroundColor;
927
+ if (!colour || colour === 'transparent') continue;
928
+ g.clearRect(0, 0, 1, 1); g.fillStyle = '#000'; g.fillStyle = colour; g.fillRect(0, 0, 1, 1);
929
+ const d = g.getImageData(0, 0, 1, 1).data;
930
+ if (d[3] > 127) return (0.299 * d[0] + 0.587 * d[1] + 0.114 * d[2]) / 255;
931
+ }
932
+ return getComputedStyle(document.documentElement).colorScheme.indexOf('dark') >= 0 && window.matchMedia('(prefers-color-scheme: dark)').matches ? 0.07 : 1;
933
+ }
934
+
935
+ _measure() {
936
+ for (const s of this.stickers) s.ground = this._groundOf(s.anchor);
937
+ const de = document.documentElement, cv = this.canvas;
938
+ cv.style.display = 'none'; // so the canvas itself does not hold the page open
939
+ this.docH = Math.max(de.scrollHeight, de.clientHeight); this.docW = de.clientWidth;
940
+ cv.style.display = 'block';
941
+ const r = cv.getBoundingClientRect();
942
+ this.origin.x = r.left + window.scrollX - this._tx; this.origin.y = r.top + window.scrollY - this._ty;
943
+ this.dpr = Math.min(this.opts.maxDpr, window.devicePixelRatio || 1);
944
+ // phone toolbars change innerHeight while scrolling; only ever grow until the width changes
945
+ if (window.innerWidth !== this._vw) { this._vw = window.innerWidth; this._vh = window.innerHeight; }
946
+ else this._vh = Math.max(this._vh, window.innerHeight);
947
+ }
948
+
949
+ _placeWindow(sy) {
950
+ const cv = this.canvas, win = this.win;
951
+ const h = Math.min(this._vh + 2 * this.opts.overscan, this.docH), w = this.docW;
952
+ const top = clamp(sy - this.opts.overscan, 0, Math.max(0, this.docH - h));
953
+ const pw = Math.round(w * this.dpr), ph = Math.round(h * this.dpr);
954
+ 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; }
955
+ const tx = -this.origin.x, ty = top - this.origin.y;
956
+ if (tx !== this._tx || ty !== this._ty) { cv.style.transform = `translate(${tx}px,${ty}px)`; this._tx = tx; this._ty = ty; this._redraw = true; }
957
+ win.top = top; win.w = w; win.h = h;
958
+ }
959
+
960
+ // ------------------------------------------------------------ input
961
+
962
+ _listen() {
963
+ const on = (target, type, fn, opt) => { target.addEventListener(type, fn, opt); this._off.push(() => target.removeEventListener(type, fn, opt)); };
964
+ const cap = { capture: true }, lazy = { capture: true, passive: true }, eager = { capture: true, passive: false };
965
+ on(window, 'pointerdown', (e) => this._down(e), cap);
966
+ on(window, 'pointermove', (e) => this._move(e), lazy);
967
+ on(window, 'pointerup', (e) => this._up(e), cap);
968
+ on(window, 'deviceorientation', (e) => this._tilt(e));
969
+ // iOS only reports orientation once asked, and it can only be asked from a tap
970
+ const orientation = window.DeviceOrientationEvent;
971
+ if (orientation && typeof orientation.requestPermission === 'function') {
972
+ const ask = (e) => {
973
+ if (e.pointerType !== 'touch' || !this.opts.gyroscope) return;
974
+ window.removeEventListener('pointerup', ask, true);
975
+ orientation.requestPermission().catch(() => {});
976
+ };
977
+ on(window, 'pointerup', ask, cap);
978
+ }
979
+ on(window, 'pointercancel', (e) => this._up(e, true), cap);
980
+ on(window, 'touchstart', (e) => { if (this.active || (!this.opts.touchHold && this._touchHit(e))) e.preventDefault(); }, eager);
981
+ on(window, 'touchmove', (e) => { if (this.active && e.cancelable) e.preventDefault(); }, eager);
982
+ on(window, 'contextmenu', (e) => { if (this.active || this.pending) e.preventDefault(); }, cap);
983
+ on(window, 'click', (e) => { if (this._eatClick) { this._eatClick = false; e.preventDefault(); e.stopPropagation(); } }, cap);
984
+ on(window, 'scroll', () => this.invalidate(), lazy);
985
+ on(window, 'resize', () => { this._dirty = true; this.invalidate(); });
986
+ on(window, 'blur', () => this._release());
987
+ // a theme switch changes the ground the marks sit on
988
+ const retheme = () => { this._dirty = true; this.invalidate(); };
989
+ const scheme = window.matchMedia('(prefers-color-scheme: dark)');
990
+ if (scheme.addEventListener) on(scheme, 'change', retheme);
991
+ if (window.MutationObserver) {
992
+ const watch = this._watch = new MutationObserver(retheme);
993
+ watch.observe(document.documentElement, { attributes: true, attributeFilter: ['class', 'style', 'data-theme'] });
994
+ this._off.push(() => watch.disconnect());
995
+ }
996
+ on(document.documentElement, 'pointerleave', () => { this.pointer.seen = false; if (!this.active) this._setHover(null); this.invalidate(); });
997
+ on(this.canvas, 'webglcontextlost', (e) => e.preventDefault());
998
+ on(this.canvas, 'webglcontextrestored', () => {
999
+ this._initGL();
1000
+ for (const [key, shape] of this._shapes) if (!shape.refs) this._shapes.delete(key);
1001
+ const rebuilt = new Set();
1002
+ for (const s of this.stickers) {
1003
+ if (rebuilt.has(s.shape)) continue;
1004
+ rebuilt.add(s.shape);
1005
+ s.shape.texArt = s.shape.texSdf = null; s._buildShape(s.shape); this._upload(s.shape);
1006
+ }
1007
+ });
1008
+ if (window.ResizeObserver) {
1009
+ this._ro = new ResizeObserver(() => { this._dirty = true; this.invalidate(); });
1010
+ this._ro.observe(document.documentElement); this._ro.observe(document.body);
1011
+ }
1012
+ }
1013
+
1014
+ _point(e) {
1015
+ const p = this.pointer;
1016
+ p.cx = e.clientX; p.cy = e.clientY; p.x = e.clientX + window.scrollX; p.y = e.clientY + window.scrollY;
1017
+ p.type = e.pointerType || 'mouse'; p.seen = true;
1018
+ }
1019
+ // How far the device has tilted from the way it is usually held, in screen axes. The resting
1020
+ // angle follows the device over a few seconds, so only turning it moves the highlights.
1021
+ _tilt(e) {
1022
+ if (!this.opts.gyroscope || e.beta == null || e.gamma == null) return;
1023
+ const a = ((screen.orientation && screen.orientation.angle) || 0) * Math.PI / 180, c = Math.cos(a), n = Math.sin(a);
1024
+ const x = e.gamma * c + e.beta * n, y = e.beta * c - e.gamma * n, T = this.tilt;
1025
+ if (!T.rest) { T.rest = { x, y, t: e.timeStamp }; return; }
1026
+ const k = 1 - Math.exp(-Math.max(0, e.timeStamp - T.rest.t) / 3000);
1027
+ T.rest.x += (x - T.rest.x) * k; T.rest.y += (y - T.rest.y) * k; T.rest.t = e.timeStamp;
1028
+ // 25 degrees of tilt slides the highlights about half a screen
1029
+ const px = this._vw * 0.31 / 25;
1030
+ T.x = clamp(x - T.rest.x, -40, 40) * px; T.y = clamp(y - T.rest.y, -40, 40) * px;
1031
+ this.invalidate();
1032
+ }
1033
+ _touchHit(e) { const t = e.changedTouches[0]; return !!t && !this.explodeTarget && !!this.hitTest(t.clientX + window.scrollX, t.clientY + window.scrollY, 7); }
1034
+ _selectable(on) {
1035
+ const st = document.documentElement.style;
1036
+ st.userSelect = on ? '' : 'none'; st.webkitUserSelect = on ? '' : 'none';
1037
+ // Not a theme change, so it needs no re-measure; pass on anything else that changed meanwhile.
1038
+ if (this._watch && this._watch.takeRecords().some(r => r.attributeName !== 'style')) { this._dirty = true; this.invalidate(); }
1039
+ }
1040
+
1041
+ _setHover(s) {
1042
+ if (s === this.hover) return;
1043
+ this.hover = s;
1044
+ this._cursor();
1045
+ if (this.onHover) this.onHover(s);
1046
+ }
1047
+ _cursor() {
1048
+ const on = !!(this.active || this.hover);
1049
+ this.catcher.style.pointerEvents = on ? 'auto' : 'none';
1050
+ this.catcher.style.cursor = this.active ? 'grabbing' : on ? 'grab' : '';
1051
+ }
1052
+
1053
+ _down(e) {
1054
+ if (this.explodeTarget || this.active || this.pending || e.button > 0 || e.isPrimary === false) return;
1055
+ this._point(e);
1056
+ const touch = e.pointerType === 'touch';
1057
+ const s = this.hitTest(this.pointer.x, this.pointer.y, touch ? 7 : 1);
1058
+ if (!s) return;
1059
+ if (touch && this.opts.touchHold > 0) {
1060
+ // A finger might be starting a scroll. Only grab if it rests on the sticker for a moment.
1061
+ this.pending = { s, id: e.pointerId, cx: e.clientX, cy: e.clientY, t: performance.now() };
1062
+ this._selectable(false);
1063
+ this._holdTimer = setTimeout(() => { const p = this.pending; if (p) { this.pending = null; this._grab(p.s, p.id); } }, this.opts.touchHold);
1064
+ return;
1065
+ }
1066
+ if (e.cancelable) e.preventDefault();
1067
+ this._grab(s, e.pointerId);
1068
+ }
1069
+
1070
+ _grab(s, pointerId) {
1071
+ const P = this.pointer;
1072
+ this.pointerId = pointerId;
1073
+ this.active = s;
1074
+ try { this.catcher.setPointerCapture(pointerId); } catch (_) {}
1075
+ s.floor = s.state === 'idle' ? s.tau : 0; s.floorNx = s.nx; s.floorNy = s.ny;
1076
+ s.state = 'peel'; s.fly = null; s.hint = null;
1077
+ s.p0x = P.x; s.p0y = P.y; s.pull = null;
1078
+ [s.gx, s.gy] = s.toLocal(P.x, P.y);
1079
+ if (P.type === 'touch' && !this.reduced) s.liftV += 90; // a small jump tells the finger it has it
1080
+ this.toFront(s);
1081
+ this._selectable(false);
1082
+ this._setHover(s); this._cursor();
1083
+ this.invalidate();
1084
+ }
1085
+
1086
+ _cancelPending() { clearTimeout(this._holdTimer); this.pending = null; this._selectable(true); }
1087
+
1088
+ _move(e) {
1089
+ const p = this.pending;
1090
+ if (p && e.pointerId === p.id && Math.hypot(e.clientX - p.cx, e.clientY - p.cy) > 9) this._cancelPending();
1091
+ if (this.active && e.pointerId !== this.pointerId) return;
1092
+ this._point(e);
1093
+ this._wake();
1094
+ }
1095
+
1096
+ _up(e, cancelled) {
1097
+ const p = this.pending;
1098
+ if (p && e.pointerId === p.id) {
1099
+ this._cancelPending();
1100
+ // a tap: lift a corner for a moment to show the sticker can be peeled
1101
+ 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(); }
1102
+ }
1103
+ if (this.active && e.pointerId === this.pointerId) { this._eatClick = true; setTimeout(() => { this._eatClick = false; }, 60); this._release(); }
1104
+ }
1105
+
1106
+ _release() {
1107
+ const s = this.active;
1108
+ if (!s) return;
1109
+ this.active = null;
1110
+ try { this.catcher.releasePointerCapture(this.pointerId); } catch (_) {}
1111
+ this.pointerId = null;
1112
+ const moved = s.state === 'held';
1113
+ if (moved) {
1114
+ // it stays where it was dropped, as an offset from its home in the layout
1115
+ s.x = clamp(s.x, 8, this.docW - 8); s.y = clamp(s.y, 8, this.docH - 8);
1116
+ s.ox = s.x - s.hx; s.oy = s.y - s.hy;
1117
+ }
1118
+ s.state = 'idle'; s.rotV = 0; s.floor = 0;
1119
+ this._selectable(true);
1120
+ if (this.pointer.type === 'touch') this._setHover(null);
1121
+ this._cursor();
1122
+ if (moved) { this._save(); if (this.onChange) this.onChange(s); }
1123
+ this.invalidate();
1124
+ }
1125
+
1126
+ _save() {
1127
+ if (!this.opts.persist) return;
1128
+ const out = {};
1129
+ 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; }
1130
+ this.saved = out;
1131
+ try { localStorage.setItem(this.opts.persist, JSON.stringify(out)); } catch (_) {}
1132
+ }
1133
+
1134
+ _detach(s) {
1135
+ const c = Math.cos(s.rot), n = Math.sin(s.rot), k = s.renderSize;
1136
+ s.state = 'held'; s.heldT = 0; s.rot0 = s.rot; s.rotV = 0;
1137
+ s.pvx = s.x + (c * s.gx - n * s.gy) * k; s.pvy = s.y + (n * s.gx + c * s.gy) * k;
1138
+ s.pvvx = 0; s.pvvy = 0;
1139
+ }
1140
+
1141
+ // ------------------------------------------------------------ simulation
1142
+
1143
+ // Follow the anchor element: its centre is home, its width sets the scale.
1144
+ _sync(s, sx, sy) {
1145
+ if (s.anchor) {
1146
+ const r = s.anchor.getBoundingClientRect();
1147
+ const { hx, hy, scale, hidden } = s;
1148
+ s.hidden = r.width === 0;
1149
+ 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; }
1150
+ if (s.hx !== hx || s.hy !== hy || s.scale !== scale || s.hidden !== hidden) this._redraw = true; // the layout moved it
1151
+ }
1152
+ if (s.state === 'idle' || s.state === 'peel') { s.x = s.hx + s.ox; s.y = s.hy + s.oy; }
1153
+ }
1154
+
1155
+ _step(s, dt) {
1156
+ const P = this.pointer;
1157
+ let tx = 0, ty = 0;
1158
+ if (s.age < 1) s.age = Math.min(1, s.age + dt / 0.16);
1159
+
1160
+ if (s.state === 'peel') {
1161
+ // The pointer has dragged the grabbed point by `delta`. Fold the sticker so the trailing
1162
+ // edge lifts; once the grabbed point itself is off the page it follows the pointer.
1163
+ const d = s.toLocalVec(P.x - s.p0x, P.y - s.p0y);
1164
+ let delta = Math.hypot(d[0], d[1]);
1165
+ // The first few pixels of a drag pick the way it peels. Pulling back the other way lays
1166
+ // the flap down again rather than peeling the opposite edge.
1167
+ if (!s.pull && delta > 4) s.pull = [-d[0] / delta, -d[1] / delta];
1168
+ if (s.pull) delta = Math.max(0, -(d[0] * s.pull[0] + d[1] * s.pull[1]));
1169
+ if (delta > 0.5) {
1170
+ const len = Math.hypot(d[0], d[1]), nx = -d[0] / len, ny = -d[1] / len;
1171
+ const far = s.support(nx, ny), near = s.support(-nx, -ny);
1172
+ const inset = Math.max(0, far - (s.gx * nx + s.gy * ny));
1173
+ let tau = s.tau;
1174
+ for (let i = 0; i < 5; i++) tau = inset + 0.5 * (delta + Math.PI * s.radius(tau));
1175
+ tau = Math.min(s.byTack(1.6, 1.15, 0.85) * delta, tau);
1176
+ tau = Math.max(tau, s.floor * Math.max(0, nx * s.floorNx + ny * s.floorNy));
1177
+ tx = nx * tau; ty = ny * tau;
1178
+ if (tau > s.byTack(0.48, this.opts.detachAt, 0.93) * (far + near)) this._detach(s);
1179
+ } else { tx = s.floorNx * s.floor; ty = s.floorNy * s.floor; }
1180
+ } else if (s.state === 'idle' && !this.explodeTarget && !this.reduced) {
1181
+ // an edge lifts towards a hovering mouse, or for a moment after a tap
1182
+ let at = null, amount = 0;
1183
+ if (s.hint) {
1184
+ s.hint.t += dt;
1185
+ 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)); }
1186
+ } else if (this.hover === s && !this.active && this.opts.hoverPeel && P.type !== 'touch') { at = s.toLocal(P.x, P.y); amount = 1; }
1187
+ if (at) {
1188
+ const [sd, gx, gy] = s.sample(at[0], at[1]);
1189
+ const e = s.hint ? 1 : smooth(Math.min(s.w, s.h) * 0.36, 0, -sd), len = Math.hypot(gx, gy);
1190
+ if (e > 0.01 && len > 1e-4) { tx = gx / len * e * amount * s.hoverLift; ty = gy / len * e * amount * s.hoverLift; }
1191
+ }
1192
+ }
1193
+
1194
+ if (s.state === 'peel') {
1195
+ const k = 1 - Math.exp(-dt * s.byTack(60, 42, 13)); // a clingy sticker gives way slowly
1196
+ s.fx += (tx - s.fx) * k; s.fy += (ty - s.fy) * k; s.fvx = 0; s.fvy = 0;
1197
+ } else {
1198
+ const w = s.state === 'held' ? 17 : s.byTack(11, 15, 24), z = 0.86;
1199
+ for (let i = 0; i < 2; i++) {
1200
+ const h = dt / 2;
1201
+ 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;
1202
+ s.fx += s.fvx * h; s.fy += s.fvy * h;
1203
+ }
1204
+ }
1205
+ const tau = s.tau;
1206
+ if (tau > 0.02) { s.nx = s.fx / tau; s.ny = s.fy / tau; }
1207
+
1208
+ let liftTarget = s.state === 'held' ? this.opts.liftHeight : 0;
1209
+ if (s.state === 'fly') {
1210
+ const f = s.fly;
1211
+ f.t += dt;
1212
+ const t = clamp(f.t / f.d, 0, 1), e = 1 - t * t * (3 - 2 * t);
1213
+ s.ox = f.ox * e; s.oy = f.oy * e; s.rot = s.baseRot + (f.r - s.baseRot) * e;
1214
+ s.x = s.hx + s.ox; s.y = s.hy + s.oy;
1215
+ liftTarget = f.t > 0 && t < 0.8 ? this.opts.liftHeight : 0;
1216
+ if (t >= 1) { s.state = 'idle'; s.fly = null; }
1217
+ }
1218
+ {
1219
+ const w = liftTarget > 0 ? 17 : 25, z = liftTarget > 0 ? 0.8 : 0.5;
1220
+ for (let i = 0; i < 2; i++) {
1221
+ const h = dt / 2;
1222
+ s.liftV += (w * w * (liftTarget - s.lift) - 2 * z * w * s.liftV) * h;
1223
+ s.lift += s.liftV * h;
1224
+ }
1225
+ }
1226
+
1227
+ if (s.state === 'held') {
1228
+ // the grabbed point is pulled to the pointer; the rest swings behind it
1229
+ s.heldT += dt;
1230
+ const w = 20 + 30 * clamp(s.heldT / 0.35, 0, 1), z = 0.82;
1231
+ const px = clamp(P.cx, 6, this._vw - 6) + window.scrollX, py = clamp(P.cy, 6, window.innerHeight - 6) + window.scrollY;
1232
+ const k = s.size;
1233
+ for (let i = 0; i < 2; i++) {
1234
+ const h = dt / 2;
1235
+ 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;
1236
+ s.pvx += s.pvvx * h; s.pvy += s.pvvy * h;
1237
+ const c = Math.cos(s.rot), n = Math.sin(s.rot);
1238
+ const rx = -(c * s.gx - n * s.gy), ry = -(n * s.gx + c * s.gy);
1239
+ const torque = (ry * s.pvvx - rx * s.pvvy) / k;
1240
+ s.rotV += (torque * 4.2e-4 - 2 * 0.5 * 12 * s.rotV - 144 * (s.rot - s.rot0)) * h;
1241
+ s.rot = clamp(s.rot + s.rotV * h, s.rot0 - 0.4, s.rot0 + 0.4);
1242
+ }
1243
+ const c = Math.cos(s.rot), n = Math.sin(s.rot), kr = s.renderSize;
1244
+ s.x = s.pvx - (c * s.gx - n * s.gy) * kr; s.y = s.pvy - (n * s.gx + c * s.gy) * kr;
1245
+ }
1246
+
1247
+ const settling = Math.abs(tx - s.fx) + Math.abs(ty - s.fy) > 0.03 || Math.abs(s.fvx) + Math.abs(s.fvy) > 0.5
1248
+ || Math.abs(liftTarget - s.lift) > 0.02 || Math.abs(s.liftV) > 0.3 || s.age < 1 || !!s.hint;
1249
+ if (!settling && s.state === 'idle') { s.fx = tx; s.fy = ty; s.fvx = s.fvy = 0; s.lift = liftTarget; s.liftV = 0; }
1250
+ return settling || s.state === 'held' || s.state === 'fly';
1251
+ }
1252
+
1253
+ _tick(now) {
1254
+ this._raf = 0;
1255
+ if (!this.ok) return;
1256
+ for (const [key, shape] of this._shapes) if (!shape.refs) { this._shapes.delete(key); this._free(shape); }
1257
+ let dt = (now - (this._last || now)) / 1000;
1258
+ this._last = now;
1259
+ if (!(dt > 0) || dt > 0.1) dt = 1 / 60;
1260
+ dt = Math.min(dt, 1 / 30);
1261
+ let busy = false;
1262
+
1263
+ if (this._dirty) { this._dirty = false; this._measure(); }
1264
+ const sx = window.scrollX, sy = window.scrollY, P = this.pointer;
1265
+ P.x = P.cx + sx; P.y = P.cy + sy;
1266
+ for (const s of this.stickers) this._sync(s, sx, sy);
1267
+ const hover = this.hover;
1268
+ if (!this.active && !this.explodeTarget && P.type !== 'touch') this._setHover(P.seen ? this.hitTest(P.x, P.y, 1) : null);
1269
+
1270
+ // highlights slide a little as the device tilts, as if the viewer moved their head
1271
+ // read the option every frame so turning it off settles the highlights back
1272
+ if (!this.opts.gyroscope) { this.tilt.x = this.tilt.y = 0; this.tilt.rest = null; }
1273
+ const ex = this.tilt.x, ey = this.tilt.y;
1274
+ const k = this.reduced ? 1 : 1 - Math.exp(-dt * 9);
1275
+ this.env.x += (ex - this.env.x) * k; this.env.y += (ey - this.env.y) * k;
1276
+ if (Math.abs(ex - this.env.x) + Math.abs(ey - this.env.y) > 0.4) busy = true;
1277
+
1278
+ if (this.explode !== this.explodeTarget) {
1279
+ this.explode += (this.explodeTarget - this.explode) * (1 - Math.exp(-dt * 9));
1280
+ if (Math.abs(this.explode - this.explodeTarget) < 0.002) this.explode = this.explodeTarget; else busy = true;
1281
+ }
1282
+ for (const s of this.stickers) if (this._step(s, dt)) busy = true;
1283
+ this._placeWindow(sy);
1284
+ // A pointer moving over bare page changes nothing on screen, unless a reflective sticker in view
1285
+ // follows it. Every other reason for a frame comes through invalidate().
1286
+ if (this._redraw || busy || this.active || this.hover || this.hover !== hover || this._lit) {
1287
+ this._redraw = false;
1288
+ this._render(sx, sy);
1289
+ }
1290
+ if (busy) this.invalidate();
1291
+ }
1292
+
1293
+ // ------------------------------------------------------------ drawing
1294
+
1295
+ _render(sx, sy) {
1296
+ const gl = this.gl, win = this.win, e = this.explode;
1297
+ gl.viewport(0, 0, this.canvas.width, this.canvas.height);
1298
+ gl.clear(gl.COLOR_BUFFER_BIT);
1299
+ gl.uniform2f(this.u.uView, win.w, win.h);
1300
+ gl.uniform2f(this.u.uOff, -sx, win.top - sy); // canvas px -> viewport px, where the lights are fixed
1301
+ gl.uniform2f(this.u.uEnv, this.env.x, this.env.y);
1302
+ gl.uniform3f(this.u.uPtr, this.pointer.cx, this.pointer.cy, this.pointer.seen ? 1 : 0);
1303
+ gl.uniform1f(this.u.uShadow, this.opts.shadow);
1304
+ // marks first, so every sticker sits on top of them
1305
+ if (this.opts.residue > 0) for (const s of this.stickers) {
1306
+ if (s.hidden) continue;
1307
+ 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;
1308
+ if ((home && s.age >= 1) || s.tack < 0.02) continue; // hidden under its own sticker, or a low-tack one that leaves nothing
1309
+ const reach = (s.shape.reach + 4) * s.scale;
1310
+ if (s.hy + reach < win.top || s.hy - reach > win.top + win.h) continue;
1311
+ this._drawMark(s);
1312
+ }
1313
+ gl.uniform1f(this.u.uMark, 0);
1314
+ this._lit = false;
1315
+ for (const s of this.stickers) {
1316
+ if (s.hidden) continue;
1317
+ const reach = (s.shape.reach + 60 + 2.5 * s.tau) * s.scale + 80 * e;
1318
+ if (s.y + reach < win.top || s.y - reach > win.top + win.h) continue;
1319
+ if (s.finish.kind === 8) this._lit = true; // lit by the pointer
1320
+ if (e < 0.002) { this._draw(s, 0, 0, 0, null); continue; }
1321
+ const gap = 40 * s.size * e;
1322
+ this._draw(s, e, 1.5 * gap, 6 * e, [1, 0, 0, 0]);
1323
+ this._draw(s, e, 0.5 * gap, 2 * e, [0.5 * e + (1 - e), 1, 1 - e, 1 - e]);
1324
+ this._draw(s, e, -0.5 * gap, 2 * e, [0.4 * e, 0, e, 0]);
1325
+ this._draw(s, e, -1.5 * gap, 2 * e, [0.3 * e, 0, 0, e]);
1326
+ }
1327
+ }
1328
+
1329
+ _drawMark(s) {
1330
+ const gl = this.gl, u = this.u;
1331
+ const k = s.scale, c = Math.cos(s.baseRot), n = Math.sin(s.baseRot);
1332
+ gl.uniformMatrix3fv(u.uM, false, [c * k, n * k, 0, -n * k, c * k, 0, s.hx, s.hy - this.win.top, 1]);
1333
+ gl.uniform4f(u.uRect, -s.W / 2, -s.H / 2, s.W / 2, s.H / 2);
1334
+ gl.uniform2f(u.uSize, s.W, s.H);
1335
+ const L = this.opts.light;
1336
+ gl.uniform3f(u.uL, c * L[0] + n * L[1], -n * L[0] + c * L[1], L[2]);
1337
+ gl.uniform2f(u.uRot, c, n);
1338
+ gl.uniform1f(u.uAlpha, s.age);
1339
+ gl.uniform1f(u.uPx, 1 / (this.dpr * k));
1340
+ gl.uniform1f(u.uSeed, s.seed);
1341
+ gl.uniform1f(u.uMark, this.opts.residue * s.byTack(0, 1, 1.9));
1342
+ gl.uniform1f(u.uGround, s.ground);
1343
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, s.shape.texArt);
1344
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, s.shape.texSdf);
1345
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
1346
+ }
1347
+
1348
+ _draw(s, e, dy, extraLift, layers) {
1349
+ const gl = this.gl, u = this.u;
1350
+ const k = s.renderSize, c = Math.cos(s.rot), n = Math.sin(s.rot);
1351
+ // local -> canvas. In exploded view the page plane is seen from an angle (an affine squash).
1352
+ const yaw = -0.5 * e, cy = Math.cos(yaw), sy = Math.sin(yaw), squash = 1 - 0.46 * e;
1353
+ const a = c * k, b = n * k, cc = -n * k, d = c * k;
1354
+ 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]);
1355
+
1356
+ const tau = e > 0.002 ? 0 : s.tau;
1357
+ const R = s.radius(tau);
1358
+ const lift = s.lift + extraLift;
1359
+ // Room around the texture for what spills out of it. Lying flat, the shadow stays inside the
1360
+ // texture's 10px padding; a peeled flap's shadow and a glowing sticker's light reach far beyond.
1361
+ const wide = tau > 0.3 || s.finish.kind === 10;
1362
+ 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);
1363
+ gl.uniform4f(u.uRect, -s.W / 2 - margin, -s.H / 2 - margin, s.W / 2 + margin, s.H / 2 + margin);
1364
+ gl.uniform2f(u.uSize, s.W, s.H);
1365
+ if (tau > 0.02) gl.uniform3f(u.uFold, s.nx, s.ny, s.support(s.nx, s.ny) - tau);
1366
+ else gl.uniform3f(u.uFold, 1, 0, 1e5);
1367
+ gl.uniform1f(u.uR, R);
1368
+ gl.uniform1f(u.uLift, lift);
1369
+ const L = this.opts.light, S = this.opts.shadowSlope;
1370
+ gl.uniform3f(u.uL, c * L[0] + n * L[1], -n * L[0] + c * L[1], L[2]);
1371
+ gl.uniform2f(u.uSh, c * S[0] + n * S[1], -n * S[0] + c * S[1]);
1372
+ gl.uniform2f(u.uRot, c, n);
1373
+ gl.uniform4f(u.uFin, s.finish.gloss, s.finish.kind, s.finish.grain, s.showThrough);
1374
+ if (s.finish.kind === 4) {
1375
+ const { width, height, flipX } = this.mirror;
1376
+ if (width) {
1377
+ const w = s.w + 2 * s.border, h = s.h + 2 * s.border;
1378
+ const ca = Math.abs(c), sa = Math.abs(n);
1379
+ const cover = Math.max((ca * w + sa * h) / width, (sa * w + ca * h) / height);
1380
+ gl.uniform3f(u.uMirrorMap, 1 / (width * cover), 1 / (height * cover), flipX ? -1 : 1);
1381
+ } else {
1382
+ gl.uniform3f(u.uMirrorMap, 0, 0, 0);
1383
+ }
1384
+ }
1385
+ gl.uniform1f(u.uGlow, 1 - smooth(0.15, 0.5, s.ground));
1386
+ gl.uniform1f(u.uTrim, s.shape.trim ? 1 : 0);
1387
+ gl.uniform3fv(u.uPaper, s.paper);
1388
+ gl.uniform3fv(u.uBack, s.back);
1389
+ gl.uniform1f(u.uAlpha, s.age);
1390
+ gl.uniform4fv(u.uLay, layers || [1, 1, 1, 1]);
1391
+ gl.uniform1f(u.uPx, 1 / (this.dpr * k * (1 - 0.3 * e)));
1392
+ gl.uniform1f(u.uSeed, s.seed);
1393
+ gl.activeTexture(gl.TEXTURE0); gl.bindTexture(gl.TEXTURE_2D, s.shape.texArt);
1394
+ gl.activeTexture(gl.TEXTURE1); gl.bindTexture(gl.TEXTURE_2D, s.shape.texSdf);
1395
+ gl.drawArrays(gl.TRIANGLE_STRIP, 0, 4);
1396
+ }
1397
+ }