@coda-console/resource-manager 0.9.0 → 0.9.2
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.
- package/README.md +5 -2
- package/lib/media.mjs +12 -8
- package/package.json +3 -2
- package/view/model3d.mjs +85 -0
- package/view/preview.mjs +46 -11
- package/view/protocol.mjs +14 -1
- package/view/style.css +15 -0
- package/view/vendor/three/LICENSE +21 -0
- package/view/vendor/three/VERSION +1 -0
- package/view/vendor/three/build/three.core.mjs +61162 -0
- package/view/vendor/three/build/three.module.mjs +19537 -0
- package/view/vendor/three/jsm/controls/OrbitControls.mjs +1985 -0
- package/view/vendor/three/jsm/environments/RoomEnvironment.mjs +185 -0
- package/view/vendor/three/jsm/libs/fflate.module.mjs +2699 -0
- package/view/vendor/three/jsm/loaders/3MFLoader.mjs +1826 -0
- package/view/vendor/three/jsm/loaders/GLTFLoader.mjs +5006 -0
- package/view/vendor/three/jsm/loaders/MTLLoader.mjs +601 -0
- package/view/vendor/three/jsm/loaders/OBJLoader.mjs +961 -0
- package/view/vendor/three/jsm/loaders/PLYLoader.mjs +992 -0
- package/view/vendor/three/jsm/loaders/STLLoader.mjs +423 -0
- package/view/vendor/three/jsm/utils/BufferGeometryUtils.mjs +1523 -0
- package/view/vendor/three/jsm/utils/SkeletonUtils.mjs +496 -0
- package/view/viewer3d.mjs +372 -0
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
// 3D 模型查看器(设计见 docs/design/phase-3.md 第 21 节)。three.js 只在打开模型时动态导入,不影响侧栏启动。
|
|
2
|
+
// 字节经模块的流式服务取(coda-view://service/media/<口令>/…),自己 fetch、自己 parse。
|
|
3
|
+
// 按需渲染:控件变化、尺寸变化、加载完成(和贴图晚到)时画一帧;有动画并在播放时才连续渲染(是否连续只看 createPlayback)。
|
|
4
|
+
// 释放登记在 held 里,建一个登记一个,中途失败、中途切走也释放得干净。
|
|
5
|
+
import { h } from './dom.mjs';
|
|
6
|
+
import { formatSize } from './format.mjs';
|
|
7
|
+
import { BIG_FILE, Z_UP, createPlayback, directoryUrl, extensionOf, gltfJson, joinRelative, mtllibOf, plyFaceCount, serviceUrl, unsupportedExtensions } from './model3d.mjs';
|
|
8
|
+
|
|
9
|
+
const VENDOR = './vendor/three';
|
|
10
|
+
|
|
11
|
+
// 带标题的错误:标题和说明显示在模型位置。
|
|
12
|
+
class Friendly extends Error {
|
|
13
|
+
constructor(title, detail = '') { super(detail || title); this.title = title; this.detail = detail; }
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
const count = value => value.toLocaleString('zh-CN');
|
|
17
|
+
const mib = n => `${(n / 1048576).toFixed(1)} MiB`;
|
|
18
|
+
|
|
19
|
+
// 页面里用的实现;测试用 env 换掉(假的 three 渲染器、手动的帧、可控的 fetch)。
|
|
20
|
+
const browser = {
|
|
21
|
+
engine: { three: () => import(`${VENDOR}/build/three.module.mjs`), module: name => import(`${VENDOR}/jsm/${name}.mjs`) },
|
|
22
|
+
fetch: (...args) => fetch(...args),
|
|
23
|
+
raf: fn => requestAnimationFrame(fn),
|
|
24
|
+
caf: id => cancelAnimationFrame(id),
|
|
25
|
+
now: () => performance.now(),
|
|
26
|
+
paint: () => new Promise(go => requestAnimationFrame(go)), // 让「解析中」先画出来,再进入会卡住页面的解析
|
|
27
|
+
// 不创建任何会长期占用的东西:开个临时的 webgl2 上下文问一遍,马上放掉。
|
|
28
|
+
hasWebGL() {
|
|
29
|
+
let gl = null;
|
|
30
|
+
try { gl = document.createElement('canvas').getContext('webgl2'); } catch { /* 当作没有 */ }
|
|
31
|
+
gl?.getExtension('WEBGL_lose_context')?.loseContext();
|
|
32
|
+
return gl !== null;
|
|
33
|
+
},
|
|
34
|
+
reducedMotion: () => typeof matchMedia !== 'function' || matchMedia('(prefers-reduced-motion: reduce)').matches, // 拿不到 matchMedia 按减弱处理,同页面其他动画
|
|
35
|
+
};
|
|
36
|
+
|
|
37
|
+
// 在 body 里挂一个模型视图。size 是文件大小(超过 64 MiB 先问);onMeta(parts):把「N 面」「K 段动画」交给预览头部的元信息行。
|
|
38
|
+
// 返回 { cancel, dispose }:cancel 只停加载和动画循环(预览逻辑关闭时),dispose 释放一切(画面退场后)。
|
|
39
|
+
export function mountViewer({ body, token, path, size, version, onMeta = () => {}, env = {} }) {
|
|
40
|
+
const { engine, fetch: get, raf, caf, now, paint, hasWebGL, reducedMotion } = { ...browser, ...env };
|
|
41
|
+
const ext = extensionOf(path);
|
|
42
|
+
|
|
43
|
+
const status = h('div', { class: 'mstatus' });
|
|
44
|
+
const resetButton = h('button', { class: 'mbtn mreset', hidden: true }, '复位视角');
|
|
45
|
+
const playButton = h('button', { class: 'mbtn' }, '暂停');
|
|
46
|
+
const clipSelect = h('select', { class: 'mclip', 'aria-label': '动画' });
|
|
47
|
+
const bar = h('div', { class: 'mbar', hidden: true }, playButton, clipSelect);
|
|
48
|
+
const stage = h('div', { class: 'mstage' }, status, resetButton, bar);
|
|
49
|
+
body.classList.add('model');
|
|
50
|
+
body.replaceChildren(h('div', { class: 'mview' }, stage));
|
|
51
|
+
|
|
52
|
+
const abort = new AbortController();
|
|
53
|
+
let dead = false, disposed = false, gate = null, playback = null, requestRender = () => {}, sync = () => {};
|
|
54
|
+
const held = { wrapper: null, canvas: null, renderer: null, controls: null, observer: null, frame: 0, mixer: null, envTarget: null, manager: null };
|
|
55
|
+
const stopFrame = () => { if (held.frame) caf(held.frame); held.frame = 0; };
|
|
56
|
+
// dead:停止(cancel)或失败(release)之后的终态:requestRender 和帧不再排帧(停止时画面留着,只是不再画),playback 也停了,其余入口(可见性、sync)自然落空。
|
|
57
|
+
const onVisibility = () => { playback?.setVisible(!document.hidden); sync(); if (!document.hidden) requestRender(); };
|
|
58
|
+
document.addEventListener('visibilitychange', onVisibility);
|
|
59
|
+
const release = () => {
|
|
60
|
+
dead = true;
|
|
61
|
+
playback?.stop();
|
|
62
|
+
if (held.manager) held.manager.onLoad = undefined;
|
|
63
|
+
document.removeEventListener('visibilitychange', onVisibility);
|
|
64
|
+
stopFrame();
|
|
65
|
+
held.observer?.disconnect();
|
|
66
|
+
held.controls?.dispose();
|
|
67
|
+
if (held.mixer) { held.mixer.stopAllAction(); held.mixer.uncacheRoot(held.mixer.getRoot()); }
|
|
68
|
+
held.envTarget?.dispose();
|
|
69
|
+
if (held.wrapper) disposeObject(held.wrapper);
|
|
70
|
+
held.renderer?.dispose();
|
|
71
|
+
held.renderer?.forceContextLoss();
|
|
72
|
+
if (held.canvas) { held.canvas.width = held.canvas.height = 0; held.canvas.remove(); } // 连画布的后备存储一起还掉(iOS 上不还会攒着)
|
|
73
|
+
Object.assign(held, { wrapper: null, canvas: null, renderer: null, controls: null, observer: null, mixer: null, envTarget: null, manager: null });
|
|
74
|
+
};
|
|
75
|
+
const say = (text, ...extra) => { status.hidden = false; status.replaceChildren(h('p', {}, text), ...extra.filter(Boolean)); }; // 真 DOM 的 replaceChildren 会把 null 变成文字「null」
|
|
76
|
+
const fail = (title, detail) => {
|
|
77
|
+
resetButton.hidden = bar.hidden = true;
|
|
78
|
+
say(title, detail ? h('p', { class: 'secondary caption' }, detail) : null);
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
// 整份读进一个预先按 content-length 分配的缓冲区,边读边报进度。
|
|
82
|
+
async function download(url, label, progress) {
|
|
83
|
+
let res;
|
|
84
|
+
try { res = await get(url, { signal: abort.signal }); } catch (error) {
|
|
85
|
+
if (dead) throw error;
|
|
86
|
+
throw new Friendly('取不到模型文件', `${label}:${error?.message ?? error}`);
|
|
87
|
+
}
|
|
88
|
+
if (!res.ok) throw new Friendly('取不到模型文件', `${label}:HTTP ${res.status}`);
|
|
89
|
+
const total = Number(res.headers.get('content-length')) || 0;
|
|
90
|
+
if (!(res.body && total)) return new Uint8Array(await res.arrayBuffer());
|
|
91
|
+
let bytes = new Uint8Array(total), got = 0;
|
|
92
|
+
const reader = res.body.getReader();
|
|
93
|
+
for (;;) {
|
|
94
|
+
const { done, value } = await reader.read();
|
|
95
|
+
if (done) break;
|
|
96
|
+
if (got + value.length > bytes.length) { const grown = new Uint8Array(got + value.length); grown.set(bytes.subarray(0, got)); bytes = grown; }
|
|
97
|
+
bytes.set(value, got);
|
|
98
|
+
got += value.length;
|
|
99
|
+
progress?.(got, total);
|
|
100
|
+
}
|
|
101
|
+
return got === bytes.length ? bytes : bytes.slice(0, got);
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function run() {
|
|
105
|
+
// 1. WebGL 能不能用:不行就不必加载库。
|
|
106
|
+
if (!hasWebGL()) throw new Friendly('这台设备不能显示 3D 模型', '没有 WebGL 2');
|
|
107
|
+
// 2. 太大的先问。
|
|
108
|
+
if (size > BIG_FILE) {
|
|
109
|
+
await new Promise(go => { gate = go; say(`这个模型有 ${formatSize(size)},加载可能耗尽这台设备的内存。`, h('button', { class: 'link', onclick: () => go() }, '仍然加载')); });
|
|
110
|
+
gate = null;
|
|
111
|
+
if (dead) return;
|
|
112
|
+
}
|
|
113
|
+
// 3. 加载库(动态导入,侧栏启动时不碰)。
|
|
114
|
+
say('加载 3D 库…');
|
|
115
|
+
const [THREE, { OrbitControls }, { RoomEnvironment }] = await Promise.all([engine.three(), engine.module('controls/OrbitControls'), engine.module('environments/RoomEnvironment')]);
|
|
116
|
+
if (dead) return;
|
|
117
|
+
// 4. 下载。
|
|
118
|
+
let lastPaint = 0;
|
|
119
|
+
let bytes = await download(serviceUrl(token, path, version), path, (got, total) => {
|
|
120
|
+
if (now() - lastPaint > 150) { lastPaint = now(); say(`下载中 ${mib(got)} / ${mib(total)}`); }
|
|
121
|
+
});
|
|
122
|
+
if (dead) return;
|
|
123
|
+
// 5. 解析(在主线程)。
|
|
124
|
+
say('解析中…');
|
|
125
|
+
await paint();
|
|
126
|
+
if (dead) return;
|
|
127
|
+
const manager = new THREE.LoadingManager();
|
|
128
|
+
let parsed;
|
|
129
|
+
try { parsed = await parseModel({ THREE, engine, manager, bytes, ext, token, path, download }); } catch (error) {
|
|
130
|
+
if (dead || error instanceof Friendly) throw error;
|
|
131
|
+
throw new Friendly('模型解析失败', String(error?.message ?? error));
|
|
132
|
+
}
|
|
133
|
+
bytes = null;
|
|
134
|
+
if (dead) { disposeObject(parsed.object); return; }
|
|
135
|
+
|
|
136
|
+
// 6. 场景和首帧。到这里以后不再有 await,建一个登记一个。
|
|
137
|
+
const wrapper = new THREE.Group();
|
|
138
|
+
held.wrapper = wrapper;
|
|
139
|
+
wrapper.add(parsed.object);
|
|
140
|
+
if (Z_UP.has(ext)) wrapper.rotation.x = -Math.PI / 2;
|
|
141
|
+
wrapper.updateMatrixWorld(true);
|
|
142
|
+
const box = new THREE.Box3().setFromObject(wrapper);
|
|
143
|
+
if (box.isEmpty()) throw new Friendly('模型里没有可显示的几何体');
|
|
144
|
+
const stats = measure(wrapper);
|
|
145
|
+
const clips = parsed.animations;
|
|
146
|
+
|
|
147
|
+
const canvas = h('canvas', { class: 'mcanvas' });
|
|
148
|
+
held.canvas = canvas;
|
|
149
|
+
let renderer;
|
|
150
|
+
try { renderer = held.renderer = new THREE.WebGLRenderer({ canvas, antialias: true, alpha: true, powerPreference: 'high-performance' }); } catch (error) {
|
|
151
|
+
throw new Friendly('这台设备不能显示 3D 模型', `创建 WebGL 渲染器失败:${error?.message ?? error}`);
|
|
152
|
+
}
|
|
153
|
+
renderer.setPixelRatio(Math.min(globalThis.devicePixelRatio ?? 1, 2));
|
|
154
|
+
const scene = new THREE.Scene();
|
|
155
|
+
const camera = new THREE.PerspectiveCamera(45, 1, 0.1, 1000);
|
|
156
|
+
scene.add(camera);
|
|
157
|
+
// 环境光:RoomEnvironment 烤成一张环境贴图,金属材质才不发黑;再加一盏跟着相机走的主光,转到哪一面都有光。
|
|
158
|
+
const pmrem = new THREE.PMREMGenerator(renderer), room = new RoomEnvironment();
|
|
159
|
+
held.envTarget = pmrem.fromScene(room, 0.04);
|
|
160
|
+
scene.environment = held.envTarget.texture;
|
|
161
|
+
scene.environmentIntensity = 0.6; // 默认的 1 会把中性灰的亮面照成一片白
|
|
162
|
+
room.dispose();
|
|
163
|
+
pmrem.dispose();
|
|
164
|
+
const key = new THREE.DirectionalLight(0xffffff, 0.8);
|
|
165
|
+
key.position.set(1, 1.5, 1);
|
|
166
|
+
camera.add(key);
|
|
167
|
+
scene.add(wrapper);
|
|
168
|
+
stage.prepend(canvas);
|
|
169
|
+
const controls = held.controls = new OrbitControls(camera, canvas);
|
|
170
|
+
controls.enableDamping = false; // 阻尼需要常驻循环,这里只在播放动画时才有循环
|
|
171
|
+
|
|
172
|
+
const sphere = box.getBoundingSphere(new THREE.Sphere());
|
|
173
|
+
const radius = Math.max(sphere.radius, 1e-6), center = sphere.center.clone();
|
|
174
|
+
const resize = () => {
|
|
175
|
+
const w = Math.max(1, stage.clientWidth), height = Math.max(1, stage.clientHeight);
|
|
176
|
+
renderer.setSize(w, height, false);
|
|
177
|
+
camera.aspect = w / height;
|
|
178
|
+
camera.updateProjectionMatrix();
|
|
179
|
+
};
|
|
180
|
+
const fit = () => {
|
|
181
|
+
const vfov = camera.fov * Math.PI / 180, hfov = 2 * Math.atan(Math.tan(vfov / 2) * camera.aspect);
|
|
182
|
+
const distance = radius / Math.sin(Math.min(vfov, hfov) / 2) * 1.1;
|
|
183
|
+
camera.near = radius / 100; camera.far = distance + radius * 100;
|
|
184
|
+
camera.updateProjectionMatrix();
|
|
185
|
+
camera.position.copy(center).addScaledVector(new THREE.Vector3(1, 0.7, 1).normalize(), distance);
|
|
186
|
+
controls.target.copy(center);
|
|
187
|
+
controls.minDistance = radius * 0.05; controls.maxDistance = radius * 30;
|
|
188
|
+
controls.update();
|
|
189
|
+
};
|
|
190
|
+
|
|
191
|
+
// 动画:只有播放时才连续渲染。
|
|
192
|
+
playback = createPlayback({ clips: clips.length, reducedMotion: reducedMotion() });
|
|
193
|
+
playback.setVisible(!document.hidden);
|
|
194
|
+
let last = 0;
|
|
195
|
+
const playClip = index => {
|
|
196
|
+
held.mixer.stopAllAction();
|
|
197
|
+
held.mixer.clipAction(clips[index]).reset().play();
|
|
198
|
+
held.mixer.update(0); // 先摆到第 0 帧的姿势
|
|
199
|
+
};
|
|
200
|
+
const paintBar = () => {
|
|
201
|
+
bar.hidden = clips.length === 0;
|
|
202
|
+
clipSelect.hidden = clips.length < 2;
|
|
203
|
+
playButton.textContent = playback.playing ? '暂停' : '播放';
|
|
204
|
+
clipSelect.value = String(playback.clip);
|
|
205
|
+
};
|
|
206
|
+
const frame = () => {
|
|
207
|
+
held.frame = 0;
|
|
208
|
+
if (dead) return;
|
|
209
|
+
const t = now();
|
|
210
|
+
if (playback.running) { held.mixer.update((t - last) / 1000); last = t; }
|
|
211
|
+
try { renderer.render(scene, camera); } catch (error) {
|
|
212
|
+
// 贴图晚到后上传失败(比如跨源的贴图被污染)会在这里抛。
|
|
213
|
+
release();
|
|
214
|
+
return fail('渲染出错', String(error?.message ?? error));
|
|
215
|
+
}
|
|
216
|
+
if (playback.running) held.frame = raf(frame);
|
|
217
|
+
};
|
|
218
|
+
requestRender = () => { if (!held.frame && !dead) held.frame = raf(frame); };
|
|
219
|
+
sync = () => {
|
|
220
|
+
if (playback.running) { if (!held.frame) { last = now(); held.frame = raf(frame); } } else stopFrame();
|
|
221
|
+
};
|
|
222
|
+
if (clips.length) {
|
|
223
|
+
held.mixer = new THREE.AnimationMixer(parsed.object);
|
|
224
|
+
for (const [index, clip] of clips.entries()) clipSelect.append(h('option', { value: String(index) }, clip.name || `动画 ${index + 1}`));
|
|
225
|
+
playClip(0);
|
|
226
|
+
playButton.addEventListener('click', () => { playback.toggle(); paintBar(); sync(); });
|
|
227
|
+
clipSelect.addEventListener('change', () => { playback.select(Number(clipSelect.value)); playClip(playback.clip); paintBar(); sync(); requestRender(); });
|
|
228
|
+
paintBar();
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
resize();
|
|
232
|
+
fit();
|
|
233
|
+
controls.addEventListener('change', requestRender);
|
|
234
|
+
held.observer = new ResizeObserver(() => { resize(); requestRender(); });
|
|
235
|
+
held.observer.observe(stage);
|
|
236
|
+
canvas.addEventListener('webglcontextlost', event => {
|
|
237
|
+
event.preventDefault();
|
|
238
|
+
if (dead) return;
|
|
239
|
+
release();
|
|
240
|
+
fail('WebGL 上下文丢失', '系统收回了显卡资源(可能同时开了太多 3D 页面),关掉再打开');
|
|
241
|
+
});
|
|
242
|
+
held.manager = manager;
|
|
243
|
+
manager.onLoad = () => requestRender(); // 贴图晚到(obj 的 mtl 里的贴图):到了就重画
|
|
244
|
+
|
|
245
|
+
renderer.render(scene, camera);
|
|
246
|
+
onMeta([stats.triangles > 0 || stats.points === 0 ? `${count(stats.triangles)} 面` : `${count(stats.points)} 个点`, clips.length ? `${clips.length} 段动画` : '']);
|
|
247
|
+
status.hidden = true;
|
|
248
|
+
resetButton.hidden = false;
|
|
249
|
+
resetButton.addEventListener('click', () => { fit(); requestRender(); });
|
|
250
|
+
sync();
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
run().catch(error => {
|
|
254
|
+
if (dead) return;
|
|
255
|
+
release(); // 失败了就不占着显卡
|
|
256
|
+
if (error instanceof Friendly) return fail(error.title, error.detail);
|
|
257
|
+
fail('加载出错', String(error?.message ?? error));
|
|
258
|
+
});
|
|
259
|
+
|
|
260
|
+
const cancel = () => { dead = true; abort.abort(); gate?.(); playback?.stop(); stopFrame(); };
|
|
261
|
+
return {
|
|
262
|
+
cancel,
|
|
263
|
+
dispose() {
|
|
264
|
+
if (disposed) return;
|
|
265
|
+
cancel();
|
|
266
|
+
disposed = true;
|
|
267
|
+
release();
|
|
268
|
+
body.classList.remove('model');
|
|
269
|
+
},
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
// 按格式解析成 three 的对象。返回 { object, animations };失败抛 Friendly 或原样的错误。
|
|
274
|
+
async function parseModel({ THREE, engine, manager, bytes, ext, token, path, download }) {
|
|
275
|
+
const neutral = () => new THREE.MeshStandardMaterial({ color: 0xb8bcc4, roughness: 0.65, metalness: 0.05, side: THREE.DoubleSide });
|
|
276
|
+
const exact = view => (view.byteOffset === 0 && view.byteLength === view.buffer.byteLength ? view.buffer : view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength));
|
|
277
|
+
const done = (object, animations = []) => ({ object, animations });
|
|
278
|
+
|
|
279
|
+
if (ext === 'glb' || ext === 'gltf') {
|
|
280
|
+
let json;
|
|
281
|
+
try { json = gltfJson(bytes, ext); } catch (error) { throw new Friendly('模型文件损坏,读不出来', error.message); }
|
|
282
|
+
const bad = unsupportedExtensions(json);
|
|
283
|
+
if (bad.length) throw new Friendly('这种压缩的模型不能预览', `用到了 ${bad.join('、')}`);
|
|
284
|
+
const { GLTFLoader } = await engine.module('loaders/GLTFLoader');
|
|
285
|
+
const data = ext === 'glb' ? exact(bytes) : new TextDecoder().decode(bytes);
|
|
286
|
+
const gltf = await new Promise((ok, no) => new GLTFLoader(manager).parse(data, directoryUrl(token, path), ok, no)).catch(error => { throw new Error(String(error?.message ?? error)); });
|
|
287
|
+
return done(gltf.scene, gltf.animations ?? []);
|
|
288
|
+
}
|
|
289
|
+
if (ext === 'stl') {
|
|
290
|
+
const { STLLoader } = await engine.module('loaders/STLLoader');
|
|
291
|
+
const geometry = new STLLoader(manager).parse(exact(bytes));
|
|
292
|
+
geometry.computeVertexNormals(); // 不信文件里的面法线:很多导出工具写成 0 0 0,会画成一片白;没有索引,算出来的是每个面自己的法线
|
|
293
|
+
const material = neutral();
|
|
294
|
+
if (geometry.hasColors === true) material.vertexColors = true;
|
|
295
|
+
return done(new THREE.Mesh(geometry, material));
|
|
296
|
+
}
|
|
297
|
+
if (ext === 'ply') {
|
|
298
|
+
const { PLYLoader } = await engine.module('loaders/PLYLoader');
|
|
299
|
+
const geometry = new PLYLoader(manager).parse(exact(bytes));
|
|
300
|
+
const colored = !!geometry.getAttribute('color');
|
|
301
|
+
if (plyFaceCount(bytes) === 0) { // 头里没有面:点云。不能看 geometry.index:带面级 texcoord 的 PLY 会被展开成没有索引的三角形
|
|
302
|
+
return done(new THREE.Points(geometry, new THREE.PointsMaterial({ size: 1, sizeAttenuation: false, vertexColors: colored, color: colored ? 0xffffff : 0xb8bcc4 })));
|
|
303
|
+
}
|
|
304
|
+
if (!geometry.getAttribute('normal')) geometry.computeVertexNormals();
|
|
305
|
+
const material = neutral();
|
|
306
|
+
if (colored) material.vertexColors = true;
|
|
307
|
+
return done(new THREE.Mesh(geometry, material));
|
|
308
|
+
}
|
|
309
|
+
if (ext === 'obj') {
|
|
310
|
+
const { OBJLoader } = await engine.module('loaders/OBJLoader');
|
|
311
|
+
const text = new TextDecoder().decode(bytes);
|
|
312
|
+
const loader = new OBJLoader(manager);
|
|
313
|
+
let withMaterials = false, creator = null;
|
|
314
|
+
const mtlName = mtllibOf(text);
|
|
315
|
+
const mtlPath = mtlName && joinRelative(path.includes('/') ? path.slice(0, path.lastIndexOf('/')) : '', mtlName);
|
|
316
|
+
if (mtlPath) { // 找不到 .mtl(或指向工作目录外)就用中性灰,不当错误
|
|
317
|
+
try {
|
|
318
|
+
const mtl = await download(serviceUrl(token, mtlPath), mtlPath);
|
|
319
|
+
const { MTLLoader } = await engine.module('loaders/MTLLoader');
|
|
320
|
+
creator = new MTLLoader(manager).parse(new TextDecoder().decode(mtl), directoryUrl(token, mtlPath));
|
|
321
|
+
creator.preload();
|
|
322
|
+
loader.setMaterials(creator);
|
|
323
|
+
withMaterials = true;
|
|
324
|
+
} catch (error) { if (error?.name === 'AbortError') throw error; }
|
|
325
|
+
}
|
|
326
|
+
let object;
|
|
327
|
+
try {
|
|
328
|
+
object = loader.parse(text);
|
|
329
|
+
object.traverse(o => {
|
|
330
|
+
if (!o.isMesh) return;
|
|
331
|
+
if (!withMaterials) o.material = neutral();
|
|
332
|
+
if (!o.geometry.getAttribute('normal')) o.geometry.computeVertexNormals();
|
|
333
|
+
});
|
|
334
|
+
} catch (error) { // 解析到一半失败:已经建出来的材质、贴图和几何体不留着
|
|
335
|
+
if (object) disposeObject(object);
|
|
336
|
+
for (const material of Object.values(creator?.materials ?? {})) disposeMaterial(material);
|
|
337
|
+
throw error;
|
|
338
|
+
}
|
|
339
|
+
return done(object);
|
|
340
|
+
}
|
|
341
|
+
if (ext === '3mf') {
|
|
342
|
+
const { ThreeMFLoader } = await engine.module('loaders/3MFLoader');
|
|
343
|
+
return done(new ThreeMFLoader(manager).parse(exact(bytes)));
|
|
344
|
+
}
|
|
345
|
+
throw new Friendly('这种格式不能预览');
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
// 面数(按绘制计,含重复使用的几何体)和点数。
|
|
349
|
+
function measure(root) {
|
|
350
|
+
const out = { triangles: 0, points: 0 };
|
|
351
|
+
root.traverse(o => {
|
|
352
|
+
const geometry = o.geometry, position = geometry?.getAttribute?.('position');
|
|
353
|
+
if (!position) return;
|
|
354
|
+
if (o.isMesh) out.triangles += (geometry.index ? geometry.index.count : position.count) / 3 * (o.isInstancedMesh ? o.count : 1);
|
|
355
|
+
else if (o.isPoints) out.points += position.count;
|
|
356
|
+
});
|
|
357
|
+
out.triangles = Math.round(out.triangles);
|
|
358
|
+
return out;
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// 释放:几何体、材质、材质上的每张贴图(含 ImageBitmap)、骨架。
|
|
362
|
+
function disposeObject(root) {
|
|
363
|
+
root.traverse(o => {
|
|
364
|
+
o.geometry?.dispose();
|
|
365
|
+
o.skeleton?.dispose?.();
|
|
366
|
+
for (const m of [o.material].flat()) if (m) disposeMaterial(m);
|
|
367
|
+
});
|
|
368
|
+
}
|
|
369
|
+
function disposeMaterial(m) {
|
|
370
|
+
for (const value of Object.values(m)) if (value?.isTexture) { value.dispose(); value.image?.close?.(); }
|
|
371
|
+
m.dispose();
|
|
372
|
+
}
|