@holtjs/stage 0.0.1 → 0.3.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.
package/CHANGELOG.md ADDED
@@ -0,0 +1,62 @@
1
+ # Changelog
2
+
3
+ All notable changes to `@holtjs/stage` (formerly `@holtjs/stage2d`) are documented in this file.
4
+
5
+ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
6
+
7
+ ## [Unreleased]
8
+
9
+ ## [0.3.0] - 2026-12-03
10
+
11
+ ### Changed
12
+ - **Package & Repository Rename**: renamed `@holtjs/stage2d` (`botiverse-play/stage2d`) to **`@holtjs/stage`** (`botiverse-play/stage`), aligning with `@holtjs/live` while preserving `Stage2D` as a non-breaking named export alias alongside default/named `Stage`. Renamed bundled skill directory to `skills/stage/`.
13
+
14
+ ### Added
15
+ - **Headless 60 FPS Image, Storyboard & Programmable Video Subpath (`@holtjs/stage/headless`)**:
16
+ - `createHeadlessStage({ createCanvas, width, height, fps, scene })`: boots `Game` (`autoStart: false`) synchronously in pure Node/Bun/Deno without `window` or `document`, supporting deterministic `.step()`, `.stepToMs()`, `.stepToFrame()`, synthetic `.pointerDown/.pointerMove/.pointerUp()`, `.toRgba()`, `.toPng()`, `.digest()`, and backpressure-aware `.recordFrames()` streaming for `ffmpeg`.
17
+ - `renderStoryboard(stage, { frames, columns, tileScale, createCanvas })`: steps across keyframes and composites a labeled multi-panel PNG contact sheet + paired `SceneDigest[]` array for single-image AI agent visual inspection.
18
+ - `createAudioTimeline({ sampleRate })`: frame-accurate stereo timeline mixer (`addAtMs`, `addAtFrame`) with constant-power stereo panning and `.toWav()` 16-bit stereo PCM RIFF export.
19
+ - **Runnable Programmable Video Example**: added CI-verified `examples/headless-video.mjs` (`pnpm run example:video`) capable of rendering 1280x720 60 FPS H.264 MP4 + stereo audio in ~1s via `@napi-rs/canvas` + `ffmpeg`.
20
+
21
+ ## [0.2.2] - 2026-12-03
22
+
23
+ ### Added
24
+ - **AI Agent Kit**: added `AGENTS.md`, `CLAUDE.md`, `llms.txt`, installable Agent Skills (`skills/stage2d/SKILL.md` + `references/subpaths.md` and `skills/stage2d-contributor/SKILL.md`) (#8).
25
+ - **Open-Source Governance**: added `CONTRIBUTING.md`, `CODE_OF_CONDUCT.md`, `SECURITY.md`, `CHANGELOG.md`, Dependabot config, structured GitHub Issue templates (with zero-PII `buildSceneDigest()` field), PR template, and refreshed `README.md` with badges and subpath/example guides (#8, #10).
26
+ - **Runnable Examples**: added `examples/minimal-game.html`, `examples/minimal-ui.html`, and CI-verified zero-DOM `examples/headless-sim.mjs` (`pnpm run example:headless`), emitted into `dist-pages/examples/` alongside `llms.txt` and `SKILL.md` (#9).
27
+ - **npm Tarball Ergonomics**: bundled `skills/stage2d/`, `llms.txt`, and `CHANGELOG.md` directly inside `@holtjs/stage2d` so downstream users and AI agents get zero-config skill & API discovery in `node_modules/@holtjs/stage2d/` (#8).
28
+
29
+ ## [0.2.1] - 2026-12-03
30
+
31
+ ### Fixed
32
+ - **ECS (`@holtjs/stage2d/ecs`)**: tightened `partitionDepthBands()` open-edge band depths (`prevBlocker === -Infinity`, `nextBlocker === Infinity`, and zero-blocker cases) to actual entity depths so un-blocked 2.5D sprites preserve exact painter's order relative to instanced bands (#7).
33
+
34
+ ### Added
35
+ - **ECS (`@holtjs/stage2d/ecs`)**: optional zero-GC `tieCol?: ArrayLike<number>` secondary sort key and `<= 48` insertion-sort fast path in `sortSlotsByDepth()` and `cullAndSortSlots()` for texture/material batch tie-breaking on equal-depth rows (#7).
36
+ - **Interactive Showcase**: upgraded `examples/showcase.html` into a 2-tab live WebGL2 demo (`2D Game Engine Lab` + `UI & SurfaceTree`) showcasing `SoaWorld`, `SpatialHashGrid`, `FlowFieldGrid`, `hit` knockback, `ParticlePool`/`AmbientEmitterPool`/`JuiceController`, procedural WebAudio foley, and `buildSceneDigest()` (#6).
37
+ - **AWS Amplify hosting**: added `amplify.yml` and `customHttp.yml` for static Showcase deployment (#5).
38
+
39
+ ## [0.2.0] - 2026-12-03
40
+
41
+ ### Added
42
+ - Six zero-dependency, tree-shakeable (`sideEffects: false`), zero-DOM first-party 2D game engine subpaths (#4):
43
+ - `@holtjs/stage2d/spatial` — zero-GC CSR uniform `SpatialHashGrid` for broadphase queries and crowd separation.
44
+ - `@holtjs/stage2d/hit` — deterministic swept-circle, melee arc, segment, capsule, AABB hit tests, obstacle push-out, and knockback decay.
45
+ - `@holtjs/stage2d/nav` — multi-target `FlowFieldGrid`, bounded 8-neighbor A* with greedy LOS string-pulling (`findGridPath`), and local steering.
46
+ - `@holtjs/stage2d/particles` — zero-GC `ParticlePool`, continuous `AmbientEmitterPool`, and `JuiceController` (hitstop + squared-trauma shake).
47
+ - `@holtjs/stage2d/audio` — procedural foley DSP (`renderFoley`), stereo panning (`spatialMix`), sfxr voice synthesis, and PCM16 WAV encoding.
48
+ - `@holtjs/stage2d/ecs` — dense-packed `TypedArray` `SoaWorld` ECS with generational entity handles, bitmask queries, spatial sync, frustum culling, Ciura-gap Shell depth sort, and 2.5D `DepthBand` partitioning.
49
+ - Expanded `scripts/pack.mjs` strict external consumer `.d.ts` gate and `scripts/size.mjs` reporting across all 12 subpaths.
50
+
51
+ ## [0.1.1] - 2026-12-03
52
+
53
+ ### Fixed
54
+ - Eliminated `tsdown` circular self-referencing `.d.ts` aliases inside `export namespace Stage2D` (`type Scene = Scene`) using non-shadowing top-level type aliases; added permanent circular-alias scan and strict external consumer `tsc --noEmit` gate to `scripts/pack.mjs` (#3).
55
+
56
+ ## [0.1.0] - 2026-12-03
57
+
58
+ ### Added
59
+ - Initial standalone release of `@holtjs/stage2d` extracted from production use (#1, #2):
60
+ - WebGL2 (`RendererGl`) and Canvas2D (`Renderer2D`) renderers with GPU SDF panels, Sharp-Bilinear Pixel-AA, and MTSDF vector icon batchers.
61
+ - Retained scene graph with LIFO cascading `onDispose`, `EngineClock`, `TweenManager` (tweens + damped springs), `computeFlexLayout` / `computeWrapLayout`, `InputPlugin`, multi-touch `VirtualJoystick`, Godot-inspired `SurfaceTree`, and zero-PII `buildSceneDigest()`.
62
+ - Interactive Showcase (`examples/showcase.html`) and OIDC Trusted Publishing workflow.
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "{}"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright {yyyy} {name of copyright owner}
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/NOTICE ADDED
@@ -0,0 +1,13 @@
1
+ Stage2D (@holtjs/stage)
2
+ Copyright 2026 Botiverse, Inc.
3
+
4
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
5
+
6
+ Design & algorithmic acknowledgments:
7
+ - Signed-distance-field rounded rectangle formulation in `src/sdf-panel.ts` builds on
8
+ Inigo Quilez's 2D signed distance functions (https://iquilezles.org/articles/distfunctions2d/).
9
+ - Multi-channel + true signed distance field (MTSDF) rendering in `src/msdf-batch.ts` implements
10
+ the median-of-three + true-SDF stroke shader model popularized by Viktor Chlumský's msdfgen
11
+ (https://github.com/Chlumsky/msdfgen).
12
+ - Sharp-bilinear anti-aliased pixel-art sampling in `src/pixel-aa-batch.ts` follows standard
13
+ GPU screen-space derivative texel-edge clamping for crisp non-integer pixel scaling.
package/README.md ADDED
@@ -0,0 +1,173 @@
1
+ # Stage2D (`@holtjs/stage`)
2
+
3
+ [![npm version](https://img.shields.io/npm/v/@holtjs/stage.svg)](https://www.npmjs.com/package/@holtjs/stage)
4
+ [![License: Apache-2.0](https://img.shields.io/badge/License-Apache--2.0-blue.svg)](LICENSE)
5
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0-brightgreen.svg)](package.json)
6
+ [![Core Gzip](https://img.shields.io/badge/core%20gzip-~45%20kB-informational.svg)](scripts/size.mjs)
7
+
8
+ A zero-dependency, tracing-first WebGL2 / Canvas2D 2D game & UI engine written in strict TypeScript — covering rendering, layout, animation, input, surface barriers, spatial hashing, hit detection, navigation, particles, procedural foley audio, and zero-GC SoA ECS.
9
+
10
+ - **npm**: https://www.npmjs.com/package/@holtjs/stage
11
+ - **Repository**: https://github.com/botiverse-play/stage
12
+ - **Architecture Docs**: [docs/architecture.md](docs/architecture.md)
13
+ - **AI Agent Kit**: [AGENTS.md](AGENTS.md) · [skills/stage/SKILL.md](skills/stage/SKILL.md) · [llms.txt](llms.txt)
14
+ - **Changelog & Community**: [CHANGELOG.md](CHANGELOG.md) · [CONTRIBUTING.md](CONTRIBUTING.md) · [SECURITY.md](SECURITY.md)
15
+
16
+ Extracted from production use inside interactive 2D multiplayer worlds and canvas-native UI suites where bundle size, deterministic timing, crisp HiDPI rendering, and production observability matter.
17
+
18
+ ## Highlights
19
+
20
+ - **Zero runtime dependencies**: Pure ESM TypeScript (~165 kB minified / ~45 kB gzipped for the entire engine; individual subpaths like `@holtjs/stage/flex` or `@holtjs/stage/surfaces` are 2–5 kB gzipped).
21
+ - **WebGL2-first with isomorphic Canvas2D fallback**:
22
+ - Single-texture zero-branch shader + 8-unit multi-texture uber-batcher (`RendererGl`) with static Quad IBO and exact-size `STREAM_DRAW` VBO orphaning (zero pipeline stalls).
23
+ - **GPU SDF Panel Batcher** (`PanelObject` / `SdfPanelBatcher`): analytic anti-aliased rounded rectangles with per-corner radii, inner borders, and optional pixel-stepped corners (`pixelStep`) — zero texture baking.
24
+ - **GPU Sharp-Bilinear Pixel-AA Batcher** (`PixelAaBatcher`): crisp pixel-art scaling at non-integer sizes (1×/2×/3× DPR) without blur or atlas bleeding.
25
+ - **GPU MTSDF Vector Icon Batcher** (`MsdfIconObject` / `MsdfIconBatcher`): sharp corners + true-SDF stroke outlines at any scale.
26
+ - Full `Renderer2D` Canvas2D fallback supporting the same display list, `PanelObject`, and `zIndex` ordering.
27
+ - **Retained Scene Graph & LIFO Cascading Disposal**:
28
+ - `DisplayObject`, `Container` (native `zIndex` + scissor clip), `Image`, `NineSlice`, `TileSprite`, `Rectangle`, `Panel`, `MsdfIcon`, `Text`, `Graphics` (cached triangulated mesh), `Blitter`, and `CustomPass` (for custom instanced WebGL2 passes).
29
+ - Every node exposes `onDispose(fn)`: destroying a subtree unwinds children and registered disposers in strict LIFO order with per-disposer error isolation.
30
+ - **Deterministic Clock, Tweens & Damped Springs**:
31
+ - `EngineClock` tracks monotonic `frameSeq` (advances only on stepped frames) and clamped `simTimeMs` (<= 100 ms/step).
32
+ - `TweenManager` drives easing curves and sub-stepped damped springs (`setTarget()` mid-flight) off `EngineClock.lastDeltaMs`, auto-canceling via `owner.onDispose()`.
33
+ - **Pure Math Layout, Input & SurfaceTree**:
34
+ - `computeFlexLayout()` and `computeWrapLayout()` — zero-DOM Flexbox + wrapping layout solvers with `grow`/`shrink`, `min`/`max` clamping, and integer pixel snapping.
35
+ - `InputPlugin` — native `PointerEvent` mouse/pen/multi-touch/wheel/keyboard layer with cached `getBoundingClientRect()` and zero-allocation `getCoalescedEvents()` sub-sample pooling for 120–240 Hz drawing.
36
+ - `VirtualJoystick` — multi-touch finger-isolated (`pointer.id`) virtual joystick (`fixed` / `floating` with optional `follow`) + pure vector/deadzone/8-way D-pad math.
37
+ - `createSurfaceTree()` — Godot-inspired unified visual stacking = input barrier tree (`SURFACE_BAND`, `modal`/`fullscreen` barriers, scoped occlusion, `ui.cancel` / `onKey` / `Tab` focus dispatch, and monotonic DOM `z-index` solver).
38
+ - **First-Party Tree-Shakeable 2D Game Engine Primitives** (`sideEffects: false`, zero extra bytes if unused):
39
+ - **Spatial Hash Grid** (`@holtjs/stage/spatial`): zero-GC CSR uniform spatial hash for O(N) broadphase queries and crowd separation.
40
+ - **Deterministic 2D Hit & Push-Out** (`@holtjs/stage/hit`): IEEE-754 swept circles, melee arc sweeps, segments/capsules, AABB/circle obstacle resolution, and frame-rate-independent knockback.
41
+ - **Navigation** (`@holtjs/stage/nav`): multi-target `FlowFieldGrid`, bounded 8-neighbor A* with greedy LOS string-pulling (`findGridPath`), and local steering.
42
+ - **Particles & Hit-Feel Juice** (`@holtjs/stage/particles`): zero-GC `ParticlePool`, continuous `AmbientEmitterPool`, and hitstop + squared-trauma screen shake (`JuiceController`).
43
+ - **Procedural Audio & Foley** (`@holtjs/stage/audio`): pure-TS organic foley synthesis (`renderFoley`), spatial stereo panning (`spatialMix`), sfxr voice synth, and PCM16 WAV export.
44
+ - **Zero-GC SoA ECS** (`@holtjs/stage/ecs`): dense-packed `TypedArray` `SoaWorld` with generational entity handles, bitmask queries, `SpatialHashGrid` sync, frustum culling, Ciura-gap Shell depth sort, and 2.5D `DepthBand` partitioning.
45
+ - **Tracing-First Observability (`buildSceneDigest`)**:
46
+ - Privacy-safe structural scene snapshot (`clock`, `viewport`, `renderer`, `lifecycle`, `tweens`, `overlays`, `surfaces`, `sandbox`, and sanitized `trackId`/`role`/`alt`/`surface` nodes). Never scrapes arbitrary `TextObject.text` or user input.
47
+
48
+ ## Install
49
+
50
+ ```bash
51
+ pnpm add @holtjs/stage
52
+ ```
53
+
54
+ ## Subpath Exports
55
+
56
+ | Import Path | Description | DOM Required? |
57
+ |---|---|---|
58
+ | `@holtjs/stage` | Full engine barrel (`Stage2D`, `Game`, `Scene`, renderers, display objects, layout, tweens, joystick, tracing, surfaces) | Browser (for `Game`/renderers) |
59
+ | `@holtjs/stage/flex` | Pure 1D Flex & Wrap layout solvers (`computeFlexLayout`, `computeWrapLayout`, `resolvePadding`) | No |
60
+ | `@holtjs/stage/tween` | Deterministic `TweenManager`, `Easings`, and damped springs | No |
61
+ | `@holtjs/stage/joystick` | `VirtualJoystick` + pure vector/origin/D-pad math helpers | Pure helpers: No |
62
+ | `@holtjs/stage/surfaces` | Godot-inspired `SurfaceTree` input barrier & DOM `z-index` router | No |
63
+ | `@holtjs/stage/trace` | `buildSceneDigest()` and `sanitizeTrackToken()` | No |
64
+ | `@holtjs/stage/spatial` | Zero-GC CSR `SpatialHashGrid` for broadphase queries & separation | No |
65
+ | `@holtjs/stage/hit` | Deterministic swept-circle, arc, segment, capsule, AABB hit & knockback math | No |
66
+ | `@holtjs/stage/nav` | Multi-target `FlowFieldGrid`, A* + LOS string-pulling (`findGridPath`), steering | No |
67
+ | `@holtjs/stage/particles` | Zero-GC `ParticlePool`, `AmbientEmitterPool`, and `JuiceController` (hitstop/shake) | No |
68
+ | `@holtjs/stage/audio` | Procedural foley DSP (`renderFoley`), `spatialMix`, sfxr voices, PCM16 WAV export | No |
69
+ | `@holtjs/stage/ecs` | Dense-packed zero-GC `SoaWorld` ECS, spatial sync, depth sort & `DepthBand`s | No |
70
+ | `@holtjs/stage/headless` | Zero-browser 60 FPS `createHeadlessStage`, `renderStoryboard`, and `createAudioTimeline` stereo WAV mixer | No (`@napi-rs/canvas` in Node) |
71
+
72
+ ## Quick Start
73
+
74
+ ```ts
75
+ import {
76
+ AUTO,
77
+ Game,
78
+ Scene,
79
+ Scale,
80
+ buildSceneDigest,
81
+ computeFlexLayout,
82
+ } from '@holtjs/stage';
83
+
84
+ class DemoScene extends Scene {
85
+ create() {
86
+ const layout = computeFlexLayout(
87
+ { dir: 'row', w: 480, h: 120, gap: 12, padding: 16, align: 'center' },
88
+ [
89
+ { w: 140, h: 80 },
90
+ { w: 0, h: 80, grow: 1 },
91
+ ],
92
+ );
93
+
94
+ const card = this.add.panel(layout.rects[0].x, layout.rects[0].y, layout.rects[0].w, layout.rects[0].h, {
95
+ fillColor: 0xfff8e7,
96
+ borderColor: 0x2c241d,
97
+ borderWidth: 2,
98
+ radius: 14,
99
+ });
100
+ card.trackId = 'demo.card';
101
+ card.role = 'panel';
102
+
103
+ // Deterministic spring animation bound to the node's lifetime
104
+ this.tweens.spring({
105
+ from: card.y + 12,
106
+ to: card.y,
107
+ stiffness: 240,
108
+ damping: 20,
109
+ owner: card,
110
+ onUpdate: (y) => { card.y = y; },
111
+ });
112
+
113
+ // Privacy-safe structural trace snapshot
114
+ console.log(buildSceneDigest(this, { traceId: 'demo-trace-01' }));
115
+ }
116
+ }
117
+
118
+ new Game({
119
+ type: AUTO,
120
+ parent: document.getElementById('app')!,
121
+ width: 640,
122
+ height: 360,
123
+ backgroundColor: '#3d9bd1',
124
+ scale: { mode: Scale.NONE },
125
+ scene: [DemoScene],
126
+ });
127
+ ```
128
+
129
+ ## AI Agent Support (`AGENTS.md`, Skills & `llms.txt`)
130
+
131
+ Stage2D is built to be first-class for AI coding agents as well as humans:
132
+
133
+ - **Agent Skill for app & game builders**: [skills/stage/SKILL.md](skills/stage/SKILL.md) + [references/subpaths.md](skills/stage/references/subpaths.md) — covers DPR HiDPI camera setup, zero-GC `SoaWorld` + `SpatialHashGrid` + `FlowFieldGrid` + `hit` + `particles` loops, GPU SDF UI + `SurfaceTree` barriers, procedural WebAudio foley, `buildSceneDigest()` debugging, and common gotchas. Shipped directly inside `node_modules/@holtjs/stage/skills/stage/` and installable via:
134
+ ```bash
135
+ npx skills add botiverse-play/stage
136
+ ```
137
+ - **Repository Agent Guide**: [AGENTS.md](AGENTS.md) (with [CLAUDE.md](CLAUDE.md) pointer) and [skills/stage-contributor/SKILL.md](skills/stage-contributor/SKILL.md) for agents contributing directly to the engine.
138
+ - **Machine-Readable Index**: [llms.txt](llms.txt) (also emitted to `dist-pages/llms.txt` alongside `dist-pages/SKILL.md` for static Showcase hosting).
139
+
140
+ ## Runnable Examples
141
+
142
+ | Example | What it demonstrates | How to run |
143
+ |---|---|---|
144
+ | [examples/showcase.html](examples/showcase.html) | Full 2-tab interactive Showcase (`2D Game Engine Lab` + `UI & SurfaceTree`) | `pnpm run build:pages && npx serve dist-pages` |
145
+ | [examples/minimal-game.html](examples/minimal-game.html) | ~120-line 2D arena (`SoaWorld` + `FlowFieldGrid` + `SpatialHashGrid` + `hit` + `ParticlePool` + `JuiceController`) | Open `/examples/minimal-game.html` from `dist-pages` |
146
+ | [examples/minimal-ui.html](examples/minimal-ui.html) | ~120-line GPU SDF UI (`computeFlexLayout` + `pixelStep` + damped springs + `SurfaceTree` Escape modal + `buildSceneDigest`) | Open `/examples/minimal-ui.html` from `dist-pages` |
147
+ | [examples/headless-sim.mjs](examples/headless-sim.mjs) | Zero-DOM Node 24 authoritative tick (`SoaWorld` + `FlowFieldGrid` + `sweptCircleHit` + `partitionDepthBands`) | `pnpm run pack && pnpm run example:headless` |
148
+ | [examples/headless-video.mjs](examples/headless-video.mjs) | Zero-browser 1280x720 60 FPS storyboard PNG + stereo WAV + H.264 MP4 video pipeline | `pnpm run pack && pnpm run example:video` |
149
+
150
+ ## Development & Showcase
151
+
152
+ ```bash
153
+ pnpm install
154
+ pnpm run typecheck
155
+ pnpm run test
156
+ pnpm run pack
157
+ pnpm run build:pages
158
+ pnpm run size
159
+ ```
160
+
161
+ Preview the 2-tab interactive Showcase (`2D Game Engine Lab` + `UI & SurfaceTree`) locally with `pnpm run build:pages && npx serve dist-pages`. Static hosting is pre-configured for **AWS Amplify** (`amplify.yml` + `customHttp.yml`) and **GitHub Pages** (`.github/workflows/pages.yml`).
162
+
163
+ See [docs/architecture.md](docs/architecture.md) for deep technical details on GPU batching invariants, coordinate/DPR contracts, cascading disposal, `SurfaceTree`, and tracing-first observability, and [CONTRIBUTING.md](CONTRIBUTING.md) before opening a pull request.
164
+
165
+ ## Community & Security
166
+
167
+ - Contributions welcome — see [CONTRIBUTING.md](CONTRIBUTING.md) and [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md).
168
+ - Release history — see [CHANGELOG.md](CHANGELOG.md).
169
+ - Security reports — see [SECURITY.md](SECURITY.md) (please do not open public issues for vulnerabilities).
170
+
171
+ ## License
172
+
173
+ Apache License 2.0 — see [LICENSE](LICENSE) and [NOTICE](NOTICE).
@@ -0,0 +1,159 @@
1
+ export type NoiseColor = 'white' | 'pink' | 'brown';
2
+ export type EnvelopeCurve = 'exp' | 'cosine';
3
+ /** Filtered organic noise layer (water swish, splashes, footsteps on grass/sand/wood/carpet). */
4
+ export interface FoleyNoiseLayer {
5
+ readonly kind: 'noise';
6
+ readonly color?: NoiseColor;
7
+ /** Start offset in seconds (default 0). */
8
+ readonly t?: number;
9
+ /** Attack duration in seconds (default 0.006). */
10
+ readonly a?: number;
11
+ /** Hold duration in seconds (default 0.01). */
12
+ readonly h?: number;
13
+ /** Decay duration in seconds (default 0.08). */
14
+ readonly d?: number;
15
+ /** Envelope shape: `'cosine'` gives velvety hydrodynamic swells; `'exp'` gives natural transients. */
16
+ readonly curve?: EnvelopeCurve;
17
+ /** Layer amplitude (default 0.5). */
18
+ readonly vol?: number;
19
+ /** Deterministic PRNG seed. */
20
+ readonly seed?: number;
21
+ /** Chamberlin SVF bandpass start / end cutoff Hz (optional; sweeps smoothly over the layer). */
22
+ readonly bp?: number;
23
+ readonly bp1?: number;
24
+ /** SVF resonance Q for bandpass (default 0.85; higher = narrower/more resonant). */
25
+ readonly q?: number;
26
+ /** One-pole low-pass start / end cutoff Hz (optional ceiling to remove harsh digital hiss). */
27
+ readonly lp?: number;
28
+ readonly lp1?: number;
29
+ /** One-pole high-pass cutoff Hz (optional floor to remove mud/DC rumble). */
30
+ readonly hp?: number;
31
+ }
32
+ /** Damped modal sine resonance (hollow wood plank, stone tap, plunge cavity, micro water droplet). */
33
+ export interface FoleyModalLayer {
34
+ readonly kind: 'modal';
35
+ /** Start offset in seconds (default 0). */
36
+ readonly t?: number;
37
+ /** Start frequency Hz. */
38
+ readonly f: number;
39
+ /** End frequency Hz (exponential glide over `slide` or full layer duration). */
40
+ readonly f1?: number;
41
+ /** Pitch glide duration in seconds. */
42
+ readonly slide?: number;
43
+ /** Attack duration in seconds (default 0.002). */
44
+ readonly a?: number;
45
+ /** Decay duration in seconds (default 0.05). */
46
+ readonly d?: number;
47
+ /** Layer amplitude (default 0.4). */
48
+ readonly vol?: number;
49
+ /** Optional mild harmonic warmth (2nd harmonic ratio 0..0.5, default 0). */
50
+ readonly harm2?: number;
51
+ }
52
+ /** Natural liquid micro-bubble cluster (Minnaert cavity resonance) for authentic water splashes & swimming strokes. */
53
+ export interface FoleyBubbleLayer {
54
+ readonly kind: 'bubbles';
55
+ /** Start offset in seconds (default 0). */
56
+ readonly t?: number;
57
+ /** Time window over which droplets scatter, in seconds. */
58
+ readonly span: number;
59
+ /** Number of tiny randomized liquid droplets. */
60
+ readonly count: number;
61
+ /** Frequency range [minHz, maxHz] of cavity bubbles. */
62
+ readonly fMin: number;
63
+ readonly fMax: number;
64
+ /** Natural subtle Minnaert upward pitch ratio per bubble (e.g. 1.15..1.35; keep modest so it sounds wet, never laser-like). */
65
+ readonly rise?: number;
66
+ /** Individual bubble decay range [minSec, maxSec] (default [0.008, 0.022]). */
67
+ readonly durMin?: number;
68
+ readonly durMax?: number;
69
+ /** Overall layer amplitude (default 0.22). */
70
+ readonly vol?: number;
71
+ /** Deterministic PRNG seed. */
72
+ readonly seed?: number;
73
+ }
74
+ export type FoleyLayer = FoleyNoiseLayer | FoleyModalLayer | FoleyBubbleLayer;
75
+ export interface RenderFoleyOptions {
76
+ /** Target peak ceiling before soft-clipping (default 0.82; set 0 to skip normalization). */
77
+ readonly peak?: number;
78
+ /** Soft-clip knee threshold (default 0.85). */
79
+ readonly clip?: number;
80
+ }
81
+ export interface SpatialMixResult {
82
+ readonly vol: number;
83
+ readonly pan: number;
84
+ }
85
+ export interface VariantPicker {
86
+ readonly count: number;
87
+ /** Pick next variant index without repeating the immediately preceding index (when count > 1). */
88
+ next(): number;
89
+ reset(): void;
90
+ }
91
+ /** Parameter spec for one sfxr-style chiptune/chime synth voice. */
92
+ export interface VoiceSpec {
93
+ t?: number;
94
+ w?: string;
95
+ f: number;
96
+ f1?: number;
97
+ slide?: number;
98
+ duty?: number;
99
+ duty1?: number;
100
+ a?: number;
101
+ h?: number;
102
+ d?: number;
103
+ punch?: number;
104
+ vol?: number;
105
+ vib?: number[];
106
+ arp?: ReadonlyArray<readonly [number, number]>;
107
+ lp?: number;
108
+ lp1?: number;
109
+ hp?: number;
110
+ bits?: number;
111
+ seed?: number;
112
+ }
113
+ /** Fast deterministic PRNG (mulberry32), returning floats in [0, 1). */
114
+ export declare function mulberry32(seed: number): () => number;
115
+ /** One-pole filter alpha coefficient for cutoff `hz` at sample rate `sr`. */
116
+ export declare function onePoleAlpha(hz: number, sr: number): number;
117
+ /** Smooth soft-saturation limiter preventing harsh digital clipping while preserving warmth. */
118
+ export declare function softClipSample(x: number, knee?: number): number;
119
+ /**
120
+ * Render a layered procedural foley sound into a mono Float32Array at `sr` Hz.
121
+ * Pure & deterministic: runs identically in browsers and Node.
122
+ */
123
+ export declare function renderFoley(layers: readonly FoleyLayer[], sr?: number, opts?: RenderFoleyOptions): Float32Array;
124
+ /** Deterministically pre-render `count` acoustic variations of a foley builder (eliminates robotic repetition). */
125
+ export declare function renderFoleyVariants(builder: (variantIndex: number) => readonly FoleyLayer[], count: number, sr?: number, opts?: RenderFoleyOptions): Float32Array[];
126
+ /** Non-repeating deterministic variant selector so consecutive steps/strokes always sound organic. */
127
+ export declare function createVariantPicker(count: number, seed?: number): VariantPicker;
128
+ /** Compute distance attenuation & stereo pan from listener delta `(dx, dy)` in world tiles, or `null` if out of earshot. */
129
+ export declare function spatialMix(dx: number, dy: number, near?: number, far?: number, farVol?: number, panSpan?: number): SpatialMixResult | null;
130
+ /** Encode mono Float32 samples (-1..1) as a standard 16-bit PCM WAV byte array (for Node preview / asset export). */
131
+ export declare function encodeWavPcm16(samples: Float32Array, sr?: number): Uint8Array;
132
+ /** Gentle hydrodynamic water paddle stroke: soft water wash + delicate Minnaert micro-bubbles (never wind-like or laser-like). */
133
+ export declare function buildSwimStrokeFoley(variant?: number): FoleyLayer[];
134
+ /** Soft character plunge into water: cozy liquid "plop" + frothy splash + shimmering water droplets. */
135
+ export declare function buildDiveInFoley(variant?: number): FoleyLayer[];
136
+ /** Climbing out of water onto a wooden dock/deck: light wet wooden step + brief trickling droplets. */
137
+ export declare function buildClimbOutFoley(variant?: number): FoleyLayer[];
138
+ /** Warm wooden plank footstep (light wooden knock + soft step — never booming). */
139
+ export declare function buildStepWoodFoley(variant?: number): FoleyLayer[];
140
+ /** Soft grass / cherry meadow footstep (plush leafy brush + faint muted step). */
141
+ export declare function buildStepGrassFoley(variant?: number): FoleyLayer[];
142
+ /** Warm beach sand footstep (two overlapping soft fine-grain puffs). */
143
+ export declare function buildStepSandFoley(variant?: number): FoleyLayer[];
144
+ /** Clean flagstone / cobble footstep (warm rounded pebble tap). */
145
+ export declare function buildStepStoneFoley(variant?: number): FoleyLayer[];
146
+ /** Muffled carpet / rug / tatami footstep (soft cloth pad). */
147
+ export declare function buildStepSoftFoley(variant?: number): FoleyLayer[];
148
+ /** MIDI note number -> frequency in Hz. */
149
+ export declare const midi: (n: number) => number;
150
+ /** Parse note name ('c5', 'g#4', 'bb3') -> MIDI number. */
151
+ export declare function noteNum(s: string): number;
152
+ /** Parse note name -> frequency in Hz. */
153
+ export declare const hz: (s: string) => number;
154
+ /** Render one chiptune/chime voice additively into `out` (Float32Array at `sr`). */
155
+ export declare function synthVoice(out: Float32Array, sr: number, v: VoiceSpec): void;
156
+ /** Sequence of notes (`[[note, beats], ...]`) at `step` seconds per beat, using `base` voice settings. */
157
+ export declare const tune: (notes: ReadonlyArray<readonly [string | null | undefined, number]>, step: number, base: Omit<VoiceSpec, 'f'>, t0?: number) => VoiceSpec[];
158
+ /** Render a list of synth voices to a soft-clipped mono Float32Array at `sr`. Pure. */
159
+ export declare function renderVoices(vs: readonly VoiceSpec[], sr?: number): Float32Array<ArrayBuffer>;