import { BufferGeometry, BoxGeometry, Color, DirectionalLight, GridHelper, Group, InstancedMesh, LineBasicMaterial, LineSegments, Matrix3, Matrix4, Mesh, MeshBasicMaterial, HemisphereLight, MeshPhysicalMaterial, Raycaster, PerspectiveCamera, Scene, type Object3D, WebGLRenderer, Float32BufferAttribute, Uint32BufferAttribute, Vector2, Vector3, DataTexture, EquirectangularReflectionMapping, FloatType, LinearSRGBColorSpace, PMREMGenerator, RGBAFormat, SRGBColorSpace, type Texture, } from "../vendor/three/three.module.js"; import { applyStudioShading, usesStudioMaterial, type SolidShadingOptions } from "./studio-light"; import { createStudioWorldTexture, fetchStudioWorld, isStudioWorldLight, studioWorldReport, STUDIO_WORLD_DEFAULT } from "./studio-environment"; import { WorkbenchPost } from "./workbench-post"; import { pickSurface, projectBrushRing, type BrushCursorRing, type SurfacePick } from "./viewport-surface-math"; import {ViewportNavigation} from './viewport-navigation'; import {nodeDisplayMatrix} from './node-display-matrix'; import type { MaterialIR, SceneNodeIR, SceneSnapshotIR } from "../../../protocol/scene-ir"; import { applySceneDelta, sceneDeltaRequiresRendererRebuild, type SceneDelta } from "../../../protocol/scene-delta"; import type { MeshElementMode, MeshGeometryBuffer, WebEngineLODLevelResult } from "../../../protocol/web-engine"; import { ThreeLODAdapter, type ThreeLODLevel, type LODSelectionResult } from "./lod"; import { configurePBRLight, configurePBRCamera, configurePBRRenderer, createPBRLight, createPBRMaterial, PBR_PROFILE, PBR_SHADOW_MAP_DIMENSION, PBR_SHADOW_PROFILE, PBR_TONE_MAPPING, setPBRMaterialSelected, } from "./pbr"; import { GPUTextureStore } from "./texture-assets"; import type { GPUTextureAsset } from "../../../protocol/render-assets"; import { gateEnvironmentImage, gateUDIMImage } from "../../../protocol/render-assets"; import { planPBRLightingBudget, type PBRLightingBudgetReport } from "../../../protocol/render-budget"; import { applyCurveHandlePreview, applyNonMeshElementSelection, applyNonMeshTransform, createNonMeshObject, type NonMeshElementKind } from "./nonmesh"; import type { NonMeshGeometryChunk } from "../../../protocol/nonmesh-binary"; import type { CurveGizmoFrameIR, CurveGizmoHandleIR, CurveGizmoScreenFrameIR } from "../../../protocol/nonmesh-interaction"; import type { NanoVDBViewportAssetIR, NanoVDBViewportRenderResultIR } from "../volume/nanovdb-viewport"; import { NANOVDB_VIEWPORT_PREVIEW_SIZE, NanoVDBViewportRenderSession, renderNanoVDBViewportAsset } from "../volume/nanovdb-viewport"; import { createNanoVDBViewportObject } from "./volume"; import { applyGreasePencilPointSelection, applyGreasePencilPointPreview, applyGreasePencilTransform, createGreasePencilObject, greasePencilMarqueeCandidates, greasePencilPointRef, type GreasePencilPointRef, type GreasePencilPointPreview, } from "./grease-pencil"; import { selectGreasePencilMarquee, type GreasePencilDrawingScopeIR, type GreasePencilMarqueeBoxIR, type GreasePencilMarqueeResultIR, } from "../../../protocol/grease-pencil-marquee"; import { validatePaintDepthVisibilityRequest, type PaintDepthVisibilityRequestIR, type PaintDepthVisibilityResultIR } from "../../../protocol/paint-depth-visibility"; import { samplePaintDepthVisibilityGPU } from "./paint-depth-visibility"; import { resolveViewportPixelMetrics, viewportNDC } from "../../../protocol/viewport-dpr"; import { observePointerEvent } from "../../../protocol/pointer-contract"; import { createInputModalState, reduceInputModal, type InputModalState } from "../../../protocol/input-modal"; export function collectMeshInstanceGroups(snapshot: SceneSnapshotIR, minimumSize = 2): Map { const groups = new Map(); for (const node of snapshot.nodes) { if (node.type !== "MESH" || !node.visible || !node.dataId) continue; const ids = groups.get(node.dataId) ?? []; ids.push(node.id); groups.set(node.dataId, ids); } for (const [meshId, ids] of groups) if (ids.length < minimumSize) groups.delete(meshId); return groups; } /** Three.js owns the browser viewport; Blender's Z-up coordinates are adapted at the boundary. */ export type ViewportShadingMode = 'WIREFRAME' | 'SOLID' | 'MATERIAL' | 'RENDERED'; export class ViewportRenderer { readonly renderer: WebGLRenderer; readonly scene: Scene; private readonly navigation:ViewportNavigation; get camera(){return this.navigation.camera;} get controls(){return this.navigation.controls;} setSceneCamera(frame:Parameters[0]){this.navigation.setSceneCamera(frame);} setCameraWriteHandler(handler:Parameters[0]){this.navigation.setCameraWriteHandler(handler);} toggleCameraView(){this.navigation.toggleCameraView();} setCameraLock(locked:boolean){this.navigation.setCameraLock(locked);} /** Navigation sensitivity preferences (orbit/zoom scale, wheel inversion). */ setNavigationPrefs(prefs:Parameters[0]){this.navigation.setNavigationPrefs(prefs);} /* Viewport shading mirrors the desktop header dropdown: WIREFRAME, SOLID, * MATERIAL and RENDERED. All four are display-only; geometry is untouched. */ setShadingMode(mode:ViewportShadingMode){if(this.shadingMode===mode)return;this.shadingMode=mode;this.applyShadingMode();this.canvas.dataset.shadingMode=mode.toLowerCase();this.requestRender();} getShadingMode(){return this.shadingMode;} /** Solid-mode lighting: the studio rig preset, matcap layers, shadow mask. */ setSolidShading(options:SolidShadingOptions){ this.solidShading={...this.solidShading,...options}; if(usesStudioMaterial(this.shadingMode)||this.shadingMode==='MATERIAL'){this.applyShadingMode();this.requestRender();} } getSolidShading(){return this.solidShading;} setXray(enabled:boolean){if(this.xray===enabled)return;this.xray=enabled;this.applyShadingMode();this.canvas.dataset.xray=enabled?'1':'0';this.requestRender();} /* Screen->surface pick for sculpt strokes: without a real hit the stroke * has no position on the mesh, only a screen coordinate. */ pickSurfacePoint(clientX:number,clientY:number):SurfacePick|null{ const bounds=this.canvas.getBoundingClientRect(); if(bounds.width<=0||bounds.height<=0)return null; const ndc=viewportNDC(clientX,clientY,bounds); return pickSurface(this.raycaster,this.camera,this.importedRoot,ndc.x,ndc.y); } getXray(){return this.xray;} /** * Screen-space sculpt cursor ring. Blender projects two points on the brush * tangent plane and takes their pixel distance (paint_cursor/../paint_cursor.cc * brush_radius_project), so the ring stays correct under any camera distance. */ projectBrushCursor(clientX:number,clientY:number,radius:number):BrushCursorRing|null{ const bounds=this.canvas.getBoundingClientRect(); if(bounds.width<=0||bounds.height<=0)return null; const ndc=viewportNDC(clientX,clientY,bounds); return projectBrushRing(this.raycaster,this.camera,this.importedRoot,ndc.x,ndc.y,radius,bounds.width,bounds.height); } isCameraView(){return this.navigation.isCameraView();} isCameraLocked(){return this.navigation.isCameraLocked();} getCameraFraming(){return this.navigation.getCameraFraming();} private readonly canvas: HTMLCanvasElement; private readonly importedRoot = new Group(); private readonly importedLights = new Group(); private readonly resizeObserver: ResizeObserver; private animationFrame = 0; private disposed = false; private renderRequested = true; private readonly requestRender = () => { this.renderRequested = true; }; private contextLost = false; private currentSnapshot: SceneSnapshotIR | null = null; private readonly objectByBlenderId = new Map(); private readonly instanceIndexByBlenderId = new Map(); private readonly lodAdapter = new ThreeLODAdapter(); private readonly textureStore = new GPUTextureStore("THREE_WEBGL2"); private readonly raycaster = new Raycaster(); private readonly pointer = new Vector2(); private inputModal: InputModalState = createInputModalState(); private readonly onSelect?: (objectId: string, additive: boolean) => void; private readonly onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void; private readonly onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void; private readonly onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void; private editMode = false; private selectionMode: MeshElementMode = "FACE"; private greasePencilSelectionRevision = 0; private curveGizmoFrame: { dataId: string; frame: CurveGizmoFrameIR } | null = null; private curveGizmoScreenFrame = ""; private volumeAssets: NanoVDBViewportAssetIR[] = []; private readonly volumeRenderCache = new Map(); private volumeRenderGeneration = 0; private shadingMode: ViewportShadingMode = 'MATERIAL'; private xray = false; private selectedObjectIds: ReadonlySet = new Set(); /* V3D_LIGHTING_STUDIO / V3D_LIGHTING_MATCAP, plus the chosen preset. */ private solidShading: SolidShadingOptions = {}; /* scene.environment saved while SOLID replaces it with analytic lighting. */ private savedEnvironment: import("../vendor/three/three.module.js").Texture | null | undefined; /* Desktop Material Preview always lights PBR from a studio light; metals have * no diffuse term, so without an environment they render black. */ private previewEnvironment: Texture | null = null; private previewFallbackEnvironment: Texture | null = null; private previewEnvironmentRequest: Promise | null = null; /* Desktop Viewport Shading studio-light selection (studiolights/world/*.exr). */ private previewStudioLight: string = STUDIO_WORLD_DEFAULT; /* Workbench screen-space cavity/curvature; idles as a pass-through. */ private readonly workbenchPost = new WorkbenchPost(); private readonly volumeRenderSession: NanoVDBViewportRenderSession; constructor( canvas: HTMLCanvasElement, onSelect?: (objectId: string, additive: boolean) => void, onElementSelect?: (meshId: string, mode: MeshElementMode, index: number, additive: boolean, nonMeshKind?: NonMeshElementKind) => void, onGreasePencilPointSelect?: (point: GreasePencilPointRef, mode: "REPLACE" | "ADD" | "SUBTRACT", baseSelectionRevision: number) => void, onGreasePencilMarqueeSelect?: (result: GreasePencilMarqueeResultIR, mode: "REPLACE" | "ADD" | "SUBTRACT") => void, ) { this.canvas = canvas; this.onSelect = onSelect; this.onElementSelect = onElementSelect; this.onGreasePencilPointSelect = onGreasePencilPointSelect; this.onGreasePencilMarqueeSelect = onGreasePencilMarqueeSelect; this.volumeRenderSession = new NanoVDBViewportRenderSession(() => { if (this.disposed) return; this.volumeRenderCache.clear(); this.canvas.dataset.volumeStatus = "loading"; void this.refreshVolumes(); }); this.raycaster.params.Points.threshold = 0.14; this.renderer = new WebGLRenderer({ canvas, antialias: true, alpha: false, preserveDrawingBuffer: true }); configurePBRRenderer(this.renderer); this.renderer.setPixelRatio(resolveViewportPixelMetrics(1, 1, window.devicePixelRatio).pixelRatio); this.renderer.setClearColor(new Color("#25272b")); this.canvas.dataset.rendererBackend = "webgl-pbr"; this.canvas.dataset.pbrProfile = PBR_PROFILE; this.canvas.dataset.toneMapping = PBR_TONE_MAPPING; this.canvas.dataset.shadowMap = PBR_SHADOW_PROFILE; this.canvas.dataset.deviceStatus = "ready"; this.scene = new Scene(); this.navigation = new ViewportNavigation(canvas,()=>this.requestRender()); this.canvas.addEventListener("webglcontextrestored", this.requestRender); this.scene.add(new HemisphereLight(0xf2f5ff, 0x3a4149, 0.55)); const keyLight = new DirectionalLight(0xffffff, 2.5); keyLight.position.set(4, -5, 8); keyLight.castShadow = true; keyLight.shadow.mapSize.set(PBR_SHADOW_MAP_DIMENSION, PBR_SHADOW_MAP_DIMENSION); keyLight.shadow.bias = -0.0005; keyLight.shadow.normalBias = 0.03; this.scene.add(keyLight, keyLight.target); /* Overlay semantics. Desktop draws the grid in the overlay engine * (`overlay_instance.cc:364`), after workbench has already consumed its own * depth buffer, so it never reaches `workbench_cavity.bsl.hh`. It also never * writes depth there. With depth writes on, the web grid lands in the cavity * depth texture: a line pixel's neighbours are all background, so the 3-tap * `view_normal` reconstructs a degenerate normal, the obscurance loop then * reads the grid as a fully occluded crease and darkens it to black. */ const grid = new GridHelper(20, 20, 0x60656e, 0x383b42); grid.material.depthWrite = false; this.scene.add(grid); this.scene.add(this.importedRoot); this.scene.add(this.importedLights); this.resizeObserver = new ResizeObserver(() => this.resize()); this.resizeObserver.observe(canvas); this.canvas.addEventListener("click", this.handleClick); this.canvas.addEventListener("pointerdown", this.handlePointerObservation); this.canvas.addEventListener("pointerup", this.handlePointerObservation); this.canvas.addEventListener("pointercancel", this.handlePointerObservation); this.canvas.addEventListener("webglcontextlost", this.handleContextLost); this.canvas.addEventListener("webglcontextrestored", this.handleContextRestored); this.resize(); this.controls.update(); this.publishCameraState(); this.publishInputModal(); this.renderLoop(); } setSnapshot(snapshot: SceneSnapshotIR, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void { this.navigation.setSnapshot(snapshot); this.requestRender(); this.currentSnapshot = snapshot; const udim = snapshot.images.find((image) => image.tiles && image.tiles.length > 0); if (udim) { const gate = gateUDIMImage(udim); this.canvas.dataset.udimGate = gate.status.toLowerCase(); this.canvas.dataset.udimGateCode = gate.issues[0]?.code ?? ""; } const worldId = snapshot.scenes[0]?.worldId; const world = snapshot.worlds.find((candidate) => candidate.id === worldId) ?? snapshot.worlds[0]; if (world?.environmentImageId) { const gate = gateEnvironmentImage(snapshot.images.find((image) => image.id === world.environmentImageId)); this.canvas.dataset.iblGate = gate.status.toLowerCase(); this.canvas.dataset.iblGateCode = gate.issues[0]?.code ?? ""; } this.objectByBlenderId.clear(); this.instanceIndexByBlenderId.clear(); this.lodAdapter.clear(); this.clearImportedScene(); this.applyWorld(snapshot); const lightingBudget = planPBRLightingBudget(snapshot, "THREE_WEBGL2"); this.publishLightingBudget(lightingBudget); this.populateLights(snapshot, lightingBudget); this.populateNonMesh(snapshot, nonMeshGeometryBuffers); this.populateGreasePencils(snapshot); const meshes = new Map(snapshot.meshes.map((mesh) => [mesh.id, mesh])); const binaryGeometry = new Map(geometryBuffers.map((payload) => [payload.meshId, payload])); for (const node of snapshot.nodes) { if (node.type !== "MESH" || !node.visible || !node.dataId) continue; const summary = meshes.get(node.dataId); if (!summary) continue; const materialById = new Map(snapshot.materials.map((material) => [material.id, material])); const fallbackMaterial = this.createMaterial(undefined, node.id === snapshot.activeObjectId); const materials = (summary.materialSlotIds ?? []) .map((id) => materialById.get(id)) .map((material) => this.createMaterial(material, node.id === snapshot.activeObjectId)); if (materials.length === 0) materials.push(fallbackMaterial); let geometry: BufferGeometry = new BoxGeometry(2, 2, 2); const payload = binaryGeometry.get(summary.id); /* Vertex colour is an opt-in attribute: a mesh without a COLOR attribute must * keep the material base colour, otherwise the shader multiplies by the * (0,0,0) default and every uncoloured mesh renders black. */ const usesVertexColor = Boolean(payload?.colors ?? summary.colors); for (const material of materials) material.vertexColors = usesVertexColor; const positionsData = payload ? new Float32Array(payload.positions) : summary.positions; const indicesData = payload ? new Uint32Array(payload.indices) : summary.indices; const normalsData = payload?.normals ? new Float32Array(payload.normals) : summary.normals; const triangleCornerData = payload?.triangleCornerIndices ? new Uint32Array(payload.triangleCornerIndices) : summary.triangleCornerIndices; const triangleFaceData = payload?.triangleFaceIndices ? new Uint32Array(payload.triangleFaceIndices) : summary.triangleFaceIndices; const uvData = payload?.uvs ? new Float32Array(payload.uvs) : summary.uvs; const colorData = payload?.colors ? new Float32Array(payload.colors) : summary.colors; const triangleMaterialData = payload?.triangleMaterialIndices ? new Uint32Array(payload.triangleMaterialIndices) : summary.triangleMaterialIndices; if ((summary.geometryStatus === "available" || summary.geometryStatus === "binary") && positionsData && indicesData) { geometry = new BufferGeometry(); const hasCornerAttributes = Boolean(triangleCornerData && (uvData || colorData)); if (hasCornerAttributes && triangleCornerData) { const positions: number[] = []; const normals: number[] = []; const uvs: number[] = []; const colors: number[] = []; for (let index = 0; index < indicesData.length; index++) { const vertex = indicesData[index] * 3; positions.push(positionsData[vertex], positionsData[vertex + 2], -positionsData[vertex + 1]); if (normalsData) { normals.push(normalsData[vertex], normalsData[vertex + 2], -normalsData[vertex + 1]); } const corner = triangleCornerData[index]; if (uvData) uvs.push(uvData[corner * 2], uvData[corner * 2 + 1]); if (colorData) colors.push(colorData[corner * 4], colorData[corner * 4 + 1], colorData[corner * 4 + 2], colorData[corner * 4 + 3]); } geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); if (normals.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); if (uvs.length > 0) geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); if (colors.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(colors, 4)); } else { const positions = new Array(positionsData.length); for (let index = 0; index < positionsData.length; index += 3) { // Blender Z-up/right-handed -> Three.js Y-up/right-handed. positions[index] = positionsData[index]; positions[index + 1] = positionsData[index + 2]; positions[index + 2] = -positionsData[index + 1]; } geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); if (normalsData) { const normals = new Array(normalsData.length); for (let index = 0; index < normalsData.length; index += 3) { normals[index] = normalsData[index]; normals[index + 1] = normalsData[index + 2]; normals[index + 2] = -normalsData[index + 1]; } geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } geometry.setIndex(new Uint32BufferAttribute(indicesData, 1)); if (!normalsData) geometry.computeVertexNormals(); } if (triangleMaterialData && materials.length > 1) { for (let triangle = 0; triangle < triangleMaterialData.length; triangle++) { const materialIndex = Math.min(triangleMaterialData[triangle], materials.length - 1); geometry.addGroup(triangle * 3, 3, materialIndex); } } } const mesh = new Mesh(geometry, materials.length === 1 ? materials[0] : materials); mesh.castShadow = true; mesh.receiveShadow = true; mesh.name = node.name; // Summary-only meshes use a bounded proxy until their transferable geometry is available. mesh.matrixAutoUpdate=false; mesh.matrix.copy(nodeDisplayMatrix(node)); mesh.userData.sceneNodeId = node.id; mesh.userData.blenderId = node.id; mesh.userData.meshId = summary.id; mesh.userData.materialSlotIds = summary.materialSlotIds ?? []; mesh.userData.revision = snapshot.revision; mesh.userData.vertexCount = summary.vertexCount; mesh.userData.sourcePositions = positionsData ? Array.from(positionsData) : undefined; mesh.userData.sourceIndices = indicesData ? Array.from(indicesData) : undefined; mesh.userData.triangleFaceIndices = triangleFaceData ? Array.from(triangleFaceData) : undefined; mesh.userData.edgeVertexIndices = payload?.edgeVertexIndices ? Array.from(new Uint32Array(payload.edgeVertexIndices)) : summary.edgeVertexIndices; this.importedRoot.add(mesh); this.objectByBlenderId.set(node.id, mesh); } this.coalesceMeshInstances(snapshot); this.populateObjectHelpers(snapshot); this.populateCollectionInstances(snapshot); this.applyShadingMode(); void this.refreshVolumes(); } private populateNonMesh(snapshot: SceneSnapshotIR, nonMeshGeometryBuffers: readonly NonMeshGeometryChunk[]): void { const dataById = new Map((snapshot.nonMeshData ?? []).map((data) => [data.id, data])); let previewCount = 0; let blockedCount = 0; for (const node of snapshot.nodes) { if (!node.visible || !node.dataId || node.type === "MESH" || node.type === "LIGHT" || node.type === "CAMERA") continue; const data = dataById.get(node.dataId); if (!data) continue; if (data.type === "VOLUME") continue; const object = createNonMeshObject(data, nonMeshGeometryBuffers); if (!object) { blockedCount++; continue; } applyNonMeshTransform(object, node); object.traverse((child) => { child.userData.sceneNodeId = node.id; child.userData.blenderId = node.id; child.userData.nonMeshDataId = data.id; }); this.importedRoot.add(object); this.objectByBlenderId.set(node.id, object); previewCount++; } this.canvas.dataset.nonMeshCount = String(previewCount); this.canvas.dataset.nonMeshBlockedCount = String(blockedCount); } private populateGreasePencils(snapshot: SceneSnapshotIR): void { const dataById = new Map((snapshot.greasePencils ?? []).map((data) => [data.id, data])); let previewCount = 0; let blockedCount = 0; let onionStrokeCount = 0; for (const node of snapshot.nodes) { if (node.type !== "GREASE_PENCIL" || !node.visible || !node.dataId) continue; const data = dataById.get(node.dataId); if (!data) continue; const object = createGreasePencilObject(data, snapshot.frame.current); if (!object) { blockedCount++; continue; } applyGreasePencilTransform(object, node); this.importedRoot.add(object); this.objectByBlenderId.set(node.id, object); onionStrokeCount += Number(object.userData.greasePencilOnionStrokeCount ?? 0); previewCount++; } this.canvas.dataset.greasePencilCount = String(previewCount); this.canvas.dataset.greasePencilBlockedCount = String(blockedCount); this.canvas.dataset.greasePencilOnionStrokeCount = String(onionStrokeCount); } setTextureAssets(assets: readonly GPUTextureAsset[]): void { this.requestRender(); if (assets.length === 0) { this.canvas.dataset.textureStatus = "none"; this.canvas.dataset.textureLoaded = "0"; this.canvas.dataset.textureBytes = "0"; this.canvas.dataset.textureBudgetStatus = "ready"; this.canvas.dataset.textureBudgetCode = ""; this.canvas.dataset.textureBudgetAssets = "0"; this.canvas.dataset.textureBudgetPayloadBytes = "0"; this.canvas.dataset.textureBudgetGpuBytes = "0"; return; } void this.textureStore.upload(assets).then((status) => { this.canvas.dataset.textureStatus = status.rejected > 0 ? "blocked" : "ready"; this.canvas.dataset.textureLoaded = String(status.loaded); this.canvas.dataset.textureBytes = String(status.bytes); this.canvas.dataset.textureErrorCode = status.errorCodes[0] ?? ""; this.canvas.dataset.textureBudgetStatus = status.budget.status.toLowerCase(); this.canvas.dataset.textureBudgetCode = status.budget.issues[0]?.code ?? ""; this.canvas.dataset.textureBudgetAssets = String(status.budget.requestedAssets); this.canvas.dataset.textureBudgetPayloadBytes = String(status.budget.payloadBytes); this.canvas.dataset.textureBudgetGpuBytes = String(status.budget.decodedGPUBytes); if (!this.currentSnapshot) return; this.textureStore.applySnapshotMaterials(this.importedRoot, this.currentSnapshot); /* Only the paths that light from the scene world may replace the * Material Preview studio environment. */ if (this.shadingMode === "RENDERED" || (this.shadingMode === "MATERIAL" && this.solidShading.useSceneWorld)) this.applyWorldEnvironment(); }); } setVolumeAssets(assets: readonly NanoVDBViewportAssetIR[]): void { this.requestRender(); this.volumeAssets = [...assets]; void this.refreshVolumes(); } private async refreshVolumes(): Promise { try { const generation = ++this.volumeRenderGeneration; for (const child of [...this.importedRoot.children]) { if (!child.userData.nanoVDBVolume) continue; this.importedRoot.remove(child); child.traverse((object) => { const mesh = object as Mesh; mesh.geometry?.dispose?.(); const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; for (const material of materials) { if (material instanceof MeshBasicMaterial) material.map?.dispose(); material?.dispose?.(); } }); } const snapshot = this.currentSnapshot; const volumeNodes = snapshot?.nodes.filter((node) => node.visible && node.type === "VOLUME" && node.dataId) ?? []; if (!snapshot || volumeNodes.length === 0) { this.canvas.dataset.volumeStatus = "none"; this.canvas.dataset.volumeCount = "0"; return; } this.canvas.dataset.volumeStatus = "loading"; this.canvas.dataset.volumeCount = "0"; try { let rendered = 0; for (const node of volumeNodes) { const asset = this.volumeAssets.find((candidate) => candidate.dataId === node.dataId); if (!asset) continue; const cacheKey = `${asset.dataId}:${asset.manifest.bundleSha256}:${JSON.stringify(asset.material ?? asset.manifest.material)}`; let result = this.volumeRenderCache.get(cacheKey); if (!result) { result = await renderNanoVDBViewportAsset(asset, NANOVDB_VIEWPORT_PREVIEW_SIZE, NANOVDB_VIEWPORT_PREVIEW_SIZE, this.volumeRenderSession); this.volumeRenderCache.set(cacheKey, result); } if (generation !== this.volumeRenderGeneration || this.currentSnapshot !== snapshot) return; const object = createNanoVDBViewportObject(result, node); this.importedRoot.add(object); this.objectByBlenderId.set(node.id, object); rendered++; } if (generation !== this.volumeRenderGeneration) return; this.canvas.dataset.volumeCount = String(rendered); this.canvas.dataset.volumeStatus = rendered === volumeNodes.length ? "ready" : "blocked"; this.canvas.dataset.volumeErrorCode = rendered === volumeNodes.length ? "" : "NON_MESH_RESOURCE_MISSING"; } catch (error) { if (generation !== this.volumeRenderGeneration) return; this.canvas.dataset.volumeStatus = "blocked"; this.canvas.dataset.volumeErrorCode = error instanceof Error ? error.message.split(":", 1)[0] : "VOLUME_SHADER_UNAVAILABLE"; } } finally { this.requestRender(); } } applyDelta(delta: SceneDelta, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void { this.requestRender(); if (!this.currentSnapshot) throw new Error("Cannot apply a SceneDelta before a snapshot"); const next = applySceneDelta(this.currentSnapshot, delta); const hasLifecycleChanges = sceneDeltaRequiresRendererRebuild(delta); if (hasLifecycleChanges) { this.setSnapshot(next, geometryBuffers, nonMeshGeometryBuffers); return; } for (const change of delta.nodes?.updated ?? []) { const object = this.objectByBlenderId.get(change.id); if (!object) continue; const instanceIndex = this.instanceIndexByBlenderId.get(change.id); if (object instanceof InstancedMesh && instanceIndex !== undefined) { const node = next.nodes.find((candidate) => candidate.id === change.id); if (node) object.setMatrixAt(instanceIndex, nodeDisplayMatrix(node, node.visible)); object.instanceMatrix.needsUpdate = true; } else if (change.visible !== undefined) object.visible = change.visible; if (change.visible !== undefined && typeof object.userData.meshId === "string") this.lodAdapter.setEnabled(object.userData.meshId, change.visible); if ((change.transform || change.worldMatrix || change.localMatrix) && !(object instanceof InstancedMesh)) { const node=next.nodes.find(candidate=>candidate.id===change.id); if(node){object.matrixAutoUpdate=false;object.matrix.copy(nodeDisplayMatrix(node));object.matrixWorldNeedsUpdate=true;} } object.userData.revision = next.revision; } this.currentSnapshot = next; this.navigation.setSnapshot(next); } setSelection( objectIds: ReadonlySet, elementSelection?: ReadonlyMap>>, greasePencilPoints: readonly GreasePencilPointRef[] = [], greasePencilSelectionRevision = 0, ): void { this.requestRender(); this.selectedObjectIds = objectIds; this.navigation.setSelection(objectIds); const visitedInstances = new Set(); for (const [objectId, object] of this.objectByBlenderId) { if (object instanceof InstancedMesh) { if (visitedInstances.has(object)) continue; visitedInstances.add(object); const ids = object.userData.instanceNodeIds as string[]; for (let index = 0; index < ids.length; index++) { object.setColorAt(index, new Color(objectIds.has(ids[index]) ? 0xf08a45 : 0xffffff)); } if (object.instanceColor) object.instanceColor.needsUpdate = true; continue; } if (!(object instanceof Mesh)) continue; const materials = Array.isArray(object.material) ? object.material : [object.material]; for (const material of materials) { if (!(material instanceof MeshPhysicalMaterial)) continue; setPBRMaterialSelected(material, objectIds.has(objectId)); } } applyNonMeshElementSelection(this.importedRoot, elementSelection ?? new Map()); applyGreasePencilPointSelection(this.importedRoot, greasePencilPoints); this.greasePencilSelectionRevision = greasePencilSelectionRevision; this.canvas.dataset.greasePencilSelectionRevision = String(greasePencilSelectionRevision); this.canvas.dataset.greasePencilSelectionPointIds = greasePencilPoints.map((point) => point.pointId).join(","); } setInteractionMode(editMode: boolean, selectionMode: MeshElementMode): void { this.requestRender(); this.editMode = editMode; this.selectionMode = selectionMode; this.importedRoot.traverse((object) => { if (typeof object.userData.greasePencilPointDataId === "string") object.visible = editMode; }); } async samplePaintVisibility(requestValue: PaintDepthVisibilityRequestIR): Promise { try { const request = validatePaintDepthVisibilityRequest(requestValue, this.currentSnapshot?.revision ?? -1); const node = this.currentSnapshot?.nodes.find((candidate) => candidate.id === request.objectId && candidate.dataId === request.meshId && candidate.visible); const object = node ? this.objectByBlenderId.get(node.id) : undefined; if (!object) throw new Error("PAINT_DEPTH_UNAVAILABLE: Paint object is not available in the current viewport"); return samplePaintDepthVisibilityGPU({ renderer: this.renderer, scene: this.scene, camera: this.camera, object, request, backend: "MAIN_THREAD_WEBGL2", }); } finally { this.requestRender(); } } selectGreasePencilMarquee( drawing: GreasePencilDrawingScopeIR, box: GreasePencilMarqueeBoxIR, baseRevision: number, baseSelectionRevision: number, mode: "REPLACE" | "ADD" | "SUBTRACT", ): void { const result = selectGreasePencilMarquee({ schemaVersion: 1, baseRevision, baseSelectionRevision, drawing, box, candidates: greasePencilMarqueeCandidates(this.importedRoot, drawing, this.camera), }, this.currentSnapshot?.revision ?? -1); this.canvas.dataset.greasePencilMarqueeSelectionRevision = String(result.baseSelectionRevision); this.canvas.dataset.greasePencilMarqueeDrawingId = result.drawing.drawingId; this.canvas.dataset.greasePencilMarqueePointIds = result.selectedPoints.map((point) => point.pointId).join(","); this.canvas.dataset.greasePencilMarqueeStrokeIds = result.selectedStrokeIds.join(","); this.canvas.dataset.greasePencilMarqueeCount = String(result.selectedPoints.length); this.onGreasePencilMarqueeSelect?.(result, mode); } setCurveHandlePreview(dataId: string, handles: readonly CurveGizmoHandleIR[] | null): void { this.requestRender(); applyCurveHandlePreview(this.importedRoot, dataId, handles); this.canvas.dataset.curveGizmoPreview = handles ? String(handles.length) : "0"; } setGreasePencilPointPreview(dataId: string, layerId: string, frame: number, points: readonly GreasePencilPointPreview[] | null): void { this.requestRender(); applyGreasePencilPointPreview(this.importedRoot, dataId, layerId, frame, points); this.canvas.dataset.greasePencilPreview = points ? String(points.length) : "0"; } setCurveGizmoFrame(dataId: string | null, frame: CurveGizmoFrameIR | null): void { this.requestRender(); this.curveGizmoFrame = dataId && frame ? { dataId, frame } : null; this.publishCurveGizmoFrame(); } /** Object-mode box select: project each object origin into the viewport rect. */ objectsInScreenRect(rect: { x0: number; y0: number; x1: number; y1: number }): string[] { const width = Math.max(1, this.canvas.clientWidth); const height = Math.max(1, this.canvas.clientHeight); const point = new Vector3(); const ids: string[] = []; for (const [id, object] of this.objectByBlenderId) { if (!object.visible) continue; object.getWorldPosition(point); point.project(this.camera); if (!Number.isFinite(point.x) || !Number.isFinite(point.y) || point.z < -1 || point.z > 1) continue; const x = (point.x + 1) / 2 * width; const y = (1 - point.y) / 2 * height; if (x >= rect.x0 && x <= rect.x1 && y >= rect.y0 && y <= rect.y1) ids.push(id); } return ids; } async boxSelect(rect: { x0: number; y0: number; x1: number; y1: number }): Promise { return this.objectsInScreenRect(rect); } async meshBoxSelect(rect: { x0: number; y0: number; x1: number; y1: number }): Promise<{ meshId: string; mode: MeshElementMode; indices: number[] }> { const nodeId = this.currentSnapshot?.activeObjectId; const object = nodeId ? this.objectByBlenderId.get(nodeId) : undefined; const meshId = object?.userData.meshId; const positions = object?.userData.sourcePositions as number[] | undefined; const sourceIndices = object?.userData.sourceIndices as number[] | undefined; const triangleFaces = object?.userData.triangleFaceIndices as number[] | undefined; if (!object || typeof meshId !== "string" || !positions || !sourceIndices || positions.length % 3 !== 0) { throw new Error("MESH_BOX_SELECT_UNAVAILABLE"); } const width = Math.max(1, this.canvas.clientWidth); const height = Math.max(1, this.canvas.clientHeight); const vertexCount = Math.floor(positions.length / 3); object.updateMatrixWorld(true); const point = new Vector3(); const inside = new Uint8Array(vertexCount); for (let index = 0; index < vertexCount; index++) { point.set(positions[index * 3], positions[index * 3 + 2], -positions[index * 3 + 1]).applyMatrix4(object.matrixWorld).project(this.camera); if (!Number.isFinite(point.x) || !Number.isFinite(point.y) || point.z < -1 || point.z > 1) continue; const x = (point.x + 1) / 2 * width; const y = (1 - point.y) / 2 * height; if (x >= rect.x0 && x <= rect.x1 && y >= rect.y0 && y <= rect.y1) inside[index] = 1; } const indices = new Set(); if (this.selectionMode === "VERT") { for (let index = 0; index < vertexCount; index++) if (inside[index]) indices.add(index); } else if (this.selectionMode === "FACE") { for (let triangle = 0; triangle + 2 < sourceIndices.length; triangle += 3) { if (!inside[sourceIndices[triangle]] || !inside[sourceIndices[triangle + 1]] || !inside[sourceIndices[triangle + 2]]) continue; indices.add(triangleFaces?.[triangle / 3] ?? triangle / 3); } } else if (this.selectionMode === "EDGE") { const edgeVertices = object.userData.edgeVertexIndices as number[] | undefined; if (edgeVertices) for (let edge = 0; edge * 2 + 1 < edgeVertices.length; edge++) { if (inside[edgeVertices[edge * 2]] && inside[edgeVertices[edge * 2 + 1]]) indices.add(edge); } } return { meshId, mode: this.selectionMode, indices: [...indices].sort((left, right) => left - right) }; } registerLOD(meshId: string, levels: readonly ThreeLODLevel[], radius: number): void { this.requestRender(); this.lodAdapter.register(meshId, levels, radius); } unregisterLOD(meshId: string): void { this.requestRender(); this.lodAdapter.unregister(meshId); } installLODLevels(meshId: string, levels: readonly WebEngineLODLevelResult[]): void { const source = [...this.objectByBlenderId.values()].find((object) => object.userData.meshId === meshId); if (!(source instanceof Mesh) || source instanceof InstancedMesh || levels.length === 0) return; const created: ThreeLODLevel[] = []; const sourceMaterials = Array.isArray(source.material) ? source.material : [source.material]; source.geometry.computeBoundingSphere(); const radius = source.geometry.boundingSphere?.radius ?? 1; for (const level of levels) { const payload = level.geometryBuffers.find((geometry) => geometry.meshId === level.meshId) ?? level.geometryBuffers[0]; if (!payload) continue; const mesh = new Mesh(this.createLODGeometry(payload, sourceMaterials.length), sourceMaterials); mesh.castShadow = true; mesh.receiveShadow = true; mesh.name = `${source.name} LOD ${level.level}`; mesh.matrixAutoUpdate=false;mesh.matrix.copy(source.matrix); mesh.userData.sceneNodeId = source.userData.sceneNodeId; mesh.userData.blenderId = source.userData.blenderId; mesh.userData.meshId = meshId; this.importedRoot.add(mesh); created.push({ object: mesh, screenHeightThreshold: Math.max(24, 768 / 2 ** level.level) }); } if (created.length === 0) return; source.visible = false; this.lodAdapter.register(meshId, created, radius); } updateLODSelection(hysteresis = 0.08): Map { return this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight), hysteresis); } private createLODGeometry(payload: MeshGeometryBuffer, materialCount: number): BufferGeometry { const positionsData = new Float32Array(payload.positions); const indicesData = new Uint32Array(payload.indices); const normalsData = payload.normals ? new Float32Array(payload.normals) : undefined; const cornerData = payload.triangleCornerIndices ? new Uint32Array(payload.triangleCornerIndices) : undefined; const uvData = payload.uvs ? new Float32Array(payload.uvs) : undefined; const colorData = payload.colors ? new Float32Array(payload.colors) : undefined; const materialData = payload.triangleMaterialIndices ? new Uint32Array(payload.triangleMaterialIndices) : undefined; const geometry = new BufferGeometry(); if (cornerData && (uvData || colorData)) { const positions: number[] = []; const normals: number[] = []; const uvs: number[] = []; const colors: number[] = []; for (let index = 0; index < indicesData.length; index++) { const vertex = indicesData[index] * 3; positions.push(positionsData[vertex], positionsData[vertex + 2], -positionsData[vertex + 1]); if (normalsData) normals.push(normalsData[vertex], normalsData[vertex + 2], -normalsData[vertex + 1]); const corner = cornerData[index]; if (uvData) uvs.push(uvData[corner * 2], uvData[corner * 2 + 1]); if (colorData) colors.push(colorData[corner * 4], colorData[corner * 4 + 1], colorData[corner * 4 + 2], colorData[corner * 4 + 3]); } geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); if (normals.length > 0) geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); if (uvs.length > 0) geometry.setAttribute("uv", new Float32BufferAttribute(uvs, 2)); if (colors.length > 0) geometry.setAttribute("color", new Float32BufferAttribute(colors, 4)); } else { const positions = new Array(positionsData.length); for (let index = 0; index < positionsData.length; index += 3) { positions[index] = positionsData[index]; positions[index + 1] = positionsData[index + 2]; positions[index + 2] = -positionsData[index + 1]; } geometry.setAttribute("position", new Float32BufferAttribute(positions, 3)); if (normalsData) { const normals = new Array(normalsData.length); for (let index = 0; index < normalsData.length; index += 3) { normals[index] = normalsData[index]; normals[index + 1] = normalsData[index + 2]; normals[index + 2] = -normalsData[index + 1]; } geometry.setAttribute("normal", new Float32BufferAttribute(normals, 3)); } geometry.setIndex(new Uint32BufferAttribute(indicesData, 1)); if (!normalsData) geometry.computeVertexNormals(); } if (materialData && materialCount > 1) { for (let triangle = 0; triangle < materialData.length; triangle++) geometry.addGroup(triangle * 3, 3, Math.min(materialData[triangle], materialCount - 1)); } return geometry; } private coalesceMeshInstances(snapshot: SceneSnapshotIR): void { const instanceGroups = collectMeshInstanceGroups(snapshot); for (const [meshId, nodeIds] of instanceGroups) { const meshes = nodeIds.map((id) => this.objectByBlenderId.get(id)).filter((object): object is Mesh => object instanceof Mesh && !(object instanceof InstancedMesh)); if (meshes.length !== nodeIds.length || meshes.length < 2) continue; const first = meshes[0]; const instances = new InstancedMesh(first.geometry, first.material, meshes.length); instances.castShadow = true; instances.receiveShadow = true; instances.name = `${first.name} (${meshes.length} instances)`; instances.frustumCulled = true; instances.userData = { ...first.userData, blenderId: undefined, instanceNodeIds: [...nodeIds], meshId }; for (let index = 0; index < nodeIds.length; index++) { const node = snapshot.nodes.find((candidate) => candidate.id === nodeIds[index]); if (!node) continue; instances.setMatrixAt(index, nodeDisplayMatrix(node, node.visible)); instances.setColorAt(index, new Color(0xffffff)); this.objectByBlenderId.set(node.id, instances); this.instanceIndexByBlenderId.set(node.id, index); } instances.instanceMatrix.needsUpdate = true; if (instances.instanceColor) instances.instanceColor.needsUpdate = true; for (let index = 0; index < meshes.length; index++) { const mesh = meshes[index]; this.importedRoot.remove(mesh); if (index === 0) continue; mesh.geometry.dispose(); const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; for (const material of materials) material.dispose(); } this.importedRoot.add(instances); } this.canvas.dataset.instanceGroups = String(instanceGroups.size); } /** Desktop editor display for cameras (frustum) and empties (axes). These * helpers also participate in collection-instance expansion. */ private populateObjectHelpers(snapshot: SceneSnapshotIR): void { const cameras = new Map(snapshot.cameras.map((camera) => [camera.id, camera])); const cameraMaterial = new LineBasicMaterial({ color: 0x9aa4b2 }); const emptyMaterial = new LineBasicMaterial({ color: 0xd9a441 }); let count = 0; for (const node of snapshot.nodes) { if (!node.visible || node.instanceCollectionId) continue; if (node.type === "CAMERA" && node.dataId) { const camera = cameras.get(node.dataId); if (!camera) continue; const aspect = camera.sensorWidthMm > 0 ? camera.sensorHeightMm / camera.sensorWidthMm : 1; const depth = 0.5; const halfWidth = camera.projection === "ORTHOGRAPHIC" ? camera.orthoScale / 2 : camera.lensMm > 0 ? depth * camera.sensorWidthMm / (2 * camera.lensMm) : depth * 0.5; const halfHeight = halfWidth * aspect; const corners = [[-halfWidth, -halfHeight], [halfWidth, -halfHeight], [halfWidth, halfHeight], [-halfWidth, halfHeight]]; const points: number[] = []; for (const [x, y] of corners) points.push(0, 0, 0, x, -depth, -y); for (let index = 0; index < 4; index++) { const [x1, y1] = corners[index]; const [x2, y2] = corners[(index + 1) % 4]; points.push(x1, -depth, -y1, x2, -depth, -y2); } const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute(points, 3)); const helper = new LineSegments(geometry, cameraMaterial); helper.matrixAutoUpdate = false; helper.matrix.copy(nodeDisplayMatrix(node)); helper.traverse((child) => { child.userData.sceneNodeId = node.id; child.userData.blenderId = node.id; child.userData.renderHelper = "CAMERA"; }); this.importedRoot.add(helper); this.objectByBlenderId.set(node.id, helper); count++; } else if (node.type === "EMPTY") { const size = 0.25; const geometry = new BufferGeometry(); geometry.setAttribute("position", new Float32BufferAttribute([-size, 0, 0, size, 0, 0, 0, -size, 0, 0, size, 0, 0, 0, -size, 0, 0, size], 3)); const helper = new LineSegments(geometry, emptyMaterial); helper.matrixAutoUpdate = false; helper.matrix.copy(nodeDisplayMatrix(node)); helper.traverse((child) => { child.userData.sceneNodeId = node.id; child.userData.blenderId = node.id; child.userData.renderHelper = "EMPTY"; }); this.importedRoot.add(helper); this.objectByBlenderId.set(node.id, helper); count++; } } this.canvas.dataset.renderHelpers = String(count); } /** Expand collection-instance empties into display copies of their members. * Geometry/material stays shared with the member render objects; picking * reports the instance owner, matching desktop selection semantics. */ private populateCollectionInstances(snapshot: SceneSnapshotIR): void { const collections = new Map(snapshot.collections.map((collection) => [collection.id, collection])); const nodes = new Map(snapshot.nodes.map((node) => [node.id, node])); let rendered = 0; const membersOf = (collectionId: string): string[] => { const memberIds = new Set(); const visited = new Set(); const collect = (id: string, depth: number) => { if (depth > 8 || visited.has(id)) return; visited.add(id); const collection = collections.get(id); if (!collection || collection.viewportVisible === false) return; for (const objectId of collection.objectIds) memberIds.add(objectId); for (const childId of collection.childCollectionIds) collect(childId, depth + 1); }; collect(collectionId, 0); return [...memberIds]; }; const renderOwner = (owner: SceneNodeIR, parentMatrix: Matrix4, depth: number, stack: Set): void => { if (depth > 4 || stack.has(owner.id) || !owner.instanceCollectionId) return; const nextStack = new Set(stack); nextStack.add(owner.id); const ownerMatrix = new Matrix4().multiplyMatrices(parentMatrix, nodeDisplayMatrix(owner)); for (const memberId of membersOf(owner.instanceCollectionId)) { if (memberId === owner.id) continue; const member = nodes.get(memberId); if (!member?.visible) continue; if (member.instanceCollectionId) { renderOwner(member, ownerMatrix, depth + 1, nextStack); continue; } const source = this.objectByBlenderId.get(memberId); if (!source) continue; let clone: Object3D | null = null; if (source instanceof InstancedMesh) { const index = this.instanceIndexByBlenderId.get(memberId); if (index === undefined) continue; const mesh = new Mesh(source.geometry, source.material); const memberMatrix = new Matrix4(); source.getMatrixAt(index, memberMatrix); mesh.matrixAutoUpdate = false; mesh.matrix.copy(ownerMatrix).multiply(memberMatrix); clone = mesh; } else { clone = source.clone(true); clone.matrixAutoUpdate = false; clone.matrix.premultiply(ownerMatrix); } clone.castShadow = true; clone.receiveShadow = true; clone.traverse((child) => { child.userData.sceneNodeId = owner.id; child.userData.blenderId = owner.id; child.userData.instanceMemberId = memberId; }); this.importedRoot.add(clone); rendered++; } }; for (const owner of snapshot.nodes) { if (!owner.visible || !owner.instanceCollectionId) continue; renderOwner(owner, new Matrix4(), 0, new Set()); } this.canvas.dataset.collectionInstanceObjects = String(rendered); } private clearImportedScene(): void { while (this.importedRoot.children.length > 0) { const child = this.importedRoot.children.pop(); if (!child) continue; child.traverse((object) => { const mesh = object as Mesh; if (mesh.geometry && typeof mesh.geometry.dispose === "function") mesh.geometry.dispose(); const materials = Array.isArray(mesh.material) ? mesh.material : [mesh.material]; for (const material of materials) { if (mesh.userData.nanoVDBVolume && material instanceof MeshBasicMaterial) material.map?.dispose(); if (material && typeof material.dispose === "function") material.dispose(); } }); } while (this.importedLights.children.length > 0) { const child = this.importedLights.children.pop(); if (child && "dispose" in child && typeof child.dispose === "function") child.dispose(); } } private createMaterial(definition: MaterialIR | undefined, active: boolean): MeshPhysicalMaterial { return createPBRMaterial(definition, active); } /* SOLID/WIREFRAME swap in the ported workbench studio material; MATERIAL and * RENDERED restore the authored PBR material. Shared with the worker so the * two render paths stay identical. */ private applyShadingMode(): void { applyStudioShading(this.importedRoot, this.shadingMode, this.xray, this.selectedObjectIds, this.solidShading); /* A studio-lit clay must not also receive the world HDRI, and the scene * lights only belong to the PBR path. */ const studio = usesStudioMaterial(this.shadingMode); if (studio) { this.savedEnvironment = this.scene.environment; this.scene.environment = null; this.importedLights.visible = false; } else { if (this.savedEnvironment !== undefined) { this.scene.environment = this.savedEnvironment; this.savedEnvironment = undefined; } this.importedLights.visible = true; /* Material Preview uses the built-in studio light unless the user turns * on Scene World (`View3DShading.use_scene_world`); Rendered always * lights from the scene world. */ if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) this.ensurePreviewEnvironment(); else this.applyWorldEnvironment(); } this.canvas.dataset.studioLighting = studio ? "studio-mvp" : "pbr"; } /* Material Preview equivalent of the desktop studio light. Desktop lights it * from the default studiolight world (blenkernel/intern/studiolight.cc: * STUDIOLIGHT_WORLD_DEFAULT, forest.exr); tools/web/import-studiolight-world.py * ships those exact float pixels. The bounded gradient is the immediate * fallback until that asset arrives, and stays if it cannot load. */ private ensurePreviewEnvironment(): void { if (!this.previewEnvironment) { if (!this.previewFallbackEnvironment) { const width = 64, height = 32, data = new Uint8Array(width * height * 4); for (let y = 0; y < height; y++) { const v = y / (height - 1); const sky = 25 + Math.round(205 * (1 - v) ** 1.6); for (let x = 0; x < width; x++) { const u = x / width; const lobe = 120 * Math.exp(-(((u - 0.25) * 7) ** 2) - (((v - 0.22) * 7) ** 2)) + 90 * Math.exp(-(((u - 0.75) * 7) ** 2) - (((v - 0.3) * 7) ** 2)); const index = (y * width + x) * 4; data[index] = Math.min(255, sky + lobe); data[index + 1] = Math.min(255, sky + lobe); data[index + 2] = Math.min(255, Math.round(sky * 1.05) + lobe); data[index + 3] = 255; } } const equirect = new DataTexture(data, width, height); equirect.mapping = EquirectangularReflectionMapping; equirect.colorSpace = SRGBColorSpace; equirect.needsUpdate = true; const pmrem = new PMREMGenerator(this.renderer); this.previewFallbackEnvironment = pmrem.fromEquirectangular(equirect).texture; equirect.dispose(); pmrem.dispose(); } this.scene.environment = this.previewFallbackEnvironment; this.canvas.dataset.previewEnvironment = "studio-fallback"; this.previewEnvironmentRequest ??= this.loadStudioEnvironment().catch(() => undefined); } else { this.scene.environment = this.previewEnvironment; this.canvas.dataset.previewEnvironment = "studio-exr"; } if (!this.scene.environmentIntensity) this.scene.environmentIntensity = 1; } /* Load the selected desktop studiolight world pixels (`WBENV1` header + RGB * float32) and prefilter them once. The raw pixel block hash doubles as the * pixel-identity check against tools/web/import-studiolight-world.py. */ private async loadStudioEnvironment(): Promise { const requested = this.previewStudioLight; const world = await fetchStudioWorld(requested).catch(() => null); /* A newer selection may have superseded this load while it was fetching. */ if (!world || requested !== this.previewStudioLight) return; this.previewEnvironment = createStudioWorldTexture(this.renderer, world); if (typeof window !== "undefined") { (window as unknown as { __webStudioEnvironment?: unknown }).__webStudioEnvironment = await studioWorldReport(world); } if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) { this.scene.environment = this.previewEnvironment; this.canvas.dataset.previewEnvironment = "studio-exr"; this.requestRender(); } } /* Desktop Viewport Shading > Studio Light: switch the Material Preview world * (`studiolights/world/*.exr`). The fallback gradient shows until the new * dataset arrives. */ setPreviewStudioLight(name: string): void { if (!isStudioWorldLight(name) || name === this.previewStudioLight) return; this.previewStudioLight = name; this.previewEnvironment?.dispose(); this.previewEnvironment = null; this.previewEnvironmentRequest = null; this.canvas.dataset.studioLight = name; if (this.shadingMode === "MATERIAL" && !this.solidShading.useSceneWorld) this.ensurePreviewEnvironment(); this.requestRender(); } /* Scene World lighting: the World colour or environment image with its * strength and rotation, shared with the offscreen render paths. */ private applyWorldEnvironment(): void { const snapshot = this.currentSnapshot; const worldId = snapshot?.scenes[0]?.worldId; const world = snapshot?.worlds.find((candidate) => candidate.id === worldId) ?? snapshot?.worlds[0]; if (!world) return; /* Material Preview with Scene World shows the world background too, like * the desktop studiolight-or-world background in the viewport. */ void this.textureStore.applyEnvironment(this.scene, this.renderer, world, true).then((ready) => { this.canvas.dataset.previewEnvironment = ready ? "world" : "none"; this.canvas.dataset.iblStatus = ready ? (world.environmentImageId ? "ready" : "color") : "blocked"; }); } private applyWorld(snapshot: SceneSnapshotIR): void { const sceneDefinition = snapshot.scenes.find((scene) => scene.id === snapshot.sceneId) ?? snapshot.scenes[0]; const worldId = snapshot.scenes[0]?.worldId; const world = snapshot.worlds.find((candidate) => candidate.id === worldId) ?? snapshot.worlds[0]; /* Desktop Background = colour x Strength; the strength scales the visible * world colour as well as its lighting contribution. */ this.scene.background = world ? new Color().setRGB(...world.color).multiplyScalar(Math.max(0, world.environmentStrength ?? 1)) : new Color("#25272b"); if (this.shadingMode === "RENDERED" || (this.shadingMode === "MATERIAL" && this.solidShading.useSceneWorld)) this.applyWorldEnvironment(); const colorManagement = sceneDefinition?.colorManagement; this.canvas.dataset.toneMapping = configurePBRRenderer(this.renderer, { viewTransform: colorManagement?.viewTransform, exposure: colorManagement?.exposure ?? world?.exposure ?? 0, look: colorManagement?.look, }); this.canvas.dataset.viewTransform = colorManagement?.viewTransform ?? ""; this.canvas.dataset.viewLook = colorManagement?.look ?? ""; this.canvas.dataset.mist = world?.mist?.enabled ? "metadata-only" : "disabled"; } private applyCamera(snapshot: SceneSnapshotIR): void { const cameraObjectId = snapshot.scenes[0]?.cameraObjectId; const cameraNode = snapshot.nodes.find((node) => node.id === cameraObjectId && node.type === "CAMERA"); const definition = snapshot.cameras.find((camera) => camera.id === cameraNode?.dataId); if (!cameraNode || !definition) return; if(this.camera instanceof PerspectiveCamera)configurePBRCamera(this.camera, definition); } private publishLightingBudget(report: PBRLightingBudgetReport): void { this.canvas.dataset.renderBudgetBackend = report.backend; this.canvas.dataset.renderBudgetStatus = report.status.toLowerCase(); this.canvas.dataset.renderBudgetCode = report.issues[0]?.code ?? ""; this.canvas.dataset.renderBudgetLights = String(report.requestedLights); this.canvas.dataset.renderBudgetRenderedLights = String(report.renderedLightNodeIds.length); this.canvas.dataset.renderBudgetDroppedLights = String(report.droppedLightNodeIds.length); this.canvas.dataset.renderBudgetShadows = String(report.requestedShadowMaps); this.canvas.dataset.renderBudgetRenderedShadows = String(report.shadowLightNodeIds.length); this.canvas.dataset.renderBudgetBlockedShadows = String(report.shadowBlockedLightNodeIds.length); this.canvas.dataset.renderBudgetShadowMapDimension = String(report.budget.shadowMapDimension); } private populateLights(snapshot: SceneSnapshotIR, budget = planPBRLightingBudget(snapshot, "THREE_WEBGL2")): void { const lights = new Map(snapshot.lights.map((light) => [light.id, light])); const rendered = new Set(budget.renderedLightNodeIds); const shadowed = new Set(budget.shadowLightNodeIds); for (const node of snapshot.nodes) { if (node.type !== "LIGHT" || !node.visible || !node.dataId || !rendered.has(node.id)) continue; const definition = lights.get(node.dataId); if (!definition) continue; const light = createPBRLight(definition); configurePBRLight(light, node, this.importedLights, { shadowEnabled: shadowed.has(node.id), shadowMapDimension: budget.budget.shadowMapDimension, }); light.name = node.name; light.userData.sceneNodeId = node.id; light.userData.blenderId = node.id; light.userData.revision = snapshot.revision; this.importedLights.add(light); this.objectByBlenderId.set(node.id, light); } } private resize(): void { this.requestRender(); const width = Math.max(1, this.canvas.clientWidth); const height = Math.max(1, this.canvas.clientHeight); const metrics = resolveViewportPixelMetrics(width, height, window.devicePixelRatio); this.navigation.resize(); this.renderer.setSize(width, height, false); this.canvas.dataset.viewportCssSize = `${metrics.cssWidth}x${metrics.cssHeight}`; this.canvas.dataset.viewportBackingSize = `${metrics.backingWidth}x${metrics.backingHeight}`; this.canvas.dataset.viewportPixelRatio = String(metrics.pixelRatio); this.publishCameraState(); } private publishCameraState(): void { this.navigation.publish(); } private handleClick = (event: MouseEvent): void => { if(event.button!==0)return; if ("pointerType" in event) { try { this.canvas.dataset.lastPointer = JSON.stringify(observePointerEvent(event as MouseEvent & { pointerType?: string; pointerId?: number; pressure?: number; tiltX?: number; tiltY?: number; buttons?: number; type?: string })); } catch { this.canvas.dataset.lastPointer = "BLOCKED"; } const pointerType = (event as MouseEvent & { pointerType?: string }).pointerType; if ((pointerType === "touch" || pointerType === "pen") && this.inputModal.cancelled) return; } const bounds = this.canvas.getBoundingClientRect(); if (bounds.width <= 0 || bounds.height <= 0) return; const ndc = viewportNDC(event.clientX, event.clientY, bounds); this.pointer.set(ndc.x, ndc.y); this.raycaster.setFromCamera(this.pointer, this.camera); const hits = this.raycaster.intersectObjects(this.importedRoot.children, true); const greasePencilHit = this.editMode ? hits.find((intersection) => intersection.index !== undefined && greasePencilPointRef(intersection.object, intersection.index) !== null) : undefined; if (greasePencilHit?.index !== undefined) { const point = greasePencilPointRef(greasePencilHit.object, greasePencilHit.index); if (point) this.onGreasePencilPointSelect?.(point, event.ctrlKey || event.metaKey ? "SUBTRACT" : event.shiftKey ? "ADD" : "REPLACE", this.greasePencilSelectionRevision); return; } const preferredNonMeshHit = this.editMode ? hits.find((intersection) => intersection.index !== undefined && Array.isArray(intersection.object.userData.nonMeshPointKindMap)) : undefined; const hit = preferredNonMeshHit ?? hits.find((intersection) => typeof intersection.object.userData.blenderId === "string" || Array.isArray(intersection.object.userData.instanceNodeIds)); if (!hit) return; const additive = event.shiftKey || event.ctrlKey || event.metaKey; const nonMeshDataId = hit.object.userData.nonMeshDataId; if (typeof nonMeshDataId === "string" && hit.index !== undefined) { const indexMap = hit.object.userData.nonMeshPointIndexMap as number[] | undefined; const pointIndex = indexMap?.[hit.index] ?? Math.max(0, Math.floor(hit.object.userData.nonMeshPointOffset ?? 0) + hit.index); const kindMap = hit.object.userData.nonMeshPointKindMap as NonMeshElementKind[] | undefined; const kind = kindMap?.[hit.index] ?? "CONTROL_POINT"; this.canvas.dataset.nonMeshLastPick = `${nonMeshDataId}:${kind}:${pointIndex}`; this.onElementSelect?.(nonMeshDataId, "VERT", pointIndex, additive, kind); return; } const meshId = hit.object.userData.meshId; const triangle = hit.faceIndex ?? -1; const sourceIndices = hit.object.userData.sourceIndices as number[] | undefined; if (this.editMode && typeof meshId === "string" && triangle >= 0 && sourceIndices) { const triangleVertices = sourceIndices.slice(triangle * 3, triangle * 3 + 3); let selectedIndex = -1; if (this.selectionMode === "FACE") { const triangleFaces = hit.object.userData.triangleFaceIndices as number[] | undefined; selectedIndex = triangleFaces?.[triangle] ?? triangle; } else if (this.selectionMode === "VERT") { const positions = hit.object.userData.sourcePositions as number[] | undefined; if (positions) { const localHit = hit.object.worldToLocal(hit.point.clone()); const local = [localHit.x, -localHit.z, localHit.y]; selectedIndex = triangleVertices.reduce((best, vertex) => { if (best < 0) return vertex; const distance = (positions[vertex * 3] - local[0]) ** 2 + (positions[vertex * 3 + 1] - local[1]) ** 2 + (positions[vertex * 3 + 2] - local[2]) ** 2; const bestDistance = (positions[best * 3] - local[0]) ** 2 + (positions[best * 3 + 1] - local[1]) ** 2 + (positions[best * 3 + 2] - local[2]) ** 2; return distance < bestDistance ? vertex : best; }, -1); } } else { const edges = hit.object.userData.edgeVertexIndices as number[] | undefined; if (edges) { const candidates = [[triangleVertices[0], triangleVertices[1]], [triangleVertices[1], triangleVertices[2]], [triangleVertices[2], triangleVertices[0]]]; selectedIndex = candidates.reduce((found, pair) => { if (found >= 0) return found; const low = Math.min(pair[0], pair[1]); const high = Math.max(pair[0], pair[1]); for (let edge = 0; edge < edges.length / 2; edge++) { if (Math.min(edges[edge * 2], edges[edge * 2 + 1]) === low && Math.max(edges[edge * 2], edges[edge * 2 + 1]) === high) return edge; } return -1; }, -1); } } if (selectedIndex >= 0) this.onElementSelect?.(meshId, this.selectionMode, selectedIndex, additive); return; } const instanceIds = hit.object.userData.instanceNodeIds as string[] | undefined; const objectId = instanceIds && hit.instanceId !== undefined ? instanceIds[hit.instanceId] : hit.object.userData.blenderId; if (typeof objectId === "string") this.onSelect?.(objectId, additive); }; private handlePointerObservation = (event: PointerEvent): void => { try { const observation = observePointerEvent(event); this.canvas.dataset.lastPointer = JSON.stringify(observation); if (observation.pointerType === "touch" || observation.pointerType === "pen") { this.inputModal = reduceInputModal(this.inputModal, { type: event.type as "pointerdown" | "pointerup" | "pointercancel", pointerType: observation.pointerType, pointerId: observation.pointerId, }); this.publishInputModal(); } } catch { this.canvas.dataset.lastPointer = "BLOCKED"; this.canvas.dataset.inputModalError = "INPUT_MODAL_EVENT_BLOCKED"; } }; private publishInputModal(): void { this.canvas.dataset.inputModalSchemaVersion = String(this.inputModal.schemaVersion); this.canvas.dataset.inputModalKind = this.inputModal.kind; this.canvas.dataset.inputModalActivePointerIds = this.inputModal.activePointerIds.join(","); this.canvas.dataset.inputModalCancelled = this.inputModal.cancelled ? "1" : "0"; this.canvas.dataset.inputModalNavigationRevision = String(this.inputModal.navigationRevision); this.canvas.dataset.inputModalMainCommitCount = String(this.inputModal.mainCommitCount); this.canvas.dataset.inputModalError = ""; } private renderLoop = (): void => { if (this.disposed) return; if (!this.contextLost) { this.controls.update(); if (this.renderRequested) { this.renderRequested = false; this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight)); /* Cavity/curvature read back the frame they just shaded, so they run as * a post pass; when disabled `render` returns without drawing. */ const cavity = this.solidShading.cavity; /* Cavity belongs to solid shading only. It also has to stay there: the * studio shaders write `gl_FragColor` directly, whereas the PBR * materials rely on the renderer's tonemap/encode, which three skips * when drawing into a render target. Running the pass in MATERIAL or * RENDERED would therefore wash those modes out. The WORLD bake needs a * per-object ray evaluation the web path lacks, so a WORLD request runs * the screen-space estimator instead of nothing. */ const solid = usesStudioMaterial(this.shadingMode); this.workbenchPost.setOptions({ ...cavity, enabled: solid && Boolean(cavity?.enabled) }); const posted = this.workbenchPost.render(this.renderer, this.scene, this.camera); if (!posted) this.renderer.render(this.scene, this.camera); /* Camera-view parity probes read the exact view used for this frame. */ if (typeof window !== "undefined") { this.camera.updateMatrixWorld(); const perspective = this.camera as PerspectiveCamera; (window as unknown as { __webViewportCamera?: unknown }).__webViewportCamera = { matrixWorld: Array.from(this.camera.matrixWorld.elements), fov: perspective.fov ?? 0, zoom: perspective.zoom ?? 1, aspect: perspective.aspect ?? (this.canvas.width / Math.max(1, this.canvas.height)), width: this.canvas.width, height: this.canvas.height, }; } this.publishCurveGizmoFrame(); if (this.canvas.dataset.deviceStatus === "restoring") { this.canvas.dataset.deviceStatus = "ready"; this.canvas.dispatchEvent(new CustomEvent("viewport-device-restored")); } } } this.animationFrame = window.requestAnimationFrame(this.renderLoop); }; private handleContextLost = (event: Event): void => { event.preventDefault(); this.contextLost = true; this.canvas.dataset.deviceStatus = "lost"; }; private handleContextRestored = (): void => { this.contextLost = false; this.canvas.dataset.deviceStatus = "restoring"; configurePBRRenderer(this.renderer); this.renderer.setPixelRatio(resolveViewportPixelMetrics(1, 1, window.devicePixelRatio).pixelRatio); this.renderer.setClearColor(new Color("#25272b")); this.resize(); this.volumeRenderCache.clear(); void this.refreshVolumes(); }; private publishCurveGizmoFrame(): void { const active = this.curveGizmoFrame; let frame: CurveGizmoScreenFrameIR | null = null; const node = active ? this.currentSnapshot?.nodes.find((candidate) => candidate.dataId === active.dataId && candidate.id === this.currentSnapshot?.activeObjectId) : undefined; const object = node ? this.objectByBlenderId.get(node.id) : undefined; if (active && object) { object.updateWorldMatrix(true, false); this.camera.updateMatrixWorld(true); const project = (value: readonly number[]): Vector3 => new Vector3(value[0], value[2], -value[1]).applyMatrix4(object.matrixWorld).project(this.camera); const origin = project(active.frame.origin); const axes = active.frame.axes.map((axis) => { const endpoint = project([active.frame.origin[0] + axis[0], active.frame.origin[1] + axis[1], active.frame.origin[2] + axis[2]]); const x = endpoint.x - origin.x; const y = origin.y - endpoint.y; const magnitude = Math.hypot(x, y); return magnitude > 1e-8 ? [x / magnitude, y / magnitude] as [number, number] : [0, 0] as [number, number]; }) as CurveGizmoScreenFrameIR["axes"]; frame = { origin: [(origin.x + 1) / 2, (1 - origin.y) / 2], axes }; } const serialized = JSON.stringify(frame); if (serialized === this.curveGizmoScreenFrame) return; this.curveGizmoScreenFrame = serialized; this.canvas.dispatchEvent(new CustomEvent("curve-gizmo-frame", { detail: frame })); } dispose(): void { this.controls.removeEventListener("change", this.requestRender); this.canvas.removeEventListener("webglcontextrestored", this.requestRender); this.disposed = true; window.cancelAnimationFrame(this.animationFrame); this.resizeObserver.disconnect(); this.canvas.removeEventListener("click", this.handleClick); this.canvas.removeEventListener("pointerdown", this.handlePointerObservation); this.canvas.removeEventListener("pointerup", this.handlePointerObservation); this.canvas.removeEventListener("pointercancel", this.handlePointerObservation); this.canvas.removeEventListener("webglcontextlost", this.handleContextLost); this.canvas.removeEventListener("webglcontextrestored", this.handleContextRestored); this.navigation.dispose(); this.lodAdapter.clear(); this.clearImportedScene(); this.volumeRenderGeneration++; this.volumeRenderCache.clear(); this.volumeRenderSession.dispose(); this.workbenchPost.dispose(); this.textureStore.dispose(); this.renderer.dispose(); } }