From 1311e9baeb104227e281155e474fc0fb9a89db8e Mon Sep 17 00:00:00 2001 From: Jonathan Bingham Date: Mon, 16 Nov 2026 16:10:26 +0000 Subject: [PATCH] fix(web,xr): inverted shadow-caster normal bias and Bug 1: fake "overhang" shadow band on flush multi-story walls. Both shadow depth vertex shaders (WebGL2 `VS_SHADOW_DEPTH`, WebGPU `vsShadowDepth`) pushed casters *outward* along +N by ~1.75 shadow texels (~5-6 cm on a house+lawn scene), while the receiver (`shdEval` / WGSL) also offsets outward along +N. The inflated upper wall stuck out past a flush lower wall and the light-facing faces self-shadowed. - Casters now shrink inward along -N (`applyShadowCasterNormalBias` is the CPU reference; GLSL and WGSL match it). - Receivers now carry the full normal bias (`SHADOW_RECEIVER_NORMAL_BIAS_SCALE = 1.0`, was 0.5) on WebGL2 and WebGPU. This keeps PCF taps across light-facing convex edges (a wall's top face meeting its front face at the floor joint) and grazing sloped/curved surfaces free of acne. Bug 2: `` did nothing to the mesh. - New `src/section-plane.ts` (`resolveSectionPlane`) is used by the WebGL2 color pass, WebGPU, and the shadow pass. `resolveShadowSectionPlane` now delegates to it. - `ThreeView.render()` binds `uSectionEnabled`/`uSectionPlane` on every primitive from the host's `section-plane`. It no longer hardcodes 0. Backdrop and plugin meshes are not clipped. - `ThreeLiveElement` observes `section-plane`, re-renders when it changes, and exposes a `sectionPlane` getter/setter. The duplicate entry in `XRLiveElement.observedAttributes` is removed. - `exploded-view` (xr-live) still overrides the uniforms when its gizmo or section is active. When inactive, it no longer zeroes the core binding. Tests (written to fail first): - shadow_maps_test: CPU shadow-map rasterizer that mirrors the shader math (caster bias, polygonOffset(1.5, 4), bilinear LEQUAL compare, receiver normal offset, 8-tap Vogel PCF). Scene: 22x18 m lawn, flush stacked walls at y=0..3 and y=3..6, and an angled castShadow sun. Checks: - The legacy +N bias darkens the wall (min 0.92). - The fixed bias gives shadow == 1.0 below the joint and across both faces, for 4 sun directions and 1024/2048 maps. - The lawn behind the walls is still shadowed. - No acne on the sloped slab, sphere, or lawn. Also covers GLSL/WGSL inward-bias parity and toggling section-plane y:0.0 -> none in the shadow pass (uSecOn, plane, upper-half clip, digest invalidation). - three_view_test: `` clips the upper half in the WebGL2 color pass without xr-live, and "none" restores the full mesh. - three_webgpu_test: WebGPU receiver bias matches WebGL2, and section-plane toggles the scene uniforms. - three_live_element_test: observedAttributes, the `sectionPlane` property, and re-render on change. Kit packaging: `THREE.Architecture` is not part of `compile_three_live_full_min` (kits are opt-in). Use `three-live-kit-architecture.min.js` (`compile_three_live_kit_architecture_min`, loaded after the full bundle). Its `installArchitectureKit` is registered as a worker extension installer, so it reaches worker sandboxes with no shims (kit_architecture_test covers this). xr-live golden tests: xr_plugins_test and xr_sim_test were already failing at head in hermetic test runners. The bundled test is a CAS symlink, so `__dirname` resolves outside the runfiles tree. Golden lookup now also resolves relative to the node entry path (`process.argv[1]`), which keeps the symlinked location. All 38 three-live + xr-live tests pass. Verified: `npm test` passes (all three-live + xr-live suites). --- README.md | 4 +- three-live/src/plugins/shadow-maps.ts | 129 +++-- three-live/src/section-plane.ts | 115 +++++ three-live/src/three-live-element.ts | 20 +- three-live/src/three-view.ts | 22 +- three-live/src/webgpu/shaders.ts | 7 +- three-live/tests/shadow_maps_test.ts | 537 ++++++++++++++++++++ three-live/tests/three_live_element_test.ts | 37 ++ three-live/tests/three_view_test.ts | 112 ++++ three-live/tests/three_webgpu_test.ts | 93 +++- xr-live/src/plugins/exploded-view.ts | 8 +- xr-live/src/xr-live-element.ts | 1 - xr-live/tests/xr_plugins_test.ts | 15 + xr-live/tests/xr_sim_test.ts | 15 + 14 files changed, 1036 insertions(+), 79 deletions(-) create mode 100644 three-live/src/section-plane.ts diff --git a/README.md b/README.md index edf23670..292781ac 100644 --- a/README.md +++ b/README.md @@ -423,7 +423,9 @@ On the web, `` supports the core HTML attributes used by `rotation-per-second`, `ar`, `ar-modes`, `ar-scale`, `ar-placement`, `exposure`, `shadow-intensity`, `shadow-softness`, `shadow-maps`, `tone-mapping`, `environment-image`, `skybox-image`, `autoplay`, `animation-name`, -`variant-name`, and `slot="hotspot-*"`). +`variant-name`, and `slot="hotspot-*"`). It also accepts a CAD `section-plane` +cut (`"y:2.8"`, `"-z:0.5"`, `"none"`) that clips the color and shadow passes on +WebGL2 and WebGPU without requiring ``. If you have existing `` HTML markup and want to add procedural Three.js scripts, native Android/iOS runtime targets, or CLI/MCP scene diff --git a/three-live/src/plugins/shadow-maps.ts b/three-live/src/plugins/shadow-maps.ts index d81afd42..b2ded7a7 100644 --- a/three-live/src/plugins/shadow-maps.ts +++ b/three-live/src/plugins/shadow-maps.ts @@ -42,6 +42,7 @@ import { type ShadowMapsMode, type ThreeLivePlugin, } from '../plugin'; +import {resolveSectionPlane, type ResolvedSectionPlane} from '../section-plane'; /** Maximum simultaneous shadow-casting lights in the depth array texture. */ export const MAX_SHADOW_LIGHTS = 4; @@ -485,70 +486,14 @@ export function fitSpotShadowMatrix( return mat4Multiply(out, _projMat, _lookView); } -/** Parses CAD section-plane clipping state on `viewer` (shared with WebGPU). */ -export function resolveShadowSectionPlane(viewerObj: unknown): { - enabled: boolean; - normal: [number, number, number]; - constant: number; -} | null { - const viewer = (viewerObj || {}) as ShadowViewerLike; - for (const m of viewer.meshes ?? []) { - if ( - m.name === '__xr_section_gizmo__' && - m.visible !== false && - m.worldMatrix && - m.worldMatrix.length >= 16 - ) { - const wm = m.worldMatrix; - const nl = Math.hypot(wm[8], wm[9], wm[10]) || 1; - const nx = wm[8] / nl; - const ny = wm[9] / nl; - const nz = wm[10] / nl; - return { - enabled: true, - normal: [nx, ny, nz], - constant: nx * wm[12] + ny * wm[13] + nz * wm[14], - }; - } - } - const raw = (viewer.container?.getAttribute?.('section-plane') ?? '') - .trim() - .toLowerCase(); - if (!raw || raw === 'none' || raw === 'false') return null; - let localN: [number, number, number] = [1, 0, 0]; - let localC = 0; - if (raw === 'interactive') { - localC = viewer.bounds?.center[0] ?? 0; - } else { - const match = - /^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/.exec(raw); - if (!match) return null; - const sign = match[1].startsWith('-') ? -1 : 1; - const axis = match[1].replace(/^[+-]/, ''); - const val = Math.max(-1000, Math.min(1000, Number(match[2]) || 0)); - localN = - axis === 'x' ? [sign, 0, 0] : axis === 'y' ? [0, sign, 0] : [0, 0, sign]; - localC = val * sign; - } - const rm = viewer.modelRootMatrix ?? IDENTITY_MAT4; - const wnx = rm[0] * localN[0] + rm[4] * localN[1] + rm[8] * localN[2]; - const wny = rm[1] * localN[0] + rm[5] * localN[1] + rm[9] * localN[2]; - const wnz = rm[2] * localN[0] + rm[6] * localN[1] + rm[10] * localN[2]; - const wnl = Math.hypot(wnx, wny, wnz) || 1; - const unx = wnx / wnl; - const uny = wny / wnl; - const unz = wnz / wnl; - const px = localN[0] * localC; - const py = localN[1] * localC; - const pz = localN[2] * localC; - const wpx = rm[0] * px + rm[4] * py + rm[8] * pz + rm[12]; - const wpy = rm[1] * px + rm[5] * py + rm[9] * pz + rm[13]; - const wpz = rm[2] * px + rm[6] * py + rm[10] * pz + rm[14]; - return { - enabled: true, - normal: [unx, uny, unz], - constant: unx * wpx + uny * wpy + unz * wpz, - }; +/** + * Parses CAD section-plane clipping state on `viewer` (shared with WebGPU and + * the core WebGL2 color pass via `../section-plane`). + */ +export function resolveShadowSectionPlane( + viewerObj: unknown, +): ResolvedSectionPlane | null { + return resolveSectionPlane(viewerObj); } function isShadowEligibleMesh(mesh: ShadowMeshLike): boolean { @@ -857,7 +802,56 @@ export function getShadowMapStats(viewer: object): ShadowMapStats { }; } -const VS_SHADOW_DEPTH = `#version 300 es +/** + * CPU reference for the caster normal-offset applied by the WebGL2 + * (`VS_SHADOW_DEPTH`) and WebGPU (`vsShadowDepth`) shadow depth passes. + * + * Casters are shrunk *inward* along `-N` (never inflated along `+N`). The + * receiver already offsets its lookup outward along `+N` in `shdEval`, so + * inflating casters as well made upper-story walls stick out ~1.75 shadow + * texels past a flush lower wall and cast a fake horizontal "overhang" band + * just below the floor joint. Shrinking light-facing casters also moves them + * away from the light, which further suppresses self-shadow acne. + * + * Writes the biased world position into `out` and returns it. + */ +export function applyShadowCasterNormalBias( + out: number[] | Float32Array, + worldPos: ArrayLike, + worldNormal: ArrayLike, + rayDir: ArrayLike, + normalBiasWorld: number, +): number[] | Float32Array { + out[0] = worldPos[0]; + out[1] = worldPos[1]; + out[2] = worldPos[2]; + const nl = Math.hypot(worldNormal[0], worldNormal[1], worldNormal[2]); + if (nl > 1e-5 && normalBiasWorld > 0) { + const nx = worldNormal[0] / nl; + const ny = worldNormal[1] / nl; + const nz = worldNormal[2] / nl; + const d = nx * rayDir[0] + ny * rayDir[1] + nz * rayDir[2]; + const k = normalBiasWorld * Math.max(1 - Math.abs(d), 0.15); + out[0] -= nx * k; + out[1] -= ny * k; + out[2] -= nz * k; + } + return out; +} + +/** + * Receiver normal-offset scale applied to `normalBiasWorld` in `shdEval` + * (`uShadowParams[s].y`) and the WebGPU receiver (`writeSceneUniforms`). + * + * With casters shrunk inward, the receiver carries the full normal bias so + * PCF taps across light-facing convex edges (e.g. a wall's top face meeting + * its front face at a floor joint) and grazing sloped/curved surfaces stay + * acne-free. + */ +export const SHADOW_RECEIVER_NORMAL_BIAS_SCALE = 1.0; + +/** WebGL2 shadow depth vertex shader (exported for shader parity tests). */ +export const VS_SHADOW_DEPTH = `#version 300 es layout(location=0) in vec3 aPos; layout(location=1) in vec3 aNormal; layout(location=3) in vec3 aOff; @@ -876,7 +870,7 @@ vec3 wn=mat3(m)*aNormal; float nl=length(wn); if(nl>1e-5&&uBiasRay.w>0.0){ wn/=nl; -wp.xyz+=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15)); +wp.xyz-=wn*(uBiasRay.w*max(1.0-abs(dot(wn,uBiasRay.xyz)),0.15)); } vWorldPos=wp.xyz; gl_Position=uLightVP*wp; @@ -1231,7 +1225,8 @@ export const shadowMapsPlugin: ThreeLivePlugin = { st.vpFlat.set(s.viewProj, s.slot * 16); const b = s.slot * 4; st.paramsFlat[b] = s.depthBias; - st.paramsFlat[b + 1] = s.normalBiasWorld * 0.5; + st.paramsFlat[b + 1] = + s.normalBiasWorld * SHADOW_RECEIVER_NORMAL_BIAS_SCALE; st.paramsFlat[b + 2] = s.uvRadius; } diff --git a/three-live/src/section-plane.ts b/three-live/src/section-plane.ts new file mode 100644 index 00000000..80ad24a1 --- /dev/null +++ b/three-live/src/section-plane.ts @@ -0,0 +1,115 @@ +// Copyright 2026 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +/** + * @fileoverview Shared CAD `section-plane` resolution used by the core WebGL2 + * color pass (`ThreeView.render`), the WebGPU scene accelerator, and the + * shadow-map depth pass so all three clip against the exact same plane. + */ + +/** World-space clipping plane: fragments with `dot(p, normal) > constant` are discarded. */ +export interface ResolvedSectionPlane { + enabled: boolean; + normal: [number, number, number]; + constant: number; +} + +interface SectionViewerLike { + readonly container?: { + readonly getAttribute?: (name: string) => string | null; + } | null; + readonly meshes?: ReadonlyArray<{ + readonly name?: string; + readonly visible?: boolean; + readonly worldMatrix?: ArrayLike; + }>; + readonly bounds?: {readonly center: readonly number[]}; + readonly modelRootMatrix?: ArrayLike; +} + +const IDENTITY: readonly number[] = [ + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, +]; + +const SPEC_RE = /^([+-]?[xyz])\s*:\s*([+-]?(?:\d+\.?\d*|\.\d+)(?:e[+-]?\d+)?)$/; + +/** + * Resolves the active world-space section plane for `viewerObj`. + * + * Priority: a visible `` interactive section gizmo + * (`__xr_section_gizmo__`) wins; otherwise the host element's + * `section-plane` attribute (authored in scene/model space, transformed by + * `modelRootMatrix`). Returns `null` when clipping is disabled. + */ +export function resolveSectionPlane( + viewerObj: unknown, +): ResolvedSectionPlane | null { + const viewer = (viewerObj || {}) as SectionViewerLike; + for (const m of viewer.meshes ?? []) { + if ( + m.name === '__xr_section_gizmo__' && + m.visible !== false && + m.worldMatrix && + m.worldMatrix.length >= 16 + ) { + const wm = m.worldMatrix; + const nl = Math.hypot(wm[8], wm[9], wm[10]) || 1; + const nx = wm[8] / nl; + const ny = wm[9] / nl; + const nz = wm[10] / nl; + return { + enabled: true, + normal: [nx, ny, nz], + constant: nx * wm[12] + ny * wm[13] + nz * wm[14], + }; + } + } + const raw = (viewer.container?.getAttribute?.('section-plane') ?? '') + .trim() + .toLowerCase(); + if (!raw || raw === 'none' || raw === 'false') return null; + let localN: [number, number, number] = [1, 0, 0]; + let localC = 0; + if (raw === 'interactive') { + localC = viewer.bounds?.center[0] ?? 0; + } else { + const match = SPEC_RE.exec(raw); + if (!match) return null; + const sign = match[1].startsWith('-') ? -1 : 1; + const axis = match[1].replace(/^[+-]/, ''); + const val = Math.max(-1000, Math.min(1000, Number(match[2]) || 0)); + localN = + axis === 'x' ? [sign, 0, 0] : axis === 'y' ? [0, sign, 0] : [0, 0, sign]; + localC = val * sign; + } + const rm = viewer.modelRootMatrix ?? IDENTITY; + const wnx = rm[0] * localN[0] + rm[4] * localN[1] + rm[8] * localN[2]; + const wny = rm[1] * localN[0] + rm[5] * localN[1] + rm[9] * localN[2]; + const wnz = rm[2] * localN[0] + rm[6] * localN[1] + rm[10] * localN[2]; + const wnl = Math.hypot(wnx, wny, wnz) || 1; + const unx = wnx / wnl; + const uny = wny / wnl; + const unz = wnz / wnl; + const px = localN[0] * localC; + const py = localN[1] * localC; + const pz = localN[2] * localC; + const wpx = rm[0] * px + rm[4] * py + rm[8] * pz + rm[12]; + const wpy = rm[1] * px + rm[5] * py + rm[9] * pz + rm[13]; + const wpz = rm[2] * px + rm[6] * py + rm[10] * pz + rm[14]; + return { + enabled: true, + normal: [unx, uny, unz], + constant: unx * wpx + uny * wpy + unz * wpz, + }; +} diff --git a/three-live/src/three-live-element.ts b/three-live/src/three-live-element.ts index 8fff84c1..18cd5860 100644 --- a/three-live/src/three-live-element.ts +++ b/three-live/src/three-live-element.ts @@ -243,7 +243,7 @@ export interface ThreeLiveElement { /** Custom `` Web Component for declarative 3D/XR rendering. */ export class ThreeLiveElement extends BaseElement { static readonly observedAttributes = - 'src ios-src script-src sandbox capabilities allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps'.split( + 'src ios-src script-src sandbox capabilities allow-client-scripts poster camera-controls camera-orbit camera-target min-camera-orbit max-camera-orbit field-of-view selected-mesh ar ar-modes ar-scale ar-placement exposure shadow-intensity shadow-softness tone-mapping bloom bloom-threshold bloom-radius outline outline-selected outline-color environment-image skybox-image autoplay animation-name variant-name auto-rotate auto-rotate-delay rotation-per-second renderer shadow-maps section-plane'.split( ' ', ); @@ -679,6 +679,12 @@ export class ThreeLiveElement extends BaseElement { v?.render(); break; + case 'section-plane': + // Color, WebGPU, and shadow passes all read `section-plane` from the + // host element each frame; just schedule a redraw. + v?.render(); + break; + case 'capabilities': if (!this._syncingCapsAttr) { this.__tlCapsOverride = null; @@ -899,6 +905,18 @@ export class ThreeLiveElement extends BaseElement { this.setAttr('shadow-maps', val); } + /** + * CAD cross-section clipping plane, e.g. `"y:2.8"`, `"-z:0.5"`, `"x:0"`, or + * `"none"`. Geometry on the positive side of the plane is discarded in the + * color pass (WebGL2 + WebGPU) and the shadow-map depth pass. + */ + get sectionPlane(): string { + return this.getAttr('section-plane')?.trim() || 'none'; + } + set sectionPlane(val: string | null) { + this.setAttr('section-plane', val); + } + protected fireEvent(type: string, detail?: unknown): void { this.dispatchEvent( new CustomEvent(type, {bubbles: true, composed: true, detail}), diff --git a/three-live/src/three-view.ts b/three-live/src/three-view.ts index 458f3ae6..5a13de1c 100644 --- a/three-live/src/three-view.ts +++ b/three-live/src/three-view.ts @@ -228,6 +228,7 @@ import { type ShadowMapsMode, type ThreeLivePlugin, } from './plugin'; +import {resolveSectionPlane} from './section-plane'; ensureCapabilityChecker(); export {getRegisteredPlugins, registerPlugin, type ThreeLivePlugin}; @@ -3977,6 +3978,7 @@ export class ThreeView { } let hasTransmissive = false; let hasRefraction = false; + const sectionPlane = resolveSectionPlane(this); const renderList = numBackdrop > 0 ? [...this.backdropMeshes, ...this.meshes] : this.meshes; const bindTex2D = ( @@ -4124,7 +4126,25 @@ export class ThreeView { ); this.bindLights(u); - if (u.uSectionEnabled) gl.uniform1i(u.uSectionEnabled, 0); + if (u.uSectionEnabled) { + // Core `section-plane` clipping (``), + // matching the shadow pass. ``'s exploded-view plugin may + // still override these uniforms in `onBeforeDrawPrimitive` below. + const clip = + sectionPlane !== null && + i >= numBackdrop && + !(mesh as any).isPluginMesh; + gl.uniform1i(u.uSectionEnabled, clip ? 1 : 0); + if (clip && u.uSectionPlane) { + gl.uniform4f( + u.uSectionPlane, + sectionPlane.normal[0], + sectionPlane.normal[1], + sectionPlane.normal[2], + sectionPlane.constant, + ); + } + } for (const plugin of registeredPlugins) { plugin.onBeforeDrawPrimitive?.( diff --git a/three-live/src/webgpu/shaders.ts b/three-live/src/webgpu/shaders.ts index 0cdd4e49..83ec387b 100644 --- a/three-live/src/webgpu/shaders.ts +++ b/three-live/src/webgpu/shaders.ts @@ -317,7 +317,8 @@ export function writeSceneUniforms( ); const pb = 180 + s.slot * 4; f32[pb] = s.depthBias; - f32[pb + 1] = s.normalBiasWorld * 0.5; + // Full receiver normal bias (SHADOW_RECEIVER_NORMAL_BIAS_SCALE). + f32[pb + 1] = s.normalBiasWorld; f32[pb + 2] = s.uvRadius; } i32[196] = input.shadowMap.dirSlots[0] | 0; @@ -954,10 +955,12 @@ fn vsShadowDepth( var wp = m * vec4(aPos, 1.0); let wn = m[0].xyz * aNormal.x + m[1].xyz * aNormal.y + m[2].xyz * aNormal.z; let nl = length(wn); + // Shrink casters inward along -N (see applyShadowCasterNormalBias in + // plugins/shadow-maps.ts); receivers already offset outward along +N. if (nl > 1e-5 && shd.biasRay.w > 0.0) { let un = wn / nl; wp = vec4( - wp.xyz + un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)), + wp.xyz - un * (shd.biasRay.w * max(1.0 - abs(dot(un, shd.biasRay.xyz)), 0.15)), 1.0, ); } diff --git a/three-live/tests/shadow_maps_test.ts b/three-live/tests/shadow_maps_test.ts index 37a62455..8d458cae 100644 --- a/three-live/tests/shadow_maps_test.ts +++ b/three-live/tests/shadow_maps_test.ts @@ -15,6 +15,7 @@ import {mat4Create} from '../src/math'; import {getSharedRegistry} from '../src/plugin'; import { + applyShadowCasterNormalBias, computeWorldSceneBounds, doesMeshCastShadow, doesMeshReceiveShadow, @@ -26,7 +27,10 @@ import { resolveActiveShadowLights, resolveShadowSectionPlane, SHADOW_MAP_TEXTURE_UNIT, + SHADOW_RECEIVER_NORMAL_BIAS_SCALE, shadowMapsPlugin, + VS_SHADOW_DEPTH, + type WorldSceneBounds, } from '../src/plugins/shadow-maps'; import THREE from '../src/three-author'; import {glbToUSDZ, sceneToGLB} from '../src/three-convert'; @@ -36,6 +40,7 @@ import { registerPlugin, ThreeView, } from '../src/three-view'; +import {SCENE_SHADOW_DEPTH_WGSL} from '../src/webgpu/shaders'; let passed = 0; let failed = 0; @@ -213,6 +218,535 @@ function makeMockShadowGl(overrides: Record = {}) { return {gl, rec, prevFboSentinel}; } +// --------------------------------------------------------------------------- +// CPU shadow-map rasterizer mirroring `VS_SHADOW_DEPTH` + `shdEval` (WebGL2) +// and `vsShadowDepth` + the WGSL receiver (WebGPU), used for pixel-level +// regression tests of normal-offset bias behavior. +// --------------------------------------------------------------------------- + +interface CpuTri { + p: number[][]; // 3 world positions + n: number[][]; // 3 world normals +} + +/** Extracts world-space triangles from a `THREE.BufferGeometry`. */ +function geometryTris(geo: any): CpuTri[] { + const pos = geo.attributes.position.array as ArrayLike; + const nor = geo.attributes.normal.array as ArrayLike; + const idx: ArrayLike | null = geo.index ? geo.index.array : null; + const count = idx ? idx.length : pos.length / 3; + const tris: CpuTri[] = []; + for (let t = 0; t + 2 < count; t += 3) { + const p: number[][] = []; + const n: number[][] = []; + for (let k = 0; k < 3; k++) { + const v = idx ? idx[t + k] : t + k; + p.push([pos[v * 3], pos[v * 3 + 1], pos[v * 3 + 2]]); + n.push([nor[v * 3], nor[v * 3 + 1], nor[v * 3 + 2]]); + } + tris.push({p, n}); + } + return tris; +} + +function boundsOfTris(tris: CpuTri[]): WorldSceneBounds { + const mn = [Infinity, Infinity, Infinity]; + const mx = [-Infinity, -Infinity, -Infinity]; + for (const t of tris) { + for (const v of t.p) { + for (let a = 0; a < 3; a++) { + mn[a] = Math.min(mn[a], v[a]); + mx[a] = Math.max(mx[a], v[a]); + } + } + } + const c: [number, number, number] = [ + (mn[0] + mx[0]) / 2, + (mn[1] + mx[1]) / 2, + (mn[2] + mx[2]) / 2, + ]; + const h = [(mx[0] - mn[0]) / 2, (mx[1] - mn[1]) / 2, (mx[2] - mn[2]) / 2]; + return { + center: c, + radius: Math.hypot(h[0], h[1], h[2]), + min: [c[0] - h[0], c[1] - h[1], c[2] - h[2]], + max: [c[0] + h[0], c[1] + h[1], c[2] + h[2]], + }; +} + +function xformPoint(m: Float32Array, p: ArrayLike): number[] { + const x = p[0], + y = p[1], + z = p[2]; + const w = m[3] * x + m[7] * y + m[11] * z + m[15]; + return [ + (m[0] * x + m[4] * y + m[8] * z + m[12]) / w, + (m[1] * x + m[5] * y + m[9] * z + m[13]) / w, + (m[2] * x + m[6] * y + m[10] * z + m[14]) / w, + ]; +} + +type CasterBiasFn = ( + out: number[], + wp: number[], + wn: number[], + rayDir: number[], + normalBiasWorld: number, +) => void; + +const productionCasterBias: CasterBiasFn = (out, wp, wn, ray, nb) => { + applyShadowCasterNormalBias(out, wp, wn, ray, nb); +}; + +/** Pre-fix behavior: casters inflated outward along `+N`. */ +const legacyInflatingCasterBias: CasterBiasFn = (out, wp, wn, ray, nb) => { + applyShadowCasterNormalBias(out, wp, wn, ray, nb); + for (let a = 0; a < 3; a++) out[a] = 2 * wp[a] - out[a]; +}; + +interface CpuShadowMap { + size: number; + depth: Float32Array; + vp: Float32Array; + dirToLight: number[]; + depthBias: number; + normalBiasWorld: number; + uvRadius: number; +} + +/** Rasterizes caster depth (min-depth, texel-center coverage, polygon offset). */ +function rasterizeShadowMap( + tris: CpuTri[], + dirToLight: number[], + size: number, + casterBias: CasterBiasFn, +): CpuShadowMap { + const bounds = boundsOfTris(tris); + const vp = mat4Create(); + fitDirectionalShadowMatrix(vp, dirToLight, bounds); + const dl = Math.hypot(dirToLight[0], dirToLight[1], dirToLight[2]); + const L = dirToLight.map((v) => v / dl); + const rayDir = L.map((v) => -v); + // Mirrors resolveShadowPlan defaults (bias -0.0005, normalBias 0.015, radius 1.5). + const texelWorld = (bounds.radius * 2.2) / size; + const normalBiasWorld = (0.015 / 0.015) * 1.75 * texelWorld; + const depth = new Float32Array(size * size).fill(1); + const tmp = [0, 0, 0]; + for (const t of tris) { + const s: number[][] = []; + for (let k = 0; k < 3; k++) { + casterBias(tmp, t.p[k], t.n[k], rayDir, normalBiasWorld); + const c = xformPoint(vp, tmp); + s.push([ + (c[0] * 0.5 + 0.5) * size, + (c[1] * 0.5 + 0.5) * size, + c[2] * 0.5 + 0.5, + ]); + } + const area = + (s[1][0] - s[0][0]) * (s[2][1] - s[0][1]) - + (s[2][0] - s[0][0]) * (s[1][1] - s[0][1]); + if (Math.abs(area) < 1e-12) continue; + // gl.polygonOffset(1.5, 4.0) on a DEPTH_COMPONENT24 target. + const dzdx = + ((s[1][2] - s[0][2]) * (s[2][1] - s[0][1]) - + (s[2][2] - s[0][2]) * (s[1][1] - s[0][1])) / + area; + const dzdy = + ((s[2][2] - s[0][2]) * (s[1][0] - s[0][0]) - + (s[1][2] - s[0][2]) * (s[2][0] - s[0][0])) / + area; + const polyOffset = + 1.5 * Math.max(Math.abs(dzdx), Math.abs(dzdy)) + 4 * 2 ** -24; + const x0 = Math.max(0, Math.floor(Math.min(s[0][0], s[1][0], s[2][0]))); + const x1 = Math.min( + size - 1, + Math.ceil(Math.max(s[0][0], s[1][0], s[2][0])), + ); + const y0 = Math.max(0, Math.floor(Math.min(s[0][1], s[1][1], s[2][1]))); + const y1 = Math.min( + size - 1, + Math.ceil(Math.max(s[0][1], s[1][1], s[2][1])), + ); + for (let y = y0; y <= y1; y++) { + const py = y + 0.5; + for (let x = x0; x <= x1; x++) { + const px = x + 0.5; + const w0 = + ((s[1][0] - px) * (s[2][1] - py) - (s[2][0] - px) * (s[1][1] - py)) / + area; + const w1 = + ((s[2][0] - px) * (s[0][1] - py) - (s[0][0] - px) * (s[2][1] - py)) / + area; + const w2 = 1 - w0 - w1; + if (w0 < 0 || w1 < 0 || w2 < 0) continue; + const z = w0 * s[0][2] + w1 * s[1][2] + w2 * s[2][2] + polyOffset; + const i = y * size + x; + if (z < depth[i]) depth[i] = z; + } + } + } + return { + size, + depth, + vp, + dirToLight: L, + depthBias: -0.0005, + normalBiasWorld, + uvRadius: (1.5 * 1.35) / size, + }; +} + +/** Bilinear `LEQUAL` hardware-compare tap (`sampler2DArrayShadow`, LINEAR). */ +function compareTap(sm: CpuShadowMap, u: number, v: number, rz: number) { + const S = sm.size; + const tx = u * S - 0.5; + const ty = v * S - 0.5; + const ix = Math.floor(tx); + const iy = Math.floor(ty); + const fx = tx - ix; + const fy = ty - iy; + const at = (x: number, y: number) => { + const cx = Math.min(S - 1, Math.max(0, x)); + const cy = Math.min(S - 1, Math.max(0, y)); + return rz <= sm.depth[cy * S + cx] ? 1 : 0; + }; + return ( + (at(ix, iy) * (1 - fx) + at(ix + 1, iy) * fx) * (1 - fy) + + (at(ix, iy + 1) * (1 - fx) + at(ix + 1, iy + 1) * fx) * fy + ); +} + +const VOGEL_DISK = [ + [0.1768, 0.0], + [-0.2265, 0.2078], + [0.0355, -0.415], + [0.3204, 0.3888], + [-0.5562, -0.1455], + [0.4916, -0.3806], + [-0.1419, 0.6596], + [-0.5177, -0.515], +]; + +/** CPU port of `shdEval` (receiver normal-offset + depth bias + 8-tap PCF). */ +function evalShadow( + sm: CpuShadowMap, + wp: number[], + N: number[], + rotAngle = 0, +): number { + const L = sm.dirToLight; + const nl = N[0] * L[0] + N[1] * L[1] + N[2] * L[2]; + if (nl <= 0) return 0; + const off = sm.normalBiasWorld * SHADOW_RECEIVER_NORMAL_BIAS_SCALE * (1 - nl); + const c = xformPoint(sm.vp, [ + wp[0] + N[0] * off, + wp[1] + N[1] * off, + wp[2] + N[2] * off, + ]); + const u = c[0] * 0.5 + 0.5; + const v = c[1] * 0.5 + 0.5; + const z = c[2] * 0.5 + 0.5; + if (u <= 0.002 || u >= 0.998 || v <= 0.002 || v >= 0.998 || z > 1 || z < 0) { + return 1; + } + const rz = Math.min(1, Math.max(0, z + sm.depthBias)); + const ca = Math.cos(rotAngle); + const sa = Math.sin(rotAngle); + let sum = 0; + for (const [dx, dy] of VOGEL_DISK) { + const rx = ca * dx - sa * dy; + const ry = sa * dx + ca * dy; + sum += compareTap(sm, u + rx * sm.uvRadius, v + ry * sm.uvRadius, rz); + } + return sum / 8; +} + +function minShadowOverFrontFace( + sm: CpuShadowMap, + yMin: number, + yMax: number, + yStep: number, +): {min: number; worstY: number} { + let min = 1; + let worstY = NaN; + for (let y = yMin; y <= yMax + 1e-9; y += yStep) { + for (let x = -2.5; x <= 2.5 + 1e-9; x += 0.125) { + for (const rot of [0, 1.7, 4.1]) { + const f = evalShadow(sm, [x, y, 0], [0, 0, 1], rot); + if (f < min) { + min = f; + worstY = y; + } + } + } + } + return {min, worstY}; +} + +async function runFlushWallShadowRegressionTests() { + console.log('\n🧱 Flush multi-story wall shadow regression (CPU raster)'); + + // Shader parity: both depth passes shrink casters inward (-N). + assert( + /wp\.xyz-=wn\*\(uBiasRay\.w\*/.test(VS_SHADOW_DEPTH) && + !/wp\.xyz\+=wn\*/.test(VS_SHADOW_DEPTH), + 'WebGL2 VS_SHADOW_DEPTH shrinks casters inward along -N (never inflates +N)', + ); + assert( + /wp\.xyz - un \* \(shd\.biasRay\.w/.test(SCENE_SHADOW_DEPTH_WGSL) && + !/wp\.xyz \+ un \*/.test(SCENE_SHADOW_DEPTH_WGSL), + 'WebGPU vsShadowDepth shrinks casters inward along -N (parity with WebGL2)', + ); + const ref = applyShadowCasterNormalBias( + [0, 0, 0], + [0, 0, 0], + [0, 0, 1], + [0, 0, -1], + 0.1, + ); + assert( + Math.abs(ref[2] + 0.015) < 1e-9, + 'applyShadowCasterNormalBias offsets by -N * bias * max(1-|N·ray|, 0.15)', + ); + + // Scene: 22m x 18m lawn + two vertically stacked, horizontally flush walls + // (y = 0..3 and y = 3..6) sharing the z = 0 outer face, plus a sloped slab + // and a sphere for acne checks. + const ground = new THREE.BoxGeometry(22, 0.1, 18).translate(0, -0.05, 0); + const lower = new THREE.BoxGeometry(6, 3, 0.3).translate(0, 1.5, -0.15); + const upper = new THREE.BoxGeometry(6, 3, 0.3).translate(0, 4.5, -0.15); + const roof = new THREE.BoxGeometry(3, 0.2, 3) + .rotateX(-0.6) + .translate(-7, 1.5, 5); + const sphere = new THREE.SphereGeometry(1, 48, 24).translate(7, 1.2, 5); + const tris = [ + ...geometryTris(ground), + ...geometryTris(lower), + ...geometryTris(upper), + ...geometryTris(roof), + ...geometryTris(sphere), + ]; + const sunDir = [0.35, 1.0, 0.9]; // toward the light: front, above, right + + const fixed = rasterizeShadowMap(tris, sunDir, 1024, productionCasterBias); + const legacy = rasterizeShadowMap( + tris, + sunDir, + 1024, + legacyInflatingCasterBias, + ); + assert( + fixed.normalBiasWorld > 0.04 && fixed.normalBiasWorld < 0.07, + `house+lawn normalBiasWorld is ~5–6 cm (got ${(fixed.normalBiasWorld * 100).toFixed(2)} cm)`, + ); + + // Eval-first: the legacy +N inflation must visibly darken the flush walls. + const legacyBand = minShadowOverFrontFace(legacy, 2.5, 2.999, 0.0025); + assert( + legacyBand.min < 0.95, + `legacy +N caster inflation darkens sunlit flush wall below the joint (min ${legacyBand.min.toFixed(3)} at y=${legacyBand.worstY.toFixed(3)})`, + ); + + const LIT = 1 - 1e-6; // PCF/bilinear weights sum to 1 within float error. + const band = minShadowOverFrontFace(fixed, 2.5, 2.999, 0.0025); + assert( + band.min >= LIT, + `no shadow darkening just below flush y=3 joint on sunlit lower wall (min ${band.min.toFixed(4)} at y=${band.worstY})`, + ); + const lowerFace = minShadowOverFrontFace(fixed, 0.25, 2.5, 0.05); + const upperFace = minShadowOverFrontFace(fixed, 3.001, 5.75, 0.05); + assert( + lowerFace.min >= LIT && upperFace.min >= LIT, + `shadow factor == 1.0 across both stacked flush wall front faces (lower ${lowerFace.min.toFixed(4)}, upper ${upperFace.min.toFixed(4)})`, + ); + + // Robustness: other sun azimuths/elevations and a 2048 map. + let sweepMin = 1; + for (const [dir, size] of [ + [[-0.5, 0.8, 1.0], 1024], + [[0.0, 1.4, 0.6], 1024], + [[0.8, 0.6, 1.0], 1024], + [[0.35, 1.0, 0.9], 2048], + ] as Array<[number[], number]>) { + const sm = rasterizeShadowMap(tris, dir, size, productionCasterBias); + sweepMin = Math.min( + sweepMin, + minShadowOverFrontFace(sm, 2.5, 2.999, 0.005).min, + minShadowOverFrontFace(sm, 3.001, 3.5, 0.01).min, + ); + } + assert( + sweepMin >= LIT, + `flush joint stays fully lit across sun directions and 1024/2048 maps (min ${sweepMin.toFixed(4)})`, + ); + + // Sanity: the walls still cast a real shadow onto the lawn behind them. + const behind = evalShadow(fixed, [-0.5, 0, -3], [0, 1, 0]); + const openLawn = evalShadow(fixed, [0, 0, 6], [0, 1, 0]); + assert( + behind === 0 && openLawn >= LIT, + `walls still shadow the lawn behind them (behind=${behind}, open=${openLawn})`, + ); + + // Zero self-shadow acne on sloped and curved lit surfaces. + const L = fixed.dirToLight; + let acneMin = 1; + let acneSamples = 0; + const acneTris = [ + ...geometryTris(roof), + ...geometryTris(sphere), + ...geometryTris(ground), + ]; + for (const t of acneTris) { + for (const [a, b] of [ + [1 / 3, 1 / 3], + [0.6, 0.2], + [0.2, 0.6], + [0.2, 0.2], + ]) { + const c = 1 - a - b; + const p = [0, 1, 2].map( + (k) => t.p[0][k] * a + t.p[1][k] * b + t.p[2][k] * c, + ); + let n = [0, 1, 2].map( + (k) => t.n[0][k] * a + t.n[1][k] * b + t.n[2][k] * c, + ); + const nl = Math.hypot(n[0], n[1], n[2]) || 1; + n = n.map((v) => v / nl); + if (n[0] * L[0] + n[1] * L[1] + n[2] * L[2] < 0.1) continue; + // Skip lawn legitimately shadowed by the walls/slab/sphere. + if (p[1] < 0.01 && (Math.abs(p[0]) < 4.5 || p[2] < 7)) continue; + acneSamples++; + for (const rot of [0, 2.3]) { + acneMin = Math.min(acneMin, evalShadow(fixed, p, n, rot)); + } + } + } + assert( + acneSamples > 500 && acneMin >= LIT, + `zero self-shadow acne on sloped slab + sphere lit surfaces (${acneSamples} samples, min ${acneMin.toFixed(3)})`, + ); +} + +/** + * `` (no ``): toggling the attribute + * clips the upper half of a mesh in the shadow depth pass. + */ +async function runSectionPlaneShadowTests() { + console.log('\n✂️ section-plane shadow pass (no xr-live)'); + const attrs = new Map(); + const container = { + getAttribute: (n: string) => attrs.get(n) ?? null, + }; + const secPlanes: number[][] = []; + const {gl, rec} = makeMockShadowGl({ + uniform4f: ( + loc: {name?: string} | null, + x: number, + y: number, + z: number, + w: number, + ) => { + if (loc?.name === 'uSecPlane') secPlanes.push([x, y, z, w]); + }, + }); + const box = new THREE.BoxGeometry(2, 2, 2); + const viewer = { + gl, + canvas: {width: 800, height: 600}, + shadowMaps: 'pcf', + container, + modelRootMatrix: makeIdentityMat4(), + meshes: [ + { + name: 'SectionBox', + visible: true, + castShadow: true, + receiveShadow: true, + transform: makeIdentityMat4(), + primitives: [ + { + vao: {} as WebGLVertexArrayObject, + indexCount: box.index!.array.length, + indexType: 5123, + indices: box.index!.array, + positions: box.attributes.position.array, + baseColor: [1, 1, 1, 1], + }, + ], + }, + ], + lights: [ + {type: 'directional', direction: [0.3, 1, 0.5], shadow: {cast: true}}, + ], + uRender: {}, + recompileRenderProgram: () => {}, + }; + const last = (a: T[]): T | undefined => a[a.length - 1]; + const secOn = () => + rec.uniform1i.filter(([n]) => n === 'uSecOn').map(([, v]) => v); + + // CPU fragment survival mirroring FS_SHADOW_DEPTH's discard test. + const survivingFraction = (plane: number[] | null) => { + const pos = box.attributes.position.array; + const idx = box.index!.array; + let kept = 0; + let total = 0; + for (let t = 0; t < idx.length; t += 3) { + for (let a = 0.05; a < 1; a += 0.1) { + for (let b = 0.05; a + b < 1; b += 0.1) { + const c = 1 - a - b; + const p = [0, 1, 2].map( + (k) => + pos[idx[t] * 3 + k] * a + + pos[idx[t + 1] * 3 + k] * b + + pos[idx[t + 2] * 3 + k] * c, + ); + total++; + const d = plane + ? p[0] * plane[0] + p[1] * plane[1] + p[2] * plane[2] + : -1; + if (!plane || d <= plane[3]) kept++; + if (plane && d > plane[3] && p[1] < -1e-6) return -1; // lower half clipped! + } + } + } + return kept / total; + }; + + shadowMapsPlugin.onBeforeDrawScene!(viewer as unknown as ThreeView, gl); + const passes0 = getShadowMapStats(viewer).renderedPasses; + assert( + last(secOn()) === 0 && survivingFraction(null) === 1, + 'section-plane absent: shadow depth pass uploads uSecOn=0 (full caster)', + ); + + attrs.set('section-plane', 'y:0.0'); + shadowMapsPlugin.onBeforeDrawScene!(viewer as unknown as ThreeView, gl); + const plane = last(secPlanes) ?? null; + const frac = survivingFraction(plane); + assert( + getShadowMapStats(viewer).renderedPasses > passes0 && + last(secOn()) === 1 && + plane !== null && + plane[1] === 1 && + plane[3] === 0 && + frac > 0.4 && + frac < 0.6, + `section-plane="y:0.0" re-renders shadows with uSecOn=1, plane (0,1,0,0), clipping the upper half of the caster (kept ${(frac * 100).toFixed(1)}%)`, + ); + + attrs.set('section-plane', 'none'); + const passes1 = getShadowMapStats(viewer).renderedPasses; + shadowMapsPlugin.onBeforeDrawScene!(viewer as unknown as ThreeView, gl); + assert( + getShadowMapStats(viewer).renderedPasses > passes1 && last(secOn()) === 0, + 'section-plane="none" invalidates the shadow digest and restores the full caster (uSecOn=0)', + ); + shadowMapsPlugin.onDestroy!(gl, viewer); +} + async function runShadowMapsTests() { console.log('🌑 Running Multi-Light Shadow Maps (Phase A) Unit Tests...\n'); @@ -695,6 +1229,9 @@ async function runShadowMapsTests() { 'onDestroy deletes viewer shadow TEXTURE_2D_ARRAY, FBO, and shared dummy resources', ); + await runFlushWallShadowRegressionTests(); + await runSectionPlaneShadowTests(); + console.log( `\n📊 Shadow Maps Tests Summary: ${passed} passed, ${failed} failed.`, ); diff --git a/three-live/tests/three_live_element_test.ts b/three-live/tests/three_live_element_test.ts index 310a7258..1f6071ed 100644 --- a/three-live/tests/three_live_element_test.ts +++ b/three-live/tests/three_live_element_test.ts @@ -353,6 +353,43 @@ async function runElementTests() { 'toneMapping getter reads attribute', ); + { + // section-plane is observed on (not only ) and + // toggling it schedules a redraw of the color + shadow passes. + assert( + ThreeLiveElement.observedAttributes.includes('section-plane'), + 'observedAttributes contains section-plane', + ); + let renders = 0; + const withViewer = instance as unknown as {viewer: unknown}; + const prevViewer = withViewer.viewer; + withViewer.viewer = { + render: () => { + renders++; + }, + }; + assert( + instance.sectionPlane === 'none', + 'sectionPlane getter defaults to "none"', + ); + instance.setAttribute('section-plane', 'y:0.0'); + assert( + renders === 1 && instance.sectionPlane === 'y:0.0', + 'setAttribute("section-plane", "y:0.0") re-renders the viewer', + ); + instance.sectionPlane = 'none'; + assert( + renders === 2 && attributes.get('section-plane') === 'none', + 'sectionPlane setter updates attribute and re-renders', + ); + instance.sectionPlane = null; + assert( + renders === 3 && !attributes.has('section-plane'), + 'sectionPlane = null removes the attribute and re-renders', + ); + withViewer.viewer = prevViewer; + } + { // tone-mapping is normalized, and removing it restores neutral. let viewerMode = 'unset'; diff --git a/three-live/tests/three_view_test.ts b/three-live/tests/three_view_test.ts index 45e84ee1..89c2ca4b 100644 --- a/three-live/tests/three_view_test.ts +++ b/three-live/tests/three_view_test.ts @@ -2995,6 +2995,118 @@ async function runThreeViewTests() { ); } + // (no xr-live): ThreeView.render binds + // uSectionEnabled/uSectionPlane from the host attribute on every primitive. + { + const secAttrs = new Map(); + const draws: Array<{enabled: number; plane: number[] | null}> = []; + let curEnabled = 0; + let curPlane: number[] | null = null; + const secGl: any = new Proxy( + { + canvas: {width: 400, height: 400}, + getShaderParameter: () => true, + getProgramParameter: () => true, + getUniformLocation: (_p: any, name: string) => ({name}), + uniform1i: (loc: any, v: number) => { + if (loc?.name === 'uSectionEnabled') curEnabled = v; + }, + uniform4f: (loc: any, x: number, y: number, z: number, w: number) => { + if (loc?.name === 'uSectionPlane') curPlane = [x, y, z, w]; + }, + drawElements: () => { + draws.push({enabled: curEnabled, plane: curPlane}); + }, + }, + { + get(t, p) { + return p in t ? (t as any)[p] : () => ({}); + }, + }, + ); + const secCanvas: any = {...mockCanvas, getContext: () => secGl}; + const secContainer: any = { + ...secCanvas, + getAttribute: (n: string) => secAttrs.get(n) ?? null, + hasAttribute: (n: string) => secAttrs.has(n), + }; + const secScene = new THREE.Scene(); + const secBox = new THREE.Mesh( + new THREE.BoxGeometry(2, 2, 2), + new THREE.MeshStandardMaterial({color: 0xcccccc}), + ); + secBox.name = 'SectionBox'; + secScene.add(secBox); + const secView = new ThreeView(secContainer, secCanvas, {autoStart: false}); + secView.loadGLBData(parseGLB(secScene.toGLB())); + // Identity model root so the authored plane maps 1:1 to world space. + (secView as any).modelRootMatrix = mat4Create(); + + // CPU fragment survival mirroring FS_RENDER's discard on box surface samples. + const keptFraction = (d: {enabled: number; plane: number[] | null}) => { + const pos = secBox.geometry.attributes.position.array; + const idx = secBox.geometry.index!.array; + let kept = 0; + let total = 0; + let lowerClipped = false; + for (let t = 0; t < idx.length; t += 3) { + for (let a = 0.05; a < 1; a += 0.1) { + for (let b = 0.05; a + b < 1; b += 0.1) { + const c = 1 - a - b; + const p = [0, 1, 2].map( + (k) => + pos[idx[t] * 3 + k] * a + + pos[idx[t + 1] * 3 + k] * b + + pos[idx[t + 2] * 3 + k] * c, + ); + total++; + const pl = d.plane; + const discard = + d.enabled === 1 && + pl !== null && + p[0] * pl[0] + p[1] * pl[1] + p[2] * pl[2] > pl[3]; + if (!discard) kept++; + else if (p[1] < -1e-6) lowerClipped = true; + } + } + } + return lowerClipped ? -1 : kept / total; + }; + + draws.length = 0; + secView.render(); + const d0 = draws[draws.length - 1]; + assert( + draws.length > 0 && d0.enabled === 0 && keptFraction(d0) === 1, + 'ThreeView.render: no section-plane -> uSectionEnabled=0 (mesh fully drawn)', + ); + + secAttrs.set('section-plane', 'y:0.0'); + draws.length = 0; + secView.render(); + const d1 = draws[draws.length - 1]; + const k1 = d1 ? keptFraction(d1) : -1; + assert( + d1 !== undefined && + d1.enabled === 1 && + d1.plane !== null && + Math.abs(d1.plane[1] - 1) < 1e-6 && + Math.abs(d1.plane[3]) < 1e-6 && + k1 > 0.4 && + k1 < 0.6, + ` clips the upper half of the mesh in the WebGL2 color pass without xr-live (kept ${(k1 * 100).toFixed(1)}%)`, + ); + + secAttrs.set('section-plane', 'none'); + draws.length = 0; + secView.render(); + const d2 = draws[draws.length - 1]; + assert( + d2 !== undefined && d2.enabled === 0 && keptFraction(d2) === 1, + 'section-plane="none" restores the unclipped mesh (uSectionEnabled=0)', + ); + } + console.log( `\n🏆 three-view Test Results: ${passed} Passed, ${failed} Failed.`, ); diff --git a/three-live/tests/three_webgpu_test.ts b/three-live/tests/three_webgpu_test.ts index edb9c0bb..c1a17f3d 100644 --- a/three-live/tests/three_webgpu_test.ts +++ b/three-live/tests/three_webgpu_test.ts @@ -18,6 +18,8 @@ import * as assert from 'assert'; import {mat4LookAt, mat4Multiply, mat4Perspective} from '../src/math'; import {getSharedRegistry} from '../src/plugin'; +import {SHADOW_RECEIVER_NORMAL_BIAS_SCALE} from '../src/plugins/shadow-maps'; +import {resolveSectionPlane} from '../src/section-plane'; import {ThreeLiveElement} from '../src/three-live-element'; import {ThreeView} from '../src/three-view'; import { @@ -50,6 +52,7 @@ import { SCENE_FLAG_HAS_ENV_MAP, SCENE_FLAG_RIGHT_EYE, SCENE_FLAG_SECTION_ENABLED, + SCENE_SHADOW_DEPTH_WGSL, } from '../src/webgpu/shaders'; interface RecordedWrite { @@ -846,6 +849,92 @@ async function runTests(): Promise { ); }); + await test('WebGPU shadow bias parity: inward caster shrink + full receiver normal bias', () => { + assert.ok( + /wp\.xyz - un \* \(shd\.biasRay\.w/.test(SCENE_SHADOW_DEPTH_WGSL) && + !/wp\.xyz \+ un \*/.test(SCENE_SHADOW_DEPTH_WGSL), + 'vsShadowDepth shrinks casters along -N (no +N inflation past flush receivers)', + ); + const buf = new ArrayBuffer(SCENE_UNIFORM_BYTES); + const vp = new Float32Array([ + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, + ]); + writeSceneUniforms(buf, { + vp, + modelRoot: vp, + eyePos: [0, 0, 5], + exposure: 1, + envIntensity: 1, + toneMappingIndex: 0, + lights: [], + hasEnvMap: false, + shadowMap: { + slices: [ + { + slot: 0, + viewProj: vp, + rayDir: [0, -1, 0], + depthBias: -0.0005, + normalBiasWorld: 0.055, + uvRadius: 0.002, + }, + ], + dirSlots: [0, -1], + ptSlots: [-1, -1], + }, + } as unknown as Parameters[1]); + const f = new Float32Array(buf); + assert.strictEqual( + f[181], + Math.fround(0.055 * SHADOW_RECEIVER_NORMAL_BIAS_SCALE), + 'WebGPU receiver normal bias matches WebGL2 uShadowParams.y', + ); + }); + + await test(' toggles WebGPU scene section uniforms without xr-live', () => { + const attrs = new Map(); + const viewerLike = { + container: {getAttribute: (n: string) => attrs.get(n) ?? null}, + meshes: [], + }; + const pack = () => { + const buf = new ArrayBuffer(SCENE_UNIFORM_BYTES); + const vp = new Float32Array([ + 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, + ]); + writeSceneUniforms(buf, { + vp, + modelRoot: vp, + eyePos: [0, 0, 5], + exposure: 1, + envIntensity: 1, + toneMappingIndex: 0, + lights: [], + hasEnvMap: false, + sectionPlane: resolveSectionPlane(viewerLike), + }); + return {f: new Float32Array(buf), u: new Uint32Array(buf)}; + }; + attrs.set('section-plane', 'y:0.0'); + const on = pack(); + assert.ok( + (on.u[115] & SCENE_FLAG_SECTION_ENABLED) !== 0, + 'section enabled', + ); + assert.deepStrictEqual( + [on.f[100], on.f[101], on.f[102], on.f[103]], + [0, 1, 0, 0], + 'y:0.0 -> plane (0,1,0,0) clips the upper half', + ); + attrs.set('section-plane', 'none'); + const off = pack(); + assert.strictEqual( + off.u[115] & SCENE_FLAG_SECTION_ENABLED, + 0, + 'none -> disabled', + ); + }); + await test('5,000-part CAD assembly compiles into 1 GPURenderBundle with 0 part uploads during orbit & turntable', () => { const harness = createMockHarness(800, 600); const gpu = createMockGPUDevice(); @@ -1430,7 +1519,9 @@ async function runTests(): Promise { const glbData = buildMultiPartCadGLBData(1); // Add COLOR_0 accessor to the primitive const binOld = new Uint8Array(glbData.bin); - const colFloats = new Float32Array([0.9, 0.1, 0.2, 0.2, 0.9, 0.1, 0.1, 0.2, 0.9]); + const colFloats = new Float32Array([ + 0.9, 0.1, 0.2, 0.2, 0.9, 0.1, 0.1, 0.2, 0.9, + ]); const colBytes = new Uint8Array( colFloats.buffer, colFloats.byteOffset, diff --git a/xr-live/src/plugins/exploded-view.ts b/xr-live/src/plugins/exploded-view.ts index f03e0717..1a2ec580 100644 --- a/xr-live/src/plugins/exploded-view.ts +++ b/xr-live/src/plugins/exploded-view.ts @@ -1057,11 +1057,9 @@ export const explodedViewPlugin: ThreeLivePlugin = { meshGpu: any, ): void { const section = activeSectionByGl.get(gl); - if (!section || !section.enabled) { - const cached = sectionUniformCache.get(program); - if (cached?.enabled) gl.uniform1i(cached.enabled, 0); - return; - } + // Inactive: leave the core `ThreeView` section-plane binding untouched + // (it already resets `uSectionEnabled` for every primitive). + if (!section || !section.enabled) return; let locs = sectionUniformCache.get(program); if (!locs) { locs = { diff --git a/xr-live/src/xr-live-element.ts b/xr-live/src/xr-live-element.ts index 947957b2..77e639a9 100644 --- a/xr-live/src/xr-live-element.ts +++ b/xr-live/src/xr-live-element.ts @@ -127,7 +127,6 @@ export class XRLiveElement extends ThreeLiveElement { 'explode', 'explode-mode', 'explode-scale', - 'section-plane', 'persistent-anchors', 'persist-url-hash', 'locomotion', diff --git a/xr-live/tests/xr_plugins_test.ts b/xr-live/tests/xr_plugins_test.ts index c5da2792..cb88b112 100644 --- a/xr-live/tests/xr_plugins_test.ts +++ b/xr-live/tests/xr_plugins_test.ts @@ -2462,6 +2462,21 @@ function testGoldenParity(): void { path.resolve(__dirname, '../../testdata/golden'), path.resolve(__dirname, '../testdata/golden'), path.resolve(process.cwd(), 'testdata/golden'), + // Blaze/Forge: the bundled test may be a symlink into a content store, so + // `__dirname` (realpath) can land outside the runfiles tree. The entry + // path passed to node (`process.argv[1]`) keeps the symlinked location. + ...(process.argv[1] + ? [ + path.resolve( + path.dirname(path.resolve(process.argv[1])), + '../testdata/golden', + ), + path.resolve( + path.dirname(path.resolve(process.argv[1])), + '../../testdata/golden', + ), + ] + : []), ]; const goldenDir = goldenCandidates.find((d: string) => diff --git a/xr-live/tests/xr_sim_test.ts b/xr-live/tests/xr_sim_test.ts index 9b967729..0a683cb1 100644 --- a/xr-live/tests/xr_sim_test.ts +++ b/xr-live/tests/xr_sim_test.ts @@ -1621,6 +1621,21 @@ function testGoldenParity() { path.resolve(__dirname, '../../testdata/golden'), path.resolve(__dirname, '../testdata/golden'), path.resolve(process.cwd(), 'testdata/golden'), + // Blaze/Forge: the bundled test may be a symlink into a content store, so + // `__dirname` (realpath) can land outside the runfiles tree. The entry + // path passed to node (`process.argv[1]`) keeps the symlinked location. + ...(process.argv[1] + ? [ + path.resolve( + path.dirname(path.resolve(process.argv[1])), + '../testdata/golden', + ), + path.resolve( + path.dirname(path.resolve(process.argv[1])), + '../../testdata/golden', + ), + ] + : []), ]; const dir = dirs.find((d: string) => fs.existsSync(path.join(d, 'sim_scene.json')),