Skip to content

Import a 3D Model and automatically assign and export animations

TypeScript

First pass at getting Zipped GLTF loaded

Scott Petrovic12219dfe2b2e
diff --git a/src/lib/processes/load-model/StepLoadModel.ts b/src/lib/processes/load-model/StepLoadModel.ts
index 41b0f2a..dedcd66 100644
--- a/src/lib/processes/load-model/StepLoadModel.ts
+++ b/src/lib/processes/load-model/StepLoadModel.ts
@@ -1,4 +1,5 @@
import { UI } from '../../UI.ts'
+import { ZipGLTFLoader } from './ZipGLTFLoader.ts'
import { Box3 } from 'three/src/math/Box3.js'
import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
import { FBXLoader } from 'three/examples/jsm/loaders/FBXLoader.js'
@@ -146,21 +147,42 @@ export class StepLoadModel extends EventTarget {
return file_extension
}
- private load_model_file (model_file_path: string, file_extension: string): void {
+ private load_model_file (model_file_path: string | ArrayBuffer | null, file_extension: string): void {
if (file_extension === 'fbx') {
console.log('Loading FBX model:', model_file_path)
- this.fbx_loader.load(model_file_path, (fbx) => {
+ this.fbx_loader.load(model_file_path as string, (fbx) => {
const loaded_scene: Scene = new Scene()
loaded_scene.add(fbx)
this.process_loaded_scene(loaded_scene)
})
} else if (file_extension === 'glb') {
- this.gltf_loader.load(model_file_path, (gltf) => {
+ this.gltf_loader.load(model_file_path as string, (gltf) => {
const loaded_scene: Scene = gltf.scene
this.process_loaded_scene(loaded_scene)
})
} else if (file_extension === 'zip') {
- console.log('try to load a GLTF file with separate BIN file from ZIP')
+ // Use ZipGLTFLoader for ZIP files
+ const handle_zip = (buffer: ArrayBuffer): void => {
+ const zip_loader = new ZipGLTFLoader(this.gltf_loader)
+
+ zip_loader.loadFromZip(buffer, (scene) => {
+ this.process_loaded_scene(scene)
+ }, (err) => {
+ console.error('Failed to load GLTF from ZIP:', err)
+ }).catch((err) => { console.error('Error loading ZIP:', err) })
+ }
+
+ if (typeof model_file_path === 'string' && model_file_path.startsWith('data:')) {
+ fetch(model_file_path)
+ .then(async res => await res.arrayBuffer())
+ .then(buffer => { handle_zip(buffer) })
+ .catch(err => { console.error('Failed to fetch ZIP data:', err) })
+ } else if (model_file_path instanceof ArrayBuffer) {
+ handle_zip(model_file_path)
+ } else {
+ console.error('ZIP file data is not in a supported format')
+ }
+ // end logic for handing zip
} else {
console.error('Unsupported file format to load. Only acccepts FBX, (ZIP)GLTF+BIN, GLB:', model_file_path)
}
diff --git a/src/lib/processes/load-model/ZipGLTFLoader.ts b/src/lib/processes/load-model/ZipGLTFLoader.ts
new file mode 100644
index 0000000..a6e4982
--- /dev/null
+++ b/src/lib/processes/load-model/ZipGLTFLoader.ts
@@ -0,0 +1,88 @@
+import JSZip from 'jszip'
+import { type GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js'
+import { type Scene } from 'three/src/scenes/Scene.js'
+
+/**
+ * Loads a GLTF (with BIN and textures) from a ZIP file buffer, using in-memory URLs for all assets.
+ * Usage: new ZipGLTFLoader(gltfLoaderInstance).loadFromZip(zipBuffer, (scene) => { ... })
+ */
+export class ZipGLTFLoader {
+ private readonly loader: GLTFLoader
+
+ constructor (loader: GLTFLoader) {
+ this.loader = loader
+ }
+
+ async loadFromZip (zipData: ArrayBuffer, onLoad: (scene: Scene) => void, onError?: (err: any) => void): Promise<void> {
+ try {
+ const zip = await JSZip.loadAsync(zipData)
+ let gltf_file: any = null
+ let bin_file: any = null
+ let gltf_filename = ''
+ let bin_filename = ''
+ zip.forEach((relativePath, file) => {
+ const lower = relativePath.toLowerCase()
+ if (lower.endsWith('.gltf')) {
+ gltf_file = file
+ gltf_filename = relativePath
+ } else if (lower.endsWith('.bin')) {
+ bin_file = file
+ bin_filename = relativePath
+ }
+ })
+ if (!gltf_file) {
+ throw new Error('No GLTF file found in ZIP')
+ }
+ const gltf_text = await gltf_file.async('text')
+ const gltf_json = JSON.parse(gltf_text)
+ if (bin_file && gltf_json.buffers && gltf_json.buffers[0]) {
+ const binNameOnly = bin_filename.split('/').pop()
+ gltf_json.buffers[0].uri = binNameOnly
+ }
+ // Map all relevant files by filename only
+ const fileMap: Record<string, Uint8Array> = {}
+ const filePromises = Object.keys(zip.files).map(async (filename) => {
+ const file = zip.files[filename]
+ if (!file.dir) {
+ const nameOnly = filename.split('/').pop() ?? filename
+ if (/\.(bin|gltf|png|jpg|jpeg|webp)$/i.test(nameOnly)) {
+ fileMap[nameOnly] = new Uint8Array(await file.async('arraybuffer'))
+ }
+ }
+ })
+ await Promise.all(filePromises)
+ // Patch loader to use in-memory blobs for all referenced files
+ this.loader.manager.setURLModifier((url: string) => {
+ const cleanUrl = url.split(/[?#]/)[0]
+ const nameOnly = cleanUrl.split('/').pop() ?? cleanUrl
+ if (fileMap[nameOnly]) {
+ let mime = 'application/octet-stream'
+ if (/\.png$/i.test(nameOnly)) mime = 'image/png'
+ else if (/\.jpe?g$/i.test(nameOnly)) mime = 'image/jpeg'
+ else if (/\.webp$/i.test(nameOnly)) mime = 'image/webp'
+ else if (/\.gltf$/i.test(nameOnly)) mime = 'application/json'
+ const blob = new Blob([fileMap[nameOnly]], { type: mime })
+ return URL.createObjectURL(blob)
+ }
+ return url
+ })
+ // Load the GLTF from the in-memory JSON
+ const gltfBlob = new Blob([JSON.stringify(gltf_json)], { type: 'application/json' })
+ const gltfUrl = URL.createObjectURL(gltfBlob)
+ this.loader.load(
+ gltfUrl,
+ (gltf) => {
+ const loaded_scene: Scene = gltf.scene
+ onLoad(loaded_scene)
+ URL.revokeObjectURL(gltfUrl)
+ },
+ undefined,
+ (err) => {
+ if (onError != null) onError(err)
+ }
+ )
+ } catch (err) {
+ if (onError != null) onError(err)
+ }
+ }
+}