feat(web): studio worlds, camera-view/offscreen environment parity, material and undo coverage
Environment lighting: - ship all eight desktop studiolights/world datasets (WBENV1 float32) and a shared loader used by both the main viewport and the offscreen worker - add the N-panel "studio 环境" selector - rotate the world background together with the environment (backgroundRotation/backgroundIntensity), so camera view and offscreen renders match the desktop Mapping-node behaviour Verification (Chromium, OPFS, NOT_CLAIMED): - environment lighting + 8 world pixel identity - camera-view rotation correspondence (camera matrices, 207 samples) - offscreen vs on-screen background parity after hiding geometry (1305 samples) - metals case extended with material-field OPFS roundtrip - material Principled edits and rename undo/redo - eight studio worlds: pairwise frame differences + luminance rank correlation - undo history depth capped at 64 steps and undo across OPFS save/reopen Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
97
web/app/src/three-adapter/matcap-assets.ts
Normal file
97
web/app/src/three-adapter/matcap-assets.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { DataTexture, HalfFloatType, LinearFilter, RGBAFormat } from "../vendor/three/three.module.js";
|
||||
|
||||
/**
|
||||
* Loads the pre-baked matcap blobs produced by
|
||||
* `/home/mes123456/workinf_Blender_Wasm/tools/web/generate-matcap-textures.mjs`.
|
||||
*
|
||||
* Why a custom format instead of an image: the desktop matcaps are half-float
|
||||
* EXR with a separate diffuse and specular layer, and the specular layer is
|
||||
* genuinely HDR (ceramic_lightbulb peaks at 157.9, fullmetal at 1.21). An 8-bit
|
||||
* PNG would clip those highlights, so the payload stays half-float and is bound
|
||||
* with `DataTexture(HalfFloatType)`.
|
||||
*
|
||||
* Byte layout (little-endian), matching the generator:
|
||||
* 0..7 magic "WBMATCAP"
|
||||
* 8..12 width (uint32)
|
||||
* 12..16 height (uint32)
|
||||
* 16..20 flags (uint32, bit 0 = specular layer present)
|
||||
* 20.. half[3]*w*h diffuse, then half[3]*w*h specular when bit 0 is set
|
||||
*/
|
||||
|
||||
export interface MatcapTextureSet {
|
||||
diffuse: import("../vendor/three/three.module.js").Texture;
|
||||
specular: import("../vendor/three/three.module.js").Texture | null;
|
||||
}
|
||||
|
||||
const MAGIC = "WBMATCAP";
|
||||
const cache = new Map<string, Promise<MatcapTextureSet>>();
|
||||
|
||||
/** Three-component half data is expanded to RGBA because that is what WebGL2
|
||||
* uploads cheaply; alpha is constant 1 so no channel decoding is needed. */
|
||||
function toTexture(view: DataView, width: number, height: number, offset: number) {
|
||||
const rgba = new Uint16Array(width * height * 4);
|
||||
for (let index = 0, source = offset; index < width * height; index += 1) {
|
||||
const target = index * 4;
|
||||
rgba[target] = view.getUint16(source, true);
|
||||
rgba[target + 1] = view.getUint16(source + 2, true);
|
||||
rgba[target + 2] = view.getUint16(source + 4, true);
|
||||
rgba[target + 3] = 0x3c00; /* half-float 1.0 */
|
||||
source += 6;
|
||||
}
|
||||
const texture = new DataTexture(rgba, width, height, RGBAFormat, HalfFloatType);
|
||||
texture.magFilter = LinearFilter;
|
||||
texture.minFilter = LinearFilter;
|
||||
texture.generateMipmaps = false;
|
||||
/* Matcap UVs are computed in view space and already point at the right texel;
|
||||
* three would otherwise spend a GPU pass flipping a DataTexture we control. */
|
||||
texture.flipY = false;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
|
||||
export function matcapUrl(name: string): string {
|
||||
return `/assets/studiolights/matcap/${name}.bin`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Decodes one matcap. Results are cached by name, including in-flight
|
||||
* requests, so switching back and forth does not re-download.
|
||||
*/
|
||||
export function loadMatcap(name: string): Promise<MatcapTextureSet> {
|
||||
const cached = cache.get(name);
|
||||
if (cached) return cached;
|
||||
const request = (async () => {
|
||||
const response = await fetch(matcapUrl(name));
|
||||
if (!response.ok) throw new Error(`MATCAP_MISSING:${name}`);
|
||||
const buffer = await response.arrayBuffer();
|
||||
const bytes = new Uint8Array(buffer);
|
||||
const header = new DataView(buffer);
|
||||
const magic = String.fromCharCode(...bytes.subarray(0, 8));
|
||||
if (magic !== MAGIC) throw new Error(`MATCAP_BAD_MAGIC:${name}`);
|
||||
const width = header.getUint32(8, true);
|
||||
const height = header.getUint32(12, true);
|
||||
const flags = header.getUint32(16, true);
|
||||
const layerBytes = width * height * 3 * 2;
|
||||
const view = new DataView(buffer);
|
||||
const diffuse = toTexture(view, width, height, 20);
|
||||
const specular = (flags & 1) ? toTexture(view, width, height, 20 + layerBytes) : null;
|
||||
return { diffuse, specular };
|
||||
})();
|
||||
cache.set(name, request);
|
||||
request.catch(() => cache.delete(name));
|
||||
return request;
|
||||
}
|
||||
|
||||
/** Names shipped by the generator; kept in sync with the matcap directory. */
|
||||
export const MATCAP_NAMES = [
|
||||
"basic_bright", "basic_dark", "basic_grey", "basic_side", "brush_thumbnail_preview",
|
||||
"ceramic_dark", "ceramic_lightbulb", "check_gradient", "check_normal+y",
|
||||
"check_reflection_horizontal", "check_reflection_vertical", "check_rim_dark",
|
||||
"check_rim_light", "clay_brown", "clay_green", "clay_studio", "clay_warm",
|
||||
"fullmetal", "hard_surface_grey", "hard_surface_red", "metal_bronze",
|
||||
"metal_carpaint", "pearl", "red_wax", "resin", "toon_dark", "toon_light",
|
||||
] as const;
|
||||
|
||||
/** BKE_studiolight_find_default() names basic_1.exr, which is not shipped; the
|
||||
* desktop therefore falls back to list order, i.e. the first loaded matcap. */
|
||||
export const DEFAULT_MATCAP = "basic_bright";
|
||||
@@ -39,7 +39,18 @@ export type OffscreenViewportRequest =
|
||||
| { type: "greasePencilPointPreview"; dataId: string; layerId: string; frame: number; points: GreasePencilPointPreview[] | null }
|
||||
| { type: "curveGizmoFrame"; dataId: string | null; frame: CurveGizmoFrameIR | null }
|
||||
| { type: "orbit"; deltaX: number; deltaY: number; zoom: number }
|
||||
/* Viewport display + navigation preferences; the worker owns both the
|
||||
* shading materials and the orbit math, so they must travel with it. */
|
||||
| { type: "display"; shadingMode: "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED"; xray: boolean }
|
||||
| { type: "solidShading"; options: import("./studio-light").SolidShadingOptions }
|
||||
/* Desktop Viewport Shading > Studio Light for Material Preview worlds. */
|
||||
| { type: "studioLight"; name: string }
|
||||
| { type: "navigationPrefs"; orbitSensitivity: number; zoomSensitivity: number; invertZoom: boolean }
|
||||
| { type: "pick"; x: number; y: number; mode: "REPLACE" | "ADD" | "SUBTRACT"; baseSelectionRevision: number }
|
||||
/* Surface picking for sculpting. `x`/`y` are NDC; the worker answers with the
|
||||
* first mesh hit so the stroke starts on geometry, never on a camera plane. */
|
||||
| { type: "pickSurface"; requestId: string; x: number; y: number }
|
||||
| { type: "projectBrushCursor"; requestId: string; x: number; y: number; radius: number; cssWidth: number; cssHeight: number }
|
||||
| { type: "boxSelect"; requestId: string; x0: number; y0: number; x1: number; y1: number; additive: boolean }
|
||||
| { type: "meshBoxSelect"; requestId: string; x0: number; y0: number; x1: number; y1: number }
|
||||
| { type: "greasePencilMarquee"; drawing: GreasePencilDrawingScopeIR; box: GreasePencilMarqueeBoxIR; baseRevision: number; baseSelectionRevision: number; mode: "REPLACE" | "ADD" | "SUBTRACT" }
|
||||
@@ -57,6 +68,8 @@ export type OffscreenViewportResponse =
|
||||
| { type: "displacementStatus"; mappedMaterials: number; boundMaterials: number; heightTextures: number; heightTextureKeys: number; heightBindingImageIds: string[]; heightTextureKeyList: string[] }
|
||||
| { type: "volumeStatus"; status: "none" | "loading" | "ready" | "blocked"; count: number; errorCode?: string }
|
||||
| { type: "selected"; objectId: string; additive: boolean }
|
||||
| { type: "surfacePicked"; requestId: string; pick: import("./viewport-surface-math").SurfacePick | null }
|
||||
| { type: "brushCursorRing"; requestId: string; ring: import("./viewport-surface-math").BrushCursorRing | null }
|
||||
| { type: "boxSelected"; requestId: string; objectIds: string[] }
|
||||
| { type: "meshBoxSelected"; requestId: string; meshId: string; mode: MeshElementMode; indices: number[] }
|
||||
| { type: "elementSelected"; meshId: string; mode: MeshElementMode; index: number; additive: boolean; nonMeshKind?: NonMeshElementKind }
|
||||
|
||||
@@ -7,6 +7,7 @@ import { cloneMeshGeometryBuffers } from "../../../protocol/mesh-geometry-delta"
|
||||
import { nonMeshChunkTransferables } from "../../../protocol/nonmesh-binary";
|
||||
import type { OffscreenTextureStatus, OffscreenViewportRequest, OffscreenViewportResponse } from "./offscreen-viewport-protocol";
|
||||
import { PBR_PROFILE, PBR_SHADOW_PROFILE, PBR_TONE_MAPPING } from "./pbr";
|
||||
import { usesStudioMaterial } from "./studio-light";
|
||||
import { resolveViewportPixelMetrics, viewportNDC } from "../../../protocol/viewport-dpr";
|
||||
import { observePointerEvent } from "../../../protocol/pointer-contract";
|
||||
import {ViewportNavigation} from './viewport-navigation';
|
||||
@@ -43,6 +44,24 @@ export interface ViewportBackend {
|
||||
setCameraWriteHandler?(handler: ((frame: import('../../../protocol/viewport-camera').BlenderViewportCamera & { objectId: string }) => void) | null): void;
|
||||
toggleCameraView?(): void;
|
||||
setCameraLock?(locked: boolean): void;
|
||||
/** Viewport shading mode (WIREFRAME/SOLID/MATERIAL/RENDERED). */
|
||||
setShadingMode?(mode: 'WIREFRAME' | 'SOLID' | 'MATERIAL' | 'RENDERED'): void;
|
||||
getShadingMode?(): 'WIREFRAME' | 'SOLID' | 'MATERIAL' | 'RENDERED';
|
||||
/** See-through rendering; desktop keeps depth but skips occlusion shading. */
|
||||
setXray?(enabled: boolean): void;
|
||||
/** Navigation sensitivity preferences (orbit/zoom scale, wheel inversion). */
|
||||
setNavigationPrefs?(prefs: { orbitSensitivity?: number; zoomSensitivity?: number; invertZoom?: boolean }): void;
|
||||
/** Workbench solid-shading look: studio rig, matcap, shadow, cavity. */
|
||||
setSolidShading?(options: import("./studio-light").SolidShadingOptions): void;
|
||||
/** Material Preview studio world (`studiolights/world/*.exr` name). */
|
||||
setPreviewStudioLight?(name: string): void;
|
||||
getXray?(): boolean;
|
||||
/** Screen-space pick resolved against the real mesh surface (sculpt strokes).
|
||||
* May be asynchronous: the offscreen path has to ask its worker. */
|
||||
pickSurfacePoint?(clientX: number, clientY: number): import("./viewport-surface-math").SurfacePick | null | Promise<import("./viewport-surface-math").SurfacePick | null>;
|
||||
/** Screen-space sculpt cursor ring; null when the pointer misses the mesh.
|
||||
* Always synchronous so pointermove can call it every event. */
|
||||
projectBrushCursor?(clientX: number, clientY: number, radius: number): import("./viewport-surface-math").BrushCursorRing | null;
|
||||
isCameraView?(): boolean;
|
||||
isCameraLocked?(): boolean;
|
||||
dispose(): void;
|
||||
@@ -107,6 +126,10 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
private lastGeometryBuffers: MeshGeometryBuffer[] | null = null;
|
||||
private lastNonMeshGeometryBuffers: NonMeshGeometryChunk[] | null = null;
|
||||
private greasePencilSelectionRevision = 0;
|
||||
private shadingMode: "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED" = "MATERIAL";
|
||||
private xray = false;
|
||||
private solidShading: import("./studio-light").SolidShadingOptions = {};
|
||||
private navigationPrefs = { orbitSensitivity: 1, zoomSensitivity: 1, invertZoom: false };
|
||||
private paintDepthRequestSequence = 0;
|
||||
private readonly pendingPaintDepth = new Map<string, {
|
||||
request: PaintDepthVisibilityRequestIR;
|
||||
@@ -115,6 +138,17 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
}>();
|
||||
private readonly pendingBoxSelect = new Map<string, { resolve: (objectIds: string[]) => void; reject: (error: Error) => void }>();
|
||||
private readonly pendingMeshBoxSelect = new Map<string, { resolve: (result: { meshId: string; mode: MeshElementMode; indices: number[] }) => void; reject: (error: Error) => void }>();
|
||||
/* Surface picking round-trips through the worker. The ring is cached so the
|
||||
* synchronous `projectBrushCursor` can answer every pointermove; the pick is
|
||||
* awaited, because a stroke that starts on a guessed point sculpts the wrong
|
||||
* place. */
|
||||
private readonly pendingSurfacePick = new Map<string, { resolve: (pick: import("./viewport-surface-math").SurfacePick | null) => void; reject: (error: Error) => void }>();
|
||||
private readonly pendingBrushRing = new Map<string, { resolve: (ring: import("./viewport-surface-math").BrushCursorRing | null) => void; reject: (error: Error) => void }>();
|
||||
/* The cached ring is anchored to the pointer position it was computed at, so
|
||||
* `projectBrushCursor` can translate it by the pointer delta and still follow
|
||||
* the cursor between worker replies instead of trailing one event behind. */
|
||||
private lastBrushRing: { ring: import("./viewport-surface-math").BrushCursorRing; clientX: number; clientY: number; radius: number } | null = null;
|
||||
private surfacePickSequence = 0;
|
||||
private boxSelectSequence = 0;
|
||||
private stillSequence = 0;
|
||||
private requestedSnapshotRevision = -1;
|
||||
@@ -174,6 +208,41 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
setCameraWriteHandler(handler: ((frame: import('../../../protocol/viewport-camera').BlenderViewportCamera & { objectId: string }) => void) | null): void { this.navigation.setCameraWriteHandler(handler); }
|
||||
toggleCameraView(): void { this.navigation.toggleCameraView(); }
|
||||
setCameraLock(locked: boolean): void { this.navigation.setCameraLock(locked); }
|
||||
/* The worker owns orbit math and materials, so these preferences must be
|
||||
* forwarded; the local ViewportNavigation only drives pointer gestures. */
|
||||
setNavigationPrefs(prefs: { orbitSensitivity?: number; zoomSensitivity?: number; invertZoom?: boolean }): void {
|
||||
this.navigationPrefs = { ...this.navigationPrefs, ...prefs };
|
||||
this.navigation.setNavigationPrefs(this.navigationPrefs);
|
||||
this.worker.postMessage({ type: "navigationPrefs", orbitSensitivity: this.navigationPrefs.orbitSensitivity, zoomSensitivity: this.navigationPrefs.zoomSensitivity, invertZoom: this.navigationPrefs.invertZoom } satisfies OffscreenViewportRequest);
|
||||
}
|
||||
setShadingMode(mode: "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED"): void {
|
||||
if (this.shadingMode === mode) return;
|
||||
this.shadingMode = mode;
|
||||
this.canvas.dataset.shadingMode = mode.toLowerCase();
|
||||
/* Same dataset marker the main-thread renderer publishes, so both paths
|
||||
* report the same studio/PBR state. */
|
||||
this.canvas.dataset.studioLighting = usesStudioMaterial(mode) ? "studio-mvp" : "pbr";
|
||||
this.worker.postMessage({ type: "display", shadingMode: mode, xray: this.xray } satisfies OffscreenViewportRequest);
|
||||
}
|
||||
getShadingMode(): "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED" { return this.shadingMode; }
|
||||
/** Solid-mode lighting settings; the worker owns the materials, so forward. */
|
||||
setSolidShading(options: import("./studio-light").SolidShadingOptions): void {
|
||||
this.solidShading = { ...this.solidShading, ...options };
|
||||
this.worker.postMessage({ type: "solidShading", options } satisfies OffscreenViewportRequest);
|
||||
}
|
||||
getSolidShading(): import("./studio-light").SolidShadingOptions { return this.solidShading; }
|
||||
/** Material Preview studio world; the worker owns the scene, so forward it. */
|
||||
setPreviewStudioLight(name: string): void {
|
||||
this.canvas.dataset.studioLight = name;
|
||||
this.worker.postMessage({ type: "studioLight", name } satisfies OffscreenViewportRequest);
|
||||
}
|
||||
setXray(enabled: boolean): void {
|
||||
if (this.xray === enabled) return;
|
||||
this.xray = enabled;
|
||||
this.canvas.dataset.xray = enabled ? "1" : "0";
|
||||
this.worker.postMessage({ type: "display", shadingMode: this.shadingMode, xray: enabled } satisfies OffscreenViewportRequest);
|
||||
}
|
||||
getXray(): boolean { return this.xray; }
|
||||
isCameraView(): boolean { return this.navigation.isCameraView(); }
|
||||
isCameraLocked(): boolean { return this.navigation.isCameraLocked(); }
|
||||
setSnapshot(snapshot: SceneSnapshotIR, geometryBuffers: MeshGeometryBuffer[] = [], nonMeshGeometryBuffers: NonMeshGeometryChunk[] = []): void {
|
||||
@@ -329,6 +398,58 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
});
|
||||
}
|
||||
|
||||
/* Requests always come back (the worker answers `null` on a miss or before a
|
||||
* snapshot exists), so the timeout only guards a torn-down worker. */
|
||||
private requestBrushRing(clientX: number, clientY: number, radius: number): Promise<import("./viewport-surface-math").BrushCursorRing | null> {
|
||||
const bounds = this.canvas.getBoundingClientRect();
|
||||
if (bounds.width <= 0 || bounds.height <= 0) return Promise.resolve(null);
|
||||
const ndc = viewportNDC(clientX, clientY, bounds);
|
||||
const requestId = `brush-ring-${++this.surfacePickSequence}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
this.pendingBrushRing.delete(requestId);
|
||||
reject(new Error("VIEWPORT_BRUSH_RING_TIMEOUT"));
|
||||
}, 5000);
|
||||
this.pendingBrushRing.set(requestId, {
|
||||
resolve: (ring) => { window.clearTimeout(timer); resolve(ring); },
|
||||
reject: (error) => { window.clearTimeout(timer); reject(error); },
|
||||
});
|
||||
this.worker.postMessage({ type: "projectBrushCursor", requestId, x: ndc.x, y: ndc.y, radius, cssWidth: bounds.width, cssHeight: bounds.height } satisfies OffscreenViewportRequest);
|
||||
});
|
||||
}
|
||||
|
||||
projectBrushCursor(clientX: number, clientY: number, radius: number): import("./viewport-surface-math").BrushCursorRing | null {
|
||||
/* Refresh the cache for the next event, but answer this one from what is
|
||||
* already known: pointermove cannot wait for a worker round-trip. */
|
||||
void this.requestBrushRing(clientX, clientY, radius)
|
||||
.then((ring) => { this.lastBrushRing = ring ? { ring, clientX, clientY, radius } : null; })
|
||||
.catch(() => {});
|
||||
const cached = this.lastBrushRing;
|
||||
if (!cached || cached.radius !== radius) return null;
|
||||
return {
|
||||
center: [cached.ring.center[0] + (clientX - cached.clientX), cached.ring.center[1] + (clientY - cached.clientY)],
|
||||
screenRadius: cached.ring.screenRadius,
|
||||
};
|
||||
}
|
||||
|
||||
pickSurfacePoint(clientX: number, clientY: number): Promise<import("./viewport-surface-math").SurfacePick | null> {
|
||||
const bounds = this.canvas.getBoundingClientRect();
|
||||
if (bounds.width <= 0 || bounds.height <= 0) return Promise.resolve(null);
|
||||
const ndc = viewportNDC(clientX, clientY, bounds);
|
||||
const requestId = `surface-pick-${++this.surfacePickSequence}`;
|
||||
return new Promise((resolve, reject) => {
|
||||
const timer = window.setTimeout(() => {
|
||||
this.pendingSurfacePick.delete(requestId);
|
||||
reject(new Error("VIEWPORT_SURFACE_PICK_TIMEOUT"));
|
||||
}, 5000);
|
||||
this.pendingSurfacePick.set(requestId, {
|
||||
resolve: (pick) => { window.clearTimeout(timer); resolve(pick); },
|
||||
reject: (error) => { window.clearTimeout(timer); reject(error); },
|
||||
});
|
||||
this.worker.postMessage({ type: "pickSurface", requestId, x: ndc.x, y: ndc.y } satisfies OffscreenViewportRequest);
|
||||
});
|
||||
}
|
||||
|
||||
boxSelect(rect: { x0: number; y0: number; x1: number; y1: number }, additive: boolean): Promise<string[]> {
|
||||
const requestId = `box-select-${++this.boxSelectSequence}`;
|
||||
return new Promise<string[]>((resolve, reject) => {
|
||||
@@ -486,6 +607,18 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
if (message.status === "ready") this.canvas.dispatchEvent(new CustomEvent("viewport-device-restored"));
|
||||
}
|
||||
else if (message.type === "selected") this.onSelect?.(message.objectId, message.additive);
|
||||
else if (message.type === "surfacePicked") {
|
||||
const pending = this.pendingSurfacePick.get(message.requestId);
|
||||
if (!pending) return;
|
||||
this.pendingSurfacePick.delete(message.requestId);
|
||||
pending.resolve(message.pick);
|
||||
}
|
||||
else if (message.type === "brushCursorRing") {
|
||||
const pending = this.pendingBrushRing.get(message.requestId);
|
||||
if (!pending) return;
|
||||
this.pendingBrushRing.delete(message.requestId);
|
||||
pending.resolve(message.ring);
|
||||
}
|
||||
else if (message.type === "boxSelected") {
|
||||
const pending = this.pendingBoxSelect.get(message.requestId);
|
||||
if (!pending) return;
|
||||
@@ -632,5 +765,15 @@ export class OffscreenViewportRenderer implements ViewportBackend {
|
||||
this.pendingPaintDepth.clear();
|
||||
for (const pending of this.pendingStill.values()) pending.reject(new Error("VIEWPORT_DISPOSED: offscreen still render was cancelled"));
|
||||
this.pendingStill.clear();
|
||||
/* The box-select maps were never drained here; a disposed viewport would
|
||||
* leave their promises hanging forever. */
|
||||
for (const pending of this.pendingBoxSelect.values()) pending.reject(new Error("VIEWPORT_DISPOSED: box select was cancelled"));
|
||||
this.pendingBoxSelect.clear();
|
||||
for (const pending of this.pendingMeshBoxSelect.values()) pending.reject(new Error("VIEWPORT_DISPOSED: mesh box select was cancelled"));
|
||||
this.pendingMeshBoxSelect.clear();
|
||||
for (const pending of this.pendingSurfacePick.values()) pending.reject(new Error("VIEWPORT_DISPOSED: surface pick was cancelled"));
|
||||
this.pendingSurfacePick.clear();
|
||||
for (const pending of this.pendingBrushRing.values()) pending.reject(new Error("VIEWPORT_DISPOSED: brush ring was cancelled"));
|
||||
this.pendingBrushRing.clear();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -104,7 +104,9 @@ export function createPBRMaterial(definition?: MaterialIR, active = false, shade
|
||||
opacity: alpha,
|
||||
transparent: alpha < 0.999,
|
||||
depthWrite: alpha >= 0.999,
|
||||
vertexColors: true,
|
||||
/* Callers opt in per geometry (see viewport.ts usesVertexColor); enabling it
|
||||
* unconditionally renders every mesh without a COLOR attribute black. */
|
||||
vertexColors: false,
|
||||
side: DoubleSide,
|
||||
});
|
||||
material.userData.baseEmissive = material.emissive.getHex();
|
||||
@@ -170,10 +172,14 @@ function blackbodySrgb(temperature: number): [number, number, number] {
|
||||
return [red, green, blue].map((component) => clamp(component / 255, 0, 1, 0)) as [number, number, number];
|
||||
}
|
||||
|
||||
function srgbToLinear(value: number): number {
|
||||
export function srgbToLinear(value: number): number {
|
||||
return value <= 0.04045 ? value / 12.92 : ((value + 0.055) / 1.055) ** 2.4;
|
||||
}
|
||||
|
||||
export function linearToSrgb(value: number): number {
|
||||
return value <= 0.0031308 ? value * 12.92 : 1.055 * value ** (1 / 2.4) - 0.055;
|
||||
}
|
||||
|
||||
/** Returns a bounded linear-RGB light color with Blender's 6500 K default treated as neutral. */
|
||||
export function blenderLightColor(definition: LightIR): [number, number, number] {
|
||||
if (!definition.useTemperature) return [...definition.color];
|
||||
|
||||
101
web/app/src/three-adapter/studio-environment.ts
Normal file
101
web/app/src/three-adapter/studio-environment.ts
Normal file
@@ -0,0 +1,101 @@
|
||||
import {
|
||||
DataTexture,
|
||||
EquirectangularReflectionMapping,
|
||||
FloatType,
|
||||
LinearSRGBColorSpace,
|
||||
PMREMGenerator,
|
||||
RGBAFormat,
|
||||
type Texture,
|
||||
type WebGLRenderer,
|
||||
} from "../vendor/three/three.module.js";
|
||||
|
||||
/**
|
||||
* Desktop Material Preview studio worlds.
|
||||
*
|
||||
* Desktop lights Material Preview from `studiolights/world/*.exr`
|
||||
* (`STUDIOLIGHT_WORLD_DEFAULT = forest.exr` in
|
||||
* blender-5.2.0/source/blender/blenkernel/intern/studiolight.cc). The browser
|
||||
* has no EXR decoder, so tools/web/import-studiolight-world.py ships the exact
|
||||
* float32 pixels as `WBENV1\n` + u32 width + u32 height + RGB float32 LE.
|
||||
* The N-panel studio selector lists the same eight datasets as the desktop
|
||||
* directory.
|
||||
*/
|
||||
export const STUDIO_WORLD_LIGHTS = [
|
||||
"city", "courtyard", "forest", "interior", "night", "studio", "sunrise", "sunset",
|
||||
] as const;
|
||||
export type StudioWorldLight = (typeof STUDIO_WORLD_LIGHTS)[number];
|
||||
export const STUDIO_WORLD_DEFAULT: StudioWorldLight = "forest";
|
||||
|
||||
export interface StudioWorldPixels {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
pixels: Float32Array;
|
||||
pixelBytes: Uint8Array;
|
||||
}
|
||||
|
||||
export interface StudioWorldReport {
|
||||
name: string;
|
||||
width: number;
|
||||
height: number;
|
||||
pixelsSha256: string;
|
||||
samples: number[][];
|
||||
}
|
||||
|
||||
export function isStudioWorldLight(name: string): name is StudioWorldLight {
|
||||
return (STUDIO_WORLD_LIGHTS as readonly string[]).includes(name);
|
||||
}
|
||||
|
||||
/** Fetch and validate one `WBENV1` dataset; null when the asset is missing or malformed. */
|
||||
export async function fetchStudioWorld(name: string): Promise<StudioWorldPixels | null> {
|
||||
const response = await fetch(`/lights/${name}.bin`);
|
||||
if (!response.ok) return null;
|
||||
const bytes = new Uint8Array(await response.arrayBuffer());
|
||||
/* "WBENV1\n" (7 bytes) + u32 width + u32 height (8) = 15-byte header. */
|
||||
if (bytes.byteLength < 15 || new TextDecoder().decode(bytes.subarray(0, 7)) !== "WBENV1\n") return null;
|
||||
const header = new DataView(bytes.buffer, bytes.byteOffset, 15);
|
||||
const width = header.getUint32(7, true), height = header.getUint32(11, true);
|
||||
const pixelBytes = bytes.subarray(15);
|
||||
if (pixelBytes.byteLength !== width * height * 12) return null;
|
||||
return { name, width, height, pixels: new Float32Array(pixelBytes.slice().buffer), pixelBytes };
|
||||
}
|
||||
|
||||
/** Prefilter one studio world into a scene environment texture (RGB float -> PMREM). */
|
||||
export function createStudioWorldTexture(renderer: WebGLRenderer, world: StudioWorldPixels): Texture {
|
||||
const { width, height, pixels } = world;
|
||||
const rgba = new Float32Array(width * height * 4);
|
||||
for (let index = 0, target = 0; index < pixels.length; index += 3, target += 4) {
|
||||
rgba[target] = pixels[index];
|
||||
rgba[target + 1] = pixels[index + 1];
|
||||
rgba[target + 2] = pixels[index + 2];
|
||||
rgba[target + 3] = 1;
|
||||
}
|
||||
const equirect = new DataTexture(rgba, width, height, RGBAFormat, FloatType);
|
||||
equirect.mapping = EquirectangularReflectionMapping;
|
||||
equirect.colorSpace = LinearSRGBColorSpace;
|
||||
equirect.flipY = true;
|
||||
equirect.needsUpdate = true;
|
||||
const pmrem = new PMREMGenerator(renderer);
|
||||
const target = pmrem.fromEquirectangular(equirect).texture;
|
||||
equirect.dispose();
|
||||
pmrem.dispose();
|
||||
return target;
|
||||
}
|
||||
|
||||
/** Pixel-identity report used by the Chromium comparison against forest.json. */
|
||||
export async function studioWorldReport(world: StudioWorldPixels): Promise<StudioWorldReport> {
|
||||
const { width, height, pixels } = world;
|
||||
const digest = await crypto.subtle.digest("SHA-256", world.pixelBytes.slice().buffer as ArrayBuffer);
|
||||
const sampleAt = (x: number, y: number) => {
|
||||
const index = (y * width + x) * 3;
|
||||
return [x, y, Number(pixels[index].toFixed(6)), Number(pixels[index + 1].toFixed(6)), Number(pixels[index + 2].toFixed(6))];
|
||||
};
|
||||
return {
|
||||
name: world.name,
|
||||
width,
|
||||
height,
|
||||
pixelsSha256: Array.from(new Uint8Array(digest), (value) => value.toString(16).padStart(2, "0")).join(""),
|
||||
samples: [sampleAt(0, 0), sampleAt(Math.floor(width / 4), Math.floor(height / 8)),
|
||||
sampleAt(Math.floor(width / 2), Math.floor(height / 2)), sampleAt(width - 1, height - 1)],
|
||||
};
|
||||
}
|
||||
60
web/app/src/three-adapter/studio-light-presets.ts
Normal file
60
web/app/src/three-adapter/studio-light-presets.ts
Normal file
@@ -0,0 +1,60 @@
|
||||
import type { StudioLightRig } from "./studio-light";
|
||||
|
||||
/**
|
||||
* GENERATED by /home/mes123456/workinf_Blender_Wasm/tools/web/generate-studiolight-presets.mjs
|
||||
* Source: blender-5.2.0/release/datafiles/studiolights/studio/*.sl
|
||||
* Do not edit by hand; re-run the generator instead.
|
||||
*
|
||||
* Keys match the desktop registry, which stores the basename *with* its
|
||||
* extension (studiolight.cc:600-618) — so the UI shows "studio.sl", not "studio".
|
||||
*/
|
||||
export const STUDIO_LIGHT_PRESETS: Record<string, StudioLightRig> = {
|
||||
"basic.sl": {
|
||||
ambient: [0, 0, 0],
|
||||
lights: [
|
||||
{ smooth: 0.100000, col: [0.507074, 0.507074, 0.507074], spec: [0.666141, 0.666141, 0.666141], vec: [0, 0.639175, 0.769061] },
|
||||
{ smooth: 0.340000, col: [0.021936, 0.058160, 0.063719], spec: [0.033668, 0.060061, 0.063712], vec: [-0.846939, -0.357143, 0.393883] },
|
||||
{ smooth: 0.340000, col: [0.063721, 0.040061, 0.037017], spec: [0.069396, 0.046455, 0.046455], vec: [0.755102, -0.530612, 0.385060] },
|
||||
{ smooth: 0.724138, col: [0, 0, 0], spec: [0.023079, 0.023393, 0.025394], vec: [0.034483, 0.913793, 0.404714] },
|
||||
],
|
||||
},
|
||||
"outdoor.sl": {
|
||||
ambient: [0.016682, 0.022491, 0.025394],
|
||||
lights: [
|
||||
{ smooth: 0.756566, col: [0.199273, 0.365712, 0.517334], spec: [0.395608, 0.594690, 0.787400], vec: [0, 0.972477, 0.232999] },
|
||||
{ smooth: 0.183261, col: [0.685958, 0.661591, 0.591560], spec: [1, 0.968130, 0.876109], vec: [0.469388, 0.612245, 0.636264] },
|
||||
{ smooth: 0.694915, col: [0.039072, 0.052218, 0.038032], spec: [0.069250, 0.095506, 0.067197], vec: [-0.023438, -0.992188, 0.122534] },
|
||||
{ smooth: 0, col: [0, 0, 0], spec: [0, 0, 0], vec: [0, 0, 0] },
|
||||
],
|
||||
},
|
||||
"paint.sl": {
|
||||
ambient: [0, 0, 0],
|
||||
lights: [
|
||||
{ smooth: 0.374078, col: [1, 1, 1], spec: [0.281010, 0.281010, 0.281010], vec: [0.033898, 0.406780, 0.912897] },
|
||||
{ smooth: 0.135593, col: [0.342384, 0.342384, 0.342384], spec: [0, 0, 0], vec: [0, 0.372881, 0.927879] },
|
||||
{ smooth: 0.630803, col: [0.201899, 0.156801, 0.147954], spec: [0.066807, 0.058182, 0.063403], vec: [0.079643, -0.681392, -0.727573] },
|
||||
{ smooth: 0.200000, col: [0.220250, 0.037944, 0.047254], spec: [0.106531, 0.080187, 0.063969], vec: [-0.081162, -0.173044, -0.981564] },
|
||||
],
|
||||
},
|
||||
"rim.sl": {
|
||||
ambient: [0, 0, 0],
|
||||
lights: [
|
||||
{ smooth: 0.100000, col: [0.673848, 0.673848, 0.673848], spec: [1, 1, 1], vec: [-0.897616, -0.016623, -0.440464] },
|
||||
{ smooth: 0.469388, col: [0.178862, 0.164949, 0.145299], spec: [0.220258, 0.204067, 0.185233], vec: [0.551020, 0.204082, 0.809152] },
|
||||
{ smooth: 0.387755, col: [0.447979, 0.447979, 0.447979], spec: [1, 1, 1], vec: [0.885727, 0.098414, -0.453655] },
|
||||
{ smooth: 0, col: [0, 0, 0], spec: [0, 0, 0], vec: [0, 0, 0] },
|
||||
],
|
||||
},
|
||||
"studio.sl": {
|
||||
ambient: [0, 0, 0],
|
||||
lights: [
|
||||
{ smooth: 0.200000, col: [0.723042, 0.723042, 0.723042], spec: [0.685956, 0.685956, 0.685956], vec: [-0.854701, 0.111111, 0.507091] },
|
||||
{ smooth: 0.719626, col: [0.063100, 0.069978, 0.067951], spec: [0.145797, 0.162642, 0.157673], vec: [0.058607, -0.987943, -0.143295] },
|
||||
{ smooth: 0.281250, col: [0.157432, 0.163405, 0.214035], spec: [0.246195, 0.225308, 0.225308], vec: [0.972202, 0.075846, -0.221518] },
|
||||
{ smooth: 0, col: [0, 0, 0], spec: [0, 0, 0], vec: [0, 0, 0] },
|
||||
],
|
||||
},
|
||||
};
|
||||
|
||||
/** The internal, non-file light that desktop always lists first. */
|
||||
export const STUDIO_LIGHT_PRESET_NAMES: string[] = ["Default", ...Object.keys(STUDIO_LIGHT_PRESETS)];
|
||||
496
web/app/src/three-adapter/studio-light.ts
Normal file
496
web/app/src/three-adapter/studio-light.ts
Normal file
@@ -0,0 +1,496 @@
|
||||
import { Color, DoubleSide, ShaderMaterial, Vector3 } from "../vendor/three/three.module.js";
|
||||
|
||||
/**
|
||||
* Blender SOLID-mode studio lighting, ported from the workbench engine.
|
||||
*
|
||||
* The desktop "studio light" is NOT an environment map or a matcap: it is an
|
||||
* analytic rig of four directional lights. `Default` is synthesised in C, not
|
||||
* loaded from `studiolights/studio/*.sl`.
|
||||
*
|
||||
* Source of truth:
|
||||
* - blender-5.2.0/source/blender/blenkernel/intern/studiolight.cc:791-841
|
||||
* (`BKE_studiolight_default`) for the rig values
|
||||
* - blender-5.2.0/source/blender/draw/engines/workbench/shaders/
|
||||
* workbench_world_light_lib.glsl:21-141 (`get_world_lighting` and helpers)
|
||||
* for the shading maths
|
||||
* - workbench_prepass.bsl.hh:340-344: lighting is evaluated in view space, and
|
||||
* `V3D_SHADING_WORLD_ORIENTATION` is off by default, so the stored light
|
||||
* vectors are used directly with no camera-relative rotation.
|
||||
*/
|
||||
|
||||
export type ViewportShadingMode = "WIREFRAME" | "SOLID" | "MATERIAL" | "RENDERED";
|
||||
|
||||
export interface StudioLight {
|
||||
smooth: number;
|
||||
col: [number, number, number];
|
||||
spec: [number, number, number];
|
||||
vec: [number, number, number];
|
||||
}
|
||||
|
||||
export interface StudioLightRig {
|
||||
ambient: [number, number, number];
|
||||
lights: StudioLight[];
|
||||
}
|
||||
|
||||
/** `BKE_studiolight_default()` — the built-in "Default" studio light. */
|
||||
export const DEFAULT_STUDIO_LIGHT: StudioLightRig = {
|
||||
ambient: [0, 0, 0],
|
||||
lights: [
|
||||
{ smooth: 0.526620, col: [0.033103, 0.033103, 0.033103], spec: [0.266761, 0.266761, 0.266761], vec: [-0.352546, 0.170931, -0.920051] },
|
||||
{ smooth: 0.000000, col: [0.521083, 0.538226, 0.538226], spec: [0.599030, 0.599030, 0.599030], vec: [-0.408163, 0.346939, 0.844415] },
|
||||
{ smooth: 0.478261, col: [0.038403, 0.034357, 0.049530], spec: [0.106102, 0.125981, 0.158523], vec: [0.521739, 0.826087, 0.212999] },
|
||||
{ smooth: 0.200000, col: [0.090838, 0.082080, 0.072255], spec: [0.106535, 0.084771, 0.066080], vec: [0.624519, -0.562067, -0.542269] },
|
||||
],
|
||||
};
|
||||
|
||||
/** Clay base colour: DNA_material_types.h:389 is linear 0.8, roughness 0.4. */
|
||||
export const SOLID_CLAY_COLOR: [number, number, number] = [0.8, 0.8, 0.8];
|
||||
export const SOLID_CLAY_ROUGHNESS = 0.4;
|
||||
|
||||
const VERTEX_SHADER = /* glsl */ `
|
||||
#include <common>
|
||||
|
||||
varying vec3 vViewNormal;
|
||||
varying vec3 vViewPosition;
|
||||
|
||||
void main() {
|
||||
/* Mirrors the defaultnormal_vertex chunk: instance scale has to be undone
|
||||
* before the instance matrix rotates the normal. */
|
||||
vec3 objectNormal = vec3(normal);
|
||||
#ifdef USE_INSTANCING
|
||||
mat3 im = mat3(instanceMatrix);
|
||||
objectNormal /= vec3(dot(im[0], im[0]), dot(im[1], im[1]), dot(im[2], im[2]));
|
||||
objectNormal = im * objectNormal;
|
||||
#endif
|
||||
vViewNormal = normalize(normalMatrix * objectNormal);
|
||||
|
||||
/* Mirrors the project_vertex chunk, including instance placement. */
|
||||
vec4 mvPosition = vec4(position, 1.0);
|
||||
#ifdef USE_INSTANCING
|
||||
mvPosition = instanceMatrix * mvPosition;
|
||||
#endif
|
||||
mvPosition = modelViewMatrix * mvPosition;
|
||||
vViewPosition = -mvPosition.xyz;
|
||||
gl_Position = projectionMatrix * mvPosition;
|
||||
}
|
||||
`;
|
||||
|
||||
const FRAGMENT_SHADER = /* glsl */ `
|
||||
precision highp float;
|
||||
|
||||
varying vec3 vViewNormal;
|
||||
varying vec3 vViewPosition;
|
||||
|
||||
uniform vec3 uBaseColor;
|
||||
uniform float uRoughness;
|
||||
uniform float uMetallic;
|
||||
uniform float uUseSpecular;
|
||||
uniform vec3 uAmbient;
|
||||
uniform vec3 uLightVec[4];
|
||||
uniform vec3 uLightDiffuse[4];
|
||||
uniform vec3 uLightSpecular[4];
|
||||
uniform float uLightWrap[4];
|
||||
uniform vec3 uSelectionTint;
|
||||
uniform float uSelectionMix;
|
||||
uniform vec3 uShadowDirection;
|
||||
uniform float uShowShadow;
|
||||
uniform float uShadowIntensity;
|
||||
uniform float uShadowShift;
|
||||
uniform float uShadowFocus;
|
||||
|
||||
/* workbench_world_light_lib.glsl:21 */
|
||||
vec3 brdf_approx(vec3 spec_color, float roughness, float NV) {
|
||||
float fresnel = exp2(-8.35 * NV) * (1.0 - roughness);
|
||||
return mix(spec_color, vec3(1.0), fresnel);
|
||||
}
|
||||
|
||||
/* workbench_world_light_lib.glsl:41 — NL is unclamped, w in [0..1]. */
|
||||
float wrapped_lighting(float NL, float w) {
|
||||
float w1 = w + 1.0;
|
||||
return clamp((NL + w) / (w1 * w1), 0.0, 1.0);
|
||||
}
|
||||
|
||||
/* workbench_world_light_lib.glsl:30 */
|
||||
float blinn_specular(float shininess, float spec_angle, float NL) {
|
||||
return pow(spec_angle, shininess) * NL * (shininess * 0.125 + 1.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 N = normalize(vViewNormal);
|
||||
vec3 I = normalize(vViewPosition);
|
||||
if (!gl_FrontFacing) N = -N;
|
||||
|
||||
vec3 base_color = uBaseColor;
|
||||
vec3 diffuse_color;
|
||||
vec3 specular_color;
|
||||
if (uUseSpecular > 0.5) {
|
||||
diffuse_color = mix(base_color, vec3(0.0), uMetallic);
|
||||
specular_color = mix(vec3(0.05), base_color, uMetallic);
|
||||
}
|
||||
else {
|
||||
diffuse_color = base_color;
|
||||
specular_color = vec3(0.0);
|
||||
}
|
||||
|
||||
vec3 specular_light = uAmbient;
|
||||
vec3 diffuse_light = uAmbient;
|
||||
|
||||
float NL[4];
|
||||
float wrapped_NL[4];
|
||||
float spec_angle[4];
|
||||
float wrap[4];
|
||||
for (int i = 0; i < 4; i++) {
|
||||
vec3 L = normalize(uLightVec[i]);
|
||||
wrap[i] = uLightWrap[i];
|
||||
NL[i] = dot(L, N);
|
||||
wrapped_NL[i] = dot(L, -reflect(I, N));
|
||||
spec_angle[i] = clamp(dot(normalize(L + I), N), 0.0, 1.0);
|
||||
}
|
||||
|
||||
if (uUseSpecular > 0.5) {
|
||||
vec3 R = -reflect(I, N);
|
||||
for (int i = 0; i < 4; i++) {
|
||||
vec3 L = normalize(uLightVec[i]);
|
||||
float gloss = (1.0 - uRoughness) * (1.0 - wrap[i]);
|
||||
float shininess = exp2(10.0 * gloss + 1.0);
|
||||
float spec = blinn_specular(shininess, spec_angle[i], clamp(NL[i], 0.0, 1.0));
|
||||
float env_w = mix(wrap[i], 1.0, uRoughness);
|
||||
float spec_env = wrapped_lighting(dot(L, R), env_w);
|
||||
spec = mix(spec, spec_env, wrap[i] * wrap[i]);
|
||||
specular_light += spec * uLightSpecular[i];
|
||||
}
|
||||
float NV = clamp(dot(N, I), 0.0, 1.0);
|
||||
specular_color = brdf_approx(specular_color, uRoughness, NV);
|
||||
}
|
||||
specular_light *= specular_color;
|
||||
|
||||
for (int i = 0; i < 4; i++) {
|
||||
diffuse_light += wrapped_lighting(NL[i], wrap[i]) * uLightDiffuse[i];
|
||||
}
|
||||
|
||||
/* workbench_world_light_lib.glsl:126-131 — monochrome specular energy. */
|
||||
float spec_energy = dot(specular_color, vec3(0.33333));
|
||||
diffuse_light *= diffuse_color * (1.0 - spec_energy);
|
||||
|
||||
vec3 color = diffuse_light + specular_light;
|
||||
color = mix(color, uSelectionTint, uSelectionMix);
|
||||
|
||||
/* workbench_world_light_lib.glsl:145-151. Desktop adds a stencil shadow-volume
|
||||
* term through "force_shadow", which needs a shadow-volume pass; we port only
|
||||
* the analytic back-face term, so a self-shadowing silhouette still darkens
|
||||
* but cast shadows onto other objects are not reproduced. */
|
||||
if (uShowShadow > 0.5) {
|
||||
float light_factor = -dot(N, uShadowDirection);
|
||||
float shadow_mix = smoothstep(uShadowShift, uShadowFocus, light_factor);
|
||||
shadow_mix *= uShadowIntensity;
|
||||
color *= shadow_mix + (1.0 - uShadowIntensity);
|
||||
}
|
||||
|
||||
gl_FragColor = vec4(color, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export interface SolidStudioMaterialOptions {
|
||||
wireframe?: boolean;
|
||||
baseColor?: [number, number, number];
|
||||
roughness?: number;
|
||||
metallic?: number;
|
||||
selected?: boolean;
|
||||
rig?: StudioLightRig;
|
||||
side?: typeof DoubleSide;
|
||||
}
|
||||
|
||||
/**
|
||||
* Builds one uniform block per rig and caches it, so switching between the six
|
||||
* studio lights does not allocate new vectors on every shading change.
|
||||
*/
|
||||
const RIG_UNIFORM_CACHE = new Map<StudioLightRig, Record<string, { value: unknown }>>();
|
||||
|
||||
function rigUniforms(rig: StudioLightRig): Record<string, { value: unknown }> {
|
||||
const cached = RIG_UNIFORM_CACHE.get(rig);
|
||||
if (cached) return cached;
|
||||
const uniforms = {
|
||||
uAmbient: { value: new Vector3(...rig.ambient) },
|
||||
uLightVec: { value: rig.lights.map((light) => new Vector3(...light.vec)) },
|
||||
uLightDiffuse: { value: rig.lights.map((light) => new Vector3(...light.col)) },
|
||||
uLightSpecular: { value: rig.lights.map((light) => new Vector3(...light.spec)) },
|
||||
uLightWrap: { value: rig.lights.map((light) => light.smooth) },
|
||||
/* workbench_shadow.cc:444-476 uses the brightest light as the shadow
|
||||
* direction; `shadow_add = 1 - shadow_mul` keeps the brightening term
|
||||
* exactly compensating so an unshadowed pixel is unchanged. */
|
||||
uShadowDirection: { value: brightestLightDirection(rig) },
|
||||
};
|
||||
RIG_UNIFORM_CACHE.set(rig, uniforms);
|
||||
return uniforms;
|
||||
}
|
||||
|
||||
function brightestLightDirection(rig: StudioLightRig): Vector3 {
|
||||
let best = rig.lights[0];
|
||||
let bestEnergy = -1;
|
||||
for (const light of rig.lights) {
|
||||
const energy = (light.col[0] + light.col[1] + light.col[2]) / 3;
|
||||
if (energy > bestEnergy) { bestEnergy = energy; best = light; }
|
||||
}
|
||||
return new Vector3(...best.vec).normalize();
|
||||
}
|
||||
|
||||
/**
|
||||
* Standard ShaderMaterial (NOT RawShaderMaterial): three only injects the
|
||||
* `instanceMatrix` attribute and the `USE_INSTANCING` define for non-raw
|
||||
* materials, and the viewport uses InstancedMesh for coalesced geometry.
|
||||
*/
|
||||
export function createSolidStudioMaterial(options: SolidStudioMaterialOptions = {}): ShaderMaterial {
|
||||
const base = options.baseColor ?? SOLID_CLAY_COLOR;
|
||||
const rig = options.rig ?? DEFAULT_STUDIO_LIGHT;
|
||||
const material = new ShaderMaterial({
|
||||
vertexShader: VERTEX_SHADER,
|
||||
fragmentShader: FRAGMENT_SHADER,
|
||||
side: options.side ?? DoubleSide,
|
||||
wireframe: options.wireframe ?? false,
|
||||
/* Workbench output is already display-referred; letting the PBR renderer's
|
||||
* ACES/AgX pass run over it would crush the clay gradient. */
|
||||
toneMapped: false,
|
||||
uniforms: {
|
||||
uBaseColor: { value: new Vector3(...base) },
|
||||
uRoughness: { value: options.roughness ?? SOLID_CLAY_ROUGHNESS },
|
||||
uMetallic: { value: options.metallic ?? 0 },
|
||||
uUseSpecular: { value: 1 },
|
||||
uSelectionTint: { value: new Vector3(0.94, 0.54, 0.27) },
|
||||
uSelectionMix: { value: options.selected ? 0.35 : 0 },
|
||||
uShowShadow: { value: 0 },
|
||||
uShadowIntensity: { value: 0.5 },
|
||||
uShadowShift: { value: 0.1 },
|
||||
uShadowFocus: { value: 0 },
|
||||
...rigUniforms(rig),
|
||||
},
|
||||
});
|
||||
material.userData.solidStudio = true;
|
||||
material.userData.studioRig = rig;
|
||||
return material;
|
||||
}
|
||||
|
||||
export function setSolidStudioSelected(material: ShaderMaterial, selected: boolean): void {
|
||||
const uniform = material.uniforms.uSelectionMix;
|
||||
if (uniform) uniform.value = selected ? 0.35 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Applies the shadow-mask uniforms. Desktop derives them in
|
||||
* `workbench_shadow.cc:444-476`: the user-facing `shadow_focus` is inverted and
|
||||
* clamped before it reaches the shader, and `shadow_add` compensates the `mul`
|
||||
* so a fully lit pixel is bit-identical with shadows off.
|
||||
*/
|
||||
export function setSolidStudioShadow(
|
||||
material: ShaderMaterial,
|
||||
options: { enabled?: boolean; intensity?: number; shift?: number; focus?: number },
|
||||
): void {
|
||||
const enabled = options.enabled ?? false;
|
||||
const intensity = options.intensity ?? 0.5;
|
||||
const shift = options.shift ?? 0.1;
|
||||
const focus = Math.min(0.99999, Math.max(0.0001, options.focus ?? 0));
|
||||
const uniforms = material.uniforms;
|
||||
uniforms.uShowShadow.value = enabled ? 1 : 0;
|
||||
uniforms.uShadowIntensity.value = intensity;
|
||||
uniforms.uShadowShift.value = shift;
|
||||
uniforms.uShadowFocus.value = 1 - focus * (1 - shift);
|
||||
}
|
||||
|
||||
/** True when SOLID/WIREFRAME should replace the PBR material with the studio one. */
|
||||
export function usesStudioMaterial(mode: ViewportShadingMode): boolean {
|
||||
return mode === "SOLID" || mode === "WIREFRAME";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------------- */
|
||||
/* MATCAP */
|
||||
/* ------------------------------------------------------------------------- */
|
||||
|
||||
const MATCAP_FRAGMENT_SHADER = /* glsl */ `
|
||||
precision highp float;
|
||||
|
||||
varying vec3 vViewNormal;
|
||||
varying vec3 vViewPosition;
|
||||
|
||||
uniform sampler2D uDiffuse;
|
||||
uniform sampler2D uSpecular;
|
||||
uniform vec3 uBaseColor;
|
||||
uniform float uUseSpecular;
|
||||
uniform float uFlipX;
|
||||
uniform vec3 uSelectionTint;
|
||||
uniform float uSelectionMix;
|
||||
|
||||
/* workbench_matcap_lib.glsl:12-24 — the 0.496 inset is Blender's, not a typo;
|
||||
* it leaves a small margin so the rim of the sampled disk is never clamped. */
|
||||
vec2 matcap_uv_compute(vec3 I, vec3 N, bool flipped)
|
||||
{
|
||||
float a = 1.0 / (1.0 + I.z);
|
||||
float b = -I.x * I.y * a;
|
||||
vec3 b1 = vec3(1.0 - I.x * I.x * a, b, -I.x);
|
||||
vec3 b2 = vec3(b, 1.0 - I.y * I.y * a, -I.y);
|
||||
vec2 matcap_uv = vec2(dot(b1, N), dot(b2, N));
|
||||
if (flipped) matcap_uv.x = -matcap_uv.x;
|
||||
return matcap_uv * 0.496 + 0.5;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 N = normalize(vViewNormal);
|
||||
vec3 I = normalize(vViewPosition);
|
||||
if (!gl_FrontFacing) N = -N;
|
||||
|
||||
vec2 uv = matcap_uv_compute(I, N, uFlipX > 0.5);
|
||||
/* matcap_lib.glsl:38 — the two layers are ADDED, and only the diffuse layer
|
||||
* is tinted by the base colour. */
|
||||
vec3 diffuse = texture2D(uDiffuse, uv).rgb;
|
||||
vec3 specular = texture2D(uSpecular, uv).rgb;
|
||||
vec3 color = diffuse * uBaseColor + specular * uUseSpecular;
|
||||
|
||||
color = mix(color, uSelectionTint, uSelectionMix);
|
||||
gl_FragColor = vec4(color, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
export interface MatcapTextures {
|
||||
diffuse: import("../vendor/three/three.module.js").Texture;
|
||||
specular: import("../vendor/three/three.module.js").Texture | null;
|
||||
}
|
||||
|
||||
/** Alias so callers can name the decoded pair without importing the loader. */
|
||||
export type MatcapTextureSet = MatcapTextures;
|
||||
|
||||
export interface MatcapMaterialOptions extends MatcapTextures {
|
||||
baseColor?: [number, number, number];
|
||||
/** V3D_SHADING_MATCAP_FLIP_X — negates u only. */
|
||||
flipX?: boolean;
|
||||
selected?: boolean;
|
||||
}
|
||||
|
||||
/**
|
||||
* MATCAP shading (`V3D_LIGHTING_MATCAP`). The workbench samples a 2-layer
|
||||
* texture array; we bind the same two layers as separate 2D textures, which is
|
||||
* the legacy overload in `workbench_matcap_lib.glsl:27-38`.
|
||||
*/
|
||||
export function createMatcapMaterial(options: MatcapMaterialOptions): ShaderMaterial {
|
||||
const base = options.baseColor ?? SOLID_CLAY_COLOR;
|
||||
const material = new ShaderMaterial({
|
||||
vertexShader: VERTEX_SHADER,
|
||||
fragmentShader: MATCAP_FRAGMENT_SHADER,
|
||||
side: DoubleSide,
|
||||
toneMapped: false,
|
||||
uniforms: {
|
||||
uDiffuse: { value: options.diffuse },
|
||||
uSpecular: { value: options.specular ?? options.diffuse },
|
||||
uBaseColor: { value: new Vector3(...base) },
|
||||
/* workbench_resources.cc:161-166: only a matcap with a specular pass and
|
||||
* V3D_SHADING_SPECULAR_HIGHLIGHT both set contribute a specular layer. */
|
||||
uUseSpecular: { value: options.specular ? 1 : 0 },
|
||||
uFlipX: { value: options.flipX ? 1 : 0 },
|
||||
uSelectionTint: { value: new Vector3(0.94, 0.54, 0.27) },
|
||||
uSelectionMix: { value: options.selected ? 0.35 : 0 },
|
||||
},
|
||||
});
|
||||
material.userData.solidStudio = true;
|
||||
material.userData.matcap = true;
|
||||
return material;
|
||||
}
|
||||
|
||||
export function setMatcapBaseColor(material: ShaderMaterial, baseColor: [number, number, number]): void {
|
||||
material.uniforms.uBaseColor.value.set(...baseColor);
|
||||
}
|
||||
|
||||
/**
|
||||
* Swaps every mesh under `root` between the PBR material and the studio clay
|
||||
* material. Shared by the main-thread renderer and the offscreen worker so the
|
||||
* two paths cannot drift; the original material is cached on the object.
|
||||
*/
|
||||
/** Solid-shading options shared by the renderer and the worker. */
|
||||
export interface SolidShadingOptions {
|
||||
/** V3D_LIGHTING_STUDIO vs V3D_LIGHTING_MATCAP. */
|
||||
lightMode?: "STUDIO" | "MATCAP";
|
||||
/** Studio light rig; ignored when `lightMode` is MATCAP. */
|
||||
rig?: StudioLightRig;
|
||||
/** Decoded matcap layers; required when `lightMode` is MATCAP. */
|
||||
matcap?: MatcapTextureSet | null;
|
||||
matcapFlipX?: boolean;
|
||||
/** `View3DShading.use_scene_world`: Material Preview lights from the world. */
|
||||
useSceneWorld?: boolean;
|
||||
shadow?: { enabled?: boolean; intensity?: number; shift?: number; focus?: number };
|
||||
/** Screen-space cavity + curvature. `WORLD` needs a bake, so it is absent. */
|
||||
cavity?: {
|
||||
enabled?: boolean;
|
||||
type?: "BOTH" | "SCREEN" | "WORLD";
|
||||
curvature?: boolean;
|
||||
distance?: number;
|
||||
attenuation?: number;
|
||||
samples?: number;
|
||||
valley?: number;
|
||||
ridge?: number;
|
||||
curvatureRidge?: number;
|
||||
curvatureValley?: number;
|
||||
};
|
||||
}
|
||||
|
||||
export function applyStudioShading(
|
||||
root: import("../vendor/three/three.module.js").Object3D,
|
||||
mode: ViewportShadingMode,
|
||||
xray: boolean,
|
||||
selectedIds: ReadonlySet<string> = new Set(),
|
||||
options: SolidShadingOptions = {},
|
||||
): void {
|
||||
const studio = usesStudioMaterial(mode);
|
||||
const wireframe = mode === "WIREFRAME";
|
||||
const lightMode = options.lightMode ?? "STUDIO";
|
||||
/* A matcap needs its texture before it can be built; until it arrives the
|
||||
* studio rig keeps the object shaded instead of leaving it unlit. */
|
||||
const matcap = lightMode === "MATCAP" && !wireframe ? options.matcap ?? null : null;
|
||||
|
||||
root.traverse((object) => {
|
||||
if (!(object as import("../vendor/three/three.module.js").Mesh).isMesh) return;
|
||||
const mesh = object as import("../vendor/three/three.module.js").Mesh;
|
||||
if (mesh.userData.nanoVDBVolume) return;
|
||||
|
||||
if (studio) {
|
||||
if (!mesh.userData.pbrMaterial) {
|
||||
mesh.userData.pbrMaterial = mesh.material;
|
||||
mesh.userData.pbrMaterialArray = Array.isArray(mesh.material);
|
||||
}
|
||||
const selected = typeof mesh.userData.blenderId === "string" && selectedIds.has(mesh.userData.blenderId as string);
|
||||
if (matcap) {
|
||||
const existing = mesh.userData.matcapMaterial as ShaderMaterial | undefined;
|
||||
const material = existing && existing.userData.matcapKey === matcapKey(matcap)
|
||||
? existing
|
||||
: createMatcapMaterial({ ...matcap, flipX: options.matcapFlipX, selected });
|
||||
material.userData.matcapKey = matcapKey(matcap);
|
||||
setSolidStudioSelected(material, selected);
|
||||
mesh.userData.matcapMaterial = material;
|
||||
mesh.material = material;
|
||||
}
|
||||
else {
|
||||
const correctRig = options.rig && options.rig !== mesh.userData.solidStudioRig;
|
||||
const clay = (correctRig ? undefined : mesh.userData.solidStudioMaterial as ShaderMaterial | undefined)
|
||||
?? createSolidStudioMaterial({ wireframe, selected, rig: options.rig });
|
||||
clay.wireframe = wireframe;
|
||||
setSolidStudioSelected(clay, selected);
|
||||
if (options.shadow) setSolidStudioShadow(clay, options.shadow);
|
||||
mesh.userData.solidStudioRig = options.rig ?? DEFAULT_STUDIO_LIGHT;
|
||||
mesh.userData.solidStudioMaterial = clay;
|
||||
mesh.material = clay;
|
||||
}
|
||||
}
|
||||
else {
|
||||
const original = mesh.userData.pbrMaterial as import("../vendor/three/three.module.js").Material | import("../vendor/three/three.module.js").Material[] | undefined;
|
||||
if (original) mesh.material = original;
|
||||
}
|
||||
mesh.castShadow = !wireframe && !xray;
|
||||
});
|
||||
}
|
||||
|
||||
/** Identity for "these two layers are the same matcap", so a swap can reuse the
|
||||
* material instead of recompiling a shader on every selection change. */
|
||||
function matcapKey(matcap: MatcapTextureSet): string {
|
||||
return `${matcap.diffuse.uuid}:${matcap.specular?.uuid ?? "none"}`;
|
||||
}
|
||||
|
||||
/** Placeholder so callers can convert an authored sRGB hex to linear once. */
|
||||
export function srgbHexToLinear(hex: number): [number, number, number] {
|
||||
const color = new Color().setHex(hex);
|
||||
return [color.r, color.g, color.b];
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import {
|
||||
DataTexture,
|
||||
EquirectangularReflectionMapping,
|
||||
NoColorSpace,
|
||||
PMREMGenerator,
|
||||
@@ -272,7 +273,10 @@ export class GPUTextureStore {
|
||||
}
|
||||
|
||||
async applyEnvironment(scene: Scene, renderer: WebGLRenderer, world: WorldIR | undefined, background = true): Promise<boolean> {
|
||||
if (!world?.environmentImageId) return false;
|
||||
if (!world) return false;
|
||||
/* Desktop EEVEE lights from the World colour even without an environment
|
||||
* image (the Background shader evaluates to that colour). */
|
||||
if (!world.environmentImageId) return this.applyColorEnvironment(scene, renderer, world);
|
||||
const source = this.get(world.environmentImageId, "ENVIRONMENT");
|
||||
if (!source) return false;
|
||||
source.mapping = EquirectangularReflectionMapping;
|
||||
@@ -297,8 +301,44 @@ export class GPUTextureStore {
|
||||
scene.environment = source;
|
||||
}
|
||||
scene.environmentIntensity = Math.max(0, world.environmentStrength ?? 1);
|
||||
/* Desktop rotates the World with a Mapping node, so lighting *and* the
|
||||
* camera-view background rotate together (EEVEE samples the same map). */
|
||||
scene.environmentRotation.set(0, world.environmentRotation ?? 0, 0);
|
||||
scene.backgroundRotation.set(0, world.environmentRotation ?? 0, 0);
|
||||
scene.backgroundIntensity = Math.max(0, world.environmentStrength ?? 1);
|
||||
if (background && (world.backgroundVisible ?? true)) scene.background = source;
|
||||
scene.userData.pbrColorKey = null;
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Uniform World colour as a prefiltered environment. Cached per colour so
|
||||
* repeated snapshots do not rebuild the PMREM chain. */
|
||||
private applyColorEnvironment(scene: Scene, renderer: WebGLRenderer, world: WorldIR): boolean {
|
||||
const [r, g, b] = world.color;
|
||||
const key = `${r},${g},${b}`;
|
||||
if (scene.userData.pbrColorKey !== key || !scene.environment) {
|
||||
const width = 4, height = 2, data = new Uint8Array(width * height * 4);
|
||||
for (let index = 0; index < data.length; index += 4) {
|
||||
data[index] = Math.round(Math.max(0, Math.min(1, r)) * 255);
|
||||
data[index + 1] = Math.round(Math.max(0, Math.min(1, g)) * 255);
|
||||
data[index + 2] = Math.round(Math.max(0, Math.min(1, b)) * 255);
|
||||
data[index + 3] = 255;
|
||||
}
|
||||
const equirect = new DataTexture(data, width, height);
|
||||
equirect.mapping = EquirectangularReflectionMapping;
|
||||
equirect.needsUpdate = true;
|
||||
const pmrem = new PMREMGenerator(renderer);
|
||||
const target = pmrem.fromEquirectangular(equirect);
|
||||
pmrem.dispose();
|
||||
equirect.dispose();
|
||||
const oldTarget = scene.userData.pbrIBLTarget as { dispose?: () => void } | undefined;
|
||||
oldTarget?.dispose?.();
|
||||
scene.userData.pbrIBLTarget = target;
|
||||
scene.userData.pbrColorKey = key;
|
||||
scene.environment = target.texture;
|
||||
}
|
||||
scene.environmentIntensity = Math.max(0, world.environmentStrength ?? 1);
|
||||
scene.environmentRotation.set(0, world.environmentRotation ?? 0, 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
@@ -32,6 +32,8 @@ export class ViewportNavigation {
|
||||
private navigationVersion=0;
|
||||
private ndofPending:NDOFViewportEvent|null=null;
|
||||
private ndofProcessing=false;
|
||||
/* Navigation sensitivity comes from web preferences; 1 keeps desktop defaults. */
|
||||
private navPrefs:{orbitSensitivity:number;zoomSensitivity:number;invertZoom:boolean}={orbitSensitivity:1,zoomSensitivity:1,invertZoom:false};
|
||||
constructor(private readonly canvas:HTMLCanvasElement,private readonly changed:(state:ViewportNavigationCamera)=>void){
|
||||
const [x,y,z]=orbitPosition(VIEWPORT_DEFAULT_ORBIT);this.camera.position.set(x,z,-y);
|
||||
canvas.tabIndex=0;
|
||||
@@ -52,7 +54,7 @@ export class ViewportNavigation {
|
||||
const distance=this.camera.position.distanceTo(target);
|
||||
controls.minDistance=Math.min(VIEWPORT_ORBIT_MIN_DISTANCE,distance);controls.maxDistance=Math.max(VIEWPORT_ORBIT_MAX_DISTANCE,distance);
|
||||
controls.minZoom=.0001;controls.maxZoom=1e5;
|
||||
controls.zoomSpeed=VIEWPORT_ORBIT_ZOOM_SENSITIVITY/(.01*-Math.log(.95));
|
||||
controls.zoomSpeed=VIEWPORT_ORBIT_ZOOM_SENSITIVITY*this.navPrefs.zoomSensitivity/(.01*-Math.log(.95));
|
||||
controls.addEventListener('change',this.onChange);
|
||||
controls.update();return controls;
|
||||
}
|
||||
@@ -81,6 +83,14 @@ export class ViewportNavigation {
|
||||
if(frame&&this.cameraView&&!this.gesture&&!this.cameraLock)this.applyCameraFrame(frame);
|
||||
}
|
||||
setCameraWriteHandler(handler:((frame:BlenderViewportCamera & {objectId:string})=>void)|null):void{this.cameraWriteHandler=handler;}
|
||||
/** Applies navigation sensitivity preferences and rescales the live controls. */
|
||||
setNavigationPrefs(prefs:Partial<{orbitSensitivity:number;zoomSensitivity:number;invertZoom:boolean}>):void{
|
||||
const next={orbitSensitivity:prefs.orbitSensitivity??this.navPrefs.orbitSensitivity,zoomSensitivity:prefs.zoomSensitivity??this.navPrefs.zoomSensitivity,invertZoom:prefs.invertZoom??this.navPrefs.invertZoom};
|
||||
if(next.orbitSensitivity===this.navPrefs.orbitSensitivity&&next.zoomSensitivity===this.navPrefs.zoomSensitivity&&next.invertZoom===this.navPrefs.invertZoom)return;
|
||||
this.navPrefs=next;
|
||||
if(this.controls){this.controls.zoomSpeed=VIEWPORT_ORBIT_ZOOM_SENSITIVITY*next.zoomSensitivity/(.01*-Math.log(.95));}
|
||||
this.resize();
|
||||
}
|
||||
isCameraView():boolean{return this.cameraView;}
|
||||
isCameraLocked():boolean{return this.cameraLock;}
|
||||
getCameraFraming():{dx:number;dy:number;camzoom:number}{return {dx:this.cameraFraming.dx,dy:this.cameraFraming.dy,camzoom:this.cameraFraming.camzoom};}
|
||||
@@ -149,10 +159,12 @@ export class ViewportNavigation {
|
||||
if(!this.cameraView)return;
|
||||
if(this.cameraLock)return;
|
||||
event.preventDefault();
|
||||
const delta=Math.exp(event.deltaY*0.001);
|
||||
/* Invert Zoom swaps the wheel direction, mirroring USER_WHEELZOOMDIR. */
|
||||
const wheel=this.navPrefs.invertZoom?-event.deltaY:event.deltaY;
|
||||
const delta=Math.exp(wheel*0.001*this.navPrefs.zoomSensitivity);
|
||||
this.camera.zoom=Math.max(.05,Math.min(20,this.camera.zoom/delta));
|
||||
this.camera.updateProjectionMatrix();
|
||||
this.cameraFraming.camzoom=Math.max(-30,Math.min(600,this.cameraFraming.camzoom-event.deltaY*0.02));
|
||||
this.cameraFraming.camzoom=Math.max(-30,Math.min(600,this.cameraFraming.camzoom-wheel*0.02));
|
||||
this.controls.update();this.publish();
|
||||
};
|
||||
private enter=()=>{this.hover=true;};
|
||||
@@ -268,7 +280,7 @@ export class ViewportNavigation {
|
||||
const width=Math.max(1,this.canvas.clientWidth),height=Math.max(1,this.canvas.clientHeight),aspect=width/height;
|
||||
if(this.camera instanceof PerspectiveCamera)this.camera.aspect=aspect;
|
||||
else{this.camera.left=-this.orthoHeight*aspect/2;this.camera.right=this.orthoHeight*aspect/2;this.camera.top=this.orthoHeight/2;this.camera.bottom=-this.orthoHeight/2;}
|
||||
this.camera.updateProjectionMatrix();if(this.controls)this.controls.rotateSpeed=VIEWPORT_ORBIT_ROTATE_SENSITIVITY*height/(2*Math.PI);this.publish();
|
||||
this.camera.updateProjectionMatrix();if(this.controls)this.controls.rotateSpeed=VIEWPORT_ORBIT_ROTATE_SENSITIVITY*this.navPrefs.orbitSensitivity*height/(2*Math.PI);this.publish();
|
||||
}
|
||||
publish():void{
|
||||
if(this.disposed||!this.controls)return;this.navigationVersion++;this.camera.updateMatrixWorld(true);
|
||||
|
||||
85
web/app/src/three-adapter/viewport-surface-math.ts
Normal file
85
web/app/src/three-adapter/viewport-surface-math.ts
Normal file
@@ -0,0 +1,85 @@
|
||||
import { Matrix3, Vector3, type Camera, type Object3D, type Raycaster } from "../vendor/three/three.module.js";
|
||||
|
||||
/**
|
||||
* Surface pick and brush-cursor projection, shared by the main-thread renderer
|
||||
* and the offscreen worker.
|
||||
*
|
||||
* Sculpting needs a real surface intersection: a screen-space fallback would
|
||||
* sculpt an invisible plane in front of the camera. The ring radius comes from
|
||||
* projecting two points on the brush tangent plane and taking their pixel
|
||||
* distance — the same trick as
|
||||
* `blender-5.2.0/source/blender/editors/sculpt_paint/mesh/paint_cursor.cc:47-91`
|
||||
* (`brush_radius_project`), which keeps the ring correct at any camera distance
|
||||
* instead of converting through a fixed pixel/world scale.
|
||||
*/
|
||||
|
||||
export interface SurfacePick {
|
||||
position: [number, number, number];
|
||||
normal: [number, number, number];
|
||||
objectId: string;
|
||||
distance: number;
|
||||
}
|
||||
|
||||
export interface BrushCursorRing {
|
||||
center: [number, number];
|
||||
screenRadius: number;
|
||||
}
|
||||
|
||||
/** `x`,`y` are normalised device coordinates, as `raycaster.setFromCamera` wants. */
|
||||
export function pickSurface(raycaster: Raycaster, camera: Camera, root: Object3D, x: number, y: number): SurfacePick | null {
|
||||
raycaster.setFromCamera({ x, y } as never, camera);
|
||||
const hits = raycaster.intersectObjects(root.children, true)
|
||||
.filter((hit) => typeof hit.object.userData.blenderId === "string" && hit.point);
|
||||
const hit = hits[0];
|
||||
if (!hit) return null;
|
||||
const normalMatrix = new Matrix3().getNormalMatrix(hit.object.matrixWorld);
|
||||
const normal = hit.face ? hit.face.normal.clone().applyMatrix3(normalMatrix).normalize() : new Vector3(0, 0, 1);
|
||||
/* An InstancedMesh hit reports the instance in `instanceId`; the per-instance
|
||||
* node id wins over the object-level one so sculpting targets the right copy. */
|
||||
const instanceIds = hit.object.userData.instanceNodeIds as string[] | undefined;
|
||||
const objectId = instanceIds && typeof hit.instanceId === "number"
|
||||
? instanceIds[hit.instanceId]
|
||||
: String(hit.object.userData.blenderId);
|
||||
return {
|
||||
position: [hit.point.x, hit.point.y, hit.point.z],
|
||||
normal: [normal.x, normal.y, normal.z],
|
||||
objectId,
|
||||
distance: hit.distance,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Projects the brush ring. `cssWidth`/`cssHeight` are the viewport's CSS pixel
|
||||
* size; the caller already converted the pointer to NDC.
|
||||
*/
|
||||
export function projectBrushRing(
|
||||
raycaster: Raycaster,
|
||||
camera: Camera,
|
||||
root: Object3D,
|
||||
x: number,
|
||||
y: number,
|
||||
radius: number,
|
||||
cssWidth: number,
|
||||
cssHeight: number,
|
||||
): BrushCursorRing | null {
|
||||
if (cssWidth <= 0 || cssHeight <= 0) return null;
|
||||
const hit = pickSurface(raycaster, camera, root, x, y);
|
||||
if (!hit) return null;
|
||||
const point = new Vector3(...hit.position);
|
||||
const normal = new Vector3(...hit.normal).normalize();
|
||||
const view = point.clone().sub(camera.position).normalize();
|
||||
const tangent = new Vector3().crossVectors(normal, view);
|
||||
if (tangent.lengthSq() < 1e-8) tangent.set(1, 0, 0); else tangent.normalize();
|
||||
const offset = point.clone().addScaledVector(tangent, radius);
|
||||
const project = (world: Vector3): [number, number] | null => {
|
||||
const ndc = world.clone().project(camera);
|
||||
if (!Number.isFinite(ndc.x) || !Number.isFinite(ndc.y)) return null;
|
||||
return [(ndc.x + 1) / 2 * cssWidth, (1 - ndc.y) / 2 * cssHeight];
|
||||
};
|
||||
const center = project(point);
|
||||
const edge = project(offset);
|
||||
if (!center || !edge) return null;
|
||||
const screenRadius = Math.hypot(edge[0] - center[0], edge[1] - center[1]);
|
||||
if (!Number.isFinite(screenRadius) || screenRadius <= 0) return null;
|
||||
return { center, screenRadius };
|
||||
}
|
||||
30
web/app/src/three-adapter/viewport-surface-pick.ts
Normal file
30
web/app/src/three-adapter/viewport-surface-pick.ts
Normal file
@@ -0,0 +1,30 @@
|
||||
/**
|
||||
* Screen-space surface picking for callers outside the viewport component.
|
||||
*
|
||||
* Sculpt strokes are created by the Properties panel, which owns no renderer
|
||||
* reference; desktop sculpting still projects the cursor onto the mesh, so the
|
||||
* stroke needs the active viewport's raycast rather than a screen-space plane.
|
||||
*/
|
||||
|
||||
export interface SurfacePickResult {
|
||||
position: [number, number, number];
|
||||
normal: [number, number, number];
|
||||
objectId: string;
|
||||
distance: number;
|
||||
}
|
||||
|
||||
/** The offscreen backend resolves picks through its worker, so a picker may
|
||||
* answer with a promise. Callers that need the point must await it. */
|
||||
type SurfacePicker = (clientX: number, clientY: number) => SurfacePickResult | null | Promise<SurfacePickResult | null>;
|
||||
|
||||
let activePicker: SurfacePicker | null = null;
|
||||
|
||||
/** Registers the current viewport's picker; returns the unregister callback. */
|
||||
export function registerSurfacePicker(picker: SurfacePicker): () => void {
|
||||
activePicker = picker;
|
||||
return () => { if (activePicker === picker) activePicker = null; };
|
||||
}
|
||||
|
||||
export async function pickViewportSurface(clientX: number, clientY: number): Promise<SurfacePickResult | null> {
|
||||
return activePicker ? await activePicker(clientX, clientY) : null;
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import {
|
||||
InstancedMesh,
|
||||
LineBasicMaterial,
|
||||
LineSegments,
|
||||
Matrix3,
|
||||
Matrix4,
|
||||
Mesh,
|
||||
MeshBasicMaterial,
|
||||
@@ -22,7 +23,19 @@ import {
|
||||
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";
|
||||
@@ -86,6 +99,8 @@ export function collectMeshInstanceGroups(snapshot: SceneSnapshotIR, minimumSize
|
||||
}
|
||||
|
||||
/** 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;
|
||||
@@ -96,6 +111,39 @@ export class ViewportRenderer {
|
||||
setCameraWriteHandler(handler:Parameters<ViewportNavigation['setCameraWriteHandler']>[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<ViewportNavigation['setNavigationPrefs']>[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();}
|
||||
@@ -128,6 +176,22 @@ export class ViewportRenderer {
|
||||
private volumeAssets: NanoVDBViewportAssetIR[] = [];
|
||||
private readonly volumeRenderCache = new Map<string, NanoVDBViewportRenderResultIR>();
|
||||
private volumeRenderGeneration = 0;
|
||||
private shadingMode: ViewportShadingMode = 'MATERIAL';
|
||||
private xray = false;
|
||||
private selectedObjectIds: ReadonlySet<string> = 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<void> | 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(
|
||||
@@ -170,7 +234,16 @@ export class ViewportRenderer {
|
||||
keyLight.shadow.bias = -0.0005;
|
||||
keyLight.shadow.normalBias = 0.03;
|
||||
this.scene.add(keyLight, keyLight.target);
|
||||
this.scene.add(new GridHelper(20, 20, 0x60656e, 0x383b42));
|
||||
/* 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);
|
||||
|
||||
@@ -230,6 +303,11 @@ export class ViewportRenderer {
|
||||
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;
|
||||
@@ -313,6 +391,7 @@ export class ViewportRenderer {
|
||||
this.coalesceMeshInstances(snapshot);
|
||||
this.populateObjectHelpers(snapshot);
|
||||
this.populateCollectionInstances(snapshot);
|
||||
this.applyShadingMode();
|
||||
void this.refreshVolumes();
|
||||
}
|
||||
|
||||
@@ -394,11 +473,9 @@ export class ViewportRenderer {
|
||||
this.canvas.dataset.textureBudgetGpuBytes = String(status.budget.decodedGPUBytes);
|
||||
if (!this.currentSnapshot) return;
|
||||
this.textureStore.applySnapshotMaterials(this.importedRoot, this.currentSnapshot);
|
||||
const worldId = this.currentSnapshot.scenes[0]?.worldId;
|
||||
const world = this.currentSnapshot.worlds.find((candidate) => candidate.id === worldId) ?? this.currentSnapshot.worlds[0];
|
||||
void this.textureStore.applyEnvironment(this.scene, this.renderer, world, true).then((ready) => {
|
||||
this.canvas.dataset.iblStatus = ready ? "ready" : world?.environmentImageId ? "blocked" : "none";
|
||||
});
|
||||
/* 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();
|
||||
});
|
||||
}
|
||||
|
||||
@@ -502,6 +579,7 @@ export class ViewportRenderer {
|
||||
greasePencilSelectionRevision = 0,
|
||||
): void {
|
||||
this.requestRender();
|
||||
this.selectedObjectIds = objectIds;
|
||||
this.navigation.setSelection(objectIds);
|
||||
const visitedInstances = new Set<InstancedMesh>();
|
||||
for (const [objectId, object] of this.objectByBlenderId) {
|
||||
@@ -944,11 +1022,135 @@ export class ViewportRenderer {
|
||||
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<void> {
|
||||
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];
|
||||
this.scene.background = world ? new Color().setRGB(...world.color) : new Color("#25272b");
|
||||
/* 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,
|
||||
@@ -1138,7 +1340,33 @@ export class ViewportRenderer {
|
||||
if (this.renderRequested) {
|
||||
this.renderRequested = false;
|
||||
this.lodAdapter.update(this.camera, Math.max(1, this.canvas.clientHeight));
|
||||
this.renderer.render(this.scene, this.camera);
|
||||
/* 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";
|
||||
@@ -1209,6 +1437,7 @@ export class ViewportRenderer {
|
||||
this.volumeRenderGeneration++;
|
||||
this.volumeRenderCache.clear();
|
||||
this.volumeRenderSession.dispose();
|
||||
this.workbenchPost.dispose();
|
||||
this.textureStore.dispose();
|
||||
this.renderer.dispose();
|
||||
}
|
||||
|
||||
578
web/app/src/three-adapter/workbench-post.ts
Normal file
578
web/app/src/three-adapter/workbench-post.ts
Normal file
@@ -0,0 +1,578 @@
|
||||
import {
|
||||
Color,
|
||||
DataTexture,
|
||||
DepthTexture,
|
||||
DoubleSide,
|
||||
FloatType,
|
||||
HalfFloatType,
|
||||
LinearFilter,
|
||||
LinearSRGBColorSpace,
|
||||
Mesh,
|
||||
MeshNormalMaterial,
|
||||
NoToneMapping,
|
||||
OrthographicCamera,
|
||||
PlaneGeometry,
|
||||
RGBAFormat,
|
||||
RepeatWrapping,
|
||||
Scene,
|
||||
ShaderMaterial,
|
||||
UnsignedByteType,
|
||||
UnsignedIntType,
|
||||
DepthFormat,
|
||||
Vector2,
|
||||
WebGLRenderTarget,
|
||||
type Camera,
|
||||
type Object3D,
|
||||
type WebGLRenderer,
|
||||
} from "../vendor/three/three.module.js";
|
||||
|
||||
/**
|
||||
* Workbench "cavity" and "curvature" screen-space passes.
|
||||
*
|
||||
* Ported from
|
||||
* `/home/mes123456/workinf_Blender_Wasm/blender-5.2.0/source/blender/draw/engines/workbench/shaders/workbench_cavity.bsl.hh`
|
||||
* and `.../workbench_curvature.bsl.hh`, composited exactly as
|
||||
* `.../workbench_composite.bsl.hh:95-104`:
|
||||
*
|
||||
* color.rgb *= clamp((1 - cavity) * (1 + edges) * (1 + curvature), 0, 4)
|
||||
*
|
||||
* Differences from desktop, both forced by the WebGL path and recorded as
|
||||
* limitations rather than silently approximated:
|
||||
*
|
||||
* * Desktop runs a normal+object-id *prepass*. The normal half is mirrored here
|
||||
* with a `MeshNormalMaterial` override pass written to a half-float target
|
||||
* (`workbench_mesh_passes.cc:149,179`); the object-id half is not available,
|
||||
* so the outline test is replaced by a depth discontinuity test. Both suppress
|
||||
* the same artifact (curvature firing on object borders) but are not identical.
|
||||
* Reconstructing the normal from the depth buffer instead, as an earlier
|
||||
* revision did, is not usable: window depth is uniform over [0, 1], so near
|
||||
* 1.0 it resolves only ~2^-24 of the range, and differencing it twice amplifies
|
||||
* that into |normal_diff| ~ 0.016 on a flat face — visible dither.
|
||||
* * Desktop uses a precomputed 64x64 blue-noise texture. We synthesise the same
|
||||
* size from a deterministic hash: the jitter is white noise, so the dither
|
||||
* pattern differs while the estimator is unchanged.
|
||||
*/
|
||||
|
||||
export interface WorkbenchCavityOptions {
|
||||
/** `V3D_SHADING_CAVITY` — the master flag; `type` only picks the effects. */
|
||||
enabled?: boolean;
|
||||
/**
|
||||
* `View3DShading.cavity_type`, DNA names in brackets:
|
||||
* `WORLD` [V3D_SHADING_CAVITY_SSAO], `SCREEN` [V3D_SHADING_CAVITY_CURVATURE],
|
||||
* `BOTH`. `workbench_state.cc:244-248` turns this into the two draw flags.
|
||||
*/
|
||||
type?: "BOTH" | "SCREEN" | "WORLD";
|
||||
/** Extra curvature gate on top of `type`; desktop has no such switch. */
|
||||
curvature?: boolean;
|
||||
/** `scene.display.matcap_ssao_distance`, DNA default 0.2. */
|
||||
distance?: number;
|
||||
/** `scene.display.matcap_ssao_attenuation`, DNA default 1.0. */
|
||||
attenuation?: number;
|
||||
/** `scene.display.matcap_ssao_samples`, DNA default 16. */
|
||||
samples?: number;
|
||||
/** `View3DShading.cavity_valley_factor`, DNA default 1.0. */
|
||||
valley?: number;
|
||||
/** `View3DShading.cavity_ridge_factor`, DNA default 1.0. */
|
||||
ridge?: number;
|
||||
/** `View3DShading.curvature_ridge_factor`, DNA default 1.0. */
|
||||
curvatureRidge?: number;
|
||||
/** `View3DShading.curvature_valley_factor`, DNA default 1.0. */
|
||||
curvatureValley?: number;
|
||||
/** One UI unit in device pixels (`world_data.ui_scale`); desktop uses 1. */
|
||||
uiScale?: number;
|
||||
}
|
||||
|
||||
const MAX_SAMPLES = 512;
|
||||
/* `CavityEffect::init`: `sample_count = min(samples_len * ssao_samples, 512)`
|
||||
* with DNA defaults `viewport_aa = 8` (`DNA_userdef_types.h:1246`) and
|
||||
* `matcap_ssao_samples = 16` (`DNA_scene_types.h:2558`), so desktop distributes
|
||||
* 128 taps and runs 16 of them per frame, letting TAA accumulate the rest over
|
||||
* 8 frames. There is no TAA here, so one frame runs the whole set: with the same
|
||||
* per-pixel rotation, averaging desktop's 8 frames of 16 is algebraically the
|
||||
* same as one pass over all 128, normalised by 1/128.
|
||||
*
|
||||
* `SSAO_SAMPLES` stays the per-iteration count, because `load_samples_buf` uses
|
||||
* it for the radius step (`i / ssao_samples`) and `load_jitter_tx` scales the
|
||||
* jitter offset by the total. Both are iteration-shaped, not total-shaped. */
|
||||
const SSAO_SAMPLES = 16;
|
||||
const USED_SAMPLES = 128;
|
||||
const NOISE_SIZE = 64;
|
||||
|
||||
/** `BLI_hammersley_1d` — radical inverse in base 2. */
|
||||
function hammersley1d(index: number): number {
|
||||
let bits = index >>> 0;
|
||||
bits = ((bits << 16) | (bits >>> 16)) >>> 0;
|
||||
bits = (((bits & 0x55555555) << 1) | ((bits & 0xaaaaaaaa) >>> 1)) >>> 0;
|
||||
bits = (((bits & 0x33333333) << 2) | ((bits & 0xcccccccc) >>> 2)) >>> 0;
|
||||
bits = (((bits & 0x0f0f0f0f) << 4) | ((bits & 0xf0f0f0f0) >>> 4)) >>> 0;
|
||||
bits = (((bits & 0x00ff00ff) << 8) | ((bits & 0xff00ff00) >>> 8)) >>> 0;
|
||||
return bits * 2.3283064365386963e-10;
|
||||
}
|
||||
|
||||
/**
|
||||
* `CavityEffect::load_samples_buf` — the disk deliberately packs more samples
|
||||
* near the centre, which is what gives the shadowed creases their falloff.
|
||||
*/
|
||||
function cavitySamples(ssaoSamples: number): Float32Array {
|
||||
const data = new Float32Array(USED_SAMPLES * 3);
|
||||
const iterationSamplesInv = 1 / ssaoSamples;
|
||||
for (let index = 0; index < USED_SAMPLES; index += 1) {
|
||||
const itAdd = (index / ssaoSamples) * 0.499;
|
||||
const radius = ((index + 0.5 + itAdd) * iterationSamplesInv) % 1;
|
||||
const phi = hammersley1d(index) * 2 * Math.PI + itAdd;
|
||||
data[index * 3] = Math.cos(phi);
|
||||
data[index * 3 + 1] = Math.sin(phi);
|
||||
data[index * 3 + 2] = radius;
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stand-in for the precomputed blue-noise tile (`workbench_resources.cc:83-108`).
|
||||
* The pattern is white noise rather than blue, but the channel *semantics* have
|
||||
* to match or the sample disk is destroyed:
|
||||
*
|
||||
* `.rg` is `(cos phi, sin phi)`, a unit vector. The shader builds the second
|
||||
* axis as `(-r.y, r.x)` and relies on the two being orthonormal; two
|
||||
* independent random bytes would scale and shear the disk per pixel.
|
||||
*
|
||||
* `.b` is a tiny radius offset, `clamp(bn, -0.499, 0.499) / total_samples`,
|
||||
* i.e. +-0.031 at 16 samples. The shader adds it to the sample radius, so a
|
||||
* random byte in [0, 1] would double the radius at random.
|
||||
*
|
||||
* The desktop tile is `SFLOAT_16_16_16_16` for the same reason: bytes cannot
|
||||
* represent the signed offset.
|
||||
*/
|
||||
function noiseTexture(totalSamples: number): DataTexture {
|
||||
const pixels = new Float32Array(NOISE_SIZE * NOISE_SIZE * 4);
|
||||
const inv = 1 / totalSamples;
|
||||
let state = 0x9e3779b9;
|
||||
const next = (): number => {
|
||||
state ^= state << 13; state >>>= 0;
|
||||
state ^= state >>> 17;
|
||||
state ^= state << 5; state >>>= 0;
|
||||
return state / 4294967296;
|
||||
};
|
||||
for (let index = 0; index < NOISE_SIZE * NOISE_SIZE; index += 1) {
|
||||
const phi = next() * 2 * Math.PI;
|
||||
/* Mirrors the firefly clamp: the offset stays strictly inside the step. */
|
||||
const offset = Math.min(0.499, Math.max(-0.499, next() - 0.5));
|
||||
pixels[index * 4] = Math.cos(phi);
|
||||
pixels[index * 4 + 1] = Math.sin(phi);
|
||||
pixels[index * 4 + 2] = offset * inv;
|
||||
pixels[index * 4 + 3] = next();
|
||||
}
|
||||
const texture = new DataTexture(pixels, NOISE_SIZE, NOISE_SIZE, RGBAFormat, FloatType);
|
||||
texture.wrapS = RepeatWrapping;
|
||||
texture.wrapT = RepeatWrapping;
|
||||
texture.magFilter = LinearFilter;
|
||||
texture.minFilter = LinearFilter;
|
||||
texture.needsUpdate = true;
|
||||
return texture;
|
||||
}
|
||||
|
||||
const VERTEX_SHADER = /* glsl */`
|
||||
varying vec2 vUv;
|
||||
void main() {
|
||||
vUv = uv;
|
||||
gl_Position = vec4(position.xy, 0.0, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
const FRAGMENT_SHADER = /* glsl */`
|
||||
precision highp float;
|
||||
|
||||
varying vec2 vUv;
|
||||
|
||||
uniform sampler2D tColor;
|
||||
uniform sampler2D tDepth;
|
||||
uniform sampler2D tNormal;
|
||||
uniform sampler2D tNoise;
|
||||
uniform vec3 uSamples[${USED_SAMPLES}];
|
||||
|
||||
uniform mat4 uProjection;
|
||||
uniform mat4 uProjectionInverse;
|
||||
uniform vec2 uResolution;
|
||||
|
||||
uniform float uNear;
|
||||
uniform float uFar;
|
||||
uniform float uDistance;
|
||||
uniform float uAttenuation;
|
||||
uniform float uSampleCountInv;
|
||||
uniform float uValley;
|
||||
uniform float uRidge;
|
||||
uniform float uCurvatureRidge;
|
||||
uniform float uCurvatureValley;
|
||||
uniform float uUiScale;
|
||||
uniform float uUseCavity;
|
||||
uniform float uUseCurvature;
|
||||
|
||||
/* workbench_common_lib.glsl — the workbench depth buffer is non-linear. */
|
||||
vec3 view_position(vec2 uv, float depth) {
|
||||
vec4 clip = vec4(uv * 2.0 - 1.0, depth * 2.0 - 1.0, 1.0);
|
||||
vec4 view = uProjectionInverse * clip;
|
||||
return view.xyz / view.w;
|
||||
}
|
||||
|
||||
/* workbench_mesh_passes.cc:149 binds a normal_tx prepass (SFLOAT_16_16,
|
||||
* sphere-mapped). The depth buffer carries 24 bits of *window* depth, which is
|
||||
* uniform over [0,1] and therefore only ~2^-24 of the range near 1.0; turning
|
||||
* that into a view position and differencing it twice (the cross product here,
|
||||
* then the four-neighbour normal difference in the curvature block) amplifies
|
||||
* the quantisation by the reciprocal of the tangent-plane baseline. Measured on
|
||||
* a flat cube face that leaves |normal_diff| ~ 0.016, i.e. visible dither.
|
||||
* Desktop never sees this because it reads real normals, so do the same: the
|
||||
* prepass below writes view-space normals at half-float precision. */
|
||||
vec3 view_normal(vec2 uv) {
|
||||
return texture2D(tNormal, uv).xyz * 2.0 - 1.0;
|
||||
}
|
||||
|
||||
/* workbench_curvature.bsl.hh:26-31 */
|
||||
float curvature_soft_clamp(float curvature, float control) {
|
||||
if (curvature < 0.5 / control) return curvature * (1.0 - curvature * control);
|
||||
return 0.25 / control;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 color = texture2D(tColor, vUv).rgb;
|
||||
float depth = texture2D(tDepth, vUv).x;
|
||||
|
||||
/* Background and the near plane are never shaded (cavity.bsl.hh:42-44). */
|
||||
if (depth == 1.0) {
|
||||
/* Only the background needs repairing here. three draws its own background
|
||||
* through linearToOutputTexel, which is a linear-to-sRGB encode on the canvas
|
||||
* but the identity for a plain render target, so the intermediate buffer
|
||||
* holds a linearised background. Our workbench materials write
|
||||
* display-referred values untouched and reach the canvas unchanged, so
|
||||
* without this re-encode the viewport background darkens as soon as cavity
|
||||
* or curvature turns the off-screen pass on. */
|
||||
gl_FragColor = vec4(linearToOutputTexel(vec4(color, 1.0)).rgb, 1.0);
|
||||
return;
|
||||
}
|
||||
if (depth == 0.0) {
|
||||
gl_FragColor = vec4(color, 1.0);
|
||||
return;
|
||||
}
|
||||
|
||||
vec2 texel = 1.0 / uResolution;
|
||||
vec3 position = view_position(vUv, depth);
|
||||
vec3 normal = view_normal(vUv);
|
||||
|
||||
float cavities = 0.0;
|
||||
float edges = 0.0;
|
||||
float curvature = 0.0;
|
||||
|
||||
if (uUseCurvature > 0.5) {
|
||||
/* workbench_curvature.bsl.hh:33-46 — object outlines are dropped by the id
|
||||
* test on desktop; depth discontinuity stands in for it here. */
|
||||
float depthUp = texture2D(tDepth, vUv + vec2(0.0, texel.y)).x;
|
||||
float depthDown = texture2D(tDepth, vUv - vec2(0.0, texel.y)).x;
|
||||
float depthRight = texture2D(tDepth, vUv + vec2(texel.x, 0.0)).x;
|
||||
float depthLeft = texture2D(tDepth, vUv - vec2(texel.x, 0.0)).x;
|
||||
vec3 normalUp = view_normal(vUv + vec2(0.0, texel.y));
|
||||
vec3 normalDown = view_normal(vUv - vec2(0.0, texel.y));
|
||||
vec3 normalRight = view_normal(vUv + vec2(texel.x, 0.0));
|
||||
vec3 normalLeft = view_normal(vUv - vec2(texel.x, 0.0));
|
||||
|
||||
float nearFar = abs(depthUp - depthDown) + abs(depthRight - depthLeft);
|
||||
bool background = depthUp == 1.0 || depthDown == 1.0 || depthRight == 1.0 || depthLeft == 1.0;
|
||||
if (!background && nearFar < 0.02) {
|
||||
float normalDiff = (normalUp.y - normalDown.y) + (normalRight.x - normalLeft.x);
|
||||
float ridge = 0.5 / max(uCurvatureRidge * uCurvatureRidge, 1e-4);
|
||||
float valley = 0.7 / max(uCurvatureValley * uCurvatureValley, 1e-4);
|
||||
curvature = normalDiff < 0.0
|
||||
? -2.0 * curvature_soft_clamp(-normalDiff, valley)
|
||||
: 2.0 * curvature_soft_clamp(normalDiff, ridge);
|
||||
}
|
||||
}
|
||||
|
||||
if (uUseCavity > 0.5) {
|
||||
/* workbench_cavity.bsl.hh — Alchemy screen-space obscurance. */
|
||||
vec2 jitterCo = (vUv * uResolution) * (1.0 / 64.0);
|
||||
vec3 noise = texture2D(tNoise, jitterCo).rgb;
|
||||
|
||||
/* Project a point one "cavity_distance" away to find the disk radius. */
|
||||
float homcoord = uProjection[2][3] * position.z + uProjection[3][3];
|
||||
vec2 offset;
|
||||
offset.x = uProjection[0][0] * uDistance / homcoord;
|
||||
offset.y = uProjection[1][1] * uDistance / homcoord;
|
||||
offset *= 0.5;
|
||||
|
||||
vec2 rotX = noise.rg;
|
||||
vec2 rotY = vec2(-rotX.y, rotX.x);
|
||||
|
||||
for (int i = 0; i < ${USED_SAMPLES}; i++) {
|
||||
vec3 sampleCoord = uSamples[i];
|
||||
vec2 dirJittered = vec2(dot(sampleCoord.xy, rotX), dot(sampleCoord.xy, rotY));
|
||||
dirJittered *= sampleCoord.z + noise.b;
|
||||
|
||||
vec2 uvcoords = vUv + dirJittered * offset;
|
||||
if (any(greaterThan(abs(uvcoords - 0.5), vec2(0.5)))) continue;
|
||||
|
||||
float sDepth = texture2D(tDepth, uvcoords).x;
|
||||
bool isBackground = sDepth == 1.0;
|
||||
/* Background samples are pulled onto the surface, which keeps edges from
|
||||
* washing out when no neighbour was found. */
|
||||
sDepth = isBackground ? depth : sDepth;
|
||||
vec3 sPosition = view_position(uvcoords, sDepth);
|
||||
if (isBackground) sPosition.z -= uDistance;
|
||||
|
||||
vec3 dir = sPosition - position;
|
||||
float len = length(dir);
|
||||
float fCavities = dot(dir, normal);
|
||||
float fEdge = -fCavities;
|
||||
float bias = 0.05 * len + 0.0001;
|
||||
float attenuation = 1.0 / (len * (1.0 + len * len * uAttenuation));
|
||||
|
||||
if (fCavities > -bias) cavities += fCavities * attenuation;
|
||||
if (fEdge > bias) edges += fEdge * attenuation;
|
||||
}
|
||||
|
||||
cavities *= uSampleCountInv;
|
||||
edges *= uSampleCountInv;
|
||||
cavities = clamp(cavities * uValley, 0.0, 1.0);
|
||||
edges = edges * uRidge;
|
||||
}
|
||||
|
||||
/* workbench_composite.bsl.hh:104 */
|
||||
color *= clamp((1.0 - cavities) * (1.0 + edges) * (1.0 + curvature), 0.0, 4.0);
|
||||
gl_FragColor = vec4(color, 1.0);
|
||||
}
|
||||
`;
|
||||
|
||||
/**
|
||||
* Renders the scene through the workbench screen-space effects. Disabled it is a
|
||||
* pass-through, so callers can route every frame through it unconditionally.
|
||||
*/
|
||||
export class WorkbenchPost {
|
||||
private readonly scene = new Scene();
|
||||
private readonly camera = new OrthographicCamera(-1, 1, 1, -1, 0, 1);
|
||||
private readonly quad: Mesh;
|
||||
private readonly material: ShaderMaterial;
|
||||
private readonly noise = noiseTexture(USED_SAMPLES);
|
||||
private target: WebGLRenderTarget | null = null;
|
||||
/* `workbench_mesh_passes.cc:179-191` allocates `gbuffer_normal_tx` as
|
||||
* `SFLOAT_16_16`; half float here for the same reason (see `view_normal`). */
|
||||
private normalTarget: WebGLRenderTarget | null = null;
|
||||
private readonly normalMaterial = new MeshNormalMaterial();
|
||||
private width = 0;
|
||||
private height = 0;
|
||||
private options: WorkbenchCavityOptions = {};
|
||||
|
||||
constructor() {
|
||||
this.material = new ShaderMaterial({
|
||||
vertexShader: VERTEX_SHADER,
|
||||
fragmentShader: FRAGMENT_SHADER,
|
||||
depthTest: false,
|
||||
depthWrite: false,
|
||||
side: DoubleSide,
|
||||
uniforms: {
|
||||
tColor: { value: null },
|
||||
tDepth: { value: null },
|
||||
tNormal: { value: null },
|
||||
tNoise: { value: this.noise },
|
||||
uSamples: { value: cavitySamples(SSAO_SAMPLES) },
|
||||
uProjection: { value: new Float32Array(16) },
|
||||
uProjectionInverse: { value: new Float32Array(16) },
|
||||
uResolution: { value: new Vector2(1, 1) },
|
||||
uNear: { value: 0.01 },
|
||||
uFar: { value: 1000 },
|
||||
uDistance: { value: 0.2 },
|
||||
uAttenuation: { value: 1 },
|
||||
uSampleCountInv: { value: 1 / USED_SAMPLES },
|
||||
uValley: { value: 1 },
|
||||
uRidge: { value: 1 },
|
||||
uCurvatureRidge: { value: 1 },
|
||||
uCurvatureValley: { value: 1 },
|
||||
uUiScale: { value: 1 },
|
||||
uUseCavity: { value: 0 },
|
||||
uUseCurvature: { value: 0 },
|
||||
},
|
||||
});
|
||||
this.quad = new Mesh(new PlaneGeometry(2, 2), this.material);
|
||||
this.quad.frustumCulled = false;
|
||||
this.scene.add(this.quad);
|
||||
}
|
||||
|
||||
setOptions(options: WorkbenchCavityOptions): void {
|
||||
this.options = { ...this.options, ...options };
|
||||
}
|
||||
|
||||
/* `workbench_state.cc:244-248`: `cavity_type` selects which of the two effects
|
||||
* run, and both are gated on the master flag. */
|
||||
private get drawCavity(): boolean {
|
||||
const type = this.options.type ?? "BOTH";
|
||||
return Boolean(this.options.enabled) && (type === "WORLD" || type === "BOTH");
|
||||
}
|
||||
|
||||
private get drawCurvature(): boolean {
|
||||
const type = this.options.type ?? "BOTH";
|
||||
return Boolean(this.options.enabled) && Boolean(this.options.curvature) && (type === "SCREEN" || type === "BOTH");
|
||||
}
|
||||
|
||||
get enabled(): boolean {
|
||||
return this.drawCavity || this.drawCurvature;
|
||||
}
|
||||
|
||||
private ensureTarget(renderer: WebGLRenderer): WebGLRenderTarget {
|
||||
const size = renderer.getDrawingBufferSize(new Vector2());
|
||||
const width = Math.max(1, Math.floor(size.x));
|
||||
const height = Math.max(1, Math.floor(size.y));
|
||||
if (this.target && this.width === width && this.height === height) return this.target;
|
||||
this.target?.dispose();
|
||||
this.normalTarget?.dispose();
|
||||
const depth = new DepthTexture(width, height, UnsignedIntType);
|
||||
depth.format = DepthFormat;
|
||||
/* `samples` stays 0 on purpose: three only resolves a multisampled depth
|
||||
* attachment when `resolveDepthBuffer` is set, and the unresolved MSAA depth
|
||||
* texture reads back as garbage here. Losing viewport AA while cavity is on
|
||||
* is preferable to feeding the cavity pass an invalid depth buffer. */
|
||||
this.target = new WebGLRenderTarget(width, height, { depthBuffer: true, stencilBuffer: false, depthTexture: depth, samples: 0 });
|
||||
this.target.texture.generateMipmaps = false;
|
||||
/* `depthBuffer` has to be on: without a depth test the prepass draws
|
||||
* whichever object comes last into each pixel, so a hidden face would
|
||||
* overwrite the visible one's normal. */
|
||||
this.normalTarget = new WebGLRenderTarget(width, height, {
|
||||
type: HalfFloatType,
|
||||
minFilter: LinearFilter,
|
||||
magFilter: LinearFilter,
|
||||
depthBuffer: true,
|
||||
stencilBuffer: false,
|
||||
samples: 0,
|
||||
});
|
||||
this.normalTarget.texture.generateMipmaps = false;
|
||||
this.width = width;
|
||||
this.height = height;
|
||||
return this.target;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draws `scene` and returns whether the effects ran. A disabled pass returns
|
||||
* `false` without touching the renderer, so the caller keeps its fast path.
|
||||
*/
|
||||
render(renderer: WebGLRenderer, scene: Object3D, camera: Camera): boolean {
|
||||
if (!this.enabled) return false;
|
||||
const target = this.ensureTarget(renderer);
|
||||
const uniforms = this.material.uniforms;
|
||||
/* `matcap_ssao_samples`: the per-iteration tap count. The shader always runs
|
||||
* the full `USED_SAMPLES` disk and normalises by the same number, so this
|
||||
* only reshapes the radius profile of the Hammersley set. */
|
||||
uniforms.uSamples.value = cavitySamples(Math.max(1, Math.min(USED_SAMPLES, Math.round(this.options.samples ?? SSAO_SAMPLES))));
|
||||
uniforms.uSampleCountInv.value = 1 / USED_SAMPLES;
|
||||
uniforms.uDistance.value = this.options.distance ?? 0.2;
|
||||
uniforms.uAttenuation.value = this.options.attenuation ?? 1;
|
||||
uniforms.uValley.value = this.options.valley ?? 1;
|
||||
uniforms.uRidge.value = this.options.ridge ?? 1;
|
||||
uniforms.uCurvatureRidge.value = this.options.curvatureRidge ?? 1;
|
||||
uniforms.uCurvatureValley.value = this.options.curvatureValley ?? 1;
|
||||
uniforms.uUiScale.value = this.options.uiScale ?? 1;
|
||||
uniforms.uUseCavity.value = this.drawCavity ? 1 : 0;
|
||||
uniforms.uUseCurvature.value = this.drawCurvature ? 1 : 0;
|
||||
|
||||
const previousTarget = renderer.getRenderTarget();
|
||||
/* Normal prepass, `workbench_mesh_passes.cc:179-205`. `overrideMaterial`
|
||||
* swaps every draw in the scene for `MeshNormalMaterial`, which writes
|
||||
* `view-space normal * 0.5 + 0.5` exactly like the desktop prepass writes
|
||||
* `normal_encode(facing, v_out.normal)`. */
|
||||
if (this.normalTarget) {
|
||||
/* Desktop's prepass draws the mesh list only, so overlay geometry (the
|
||||
* viewport grid) never enters the G-buffer. `overrideMaterial` applies to
|
||||
* every draw, so without this the grid is rendered as normal shading: its
|
||||
* fragments are not meshes, decode to a garbage normal, and punch lines of
|
||||
* false curvature across the surface behind them. */
|
||||
const overlays: Object3D[] = [];
|
||||
scene.traverse((object) => {
|
||||
const kind = object as Object3D & { isLine?: boolean; isPoints?: boolean; isSprite?: boolean };
|
||||
if (object.visible && (kind.isLine || kind.isPoints || kind.isSprite)) {
|
||||
object.visible = false;
|
||||
overlays.push(object);
|
||||
}
|
||||
});
|
||||
const targetScene = scene as Scene & { overrideMaterial: unknown };
|
||||
const previousOverride = targetScene.isScene ? targetScene.overrideMaterial : null;
|
||||
if (targetScene.isScene) targetScene.overrideMaterial = this.normalMaterial;
|
||||
const previousColor = renderer.getClearColor(new Color());
|
||||
const previousAlpha = renderer.getClearAlpha();
|
||||
const previousColorSpace = renderer.outputColorSpace;
|
||||
const previousToneMapping = renderer.toneMapping;
|
||||
/* A normal buffer is data, not colour: no tone map, no sRGB encode. */
|
||||
renderer.toneMapping = NoToneMapping;
|
||||
renderer.outputColorSpace = LinearSRGBColorSpace;
|
||||
renderer.setRenderTarget(this.normalTarget);
|
||||
renderer.clear();
|
||||
renderer.render(scene, camera);
|
||||
renderer.toneMapping = previousToneMapping;
|
||||
renderer.outputColorSpace = previousColorSpace;
|
||||
renderer.setClearColor(previousColor, previousAlpha);
|
||||
if (targetScene.isScene) targetScene.overrideMaterial = previousOverride;
|
||||
for (const overlay of overlays) overlay.visible = true;
|
||||
uniforms.tNormal.value = this.normalTarget.texture;
|
||||
}
|
||||
renderer.setRenderTarget(target);
|
||||
renderer.clear();
|
||||
renderer.render(scene, camera);
|
||||
|
||||
/* `view_position` inverts the projection, so it has to be current. */
|
||||
const projection = (camera as Camera & { projectionMatrix: { elements: number[] } }).projectionMatrix;
|
||||
uniforms.uProjection.value = projection.elements.slice();
|
||||
(uniforms.uProjectionInverse.value as Float32Array).set(
|
||||
projectionInverse(projection.elements),
|
||||
);
|
||||
uniforms.uResolution.value.set(this.width, this.height);
|
||||
uniforms.uNear.value = (camera as Camera & { near?: number }).near ?? 0.01;
|
||||
uniforms.uFar.value = (camera as Camera & { far?: number }).far ?? 1000;
|
||||
uniforms.tColor.value = target.texture;
|
||||
uniforms.tDepth.value = target.depthTexture;
|
||||
|
||||
renderer.setRenderTarget(previousTarget);
|
||||
renderer.render(this.scene, this.camera);
|
||||
return true;
|
||||
}
|
||||
|
||||
dispose(): void {
|
||||
this.target?.dispose();
|
||||
this.target = null;
|
||||
this.normalTarget?.dispose();
|
||||
this.normalTarget = null;
|
||||
this.normalMaterial.dispose();
|
||||
this.material.dispose();
|
||||
this.quad.geometry.dispose();
|
||||
this.noise.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
/** Inverts a column-major 4x4 without pulling in the whole Matrix4 API. */
|
||||
function projectionInverse(elements: number[]): Float32Array {
|
||||
const m = elements;
|
||||
const out = new Float32Array(16);
|
||||
const a00 = m[0], a01 = m[1], a02 = m[2], a03 = m[3];
|
||||
const a10 = m[4], a11 = m[5], a12 = m[6], a13 = m[7];
|
||||
const a20 = m[8], a21 = m[9], a22 = m[10], a23 = m[11];
|
||||
const a30 = m[12], a31 = m[13], a32 = m[14], a33 = m[15];
|
||||
const b00 = a00 * a11 - a01 * a10, b01 = a00 * a12 - a02 * a10;
|
||||
const b02 = a00 * a13 - a03 * a10, b03 = a01 * a12 - a02 * a11;
|
||||
const b04 = a01 * a13 - a03 * a11, b05 = a02 * a13 - a03 * a12;
|
||||
const b06 = a20 * a31 - a21 * a30, b07 = a20 * a32 - a22 * a30;
|
||||
const b08 = a20 * a33 - a23 * a30, b09 = a21 * a32 - a22 * a31;
|
||||
const b10 = a21 * a33 - a23 * a31, b11 = a22 * a33 - a23 * a32;
|
||||
let det = b00 * b11 - b01 * b10 + b02 * b09 + b03 * b08 - b04 * b07 + b05 * b06;
|
||||
if (!det) return out;
|
||||
det = 1 / det;
|
||||
out[0] = (a11 * b11 - a12 * b10 + a13 * b09) * det;
|
||||
out[1] = (a02 * b10 - a01 * b11 - a03 * b09) * det;
|
||||
out[2] = (a31 * b05 - a32 * b04 + a33 * b03) * det;
|
||||
out[3] = (a22 * b04 - a21 * b05 - a23 * b03) * det;
|
||||
out[4] = (a12 * b08 - a10 * b11 - a13 * b07) * det;
|
||||
out[5] = (a00 * b11 - a02 * b08 + a03 * b07) * det;
|
||||
out[6] = (a32 * b02 - a30 * b05 - a33 * b01) * det;
|
||||
out[7] = (a20 * b05 - a22 * b02 + a23 * b01) * det;
|
||||
out[8] = (a10 * b10 - a11 * b08 + a13 * b06) * det;
|
||||
out[9] = (a01 * b08 - a00 * b10 - a03 * b06) * det;
|
||||
out[10] = (a30 * b04 - a31 * b02 + a33 * b00) * det;
|
||||
out[11] = (a21 * b02 - a20 * b04 - a23 * b00) * det;
|
||||
out[12] = (a11 * b07 - a10 * b09 - a12 * b06) * det;
|
||||
out[13] = (a00 * b09 - a01 * b07 + a02 * b06) * det;
|
||||
out[14] = (a31 * b01 - a30 * b03 - a32 * b00) * det;
|
||||
out[15] = (a20 * b03 - a21 * b01 + a22 * b00) * det;
|
||||
return out;
|
||||
}
|
||||
Reference in New Issue
Block a user