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.

50.5 KB
Raw Blame
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright (c) 2024-present ESEngine Team
/**
 * @file  gameHost.ts — the exported game's runtime host.
 *        Bundled by exportGame (esbuild, esengine inlined) into a
 *        self-contained game.js. Boots the SAME shipping runtime the editor's
 *        play realm uses (createWebApp → initPlayRealmRuntime), but loads the
 *        scene + asset manifest from the COOKED files next to index.html — so the
 *        shipped game is what the editor played (play == ship).
 *
 *        Builtin scenes run as-is; project custom-script bundles are a follow-up
 *        (shared with the play realm's import-map work).
 */
import {
  createWebApp, setEditorMode, setPlayMode, Assets, Ads, extendPlatform, getPlatform,
  indexPackagedManifest, createPackagedAssetSource, applyAssetRefResolvers, initRuntime,
  HttpBackend, fetchDecodePixels, registerPackagedSideModules,
  packagedAppOptions, packagedRuntimeInit, Transform, SceneManager, UINode,
  acquireWebGPUDevice, CharacterController3D, AnimatorController,
  Animator, TPC_SPEED, TPC_GROUNDED, Particle,
  AnimatorRootMotion, Playthrough, Name,
  worldResidencyReport, PostProcess, Renderer, Audio, Camera,
  getComponentRegistry, BakesRes,
  startDebugChannel, glContextAttributes, warmShaders, getResourceStats,
} from 'esengine';
import { installDevicePreview } from './devicePreviewClient';
declare const __ESTELLA_LAN_PREVIEW__: boolean;

/**
 * A component this host only READS, by the name the registry knows it by.
 * Importing it would put its subsystem in every package the host is in, which
 * is all of them — and this is a probe the verifier calls, not something the
 * game needs to run.
 */
/** The registry's entry for a name, or null where the subsystem is not shipped. */
function optionalDef(name: string): never | null {
  return (getComponentRegistry().get(name) as never | undefined) ?? null;
}

/** How many entities carry a component the package may not ship at all. */
function countOfIn(app: { world: { getEntitiesWithComponents(c: never[]): readonly unknown[] } }, name: string): number {
  const def = optionalDef(name);
  return def === null ? 0 : app.world.getEntitiesWithComponents([def]).length;
}

/** Entities carrying a component the package may not ship at all. */
function optionalEntities(app: { world: { getEntitiesWithComponents(c: never[]): readonly number[] } },
                          name: string): readonly number[] {
  const def = optionalDef(name);
  return def === null ? [] : app.world.getEntitiesWithComponents([def]);
}

function optionalRead(app: { world: { has(e: number, c: never): boolean; get(e: number, c: never): unknown } },
                      entity: number, name: string): Record<string, never> | null {
  const def = optionalDef(name);
  if (def === null || !app.world.has(entity, def)) return null;
  return app.world.get(entity, def) as Record<string, never>;
}
import type {
  SceneData, AddressableManifest, PackagedGameConfig, RenderSurfaceSource, WorldManifest,
} from 'esengine';
import type { ESEngineModule } from 'esengine/wasm';
import { attachSplash, type Splash } from '../export/splash';
import { countedStream, engineDownloadTotal } from './engineDownload';
import { initializePoki, type PokiSdk } from './pokiProfile';
import { initializeCrazyGames, type CrazyGamesSdk } from './crazyGamesProfile';
import { initializeYouTube, type YouTubeSdk } from './youtubeProfile';

/**
 * Fetch the engine binary through a stream we can count, and hand the SAME
 * stream to the compiler — emscripten fetches it itself otherwise and nothing
 * sees the bytes. Re-wrapping the body keeps `instantiateStreaming`: reading it
 * to an ArrayBuffer first would buy the bar at the cost of what it measures.
 */
function engineInstantiator(url: string, splash: Splash | null, engineBytes: number | undefined) {
  return (imports: WebAssembly.Imports,
    ok: (inst: WebAssembly.Instance, mod: WebAssembly.Module) => void): Record<string, never> => {
    void (async () => {
      const res = await fetch(url);
      const total = engineDownloadTotal(res.headers, engineBytes);
      // No length or no stream ⇒ the honest answer is the stage weight alone.
      const source = total > 0 && res.body
        ? new Response(countedStream(res.body, total, (f) => splash?.within('engine', f)), {
          headers: { 'content-type': 'application/wasm' },
        })
        : res;
      const { instance, module } = await WebAssembly.instantiateStreaming(source, imports);
      ok(instance, module);
    })();
    return {};
  };
}

async function boot(): Promise<void> {
  const canvas = document.getElementById('canvas') as HTMLCanvasElement;
  // Null on a page without one, and every call below is then a no-op: a start
  // screen is something a boot shows, never something a boot depends on.
  const splash = attachSplash();
  // Render-verification hook: with ?headless the cooked build keeps its drawing
  // buffer + exposes a framebuffer readback, so a driver can prove the SHIPPED
  // runtime actually rendered the cooked scene (the editor host can't — it uses a
  // different asset path).
  const headless = new URLSearchParams(location.search).has('headless');
  const resize = () => {
    const dpr = window.devicePixelRatio || 1;
    canvas.width = Math.max(1, Math.floor(window.innerWidth * dpr));
    canvas.height = Math.max(1, Math.floor(window.innerHeight * dpr));
  };
  window.addEventListener('resize', resize);
  resize();

  const cfg = (await (await fetch('./game.config.json')).json()) as PackagedGameConfig;
  splash?.reach('config');
  const youtube = cfg.webChannel === 'youtube'
    ? initializeYouTube((window as unknown as { ytgame?: YouTubeSdk }).ytgame, (message, error) => console.warn(message, error))
    : null;
  if (youtube) {
    await youtube.waitActive();
    // A painted loading screen qualifies as the first frame; it precedes cloud loading.
    await new Promise<void>(resolve => requestAnimationFrame(() => requestAnimationFrame(() => resolve())));
    await youtube.waitActive();
    youtube.firstFrameReady();
    await youtube.load();
    const fetchFromHost = getPlatform().fetch.bind(getPlatform());
    extendPlatform({ ...youtube.storage, onAudioMute: youtube.onAudioMute, submitScore: youtube.submitScore,
      fetch: async (url, options) => {
        await youtube.waitActive(); const response = await fetchFromHost(url, options); await youtube.waitActive(); return response;
      },
    });
    document.documentElement.dataset.webSdkReady = String(youtube.provider !== null);
  }
  const poki = cfg.webChannel === 'poki'
    ? await initializePoki((window as unknown as { PokiSDK?: PokiSdk }).PokiSDK, (message, error) => console.warn(message, error))
    : null;
  const crazyGames = cfg.webChannel === 'crazygames'
    ? await initializeCrazyGames((window as unknown as { CrazyGames?: { SDK: CrazyGamesSdk } }).CrazyGames?.SDK, (message, error) => console.warn(message, error), 10000, cfg.leaderboardEncryptionKey)
    : null;
  if (crazyGames) {
    extendPlatform({ ...crazyGames.storage, onAudioMute: crazyGames.onAudioMute, submitScore: crazyGames.submitScore });
    document.documentElement.dataset.webSdkReady = String(crazyGames.provider !== null);
  }
  // Before the engine boots, so a boot that fails is still heard by the editor.
  if (cfg.debugChannel) startDebugChannel(cfg.debugChannel);
  await youtube?.waitActive();

  // The project's own components and systems. The config SAYS whether this build
  // has any, so a load failure is a failure rather than a build that turned out
  // not to have scripts — catching the difference boots an empty world.
  if (cfg.scripts) {
    const url = new URL(`./${cfg.scripts}`, import.meta.url).href;
    try {
      await import(/* @vite-ignore */ url);
    } catch (err) {
      const cause = err instanceof Error ? err : new Error(String(err));
      // Logged as well as thrown: a rejected boot is observable to automation
      // through either, and only one of them survives a host that awaits this.
      console.error(`[estella] project scripts failed to load (${url})`, cause);
      throw new Error(
        `[estella] startup failed: project scripts "${cfg.scripts}" did not load — ${cause.message}`,
        { cause },
      );
    }
  }
  splash?.reach('scripts');
  // Before anything acquires: the project's own modules were staged into wasm/
  // beside the engine's, and this is what makes their ids resolvable.
  registerPackagedSideModules(cfg);
  // The addressable manifest is the asset index — the same one the WeChat and
  // native runtimes read. It resolves every ref spelling to its staged path and
  // carries the atlas metadata the catalog needs, so there is one asset model
  // across every packaged realm rather than a flat map here and a manifest there.
  const index = indexPackagedManifest(
    (await (await fetch('./asset-manifest.json')).json()) as AddressableManifest,
  );
  splash?.reach('manifest');
  // A named scene from the query boots instead of the entry, so a conformance
  // harness can drive a fixture scene in the real package rather than needing a
  // project of its own. Unknown names are refused rather than silently ignored.
  const wanted = new URLSearchParams(location.search).get('scene');
  const chosen = wanted
    ? (cfg.scenes ?? []).find((s) => s.name === wanted)?.path
    : cfg.entryScene;
  if (!chosen) throw new Error(`[estella] no scene named "${wanted}" in this package`);
  await youtube?.waitActive();
  const sceneData = (await (await fetch(`./${chosen}`)).json()) as SceneData;
  await youtube?.waitActive();

  // The cooked worlds this build carries. Fetched beside the entry scene because
  // residency answers for the entry scene from its first frame, and a manifest
  // that arrived later would be a world that popped in.
  const worlds: WorldManifest[] = [];
  for (const world of cfg.worlds ?? []) {
    worlds.push((await (await fetch(`./${world.manifest}`)).json()) as WorldManifest);
  }

  splash?.reach('scene');
  const wasmBase = new URL('./wasm/', import.meta.url).href; // relative → mount-path agnostic
  // A host with no WebAssembly (an old WebView, a locked-down runtime) gets the
  // same engine built as plain JavaScript, when the build carries it; `?engine=js`
  // asks for it anywhere, which is how it is tested in a browser that has wasm.
  const engineAsJs = (typeof WebAssembly === 'undefined'
    || new URLSearchParams(location.search).get('engine') === 'js') && cfg.engineJs === true;
  if (typeof WebAssembly === 'undefined' && !engineAsJs) {
    throw new Error('This browser has no WebAssembly, and this build carries no JavaScript engine '
      + '(Project Settings → Web → "Run without WebAssembly", packaging.platforms.web.engineJs).');
  }
  const { default: createModule } = (await import(
    /* @vite-ignore */ `${wasmBase}${engineAsJs ? 'esengine.asm.js' : 'esengine.js'}`)) as {
    default: (options?: Record<string, unknown>) => Promise<ESEngineModule>;
  };
  if (engineAsJs) console.info('[estella] engine: JavaScript build (no WebAssembly)');
  // The device has to exist before the module reads it, and the fallback IS the
  // contract. `?headless` pins WebGL2: a driver reads the frame back through the
  // GL context, which is what the capture hook below has. The JavaScript engine is
  // built without WebGPU: a host with no wasm has no WebGPU either.
  const wantsWebGPU = cfg.renderBackend === 'webgpu' && !headless && !engineAsJs;
  const gpu = await acquireWebGPUDevice(wantsWebGPU ? 'webgpu' : 'webgl2',
    (m) => console.error(m));
  if (wantsWebGPU && !gpu.device) console.warn(`[estella] WebGPU unavailable (${gpu.reason}) — using WebGL2.`);

  const module = await createModule({
    canvas,
    locateFile: (p: string) => `${wasmBase}${p}`,
    // The JavaScript engine is the whole module in its own file: nothing to instantiate.
    ...(engineAsJs ? {} : { instantiateWasm: engineInstantiator(`${wasmBase}esengine.wasm`, splash, cfg.engineBytes) }),
    print: (t: string) => console.log(t),
    printErr: (t: string) => console.error(t),
    ...(gpu.device ? { preinitializedWebGPUDevice: gpu.device } : {}),
  });

  splash?.reach('engine');

  let gl: WebGL2RenderingContext | null = null;
  let renderSurface: RenderSurfaceSource;
  if (gpu.device) {
    canvas.id ||= 'canvas';
    renderSurface = { kind: 'webgpu', canvasSelector: `#${canvas.id}` };
  } else {
    gl = canvas.getContext('webgl2', glContextAttributes(headless)) as WebGL2RenderingContext | null;
    if (!gl) throw new Error('WebGL2 is not available.');
    renderSurface = {
      kind: 'gl-context',
      handle: module.GL.registerContext(gl, { majorVersion: 2, minorVersion: 0, enableExtensionsByDefault: true }),
    };
  }

  const app = createWebApp(module, {
    renderSurface,
    // Everything the config says an App must be BUILT with (see packagedAppOptions).
    ...packagedAppOptions(cfg),
    getViewportSize: () => ({ width: canvas.width, height: canvas.height }),
    wasmBaseUrl: wasmBase.replace(/\/$/, ''), // SDK appends "/<file>" — no trailing slash
  });
  if (poki?.provider) app.getResource(Ads)?.setProvider(poki.provider);
  if (crazyGames?.provider) app.getResource(Ads)?.setProvider(crazyGames.provider);
  if (youtube) app.addPlugin({ name: 'YouTubeHost', build(host) {
    if (youtube.provider) host.getResource(Ads)?.setProvider(youtube.provider);
    let release: (() => void) | null = null;
    const off = youtube.onPause(paused => {
      if (paused && !release) release = host.holdExecution();
      else if (!paused && release) { const finish = release; release = null; finish(); }
    });
    this.cleanup = () => { off(); release?.(); youtube.dispose(); };
  } });
  splash?.reach('app');
  setEditorMode(false);
  setPlayMode(true);

  if (headless) {
    let statsOn = false;
    const PREWARM_WORDS = 15;
    const PREPARE_WORDS = 11;

    /** Eleven words back from the production readying: whether a claim may be
     *  recorded at all, four counts, and the stamp with the generation that
     *  witnessed it. No key set — that is the oracle's job, not production's. */
    const readPrepare = (heap: Uint32Array, ptr: number): Record<string, number> => {
      const o = heap.subarray(ptr >> 2, (ptr >> 2) + PREPARE_WORDS);
      return {
        claimValid: o[0],
        asks: o[1], compiles: o[2], materialAsks: o[3], materialCompiles: o[4],
        digestLo: o[5], digestHi: o[6],
        programEpoch: o[7] + o[8] * 0x100000000,
        deviceGeneration: o[9] + o[10] * 0x100000000,
      };
    };
    /** Thirteen words out: five counts, the stock key SET, the readiness stamp
     *  (digest over BOTH program paths plus the epoch it was taken under), and
     *  the device generation that guards it — never part of the claim itself. */
    const readPrewarm = (heap: Uint32Array, ptr: number): Record<string, number> => {
      const o = heap.subarray(ptr >> 2, (ptr >> 2) + PREWARM_WORDS);
      return {
        asks: o[0], compiles: o[1], uniqueKeys: o[2],
        materialAsks: o[3], materialCompiles: o[4],
        keysLo: o[5], keysHi: o[6], keysLo2: o[7], keysHi2: o[8],
        digestLo: o[9], digestHi: o[10],
        programEpoch: o[11] + o[12] * 0x100000000,
        deviceGeneration: o[13] + o[14] * 0x100000000,
      };
    };

    /**
     * Ready the shader programs a resident cell's meshes will be asked for,
     * drawing none of them. Attached only where the engine answers it.
     *
     * Turning the camera would ready them too, and would bring every other
     * first-sight effect with it — which is the isolation this exists to keep.
     */
    const prewarmMeshVariants = (cell: string): Record<string, number> => {
      const rows = (worldResidencyReport(app).cellRows ?? {})[cell];
      if (!rows || rows.length === 0) throw new Error(`[estella] no resident cell "${cell}"`);
      const entities = new Uint32Array(rows.map((r) => r.entity));
      const m = module as unknown as {
        _malloc(n: number): number;
        _free(p: number): void;
        HEAPU32: Uint32Array;
        engine_prewarmMeshVariants(registry: unknown, entitiesPtr: number, count: number,
                                   outPtr: number): void;
      };
      const entityPtr = m._malloc(entities.length * 4);
      const outPtr = m._malloc(PREWARM_WORDS * 4);
      try {
        m.HEAPU32.set(entities, entityPtr >> 2);
        // Around the call ALONE: reading the counts back is this probe's cost,
        // not the readiness cost the experiment is about.
        const began = performance.now();
        m.engine_prewarmMeshVariants(app.world.getCppRegistry(), entityPtr, entities.length,
                                     outPtr);
        const ms = performance.now() - began;
        return { ms, entities: entities.length, ...readPrewarm(m.HEAPU32, outPtr) };
      } finally {
        m._free(entityPtr);
        m._free(outPtr);
      }
    };

    /**
     * The production path: readiness from the cell's DOCUMENT and the assets its
     * preparation decoded, no entity consulted. Whether those facts SUFFICE is a
     * claim about the two derivations agreeing, not about this call succeeding.
     */
    const prepareMeshPrograms = async (cell: string): Promise<Record<string, number>> => {
      const found = worlds.flatMap((w) => w.cells).find((c) => c.name === cell);
      if (!found) throw new Error(`[estella] no cooked cell "${cell}"`);
      const doc = (await (await fetch(`./${found.path}`)).json()) as SceneData;
      const assets = app.getResource(Assets);
      // The same channel preparation loads through, so the handles are the ones
      // it already acquired rather than a second decode.
      const resolved = await assets.preloadSceneAssets(doc);
      assets.resolveSceneAssetPaths(doc, resolved);
      const rows: number[] = [];
      for (const entity of doc.entities) {
        const parts = (entity as { components?: Array<{ type: string; data: Record<string, unknown> }> }).components;
        const renderer = parts?.find((c) => c.type === 'MeshRenderer');
        if (!renderer) continue;
        const skin = parts?.find((c) => c.type === 'MeshSkin');
        const joints = (skin?.data.joints as unknown[] | undefined)?.length ?? 0;
        rows.push(Number(renderer.data.mesh) || 0, renderer.data.lit ? 1 : 0,
                  Number(renderer.data.normalMap) || 0, joints,
                  Number(renderer.data.material) || 0);
      }
      const m = module as unknown as {
        _malloc(n: number): number;
        _free(p: number): void;
        HEAPU32: Uint32Array;
        engine_prepareMeshPrograms(rowsPtr: number, count: number, outPtr: number): void;
      };
      const rowsPtr = m._malloc(rows.length * 4);
      const outPtr = m._malloc(PREPARE_WORDS * 4);
      try {
        m.HEAPU32.set(rows, rowsPtr >> 2);
        const began = performance.now();
        m.engine_prepareMeshPrograms(rowsPtr, rows.length / 5, outPtr);
        const ms = performance.now() - began;
        return { ms, entities: rows.length / 5, ...readPrepare(m.HEAPU32, outPtr) };
      } finally {
        m._free(rowsPtr);
        m._free(outPtr);
      }
    };

    const cooked: Record<string, unknown> = {
      capture(): { width: number; height: number; rgba: Uint8Array } {
        const w = canvas.width, h = canvas.height;
        const rgba = new Uint8Array(w * h * 4);
        // `?headless` pins WebGL2 above, so this is the context that drew.
        gl!.readPixels(0, 0, w, h, gl!.RGBA, gl!.UNSIGNED_BYTE, rgba);
        return { width: w, height: h, rgba };
      },
      /**
       * How many of this build's systems run as compiled code. Zero in an
       * interpreted package, which is what tells the two apart from outside —
       * the frames they produce are meant to be identical.
       */
      compiledSystems(): number {
        return app.compiledSystemCount;
      },
      /**
       * Which systems this package is running compiled, and how many twin calls
       * have happened. Installed and dispatched are separate questions, and a
       * driver comparing positions can answer neither — the closure a twin
       * replaced moves the entity to the same place.
       */
      compiled(): { installed: readonly string[]; calls: number } {
        return app.compiledSystems;
      },

      /**
       * Where things are, for a driver that has to play rather than just look.
       * Capture answers "did it draw"; walking a route needs "am I there yet",
       * and guessing that from frame counts breaks on the first enemy in the
       * way. Named entities only, and only the names asked for.
       */
      probe(names: string[] = []): {
        scene: string | null;
        transitioning: boolean;
        at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number; text?: string }>;
      } {
        const at: Record<string, { x: number; y: number; z?: number; w?: number; h?: number; text?: string }> = {};
        for (const name of names) {
          const entity = app.world.findEntityByName(name);
          if (entity === null || !app.world.has(entity, Transform)) continue;
          // World, not local: a driver asks where something IS, and for anything
          // parented (every UI node) the local offset answers a different question.
          const t = app.world.get(entity, Transform);
          const p = t.worldPosition ?? t.position;
          // z as well: a 3D driver asking where something is cannot be answered
          // by the plane, and a character walking a ramp moves in all three.
          at[name] = { x: p.x, y: p.y, z: p.z ?? 0 };
          const text = optionalRead(app, entity, 'Text');
          if (typeof text?.content === 'string') at[name].text = text.content;
          // A node's own size, for a claim about a value the game COMPUTED rather
          // than about where it ended up — a spectrum bar barely moves while its
          // height carries the whole answer.
          if (app.world.has(entity, UINode)) {
            const node = app.world.get(entity, UINode);
            at[name].w = node.width?.value;
            at[name].h = node.height?.value;
          }
        }
        const scenes = app.hasResource(SceneManager) ? app.getResource(SceneManager) : null;
        // A scene arrives entity by entity, and a driver polling from outside
        // the frame loop can land in the middle of that. Half a world reads as
        // "the thing I was walking to is gone", which is a lie with a cost.
        return { scene: scenes?.getActive() ?? null, transitioning: scenes?.isTransitioning() ?? false, at };
      },
      /**
       * Who the world still holds, asked once by a driver that lost sight of its
       * goal. `probe` can only report a name it did not find, and "despawned",
       * "renamed" and "alive but with no Transform" are three different bugs.
       */
      census(limit = 24): {
        entities: number;
        named: string[];
        alive: { name: string; hp: number }[];
      } {
        const named: string[] = [];
        const alive: { name: string; hp: number }[] = [];
        for (const e of app.world.getEntitiesWithComponents([Name])) {
          const n = app.world.get(e, Name).value;
          if (named.length < limit) named.push(n);
          const hp = optionalRead(app, e, 'Health');
          if (hp !== null && alive.length < limit) alive.push({ name: n, hp: hp.current as never });
        }
        return { entities: app.world.getAllEntities().length, named, alive };
      },
      /**
       * What an autonomous character is doing, and on whose terms. Read-only and
       * off the same components the game runs on: a driver that could set the
       * state would be answering its own question, so a chase still has to be
       * caused by walking into what the enemy can see.
       */
      ai(enemyName: string): {
        found: boolean;
        state: string;
        animator: string;
        visible: boolean;
        distance: number;
        hasTarget: boolean;
        target: { x: number; y: number; z: number } | null;
        askedVelocity: { x: number; z: number } | null;
        realVelocity: { x: number; z: number } | null;
        lunge: { x: number; z: number } | null;
        position: { x: number; y: number; z: number } | null;
        attackId: number;
        health: number;
      } {
        const blank = {
          found: false, state: '', animator: '', visible: false, distance: 0, hasTarget: false,
          target: null, askedVelocity: null, realVelocity: null, lunge: null, position: null,
          attackId: 0, health: 0,
        };
        const enemy = app.world.findEntityByName(enemyName);
        const hunter = enemy === null ? null : optionalRead(app, enemy, 'Hunter');
        if (enemy === null || hunter === null) return blank;
        // The composed placement is stale until something asks: a reading taken
        // between frames would otherwise report where the enemy was, beside a
        // distance computed from where it is.
        app.world.ensureTransformsComposed();

        const sight = optionalRead(app, enemy, 'Perception');
        const agent = optionalRead(app, enemy, 'NavAgent');
        const body = app.world.has(enemy, CharacterController3D)
          ? app.world.get(enemy, CharacterController3D) : null;
        const root = app.world.has(enemy, AnimatorRootMotion)
          ? app.world.get(enemy, AnimatorRootMotion) : null;
        const t = app.world.has(enemy, Transform) ? app.world.get(enemy, Transform) : null;
        const p = t ? (t.worldPosition ?? t.position) : null;
        return {
          found: true,
          state: hunter.state,
          animator: app.world.has(enemy, Animator)
            ? app.world.get(enemy, Animator).currentState : '',
          visible: sight?.visible ?? false,
          // The ground plane, which is what the hunter itself decides on — and
          // zero when nothing is seen, since the fields it would be read from
          // are stale rather than empty.
          distance: sight?.visible && p
            ? Math.hypot(sight.targetX - p.x, sight.targetZ - (p.z ?? 0)) : 0,
          hasTarget: agent?.hasTarget ?? false,
          target: agent ? { x: agent.targetX, y: agent.targetY, z: agent.targetZ } : null,
          askedVelocity: body ? { x: body.velocity.x, z: body.velocity.z } : null,
          realVelocity: body ? { x: body.realVelocity.x, z: body.realVelocity.z } : null,
          // What the ATTACK is asking for, as the rate it covers — the request the
          // steering velocity above has already been overwritten with or cleared.
          lunge: root?.active && root.deltaTime > 0
            ? { x: root.deltaPosition.x / root.deltaTime, z: root.deltaPosition.z / root.deltaTime }
            : null,
          position: p ? { x: p.x, y: p.y, z: p.z ?? 0 } : null,
          attackId: optionalRead(app, enemy, 'MeleeAttack')?.attackId ?? 0,
          health: optionalRead(app, enemy, 'Health')?.current ?? 0,
        };
      },
      /**
       * What a swing IS and what it has done to whom: the live attack instance
       * and every named target's health. Off the same components the game runs
       * on, and read-only — a driver that could deal damage would be answering
       * its own question, so damage still has to come from the keyboard.
       */
      combat(attackerName: string, targetNames: string[] = []): {
        attack: { id: number; hitCount: number; state: string } | null;
        targets: Record<string, { health: number; max: number }>;
      } {
        const targets: Record<string, { health: number; max: number }> = {};
        for (const name of targetNames) {
          const entity = app.world.findEntityByName(name);
          const health = entity === null ? null : optionalRead(app, entity, 'Health');
          if (health === null) continue;
          targets[name] = { health: health.current as never, max: health.max as never };
        }
        const attacker = app.world.findEntityByName(attackerName);
        const melee = attacker === null ? null : optionalRead(app, attacker, 'MeleeAttack');
        if (attacker === null || melee === null) return { attack: null, targets };
        return {
          attack: {
            id: melee.attackId,
            hitCount: melee.hitCount,
            state: app.world.has(attacker, Animator)
              ? app.world.get(attacker, Animator).currentState : '',
          },
          targets,
        };
      },
      /**
       * How many particles a named emitter is running. The far END of a chain
       * that starts in a clip: nothing else can say a moment the animation
       * declared reached the effect a project chose to answer it with, since a
       * position cannot and a unit test stops at the event being posted.
       */
      particles(names: string[] = []): Record<string, number> {
        const out: Record<string, number> = {};
        if (!app.hasResource(Particle)) return out;
        const api = app.getResource(Particle);
        for (const name of names) {
          const entity = app.world.findEntityByName(name);
          if (entity === null) continue;
          out[name] = api.getAliveCount(entity);
        }
        return out;
      },
      /**
       * What a third-person character IS: where it stands, what the physics step
       * gave it, what its animator was told. Read-only, off the same components
       * the game runs on — pixels cannot say whether a ramp was climbed, and a
       * unit test answers about the request rather than the result.
       */
      gameplay(playerName: string, cameraName?: string): {
        found: boolean;
        position: { x: number; y: number; z: number } | null;
        realVelocity: { x: number; y: number; z: number } | null;
        askedVelocity: { x: number; y: number; z: number } | null;
        grounded: boolean;
        animator: { speed: number; grounded: boolean; state: string } | null;
        camera: { x: number; y: number; z: number } | null;
        cameraDistance: number | null;
      } {
        const blank = {
          found: false, position: null, realVelocity: null, askedVelocity: null,
          grounded: false, animator: null, camera: null, cameraDistance: null,
        };
        const player = app.world.findEntityByName(playerName);
        if (player === null || !app.world.has(player, Transform)) return blank;

        const t = app.world.get(player, Transform);
        const p = t.worldPosition ?? t.position;
        const position = { x: p.x, y: p.y, z: p.z ?? 0 };

        let realVelocity = null;
        let askedVelocity = null;
        let grounded = false;
        if (app.world.has(player, CharacterController3D)) {
          const c = app.world.get(player, CharacterController3D);
          realVelocity = { x: c.realVelocity.x, y: c.realVelocity.y, z: c.realVelocity.z };
          askedVelocity = { x: c.velocity.x, y: c.velocity.y, z: c.velocity.z };
          grounded = c.isOnFloor;
        }

        let animator = null;
        if (app.hasResource(AnimatorController) && app.world.has(player, Animator)) {
          const ctrl = app.getResource(AnimatorController);
          animator = {
            speed: ctrl.getFloat(player, TPC_SPEED),
            grounded: ctrl.getBool(player, TPC_GROUNDED),
            state: app.world.get(player, Animator).currentState,
          };
        }

        let camera = null;
        let cameraDistance = null;
        const eye = cameraName ? app.world.findEntityByName(cameraName)
          : (optionalEntities(app, 'ThirdPersonCamera')[0] ?? null);
        if (eye !== null && eye !== undefined && app.world.has(eye, Transform)) {
          const ct = app.world.get(eye, Transform);
          const cp = ct.worldPosition ?? ct.position;
          camera = { x: cp.x, y: cp.y, z: cp.z ?? 0 };
          cameraDistance = Math.hypot(cp.x - position.x, cp.y - position.y,
                                      (cp.z ?? 0) - position.z);
        }

        return { found: true, position, realVelocity, askedVelocity, grounded,
                 animator, camera, cameraDistance };
      },
      /**
       * Advance the world by `frames` steps of exactly `dt`, wall clock ignored.
       *
       * What a driver measures between two probes is otherwise a function of
       * when the runner got scheduled — and two launches of ONE package disagree
       * by more than a compiled system reading the wrong field does.
       */
      async step(frames = 1, dt = 1 / 60): Promise<void> {
        await app.stepFrames(frames, dt);
      },
      /**
       * Hand the clock to the driver. `step` alone is not enough: it pauses the
       * loop only while it runs, so between two calls the world still advances by
       * whatever wall time the round trip took — which is the runner's load, not
       * the game's. Paused, the only frames are the ones a driver asks for.
       */
      setPaused(paused: boolean): void {
        app.setPaused(paused);
      },
      /**
       * What the GAME says about its own run. The rest of this seam reports the
       * engine's side of a frame, and a checkpoint or a victory lives only in
       * the game's own state. A copy: this observes a run, it never drives one.
       */
      facts(): Record<string, string | number | boolean> {
        if (!app.hasResource(Playthrough)) return {};
        return { ...app.getResource(Playthrough).facts };
      },
      /**
       * A way from one named entity to another, over the same navigation grid
       * the game's own enemies walk. A driver that steers straight at its goal
       * is a driver that walks into the first wall between them; asking the
       * game means the route stays right when the level is re-authored.
       */
      pathBetween(fromName: string, toName: string): Array<{ x: number; y: number }> | null {
        // Through the App's own by-name door: `Nav` is a RESOURCE, and the
        // component registry optionalDef reads has never held one — asked there
        // it answered null, and every path this host was asked for was no path.
        const nav = app.getResourceByName('Nav') as
          { findWorldPath(a: { x: number; y: number }, b: { x: number; y: number }): Array<{ x: number; y: number }> | null } | undefined;
        if (!nav) return null;
        const ends = [fromName, toName].map((name) => {
          const entity = app.world.findEntityByName(name);
          if (entity === null || !app.world.has(entity, Transform)) return null;
          const p = app.world.get(entity, Transform).position;
          return { x: p.x, y: p.y };
        });
        if (!ends[0] || !ends[1]) return null;
        return nav.findWorldPath(ends[0], ends[1]);
      },
      /** Turns the engine's profiler off again, which render(), gpu() and costs() engage: a frame timed after it costs what a player's does. */
      quiet(): void {
        module.engine_setCpuProfiling?.(false);
      },
      /** The change audit (World.setChangeAudit): on, every frame counts component writes made without a change stamp. */
      changeAudit(enabled: boolean): void {
        app.world.setChangeAudit(enabled);
      },
      /** Component writes found without a change stamp since the audit was turned on. */
      changeAuditTotal(): number {
        return app.world.changeAuditTotal();
      },
      /**
       * What the last frame's renderer counted — the work a picture cannot show.
       * A field of props drawn at three levels and one drawn at one look alike
       * from outside; the counts are the difference. Engaging the profiler is
       * what fills them, so a package that is only played pays nothing.
       */
      render(): Record<string, number> {
        module.engine_setCpuProfiling?.(true);
        try {
          return JSON.parse(module.engine_getCounters?.() ?? '{}') as Record<string, number>;
        } catch {
          return {};
        }
      },
      /**
       * What the GPU spent on the last frames it has an answer for: `graph`, and `pass/<name>` for each render-graph pass.
       * The device answers a few frames late, so a value is the newest finished frame's, not the one just drawn. Engaging
       * the profiler is what turns the per-pass timers on.
       */
      gpu(detail = false): Record<string, number> {
        // Per-shader segments of the scene pass: read by the engine each frame while the profiler is on.
        (module as unknown as { esGpuDetail?: boolean }).esGpuDetail = detail;
        module.engine_setCpuProfiling?.(true);
        try {
          return JSON.parse(module.engine_getGpuScopes?.() ?? '{}') as Record<string, number>;
        } catch {
          return {};
        }
      },
      /**
       * The capability decisions the SHIPPING renderer committed to, asked of
       * the frame that drew rather than of the editor's account of what a build
       * would do. Those are two code paths, and an explanation that is right
       * about one nothing takes explains nothing.
       */
      renderFacts(): Record<string, unknown> {
        const post = app.hasResource(PostProcess) ? app.getResource(PostProcess) : null;
        return {
          backend: gpu.device ? 'webgpu' : 'webgl2',
          msaa: { requested: cfg.msaaSamples ?? null, ...(post?.msaaCapability() ?? {}) },
          hdr: post?.hdrFormat() ?? null,
          texture: app.getResource(Assets)?.textureFormatReport() ?? null,
        };
      },
      /**
       * The per-entity decisions a frame made about one named thing: which LOD
       * the view chose, whether the light cap kept it, what the shadow atlas
       * granted. Read through the same Renderer API the editor's panels use, so
       * a divergence here is the shipping path and not a second implementation.
       */
      decisions(name: string, view?: number): Record<string, unknown> | null {
        const entity = app.world.findEntityByName(name);
        if (entity === null) return null;
        // A LOD level belongs to a VIEW, not to the entity: asked with view 0 the
        // renderer has no record and answers null, which reads as "no LOD here".
        const camera = view ?? [...app.world.getEntitiesWithComponents([Camera])][0] ?? 0;
        return {
          entity,
          view: camera,
          lod: Renderer.lodInspect(camera >>> 0, entity),
          light: Renderer.lightStatus(entity),
          shadow: Renderer.shadowStatus(entity),
        };
      },
      /**
       * The project's own configuration, as the SHIPPING runtime holds it: what
       * the package carries beside what the runtime ended up with. A manifest
       * proving itself proves only that the packager wrote what it wrote.
       */
      configFacts(busNames: string[] = []): Record<string, unknown> {
        const audio = app.hasResource(Audio) ? app.getResource(Audio) : null;
        const names = new Set([...busNames, ...(cfg.audioConfig?.buses ?? []).map((b) => b.name)]);
        return {
          carried: { audioConfig: cfg.audioConfig ?? null },
          audio: audio ? {
            maxVoices: audio.maxVoices,
            buses: Object.fromEntries([...names].map((n) => [n, {
              volume: audio.getBusVolume(n), muted: audio.isBusMuted(n),
            }])),
          } : null,
        };
      },
      /**
       * Resize one named thing, so a LOD decision can be driven WITHOUT moving the
       * camera. Distance and projected size change together when a driver walks,
       * and a selector that used distance would pass a test that only ever walked.
       */
      setScale(name: string, s: number): boolean {
        const entity = app.world.findEntityByName(name);
        if (entity === null || !app.world.has(entity, Transform)) return false;
        app.world.update(entity, Transform, (t) => {
          t.scale.x = s; t.scale.y = s; t.scale.z = s;
        });
        return true;
      },
      /**
       * Take the GPU away, and read what the renderer says about itself after.
       *
       * Deliberately narrow: whether recovery is CORRECT is the renderer's own
       * device-loss corpus to judge. What this exists for is the question only
       * residency can answer — what an old readiness claim is worth afterwards.
       */
      device(): Record<string, number | boolean> {
        const m = module as unknown as {
          renderer_deviceGeneration?(): number;
          renderer_programEpoch?(): number;
        };
        return {
          generation: m.renderer_deviceGeneration?.() ?? -1,
          programEpoch: m.renderer_programEpoch?.() ?? -1,
          lost: gl ? gl.isContextLost() : false,
          // The CPU copies the device keeps to restore content after a loss.
          retainedBytes: getResourceStats()?.retainedBytes ?? -1,
        };
      },
      loseDevice(): boolean {
        const ext = gl?.getExtension('WEBGL_lose_context') as
          { loseContext(): void; restoreContext(): void } | null;
        if (!ext) return false;
        ext.loseContext();
        // Standing in for the browser, which hands a context back on its own.
        // The ENGINE's recovery is not driven here: AssetPlugin does that, and a
        // harness that drove it would be testing its own driver.
        setTimeout(() => ext.restoreContext(), 50);
        return true;
      },

      /** The render-program claim a cell is holding, if any. Through the report,
       *  because residency has one author and this is not it. */
      readiness(cell: string): Record<string, number> | null {
        const claim = worldResidencyReport(app).renderClaims?.[cell];
        return claim ? { ...claim } : null;
      },

      /**
       * What residency did, and what the subsystems still hold.
       *
       * The counts are the whole point: a far cell that is not DRAWN and one
       * that does not EXIST look identical from a camera. Read-only — nothing
       * here loads a cell, so residency still has to have been caused by walking.
       */
      streaming(): Record<string, unknown> {
        const report = worldResidencyReport(app);
        // By NAME: the 3D world is a side module, and importing its resource
        // here would pull the whole thing into a game that may not use physics.
        const physics = app.getResourceByName('Physics3DRuntime') as {
          bodies: Map<number, unknown>;
          characters: Map<number, unknown>;
          joints: Map<number, unknown>;
        } | undefined;
        let stalePhysics = 0;
        for (const rows of [physics?.bodies, physics?.characters, physics?.joints]) {
          for (const entity of rows?.keys() ?? []) {
            if (!app.world.valid(entity)) stalePhysics++;
          }
        }
        return {
          ...report,
          // Whether the 3D world is even up, so a zero body count cannot be read
          // as "the cell brought none" when it means "physics never loaded".
          physicsUp: physics !== undefined,
          physicsBodies: physics?.bodies.size ?? 0,
          physicsCharacters: physics?.characters.size ?? 0,
          // Rows physics still keeps for entities the world no longer has. A
          // teardown that forgot one shows up here and nowhere else.
          stalePhysics,
          navAgents: countOfIn(app, 'NavAgent'),
          hunters: countOfIn(app, 'Hunter'),
          entities: app.world.entityCount(),
        };
      },
      /**
       * What the LAST frame cost, by system.
       *
       * The other half of a cell's arrival: the load runs between frames and
       * shows on no system timer, while registering what it spawned happens
       * inside systems on the frames after. Engaging the stats fills this.
       */
      costs(): {
        on: boolean;
        systems: Array<{ name: string; ms: number; domain: string }>;
        scopes: Array<{ name: string; ms: number; system: string; remainder: string }>;
        native: Record<string, number>;
      } {
        // Engaged once, BOTH halves. Re-enabling swaps the maps the frame just
        // filled; and the C++ scopes are behind their own switch, so engaging
        // only the JS side shows a renderer that costs nothing inside itself.
        if (!statsOn) {
          app.enableStats();
          (app.wasmModule as { engine_setCpuProfiling?: (on: boolean) => void } | null)
            ?.engine_setCpuProfiling?.(true);
          statsOn = true;
        }
        const costs = app.getFrameCosts();
        if (!costs) return { on: false, systems: [], scopes: [], native: {} };
        let native: Record<string, number> = {};
        try {
          const raw = (app.wasmModule as { engine_getCpuScopes?: () => string } | null)
            ?.engine_getCpuScopes?.();
          if (raw) native = JSON.parse(raw) as Record<string, number>;
        } catch { /* a frame with no scopes reports none */ }
        // EVERY system, not the dearest few: what a caller wants to know about
        // an arrival frame is how much of it the breakdown explains, and a
        // truncated list can only ever be a lower bound on its own total.
        //
        // Systems are mutually exclusive and scopes nest INSIDE them, so the two
        // lists are never added together — that is how a breakdown reaches 130%.
        return {
          on: true,
          systems: [...costs.systems]
            .map((s) => ({ name: s.name, ms: s.ms, domain: s.domain }))
            .sort((a, b) => b.ms - a.ms),
          scopes: [...costs.scopes]
            .map((s) => ({ name: s.name, ms: s.ms, system: s.system, remainder: s.remainder }))
            .sort((a, b) => b.ms - a.ms),
          native,
        };
      },
      /** Drive a hot update against a served (CDN) manifest: fetch + diff + apply.
       *  Rebinding the visuals is the game's job (via Assets.onInvalidate); a
       *  driver settles frames after this before re-capturing. */
      async applyRemoteUpdate(manifestUrl: string, remoteRoot?: string) {
        const assets = app.getResource(Assets);
        const plan = await assets.checkForUpdate({ manifestUrl, remoteRoot });
        const result = await assets.applyUpdate();
        return {
          changed: plan.changedAssets.length, applied: result.ok, failed: result.failed.length,
          stages: result.stages, revision: result.revision,
        };
      },
      updateStatus: () => app.getResource(Assets).updateStatus(),
      /** What the engine is still baking in the background (the world laying itself out, plants growing): empty once it has caught up. */
      bakes(): readonly { label: string; progress: number }[] {
        return app.hasResource(BakesRes) ? app.getResource(BakesRes).active : [];
      },
    };
    // Each behind its OWN export. They are different ABIs now: readying a
    // prepared cell ships, and deriving the same from live entities is the
    // oracle that judges it and exists only in a probe build.
    const has = (name: string): boolean =>
      typeof (module as unknown as Record<string, unknown>)[name] === 'function';
    if (has('engine_prepareMeshPrograms')) cooked.prepareMeshPrograms = prepareMeshPrograms;
    if (has('engine_prewarmMeshVariants')) cooked.prewarmMeshVariants = prewarmMeshVariants;
    (window as unknown as { __estellaCooked?: unknown }).__estellaCooked = cooked;
  }
  // physics.wasm sits next to esengine.wasm; the runtime loads it when a scene
  // uses physics, or when the project declared physics on for bodies it spawns
  // from script (packagedRuntimeInit carries that flag).
  // The entry scene boots eagerly (already fetched); every other shipped scene
  // registers lazily by path, so SceneManager.switchTo('name') fetches it on
  // first use — the same registration shape the WeChat runtime uses.
  const sceneList = cfg.scenes ?? [];
  const entryName = sceneList.find((s) => s.path === cfg.entryScene)?.name ?? '__play';
  // Cross-origin images taint a canvas, so a cooked build decodes through
  // fetch+blob rather than the platform's Image path.
  const source = createPackagedAssetSource(index, {
    backend: new HttpBackend({ baseUrl: '' }),
    decodePixels: (path) => fetchDecodePixels(path),
  });
  applyAssetRefResolvers(app, index.resolvePath);
  await initRuntime({
    app,
    module,
    source,
    // The compiled twins this build produced, if any. The path, not the bytes:
    // reading it is the platform seam's job, and on a mini-game only the seam
    // knows how (docs/REARCH_AOT.md §9).
    manifest: index.manifest,
    catalog: index.catalog,
    remoteRoot: cfg.hotUpdate?.remoteRoot,
    persistUpdateKey: cfg.hotUpdate?.persistUpdateKey,
    scenes: [
      { name: entryName, data: sceneData },
      ...sceneList.filter((s) => s.path !== cfg.entryScene).map((s) => ({ name: s.name, path: s.path })),
    ],
    ...(worlds.length > 0 ? { worlds } : {}),
    firstScene: entryName,
    aspectRatio: canvas.width / canvas.height,
    // Everything the config APPLIES to a live app: physics, the mixer, the theme.
    ...packagedRuntimeInit(cfg),
  });
  poki?.loaded();
  crazyGames?.loaded();
  splash?.reach('assets');
  // With the shaders compiled in the background, the first scene is drawn out of sight until they are ready (the splash is still up), so the
  // game opens on a complete picture; without this it opens at once and fills in.
  if (cfg.quality?.asyncShaderCompile && cfg.quality.prewarmShaders) {
    try {
      const warmed = await warmShaders(app, {
        timeoutMs: cfg.quality.prewarmTimeoutMs,
        // The stage list has no stage for this, and it can be most of a boot: say so rather than sit on "Ready".
        onProgress: (pending) => splash?.busy(pending > 0 ? 'Compiling shaders' : 'Preparing the scene'),
      });
      if (warmed.timedOut) console.warn(`[game] ${warmed.pending} shader(s) still compiling after ${Math.round(warmed.ms)} ms; opening anyway`);
    } catch (error) {
      console.warn('[game] shader warm-up failed', error);
    }
  }
  // After the warm-up above: its frames exist to be drawn.
  if (cfg.quality?.renderOnDemand) app.pipeline?.demand.enable({ tailFrames: cfg.quality.renderOnDemandTail });
  // Before run(), not after: run() may hand control to the emscripten loop and
  // never return, and the fade is what the first frames should arrive through.
  splash?.reach('ready');
  splash?.done();
  if (youtube) {
    let sent = false;
    const offFrame = app.onFrameEnd(() => {
      if (sent) return; sent = true; offFrame();
      const ready = async () => {
        while (document.getElementById('es-splash')) await new Promise<void>(resolve => setTimeout(resolve, 30));
        await youtube.gameReady();
      };
      void ready().catch(error => console.warn('[YouTube] Ready notification failed', error));
    });
  }
  if (typeof __ESTELLA_LAN_PREVIEW__ !== 'undefined' && __ESTELLA_LAN_PREVIEW__) installDevicePreview(app, cfg.scripts);
  app.run();
}

boot().catch((err) => {
  const message = err instanceof Error ? err.message : String(err);
  if (err === 'unwind' || message.includes('unwind')) return; // emscripten loop took over — success
  console.error('[game] boot failed', err);
  // The game realm has no editor stylesheet — this literal mirrors --error.
  document.body.innerHTML = `<pre style="color:#d65a5a;padding:20px;font:13px monospace">${message}</pre>`;
});