@needle-tools/gltf-progressive 1.0.0-alpha.1 → 1.0.0-alpha.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/lib/index.d.ts ADDED
@@ -0,0 +1,27 @@
1
+ export * from "./extension.js";
2
+ export * from "./plugins/index.js";
3
+ export { LODsManager } from "./lods_manager.js";
4
+ export { setDracoDecoderLocation, setKTX2TranscoderLocation } from "./loaders.js";
5
+ import { WebGLRenderer } from "three";
6
+ import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
7
+ import { LODsManager } from "./lods_manager.js";
8
+ declare class UseNeedleGLTFProgressive {
9
+ /** */
10
+ enableLODsManager?: boolean;
11
+ }
12
+ /** Use this function to enable progressive loading of gltf models.
13
+ * @param url The url of the gltf model.
14
+ * @param renderer The renderer of the scene.
15
+ * @param loader The gltf loader.
16
+ * @param opts Options.
17
+ * @returns The LODsManager instance.
18
+ * @example In react-three-fiber:
19
+ * ```ts
20
+ * const url = 'https://yourdomain.com/yourmodel.glb'
21
+ * const { scene } = useGLTF(url, false, false, (loader) => {
22
+ * useNeedleGLTFProgressive(url, gl, loader)
23
+ * })
24
+ * return <primitive object={scene} />
25
+ * ```
26
+ */
27
+ export declare function useNeedleProgressive(url: string, renderer: WebGLRenderer, loader: GLTFLoader, opts?: UseNeedleGLTFProgressive): LODsManager;
package/lib/index.js ADDED
@@ -0,0 +1,38 @@
1
+ export * from "./extension.js";
2
+ export * from "./plugins/index.js";
3
+ export { LODsManager } from "./lods_manager.js";
4
+ export { setDracoDecoderLocation, setKTX2TranscoderLocation } from "./loaders.js";
5
+ import { addDracoAndKTX2Loaders, createLoaders } from "./loaders.js";
6
+ import { NEEDLE_progressive } from "./extension.js";
7
+ import { LODsManager } from "./lods_manager.js";
8
+ ;
9
+ /** Use this function to enable progressive loading of gltf models.
10
+ * @param url The url of the gltf model.
11
+ * @param renderer The renderer of the scene.
12
+ * @param loader The gltf loader.
13
+ * @param opts Options.
14
+ * @returns The LODsManager instance.
15
+ * @example In react-three-fiber:
16
+ * ```ts
17
+ * const url = 'https://yourdomain.com/yourmodel.glb'
18
+ * const { scene } = useGLTF(url, false, false, (loader) => {
19
+ * useNeedleGLTFProgressive(url, gl, loader)
20
+ * })
21
+ * return <primitive object={scene} />
22
+ * ```
23
+ */
24
+ export function useNeedleProgressive(url, renderer, loader, opts) {
25
+ createLoaders(renderer);
26
+ addDracoAndKTX2Loaders(loader);
27
+ loader.register(p => new NEEDLE_progressive(p, url));
28
+ const lod = new LODsManager(renderer);
29
+ if (opts?.enableLODsManager !== false) {
30
+ lod.enable();
31
+ }
32
+ return lod;
33
+ }
34
+ import { patchModelViewer } from "./plugins/modelviewer.js";
35
+ // Query once for model viewer. If a user does not have model-viewer in their page, this will return null.
36
+ document.addEventListener("DOMContentLoaded", () => {
37
+ patchModelViewer(document.querySelector("model-viewer"));
38
+ });
@@ -0,0 +1,14 @@
1
+ import { WebGLRenderer } from 'three';
2
+ import { GLTFLoader } from 'three/examples/jsm/loaders/GLTFLoader.js';
3
+ /**
4
+ * Set the location of the Draco decoder.
5
+ * @default 'https://www.gstatic.com/draco/versioned/decoders/1.4.1/'
6
+ */
7
+ export declare function setDracoDecoderLocation(location: string): void;
8
+ /**
9
+ * Set the location of the KTX2 transcoder.
10
+ * @default 'https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/'
11
+ */
12
+ export declare function setKTX2TranscoderLocation(location: string): void;
13
+ export declare function createLoaders(renderer: WebGLRenderer): void;
14
+ export declare function addDracoAndKTX2Loaders(loader: GLTFLoader): void;
package/lib/loaders.js ADDED
@@ -0,0 +1,54 @@
1
+ import { MeshoptDecoder } from 'three/examples/jsm/libs/meshopt_decoder.module.js';
2
+ import { DRACOLoader } from 'three/examples/jsm/loaders/DRACOLoader.js';
3
+ import { KTX2Loader } from 'three/examples/jsm/loaders/KTX2Loader.js';
4
+ let DEFAULT_DRACO_DECODER_LOCATION = 'https://www.gstatic.com/draco/versioned/decoders/1.4.1/';
5
+ let DEFAULT_KTX2_TRANSCODER_LOCATION = 'https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/';
6
+ fetch(DEFAULT_DRACO_DECODER_LOCATION + "draco_decoder.js", { method: "head" })
7
+ .catch(_ => {
8
+ DEFAULT_DRACO_DECODER_LOCATION = "./include/draco/";
9
+ DEFAULT_KTX2_TRANSCODER_LOCATION = "./include/ktx2/";
10
+ });
11
+ /**
12
+ * Set the location of the Draco decoder.
13
+ * @default 'https://www.gstatic.com/draco/versioned/decoders/1.4.1/'
14
+ */
15
+ export function setDracoDecoderLocation(location) {
16
+ DEFAULT_DRACO_DECODER_LOCATION = location;
17
+ }
18
+ /**
19
+ * Set the location of the KTX2 transcoder.
20
+ * @default 'https://www.gstatic.com/basis-universal/versioned/2021-04-15-ba1c3e4/'
21
+ */
22
+ export function setKTX2TranscoderLocation(location) {
23
+ DEFAULT_KTX2_TRANSCODER_LOCATION = location;
24
+ }
25
+ let dracoLoader;
26
+ let meshoptDecoder;
27
+ let ktx2Loader;
28
+ export function createLoaders(renderer) {
29
+ if (!dracoLoader) {
30
+ dracoLoader = new DRACOLoader();
31
+ dracoLoader.setDecoderPath(DEFAULT_DRACO_DECODER_LOCATION);
32
+ dracoLoader.setDecoderConfig({ type: 'js' });
33
+ }
34
+ if (!ktx2Loader) {
35
+ ktx2Loader = new KTX2Loader();
36
+ ktx2Loader.setTranscoderPath(DEFAULT_KTX2_TRANSCODER_LOCATION);
37
+ }
38
+ if (!meshoptDecoder) {
39
+ meshoptDecoder = MeshoptDecoder;
40
+ }
41
+ if (renderer) {
42
+ ktx2Loader.detectSupport(renderer);
43
+ }
44
+ else
45
+ console.warn("No renderer provided to detect ktx2 support - loading KTX2 textures will probably fail");
46
+ }
47
+ export function addDracoAndKTX2Loaders(loader) {
48
+ if (!loader.dracoLoader)
49
+ loader.setDRACOLoader(dracoLoader);
50
+ if (!loader.ktx2Loader)
51
+ loader.setKTX2Loader(ktx2Loader);
52
+ if (!loader.meshoptDecoder)
53
+ loader.setMeshoptDecoder(meshoptDecoder);
54
+ }
@@ -1,51 +1,70 @@
1
- import { Frustum, Matrix4, Object3D, Vector3, WebGLRenderer } from "three";
2
- import { NEEDLE_progressive_plugin } from "./plugins/plugin.js";
3
- export declare class LODsManager {
4
- readonly renderer: WebGLRenderer;
5
- readonly projectionScreenMatrix: Matrix4;
6
- readonly cameraFrustrum: Frustum;
7
- updateInterval: number;
8
- pause: boolean;
9
- readonly plugins: NEEDLE_progressive_plugin[];
10
- constructor(renderer: WebGLRenderer);
11
- private _originalRender?;
12
- enable(): void;
13
- disable(): void;
14
- private onBeforeRender;
15
- private onAfterRender;
16
- static getObjectLODState(object: Object3D): LOD_state | undefined;
17
- /** Update the LOD levels for the renderer. */
18
- private updateLODs;
19
- /** Load progressive textures for the given material
20
- * @param material the material to load the textures for
21
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
22
- * @returns Promise with true if the LOD was loaded, false if not
23
- */
24
- private loadProgressiveTextures;
25
- /** Load progressive meshes for the given mesh
26
- * @param mesh the mesh to load the LOD for
27
- * @param index the index of the mesh if it's part of a group
28
- * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
29
- * @returns Promise with true if the LOD was loaded, false if not
30
- */
31
- private loadProgressiveMeshes;
32
- private readonly _sphere;
33
- private readonly _tempBox;
34
- private readonly tempMatrix;
35
- private readonly _tempWorldPosition;
36
- private readonly _tempBoxSize;
37
- private readonly _tempBox2Size;
38
- private static corner0;
39
- private static corner1;
40
- private static corner2;
41
- private static corner3;
42
- static debugDrawLine: (a: Vector3, b: Vector3, color: number) => void | null;
43
- private calculateLodLevel;
44
- }
45
- declare class LOD_state {
46
- lastLodLevel: number;
47
- lastScreenCoverage: number;
48
- readonly lastScreenspaceVolume: Vector3;
49
- lastCentrality: number;
50
- }
51
- export {};
1
+ import { Frustum, Matrix4, Object3D, Vector3, WebGLRenderer } from "three";
2
+ import { NEEDLE_progressive_plugin } from "./plugins/plugin.js";
3
+ /**
4
+ * The LODsManager class is responsible for managing the LODs and progressive assets in the scene. It will automatically update the LODs based on the camera position, screen coverage and mesh density of the objects.
5
+ * It must be enabled by calling the `enable` method.
6
+ *
7
+ * Instead of using the LODs manager directly you can also call `useNeedleProgressive` to enable progressive loading for a GLTFLoader
8
+ */
9
+ export declare class LODsManager {
10
+ /** Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
11
+ */
12
+ static debugDrawLine?: (a: Vector3, b: Vector3, color: number) => void;
13
+ /** @internal */
14
+ static getObjectLODState(object: Object3D): LOD_state | undefined;
15
+ readonly renderer: WebGLRenderer;
16
+ readonly projectionScreenMatrix: Matrix4;
17
+ readonly cameraFrustrum: Frustum;
18
+ /**
19
+ * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 1, the LODs will be updated every second frame, etc.
20
+ */
21
+ updateInterval: number;
22
+ /**
23
+ * If set to true, the LODsManager will not update the LODs.
24
+ */
25
+ pause: boolean;
26
+ readonly plugins: NEEDLE_progressive_plugin[];
27
+ constructor(renderer: WebGLRenderer);
28
+ private _frame;
29
+ private _originalRender?;
30
+ /**
31
+ * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
32
+ */
33
+ enable(): void;
34
+ disable(): void;
35
+ private onBeforeRender;
36
+ private onAfterRender;
37
+ /** Update the LOD levels for the renderer. */
38
+ private updateLODs;
39
+ /** Load progressive textures for the given material
40
+ * @param material the material to load the textures for
41
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
42
+ * @returns Promise with true if the LOD was loaded, false if not
43
+ */
44
+ private loadProgressiveTextures;
45
+ /** Load progressive meshes for the given mesh
46
+ * @param mesh the mesh to load the LOD for
47
+ * @param index the index of the mesh if it's part of a group
48
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
49
+ * @returns Promise with true if the LOD was loaded, false if not
50
+ */
51
+ private loadProgressiveMeshes;
52
+ private readonly _sphere;
53
+ private readonly _tempBox;
54
+ private readonly tempMatrix;
55
+ private readonly _tempWorldPosition;
56
+ private readonly _tempBoxSize;
57
+ private readonly _tempBox2Size;
58
+ private static corner0;
59
+ private static corner1;
60
+ private static corner2;
61
+ private static corner3;
62
+ private calculateLodLevel;
63
+ }
64
+ declare class LOD_state {
65
+ lastLodLevel: number;
66
+ lastScreenCoverage: number;
67
+ readonly lastScreenspaceVolume: Vector3;
68
+ lastCentrality: number;
69
+ }
70
+ export {};
@@ -0,0 +1,381 @@
1
+ import { Box3, Frustum, Matrix4, Mesh, Sphere, Vector3 } from "three";
2
+ import { NEEDLE_progressive } from "./extension.js";
3
+ import { createLoaders } from "./loaders.js";
4
+ import { getParam } from "./utils.js";
5
+ const debugProgressiveLoading = getParam("debugprogressive");
6
+ const suppressProgressiveLoading = getParam("noprogressive");
7
+ /**
8
+ * The LODsManager class is responsible for managing the LODs and progressive assets in the scene. It will automatically update the LODs based on the camera position, screen coverage and mesh density of the objects.
9
+ * It must be enabled by calling the `enable` method.
10
+ *
11
+ * Instead of using the LODs manager directly you can also call `useNeedleProgressive` to enable progressive loading for a GLTFLoader
12
+ */
13
+ export class LODsManager {
14
+ /** Assign a function to draw debug lines for the LODs. This function will be called with the start and end position of the line and the color of the line when the `debugprogressive` query parameter is set.
15
+ */
16
+ static debugDrawLine;
17
+ /** @internal */
18
+ static getObjectLODState(object) {
19
+ return object.userData?.LOD_state;
20
+ }
21
+ renderer;
22
+ projectionScreenMatrix = new Matrix4();
23
+ cameraFrustrum = new Frustum();
24
+ /**
25
+ * The update interval in frames. If set to 0, the LODs will be updated every frame. If set to 1, the LODs will be updated every second frame, etc.
26
+ */
27
+ updateInterval = 0;
28
+ /**
29
+ * If set to true, the LODsManager will not update the LODs.
30
+ */
31
+ pause = false;
32
+ plugins = [];
33
+ constructor(renderer) {
34
+ this.renderer = renderer;
35
+ }
36
+ _frame = 0;
37
+ _originalRender;
38
+ /**
39
+ * Enable the LODsManager. This will replace the render method of the renderer with a method that updates the LODs.
40
+ */
41
+ enable() {
42
+ if (this._originalRender)
43
+ return;
44
+ let stack = 0;
45
+ // Save the original render method
46
+ this._originalRender = this.renderer.render;
47
+ const self = this;
48
+ createLoaders(this.renderer);
49
+ this.renderer.render = function (scene, camera) {
50
+ // check if this render call is rendering to a texture or the canvas
51
+ // if it's rendering to a texture we don't want to update the LODs
52
+ // This might need to be loosened later - e.g. we might want to update LODs for a render texture - but then we need to store the last LOD level differently and we also might not want to perform all the plugin calls?
53
+ const renderTarget = self.renderer.getRenderTarget();
54
+ if (renderTarget == null) {
55
+ stack = 0;
56
+ self._frame += 1;
57
+ }
58
+ const frame = self._frame;
59
+ const stack_level = stack++;
60
+ self.onBeforeRender(scene, camera, stack_level, frame);
61
+ self._originalRender.call(this, scene, camera);
62
+ self.onAfterRender(scene, camera, stack_level, frame);
63
+ };
64
+ }
65
+ disable() {
66
+ if (!this._originalRender)
67
+ return;
68
+ this.renderer.render = this._originalRender;
69
+ this._originalRender = undefined;
70
+ }
71
+ onBeforeRender(_scene, _camera, _stack, _frame) {
72
+ }
73
+ onAfterRender(scene, camera, stack, frame) {
74
+ if (this.pause)
75
+ return;
76
+ // we only want to update LODs during the main render call
77
+ if (stack == 0) {
78
+ if (suppressProgressiveLoading)
79
+ return;
80
+ if (this.updateInterval > 0 && frame % this.updateInterval != 0)
81
+ return;
82
+ this.projectionScreenMatrix.multiplyMatrices(camera.projectionMatrix, camera.matrixWorldInverse);
83
+ this.cameraFrustrum.setFromProjectionMatrix(this.projectionScreenMatrix, this.renderer.coordinateSystem);
84
+ const desiredDensity = 100_000;
85
+ // const isLowPerformanceDevice = false;// isMobileDevice();
86
+ // Experiment: quick & dirty performance-adaptive LODs
87
+ /*
88
+ if (this.context.time.smoothedFps < 59) {
89
+ currentAllowedDensity *= 0.5;
90
+ }
91
+ else if (this.context.time.smoothedFps >= 59) {
92
+ currentAllowedDensity *= 1.25;
93
+ }
94
+ */
95
+ const renderList = this.renderer.renderLists.get(scene, stack);
96
+ const opaque = renderList.opaque;
97
+ for (const entry of opaque) {
98
+ if (entry.material && (entry.geometry?.type === "BoxGeometry" || entry.geometry?.type === "BufferGeometry")) {
99
+ // Ignore the skybox
100
+ if (entry.material.name === "SphericalGaussianBlur" || entry.material.name == "BackgroundCubeMaterial" || entry.material.name === "CubemapFromEquirect" || entry.material.name === "EquirectangularToCubeUV") {
101
+ if (debugProgressiveLoading) {
102
+ if (!entry.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"]) {
103
+ entry.material["NEEDLE_PROGRESSIVE:IGNORE-WARNING"] = true;
104
+ console.warn("Ignoring skybox or BLIT object", entry, entry.material.name, entry.material.type);
105
+ }
106
+ }
107
+ continue;
108
+ }
109
+ }
110
+ const object = entry.object;
111
+ if (object instanceof Mesh || (object.isMesh)) {
112
+ this.updateLODs(scene, camera, object, desiredDensity);
113
+ }
114
+ }
115
+ const transparent = renderList.transparent;
116
+ for (const entry of transparent) {
117
+ const object = entry.object;
118
+ if (object instanceof Mesh || (object.isMesh)) {
119
+ this.updateLODs(scene, camera, object, desiredDensity);
120
+ }
121
+ }
122
+ }
123
+ }
124
+ /** Update the LOD levels for the renderer. */
125
+ updateLODs(scene, camera, object, desiredDensity) {
126
+ for (const plugin of this.plugins) {
127
+ plugin.onBeforeUpdateLOD?.(this.renderer, scene, camera, object);
128
+ }
129
+ let state = object.userData.LOD_state;
130
+ if (!state) {
131
+ state = new LOD_state();
132
+ object.userData.LOD_state = state;
133
+ }
134
+ let level = this.calculateLodLevel(camera, object, state, desiredDensity);
135
+ level = Math.round(level);
136
+ // we currently only support auto LOD changes for meshes
137
+ if (level >= 0) {
138
+ this.loadProgressiveMeshes(object, level);
139
+ }
140
+ // TODO: we currently can not switch texture lods because we need better caching for the textures internally (see copySettings in progressive + NE-4431)
141
+ let textureLOD = 0; // Math.max(0, LODlevel - 2)
142
+ if (object.material) {
143
+ const debugLevel = object["DEBUG:LOD"];
144
+ if (debugLevel != undefined)
145
+ textureLOD = debugLevel;
146
+ if (Array.isArray(object.material)) {
147
+ for (const mat of object.material) {
148
+ this.loadProgressiveTextures(mat, textureLOD);
149
+ }
150
+ }
151
+ else {
152
+ this.loadProgressiveTextures(object.material, textureLOD);
153
+ }
154
+ }
155
+ for (const plugin of this.plugins) {
156
+ plugin.onAfterUpdatedLOD?.(this.renderer, scene, camera, object, level);
157
+ }
158
+ state.lastLodLevel = level;
159
+ }
160
+ /** Load progressive textures for the given material
161
+ * @param material the material to load the textures for
162
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
163
+ * @returns Promise with true if the LOD was loaded, false if not
164
+ */
165
+ loadProgressiveTextures(material, level) {
166
+ if (!material)
167
+ return Promise.resolve(null);
168
+ if (material.userData && material.userData.LOD !== level) {
169
+ material.userData.LOD = level;
170
+ return NEEDLE_progressive.assignTextureLOD(material, level);
171
+ }
172
+ return Promise.resolve(null);
173
+ }
174
+ /** Load progressive meshes for the given mesh
175
+ * @param mesh the mesh to load the LOD for
176
+ * @param index the index of the mesh if it's part of a group
177
+ * @param level the LOD level to load. Level 0 is the best quality, higher levels are lower quality
178
+ * @returns Promise with true if the LOD was loaded, false if not
179
+ */
180
+ loadProgressiveMeshes(mesh, level) {
181
+ if (!mesh)
182
+ return Promise.resolve(null);
183
+ if (!mesh.userData)
184
+ mesh.userData = {};
185
+ if (mesh.userData.LOD !== level) {
186
+ mesh.userData.LOD = level;
187
+ const originalGeometry = mesh.geometry;
188
+ return NEEDLE_progressive.assignMeshLOD(mesh, level).then(res => {
189
+ if (res && mesh.userData.LOD == level && originalGeometry != mesh.geometry) {
190
+ // update the lightmap
191
+ // this.applyLightmapping();
192
+ // if (this.handles) {
193
+ // for (const inst of this.handles) {
194
+ // // if (inst["LOD"] < level) continue;
195
+ // // inst["LOD"] = level;
196
+ // inst.setGeometry(mesh.geometry);
197
+ // }
198
+ // }
199
+ }
200
+ return res;
201
+ });
202
+ }
203
+ return Promise.resolve(null);
204
+ }
205
+ // private testIfLODLevelsAreAvailable() {
206
+ _sphere = new Sphere();
207
+ _tempBox = new Box3();
208
+ tempMatrix = new Matrix4();
209
+ _tempWorldPosition = new Vector3();
210
+ _tempBoxSize = new Vector3();
211
+ _tempBox2Size = new Vector3();
212
+ static corner0 = new Vector3();
213
+ static corner1 = new Vector3();
214
+ static corner2 = new Vector3();
215
+ static corner3 = new Vector3();
216
+ calculateLodLevel(camera, mesh, state, desiredDensity) {
217
+ if (!mesh)
218
+ return -1;
219
+ // if this is using instancing we always load level 0
220
+ // if (this.isInstancingActive) return 0;
221
+ /** rough measure of "triangles on quadratic screen" – we're switching LODs based on this metric. */
222
+ /** highest LOD level we'd ever expect to be generated */
223
+ const maxLevel = 10;
224
+ let level = maxLevel + 1;
225
+ if (camera) {
226
+ if (debugProgressiveLoading && mesh["DEBUG:LOD"] != undefined) {
227
+ return mesh["DEBUG:LOD"];
228
+ }
229
+ // The mesh info contains also the density for all available LOD level so we can use this for selecting which level to show
230
+ const lodsInfo = NEEDLE_progressive.getMeshLODInformation(mesh.geometry);
231
+ const lods = lodsInfo?.lods;
232
+ // We can skip all this if we dont have any LOD information - we can ask the progressive extension for that
233
+ if (!lods || lods.length <= 0) {
234
+ return 99;
235
+ }
236
+ if (!this.cameraFrustrum?.intersectsObject(mesh)) {
237
+ // console.log("Mesh not visible");
238
+ // if (debugProgressiveLoading && mesh.geometry.boundingSphere) {
239
+ // const bounds = mesh.geometry.boundingSphere;
240
+ // this._sphere.copy(bounds);
241
+ // this._sphere.applyMatrix4(mesh.matrixWorld);
242
+ // Gizmos.DrawWireSphere(this._sphere.center, this._sphere.radius * 1.01, 0xff5555, .5);
243
+ // }
244
+ // the object is not visible by the camera
245
+ return 99;
246
+ }
247
+ const box = mesh.geometry.boundingBox;
248
+ if (box && camera.isPerspectiveCamera) {
249
+ const cam = camera;
250
+ // hack: if the mesh has vertex colors, has less than 100 vertices we always select the highest LOD
251
+ if (mesh.geometry.attributes.color && mesh.geometry.attributes.color.count < 100) {
252
+ if (mesh.geometry.boundingSphere) {
253
+ this._sphere.copy(mesh.geometry.boundingSphere);
254
+ this._sphere.applyMatrix4(mesh.matrixWorld);
255
+ const worldPosition = camera.getWorldPosition(this._tempWorldPosition);
256
+ if (this._sphere.containsPoint(worldPosition)) {
257
+ return 0;
258
+ }
259
+ }
260
+ }
261
+ // calculate size on screen
262
+ this._tempBox.copy(box);
263
+ this._tempBox.applyMatrix4(mesh.matrixWorld);
264
+ // Converting into projection space has the disadvantage that objects further to the side
265
+ // will have a much larger coverage, especially with high-field-of-view situations like in VR.
266
+ // Alternatively, we could attempt to calculate angular coverage (some kind of polar coordinates maybe?)
267
+ // or introduce a correction factor based on "expected distortion" of the object.
268
+ // High distortions would lead to lower LOD levels.
269
+ // "Centrality" of the calculated screen-space bounding box could be a factor here –
270
+ // what's the distance of the bounding box to the center of the screen?
271
+ this._tempBox.applyMatrix4(this.projectionScreenMatrix);
272
+ // TODO might need to be adjusted for cameras that are rendered during an XR session but are
273
+ // actually not XR cameras (e.g. a render texture)
274
+ if (this.renderer.xr.enabled && cam.fov > 70) {
275
+ // calculate centrality of the bounding box - how close is it to the screen center
276
+ const min = this._tempBox.min;
277
+ const max = this._tempBox.max;
278
+ let minX = min.x;
279
+ let minY = min.y;
280
+ let maxX = max.x;
281
+ let maxY = max.y;
282
+ // enlarge
283
+ const enlargementFactor = 2.0;
284
+ const centerBoost = 1.5;
285
+ const centerX = (min.x + max.x) * 0.5;
286
+ const centerY = (min.y + max.y) * 0.5;
287
+ minX = (minX - centerX) * enlargementFactor + centerX;
288
+ minY = (minY - centerY) * enlargementFactor + centerY;
289
+ maxX = (maxX - centerX) * enlargementFactor + centerX;
290
+ maxY = (maxY - centerY) * enlargementFactor + centerY;
291
+ const xCentrality = minX < 0 && maxX > 0 ? 0 : Math.min(Math.abs(min.x), Math.abs(max.x));
292
+ const yCentrality = minY < 0 && maxY > 0 ? 0 : Math.min(Math.abs(min.y), Math.abs(max.y));
293
+ const centrality = Math.max(xCentrality, yCentrality);
294
+ // heuristically determined to lower quality for objects at the edges of vision
295
+ state.lastCentrality = (centerBoost - centrality) * (centerBoost - centrality) * (centerBoost - centrality);
296
+ }
297
+ else {
298
+ state.lastCentrality = 1;
299
+ }
300
+ const boxSize = this._tempBox.getSize(this._tempBoxSize);
301
+ boxSize.multiplyScalar(0.5); // goes from -1..1, we want -0.5..0.5 for coverage in percent
302
+ if (screen.availHeight > 0)
303
+ boxSize.multiplyScalar(this.renderer.domElement.clientHeight / screen.availHeight); // correct for size of context on screen
304
+ boxSize.x *= cam.aspect;
305
+ const matView = camera.matrixWorldInverse;
306
+ const box2 = new Box3();
307
+ box2.copy(box);
308
+ box2.applyMatrix4(mesh.matrixWorld);
309
+ box2.applyMatrix4(matView);
310
+ const boxSize2 = box2.getSize(this._tempBox2Size);
311
+ // approximate depth coverage in relation to screenspace size
312
+ const max2 = Math.max(boxSize2.x, boxSize2.y);
313
+ const max1 = Math.max(boxSize.x, boxSize.y);
314
+ if (max1 != 0 && max2 != 0)
315
+ boxSize.z = boxSize2.z / Math.max(boxSize2.x, boxSize2.y) * Math.max(boxSize.x, boxSize.y);
316
+ state.lastScreenCoverage = Math.max(boxSize.x, boxSize.y, boxSize.z);
317
+ state.lastScreenspaceVolume.copy(boxSize);
318
+ state.lastScreenCoverage *= state.lastCentrality;
319
+ // draw screen size box
320
+ if (debugProgressiveLoading && LODsManager.debugDrawLine) {
321
+ const mat = this.tempMatrix.copy(this.projectionScreenMatrix);
322
+ mat.invert();
323
+ const corner0 = LODsManager.corner0;
324
+ const corner1 = LODsManager.corner1;
325
+ const corner2 = LODsManager.corner2;
326
+ const corner3 = LODsManager.corner3;
327
+ // get box corners, transform with camera space, and draw as quad lines
328
+ corner0.copy(this._tempBox.min);
329
+ corner1.copy(this._tempBox.max);
330
+ corner1.x = corner0.x;
331
+ corner2.copy(this._tempBox.max);
332
+ corner2.y = corner0.y;
333
+ corner3.copy(this._tempBox.max);
334
+ // draw outlines at the center of the box
335
+ const z = (corner0.z + corner3.z) * 0.5;
336
+ // all outlines should have the same depth in screen space
337
+ corner0.z = corner1.z = corner2.z = corner3.z = z;
338
+ corner0.applyMatrix4(mat);
339
+ corner1.applyMatrix4(mat);
340
+ corner2.applyMatrix4(mat);
341
+ corner3.applyMatrix4(mat);
342
+ LODsManager.debugDrawLine(corner0, corner1, 0x0000ff);
343
+ LODsManager.debugDrawLine(corner0, corner2, 0x0000ff);
344
+ LODsManager.debugDrawLine(corner1, corner3, 0x0000ff);
345
+ LODsManager.debugDrawLine(corner2, corner3, 0x0000ff);
346
+ }
347
+ let expectedLevel = 999;
348
+ // const framerate = this.context.time.smoothedFps;
349
+ if (lods && state.lastScreenCoverage > 0) {
350
+ for (let l = 0; l < lods.length; l++) {
351
+ const densityForThisLevel = lods[l].density;
352
+ const resultingDensity = densityForThisLevel / state.lastScreenCoverage;
353
+ if (resultingDensity < desiredDensity) {
354
+ expectedLevel = l;
355
+ break;
356
+ }
357
+ }
358
+ }
359
+ const isLowerLod = expectedLevel < level;
360
+ if (isLowerLod) {
361
+ level = expectedLevel;
362
+ }
363
+ }
364
+ // }
365
+ }
366
+ // if (this._lastLodLevel != level) {
367
+ // this._nextLodTestTime = this.context.time.realtimeSinceStartup + .5;
368
+ // if (debugProgressiveLoading) {
369
+ // if (debugProgressiveLoading == "verbose") console.warn(`LOD Level changed from ${this._lastLodLevel} to ${level} for ${this.name}`);
370
+ // this.drawGizmoLodLevel(true);
371
+ // }
372
+ // }
373
+ return level;
374
+ }
375
+ }
376
+ class LOD_state {
377
+ lastLodLevel = 0;
378
+ lastScreenCoverage = 0;
379
+ lastScreenspaceVolume = new Vector3();
380
+ lastCentrality = 0;
381
+ }
@@ -1,2 +1,2 @@
1
- export { patchModelViewer } from "./modelviewer.js";
2
- export { registerPlugin, type NEEDLE_progressive_plugin } from "./plugin.js";
1
+ export { patchModelViewer } from "./modelviewer.js";
2
+ export { registerPlugin, type NEEDLE_progressive_plugin } from "./plugin.js";
@@ -0,0 +1,2 @@
1
+ export { patchModelViewer } from "./modelviewer.js";
2
+ export { registerPlugin } from "./plugin.js";
@@ -0,0 +1,4 @@
1
+ /** Patch modelviewer to support NEEDLE progressive system
2
+ * @returns a function to remove the patch
3
+ */
4
+ export declare function patchModelViewer(modelviewer: HTMLElement): (() => void) | null;