@7ots/cli 0.1.19 → 0.1.36

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 (104) hide show
  1. package/.env.example +14 -0
  2. package/brand/logos/base.svg +1 -0
  3. package/brand/logos/clawpump.png +0 -0
  4. package/brand/logos/conductors.svg +1 -0
  5. package/brand/logos/notlogin.svg +12 -0
  6. package/brand/logos/pumpfun.png +0 -0
  7. package/brand/logos/solana.png +0 -0
  8. package/brand/logos/spawnerbot.svg +1 -0
  9. package/brand/logos/virtuals.png +0 -0
  10. package/cli/7ots.mjs +59 -1
  11. package/cli/lib/account.mjs +23 -3
  12. package/cli/lib/assistant.mjs +88 -13
  13. package/cli/lib/brain.mjs +76 -8
  14. package/cli/lib/config.mjs +14 -3
  15. package/cli/lib/desktop-sync.mjs +177 -0
  16. package/cli/lib/i18n.mjs +9 -0
  17. package/cli/lib/inferences.mjs +19 -2
  18. package/cli/lib/integrations.mjs +61 -6
  19. package/cli/lib/pet-server.mjs +316 -41
  20. package/cli/lib/prompts.mjs +1 -1
  21. package/cli/lib/senses/gestures.mjs +121 -0
  22. package/cli/lib/senses/index.mjs +490 -0
  23. package/cli/lib/senses/rules.mjs +159 -0
  24. package/cli/lib/senses/sources/activity.mjs +95 -0
  25. package/cli/lib/senses/sources/calendar.mjs +75 -0
  26. package/cli/lib/senses/sources/index.mjs +17 -0
  27. package/cli/lib/senses/sources/mail.mjs +48 -0
  28. package/cli/lib/senses/sources/system.mjs +39 -0
  29. package/cli/lib/senses/util.mjs +41 -0
  30. package/cli/lib/senses/vendor.mjs +78 -0
  31. package/cli/lib/stt-local.py +16 -8
  32. package/cli/lib/stt.mjs +53 -6
  33. package/cli/lib/tooluse.mjs +56 -0
  34. package/cli/lib/vm.mjs +1 -1
  35. package/cli/lib/wake-local.py +109 -0
  36. package/cli/lib/wake.mjs +102 -0
  37. package/cli/pet/electron/main.cjs +137 -13
  38. package/cli/pet/pet.html +125 -26
  39. package/cli/pet/senses.html +342 -0
  40. package/cli/pet/settings.html +787 -86
  41. package/dist/7ots.esm.js +373 -146
  42. package/dist/7ots.esm.js.map +4 -4
  43. package/dist/7ots.iife.js +373 -146
  44. package/dist/7ots.iife.js.map +4 -4
  45. package/llms.txt +27 -0
  46. package/package.json +5 -2
  47. package/server/channels/apuchat.mjs +2 -0
  48. package/server/errors.mjs +90 -0
  49. package/server/notify.mjs +78 -0
  50. package/server/server.mjs +68 -12
  51. package/server/settings.mjs +3 -0
  52. package/server/site.mjs +401 -0
  53. package/server/tts.mjs +29 -5
  54. package/src/avatar/AvatarStage.js +2 -2
  55. package/src/avatar/three.js +3 -2
  56. package/src/character/AvatarEditor.js +2 -1
  57. package/src/character/Character.js +1 -1
  58. package/src/character/TradingCard.js +2 -0
  59. package/src/character/beat.js +64 -2
  60. package/src/character/mods/orc.js +8 -1
  61. package/src/character/mods.js +104 -10
  62. package/src/character/motion.js +162 -0
  63. package/src/character/parts.js +40 -38
  64. package/src/character/styles.js +40 -38
  65. package/src/character3d/Character3D.js +26 -5
  66. package/src/character3d/body.js +14 -12
  67. package/src/character3d/export.js +693 -0
  68. package/src/character3d/fx.js +13 -0
  69. package/src/character3d/index.js +2 -0
  70. package/src/character3d/materials.js +106 -10
  71. package/src/character3d/room-themes.js +1184 -0
  72. package/src/character3d/room.js +487 -0
  73. package/src/character3d/stage.js +2 -1
  74. package/src/creator/StepCreator.js +316 -0
  75. package/src/i18n/index.js +3 -3
  76. package/src/i18n/messages/character.js +352 -4
  77. package/src/i18n/messages/creator.js +138 -0
  78. package/src/i18n/messages/identity.js +89 -1
  79. package/src/i18n/messages/platform.js +255 -1
  80. package/src/i18n/messages/server.js +443 -1
  81. package/src/i18n/messages/widget.js +233 -0
  82. package/src/identity/random.js +14 -2
  83. package/src/identity/schema.js +2 -1
  84. package/src/index.js +9 -2
  85. package/src/voice/tags.js +22 -0
  86. package/server/platform/apuchat.mjs +0 -266
  87. package/server/platform/auth.mjs +0 -337
  88. package/server/platform/byte.mjs +0 -291
  89. package/server/platform/connect.mjs +0 -391
  90. package/server/platform/crypto.mjs +0 -80
  91. package/server/platform/db.mjs +0 -293
  92. package/server/platform/device.mjs +0 -247
  93. package/server/platform/integrations.mjs +0 -169
  94. package/server/platform/look.mjs +0 -20
  95. package/server/platform/mods.mjs +0 -222
  96. package/server/platform/orquesta.mjs +0 -611
  97. package/server/platform/profile.mjs +0 -182
  98. package/server/platform/routes.mjs +0 -589
  99. package/server/platform/runtime.mjs +0 -286
  100. package/server/platform/sites.mjs +0 -146
  101. package/server/platform/stage3d.mjs +0 -82
  102. package/server/platform/store.mjs +0 -469
  103. package/server/platform/vm.mjs +0 -1057
  104. package/server/platform/wallet.mjs +0 -255
@@ -0,0 +1,693 @@
1
+ /**
2
+ * Un ot como .glb: el MISMO Character3D de la vista 3D, horneado para cualquier visor glTF
3
+ * (lo usa byte arena para que el ot juegue con su propio cuerpo; ver server/platform/model3d.mjs).
4
+ *
5
+ * Lo que vive en shaders de 7ots se hornea:
6
+ * - el cuerpo pasa a una esfera deformada CON uv (mismo mapeo de body.js) y su color sale de
7
+ * una textura: estampado, piel, mejillas y oclusión, la misma lógica que materials.js en JS;
8
+ * - toon/sketch/estilos: material sin luz (KHR_materials_unlit) con las 3 bandas de luz ya
9
+ * pintadas, desde la luz principal del escenario de 7ots;
10
+ * - contorno de dibujo animado: casco invertido real (geometría inflada con caras al revés);
11
+ * - parches (tirita, antifaz, tapabocas): superficie inflada + textura con alfa (MASK).
12
+ * El pelo (capas instanciadas), la sombra, los efectos y las piezas SVG de mods se quedan fuera.
13
+ *
14
+ * Animación: clips muestreados del propio `tick()` del personaje, con propiedades disjuntas
15
+ * para que el visor pueda mezclarlos:
16
+ * idle | win | lose | thinking | walk — base (uno a la vez, con fundido): cuerpo, cejas, ojos (ánimo), manos…
17
+ * talk — capa: sólo la boca (abrir/cerrar, cavidad)
18
+ * blink — capa: sólo el parpadeo (escala del ojo)
19
+ * La sonrisa/ceño (morph de la línea de la boca) va en los clips base; un nodo `head` marca la cara.
20
+ * Los nodos ocultos en reposo (boca abierta, manos) van con escala ~0: glTF no tiene visibilidad.
21
+ *
22
+ * Isomórfico: corre en el navegador o en Node (con los shims de model3d.mjs). `encodePng` lo
23
+ * pone quien llama (Node: zlib).
24
+ */
25
+
26
+ import * as THREE from 'three';
27
+ import { GLTFExporter } from 'three/addons/exporters/GLTFExporter.js';
28
+ import { Character3D } from './Character3D.js';
29
+
30
+ const TAU = Math.PI * 2;
31
+ const HIDDEN = 1e-4;
32
+ const fract = (x) => x - Math.floor(x);
33
+ const clamp01 = (x) => (x < 0 ? 0 : x > 1 ? 1 : x);
34
+ const sstep = (a, b, x) => { const t = clamp01((x - a) / (b - a)); return t * t * (3 - 2 * t); };
35
+ const mix = (a, b, t) => a + (b - a) * t;
36
+ const toSrgb = (c) => Math.round(255 * clamp01(c <= 0.0031308 ? c * 12.92 : 1.055 * c ** (1 / 2.4) - 0.055));
37
+
38
+ // ───────────────────── materials.js (GLSL) → JS ─────────────────────
39
+
40
+ function h33(x, y, z) {
41
+ const a = x * 127.1 + y * 311.7 + z * 74.7;
42
+ const b = x * 269.5 + y * 183.3 + z * 246.1;
43
+ const c = x * 113.5 + y * 271.9 + z * 124.6;
44
+ return [fract(Math.sin(a) * 43758.5453123), fract(Math.sin(b) * 43758.5453123), fract(Math.sin(c) * 43758.5453123)];
45
+ }
46
+
47
+ function patMask(u, P) {
48
+ const W = u.uDims.value.x, H = u.uDims.value.y;
49
+ const t = u.uPatType.value;
50
+ if (t === 1) {
51
+ const qx = P.x / (W * 0.33), qy = (P.y - H * 0.33) / (H * 0.29);
52
+ return (1 - sstep(0.9, 1.05, Math.hypot(qx, qy))) * sstep(-0.05, 0.12, P.z);
53
+ }
54
+ if (t === 2) return 1 - sstep(H * 0.4, H * 0.43, P.y);
55
+ if (t === 3) {
56
+ const k = 4.2 / W;
57
+ const qx = P.x * k, qy = P.y * k, qz = P.z * k;
58
+ const cx = Math.floor(qx), cy = Math.floor(qy), cz = Math.floor(qz);
59
+ const r = h33(cx, cy, cz);
60
+ if (r[0] <= 0.45) return 0;
61
+ return 1 - sstep(0.2, 0.25, Math.hypot(qx - cx - (0.3 + 0.4 * r[0]), qy - cy - (0.3 + 0.4 * r[1]), qz - cz - (0.3 + 0.4 * r[2])));
62
+ }
63
+ if (t === 4) return Math.sin((P.y / H) * 38) >= 0.55 ? 1 : 0;
64
+ if (t === 5) return (Math.sin((P.y / H) * 30 + Math.sin(P.x * 9) * 1.6) >= 0.45 ? 1 : 0) * sstep(0.15 * W, 0.4 * W, Math.abs(P.x) + 0.25 * W * (P.z >= 0 ? 0 : 1));
65
+ if (t === 6) return (1 - sstep(u.uDims.value.w * 1.6, u.uDims.value.w * 1.8, Math.abs(P.y - u.uDims.value.z))) * sstep(-0.05, 0.1, P.z);
66
+ return 0;
67
+ }
68
+
69
+ function skinTex(u, P, N) {
70
+ const W = u.uDims.value.x, H = u.uDims.value.y;
71
+ const t = u.uTex.value;
72
+ if (t === 1) {
73
+ const s = W * 0.085;
74
+ const qx = (Math.atan2(P.x, P.z) * W * 0.42) / s, qy = P.y / s;
75
+ let best = 0;
76
+ for (let k = 0; k < 2; k++) {
77
+ const row = Math.floor(qy) + k;
78
+ const fx = qx + 0.5 * (((row % 2) + 2) % 2);
79
+ const dx = fract(fx) - 0.5, dy = qy - row + 0.15;
80
+ best = Math.max(best, 1 - Math.hypot(dx, dy * 1.25));
81
+ }
82
+ return mix(0.72, 1.08, sstep(0, 0.5, best));
83
+ }
84
+ if (t === 2) {
85
+ const k = 13 / W;
86
+ const qx = P.x * k, qy = P.y * k, qz = P.z * k;
87
+ const cx = Math.floor(qx), cy = Math.floor(qy), cz = Math.floor(qz);
88
+ const r = h33(cx + 3.1, cy + 3.1, cz + 3.1);
89
+ const d = Math.hypot(qx - cx - (0.25 + 0.5 * r[0]), qy - cy - (0.25 + 0.5 * r[1]), qz - cz - (0.25 + 0.5 * r[2]));
90
+ const sp = r[0] > 0.35 ? 1 - sstep(0.1, 0.16, d / (0.6 + r[2])) : 0;
91
+ return mix(1, r[1] > 0.5 ? 0.62 : 1.22, sp);
92
+ }
93
+ if (t === 3) {
94
+ const b = 0.5 + 0.5 * Math.sin((P.y / H) * TAU * 9);
95
+ return mix(0.8, 1.04, sstep(0.15, 0.85, b) * 0.8);
96
+ }
97
+ if (t === 5) {
98
+ const s = W * 0.3;
99
+ const ax = Math.abs(N.x), ay = Math.abs(N.y), az = Math.abs(N.z);
100
+ const [qa, qb] = az > ax && az > ay ? [P.x, P.y] : ax > ay ? [P.z, P.y] : [P.x, P.z];
101
+ const fa = fract(qa / s + 0.5) - 0.5, fb = fract(qb / s + 0.5) - 0.5;
102
+ const e = Math.min(0.5 - Math.abs(fa), 0.5 - Math.abs(fb)) * s;
103
+ const groove = 1 - sstep(0, W * 0.012, e);
104
+ const rivet = 1 - sstep(W * 0.01, W * 0.016, Math.hypot(Math.abs(fa) * s - (0.5 * s - W * 0.035), Math.abs(fb) * s - (0.5 * s - W * 0.035)));
105
+ return mix(1, 0.7, groove) * mix(1, 1.15, rivet);
106
+ }
107
+ return 1;
108
+ }
109
+
110
+ function sdSeg(px, py, ax, ay, bx, by) {
111
+ const pax = px - ax, pay = py - ay, bax = bx - ax, bay = by - ay;
112
+ const h = clamp01((pax * bax + pay * bay) / (bax * bax + bay * bay));
113
+ return Math.hypot(pax - bax * h, pay - bay * h);
114
+ }
115
+ function sdHeart(px, py) {
116
+ px = Math.abs(px);
117
+ py += 0.6;
118
+ if (py + px > 1) return Math.hypot(px - 0.25, py - 0.75) - 0.3536;
119
+ const m = 0.5 * Math.max(px + py, 0);
120
+ return Math.sqrt(Math.min(px * px + (py - 1) ** 2, (px - m) ** 2 + (py - m) ** 2)) * Math.sign(px - py);
121
+ }
122
+ function sdStar(px, py, r) {
123
+ const k1x = 0.809016994375, k1y = -0.587785252292, k2x = -0.809016994375, k2y = -0.587785252292;
124
+ px = Math.abs(px);
125
+ let d = 2 * Math.max(k1x * px + k1y * py, 0);
126
+ px -= d * k1x; py -= d * k1y;
127
+ d = 2 * Math.max(k2x * px + k2y * py, 0);
128
+ px -= d * k2x; py -= d * k2y;
129
+ px = Math.abs(px);
130
+ py -= r;
131
+ const bax = 0.45 * -k1y - 0, bay = 0.45 * k1x - 1;
132
+ const h = Math.min(Math.max((px * bax + py * bay) / (bax * bax + bay * bay), 0), r);
133
+ return Math.hypot(px - bax * h, py - bay * h) * Math.sign(py * bax - px * bay);
134
+ }
135
+
136
+ /** Mejillas: [r, g, b, alfa] (lineal) o null. */
137
+ function cheekPaint(u, P) {
138
+ if (u.uCheekOn.value < 0.5) return null;
139
+ const r = u.uDims.value.w;
140
+ const ch = u.uCheek.value;
141
+ const qx = (Math.abs(P.x) - ch.x) / r, qy = (P.y - ch.y) / r;
142
+ const front = sstep(-0.02, 0.06, P.z);
143
+ if (!front) return null;
144
+ const t = u.uCheekType.value;
145
+ let a = 0;
146
+ if (t === 1) { const cd = Math.hypot(Math.abs(P.x) - ch.x, P.y - ch.y, P.z - ch.z) / ch.w; a = 0.7 * Math.exp(-cd * cd * 2.2); }
147
+ else if (t === 2) { let d = 9; for (let i = 0; i < 3; i++) { const bx = (i - 1) * 0.4 - 0.12, by = -0.25; d = Math.min(d, sdSeg(qx, qy, bx, by, bx + 0.25, by + 0.5)); } a = 1 - sstep(0.06, 0.1, d); }
148
+ else if (t === 3) {
149
+ const F = [[0, 0], [0.5, -0.3], [-0.4, -0.4], [0.2, -0.75], [-0.2, 0.1]];
150
+ let d = 9;
151
+ for (const [fx, fy] of F) d = Math.min(d, Math.hypot(qx - fx + 0.25, qy - fy - 0.1));
152
+ a = 1 - sstep(0.08, 0.12, d);
153
+ }
154
+ else if (t === 4) { const d = Math.min(sdSeg(qx, qy, -0.65, 0.4, 0.95, 0.4), sdSeg(qx, qy, -0.65, -0.1, 0.95, -0.1)); a = (1 - sstep(0.1, 0.14, d)) * 0.95; }
155
+ else if (t === 5) a = 1 - sstep(-0.02, 0.03, sdHeart((qx - 0.05) / 0.5, (qy + 0.1) / 0.5) * 0.5);
156
+ else if (t === 6) a = 1 - sstep(-0.01, 0.03, sdStar(qx - 0.15, qy + 0.1, 0.42));
157
+ a *= front;
158
+ if (a <= 0) return null;
159
+ const c = u.uCheekColor.value;
160
+ return [c.r, c.g, c.b, a];
161
+ }
162
+
163
+ // luz del escenario de 7ots (stage.js makeScene), para hornear las bandas del toon
164
+ const LIN = (hex) => new THREE.Color(hex);
165
+ const LIGHTS = [
166
+ { d: new THREE.Vector3(2.2, 3.4, 3.2).normalize(), c: LIN(0xfff1e0), i: 2.4 },
167
+ { d: new THREE.Vector3(-2.6, 2.2, -3.0).normalize(), c: LIN(0xcfe0ff), i: 2.2 },
168
+ { d: new THREE.Vector3(-3, 0.5, 2).normalize(), c: LIN(0xffe6f4), i: 0.5 },
169
+ ];
170
+ const SKY = LIN(0xe8ecff);
171
+ const GROUND = LIN(0x40304e);
172
+ function irradiance(N) {
173
+ const w = 0.5 * N.y + 0.5;
174
+ const out = [0, 0, 0];
175
+ const ch = ['r', 'g', 'b'];
176
+ for (let k = 0; k < 3; k++) {
177
+ let v = mix(GROUND[ch[k]], SKY[ch[k]], w) * 0.7;
178
+ for (const l of LIGHTS) v += l.c[ch[k]] * l.i * Math.max(0, N.dot(l.d));
179
+ out[k] = v / Math.PI + 0.45; // + entorno (RoomEnvironment × 0.75, aprox.)
180
+ }
181
+ return out;
182
+ }
183
+
184
+ // ───────────────────── geometría con uv ─────────────────────
185
+
186
+ /** Esfera deformada igual que body.js, pero con uv (mapeo equirectangular de la esfera). */
187
+ function uvBody(B) {
188
+ const [ws, hs] = B.segments;
189
+ const g = new THREE.SphereGeometry(1, ws, hs);
190
+ const pos = g.attributes.position;
191
+ const v = new THREE.Vector3();
192
+ for (let i = 0; i < pos.count; i++) {
193
+ v.fromBufferAttribute(pos, i).normalize();
194
+ B.surface(v.x, v.y, v.z, v);
195
+ pos.setXYZ(i, v.x, v.y, v.z);
196
+ }
197
+ // normales continuas: las de la geometría soldada (misma posición → misma normal)
198
+ const key = (x, y, z) => `${Math.round(x * 1e5)},${Math.round(y * 1e5)},${Math.round(z * 1e5)}`;
199
+ const src = B.geometry.attributes;
200
+ const nmap = new Map();
201
+ for (let i = 0; i < src.position.count; i++) nmap.set(key(src.position.getX(i), src.position.getY(i), src.position.getZ(i)), i);
202
+ const nrm = g.attributes.normal;
203
+ for (let i = 0; i < pos.count; i++) {
204
+ const j = nmap.get(key(pos.getX(i), pos.getY(i), pos.getZ(i)));
205
+ if (j !== undefined) nrm.setXYZ(i, src.normal.getX(j), src.normal.getY(j), src.normal.getZ(j));
206
+ }
207
+ // SphereGeometry: uv.y = 1 - θ/π (arriba = 1). En glTF la imagen empieza arriba (v = 0), así que
208
+ // la fila r de la textura es v = (r + .5) / alto: la fila 0 es el polo de ARRIBA si invertimos.
209
+ const uv = g.attributes.uv;
210
+ for (let i = 0; i < uv.count; i++) uv.setY(i, 1 - uv.getY(i));
211
+ return g;
212
+ }
213
+
214
+ /** Copia inflada a lo largo de la normal; `flip` invierte las caras (contorno de casco invertido). */
215
+ function inflated(geo, off, flip) {
216
+ const g = geo.clone();
217
+ const p = g.attributes.position;
218
+ const n = g.attributes.normal;
219
+ for (let i = 0; i < p.count; i++) p.setXYZ(i, p.getX(i) + n.getX(i) * off, p.getY(i) + n.getY(i) * off, p.getZ(i) + n.getZ(i) * off);
220
+ if (flip) {
221
+ const ix = g.index.array;
222
+ for (let i = 0; i < ix.length; i += 3) { const t = ix[i + 1]; ix[i + 1] = ix[i + 2]; ix[i + 2] = t; }
223
+ g.deleteAttribute('uv');
224
+ }
225
+ return g;
226
+ }
227
+
228
+ // ───────────────────── horneado ─────────────────────
229
+
230
+ /**
231
+ * Textura del cuerpo (RGBA, sRGB) + una de alfa por parche. Cada texel se evalúa en la superficie
232
+ * analítica (θ, φ de la esfera → body.surface), así no hay huecos ni costuras que rellenar.
233
+ */
234
+ function bake(c, size, patches, geo) {
235
+ const Wt = size, Ht = size / 2;
236
+ const u = c.bodyU;
237
+ const B = c.B;
238
+ const s = c.spec;
239
+ const toon = !!s._style || ((s.finish === 'toon' || s.finish === 'sketch') && !c.plush);
240
+ const base = new THREE.Color(s.body.color);
241
+ const pat = u.uPat.value;
242
+ const H = c.H;
243
+ const plush = c.plush;
244
+ const dens = c.density || 0;
245
+ const out = new Uint8Array(Wt * Ht * 4);
246
+ const masks = patches.map(() => new Uint8Array(Wt * Ht * 4));
247
+ const boxes = patches.map((p) => {
248
+ const b = p.box;
249
+ return { c: b.c, h: b.h, cr: Math.cos(b.rot || 0), sr: Math.sin(b.rot || 0), round: p.round || 0 };
250
+ });
251
+ // cada texel cae en una celda (ix, iy) de la malla con uv (SphereGeometry): su punto y normal son los
252
+ // de ESE triángulo plano, no los de la superficie analítica — así las rayas siguen exactamente a la
253
+ // malla que se dibuja (con la superficie analítica, la interpolación lineal de uv las dentaba)
254
+ const [ws, hs] = B.segments;
255
+ const pa = geo.attributes.position.array, na = geo.attributes.normal.array;
256
+ const P = new THREE.Vector3(), N = new THREE.Vector3();
257
+ const tri = (out, arr, a, b, c, wa, wb, wc) => out.set(
258
+ arr[a] * wa + arr[b] * wb + arr[c] * wc, arr[a + 1] * wa + arr[b + 1] * wb + arr[c + 1] * wc, arr[a + 2] * wa + arr[b + 2] * wb + arr[c + 2] * wc);
259
+ // se evalúa en las ESQUINAS de los texels y cada texel promedia sus 4: antialias 2×2 al precio de 1×
260
+ // (sin él, los bordes de rayas y parches quedan en escalera)
261
+ const W1 = Wt + 1;
262
+ const col = new Float32Array(W1 * (Ht + 1) * 3);
263
+ const ins = boxes.map(() => new Uint8Array(W1 * (Ht + 1)));
264
+ for (let r = 0; r <= Ht; r++) {
265
+ const gy = (r / Ht) * hs; // fila 0 = arriba (ver uvBody)
266
+ const iy = Math.min(hs - 1, Math.floor(gy)), fy = gy - iy;
267
+ for (let i = 0; i <= Wt; i++) {
268
+ const gx = (i / Wt) * ws;
269
+ const ix = Math.min(ws - 1, Math.floor(gx)), fx = gx - ix;
270
+ // SphereGeometry parte cada celda por la diagonal (ix, iy)–(ix+1, iy+1)
271
+ const v00 = (iy * (ws + 1) + ix) * 3, v10 = v00 + 3, v01 = v00 + (ws + 1) * 3, v11 = v01 + 3;
272
+ if (fx >= fy) { tri(P, pa, v00, v10, v11, 1 - fx, fx - fy, fy); tri(N, na, v00, v10, v11, 1 - fx, fx - fy, fy); }
273
+ else { tri(P, pa, v00, v01, v11, 1 - fy, fy - fx, fx); tri(N, na, v00, v01, v11, 1 - fy, fy - fx, fx); }
274
+ N.normalize();
275
+ // color (lineal), como el fragment shader del cuerpo
276
+ let cr = base.r, cg = base.g, cb = base.b;
277
+ const m = patMask(u, P);
278
+ if (m > 0) { cr = mix(cr, pat.r, m); cg = mix(cg, pat.g, m); cb = mix(cb, pat.b, m); }
279
+ const k = skinTex(u, P, N);
280
+ cr *= k; cg *= k; cb *= k;
281
+ const ch = cheekPaint(u, P);
282
+ if (ch) { cr = mix(cr, ch[0], ch[3]); cg = mix(cg, ch[1], ch[3]); cb = mix(cb, ch[2], ch[3]); }
283
+ const ao = H < 0.01 ? 1 : mix(0.5, 1, sstep(0, 0.3 * H, P.y));
284
+ cr *= ao; cg *= ao; cb *= ao;
285
+ if (plush && dens) { // hebras: variación por celda como las capas de pelo
286
+ const h = h33(Math.floor(P.x * dens), Math.floor(P.y * dens), Math.floor(P.z * dens));
287
+ const f = 0.9 + 0.16 * h[0];
288
+ cr *= f; cg *= f; cb *= f;
289
+ }
290
+ if (toon) {
291
+ const L = irradiance(N);
292
+ const lum = 0.299 * cr * L[0] + 0.587 * cg * L[1] + 0.114 * cb * L[2];
293
+ const ql = (lum < 0.1 ? 0.55 : lum < 0.35 ? 0.8 : 1) * 0.95;
294
+ cr *= ql; cg *= ql; cb *= ql;
295
+ }
296
+ const o = r * W1 + i;
297
+ col[o * 3] = cr; col[o * 3 + 1] = cg; col[o * 3 + 2] = cb;
298
+ for (let j = 0; j < boxes.length; j++) {
299
+ const bx = boxes[j];
300
+ const dx = P.x - bx.c[0], dy = P.y - bx.c[1], dz = P.z - bx.c[2];
301
+ const rx = bx.cr * dx + bx.sr * dy, ry = -bx.sr * dx + bx.cr * dy;
302
+ const ex = Math.abs(rx) - bx.h[0] + bx.round, ey = Math.abs(ry) - bx.h[1] + bx.round, ez = Math.abs(dz) - bx.h[2] + bx.round;
303
+ ins[j][o] = Math.hypot(Math.max(ex, 0), Math.max(ey, 0)) - bx.round > 0 || ez > bx.round ? 0 : 1;
304
+ }
305
+ }
306
+ }
307
+ for (let r = 0; r < Ht; r++) {
308
+ for (let i = 0; i < Wt; i++) {
309
+ const k0 = r * W1 + i, k1 = k0 + 1, k2 = k0 + W1, k3 = k2 + 1;
310
+ const o = (r * Wt + i) * 4;
311
+ for (let ch = 0; ch < 3; ch++) out[o + ch] = toSrgb((col[k0 * 3 + ch] + col[k1 * 3 + ch] + col[k2 * 3 + ch] + col[k3 * 3 + ch]) * 0.25);
312
+ out[o + 3] = 255;
313
+ for (let j = 0; j < boxes.length; j++) {
314
+ const m = ins[j], mk = masks[j];
315
+ mk[o] = mk[o + 1] = mk[o + 2] = 255;
316
+ mk[o + 3] = ((m[k0] + m[k1] + m[k2] + m[k3]) * 255) >> 2;
317
+ }
318
+ }
319
+ }
320
+ return { body: { rgba: out, w: Wt, h: Ht }, masks: masks.map((rgba) => ({ rgba, w: Wt, h: Ht })), toon };
321
+ }
322
+
323
+ // ───────────────────── animación ─────────────────────
324
+
325
+ function snap(o) {
326
+ const vis = o.visible;
327
+ const sc = vis ? o.scale.toArray() : [HIDDEN, HIDDEN, HIDDEN];
328
+ return { p: o.position.toArray(), q: o.quaternion.toArray(), s: sc, w: o.morphTargetInfluences ? [...o.morphTargetInfluences] : null };
329
+ }
330
+
331
+ const near = (a, b, eps = 1e-4) => a.every((v, i) => Math.abs(v - b[i]) < eps);
332
+
333
+ /**
334
+ * Muestrea `run(τ)` (que deja al personaje en su pose del instante τ) y devuelve, por objeto,
335
+ * los fotogramas. `objs` es la lista fija de objetos que se registran.
336
+ */
337
+ function sampleFrames(c, objs, dur, fps, run) {
338
+ const n = Math.max(2, Math.round(dur * fps) + 1);
339
+ const times = new Float32Array(n);
340
+ const frames = objs.map(() => []);
341
+ for (let f = 0; f < n; f++) {
342
+ const tau = (f / (n - 1)) * dur;
343
+ times[f] = tau;
344
+ run(tau, f);
345
+ objs.forEach((o, i) => frames[i].push(snap(o)));
346
+ }
347
+ return { times, frames };
348
+ }
349
+
350
+ /** Deja al personaje quieto, en neutral, sin gesto ni metamorfosis. */
351
+ function rest(c, t) {
352
+ if (c.gest) c.endGesture();
353
+ c.morphs.clear();
354
+ c.mood('neutral');
355
+ c.mo.open = c.mo.target = 0;
356
+ c.mo.msx = c.mo.tmsx = 1;
357
+ c.blinkAt = -1e9;
358
+ c.look.x = c.look.y = c.look.tx = c.look.ty = 0;
359
+ for (let i = 0; i < 90; i++) c.tick(t - (90 - i) * 33, 33);
360
+ }
361
+
362
+ /**
363
+ * @param {object} spec look.character
364
+ * @param {object} o { encodePng(rgba, w, h) → Uint8Array (obligatorio), rasterSvg(svg, w, h) → RGBA (piezas SVG de mods; sin él no van), textureSize = 2048, fps = 30, waitMs = 8000, quality }
365
+ * @returns {Promise<{ glb: ArrayBuffer, info: object } | null>} null si el ot es un modelo completo de mod (VRM/GLB ajeno)
366
+ */
367
+ export async function characterGlb(spec, o = {}) {
368
+ if (typeof o.encodePng !== 'function') throw new Error('characterGlb: falta encodePng');
369
+ const size = o.textureSize || 2048;
370
+ const fps = o.fps || 30;
371
+ const c = new Character3D(spec, { idle: false, moodFx: false, quality: o.quality || 'high' });
372
+ if (c.modelMode) return null;
373
+ // piezas glb de los mods (cargan en segundo plano)
374
+ if (c.pending?.length) {
375
+ await Promise.race([Promise.allSettled(c.pending), new Promise((r) => setTimeout(r, o.waitMs ?? 8000))]);
376
+ }
377
+ c.effect = () => true; // sin efectos (confeti, pensamientos…): no van en el glb
378
+ const T0 = performance.now();
379
+ rest(c, T0);
380
+
381
+ // ── objetos que se exportan ──
382
+ const drop = [];
383
+ const planes = [];
384
+ c.root.traverse((m) => {
385
+ if (m.userData.modPlane && typeof o.rasterSvg === 'function') planes.push(m);
386
+ else if (m.isInstancedMesh || m.userData.modPlane) drop.push(m);
387
+ });
388
+ drop.push(c.fxg, c.shadow);
389
+ for (const m of drop) m.removeFromParent();
390
+
391
+ const objs = [];
392
+ c.rig.traverse((m) => objs.push(m));
393
+ const restSnap = new Map(objs.map((m) => [m, snap(m)]));
394
+ const mouth = new Set();
395
+ c.mouthRig.g.traverse((m) => mouth.add(m));
396
+ const line = c.mouthRig.line;
397
+ const mains = new Set(c.eyes.map((e) => e.main));
398
+
399
+ // ── clips ──
400
+ const L = 6.8; // idle: 2 respiraciones y un balanceo
401
+ const breathe = (tau, dur) => {
402
+ const nb = Math.max(1, Math.round(dur / 3.4));
403
+ const b = Math.sin((tau / dur) * TAU * nb);
404
+ c.rig.scale.x *= 1 - 0.006 * b;
405
+ c.rig.scale.z *= 1 - 0.006 * b;
406
+ c.rig.scale.y *= 1 + 0.014 * b;
407
+ c.rig.rotation.y += 0.04 * Math.sin((tau / dur) * TAU);
408
+ c.rig.quaternion.setFromEuler(c.rig.rotation);
409
+ };
410
+ const ticker = (t0) => {
411
+ let last = t0;
412
+ return (t) => { c.tick(t, Math.max(1, t - last)); last = t; };
413
+ };
414
+ const base = (name, { mood = 'neutral', gesture, ms, dur, start = 0, pre = 1500 }) => {
415
+ const t0 = performance.now() + 1e6 * (Object.keys(raw).length + 1); // cada clip en su tramo de tiempo
416
+ rest(c, t0 - pre);
417
+ c.mood(mood, { fx: false });
418
+ const tk = ticker(t0 - pre);
419
+ for (let t = t0 - pre; t < t0; t += 33) tk(t);
420
+ if (gesture) {
421
+ c.gesture(gesture, ms ? { ms } : {});
422
+ c.gest.start = t0; // el gesto empieza en t0 (gesture() usa el reloj real)
423
+ for (const m of c.morphs.values()) { m.start = t0; if (m.byGesture) m.until = t0 + (ms || c.gest.ms) - 300; }
424
+ }
425
+ raw[name] = sampleFrames(c, objs, dur, fps, (tau) => {
426
+ tk(t0 + (start + tau) * 1000);
427
+ breathe(tau, dur);
428
+ });
429
+ raw[name].kind = 'base';
430
+ };
431
+ const raw = {};
432
+ base('idle', { dur: L });
433
+ base('win', { mood: 'happy', gesture: 'celebrate', dur: 1.7 });
434
+ base('lose', { mood: 'sad', dur: 3.4 });
435
+ base('thinking', { gesture: 'think', ms: 8000, start: 1.2, dur: 2.5 });
436
+ base('walk', { gesture: 'bounce', dur: 0.9 });
437
+ // talk: sólo la boca
438
+ {
439
+ const t0 = performance.now() + 9e6;
440
+ rest(c, t0);
441
+ const tk = ticker(t0);
442
+ const seq = [0, 0.75, 0.25, 0.9, 0.45, 0.1, 0.8, 0.35, 0.65, 0.15, 0.7, 0.3, 0];
443
+ const wid = [1, 0.85, 1.1, 0.9, 1, 1.05, 0.8, 1, 1.1, 0.9, 1, 1, 1];
444
+ const dur = 2.4;
445
+ raw.talk = sampleFrames(c, objs, dur, fps, (tau) => {
446
+ const k = Math.min(seq.length - 1, Math.floor((tau / dur) * (seq.length - 1) + 0.5));
447
+ c.mo.target = tau > dur - 0.25 ? 0 : seq[k];
448
+ c.mo.tmsx = tau > dur - 0.25 ? 1 : wid[k];
449
+ tk(t0 + tau * 1000);
450
+ });
451
+ raw.talk.kind = 'talk';
452
+ }
453
+ // blink: sólo los ojos
454
+ {
455
+ const t0 = performance.now() + 1e7;
456
+ rest(c, t0);
457
+ c.blinkAt = t0;
458
+ const tk = ticker(t0);
459
+ raw.blink = sampleFrames(c, objs, 0.2, 60, (tau) => tk(t0 + tau * 1000));
460
+ raw.blink.kind = 'blink';
461
+ }
462
+ rest(c, performance.now() + 2e7);
463
+
464
+ // ── estructura de export: nombres, envoltorio del ojo (ánimo) y del parpadeo, cabeza ──
465
+ let seq = 0;
466
+ const used = new Set();
467
+ const nameOf = (m, want) => {
468
+ let n = (want || m.name || 'n').replace(/[^a-zA-Z0-9_]/g, '_');
469
+ if (used.has(n) || !want) n = `${n}_${seq++}`;
470
+ used.add(n);
471
+ m.name = n;
472
+ return n;
473
+ };
474
+ c.root.name = 'ot';
475
+ used.add('ot');
476
+ nameOf(c.rig, 'rig');
477
+ const moodNode = new Map(); // ojo → envoltorio
478
+ c.eyes.forEach((e, i) => {
479
+ const mn = e.main;
480
+ const w = new THREE.Group();
481
+ w.position.copy(mn.position);
482
+ w.quaternion.copy(mn.quaternion);
483
+ w.scale.fromArray(restSnap.get(mn).s);
484
+ const parent = mn.parent;
485
+ parent.add(w);
486
+ w.add(mn);
487
+ mn.position.set(0, 0, 0);
488
+ mn.quaternion.identity();
489
+ mn.scale.set(1, 1, 1);
490
+ mn.visible = true;
491
+ nameOf(w, `eye${i}_mood`);
492
+ nameOf(mn, `eye${i}`);
493
+ moodNode.set(mn, w);
494
+ });
495
+ nameOf(c.mouthRig.g, 'mouth');
496
+ if (line) nameOf(line, 'mouth_line');
497
+ if (c.mouthRig.cav) nameOf(c.mouthRig.cav, 'mouth_open');
498
+ c.brows.forEach((b, i) => nameOf(b.g, `brow${i}`));
499
+ c.hands.forEach((h, i) => nameOf(h, `hand${i}`));
500
+ const head = new THREE.Object3D();
501
+ head.position.set(0, c.eyeY, 0);
502
+ c.rig.add(head);
503
+ nameOf(head, 'head');
504
+ for (const m of objs) if (!m.name || !used.has(m.name)) nameOf(m);
505
+ // ocultos en reposo → visibles con escala ~0
506
+ for (const m of objs) {
507
+ if (!m.visible && !mains.has(m)) { m.visible = true; m.scale.set(HIDDEN, HIDDEN, HIDDEN); }
508
+ }
509
+
510
+ // ── pistas ──
511
+ const clips = [];
512
+ for (const [name, r] of Object.entries(raw)) {
513
+ const tracks = [];
514
+ objs.forEach((m, i) => {
515
+ const fr = r.frames[i];
516
+ const rs = restSnap.get(m);
517
+ const inMouth = mouth.has(m);
518
+ const add = (prop, key, Track, target = m) => {
519
+ if (fr.every((f) => near(f[key], rs[key]))) return;
520
+ tracks.push(new Track(`${target.name}.${prop}`, r.times, fr.flatMap((f) => f[key])));
521
+ };
522
+ if (r.kind === 'blink') {
523
+ if (!mains.has(m)) return;
524
+ const s0 = rs.s;
525
+ if (fr.every((f) => near(f.s, s0))) return;
526
+ tracks.push(new THREE.VectorKeyframeTrack(`${m.name}.scale`, r.times, fr.flatMap((f) => [f.s[0] / s0[0], f.s[1] / s0[1], f.s[2] / s0[2]])));
527
+ return;
528
+ }
529
+ if (r.kind === 'talk') {
530
+ if (!inMouth) return;
531
+ add('position', 'p', THREE.VectorKeyframeTrack);
532
+ add('quaternion', 'q', THREE.QuaternionKeyframeTrack);
533
+ add('scale', 's', THREE.VectorKeyframeTrack);
534
+ return;
535
+ }
536
+ // base
537
+ if (m === line && rs.w && !fr.every((f) => near(f.w, rs.w))) tracks.push(new THREE.NumberKeyframeTrack(`${m.name}.morphTargetInfluences`, r.times, fr.flatMap((f) => f.w)));
538
+ if (inMouth) return;
539
+ if (mains.has(m)) { add('scale', 's', THREE.VectorKeyframeTrack, moodNode.get(m)); return; }
540
+ add('position', 'p', THREE.VectorKeyframeTrack);
541
+ add('quaternion', 'q', THREE.QuaternionKeyframeTrack);
542
+ add('scale', 's', THREE.VectorKeyframeTrack);
543
+ });
544
+ // una pista vacía no deja exportar el clip: idle quieto igual lleva el cuerpo
545
+ if (!tracks.length) tracks.push(new THREE.VectorKeyframeTrack('rig.scale', [0, r.times[r.times.length - 1]], [1, 1, 1, 1, 1, 1]));
546
+ clips.push(new THREE.AnimationClip(name, r.times[r.times.length - 1], tracks));
547
+ }
548
+
549
+ // ── materiales y geometría horneados ──
550
+ const patches = [];
551
+ const bodyMesh = c.bodyMeshes[0];
552
+ const geo = uvBody(c.B);
553
+ let outline = null;
554
+ c.rig.traverse((m) => {
555
+ if (!m.isMesh || m === bodyMesh) return;
556
+ const sf = m.material?.userData?.surface;
557
+ if (!sf) return;
558
+ if (sf.outline) outline = m;
559
+ else patches.push({ mesh: m, ...sf });
560
+ });
561
+ const baked = bake(c, size, patches, geo);
562
+ const textures = new Map();
563
+ const bm = c.bodyMat;
564
+ let bodyMat;
565
+ if (baked.toon) bodyMat = new THREE.MeshBasicMaterial({ color: 0xffffff });
566
+ else {
567
+ bodyMat = new THREE.MeshPhysicalMaterial({
568
+ color: 0xffffff, roughness: bm.roughness, metalness: 0, clearcoat: bm.clearcoat, clearcoatRoughness: bm.clearcoatRoughness,
569
+ sheen: bm.sheen, sheenRoughness: bm.sheenRoughness, sheenColor: bm.sheenColor.clone(), emissive: bm.emissive.clone(),
570
+ });
571
+ if (c.bodyU.uTex.value === 4) bodyMat.emissive.copy(new THREE.Color(c.spec.body.color)).multiplyScalar(0.22);
572
+ }
573
+ bodyMat.name = 'ot_body';
574
+ textures.set('ot_body', { png: o.encodePng(baked.body.rgba, baked.body.w, baked.body.h) });
575
+ bodyMesh.geometry = geo;
576
+ bodyMesh.material = bodyMat;
577
+ nameOf(bodyMesh, 'body');
578
+ if (outline) {
579
+ outline.geometry = inflated(geo, outline.material.userData.surface.off, true);
580
+ const om = new THREE.MeshBasicMaterial({ color: outline.material.color.clone() });
581
+ om.name = 'ot_outline';
582
+ outline.material = om;
583
+ nameOf(outline, 'outline');
584
+ }
585
+ patches.forEach((p, i) => {
586
+ const old = p.mesh.material;
587
+ const pm = new THREE.MeshPhysicalMaterial({ color: old.color.clone(), roughness: old.roughness, clearcoat: old.clearcoat, sheen: old.sheen, sheenRoughness: old.sheenRoughness, sheenColor: old.sheenColor?.clone() });
588
+ pm.name = `ot_patch${i}`;
589
+ pm.alphaTest = 0.5;
590
+ p.mesh.material = pm;
591
+ p.mesh.geometry = inflated(geo, p.off, false);
592
+ textures.set(pm.name, { png: o.encodePng(baked.masks[i].rgba, baked.masks[i].w, baked.masks[i].h), mask: true });
593
+ });
594
+ // piezas SVG de mods: el SVG rasterizado (o.rasterSvg) como textura del plano
595
+ planes.forEach((m, i) => {
596
+ const { svg, w, h } = m.userData.modPlane;
597
+ let rgba = null;
598
+ try { rgba = o.rasterSvg(svg, w, h); } catch {}
599
+ if (!rgba) return m.removeFromParent();
600
+ const flip = new Uint8Array(rgba.length); // filas de abajo hacia arriba: el v de PlaneGeometry crece hacia arriba
601
+ for (let y = 0; y < h; y++) flip.set(rgba.subarray(y * w * 4, (y + 1) * w * 4), (h - 1 - y) * w * 4);
602
+ const pm = new THREE.MeshBasicMaterial({ color: 0xffffff, transparent: true, depthWrite: false, side: THREE.DoubleSide });
603
+ pm.name = `ot_mod${i}`;
604
+ m.material = pm;
605
+ textures.set(pm.name, { png: o.encodePng(flip, w, h) });
606
+ });
607
+ // shaders propios (pelo de manos/pompones, toon) → materiales estándar
608
+ const conv = new Map();
609
+ c.rig.traverse((m) => {
610
+ if (!m.isMesh || m === bodyMesh || m === outline) return;
611
+ const old = m.material;
612
+ if (!old || old.name?.startsWith('ot_')) return;
613
+ if (conv.has(old)) { m.material = conv.get(old); return; }
614
+ let nm = null;
615
+ if (old.isMeshToonMaterial) nm = new THREE.MeshStandardMaterial({ color: old.color.clone(), roughness: 0.8 });
616
+ else if (old.customProgramCacheKey !== THREE.Material.prototype.customProgramCacheKey) {
617
+ nm = new THREE.MeshPhysicalMaterial({
618
+ color: old.color.clone(), roughness: old.roughness, clearcoat: old.clearcoat, sheen: old.sheen, sheenRoughness: old.sheenRoughness,
619
+ sheenColor: old.sheenColor?.clone(), emissive: old.emissive?.clone(),
620
+ });
621
+ if (old.defines && 'FUR' in old.defines) nm.color.multiplyScalar(0.92);
622
+ }
623
+ if (nm) { conv.set(old, nm); m.material = nm; }
624
+ });
625
+
626
+ // ── glTF ──
627
+ c.root.updateMatrixWorld(true);
628
+ const bbox = new THREE.Box3().setFromObject(c.rig);
629
+ const exporter = new GLTFExporter();
630
+ const glb = await new Promise((res, rej) => exporter.parse(c.root, res, rej, { binary: true, animations: clips, onlyVisible: false, trs: true }));
631
+ const out = withTextures(glb, textures);
632
+ return {
633
+ glb: out,
634
+ info: {
635
+ clips: clips.map((k) => k.name),
636
+ toon: baked.toon,
637
+ plush: c.plush,
638
+ height: bbox.max.y - bbox.min.y,
639
+ headY: c.eyeY,
640
+ bytes: out.byteLength,
641
+ },
642
+ };
643
+ }
644
+
645
+ /** Mete las texturas horneadas (PNG) en el glb, en los materiales por nombre. */
646
+ function withTextures(glb, textures) {
647
+ const dv = new DataView(glb);
648
+ const jsonLen = dv.getUint32(12, true);
649
+ const json = JSON.parse(new TextDecoder().decode(new Uint8Array(glb, 20, jsonLen)));
650
+ const binStart = 20 + jsonLen;
651
+ const binLen = dv.getUint32(binStart, true);
652
+ const parts = [new Uint8Array(glb, binStart + 8, binLen)];
653
+ let len = binLen;
654
+ const pad = () => { const p = (4 - (len % 4)) % 4; if (p) { parts.push(new Uint8Array(p)); len += p; } };
655
+ json.images ||= [];
656
+ json.textures ||= [];
657
+ json.samplers ||= [];
658
+ json.bufferViews ||= [];
659
+ const sampler = json.samplers.push({ magFilter: 9729, minFilter: 9987, wrapS: 10497, wrapT: 33071 }) - 1;
660
+ for (const m of json.materials || []) {
661
+ const t = textures.get(m.name);
662
+ if (!t) continue;
663
+ pad();
664
+ const bv = json.bufferViews.push({ buffer: 0, byteOffset: len, byteLength: t.png.length }) - 1;
665
+ parts.push(t.png);
666
+ len += t.png.length;
667
+ const img = json.images.push({ bufferView: bv, mimeType: 'image/png' }) - 1;
668
+ const tex = json.textures.push({ sampler, source: img }) - 1;
669
+ m.pbrMetallicRoughness ||= {};
670
+ m.pbrMetallicRoughness.baseColorTexture = { index: tex };
671
+ if (t.mask) { m.alphaMode = 'MASK'; m.alphaCutoff = 0.5; }
672
+ }
673
+ pad();
674
+ json.buffers[0].byteLength = len;
675
+ let js = new TextEncoder().encode(JSON.stringify(json));
676
+ const jp = (4 - (js.length % 4)) % 4;
677
+ if (jp) { const j2 = new Uint8Array(js.length + jp).fill(0x20); j2.set(js); js = j2; }
678
+ const total = 12 + 8 + js.length + 8 + len;
679
+ const out = new Uint8Array(total);
680
+ const ov = new DataView(out.buffer);
681
+ ov.setUint32(0, 0x46546c67, true);
682
+ ov.setUint32(4, 2, true);
683
+ ov.setUint32(8, total, true);
684
+ ov.setUint32(12, js.length, true);
685
+ ov.setUint32(16, 0x4e4f534a, true);
686
+ out.set(js, 20);
687
+ let off = 20 + js.length;
688
+ ov.setUint32(off, len, true);
689
+ ov.setUint32(off + 4, 0x004e4942, true);
690
+ off += 8;
691
+ for (const p of parts) { out.set(p, off); off += p.length; }
692
+ return out.buffer;
693
+ }