@cesarvenzac/figures 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.
package/dist/react.js ADDED
@@ -0,0 +1,796 @@
1
+ "use client";
2
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
3
+ import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react";
4
+ import { BLINK_FOR, COLOURWAYS, ENERGY, FACE_KEYS, FACES, FLAT, hashOf, INK, LOOK_KEYS, LOOKS, MOOD, OFF_LOOK, ONCE, ONCE_FOR, reactionTo, springStep, swellAt, } from "./figure.js";
5
+ import { actLoopAt } from "./figure-acts.js";
6
+ import { easeInOut, span } from "./figure-curves.js";
7
+ import { drawFigure, MOST_PIXELS, NOT_YET, shaderState, watchShader } from "./figure-gl.js";
8
+ import { animate } from "./figure-loop.js";
9
+ import { bodyLoopAt, combine, loopActAt, moveAt, REST_YAW, stopFor, SWITCH_AT, thinkingAt, THINKING_CYCLE, TURN_BY } from "./figure-motion.js";
10
+ import { eventToWatch, gazeAt, glanceTarget, WATCH_FOR, watchedBy } from "./figure-peers.js";
11
+ import { blendBody, REST } from "./figure-pose.js";
12
+ import { sceneFor } from "./figure-scene.js";
13
+ import { paletteThrough } from "./figure-space.js";
14
+ import { applyMove, cellsOf, solved } from "./rubik.js";
15
+ /**
16
+ * The figures in React: `AgentFigure`, one live and in 3D, and `AgentDot`, its colours alone.
17
+ * Client components; nothing else to load, no stylesheet.
18
+ */
19
+ const joined = (...names) => names.filter(Boolean).join(" ") || undefined;
20
+ const REDUCE = "(prefers-reduced-motion: reduce)";
21
+ const subscribeToMotion = (callback) => {
22
+ const query = window.matchMedia(REDUCE);
23
+ query.addEventListener("change", callback);
24
+ return () => query.removeEventListener("change", callback);
25
+ };
26
+ /** Whether the visitor asked for less motion: false on the server and while hydrating, then their setting, kept current. */
27
+ const useReducedMotion = () => useSyncExternalStore(subscribeToMotion, () => window.matchMedia(REDUCE).matches, () => false);
28
+ /** Where the page's shader stands (figure-gl.ts): being made ready, as the server has it, until the browser says. */
29
+ const useShader = () => useSyncExternalStore(watchShader, shaderState, () => NOT_YET);
30
+ /** True while the element is in the viewport and the tab is in front. */
31
+ function useOnScreen(ref) {
32
+ const [onScreen, setOnScreen] = useState(false);
33
+ useEffect(() => {
34
+ const element = ref.current;
35
+ if (!element)
36
+ return;
37
+ let intersecting = false;
38
+ const update = () => setOnScreen(intersecting && !document.hidden);
39
+ const observer = new IntersectionObserver(([entry]) => {
40
+ intersecting = entry.isIntersecting;
41
+ update();
42
+ });
43
+ observer.observe(element);
44
+ document.addEventListener("visibilitychange", update);
45
+ return () => {
46
+ observer.disconnect();
47
+ document.removeEventListener("visibilitychange", update);
48
+ };
49
+ }, [ref]);
50
+ return onScreen;
51
+ }
52
+ /** The canvas is this much bigger than the figure's box, for its halo, its shadow, its hops and what it throws off. */
53
+ const CANVAS = 1.5;
54
+ /** How long after the pointer last moved the figures stop following it and look at each other again, in ms. */
55
+ const POINTER_FRESH = 1600;
56
+ /** How long a loop's body takes to turn into the next loop's, in ms. */
57
+ const BLEND = 500;
58
+ /** A walking hop's height at its top, in world units (the figure's box is 2 wide): lower than a hop on the spot (0.34). */
59
+ const WALK_LIFT = 0.22;
60
+ // One pointer for every figure on the page: a listener while any is looking, a frame at a time.
61
+ let pointer = null;
62
+ const lookers = new Set();
63
+ let pointerFrame = 0;
64
+ function onMove(event) {
65
+ if (event.pointerType === "touch")
66
+ return;
67
+ pointer = { x: event.clientX, y: event.clientY, at: performance.now() };
68
+ pointerFrame ||= requestAnimationFrame(() => {
69
+ pointerFrame = 0;
70
+ for (const look of lookers)
71
+ look();
72
+ });
73
+ }
74
+ function follow(look) {
75
+ if (!lookers.size)
76
+ window.addEventListener("pointermove", onMove, { passive: true });
77
+ lookers.add(look);
78
+ return () => {
79
+ lookers.delete(look);
80
+ if (!lookers.size)
81
+ window.removeEventListener("pointermove", onMove);
82
+ };
83
+ }
84
+ // Every moving figure on the page, as the others see it (lib/agents/figure-peers.ts).
85
+ const peers = new Map();
86
+ let nextPeer = 1;
87
+ function boxOf(element) {
88
+ const box = element.getBoundingClientRect();
89
+ return { x: box.left, y: box.top, width: box.width, height: box.height };
90
+ }
91
+ /** Tells the other figures to look at this one for a moment. */
92
+ function announce(id) {
93
+ const peer = peers.get(id);
94
+ if (!peer)
95
+ return;
96
+ peer.event = performance.now() + WATCH_FOR;
97
+ // The page may have scrolled since: where everyone is, now.
98
+ for (const each of peers.values())
99
+ each.box = boxOf(each.element);
100
+ }
101
+ // Colours as the shader takes them, worked out once a colour: any CSS colour, a custom property
102
+ // (`var(--name)`) read from the page's root.
103
+ const linears = new Map();
104
+ const palettes = new Map();
105
+ function linearOf(css) {
106
+ const known = linears.get(css);
107
+ if (known)
108
+ return known;
109
+ const variable = /^var\(\s*(--[\w-]+)\s*(?:,\s*(.+))?\)$/.exec(css.trim());
110
+ const colour = variable ? getComputedStyle(document.documentElement).getPropertyValue(variable[1]).trim() || variable[2] || "" : css;
111
+ const context = document.createElement("canvas").getContext("2d", { willReadFrequently: true });
112
+ context.fillStyle = colour || "#888";
113
+ context.fillRect(0, 0, 1, 1);
114
+ const [r, g, b] = context.getImageData(0, 0, 1, 1).data;
115
+ const made = [r, g, b].map((v) => {
116
+ const c = v / 255;
117
+ return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;
118
+ });
119
+ linears.set(css, made);
120
+ return made;
121
+ }
122
+ function paletteOf(colours) {
123
+ const key = `${colours.main}|${colours.light}|${colours.deep}`;
124
+ const known = palettes.get(key);
125
+ if (known)
126
+ return known;
127
+ const made = paletteThrough(linearOf(colours.main), linearOf(colours.light), linearOf(colours.deep));
128
+ palettes.set(key, made);
129
+ return made;
130
+ }
131
+ /** How long the 3D drawing takes to fade in, over the flat one when that was there, in ms. */
132
+ const FADE = 300;
133
+ const FADING = `opacity ${FADE}ms cubic-bezier(0.22, 1, 0.36, 1)`;
134
+ /** The canvas's own styles, overhanging the figure's box on every side and letting the pointer through; it fades in once it has drawn. */
135
+ const CANVAS_STYLE = { position: "absolute", left: "-25%", top: "-25%", width: "150%", height: "150%", pointerEvents: "none", opacity: 0, transition: FADING };
136
+ const LIT_STYLE = { ...CANVAS_STYLE, opacity: 1 };
137
+ const wait = (from, to) => from + Math.random() * (to - from);
138
+ const sprungFrom = (look) => Object.fromEntries(LOOK_KEYS.map((key) => [key, { value: look[key], velocity: 0 }]));
139
+ const valuesOf = (sprung) => Object.fromEntries(LOOK_KEYS.map((key) => [key, sprung[key].value]));
140
+ /**
141
+ * An agent's figure (figure.ts), `size` pixels square: a cube, a sphere, a pyramid, a
142
+ * block or a cloud, really in 3D, in the original Aura's iridescent material in its colourway,
143
+ * with two eyes painted on its face, drawn by one shader for the whole page (figure-gl.ts).
144
+ *
145
+ * Its state (`mood`) gives its expression and how it moves, the shape's own act included (the
146
+ * cube's Rubik's turns as it thinks, the block's dials as wheels at work, z's asleep: figure-acts
147
+ * ts); and as its state changes it reacts, the shape its own way: a run finished, it celebrates;
148
+ * failed, it fails; work starting, it gets going; switched off, it dozes off; on again, it wakes.
149
+ * Clicked (`pet`), it's petted, and doesn't open the card it's on. `expression` and `motion` set
150
+ * its face and loop outright (the editor's preview), `play` a move to make now.
151
+ *
152
+ * It holds its head as its expression does, blinks, glances, sways, turns toward the pointer on a
153
+ * desktop (`look`; every figure but a switched-off one), looks at the others on the page when one
154
+ * of them has a moment and now and then at whichever is busy, does its habit while it waits, and
155
+ * smiles with a small bounce when the card it's on is hovered (`react`). `grab` lets it be turned
156
+ * by hand, springing back when let go. `aim` turns its eyes somewhere of its own in place of the
157
+ * pointer and the others' glances (the Lab's playground: at whoever it's talking to), and `lift`
158
+ * hops it off the ground as it walks, its shadow staying there. Its energy scales every move;
159
+ * `drain` (0–1: an agent's budget running out, say) greys it. Its colours are its colourway's
160
+ * (`COLOURWAYS`) unless `colours` says otherwise, and its eyes `INK` unless `ink` does: any CSS
161
+ * colours, a custom property (`var(--name)`) read from the page's root once. All of it is worked
162
+ * out by figure-motion.ts, figure-acts.ts and figure-scene.ts on one frame loop for the page
163
+ * (figure-loop.ts); a still figure (`still`, reduced motion, off screen) is drawn once. Until the
164
+ * page's shader is ready (made ready without holding up the page: figure-gl.ts), it's its flat
165
+ * drawing, fading into the 3D one where it stands once that's drawn; where there's no WebGL 2 it
166
+ * stays flat. A drawing, hidden from assistive tech: the words beside it say who it is and what
167
+ * it's doing.
168
+ */
169
+ export function AgentFigure({ figure, mood = "idle", expression: asked, motion: askedMotion, play, size = 48, look = true, react = true, pet = true, still = false, grab = false, drain = 0, aim, lift, colours: given, ink = INK, className, style, }) {
170
+ const ref = useRef(null);
171
+ const canvasRef = useRef(null);
172
+ const onScreen = useOnScreen(ref);
173
+ const reduced = useReducedMotion();
174
+ const moving = onScreen && !reduced && !still;
175
+ const shader = useShader();
176
+ const ready = shader.readiness === "ready";
177
+ const generation = shader.generation;
178
+ // A canvas that can't be drawn on: the flat drawing, for good.
179
+ const [broken, setBroken] = useState(false);
180
+ const usable = shader.readiness !== "unavailable" && !broken;
181
+ // The shader's generation the canvas has drawn in, and the one whose fade has ended: the flat
182
+ // drawing stands in until then (from the server on, and while a lost context comes back), except
183
+ // for a figure that first came once the shader was ready, which fades in from nothing as before.
184
+ const [litIn, setLitIn] = useState(0);
185
+ const [shownIn, setShownIn] = useState(() => (ready ? generation : 0));
186
+ const lit = usable && ready && litIn === generation;
187
+ const flat = !usable || !ready || shownIn !== generation;
188
+ const litRef = useRef(0);
189
+ const [ratio, setRatio] = useState(2);
190
+ const [override, setOverride] = useState(null);
191
+ const state = MOOD[mood];
192
+ const expression = override ?? asked ?? state.expression;
193
+ const loop = askedMotion && !ONCE.includes(askedMotion) ? askedMotion : state.loop;
194
+ const energy = ENERGY[figure.energy];
195
+ const off = mood === "sleep";
196
+ const pixels = Math.min(MOST_PIXELS, Math.round(size * CANVAS * ratio));
197
+ const seed = hashOf(`${figure.shape}${figure.palette}${figure.habit}`);
198
+ const colours = given ?? COLOURWAYS[figure.palette];
199
+ const paint = `${colours.main}|${colours.light}|${colours.deep}|${ink}`;
200
+ const sim = useRef(null);
201
+ sim.current ??= {
202
+ face: { ...FACES[expression] },
203
+ glyphFrom: FACES[expression].glyph,
204
+ glyphTo: FACES[expression].glyph,
205
+ glyphMix: 0,
206
+ look: sprungFrom(off ? OFF_LOOK : LOOKS[expression]),
207
+ flow: (seed % 1000) / 100,
208
+ hue: 0,
209
+ arcAngle: 0,
210
+ rings: 0,
211
+ baseYaw: 0,
212
+ eyeYaw: 0,
213
+ trail: null,
214
+ playing: null,
215
+ body: { loop, from: loop, at: 0 },
216
+ act: { loop, from: 0, stop: null },
217
+ queued: null,
218
+ holdActs: 0,
219
+ cube: { key: "", cells: cellsOf(solved()) },
220
+ drag: { yaw: { value: 0, velocity: 0 }, pitch: { value: 0, velocity: 0 }, held: false },
221
+ busyUntil: 0,
222
+ };
223
+ const gaze = useRef({ x: 0, y: 0 });
224
+ const glance = useRef({ x: 0, y: 0, until: 0, next: 0 });
225
+ const watch = useRef({ x: 0, y: 0, until: 0, of: 0, moment: false, next: 0, back: 0 });
226
+ const hover = useRef({ until: 0, last: -Infinity });
227
+ const blink = useRef({ next: 0, start: -1 });
228
+ const peerId = useRef(0);
229
+ const lastMood = useRef(null);
230
+ // Read by the frame loop as they are now, without starting it again.
231
+ const aimRef = useRef(aim);
232
+ const liftRef = useRef(lift);
233
+ useEffect(() => {
234
+ aimRef.current = aim;
235
+ liftRef.current = lift;
236
+ }, [aim, lift]);
237
+ // How sharp to draw: the screen's own pixels, up to two a pixel.
238
+ useEffect(() => {
239
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- the screen's pixel ratio is only known in the browser.
240
+ setRatio(Math.min(2, Math.max(1, window.devicePixelRatio || 1)));
241
+ }, []);
242
+ /** Builds this moment's scene and draws it; false when there's no shader. */
243
+ const draw = (now, open = 1) => {
244
+ const canvas = canvasRef.current;
245
+ if (!canvas)
246
+ return true;
247
+ const s = sim.current;
248
+ const t = now / 1000;
249
+ const shape = figure.shape;
250
+ // The body's loop, turning from the last one into this one.
251
+ const blend = easeInOut(span(now, s.body.at, s.body.at + BLEND));
252
+ let pose = blend < 1 ? blendBody(bodyLoopAt(s.body.from, t, shape, energy.amp), bodyLoopAt(s.body.loop, t, shape, energy.amp), blend) : bodyLoopAt(s.body.loop, t, shape, energy.amp);
253
+ // The shape's own act, when it's moving: once one has gone home, the next begins.
254
+ let split = 0;
255
+ let turning = null;
256
+ if (moving && !still) {
257
+ let playing = loopActAt(s.act, now, shape, energy.speed);
258
+ if (!playing && s.queued) {
259
+ s.act = { loop: s.queued, from: Math.max(now, s.holdActs), stop: null };
260
+ s.queued = null;
261
+ playing = loopActAt(s.act, now, shape, energy.speed);
262
+ }
263
+ if (playing && playing.env > 0) {
264
+ if (s.act.loop === "think" && shape === "cube") {
265
+ // The cube's Rubik's turns: it splits, scrambles, solves itself and joins up each round.
266
+ const thinking = thinkingAt(playing.t, seed);
267
+ split = thinking.split;
268
+ const key = `${Math.floor(playing.t / THINKING_CYCLE)}:${thinking.done.length}`;
269
+ if (key !== s.cube.key)
270
+ s.cube = { key, cells: cellsOf(thinking.done.reduce(applyMove, solved())) };
271
+ if (thinking.turning)
272
+ turning = { axis: thinking.turning.move.axis, layer: thinking.turning.move.layer, angle: thinking.turning.angle };
273
+ }
274
+ else
275
+ pose = combine(pose, actLoopAt(s.act.loop, playing.t, shape, energy.amp, playing.env));
276
+ }
277
+ }
278
+ const playing = s.playing;
279
+ if (playing) {
280
+ const p = Math.min(1, (now - playing.start) / playing.duration);
281
+ pose = combine(pose, moveAt(playing.motion, p, shape, energy.amp));
282
+ }
283
+ // Turned by hand, and off the ground as it walks.
284
+ pose = { ...pose, yaw: pose.yaw + s.drag.yaw.value, pitch: pose.pitch + s.drag.pitch.value, lift: pose.lift + WALK_LIFT * (liftRef.current?.(now) ?? 0) };
285
+ let trailing = null;
286
+ if (shape === "sphere" && s.trail)
287
+ trailing = { yaw: s.trail.yaw.value, pitch: s.trail.pitch.value, roll: s.trail.roll.value };
288
+ const lookNow = valuesOf(s.look);
289
+ s.scene = sceneFor({
290
+ figure,
291
+ face: s.face,
292
+ glyph: s.glyphFrom,
293
+ glyphTo: s.glyphTo,
294
+ glyphMix: s.glyphMix,
295
+ open,
296
+ pose,
297
+ baseYaw: s.baseYaw,
298
+ eyeYaw: s.eyeYaw,
299
+ trailing,
300
+ look: lookNow,
301
+ flow: s.flow,
302
+ hue: s.hue,
303
+ arcAngle: s.arcAngle,
304
+ rings: s.rings,
305
+ time: t,
306
+ swell: swellAt(lookNow, t),
307
+ palette: paletteOf(colours),
308
+ split,
309
+ cells: split > 0 ? s.cube.cells : null,
310
+ turning,
311
+ ink: linearOf(ink),
312
+ drain,
313
+ }, s.scene);
314
+ if (!drawFigure(canvas, s.scene))
315
+ return false;
316
+ if (litRef.current !== generation) {
317
+ litRef.current = generation;
318
+ setLitIn(generation);
319
+ }
320
+ return true;
321
+ };
322
+ /** Drawn, or the flat drawing for good where the shader is ready and the canvas still can't be drawn on. */
323
+ const drawOrBreak = (now, open) => {
324
+ if (!draw(now, open) && shaderState().readiness === "ready")
325
+ setBroken(true);
326
+ };
327
+ // Once the 3D drawing has faded in, the flat one goes.
328
+ useEffect(() => {
329
+ if (!lit || shownIn === generation)
330
+ return;
331
+ const timer = setTimeout(() => setShownIn(generation), FADE);
332
+ return () => clearTimeout(timer);
333
+ }, [lit, shownIn, generation]);
334
+ // A still figure, drawn once as its expression has it, once the shader is ready (and again if the context comes back).
335
+ useEffect(() => {
336
+ if (moving || !ready || broken)
337
+ return;
338
+ const s = sim.current;
339
+ s.face = { ...FACES[expression] };
340
+ s.glyphFrom = s.glyphTo = FACES[expression].glyph;
341
+ s.glyphMix = 0;
342
+ s.look = sprungFrom(off ? OFF_LOOK : LOOKS[expression]);
343
+ s.playing = null;
344
+ s.trail = null;
345
+ // eslint-disable-next-line react-hooks/set-state-in-effect -- whether the canvas drew (and so fades in) is only known once it has.
346
+ drawOrBreak(performance.now());
347
+ // eslint-disable-next-line react-hooks/exhaustive-deps
348
+ }, [moving, ready, generation, broken, expression, figure.shape, paint, off, pixels, drain]);
349
+ // A new shape starts from its own front.
350
+ useEffect(() => {
351
+ const s = sim.current;
352
+ s.baseYaw = s.eyeYaw = 0;
353
+ s.trail = null;
354
+ s.playing = null;
355
+ }, [figure.shape]);
356
+ /** Starts a move now (from its start, if it's the one already under way). */
357
+ const start = (motion) => {
358
+ const s = sim.current;
359
+ if (s.playing?.motion === "turn" && !s.playing.switched)
360
+ return;
361
+ s.playing = { motion, start: performance.now(), duration: ONCE_FOR[motion] * energy.speed, from: s.baseYaw, switched: false };
362
+ };
363
+ // Its state changing: it reacts (a run finished, it celebrates…), and its loop turns into the
364
+ // next: the body at once, the shape's own act once the last one has come home and the reaction
365
+ // has played.
366
+ useEffect(() => {
367
+ const s = sim.current;
368
+ const now = performance.now();
369
+ const from = lastMood.current;
370
+ lastMood.current = mood;
371
+ if (from && from !== mood && moving) {
372
+ const reaction = reactionTo(from, mood);
373
+ if (reaction) {
374
+ start(reaction);
375
+ s.holdActs = now + ONCE_FOR[reaction] * energy.speed * 0.8;
376
+ if (reaction === "celebrate" || reaction === "fail")
377
+ announce(peerId.current);
378
+ }
379
+ }
380
+ if (s.body.loop !== loop)
381
+ s.body = { loop, from: s.body.loop, at: now };
382
+ if (s.act.loop === loop) {
383
+ // Asked back before it went: carry on.
384
+ if (s.act.stop !== null && loopActAt(s.act, now, figure.shape, energy.speed))
385
+ s.act.stop = null;
386
+ s.queued = null;
387
+ return;
388
+ }
389
+ if (loopActAt(s.act, now, figure.shape, energy.speed)?.env) {
390
+ s.act.stop ??= stopFor(s.act, now, figure.shape, energy.speed);
391
+ s.queued = loop;
392
+ }
393
+ else {
394
+ s.act = { loop, from: Math.max(now, s.holdActs), stop: null };
395
+ s.queued = null;
396
+ }
397
+ // eslint-disable-next-line react-hooks/exhaustive-deps
398
+ }, [mood, loop]);
399
+ // While it moves: the face tweens toward its expression, the eyes blink and glance, its Aura
400
+ // glows and flows, it makes its moves, and it's drawn, every frame while something's happening
401
+ // and every other one while it only breathes.
402
+ useEffect(() => {
403
+ if (!moving || !ready || broken)
404
+ return;
405
+ const s = sim.current;
406
+ const face = FACES[expression];
407
+ const target = off ? OFF_LOOK : LOOKS[expression];
408
+ blink.current.next = performance.now() + wait(600, 2600);
409
+ glance.current.next = performance.now() + wait(1500, 5000);
410
+ watch.current.next = performance.now() + wait(3000, 9000);
411
+ const phase = (seed % 628) / 100;
412
+ let frames = 0;
413
+ return animate((dt, now) => {
414
+ const t = now / 1000;
415
+ const g = glance.current;
416
+ if (!face.scan && !face.dx && figure.habit !== "look" && now > g.next)
417
+ Object.assign(g, { x: (Math.random() - 0.5) * 1.6, y: (Math.random() - 0.5) * 0.9, until: now + wait(700, 1300), next: now + wait(4000, 9000) });
418
+ // The others on the page: another's moment to turn to (before anything), or, while the
419
+ // pointer is still, a busy one to glance at, or one caught looking at this one to look back at.
420
+ const w = watch.current;
421
+ const self = peers.get(peerId.current);
422
+ const pointerFresh = pointer !== null && now - pointer.at < POINTER_FRESH;
423
+ if (self?.box) {
424
+ const moment = eventToWatch(self, peers.values(), now);
425
+ if (moment?.box) {
426
+ if (!w.moment || w.of !== moment.id)
427
+ Object.assign(w, { ...gazeAt(self.box, moment.box), of: moment.id, moment: true });
428
+ w.until = moment.event;
429
+ }
430
+ else if (!pointerFresh && now > w.until) {
431
+ const watcher = watchedBy(self, peers.values());
432
+ if (watcher?.box && w.back !== watcher.id) {
433
+ w.back = watcher.id;
434
+ if (Math.random() < 0.5)
435
+ Object.assign(w, { ...gazeAt(self.box, watcher.box), until: now + 900, of: watcher.id, moment: false });
436
+ }
437
+ else if (now > w.next) {
438
+ const busy = glanceTarget(self, [...peers.values()], Math.random);
439
+ if (busy?.box)
440
+ Object.assign(w, { ...gazeAt(self.box, busy.box), until: now + wait(1100, 1700), of: busy.id, moment: false });
441
+ w.next = now + wait(6000, 14000);
442
+ }
443
+ if (!watcher)
444
+ w.back = 0;
445
+ }
446
+ self.watching = now < w.until ? w.of : null;
447
+ }
448
+ const aimed = aimRef.current;
449
+ const watching = now < w.until && (w.moment || (!pointerFresh && !aimed));
450
+ // Where it looks, from −1 to 1 each way: the pointer, the others, a glance, scanning its work.
451
+ const scan = face.scan ? Math.sin(t * 2.3 + phase) : 0;
452
+ const toward = aimed ?? gaze.current;
453
+ const x = (watching ? w.x : toward.x) + (now < g.until ? g.x : 0) + scan;
454
+ const y = (watching ? w.y : toward.y) + (now < g.until ? g.y : 0);
455
+ const bob = face.bob ? Math.abs(Math.sin(t * 8.5 + phase)) : 0;
456
+ const amp = energy.amp;
457
+ const goal = {
458
+ ...face,
459
+ dx: face.dx + x * 0.035,
460
+ dy: face.dy - y * 0.025 + bob * 0.02,
461
+ // Watching another's moment, its eyes widen a little.
462
+ size: face.size + (face.pulse ? Math.sin(t * 3 + phase) * 0.03 : 0) + (watching && w.moment ? 0.08 : 0),
463
+ yaw: face.yaw + x * 22 + Math.sin(t * 0.6 + phase) * 3 * amp,
464
+ pitch: face.pitch - y * 14 + bob * 3 + Math.sin(t * 0.43 + phase * 2) * 2 * amp,
465
+ roll: face.roll + Math.sin(t * 0.37 + phase) * 1.5 * amp,
466
+ };
467
+ const k = 1 - Math.exp((-dt * 10) / energy.speed);
468
+ for (const key of FACE_KEYS)
469
+ s.face[key] += (goal[key] - s.face[key]) * k;
470
+ // The eyes' shape: a smile while hovered, else the expression's, morphing from one to the other.
471
+ const glyph = now < hover.current.until ? "arc" : face.glyph;
472
+ if (glyph !== s.glyphTo) {
473
+ s.glyphFrom = s.glyphMix > 0.5 ? s.glyphTo : s.glyphFrom;
474
+ s.glyphTo = glyph;
475
+ s.glyphMix = 0;
476
+ }
477
+ s.glyphMix = Math.min(1, s.glyphMix + dt * 6);
478
+ if (s.glyphMix >= 1)
479
+ s.glyphFrom = s.glyphTo;
480
+ let open = 1;
481
+ const b = blink.current;
482
+ if (face.blink !== "none" && s.glyphTo === "rect") {
483
+ if (b.start < 0 && now > b.next)
484
+ b.start = now;
485
+ if (b.start >= 0) {
486
+ const p = (now - b.start) / BLINK_FOR[face.blink];
487
+ if (p >= 1) {
488
+ b.start = -1;
489
+ // Now and then twice in a row.
490
+ b.next = now + (Math.random() < 0.18 ? 140 : wait(2400, 6200));
491
+ }
492
+ else
493
+ open = 1 - Math.sin(Math.PI * p) * 0.94;
494
+ }
495
+ }
496
+ // Its Aura springs toward the look, and flows.
497
+ for (const key of LOOK_KEYS)
498
+ s.look[key] = springStep(s.look[key], target[key], Math.min(dt, 1 / 30));
499
+ const speed = s.look.speed.value;
500
+ s.flow += (speed * dt) / energy.speed;
501
+ s.hue += (0.015 + speed * 0.03) * dt;
502
+ s.arcAngle += 0.85 * dt;
503
+ s.rings += 3.2 * dt;
504
+ // A move: when it's done, its turn is kept; halfway through a turn, the eyes move to the face coming round.
505
+ const playing = s.playing;
506
+ if (playing) {
507
+ const p = (now - playing.start) / playing.duration;
508
+ if (playing.motion === "turn" && !playing.switched && p >= SWITCH_AT && TURN_BY[figure.shape]) {
509
+ playing.switched = true;
510
+ s.eyeYaw = (playing.from + TURN_BY[figure.shape]) % 360;
511
+ }
512
+ if (p >= 1) {
513
+ if (playing.motion === "turn" && TURN_BY[figure.shape])
514
+ s.baseYaw = (playing.from + TURN_BY[figure.shape]) % 360;
515
+ s.playing = null;
516
+ }
517
+ }
518
+ // Turned by hand: springs home once let go.
519
+ if (!s.drag.held) {
520
+ s.drag.yaw = springStep(s.drag.yaw, 0, Math.min(dt, 1 / 30));
521
+ s.drag.pitch = springStep(s.drag.pitch, 0, Math.min(dt, 1 / 30));
522
+ }
523
+ // A sphere's eyes trail its turns a moment behind, catching up with a little overshoot.
524
+ if (figure.shape === "sphere") {
525
+ const pose = s.playing ? moveAt(s.playing.motion, Math.min(1, (now - s.playing.start) / s.playing.duration), "sphere", amp) : REST;
526
+ const angles = [REST_YAW.sphere + s.face.yaw + pose.yaw + s.drag.yaw.value, s.face.pitch + pose.pitch + s.drag.pitch.value, s.face.roll + pose.roll];
527
+ if (!s.trail)
528
+ s.trail = { yaw: { value: angles[0], velocity: 0 }, pitch: { value: angles[1], velocity: 0 }, roll: { value: angles[2], velocity: 0 }, seen: angles };
529
+ const trail = s.trail;
530
+ ["yaw", "pitch", "roll"].forEach((axis, i) => {
531
+ // A jump (a spin ending at a whole turn) moves the eyes with it, not round again.
532
+ const jump = angles[i] - trail.seen[i];
533
+ if (Math.abs(jump) > 90)
534
+ trail[axis].value += jump;
535
+ trail[axis] = trailStep(trail[axis], angles[i], Math.min(dt, 1 / 30));
536
+ });
537
+ trail.seen = angles;
538
+ }
539
+ else
540
+ s.trail = null;
541
+ // Drawn every frame while something's happening, every other while it only breathes.
542
+ frames++;
543
+ const acting = s.act.loop !== "breathe" && s.act.loop !== "float";
544
+ const walking = (liftRef.current?.(now) ?? 0) > 0;
545
+ const busy = s.playing || acting || s.queued || now < s.busyUntil || now < hover.current.until || now < w.until || s.drag.held || Math.abs(s.drag.yaw.value) > 0.5 || pointerFresh || walking;
546
+ if (!busy && frames % 2)
547
+ return;
548
+ drawOrBreak(now, open);
549
+ });
550
+ // eslint-disable-next-line react-hooks/exhaustive-deps
551
+ }, [moving, ready, generation, broken, expression, figure.shape, figure.habit, paint, energy.speed, energy.amp, off, pixels, drain]);
552
+ // A move asked for from outside, as it arrives.
553
+ useEffect(() => {
554
+ if (play && moving && ONCE.includes(play.motion)) {
555
+ start(play.motion);
556
+ if (play.motion === "pet" || play.motion === "celebrate" || play.motion === "fail")
557
+ announce(peerId.current);
558
+ }
559
+ // eslint-disable-next-line react-hooks/exhaustive-deps
560
+ }, [play, moving]);
561
+ // Its state's move, now and then (a pleased figure turns into a star for a beat).
562
+ useEffect(() => {
563
+ if (!moving || !state.now || asked)
564
+ return;
565
+ let timer;
566
+ const next = () => {
567
+ timer = setTimeout(() => {
568
+ if (!sim.current.playing)
569
+ start(state.now);
570
+ next();
571
+ }, wait(...(state.every ?? [6000, 12000])) * energy.speed);
572
+ };
573
+ next();
574
+ return () => clearTimeout(timer);
575
+ // eslint-disable-next-line react-hooks/exhaustive-deps
576
+ }, [moving, state.now, asked, energy.speed]);
577
+ // Its habit, while it waits: looking around, humming, napping, spinning, wobbling, shape-shifting.
578
+ useEffect(() => {
579
+ if (!moving || mood !== "idle" || asked)
580
+ return;
581
+ let timer;
582
+ let shifts = 0;
583
+ const steps = (list) => {
584
+ let i = 0;
585
+ const step = () => {
586
+ if (i >= list.length)
587
+ return next();
588
+ const [act, hold] = list[i++];
589
+ act();
590
+ timer = setTimeout(step, hold);
591
+ };
592
+ step();
593
+ };
594
+ const lookTo = (x, y, hold) => () => Object.assign(glance.current, { x, y, until: performance.now() + hold, next: Infinity });
595
+ const next = () => {
596
+ timer = setTimeout(() => {
597
+ if (figure.habit === "look")
598
+ steps([[lookTo(-1, 0.2, 1000), 1000], [lookTo(1, -0.25, 1000), 1000], [lookTo(0, 0, 0), 0]]);
599
+ else if (figure.habit === "hum")
600
+ steps([[() => setOverride("speaking"), 2200], [() => setOverride(null), 0]]);
601
+ else if (figure.habit === "nap")
602
+ steps([[() => setOverride("tired"), 2400], [() => setOverride("sleeping"), 4200], [() => setOverride(null), 0]]);
603
+ else {
604
+ if (!sim.current.playing)
605
+ start(figure.habit === "morph" ? (shifts++ % 2 ? "pop" : "melt") : figure.habit === "spin" ? "spin" : "wave");
606
+ next();
607
+ }
608
+ }, figure.habit === "look" ? wait(3500, 7000) : wait(7000, 13000));
609
+ };
610
+ next();
611
+ return () => {
612
+ clearTimeout(timer);
613
+ setOverride(null);
614
+ };
615
+ // eslint-disable-next-line react-hooks/exhaustive-deps
616
+ }, [moving, mood, asked, figure.habit]);
617
+ // Hovering the card it's on: a smile and a small bounce, not on every pass.
618
+ useEffect(() => {
619
+ const host = ref.current?.closest("a, button, [data-figure-host]");
620
+ if (!moving || !react || !host || off)
621
+ return;
622
+ const enter = () => {
623
+ const now = performance.now();
624
+ const h = hover.current;
625
+ if (now - h.last < 2500)
626
+ return;
627
+ h.last = now;
628
+ h.until = now + 1300;
629
+ if (!sim.current.playing)
630
+ start("bounce");
631
+ };
632
+ host.addEventListener("pointerenter", enter);
633
+ return () => host.removeEventListener("pointerenter", enter);
634
+ // eslint-disable-next-line react-hooks/exhaustive-deps
635
+ }, [moving, react, off]);
636
+ // It turns toward the pointer on a desktop, head and eyes: every figure but a switched-off one.
637
+ useEffect(() => {
638
+ if (!moving || !look || off || !window.matchMedia("(hover: hover) and (pointer: fine)").matches)
639
+ return;
640
+ const turnTo = () => {
641
+ const box = ref.current?.getBoundingClientRect();
642
+ if (!box || !pointer)
643
+ return;
644
+ const dx = pointer.x - (box.left + box.width / 2);
645
+ const dy = pointer.y - (box.top + box.height / 2);
646
+ const distance = Math.hypot(dx, dy) || 1;
647
+ const reach = Math.min(1, distance / Math.max(180, box.width * 3));
648
+ gaze.current = { x: (dx / distance) * reach, y: (dy / distance) * reach };
649
+ };
650
+ turnTo();
651
+ const stop = follow(turnTo);
652
+ return () => {
653
+ stop();
654
+ gaze.current = { x: 0, y: 0 };
655
+ };
656
+ }, [moving, look, off]);
657
+ // One of the figures on the page, for the others to look at; where it is, read again on scroll.
658
+ useEffect(() => {
659
+ const element = ref.current;
660
+ if (!moving || !element)
661
+ return;
662
+ const id = (peerId.current ||= nextPeer++);
663
+ peers.set(id, { id, mood, box: boxOf(element), event: 0, watching: null, element });
664
+ const place = () => {
665
+ const peer = peers.get(id);
666
+ if (peer)
667
+ peer.box = boxOf(element);
668
+ };
669
+ window.addEventListener("scroll", place, { passive: true });
670
+ window.addEventListener("resize", place);
671
+ return () => {
672
+ peers.delete(id);
673
+ window.removeEventListener("scroll", place);
674
+ window.removeEventListener("resize", place);
675
+ };
676
+ // eslint-disable-next-line react-hooks/exhaustive-deps
677
+ }, [moving]);
678
+ useEffect(() => {
679
+ const peer = peers.get(peerId.current);
680
+ if (peer)
681
+ peer.mood = mood;
682
+ }, [mood]);
683
+ // Petted: clicked, it's petted (and the card it's on doesn't open); dragged where `grab` is on,
684
+ // it turns with the pointer and springs home when let go.
685
+ useEffect(() => {
686
+ const root = ref.current;
687
+ if (!root || !moving || (!grab && !pet))
688
+ return;
689
+ const s = sim.current;
690
+ let from = null;
691
+ let dragged = false;
692
+ const down = (event) => {
693
+ if (!grab || event.button !== 0)
694
+ return;
695
+ from = { x: event.clientX, y: event.clientY, yaw: s.drag.yaw.value, pitch: s.drag.pitch.value };
696
+ dragged = false;
697
+ };
698
+ const move = (event) => {
699
+ if (!from)
700
+ return;
701
+ const dx = event.clientX - from.x;
702
+ const dy = event.clientY - from.y;
703
+ if (!dragged && Math.hypot(dx, dy) < 5)
704
+ return;
705
+ if (!dragged) {
706
+ dragged = true;
707
+ s.drag.held = true;
708
+ root.setPointerCapture(event.pointerId);
709
+ root.style.cursor = "grabbing";
710
+ }
711
+ const yaw = from.yaw + (dx / size) * 220;
712
+ const pitch = Math.max(-70, Math.min(70, from.pitch - (dy / size) * 160));
713
+ s.drag.yaw = { value: yaw, velocity: (yaw - s.drag.yaw.value) * 60 };
714
+ s.drag.pitch = { value: pitch, velocity: (pitch - s.drag.pitch.value) * 60 };
715
+ };
716
+ const up = () => {
717
+ from = null;
718
+ s.drag.held = false;
719
+ root.style.cursor = "";
720
+ // Home the short way round.
721
+ s.drag.yaw.value = ((((s.drag.yaw.value + 180) % 360) + 360) % 360) - 180;
722
+ };
723
+ const click = (event) => {
724
+ if (!dragged && !pet)
725
+ return;
726
+ event.preventDefault();
727
+ event.stopPropagation();
728
+ if (dragged) {
729
+ dragged = false;
730
+ return;
731
+ }
732
+ if (off)
733
+ return;
734
+ if (s.playing?.motion !== "pet")
735
+ start("pet");
736
+ announce(peerId.current);
737
+ };
738
+ root.addEventListener("pointerdown", down);
739
+ root.addEventListener("pointermove", move);
740
+ root.addEventListener("pointerup", up);
741
+ root.addEventListener("pointercancel", up);
742
+ root.addEventListener("click", click, true);
743
+ return () => {
744
+ root.removeEventListener("pointerdown", down);
745
+ root.removeEventListener("pointermove", move);
746
+ root.removeEventListener("pointerup", up);
747
+ root.removeEventListener("pointercancel", up);
748
+ root.removeEventListener("click", click, true);
749
+ };
750
+ // eslint-disable-next-line react-hooks/exhaustive-deps
751
+ }, [grab, pet, moving, size, off]);
752
+ const pettable = pet && !grab && moving && !off;
753
+ return (_jsxs("div", { ref: ref, "aria-hidden": "true", "data-mood": mood, "data-expression": expression, "data-moving": moving ? "" : undefined, className: joined("figure", grab && "figure-grab", pettable && "figure-pet", className), style: {
754
+ position: "relative",
755
+ display: "inline-block",
756
+ flexShrink: 0,
757
+ verticalAlign: "middle",
758
+ width: size,
759
+ height: size,
760
+ cursor: grab ? "grab" : pettable ? "pointer" : undefined,
761
+ touchAction: grab ? "none" : undefined,
762
+ ...style,
763
+ }, children: [flat ? _jsx(FlatFigure, { figure: figure, expression: expression, off: off, colours: colours, ink: ink, shown: !lit }) : null, usable ? _jsx("canvas", { ref: canvasRef, width: pixels, height: pixels, "data-lit": lit ? "" : undefined, style: lit ? LIT_STYLE : CANVAS_STYLE }) : null] }));
764
+ }
765
+ /** A trailing spring: quick, a little under critically damped, so the eyes catch up and overshoot a touch. */
766
+ function trailStep(current, target, dt) {
767
+ const force = 230 * (target - current.value) - 22 * current.velocity;
768
+ const velocity = current.velocity + force * dt;
769
+ return { value: current.value + velocity * dt, velocity };
770
+ }
771
+ /** The figure flat, seen from the front: where there's no WebGL 2 to draw it, and until the shader is ready. It fades out as the 3D drawing fades in over it (`shown`). */
772
+ function FlatFigure({ figure, expression, off, colours, ink, shown }) {
773
+ const id = useId();
774
+ const art = FLAT[figure.shape];
775
+ const face = FACES[expression];
776
+ const [fx, fy] = art.face;
777
+ const { w, h, gap } = art.eye;
778
+ return (_jsxs("svg", { viewBox: "0 0 100 100", className: "figure-flat", style: { position: "absolute", inset: 0, display: "block", width: "100%", height: "100%", opacity: shown ? (off ? 0.7 : 1) : 0, transition: FADING, ...(off ? { filter: "grayscale(1)" } : null) }, children: [_jsx("defs", { children: _jsxs("linearGradient", { id: `${id}-body`, x1: "0.15", y1: "0.1", x2: "0.85", y2: "0.95", children: [_jsx("stop", { offset: "0", style: { stopColor: colours.light } }), _jsx("stop", { offset: "0.55", style: { stopColor: colours.main } }), _jsx("stop", { offset: "1", style: { stopColor: colours.deep } })] }) }), _jsx("path", { d: art.d, fill: `url(#${id}-body)` }), [-1, 1].map((side) => {
779
+ const cx = fx + side * gap;
780
+ const ew = w * face.size;
781
+ const eh = (face.glyph === "rect" ? h : h * 0.2) * face.size;
782
+ return _jsx("rect", { x: cx - ew / 2, y: fy - eh / 2, width: ew, height: eh, style: { fill: ink } }, side);
783
+ })] }));
784
+ }
785
+ /** An agent's colours alone, as a dot `size` pixels across: where a whole figure wouldn't read (a table's row). */
786
+ export function AgentDot({ figure, colours = COLOURWAYS[figure.palette], size = 8, className, style }) {
787
+ return (_jsx("span", { "aria-hidden": "true", className: className, style: {
788
+ display: "inline-block",
789
+ width: size,
790
+ height: size,
791
+ flexShrink: 0,
792
+ borderRadius: "50%",
793
+ background: `linear-gradient(135deg, ${colours.light}, ${colours.main} 50%, ${colours.deep})`,
794
+ ...style,
795
+ } }));
796
+ }