-
Notifications
You must be signed in to change notification settings - Fork 2
/
model-loader.js
264 lines (255 loc) · 8.13 KB
/
model-loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
import './GLTFLoader.js';
import './FBXLoader.js';
import './GLTFExporter.js';
import './SkeletonUtils.js';
import './inflate.min.js';
import './gunzip.min.js';
import './ProgressivePromise.js';
import './untar.js';
import './zip.js';
const basePath = import.meta.url.replace(/[^\/]*$/, '');
const _getFileType = filename => {
if (/\.(?:gltf|glb|vrm)$/.test(filename)) {
return 'gltf';
} else if (/\.fbx$/.test(filename)) {
return 'fbx';
} else if (/\.(?:tar\.gz|tgz|unitypackage)$/.test(filename)) {
return 'tgz';
} else if (/\.(?:zip)$/.test(filename)) {
return 'zip';
} else if (/\.(?:png|jpe?g)/) {
return 'img';
} else {
return null;
}
};
const _pathname2Filename = pathname => {
const match = pathname.match(/([^\/]+)$/);
return match && match[1];
};
const _filename2Ext = filename => {
const match = filename.match(/\.([^\.]+)$/);
return match ? match[1] : null;
};
const _patchModel = model => {
model.scene.traverse(o => {
if (o.isMesh) {
const materials = Array.isArray(o.material) ? o.material : [o.material];
for (let i = 0; i < materials.length; i++) {
const material = materials[i];
if (material.map && !material.map.image) {
material.map = null;
}
}
}
});
const saved = THREE.SkeletonUtils.clone(model.scene);
model.export = () => new Promise((accept, reject) => {
new THREE.GLTFExporter().parse(saved, ab => {
accept(ab);
}, {
binary: true,
});
});
};
const _loadModelFilesystem = async filesystem => {
const modelFiles = filesystem.filter(file => /\.(?:fbx|gltf|glb)/.test(file.pathname)).map(file => {
const pathnamePrefix = file.pathname.replace(/[^\/]+$/, '');
const numSiblingFiles = filesystem.filter(file => file.pathname.startsWith(pathnamePrefix)).length;
return {
file,
numSiblingFiles,
};
}).sort((a, b) => {
const diff = b.numSiblingFiles - a.numSiblingFiles;
if (diff !== 0) {
return diff;
} else {
return +/unity/i.test(b.file.filename) - +/unity/i.test(a.file.filename);
}
}).map(({file}) => file);
if (modelFiles.length > 0) {
const modelFile = modelFiles[0];
// console.log('got model file', modelFile);
const modelFileUrl = modelFile.url;
console.log(`using model file: ${modelFile.pathname}`);
const manager = new THREE.LoadingManager();
manager.setURLModifier(url => {
const match = url.match(/([^\/]+)$/);
if (match) {
const filename = match[1];
const file = filesystem.find(file => file.filename === filename);
if (file) {
url = file.url;
} else {
const ext = _filename2Ext(filename);
if (ext) {
const file = filesystem.find(file => file.ext === ext);
if (file) {
url = file.url;
}
}
}
}
return url;
});
const managerLoadPromise = _makeManagerLoadPromise(manager);
if (/\.fbx$/.test(modelFile.pathname)) {
const model = await new Promise((accept, reject) => {
new THREE.FBXLoader(manager).load(modelFileUrl, scene => {
accept({scene});
}, function onprogress() {}, reject);
});
await managerLoadPromise;
return model;
} else {
const model = await new Promise((accept, reject) => {
new THREE.GLTFLoader(manager).load(modelFileUrl, accept, xhr => {}, reject);
});
await managerLoadPromise;
return model;
}
} else {
throw new Error('no model file in package');
}
};
const _readAsArrayBuffer = blob => new Promise((accept, reject) => {
const reader = new FileReader();
reader.onload = () => {
accept(reader.result);
};
reader.onerror = reject;
reader.readAsArrayBuffer(blob);
});
const _makeManager = () => {
const manager = new THREE.LoadingManager();
const managerLoadPromise = _makeManagerLoadPromise(manager);
return {
manager,
managerLoadPromise,
};
};
const _makeManagerLoadPromise = manager => {
let accept, reject;
const p = new Promise((a, r) => {
accept = a;
reject = r;
});
manager.onLoad = () => {
accept();
};
return p;
};
const loadModelUrl = async (href, filename = href) => {
const fileType = _getFileType(filename);
if (fileType === 'gltf') {
const {manager, managerLoadPromise} = _makeManager();
const model = await new Promise((accept, reject) => {
new THREE.GLTFLoader(manager).load(href, accept, xhr => {}, reject);
});
await managerLoadPromise;
_patchModel(model);
return model;
} else if (fileType === 'fbx') {
const {manager, managerLoadPromise} = _makeManager();
const model = await new Promise((accept, reject) => {
new THREE.FBXLoader(manager).load(href, scene => {
accept({scene});
}, xhr => {}, reject);
});
await managerLoadPromise;
_patchModel(model);
return model;
} else if (fileType === 'zip') {
const unitypackageRes = await fetch(href);
const blob = await unitypackageRes.blob();
const reader = await new Promise((accept, reject) => {
zip.createReader(new zip.BlobReader(blob), accept, reject);
});
const entries = await new Promise((accept, reject) => {
reader.getEntries(accept);
});
const filesystem = [];
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
const pathname = entry.filename;
const filename = _pathname2Filename(pathname);
const ext = _filename2Ext(filename);
const blob = await new Promise((accept, reject) => {
entry.getData(new zip.BlobWriter('application/octet-stream'), accept, function onprogress(current, total) {});
});
const url = URL.createObjectURL(blob);
filesystem.push({
pathname,
filename,
ext,
url,
});
// console.log('got blob', entry, blob, pathname, filename, url);
}
// console.log('got filesystem', filesystem);
const model = await _loadModelFilesystem(filesystem);
_patchModel(model);
return model;
} else if (fileType === 'tgz') {
const unitypackageRes = await fetch(href);
const arraybuffer = await unitypackageRes.arrayBuffer();
const inflatedArrayBuffer = new Zlib.Gunzip(new Uint8Array(arraybuffer)).decompress().buffer;
const files = await untar(inflatedArrayBuffer);
// console.log('got files', files);
// window.files = files;
const filesystem = [];
for (let j = 0; j < files.length; j++) {
const file = files[j];
const {name} = file;
const match = name.match(/^([a-zA-Z0-9]+)\/pathname$/);
if (match) {
const pathname = new TextDecoder().decode(await _readAsArrayBuffer(file.blob));
const id = match[1];
const assetFileName = `${id}/asset`;
const assetFile = files.find(file => file.name === assetFileName);
if (assetFile) {
const filename = _pathname2Filename(pathname);
const url = assetFile.getBlobUrl();
filesystem.push({
pathname,
filename,
url,
});
}
}
}
const model = await _loadModelFilesystem(filesystem);
_patchModel(model);
return model;
} else if (fileType === 'img') {
const img = await new Promise((accept, reject) => {
const img = new Image();
img.onload = () => {
accept(img);
};
img.onerror = reject;
img.crossOrigin = 'Anonymous';
img.src = href;
});
const model = await new Promise((accept, reject) => {
new THREE.GLTFLoader().load(`${basePath}minecraft.glb`, accept, xhr => {}, reject);
});
const texture = new THREE.Texture(img, THREE.UVMapping, THREE.ClampToEdgeWrapping, THREE.ClampToEdgeWrapping, THREE.NearestFilter, THREE.LinearMipmapLinearFilter, THREE.RGBAFormat, THREE.UnsignedByteType, 16, THREE.LinearEncoding);
texture.flipY = false;
texture.needsUpdate = true;
model.scene.traverse(o => {
if (o.isSkinnedMesh) {
o.material.map = texture;
}
});
_patchModel(model);
return model;
} else {
throw new Error(`unknown file type: ${filename} (${fileType})`);
}
};
const ModelLoader = {
loadModelUrl,
};
export default ModelLoader;