master
AdityaAngajala v0.13.0 12542ed
import { Engine } from '@babylonjs/core/Engines/engine';
import { Scene } from '@babylonjs/core/scene';
import { AdomCamera } from './Camera/AdomCamera';
import type { Nullable } from '@babylonjs/core/types';
import { ShadowGenerator } from '@babylonjs/core/Lights/Shadows/shadowGenerator';
import type { SpotLight } from '@babylonjs/core/Lights/spotLight';
import type { HemisphericLight } from '@babylonjs/core/Lights/hemisphericLight';
import { RenderTargetTexture } from '@babylonjs/core/Materials/Textures/renderTargetTexture';

// The highest display density the scene renders at (see init).
const MAX_DEVICE_RATIO = 2;

// Contexts that hold a shadow generator. Each viewer has its own engine, so
// each shadow map is a separate GPU allocation, and an 8192 x 8192 map is
// about 256 MB: the edge length shrinks as more of them are live.
const shadowed = new Set<ViewerContext>();

/**
 * The largest shadow map this device gets: 2048 on a phone or tablet (a coarse
 * pointer on a screen up to 1400 px) or a device reporting 4 GB of memory or
 * less, else 8192. At 8192 with percentage-closer filtering the map is a
 * half-float color target plus a depth texture, several hundred MB; on iOS,
 * where a page and its frames share one content process, that killed the tab
 * and reloaded it, over and over (wiki component pages, 2026-10-23; 0.12.4).
 */
export function deviceShadowCap(): number {
    try {
        const coarse = typeof window.matchMedia === 'function' && window.matchMedia('(pointer: coarse)').matches;
        const small = Math.max(window.screen.width, window.screen.height) <= 1400;
        const memory = (navigator as unknown as { deviceMemory?: number }).deviceMemory;
        if ((coarse && small) || (typeof memory === 'number' && memory <= 4)) return 2048;
    } catch { /* no window: a desktop size */ }
    return 8192;
}

/** The shadow map edge length while `count` viewers have shadows, within the device's cap. */
export function shadowMapSize(count: number): number {
    return Math.min(count <= 1 ? 8192 : count <= 4 ? 4096 : 2048, deviceShadowCap());
}

function resizeShadowMaps(): void {
    const size = shadowMapSize(shadowed.size);
    for (const ctx of shadowed) {
        const sg = ctx.shadowGenerator;
        if (!sg || sg.mapSize === size) continue;
        // Babylon rebuilds the map (keeping its casters); refreshShadows
        // puts this viewer's refresh rate back on the new one.
        sg.mapSize = size;
        ctx.refreshShadows();
    }
}

/**
 * One viewer's engine, scene, camera and lighting rig. Each viewer owns one,
 * so several viewers on a page each render into their own canvas and
 * disposing one leaves the others running.
 */
export class ViewerContext {
    public engine: Nullable<Engine> = null;
    public scene: Nullable<Scene> = null;
    public camera: Nullable<AdomCamera> = null;
    public shadowGenerator: Nullable<ShadowGenerator> = null;
    public spotLight: Nullable<SpotLight> = null;
    /** Bottom-fill hemispheric light — illuminates the underside of parts.
     *  Default OFF (intensity 0). Toggleable via ThreeDViewer.setBottomLight(). */
    public bottomLight: Nullable<HemisphericLight> = null;
    /** The view cube's own scene, drawn over a corner of the canvas; null without a view cube. */
    public viewCubeScene: Nullable<Scene> = null;

    /**
     * Initialize the engine and scene. A second call on the same context
     * does nothing.
     * @param canvas - The canvas element to render to
     * @param zUp - If true, use Z-up coordinate system (default). If false, use Y-up (Babylon default).
     */
    public async init(canvas: HTMLCanvasElement, zUp: boolean = true): Promise<void> {
        if (this.engine && this.scene && this.camera) {
            return;
        }

        // preserveDrawingBuffer + stencil: without them the backbuffer is
        // undefined after the frame is presented, so canvas.toDataURL() and
        // any consumer-side capture return a blank image (adom/wiki#60 item
        // 9). Babylon's own CreateScreenshotUsingRenderTarget re-renders into
        // an RTT and does not need this, but consumers reaching for the canvas
        // directly do, and the cost is one retained buffer.
        // adaptToDeviceRatio: render at the display's pixel density, not at
        // CSS pixels, or a 2x (Retina) screen shows the scene upscaled and
        // blurry next to the page's text. Capped at 2x: a 3x phone would pay
        // 9x the fill of 1x for detail nobody can see at that size.
        this.engine = new Engine(canvas, true, {
            useHighPrecisionFloats: true,
            preserveDrawingBuffer: true,
            stencil: true,
            limitDeviceRatio: MAX_DEVICE_RATIO,
        }, true);
        // Decode images (environment mip levels, GLB-embedded textures) as
        // ImageBitmaps instead of <img src="blob:...">. Babylon's default on
        // WebGL builds a blob URL per image, and a sandboxed frame whose CSP
        // has no blob: in img-src (the wiki's widget and readme frames)
        // blocks every one of them: the environment never uploads and the
        // materials wait forever (adom/adom-3d-viewer#5). createImageBitmap
        // takes the Blob directly; no URL, no fetch, nothing for a CSP to see.
        if (typeof createImageBitmap === 'function') {
            (this.engine as any)._features.forceBitmapOverHTMLImageElement = true;
        }
        this.scene = new Scene(this.engine);
        this.scene.useRightHandedSystem = zUp;

        this.camera = new AdomCamera(this.scene, canvas, zUp);
        this.camera.disableBounds();
        this.camera.setClickToSetRotationPoint(false);
        this.scene.activeCamera = this.camera;
    }

    /**
     * Re-read the display's pixel density (the window moved to a screen with
     * a different one, or the page zoom changed) and resize to it.
     */
    public syncDeviceRatio(): void {
        if (!this.engine) return;
        const ratio = Math.min(window.devicePixelRatio || 1, MAX_DEVICE_RATIO);
        if (Math.abs(this.engine.getHardwareScalingLevel() - 1 / ratio) > 1e-6) {
            this.engine.setHardwareScalingLevel(1 / ratio);
        }
        this.engine.resize();
    }

    /**
     * Create the shadow generator for `light` and store it on this context.
     * Every live viewer's shadow map is then sized for the new count (see
     * shadowMapSize).
     */
    public createShadowGenerator(light: SpotLight): ShadowGenerator {
        shadowed.add(this);
        const sg = new ShadowGenerator(shadowMapSize(shadowed.size), light);
        this.shadowGenerator = sg;
        resizeShadowMaps();
        return sg;
    }

    /**
     * Releases everything this context created. The context is empty, the
     * camera's listeners and the shadow map are gone at once; the scene and
     * engine may follow a moment later (see below).
     */
    public dispose(): void {
        const { scene, engine, camera, shadowGenerator, spotLight, bottomLight } = this;
        this.scene = null;
        this.engine = null;
        this.camera = null;
        this.shadowGenerator = null;
        this.spotLight = null;
        this.bottomLight = null;
        this.viewCubeScene = null;
        shadowed.delete(this);
        engine?.stopRenderLoop();
        camera?.dispose();
        // The shadow map is the largest allocation and no texture decode
        // reads it, so it goes now rather than with the scene; the other
        // viewers' maps then grow back.
        if (shadowGenerator) {
            shadowGenerator.dispose();
            resizeShadowMaps();
        }
        const release = () => {
            spotLight?.dispose();
            bottomLight?.dispose();
            scene?.dispose();
            engine?.dispose();
        };
        // Babylon finishes an RGBD texture (the environment map, and the
        // lighting lookup texture the first PBR material creates) after its
        // load event: it decodes the data through an async shader import and
        // compile, then reads the texture's scene. A scene disposed inside
        // that window makes the callback throw. The texture stays not ready
        // from its creation to the end of that decode, and Babylon has no
        // event for the end, so the scene is kept until no texture is still
        // loading or decoding: each one is ready or has a load error. Two
        // quiet checks in a row catch a decode that hands off to another in
        // a later task. The 30 s backstop is only for a decode that never
        // ends (a shader that fails to compile); it is not a guess at how
        // long a decode takes.
        const pending = () => !!scene && scene.textures.some(t => {
            const internal = t.getInternalTexture();
            return !!internal && !internal.isReady && !t.loadingError;
        });
        const until = performance.now() + 30_000;
        let quiet = 0;
        const poll = () => {
            quiet = pending() ? 0 : quiet + 1;
            if (quiet >= 2 || performance.now() > until) release();
            else setTimeout(poll, 50);
        };
        poll();
    }

    private _pcssTransparencyWarned = false;

    /**
     * PCSS combined with soft transparent shadows renders NO shadows at all,
     * silently (pixel-diff proven: PCSS 0.0% change, PCF 26.7%). Auto-correct
     * to PCF so consumers flipping useContactHardeningShadow on a scene with
     * enableSoftTransparentShadow don't lose shadows. Called from
     * refreshShadows and once per frame (two boolean reads, negligible).
     */
    public enforceShadowFilterCompat(): void {
        const sg = this.shadowGenerator;
        if (!sg) return;
        if (sg.useContactHardeningShadow && sg.enableSoftTransparentShadow) {
            if (!this._pcssTransparencyWarned) {
                this._pcssTransparencyWarned = true;
                console.warn(
                    '[adom-3d-viewer] PCSS (useContactHardeningShadow) + enableSoftTransparentShadow ' +
                    'silently renders no shadows. Falling back to PCF (usePercentageCloserFiltering). ' +
                    'Use PCF whenever soft transparent shadows are enabled.'
                );
            }
            sg.useContactHardeningShadow = false;
            sg.usePercentageCloserFiltering = true;
        }
    }

    /**
     * Consumer override for the shadow map refresh rate (adom/wiki#60 item 7).
     *
     * null means "auto": every frame for animated content, once for static.
     * Set a RenderTargetTexture.REFRESHRATE_* value to pin it. Without this an
     * external caller who set refreshRate through getShadowGenerator() had it
     * silently reverted by the next refreshShadows(), which fires on every
     * load, frame and layer toggle. Content driven from OUTSIDE the viewer
     * (a consumer animating an added content root) has no animationGroups on
     * the scene, so auto-detection cannot see it and guesses wrong.
     */
    public shadowRefreshRateOverride: number | null = null;

    /**
     * Re-renders the shadow map once. Defers by one frame so that any light
     * frustum or caster-list changes from the current frame are applied first.
     */
    public refreshShadows(): void {
        if (!this.shadowGenerator || !this.scene) return;
        const sg = this.shadowGenerator;
        const shadowMap = sg.getShadowMap();
        if (!shadowMap) return;

        this.enforceShadowFilterCompat();

        if (this.shadowRefreshRateOverride !== null) {
            shadowMap.refreshRate = this.shadowRefreshRateOverride;
            return;
        }

        // Animated models (glTF animationGroups, e.g. a press-fit insertion or a
        // spin) need the shadow map re-rendered EVERY frame so the cast shadows
        // track the moving meshes. A one-shot render freezes the shadow at frame 0,
        // which reads as broken (the pin moves, its shadow does not). Keep the
        // cheap render-once only for fully static models.
        const hasAnimation = (this.scene.animationGroups || []).length > 0;
        if (hasAnimation) {
            shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME;
            return;
        }

        this.scene.onAfterRenderObservable.addOnce(() => {
            // An override set after this was queued wins.
            if (this.shadowRefreshRateOverride !== null) return;
            shadowMap.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
            shadowMap.resetRefreshCounter();
        });
    }
}