master
Colby Knox 0.9.1: American English in the help card, README and comments 69feee6
/**
 * Lights that arrive INSIDE a GLB (KHR_lights_punctual), as John's LED
 * component models now do: an Adom.LED.State group holding the emissive lens
 * skin and a real spot light (adom/adom-3d-viewer#7).
 *
 * The viewer never creates these and never edits their photometry: glTF range
 * is meters and intensity candela, and neither follows a node matrix, so a
 * viewer that rescaled them would turn a 15 mm throw into 15 m. What the
 * viewer owns is the BUDGET. Babylon's materials light at most
 * maxSimultaneousLights (4 by default, and the viewer's own key and fill
 * lights already take three of those), so a board with forty lit LEDs cannot
 * light every surface with every LED. Each frame's nearest and brightest N
 * content lights stay on; the rest go dark as lights while their emissive
 * lens keeps glowing, which is what a person sees on a real board anyway.
 *
 * Shadows stay off: one shadow generator per LED does not scale, and the
 * viewer's ground shadow comes from its own key light.
 */
import type { Scene } from '@babylonjs/core/scene';

type AnyLight = any;

export type ContentLightRow = {
    /** Node name from the GLB (e.g. Adom.LED.Light). */
    name: string;
    /** extras.adomRole on the light node or its parent, when the content set one. */
    role: string | null;
    /** As authored: candela and meters, never rescaled by the viewer. */
    intensity: number;
    range: number;
    /** The light's own switch (the budget turns this on and off). */
    enabled: boolean;
    /** Lit right now: its own switch AND every ancestor group enabled. */
    active: boolean;
    /** World position the budget scored it at. */
    position: { x: number; y: number; z: number };
};

type Item = {
    light: AnyLight;
    role: string | null;
    intensity: number;
    range: number;
    /** World position, resolved once (see refreshPositions). */
    x: number; y: number; z: number;
};

const DEFAULT_BUDGET = 4;
/** Ceiling for maxSimultaneousLights; past this, shaders pay for lights nobody sees. */
const MAX_MATERIAL_LIGHTS = 8;

function roleOf(light: AnyLight): string | null {
    let n: any = light;
    for (let depth = 0; n && depth < 3; depth++) {
        const r = n.metadata?.gltf?.extras?.adomRole;
        if (typeof r === 'string' && r.trim()) return r.trim().slice(0, 64);
        n = n.parent;
    }
    return null;
}

/** Ancestors enabled? (a light inside a switched-off state group is not lit). */
function ancestorsEnabled(light: AnyLight): boolean {
    let n: any = light.parent;
    for (let depth = 0; n && depth < 12; depth++) {
        if (n.isEnabled && n.isEnabled(false) === false) return false;
        n = n.parent;
    }
    return true;
}

export class ContentLights {
    private scene: Scene;
    private items: Item[] = [];
    private budget = DEFAULT_BUDGET;
    private viewerLightCount = 0;
    private observer: any = null;
    private lastRunAt = 0;
    private lastCamKey = '';
    private dirty = true;

    constructor(scene: Scene, budget?: number) {
        this.scene = scene;
        // The lights already in the scene when we start are the viewer's own
        // (key, fill, bottom); everything adopted later is content.
        this.viewerLightCount = scene.lights ? scene.lights.length : 0;
        if (typeof budget === 'number') this.budget = Math.max(0, Math.floor(budget));
    }

    /** Take the lights an import produced. Photometry is left exactly as authored. */
    adopt(lights: AnyLight[] | undefined | null, materials?: any[]): void {
        for (const light of lights || []) {
            if (!light || this.items.some(i => i.light === light)) continue;
            // #2: no per-LED shadows. Any generator attached later is the
            // caller's deliberate choice.
            light.shadowEnabled = false;
            this.items.push({
                light,
                role: roleOf(light),
                intensity: typeof light.intensity === 'number' ? light.intensity : 0,
                range: typeof light.range === 'number' ? light.range : 0,
                x: 0, y: 0, z: 0,
            });
        }
        this.refreshPositions();
        this.applyMaterialBudget(materials);
        this.dirty = true;
        this.update(true);
        this.attach();
    }

    /** Raise the per-material light cap to fit the viewer's lights plus the budget. */
    applyMaterialBudget(materials?: any[]): void {
        if (!this.items.length) return;
        const want = Math.min(this.viewerLightCount + this.budget, MAX_MATERIAL_LIGHTS);
        const list = materials && materials.length ? materials : (this.scene.materials || []);
        for (const m of list) {
            if (!m || typeof m.maxSimultaneousLights !== 'number') continue;
            if (m.maxSimultaneousLights < want) m.maxSimultaneousLights = want;
        }
    }

    private attach(): void {
        if (this.observer || !this.items.length) return;
        this.observer = this.scene.onBeforeRenderObservable.add(() => this.update(false));
    }

    detach(): void {
        if (this.observer) {
            this.scene.onBeforeRenderObservable.remove(this.observer);
            this.observer = null;
        }
    }

    /**
     * Dispose every adopted light and forget them. Content lights hang off
     * transform nodes rather than meshes, so disposing the mesh roots alone
     * leaves them in the scene lighting the NEXT model.
     */
    clear(): void {
        this.detach();
        for (const i of this.items) { try { i.light.dispose(); } catch { /* already gone */ } }
        this.items = [];
        this.lastCamKey = '';
        this.dirty = true;
    }

    count(): number { return this.items.length; }
    getBudget(): number { return this.budget; }

    setBudget(n: number): void {
        const next = Math.max(0, Math.floor(Number(n) || 0));
        if (next === this.budget) return;
        this.budget = next;
        this.applyMaterialBudget();
        this.dirty = true;
        this.update(true);
    }

    /** Switch every content light off (or back to budgeted behavior). */
    setEnabled(on: boolean): void {
        if (!on) {
            this.detach();
            for (const i of this.items) i.light.setEnabled(false);
            return;
        }
        this.dirty = true;
        this.update(true);
        this.attach();
    }

    /**
     * Resolve each light's world position. A transform node whose only child
     * is a light never gets its world matrix computed by the render loop (no
     * geometry hangs off it), so getAbsolutePosition would report the origin
     * for every LED on the board and the budget would pick arbitrarily.
     * Positions are static for a static model; call this again after moving
     * content.
     */
    refreshPositions(): void {
        for (const i of this.items) {
            try {
                let n: any = i.light.parent;
                const chain: any[] = [];
                for (let d = 0; n && d < 12; d++) { chain.push(n); n = n.parent; }
                for (let k = chain.length - 1; k >= 0; k--) chain[k].computeWorldMatrix?.(true);
                // Not getAbsolutePosition(): a Light only refreshes its
                // transformed position while it is being rendered, so a light
                // the budget switched off would report the origin forever and
                // could never win its way back on. Transform the local
                // position by the parent's world matrix ourselves.
                const lp = i.light.position || { x: 0, y: 0, z: 0 };
                const parent: any = i.light.parent;
                const m = parent && parent.getWorldMatrix ? parent.getWorldMatrix().m : null;
                if (m) {
                    i.x = lp.x * m[0] + lp.y * m[4] + lp.z * m[8] + m[12];
                    i.y = lp.x * m[1] + lp.y * m[5] + lp.z * m[9] + m[13];
                    i.z = lp.x * m[2] + lp.y * m[6] + lp.z * m[10] + m[14];
                } else { i.x = lp.x; i.y = lp.y; i.z = lp.z; }
            } catch { /* leave it at the origin */ }
        }
    }

    /** Note that something changed (a group toggled, a model loaded). */
    invalidate(): void { this.dirty = true; }

    /**
     * Enable the nearest and brightest `budget` lights, disable the rest.
     * Cheap: skipped entirely while the camera is still and nothing changed,
     * and a no-op when the content has no more lights than the budget.
     */
    update(force: boolean): void {
        if (!this.items.length) return;
        const cam: any = this.scene.activeCamera;
        const now = Date.now();
        if (!force) {
            if (now - this.lastRunAt < 100) return;
            // The TARGET belongs in the key as much as the position: an orbit
            // camera re-aimed at the far end of a board keeps its position and
            // would otherwise never re-score.
            const p = cam?.position, t = cam?.target;
            const key = cam
                ? `${p?.x?.toFixed(5)},${p?.y?.toFixed(5)},${p?.z?.toFixed(5)}|${t?.x?.toFixed(5)},${t?.y?.toFixed(5)},${t?.z?.toFixed(5)}`
                : '';
            if (!this.dirty && key === this.lastCamKey) return;
            this.lastCamKey = key;
        }
        this.lastRunAt = now;
        this.dirty = false;

        // Under budget: every light stays on, no scoring at all.
        if (this.items.length <= this.budget) {
            for (const i of this.items) i.light.setEnabled(true);
            return;
        }
        if (this.budget === 0) {
            for (const i of this.items) i.light.setEnabled(false);
            return;
        }
        const focus = (cam && (cam.target || cam.position)) || null;
        const scored = this.items.map(i => {
            if (!ancestorsEnabled(i.light)) return { i, score: -1 };
            let d2 = 0;
            if (focus) {
                const dx = i.x - focus.x, dy = i.y - focus.y, dz = i.z - focus.z;
                d2 = dx * dx + dy * dy + dz * dz;
            }
            // Brightness falling off with distance: the LED you are looking at
            // wins over a brighter one across the board.
            return { i, score: (i.intensity || 1e-9) / (d2 + 1e-12) };
        });
        scored.sort((a, b) => b.score - a.score);
        for (let k = 0; k < scored.length; k++) {
            const on = scored[k].score >= 0 && k < this.budget;
            if (scored[k].i.light.isEnabled(false) !== on) scored[k].i.light.setEnabled(on);
        }
    }

    rows(): ContentLightRow[] {
        return this.items.map(i => ({
            name: i.light.name,
            role: i.role,
            intensity: i.intensity,
            range: i.range,
            enabled: !!i.light.isEnabled(false),
            active: !!i.light.isEnabled(true),
            position: { x: i.x, y: i.y, z: i.z },
        }));
    }
}