cozyclay 1.0.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 (85) hide show
  1. package/LICENSE +674 -0
  2. package/README.md +109 -0
  3. package/THIRD_PARTY_NOTICES.md +29 -0
  4. package/bin/cozyclay.mjs +194 -0
  5. package/dist/ardy/cskel27-rest.json +557 -0
  6. package/dist/assets/basis_transcoder-VXdx5NbI.wasm +0 -0
  7. package/dist/assets/basis_transcoder-o4Hde_L7.js +19 -0
  8. package/dist/assets/draco_decoder-C32yEggz.wasm +0 -0
  9. package/dist/assets/draco_decoder-Z1_iN-Ht.wasm +0 -0
  10. package/dist/assets/draco_decoder-fzg4nYZr.js +34 -0
  11. package/dist/assets/draco_wasm_wrapper-DxJM36Ib.js +117 -0
  12. package/dist/assets/draco_wasm_wrapper-fZCQGLGb.js +116 -0
  13. package/dist/assets/index-BW_S1YRy.js +4395 -0
  14. package/dist/assets/index-nRmmJgap.css +1 -0
  15. package/dist/demo/walk-then-stop.npz +0 -0
  16. package/dist/fonts/instrument-serif-italic-latin.woff2 +0 -0
  17. package/dist/fonts/instrument-serif-latin.woff2 +0 -0
  18. package/dist/fonts/inter-latin.woff2 +0 -0
  19. package/dist/index.html +13 -0
  20. package/dist/models/x-bot-tpose.fbx +0 -0
  21. package/dist/models/y-bot-tpose.fbx +0 -0
  22. package/package.json +80 -0
  23. package/src/App.jsx +3840 -0
  24. package/src/ardy/client.js +140 -0
  25. package/src/ardy/convert.js +313 -0
  26. package/src/ardy/cskel27-neutral.js +39 -0
  27. package/src/ardy/cskel27.js +68 -0
  28. package/src/ardy/export.js +157 -0
  29. package/src/ardy/ik.js +610 -0
  30. package/src/ardy/npz.js +520 -0
  31. package/src/ardy/playback.js +414 -0
  32. package/src/ardy/prompt-clips.js +16 -0
  33. package/src/ardy/timeline-coordinates.js +17 -0
  34. package/src/ardy/timeline-resize.js +11 -0
  35. package/src/ardy/timeline.jsx +723 -0
  36. package/src/ardy/to-cskel27.js +205 -0
  37. package/src/ardy/waypoints.js +364 -0
  38. package/src/camera-follow.js +366 -0
  39. package/src/camera-move.js +286 -0
  40. package/src/controls.jsx +245 -0
  41. package/src/dualview.jsx +305 -0
  42. package/src/hierarchy-model.js +77 -0
  43. package/src/hierarchy-panel.jsx +365 -0
  44. package/src/history.js +90 -0
  45. package/src/main.jsx +10 -0
  46. package/src/object-catalog.jsx +90 -0
  47. package/src/object-gizmo.jsx +755 -0
  48. package/src/planview.jsx +653 -0
  49. package/src/poses.js +424 -0
  50. package/src/posestudio.jsx +811 -0
  51. package/src/props.jsx +302 -0
  52. package/src/room.jsx +64 -0
  53. package/src/scene-history.js +125 -0
  54. package/src/scene-objects.js +420 -0
  55. package/src/shot-authoring.js +113 -0
  56. package/src/shot.js +239 -0
  57. package/src/styles.css +5639 -0
  58. package/src/ui.jsx +391 -0
  59. package/src/use-render-activity.js +96 -0
  60. package/tools/ardy/BRIDGE.md +255 -0
  61. package/tools/ardy/README.md +136 -0
  62. package/tools/ardy/__pycache__/cclay_sequence_generate.cpython-313.pyc +0 -0
  63. package/tools/ardy/bridge.mjs +1427 -0
  64. package/tools/ardy/cclay_motion_edit.py +445 -0
  65. package/tools/ardy/cclay_sequence_generate.py +595 -0
  66. package/tools/ardy/dump-npz.py +205 -0
  67. package/tools/ardy/extract-rest.mjs +299 -0
  68. package/tools/ardy/npz.mjs +335 -0
  69. package/tools/ardy/out/gen-1786443326924-c6019e-generated.npz +0 -0
  70. package/tools/ardy/out/gen-1786443609325-0053db-generated.npz +0 -0
  71. package/tools/ardy/out/gen-1786443835628-749ed1-generated.npz +0 -0
  72. package/tools/ardy/out/gen-1786462605247-03cb19-generated.npz +0 -0
  73. package/tools/ardy/pose-to-npz.mjs +106 -0
  74. package/tools/ardy/run-edit-on-box.sh +73 -0
  75. package/tools/ardy/run-on-box.sh +568 -0
  76. package/tools/ardy/run-sequence-on-box.sh +162 -0
  77. package/tools/ardy/visual-qa.mjs +188 -0
  78. package/tools/ardy/vq-car.mjs +52 -0
  79. package/tools/dev-full.mjs +29 -0
  80. package/tools/process-supervisor.mjs +63 -0
  81. package/tools/qa-browser.mjs +84 -0
  82. package/tools/qa-crop3.mjs +22 -0
  83. package/tools/qa-playview.mjs +49 -0
  84. package/tools/qa-screenshot.mjs +24 -0
  85. package/tools/qa-visual.mjs +51 -0
@@ -0,0 +1,520 @@
1
+ /**
2
+ * Bounded browser reader for ARDY motion npz archives.
3
+ *
4
+ * A numpy savez() archive is a zip of .npy members. The dev sidecar writes
5
+ * STORED archives (tools/ardy/npz.mjs), but a box-generated motion is a real
6
+ * numpy archive, which may use DEFLATE, so both zip methods are supported.
7
+ * Deflate is decoded with the platform's DecompressionStream("deflate-raw");
8
+ * no dependency is added and no package file changes.
9
+ *
10
+ * Every bound is explicit: archive size, per-member decompressed size, npy
11
+ * header length, frame count, and fps range all have caps (the frame/fps caps
12
+ * mirror CozyClay's motion_retarget.MAX_FRAMES / FPS_BOUNDS). Every member is
13
+ * validated (magic, version, header dict, dtype, C order, exact byte length,
14
+ * CRC-32, finite values, proper rotation matrices) before it is accepted, and
15
+ * malformed input is rejected with a specific NpzError instead of a silent
16
+ * fallback.
17
+ *
18
+ * The archive is parsed from the central directory (EOCD at the end), which
19
+ * always carries the authoritative sizes regardless of data-descriptor flags
20
+ * in the local headers. Zip64 archives are out of scope: the caps here are
21
+ * far below 4 GiB, so a zip64 record is rejected explicitly.
22
+ */
23
+
24
+ import { CSKEL27_JOINTS } from "./cskel27.js";
25
+
26
+ const MAX_ARCHIVE_BYTES = 192 * 1024 * 1024; // download cap
27
+ const MAX_MEMBER_BYTES = 192 * 1024 * 1024; // decompressed member cap
28
+ const MAX_NPY_HEADER_BYTES = 16 * 1024; // matches CozyClay's cap
29
+ const MAX_FRAMES = 24000; // matches CozyClay motion_retarget.MAX_FRAMES
30
+ const FPS_MIN = 1;
31
+ const FPS_MAX = 240; // matches CozyClay motion_retarget.FPS_BOUNDS
32
+ // Same tolerance motion_retarget uses for squared row/column norms, pairwise
33
+ // dots, and determinant; float32 serialization noise sits far below 1e-3.
34
+ const ROTATION_MATRIX_TOLERANCE = 1e-3;
35
+
36
+ const ZIP_EOCD_SIG = 0x06054b50;
37
+ const ZIP_CENTRAL_SIG = 0x02014b50;
38
+ const ZIP_LOCAL_SIG = 0x04034b50;
39
+ const ZIP64_EOCD_SIG = 0x06064b50;
40
+ const FLAG_ENCRYPTED = 0x0001;
41
+ const FLAG_PATCHED = 0x0020;
42
+ const FLAG_STRONG = 0x0040;
43
+
44
+ export class NpzError extends Error {
45
+ constructor(message) {
46
+ super(message);
47
+ this.name = "NpzError";
48
+ }
49
+ }
50
+
51
+ /* --- CRC-32 (IEEE 802.3, reflected) -------------------------------------- */
52
+
53
+ const CRC_TABLE = (() => {
54
+ const table = new Uint32Array(256);
55
+ for (let n = 0; n < 256; n += 1) {
56
+ let c = n;
57
+ for (let k = 0; k < 8; k += 1) c = c & 1 ? 0xedb88320 ^ (c >>> 1) : c >>> 1;
58
+ table[n] = c >>> 0;
59
+ }
60
+ return table;
61
+ })();
62
+
63
+ function crc32(bytes) {
64
+ let c = 0xffffffff;
65
+ for (let i = 0; i < bytes.length; i += 1) c = CRC_TABLE[(c ^ bytes[i]) & 0xff] ^ (c >>> 8);
66
+ return (c ^ 0xffffffff) >>> 0;
67
+ }
68
+
69
+ /* --- zip container -------------------------------------------------------- */
70
+
71
+ /** Locate the End of Central Directory record, scanning back from EOF. */
72
+ function findEocd(view) {
73
+ // EOCD is 22 bytes + a comment of up to 65535; the scan window also covers
74
+ // a possible zip64 locator (20 bytes) parked just before it.
75
+ const window = Math.min(view.byteLength, 22 + 65535 + 20);
76
+ const start = view.byteLength - window;
77
+ for (let i = view.byteLength - 22; i >= start; i -= 1) {
78
+ if (view.getUint32(i, true) !== ZIP_EOCD_SIG) continue;
79
+ const totalEntries = view.getUint16(i + 10, true);
80
+ const cdSize = view.getUint32(i + 12, true);
81
+ const cdOffset = view.getUint32(i + 16, true);
82
+ if (cdOffset === 0xffffffff || cdSize === 0xffffffff || totalEntries === 0xffff) {
83
+ throw new NpzError("npz uses zip64 records, which are out of scope");
84
+ }
85
+ return { totalEntries, cdSize, cdOffset };
86
+ }
87
+ throw new NpzError("npz has no End of Central Directory record");
88
+ }
89
+
90
+ /** Parse the central directory into a name -> entry map (authoritative sizes). */
91
+ function parseCentralDirectory(view, cdOffset, cdSize) {
92
+ const end = cdOffset + cdSize;
93
+ if (end > view.byteLength) throw new NpzError("npz central directory is truncated");
94
+ const entries = new Map();
95
+ let offset = cdOffset;
96
+ while (offset < end) {
97
+ if (view.getUint32(offset, true) !== ZIP_CENTRAL_SIG) {
98
+ throw new NpzError("npz central directory is corrupt (bad record signature)");
99
+ }
100
+ const flags = view.getUint16(offset + 8, true);
101
+ const method = view.getUint16(offset + 10, true);
102
+ const crc = view.getUint32(offset + 16, true);
103
+ const compSize = view.getUint32(offset + 20, true);
104
+ const uncompSize = view.getUint32(offset + 24, true);
105
+ const nameLen = view.getUint16(offset + 28, true);
106
+ const extraLen = view.getUint16(offset + 30, true);
107
+ const commentLen = view.getUint16(offset + 32, true);
108
+ const localOffset = view.getUint32(offset + 42, true);
109
+ const nameBytes = new Uint8Array(view.buffer, view.byteOffset + offset + 46, nameLen);
110
+ const name = new TextDecoder("latin1").decode(nameBytes);
111
+ if (localOffset === 0xffffffff || compSize === 0xffffffff || uncompSize === 0xffffffff) {
112
+ throw new NpzError(`npz member ${name} uses zip64 sizes, which are out of scope`);
113
+ }
114
+ entries.set(name, { name, flags, method, crc, compSize, uncompSize, localOffset });
115
+ offset += 46 + nameLen + extraLen + commentLen;
116
+ }
117
+ return entries;
118
+ }
119
+
120
+ /** Locate a member's compressed payload via its local file header. */
121
+ function locateMember(view, entry) {
122
+ const off = entry.localOffset;
123
+ if (off + 30 > view.byteLength) throw new NpzError(`npz member ${entry.name} local header is truncated`);
124
+ if (view.getUint32(off, true) !== ZIP_LOCAL_SIG) {
125
+ throw new NpzError(`npz member ${entry.name} local header is corrupt`);
126
+ }
127
+ const flags = view.getUint16(off + 6, true);
128
+ const method = view.getUint16(off + 8, true);
129
+ const nameLen = view.getUint16(off + 26, true);
130
+ const extraLen = view.getUint16(off + 28, true);
131
+ let localComp = view.getUint32(off + 18, true);
132
+ if (flags & (FLAG_ENCRYPTED | FLAG_PATCHED | FLAG_STRONG)) {
133
+ throw new NpzError(`npz member ${entry.name} uses unsupported encryption/patching flags`);
134
+ }
135
+ if (method !== entry.method) throw new NpzError(`npz member ${entry.name} method mismatch between local and central headers`);
136
+ // Recent numpy writes a zip64 extra field in local headers even for small
137
+ // members, leaving the 32-bit size fields at 0xFFFFFFFF. Resolve it: the
138
+ // extra's 8-byte sizes appear only for the fields that are 0xFFFFFFFF.
139
+ if (localComp === 0xffffffff) {
140
+ let found = false;
141
+ let extra = off + 30 + nameLen;
142
+ const extraEnd = extra + extraLen;
143
+ while (extra + 4 <= extraEnd) {
144
+ const id = view.getUint16(extra, true);
145
+ const size = view.getUint16(extra + 2, true);
146
+ if (extra + 4 + size > extraEnd) {
147
+ throw new NpzError(`npz member ${entry.name} zip64 extra field is truncated`);
148
+ }
149
+ if (id === 0x0001) {
150
+ let at = extra + 4;
151
+ let uncomp64 = null;
152
+ let comp64 = null;
153
+ const localUncomp = view.getUint32(off + 22, true);
154
+ if (localUncomp === 0xffffffff) {
155
+ uncomp64 = view.getBigUint64(at, true);
156
+ at += 8;
157
+ }
158
+ if (localComp === 0xffffffff) {
159
+ comp64 = view.getBigUint64(at, true);
160
+ }
161
+ if (comp64 !== null) {
162
+ if (comp64 > 0xffffffffn) {
163
+ throw new NpzError(`npz member ${entry.name} uses zip64 sizes, which are out of scope`);
164
+ }
165
+ localComp = Number(comp64);
166
+ }
167
+ if (uncomp64 !== null && uncomp64 !== BigInt(entry.uncompSize)) {
168
+ throw new NpzError(`npz member ${entry.name} size mismatch between local and central headers`);
169
+ }
170
+ found = true;
171
+ break;
172
+ }
173
+ extra += 4 + size;
174
+ }
175
+ if (!found) throw new NpzError(`npz member ${entry.name} local header is corrupt (missing zip64 extra)`);
176
+ }
177
+ // Writers that use data descriptors leave the local sizes at 0; when they
178
+ // are present they must agree with the central directory.
179
+ if (localComp !== 0 && localComp !== entry.compSize) {
180
+ throw new NpzError(`npz member ${entry.name} size mismatch between local and central headers`);
181
+ }
182
+ const dataStart = off + 30 + nameLen + extraLen;
183
+ if (dataStart + entry.compSize > view.byteLength) {
184
+ throw new NpzError(`npz member ${entry.name} payload is truncated`);
185
+ }
186
+ return new Uint8Array(view.buffer, view.byteOffset + dataStart, entry.compSize);
187
+ }
188
+
189
+ /** Inflate a raw-deflate member with the platform primitive, bounded by `cap`. */
190
+ async function inflateRaw(bytes, cap) {
191
+ if (typeof DecompressionStream !== "function") {
192
+ throw new NpzError("this browser cannot decode deflate npz members (DecompressionStream unsupported)");
193
+ }
194
+ const reader = new Blob([bytes]).stream().pipeThrough(new DecompressionStream("deflate-raw")).getReader();
195
+ const chunks = [];
196
+ let total = 0;
197
+ for (;;) {
198
+ const { done, value } = await reader.read();
199
+ if (done) break;
200
+ total += value.byteLength;
201
+ if (total > cap) {
202
+ await reader.cancel();
203
+ throw new NpzError(`deflate member exceeds the ${cap} byte cap`);
204
+ }
205
+ chunks.push(value);
206
+ }
207
+ const out = new Uint8Array(total);
208
+ let offset = 0;
209
+ for (const chunk of chunks) {
210
+ out.set(chunk, offset);
211
+ offset += chunk.byteLength;
212
+ }
213
+ return out;
214
+ }
215
+
216
+ /* --- npy member ----------------------------------------------------------- */
217
+
218
+ const DTYPE_RE = /^([<>=|])([A-Za-z?])([0-9]{1,4})$/;
219
+
220
+ /**
221
+ * Parse one .npy member. Returns { shape, kind, itemsize, littleEndian,
222
+ * data: Uint8Array } where `data` starts at the array payload (the npy header
223
+ * has already been validated). Throws NpzError on anything malformed.
224
+ */
225
+ function parseNpyMember(bytes, memberName) {
226
+ if (bytes.length < 10) throw new NpzError(`npy member ${memberName} is too short`);
227
+ if (bytes[0] !== 0x93 || bytes[1] !== 0x4e || bytes[2] !== 0x55 || bytes[3] !== 0x4d || bytes[4] !== 0x50 || bytes[5] !== 0x59) {
228
+ throw new NpzError(`npy member ${memberName} has an invalid magic`);
229
+ }
230
+ let prefixLen;
231
+ let headerLen;
232
+ if (bytes[6] === 1 && bytes[7] === 0) {
233
+ prefixLen = 10; // magic(6) + version(2) + header length(2)
234
+ headerLen = bytes[8] | (bytes[9] << 8);
235
+ } else if ((bytes[6] === 2 || bytes[6] === 3) && bytes[7] === 0) {
236
+ prefixLen = 12; // magic(6) + version(2) + header length(4)
237
+ headerLen = bytes[8] | (bytes[9] << 8) | (bytes[10] << 16) | (bytes[11] << 24);
238
+ } else {
239
+ throw new NpzError(`npy member ${memberName} uses an unsupported version (${bytes[6]}.${bytes[7]})`);
240
+ }
241
+ if (headerLen <= 0 || headerLen > MAX_NPY_HEADER_BYTES) {
242
+ throw new NpzError(`npy member ${memberName} header length ${headerLen} is out of range`);
243
+ }
244
+ if (prefixLen + headerLen > bytes.length) throw new NpzError(`npy member ${memberName} header is truncated`);
245
+
246
+ let text;
247
+ try {
248
+ text = new TextDecoder("latin1").decode(bytes.subarray(prefixLen, prefixLen + headerLen));
249
+ } catch {
250
+ throw new NpzError(`npy member ${memberName} header is not decodable text`);
251
+ }
252
+ const descrMatch = /['"]descr['"]\s*:\s*['"]([^'"]+)['"]/.exec(text);
253
+ const orderMatch = /['"]fortran_order['"]\s*:\s*(True|False)/.exec(text);
254
+ const shapeMatch = /['"]shape['"]\s*:\s*\(([^()]*)\)/.exec(text);
255
+ if (!descrMatch || !orderMatch || !shapeMatch) {
256
+ throw new NpzError(`npy member ${memberName} header is missing descr/fortran_order/shape`);
257
+ }
258
+ if (orderMatch[1] !== "False") {
259
+ throw new NpzError(`npy member ${memberName} must be C order (fortran_order False)`);
260
+ }
261
+ const dims = shapeMatch[1]
262
+ .split(",")
263
+ .map((s) => s.trim())
264
+ .filter((s) => s !== "")
265
+ .map((s) => {
266
+ const n = Number(s);
267
+ if (!Number.isInteger(n) || n < 0) throw new NpzError(`npy member ${memberName} has an invalid shape dimension '${s}'`);
268
+ return n;
269
+ });
270
+ const dtypeMatch = DTYPE_RE.exec(descrMatch[1]);
271
+ if (!dtypeMatch) throw new NpzError(`npy member ${memberName} has an invalid dtype '${descrMatch[1]}'`);
272
+ const [, byteOrder, kind, itemsizeText] = dtypeMatch;
273
+ const itemsize = Number(itemsizeText);
274
+
275
+ const itemCount = dims.reduce((a, b) => a * b, 1);
276
+ const payloadBytes = itemCount * itemsize;
277
+ if (prefixLen + headerLen + payloadBytes > bytes.length) {
278
+ throw new NpzError(`npy member ${memberName} payload is truncated (expected ${payloadBytes} bytes)`);
279
+ }
280
+ return {
281
+ shape: dims,
282
+ kind,
283
+ itemsize,
284
+ littleEndian: byteOrder !== ">",
285
+ data: bytes.subarray(prefixLen + headerLen, prefixLen + headerLen + payloadBytes),
286
+ };
287
+ }
288
+
289
+ /** float32 view (little-endian); big-endian archives are byte-swapped. */
290
+ function float32Of(parsed, label) {
291
+ if (parsed.kind !== "f" || parsed.itemsize !== 4) {
292
+ throw new NpzError(`${label} must be float32, got descr kind '${parsed.kind}'/${parsed.itemsize}`);
293
+ }
294
+ const bytes = parsed.data;
295
+ if (!parsed.littleEndian) {
296
+ const swapped = new Uint8Array(bytes.byteLength);
297
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
298
+ const out = new DataView(swapped.buffer);
299
+ for (let i = 0; i < bytes.byteLength; i += 4) out.setUint32(i, view.getUint32(i, false), true);
300
+ return new Float32Array(swapped.buffer);
301
+ }
302
+ // A real box-generated npz's npy payload may start at a byteOffset that is
303
+ // not 4-byte aligned relative to the archive ArrayBuffer (zip local-header
304
+ // and npy header lengths are arbitrary bytes). Float32Array requires its
305
+ // byteOffset to be a multiple of 4, so keep the zero-copy view only when
306
+ // the payload is already aligned; otherwise copy the exact payload bytes
307
+ // into a fresh aligned buffer first. The copy is byte-identical, so the
308
+ // big-endian swap path above is unaffected and all downstream size/dtype/
309
+ // shape/finite/rotation validation still sees the same values.
310
+ if (bytes.byteOffset % 4 === 0) {
311
+ return new Float32Array(bytes.buffer, bytes.byteOffset, bytes.byteLength / 4);
312
+ }
313
+ const aligned = new Uint8Array(bytes.byteLength);
314
+ aligned.set(bytes);
315
+ return new Float32Array(aligned.buffer);
316
+ }
317
+
318
+ /** scalar integer value (fps); returns Number. */
319
+ function scalarIntOf(parsed, label) {
320
+ if (parsed.kind !== "i" && parsed.kind !== "u") {
321
+ throw new NpzError(`${label} must be an integer scalar, got descr kind '${parsed.kind}'`);
322
+ }
323
+ if (parsed.shape.length > 1 || (parsed.shape.length === 1 && parsed.shape[0] !== 1)) {
324
+ throw new NpzError(`${label} must be a scalar (shape () or (1,)), got shape (${parsed.shape.join(", ")})`);
325
+ }
326
+ const view = new DataView(parsed.data.buffer, parsed.data.byteOffset, parsed.data.byteLength);
327
+ const little = parsed.littleEndian;
328
+ let value;
329
+ switch (parsed.itemsize) {
330
+ case 1: value = parsed.kind === "u" ? view.getUint8(0) : view.getInt8(0); break;
331
+ case 2: value = parsed.kind === "u" ? view.getUint16(0, little) : view.getInt16(0, little); break;
332
+ case 4: value = parsed.kind === "u" ? view.getUint32(0, little) : view.getInt32(0, little); break;
333
+ case 8: {
334
+ const big = view.getBigInt64(0, little);
335
+ if (big > 4294967295n || big < -2147483648n) {
336
+ throw new NpzError(`${label} value ${big} is out of range`);
337
+ }
338
+ value = Number(big);
339
+ break;
340
+ }
341
+ default:
342
+ throw new NpzError(`${label} has unsupported integer itemsize ${parsed.itemsize}`);
343
+ }
344
+ if (!Number.isFinite(value)) throw new NpzError(`${label} is not a finite number`);
345
+ return value;
346
+ }
347
+
348
+ /** Validate one 3x3 matrix: finite, orthonormal rows/columns, det +1. */
349
+ function checkRotationMatrix(rows, frame, joint) {
350
+ const columns = [
351
+ [rows[0][0], rows[1][0], rows[2][0]],
352
+ [rows[0][1], rows[1][1], rows[2][1]],
353
+ [rows[0][2], rows[1][2], rows[2][2]],
354
+ ];
355
+ for (const vectors of [rows, columns]) {
356
+ for (const vector of vectors) {
357
+ const squaredNorm = vector[0] * vector[0] + vector[1] * vector[1] + vector[2] * vector[2];
358
+ if (!Number.isFinite(squaredNorm) || Math.abs(squaredNorm - 1) > ROTATION_MATRIX_TOLERANCE) {
359
+ throw new NpzError(`motion npz frame ${frame} joint ${joint}: row/column squared norm ${squaredNorm} is not 1`);
360
+ }
361
+ }
362
+ for (const [first, second] of [[0, 1], [0, 2], [1, 2]]) {
363
+ const dot =
364
+ vectors[first][0] * vectors[second][0] +
365
+ vectors[first][1] * vectors[second][1] +
366
+ vectors[first][2] * vectors[second][2];
367
+ if (!Number.isFinite(dot) || Math.abs(dot) > ROTATION_MATRIX_TOLERANCE) {
368
+ throw new NpzError(`motion npz frame ${frame} joint ${joint}: row/column dot ${dot} is not 0`);
369
+ }
370
+ }
371
+ }
372
+ const determinant =
373
+ rows[0][0] * (rows[1][1] * rows[2][2] - rows[1][2] * rows[2][1]) -
374
+ rows[0][1] * (rows[1][0] * rows[2][2] - rows[1][2] * rows[2][0]) +
375
+ rows[0][2] * (rows[1][0] * rows[2][1] - rows[1][1] * rows[2][0]);
376
+ if (!Number.isFinite(determinant) || Math.abs(determinant - 1) > ROTATION_MATRIX_TOLERANCE) {
377
+ throw new NpzError(`motion npz frame ${frame} joint ${joint}: determinant ${determinant} is not +1`);
378
+ }
379
+ }
380
+
381
+ /* --- archive decode ------------------------------------------------------- */
382
+
383
+ /**
384
+ * Decode an ARDY motion npz from raw bytes.
385
+ *
386
+ * Returns { frames, fps, rotMats, rootPos, posedJoints } with `rotMats` a
387
+ * Float32Array of frames*27*9 row-major 3x3 matrices (cskel27 joint order),
388
+ * `rootPos` a Float32Array of frames*3 (x, y, z) ARDY-world root positions,
389
+ * and `posedJoints` a Float32Array of frames*27*3 ARDY-world joint
390
+ * positions (the positional-skinning reference — playback.js drives bone
391
+ * positions straight from it). Throws NpzError on anything malformed.
392
+ */
393
+ export async function decodeMotionNpz(bytes) {
394
+ if (bytes.byteLength > MAX_ARCHIVE_BYTES) {
395
+ throw new NpzError(`motion npz is ${bytes.byteLength} bytes, over the ${MAX_ARCHIVE_BYTES} byte cap`);
396
+ }
397
+ const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
398
+ const eocd = findEocd(view);
399
+ const entries = parseCentralDirectory(view, eocd.cdOffset, eocd.cdSize);
400
+
401
+ const names = ["local_rot_mats.npy", "root_positions.npy", "fps.npy", "posed_joints.npy"];
402
+ const missing = names.filter((n) => !entries.has(n));
403
+ if (missing.length) throw new NpzError(`motion npz is missing members: ${missing.join(", ")}`);
404
+
405
+ const members = {};
406
+ for (const name of names) {
407
+ const entry = entries.get(name);
408
+ if (entry.uncompSize > MAX_MEMBER_BYTES) {
409
+ throw new NpzError(`motion npz member ${name} decompresses to ${entry.uncompSize} bytes, over the ${MAX_MEMBER_BYTES} byte cap`);
410
+ }
411
+ let payload = locateMember(view, entry);
412
+ if (entry.method === 8) payload = await inflateRaw(payload, MAX_MEMBER_BYTES);
413
+ else if (entry.method !== 0) throw new NpzError(`motion npz member ${name} uses unsupported zip method ${entry.method}`);
414
+ if (payload.byteLength !== entry.uncompSize) {
415
+ throw new NpzError(`motion npz member ${name} decompressed to ${payload.byteLength} bytes, expected ${entry.uncompSize}`);
416
+ }
417
+ if (crc32(payload) !== entry.crc) {
418
+ throw new NpzError(`motion npz member ${name} failed its CRC-32 check (corrupt data)`);
419
+ }
420
+ members[name] = payload;
421
+ }
422
+
423
+ const rotParsed = parseNpyMember(members["local_rot_mats.npy"], "local_rot_mats");
424
+ const posParsed = parseNpyMember(members["root_positions.npy"], "root_positions");
425
+ const fpsParsed = parseNpyMember(members["fps.npy"], "fps");
426
+ const jointsParsed = parseNpyMember(members["posed_joints.npy"], "posed_joints");
427
+
428
+ const joints = CSKEL27_JOINTS.length;
429
+ if (rotParsed.shape.length !== 4 || rotParsed.shape[1] !== joints || rotParsed.shape[2] !== 3 || rotParsed.shape[3] !== 3) {
430
+ throw new NpzError(`local_rot_mats must have shape (F, ${joints}, 3, 3), got (${rotParsed.shape.join(", ")})`);
431
+ }
432
+ if (posParsed.shape.length !== 2 || posParsed.shape[1] !== 3) {
433
+ throw new NpzError(`root_positions must have shape (F, 3), got (${posParsed.shape.join(", ")})`);
434
+ }
435
+ const frames = rotParsed.shape[0];
436
+ if (frames < 1 || frames > MAX_FRAMES) {
437
+ throw new NpzError(`motion npz has ${frames} frames, outside 1..${MAX_FRAMES}`);
438
+ }
439
+ if (posParsed.shape[0] !== frames) {
440
+ throw new NpzError(`root_positions frame count ${posParsed.shape[0]} differs from local_rot_mats (${frames})`);
441
+ }
442
+ if (jointsParsed.shape.length !== 3 || jointsParsed.shape[1] !== joints || jointsParsed.shape[2] !== 3) {
443
+ throw new NpzError(`posed_joints must have shape (F, ${joints}, 3), got (${jointsParsed.shape.join(", ")})`);
444
+ }
445
+ if (jointsParsed.shape[0] !== frames) {
446
+ throw new NpzError(`posed_joints frame count ${jointsParsed.shape[0]} differs from local_rot_mats (${frames})`);
447
+ }
448
+ const fps = scalarIntOf(fpsParsed, "fps");
449
+ if (fps < FPS_MIN || fps > FPS_MAX) {
450
+ throw new NpzError(`motion fps ${fps} is outside ${FPS_MIN}..${FPS_MAX}`);
451
+ }
452
+
453
+ const rotMats = float32Of(rotParsed, "local_rot_mats");
454
+ const rootPos = float32Of(posParsed, "root_positions");
455
+ const posedJoints = float32Of(jointsParsed, "posed_joints");
456
+ if (rotMats.length !== frames * joints * 9 || rootPos.length !== frames * 3 || posedJoints.length !== frames * joints * 3) {
457
+ throw new NpzError("motion npz member byte lengths do not match their shapes");
458
+ }
459
+
460
+ // Full validation before anything is accepted: every rotation matrix must
461
+ // be a proper rotation and every root position finite.
462
+ const m = rotMats;
463
+ for (let f = 0; f < frames; f += 1) {
464
+ const base = f * joints * 9;
465
+ for (let j = 0; j < joints; j += 1) {
466
+ const o = base + j * 9;
467
+ checkRotationMatrix(
468
+ [
469
+ [m[o], m[o + 1], m[o + 2]],
470
+ [m[o + 3], m[o + 4], m[o + 5]],
471
+ [m[o + 6], m[o + 7], m[o + 8]],
472
+ ],
473
+ f,
474
+ j,
475
+ );
476
+ }
477
+ }
478
+ for (let i = 0; i < rootPos.length; i += 1) {
479
+ if (!Number.isFinite(rootPos[i])) throw new NpzError(`motion npz root_positions contains a non-finite value at index ${i}`);
480
+ }
481
+ for (let i = 0; i < posedJoints.length; i += 1) {
482
+ if (!Number.isFinite(posedJoints[i])) throw new NpzError(`motion npz posed_joints contains a non-finite value at index ${i}`);
483
+ }
484
+
485
+ return { frames, fps, rotMats, rootPos, posedJoints };
486
+ }
487
+
488
+ /**
489
+ * Fetch and decode a motion npz from the bridge's motionUrl.
490
+ *
491
+ * The download is size-capped (Content-Length when present, plus the actual
492
+ * body) and every decode error surfaces as an NpzError with a specific
493
+ * message; a missing/stale run id is a plain fetch error.
494
+ */
495
+ export async function loadMotionFromUrl(url, { signal } = {}) {
496
+ let res;
497
+ try {
498
+ res = await fetch(url, { signal });
499
+ } catch (err) {
500
+ throw new NpzError(`motion download failed: ${err?.message || String(err)}`);
501
+ }
502
+ if (!res.ok) {
503
+ throw new NpzError(`motion download failed (HTTP ${res.status})`);
504
+ }
505
+ const declared = Number(res.headers.get("content-length"));
506
+ if (Number.isFinite(declared) && declared > MAX_ARCHIVE_BYTES) {
507
+ throw new NpzError(`motion download is ${declared} bytes, over the ${MAX_ARCHIVE_BYTES} byte cap`);
508
+ }
509
+ let blob;
510
+ try {
511
+ blob = await res.blob();
512
+ } catch (err) {
513
+ throw new NpzError(`motion download failed: ${err?.message || String(err)}`);
514
+ }
515
+ if (blob.size > MAX_ARCHIVE_BYTES) {
516
+ throw new NpzError(`motion download is ${blob.size} bytes, over the ${MAX_ARCHIVE_BYTES} byte cap`);
517
+ }
518
+ const buffer = await blob.arrayBuffer();
519
+ return decodeMotionNpz(new Uint8Array(buffer));
520
+ }