Skip to content

A fast 2D and 3D game engine — TypeScript SDK, C++/WebAssembly core, visual editor. Ship one project to web, desktop, WeChat MiniGames, playable ads, and native Android / iOS.

35.0 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
import { onWorldUnitsPerMeter } from '../ecs/worldUnits';
import { flushEngineStamps } from '../ecs/engineStamps';
import type { ESEngineModule, CppRegistry } from '../wasm';
import { CoreApiBridge } from '../wasm/CoreApiBridge';
import { handleWasmError } from '../wasm/wasmError';
import { requireResourceManager } from '../wasm/resourceManager';
import { platformOnContextLost } from '../platform';
import { findWebGL2Context } from '../asset/glTextureUpload';
import { log } from '../util/logger';
import { decodeFrameCapture, replayToDrawCall as replayToDrawCallImpl, getSnapshotImageData as getSnapshotImpl, snapshotMatchesCapture as snapshotMatchesImpl, type FrameCaptureData } from './frameCapture';
import { acquireWebGPUDevice } from './webgpuBoot';
import { ATLAS_REFUSAL, LIGHT_REFUSAL } from './refusals';
import { nativeEngineApi, type EngineApi } from '../ecs/bridge/engineApi';

export enum RenderStage {
    Background = 0,
    Opaque = 1,
    Transparent = 2,
    Overlay = 3,
}

export type RenderTargetHandle = number;

export interface RenderStats {
    /** The draws of the scene's and the overlay's lists, after batching: what the draw calls a frame debugger lists add up to. */
    drawCalls: number;
    /**
     * Every draw the GPU was asked for, every pass included: shadow maps, the depth prepass, reflections, motion vectors and post-processing as well as
     * the scene. This is the number a draw call budget is held to.
     */
    gpuDraws: number;
    triangles: number;
    sprites: number;
    text: number;
    /// Triangles posed by a skeletal runtime — Spine and DragonBones both count here.
    skeletal: number;
    meshes: number;
    culled: number;
}

/**
 * How a frame reaches the engine. The web marshals through the wasm heap; the
 * native (embedded-Dawn) core takes the typed arrays as they are. One `Renderer`
 * façade over two backends — the shape the ResourceManager and the memory
 * provider already take — so the frame ORCHESTRATION (cameras, viewports, clear
 * flags, pre-flush draws) is one implementation on both platforms instead of one
 * per host.
 *
 * Only the frame lives here. Render targets, capture and the editor-side queries
 * remain wasm-only below, and simply do nothing on a native build until they
 * grow their own bindings.
 */
export interface RendererBackend {
    init(width: number, height: number): void;
    resize(width: number, height: number): void;
    beginFrame(elapsedSec: number): void;
    /** The point the frames are drawn relative to (render/renderOrigin.ts). A host predating it draws relative to zero. */
    setOrigin?(x: number, y: number, z: number): void;
    updateTransforms(registry: CppRegistry): void;
    begin(viewProjection: Float32Array, target: number, clearFlags: number,
          r: number, g: number, b: number, a: number,
          clearX: number, clearY: number, clearW: number, clearH: number): void;
    submitAll(registry: CppRegistry,
              vpX: number, vpY: number, vpW: number, vpH: number): void;
    flush(): void;
    end(): void;
    /** Closes the frame. Per FRAME, not per camera: this is where a backend
     *  holding a swapchain image for the duration of one gives it back. */
    endFrame(): void;
    /** Whether this core can draw the frame's screen overlay. False means it
     *  keeps screen UI in the world domain, as every core did before the pass
     *  existed — the partition and the pass ship in the same binary, so the two
     *  answers cannot disagree. */
    hasScreenOverlay(): boolean;
    beginScreenOverlay(projection: Float32Array,
                       vpX: number, vpY: number, vpW: number, vpH: number): void;
    submitScreenOverlay(registry: CppRegistry): void;
    endScreenOverlay(target: number): void;
    setStage(stage: number): void;
    setViewport(x: number, y: number, w: number, h: number): void;
    setYSortLayers(mask: number): void;
    setDepthLayers(mask: number): void;
    setTreeSortLayers(mask: number): void;
    setCullingMask(mask: number): void;
    setViewId(view: number): void;
    lodInspect(view: number, entity: number): LodDecision | null;
    setLodPreview(view: number, entity: number, level: number | null): void;
    setViewShading(view: number, mode: number): void;
    setMeshEdgeBuffers(enabled: boolean): void;
    setViewSkinWeights(view: number, entity: number, joint: number): void;
    lightStatus(entity: number): LightStatus | null;
    shadowStatus(entity: number): ShadowStatus | null;
    getStats(): RenderStats;
}

/**
 * What the shadow atlas gave one caster last frame. @experimental
 *
 * `granted` below `requested` and above zero is a REDUCTION: a sun that kept two
 * cascades of four still casts, and calling that a rejection would throw away the
 * distinction the frame records it for. Zero granted is a denial.
 */
export interface ShadowStatus {
    /** Tiles asked for: a cascade set, a cube's six faces, or one. */
    requested: number;
    /** Tiles kept. 0 means this light casts no shadow at all this frame. */
    granted: number;
    /**
     * Why it did not get what it asked for. Three answers, not one: only
     * `atlas-full` is fixed by a bigger atlas, and `tile-budget` is the shader's
     * array bound, which no size changes.
     */
    refusal: (typeof ATLAS_REFUSAL)[number];
    /** Casters the frame denied outright, for a reader that wants the total. */
    deniedCasters: number;
    /** Casters that kept fewer tiles than they asked for. */
    reducedCasters: number;
}

/**
 * What the light cap did to one light last frame, and what it did overall.
 * @experimental
 *
 * `accepted` false comes with the reason beside it: the cap logged a COUNT and
 * dropped the rest, so which light went dark was a question only deleting lights
 * could answer.
 */
export interface LightStatus {
    accepted: boolean;
    /** Why not, when `accepted` is false; `none` otherwise. */
    refusal: (typeof LIGHT_REFUSAL)[number];
    /** The shader's array bound — what `accepted` lights can never exceed. */
    limit: number;
    /** Lights that asked this frame. */
    requested: number;
    /** How many the frame turned away, for a reader that wants the total. */
    refusedCount: number;
    /** Where the environment's sun shone this frame, when a light followed it —
     *  the aim such a light takes instead of its Transform's. */
    environmentSunAim: [number, number, number] | null;
}

/**
 * What a view decided about one object's level, read back from where the decision
 * was made. @experimental
 *
 * Never recomputed by a reader: the whole point of carrying `unbiased` is that an
 * explanation of a level has to be the frame's own, and a second selector written
 * beside this one would be free to disagree with the picture on screen.
 */
/** How a view shades its meshes. @experimental */
/** `directLighting` / `indirectLighting`: clay lit by the lights alone, or by everything that is not a light (ambient,
 *  sky, reflections, probes, bakes) — Unreal's lighting components, for asking where a shadow's fill comes from. */
export type ViewShading = 'shaded' | 'clay' | 'albedo' | 'wireframe' | 'directLighting' | 'indirectLighting';

const VIEW_SHADING_CODE: Record<ViewShading, number> = {
    shaded: 0, clay: 1, albedo: 2, wireframe: 3, directLighting: 4, indirectLighting: 5,
};

export interface LodDecision {
    /** The level drawn, or `null` when the object was small enough to be culled. */
    level: number | null;
    /** What the bare thresholds ask for with no memory behind them; differing from
     *  `level` is hysteresis holding the coarser (or finer) side. */
    unbiased: number | null;
    /** Stand-ins the group actually reaches — levels beyond it do not exist. */
    levels: number;
    /** Fraction of the viewport HEIGHT the object covered when it was measured. */
    screenSize: number;
}

const NO_STATS: RenderStats = { drawCalls: 0, gpuDraws: 0, triangles: 0, sprites: 0, text: 0, skeletal: 0, meshes: 0, culled: 0 };

const bridge = new CoreApiBridge('renderer');
let module: ESEngineModule | null = null;
let viewProjectionPtr: number = 0;
/** Four floats a LOD decision is read back through. */
let lodInspectPtr: number = 0;
/** Five floats a light's standing with the cap or the atlas is read back
 *  through. One buffer: neither answer outlives the call that asks. */
let lightStatusPtr: number = 0;
/** AtlasRefusal, in the order ShadowAtlas.hpp declares it. */
let backend: RendererBackend | null = null;

function engine(): EngineApi | null {
    return (module as EngineApi | null) ?? nativeEngineApi();
}

/** The wasm backend: every call marshals through the module's heap, exactly as
 *  the Renderer always has. */
function wasmBackend(m: ESEngineModule): RendererBackend {
    return {
        init: (width, height) => m.renderer_init(width, height),
        resize: (width, height) => m.renderer_resize(width, height),
        beginFrame: (elapsedSec) => m.renderer_beginFrame(elapsedSec),
        setOrigin: (x, y, z) => { m.renderer_setOrigin?.(x, y, z); },
        updateTransforms: (registry) => {
            try {
                m.renderer_updateTransforms(registry);
            } catch (e) {
                handleWasmError(e, 'Renderer.updateTransforms');
            }
        },
        begin: (viewProjection, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH) => {
            if (!viewProjectionPtr) return;
            try {
                m.HEAPF32.set(viewProjection, viewProjectionPtr / 4);
                m.renderer_begin(viewProjectionPtr, target, clearFlags, r, g, b, a, clearX, clearY, clearW, clearH);
            } catch (e) {
                handleWasmError(e, 'Renderer.begin');
            }
        },
        submitAll: (registry, vpX, vpY, vpW, vpH) => {
            try {
                m.renderer_submitAll(registry, vpX, vpY, vpW, vpH);
            } catch (e) {
                handleWasmError(e, 'Renderer.submitAll');
            }
        },
        flush: () => {
            try {
                m.renderer_flush();
            } catch (e) {
                handleWasmError(e, 'Renderer.flush');
            }
        },
        end: () => {
            try {
                m.renderer_end();
            } catch (e) {
                handleWasmError(e, 'Renderer.end');
            }
        },
        endFrame: () => {
            try {
                m.renderer_endFrame?.();
            } catch (e) {
                handleWasmError(e, 'Renderer.endFrame');
            }
        },
        hasScreenOverlay: () => typeof m.renderer_beginScreenOverlay === 'function',
        beginScreenOverlay: (projection, vpX, vpY, vpW, vpH) => {
            if (!viewProjectionPtr) return;
            try {
                m.HEAPF32.set(projection, viewProjectionPtr / 4);
                m.renderer_beginScreenOverlay?.(viewProjectionPtr, vpX, vpY, vpW, vpH);
            } catch (e) {
                handleWasmError(e, 'Renderer.beginScreenOverlay');
            }
        },
        submitScreenOverlay: (registry) => {
            try {
                m.renderer_submitScreenOverlay?.(registry);
            } catch (e) {
                handleWasmError(e, 'Renderer.submitScreenOverlay');
            }
        },
        endScreenOverlay: (target) => {
            try {
                m.renderer_endScreenOverlay?.(target);
            } catch (e) {
                handleWasmError(e, 'Renderer.endScreenOverlay');
            }
        },
        setStage: (stage) => m.renderer_setStage(stage),
        setViewport: (x, y, w, h) => m.renderer_setViewport(x, y, w, h),
        setYSortLayers: (mask) => m.renderer_setYSortLayers?.(mask >>> 0),
        setDepthLayers: (mask) => m.renderer_setDepthLayers?.(mask >>> 0),
        setTreeSortLayers: (mask) => m.renderer_setTreeSortLayers?.(mask >>> 0),
        setCullingMask: (mask) => m.renderer_setCullingMask?.(mask >>> 0),
        setViewId: (view) => m.renderer_setViewId?.(view >>> 0),
        lodInspect: (view, entity) => {
            if (!m.renderer_lodInspect || !lodInspectPtr) return null;
            if (!m.renderer_lodInspect(view >>> 0, entity >>> 0, lodInspectPtr)) return null;
            const f = m.HEAPF32.subarray(lodInspectPtr >> 2, (lodInspectPtr >> 2) + 4);
            return {
                level: f[0]! < 0 ? null : f[0]!,
                unbiased: f[1]! < 0 ? null : f[1]!,
                levels: f[2]!,
                screenSize: f[3]!,
            };
        },
        setLodPreview: (view, entity, level) =>
            m.renderer_setLodPreview?.(view >>> 0, entity >>> 0, level ?? -1),
        setViewShading: (view, mode) => m.renderer_setViewShading?.(view >>> 0, mode),
        setMeshEdgeBuffers: (enabled) => m.renderer_setMeshEdgeBuffers?.(enabled),
        setViewSkinWeights: (view, entity, joint) => m.renderer_setViewSkinWeights?.(view >>> 0, entity >>> 0, joint),
        shadowStatus: (entity) => {
            if (!m.renderer_shadowStatus || !lightStatusPtr) return null;
            if (!m.renderer_shadowStatus(entity >>> 0, lightStatusPtr)) return null;
            const f = m.HEAPF32.subarray(lightStatusPtr >> 2, (lightStatusPtr >> 2) + 5);
            return {
                requested: f[0]!, granted: f[1]!, refusal: ATLAS_REFUSAL[f[2]!] ?? 'none',
                deniedCasters: f[3]!, reducedCasters: f[4]!,
            };
        },
        lightStatus: (entity) => {
            if (!m.renderer_lightStatus || !lightStatusPtr) return null;
            if (!m.renderer_lightStatus(entity >>> 0, lightStatusPtr)) return null;
            const f = m.HEAPF32.subarray(lightStatusPtr >> 2, (lightStatusPtr >> 2) + 9);
            return {
                accepted: f[0] === 1,
                refusal: LIGHT_REFUSAL[f[1]!] ?? 'none',
                limit: f[2]!, requested: f[3]!, refusedCount: f[4]!,
                environmentSunAim: f[5] === 1 ? [f[6]!, f[7]!, f[8]!] : null,
            };
        },
        getStats: () => ({
            drawCalls: m.renderer_getDrawCalls(),
            gpuDraws: m.renderer_getGpuDrawCalls?.() ?? 0,
            triangles: m.renderer_getTriangles(),
            sprites: m.renderer_getSprites(),
            text: m.renderer_getText(),
            skeletal: m.renderer_getSkeletal?.() ?? 0,
            meshes: m.renderer_getMeshes(),
            culled: m.renderer_getCulled(),
        }),
    };
}

/** GPU device status, mirroring the engine's `GfxDeviceStatus`. */
export const DeviceStatus = { Live: 0, Lost: 1, Recovering: 2, Dead: 3 } as const;

/** Why a device was lost, mirroring the engine's `GfxDeviceLostReason`. */
export const DeviceLostReason = {
    Unknown: 0, ContextLost: 1, OutOfMemory: 2, Reset: 3,
    Removed: 4, Destroyed: 5, Validation: 6, Internal: 7,
} as const;

/**
 * Whether the GPU device can still be drawn to.
 *
 * Reports `Live` when the core cannot answer — an older wasm build, or a native
 * backend with no heap to marshal. Treating "cannot tell" as a loss would black
 * out every host predating this call.
 */
export function getDeviceStatus(): number {
    return module?.deviceStatus?.() ?? DeviceStatus.Live;
}

/** The engine's one-line loss report (backend, GPU, driver, reason); empty while live. */
export function getDeviceLostReport(): string {
    return module?.deviceLostReport?.() ?? '';
}

/** Who the device is. */
export interface DeviceIdentity {
    backend: string;
    vendor: string;
    renderer: string;
    /** Driver / API version string, as the driver spells it. */
    version: string;
}

/**
 * The GPU this session is running on, readable WHILE it works.
 *
 * The engine captured this at init all along — a lost backend cannot be asked
 * who it was — but it could only be read off a loss report, so a healthy session
 * could not say which GPU it had. Null before a device exists.
 */
export function getDeviceIdentity(source: ESEngineModule | null = module): DeviceIdentity | null {
    const raw = source?.deviceIdentity?.() ?? '';
    if (!raw) return null;
    const [backend = '', vendor = '', renderer = '', version = ''] = raw.split('|');
    return { backend, vendor, renderer, version };
}

/**
 * Tell the engine about a loss the host observed.
 *
 * The browser reports context loss to JS, not to wasm, so without this the core
 * keeps submitting until its own next poll notices.
 */
export function reportDeviceLost(reason: number, message: string): void {
    module?.notifyDeviceLost?.(reason, message);
}

/**
 * What the loss guard actually did — where it attached, and how many events it
 * has seen. An observation point, because every inference about this has been
 * wrong and only direct measurement has held.
 */
export function getContextLossGuardInfo(): { target: string; lostEventsSeen: number } {
    return { target: lossGuardTarget, lostEventsSeen };
}

/**
 * Ask the engine to rebuild the device and every object it issued, behind the
 * same handles.
 *
 * False means "not yet": a browser hands a WebGL context back when it is ready.
 * The device then draws while Recovering and turns Live once nothing is owed.
 */
export function recoverDevice(): boolean {
    return module?.recoverDevice?.() ?? false;
}

/**
 * Which generation of the GPU device is current; every rebuild advances it.
 * 0 where the core cannot answer.
 */
export function deviceGeneration(): number {
    return module?.renderer_deviceGeneration?.() ?? 0;
}

/** Told that the device came back, with the generation it came back as. */
export type DeviceRestoredListener = (generation: number) => void;

const deviceRestoredListeners = new Set<DeviceRestoredListener>();
let seenDeviceGeneration_ = -1;

/**
 * Called after the device has been rebuilt AND refilled — everything the GPU held
 * is new storage, so content the game drew itself (a render texture) is blank
 * until it is drawn again. Returns the unsubscribe.
 */
export function onDeviceRestored(listener: DeviceRestoredListener): () => void {
    deviceRestoredListeners.add(listener);
    return () => { deviceRestoredListeners.delete(listener); };
}

/**
 * @internal The one watcher, ticked once a frame by the core plugin. Reads the
 * GENERATION, not the status: a loss that is recovered from between two frames
 * leaves the status back at Live with nothing to notice.
 */
export function pollDeviceRestored(): void {
    const generation = deviceGeneration();
    if (seenDeviceGeneration_ < 0) {
        seenDeviceGeneration_ = generation;
        return;
    }
    // Still owed content: the device is drawing placeholders, so a game redrawing
    // now would be told it is whole while half of it is not there yet.
    if (generation === seenDeviceGeneration_ || getDeviceStatus() !== DeviceStatus.Live) return;
    seenDeviceGeneration_ = generation;
    for (const listener of [...deviceRestoredListeners]) {
        try {
            listener(generation);
        } catch (err) {
            log.error('render', 'a deviceRestored listener threw', err);
        }
    }
}

/** @internal Test seam: forget the device the watcher has seen. */
export function resetDeviceRestoredWatch(): void {
    deviceRestoredListeners.clear();
    seenDeviceGeneration_ = -1;
}

/**
 * Subscribe to the host's `GPUDevice.lost`.
 *
 * WebGPU reports loss to whoever holds the JS device object, never to the
 * engine — the page acquires it before the module exists. Reading it back off
 * the module lets ONE subscription cover every host, instead of each wiring its own.
 */
export function watchWebGPUDeviceLoss(wasmModule: ESEngineModule): void {
    watchOneWebGPUDevice(wasmModule, (wasmModule as unknown as {
        preinitializedWebGPUDevice?: WatchableGPUDevice;
    }).preinitializedWebGPUDevice);
}

interface WatchableGPUDevice { lost?: Promise<{ reason?: string; message?: string }> }

/**
 * Reports the loss, then acquires the replacement only the page can make.
 *
 * The engine cannot create a GPUDevice, so a lost one is fatal until something
 * hands over another — and left to each host, the second device's feature
 * negotiation stops matching the first's. Re-armed on the replacement.
 */
function watchOneWebGPUDevice(wasmModule: ESEngineModule, device?: WatchableGPUDevice): void {
    // Which device is live NOW, since the one the page booted with may be several
    // losses ago and nothing else records the succession.
    (wasmModule as unknown as { currentWebGPUDevice?: unknown }).currentWebGPUDevice = device;
    void device?.lost?.then(async (info) => {
        const reason = info?.reason === 'destroyed'
            ? DeviceLostReason.Destroyed
            : DeviceLostReason.Unknown;
        reportDeviceLost(reason, info?.message ?? 'The GPUDevice reported itself lost');
        // Our own teardown resolves this promise too, and replacing a device
        // nobody is going to draw with would resurrect a renderer being closed.
        if (!module) return;

        const { device: next } = await acquireWebGPUDevice('webgpu');
        if (!next || !module) return;
        (wasmModule as unknown as { pendingWebGPUDevice?: unknown }).pendingWebGPUDevice = next;
        // Handed over, not adopted here: the recovery attempt takes it up, so
        // both backends rebuild through the same one order of operations.
        wasmModule.provideReplacementDevice?.();
        watchOneWebGPUDevice(wasmModule, next as WatchableGPUDevice);
    });
}

let lossGuardInstalled = false;
let lossGuardTarget: 'none' | 'canvas' | 'window' = 'none';
let lostEventsSeen = 0;

/**
 * Subscribe to context loss unconditionally, at renderer init.
 *
 * The subscription is what calls preventDefault, and without that the browser
 * abandons the context for good. That decision belongs to the renderer, not to
 * whether a diagnostics plugin happens to be installed.
 */
function installContextLossGuard(m: ESEngineModule): void {
    if (lossGuardInstalled) return;
    lossGuardInstalled = true;
    const onLost = (e?: Event): void => {
        lostEventsSeen++;
        e?.preventDefault();
        reportDeviceLost(DeviceLostReason.ContextLost, 'The host reported the rendering context was lost');
    };

    // On the CANVAS, not on window: an unattached canvas has no path to window
    // at all — not even a capture phase — and the engine's own canvas is exactly
    // that in a headless host.
    const canvas = findWebGL2Context(m.GL)?.canvas as EventTarget | undefined;
    if (canvas?.addEventListener) {
        lossGuardTarget = 'canvas';
        canvas.addEventListener('webglcontextlost', onLost as EventListener);
        return;
    }
    lossGuardTarget = 'window';
    platformOnContextLost(() => onLost());
}

/** @internal Wired by the engine plugins — not part of the public API. */
let unitsSubscription: (() => void) | null = null;

export function initRendererAPI(wasmModule: ESEngineModule): void {
    // The frame measures inverse-square lights in metres: it is told what one is, now and whenever the project says.
    unitsSubscription?.();
    unitsSubscription = onWorldUnitsPerMeter((units) => {
        (wasmModule as unknown as { renderer_setWorldUnitsPerMeter?(u: number): void }).renderer_setWorldUnitsPerMeter?.(units);
    });
    bridge.connect(wasmModule);
    module = bridge.module;
    installContextLossGuard(module);
    viewProjectionPtr = module._malloc(16 * 4);
    lodInspectPtr = module._malloc(4 * 4);
    lightStatusPtr = module._malloc(9 * 4);
    backend = wasmBackend(module);
}

/** @internal Install a non-wasm backend (the native host's). Mirrors
 *  {@link initRendererAPI} for a core that has no heap to marshal through. */
export function setRendererBackend(next: RendererBackend | null): void {
    backend = next;
}

export function shutdownRendererAPI(): void {
    if (module && viewProjectionPtr) {
        module._free(viewProjectionPtr);
        viewProjectionPtr = 0;
    }
    if (module && lodInspectPtr) {
        module._free(lodInspectPtr);
        lodInspectPtr = 0;
    }
    if (module && lightStatusPtr) {
        module._free(lightStatusPtr);
        lightStatusPtr = 0;
    }
    bridge.disconnect();
    module = null;
    backend = null;
}

export const Renderer = {
    init(width: number, height: number): void {
        backend?.init(width, height);
    },

    resize(width: number, height: number): void {
        backend?.resize(width, height);
    },

    beginFrame(elapsedSec = 0): void {
        backend?.beginFrame(elapsedSec);
    },

    setOrigin(x: number, y: number, z: number): void {
        backend?.setOrigin?.(x, y, z);
    },

    updateTransforms(registry: { _cpp: CppRegistry }): void {
        // The writes a script made this frame reach the engine's stamps before anything composes or draws from them.
        flushEngineStamps(registry._cpp);
        backend?.updateTransforms(registry._cpp);
    },

    /**
     * Begins the pass. The clear rides begin as a load-op: `clearFlags` bit 0 =
     * color, bit 1 = depth; `clearColor` is the color value; `clearRect` scopes the
     * clear to a viewport region (omitted = the whole target). No flags = load.
     */
    begin(viewProjection: Float32Array, target?: RenderTargetHandle, clearFlags = 0,
          clearColor?: { x: number; y: number; z: number; w: number },
          clearRect?: { x: number; y: number; w: number; h: number }): void {
        backend?.begin(viewProjection, target ?? 0, clearFlags,
            clearColor?.x ?? 0, clearColor?.y ?? 0, clearColor?.z ?? 0, clearColor?.w ?? 1,
            clearRect?.x ?? 0, clearRect?.y ?? 0, clearRect?.w ?? 0, clearRect?.h ?? 0);
    },

    flush(): void {
        backend?.flush();
    },

    end(): void {
        backend?.end();
    },

    /** Closes the frame — after every camera, after the screen post stack, and
     *  after the overlay. See RendererBackend.endFrame. */
    endFrame(): void {
        backend?.endFrame();
    },

    /** Whether the core can draw the frame's screen overlay. */
    hasScreenOverlay(): boolean {
        return backend?.hasScreenOverlay() ?? false;
    },

    beginScreenOverlay(projection: Float32Array,
                       vpX: number, vpY: number, vpW: number, vpH: number): void {
        backend?.beginScreenOverlay(projection, vpX, vpY, vpW, vpH);
    },

    submitScreenOverlay(registry: { _cpp: CppRegistry }): void {
        backend?.submitScreenOverlay(registry._cpp);
    },

    endScreenOverlay(target: RenderTargetHandle = 0): void {
        backend?.endScreenOverlay(target);
    },

    submitAll(registry: { _cpp: CppRegistry }, vpX: number, vpY: number, vpW: number, vpH: number): void {
        backend?.submitAll(registry._cpp, vpX, vpY, vpW, vpH);
    },

    setStage(stage: RenderStage): void {
        backend?.setStage(stage);
    },

    /**
     * A render target: `flags` 1 with a depth buffer, 2 filtered linearly, 4 its texture as drawn (on a device that stores targets
     * top-down, no copy turned to bottom-up rows is kept, for a target only shaders that know the device's rows read).
     */
    createRenderTarget(width: number, height: number, flags: number = 1): RenderTargetHandle {
        return engine()?.renderer_createTarget?.(width, height, flags) ?? 0;
    },

    releaseRenderTarget(handle: RenderTargetHandle): void {
        engine()?.renderer_releaseTarget?.(handle);
    },

    getTargetTexture(handle: RenderTargetHandle): number {
        return engine()?.renderer_getTargetTexture?.(handle) ?? 0;
    },

    getTargetDepthTexture(handle: RenderTargetHandle): number {
        return engine()?.renderer_getTargetDepthTexture?.(handle) ?? 0;
    },

    /**
     * Draws `material` through `shader` (a PostProcess-domain shader, compiled) into the rect `x, y, w, h` of render target `target`,
     * before the next frame's scene: a surface baked into a texture, as Unreal draws a material to a render target. The shader takes the
     * material's values by name (params and textures it shares with the material's own shader), and `a` and `b` as its params `u_bakeA`
     * and `u_bakeB`. Returns a ticket for {@link Renderer.bakeState}, 0 without a renderer that bakes.
     * @experimental
     */
    bakeMaterial(material: number, shader: number, target: RenderTargetHandle, x: number, y: number, w: number, h: number,
                 a: readonly [number, number, number, number], b: readonly [number, number, number, number]): number {
        return engine()?.renderer_queueMaterialBake?.(material, shader, target, x, y, w, h, a[0], a[1], a[2], a[3], b[0], b[1], b[2], b[3]) ?? 0;
    },

    /**
     * Where a bake stands: 0 waiting (its program may still be compiling), 1 drawn, -1 not drawable (no such target, shader or material,
     * or no renderer that bakes). A drawn or failed ticket is forgotten once asked.
     * @experimental
     */
    bakeState(ticket: number): number {
        if (!ticket) return -1;
        return engine()?.renderer_materialBakeState?.(ticket) ?? -1;
    },

    setClearColor(r: number, g: number, b: number, a: number): void {
        engine()?.renderer_setClearColor?.(r, g, b, a);
    },

    setViewport(x: number, y: number, w: number, h: number): void {
        backend?.setViewport(x, y, w, h);
    },

    /** Layers (bits 0..31) that sort by world Y within the layer — top-down occlusion. */
    setYSortLayers(mask: number): void {
        backend?.setYSortLayers(mask);
    },

    /**
     * Layers (bits 0..31) that resolve their contents by the depth buffer instead
     * of paint order — the 2.5D opt-in. Opaque draws (blend mode None) in such a
     * layer write depth and occlude whatever is behind them whatever order they
     * were drawn in; blended ones test without writing and stay back-to-front. A
     * layer that also y-sorts keeps y-sorting (see `layerOrderOf`).
     *
     * The live twin of the `depthLayers` app option, so an editor can apply the
     * project setting to a running view without rebooting the realm.
     */
    setDepthLayers(mask: number): void {
        backend?.setDepthLayers(mask);
    },

    /**
     * Layers (bits 0..31) whose draws are painted in hierarchy order: a sprite, a label and a shape stack as their entities do in the tree
     * (a preorder walk), instead of by shader and depth. The order a scene of nodes has in an authoring tool, and the one in which a panel
     * covers the text of the panel under it.
     */
    setTreeSortLayers(mask: number): void {
        backend?.setTreeSortLayers(mask);
    },

    /**
     * Sorting layers (bits 0..31) the NEXT collect draws — `Camera.cullingMask`.
     * Set per camera before submitting it; a layer with no bit (outside 0..31) is
     * drawn by every camera.
     */
    setCullingMask(mask: number): void {
        backend?.setCullingMask(mask);
    },

    /**
     * Names the view the NEXT collect looks from — the camera entity, so a level
     * chosen by how big something looks is remembered per camera. Set per camera
     * before submitting it; 0 is the shared default view.
     */
    setViewId(view: number): void {
        backend?.setViewId(view);
    },

    /**
     * What @p view decided about `entity`'s LOD last time it drew it, or null when
     * that view has not measured it — off screen, or carrying no LODGroup, which
     * is not the same as measuring it at level 0. @experimental
     */
    lodInspect(view: number, entity: number): LodDecision | null {
        return backend?.lodInspect(view, entity) ?? null;
    },

    /**
     * Show `level` for `entity` in `view` instead of the level that view chose;
     * `null` goes back to choosing. @experimental
     *
     * View state, never component state: a group is authored policy and reads the
     * same everywhere. The choice goes on being made underneath, so leaving a
     * preview obeys the selector again rather than resuming from what was held up.
     */
    setLodPreview(view: number, entity: number, level: number | null): void {
        backend?.setLodPreview(view, entity, level);
    },

    /**
     * Shade `view`'s meshes as `mode` says instead of as authored. @experimental
     *
     * View state, like a LOD preview. Clay is one neutral lit surface, albedo the base
     * colour with no light, wireframe a dark surface with its edges; a shadow map is
     * unaffected and a host that predates the mode ignores the call.
     */
    setViewShading(view: number, mode: ViewShading): void {
        backend?.setViewShading(view, VIEW_SHADING_CODE[mode]);
    },

    /**
     * Give meshes loaded from now on an edge buffer, which a wireframe view draws. @experimental
     *
     * A second index buffer per mesh, so off unless an editor asks, and asked before the
     * assets load: a mesh realized earlier has none and is drawn as a plain surface.
     */
    setMeshEdgeBuffers(enabled: boolean): void {
        backend?.setMeshEdgeBuffers(enabled);
    },

    /**
     * Colour one skinned entity in `view` by how much a joint moves each of its vertices;
     * `null` stops. @experimental
     *
     * `joint` is an index into the mesh's own bind matrices, the order its joint channel
     * uses. View state like the shading beside it: the same entity drawn through another
     * view keeps its look.
     */
    setViewSkinWeights(view: number, entity: number | null, joint = 0): void {
        backend?.setViewSkinWeights(view, entity ?? 0, entity === null ? -1 : joint);
    },

    /**
     * What the light cap did to `entity` last frame, or null before any frame has
     * collected lights. @experimental
     *
     * Read back rather than derived: a reader working out which lights were
     * dropped by taking the tail of a list would be a second cap, agreeing with
     * the frame only until either sorted differently.
     */
    lightStatus(entity: number): LightStatus | null {
        return backend?.lightStatus(entity) ?? null;
    },

    /**
     * What the shadow atlas gave `entity` last frame, or null when it asked the
     * atlas for nothing. @experimental
     */
    shadowStatus(entity: number): ShadowStatus | null {
        return backend?.shadowStatus(entity) ?? null;
    },

    setTextureParams(textureId: number, minFilter: number, magFilter: number, wrapS: number, wrapT: number): void {
        engine()?.renderer_setTextureParams?.(textureId, minFilter, magFilter, wrapS, wrapT);
    },

    measureBitmapText(fontHandle: number, text: string, fontSize: number, spacing: number): { width: number; height: number } {
        if (!module) return { width: 0, height: 0 };
        return requireResourceManager().measureBitmapText(fontHandle, text, fontSize, spacing);
    },

    getStats(): RenderStats {
        return backend?.getStats() ?? NO_STATS;
    },

    captureNextFrame(): void {
        module?.renderer_captureNextFrame();
    },

    getCapturedData(): FrameCaptureData | null {
        if (!module) return null;
        return decodeFrameCapture(module);
    },

    hasCapturedData(): boolean {
        return module?.renderer_hasCapturedData() ?? false;
    },

    replayToDrawCall(drawCallIndex: number): void {
        if (!module) return;
        replayToDrawCallImpl(module, drawCallIndex);
    },

    /** Resolves with the replay snapshot once its async readback lands (see frameCapture). */
    getSnapshotImageData(): Promise<ImageData | null> {
        if (!module) return Promise.resolve(null);
        return getSnapshotImpl(module);
    },

    snapshotMatchesCapture(): boolean {
        return module ? snapshotMatchesImpl(module) : false;
    },
};