neon-activity-graph 0.0.0-stage → 0.1.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,2906 @@
1
+ import {
2
+ CAMERA_DIR,
3
+ clampTone,
4
+ glassShades,
5
+ layoutGraph,
6
+ lightBehind,
7
+ mountPlaceholder,
8
+ predictBounds,
9
+ roomFor,
10
+ sameColor,
11
+ shiftsFromLayers,
12
+ slabFor,
13
+ tallestOfLayers
14
+ } from "./chunk-ZQXBO776.js";
15
+
16
+ // src/ground-light.ts
17
+ var COMMON = (
18
+ /* glsl */
19
+ `
20
+ const float IOR = 1.5;
21
+ const float R0 = 0.04;
22
+ float reflectance(float c) { c = clamp(c, 0., 1.); return R0 + (1. - R0) * pow(1. - c, 5.); }
23
+ float sdf(vec3 p, vec3 h, float r) {
24
+ vec3 q = abs(p) - (h - r);
25
+ return length(max(q, 0.)) + min(max(q.x, max(q.y, q.z)), 0.) - r;
26
+ }
27
+ // where a ray enters and leaves the sharp box (x, y), y < x for a miss
28
+ vec2 slab(vec3 o, vec3 d, vec3 h) {
29
+ float t0 = -1e9; float t1 = 1e9;
30
+ for (int i = 0; i < 3; i++) {
31
+ float di = d[i]; float oi = o[i]; float hi = h[i];
32
+ if (abs(di) < 1e-9) { if (abs(oi) > hi) return vec2(1., -1.); continue; }
33
+ float a = (-hi - oi) / di; float b = (hi - oi) / di;
34
+ t0 = max(t0, min(a, b)); t1 = min(t1, max(a, b));
35
+ }
36
+ return vec2(t0, t1);
37
+ }
38
+ vec3 roundedNormal(vec3 p, vec3 h, float r, vec3 bias) {
39
+ vec3 q = abs(p) - (h - r);
40
+ vec3 s = vec3(p.x >= 0. ? 1. : -1., p.y >= 0. ? 1. : -1., p.z >= 0. ? 1. : -1.);
41
+ float m = max(q.x, max(q.y, q.z));
42
+ vec3 n;
43
+ if (m <= 0.) {
44
+ n = q.x >= q.y && q.x >= q.z ? vec3(s.x, 0., 0.) : q.y >= q.z ? vec3(0., s.y, 0.) : vec3(0., 0., s.z);
45
+ } else {
46
+ n = normalize(max(q, 0.) * s);
47
+ }
48
+ return normalize(n + bias);
49
+ }
50
+ // from inside the glass, at p going along d: bounce until it gets out; where it lands on the ground (world y = 0), the share of its power that got out, the length it went through glass
51
+ bool leaveGlass(vec3 p, vec3 dir, vec3 c, vec3 h, float r, vec3 bias, out vec3 land, out float share, out float path) {
52
+ vec3 o = p; vec3 d = dir; share = 1.; path = 0.; land = vec3(0.);
53
+ for (int b = 0; b < 12; b++) {
54
+ vec2 s = slab(o, d, h);
55
+ if (s.y < s.x) return false;
56
+ float lo = 0.; float hi = s.y + 0.01;
57
+ for (int k = 0; k < 14; k++) { float mid = .5 * (lo + hi); if (sdf(o + d * mid, h, r) < 0.) lo = mid; else hi = mid; }
58
+ float t = .5 * (lo + hi);
59
+ path += t;
60
+ vec3 q = o + d * t;
61
+ vec3 n = roundedNormal(q, h, r, bias);
62
+ vec3 outd = refract(d, -n, IOR);
63
+ if (dot(outd, outd) > 1e-8) {
64
+ share *= 1. - reflectance(dot(outd, n));
65
+ if (outd.y >= -1e-3) return false;
66
+ float g = -(q.y + c.y) / outd.y;
67
+ land = vec3(q.x + c.x + outd.x * g, 0., q.z + c.z + outd.z * g);
68
+ return true;
69
+ }
70
+ d = reflect(d, n);
71
+ o = q + d * 1e-4;
72
+ }
73
+ return false;
74
+ }
75
+ float reachFade(float dist, float near, float far) {
76
+ if (dist <= near) return 1.;
77
+ if (dist >= far) return 0.;
78
+ float u = 1. - (dist - near) / (far - near);
79
+ return u * u * (3. - 2. * u);
80
+ }
81
+ `
82
+ );
83
+ var ATTRIBUTES = (
84
+ /* glsl */
85
+ `
86
+ attribute float ray;
87
+ attribute vec3 iC; attribute vec3 iH; attribute vec3 iBias; attribute vec3 iCol;
88
+ attribute vec4 iA; // r, power, near, far
89
+ attribute vec4 iB; // rod, seed0, seed1, seed2
90
+ attribute vec2 iD; // seed3, seed4
91
+ uniform vec4 uGrid; // pixels per unit, x0, z0, (unused)
92
+ uniform vec2 uSize; // target size in pixels
93
+ varying vec3 vColor;
94
+ vec4 toClip(vec3 land) {
95
+ float gx = (land.x - uGrid.y) * uGrid.x;
96
+ float gz = (land.z - uGrid.z) * uGrid.x;
97
+ return vec4(gx / uSize.x * 2. - 1., 1. - gz / uSize.y * 2., 0., 1.);
98
+ }
99
+ void discardPoint() { gl_Position = vec4(2., 2., 2., 1.); gl_PointSize = 0.; vColor = vec3(0.); }
100
+ `
101
+ );
102
+ var SUN_VERT = (
103
+ /* glsl */
104
+ `
105
+ ${COMMON}
106
+ ${ATTRIBUTES}
107
+ uniform vec3 uDir; // the way the light travels
108
+ uniform float uN; // rays per side
109
+ uniform float uFree; // 0: where the glass lands the ray (adds), 1: where it would have landed (takes away)
110
+ uniform float uAbsorb;
111
+ uniform float uStraight;
112
+ uniform float uPerArea; // pixel area / cos
113
+ float hash(float n) { return fract(sin(n * 12.9898 + 78.233) * 43758.5453); }
114
+ void main() {
115
+ float i = ray;
116
+ float r = iA.x; float power = iA.y; float near = iA.z; float far = iA.w;
117
+ vec3 h = iH;
118
+ float R = length(h);
119
+ float gi = mod(i, uN); float gj = floor(i / uN);
120
+ float cell = 2. * R / uN;
121
+ float a = -R + (gi + hash(i + iB.y)) * cell;
122
+ float b = -R + (gj + hash(i * 1.37 + iB.z)) * cell;
123
+ vec3 d = uDir;
124
+ vec3 u = normalize(cross(d, vec3(0., 1., 0.)));
125
+ vec3 v = cross(d, u);
126
+ vec3 o = u * a + v * b - d * 2. * R;
127
+ vec2 s = slab(o, d, h);
128
+ if (s.y < s.x) { discardPoint(); return; }
129
+ float area = cell * cell * uPerArea;
130
+ if (uFree > .5) {
131
+ float fy = -(o.y + iC.y) / d.y;
132
+ vec3 free = vec3(o.x + iC.x + d.x * fy, 0., o.z + iC.z + d.z * fy);
133
+ vec3 tint = vec3(1.) - uStraight * exp(-uAbsorb * (vec3(1.) - iCol));
134
+ vColor = -area * tint;
135
+ gl_Position = toClip(free);
136
+ gl_PointSize = 1.;
137
+ return;
138
+ }
139
+ // sphere tracing from where it enters the sharp box, to the rounded one
140
+ float te = max(0., s.x - 1e-3);
141
+ bool hit = false;
142
+ for (int k = 0; k < 48; k++) {
143
+ float sd = sdf(o + d * te, h, r);
144
+ if (sd < 1e-4) { hit = true; break; }
145
+ te += sd;
146
+ if (te > s.y + 1e-3) break;
147
+ }
148
+ if (!hit) { discardPoint(); return; }
149
+ vec3 q = o + d * te;
150
+ vec3 nrm = roundedNormal(q, h, r, iBias);
151
+ vec3 inside = refract(d, nrm, 1. / IOR);
152
+ if (dot(inside, inside) < 1e-8) { discardPoint(); return; }
153
+ float entered = 1. - reflectance(-dot(d, nrm));
154
+ vec3 land; float share; float path;
155
+ if (!leaveGlass(q + inside * 1e-4, inside, iC, h, r, iBias, land, share, path)) { discardPoint(); return; }
156
+ float fade = reachFade(length(land.xz - iC.xz), near, far);
157
+ if (fade <= 0.) { discardPoint(); return; }
158
+ vColor = area * entered * share * fade * exp(-uAbsorb * (vec3(1.) - iCol) * path);
159
+ gl_Position = toClip(land);
160
+ gl_PointSize = 1.;
161
+ }
162
+ `
163
+ );
164
+ var POINT_FRAG = (
165
+ /* glsl */
166
+ `varying vec3 vColor; void main() { gl_FragColor = vec4(vColor, 1.); }`
167
+ );
168
+ var FULL_VERT = (
169
+ /* glsl */
170
+ `varying vec2 vUv; void main() { vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }`
171
+ );
172
+ var TEMPLATE_HEIGHTS = [0.5, 1.3, 2.4];
173
+ var TEMPLATE_FEET = [0, 0.9, 1.8, 2.7];
174
+ var TEMPLATE_EXTENT = 8;
175
+ var STAMP_CONTRAST = 2.4;
176
+ var STAMP_FOOT = 0.04;
177
+ var TEMPLATE_SIZE = 128;
178
+ var LOG_FLOOR = 1e-4;
179
+ var LOG_RANGE = 10;
180
+ async function loadCausticTemplates(THREE, url) {
181
+ const img = new Image();
182
+ img.src = url;
183
+ await img.decode();
184
+ const canvas = document.createElement("canvas");
185
+ canvas.width = img.width;
186
+ canvas.height = img.height;
187
+ const ctx2 = canvas.getContext("2d", { willReadFrequently: true });
188
+ ctx2.drawImage(img, 0, 0);
189
+ const px = ctx2.getImageData(0, 0, img.width, img.height).data;
190
+ const half = new Uint16Array(img.width * img.height * 4);
191
+ const one = THREE.DataUtils.toHalfFloat(1);
192
+ for (let i = 0; i < img.width * img.height; i++) {
193
+ const v = (Math.exp(px[i * 4] / 255 * LOG_RANGE) - 1) * LOG_FLOOR;
194
+ half[i * 4] = half[i * 4 + 1] = half[i * 4 + 2] = THREE.DataUtils.toHalfFloat(v);
195
+ half[i * 4 + 3] = one;
196
+ }
197
+ const texture = new THREE.DataTexture(half, img.width, img.height, THREE.RGBAFormat, THREE.HalfFloatType);
198
+ texture.minFilter = THREE.LinearFilter;
199
+ texture.magFilter = THREE.LinearFilter;
200
+ texture.needsUpdate = true;
201
+ return { texture, heights: TEMPLATE_HEIGHTS, feet: TEMPLATE_FEET, extent: TEMPLATE_EXTENT };
202
+ }
203
+ var STAMP_VERT = (
204
+ /* glsl */
205
+ `
206
+ attribute vec2 iPos; attribute vec3 iCol; attribute vec4 iIdx; attribute vec3 iPoolCol; attribute float iPoolR;
207
+ uniform vec4 uGrid; uniform vec2 uSize; uniform float uExtent;
208
+ varying vec3 vCol; varying vec2 vLocal; varying vec4 vIdx; varying vec3 vPoolCol; varying float vPoolR;
209
+ void main() {
210
+ vPoolCol = iPoolCol; vPoolR = iPoolR;
211
+ vLocal = position.xy * 2. * uExtent;
212
+ vCol = iCol; vIdx = iIdx;
213
+ vec2 world = iPos + vLocal;
214
+ float gx = (world.x - uGrid.y) * uGrid.x;
215
+ float gz = (world.y - uGrid.z) * uGrid.x;
216
+ gl_Position = vec4(gx / uSize.x * 2. - 1., 1. - gz / uSize.y * 2., 0., 1.);
217
+ }
218
+ `
219
+ );
220
+ var STAMP_FRAG = (
221
+ /* glsl */
222
+ `
223
+ uniform sampler2D atlas; uniform float uContrast; uniform float uFoot; uniform float uExtent; uniform vec2 uCells; uniform float uQuarter;
224
+ varying vec3 vCol; varying vec2 vLocal; varying vec4 vIdx; varying vec3 vPoolCol; varying float vPoolR;
225
+ float tap(float h, float f, vec2 u) {
226
+ // the template of height class h, foot class f: the cell of the atlas, sampled inside it (never across its edge)
227
+ vec2 inside = (clamp(u, 0., 1.) * (uQuarter - 1.) + .5) / uQuarter;
228
+ return texture2D(atlas, (vec2(f, h) + inside) / uCells).r;
229
+ }
230
+ void main() {
231
+ // the soft pool: a round spot of haze under the block, a third of its peak at 0.45 of its radius and out to nothing at the radius
232
+ float pu = length(vLocal) / vPoolR;
233
+ float pool = pu >= 1. ? 0. : (pu < .45 ? 1. - (pu / .45) * .65 : .35 * (1. - (pu - .45) / .55));
234
+ vec2 u = abs(vLocal) / uExtent;
235
+ float edge = length(u);
236
+ if (edge >= 1.) discard;
237
+ float h0 = vIdx.x; float fH = vIdx.y; float f0 = vIdx.z; float fF = vIdx.w;
238
+ float h1 = min(h0 + 1., uCells.y - 1.); float f1 = min(f0 + 1., uCells.x - 1.);
239
+ float v = mix(mix(tap(h0, f0, u), tap(h0, f1, u), fF), mix(tap(h1, f0, u), tap(h1, f1, u), fF), fH);
240
+ // (a curve that keeps the bright structure and lowers the faint wide glow under it, so that the streaks are not drowned: where the template is a tenth of its peak, it is far less than a tenth)
241
+ v = pow(max(v, 0.), uContrast);
242
+ // (the template ends at its edge: let it fade out just before, not stop)
243
+ v *= 1. - smoothstep(.5, 1., edge);
244
+ // (the bright foot of a block is for a block on open ground: in the picture its neighbours stand in the way, and the ground between blocks is not lit like that; it is lowered near the block, and the light that goes further out is kept)
245
+ v *= mix(uFoot, 1., smoothstep(1., 3., length(vLocal)));
246
+ gl_FragColor = vec4(vCol * v + vPoolCol * pool * 0.04, 1.);
247
+ }
248
+ `
249
+ );
250
+ function createGroundLight(THREE, renderer, grid) {
251
+ const type = renderer.extensions.has("EXT_float_blend") && renderer.extensions.has("EXT_color_buffer_float") ? THREE.FloatType : THREE.HalfFloatType;
252
+ const make = () => new THREE.WebGLRenderTarget(grid.w, grid.h, { type, depthBuffer: false, minFilter: THREE.LinearFilter, magFilter: THREE.LinearFilter });
253
+ let target = make();
254
+ let spare = make();
255
+ const cam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
256
+ const points = new THREE.Scene();
257
+ const full = new THREE.Scene();
258
+ const quad = new THREE.Mesh(new THREE.PlaneGeometry(2, 2));
259
+ full.add(quad);
260
+ const blurMat = new THREE.ShaderMaterial({
261
+ uniforms: { map: { value: null }, stepv: { value: new THREE.Vector2() } },
262
+ vertexShader: FULL_VERT,
263
+ fragmentShader: `uniform sampler2D map; uniform vec2 stepv; varying vec2 vUv;
264
+ void main() { gl_FragColor = (texture2D(map, vUv - 2. * stepv) + 4. * texture2D(map, vUv - stepv) + 6. * texture2D(map, vUv) + 4. * texture2D(map, vUv + stepv) + texture2D(map, vUv + 2. * stepv)) / 16.; }`,
265
+ depthTest: false,
266
+ depthWrite: false
267
+ });
268
+ const disposables = [blurMat, quad.geometry];
269
+ const draw = (blocks, rays, vertex, uniforms, keep) => {
270
+ const geo = new THREE.InstancedBufferGeometry();
271
+ geo.instanceCount = blocks.length;
272
+ const ray = new Float32Array(rays);
273
+ for (let i = 0; i < rays; i++) ray[i] = i;
274
+ geo.setAttribute("ray", new THREE.BufferAttribute(ray, 1));
275
+ geo.setAttribute("position", new THREE.BufferAttribute(new Float32Array(rays * 3), 3));
276
+ const inst = (size, fill) => {
277
+ const a = new Float32Array(blocks.length * size);
278
+ blocks.forEach((b, i) => a.set(fill(b), i * size));
279
+ return new THREE.InstancedBufferAttribute(a, size);
280
+ };
281
+ geo.setAttribute("iC", inst(3, (b) => b.c));
282
+ geo.setAttribute("iH", inst(3, (b) => b.h));
283
+ geo.setAttribute("iBias", inst(3, (b) => b.bias));
284
+ geo.setAttribute("iCol", inst(3, (b) => b.col));
285
+ geo.setAttribute("iA", inst(4, (b) => [b.r, b.power, b.near, b.far]));
286
+ geo.setAttribute("iB", inst(4, (b) => [b.rod, b.seed[0], b.seed[1], b.seed[2]]));
287
+ geo.setAttribute("iD", inst(2, (b) => [b.seed[3], b.seed[4]]));
288
+ const mat = new THREE.ShaderMaterial({
289
+ vertexShader: vertex,
290
+ fragmentShader: POINT_FRAG,
291
+ uniforms: { uGrid: { value: new THREE.Vector4(grid.scale, grid.x0, grid.z0, 0) }, uSize: { value: new THREE.Vector2(grid.w, grid.h) }, ...uniforms },
292
+ blending: THREE.CustomBlending,
293
+ blendEquation: THREE.AddEquation,
294
+ blendSrc: THREE.OneFactor,
295
+ blendDst: THREE.OneFactor,
296
+ depthTest: false,
297
+ depthWrite: false,
298
+ transparent: true
299
+ });
300
+ const mesh = new THREE.Points(geo, mat);
301
+ mesh.frustumCulled = false;
302
+ points.add(mesh);
303
+ const prevTarget = renderer.getRenderTarget();
304
+ const prevAuto = renderer.autoClear;
305
+ renderer.setRenderTarget(target);
306
+ renderer.autoClear = !keep;
307
+ renderer.render(points, cam);
308
+ renderer.autoClear = prevAuto;
309
+ renderer.setRenderTarget(prevTarget);
310
+ points.remove(mesh);
311
+ geo.dispose();
312
+ mat.dispose();
313
+ };
314
+ const sun = (blocks, n, dir, absorb, straight, pixelPerArea) => {
315
+ const common = { uDir: { value: new THREE.Vector3(...dir) }, uN: { value: n }, uAbsorb: { value: absorb }, uStraight: { value: straight }, uPerArea: { value: pixelPerArea } };
316
+ draw(blocks, n * n, SUN_VERT, { ...common, uFree: { value: 0 } }, false);
317
+ draw(blocks, n * n, SUN_VERT, { ...common, uFree: { value: 1 } }, true);
318
+ };
319
+ const stamps = (blocks, templates) => {
320
+ const geo = new THREE.InstancedBufferGeometry();
321
+ const plane = new THREE.PlaneGeometry(1, 1);
322
+ geo.setAttribute("position", plane.getAttribute("position"));
323
+ geo.setIndex(plane.getIndex());
324
+ geo.instanceCount = blocks.length;
325
+ const pos = new Float32Array(blocks.length * 2);
326
+ const base = new Float32Array(blocks.length * 3);
327
+ const idx = new Float32Array(blocks.length * 4);
328
+ const poolBase = new Float32Array(blocks.length * 3);
329
+ const poolR = new Float32Array(blocks.length);
330
+ const place = (v, classes) => {
331
+ if (v <= classes[0]) return [0, 0];
332
+ for (let i = 1; i < classes.length; i++) if (v <= classes[i]) return [i - 1, (v - classes[i - 1]) / (classes[i] - classes[i - 1])];
333
+ return [classes.length - 1, 0];
334
+ };
335
+ blocks.forEach((b, i) => {
336
+ pos.set([b.x, b.z], i * 2);
337
+ base.set(b.col, i * 3);
338
+ const [h0, fh] = place(b.height, templates.heights);
339
+ const [f0, ff] = place(b.foot, templates.feet);
340
+ idx.set([h0, fh, f0, ff], i * 4);
341
+ poolBase.set(b.poolCol, i * 3);
342
+ poolR[i] = b.poolRadius;
343
+ });
344
+ const poolColours = new THREE.InstancedBufferAttribute(poolBase.slice(), 3);
345
+ const colours = new THREE.InstancedBufferAttribute(base.slice(), 3);
346
+ geo.setAttribute("iPos", new THREE.InstancedBufferAttribute(pos, 2));
347
+ geo.setAttribute("iCol", colours);
348
+ geo.setAttribute("iIdx", new THREE.InstancedBufferAttribute(idx, 4));
349
+ geo.setAttribute("iPoolCol", poolColours);
350
+ geo.setAttribute("iPoolR", new THREE.InstancedBufferAttribute(poolR, 1));
351
+ const mat = new THREE.ShaderMaterial({
352
+ vertexShader: STAMP_VERT,
353
+ fragmentShader: STAMP_FRAG,
354
+ uniforms: {
355
+ uGrid: { value: new THREE.Vector4(grid.scale, grid.x0, grid.z0, 0) },
356
+ uSize: { value: new THREE.Vector2(grid.w, grid.h) },
357
+ uExtent: { value: templates.extent },
358
+ atlas: { value: templates.texture },
359
+ uContrast: { value: STAMP_CONTRAST },
360
+ uFoot: { value: STAMP_FOOT },
361
+ uCells: { value: new THREE.Vector2(templates.feet.length, templates.heights.length) },
362
+ uQuarter: { value: TEMPLATE_SIZE }
363
+ },
364
+ blending: THREE.CustomBlending,
365
+ blendEquation: THREE.AddEquation,
366
+ blendSrc: THREE.OneFactor,
367
+ blendDst: THREE.OneFactor,
368
+ depthTest: false,
369
+ depthWrite: false,
370
+ transparent: true,
371
+ side: THREE.DoubleSide
372
+ });
373
+ const mesh = new THREE.Mesh(geo, mat);
374
+ mesh.frustumCulled = false;
375
+ const scene = new THREE.Scene();
376
+ scene.add(mesh);
377
+ const draw2 = () => {
378
+ const prevTarget = renderer.getRenderTarget();
379
+ renderer.setRenderTarget(target);
380
+ renderer.render(scene, cam);
381
+ renderer.setRenderTarget(prevTarget);
382
+ };
383
+ disposables.push(geo, plane, mat);
384
+ draw2();
385
+ return {
386
+ update(levels) {
387
+ const a = colours.array;
388
+ for (let i = 0; i < blocks.length; i++) {
389
+ const k = levels[i];
390
+ a[i * 3] = base[i * 3] * k;
391
+ a[i * 3 + 1] = base[i * 3 + 1] * k;
392
+ a[i * 3 + 2] = base[i * 3 + 2] * k;
393
+ const p = poolColours.array;
394
+ p[i * 3] = poolBase[i * 3] * k;
395
+ p[i * 3 + 1] = poolBase[i * 3 + 1] * k;
396
+ p[i * 3 + 2] = poolBase[i * 3 + 2] * k;
397
+ }
398
+ colours.needsUpdate = true;
399
+ poolColours.needsUpdate = true;
400
+ draw2();
401
+ }
402
+ };
403
+ };
404
+ const smooth = (passes) => {
405
+ const prevTarget = renderer.getRenderTarget();
406
+ quad.material = blurMat;
407
+ for (let i = 0; i < passes; i++) {
408
+ for (const step of [new THREE.Vector2(1 / grid.w, 0), new THREE.Vector2(0, 1 / grid.h)]) {
409
+ blurMat.uniforms.map.value = target.texture;
410
+ blurMat.uniforms.stepv.value.copy(step);
411
+ renderer.setRenderTarget(spare);
412
+ renderer.render(full, cam);
413
+ [target, spare] = [spare, target];
414
+ }
415
+ }
416
+ renderer.setRenderTarget(prevTarget);
417
+ };
418
+ return {
419
+ stamps,
420
+ sun,
421
+ smooth,
422
+ get texture() {
423
+ return target.texture;
424
+ },
425
+ dispose() {
426
+ target.dispose();
427
+ spare.dispose();
428
+ disposables.forEach((d) => d.dispose());
429
+ }
430
+ };
431
+ }
432
+
433
+ // src/neon.ts
434
+ var AREAS = 5;
435
+ var FLICKERING = AREAS;
436
+ var SPAN_MS = 2600;
437
+ var NEON_FPS = 20;
438
+ var PARTIALS = [[1, 1, 0.3], [2.76, 0.35, 0.14], [5.4, 0.12, 0.07]];
439
+ function bell(c, dest, when, f0, pan, level) {
440
+ const out = c.createGain();
441
+ out.gain.value = 0.05 * level;
442
+ const panner = c.createStereoPanner();
443
+ panner.pan.value = pan * 0.8;
444
+ out.connect(panner).connect(dest);
445
+ for (const [ratio, gain, decay] of PARTIALS) {
446
+ const f = f0 * ratio;
447
+ if (f > 16e3) continue;
448
+ const o = c.createOscillator();
449
+ o.type = "sine";
450
+ o.frequency.value = f;
451
+ const g = c.createGain();
452
+ g.gain.setValueAtTime(0, when);
453
+ g.gain.linearRampToValueAtTime(gain, when + 1e-3);
454
+ g.gain.exponentialRampToValueAtTime(1e-4, when + decay);
455
+ o.connect(g).connect(out);
456
+ o.start(when);
457
+ o.stop(when + decay + 0.02);
458
+ }
459
+ }
460
+ function createNeon({ blocks, apply, done, sound, fps = NEON_FPS, wobbleFps = 40, seed = 7, canPlay = () => true }) {
461
+ if (blocks.length === 0) return { levels: new Float32Array(0), count: 0, start: () => done(), stop: () => {
462
+ } };
463
+ let s = seed;
464
+ const random = () => (s = s * 16807 % 2147483647) / 2147483647;
465
+ const levels = new Float32Array(blocks.length).fill(1);
466
+ const pieces = [blocks.map((_, i) => i)];
467
+ while (pieces.length < Math.min(AREAS, blocks.length)) {
468
+ pieces.sort((p, q) => q.length - p.length);
469
+ const piece = pieces.shift();
470
+ if (piece.length < 2) {
471
+ pieces.push(piece);
472
+ break;
473
+ }
474
+ const xs = piece.map((i) => blocks[i].x);
475
+ const zs = piece.map((i) => blocks[i].z);
476
+ const alongX = Math.max(...xs) - Math.min(...xs) >= Math.max(...zs) - Math.min(...zs);
477
+ const sorted = [...piece].sort((i, j) => alongX ? blocks[i].x - blocks[j].x : blocks[i].z - blocks[j].z);
478
+ const cut = Math.min(sorted.length - 1, Math.max(1, Math.round(sorted.length * (0.35 + random() * 0.3))));
479
+ pieces.push(sorted.slice(0, cut), sorted.slice(cut));
480
+ }
481
+ const centres = pieces;
482
+ const areaOf = new Array(blocks.length).fill(0);
483
+ pieces.forEach((p, k) => p.forEach((i) => areaOf[i] = k));
484
+ const flickering = new Set([...centres.keys()].sort(() => random() - 0.5).slice(0, FLICKERING));
485
+ const areaPlans = /* @__PURE__ */ new Map();
486
+ flickering.forEach((k) => {
487
+ const start = random() * (SPAN_MS - 1100);
488
+ const count = 2 + Math.floor(random() * 3);
489
+ const stutters = [];
490
+ let at = start;
491
+ for (let j = 0; j < count; j++) {
492
+ const length = 30 + random() * 110;
493
+ stutters.push({ at, length, level: 0.4 + random() * 0.6 });
494
+ at += length + (50 + random() * 240) * (1 - j / count * 0.6);
495
+ }
496
+ areaPlans.set(k, { start, stutters, steady: at + 60 });
497
+ });
498
+ const plans = /* @__PURE__ */ new Map();
499
+ blocks.forEach((_, i) => {
500
+ const base = areaPlans.get(areaOf[i]);
501
+ if (base) plans.set(i, { ...base, shift: random() * 70, scale: 0.8 + random() * 0.2, area: areaOf[i] });
502
+ });
503
+ const end = Math.max(0, ...[...areaPlans.values()].map((p) => p.steady + 380 + 70));
504
+ const levelAt = (plan, at) => {
505
+ const ms = at - plan.shift;
506
+ if (ms < plan.start) return 0;
507
+ if (ms >= plan.steady + 380) return 1;
508
+ if (ms >= plan.steady) return 0.6 + 0.4 * ((ms - plan.steady) / 380);
509
+ for (const st of plan.stutters) if (ms >= st.at && ms < st.at + st.length) return st.level * plan.scale;
510
+ return 0;
511
+ };
512
+ plans.forEach((_, i) => levels[i] = 0);
513
+ let raf = 0;
514
+ let t0 = 0;
515
+ let last = -1;
516
+ let dirty = false;
517
+ let running = false;
518
+ const FRAME_LAG = 25;
519
+ const audioTime = (c, perfStart) => c.currentTime - (performance.now() - perfStart) / 1e3 + FRAME_LAG / 1e3 - (c.outputLatency || c.baseLatency || 0);
520
+ const mayWait = () => navigator.userActivation?.hasBeenActive !== false;
521
+ let ctx2 = null;
522
+ let closeTimer = 0;
523
+ const closeSound = () => {
524
+ window.clearTimeout(closeTimer);
525
+ document.removeEventListener("visibilitychange", onVisibility);
526
+ const c = ctx2;
527
+ ctx2 = null;
528
+ if (c && c.state !== "closed") c.close().catch(() => {
529
+ });
530
+ };
531
+ const onVisibility = () => {
532
+ if (document.hidden) closeSound();
533
+ };
534
+ const prepare = async () => {
535
+ if (!sound || typeof AudioContext === "undefined" || document.hidden || !mayWait()) return null;
536
+ let c;
537
+ try {
538
+ c = new AudioContext();
539
+ await Promise.race([c.resume(), new Promise((r) => setTimeout(r, 300))]);
540
+ } catch {
541
+ return null;
542
+ }
543
+ if (c.state !== "running" || document.hidden) {
544
+ c.close().catch(() => {
545
+ });
546
+ return null;
547
+ }
548
+ return c;
549
+ };
550
+ const schedule = (c) => {
551
+ ctx2 = c;
552
+ const now = audioTime(c, t0);
553
+ const master2 = c.createGain();
554
+ master2.gain.value = 0.5;
555
+ const limiter = c.createDynamicsCompressor();
556
+ master2.connect(limiter).connect(c.destination);
557
+ const lit = [];
558
+ for (let ms = 0; ms <= end + 200; ms += 25) {
559
+ let sum = 0;
560
+ plans.forEach((p) => sum += levelAt(p, ms));
561
+ lit.push(sum / Math.max(1, plans.size));
562
+ }
563
+ const settled = now + (end + 200) / 1e3;
564
+ const FADE = 10;
565
+ const hum = c.createOscillator();
566
+ hum.type = "sawtooth";
567
+ hum.frequency.value = 100;
568
+ const lowpass = c.createBiquadFilter();
569
+ lowpass.type = "lowpass";
570
+ lowpass.frequency.value = 520;
571
+ const humGain = c.createGain();
572
+ humGain.gain.setValueAtTime(0, c.currentTime);
573
+ lit.forEach((v, i) => humGain.gain.linearRampToValueAtTime(4e-3 * v, Math.max(now + i * 25 / 1e3, c.currentTime + 1e-3)));
574
+ humGain.gain.setTargetAtTime(0, Math.max(settled, c.currentTime), FADE / 3);
575
+ hum.connect(lowpass).connect(humGain).connect(master2);
576
+ hum.start(Math.max(now, c.currentTime));
577
+ const stopAt = settled + FADE * 1.6;
578
+ hum.stop(stopAt);
579
+ const members = /* @__PURE__ */ new Map();
580
+ plans.forEach((p, i) => (members.get(p.area) ?? members.set(p.area, []).get(p.area)).push(i));
581
+ const voices = blocks.map(() => {
582
+ const r = random();
583
+ const band = random();
584
+ const hz = band < 0.15 ? 1300 + random() * 250 : 2700 + random() * 650;
585
+ return { quiet: r >= 0.85, hz, gain: 0.45 + random() * 0.95 };
586
+ });
587
+ const heard = [];
588
+ const click = (at, pan, level, tube) => {
589
+ const voice = voices[tube];
590
+ if (voice && !voice.quiet) heard.push({ at: at + (plans.get(tube)?.shift ?? 0), pan, level, tube });
591
+ };
592
+ areaPlans.forEach((plan, area) => {
593
+ const own = members.get(area) ?? [];
594
+ if (!own.length) return;
595
+ plan.stutters.forEach((st) => {
596
+ const n = 1 + Math.floor(random() * 3);
597
+ for (let k = 0; k < n; k++) {
598
+ const i = own[Math.floor(random() * own.length)];
599
+ click(st.at, blocks[i].pan, st.level, i);
600
+ if (random() < 0.6) click(st.at + st.length, blocks[i].pan, st.level * 0.35, i);
601
+ }
602
+ });
603
+ const settle = 2 + Math.floor(random() * 3);
604
+ for (let k = 0; k < settle; k++) {
605
+ const i = own[Math.floor(random() * own.length)];
606
+ click(plan.steady, blocks[i].pan, 0.85, i);
607
+ }
608
+ });
609
+ const keep = Math.min(1, 40 / Math.max(1, heard.length));
610
+ heard.forEach((h) => {
611
+ if (random() > keep) return;
612
+ const voice = voices[h.tube];
613
+ const when = Math.max(now + h.at / 1e3, c.currentTime);
614
+ bell(c, master2, when, voice.hz * (0.98 + random() * 0.04), h.pan, h.level * voice.gain * (0.6 + random() * 0.6));
615
+ });
616
+ closeTimer = window.setTimeout(closeSound, (stopAt - c.currentTime) * 1e3 + 500);
617
+ };
618
+ let idleTimer = 0;
619
+ let idleRaf = 0;
620
+ let idleCtx = null;
621
+ let idleClose = 0;
622
+ let idleOn = false;
623
+ let idleSince = 0;
624
+ const idleRandom = () => Math.random();
625
+ const busy = /* @__PURE__ */ new Set();
626
+ const fMax = wobbleFps * 0.4;
627
+ const wobbleSeed = blocks.map(() => ({ s: random() < 0.18 ? 0.4 + random() * 0.6 : 0, f1: fMax * (0.25 + random() * 0.25), f2: fMax * (0.5 + random() * 0.5), p1: random() * 6.283, p2: random() * 6.283 }));
628
+ const rate = Math.max(fps, wobbleFps);
629
+ const HUM_STEP = 25;
630
+ const humEnd = end + 200;
631
+ const humLit = [];
632
+ for (let ms = 0; ms <= humEnd; ms += HUM_STEP) {
633
+ let sum = 0;
634
+ plans.forEach((p) => sum += levelAt(p, ms));
635
+ humLit.push(sum / Math.max(1, plans.size));
636
+ }
637
+ const humAt = (ms) => ms <= humEnd ? humLit[Math.min(humLit.length - 1, Math.floor(ms / HUM_STEP))] ?? 0 : Math.exp(-(ms - humEnd) / 3333);
638
+ const WOBBLE_DEPTH = 0.45;
639
+ const wob = (i, ms, hum) => {
640
+ if (hum <= 5e-3) return 1;
641
+ const w = wobbleSeed[i];
642
+ const sec = ms / 1e3;
643
+ const n = 0.5 + 0.5 * (0.6 * Math.sin(6.283 * w.f1 * sec + w.p1) + 0.4 * Math.sin(6.283 * w.f2 * sec + w.p2));
644
+ return 1 - WOBBLE_DEPTH * hum * w.s * n;
645
+ };
646
+ let tailing = false;
647
+ let tailRaf = 0;
648
+ let tailLast = -1;
649
+ const tail = (stamp) => {
650
+ tailRaf = 0;
651
+ if (!tailing) return;
652
+ const ms = performance.now() - t0;
653
+ const hum = humAt(ms);
654
+ if (tailLast < 0 || stamp - tailLast >= 1e3 / rate) {
655
+ tailLast = stamp;
656
+ if (canPlay() && !document.hidden) {
657
+ for (let i = 0; i < blocks.length; i++) if (!busy.has(i)) levels[i] = wob(i, ms, hum);
658
+ apply(levels);
659
+ }
660
+ }
661
+ if (hum < 0.015) {
662
+ tailing = false;
663
+ for (let i = 0; i < blocks.length; i++) if (!busy.has(i)) levels[i] = 1;
664
+ apply(levels);
665
+ done();
666
+ return;
667
+ }
668
+ tailRaf = requestAnimationFrame(tail);
669
+ };
670
+ const stopIdle = () => {
671
+ idleOn = false;
672
+ tailing = false;
673
+ cancelAnimationFrame(tailRaf);
674
+ busy.clear();
675
+ window.clearTimeout(idleTimer);
676
+ window.clearTimeout(idleClose);
677
+ cancelAnimationFrame(idleRaf);
678
+ const c = idleCtx;
679
+ idleCtx = null;
680
+ if (c && c.state !== "closed") c.close().catch(() => {
681
+ });
682
+ };
683
+ const idleContext = async () => {
684
+ if (!sound || typeof AudioContext === "undefined" || !mayWait()) return null;
685
+ let c;
686
+ try {
687
+ c = new AudioContext();
688
+ await Promise.race([c.resume(), new Promise((r) => setTimeout(r, 300))]);
689
+ } catch {
690
+ return null;
691
+ }
692
+ if (c.state !== "running" || !idleOn) {
693
+ c.close().catch(() => {
694
+ });
695
+ return null;
696
+ }
697
+ return c;
698
+ };
699
+ const idleSound = (c, edges, pan, perfStart) => {
700
+ idleCtx = c;
701
+ const master2 = c.createGain();
702
+ master2.gain.value = 0.5;
703
+ master2.connect(c.createDynamicsCompressor()).connect(c.destination);
704
+ const base = audioTime(c, perfStart);
705
+ const outHz = 800 + idleRandom() * 150;
706
+ const onHz = 2700 + idleRandom() * 350;
707
+ edges.forEach((e) => bell(c, master2, base + e.at / 1e3, e.on ? onHz : outHz, pan, e.level));
708
+ window.clearTimeout(idleClose);
709
+ idleClose = window.setTimeout(() => {
710
+ const x = idleCtx;
711
+ idleCtx = null;
712
+ if (x && x.state !== "closed") x.close().catch(() => {
713
+ });
714
+ }, (edges[edges.length - 1]?.at ?? 0) + 1500);
715
+ };
716
+ const flicker = () => {
717
+ const slow = Math.exp((performance.now() - idleSince) / 45e3);
718
+ idleTimer = window.setTimeout(flicker, (3e3 + idleRandom() ** 1.6 * 17e3) * slow);
719
+ if (!idleOn || document.hidden || !canPlay()) return;
720
+ const r = idleRandom();
721
+ const want = r < 0.2 ? 1 : r < 0.45 ? 2 + Math.floor(idleRandom() * 3) : r < 0.8 ? 5 + Math.floor(idleRandom() * 5) : 10 + Math.floor(idleRandom() * 9);
722
+ const first = Math.floor(idleRandom() * blocks.length);
723
+ const ranked = blocks.map((b, i) => ({ i, d: Math.hypot(b.x - blocks[first].x, b.z - blocks[first].z) })).filter((o) => o.d <= 5).sort((a, b) => a.d - b.d).slice(0, want);
724
+ const batch = ranked.map((o) => o.i);
725
+ batch.forEach((i) => busy.add(i));
726
+ const dark = 120 + idleRandom() ** 2 * 2400;
727
+ let at = dark;
728
+ const glows = [];
729
+ const stutters = idleRandom() < 0.55 ? 1 + Math.floor(idleRandom() * 3) : 0;
730
+ for (let j = 0; j < stutters; j++) {
731
+ const len = 40 + idleRandom() * 60;
732
+ glows.push([at, at + len, 0.55 + idleRandom() * 0.3]);
733
+ at += len + 40 + idleRandom() * 110;
734
+ }
735
+ const onAt = at;
736
+ const shift = ranked.map((o) => o.d * 12 + idleRandom() * 30);
737
+ const total = onAt + 40 + 40;
738
+ const edges = [{ at: 0, on: false, level: 1 }];
739
+ glows.forEach(([a, b, v]) => edges.push({ at: a, on: true, level: 0.5 * v + 0.2 }, { at: b, on: false, level: 0.6 }));
740
+ edges.push({ at: onAt, on: true, level: 0.8 });
741
+ const play = async () => {
742
+ const c = await idleContext();
743
+ if (!idleOn) {
744
+ c?.close().catch(() => {
745
+ });
746
+ return;
747
+ }
748
+ const t02 = performance.now();
749
+ if (c) idleSound(c, edges, blocks[first].pan, t02);
750
+ let last2 = -1;
751
+ const step = (stamp) => {
752
+ idleRaf = 0;
753
+ if (!idleOn) return;
754
+ const ms = stamp - t02;
755
+ let changed = false;
756
+ batch.forEach((i, k) => {
757
+ const m = ms - shift[k];
758
+ let v = 1;
759
+ if (m >= 0 && m < onAt) v = glows.find(([a, b]) => m >= a && m < b)?.[2] ?? 0;
760
+ if (v !== levels[i] || last2 < 0) changed = true;
761
+ levels[i] = v;
762
+ });
763
+ last2 = stamp;
764
+ if (changed) apply(levels, true);
765
+ if (ms >= total) {
766
+ batch.forEach((i) => {
767
+ levels[i] = 1;
768
+ busy.delete(i);
769
+ });
770
+ apply(levels, true);
771
+ done();
772
+ return;
773
+ }
774
+ idleRaf = requestAnimationFrame(step);
775
+ };
776
+ idleRaf = requestAnimationFrame(step);
777
+ };
778
+ void play();
779
+ };
780
+ const startIdle = () => {
781
+ idleOn = true;
782
+ idleSince = performance.now();
783
+ window.clearTimeout(idleTimer);
784
+ idleTimer = window.setTimeout(flicker, 2500 + idleRandom() * 3500);
785
+ };
786
+ const tick = (stamp) => {
787
+ raf = 0;
788
+ if (!running) return;
789
+ const ms = stamp - t0;
790
+ let jump = false;
791
+ const hum = humAt(ms);
792
+ for (let i = 0; i < blocks.length; i++) {
793
+ const plan = plans.get(i);
794
+ const v = (plan ? levelAt(plan, ms) : 1) * wob(i, ms, hum);
795
+ const d = Math.abs(v - levels[i]);
796
+ if (d > 1e-3) {
797
+ if (d > 0.15) jump = true;
798
+ levels[i] = v;
799
+ dirty = true;
800
+ }
801
+ }
802
+ if (dirty && (jump || last < 0 || stamp - last >= 1e3 / rate)) {
803
+ last = stamp;
804
+ dirty = false;
805
+ apply(levels);
806
+ }
807
+ if (ms >= end) {
808
+ running = false;
809
+ if (!ctx2) document.removeEventListener("visibilitychange", onVisibility);
810
+ done();
811
+ startIdle();
812
+ tailing = true;
813
+ tailLast = -1;
814
+ tailRaf = requestAnimationFrame(tail);
815
+ return;
816
+ }
817
+ raf = requestAnimationFrame(tick);
818
+ };
819
+ return {
820
+ /** The levels as they stand (the scene reads them at once, to build the first frame with the flickering rods off). */
821
+ levels,
822
+ /** How many rods flicker. */
823
+ count: plans.size,
824
+ start() {
825
+ if (running) return;
826
+ running = true;
827
+ dirty = false;
828
+ apply(levels);
829
+ document.addEventListener("visibilitychange", onVisibility);
830
+ void prepare().then((c) => {
831
+ if (!running || raf) {
832
+ c?.close().catch(() => {
833
+ });
834
+ return;
835
+ }
836
+ last = -1;
837
+ t0 = performance.now();
838
+ if (c) schedule(c);
839
+ raf = requestAnimationFrame(tick);
840
+ });
841
+ },
842
+ stop() {
843
+ running = false;
844
+ cancelAnimationFrame(raf);
845
+ document.removeEventListener("visibilitychange", onVisibility);
846
+ levels.fill(1);
847
+ closeSound();
848
+ stopIdle();
849
+ }
850
+ };
851
+ }
852
+
853
+ // src/size.ts
854
+ function renderSize(input) {
855
+ const { cssWidth, cssHeight, lite, maxPixelRatio = 2, maxPixels = 8e6, maxSize = 8192 } = input;
856
+ let ratio = lite ? 1 : Math.min(input.devicePixelRatio || 1, maxPixelRatio);
857
+ const area = Math.max(1, cssWidth) * Math.max(1, cssHeight);
858
+ ratio = Math.min(ratio, Math.sqrt(maxPixels / area), maxSize / Math.max(1, cssWidth, cssHeight));
859
+ return { width: Math.max(1, Math.round(cssWidth * ratio)), height: Math.max(1, Math.round(cssHeight * ratio)), ratio };
860
+ }
861
+
862
+ // src/hover-hum.ts
863
+ var MAX = 3e-3;
864
+ var IDLE_CLOSE_MS = 4500;
865
+ var ATTACK = 0.09;
866
+ var RELEASE = 0.45;
867
+ var pitchOf = (size) => 112 - 42 * Math.max(0, Math.min(1, size));
868
+ function voiceOf(seed, size) {
869
+ let a = seed * 2654435761 + 2654435769 >>> 0;
870
+ const rnd = () => {
871
+ a = a + 1831565813 >>> 0;
872
+ let t = a;
873
+ t = Math.imul(t ^ t >>> 15, t | 1);
874
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
875
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
876
+ };
877
+ const base = pitchOf(size) * (0.96 + rnd() * 0.08);
878
+ const ratios = [1.5, 1.335, 1.26, 2.01];
879
+ return {
880
+ base,
881
+ beat: 0.3 + rnd() * 1.1,
882
+ second: base * ratios[Math.floor(rnd() * ratios.length)],
883
+ lfo: 0.35 + rnd() * 1.3,
884
+ depth: 0.5 + rnd() * 0.4,
885
+ upper: 0.15 + rnd() * 0.35,
886
+ tone: 0.85 + rnd() * 0.3
887
+ };
888
+ }
889
+ function createHoverHum() {
890
+ let c = null;
891
+ let gain = null;
892
+ let lp = null;
893
+ let panner = null;
894
+ let closeTimer = 0;
895
+ let oscs = [];
896
+ let upperGain = null;
897
+ let duck = null;
898
+ let swell = null;
899
+ let voiceA = null;
900
+ let voiceB = null;
901
+ let seeded = -1;
902
+ let seededSize = -1;
903
+ let tone = 1;
904
+ let prev = 0;
905
+ const allowed = () => navigator.userActivation?.hasBeenActive !== false;
906
+ const close = () => {
907
+ window.clearTimeout(closeTimer);
908
+ oscs.forEach((o) => {
909
+ try {
910
+ o.stop();
911
+ } catch {
912
+ }
913
+ });
914
+ oscs = [];
915
+ const x = c;
916
+ c = null;
917
+ gain = lp = panner = upperGain = duck = swell = voiceA = voiceB = null;
918
+ seeded = -1;
919
+ seededSize = -1;
920
+ prev = 0;
921
+ if (x && x.state !== "closed") x.close().catch(() => {
922
+ });
923
+ };
924
+ const open = () => {
925
+ const AC = window.AudioContext ?? window.webkitAudioContext;
926
+ if (!AC || !allowed()) return false;
927
+ c = new AC();
928
+ void c.resume().catch(() => {
929
+ });
930
+ gain = c.createGain();
931
+ gain.gain.value = 0;
932
+ lp = c.createBiquadFilter();
933
+ lp.type = "lowpass";
934
+ lp.frequency.value = 380;
935
+ lp.Q.value = 0.6;
936
+ panner = c.createStereoPanner();
937
+ const osc = (type) => {
938
+ const o = c.createOscillator();
939
+ o.type = type;
940
+ o.frequency.value = 100;
941
+ o.start();
942
+ oscs.push(o);
943
+ return o;
944
+ };
945
+ voiceA = c.createGain();
946
+ voiceA.gain.value = 0.7;
947
+ osc("sawtooth").connect(voiceA);
948
+ osc("sawtooth").connect(voiceA);
949
+ voiceB = c.createGain();
950
+ voiceB.gain.value = 0.4;
951
+ osc("sawtooth").connect(voiceB);
952
+ upperGain = c.createGain();
953
+ upperGain.gain.value = 0.3;
954
+ osc("sine").connect(upperGain);
955
+ const lfo = osc("sine");
956
+ lfo.frequency.value = 0.8;
957
+ swell = c.createGain();
958
+ swell.gain.value = 0.3;
959
+ duck = c.createGain();
960
+ duck.gain.value = -0.3;
961
+ lfo.connect(swell).connect(voiceB.gain);
962
+ lfo.connect(duck).connect(voiceA.gain);
963
+ voiceA.connect(lp);
964
+ voiceB.connect(lp);
965
+ upperGain.connect(lp);
966
+ lp.connect(gain).connect(panner).connect(c.destination);
967
+ return true;
968
+ };
969
+ return {
970
+ /**
971
+ * The hum's strength, 0 to 1 (the selected neon's brightness above its normal, as a share of the most it gets). `pan` (-1 to 1), `seed` (the neon's number) and `size` (0 the smallest to 1 the biggest: it sets the pitch, small high and big low) say which neon it is, or `null` when none is under the pointer:
972
+ * then the hum is the last neon's, as it was, and only fades.
973
+ */
974
+ set(level, pan = null, seed = null, size = 0.5) {
975
+ const v = Math.max(0, Math.min(1, level));
976
+ if (v < 0.01 && !c) return;
977
+ if (!c && !open()) return;
978
+ if (!c || !gain || !lp || !panner) return;
979
+ const t = c.currentTime;
980
+ if (c.state === "suspended") void c.resume().catch(() => {
981
+ });
982
+ if (seed !== null && pan !== null && (seed !== seeded || size !== seededSize)) {
983
+ const vc = voiceOf(seed, size);
984
+ const glide = seeded < 0 ? 1e-3 : 0.12;
985
+ oscs[0]?.frequency.setTargetAtTime(vc.base, t, glide);
986
+ oscs[1]?.frequency.setTargetAtTime(vc.base + vc.beat, t, glide);
987
+ oscs[2]?.frequency.setTargetAtTime(vc.second, t, glide);
988
+ oscs[3]?.frequency.setTargetAtTime(vc.base * 2, t, glide);
989
+ oscs[4]?.frequency.setTargetAtTime(vc.lfo, t, glide);
990
+ upperGain?.gain.setTargetAtTime(vc.upper, t, glide);
991
+ swell?.gain.setTargetAtTime(0.4 * vc.depth, t, glide);
992
+ duck?.gain.setTargetAtTime(-0.4 * vc.depth, t, glide);
993
+ tone = vc.tone;
994
+ seeded = seed;
995
+ seededSize = size;
996
+ }
997
+ if (pan !== null) panner.pan.setTargetAtTime(pan * 0.7, t, 0.15);
998
+ const tc = v >= prev ? ATTACK : RELEASE;
999
+ prev = v;
1000
+ gain.gain.setTargetAtTime(MAX * v ** 1.5, t, tc);
1001
+ lp.frequency.setTargetAtTime((380 + 520 * v) * tone, t, tc);
1002
+ window.clearTimeout(closeTimer);
1003
+ if (v < 0.01) closeTimer = window.setTimeout(close, IDLE_CLOSE_MS);
1004
+ },
1005
+ /** Let the hum go at once (the picture is rebuilt or taken down). */
1006
+ stop: close
1007
+ };
1008
+ }
1009
+
1010
+ // src/graph.ts
1011
+ var GLASS_ABSORB = 0.45;
1012
+ var GLASS_FLOOR = 0.3;
1013
+ var SAMPLES = 96;
1014
+ var DEFAULT_COLORS = {
1015
+ // each source has its own hue and the level of the day is the brightness: a quiet day is a dim dark shade, a busy one the brightest
1016
+ top: { light: [692012, 54844], dark: [1018412, 1031998] },
1017
+ bottom: { light: [1464504, 1740031], dark: [1006248, 2071551] }
1018
+ };
1019
+ function resolveLite(lite) {
1020
+ if (typeof lite === "boolean") return lite;
1021
+ const nav = navigator;
1022
+ return window.matchMedia("(pointer: coarse)").matches || (nav.hardwareConcurrency ?? 8) <= 4 || (nav.deviceMemory ?? 8) < 4;
1023
+ }
1024
+ function resolveBackground(el, option, theme) {
1025
+ const given = typeof option === "function" ? option(theme) : option;
1026
+ if (given) return given;
1027
+ for (let n = el; n; n = n.parentElement) {
1028
+ const c = getComputedStyle(n).backgroundColor;
1029
+ if (c && c !== "transparent" && !/rgba\(.*,\s*0\)$/.test(c)) return c;
1030
+ }
1031
+ return theme === "dark" ? "#0b0b0e" : "#ffffff";
1032
+ }
1033
+ function mountScene(el, opts, st) {
1034
+ const api = { stop: () => {
1035
+ }, rethink: (_recolour) => {
1036
+ }, bounds: () => null };
1037
+ let cancelled = false;
1038
+ const dbg = opts.debug ?? {};
1039
+ const mq = window.matchMedia("(prefers-color-scheme: dark)");
1040
+ const isDark = () => st.theme === "auto" ? mq.matches : st.theme === "dark";
1041
+ const colorOf = (layer, dark) => opts.colors?.[layer]?.[dark ? "dark" : "light"] ?? DEFAULT_COLORS[layer][dark ? "dark" : "light"];
1042
+ el.setAttribute("role", "group");
1043
+ el.setAttribute("aria-roledescription", "interactive chart");
1044
+ el.setAttribute("aria-label", opts.label ?? "Activity graph, one column a day. Use the arrow keys to move between days.");
1045
+ const ready = (async () => {
1046
+ const THREE = await import("three");
1047
+ const { RoundedBoxGeometry } = await import("three/examples/jsm/geometries/RoundedBoxGeometry.js");
1048
+ const { mergeGeometries } = await import("three/examples/jsm/utils/BufferGeometryUtils.js");
1049
+ const { RoomEnvironment } = await import("three/examples/jsm/environments/RoomEnvironment.js");
1050
+ let templates = null;
1051
+ let templatesFailed = false;
1052
+ const templatesSource = async () => opts.templatesUrl ?? (await import("./templates-data-2RIHMIOJ.js")).TEMPLATES_DATA_URI;
1053
+ const wantTemplates = () => templatesFailed ? Promise.resolve() : templatesSource().then((url) => loadCausticTemplates(THREE, url)).then((t) => void (templates = t)).catch(() => void (templatesFailed = true));
1054
+ if (isDark()) await wantTemplates();
1055
+ if (cancelled) return;
1056
+ const cm = (fn) => {
1057
+ const prev = THREE.ColorManagement.enabled;
1058
+ THREE.ColorManagement.enabled = true;
1059
+ try {
1060
+ return fn();
1061
+ } finally {
1062
+ THREE.ColorManagement.enabled = prev;
1063
+ }
1064
+ };
1065
+ cm(() => {
1066
+ const { onReady, onLit, onHover } = opts;
1067
+ const strips = opts.strips ?? 1;
1068
+ const layout = layoutGraph(opts.data, opts.weeks ?? 53);
1069
+ const lite = resolveLite(opts.lite);
1070
+ const samples = lite ? 32 : SAMPLES;
1071
+ const t0 = performance.now();
1072
+ const renderer = new THREE.WebGLRenderer({ antialias: false, alpha: true, powerPreference: "high-performance" });
1073
+ renderer.setClearColor(0, 0);
1074
+ renderer.shadowMap.enabled = true;
1075
+ renderer.shadowMap.type = THREE.PCFShadowMap;
1076
+ el.appendChild(renderer.domElement);
1077
+ if (getComputedStyle(el).position === "static") el.style.position = "relative";
1078
+ const CANVAS_FADE = "filter .4s ease,opacity .4s ease";
1079
+ renderer.domElement.style.cssText = `position:absolute;inset:0;display:block;width:100%;height:100%;transition:${CANVAS_FADE};opacity:0;filter:blur(7px)`;
1080
+ let settling = false;
1081
+ const soften = (opacity = "0.85") => {
1082
+ settling = true;
1083
+ renderer.domElement.style.filter = "blur(7px)";
1084
+ renderer.domElement.style.opacity = opacity;
1085
+ };
1086
+ let announced = false;
1087
+ let neonStart = null;
1088
+ let shownW = 0;
1089
+ let shownH = 0;
1090
+ const holdSize = () => {
1091
+ if (!shownW || !shownH) return;
1092
+ const s = renderer.domElement.style;
1093
+ s.inset = "auto";
1094
+ s.width = `${shownW}px`;
1095
+ s.height = `${shownH}px`;
1096
+ s.left = `${(el.clientWidth - shownW) / 2}px`;
1097
+ s.top = `${(el.clientHeight - shownH) / 2}px`;
1098
+ };
1099
+ const releaseSize = () => {
1100
+ const s = renderer.domElement.style;
1101
+ s.inset = "0";
1102
+ s.left = "";
1103
+ s.top = "";
1104
+ s.width = "100%";
1105
+ s.height = "100%";
1106
+ shownW = el.clientWidth;
1107
+ shownH = el.clientHeight;
1108
+ };
1109
+ const sharpen = () => {
1110
+ settling = false;
1111
+ if (!announced) {
1112
+ announced = true;
1113
+ onReady?.();
1114
+ }
1115
+ renderer.domElement.style.transition = CANVAS_FADE;
1116
+ renderer.domElement.style.filter = "";
1117
+ renderer.domElement.style.opacity = "";
1118
+ opts.onRedrawn?.();
1119
+ const go = neonStart;
1120
+ neonStart = null;
1121
+ go?.();
1122
+ };
1123
+ soften("0");
1124
+ const ROOM = roomFor(strips);
1125
+ const { width, total, at, corners } = slabFor(layout.top.weeks, strips, shiftsFromLayers([layout.top, layout.bottom], strips));
1126
+ const scene = new THREE.Scene();
1127
+ const pmrem = new THREE.PMREMGenerator(renderer);
1128
+ const env = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;
1129
+ scene.environment = env;
1130
+ scene.environmentIntensity = 0.9;
1131
+ const GRAIN = opts.grain ?? 0.012;
1132
+ const LIGHT_ENV = 0.3;
1133
+ const LIGHT_COAT = 0.1;
1134
+ const LIGHT_GLASS_ROUGHNESS = 0.04;
1135
+ const LIGHT_SPECULAR = 0.35;
1136
+ const blockMaterial = new THREE.MeshPhysicalMaterial({
1137
+ vertexColors: true,
1138
+ roughness: 0.04,
1139
+ metalness: 0,
1140
+ transmission: 1,
1141
+ thickness: 1.6,
1142
+ ior: 1.5,
1143
+ dispersion: 0.35,
1144
+ attenuationColor: new THREE.Color(16777215),
1145
+ attenuationDistance: 4,
1146
+ clearcoat: 1,
1147
+ clearcoatRoughness: 0.03,
1148
+ specularIntensity: 1,
1149
+ envMapIntensity: 1.4
1150
+ });
1151
+ const tileUnlit = new THREE.MeshBasicMaterial({ vertexColors: true, toneMapped: false, side: THREE.BackSide });
1152
+ const pageColour = () => {
1153
+ const css = resolveBackground(el, opts.background, isDark() ? "dark" : "light");
1154
+ const probe = document.createElement("canvas");
1155
+ probe.width = probe.height = 1;
1156
+ const ctx2 = probe.getContext("2d");
1157
+ ctx2.fillStyle = css;
1158
+ ctx2.fillRect(0, 0, 1, 1);
1159
+ const [r, g, b] = ctx2.getImageData(0, 0, 1, 1).data;
1160
+ return new THREE.Color().setRGB(r / 255, g / 255, b / 255, THREE.SRGBColorSpace);
1161
+ };
1162
+ const LIGHT_CORE_LIFT = 0;
1163
+ const LIGHT_CORE_DEPTH = 0.78;
1164
+ const LIGHT_SHELL_WHITE = 0.78;
1165
+ const LIGHT_DOUBLE_SIDED = false;
1166
+ const LIGHT_BACKDROP = true;
1167
+ const DARK_BACKDROP = true;
1168
+ const DARK_BACKDROP_GAIN = 200;
1169
+ const DARK_BACKDROP_CAP = 0.15;
1170
+ const LIGHT_BEHIND_TINT = 0.85;
1171
+ const coreMaterial = new THREE.MeshBasicMaterial({ vertexColors: true });
1172
+ coreMaterial.onBeforeCompile = (shader) => {
1173
+ shader.vertexShader = shader.vertexShader.replace("#include <common>", "#include <common>\nvarying vec3 vCoreN;").replace("#include <begin_vertex>", "#include <begin_vertex>\n vCoreN = normalize(normalMatrix * normal);");
1174
+ shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nvarying vec3 vCoreN;").replace("#include <color_fragment>", "#include <color_fragment>\n float cf = pow(clamp(abs(normalize(vCoreN).z), 0.0, 1.0), 0.9);\n diffuseColor.rgb = mix(mix(diffuseColor.rgb, vec3(1.0), CORE_HAZE), diffuseColor.rgb, cf);".replace("CORE_HAZE", "0.5"));
1175
+ };
1176
+ const ROD_KNEE = 0.7;
1177
+ const ROD_MAX = 1.5;
1178
+ const ROD_WHITE = 0.35;
1179
+ const glowMaterial = new THREE.MeshBasicMaterial({ vertexColors: true, toneMapped: false, blending: THREE.AdditiveBlending, depthWrite: false });
1180
+ const backdropDim = { value: 1 };
1181
+ const softSeen = `vec3 softSeen(vec3 g) { float m = max(g.r, max(g.g, g.b)); if (m < 1e-6) return g; float k = ${DARK_BACKDROP_CAP.toFixed(3)}; return g * (k * tanh(min(m * ${DARK_BACKDROP_GAIN.toFixed(3)} / k, 12.0)) / m); }`;
1182
+ const DARK_GREEN_GLOW = 0.2;
1183
+ const LAYER_FILTER_DISTANCE = 2;
1184
+ const LAYER_FILTER_PURITY = 0.72;
1185
+ const NEIGHBOUR_GLOW = 0.22;
1186
+ const BEHIND_SCALE = 1.6;
1187
+ const GLOW_TINT = 1;
1188
+ const GLOW_TINT_FAINT = 0.35;
1189
+ const GLOW_SATURATION = 2.5;
1190
+ const GREEN_MIN_LEVEL = 1.1;
1191
+ const DARK_GLASS_ROUGHNESS = 0.04;
1192
+ const OFF_EMISSIVE = 12e-4;
1193
+ const OFF_ENV = 4e-3;
1194
+ const MAX_LEVELS = 1024;
1195
+ const levelData = new Float32Array(MAX_LEVELS * 2).fill(1);
1196
+ const levelTex = new THREE.DataTexture(levelData, MAX_LEVELS, 1, THREE.RGFormat, THREE.FloatType);
1197
+ levelTex.needsUpdate = true;
1198
+ glowMaterial.onBeforeCompile = (shader) => {
1199
+ shader.uniforms.uLevels = { value: levelTex };
1200
+ shader.vertexShader = shader.vertexShader.replace("#include <common>", "#include <common>\nattribute float aBlock;\nattribute vec3 aInc;\nattribute vec2 aCtr;\nvarying float vRodA;\nuniform highp sampler2D uLevels;").replace("#include <color_vertex>", "#include <color_vertex>\n#ifdef USE_COLOR\n vec2 lv = texelFetch(uLevels, ivec2(int(aBlock + 0.5), 0), 0).rg;\n float rodB = max(vColor.r, max(vColor.g, vColor.b)) * lv.r;\n vColor.rgb = vColor.rgb * lv.r + vec3(0.029, 0.037, 0.053) * (1.0 - lv.r) + aInc * lv.g;\n vRodA = smoothstep(0.0, 3.0, rodB);\n float rodL = dot(vColor.rgb, vec3(0.299, 0.587, 0.114));\n vColor.rgb = max(vec3(0.0), mix(vec3(rodL), vColor.rgb, 1.3 + 1.8 * (1.0 - clamp(lv.r, 0.0, 1.0))));\n#endif").replace("#include <begin_vertex>", "#include <begin_vertex>\n transformed.xz = aCtr + (transformed.xz - aCtr) * mix(0.6, 1.0, smoothstep(0.0, 2.5, rodB));");
1201
+ shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nvarying float vRodA;").replace("#include <color_fragment>", "#include <color_fragment>\n diffuseColor.rgb *= vRodA;\n // (a very bright rod is not a flat blob of its colour: above the knee its level is compressed, whatever its hue, and what is left of it is whitened a little, as a real light too bright for the eye or the film turns to a hot white core with the colour round it; the faces' shading survives, as a smaller difference)\n float rm = max(diffuseColor.r, max(diffuseColor.g, diffuseColor.b));\n if (rm > " + ROD_KNEE.toFixed(2) + ") {\n float rc = " + ROD_KNEE.toFixed(2) + " + " + (ROD_MAX - ROD_KNEE).toFixed(2) + " * tanh(min((rm - " + ROD_KNEE.toFixed(2) + ") / " + (ROD_MAX - ROD_KNEE).toFixed(2) + ", 12.0));\n // (only a SATURATED rod is held back: a pale one, like the stock blue whose brightness is light added to all three channels, is already a hot core and keeps its full power)\n float rs = smoothstep(0.62, 0.85, (rm - min(diffuseColor.r, min(diffuseColor.g, diffuseColor.b))) / rm);\n diffuseColor.rgb = mix(diffuseColor.rgb, mix(diffuseColor.rgb * (rc / rm), vec3(rc), " + ROD_WHITE.toFixed(2) + " * smoothstep(" + ROD_KNEE.toFixed(2) + ", 3.0, rm)), rs);\n }");
1202
+ };
1203
+ glowMaterial.customProgramCacheKey = () => "rod-levels";
1204
+ const paint = (g, col, glow = 0, shade = false) => {
1205
+ const n2 = g.getAttribute("position").count;
1206
+ const colors = new Float32Array(n2 * 3);
1207
+ const pos = g.getAttribute("position");
1208
+ const nor = g.getAttribute("normal");
1209
+ let y0 = Infinity;
1210
+ let y1 = -Infinity;
1211
+ if (shade) for (let i = 0; i < n2; i++) {
1212
+ y0 = Math.min(y0, pos.getY(i));
1213
+ y1 = Math.max(y1, pos.getY(i));
1214
+ }
1215
+ for (let i = 0; i < n2; i++) {
1216
+ col.toArray(colors, i * 3);
1217
+ if (!shade || !nor) continue;
1218
+ const nx = nor.getX(i);
1219
+ const ny = nor.getY(i);
1220
+ const nz = nor.getZ(i);
1221
+ const face = 0.5 + 0.62 * Math.max(0, ny) + 0.3 * Math.max(0, -nx) + 0.08 * Math.max(0, -nz);
1222
+ const foot = 0.7 + 0.3 * (y1 > y0 ? (pos.getY(i) - y0) / (y1 - y0) : 1);
1223
+ const k = face * foot;
1224
+ colors[i * 3] = colors[i * 3] * k;
1225
+ colors[i * 3 + 1] = colors[i * 3 + 1] * k;
1226
+ colors[i * 3 + 2] = colors[i * 3 + 2] * k;
1227
+ }
1228
+ g.setAttribute("color", new THREE.BufferAttribute(colors, 3));
1229
+ g.setAttribute("aGlow", new THREE.BufferAttribute(new Float32Array(n2).fill(glow), 1));
1230
+ g.deleteAttribute("uv");
1231
+ };
1232
+ const GLOW_PAD = 9;
1233
+ const GROUND_REACH = 1.75;
1234
+ const GROUND_LIGHT = 0.5;
1235
+ const POOL = 0.15;
1236
+ const CAUSTIC_NEAR = 7;
1237
+ const CAUSTIC_FAR = 18;
1238
+ const CAUSTIC_POWER = 0.055;
1239
+ const ABSORB = 2.6;
1240
+ const LIGHT_CAUSTIC = 1;
1241
+ const STRAIGHT = 0.92;
1242
+ const SHADOW = 0.72;
1243
+ const SHADE_SATURATION = 2.4;
1244
+ const LIGHT_SHADOW_DEPTH = 0.45;
1245
+ const GLEAM = 4.8;
1246
+ const NOISE_FLOOR = 0.03;
1247
+ const GLEAM_MAX = 0.8;
1248
+ const SUN_NEAR = 3.4;
1249
+ const SUN_FAR = 6;
1250
+ const PX = 22;
1251
+ const LPX = PX / 2;
1252
+ let neonNeighbours = [];
1253
+ let neonBlocks = [];
1254
+ let stampCtl = null;
1255
+ let pitLight = null;
1256
+ let rimLight = null;
1257
+ const customOn = () => !!opts.rodColor && isDark();
1258
+ const WHITE_ROD = 0.62;
1259
+ const customHue = (cell, src, t) => {
1260
+ const rgb = opts.rodColor({ layer: src, index: cell, date: layout.top.cells[cell].date, t });
1261
+ return rgb ? new THREE.Color(rgb[0], rgb[1], rgb[2]) : null;
1262
+ };
1263
+ const groundLayers = (stack2, tones, dark) => {
1264
+ const cw = Math.ceil((width + GLOW_PAD * 2) * PX);
1265
+ const ch = Math.ceil((total + GLOW_PAD * 2) * PX);
1266
+ const lw = Math.ceil((width + GLOW_PAD * 2) * LPX);
1267
+ const lh = Math.ceil((total + GLOW_PAD * 2) * LPX);
1268
+ const canvas = () => {
1269
+ const c2 = document.createElement("canvas");
1270
+ c2.width = cw;
1271
+ c2.height = ch;
1272
+ return c2;
1273
+ };
1274
+ const ao = canvas();
1275
+ const actx = ao.getContext("2d");
1276
+ const occlude = (x, z, height, tint = "0,0,0") => {
1277
+ const cx = (x + GLOW_PAD) * PX;
1278
+ const cy = (z + GLOW_PAD) * PX;
1279
+ const r = (0.75 + 0.22 * height) * PX;
1280
+ const g = actx.createRadialGradient(cx, cy, 0.3 * PX, cx, cy, r);
1281
+ const a = Math.min(0.85, (dark ? 0.5 : 0.28) + 0.06 * height);
1282
+ g.addColorStop(0, `rgba(${tint},${a})`);
1283
+ g.addColorStop(0.5, `rgba(${tint},${a * 0.4})`);
1284
+ g.addColorStop(1, `rgba(${tint},0)`);
1285
+ actx.fillStyle = g;
1286
+ actx.fillRect(cx - r, cy - r, r * 2, r * 2);
1287
+ };
1288
+ const pitCells = [];
1289
+ const recess = (x, z, lx, lz, amount, ctx2 = actx) => {
1290
+ const cx = (x + GLOW_PAD) * PX;
1291
+ const cy = (z + GLOW_PAD) * PX;
1292
+ const half = 0.44 * PX;
1293
+ const rr = 0.16 * PX;
1294
+ const path = new Path2D();
1295
+ path.roundRect(cx - half, cy - half, half * 2, half * 2, rr);
1296
+ const frame2 = new Path2D();
1297
+ frame2.rect(cx - 2 * PX, cy - 2 * PX, 4 * PX, 4 * PX);
1298
+ frame2.addPath(path);
1299
+ ctx2.save();
1300
+ ctx2.clip(path);
1301
+ ctx2.shadowColor = `rgba(0,0,0,${dark ? 0.9 : 0.5})`;
1302
+ ctx2.shadowBlur = 0.16 * PX;
1303
+ ctx2.shadowOffsetX = -lx * amount * 0.09 * PX;
1304
+ ctx2.shadowOffsetY = -lz * amount * 0.09 * PX;
1305
+ ctx2.fillStyle = "#000";
1306
+ ctx2.fill(frame2, "evenodd");
1307
+ ctx2.restore();
1308
+ };
1309
+ stack2.top.cells.forEach((g, i) => {
1310
+ const w2 = stack2.bottom.cells[i];
1311
+ const { x, z } = at(g.week, g.day);
1312
+ if (w2.value > 0 || g.value > 0) {
1313
+ let tint = "0,0,0";
1314
+ if (!dark) {
1315
+ const ww = w2.value > 0 ? 0.18 + w2.t * LAYER_MAX : 0;
1316
+ const wg = g.value > 0 ? 0.18 + g.t * LAYER_MAX : 0;
1317
+ const c = tones.bottom[1].clone().multiplyScalar(ww).add(tones.top[1].clone().multiplyScalar(wg)).multiplyScalar(1 / (ww + wg));
1318
+ const m = Math.max(c.r, c.g, c.b, 1e-3);
1319
+ const deep = c.clone().multiplyScalar(LIGHT_SHADOW_DEPTH / m);
1320
+ tint = [deep.r, deep.g, deep.b].map((v) => Math.round(255 * Math.min(1, v) ** (1 / 2.2))).join(",");
1321
+ }
1322
+ occlude(x, z, (w2.value > 0 ? 0.18 + w2.t * LAYER_MAX : 0) + (g.value > 0 ? 0.18 + g.t * LAYER_MAX : 0), tint);
1323
+ } else pitCells.push({ x, z });
1324
+ });
1325
+ const t02 = performance.now();
1326
+ const glass = [];
1327
+ neonBlocks = [];
1328
+ const variety = /* @__PURE__ */ (() => {
1329
+ let seed = 987654;
1330
+ return () => (seed = seed * 16807 % 2147483647) / 2147483647;
1331
+ })();
1332
+ stack2.top.cells.forEach((g, i) => {
1333
+ const w2 = stack2.bottom.cells[i];
1334
+ const { x, z } = at(g.week, g.day);
1335
+ let top = 0;
1336
+ const add = (src, y0, y1, t, [low, high], gain) => {
1337
+ const hy = (y1 - y0) / 2;
1338
+ const hue = (customOn() ? customHue(i, src, t) : null) ?? low.clone().lerp(high, t);
1339
+ const rod = customOn() ? (
1340
+ // (`rodColor`: the light on the ground is the light's own colour, not lifted toward white as a busy rod is in the usual picture)
1341
+ hue.clone()
1342
+ ) : rodLight(src, hue, t, 1);
1343
+ const peak = Math.max(rod.r, rod.g, rod.b) * (customOn() ? 0.55 : 1);
1344
+ const col = dark ? rod.multiplyScalar(1 / Math.max(1e-4, rod.r, rod.g, rod.b)) : hue;
1345
+ const whiteLight = customOn() && Math.max(hue.r, hue.g, hue.b) - Math.min(hue.r, hue.g, hue.b) < 0.15 * Math.max(hue.r, hue.g, hue.b) ? 0.5 : 1;
1346
+ const tilt = () => (variety() - 0.5) * 0.22;
1347
+ const luck = 0.6 + 0.8 * variety();
1348
+ const near = dark ? CAUSTIC_NEAR : SUN_NEAR;
1349
+ const far = dark ? CAUSTIC_FAR : SUN_FAR;
1350
+ neonBlocks.push({
1351
+ x,
1352
+ z,
1353
+ // (the camera looks along -z, so the world's +x is on the LEFT of the screen: the stereo place is the other way round)
1354
+ pan: 1 - x / width * 2,
1355
+ t,
1356
+ cell: i,
1357
+ peak
1358
+ });
1359
+ glass.push({
1360
+ c: [x, y0 + hy, z],
1361
+ h: [0.46, hy, 0.46],
1362
+ r: Math.min(0.16, 2 * hy / 2.2),
1363
+ bias: [tilt(), tilt() * 0.4, tilt()],
1364
+ col: [col.r, col.g, col.b],
1365
+ power: (0.05 + t * t) * gain * luck * CAUSTIC_POWER * whiteLight,
1366
+ near,
1367
+ far,
1368
+ // (the rod, as drawn: its width)
1369
+ rod: (0.5 - 0.2 * t ** 0.85) / 2,
1370
+ seed: [variety(), variety(), variety(), variety(), variety()],
1371
+ // (the soft pool: a haze under the block, as bright as its day was busy; it goes out with its rod)
1372
+ pool: (() => {
1373
+ const peak2 = POOL * GROUND_LIGHT * gain * (4e-3 + 0.26 * t * t + 0.03 * t) * whiteLight;
1374
+ return { col: [hue.r * peak2, hue.g * peak2, hue.b * peak2], r: 0.9 + GROUND_REACH * (0.5 + t * 1.5) };
1375
+ })()
1376
+ });
1377
+ };
1378
+ if (w2.value > 0) {
1379
+ add("bottom", 0, 0.18 + w2.t * LAYER_MAX, w2.t, tones.bottom, 1);
1380
+ top = 0.18 + w2.t * LAYER_MAX + 0.04;
1381
+ }
1382
+ if (g.value > 0) add("top", top, top + 0.18 + g.t * LAYER_MAX, g.t, tones.top, 1.8);
1383
+ });
1384
+ const ground2 = dark ? createGroundLight(THREE, renderer, { w: cw, h: ch, scale: PX, x0: -GLOW_PAD, z0: -GLOW_PAD }) : createGroundLight(THREE, renderer, { w: lw, h: lh, scale: LPX, x0: -GLOW_PAD, z0: -GLOW_PAD });
1385
+ if (dark) {
1386
+ stampCtl = !templates ? null : ground2.stamps(
1387
+ glass.map((g) => ({ x: g.c[0], z: g.c[2], height: 2 * g.h[1], foot: g.c[1] - g.h[1], col: [g.col[0] * g.power, g.col[1] * g.power, g.col[2] * g.power], poolCol: g.pool.col, poolRadius: g.pool.r })),
1388
+ templates
1389
+ );
1390
+ } else {
1391
+ const sunDir = new THREE.Vector3().copy(sunBase).normalize().negate();
1392
+ ground2.sun(glass, lite ? 40 : 64, [sunDir.x, sunDir.y, sunDir.z], ABSORB, STRAIGHT, LPX * LPX / -sunDir.y);
1393
+ ground2.smooth(3);
1394
+ }
1395
+ if (dbg.metrics) console.info(`[activity] ground light drawn in ${Math.round(performance.now() - t02)} ms (${dark ? "dark" : "light"}, ${glass.length} blocks)`);
1396
+ const layers = new THREE.Group();
1397
+ const disposers = [];
1398
+ const plane = (tex, material, order) => {
1399
+ const mat = material(tex);
1400
+ const mesh = new THREE.Mesh(new THREE.PlaneGeometry(cw / PX, ch / PX), mat);
1401
+ mesh.rotation.x = -Math.PI / 2;
1402
+ mesh.position.set(width / 2, 0.11 + order * 2e-3, total / 2);
1403
+ mesh.renderOrder = order;
1404
+ layers.add(mesh);
1405
+ disposers.push(() => {
1406
+ tex.dispose();
1407
+ mat.dispose();
1408
+ });
1409
+ };
1410
+ if (dark) plane(ground2.texture, (map) => new THREE.MeshBasicMaterial({ map, transparent: true, blending: THREE.AdditiveBlending, depthWrite: false, toneMapped: false }), 1);
1411
+ else {
1412
+ const resolve = (shade) => new THREE.ShaderMaterial({
1413
+ uniforms: { map: { value: ground2.texture } },
1414
+ vertexShader: "varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }",
1415
+ fragmentShader: `uniform sampler2D map; varying vec2 vUv;
1416
+ void main() {
1417
+ vec3 v = texture2D(map, vUv).rgb;
1418
+ // (the differences of overlapping shadows are summed, but light that has been through two blocks has lost the share of each, not both shares: the product, which the exponential of the sum is) (below a small difference there is only the noise of the rays: it is not light)
1419
+ vec3 f = exp(${(LIGHT_CAUSTIC * 1.2).toFixed(3)} * sign(v) * max(abs(v) - ${NOISE_FLOOR.toFixed(3)}, 0.));
1420
+ ${shade ? `vec3 d = 1. - min(f, vec3(1.)); d = max(vec3(0.), mix(vec3(dot(d, vec3(0.3333))), d, ${SHADE_SATURATION.toFixed(2)})); gl_FragColor = vec4(vec3(1. - ${SHADOW.toFixed(3)} * min(d, vec3(1.))), 1.);` : `vec3 g = max(f - 1., 0.) * ${GLEAM.toFixed(3)}; gl_FragColor = vec4(${GLEAM_MAX.toFixed(3)} * tanh(min(g / ${GLEAM_MAX.toFixed(3)}, vec3(12.))), 1.);`}
1421
+ }`,
1422
+ transparent: true,
1423
+ blending: shade ? THREE.MultiplyBlending : THREE.AdditiveBlending,
1424
+ premultipliedAlpha: shade,
1425
+ depthWrite: false
1426
+ });
1427
+ plane(ground2.texture, () => resolve(true), 0);
1428
+ plane(ground2.texture, () => resolve(false), 1);
1429
+ }
1430
+ const aoSym = dark ? canvas() : null;
1431
+ aoSym?.getContext("2d").drawImage(ao, 0, 0);
1432
+ const pitNear = [];
1433
+ const pitBase = [];
1434
+ const pitStrength = [];
1435
+ const amountOf = (lxv, lzv, st2) => Math.min(1, Math.hypot(lxv, lzv) / Math.max(st2, 1e-6) * 1.4) * Math.min(1, st2 * 6);
1436
+ for (const pc of pitCells) {
1437
+ let lx = 0;
1438
+ let lz = 0;
1439
+ let strength = 0;
1440
+ const near = [];
1441
+ if (dark) {
1442
+ glass.forEach((g, gi) => {
1443
+ const dx = g.c[0] - pc.x;
1444
+ const dz = g.c[2] - pc.z;
1445
+ const dist = Math.hypot(dx, dz);
1446
+ if (dist < 0.5 || dist > 5) return;
1447
+ const w2 = (g.col[0] + g.col[1] + g.col[2]) * g.power * Math.exp(-(dist * dist) / (2 * 1.8 * 1.8));
1448
+ lx += dx / dist * w2;
1449
+ lz += dz / dist * w2;
1450
+ strength += w2;
1451
+ near.push({ gi, wx: dx / dist * w2, wz: dz / dist * w2, w: w2 });
1452
+ });
1453
+ } else {
1454
+ lx = -0.63;
1455
+ lz = 0.77;
1456
+ strength = 1;
1457
+ }
1458
+ const len = Math.hypot(lx, lz);
1459
+ const amount = dark ? amountOf(lx, lz, strength) : 1;
1460
+ recess(pc.x, pc.z, len > 0 ? lx / len : 0, len > 0 ? lz / len : 0, amount);
1461
+ if (aoSym) recess(pc.x, pc.z, 0, 0, 0, aoSym.getContext("2d"));
1462
+ pitNear.push(near);
1463
+ pitBase.push(amount);
1464
+ pitStrength.push(strength);
1465
+ }
1466
+ const aoTex = new THREE.CanvasTexture(ao);
1467
+ aoTex.colorSpace = THREE.SRGBColorSpace;
1468
+ if (!aoSym) plane(aoTex, (map) => new THREE.MeshBasicMaterial({ map, transparent: true, depthWrite: false, toneMapped: false }), 2);
1469
+ else {
1470
+ const symTex = new THREE.CanvasTexture(aoSym);
1471
+ symTex.colorSpace = THREE.SRGBColorSpace;
1472
+ const LT = 4;
1473
+ const litW = Math.ceil(cw / PX * LT);
1474
+ const litH = Math.ceil(ch / PX * LT);
1475
+ const litData = new Float32Array(litW * litH).fill(1);
1476
+ const litTex = new THREE.DataTexture(litData, litW, litH, THREE.RedFormat, THREE.FloatType);
1477
+ litTex.minFilter = THREE.NearestFilter;
1478
+ litTex.magFilter = THREE.NearestFilter;
1479
+ litTex.needsUpdate = true;
1480
+ plane(aoTex, (map) => {
1481
+ const m = new THREE.ShaderMaterial({
1482
+ uniforms: { full: { value: map }, sym: { value: symTex }, lit: { value: litTex } },
1483
+ vertexShader: "varying vec2 vUv; void main() { vUv = uv; gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.); }",
1484
+ fragmentShader: "uniform sampler2D full; uniform sampler2D sym; uniform sampler2D lit; varying vec2 vUv; void main() { float a = mix(texture2D(sym, vUv).a, texture2D(full, vUv).a, clamp(texture2D(lit, vUv).r, 0., 1.)); gl_FragColor = vec4(0., 0., 0., a); }",
1485
+ transparent: true,
1486
+ depthWrite: false
1487
+ });
1488
+ return m;
1489
+ }, 2);
1490
+ disposers.push(() => {
1491
+ symTex.dispose();
1492
+ litTex.dispose();
1493
+ });
1494
+ layers.userData.setLevels = (levels) => {
1495
+ for (let k = 0; k < pitCells.length; k++) {
1496
+ let lx = 0;
1497
+ let lz = 0;
1498
+ let st2 = 0;
1499
+ for (const n2 of pitNear[k]) {
1500
+ const lv = levels[n2.gi] ?? 1;
1501
+ lx += n2.wx * lv;
1502
+ lz += n2.wz * lv;
1503
+ st2 += n2.w * lv;
1504
+ }
1505
+ const lit = pitBase[k] > 1e-4 && pitStrength[k] > 1e-6 ? Math.min(1, amountOf(lx, lz, st2) / pitBase[k] * Math.min(1, st2 / pitStrength[k])) : 0;
1506
+ const u = pitCells[k].x + GLOW_PAD;
1507
+ const v = pitCells[k].z + GLOW_PAD;
1508
+ const i0 = Math.max(0, Math.floor((u - 0.44) * LT));
1509
+ const i1 = Math.min(litW - 1, Math.floor((u + 0.44) * LT));
1510
+ const j0 = Math.max(0, litH - 1 - Math.floor((v + 0.44) * LT));
1511
+ const j1 = Math.min(litH - 1, litH - 1 - Math.floor((v - 0.44) * LT));
1512
+ for (let jj = j0; jj <= j1; jj++) for (let ii = i0; ii <= i1; ii++) litData[jj * litW + ii] = lit;
1513
+ }
1514
+ litTex.needsUpdate = true;
1515
+ };
1516
+ }
1517
+ disposers.push(() => ground2.dispose());
1518
+ if (!dark && LIGHT_BACKDROP) {
1519
+ const sizeX = cw / PX;
1520
+ const sizeZ = ch / PX;
1521
+ const bakeW = Math.min(2048, Math.ceil(sizeX * 48));
1522
+ const bakeH = Math.min(2048, Math.ceil(sizeZ / sizeX * bakeW));
1523
+ const bake = new THREE.WebGLRenderTarget(bakeW, bakeH, { type: THREE.HalfFloatType, depthBuffer: false });
1524
+ const cam = new THREE.OrthographicCamera(-sizeX / 2, sizeX / 2, sizeZ / 2, -sizeZ / 2, 0.1, 20);
1525
+ cam.up.set(0, 0, -1);
1526
+ cam.position.set(width / 2, 5, total / 2);
1527
+ cam.lookAt(width / 2, 0, total / 2);
1528
+ const bakeScene = new THREE.Scene();
1529
+ bakeScene.add(layers);
1530
+ const prevTarget = renderer.getRenderTarget();
1531
+ const prevClear = renderer.getClearColor(new THREE.Color());
1532
+ const prevAlpha = renderer.getClearAlpha();
1533
+ renderer.setRenderTarget(bake);
1534
+ renderer.setClearColor(pageColour(), 1);
1535
+ renderer.clear();
1536
+ renderer.render(bakeScene, cam);
1537
+ renderer.setRenderTarget(prevTarget);
1538
+ renderer.setClearColor(prevClear, prevAlpha);
1539
+ bakeScene.remove(layers);
1540
+ const uBackdrop = { value: 0 };
1541
+ const proxyMat = new THREE.MeshBasicMaterial({ map: bake.texture, toneMapped: false });
1542
+ proxyMat.onBeforeCompile = (shader) => {
1543
+ shader.uniforms.uBackdrop = uBackdrop;
1544
+ shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nuniform float uBackdrop;").replace("void main() {", "void main() {\n if (uBackdrop < 0.5) discard;");
1545
+ };
1546
+ proxyMat.customProgramCacheKey = () => "ground-backdrop";
1547
+ const proxy = new THREE.Mesh(new THREE.PlaneGeometry(sizeX, sizeZ), proxyMat);
1548
+ proxy.rotation.x = -Math.PI / 2;
1549
+ proxy.position.set(width / 2, 0.01, total / 2);
1550
+ proxy.onBeforeRender = (r) => {
1551
+ uBackdrop.value = r.getRenderTarget() === sceneRT ? 0 : 1;
1552
+ };
1553
+ proxy.frustumCulled = false;
1554
+ layers.add(proxy);
1555
+ disposers.push(() => {
1556
+ bake.dispose();
1557
+ proxyMat.dispose();
1558
+ proxy.geometry.dispose();
1559
+ });
1560
+ }
1561
+ if (dark && DARK_BACKDROP) {
1562
+ const uBackdrop = { value: 0 };
1563
+ const page = pageColour();
1564
+ const proxyMat = new THREE.MeshBasicMaterial({ map: ground2.texture, toneMapped: false });
1565
+ proxyMat.onBeforeCompile = (shader) => {
1566
+ shader.uniforms.uBackdrop = uBackdrop;
1567
+ shader.uniforms.uPage = { value: page };
1568
+ shader.uniforms.uDim = backdropDim;
1569
+ shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nuniform float uBackdrop;\nuniform float uDim;\nuniform vec3 uPage;").replace("void main() {", softSeen + "\nvoid main() {\n if (uBackdrop < 0.5) discard;").replace("#include <opaque_fragment>", `outgoingLight = uPage + uDim * softSeen(outgoingLight);
1570
+ #include <opaque_fragment>`);
1571
+ };
1572
+ proxyMat.customProgramCacheKey = () => "ground-backdrop-dark";
1573
+ const proxy = new THREE.Mesh(new THREE.PlaneGeometry(cw / PX, ch / PX), proxyMat);
1574
+ proxy.rotation.x = -Math.PI / 2;
1575
+ proxy.position.set(width / 2, 0.01, total / 2);
1576
+ proxy.onBeforeRender = (r) => {
1577
+ uBackdrop.value = r.getRenderTarget() === sceneRT ? 0 : 1;
1578
+ };
1579
+ proxy.frustumCulled = false;
1580
+ layers.add(proxy);
1581
+ disposers.push(() => {
1582
+ proxyMat.dispose();
1583
+ proxy.geometry.dispose();
1584
+ });
1585
+ }
1586
+ layers.userData.dispose = () => disposers.forEach((d) => d());
1587
+ return layers;
1588
+ };
1589
+ const LAYER_MAX = 2.3;
1590
+ const roundedSquare = (() => {
1591
+ const half = 0.46;
1592
+ const r = 0.16;
1593
+ const sh = new THREE.Shape();
1594
+ sh.moveTo(-half + r, -half);
1595
+ sh.lineTo(half - r, -half);
1596
+ sh.absarc(half - r, -half + r, r, -Math.PI / 2, 0, false);
1597
+ sh.lineTo(half, half - r);
1598
+ sh.absarc(half - r, half - r, r, 0, Math.PI / 2, false);
1599
+ sh.lineTo(-half + r, half);
1600
+ sh.absarc(-half + r, half - r, r, Math.PI / 2, Math.PI, false);
1601
+ sh.lineTo(-half, -half + r);
1602
+ sh.absarc(-half + r, -half + r, r, Math.PI, Math.PI * 1.5, false);
1603
+ return sh;
1604
+ })();
1605
+ let tallest = 1;
1606
+ const boxes = /* @__PURE__ */ new Map();
1607
+ const roundedBox = (w2, h2, d, seg, r) => {
1608
+ const key = `${w2.toFixed(4)}|${h2.toFixed(4)}|${d.toFixed(4)}|${seg}|${r.toFixed(4)}`;
1609
+ let g = boxes.get(key);
1610
+ if (!g) boxes.set(key, g = new RoundedBoxGeometry(w2, h2, d, seg, r));
1611
+ return g.clone();
1612
+ };
1613
+ const stock = { top: true, bottom: true };
1614
+ const lum = (c) => 0.2126 * c.r + 0.7152 * c.g + 0.0722 * c.b;
1615
+ const stockRod = (src, hue, t, level) => src === "bottom" ? hue.clone().multiplyScalar(level * (0.5 + 0.45 * (1 - t) ** 2)).add(new THREE.Color(0.4, 0.56, 0.6).multiplyScalar(level * (0.06 + 1.32 * t * t))) : hue.clone().multiplyScalar(level * 1.25).add(new THREE.Color(0.22, 0.4, 0.24).multiplyScalar(level * (0.05 + 0.8 * t * t)));
1616
+ const rodLight = (src, hue, t, level) => {
1617
+ if (stock[src]) return stockRod(src, hue, t, level);
1618
+ const [dl, dh] = DEFAULT_COLORS[src].dark;
1619
+ const ref = stockRod(src, new THREE.Color(dl).lerp(new THREE.Color(dh), t), t, level);
1620
+ const k = Math.min(lum(ref) / Math.max(lum(hue), 1e-3), Math.max(ref.r, ref.g, ref.b) / Math.max(hue.r, hue.g, hue.b, 1e-3));
1621
+ return hue.clone().multiplyScalar(k);
1622
+ };
1623
+ let bounds = null;
1624
+ api.bounds = () => bounds;
1625
+ let picks = [];
1626
+ const LIFT = 0.04;
1627
+ const build = (stack2, tones, dark) => {
1628
+ const tb0 = performance.now();
1629
+ picks = [];
1630
+ let tileShape = null;
1631
+ let ringShape0 = null;
1632
+ const rims = [];
1633
+ const pitRims = [];
1634
+ const pitLamps = [];
1635
+ const page = pageColour();
1636
+ const shellsBy = /* @__PURE__ */ new Map();
1637
+ const shellHue = /* @__PURE__ */ new Map();
1638
+ const shellTier = /* @__PURE__ */ new Map();
1639
+ const cores = [];
1640
+ const tiles = [];
1641
+ const specs = [];
1642
+ const emit = (t) => 1.3 * (0.3 + 0.1 * (1 - t) ** 3 + 1.3 * t * t + 0.4 * t);
1643
+ const layer = (cell, src, x, z, y0, t, [low, high]) => {
1644
+ const h2 = 0.18 + t * LAYER_MAX;
1645
+ picks.push({ cell, x, z, y0, y1: y0 + h2 });
1646
+ specs.push({ src, x, z, y0, h: h2, t, hue: (customOn() ? customHue(cell, src, t) : null) ?? low.clone().lerp(high, t) });
1647
+ tallest = Math.max(tallest, y0 + h2);
1648
+ return y0 + h2;
1649
+ };
1650
+ stack2.top.cells.forEach((g, i) => {
1651
+ const w2 = stack2.bottom.cells[i];
1652
+ const { x, z } = at(g.week, g.day);
1653
+ if (w2.value <= 0 && g.value <= 0) {
1654
+ if (!tileShape) {
1655
+ const PIT = 0.07;
1656
+ const BEVEL = 0.025;
1657
+ const g2 = new THREE.ExtrudeGeometry(roundedSquare, { depth: PIT, bevelEnabled: true, bevelSize: BEVEL, bevelThickness: BEVEL, bevelSegments: lite ? 1 : 3, curveSegments: lite ? 3 : 6 });
1658
+ g2.rotateX(-Math.PI / 2);
1659
+ g2.deleteAttribute("uv");
1660
+ g2.translate(0, -(PIT + BEVEL), 0);
1661
+ const pos = g2.getAttribute("position");
1662
+ const col = new Float32Array(pos.count * 3);
1663
+ const floor2 = dark ? page.clone().multiplyScalar(0.3) : page.clone().multiplyScalar(0.8);
1664
+ const wall = dark ? page.clone().add(new THREE.Color(0.012, 0.013, 0.016)) : page.clone().multiplyScalar(0.97);
1665
+ const c3 = new THREE.Color();
1666
+ for (let q = 0; q < pos.count; q++) {
1667
+ const d = Math.min(1, Math.max(0, -pos.getY(q) / (PIT + BEVEL)));
1668
+ c3.copy(wall).lerp(floor2, d * d);
1669
+ c3.toArray(col, q * 3);
1670
+ }
1671
+ g2.setAttribute("color", new THREE.BufferAttribute(col, 3));
1672
+ tileShape = g2;
1673
+ const outer = roundedSquare.getPoints(lite ? 3 : 6);
1674
+ const ringShape = new THREE.Shape(outer.map((v) => v.clone().multiplyScalar(1.05)));
1675
+ ringShape.holes.push(new THREE.Path(outer.map((v) => v.clone().multiplyScalar(0.955)).reverse()));
1676
+ const ring = new THREE.ShapeGeometry(ringShape);
1677
+ ring.rotateX(-Math.PI / 2);
1678
+ ring.translate(0, 4e-3, 0);
1679
+ ring.deleteAttribute("uv");
1680
+ const rp = ring.getAttribute("position");
1681
+ const rc = new Float32Array(rp.count * 3);
1682
+ for (let q = 0; q < rp.count; q++) {
1683
+ const rx = rp.getX(q);
1684
+ const rz = rp.getZ(q);
1685
+ const rl = Math.hypot(rx, rz) || 1;
1686
+ const w3 = Math.pow(Math.max(0, rx / rl), 3) + 0.3 * Math.pow(Math.max(0, -rz / rl), 3);
1687
+ if (dark) c3.copy(page).add(new THREE.Color(0.024, 0.026, 0.034).multiplyScalar(Math.min(1, w3)));
1688
+ else c3.copy(page).lerp(new THREE.Color(1, 1, 1), 0.3 * Math.min(1, w3));
1689
+ c3.toArray(rc, q * 3);
1690
+ }
1691
+ ring.setAttribute("color", new THREE.BufferAttribute(rc, 3));
1692
+ ringShape0 = ring;
1693
+ }
1694
+ const tile = tileShape.clone();
1695
+ tile.translate(x, 0, z);
1696
+ tiles.push(tile);
1697
+ const rim = ringShape0.clone();
1698
+ rim.translate(x, 0, z);
1699
+ rims.push(rim);
1700
+ pitRims.push({ geom: rim, x, z });
1701
+ picks.push({ cell: i, x, z, y0: 0, y1: 0.04, pit: true });
1702
+ return;
1703
+ }
1704
+ let y = 0;
1705
+ if (w2.value > 0) y = layer(i, "bottom", x, z, 0, w2.t, tones.bottom) + LIFT;
1706
+ if (g.value > 0) layer(i, "top", x, z, y, g.t, tones.top);
1707
+ });
1708
+ let blockIndex = 0;
1709
+ neonNeighbours = [];
1710
+ const shades = dark ? glassShades(specs.map((q) => ({ x: q.x, z: q.z, y0: q.y0, h: q.h })), GLASS_ABSORB, GLASS_FLOOR) : [];
1711
+ const shadeOf = new Map(specs.map((q, k) => [q, shades[k] ?? 1]));
1712
+ const glowOf = /* @__PURE__ */ new Map();
1713
+ if (dark) {
1714
+ const bright = specs.map((q) => {
1715
+ const lv = Math.max(emit(q.t) * (1 + 1.1 * q.t), q.src === "top" ? GREEN_MIN_LEVEL : 0);
1716
+ const r = customOn() ? q.hue.clone().multiplyScalar(lv * 0.55) : rodLight(q.src, q.hue, q.t, lv);
1717
+ return Math.max(r.r, r.g, r.b);
1718
+ });
1719
+ const behind = lightBehind(specs.map((q) => ({ x: q.x, z: q.z, y0: q.y0, h: q.h })), bright);
1720
+ specs.forEach((q, k) => {
1721
+ const own = Math.min(1, Math.max(0, (bright[k] - 0.5) / 1.5));
1722
+ glowOf.set(q, (1 - Math.exp(-(behind[k] ?? 0) / BEHIND_SCALE)) * (1 - own * own * (3 - 2 * own)));
1723
+ });
1724
+ }
1725
+ const behindTint = /* @__PURE__ */ new Map();
1726
+ if (!dark && !LIGHT_DOUBLE_SIDED) {
1727
+ const boxes2 = specs.map((q) => ({ x: q.x, z: q.z, y0: q.y0, h: q.h }));
1728
+ const cover = lightBehind(boxes2, specs.map(() => 1));
1729
+ const chans = [0, 1, 2].map((c) => lightBehind(boxes2, specs.map((q) => [q.hue.r, q.hue.g, q.hue.b][c])));
1730
+ specs.forEach((q, k) => {
1731
+ const cv = cover[k] ?? 0;
1732
+ if (cv < 1e-3) return;
1733
+ const mean = new THREE.Color(chans[0][k] / cv, chans[1][k] / cv, chans[2][k] / cv);
1734
+ behindTint.set(q, new THREE.Color(1, 1, 1).lerp(mean, Math.min(1, cv) * LIGHT_BEHIND_TINT));
1735
+ });
1736
+ }
1737
+ for (const sp of specs) {
1738
+ const { src, x, z, y0, h: h2, t, hue: hue0 } = sp;
1739
+ let hue = hue0;
1740
+ const inc = new THREE.Color(0, 0, 0);
1741
+ const nb = { j: [], m: [] };
1742
+ if (dark) {
1743
+ for (let oi = 0; oi < specs.length; oi++) {
1744
+ const o = specs[oi];
1745
+ if (o === sp) continue;
1746
+ const dx = o.x - x;
1747
+ const dz = o.z - z;
1748
+ if (Math.abs(dx) > 4 || Math.abs(dz) > 4) continue;
1749
+ const dy = o.y0 + o.h / 2 - (y0 + h2 / 2);
1750
+ const k = Math.exp(-(dx * dx + dz * dz + dy * dy) / (2 * 1.2 * 1.2)) * 0.11;
1751
+ inc.add(o.hue.clone().multiplyScalar(emit(o.t) * k));
1752
+ nb.j.push(oi);
1753
+ nb.m.push(emit(o.t) * k * (o.hue.r + o.hue.g + o.hue.b));
1754
+ }
1755
+ }
1756
+ neonNeighbours.push(nb);
1757
+ if (dark && customOn() && Math.max(hue.r, hue.g, hue.b) - Math.min(hue.r, hue.g, hue.b) < 0.15 * Math.max(hue.r, hue.g, hue.b)) {
1758
+ const m = Math.max(inc.r, inc.g, inc.b);
1759
+ if (m > 1e-4) hue = hue.clone().lerp(inc.clone().multiplyScalar(1 / m).multiplyScalar(Math.max(hue.r, hue.g, hue.b)), Math.min(0.75, m * 3));
1760
+ }
1761
+ inc.r = Math.min(inc.r, 0.6);
1762
+ inc.g = Math.min(inc.g, 0.6);
1763
+ inc.b = Math.min(inc.b, 0.6);
1764
+ const incLum = (inc.r + inc.g + inc.b) / 3;
1765
+ const tEff = t + (1 - t) * Math.min(1, Math.sqrt(incLum * 1.2));
1766
+ const shell = roundedBox(0.92, h2, 0.92, lite ? 2 : 3, Math.min(0.16, h2 / 2.2));
1767
+ shell.translate(x, y0 + h2 / 2, z);
1768
+ paint(shell, (dark ? new THREE.Color(16777215) : hue.clone().lerp(new THREE.Color(16777215), LIGHT_SHELL_WHITE).multiply(behindTint.get(sp) ?? new THREE.Color(1, 1, 1))).add(inc.clone().multiplyScalar(dark && customOn() ? 0.35 : 0.08)), 0, dark);
1769
+ shell.setAttribute("aBlock", new THREE.BufferAttribute(new Float32Array(shell.getAttribute("position").count).fill(blockIndex), 1));
1770
+ const nbShare = glowOf.get(sp) ?? 0;
1771
+ const glowTint = (() => {
1772
+ const m = Math.max(hue0.r, hue0.g, hue0.b, 1e-3);
1773
+ return new THREE.Color(1, 1, 1).lerp(new THREE.Color(hue0.r / m, hue0.g / m, hue0.b / m), GLOW_TINT);
1774
+ })();
1775
+ const vcount = shell.getAttribute("position").count;
1776
+ shell.setAttribute("aInc", new THREE.BufferAttribute(Float32Array.from({ length: vcount * 3 }, (_, k) => [inc.r, inc.g, inc.b][k % 3] * nbShare), 3));
1777
+ shell.setAttribute("aTint", new THREE.BufferAttribute(Float32Array.from({ length: vcount * 3 }, (_, k) => [glowTint.r, glowTint.g, glowTint.b][k % 3]), 3));
1778
+ const tier = tEff < 0.34 ? 0 : tEff < 0.67 ? 1 : 2;
1779
+ const key = `${src}${tier}`;
1780
+ (shellsBy.get(key) ?? shellsBy.set(key, []).get(key)).push(shell);
1781
+ shellTier.set(key, [src, tier]);
1782
+ if (!shellHue.has(key)) shellHue.set(key, hue0.clone());
1783
+ const cw = dark ? 0.5 - 0.2 * t ** 0.85 : 0.38;
1784
+ const gap = (0.92 - cw) / 2;
1785
+ const hc = dark ? Math.max(0.1, h2 - 2 * Math.min(gap, (h2 - 0.1) / 2)) : h2 * 0.8;
1786
+ const core = roundedBox(cw, hc, cw, lite ? 1 : 2, Math.min(0.1, cw / 2.4, hc / 2.2));
1787
+ core.translate(x, y0 + h2 / 2, z);
1788
+ const level = Math.max(emit(t) * (1 + 1.1 * t), src === "top" ? GREEN_MIN_LEVEL : 0);
1789
+ const rod = dark && customOn() ? hue0.clone().multiplyScalar(level * 0.55 * (Math.max(hue0.r, hue0.g, hue0.b) - Math.min(hue0.r, hue0.g, hue0.b) < 0.15 * Math.max(hue0.r, hue0.g, hue0.b) ? WHITE_ROD : 1)) : dark ? rodLight(src, hue, t, level) : hue;
1790
+ paint(core, dark ? rod.clone().multiplyScalar(shadeOf.get(sp) ?? 1) : hue.clone().lerp(new THREE.Color(16777215), LIGHT_CORE_LIFT).multiplyScalar(LIGHT_CORE_DEPTH));
1791
+ {
1792
+ const count = core.getAttribute("position").count;
1793
+ const incs = new Float32Array(count * 3);
1794
+ if (dark) for (let q = 0; q < count; q++) inc.toArray(incs, q * 3);
1795
+ core.setAttribute("aInc", new THREE.BufferAttribute(incs, 3));
1796
+ }
1797
+ core.setAttribute("aBlock", new THREE.BufferAttribute(new Float32Array(core.getAttribute("position").count).fill(blockIndex++), 1));
1798
+ core.setAttribute("aCtr", new THREE.BufferAttribute(Float32Array.from({ length: core.getAttribute("position").count * 2 }, (_, k) => k % 2 ? z : x), 2));
1799
+ cores.push(core);
1800
+ }
1801
+ if (dark) {
1802
+ pitRims.forEach((pr, pi) => {
1803
+ pr.geom.setAttribute("aPit", new THREE.BufferAttribute(new Float32Array(pr.geom.getAttribute("position").count).fill(pi), 1));
1804
+ const lamps = [];
1805
+ specs.forEach((sp, si) => {
1806
+ const d = Math.hypot(sp.x - pr.x, sp.z - pr.z);
1807
+ if (d >= 0.5 && d <= 4) lamps.push({ si, w: emit(sp.t) * Math.exp(-(d * d) / (2 * 1.6 * 1.6)) });
1808
+ });
1809
+ pitLamps.push(lamps);
1810
+ const rp = pr.geom.getAttribute("position");
1811
+ const rc = pr.geom.getAttribute("color");
1812
+ for (let q = 0; q < rp.count; q++) {
1813
+ const rx = rp.getX(q) - pr.x;
1814
+ const rz = rp.getZ(q) - pr.z;
1815
+ const rl = Math.hypot(rx, rz) || 1;
1816
+ let r = 0;
1817
+ let gg = 0;
1818
+ let bb = 0;
1819
+ for (const sp of specs) {
1820
+ const dx = sp.x - pr.x;
1821
+ const dz = sp.z - pr.z;
1822
+ const dist = Math.hypot(dx, dz);
1823
+ if (dist < 0.5 || dist > 4) continue;
1824
+ const facing = Math.max(0, (-(rx / rl) * dx - rz / rl * dz) / dist);
1825
+ if (facing <= 0) continue;
1826
+ const k = emit(sp.t) * Math.exp(-(dist * dist) / (2 * 1.6 * 1.6)) * facing * facing * 0.018;
1827
+ r += sp.hue.r * k;
1828
+ gg += sp.hue.g * k;
1829
+ bb += sp.hue.b * k;
1830
+ }
1831
+ rc.setXYZ(q, page.r + Math.min(r, 0.1), page.g + Math.min(gg, 0.1), page.b + Math.min(bb, 0.1));
1832
+ }
1833
+ rc.needsUpdate = true;
1834
+ });
1835
+ }
1836
+ const tb1 = performance.now();
1837
+ const group = new THREE.Group();
1838
+ const groundGroup = groundLayers(stack2, tones, dark);
1839
+ pitLight = groundGroup.userData.setLevels ?? null;
1840
+ group.add(groundGroup);
1841
+ const tb2 = performance.now();
1842
+ rimLight = null;
1843
+ if (tiles.length) {
1844
+ const tile = new THREE.Mesh(mergeGeometries(tiles), tileUnlit);
1845
+ group.add(tile);
1846
+ const rim = new THREE.Mesh(mergeGeometries(rims), tileUnlit.clone());
1847
+ const rimMat = rim.material;
1848
+ rimMat.side = THREE.FrontSide;
1849
+ if (dark && pitLamps.length === pitRims.length && pitRims.length > 0) {
1850
+ const litData = new Float32Array(pitRims.length).fill(1);
1851
+ const litTex = new THREE.DataTexture(litData, pitRims.length, 1, THREE.RedFormat, THREE.FloatType);
1852
+ litTex.needsUpdate = true;
1853
+ rimMat.onBeforeCompile = (shader) => {
1854
+ shader.uniforms.uPitLit = { value: litTex };
1855
+ shader.uniforms.uPage = { value: page };
1856
+ shader.vertexShader = shader.vertexShader.replace("#include <common>", "#include <common>\nattribute float aPit;\nuniform highp sampler2D uPitLit;\nuniform vec3 uPage;").replace("#include <color_vertex>", "#include <color_vertex>\n#ifdef USE_COLOR\n vColor.rgb = uPage + (vColor.rgb - uPage) * texelFetch(uPitLit, ivec2(int(aPit + 0.5), 0), 0).r;\n#endif");
1857
+ };
1858
+ rimMat.customProgramCacheKey = () => "pit-rim-lit";
1859
+ const totals = pitLamps.map((l) => l.reduce((acc, q) => acc + q.w, 0));
1860
+ rimLight = (levels) => {
1861
+ for (let k = 0; k < pitLamps.length; k++) {
1862
+ let on = 0;
1863
+ for (const q of pitLamps[k]) on += q.w * Math.min(1, levels[q.si] ?? 1);
1864
+ litData[k] = totals[k] > 1e-6 ? on / totals[k] : 0;
1865
+ }
1866
+ litTex.needsUpdate = true;
1867
+ };
1868
+ }
1869
+ group.add(rim);
1870
+ }
1871
+ const materials = [];
1872
+ for (const [key, list] of shellsBy) {
1873
+ const [src, tier] = shellTier.get(key);
1874
+ const mat = blockMaterial.clone();
1875
+ if (dbg.wireframe) {
1876
+ mat.wireframe = true;
1877
+ mat.transmission = 0;
1878
+ mat.transparent = true;
1879
+ mat.opacity = 0.9;
1880
+ }
1881
+ mat.emissive.copy(customOn() ? new THREE.Color(0) : tones[src][1]);
1882
+ if (dark) {
1883
+ const lh = shellHue.get(key);
1884
+ const m = lh ? Math.max(lh.r, lh.g, lh.b, 1e-3) : 1;
1885
+ const sat = lh ? (m - Math.min(lh.r, lh.g, lh.b)) / m : 0;
1886
+ mat.attenuationColor.copy(lh && src === "top" ? new THREE.Color(1, 1, 1).lerp(new THREE.Color(lh.r / m, lh.g / m, lh.b / m), LAYER_FILTER_PURITY) : new THREE.Color(1, 1, 1));
1887
+ mat.attenuationDistance = src === "top" && sat > 0.15 ? LAYER_FILTER_DISTANCE / Math.min(1, sat * 1.5) : 1e3;
1888
+ }
1889
+ mat.emissiveIntensity = dark ? [0.02, 0.08, 0.15][tier] * (src === "top" ? DARK_GREEN_GLOW : 0.6) : 0;
1890
+ if (dark) {
1891
+ mat.onBeforeCompile = (shader) => {
1892
+ shader.uniforms.uLevels = { value: levelTex };
1893
+ shader.uniforms.uFloorEm = { value: OFF_EMISSIVE / Math.max(mat.emissiveIntensity, 1e-4) };
1894
+ shader.uniforms.uFloorEnv = { value: mat.envMapIntensity > 0 ? OFF_ENV / mat.envMapIntensity : 0 };
1895
+ shader.vertexShader = shader.vertexShader.replace("#include <common>", "#include <common>\nattribute float aBlock;\nattribute vec3 aInc;\nattribute vec3 aTint;\nvarying vec3 vInc;\nvarying vec3 vTint;\nuniform highp sampler2D uLevels;\nuniform float uFloorEm;\nuniform float uFloorEnv;\nvarying float vLevelEm;\nvarying float vLevelEnv;\nvarying float vOn;").replace("#include <begin_vertex>", "#include <begin_vertex>\n vec2 lv = texelFetch(uLevels, ivec2(int(aBlock + 0.5), 0), 0).rg;\n float own = max(lv.r, 0.3 * lv.g);\n vOn = clamp(own, 0.0, 1.0);\n vLevelEm = max(own, uFloorEm);\n vLevelEnv = max(own, uFloorEnv);\n vInc = aInc * lv.g * lv.g * lv.g;\n vTint = aTint;");
1896
+ shader.fragmentShader = shader.fragmentShader.replace("#include <common>", "#include <common>\nvarying float vLevelEm;\nvarying float vLevelEnv;\nvarying float vOn;\nvarying vec3 vInc;\nvarying vec3 vTint;").replace("#include <emissivemap_fragment>", "#include <emissivemap_fragment>\n // (right off, the glass glows the same cool grey whatever its source; as soon as there is a light in it, its own colour, darker the dimmer the light: a dimmed block is a tinted, darker one, not a grey one)\n float offGrey = 1.0 - smoothstep(0.05, 0.6, vOn);\n totalEmissiveRadiance = mix(totalEmissiveRadiance, vec3(dot(totalEmissiveRadiance, vec3(0.333))) * vec3(0.85, 0.95, 1.15), offGrey) * mix(pow(vLevelEm, 2.0), vLevelEm, offGrey);\n vec3 nb = min(vInc * " + NEIGHBOUR_GLOW.toFixed(3) + ", vec3(0.1));\n nb = max(vec3(0.0), mix(vec3(dot(nb, vec3(0.299, 0.587, 0.114))), nb, " + GLOW_SATURATION.toFixed(2) + "));\n nb *= mix(vec3(1.0), vTint, smoothstep(0.05, 0.6, vOn) * mix(" + GLOW_TINT_FAINT.toFixed(3) + ", 1.0, smoothstep(0.02, 0.1, max(nb.r, max(nb.g, nb.b)))));\n totalEmissiveRadiance += nb;").replace("#include <lights_physical_fragment>", "#include <lights_physical_fragment>\n#ifdef USE_TRANSMISSION\n material.attenuationColor = mix(vec3(1.0), material.attenuationColor, smoothstep(0.12, 0.9, vOn));\n#endif").replace("#include <lights_fragment_maps>", "#include <lights_fragment_maps>\n#if defined( RE_IndirectSpecular )\n radiance *= vLevelEnv;\n#ifdef USE_CLEARCOAT\n clearcoatRadiance *= vLevelEnv;\n#endif\n#endif\n#if defined( RE_IndirectDiffuse )\n iblIrradiance *= vLevelEnv;\n#endif");
1897
+ };
1898
+ mat.customProgramCacheKey = () => "glass-levels";
1899
+ }
1900
+ mat.envMap = dark ? env : null;
1901
+ mat.envMapIntensity = dark ? [0.02, 0.18, 0.55][tier] * 0.1 : LIGHT_ENV;
1902
+ if (dark) {
1903
+ mat.specularColor = new THREE.Color(16777215);
1904
+ mat.clearcoat = 0.15;
1905
+ mat.roughness = DARK_GLASS_ROUGHNESS;
1906
+ }
1907
+ if (!dark) {
1908
+ mat.clearcoat = LIGHT_COAT;
1909
+ mat.roughness = LIGHT_GLASS_ROUGHNESS;
1910
+ mat.specularIntensity = LIGHT_SPECULAR;
1911
+ mat.specularColor = tones[src][1].clone().lerp(new THREE.Color(16777215), 0.75);
1912
+ mat.side = LIGHT_DOUBLE_SIDED ? THREE.DoubleSide : THREE.FrontSide;
1913
+ }
1914
+ materials.push(mat);
1915
+ const glass = new THREE.Mesh(mergeGeometries(list), mat);
1916
+ glass.castShadow = true;
1917
+ glass.receiveShadow = true;
1918
+ group.add(glass);
1919
+ list.forEach((p) => p.dispose());
1920
+ }
1921
+ group.userData.dispose = () => materials.forEach((m) => m.dispose());
1922
+ if (cores.length) {
1923
+ const core = new THREE.Mesh(mergeGeometries(cores), dark ? glowMaterial : coreMaterial);
1924
+ if (dark) core.renderOrder = 10;
1925
+ core.castShadow = false;
1926
+ group.add(core);
1927
+ }
1928
+ [...cores, ...tiles].forEach((p) => p.dispose());
1929
+ tileShape?.dispose();
1930
+ ringShape0?.dispose();
1931
+ if (dbg.metrics) console.info(`[activity] build: geometry ${Math.round(tb1 - tb0)} ms, ground ${Math.round(tb2 - tb1)} ms, merge ${Math.round(performance.now() - tb2)} ms`);
1932
+ return group;
1933
+ };
1934
+ const blocks = new THREE.Group();
1935
+ scene.add(blocks);
1936
+ const ground0 = () => ground.material.opacity = isDark() ? 0 : 0.05;
1937
+ const buildBlocks = () => {
1938
+ showMat.uniforms.bloom.value = isDark() ? customOn() ? 0.4 : 1 : 0;
1939
+ showMat.uniforms.veil.value = customOn() ? 0.75 : 0;
1940
+ scene.environmentIntensity = isDark() ? 0 : 0.9;
1941
+ sun.intensity = isDark() ? 0 : 2.2;
1942
+ ground0();
1943
+ blocks.traverse((o) => {
1944
+ o.geometry?.dispose();
1945
+ o.userData.dispose?.();
1946
+ });
1947
+ blocks.clear();
1948
+ const dark = isDark();
1949
+ const pair = (layer) => {
1950
+ const [low, high] = colorOf(layer, dark);
1951
+ const [dl, dh] = DEFAULT_COLORS[layer][dark ? "dark" : "light"];
1952
+ stock[layer] = sameColor(low, dl) && sameColor(high, dh);
1953
+ if (!stock[layer]) {
1954
+ const [lo, hi] = clampTone(high);
1955
+ return [new THREE.Color(lo), new THREE.Color(hi)];
1956
+ }
1957
+ return [new THREE.Color(low), new THREE.Color(high)];
1958
+ };
1959
+ blocks.add(build({ bottom: layout.bottom, top: layout.top }, { bottom: pair("bottom"), top: pair("top") }, dark));
1960
+ };
1961
+ const floor = new THREE.Mesh(new THREE.PlaneGeometry(1200, 1200), new THREE.MeshBasicMaterial({ color: pageColour() }));
1962
+ floor.rotation.x = -Math.PI / 2;
1963
+ floor.position.set(width / 2, -0.02, total / 2);
1964
+ scene.add(floor);
1965
+ const ground = new THREE.Mesh(new THREE.PlaneGeometry(1200, 1200), new THREE.ShadowMaterial({ opacity: 0.32, depthWrite: false }));
1966
+ ground.rotation.x = -Math.PI / 2;
1967
+ ground.position.set(width / 2, 0.06, total / 2);
1968
+ ground.receiveShadow = true;
1969
+ scene.add(ground);
1970
+ const sun = new THREE.DirectionalLight(16777215, 2.2);
1971
+ const sunBase = new THREE.Vector3(-0.45, 1, 0.55).normalize().multiplyScalar(60);
1972
+ sun.castShadow = true;
1973
+ sun.shadow.mapSize.set(lite ? 2048 : 4096, lite ? 2048 : 4096);
1974
+ sun.shadow.bias = -4e-4;
1975
+ sun.shadow.normalBias = 0.03;
1976
+ const sc = sun.shadow.camera;
1977
+ sc.left = -width * 1.4;
1978
+ sc.right = width * 1.4;
1979
+ sc.top = total * 6;
1980
+ sc.bottom = -total * 6;
1981
+ sc.near = 1;
1982
+ sc.far = 160;
1983
+ sun.target.position.set(width / 2, 0, total / 2);
1984
+ scene.add(sun, sun.target);
1985
+ const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 1, 1900);
1986
+ const centre = new THREE.Vector3(width / 2, 1.2, total / 2);
1987
+ camera.position.copy(centre).add(new THREE.Vector3(...CAMERA_DIR).normalize().multiplyScalar(900));
1988
+ camera.up.set(0, 1, 0);
1989
+ camera.lookAt(centre);
1990
+ const sceneRT = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType });
1991
+ const accumRT = new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType });
1992
+ const quadGeo = new THREE.PlaneGeometry(2, 2);
1993
+ const quadCam = new THREE.OrthographicCamera(-1, 1, 1, -1, 0, 1);
1994
+ const addMat = new THREE.ShaderMaterial({
1995
+ uniforms: { map: { value: sceneRT.texture } },
1996
+ vertexShader: "varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }",
1997
+ fragmentShader: "uniform sampler2D map; varying vec2 vUv; void main(){ gl_FragColor = texture2D(map, vUv); }",
1998
+ // a running average (new * k + old * (1 - k), k = 1 / (n + 1)): the values stay in 0..1, where a half float is precise; a plain sum grows to ~100 and its rounding errors tint the whole picture
1999
+ blending: THREE.CustomBlending,
2000
+ blendEquation: THREE.AddEquation,
2001
+ blendSrc: THREE.ConstantAlphaFactor,
2002
+ blendDst: THREE.OneMinusConstantAlphaFactor,
2003
+ blendSrcAlpha: THREE.ConstantAlphaFactor,
2004
+ blendDstAlpha: THREE.OneMinusConstantAlphaFactor,
2005
+ depthTest: false,
2006
+ depthWrite: false
2007
+ });
2008
+ const VERT = "varying vec2 vUv; void main(){ vUv = uv; gl_Position = vec4(position.xy, 0., 1.); }";
2009
+ const rt = () => new THREE.WebGLRenderTarget(1, 1, { type: THREE.HalfFloatType, depthBuffer: false });
2010
+ const halfA = rt();
2011
+ const halfB = rt();
2012
+ const quarterA = rt();
2013
+ const quarterB = rt();
2014
+ const brightMat = new THREE.ShaderMaterial({
2015
+ uniforms: { map: { value: accumRT.texture } },
2016
+ vertexShader: VERT,
2017
+ fragmentShader: "uniform sampler2D map; varying vec2 vUv; void main(){ vec3 c = texture2D(map, vUv).rgb; gl_FragColor = vec4(max(c - 1.0, 0.), 1.); }",
2018
+ depthTest: false,
2019
+ depthWrite: false
2020
+ });
2021
+ const blurMat = new THREE.ShaderMaterial({
2022
+ uniforms: { map: { value: halfA.texture }, stepv: { value: new THREE.Vector2() } },
2023
+ vertexShader: VERT,
2024
+ fragmentShader: `uniform sampler2D map; uniform vec2 stepv; varying vec2 vUv;
2025
+ void main(){
2026
+ vec3 c = texture2D(map, vUv).rgb * 0.227027;
2027
+ c += (texture2D(map, vUv + stepv * 1.3846154).rgb + texture2D(map, vUv - stepv * 1.3846154).rgb) * 0.3162162;
2028
+ c += (texture2D(map, vUv + stepv * 3.2307692).rgb + texture2D(map, vUv - stepv * 3.2307692).rgb) * 0.0702703;
2029
+ gl_FragColor = vec4(c, 1.);
2030
+ }`,
2031
+ depthTest: false,
2032
+ depthWrite: false
2033
+ });
2034
+ const showMat = new THREE.ShaderMaterial({
2035
+ uniforms: { map: { value: accumRT.texture }, bloom: { value: 0 }, veil: { value: 0 }, grain: { value: GRAIN }, near: { value: halfA.texture }, far: { value: quarterA.texture } },
2036
+ vertexShader: VERT,
2037
+ fragmentShader: `uniform sampler2D map; uniform sampler2D near; uniform sampler2D far; uniform float bloom; uniform float veil; uniform float grain; varying vec2 vUv;
2038
+ void main(){
2039
+ vec4 c = texture2D(map, vUv);
2040
+ if (bloom > 0.) {
2041
+ vec3 halo = texture2D(near, vUv).rgb * 0.24 + texture2D(far, vUv).rgb * 0.17;
2042
+ // The halo is cut out of the picture before the rods are taken toward white, so it keeps the saturated blue of their raw light: a near-white rod would glow deep blue. It takes the rod's colour (the same pull toward white), only dimmer; green is left as it is.
2043
+ float hm = max(max(halo.r, halo.g), halo.b);
2044
+ float haloBlue = smoothstep(0., 0.25, (halo.b - halo.g) / max(hm, 1e-4));
2045
+ halo = mix(halo, vec3(hm), haloBlue * 0.6);
2046
+ // (the blue's halo is fainter, the green's a little stronger)
2047
+ c.rgb += bloom * halo * mix(1.3, 0.38, haloBlue);
2048
+ }
2049
+ // (rodColor: the grey-white veil that the glass's reflections, the halo and the emissive add to every channel is taken off: what is left is the rod's own colour, as saturated as it is, at the same brightness)
2050
+ if (veil > 0.) { float mx = max(c.r, max(c.g, c.b)); float mn = min(c.r, min(c.g, c.b)); float k = smoothstep(0.12, 0.5, (mx - mn) / max(mx, 1e-4)); c.rgb -= mn * veil * k; c.rgb *= mix(1., mix(0.15, 1., k), smoothstep(0.04, 0.2, mx) * (1. - smoothstep(0.2, 0.4, mx))); }
2051
+ // A hue-preserving soft clip: a channel past 1 (a busy blue: its blue is far over, its green and red are not) would clip alone and turn the colour pale; the whole colour is brought back so that its brightest channel
2052
+ // only just passes 1, and the hue and the saturation stay.
2053
+ float m = max(max(c.r, c.g), c.b);
2054
+ // A blue light far over 1 (a busy day's rod) is taken toward white as it rises, so the rod is whiter than the blue glass around it (whose reflections and refractions stay under 1); green is left as it is.
2055
+ float blueish = smoothstep(0., 0.25, (c.b - c.g) / max(m, 1e-4));
2056
+ float hot = smoothstep(1., 3., m);
2057
+ c.rgb = mix(c.rgb, vec3(m), blueish * hot * 0.55 * step(veil, 0.));
2058
+ if (m > 1.) c.rgb *= (1. + (m - 1.) * 0.12) / m;
2059
+ gl_FragColor = c;
2060
+ #include <colorspace_fragment>
2061
+ // Camera grain: a fine, fixed noise over the whole picture, added after the lighting (on what is shown, not in it). It is meant to read as the noise of a good camera, not as rendering noise: soft (the sum of three
2062
+ // uniform numbers, so close to a gaussian and not the harsh specks of a single one), the same for every colour of the picture (it is not gated by brightness: a coloured block gets as much as a grey one), growing with the light (as a sensor's does: the dark glows stay clean) and easing off in the highlights (so that a bright surface does not burn); brightness only, no colour noise.
2063
+ if (grain > 0.) {
2064
+ vec3 q = fract(vec3(gl_FragCoord.xyx) * vec3(.1031, .1030, .0973));
2065
+ q += dot(q, q.yzx + 33.33);
2066
+ vec3 h = fract((q.xxy + q.yzz) * q.zyx);
2067
+ float g = (h.x + h.y + h.z - 1.5) * 0.7;
2068
+ float lum = dot(gl_FragColor.rgb, vec3(0.2126, 0.7152, 0.0722));
2069
+ // (the noise of a sensor grows with the light it gets, as its square root: the dark glows stay clean, the lit surfaces carry the grain)
2070
+ // (and none at all in the near-blacks: in an 8-bit picture a tiny noise there only flips single pixels between two levels, which is a speckle, not a grain)
2071
+ float tone = sqrt(clamp(lum, 0., 1.)) * smoothstep(0.08, 0.3, lum) * (1. - smoothstep(0.7, 1.0, lum) * 0.8);
2072
+ // (a soft rise or loss of brightness, a few per cent, never a dark speck: the colour is scaled, its hue kept, and there is no colour noise)
2073
+ gl_FragColor.rgb *= 1. + g * grain * 5. * tone;
2074
+ }
2075
+ }`,
2076
+ depthTest: false,
2077
+ depthWrite: false
2078
+ });
2079
+ const fsMesh = new THREE.Mesh(quadGeo, brightMat);
2080
+ const fsScene = new THREE.Scene();
2081
+ fsScene.add(fsMesh);
2082
+ const pass = (material, target) => {
2083
+ fsMesh.material = material;
2084
+ renderer.setRenderTarget(target);
2085
+ renderer.render(fsScene, quadCam);
2086
+ };
2087
+ const blur = (from, to, size, radius) => {
2088
+ blurMat.uniforms.map.value = from.texture;
2089
+ blurMat.uniforms.stepv.value.set(radius / size[0], 0);
2090
+ pass(blurMat, to);
2091
+ blurMat.uniforms.map.value = to.texture;
2092
+ blurMat.uniforms.stepv.value.set(0, radius / size[1]);
2093
+ pass(blurMat, from);
2094
+ };
2095
+ const addQuad = new THREE.Mesh(quadGeo, addMat);
2096
+ const showQuad = new THREE.Mesh(quadGeo, showMat);
2097
+ const quadScene = new THREE.Scene();
2098
+ quadScene.add(addQuad);
2099
+ let w = 1;
2100
+ let h = 1;
2101
+ let n = 0;
2102
+ let samplesCap = samples;
2103
+ let raf = 0;
2104
+ const halton = (i, b) => {
2105
+ let f = 1;
2106
+ let r = 0;
2107
+ for (let k = i + 1; k > 0; k = Math.floor(k / b)) {
2108
+ f /= b;
2109
+ r += f * (k % b);
2110
+ }
2111
+ return r;
2112
+ };
2113
+ const fit = () => {
2114
+ const size = renderSize({ cssWidth: el.clientWidth, cssHeight: el.clientHeight, devicePixelRatio: window.devicePixelRatio, lite, maxPixelRatio: opts.maxPixelRatio, maxPixels: opts.maxPixels, maxSize: renderer.capabilities.maxTextureSize });
2115
+ w = size.width;
2116
+ h = size.height;
2117
+ renderer.setPixelRatio(1);
2118
+ renderer.setSize(w, h, false);
2119
+ sceneRT.setSize(w, h);
2120
+ accumRT.setSize(w, h);
2121
+ halfA.setSize(Math.max(1, w >> 1), Math.max(1, h >> 1));
2122
+ halfB.setSize(Math.max(1, w >> 1), Math.max(1, h >> 1));
2123
+ quarterA.setSize(Math.max(1, w >> 1), Math.max(1, h >> 1));
2124
+ quarterB.setSize(Math.max(1, w >> 1), Math.max(1, h >> 1));
2125
+ camera.updateMatrixWorld();
2126
+ const inv = camera.matrixWorldInverse;
2127
+ let x0 = Infinity, x1 = -Infinity, y0 = Infinity, y1 = -Infinity;
2128
+ for (const [cx, cz] of corners(ROOM)) for (const cy of [0, tallest]) {
2129
+ const p = new THREE.Vector3(cx, cy, cz).applyMatrix4(inv);
2130
+ x0 = Math.min(x0, p.x);
2131
+ x1 = Math.max(x1, p.x);
2132
+ y0 = Math.min(y0, p.y);
2133
+ y1 = Math.max(y1, p.y);
2134
+ }
2135
+ if (dbg.metrics) el.dataset.fit = ((x1 - x0) / (y1 - y0)).toFixed(3);
2136
+ const aspect = w / h;
2137
+ let gx = (x0 + x1) / 2;
2138
+ if (strips > 1) {
2139
+ const perStrip = Math.ceil(layout.top.weeks / strips);
2140
+ let sum = 0;
2141
+ for (let k = 0; k < strips; k++) {
2142
+ const c = at(k * perStrip + (perStrip - 1) / 2, 3);
2143
+ sum += new THREE.Vector3(c.x, 0, c.z).applyMatrix4(inv).x;
2144
+ }
2145
+ gx = sum / strips;
2146
+ }
2147
+ const halfH = Math.max((y1 - y0) / 2, Math.max(x1 - gx, gx - x0) / aspect) * 1.04;
2148
+ const mx = gx;
2149
+ const my = (y0 + y1) / 2;
2150
+ camera.left = mx - halfH * aspect;
2151
+ camera.right = mx + halfH * aspect;
2152
+ camera.top = my + halfH;
2153
+ camera.bottom = my - halfH;
2154
+ camera.updateProjectionMatrix();
2155
+ releaseSize();
2156
+ publishBounds();
2157
+ restart();
2158
+ };
2159
+ const publishBounds = () => {
2160
+ camera.updateMatrixWorld();
2161
+ let l = Infinity, r = -Infinity, t = Infinity, b = -Infinity;
2162
+ const cw = el.clientWidth;
2163
+ const ch = el.clientHeight;
2164
+ const px = (x, y, z) => {
2165
+ const p = new THREE.Vector3(x, y, z).project(camera);
2166
+ return { x: (p.x + 1) / 2 * cw, y: (1 - p.y) / 2 * ch };
2167
+ };
2168
+ layout.top.cells.forEach((g, i) => {
2169
+ if (g.value <= 0 && layout.bottom.cells[i].value <= 0) return;
2170
+ const { x, z } = at(g.week, g.day);
2171
+ for (const [dx, dz] of [[-0.46, -0.46], [0.46, -0.46], [-0.46, 0.46], [0.46, 0.46]]) {
2172
+ const foot = px(x + dx, 0, z + dz);
2173
+ l = Math.min(l, foot.x);
2174
+ r = Math.max(r, foot.x);
2175
+ b = Math.max(b, foot.y);
2176
+ }
2177
+ t = Math.min(t, px(x, topOf(i), z).y);
2178
+ });
2179
+ if (!Number.isFinite(l)) return;
2180
+ bounds = { left: l, right: r, top: t, bottom: b };
2181
+ for (const [k, v] of Object.entries(bounds)) el.style.setProperty(`--nag-content-${k}`, `${v.toFixed(1)}px`);
2182
+ opts.onLayout?.(bounds);
2183
+ };
2184
+ const frames = [];
2185
+ const frame = () => cm(() => frameBody());
2186
+ let blendFloor = 0;
2187
+ let jitter = 0;
2188
+ const frameBody = (count = 1) => {
2189
+ raf = 0;
2190
+ const f0 = performance.now();
2191
+ for (let c = 0; c < count; c++) {
2192
+ const a = halton(n + jitter, 2) * Math.PI * 2;
2193
+ const r = Math.sqrt(halton(n + jitter, 3)) * 9;
2194
+ sun.position.copy(sunBase).add(new THREE.Vector3(Math.cos(a) * r, 0, Math.sin(a) * r)).add(sun.target.position);
2195
+ camera.setViewOffset(w, h, halton(n + jitter, 5) - 0.5, halton(n + jitter, 7) - 0.5, w, h);
2196
+ renderer.setRenderTarget(sceneRT);
2197
+ renderer.setClearColor(0, 0);
2198
+ renderer.clear();
2199
+ renderer.render(scene, camera);
2200
+ renderer.setRenderTarget(accumRT);
2201
+ renderer.autoClear = false;
2202
+ addMat.blendAlpha = Math.max(1 / (n + 1), blendFloor);
2203
+ renderer.render(quadScene, quadCam);
2204
+ renderer.autoClear = true;
2205
+ n++;
2206
+ }
2207
+ if (settling && n >= Math.min(10, samples, samplesCap)) sharpen();
2208
+ if (showMat.uniforms.bloom.value > 0) {
2209
+ pass(brightMat, halfA);
2210
+ blur(halfA, halfB, [w >> 1, h >> 1], 1.5);
2211
+ blur(halfA, halfB, [w >> 1, h >> 1], 3);
2212
+ blurMat.uniforms.map.value = halfA.texture;
2213
+ blurMat.uniforms.stepv.value.set(0, 0);
2214
+ pass(blurMat, quarterA);
2215
+ blur(quarterA, quarterB, [w >> 1, h >> 1], 3);
2216
+ if (!lite) blur(quarterA, quarterB, [w >> 1, h >> 1], 5);
2217
+ }
2218
+ renderer.setRenderTarget(null);
2219
+ renderer.clear();
2220
+ renderer.render(showQuad, quadCam);
2221
+ if (dbg.metrics) {
2222
+ renderer.getContext().finish();
2223
+ frames.push(performance.now() - f0);
2224
+ el.dataset.frameMs = (frames.reduce((x, y) => x + y, 0) / frames.length).toFixed(1);
2225
+ }
2226
+ if (n < samplesCap) raf = requestAnimationFrame(frame);
2227
+ else if (dbg.metrics) el.dataset.renderMs = String(Math.round(performance.now() - t0));
2228
+ };
2229
+ function restart() {
2230
+ n = 0;
2231
+ if (!raf) raf = requestAnimationFrame(frame);
2232
+ }
2233
+ const ema = (floor2 = 0.3) => {
2234
+ cancelAnimationFrame(raf);
2235
+ raf = 0;
2236
+ n = Math.min(n, 6);
2237
+ jitter += 1;
2238
+ samplesCap = 0;
2239
+ blendFloor = floor2;
2240
+ cm(() => frameBody(1));
2241
+ blendFloor = 0;
2242
+ };
2243
+ let neon = null;
2244
+ let neonApplyMs = 0;
2245
+ let neonTicks = 0;
2246
+ const neonAllowed = () => !(opts.reducedMotion === "auto" || opts.reducedMotion === void 0 ? window.matchMedia("(prefers-reduced-motion: reduce)").matches : opts.reducedMotion);
2247
+ let inView = true;
2248
+ const viewObserver = typeof IntersectionObserver === "undefined" ? null : new IntersectionObserver((entries) => inView = entries.some((e) => e.isIntersecting));
2249
+ viewObserver?.observe(el);
2250
+ let hook = null;
2251
+ const stopNeon = () => {
2252
+ hook?.stop?.();
2253
+ hook = null;
2254
+ neon?.stop();
2255
+ neon = null;
2256
+ neonStart = null;
2257
+ samplesCap = samples;
2258
+ levelData.fill(1);
2259
+ levelTex.needsUpdate = true;
2260
+ };
2261
+ const uploadLevels = (levels, idle = false) => {
2262
+ for (let i = 0; i < neonNeighbours.length && i < MAX_LEVELS; i++) {
2263
+ const nb = neonNeighbours[i];
2264
+ let on = 0;
2265
+ let all = 0;
2266
+ for (let k = 0; k < nb.j.length; k++) {
2267
+ on += nb.m[k] * levels[nb.j[k]];
2268
+ all += nb.m[k];
2269
+ }
2270
+ levelData[i * 2] = levels[i];
2271
+ levelData[i * 2 + 1] = all > 0 ? idle ? 0.55 * (on / all) + 0.45 * Math.min(1, levels[i]) : on / all : 1;
2272
+ }
2273
+ levelTex.needsUpdate = true;
2274
+ };
2275
+ const FOCUS_ON = 1.7;
2276
+ const FOCUS_MIN_PEAK = 1.7;
2277
+ const FOCUS_MAX_GAIN = 5;
2278
+ const FOCUS_OFF = 0.34;
2279
+ const BACKDROP_DIM_POWER = 2;
2280
+ let focusCtl = null;
2281
+ let focus = new Float32Array(0);
2282
+ let focusTo = new Float32Array(0);
2283
+ let effective = new Float32Array(0);
2284
+ let lastLevels = new Float32Array(0);
2285
+ let idleLook = false;
2286
+ let focusRaf = 0;
2287
+ let focusTimer = 0;
2288
+ const applyLevels = (levels) => {
2289
+ lastLevels = levels;
2290
+ const n2 = neonBlocks.length;
2291
+ if (effective.length !== n2) effective = new Float32Array(n2).fill(1);
2292
+ for (let i = 0; i < n2; i++) effective[i] = levels[i] * (focus[i] ?? 1);
2293
+ uploadLevels(effective, idleLook);
2294
+ focusCtl?.update(effective);
2295
+ pitLight?.(effective);
2296
+ rimLight?.(effective);
2297
+ let lit = 0;
2298
+ for (let i = 0; i < n2; i++) lit += Math.min(1, effective[i]);
2299
+ backdropDim.value = n2 > 0 ? (lit / n2) ** BACKDROP_DIM_POWER : 1;
2300
+ };
2301
+ const hum = createHoverHum();
2302
+ let humOk = false;
2303
+ const humLevel = () => {
2304
+ if (!humOk || !(opts.sound ?? true)) return hum.set(0);
2305
+ let lvl = 0;
2306
+ let held = -1;
2307
+ for (let i = 0; i < focus.length; i++) {
2308
+ lvl = Math.max(lvl, Math.min(1, (focus[i] - 1) / (FOCUS_ON - 1)));
2309
+ if (focusTo[i] > 1 && (held < 0 || focusTo[i] > focusTo[held])) held = i;
2310
+ }
2311
+ if (held < 0) return hum.set(lvl);
2312
+ hum.set(lvl, neonBlocks[held].pan, neonBlocks[held].cell, neonBlocks[held].t);
2313
+ };
2314
+ const stepFocus = () => {
2315
+ focusRaf = 0;
2316
+ let moving = false;
2317
+ for (let i = 0; i < focus.length; i++) {
2318
+ const d = focusTo[i] - focus[i];
2319
+ if (Math.abs(d) > 0.01) {
2320
+ focus[i] += d * 0.28;
2321
+ moving = true;
2322
+ } else focus[i] = focusTo[i];
2323
+ }
2324
+ applyLevels(lastLevels);
2325
+ humLevel();
2326
+ ema(lite ? 0.45 : 0.3);
2327
+ if (moving) focusRaf = window.setTimeout(stepFocus, 1e3 / (lite ? 20 : 30));
2328
+ else {
2329
+ samplesCap = samples;
2330
+ if (!raf) raf = requestAnimationFrame(frame);
2331
+ }
2332
+ };
2333
+ const GHOST = 0.12;
2334
+ const focusOn = (cell, ghosts = []) => {
2335
+ window.clearTimeout(focusTimer);
2336
+ if (!focusCtl) return;
2337
+ focusTimer = window.setTimeout(() => {
2338
+ for (let i = 0; i < focusTo.length; i++) focusTo[i] = cell < 0 ? 1 : neonBlocks[i].cell === cell ? Math.min(FOCUS_MAX_GAIN, Math.max(FOCUS_ON, FOCUS_MIN_PEAK / Math.max(neonBlocks[i].peak, 1e-3))) : ghosts.includes(neonBlocks[i].cell) ? GHOST : FOCUS_OFF;
2339
+ window.clearTimeout(focusRaf);
2340
+ stepFocus();
2341
+ }, cell < 0 ? 140 : 70);
2342
+ };
2343
+ const prepareNeon = (skipStartup = false) => {
2344
+ stopNeon();
2345
+ humOk = false;
2346
+ hum.stop();
2347
+ onLit?.(false);
2348
+ window.clearTimeout(focusTimer);
2349
+ window.clearTimeout(focusRaf);
2350
+ focusCtl = isDark() && stampCtl && neonBlocks.length > 0 && neonBlocks.length <= MAX_LEVELS ? stampCtl : null;
2351
+ focus = new Float32Array(neonBlocks.length).fill(1);
2352
+ focusTo = new Float32Array(neonBlocks.length).fill(1);
2353
+ effective = new Float32Array(neonBlocks.length).fill(1);
2354
+ lastLevels = new Float32Array(neonBlocks.length).fill(1);
2355
+ idleLook = false;
2356
+ backdropDim.value = 1;
2357
+ if (focusCtl) applyLevels(lastLevels);
2358
+ if (!isDark() || !neonAllowed() || skipStartup || !stampCtl || neonBlocks.length === 0 || neonBlocks.length > MAX_LEVELS) return void (humOk = true, onLit?.(true));
2359
+ const ctl = stampCtl;
2360
+ neonApplyMs = 0;
2361
+ neonTicks = 0;
2362
+ neon = createNeon({
2363
+ blocks: neonBlocks,
2364
+ sound: opts.sound ?? true,
2365
+ canPlay: () => inView,
2366
+ // (a weak device, a phone: half the updates, so half the redraws of the picture while the lights flicker)
2367
+ fps: lite ? 10 : 20,
2368
+ // (the wobble is redrawn more often than the flickers: 40 a second, 15 on a weak device)
2369
+ wobbleFps: lite ? 15 : 40,
2370
+ apply: (levels, idle) => {
2371
+ const a0 = performance.now();
2372
+ idleLook = !!idle;
2373
+ applyLevels(levels);
2374
+ neonApplyMs += performance.now() - a0;
2375
+ neonTicks++;
2376
+ if (dbg.metrics) {
2377
+ let mn = 1;
2378
+ let sum = 0;
2379
+ for (let q = 0; q < levels.length; q++) {
2380
+ mn = Math.min(mn, levels[q]);
2381
+ sum += levels[q];
2382
+ }
2383
+ el.dataset.neonMin = mn.toFixed(2);
2384
+ el.dataset.neonMean = (sum / levels.length).toFixed(3);
2385
+ }
2386
+ ema(lite ? 0.45 : 0.3);
2387
+ },
2388
+ done: () => {
2389
+ humOk = true;
2390
+ onLit?.(true);
2391
+ samplesCap = samples;
2392
+ if (!raf) raf = requestAnimationFrame(frame);
2393
+ if (dbg.metrics) {
2394
+ el.dataset.neonTicks = String(neonTicks);
2395
+ el.dataset.neonApplyMs = (neonApplyMs / Math.max(1, neonTicks)).toFixed(2);
2396
+ el.dataset.neonFrameMs = (frames.reduce((x, y) => x + y, 0) / Math.max(1, frames.length)).toFixed(1);
2397
+ el.dataset.neonDone = "1";
2398
+ }
2399
+ }
2400
+ });
2401
+ hook = opts.startup?.({ inView: () => inView }) ?? null;
2402
+ if (dbg.metrics) el.dataset.neonRods = String(neon.count);
2403
+ applyLevels(neon.levels);
2404
+ neonStart = () => {
2405
+ frames.length = 0;
2406
+ hook?.start?.();
2407
+ neon?.start();
2408
+ };
2409
+ if (dbg.neonHold) {
2410
+ neonStart = null;
2411
+ const half = Float32Array.from(neonBlocks, (b) => b.pan > -0.1 ? 1 : Number(dbg.neonHold) > 0 && Number(dbg.neonHold) < 1 ? Number(dbg.neonHold) : 0);
2412
+ uploadLevels(half);
2413
+ ctl.update(half);
2414
+ }
2415
+ };
2416
+ buildBlocks();
2417
+ prepareNeon();
2418
+ const dom = renderer.domElement;
2419
+ const ray = new THREE.Raycaster();
2420
+ const ndc = new THREE.Vector2();
2421
+ let current = -1;
2422
+ let pinned = false;
2423
+ const cells = layout.top.cells;
2424
+ const topOf = (cell) => picks.filter((b) => b.cell === cell).reduce((m, b) => Math.max(m, b.y1), 0);
2425
+ const pickAll = (cx, cy) => {
2426
+ const r = dom.getBoundingClientRect();
2427
+ ndc.set((cx - r.left) / r.width * 2 - 1, -((cy - r.top) / r.height) * 2 + 1);
2428
+ camera.updateMatrixWorld();
2429
+ ray.setFromCamera(ndc, camera);
2430
+ const o = ray.ray.origin;
2431
+ const d = ray.ray.direction;
2432
+ const hits = /* @__PURE__ */ new Map();
2433
+ for (const b of picks) {
2434
+ let t02 = -Infinity;
2435
+ let t1 = Infinity;
2436
+ for (const [oo, dd, lo, hi] of [[o.x, d.x, b.x - 0.46, b.x + 0.46], [o.y, d.y, b.y0, b.y1], [o.z, d.z, b.z - 0.46, b.z + 0.46]]) {
2437
+ if (Math.abs(dd) < 1e-9) {
2438
+ if (oo < lo || oo > hi) t02 = Infinity;
2439
+ continue;
2440
+ }
2441
+ const a = (lo - oo) / dd;
2442
+ const c = (hi - oo) / dd;
2443
+ t02 = Math.max(t02, Math.min(a, c));
2444
+ t1 = Math.min(t1, Math.max(a, c));
2445
+ }
2446
+ if (t02 <= t1 && t02 < (hits.get(b.cell) ?? Infinity)) hits.set(b.cell, t02);
2447
+ }
2448
+ return [...hits.entries()].sort((x, y) => x[1] - y[1]).map(([cell]) => cell);
2449
+ };
2450
+ const toCss = (v) => {
2451
+ const p = v.clone().project(camera);
2452
+ return { x: (p.x + 1) / 2 * el.clientWidth, y: (1 - p.y) / 2 * el.clientHeight };
2453
+ };
2454
+ const hull = (pts) => {
2455
+ const s2 = [...pts].sort((a, b) => a.x - b.x || a.y - b.y);
2456
+ const cr = (o, a, b) => (a.x - o.x) * (b.y - o.y) - (a.y - o.y) * (b.x - o.x);
2457
+ const lower = [];
2458
+ for (const p of s2) {
2459
+ while (lower.length >= 2 && cr(lower[lower.length - 2], lower[lower.length - 1], p) <= 0) lower.pop();
2460
+ lower.push(p);
2461
+ }
2462
+ const upper = [];
2463
+ for (const p of [...s2].reverse()) {
2464
+ while (upper.length >= 2 && cr(upper[upper.length - 2], upper[upper.length - 1], p) <= 0) upper.pop();
2465
+ upper.push(p);
2466
+ }
2467
+ return [...lower.slice(0, -1), ...upper.slice(0, -1)];
2468
+ };
2469
+ const resample = (poly, n2) => {
2470
+ let start = 0;
2471
+ poly.forEach((p, i) => {
2472
+ if (p.y < poly[start].y) start = i;
2473
+ });
2474
+ const ring = [...poly.slice(start), ...poly.slice(0, start)];
2475
+ const lens = ring.map((p, i) => Math.hypot(ring[(i + 1) % ring.length].x - p.x, ring[(i + 1) % ring.length].y - p.y));
2476
+ const total2 = lens.reduce((x, y) => x + y, 0);
2477
+ const out = [];
2478
+ let seg = 0;
2479
+ let acc = 0;
2480
+ for (let k = 0; k < n2; k++) {
2481
+ const target = k / n2 * total2;
2482
+ while (acc + lens[seg] < target && seg < ring.length - 1) acc += lens[seg++];
2483
+ const f = lens[seg] > 0 ? (target - acc) / lens[seg] : 0;
2484
+ const a2 = ring[seg];
2485
+ const b2 = ring[(seg + 1) % ring.length];
2486
+ out.push({ x: a2.x + (b2.x - a2.x) * f, y: a2.y + (b2.y - a2.y) * f });
2487
+ }
2488
+ return out;
2489
+ };
2490
+ let stack = [];
2491
+ let stackAt = { x: 0, y: 0 };
2492
+ let cycling = false;
2493
+ const announce = (cell, behind) => {
2494
+ current = cell;
2495
+ focusOn(cell, behind ? stack.slice(0, behind.index) : []);
2496
+ if (cell < 0 || !onHover) return onHover?.(null);
2497
+ const g = cells[cell];
2498
+ const { x, z } = at(g.week, g.day);
2499
+ const top = topOf(cell);
2500
+ camera.updateMatrixWorld();
2501
+ const right = new THREE.Vector3().setFromMatrixColumn(camera.matrixWorld, 0);
2502
+ const origin = toCss(new THREE.Vector3(x, 0, z));
2503
+ const unit = Math.hypot(toCss(new THREE.Vector3(x, 0, z).add(right)).x - origin.x, toCss(new THREE.Vector3(x, 0, z).add(right)).y - origin.y);
2504
+ const corners2 = [];
2505
+ for (const b of picks) {
2506
+ if (b.cell !== cell) continue;
2507
+ const r = b.pit ? 0.16 : Math.min(0.16, (b.y1 - b.y0) / 2.2);
2508
+ for (const dx of [-1, 1]) for (const dz of [-1, 1]) for (const y of b.pit ? [0] : [b.y0 + r, b.y1 - r]) {
2509
+ const p = toCss(new THREE.Vector3(x + dx * (0.46 - r), y, z + dz * (0.46 - r)));
2510
+ for (let k = 0; k < 10; k++) corners2.push({ x: p.x + r * unit * Math.cos(k / 10 * Math.PI * 2), y: p.y + r * unit * Math.sin(k / 10 * Math.PI * 2) });
2511
+ }
2512
+ }
2513
+ const c = toCss(new THREE.Vector3(x, top, z));
2514
+ onHover({ index: cell, date: g.date, top: g.value, bottom: layout.bottom.cells[cell]?.value ?? 0, outline: resample(hull(corners2), 64).map((p) => `${p.x.toFixed(1)},${p.y.toFixed(1)}`).join(" "), x: c.x, y: c.y, behind });
2515
+ };
2516
+ const onMove = (e) => {
2517
+ if (e.pointerType === "touch" || settling) return;
2518
+ if (cycling && Math.hypot(e.clientX - stackAt.x, e.clientY - stackAt.y) > 8) {
2519
+ cycling = false;
2520
+ pinned = false;
2521
+ }
2522
+ if (pinned) return;
2523
+ const here = pickAll(e.clientX, e.clientY);
2524
+ const cell = here[0] ?? -1;
2525
+ if (cell !== current) {
2526
+ stack = here;
2527
+ stackAt = { x: e.clientX, y: e.clientY };
2528
+ announce(cell, here.length > 1 ? { index: 0, count: here.length } : void 0);
2529
+ }
2530
+ };
2531
+ const onLeave = () => {
2532
+ if (!pinned && current !== -1) announce(-1);
2533
+ };
2534
+ const onDown = (e) => {
2535
+ if (settling) return;
2536
+ const here = pickAll(e.clientX, e.clientY);
2537
+ const sameSpot = Math.hypot(e.clientX - stackAt.x, e.clientY - stackAt.y) <= 8 && stack.length > 1;
2538
+ if (e.pointerType !== "touch") {
2539
+ if (here.length < 2) return;
2540
+ if (!sameSpot || !stack.includes(current)) {
2541
+ stack = here;
2542
+ stackAt = { x: e.clientX, y: e.clientY };
2543
+ }
2544
+ const next = (Math.max(0, stack.indexOf(current)) + 1) % stack.length;
2545
+ cycling = true;
2546
+ pinned = true;
2547
+ announce(stack[next], { index: next, count: stack.length });
2548
+ return;
2549
+ }
2550
+ if (pinned && sameSpot && current >= 0) {
2551
+ const next = stack.indexOf(current) + 1;
2552
+ if (next < stack.length) return announce(stack[next], { index: next, count: stack.length });
2553
+ pinned = false;
2554
+ return announce(-1);
2555
+ }
2556
+ const cell = here[0] ?? -1;
2557
+ stack = here;
2558
+ stackAt = { x: e.clientX, y: e.clientY };
2559
+ pinned = cell !== -1 && cell !== current;
2560
+ announce(pinned ? cell : -1, pinned && here.length > 1 ? { index: 0, count: here.length } : void 0);
2561
+ };
2562
+ const onKey = (e) => {
2563
+ const last = cells.length - 1;
2564
+ let next = current;
2565
+ if (e.key === "Escape") {
2566
+ pinned = false;
2567
+ return announce(-1);
2568
+ }
2569
+ const step = { ArrowLeft: -7, ArrowRight: 7, ArrowUp: -1, ArrowDown: 1 }[e.key];
2570
+ if (step === void 0) return;
2571
+ e.preventDefault();
2572
+ next = current < 0 ? last : Math.min(last, Math.max(0, current + step));
2573
+ pinned = true;
2574
+ announce(next);
2575
+ };
2576
+ el.tabIndex = -1;
2577
+ dom.addEventListener("pointermove", onMove);
2578
+ dom.addEventListener("pointerleave", onLeave);
2579
+ dom.addEventListener("pointerdown", onDown);
2580
+ el.addEventListener("keydown", onKey);
2581
+ el.addEventListener("blur", onLeave);
2582
+ let first = true;
2583
+ let resizeTimer = 0;
2584
+ let seenW = 0;
2585
+ let seenH = 0;
2586
+ const ro = new ResizeObserver(() => {
2587
+ if (first) {
2588
+ first = false;
2589
+ seenW = el.clientWidth;
2590
+ seenH = el.clientHeight;
2591
+ fit();
2592
+ return;
2593
+ }
2594
+ if (Math.abs(el.clientWidth - seenW) < 1 && Math.abs(el.clientHeight - seenH) < 1) return;
2595
+ seenW = el.clientWidth;
2596
+ seenH = el.clientHeight;
2597
+ soften();
2598
+ holdSize();
2599
+ pinned = false;
2600
+ if (current !== -1) announce(-1);
2601
+ window.clearTimeout(resizeTimer);
2602
+ resizeTimer = window.setTimeout(fit, 180);
2603
+ });
2604
+ ro.observe(el);
2605
+ const rethink = (recolour = false) => cm(() => rethinkBody(recolour));
2606
+ const rethinkBody = (recolour) => {
2607
+ if (!recolour) renderer.domElement.style.transition = "none";
2608
+ soften(recolour ? "0.85" : "0");
2609
+ pinned = false;
2610
+ if (current !== -1) announce(-1);
2611
+ floor.material.color.copy(pageColour());
2612
+ if (isDark() && !templates && !templatesFailed) {
2613
+ cancelAnimationFrame(raf);
2614
+ raf = 0;
2615
+ void wantTemplates().then(() => !cancelled && rethink(recolour));
2616
+ return;
2617
+ }
2618
+ buildBlocks();
2619
+ prepareNeon(recolour);
2620
+ restart();
2621
+ };
2622
+ const onScheme = () => st.theme === "auto" && rethink(false);
2623
+ mq.addEventListener("change", onScheme);
2624
+ api.rethink = (recolour) => rethink(recolour);
2625
+ api.stop = () => {
2626
+ stopNeon();
2627
+ hum.stop();
2628
+ window.clearTimeout(focusTimer);
2629
+ window.clearTimeout(focusRaf);
2630
+ cancelAnimationFrame(raf);
2631
+ window.clearTimeout(resizeTimer);
2632
+ dom.removeEventListener("pointermove", onMove);
2633
+ dom.removeEventListener("pointerleave", onLeave);
2634
+ dom.removeEventListener("pointerdown", onDown);
2635
+ el.removeEventListener("keydown", onKey);
2636
+ el.removeEventListener("blur", onLeave);
2637
+ onHover?.(null);
2638
+ ro.disconnect();
2639
+ mq.removeEventListener("change", onScheme);
2640
+ el.removeAttribute("tabindex");
2641
+ blocks.traverse((o) => {
2642
+ o.geometry?.dispose();
2643
+ o.userData.dispose?.();
2644
+ });
2645
+ boxes.forEach((g) => g.dispose());
2646
+ blockMaterial.dispose();
2647
+ coreMaterial.dispose();
2648
+ glowMaterial.dispose();
2649
+ levelTex.dispose();
2650
+ viewObserver?.disconnect();
2651
+ templates?.texture.dispose();
2652
+ tileUnlit.dispose();
2653
+ sceneRT.dispose();
2654
+ accumRT.dispose();
2655
+ [halfA, halfB, quarterA, quarterB].forEach((t) => t.dispose());
2656
+ env.dispose();
2657
+ pmrem.dispose();
2658
+ renderer.dispose();
2659
+ renderer.domElement.remove();
2660
+ };
2661
+ });
2662
+ })().catch((e) => console.error("[neon-activity-graph]", e));
2663
+ return {
2664
+ stop() {
2665
+ cancelled = true;
2666
+ api.stop();
2667
+ el.removeAttribute("role");
2668
+ el.removeAttribute("aria-roledescription");
2669
+ el.removeAttribute("aria-label");
2670
+ },
2671
+ rethink: (recolour) => api.rethink(recolour),
2672
+ bounds: () => api.bounds(),
2673
+ ready
2674
+ };
2675
+ }
2676
+
2677
+ // src/overlay-math.ts
2678
+ function outlinePath(outline) {
2679
+ const pts = outline.trim().split(/\s+/).filter(Boolean);
2680
+ return pts.length ? `M${pts.join("L").replaceAll(",", " ")}Z` : "";
2681
+ }
2682
+ function formatDay(date, locale) {
2683
+ return (/* @__PURE__ */ new Date(`${date}T00:00:00Z`)).toLocaleDateString(locale, { weekday: "short", day: "numeric", month: "short", year: "numeric", timeZone: "UTC" });
2684
+ }
2685
+ function cardPosition(info, box, card, gap = 14, margin = 8) {
2686
+ const half = card.width / 2;
2687
+ const x = box.width > card.width + 2 * margin ? Math.min(Math.max(info.x, half + margin), box.width - half - margin) : box.width / 2;
2688
+ const below = info.y - card.height - gap < 0;
2689
+ return { x: x - half, y: below ? info.y + gap : info.y - card.height - gap, below };
2690
+ }
2691
+ function formatValue(v) {
2692
+ return Number.isInteger(v) ? String(v) : v.toFixed(1);
2693
+ }
2694
+
2695
+ // src/overlay.ts
2696
+ function createHoverOverlay(container, options = {}, labels = () => ({})) {
2697
+ const { outline = true, card = true, locale } = options;
2698
+ if (getComputedStyle(container).position === "static") container.style.position = "relative";
2699
+ const root = document.createElement("div");
2700
+ root.className = "nag-overlay";
2701
+ root.style.cssText = "position:absolute;inset:0;pointer-events:none;z-index:2;overflow:clip";
2702
+ root.innerHTML = `<style>
2703
+ .nag-overlay{--nag-top-default:#0a8f2c;--nag-bottom-default:#1a6fe0}
2704
+ @media (prefers-color-scheme:dark){.nag-overlay{--nag-top-default:#3ddc6a;--nag-bottom-default:#5aa9ff}}
2705
+ .nag-outline{fill:var(--nag-outline-fill,color-mix(in srgb,currentColor 7%,transparent));stroke:var(--nag-outline,currentColor);stroke-width:1.5;stroke-linejoin:round}
2706
+ .nag-card{position:absolute;left:0;top:0;padding:10px 14px;min-width:9.5em;border-radius:var(--nag-card-radius,12px);color:var(--nag-card-fg,inherit);font:13px/1.35 system-ui,sans-serif;white-space:nowrap;background:var(--nag-card-bg,color-mix(in srgb,Canvas 70%,transparent));-webkit-backdrop-filter:blur(12px);backdrop-filter:blur(12px);box-shadow:inset 0 0 0 1px color-mix(in srgb,currentColor 11%,transparent),0 14px 44px -12px rgb(0 0 0/.38),0 2px 10px -4px rgb(0 0 0/.22);transition:opacity .16s,transform .3s cubic-bezier(.2,.7,.2,1)}
2707
+ .nag-card .nag-day{font-size:11px;letter-spacing:.06em;text-transform:uppercase;color:var(--nag-card-muted,color-mix(in srgb,currentColor 60%,transparent))}
2708
+ .nag-card .nag-figs{display:flex;gap:22px;margin-top:8px}
2709
+ .nag-card .nag-v{font-size:26px;font-weight:600;line-height:1;font-variant-numeric:tabular-nums}
2710
+ .nag-card .nag-l{margin-top:4px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--nag-card-muted,color-mix(in srgb,currentColor 60%,transparent))}
2711
+ .nag-card .nag-top{color:var(--nag-top,var(--nag-top-default))}.nag-card .nag-bottom{color:var(--nag-bottom,var(--nag-bottom-default))}
2712
+ .nag-card .nag-behind{margin-top:10px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--nag-card-muted,color-mix(in srgb,currentColor 60%,transparent))}
2713
+ @media (prefers-reduced-motion:reduce){.nag-card{transition:opacity .16s}}
2714
+ </style>`;
2715
+ const svg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
2716
+ svg.setAttribute("aria-hidden", "true");
2717
+ svg.style.cssText = "position:absolute;inset:0;width:100%;height:100%;overflow:visible;opacity:0;transition:opacity .12s";
2718
+ const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
2719
+ path.setAttribute("class", "nag-outline");
2720
+ svg.append(path);
2721
+ if (outline) root.append(svg);
2722
+ const cardEl = document.createElement("div");
2723
+ cardEl.className = "nag-card";
2724
+ cardEl.style.opacity = "0";
2725
+ if (card) root.append(cardEl);
2726
+ const live = document.createElement("p");
2727
+ live.setAttribute("aria-live", "polite");
2728
+ live.style.cssText = "position:absolute;width:1px;height:1px;overflow:hidden;clip:rect(0 0 0 0);white-space:nowrap;margin:0";
2729
+ root.append(live);
2730
+ container.append(root);
2731
+ const fill = (info) => {
2732
+ if (typeof card === "function") {
2733
+ const c = card(info);
2734
+ return void (typeof c === "string" ? cardEl.textContent = c : cardEl.replaceChildren(c));
2735
+ }
2736
+ const l = labels();
2737
+ const fig = (cls, v, name, unit) => `<div class="${cls}"><div class="nag-v">${formatValue(v)}${unit && unit.length <= 2 ? `<span style="font-size:13px;font-weight:400"> ${unit}</span>` : ""}</div><div class="nag-l">${name ?? ""}</div></div>`;
2738
+ const esc = (s) => (s ?? "").replace(/[&<>"]/g, (c) => ({ "&": "&amp;", "<": "&lt;", ">": "&gt;", '"': "&quot;" })[c]);
2739
+ cardEl.innerHTML = `<div class="nag-day">${esc(formatDay(info.date, locale))}</div><div class="nag-figs">${fig("nag-top", info.top, esc(l.top?.label), l.top?.unit)}${fig("nag-bottom", info.bottom, esc(l.bottom?.label), l.bottom?.unit)}</div>${info.behind && info.behind.count > 1 ? `<div class="nag-behind">${info.behind.index + 1} of ${info.behind.count} \xB7 click for next</div>` : ""}`;
2740
+ };
2741
+ let seen = false;
2742
+ return {
2743
+ update(info) {
2744
+ if (!info) {
2745
+ svg.style.opacity = "0";
2746
+ cardEl.style.opacity = "0";
2747
+ live.textContent = "";
2748
+ return;
2749
+ }
2750
+ path.setAttribute("d", outlinePath(info.outline));
2751
+ svg.style.opacity = "1";
2752
+ if (card) {
2753
+ fill(info);
2754
+ const p = cardPosition(info, { width: container.clientWidth, height: container.clientHeight }, { width: cardEl.offsetWidth, height: cardEl.offsetHeight });
2755
+ if (!seen) cardEl.style.transition = "opacity .16s";
2756
+ cardEl.style.transform = `translate(${p.x}px, ${p.y}px)`;
2757
+ cardEl.style.opacity = "1";
2758
+ if (!seen) requestAnimationFrame(() => cardEl.style.transition = "");
2759
+ seen = true;
2760
+ }
2761
+ live.textContent = `${formatDay(info.date, locale)}: ${formatValue(info.top)} and ${formatValue(info.bottom)}`;
2762
+ },
2763
+ destroy() {
2764
+ root.remove();
2765
+ }
2766
+ };
2767
+ }
2768
+
2769
+ // src/sound.ts
2770
+ var ctx = null;
2771
+ var master = null;
2772
+ function cling(size = "small") {
2773
+ try {
2774
+ const AC = window.AudioContext ?? window.webkitAudioContext;
2775
+ if (!AC) return;
2776
+ if (!ctx) {
2777
+ ctx = new AC();
2778
+ master = ctx.createGain();
2779
+ master.gain.value = 1;
2780
+ master.connect(ctx.destination);
2781
+ }
2782
+ if (ctx.state === "suspended") void ctx.resume().catch(() => {
2783
+ });
2784
+ const when = ctx.currentTime + 0.01;
2785
+ const pitch = 2700 + Math.random() * 650;
2786
+ if (size === "big") {
2787
+ bell(ctx, master, when, 1e3 + Math.random() * 150, 0, 2.6);
2788
+ bell(ctx, master, when + 0.03, pitch, 0, 1.6);
2789
+ } else {
2790
+ bell(ctx, master, when, pitch, 0, 1.2);
2791
+ }
2792
+ } catch {
2793
+ }
2794
+ }
2795
+
2796
+ // src/index.ts
2797
+ function createActivityGraph(container, options) {
2798
+ const state = { theme: options.theme ?? "auto" };
2799
+ let opts = options;
2800
+ const strips0 = options.strips ?? 1;
2801
+ const geometryOf = (data) => {
2802
+ const known = data ? layoutGraph(data, options.weeks ?? 53) : null;
2803
+ return { shifts: known && strips0 > 1 ? shiftsFromLayers([known.top, known.bottom], strips0) : void 0, tallest: known ? tallestOfLayers(known.top, known.bottom) : void 0 };
2804
+ };
2805
+ let { shifts, tallest } = geometryOf(options.data);
2806
+ const isDarkTheme = () => state.theme === "auto" ? typeof matchMedia === "undefined" ? void 0 : matchMedia("(prefers-color-scheme: dark)").matches : state.theme === "dark";
2807
+ const holder = options.placeholder === false ? null : mountPlaceholder(container, { weeks: options.weeks, strips: options.strips, shifts, tallest, dark: isDarkTheme() });
2808
+ const overlay = options.overlay ? createHoverOverlay(container, options.overlay === true ? {} : options.overlay, () => ({ top: opts.data?.top, bottom: opts.data?.bottom })) : null;
2809
+ const wrap = (o) => ({
2810
+ ...o,
2811
+ onLayout,
2812
+ onReady: () => {
2813
+ holder?.fadeOut();
2814
+ o.onReady?.();
2815
+ },
2816
+ onHover: (i) => {
2817
+ overlay?.update(i);
2818
+ o.onHover?.(i);
2819
+ }
2820
+ });
2821
+ let sceneOpts = null;
2822
+ const start = () => opts.data ? mountScene(container, sceneOpts = wrap({ ...opts, data: opts.data }), state) : { stop() {
2823
+ }, rethink() {
2824
+ }, bounds: () => null, ready: Promise.resolve() };
2825
+ let measured = false;
2826
+ const predict = () => {
2827
+ if (measured || !container.clientWidth || !container.clientHeight) return;
2828
+ const b = predictBounds(options.weeks ?? 53, options.strips ?? 1, container.clientWidth, container.clientHeight, tallest, shifts);
2829
+ for (const [k, v] of Object.entries(b)) container.style.setProperty(`--nag-content-${k}`, `${v.toFixed(1)}px`);
2830
+ };
2831
+ predict();
2832
+ const predictObserver = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(predict);
2833
+ predictObserver?.observe(container);
2834
+ const onLayout = (b) => {
2835
+ measured = true;
2836
+ predictObserver?.disconnect();
2837
+ options.onLayout?.(b);
2838
+ };
2839
+ let handle = start();
2840
+ let destroyed = false;
2841
+ let colorTimer = 0;
2842
+ let colorDirty = false;
2843
+ return {
2844
+ get bounds() {
2845
+ return handle.bounds();
2846
+ },
2847
+ get ready() {
2848
+ return handle.ready;
2849
+ },
2850
+ update(data) {
2851
+ if (destroyed) return;
2852
+ ({ shifts, tallest } = geometryOf(data));
2853
+ holder?.setGeometry({ shifts, tallest });
2854
+ predict();
2855
+ handle.stop();
2856
+ opts = { ...opts, data };
2857
+ handle = start();
2858
+ },
2859
+ cling(size) {
2860
+ if (!destroyed && options.sound !== false && isDarkTheme()) cling(size);
2861
+ },
2862
+ setColors(colors) {
2863
+ if (destroyed) return;
2864
+ opts = { ...opts, colors: { top: { ...opts.colors?.top, ...colors.top }, bottom: { ...opts.colors?.bottom, ...colors.bottom } } };
2865
+ if (sceneOpts) sceneOpts.colors = opts.colors;
2866
+ if (colorTimer) {
2867
+ colorDirty = true;
2868
+ return;
2869
+ }
2870
+ handle.rethink(true);
2871
+ const settle = () => {
2872
+ colorTimer = 0;
2873
+ if (!colorDirty || destroyed) return;
2874
+ colorDirty = false;
2875
+ handle.rethink(true);
2876
+ colorTimer = window.setTimeout(settle, 120);
2877
+ };
2878
+ colorTimer = window.setTimeout(settle, 120);
2879
+ },
2880
+ setTheme(theme) {
2881
+ if (destroyed) return;
2882
+ state.theme = theme;
2883
+ holder?.setDark(isDarkTheme());
2884
+ handle.rethink();
2885
+ },
2886
+ destroy() {
2887
+ destroyed = true;
2888
+ window.clearTimeout(colorTimer);
2889
+ handle.stop();
2890
+ predictObserver?.disconnect();
2891
+ holder?.remove();
2892
+ overlay?.destroy();
2893
+ }
2894
+ };
2895
+ }
2896
+
2897
+ export {
2898
+ renderSize,
2899
+ DEFAULT_COLORS,
2900
+ outlinePath,
2901
+ formatDay,
2902
+ cardPosition,
2903
+ createHoverOverlay,
2904
+ createActivityGraph
2905
+ };
2906
+ //# sourceMappingURL=chunk-METLYI5N.js.map