import { inflate } from './muse-inflate.js'; export const MUSE_FBX_READER_VERSION = 'muse-fbx-reader-1'; export function isBinaryFBX(buffer) { if (!(buffer instanceof ArrayBuffer)) return false; const view = new Uint8Array(buffer, 0, 21); const txt = new TextDecoder('latin1').decode(view); return txt.startsWith('Kaydara FBX Binary'); // [w2 coach] header is 21 bytes with a NUL, the draft compared 20 chars } export function nodeFind(node, name) { if (!node || !node.children) return null; for (const c of node.children) if (c.name === name) return c; return null; } export function nodeFindAll(node, name) { const out = []; if (!node || !node.children) return out; for (const c of node.children) { if (c.name === name) out.push(c); out.push(...nodeFindAll(c, name)); } return out; } export function propValue(node, index = 0) { if (!node || !node.props) return undefined; return node.props[index]; } function readU32(view, off) { return view.getUint32(off, true); } function readU16(view, off) { return view.getUint16(off, true); } function readI16(view, off) { return view.getInt16(off, true); } function readI32(view, off) { return view.getInt32(off, true); } function readF32(view, off) { return view.getFloat32(off, true); } function readF64(view, off) { return view.getFloat64(off, true); } function readU64AsNumber(view, off) { const lo = view.getUint32(off, true); const hi = view.getUint32(off + 4, true); return hi * 4294967296 + lo; } function decodeLatin1(bytes) { return new TextDecoder('latin1').decode(bytes); } function decodeString(bytes) { try { return new TextDecoder('utf-8').decode(bytes); } catch { return decodeLatin1(bytes); } } function parseBinaryNode(view, offset, version, bufferLength) { const endOffset = version < 7500 ? readU32(view, offset) : readU64AsNumber(view, offset); const numProps = version < 7500 ? readU32(view, offset + 4) : readU64AsNumber(view, offset + 8); const propListLen = version < 7500 ? readU32(view, offset + 8) : readU64AsNumber(view, offset + 16); let pos = version < 7500 ? offset + 12 : offset + 24; if (endOffset === 0) { return { node: null, nextPos: pos, endOffset }; } if (endOffset > bufferLength) throw new Error('FBX file is truncated'); const nameLen = view.getUint8(pos); pos += 1; const nameBytes = new Uint8Array(view.buffer, view.byteOffset + pos, nameLen); const name = decodeLatin1(nameBytes); pos += nameLen; const props = []; for (let i = 0; i < numProps; i++) { const type = decodeLatin1(new Uint8Array(view.buffer, view.byteOffset + pos, 1)); pos += 1; if (type === 'Y') { props.push(readI16(view, pos)); pos += 2; } else if (type === 'C') { props.push(view.getUint8(pos) !== 0); pos += 1; } else if (type === 'I') { props.push(readI32(view, pos)); pos += 4; } else if (type === 'F') { props.push(readF32(view, pos)); pos += 4; } else if (type === 'D') { props.push(readF64(view, pos)); pos += 8; } else if (type === 'L') { const lo = view.getUint32(pos, true); const hi = view.getInt32(pos + 4, true); const num = hi * 4294967296 + lo; props.push(num); pos += 8; } else if (type === 'S') { const len = readU32(view, pos); pos += 4; const bytes = new Uint8Array(view.buffer, view.byteOffset + pos, len); props.push(decodeString(bytes)); pos += len; } else if (type === 'R') { const len = readU32(view, pos); pos += 4; const bytes = new Uint8Array(view.buffer, view.byteOffset + pos, len); props.push(bytes.slice()); pos += len; } else if (type === 'f' || type === 'd' || type === 'l' || type === 'i' || type === 'b') { const arrayLength = readU32(view, pos); pos += 4; const encoding = readU32(view, pos); pos += 4; const compressedLength = readU32(view, pos); pos += 4; const dataStart = pos; const dataLen = encoding === 1 ? compressedLength : arrayLength * (type === 'f' ? 4 : type === 'd' ? 8 : type === 'l' ? 8 : type === 'i' ? 4 : 1); // [w2 coach] FBX array data is not aligned, so copy it before making typed-array views; 'l' (int64) is read through DataView const raw = new Uint8Array(view.buffer, view.byteOffset + pos, dataLen); pos += dataLen; if (encoding === 0) { props.push(decodeArray(type, raw.slice(), arrayLength)); } else { props.push({ __z: true, type, length: arrayLength, bytes: raw.slice() }); } } else { props.push(null); } } const children = []; let childPos = pos; while (childPos < endOffset) { const childRes = parseBinaryNode(view, childPos, version, bufferLength); if (!childRes.node) break; children.push(childRes.node); childPos = childRes.nextPos; } const node = { name, props, children }; const nextPos = endOffset; return { node, nextPos, endOffset }; } function decodeArray(type, bytes, n) { const buf = bytes.buffer; if (type === 'f') return new Float32Array(buf, bytes.byteOffset, n); if (type === 'd') return new Float64Array(buf, bytes.byteOffset, n); if (type === 'i') return new Int32Array(buf, bytes.byteOffset, n); if (type === 'l') { const dv = new DataView(buf, bytes.byteOffset, n * 8), out = new Float64Array(n); for (let i = 0; i < n; i++) out[i] = dv.getInt32(i * 8 + 4, true) * 4294967296 + dv.getUint32(i * 8, true); return out; } const out = new Array(n); for (let i = 0; i < n; i++) out[i] = bytes[i] !== 0; return out; } function inflateCompressed(placeholders) { // [w2 coach] own synchronous zlib decoder (muse-inflate.js) const size = { f: 4, d: 8, l: 8, i: 4, b: 1 }; return placeholders.map((ph) => decodeArray(ph.type, inflate(ph.bytes, ph.length * size[ph.type]), ph.length)); } function collectPlaceholders(node, out) { if (!node) return; for (const p of node.props) { if (p && typeof p === 'object' && p.__z) out.push(p); } for (const c of node.children) collectPlaceholders(c, out); } function replacePlaceholders(node, it) { if (!node) return; for (let i = 0; i < node.props.length; i++) { const p = node.props[i]; if (p && typeof p === 'object' && p.__z) { node.props[i] = it.next().value; } } for (const c of node.children) replacePlaceholders(c, it); } async function readBinaryFBX(buffer) { const view = new DataView(buffer); if (!isBinaryFBX(buffer)) throw new Error('Unknown format: not an FBX file'); const version = readU32(view, 23); const root = { name: '', props: [], children: [] }; let pos = 27; const bufferLength = buffer.byteLength; while (pos < bufferLength) { const res = parseBinaryNode(view, pos, version, bufferLength); if (!res.node) break; root.children.push(res.node); pos = res.nextPos; } const placeholders = []; collectPlaceholders(root, placeholders); if (placeholders.length) { const inflated = inflateCompressed(placeholders); const it = inflated[Symbol.iterator](); replacePlaceholders(root, it); } return { version, root }; } // [w2 coach] ASCII FBX reader rewritten (the draft could not nest nodes or read multi-line "a:" arrays). function splitProps(str) { const out = []; let i = 0; const n = str.length; while (i < n) { const ch = str[i]; if (ch === ' ' || ch === '\t' || ch === ',') { i++; continue; } if (ch === '"') { let j = i + 1; while (j < n && str[j] !== '"') j++; out.push(str.slice(i + 1, j)); i = j + 1; continue; } if (ch === '*') { let j = i + 1; while (j < n && str[j] !== ',' && str[j] !== ' ') j++; i = j; continue; } // array length marker, not a value let j = i; while (j < n && str[j] !== ',') j++; const tok = str.slice(i, j).trim(); i = j; if (tok === '') continue; const c = tok.charCodeAt(0); out.push((c >= 48 && c <= 57) || c === 45 || c === 43 || c === 46 ? Number(tok) : tok); } return out; } function parseAsciiFBX(text) { if (!text.includes('FBXHeaderExtension') && !text.includes('; FBX')) throw new Error('Unknown format: not an FBX file'); let version = 0; const versionMatch = text.match(/FBXVersion:\s*(\d+)/); if (versionMatch) version = parseInt(versionMatch[1], 10); const lines = text.split(/\r?\n/); const root = { name: '', props: [], children: [] }; const stack = [root]; for (let i = 0; i < lines.length; i++) { const line = lines[i].trim(); if (!line || line.charCodeAt(0) === 59) continue; // blank or ';' comment if (line === '}') { if (stack.length > 1) stack.pop(); continue; } const colon = line.indexOf(':'); if (colon < 0) continue; const name = line.slice(0, colon).trim(); let rest = line.slice(colon + 1).trim(); if (name === 'a' && stack.length > 1) { // numeric array body, may continue over several lines up to the closing brace let buf = rest; while (i + 1 < lines.length && lines[i + 1].trim() !== '}') { i++; buf += lines[i].trim(); } const parts = buf.split(','); const arr = new Float64Array(parts.length); let k = 0; for (const t of parts) { if (t.length) arr[k++] = Number(t); } stack[stack.length - 1].props.push(k === arr.length ? arr : arr.slice(0, k)); continue; } const open = rest.endsWith('{'); if (open) rest = rest.slice(0, -1).trim(); const node = { name, props: splitProps(rest), children: [] }; stack[stack.length - 1].children.push(node); if (open) stack.push(node); } return { version, root }; } export async function readFBX(input) { if (typeof input === 'string') { return parseAsciiFBX(input); } if (input instanceof ArrayBuffer) { if (isBinaryFBX(input)) return await readBinaryFBX(input); return parseAsciiFBX(new TextDecoder('utf-8').decode(input)); // [w2 coach] ASCII FBX arrives as bytes too } throw new Error('Unknown format: not an FBX file'); }