Optimize mesh parsing and idle controls

This commit is contained in:
eust-w 2026-06-25 16:39:57 +08:00
parent 678125cb0f
commit a80d356962
5 changed files with 182 additions and 10 deletions

View File

@ -76,10 +76,19 @@ Important properties:
the default for local uploaded/custom OBJ assets. The product gate checks
`objFast`, `objLines`, `objStream`, and `fallback` counters so this
optimization remains measurable.
- Controlled `/assets/...` binary STL sources use a narrow triangle-buffer
parser for standard robot meshes, with Three.js `STLLoader` retained as
fallback and as the default for uploaded/custom STL assets. The release gate
checks `stlFast`, `stlTris`, `stlBytes`, and `fallback` counters so robot
mesh parse cost remains observable instead of hidden inside loader work.
- Large-scene diagnostics use adaptive stats refresh: user-visible events still
force an immediate panel update, while background periodic refreshes drop to
a lower cadence for large or paused scenes so long diagnostic strings do not
compete with WebGL interaction on the main thread.
- Large-scene camera controls skip idle `OrbitControls.update()` work when the
camera is not dirty and the damping tail has settled. The controls still wake
on `start/change/end` events and programmatic camera changes, while
`controls update/skip` diagnostics make idle main-thread savings observable.
- Dragging objects in the scene no longer rebuilds the builder object list,
scene outline, and inspector on every pointer event. Position edits are
coalesced during drag and flushed immediately on drag end, keeping WebGL
@ -432,8 +441,10 @@ Scene evidence:
- Frontend mesh source cache: parsed GLTF/OBJ/STL sources are retained across
scene rebuilds, while scene-owned clones still release their non-retained
resources. Controlled backend OBJ sources also use the fast parser before the
retained source enters the cache. The release gate now checks mesh cache
hit/miss plus `objFast/objLines/objStream/fallback` diagnostics.
retained source enters the cache, and controlled binary STL robot meshes use
the dedicated triangle-buffer parser. The release gate now checks mesh cache
hit/miss plus `objFast/objLines/objStream/fallback` and
`stlFast/stlTris/stlBytes/fallback` diagnostics.
- Camera-fit bounds cache: object world bounds are captured while creating
cached pick targets, so camera fitting no longer performs a second deep
`Box3.setFromObject` traversal across the full scene.
@ -619,8 +630,16 @@ Bundle evidence:
- Controlled OBJ fast parse gate: `browser-large-scene-performance-mode` now
requires `objFast > 0`, `objLines > 0`, `objStream > 0`, and
`objLoaderFallbackCount = 0` for the Wuying-backed store scene. The latest
product release gate recorded `objFast=16/fallback=0`, while uploaded/custom
OBJ assets keep the full Three.js `OBJLoader` path for compatibility.
product release gate recorded `objFast=16`, `objLines=173670`,
`objStream=53/5628890B`, and `fallback=0`, while uploaded/custom OBJ assets
keep the full Three.js `OBJLoader` path for compatibility.
- Controlled STL fast parse gate: the same performance gate requires
`stlFast > 0`, `stlTris > 0`, `stlBytes > 0`, and
`stlLoaderFallbackCount = 0` for Wuying-backed standard binary STL robot
meshes. The latest product release gate recorded `stlFast=35`,
`stlTris=393270`, `stlBytes=19666440B`, and `fallback=0`. Uploaded/custom STL
assets keep the full Three.js `STLLoader` path for compatibility with ASCII
STL, non-standard binary STL, and color-bearing variants.
- Fast OBJ parser allocation hygiene: controlled OBJ parsing stores source
positions, UVs, and normals in flat numeric arrays and triangulates faces
without per-triangle temporary arrays. It also scans the OBJ text one line at
@ -757,7 +776,7 @@ Control evidence:
`acceptanceLatency=0 ms / 11-0-0`,
`binding=635/636; 4/568`,
`builderPhysics=已添加物体 4: 后端动态 4 / 仅视觉 0`,
`renderPerformance=large-scene; target 45 fps; dpr 1.00; buffer preserved false; readback renders 1; shadows off; hover 32ms; load 1843-3089ms; frozen 135 prefrozen 59 spinSkip 627; instanced 568/16/16 matrices 568 cull 16 static 16 elidedLocal 568 virtualRoots 568; manual roots 68 updates 67; primitive geometries 7; mesh cache 51 sources 24/51 hit/miss objFast 16 objLines >0 objStream >0/fallback 0 retained 51g/17m; bounds cache 636 fast 627 scratch 695 source 51 hoverProxy 1-2 cached 1-2/fallback 0 camera traversals 0; scene batches 4/84 yields 26; state payload 34/602 reduced 1-2 incremental 3; poll 50/2000ms; pick targets 88/636; released 0g/0m/0t`.
`renderPerformance=large-scene; target 45 fps; dpr 1.00; buffer preserved false; readback renders 1; shadows off; hover 32ms; controls 10/1032 update/skip; load 1974ms; frozen 135 prefrozen 59 spinSkip 627; instanced 568/16/16 matrices 568 cull 16 static 16 elidedLocal 568 virtualRoots 568; manual roots 68 updates 67; primitive geometries 7; mesh cache 51 sources 24/51 hit/miss objFast 16 objLines 173670 objStream 53/5628890B/fallback 0 stlFast 35 stlTris 393270 stlBytes 19666440B/fallback 0 retained 51g/17m; bounds cache 636 fast 627 scratch 695 source 51 hoverProxy 1-2 cached 1-2/fallback 0 camera traversals 0; scene batches 4/84 yields 26; state payload 34/602 reduced 1 incremental 3; poll 50/2000ms; pick targets 88/636; released 0g/0m/0t`.
- Evidence screenshot artifacts:
`builder page; share page; import page; visual-only boundary canvas; desktop canvas; debug PNG; mobile canvas`
- Evidence export artifacts:

File diff suppressed because one or more lines are too long

View File

@ -204,6 +204,8 @@ interface RuntimeDiagnostics {
renderSkipCount: number;
lastRenderDurationMs: number;
readbackRenderCount: number;
controlsUpdateCount: number;
controlsUpdateSkippedCount: number;
hoverPickIntervalMs: number;
sceneLoadTotalMs: number;
sceneLoadConfigureMs: number;
@ -252,6 +254,10 @@ interface RuntimeDiagnostics {
fastObjStreamChunkCount: number;
fastObjStreamByteCount: number;
objLoaderFallbackCount: number;
fastStlParseCount: number;
fastStlTriangleCount: number;
fastStlByteCount: number;
stlLoaderFallbackCount: number;
retainedMeshGeometryCount: number;
retainedMeshMaterialCount: number;
sceneObjectBoundsCount: number;
@ -2811,6 +2817,8 @@ function currentRuntimeDiagnostics(
renderSkipCount: stats.renderSkipCount,
lastRenderDurationMs: stats.lastRenderDurationMs,
readbackRenderCount: stats.readbackRenderCount,
controlsUpdateCount: stats.controlsUpdateCount,
controlsUpdateSkippedCount: stats.controlsUpdateSkippedCount,
hoverPickIntervalMs: stats.hoverPickIntervalMs,
sceneLoadTotalMs: stats.sceneLoadTotalMs,
sceneLoadConfigureMs: stats.sceneLoadConfigureMs,
@ -2859,6 +2867,10 @@ function currentRuntimeDiagnostics(
fastObjStreamChunkCount: stats.fastObjStreamChunkCount,
fastObjStreamByteCount: stats.fastObjStreamByteCount,
objLoaderFallbackCount: stats.objLoaderFallbackCount,
fastStlParseCount: stats.fastStlParseCount,
fastStlTriangleCount: stats.fastStlTriangleCount,
fastStlByteCount: stats.fastStlByteCount,
stlLoaderFallbackCount: stats.stlLoaderFallbackCount,
retainedMeshGeometryCount: stats.retainedMeshGeometryCount,
retainedMeshMaterialCount: stats.retainedMeshMaterialCount,
sceneObjectBoundsCount: stats.sceneObjectBoundsCount,
@ -2965,7 +2977,7 @@ function currentDiagnosticsReport(): string {
function renderPerformanceLabel(stats: RuntimeDiagnostics["stats"]): string {
const mode = stats.largeSceneMode ? "large-scene" : "standard";
const shadows = stats.shadowsEnabled ? "shadows on" : "shadows off";
return `${mode}; target ${stats.targetRenderFps} fps; actual ${stats.actualRenderFps.toFixed(1)} fps; stats refresh ${stats.statsRefreshIntervalMs}ms ${stats.statsRefreshRenderCount}/${stats.statsRefreshSkipCount}; dpr ${stats.renderPixelRatio.toFixed(2)}; buffer preserved ${stats.preserveDrawingBufferEnabled}; readback renders ${stats.readbackRenderCount}; ${shadows}; skipped ${stats.renderSkipCount}; hover ${stats.hoverPickIntervalMs}ms; load ${Math.round(stats.sceneLoadTotalMs)}ms objects ${Math.round(stats.sceneLoadObjectsMs)}ms prewarm ${stats.instancedMeshPrewarmCount}/${Math.round(stats.instancedMeshPrewarmMs)}ms finalize ${Math.round(stats.instancedMeshFinalizeMs)}ms camera ${Math.round(stats.sceneLoadCameraFitMs)}ms; frozen ${stats.frozenStaticObjectCount} prefrozen ${stats.preFrozenMeshCloneCount} spinSkip ${stats.spinningScanSkippedCount}; instanced ${stats.instancedMeshObjectCount}/${stats.instancedMeshBatchCount}/${stats.instancedMeshDrawCount} matrices ${stats.instancedMeshMatrixUpdateCount} cull ${stats.instancedMeshFrustumCulledCount} static ${stats.instancedMeshStaticMatrixCount} elidedLocal ${stats.instancedLocalObjectElisionCount} virtualRoots ${stats.virtualInstancedRootCount}; manual roots ${stats.manualMatrixRootCount} updates ${stats.manualMatrixUpdateCount}; primitive geometries ${stats.primitiveGeometryCount}; mesh load limit ${stats.meshSourceLoadLimit} active ${stats.activeMeshSourceLoadCount} peak ${stats.peakMeshSourceLoadCount} queued ${stats.queuedMeshSourceLoadCount}; mesh cache ${stats.meshCacheSourceCount} sources ${stats.meshCacheHitCount}/${stats.meshCacheMissCount} hit/miss objFast ${stats.fastObjParseCount} objLines ${stats.fastObjLineScanCount} objStream ${stats.fastObjStreamChunkCount}/${stats.fastObjStreamByteCount}B/fallback ${stats.objLoaderFallbackCount} retained ${stats.retainedMeshGeometryCount}g/${stats.retainedMeshMaterialCount}m; bounds cache ${stats.sceneObjectBoundsCount} fast ${stats.fastPickProxyBoundsCount} scratch ${stats.pickBoundsScratchTransformCount} source ${stats.meshSourceBoundsCount} hoverProxy ${stats.hoverProxyBoundsHitCount} cached ${stats.hoverCachedBoundsHitCount}/fallback ${stats.hoverRootBoundsFallbackCount} camera traversals ${stats.cameraFitTraversalCount}; scene batches ${stats.sceneRootBatchCount}/${stats.batchedSceneRootCount} suppressed ${stats.sceneLoadSuppressedRenderCount} yields ${stats.sceneBuildYieldCount}; state payload ${stats.statePayloadBodyCount}/${stats.mergedBodyStateCount} reduced ${stats.reducedStateFrameCount} incremental ${stats.incrementalBodyMergeCount} poll ${stats.stateBasePollIntervalMs}/${stats.statePausedPollIntervalMs}/${stats.stateLastScheduledPollIntervalMs}ms ${stats.statePollRequestCount}/${stats.stateActivePollRequestCount}/${stats.statePausedPollRequestCount} semantic ${stats.stateParsedPollFrameCount}/${stats.stateForwardedPollFrameCount}/${stats.stateSkippedDuplicatePollFrameCount} hash ${stats.stateHashedPollFrameCount}/${stats.stateSkippedDuplicateHashPollFrameCount}/${stats.stateSkippedDuplicateSemanticPollFrameCount} notModified ${stats.stateNotModifiedPollFrameCount}; ui cache physics ${stats.objectPhysicsProfileCacheHitCount}/${stats.objectPhysicsProfileCacheMissCount} builder ${stats.builderPhysicsProfileCacheHitCount}/${stats.builderPhysicsProfileCacheMissCount} text ${stats.textWriteCount}/${stats.textWriteSkipCount} selector ${stats.textSelectorCacheHitCount}/${stats.textSelectorCacheMissCount} diagnostics ${stats.diagnosticsPanelRenderCount}/${stats.diagnosticsPanelSkipCount} builderPanels ${stats.builderPanelRenderCount}/${stats.builderPanelDeferredRenderCount}/${stats.builderPanelCoalescedRenderCount}; drag ${stats.dragMoveEventCount}/${stats.dragAppliedMoveCount}/${stats.dragCoalescedMoveCount}; pick targets ${stats.hoverPickTargetCount}/${stats.pickProxyCount}; state apply ${stats.appliedBodyStateCount}/skip ${stats.skippedBodyStateCount}; unchanged frames ${stats.unchangedFrameCount}; released ${stats.releasedGeometryCount}g/${stats.releasedMaterialCount}m/${stats.releasedTextureCount}t`;
return `${mode}; target ${stats.targetRenderFps} fps; actual ${stats.actualRenderFps.toFixed(1)} fps; stats refresh ${stats.statsRefreshIntervalMs}ms ${stats.statsRefreshRenderCount}/${stats.statsRefreshSkipCount}; dpr ${stats.renderPixelRatio.toFixed(2)}; buffer preserved ${stats.preserveDrawingBufferEnabled}; readback renders ${stats.readbackRenderCount}; ${shadows}; skipped ${stats.renderSkipCount}; controls ${stats.controlsUpdateCount}/${stats.controlsUpdateSkippedCount} update/skip; hover ${stats.hoverPickIntervalMs}ms; load ${Math.round(stats.sceneLoadTotalMs)}ms objects ${Math.round(stats.sceneLoadObjectsMs)}ms prewarm ${stats.instancedMeshPrewarmCount}/${Math.round(stats.instancedMeshPrewarmMs)}ms finalize ${Math.round(stats.instancedMeshFinalizeMs)}ms camera ${Math.round(stats.sceneLoadCameraFitMs)}ms; frozen ${stats.frozenStaticObjectCount} prefrozen ${stats.preFrozenMeshCloneCount} spinSkip ${stats.spinningScanSkippedCount}; instanced ${stats.instancedMeshObjectCount}/${stats.instancedMeshBatchCount}/${stats.instancedMeshDrawCount} matrices ${stats.instancedMeshMatrixUpdateCount} cull ${stats.instancedMeshFrustumCulledCount} static ${stats.instancedMeshStaticMatrixCount} elidedLocal ${stats.instancedLocalObjectElisionCount} virtualRoots ${stats.virtualInstancedRootCount}; manual roots ${stats.manualMatrixRootCount} updates ${stats.manualMatrixUpdateCount}; primitive geometries ${stats.primitiveGeometryCount}; mesh load limit ${stats.meshSourceLoadLimit} active ${stats.activeMeshSourceLoadCount} peak ${stats.peakMeshSourceLoadCount} queued ${stats.queuedMeshSourceLoadCount}; mesh cache ${stats.meshCacheSourceCount} sources ${stats.meshCacheHitCount}/${stats.meshCacheMissCount} hit/miss objFast ${stats.fastObjParseCount} objLines ${stats.fastObjLineScanCount} objStream ${stats.fastObjStreamChunkCount}/${stats.fastObjStreamByteCount}B/fallback ${stats.objLoaderFallbackCount} stlFast ${stats.fastStlParseCount} stlTris ${stats.fastStlTriangleCount} stlBytes ${stats.fastStlByteCount}B/fallback ${stats.stlLoaderFallbackCount} retained ${stats.retainedMeshGeometryCount}g/${stats.retainedMeshMaterialCount}m; bounds cache ${stats.sceneObjectBoundsCount} fast ${stats.fastPickProxyBoundsCount} scratch ${stats.pickBoundsScratchTransformCount} source ${stats.meshSourceBoundsCount} hoverProxy ${stats.hoverProxyBoundsHitCount} cached ${stats.hoverCachedBoundsHitCount}/fallback ${stats.hoverRootBoundsFallbackCount} camera traversals ${stats.cameraFitTraversalCount}; scene batches ${stats.sceneRootBatchCount}/${stats.batchedSceneRootCount} suppressed ${stats.sceneLoadSuppressedRenderCount} yields ${stats.sceneBuildYieldCount}; state payload ${stats.statePayloadBodyCount}/${stats.mergedBodyStateCount} reduced ${stats.reducedStateFrameCount} incremental ${stats.incrementalBodyMergeCount} poll ${stats.stateBasePollIntervalMs}/${stats.statePausedPollIntervalMs}/${stats.stateLastScheduledPollIntervalMs}ms ${stats.statePollRequestCount}/${stats.stateActivePollRequestCount}/${stats.statePausedPollRequestCount} semantic ${stats.stateParsedPollFrameCount}/${stats.stateForwardedPollFrameCount}/${stats.stateSkippedDuplicatePollFrameCount} hash ${stats.stateHashedPollFrameCount}/${stats.stateSkippedDuplicateHashPollFrameCount}/${stats.stateSkippedDuplicateSemanticPollFrameCount} notModified ${stats.stateNotModifiedPollFrameCount}; ui cache physics ${stats.objectPhysicsProfileCacheHitCount}/${stats.objectPhysicsProfileCacheMissCount} builder ${stats.builderPhysicsProfileCacheHitCount}/${stats.builderPhysicsProfileCacheMissCount} text ${stats.textWriteCount}/${stats.textWriteSkipCount} selector ${stats.textSelectorCacheHitCount}/${stats.textSelectorCacheMissCount} diagnostics ${stats.diagnosticsPanelRenderCount}/${stats.diagnosticsPanelSkipCount} builderPanels ${stats.builderPanelRenderCount}/${stats.builderPanelDeferredRenderCount}/${stats.builderPanelCoalescedRenderCount}; drag ${stats.dragMoveEventCount}/${stats.dragAppliedMoveCount}/${stats.dragCoalescedMoveCount}; pick targets ${stats.hoverPickTargetCount}/${stats.pickProxyCount}; state apply ${stats.appliedBodyStateCount}/skip ${stats.skippedBodyStateCount}; unchanged frames ${stats.unchangedFrameCount}; released ${stats.releasedGeometryCount}g/${stats.releasedMaterialCount}m/${stats.releasedTextureCount}t`;
}
function renderDiagnosticsPanel(
@ -3011,6 +3023,8 @@ function renderDiagnosticsPanel(
data.renderSkipCount = String(diagnostics.stats.renderSkipCount);
data.lastRenderDurationMs = diagnostics.stats.lastRenderDurationMs.toFixed(2);
data.readbackRenderCount = String(diagnostics.stats.readbackRenderCount);
data.controlsUpdateCount = String(diagnostics.stats.controlsUpdateCount);
data.controlsUpdateSkippedCount = String(diagnostics.stats.controlsUpdateSkippedCount);
data.hoverPickIntervalMs = String(diagnostics.stats.hoverPickIntervalMs);
data.sceneLoadTotalMs = diagnostics.stats.sceneLoadTotalMs.toFixed(2);
data.sceneLoadConfigureMs = diagnostics.stats.sceneLoadConfigureMs.toFixed(2);
@ -3059,6 +3073,10 @@ function renderDiagnosticsPanel(
data.fastObjStreamChunkCount = String(diagnostics.stats.fastObjStreamChunkCount);
data.fastObjStreamByteCount = String(diagnostics.stats.fastObjStreamByteCount);
data.objLoaderFallbackCount = String(diagnostics.stats.objLoaderFallbackCount);
data.fastStlParseCount = String(diagnostics.stats.fastStlParseCount);
data.fastStlTriangleCount = String(diagnostics.stats.fastStlTriangleCount);
data.fastStlByteCount = String(diagnostics.stats.fastStlByteCount);
data.stlLoaderFallbackCount = String(diagnostics.stats.stlLoaderFallbackCount);
data.retainedMeshGeometryCount = String(diagnostics.stats.retainedMeshGeometryCount);
data.retainedMeshMaterialCount = String(diagnostics.stats.retainedMeshMaterialCount);
data.sceneObjectBoundsCount = String(diagnostics.stats.sceneObjectBoundsCount);

View File

@ -252,6 +252,9 @@ export class UniversalPreviewer {
private renderSkipCount = 0;
private lastRenderDurationMs = 0;
private readbackRenderCount = 0;
private controlsUpdateCount = 0;
private controlsUpdateSkippedCount = 0;
private controlsUpdateTrailUntil = 0;
private renderWindowStartedAt = 0;
private renderWindowFrameCount = 0;
private measuredRenderFps = 0;
@ -294,6 +297,10 @@ export class UniversalPreviewer {
private fastObjStreamChunkCount = 0;
private fastObjStreamByteCount = 0;
private objLoaderFallbackCount = 0;
private fastStlParseCount = 0;
private fastStlTriangleCount = 0;
private fastStlByteCount = 0;
private stlLoaderFallbackCount = 0;
private sceneObjectBoundsCount = 0;
private fastPickProxyBoundsCount = 0;
private pickBoundsScratchTransformCount = 0;
@ -391,6 +398,9 @@ export class UniversalPreviewer {
};
this.controls.screenSpacePanning = true;
this.controls.target.set(0, 1, 0);
this.controls.addEventListener("start", this.handleControlsActivity);
this.controls.addEventListener("change", this.handleControlsActivity);
this.controls.addEventListener("end", this.handleControlsActivity);
this.camera.position.set(5.5, 4.6, 7.2);
this.setupCameraInput();
this.resize();
@ -615,6 +625,8 @@ export class UniversalPreviewer {
renderSkipCount: this.renderSkipCount,
lastRenderDurationMs: this.lastRenderDurationMs,
readbackRenderCount: this.readbackRenderCount,
controlsUpdateCount: this.controlsUpdateCount,
controlsUpdateSkippedCount: this.controlsUpdateSkippedCount,
hoverPickIntervalMs: this.hoverPickIntervalMs,
sceneLoadTotalMs: this.sceneLoadTotalMs,
sceneLoadConfigureMs: this.sceneLoadConfigureMs,
@ -665,6 +677,10 @@ export class UniversalPreviewer {
fastObjStreamChunkCount: this.fastObjStreamChunkCount,
fastObjStreamByteCount: this.fastObjStreamByteCount,
objLoaderFallbackCount: this.objLoaderFallbackCount,
fastStlParseCount: this.fastStlParseCount,
fastStlTriangleCount: this.fastStlTriangleCount,
fastStlByteCount: this.fastStlByteCount,
stlLoaderFallbackCount: this.stlLoaderFallbackCount,
retainedMeshGeometryCount: this.retainedMeshGeometries.size,
retainedMeshMaterialCount: this.retainedMeshMaterials.size,
sceneObjectBoundsCount: this.sceneObjectBoundsCount,
@ -779,6 +795,9 @@ export class UniversalPreviewer {
}
this.primitiveGeometryCache.clear();
this.renderer.dispose();
this.controls.removeEventListener("start", this.handleControlsActivity);
this.controls.removeEventListener("change", this.handleControlsActivity);
this.controls.removeEventListener("end", this.handleControlsActivity);
this.controls.dispose();
}
@ -832,7 +851,7 @@ export class UniversalPreviewer {
if (now < this.renderSuspendedUntil) {
return;
}
const controlsChanged = this.controls.update();
const controlsChanged = this.updateControlsIfNeeded(now);
const focusChanged = this.updateFocusMarker();
const spinChanged = this.updateSpinningObjects(this.clock.getElapsedTime());
const renderIntervalMs = this.sceneLoadInProgress
@ -852,6 +871,29 @@ export class UniversalPreviewer {
this.updateRenderFps(performance.now());
};
private handleControlsActivity = (): void => {
this.controlsUpdateTrailUntil = performance.now() + 360;
this.markRenderDirty();
};
private updateControlsIfNeeded(now: number): boolean {
if (
this.largeSceneMode
&& !this.renderDirty
&& !this.dragState
&& now >= this.controlsUpdateTrailUntil
) {
this.controlsUpdateSkippedCount += 1;
return false;
}
this.controlsUpdateCount += 1;
const controlsChanged = this.controls.update();
if (controlsChanged) {
this.controlsUpdateTrailUntil = now + 360;
}
return controlsChanged;
}
private renderForReadback(): void {
const renderStartedAt = performance.now();
this.renderer.render(this.scene, this.camera);
@ -1253,6 +1295,9 @@ export class UniversalPreviewer {
this.renderSkipCount = 0;
this.lastRenderDurationMs = 0;
this.readbackRenderCount = 0;
this.controlsUpdateCount = 0;
this.controlsUpdateSkippedCount = 0;
this.controlsUpdateTrailUntil = 0;
this.measuredRenderFps = 0;
this.frozenStaticObjectCount = 0;
this.preFrozenMeshCloneCount = 0;
@ -1272,6 +1317,10 @@ export class UniversalPreviewer {
this.fastObjStreamChunkCount = 0;
this.fastObjStreamByteCount = 0;
this.objLoaderFallbackCount = 0;
this.fastStlParseCount = 0;
this.fastStlTriangleCount = 0;
this.fastStlByteCount = 0;
this.stlLoaderFallbackCount = 0;
this.sceneObjectBounds.makeEmpty();
this.sceneObjectBoundsCount = 0;
this.fastPickProxyBoundsCount = 0;
@ -2910,8 +2959,7 @@ export class UniversalPreviewer {
const gltf = await this.gltfLoader.loadAsync(geometry.url);
loaded = gltf.scene;
} else if (format === "stl") {
const stl = await this.stlLoader.loadAsync(geometry.url);
loaded = new THREE.Mesh(stl, material);
loaded = await this.loadStlSource(geometry.url, material);
} else if (format === "obj") {
loaded = await this.loadObjSource(geometry.url, material);
} else {
@ -2929,6 +2977,75 @@ export class UniversalPreviewer {
return loaded;
}
private async loadStlSource(url: string, material: THREE.Material): Promise<THREE.Object3D> {
if (!this.shouldUseFastStlParser(url)) {
const stl = await this.stlLoader.loadAsync(url);
return new THREE.Mesh(stl, material);
}
try {
const response = await fetch(url);
if (!response.ok) {
throw new Error(`STL fetch failed ${response.status}`);
}
const bytes = await response.arrayBuffer();
const geometry = this.parseBinaryStlMesh(bytes);
this.fastStlParseCount += 1;
this.fastStlByteCount += bytes.byteLength;
return new THREE.Mesh(geometry, material);
} catch {
this.stlLoaderFallbackCount += 1;
const stl = await this.stlLoader.loadAsync(url);
return new THREE.Mesh(stl, material);
}
}
private shouldUseFastStlParser(url: string): boolean {
if (url.startsWith("blob:") || url.startsWith("data:")) {
return false;
}
try {
return new URL(url, window.location.href).pathname.includes("/assets/");
} catch {
return url.includes("/assets/");
}
}
private parseBinaryStlMesh(data: ArrayBuffer): THREE.BufferGeometry {
if (data.byteLength < 84) {
throw new Error("binary STL is too small");
}
const reader = new DataView(data);
const faces = reader.getUint32(80, true);
const expectedBytes = 84 + faces * 50;
if (expectedBytes !== data.byteLength) {
throw new Error("STL is not standard binary layout");
}
const vertices = new Float32Array(faces * 9);
const normals = new Float32Array(faces * 9);
for (let face = 0; face < faces; face += 1) {
const sourceOffset = 84 + face * 50;
const targetOffset = face * 9;
const normalX = reader.getFloat32(sourceOffset, true);
const normalY = reader.getFloat32(sourceOffset + 4, true);
const normalZ = reader.getFloat32(sourceOffset + 8, true);
for (let vertex = 0; vertex < 3; vertex += 1) {
const vertexSourceOffset = sourceOffset + 12 + vertex * 12;
const componentOffset = targetOffset + vertex * 3;
vertices[componentOffset] = reader.getFloat32(vertexSourceOffset, true);
vertices[componentOffset + 1] = reader.getFloat32(vertexSourceOffset + 4, true);
vertices[componentOffset + 2] = reader.getFloat32(vertexSourceOffset + 8, true);
normals[componentOffset] = normalX;
normals[componentOffset + 1] = normalY;
normals[componentOffset + 2] = normalZ;
}
}
const geometry = new THREE.BufferGeometry();
geometry.setAttribute("position", new THREE.BufferAttribute(vertices, 3));
geometry.setAttribute("normal", new THREE.BufferAttribute(normals, 3));
this.fastStlTriangleCount += faces;
return geometry;
}
private async loadObjSource(url: string, material: THREE.Material): Promise<THREE.Object3D> {
if (!this.shouldUseFastObjParser(url)) {
return this.objLoader.loadAsync(url);

View File

@ -207,6 +207,8 @@ export interface RendererStats {
renderSkipCount: number;
lastRenderDurationMs: number;
readbackRenderCount: number;
controlsUpdateCount: number;
controlsUpdateSkippedCount: number;
hoverPickIntervalMs: number;
sceneLoadTotalMs: number;
sceneLoadConfigureMs: number;
@ -257,6 +259,10 @@ export interface RendererStats {
fastObjStreamChunkCount: number;
fastObjStreamByteCount: number;
objLoaderFallbackCount: number;
fastStlParseCount: number;
fastStlTriangleCount: number;
fastStlByteCount: number;
stlLoaderFallbackCount: number;
retainedMeshGeometryCount: number;
retainedMeshMaterialCount: number;
sceneObjectBoundsCount: number;