@file-viewer/renderer-3d 2.0.11

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/LICENSE ADDED
@@ -0,0 +1,160 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction, and
10
+ distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by the copyright
13
+ owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all other entities
16
+ that control, are controlled by, or are under common control with that entity.
17
+ For the purposes of this definition, "control" means (i) the power, direct or
18
+ indirect, to cause the direction or management of such entity, whether by
19
+ contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
20
+ outstanding shares, or (iii) beneficial ownership of such entity.
21
+
22
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
23
+ permissions granted by this License.
24
+
25
+ "Source" form shall mean the preferred form for making modifications, including
26
+ but not limited to software source code, documentation source, and configuration
27
+ files.
28
+
29
+ "Object" form shall mean any form resulting from mechanical transformation or
30
+ translation of a Source form, including but not limited to compiled object code,
31
+ generated documentation, and conversions to other media types.
32
+
33
+ "Work" shall mean the work of authorship, whether in Source or Object form,
34
+ made available under the License, as indicated by a copyright notice that is
35
+ included in or attached to the work.
36
+
37
+ "Derivative Works" shall mean any work, whether in Source or Object form, that
38
+ is based on (or derived from) the Work and for which the editorial revisions,
39
+ annotations, elaborations, or other modifications represent, as a whole, an
40
+ original work of authorship. For the purposes of this License, Derivative Works
41
+ shall not include works that remain separable from, or merely link (or bind by
42
+ name) to the interfaces of, the Work and Derivative Works thereof.
43
+
44
+ "Contribution" shall mean any work of authorship, including the original version
45
+ of the Work and any modifications or additions to that Work or Derivative Works
46
+ thereof, that is intentionally submitted to Licensor for inclusion in the Work by
47
+ the copyright owner or by an individual or Legal Entity authorized to submit on
48
+ behalf of the copyright owner. For the purposes of this definition, "submitted"
49
+ means any form of electronic, verbal, or written communication sent to the
50
+ Licensor or its representatives, including but not limited to communication on
51
+ electronic mailing lists, source code control systems, and issue tracking systems
52
+ that are managed by, or on behalf of, the Licensor for the purpose of discussing
53
+ and improving the Work, but excluding communication that is conspicuously marked
54
+ or otherwise designated in writing by the copyright owner as "Not a
55
+ Contribution."
56
+
57
+ "Contributor" shall mean Licensor and any individual or Legal Entity on behalf
58
+ of whom a Contribution has been received by Licensor and subsequently
59
+ incorporated within the Work.
60
+
61
+ 2. Grant of Copyright License. Subject to the terms and conditions of this
62
+ License, each Contributor hereby grants to You a perpetual, worldwide,
63
+ non-exclusive, no-charge, royalty-free, irrevocable copyright license to
64
+ reproduce, prepare Derivative Works of, publicly display, publicly perform,
65
+ sublicense, and distribute the Work and such Derivative Works in Source or
66
+ Object form.
67
+
68
+ 3. Grant of Patent License. Subject to the terms and conditions of this License,
69
+ each Contributor hereby grants to You a perpetual, worldwide, non-exclusive,
70
+ no-charge, royalty-free, irrevocable (except as stated in this section) patent
71
+ license to make, have made, use, offer to sell, sell, import, and otherwise
72
+ transfer the Work, where such license applies only to those patent claims
73
+ licensable by such Contributor that are necessarily infringed by their
74
+ Contribution(s) alone or by combination of their Contribution(s) with the Work to
75
+ which such Contribution(s) was submitted. If You institute patent litigation
76
+ against any entity (including a cross-claim or counterclaim in a lawsuit)
77
+ alleging that the Work or a Contribution incorporated within the Work
78
+ constitutes direct or contributory patent infringement, then any patent licenses
79
+ granted to You under this License for that Work shall terminate as of the date
80
+ such litigation is filed.
81
+
82
+ 4. Redistribution. You may reproduce and distribute copies of the Work or
83
+ Derivative Works thereof in any medium, with or without modifications, and in
84
+ Source or Object form, provided that You meet the following conditions:
85
+
86
+ (a) You must give any other recipients of the Work or Derivative Works a copy of
87
+ this License; and
88
+
89
+ (b) You must cause any modified files to carry prominent notices stating that
90
+ You changed the files; and
91
+
92
+ (c) You must retain, in the Source form of any Derivative Works that You
93
+ distribute, all copyright, patent, trademark, and attribution notices from the
94
+ Source form of the Work, excluding those notices that do not pertain to any part
95
+ of the Derivative Works; and
96
+
97
+ (d) If the Work includes a "NOTICE" text file as part of its distribution, then
98
+ any Derivative Works that You distribute must include a readable copy of the
99
+ attribution notices contained within such NOTICE file, excluding those notices
100
+ that do not pertain to any part of the Derivative Works, in at least one of the
101
+ following places: within a NOTICE text file distributed as part of the Derivative
102
+ Works; within the Source form or documentation, if provided along with the
103
+ Derivative Works; or, within a display generated by the Derivative Works, if and
104
+ wherever such third-party notices normally appear. The contents of the NOTICE
105
+ file are for informational purposes only and do not modify the License. You may
106
+ add Your own attribution notices within Derivative Works that You distribute,
107
+ alongside or as an addendum to the NOTICE text from the Work, provided that such
108
+ additional attribution notices cannot be construed as modifying the License.
109
+
110
+ You may add Your own copyright statement to Your modifications and may provide
111
+ additional or different license terms and conditions for use, reproduction, or
112
+ distribution of Your modifications, or for any such Derivative Works as a whole,
113
+ provided Your use, reproduction, and distribution of the Work otherwise complies
114
+ with the conditions stated in this License.
115
+
116
+ 5. Submission of Contributions. Unless You explicitly state otherwise, any
117
+ Contribution intentionally submitted for inclusion in the Work by You to the
118
+ Licensor shall be under the terms and conditions of this License, without any
119
+ additional terms or conditions. Notwithstanding the above, nothing herein shall
120
+ supersede or modify the terms of any separate license agreement you may have
121
+ executed with Licensor regarding such Contributions.
122
+
123
+ 6. Trademarks. This License does not grant permission to use the trade names,
124
+ trademarks, service marks, or product names of the Licensor, except as required
125
+ for reasonable and customary use in describing the origin of the Work and
126
+ reproducing the content of the NOTICE file.
127
+
128
+ 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in
129
+ writing, Licensor provides the Work (and each Contributor provides its
130
+ Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
131
+ KIND, either express or implied, including, without limitation, any warranties or
132
+ conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
133
+ PARTICULAR PURPOSE. You are solely responsible for determining the
134
+ appropriateness of using or redistributing the Work and assume any risks
135
+ associated with Your exercise of permissions under this License.
136
+
137
+ 8. Limitation of Liability. In no event and under no legal theory, whether in
138
+ tort (including negligence), contract, or otherwise, unless required by
139
+ applicable law (such as deliberate and grossly negligent acts) or agreed to in
140
+ writing, shall any Contributor be liable to You for damages, including any
141
+ direct, indirect, special, incidental, or consequential damages of any character
142
+ arising as a result of this License or out of the use or inability to use the
143
+ Work (including but not limited to damages for loss of goodwill, work stoppage,
144
+ computer failure or malfunction, or any and all other commercial damages or
145
+ losses), even if such Contributor has been advised of the possibility of such
146
+ damages.
147
+
148
+ 9. Accepting Warranty or Additional Liability. While redistributing the Work or
149
+ Derivative Works thereof, You may choose to offer, and charge a fee for,
150
+ acceptance of support, warranty, indemnity, or other liability obligations and/or
151
+ rights consistent with this License. However, in accepting such obligations, You
152
+ may act only on Your own behalf and on Your sole responsibility, not on behalf of
153
+ any other Contributor, and only if You agree to indemnify, defend, and hold each
154
+ Contributor harmless for any liability incurred by, or claims asserted against,
155
+ such Contributor by reason of your accepting any such warranty or additional
156
+ liability.
157
+
158
+ END OF TERMS AND CONDITIONS
159
+
160
+ Copyright 2026 Flyfish Viewer
package/README.en.md ADDED
@@ -0,0 +1,34 @@
1
+ # @file-viewer/renderer-3d
2
+
3
+ Standalone 3D model renderer package for Flyfish File Viewer. It uses Three.js, OrbitControls, and format-specific Three.js loaders to preview GLB/GLTF, OBJ, STL, PLY, FBX, DAE, 3DS, 3MF, AMF, USD, KMZ, PCD, VRML, XYZ, VTK, and related model files directly in the browser.
4
+
5
+ ## Usage
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { modelRenderer } from '@file-viewer/renderer-3d'
10
+
11
+ const options = {
12
+ rendererMode: 'replace',
13
+ renderers: modelRenderer,
14
+ }
15
+ ```
16
+
17
+ You can combine it with other renderer packages:
18
+
19
+ ```ts
20
+ import { modelRenderer } from '@file-viewer/renderer-3d'
21
+ import { cadRenderer } from '@file-viewer/renderer-cad'
22
+
23
+ const options = {
24
+ rendererMode: 'replace',
25
+ renderers: [modelRenderer, cadRenderer],
26
+ }
27
+ ```
28
+
29
+ ## Capabilities
30
+
31
+ - Supports WebGL preview, orbit controls, fit-to-view, grid, axes, wireframe, and auto-rotate.
32
+ - For `gltf`, `dae`, and `fbx` files with external textures or binary resources, the original URL directory is used as the resource base.
33
+ - STEP, IGES, IFC, 3DM, and BREP entries use `@file-viewer/geometry-engine` for lightweight signature detection and accurate conversion guidance; full decoding should keep evolving through dedicated OpenCascade / web-ifc / rhino3dm WASM renderer paths.
34
+ - `@file-viewer/core` no longer bundles the 3D renderer and no longer depends directly on `three`. Install this package explicitly for 3D model preview, or use `@file-viewer/preset-all`, which aggregates this renderer automatically.
package/README.md ADDED
@@ -0,0 +1,34 @@
1
+ # @file-viewer/renderer-3d
2
+
3
+ Flyfish File Viewer 的独立 3D 模型 renderer 包。它使用 Three.js、OrbitControls 和按格式异步加载的 Three.js loaders,为 GLB/GLTF、OBJ、STL、PLY、FBX、DAE、3DS、3MF、AMF、USD、KMZ、PCD、VRML、XYZ、VTK 等模型提供浏览器端只读预览。
4
+
5
+ ## 用法
6
+
7
+ ```ts
8
+ import FileViewer from '@file-viewer/vue3'
9
+ import { modelRenderer } from '@file-viewer/renderer-3d'
10
+
11
+ const options = {
12
+ rendererMode: 'replace',
13
+ renderers: modelRenderer,
14
+ }
15
+ ```
16
+
17
+ 也可以和其他 renderer 一起组合:
18
+
19
+ ```ts
20
+ import { modelRenderer } from '@file-viewer/renderer-3d'
21
+ import { cadRenderer } from '@file-viewer/renderer-cad'
22
+
23
+ const options = {
24
+ rendererMode: 'replace',
25
+ renderers: [modelRenderer, cadRenderer],
26
+ }
27
+ ```
28
+
29
+ ## 能力边界
30
+
31
+ - 支持 WebGL 交互预览、轨道控制、适配视图、网格、坐标轴、线框和自动旋转。
32
+ - `gltf` / `dae` / `fbx` 等带外部贴图或二进制资源的格式,会以原始 `url` 的目录作为资源基准继续加载。
33
+ - STEP、IGES、IFC、3DM、BREP 等工程 B-Rep / BIM 格式入口会通过 `@file-viewer/geometry-engine` 做轻量签名识别和明确转换说明;完整解析应继续沿 OpenCascade / web-ifc / rhino3dm 独立 WASM renderer 路线演进。
34
+ - `@file-viewer/core` 已不再内置 3D renderer,也不再直接依赖 `three`。需要 3D 模型预览时,请显式安装本包,或使用会自动聚合本包的 `@file-viewer/preset-all`。
@@ -0,0 +1,5 @@
1
+ import { type FileRenderHandler, type FileViewerRenderedInstance, type FileViewerRendererPlugin, type RendererDefinition } from '@file-viewer/core';
2
+ export declare const modelRendererDefinition: RendererDefinition;
3
+ export declare const renderFileViewerModel: FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>;
4
+ export declare const modelRenderer: FileViewerRendererPlugin<FileRenderHandler<FileViewerRenderedInstance, HTMLDivElement>>;
5
+ export default modelRenderer;
package/dist/index.js ADDED
@@ -0,0 +1,17 @@
1
+ import { DEFAULT_RENDERER_DEFINITIONS, } from '@file-viewer/core';
2
+ const modelDefinition = DEFAULT_RENDERER_DEFINITIONS.find(definition => definition.id === 'model');
3
+ if (!modelDefinition) {
4
+ throw new Error('@file-viewer/renderer-3d could not locate the core 3D model renderer definition.');
5
+ }
6
+ export const modelRendererDefinition = modelDefinition;
7
+ export const renderFileViewerModel = (buffer, target, type, context) => import('./model.js').then(({ default: renderModel }) => renderModel(buffer, target, type, context));
8
+ export const modelRenderer = {
9
+ id: 'file-viewer-renderer-3d',
10
+ label: 'Flyfish File Viewer 3D model renderer',
11
+ definitions: [modelRendererDefinition],
12
+ handlers: [{
13
+ rendererId: modelRendererDefinition.id,
14
+ handler: renderFileViewerModel,
15
+ }],
16
+ };
17
+ export default modelRenderer;
@@ -0,0 +1,2 @@
1
+ import type { FileRenderContext, FileViewerRenderedInstance } from '@file-viewer/core';
2
+ export default function renderModel(buffer: ArrayBuffer, target: HTMLDivElement, type?: string, context?: FileRenderContext): Promise<FileViewerRenderedInstance>;
package/dist/model.js ADDED
@@ -0,0 +1,567 @@
1
+ import * as THREE from 'three';
2
+ import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
3
+ import { formatGeometryKernelNotice, inspectGeometryKernelFile, isGeometryKernelFormat, } from '@file-viewer/geometry-engine';
4
+ const modelStyle = `
5
+ .model-viewer{display:flex;height:100%;min-height:100%;flex-direction:column;background:#f8fafc;color:#162333}
6
+ .model-viewer *{box-sizing:border-box}
7
+ .model-toolbar{display:flex;min-height:48px;align-items:center;justify-content:space-between;gap:16px;padding:0 12px;border-bottom:1px solid rgba(15,23,42,.08);background:#fff}
8
+ .model-actions{display:flex;min-width:0;flex-wrap:wrap;gap:6px}
9
+ .model-actions button{min-height:30px;border:0;border-radius:8px;padding:0 10px;background:rgba(15,23,42,.06);color:#475569;cursor:pointer;font-size:12px;font-weight:700;letter-spacing:0;transition:background-color .18s ease,color .18s ease}
10
+ .model-actions button.active,.model-actions button:hover{background:rgba(33,163,102,.14);color:#16804f}
11
+ .model-meta{min-width:0;display:flex;align-items:center;justify-content:flex-end;gap:8px;color:#64748b;font-size:12px}
12
+ .model-meta strong{color:#0f766e;font-weight:800}
13
+ .model-meta span{overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
14
+ .model-stage{position:relative;flex:1;min-height:0;overflow:hidden}
15
+ .model-stage canvas{display:block;width:100%;height:100%;outline:none}
16
+ .model-state{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:10px;padding:24px;background:rgba(248,250,252,.88);color:#64748b;text-align:center;line-height:1.7}
17
+ .model-state[hidden]{display:none!important}
18
+ .model-state.error{color:#b42318}
19
+ .model-state strong{color:#b42318;font-size:18px}
20
+ @media (max-width:720px){.model-toolbar{min-height:64px;align-items:flex-start;flex-direction:column;gap:8px;padding:8px 10px}.model-meta{width:100%;justify-content:flex-start}}
21
+ `;
22
+ class ModelPreviewNotice extends Error {
23
+ }
24
+ const createStyle = () => {
25
+ const style = document.createElement('style');
26
+ style.textContent = modelStyle;
27
+ return style;
28
+ };
29
+ const createElement = (tagName, className, text) => {
30
+ const element = document.createElement(tagName);
31
+ if (className) {
32
+ element.className = className;
33
+ }
34
+ if (text !== undefined) {
35
+ element.textContent = text;
36
+ }
37
+ return element;
38
+ };
39
+ const normalizeError = (reason) => {
40
+ if (reason instanceof Error) {
41
+ return reason.message;
42
+ }
43
+ if (typeof reason === 'string') {
44
+ return reason;
45
+ }
46
+ try {
47
+ return JSON.stringify(reason);
48
+ }
49
+ catch {
50
+ return String(reason);
51
+ }
52
+ };
53
+ const getResourcePath = (sourceUrl) => {
54
+ if (!sourceUrl) {
55
+ return '';
56
+ }
57
+ try {
58
+ return new URL('.', sourceUrl).href;
59
+ }
60
+ catch {
61
+ const clean = sourceUrl.split(/[?#]/)[0] || sourceUrl;
62
+ const slashIndex = clean.lastIndexOf('/');
63
+ return slashIndex >= 0 ? clean.slice(0, slashIndex + 1) : '';
64
+ }
65
+ };
66
+ const disposeMaterial = (material) => {
67
+ const materials = Array.isArray(material) ? material : [material];
68
+ materials.forEach(item => item.dispose());
69
+ };
70
+ const disposeObject = (object) => {
71
+ object.traverse(child => {
72
+ const mesh = child;
73
+ const points = child;
74
+ if (mesh.geometry) {
75
+ mesh.geometry.dispose();
76
+ }
77
+ if (mesh.material) {
78
+ disposeMaterial(mesh.material);
79
+ }
80
+ if (points.material) {
81
+ disposeMaterial(points.material);
82
+ }
83
+ });
84
+ };
85
+ export default async function renderModel(buffer, target, type = 'glb', context) {
86
+ const normalizedType = type.toLowerCase();
87
+ const sourceUrl = context?.url;
88
+ let status = 'loading';
89
+ let errorMessage = '';
90
+ let objectSummary = '正在加载模型';
91
+ let autoRotate = false;
92
+ let wireframe = false;
93
+ let showGrid = true;
94
+ let showAxes = true;
95
+ let renderer = null;
96
+ let scene = null;
97
+ let camera = null;
98
+ let controls = null;
99
+ let modelRoot = null;
100
+ let gridHelper = null;
101
+ let axesHelper = null;
102
+ let resizeObserver = null;
103
+ let animationFrame = 0;
104
+ let activeVersion = 0;
105
+ let mixer = null;
106
+ const clock = new THREE.Clock();
107
+ const root = createElement('div', 'model-viewer');
108
+ const toolbar = createElement('div', 'model-toolbar');
109
+ const actions = createElement('div', 'model-actions');
110
+ const fitButton = createElement('button', undefined, '适配');
111
+ const rotateButton = createElement('button', undefined, '旋转');
112
+ const wireframeButton = createElement('button', undefined, '线框');
113
+ const gridButton = createElement('button', undefined, '网格');
114
+ const axesButton = createElement('button', undefined, '坐标');
115
+ const meta = createElement('div', 'model-meta');
116
+ const typeText = createElement('strong', undefined, normalizedType.toUpperCase());
117
+ const summaryText = createElement('span', undefined, objectSummary);
118
+ const stage = createElement('div', 'model-stage');
119
+ const canvas = document.createElement('canvas');
120
+ const state = createElement('div', 'model-state', '正在解析 3D 模型...');
121
+ const buttons = [fitButton, rotateButton, wireframeButton, gridButton, axesButton];
122
+ buttons.forEach(button => {
123
+ button.type = 'button';
124
+ });
125
+ actions.append(fitButton, rotateButton, wireframeButton, gridButton, axesButton);
126
+ meta.append(typeText, summaryText);
127
+ toolbar.append(actions, meta);
128
+ stage.append(canvas, state);
129
+ root.append(toolbar, stage);
130
+ target.replaceChildren(createStyle(), root);
131
+ const readText = () => {
132
+ if (typeof TextDecoder === 'function') {
133
+ return new TextDecoder('utf-8').decode(buffer);
134
+ }
135
+ const bytes = new Uint8Array(buffer);
136
+ let text = '';
137
+ for (let index = 0; index < bytes.length; index += 1) {
138
+ text += String.fromCharCode(bytes[index]);
139
+ }
140
+ return text;
141
+ };
142
+ const updateUi = () => {
143
+ rotateButton.classList.toggle('active', autoRotate);
144
+ wireframeButton.classList.toggle('active', wireframe);
145
+ gridButton.classList.toggle('active', showGrid);
146
+ axesButton.classList.toggle('active', showAxes);
147
+ summaryText.textContent = objectSummary;
148
+ state.hidden = status === 'ready';
149
+ state.classList.toggle('error', status === 'error');
150
+ if (status === 'loading') {
151
+ state.textContent = '正在解析 3D 模型...';
152
+ }
153
+ else if (status === 'error') {
154
+ state.replaceChildren(createElement('strong', undefined, '模型解析失败'), createElement('span', undefined, errorMessage));
155
+ }
156
+ };
157
+ const updateHelperVisibility = () => {
158
+ if (gridHelper) {
159
+ gridHelper.visible = showGrid;
160
+ }
161
+ if (axesHelper) {
162
+ axesHelper.visible = showAxes;
163
+ }
164
+ updateUi();
165
+ };
166
+ const resize = () => {
167
+ if (!renderer || !camera) {
168
+ return;
169
+ }
170
+ const rect = canvas.getBoundingClientRect();
171
+ const width = Math.max(1, Math.floor(rect.width));
172
+ const height = Math.max(1, Math.floor(rect.height));
173
+ renderer.setSize(width, height, false);
174
+ camera.aspect = width / height;
175
+ camera.updateProjectionMatrix();
176
+ };
177
+ const ensureScene = () => {
178
+ if (!renderer) {
179
+ renderer = new THREE.WebGLRenderer({
180
+ antialias: true,
181
+ alpha: false,
182
+ canvas,
183
+ powerPreference: 'high-performance',
184
+ });
185
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));
186
+ renderer.outputColorSpace = THREE.SRGBColorSpace;
187
+ renderer.setClearColor(0xf8fafc, 1);
188
+ }
189
+ if (!scene) {
190
+ scene = new THREE.Scene();
191
+ scene.background = new THREE.Color(0xf8fafc);
192
+ const hemiLight = new THREE.HemisphereLight(0xffffff, 0xd7dee8, 2.4);
193
+ scene.add(hemiLight);
194
+ const keyLight = new THREE.DirectionalLight(0xffffff, 2.2);
195
+ keyLight.position.set(8, 10, 8);
196
+ scene.add(keyLight);
197
+ const fillLight = new THREE.DirectionalLight(0xffffff, 0.9);
198
+ fillLight.position.set(-7, 5, -4);
199
+ scene.add(fillLight);
200
+ gridHelper = new THREE.GridHelper(10, 10, 0xcbd5e1, 0xe2e8f0);
201
+ scene.add(gridHelper);
202
+ axesHelper = new THREE.AxesHelper(3);
203
+ scene.add(axesHelper);
204
+ }
205
+ if (!camera) {
206
+ camera = new THREE.PerspectiveCamera(45, 1, 0.01, 100000);
207
+ camera.position.set(5, 4, 6);
208
+ }
209
+ if (!controls && camera && renderer) {
210
+ controls = new OrbitControls(camera, renderer.domElement);
211
+ controls.enableDamping = true;
212
+ controls.dampingFactor = 0.08;
213
+ controls.screenSpacePanning = true;
214
+ controls.autoRotateSpeed = 1.2;
215
+ }
216
+ updateHelperVisibility();
217
+ resize();
218
+ };
219
+ const clearModel = () => {
220
+ if (modelRoot && scene) {
221
+ scene.remove(modelRoot);
222
+ disposeObject(modelRoot);
223
+ }
224
+ modelRoot = null;
225
+ mixer = null;
226
+ };
227
+ const createSurfaceMaterial = () => new THREE.MeshStandardMaterial({
228
+ color: 0x4f8fba,
229
+ metalness: 0.08,
230
+ roughness: 0.78,
231
+ side: THREE.DoubleSide,
232
+ wireframe,
233
+ });
234
+ const createPointMaterial = () => new THREE.PointsMaterial({
235
+ color: 0x1f7a8c,
236
+ size: 0.035,
237
+ sizeAttenuation: true,
238
+ });
239
+ const applyDefaultMaterials = (object) => {
240
+ object.traverse(child => {
241
+ const mesh = child;
242
+ if (mesh.isMesh && !mesh.material) {
243
+ mesh.material = createSurfaceMaterial();
244
+ }
245
+ if (mesh.isMesh && mesh.material) {
246
+ const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material];
247
+ materials.forEach(material => {
248
+ if ('wireframe' in material) {
249
+ material.wireframe = wireframe;
250
+ }
251
+ material.needsUpdate = true;
252
+ });
253
+ }
254
+ });
255
+ };
256
+ const countMeshes = (object) => {
257
+ let meshes = 0;
258
+ let points = 0;
259
+ object.traverse(child => {
260
+ if (child.isMesh) {
261
+ meshes += 1;
262
+ }
263
+ if (child.isPoints) {
264
+ points += 1;
265
+ }
266
+ });
267
+ return { meshes, points };
268
+ };
269
+ const summarizeModel = (object) => {
270
+ const { meshes, points } = countMeshes(object);
271
+ const parts = [];
272
+ if (meshes) {
273
+ parts.push(`${meshes} 个网格`);
274
+ }
275
+ if (points) {
276
+ parts.push(`${points} 个点云`);
277
+ }
278
+ objectSummary = parts.length ? parts.join(',') : '模型已加载';
279
+ updateUi();
280
+ };
281
+ const normalizeObject = (object) => {
282
+ const box = new THREE.Box3().setFromObject(object);
283
+ if (box.isEmpty()) {
284
+ return {
285
+ center: new THREE.Vector3(),
286
+ size: new THREE.Vector3(4, 4, 4),
287
+ };
288
+ }
289
+ const center = box.getCenter(new THREE.Vector3());
290
+ const size = box.getSize(new THREE.Vector3());
291
+ object.position.sub(center);
292
+ return {
293
+ center: new THREE.Vector3(),
294
+ size,
295
+ };
296
+ };
297
+ const fitToView = () => {
298
+ if (!modelRoot || !camera || !controls) {
299
+ return;
300
+ }
301
+ const box = new THREE.Box3().setFromObject(modelRoot);
302
+ const size = box.getSize(new THREE.Vector3());
303
+ const center = box.getCenter(new THREE.Vector3());
304
+ const radius = Math.max(size.x, size.y, size.z, 1);
305
+ const distance = radius / (2 * Math.tan(THREE.MathUtils.degToRad(camera.fov / 2))) * 1.65;
306
+ camera.near = Math.max(distance / 1000, 0.01);
307
+ camera.far = Math.max(distance * 1000, 1000);
308
+ camera.position.copy(center).add(new THREE.Vector3(distance, distance * 0.62, distance));
309
+ camera.updateProjectionMatrix();
310
+ controls.target.copy(center);
311
+ controls.update();
312
+ };
313
+ const addModelToScene = async (object) => {
314
+ if (!scene) {
315
+ return;
316
+ }
317
+ clearModel();
318
+ applyDefaultMaterials(object);
319
+ const { size } = normalizeObject(object);
320
+ modelRoot = object;
321
+ scene.add(object);
322
+ fitToView();
323
+ summarizeModel(object);
324
+ const maxSize = Math.max(size.x, size.y, size.z, 1);
325
+ if (gridHelper) {
326
+ gridHelper.scale.setScalar(Math.max(maxSize / 10, 1));
327
+ }
328
+ };
329
+ const parseGlbOrGltf = async () => {
330
+ const { GLTFLoader } = await import('three/addons/loaders/GLTFLoader.js');
331
+ const loader = new GLTFLoader();
332
+ const resourcePath = getResourcePath(sourceUrl);
333
+ const input = normalizedType === 'gltf' ? readText() : buffer;
334
+ return await new Promise((resolve, reject) => {
335
+ loader.parse(input, resourcePath, gltf => {
336
+ if (gltf.animations?.length) {
337
+ mixer = new THREE.AnimationMixer(gltf.scene);
338
+ gltf.animations.forEach(clip => mixer?.clipAction(clip).play());
339
+ }
340
+ resolve(gltf.scene);
341
+ }, reject);
342
+ });
343
+ };
344
+ const parseObj = async () => {
345
+ const { OBJLoader } = await import('three/addons/loaders/OBJLoader.js');
346
+ return new OBJLoader().parse(readText());
347
+ };
348
+ const parseStl = async () => {
349
+ const { STLLoader } = await import('three/addons/loaders/STLLoader.js');
350
+ const geometry = new STLLoader().parse(buffer);
351
+ geometry.computeVertexNormals();
352
+ return new THREE.Mesh(geometry, createSurfaceMaterial());
353
+ };
354
+ const parsePly = async () => {
355
+ const { PLYLoader } = await import('three/addons/loaders/PLYLoader.js');
356
+ const geometry = new PLYLoader().parse(buffer);
357
+ geometry.computeVertexNormals();
358
+ return new THREE.Mesh(geometry, createSurfaceMaterial());
359
+ };
360
+ const parseFbx = async () => {
361
+ const { FBXLoader } = await import('three/addons/loaders/FBXLoader.js');
362
+ const object = new FBXLoader().parse(buffer, getResourcePath(sourceUrl));
363
+ if (object.animations?.length) {
364
+ mixer = new THREE.AnimationMixer(object);
365
+ object.animations.forEach((clip) => mixer?.clipAction(clip).play());
366
+ }
367
+ return object;
368
+ };
369
+ const parseDae = async () => {
370
+ const { ColladaLoader } = await import('three/addons/loaders/ColladaLoader.js');
371
+ const result = new ColladaLoader().parse(readText(), getResourcePath(sourceUrl));
372
+ if (!result?.scene) {
373
+ throw new Error('DAE 模型未解析出有效场景');
374
+ }
375
+ return result.scene;
376
+ };
377
+ const parse3ds = async () => {
378
+ const { TDSLoader } = await import('three/addons/loaders/TDSLoader.js');
379
+ return new TDSLoader().parse(buffer, getResourcePath(sourceUrl));
380
+ };
381
+ const parse3mf = async () => {
382
+ const { ThreeMFLoader } = await import('three/addons/loaders/3MFLoader.js');
383
+ return new ThreeMFLoader().parse(buffer);
384
+ };
385
+ const parseAmf = async () => {
386
+ const { AMFLoader } = await import('three/addons/loaders/AMFLoader.js');
387
+ return new AMFLoader().parse(buffer);
388
+ };
389
+ const parseUsd = async () => {
390
+ const { USDLoader } = await import('three/addons/loaders/USDLoader.js');
391
+ return new USDLoader().parse(buffer);
392
+ };
393
+ const parseKmz = async () => {
394
+ const { KMZLoader } = await import('three/addons/loaders/KMZLoader.js');
395
+ return new KMZLoader().parse(buffer).scene;
396
+ };
397
+ const explainEngineeringModel = (modelType) => {
398
+ const inspection = inspectGeometryKernelFile(buffer, modelType);
399
+ const notice = formatGeometryKernelNotice(inspection.format || modelType);
400
+ const signature = inspection.signature ? `检测到文件签名: ${inspection.signature}。` : '';
401
+ const warnings = inspection.warnings.length ? ` ${inspection.warnings.join(' ')}` : '';
402
+ throw new ModelPreviewNotice(`${signature}${notice}${warnings}`);
403
+ };
404
+ const parsePcd = async () => {
405
+ const { PCDLoader } = await import('three/addons/loaders/PCDLoader.js');
406
+ return new PCDLoader().parse(buffer, sourceUrl || 'model.pcd');
407
+ };
408
+ const parseVrml = async () => {
409
+ const { VRMLLoader } = await import('three/addons/loaders/VRMLLoader.js');
410
+ return new VRMLLoader().parse(readText(), getResourcePath(sourceUrl));
411
+ };
412
+ const parseXyz = async () => {
413
+ const { XYZLoader } = await import('three/addons/loaders/XYZLoader.js');
414
+ const geometry = new XYZLoader().parse(readText());
415
+ geometry.computeBoundingSphere();
416
+ return new THREE.Points(geometry, createPointMaterial());
417
+ };
418
+ const parseVtk = async () => {
419
+ const { VTKLoader } = await import('three/addons/loaders/VTKLoader.js');
420
+ const geometry = new VTKLoader().parse(buffer);
421
+ geometry.computeVertexNormals();
422
+ return new THREE.Mesh(geometry, createSurfaceMaterial());
423
+ };
424
+ const parseModel = (modelType) => {
425
+ switch (modelType) {
426
+ case 'glb':
427
+ case 'gltf':
428
+ return parseGlbOrGltf();
429
+ case 'obj':
430
+ return parseObj();
431
+ case 'stl':
432
+ return parseStl();
433
+ case 'ply':
434
+ return parsePly();
435
+ case 'fbx':
436
+ return parseFbx();
437
+ case 'dae':
438
+ return parseDae();
439
+ case '3ds':
440
+ return parse3ds();
441
+ case '3mf':
442
+ return parse3mf();
443
+ case 'amf':
444
+ return parseAmf();
445
+ case 'usd':
446
+ case 'usda':
447
+ case 'usdc':
448
+ case 'usdz':
449
+ return parseUsd();
450
+ case 'kmz':
451
+ return parseKmz();
452
+ case 'step':
453
+ case 'stp':
454
+ case 'iges':
455
+ case 'igs':
456
+ case 'ifc':
457
+ case '3dm':
458
+ case 'brep':
459
+ return explainEngineeringModel(modelType);
460
+ case 'pcd':
461
+ return parsePcd();
462
+ case 'wrl':
463
+ case 'vrml':
464
+ return parseVrml();
465
+ case 'xyz':
466
+ return parseXyz();
467
+ case 'vtk':
468
+ case 'vtp':
469
+ return parseVtk();
470
+ default:
471
+ if (isGeometryKernelFormat(modelType)) {
472
+ return explainEngineeringModel(modelType);
473
+ }
474
+ throw new Error(`暂不支持 .${modelType} 模型格式`);
475
+ }
476
+ };
477
+ const loadModel = async () => {
478
+ const version = ++activeVersion;
479
+ status = 'loading';
480
+ errorMessage = '';
481
+ objectSummary = '正在加载模型';
482
+ updateUi();
483
+ ensureScene();
484
+ try {
485
+ const object = await parseModel(normalizedType);
486
+ if (version !== activeVersion) {
487
+ disposeObject(object);
488
+ return;
489
+ }
490
+ await addModelToScene(object);
491
+ status = 'ready';
492
+ updateUi();
493
+ }
494
+ catch (reason) {
495
+ if (version !== activeVersion) {
496
+ return;
497
+ }
498
+ if (!(reason instanceof ModelPreviewNotice)) {
499
+ console.error(reason);
500
+ }
501
+ status = 'error';
502
+ errorMessage = normalizeError(reason) || `${normalizedType.toUpperCase()} 模型解析失败`;
503
+ updateUi();
504
+ }
505
+ };
506
+ const renderFrame = () => {
507
+ if (!renderer || !scene || !camera || !controls) {
508
+ return;
509
+ }
510
+ controls.autoRotate = autoRotate;
511
+ controls.update();
512
+ const delta = clock.getDelta();
513
+ mixer?.update(delta);
514
+ renderer.render(scene, camera);
515
+ animationFrame = window.requestAnimationFrame(renderFrame);
516
+ };
517
+ const updateWireframe = () => {
518
+ if (modelRoot) {
519
+ applyDefaultMaterials(modelRoot);
520
+ }
521
+ updateUi();
522
+ };
523
+ fitButton.addEventListener('click', fitToView);
524
+ rotateButton.addEventListener('click', () => {
525
+ autoRotate = !autoRotate;
526
+ updateUi();
527
+ });
528
+ wireframeButton.addEventListener('click', () => {
529
+ wireframe = !wireframe;
530
+ updateWireframe();
531
+ });
532
+ gridButton.addEventListener('click', () => {
533
+ showGrid = !showGrid;
534
+ updateHelperVisibility();
535
+ });
536
+ axesButton.addEventListener('click', () => {
537
+ showAxes = !showAxes;
538
+ updateHelperVisibility();
539
+ });
540
+ updateUi();
541
+ ensureScene();
542
+ resizeObserver = new ResizeObserver(resize);
543
+ resizeObserver.observe(canvas);
544
+ clock.start();
545
+ renderFrame();
546
+ void loadModel();
547
+ return {
548
+ $el: root,
549
+ unmount() {
550
+ activeVersion += 1;
551
+ window.cancelAnimationFrame(animationFrame);
552
+ resizeObserver?.disconnect();
553
+ resizeObserver = null;
554
+ clearModel();
555
+ controls?.dispose();
556
+ controls = null;
557
+ renderer?.dispose();
558
+ renderer = null;
559
+ clock.stop();
560
+ scene = null;
561
+ camera = null;
562
+ gridHelper = null;
563
+ axesHelper = null;
564
+ target.replaceChildren();
565
+ },
566
+ };
567
+ }
package/package.json ADDED
@@ -0,0 +1,73 @@
1
+ {
2
+ "name": "@file-viewer/renderer-3d",
3
+ "version": "2.0.11",
4
+ "private": false,
5
+ "type": "module",
6
+ "description": "Standalone 3D model renderer plugin for Flyfish File Viewer powered by Three.js loaders and OrbitControls.",
7
+ "keywords": [
8
+ "file-viewer",
9
+ "renderer",
10
+ "3d",
11
+ "three",
12
+ "gltf",
13
+ "glb",
14
+ "stl",
15
+ "obj",
16
+ "document-preview",
17
+ "document-viewer",
18
+ "file-preview",
19
+ "self-hosted"
20
+ ],
21
+ "publishConfig": {
22
+ "access": "public",
23
+ "registry": "https://registry.npmjs.org/"
24
+ },
25
+ "author": {
26
+ "name": "Wangyu",
27
+ "email": "wybaby168@gmail.com"
28
+ },
29
+ "repository": {
30
+ "type": "git",
31
+ "url": "git+https://github.com/flyfish-dev/file-viewer-renderer-3d.git",
32
+ "directory": "packages/renderers/3d"
33
+ },
34
+ "homepage": "https://doc.file-viewer.app/guide/on-demand-renderers",
35
+ "bugs": {
36
+ "url": "https://github.com/flyfish-dev/file-viewer-renderer-3d/issues"
37
+ },
38
+ "funding": {
39
+ "type": "individual",
40
+ "url": "https://dev.flyfish.group/shop"
41
+ },
42
+ "main": "./dist/index.js",
43
+ "module": "./dist/index.js",
44
+ "types": "./dist/index.d.ts",
45
+ "exports": {
46
+ ".": {
47
+ "types": "./dist/index.d.ts",
48
+ "import": "./dist/index.js",
49
+ "default": "./dist/index.js"
50
+ },
51
+ "./package.json": "./package.json"
52
+ },
53
+ "files": [
54
+ "dist",
55
+ "README.md",
56
+ "README.en.md",
57
+ "LICENSE"
58
+ ],
59
+ "dependencies": {
60
+ "@file-viewer/core": "^2.0.11",
61
+ "@file-viewer/geometry-engine": "^2.0.11",
62
+ "three": "^0.184.0"
63
+ },
64
+ "devDependencies": {
65
+ "@types/three": "^0.184.1",
66
+ "typescript": "^6.0.3"
67
+ },
68
+ "license": "Apache-2.0",
69
+ "scripts": {
70
+ "build": "tsc -b tsconfig.json",
71
+ "type-check": "tsc -b tsconfig.json"
72
+ }
73
+ }