@voqalize/avatar 0.3.0 → 0.4.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.
Files changed (147) hide show
  1. package/LICENSE-CC-BY-4.0 +396 -0
  2. package/README.md +65 -17
  3. package/assets/README.md +48 -0
  4. package/assets/tanya.glb +0 -0
  5. package/assets/tara.glb +0 -0
  6. package/assets/tushar.glb +0 -0
  7. package/client/AvatarClient.ts +337 -42
  8. package/client/arjun.ts +2 -0
  9. package/client/createAvatar.ts +38 -0
  10. package/client/index.ts +6 -1
  11. package/client/internal.ts +31 -3
  12. package/client/ishita.ts +2 -0
  13. package/client/kabir.ts +2 -0
  14. package/client/meera.ts +2 -0
  15. package/client/naina.ts +2 -0
  16. package/client/playout.ts +95 -0
  17. package/client/supports.ts +28 -0
  18. package/client/three/assets.ts +22 -0
  19. package/client/three/budgets.ts +27 -0
  20. package/client/three/holds.ts +64 -0
  21. package/client/three/internal.ts +54 -0
  22. package/client/three/motion-limits.json +116 -0
  23. package/client/three/sequences.ts +281 -0
  24. package/client/three/tanya-asset.ts +6 -0
  25. package/client/three/tanya.ts +69 -0
  26. package/client/three/tara-asset.ts +25 -0
  27. package/client/three/tara-rig.ts +1571 -0
  28. package/client/three/tara.ts +77 -0
  29. package/client/three/tushar-asset.ts +6 -0
  30. package/client/three/tushar.ts +65 -0
  31. package/client/types.ts +109 -20
  32. package/client/vikram.ts +2 -0
  33. package/dist/AvatarClient.d.ts +89 -11
  34. package/dist/AvatarClient.d.ts.map +1 -1
  35. package/dist/AvatarClient.js +297 -35
  36. package/dist/AvatarClient.js.map +1 -1
  37. package/dist/arjun.d.ts +1 -0
  38. package/dist/arjun.d.ts.map +1 -1
  39. package/dist/arjun.js +2 -0
  40. package/dist/arjun.js.map +1 -1
  41. package/dist/createAvatar.d.ts +36 -0
  42. package/dist/createAvatar.d.ts.map +1 -1
  43. package/dist/createAvatar.js.map +1 -1
  44. package/dist/index.d.ts +6 -2
  45. package/dist/index.d.ts.map +1 -1
  46. package/dist/index.js +5 -1
  47. package/dist/index.js.map +1 -1
  48. package/dist/internal.d.ts +9 -5
  49. package/dist/internal.d.ts.map +1 -1
  50. package/dist/internal.js +13 -5
  51. package/dist/internal.js.map +1 -1
  52. package/dist/ishita.d.ts +1 -0
  53. package/dist/ishita.d.ts.map +1 -1
  54. package/dist/ishita.js +2 -0
  55. package/dist/ishita.js.map +1 -1
  56. package/dist/kabir.d.ts +1 -0
  57. package/dist/kabir.d.ts.map +1 -1
  58. package/dist/kabir.js +2 -0
  59. package/dist/kabir.js.map +1 -1
  60. package/dist/meera.d.ts +1 -0
  61. package/dist/meera.d.ts.map +1 -1
  62. package/dist/meera.js +2 -0
  63. package/dist/meera.js.map +1 -1
  64. package/dist/naina.d.ts +1 -0
  65. package/dist/naina.d.ts.map +1 -1
  66. package/dist/naina.js +2 -0
  67. package/dist/naina.js.map +1 -1
  68. package/dist/playout.d.ts +42 -0
  69. package/dist/playout.d.ts.map +1 -0
  70. package/dist/playout.js +85 -0
  71. package/dist/playout.js.map +1 -0
  72. package/dist/supports.d.ts +20 -0
  73. package/dist/supports.d.ts.map +1 -0
  74. package/dist/supports.js +26 -0
  75. package/dist/supports.js.map +1 -0
  76. package/dist/three/assets.d.ts +8 -0
  77. package/dist/three/assets.d.ts.map +1 -0
  78. package/dist/three/assets.js +19 -0
  79. package/dist/three/assets.js.map +1 -0
  80. package/dist/three/budgets.d.ts +17 -0
  81. package/dist/three/budgets.d.ts.map +1 -0
  82. package/dist/three/budgets.js +21 -0
  83. package/dist/three/budgets.js.map +1 -0
  84. package/dist/three/holds.d.ts +33 -0
  85. package/dist/three/holds.d.ts.map +1 -0
  86. package/dist/three/holds.js +56 -0
  87. package/dist/three/holds.js.map +1 -0
  88. package/dist/three/internal.d.ts +52 -0
  89. package/dist/three/internal.d.ts.map +1 -0
  90. package/dist/three/internal.js +49 -0
  91. package/dist/three/internal.js.map +1 -0
  92. package/dist/three/motion-limits.json +116 -0
  93. package/dist/three/sequences.d.ts +71 -0
  94. package/dist/three/sequences.d.ts.map +1 -0
  95. package/dist/three/sequences.js +262 -0
  96. package/dist/three/sequences.js.map +1 -0
  97. package/dist/three/tanya-asset.d.ts +7 -0
  98. package/dist/three/tanya-asset.d.ts.map +1 -0
  99. package/dist/three/tanya-asset.js +7 -0
  100. package/dist/three/tanya-asset.js.map +1 -0
  101. package/dist/three/tanya.d.ts +35 -0
  102. package/dist/three/tanya.d.ts.map +1 -0
  103. package/dist/three/tanya.js +51 -0
  104. package/dist/three/tanya.js.map +1 -0
  105. package/dist/three/tara-asset.d.ts +26 -0
  106. package/dist/three/tara-asset.d.ts.map +1 -0
  107. package/dist/three/tara-asset.js +26 -0
  108. package/dist/three/tara-asset.js.map +1 -0
  109. package/dist/three/tara-rig.d.ts +409 -0
  110. package/dist/three/tara-rig.d.ts.map +1 -0
  111. package/dist/three/tara-rig.js +1504 -0
  112. package/dist/three/tara-rig.js.map +1 -0
  113. package/dist/three/tara.d.ts +35 -0
  114. package/dist/three/tara.d.ts.map +1 -0
  115. package/dist/three/tara.js +59 -0
  116. package/dist/three/tara.js.map +1 -0
  117. package/dist/three/tushar-asset.d.ts +7 -0
  118. package/dist/three/tushar-asset.d.ts.map +1 -0
  119. package/dist/three/tushar-asset.js +7 -0
  120. package/dist/three/tushar-asset.js.map +1 -0
  121. package/dist/three/tushar.d.ts +31 -0
  122. package/dist/three/tushar.d.ts.map +1 -0
  123. package/dist/three/tushar.js +47 -0
  124. package/dist/three/tushar.js.map +1 -0
  125. package/dist/types.d.ts +65 -10
  126. package/dist/types.d.ts.map +1 -1
  127. package/dist/types.js +58 -11
  128. package/dist/types.js.map +1 -1
  129. package/dist/vikram.d.ts +1 -0
  130. package/dist/vikram.d.ts.map +1 -1
  131. package/dist/vikram.js +2 -0
  132. package/dist/vikram.js.map +1 -1
  133. package/package.json +34 -6
  134. package/src/avatar.d.ts +59 -2
  135. package/src/avatar.js +743 -94
  136. package/src/behavior.d.ts +28 -12
  137. package/src/behavior.js +54 -42
  138. package/src/canvas/create-rig.js +1 -1
  139. package/src/canvas/src/live.js +2 -2
  140. package/src/conformance.js +1 -1
  141. package/src/emotions.js +4 -2
  142. package/src/gaze.js +334 -73
  143. package/src/head.js +134 -0
  144. package/src/idle.js +210 -19
  145. package/src/interjections.js +70 -26
  146. package/src/prosody.js +647 -0
  147. package/src/visemes.js +85 -15
@@ -0,0 +1,1571 @@
1
+
2
+ /**
3
+ * tara's renderer: the `AvatarRig` contract (`apply(frame)` / `destroy()`)
4
+ * over the Blender-authored GLB.
5
+ *
6
+ * The whole file is one idea — **the pose channel is the interface, and every
7
+ * mapping here is a translation of one channel into the one control that
8
+ * renders it.** `scripts/morphs.py` authored the shape keys under the library's
9
+ * own channel names precisely so this file never has to interpret a viseme, a
10
+ * state or an emotion; it receives a fully mixed pose and moves geometry.
11
+ *
12
+ * Three kinds of control, in the order they appear below:
13
+ *
14
+ * morph targets the face itself — lips, jaw, lids, brows, and the mouth
15
+ * interior that has to choreograph with them
16
+ * head group `headYaw` / `headPitch` / `headRoll`, as a rotation of the
17
+ * parts that ride the skull about the jaw-angle pivot
18
+ * eye globes `pupilX` / `pupilY`, as a rotation of the eyeball, because
19
+ * the iris is painted onto a sphere and cannot slide
20
+ *
21
+ * and a fourth, for the body: `shoulderL/R` are morph targets on the torso
22
+ * shell like any face channel, and `breath`, `torsoLean` and `torsoTurn` are
23
+ * each one transform of a group — a swell, a scale, a sway (see `BODY`).
24
+ *
25
+ * An asset may add a fifth: expression maps, which change the face's *light*
26
+ * where a smile or a raised brow would, because moving the geometry cannot
27
+ * (see `expressive`).
28
+ */
29
+
30
+ import { REST } from "../internal.js";
31
+ import type { AvatarFrame, AvatarRig, RigPose } from "../internal.js";
32
+ import * as THREE from "three";
33
+ import { GLTFLoader } from "three/addons/loaders/GLTFLoader.js";
34
+ import { HARD_BUDGET, pixelRatioFor } from "./budgets.js";
35
+
36
+ /**
37
+ * The camera, from `scripts/render_frame.py`. It is orthographic and that is
38
+ * forced by the albedo rather than chosen: the atlas is a front-orthographic
39
+ * projection of the shell, so an atlas texel sits at face-space (u, v) whatever
40
+ * depth the triangle carrying it has. A perspective camera disagrees by
41
+ * (offset from the axis) x (depth / distance) — which put the hair rim 3 px
42
+ * above the hairline it is textured to and opened a black band across the
43
+ * forehead. `build_tara.setup_scene` has the measurement.
44
+ */
45
+ const FRAME = { bottom: -0.52, top: 1.46 };
46
+ const FRAME_HEIGHT = FRAME.top - FRAME.bottom;
47
+ const FRAME_CENTRE = (FRAME.top + FRAME.bottom) / 2;
48
+
49
+ /**
50
+ * Head motion, in degrees at the channel's own clamp of ±1.4.
51
+ *
52
+ * These are the program's *working* envelope, mapped so that a channel pinned to
53
+ * its limit lands exactly on it. That is the point of scaling by the clamp
54
+ * rather than by 1: the mixer cannot ask for more than the envelope allows, and
55
+ * the hard ceiling stays unreachable by construction instead of by a second
56
+ * clamp nobody runs.
57
+ *
58
+ * **It opened on 2026-09-12, from yaw ±6°, pitch ±5°, roll ±3°.** That
59
+ * envelope made Busso's neutral-speech numbers unreachable: his mean
60
+ * per-sentence pitch *range* is 9.5°, which is 95 % of everything ±5° could
61
+ * ever produce, so speaking alone would have swung the channel corner to corner
62
+ * and a deliberate nod on top of it would have had nowhere left to go. What had
63
+ * held it there was the asset, not anatomy — the neck's follow was linear and
64
+ * drew a second jawline past a few degrees — and once that follow became exact
65
+ * (`NECK_QUAD` below) pitch could open to 24 and roll to 8.
66
+ *
67
+ * Yaw is still the smallest because it is the one axis this rig is genuinely
68
+ * constrained on: the albedo is a front-orthographic projection of a 0.34-deep
69
+ * shell, and a large turn is where that reads as a cardboard cutout rather than
70
+ * a head. **It opened from 9° to 15° on 2026-09-18.** The cutout was measured
71
+ * rather than assumed — a ladder rendered at 9/12/15/18/21/25/30 and read at
72
+ * crop on all three characters is clean to 21° on tara and to 18° on tanya and
73
+ * tushar. 9° was therefore set at half of where the artefact actually begins,
74
+ * and the stiffness the owner reported on tanya's turns was that margin, not
75
+ * her asset. 15° keeps 3° of headroom on the tightest of the three.
76
+ *
77
+ * This is not for speech: Busso wants ±1.15° of yaw in neutral conversation and
78
+ * always did. It is for a head that turns to *look* at something, which is what
79
+ * mocap drives and what pegged the channel — a real 25° turn still saturates at
80
+ * 15°, so this widens the envelope without making it generous.
81
+ *
82
+ * And it is not the angle a pose may be *held* at, which is a stricter question
83
+ * with its own measurement per character (`motion-limits.json`, applied through
84
+ * `holds.ts`): a turn that returns is forgiven what a sustained one is not. The
85
+ * two numbers differ by about 3x on yaw and neither is a correction of the
86
+ * other.
87
+ *
88
+ * **Editing these needs no rebuild, but it is not free.** The neck's fields
89
+ * carry no angle, so `tara.glb` cannot go stale against them. What a number
90
+ * here does move:
91
+ *
92
+ * - Every clip is authored in channel units, so a degree here re-sizes every
93
+ * clip driving that axis. `test/nods.test.ts` bands *pitch* only — `down`,
94
+ * `up`, `upFirst` — and computes `yawPP` without ever asserting it. A yaw
95
+ * change moves nothing there; a pitch change moves four tests.
96
+ * - `head_parallax.py` and `validate_morphs.py` quote their gates at this
97
+ * envelope. `validate_morphs` reads `morphs.head_envelope()`, but
98
+ * `head_parallax.POSES` hardcoded `yaw 9` until 2026-09-18 and would have
99
+ * gone on grading 9° while the rig shipped 15° — a gate defending a number
100
+ * nothing used. It derives both angles from here now.
101
+ * - The yaw twist's two fields are an expansion in the angle, so their error
102
+ * grows as θ²/6. Against the exact rotation at the maximum ramp
103
+ * (`NECK_TWIST` = 0.5) that is 0.31 % at 9°, 0.85 % at 15°, 1.23 % at 18°
104
+ * (`morphs.neck_twist`). The note here used to read as a wall at 9°; it is
105
+ * not one — 15° costs under a percent of a displacement that is itself a
106
+ * fraction of the neck's radius.
107
+ *
108
+ * TARA-SPECIFIC: each number is her reach before an artefact shows — yaw by
109
+ * the cutout, pitch by the neck fold that starts to crease at 24° chin-up.
110
+ * Both were measured on the shipping surface, one axis at a time. This is still
111
+ * one shared pair of
112
+ * constants for all three characters, which holds only because 15° is inside
113
+ * every one of them; the first character that wants more than its neighbours
114
+ * forces the envelope onto `TaraRigOptions` as a per-character fact. A second
115
+ * avatar measures its own with the audit.
116
+ */
117
+ // Exported through `internal.ts` for the instruments that need to put a real
118
+ // angle *into* a channel, which is this scaling run backwards. The mocap
119
+ // instrument kept its own copy for want of that export and said in a comment
120
+ // that the copy would lie the day the envelope moved; it moved on 2026-09-18.
121
+ export const HEAD_CLAMP = 1.4;
122
+ export const HEAD_DEG = { yaw: 15, pitch: 24, roll: 8 };
123
+
124
+ /**
125
+ * Where the head turns about, from `build_tara.PIVOT`, in glTF's Y-up frame:
126
+ * Blender (x, y, z) exports as (x, z, −y). v 0.36 is the jaw angle and the
127
+ * earlobe, and it sits a fifth of a face height *behind* the face plane —
128
+ * a pivot on the surface spins the face in place, where a real yaw swings the
129
+ * chin across as well as around, which is most of what makes a small turn read.
130
+ */
131
+ const PIVOT = new THREE.Vector3(0.0, 0.36, -0.22);
132
+
133
+ /**
134
+ * Where the head *tilts* about, from `morphs.ROLL_PIVOT`: the midline just
135
+ * above the chin. A roll is a bend of the whole neck, so its centre is far
136
+ * below the ear, and a drawn head sells it by holding the chin and swinging
137
+ * the crown — Live2D's sample rigs tilt about this same point. About PIVOT
138
+ * instead, the chin swung 7 px the other way at 8° and the head read as a
139
+ * pendulum hung from the ears.
140
+ *
141
+ * It sits inside the yaw and pitch, so a turned head still tilts about its own
142
+ * chin. TARA-SPECIFIC: see `morphs.ROLL_PIVOT` for what fixed the height and
143
+ * what a second avatar supplies.
144
+ */
145
+ const ROLL_PIVOT = new THREE.Vector3(0.0, 0.05, -0.22);
146
+
147
+ /**
148
+ * What the head takes with it, from `build_tara.HEAD_PARTS`. `Body` stays
149
+ * behind, and so does `Neck` — but the neck is not *static*: it carries
150
+ * `headYaw` / `headPitch` / `headRoll` morph targets of its own, ramped from
151
+ * full under the jaw to nothing at the collar (`morphs.neck_targets`). Pitch and
152
+ * roll are the same rotation this group gets; yaw is a twist about the neck's
153
+ * own axis at half the angle, which keeps the neck's outline where it is
154
+ * (`morphs.neck_twist`). They need no code here at all, which is the
155
+ * whole reason they are morphs: they are named for pose channels that rest at
156
+ * 0, so the loop below drives them like any other channel and the influence law
157
+ * hands them the raw pose value.
158
+ *
159
+ * Without it a turn dragged the skull's jaw rim across a throat that had not
160
+ * moved, and the rim landed mid-neck as a second jawline — invisible at the
161
+ * 400 × 300 tile, obvious at a 3× crop.
162
+ */
163
+ const HEAD_PARTS = ["Head", "Ears", "Hair", "Eye_L", "Eye_R", "Cavity",
164
+ "Teeth_Upper", "Teeth_Lower", "Tongue"];
165
+
166
+ /**
167
+ * The body, in face-space units (glTF y is face-space v) and degrees.
168
+ *
169
+ * Every mechanism is the SVG faces' (`face-core.poseTransforms`); the
170
+ * amplitudes are set from the anatomy, which on this face is ~8.8 px per
171
+ * centimetre at the 400 × 300 tile (crown to chin is 1.39 units of ~24 cm),
172
+ * and land at about peep's travel as a share of the same tile. The first cut
173
+ * was 0.6 of peep, on the theory that a photograph shows a millimetre a line
174
+ * drawing cannot. Measured in a 30-second listening hold it moved the
175
+ * shoulders 2 px, under 1 % of the tile, and read as a still with a tremor:
176
+ * the head was moving more than the body carrying it. Anatomy is the floor,
177
+ * not a fraction of a cartoon — these now put a listening hold at 4-5 px at
178
+ * the shoulders, still slow, and still well under the 1.5 Hz ceiling.
179
+ *
180
+ * breath A swell, not a slide (`docs/research-biomechanics.md` §6.1): the
181
+ * torso scales about a point 0.35 of a frame below the frame, as peep's
182
+ * does about its hem, so the shoulder line comes up 2.4 px at full
183
+ * inhale against a lower edge that moves two-thirds of that, and the
184
+ * chest widens 2 px a side. Quiet breathing changes chest
185
+ * circumference 2-3 %; 1.2 % wide is the calm end of that in linear
186
+ * scale, and the rise is a little more because in this crop — about
187
+ * 5 cm of chest below the collar — what a breath shows is the upper
188
+ * ribs and clavicles lifting as much as the rib cage widening. The
189
+ * neck and head ride the lift at the collar, derived rather than tuned
190
+ * (peep's `neckLift`), so the neck cannot telescope: ~2.4 px, the
191
+ * 2-3 mm a seated head really moves with a breath.
192
+ * lean `torsoLean` as a deformation of the trunk, on the shell itself
193
+ * (`morphs.torso_targets`) — hem pinned at the frame's lower edge, the
194
+ * shoulders spreading and tipping as they come nearer. Only the head's
195
+ * *ride* is here: above the collar the field is flat, so the neck and
196
+ * head take a pure translation of `leanRide` and nothing else. That is
197
+ * Live2D's measured behaviour rather than a simplification — body angle
198
+ * moves every head part by 1.00 ± 0.02 and adds no differential motion
199
+ * inside the head (`docs/research-torso-motion.md` § 8 item 4).
200
+ *
201
+ * It replaced a uniform `figure.scale.setScalar()`, which was peep's
202
+ * `LEAN_SCALE` carried onto photographic geometry and, with the
203
+ * orthographic camera outside the group it scaled, was arithmetically a
204
+ * zoom: fit the displacement as a linear map and its singular values
205
+ * came back equal to three decimals with no residual, at every lean the
206
+ * mixer produces. What it looked like was the owner's report — the
207
+ * shoulders swelling and dropping in half a second. The crown travelled
208
+ * 4.56× what the eyes did, which is a head being scaled, not carried.
209
+ * A headless audit of what the crown travels against the eyes is that
210
+ * measurement, and its gates are what this change had to turn green.
211
+ * sway `torsoTurn` as the seated body's inverted pendulum: the whole figure
212
+ * rolls about the hips, ~45 cm below the collar, so the trunk shifts
213
+ * sideways and tips by a fraction of a degree together. peep slides
214
+ * its torso under a head that stays; a photograph cannot, because a
215
+ * neck joins them, so here the head rides the trunk and is rolled back
216
+ * level by exactly the trunk's tilt — its roll is `headRoll`'s alone,
217
+ * as a person shifting their weight goes on holding their eyes level on
218
+ * the person they are listening to. One degree at full `torsoTurn`: a
219
+ * weight shift (0.16-0.42) moves the collar 1.1-2.9 px, and following
220
+ * a full head turn ~7 px — 1.7 cm at the collar, what a seated body
221
+ * shifting onto one hip really does.
222
+ */
223
+ const BODY = {
224
+ swellPivot: FRAME.bottom - 0.35 * FRAME_HEIGHT,
225
+ rise: 0.016,
226
+ widen: 0.012,
227
+ /** `landmarks.SHOULDER.top`: where the neck meets the torso. */
228
+ collar: -0.24,
229
+ /**
230
+ * The head group's rigid drop at a full lean. `morphs.py` parses this and
231
+ * plateaus `torsoLean`'s field at it above the collar, so the body's
232
+ * deformation and the head's transform are one number and meet without a
233
+ * seam — the same arrangement `lift.position.y` already has with the breath.
234
+ */
235
+ leanRide: 0.021,
236
+ hip: -2.9,
237
+ swayDeg: 1.0,
238
+ };
239
+
240
+ /**
241
+ * Gaze, as iris travel in face heights at `pupilX/Y` = 1, converted to a globe
242
+ * rotation on load. Authored as travel, not as an angle, because travel is what
243
+ * anyone can measure off the render and the angle is an artefact of this
244
+ * build's globe radius (0.24, some 4x anatomical — the sphere is a curved
245
+ * backing for a painted iris, not an eyeball).
246
+ *
247
+ * 0.042 across is ~7 mm on a face 165 mm tall, the iris travel of a ~35°
248
+ * version, and 6.4 px at the 400 px tile; the first value (0.026, ~4 px) was
249
+ * under the threshold where a look to the screen edge reads as a look rather
250
+ * than a drift. Vertical is shorter because a person looking up or down
251
+ * carries most of it with the lids and the head.
252
+ */
253
+ const GAZE_TRAVEL = { x: 0.042, y: 0.026 };
254
+ /** `head_mesh.GLOBE_R`. The arc a rotation moves the iris through is r·θ. */
255
+ const GLOBE_RADIUS = 0.24;
256
+ /** `face_texture.EYE_EXTENT`'s span: one eye tile covers 0.30 face heights. */
257
+ const EYE_TILE = 0.3;
258
+
259
+ /** Degrees per pose unit: the globe turns `pupil * GAZE_TRAVEL / GLOBE_RADIUS`
260
+ * radians, and the head reaches `HEAD_DEG` at the clamp.
261
+ *
262
+ * Exported through `internal.ts` for the same reason as the head envelope: an
263
+ * instrument that asks for "eyes on the camera through a head turn" is running
264
+ * this conversion backwards, and a second copy of it would be a second thing to
265
+ * update when the eye tile or the globe changes. */
266
+ export const EYE_DEG = { x: (GAZE_TRAVEL.x / GLOBE_RADIUS) * 180 / Math.PI, y: (GAZE_TRAVEL.y / GLOBE_RADIUS) * 180 / Math.PI };
267
+ const HEAD_UNIT_DEG = { x: HEAD_DEG.yaw / HEAD_CLAMP, y: HEAD_DEG.pitch / HEAD_CLAMP };
268
+
269
+ /**
270
+ * The mixer's per-rig calibration for tara, passed by `tara.ts` and the motion
271
+ * audit so both measure the same face. A pose unit is an angle here and a
272
+ * pixel count on an SVG face, so the speech layer's amplitudes are tuned per
273
+ * rig rather than in the library: `prosodyHeadGain` sizes speech-rhythm head
274
+ * motion against this face's own motion envelope.
275
+ *
276
+ * `oculomotor` is the eye-head system sized for this face (`gaze.js`). Her eye
277
+ * turns 10° a pupil unit and her head 6.4° of yaw a head unit, and the shared
278
+ * look table — drawn for a line face, whose pupils cross most of an eye — put
279
+ * every look in the eyes: a thinking look away was the iris parked in the
280
+ * corner of the socket for two thirds of the state, which is side-eye, not
281
+ * thought. Here the head carries about 60 % of a look and the eyes land a third
282
+ * of the way off centre, where a real eye-head shift leaves them (Freedman &
283
+ * Sparks; Pejsa & Andrist). The comment on each target is its world angle,
284
+ * x right and y down.
285
+ *
286
+ * vor Real gain in the light is close to 1. A little under leaves the
287
+ * head some say, so a nod carries the eyes a touch with it rather
288
+ * than pinning them to the lens. Vertically it is well under
289
+ * (2026-09-15): her pitch is a shell tipping on a photograph and
290
+ * reads as a fraction of what it is, so the eyes' full answer to
291
+ * it read as the eyes moving on their own — at 0.8, THINKING's
292
+ * up-look rolled the iris to the lid with white beneath it, and
293
+ * the reply that followed dropped it into a downcast look with the
294
+ * lid riding down, while the head was still coming back. At 0.35
295
+ * the eyes mostly go where the head takes them.
296
+ * range How far the reflex may carry the eye in the socket. Unlimited,
297
+ * an up-look's onset put the whole 8° in the eye before the neck
298
+ * moved — the iris pinned under the lid, white beneath it, which
299
+ * on this photograph reads as an eye-roll. Up 0.45 is 2.8° and
300
+ * down 0.5 is 3.1°; the head covers the rest, as it does once the
301
+ * eye nears its effective range. Both were looser (0.55, 0.85)
302
+ * and a gap between turns hit both ends of them every time.
303
+ * lidFollow Down 0.38 keeps the upper lid on the iris: the lid travels
304
+ * 0.068 face units per lid unit and the iris 0.026 per pupil unit.
305
+ * Up a little less, so an upward look opens the eye a hair instead
306
+ * of dragging the lid along with it.
307
+ * avert A conversational look away keeps under half its size in the
308
+ * eyes and gives the neck 0.6 of it — on this face the eyes alone
309
+ * could only make it a glance sideways.
310
+ * head The follow's launch and cruise, in head units. A real head
311
+ * reaches a 7-8° shift in about 0.4 s, its speed scaling with the
312
+ * size of the shift; the shared amble took a thinking look 1.2 s,
313
+ * and the reflex, doing its job, held the eyes in the corner of
314
+ * the socket the whole way.
315
+ *
316
+ * `trunkFollow` is 0.3, under the line faces' 0.45. Live2D's face-tracking
317
+ * sample gives the body a third of the head's yaw (BodyAngleX 10 against
318
+ * AngleX 30; docs/research-head-rotation.md § 5 item 6), and that is the
319
+ * benchmark to sit at, not above. Here it matters for a reason a line face
320
+ * does not have: the neck's outline holds under a twist by construction
321
+ * (`morphs.neck_twist`), so the trunk's sway is what is left moving it — a
322
+ * quarter to a third of it at the yaw peak in the recorded call, read as the
323
+ * neck sliding. TARA-SPECIFIC in its evidence only: a second Blender avatar
324
+ * starts from 0.3 and checks its own outline at crop.
325
+ */
326
+ export const TARA_TUNING = {
327
+ prosodyHeadGain: 1.0, prosodyFaceGain: 1, saccadeGain: 2.4, aversionGain: 1.8,
328
+ trunkFollow: 0.3,
329
+ // **The speaking face's upper half, sized for a photograph.** A reviewer read
330
+ // her speech as delivered "with zero emotion or movement in her eyes or
331
+ // forehead", against the same reviewer's praise for `CANT_HEAR`. The two are
332
+ // the same channels at different values, and the gap is measurable in the
333
+ // expression maps: `CANT_HEAR` above is knit 0.14/0.45 plus inner 0.22/0.5,
334
+ // about 0.75 of map weight, where speech averaged 0.19.
335
+ //
336
+ // `floor` is the larger half of the answer. `browRaise` is split by sign into
337
+ // two maps and *both* read as nothing near zero, so the shared [-0.14, 0.18]
338
+ // range spends most phrases in a dead band recruiting no light at all. The
339
+ // band is skipped rather than the range widened, because what carries the
340
+ // read is the sign a phrase commits to, not how far it goes — and the ceiling
341
+ // stays under a beat's 0.34 for the reason `POSE.brow` gives.
342
+ //
343
+ // `forms` moves draws off the plain raise and onto the inner lift, which on
344
+ // this asset is the only brow shape besides the raise that recruits light at
345
+ // all (`EXPRESSION_WEIGHT`: there is no map for `browAngle`, and its 0.026 of
346
+ // travel is the smallest of the three). `prosody.js` makes the inner lift the
347
+ // rarest form deliberately, because a face that keeps lifting its inner brows
348
+ // reads as worried — that rule is written for the line faces, and the face it
349
+ // is being relaxed for holds `browInner` at 0.22 for the whole of `CANT_HEAR`
350
+ // and was praised for it. Still a transient on a 0.55 s envelope, never a
351
+ // held shape: the prohibition is on the hold, not the event.
352
+ //
353
+ // TARA-SPECIFIC, and fork debt: on a driver of her own these are three
354
+ // constants beside the research comment, not an option on a shared mixer.
355
+ brows: {
356
+ range: [-0.28, 0.24],
357
+ floor: 0.11,
358
+ forms: [
359
+ { p: 0.38, inner: 0.00, angle: 0.00 },
360
+ { p: 0.34, inner: 0.26, angle: 0.00 },
361
+ { p: 0.28, inner: 0.00, angle: 0.30 },
362
+ ],
363
+ },
364
+ states: {
365
+ // The shared WORKING pose without its AU4 brows. On peep, brows-down is
366
+ // what makes reading read as effort rather than a blank face; on a
367
+ // photograph, over lids that are already following the eyes down, it
368
+ // closes them to a squint the owner read as straining at the screen, not
369
+ // working. Her reading scan carries the state instead: eyes off the user,
370
+ // stepping along a line, the way a person at their own display looks.
371
+ // TARA-SPECIFIC: a photographic face with a deeper lid crease may want
372
+ // some of the knit back; judge it at crop against LISTENING.
373
+ WORKING: {
374
+ pose: { headPitch: 0.04, lidL: -0.08, lidR: -0.08, shoulderL: 0.06, shoulderR: 0.06 },
375
+ },
376
+ // Straining to hear, without the squint. Its AU7 lifts her lower lid and
377
+ // pushes the cheek up under it: at 0.75 the eyes closed to slits over a
378
+ // dark band, and under brows at -0.45, with the eyes countered into the
379
+ // corner of the socket (`USER_EAR` below), she read as giving the user a
380
+ // suspicious side-eye. The lean in and the ear offered carry the state,
381
+ // which the shared comment already says of them. The brows keep a small
382
+ // knit with the inner ends up: effort that is also asking. The mouth is
383
+ // pressed at a photograph's scale; the shared -0.22 corners clear peep's
384
+ // drawn smile, and hers rests neutral. TARA-SPECIFIC: the squint morph's
385
+ // cheek push is what darkens, so a face built without one might keep a
386
+ // little squint — check the band under the eye at crop.
387
+ //
388
+ // The lean is attentive-sized, not the shared 0.70. Until 2026-09-16 her
389
+ // lean scaled the whole figure about mid-face (`BODY`), so 0.70 plus the
390
+ // engage add was a 4.4% zoom arriving on torsoLean's 0.24 s tau: the
391
+ // shoulders swelled and dropped in half a second, read by the owner as a
392
+ // lurch nothing like a lean. 0.22 sits in the research's sustained band
393
+ // (+0.15–0.25, research-biomechanics.md §6.3) and the ear and chin carry
394
+ // the rest.
395
+ //
396
+ // The lean deforms the trunk now, which is exactly the condition the old
397
+ // note here predicted might afford more. It is left at 0.22 on purpose: the
398
+ // cut was made by eye at crop, and putting it back is the same kind of
399
+ // judgement rather than a consequence of the field changing. TARA-SPECIFIC,
400
+ // and the thing to re-judge first if she reads as under-committed.
401
+ CANT_HEAR: {
402
+ pose: {
403
+ torsoLean: 0.22, headPitch: 0.10,
404
+ browRaiseL: -0.14, browRaiseR: -0.14, browInnerL: 0.22, browInnerR: 0.18,
405
+ mouthPress: 0.40, mouthCornerL: -0.10, mouthCornerR: -0.10,
406
+ },
407
+ },
408
+ // Hunting for a control, without the squint: the same lower lid and cheek
409
+ // at 0.40 left the eyes half-lidded from below over a dark band. The hunt
410
+ // is the wander and the flick; the face only has to be not smiling, and
411
+ // on a mouth that rests neutral that is a small press, not peep's -0.25
412
+ // corners. TARA-SPECIFIC, the same way as CANT_HEAR.
413
+ SEARCHING_SCREEN: {
414
+ pose: { mouthPress: 0.40, mouthCornerL: -0.08, mouthCornerR: -0.08,
415
+ browRaiseL: -0.10, browRaiseR: -0.06 },
416
+ },
417
+ },
418
+ oculomotor: {
419
+ angles: { eye: EYE_DEG, head: HEAD_UNIT_DEG },
420
+ vor: { x: 0.8, y: 0.35 },
421
+ range: { x: 0.8, up: 0.45, down: 0.5 },
422
+ lidFollow: { down: 0.38, up: 0.30 },
423
+ avert: { eye: 0.45, head: 0.6 },
424
+ head: { accel: 16, speed: 3.5 },
425
+ targets: {
426
+ // 2.0° right, 2.5° down: her own display, read level and a little to
427
+ // the side (WORKING, and OFFLINE's wait). The upper lid follows the eye
428
+ // down (`lidFollow`), and a photographed eye 6.8° down — where this
429
+ // sat — hooded to a lid of 0.25-0.43 against listening's 0.14, read as
430
+ // a squint rather than reading. Here it holds 0.12-0.18 through the
431
+ // scan, and being off the user to the side is what says "busy".
432
+ // TARA-SPECIFIC: the depth that hoods is her lid crease's.
433
+ OWN_SCREEN: { px: 0.14, py: 0.24, hx: 0.10, hy: 0.06 },
434
+ // 2.6° of head turn toward the user's side and 3.1° of roll, the eyes
435
+ // countered 2.0° back onto them: the ear offered, contact held from
436
+ // inside the socket. The shared 0.42 counter held her iris against the
437
+ // corner of the socket with white on one side, which on a photograph is
438
+ // side-eye; the roll is the cue that says "ear", so it keeps its size.
439
+ USER_EAR: { px: -0.20, py: 0.05, hx: 0.40, hy: 0.02, roll: 0.55 },
440
+ // 2.8° up, nearly all of it the head — the same total the shared target
441
+ // gives on her, redistributed. The shared split puts 1.0° on the eyes,
442
+ // and the middle of a screen is the one place a hunt keeps returning to,
443
+ // so it is the worst place to sit with the iris off-centre.
444
+ SCREEN_CENTER: { px: 0.00, py: -0.06, hx: 0.00, hy: -0.14 },
445
+ // 9.3° to the side, 1.5° up, the head carrying over half. The shared
446
+ // ones put the eyes at the edge of her socket (0.78 of 0.8) — white on
447
+ // one side again, and a hunt that reads as shifty. SEARCHING_SCREEN,
448
+ // REVIEWING_SCREEN and DISTRACTED look here.
449
+ SCREEN_LEFT: { px: -0.42, py: -0.10, hx: -0.80, hy: -0.05 },
450
+ SCREEN_RIGHT: { px: 0.42, py: -0.10, hx: 0.80, hy: -0.05 },
451
+ // 6.4° up, three quarters of it the head. The shared target is 9.6° on
452
+ // her — higher than her own AWAY_THINKING, so it read as looking over
453
+ // the monitor rather than at the top of it, and it made the two longest
454
+ // hops in SEARCHING_SCREEN's set (14.6° from SCREEN_WORK, 12.4° from
455
+ // either side) on a face whose looks are all scaled to a head-and-
456
+ // shoulders crop.
457
+ SCREEN_TOP: { px: 0.00, py: -0.26, hx: 0.00, hy: -0.28 },
458
+ // 7.0° left, 3.2° down, for the same reason, split evenly.
459
+ SCREEN_WORK: { px: -0.35, py: 0.18, hx: -0.55, hy: 0.12 },
460
+ // 7.8° left, 8.1° up.
461
+ AWAY_THINKING: { px: -0.30, py: -0.40, hx: -0.75, hy: -0.33, roll: 0.08 },
462
+ // 7.6° right, 7.4° up.
463
+ AWAY_RIGHT: { px: 0.30, py: -0.36, hx: 0.72, hy: -0.30, roll: -0.06 },
464
+ // 6.8° left, 5.5° down: shallower than the up-looks, since down on a
465
+ // face this real is the one read as downcast.
466
+ AWAY_DOWN: { px: -0.28, py: 0.45, hx: -0.62, hy: 0.16, roll: 0.04 },
467
+ // 7.8° right, level.
468
+ AWAY_SIDE: { px: 0.32, py: 0.08, hx: 0.72, hy: 0.02, roll: -0.03 },
469
+ },
470
+ },
471
+ } as const;
472
+
473
+ /**
474
+ * The eye material, taught to hold its socket still while the globe turns.
475
+ *
476
+ * The eye atlas is two tiles (`face_texture.write_eye_atlas`): the globe, and
477
+ * a linear multiplier holding what the lids and the socket put on the eye —
478
+ * the shadow under the upper lid, the caruncle, the shading into each corner.
479
+ * A real eye turns under all of that, and when it was baked into the globe a
480
+ * sideways look swung the caruncle into the middle of the white. So the
481
+ * globe's texel is read where the surface point *was* and the socket's where
482
+ * it *is*: the planar UV of the rotated position, which is the unrotated UV
483
+ * plus the rotation's displacement through the UV's own gradient. One extra
484
+ * texture read on two small meshes; no pass, no draw call.
485
+ */
486
+ function socketed(base: THREE.MeshStandardMaterial, side: number,
487
+ gaze: { value: THREE.Matrix3 }, deep: boolean) {
488
+ const material = base.clone();
489
+ // d(u)/dx and d(v)/dy of `head_mesh.eye_uvs`: the globe is half the atlas
490
+ // wide, the right eye reads it mirrored, and glTF flips v.
491
+ const socket = { value: new THREE.Vector2((0.5 * -side) / EYE_TILE, -1 / EYE_TILE) };
492
+ material.onBeforeCompile = (shader) => {
493
+ shader.uniforms.uGaze = gaze;
494
+ shader.uniforms.uSocket = socket;
495
+ // The globe's hidden skirt turns at the frame's motion depth like the skin
496
+ // that hides it; its visible cap carries a field of exactly zero, so the
497
+ // socket, the iris and gaze below are unaffected by this. It turns at the
498
+ // *frame's* rotation and not its own, which is what `undoGaze` reads back
499
+ // out of `uGaze` — hence this sitting after that uniform is bound.
500
+ if (deep) turnDeep(shader, true);
501
+ shader.vertexShader = shader.vertexShader
502
+ .replace("#include <uv_pars_vertex>",
503
+ "#include <uv_pars_vertex>\nuniform mat3 uGaze;\nuniform vec2 uSocket;\nvarying vec2 vSocketUv;")
504
+ .replace("#include <uv_vertex>",
505
+ "#include <uv_vertex>\nvSocketUv = vMapUv + vec2(0.5, 0.0)"
506
+ + " + uSocket * ((uGaze * position).xy - position.xy);");
507
+ shader.fragmentShader = shader.fragmentShader
508
+ .replace("#include <uv_pars_fragment>", "#include <uv_pars_fragment>\nvarying vec2 vSocketUv;")
509
+ .replace("#include <map_fragment>",
510
+ "vec3 socket = 2.0 * texture2D( map, vSocketUv ).rgb;\n#include <map_fragment>\ndiffuseColor.rgb *= socket;")
511
+ .replace("#include <emissivemap_fragment>",
512
+ "#include <emissivemap_fragment>\ntotalEmissiveRadiance *= socket;");
513
+ };
514
+ material.customProgramCacheKey = () => (deep ? "tara-eye-socket-deep" : "tara-eye-socket");
515
+ return material;
516
+ }
517
+
518
+ /** `cavityShade`'s two measured heights, in the cavity patch's own normalised
519
+ * rest height — 0 at the bottom of its bounding box, 1 at the top, morph deltas
520
+ * included, because `computeBoundingBox` counts them and the shader normalises
521
+ * by that same call.
522
+ *
523
+ * Both were read off a ruler build that painted the normalised height into the
524
+ * emissive term, where the output bypasses the lamps and decodes straight back
525
+ * to the height that produced it. It found two things worth keeping.
526
+ *
527
+ * `seam` is the height a *closed* mouth shows: pixel-weighted 0.805 on tara and
528
+ * 0.808 on tushar, near enough identical to be one constant rather than a
529
+ * per-character tuning. It is deliberately the pivot — see `cavityShade`.
530
+ *
531
+ * `falloff` is sized against the band an *open* mouth exposes, and that band is
532
+ * why this is measured rather than guessed: it is 0.70..0.89, the top fifth of
533
+ * the patch, with nothing below it even at jaw 1 and mouthOpen 1 — the patch
534
+ * runs far past the aperture on purpose, so that its lower edge can chase the
535
+ * lip without ever reaching the chin (`build_tara`, the cavity's lower edge). A
536
+ * ramp laid across the whole patch would put a fifth of its range in the only
537
+ * part anyone sees, which is the mistake the lower arch's `floor` made one
538
+ * commit ago by being sized against its tile instead of its visible band.
539
+ *
540
+ * At 8 the multiplier runs 0.51 at the top of that band to 2.32 at the bottom.
541
+ * Neither clamp engages anywhere the aperture reaches; they are there so that a
542
+ * future morph exposing more of the patch cannot blow the exponential up.
543
+ */
544
+ const CAVITY_SHADE = { seam: 0.805, falloff: 8, min: 0.35, max: 2.6 };
545
+
546
+ /**
547
+ * The inside of the mouth, shaded by how far the light has to reach into it.
548
+ *
549
+ * Both video reviewers called the open mouth "a dark void", and a luminance
550
+ * profile says why in one number: through viseme D's aperture the cavity
551
+ * renders ten consecutive rows inside a single level of 255 — 49.6 down to 48.7
552
+ * on tara, 49.3 to 48.6 on tushar — between an upper arch at 232 and a lower
553
+ * one at 163. Every other band in that column moves tens of levels per row. The
554
+ * complaint is not that the interior is too dark, then. It is that it is the
555
+ * one surface on this face with no variation in it at all, and a
556
+ * constant-valued region reads as a hole cut in the head rather than as a space
557
+ * behind it.
558
+ *
559
+ * It is flat because it is the only mouth surface that is genuinely *lit*.
560
+ * `build_tara.flat_material` gives it no emissive term, where the teeth beside
561
+ * it carry `emissiveFactor` 0.75 and their photograph's own light with it — so
562
+ * all of the cavity comes from the lamps, and those are 0.62π of ambient
563
+ * against a patch whose normal barely turns. Ambient on a constant normal is a
564
+ * constant.
565
+ *
566
+ * This is authored rather than sampled, which is the wrong way round for this
567
+ * repo and worth saying why: the reference is a *smile*, and a smile shows no
568
+ * interior — the same fact that left the lower arch with no enamel to copy.
569
+ * There is no photograph of this mouth's inside to project, so the choice is an
570
+ * authored gradient or the flat colour, and it is kept modest for it.
571
+ *
572
+ * Authored rather than derived, too. The true form factor from a flat backdrop
573
+ * to the aperture in front of it is *brightest at the centre*, which is exactly
574
+ * backwards: a real mouth is darkest in the middle because it is a tunnel
575
+ * there, and this one is a curtain — `build_tara` parks it in front of the
576
+ * teeth so a closed mouth has something dark to show, and walks it back past
577
+ * them as the jaw drops. So this shades the mouth it stands for, not the
578
+ * geometry it is drawn on.
579
+ *
580
+ * The pivot is what makes that safe. `CAVITY_SHADE.seam` is the height the
581
+ * closed mouth shows, so the multiplier is 1.0 there by construction and the
582
+ * rest pose barely moves: measured over the whole mouth region, at most 4
583
+ * levels of 255 on tara and 3 on tushar. Not nothing, and not worth claiming as
584
+ * nothing — but it matters that it is small, because "a closed mouth is a dark
585
+ * line" is this surface's first job, and `landmarks.PALETTE.cavity` is the
586
+ * colour of that line and stays the authority on it.
587
+ *
588
+ * Opening the mouth reveals the rest: darker above the seam, lighter below it.
589
+ * Where those two halves actually land is not symmetric and not the same on the
590
+ * two characters, because what hides the cavity is the upper arch, and the
591
+ * arches differ. Down the middle of tara's mouth the arch reaches to roughly
592
+ * the seam, so the centre gets the lighter half nearly alone — the ten flat
593
+ * rows above become 50 at the top of the aperture rising to 83 at its bottom,
594
+ * which is the floor the aperture faces. The darker half surfaces instead in
595
+ * two lobes flanking the arch, where the aperture runs wider than the teeth do
596
+ * and so exposes cavity above the seam: −4 levels on tara, −5 on tushar. Those
597
+ * lobes are the commissures, and their being the deepest part of the mouth is
598
+ * right for a reason this shader did not plan — it falls out of a vertical ramp
599
+ * meeting a curved arch.
600
+ *
601
+ * tushar gets the darker half down the centre as well, 49.3 to 43.6, because
602
+ * his teeth are narrower — `TEETH.half_width` 0.110 against tara's 0.132 — so
603
+ * his aperture exposes cavity above the seam in the middle too. One constant,
604
+ * two characters, two different-looking mouths, and the difference between them
605
+ * is the arch's width showing through. That is the argument for the constant
606
+ * staying shared rather than being tuned per character: it is already reading a
607
+ * per-character fact, just not one of its own.
608
+ */
609
+ function cavityShade(base: THREE.MeshStandardMaterial, lo: number, hi: number) {
610
+ const material = base.clone();
611
+ const span = { value: new THREE.Vector2(lo, (hi - lo) || 1) };
612
+ const shade = {
613
+ value: new THREE.Vector4(CAVITY_SHADE.seam, CAVITY_SHADE.falloff,
614
+ CAVITY_SHADE.min, CAVITY_SHADE.max),
615
+ };
616
+ material.onBeforeCompile = (shader) => {
617
+ shader.uniforms.uCavitySpan = span;
618
+ shader.uniforms.uCavityShade = shade;
619
+ shader.vertexShader = shader.vertexShader
620
+ .replace("#include <common>",
621
+ "#include <common>\nvarying float vCavityAt;\nuniform vec2 uCavitySpan;")
622
+ // `position`, not `transformed`: `morphs.cavity_targets` translates this
623
+ // patch back and drops its lower edge as the jaw opens, and this shading
624
+ // is painted *on* the surface — so it has to ride that, not be swept
625
+ // across it. The raw attribute is the rest frame, before the morphs.
626
+ .replace("#include <begin_vertex>",
627
+ "#include <begin_vertex>\nvCavityAt = (position.y - uCavitySpan.x) / uCavitySpan.y;");
628
+ shader.fragmentShader = shader.fragmentShader
629
+ .replace("#include <common>",
630
+ "#include <common>\nvarying float vCavityAt;\nuniform vec4 uCavityShade;")
631
+ // No `emissivemap_fragment` half, unlike `jawShadow` and `socketed`:
632
+ // those modulate surfaces that emit 75% of a photograph verbatim, and
633
+ // this one has no emissive term at all. The diffuse is the whole output.
634
+ .replace("#include <map_fragment>",
635
+ "#include <map_fragment>\n"
636
+ + "float cavityK = exp(uCavityShade.y * (uCavityShade.x - vCavityAt));\n"
637
+ + "diffuseColor.rgb *= clamp(cavityK, uCavityShade.z, uCavityShade.w);");
638
+ };
639
+ material.customProgramCacheKey = () => "tara-cavity-shade";
640
+ return material;
641
+ }
642
+
643
+ /** `scripts/head_mesh.MOTION_DEPTH_ATTR`, as GLTFLoader names it: lowercased. */
644
+ const MOTION_DEPTH = "_motion_depth";
645
+
646
+ /**
647
+ * The head's frame, taught to turn as if it sat deeper than it does.
648
+ *
649
+ * Rotated at their real depth, the ears, crown, side hair and outline move
650
+ * nearly as far as the nose, and a nod reads as the whole head dropping
651
+ * (docs/research-head-rotation.md § 1). A real head's frame sits near the axis
652
+ * and barely moves, and that differential is what reads as rotation. Each
653
+ * vertex of the skin, hair and ears carries a Δz toward the viewer
654
+ * (`head_mesh.motion_depth`, ≤ 0 and zero across the features), and this moves
655
+ * it on screen by the rotated Δz: the view-space xy of modelView · (0, 0, Δz).
656
+ * Depth, draw order and lighting keep the real position. At rest that xy is
657
+ * exactly zero through the orthographic camera, so the drawing is untouched.
658
+ *
659
+ * The attribute decides, not the mesh name: the neck shares the skin material
660
+ * and has no field, which is why each head shell gets a clone. The same clone
661
+ * wears the expression maps, when the asset has them: the three shells are
662
+ * exactly the ones textured from the face atlas the maps are registered to.
663
+ */
664
+ /**
665
+ * The vertex half of `motionDepth`, which the eye's socket shader needs too.
666
+ *
667
+ * It is a free function rather than inheritance because `Material.copy` does not
668
+ * carry `onBeforeCompile`: cloning a motion-depth material and giving the clone
669
+ * a second injection drops the first one silently, with no error and a rest pose
670
+ * that looks right. The two are composed by hand instead.
671
+ */
672
+ function turnDeep(shader: { vertexShader: string }, undoGaze = false) {
673
+ // `undoGaze` is for the globes, and without it the cure draws a worse defect
674
+ // than the one it removes. A globe is *rotated* for gaze, so its own
675
+ // `modelViewMatrix` carries that rotation: building the offset from it tilts
676
+ // (0, 0, Δz) into the screen plane and slides the hidden skirt out past the
677
+ // temple on a look alone, head square on, where the skin it hides behind has
678
+ // not moved at all. The frame's rotation is the one the skirt must follow, and
679
+ // `uGaze` is exactly the extra rotation to take back out. A rotation's inverse
680
+ // is its transpose, and a vector multiplied from the left is the transpose
681
+ // multiply, so this needs no second uniform and no `transpose()`.
682
+ const depth = `vec3(0.0, 0.0, ${MOTION_DEPTH})`;
683
+ shader.vertexShader = shader.vertexShader
684
+ .replace("#include <common>", `#include <common>\nattribute float ${MOTION_DEPTH};`)
685
+ .replace("#include <project_vertex>",
686
+ "#include <project_vertex>\n"
687
+ + `mvPosition.xy += (modelViewMatrix * vec4(${undoGaze ? `${depth} * uGaze` : depth}, 0.0)).xy;\n`
688
+ + "gl_Position = projectionMatrix * mvPosition;");
689
+ }
690
+
691
+ function motionDepth(base: THREE.MeshStandardMaterial, expression?: Expression) {
692
+ const material = base.clone();
693
+ material.onBeforeCompile = (shader) => {
694
+ turnDeep(shader);
695
+ if (!expression) return;
696
+ const n = expression.names.length;
697
+ Object.assign(shader.uniforms, expression.uniforms);
698
+ shader.fragmentShader = shader.fragmentShader
699
+ .replace("#include <common>", `#include <common>\n${EXPRESSION_UNIFORMS(n)}`)
700
+ .replace("#include <map_fragment>", `#include <map_fragment>\n${EXPRESSION_FRAGMENT(n)}`)
701
+ .replace("#include <emissivemap_fragment>",
702
+ "#include <emissivemap_fragment>\ntotalEmissiveRadiance *= expression;");
703
+ };
704
+ material.customProgramCacheKey = () =>
705
+ (expression ? `tara-motion-depth-expression-${expression.names.length}` : "tara-motion-depth");
706
+ return material;
707
+ }
708
+
709
+ /**
710
+ * Expression maps: the light a smile or a raised brow changes, which the
711
+ * geometry cannot.
712
+ *
713
+ * A pixel of this face is 75% photograph, emitted, and 25% lit (the lamps,
714
+ * below), so the most a morph can change by moving skin is a quarter of its
715
+ * shading — and the shading it moves is the neutral photograph's, which has no
716
+ * nasolabial fold to deepen and no forehead line to show. A cheek morph
717
+ * measured 0.00% of the tile changed. So an asset can carry, per expression, a
718
+ * grey ratio taken from a photograph of the same face making it
719
+ * (`scripts/expression_maps.py`): the fold's shadow, the cheek's lift into the
720
+ * light, the lines of a raised brow, the two creases of a knit one. Here each
721
+ * is raised to the power of its weight and multiplies the albedo's diffuse and
722
+ * emitted halves alike, as the jaw's shadow does — so at weight 0 it is exactly
723
+ * 1 and the face is the photograph, and at 1 it is the expression's light.
724
+ *
725
+ * Read at the texel's *rest* position, which is where the build registered it:
726
+ * the morph that lifts the cheek carries the lifted cheek's light up with its
727
+ * texture, so light and shape arrive together without the shader knowing
728
+ * where anything went.
729
+ *
730
+ * Per side, because the channels are. The weights cross over at the midline
731
+ * rather than switching there, so a one-sided smile does not cut its fold's
732
+ * light off in a line down the philtrum.
733
+ *
734
+ * The maps are the one thing in the asset nothing draws: they ride on a
735
+ * carrier mesh (`build_tara.py`, "Expression") that exists to get the texture
736
+ * into the GLB, and is taken out of the scene on load. An asset without one is
737
+ * a face whose light never changes, which is every asset built before these.
738
+ */
739
+ const EXPRESSION_SPLIT = 0.03;
740
+ /**
741
+ * Each map's weight, from one side's channels, as a fraction of the channel
742
+ * value at which it is at its photograph's full strength. The smile's is the
743
+ * mixer's broad smile (0.48-0.58 in the happy states) with room above it; a
744
+ * raise at the mixer's highest (0.42) gets most of the lines; a knit at
745
+ * `CANT_HEAR`'s −0.14 gets a third of the crease and the deepest frown the
746
+ * mixer asks for (−0.45) gets all of it; the inner brow's concern is full at
747
+ * its 0.55 and a press at the 0.40-0.55 most states hold gets most of the chin.
748
+ *
749
+ * A map named here that the asset lacks is simply not read, and a map the
750
+ * asset has that is not named here stays at weight 0: an asset newer than its
751
+ * rig loses the light the rig cannot place, not the face.
752
+ * TARA-SPECIFIC: judged on tushar's maps at the 400 × 300 tile, the only ones
753
+ * that exist.
754
+ */
755
+ const EXPRESSION_WEIGHT: Record<string, (at: (channel: string) => number) => number> = {
756
+ smile: (at) => at("mouthCorner") / 0.8,
757
+ raise: (at) => at("browRaise") / 0.6,
758
+ knit: (at) => -at("browRaise") / 0.45,
759
+ inner: (at) => at("browInner") / 0.5,
760
+ press: (at) => at("mouthPress") / 0.7,
761
+ };
762
+ const EXPRESSION_UNIFORMS = (n: number) => [
763
+ "uniform sampler2D uExpression;", "uniform vec4 uExpressionTile;", "uniform vec2 uExpressionU;",
764
+ "uniform vec4 uExpressionStrip;", "uniform float uExpressionStep;",
765
+ "uniform float uExpressionScale;",
766
+ `uniform float uExpressionL[${n}];`, `uniform float uExpressionR[${n}];`,
767
+ ].join("\n");
768
+ // Every tap is read whatever its weight: a texture read under a branch that
769
+ // differs across the midline has no derivatives to choose its mip from.
770
+ const EXPRESSION_FRAGMENT = (n: number) => [
771
+ "vec2 expressionAt = clamp(uExpressionTile.xz + uExpressionTile.yw * vMapUv, 0.0, 1.0);",
772
+ "vec2 expressionUv = uExpressionStrip.zw + expressionAt * uExpressionStrip.xy;",
773
+ "float expressionSide = smoothstep(",
774
+ ` -${EXPRESSION_SPLIT}, ${EXPRESSION_SPLIT}, uExpressionU.x + uExpressionU.y * vMapUv.x);`,
775
+ "float expressionLog = 0.0;",
776
+ `for (int i = 0; i < ${n}; i++) {`,
777
+ " float ratio = texture2D(uExpression, expressionUv + vec2(float(i) * uExpressionStep, 0.0)).r;",
778
+ " expressionLog += mix(uExpressionL[i], uExpressionR[i], expressionSide)",
779
+ " * log(max(ratio * uExpressionScale, 0.01));",
780
+ "}",
781
+ "float expression = exp(expressionLog);",
782
+ "diffuseColor.rgb *= expression;",
783
+ ].join("\n");
784
+
785
+ interface Expression {
786
+ readonly map: THREE.Texture;
787
+ readonly names: readonly string[];
788
+ readonly left: Float32Array;
789
+ readonly right: Float32Array;
790
+ readonly uniforms: Record<string, THREE.IUniform>;
791
+ }
792
+
793
+ /** The maps from their carrier's node, or `null` for an asset whose carrier
794
+ * does not say what this rig reads — a face with no expression maps is a
795
+ * correct face, and a map read with the wrong layout is not. */
796
+ function expressive(carrier: THREE.Mesh): Expression | null {
797
+ const { expression_tile: tile, expression_u: u, expression_maps: names,
798
+ expression_layout: layout, expression_unity: unity } = carrier.userData;
799
+ const map = (carrier.material as THREE.MeshStandardMaterial).map;
800
+ if (!map || !Array.isArray(tile) || !Array.isArray(u) || !Array.isArray(layout)
801
+ || typeof unity !== "number" || !Array.isArray(names) || !names.length) return null;
802
+ // A ratio, not a colour. The loader tags every base colour sRGB.
803
+ map.colorSpace = THREE.NoColorSpace;
804
+ map.needsUpdate = true;
805
+ const [width, height, pad, stripWidth, stripHeight] = layout as number[];
806
+ const left = new Float32Array(names.length);
807
+ const right = new Float32Array(names.length);
808
+ return {
809
+ map, names: names.map(String), left, right,
810
+ uniforms: {
811
+ uExpression: { value: map },
812
+ uExpressionTile: { value: new THREE.Vector4(tile[0], tile[1], tile[2], tile[3]) },
813
+ uExpressionU: { value: new THREE.Vector2(u[0], u[1]) },
814
+ uExpressionStrip: { value: new THREE.Vector4(width / stripWidth, height / stripHeight,
815
+ pad / stripWidth, pad / stripHeight) },
816
+ uExpressionStep: { value: (width + pad) / stripWidth },
817
+ uExpressionScale: { value: 255 / unity },
818
+ uExpressionL: { value: left },
819
+ uExpressionR: { value: right },
820
+ },
821
+ };
822
+ }
823
+
824
+ /**
825
+ * The neck, taught to wear the jaw's shadow where the jaw is.
826
+ *
827
+ * The photograph paints the shadow the chin casts on the throat, and a painted
828
+ * shadow stays where it was painted: under a 9° turn the jaw crossed the top of
829
+ * the neck by 8 px and its shadow did not move, which read as the neck sliding
830
+ * out from under the head. So the
831
+ * build lifts it out of the albedo into a ratio tile
832
+ * (`project_albedo.lift_jaw_shadow`), and this puts it back from the head's
833
+ * frame: each neck fragment finds the point of the *turned* head in front of it
834
+ * — the view ray met with the plane the jaw's rim turns in — and reads the
835
+ * ratio at that point's rest position. At rest that point is the fragment's
836
+ * own, so the drawing is the photograph; under a turn the shadow's edge rides
837
+ * the rim, whatever the neck's own follow is doing.
838
+ *
839
+ * The tile lives in the albedo atlas (`face_texture.JAW_SHADOW_AT`), the way
840
+ * the eye's socket multiplier lives beside its globe, so it is one more read of
841
+ * a texture already bound and no draw call. Its edges are white — no shadow —
842
+ * and the lookup is clamped to it, so a ray that lands past the tile (the
843
+ * throat's far side under a hard turn) reads "no shadow" rather than the hair
844
+ * or the iris the atlas keeps beside it.
845
+ */
846
+ function jawShadow(base: THREE.MeshStandardMaterial, uv: number[], extent: number[],
847
+ rimZ: number, headInverse: { value: THREE.Matrix4 }) {
848
+ const material = base.clone();
849
+ const tile = { value: new THREE.Vector4(uv[0], uv[1], uv[2], uv[3]) };
850
+ const bounds = { value: new THREE.Vector4(extent[0], extent[1], extent[2], extent[3]) };
851
+ const rim = { value: rimZ };
852
+ material.onBeforeCompile = (shader) => {
853
+ shader.uniforms.uHeadInverse = headInverse;
854
+ shader.uniforms.uJawTile = tile;
855
+ shader.uniforms.uJawBounds = bounds;
856
+ shader.uniforms.uJawRim = rim;
857
+ shader.vertexShader = shader.vertexShader
858
+ .replace("#include <common>", "#include <common>\nvarying vec3 vJawView;")
859
+ .replace("#include <project_vertex>", "#include <project_vertex>\nvJawView = mvPosition.xyz;");
860
+ shader.fragmentShader = shader.fragmentShader
861
+ .replace("#include <common>",
862
+ "#include <common>\nvarying vec3 vJawView;\nuniform mat4 uHeadInverse;\n"
863
+ + "uniform vec4 uJawTile;\nuniform vec4 uJawBounds;\nuniform float uJawRim;")
864
+ .replace("#include <map_fragment>",
865
+ "#include <map_fragment>\n"
866
+ + "vec3 jawFrom = (uHeadInverse * vec4(vJawView, 1.0)).xyz;\n"
867
+ + "vec3 jawRay = (uHeadInverse * vec4(0.0, 0.0, 1.0, 0.0)).xyz;\n"
868
+ + "vec2 jawAt = jawFrom.xy + jawRay.xy * ((uJawRim - jawFrom.z) / jawRay.z);\n"
869
+ + "jawAt = clamp(jawAt, uJawBounds.xz, uJawBounds.yw);\n"
870
+ + "vec3 jawShadow = texture2D(map, uJawTile.xz + uJawTile.yw * jawAt).rgb;\n"
871
+ + "diffuseColor.rgb *= jawShadow;")
872
+ .replace("#include <emissivemap_fragment>",
873
+ "#include <emissivemap_fragment>\ntotalEmissiveRadiance *= jawShadow;");
874
+ };
875
+ material.customProgramCacheKey = () => "tara-jaw-shadow";
876
+ return material;
877
+ }
878
+
879
+ /** Lamps, standing in for the four area lights `build_tara.setup_scene` uses.
880
+ *
881
+ * The albedo is a photograph and already holds this face's light, so 75% of it
882
+ * is emitted verbatim (`emissiveFactor` in the GLB) and only the remaining 25%
883
+ * is handed to these. They exist for the quarter that makes a yaw read as a
884
+ * head turning rather than a picture sliding; their sum along the face normal
885
+ * is π, which is exactly the irradiance that renders that quarter back at full
886
+ * albedo — so the rest frame is the reference photograph, and only a turned
887
+ * head departs from it.
888
+ */
889
+ const AMBIENT = 0.62 * Math.PI;
890
+ const KEY = 0.26 * Math.PI;
891
+ const WRAP = 0.10 * Math.PI;
892
+
893
+ /** Frames drawn per second, capped rather than left at the display's rate.
894
+ *
895
+ * `setAnimationLoop` is `requestAnimationFrame`, so uncapped this face is drawn
896
+ * as fast as the viewer's hardware refreshes — 60 on most panels, 120 on a
897
+ * ProMotion Mac or a current flagship phone. That is the wrong way round: the
898
+ * device most likely to care about the battery is the one that would draw the
899
+ * most, and it buys nothing, because idle motion here is deliberately held
900
+ * under ~1.5 Hz (CLAUDE.md) and the head's travel is a few degrees, slowly, in
901
+ * a 400 × 300 tile. 30 samples that twenty times a cycle. Character animation
902
+ * ships lipsync at 24 for a living.
903
+ *
904
+ * Measured on an M1 over four paired reps against `peep`, which is the SVG
905
+ * avatar that already ships: uncapped at 60 the 3-D face cost 13.8 points of
906
+ * one core more than peep; capped at 30 the difference was inside the noise
907
+ * (−0.9 points over three reps). The cap is most of the runtime cost of being
908
+ * 3-D at all.
909
+ *
910
+ * It throttles *drawing* only. The mixer runs its own rAF loop and keeps its
911
+ * own clock, so cue timing is exactly as accurate as it was — what drops is how
912
+ * often that clock is looked at, not how well it is kept.
913
+ */
914
+ const RENDER_FPS = 30;
915
+ const MIN_FRAME_MS = 1000 / RENDER_FPS;
916
+
917
+ export interface TaraRigOptions {
918
+ /** Called once the GLB is in the scene, for a capture tool that must wait. */
919
+ readonly onReady?: () => void;
920
+ /** The character's GLB. The second-character seam: every build fact the rig
921
+ * reads (jaw-shadow tile, rim depth, morph names) travels in the GLB's own
922
+ * extras, so a character built by the same scripts needs nothing else. Tara's
923
+ * tuning is still applied, which is the experiment.
924
+ *
925
+ * Required, and it used to default to tara's. A default meant this module
926
+ * imported one character's URL, and a bundler emits assets per module — so
927
+ * every consumer of *any* character shipped tara's GLB whether or not they
928
+ * mounted her. The caller knows which character it is building; this file
929
+ * must not ([tara-asset.ts](./tara-asset.ts)). */
930
+ readonly url: string;
931
+ /** `false` leaves an asset's expression maps unread, for a capture tool
932
+ * comparing the face with and without them. */
933
+ readonly expression?: boolean;
934
+ }
935
+
936
+ const radians = (deg: number) => (deg * Math.PI) / 180;
937
+
938
+ /** The renderer, or `null` where the browser will not give a context.
939
+ *
940
+ * Three.js throws out of the constructor rather than returning anything, and it
941
+ * has already written its own line to the console by then; that line is kept
942
+ * because it names the underlying reason, which this one does not. */
943
+ function webglRenderer(): THREE.WebGLRenderer | null {
944
+ try {
945
+ return new THREE.WebGLRenderer({ antialias: true, alpha: true });
946
+ } catch {
947
+ return null;
948
+ }
949
+ }
950
+
951
+ /**
952
+ * Where a lid channel's influence reaches a shut eye. Not at 1, because the
953
+ * mixer never asks for 1: a blink is a 0.11–0.15 s triangle, the lid channel's
954
+ * 18 ms smoothing rounds its peak off, and this rig draws at 30 fps, so the
955
+ * frame a viewer actually sees peaks at influence 0.74 on the median blink and
956
+ * 0.66 at the fifth percentile. A lid morph that shut only at 1 left every
957
+ * blink a quarter open — the lid came down and the iris was still there.
958
+ *
959
+ * So above `LID_KNEE` the influence is eased up to meet 1 at `LID_SHUT`, and
960
+ * held there: past that point the lid has landed on the lower one. Below the
961
+ * knee it is untouched, and that is every lid held part-way on purpose — the
962
+ * lowered lid of a degraded link, the lid following a downward gaze — so those
963
+ * look exactly as they did. The ease is quadratic from the knee, so both the
964
+ * value and its slope are continuous there.
965
+ *
966
+ * `scripts/morphs.py:influence` parses both numbers out of this file.
967
+ */
968
+ /**
969
+ * The lower lid follows the eye down. Its retractor is tied to the inferior
970
+ * rectus, so a look down pulls the lower margin down with it by a millimetre
971
+ * or two — the upper lid's half of this is the mixer's `lidBias`, and a face
972
+ * whose upper lid follows while the lower one stays reads as a drowsy droop
973
+ * rather than a glance. Driven through the squint target run backwards,
974
+ * which is the lower lid and nothing else: at the notes gaze (`pupilY` 0.72)
975
+ * the margin drops ~0.006, about 1.7 px at the 400 px tile.
976
+ */
977
+ const LOWER_LID_FOLLOW = 0.35;
978
+
979
+ const LID_KNEE = 0.35;
980
+ const LID_SHUT = 0.66;
981
+
982
+ /**
983
+ * A squint's influence rises faster than its channel. The mixer's values are
984
+ * set where a line face's lower lid reads — a smile's squint is 0.30 — and a
985
+ * photographic lower lid rising 0.30 of its travel is a pixel or two, so the
986
+ * squint that makes a smile real was not there. A power curve lifts the small
987
+ * values into sight. The lower-lid follow, which runs this target backwards,
988
+ * is added after it and stays linear.
989
+ *
990
+ * TARA-SPECIFIC. The curve needs a ceiling as well as a lift, because the
991
+ * squint stacks and the mouth does not. A *silent* smile takes squint from
992
+ * three layers at once — an approval clip, the encouraging emotion and
993
+ * prosody's warmth — which reach 0.51 together, while the smile map saturates
994
+ * at a mouth corner of 0.8 and no layer drives the jaw, so the last third of a
995
+ * smile arrives as narrowing eyes over lips that cannot part any further. On a
996
+ * line face that reads as warmth. On a photograph it reads as sedation: a
997
+ * reviewer watching a recorded call read those two moments as the avatar
998
+ * falling asleep or heavily medicated, and named the eyes, not the mouth. The
999
+ * ceiling is where the face stops reading drugged, judged at crop. The knee is
1000
+ * low enough that an ordinary one-layer smile is untouched (0.22 renders
1001
+ * 0.402, against 0.403 with no ceiling at all), and the approach is
1002
+ * exponential rather than a clamp so the slope is continuous where the two
1003
+ * meet and the lower lid never visibly sticks.
1004
+ */
1005
+ const SQUINT_CURVE = 0.6;
1006
+ const SQUINT_KNEE = 0.2;
1007
+ const SQUINT_CEIL = 0.54;
1008
+
1009
+ const squintCurve = (i: number): number => {
1010
+ if (i <= 0) return i;
1011
+ if (i <= SQUINT_KNEE) return i ** SQUINT_CURVE;
1012
+ const knee = SQUINT_KNEE ** SQUINT_CURVE;
1013
+ const slope = SQUINT_CURVE * SQUINT_KNEE ** (SQUINT_CURVE - 1);
1014
+ const head = SQUINT_CEIL - knee;
1015
+ return SQUINT_CEIL - head * Math.exp((-slope * (i - SQUINT_KNEE)) / head);
1016
+ };
1017
+
1018
+ const lidClosure = (i: number): number => {
1019
+ if (i <= LID_KNEE) return i;
1020
+ if (i >= LID_SHUT) return 1;
1021
+ const t = (i - LID_KNEE) / (LID_SHUT - LID_KNEE);
1022
+ return i + (1 - LID_SHUT) * t * t;
1023
+ };
1024
+
1025
+ /**
1026
+ * A channel's morph influence. One line — and the lid and squint curves above — and the
1027
+ * same one `scripts/morphs.py:influence` uses, so a Blender preview and the
1028
+ * browser pose the face identically.
1029
+ *
1030
+ * It is allowed to go negative, which is what lets one target serve a
1031
+ * bidirectional channel: `mouthCornerL` at −1.4 is the smile target run
1032
+ * backwards into a frown, and `lidL` below its 0.12 rest opens the eye wider
1033
+ * than neutral. A rig that clamped this at 0 would silently delete the negative
1034
+ * half of six channels.
1035
+ */
1036
+ /**
1037
+ * The neck's follow targets, and the one place a morph is not driven by
1038
+ * `influence`.
1039
+ *
1040
+ * `scripts/morphs.neck_targets` authors two fields per head axis — `A P` and
1041
+ * `A^2 P` for that axis's skew matrix — because a rigid rotation is exactly
1042
+ * `sin(th)` of the first plus `1 - cos(th)` of the second. A single field scaled
1043
+ * by the pose is the *linear* approximation of that, and it stretches the neck
1044
+ * away from the pivot by `radius x (1 - cos th)`: fine at six degrees, five
1045
+ * pixels at the envelope a nod that lands actually needs.
1046
+ *
1047
+ * So under pitch and roll the throat tracks the skull exactly at any angle,
1048
+ * and — the part worth having — the asset stops depending on the envelope.
1049
+ * These fields carry no angle, so `HEAD_DEG` below is a runtime number that can
1050
+ * move without leaving `tara.glb` stale. Yaw's pair is a partial twist rather
1051
+ * than the skull's own rotation, and the build weights its two fields so these
1052
+ * same two influences drive it (`morphs.neck_twist`).
1053
+ */
1054
+ const NECK_QUAD = "_q";
1055
+ const HEAD_AXIS: Record<string, keyof typeof HEAD_DEG> = {
1056
+ headYaw: "yaw", headPitch: "pitch", headRoll: "roll",
1057
+ };
1058
+
1059
+ const neckInfluence = (channel: string, pose: RigPose): number | null => {
1060
+ const quad = channel.endsWith(NECK_QUAD);
1061
+ const axis = HEAD_AXIS[quad ? channel.slice(0, -NECK_QUAD.length) : channel];
1062
+ if (!axis) return null;
1063
+ const value = pose[quad ? channel.slice(0, -NECK_QUAD.length) : channel] ?? 0;
1064
+ const radians = ((value / HEAD_CLAMP) * HEAD_DEG[axis] * Math.PI) / 180;
1065
+ return quad ? 1 - Math.cos(radians) : Math.sin(radians);
1066
+ };
1067
+
1068
+ /**
1069
+ * The hair's roll, which is the one thing in this rig that is not a function of
1070
+ * the pose alone.
1071
+ *
1072
+ * A hank that hangs past the jaw is lying on a shoulder, and a shoulder does not
1073
+ * tilt when the head does. Rolled rigidly with the skull it lifts off the collar
1074
+ * and the page shows through behind it, so the shell gives up `hold` of the
1075
+ * roll at its lowest rows and none at the crown, graded by `morphs.hair_hold`.
1076
+ * That is the static half and it is what fixes the gap.
1077
+ *
1078
+ * The other half is why roll read as a hinge at all. A rigid rotation about a
1079
+ * fixed point is a hinge — there is nothing else in it — and what a real head
1080
+ * tilt has that this lacked is hair that arrives late and settles. Live2D gives
1081
+ * every hank a spring for exactly this (`docs/research-head-rotation.md` § 3.1:
1082
+ * mobility ~0.95, delay 0.8-0.9, one clear overshoot), so this is a spring on
1083
+ * the hair's own angle chasing the share of the roll it agrees to take.
1084
+ *
1085
+ * It is on the hair and not on the head's channels on purpose. The mixer's
1086
+ * per-channel time constants are shared with the SVG faces and every clip in the
1087
+ * library is authored pre-compensated for them, so a spring on `headRoll` would
1088
+ * silently re-time every nod ever authored. Secondary motion on a shell that
1089
+ * only this renderer has costs nothing outside it.
1090
+ *
1091
+ * 1.5 Hz is the band the library already keeps gesture under, and a hank of hair
1092
+ * on a real head swings near it (a 7 cm pendulum is 1.9 Hz); the damping is a
1093
+ * single visible overshoot, settling inside 0.8 s. Faster reads as a flick and
1094
+ * slower as wet hair.
1095
+ */
1096
+ /**
1097
+ * `hold` is the share of the head's roll the hanging hair declines to take, and
1098
+ * `hz`/`damping` are how it gets there. 1.5 Hz is the ceiling the repo's idle
1099
+ * constraint sets on *driven* oscillation; a settle is a one-shot and could
1100
+ * defensibly go faster, but there is no reason to spend the exemption: what
1101
+ * unhinges the roll is the hair arriving late, not the ring. At 0.65 it trails
1102
+ * by 93% of its travel a frame in, overshoots 5% and is inside 5% of the hold in
1103
+ * 450 ms — well within a phrase's hold.
1104
+ */
1105
+ export const HAIR_ROLL = { hold: 0.85, hz: 1.5, damping: 0.65 };
1106
+
1107
+ /**
1108
+ * One step of `HAIR_ROLL`'s spring: semi-implicit, the rate taking the frame's
1109
+ * acceleration before the angle takes the rate. Explicit Euler rings at this
1110
+ * stiffness and 30 fps; this does not, which is the only reason the order of
1111
+ * those two lines is worth a sentence.
1112
+ *
1113
+ * Exported for `test/nods.test.ts`, because settle time and overshoot are
1114
+ * numbers and not something a still frame can show. It is not part of the
1115
+ * package's surface — `packages/avatar/client/tara.ts` is.
1116
+ */
1117
+ export const hairRollStep = (angle: number, rate: number, target: number, dt: number) => {
1118
+ const w = 2 * Math.PI * HAIR_ROLL.hz;
1119
+ const next = rate + (w * w * (target - angle) - 2 * HAIR_ROLL.damping * w * rate) * dt;
1120
+ return { angle: angle + next * dt, rate: next };
1121
+ };
1122
+
1123
+ /** The hair pair's two influences, from the *extra* angle the shell is turned
1124
+ * by — the same `sin` / `1 - cos` terms the neck's fields are driven with. */
1125
+ const hairInfluence = (channel: string, extra: number): number | null => {
1126
+ if (channel === "headRoll") return Math.sin(extra);
1127
+ if (channel === "headRoll" + NECK_QUAD) return 1 - Math.cos(extra);
1128
+ return null;
1129
+ };
1130
+
1131
+ const influence = (channel: string, value: number): number => {
1132
+ const rest = (REST as Record<string, number>)[channel] ?? 0;
1133
+ const i = (value - rest) / (1 - rest);
1134
+ if (channel === "lidL" || channel === "lidR") return lidClosure(i);
1135
+ return channel === "squintL" || channel === "squintR" ? squintCurve(i) : i;
1136
+ };
1137
+
1138
+ /** One side's weights for the asset's expression maps, in its order. A
1139
+ * channel with no side (`mouthPress`) weighs the same on both. */
1140
+ const expressionWeights = (pose: RigPose, side: "L" | "R", expression: Expression,
1141
+ into: Float32Array) => {
1142
+ const at = (channel: string) => {
1143
+ const name = pose[channel + side] === undefined ? channel : channel + side;
1144
+ const value = pose[name];
1145
+ return value === undefined ? 0 : influence(name, value);
1146
+ };
1147
+ expression.names.forEach((map, i) => {
1148
+ const weight = EXPRESSION_WEIGHT[map]?.(at) ?? 0;
1149
+ into[i] = Math.min(Math.max(weight, 0), 1);
1150
+ });
1151
+ };
1152
+
1153
+ // `options` is `unknown` in the contract, and stays `unknown` here: the mixer
1154
+ // passes `rigOptions` through verbatim and has no way to know any rig's shape.
1155
+ export function createTaraRig(mount: HTMLElement, options?: unknown): AvatarRig {
1156
+ const { onReady, url, expression: readExpression = true } =
1157
+ (options ?? {}) as TaraRigOptions;
1158
+ // A missing `url` is a caller's defect, not a browser condition — the WebGL
1159
+ // path below degrades because a driver is nobody's fault, whereas this would
1160
+ // otherwise be a 404 on a path spelled `undefined`.
1161
+ if (!url) throw new TypeError("createTaraRig: `url` is required");
1162
+ const scene = new THREE.Scene();
1163
+ const camera = new THREE.OrthographicCamera(-1, 1, 1, -1, 0.1, 100);
1164
+ camera.position.set(0, FRAME_CENTRE, 6);
1165
+ camera.lookAt(0, FRAME_CENTRE, 0);
1166
+
1167
+ const renderer = webglRenderer();
1168
+ // No context, no face — and that has to be the whole of it. `createAvatar` is
1169
+ // synchronous and returns `{ destroy }`, so a consumer has nothing to catch:
1170
+ // anything thrown here lands in *their* window and takes the call page with
1171
+ // it, over a browser condition that is nobody's defect. WebGL is unavailable
1172
+ // more often than it looks — a driver on a blocklist, a hardened profile, a
1173
+ // remote desktop — and the right outcome is a call that still has audio,
1174
+ // captions and states, with an empty tile where the head would be.
1175
+ //
1176
+ // `warn` rather than `error` on purpose: `[avatar]` console errors mean a
1177
+ // defect in this package, and the capture tools fail a run on any of them.
1178
+ // This one says the environment cannot draw, which is a different sentence.
1179
+ if (!renderer) {
1180
+ console.warn("[avatar] no WebGL context; this character will not render in this browser");
1181
+ return { apply() { /* nothing to pose */ }, destroy() { /* nothing to release */ } };
1182
+ }
1183
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
1184
+ // `setSize(…, false)` below leaves CSS alone, so the canvas has to be told to
1185
+ // fill the mount. Without this it displays at its backing-store size, which on
1186
+ // a 2x screen is a head twice the tile, cropped to its top-left quarter —
1187
+ // invisible at devicePixelRatio 1, which is what every capture tool ran at.
1188
+ renderer.domElement.style.cssText = "display:block;width:100%;height:100%";
1189
+ mount.append(renderer.domElement);
1190
+
1191
+ scene.add(new THREE.AmbientLight(0xffffff, AMBIENT));
1192
+ const key = new THREE.DirectionalLight(0xffffff, KEY);
1193
+ key.position.set(0, 1.0, 3.0);
1194
+ scene.add(key);
1195
+ for (const x of [-1.9, 1.9]) {
1196
+ const wrap = new THREE.DirectionalLight(0xffffff, WRAP);
1197
+ wrap.position.set(x, 1.0, 2.5);
1198
+ scene.add(wrap);
1199
+ }
1200
+
1201
+ // The head swings as a group; the neck and torso do not (see HEAD_PARTS).
1202
+ // Parenting to a pivot object rather than rotating each part is not a
1203
+ // convenience — the parts have to rotate about a shared point, and a per-mesh
1204
+ // rotation about each mesh's own origin would slide them apart.
1205
+ //
1206
+ // The body's two transforms nest outside it, one group each (see BODY):
1207
+ // `trunk` sways everything, and `lift` carries the neck and head on the
1208
+ // breath the torso takes inside `trunk` — and on the lean's rigid share,
1209
+ // which reaches the head the same way for the same reason.
1210
+ //
1211
+ // There were three. The outermost was `figure`, and it existed only to scale
1212
+ // the whole character for `torsoLean`; with the camera a sibling rather than
1213
+ // a child, that was a zoom and not a lean. The trunk deforms on the shell now
1214
+ // (`morphs.torso_targets`), so the group has no work left and is gone rather
1215
+ // than left behind as an identity transform for someone to wonder about.
1216
+ const trunk = new THREE.Group();
1217
+ const lift = new THREE.Group();
1218
+ const head = new THREE.Group();
1219
+ head.position.copy(PIVOT);
1220
+ // Yaw and pitch turn `head`; roll turns `tilt`, which rides inside them at
1221
+ // the chin (ROLL_PIVOT), so the parts hang from `tilt`.
1222
+ const tilt = new THREE.Group();
1223
+ tilt.position.subVectors(ROLL_PIVOT, PIVOT);
1224
+ scene.add(trunk);
1225
+ trunk.add(lift);
1226
+ lift.add(head);
1227
+ head.add(tilt);
1228
+ let torso: THREE.Object3D | null = null;
1229
+
1230
+ let destroyed = false;
1231
+ let pending: RigPose | null = null;
1232
+ let loaded = false;
1233
+ let warnedAboutRuntimeBudget = false;
1234
+ // Every mesh that owns morph targets, paired with the dictionary three.js
1235
+ // built from the GLB's `extras.targetNames` — i.e. the pose channel names
1236
+ // `scripts/morphs.py` authored them under.
1237
+ const morphed: THREE.Mesh[] = [];
1238
+ const eyes: THREE.Object3D[] = [];
1239
+ // Both globes turn together, so one rotation serves both sockets.
1240
+ const gaze = { value: new THREE.Matrix3() };
1241
+ const turn = new THREE.Matrix4();
1242
+ let expression: Expression | null = null;
1243
+ // The `Hair` shell, on a character whose hair hangs low enough to have the
1244
+ // roll pair; null on one whose hair stops beside the temple (`HAIR_ROLL`).
1245
+ let hairMesh: THREE.Mesh | null = null;
1246
+ // The head's roll in the asset's own frame — what both the neck's follow and
1247
+ // the hair's are authored about — and the hair's own, which chases it.
1248
+ let headRollRad = 0;
1249
+ let hairRollRad = 0;
1250
+ let hairRate = 0;
1251
+ let hairSeeded = false;
1252
+
1253
+ /** The share of the head's roll the hair settles at. */
1254
+ const hairTarget = () => headRollRad * (1 - HAIR_ROLL.hold);
1255
+
1256
+ const writeHair = () => {
1257
+ const dictionary = hairMesh?.morphTargetDictionary;
1258
+ const influences = hairMesh?.morphTargetInfluences;
1259
+ if (!dictionary || !influences) return;
1260
+ const extra = hairRollRad - headRollRad;
1261
+ for (const [channel, index] of Object.entries(dictionary)) {
1262
+ const term = hairInfluence(channel, extra);
1263
+ if (term !== null) influences[index] = term;
1264
+ }
1265
+ };
1266
+
1267
+ const stepHair = (dt: number) => {
1268
+ if (!hairMesh || !hairSeeded) return;
1269
+ ({ angle: hairRollRad, rate: hairRate } =
1270
+ hairRollStep(hairRollRad, hairRate, hairTarget(), dt));
1271
+ };
1272
+
1273
+ const resize = () => {
1274
+ const width = Math.max(1, mount.clientWidth);
1275
+ const height = Math.max(1, mount.clientHeight || Math.round((width * 3) / 4));
1276
+ renderer.setPixelRatio(pixelRatioFor(width, height, window.devicePixelRatio));
1277
+ renderer.setSize(width, height, false);
1278
+ // The framed *height* is fixed and the width follows the mount, so a tile
1279
+ // of the wrong aspect shows more or less background rather than a face of
1280
+ // the wrong shape. The atlas cannot be stretched: it is a photograph.
1281
+ // Symmetric about the camera, which is *already* at the frame's centre
1282
+ // height. Offsetting the frustum by that centre as well applies it twice:
1283
+ // the face rendered 0.47 face heights low, at exactly the right size, which
1284
+ // reads as a framing choice rather than as the arithmetic error it was.
1285
+ const halfHeight = FRAME_HEIGHT / 2;
1286
+ const halfWidth = (halfHeight * width) / height;
1287
+ camera.top = halfHeight;
1288
+ camera.bottom = -halfHeight;
1289
+ camera.left = -halfWidth;
1290
+ camera.right = halfWidth;
1291
+ camera.updateProjectionMatrix();
1292
+ };
1293
+ const observer = new ResizeObserver(resize);
1294
+ observer.observe(mount);
1295
+ resize();
1296
+
1297
+ const applyPose = (pose: RigPose) => {
1298
+ headRollRad = radians(((pose.headRoll ?? 0) / HEAD_CLAMP) * HEAD_DEG.roll);
1299
+ // The first pose is a starting point, not a movement: seed the hair where it
1300
+ // would have settled, so a tool that sets one pose and screenshots it gets
1301
+ // the hold with no transient, and only a *change* of roll swings the hank.
1302
+ if (!hairSeeded) { hairSeeded = true; hairRollRad = hairTarget(); hairRate = 0; }
1303
+ for (const mesh of morphed) {
1304
+ const dictionary = mesh.morphTargetDictionary;
1305
+ const influences = mesh.morphTargetInfluences;
1306
+ if (!dictionary || !influences) continue;
1307
+ const neck = mesh.name === "Neck";
1308
+ const hair = mesh === hairMesh;
1309
+ for (const [channel, index] of Object.entries(dictionary)) {
1310
+ // The hair carries the head's roll channel too, and it is neither a
1311
+ // channel value nor the head's own angle: it is how much *further* than
1312
+ // the skull this shell is turned, which is negative while it holds and
1313
+ // swings either side of that while it settles (`HAIR_ROLL`).
1314
+ if (hair) {
1315
+ const term = hairInfluence(channel, hairRollRad - headRollRad);
1316
+ if (term !== null) { influences[index] = term; continue; }
1317
+ }
1318
+ // The neck's head targets are the rotation's two terms, not a channel
1319
+ // scaled by the influence law. Only on the neck: the same three channel
1320
+ // names on the head group are a rigid transform, and nowhere else.
1321
+ if (neck) {
1322
+ const term = neckInfluence(channel, pose);
1323
+ if (term !== null) { influences[index] = term; continue; }
1324
+ }
1325
+ const value = pose[channel];
1326
+ const follow = channel.startsWith("squint") ? LOWER_LID_FOLLOW * Math.max(pose.pupilY ?? 0, 0) : 0;
1327
+ if (value === undefined && !follow) continue;
1328
+ influences[index] = (value === undefined ? 0 : influence(channel, value)) - follow;
1329
+ }
1330
+ }
1331
+ // Blender's Z is face-space v, so its yaw is about Z, its pitch about X and
1332
+ // its roll about Y. The export maps Blender (x, y, z) to glTF (x, z, −y),
1333
+ // so Blender +Z *is* glTF +Y and Blender +X is glTF +X: yaw and pitch carry
1334
+ // across with their sign intact. Only roll changes sign, because Blender +Y
1335
+ // is glTF −Z, and that is a statement about two axes and not about the
1336
+ // channel.
1337
+ //
1338
+ // Yaw was negated here as well until 2026-09-10, on the belief that the
1339
+ // export flips the handedness of a turn. It does not — both frames are
1340
+ // right-handed — and the cost was a head that turned toward the viewer's
1341
+ // *left* on a positive `headYaw`, against `params.js`'s stated sign. It
1342
+ // survived because the same negation was in `build_tara.pose_head`, so the
1343
+ // Blender preview and the browser agreed with each other and only disagreed
1344
+ // with the library. `gaze.js` is what makes it a defect rather than a
1345
+ // convention: it hands `pupilX` and `headYaw` the same aversion term, so
1346
+ // tara's eyes went one way and her head went the other.
1347
+ //
1348
+ // YXZ because that is the order a neck composes in — yaw carrying the pitch
1349
+ // — rather than the order three.js defaults to.
1350
+ // The body first, because the head's roll is stated against it.
1351
+ //
1352
+ // Positive `torsoTurn` takes the trunk to the viewer's right, which about a
1353
+ // pivot below it is a clockwise roll as the camera sees it: negative about
1354
+ // glTF +Z, the axis pointing at the camera.
1355
+ const sway = -radians((pose.torsoTurn ?? 0) * BODY.swayDeg);
1356
+ trunk.rotation.z = sway;
1357
+ trunk.position.set(BODY.hip * Math.sin(sway), BODY.hip * (1 - Math.cos(sway)), 0);
1358
+ // `torsoLean` itself is not applied here at all — it is two morph targets on
1359
+ // the shell, driven by the generic loop above like any other channel that
1360
+ // rests at 0. What is left for the rig is the head's ride: above the collar
1361
+ // the field is flat, so the neck and head take a pure translation and the
1362
+ // head does not deform under a body lean (research § 8 item 4). `morphs.py`
1363
+ // parses `leanRide`, so this is the same number the field plateaus at.
1364
+ const breath = pose.breath ?? 0;
1365
+ if (torso) {
1366
+ torso.scale.set(1 + breath * BODY.widen, 1 + breath * BODY.rise, 1);
1367
+ torso.position.y = -BODY.swellPivot * breath * BODY.rise;
1368
+ }
1369
+ lift.position.y = breath * BODY.rise * (BODY.collar - BODY.swellPivot)
1370
+ - (pose.torsoLean ?? 0) * BODY.leanRide;
1371
+
1372
+ head.rotation.order = "YXZ";
1373
+ head.rotation.set(
1374
+ radians(((pose.headPitch ?? 0) / HEAD_CLAMP) * HEAD_DEG.pitch),
1375
+ radians(((pose.headYaw ?? 0) / HEAD_CLAMP) * HEAD_DEG.yaw),
1376
+ 0,
1377
+ );
1378
+ // Less the trunk's roll, so the head's world roll is `headRoll` and
1379
+ // nothing else. Exact about Z alone; with the yaw and pitch it composes
1380
+ // with, the error is the product of two sub-degree angles.
1381
+ tilt.rotation.z = -headRollRad - sway;
1382
+ for (const globe of eyes) {
1383
+ globe.rotation.order = "YXZ";
1384
+ globe.rotation.set(
1385
+ (pose.pupilY ?? 0) * GAZE_TRAVEL.y / GLOBE_RADIUS,
1386
+ (pose.pupilX ?? 0) * GAZE_TRAVEL.x / GLOBE_RADIUS,
1387
+ 0,
1388
+ );
1389
+ }
1390
+ if (eyes.length) gaze.value.setFromMatrix4(turn.makeRotationFromEuler(eyes[0].rotation));
1391
+ if (expression) {
1392
+ expressionWeights(pose, "L", expression, expression.left);
1393
+ expressionWeights(pose, "R", expression, expression.right);
1394
+ }
1395
+ };
1396
+
1397
+ new GLTFLoader().load(url, (gltf) => {
1398
+ if (destroyed) return;
1399
+ trunk.add(gltf.scene);
1400
+ // Collect the morphed meshes *before* reparenting: every one of them is a
1401
+ // head part, so a traverse of `gltf.scene` after the move finds only the
1402
+ // neck and the torso and the whole face goes rigid — silently, because a
1403
+ // rig with nothing to drive still renders a perfectly good rest pose.
1404
+ gltf.scene.traverse((object) => {
1405
+ const mesh = object as THREE.Mesh;
1406
+ if (mesh.isMesh && mesh.morphTargetDictionary) morphed.push(mesh);
1407
+ // Kept aside as well: its roll pair is driven by a clock and not only by a
1408
+ // pose, so the render loop has to reach it between poses (`HAIR_ROLL`).
1409
+ if (mesh.isMesh && mesh.name === "Hair" && mesh.morphTargetDictionary) hairMesh = mesh;
1410
+ });
1411
+ // Out of the scene before anything draws it: it carries the maps, and is
1412
+ // one triangle behind the body that nothing should pay a draw call for.
1413
+ const carrier = gltf.scene.getObjectByName("Expression") as THREE.Mesh | undefined;
1414
+ if (carrier) {
1415
+ carrier.removeFromParent();
1416
+ expression = readExpression ? expressive(carrier) : null;
1417
+ if (!expression) (carrier.material as THREE.MeshStandardMaterial).map?.dispose();
1418
+ carrier.geometry.dispose();
1419
+ (carrier.material as THREE.Material).dispose();
1420
+ }
1421
+ for (const name of HEAD_PARTS) {
1422
+ const part = gltf.scene.getObjectByName(name);
1423
+ // Reparenting moves the object into the tilt's frame, whose origin is
1424
+ // ROLL_PIVOT, so subtract that to leave the part where it was authored.
1425
+ // `attach()` would do this from the world matrix, which has not been
1426
+ // computed yet at load.
1427
+ if (part) {
1428
+ part.position.sub(ROLL_PIVOT);
1429
+ tilt.add(part);
1430
+ }
1431
+ }
1432
+ // One clone per source material, shared by every shell that carries the
1433
+ // field; a mesh without it keeps the material it came with.
1434
+ const turned = new Map<THREE.Material, THREE.MeshStandardMaterial>();
1435
+ head.traverse((object) => {
1436
+ const mesh = object as THREE.Mesh;
1437
+ if (!mesh.isMesh || !mesh.geometry.getAttribute(MOTION_DEPTH)) return;
1438
+ const base = mesh.material as THREE.MeshStandardMaterial;
1439
+ const own = turned.get(base) ?? motionDepth(base, expression ?? undefined);
1440
+ turned.set(base, own);
1441
+ mesh.material = own;
1442
+ });
1443
+ // The neck rides the breath with the head; the torso *is* the breath. Both
1444
+ // are authored in world space with identity nodes, and `lift` sits at the
1445
+ // origin until a pose arrives, so moving the neck needs no correction.
1446
+ const neck = gltf.scene.getObjectByName("Neck") as THREE.Mesh | undefined;
1447
+ if (neck) lift.add(neck);
1448
+ // The shadow's map comes from the build (`build_tara.py`, the neck); an
1449
+ // asset without it keeps the shadow painted on, as every build did before.
1450
+ const skull = head.getObjectByName("Head");
1451
+ const { jaw_shadow_uv: jawUv, jaw_shadow_extent: jawExtent, jaw_shadow_rim_z: jawRim } =
1452
+ neck?.userData ?? {};
1453
+ if (neck && skull && Array.isArray(jawUv) && Array.isArray(jawExtent) && typeof jawRim === "number") {
1454
+ const headInverse = { value: new THREE.Matrix4() };
1455
+ neck.material = jawShadow(neck.material as THREE.MeshStandardMaterial, jawUv, jawExtent,
1456
+ jawRim, headInverse);
1457
+ neck.onBeforeRender = (_renderer, _scene, camera) => {
1458
+ headInverse.value.multiplyMatrices(camera.matrixWorldInverse, skull.matrixWorld).invert();
1459
+ };
1460
+ }
1461
+ torso = gltf.scene.getObjectByName("Body") ?? null;
1462
+ for (const name of ["Eye_L", "Eye_R"]) {
1463
+ const globe = head.getObjectByName(name);
1464
+ if (!globe) continue;
1465
+ // The globe's geometry is authored in world space with no node transform,
1466
+ // so it has to be rotated about its own centre rather than about the
1467
+ // origin. Re-centre the geometry once and put the offset on the node; the
1468
+ // catchlight is already a child and rides the globe, which is what a
1469
+ // reflection on a wet cornea does.
1470
+ const geometry = (globe as THREE.Mesh).geometry;
1471
+ geometry.computeBoundingSphere();
1472
+ const centre = geometry.boundingSphere?.center.clone() ?? new THREE.Vector3();
1473
+ geometry.translate(-centre.x, -centre.y, -centre.z);
1474
+ globe.position.add(centre);
1475
+ for (const child of globe.children) child.position.sub(centre);
1476
+ const mesh = globe as THREE.Mesh;
1477
+ // Whether the globe turns deep is the attribute's to say, not the name's —
1478
+ // the same rule the frame's shells are found by above. An asset built
1479
+ // before the globes carried the field keeps the socket shader alone.
1480
+ mesh.material = socketed(mesh.material as THREE.MeshStandardMaterial,
1481
+ name === "Eye_L" ? -1 : 1, gaze,
1482
+ mesh.geometry.getAttribute(MOTION_DEPTH) !== undefined);
1483
+ eyes.push(globe);
1484
+ }
1485
+ // The mouth's inside, which is otherwise the one flat-lit surface on this
1486
+ // face. Found by *mesh* name rather than material name: `flat_material`
1487
+ // hard-codes a `tara_` prefix, so tushar's cavity material is called
1488
+ // `tara_cavity` as well, and the mesh is what distinguishes it.
1489
+ const cavity = head.getObjectByName("Cavity") as THREE.Mesh | undefined;
1490
+ if (cavity) {
1491
+ cavity.geometry.computeBoundingBox();
1492
+ const box = cavity.geometry.boundingBox;
1493
+ if (box) {
1494
+ cavity.material = cavityShade(cavity.material as THREE.MeshStandardMaterial,
1495
+ box.min.y, box.max.y);
1496
+ }
1497
+ }
1498
+ // A rig with no morph targets still renders a perfectly good rest pose, so
1499
+ // the failure mode of losing them is a face that simply never moves — which
1500
+ // a still frame cannot show. Say so, loudly enough that the Gate B capture
1501
+ // (which fails on any `[avatar]` console error) catches it.
1502
+ if (!morphed.length) console.error("[avatar] this character has no morph targets; the face will not move", url);
1503
+ loaded = true;
1504
+ if (pending) applyPose(pending);
1505
+ onReady?.();
1506
+ }, undefined, (error: unknown) => console.error("[avatar] could not load this character", url, error));
1507
+
1508
+ // The tolerance is not a fudge factor, it is the whole of what makes the cap
1509
+ // land on 30. rAF fires on the panel's own grid, so the elapsed time is only
1510
+ // ever a multiple of the refresh interval and lands *near* 33.3 ms rather than
1511
+ // on it: 33.33 on a 60 Hz panel, and either side of it under any timestamp
1512
+ // jitter. A bare `elapsed < MIN_FRAME_MS` therefore rejects the frame it wants
1513
+ // and waits for the next one — 50 ms, i.e. 20 fps, not 30. Four milliseconds
1514
+ // is under half the interval of every rate worth caring about (8.3 at 120,
1515
+ // 11.1 at 90, 16.7 at 60), so it can never admit two frames where one belongs,
1516
+ // and it puts 60, 90 and 120 Hz all on 30 fps.
1517
+ const GRID_TOLERANCE_MS = 4;
1518
+ let lastFrameMs = 0;
1519
+ renderer.setAnimationLoop(() => {
1520
+ const now = performance.now();
1521
+ const elapsed = now - lastFrameMs;
1522
+ if (elapsed < MIN_FRAME_MS - GRID_TOLERANCE_MS) return;
1523
+ lastFrameMs = now;
1524
+ // The hair lags the skull and settles behind it, which is a state and not a
1525
+ // function of the pose, so it advances on the clock. Clamped, because a tab
1526
+ // that was in the background hands back a gap and not a frame.
1527
+ stepHair(Math.min(elapsed / 1000, 0.1));
1528
+ writeHair();
1529
+ renderer.render(scene, camera);
1530
+ if (!warnedAboutRuntimeBudget &&
1531
+ (renderer.info.render.calls > HARD_BUDGET.drawCalls ||
1532
+ renderer.info.render.triangles > HARD_BUDGET.triangles)) {
1533
+ warnedAboutRuntimeBudget = true;
1534
+ console.warn("[avatar] runtime budget exceeded", {
1535
+ calls: renderer.info.render.calls,
1536
+ triangles: renderer.info.render.triangles,
1537
+ });
1538
+ }
1539
+ });
1540
+
1541
+ return {
1542
+ apply(frame: AvatarFrame) {
1543
+ // The mixer smooths every channel before it gets here (each has its own
1544
+ // τ, `docs/internal-rig.md`), so the rig eases nothing itself. Poses that
1545
+ // arrive before the GLB does are not queued, only remembered: the newest
1546
+ // one is the only one that was ever going to be shown.
1547
+ if (!loaded) { pending = frame.pose; return; }
1548
+ applyPose(frame.pose);
1549
+ },
1550
+ destroy() {
1551
+ if (destroyed) return;
1552
+ destroyed = true;
1553
+ observer.disconnect();
1554
+ renderer.setAnimationLoop(null);
1555
+ scene.traverse((object) => {
1556
+ const mesh = object as THREE.Mesh;
1557
+ mesh.geometry?.dispose();
1558
+ for (const item of Array.isArray(mesh.material) ? mesh.material : [mesh.material]) {
1559
+ const material = item as THREE.MeshStandardMaterial | undefined;
1560
+ material?.map?.dispose();
1561
+ material?.emissiveMap?.dispose();
1562
+ material?.dispose();
1563
+ }
1564
+ });
1565
+ // A uniform, not a material's map, so the traverse above never meets it.
1566
+ expression?.map.dispose();
1567
+ renderer.dispose();
1568
+ renderer.domElement.remove();
1569
+ },
1570
+ };
1571
+ }