spi3der 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (113) hide show
  1. package/APP.md +40 -0
  2. package/Dockerfile +4 -0
  3. package/MCP.md +149 -0
  4. package/PLAYER.md +136 -0
  5. package/README.md +35 -2
  6. package/api/mcp.mjs +31 -0
  7. package/api/store.mjs +158 -0
  8. package/bin/spi3der.mjs +20 -0
  9. package/emulator.html +17 -0
  10. package/engine/8fa668821759/bevel.js +265 -0
  11. package/engine/8fa668821759/camera.js +76 -0
  12. package/engine/8fa668821759/character.js +1019 -0
  13. package/engine/8fa668821759/check.js +83 -0
  14. package/engine/8fa668821759/csg.js +342 -0
  15. package/engine/8fa668821759/edit.js +48 -0
  16. package/engine/8fa668821759/galaxy.js +265 -0
  17. package/engine/8fa668821759/gl.js +798 -0
  18. package/engine/8fa668821759/gpu.js +1356 -0
  19. package/engine/8fa668821759/index.js +48 -0
  20. package/engine/8fa668821759/instances.js +41 -0
  21. package/engine/8fa668821759/joints.js +355 -0
  22. package/engine/8fa668821759/kernel-bytes.js +2 -0
  23. package/engine/8fa668821759/kernel.js +82 -0
  24. package/engine/8fa668821759/lathe.js +87 -0
  25. package/engine/8fa668821759/material.js +19 -0
  26. package/engine/8fa668821759/mesh.js +131 -0
  27. package/engine/8fa668821759/order.js +125 -0
  28. package/engine/8fa668821759/pick.js +85 -0
  29. package/engine/8fa668821759/place.js +17 -0
  30. package/engine/8fa668821759/planet.js +376 -0
  31. package/engine/8fa668821759/rig.js +417 -0
  32. package/engine/8fa668821759/saw.js +121 -0
  33. package/engine/8fa668821759/sky.js +428 -0
  34. package/engine/8fa668821759/svg.js +239 -0
  35. package/engine/8fa668821759/text.js +231 -0
  36. package/engine/8fa668821759/triangulate.js +72 -0
  37. package/engine/8fa668821759/types.js +2 -0
  38. package/engine/8fa668821759/vec.js +22 -0
  39. package/engine/8fa668821759/version.js +7 -0
  40. package/engine/8fa668821759/vrtsh.js +354 -0
  41. package/engine/8fa668821759/wire.js +346 -0
  42. package/favicon.svg +15 -0
  43. package/help.md +289 -0
  44. package/icons/apple-touch-icon.png +0 -0
  45. package/icons/favicon-32.png +0 -0
  46. package/icons/icon-192.png +0 -0
  47. package/icons/icon-512.png +0 -0
  48. package/icons/icon-maskable-512.png +0 -0
  49. package/icons/icon-maskable.svg +13 -0
  50. package/icons/icon.svg +15 -0
  51. package/index.html +13730 -0
  52. package/manifest.webmanifest +37 -0
  53. package/mcp/engine/bevel.js +265 -0
  54. package/mcp/engine/camera.js +76 -0
  55. package/mcp/engine/character.js +1019 -0
  56. package/mcp/engine/check.js +83 -0
  57. package/mcp/engine/csg.js +342 -0
  58. package/mcp/engine/edit.js +48 -0
  59. package/mcp/engine/galaxy.js +265 -0
  60. package/mcp/engine/gl.js +798 -0
  61. package/mcp/engine/gpu.js +1356 -0
  62. package/mcp/engine/index.js +48 -0
  63. package/mcp/engine/instances.js +41 -0
  64. package/mcp/engine/joints.js +355 -0
  65. package/mcp/engine/kernel-bytes.js +2 -0
  66. package/mcp/engine/kernel.js +82 -0
  67. package/mcp/engine/lathe.js +87 -0
  68. package/mcp/engine/material.js +19 -0
  69. package/mcp/engine/mesh.js +131 -0
  70. package/mcp/engine/order.js +125 -0
  71. package/mcp/engine/pick.js +85 -0
  72. package/mcp/engine/place.js +17 -0
  73. package/mcp/engine/planet.js +376 -0
  74. package/mcp/engine/rig.js +417 -0
  75. package/mcp/engine/saw.js +121 -0
  76. package/mcp/engine/sky.js +428 -0
  77. package/mcp/engine/svg.js +239 -0
  78. package/mcp/engine/text.js +231 -0
  79. package/mcp/engine/triangulate.js +72 -0
  80. package/mcp/engine/types.js +2 -0
  81. package/mcp/engine/vec.js +22 -0
  82. package/mcp/engine/version.js +7 -0
  83. package/mcp/engine/vrtsh.js +354 -0
  84. package/mcp/engine/wire.js +346 -0
  85. package/mcp/http.js +292 -0
  86. package/mcp/live.js +95 -0
  87. package/mcp/package.json +10 -0
  88. package/mcp/scene.js +1027 -0
  89. package/mcp/serve.js +87 -0
  90. package/mcp/server.js +97 -0
  91. package/media/face-of-spider.png +0 -0
  92. package/media/spider-paint-2015.png +0 -0
  93. package/media/spider-web.png +0 -0
  94. package/models/deepsky-lark.scene.json +1 -0
  95. package/models/deepsky.scene.json +1 -0
  96. package/models/globe.scene.json +1 -0
  97. package/models/lark-4.scene.json +1 -0
  98. package/models/lark.game.json +14 -0
  99. package/models/spider-build-v2.md +215 -0
  100. package/models/spider-build-v2.mjs +355 -0
  101. package/models/spider-build-v2.schema.json +1001 -0
  102. package/nginx.conf +12 -0
  103. package/package.json +45 -4
  104. package/player.html +274 -0
  105. package/sky.html +133 -0
  106. package/sky.md +285 -0
  107. package/src/demo.js +92 -0
  108. package/src/emulator/devices.js +22 -0
  109. package/src/emulator/xr.js +362 -0
  110. package/src/math.js +77 -0
  111. package/sw.js +37 -0
  112. package/xr-compare.html +332 -0
  113. package/xr-test.html +248 -0
@@ -0,0 +1,1019 @@
1
+ // Characters: a stylized low-poly figure made from a few numbers, for many quick, animatable extras.
2
+ //
3
+ // A character is a spec (`CharacterSpec`, versioned, plain JSON): a base figure (female or male), body sliders (height,
4
+ // build, shoulders, head), a face (shape, jaw, nose, skin), hair, glasses, beard, an outfit and one prop. buildCharacter()
5
+ // turns it into a few meshes with stable ids and a rig with the humanoid joints (rig.ts: HUMANOID_JOINTS), so posed(),
6
+ // walkPose() and HUMANOID_POSES move it like any figure. The same spec always gives the same figure.
7
+ //
8
+ // The look: about six heads tall, a big round head, a slim neck, long legs, hands a little large; the female base an
9
+ // hourglass (hips as wide as the shoulders, a narrow waist, a soft bust), the male a V (wide shoulders and chest,
10
+ // narrow hips). The meshes are lofts of rings with the loops a modeller would put there (extra loops at the knees and
11
+ // elbows, the trunk 12 round, the limbs 8), so they bend cleanly; smooth shading is meant (the renderers' `smooth`).
12
+ // `body` is ONE closed surface (trunk, neck, both legs and feet, branching at the crotch), `arms` both arms with their
13
+ // hands, `head` the head, `face` the eyes, brows, mouth, nose and ears as thin plates lying just over the skin (like a
14
+ // face drawn on with 5 + V in the viewer), `hair` flat locks (thin ribbons) and a cap, with the beard, `gear` what is
15
+ // worn on top (glasses, a coat's skirt, straps, a belt, an astronaut's helmet and pack), `prop` the thing in the right hand.
16
+ // The body and the arms bend smoothly: a point near a joint is shared by the bones on both sides of it (blended weights).
17
+ //
18
+ // There are no colours in a spec: every face names a palette material (`face.mat`, the engine's material model; its
19
+ // colour is only the fallback). CHARACTER_MATERIALS lists the ones a character uses, the spec picks skin, hair and cloth
20
+ // by material name, so a palette edit restyles every character made of it, and any palette entry can be chosen.
21
+ // Clothes are the body's own faces in cloth materials (a sleeve is the arm's surface, so it can never come off), plus a
22
+ // little gear for the shapes cloth adds (a coat's skirt, straps, a belt, a helmet).
23
+ //
24
+ // Y is up, the figure stands on y = 0 and looks to +z, its left is +x (as rig.ts expects).
25
+ import { add, sub, scale, dot, cross, norm } from './vec.js';
26
+ import { HUMANOID_JOINTS } from './rig.js';
27
+ export const CHARACTER_VERSION = 3;
28
+ /** The materials characters are made of (palette entries: add the missing ones to a palette). */
29
+ export const CHARACTER_MATERIALS = {
30
+ 'skin-1': { color: '#f4d6c0', rough: 0.6, soft: 0.7 },
31
+ 'skin-2': { color: '#e9bd9c', rough: 0.6, soft: 0.7 },
32
+ 'skin-3': { color: '#d8a680', rough: 0.6, soft: 0.7 },
33
+ 'skin-4': { color: '#c28c63', rough: 0.6, soft: 0.7 },
34
+ 'skin-5': { color: '#a16f49', rough: 0.6, soft: 0.7 },
35
+ 'skin-6': { color: '#805337', rough: 0.6, soft: 0.7 },
36
+ 'skin-7': { color: '#5f3b26', rough: 0.6, soft: 0.7 },
37
+ 'hair-black': { color: '#1f1b1a', rough: 0.5, soft: 0.2 },
38
+ 'hair-brown': { color: '#4a3020', rough: 0.5, soft: 0.2 },
39
+ 'hair-chestnut': { color: '#7a4b2a', rough: 0.5, soft: 0.2 },
40
+ 'hair-auburn': { color: '#9a4426', rough: 0.5, soft: 0.2 },
41
+ 'hair-blond': { color: '#cfa868', rough: 0.5, soft: 0.2 },
42
+ 'hair-grey': { color: '#9c9a96', rough: 0.5, soft: 0.2 },
43
+ 'hair-white': { color: '#e2e0da', rough: 0.5, soft: 0.2 },
44
+ 'lab-white': { color: '#ecebe5', rough: 0.85, soft: 0.2 },
45
+ 'shirt-white': { color: '#dcdad2', rough: 0.9, soft: 0.2 },
46
+ 'crew-beige': { color: '#d9cdb2', rough: 0.9, soft: 0.2 },
47
+ 'denim': { color: '#3f5a86', rough: 0.95, soft: 0.1 },
48
+ 'navy': { color: '#2a3550', rough: 0.9, soft: 0.1 },
49
+ 'olive': { color: '#5f6e46', rough: 0.95, soft: 0.1 },
50
+ 'khaki': { color: '#a89a72', rough: 0.95, soft: 0.1 },
51
+ 'brown-canvas': { color: '#6b4e33', rough: 0.95, soft: 0.1 },
52
+ 'charcoal': { color: '#34363b', rough: 0.9, soft: 0.1 },
53
+ 'rust': { color: '#b4552f', rough: 0.9, soft: 0.1 },
54
+ 'mustard': { color: '#d0a63a', rough: 0.9, soft: 0.1 },
55
+ 'teal': { color: '#2f7a7c', rough: 0.9, soft: 0.1 },
56
+ 'plum': { color: '#6a3a63', rough: 0.9, soft: 0.1 },
57
+ 'suit-white': { color: '#e8e8e4', rough: 0.75, soft: 0.1 },
58
+ 'suit-grey': { color: '#8d9096', rough: 0.7 },
59
+ 'suit-orange': { color: '#d8692c', rough: 0.8, soft: 0.1 },
60
+ 'leather': { color: '#3a2a1e', rough: 0.6 },
61
+ 'rubber': { color: '#26272a', rough: 0.85 },
62
+ 'eye': { color: '#1a1512', rough: 0.15 },
63
+ 'eye-white': { color: '#f4f1ea', rough: 0.3 },
64
+ 'mouth': { color: '#8a4a42', rough: 0.6, soft: 0.4 },
65
+ 'lens': { color: '#cfe6f0', metal: 0.2, rough: 0.05, alpha: 0.3 },
66
+ 'frame': { color: '#1a1a1c', rough: 0.4 },
67
+ 'visor': { color: '#d9a640', metal: 0.9, rough: 0.12, alpha: 0.55 },
68
+ 'screen': { color: '#5fc8e8', rough: 0.3, emit: 0.8 },
69
+ 'plastic': { color: '#2b2d33', rough: 0.45 },
70
+ 'steel': { color: '#9aa7b4', metal: 1, rough: 0.3 },
71
+ 'brass': { color: '#c9a24a', metal: 1, rough: 0.3 },
72
+ };
73
+ const MATS = CHARACTER_MATERIALS;
74
+ /** The material choices offered for skin, hair and cloth (any palette name works too). */
75
+ export const CHARACTER_SKINS = Object.keys(MATS).filter((n) => n.startsWith('skin-'));
76
+ export const CHARACTER_HAIRS = Object.keys(MATS).filter((n) => n.startsWith('hair-'));
77
+ export const CHARACTER_CLOTHS = ['lab-white', 'shirt-white', 'crew-beige', 'denim', 'navy', 'olive', 'khaki', 'brown-canvas', 'charcoal', 'rust', 'mustard', 'teal', 'plum', 'suit-white', 'suit-grey', 'suit-orange', 'leather'];
78
+ /** The palette entries characters use, as { name, ...material } (the form a scene file's `palette` has). */
79
+ export const characterPalette = () => Object.entries(MATS).map(([name, m]) => ({ name, metal: 0, rough: 0.7, alpha: 1, emit: 0, ...m }));
80
+ /** The slider ranges in which the poses and the clothes still fit. */
81
+ export const CHARACTER_RANGES = {
82
+ height: [1.45, 2.05], build: [-1, 1], shoulders: [-1, 1], head: [0.85, 1.4], jaw: [-1, 1], nose: [-1, 1],
83
+ };
84
+ export const FACE_SHAPES = ['oval', 'round', 'square', 'long'];
85
+ export const HAIR_STYLES = ['short', 'long', 'bun', 'bald'];
86
+ export const BEARD_STYLES = ['none', 'full', 'goatee'];
87
+ export const OUTFITS = ['coat', 'overall', 'workwear', 'crew', 'astronaut'];
88
+ export const PROPS = ['none', 'tablet', 'wrench', 'commlock'];
89
+ /** the parts, in the order buildCharacter() returns them (missing ones are left out) */
90
+ export const CHARACTER_PARTS = ['body', 'arms', 'head', 'face', 'hair', 'gear', 'prop'];
91
+ export const CHARACTER_PRESETS = {
92
+ scientist: {
93
+ version: 3, role: 'scientist', base: 'male', seed: 11,
94
+ body: { height: 1.76, build: -0.3, shoulders: -0.2, head: 1 },
95
+ face: { shape: 'long', jaw: -0.2, nose: 0.2, skin: 'skin-2' },
96
+ hair: { style: 'short', mat: 'hair-brown' }, glasses: true, beard: 'none',
97
+ outfit: { kind: 'coat', main: 'lab-white', second: 'charcoal', helmet: true }, prop: 'tablet',
98
+ },
99
+ mechanic: {
100
+ version: 3, role: 'mechanic', base: 'female', seed: 23,
101
+ body: { height: 1.64, build: 0.1, shoulders: 0, head: 1 },
102
+ face: { shape: 'round', jaw: 0, nose: 0, skin: 'skin-4' },
103
+ hair: { style: 'bun', mat: 'hair-black' }, glasses: false, beard: 'none',
104
+ outfit: { kind: 'overall', main: 'denim', second: 'shirt-white', helmet: true }, prop: 'wrench',
105
+ },
106
+ crew: {
107
+ version: 3, role: 'crew', base: 'female', seed: 37,
108
+ body: { height: 1.7, build: -0.2, shoulders: 0, head: 1 },
109
+ face: { shape: 'oval', jaw: -0.3, nose: -0.2, skin: 'skin-1' },
110
+ hair: { style: 'long', mat: 'hair-chestnut' }, glasses: false, beard: 'none',
111
+ outfit: { kind: 'crew', main: 'crew-beige', second: 'rust', helmet: true }, prop: 'commlock',
112
+ },
113
+ astronaut: {
114
+ version: 3, role: 'astronaut', base: 'male', seed: 51,
115
+ body: { height: 1.8, build: 0.1, shoulders: 0.3, head: 1 },
116
+ face: { shape: 'square', jaw: 0.3, nose: 0, skin: 'skin-3' },
117
+ hair: { style: 'short', mat: 'hair-black' }, glasses: false, beard: 'none',
118
+ outfit: { kind: 'astronaut', main: 'suit-white', second: 'suit-grey', helmet: true }, prop: 'none',
119
+ },
120
+ };
121
+ const clamp = (v, [lo, hi], d) => (typeof v === 'number' && Number.isFinite(v) ? Math.min(hi, Math.max(lo, v)) : d);
122
+ const pick = (v, list, d) => (list.includes(v) ? v : d);
123
+ const rgb = (h) => [1, 3, 5].map((i) => parseInt(h.slice(i, i + 2), 16));
124
+ /** A material name; an old spec's #rrggbb colour becomes the nearest material of the group. */
125
+ const matName = (v, group, d) => {
126
+ if (typeof v !== 'string')
127
+ return d;
128
+ if (/^#[0-9a-f]{6}$/i.test(v)) {
129
+ const c = rgb(v);
130
+ let best = d, far = Infinity;
131
+ for (const n of group) {
132
+ const e = rgb(MATS[n].color).reduce((s, x, i) => s + (x - c[i]) ** 2, 0);
133
+ if (e < far)
134
+ ((far = e), (best = n));
135
+ }
136
+ return best;
137
+ }
138
+ return /^[\w .+-]{1,48}$/.test(v) ? v : d;
139
+ };
140
+ /** A complete, valid spec from anything (missing or bad fields take the defaults; values are clamped; older specs are brought up: colours become materials, curly hair long, a tomato nothing). */
141
+ export const normalizeCharacter = (s = {}) => {
142
+ const R = CHARACTER_RANGES;
143
+ const base = s.base === 'male' ? 'male' : 'female';
144
+ const kind = pick(s.outfit?.kind, OUTFITS, 'crew');
145
+ return {
146
+ version: CHARACTER_VERSION,
147
+ ...(typeof s.role === 'string' ? { role: s.role } : {}),
148
+ base,
149
+ body: { height: clamp(s.body?.height, R.height, base === 'male' ? 1.78 : 1.66), build: clamp(s.body?.build, R.build, 0), shoulders: clamp(s.body?.shoulders, R.shoulders, 0), head: clamp(s.body?.head, R.head, 1) },
150
+ face: { shape: pick(s.face?.shape, FACE_SHAPES, 'oval'), jaw: clamp(s.face?.jaw, R.jaw, 0), nose: clamp(s.face?.nose, R.nose, 0), skin: matName(s.face?.skin, CHARACTER_SKINS, 'skin-2') },
151
+ hair: { style: s.hair?.style === 'curly' ? 'long' : pick(s.hair?.style, HAIR_STYLES, 'short'), mat: matName(s.hair?.mat ?? s.hair?.color, CHARACTER_HAIRS, 'hair-brown') },
152
+ glasses: Boolean(s.glasses),
153
+ beard: pick(s.beard, BEARD_STYLES, 'none'),
154
+ outfit: {
155
+ kind,
156
+ main: matName(s.outfit?.main ?? s.outfit?.color, CHARACTER_CLOTHS, kind === 'astronaut' ? 'suit-white' : kind === 'coat' ? 'lab-white' : kind === 'crew' ? 'crew-beige' : 'olive'),
157
+ second: matName(s.outfit?.second ?? s.outfit?.color2, CHARACTER_CLOTHS, kind === 'astronaut' ? 'suit-grey' : kind === 'crew' ? 'mustard' : 'charcoal'),
158
+ helmet: s.outfit?.helmet !== false,
159
+ },
160
+ prop: pick(s.prop, PROPS, 'none'),
161
+ seed: Number.isInteger(s.seed) ? s.seed : 1,
162
+ };
163
+ };
164
+ // a small seeded random (mulberry32)
165
+ const rng = (seed) => {
166
+ let a = seed >>> 0;
167
+ return () => {
168
+ a = (a + 0x6d2b79f5) >>> 0;
169
+ let t = a;
170
+ t = Math.imul(t ^ (t >>> 15), t | 1);
171
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
172
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
173
+ };
174
+ };
175
+ /**
176
+ * Another person in the same role: a different face, hair, build, skin and hair materials (from `seed`); the outfit's
177
+ * kind and the prop stay, and so does the main cloth of a uniform (a crew tunic, a lab coat, a suit; a crew member's
178
+ * sleeve, the department, may change).
179
+ */
180
+ export const variateCharacter = (spec, seed) => {
181
+ const s = normalizeCharacter(spec);
182
+ const r = rng(seed * 2654435761);
183
+ const any = (l) => l[Math.floor(r() * l.length)];
184
+ const span = (lo, hi) => lo + r() * (hi - lo);
185
+ const base = r() < 0.5 ? 'female' : 'male';
186
+ const R = CHARACTER_RANGES;
187
+ const uniform = s.outfit.kind === 'coat' || s.outfit.kind === 'astronaut' || s.outfit.kind === 'crew';
188
+ const keepMain = uniform || r() < 0.5;
189
+ const work = CHARACTER_CLOTHS.filter((c) => !c.startsWith('suit') && c !== 'lab-white' && c !== 'crew-beige');
190
+ const dept = ['mustard', 'rust', 'plum', 'teal', 'charcoal', 'shirt-white', 'olive'];
191
+ return normalizeCharacter({
192
+ ...s,
193
+ base,
194
+ seed,
195
+ body: { height: span(base === 'male' ? 1.66 : 1.56, base === 'male' ? 1.94 : 1.8), build: span(-0.9, 1), shoulders: span(-0.7, 0.8), head: span(0.95, 1.12) },
196
+ face: { shape: any(FACE_SHAPES), jaw: span(R.jaw[0], R.jaw[1]) * 0.55 + (base === 'male' ? 0.3 : -0.2), nose: span(-0.8, 0.9), skin: any(CHARACTER_SKINS) },
197
+ hair: { style: any(base === 'male' ? ['short', 'short', 'bald', 'long'] : ['short', 'long', 'long', 'bun']), mat: any(CHARACTER_HAIRS) },
198
+ glasses: r() < 0.3,
199
+ beard: base === 'male' ? any(BEARD_STYLES) : 'none',
200
+ outfit: { ...s.outfit, main: keepMain ? s.outfit.main : any(work), second: s.outfit.kind === 'crew' ? any(dept) : s.outfit.kind === 'astronaut' || r() < 0.5 ? s.outfit.second : any(work) },
201
+ });
202
+ };
203
+ // ---------- the mesh builder ----------
204
+ // Points with their weights and faces with their materials. Faces may be built in any winding: finish() makes every
205
+ // closed piece wind one way, outwards.
206
+ class Build {
207
+ P = [];
208
+ W = [];
209
+ F = [];
210
+ pt(p, w) {
211
+ this.P.push(p);
212
+ this.W.push(w);
213
+ return this.P.length - 1;
214
+ }
215
+ ring(pts, w) {
216
+ return pts.map((p, k) => this.pt(p, typeof w === 'function' ? w(p, k) : w));
217
+ }
218
+ tri(a, b, c, mat) {
219
+ this.F.push({ v: [a, b, c], mat });
220
+ }
221
+ /** triangles between two rings of the same length (wrap: the last point joins the first) */
222
+ band(A, B, mat, wrap = true) {
223
+ const n = A.length;
224
+ for (let k = 0; k < (wrap ? n : n - 1); k++) {
225
+ const k1 = (k + 1) % n;
226
+ const m = typeof mat === 'string' ? mat : mat(k);
227
+ this.tri(A[k], A[k1], B[k1], m);
228
+ this.tri(A[k], B[k1], B[k], m);
229
+ }
230
+ }
231
+ fan(A, apex, mat) {
232
+ for (let k = 0; k < A.length; k++)
233
+ this.tri(A[k], A[(k + 1) % A.length], apex, mat);
234
+ }
235
+ /** a rigid closed shell on one weight set: points and polygon faces (planar ones only: a rigid piece stays planar) */
236
+ shell(pts, faces, mat, w) {
237
+ const o = this.P.length;
238
+ for (const p of pts)
239
+ this.pt(p, w);
240
+ faces.forEach((f, i) => this.F.push({ v: f.map((k) => k + o), mat: typeof mat === 'string' ? mat : mat(i) }));
241
+ }
242
+ /** a thin flat plate: a planar polygon `poly` (in order round), `thick` behind it along -n; both faces n-gons, the rim quads */
243
+ plate(poly, n, thick, mat, w) {
244
+ const back = poly.map((p) => sub(p, scale(n, thick)));
245
+ const k = poly.length;
246
+ const faces = [poly.map((_, i) => i), back.map((_, i) => k + i)];
247
+ for (let i = 0; i < k; i++)
248
+ faces.push([i, (i + 1) % k, k + ((i + 1) % k), k + i]);
249
+ this.shell([...poly, ...back], faces, mat, w);
250
+ }
251
+ /**
252
+ * a thin ribbon (a lock of hair): rows of [left, right] points along it, `thick` towards -n of each row; the front and the
253
+ * back are triangle strips, the rim closes it. Rows may be any width (a pointed end is a row of two near points).
254
+ */
255
+ ribbon(rows, thick, mat, w) {
256
+ const n = rows.length;
257
+ const normals = rows.map(([l, r], i) => {
258
+ const along = sub(rows[Math.min(n - 1, i + 1)][0], rows[Math.max(0, i - 1)][0]);
259
+ const nn = norm(cross(sub(r, l), along));
260
+ return nn;
261
+ });
262
+ const front = rows.map(([l, r]) => [this.pt(l, w), this.pt(r, w)]);
263
+ const back = rows.map(([l, r], i) => [this.pt(sub(l, scale(normals[i], thick)), w), this.pt(sub(r, scale(normals[i], thick)), w)]);
264
+ for (let i = 0; i < n - 1; i++) {
265
+ const [a, b] = front[i], [c, d] = front[i + 1];
266
+ this.tri(a, b, d, mat);
267
+ this.tri(a, d, c, mat);
268
+ const [e, f] = back[i], [g, h] = back[i + 1];
269
+ this.tri(e, h, f, mat);
270
+ this.tri(e, g, h, mat);
271
+ // the two sides
272
+ this.tri(a, c, g, mat);
273
+ this.tri(a, g, e, mat);
274
+ this.tri(b, h, d, mat);
275
+ this.tri(b, f, h, mat);
276
+ }
277
+ // the ends
278
+ const [a0, b0] = front[0], [e0, f0] = back[0];
279
+ this.tri(a0, e0, f0, mat);
280
+ this.tri(a0, f0, b0, mat);
281
+ const [a1, b1] = front[n - 1], [e1, f1] = back[n - 1];
282
+ this.tri(a1, b1, f1, mat);
283
+ this.tri(a1, f1, e1, mat);
284
+ }
285
+ /** one winding for every connected piece, outwards (by its signed volume) */
286
+ finish(color) {
287
+ const { P, F } = this;
288
+ const edges = new Map();
289
+ const key = (a, b) => (a < b ? `${a},${b}` : `${b},${a}`);
290
+ F.forEach((f, i) => f.v.forEach((a, j) => {
291
+ const k = key(a, f.v[(j + 1) % f.v.length]);
292
+ const l = edges.get(k);
293
+ if (l)
294
+ l.push(i);
295
+ else
296
+ edges.set(k, [i]);
297
+ }));
298
+ const has = (v, a, b) => v.some((x, j) => x === a && v[(j + 1) % v.length] === b);
299
+ const done = new Uint8Array(F.length);
300
+ for (let s = 0; s < F.length; s++) {
301
+ if (done[s])
302
+ continue;
303
+ done[s] = 1;
304
+ const stack = [s], comp = [];
305
+ while (stack.length) {
306
+ const f = stack.pop();
307
+ comp.push(f);
308
+ const v = F[f].v;
309
+ for (let j = 0; j < v.length; j++) {
310
+ const a = v[j], b = v[(j + 1) % v.length];
311
+ for (const g of edges.get(key(a, b))) {
312
+ if (done[g])
313
+ continue;
314
+ if (has(F[g].v, a, b))
315
+ F[g].v.reverse();
316
+ done[g] = 1;
317
+ stack.push(g);
318
+ }
319
+ }
320
+ }
321
+ let vol = 0;
322
+ for (const f of comp) {
323
+ const q = F[f].v.map((i) => P[i]);
324
+ for (let j = 1; j < q.length - 1; j++)
325
+ vol += dot(q[0], cross(q[j], q[j + 1]));
326
+ }
327
+ if (vol < 0)
328
+ for (const f of comp)
329
+ F[f].v.reverse();
330
+ }
331
+ const r5 = (v) => Math.round(v * 1e5) / 1e5;
332
+ const faces = F.map((f) => ({ v: f.v, color: color(f.mat), mat: f.mat }));
333
+ return { mesh: { positions: P.map((p) => p.map(r5)), faces }, w: this.W };
334
+ }
335
+ }
336
+ // rigid closed shells (points + faces), placed by the caller
337
+ const boxShape = (c, [hx, hy, hz], rotY = 0, rotX = 0, taper = 1) => {
338
+ const raw = [];
339
+ for (const y of [-1, 1])
340
+ for (const z of [-1, 1])
341
+ for (const x of [-1, 1])
342
+ raw.push([x * hx * (y > 0 ? taper : 1), y * hy, z * hz * (y > 0 ? taper : 1)]);
343
+ const pts = raw.map(([x, y, z]) => {
344
+ const y1 = y * Math.cos(rotX) - z * Math.sin(rotX), z1 = y * Math.sin(rotX) + z * Math.cos(rotX);
345
+ return add(c, [x * Math.cos(rotY) + z1 * Math.sin(rotY), y1, -x * Math.sin(rotY) + z1 * Math.cos(rotY)]);
346
+ });
347
+ return [pts, [[0, 1, 3, 2], [4, 6, 7, 5], [0, 4, 5, 1], [2, 3, 7, 6], [0, 2, 6, 4], [1, 5, 7, 3]]];
348
+ };
349
+ /** a faceted ellipsoid; triangles at the poles, quads (planar: rings are level) between */
350
+ const blobShape = (c, [rx, ry, rz], seg = 8, rings = 5) => {
351
+ const pts = [add(c, [0, ry, 0])];
352
+ for (let i = 1; i < rings; i++)
353
+ for (let j = 0; j < seg; j++) {
354
+ const th = (Math.PI * i) / rings, ph = (2 * Math.PI * (j + 0.5)) / seg;
355
+ pts.push(add(c, [rx * Math.sin(th) * Math.cos(ph), ry * Math.cos(th), rz * Math.sin(th) * Math.sin(ph)]));
356
+ }
357
+ pts.push(add(c, [0, -ry, 0]));
358
+ const faces = [];
359
+ const R = (i, j) => 1 + (i - 1) * seg + (j % seg);
360
+ for (let j = 0; j < seg; j++)
361
+ faces.push([0, R(1, j + 1), R(1, j)]);
362
+ for (let i = 1; i < rings - 1; i++)
363
+ for (let j = 0; j < seg; j++)
364
+ faces.push([R(i, j), R(i, j + 1), R(i + 1, j + 1)], [R(i, j), R(i + 1, j + 1), R(i + 1, j)]);
365
+ for (let j = 0; j < seg; j++)
366
+ faces.push([R(rings - 1, j), R(rings - 1, j + 1), pts.length - 1]);
367
+ return [pts, faces];
368
+ };
369
+ /** a tube from a to b (n sides), radius ra at a and rb at b, closed */
370
+ const tubeShape = (a, b, ra, rb, n = 6) => {
371
+ const u = norm(sub(b, a));
372
+ const ref = Math.abs(u[1]) > 0.9 ? [0, 0, 1] : [0, 1, 0];
373
+ const X = norm(cross(u, ref)), Z = cross(X, u);
374
+ const ring = (c, r) => Array.from({ length: n }, (_, k) => {
375
+ const t = ((k + 0.5) / n) * Math.PI * 2;
376
+ return add(c, add(scale(X, Math.cos(t) * r), scale(Z, Math.sin(t) * r)));
377
+ });
378
+ const pts = [...ring(a, ra), ...ring(b, rb)];
379
+ const faces = [];
380
+ for (let k = 0; k < n; k++)
381
+ faces.push([k, (k + 1) % n, n + ((k + 1) % n)], [k, n + ((k + 1) % n), n + k]);
382
+ faces.push(Array.from({ length: n }, (_, k) => k), Array.from({ length: n }, (_, k) => n + k));
383
+ return [pts, faces];
384
+ };
385
+ const lerp = (a, b, t) => [a[0] + (b[0] - a[0]) * t, a[1] + (b[1] - a[1]) * t, a[2] + (b[2] - a[2]) * t];
386
+ /** a smooth bump 0..1..0 over [a, b] (for pushing a ring out over a few rings) */
387
+ const bump = (t, a, b) => (t <= a || t >= b ? 0 : 0.5 - 0.5 * Math.cos((2 * Math.PI * (t - a)) / (b - a)));
388
+ /** The figure's measures for a spec: the joints and the sizes every part is built from (cloth bulk included). */
389
+ const measures = (s) => {
390
+ const H = s.body.height, b = s.body.build, f = s.base === 'female', sw = s.body.shoulders;
391
+ const kind = s.outfit.kind;
392
+ const suit = kind === 'astronaut';
393
+ const fat = 1 + 0.26 * b; // thickness of the limbs
394
+ const belly = 1 + 0.45 * Math.max(0, b) - 0.1 * Math.max(0, -b);
395
+ // cloth over the body: the trunk, the limbs, the feet
396
+ const tb = suit ? 1.15 : kind === 'coat' ? 1.04 : kind === 'workwear' ? 1.035 : 1.01;
397
+ const lb = suit ? 1.22 : kind === 'coat' ? 1.05 : kind === 'workwear' ? 1.04 : 1.015;
398
+ const fb = suit ? 1.22 : 1.05;
399
+ // half widths (x) and half depths (z) of the trunk; the female an hourglass, the male a V
400
+ const sh = (f ? 0.108 : 0.136) * H * (1 + 0.11 * sw) * (1 + 0.05 * b) * (suit ? 1.08 : 1);
401
+ const chest = (f ? 0.082 : 0.104) * H * (1 + 0.09 * b) * (1 + 0.05 * sw);
402
+ const waist = (f ? 0.057 : 0.082) * H * belly;
403
+ const hip = (f ? 0.11 : 0.088) * H * (1 + 0.13 * b);
404
+ const dChest = (f ? 0.052 : 0.066) * H * (1 + 0.14 * b), dWaist = (f ? 0.045 : 0.058) * H * belly, dHip = (f ? 0.064 : 0.055) * H * (1 + 0.14 * b);
405
+ const neck = (f ? 0.02 : 0.027) * H * (1 + 0.12 * b);
406
+ const armR = (f ? 0.021 : 0.027) * H * fat * lb; // the upper arm
407
+ const thigh = (f ? 0.056 : 0.05) * H * fat * lb, knee = (f ? 0.035 : 0.037) * H * fat * lb, calf = (f ? 0.04 : 0.042) * H * fat * lb, ankle = (f ? 0.023 : 0.026) * H * fat * lb;
408
+ const hand = (f ? 0.95 : 1.02) * H * (suit ? 1.25 : 1);
409
+ const hh = 0.162 * H * s.body.head; // the head, chin to crown (about six heads tall)
410
+ const y = (k) => k * H;
411
+ const legX = hip * (f ? 0.5 : 0.54);
412
+ const shX = sh - armR * 1.0;
413
+ const wristX = Math.max(shX + 0.03 * H, hip * tb + armR * 0.9 + 0.012 * H, waist * tb * 1.1 + armR + 0.035 * H);
414
+ const J = {
415
+ root: [0, y(0.53), 0],
416
+ spine: [0, y(0.66), -0.005 * H],
417
+ head: [0, y(0.852), -0.004 * H],
418
+ shoulderL: [shX, y(0.8), -0.006 * H],
419
+ elbowL: [(shX + wristX) / 2 + 0.006 * H, y(0.625), -0.014 * H],
420
+ wristL: [wristX, y(0.49), 0.006 * H],
421
+ hipL: [legX, y(0.505), 0],
422
+ kneeL: [legX * 0.92, y(0.275), 0.006 * H],
423
+ ankleL: [legX * 0.88, y(0.05), -0.004 * H],
424
+ };
425
+ for (const n of ['shoulder', 'elbow', 'wrist', 'hip', 'knee', 'ankle']) {
426
+ const p = J[`${n}L`];
427
+ J[`${n}R`] = [-p[0], p[1], p[2]];
428
+ }
429
+ return { H, f, b, fat, tb, lb, fb, sh, chest, waist, hip, dChest, dWaist, dHip, neck, armR, thigh, knee, calf, ankle, hand, hh, J, y, legX, suit, flare: kind === 'crew' };
430
+ };
431
+ /** Which material each region of the body and the arms is, for the outfit (L / R suffixes for one side only). */
432
+ const lookOf = (s) => {
433
+ const skin = s.face.skin, { kind, main, second } = s.outfit;
434
+ const legs = { thigh: second, knee: second, shin: second, foot: 'leather' };
435
+ if (kind === 'coat')
436
+ return { pelvis: second, belt: second, belly: main, chest: main, vee: second, shoulder: main, collar: main, neck: skin, ...legs, upper: main, elbow: main, fore: main, cuff: main, hand: skin };
437
+ if (kind === 'overall')
438
+ return { pelvis: main, belt: main, belly: main, bib: main, chest: second, vee: second, shoulder: second, collar: second, neck: skin, thigh: main, knee: main, shin: main, foot: 'leather', upper: second, elbow: skin, fore: skin, cuff: skin, hand: skin };
439
+ if (kind === 'astronaut')
440
+ return { pelvis: main, belt: second, belly: main, chest: main, vee: main, shoulder: main, collar: second, neck: second, thigh: main, knee: second, shin: main, foot: second, upper: main, elbow: second, fore: main, cuff: second, hand: second };
441
+ // the crew tunic: beige with the left sleeve in the department's colour, a round black collar, a black belt
442
+ if (kind === 'crew')
443
+ return { pelvis: main, belt: 'charcoal', belly: main, chest: main, vee: main, shoulder: main, collar: 'charcoal', neck: skin, thigh: main, knee: main, shin: main, foot: 'leather', upper: main, elbow: main, fore: main, cuff: main, hand: skin, upperL: second, elbowL: second, foreL: second, cuffL: second, shoulderL: second };
444
+ return { pelvis: second, belt: 'leather', belly: main, chest: main, vee: main, shoulder: main, collar: main, neck: skin, ...legs, upper: main, elbow: main, fore: main, cuff: second, hand: skin };
445
+ };
446
+ // ---------- the body: trunk, neck, legs and feet as one surface ----------
447
+ // The trunk's rings have 12 points (k = 0 at the left side, 3 in front, 6 at the right, 9 at the back). At the crotch the
448
+ // lowest ring splits: its left half, the front and back middle points and a crotch point make the left leg's first ring
449
+ // (8 points), the right half the right leg's.
450
+ const bodyMesh = (B, s, m, look, id) => {
451
+ const { H, f, b, tb, hip, waist, chest, sh, dChest, dWaist, dHip, neck, thigh, knee, calf, ankle, fb, J, y } = m;
452
+ const bt = Math.min(tb, 1.05); // trousers are thinner than a suit's trunk
453
+ const bust = f ? 0.028 * H * (1 + 0.25 * Math.max(0, b)) : 0.006 * H;
454
+ const glute = (f ? 0.018 : 0.01) * H;
455
+ const tummy = 0.03 * H * Math.max(0, b);
456
+ const R = (j) => id[j];
457
+ // a trunk ring: an ellipse pushed out in front (the bust, a belly) and behind (the seat); squareFront flattens the chest
458
+ const ring12 = (r) => B.ring(Array.from({ length: 12 }, (_, k) => {
459
+ const t = (k * Math.PI) / 6;
460
+ const c = Math.cos(t), sn = Math.sin(t);
461
+ let z = sn * r.rz + (r.z ?? 0);
462
+ if (k === 2 || k === 4)
463
+ z += (r.front ?? 0);
464
+ if (k === 3)
465
+ z += r.frontMid ?? r.front ?? 0;
466
+ if (k === 8 || k === 10)
467
+ z += -(r.back ?? 0) * 0.8;
468
+ if (k === 9)
469
+ z += -(r.back ?? 0);
470
+ if (r.squareFront && (k === 2 || k === 4))
471
+ z += r.squareFront * r.rz; // the chest's front is flatter and wider
472
+ return [c * r.rx * (r.squareFront && (k === 2 || k === 4) ? 1.08 : 1), r.y, z];
473
+ }), r.w);
474
+ const root = [[R('root'), 1]], spine = [[R('spine'), 1]];
475
+ const mix = (a) => [[R('root'), 1 - a], [R('spine'), a]];
476
+ const sq = f ? 0 : 0.12;
477
+ const rings = {
478
+ c: ring12({ y: y(0.485), rx: hip * 0.9 * bt, rz: dHip * 0.86 * bt, back: glute * 0.6, w: root }),
479
+ hip: ring12({ y: y(0.53), rx: hip * bt, rz: dHip * bt, back: glute, w: root }),
480
+ hip2: ring12({ y: y(0.572), rx: (f ? hip * 0.9 : hip * 0.9) * bt, rz: dHip * 0.95 * bt, front: tummy * 0.4, back: glute * 0.45, w: mix(0.25) }),
481
+ waist: ring12({ y: y(0.615), rx: waist * tb, rz: dWaist * tb, front: tummy, w: mix(0.55) }),
482
+ under: ring12({ y: y(0.66), rx: (chest * 0.9) * tb, rz: dChest * 0.92 * tb, front: bust * 0.3 + tummy * 0.5, frontMid: bust * 0.1 + tummy * 0.5, squareFront: sq, w: spine }),
483
+ bust: ring12({ y: y(0.7), rx: chest * tb, rz: dChest * tb, front: bust, frontMid: bust * 0.7, squareFront: sq, w: spine }),
484
+ upper: ring12({ y: y(0.745), rx: (f ? chest * 0.98 : Math.max(chest * 1.02, sh * 0.8)) * tb, rz: dChest * 0.96 * tb, front: bust * 0.45, frontMid: bust * 0.3, squareFront: sq, w: spine }),
485
+ shoulder: ring12({ y: y(0.79), rx: sh * (f ? 0.88 : 0.9) * tb, rz: dChest * 0.72 * tb, z: -0.003 * H, front: bust * 0.05, back: -0.005 * H, w: spine }),
486
+ trap: ring12({ y: y(0.818), rx: neck * 2.3 * tb, rz: neck * 1.7 * tb, z: -0.004 * H, w: spine }),
487
+ n0: ring12({ y: y(0.838), rx: neck, rz: neck * 1.05, z: 0.002 * H, w: spine }),
488
+ n1: ring12({ y: y(0.878), rx: neck * 0.94, rz: neck, z: 0.005 * H, w: [[R('spine'), 0.5], [R('head'), 0.5]] }),
489
+ };
490
+ const isFront = (k) => k >= 1 && k <= 4; // the columns between points 1..5 (the middle 120 degrees in front)
491
+ const isVee = (k) => k === 2 || k === 3;
492
+ B.band(rings.c, rings.hip, look.pelvis);
493
+ B.band(rings.hip, rings.hip2, look.pelvis);
494
+ B.band(rings.hip2, rings.waist, look.belt);
495
+ B.band(rings.waist, rings.under, (k) => (look.bib && !isFront(k) ? look.chest : look.belly));
496
+ B.band(rings.under, rings.bust, (k) => (look.bib && isFront(k) ? look.bib : look.chest));
497
+ B.band(rings.bust, rings.upper, (k) => (look.bib && isFront(k) ? look.bib : look.chest));
498
+ B.band(rings.upper, rings.shoulder, (k) => (isVee(k) ? look.vee : look.chest));
499
+ B.band(rings.shoulder, rings.trap, (k) => (isVee(k) ? look.vee : look.shoulder));
500
+ B.band(rings.trap, rings.n0, look.collar);
501
+ B.band(rings.n0, rings.n1, look.neck);
502
+ B.fan(rings.n1, B.pt([0, y(0.886), 0.005 * H], [[R('spine'), 0.5], [R('head'), 0.5]]), look.neck);
503
+ // the legs
504
+ const crotch = B.pt([0, y(0.462), 0.004 * H], root);
505
+ const c = rings.c;
506
+ // the shoe's outline (x across, z forward), in H: a rounded toe, a narrow heel
507
+ const FOOT = [[0.03, 0.01], [0.034, 0.075], [0.022, 0.118], [0.0, 0.13], [-0.022, 0.115], [-0.03, 0.06], [-0.026, -0.02], [-0.012, -0.042], [0.012, -0.042], [0.028, -0.025]];
508
+ for (const [n, side] of [['L', 1], ['R', -1]]) {
509
+ const hipJ = R(`hip${n}`), kneeJ = R(`knee${n}`), ankleJ = R(`ankle${n}`);
510
+ const top = side > 0 ? [c[0], c[1], c[2], c[3], crotch, c[9], c[10], c[11]] : [c[6], c[5], c[4], c[3], crotch, c[9], c[8], c[7]];
511
+ const P = J[`hip${n}`], K = J[`knee${n}`], A = J[`ankle${n}`];
512
+ const centre = (yy) => (yy >= K[1] ? lerp(K, P, (yy - K[1]) / (P[1] - K[1])) : lerp(A, K, (yy - A[1]) / (K[1] - A[1])));
513
+ const ring8 = (yy, rx, rz, dz, w, inward = 0) => {
514
+ const cc = centre(yy);
515
+ return B.ring(Array.from({ length: 8 }, (_, k) => {
516
+ const t = (k * Math.PI) / 4;
517
+ return [cc[0] + side * (Math.cos(t) * rx - inward), yy, cc[2] + dz + Math.sin(t) * rz];
518
+ }), w);
519
+ };
520
+ const wt = (a, ja, jb) => (a >= 1 ? [[ja, 1]] : [[ja, a], [jb, 1 - a]]);
521
+ const fl = m.flare ? 1.35 : 1;
522
+ const t1 = ring8(y(0.445), thigh, thigh * 1.02, 0.004 * H, wt(0.6, hipJ, R('root')), thigh * 0.08);
523
+ const t2 = ring8(y(0.39), thigh * 0.93, thigh * 0.94, 0.004 * H, [[hipJ, 1]]);
524
+ const t3 = ring8(y(0.335), thigh * 0.78, thigh * 0.8, 0.002 * H, wt(0.9, hipJ, kneeJ));
525
+ const k0 = ring8(y(0.3), knee * 1.06, knee * 1.08, 0.002 * H, wt(0.7, hipJ, kneeJ));
526
+ const kn = ring8(y(0.275), knee, knee * 1.06, 0.006 * H, wt(0.5, hipJ, kneeJ));
527
+ const k1 = ring8(y(0.25), knee * 1.02, knee * 1.02, 0, wt(0.7, kneeJ, hipJ));
528
+ const c1 = ring8(y(0.205), calf, calf * 1.08, -0.006 * H, [[kneeJ, 1]]);
529
+ const c2 = ring8(y(0.15), calf * 0.86, calf * 0.9, -0.006 * H, [[kneeJ, 1]]);
530
+ const a1 = ring8(y(0.095), ankle * 1.05 * fl, ankle * 1.1 * fl, -0.002 * H, [[kneeJ, 1]]);
531
+ const a0 = ring8(y(0.058), ankle * 1.0 * fb * fl, ankle * 1.08 * fb * fl, 0, wt(0.5, kneeJ, ankleJ));
532
+ const foot = (yy, k) => B.ring(FOOT.map(([ox, oz]) => [A[0] + side * ox * H * k, yy, A[2] + 0.004 * H + oz * H * k]), [[ankleJ, 1]]);
533
+ const f2 = B.ring(FOOT.map(([ox, oz]) => [A[0] + side * ox * H * 0.75 * fb, y(0.038), A[2] + 0.004 * H + oz * H * 0.8 * fb]), [[ankleJ, 1]]);
534
+ const f1 = foot(y(0.016), 0.98 * fb);
535
+ const f0 = foot(0, fb);
536
+ B.band(top, t1, look.thigh);
537
+ B.band(t1, t2, look.thigh);
538
+ B.band(t2, t3, look.thigh);
539
+ B.band(t3, k0, look.thigh);
540
+ B.band(k0, kn, look.knee);
541
+ B.band(kn, k1, look.knee);
542
+ B.band(k1, c1, look.shin);
543
+ B.band(c1, c2, look.shin);
544
+ B.band(c2, a1, look.shin);
545
+ B.band(a1, a0, m.flare ? look.shin : look.foot);
546
+ B.band(a0, f2, look.foot);
547
+ B.band(f2, f1, look.foot);
548
+ B.band(f1, f0, look.foot);
549
+ B.fan(f0, B.pt([A[0] + side * 0.002 * H, 0, A[2] + 0.004 * H + 0.045 * H * fb], [[ankleJ, 1]]), look.foot === 'leather' ? 'rubber' : look.foot);
550
+ }
551
+ };
552
+ // ---------- the arms and hands ----------
553
+ const armsMesh = (B, s, m, look, id) => {
554
+ const { H, armR, hand, J } = m;
555
+ const R = (j) => id[j];
556
+ for (const [n, side] of [['L', 1], ['R', -1]]) {
557
+ const S = J[`shoulder${n}`], E = J[`elbow${n}`], W = J[`wrist${n}`];
558
+ const spine = R('spine'), sj = R(`shoulder${n}`), ej = R(`elbow${n}`), wj = R(`wrist${n}`);
559
+ const L = (k) => look[`${k}${n}`] ?? look[k];
560
+ // a ring across the limb (direction u): X points away from the body, Z forward
561
+ const ring = (c, u, rx, rz, w) => {
562
+ const Z = norm(sub([0, 0, 1], scale(u, u[2])));
563
+ const X = norm(cross(u, Z));
564
+ const out = dot(X, [side, 0, 0]) < 0 ? scale(X, -1) : X;
565
+ return B.ring(Array.from({ length: 8 }, (_, k) => {
566
+ const t = (k * Math.PI) / 4;
567
+ return add(c, add(scale(out, Math.cos(t) * rx), scale(Z, Math.sin(t) * rz)));
568
+ }), w);
569
+ };
570
+ const up = norm(sub(E, S)), lo = norm(sub(W, E));
571
+ const A = armR;
572
+ // the shoulder: a dome over the joint (its inner half inside the trunk), then the deltoid, a slim elbow, the forearm
573
+ const a0 = ring(add(S, [-side * A * 0.4, A * 0.3, 0]), up, A * 0.95, A * 0.9, [[spine, 0.5], [sj, 0.5]]);
574
+ const a1 = ring(add(S, [side * A * 0.1, -A * 0.25, 0]), up, A * 1.22, A * 1.15, [[sj, 0.8], [spine, 0.2]]);
575
+ const a2 = ring(lerp(S, E, 0.3), up, A * 1.12, A * 1.1, [[sj, 1]]);
576
+ const a3 = ring(lerp(S, E, 0.72), up, A * 0.9, A * 0.92, [[sj, 1]]);
577
+ const a4 = ring(lerp(S, E, 0.9), up, A * 0.84, A * 0.86, [[sj, 0.8], [ej, 0.2]]);
578
+ const a5 = ring(E, norm(add(up, lo)), A * 0.8, A * 0.84, [[sj, 0.5], [ej, 0.5]]);
579
+ const a6 = ring(lerp(E, W, 0.1), lo, A * 0.84, A * 0.88, [[ej, 0.8], [sj, 0.2]]);
580
+ const a7 = ring(lerp(E, W, 0.3), lo, A * 0.9, A * 1.0, [[ej, 1]]);
581
+ const a8 = ring(lerp(E, W, 0.8), lo, A * 0.6, A * 0.7, [[ej, 1]]);
582
+ const a9 = ring(W, lo, A * 0.52, A * 0.62, [[ej, 0.5], [wj, 0.5]]);
583
+ // the hand: a flat paddle (the palm faces the thigh), a little bigger than life, fingers together, rounded
584
+ const hu = norm([side * 0.06, -1, 0.05]);
585
+ const h = (k) => k * hand;
586
+ const h1 = ring(add(W, scale(hu, h(0.028))), hu, h(0.011), h(0.024), [[wj, 1]]);
587
+ const h2 = ring(add(W, scale(hu, h(0.062))), hu, h(0.0105), h(0.029), [[wj, 1]]);
588
+ const h3 = ring(add(W, scale(hu, h(0.095))), hu, h(0.009), h(0.025), [[wj, 1]]);
589
+ const h4 = ring(add(W, scale(hu, h(0.115))), hu, h(0.006), h(0.015), [[wj, 1]]);
590
+ B.fan(a0, B.pt(add(S, [-side * A * 0.6, A * 0.5, 0]), [[spine, 0.5], [sj, 0.5]]), L('shoulder'));
591
+ B.band(a0, a1, L('upper'));
592
+ B.band(a1, a2, L('upper'));
593
+ B.band(a2, a3, L('upper'));
594
+ B.band(a3, a4, L('upper'));
595
+ B.band(a4, a5, L('elbow'));
596
+ B.band(a5, a6, L('elbow'));
597
+ B.band(a6, a7, L('fore'));
598
+ B.band(a7, a8, L('fore'));
599
+ B.band(a8, a9, L('cuff'));
600
+ B.band(a9, h1, look.hand);
601
+ B.band(h1, h2, look.hand);
602
+ B.band(h2, h3, look.hand);
603
+ B.band(h3, h4, look.hand);
604
+ B.fan(h4, B.pt(add(W, scale(hu, h(0.122))), [[wj, 1]]), look.hand);
605
+ // the thumb, forward of the palm
606
+ const fwd = [0, 0, 1];
607
+ B.shell(...tubeShape(add(add(W, scale(hu, h(0.028))), scale(fwd, h(0.014))), add(add(W, scale(hu, h(0.068))), scale(fwd, h(0.03))), h(0.008), h(0.006), 5), look.hand, [[wj, 1]]);
608
+ }
609
+ };
610
+ // ---------- the head ----------
611
+ // The head's rings, chin (t = 0) to crown (t = 1): [t, half width, half depth, forward shift], all in head heights.
612
+ // A big round cranium, full cheeks, a small chin: the eyes sit at half the height, the face below is short.
613
+ const headProfile = (s, m) => {
614
+ const shape = s.face.shape, jaw = s.face.jaw, male = s.base === 'male';
615
+ const wide = { oval: 0.98, round: 1.05, square: 1.02, long: 0.93 }[shape];
616
+ const tall = { oval: 1, round: 0.96, square: 1, long: 1.07 }[shape];
617
+ const jw = (0.68 + 0.14 * jaw + (shape === 'square' ? 0.12 : shape === 'round' ? 0.06 : 0)) * (male ? 1.06 : 0.94);
618
+ const chin = (shape === 'square' ? 0.2 : shape === 'round' ? 0.16 : 0.13) + 0.04 * jaw;
619
+ const keys = [
620
+ [0, chin * wide, 0.11, 0.12],
621
+ [0.07, 0.36 * jw * wide, 0.3, 0.1],
622
+ [0.17, 0.43 * jw * wide * (0.94 + 0.06 * jw), 0.41, 0.07],
623
+ [0.3, 0.47 * wide, 0.48, 0.045],
624
+ [0.44, 0.5 * wide, 0.52, 0.025],
625
+ [0.58, 0.515 * wide, 0.54, 0.01],
626
+ [0.72, 0.5 * wide, 0.53, -0.01],
627
+ [0.85, 0.42 * wide, 0.45, -0.03],
628
+ [0.95, 0.26 * wide, 0.28, -0.05],
629
+ ];
630
+ const hh = m.hh * tall;
631
+ return { keys, hh, y0: m.y(0.852) - 0.01 * hh, zc: 0.012 * m.H };
632
+ };
633
+ const headAt = (P, t) => {
634
+ const k = P.keys;
635
+ const tt = Math.max(0, Math.min(k.at(-1)[0], t));
636
+ let i = 0;
637
+ while (i < k.length - 2 && k[i + 1][0] < tt)
638
+ i++;
639
+ const a = k[i], b = k[i + 1];
640
+ const u = (tt - a[0]) / (b[0] - a[0]);
641
+ const L = (j) => (a[j] + (b[j] - a[j]) * u) * P.hh;
642
+ return { y: P.y0 + t * P.hh, rx: L(1), rz: L(2), z: P.zc + L(3) };
643
+ };
644
+ /** a point on the head at height t and angle th (0 = left, 90 degrees = front), d further out */
645
+ const headPt = (P, t, th, d = 0) => {
646
+ const r = headAt(P, t);
647
+ return [Math.cos(th) * (r.rx + d), r.y, r.z + Math.sin(th) * (r.rz + d)];
648
+ };
649
+ /** the face's front surface at height t and sideways offset x, and its outward normal */
650
+ const frontAt = (P, t, x) => {
651
+ const r = headAt(P, t);
652
+ const th = Math.acos(Math.max(-1, Math.min(1, x / r.rx)));
653
+ const p = [x, r.y, r.z + Math.sin(th) * r.rz];
654
+ // the normal of the ellipse in xz, tilted by the profile's slope in y
655
+ const up = headAt(P, Math.min(0.95, t + 0.03)), dn = headAt(P, Math.max(0, t - 0.03));
656
+ const slope = ((up.rz + up.z) - (dn.rz + dn.z)) / (up.y - dn.y);
657
+ const n = norm([Math.cos(th) / Math.max(r.rx, 1e-6), -slope * Math.sin(th), Math.sin(th) / Math.max(r.rz, 1e-6)]);
658
+ return { p, n };
659
+ };
660
+ /** a planar polygon on the face: at (t, x), `pts` as [across, up] offsets, lifted `lift` off the skin */
661
+ const facePoly = (P, t, x, pts, lift) => {
662
+ const { p, n } = frontAt(P, t, x);
663
+ const u = norm(cross([0, 1, 0], n)), v = cross(n, u);
664
+ return { poly: pts.map(([a, b]) => add(add(add(p, scale(n, lift)), scale(u, a)), scale(v, b))), n };
665
+ };
666
+ const headMesh = (B, s, P, id) => {
667
+ const w = [[id.head, 1]];
668
+ const skin = s.face.skin, hh = P.hh;
669
+ const rings = P.keys.map(([t]) => B.ring(Array.from({ length: 12 }, (_, k) => headPt(P, t, (k * Math.PI) / 6)), w));
670
+ for (let i = 0; i < rings.length - 1; i++)
671
+ B.band(rings[i], rings[i + 1], skin);
672
+ const top = headAt(P, 1);
673
+ B.fan(rings.at(-1), B.pt([0, top.y, P.zc - 0.05 * hh], w), skin);
674
+ const chin = headAt(P, 0);
675
+ B.fan(rings[0], B.pt([0, chin.y - 0.012 * hh, chin.z], w), skin);
676
+ // the nose: a small wedge standing off the face
677
+ const nose = 0.8 + 0.4 * s.face.nose;
678
+ const { p: nb, n: nn } = frontAt(P, 0.4, 0);
679
+ const tip = add(add(nb, scale(nn, 0.07 * hh * nose)), [0, -0.09 * hh * nose, 0]);
680
+ const base = [add(nb, [-0.045 * hh * nose, -0.1 * hh * nose, -0.01 * hh]), add(nb, [0.045 * hh * nose, -0.1 * hh * nose, -0.01 * hh]), add(nb, [0, 0.02 * hh, -0.01 * hh])];
681
+ B.shell([...base, tip], [[0, 1, 2], [0, 3, 1], [1, 3, 2], [2, 3, 0]], skin, w);
682
+ // the ears: small rounded plates on the sides
683
+ for (const sd of [1, -1]) {
684
+ const ear = headAt(P, 0.47);
685
+ const c = [sd * ear.rx * 0.98, ear.y, ear.z - 0.07 * hh];
686
+ const poly = Array.from({ length: 6 }, (_, k) => {
687
+ const a = (k / 6) * Math.PI * 2;
688
+ return add(c, [sd * 0.012 * hh, Math.sin(a) * 0.085 * hh, Math.cos(a) * 0.06 * hh]);
689
+ });
690
+ B.plate(poly, [sd, 0, 0], 0.025 * hh, skin, w);
691
+ }
692
+ };
693
+ /** The face: eyes, brows and the mouth as flat plates lying a little over the skin (an n-gon drawn on the face). */
694
+ const faceMesh = (B, s, P, id) => {
695
+ const w = [[id.head, 1]];
696
+ const hh = P.hh, lift = 0.012 * hh, thick = 0.01 * hh;
697
+ const brow = s.hair.style === 'bald' && s.beard === 'none' ? 'hair-brown' : s.hair.mat;
698
+ const female = s.base === 'female';
699
+ for (const sd of [1, -1]) {
700
+ // an almond eye (6-gon), a little taller on the female base; the outer corner slightly higher
701
+ const ew = 0.085 * hh, eh = (female ? 0.06 : 0.05) * hh;
702
+ const eye = facePoly(P, 0.5, sd * 0.17 * hh, [[-ew, 0], [-ew * 0.5, eh], [ew * 0.5, eh * 1.05], [ew, eh * 0.15], [ew * 0.5, -eh * 0.9], [-ew * 0.5, -eh * 0.85]].map(([a, b]) => [sd * a, b]), lift);
703
+ B.plate(eye.poly, eye.n, thick, 'eye-white', w);
704
+ // the pupil: a dark hexagon over the white, a little to the inner side (looking at you)
705
+ const pr = eh * 0.78;
706
+ const pupil = facePoly(P, 0.495, sd * 0.16 * hh, Array.from({ length: 6 }, (_, k) => [Math.cos((k * Math.PI) / 3 + Math.PI / 6) * pr * 0.95, Math.sin((k * Math.PI) / 3 + Math.PI / 6) * pr]), lift + thick * 1.2);
707
+ B.plate(pupil.poly, pupil.n, thick, 'eye', w);
708
+ // a brow: a slim arc of four points
709
+ const bw = 0.1 * hh, bh = female ? 0.014 * hh : 0.022 * hh;
710
+ const browP = facePoly(P, 0.63, sd * 0.17 * hh, [[-bw, -bh * 0.6], [0, bh * 0.9], [bw, 0], [bw * 0.9, -bh * 1.2], [0, -bh * 0.9], [-bw * 0.95, -bh * 2.2]].map(([a, b]) => [sd * a, b]), lift);
711
+ B.plate(browP.poly, browP.n, thick, brow, w);
712
+ }
713
+ // the mouth: a soft smile (5-gon), wider on the male base
714
+ const mw = (female ? 0.075 : 0.085) * hh, mh = 0.02 * hh;
715
+ const mouth = facePoly(P, 0.2, 0, [[-mw, mh * 0.6], [0, -mh * 0.2], [mw, mh * 0.6], [mw * 0.55, -mh * 1.2], [-mw * 0.55, -mh * 1.2]], lift);
716
+ B.plate(mouth.poly, mouth.n, thick, 'mouth', w);
717
+ };
718
+ // ---------- hair and beard ----------
719
+ /**
720
+ * A closed layer over the head: columns at angles `ths`, rows from lowT(th) up to highT(th); outside d out from the skin,
721
+ * inside just under it. wrap: the columns go all the way round (the top closed by a point), else the patch gets side walls.
722
+ */
723
+ const headLayer = (B, P, w, mat, ths, lowT, highT, d, wrap, rows = 4, drop = 0) => {
724
+ const grid = (out) => Array.from({ length: rows + 1 }, (_, r) => B.ring(ths.map((th) => {
725
+ const lo = lowT(th), hi = highT(th);
726
+ const t = lo + ((hi - lo) * r) / rows;
727
+ const p = headPt(P, t, th, out ? d(th, t, r / rows) : -0.012 * P.hh);
728
+ return r === 0 && out ? add(p, [0, -drop * P.hh, 0]) : p;
729
+ }), w));
730
+ const O = grid(true), I = grid(false);
731
+ for (let r = 0; r < rows; r++) {
732
+ B.band(O[r], O[r + 1], mat, wrap);
733
+ B.band(I[r], I[r + 1], mat, wrap);
734
+ }
735
+ B.band(O[0], I[0], mat, wrap);
736
+ if (wrap) {
737
+ const top = headAt(P, 1);
738
+ B.fan(O[rows], B.pt([0, top.y + d(Math.PI / 2, 1, 1) * 0.9, P.zc - 0.05 * P.hh], w), mat);
739
+ B.fan(I[rows], B.pt([0, top.y - 0.02 * P.hh, P.zc - 0.05 * P.hh], w), mat);
740
+ }
741
+ else {
742
+ B.band(O[rows], I[rows], mat, false);
743
+ const n = ths.length;
744
+ for (const k of [0, n - 1]) {
745
+ const o = O.map((row) => row[k]), i = I.map((row) => row[k]);
746
+ B.band(o, i, mat, false);
747
+ }
748
+ }
749
+ };
750
+ /**
751
+ * A lock of hair: a flat ribbon along `path` points ([t, th, d] on the head, or absolute points), `width` at the root
752
+ * tapering to a point; it lies on the head's surface where it passes (the d offsets keep it off the skin).
753
+ */
754
+ const lock = (B, P, w, mat, path, width, thick, taper = 0.15) => {
755
+ const n = path.length;
756
+ const rows = path.map((c, i) => {
757
+ const along = norm(sub(path[Math.min(n - 1, i + 1)], path[Math.max(0, i - 1)]));
758
+ // sideways: across the lock, level with the head's surface there (radial from the head's axis)
759
+ const r = headAt(P, Math.max(0, Math.min(0.95, (c[1] - P.y0) / P.hh)));
760
+ const radial = norm([c[0], 0, c[2] - r.z]);
761
+ let side = norm(cross(along, radial));
762
+ if (!Number.isFinite(side[0]))
763
+ side = [1, 0, 0];
764
+ const wd = width * (1 - (1 - taper) * (i / (n - 1)) ** 1.3);
765
+ return [add(c, scale(side, -wd / 2)), add(c, scale(side, wd / 2))];
766
+ });
767
+ B.ribbon(rows, thick, mat, w);
768
+ };
769
+ const hairMesh = (B, s, P, m, id) => {
770
+ const w = [[id.head, 1]];
771
+ const hh = P.hh, mat = s.hair.mat;
772
+ const style = s.hair.style;
773
+ const ring16 = Array.from({ length: 16 }, (_, k) => (k * Math.PI) / 8);
774
+ const r = rng(s.seed * 7919 + 13);
775
+ if (style !== 'bald') {
776
+ // the cap: the hairline high over the forehead, over the ears, lowest at the nape; thin at the line, full on top
777
+ const low = (th) => {
778
+ const a = Math.sin(th);
779
+ return a > 0 ? 0.52 + 0.24 * a ** 1.4 : 0.52 + (style === 'short' ? 0.18 : 0.26) * a;
780
+ };
781
+ const thick = style === 'bun' ? 0.04 : 0.055;
782
+ headLayer(B, P, w, mat, ring16, low, () => 0.94, (th, t, rel) => thick * hh * (0.2 + 0.8 * Math.min(1, rel * 1.5)), true, 4);
783
+ // the fringe and the side locks: flat locks over the hairline, each a slightly different length and swing
784
+ const fringe = (count, thFrom, thTo, len, swing, width) => {
785
+ for (let k = 0; k < count; k++) {
786
+ const u = count === 1 ? 0.5 : k / (count - 1);
787
+ const th = thFrom + (thTo - thFrom) * u;
788
+ const L = len * (0.85 + 0.3 * r()), sw = swing * (u - 0.5) * 2 + (r() - 0.5) * 0.3;
789
+ const path = [];
790
+ for (let i = 0; i <= 3; i++) {
791
+ const f = i / 3;
792
+ const t = 0.8 - L * f;
793
+ const p = headPt(P, Math.max(0.3, t), th + sw * f * 0.6, thick * hh * (0.75 - 0.3 * f) + 0.012 * hh * f);
794
+ path.push(t < 0.3 ? [p[0], P.y0 + t * hh, p[2]] : p);
795
+ }
796
+ lock(B, P, w, mat, path, width * hh, 0.014 * hh, 0.2);
797
+ }
798
+ };
799
+ if (style === 'short') {
800
+ fringe(5, Math.PI * 0.3, Math.PI * 0.7, 0.2, 0.4, 0.2);
801
+ fringe(1, Math.PI * 0.08, Math.PI * 0.08, 0.26, 0, 0.17);
802
+ fringe(1, Math.PI * 0.92, Math.PI * 0.92, 0.26, 0, 0.17);
803
+ }
804
+ else if (style === 'long') {
805
+ fringe(4, Math.PI * 0.32, Math.PI * 0.68, 0.24, 0.5, 0.2);
806
+ // long locks down the back and the sides, past the shoulders
807
+ for (let k = 0; k < 9; k++) {
808
+ const th = -Math.PI * 0.1 + (Math.PI * 1.2 * k) / 8 + Math.PI; // the back half, ear to ear
809
+ const back = th > Math.PI * 1.3 && th < Math.PI * 1.7;
810
+ const L = (back ? 0.95 : 0.75) * (0.9 + 0.2 * r());
811
+ const path = [];
812
+ for (let i = 0; i <= 4; i++) {
813
+ const f = i / 4;
814
+ const t = 0.8 - 0.95 * f;
815
+ if (t > 0.35)
816
+ path.push(headPt(P, t, th, 0.045 * hh));
817
+ else {
818
+ // below the jaw the lock hangs straight, drifting a little out and back
819
+ const base = headPt(P, 0.35, th, 0.05 * hh);
820
+ const y = P.y0 + (0.35 - (0.35 - t) * (L / 0.49)) * hh;
821
+ path.push([base[0] * (1 + 0.1 * f), Math.max(y, P.y0 - L * hh + 0.35 * hh), base[2] - 0.04 * hh * f]);
822
+ }
823
+ }
824
+ lock(B, P, w, mat, path, 0.26 * hh, 0.016 * hh, 0.35);
825
+ }
826
+ }
827
+ else if (style === 'bun') {
828
+ fringe(3, Math.PI * 0.34, Math.PI * 0.66, 0.16, 0.3, 0.2);
829
+ const c = headPt(P, 0.84, -Math.PI / 2, 0.14 * hh);
830
+ B.shell(...blobShape(add(c, [0, 0.07 * hh, 0]), [0.2 * hh, 0.17 * hh, 0.19 * hh], 8, 5), mat, w);
831
+ B.shell(...tubeShape(add(c, [0, -0.01 * hh, 0.08 * hh]), add(c, [0, 0.03 * hh, 0.1 * hh]), 0.14 * hh, 0.13 * hh, 8), mat, w);
832
+ }
833
+ }
834
+ if (s.beard !== 'none') {
835
+ const bm = s.hair.mat;
836
+ const span = s.beard === 'full' ? [-0.2, Math.PI + 0.2] : [Math.PI / 2 - 0.42, Math.PI / 2 + 0.42];
837
+ const cols = s.beard === 'full' ? 11 : 5;
838
+ const ths = Array.from({ length: cols }, (_, k) => span[0] + ((span[1] - span[0]) * k) / (cols - 1));
839
+ const top = (th) => (s.beard === 'full' ? 0.13 + 0.17 * (1 - Math.abs(Math.sin(th))) : 0.12);
840
+ headLayer(B, P, w, bm, ths, () => 0.0, top, (th, t, rel) => (s.beard === 'full' ? 0.04 : 0.035) * hh * (1 - 0.7 * rel) * (0.6 + 0.4 * Math.abs(Math.sin(th))), false, 3, s.beard === 'full' ? 0.035 : 0.03);
841
+ const mo = facePoly(P, 0.27, 0, [[-0.1 * hh, 0.012 * hh], [0, 0.03 * hh], [0.1 * hh, 0.012 * hh], [0.08 * hh, -0.02 * hh], [-0.08 * hh, -0.02 * hh]], 0.014 * hh);
842
+ B.plate(mo.poly, mo.n, 0.012 * hh, bm, w);
843
+ }
844
+ void m;
845
+ };
846
+ // ---------- gear: glasses, a coat's skirt, straps, a belt, pads, an astronaut's helmet and pack ----------
847
+ const gearMesh = (B, s, m, P, id) => {
848
+ const { H, tb, hip, waist, chest, dChest, dWaist, dHip, neck, knee, J, y } = m;
849
+ const { kind, main, second } = s.outfit;
850
+ const head = [[id.head, 1]], spine = [[id.spine, 1]], root = id.root;
851
+ const hh = P.hh;
852
+ const helmet = kind === 'astronaut' && s.outfit.helmet;
853
+ if (s.glasses && !helmet) {
854
+ for (const sd of [1, -1]) {
855
+ const rim = facePoly(P, 0.5, sd * 0.17 * hh, [[-0.11, 0.08], [0.11, 0.08], [0.11, -0.08], [-0.11, -0.08]].map(([a, b]) => [a * hh, b * hh]), 0.03 * hh);
856
+ B.plate(rim.poly, rim.n, 0.008 * hh, 'frame', head);
857
+ const lens = facePoly(P, 0.5, sd * 0.17 * hh, [[-0.09, 0.06], [0.09, 0.06], [0.09, -0.06], [-0.09, -0.06]].map(([a, b]) => [a * hh, b * hh]), 0.034 * hh);
858
+ B.plate(lens.poly, lens.n, 0.004 * hh, 'lens', head);
859
+ const side = headAt(P, 0.5);
860
+ B.shell(...boxShape([sd * side.rx * 1.01, side.y + 0.012 * hh, side.z + side.rz * 0.3], [0.008 * hh, 0.01 * hh, side.rz * 0.6]), 'frame', head);
861
+ }
862
+ const mid = facePoly(P, 0.52, 0, [[-0.05 * hh, 0.012 * hh], [0.05 * hh, 0.012 * hh], [0.05 * hh, -0.012 * hh], [-0.05 * hh, -0.012 * hh]], 0.03 * hh);
863
+ B.plate(mid.poly, mid.n, 0.008 * hh, 'frame', head);
864
+ }
865
+ if (kind === 'coat') {
866
+ // the skirt: from the belt to above the knee; its hem follows the thighs in front (sitting, walking), much less behind
867
+ const hipL = id.hipL, hipR = id.hipR;
868
+ const sk = (yy, rx, rz, hem) => B.ring(Array.from({ length: 12 }, (_, k) => {
869
+ const t = (k * Math.PI) / 6;
870
+ return [Math.cos(t) * rx, yy, Math.sin(t) * rz + (Math.sin(t) < 0 ? -0.004 * H : 0)];
871
+ }), (p) => {
872
+ if (!hem)
873
+ return [[root, 1]];
874
+ const h = hem * (p[2] > 0 ? 1 : 0.35 + 0.65 * Math.max(0, 1 + p[2] / (rz * 0.5)));
875
+ const l = Math.max(0, Math.min(1, 0.5 + p[0] / (2 * rx * 0.6)));
876
+ return [[root, 1 - h], [hipL, h * l], [hipR, h * (1 - l)]].filter(([, x]) => x > 0);
877
+ });
878
+ const tummy = 0.03 * H * Math.max(0, m.b);
879
+ const levels = [
880
+ [0.612, Math.max(waist * 1.04, m.f ? waist * 0.5 + hip * 0.5 : 0) * tb * 1.04, dWaist * tb * 1.05 + tummy * 0.85, 0],
881
+ [0.572, hip * 0.9 * Math.min(tb, 1.05) * 1.06, dHip * 0.95 * 1.08 + tummy * 0.7, 0],
882
+ [0.53, hip * Math.min(tb, 1.05) * 1.07, dHip * 1.14 + tummy * 0.6 + (m.f ? 0.014 : 0.008) * H, 0],
883
+ [0.43, hip * 1.17, dHip * 1.36 + tummy * 0.4, 0.55],
884
+ [0.345, hip * 1.23, dHip * 1.42 + tummy * 0.3, 0.85],
885
+ ];
886
+ for (let r = 1; r < levels.length; r++)
887
+ ((levels[r][1] = Math.max(levels[r][1], levels[r - 1][1])), (levels[r][2] = Math.max(levels[r][2], levels[r - 1][2])));
888
+ const o = levels.map(([yy, rx, rz, hem]) => sk(y(yy), rx, rz, hem));
889
+ const i = levels.map(([yy, rx, rz, hem]) => sk(y(yy), rx * 0.95, rz * 0.95, hem));
890
+ for (let r = 0; r < o.length - 1; r++)
891
+ (B.band(o[r], o[r + 1], main), B.band(i[r], i[r + 1], main));
892
+ B.band(o[0], i[0], main);
893
+ B.band(o.at(-1), i.at(-1), main);
894
+ // lapels and the button line
895
+ for (const sd of [1, -1])
896
+ B.shell(...boxShape([sd * chest * 0.22 * tb, y(0.765), dChest * 0.95 * tb], [chest * 0.12, 0.035 * H, 0.006 * H], sd * 0.35, -0.2, 0.6), main, spine);
897
+ B.shell(...boxShape([0, y(0.52), dHip * 1.1 + 0.004 * H], [0.003 * H, 0.08 * H, 0.003 * H]), second, [[root, 1]]);
898
+ }
899
+ if (kind === 'overall') {
900
+ // the straps over the shoulders, brass buttons, a bib pocket
901
+ for (const sd of [1, -1]) {
902
+ const bust = m.f ? 0.028 * H * (1 + 0.25 * Math.max(0, m.b)) : 0.006 * H;
903
+ const fr = [sd * chest * 0.42, y(0.752), dChest * tb + bust * 0.5 + 0.004 * H];
904
+ const top = [sd * chest * 0.55, y(0.828), -0.004 * H];
905
+ const bk = [sd * chest * 0.32, y(0.7), -dChest * tb - 0.014 * H];
906
+ B.shell(...tubeShape(fr, top, 0.009 * H, 0.009 * H, 4), main, spine);
907
+ B.shell(...tubeShape(top, bk, 0.009 * H, 0.009 * H, 4), main, spine);
908
+ B.shell(...boxShape(add(fr, [0, -0.006 * H, 0.008 * H]), [0.007 * H, 0.007 * H, 0.004 * H]), 'brass', spine);
909
+ }
910
+ B.shell(...boxShape([0, y(0.705), dChest + m.dChest * 0.15 + 0.004 * H], [chest * 0.25, 0.022 * H, 0.004 * H]), main, spine);
911
+ }
912
+ if (kind === 'workwear') {
913
+ for (const n of ['L', 'R']) {
914
+ const K = J[`knee${n}`];
915
+ B.shell(...boxShape(add(K, [0, 0, knee * 0.95 + 0.006 * H]), [knee * 0.7, knee * 0.9, 0.008 * H], 0, -0.1), 'rubber', [[id[`knee${n}`], 1]]);
916
+ }
917
+ B.shell(...boxShape([chest * 0.45 * tb, y(0.725), dChest * tb + 0.004 * H], [chest * 0.2, 0.025 * H, 0.004 * H]), second, spine);
918
+ }
919
+ if (kind === 'crew') {
920
+ // the belt with its buckle, the zip line down the tunic's front
921
+ const bw = (waist * 0.55 + hip * 0.45) * tb;
922
+ B.shell(...tubeShape([0, y(0.6), 0], [0, y(0.625), 0], bw * 1.07, bw * 1.05, 12), 'charcoal', [[root, 0.5], [id.spine, 0.5]]);
923
+ B.shell(...boxShape([0, y(0.612), dWaist * tb * 1.1 + 0.006 * H], [0.014 * H, 0.011 * H, 0.004 * H]), 'brass', [[root, 0.5], [id.spine, 0.5]]);
924
+ B.shell(...boxShape([0, y(0.71), dChest * tb + (m.f ? 0.03 : 0.012) * H], [0.0025 * H, 0.075 * H, 0.003 * H], 0, 0.12), 'charcoal', spine);
925
+ }
926
+ if (kind === 'astronaut') {
927
+ // the collar ring the helmet locks onto, a small pack on the back, the chest panel
928
+ B.shell(...tubeShape([0, y(0.836), 0], [0, y(0.86), 0.002 * H], neck * 2.2, neck * 2.1, 10), second, spine);
929
+ const back = dChest * tb;
930
+ B.shell(...boxShape([0, y(0.705), -back - 0.03 * H], [chest * 0.72, 0.085 * H, 0.03 * H], 0, 0, 0.94), main, spine);
931
+ B.shell(...boxShape([0, y(0.785), -back - 0.03 * H], [chest * 0.5, 0.008 * H, 0.024 * H]), second, spine);
932
+ B.shell(...boxShape([0, y(0.705), dChest * tb + 0.008 * H], [0.05 * H, 0.032 * H, 0.012 * H]), second, spine);
933
+ for (const sd of [1, 0, -1])
934
+ B.shell(...boxShape([sd * 0.022 * H, y(0.712), dChest * tb + 0.021 * H], [0.007 * H, 0.007 * H, 0.002 * H]), sd === 0 ? 'screen' : 'rubber', spine);
935
+ if (helmet) {
936
+ const c = [0, P.y0 + hh * 0.5, P.zc + 0.03 * hh];
937
+ const r = hh * 0.74;
938
+ const seg = 12;
939
+ const [pts, faces] = blobShape(c, [r, r * 1.02, r * 1.02], seg, 8);
940
+ const mid = (f) => scale(f.reduce((a, i) => add(a, pts[i]), [0, 0, 0]), 1 / f.length);
941
+ B.shell(pts, faces, (i) => {
942
+ const f = faces[i], k = i - seg;
943
+ const at = i < seg || i >= faces.length - seg ? mid(f) : mid(k % 2 === 0 ? [f[0], f[2]] : [f[0], f[1]]);
944
+ const q = sub(at, c);
945
+ return q[2] > r * 0.45 && q[1] > -r * 0.5 && q[1] < r * 0.55 && Math.abs(q[0]) < r * 0.78 ? 'visor' : main;
946
+ }, head);
947
+ }
948
+ }
949
+ };
950
+ // ---------- the prop in the right hand ----------
951
+ const propMesh = (B, s, m, id) => {
952
+ const { H, hand, J } = m;
953
+ const w = [[id.wristR, 1]];
954
+ const W = J.wristR;
955
+ const hu = norm([-0.06, -1, 0.05]);
956
+ const palm = add(W, scale(hu, 0.062 * hand));
957
+ if (s.prop === 'tablet') {
958
+ // held upright against the palm, the screen facing out
959
+ const c = add(palm, [0.002 * H, -0.01 * H, 0.034 * H]);
960
+ B.shell(...boxShape(c, [0.006 * H, 0.085 * H, 0.06 * H], 0, 0.15), 'plastic', w);
961
+ B.shell(...boxShape(add(c, [-0.0068 * H, 0, 0]), [0.0012 * H, 0.075 * H, 0.052 * H], 0, 0.15), 'screen', w);
962
+ }
963
+ else if (s.prop === 'wrench') {
964
+ const c = add(palm, [0, -0.01 * H, 0.014 * H]);
965
+ B.shell(...boxShape(add(c, [0, -0.05 * H, 0.012 * H]), [0.006 * H, 0.085 * H, 0.012 * H], 0, -0.2), 'steel', w);
966
+ B.shell(...boxShape(add(c, [0, -0.14 * H, 0.032 * H]), [0.009 * H, 0.016 * H, 0.03 * H], 0, -0.2), 'steel', w);
967
+ B.shell(...boxShape(add(c, [0, -0.16 * H, 0.058 * H]), [0.009 * H, 0.012 * H, 0.009 * H], 0, -0.2), 'steel', w);
968
+ B.shell(...boxShape(add(c, [0, -0.165 * H, 0.015 * H]), [0.009 * H, 0.012 * H, 0.009 * H], 0, -0.2), 'steel', w);
969
+ }
970
+ else if (s.prop === 'commlock') {
971
+ // a hand-held communicator: a flat box in the fist with a small screen and a button row, its top at the thumb
972
+ const c = add(palm, [0.0, -0.005 * H, 0.03 * H]);
973
+ B.shell(...boxShape(c, [0.012 * H, 0.05 * H, 0.014 * H], 0, 0.1), 'suit-grey', w);
974
+ B.shell(...boxShape(add(c, [-0.0125 * H, 0.015 * H, 0]), [0.001 * H, 0.016 * H, 0.009 * H], 0, 0.1), 'screen', w);
975
+ for (const k of [-1, 0, 1])
976
+ B.shell(...boxShape(add(c, [-0.0125 * H, -0.022 * H, k * 0.008 * H]), [0.001 * H, 0.004 * H, 0.0025 * H], 0, 0.1), k === 0 ? 'rust' : 'rubber', w);
977
+ B.shell(...boxShape(add(c, [0, 0.056 * H, -0.004 * H]), [0.004 * H, 0.008 * H, 0.004 * H]), 'charcoal', w);
978
+ }
979
+ };
980
+ const r5 = (v) => Math.round(v * 1e5) / 1e5;
981
+ /**
982
+ * The figure of a spec: its parts (stable ids, in CHARACTER_PARTS order, the empty ones left out) and its rig (the humanoid
983
+ * joints, blended weights). Faces name palette materials; their colours come from `palette` (else CHARACTER_MATERIALS).
984
+ * Use the rig with posed() / boneMatrices() / walkPose() / HUMANOID_POSES.
985
+ */
986
+ export const buildCharacter = (input, palette) => {
987
+ const spec = normalizeCharacter(input);
988
+ const m = measures(spec);
989
+ const joints = HUMANOID_JOINTS.map((name) => {
990
+ const parent = name === 'root' ? null : name === 'spine' || name.startsWith('hip') ? 'root' : name === 'head' || name.startsWith('shoulder') ? 'spine' : name.startsWith('elbow') ? `shoulder${name.slice(-1)}` : name.startsWith('wrist') ? `elbow${name.slice(-1)}` : name.startsWith('knee') ? `hip${name.slice(-1)}` : `knee${name.slice(-1)}`;
991
+ return { name, parent, at: m.J[name].map(r5) };
992
+ });
993
+ const id = Object.fromEntries(joints.map((j, i) => [j.name, i]));
994
+ const look = lookOf(spec);
995
+ const P = headProfile(spec, m);
996
+ const helmet = spec.outfit.kind === 'astronaut' && spec.outfit.helmet;
997
+ const color = (mat) => palette?.[mat]?.color ?? MATS[mat]?.color ?? '#c8c8c8';
998
+ const makers = [
999
+ ['body', (B) => bodyMesh(B, spec, m, look, id)],
1000
+ ['arms', (B) => armsMesh(B, spec, m, look, id)],
1001
+ ['head', (B) => headMesh(B, spec, P, id)],
1002
+ ['face', (B) => faceMesh(B, spec, P, id)],
1003
+ ['hair', (B) => (helmet ? undefined : hairMesh(B, spec, P, m, id))],
1004
+ ['gear', (B) => gearMesh(B, spec, m, P, id)],
1005
+ ['prop', (B) => propMesh(B, spec, m, id)],
1006
+ ];
1007
+ const parts = [];
1008
+ const skin = [];
1009
+ for (const [pid, make] of makers) {
1010
+ const B = new Build();
1011
+ make(B);
1012
+ if (!B.F.length)
1013
+ continue;
1014
+ const { mesh, w } = B.finish(color);
1015
+ parts.push({ id: pid, mesh });
1016
+ skin.push(w);
1017
+ }
1018
+ return { spec, parts, rig: { joints, skin }, height: Math.max(m.H, P.y0 + P.hh) };
1019
+ };