@vibechain/os 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (79) hide show
  1. package/AGENTS.md +76 -48
  2. package/README.md +131 -54
  3. package/SECURITY.md +45 -20
  4. package/dist/app-client.d.ts +4 -1
  5. package/dist/app-client.js +4 -1
  6. package/dist/app-host.d.ts +111 -9
  7. package/dist/app-host.js +339 -58
  8. package/dist/app-protocol.d.ts +2 -0
  9. package/dist/app-runtime.d.ts +18 -2
  10. package/dist/app-runtime.js +75 -11
  11. package/dist/app-wire.d.ts +194 -0
  12. package/dist/app-wire.js +253 -0
  13. package/dist/browser.d.ts +2 -0
  14. package/dist/browser.js +2 -0
  15. package/dist/bundle.js +6 -6
  16. package/dist/canvas.d.ts +2 -2
  17. package/dist/canvas.js +3 -1
  18. package/dist/check.d.ts +12 -0
  19. package/dist/check.js +167 -0
  20. package/dist/cli-publish.d.ts +24 -0
  21. package/dist/cli-publish.js +288 -0
  22. package/dist/cli-session.d.ts +108 -0
  23. package/dist/cli-session.js +245 -0
  24. package/dist/cli.d.ts +10 -0
  25. package/dist/cli.js +46 -10
  26. package/dist/index.d.ts +5 -0
  27. package/dist/index.js +3 -0
  28. package/dist/listing.d.ts +3 -3
  29. package/dist/listing.js +1 -1
  30. package/dist/loop.d.ts +18 -2
  31. package/dist/loop.js +13 -1
  32. package/dist/manifest.d.ts +90 -4
  33. package/dist/manifest.js +340 -5
  34. package/dist/os.d.ts +56 -0
  35. package/dist/os.js +354 -0
  36. package/dist/preview-parent.d.ts +36 -0
  37. package/dist/preview-parent.js +122 -11
  38. package/dist/preview-ui.js +1 -1
  39. package/dist/preview.js +25 -7
  40. package/dist/redact.d.ts +6 -0
  41. package/dist/redact.js +16 -0
  42. package/dist/runtime-policy.d.ts +20 -0
  43. package/dist/runtime-policy.js +45 -0
  44. package/dist/scaffold.d.ts +13 -2
  45. package/dist/scaffold.js +95 -31
  46. package/dist/submit-notice.d.ts +26 -0
  47. package/dist/submit-notice.js +34 -0
  48. package/dist/templates/plain/game.js +18 -0
  49. package/dist/testing.d.ts +63 -0
  50. package/dist/testing.js +157 -1
  51. package/dist/transport.d.ts +20 -0
  52. package/dist/transport.js +71 -19
  53. package/dist/vibemarket-os.js +1 -0
  54. package/dist/worker.d.ts +18 -0
  55. package/dist/worker.js +34 -0
  56. package/examples/paw-beat/README.md +20 -8
  57. package/examples/paw-beat/cat.ts +665 -89
  58. package/examples/paw-beat/game.ts +162 -28
  59. package/examples/paw-beat/index.html +114 -40
  60. package/examples/paw-beat/main.ts +264 -149
  61. package/examples/paw-beat/music.ts +314 -65
  62. package/examples/paw-beat/stage.ts +560 -0
  63. package/examples/paw-beat/store/icon.png +0 -0
  64. package/examples/paw-beat/store/screenshot-1.webp +0 -0
  65. package/examples/paw-beat/store/screenshot-2.webp +0 -0
  66. package/examples/paw-beat/vibemarket.json +2 -2
  67. package/examples/vibexp-app/README.md +7 -7
  68. package/examples/vibexp-app/index.html +3 -2
  69. package/examples/vibexp-app/plain/game.ts +20 -0
  70. package/examples/vibexp-app/plain/index.html +6 -0
  71. package/examples/vibexp-app/plain/vibemarket.json +17 -0
  72. package/examples/vibexp-app/src/main.ts +46 -31
  73. package/examples/vibexp-app/store/icon.png +0 -0
  74. package/examples/vibexp-app/three/README.md +21 -0
  75. package/examples/vibexp-app/three/index.html +4 -0
  76. package/examples/vibexp-app/three/src/main.ts +45 -0
  77. package/examples/vibexp-app/three/vibemarket.json +19 -0
  78. package/examples/vibexp-app/vibemarket.json +17 -11
  79. package/package.json +6 -2
@@ -1,125 +1,701 @@
1
1
  import * as THREE from "three";
2
- import type { Lane } from "./game";
2
+ import type { Judgement, Lane } from "./game";
3
3
 
4
+ /**
5
+ * Biscuit, a procedural dancing cat. Nothing is loaded: every shape is built in code when the
6
+ * game starts, and every colour and marking is drawn by a shader.
7
+ *
8
+ * Techniques worth borrowing:
9
+ * - The head, body and ears are signed distance functions (ellipsoids blended with a smooth
10
+ * minimum) turned into meshes once at startup with "surface nets", so the cheeks flow into the
11
+ * head and the neck into the body without seams.
12
+ * - One toon shader paints everything: two light bands, a rim light tinted by the stage, and
13
+ * markings (tabby stripes, cream muzzle and belly, pink ears) computed from each part's own
14
+ * coordinates. The face (eyes, pupils, highlights, nose, mouth, blush) is painted by the head's
15
+ * shader too, so an expression is just a few numbers.
16
+ * - Outlines are the same meshes drawn again, pushed out along their normals, back faces only.
17
+ * - Arms and legs are two-bone chains solved with inverse kinematics, so a pose is "put the paw
18
+ * here" and the feet stay planted while the body bounces. The tail is one tube whose rings are
19
+ * moved along a curve every frame.
20
+ * - The pose is a set of numbers, each following its target on a spring. Moves add to the
21
+ * targets; the springs blend one move into the next and add follow-through for free.
22
+ */
4
23
  export interface Cat {
5
24
  readonly root: THREE.Group;
6
- /** Play the move for a step that landed. */
7
- dance(lane: Lane): void;
8
- /** A missed step: ears back, a wobble. */
25
+ /** The head, for keeping other things clear of the face. */
26
+ readonly head: THREE.Object3D;
27
+ /** How far the cat is off the floor right now (world units), for its shadow. */
28
+ lift(): number;
29
+ /** A step that landed: that lane's move, bigger and happier on a perfect. */
30
+ dance(lane: Lane, judgement: Judgement): void;
31
+ /** A missed step: a stumble, then recovery. */
9
32
  stumble(): void;
10
- /** `beatPhase` runs 0 to 1 across each beat, so the idle bounce lands on the music. */
11
- animate(seconds: number, beatPhase: number): void;
33
+ /** A combo milestone: a spin with paws up. */
34
+ celebrate(): void;
35
+ /** How the cat feels when it is not dancing: after a good round it beams, after a rough one it droops a little. */
36
+ setMood(mood: "neutral" | "happy" | "sad"): void;
37
+ /** Colour of the rim light, from the stage. */
38
+ setRim(color: THREE.Color): void;
39
+ /**
40
+ * Advance by `seconds`. `beat` is the song position in beats, so the idle groove lands on the
41
+ * music; `energy` (0 to 1) is how hard to groove.
42
+ */
43
+ animate(seconds: number, beat: number, energy?: number): void;
12
44
  dispose(): void;
13
45
  }
14
46
 
15
- const FUR = "#e8944a", FUR_DARK = "#b9652a", CREAM = "#fff1dc", PINK = "#ff9db5", INK = "#2a1a2e";
16
- type Triple = [number, number, number];
47
+ /** Biscuit is modelled about 2.8 units tall and drawn a little larger. */
48
+ const SCALE = 1.15;
49
+
50
+ // ---- Palette ----
51
+ const FUR = "#f2923e", STRIPE = "#c4581f", CREAM = "#fff1da", PINK = "#ff8fab", INK = "#2a1a2e";
52
+ const IRIS = "#9be15d", IRIS_DARK = "#3f8f3a";
53
+
54
+ // ---- Signed distance functions and the mesher ----
55
+ type Sdf = (x: number, y: number, z: number) => number;
56
+
57
+ /** Approximate distance to an ellipsoid centred at the origin (Inigo Quilez's bound). */
58
+ function ellipsoid(x: number, y: number, z: number, rx: number, ry: number, rz: number): number {
59
+ const ax = x / rx, ay = y / ry, az = z / rz, bx = ax / rx, by = ay / ry, bz = az / rz;
60
+ const k0 = Math.sqrt(ax * ax + ay * ay + az * az), k1 = Math.sqrt(bx * bx + by * by + bz * bz);
61
+ return k1 === 0 ? -Math.min(rx, ry, rz) : (k0 * (k0 - 1)) / k1;
62
+ }
63
+ /** A cone with rounded ends, radius r1 at y = 0 narrowing to r2 at y = h. */
64
+ function roundCone(x: number, y: number, z: number, r1: number, r2: number, h: number): number {
65
+ const qx = Math.sqrt(x * x + z * z), b = (r1 - r2) / h, a = Math.sqrt(1 - b * b), k = -b * qx + a * y;
66
+ if (k < 0) return Math.sqrt(qx * qx + y * y) - r1;
67
+ if (k > a * h) return Math.sqrt(qx * qx + (y - h) * (y - h)) - r2;
68
+ return qx * a + y * b - r1;
69
+ }
70
+ /** Smooth minimum: a union that rounds the crease where two shapes meet, over a width of about k. */
71
+ function smin(a: number, b: number, k: number): number {
72
+ const h = Math.max(k - Math.abs(a - b), 0) / k;
73
+ return Math.min(a, b) - h * h * k * 0.25;
74
+ }
17
75
 
18
76
  /**
19
- * Biscuit, a procedural dancing cat. Everything is built from primitives at runtime:
20
- * there is no model file, texture or other downloaded asset.
77
+ * Surface nets: sample the field on a grid, put one vertex inside every cell the surface passes
78
+ * through (the average of where it crosses the cell's edges), and join the four cells around every
79
+ * crossed grid edge with a quad. Normals come from the field's gradient, so shading is smooth.
21
80
  */
81
+ function meshSdf(sdf: Sdf, min: readonly number[], max: readonly number[], step: number): THREE.BufferGeometry {
82
+ const [x0, y0, z0] = min as [number, number, number];
83
+ const nx = Math.ceil(((max[0] ?? 0) - x0) / step) + 1, ny = Math.ceil(((max[1] ?? 0) - y0) / step) + 1, nz = Math.ceil(((max[2] ?? 0) - z0) / step) + 1;
84
+ const field = new Float32Array(nx * ny * nz), at = (i: number, j: number, k: number) => i + nx * (j + ny * k);
85
+ for (let k = 0; k < nz; k++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) field[at(i, j, k)] = sdf(x0 + i * step, y0 + j * step, z0 + k * step);
86
+
87
+ const cell = new Int32Array(nx * ny * nz).fill(-1), positions: number[] = [], corner = new Float32Array(8);
88
+ for (let k = 0; k < nz - 1; k++) for (let j = 0; j < ny - 1; j++) for (let i = 0; i < nx - 1; i++) {
89
+ let inside = 0;
90
+ for (let c = 0; c < 8; c++) {
91
+ corner[c] = field[at(i + (c & 1), j + ((c >> 1) & 1), k + ((c >> 2) & 1))]!;
92
+ if (corner[c]! < 0) inside++;
93
+ }
94
+ if (inside === 0 || inside === 8) continue;
95
+ let sx = 0, sy = 0, sz = 0, crossings = 0;
96
+ for (let c = 0; c < 8; c++) for (const bit of [1, 2, 4]) {
97
+ if (c & bit) continue;
98
+ const a = corner[c]!, b = corner[c | bit]!;
99
+ if ((a < 0) === (b < 0)) continue;
100
+ const t = a / (a - b);
101
+ sx += (c & 1) + (bit === 1 ? t : 0);
102
+ sy += ((c >> 1) & 1) + (bit === 2 ? t : 0);
103
+ sz += ((c >> 2) & 1) + (bit === 4 ? t : 0);
104
+ crossings++;
105
+ }
106
+ cell[at(i, j, k)] = positions.length / 3;
107
+ positions.push(x0 + (i + sx / crossings) * step, y0 + (j + sy / crossings) * step, z0 + (k + sz / crossings) * step);
108
+ }
109
+
110
+ const gradient = (x: number, y: number, z: number, out: THREE.Vector3) => {
111
+ const e = step * 0.5;
112
+ return out.set(sdf(x + e, y, z) - sdf(x - e, y, z), sdf(x, y + e, z) - sdf(x, y - e, z), sdf(x, y, z + e) - sdf(x, y, z - e)).normalize();
113
+ };
114
+ const normals = new Float32Array(positions.length), n = new THREE.Vector3();
115
+ for (let v = 0; v < positions.length; v += 3) {
116
+ gradient(positions[v]!, positions[v + 1]!, positions[v + 2]!, n);
117
+ normals[v] = n.x; normals[v + 1] = n.y; normals[v + 2] = n.z;
118
+ }
119
+ const indices: number[] = [], a = new THREE.Vector3(), b = new THREE.Vector3(), c = new THREE.Vector3();
120
+ const quad = (p: number, q: number, r: number, s: number) => {
121
+ if (p < 0 || q < 0 || r < 0 || s < 0) return;
122
+ // Wind each quad so it faces the way the field's gradient points (outwards).
123
+ a.fromArray(positions, q * 3).sub(b.fromArray(positions, p * 3));
124
+ c.fromArray(positions, r * 3).sub(b);
125
+ a.cross(c);
126
+ n.set(normals[p * 3]! + normals[r * 3]!, normals[p * 3 + 1]! + normals[r * 3 + 1]!, normals[p * 3 + 2]! + normals[r * 3 + 2]!);
127
+ if (a.dot(n) >= 0) indices.push(p, q, r, p, r, s);
128
+ else indices.push(p, r, q, p, s, r);
129
+ };
130
+ for (let k = 0; k < nz; k++) for (let j = 0; j < ny; j++) for (let i = 0; i < nx; i++) {
131
+ const inside = field[at(i, j, k)]! < 0;
132
+ if (i < nx - 1 && j > 0 && k > 0 && inside !== field[at(i + 1, j, k)]! < 0) quad(cell[at(i, j - 1, k - 1)]!, cell[at(i, j, k - 1)]!, cell[at(i, j, k)]!, cell[at(i, j - 1, k)]!);
133
+ if (j < ny - 1 && i > 0 && k > 0 && inside !== field[at(i, j + 1, k)]! < 0) quad(cell[at(i - 1, j, k - 1)]!, cell[at(i, j, k - 1)]!, cell[at(i, j, k)]!, cell[at(i - 1, j, k)]!);
134
+ if (k < nz - 1 && i > 0 && j > 0 && inside !== field[at(i, j, k + 1)]! < 0) quad(cell[at(i - 1, j - 1, k)]!, cell[at(i, j - 1, k)]!, cell[at(i, j, k)]!, cell[at(i - 1, j, k)]!);
135
+ }
136
+ const geometry = new THREE.BufferGeometry();
137
+ geometry.setAttribute("position", new THREE.Float32BufferAttribute(positions, 3));
138
+ geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
139
+ geometry.setIndex(indices);
140
+ geometry.computeBoundingSphere();
141
+ return geometry;
142
+ }
143
+
144
+ // The parts, each in its own coordinates. The head's front is +z; units are about a third of a metre.
145
+ const HEAD_SDF: Sdf = (x, y, z) => {
146
+ let d = ellipsoid(x, y - 0.04, z, 0.74, 0.6, 0.6); // cranium
147
+ const ax = Math.abs(x);
148
+ d = smin(d, ellipsoid(ax - 0.34, y + 0.16, z - 0.06, 0.38, 0.28, 0.38), 0.22); // cheek fluff, a little wider at the jaw
149
+ d = smin(d, ellipsoid(x, y + 0.2, z - 0.42, 0.25, 0.17, 0.2), 0.1); // muzzle
150
+ d = smin(d, ellipsoid(x, y + 0.1, z - 0.58, 0.07, 0.05, 0.05), 0.05); // nose bump
151
+ return smin(d, ellipsoid(x, y + 0.33, z - 0.28, 0.16, 0.1, 0.14), 0.08); // chin
152
+ };
153
+ const BODY_SDF: Sdf = (x, y, z) => {
154
+ let d = ellipsoid(x, y - 0.3, z, 0.44, 0.36, 0.36); // belly and hips
155
+ d = smin(d, ellipsoid(x, y - 0.56, z - 0.02, 0.34, 0.3, 0.3), 0.2); // chest
156
+ d = smin(d, ellipsoid(x, y - 0.78, z, 0.2, 0.15, 0.19), 0.16); // neck
157
+ return smin(d, ellipsoid(Math.abs(x) - 0.24, y - 0.2, z + 0.03, 0.22, 0.22, 0.25), 0.15); // haunches
158
+ };
159
+ /** A rounded cone flattened front to back, its base at the origin and its tip up. */
160
+ const EAR_SDF: Sdf = (x, y, z) => roundCone(x, y, z / 0.45, 0.22, 0.045, 0.36) * 0.6;
161
+
162
+ // ---- Shaders ----
163
+ const VERTEX = /* glsl */ `
164
+ varying vec3 vNormal;
165
+ varying vec3 vView;
166
+ varying vec3 vLocal;
167
+ varying vec2 vUv;
168
+ void main() {
169
+ vLocal = position;
170
+ vUv = uv;
171
+ vec4 view = modelViewMatrix * vec4(position, 1.0);
172
+ vView = view.xyz;
173
+ vNormal = normalize(normalMatrix * normal);
174
+ gl_Position = projectionMatrix * view;
175
+ }`;
176
+
177
+ const FRAGMENT = /* glsl */ `
178
+ uniform vec3 uBase;
179
+ uniform vec3 uLight;
180
+ uniform vec3 uRim;
181
+ uniform vec3 uCream;
182
+ uniform vec3 uStripe;
183
+ uniform vec3 uPink;
184
+ uniform vec3 uInk;
185
+ uniform vec3 uIris;
186
+ uniform vec3 uIrisDark;
187
+ uniform vec4 uFace; // eyes open, happy, wide, mouth open
188
+ uniform vec2 uLook;
189
+ varying vec3 vNormal;
190
+ varying vec3 vView;
191
+ varying vec3 vLocal;
192
+ varying vec2 vUv;
193
+
194
+ // 1 inside a shape whose signed distance is d, 0 outside, with an edge one pixel wide.
195
+ float inside(float d) { return clamp(0.5 - d / max(fwidth(d), 1e-4), 0.0, 1.0); }
196
+ float ellipse(vec2 q, vec2 r) { return (length(q / r) - 1.0) * min(r.x, r.y); }
197
+ float segment(vec2 p, vec2 a, vec2 b) {
198
+ vec2 pa = p - a, ba = b - a;
199
+ return length(pa - ba * clamp(dot(pa, ba) / dot(ba, ba), 0.0, 1.0));
200
+ }
201
+
202
+ void main() {
203
+ vec3 albedo = uBase;
204
+ float unlit = 0.0; // painted features keep most of their colour in shadow
205
+ vec3 l = vLocal;
206
+
207
+ #ifdef HEAD
208
+ vec2 p = l.xy;
209
+ float front = smoothstep(0.12, 0.3, l.z);
210
+ // The cream muzzle stays mostly out of the shadow band, so its whole shape (and the mouth inside it) reads.
211
+ float muzzle = inside(ellipse(vec2(abs(p.x) - 0.08, p.y + 0.225), vec2(0.18, 0.15))) * front;
212
+ albedo = mix(albedo, uCream, muzzle);
213
+ unlit = max(unlit, muzzle);
214
+ // Tabby stripes: three on the forehead, two on each cheek.
215
+ float stripes = 0.0;
216
+ for (int i = -1; i <= 1; i++) {
217
+ float x = float(i) * 0.14, len = i == 0 ? 0.26 : 0.19;
218
+ stripes = max(stripes, inside(segment(p, vec2(x * 1.15, 0.64), vec2(x, 0.64 - len)) - (i == 0 ? 0.04 : 0.032)));
219
+ }
220
+ stripes *= smoothstep(-0.1, 0.1, l.z);
221
+ // Bands across the back of the head, seen when Biscuit spins.
222
+ stripes = max(stripes, inside(abs(fract(p.y * 3.2 + 0.1 * p.x * p.x) - 0.5) - 0.13) * smoothstep(-0.15, -0.35, l.z) * step(-0.2, p.y));
223
+ float cheeks = 0.0;
224
+ for (int i = 0; i < 2; i++) cheeks = max(cheeks, inside(abs(p.y + 0.06 - float(i) * 0.13 - (abs(p.x) - 0.6) * 0.3) - 0.026));
225
+ stripes = max(stripes, cheeks * smoothstep(0.58, 0.63, abs(p.x)) * step(-0.25, l.z));
226
+ albedo = mix(albedo, uStripe, stripes);
227
+ float blush = smoothstep(1.0, 0.3, length((vec2(abs(p.x), p.y) - vec2(0.45, -0.13)) / vec2(0.11, 0.06)));
228
+ albedo = mix(albedo, uPink, blush * 0.55 * front);
229
+
230
+ // Eyes. Highlights sit on the same side of both eyes, as a reflection of one light would.
231
+ float side = p.x < 0.0 ? -1.0 : 1.0, open = uFace.x, happy = smoothstep(0.3, 0.7, uFace.y), wide = uFace.z;
232
+ vec2 q = p - vec2(side * 0.29, 0.03);
233
+ vec2 r = vec2(0.14, 0.17) * (1.0 + 0.16 * wide);
234
+ float shown = smoothstep(0.15, 0.35, open) * (1.0 - happy) * front;
235
+ float eyeShape = ellipse(q, vec2(r.x, r.y * max(open, 0.2)));
236
+ vec3 eye = mix(uIris, uIrisDark, smoothstep(-0.1, 0.14, q.y));
237
+ float pupil = inside(ellipse(q - uLook * 0.04, vec2(0.05 + 0.02 * happy, 0.125) * (1.0 - 0.55 * wide)));
238
+ eye = mix(eye, uInk, pupil);
239
+ float shine = max(inside(length(q - vec2(-0.05, 0.07)) - 0.048), inside(length(q - vec2(0.05, -0.06)) - 0.022));
240
+ eye = mix(eye, vec3(1.0), shine);
241
+ float outline = inside(eyeShape - 0.026) * shown, ball = inside(eyeShape) * shown;
242
+ albedo = mix(albedo, uInk, outline);
243
+ albedo = mix(albedo, eye, ball);
244
+ unlit = max(unlit, outline);
245
+ // Closed for a blink: a gentle downward curve.
246
+ float lid = inside(abs(q.y + 0.02 - 2.2 * q.x * q.x) - 0.02) * inside(abs(q.x) - 0.13) * front * (1.0 - happy);
247
+ // Happy: an upturned arc.
248
+ float arc = inside(abs(length(q - vec2(0.0, -0.1)) - 0.13) - 0.024) * step(-0.08, q.y) * front * happy;
249
+ float shut = max(lid * (1.0 - smoothstep(0.15, 0.35, open)), arc);
250
+ albedo = mix(albedo, uInk, shut);
251
+ unlit = max(unlit, shut);
252
+
253
+ // One mouth. Closed, it is a short line down from the nose into a "w" lip line. Opening it
254
+ // lowers a jaw curve beneath that same lip line, so the lip becomes the top edge of the open
255
+ // mouth rather than a second line over it. The opening starts under the middle, and at its
256
+ // widest it still ends well inside the muzzle patch. Surprise swaps the "w" for a small "o".
257
+ float mouthOpen = uFace.w * (1.0 - wide);
258
+ vec2 w = vec2(abs(p.x) - 0.062, p.y + 0.175);
259
+ float lipY = -0.175 - sqrt(max(0.0, 0.062 * 0.062 - w.x * w.x)); // the lip line's height at this x
260
+ float across = p.x / 0.124;
261
+ float jawY = min(lipY, -0.175 - mouthOpen * 0.11 * sqrt(max(0.0, 1.0 - across * across)));
262
+ float hole = max(max(p.y - lipY, jawY - p.y), abs(p.x) - 0.124);
263
+ float inner = inside(hole) * front;
264
+ float tongue = inside(length(p - vec2(0.0, jawY + 0.035)) - 0.045) * inner;
265
+ albedo = mix(albedo, mix(vec3(0.33, 0.07, 0.14), uPink, tongue), inner);
266
+ float lip = inside(abs(length(w) - 0.062) - 0.014) * step(w.y, 0.004);
267
+ float philtrum = inside(segment(p, vec2(0.0, -0.12), vec2(0.0, -0.175)) - 0.014);
268
+ float jaw = inside(hole - 0.013) * (1.0 - inner);
269
+ float surprised = inside(abs(ellipse(p - vec2(0.0, -0.245), vec2(0.045, 0.055))) - 0.014);
270
+ float mouth = max(philtrum, max(max(lip, jaw) * (1.0 - wide), surprised * wide)) * front;
271
+ albedo = mix(albedo, uInk, mouth);
272
+ // The nose goes on last, so the line from it starts under its tip with no gap.
273
+ vec2 n = p - vec2(0.0, -0.1);
274
+ float nose = inside(max(abs(n.x) - 0.066 * clamp(1.0 + n.y * 7.0, 0.15, 1.4), abs(n.y) - 0.038) - 0.006) * front;
275
+ albedo = mix(albedo, uPink, nose);
276
+ unlit = max(unlit, max(max(mouth, inner), ball));
277
+ #endif
278
+
279
+ #ifdef BODY
280
+ float belly = inside(ellipse(l.xy - vec2(0.0, 0.42), vec2(0.27, 0.42))) * smoothstep(0.04, 0.2, l.z);
281
+ float band = abs(fract(l.y * 3.3 + 0.06 * sin(l.x * 9.0)) - 0.5) - (0.17 - 0.2 * abs(l.x));
282
+ float stripe = inside(band) * smoothstep(0.1, -0.12, l.z) * step(0.2, l.y);
283
+ albedo = mix(mix(albedo, uStripe, stripe), uCream, belly);
284
+ #endif
285
+
286
+ #ifdef TAIL
287
+ float t = vUv.x;
288
+ float ring = inside(abs(fract(t * 4.0 + 0.3) - 0.5) - 0.16) * step(0.25, t);
289
+ albedo = mix(albedo, uStripe, max(ring, step(0.88, t)));
290
+ #endif
291
+
292
+ #ifdef LIMB
293
+ // Two tabby rings along each arm and leg segment (uv.y runs along the capsule), so limbs read apart from the body.
294
+ albedo = mix(albedo, uStripe, inside(abs(fract(vUv.y * 2.0 + 0.25) - 0.5) - 0.1));
295
+ #endif
296
+
297
+ #ifdef EAR
298
+ float inner = max(abs(l.x) - 0.12 * (1.0 - (l.y - 0.02) / 0.3), max(0.03 - l.y, l.y - 0.3));
299
+ albedo = mix(albedo, uPink, inside(inner) * smoothstep(0.0, 0.03, l.z));
300
+ #endif
301
+
302
+ // Toon lighting from one fixed light: lit or shaded, plus a soft highlight band and a rim.
303
+ vec3 normal = normalize(vNormal);
304
+ float light = dot(normal, uLight);
305
+ float lit = smoothstep(-0.04, 0.04, light), high = smoothstep(0.72, 0.8, light);
306
+ vec3 color = albedo * mix(vec3(0.6, 0.5, 0.68), vec3(1.0), lit) + albedo * 0.12 * high;
307
+ float facing = max(dot(normal, normalize(-vView)), 0.0);
308
+ // The rim catches the top and side edges, as a light from above and behind would, never the chin.
309
+ color += uRim * smoothstep(0.7, 0.88, 1.0 - facing) * (0.55 - 0.3 * lit) * smoothstep(-0.35, 0.25, normal.y);
310
+ color = mix(color, albedo, unlit * 0.7);
311
+ gl_FragColor = vec4(color, 1.0);
312
+ #include <colorspace_fragment>
313
+ }`;
314
+
315
+ const OUTLINE_VERTEX = /* glsl */ `
316
+ uniform float uWidth;
317
+ void main() {
318
+ vec4 view = modelViewMatrix * vec4(position, 1.0);
319
+ // Push out along the normal by an amount that grows with distance, so the line keeps its width on screen.
320
+ view.xyz += normalize(normalMatrix * normal) * uWidth * -view.z;
321
+ gl_Position = projectionMatrix * view;
322
+ }`;
323
+ const OUTLINE_FRAGMENT = /* glsl */ `
324
+ uniform vec3 uInk;
325
+ void main() {
326
+ gl_FragColor = vec4(uInk, 1.0);
327
+ #include <colorspace_fragment>
328
+ }`;
329
+
330
+ // ---- The pose: named channels, each a value chasing a target on a spring ----
331
+ const C = {
332
+ x: 0, y: 1, lean: 2, bend: 3, twist: 4, squash: 5, nod: 6, tilt: 7, turn: 8,
333
+ leftPawX: 9, leftPawY: 10, leftPawZ: 11, rightPawX: 12, rightPawY: 13, rightPawZ: 14,
334
+ leftFootX: 15, leftLift: 16, rightFootX: 17, rightLift: 18,
335
+ tailLift: 19, tailSway: 20, ears: 21, happy: 22, wide: 23, mouth: 24, look: 25,
336
+ } as const;
337
+ const CHANNELS = 26;
338
+ /** Spring stiffness per channel: the body is snappy, ears and tail lag and overshoot. */
339
+ const STIFFNESS = new Float32Array(CHANNELS).fill(260);
340
+ STIFFNESS[C.tailLift] = STIFFNESS[C.tailSway] = 60;
341
+ STIFFNESS[C.ears] = 120;
342
+ STIFFNESS[C.happy] = STIFFNESS[C.wide] = STIFFNESS[C.mouth] = 400;
343
+
344
+ type MoveKind = Lane | "stumble" | "celebrate";
345
+ interface Move { kind: MoveKind; start: number; length: number; size: number; variant: number }
346
+
347
+ // Shapes of time for a move, u running 0 to 1: a quick wind-up the other way, then the action.
348
+ const clamp01 = (value: number) => Math.min(1, Math.max(0, value));
349
+ const windUp = (u: number) => (u < 0.16 ? Math.sin((Math.PI * u) / 0.16) : 0);
350
+ const action = (u: number) => clamp01((u - 0.1) / 0.18) * (1 - clamp01((u - 0.62) / 0.38));
351
+ const arc = (u: number, from: number, to: number) => Math.sin(Math.PI * clamp01((u - from) / (to - from)));
352
+
22
353
  export function createCat(): Cat {
23
- const root = new THREE.Group(), figure = new THREE.Group(), head = new THREE.Group();
24
- root.add(figure);
25
354
  const geometries: THREE.BufferGeometry[] = [], materials: THREE.Material[] = [];
26
- const sphere = new THREE.SphereGeometry(1, 28, 20), cone = new THREE.ConeGeometry(0.3, 0.52, 4);
27
- geometries.push(sphere, cone);
28
- const paint = (color: string, roughness = 0.85) => {
29
- const material = new THREE.MeshStandardMaterial({ color, roughness });
355
+ const color = (hex: string) => ({ value: new THREE.Color(hex) });
356
+ // Shared uniforms: one update reaches every part.
357
+ const shared = {
358
+ uLight: { value: new THREE.Vector3(-0.45, 0.62, 0.64).normalize() },
359
+ uRim: { value: new THREE.Color("#7f6bff") },
360
+ uCream: color(CREAM), uStripe: color(STRIPE), uPink: color(PINK), uInk: color(INK), uIris: color(IRIS), uIrisDark: color(IRIS_DARK),
361
+ uFace: { value: new THREE.Vector4(1, 0, 0, 0) },
362
+ uLook: { value: new THREE.Vector2() },
363
+ };
364
+ const toon = (base: string, pattern?: "HEAD" | "BODY" | "TAIL" | "EAR" | "LIMB") => {
365
+ const material = new THREE.ShaderMaterial({ uniforms: { ...shared, uBase: color(base) }, vertexShader: VERTEX, fragmentShader: FRAGMENT, defines: pattern ? { [pattern]: "" } : {} });
30
366
  materials.push(material);
31
367
  return material;
32
368
  };
33
- const fur = paint(FUR), dark = paint(FUR_DARK), cream = paint(CREAM), pink = paint(PINK, 0.6), ink = paint(INK, 0.3);
34
- const part = (parent: THREE.Object3D, geometry: THREE.BufferGeometry, material: THREE.Material, position: Triple, scale: Triple) => {
369
+ const outline = new THREE.ShaderMaterial({ uniforms: { uWidth: { value: 0.0042 }, uInk: shared.uInk }, vertexShader: OUTLINE_VERTEX, fragmentShader: OUTLINE_FRAGMENT, side: THREE.BackSide });
370
+ materials.push(outline);
371
+ /** A part and its outline, which shares the geometry. */
372
+ const part = (parent: THREE.Object3D, geometry: THREE.BufferGeometry, material: THREE.Material) => {
373
+ geometries.push(geometry);
35
374
  const mesh = new THREE.Mesh(geometry, material);
36
- mesh.position.set(position[0], position[1], position[2]);
37
- mesh.scale.set(scale[0], scale[1], scale[2]);
375
+ mesh.add(new THREE.Mesh(geometry, outline));
38
376
  parent.add(mesh);
39
377
  return mesh;
40
378
  };
41
379
 
42
- // Upright body with a cream tummy and two stripes.
43
- part(figure, sphere, fur, [0, 1.0, 0], [0.78, 0.95, 0.7]);
44
- part(figure, sphere, cream, [0, 0.92, 0.36], [0.5, 0.62, 0.42]);
45
- for (const y of [1.25, 1.0]) part(figure, sphere, dark, [0, y, -0.62], [0.42, 0.06, 0.08]);
46
-
47
- // Feet stay planted; front paws are the arms that do the dancing.
48
- for (const side of [-1, 1]) part(figure, sphere, cream, [side * 0.36, 0.14, 0.2], [0.26, 0.15, 0.36]);
49
- const leftPaw = part(figure, sphere, cream, [-0.74, 1.05, 0.25], [0.2, 0.2, 0.2]);
50
- const rightPaw = part(figure, sphere, cream, [0.74, 1.05, 0.25], [0.2, 0.2, 0.2]);
51
-
52
- const tail: THREE.Mesh[] = [];
53
- for (let i = 0; i < 7; i++) {
54
- const size = 0.17 - i * 0.01;
55
- tail.push(part(figure, sphere, dark, [0, 0.45 + i * 0.17, -0.7 - i * 0.1], [size, size, size]));
56
- }
57
-
58
- head.position.set(0, 2.2, 0.08);
380
+ // root > figure (hips: position, lean, twist) > [torso, arms, tail, head pivot]; legs hang off the root.
381
+ const root = new THREE.Group(), figure = new THREE.Group(), head = new THREE.Group();
382
+ root.add(figure);
383
+ root.scale.setScalar(SCALE);
384
+ const limb = toon(FUR, "LIMB"), cream = toon(CREAM);
385
+ const torso = part(figure, meshSdf(BODY_SDF, [-0.6, -0.1, -0.45], [0.6, 1.08, 0.45], 0.028), toon(FUR, "BODY"));
386
+ const headMesh = part(head, meshSdf(HEAD_SDF, [-0.95, -0.62, -0.66], [0.95, 0.72, 0.72], 0.026), toon(FUR, "HEAD"));
387
+ headMesh.position.set(0, 0.5, 0.06);
59
388
  figure.add(head);
60
- part(head, sphere, fur, [0, 0, 0], [0.74, 0.64, 0.66]);
389
+ const earGeometry = meshSdf(EAR_SDF, [-0.25, -0.25, -0.12], [0.25, 0.44, 0.12], 0.016), earMaterial = toon(FUR, "EAR");
61
390
  const ears = [-1, 1].map(side => {
62
- const ear = part(head, cone, fur, [side * 0.44, 0.58, -0.02], [1, 1, 0.6]);
63
- ear.rotation.z = side * -0.3;
64
- part(ear, cone, pink, [0, -0.04, 0.12], [0.6, 0.7, 0.5]);
391
+ const ear = part(headMesh, side < 0 ? earGeometry : earGeometry.clone(), earMaterial);
392
+ ear.position.set(side * 0.38, 0.42, -0.04);
65
393
  return { ear, side };
66
394
  });
67
- for (const side of [-1, 1]) part(head, sphere, cream, [side * 0.26, -0.2, 0.5], [0.24, 0.18, 0.2]);
68
- part(head, sphere, pink, [0, -0.1, 0.66], [0.07, 0.05, 0.05]);
69
- const eyes = [-1, 1].map(side => part(head, sphere, ink, [side * 0.27, 0.1, 0.57], [0.09, 0.13, 0.05]));
70
- const whiskers = new THREE.LineBasicMaterial({ color: "#ffffff", transparent: true, opacity: 0.7 });
71
- materials.push(whiskers);
72
- for (const side of [-1, 1]) {
73
- for (let i = 0; i < 3; i++) {
74
- const geometry = new THREE.BufferGeometry().setFromPoints([
75
- new THREE.Vector3(side * 0.34, -0.16 - i * 0.05, 0.6),
76
- new THREE.Vector3(side * 0.95, -0.1 - i * 0.13, 0.5),
77
- ]);
78
- geometries.push(geometry);
79
- head.add(new THREE.Line(geometry, whiskers));
80
- }
395
+ // Whiskers: three a side, light against the dark stage.
396
+ const whiskerPoints: number[] = [];
397
+ for (const side of [-1, 1]) for (let i = 0; i < 3; i++) whiskerPoints.push(side * 0.5, -0.12 - i * 0.05, 0.42, side * (1.02 - i * 0.04), -0.04 - i * 0.12, 0.3);
398
+ const whiskerGeometry = new THREE.BufferGeometry();
399
+ whiskerGeometry.setAttribute("position", new THREE.Float32BufferAttribute(whiskerPoints, 3));
400
+ geometries.push(whiskerGeometry);
401
+ const whiskerMaterial = new THREE.LineBasicMaterial({ color: CREAM, transparent: true, opacity: 0.85 });
402
+ materials.push(whiskerMaterial);
403
+ headMesh.add(new THREE.LineSegments(whiskerGeometry, whiskerMaterial));
404
+
405
+ // Limbs: capsules whose ends meet in a round joint, placed by inverse kinematics each frame.
406
+ const UPPER_ARM = 0.3, FOREARM = 0.27, THIGH = 0.22, SHIN = 0.22;
407
+ const arm = (side: number) => ({
408
+ side,
409
+ upper: part(figure, new THREE.CapsuleGeometry(0.085, UPPER_ARM, 4, 10), limb),
410
+ lower: part(figure, new THREE.CapsuleGeometry(0.08, FOREARM, 4, 10), limb),
411
+ paw: part(figure, new THREE.SphereGeometry(0.11, 16, 12), cream),
412
+ });
413
+ const leg = (side: number) => {
414
+ const foot = part(root, new THREE.SphereGeometry(1, 16, 12), cream);
415
+ foot.scale.set(0.12, 0.075, 0.18);
416
+ return { side, upper: part(root, new THREE.CapsuleGeometry(0.1, THIGH, 4, 10), limb), lower: part(root, new THREE.CapsuleGeometry(0.09, SHIN, 4, 10), limb), foot };
417
+ };
418
+ const arms = [arm(-1), arm(1)], legs = [leg(-1), leg(1)];
419
+
420
+ // The tail: a tube of RINGS rings of SIDES vertices plus a tip, rewritten along a curve every frame.
421
+ const RINGS = 18, SIDES = 10, TAIL_LENGTH = 1.25;
422
+ const tailPositions = new Float32Array((RINGS * SIDES + 1) * 3), tailNormals = new Float32Array(tailPositions.length);
423
+ const tailUv = new Float32Array((RINGS * SIDES + 1) * 2), tailIndex: number[] = [];
424
+ for (let ring = 0; ring < RINGS; ring++) for (let s = 0; s < SIDES; s++) {
425
+ tailUv[(ring * SIDES + s) * 2] = ring / (RINGS - 1);
426
+ if (ring < RINGS - 1) {
427
+ const a = ring * SIDES + s, b = ring * SIDES + ((s + 1) % SIDES);
428
+ tailIndex.push(a, b, a + SIDES, b, b + SIDES, a + SIDES); // counter-clockwise seen from outside
429
+ } else tailIndex.push(ring * SIDES + s, ring * SIDES + ((s + 1) % SIDES), RINGS * SIDES);
81
430
  }
431
+ tailUv[RINGS * SIDES * 2] = 1;
432
+ const tailGeometry = new THREE.BufferGeometry();
433
+ tailGeometry.setAttribute("position", new THREE.BufferAttribute(tailPositions, 3).setUsage(THREE.DynamicDrawUsage));
434
+ tailGeometry.setAttribute("normal", new THREE.BufferAttribute(tailNormals, 3).setUsage(THREE.DynamicDrawUsage));
435
+ tailGeometry.setAttribute("uv", new THREE.BufferAttribute(tailUv, 2));
436
+ tailGeometry.setIndex(tailIndex);
437
+ const tail = part(figure, tailGeometry, toon(FUR, "TAIL"));
438
+ tail.frustumCulled = false; // its bounds change every frame
439
+ for (const child of tail.children) child.frustumCulled = false;
440
+
441
+ // ---- Pose state ----
442
+ const target = new Float32Array(CHANNELS), value = new Float32Array(CHANNELS), velocity = new Float32Array(CHANNELS);
443
+ const moves: Move[] = Array.from({ length: 4 }, () => ({ kind: "up" as MoveKind, start: -10, length: 1, size: 0, variant: 0 }));
444
+ let clock = 0, nextMove = 0, spinStart = -10, blinkAt = 2, blinkStart = -10, mood: "neutral" | "happy" | "sad" = "neutral";
445
+ let snapped = false, side = 1;
446
+ const variants: Record<Lane, number> = { left: 0, right: 0, up: 0, down: 0 };
447
+ const start = (kind: MoveKind, length: number, size: number) => {
448
+ const move = moves[nextMove]!;
449
+ nextMove = (nextMove + 1) % moves.length;
450
+ move.kind = kind; move.start = clock; move.length = length; move.size = size;
451
+ if (kind in variants) move.variant = variants[kind as Lane]++ % 2;
452
+ };
453
+
454
+ /** Add one move's contribution to the targets. */
455
+ const applyMove = (move: Move) => {
456
+ const u = (clock - move.start) / move.length;
457
+ if (u < 0 || u > 1) return;
458
+ const t = target, s = move.size, act = action(u) * s, wind = windUp(u) * s;
459
+ switch (move.kind) {
460
+ case "left":
461
+ case "right": {
462
+ // Step to the side and point: a paw up and out (or a low sweep), the other paw on the hip.
463
+ const d = move.kind === "left" ? -1 : 1, low = move.variant === 1;
464
+ t[C.x] += d * 0.3 * act - d * 0.08 * wind;
465
+ t[C.lean] += -d * 0.16 * act;
466
+ t[C.twist] += d * 0.22 * act;
467
+ t[C.squash] += 0.1 * wind - 0.05 * act;
468
+ t[C.tilt] += -d * 0.22 * act;
469
+ t[C.turn] += d * 0.18 * act;
470
+ t[C.tailSway] += -d * 0.9 * act;
471
+ const out = d < 0 ? C.leftPawX : C.rightPawX, other = d < 0 ? C.rightPawX : C.leftPawX;
472
+ t[out] += d * (low ? 0.5 : 0.36) * act;
473
+ t[out + 1] += (low ? 0.2 : 0.62) * act;
474
+ t[out + 2] += 0.12 * act;
475
+ t[other] += -d * 0.08 * act;
476
+ t[other + 1] += 0.2 * act;
477
+ t[other + 2] += -0.06 * act;
478
+ t[d < 0 ? C.leftFootX : C.rightFootX] += d * 0.14 * act;
479
+ t[d < 0 ? C.leftLift : C.rightLift] += 0.14 * s * arc(u, 0.05, 0.4);
480
+ t[C.look] += d * act;
481
+ side = d;
482
+ break;
483
+ }
484
+ case "up": {
485
+ // Crouch, leap with both paws high, land with a squash.
486
+ const air = arc(u, 0.16, 0.72) * s;
487
+ t[C.squash] += 0.2 * wind - 0.14 * air + 0.16 * arc(u, 0.7, 0.92) * s;
488
+ t[C.y] += -0.12 * wind + 0.62 * air;
489
+ t[C.leftLift] += 0.5 * air; t[C.rightLift] += 0.5 * air;
490
+ // Paws up and out beside the cheeks (straight up they would hide behind the big head).
491
+ t[C.leftPawX] -= 0.42 * act; t[C.rightPawX] += 0.42 * act;
492
+ t[C.leftPawY] += 0.8 * act; t[C.rightPawY] += 0.8 * act;
493
+ t[C.leftPawZ] -= 0.08 * act; t[C.rightPawZ] -= 0.08 * act;
494
+ t[C.nod] += -0.25 * act;
495
+ t[C.ears] += -0.6 * act;
496
+ t[C.tailLift] += 0.8 * act;
497
+ t[C.happy] += 0.6 * act;
498
+ break;
499
+ }
500
+ case "down": {
501
+ // A quick rise, then a deep squat, knees out, both paws patting the floor in front, hips shimmying.
502
+ t[C.y] += 0.06 * wind - 0.3 * act;
503
+ t[C.squash] += -0.06 * wind + 0.2 * act;
504
+ t[C.bend] += 0.16 * act;
505
+ t[C.twist] += 0.22 * Math.sin(u * Math.PI * 4) * act;
506
+ t[C.leftPawX] -= 0.1 * act; t[C.rightPawX] += 0.1 * act;
507
+ t[C.leftPawY] += -0.42 * act + 0.12 * arc(u, 0.3, 0.5) * s; t[C.rightPawY] += -0.42 * act + 0.12 * arc(u, 0.45, 0.65) * s;
508
+ t[C.leftPawZ] += 0.24 * act; t[C.rightPawZ] += 0.24 * act;
509
+ t[C.leftFootX] -= 0.14 * act; t[C.rightFootX] += 0.14 * act;
510
+ t[C.nod] += 0.04 * act;
511
+ t[C.tailLift] += 1.2 * act;
512
+ t[C.mouth] += 0.3 * act;
513
+ break;
514
+ }
515
+ case "stumble": {
516
+ // Off balance backwards with paws flailing, wide eyes and flat ears, then back on its feet.
517
+ const fade = 1 - u, wobble = Math.sin(u * 22) * fade;
518
+ t[C.lean] += 0.2 * wobble * side;
519
+ t[C.bend] += -0.1 * fade;
520
+ t[C.x] += -0.08 * side * fade;
521
+ t[C.squash] += 0.08 * fade;
522
+ t[C.leftPawX] -= 0.22 * fade; t[C.rightPawX] += 0.22 * fade;
523
+ t[C.leftPawY] += (0.4 + 0.25 * wobble) * fade; t[C.rightPawY] += (0.4 - 0.25 * wobble) * fade;
524
+ t[side < 0 ? C.rightLift : C.leftLift] += 0.16 * arc(u, 0, 0.35);
525
+ t[C.ears] += 1.1 * fade;
526
+ t[C.wide] += 1.4 * fade;
527
+ t[C.tailLift] -= 0.8 * fade;
528
+ t[C.nod] += -0.12 * fade;
529
+ break;
530
+ }
531
+ case "celebrate": {
532
+ const air = arc(u, 0.1, 0.6);
533
+ t[C.y] += 0.3 * air;
534
+ t[C.leftLift] += 0.3 * air; t[C.rightLift] += 0.3 * air;
535
+ t[C.leftPawX] -= 0.42 * act; t[C.rightPawX] += 0.42 * act;
536
+ t[C.leftPawZ] -= 0.08 * act; t[C.rightPawZ] -= 0.08 * act;
537
+ t[C.leftPawY] += (0.8 + 0.1 * Math.sin(u * 30)) * act; t[C.rightPawY] += (0.8 - 0.1 * Math.sin(u * 30)) * act;
538
+ t[C.happy] += act; t[C.mouth] += act; t[C.tailLift] += act; t[C.ears] -= 0.5 * act;
539
+ break;
540
+ }
541
+ }
542
+ };
543
+
544
+ // ---- Placing limbs ----
545
+ const v1 = new THREE.Vector3(), v2 = new THREE.Vector3(), v3 = new THREE.Vector3(), pole = new THREE.Vector3(), joint = new THREE.Vector3();
546
+ const tip = new THREE.Vector3(), UP = new THREE.Vector3(0, 1, 0);
547
+ /** Two-bone IK: from `base` toward `goal`, bending toward `bend`. Writes the joint and end points. */
548
+ const solve = (base: THREE.Vector3, goal: THREE.Vector3, bend: THREE.Vector3, a: number, b: number) => {
549
+ const reach = v3.subVectors(goal, base), distance = Math.min(Math.max(reach.length(), Math.abs(a - b) + 0.01), a + b - 0.002);
550
+ reach.normalize();
551
+ const cos = (a * a + distance * distance - b * b) / (2 * a * distance), sin = Math.sqrt(Math.max(0, 1 - cos * cos));
552
+ pole.copy(bend).addScaledVector(reach, -bend.dot(reach)).normalize();
553
+ joint.copy(base).addScaledVector(reach, a * cos).addScaledVector(pole, a * sin);
554
+ tip.copy(base).addScaledVector(reach, distance);
555
+ };
556
+ /** Point a capsule (built along +y) from `from` to `to`. */
557
+ const span = (mesh: THREE.Mesh, from: THREE.Vector3, to: THREE.Vector3) => {
558
+ mesh.position.addVectors(from, to).multiplyScalar(0.5);
559
+ mesh.quaternion.setFromUnitVectors(UP, v1.subVectors(to, from).normalize());
560
+ };
561
+
562
+ /** Lay the tail's rings along a curve that rises behind the cat and curls at the tip. */
563
+ const tailFrame = { tangent: new THREE.Vector3(), normal: new THREE.Vector3(), binormal: new THREE.Vector3(), centre: new THREE.Vector3() };
564
+ const placeTail = (lift: number, sway: number, phase: number, sy: number) => {
565
+ const { tangent, normal, binormal, centre } = tailFrame, segment = TAIL_LENGTH / (RINGS - 1);
566
+ centre.set(0, 0.2 * sy, -0.3);
567
+ for (let ring = 0; ring < RINGS; ring++) {
568
+ const s = ring / (RINGS - 1);
569
+ const pitch = 0.25 + (1.3 + 0.5 * lift) * s * s + 0.9 * Math.max(0, s - 0.7) * (1 + lift);
570
+ const yaw = (sway * 0.7 + 0.18 * Math.sin(phase - s * 2.4)) * s;
571
+ tangent.set(Math.sin(yaw) * Math.cos(pitch), Math.sin(pitch), -Math.cos(yaw) * Math.cos(pitch));
572
+ if (ring > 0) centre.addScaledVector(tangent, segment);
573
+ normal.crossVectors(tangent, v2.set(1, 0, 0)).normalize();
574
+ binormal.crossVectors(tangent, normal);
575
+ const radius = 0.085 * (1 - 0.35 * s) * (s > 0.9 ? Math.sqrt(Math.max(0.15, 1 - ((s - 0.9) / 0.1) ** 2)) : 1);
576
+ for (let k = 0; k < SIDES; k++) {
577
+ const angle = (k / SIDES) * Math.PI * 2, c = Math.cos(angle), n = Math.sin(angle), o = (ring * SIDES + k) * 3;
578
+ const nx = normal.x * c + binormal.x * n, ny = normal.y * c + binormal.y * n, nz = normal.z * c + binormal.z * n;
579
+ tailPositions[o] = centre.x + nx * radius; tailPositions[o + 1] = centre.y + ny * radius; tailPositions[o + 2] = centre.z + nz * radius;
580
+ tailNormals[o] = nx; tailNormals[o + 1] = ny; tailNormals[o + 2] = nz;
581
+ }
582
+ }
583
+ const o = RINGS * SIDES * 3;
584
+ tailPositions[o] = centre.x + tangent.x * 0.03; tailPositions[o + 1] = centre.y + tangent.y * 0.03; tailPositions[o + 2] = centre.z + tangent.z * 0.03;
585
+ tailNormals[o] = tangent.x; tailNormals[o + 1] = tangent.y; tailNormals[o + 2] = tangent.z;
586
+ tailGeometry.attributes.position!.needsUpdate = true;
587
+ tailGeometry.attributes.normal!.needsUpdate = true;
588
+ };
589
+
590
+ const shoulder = new THREE.Vector3(), hand = new THREE.Vector3(), hip = new THREE.Vector3(), ankle = new THREE.Vector3();
82
591
 
83
- // Each move is a short pulse (1 fading to 0) that the pose below reads.
84
- const pulse = { left: 0, right: 0, up: 0, down: 0, stumble: 0 };
85
- let clock = 0;
86
592
  return {
87
593
  root,
88
- dance(lane) {
89
- pulse[lane] = 1;
594
+ head,
595
+ lift: () => Math.max(0, value[C.y]!) * SCALE,
596
+ dance(lane, judgement) {
597
+ start(lane, lane === "up" ? 0.62 : 0.5, judgement === "perfect" ? 1.15 : judgement === "great" ? 1 : 0.8);
598
+ target[C.happy] = 0;
599
+ if (judgement === "perfect") velocity[C.happy] += 14;
90
600
  },
91
601
  stumble() {
92
- pulse.stumble = 1;
602
+ start("stumble", 0.85, 1);
603
+ },
604
+ celebrate() {
605
+ start("celebrate", 0.9, 1);
606
+ spinStart = clock;
607
+ },
608
+ setMood(next) {
609
+ mood = next;
610
+ },
611
+ setRim(next) {
612
+ shared.uRim.value.copy(next);
93
613
  },
94
- animate(seconds, beatPhase) {
614
+ animate(seconds, beat, energy = 0.6) {
95
615
  clock += seconds;
96
- for (const key of Object.keys(pulse) as (keyof typeof pulse)[]) pulse[key] = Math.max(0, pulse[key] - seconds * 3.2);
97
- const ease = (value: number) => Math.sin(value * Math.PI); // up and back down over one pulse
98
- const side = ease(pulse.right) - ease(pulse.left), jump = ease(pulse.up), crouch = ease(pulse.down), wobble = pulse.stumble;
99
- // The idle bounce: a quick dip right on the beat that relaxes before the next one.
100
- const bounce = Math.pow(1 - beatPhase, 3);
101
-
102
- figure.position.x = side * 0.75;
103
- figure.position.y = jump * 1.1;
104
- figure.rotation.z = -side * 0.28 + Math.sin(clock * 38) * 0.07 * wobble;
105
- figure.rotation.y = side * 0.35;
106
- figure.scale.y = 1 - bounce * 0.07 - crouch * 0.38 + jump * 0.08;
107
- figure.scale.x = figure.scale.z = 1 + bounce * 0.04 + crouch * 0.2;
108
-
109
- head.rotation.x = bounce * 0.18 + crouch * 0.25 - jump * 0.2;
110
- head.rotation.z = side * 0.2;
111
-
112
- // Paws: the stepping side punches out, both go up for a jump, both drop for a crouch.
113
- const leftUp = Math.max(ease(pulse.left), jump), rightUp = Math.max(ease(pulse.right), jump);
114
- leftPaw.position.set(-0.74 - ease(pulse.left) * 0.45, 1.05 + leftUp * 0.85 - crouch * 0.4 + bounce * 0.06, 0.25);
115
- rightPaw.position.set(0.74 + ease(pulse.right) * 0.45, 1.05 + rightUp * 0.85 - crouch * 0.4 + bounce * 0.06, 0.25);
116
-
117
- // Eyes squeeze shut on a landed jump; ears go flat on a stumble.
118
- for (const eye of eyes) eye.scale.y = 0.13 * (1 - jump * 0.7) * (1 - wobble * 0.5);
119
- for (const { ear, side: earSide } of ears) ear.rotation.z = earSide * (-0.3 - wobble * 0.8);
120
- tail.forEach((segment, index) => {
121
- segment.position.x = Math.sin(clock * 6 + index * 0.55) * 0.05 * index + side * -0.06 * index;
122
- });
616
+ const e = energy, t = target, swing = Math.sin(Math.PI * beat), dip = 0.5 + 0.5 * Math.cos(2 * Math.PI * beat);
617
+ // The idle groove, locked to the beat: dip on each beat, sway across two, steps in place.
618
+ t.fill(0);
619
+ t[C.y] = -0.05 * e * dip;
620
+ t[C.squash] = 0.045 * e * dip;
621
+ t[C.x] = 0.07 * e * swing;
622
+ t[C.lean] = -0.07 * e * swing;
623
+ // A slight upward gaze, toward the camera above the stage.
624
+ t[C.nod] = -0.12 + 0.09 * e * Math.cos(2 * Math.PI * (beat - 0.12));
625
+ t[C.tilt] = 0.1 * e * Math.sin(Math.PI * beat - 0.4);
626
+ t[C.leftPawY] = 0.07 * e * swing; t[C.rightPawY] = -0.07 * e * swing;
627
+ t[C.leftPawZ] = 0.04 * e * dip; t[C.rightPawZ] = 0.04 * e * dip;
628
+ t[C.leftLift] = 0.05 * e * Math.max(0, swing); t[C.rightLift] = 0.05 * e * Math.max(0, -swing);
629
+ t[C.tailSway] = 0.5 * Math.sin(Math.PI * beat * 0.5);
630
+ t[C.tailLift] = mood === "sad" ? -0.6 : 0.1 * e;
631
+ if (mood === "happy") { t[C.happy] = 1; t[C.mouth] = 0.8; }
632
+ if (mood === "sad") { t[C.ears] = 0.8; t[C.nod] += 0.15; }
633
+ for (const move of moves) applyMove(move);
634
+ t[C.happy] = Math.min(1, t[C.happy]);
635
+
636
+ // Springs: critically damped-ish for the body, looser for the ears and tail.
637
+ if (!snapped || seconds <= 0) {
638
+ value.set(t);
639
+ velocity.fill(0);
640
+ snapped = seconds > 0;
641
+ } else {
642
+ for (let i = 0; i < CHANNELS; i++) {
643
+ const k = STIFFNESS[i]!, damping = 2 * Math.sqrt(k) * (i === C.tailLift || i === C.tailSway || i === C.ears ? 0.35 : 0.7);
644
+ velocity[i] = velocity[i]! + (k * (t[i]! - value[i]!) - damping * velocity[i]!) * seconds;
645
+ value[i] = value[i]! + velocity[i]! * seconds;
646
+ }
647
+ // Secondary motion: the ears flop against fast vertical moves; the tail drags behind the hips.
648
+ velocity[C.ears] = velocity[C.ears]! + velocity[C.y]! * 0.6 * seconds * 60 * 0.05;
649
+ velocity[C.tailSway] = velocity[C.tailSway]! - velocity[C.x]! * 0.8 * seconds * 60 * 0.05;
650
+ }
651
+ const p = value;
652
+
653
+ // Body: squash and stretch keep the volume (taller means thinner).
654
+ const sy = 1 - p[C.squash]!, sxz = 1 / Math.sqrt(Math.max(0.5, sy));
655
+ const spinU = clamp01((clock - spinStart) / 0.7), spin = spinU < 1 ? Math.PI * 2 * (spinU * spinU * (3 - 2 * spinU)) : 0;
656
+ figure.position.set(p[C.x]!, 0.36 + p[C.y]!, 0);
657
+ figure.rotation.set(p[C.bend]!, p[C.twist]! + spin, p[C.lean]!);
658
+ torso.scale.set(sxz, sy, sxz);
659
+ head.position.set(0, 0.8 * sy, 0.02);
660
+ head.rotation.set(p[C.nod]!, p[C.turn]!, p[C.tilt]!);
661
+ head.scale.set(1 + (sxz - 1) * 0.4, 1 - (1 - sy) * 0.4, 1);
662
+ for (const { ear, side: s } of ears) {
663
+ // Ears perk forward (negative) or flatten back and out (positive).
664
+ ear.rotation.set(-0.12 - p[C.ears]! * 0.45, 0, s * (-0.32 - p[C.ears]! * 0.32));
665
+ }
666
+
667
+ // Face: blink every few seconds, unless the eyes are already happy arcs.
668
+ if (clock > blinkAt) { blinkStart = clock; blinkAt = clock + 2 + ((clock * 7919) % 3); }
669
+ const blink = clock - blinkStart < 0.14 ? Math.sin(((clock - blinkStart) / 0.14) * Math.PI) : 0;
670
+ shared.uFace.value.set(1 - blink, clamp01(p[C.happy]!), clamp01(p[C.wide]!), clamp01(p[C.mouth]!));
671
+ shared.uLook.value.set(Math.max(-1, Math.min(1, p[C.look]!)), 0);
672
+
673
+ // Arms, in the figure's space.
674
+ for (const limb of arms) {
675
+ const s = limb.side, base = s < 0 ? C.leftPawX : C.rightPawX;
676
+ shoulder.set(s * 0.25 * sxz, 0.66 * sy, 0.05);
677
+ hand.set(s * 0.25 + p[base]!, 0.42 * sy + p[base + 1]!, 0.5 + p[base + 2]!);
678
+ solve(shoulder, hand, v2.set(s, -0.4, -0.5), UPPER_ARM, FOREARM);
679
+ span(limb.upper, shoulder, joint);
680
+ span(limb.lower, joint, tip);
681
+ limb.paw.position.copy(tip).addScaledVector(v3.subVectors(tip, joint).normalize(), 0.06);
682
+ }
683
+ // Legs, in the root's space: hips come from the figure, feet stay on the floor unless lifted.
684
+ figure.updateMatrix();
685
+ const cosSpin = Math.cos(spin), sinSpin = Math.sin(spin);
686
+ for (const limb of legs) {
687
+ const s = limb.side;
688
+ hip.set(s * 0.17 * sxz, 0.18 * sy, 0).applyMatrix4(figure.matrix);
689
+ const footX = s * 0.21 + p[s < 0 ? C.leftFootX : C.rightFootX]!, footZ = 0.04;
690
+ ankle.set(footX * cosSpin + footZ * sinSpin, 0.11 + Math.max(0, p[s < 0 ? C.leftLift : C.rightLift]!), footZ * cosSpin - footX * sinSpin);
691
+ ankle.x += p[C.x]! * 0.6;
692
+ solve(hip, ankle, v2.set(s * 0.35 * cosSpin + sinSpin, 0, cosSpin - s * 0.35 * sinSpin), THIGH, SHIN);
693
+ span(limb.upper, hip, joint);
694
+ span(limb.lower, joint, tip);
695
+ limb.foot.position.set(tip.x + sinSpin * 0.06, Math.max(0.075, tip.y - 0.04), tip.z + cosSpin * 0.06);
696
+ limb.foot.rotation.y = figure.rotation.y * 0.5;
697
+ }
698
+ placeTail(p[C.tailLift]!, p[C.tailSway]!, beat * Math.PI * 0.5, sy);
123
699
  },
124
700
  dispose() {
125
701
  for (const geometry of geometries) geometry.dispose();