@netforge/template-dungeon 0.0.0-stage → 0.2.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/AGENTS.md ADDED
@@ -0,0 +1,74 @@
1
+ # Extending CRYPTWICK
2
+
3
+ CRYPTWICK is the co-op dungeon crawl template of the Net Forge game engine. The template already has the crypt's walls and floors, enemies that path through doors, weapons, XP shards, level-ups, bosses, co-op revive, netcode, rendering, touch controls, earn and the store. You change the game by changing declarations and the crawl system. Read `llms.txt` for every field, `llms-full.txt` for the complete worked example, and `GAME-DESIGN.md` in `@netforge/engine` for the design rules the playtest gate scores.
4
+
5
+ ## The one file to edit
6
+
7
+ - `src/game.ts` is the whole game, including the `crawl` system (room wakes, `ENCOUNTERS` by depth, `STIR_AFTER`, reliquaries). Change it in place.
8
+ - `src/names.json`, next to it, holds the title and every label players read (weapons, upgrades, earn rules, store items). Add a label there for every new id.
9
+ - Everything else (`src/manifest.ts`, `src/store.ts`, `client/`, `test/`, `scripts/`) is template machinery. Do not edit it.
10
+
11
+ ## Imports
12
+
13
+ `src/game.ts` imports only from `@netforge/engine`. The shipped game uses:
14
+
15
+ ```ts
16
+ import { achievement, dungeon, earn, game, keeper, mission, prefab, store, system, title, upgrade, weapon } from "@netforge/engine";
17
+ ```
18
+
19
+ Also available: `economy` and `metaUpgrade` (opt-in, only when the creator asks for permanent upgrades; the engine caps them at +15% a stat and +30% in all).
20
+
21
+ ## Declarations
22
+
23
+ - `dungeon({ seed, rooms, cell, size, corridor, loops })` grows the floor plan. Pass its `field` to `game({ field })`. `CRYPT.rooms`, `CRYPT.boss` and `CRYPT.roomAt(x, z)` feed the crawl.
24
+ - `game({ template: "dungeon", style, places, field, look?, players: { prefab, max, weapon, xp, magnet, hitIframes, downed, ... } })`.
25
+ - `prefab(id, { model, health, speed, radius, damage, ai, drops?, attack?, split?, mass? })` for the dead, bosses and pickups. `ai` is one of the engine's behaviours (`chase`, `runner`, `tank`, `ranged`, `bomber`, `healer`, `summoner`, `charger` and others).
26
+ - `weapon(id, { kind, damage, cooldown, range, levels?, evolve? })`, at most 15 including evolutions.
27
+ - `upgrade(id, ...)`, at most 8.
28
+ - `system(id, (ctx) => { ... })` with `every`, `after`, `onTick`, `spawn`, `spawnPickup`, `spawnEdge`, `spawnRing`, `announce`, `upcoming`, `alive`, `players`, `emit`, `on`, `respawnDead`, `end`, `onScreen`, `random`, `tick`, `time` and more (see llms.txt, Systems API).
29
+ - `keeper(id, { name, text, weapon, passive, model?, tint?, unlock? })`, `achievement(...)`, `mission(...)`, `title(...)`.
30
+ - `earn.rule(id, { when, n, pay, oncePer: "run" })`. Events: `room.cleared`, `enemy.killed`, `boss.killed`, `player.downed`, `player.revived`, `player.levelup`, `run.won`, `run.lost`, and anything a system emits.
31
+ - `earn.stake({ min, max, multiple })`, exactly one, on one top-level line.
32
+ - `store.sku(id, { coins, grants? })`.
33
+
34
+ ## Rules the build enforces
35
+
36
+ - Ids are lower_snake_case.
37
+ - Every game declares at least one `earn.rule` and exactly one `earn.stake`. `"stake"` is reserved.
38
+ - A dungeon game needs one enemy prefab, one weapon and `players.weapon` (or keepers).
39
+ - Drops must be pickup prefabs.
40
+ - A keeper is earned (an achievement unlock) or bought (a SKU), never both. The first keeper is free.
41
+ - Asset ids are library ids such as `"style.lowpoly.skeleton"`, never URLs or paths, and must exist in the asset library. Keep `game({ style })` as the creator picked it.
42
+ - Keep the SKUs the client is wired to exactly: `revive`, `skin_ossuary` and the `wick_charm` gear.
43
+
44
+ ## Validate
45
+
46
+ - With the MCP server (`npx -y @netforge/mcp`), call `netforge_validate_game` on `src/game.ts`. It returns one actionable line per problem.
47
+ - In this package, run the tests with vitest: `test/harness.test.ts`, `test/host.test.ts` and `test/store.test.ts`.
48
+
49
+ ## Playtest
50
+
51
+ - With the MCP server, call `netforge_run_playtest`.
52
+ - In code, import the game module and run the headless harness:
53
+
54
+ ```ts
55
+ import { engine } from "@netforge/engine";
56
+ import "./src/game.js";
57
+
58
+ const report = await engine.test.run({ ticks: 30 * 180, bots: 4, seed: 1, bot: "human" });
59
+ console.log(report.kills, report.wave, report.maxLevel, report.earned, report.fun);
60
+ ```
61
+
62
+ The report has kills, wave (1 + rooms cleared), maxLevel, earn by rule, deaths, runs won and lost, softlock and ms per tick. With `bot: "human"`, `report.fun` has the fun metrics the gate scores.
63
+
64
+ ## Play locally
65
+
66
+ In a folder with `netnet.json` (`{"template":"dungeon"}`) and `src/game.ts`, with `@netforge/kit-play` and `@netforge/engine` installed, run `npx kit-play`. It opens http://127.0.0.1:4663 with play money. The MCP tool `netforge_play_locally` gives the same steps.
67
+
68
+ ## Do not
69
+
70
+ - Do not write renderers, netcode, physics or pathing. The template has them.
71
+ - Do not reference assets by URL or file path.
72
+ - Do not import anything other than `@netforge/engine` in `src/game.ts`.
73
+ - Do not edit `client/`, `src/manifest.ts` or `src/store.ts`.
74
+ - Do not rename or reprice the SKUs the client is wired to.
package/CLAUDE.md ADDED
@@ -0,0 +1,11 @@
1
+ # CLAUDE.md
2
+
3
+ This package is CRYPTWICK, a Net Forge game template. Read AGENTS.md before changing this game. It lists the declarations this genre has, the rules the build enforces, and how to validate, playtest and play the game locally.
4
+
5
+ The five hard rules:
6
+
7
+ 1. Edit only src/game.ts (and src/names.json for the labels players read).
8
+ 2. Import only from @netforge/engine.
9
+ 3. Ids are lower_snake_case.
10
+ 4. Declare at least one earn.rule and exactly one earn.stake.
11
+ 5. Never write renderers, netcode, physics or bot AI, and never reference assets by URL or file path (use library ids such as "style.lowpoly.frog").
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 NetNet Capital Management
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/NOTICE ADDED
@@ -0,0 +1,35 @@
1
+ @netforge/template-dungeon (CRYPTWICK)
2
+ Copyright (c) 2026 NetNet Capital Management
3
+
4
+ An original game. No names, characters, sprites, models, sounds or code
5
+ from any other game or franchise. Nothing from PokéSurvivor (its code and
6
+ sprites are non-commercial) or SpriteCollab was used or consulted for code.
7
+
8
+ Art and sound
9
+ - Models come from the per-style asset library
10
+ (@netforge/asset-library): CC0 1.0 models by Quaternius (wickbearers,
11
+ the dead) and Kenney (columns, crates and rocks), each pack listed
12
+ with its source URL and licence verification in that package's NOTICE and
13
+ manifest/packs.json. The files are fetched and built, never committed
14
+ here; the build copies only the models this game uses.
15
+ - Fallback shapes (client/library.ts) are generated from three.js
16
+ primitives; textures are drawn on a canvas at load.
17
+
18
+ Dependencies (unmodified, via npm)
19
+ - three.js 0.186.1 (https://github.com/mrdoob/three.js), MIT.
20
+ - nipplejs 1.0.4 (https://github.com/yoannmoinet/nipplejs), MIT.
21
+ - @netforge/engine and @netforge/engine-sim (this repository);
22
+ see their NOTICE files (bitECS MPL-2.0, Rapier Apache-2.0, Colyseus MIT,
23
+ zod MIT).
24
+
25
+ Patterns (ideas only)
26
+ - The dungeon-crawl and survivor-like genres' general mechanics (rooms
27
+ joined by corridors, rooms that wake as you near them, loot in cleared
28
+ rooms, permadeath runs, auto-firing weapons, pick-one-of-three
29
+ level-ups, a boss in the deepest room). Mechanics, not expression; no
30
+ level, item, enemy or text was copied from any game. The floor plan is
31
+ generated by our own code (engine dungeon.ts) from a seed.
32
+ - Flow-field pathing (a breadth-first distance field steered down its
33
+ gradient), a textbook technique, implemented in engine-sim walls.ts.
34
+ - Hit-stop, screen shake and damage numbers as described in common
35
+ game-feel talks and articles (e.g. "Juice it or lose it", GDC 2012).
package/README.md CHANGED
@@ -1,3 +1,85 @@
1
- # Temporary Holding Version
1
+ # @netforge/template-dungeon
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A co-op dungeon crawler game template for Net Forge: up to 4 players descend a procedural crypt, room by room, in permadeath runs (CRYPTWICK).
4
+
5
+ Four wickbearers go down into a candle-lit crypt. The crypt is grown from a seed with `dungeon(...)`: ten rooms joined by corridors, the start room at the top and the Wax Abbot in the deepest one. Rooms wake as the party nears them and their dead come through the doors. A cleared room leaves a reliquary (pick an upgrade) and brings back anyone who fell. If the whole party is down at once, the descent is over.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @netforge/template-dungeon
11
+ ```
12
+
13
+ You rarely import this package directly. kit play (`@netforge/kit-play`) and the Net Forge MCP server use it to build and run a game whose `src/game.ts` you write.
14
+
15
+ ## Play it locally
16
+
17
+ ```sh
18
+ mkdir -p my-game/src && cd my-game
19
+ npm init -y && npm install @netforge/kit-play @netforge/engine @netforge/template-dungeon
20
+ cp node_modules/@netforge/template-dungeon/src/game.ts src/
21
+ echo '{"template":"dungeon"}' > netnet.json
22
+ npx kit-play # opens http://127.0.0.1:4663
23
+ ```
24
+
25
+ Open the Invite link (`?room=<id>`) in another tab to play together, or start with `--host 0.0.0.0` and open it on a phone on the same network. Coins are play money. Real-token earning, stakes and claims run only on the hosted Net Forge server.
26
+
27
+ ## Change the game
28
+
29
+ Edit `src/game.ts` and run `npx kit-play` again. For example, grow a different and larger crypt by changing the seed and the room count:
30
+
31
+ ```ts
32
+ const CRYPT = dungeon({ seed: 7, rooms: 14, cell: 24, size: [12, 18], corridor: 6, loops: 3 });
33
+ ```
34
+
35
+ Or make the candle burst, the starting weapon, hit harder:
36
+
37
+ ```ts
38
+ weapon("candle_burst", {
39
+ kind: "nova", damage: 16, cooldown: 1.1, range: 3.8, knockback: 2.5,
40
+ // levels and evolve as shipped
41
+ });
42
+ ```
43
+
44
+ ## How it plays on the server
45
+
46
+ - Server-authoritative at 30 Hz on the survivor machinery: auto-firing weapons, shards and level-up cards, co-op downs and revives, keepers, and bosses with telegraphed attacks. Your own wickbearer is predicted.
47
+ - The crypt's walls are boxes in the sim (`field.walls`) and its floors (`field.floors`) are the only ground. Enemies behind a wall walk round through the doors on a flow field, with a wider grid for big bodies.
48
+ - The crawl is a system in `src/game.ts` that you can read and change: room wakes, encounters by depth, off-screen spawns inside the woken room, the quiet timer that wakes the nearest room when the party waits, reliquaries and the respawn on clear.
49
+ - Earn: rooms cleared (2 and 7), the Abbot, and 60 kills by one wickbearer, once per run each. The room server is the referee.
50
+
51
+ ## Files
52
+
53
+ | Path | What |
54
+ |---|---|
55
+ | `src/game.ts` | The game, as declarations only: the crypt's spec, the dead, weapons, the crawl system, earn and the store. This is the file you edit. |
56
+ | `src/manifest.ts` | Loads and compiles the game; `dungeonAdapter()` for the room host and the client. |
57
+ | `src/store.ts` | Store hooks on the Kit's API names (`kit.coins.*`, `kit.store.*`): a revive, a cosmetic and the wick charm (losable gear). |
58
+ | `client/` | The browser client: three.js scene, the crypt's floors and walls with an x-ray cut and fog of war, HUD, input (keys, gamepad, touch), game feel. |
59
+ | `test/` | Playtest bots through `engine.test.run`, the host test and the store test. |
60
+ | `llms.txt`, `llms-full.txt` | How to change the game, for agents. |
61
+
62
+ ## Controls
63
+
64
+ WASD or arrows to move, Space to dash, 1 2 3 to pick a card. On touch, drag on the left half, use the DASH button and tap a card. The backtick key shows stats.
65
+
66
+ ## For AI agents
67
+
68
+ Read `AGENTS.md` and `llms.txt` before editing. The Net Forge MCP server gives a coding agent the templates, the API and a playtest loop:
69
+
70
+ ```sh
71
+ npx -y @netforge/mcp
72
+ ```
73
+
74
+ The package is `@netforge/mcp` and its bin is `netforge-mcp`. Its tools are `netforge_list_templates`, `netforge_create_game`, `netforge_explain_api`, `netforge_search_docs`, `netforge_validate_game`, `netforge_run_playtest` and `netforge_play_locally`. The engine's `GAME-DESIGN.md` (in `@netforge/engine`) has the design rules the playtest gate scores.
75
+
76
+ To set up a coding agent in a game project, run `npx netforge setup agent`. It writes AGENTS.md, CLAUDE.md, Cursor rules and `.mcp.json` into the project. In Claude Code you can also add the server directly with `claude mcp add netforge -- npx -y @netforge/mcp`.
77
+
78
+ ## Docs
79
+
80
+ - https://forge.netnet.capital/docs/templates/dungeon
81
+ - `llms.txt` and `llms-full.txt` in this package. The full file includes the complete `src/game.ts` and the validate and playtest steps.
82
+
83
+ ## License
84
+
85
+ MIT. See LICENSE and NOTICE.
@@ -0,0 +1,274 @@
1
+ /**
2
+ * The crypt as drawn: dark rock under everything, a flagstone floor on
3
+ * every room and corridor (game.ts field.floors), stone walls on every
4
+ * wall box (field.walls), and candles in sconces at the room corners. One merged mesh for all the walls and one for all
5
+ * the floors, so the whole level is a handful of draws.
6
+ *
7
+ * Rooms nobody has walked into yet stay dim (a soft fog of war that lifts
8
+ * as a wickbearer enters); the walls stay readable so the plan is always
9
+ * there to see.
10
+ *
11
+ * An art style that paints surfaces (ps1's textures) paints these too
12
+ * (surface roles "floor", "wall", "stone"); the toon, pixel, voxel and
13
+ * hand-drawn styles reshade them in post like everything else.
14
+ */
15
+ import { BufferAttribute, BufferGeometry, CanvasTexture, Color, CylinderGeometry, Group, Mesh, MeshBasicMaterial, MeshStandardMaterial, MeshStandardNodeMaterial, PlaneGeometry, RepeatWrapping, SphereGeometry, SRGBColorSpace, Vector3 } from "three/webgpu";
16
+ import { clamp, dot, float, length, positionWorld, select, uniform } from "three/tsl";
17
+ import type { Texture } from "three/webgpu";
18
+ import type { WallBox } from "@netforge/engine-sim";
19
+
20
+ /** Walls are drawn this tall (the sim's are 3 m): low enough that a wall south of you hides less of the room. */
21
+ export const WALL_DRAW_HEIGHT = 2.2;
22
+ /** Candles burn in sconces this high in the room corners, under the wall tops. */
23
+ const SCONCE_HEIGHT = 1.75;
24
+ /** Brightness of a floor nobody has walked into yet, and of one a wickbearer has. */
25
+ const UNSEEN = 0.2;
26
+ const LIT = 0.8;
27
+
28
+ function hash01(n: number): number {
29
+ let t = (n + 0x6d2b79f5) >>> 0;
30
+ t = Math.imul(t ^ (t >>> 15), t | 1);
31
+ t ^= t + Math.imul(t ^ (t >>> 7), t | 61);
32
+ return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
33
+ }
34
+
35
+ /** Worn flagstones, drawn on a canvas (one repeat covers 4 m). */
36
+ function flagstones(): CanvasTexture {
37
+ const c = document.createElement("canvas");
38
+ c.width = c.height = 256;
39
+ const g = c.getContext("2d");
40
+ if (g) {
41
+ g.fillStyle = "#3b342d";
42
+ g.fillRect(0, 0, 256, 256);
43
+ for (let j = 0; j < 4; j++) {
44
+ for (let i = 0; i < 4; i++) {
45
+ const k = j * 4 + i;
46
+ const off = j % 2 === 0 ? 0 : 32;
47
+ const v = 70 + Math.floor(hash01(k) * 26);
48
+ g.fillStyle = `rgb(${v + 8}, ${v}, ${v - 10})`;
49
+ g.fillRect(((i * 64 + off) % 256) + 2, j * 64 + 2, 60, 60);
50
+ // Cracks and wear.
51
+ g.strokeStyle = "rgba(20, 16, 12, 0.35)";
52
+ g.beginPath();
53
+ g.moveTo(((i * 64 + off) % 256) + 8 + hash01(k + 50) * 40, j * 64 + 6);
54
+ g.lineTo(((i * 64 + off) % 256) + 10 + hash01(k + 90) * 44, j * 64 + 58);
55
+ g.stroke();
56
+ }
57
+ }
58
+ g.fillStyle = "rgba(255, 220, 160, 0.04)";
59
+ for (let n = 0; n < 300; n++) g.fillRect(hash01(n * 3) * 256, hash01(n * 3 + 1) * 256, 2, 2);
60
+ }
61
+ const t = new CanvasTexture(c);
62
+ t.wrapS = t.wrapT = RepeatWrapping;
63
+ t.colorSpace = SRGBColorSpace;
64
+ t.userData = { tile: 4 };
65
+ return t;
66
+ }
67
+
68
+ /** Coursed stone blocks for the walls (one repeat covers 2 m). */
69
+ function masonry(): CanvasTexture {
70
+ const c = document.createElement("canvas");
71
+ c.width = c.height = 128;
72
+ const g = c.getContext("2d");
73
+ if (g) {
74
+ g.fillStyle = "#1d1a18";
75
+ g.fillRect(0, 0, 128, 128);
76
+ for (let j = 0; j < 4; j++) {
77
+ for (let i = -1; i < 3; i++) {
78
+ const v = 52 + Math.floor(hash01(j * 7 + i + 20) * 22);
79
+ g.fillStyle = `rgb(${v}, ${v - 4}, ${v - 9})`;
80
+ g.fillRect(i * 64 + (j % 2) * 32 + 2, j * 32 + 2, 60, 28);
81
+ }
82
+ }
83
+ }
84
+ const t = new CanvasTexture(c);
85
+ t.wrapS = t.wrapT = RepeatWrapping;
86
+ t.colorSpace = SRGBColorSpace;
87
+ t.userData = { tile: 2 };
88
+ return t;
89
+ }
90
+
91
+ /**
92
+ * Boxes as one geometry with world-space UVs (so a texture tiles at the
93
+ * same scale on a 1 m stub and a 40 m run). `h` is the height; the floor
94
+ * is y = 0.
95
+ */
96
+ function boxesGeometry(boxes: readonly WallBox[], h: number, tile: number): BufferGeometry {
97
+ const pos: number[] = [];
98
+ const nor: number[] = [];
99
+ const uv: number[] = [];
100
+ const idx: number[] = [];
101
+ const quad = (a: number[], b: number[], c: number[], d: number[], n: number[], uvOf: (p: number[]) => [number, number]) => {
102
+ const base = pos.length / 3;
103
+ for (const p of [a, b, c, d]) {
104
+ pos.push(p[0] ?? 0, p[1] ?? 0, p[2] ?? 0);
105
+ nor.push(n[0] ?? 0, n[1] ?? 0, n[2] ?? 0);
106
+ const [u, v] = uvOf(p);
107
+ uv.push(u / tile, v / tile);
108
+ }
109
+ idx.push(base, base + 1, base + 2, base, base + 2, base + 3);
110
+ };
111
+ for (const b of boxes) {
112
+ const x0 = b.x - b.hx;
113
+ const x1 = b.x + b.hx;
114
+ const z0 = b.z - b.hz;
115
+ const z1 = b.z + b.hz;
116
+ const xz = (p: number[]): [number, number] => [p[0] ?? 0, p[2] ?? 0];
117
+ const xy = (p: number[]): [number, number] => [p[0] ?? 0, p[1] ?? 0];
118
+ const zy = (p: number[]): [number, number] => [p[2] ?? 0, p[1] ?? 0];
119
+ quad([x0, h, z1], [x1, h, z1], [x1, h, z0], [x0, h, z0], [0, 1, 0], xz);
120
+ quad([x0, 0, z1], [x1, 0, z1], [x1, h, z1], [x0, h, z1], [0, 0, 1], xy);
121
+ quad([x1, 0, z0], [x0, 0, z0], [x0, h, z0], [x1, h, z0], [0, 0, -1], xy);
122
+ quad([x1, 0, z1], [x1, 0, z0], [x1, h, z0], [x1, h, z1], [1, 0, 0], zy);
123
+ quad([x0, 0, z0], [x0, 0, z1], [x0, h, z1], [x0, h, z0], [-1, 0, 0], zy);
124
+ }
125
+ const g = new BufferGeometry();
126
+ g.setAttribute("position", new BufferAttribute(new Float32Array(pos), 3));
127
+ g.setAttribute("normal", new BufferAttribute(new Float32Array(nor), 3));
128
+ g.setAttribute("uv", new BufferAttribute(new Float32Array(uv), 2));
129
+ g.setIndex(idx);
130
+ g.computeBoundingSphere();
131
+ return g;
132
+ }
133
+
134
+ /**
135
+ * The x-ray cut: wall fragments near the line from the camera to your
136
+ * wickbearer (and in front of them) are not drawn, so a wall south of you
137
+ * never hides you. Works on the node material every backend draws, and the
138
+ * art styles carry it over (they copy opacity nodes and the alpha test).
139
+ */
140
+ export class WallCut {
141
+ readonly camera = uniform(new Vector3(0, 20, 20));
142
+ readonly hero = uniform(new Vector3(0, 1, 0));
143
+ /** Radius of the cut, m. */
144
+ readonly radius = uniform(1.6);
145
+
146
+ /** A wall material with the cut in it. */
147
+ material(color: number, map: Texture | null, roughness: number): MeshStandardNodeMaterial {
148
+ const m = new MeshStandardNodeMaterial({ color, roughness, flatShading: true });
149
+ if (map) m.map = map;
150
+ const c = this.camera;
151
+ const seg = this.hero.sub(c);
152
+ const p = positionWorld;
153
+ const t = clamp(dot(p.sub(c), seg).div(dot(seg, seg)), 0, 1);
154
+ const d = length(p.sub(c.add(seg.mul(t))));
155
+ // Cut: close to the sight line, before the hero, and above the wall's foot (the base still outlines the room).
156
+ const cut = d.lessThan(this.radius).and(t.lessThan(0.97)).and(p.y.greaterThan(0.12));
157
+ m.opacityNode = select(cut, float(0), float(1));
158
+ m.alphaTest = 0.5;
159
+ return m;
160
+ }
161
+
162
+ update(camera: Vector3, hero: Vector3): void {
163
+ this.camera.value.copy(camera);
164
+ this.hero.value.set(hero.x, hero.y + 0.9, hero.z);
165
+ }
166
+ }
167
+
168
+ interface FloorPiece {
169
+ readonly box: WallBox;
170
+ readonly material: MeshStandardMaterial;
171
+ lit: number;
172
+ seen: boolean;
173
+ }
174
+
175
+ export class CryptLevel {
176
+ readonly group = new Group();
177
+ /** Where candles burn ([x, y, z]): the scene drifts embers off the near ones. */
178
+ readonly flames: [number, number, number][] = [];
179
+ private readonly floors: FloorPiece[] = [];
180
+ readonly cut = new WallCut();
181
+
182
+ constructor(
183
+ walls: readonly WallBox[],
184
+ floors: readonly WallBox[],
185
+ half: number,
186
+ surface: ((kind: "floor" | "wall" | "stone" | "ground") => Texture | null) | null,
187
+ ) {
188
+ // Rock under everything: what the camera sees past the walls.
189
+ const rock = new Mesh(new PlaneGeometry(half * 2 + 60, half * 2 + 60), new MeshStandardMaterial({ color: 0x0b0a0c, roughness: 1 }));
190
+ rock.rotation.x = -Math.PI / 2;
191
+ rock.position.y = -0.02;
192
+ rock.userData.surface = "rock";
193
+ this.group.add(rock);
194
+
195
+ // Floors: one mesh per room or corridor, so each can lift out of the dark on its own.
196
+ const floorMap = surface?.("floor") ?? flagstones();
197
+ const ftile = (floorMap.userData as { tile?: number }).tile ?? 4;
198
+ for (const f of floors) {
199
+ const map = floorMap.clone();
200
+ map.needsUpdate = true;
201
+ map.repeat.set((f.hx * 2) / ftile, (f.hz * 2) / ftile);
202
+ map.offset.set(((f.x - f.hx) / ftile) % 1, ((f.z - f.hz) / ftile) % 1);
203
+ const material = new MeshStandardMaterial({ map, roughness: 0.95, color: new Color(UNSEEN, UNSEEN, UNSEEN) });
204
+ const m = new Mesh(new PlaneGeometry(f.hx * 2, f.hz * 2), material);
205
+ m.rotation.x = -Math.PI / 2;
206
+ m.position.set(f.x, 0.005, f.z);
207
+ m.receiveShadow = true;
208
+ m.userData.surface = "floor";
209
+ this.group.add(m);
210
+ this.floors.push({ box: f, material, lit: UNSEEN, seen: false });
211
+ }
212
+
213
+ // Walls: one merged mesh with a darker cap, so the plan reads from above.
214
+ const wallMap = surface?.("wall") ?? masonry();
215
+ wallMap.wrapS = wallMap.wrapT = RepeatWrapping;
216
+ const wtile = (wallMap.userData as { tile?: number }).tile ?? 2;
217
+ const wall = new Mesh(boxesGeometry(walls, WALL_DRAW_HEIGHT, wtile), this.cut.material(0x9a8f84, wallMap, 0.92));
218
+ wall.castShadow = true;
219
+ wall.receiveShadow = true;
220
+ wall.userData.surface = "wall";
221
+ this.group.add(wall);
222
+ const capMat = this.cut.material(0x2b2420, null, 1);
223
+ const cap = new Mesh(boxesGeometry(walls.map((b) => ({ x: b.x, z: b.z, hx: b.hx + 0.04, hz: b.hz + 0.04 })), 0.08, 1), capMat);
224
+ cap.position.y = WALL_DRAW_HEIGHT;
225
+ this.group.add(cap);
226
+
227
+ // Candles: a sconce flame at each room's inner corners (rooms are the floors big enough to be rooms).
228
+ const flameMat = new MeshBasicMaterial({ color: new Color(0xffb04a).multiplyScalar(5) });
229
+ const flameGeo = new SphereGeometry(0.16, 8, 6);
230
+ const sconceGeo = new CylinderGeometry(0.22, 0.12, 0.24, 6);
231
+ const sconceMat = new MeshStandardMaterial({ color: 0x2a2420, roughness: 0.6, metalness: 0.4 });
232
+ for (const f of floors) {
233
+ if (f.hx < 4 || f.hz < 4) continue;
234
+ for (const [sx, sz] of [
235
+ [-1, -1],
236
+ [1, -1],
237
+ [-1, 1],
238
+ [1, 1],
239
+ ] as const) {
240
+ // A candle in an iron sconce, set into the corner.
241
+ const x = f.x + sx * (f.hx - 0.3);
242
+ const z = f.z + sz * (f.hz - 0.3);
243
+ const sconce = new Mesh(sconceGeo, sconceMat);
244
+ sconce.position.set(x, SCONCE_HEIGHT - 0.12, z);
245
+ this.group.add(sconce);
246
+ const flame = new Mesh(flameGeo, flameMat);
247
+ flame.position.set(x, SCONCE_HEIGHT + 0.1, z);
248
+ this.group.add(flame);
249
+ this.flames.push([x, SCONCE_HEIGHT + 0.15, z]);
250
+ }
251
+ }
252
+ }
253
+
254
+ /** Lift the dark off every floor a wickbearer stands on (or within 2 m of). */
255
+ update(dt: number, players: readonly (readonly [number, number])[]): void {
256
+ for (const f of this.floors) {
257
+ if (!f.seen) {
258
+ for (const [x, z] of players) {
259
+ if (Math.abs(x - f.box.x) <= f.box.hx + 2 && Math.abs(z - f.box.z) <= f.box.hz + 2) f.seen = true;
260
+ }
261
+ }
262
+ const goal = f.seen ? LIT : UNSEEN;
263
+ if (Math.abs(goal - f.lit) < 0.002) continue;
264
+ f.lit += (goal - f.lit) * Math.min(1, dt * 2.5);
265
+ // Candle-warm: a touch less blue than red.
266
+ f.material.color.setRGB(f.lit, f.lit * 0.93, f.lit * 0.84);
267
+ }
268
+ }
269
+
270
+ /** A fresh descent: every room goes back into the dark. */
271
+ reset(): void {
272
+ for (const f of this.floors) f.seen = false;
273
+ }
274
+ }