@cesarvenzac/figures 0.1.0 → 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/README.md CHANGED
@@ -91,8 +91,9 @@ to look, and now and then one glances at whichever is busy. A hover on a link or
91
91
  figure is in makes it smile; to react to another element's hover, mark it `data-figure-host`.
92
92
 
93
93
  It's a drawing, hidden from assistive tech: put words beside it saying who it is and what it's
94
- doing. It holds still under reduced motion and while it's off screen, and where there's no WebGL 2
95
- it's a flat drawing instead.
94
+ doing. It holds still under reduced motion and while it's off screen. Until its shader is ready
95
+ it's a flat drawing, from the server on, which the 3D one fades in over where it stands; where
96
+ there's no WebGL 2 it stays flat.
96
97
 
97
98
  ## Colours
98
99
 
@@ -128,6 +129,12 @@ shader, and copied onto its own canvas; the canvas is at most 512 device pixels
128
129
  figure is drawn every frame only while something happens, every other frame while it only
129
130
  breathes, and not at all off screen. They all share one frame loop and one pointer listener.
130
131
 
132
+ The shader is big, and a slow or software driver takes seconds over it (headless Chromium's
133
+ SwiftShader spends two on its first draw), so it's made ready without holding up the page: compiled
134
+ with `KHR_parallel_shader_compile` where the browser has it, else once the page is idle, then drawn
135
+ once on a single pixel, each step waited for a frame at a time, never asked about before it's done.
136
+ The page answers throughout; the figures show their flat drawings meanwhile.
137
+
131
138
  ## Development
132
139
 
133
140
  ```sh
@@ -20,14 +20,51 @@ import { type FigureScene } from "./figure-space.ts";
20
20
  * the sphere's size, ripples and moons, the cloud's puffs and raindrops. In front of it, hearts,
21
21
  * stars, z's and sparks; behind and under a cloud, its rainbow and its lightning. One WebGL 2 context for every figure on the
22
22
  * page (a browser keeps only a few): each figure is drawn into it and copied onto its own canvas
23
- * straight away. Where WebGL 2 is missing or lost, `drawFigure` says so and the figure keeps its
24
- * still drawing.
23
+ * straight away. The shader is made ready without holding up the page (`prepare`), and until it
24
+ * is, or where WebGL 2 is missing or lost, the figures show their flat drawings (`shaderState`).
25
25
  */
26
26
  /** The largest figure drawn, in device pixels; a bigger one is drawn at this and scaled. */
27
27
  export declare const MOST_PIXELS = 512;
28
- /** Whether figures can be drawn here at all (WebGL 2, and the shader compiled). */
29
- export declare function canDraw(): boolean;
30
- /** Draws a figure's scene onto `target` (its own canvas, in device pixels). False when there's no WebGL 2, or it was lost. */
28
+ type Uniform = "uSize" | "uShape" | "uMorphTo" | "uMorph" | "uTime" | "uBody" | "uBodyPos" | "uBodyScale" | "uSplit" | "uSpread" | "uCells" | "uLayers" | "uPieces" | "uShear" | "uCore" | "uBeads" | "uBeadCount" | "uPuffs" | "uSurface" | "uRoll" | "uBits" | "uBitKinds" | "uRainbow" | "uBolt" | "uEyeO" | "uEyeR" | "uEyeU" | "uEyeF" | "uEyeSize" | "uLook" | "uLidL" | "uLidR" | "uGlyph" | "uInk" | "uPalA" | "uPalB" | "uPalD" | "uHue" | "uFlow" | "uSwirl" | "uEnergy" | "uSaturation" | "uHalo" | "uRipple" | "uRings" | "uArc" | "uArcAngle" | "uFloorY" | "uBottom" | "uReach" | "uMilk";
29
+ type Renderer = {
30
+ gl: WebGL2RenderingContext;
31
+ at: Record<Uniform, WebGLUniformLocation | null>;
32
+ };
33
+ /** What `prepare` waits for between its steps: a moment the page is idle, or the next frame. */
34
+ export type Wait = "idle" | "frame";
35
+ /**
36
+ * The shader made ready without holding up the page, a step at a time: `prepare` yields what to
37
+ * wait for before its next step, and never asks the context anything it would have to wait for.
38
+ *
39
+ * A browser hands its WebGL calls to a GPU process and answers a question about them (did it
40
+ * compile? what does it draw?) only once the work is done, holding the page's main thread
41
+ * meanwhile. This shader is big: a slow or software driver takes seconds over it (SwiftShader, as
42
+ * headless Chromium has it, compiles it in 30 ms and then 2 s more over the first draw, making the
43
+ * pipeline). So nothing is asked until it's done. With `KHR_parallel_shader_compile` the program
44
+ * is compiled and linked at once and its completion asked each frame, which never waits. Without
45
+ * it, the compile starts once the page is idle, so it isn't inside the first render, with a fence
46
+ * behind it, which says each frame whether the work before it is done, again without waiting.
47
+ * Then a first draw, on one pixel, behind a fence of its own: the pipeline is made there. Only
48
+ * then is the program used, and drawing a figure costs what drawing it costs.
49
+ *
50
+ * Returns the renderer, or null when the shader doesn't compile here (it says why on the console).
51
+ */
52
+ export declare function prepare(gl: WebGL2RenderingContext): Generator<Wait, Renderer | null, void>;
53
+ /**
54
+ * Where the page's shader stands: being made ready (`compiling`: the figures show their flat
55
+ * drawings meanwhile), `ready`, or `unavailable` (no WebGL 2, or it didn't compile). `generation`
56
+ * counts the times it became ready: a lost context comes back as a new one, drawn into afresh.
57
+ */
58
+ export type ShaderState = {
59
+ readiness: "compiling" | "ready" | "unavailable";
60
+ generation: number;
61
+ };
62
+ /** How things stand before anything's tried, as the server draws a figure. */
63
+ export declare const NOT_YET: ShaderState;
64
+ /** Where the page's shader stands now (`ShaderState`). */
65
+ export declare const shaderState: () => ShaderState;
66
+ /** Calls `change` whenever the shader's state changes, and starts making it ready if nothing has yet. Returns a function to stop. */
67
+ export declare function watchShader(change: () => void): () => void;
68
+ /** Draws a figure's scene onto `target` (its own canvas, in device pixels). False when the shader isn't ready (`shaderState`), or the canvas can't be drawn on. */
31
69
  export declare function drawFigure(target: HTMLCanvasElement, scene: FigureScene): boolean;
32
- /** Calls `redraw` when a lost context comes back, so a figure can draw again. */
33
- export declare function onRestored(redraw: () => void): () => void;
70
+ export {};
package/dist/figure-gl.js CHANGED
@@ -20,8 +20,8 @@ import { BODY, CAMERA, MOST } from "./figure-space.js";
20
20
  * the sphere's size, ripples and moons, the cloud's puffs and raindrops. In front of it, hearts,
21
21
  * stars, z's and sparks; behind and under a cloud, its rainbow and its lightning. One WebGL 2 context for every figure on the
22
22
  * page (a browser keeps only a few): each figure is drawn into it and copied onto its own canvas
23
- * straight away. Where WebGL 2 is missing or lost, `drawFigure` says so and the figure keeps its
24
- * still drawing.
23
+ * straight away. The shader is made ready without holding up the page (`prepare`), and until it
24
+ * is, or where WebGL 2 is missing or lost, the figures show their flat drawings (`shaderState`).
25
25
  */
26
26
  /** The largest figure drawn, in device pixels; a bigger one is drawn at this and scaled. */
27
27
  export const MOST_PIXELS = 512;
@@ -737,65 +737,157 @@ const NAMES = [
737
737
  "uReach",
738
738
  "uMilk",
739
739
  ];
740
- /** Not tried yet (undefined), unavailable (null), or ready. */
741
- let renderer;
742
- const contexts = new WeakMap();
743
- const restored = new Set();
744
- function compile(gl, type, source) {
745
- const shader = gl.createShader(type);
746
- if (!shader)
747
- return null;
748
- gl.shaderSource(shader, source);
749
- gl.compileShader(shader);
750
- if (gl.getShaderParameter(shader, gl.COMPILE_STATUS))
751
- return shader;
752
- console.error(gl.getShaderInfoLog(shader));
753
- return null;
754
- }
755
- function create() {
756
- if (typeof document === "undefined")
757
- return null;
758
- const canvas = document.createElement("canvas");
759
- canvas.width = canvas.height = MOST_PIXELS;
760
- const gl = canvas.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer: false });
761
- if (!gl)
762
- return null;
763
- const vertex = compile(gl, gl.VERTEX_SHADER, VERTEX);
764
- const fragment = compile(gl, gl.FRAGMENT_SHADER, FRAGMENT);
740
+ /**
741
+ * The shader made ready without holding up the page, a step at a time: `prepare` yields what to
742
+ * wait for before its next step, and never asks the context anything it would have to wait for.
743
+ *
744
+ * A browser hands its WebGL calls to a GPU process and answers a question about them (did it
745
+ * compile? what does it draw?) only once the work is done, holding the page's main thread
746
+ * meanwhile. This shader is big: a slow or software driver takes seconds over it (SwiftShader, as
747
+ * headless Chromium has it, compiles it in 30 ms and then 2 s more over the first draw, making the
748
+ * pipeline). So nothing is asked until it's done. With `KHR_parallel_shader_compile` the program
749
+ * is compiled and linked at once and its completion asked each frame, which never waits. Without
750
+ * it, the compile starts once the page is idle, so it isn't inside the first render, with a fence
751
+ * behind it, which says each frame whether the work before it is done, again without waiting.
752
+ * Then a first draw, on one pixel, behind a fence of its own: the pipeline is made there. Only
753
+ * then is the program used, and drawing a figure costs what drawing it costs.
754
+ *
755
+ * Returns the renderer, or null when the shader doesn't compile here (it says why on the console).
756
+ */
757
+ export function* prepare(gl) {
758
+ const parallel = gl.getExtension("KHR_parallel_shader_compile");
759
+ if (!parallel)
760
+ yield "idle";
761
+ const vertex = gl.createShader(gl.VERTEX_SHADER);
762
+ const fragment = gl.createShader(gl.FRAGMENT_SHADER);
765
763
  const program = gl.createProgram();
766
764
  if (!vertex || !fragment || !program)
767
765
  return null;
766
+ gl.shaderSource(vertex, VERTEX);
767
+ gl.compileShader(vertex);
768
+ gl.shaderSource(fragment, FRAGMENT);
769
+ gl.compileShader(fragment);
768
770
  gl.attachShader(program, vertex);
769
771
  gl.attachShader(program, fragment);
770
772
  gl.linkProgram(program);
771
- if (!gl.getProgramParameter(program, gl.LINK_STATUS))
773
+ if (parallel) {
774
+ gl.flush();
775
+ while (!gl.getProgramParameter(program, parallel.COMPLETION_STATUS_KHR))
776
+ yield "frame";
777
+ }
778
+ else
779
+ yield* fenced(gl);
780
+ if (!gl.getProgramParameter(program, gl.LINK_STATUS)) {
781
+ for (const shader of [vertex, fragment])
782
+ if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS))
783
+ console.error(gl.getShaderInfoLog(shader));
784
+ console.error(gl.getProgramInfoLog(program));
772
785
  return null;
786
+ }
773
787
  gl.useProgram(program);
774
788
  const at = Object.fromEntries(NAMES.map((name) => [name, gl.getUniformLocation(program, name)]));
789
+ // The first draw, where a driver makes the pipeline: one pixel, as every figure is drawn.
790
+ gl.viewport(0, 0, 1, 1);
791
+ gl.uniform2f(at.uSize, 1, 1);
792
+ gl.drawArrays(gl.TRIANGLES, 0, 3);
793
+ yield* fenced(gl);
794
+ return { gl, at };
795
+ }
796
+ /** Waits, a frame at a time, until the context has done everything asked of it so far. */
797
+ function* fenced(gl) {
798
+ const sync = gl.fenceSync(gl.SYNC_GPU_COMMANDS_COMPLETE, 0);
799
+ gl.flush();
800
+ if (!sync)
801
+ return;
802
+ // A fence's status changes only between tasks: it's asked a frame later at the soonest.
803
+ yield "frame";
804
+ while (gl.getSyncParameter(sync, gl.SYNC_STATUS) !== gl.SIGNALED)
805
+ yield "frame";
806
+ gl.deleteSync(sync);
807
+ }
808
+ /** How things stand before anything's tried, as the server draws a figure. */
809
+ export const NOT_YET = { readiness: "compiling", generation: 0 };
810
+ let state = NOT_YET;
811
+ let renderer = null;
812
+ /** Whether the shared canvas was made (or found impossible). */
813
+ let started = false;
814
+ /** Which preparation is under way; one started before a lost context is let go. */
815
+ let preparing = 0;
816
+ const watchers = new Set();
817
+ const contexts = new WeakMap();
818
+ function moveTo(readiness) {
819
+ state = { readiness, generation: state.generation + (readiness === "ready" ? 1 : 0) };
820
+ // Told after the current task: a watcher may be in the middle of subscribing.
821
+ queueMicrotask(() => {
822
+ for (const watcher of watchers)
823
+ watcher();
824
+ });
825
+ }
826
+ const later = (wait, step) => {
827
+ if (wait === "frame")
828
+ requestAnimationFrame(step);
829
+ else if (typeof requestIdleCallback === "function")
830
+ requestIdleCallback(step, { timeout: 1000 });
831
+ else
832
+ setTimeout(step, 100);
833
+ };
834
+ function run(gl) {
835
+ const mine = ++preparing;
836
+ renderer = null;
837
+ const steps = prepare(gl);
838
+ const step = () => {
839
+ if (mine !== preparing)
840
+ return;
841
+ if (gl.isContextLost())
842
+ return;
843
+ const next = steps.next();
844
+ if (!next.done)
845
+ return later(next.value, step);
846
+ renderer = next.value;
847
+ moveTo(renderer ? "ready" : "unavailable");
848
+ };
849
+ step();
850
+ }
851
+ function start() {
852
+ if (started)
853
+ return;
854
+ started = true;
855
+ const canvas = typeof document === "undefined" ? null : document.createElement("canvas");
856
+ if (canvas)
857
+ canvas.width = canvas.height = MOST_PIXELS;
858
+ const gl = canvas?.getContext("webgl2", { alpha: true, premultipliedAlpha: true, antialias: false, depth: false, stencil: false, preserveDrawingBuffer: false });
859
+ if (!canvas || !gl)
860
+ return moveTo("unavailable");
775
861
  canvas.addEventListener("webglcontextlost", (event) => {
776
862
  event.preventDefault();
863
+ preparing++;
777
864
  renderer = null;
865
+ moveTo("compiling");
778
866
  });
779
- canvas.addEventListener("webglcontextrestored", () => {
780
- renderer = undefined;
781
- for (const redraw of restored)
782
- redraw();
783
- });
784
- return { gl, at };
785
- }
786
- /** Whether figures can be drawn here at all (WebGL 2, and the shader compiled). */
787
- export function canDraw() {
788
- if (renderer === undefined)
789
- renderer = create();
790
- return Boolean(renderer && !renderer.gl.isContextLost());
867
+ // Everything the context held is gone: made ready again, from the start.
868
+ canvas.addEventListener("webglcontextrestored", () => run(gl));
869
+ run(gl);
870
+ }
871
+ /** Where the page's shader stands now (`ShaderState`). */
872
+ export const shaderState = () => state;
873
+ /** Calls `change` whenever the shader's state changes, and starts making it ready if nothing has yet. Returns a function to stop. */
874
+ export function watchShader(change) {
875
+ watchers.add(change);
876
+ start();
877
+ return () => {
878
+ watchers.delete(change);
879
+ };
791
880
  }
792
- /** Draws a figure's scene onto `target` (its own canvas, in device pixels). False when there's no WebGL 2, or it was lost. */
881
+ /** Draws a figure's scene onto `target` (its own canvas, in device pixels). False when the shader isn't ready (`shaderState`), or the canvas can't be drawn on. */
793
882
  export function drawFigure(target, scene) {
794
- if (renderer === undefined)
795
- renderer = create();
796
883
  const r = renderer;
797
- if (!r || r.gl.isContextLost())
884
+ if (!r || state.readiness !== "ready")
885
+ return false;
886
+ if (r.gl.isContextLost()) {
887
+ // Lost before the browser has said so: the figures stand in flat until it's back.
888
+ moveTo("compiling");
798
889
  return false;
890
+ }
799
891
  let context = contexts.get(target);
800
892
  if (context === undefined) {
801
893
  context = target.getContext("2d");
@@ -866,10 +958,3 @@ export function drawFigure(target, scene) {
866
958
  context.drawImage(gl.canvas, 0, MOST_PIXELS - size, size, size, 0, 0, target.width, target.height);
867
959
  return true;
868
960
  }
869
- /** Calls `redraw` when a lost context comes back, so a figure can draw again. */
870
- export function onRestored(redraw) {
871
- restored.add(redraw);
872
- return () => {
873
- restored.delete(redraw);
874
- };
875
- }
package/dist/react.d.ts CHANGED
@@ -23,9 +23,11 @@ import { type Colourway, type Expression, type Figure, type Mood, type Motion }
23
23
  * (`COLOURWAYS`) unless `colours` says otherwise, and its eyes `INK` unless `ink` does: any CSS
24
24
  * colours, a custom property (`var(--name)`) read from the page's root once. All of it is worked
25
25
  * out by figure-motion.ts, figure-acts.ts and figure-scene.ts on one frame loop for the page
26
- * (figure-loop.ts); a still figure (`still`, reduced motion, off screen) is drawn once. Where
27
- * there's no WebGL 2 it's a flat drawing instead. A drawing, hidden from assistive tech: the words beside it say who it is and
28
- * what it's doing.
26
+ * (figure-loop.ts); a still figure (`still`, reduced motion, off screen) is drawn once. Until the
27
+ * page's shader is ready (made ready without holding up the page: figure-gl.ts), it's its flat
28
+ * drawing, fading into the 3D one where it stands once that's drawn; where there's no WebGL 2 it
29
+ * stays flat. A drawing, hidden from assistive tech: the words beside it say who it is and what
30
+ * it's doing.
29
31
  */
30
32
  export declare function AgentFigure({ figure, mood, expression: asked, motion: askedMotion, play, size, look, react, pet, still, grab, drain, aim, lift, colours: given, ink, className, style, }: {
31
33
  figure: Figure;
package/dist/react.js CHANGED
@@ -4,7 +4,7 @@ import { useEffect, useId, useRef, useState, useSyncExternalStore } from "react"
4
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
5
  import { actLoopAt } from "./figure-acts.js";
6
6
  import { easeInOut, span } from "./figure-curves.js";
7
- import { canDraw, drawFigure, MOST_PIXELS, onRestored } from "./figure-gl.js";
7
+ import { drawFigure, MOST_PIXELS, NOT_YET, shaderState, watchShader } from "./figure-gl.js";
8
8
  import { animate } from "./figure-loop.js";
9
9
  import { bodyLoopAt, combine, loopActAt, moveAt, REST_YAW, stopFor, SWITCH_AT, thinkingAt, THINKING_CYCLE, TURN_BY } from "./figure-motion.js";
10
10
  import { eventToWatch, gazeAt, glanceTarget, WATCH_FOR, watchedBy } from "./figure-peers.js";
@@ -25,6 +25,8 @@ const subscribeToMotion = (callback) => {
25
25
  };
26
26
  /** Whether the visitor asked for less motion: false on the server and while hydrating, then their setting, kept current. */
27
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);
28
30
  /** True while the element is in the viewport and the tab is in front. */
29
31
  function useOnScreen(ref) {
30
32
  const [onScreen, setOnScreen] = useState(false);
@@ -126,8 +128,12 @@ function paletteOf(colours) {
126
128
  palettes.set(key, made);
127
129
  return made;
128
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)`;
129
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. */
130
- const CANVAS_STYLE = { position: "absolute", left: "-25%", top: "-25%", width: "150%", height: "150%", pointerEvents: "none", opacity: 0, transition: "opacity 300ms cubic-bezier(0.22, 1, 0.36, 1)" };
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 };
131
137
  const wait = (from, to) => from + Math.random() * (to - from);
132
138
  const sprungFrom = (look) => Object.fromEntries(LOOK_KEYS.map((key) => [key, { value: look[key], velocity: 0 }]));
133
139
  const valuesOf = (sprung) => Object.fromEntries(LOOK_KEYS.map((key) => [key, sprung[key].value]));
@@ -154,9 +160,11 @@ const valuesOf = (sprung) => Object.fromEntries(LOOK_KEYS.map((key) => [key, spr
154
160
  * (`COLOURWAYS`) unless `colours` says otherwise, and its eyes `INK` unless `ink` does: any CSS
155
161
  * colours, a custom property (`var(--name)`) read from the page's root once. All of it is worked
156
162
  * out by figure-motion.ts, figure-acts.ts and figure-scene.ts on one frame loop for the page
157
- * (figure-loop.ts); a still figure (`still`, reduced motion, off screen) is drawn once. Where
158
- * there's no WebGL 2 it's a flat drawing instead. A drawing, hidden from assistive tech: the words beside it say who it is and
159
- * what it's doing.
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.
160
168
  */
161
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, }) {
162
170
  const ref = useRef(null);
@@ -164,7 +172,20 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
164
172
  const onScreen = useOnScreen(ref);
165
173
  const reduced = useReducedMotion();
166
174
  const moving = onScreen && !reduced && !still;
167
- const [flat, setFlat] = useState(false);
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);
168
189
  const [ratio, setRatio] = useState(2);
169
190
  const [override, setOverride] = useState(null);
170
191
  const state = MOOD[mood];
@@ -292,21 +313,28 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
292
313
  }, s.scene);
293
314
  if (!drawFigure(canvas, s.scene))
294
315
  return false;
295
- if (canvas.dataset.lit === undefined) {
296
- canvas.dataset.lit = "";
297
- canvas.style.opacity = "1";
316
+ if (litRef.current !== generation) {
317
+ litRef.current = generation;
318
+ setLitIn(generation);
298
319
  }
299
320
  return true;
300
321
  };
301
- // A still figure, drawn once as its expression has it (and again if the context comes back).
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.
302
328
  useEffect(() => {
303
- if (moving)
329
+ if (!lit || shownIn === generation)
304
330
  return;
305
- if (!canDraw()) {
306
- // eslint-disable-next-line react-hooks/set-state-in-effect -- whether the browser can draw it is only known here.
307
- setFlat(true);
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)
308
337
  return;
309
- }
310
338
  const s = sim.current;
311
339
  s.face = { ...FACES[expression] };
312
340
  s.glyphFrom = s.glyphTo = FACES[expression].glyph;
@@ -314,11 +342,10 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
314
342
  s.look = sprungFrom(off ? OFF_LOOK : LOOKS[expression]);
315
343
  s.playing = null;
316
344
  s.trail = null;
317
- const redraw = () => draw(performance.now());
318
- redraw();
319
- return onRestored(redraw);
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());
320
347
  // eslint-disable-next-line react-hooks/exhaustive-deps
321
- }, [moving, expression, figure.shape, paint, off, pixels, drain]);
348
+ }, [moving, ready, generation, broken, expression, figure.shape, paint, off, pixels, drain]);
322
349
  // A new shape starts from its own front.
323
350
  useEffect(() => {
324
351
  const s = sim.current;
@@ -373,13 +400,8 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
373
400
  // glows and flows, it makes its moves, and it's drawn, every frame while something's happening
374
401
  // and every other one while it only breathes.
375
402
  useEffect(() => {
376
- if (!moving)
377
- return;
378
- if (!canDraw()) {
379
- // eslint-disable-next-line react-hooks/set-state-in-effect -- whether the browser can draw it is only known here.
380
- setFlat(true);
403
+ if (!moving || !ready || broken)
381
404
  return;
382
- }
383
405
  const s = sim.current;
384
406
  const face = FACES[expression];
385
407
  const target = off ? OFF_LOOK : LOOKS[expression];
@@ -523,11 +545,10 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
523
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;
524
546
  if (!busy && frames % 2)
525
547
  return;
526
- if (!draw(now, open))
527
- setFlat(true);
548
+ drawOrBreak(now, open);
528
549
  });
529
550
  // eslint-disable-next-line react-hooks/exhaustive-deps
530
- }, [moving, expression, figure.shape, figure.habit, paint, energy.speed, energy.amp, off, pixels, drain]);
551
+ }, [moving, ready, generation, broken, expression, figure.shape, figure.habit, paint, energy.speed, energy.amp, off, pixels, drain]);
531
552
  // A move asked for from outside, as it arrives.
532
553
  useEffect(() => {
533
554
  if (play && moving && ONCE.includes(play.motion)) {
@@ -729,7 +750,7 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
729
750
  // eslint-disable-next-line react-hooks/exhaustive-deps
730
751
  }, [grab, pet, moving, size, off]);
731
752
  const pettable = pet && !grab && moving && !off;
732
- return (_jsx("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: {
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: {
733
754
  position: "relative",
734
755
  display: "inline-block",
735
756
  flexShrink: 0,
@@ -739,7 +760,7 @@ export function AgentFigure({ figure, mood = "idle", expression: asked, motion:
739
760
  cursor: grab ? "grab" : pettable ? "pointer" : undefined,
740
761
  touchAction: grab ? "none" : undefined,
741
762
  ...style,
742
- }, children: flat ? _jsx(FlatFigure, { figure: figure, expression: expression, off: off, colours: colours, ink: ink }) : _jsx("canvas", { ref: canvasRef, width: pixels, height: pixels, style: CANVAS_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] }));
743
764
  }
744
765
  /** A trailing spring: quick, a little under critically damped, so the eyes catch up and overshoot a touch. */
745
766
  function trailStep(current, target, dt) {
@@ -747,14 +768,14 @@ function trailStep(current, target, dt) {
747
768
  const velocity = current.velocity + force * dt;
748
769
  return { value: current.value + velocity * dt, velocity };
749
770
  }
750
- /** The figure flat, seen from the front, where there's no WebGL 2 to draw it. */
751
- function FlatFigure({ figure, expression, off, colours, ink }) {
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 }) {
752
773
  const id = useId();
753
774
  const art = FLAT[figure.shape];
754
775
  const face = FACES[expression];
755
776
  const [fx, fy] = art.face;
756
777
  const { w, h, gap } = art.eye;
757
- return (_jsxs("svg", { viewBox: "0 0 100 100", className: "figure-flat", style: { display: "block", width: "100%", height: "100%", ...(off ? { filter: "grayscale(1)", opacity: 0.7 } : 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) => {
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) => {
758
779
  const cx = fx + side * gap;
759
780
  const ew = w * face.size;
760
781
  const eh = (face.glyph === "rect" ? h : h * 0.2) * face.size;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@cesarvenzac/figures",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Small 3D figures for the agents in your interface: a cube, a sphere, a pyramid, a block or a cloud with two eyes, saying what each is doing with their eyes and the way they move.",
5
5
  "keywords": [
6
6
  "agents",