Skip to content

Commit ddd9232

Browse files
authored
fix the parsing issue of glb files in model viewer (tscircuit#10)
1 parent 011e795 commit ddd9232

1 file changed

Lines changed: 17 additions & 3 deletions

File tree

lib/gltf/gltf-builder.ts

Lines changed: 17 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -696,7 +696,17 @@ export class GLTFBuilder {
696696
// JSON chunk
697697
// Binary chunk
698698

699-
const jsonString = JSON.stringify(gltf)
699+
// For GLB format, we need to add a buffer reference to the embedded binary data
700+
const gltfWithBuffer = {
701+
...gltf,
702+
buffers: [
703+
{
704+
byteLength: bufferData.byteLength,
705+
},
706+
],
707+
}
708+
709+
const jsonString = JSON.stringify(gltfWithBuffer)
700710
const jsonData = new TextEncoder().encode(jsonString)
701711

702712
// Pad JSON to 4-byte alignment
@@ -723,9 +733,13 @@ export class GLTFBuilder {
723733
view.setUint32(12, jsonLength, true) // chunk length
724734
view.setUint32(16, 0x4e4f534a, true) // chunk type "JSON"
725735

726-
// Copy JSON data
727-
const jsonArray = new Uint8Array(glb, 20, jsonData.length)
736+
// Copy JSON data and pad with spaces
737+
const jsonArray = new Uint8Array(glb, 20, jsonLength)
728738
jsonArray.set(jsonData)
739+
// Fill padding bytes with spaces (0x20) as required by GLB spec
740+
for (let i = jsonData.length; i < jsonLength; i++) {
741+
jsonArray[i] = 0x20
742+
}
729743

730744
// Binary chunk
731745
const binChunkOffset = 20 + jsonLength

0 commit comments

Comments
 (0)