open-bot-avatar 0.1.2 → 0.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/contour.ts CHANGED
@@ -113,14 +113,81 @@ export function simplifyLoop(loop: Point[], tolerance: number): Point[] {
113
113
  return loop.filter((_, k) => keep[k]);
114
114
  }
115
115
 
116
- const n1 = (v: number) => {
117
- const r = Math.round(v * 10) / 10;
118
- return (Object.is(r, -0) ? 0 : r).toString();
116
+ /** Path numbers are hundredths; vertices snap to even ones so edge midpoints land exactly on the grid. */
117
+ const UNIT = 100;
118
+
119
+ /** A grid value as a path number, as short as SVG allows: no leading zero, no `-0`. */
120
+ const num = (k: number) => {
121
+ const a = Math.abs(k), whole = Math.floor(a / UNIT), frac = a % UNIT;
122
+ const f = frac === 0 ? '' : frac % 10 === 0 ? `.${frac / 10}` : frac < 10 ? `.0${frac}` : `.${frac}`;
123
+ return (k < 0 ? '-' : '') + (whole || !f ? whole : '') + f;
119
124
  };
120
125
 
121
- /** Compact closed path from loops (draw with fill-rule evenodd). */
126
+ /** Turns sharper than this (radians) stay corners; gentler ones are drawn as curves. */
127
+ const CORNER = 0.6;
128
+
129
+ /**
130
+ * A gentle turn between long edges is a corner of the outline too, not a facet of a traced curve:
131
+ * it stays sharp once its curve would leave the traced loop by more than this (viewBox units).
132
+ */
133
+ const SAG = 0.1;
134
+
135
+ /**
136
+ * Compact closed path from loops (draw with fill-rule evenodd). Traced loops are polylines, so
137
+ * gentle turns are drawn as quadratics between edge midpoints, which hides their facets at large
138
+ * sizes; real corners stay sharp. Relative commands, smooth t segments and implicit repeats keep
139
+ * the string short.
140
+ */
122
141
  export function loopsToPath(loops: Point[][]): string {
123
- return loops
124
- .map((loop) => `M${n1(loop[0][0])} ${n1(loop[0][1])}L${loop.slice(1).map((p) => `${n1(p[0])} ${n1(p[1])}`).join(' ')}Z`)
125
- .join('');
142
+ let d = '', cmd = '', last = '';
143
+ const emit = (c: string, ...ks: number[]) => {
144
+ if (c !== cmd) { d += c; cmd = c; last = ''; }
145
+ for (const k of ks) {
146
+ const t = num(k);
147
+ // A separator is only needed where the next number could be read as part of the last one.
148
+ if (last && t[0] !== '-' && !(t[0] === '.' && last.includes('.'))) d += ' ';
149
+ d += t;
150
+ last = t;
151
+ }
152
+ };
153
+ for (const loop of loops) {
154
+ const n = loop.length;
155
+ const v = loop.map(([x, y]) => [2 * Math.round(x * UNIT / 2), 2 * Math.round(y * UNIT / 2)]);
156
+ const corner = loop.map((p, k) => {
157
+ const a = loop[(k + n - 1) % n], b = loop[(k + 1) % n];
158
+ const cross = (p[0] - a[0]) * (b[1] - p[1]) - (p[1] - a[1]) * (b[0] - p[0]);
159
+ // The curve passes a quarter of p's height over the chord a-b away from p.
160
+ return Math.abs(Math.atan2(cross, (p[0] - a[0]) * (b[0] - p[0]) + (p[1] - a[1]) * (b[1] - p[1]))) > CORNER
161
+ || Math.abs(cross) > 4 * SAG * Math.hypot(b[0] - a[0], b[1] - a[1]);
162
+ });
163
+ const mid = (k: number) => [(v[k % n][0] + v[(k + 1) % n][0]) / 2, (v[k % n][1] + v[(k + 1) % n][1]) / 2];
164
+ let [cx, cy] = mid(0);
165
+ emit('M', cx, cy);
166
+ let smooth = false;
167
+ for (let k = 1; k <= n; k++) {
168
+ const [px, py] = v[k % n];
169
+ if (corner[k % n]) {
170
+ // A midpoint between two corners lies on their straight edge, so it is only kept to start a curve.
171
+ emit('l', px - cx, py - cy);
172
+ cx = px; cy = py;
173
+ if (k < n && !corner[(k + 1) % n]) {
174
+ const [mx, my] = mid(k);
175
+ emit('l', mx - cx, my - cy);
176
+ cx = mx; cy = my;
177
+ }
178
+ smooth = false;
179
+ } else {
180
+ const [mx, my] = mid(k);
181
+ // After a curve, the reflected control point is exactly this vertex (it mirrors the last one
182
+ // across their shared midpoint), so t needs only the end point.
183
+ if (smooth) emit('t', mx - cx, my - cy);
184
+ else emit('q', px - cx, py - cy, mx - cx, my - cy);
185
+ cx = mx; cy = my;
186
+ smooth = true;
187
+ }
188
+ }
189
+ d += 'Z';
190
+ cmd = 'Z'; last = '';
191
+ }
192
+ return d;
126
193
  }
package/src/dom/mount.ts CHANGED
@@ -5,25 +5,28 @@
5
5
  * avatar.update({ mood: 'happy' });
6
6
  * avatar.destroy();
7
7
  *
8
- * Live avatars are a CSS 3D scene: every cross-section of the inferred volume
9
- * is mounted once as its own small SVG, and each frame only writes a few CSS
10
- * transforms (view, hop/roll/squash, the eyes' gaze and blink). Changing the
11
- * color only changes CSS `color`. `still` avatars are a single static SVG and
12
- * never animate. Every avatar on the page shares one animation loop.
8
+ * Live avatars paint each frame to one canvas (see paint.ts): one compositor
9
+ * layer and a small bitmap per avatar. `renderer: 'scene'` mounts a CSS 3D scene
10
+ * instead, where every cross-section is its own small SVG and each frame only
11
+ * writes a few CSS transforms; it costs a compositor layer per visible slice,
12
+ * and is also the fallback where canvas is unavailable. `still` avatars are a
13
+ * single static SVG and never animate. Every avatar on the page shares one
14
+ * animation loop.
13
15
  */
14
16
  import { createAnimator } from '../animator.ts';
15
17
  import { pointerGaze } from '../follow.ts';
16
- import { DEFAULT_COLOR, DEFAULT_EYE_COLOR, renderAvatarScene, renderAvatarSvg, sceneFrame, type SceneFrame } from '../render.ts';
18
+ import { DEFAULT_COLOR, DEFAULT_EYE_COLOR, liveFrame, renderAvatarScene, renderAvatarSvg, sceneFrame, type SceneFrame } from '../render.ts';
17
19
  import type { AvatarDefinition, AvatarMotion, RenderOptions } from '../types.ts';
18
20
  import { requestFrame, subscribeFrames } from './clock.ts';
21
+ import { canvasSupported, mountCanvas, paintCanvas, type CanvasSurface } from './paint.ts';
19
22
  import { trackPointer } from './pointer.ts';
20
23
  import { prefersReducedMotion } from './reduced.ts';
21
24
 
22
25
  export interface AvatarOptions {
23
26
  definition: AvatarDefinition;
24
- /** Body color, #rgb or #rrggbb. */
27
+ /** Body color: #rgb or #rrggbb, or any CSS color (e.g. var(--brand)). */
25
28
  color?: string;
26
- /** Eye color, #rgb or #rrggbb. Defaults to a near-black ink. */
29
+ /** Eye color: #rgb or #rrggbb, or any CSS color. Defaults to a near-black ink. */
27
30
  eyeColor?: string;
28
31
  /** Volume amount 0..14 (6 = natural depth, 0 = flat). */
29
32
  depth?: number;
@@ -40,6 +43,12 @@ export interface AvatarOptions {
40
43
  reducedMotion?: boolean | 'system';
41
44
  /** Render one static SVG and never animate (thumbnails, lists). */
42
45
  still?: boolean;
46
+ /**
47
+ * How a live avatar draws. 'canvas' (default) paints each frame to one canvas: one compositor layer
48
+ * per avatar. 'scene' is a CSS 3D scene with a compositor layer per visible slice: more CPU and
49
+ * layers, but less video memory for a single avatar several hundred pixels wide.
50
+ */
51
+ renderer?: 'canvas' | 'scene';
43
52
  /** Accessible name; defaults to the definition's name. "" marks the avatar decorative. */
44
53
  label?: string;
45
54
  }
@@ -106,6 +115,9 @@ function apply(m: Scene, frame: SceneFrame) {
106
115
  });
107
116
  }
108
117
 
118
+ const HEX = /^#(?:[0-9a-f]{3}|[0-9a-f]{6})$/i;
119
+ const isHex = (c: string | undefined) => c === undefined || HEX.test(c);
120
+
109
121
  const keys = new WeakMap<object, string>();
110
122
  /** Everything in a definition the static scene markup depends on. */
111
123
  function geometryKey(definition: AvatarDefinition): string {
@@ -124,9 +136,11 @@ function eyesOrigin(definition: AvatarDefinition): { x: number; y: number } {
124
136
  return { x: at(x), y: at(y) };
125
137
  }
126
138
 
127
- /** Avatars smaller than this (CSS px) redraw at SMALL_FPS: a frame of 3D layers costs the same at any size. */
139
+ /** Avatars smaller than this (CSS px) redraw at SMALL_FPS: the difference doesn't show, and pages often hold many. */
128
140
  const SMALL_SIZE = 128;
129
141
  const SMALL_FPS = 30;
142
+ /** How far outside the viewport (CSS px) avatars keep animating, so they are already moving as they scroll in. */
143
+ const VIEW_MARGIN = 100;
130
144
  /** Slack so a 60 Hz display reliably draws every other frame rather than drifting between 1 and 3. */
131
145
  const FRAME_SLACK = 0.004;
132
146
 
@@ -135,6 +149,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
135
149
  const animator = createAnimator();
136
150
  let rect: DOMRect | null = null;
137
151
  let scene: Scene | null = null;
152
+ let surface: CanvasSurface | null = null;
138
153
  let lastStill = '';
139
154
  let failed = false;
140
155
  let dirty = true;
@@ -150,6 +165,21 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
150
165
  });
151
166
  resize?.observe(host);
152
167
 
168
+ /** Whether the host is in or near the viewport. Offscreen, a live avatar only redraws after a change. */
169
+ let visible = true;
170
+ const intersect = typeof IntersectionObserver === 'undefined'
171
+ ? null
172
+ : new IntersectionObserver(
173
+ (entries) => {
174
+ const next = entries[entries.length - 1].isIntersecting;
175
+ if (next === visible) return;
176
+ visible = next;
177
+ if (visible) requestFrame();
178
+ },
179
+ { rootMargin: `${VIEW_MARGIN}px` },
180
+ );
181
+ intersect?.observe(host);
182
+
153
183
  if (getComputedStyle(host).position === 'static') host.style.position = 'relative';
154
184
 
155
185
  const syncHost = () => {
@@ -176,6 +206,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
176
206
  const clear = () => {
177
207
  host.textContent = '';
178
208
  scene = null;
209
+ surface = null;
179
210
  lastStill = '';
180
211
  };
181
212
 
@@ -185,7 +216,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
185
216
  const now = performance.now();
186
217
  try {
187
218
  if (p.still) {
188
- if (scene) clear();
219
+ if (scene || surface) clear();
189
220
  const svg = renderAvatarSvg(p.definition, {
190
221
  color: p.color,
191
222
  eyeColor: p.eyeColor,
@@ -221,6 +252,21 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
221
252
  view: p.view,
222
253
  reducedMotion,
223
254
  };
255
+ if (p.renderer !== 'scene' && canvasSupported()) {
256
+ if (scene) clear();
257
+ const flat = liveFrame(p.definition, { ...options, color: p.color, eyeColor: p.eyeColor });
258
+ const key = `${geometryKey(p.definition)}|${p.depth}`;
259
+ if (!surface || surface.key !== key || !host.contains(surface.canvas)) surface = mountCanvas(host, key, p.definition, p.depth);
260
+ // Any CSS color works, as in the scene: one that is not hex is read back every frame from the
261
+ // host's computed `color` and --avatar-ink (which syncHost sets), so themes apply live.
262
+ const css = isHex(p.color) && isHex(p.eyeColor) ? null : getComputedStyle(host);
263
+ const fill = css && !isHex(p.color) ? css.color || flat.color : flat.color;
264
+ const ink = css && !isHex(p.eyeColor) ? css.getPropertyValue('--avatar-ink').trim() || flat.ink : flat.ink;
265
+ paintCanvas(surface, flat, size, fill, ink);
266
+ failed = false;
267
+ return !reducedMotion || step.moving;
268
+ }
269
+ if (surface) clear();
224
270
  const frame = sceneFrame(p.definition, options);
225
271
  if (!scene || scene.key !== frame.scene || scene.geometry !== geometryKey(p.definition) || !host.contains(scene.view)) {
226
272
  scene = mountScene(host, p.definition, p.depth);
@@ -241,13 +287,15 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
241
287
  syncHost();
242
288
  const unsubscribe = subscribeFrames({
243
289
  measure: () => {
244
- rect = opts.followPointer && !opts.still && !opts.holdGaze && !opts.lookAt ? host.getBoundingClientRect() : null;
290
+ rect = visible && opts.followPointer && !opts.still && !opts.holdGaze && !opts.lookAt ? host.getBoundingClientRect() : null;
245
291
  },
246
292
  draw: (time, pointer) => {
247
- // Stills only redraw after a change; live avatars every frame they ask for.
248
- if (opts.still && !dirty) return false;
293
+ // Stills, and live avatars out of view, only redraw after a change; live avatars in view every
294
+ // frame they ask for. A change still draws offscreen, so the content is current when printed.
295
+ if ((opts.still || !visible) && !dirty) return false;
249
296
  dirty = false;
250
297
  const more = draw(time, pointer);
298
+ if (!visible) return false;
251
299
  return more && size > 0 && size < SMALL_SIZE ? 1 / SMALL_FPS - FRAME_SLACK : more;
252
300
  },
253
301
  });
@@ -262,6 +310,7 @@ export function mountAvatar(host: HTMLElement, initial: AvatarOptions): MountedA
262
310
  destroy() {
263
311
  unsubscribe();
264
312
  resize?.disconnect();
313
+ intersect?.disconnect();
265
314
  releasePointer?.();
266
315
  releasePointer = null;
267
316
  clear();
@@ -0,0 +1,215 @@
1
+ /**
2
+ * The canvas renderer, the default for live avatars: paints flat avatar frames
3
+ * to one canvas, so an avatar costs one compositor layer and one small bitmap
4
+ * however many slices it shows. Equal geometry shares its parsed paths.
5
+ *
6
+ * The bitmap covers what the frames actually paint, plus slack, and only grows
7
+ * while the avatar's size and the pixel ratio stay the same. A GPU canvas that
8
+ * animates antialiased paths holds several times its bitmap in video memory,
9
+ * so covering every possible view up front (avatarExtent, kept as the upper
10
+ * bound) would cost about three times as much.
11
+ *
12
+ * The canvas sits in a wrapper at the host's content box, as the scene does,
13
+ * overhangs it by the avatar's reach and ignores the pointer.
14
+ */
15
+ import { avatarExtent } from '../render.ts';
16
+ import type { AvatarFrame, EyeMark, FramePath, Matrix } from '../render.ts';
17
+ import type { AvatarDefinition } from '../types.ts';
18
+
19
+ /** A square in viewBox units. */
20
+ export interface Square {
21
+ x: number;
22
+ y: number;
23
+ size: number;
24
+ }
25
+
26
+ /** An axis-aligned box in viewBox units; empty when x0 > x1. */
27
+ export interface Bounds {
28
+ x0: number;
29
+ y0: number;
30
+ x1: number;
31
+ y1: number;
32
+ }
33
+
34
+ /** Slack around a frame's bounds when the bitmap is laid out, viewBox units: idle motion and gaze stay inside it. */
35
+ export const FIT_SLACK = 8;
36
+ /** Margin a frame keeps from the bitmap's edge for antialiasing, viewBox units. */
37
+ export const FIT_PAD = 1;
38
+
39
+ /**
40
+ * The square to lay the bitmap out over: `prev` while it still holds `b`, else `prev` grown to
41
+ * hold `b` with slack. Never larger than `cap` unless `b` itself leaves `cap`.
42
+ */
43
+ export function fitSquare(prev: Square | null, b: Bounds, cap: Square): Square {
44
+ if (!(b.x0 <= b.x1 && b.y0 <= b.y1)) return prev ?? cap;
45
+ if (
46
+ prev &&
47
+ b.x0 - FIT_PAD >= prev.x &&
48
+ b.y0 - FIT_PAD >= prev.y &&
49
+ b.x1 + FIT_PAD <= prev.x + prev.size &&
50
+ b.y1 + FIT_PAD <= prev.y + prev.size
51
+ ) {
52
+ return prev;
53
+ }
54
+ let x0 = b.x0 - FIT_SLACK, y0 = b.y0 - FIT_SLACK, x1 = b.x1 + FIT_SLACK, y1 = b.y1 + FIT_SLACK;
55
+ if (prev) {
56
+ x0 = Math.min(x0, prev.x);
57
+ y0 = Math.min(y0, prev.y);
58
+ x1 = Math.max(x1, prev.x + prev.size);
59
+ y1 = Math.max(y1, prev.y + prev.size);
60
+ }
61
+ const size = Math.max(x1 - x0, y1 - y0);
62
+ const inCap = b.x0 >= cap.x && b.y0 >= cap.y && b.x1 <= cap.x + cap.size && b.y1 <= cap.y + cap.size;
63
+ if (size >= cap.size && inCap) return cap;
64
+ return { x: (x0 + x1 - size) / 2, y: (y0 + y1 - size) / 2, size };
65
+ }
66
+
67
+ interface Section {
68
+ path: Path2D;
69
+ rule: CanvasFillRule;
70
+ }
71
+
72
+ const MAX_SECTIONS = 4096;
73
+ const sections = new Map<string, Section>();
74
+
75
+ let supported: boolean | undefined;
76
+ /** Whether this environment can paint avatars: a 2D canvas and Path2D (jsdom has neither). */
77
+ export function canvasSupported(): boolean {
78
+ if (supported === undefined) {
79
+ // Path2D first: asking jsdom for a context logs a "not implemented" error.
80
+ supported = typeof Path2D !== 'undefined' && typeof document !== 'undefined' && !!document.createElement('canvas').getContext('2d');
81
+ }
82
+ return supported;
83
+ }
84
+
85
+ /**
86
+ * Each shape's matrix with the frame's root motion applied, and the bounds of everything the frame
87
+ * paints, in viewBox units. Pure.
88
+ */
89
+ export function framePlacement(frame: AvatarFrame): { matrices: Matrix[]; bounds: Bounds } {
90
+ const boxes = new Map(frame.paths.map((p) => [p.id, p.box]));
91
+ const [ra, rb, rc, rd, re, rf] = frame.root;
92
+ const bounds: Bounds = { x0: Infinity, y0: Infinity, x1: -Infinity, y1: -Infinity };
93
+ const add = (m: Matrix, x: number, y: number) => {
94
+ const X = m[0] * x + m[2] * y + m[4], Y = m[1] * x + m[3] * y + m[5];
95
+ if (X < bounds.x0) bounds.x0 = X;
96
+ if (X > bounds.x1) bounds.x1 = X;
97
+ if (Y < bounds.y0) bounds.y0 = Y;
98
+ if (Y > bounds.y1) bounds.y1 = Y;
99
+ };
100
+ const matrices = frame.shapes.map((shape) => {
101
+ const [a, b, c, d, e, f] = shape.matrix;
102
+ const m: Matrix = [ra * a + rc * b, rb * a + rd * b, ra * c + rc * d, rb * c + rd * d, ra * e + rc * f + re, rb * e + rd * f + rf];
103
+ const box = shape.kind === 'slice' ? boxes.get(shape.path) : eyeBox(shape.mark);
104
+ if (box) {
105
+ add(m, box.x, box.y);
106
+ add(m, box.x + box.w, box.y);
107
+ add(m, box.x, box.y + box.h);
108
+ add(m, box.x + box.w, box.y + box.h);
109
+ }
110
+ return m;
111
+ });
112
+ return { matrices, bounds };
113
+ }
114
+
115
+ function eyeBox(mark: EyeMark): FramePath['box'] {
116
+ if (mark.shape === 'pill') return { x: mark.x, y: mark.y, w: mark.width, h: mark.height };
117
+ // A quadratic arc lies within its points' hull; the stroke reaches half its width past it.
118
+ const n = (mark.d.match(/-?\d+(?:\.\d+)?/g) ?? []).map(Number);
119
+ const xs = n.filter((_, i) => i % 2 === 0), ys = n.filter((_, i) => i % 2 === 1);
120
+ const x = Math.min(...xs) - mark.strokeWidth, y = Math.min(...ys) - mark.strokeWidth;
121
+ return { x, y, w: Math.max(...xs) + mark.strokeWidth - x, h: Math.max(...ys) + mark.strokeWidth - y };
122
+ }
123
+
124
+ function eye(ctx: CanvasRenderingContext2D, mark: EyeMark) {
125
+ if (mark.shape === 'arc') {
126
+ ctx.lineWidth = mark.strokeWidth;
127
+ ctx.stroke(new Path2D(mark.d));
128
+ return;
129
+ }
130
+ const { x, y, width: w, height: h, radius: r } = mark;
131
+ ctx.beginPath();
132
+ if (typeof ctx.roundRect === 'function') ctx.roundRect(x, y, w, h, r);
133
+ else {
134
+ // Safari before 16 and Firefox before 112.
135
+ ctx.moveTo(x + r, y);
136
+ ctx.arcTo(x + w, y, x + w, y + h, r);
137
+ ctx.arcTo(x + w, y + h, x, y + h, r);
138
+ ctx.arcTo(x, y + h, x, y, r);
139
+ ctx.arcTo(x, y, x + w, y, r);
140
+ ctx.closePath();
141
+ }
142
+ ctx.fill();
143
+ }
144
+
145
+ /** A mounted canvas and the square and size its bitmap was last laid out at. */
146
+ export interface CanvasSurface {
147
+ key: string;
148
+ canvas: HTMLCanvasElement;
149
+ ctx: CanvasRenderingContext2D | null;
150
+ cap: Square;
151
+ fit: Square | null;
152
+ layout: string;
153
+ left: number;
154
+ top: number;
155
+ }
156
+
157
+ export function mountCanvas(el: HTMLElement, key: string, definition: AvatarDefinition, depth: number | undefined): CanvasSurface {
158
+ const cap = avatarExtent(definition, depth);
159
+ const wrap = document.createElement('div');
160
+ // In flow at the content box, like the scene's root, so the host's padding and border place it.
161
+ wrap.style.cssText = 'position:relative;width:100%;height:100%;pointer-events:none';
162
+ const canvas = document.createElement('canvas');
163
+ canvas.setAttribute('aria-hidden', 'true');
164
+ canvas.style.cssText = 'position:absolute';
165
+ wrap.append(canvas);
166
+ el.replaceChildren(wrap);
167
+ return { key, canvas, ctx: canvas.getContext('2d'), cap, fit: null, layout: '', left: 0, top: 0 };
168
+ }
169
+
170
+ /** Paint one frame `size` CSS pixels wide. `fill` and `ink` override the frame's colors with any canvas color. */
171
+ export function paintCanvas(surface: CanvasSurface, frame: AvatarFrame, size: number, fill = frame.color, ink = frame.ink) {
172
+ const { canvas, ctx } = surface;
173
+ if (!ctx || size <= 0) return;
174
+ const dpr = window.devicePixelRatio || 1;
175
+ const scale = (size / 100) * dpr;
176
+ const layout = `${size}|${dpr}`;
177
+ if (sections.size > MAX_SECTIONS) sections.clear();
178
+ for (const { id, d, evenOdd } of frame.paths) {
179
+ if (!sections.has(id)) sections.set(id, { path: new Path2D(d), rule: evenOdd ? 'evenodd' : 'nonzero' });
180
+ }
181
+ const { matrices, bounds } = framePlacement(frame);
182
+ const fit = fitSquare(surface.layout === layout ? surface.fit : null, bounds, surface.cap);
183
+ if (surface.layout === layout && fit === surface.fit) {
184
+ ctx.setTransform(1, 0, 0, 1, 0, 0);
185
+ ctx.clearRect(0, 0, canvas.width, canvas.height);
186
+ } else {
187
+ // Whole device pixels, so the bitmap is never resampled. Setting the width also clears it.
188
+ surface.layout = layout;
189
+ surface.fit = fit;
190
+ surface.left = Math.floor(fit.x * scale);
191
+ surface.top = Math.floor(fit.y * scale);
192
+ const bitmap = Math.ceil(fit.size * scale) + 1;
193
+ canvas.width = canvas.height = bitmap;
194
+ canvas.style.left = `${surface.left / dpr}px`;
195
+ canvas.style.top = `${surface.top / dpr}px`;
196
+ canvas.style.width = canvas.style.height = `${bitmap / dpr}px`;
197
+ }
198
+
199
+ ctx.lineCap = 'round';
200
+ ctx.strokeStyle = ink;
201
+ ctx.fillStyle = fill;
202
+ // Shapes run in the thousands per second across a page: one setTransform each beats save/restore.
203
+ for (let i = 0; i < frame.shapes.length; i++) {
204
+ const shape = frame.shapes[i], m = matrices[i];
205
+ ctx.setTransform(scale * m[0], scale * m[1], scale * m[2], scale * m[3], scale * m[4] - surface.left, scale * m[5] - surface.top);
206
+ if (shape.kind === 'slice') {
207
+ const section = sections.get(shape.path) as Section;
208
+ ctx.fill(section.path, section.rule);
209
+ } else {
210
+ ctx.fillStyle = ink;
211
+ eye(ctx, shape.mark);
212
+ ctx.fillStyle = fill;
213
+ }
214
+ }
215
+ }
package/src/index.ts CHANGED
@@ -9,7 +9,7 @@ export {
9
9
  DEFAULT_DEPTH,
10
10
  DEFAULT_EYE_COLOR,
11
11
  } from './render.ts';
12
- export type { AvatarFrame, EyeMark, FrameShape, Matrix, SceneFrame } from './render.ts';
12
+ export type { AvatarFrame, EyeMark, FramePath, FrameShape, Matrix, SceneFrame } from './render.ts';
13
13
  export { BASE_PITCH, BASE_YAW, blendPoses, computePose } from './motion.ts';
14
14
  export type { Pose, PoseInput } from './motion.ts';
15
15
  export { MOOD_MS, moodProgress, settleMood } from './mood.ts';
package/src/path.ts CHANGED
@@ -194,7 +194,9 @@ function sampleArc(x0: number, y0: number, s: Extract<Segment, { c: 'A' }>, out:
194
194
  let dt = ang((x1p - cxp) / rx, (y1p - cyp) / ry, (-x1p - cxp) / rx, (-y1p - cyp) / ry);
195
195
  if (!s.sweep && dt > 0) dt -= 2 * Math.PI;
196
196
  if (s.sweep && dt < 0) dt += 2 * Math.PI;
197
- const steps = Math.max(4, Math.ceil((Math.abs(dt) / (Math.PI / 2)) * 6));
197
+ // Chords within FLATNESS of the arc: a chord over angle θ sags r(1 - cos(θ/2)).
198
+ const step = 2 * Math.acos(Math.max(-1, 1 - FLATNESS / Math.max(rx, ry)));
199
+ const steps = Math.min(256, Math.max(4, Math.ceil(Math.abs(dt) / step)));
198
200
  for (let k = 1; k <= steps; k++) {
199
201
  const t = t1 + (dt * k) / steps;
200
202
  const ex = rx * Math.cos(t), ey = ry * Math.sin(t);
@@ -202,6 +204,13 @@ function sampleArc(x0: number, y0: number, s: Extract<Segment, { c: 'A' }>, out:
202
204
  }
203
205
  }
204
206
 
207
+ /**
208
+ * Largest gap, viewBox units, between a curve and the polygon that stands for it. Volume slices
209
+ * follow that polygon while the flat core draws the real curve, so coarser chords show as facets
210
+ * and teeth along the rim of large avatars.
211
+ */
212
+ export const FLATNESS = 0.02;
213
+
205
214
  /** Flatten into closed polygons, one per subpath. */
206
215
  export function flattenPath(segs: Segment[]): Point[][] {
207
216
  const polys: Point[][] = [];
@@ -214,7 +223,9 @@ export function flattenPath(segs: Segment[]): Point[][] {
214
223
  cur = [[s.x, s.y]]; px = s.x; py = s.y; break;
215
224
  case 'L': cur.push([s.x, s.y]); px = s.x; py = s.y; break;
216
225
  case 'C': {
217
- const n = 12;
226
+ // Wang's bound: this many chords keep within FLATNESS of the curve.
227
+ const m = Math.max(Math.hypot(px - 2 * s.x1 + s.x2, py - 2 * s.y1 + s.y2), Math.hypot(s.x1 - 2 * s.x2 + s.x, s.y1 - 2 * s.y2 + s.y));
228
+ const n = Math.min(128, Math.max(2, Math.ceil(Math.sqrt((0.75 * m) / FLATNESS))));
218
229
  for (let k = 1; k <= n; k++) {
219
230
  const t = k / n, u = 1 - t;
220
231
  cur.push([
@@ -225,7 +236,7 @@ export function flattenPath(segs: Segment[]): Point[][] {
225
236
  px = s.x; py = s.y; break;
226
237
  }
227
238
  case 'Q': {
228
- const n = 8;
239
+ const n = Math.min(128, Math.max(2, Math.ceil(Math.sqrt((0.25 * Math.hypot(px - 2 * s.x1 + s.x, py - 2 * s.y1 + s.y)) / FLATNESS))));
229
240
  for (let k = 1; k <= n; k++) {
230
241
  const t = k / n, u = 1 - t;
231
242
  cur.push([u * u * px + 2 * u * t * s.x1 + t * t * s.x, u * u * py + 2 * u * t * s.y1 + t * t * s.y]);
package/src/render.ts CHANGED
@@ -8,10 +8,12 @@
8
8
  * for any vector renderer.
9
9
  * - renderAvatarSvg: a standalone still, serialized from avatarFrame. Cross-sections of the stack that
10
10
  * faces the viewer are projected orthographically and painted back to front.
11
- * - renderAvatarScene + sceneFrame: a live CSS 3D scene. Every cross-section
12
- * is its own small SVG placed once with a 3D transform; animating, turning
13
- * and recoloring only change a few CSS transforms, and the browser's
14
- * compositor does projection and occlusion.
11
+ * - renderAvatarScene + sceneFrame: a CSS 3D scene. Every cross-section is its
12
+ * own small SVG placed once with a 3D transform; animating, turning and
13
+ * recoloring only change a few CSS transforms, and the browser's compositor
14
+ * does projection and occlusion. Each visible slice costs a compositor layer,
15
+ * so mountAvatar paints live avatars to one canvas by default and only uses
16
+ * the scene with `renderer: 'scene'`.
15
17
  */
16
18
  import { parseHex, toHex } from './color.ts';
17
19
  import type { Rgb } from './color.ts';
@@ -192,18 +194,38 @@ function rootMatrix(pose: Pose, b: Bounds): M {
192
194
 
193
195
  const pivotOf = (b: Bounds): Point => [(b.minX + b.maxX) / 2, (b.minY + b.maxY) / 2];
194
196
 
197
+ /** The hop and the share of a point's distance from the base that roll and squash can move it. */
198
+ const POSE_LIFT = 4;
199
+ const POSE_SWAY = 0.2;
200
+
201
+ /**
202
+ * A square of viewBox units that holds the avatar at every view and pose. Throws if invalid. The
203
+ * canvas renderer uses it only as an upper bound: it sizes each bitmap to what is actually painted.
204
+ */
205
+ export function avatarExtent(definition: AvatarDefinition, depth?: number): { x: number; y: number; size: number } {
206
+ const { vol } = prepare(definition, depthOption({ depth }));
207
+ const b = vol.bounds;
208
+ const [cx, cy] = pivotOf(b);
209
+ const radius = Math.hypot(b.maxX - b.minX, b.maxY - b.minY, Math.max(...vol.parts.map((part) => part.depth)) + 2 * EYE_LIFT) / 2;
210
+ const half = radius + POSE_LIFT + POSE_SWAY * (radius + b.maxY - cy);
211
+ return { x: cx - half, y: cy - half, size: 2 * half };
212
+ }
213
+
195
214
  /**
196
215
  * Every cross-section a view draws, with its projection: the stack facing the
197
216
  * viewer, minus z-slices hidden behind the core (they add nothing to the
198
217
  * silhouette or the paint). Their union is the silhouette on screen.
199
218
  */
200
- function drawnSlices(vol: Volume, v: ViewBasis, visit: (s: VolumeSlice, m: M, part: number, index: number) => void) {
219
+ function drawnSlices(p: Prepared, v: ViewBasis, size: number | undefined, visit: (s: VolumeSlice, m: M, part: number, index: number) => void) {
220
+ const { vol } = p;
201
221
  const stack = activeStack(v);
202
222
  const pivot = pivotOf(vol.bounds);
203
223
  const drawn = sliceCull(v);
224
+ const kept = sliceDetail(p, stack, size);
225
+ let k = 0;
204
226
  vol.parts.forEach((part, i) => {
205
227
  (stack === 'z' ? part.zSlices : part.xSlices).forEach((s, j) => {
206
- if (!drawn(s)) return;
228
+ if (!kept[k++] || !drawn(s)) return;
207
229
  visit(s, stack === 'z' ? planeMatrix(v, s.at, pivot) : sidePlaneMatrix(v, s.at, pivot), i, j);
208
230
  });
209
231
  });
@@ -290,6 +312,14 @@ export type FrameShape =
290
312
  }
291
313
  | { kind: 'eye'; key: 'eye-0' | 'eye-1'; matrix: Matrix; mark: EyeMark };
292
314
 
315
+ /** One cross-section outline, shared by every shape that draws it. */
316
+ export interface FramePath {
317
+ id: string;
318
+ d: string;
319
+ evenOdd: boolean;
320
+ box: { x: number; y: number; w: number; h: number };
321
+ }
322
+
293
323
  /**
294
324
  * One frame of the avatar flattened onto the screen: every cross-section the
295
325
  * view draws with its projection, and the visible eyes, sorted back to front.
@@ -302,8 +332,11 @@ export interface AvatarFrame {
302
332
  name: string;
303
333
  color: string;
304
334
  ink: string;
305
- /** Distinct cross-section paths this frame uses; ids are stable for equal geometry and depth. */
306
- paths: { id: string; d: string; evenOdd: boolean }[];
335
+ /**
336
+ * Distinct cross-section paths this frame uses; ids are stable for equal geometry and depth.
337
+ * `box` bounds `d` in its own coordinates, before a shape's matrix.
338
+ */
339
+ paths: FramePath[];
307
340
  /** 2D motion (hop, roll, squash) about the base of the body, applied to every shape. */
308
341
  root: Matrix;
309
342
  /** Back to front. */
@@ -312,6 +345,19 @@ export interface AvatarFrame {
312
345
 
313
346
  /** Compute one flat frame of a definition. Throws if the definition is invalid. */
314
347
  export function avatarFrame(definition: AvatarDefinition, options: RenderOptions = {}): AvatarFrame {
348
+ return flatFrame(definition, options, undefined);
349
+ }
350
+
351
+ /**
352
+ * avatarFrame for a live avatar drawn `options.size` CSS pixels wide: like the scene, it skips
353
+ * cross-sections that would sit less than a pixel apart. Internal to the live renderers, so
354
+ * `size` never changes what avatarFrame returns to custom renderers.
355
+ */
356
+ export function liveFrame(definition: AvatarDefinition, options: RenderOptions = {}): AvatarFrame {
357
+ return flatFrame(definition, options, options.size);
358
+ }
359
+
360
+ function flatFrame(definition: AvatarDefinition, options: RenderOptions, size: number | undefined): AvatarFrame {
315
361
  const p = prepare(definition, depthOption(options));
316
362
  const { vol } = p;
317
363
  const b = vol.bounds;
@@ -323,12 +369,12 @@ export function avatarFrame(definition: AvatarDefinition, options: RenderOptions
323
369
  const eyesMid: Point = [p.def.eyes.x, p.def.eyes.y];
324
370
 
325
371
  // Only the cross-sections this view draws are listed; ids are stable across frames.
326
- const paths = new Map<string, { id: string; d: string; evenOdd: boolean }>();
372
+ const paths = new Map<string, FramePath>();
327
373
  const items: { depth: number; shape: FrameShape }[] = [];
328
- drawnSlices(vol, v, (s, m, i, j) => {
374
+ drawnSlices(p, v, size, (s, m, i, j) => {
329
375
  let path = paths.get(s.d);
330
376
  if (!path) {
331
- path = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd };
377
+ path = { id: p.ids.get(s.d) as string, d: s.d, evenOdd: s.evenOdd, box: { ...s.box } };
332
378
  paths.set(s.d, path);
333
379
  }
334
380
  // Depth keys are taken under the eyes for the eye part, so only depth decides eye-vs-body order there.
package/src/validate.ts CHANGED
@@ -211,7 +211,7 @@ export function validateAvatar(input: unknown): ValidationResult {
211
211
  errors.push('name must be 1-40 printable characters without < or >');
212
212
  }
213
213
 
214
- let path = '';
214
+ let path: string | null = null;
215
215
  if (!isRecord(input.body)) errors.push('body must be an object { "path": "..." }');
216
216
  else {
217
217
  for (const k of Object.keys(input.body)) if (k !== 'path') errors.push(`unknown field "body.${k}" (only "path" is allowed)`);
@@ -238,7 +238,7 @@ export function validateAvatar(input: unknown): ValidationResult {
238
238
 
239
239
  let normalized = '';
240
240
  let body: BodyAnalysis | null = null;
241
- if (path) {
241
+ if (path !== null) {
242
242
  try {
243
243
  const segs = parsePath(path);
244
244
  normalized = serializePath(segs);