@holtjs/stage 0.10.2 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,5 +1,6 @@
1
- import { I as ScaleMode, M as Matrix2D, N as Rect2D, O as EventEmitter, P as RgbaColor, R as TintMode, S as TextureSource, T as BlendMode, U as WorldView2D, _ as SpriteSheetConfig, d as AtlasJsonLike, g as GlTextureHost, p as Frame, r as AnimationManager, u as StageAnimation, v as Texture, x as TextureManager, y as TextureImageOptions } from "./anims-D9N8w6IM.js";
1
+ import { I as ScaleMode, M as Matrix2D, N as Rect2D, O as EventEmitter, P as RgbaColor, R as TintMode, S as TextureSource, T as BlendMode, U as WorldView2D, _ as SpriteSheetConfig, d as AtlasJsonLike, g as GlTextureHost, p as Frame, r as AnimationManager, u as StageAnimation, v as Texture, x as TextureManager, y as TextureImageOptions } from "./anims-BYBzSNXO.js";
2
2
  import { c as TweenManager, u as TweenStats } from "./tween-BiF1FUvc.js";
3
+ import { a as ScriptOptions, i as ScriptHandle, o as ScriptScheduler, r as ScriptContext, s as ScriptStats, t as CoroutineGenerator } from "./coroutine-DLgJumtD.js";
3
4
  interface CameraFollowOptions {
4
5
  /** Horizontal smoothing factor in `(0, 1]` (`1` = instant lock; default `1`). */
5
6
  lerpX?: number;
@@ -930,6 +931,80 @@ declare class ShapeBatchObject extends DisplayObject {
930
931
  setColumns(columns: ShapeBatchColumns): this;
931
932
  destroy(fromScene?: boolean): void;
932
933
  }
934
+ interface DrawStreamOptions {
935
+ /** Initial sprite instance capacity (`default = 256`, doubles automatically on demand). */
936
+ initialCapacity?: number;
937
+ /** Default frame when `sprite()` passes `undefined` (`default = '__BASE'`). */
938
+ defaultFrame?: string | number;
939
+ /** Automatically reset `count = 0` on scene `'preupdate'` each tick (`default = true`). */
940
+ autoReset?: boolean;
941
+ /** Automatically sort emitted instances by `depth` (ascending painter's order) before render (`default = false`). */
942
+ depthSort?: boolean;
943
+ /** Scene-graph depth of this `DrawStreamObject`. */
944
+ depth?: number;
945
+ /** Optional blend mode (`BlendModes.NORMAL`, `ADD`, `MULTIPLY`, `SCREEN`). */
946
+ blendMode?: BlendMode;
947
+ /** Scroll factor (`default = 1` world space; `0` screen/HUD space). */
948
+ scrollFactor?: number;
949
+ /** Optional logical stream key when acquired via `scene.drawStream(textureKey, opts)`. */
950
+ streamId?: string;
951
+ }
952
+ interface DrawStreamSpriteOptions {
953
+ scale?: number;
954
+ scaleX?: number;
955
+ scaleY?: number;
956
+ rotation?: number;
957
+ alpha?: number;
958
+ tint?: number;
959
+ depth?: number;
960
+ }
961
+ interface DrawStreamBulkView {
962
+ readonly x: Float32Array;
963
+ readonly y: Float32Array;
964
+ readonly scaleX: Float32Array;
965
+ readonly scaleY: Float32Array;
966
+ readonly rotation: Float32Array;
967
+ readonly alpha: Float32Array;
968
+ readonly tint: Uint32Array;
969
+ readonly frameIndex: Int32Array;
970
+ readonly depth: Float32Array;
971
+ }
972
+ /**
973
+ * Stateless per-frame immediate-mode sprite batch (`scene.drawStream(textureKey)` or `scene.add.drawStream(...)`).
974
+ * Submits thousands of transient drops, projectiles, grass tufts, or minimap markers in 1 GPU instanced draw call
975
+ * across WebGPU, WebGL2, and Canvas2D with zero retained `DisplayObject` allocations!
976
+ */
977
+ declare class DrawStreamObject extends InstancedBatchObject {
978
+ autoReset: boolean;
979
+ depthSort: boolean;
980
+ private cap;
981
+ private curCount;
982
+ private depthDirty;
983
+ private colX;
984
+ private colY;
985
+ private colSx;
986
+ private colSy;
987
+ private colRot;
988
+ private colAlpha;
989
+ private colTint;
990
+ private colFrame;
991
+ private colDepth;
992
+ private colOrder;
993
+ private readonly liveColumns;
994
+ private readonly detachEvents;
995
+ constructor(scene: SceneHostLike, key: string, options?: DrawStreamOptions);
996
+ get count(): number;
997
+ /** Reset write cursor to `0` for a fresh frame (zero memory freed or allocated). */
998
+ begin(): this;
999
+ private ensureStreamCapacity;
1000
+ /** Append a single sprite command in O(1) zero-GC typed-array writes; returns emitted instance index. */
1001
+ sprite(frame: string | number | undefined, x: number, y: number, opts?: DrawStreamSpriteOptions): number;
1002
+ /** Reserve `count` contiguous instance slots for bulk SIMD / Worker `TypedArray.set()` fills! */
1003
+ writeBulk(count: number, writer: (cols: DrawStreamBulkView, offset: number) => void): number;
1004
+ /** Materialize ascending `depth` painter's order in `columns.order` when `depthSort: true`. */
1005
+ flushOrder(): void;
1006
+ destroy(fromScene?: boolean): void;
1007
+ }
933
1008
  interface RendererGlOptions {
934
1009
  transparent?: boolean;
935
1010
  antialias?: boolean;
@@ -1128,6 +1203,9 @@ declare class Renderer2D extends EventEmitter {
1128
1203
  private tintCanvas;
1129
1204
  private tintCtx;
1130
1205
  private readonly tintCache;
1206
+ private static readonly MAX_SLICE_BYTES;
1207
+ private readonly sliceCache;
1208
+ private sliceBytes;
1131
1209
  private readonly maskWorldMat;
1132
1210
  private readonly rootScrollMat;
1133
1211
  private readonly matPool;
@@ -1155,8 +1233,10 @@ declare class Renderer2D extends EventEmitter {
1155
1233
  msdfDraws: number;
1156
1234
  pixelAaIcons: number;
1157
1235
  pixelAaDraws: number;
1236
+ frameSlices: number;
1158
1237
  };
1159
1238
  resize(width: number, height: number): void;
1239
+ private getFrameSlice;
1160
1240
  private getTintedSource;
1161
1241
  private isOffscreen;
1162
1242
  private mulMat;
@@ -1540,6 +1620,411 @@ declare function sanitizeTrackToken(raw: unknown, maxLen?: number): string | nul
1540
1620
  * tokens and explicitly declared semantic `alt` labels.
1541
1621
  */
1542
1622
  declare function buildSceneDigest(scene: Scene, opts?: SceneDigestOptions): SceneDigest;
1623
+ /** Pack signed 16-bit chunk coordinates `[-32768..32767]` into a single 32-bit integer Map key (zero string allocation). */
1624
+ declare function packChunkKey(cx: number, cy: number): number;
1625
+ declare function unpackChunkX(key: number): number;
1626
+ declare function unpackChunkY(key: number): number;
1627
+ declare function floorDiv(a: number, b: number): number;
1628
+ declare function positiveMod(a: number, b: number): number;
1629
+ /**
1630
+ * Compute Oskar Stålberg's 4-bit **Dual-Grid** mask (`0..15`) for visual vertex `(vx, vy)`,
1631
+ * which sits at world `(vx * tileSize - tileSize * 0.5, vy * tileSize - tileSize * 0.5)` and samples
1632
+ * the 4 surrounding logical cells `(vx-1, vy-1)`, `(vx, vy-1)`, `(vx-1, vy)`, `(vx, vy)`.
1633
+ *
1634
+ * Bit layout: `TL (8) | TR (4) | BL (2) | BR (1)`.
1635
+ * - `0` = completely empty (do not draw this overlay layer)
1636
+ * - `15` = solid interior fill
1637
+ * - `1..14` = 14 organic rounded corners, edges, and diagonal saddles (`6` and `9`)
1638
+ */
1639
+ declare function computeDualGridMask(tl: boolean, tr: boolean, bl: boolean, br: boolean): number;
1640
+ /**
1641
+ * Compute the canonical **47-tile Blob** index (`0..46`) from 8 neighbors (`n, ne, e, se, s, sw, w, nw`).
1642
+ * Diagonal bits are automatically gated by their two adjacent cardinal neighbors so invalid corner combinations collapse cleanly.
1643
+ */
1644
+ declare function computeBlob47Index(n: boolean, ne: boolean, e: boolean, se: boolean, s: boolean, sw: boolean, w: boolean, nw: boolean): number;
1645
+ interface TileChunk {
1646
+ readonly cx: number;
1647
+ readonly cy: number;
1648
+ readonly size: number;
1649
+ /** Primary ground turf ID per cell (`Uint16Array(size * size)`). */
1650
+ readonly ground: Uint16Array;
1651
+ /** Optional wall / road / overlay ID per cell (`Uint16Array(size * size)`). */
1652
+ readonly overlay: Uint16Array;
1653
+ /** Per-cell bitflags (`bit 0 = solid/blocked`, `bit 1 = water`, `bit 2 = modifiedByPlayer`). */
1654
+ readonly flags: Uint8Array;
1655
+ /** Monotonic revision incremented whenever this chunk or a 1-tile neighbor mutates. */
1656
+ version: number;
1657
+ /** True if player/world simulation mutated at least one cell away from procedural baseline. */
1658
+ modified: boolean;
1659
+ }
1660
+ declare const TileCellFlags: {
1661
+ readonly NONE: 0;
1662
+ readonly SOLID: 1;
1663
+ readonly WATER: 2;
1664
+ readonly MODIFIED: 4;
1665
+ };
1666
+ type ChunkGeneratorFn = (cx: number, cy: number, chunk: TileChunk) => void;
1667
+ interface ChunkedTilemapOptions {
1668
+ chunkSize?: number;
1669
+ tileSize?: number;
1670
+ defaultGround?: number;
1671
+ generator?: ChunkGeneratorFn;
1672
+ }
1673
+ /**
1674
+ * Sparse chunked 2D world grid supporting massive/infinite survival worlds (`+/-1,000,000` cells)
1675
+ * with lazy procedural chunk creation, cross-border autotile dirty propagation, and O(1) nav collision queries.
1676
+ */
1677
+ declare class ChunkedTilemap {
1678
+ readonly chunkSize: number;
1679
+ readonly tileSize: number;
1680
+ readonly defaultGround: number;
1681
+ private readonly chunks;
1682
+ private generator;
1683
+ private globalRevision;
1684
+ constructor(opts?: ChunkedTilemapOptions);
1685
+ get loadedChunkCount(): number;
1686
+ get revision(): number;
1687
+ setGenerator(gen: ChunkGeneratorFn | undefined): void;
1688
+ hasChunk(cx: number, cy: number): boolean;
1689
+ peekChunk(cx: number, cy: number): TileChunk | undefined;
1690
+ getOrCreateChunk(cx: number, cy: number): TileChunk;
1691
+ /** Iterate over all currently materialized chunks without copying. */
1692
+ forEachChunk(fn: (chunk: TileChunk) => void): void;
1693
+ unloadChunk(cx: number, cy: number): boolean;
1694
+ worldToTileX(wx: number): number;
1695
+ worldToTileY(wy: number): number;
1696
+ tileToWorldCenter(tx: number, ty: number, out?: {
1697
+ x: number;
1698
+ y: number;
1699
+ }): {
1700
+ x: number;
1701
+ y: number;
1702
+ };
1703
+ getGround(tx: number, ty: number, createIfMissing?: boolean): number;
1704
+ setGround(tx: number, ty: number, turfId: number, markModified?: boolean): void;
1705
+ getOverlay(tx: number, ty: number, createIfMissing?: boolean): number;
1706
+ setOverlay(tx: number, ty: number, overlayId: number, solid?: boolean, markModified?: boolean): void;
1707
+ getFlags(tx: number, ty: number, createIfMissing?: boolean): number;
1708
+ setSolid(tx: number, ty: number, solid: boolean, markModified?: boolean): void;
1709
+ isWalkable(tx: number, ty: number, createIfMissing?: boolean): boolean;
1710
+ /** Sample the 4-bit Dual-Grid mask (`0..15`) for visual vertex `(vx, vy)` matching `predicate(turfId)`. */
1711
+ sampleDualGridMask(vx: number, vy: number, predicate: (turfId: number) => boolean): number;
1712
+ /** Sample the canonical 47-tile Blob index (`0..46`) at `(tx, ty)` for wall/cliff `overlayId`. */
1713
+ sampleOverlayBlob47(tx: number, ty: number, predicate: (overlayId: number) => boolean): number;
1714
+ /**
1715
+ * Extract a dense `Uint8Array` obstacle grid (`1 = blocked, 0 = walkable`) over `[originTx..originTx+cols-1, originTy..originTy+rows-1]`
1716
+ * ready to feed directly into `FlowFieldGrid` or `findGridPath` (`@holtjs/stage/nav`).
1717
+ */
1718
+ extractObstacleGrid(originTx: number, originTy: number, cols: number, rows: number, out?: Uint8Array): Uint8Array;
1719
+ private bumpChunkAndBorderNeighbors;
1720
+ }
1721
+ declare function hash2D(ix: number, iy: number, seed: number): number;
1722
+ declare function valueNoise2D(x: number, y: number, seed: number): number;
1723
+ declare function fbm2D(x: number, y: number, seed: number, octaves?: number): number;
1724
+ declare const SurvivalBiomes: {
1725
+ readonly OCEAN: 0;
1726
+ readonly BEACH: 1;
1727
+ readonly MEADOW: 2;
1728
+ readonly FOREST: 3;
1729
+ readonly GRAVEYARD_STONE: 4;
1730
+ readonly COBBLESTONE_ROAD: 5;
1731
+ };
1732
+ interface IslandBiomeConfig {
1733
+ seed: number;
1734
+ radiusTiles?: number;
1735
+ featureScale?: number;
1736
+ }
1737
+ /** Build a deterministic *Don't Starve* / *Graveyard Keeper* island chunk generator from a single integer seed. */
1738
+ declare function createIslandBiomeGenerator(cfg: IslandBiomeConfig): ChunkGeneratorFn;
1739
+ interface DualGridLayerSpec {
1740
+ id: string;
1741
+ fillColor: number;
1742
+ edgeColor: number;
1743
+ speckleColor?: number;
1744
+ /** Returns true when a ground `turfId` belongs to (or sits above) this Dual-Grid terrain layer. */
1745
+ matches: (turfId: number) => boolean;
1746
+ }
1747
+ interface BakedDualGridAtlas {
1748
+ readonly textureKey: string;
1749
+ readonly tileSize: number;
1750
+ readonly canvas: HTMLCanvasElement;
1751
+ readonly layers: ReadonlyArray<DualGridLayerSpec>;
1752
+ frameName(layerId: string, mask: number): string;
1753
+ registerOnScene(scene: SceneHostLike): void;
1754
+ }
1755
+ /**
1756
+ * Bake one or more 16-tile (`0..15`) organic Dual-Grid terrain layers onto a single crisp texture atlas!
1757
+ * Uses smooth analytical quarter-circle / saddle SDF distance fields per pixel so beaches, grass, dark forest,
1758
+ * and cobblestone roads interlock with hand-crafted *Don't Starve* turf borders.
1759
+ */
1760
+ declare function bakeDualGridTileset(textureKey: string, tileSize: number, layers: DualGridLayerSpec[], createCanvasFn?: (w: number, h: number) => HTMLCanvasElement): BakedDualGridAtlas;
1761
+ interface MountedChunkedTilemap {
1762
+ readonly container: Container;
1763
+ readonly blitters: ReadonlyArray<BlitterObject>;
1764
+ /** Update visible chunks around `(viewLeft, viewTop, viewWidth, viewHeight)` in world pixels (O(visibleChunks)). */
1765
+ syncViewport(viewLeft: number, viewTop: number, viewWidth: number, viewHeight: number): void;
1766
+ /** Convenience alias accepting `Camera25D.getGroundViewportBounds()` (`{ left, top, width, height }`) directly. */
1767
+ update(bounds: {
1768
+ left: number;
1769
+ top: number;
1770
+ width: number;
1771
+ height: number;
1772
+ }): void;
1773
+ readonly activeChunkCount: number;
1774
+ readonly activeBobCount: number;
1775
+ destroy(): void;
1776
+ }
1777
+ /**
1778
+ * Mount a `ChunkedTilemap` + `BakedDualGridAtlas` onto a Stage `Scene`.
1779
+ * - On WebGL2 / WebGPU: batches into 1 GPU `BlitterObject` draw call per Dual-Grid layer.
1780
+ * - On Canvas2D / pure-Node `createHeadlessStage`: automatically pre-composites all Dual-Grid layers of each
1781
+ * `16×16` chunk onto a cached offscreen chunk canvas keyed by `chunk.version` (collapsing ~4,500 per-frame
1782
+ * rotated tile `drawImage` calls down to ~12 chunk blits — >10× faster 60 FPS headless video rendering!).
1783
+ */
1784
+ declare function mountChunkedTilemap(scene: SceneHostLike, map: ChunkedTilemap, atlas: BakedDualGridAtlas, opts?: {
1785
+ baseColor?: number;
1786
+ depth?: number;
1787
+ marginChunks?: number;
1788
+ trackId?: string;
1789
+ chunkCache?: boolean;
1790
+ }): MountedChunkedTilemap;
1791
+ interface ItemDef {
1792
+ id: string;
1793
+ name?: string;
1794
+ maxStack?: number;
1795
+ /** Time in ms until `freshness01` decays from `1.0` to `0.0` (`undefined` = non-perishable). */
1796
+ spoilDurationMs?: number;
1797
+ /** Item ID produced when `freshness01` hits `0` (`default = 'rot'`). */
1798
+ spoiledItemId?: string;
1799
+ /** Fuel burn time in ms when fed into a fuel-burning workstation (`undefined` = not fuel). */
1800
+ fuelValueMs?: number;
1801
+ /** Max tool uses (`undefined` = infinite durability). */
1802
+ maxUses?: number;
1803
+ }
1804
+ interface ItemStack {
1805
+ itemId: string;
1806
+ count: number;
1807
+ freshness01: number;
1808
+ durability01: number;
1809
+ }
1810
+ declare class ItemRegistry {
1811
+ private readonly defs;
1812
+ register(def: ItemDef): this;
1813
+ registerAll(list: ReadonlyArray<ItemDef>): this;
1814
+ /** Replace all registered item definitions in-place (preserving `ItemRegistry` identity for live `InventoryContainer`s!). */
1815
+ replaceAll(list: ReadonlyArray<ItemDef>): this;
1816
+ get size(): number;
1817
+ ids(): string[];
1818
+ get(itemId: string): ItemDef | undefined;
1819
+ maxStackOf(itemId: string): number;
1820
+ }
1821
+ declare class InventoryContainer {
1822
+ readonly capacity: number;
1823
+ readonly registry: ItemRegistry;
1824
+ /** Spoilage rate multiplier (`1.0` normal backpack, `0.25` icebox, `0` preserved). */
1825
+ spoilMultiplier: number;
1826
+ readonly slots: Array<ItemStack | null>;
1827
+ constructor(registry: ItemRegistry, capacity?: number, spoilMultiplier?: number);
1828
+ countItem(itemId: string): number;
1829
+ hasItems(reqs: ReadonlyArray<{
1830
+ itemId: string;
1831
+ count: number;
1832
+ }>): boolean;
1833
+ /** Add items, merging weighted freshness into existing partial stacks first; returns leftover count that did not fit. */
1834
+ addItem(itemId: string, count?: number, freshness01?: number, durability01?: number): number;
1835
+ /** Consume up to `count` of `itemId`; returns true if the full requested amount was removed. */
1836
+ removeItem(itemId: string, count?: number): boolean;
1837
+ /** Advance perishable spoilage across all slots; converts fully spoiled stacks into `spoiledItemId` (`'rot'`). */
1838
+ stepSpoilage(deltaMs: number): number;
1839
+ toJSON(): Array<ItemStack | null>;
1840
+ loadJSON(data: ReadonlyArray<ItemStack | null>): void;
1841
+ }
1842
+ interface RecipeDef {
1843
+ id: string;
1844
+ /** Required workstation kind (`null` / `undefined` = hand-craftable anywhere). */
1845
+ stationKind?: string | null;
1846
+ inputs: Array<{
1847
+ itemId: string;
1848
+ count: number;
1849
+ }>;
1850
+ outputs: Array<{
1851
+ itemId: string;
1852
+ count: number;
1853
+ }>;
1854
+ /** Processing duration in ms (`0` = instant craft). */
1855
+ durationMs?: number;
1856
+ /** Whether processing requires active fuel burning on the station (`default = false`). */
1857
+ requiresFuel?: boolean;
1858
+ }
1859
+ declare class RecipeRegistry {
1860
+ private readonly recipes;
1861
+ register(recipe: RecipeDef): this;
1862
+ registerAll(list: ReadonlyArray<RecipeDef>): this;
1863
+ /** Replace all registered crafting recipes in-place (preserving `RecipeRegistry` identity for live `WorkstationScheduler`s!). */
1864
+ replaceAll(list: ReadonlyArray<RecipeDef>): this;
1865
+ get size(): number;
1866
+ ids(): string[];
1867
+ get(recipeId: string): RecipeDef | undefined;
1868
+ canCraft(recipeId: string, inventory: InventoryContainer, availableStationKinds?: ReadonlySet<string>): boolean;
1869
+ /** Perform an instant craft directly from/into `inventory`. */
1870
+ craftInstant(recipeId: string, inventory: InventoryContainer, availableStationKinds?: ReadonlySet<string>): boolean;
1871
+ }
1872
+ interface WorkstationJob {
1873
+ recipeId: string;
1874
+ batchesRemaining: number;
1875
+ progressMs: number;
1876
+ }
1877
+ interface WorkstationSnapshot {
1878
+ id: string;
1879
+ kind: string;
1880
+ wx: number;
1881
+ wy: number;
1882
+ fuelRemainingMs: number;
1883
+ maxFuelMs: number;
1884
+ queue: WorkstationJob[];
1885
+ inputSlots: Array<ItemStack | null>;
1886
+ fuelSlots: Array<ItemStack | null>;
1887
+ outputSlots: Array<ItemStack | null>;
1888
+ }
1889
+ declare class WorkstationInstance {
1890
+ readonly id: string;
1891
+ readonly kind: string;
1892
+ wx: number;
1893
+ wy: number;
1894
+ fuelRemainingMs: number;
1895
+ readonly maxFuelMs: number;
1896
+ readonly inputInv: InventoryContainer;
1897
+ readonly fuelInv: InventoryContainer;
1898
+ readonly outputInv: InventoryContainer;
1899
+ readonly queue: WorkstationJob[];
1900
+ constructor(id: string, kind: string, itemRegistry: ItemRegistry, opts?: {
1901
+ wx?: number;
1902
+ wy?: number;
1903
+ maxFuelMs?: number;
1904
+ });
1905
+ get isBurning(): boolean;
1906
+ get activeProgress01(): number;
1907
+ private activeProgressRatio;
1908
+ enqueue(recipe: RecipeDef, batches?: number): boolean;
1909
+ private tryAutoRefuel;
1910
+ /**
1911
+ * Deterministically advance smelting/crafting + fuel burn + slot spoilage over arbitrarily small or huge `deltaMs`
1912
+ * (supports multi-minute offline chunk catch-up in exact analytical sub-steps!).
1913
+ */
1914
+ step(deltaMs: number, recipes: RecipeRegistry): number;
1915
+ toSnapshot(): WorkstationSnapshot;
1916
+ loadSnapshot(snap: WorkstationSnapshot): void;
1917
+ }
1918
+ declare class WorkstationScheduler {
1919
+ readonly items: ItemRegistry;
1920
+ readonly recipes: RecipeRegistry;
1921
+ private readonly stations;
1922
+ constructor(items: ItemRegistry, recipes: RecipeRegistry);
1923
+ addStation(station: WorkstationInstance): WorkstationInstance;
1924
+ getStation(id: string): WorkstationInstance | undefined;
1925
+ removeStation(id: string): boolean;
1926
+ stepAll(deltaMs: number): number;
1927
+ /** Return set of station `kind`s within `radiusPx` of `(wx, wy)` for proximity-gated crafting menus. */
1928
+ nearbyStationKinds(wx: number, wy: number, radiusPx?: number): Set<string>;
1929
+ toJSON(): WorkstationSnapshot[];
1930
+ loadJSON(snaps: ReadonlyArray<WorkstationSnapshot>): void;
1931
+ }
1932
+ interface WorldEntityRecord {
1933
+ id: string;
1934
+ kind: string;
1935
+ x: number;
1936
+ y: number;
1937
+ state?: Record<string, number | string | boolean>;
1938
+ }
1939
+ interface TileCellDelta {
1940
+ tx: number;
1941
+ ty: number;
1942
+ ground: number;
1943
+ overlay: number;
1944
+ flags: number;
1945
+ }
1946
+ interface WorldDeltaSnapshot {
1947
+ schemaVersion: 1;
1948
+ seed: number;
1949
+ dayCount: number;
1950
+ time01: number;
1951
+ tileDeltas: TileCellDelta[];
1952
+ spawnedOrModifiedEntities: WorldEntityRecord[];
1953
+ /** Seed-generated entity IDs that were chopped/mined/destroyed so they stay removed on reload! */
1954
+ removedSeedEntityIds: string[];
1955
+ workstations: WorkstationSnapshot[];
1956
+ playerInventory?: Array<ItemStack | null>;
1957
+ }
1958
+ /**
1959
+ * Capture ONLY player/simulation-modified tiles (`TileCellFlags.MODIFIED`) from a `ChunkedTilemap`
1960
+ * plus entity deltas and workstation states into a tiny `WorldDeltaSnapshot`.
1961
+ */
1962
+ declare function captureWorldDelta(opts: {
1963
+ seed: number;
1964
+ dayCount?: number;
1965
+ time01?: number;
1966
+ tilemap: ChunkedTilemap;
1967
+ spawnedOrModifiedEntities?: ReadonlyArray<WorldEntityRecord>;
1968
+ removedSeedEntityIds?: Iterable<string>;
1969
+ scheduler?: WorkstationScheduler;
1970
+ playerInventory?: InventoryContainer;
1971
+ }): WorldDeltaSnapshot;
1972
+ /** Replay a `WorldDeltaSnapshot` onto a freshly seeded `ChunkedTilemap` + `WorkstationScheduler` + `InventoryContainer`. */
1973
+ declare function applyWorldDelta(snapshot: WorldDeltaSnapshot, targets: {
1974
+ tilemap: ChunkedTilemap;
1975
+ scheduler?: WorkstationScheduler;
1976
+ playerInventory?: InventoryContainer;
1977
+ }): void;
1978
+ /** Compact UTF-8 binary framing (`HWLD` magic + version + JSON payload) for tiny file / IndexedDB / network storage. */
1979
+ declare function encodeWorldDeltaBytes(snapshot: WorldDeltaSnapshot): Uint8Array;
1980
+ declare function decodeWorldDeltaBytes(bytes: Uint8Array): WorldDeltaSnapshot;
1981
+ interface WorldCatalogSpec<TRules extends Record<string, unknown> = Record<string, unknown>> {
1982
+ readonly version?: number | string;
1983
+ readonly items?: ReadonlyArray<ItemDef>;
1984
+ readonly recipes?: ReadonlyArray<RecipeDef>;
1985
+ readonly rules?: Readonly<TRules>;
1986
+ }
1987
+ interface FrozenWorldCatalog<TRules extends Record<string, unknown> = Record<string, unknown>> {
1988
+ readonly version: number | string;
1989
+ readonly items: ReadonlyArray<Readonly<ItemDef>>;
1990
+ readonly recipes: ReadonlyArray<Readonly<RecipeDef>>;
1991
+ readonly rules: Readonly<TRules>;
1992
+ }
1993
+ interface CatalogReloadDiff {
1994
+ readonly reloadSeq: number;
1995
+ readonly addedItems: readonly string[];
1996
+ readonly updatedItems: readonly string[];
1997
+ readonly removedItems: readonly string[];
1998
+ readonly addedRecipes: readonly string[];
1999
+ readonly updatedRecipes: readonly string[];
2000
+ readonly removedRecipes: readonly string[];
2001
+ readonly changedRules: readonly string[];
2002
+ }
2003
+ interface WorldCatalogRuntime<TRules extends Record<string, unknown> = Record<string, unknown>> {
2004
+ readonly items: ItemRegistry;
2005
+ readonly recipes: RecipeRegistry;
2006
+ readonly catalog: FrozenWorldCatalog<TRules>;
2007
+ readonly rules: Readonly<TRules>;
2008
+ readonly reloadSeq: number;
2009
+ /** Hot-swap static item/recipe/balance rules in-place without resetting live inventories, workstations, or world tiles! */
2010
+ reload(next: WorldCatalogSpec<TRules> | FrozenWorldCatalog<TRules>): CatalogReloadDiff;
2011
+ /** Subscribe to hot-reload diffs (e.g. from Vite `import.meta.hot`, Bun `--hot`, or AI balance sweeps). */
2012
+ onReload(listener: (diff: CatalogReloadDiff, catalog: FrozenWorldCatalog<TRules>) => void): () => void;
2013
+ }
2014
+ /**
2015
+ * Validate, deep-clone, and deep-freeze a pure acyclic `WorldCatalogSpec` (rejecting functions,
2016
+ * class instances, and cycles so static rules stay 100% decoupled from mutable runtime state).
2017
+ */
2018
+ declare function defineWorldCatalog<const TRules extends Record<string, unknown> = Record<string, unknown>>(spec: WorldCatalogSpec<TRules>): FrozenWorldCatalog<TRules>;
2019
+ /**
2020
+ * Create a hot-reloadable catalog runtime backed by live `ItemRegistry` and `RecipeRegistry` instances.
2021
+ * Calling `runtime.reload(nextCatalog)` swaps item/recipe/balance definitions in-place while preserving
2022
+ * all active `InventoryContainer` stacks, `WorkstationInstance` progress, and `ChunkedTilemap` state!
2023
+ */
2024
+ declare function createWorldCatalogRuntime<TRules extends Record<string, unknown> = Record<string, unknown>>(initial: WorldCatalogSpec<TRules> | FrozenWorldCatalog<TRules>, opts?: {
2025
+ items?: ItemRegistry;
2026
+ recipes?: RecipeRegistry;
2027
+ }): WorldCatalogRuntime<TRules>;
1543
2028
  type StageInputEvent = {
1544
2029
  readonly kind: 'pointerdown' | 'pointermove' | 'pointerup';
1545
2030
  readonly x: number;
@@ -1611,10 +2096,15 @@ declare class StageKernel {
1611
2096
  private readonly providerOrder;
1612
2097
  private readonly inputListeners;
1613
2098
  private inputGuard;
2099
+ private boundCatalog;
1614
2100
  private disposed;
1615
2101
  constructor(game: Game);
1616
2102
  /** Optional input barrier predicate (e.g. `() => !surfaces.isWorldBlocked()`). */
1617
2103
  setInputGuard(guard: ((ev: StageInputEvent) => boolean) | null): this;
2104
+ /** Bind a `WorldCatalogRuntime` so Vite/Bun HMR or AI balance harnesses can hot-reload via `kernel.reloadCatalog()`. */
2105
+ bindCatalog<TRules extends Record<string, unknown>>(catalogRuntime: WorldCatalogRuntime<TRules> | null): this;
2106
+ /** Hot-reload the bound `WorldCatalogRuntime` in-place without resetting live scene/world state! */
2107
+ reloadCatalog<TRules extends Record<string, unknown> = Record<string, unknown>>(nextCatalog: WorldCatalogSpec<TRules>): CatalogReloadDiff;
1618
2108
  /** Subscribe to every normalized `StageInputEvent` flowing through the kernel (used by recorders/mods). */
1619
2109
  onInput(listener: (ev: StageInputEvent, frameSeq: number, simTimeMs: number) => void): () => void;
1620
2110
  /** Mount a `StagePlugin` (idempotent per `plugin.id`; LIFO-disposed on `remove` or `game.destroy()`). */
@@ -1829,6 +2319,8 @@ declare class GameObjectFactory {
1829
2319
  }): Graphics;
1830
2320
  blitter(x: number, y: number, key: string): BlitterObject;
1831
2321
  instancedBatch(key: string, maxCount?: number, frame?: string | number): InstancedBatchObject;
2322
+ /** Create an immediate-mode per-frame `DrawStreamObject` (`sprite()` / `writeBulk()`). */
2323
+ drawStream(key: string, options?: DrawStreamOptions): DrawStreamObject;
1832
2324
  /** Create a zero-texture GPU analytical SDF shape batch (`circles`, `rings`, `pills`, `rounded rects`). */
1833
2325
  shapeBatch(maxCount?: number, defaults?: ShapeBatchStyleDefaults): ShapeBatchObject;
1834
2326
  container(x?: number, y?: number, children?: DisplayObject[]): Container;
@@ -1876,6 +2368,9 @@ declare class Scene {
1876
2368
  readonly events: EventEmitter;
1877
2369
  /** Deterministic EngineClock-driven tween & spring manager (auto-stepped in `Game.step()`). */
1878
2370
  readonly tweens: TweenManager;
2371
+ /** Deterministic EngineClock-driven generator coroutine scheduler (`scene.script(function* (co) { ... })`). */
2372
+ readonly scripts: ScriptScheduler;
2373
+ private readonly _drawStreams;
1879
2374
  private readonly _animatedSprites;
1880
2375
  private readonly _equippedSprites;
1881
2376
  private _nodesCreated;
@@ -1932,6 +2427,15 @@ declare class Scene {
1932
2427
  lifecycleStats(): SceneLifecycleStats;
1933
2428
  /** Lightweight active/completed/cancelled tween & spring counters for `sceneDigest()` and `perf()`. */
1934
2429
  tweenStats(): TweenStats;
2430
+ /** Launch a deterministic EngineClock-driven generator coroutine (`function* (co) { yield* co.wait(0.35); ... }`). */
2431
+ script<R = unknown>(fn: (co: ScriptContext) => CoroutineGenerator<R>, options?: ScriptOptions): ScriptHandle;
2432
+ /** Lightweight active/completed/cancelled coroutine counters. */
2433
+ scriptStats(): ScriptStats;
2434
+ /**
2435
+ * Acquire (or lazily create) a memoized immediate-mode `DrawStreamObject` keyed by `(textureKey, opts?.streamId ?? 'default')`.
2436
+ * Safe to call directly inside `update()` or `preRender()` every frame with zero node allocation!
2437
+ */
2438
+ drawStream(key: string, options?: DrawStreamOptions): DrawStreamObject;
1935
2439
  _registerAnimatedSprite(sprite: SpriteObject): void;
1936
2440
  _unregisterAnimatedSprite(sprite: SpriteObject): void;
1937
2441
  _stepAnimations(deltaMs: number): void;
@@ -2003,4 +2507,4 @@ declare class Game {
2003
2507
  step(time: number, delta: number): void;
2004
2508
  destroy(removeCanvas?: boolean): void;
2005
2509
  }
2006
- export { WebGpuBootstrapResult as $, createInputRecorder as A, NineSliceObject as At, SceneDigestSurfaceEntry as B, SpriteAnimEventListener as Bt, RecordedInputEntry as C, EquipmentBinding as Ct, TimelineClickOptions as D, InstancedColumns as Dt, StagePlugin as E, InstancedBatchObject as Et, SceneDigestEngineSandbox as F, RectangleObject as Ft, InputConfig as G, TextStyleConfig as Gt, SceneDigestSurfaces as H, SpritePlayOptions as Ht, SceneDigestNode as I, SceneHostLike as It, Pointer as J, CameraFollowOptions as Jt, InputPlugin as K, TileSpriteObject as Kt, SceneDigestOptions as L, ShapeBatchColumns as Lt, createInputTimeline as M, PanelOpenSide as Mt, SceneDigest as N, PanelStyleConfig as Nt, TimelineDragOptions as O, MsdfIconConfig as Ot, SceneDigestActiveFocus as P, RectClipMask as Pt, RequestWebGpuOptions as Q, SceneDigestOverlayStats as R, ShapeBatchObject as Rt, InputTimelinePlugin as S, DisplaySemantics as St, StageKernel as T, ImageObject as Tt, buildSceneDigest as U, SyncAttachmentOptions as Ut, SceneDigestSurfaceSource as V, SpriteObject as Vt, sanitizeTrackToken as W, TextObject as Wt, RendererWebGpu as X, HiDpiScaleLike as Xt, PointerSample as Y, HiDpiConfigureOptions as Yt, RendererWebGpuOptions as Z, ActionMap as _, CustomPassOptions as _t, GameLoop as a, RendererGlOptions as at, InputTargetSpec as b, DisplayObject as bt, LoaderPlugin as c, StageRenderTarget as ct, SceneCtor as d, BlitterObject as dt, WebGpuCanvasContextLike as et, SceneInput as f, Bob as ft, ViewportFitResult as g, CustomPassObject as gt, StageRenderer as h, CustomPassCallback as ht, GameConfig as i, RendererGl as it, createInputReplay as j, PanelObject as jt, TimelineKeyOptions as k, MsdfIconObject as kt, ScaleManager as l, AnchorPose2D as lt, SceneManager as m, ContainerFiltersShim as mt, EngineClockSnapshot as n, requestWebGpuDevice as nt, GameObjectFactory as o, RendererStats as ot, SceneLifecycleStats as p, Container as pt, KeyboardPlugin as q, Camera as qt, Game as r, Renderer2D as rt, JsonCache as s, Stage2DCustomImageHandler as st, EngineClock as t, WebGpuDeviceLike as tt, Scene as u, BindEquipmentOptions as ut, InputProvider as v, DirectionalPlayOptions as vt, StageInputEvent as w, Graphics as wt, InputTimelineOptions as x, DisplayObjectType as xt, InputRecorderPlugin as y, DisplayList as yt, SceneDigestSandbox as z, ShapeBatchStyleDefaults as zt };
2510
+ export { decodeWorldDeltaBytes as $, Stage2DCustomImageHandler as $t, createInputRecorder as A, RectClipMask as An, SceneDigestOverlayStats as At, RecipeRegistry as B, TextObject as Bn, Pointer as Bt, RecordedInputEntry as C, InstancedColumns as Cn, unpackChunkY as Ct, TimelineClickOptions as D, PanelObject as Dn, SceneDigestEngineSandbox as Dt, StagePlugin as E, NineSliceObject as En, SceneDigestActiveFocus as Et, InventoryContainer as F, ShapeBatchStyleDefaults as Fn, buildSceneDigest as Ft, WorkstationSnapshot as G, HiDpiConfigureOptions as Gn, WebGpuBootstrapResult as Gt, WorkstationInstance as H, TileSpriteObject as Hn, RendererWebGpu as Ht, ItemDef as I, SpriteAnimEventListener as In, sanitizeTrackToken as It, WorldDeltaSnapshot as J, requestWebGpuDevice as Jt, WorldCatalogRuntime as K, HiDpiScaleLike as Kn, WebGpuCanvasContextLike as Kt, ItemRegistry as L, SpriteObject as Ln, InputConfig as Lt, createInputTimeline as M, SceneHostLike as Mn, SceneDigestSurfaceEntry as Mt, CatalogReloadDiff as N, ShapeBatchColumns as Nn, SceneDigestSurfaceSource as Nt, TimelineDragOptions as O, PanelOpenSide as On, SceneDigestNode as Ot, FrozenWorldCatalog as P, ShapeBatchObject as Pn, SceneDigestSurfaces as Pt, createWorldCatalogRuntime as Q, RendererStats as Qt, ItemStack as R, SpritePlayOptions as Rn, InputPlugin as Rt, InputTimelinePlugin as S, InstancedBatchObject as Sn, unpackChunkX as St, StageKernel as T, MsdfIconObject as Tn, SceneDigest as Tt, WorkstationJob as U, Camera as Un, RendererWebGpuOptions as Ut, TileCellDelta as V, TextStyleConfig as Vn, PointerSample as Vt, WorkstationScheduler as W, CameraFollowOptions as Wn, RequestWebGpuOptions as Wt, applyWorldDelta as X, RendererGl as Xt, WorldEntityRecord as Y, Renderer2D as Yt, captureWorldDelta as Z, RendererGlOptions as Zt, ActionMap as _, DrawStreamOptions as _n, floorDiv as _t, GameLoop as a, Container as an, ChunkedTilemapOptions as at, InputTargetSpec as b, Graphics as bn, packChunkKey as bt, LoaderPlugin as c, CustomPassObject as cn, MountedChunkedTilemap as ct, SceneCtor as d, DisplayList as dn, TileChunk as dt, StageRenderTarget as en, defineWorldCatalog as et, SceneInput as f, DisplayObject as fn, bakeDualGridTileset as ft, ViewportFitResult as g, DrawStreamObject as gn, fbm2D as gt, StageRenderer as h, DrawStreamBulkView as hn, createIslandBiomeGenerator as ht, GameConfig as i, Bob as in, ChunkedTilemap as it, createInputReplay as j, RectangleObject as jn, SceneDigestSandbox as jt, TimelineKeyOptions as k, PanelStyleConfig as kn, SceneDigestOptions as kt, ScaleManager as l, CustomPassOptions as ln, SurvivalBiomes as lt, SceneManager as m, DisplaySemantics as mn, computeDualGridMask as mt, EngineClockSnapshot as n, BindEquipmentOptions as nn, BakedDualGridAtlas as nt, GameObjectFactory as o, ContainerFiltersShim as on, DualGridLayerSpec as ot, SceneLifecycleStats as p, DisplayObjectType as pn, computeBlob47Index as pt, WorldCatalogSpec as q, WebGpuDeviceLike as qt, Game as r, BlitterObject as rn, ChunkGeneratorFn as rt, JsonCache as s, CustomPassCallback as sn, IslandBiomeConfig as st, EngineClock as t, AnchorPose2D as tn, encodeWorldDeltaBytes as tt, Scene as u, DirectionalPlayOptions as un, TileCellFlags as ut, InputProvider as v, DrawStreamSpriteOptions as vn, hash2D as vt, StageInputEvent as w, MsdfIconConfig as wn, valueNoise2D as wt, InputTimelineOptions as x, ImageObject as xn, positiveMod as xt, InputRecorderPlugin as y, EquipmentBinding as yn, mountChunkedTilemap as yt, RecipeDef as z, SyncAttachmentOptions as zn, KeyboardPlugin as zt };