BlueGit

timfa questward

Sprite and worldeditor tweaks, including a bloom layer for torches and other lights.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
4874d49c9cd209baa1785b5d604cf4c8b92a35c3
Parent
34d858d6
71 files changed +5722 −419
.cursor/rules/framework-readonly.mdc added +33 −0
@@ -0,0 +1,33 @@
1 ---
2 description: Treat FrameworkV3 as read-only unless explicitly asked to change the engine; then edit generically, build, and open a GitLab MR.
3 alwaysApply: true
4 ---
5
6 # FrameworkV3 is read-only by default
7
8 `client/frameworkv3/` is the **generic client-side engine** (FrameworkV3), not game-specific code. Treat all Framework source and its built bundle as **read-only**.
9
10 ## Do not edit Framework unless asked
11
12 - Do **not** modify files under `client/frameworkv3/` to fix or feature this game.
13 - Prefer solving game needs in `client/src/`, `shared/`, or `server/` by using Framework APIs as they exist.
14 - Reading Framework source for understanding APIs is fine; writing is not.
15
16 ## When the user explicitly asks to change Framework
17
18 Only then edit Framework, and keep changes **engine-generic** (reusable for any project that uses FrameworkV3 — no MMO/tile-game specifics, no repo-local hacks).
19
20 1. Edit source under `client/frameworkv3/framework/` (not hand-edit the concatenated bundle as the source of truth).
21 2. Build locally from `client/frameworkv3/`: `./glbuild.sh` (or `framework/build.sh`).
22 3. In the Framework repo (`client/frameworkv3`, remote `gitlab.com/Timfa/frameworkv3`), create a branch, commit, push, and open a **GitLab merge request** that states:
23 - **what** changed
24 - **why** (engine capability / bugfix — not “so the MMO can …” as the primary rationale)
25 4. Do not push to `master` directly; use an MR.
26
27 ```text
28 # ❌ BAD — game workaround inside the engine
29 client/frameworkv3/framework/... // hardcode tile size / night shade for this MMO
30
31 # ✅ GOOD — game uses the engine; engine stays generic
32 client/src/render/worldView.js // call existing Scene / Shader / RenderLayer APIs
33 ```
@@ -0,0 +1,33 @@
1---
2description: Treat FrameworkV3 as read-only unless explicitly asked to change the engine; then edit generically, build, and open a GitLab MR.
3alwaysApply: true
4---
5
6# FrameworkV3 is read-only by default
7
8`client/frameworkv3/` is the **generic client-side engine** (FrameworkV3), not game-specific code. Treat all Framework source and its built bundle as **read-only**.
9
10## Do not edit Framework unless asked
11
12- Do **not** modify files under `client/frameworkv3/` to fix or feature this game.
13- Prefer solving game needs in `client/src/`, `shared/`, or `server/` by using Framework APIs as they exist.
14- Reading Framework source for understanding APIs is fine; writing is not.
15
16## When the user explicitly asks to change Framework
17
18Only then edit Framework, and keep changes **engine-generic** (reusable for any project that uses FrameworkV3 — no MMO/tile-game specifics, no repo-local hacks).
19
201. Edit source under `client/frameworkv3/framework/` (not hand-edit the concatenated bundle as the source of truth).
212. Build locally from `client/frameworkv3/`: `./glbuild.sh` (or `framework/build.sh`).
223. In the Framework repo (`client/frameworkv3`, remote `gitlab.com/Timfa/frameworkv3`), create a branch, commit, push, and open a **GitLab merge request** that states:
23 - **what** changed
24 - **why** (engine capability / bugfix — not “so the MMO can …” as the primary rationale)
254. Do not push to `master` directly; use an MR.
26
27```text
28# ❌ BAD — game workaround inside the engine
29client/frameworkv3/framework/... // hardcode tile size / night shade for this MMO
30
31# ✅ GOOD — game uses the engine; engine stays generic
32client/src/render/worldView.js // call existing Scene / Shader / RenderLayer APIs
33```
README.md +1 −1
@@ -24,4 +24,4 @@ Open [http://localhost:8080](http://localhost:8080) to play and [http://localhos
24 24
25 25 Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
26 26
27 The player-driven marketplace is not in this slice. It will be placed in the world editor after those assets exist.
27 The player-driven marketplace is not in this slice. Bank and spawner blocks can be placed in the editor (placeholder sprites until real art exists). Open **Bag** in play to drop, pick up, and equip starter items.
@@ -24,4 +24,4 @@ Open [http://localhost:8080](http://localhost:8080) to play and [http://localhos
24
24
25Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
25Until auth.timfalken.com exists, each browser connection is a stub admin (`admin-1`, `admin-2`, …). A fresh world is infinite closed grass: open chunk `0,0` in the editor, save, then **Apply now** before a character can walk.
26
26
27The player-driven marketplace is not in this slice. It will be placed in the world editor after those assets exist.
27The player-driven marketplace is not in this slice. Bank and spawner blocks can be placed in the editor (placeholder sprites until real art exists). Open **Bag** in play to drop, pick up, and equip starter items.
client/assets/blocks/bank/bank.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/spawner/spawner.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/torch/torch-bloom.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/characters/player-body-female.png client/assets/characters/player-body-female/player-body-female.png renamed +0 −0
client/assets/characters/player-body-male.png client/assets/characters/player-body-male/player-body-male.png renamed +0 −0
client/assets/doves/dove/dove-flying.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/apple/apple.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/blank-cheque/blank-cheque.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/cloth-shirt/cloth-shirt-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/cloth-shirt/cloth-shirt.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/paper/paper.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/stick/stick-equip.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/items/stick/stick.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/mobs/deer/deer.png added Binary file +0 −0

The contents of this binary file are not shown.

client/editor.html +9 −1
@@ -30,13 +30,21 @@
30 30 <button type="button" data-tool='{"kind":"ground","typeId":2}'>Wood</button>
31 31 <button type="button" data-tool='{"kind":"block","typeId":1}'>Stone wall</button>
32 32 <button type="button" data-tool='{"kind":"block","typeId":2}'>Torch</button>
33 <button type="button" data-tool='{"kind":"block","typeId":3}'>Spawner</button>
34 <button type="button" data-tool='{"kind":"block","typeId":4}'>Bank</button>
33 35 <button type="button" data-tool='{"kind":"erase"}'>Erase block</button>
34 36 </div>
37 <div id="spawner-config">
38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option></select></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
42 </div>
35 43 <button id="save" type="button">Save chunk</button>
36 44 <button id="apply" type="button">Apply now</button>
37 45 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
38 46 <button id="open-settings" type="button">World settings</button>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool; the mouse wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
47 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool. Mouse wheel zooms (view stays centred on the selected chunk); Shift+wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Place a spawner or bank with the tools above (placeholder art until real sprites exist).</p>
40 48 </aside>
41 49 <section id="changelog-wrap">
42 50 <h2>Changelog</h2>
@@ -30,13 +30,21 @@
30 <button type="button" data-tool='{"kind":"ground","typeId":2}'>Wood</button>
30 <button type="button" data-tool='{"kind":"ground","typeId":2}'>Wood</button>
31 <button type="button" data-tool='{"kind":"block","typeId":1}'>Stone wall</button>
31 <button type="button" data-tool='{"kind":"block","typeId":1}'>Stone wall</button>
32 <button type="button" data-tool='{"kind":"block","typeId":2}'>Torch</button>
32 <button type="button" data-tool='{"kind":"block","typeId":2}'>Torch</button>
33 <button type="button" data-tool='{"kind":"block","typeId":3}'>Spawner</button>
34 <button type="button" data-tool='{"kind":"block","typeId":4}'>Bank</button>
33 <button type="button" data-tool='{"kind":"erase"}'>Erase block</button>
35 <button type="button" data-tool='{"kind":"erase"}'>Erase block</button>
34 </div>
36 </div>
37 <div id="spawner-config">
38 <p>Spawner (used when painting a new spawner tile)</p>
39 <label>Mob <select id="spawner-mob"><option value="deer">Deer</option></select></label>
40 <label>Max alive <input id="spawner-max" type="number" min="1" max="20" value="3"></label>
41 <label>Range <input id="spawner-range" type="number" min="1" max="16" value="4"></label>
42 </div>
35 <button id="save" type="button">Save chunk</button>
43 <button id="save" type="button">Save chunk</button>
36 <button id="apply" type="button">Apply now</button>
44 <button id="apply" type="button">Apply now</button>
37 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
45 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
38 <button id="open-settings" type="button">World settings</button>
46 <button id="open-settings" type="button">World settings</button>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool; the mouse wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
47 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool. Mouse wheel zooms (view stays centred on the selected chunk); Shift+wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Place a spawner or bank with the tools above (placeholder art until real sprites exist).</p>
40 </aside>
48 </aside>
41 <section id="changelog-wrap">
49 <section id="changelog-wrap">
42 <h2>Changelog</h2>
50 <h2>Changelog</h2>
client/index.html +30 −0
@@ -11,8 +11,34 @@
11 11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 13 <button id="friends-toggle" type="button">Friends</button>
14 <button id="bag-toggle" type="button">Bag</button>
14 15 <button id="leave" type="button">Leave world</button>
15 16 </div>
17 <aside id="bag-panel" hidden>
18 <h2>Bag</h2>
19 <p id="bag-coins">0 coins</p>
20 <div id="equip-grid" class="item-grid equip"></div>
21 <div id="bag-grid" class="item-grid"></div>
22 <p id="bag-hint" class="hint">Click a slot, then Drop or Equip.</p>
23 <div class="bag-actions">
24 <button id="bag-drop" type="button">Drop</button>
25 <button id="bag-equip" type="button">Equip</button>
26 <button id="bag-bank" type="button">Deposit selected</button>
27 </div>
28 </aside>
29 <aside id="bank-panel" hidden>
30 <header>
31 <h2>Bank</h2>
32 <button id="bank-close" type="button">Close</button>
33 </header>
34 <p id="vault-coins"></p>
35 <div id="vault-grid" class="item-grid"></div>
36 <h3>Inheritance</h3>
37 <p id="inherit-coins"></p>
38 <div id="inherit-grid" class="item-grid"></div>
39 <button id="bank-claim" type="button">Claim inheritance into vault</button>
40 <p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p>
41 </aside>
16 42 <aside id="friends-panel" hidden>
17 43 <h2>Friends</h2>
18 44 <div id="friends-list"></div>
@@ -23,6 +49,10 @@
23 49 <p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
24 50 </aside>
25 51 <div id="nametag" hidden></div>
52 <div id="chat-bubbles"></div>
53 <div id="chat-bar" hidden>
54 <input id="chat-input" type="text" maxlength="100" autocomplete="off" spellcheck="false" placeholder="Say something…">
55 </div>
26 56 <div id="inspect-backdrop" hidden></div>
27 57 <div id="inspect-modal" hidden>
28 58 <header>
@@ -11,8 +11,34 @@
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
11 <span>Walk/run: <strong id="gait">walk</strong> (press R)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
12 <span>Zoom: <strong id="zoom">2.00×</strong> (scroll)</span>
13 <button id="friends-toggle" type="button">Friends</button>
13 <button id="friends-toggle" type="button">Friends</button>
14 <button id="bag-toggle" type="button">Bag</button>
14 <button id="leave" type="button">Leave world</button>
15 <button id="leave" type="button">Leave world</button>
15 </div>
16 </div>
17 <aside id="bag-panel" hidden>
18 <h2>Bag</h2>
19 <p id="bag-coins">0 coins</p>
20 <div id="equip-grid" class="item-grid equip"></div>
21 <div id="bag-grid" class="item-grid"></div>
22 <p id="bag-hint" class="hint">Click a slot, then Drop or Equip.</p>
23 <div class="bag-actions">
24 <button id="bag-drop" type="button">Drop</button>
25 <button id="bag-equip" type="button">Equip</button>
26 <button id="bag-bank" type="button">Deposit selected</button>
27 </div>
28 </aside>
29 <aside id="bank-panel" hidden>
30 <header>
31 <h2>Bank</h2>
32 <button id="bank-close" type="button">Close</button>
33 </header>
34 <p id="vault-coins"></p>
35 <div id="vault-grid" class="item-grid"></div>
36 <h3>Inheritance</h3>
37 <p id="inherit-coins"></p>
38 <div id="inherit-grid" class="item-grid"></div>
39 <button id="bank-claim" type="button">Claim inheritance into vault</button>
40 <p class="hint">Stand next to a bank block. Click a vault slot to withdraw. Deposit uses the selected bag slot.</p>
41 </aside>
16 <aside id="friends-panel" hidden>
42 <aside id="friends-panel" hidden>
17 <h2>Friends</h2>
43 <h2>Friends</h2>
18 <div id="friends-list"></div>
44 <div id="friends-list"></div>
@@ -23,6 +49,10 @@
23 <p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
49 <p class="hint">Later, sending a pigeon can type a first and last name or pick a friend to fill those fields.</p>
24 </aside>
50 </aside>
25 <div id="nametag" hidden></div>
51 <div id="nametag" hidden></div>
52 <div id="chat-bubbles"></div>
53 <div id="chat-bar" hidden>
54 <input id="chat-input" type="text" maxlength="100" autocomplete="off" spellcheck="false" placeholder="Say something…">
55 </div>
26 <div id="inspect-backdrop" hidden></div>
56 <div id="inspect-backdrop" hidden></div>
27 <div id="inspect-modal" hidden>
57 <div id="inspect-modal" hidden>
28 <header>
58 <header>
client/scripts/write-placeholder-assets.mjs added +49 −0
@@ -0,0 +1,49 @@
1 import { join } from "node:path";
2 import { fillRect, makeRgba, writeRgbaPng } from "../../server/src/assets/placeholderPng.js";
3
4 const root = join(import.meta.dirname, "..", "assets");
5
6 function solid (file, color, border = [20, 20, 24, 255])
7 {
8 const image = makeRgba(16, 16, color);
9 fillRect(image, 0, 0, 16, 1, border);
10 fillRect(image, 0, 15, 16, 1, border);
11 fillRect(image, 0, 0, 1, 16, border);
12 fillRect(image, 15, 0, 1, 16, border);
13 writeRgbaPng(file, 16, 16, image.pixels);
14 }
15
16 function overlay (file, color)
17 {
18 const image = makeRgba(16, 16, [0, 0, 0, 0]);
19 fillRect(image, 4, 3, 8, 11, color);
20 writeRgbaPng(file, 16, 16, image.pixels);
21 }
22
23 function torchBloom (file)
24 {
25 const image = makeRgba(16, 16, [0, 0, 0, 0]);
26 const rings = [
27 { x: 3, y: 2, w: 10, h: 10, rgba: [180, 48, 12, 90] },
28 { x: 4, y: 3, w: 8, h: 8, rgba: [230, 110, 24, 160] },
29 { x: 5, y: 4, w: 6, h: 6, rgba: [255, 190, 48, 220] },
30 { x: 6, y: 5, w: 4, h: 4, rgba: [255, 245, 200, 255] }
31 ];
32 for (const ring of rings)
33 { fillRect(image, ring.x, ring.y, ring.w, ring.h, ring.rgba); }
34 writeRgbaPng(file, 16, 16, image.pixels);
35 }
36
37 solid(join(root, "items", "paper", "paper.png"), [232, 224, 196, 255]);
38 solid(join(root, "items", "apple", "apple.png"), [196, 48, 48, 255]);
39 solid(join(root, "items", "stick", "stick.png"), [140, 92, 44, 255]);
40 solid(join(root, "items", "blank-cheque", "blank-cheque.png"), [168, 214, 168, 255]);
41 solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]);
42 solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43 solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44 solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45 overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46 overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47 torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
48
49 console.log("Wrote placeholder sprites under client/assets.");
@@ -0,0 +1,49 @@
1import { join } from "node:path";
2import { fillRect, makeRgba, writeRgbaPng } from "../../server/src/assets/placeholderPng.js";
3
4const root = join(import.meta.dirname, "..", "assets");
5
6function solid (file, color, border = [20, 20, 24, 255])
7{
8 const image = makeRgba(16, 16, color);
9 fillRect(image, 0, 0, 16, 1, border);
10 fillRect(image, 0, 15, 16, 1, border);
11 fillRect(image, 0, 0, 1, 16, border);
12 fillRect(image, 15, 0, 1, 16, border);
13 writeRgbaPng(file, 16, 16, image.pixels);
14}
15
16function overlay (file, color)
17{
18 const image = makeRgba(16, 16, [0, 0, 0, 0]);
19 fillRect(image, 4, 3, 8, 11, color);
20 writeRgbaPng(file, 16, 16, image.pixels);
21}
22
23function torchBloom (file)
24{
25 const image = makeRgba(16, 16, [0, 0, 0, 0]);
26 const rings = [
27 { x: 3, y: 2, w: 10, h: 10, rgba: [180, 48, 12, 90] },
28 { x: 4, y: 3, w: 8, h: 8, rgba: [230, 110, 24, 160] },
29 { x: 5, y: 4, w: 6, h: 6, rgba: [255, 190, 48, 220] },
30 { x: 6, y: 5, w: 4, h: 4, rgba: [255, 245, 200, 255] }
31 ];
32 for (const ring of rings)
33 { fillRect(image, ring.x, ring.y, ring.w, ring.h, ring.rgba); }
34 writeRgbaPng(file, 16, 16, image.pixels);
35}
36
37solid(join(root, "items", "paper", "paper.png"), [232, 224, 196, 255]);
38solid(join(root, "items", "apple", "apple.png"), [196, 48, 48, 255]);
39solid(join(root, "items", "stick", "stick.png"), [140, 92, 44, 255]);
40solid(join(root, "items", "blank-cheque", "blank-cheque.png"), [168, 214, 168, 255]);
41solid(join(root, "items", "cloth-shirt", "cloth-shirt.png"), [72, 112, 176, 255]);
42solid(join(root, "blocks", "spawner", "spawner.png"), [168, 64, 196, 255], [80, 20, 96, 255]);
43solid(join(root, "blocks", "bank", "bank.png"), [212, 176, 72, 255], [96, 72, 16, 255]);
44solid(join(root, "mobs", "deer", "deer.png"), [120, 78, 42, 255]);
45overlay(join(root, "items", "stick", "stick-equip.png"), [150, 98, 46, 230]);
46overlay(join(root, "items", "cloth-shirt", "cloth-shirt-equip.png"), [72, 112, 176, 230]);
47torchBloom(join(root, "blocks", "torch", "torch-bloom.png"));
48
49console.log("Wrote placeholder sprites under client/assets.");
client/src/editor/main.js +68 −13
@@ -1,8 +1,8 @@
1 1 import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3 3 import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
4 4 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5 import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6 6 import { WorldView } from "../render/worldView.js";
7 7 import { initSettingsModal } from "./settingsModal.js";
8 8
@@ -17,6 +17,10 @@ let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17 17 let settingsModal;
18 18 let catalog = { grounds: {}, blocks: {} };
19 19 let hoverLocal = null;
20 let editorZoom = null;
21 const EDITOR_ZOOM_MIN = 0.25;
22 const EDITOR_ZOOM_MAX = 8;
23 const EDITOR_ZOOM_STEP = 1.12;
20 24
21 25 function $ (id)
22 26 {
@@ -52,13 +56,23 @@ function selectTool (next)
52 56 };
53 57 }
54 58
59 function placeableToolState ()
60 {
61 if (tool.kind === "erase")
62 { return null; }
63 const layer = tool.kind === "ground" ? "ground" : "block";
64 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
65 return resolveState(statesForType(catalog, layer, def.key), tool.state);
66 }
67
55 68 function previewFromTool ()
56 69 {
57 70 if (tool.kind === "erase")
58 71 { return { block: null }; }
72 const state = placeableToolState();
59 73 if (tool.kind === "ground")
60 { return { ground: { typeId: tool.typeId, state: tool.state } }; }
61 return { block: { typeId: tool.typeId, state: tool.state, config: null } };
74 { return { ground: { typeId: tool.typeId, state } }; }
75 return { block: { typeId: tool.typeId, state, config: null } };
62 76 }
63 77
64 78 function inEditorView (x, y)
@@ -96,12 +110,28 @@ function paintAt (localX, localY)
96 110 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
97 111 { return; }
98 112 const index = localY * CHUNK_SIZE + localX;
113 const state = placeableToolState();
99 114 if (tool.kind === "ground")
100 { draft.grounds[index] = { typeId: tool.typeId, state: tool.state }; }
115 { draft.grounds[index] = { typeId: tool.typeId, state }; }
101 116 else if (tool.kind === "erase")
102 117 { draft.blocks[index] = null; }
103 118 else
104 { draft.blocks[index] = { typeId: tool.typeId, state: tool.state, config: null }; }
119 {
120 const existing = draft.blocks[index];
121 let config = null;
122 if (tool.typeId === BlockType.spawner)
123 {
124 config = existing?.typeId === BlockType.spawner && existing.config
125 ? { ...existing.config }
126 : {
127 spawnerId: `${chunkX}:${chunkY}:${index}`,
128 mobTypeId: $("spawner-mob")?.value || "deer",
129 maxAlive: Number($("spawner-max")?.value || 3),
130 spawnRangeTiles: Number($("spawner-range")?.value || 4)
131 };
132 }
133 draft.blocks[index] = { typeId: tool.typeId, state, config };
134 }
105 135 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
106 136 ground: draft.grounds[index],
107 137 block: draft.blocks[index],
@@ -199,7 +229,21 @@ function layoutScene ()
199 229 scene.g_fixSize();
200 230 useNearestNeighbour(scene, game.images);
201 231 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
202 view.setZoom(fit, { min: 0.5, max: 4 });
232 if (editorZoom == null)
233 { editorZoom = fit; }
234 else
235 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
236 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
237 frameNeighborhood();
238 }
239
240 function zoomEditor (direction)
241 {
242 if (!view)
243 { return; }
244 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
245 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
246 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
203 247 frameNeighborhood();
204 248 }
205 249
@@ -227,7 +271,7 @@ function requestNeighbors ()
227 271 async function main ()
228 272 {
229 273 catalog = await loadSpriteCatalog();
230 await game.preloadImages(playImagesFromCatalog(catalog));
274 await preloadCatalogImages(game, catalog);
231 275 applySpriteSheets(game.images, catalog);
232 276 scene = new Scene(250, 56, 64, 64);
233 277 game.loadScene(scene);
@@ -282,7 +326,7 @@ async function main ()
282 326 else if (message.type === MessageType.editorChunk)
283 327 {
284 328 if (message.settings)
285 { view.settings = message.settings; }
329 { view.setSettings(message.settings); }
286 330 if (!inEditorView(message.chunkX, message.chunkY))
287 331 { return; }
288 332 if (message.chunkX === chunkX && message.chunkY === chunkY)
@@ -299,7 +343,13 @@ async function main ()
299 343 MessageType,
300 344 onApplied (settings)
301 345 {
302 view.settings = settings;
346 view.setSettings(settings);
347 },
348 onPreviewNight (hour)
349 {
350 view.nightPreview = hour;
351 $("night").value = String(hour);
352 $("night-label").textContent = Number(hour).toFixed(1);
303 353 }
304 354 });
305 355 game.startGame();
@@ -374,9 +424,14 @@ document.addEventListener("wheel", (event) =>
374 424 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
375 425 { return; }
376 426 event.preventDefault();
377 cycleToolState(event.deltaY < 0 ? 1 : -1);
378 if (hoverLocal)
379 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
427 if (event.shiftKey)
428 {
429 cycleToolState(event.deltaY < 0 ? 1 : -1);
430 if (hoverLocal)
431 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
432 return;
433 }
434 zoomEditor(event.deltaY < 0 ? 1 : -1);
380 435 }, { passive: false });
381 436
382 437 main().catch((error) =>
@@ -1,8 +1,8 @@
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, BlockType, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { WorldView } from "../render/worldView.js";
6import { WorldView } from "../render/worldView.js";
7import { initSettingsModal } from "./settingsModal.js";
7import { initSettingsModal } from "./settingsModal.js";
8
8
@@ -17,6 +17,10 @@ let tool = { kind: "ground", typeId: GroundType.grass, state: null };
17let settingsModal;
17let settingsModal;
18let catalog = { grounds: {}, blocks: {} };
18let catalog = { grounds: {}, blocks: {} };
19let hoverLocal = null;
19let hoverLocal = null;
20let editorZoom = null;
21const EDITOR_ZOOM_MIN = 0.25;
22const EDITOR_ZOOM_MAX = 8;
23const EDITOR_ZOOM_STEP = 1.12;
20
24
21function $ (id)
25function $ (id)
22{
26{
@@ -52,13 +56,23 @@ function selectTool (next)
52 };
56 };
53}
57}
54
58
59function placeableToolState ()
60{
61 if (tool.kind === "erase")
62 { return null; }
63 const layer = tool.kind === "ground" ? "ground" : "block";
64 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
65 return resolveState(statesForType(catalog, layer, def.key), tool.state);
66}
67
55function previewFromTool ()
68function previewFromTool ()
56{
69{
57 if (tool.kind === "erase")
70 if (tool.kind === "erase")
58 { return { block: null }; }
71 { return { block: null }; }
72 const state = placeableToolState();
59 if (tool.kind === "ground")
73 if (tool.kind === "ground")
60 { return { ground: { typeId: tool.typeId, state: tool.state } }; }
74 { return { ground: { typeId: tool.typeId, state } }; }
61 return { block: { typeId: tool.typeId, state: tool.state, config: null } };
75 return { block: { typeId: tool.typeId, state, config: null } };
62}
76}
63
77
64function inEditorView (x, y)
78function inEditorView (x, y)
@@ -96,12 +110,28 @@ function paintAt (localX, localY)
96 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
110 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
97 { return; }
111 { return; }
98 const index = localY * CHUNK_SIZE + localX;
112 const index = localY * CHUNK_SIZE + localX;
113 const state = placeableToolState();
99 if (tool.kind === "ground")
114 if (tool.kind === "ground")
100 { draft.grounds[index] = { typeId: tool.typeId, state: tool.state }; }
115 { draft.grounds[index] = { typeId: tool.typeId, state }; }
101 else if (tool.kind === "erase")
116 else if (tool.kind === "erase")
102 { draft.blocks[index] = null; }
117 { draft.blocks[index] = null; }
103 else
118 else
104 { draft.blocks[index] = { typeId: tool.typeId, state: tool.state, config: null }; }
119 {
120 const existing = draft.blocks[index];
121 let config = null;
122 if (tool.typeId === BlockType.spawner)
123 {
124 config = existing?.typeId === BlockType.spawner && existing.config
125 ? { ...existing.config }
126 : {
127 spawnerId: `${chunkX}:${chunkY}:${index}`,
128 mobTypeId: $("spawner-mob")?.value || "deer",
129 maxAlive: Number($("spawner-max")?.value || 3),
130 spawnRangeTiles: Number($("spawner-range")?.value || 4)
131 };
132 }
133 draft.blocks[index] = { typeId: tool.typeId, state, config };
134 }
105 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
135 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
106 ground: draft.grounds[index],
136 ground: draft.grounds[index],
107 block: draft.blocks[index],
137 block: draft.blocks[index],
@@ -199,7 +229,21 @@ function layoutScene ()
199 scene.g_fixSize();
229 scene.g_fixSize();
200 useNearestNeighbour(scene, game.images);
230 useNearestNeighbour(scene, game.images);
201 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
231 const fit = Math.min(width, height) / (CHUNK_SIZE * 3 * SPRITE_SIZE_PX);
202 view.setZoom(fit, { min: 0.5, max: 4 });
232 if (editorZoom == null)
233 { editorZoom = fit; }
234 else
235 { editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, editorZoom)); }
236 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
237 frameNeighborhood();
238}
239
240function zoomEditor (direction)
241{
242 if (!view)
243 { return; }
244 const factor = direction > 0 ? EDITOR_ZOOM_STEP : 1 / EDITOR_ZOOM_STEP;
245 editorZoom = Math.min(EDITOR_ZOOM_MAX, Math.max(EDITOR_ZOOM_MIN, (editorZoom ?? view.zoom) * factor));
246 view.setZoom(editorZoom, { min: EDITOR_ZOOM_MIN, max: EDITOR_ZOOM_MAX });
203 frameNeighborhood();
247 frameNeighborhood();
204}
248}
205
249
@@ -227,7 +271,7 @@ function requestNeighbors ()
227async function main ()
271async function main ()
228{
272{
229 catalog = await loadSpriteCatalog();
273 catalog = await loadSpriteCatalog();
230 await game.preloadImages(playImagesFromCatalog(catalog));
274 await preloadCatalogImages(game, catalog);
231 applySpriteSheets(game.images, catalog);
275 applySpriteSheets(game.images, catalog);
232 scene = new Scene(250, 56, 64, 64);
276 scene = new Scene(250, 56, 64, 64);
233 game.loadScene(scene);
277 game.loadScene(scene);
@@ -282,7 +326,7 @@ async function main ()
282 else if (message.type === MessageType.editorChunk)
326 else if (message.type === MessageType.editorChunk)
283 {
327 {
284 if (message.settings)
328 if (message.settings)
285 { view.settings = message.settings; }
329 { view.setSettings(message.settings); }
286 if (!inEditorView(message.chunkX, message.chunkY))
330 if (!inEditorView(message.chunkX, message.chunkY))
287 { return; }
331 { return; }
288 if (message.chunkX === chunkX && message.chunkY === chunkY)
332 if (message.chunkX === chunkX && message.chunkY === chunkY)
@@ -299,7 +343,13 @@ async function main ()
299 MessageType,
343 MessageType,
300 onApplied (settings)
344 onApplied (settings)
301 {
345 {
302 view.settings = settings;
346 view.setSettings(settings);
347 },
348 onPreviewNight (hour)
349 {
350 view.nightPreview = hour;
351 $("night").value = String(hour);
352 $("night-label").textContent = Number(hour).toFixed(1);
303 }
353 }
304 });
354 });
305 game.startGame();
355 game.startGame();
@@ -374,9 +424,14 @@ document.addEventListener("wheel", (event) =>
374 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
424 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
375 { return; }
425 { return; }
376 event.preventDefault();
426 event.preventDefault();
377 cycleToolState(event.deltaY < 0 ? 1 : -1);
427 if (event.shiftKey)
378 if (hoverLocal)
428 {
379 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
429 cycleToolState(event.deltaY < 0 ? 1 : -1);
430 if (hoverLocal)
431 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
432 return;
433 }
434 zoomEditor(event.deltaY < 0 ? 1 : -1);
380}, { passive: false });
435}, { passive: false });
381
436
382main().catch((error) =>
437main().catch((error) =>
client/src/editor/settingsModal.js +46 −9
@@ -1,6 +1,6 @@
1 import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue } from "/shared/definitions/worldSettings.js";
1 import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue, settingsValuesEqual } from "/shared/definitions/worldSettings.js";
2 2
3 export function initSettingsModal ({ socket, MessageType, onApplied })
3 export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
4 4 {
5 5 const backdrop = document.getElementById("settings-backdrop");
6 6 const modal = document.getElementById("settings-modal");
@@ -10,8 +10,21 @@ export function initSettingsModal ({ socket, MessageType, onApplied })
10 10 let baseline = {};
11 11 let open = false;
12 12 let loaded = false;
13 let activeCategory = WORLD_SETTING_CATEGORIES[0]?.id ?? null;
13 14
14 buildForm(form);
15 buildForm(form, {
16 getActiveCategory: () => activeCategory,
17 setActiveCategory (id)
18 {
19 activeCategory = id;
20 syncTabs(form, activeCategory);
21 },
22 onFieldInput (field)
23 {
24 if (field.previewNightHour != null && onPreviewNight)
25 { onPreviewNight(field.previewNightHour); }
26 }
27 });
15 28 form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
16 29 form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
17 30
@@ -59,16 +72,28 @@ export function initSettingsModal ({ socket, MessageType, onApplied })
59 72 };
60 73 }
61 74
62 function buildForm (form)
75 function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput })
63 76 {
64 77 form.innerHTML = "";
78 const tabs = document.createElement("div");
79 tabs.className = "settings-tabs";
80 tabs.setAttribute("role", "tablist");
81 const panels = document.createElement("div");
82 panels.className = "settings-panels";
83
65 84 for (const category of WORLD_SETTING_CATEGORIES)
66 85 {
86 const tab = document.createElement("button");
87 tab.type = "button";
88 tab.className = "settings-tab";
89 tab.dataset.category = category.id;
90 tab.textContent = category.label;
91 tab.addEventListener("click", () => setActiveCategory(category.id));
92 tabs.append(tab);
93
67 94 const section = document.createElement("section");
68 95 section.className = "settings-category";
69 const heading = document.createElement("h3");
70 heading.textContent = category.label;
71 section.append(heading);
96 section.dataset.category = category.id;
72 97 for (const field of category.fields)
73 98 {
74 99 const row = document.createElement("label");
@@ -92,6 +117,7 @@ function buildForm (form)
92 117 input.addEventListener("input", () =>
93 118 {
94 119 valueLabel.textContent = formatSettingValue(Number(input.value));
120 onFieldInput?.(field);
95 121 });
96 122 row.append(title, input, valueLabel);
97 123 if (field.hint)
@@ -103,8 +129,19 @@ function buildForm (form)
103 129 }
104 130 section.append(row);
105 131 }
106 form.append(section);
132 panels.append(section);
107 133 }
134
135 form.append(tabs, panels);
136 syncTabs(form, getActiveCategory());
137 }
138
139 function syncTabs (form, activeCategory)
140 {
141 for (const tab of form.querySelectorAll(".settings-tab"))
142 { tab.classList.toggle("active", tab.dataset.category === activeCategory); }
143 for (const panel of form.querySelectorAll(".settings-category"))
144 { panel.hidden = panel.dataset.category !== activeCategory; }
108 145 }
109 146
110 147 function fillForm (form, settings)
@@ -126,7 +163,7 @@ function dirtyValues (form, baseline)
126 163 {
127 164 const field = findField(input.dataset.key);
128 165 const next = coerceSettingValue(field, input.value);
129 if (next == null || next === baseline[field.key])
166 if (next == null || settingsValuesEqual(next, baseline[field.key]))
130 167 { continue; }
131 168 changed[field.key] = next;
132 169 }
@@ -1,6 +1,6 @@
1import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue } from "/shared/definitions/worldSettings.js";
1import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue, settingsValuesEqual } from "/shared/definitions/worldSettings.js";
2
2
3export function initSettingsModal ({ socket, MessageType, onApplied })
3export function initSettingsModal ({ socket, MessageType, onApplied, onPreviewNight })
4{
4{
5 const backdrop = document.getElementById("settings-backdrop");
5 const backdrop = document.getElementById("settings-backdrop");
6 const modal = document.getElementById("settings-modal");
6 const modal = document.getElementById("settings-modal");
@@ -10,8 +10,21 @@ export function initSettingsModal ({ socket, MessageType, onApplied })
10 let baseline = {};
10 let baseline = {};
11 let open = false;
11 let open = false;
12 let loaded = false;
12 let loaded = false;
13 let activeCategory = WORLD_SETTING_CATEGORIES[0]?.id ?? null;
13
14
14 buildForm(form);
15 buildForm(form, {
16 getActiveCategory: () => activeCategory,
17 setActiveCategory (id)
18 {
19 activeCategory = id;
20 syncTabs(form, activeCategory);
21 },
22 onFieldInput (field)
23 {
24 if (field.previewNightHour != null && onPreviewNight)
25 { onPreviewNight(field.previewNightHour); }
26 }
27 });
15 form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
28 form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
16 form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
29 form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
17
30
@@ -59,16 +72,28 @@ export function initSettingsModal ({ socket, MessageType, onApplied })
59 };
72 };
60}
73}
61
74
62function buildForm (form)
75function buildForm (form, { getActiveCategory, setActiveCategory, onFieldInput })
63{
76{
64 form.innerHTML = "";
77 form.innerHTML = "";
78 const tabs = document.createElement("div");
79 tabs.className = "settings-tabs";
80 tabs.setAttribute("role", "tablist");
81 const panels = document.createElement("div");
82 panels.className = "settings-panels";
83
65 for (const category of WORLD_SETTING_CATEGORIES)
84 for (const category of WORLD_SETTING_CATEGORIES)
66 {
85 {
86 const tab = document.createElement("button");
87 tab.type = "button";
88 tab.className = "settings-tab";
89 tab.dataset.category = category.id;
90 tab.textContent = category.label;
91 tab.addEventListener("click", () => setActiveCategory(category.id));
92 tabs.append(tab);
93
67 const section = document.createElement("section");
94 const section = document.createElement("section");
68 section.className = "settings-category";
95 section.className = "settings-category";
69 const heading = document.createElement("h3");
96 section.dataset.category = category.id;
70 heading.textContent = category.label;
71 section.append(heading);
72 for (const field of category.fields)
97 for (const field of category.fields)
73 {
98 {
74 const row = document.createElement("label");
99 const row = document.createElement("label");
@@ -92,6 +117,7 @@ function buildForm (form)
92 input.addEventListener("input", () =>
117 input.addEventListener("input", () =>
93 {
118 {
94 valueLabel.textContent = formatSettingValue(Number(input.value));
119 valueLabel.textContent = formatSettingValue(Number(input.value));
120 onFieldInput?.(field);
95 });
121 });
96 row.append(title, input, valueLabel);
122 row.append(title, input, valueLabel);
97 if (field.hint)
123 if (field.hint)
@@ -103,8 +129,19 @@ function buildForm (form)
103 }
129 }
104 section.append(row);
130 section.append(row);
105 }
131 }
106 form.append(section);
132 panels.append(section);
107 }
133 }
134
135 form.append(tabs, panels);
136 syncTabs(form, getActiveCategory());
137}
138
139function syncTabs (form, activeCategory)
140{
141 for (const tab of form.querySelectorAll(".settings-tab"))
142 { tab.classList.toggle("active", tab.dataset.category === activeCategory); }
143 for (const panel of form.querySelectorAll(".settings-category"))
144 { panel.hidden = panel.dataset.category !== activeCategory; }
108}
145}
109
146
110function fillForm (form, settings)
147function fillForm (form, settings)
@@ -126,7 +163,7 @@ function dirtyValues (form, baseline)
126 {
163 {
127 const field = findField(input.dataset.key);
164 const field = findField(input.dataset.key);
128 const next = coerceSettingValue(field, input.value);
165 const next = coerceSettingValue(field, input.value);
129 if (next == null || next === baseline[field.key])
166 if (next == null || settingsValuesEqual(next, baseline[field.key]))
130 { continue; }
167 { continue; }
131 changed[field.key] = next;
168 changed[field.key] = next;
132 }
169 }
client/src/play/chat.js added +149 −0
@@ -0,0 +1,149 @@
1 const BUBBLE_MS = 8000;
2
3 export function initChat ({ socket, MessageType, getSettings })
4 {
5 const bar = document.getElementById("chat-bar");
6 const input = document.getElementById("chat-input");
7 const layer = document.getElementById("chat-bubbles");
8 const bubbles = new Map();
9 let open = false;
10
11 function maxChars ()
12 {
13 return Math.max(1, Math.round(getSettings()?.chatMaxCharacters || 100));
14 }
15
16 function close ()
17 {
18 open = false;
19 bar.hidden = true;
20 input.value = "";
21 input.blur();
22 }
23
24 function openBar ()
25 {
26 open = true;
27 input.maxLength = maxChars();
28 bar.hidden = false;
29 input.focus();
30 }
31
32 function submit ()
33 {
34 const text = input.value.trim().slice(0, maxChars());
35 close();
36 if (!text)
37 { return; }
38 socket.send({ type: MessageType.chatSay, text });
39 }
40
41 function playingHudReady ()
42 {
43 return !!(
44 document.getElementById("overlay")?.hidden
45 && !document.getElementById("hud")?.hidden
46 && document.getElementById("inspect-modal")?.hidden
47 );
48 }
49
50 input.addEventListener("keydown", (event) =>
51 {
52 event.stopPropagation();
53 if (event.key === "Enter")
54 {
55 event.preventDefault();
56 submit();
57 }
58 if (event.key === "Escape")
59 {
60 event.preventDefault();
61 close();
62 }
63 });
64 input.addEventListener("keyup", (event) => event.stopPropagation());
65
66 window.addEventListener("keydown", (event) =>
67 {
68 if (event.key !== "Enter" || event.repeat)
69 { return; }
70 if (document.activeElement === input)
71 { return; }
72 if (!playingHudReady())
73 { return; }
74 event.preventDefault();
75 event.stopPropagation();
76 if (open)
77 { submit(); }
78 else
79 { openBar(); }
80 }, true);
81
82 return {
83 isOpen: () => open,
84 isBlocking ()
85 {
86 if (!open)
87 { return false; }
88 const box = bar.getBoundingClientRect();
89 const x = GameInput.mousePosition.x;
90 const y = GameInput.mousePosition.y;
91 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
92 },
93 close,
94 reset ()
95 {
96 close();
97 layer.replaceChildren();
98 bubbles.clear();
99 },
100 showBubble (message)
101 {
102 if (!message?.text)
103 { return; }
104 let bubble = bubbles.get(message.entityId);
105 if (!bubble)
106 {
107 bubble = { element: document.createElement("div"), until: 0 };
108 bubble.element.className = "chat-bubble";
109 layer.append(bubble.element);
110 bubbles.set(message.entityId, bubble);
111 }
112 bubble.element.textContent = message.text;
113 bubble.until = Date.now() + BUBBLE_MS;
114 },
115 syncSettings ()
116 {
117 input.maxLength = maxChars();
118 if (input.value.length > input.maxLength)
119 { input.value = input.value.slice(0, input.maxLength); }
120 },
121 update (view, scene)
122 {
123 const now = Date.now();
124 const canvas = scene?.canvas;
125 if (!canvas)
126 { return; }
127 const rect = canvas.getBoundingClientRect();
128 for (const [entityId, bubble] of [...bubbles.entries()])
129 {
130 if (now >= bubble.until)
131 {
132 bubble.element.remove();
133 bubbles.delete(entityId);
134 continue;
135 }
136 const entity = view.entities.get(entityId);
137 const anchor = entity ? view.nametagAnchor(entity) : null;
138 if (!anchor)
139 {
140 bubble.element.hidden = true;
141 continue;
142 }
143 bubble.element.hidden = false;
144 bubble.element.style.left = `${rect.left + anchor.x}px`;
145 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
146 }
147 }
148 };
149 }
@@ -0,0 +1,149 @@
1const BUBBLE_MS = 8000;
2
3export function initChat ({ socket, MessageType, getSettings })
4{
5 const bar = document.getElementById("chat-bar");
6 const input = document.getElementById("chat-input");
7 const layer = document.getElementById("chat-bubbles");
8 const bubbles = new Map();
9 let open = false;
10
11 function maxChars ()
12 {
13 return Math.max(1, Math.round(getSettings()?.chatMaxCharacters || 100));
14 }
15
16 function close ()
17 {
18 open = false;
19 bar.hidden = true;
20 input.value = "";
21 input.blur();
22 }
23
24 function openBar ()
25 {
26 open = true;
27 input.maxLength = maxChars();
28 bar.hidden = false;
29 input.focus();
30 }
31
32 function submit ()
33 {
34 const text = input.value.trim().slice(0, maxChars());
35 close();
36 if (!text)
37 { return; }
38 socket.send({ type: MessageType.chatSay, text });
39 }
40
41 function playingHudReady ()
42 {
43 return !!(
44 document.getElementById("overlay")?.hidden
45 && !document.getElementById("hud")?.hidden
46 && document.getElementById("inspect-modal")?.hidden
47 );
48 }
49
50 input.addEventListener("keydown", (event) =>
51 {
52 event.stopPropagation();
53 if (event.key === "Enter")
54 {
55 event.preventDefault();
56 submit();
57 }
58 if (event.key === "Escape")
59 {
60 event.preventDefault();
61 close();
62 }
63 });
64 input.addEventListener("keyup", (event) => event.stopPropagation());
65
66 window.addEventListener("keydown", (event) =>
67 {
68 if (event.key !== "Enter" || event.repeat)
69 { return; }
70 if (document.activeElement === input)
71 { return; }
72 if (!playingHudReady())
73 { return; }
74 event.preventDefault();
75 event.stopPropagation();
76 if (open)
77 { submit(); }
78 else
79 { openBar(); }
80 }, true);
81
82 return {
83 isOpen: () => open,
84 isBlocking ()
85 {
86 if (!open)
87 { return false; }
88 const box = bar.getBoundingClientRect();
89 const x = GameInput.mousePosition.x;
90 const y = GameInput.mousePosition.y;
91 return x >= box.left && x < box.right && y >= box.top && y < box.bottom;
92 },
93 close,
94 reset ()
95 {
96 close();
97 layer.replaceChildren();
98 bubbles.clear();
99 },
100 showBubble (message)
101 {
102 if (!message?.text)
103 { return; }
104 let bubble = bubbles.get(message.entityId);
105 if (!bubble)
106 {
107 bubble = { element: document.createElement("div"), until: 0 };
108 bubble.element.className = "chat-bubble";
109 layer.append(bubble.element);
110 bubbles.set(message.entityId, bubble);
111 }
112 bubble.element.textContent = message.text;
113 bubble.until = Date.now() + BUBBLE_MS;
114 },
115 syncSettings ()
116 {
117 input.maxLength = maxChars();
118 if (input.value.length > input.maxLength)
119 { input.value = input.value.slice(0, input.maxLength); }
120 },
121 update (view, scene)
122 {
123 const now = Date.now();
124 const canvas = scene?.canvas;
125 if (!canvas)
126 { return; }
127 const rect = canvas.getBoundingClientRect();
128 for (const [entityId, bubble] of [...bubbles.entries()])
129 {
130 if (now >= bubble.until)
131 {
132 bubble.element.remove();
133 bubbles.delete(entityId);
134 continue;
135 }
136 const entity = view.entities.get(entityId);
137 const anchor = entity ? view.nametagAnchor(entity) : null;
138 if (!anchor)
139 {
140 bubble.element.hidden = true;
141 continue;
142 }
143 bubble.element.hidden = false;
144 bubble.element.style.left = `${rect.left + anchor.x}px`;
145 bubble.element.style.top = `${rect.top + anchor.y - 36}px`;
146 }
147 }
148 };
149}
client/src/play/inventory.js added +173 −0
@@ -0,0 +1,173 @@
1 import { itemDefinition, itemAssetPath, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
2
3 const EQUIP_LABELS = {
4 [EQUIPMENT_SLOT.head]: "Head",
5 [EQUIPMENT_SLOT.chest]: "Chest",
6 [EQUIPMENT_SLOT.legs]: "Legs",
7 [EQUIPMENT_SLOT.boots]: "Boots",
8 [EQUIPMENT_SLOT.weapon]: "Weapon",
9 [EQUIPMENT_SLOT.offhand]: "Off-hand"
10 };
11
12 export function initInventory ({ socket, MessageType, game })
13 {
14 const bagPanel = document.getElementById("bag-panel");
15 const bagGrid = document.getElementById("bag-grid");
16 const equipGrid = document.getElementById("equip-grid");
17 const coins = document.getElementById("bag-coins");
18 const hint = document.getElementById("bag-hint");
19 const bankPanel = document.getElementById("bank-panel");
20 const vaultGrid = document.getElementById("vault-grid");
21 const vaultCoins = document.getElementById("vault-coins");
22 const inheritGrid = document.getElementById("inherit-grid");
23 const inheritCoins = document.getElementById("inherit-coins");
24 let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
25 let selected = null;
26 let bankOpen = false;
27
28 document.getElementById("bag-toggle").addEventListener("click", () =>
29 {
30 bagPanel.hidden = !bagPanel.hidden;
31 });
32 document.getElementById("bag-drop").addEventListener("click", () =>
33 {
34 if (selected == null)
35 { return; }
36 socket.send({ type: MessageType.dropItem, slotIndex: selected });
37 });
38 document.getElementById("bag-equip").addEventListener("click", () =>
39 {
40 if (selected == null)
41 { return; }
42 socket.send({ type: MessageType.equipItem, slotIndex: selected });
43 });
44 document.getElementById("bank-close").addEventListener("click", () =>
45 {
46 bankOpen = false;
47 bankPanel.hidden = true;
48 });
49 document.getElementById("bank-claim").addEventListener("click", () =>
50 {
51 socket.send({ type: MessageType.claimInheritance });
52 });
53
54 function render ()
55 {
56 coins.textContent = `${bag.currency ?? 0} coins`;
57 bagGrid.innerHTML = "";
58 (bag.inventory ?? []).forEach((slot, index) =>
59 {
60 const button = document.createElement("button");
61 button.className = `item-slot${selected === index ? " selected" : ""}`;
62 button.title = tooltip(slot);
63 if (slot)
64 {
65 const def = itemDefinition(slot.itemId);
66 const img = document.createElement("img");
67 img.src = itemAssetPath(slot.itemId);
68 img.alt = def?.displayName ?? "";
69 button.append(img);
70 if (slot.quantity > 1)
71 {
72 const count = document.createElement("span");
73 count.className = "qty";
74 count.textContent = String(slot.quantity);
75 button.append(count);
76 }
77 }
78 button.addEventListener("click", () =>
79 {
80 selected = index;
81 const def = slot ? itemDefinition(slot.itemId) : null;
82 hint.textContent = def ? `${def.displayName}: ${def.description}` : "Empty slot.";
83 render();
84 });
85 bagGrid.append(button);
86 });
87 equipGrid.innerHTML = "";
88 for (const [slot, label] of Object.entries(EQUIP_LABELS))
89 {
90 const worn = bag.equipment?.slots?.[slot];
91 const button = document.createElement("button");
92 button.className = "item-slot";
93 button.title = worn ? tooltip(worn) : label;
94 button.textContent = worn ? (itemDefinition(worn.itemId)?.displayName ?? label) : label;
95 button.addEventListener("click", () =>
96 {
97 if (worn)
98 { socket.send({ type: MessageType.unequipItem, equipSlot: slot }); }
99 });
100 equipGrid.append(button);
101 }
102 }
103
104 function renderVault (grid, slots)
105 {
106 grid.innerHTML = "";
107 (slots ?? []).forEach((slot, index) =>
108 {
109 const button = document.createElement("button");
110 button.className = "item-slot";
111 button.title = tooltip(slot);
112 button.textContent = slot
113 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`
114 : "";
115 button.addEventListener("click", () =>
116 {
117 if (!slot)
118 { return; }
119 socket.send({ type: MessageType.bankWithdraw, slotIndex: index });
120 });
121 grid.append(button);
122 });
123 }
124
125 function tooltip (slot)
126 {
127 if (!slot)
128 { return ""; }
129 const def = itemDefinition(slot.itemId);
130 return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`;
131 }
132
133 return {
134 isOpen ()
135 {
136 return !bagPanel.hidden || bankOpen;
137 },
138 handleInventory (message)
139 {
140 bag = { ...bag, ...message };
141 render();
142 },
143 handleBank (message)
144 {
145 bankOpen = true;
146 bankPanel.hidden = false;
147 bag.vault = message.vault;
148 bag.vaultCurrency = message.vaultCurrency;
149 vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`;
150 inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`;
151 renderVault(vaultGrid, message.vault);
152 renderVault(inheritGrid, message.inheritance?.slots ?? []);
153 inheritGrid.querySelectorAll("button").forEach((button) =>
154 {
155 button.onclick = null;
156 });
157 render();
158 },
159 depositSelected ()
160 {
161 if (selected == null)
162 { return; }
163 socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
164 },
165 reset ()
166 {
167 bagPanel.hidden = true;
168 bankPanel.hidden = true;
169 bankOpen = false;
170 selected = null;
171 }
172 };
173 }
@@ -0,0 +1,173 @@
1import { itemDefinition, itemAssetPath, EQUIPMENT_SLOT } from "/shared/definitions/items.js";
2
3const EQUIP_LABELS = {
4 [EQUIPMENT_SLOT.head]: "Head",
5 [EQUIPMENT_SLOT.chest]: "Chest",
6 [EQUIPMENT_SLOT.legs]: "Legs",
7 [EQUIPMENT_SLOT.boots]: "Boots",
8 [EQUIPMENT_SLOT.weapon]: "Weapon",
9 [EQUIPMENT_SLOT.offhand]: "Off-hand"
10};
11
12export function initInventory ({ socket, MessageType, game })
13{
14 const bagPanel = document.getElementById("bag-panel");
15 const bagGrid = document.getElementById("bag-grid");
16 const equipGrid = document.getElementById("equip-grid");
17 const coins = document.getElementById("bag-coins");
18 const hint = document.getElementById("bag-hint");
19 const bankPanel = document.getElementById("bank-panel");
20 const vaultGrid = document.getElementById("vault-grid");
21 const vaultCoins = document.getElementById("vault-coins");
22 const inheritGrid = document.getElementById("inherit-grid");
23 const inheritCoins = document.getElementById("inherit-coins");
24 let bag = { inventory: [], equipment: { slots: {} }, currency: 0, vault: [], vaultCurrency: 0 };
25 let selected = null;
26 let bankOpen = false;
27
28 document.getElementById("bag-toggle").addEventListener("click", () =>
29 {
30 bagPanel.hidden = !bagPanel.hidden;
31 });
32 document.getElementById("bag-drop").addEventListener("click", () =>
33 {
34 if (selected == null)
35 { return; }
36 socket.send({ type: MessageType.dropItem, slotIndex: selected });
37 });
38 document.getElementById("bag-equip").addEventListener("click", () =>
39 {
40 if (selected == null)
41 { return; }
42 socket.send({ type: MessageType.equipItem, slotIndex: selected });
43 });
44 document.getElementById("bank-close").addEventListener("click", () =>
45 {
46 bankOpen = false;
47 bankPanel.hidden = true;
48 });
49 document.getElementById("bank-claim").addEventListener("click", () =>
50 {
51 socket.send({ type: MessageType.claimInheritance });
52 });
53
54 function render ()
55 {
56 coins.textContent = `${bag.currency ?? 0} coins`;
57 bagGrid.innerHTML = "";
58 (bag.inventory ?? []).forEach((slot, index) =>
59 {
60 const button = document.createElement("button");
61 button.className = `item-slot${selected === index ? " selected" : ""}`;
62 button.title = tooltip(slot);
63 if (slot)
64 {
65 const def = itemDefinition(slot.itemId);
66 const img = document.createElement("img");
67 img.src = itemAssetPath(slot.itemId);
68 img.alt = def?.displayName ?? "";
69 button.append(img);
70 if (slot.quantity > 1)
71 {
72 const count = document.createElement("span");
73 count.className = "qty";
74 count.textContent = String(slot.quantity);
75 button.append(count);
76 }
77 }
78 button.addEventListener("click", () =>
79 {
80 selected = index;
81 const def = slot ? itemDefinition(slot.itemId) : null;
82 hint.textContent = def ? `${def.displayName}: ${def.description}` : "Empty slot.";
83 render();
84 });
85 bagGrid.append(button);
86 });
87 equipGrid.innerHTML = "";
88 for (const [slot, label] of Object.entries(EQUIP_LABELS))
89 {
90 const worn = bag.equipment?.slots?.[slot];
91 const button = document.createElement("button");
92 button.className = "item-slot";
93 button.title = worn ? tooltip(worn) : label;
94 button.textContent = worn ? (itemDefinition(worn.itemId)?.displayName ?? label) : label;
95 button.addEventListener("click", () =>
96 {
97 if (worn)
98 { socket.send({ type: MessageType.unequipItem, equipSlot: slot }); }
99 });
100 equipGrid.append(button);
101 }
102 }
103
104 function renderVault (grid, slots)
105 {
106 grid.innerHTML = "";
107 (slots ?? []).forEach((slot, index) =>
108 {
109 const button = document.createElement("button");
110 button.className = "item-slot";
111 button.title = tooltip(slot);
112 button.textContent = slot
113 ? `${itemDefinition(slot.itemId)?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`
114 : "";
115 button.addEventListener("click", () =>
116 {
117 if (!slot)
118 { return; }
119 socket.send({ type: MessageType.bankWithdraw, slotIndex: index });
120 });
121 grid.append(button);
122 });
123 }
124
125 function tooltip (slot)
126 {
127 if (!slot)
128 { return ""; }
129 const def = itemDefinition(slot.itemId);
130 return `${def?.displayName ?? "Item"}${slot.quantity > 1 ? ` ×${slot.quantity}` : ""}`;
131 }
132
133 return {
134 isOpen ()
135 {
136 return !bagPanel.hidden || bankOpen;
137 },
138 handleInventory (message)
139 {
140 bag = { ...bag, ...message };
141 render();
142 },
143 handleBank (message)
144 {
145 bankOpen = true;
146 bankPanel.hidden = false;
147 bag.vault = message.vault;
148 bag.vaultCurrency = message.vaultCurrency;
149 vaultCoins.textContent = `${message.vaultCurrency ?? 0} coins in vault · you carry ${message.currency ?? 0}`;
150 inheritCoins.textContent = `${message.inheritance?.currency ?? 0} coins waiting`;
151 renderVault(vaultGrid, message.vault);
152 renderVault(inheritGrid, message.inheritance?.slots ?? []);
153 inheritGrid.querySelectorAll("button").forEach((button) =>
154 {
155 button.onclick = null;
156 });
157 render();
158 },
159 depositSelected ()
160 {
161 if (selected == null)
162 { return; }
163 socket.send({ type: MessageType.bankDeposit, slotIndex: selected });
164 },
165 reset ()
166 {
167 bagPanel.hidden = true;
168 bankPanel.hidden = true;
169 bankOpen = false;
170 selected = null;
171 }
172 };
173}
client/src/play/main.js +76 −11
@@ -1,8 +1,11 @@
1 import { MessageType, GAIT } from "/shared/protocol/constants.js";
1 import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2 import { BlockType } from "/shared/definitions/tiles.js";
2 3 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3 import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4 5 import { WorldView } from "../render/worldView.js";
5 6 import { initSocial } from "./social.js";
7 import { initChat } from "./chat.js";
8 import { initInventory } from "./inventory.js";
6 9
7 10 const game = new Game();
8 11 const hud = document.getElementById("hud");
@@ -19,6 +22,8 @@ let scene = null;
19 22 let gait = GAIT.walk;
20 23 let catalog = { grounds: {}, blocks: {} };
21 24 let social;
25 let chat;
26 let inventory;
22 27
23 28 function showError (message)
24 29 {
@@ -71,7 +76,7 @@ function startPlay (payload)
71 76 const ticker = new GameObject(0, 0, null, 10);
72 77 ticker.update = (dt) =>
73 78 {
74 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking())
79 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking() && !chat?.isBlocking() && !inventory?.isOpen())
75 80 {
76 81 const canvas = scene.canvas;
77 82 const rect = canvas.getBoundingClientRect();
@@ -83,17 +88,27 @@ function startPlay (payload)
83 88 else
84 89 {
85 90 const tile = view.screenToTile(mouseX, mouseY);
86 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
91 const local = view.entities.get(view.localEntityId);
92 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
93 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
94 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
95 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
96 { socket.send({ type: MessageType.openBank }); }
97 else
98 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
87 99 }
88 100 }
89 if (GameInput.isPressed(82))
101 if (GameInput.isPressed(82) && !chat?.isOpen())
90 102 {
91 103 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
92 104 socket.send({ type: MessageType.setGait, gait });
93 105 document.getElementById("gait").textContent = gait;
94 106 }
95 107 if (playing)
96 { social?.updateNametag(view, scene, view.localEntityId); }
108 {
109 social?.updateNametag(view, scene, view.localEntityId);
110 chat?.update(view, scene);
111 }
97 112 view.update(dt);
98 113 };
99 114 scene.addObject(ticker);
@@ -105,13 +120,14 @@ function startPlay (payload)
105 120 });
106 121 window.addEventListener("wheel", (event) =>
107 122 {
108 if (!playing)
123 if (!playing || chat?.isOpen())
109 124 { return; }
110 125 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
111 126 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
112 127 }, { passive: true });
113 128 }
114 view.settings = payload.settings ?? view.settings;
129 view.setSettings(payload.settings ?? view.settings);
130 chat?.syncSettings();
115 131 view.worldHour = payload.worldTime?.hour ?? 12;
116 132 view.setLocalEntity(
117 133 payload.entityId,
@@ -121,16 +137,24 @@ function startPlay (payload)
121 137 payload.sex,
122 138 payload.firstName,
123 139 payload.lastName,
124 payload.characterId
140 payload.characterId,
141 payload.layers
125 142 );
126 143 }
127 144
128 145 async function main ()
129 146 {
130 147 catalog = await loadSpriteCatalog();
131 await game.preloadImages(playImagesFromCatalog(catalog));
148 await preloadCatalogImages(game, catalog);
132 149 applySpriteSheets(game.images, catalog);
133 150 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
151 inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
152 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
153 chat = initChat({
154 socket: { send (payload) { socket.send(payload); } },
155 MessageType,
156 getSettings: () => view?.settings
157 });
134 158 game.startGame();
135 159
136 160 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -156,19 +180,41 @@ async function main ()
156 180 case MessageType.unsubscribeChunk:
157 181 view?.removeChunk(message.chunkX, message.chunkY);
158 182 break;
183 case MessageType.entitySpawn:
184 view?.spawnEntity(message);
185 break;
159 186 case MessageType.entityMove:
160 187 view?.moveEntity(message);
161 188 break;
162 189 case MessageType.entityDespawn:
163 190 view?.despawnEntity(message.entityId);
164 191 break;
192 case MessageType.entityAppearance:
193 view?.setAppearance(message);
194 break;
195 case MessageType.groundItemAppear:
196 view?.upsertGroundItem(message);
197 break;
198 case MessageType.groundItemDespawn:
199 view?.despawnGroundItem(message.groundItemId);
200 break;
201 case MessageType.inventory:
202 inventory?.handleInventory(message);
203 break;
204 case MessageType.bankSnapshot:
205 inventory?.handleBank(message);
206 break;
165 207 case MessageType.worldStatus:
166 208 if (view)
167 209 {
168 view.settings = message.settings ?? view.settings;
210 view.setSettings(message.settings ?? view.settings);
169 211 view.worldHour = message.worldTime?.hour ?? view.worldHour;
212 chat?.syncSettings();
170 213 }
171 214 break;
215 case MessageType.chatBubble:
216 chat?.showBubble(message);
217 break;
172 218 case MessageType.friends:
173 219 social?.handleFriends(message);
174 220 break;
@@ -198,6 +244,8 @@ document.getElementById("leave").addEventListener("click", () =>
198 244 socket.send({ type: MessageType.leaveWorld });
199 245 playing = false;
200 246 social?.reset();
247 chat?.reset();
248 inventory?.reset();
201 249 overlay.hidden = false;
202 250 hud.hidden = true;
203 251 });
@@ -207,3 +255,20 @@ main().catch((error) =>
207 255 showError(error.message);
208 256 console.error(error);
209 257 });
258
259 function isBankTile (view, tileX, tileY)
260 {
261 const chunkX = Math.floor(tileX / CHUNK_SIZE);
262 const chunkY = Math.floor(tileY / CHUNK_SIZE);
263 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
264 if (!snapshot)
265 { return false; }
266 const localX = tileX - chunkX * CHUNK_SIZE;
267 const localY = tileY - chunkY * CHUNK_SIZE;
268 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank;
269 }
270
271 function chebyshev (ax, ay, bx, by)
272 {
273 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
274 }
@@ -1,8 +1,11 @@
1import { MessageType, GAIT } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { BlockType } from "/shared/definitions/tiles.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { WorldView } from "../render/worldView.js";
5import { WorldView } from "../render/worldView.js";
5import { initSocial } from "./social.js";
6import { initSocial } from "./social.js";
7import { initChat } from "./chat.js";
8import { initInventory } from "./inventory.js";
6
9
7const game = new Game();
10const game = new Game();
8const hud = document.getElementById("hud");
11const hud = document.getElementById("hud");
@@ -19,6 +22,8 @@ let scene = null;
19let gait = GAIT.walk;
22let gait = GAIT.walk;
20let catalog = { grounds: {}, blocks: {} };
23let catalog = { grounds: {}, blocks: {} };
21let social;
24let social;
25let chat;
26let inventory;
22
27
23function showError (message)
28function showError (message)
24{
29{
@@ -71,7 +76,7 @@ function startPlay (payload)
71 const ticker = new GameObject(0, 0, null, 10);
76 const ticker = new GameObject(0, 0, null, 10);
72 ticker.update = (dt) =>
77 ticker.update = (dt) =>
73 {
78 {
74 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking())
79 if (GameInput.mousePressed(GameInput.MouseButtons.Left) && playing && !social?.isBlocking() && !chat?.isBlocking() && !inventory?.isOpen())
75 {
80 {
76 const canvas = scene.canvas;
81 const canvas = scene.canvas;
77 const rect = canvas.getBoundingClientRect();
82 const rect = canvas.getBoundingClientRect();
@@ -83,17 +88,27 @@ function startPlay (payload)
83 else
88 else
84 {
89 {
85 const tile = view.screenToTile(mouseX, mouseY);
90 const tile = view.screenToTile(mouseX, mouseY);
86 socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY });
91 const local = view.entities.get(view.localEntityId);
92 const ground = view.groundItemAtTile(tile.tileX, tile.tileY);
93 if (ground && local && local.tileX === ground.tileX && local.tileY === ground.tileY)
94 { socket.send({ type: MessageType.pickupItem, groundItemId: ground.groundItemId }); }
95 else if (isBankTile(view, tile.tileX, tile.tileY) && local && chebyshev(local.tileX, local.tileY, tile.tileX, tile.tileY) <= 1)
96 { socket.send({ type: MessageType.openBank }); }
97 else
98 { socket.send({ type: MessageType.moveTo, tileX: tile.tileX, tileY: tile.tileY }); }
87 }
99 }
88 }
100 }
89 if (GameInput.isPressed(82))
101 if (GameInput.isPressed(82) && !chat?.isOpen())
90 {
102 {
91 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
103 gait = gait === GAIT.run ? GAIT.walk : GAIT.run;
92 socket.send({ type: MessageType.setGait, gait });
104 socket.send({ type: MessageType.setGait, gait });
93 document.getElementById("gait").textContent = gait;
105 document.getElementById("gait").textContent = gait;
94 }
106 }
95 if (playing)
107 if (playing)
96 { social?.updateNametag(view, scene, view.localEntityId); }
108 {
109 social?.updateNametag(view, scene, view.localEntityId);
110 chat?.update(view, scene);
111 }
97 view.update(dt);
112 view.update(dt);
98 };
113 };
99 scene.addObject(ticker);
114 scene.addObject(ticker);
@@ -105,13 +120,14 @@ function startPlay (payload)
105 });
120 });
106 window.addEventListener("wheel", (event) =>
121 window.addEventListener("wheel", (event) =>
107 {
122 {
108 if (!playing)
123 if (!playing || chat?.isOpen())
109 { return; }
124 { return; }
110 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
125 view.setZoom(view.zoom + (event.deltaY < 0 ? 0.25 : -0.25));
111 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
126 document.getElementById("zoom").textContent = `${view.zoom.toFixed(2)}×`;
112 }, { passive: true });
127 }, { passive: true });
113 }
128 }
114 view.settings = payload.settings ?? view.settings;
129 view.setSettings(payload.settings ?? view.settings);
130 chat?.syncSettings();
115 view.worldHour = payload.worldTime?.hour ?? 12;
131 view.worldHour = payload.worldTime?.hour ?? 12;
116 view.setLocalEntity(
132 view.setLocalEntity(
117 payload.entityId,
133 payload.entityId,
@@ -121,16 +137,24 @@ function startPlay (payload)
121 payload.sex,
137 payload.sex,
122 payload.firstName,
138 payload.firstName,
123 payload.lastName,
139 payload.lastName,
124 payload.characterId
140 payload.characterId,
141 payload.layers
125 );
142 );
126}
143}
127
144
128async function main ()
145async function main ()
129{
146{
130 catalog = await loadSpriteCatalog();
147 catalog = await loadSpriteCatalog();
131 await game.preloadImages(playImagesFromCatalog(catalog));
148 await preloadCatalogImages(game, catalog);
132 applySpriteSheets(game.images, catalog);
149 applySpriteSheets(game.images, catalog);
133 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
150 social = initSocial({ socket: { send (payload) { socket.send(payload); } }, MessageType });
151 inventory = initInventory({ socket: { send (payload) { socket.send(payload); } }, MessageType, game });
152 document.getElementById("bag-bank").addEventListener("click", () => inventory.depositSelected());
153 chat = initChat({
154 socket: { send (payload) { socket.send(payload); } },
155 MessageType,
156 getSettings: () => view?.settings
157 });
134 game.startGame();
158 game.startGame();
135
159
136 socket = new GameSocket(defaultSocketUrl(), (message) =>
160 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -156,19 +180,41 @@ async function main ()
156 case MessageType.unsubscribeChunk:
180 case MessageType.unsubscribeChunk:
157 view?.removeChunk(message.chunkX, message.chunkY);
181 view?.removeChunk(message.chunkX, message.chunkY);
158 break;
182 break;
183 case MessageType.entitySpawn:
184 view?.spawnEntity(message);
185 break;
159 case MessageType.entityMove:
186 case MessageType.entityMove:
160 view?.moveEntity(message);
187 view?.moveEntity(message);
161 break;
188 break;
162 case MessageType.entityDespawn:
189 case MessageType.entityDespawn:
163 view?.despawnEntity(message.entityId);
190 view?.despawnEntity(message.entityId);
164 break;
191 break;
192 case MessageType.entityAppearance:
193 view?.setAppearance(message);
194 break;
195 case MessageType.groundItemAppear:
196 view?.upsertGroundItem(message);
197 break;
198 case MessageType.groundItemDespawn:
199 view?.despawnGroundItem(message.groundItemId);
200 break;
201 case MessageType.inventory:
202 inventory?.handleInventory(message);
203 break;
204 case MessageType.bankSnapshot:
205 inventory?.handleBank(message);
206 break;
165 case MessageType.worldStatus:
207 case MessageType.worldStatus:
166 if (view)
208 if (view)
167 {
209 {
168 view.settings = message.settings ?? view.settings;
210 view.setSettings(message.settings ?? view.settings);
169 view.worldHour = message.worldTime?.hour ?? view.worldHour;
211 view.worldHour = message.worldTime?.hour ?? view.worldHour;
212 chat?.syncSettings();
170 }
213 }
171 break;
214 break;
215 case MessageType.chatBubble:
216 chat?.showBubble(message);
217 break;
172 case MessageType.friends:
218 case MessageType.friends:
173 social?.handleFriends(message);
219 social?.handleFriends(message);
174 break;
220 break;
@@ -198,6 +244,8 @@ document.getElementById("leave").addEventListener("click", () =>
198 socket.send({ type: MessageType.leaveWorld });
244 socket.send({ type: MessageType.leaveWorld });
199 playing = false;
245 playing = false;
200 social?.reset();
246 social?.reset();
247 chat?.reset();
248 inventory?.reset();
201 overlay.hidden = false;
249 overlay.hidden = false;
202 hud.hidden = true;
250 hud.hidden = true;
203});
251});
@@ -207,3 +255,20 @@ main().catch((error) =>
207 showError(error.message);
255 showError(error.message);
208 console.error(error);
256 console.error(error);
209});
257});
258
259function isBankTile (view, tileX, tileY)
260{
261 const chunkX = Math.floor(tileX / CHUNK_SIZE);
262 const chunkY = Math.floor(tileY / CHUNK_SIZE);
263 const snapshot = view.chunks.get(`${chunkX},${chunkY}`);
264 if (!snapshot)
265 { return false; }
266 const localX = tileX - chunkX * CHUNK_SIZE;
267 const localY = tileY - chunkY * CHUNK_SIZE;
268 return snapshot.blocks[localY * CHUNK_SIZE + localX]?.typeId === BlockType.bank;
269}
270
271function chebyshev (ax, ay, bx, by)
272{
273 return Math.max(Math.abs(ax - bx), Math.abs(ay - by));
274}
client/src/render/sprites.js +43 −2
@@ -1,8 +1,6 @@
1 1 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 2
3 3 export const UTILITY_IMAGES = [
4 { name: "player-body-male", url: "/assets/characters/player-body-male.png" },
5 { name: "player-body-female", url: "/assets/characters/player-body-female.png" },
6 4 { name: "night-shade", url: shadeDataUrl("#000000") },
7 5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
8 6 ];
@@ -20,6 +18,49 @@ export async function loadSpriteCatalog ()
20 18 return response.json();
21 19 }
22 20
21 /**
22 * Load catalog images without aborting the whole client when one file is missing.
23 * Failed entries are logged and omitted from `game.images`.
24 */
25 export async function preloadCatalogImages (game, catalog)
26 {
27 const failed = [];
28 await Promise.all(playImagesFromCatalog(catalog).map((imageData) => loadOneImage(game, imageData).catch((error) =>
29 {
30 console.error(error.message ?? error);
31 failed.push({ name: imageData.name, url: imageData.url });
32 })));
33 if (failed.length)
34 { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); }
35 return failed;
36 }
37
38 function loadOneImage (game, imageData)
39 {
40 return new Promise((resolve, reject) =>
41 {
42 const img = new Image();
43 img.onload = () =>
44 {
45 const finalImage = new image(
46 img,
47 imageData.subImgTotal,
48 imageData.perRow,
49 imageData.loop,
50 imageData.chain
51 );
52 finalImage.name = imageData.name;
53 game.images[imageData.name] = finalImage;
54 resolve(finalImage);
55 };
56 img.onerror = () =>
57 {
58 reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`));
59 };
60 img.src = imageData.url;
61 });
62 }
63
23 64 export function applySpriteSheets (images, catalog)
24 65 {
25 66 for (const entry of catalog?.images ?? [])
@@ -1,8 +1,6 @@
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
2
3export const UTILITY_IMAGES = [
3export const UTILITY_IMAGES = [
4 { name: "player-body-male", url: "/assets/characters/player-body-male.png" },
5 { name: "player-body-female", url: "/assets/characters/player-body-female.png" },
6 { name: "night-shade", url: shadeDataUrl("#000000") },
4 { name: "night-shade", url: shadeDataUrl("#000000") },
7 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
8];
6];
@@ -20,6 +18,49 @@ export async function loadSpriteCatalog ()
20 return response.json();
18 return response.json();
21}
19}
22
20
21/**
22 * Load catalog images without aborting the whole client when one file is missing.
23 * Failed entries are logged and omitted from `game.images`.
24 */
25export async function preloadCatalogImages (game, catalog)
26{
27 const failed = [];
28 await Promise.all(playImagesFromCatalog(catalog).map((imageData) => loadOneImage(game, imageData).catch((error) =>
29 {
30 console.error(error.message ?? error);
31 failed.push({ name: imageData.name, url: imageData.url });
32 })));
33 if (failed.length)
34 { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); }
35 return failed;
36}
37
38function loadOneImage (game, imageData)
39{
40 return new Promise((resolve, reject) =>
41 {
42 const img = new Image();
43 img.onload = () =>
44 {
45 const finalImage = new image(
46 img,
47 imageData.subImgTotal,
48 imageData.perRow,
49 imageData.loop,
50 imageData.chain
51 );
52 finalImage.name = imageData.name;
53 game.images[imageData.name] = finalImage;
54 resolve(finalImage);
55 };
56 img.onerror = () =>
57 {
58 reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`));
59 };
60 img.src = imageData.url;
61 });
62}
63
23export function applySpriteSheets (images, catalog)
64export function applySpriteSheets (images, catalog)
24{
65{
25 for (const entry of catalog?.images ?? [])
66 for (const entry of catalog?.images ?? [])
client/src/render/worldView.js +206 −5
@@ -1,6 +1,7 @@
1 1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2 2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 import { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3 import { bloomCompanionName, bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4 import { itemSpriteName } from "/shared/definitions/items.js";
4 5 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5 6
6 7 const LAYER_GROUND = 0;
@@ -8,6 +9,7 @@ const LAYER_SHADE = 500000;
8 9 const LAYER_EDGE = 900000;
9 10 const SORT_BLOCK = 1;
10 11 const SORT_ENTITY = 2;
12 const RENDER_LAYER_BLOOM = "bloom";
11 13
12 14 export class WorldView
13 15 {
@@ -21,15 +23,23 @@ export class WorldView
21 23 this.chunks = new Map();
22 24 this.tiles = new Map();
23 25 this.entities = new Map();
26 this.groundItems = new Map();
24 27 this.edges = new Map();
25 28 this.localEntityId = null;
26 29 this.settings = { ...DEFAULT_WORLD_SETTINGS };
27 30 this.worldHour = 12;
28 31 this.nightPreview = null;
29 32 this.followPlayer = true;
33 this.#syncBloomLayer();
30 34 }
31 35
32 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null)
36 setSettings (settings)
37 {
38 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
39 this.#syncBloomLayer();
40 }
41
42 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
33 43 {
34 44 this.localEntityId = entityId;
35 45 this.#upsertEntity({
@@ -40,7 +50,8 @@ export class WorldView
40 50 gait,
41 51 sex,
42 52 firstName,
43 lastName
53 lastName,
54 layers: layers ?? undefined
44 55 });
45 56 }
46 57
@@ -52,6 +63,14 @@ export class WorldView
52 63 this.#redrawPreview();
53 64 for (const entity of snapshot.entities ?? [])
54 65 { this.#upsertEntity(entity); }
66 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
67 for (const [id, item] of [...this.groundItems.entries()])
68 {
69 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
70 { this.despawnGroundItem(id); }
71 }
72 for (const item of snapshot.groundItems ?? [])
73 { this.upsertGroundItem(item); }
55 74 this.#rebuildAllEdges();
56 75 }
57 76
@@ -65,11 +84,18 @@ export class WorldView
65 84 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
66 85 {
67 86 objects.ground?.destroy();
87 objects.groundBloom?.destroy();
68 88 objects.block?.destroy();
89 objects.blockBloom?.destroy();
69 90 objects.shade?.destroy();
70 91 this.tiles.delete(tileKey);
71 92 }
72 93 }
94 for (const [id, item] of [...this.groundItems.entries()])
95 {
96 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
97 { this.despawnGroundItem(id); }
98 }
73 99 this.#rebuildAllEdges();
74 100 }
75 101
@@ -82,6 +108,11 @@ export class WorldView
82 108 this.#rebuildAllEdges();
83 109 }
84 110
111 spawnEntity (payload)
112 {
113 this.#upsertEntity(payload);
114 }
115
85 116 moveEntity (payload)
86 117 {
87 118 const existing = this.entities.get(payload.entityId);
@@ -105,9 +136,63 @@ export class WorldView
105 136 if (!existing)
106 137 { return; }
107 138 existing.object?.destroy();
139 for (const overlay of existing.overlays ?? [])
140 { overlay.destroy(); }
141 for (const overlay of existing.bloomOverlays ?? [])
142 { overlay.destroy(); }
108 143 this.entities.delete(entityId);
109 144 }
110 145
146 setAppearance (payload)
147 {
148 const existing = this.entities.get(payload.entityId);
149 if (!existing)
150 { return; }
151 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
152 this.#placeEntity(existing);
153 }
154
155 upsertGroundItem (payload)
156 {
157 const size = this.tileSize();
158 const pivot = tilePivot(payload.tileX, payload.tileY, size);
159 let item = this.groundItems.get(payload.groundItemId);
160 if (!item)
161 {
162 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
163 this.scene.addObject(object);
164 item = { object };
165 this.groundItems.set(payload.groundItemId, item);
166 }
167 item.groundItemId = payload.groundItemId;
168 item.tileX = payload.tileX;
169 item.tileY = payload.tileY;
170 item.itemId = payload.itemId;
171 item.quantity = payload.quantity;
172 item.displayName = payload.displayName;
173 item.sprite = payload.sprite;
174 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
175 }
176
177 despawnGroundItem (groundItemId)
178 {
179 const item = this.groundItems.get(groundItemId);
180 if (!item)
181 { return; }
182 item.object?.destroy();
183 this.groundItems.delete(groundItemId);
184 }
185
186 groundItemAtTile (tileX, tileY)
187 {
188 for (const item of this.groundItems.values())
189 {
190 if (item.tileX === tileX && item.tileY === tileY)
191 { return item; }
192 }
193 return null;
194 }
195
111 196 setZoom (zoom, limits = { min: 1, max: 4 })
112 197 {
113 198 const min = limits.min ?? 1;
@@ -125,6 +210,11 @@ export class WorldView
125 210 entity.lerpStarted = null;
126 211 this.#placeEntity(entity);
127 212 }
213 for (const item of this.groundItems.values())
214 {
215 const pivot = tilePivot(item.tileX, item.tileY, size);
216 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
217 }
128 218 this.#rebuildAllEdges();
129 219 this.#redrawPreview();
130 220 }
@@ -275,10 +365,12 @@ export class WorldView
275 365 let entity = this.entities.get(payload.entityId);
276 366 if (!entity)
277 367 {
278 const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male";
368 const spriteName = payload.layers?.[0]?.sprite
369 ?? payload.sprite
370 ?? bodySpriteName(payload.sex);
279 371 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
280 372 this.scene.addObject(object);
281 entity = { object, visualX: pivot.x, visualY: pivot.y };
373 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
282 374 this.entities.set(payload.entityId, entity);
283 375 }
284 376 entity.entityId = payload.entityId;
@@ -297,12 +389,49 @@ export class WorldView
297 389 entity.visualY = pivot.y;
298 390 entity.fromX = pivot.x;
299 391 entity.fromY = pivot.y;
392 if (payload.layers)
393 { this.#applyLayers(entity, payload.layers); }
300 394 this.#placeEntity(entity);
301 395 }
302 396
397 #applyLayers (entity, layers)
398 {
399 const base = layers[0]?.sprite
400 ?? bodySpriteName(entity.sex);
401 if (this.game.images[base])
402 { entity.object.renderer.sprite = this.game.images[base]; }
403 for (const overlay of entity.overlays ?? [])
404 { overlay.destroy(); }
405 for (const overlay of entity.bloomOverlays ?? [])
406 { overlay.destroy(); }
407 entity.overlays = [];
408 entity.bloomOverlays = [];
409 for (const layer of layers.slice(1))
410 {
411 const image = this.game.images[layer.sprite];
412 if (!image)
413 { continue; }
414 const object = new GameObject(0, 0, image, SORT_ENTITY);
415 this.scene.addObject(object);
416 entity.overlays.push(object);
417 const bloomName = bloomCompanionName(layer.sprite);
418 const bloomImage = this.game.images[bloomName];
419 if (!bloomImage)
420 { continue; }
421 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
422 bloom.renderer.layer = RENDER_LAYER_BLOOM;
423 this.scene.addObject(bloom);
424 entity.bloomOverlays.push(bloom);
425 }
426 }
427
303 428 #placeEntity (entity)
304 429 {
305 430 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
431 for (const overlay of entity.overlays ?? [])
432 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
433 for (const overlay of entity.bloomOverlays ?? [])
434 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
306 435 }
307 436
308 437 #rebuildChunk (snapshot)
@@ -358,6 +487,7 @@ export class WorldView
358 487 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
359 488 objects.ground.layer = LAYER_GROUND;
360 489 }
490 objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, this.#groundBloomName(ground), pivot);
361 491
362 492 const blockName = this.#blockSpriteName(block);
363 493 if (blockName)
@@ -371,6 +501,7 @@ export class WorldView
371 501 objects.block.destroy();
372 502 objects.block = null;
373 503 }
504 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, this.#blockBloomName(block), pivot);
374 505
375 506 objects.light = snapshot.light[index] ?? 0;
376 507 const previousShade = objects.shade;
@@ -401,6 +532,47 @@ export class WorldView
401 532 return spriteImageName("block", def.key, state);
402 533 }
403 534
535 #groundBloomName (ground)
536 {
537 const entry = normalizeGround(ground);
538 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
539 const type = this.catalog.grounds?.[def.key];
540 const state = resolveState(type?.states ?? [], entry.state);
541 if (!state || !type?.blooms?.[state])
542 { return null; }
543 return bloomImageName("ground", def.key, state);
544 }
545
546 #blockBloomName (block)
547 {
548 const entry = normalizeBlock(block);
549 if (!entry)
550 { return null; }
551 const def = BLOCK_DEFINITIONS[entry.typeId];
552 if (!def)
553 { return null; }
554 const type = this.catalog.blocks?.[def.key];
555 const state = resolveState(type?.states ?? [], entry.state);
556 if (!state || !type?.blooms?.[state])
557 { return null; }
558 return bloomImageName("block", def.key, state);
559 }
560
561 #placeBloomOverlay (existing, name, pivot)
562 {
563 if (!name)
564 {
565 existing?.destroy();
566 return null;
567 }
568 const object = this.#ensureSprite(existing, name, SORT_BLOCK);
569 if (!object)
570 { return null; }
571 object.renderer.layer = RENDER_LAYER_BLOOM;
572 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
573 return object;
574 }
575
404 576 #tileFill (existing, name, x, y, layer)
405 577 {
406 578 existing = this.#ensureSprite(existing, name, layer);
@@ -552,6 +724,29 @@ export class WorldView
552 724 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
553 725 }
554 726 }
727
728 #syncBloomLayer ()
729 {
730 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
731 this.scene.setLayers([
732 { name: "default" },
733 {
734 name: RENDER_LAYER_BLOOM,
735 composite: "add",
736 postShaders: Shader.getBloomPostChain({
737 threshold: settings.bloomThreshold,
738 softKnee: settings.bloomSoftKnee,
739 intensity: settings.bloomIntensity,
740 blurSize: settings.bloomBlurSize,
741 saturation: settings.bloomSaturation,
742 colorPreserve: settings.bloomColorPreserve,
743 dilate: settings.bloomDilate,
744 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
745 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
746 })
747 }
748 ]);
749 }
555 750 }
556 751
557 752 export function nightFactor (hour, nightDarkness = 0.72)
@@ -566,6 +761,12 @@ export function nightFactor (hour, nightDarkness = 0.72)
566 761 return lerp(0, peak, (hour - 16) / 6);
567 762 }
568 763
764 function bodySpriteName (sex)
765 {
766 const key = sex === "female" ? "player-body-female" : "player-body-male";
767 return spriteImageName("character", key, key);
768 }
769
569 770 function lerp (a, b, t)
570 771 {
571 772 return a + (b - a) * Math.min(1, Math.max(0, t));
@@ -1,6 +1,7 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { bloomCompanionName, bloomImageName, resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
4import { itemSpriteName } from "/shared/definitions/items.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
5
6
6const LAYER_GROUND = 0;
7const LAYER_GROUND = 0;
@@ -8,6 +9,7 @@ const LAYER_SHADE = 500000;
8const LAYER_EDGE = 900000;
9const LAYER_EDGE = 900000;
9const SORT_BLOCK = 1;
10const SORT_BLOCK = 1;
10const SORT_ENTITY = 2;
11const SORT_ENTITY = 2;
12const RENDER_LAYER_BLOOM = "bloom";
11
13
12export class WorldView
14export class WorldView
13{
15{
@@ -21,15 +23,23 @@ export class WorldView
21 this.chunks = new Map();
23 this.chunks = new Map();
22 this.tiles = new Map();
24 this.tiles = new Map();
23 this.entities = new Map();
25 this.entities = new Map();
26 this.groundItems = new Map();
24 this.edges = new Map();
27 this.edges = new Map();
25 this.localEntityId = null;
28 this.localEntityId = null;
26 this.settings = { ...DEFAULT_WORLD_SETTINGS };
29 this.settings = { ...DEFAULT_WORLD_SETTINGS };
27 this.worldHour = 12;
30 this.worldHour = 12;
28 this.nightPreview = null;
31 this.nightPreview = null;
29 this.followPlayer = true;
32 this.followPlayer = true;
33 this.#syncBloomLayer();
30 }
34 }
31
35
32 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null)
36 setSettings (settings)
37 {
38 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
39 this.#syncBloomLayer();
40 }
41
42 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
33 {
43 {
34 this.localEntityId = entityId;
44 this.localEntityId = entityId;
35 this.#upsertEntity({
45 this.#upsertEntity({
@@ -40,7 +50,8 @@ export class WorldView
40 gait,
50 gait,
41 sex,
51 sex,
42 firstName,
52 firstName,
43 lastName
53 lastName,
54 layers: layers ?? undefined
44 });
55 });
45 }
56 }
46
57
@@ -52,6 +63,14 @@ export class WorldView
52 this.#redrawPreview();
63 this.#redrawPreview();
53 for (const entity of snapshot.entities ?? [])
64 for (const entity of snapshot.entities ?? [])
54 { this.#upsertEntity(entity); }
65 { this.#upsertEntity(entity); }
66 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
67 for (const [id, item] of [...this.groundItems.entries()])
68 {
69 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
70 { this.despawnGroundItem(id); }
71 }
72 for (const item of snapshot.groundItems ?? [])
73 { this.upsertGroundItem(item); }
55 this.#rebuildAllEdges();
74 this.#rebuildAllEdges();
56 }
75 }
57
76
@@ -65,11 +84,18 @@ export class WorldView
65 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
84 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
66 {
85 {
67 objects.ground?.destroy();
86 objects.ground?.destroy();
87 objects.groundBloom?.destroy();
68 objects.block?.destroy();
88 objects.block?.destroy();
89 objects.blockBloom?.destroy();
69 objects.shade?.destroy();
90 objects.shade?.destroy();
70 this.tiles.delete(tileKey);
91 this.tiles.delete(tileKey);
71 }
92 }
72 }
93 }
94 for (const [id, item] of [...this.groundItems.entries()])
95 {
96 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
97 { this.despawnGroundItem(id); }
98 }
73 this.#rebuildAllEdges();
99 this.#rebuildAllEdges();
74 }
100 }
75
101
@@ -82,6 +108,11 @@ export class WorldView
82 this.#rebuildAllEdges();
108 this.#rebuildAllEdges();
83 }
109 }
84
110
111 spawnEntity (payload)
112 {
113 this.#upsertEntity(payload);
114 }
115
85 moveEntity (payload)
116 moveEntity (payload)
86 {
117 {
87 const existing = this.entities.get(payload.entityId);
118 const existing = this.entities.get(payload.entityId);
@@ -105,9 +136,63 @@ export class WorldView
105 if (!existing)
136 if (!existing)
106 { return; }
137 { return; }
107 existing.object?.destroy();
138 existing.object?.destroy();
139 for (const overlay of existing.overlays ?? [])
140 { overlay.destroy(); }
141 for (const overlay of existing.bloomOverlays ?? [])
142 { overlay.destroy(); }
108 this.entities.delete(entityId);
143 this.entities.delete(entityId);
109 }
144 }
110
145
146 setAppearance (payload)
147 {
148 const existing = this.entities.get(payload.entityId);
149 if (!existing)
150 { return; }
151 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
152 this.#placeEntity(existing);
153 }
154
155 upsertGroundItem (payload)
156 {
157 const size = this.tileSize();
158 const pivot = tilePivot(payload.tileX, payload.tileY, size);
159 let item = this.groundItems.get(payload.groundItemId);
160 if (!item)
161 {
162 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
163 this.scene.addObject(object);
164 item = { object };
165 this.groundItems.set(payload.groundItemId, item);
166 }
167 item.groundItemId = payload.groundItemId;
168 item.tileX = payload.tileX;
169 item.tileY = payload.tileY;
170 item.itemId = payload.itemId;
171 item.quantity = payload.quantity;
172 item.displayName = payload.displayName;
173 item.sprite = payload.sprite;
174 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
175 }
176
177 despawnGroundItem (groundItemId)
178 {
179 const item = this.groundItems.get(groundItemId);
180 if (!item)
181 { return; }
182 item.object?.destroy();
183 this.groundItems.delete(groundItemId);
184 }
185
186 groundItemAtTile (tileX, tileY)
187 {
188 for (const item of this.groundItems.values())
189 {
190 if (item.tileX === tileX && item.tileY === tileY)
191 { return item; }
192 }
193 return null;
194 }
195
111 setZoom (zoom, limits = { min: 1, max: 4 })
196 setZoom (zoom, limits = { min: 1, max: 4 })
112 {
197 {
113 const min = limits.min ?? 1;
198 const min = limits.min ?? 1;
@@ -125,6 +210,11 @@ export class WorldView
125 entity.lerpStarted = null;
210 entity.lerpStarted = null;
126 this.#placeEntity(entity);
211 this.#placeEntity(entity);
127 }
212 }
213 for (const item of this.groundItems.values())
214 {
215 const pivot = tilePivot(item.tileX, item.tileY, size);
216 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
217 }
128 this.#rebuildAllEdges();
218 this.#rebuildAllEdges();
129 this.#redrawPreview();
219 this.#redrawPreview();
130 }
220 }
@@ -275,10 +365,12 @@ export class WorldView
275 let entity = this.entities.get(payload.entityId);
365 let entity = this.entities.get(payload.entityId);
276 if (!entity)
366 if (!entity)
277 {
367 {
278 const spriteName = payload.sex === "female" ? "player-body-female" : "player-body-male";
368 const spriteName = payload.layers?.[0]?.sprite
369 ?? payload.sprite
370 ?? bodySpriteName(payload.sex);
279 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
371 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
280 this.scene.addObject(object);
372 this.scene.addObject(object);
281 entity = { object, visualX: pivot.x, visualY: pivot.y };
373 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
282 this.entities.set(payload.entityId, entity);
374 this.entities.set(payload.entityId, entity);
283 }
375 }
284 entity.entityId = payload.entityId;
376 entity.entityId = payload.entityId;
@@ -297,12 +389,49 @@ export class WorldView
297 entity.visualY = pivot.y;
389 entity.visualY = pivot.y;
298 entity.fromX = pivot.x;
390 entity.fromX = pivot.x;
299 entity.fromY = pivot.y;
391 entity.fromY = pivot.y;
392 if (payload.layers)
393 { this.#applyLayers(entity, payload.layers); }
300 this.#placeEntity(entity);
394 this.#placeEntity(entity);
301 }
395 }
302
396
397 #applyLayers (entity, layers)
398 {
399 const base = layers[0]?.sprite
400 ?? bodySpriteName(entity.sex);
401 if (this.game.images[base])
402 { entity.object.renderer.sprite = this.game.images[base]; }
403 for (const overlay of entity.overlays ?? [])
404 { overlay.destroy(); }
405 for (const overlay of entity.bloomOverlays ?? [])
406 { overlay.destroy(); }
407 entity.overlays = [];
408 entity.bloomOverlays = [];
409 for (const layer of layers.slice(1))
410 {
411 const image = this.game.images[layer.sprite];
412 if (!image)
413 { continue; }
414 const object = new GameObject(0, 0, image, SORT_ENTITY);
415 this.scene.addObject(object);
416 entity.overlays.push(object);
417 const bloomName = bloomCompanionName(layer.sprite);
418 const bloomImage = this.game.images[bloomName];
419 if (!bloomImage)
420 { continue; }
421 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
422 bloom.renderer.layer = RENDER_LAYER_BLOOM;
423 this.scene.addObject(bloom);
424 entity.bloomOverlays.push(bloom);
425 }
426 }
427
303 #placeEntity (entity)
428 #placeEntity (entity)
304 {
429 {
305 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
430 this.#placePivoted(entity.object, entity.visualX, entity.visualY, entity.visualY, SORT_ENTITY);
431 for (const overlay of entity.overlays ?? [])
432 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.001, SORT_ENTITY); }
433 for (const overlay of entity.bloomOverlays ?? [])
434 { this.#placePivoted(overlay, entity.visualX, entity.visualY, entity.visualY + 0.002, SORT_ENTITY); }
306 }
435 }
307
436
308 #rebuildChunk (snapshot)
437 #rebuildChunk (snapshot)
@@ -358,6 +487,7 @@ export class WorldView
358 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
487 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
359 objects.ground.layer = LAYER_GROUND;
488 objects.ground.layer = LAYER_GROUND;
360 }
489 }
490 objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, this.#groundBloomName(ground), pivot);
361
491
362 const blockName = this.#blockSpriteName(block);
492 const blockName = this.#blockSpriteName(block);
363 if (blockName)
493 if (blockName)
@@ -371,6 +501,7 @@ export class WorldView
371 objects.block.destroy();
501 objects.block.destroy();
372 objects.block = null;
502 objects.block = null;
373 }
503 }
504 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, this.#blockBloomName(block), pivot);
374
505
375 objects.light = snapshot.light[index] ?? 0;
506 objects.light = snapshot.light[index] ?? 0;
376 const previousShade = objects.shade;
507 const previousShade = objects.shade;
@@ -401,6 +532,47 @@ export class WorldView
401 return spriteImageName("block", def.key, state);
532 return spriteImageName("block", def.key, state);
402 }
533 }
403
534
535 #groundBloomName (ground)
536 {
537 const entry = normalizeGround(ground);
538 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
539 const type = this.catalog.grounds?.[def.key];
540 const state = resolveState(type?.states ?? [], entry.state);
541 if (!state || !type?.blooms?.[state])
542 { return null; }
543 return bloomImageName("ground", def.key, state);
544 }
545
546 #blockBloomName (block)
547 {
548 const entry = normalizeBlock(block);
549 if (!entry)
550 { return null; }
551 const def = BLOCK_DEFINITIONS[entry.typeId];
552 if (!def)
553 { return null; }
554 const type = this.catalog.blocks?.[def.key];
555 const state = resolveState(type?.states ?? [], entry.state);
556 if (!state || !type?.blooms?.[state])
557 { return null; }
558 return bloomImageName("block", def.key, state);
559 }
560
561 #placeBloomOverlay (existing, name, pivot)
562 {
563 if (!name)
564 {
565 existing?.destroy();
566 return null;
567 }
568 const object = this.#ensureSprite(existing, name, SORT_BLOCK);
569 if (!object)
570 { return null; }
571 object.renderer.layer = RENDER_LAYER_BLOOM;
572 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
573 return object;
574 }
575
404 #tileFill (existing, name, x, y, layer)
576 #tileFill (existing, name, x, y, layer)
405 {
577 {
406 existing = this.#ensureSprite(existing, name, layer);
578 existing = this.#ensureSprite(existing, name, layer);
@@ -552,6 +724,29 @@ export class WorldView
552 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
724 objects.shade.renderer.alpha = ambientDark * (1 - intensity);
553 }
725 }
554 }
726 }
727
728 #syncBloomLayer ()
729 {
730 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
731 this.scene.setLayers([
732 { name: "default" },
733 {
734 name: RENDER_LAYER_BLOOM,
735 composite: "add",
736 postShaders: Shader.getBloomPostChain({
737 threshold: settings.bloomThreshold,
738 softKnee: settings.bloomSoftKnee,
739 intensity: settings.bloomIntensity,
740 blurSize: settings.bloomBlurSize,
741 saturation: settings.bloomSaturation,
742 colorPreserve: settings.bloomColorPreserve,
743 dilate: settings.bloomDilate,
744 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
745 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
746 })
747 }
748 ]);
749 }
555}
750}
556
751
557export function nightFactor (hour, nightDarkness = 0.72)
752export function nightFactor (hour, nightDarkness = 0.72)
@@ -566,6 +761,12 @@ export function nightFactor (hour, nightDarkness = 0.72)
566 return lerp(0, peak, (hour - 16) / 6);
761 return lerp(0, peak, (hour - 16) / 6);
567}
762}
568
763
764function bodySpriteName (sex)
765{
766 const key = sex === "female" ? "player-body-female" : "player-body-male";
767 return spriteImageName("character", key, key);
768}
769
569function lerp (a, b, t)
770function lerp (a, b, t)
570{
771{
571 return a + (b - a) * Math.min(1, Math.max(0, t));
772 return a + (b - a) * Math.min(1, Math.max(0, t));
client/ui/editor.css +41 −1
@@ -118,13 +118,53 @@ label { display: block; margin: 0.4rem 0; }
118 118 }
119 119
120 120 #settings-form {
121 flex: 1;
122 overflow: auto;
123 padding: 0;
124 display: flex;
125 flex-direction: column;
126 min-height: 0;
127 }
128
129 .settings-tabs {
130 display: flex;
131 flex-wrap: wrap;
132 gap: 0.25rem;
133 padding: 0.65rem 1rem 0.5rem;
134 border-bottom: 1px solid #2c3340;
135 background: #12151c;
136 }
137
138 .settings-tab {
139 appearance: none;
140 border: 1px solid transparent;
141 background: transparent;
142 color: #a8a295;
143 padding: 0.35rem 0.7rem;
144 border-radius: 4px;
145 cursor: pointer;
146 font: inherit;
147 }
148
149 .settings-tab:hover {
150 color: #e8e2d4;
151 background: #1c222c;
152 }
153
154 .settings-tab.active {
155 color: #1a1510;
156 background: #d4c48a;
157 border-color: #d4c48a;
158 }
159
160 .settings-panels {
121 161 flex: 1;
122 162 overflow: auto;
123 163 padding: 0.75rem 1rem 1.25rem;
124 164 }
125 165
126 166 .settings-category {
127 margin-bottom: 1.25rem;
167 margin-bottom: 0;
128 168 }
129 169
130 170 .settings-category h3 {
@@ -118,13 +118,53 @@ label { display: block; margin: 0.4rem 0; }
118}
118}
119
119
120#settings-form {
120#settings-form {
121 flex: 1;
122 overflow: auto;
123 padding: 0;
124 display: flex;
125 flex-direction: column;
126 min-height: 0;
127}
128
129.settings-tabs {
130 display: flex;
131 flex-wrap: wrap;
132 gap: 0.25rem;
133 padding: 0.65rem 1rem 0.5rem;
134 border-bottom: 1px solid #2c3340;
135 background: #12151c;
136}
137
138.settings-tab {
139 appearance: none;
140 border: 1px solid transparent;
141 background: transparent;
142 color: #a8a295;
143 padding: 0.35rem 0.7rem;
144 border-radius: 4px;
145 cursor: pointer;
146 font: inherit;
147}
148
149.settings-tab:hover {
150 color: #e8e2d4;
151 background: #1c222c;
152}
153
154.settings-tab.active {
155 color: #1a1510;
156 background: #d4c48a;
157 border-color: #d4c48a;
158}
159
160.settings-panels {
121 flex: 1;
161 flex: 1;
122 overflow: auto;
162 overflow: auto;
123 padding: 0.75rem 1rem 1.25rem;
163 padding: 0.75rem 1rem 1.25rem;
124}
164}
125
165
126.settings-category {
166.settings-category {
127 margin-bottom: 1.25rem;
167 margin-bottom: 0;
128}
168}
129
169
130.settings-category h3 {
170.settings-category h3 {
client/ui/play.css +107 −1
@@ -124,6 +124,73 @@ a { color: #d4c48a; }
124 124 padding: 0.75rem;
125 125 }
126 126
127 #bag-panel, #bank-panel {
128 position: fixed;
129 z-index: 5;
130 top: 48px;
131 left: 0.75rem;
132 width: min(320px, 92vw);
133 max-height: calc(100vh - 64px);
134 overflow: auto;
135 background: #1a1e26;
136 border: 1px solid #2c3340;
137 padding: 0.75rem;
138 }
139
140 #bank-panel {
141 left: auto;
142 right: 0.75rem;
143 width: min(340px, 92vw);
144 }
145
146 #bank-panel header {
147 display: flex;
148 justify-content: space-between;
149 align-items: center;
150 }
151
152 .item-grid {
153 display: grid;
154 grid-template-columns: repeat(8, 1fr);
155 gap: 0.25rem;
156 margin: 0.4rem 0;
157 }
158
159 .item-grid.equip {
160 grid-template-columns: repeat(3, 1fr);
161 }
162
163 .item-slot {
164 position: relative;
165 min-height: 36px;
166 padding: 0.15rem;
167 image-rendering: pixelated;
168 }
169
170 .item-slot img {
171 width: 100%;
172 height: 32px;
173 object-fit: contain;
174 image-rendering: pixelated;
175 }
176
177 .item-slot.selected {
178 outline: 2px solid #d4c48a;
179 }
180
181 .item-slot .qty {
182 position: absolute;
183 right: 2px;
184 bottom: 1px;
185 font-size: 0.7rem;
186 }
187
188 .bag-actions {
189 display: flex;
190 flex-wrap: wrap;
191 gap: 0.35rem;
192 }
193
127 194 #friends-panel h2, #friends-panel h3 {
128 195 margin: 0.4rem 0;
129 196 font-size: 0.95rem;
@@ -140,6 +207,45 @@ a { color: #d4c48a; }
140 207 #inspect-modal[hidden],
141 208 #inspect-backdrop[hidden],
142 209 #friends-panel[hidden],
143 #nametag[hidden] {
210 #bag-panel[hidden],
211 #bank-panel[hidden],
212 #nametag[hidden],
213 #chat-bar[hidden] {
214 display: none !important;
215 }
216
217 #chat-bar {
218 position: fixed;
219 z-index: 5;
220 left: 50%;
221 bottom: 1.25rem;
222 transform: translateX(-50%);
223 width: min(640px, calc(100vw - 2rem));
224 }
225
226 #chat-bar input {
227 width: 100%;
228 box-sizing: border-box;
229 padding: 0.55rem 0.75rem;
230 background: rgba(12, 14, 18, 0.92);
231 }
232
233 .chat-bubble {
234 position: fixed;
235 z-index: 4;
236 pointer-events: none;
237 transform: translate(-50%, -100%);
238 max-width: min(280px, 70vw);
239 background: rgba(16, 18, 24, 0.92);
240 border: 1px solid #3a4250;
241 border-radius: 8px;
242 padding: 0.3rem 0.55rem;
243 font-size: 0.9rem;
244 line-height: 1.25;
245 white-space: pre-wrap;
246 word-break: break-word;
247 }
248
249 .chat-bubble[hidden] {
144 250 display: none !important;
145 251 }
@@ -124,6 +124,73 @@ a { color: #d4c48a; }
124 padding: 0.75rem;
124 padding: 0.75rem;
125}
125}
126
126
127#bag-panel, #bank-panel {
128 position: fixed;
129 z-index: 5;
130 top: 48px;
131 left: 0.75rem;
132 width: min(320px, 92vw);
133 max-height: calc(100vh - 64px);
134 overflow: auto;
135 background: #1a1e26;
136 border: 1px solid #2c3340;
137 padding: 0.75rem;
138}
139
140#bank-panel {
141 left: auto;
142 right: 0.75rem;
143 width: min(340px, 92vw);
144}
145
146#bank-panel header {
147 display: flex;
148 justify-content: space-between;
149 align-items: center;
150}
151
152.item-grid {
153 display: grid;
154 grid-template-columns: repeat(8, 1fr);
155 gap: 0.25rem;
156 margin: 0.4rem 0;
157}
158
159.item-grid.equip {
160 grid-template-columns: repeat(3, 1fr);
161}
162
163.item-slot {
164 position: relative;
165 min-height: 36px;
166 padding: 0.15rem;
167 image-rendering: pixelated;
168}
169
170.item-slot img {
171 width: 100%;
172 height: 32px;
173 object-fit: contain;
174 image-rendering: pixelated;
175}
176
177.item-slot.selected {
178 outline: 2px solid #d4c48a;
179}
180
181.item-slot .qty {
182 position: absolute;
183 right: 2px;
184 bottom: 1px;
185 font-size: 0.7rem;
186}
187
188.bag-actions {
189 display: flex;
190 flex-wrap: wrap;
191 gap: 0.35rem;
192}
193
127#friends-panel h2, #friends-panel h3 {
194#friends-panel h2, #friends-panel h3 {
128 margin: 0.4rem 0;
195 margin: 0.4rem 0;
129 font-size: 0.95rem;
196 font-size: 0.95rem;
@@ -140,6 +207,45 @@ a { color: #d4c48a; }
140#inspect-modal[hidden],
207#inspect-modal[hidden],
141#inspect-backdrop[hidden],
208#inspect-backdrop[hidden],
142#friends-panel[hidden],
209#friends-panel[hidden],
143#nametag[hidden] {
210#bag-panel[hidden],
211#bank-panel[hidden],
212#nametag[hidden],
213#chat-bar[hidden] {
214 display: none !important;
215}
216
217#chat-bar {
218 position: fixed;
219 z-index: 5;
220 left: 50%;
221 bottom: 1.25rem;
222 transform: translateX(-50%);
223 width: min(640px, calc(100vw - 2rem));
224}
225
226#chat-bar input {
227 width: 100%;
228 box-sizing: border-box;
229 padding: 0.55rem 0.75rem;
230 background: rgba(12, 14, 18, 0.92);
231}
232
233.chat-bubble {
234 position: fixed;
235 z-index: 4;
236 pointer-events: none;
237 transform: translate(-50%, -100%);
238 max-width: min(280px, 70vw);
239 background: rgba(16, 18, 24, 0.92);
240 border: 1px solid #3a4250;
241 border-radius: 8px;
242 padding: 0.3rem 0.55rem;
243 font-size: 0.9rem;
244 line-height: 1.25;
245 white-space: pre-wrap;
246 word-break: break-word;
247}
248
249.chat-bubble[hidden] {
144 display: none !important;
250 display: none !important;
145}
251}
docs/FEATURES.md +41 −35
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16 16 ## Ground and block tile layers
17 17
18 18 **Status:** full
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. Each type's PNGs live in a per-type folder; filenames are visual states (first alphabetical is default).
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `server/src/assets/spriteCatalog.js`
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states.
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`
21 21
22 22 ## Open and closed chunks
23 23
@@ -27,14 +27,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
27 27
28 28 ## ECS registry and components
29 29
30 **Status:** partial
31 **Spec:** Entities are compositions of components with integer tile positions. First-version components are `position`, `movement`, `appearance`, and `character`. No worker-local handles or full component set yet.
32 **Code:** `server/src/ecs/world.js`
30 **Status:** full
31 **Spec:** Entities are compositions of components with integer tile positions. Live components include `position`, `movement`, `path`, `appearance`, `character`, `networkIdentity`, `chunkLoader`, and `persistent`. Global `EntityId`s are used for storage, networking and transfer; each worker uses compact recycled `EntityHandle`s for hot ECS arrays.
32 **Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
33 33
34 34 ## Simulation tick
35 35
36 **Status:** partial
37 **Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries. Single process; no region workers.
36 **Status:** full
37 **Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries, then activation, movement, transfers, and ghost exchange. Multiple isolated simulation workers.
38 38 **Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
39 39
40 40 ## Authored world and runtime state persistence
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52 52 ## World settings
53 53
54 54 **Status:** full
55 **Spec:** Global cadence, timers, and night darkness live in `world_live_settings` and apply as soon as an admin saves. The editor modal is categorised and scrollable, marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
55 **Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56 56 **Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57 57
58 58 ## Baked lighting
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64 64 ## World editor (server)
65 65
66 66 **Status:** full
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace/bank/spawner placement is later.
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks (including spawners and banks), write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
68 68 **Code:** `server/src/editor/service.js`
69 69
70 70 ## World editor (client)
71 71
72 72 **Status:** full
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. Spawner paint uses mob type, max alive and range; bank is a placeable block. Placeholder sprites stand in until real art exists.
74 74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
75 75
76 76 ## Per-chunk changelog
@@ -99,27 +99,27 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
99 99
100 100 ## Character deletion and inheritance
101 101
102 **Status:** partial
103 **Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory/equipment/wallet/vault inheritance is not implemented (no items yet).
104 **Code:** `server/src/characters/service.js` (`scheduleDelete`, `cancelDelete`, `processDueDeletions`)
102 **Status:** full
103 **Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory, equipment, carried coins, and vault move to the account inheritance tab, claimable at a bank into another character's vault.
104 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
105 105
106 106 ## 3×3 chunk replication
107 107
108 **Status:** partial
109 **Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Entity moves are incremental; tile deltas are not used yet because live tile edits wait for Apply now.
110 **Code:** `server/src/simulation/simulation.js` (`snapshotFor`), `server/src/gateway/websocket.js` (`syncSubscriptions`)
108 **Status:** full
109 **Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
110 **Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)
111 111
112 112 ## Click-to-move and A\* pathfinding
113 113
114 114 **Status:** full
115 115 **Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence.
116 **Code:** `server/src/navigation/astar.js`, `server/src/simulation/simulation.js` (`#moveTo`, `#stepMovement`)
116 **Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`)
117 117
118 118 ## Global walk/run cadence
119 119
120 120 **Status:** full
121 121 **Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
122 **Code:** `server/src/simulation/simulation.js` (`#stepMovement`, `#setGait`)
122 **Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
123 123
124 124 ## Client movement interpolation
125 125
@@ -159,15 +159,15 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
159 159
160 160 ## Region workers and cross-worker transfer
161 161
162 **Status:** not implemented
163 **Spec:** Regions owned by simulation workers, ghost borders, entity transfer. First version is a single process.
164 **Code:** —
162 **Status:** full
163 **Spec:** Isolated simulation workers own regions. Default is two in-process workers behind a clone-on-boundary protocol (`SIMULATION_WORKER_MODE=thread` uses `worker_threads`). Neighbour-sticky assignment; an entity that steps into a foreign region is frozen, accepted on the destination, then removed from the source (one authoritative copy). Ghost occupancy is visible for pathfinding. Dynamic load rebalance is later.
164 **Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
165 165
166 166 ## ChunkLoader activation and unload persistence
167 167
168 **Status:** partial
169 **Spec:** Chunks around players are loaded into memory for simulation and visibility. Character positions persist on despawn. There is no grace-period unload writer yet; authored data is already in `world.sqlite`.
170 **Code:** `server/src/simulation/simulation.js` (`#ensureChunk`, `despawnCharacter`)
168 **Status:** full
169 **Spec:** Players carry `ChunkLoader` (3×3 simulating chunks, 3×3 resident regions). Chunks with no simulation refs stay dormant in memory. Regions with no residency refs unload after `regionUnloadGracePeriodMs`. Persistent entities are written on unload and restored on the next load; non-persistent entities are discarded.
170 **Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
171 171
172 172 ## Midnight restart and Git deploy
173 173
@@ -177,22 +177,28 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
177 177
178 178 ## Spawners
179 179
180 **Status:** not implemented
181 **Spec:** Spawner blocks with mob type, max alive, range. Do not fire in closed chunks.
182 **Code:** —
180 **Status:** full
181 **Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Placeholder deer art until real sprites exist.
182 **Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`
183 183
184 184 ## Inventory, items, equipment, ground drops
185 185
186 **Status:** not implemented
187 **Spec:** 32-slot inventory, stacking, equipment overlays, temporary ground items. Waiting on item assets.
188 **Code:** —
186 **Status:** full
187 **Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists.
188 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
189 189
190 ## Combat, skills, groups, proximity chat, pigeons
190 ## Combat, skills, groups, pigeons
191 191
192 192 **Status:** not implemented
193 **Spec:** Later systems described in the design. Not part of the first playable slice. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
193 **Spec:** Later systems described in the design. Not part of this playable basis. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
194 194 **Code:** —
195 195
196 ## Proximity chat
197
198 **Status:** full
199 **Spec:** Enter opens a bottom chat line (max `chatMaxCharacters`, default 100). Enter trims and sends; Escape cancels. The speaker always sees their own bubble. Other players receive server-side obfuscation: full text within 8 tiles, linear falloff to silent at 16 tiles. At 0% readability the bubble is not sent.
200 **Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
201
196 202 ## Friends
197 203
198 204 **Status:** full
@@ -201,9 +207,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
201 207
202 208 ## Banking, cheques, shops, player-driven marketplace
203 209
204 **Status:** not implemented
205 **Spec:** Marketplace and related world features are built in the world editor after the required assets exist.
206 **Code:** —
210 **Status:** partial
211 **Spec:** Bank blocks can be placed in the editor. Standing next to a bank opens vault deposit/withdraw and inheritance claim. Filled cheques, shop NPCs, and the player marketplace are not in this slice.
212 **Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`
207 213
208 214 ## Player scripting hooks
209 215
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16## Ground and block tile layers
16## Ground and block tile layers
17
17
18**Status:** full
18**Status:** full
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. Each type's PNGs live in a per-type folder; filenames are visual states (first alphabetical is default).
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. **All** sprite kinds (grounds, blocks, items, mobs, characters) use a per-type folder; base PNGs are visual states and companions (`*-bloom`, `*-equip`, `*-equip-bloom`) live in that same folder and are never placeable editor states.
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `server/src/assets/spriteCatalog.js`
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`
21
21
22## Open and closed chunks
22## Open and closed chunks
23
23
@@ -27,14 +27,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
27
27
28## ECS registry and components
28## ECS registry and components
29
29
30**Status:** partial
30**Status:** full
31**Spec:** Entities are compositions of components with integer tile positions. First-version components are `position`, `movement`, `appearance`, and `character`. No worker-local handles or full component set yet.
31**Spec:** Entities are compositions of components with integer tile positions. Live components include `position`, `movement`, `path`, `appearance`, `character`, `networkIdentity`, `chunkLoader`, and `persistent`. Global `EntityId`s are used for storage, networking and transfer; each worker uses compact recycled `EntityHandle`s for hot ECS arrays.
32**Code:** `server/src/ecs/world.js`
32**Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
33
33
34## Simulation tick
34## Simulation tick
35
35
36**Status:** partial
36**Status:** full
37**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries. Single process; no region workers.
37**Spec:** Fixed tick from `WorldSettings.simulationTickHz` (default 20 Hz). Commands drain at tick boundaries, then activation, movement, transfers, and ghost exchange. Multiple isolated simulation workers.
38**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
38**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
39
39
40## Authored world and runtime state persistence
40## Authored world and runtime state persistence
@@ -52,7 +52,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
52## World settings
52## World settings
53
53
54**Status:** full
54**Status:** full
55**Spec:** Global cadence, timers, and night darkness live in `world_live_settings` and apply as soon as an admin saves. The editor modal is categorised and scrollable, marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
55**Spec:** Global cadence, timers, night darkness, bloom post-chain knobs, and chat max characters live in `world_live_settings` and apply as soon as an admin saves. The editor modal uses category tabs (Simulation, Graphics, Inventory, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Editing night darkness snaps the Night preview to night so the effect is visible (day hours otherwise keep ambient darkening at 0). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56**Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
56**Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57
57
58## Baked lighting
58## Baked lighting
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64## World editor (server)
64## World editor (server)
65
65
66**Status:** full
66**Status:** full
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace/bank/spawner placement is later.
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks (including spawners and banks), write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace stalls wait on later economy work.
68**Code:** `server/src/editor/service.js`
68**Code:** `server/src/editor/service.js`
69
69
70## World editor (client)
70## World editor (client)
71
71
72**Status:** full
72**Status:** full
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse-wheel zoom (centred on the selected chunk) and Shift+wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal, save chunk and Apply now. Spawner paint uses mob type, max alive and range; bank is a placeable block. Placeholder sprites stand in until real art exists.
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
75
75
76## Per-chunk changelog
76## Per-chunk changelog
@@ -99,27 +99,27 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
99
99
100## Character deletion and inheritance
100## Character deletion and inheritance
101
101
102**Status:** partial
102**Status:** full
103**Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory/equipment/wallet/vault inheritance is not implemented (no items yet).
103**Spec:** 24h delayed delete, cancellable. Notify via stub log (or email when present). Names and surname claims are freed on permanent delete. Inventory, equipment, carried coins, and vault move to the account inheritance tab, claimable at a bank into another character's vault.
104**Code:** `server/src/characters/service.js` (`scheduleDelete`, `cancelDelete`, `processDueDeletions`)
104**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
105
105
106## 3×3 chunk replication
106## 3×3 chunk replication
107
107
108**Status:** partial
108**Status:** full
109**Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Entity moves are incremental; tile deltas are not used yet because live tile edits wait for Apply now.
109**Spec:** Players receive the current chunk and eight neighbours as snapshots. Closed chunks are still sent. Afterwards the gateway sends `ENTITY_SPAWN`, compact `ENTITY_MOVE` (tile + gait) and `ENTITY_DESPAWN`; appearance and path stay off the move payload. Tile deltas are not used yet because live tile edits wait for Apply now. Visible chunks may be owned by different workers; the gateway never reassigns regions for rendering.
110**Code:** `server/src/simulation/simulation.js` (`snapshotFor`), `server/src/gateway/websocket.js` (`syncSubscriptions`)
110**Code:** `server/src/simulation/simulation.js` (`snapshotFor`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`)
111
111
112## Click-to-move and A\* pathfinding
112## Click-to-move and A\* pathfinding
113
113
114**Status:** full
114**Status:** full
115**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence.
115**Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Occupied tiles block. Server commits integer tiles on the movement cadence.
116**Code:** `server/src/navigation/astar.js`, `server/src/simulation/simulation.js` (`#moveTo`, `#stepMovement`)
116**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`)
117
117
118## Global walk/run cadence
118## Global walk/run cadence
119
119
120**Status:** full
120**Status:** full
121**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
121**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
122**Code:** `server/src/simulation/simulation.js` (`#stepMovement`, `#setGait`)
122**Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
123
123
124## Client movement interpolation
124## Client movement interpolation
125
125
@@ -159,15 +159,15 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
159
159
160## Region workers and cross-worker transfer
160## Region workers and cross-worker transfer
161
161
162**Status:** not implemented
162**Status:** full
163**Spec:** Regions owned by simulation workers, ghost borders, entity transfer. First version is a single process.
163**Spec:** Isolated simulation workers own regions. Default is two in-process workers behind a clone-on-boundary protocol (`SIMULATION_WORKER_MODE=thread` uses `worker_threads`). Neighbour-sticky assignment; an entity that steps into a foreign region is frozen, accepted on the destination, then removed from the source (one authoritative copy). Ghost occupancy is visible for pathfinding. Dynamic load rebalance is later.
164**Code:** —
164**Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
165
165
166## ChunkLoader activation and unload persistence
166## ChunkLoader activation and unload persistence
167
167
168**Status:** partial
168**Status:** full
169**Spec:** Chunks around players are loaded into memory for simulation and visibility. Character positions persist on despawn. There is no grace-period unload writer yet; authored data is already in `world.sqlite`.
169**Spec:** Players carry `ChunkLoader` (3×3 simulating chunks, 3×3 resident regions). Chunks with no simulation refs stay dormant in memory. Regions with no residency refs unload after `regionUnloadGracePeriodMs`. Persistent entities are written on unload and restored on the next load; non-persistent entities are discarded.
170**Code:** `server/src/simulation/simulation.js` (`#ensureChunk`, `despawnCharacter`)
170**Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
171
171
172## Midnight restart and Git deploy
172## Midnight restart and Git deploy
173
173
@@ -177,22 +177,28 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
177
177
178## Spawners
178## Spawners
179
179
180**Status:** not implemented
180**Status:** full
181**Spec:** Spawner blocks with mob type, max alive, range. Do not fire in closed chunks.
181**Spec:** Spawner blocks with mob type, max alive, and range. They fire only in open, simulating chunks. Spawned mobs get `SpawnOrigin`; persistence follows the mob definition (deer are not persistent). Placeholder deer art until real sprites exist.
182**Code:** —
182**Code:** `server/src/simulation/spawners.js`, `shared/definitions/mobs.js`, `client/assets/blocks/spawner/`, `client/assets/mobs/deer/`
183
183
184## Inventory, items, equipment, ground drops
184## Inventory, items, equipment, ground drops
185
185
186**Status:** not implemented
186**Status:** full
187**Spec:** 32-slot inventory, stacking, equipment overlays, temporary ground items. Waiting on item assets.
187**Spec:** 32-slot inventory, stacking, equipment slots with a separate `equipSprite` overlay on the body, carried currency, player drops that last `groundItemDespawnDurationMs` (default 10 minutes). Pickup requires standing on the tile. Inventory is private UI state; nearby clients see ground items and worn overlays. New characters start with paper, apples, a stick, a cloth shirt, and coins. Placeholder item/equipment PNGs until real art exists.
188**Code:** —
188**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
189
189
190## Combat, skills, groups, proximity chat, pigeons
190## Combat, skills, groups, pigeons
191
191
192**Status:** not implemented
192**Status:** not implemented
193**Spec:** Later systems described in the design. Not part of the first playable slice. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
193**Spec:** Later systems described in the design. Not part of this playable basis. Pigeon dispatch will type a first+last name or pick a friend to fill those fields.
194**Code:** —
194**Code:** —
195
195
196## Proximity chat
197
198**Status:** full
199**Spec:** Enter opens a bottom chat line (max `chatMaxCharacters`, default 100). Enter trims and sends; Escape cancels. The speaker always sees their own bubble. Other players receive server-side obfuscation: full text within 8 tiles, linear falloff to silent at 16 tiles. At 0% readability the bubble is not sent.
200**Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
201
196## Friends
202## Friends
197
203
198**Status:** full
204**Status:** full
@@ -201,9 +207,9 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
201
207
202## Banking, cheques, shops, player-driven marketplace
208## Banking, cheques, shops, player-driven marketplace
203
209
204**Status:** not implemented
210**Status:** partial
205**Spec:** Marketplace and related world features are built in the world editor after the required assets exist.
211**Spec:** Bank blocks can be placed in the editor. Standing next to a bank opens vault deposit/withdraw and inheritance claim. Filled cheques, shop NPCs, and the player marketplace are not in this slice.
206**Code:** —
212**Code:** `server/src/items/bags.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`
207
213
208## Player scripting hooks
214## Player scripting hooks
209
215
server/src/assets/placeholderPng.js added +70 −0
@@ -0,0 +1,70 @@
1 import { deflateSync } from "node:zlib";
2 import { mkdirSync, writeFileSync } from "node:fs";
3 import { dirname } from "node:path";
4
5 export function writeRgbaPng (filePath, width, height, pixels)
6 {
7 const raw = Buffer.alloc((width * 4 + 1) * height);
8 for (let y = 0; y < height; y++)
9 {
10 raw[y * (width * 4 + 1)] = 0;
11 Buffer.from(pixels).copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
12 }
13 const ihdr = Buffer.alloc(13);
14 ihdr.writeUInt32BE(width, 0);
15 ihdr.writeUInt32BE(height, 4);
16 ihdr[8] = 8;
17 ihdr[9] = 6;
18 const png = Buffer.concat([
19 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
20 chunk("IHDR", ihdr),
21 chunk("IDAT", deflateSync(raw)),
22 chunk("IEND", Buffer.alloc(0))
23 ]);
24 mkdirSync(dirname(filePath), { recursive: true });
25 writeFileSync(filePath, png);
26 }
27
28 export function makeRgba (width, height, fill = [0, 0, 0, 0])
29 {
30 const pixels = Buffer.alloc(width * height * 4);
31 for (let i = 0; i < width * height; i++)
32 { pixels.set(fill, i * 4); }
33 return { width, height, pixels };
34 }
35
36 export function fillRect (image, x, y, width, height, rgba)
37 {
38 for (let py = y; py < y + height; py++)
39 {
40 for (let px = x; px < x + width; px++)
41 {
42 if (px < 0 || py < 0 || px >= image.width || py >= image.height)
43 { continue; }
44 image.pixels.set(rgba, (py * image.width + px) * 4);
45 }
46 }
47 }
48
49 function chunk (type, data)
50 {
51 const name = Buffer.from(type);
52 const payload = Buffer.concat([name, data]);
53 const header = Buffer.alloc(4);
54 header.writeUInt32BE(data.length, 0);
55 const crc = Buffer.alloc(4);
56 crc.writeUInt32BE(crc32(payload), 0);
57 return Buffer.concat([header, payload, crc]);
58 }
59
60 function crc32 (buffer)
61 {
62 let crc = 0xffffffff;
63 for (const byte of buffer)
64 {
65 crc ^= byte;
66 for (let i = 0; i < 8; i++)
67 { crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); }
68 }
69 return (crc ^ 0xffffffff) >>> 0;
70 }
@@ -0,0 +1,70 @@
1import { deflateSync } from "node:zlib";
2import { mkdirSync, writeFileSync } from "node:fs";
3import { dirname } from "node:path";
4
5export function writeRgbaPng (filePath, width, height, pixels)
6{
7 const raw = Buffer.alloc((width * 4 + 1) * height);
8 for (let y = 0; y < height; y++)
9 {
10 raw[y * (width * 4 + 1)] = 0;
11 Buffer.from(pixels).copy(raw, y * (width * 4 + 1) + 1, y * width * 4, (y + 1) * width * 4);
12 }
13 const ihdr = Buffer.alloc(13);
14 ihdr.writeUInt32BE(width, 0);
15 ihdr.writeUInt32BE(height, 4);
16 ihdr[8] = 8;
17 ihdr[9] = 6;
18 const png = Buffer.concat([
19 Buffer.from([137, 80, 78, 71, 13, 10, 26, 10]),
20 chunk("IHDR", ihdr),
21 chunk("IDAT", deflateSync(raw)),
22 chunk("IEND", Buffer.alloc(0))
23 ]);
24 mkdirSync(dirname(filePath), { recursive: true });
25 writeFileSync(filePath, png);
26}
27
28export function makeRgba (width, height, fill = [0, 0, 0, 0])
29{
30 const pixels = Buffer.alloc(width * height * 4);
31 for (let i = 0; i < width * height; i++)
32 { pixels.set(fill, i * 4); }
33 return { width, height, pixels };
34}
35
36export function fillRect (image, x, y, width, height, rgba)
37{
38 for (let py = y; py < y + height; py++)
39 {
40 for (let px = x; px < x + width; px++)
41 {
42 if (px < 0 || py < 0 || px >= image.width || py >= image.height)
43 { continue; }
44 image.pixels.set(rgba, (py * image.width + px) * 4);
45 }
46 }
47}
48
49function chunk (type, data)
50{
51 const name = Buffer.from(type);
52 const payload = Buffer.concat([name, data]);
53 const header = Buffer.alloc(4);
54 header.writeUInt32BE(data.length, 0);
55 const crc = Buffer.alloc(4);
56 crc.writeUInt32BE(crc32(payload), 0);
57 return Buffer.concat([header, payload, crc]);
58}
59
60function crc32 (buffer)
61{
62 let crc = 0xffffffff;
63 for (const byte of buffer)
64 {
65 crc ^= byte;
66 for (let i = 0; i < 8; i++)
67 { crc = (crc >>> 1) ^ (crc & 1 ? 0xedb88320 : 0); }
68 }
69 return (crc ^ 0xffffffff) >>> 0;
70}
server/src/assets/spriteCatalog.js +143 −10
@@ -1,27 +1,86 @@
1 1 import { readdirSync } from "node:fs";
2 2 import { extname, join } from "node:path";
3 3 import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4 import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5 import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6 import {
7 bloomImageName,
8 equipBloomImageName,
9 equipImageName,
10 isCompanionSpriteStem,
11 parseSpriteStem,
12 spriteImageName
13 } from "../../../shared/definitions/tileSprites.js";
14
15 const CHARACTER_DEFINITIONS = Object.freeze({
16 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
17 "player-body-female": Object.freeze({ key: "player-body-female", id: "player-body-female" })
18 });
5 19
6 20 export function buildSpriteCatalog (assetRoot)
7 21 {
8 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground");
9 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block");
22 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
23 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
24 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
25 const mobs = scanLayer(join(assetRoot, "mobs"), mobScanDefs(), "mob", "mobs");
26 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
10 27 return {
11 28 grounds: grounds.types,
12 29 blocks: blocks.types,
13 images: [...grounds.images, ...blocks.images]
30 items: items.types,
31 mobs: mobs.types,
32 characters: characters.types,
33 images: [
34 ...grounds.images,
35 ...blocks.images,
36 ...items.images,
37 ...mobs.images,
38 ...characters.images
39 ]
14 40 };
15 41 }
16 42
17 function scanLayer (layerDir, definitions, layer)
43 function itemScanDefs ()
44 {
45 const defs = {};
46 for (const def of Object.values(ITEM_DEFINITIONS))
47 {
48 defs[def.key] = {
49 key: def.key,
50 id: def.itemId,
51 frames: def.frames ?? 1,
52 framesPerRow: def.framesPerRow ?? 1,
53 animationSpeed: def.animationSpeed ?? 0
54 };
55 }
56 return defs;
57 }
58
59 function mobScanDefs ()
60 {
61 const defs = {};
62 for (const def of Object.values(MOB_DEFINITIONS))
63 {
64 const key = def.key ?? def.mobTypeId;
65 defs[key] = {
66 key,
67 id: def.mobTypeId,
68 frames: def.frames ?? 1,
69 framesPerRow: def.framesPerRow ?? 1,
70 animationSpeed: def.animationSpeed ?? 0
71 };
72 }
73 return defs;
74 }
75
76 function scanLayer (layerDir, definitions, layer, urlFolder)
18 77 {
19 78 const types = {};
20 79 const images = [];
21 80 for (const def of Object.values(definitions))
22 81 {
23 82 const folder = join(layerDir, def.key);
24 const states = listPngStates(folder);
83 const { states, blooms, equips, equipBlooms } = listVisualStates(folder);
25 84 if (states.length === 0)
26 85 { throw new Error(`No PNG states in ${folder}`); }
27 86
@@ -33,26 +92,100 @@ function scanLayer (layerDir, definitions, layer)
33 92 typeId: def.id,
34 93 states,
35 94 defaultState: states[0],
95 blooms,
96 equips,
97 equipBlooms,
36 98 frames,
37 99 framesPerRow,
38 100 animationSpeed
39 101 };
40 102 for (const state of states)
41 103 {
42 images.push({
43 name: spriteImageName(layer, def.key, state),
44 url: `/assets/${layer === "ground" ? "grounds" : "blocks"}/${def.key}/${state}.png`,
104 const sheet = {
45 105 subImgTotal: frames,
46 106 perRow: framesPerRow,
47 107 loop: animationSpeed > 0,
48 108 animationSpeed
109 };
110 images.push({
111 name: spriteImageName(layer, def.key, state),
112 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
113 ...sheet
49 114 });
115 if (blooms[state])
116 {
117 images.push({
118 name: bloomImageName(layer, def.key, state),
119 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
120 ...sheet
121 });
122 }
123 if (equips[state])
124 {
125 images.push({
126 name: equipImageName(layer, def.key, state),
127 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
128 ...sheet
129 });
130 }
131 if (equipBlooms[state])
132 {
133 images.push({
134 name: equipBloomImageName(layer, def.key, state),
135 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
136 ...sheet
137 });
138 }
50 139 }
51 140 }
52 141 return { types, images };
53 142 }
54 143
55 function listPngStates (folder)
144 function listVisualStates (folder)
145 {
146 const stems = listPngStems(folder);
147 const blooms = {};
148 const equips = {};
149 const equipBlooms = {};
150 const states = [];
151 for (const stem of stems)
152 {
153 const parsed = parseSpriteStem(stem);
154 if (parsed.companion)
155 {
156 if (!parsed.base)
157 { continue; }
158 if (parsed.equip && parsed.bloom)
159 { equipBlooms[parsed.base] = true; }
160 else if (parsed.equip)
161 { equips[parsed.base] = true; }
162 else if (parsed.bloom)
163 { blooms[parsed.base] = true; }
164 continue;
165 }
166 if (isCompanionSpriteStem(stem))
167 { continue; }
168 states.push(stem);
169 }
170 const filterMap = (map) =>
171 {
172 const next = {};
173 for (const state of states)
174 {
175 if (map[state])
176 { next[state] = true; }
177 }
178 return next;
179 };
180 return {
181 states,
182 blooms: filterMap(blooms),
183 equips: filterMap(equips),
184 equipBlooms: filterMap(equipBlooms)
185 };
186 }
187
188 function listPngStems (folder)
56 189 {
57 190 let entries;
58 191 try
@@ -1,27 +1,86 @@
1import { readdirSync } from "node:fs";
1import { readdirSync } from "node:fs";
2import { extname, join } from "node:path";
2import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import {
7 bloomImageName,
8 equipBloomImageName,
9 equipImageName,
10 isCompanionSpriteStem,
11 parseSpriteStem,
12 spriteImageName
13} from "../../../shared/definitions/tileSprites.js";
14
15const CHARACTER_DEFINITIONS = Object.freeze({
16 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
17 "player-body-female": Object.freeze({ key: "player-body-female", id: "player-body-female" })
18});
5
19
6export function buildSpriteCatalog (assetRoot)
20export function buildSpriteCatalog (assetRoot)
7{
21{
8 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground");
22 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
9 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block");
23 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block", "blocks");
24 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
25 const mobs = scanLayer(join(assetRoot, "mobs"), mobScanDefs(), "mob", "mobs");
26 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
10 return {
27 return {
11 grounds: grounds.types,
28 grounds: grounds.types,
12 blocks: blocks.types,
29 blocks: blocks.types,
13 images: [...grounds.images, ...blocks.images]
30 items: items.types,
31 mobs: mobs.types,
32 characters: characters.types,
33 images: [
34 ...grounds.images,
35 ...blocks.images,
36 ...items.images,
37 ...mobs.images,
38 ...characters.images
39 ]
14 };
40 };
15}
41}
16
42
17function scanLayer (layerDir, definitions, layer)
43function itemScanDefs ()
44{
45 const defs = {};
46 for (const def of Object.values(ITEM_DEFINITIONS))
47 {
48 defs[def.key] = {
49 key: def.key,
50 id: def.itemId,
51 frames: def.frames ?? 1,
52 framesPerRow: def.framesPerRow ?? 1,
53 animationSpeed: def.animationSpeed ?? 0
54 };
55 }
56 return defs;
57}
58
59function mobScanDefs ()
60{
61 const defs = {};
62 for (const def of Object.values(MOB_DEFINITIONS))
63 {
64 const key = def.key ?? def.mobTypeId;
65 defs[key] = {
66 key,
67 id: def.mobTypeId,
68 frames: def.frames ?? 1,
69 framesPerRow: def.framesPerRow ?? 1,
70 animationSpeed: def.animationSpeed ?? 0
71 };
72 }
73 return defs;
74}
75
76function scanLayer (layerDir, definitions, layer, urlFolder)
18{
77{
19 const types = {};
78 const types = {};
20 const images = [];
79 const images = [];
21 for (const def of Object.values(definitions))
80 for (const def of Object.values(definitions))
22 {
81 {
23 const folder = join(layerDir, def.key);
82 const folder = join(layerDir, def.key);
24 const states = listPngStates(folder);
83 const { states, blooms, equips, equipBlooms } = listVisualStates(folder);
25 if (states.length === 0)
84 if (states.length === 0)
26 { throw new Error(`No PNG states in ${folder}`); }
85 { throw new Error(`No PNG states in ${folder}`); }
27
86
@@ -33,26 +92,100 @@ function scanLayer (layerDir, definitions, layer)
33 typeId: def.id,
92 typeId: def.id,
34 states,
93 states,
35 defaultState: states[0],
94 defaultState: states[0],
95 blooms,
96 equips,
97 equipBlooms,
36 frames,
98 frames,
37 framesPerRow,
99 framesPerRow,
38 animationSpeed
100 animationSpeed
39 };
101 };
40 for (const state of states)
102 for (const state of states)
41 {
103 {
42 images.push({
104 const sheet = {
43 name: spriteImageName(layer, def.key, state),
44 url: `/assets/${layer === "ground" ? "grounds" : "blocks"}/${def.key}/${state}.png`,
45 subImgTotal: frames,
105 subImgTotal: frames,
46 perRow: framesPerRow,
106 perRow: framesPerRow,
47 loop: animationSpeed > 0,
107 loop: animationSpeed > 0,
48 animationSpeed
108 animationSpeed
109 };
110 images.push({
111 name: spriteImageName(layer, def.key, state),
112 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
113 ...sheet
49 });
114 });
115 if (blooms[state])
116 {
117 images.push({
118 name: bloomImageName(layer, def.key, state),
119 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
120 ...sheet
121 });
122 }
123 if (equips[state])
124 {
125 images.push({
126 name: equipImageName(layer, def.key, state),
127 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
128 ...sheet
129 });
130 }
131 if (equipBlooms[state])
132 {
133 images.push({
134 name: equipBloomImageName(layer, def.key, state),
135 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
136 ...sheet
137 });
138 }
50 }
139 }
51 }
140 }
52 return { types, images };
141 return { types, images };
53}
142}
54
143
55function listPngStates (folder)
144function listVisualStates (folder)
145{
146 const stems = listPngStems(folder);
147 const blooms = {};
148 const equips = {};
149 const equipBlooms = {};
150 const states = [];
151 for (const stem of stems)
152 {
153 const parsed = parseSpriteStem(stem);
154 if (parsed.companion)
155 {
156 if (!parsed.base)
157 { continue; }
158 if (parsed.equip && parsed.bloom)
159 { equipBlooms[parsed.base] = true; }
160 else if (parsed.equip)
161 { equips[parsed.base] = true; }
162 else if (parsed.bloom)
163 { blooms[parsed.base] = true; }
164 continue;
165 }
166 if (isCompanionSpriteStem(stem))
167 { continue; }
168 states.push(stem);
169 }
170 const filterMap = (map) =>
171 {
172 const next = {};
173 for (const state of states)
174 {
175 if (map[state])
176 { next[state] = true; }
177 }
178 return next;
179 };
180 return {
181 states,
182 blooms: filterMap(blooms),
183 equips: filterMap(equips),
184 equipBlooms: filterMap(equipBlooms)
185 };
186}
187
188function listPngStems (folder)
56{
189{
57 let entries;
190 let entries;
58 try
191 try
server/src/characters/service.js +2 −1
@@ -68,10 +68,11 @@ export class CharacterService
68 68 return publicCharacter(this.stateDb.getCharacter(characterId));
69 69 }
70 70
71 processDueDeletions (now = Date.now())
71 processDueDeletions (now = Date.now(), despawn = null)
72 72 {
73 73 for (const character of this.stateDb.listDueDeletions(now))
74 74 {
75 despawn?.(character.character_id);
75 76 this.stateDb.deleteCharacter(character.character_id);
76 77 this.log.info?.(
77 78 `[mail-stub] Permanently deleted ${character.first_name} ${character.last_name} for account ${character.account_id}`
@@ -68,10 +68,11 @@ export class CharacterService
68 return publicCharacter(this.stateDb.getCharacter(characterId));
68 return publicCharacter(this.stateDb.getCharacter(characterId));
69 }
69 }
70
70
71 processDueDeletions (now = Date.now())
71 processDueDeletions (now = Date.now(), despawn = null)
72 {
72 {
73 for (const character of this.stateDb.listDueDeletions(now))
73 for (const character of this.stateDb.listDueDeletions(now))
74 {
74 {
75 despawn?.(character.character_id);
75 this.stateDb.deleteCharacter(character.character_id);
76 this.stateDb.deleteCharacter(character.character_id);
76 this.log.info?.(
77 this.log.info?.(
77 `[mail-stub] Permanently deleted ${character.first_name} ${character.last_name} for account ${character.account_id}`
78 `[mail-stub] Permanently deleted ${character.first_name} ${character.last_name} for account ${character.account_id}`
server/src/chat/speech.js added +49 −0
@@ -0,0 +1,49 @@
1 import { CHUNK_SIZE, MessageType } from "../../../shared/protocol/constants.js";
2 import { obscureSpeech, speechReadability } from "../../../shared/speech/proximity.js";
3
4 let nextMessageId = 1;
5
6 export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
7 {
8 const maxChars = Math.max(1, Math.round(simulation.settings.chatMaxCharacters || 100));
9 const text = String(rawText ?? "").trim().slice(0, maxChars);
10 if (!text)
11 { return; }
12
13 const speakerPos = simulation.positionOf(speakerSession.entityId);
14 if (!speakerPos)
15 { return; }
16
17 const messageId = nextMessageId++;
18 const createdAt = Date.now();
19 for (const other of sessions.values())
20 {
21 if (!other.entityId)
22 { continue; }
23 let readable = text;
24 if (other !== speakerSession)
25 {
26 const listenerPos = simulation.positionOf(other.entityId);
27 if (!listenerPos)
28 { continue; }
29 const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
30 const readability = speechReadability(distance, CHUNK_SIZE);
31 if (readability <= 0)
32 { continue; }
33 readable = obscureSpeech(text, readability, messageId ^ other.id);
34 if (!readable)
35 { continue; }
36 }
37 if (other.socket.readyState === 1)
38 {
39 other.socket.send(JSON.stringify({
40 type: MessageType.chatBubble,
41 messageId,
42 entityId: speakerSession.entityId,
43 characterId: speakerSession.characterId,
44 text: readable,
45 createdAt
46 }));
47 }
48 }
49 }
@@ -0,0 +1,49 @@
1import { CHUNK_SIZE, MessageType } from "../../../shared/protocol/constants.js";
2import { obscureSpeech, speechReadability } from "../../../shared/speech/proximity.js";
3
4let nextMessageId = 1;
5
6export function broadcastSpeech (sessions, simulation, speakerSession, rawText)
7{
8 const maxChars = Math.max(1, Math.round(simulation.settings.chatMaxCharacters || 100));
9 const text = String(rawText ?? "").trim().slice(0, maxChars);
10 if (!text)
11 { return; }
12
13 const speakerPos = simulation.positionOf(speakerSession.entityId);
14 if (!speakerPos)
15 { return; }
16
17 const messageId = nextMessageId++;
18 const createdAt = Date.now();
19 for (const other of sessions.values())
20 {
21 if (!other.entityId)
22 { continue; }
23 let readable = text;
24 if (other !== speakerSession)
25 {
26 const listenerPos = simulation.positionOf(other.entityId);
27 if (!listenerPos)
28 { continue; }
29 const distance = Math.hypot(listenerPos.tileX - speakerPos.tileX, listenerPos.tileY - speakerPos.tileY);
30 const readability = speechReadability(distance, CHUNK_SIZE);
31 if (readability <= 0)
32 { continue; }
33 readable = obscureSpeech(text, readability, messageId ^ other.id);
34 if (!readable)
35 { continue; }
36 }
37 if (other.socket.readyState === 1)
38 {
39 other.socket.send(JSON.stringify({
40 type: MessageType.chatBubble,
41 messageId,
42 entityId: speakerSession.entityId,
43 characterId: speakerSession.characterId,
44 text: readable,
45 createdAt
46 }));
47 }
48 }
49}
server/src/ecs/components.js added +17 −0
@@ -0,0 +1,17 @@
1 export const Component = Object.freeze({
2 position: "position",
3 movement: "movement",
4 path: "path",
5 appearance: "appearance",
6 character: "character",
7 networkIdentity: "networkIdentity",
8 chunkLoader: "chunkLoader",
9 persistent: "persistent",
10 inventory: "inventory",
11 equipment: "equipment",
12 currency: "currency",
13 vault: "vault",
14 health: "health",
15 creature: "creature",
16 spawnOrigin: "spawnOrigin"
17 });
@@ -0,0 +1,17 @@
1export const Component = Object.freeze({
2 position: "position",
3 movement: "movement",
4 path: "path",
5 appearance: "appearance",
6 character: "character",
7 networkIdentity: "networkIdentity",
8 chunkLoader: "chunkLoader",
9 persistent: "persistent",
10 inventory: "inventory",
11 equipment: "equipment",
12 currency: "currency",
13 vault: "vault",
14 health: "health",
15 creature: "creature",
16 spawnOrigin: "spawnOrigin"
17});
server/src/ecs/serialize.js added +153 −0
@@ -0,0 +1,153 @@
1 import { Component } from "./components.js";
2 import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4
5 function bodySprite (sex)
6 {
7 const key = sex === "female" ? "player-body-female" : "player-body-male";
8 return spriteImageName("character", key, key);
9 }
10
11 export function normalizeMobileComponents (components)
12 {
13 const next = { ...(components ?? {}) };
14 if (next.movement && Array.isArray(next.movement.path) && !next.path)
15 {
16 const { path, ...movement } = next.movement;
17 next.movement = movement;
18 next.path = { tiles: path };
19 }
20 if (next.movement && !next.path)
21 { next.path = { tiles: [] }; }
22 if (next.character && Object.prototype.hasOwnProperty.call(next.character, "sessionId"))
23 {
24 const { sessionId, ...character } = next.character;
25 next.character = character;
26 if (sessionId != null)
27 { next.networkIdentity = { ...(next.networkIdentity ?? {}), sessionId }; }
28 }
29 return next;
30 }
31
32 export function serializeEntity (ecs, entityId)
33 {
34 const handle = ecs.handleOf(entityId);
35 if (handle == null)
36 { return null; }
37 return {
38 entityId,
39 components: structuredClone(ecs.componentsOf(handle))
40 };
41 }
42
43 export function deserializeEntity (ecs, payload)
44 {
45 const handle = ecs.spawn(payload.entityId);
46 const components = normalizeMobileComponents(payload.components);
47 for (const [name, data] of Object.entries(components))
48 { ecs.add(handle, name, structuredClone(data)); }
49 return payload.entityId;
50 }
51
52 export function publicEntityView (ecs, entityId)
53 {
54 const handle = ecs.handleOf(entityId);
55 if (handle == null)
56 { return null; }
57 const position = ecs.get(handle, Component.position);
58 if (!position)
59 { return null; }
60 const movement = ecs.get(handle, Component.movement);
61 const appearance = ecs.get(handle, Component.appearance);
62 const character = ecs.get(handle, Component.character);
63 const layers = appearanceLayers(ecs, handle, appearance);
64 return {
65 entityId,
66 tileX: position.tileX,
67 tileY: position.tileY,
68 gait: movement?.gait ?? "walk",
69 sex: appearance?.sex ?? null,
70 firstName: appearance?.firstName ?? "",
71 lastName: appearance?.lastName ?? "",
72 characterId: character?.characterId ?? null,
73 sprite: layers[0]?.sprite ?? null,
74 layers
75 };
76 }
77
78 export function appearanceLayers (ecs, handle, appearance)
79 {
80 const sprite = appearance?.sprite ?? bodySprite(appearance?.sex);
81 const layers = [{ sprite }];
82 const equipment = ecs.get(handle, Component.equipment);
83 for (const slot of EQUIPMENT_DRAW_ORDER)
84 {
85 const worn = equipment?.slots?.[slot];
86 if (!worn)
87 { continue; }
88 const overlay = itemEquipSprite(worn.itemId);
89 if (overlay)
90 { layers.push({ sprite: overlay }); }
91 }
92 return layers;
93 }
94
95 export function replicationSpawn (view)
96 {
97 if (!view)
98 { return null; }
99 return {
100 type: "entity-spawn",
101 entityId: view.entityId,
102 characterId: view.characterId,
103 tileX: view.tileX,
104 tileY: view.tileY,
105 gait: view.gait,
106 sex: view.sex,
107 firstName: view.firstName,
108 lastName: view.lastName,
109 sprite: view.sprite ?? null,
110 layers: view.layers ?? []
111 };
112 }
113
114 export function replicationMove (view, fromTileX, fromTileY)
115 {
116 if (!view)
117 { return null; }
118 return {
119 type: "entity-move",
120 entityId: view.entityId,
121 tileX: view.tileX,
122 tileY: view.tileY,
123 gait: view.gait,
124 fromTileX,
125 fromTileY
126 };
127 }
128
129 export function replicationAppearance (view)
130 {
131 if (!view)
132 { return null; }
133 return {
134 type: "entity-appearance",
135 entityId: view.entityId,
136 tileX: view.tileX,
137 tileY: view.tileY,
138 sprite: view.sprite ?? null,
139 layers: view.layers ?? []
140 };
141 }
142
143 export function replicationDespawn (view)
144 {
145 if (!view)
146 { return null; }
147 return {
148 type: "entity-despawn",
149 entityId: view.entityId,
150 tileX: view.tileX,
151 tileY: view.tileY
152 };
153 }
@@ -0,0 +1,153 @@
1import { Component } from "./components.js";
2import { EQUIPMENT_DRAW_ORDER, itemEquipSprite } from "../../../shared/definitions/items.js";
3import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
4
5function bodySprite (sex)
6{
7 const key = sex === "female" ? "player-body-female" : "player-body-male";
8 return spriteImageName("character", key, key);
9}
10
11export function normalizeMobileComponents (components)
12{
13 const next = { ...(components ?? {}) };
14 if (next.movement && Array.isArray(next.movement.path) && !next.path)
15 {
16 const { path, ...movement } = next.movement;
17 next.movement = movement;
18 next.path = { tiles: path };
19 }
20 if (next.movement && !next.path)
21 { next.path = { tiles: [] }; }
22 if (next.character && Object.prototype.hasOwnProperty.call(next.character, "sessionId"))
23 {
24 const { sessionId, ...character } = next.character;
25 next.character = character;
26 if (sessionId != null)
27 { next.networkIdentity = { ...(next.networkIdentity ?? {}), sessionId }; }
28 }
29 return next;
30}
31
32export function serializeEntity (ecs, entityId)
33{
34 const handle = ecs.handleOf(entityId);
35 if (handle == null)
36 { return null; }
37 return {
38 entityId,
39 components: structuredClone(ecs.componentsOf(handle))
40 };
41}
42
43export function deserializeEntity (ecs, payload)
44{
45 const handle = ecs.spawn(payload.entityId);
46 const components = normalizeMobileComponents(payload.components);
47 for (const [name, data] of Object.entries(components))
48 { ecs.add(handle, name, structuredClone(data)); }
49 return payload.entityId;
50}
51
52export function publicEntityView (ecs, entityId)
53{
54 const handle = ecs.handleOf(entityId);
55 if (handle == null)
56 { return null; }
57 const position = ecs.get(handle, Component.position);
58 if (!position)
59 { return null; }
60 const movement = ecs.get(handle, Component.movement);
61 const appearance = ecs.get(handle, Component.appearance);
62 const character = ecs.get(handle, Component.character);
63 const layers = appearanceLayers(ecs, handle, appearance);
64 return {
65 entityId,
66 tileX: position.tileX,
67 tileY: position.tileY,
68 gait: movement?.gait ?? "walk",
69 sex: appearance?.sex ?? null,
70 firstName: appearance?.firstName ?? "",
71 lastName: appearance?.lastName ?? "",
72 characterId: character?.characterId ?? null,
73 sprite: layers[0]?.sprite ?? null,
74 layers
75 };
76}
77
78export function appearanceLayers (ecs, handle, appearance)
79{
80 const sprite = appearance?.sprite ?? bodySprite(appearance?.sex);
81 const layers = [{ sprite }];
82 const equipment = ecs.get(handle, Component.equipment);
83 for (const slot of EQUIPMENT_DRAW_ORDER)
84 {
85 const worn = equipment?.slots?.[slot];
86 if (!worn)
87 { continue; }
88 const overlay = itemEquipSprite(worn.itemId);
89 if (overlay)
90 { layers.push({ sprite: overlay }); }
91 }
92 return layers;
93}
94
95export function replicationSpawn (view)
96{
97 if (!view)
98 { return null; }
99 return {
100 type: "entity-spawn",
101 entityId: view.entityId,
102 characterId: view.characterId,
103 tileX: view.tileX,
104 tileY: view.tileY,
105 gait: view.gait,
106 sex: view.sex,
107 firstName: view.firstName,
108 lastName: view.lastName,
109 sprite: view.sprite ?? null,
110 layers: view.layers ?? []
111 };
112}
113
114export function replicationMove (view, fromTileX, fromTileY)
115{
116 if (!view)
117 { return null; }
118 return {
119 type: "entity-move",
120 entityId: view.entityId,
121 tileX: view.tileX,
122 tileY: view.tileY,
123 gait: view.gait,
124 fromTileX,
125 fromTileY
126 };
127}
128
129export function replicationAppearance (view)
130{
131 if (!view)
132 { return null; }
133 return {
134 type: "entity-appearance",
135 entityId: view.entityId,
136 tileX: view.tileX,
137 tileY: view.tileY,
138 sprite: view.sprite ?? null,
139 layers: view.layers ?? []
140 };
141}
142
143export function replicationDespawn (view)
144{
145 if (!view)
146 { return null; }
147 return {
148 type: "entity-despawn",
149 entityId: view.entityId,
150 tileX: view.tileX,
151 tileY: view.tileY
152 };
153}
server/src/ecs/world.js +100 −19
@@ -2,26 +2,92 @@ export class EcsWorld
2 2 {
3 3 constructor ()
4 4 {
5 this.nextId = 1;
5 this.nextHandle = 1;
6 this.nextEntityId = 1;
7 this.freeHandles = [];
6 8 this.alive = new Set();
9 this.entityIdByHandle = new Map();
10 this.handleByEntityId = new Map();
7 11 this.stores = new Map();
8 12 }
9 13
14 spawn (entityId = null)
15 {
16 const id = entityId == null ? this.nextEntityId : Number(entityId);
17 if (!Number.isInteger(id) || id < 1)
18 {
19 const error = new Error("Entity id must be a positive integer.");
20 error.userFacing = true;
21 throw error;
22 }
23 if (this.handleByEntityId.has(id))
24 {
25 const error = new Error(`Entity ${id} already exists.`);
26 error.userFacing = true;
27 throw error;
28 }
29 if (id >= this.nextEntityId)
30 { this.nextEntityId = id + 1; }
31
32 const handle = this.freeHandles.pop() ?? this.nextHandle++;
33 this.alive.add(handle);
34 this.entityIdByHandle.set(handle, id);
35 this.handleByEntityId.set(id, handle);
36 return handle;
37 }
38
10 39 entity ()
11 40 {
12 const id = this.nextId++;
13 this.alive.add(id);
14 return id;
41 return this.spawn();
15 42 }
16 43
17 destroy (id)
44 adopt (entityId)
18 45 {
19 this.alive.delete(id);
46 return this.spawn(entityId);
47 }
48
49 handleOf (entityId)
50 {
51 return this.handleByEntityId.get(entityId) ?? null;
52 }
53
54 entityIdOf (handle)
55 {
56 return this.entityIdByHandle.get(handle) ?? null;
57 }
58
59 hasEntity (entityId)
60 {
61 return this.handleByEntityId.has(entityId);
62 }
63
64 isAlive (handle)
65 {
66 return this.alive.has(handle);
67 }
68
69 destroy (handle)
70 {
71 if (!this.alive.has(handle))
72 { return; }
73 const entityId = this.entityIdByHandle.get(handle);
74 this.alive.delete(handle);
75 this.entityIdByHandle.delete(handle);
76 if (entityId != null)
77 { this.handleByEntityId.delete(entityId); }
20 78 for (const store of this.stores.values())
21 { store.delete(id); }
79 { store.delete(handle); }
80 this.freeHandles.push(handle);
22 81 }
23 82
24 add (id, name, data)
83 destroyEntity (entityId)
84 {
85 const handle = this.handleOf(entityId);
86 if (handle != null)
87 { this.destroy(handle); }
88 }
89
90 add (handle, name, data)
25 91 {
26 92 let store = this.stores.get(name);
27 93 if (!store)
@@ -29,23 +95,34 @@ export class EcsWorld
29 95 store = new Map();
30 96 this.stores.set(name, store);
31 97 }
32 store.set(id, data);
98 store.set(handle, data);
33 99 return data;
34 100 }
35 101
36 get (id, name)
102 get (handle, name)
37 103 {
38 return this.stores.get(name)?.get(id);
104 return this.stores.get(name)?.get(handle);
39 105 }
40 106
41 has (id, name)
107 has (handle, name)
42 108 {
43 return this.stores.get(name)?.has(id) ?? false;
109 return this.stores.get(name)?.has(handle) ?? false;
44 110 }
45 111
46 remove (id, name)
112 remove (handle, name)
47 113 {
48 this.stores.get(name)?.delete(id);
114 this.stores.get(name)?.delete(handle);
115 }
116
117 componentsOf (handle)
118 {
119 const components = {};
120 for (const [name, store] of this.stores)
121 {
122 if (store.has(handle))
123 { components[name] = store.get(handle); }
124 }
125 return components;
49 126 }
50 127
51 128 query (...names)
@@ -55,16 +132,20 @@ export class EcsWorld
55 132 { return []; }
56 133
57 134 const results = [];
58 for (const [id, first] of primary)
135 for (const [handle, first] of primary)
59 136 {
60 if (!this.alive.has(id))
137 if (!this.alive.has(handle))
61 138 { continue; }
62 139
63 const record = { id, [names[0]]: first };
140 const record = {
141 handle,
142 entityId: this.entityIdByHandle.get(handle),
143 [names[0]]: first
144 };
64 145 let matched = true;
65 146 for (let i = 1; i < names.length; i++)
66 147 {
67 const component = this.get(id, names[i]);
148 const component = this.get(handle, names[i]);
68 149 if (!component)
69 150 {
70 151 matched = false;
@@ -2,26 +2,92 @@ export class EcsWorld
2{
2{
3 constructor ()
3 constructor ()
4 {
4 {
5 this.nextId = 1;
5 this.nextHandle = 1;
6 this.nextEntityId = 1;
7 this.freeHandles = [];
6 this.alive = new Set();
8 this.alive = new Set();
9 this.entityIdByHandle = new Map();
10 this.handleByEntityId = new Map();
7 this.stores = new Map();
11 this.stores = new Map();
8 }
12 }
9
13
14 spawn (entityId = null)
15 {
16 const id = entityId == null ? this.nextEntityId : Number(entityId);
17 if (!Number.isInteger(id) || id < 1)
18 {
19 const error = new Error("Entity id must be a positive integer.");
20 error.userFacing = true;
21 throw error;
22 }
23 if (this.handleByEntityId.has(id))
24 {
25 const error = new Error(`Entity ${id} already exists.`);
26 error.userFacing = true;
27 throw error;
28 }
29 if (id >= this.nextEntityId)
30 { this.nextEntityId = id + 1; }
31
32 const handle = this.freeHandles.pop() ?? this.nextHandle++;
33 this.alive.add(handle);
34 this.entityIdByHandle.set(handle, id);
35 this.handleByEntityId.set(id, handle);
36 return handle;
37 }
38
10 entity ()
39 entity ()
11 {
40 {
12 const id = this.nextId++;
41 return this.spawn();
13 this.alive.add(id);
14 return id;
15 }
42 }
16
43
17 destroy (id)
44 adopt (entityId)
18 {
45 {
19 this.alive.delete(id);
46 return this.spawn(entityId);
47 }
48
49 handleOf (entityId)
50 {
51 return this.handleByEntityId.get(entityId) ?? null;
52 }
53
54 entityIdOf (handle)
55 {
56 return this.entityIdByHandle.get(handle) ?? null;
57 }
58
59 hasEntity (entityId)
60 {
61 return this.handleByEntityId.has(entityId);
62 }
63
64 isAlive (handle)
65 {
66 return this.alive.has(handle);
67 }
68
69 destroy (handle)
70 {
71 if (!this.alive.has(handle))
72 { return; }
73 const entityId = this.entityIdByHandle.get(handle);
74 this.alive.delete(handle);
75 this.entityIdByHandle.delete(handle);
76 if (entityId != null)
77 { this.handleByEntityId.delete(entityId); }
20 for (const store of this.stores.values())
78 for (const store of this.stores.values())
21 { store.delete(id); }
79 { store.delete(handle); }
80 this.freeHandles.push(handle);
22 }
81 }
23
82
24 add (id, name, data)
83 destroyEntity (entityId)
84 {
85 const handle = this.handleOf(entityId);
86 if (handle != null)
87 { this.destroy(handle); }
88 }
89
90 add (handle, name, data)
25 {
91 {
26 let store = this.stores.get(name);
92 let store = this.stores.get(name);
27 if (!store)
93 if (!store)
@@ -29,23 +95,34 @@ export class EcsWorld
29 store = new Map();
95 store = new Map();
30 this.stores.set(name, store);
96 this.stores.set(name, store);
31 }
97 }
32 store.set(id, data);
98 store.set(handle, data);
33 return data;
99 return data;
34 }
100 }
35
101
36 get (id, name)
102 get (handle, name)
37 {
103 {
38 return this.stores.get(name)?.get(id);
104 return this.stores.get(name)?.get(handle);
39 }
105 }
40
106
41 has (id, name)
107 has (handle, name)
42 {
108 {
43 return this.stores.get(name)?.has(id) ?? false;
109 return this.stores.get(name)?.has(handle) ?? false;
44 }
110 }
45
111
46 remove (id, name)
112 remove (handle, name)
47 {
113 {
48 this.stores.get(name)?.delete(id);
114 this.stores.get(name)?.delete(handle);
115 }
116
117 componentsOf (handle)
118 {
119 const components = {};
120 for (const [name, store] of this.stores)
121 {
122 if (store.has(handle))
123 { components[name] = store.get(handle); }
124 }
125 return components;
49 }
126 }
50
127
51 query (...names)
128 query (...names)
@@ -55,16 +132,20 @@ export class EcsWorld
55 { return []; }
132 { return []; }
56
133
57 const results = [];
134 const results = [];
58 for (const [id, first] of primary)
135 for (const [handle, first] of primary)
59 {
136 {
60 if (!this.alive.has(id))
137 if (!this.alive.has(handle))
61 { continue; }
138 { continue; }
62
139
63 const record = { id, [names[0]]: first };
140 const record = {
141 handle,
142 entityId: this.entityIdByHandle.get(handle),
143 [names[0]]: first
144 };
64 let matched = true;
145 let matched = true;
65 for (let i = 1; i < names.length; i++)
146 for (let i = 1; i < names.length; i++)
66 {
147 {
67 const component = this.get(id, names[i]);
148 const component = this.get(handle, names[i]);
68 if (!component)
149 if (!component)
69 {
150 {
70 matched = false;
151 matched = false;
server/src/gateway/http.js +3 −3
@@ -80,9 +80,9 @@ function safeJoin (root, relativePath)
80 80
81 81 function spriteCatalogFor (clientDir)
82 82 {
83 if (!spriteCatalogFor.cache)
84 { spriteCatalogFor.cache = buildSpriteCatalog(join(clientDir, "assets")); }
85 return spriteCatalogFor.cache;
83 // Rebuild each request so deleting optional companions (e.g. *-bloom) is picked up
84 // without a process restart.
85 return buildSpriteCatalog(join(clientDir, "assets"));
86 86 }
87 87
88 88 export function repoRootFrom (url)
@@ -80,9 +80,9 @@ function safeJoin (root, relativePath)
80
80
81function spriteCatalogFor (clientDir)
81function spriteCatalogFor (clientDir)
82{
82{
83 if (!spriteCatalogFor.cache)
83 // Rebuild each request so deleting optional companions (e.g. *-bloom) is picked up
84 { spriteCatalogFor.cache = buildSpriteCatalog(join(clientDir, "assets")); }
84 // without a process restart.
85 return spriteCatalogFor.cache;
85 return buildSpriteCatalog(join(clientDir, "assets"));
86}
86}
87
87
88export function repoRootFrom (url)
88export function repoRootFrom (url)
server/src/gateway/websocket.js +215 −38
@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";
2 2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 import { broadcastSpeech } from "../chat/speech.js";
5 6
6 7 let nextSessionId = 1;
7 8
@@ -122,6 +123,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
122 123 friends.remove(session.characterId, message.characterId);
123 124 pushFriends(session.characterId, message.characterId);
124 125 break;
126 case MessageType.chatSay:
127 requirePlaying(session);
128 broadcastSpeech(sessions, simulation, session, message.text);
129 break;
130 case MessageType.dropItem:
131 requirePlaying(session);
132 simulation.enqueue(session.id, {
133 type: "drop-item",
134 characterId: session.characterId,
135 slotIndex: message.slotIndex | 0,
136 quantity: message.quantity ?? null
137 });
138 break;
139 case MessageType.pickupItem:
140 requirePlaying(session);
141 simulation.enqueue(session.id, {
142 type: "pickup-item",
143 characterId: session.characterId,
144 groundItemId: message.groundItemId | 0
145 });
146 break;
147 case MessageType.equipItem:
148 requirePlaying(session);
149 simulation.enqueue(session.id, {
150 type: "equip-item",
151 characterId: session.characterId,
152 slotIndex: message.slotIndex | 0
153 });
154 break;
155 case MessageType.unequipItem:
156 requirePlaying(session);
157 simulation.enqueue(session.id, {
158 type: "unequip-item",
159 characterId: session.characterId,
160 equipSlot: message.equipSlot
161 });
162 break;
163 case MessageType.openBank:
164 requirePlaying(session);
165 simulation.enqueue(session.id, {
166 type: "open-bank",
167 characterId: session.characterId
168 });
169 break;
170 case MessageType.bankDeposit:
171 requirePlaying(session);
172 simulation.enqueue(session.id, {
173 type: message.money ? "bank-deposit-money" : "bank-deposit",
174 characterId: session.characterId,
175 slotIndex: message.slotIndex | 0,
176 quantity: message.quantity ?? null,
177 amount: message.amount | 0
178 });
179 break;
180 case MessageType.bankWithdraw:
181 requirePlaying(session);
182 simulation.enqueue(session.id, {
183 type: message.money ? "bank-withdraw-money" : "bank-withdraw",
184 characterId: session.characterId,
185 slotIndex: message.slotIndex | 0,
186 quantity: message.quantity ?? null,
187 amount: message.amount | 0
188 });
189 break;
190 case MessageType.claimInheritance:
191 requirePlaying(session);
192 {
193 const inheritance = stateDb.getInheritance(session.account.account_id);
194 simulation.enqueue(session.id, {
195 type: "claim-inheritance",
196 characterId: session.characterId,
197 stacks: (inheritance.slots ?? []).filter(Boolean),
198 currency: inheritance.currency | 0
199 });
200 }
201 break;
125 202 case MessageType.editorLoadChunk:
126 203 requireAdmin(session);
127 204 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -183,30 +260,34 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
183 260 }
184 261 session.characterId = character.character_id;
185 262 session.entityId = simulation.spawnCharacter(session.id, character);
186 const appearance = simulation.ecs.get(session.entityId, "appearance");
187 const position = simulation.ecs.get(session.entityId, "position");
188 const movement = simulation.ecs.get(session.entityId, "movement");
263 const spawned = simulation.entityRecord(session.entityId);
189 264 send(session, {
190 265 type: MessageType.enterWorld,
191 266 entityId: session.entityId,
192 267 characterId: session.characterId,
193 tileX: position.tileX,
194 tileY: position.tileY,
195 gait: movement.gait,
196 sex: appearance.sex,
197 firstName: appearance.firstName,
198 lastName: appearance.lastName,
268 tileX: spawned.tileX,
269 tileY: spawned.tileY,
270 gait: spawned.gait,
271 sex: spawned.sex,
272 firstName: spawned.firstName,
273 lastName: spawned.lastName,
274 layers: spawned.layers ?? [],
199 275 settings: simulation.settings,
200 276 worldTime: simulation.worldTime()
201 277 });
202 278 syncSubscriptions(session, true);
203 279 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
280 const bag = simulation.bagOf(session.entityId);
281 if (bag)
282 { send(session, { type: MessageType.inventory, ...bag }); }
283 publishReplication(simulation.drainReplication());
204 284 }
205 285
206 286 function leaveWorld (session)
207 287 {
208 288 if (session.characterId)
209 289 { simulation.despawnCharacter(session.characterId); }
290 publishReplication(simulation.drainReplication());
210 291 session.characterId = null;
211 292 session.entityId = null;
212 293 session.subscribed.clear();
@@ -216,7 +297,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
216 297 {
217 298 if (!session.entityId)
218 299 { return; }
219 const position = simulation.ecs.get(session.entityId, "position");
300 const position = simulation.positionOf(session.entityId);
220 301 if (!position)
221 302 { return; }
222 303
@@ -308,6 +389,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
308 389
309 390 function onTickResult (result)
310 391 {
392 publishReplication(result.replication ?? []);
311 393 for (const event of result.events)
312 394 {
313 395 if (event.type === "command-error")
@@ -317,43 +399,138 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
317 399 { send(session, { type: MessageType.error, message: event.message }); }
318 400 continue;
319 401 }
320 if (event.type === "entity-move")
402 if (event.type === "inventory")
321 403 {
322 const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY));
323 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
324 for (const session of sessions.values())
404 const session = sessions.get(event.sessionId);
405 if (!session)
406 { continue; }
407 send(session, {
408 type: MessageType.inventory,
409 inventory: event.inventory,
410 equipment: event.equipment,
411 currency: event.currency,
412 vault: event.vault,
413 vaultCurrency: event.vaultCurrency
414 });
415 if (event.bank)
325 416 {
326 if (!session.entityId)
327 { continue; }
328 const seesFrom = session.subscribed.has(fromKey);
329 const seesTo = session.subscribed.has(toKey);
330 if (seesTo)
331 {
332 send(session, {
333 type: MessageType.entityMove,
334 entityId: event.entityId,
335 characterId: event.characterId,
336 tileX: event.tileX,
337 tileY: event.tileY,
338 gait: event.gait,
339 sex: event.sex,
340 firstName: event.firstName,
341 lastName: event.lastName
342 });
343 }
344 else if (seesFrom)
345 {
346 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
347 }
348 if (session.entityId === event.entityId)
349 { syncSubscriptions(session, false); }
417 send(session, {
418 type: MessageType.bankSnapshot,
419 vault: event.vault,
420 vaultCurrency: event.vaultCurrency,
421 currency: event.currency,
422 inheritance: stateDb.getInheritance(session.account.account_id)
423 });
350 424 }
425 continue;
351 426 }
427 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance")
428 { publishEntity(event); }
352 429 }
353 430 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
354 431 { broadcastStatus(); }
355 432 }
356 433
434 function publishReplication (events)
435 {
436 for (const event of events ?? [])
437 { publishEntity(event); }
438 }
439
440 function publishEntity (event)
441 {
442 const fromKey = event.fromTileX != null
443 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY))
444 : null;
445 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
446 for (const session of sessions.values())
447 {
448 if (!session.entityId)
449 { continue; }
450 const seesFrom = fromKey ? session.subscribed.has(fromKey) : false;
451 const seesTo = session.subscribed.has(toKey);
452 if (event.type === "entity-spawn")
453 {
454 if (session.entityId === event.entityId || !seesTo)
455 { continue; }
456 send(session, spawnPayload(event));
457 continue;
458 }
459 if (event.type === "entity-despawn")
460 {
461 if (session.entityId === event.entityId || (!seesTo && !seesFrom))
462 { continue; }
463 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
464 continue;
465 }
466 if (event.type === "entity-appearance")
467 {
468 if (!seesTo)
469 { continue; }
470 send(session, {
471 type: MessageType.entityAppearance,
472 entityId: event.entityId,
473 sprite: event.sprite,
474 layers: event.layers ?? []
475 });
476 continue;
477 }
478 if (event.type === "ground-item-appear")
479 {
480 if (!seesTo)
481 { continue; }
482 send(session, { type: MessageType.groundItemAppear, ...event, type: MessageType.groundItemAppear });
483 continue;
484 }
485 if (event.type === "ground-item-despawn")
486 {
487 if (!seesTo)
488 { continue; }
489 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
490 continue;
491 }
492 if (event.type !== "entity-move")
493 { continue; }
494 if (seesTo)
495 {
496 if (!seesFrom)
497 { send(session, spawnPayload(event)); }
498 else
499 {
500 send(session, {
501 type: MessageType.entityMove,
502 entityId: event.entityId,
503 tileX: event.tileX,
504 tileY: event.tileY,
505 gait: event.gait
506 });
507 }
508 }
509 else if (seesFrom)
510 { send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); }
511 if (session.entityId === event.entityId)
512 { syncSubscriptions(session, false); }
513 }
514 }
515
516 function spawnPayload (event)
517 {
518 const record = simulation.entityRecord(event.entityId) ?? event;
519 return {
520 type: MessageType.entitySpawn,
521 entityId: event.entityId,
522 characterId: record.characterId ?? event.characterId ?? null,
523 tileX: event.tileX ?? record.tileX,
524 tileY: event.tileY ?? record.tileY,
525 gait: event.gait ?? record.gait,
526 sex: record.sex ?? event.sex ?? null,
527 firstName: record.firstName ?? event.firstName ?? "",
528 lastName: record.lastName ?? event.lastName ?? "",
529 sprite: record.sprite ?? event.sprite ?? null,
530 layers: record.layers ?? event.layers ?? []
531 };
532 }
533
357 534 return { sessions, onTickResult, wss };
358 535 }
359 536
@@ -2,6 +2,7 @@ import { WebSocketServer } from "ws";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
2import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { broadcastSpeech } from "../chat/speech.js";
5
6
6let nextSessionId = 1;
7let nextSessionId = 1;
7
8
@@ -122,6 +123,82 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
122 friends.remove(session.characterId, message.characterId);
123 friends.remove(session.characterId, message.characterId);
123 pushFriends(session.characterId, message.characterId);
124 pushFriends(session.characterId, message.characterId);
124 break;
125 break;
126 case MessageType.chatSay:
127 requirePlaying(session);
128 broadcastSpeech(sessions, simulation, session, message.text);
129 break;
130 case MessageType.dropItem:
131 requirePlaying(session);
132 simulation.enqueue(session.id, {
133 type: "drop-item",
134 characterId: session.characterId,
135 slotIndex: message.slotIndex | 0,
136 quantity: message.quantity ?? null
137 });
138 break;
139 case MessageType.pickupItem:
140 requirePlaying(session);
141 simulation.enqueue(session.id, {
142 type: "pickup-item",
143 characterId: session.characterId,
144 groundItemId: message.groundItemId | 0
145 });
146 break;
147 case MessageType.equipItem:
148 requirePlaying(session);
149 simulation.enqueue(session.id, {
150 type: "equip-item",
151 characterId: session.characterId,
152 slotIndex: message.slotIndex | 0
153 });
154 break;
155 case MessageType.unequipItem:
156 requirePlaying(session);
157 simulation.enqueue(session.id, {
158 type: "unequip-item",
159 characterId: session.characterId,
160 equipSlot: message.equipSlot
161 });
162 break;
163 case MessageType.openBank:
164 requirePlaying(session);
165 simulation.enqueue(session.id, {
166 type: "open-bank",
167 characterId: session.characterId
168 });
169 break;
170 case MessageType.bankDeposit:
171 requirePlaying(session);
172 simulation.enqueue(session.id, {
173 type: message.money ? "bank-deposit-money" : "bank-deposit",
174 characterId: session.characterId,
175 slotIndex: message.slotIndex | 0,
176 quantity: message.quantity ?? null,
177 amount: message.amount | 0
178 });
179 break;
180 case MessageType.bankWithdraw:
181 requirePlaying(session);
182 simulation.enqueue(session.id, {
183 type: message.money ? "bank-withdraw-money" : "bank-withdraw",
184 characterId: session.characterId,
185 slotIndex: message.slotIndex | 0,
186 quantity: message.quantity ?? null,
187 amount: message.amount | 0
188 });
189 break;
190 case MessageType.claimInheritance:
191 requirePlaying(session);
192 {
193 const inheritance = stateDb.getInheritance(session.account.account_id);
194 simulation.enqueue(session.id, {
195 type: "claim-inheritance",
196 characterId: session.characterId,
197 stacks: (inheritance.slots ?? []).filter(Boolean),
198 currency: inheritance.currency | 0
199 });
200 }
201 break;
125 case MessageType.editorLoadChunk:
202 case MessageType.editorLoadChunk:
126 requireAdmin(session);
203 requireAdmin(session);
127 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
204 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
@@ -183,30 +260,34 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
183 }
260 }
184 session.characterId = character.character_id;
261 session.characterId = character.character_id;
185 session.entityId = simulation.spawnCharacter(session.id, character);
262 session.entityId = simulation.spawnCharacter(session.id, character);
186 const appearance = simulation.ecs.get(session.entityId, "appearance");
263 const spawned = simulation.entityRecord(session.entityId);
187 const position = simulation.ecs.get(session.entityId, "position");
188 const movement = simulation.ecs.get(session.entityId, "movement");
189 send(session, {
264 send(session, {
190 type: MessageType.enterWorld,
265 type: MessageType.enterWorld,
191 entityId: session.entityId,
266 entityId: session.entityId,
192 characterId: session.characterId,
267 characterId: session.characterId,
193 tileX: position.tileX,
268 tileX: spawned.tileX,
194 tileY: position.tileY,
269 tileY: spawned.tileY,
195 gait: movement.gait,
270 gait: spawned.gait,
196 sex: appearance.sex,
271 sex: spawned.sex,
197 firstName: appearance.firstName,
272 firstName: spawned.firstName,
198 lastName: appearance.lastName,
273 lastName: spawned.lastName,
274 layers: spawned.layers ?? [],
199 settings: simulation.settings,
275 settings: simulation.settings,
200 worldTime: simulation.worldTime()
276 worldTime: simulation.worldTime()
201 });
277 });
202 syncSubscriptions(session, true);
278 syncSubscriptions(session, true);
203 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
279 send(session, { type: MessageType.friends, ...friends.snapshot(session.characterId) });
280 const bag = simulation.bagOf(session.entityId);
281 if (bag)
282 { send(session, { type: MessageType.inventory, ...bag }); }
283 publishReplication(simulation.drainReplication());
204 }
284 }
205
285
206 function leaveWorld (session)
286 function leaveWorld (session)
207 {
287 {
208 if (session.characterId)
288 if (session.characterId)
209 { simulation.despawnCharacter(session.characterId); }
289 { simulation.despawnCharacter(session.characterId); }
290 publishReplication(simulation.drainReplication());
210 session.characterId = null;
291 session.characterId = null;
211 session.entityId = null;
292 session.entityId = null;
212 session.subscribed.clear();
293 session.subscribed.clear();
@@ -216,7 +297,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
216 {
297 {
217 if (!session.entityId)
298 if (!session.entityId)
218 { return; }
299 { return; }
219 const position = simulation.ecs.get(session.entityId, "position");
300 const position = simulation.positionOf(session.entityId);
220 if (!position)
301 if (!position)
221 { return; }
302 { return; }
222
303
@@ -308,6 +389,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
308
389
309 function onTickResult (result)
390 function onTickResult (result)
310 {
391 {
392 publishReplication(result.replication ?? []);
311 for (const event of result.events)
393 for (const event of result.events)
312 {
394 {
313 if (event.type === "command-error")
395 if (event.type === "command-error")
@@ -317,43 +399,138 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
317 { send(session, { type: MessageType.error, message: event.message }); }
399 { send(session, { type: MessageType.error, message: event.message }); }
318 continue;
400 continue;
319 }
401 }
320 if (event.type === "entity-move")
402 if (event.type === "inventory")
321 {
403 {
322 const fromKey = chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY));
404 const session = sessions.get(event.sessionId);
323 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
405 if (!session)
324 for (const session of sessions.values())
406 { continue; }
407 send(session, {
408 type: MessageType.inventory,
409 inventory: event.inventory,
410 equipment: event.equipment,
411 currency: event.currency,
412 vault: event.vault,
413 vaultCurrency: event.vaultCurrency
414 });
415 if (event.bank)
325 {
416 {
326 if (!session.entityId)
417 send(session, {
327 { continue; }
418 type: MessageType.bankSnapshot,
328 const seesFrom = session.subscribed.has(fromKey);
419 vault: event.vault,
329 const seesTo = session.subscribed.has(toKey);
420 vaultCurrency: event.vaultCurrency,
330 if (seesTo)
421 currency: event.currency,
331 {
422 inheritance: stateDb.getInheritance(session.account.account_id)
332 send(session, {
423 });
333 type: MessageType.entityMove,
334 entityId: event.entityId,
335 characterId: event.characterId,
336 tileX: event.tileX,
337 tileY: event.tileY,
338 gait: event.gait,
339 sex: event.sex,
340 firstName: event.firstName,
341 lastName: event.lastName
342 });
343 }
344 else if (seesFrom)
345 {
346 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
347 }
348 if (session.entityId === event.entityId)
349 { syncSubscriptions(session, false); }
350 }
424 }
425 continue;
351 }
426 }
427 if (event.type === "entity-move" || event.type === "ground-item-appear" || event.type === "ground-item-despawn" || event.type === "entity-appearance")
428 { publishEntity(event); }
352 }
429 }
353 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
430 if (simulation.tickIndex % simulation.settings.simulationTickHz === 0)
354 { broadcastStatus(); }
431 { broadcastStatus(); }
355 }
432 }
356
433
434 function publishReplication (events)
435 {
436 for (const event of events ?? [])
437 { publishEntity(event); }
438 }
439
440 function publishEntity (event)
441 {
442 const fromKey = event.fromTileX != null
443 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY))
444 : null;
445 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
446 for (const session of sessions.values())
447 {
448 if (!session.entityId)
449 { continue; }
450 const seesFrom = fromKey ? session.subscribed.has(fromKey) : false;
451 const seesTo = session.subscribed.has(toKey);
452 if (event.type === "entity-spawn")
453 {
454 if (session.entityId === event.entityId || !seesTo)
455 { continue; }
456 send(session, spawnPayload(event));
457 continue;
458 }
459 if (event.type === "entity-despawn")
460 {
461 if (session.entityId === event.entityId || (!seesTo && !seesFrom))
462 { continue; }
463 send(session, { type: MessageType.entityDespawn, entityId: event.entityId });
464 continue;
465 }
466 if (event.type === "entity-appearance")
467 {
468 if (!seesTo)
469 { continue; }
470 send(session, {
471 type: MessageType.entityAppearance,
472 entityId: event.entityId,
473 sprite: event.sprite,
474 layers: event.layers ?? []
475 });
476 continue;
477 }
478 if (event.type === "ground-item-appear")
479 {
480 if (!seesTo)
481 { continue; }
482 send(session, { type: MessageType.groundItemAppear, ...event, type: MessageType.groundItemAppear });
483 continue;
484 }
485 if (event.type === "ground-item-despawn")
486 {
487 if (!seesTo)
488 { continue; }
489 send(session, { type: MessageType.groundItemDespawn, groundItemId: event.groundItemId });
490 continue;
491 }
492 if (event.type !== "entity-move")
493 { continue; }
494 if (seesTo)
495 {
496 if (!seesFrom)
497 { send(session, spawnPayload(event)); }
498 else
499 {
500 send(session, {
501 type: MessageType.entityMove,
502 entityId: event.entityId,
503 tileX: event.tileX,
504 tileY: event.tileY,
505 gait: event.gait
506 });
507 }
508 }
509 else if (seesFrom)
510 { send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); }
511 if (session.entityId === event.entityId)
512 { syncSubscriptions(session, false); }
513 }
514 }
515
516 function spawnPayload (event)
517 {
518 const record = simulation.entityRecord(event.entityId) ?? event;
519 return {
520 type: MessageType.entitySpawn,
521 entityId: event.entityId,
522 characterId: record.characterId ?? event.characterId ?? null,
523 tileX: event.tileX ?? record.tileX,
524 tileY: event.tileY ?? record.tileY,
525 gait: event.gait ?? record.gait,
526 sex: record.sex ?? event.sex ?? null,
527 firstName: record.firstName ?? event.firstName ?? "",
528 lastName: record.lastName ?? event.lastName ?? "",
529 sprite: record.sprite ?? event.sprite ?? null,
530 layers: record.layers ?? event.layers ?? []
531 };
532 }
533
357 return { sessions, onTickResult, wss };
534 return { sessions, onTickResult, wss };
358}
535}
359
536
server/src/index.js +7 −9
@@ -29,7 +29,7 @@ function scheduleTick ()
29 29 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
30 30 tickTimer = setTimeout(() =>
31 31 {
32 characters.processDueDeletions();
32 characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId));
33 33 const result = simulation.step();
34 34 gateway.onTickResult(result);
35 35 scheduleTick();
@@ -46,15 +46,13 @@ httpServer.listen(port, () =>
46 46 function shutdown ()
47 47 {
48 48 clearTimeout(tickTimer);
49 for (const session of gateway.sessions.values())
49 simulation.shutdown().finally(() =>
50 50 {
51 if (session.characterId)
52 { simulation.despawnCharacter(session.characterId); }
53 }
54 worldDb.close();
55 stateDb.close();
56 httpServer.close();
57 process.exit(0);
51 worldDb.close();
52 stateDb.close();
53 httpServer.close();
54 process.exit(0);
55 });
58 56 }
59 57
60 58 process.on("SIGINT", shutdown);
@@ -29,7 +29,7 @@ function scheduleTick ()
29 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
29 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
30 tickTimer = setTimeout(() =>
30 tickTimer = setTimeout(() =>
31 {
31 {
32 characters.processDueDeletions();
32 characters.processDueDeletions(Date.now(), (characterId) => simulation.despawnCharacter(characterId));
33 const result = simulation.step();
33 const result = simulation.step();
34 gateway.onTickResult(result);
34 gateway.onTickResult(result);
35 scheduleTick();
35 scheduleTick();
@@ -46,15 +46,13 @@ httpServer.listen(port, () =>
46function shutdown ()
46function shutdown ()
47{
47{
48 clearTimeout(tickTimer);
48 clearTimeout(tickTimer);
49 for (const session of gateway.sessions.values())
49 simulation.shutdown().finally(() =>
50 {
50 {
51 if (session.characterId)
51 worldDb.close();
52 { simulation.despawnCharacter(session.characterId); }
52 stateDb.close();
53 }
53 httpServer.close();
54 worldDb.close();
54 process.exit(0);
55 stateDb.close();
55 });
56 httpServer.close();
57 process.exit(0);
58}
56}
59
57
60process.on("SIGINT", shutdown);
58process.on("SIGINT", shutdown);
server/src/items/bags.js added +358 −0
@@ -0,0 +1,358 @@
1 import { Component } from "../ecs/components.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { itemDefinition, itemSpriteName } from "../../../shared/definitions/items.js";
4 import {
5 emptyEquipment,
6 emptySlots,
7 insertStack,
8 publicEquipment,
9 publicSlots,
10 takeFromSlot
11 } from "../../../shared/items/inventory.js";
12 import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
14
15 export function publicGroundItem (item)
16 {
17 const def = itemDefinition(item.stack?.itemId);
18 return {
19 groundItemId: item.groundItemId,
20 tileX: item.tileX,
21 tileY: item.tileY,
22 itemId: item.stack.itemId,
23 quantity: item.stack.quantity,
24 displayName: def?.displayName ?? "Item",
25 sprite: itemSpriteName(item.stack.itemId),
26 expiresAt: item.expiresAt
27 };
28 }
29
30 export function bagView (ecs, handle)
31 {
32 return {
33 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
34 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
35 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
36 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
37 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
38 };
39 }
40
41 export function handleItemCommand (world, sessionId, command, now)
42 {
43 switch (command.type)
44 {
45 case "drop-item":
46 return dropItem(world, sessionId, command, now);
47 case "pickup-item":
48 return pickupItem(world, sessionId, command);
49 case "equip-item":
50 return equipItem(world, sessionId, command);
51 case "unequip-item":
52 return unequipItem(world, sessionId, command);
53 case "open-bank":
54 return openBank(world, sessionId, command);
55 case "bank-deposit":
56 return bankMove(world, sessionId, command, "inventory", "vault");
57 case "bank-withdraw":
58 return bankMove(world, sessionId, command, "vault", "inventory");
59 case "bank-deposit-money":
60 return bankMoney(world, sessionId, command, "currency", "vault");
61 case "bank-withdraw-money":
62 return bankMoney(world, sessionId, command, "vault", "currency");
63 case "claim-inheritance":
64 return claimInheritance(world, sessionId, command);
65 default:
66 return null;
67 }
68 }
69
70 export function expireGroundItems (world, now)
71 {
72 const events = [];
73 for (const item of [...world.groundItems.values()])
74 {
75 if (item.expiresAt > now)
76 { continue; }
77 removeGroundItem(world, item.groundItemId);
78 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
79 }
80 return events;
81 }
82
83 export function groundItemsInChunk (world, chunkX, chunkY)
84 {
85 return [...world.groundItems.values()]
86 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
87 .map(publicGroundItem);
88 }
89
90 export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
91 {
92 return [...world.groundItems.values()].filter((item) =>
93 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
94 );
95 }
96
97 export function addGroundItem (world, item)
98 {
99 world.groundItems.set(item.groundItemId, item);
100 const key = tileKey(item.tileX, item.tileY);
101 if (!world.groundByTile.has(key))
102 { world.groundByTile.set(key, new Set()); }
103 world.groundByTile.get(key).add(item.groundItemId);
104 }
105
106 export function removeGroundItem (world, groundItemId)
107 {
108 const item = world.groundItems.get(groundItemId);
109 if (!item)
110 { return null; }
111 world.groundItems.delete(groundItemId);
112 const key = tileKey(item.tileX, item.tileY);
113 world.groundByTile.get(key)?.delete(groundItemId);
114 return item;
115 }
116
117 export function replaceGroundItems (world, items)
118 {
119 world.groundItems.clear();
120 world.groundByTile.clear();
121 for (const item of items ?? [])
122 { addGroundItem(world, item); }
123 }
124
125 export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
126 {
127 for (const item of [...world.groundItems.values()])
128 {
129 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
130 { removeGroundItem(world, item.groundItemId); }
131 }
132 for (const item of items ?? [])
133 { addGroundItem(world, item); }
134 }
135
136 function dropItem (world, sessionId, command, now)
137 {
138 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
139 const inventory = ensureInventory(world.ecs, handle);
140 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
141 if (!taken.ok)
142 { throw userError("That inventory slot is empty."); }
143 inventory.slots = taken.slots;
144 const position = world.ecs.get(handle, Component.position);
145 const item = {
146 groundItemId: command.groundItemId,
147 tileX: position.tileX,
148 tileY: position.tileY,
149 stack: taken.taken,
150 droppedAt: now,
151 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
152 source: "player-drop",
153 droppedByCharacterId: command.characterId
154 };
155 addGroundItem(world, item);
156 return {
157 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
158 private: bagView(world.ecs, handle)
159 };
160 }
161
162 function pickupItem (world, sessionId, command)
163 {
164 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
165 const item = world.groundItems.get(command.groundItemId);
166 if (!item)
167 { throw userError("That item is no longer on the ground."); }
168 const position = world.ecs.get(handle, Component.position);
169 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
170 { throw userError("Stand on the item to pick it up."); }
171 const def = itemDefinition(item.stack.itemId);
172 if (!def)
173 { throw userError("Unknown item."); }
174 const inventory = ensureInventory(world.ecs, handle);
175 const inserted = insertStack(inventory.slots, item.stack, def);
176 if (!inserted.ok)
177 { throw userError("Your inventory cannot hold that."); }
178 inventory.slots = inserted.slots;
179 removeGroundItem(world, item.groundItemId);
180 return {
181 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
182 private: bagView(world.ecs, handle)
183 };
184 }
185
186 function equipItem (world, sessionId, command)
187 {
188 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
189 const inventory = ensureInventory(world.ecs, handle);
190 const equipment = ensureEquipment(world.ecs, handle);
191 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
192 if (!taken.ok)
193 { throw userError("That inventory slot is empty."); }
194 const def = itemDefinition(taken.taken.itemId);
195 const slot = def?.equipment?.slot;
196 if (!slot)
197 {
198 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
199 throw userError("That item cannot be equipped.");
200 }
201 const previous = equipment.slots[slot];
202 if (previous)
203 {
204 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
205 if (!back.ok)
206 {
207 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
208 throw userError("No inventory space to unequip the current item.");
209 }
210 inventory.slots = back.slots;
211 }
212 else
213 { inventory.slots = taken.slots; }
214 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
215 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
216 }
217
218 function unequipItem (world, sessionId, command)
219 {
220 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
221 const inventory = ensureInventory(world.ecs, handle);
222 const equipment = ensureEquipment(world.ecs, handle);
223 const worn = equipment.slots[command.equipSlot];
224 if (!worn)
225 { throw userError("Nothing is equipped there."); }
226 const def = itemDefinition(worn.itemId);
227 const inserted = insertStack(inventory.slots, worn, def);
228 if (!inserted.ok)
229 { throw userError("Your inventory cannot hold that."); }
230 inventory.slots = inserted.slots;
231 equipment.slots[command.equipSlot] = null;
232 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
233 }
234
235 function openBank (world, sessionId, command)
236 {
237 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
238 const position = world.ecs.get(handle, Component.position);
239 if (!nearBank(world, position.tileX, position.tileY))
240 { throw userError("Stand next to a bank."); }
241 return { events: [], private: bagView(world.ecs, handle), bank: true };
242 }
243
244 function bankMove (world, sessionId, command, fromKey, toKey)
245 {
246 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
247 requireBank(world, handle);
248 const inventory = ensureInventory(world.ecs, handle);
249 const vault = ensureVault(world.ecs, handle);
250 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
251 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
252 if (!taken.ok)
253 { throw userError("That slot is empty."); }
254 const def = itemDefinition(taken.taken.itemId);
255 const dest = toKey === "vault" ? vault : inventory;
256 const inserted = insertStack(dest.slots, taken.taken, def);
257 if (!inserted.ok)
258 { throw userError("Not enough space."); }
259 if (fromKey === "vault")
260 { vault.slots = taken.slots; }
261 else
262 { inventory.slots = taken.slots; }
263 dest.slots = inserted.slots;
264 return { events: [], private: bagView(world.ecs, handle), bank: true };
265 }
266
267 function bankMoney (world, sessionId, command, fromKey, toKey)
268 {
269 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
270 requireBank(world, handle);
271 const amount = Math.max(0, command.amount | 0);
272 if (!amount)
273 { throw userError("Enter an amount."); }
274 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
275 const vault = ensureVault(world.ecs, handle);
276 const from = fromKey === "vault" ? vault : currency;
277 const to = toKey === "vault" ? vault : currency;
278 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
279 if (fromAmount < amount)
280 { throw userError("Not enough coins."); }
281 if (fromKey === "vault")
282 { vault.currency -= amount; }
283 else
284 { currency.amount -= amount; }
285 if (toKey === "vault")
286 { vault.currency += amount; }
287 else
288 { currency.amount += amount; }
289 return { events: [], private: bagView(world.ecs, handle), bank: true };
290 }
291
292 function claimInheritance (world, sessionId, command)
293 {
294 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
295 requireBank(world, handle);
296 const vault = ensureVault(world.ecs, handle);
297 const remainder = [];
298 for (const stack of command.stacks ?? [])
299 {
300 const def = itemDefinition(stack.itemId);
301 if (!def)
302 {
303 remainder.push(stack);
304 continue;
305 }
306 const inserted = insertStack(vault.slots, stack, def);
307 if (inserted.ok)
308 { vault.slots = inserted.slots; }
309 else
310 { remainder.push(stack); }
311 }
312 vault.currency += command.currency | 0;
313 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
314 }
315
316 function requireBank (world, handle)
317 {
318 const position = world.ecs.get(handle, Component.position);
319 if (!nearBank(world, position.tileX, position.tileY))
320 { throw userError("Stand next to a bank."); }
321 }
322
323 function nearBank (world, tileX, tileY)
324 {
325 for (let dy = -1; dy <= 1; dy++)
326 {
327 for (let dx = -1; dx <= 1; dx++)
328 {
329 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
330 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
331 if (data.blocks[index]?.typeId === BlockType.bank)
332 { return true; }
333 }
334 }
335 return false;
336 }
337
338 function ensureInventory (ecs, handle)
339 {
340 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
341 }
342
343 function ensureEquipment (ecs, handle)
344 {
345 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
346 }
347
348 function ensureVault (ecs, handle)
349 {
350 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
351 }
352
353 function userError (message)
354 {
355 const error = new Error(message);
356 error.userFacing = true;
357 return error;
358 }
@@ -0,0 +1,358 @@
1import { Component } from "../ecs/components.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { itemDefinition, itemSpriteName } from "../../../shared/definitions/items.js";
4import {
5 emptyEquipment,
6 emptySlots,
7 insertStack,
8 publicEquipment,
9 publicSlots,
10 takeFromSlot
11} from "../../../shared/items/inventory.js";
12import { tileKey, tileToChunk, tileToLocal } from "../world/coordinates.js";
13import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
14
15export function publicGroundItem (item)
16{
17 const def = itemDefinition(item.stack?.itemId);
18 return {
19 groundItemId: item.groundItemId,
20 tileX: item.tileX,
21 tileY: item.tileY,
22 itemId: item.stack.itemId,
23 quantity: item.stack.quantity,
24 displayName: def?.displayName ?? "Item",
25 sprite: itemSpriteName(item.stack.itemId),
26 expiresAt: item.expiresAt
27 };
28}
29
30export function bagView (ecs, handle)
31{
32 return {
33 inventory: publicSlots(ecs.get(handle, Component.inventory)?.slots ?? emptySlots()),
34 equipment: publicEquipment(ecs.get(handle, Component.equipment) ?? emptyEquipment()),
35 currency: ecs.get(handle, Component.currency)?.amount ?? 0,
36 vault: publicSlots(ecs.get(handle, Component.vault)?.slots ?? emptySlots()),
37 vaultCurrency: ecs.get(handle, Component.vault)?.currency ?? 0
38 };
39}
40
41export function handleItemCommand (world, sessionId, command, now)
42{
43 switch (command.type)
44 {
45 case "drop-item":
46 return dropItem(world, sessionId, command, now);
47 case "pickup-item":
48 return pickupItem(world, sessionId, command);
49 case "equip-item":
50 return equipItem(world, sessionId, command);
51 case "unequip-item":
52 return unequipItem(world, sessionId, command);
53 case "open-bank":
54 return openBank(world, sessionId, command);
55 case "bank-deposit":
56 return bankMove(world, sessionId, command, "inventory", "vault");
57 case "bank-withdraw":
58 return bankMove(world, sessionId, command, "vault", "inventory");
59 case "bank-deposit-money":
60 return bankMoney(world, sessionId, command, "currency", "vault");
61 case "bank-withdraw-money":
62 return bankMoney(world, sessionId, command, "vault", "currency");
63 case "claim-inheritance":
64 return claimInheritance(world, sessionId, command);
65 default:
66 return null;
67 }
68}
69
70export function expireGroundItems (world, now)
71{
72 const events = [];
73 for (const item of [...world.groundItems.values()])
74 {
75 if (item.expiresAt > now)
76 { continue; }
77 removeGroundItem(world, item.groundItemId);
78 events.push({ type: "ground-item-despawn", ...publicGroundItem(item) });
79 }
80 return events;
81}
82
83export function groundItemsInChunk (world, chunkX, chunkY)
84{
85 return [...world.groundItems.values()]
86 .filter((item) => tileToChunk(item.tileX) === chunkX && tileToChunk(item.tileY) === chunkY)
87 .map(publicGroundItem);
88}
89
90export function groundItemsInRegion (world, regionX, regionY, tileToRegion)
91{
92 return [...world.groundItems.values()].filter((item) =>
93 tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY
94 );
95}
96
97export function addGroundItem (world, item)
98{
99 world.groundItems.set(item.groundItemId, item);
100 const key = tileKey(item.tileX, item.tileY);
101 if (!world.groundByTile.has(key))
102 { world.groundByTile.set(key, new Set()); }
103 world.groundByTile.get(key).add(item.groundItemId);
104}
105
106export function removeGroundItem (world, groundItemId)
107{
108 const item = world.groundItems.get(groundItemId);
109 if (!item)
110 { return null; }
111 world.groundItems.delete(groundItemId);
112 const key = tileKey(item.tileX, item.tileY);
113 world.groundByTile.get(key)?.delete(groundItemId);
114 return item;
115}
116
117export function replaceGroundItems (world, items)
118{
119 world.groundItems.clear();
120 world.groundByTile.clear();
121 for (const item of items ?? [])
122 { addGroundItem(world, item); }
123}
124
125export function setGroundItemsForRegion (world, regionX, regionY, items, tileToRegion)
126{
127 for (const item of [...world.groundItems.values()])
128 {
129 if (tileToRegion(item.tileX) === regionX && tileToRegion(item.tileY) === regionY)
130 { removeGroundItem(world, item.groundItemId); }
131 }
132 for (const item of items ?? [])
133 { addGroundItem(world, item); }
134}
135
136function dropItem (world, sessionId, command, now)
137{
138 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
139 const inventory = ensureInventory(world.ecs, handle);
140 const taken = takeFromSlot(inventory.slots, command.slotIndex, command.quantity ?? null);
141 if (!taken.ok)
142 { throw userError("That inventory slot is empty."); }
143 inventory.slots = taken.slots;
144 const position = world.ecs.get(handle, Component.position);
145 const item = {
146 groundItemId: command.groundItemId,
147 tileX: position.tileX,
148 tileY: position.tileY,
149 stack: taken.taken,
150 droppedAt: now,
151 expiresAt: now + (world.settings.groundItemDespawnDurationMs ?? 600_000),
152 source: "player-drop",
153 droppedByCharacterId: command.characterId
154 };
155 addGroundItem(world, item);
156 return {
157 events: [{ type: "ground-item-appear", ...publicGroundItem(item), stack: item.stack, droppedAt: item.droppedAt, source: item.source, droppedByCharacterId: item.droppedByCharacterId, expiresAt: item.expiresAt }],
158 private: bagView(world.ecs, handle)
159 };
160}
161
162function pickupItem (world, sessionId, command)
163{
164 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
165 const item = world.groundItems.get(command.groundItemId);
166 if (!item)
167 { throw userError("That item is no longer on the ground."); }
168 const position = world.ecs.get(handle, Component.position);
169 if (position.tileX !== item.tileX || position.tileY !== item.tileY)
170 { throw userError("Stand on the item to pick it up."); }
171 const def = itemDefinition(item.stack.itemId);
172 if (!def)
173 { throw userError("Unknown item."); }
174 const inventory = ensureInventory(world.ecs, handle);
175 const inserted = insertStack(inventory.slots, item.stack, def);
176 if (!inserted.ok)
177 { throw userError("Your inventory cannot hold that."); }
178 inventory.slots = inserted.slots;
179 removeGroundItem(world, item.groundItemId);
180 return {
181 events: [{ type: "ground-item-despawn", ...publicGroundItem(item) }],
182 private: bagView(world.ecs, handle)
183 };
184}
185
186function equipItem (world, sessionId, command)
187{
188 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
189 const inventory = ensureInventory(world.ecs, handle);
190 const equipment = ensureEquipment(world.ecs, handle);
191 const taken = takeFromSlot(inventory.slots, command.slotIndex, 1);
192 if (!taken.ok)
193 { throw userError("That inventory slot is empty."); }
194 const def = itemDefinition(taken.taken.itemId);
195 const slot = def?.equipment?.slot;
196 if (!slot)
197 {
198 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
199 throw userError("That item cannot be equipped.");
200 }
201 const previous = equipment.slots[slot];
202 if (previous)
203 {
204 const back = insertStack(taken.slots, previous, itemDefinition(previous.itemId));
205 if (!back.ok)
206 {
207 inventory.slots = insertStack(inventory.slots, taken.taken, def).slots;
208 throw userError("No inventory space to unequip the current item.");
209 }
210 inventory.slots = back.slots;
211 }
212 else
213 { inventory.slots = taken.slots; }
214 equipment.slots[slot] = { ...taken.taken, quantity: 1 };
215 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
216}
217
218function unequipItem (world, sessionId, command)
219{
220 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
221 const inventory = ensureInventory(world.ecs, handle);
222 const equipment = ensureEquipment(world.ecs, handle);
223 const worn = equipment.slots[command.equipSlot];
224 if (!worn)
225 { throw userError("Nothing is equipped there."); }
226 const def = itemDefinition(worn.itemId);
227 const inserted = insertStack(inventory.slots, worn, def);
228 if (!inserted.ok)
229 { throw userError("Your inventory cannot hold that."); }
230 inventory.slots = inserted.slots;
231 equipment.slots[command.equipSlot] = null;
232 return { events: [], private: bagView(world.ecs, handle), appearanceChanged: true };
233}
234
235function openBank (world, sessionId, command)
236{
237 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
238 const position = world.ecs.get(handle, Component.position);
239 if (!nearBank(world, position.tileX, position.tileY))
240 { throw userError("Stand next to a bank."); }
241 return { events: [], private: bagView(world.ecs, handle), bank: true };
242}
243
244function bankMove (world, sessionId, command, fromKey, toKey)
245{
246 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
247 requireBank(world, handle);
248 const inventory = ensureInventory(world.ecs, handle);
249 const vault = ensureVault(world.ecs, handle);
250 const fromSlots = fromKey === "vault" ? vault.slots : inventory.slots;
251 const taken = takeFromSlot(fromSlots, command.slotIndex, command.quantity ?? null);
252 if (!taken.ok)
253 { throw userError("That slot is empty."); }
254 const def = itemDefinition(taken.taken.itemId);
255 const dest = toKey === "vault" ? vault : inventory;
256 const inserted = insertStack(dest.slots, taken.taken, def);
257 if (!inserted.ok)
258 { throw userError("Not enough space."); }
259 if (fromKey === "vault")
260 { vault.slots = taken.slots; }
261 else
262 { inventory.slots = taken.slots; }
263 dest.slots = inserted.slots;
264 return { events: [], private: bagView(world.ecs, handle), bank: true };
265}
266
267function bankMoney (world, sessionId, command, fromKey, toKey)
268{
269 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
270 requireBank(world, handle);
271 const amount = Math.max(0, command.amount | 0);
272 if (!amount)
273 { throw userError("Enter an amount."); }
274 const currency = world.ecs.get(handle, Component.currency) ?? world.ecs.add(handle, Component.currency, { amount: 0 });
275 const vault = ensureVault(world.ecs, handle);
276 const from = fromKey === "vault" ? vault : currency;
277 const to = toKey === "vault" ? vault : currency;
278 const fromAmount = fromKey === "vault" ? vault.currency : currency.amount;
279 if (fromAmount < amount)
280 { throw userError("Not enough coins."); }
281 if (fromKey === "vault")
282 { vault.currency -= amount; }
283 else
284 { currency.amount -= amount; }
285 if (toKey === "vault")
286 { vault.currency += amount; }
287 else
288 { currency.amount += amount; }
289 return { events: [], private: bagView(world.ecs, handle), bank: true };
290}
291
292function claimInheritance (world, sessionId, command)
293{
294 const { handle } = world.requireOwnedEntity(sessionId, command.characterId);
295 requireBank(world, handle);
296 const vault = ensureVault(world.ecs, handle);
297 const remainder = [];
298 for (const stack of command.stacks ?? [])
299 {
300 const def = itemDefinition(stack.itemId);
301 if (!def)
302 {
303 remainder.push(stack);
304 continue;
305 }
306 const inserted = insertStack(vault.slots, stack, def);
307 if (inserted.ok)
308 { vault.slots = inserted.slots; }
309 else
310 { remainder.push(stack); }
311 }
312 vault.currency += command.currency | 0;
313 return { events: [], private: bagView(world.ecs, handle), bank: true, remainder };
314}
315
316function requireBank (world, handle)
317{
318 const position = world.ecs.get(handle, Component.position);
319 if (!nearBank(world, position.tileX, position.tileY))
320 { throw userError("Stand next to a bank."); }
321}
322
323function nearBank (world, tileX, tileY)
324{
325 for (let dy = -1; dy <= 1; dy++)
326 {
327 for (let dx = -1; dx <= 1; dx++)
328 {
329 const data = world.chunkData(tileToChunk(tileX + dx), tileToChunk(tileY + dy));
330 const index = tileToLocal(tileY + dy) * CHUNK_SIZE + tileToLocal(tileX + dx);
331 if (data.blocks[index]?.typeId === BlockType.bank)
332 { return true; }
333 }
334 }
335 return false;
336}
337
338function ensureInventory (ecs, handle)
339{
340 return ecs.get(handle, Component.inventory) ?? ecs.add(handle, Component.inventory, { slots: emptySlots() });
341}
342
343function ensureEquipment (ecs, handle)
344{
345 return ecs.get(handle, Component.equipment) ?? ecs.add(handle, Component.equipment, emptyEquipment());
346}
347
348function ensureVault (ecs, handle)
349{
350 return ecs.get(handle, Component.vault) ?? ecs.add(handle, Component.vault, { slots: emptySlots(), currency: 0 });
351}
352
353function userError (message)
354{
355 const error = new Error(message);
356 error.userFacing = true;
357 return error;
358}
server/src/persistence/stateDb.js +264 −0
@@ -1,4 +1,6 @@
1 1 import { openDatabase } from "./database.js";
2 import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";
3 import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
2 4
3 5 const STATE_SCHEMA = `
4 6 CREATE TABLE IF NOT EXISTS accounts (
@@ -40,6 +42,39 @@ CREATE TABLE IF NOT EXISTS friendships (
40 42 created_at INTEGER NOT NULL,
41 43 PRIMARY KEY (character_id_a, character_id_b)
42 44 );
45
46 CREATE TABLE IF NOT EXISTS persistent_entities (
47 entity_id INTEGER PRIMARY KEY,
48 tile_x INTEGER NOT NULL,
49 tile_y INTEGER NOT NULL,
50 components_blob TEXT NOT NULL
51 );
52
53 CREATE TABLE IF NOT EXISTS character_bags (
54 character_id INTEGER PRIMARY KEY,
55 inventory_blob TEXT NOT NULL,
56 equipment_blob TEXT NOT NULL,
57 currency INTEGER NOT NULL DEFAULT 0,
58 vault_blob TEXT NOT NULL,
59 vault_currency INTEGER NOT NULL DEFAULT 0
60 );
61
62 CREATE TABLE IF NOT EXISTS account_inheritance (
63 account_id INTEGER PRIMARY KEY,
64 slots_blob TEXT NOT NULL,
65 currency INTEGER NOT NULL DEFAULT 0
66 );
67
68 CREATE TABLE IF NOT EXISTS ground_items (
69 ground_item_id INTEGER PRIMARY KEY,
70 tile_x INTEGER NOT NULL,
71 tile_y INTEGER NOT NULL,
72 stack_blob TEXT NOT NULL,
73 dropped_at INTEGER NOT NULL,
74 expires_at INTEGER NOT NULL,
75 source TEXT NOT NULL,
76 dropped_by_character_id INTEGER
77 );
43 78 `;
44 79
45 80 export class StateDatabase
@@ -117,6 +152,7 @@ export class StateDatabase
117 152 }
118 153
119 154 this.db.exec("COMMIT");
155 this.#ensureBag(characterId);
120 156 return this.getCharacter(characterId);
121 157 }
122 158 catch (error)
@@ -145,6 +181,8 @@ export class StateDatabase
145 181 this.db.exec("BEGIN");
146 182 try
147 183 {
184 this.#moveGoodsToInheritance(character);
185 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
148 186 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
149 187 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
150 188 characterId,
@@ -281,6 +319,206 @@ export class StateDatabase
281 319 `).run(fromId, toId);
282 320 }
283 321
322 listPersistentInRegion (minX, minY, maxX, maxY)
323 {
324 return this.db.prepare(`
325 SELECT entity_id, tile_x, tile_y, components_blob
326 FROM persistent_entities
327 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
328 `).all(minX, maxX, minY, maxY);
329 }
330
331 replacePersistentInRegion (minX, minY, maxX, maxY, entities)
332 {
333 this.db.exec("BEGIN");
334 try
335 {
336 this.db.prepare(`
337 DELETE FROM persistent_entities
338 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
339 `).run(minX, maxX, minY, maxY);
340 const insert = this.db.prepare(`
341 INSERT INTO persistent_entities (entity_id, tile_x, tile_y, components_blob)
342 VALUES (?, ?, ?, ?)
343 `);
344 for (const entity of entities)
345 {
346 insert.run(
347 entity.entityId,
348 entity.tileX,
349 entity.tileY,
350 JSON.stringify(entity.payload?.components ?? entity.components)
351 );
352 }
353 this.db.exec("COMMIT");
354 }
355 catch (error)
356 {
357 this.db.exec("ROLLBACK");
358 throw error;
359 }
360 }
361
362 #ensureBag (characterId)
363 {
364 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
365 if (existing)
366 { return parseBag(existing, characterId); }
367 const slots = emptySlots();
368 for (const starter of STARTER_ITEMS)
369 {
370 const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId));
371 if (result.ok)
372 { slots.splice(0, slots.length, ...result.slots); }
373 }
374 this.db.prepare(`
375 INSERT INTO character_bags (
376 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency
377 ) VALUES (?, ?, ?, ?, ?, 0)
378 `).run(
379 characterId,
380 JSON.stringify(slots),
381 JSON.stringify(emptyEquipment()),
382 STARTER_CURRENCY,
383 JSON.stringify(emptySlots())
384 );
385 return this.getBag(characterId);
386 }
387
388 getBag (characterId)
389 {
390 const row = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
391 if (row)
392 { return parseBag(row, characterId); }
393 if (this.getCharacter(characterId))
394 { return this.#ensureBag(characterId); }
395 return null;
396 }
397
398 saveBag (characterId, bag)
399 {
400 this.#ensureBag(characterId);
401 this.db.prepare(`
402 UPDATE character_bags
403 SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ?
404 WHERE character_id = ?
405 `).run(
406 JSON.stringify(bag.inventory ?? emptySlots()),
407 JSON.stringify(bag.equipment ?? emptyEquipment()),
408 bag.currency ?? 0,
409 JSON.stringify(bag.vault ?? emptySlots()),
410 bag.vaultCurrency ?? 0,
411 characterId
412 );
413 }
414
415 getInheritance (accountId)
416 {
417 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
418 if (!row)
419 { return { accountId, slots: emptySlots(), currency: 0 }; }
420 return {
421 accountId,
422 slots: JSON.parse(row.slots_blob),
423 currency: row.currency
424 };
425 }
426
427 saveInheritance (accountId, inheritance)
428 {
429 this.db.prepare(`
430 INSERT INTO account_inheritance (account_id, slots_blob, currency)
431 VALUES (?, ?, ?)
432 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency
433 `).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0);
434 }
435
436 #moveGoodsToInheritance (character)
437 {
438 const bag = this.getBag(character.character_id) ?? {
439 inventory: emptySlots(),
440 equipment: emptyEquipment(),
441 currency: 0,
442 vault: emptySlots(),
443 vaultCurrency: 0
444 };
445 const inheritance = this.getInheritance(character.account_id);
446 const incoming = [
447 ...(bag.inventory ?? []),
448 ...Object.values(bag.equipment?.slots ?? {}),
449 ...(bag.vault ?? [])
450 ].filter(Boolean);
451 let slots = inheritance.slots ?? emptySlots();
452 for (const stack of incoming)
453 {
454 const def = itemDefinition(stack.itemId);
455 if (!def)
456 { continue; }
457 const result = insertStack(slots, stack, def);
458 if (result.ok)
459 { slots = result.slots; }
460 else
461 {
462 const extra = result.slots;
463 for (const leftover of extra)
464 {
465 if (leftover)
466 { slots.push(leftover); }
467 }
468 slots.push({ ...stack, quantity: result.remainder });
469 }
470 }
471 this.saveInheritance(character.account_id, {
472 slots: publicSlots(slots),
473 currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0)
474 });
475 }
476
477 nextGroundItemId ()
478 {
479 const row = this.db.prepare("SELECT MAX(ground_item_id) AS id FROM ground_items").get();
480 return (row?.id ?? 0) + 1;
481 }
482
483 listGroundItemsInRegion (minX, minY, maxX, maxY)
484 {
485 return this.db.prepare(`
486 SELECT * FROM ground_items
487 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
488 `).all(minX, maxX, minY, maxY).map(parseGroundItem);
489 }
490
491 upsertGroundItem (item)
492 {
493 this.db.prepare(`
494 INSERT INTO ground_items (
495 ground_item_id, tile_x, tile_y, stack_blob, dropped_at, expires_at, source, dropped_by_character_id
496 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
497 ON CONFLICT(ground_item_id) DO UPDATE SET
498 tile_x = excluded.tile_x,
499 tile_y = excluded.tile_y,
500 stack_blob = excluded.stack_blob,
501 dropped_at = excluded.dropped_at,
502 expires_at = excluded.expires_at,
503 source = excluded.source,
504 dropped_by_character_id = excluded.dropped_by_character_id
505 `).run(
506 item.groundItemId,
507 item.tileX,
508 item.tileY,
509 JSON.stringify(item.stack),
510 item.droppedAt,
511 item.expiresAt,
512 item.source,
513 item.droppedByCharacterId ?? null
514 );
515 }
516
517 deleteGroundItem (groundItemId)
518 {
519 this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);
520 }
521
284 522 close ()
285 523 {
286 524 this.db.close();
@@ -296,3 +534,29 @@ function pairIds (left, right)
296 534 {
297 535 return left < right ? [left, right] : [right, left];
298 536 }
537
538 function parseGroundItem (row)
539 {
540 return {
541 groundItemId: row.ground_item_id,
542 tileX: row.tile_x,
543 tileY: row.tile_y,
544 stack: JSON.parse(row.stack_blob),
545 droppedAt: row.dropped_at,
546 expiresAt: row.expires_at,
547 source: row.source,
548 droppedByCharacterId: row.dropped_by_character_id
549 };
550 }
551
552 function parseBag (row, characterId)
553 {
554 return {
555 characterId,
556 inventory: JSON.parse(row.inventory_blob),
557 equipment: JSON.parse(row.equipment_blob),
558 currency: row.currency,
559 vault: JSON.parse(row.vault_blob),
560 vaultCurrency: row.vault_currency
561 };
562 }
@@ -1,4 +1,6 @@
1import { openDatabase } from "./database.js";
1import { openDatabase } from "./database.js";
2import { emptyEquipment, emptySlots, insertStack, publicSlots } from "../../../shared/items/inventory.js";
3import { STARTER_CURRENCY, STARTER_ITEMS, itemDefinition } from "../../../shared/definitions/items.js";
2
4
3const STATE_SCHEMA = `
5const STATE_SCHEMA = `
4CREATE TABLE IF NOT EXISTS accounts (
6CREATE TABLE IF NOT EXISTS accounts (
@@ -40,6 +42,39 @@ CREATE TABLE IF NOT EXISTS friendships (
40 created_at INTEGER NOT NULL,
42 created_at INTEGER NOT NULL,
41 PRIMARY KEY (character_id_a, character_id_b)
43 PRIMARY KEY (character_id_a, character_id_b)
42);
44);
45
46CREATE TABLE IF NOT EXISTS persistent_entities (
47 entity_id INTEGER PRIMARY KEY,
48 tile_x INTEGER NOT NULL,
49 tile_y INTEGER NOT NULL,
50 components_blob TEXT NOT NULL
51);
52
53CREATE TABLE IF NOT EXISTS character_bags (
54 character_id INTEGER PRIMARY KEY,
55 inventory_blob TEXT NOT NULL,
56 equipment_blob TEXT NOT NULL,
57 currency INTEGER NOT NULL DEFAULT 0,
58 vault_blob TEXT NOT NULL,
59 vault_currency INTEGER NOT NULL DEFAULT 0
60);
61
62CREATE TABLE IF NOT EXISTS account_inheritance (
63 account_id INTEGER PRIMARY KEY,
64 slots_blob TEXT NOT NULL,
65 currency INTEGER NOT NULL DEFAULT 0
66);
67
68CREATE TABLE IF NOT EXISTS ground_items (
69 ground_item_id INTEGER PRIMARY KEY,
70 tile_x INTEGER NOT NULL,
71 tile_y INTEGER NOT NULL,
72 stack_blob TEXT NOT NULL,
73 dropped_at INTEGER NOT NULL,
74 expires_at INTEGER NOT NULL,
75 source TEXT NOT NULL,
76 dropped_by_character_id INTEGER
77);
43`;
78`;
44
79
45export class StateDatabase
80export class StateDatabase
@@ -117,6 +152,7 @@ export class StateDatabase
117 }
152 }
118
153
119 this.db.exec("COMMIT");
154 this.db.exec("COMMIT");
155 this.#ensureBag(characterId);
120 return this.getCharacter(characterId);
156 return this.getCharacter(characterId);
121 }
157 }
122 catch (error)
158 catch (error)
@@ -145,6 +181,8 @@ export class StateDatabase
145 this.db.exec("BEGIN");
181 this.db.exec("BEGIN");
146 try
182 try
147 {
183 {
184 this.#moveGoodsToInheritance(character);
185 this.db.prepare("DELETE FROM character_bags WHERE character_id = ?").run(characterId);
148 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
186 this.db.prepare("DELETE FROM characters WHERE character_id = ?").run(characterId);
149 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
187 this.db.prepare("DELETE FROM friend_requests WHERE from_character_id = ? OR to_character_id = ?").run(
150 characterId,
188 characterId,
@@ -281,6 +319,206 @@ export class StateDatabase
281 `).run(fromId, toId);
319 `).run(fromId, toId);
282 }
320 }
283
321
322 listPersistentInRegion (minX, minY, maxX, maxY)
323 {
324 return this.db.prepare(`
325 SELECT entity_id, tile_x, tile_y, components_blob
326 FROM persistent_entities
327 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
328 `).all(minX, maxX, minY, maxY);
329 }
330
331 replacePersistentInRegion (minX, minY, maxX, maxY, entities)
332 {
333 this.db.exec("BEGIN");
334 try
335 {
336 this.db.prepare(`
337 DELETE FROM persistent_entities
338 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
339 `).run(minX, maxX, minY, maxY);
340 const insert = this.db.prepare(`
341 INSERT INTO persistent_entities (entity_id, tile_x, tile_y, components_blob)
342 VALUES (?, ?, ?, ?)
343 `);
344 for (const entity of entities)
345 {
346 insert.run(
347 entity.entityId,
348 entity.tileX,
349 entity.tileY,
350 JSON.stringify(entity.payload?.components ?? entity.components)
351 );
352 }
353 this.db.exec("COMMIT");
354 }
355 catch (error)
356 {
357 this.db.exec("ROLLBACK");
358 throw error;
359 }
360 }
361
362 #ensureBag (characterId)
363 {
364 const existing = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
365 if (existing)
366 { return parseBag(existing, characterId); }
367 const slots = emptySlots();
368 for (const starter of STARTER_ITEMS)
369 {
370 const result = insertStack(slots, { ...starter }, itemDefinition(starter.itemId));
371 if (result.ok)
372 { slots.splice(0, slots.length, ...result.slots); }
373 }
374 this.db.prepare(`
375 INSERT INTO character_bags (
376 character_id, inventory_blob, equipment_blob, currency, vault_blob, vault_currency
377 ) VALUES (?, ?, ?, ?, ?, 0)
378 `).run(
379 characterId,
380 JSON.stringify(slots),
381 JSON.stringify(emptyEquipment()),
382 STARTER_CURRENCY,
383 JSON.stringify(emptySlots())
384 );
385 return this.getBag(characterId);
386 }
387
388 getBag (characterId)
389 {
390 const row = this.db.prepare("SELECT * FROM character_bags WHERE character_id = ?").get(characterId);
391 if (row)
392 { return parseBag(row, characterId); }
393 if (this.getCharacter(characterId))
394 { return this.#ensureBag(characterId); }
395 return null;
396 }
397
398 saveBag (characterId, bag)
399 {
400 this.#ensureBag(characterId);
401 this.db.prepare(`
402 UPDATE character_bags
403 SET inventory_blob = ?, equipment_blob = ?, currency = ?, vault_blob = ?, vault_currency = ?
404 WHERE character_id = ?
405 `).run(
406 JSON.stringify(bag.inventory ?? emptySlots()),
407 JSON.stringify(bag.equipment ?? emptyEquipment()),
408 bag.currency ?? 0,
409 JSON.stringify(bag.vault ?? emptySlots()),
410 bag.vaultCurrency ?? 0,
411 characterId
412 );
413 }
414
415 getInheritance (accountId)
416 {
417 const row = this.db.prepare("SELECT * FROM account_inheritance WHERE account_id = ?").get(accountId);
418 if (!row)
419 { return { accountId, slots: emptySlots(), currency: 0 }; }
420 return {
421 accountId,
422 slots: JSON.parse(row.slots_blob),
423 currency: row.currency
424 };
425 }
426
427 saveInheritance (accountId, inheritance)
428 {
429 this.db.prepare(`
430 INSERT INTO account_inheritance (account_id, slots_blob, currency)
431 VALUES (?, ?, ?)
432 ON CONFLICT(account_id) DO UPDATE SET slots_blob = excluded.slots_blob, currency = excluded.currency
433 `).run(accountId, JSON.stringify(inheritance.slots ?? emptySlots()), inheritance.currency ?? 0);
434 }
435
436 #moveGoodsToInheritance (character)
437 {
438 const bag = this.getBag(character.character_id) ?? {
439 inventory: emptySlots(),
440 equipment: emptyEquipment(),
441 currency: 0,
442 vault: emptySlots(),
443 vaultCurrency: 0
444 };
445 const inheritance = this.getInheritance(character.account_id);
446 const incoming = [
447 ...(bag.inventory ?? []),
448 ...Object.values(bag.equipment?.slots ?? {}),
449 ...(bag.vault ?? [])
450 ].filter(Boolean);
451 let slots = inheritance.slots ?? emptySlots();
452 for (const stack of incoming)
453 {
454 const def = itemDefinition(stack.itemId);
455 if (!def)
456 { continue; }
457 const result = insertStack(slots, stack, def);
458 if (result.ok)
459 { slots = result.slots; }
460 else
461 {
462 const extra = result.slots;
463 for (const leftover of extra)
464 {
465 if (leftover)
466 { slots.push(leftover); }
467 }
468 slots.push({ ...stack, quantity: result.remainder });
469 }
470 }
471 this.saveInheritance(character.account_id, {
472 slots: publicSlots(slots),
473 currency: (inheritance.currency ?? 0) + (bag.currency ?? 0) + (bag.vaultCurrency ?? 0)
474 });
475 }
476
477 nextGroundItemId ()
478 {
479 const row = this.db.prepare("SELECT MAX(ground_item_id) AS id FROM ground_items").get();
480 return (row?.id ?? 0) + 1;
481 }
482
483 listGroundItemsInRegion (minX, minY, maxX, maxY)
484 {
485 return this.db.prepare(`
486 SELECT * FROM ground_items
487 WHERE tile_x >= ? AND tile_x <= ? AND tile_y >= ? AND tile_y <= ?
488 `).all(minX, maxX, minY, maxY).map(parseGroundItem);
489 }
490
491 upsertGroundItem (item)
492 {
493 this.db.prepare(`
494 INSERT INTO ground_items (
495 ground_item_id, tile_x, tile_y, stack_blob, dropped_at, expires_at, source, dropped_by_character_id
496 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
497 ON CONFLICT(ground_item_id) DO UPDATE SET
498 tile_x = excluded.tile_x,
499 tile_y = excluded.tile_y,
500 stack_blob = excluded.stack_blob,
501 dropped_at = excluded.dropped_at,
502 expires_at = excluded.expires_at,
503 source = excluded.source,
504 dropped_by_character_id = excluded.dropped_by_character_id
505 `).run(
506 item.groundItemId,
507 item.tileX,
508 item.tileY,
509 JSON.stringify(item.stack),
510 item.droppedAt,
511 item.expiresAt,
512 item.source,
513 item.droppedByCharacterId ?? null
514 );
515 }
516
517 deleteGroundItem (groundItemId)
518 {
519 this.db.prepare("DELETE FROM ground_items WHERE ground_item_id = ?").run(groundItemId);
520 }
521
284 close ()
522 close ()
285 {
523 {
286 this.db.close();
524 this.db.close();
@@ -296,3 +534,29 @@ function pairIds (left, right)
296{
534{
297 return left < right ? [left, right] : [right, left];
535 return left < right ? [left, right] : [right, left];
298}
536}
537
538function parseGroundItem (row)
539{
540 return {
541 groundItemId: row.ground_item_id,
542 tileX: row.tile_x,
543 tileY: row.tile_y,
544 stack: JSON.parse(row.stack_blob),
545 droppedAt: row.dropped_at,
546 expiresAt: row.expires_at,
547 source: row.source,
548 droppedByCharacterId: row.dropped_by_character_id
549 };
550}
551
552function parseBag (row, characterId)
553{
554 return {
555 characterId,
556 inventory: JSON.parse(row.inventory_blob),
557 equipment: JSON.parse(row.equipment_blob),
558 currency: row.currency,
559 vault: JSON.parse(row.vault_blob),
560 vaultCurrency: row.vault_currency
561 };
562}
server/src/simulation/chunkLoader.js added +53 −0
@@ -0,0 +1,53 @@
1 import { DEFAULT_CHUNK_LOADER } from "../../../shared/protocol/constants.js";
2 import {
3 chunkKey,
4 chunkToRegion,
5 regionKey,
6 tileToChunk,
7 visibleChunkCoords,
8 visibleRegionCoords
9 } from "../world/coordinates.js";
10
11 export function normalizeChunkLoader (loader)
12 {
13 return {
14 simulationRadiusChunks: Math.max(0, Math.round(loader?.simulationRadiusChunks ?? DEFAULT_CHUNK_LOADER.simulationRadiusChunks)),
15 regionLoadRadius: Math.max(0, Math.round(loader?.regionLoadRadius ?? DEFAULT_CHUNK_LOADER.regionLoadRadius))
16 };
17 }
18
19 export function loaderCoverage (tileX, tileY, loader)
20 {
21 const chunkLoader = normalizeChunkLoader(loader);
22 const chunkX = tileToChunk(tileX);
23 const chunkY = tileToChunk(tileY);
24 return {
25 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks),
26 residentRegions: visibleRegionCoords(
27 chunkToRegion(chunkX),
28 chunkToRegion(chunkY),
29 chunkLoader.regionLoadRadius
30 )
31 };
32 }
33
34 export function accumulateLoaderRefs (loaders)
35 {
36 const chunkSim = new Map();
37 const regionRes = new Map();
38 for (const loader of loaders)
39 {
40 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
41 for (const chunk of coverage.simulationChunks)
42 {
43 const key = chunkKey(chunk.chunkX, chunk.chunkY);
44 chunkSim.set(key, (chunkSim.get(key) ?? 0) + 1);
45 }
46 for (const region of coverage.residentRegions)
47 {
48 const key = regionKey(region.regionX, region.regionY);
49 regionRes.set(key, (regionRes.get(key) ?? 0) + 1);
50 }
51 }
52 return { chunkSim, regionRes };
53 }
@@ -0,0 +1,53 @@
1import { DEFAULT_CHUNK_LOADER } from "../../../shared/protocol/constants.js";
2import {
3 chunkKey,
4 chunkToRegion,
5 regionKey,
6 tileToChunk,
7 visibleChunkCoords,
8 visibleRegionCoords
9} from "../world/coordinates.js";
10
11export function normalizeChunkLoader (loader)
12{
13 return {
14 simulationRadiusChunks: Math.max(0, Math.round(loader?.simulationRadiusChunks ?? DEFAULT_CHUNK_LOADER.simulationRadiusChunks)),
15 regionLoadRadius: Math.max(0, Math.round(loader?.regionLoadRadius ?? DEFAULT_CHUNK_LOADER.regionLoadRadius))
16 };
17}
18
19export function loaderCoverage (tileX, tileY, loader)
20{
21 const chunkLoader = normalizeChunkLoader(loader);
22 const chunkX = tileToChunk(tileX);
23 const chunkY = tileToChunk(tileY);
24 return {
25 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks),
26 residentRegions: visibleRegionCoords(
27 chunkToRegion(chunkX),
28 chunkToRegion(chunkY),
29 chunkLoader.regionLoadRadius
30 )
31 };
32}
33
34export function accumulateLoaderRefs (loaders)
35{
36 const chunkSim = new Map();
37 const regionRes = new Map();
38 for (const loader of loaders)
39 {
40 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
41 for (const chunk of coverage.simulationChunks)
42 {
43 const key = chunkKey(chunk.chunkX, chunk.chunkY);
44 chunkSim.set(key, (chunkSim.get(key) ?? 0) + 1);
45 }
46 for (const region of coverage.residentRegions)
47 {
48 const key = regionKey(region.regionX, region.regionY);
49 regionRes.set(key, (regionRes.get(key) ?? 0) + 1);
50 }
51 }
52 return { chunkSim, regionRes };
53}
server/src/simulation/inProcessWorker.js added +20 −0
@@ -0,0 +1,20 @@
1 import { WorkerWorld } from "./workerWorld.js";
2
3 export class InProcessWorker
4 {
5 constructor (workerId)
6 {
7 this.workerId = workerId;
8 this.world = new WorkerWorld(workerId);
9 }
10
11 call (message)
12 {
13 const result = this.world.handle(structuredClone(message));
14 return result === undefined ? undefined : structuredClone(result);
15 }
16
17 async terminate ()
18 {
19 }
20 }
@@ -0,0 +1,20 @@
1import { WorkerWorld } from "./workerWorld.js";
2
3export class InProcessWorker
4{
5 constructor (workerId)
6 {
7 this.workerId = workerId;
8 this.world = new WorkerWorld(workerId);
9 }
10
11 call (message)
12 {
13 const result = this.world.handle(structuredClone(message));
14 return result === undefined ? undefined : structuredClone(result);
15 }
16
17 async terminate ()
18 {
19 }
20}
server/src/simulation/protocol.js added +25 −0
@@ -0,0 +1,25 @@
1 export const WorkerMessage = Object.freeze({
2 configure: "configure",
3 assignRegion: "assignRegion",
4 dropRegion: "dropRegion",
5 replaceRegionChunks: "replaceRegionChunks",
6 setReplicas: "setReplicas",
7 setSimulatingChunks: "setSimulatingChunks",
8 setGhosts: "setGhosts",
9 spawn: "spawn",
10 despawn: "despawn",
11 despawnCharacter: "despawnCharacter",
12 command: "command",
13 stepMovement: "stepMovement",
14 applyTransfer: "applyTransfer",
15 commitTransfer: "commitTransfer",
16 abortTransfer: "abortTransfer",
17 snapshotChunk: "snapshotChunk",
18 listLoaders: "listLoaders",
19 listPublicEntities: "listPublicEntities",
20 entitiesInRegion: "entitiesInRegion",
21 inspect: "inspect",
22 inspectBag: "inspectBag",
23 setGroundItems: "setGroundItems",
24 stepSpawners: "stepSpawners"
25 });
@@ -0,0 +1,25 @@
1export const WorkerMessage = Object.freeze({
2 configure: "configure",
3 assignRegion: "assignRegion",
4 dropRegion: "dropRegion",
5 replaceRegionChunks: "replaceRegionChunks",
6 setReplicas: "setReplicas",
7 setSimulatingChunks: "setSimulatingChunks",
8 setGhosts: "setGhosts",
9 spawn: "spawn",
10 despawn: "despawn",
11 despawnCharacter: "despawnCharacter",
12 command: "command",
13 stepMovement: "stepMovement",
14 applyTransfer: "applyTransfer",
15 commitTransfer: "commitTransfer",
16 abortTransfer: "abortTransfer",
17 snapshotChunk: "snapshotChunk",
18 listLoaders: "listLoaders",
19 listPublicEntities: "listPublicEntities",
20 entitiesInRegion: "entitiesInRegion",
21 inspect: "inspect",
22 inspectBag: "inspectBag",
23 setGroundItems: "setGroundItems",
24 stepSpawners: "stepSpawners"
25});
server/src/simulation/simulation.js +778 −185
@@ -1,61 +1,118 @@
1 import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js";
2 import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js";
1 import {
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8 } from "../../../shared/protocol/constants.js";
9 import {
10 chunkKey,
11 chunkToRegion,
12 chunksInRegion,
13 parseChunkKey,
14 parseRegionKey,
15 regionKey,
16 regionTileBounds,
17 tileToChunk,
18 tileToLocal,
19 tileToRegion,
20 visibleChunkCoords
21 } from "../world/coordinates.js";
3 22 import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
4 import { EcsWorld } from "../ecs/world.js";
5 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6 23 import { closedNeighborEdges } from "../world/chunkFlags.js";
24 import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
25 import { InProcessWorker } from "./inProcessWorker.js";
26 import { ThreadWorker } from "./threadWorker.js";
27 import { WorkerMessage } from "./protocol.js";
28 import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29 import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30 import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31 import { mobComponents } from "./spawners.js";
7 32
8 33 export class Simulation
9 34 {
10 constructor (worldDb, stateDb)
35 constructor (worldDb, stateDb, options = {})
11 36 {
12 37 this.worldDb = worldDb;
13 38 this.stateDb = stateDb;
14 this.ecs = new EcsWorld();
15 this.chunks = new Map();
16 this.occupancy = new Map();
39 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
40 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
41 this.pinRegion = options.pinRegion ?? null;
42 this.nowFn = options.now ?? (() => Date.now());
43 this.workers = [];
44 this.regionOwner = new Map();
45 this.regionGraceUntil = new Map();
46 this.directory = new Map();
17 47 this.characterEntities = new Map();
18 48 this.commandQueue = [];
49 this.replication = [];
50 this.authoredCache = new Map();
51 this.nextEntityId = 1;
52 this.nextGroundItemId = stateDb.nextGroundItemId();
53 this.tickIndex = 0;
19 54 this.movementTickCounter = 0;
55 this.lastTickAt = null;
56 this.movementAccumulator = 0;
20 57 this.activeRevisionId = worldDb.getActiveRevisionId();
21 58 this.settings = worldDb.getLiveSettings();
22 this.tickIndex = 0;
23 this.reloadWorld();
59
60 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
61 for (let workerId = 0; workerId < this.workerCount; workerId++)
62 {
63 const worker = new WorkerImpl(workerId);
64 worker.call({
65 type: WorkerMessage.configure,
66 settings: this.settings,
67 activeRevisionId: this.activeRevisionId
68 });
69 this.workers.push(worker);
70 }
71 }
72
73 get now ()
74 {
75 return this.nowFn();
24 76 }
25 77
26 78 applySettings (settings)
27 79 {
28 80 this.settings = { ...this.settings, ...settings };
81 this.#configureWorkers();
29 82 }
30 83
31 84 reloadWorld ()
32 85 {
33 86 this.activeRevisionId = this.worldDb.getActiveRevisionId();
34 87 this.settings = this.worldDb.getLiveSettings();
35 this.chunks.clear();
36 for (const entity of this.ecs.query("position"))
88 this.authoredCache.clear();
89 this.#configureWorkers();
90 for (const [key, workerId] of this.regionOwner)
37 91 {
38 const pos = entity.position;
39 this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY));
92 const { regionX, regionY } = parseRegionKey(key);
93 this.workers[workerId].call({
94 type: WorkerMessage.replaceRegionChunks,
95 chunks: this.#regionChunkBlobs(regionX, regionY)
96 });
40 97 }
98 this.#syncAllReplicas();
41 99 }
42 100
43 101 enqueue (sessionId, command)
44 102 {
45 this.commandQueue.push({ sessionId, command, receivedAt: Date.now() });
103 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
46 104 }
47 105
48 step (now = Date.now())
106 step (now = this.now)
49 107 {
50 108 this.tickIndex += 1;
51 const commands = this.commandQueue.splice(0);
52 109 const events = [];
110 const commands = this.commandQueue.splice(0);
53 111 for (const item of commands)
54 112 {
55 113 try
56 114 {
57 const produced = this.#handleCommand(item.sessionId, item.command) ?? [];
58 events.push(...produced);
115 events.push(...this.#routeCommand(item));
59 116 }
60 117 catch (error)
61 118 {
@@ -67,19 +124,52 @@ export class Simulation
67 124 }
68 125 }
69 126
70 const movementHz = this.settings.walkTilesPerSecond * 2;
71 const simHz = this.settings.simulationTickHz;
72 const movementEvery = Math.max(1, Math.round(simHz / movementHz));
73 if (this.tickIndex % movementEvery === 0)
127 this.#recalculateActivation(now);
128
129 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
130 const expectedDt = 1 / simHz;
131 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
132 ? expectedDt
133 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 this.lastTickAt = now;
135
136 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
137 this.movementAccumulator += dt * movementHz;
138 while (this.movementAccumulator >= 1)
74 139 {
140 this.movementAccumulator -= 1;
75 141 this.movementTickCounter += 1;
76 events.push(...this.#stepMovement());
142 const transfers = [];
143 for (const worker of this.workers)
144 {
145 const result = worker.call({ type: WorkerMessage.stepMovement, now });
146 for (const event of result?.events ?? [])
147 {
148 if (event.type === "entity-move")
149 { this.#applyMoveToDirectory(event); }
150 this.#persistGroundEvent(event);
151 events.push(event);
152 }
153 for (const request of result?.transferRequests ?? [])
154 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
155 }
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
77 158 }
78 159
79 return { now, events };
160 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
161 { events.push(...this.#stepSpawners()); }
162
163 this.#syncGhosts();
164 return { now, events, replication: this.drainReplication() };
80 165 }
81 166
82 worldTime (now = Date.now())
167 drainReplication ()
168 {
169 return this.replication.splice(0);
170 }
171
172 worldTime (now = this.now)
83 173 {
84 174 const date = new Date(now);
85 175 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
@@ -94,9 +184,9 @@ export class Simulation
94 184 spawnCharacter (sessionId, character)
95 185 {
96 186 this.despawnCharacter(character.character_id);
97 const tileX = character.tile_x;
98 const tileY = character.tile_y;
99 if (!this.isEnterable(tileX, tileY))
187 let tileX = character.tile_x;
188 let tileY = character.tile_y;
189 if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY))
100 190 {
101 191 const spawn = this.findOpenSpawn();
102 192 if (!spawn)
@@ -105,45 +195,113 @@ export class Simulation
105 195 error.userFacing = true;
106 196 throw error;
107 197 }
108 character.tile_x = spawn.tileX;
109 character.tile_y = spawn.tileY;
110 this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait);
198 tileX = spawn.tileX;
199 tileY = spawn.tileY;
200 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, character.gait);
111 201 }
112 202
113 const id = this.ecs.entity();
114 this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y });
115 this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 });
116 this.ecs.add(id, "appearance", {
117 sex: character.sex,
118 firstName: character.first_name,
119 lastName: character.last_name
203 const bag = this.stateDb.getBag(character.character_id) ?? {
204 inventory: emptySlots(),
205 equipment: emptyEquipment(),
206 currency: 0,
207 vault: emptySlots(),
208 vaultCurrency: 0
209 };
210 const entityId = this.nextEntityId++;
211 const components = {
212 position: { tileX, tileY },
213 movement: { gait: character.gait || GAIT.walk, walkCarry: 0 },
214 path: { tiles: [] },
215 appearance: {
216 sex: character.sex,
217 firstName: character.first_name,
218 lastName: character.last_name
219 },
220 character: {
221 characterId: character.character_id,
222 accountId: character.account_id
223 },
224 networkIdentity: { sessionId },
225 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
226 inventory: { slots: bag.inventory ?? emptySlots() },
227 equipment: bag.equipment ?? emptyEquipment(),
228 currency: { amount: bag.currency ?? 0 },
229 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }
230 };
231 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
232 const workerId = this.#ownerOfTile(tileX, tileY);
233 const view = this.workers[workerId].call({
234 type: WorkerMessage.spawn,
235 entityId,
236 components
120 237 });
121 this.ecs.add(id, "character", {
122 characterId: character.character_id,
123 accountId: character.account_id,
124 sessionId
238 this.#remember(view, workerId);
239 this.#queueReplication(replicationSpawn(view));
240 this.#recalculateActivation(this.now);
241 this.#syncGhosts();
242 return entityId;
243 }
244
245 spawnEntity (components, options = {})
246 {
247 const entityId = options.entityId ?? this.nextEntityId++;
248 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
249 const position = components.position;
250 if (!position)
251 { throw new Error("spawnEntity requires position."); }
252 if (components.chunkLoader)
253 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
254 else
255 {
256 this.#ensureRegion(
257 tileToRegion(position.tileX),
258 tileToRegion(position.tileY),
259 null
260 );
261 }
262 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
263 const view = this.workers[workerId].call({
264 type: WorkerMessage.spawn,
265 entityId,
266 components
125 267 });
126 this.characterEntities.set(character.character_id, id);
127 this.#occupy(id, character.tile_x, character.tile_y);
128 this.#ensureVisibleChunks(character.tile_x, character.tile_y);
129 return id;
268 this.#remember(view, workerId);
269 if (components.appearance)
270 { this.#queueReplication(replicationSpawn(view)); }
271 this.#recalculateActivation(this.now);
272 this.#syncGhosts();
273 return entityId;
130 274 }
131 275
132 276 despawnCharacter (characterId)
133 277 {
134 const id = this.characterEntities.get(characterId);
135 if (!id)
278 const entityId = this.characterEntities.get(characterId);
279 if (!entityId)
136 280 { return; }
137
138 const position = this.ecs.get(id, "position");
139 const movement = this.ecs.get(id, "movement");
140 if (position)
281 const record = this.directory.get(entityId);
282 if (!record)
283 {
284 this.characterEntities.delete(characterId);
285 return;
286 }
287 this.#saveBag(entityId, record.workerId);
288 const dropped = this.workers[record.workerId].call({
289 type: WorkerMessage.despawnCharacter,
290 characterId
291 });
292 if (dropped)
141 293 {
142 this.#vacate(id, position.tileX, position.tileY);
143 this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk);
294 this.stateDb.saveCharacterPosition(
295 characterId,
296 dropped.tileX,
297 dropped.tileY,
298 dropped.gait ?? GAIT.walk
299 );
300 this.#queueReplication(replicationDespawn(dropped));
144 301 }
145 this.ecs.destroy(id);
146 this.characterEntities.delete(characterId);
302 this.#forget(entityId);
303 this.#recalculateActivation(this.now);
304 this.#syncGhosts();
147 305 }
148 306
149 307 entityForCharacter (characterId)
@@ -151,14 +309,48 @@ export class Simulation
151 309 return this.characterEntities.get(characterId) ?? null;
152 310 }
153 311
312 entityRecord (entityId)
313 {
314 const record = this.directory.get(entityId);
315 return record ? { ...record } : null;
316 }
317
318 positionOf (entityId)
319 {
320 const record = this.directory.get(entityId);
321 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
322 }
323
324 bagOf (entityId)
325 {
326 const record = this.directory.get(entityId);
327 if (!record)
328 { return null; }
329 return this.workers[record.workerId].call({
330 type: WorkerMessage.inspectBag,
331 entityId
332 });
333 }
334
154 335 snapshotFor (entityId)
155 336 {
156 const position = this.ecs.get(entityId, "position");
157 if (!position)
337 const record = this.directory.get(entityId);
338 if (!record)
158 339 { return []; }
340 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
341 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
342 }
159 343
160 const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS);
161 return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY));
344 snapshotChunk (chunkX, chunkY)
345 {
346 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
347 if (owner == null)
348 { return this.#syntheticSnapshot(chunkX, chunkY); }
349 return this.workers[owner].call({
350 type: WorkerMessage.snapshotChunk,
351 chunkX,
352 chunkY
353 });
162 354 }
163 355
164 356 findOpenSpawn ()
@@ -166,7 +358,7 @@ export class Simulation
166 358 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
167 359 for (const coord of coords)
168 360 {
169 const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y);
361 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
170 362 if (!data.open)
171 363 { continue; }
172 364 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -175,7 +367,7 @@ export class Simulation
175 367 {
176 368 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
177 369 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
178 if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY))
370 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
179 371 { return { tileX, tileY }; }
180 372 }
181 373 }
@@ -185,202 +377,603 @@ export class Simulation
185 377
186 378 isEnterable (tileX, tileY)
187 379 {
188 const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY));
380 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
189 381 if (!data.open)
190 382 { return false; }
191 383 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
192 384 }
193 385
194 #handleCommand (sessionId, command)
386 debugWorld ()
195 387 {
196 switch (command.type)
197 {
198 case "move-to":
199 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
200 case "set-gait":
201 return this.#setGait(sessionId, command.characterId, command.gait);
202 default:
203 return [];
204 }
388 const loaders = this.#allLoaders();
389 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
390 const simulatingChunks = [...chunkSim.entries()]
391 .filter(([, count]) => count > 0)
392 .map(([key]) => key)
393 .sort();
394 return {
395 tickIndex: this.tickIndex,
396 workerCount: this.workers.length,
397 workerMode: this.workerMode,
398 simulatingChunks,
399 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
400 ...parseRegionKey(key),
401 workerId,
402 state: REGION_RUNTIME_STATE.resident,
403 refs: regionRes.get(key) ?? 0,
404 graceUntil: this.regionGraceUntil.get(key) ?? null
405 })),
406 entities: [...this.directory.values()].map((entity) => ({
407 entityId: entity.entityId,
408 workerId: entity.workerId,
409 tileX: entity.tileX,
410 tileY: entity.tileY,
411 characterId: entity.characterId
412 }))
413 };
205 414 }
206 415
207 #moveTo (sessionId, characterId, tileX, tileY)
208 {
209 const id = this.#requireOwnedEntity(sessionId, characterId);
210 const position = this.ecs.get(id, "position");
211 const movement = this.ecs.get(id, "movement");
212 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
213 const path = findPath(
214 position.tileX,
215 position.tileY,
216 tileX,
217 tileY,
218 (x, y) => this.#walkableFor(id, x, y),
219 bounds.minX,
220 bounds.minY,
221 bounds.maxX,
222 bounds.maxY
223 );
224 movement.path = path;
225 movement.walkCarry = 0;
226 return [];
416 async shutdown ()
417 {
418 for (const characterId of [...this.characterEntities.keys()])
419 { this.despawnCharacter(characterId); }
420 this.forceUnloadAll();
421 await Promise.all(this.workers.map((worker) => worker.terminate()));
227 422 }
228 423
229 #setGait (sessionId, characterId, gait)
424 forceUnloadAll ()
230 425 {
231 if (gait !== GAIT.walk && gait !== GAIT.run)
426 for (const key of [...this.regionOwner.keys()])
232 427 {
233 const error = new Error("Gait must be walk or run.");
234 error.userFacing = true;
235 throw error;
428 const { regionX, regionY } = parseRegionKey(key);
429 this.#unloadRegion(regionX, regionY);
236 430 }
237 const id = this.#requireOwnedEntity(sessionId, characterId);
238 this.ecs.get(id, "movement").gait = gait;
239 return [];
240 431 }
241 432
242 #requireOwnedEntity (sessionId, characterId)
433 #configureWorkers ()
243 434 {
244 const id = this.characterEntities.get(characterId);
245 if (!id)
435 for (const worker of this.workers)
246 436 {
247 const error = new Error("Character is not in the world.");
248 error.userFacing = true;
249 throw error;
437 worker.call({
438 type: WorkerMessage.configure,
439 settings: this.settings,
440 activeRevisionId: this.activeRevisionId
441 });
250 442 }
251 const character = this.ecs.get(id, "character");
252 if (!character || character.sessionId !== sessionId)
443 }
444
445 #routeCommand (item)
446 {
447 const entityId = this.characterEntities.get(item.command.characterId);
448 const record = entityId ? this.directory.get(entityId) : null;
449 if (!record)
253 450 {
254 451 const error = new Error("Character is not in the world.");
255 452 error.userFacing = true;
256 453 throw error;
257 454 }
258 return id;
455 if (item.command.type === "drop-item" && item.command.groundItemId == null)
456 { item.command.groundItemId = this.nextGroundItemId++; }
457 const result = this.workers[record.workerId].call({
458 type: WorkerMessage.command,
459 sessionId: item.sessionId,
460 command: item.command,
461 now: item.receivedAt ?? this.now
462 });
463 const view = this.workers[record.workerId].call({
464 type: WorkerMessage.inspect,
465 entityId: record.entityId
466 });
467 if (view)
468 { this.#remember(view, record.workerId); }
469 if (result?.private)
470 { this.#saveBagFromView(item.command.characterId, result.private); }
471 if (result?.appearanceChanged && view)
472 { this.#queueReplication(replicationAppearance(view)); }
473 if (result?.remainder)
474 {
475 this.stateDb.saveInheritance(
476 this.stateDb.getCharacter(item.command.characterId).account_id,
477 { slots: result.remainder, currency: 0 }
478 );
479 }
480 for (const event of result?.events ?? [])
481 { this.#persistGroundEvent(event); }
482 const events = [...(result?.events ?? [])];
483 if (result?.private)
484 {
485 events.push({
486 type: "inventory",
487 sessionId: item.sessionId,
488 bank: !!result.bank,
489 ...result.private
490 });
491 }
492 return events;
259 493 }
260 494
261 #stepMovement ()
495 #recalculateActivation (now)
262 496 {
263 const events = [];
264 for (const entity of this.ecs.query("position", "movement"))
497 const loaders = this.#allLoaders();
498 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
499
500 for (const [key, count] of regionRes)
265 501 {
266 const { id, position, movement } = entity;
267 if (!movement.path.length)
502 if (count <= 0)
268 503 { continue; }
504 const { regionX, regionY } = parseRegionKey(key);
505 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
506 this.regionGraceUntil.delete(key);
507 }
508
509 for (const [key] of [...this.regionOwner.entries()])
510 {
511 if ((regionRes.get(key) ?? 0) > 0)
512 { continue; }
513 if (!this.regionGraceUntil.has(key))
514 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
515 if (now >= this.regionGraceUntil.get(key))
516 {
517 const { regionX, regionY } = parseRegionKey(key);
518 this.#unloadRegion(regionX, regionY);
519 }
520 }
269 521
270 const isWalk = movement.gait !== GAIT.run;
271 if (isWalk)
522 for (const [workerId, worker] of this.workers.entries())
523 {
524 const chunkKeys = [];
525 for (const [key, count] of chunkSim)
272 526 {
273 movement.walkCarry = (movement.walkCarry + 1) % 2;
274 if (movement.walkCarry !== 0)
527 if (count <= 0)
275 528 { continue; }
529 const { chunkX, chunkY } = parseChunkKey(key);
530 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
531 { chunkKeys.push(key); }
532 }
533 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
534 }
535 this.#syncAllReplicas();
536 }
537
538 #ensureCoverage (tileX, tileY, loader)
539 {
540 const coverage = loaderCoverage(tileX, tileY, loader);
541 let preferred = this.#ownerOfTile(tileX, tileY);
542 for (const region of coverage.residentRegions)
543 {
544 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
545 if (preferred == null)
546 { preferred = owner; }
547 }
548 }
549
550 #ensureRegion (regionX, regionY, preferredWorkerId)
551 {
552 const key = regionKey(regionX, regionY);
553 if (this.regionOwner.has(key))
554 { return this.regionOwner.get(key); }
555 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
556 this.workers[workerId].call({
557 type: WorkerMessage.assignRegion,
558 regionX,
559 regionY,
560 chunks: this.#regionChunkBlobs(regionX, regionY)
561 });
562 this.regionOwner.set(key, workerId);
563 this.#restorePersistent(regionX, regionY, workerId);
564 this.#restoreGroundItems(regionX, regionY, workerId);
565 return workerId;
566 }
567
568 #unloadRegion (regionX, regionY)
569 {
570 const key = regionKey(regionX, regionY);
571 const workerId = this.regionOwner.get(key);
572 if (workerId == null)
573 { return; }
574 const bounds = regionTileBounds(regionX, regionY);
575 const { dropped, groundItems } = this.workers[workerId].call({
576 type: WorkerMessage.dropRegion,
577 regionX,
578 regionY
579 });
580 const persistent = [];
581 for (const record of dropped ?? [])
582 {
583 if (record.characterId)
584 {
585 this.stateDb.saveCharacterPosition(
586 record.characterId,
587 record.tileX,
588 record.tileY,
589 record.gait ?? GAIT.walk
590 );
276 591 }
592 if (record.persistent)
593 { persistent.push(record); }
594 this.#forget(record.entityId);
595 }
596 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
597 for (const item of groundItems ?? [])
598 { this.stateDb.upsertGroundItem(item); }
599 this.regionOwner.delete(key);
600 this.regionGraceUntil.delete(key);
601 }
277 602
278 const next = movement.path[0];
279 if (!this.#walkableFor(id, next.x, next.y))
603 #restorePersistent (regionX, regionY, workerId)
604 {
605 const bounds = regionTileBounds(regionX, regionY);
606 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
607 for (const row of rows)
608 {
609 if (this.directory.has(row.entity_id))
280 610 { continue; }
611 const components = JSON.parse(row.components_blob);
612 const view = this.workers[workerId].call({
613 type: WorkerMessage.spawn,
614 entityId: row.entity_id,
615 components
616 });
617 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
618 this.#remember(view, workerId);
619 }
620 }
281 621
282 const fromTileX = position.tileX;
283 const fromTileY = position.tileY;
284 this.#vacate(id, fromTileX, fromTileY);
285 position.tileX = next.x;
286 position.tileY = next.y;
287 movement.path.shift();
288 this.#occupy(id, position.tileX, position.tileY);
289 this.#ensureVisibleChunks(position.tileX, position.tileY);
290 const character = this.ecs.get(id, "character");
291 const appearance = this.ecs.get(id, "appearance");
622 #applyTransfers (requests)
623 {
624 const events = [];
625 for (const request of requests)
626 {
627 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
628 if (destWorkerId === request.fromWorkerId)
629 {
630 this.workers[request.fromWorkerId].call({
631 type: WorkerMessage.abortTransfer,
632 entityId: request.entityId
633 });
634 continue;
635 }
636 let result;
637 try
638 {
639 result = this.workers[destWorkerId].call({
640 type: WorkerMessage.applyTransfer,
641 payload: request.payload,
642 destTileX: request.destTileX,
643 destTileY: request.destTileY
644 });
645 }
646 catch
647 {
648 result = { accepted: false };
649 }
650 if (!result?.accepted)
651 {
652 this.workers[request.fromWorkerId].call({
653 type: WorkerMessage.abortTransfer,
654 entityId: request.entityId
655 });
656 continue;
657 }
658 this.workers[request.fromWorkerId].call({
659 type: WorkerMessage.commitTransfer,
660 entityId: request.entityId
661 });
662 this.#remember(result.entity, destWorkerId);
292 663 events.push({
293 664 type: "entity-move",
294 entityId: id,
295 characterId: character?.characterId,
296 fromTileX,
297 fromTileY,
298 tileX: position.tileX,
299 tileY: position.tileY,
300 gait: movement.gait,
301 sex: appearance?.sex,
302 firstName: appearance?.firstName,
303 lastName: appearance?.lastName
665 entityId: request.entityId,
666 fromTileX: request.fromTileX,
667 fromTileY: request.fromTileY,
668 tileX: result.entity.tileX,
669 tileY: result.entity.tileY,
670 gait: result.entity.gait
304 671 });
305 672 }
306 673 return events;
307 674 }
308 675
309 #walkableFor (entityId, tileX, tileY)
676 #syncAllReplicas ()
310 677 {
311 if (!this.isEnterable(tileX, tileY))
312 { return false; }
313 const occupant = this.#occupied(tileX, tileY);
314 return !occupant || occupant === entityId;
678 for (const [workerId, worker] of this.workers.entries())
679 {
680 const ownedKeys = new Set();
681 for (const [key, owner] of this.regionOwner)
682 {
683 if (owner !== workerId)
684 { continue; }
685 const { regionX, regionY } = parseRegionKey(key);
686 for (const chunk of chunksInRegion(regionX, regionY))
687 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
688 }
689 const replicas = [];
690 for (const key of replicaNeededForOwnedChunks(ownedKeys))
691 {
692 if (ownedKeys.has(key))
693 { continue; }
694 const { chunkX, chunkY } = parseChunkKey(key);
695 replicas.push({
696 chunkX,
697 chunkY,
698 data: this.#authoredChunk(chunkX, chunkY)
699 });
700 }
701 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
702 }
315 703 }
316 704
317 #ensureVisibleChunks (tileX, tileY)
705 #syncGhosts ()
318 706 {
319 for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS))
320 { this.#ensureChunk(coord.chunkX, coord.chunkY); }
707 const entities = [];
708 for (const worker of this.workers)
709 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
710 for (const [workerId, worker] of this.workers.entries())
711 {
712 const ghosts = entities.filter((entity) =>
713 {
714 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
715 { return false; }
716 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
717 });
718 worker.call({ type: WorkerMessage.setGhosts, ghosts });
719 }
321 720 }
322 721
323 #ensureChunk (chunkX, chunkY)
722 #nearWorker (workerId, tileX, tileY)
324 723 {
325 const key = chunkKey(chunkX, chunkY);
326 if (this.chunks.has(key))
327 { return this.chunks.get(key); }
724 const chunkX = tileToChunk(tileX);
725 const chunkY = tileToChunk(tileY);
726 for (const [key, owner] of this.regionOwner)
727 {
728 if (owner !== workerId)
729 { continue; }
730 const { regionX, regionY } = parseRegionKey(key);
731 for (const chunk of chunksInRegion(regionX, regionY))
732 {
733 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
734 { return true; }
735 }
736 }
737 return false;
738 }
739
740 #allLoaders ()
741 {
742 const loaders = [];
743 for (const worker of this.workers)
744 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
745 return loaders;
746 }
747
748 #preferredWorkerForRegion (loaders, regionX, regionY)
749 {
750 const votes = new Map();
751 for (const loader of loaders)
752 {
753 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
754 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
755 { continue; }
756 const record = this.directory.get(loader.entityId);
757 if (record?.workerId == null)
758 { continue; }
759 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
760 }
761 let best = null;
762 let bestVotes = -1;
763 for (const [workerId, count] of votes)
764 {
765 if (count > bestVotes)
766 {
767 best = workerId;
768 bestVotes = count;
769 }
770 }
771 return best;
772 }
773
774 #pickWorker (regionX, regionY, preferredWorkerId)
775 {
776 const pinned = this.pinRegion?.(regionX, regionY);
777 if (pinned != null)
778 { return pinned; }
779
780 const neighborOwners = [];
781 for (let dy = -1; dy <= 1; dy++)
782 {
783 for (let dx = -1; dx <= 1; dx++)
784 {
785 if (dx === 0 && dy === 0)
786 { continue; }
787 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
788 if (owner != null)
789 { neighborOwners.push(owner); }
790 }
791 }
792
793 const scores = this.workers.map((_, workerId) => ({
794 workerId,
795 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
796 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
797 }));
798
799 if (preferredWorkerId != null && scores[preferredWorkerId])
800 {
801 const preferred = scores[preferredWorkerId];
802 if (preferred.neighbors > 0 || neighborOwners.length === 0)
803 { return preferredWorkerId; }
804 }
805
806 scores.sort((left, right) =>
807 right.neighbors - left.neighbors
808 || left.load - right.load
809 || left.workerId - right.workerId
810 );
811 return scores[0].workerId;
812 }
328 813
814 #ownerOfTile (tileX, tileY)
815 {
816 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
817 }
818
819 #regionKeyForChunk (chunkX, chunkY)
820 {
821 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
822 }
823
824 #regionChunkBlobs (regionX, regionY)
825 {
826 return chunksInRegion(regionX, regionY).map((coord) => ({
827 chunkX: coord.chunkX,
828 chunkY: coord.chunkY,
829 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
830 }));
831 }
832
833 #authoredChunk (chunkX, chunkY)
834 {
835 const key = chunkKey(chunkX, chunkY);
836 if (this.authoredCache.has(key))
837 { return this.authoredCache.get(key); }
329 838 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
330 839 const data = row
331 840 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
332 841 : createEmptyChunkData(this.settings.defaultGroundTypeId);
333 this.chunks.set(key, data);
842 this.authoredCache.set(key, data);
334 843 return data;
335 844 }
336 845
337 #chunkSnapshot (chunkX, chunkY)
846 #syntheticSnapshot (chunkX, chunkY)
338 847 {
339 const data = this.#ensureChunk(chunkX, chunkY);
340 const entities = [];
341 for (const entity of this.ecs.query("position", "appearance"))
342 {
343 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
344 { continue; }
345 const movement = this.ecs.get(entity.id, "movement");
346 const character = this.ecs.get(entity.id, "character");
347 entities.push({
348 entityId: entity.id,
349 characterId: character?.characterId ?? null,
350 tileX: entity.position.tileX,
351 tileY: entity.position.tileY,
352 gait: movement?.gait ?? GAIT.walk,
353 sex: entity.appearance.sex,
354 firstName: entity.appearance.firstName,
355 lastName: entity.appearance.lastName
356 });
357 }
848 const data = this.#authoredChunk(chunkX, chunkY);
358 849 return {
359 850 chunkX,
360 851 chunkY,
361 852 open: data.open,
362 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#ensureChunk(x, y).open),
853 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
363 854 grounds: data.grounds,
364 855 blocks: data.blocks,
365 856 light: data.light,
366 entities
857 entities: [],
858 groundItems: []
367 859 };
368 860 }
369 861
370 #occupy (entityId, tileX, tileY)
862 #occupiedTile (tileX, tileY)
863 {
864 for (const record of this.directory.values())
865 {
866 if (record.tileX === tileX && record.tileY === tileY)
867 { return record.entityId; }
868 }
869 return null;
870 }
871
872 #queueReplication (event)
873 {
874 if (event)
875 { this.replication.push(event); }
876 }
877
878 #stepSpawners ()
879 {
880 const events = [];
881 for (const worker of this.workers)
882 {
883 const result = worker.call({ type: WorkerMessage.stepSpawners });
884 for (const request of result?.spawnRequests ?? [])
885 {
886 try
887 {
888 this.spawnEntity(mobComponents(request));
889 }
890 catch
891 { continue; }
892 }
893 }
894 return events;
895 }
896
897 #restoreGroundItems (regionX, regionY, workerId)
371 898 {
372 this.occupancy.set(tileKey(tileX, tileY), entityId);
899 const bounds = regionTileBounds(regionX, regionY);
900 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
901 .filter((item) => item.expiresAt > this.now);
902 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
903 this.workers[workerId].call({
904 type: WorkerMessage.setGroundItems,
905 regionX,
906 regionY,
907 items
908 });
909 }
910
911 #persistGroundEvent (event)
912 {
913 if (event.type === "ground-item-appear")
914 {
915 this.stateDb.upsertGroundItem({
916 groundItemId: event.groundItemId,
917 tileX: event.tileX,
918 tileY: event.tileY,
919 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
920 droppedAt: event.droppedAt ?? this.now,
921 expiresAt: event.expiresAt,
922 source: event.source ?? "player-drop",
923 droppedByCharacterId: event.droppedByCharacterId ?? null
924 });
925 }
926 if (event.type === "ground-item-despawn")
927 { this.stateDb.deleteGroundItem(event.groundItemId); }
373 928 }
374 929
375 #vacate (entityId, tileX, tileY)
930 #saveBag (entityId, workerId)
376 931 {
377 const key = tileKey(tileX, tileY);
378 if (this.occupancy.get(key) === entityId)
379 { this.occupancy.delete(key); }
932 const record = this.directory.get(entityId);
933 const bag = this.workers[workerId].call({
934 type: WorkerMessage.inspectBag,
935 entityId
936 });
937 if (!bag || !record?.characterId)
938 { return; }
939 this.#saveBagFromView(record.characterId, bag);
940 }
941
942 #saveBagFromView (characterId, bag)
943 {
944 this.stateDb.saveBag(characterId, {
945 inventory: bag.inventory,
946 equipment: bag.equipment,
947 currency: bag.currency,
948 vault: bag.vault,
949 vaultCurrency: bag.vaultCurrency
950 });
951 }
952
953 #remember (view, workerId)
954 {
955 if (!view)
956 { return; }
957 this.directory.set(view.entityId, { ...view, workerId });
958 if (view.characterId)
959 { this.characterEntities.set(view.characterId, view.entityId); }
960 }
961
962 #applyMoveToDirectory (event)
963 {
964 const record = this.directory.get(event.entityId);
965 if (!record)
966 { return; }
967 record.tileX = event.tileX;
968 record.tileY = event.tileY;
969 record.gait = event.gait;
380 970 }
381 971
382 #occupied (tileX, tileY)
972 #forget (entityId)
383 973 {
384 return this.occupancy.get(tileKey(tileX, tileY)) ?? null;
974 const record = this.directory.get(entityId);
975 if (record?.characterId)
976 { this.characterEntities.delete(record.characterId); }
977 this.directory.delete(entityId);
385 978 }
386 979 }
@@ -1,61 +1,118 @@
1import { CHUNK_SIZE, GAIT, VISIBLE_CHUNK_RADIUS, WORLD_YEAR_OFFSET } from "../../../shared/protocol/constants.js";
1import {
2import { tileToChunk, tileToLocal, chunkKey, visibleChunkCoords, tileKey } from "../world/coordinates.js";
2 CHUNK_SIZE,
3 DEFAULT_CHUNK_LOADER,
4 GAIT,
5 REGION_RUNTIME_STATE,
6 VISIBLE_CHUNK_RADIUS,
7 WORLD_YEAR_OFFSET
8} from "../../../shared/protocol/constants.js";
9import {
10 chunkKey,
11 chunkToRegion,
12 chunksInRegion,
13 parseChunkKey,
14 parseRegionKey,
15 regionKey,
16 regionTileBounds,
17 tileToChunk,
18 tileToLocal,
19 tileToRegion,
20 visibleChunkCoords
21} from "../world/coordinates.js";
3import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
22import { createEmptyChunkData, decodeChunkBlob, isChunkTilePassable } from "../world/chunkData.js";
4import { EcsWorld } from "../ecs/world.js";
5import { chunkBoundsAround, findPath } from "../navigation/astar.js";
6import { closedNeighborEdges } from "../world/chunkFlags.js";
23import { closedNeighborEdges } from "../world/chunkFlags.js";
24import { accumulateLoaderRefs, loaderCoverage } from "./chunkLoader.js";
25import { InProcessWorker } from "./inProcessWorker.js";
26import { ThreadWorker } from "./threadWorker.js";
27import { WorkerMessage } from "./protocol.js";
28import { replicaNeededForOwnedChunks } from "./workerWorld.js";
29import { replicationAppearance, replicationDespawn, replicationSpawn } from "../ecs/serialize.js";
30import { emptyEquipment, emptySlots } from "../../../shared/items/inventory.js";
31import { mobComponents } from "./spawners.js";
7
32
8export class Simulation
33export class Simulation
9{
34{
10 constructor (worldDb, stateDb)
35 constructor (worldDb, stateDb, options = {})
11 {
36 {
12 this.worldDb = worldDb;
37 this.worldDb = worldDb;
13 this.stateDb = stateDb;
38 this.stateDb = stateDb;
14 this.ecs = new EcsWorld();
39 this.workerCount = Math.max(1, Math.round(options.workerCount ?? Number(process.env.SIMULATION_WORKERS ?? 2)));
15 this.chunks = new Map();
40 this.workerMode = options.workerMode ?? process.env.SIMULATION_WORKER_MODE ?? "inprocess";
16 this.occupancy = new Map();
41 this.pinRegion = options.pinRegion ?? null;
42 this.nowFn = options.now ?? (() => Date.now());
43 this.workers = [];
44 this.regionOwner = new Map();
45 this.regionGraceUntil = new Map();
46 this.directory = new Map();
17 this.characterEntities = new Map();
47 this.characterEntities = new Map();
18 this.commandQueue = [];
48 this.commandQueue = [];
49 this.replication = [];
50 this.authoredCache = new Map();
51 this.nextEntityId = 1;
52 this.nextGroundItemId = stateDb.nextGroundItemId();
53 this.tickIndex = 0;
19 this.movementTickCounter = 0;
54 this.movementTickCounter = 0;
55 this.lastTickAt = null;
56 this.movementAccumulator = 0;
20 this.activeRevisionId = worldDb.getActiveRevisionId();
57 this.activeRevisionId = worldDb.getActiveRevisionId();
21 this.settings = worldDb.getLiveSettings();
58 this.settings = worldDb.getLiveSettings();
22 this.tickIndex = 0;
59
23 this.reloadWorld();
60 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
61 for (let workerId = 0; workerId < this.workerCount; workerId++)
62 {
63 const worker = new WorkerImpl(workerId);
64 worker.call({
65 type: WorkerMessage.configure,
66 settings: this.settings,
67 activeRevisionId: this.activeRevisionId
68 });
69 this.workers.push(worker);
70 }
71 }
72
73 get now ()
74 {
75 return this.nowFn();
24 }
76 }
25
77
26 applySettings (settings)
78 applySettings (settings)
27 {
79 {
28 this.settings = { ...this.settings, ...settings };
80 this.settings = { ...this.settings, ...settings };
81 this.#configureWorkers();
29 }
82 }
30
83
31 reloadWorld ()
84 reloadWorld ()
32 {
85 {
33 this.activeRevisionId = this.worldDb.getActiveRevisionId();
86 this.activeRevisionId = this.worldDb.getActiveRevisionId();
34 this.settings = this.worldDb.getLiveSettings();
87 this.settings = this.worldDb.getLiveSettings();
35 this.chunks.clear();
88 this.authoredCache.clear();
36 for (const entity of this.ecs.query("position"))
89 this.#configureWorkers();
90 for (const [key, workerId] of this.regionOwner)
37 {
91 {
38 const pos = entity.position;
92 const { regionX, regionY } = parseRegionKey(key);
39 this.#ensureChunk(tileToChunk(pos.tileX), tileToChunk(pos.tileY));
93 this.workers[workerId].call({
94 type: WorkerMessage.replaceRegionChunks,
95 chunks: this.#regionChunkBlobs(regionX, regionY)
96 });
40 }
97 }
98 this.#syncAllReplicas();
41 }
99 }
42
100
43 enqueue (sessionId, command)
101 enqueue (sessionId, command)
44 {
102 {
45 this.commandQueue.push({ sessionId, command, receivedAt: Date.now() });
103 this.commandQueue.push({ sessionId, command, receivedAt: this.now });
46 }
104 }
47
105
48 step (now = Date.now())
106 step (now = this.now)
49 {
107 {
50 this.tickIndex += 1;
108 this.tickIndex += 1;
51 const commands = this.commandQueue.splice(0);
52 const events = [];
109 const events = [];
110 const commands = this.commandQueue.splice(0);
53 for (const item of commands)
111 for (const item of commands)
54 {
112 {
55 try
113 try
56 {
114 {
57 const produced = this.#handleCommand(item.sessionId, item.command) ?? [];
115 events.push(...this.#routeCommand(item));
58 events.push(...produced);
59 }
116 }
60 catch (error)
117 catch (error)
61 {
118 {
@@ -67,19 +124,52 @@ export class Simulation
67 }
124 }
68 }
125 }
69
126
70 const movementHz = this.settings.walkTilesPerSecond * 2;
127 this.#recalculateActivation(now);
71 const simHz = this.settings.simulationTickHz;
128
72 const movementEvery = Math.max(1, Math.round(simHz / movementHz));
129 const simHz = Math.max(1, this.settings.simulationTickHz || 20);
73 if (this.tickIndex % movementEvery === 0)
130 const expectedDt = 1 / simHz;
131 const dt = (this.lastTickAt == null || now <= this.lastTickAt)
132 ? expectedDt
133 : Math.min(0.25, (now - this.lastTickAt) / 1000);
134 this.lastTickAt = now;
135
136 const movementHz = Math.max(0.25, (this.settings.walkTilesPerSecond || 2) * 2);
137 this.movementAccumulator += dt * movementHz;
138 while (this.movementAccumulator >= 1)
74 {
139 {
140 this.movementAccumulator -= 1;
75 this.movementTickCounter += 1;
141 this.movementTickCounter += 1;
76 events.push(...this.#stepMovement());
142 const transfers = [];
143 for (const worker of this.workers)
144 {
145 const result = worker.call({ type: WorkerMessage.stepMovement, now });
146 for (const event of result?.events ?? [])
147 {
148 if (event.type === "entity-move")
149 { this.#applyMoveToDirectory(event); }
150 this.#persistGroundEvent(event);
151 events.push(event);
152 }
153 for (const request of result?.transferRequests ?? [])
154 { transfers.push({ ...request, fromWorkerId: worker.workerId }); }
155 }
156 events.push(...this.#applyTransfers(transfers));
157 this.#recalculateActivation(now);
77 }
158 }
78
159
79 return { now, events };
160 if (this.tickIndex % Math.max(1, Math.round(simHz * 2)) === 0)
161 { events.push(...this.#stepSpawners()); }
162
163 this.#syncGhosts();
164 return { now, events, replication: this.drainReplication() };
80 }
165 }
81
166
82 worldTime (now = Date.now())
167 drainReplication ()
168 {
169 return this.replication.splice(0);
170 }
171
172 worldTime (now = this.now)
83 {
173 {
84 const date = new Date(now);
174 const date = new Date(now);
85 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
175 date.setFullYear(date.getFullYear() - WORLD_YEAR_OFFSET);
@@ -94,9 +184,9 @@ export class Simulation
94 spawnCharacter (sessionId, character)
184 spawnCharacter (sessionId, character)
95 {
185 {
96 this.despawnCharacter(character.character_id);
186 this.despawnCharacter(character.character_id);
97 const tileX = character.tile_x;
187 let tileX = character.tile_x;
98 const tileY = character.tile_y;
188 let tileY = character.tile_y;
99 if (!this.isEnterable(tileX, tileY))
189 if (!this.isEnterable(tileX, tileY) || this.#occupiedTile(tileX, tileY))
100 {
190 {
101 const spawn = this.findOpenSpawn();
191 const spawn = this.findOpenSpawn();
102 if (!spawn)
192 if (!spawn)
@@ -105,45 +195,113 @@ export class Simulation
105 error.userFacing = true;
195 error.userFacing = true;
106 throw error;
196 throw error;
107 }
197 }
108 character.tile_x = spawn.tileX;
198 tileX = spawn.tileX;
109 character.tile_y = spawn.tileY;
199 tileY = spawn.tileY;
110 this.stateDb.saveCharacterPosition(character.character_id, spawn.tileX, spawn.tileY, character.gait);
200 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, character.gait);
111 }
201 }
112
202
113 const id = this.ecs.entity();
203 const bag = this.stateDb.getBag(character.character_id) ?? {
114 this.ecs.add(id, "position", { tileX: character.tile_x, tileY: character.tile_y });
204 inventory: emptySlots(),
115 this.ecs.add(id, "movement", { gait: character.gait || GAIT.walk, path: [], walkCarry: 0 });
205 equipment: emptyEquipment(),
116 this.ecs.add(id, "appearance", {
206 currency: 0,
117 sex: character.sex,
207 vault: emptySlots(),
118 firstName: character.first_name,
208 vaultCurrency: 0
119 lastName: character.last_name
209 };
210 const entityId = this.nextEntityId++;
211 const components = {
212 position: { tileX, tileY },
213 movement: { gait: character.gait || GAIT.walk, walkCarry: 0 },
214 path: { tiles: [] },
215 appearance: {
216 sex: character.sex,
217 firstName: character.first_name,
218 lastName: character.last_name
219 },
220 character: {
221 characterId: character.character_id,
222 accountId: character.account_id
223 },
224 networkIdentity: { sessionId },
225 chunkLoader: { ...DEFAULT_CHUNK_LOADER },
226 inventory: { slots: bag.inventory ?? emptySlots() },
227 equipment: bag.equipment ?? emptyEquipment(),
228 currency: { amount: bag.currency ?? 0 },
229 vault: { slots: bag.vault ?? emptySlots(), currency: bag.vaultCurrency ?? 0 }
230 };
231 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
232 const workerId = this.#ownerOfTile(tileX, tileY);
233 const view = this.workers[workerId].call({
234 type: WorkerMessage.spawn,
235 entityId,
236 components
120 });
237 });
121 this.ecs.add(id, "character", {
238 this.#remember(view, workerId);
122 characterId: character.character_id,
239 this.#queueReplication(replicationSpawn(view));
123 accountId: character.account_id,
240 this.#recalculateActivation(this.now);
124 sessionId
241 this.#syncGhosts();
242 return entityId;
243 }
244
245 spawnEntity (components, options = {})
246 {
247 const entityId = options.entityId ?? this.nextEntityId++;
248 this.nextEntityId = Math.max(this.nextEntityId, entityId + 1);
249 const position = components.position;
250 if (!position)
251 { throw new Error("spawnEntity requires position."); }
252 if (components.chunkLoader)
253 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
254 else
255 {
256 this.#ensureRegion(
257 tileToRegion(position.tileX),
258 tileToRegion(position.tileY),
259 null
260 );
261 }
262 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
263 const view = this.workers[workerId].call({
264 type: WorkerMessage.spawn,
265 entityId,
266 components
125 });
267 });
126 this.characterEntities.set(character.character_id, id);
268 this.#remember(view, workerId);
127 this.#occupy(id, character.tile_x, character.tile_y);
269 if (components.appearance)
128 this.#ensureVisibleChunks(character.tile_x, character.tile_y);
270 { this.#queueReplication(replicationSpawn(view)); }
129 return id;
271 this.#recalculateActivation(this.now);
272 this.#syncGhosts();
273 return entityId;
130 }
274 }
131
275
132 despawnCharacter (characterId)
276 despawnCharacter (characterId)
133 {
277 {
134 const id = this.characterEntities.get(characterId);
278 const entityId = this.characterEntities.get(characterId);
135 if (!id)
279 if (!entityId)
136 { return; }
280 { return; }
137
281 const record = this.directory.get(entityId);
138 const position = this.ecs.get(id, "position");
282 if (!record)
139 const movement = this.ecs.get(id, "movement");
283 {
140 if (position)
284 this.characterEntities.delete(characterId);
285 return;
286 }
287 this.#saveBag(entityId, record.workerId);
288 const dropped = this.workers[record.workerId].call({
289 type: WorkerMessage.despawnCharacter,
290 characterId
291 });
292 if (dropped)
141 {
293 {
142 this.#vacate(id, position.tileX, position.tileY);
294 this.stateDb.saveCharacterPosition(
143 this.stateDb.saveCharacterPosition(characterId, position.tileX, position.tileY, movement?.gait ?? GAIT.walk);
295 characterId,
296 dropped.tileX,
297 dropped.tileY,
298 dropped.gait ?? GAIT.walk
299 );
300 this.#queueReplication(replicationDespawn(dropped));
144 }
301 }
145 this.ecs.destroy(id);
302 this.#forget(entityId);
146 this.characterEntities.delete(characterId);
303 this.#recalculateActivation(this.now);
304 this.#syncGhosts();
147 }
305 }
148
306
149 entityForCharacter (characterId)
307 entityForCharacter (characterId)
@@ -151,14 +309,48 @@ export class Simulation
151 return this.characterEntities.get(characterId) ?? null;
309 return this.characterEntities.get(characterId) ?? null;
152 }
310 }
153
311
312 entityRecord (entityId)
313 {
314 const record = this.directory.get(entityId);
315 return record ? { ...record } : null;
316 }
317
318 positionOf (entityId)
319 {
320 const record = this.directory.get(entityId);
321 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
322 }
323
324 bagOf (entityId)
325 {
326 const record = this.directory.get(entityId);
327 if (!record)
328 { return null; }
329 return this.workers[record.workerId].call({
330 type: WorkerMessage.inspectBag,
331 entityId
332 });
333 }
334
154 snapshotFor (entityId)
335 snapshotFor (entityId)
155 {
336 {
156 const position = this.ecs.get(entityId, "position");
337 const record = this.directory.get(entityId);
157 if (!position)
338 if (!record)
158 { return []; }
339 { return []; }
340 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
341 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY));
342 }
159
343
160 const coords = visibleChunkCoords(tileToChunk(position.tileX), tileToChunk(position.tileY), VISIBLE_CHUNK_RADIUS);
344 snapshotChunk (chunkX, chunkY)
161 return coords.map((coord) => this.#chunkSnapshot(coord.chunkX, coord.chunkY));
345 {
346 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
347 if (owner == null)
348 { return this.#syntheticSnapshot(chunkX, chunkY); }
349 return this.workers[owner].call({
350 type: WorkerMessage.snapshotChunk,
351 chunkX,
352 chunkY
353 });
162 }
354 }
163
355
164 findOpenSpawn ()
356 findOpenSpawn ()
@@ -166,7 +358,7 @@ export class Simulation
166 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
358 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
167 for (const coord of coords)
359 for (const coord of coords)
168 {
360 {
169 const data = this.#ensureChunk(coord.chunk_x, coord.chunk_y);
361 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
170 if (!data.open)
362 if (!data.open)
171 { continue; }
363 { continue; }
172 for (let localY = 0; localY < CHUNK_SIZE; localY++)
364 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -175,7 +367,7 @@ export class Simulation
175 {
367 {
176 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
368 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
177 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
369 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
178 if (this.isEnterable(tileX, tileY) && !this.#occupied(tileX, tileY))
370 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
179 { return { tileX, tileY }; }
371 { return { tileX, tileY }; }
180 }
372 }
181 }
373 }
@@ -185,202 +377,603 @@ export class Simulation
185
377
186 isEnterable (tileX, tileY)
378 isEnterable (tileX, tileY)
187 {
379 {
188 const data = this.#ensureChunk(tileToChunk(tileX), tileToChunk(tileY));
380 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
189 if (!data.open)
381 if (!data.open)
190 { return false; }
382 { return false; }
191 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
383 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
192 }
384 }
193
385
194 #handleCommand (sessionId, command)
386 debugWorld ()
195 {
387 {
196 switch (command.type)
388 const loaders = this.#allLoaders();
197 {
389 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
198 case "move-to":
390 const simulatingChunks = [...chunkSim.entries()]
199 return this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
391 .filter(([, count]) => count > 0)
200 case "set-gait":
392 .map(([key]) => key)
201 return this.#setGait(sessionId, command.characterId, command.gait);
393 .sort();
202 default:
394 return {
203 return [];
395 tickIndex: this.tickIndex,
204 }
396 workerCount: this.workers.length,
397 workerMode: this.workerMode,
398 simulatingChunks,
399 regions: [...this.regionOwner.entries()].map(([key, workerId]) => ({
400 ...parseRegionKey(key),
401 workerId,
402 state: REGION_RUNTIME_STATE.resident,
403 refs: regionRes.get(key) ?? 0,
404 graceUntil: this.regionGraceUntil.get(key) ?? null
405 })),
406 entities: [...this.directory.values()].map((entity) => ({
407 entityId: entity.entityId,
408 workerId: entity.workerId,
409 tileX: entity.tileX,
410 tileY: entity.tileY,
411 characterId: entity.characterId
412 }))
413 };
205 }
414 }
206
415
207 #moveTo (sessionId, characterId, tileX, tileY)
416 async shutdown ()
208 {
417 {
209 const id = this.#requireOwnedEntity(sessionId, characterId);
418 for (const characterId of [...this.characterEntities.keys()])
210 const position = this.ecs.get(id, "position");
419 { this.despawnCharacter(characterId); }
211 const movement = this.ecs.get(id, "movement");
420 this.forceUnloadAll();
212 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
421 await Promise.all(this.workers.map((worker) => worker.terminate()));
213 const path = findPath(
214 position.tileX,
215 position.tileY,
216 tileX,
217 tileY,
218 (x, y) => this.#walkableFor(id, x, y),
219 bounds.minX,
220 bounds.minY,
221 bounds.maxX,
222 bounds.maxY
223 );
224 movement.path = path;
225 movement.walkCarry = 0;
226 return [];
227 }
422 }
228
423
229 #setGait (sessionId, characterId, gait)
424 forceUnloadAll ()
230 {
425 {
231 if (gait !== GAIT.walk && gait !== GAIT.run)
426 for (const key of [...this.regionOwner.keys()])
232 {
427 {
233 const error = new Error("Gait must be walk or run.");
428 const { regionX, regionY } = parseRegionKey(key);
234 error.userFacing = true;
429 this.#unloadRegion(regionX, regionY);
235 throw error;
236 }
430 }
237 const id = this.#requireOwnedEntity(sessionId, characterId);
238 this.ecs.get(id, "movement").gait = gait;
239 return [];
240 }
431 }
241
432
242 #requireOwnedEntity (sessionId, characterId)
433 #configureWorkers ()
243 {
434 {
244 const id = this.characterEntities.get(characterId);
435 for (const worker of this.workers)
245 if (!id)
246 {
436 {
247 const error = new Error("Character is not in the world.");
437 worker.call({
248 error.userFacing = true;
438 type: WorkerMessage.configure,
249 throw error;
439 settings: this.settings,
440 activeRevisionId: this.activeRevisionId
441 });
250 }
442 }
251 const character = this.ecs.get(id, "character");
443 }
252 if (!character || character.sessionId !== sessionId)
444
445 #routeCommand (item)
446 {
447 const entityId = this.characterEntities.get(item.command.characterId);
448 const record = entityId ? this.directory.get(entityId) : null;
449 if (!record)
253 {
450 {
254 const error = new Error("Character is not in the world.");
451 const error = new Error("Character is not in the world.");
255 error.userFacing = true;
452 error.userFacing = true;
256 throw error;
453 throw error;
257 }
454 }
258 return id;
455 if (item.command.type === "drop-item" && item.command.groundItemId == null)
456 { item.command.groundItemId = this.nextGroundItemId++; }
457 const result = this.workers[record.workerId].call({
458 type: WorkerMessage.command,
459 sessionId: item.sessionId,
460 command: item.command,
461 now: item.receivedAt ?? this.now
462 });
463 const view = this.workers[record.workerId].call({
464 type: WorkerMessage.inspect,
465 entityId: record.entityId
466 });
467 if (view)
468 { this.#remember(view, record.workerId); }
469 if (result?.private)
470 { this.#saveBagFromView(item.command.characterId, result.private); }
471 if (result?.appearanceChanged && view)
472 { this.#queueReplication(replicationAppearance(view)); }
473 if (result?.remainder)
474 {
475 this.stateDb.saveInheritance(
476 this.stateDb.getCharacter(item.command.characterId).account_id,
477 { slots: result.remainder, currency: 0 }
478 );
479 }
480 for (const event of result?.events ?? [])
481 { this.#persistGroundEvent(event); }
482 const events = [...(result?.events ?? [])];
483 if (result?.private)
484 {
485 events.push({
486 type: "inventory",
487 sessionId: item.sessionId,
488 bank: !!result.bank,
489 ...result.private
490 });
491 }
492 return events;
259 }
493 }
260
494
261 #stepMovement ()
495 #recalculateActivation (now)
262 {
496 {
263 const events = [];
497 const loaders = this.#allLoaders();
264 for (const entity of this.ecs.query("position", "movement"))
498 const { chunkSim, regionRes } = accumulateLoaderRefs(loaders);
499
500 for (const [key, count] of regionRes)
265 {
501 {
266 const { id, position, movement } = entity;
502 if (count <= 0)
267 if (!movement.path.length)
268 { continue; }
503 { continue; }
504 const { regionX, regionY } = parseRegionKey(key);
505 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
506 this.regionGraceUntil.delete(key);
507 }
508
509 for (const [key] of [...this.regionOwner.entries()])
510 {
511 if ((regionRes.get(key) ?? 0) > 0)
512 { continue; }
513 if (!this.regionGraceUntil.has(key))
514 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
515 if (now >= this.regionGraceUntil.get(key))
516 {
517 const { regionX, regionY } = parseRegionKey(key);
518 this.#unloadRegion(regionX, regionY);
519 }
520 }
269
521
270 const isWalk = movement.gait !== GAIT.run;
522 for (const [workerId, worker] of this.workers.entries())
271 if (isWalk)
523 {
524 const chunkKeys = [];
525 for (const [key, count] of chunkSim)
272 {
526 {
273 movement.walkCarry = (movement.walkCarry + 1) % 2;
527 if (count <= 0)
274 if (movement.walkCarry !== 0)
275 { continue; }
528 { continue; }
529 const { chunkX, chunkY } = parseChunkKey(key);
530 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
531 { chunkKeys.push(key); }
532 }
533 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
534 }
535 this.#syncAllReplicas();
536 }
537
538 #ensureCoverage (tileX, tileY, loader)
539 {
540 const coverage = loaderCoverage(tileX, tileY, loader);
541 let preferred = this.#ownerOfTile(tileX, tileY);
542 for (const region of coverage.residentRegions)
543 {
544 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
545 if (preferred == null)
546 { preferred = owner; }
547 }
548 }
549
550 #ensureRegion (regionX, regionY, preferredWorkerId)
551 {
552 const key = regionKey(regionX, regionY);
553 if (this.regionOwner.has(key))
554 { return this.regionOwner.get(key); }
555 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
556 this.workers[workerId].call({
557 type: WorkerMessage.assignRegion,
558 regionX,
559 regionY,
560 chunks: this.#regionChunkBlobs(regionX, regionY)
561 });
562 this.regionOwner.set(key, workerId);
563 this.#restorePersistent(regionX, regionY, workerId);
564 this.#restoreGroundItems(regionX, regionY, workerId);
565 return workerId;
566 }
567
568 #unloadRegion (regionX, regionY)
569 {
570 const key = regionKey(regionX, regionY);
571 const workerId = this.regionOwner.get(key);
572 if (workerId == null)
573 { return; }
574 const bounds = regionTileBounds(regionX, regionY);
575 const { dropped, groundItems } = this.workers[workerId].call({
576 type: WorkerMessage.dropRegion,
577 regionX,
578 regionY
579 });
580 const persistent = [];
581 for (const record of dropped ?? [])
582 {
583 if (record.characterId)
584 {
585 this.stateDb.saveCharacterPosition(
586 record.characterId,
587 record.tileX,
588 record.tileY,
589 record.gait ?? GAIT.walk
590 );
276 }
591 }
592 if (record.persistent)
593 { persistent.push(record); }
594 this.#forget(record.entityId);
595 }
596 this.stateDb.replacePersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY, persistent);
597 for (const item of groundItems ?? [])
598 { this.stateDb.upsertGroundItem(item); }
599 this.regionOwner.delete(key);
600 this.regionGraceUntil.delete(key);
601 }
277
602
278 const next = movement.path[0];
603 #restorePersistent (regionX, regionY, workerId)
279 if (!this.#walkableFor(id, next.x, next.y))
604 {
605 const bounds = regionTileBounds(regionX, regionY);
606 const rows = this.stateDb.listPersistentInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY);
607 for (const row of rows)
608 {
609 if (this.directory.has(row.entity_id))
280 { continue; }
610 { continue; }
611 const components = JSON.parse(row.components_blob);
612 const view = this.workers[workerId].call({
613 type: WorkerMessage.spawn,
614 entityId: row.entity_id,
615 components
616 });
617 this.nextEntityId = Math.max(this.nextEntityId, row.entity_id + 1);
618 this.#remember(view, workerId);
619 }
620 }
281
621
282 const fromTileX = position.tileX;
622 #applyTransfers (requests)
283 const fromTileY = position.tileY;
623 {
284 this.#vacate(id, fromTileX, fromTileY);
624 const events = [];
285 position.tileX = next.x;
625 for (const request of requests)
286 position.tileY = next.y;
626 {
287 movement.path.shift();
627 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
288 this.#occupy(id, position.tileX, position.tileY);
628 if (destWorkerId === request.fromWorkerId)
289 this.#ensureVisibleChunks(position.tileX, position.tileY);
629 {
290 const character = this.ecs.get(id, "character");
630 this.workers[request.fromWorkerId].call({
291 const appearance = this.ecs.get(id, "appearance");
631 type: WorkerMessage.abortTransfer,
632 entityId: request.entityId
633 });
634 continue;
635 }
636 let result;
637 try
638 {
639 result = this.workers[destWorkerId].call({
640 type: WorkerMessage.applyTransfer,
641 payload: request.payload,
642 destTileX: request.destTileX,
643 destTileY: request.destTileY
644 });
645 }
646 catch
647 {
648 result = { accepted: false };
649 }
650 if (!result?.accepted)
651 {
652 this.workers[request.fromWorkerId].call({
653 type: WorkerMessage.abortTransfer,
654 entityId: request.entityId
655 });
656 continue;
657 }
658 this.workers[request.fromWorkerId].call({
659 type: WorkerMessage.commitTransfer,
660 entityId: request.entityId
661 });
662 this.#remember(result.entity, destWorkerId);
292 events.push({
663 events.push({
293 type: "entity-move",
664 type: "entity-move",
294 entityId: id,
665 entityId: request.entityId,
295 characterId: character?.characterId,
666 fromTileX: request.fromTileX,
296 fromTileX,
667 fromTileY: request.fromTileY,
297 fromTileY,
668 tileX: result.entity.tileX,
298 tileX: position.tileX,
669 tileY: result.entity.tileY,
299 tileY: position.tileY,
670 gait: result.entity.gait
300 gait: movement.gait,
301 sex: appearance?.sex,
302 firstName: appearance?.firstName,
303 lastName: appearance?.lastName
304 });
671 });
305 }
672 }
306 return events;
673 return events;
307 }
674 }
308
675
309 #walkableFor (entityId, tileX, tileY)
676 #syncAllReplicas ()
310 {
677 {
311 if (!this.isEnterable(tileX, tileY))
678 for (const [workerId, worker] of this.workers.entries())
312 { return false; }
679 {
313 const occupant = this.#occupied(tileX, tileY);
680 const ownedKeys = new Set();
314 return !occupant || occupant === entityId;
681 for (const [key, owner] of this.regionOwner)
682 {
683 if (owner !== workerId)
684 { continue; }
685 const { regionX, regionY } = parseRegionKey(key);
686 for (const chunk of chunksInRegion(regionX, regionY))
687 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
688 }
689 const replicas = [];
690 for (const key of replicaNeededForOwnedChunks(ownedKeys))
691 {
692 if (ownedKeys.has(key))
693 { continue; }
694 const { chunkX, chunkY } = parseChunkKey(key);
695 replicas.push({
696 chunkX,
697 chunkY,
698 data: this.#authoredChunk(chunkX, chunkY)
699 });
700 }
701 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
702 }
315 }
703 }
316
704
317 #ensureVisibleChunks (tileX, tileY)
705 #syncGhosts ()
318 {
706 {
319 for (const coord of visibleChunkCoords(tileToChunk(tileX), tileToChunk(tileY), VISIBLE_CHUNK_RADIUS))
707 const entities = [];
320 { this.#ensureChunk(coord.chunkX, coord.chunkY); }
708 for (const worker of this.workers)
709 { entities.push(...(worker.call({ type: WorkerMessage.listPublicEntities }) ?? [])); }
710 for (const [workerId, worker] of this.workers.entries())
711 {
712 const ghosts = entities.filter((entity) =>
713 {
714 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
715 { return false; }
716 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
717 });
718 worker.call({ type: WorkerMessage.setGhosts, ghosts });
719 }
321 }
720 }
322
721
323 #ensureChunk (chunkX, chunkY)
722 #nearWorker (workerId, tileX, tileY)
324 {
723 {
325 const key = chunkKey(chunkX, chunkY);
724 const chunkX = tileToChunk(tileX);
326 if (this.chunks.has(key))
725 const chunkY = tileToChunk(tileY);
327 { return this.chunks.get(key); }
726 for (const [key, owner] of this.regionOwner)
727 {
728 if (owner !== workerId)
729 { continue; }
730 const { regionX, regionY } = parseRegionKey(key);
731 for (const chunk of chunksInRegion(regionX, regionY))
732 {
733 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
734 { return true; }
735 }
736 }
737 return false;
738 }
739
740 #allLoaders ()
741 {
742 const loaders = [];
743 for (const worker of this.workers)
744 { loaders.push(...(worker.call({ type: WorkerMessage.listLoaders }) ?? [])); }
745 return loaders;
746 }
747
748 #preferredWorkerForRegion (loaders, regionX, regionY)
749 {
750 const votes = new Map();
751 for (const loader of loaders)
752 {
753 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
754 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
755 { continue; }
756 const record = this.directory.get(loader.entityId);
757 if (record?.workerId == null)
758 { continue; }
759 votes.set(record.workerId, (votes.get(record.workerId) ?? 0) + 1);
760 }
761 let best = null;
762 let bestVotes = -1;
763 for (const [workerId, count] of votes)
764 {
765 if (count > bestVotes)
766 {
767 best = workerId;
768 bestVotes = count;
769 }
770 }
771 return best;
772 }
773
774 #pickWorker (regionX, regionY, preferredWorkerId)
775 {
776 const pinned = this.pinRegion?.(regionX, regionY);
777 if (pinned != null)
778 { return pinned; }
779
780 const neighborOwners = [];
781 for (let dy = -1; dy <= 1; dy++)
782 {
783 for (let dx = -1; dx <= 1; dx++)
784 {
785 if (dx === 0 && dy === 0)
786 { continue; }
787 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
788 if (owner != null)
789 { neighborOwners.push(owner); }
790 }
791 }
792
793 const scores = this.workers.map((_, workerId) => ({
794 workerId,
795 neighbors: neighborOwners.filter((owner) => owner === workerId).length,
796 load: [...this.regionOwner.values()].filter((owner) => owner === workerId).length
797 }));
798
799 if (preferredWorkerId != null && scores[preferredWorkerId])
800 {
801 const preferred = scores[preferredWorkerId];
802 if (preferred.neighbors > 0 || neighborOwners.length === 0)
803 { return preferredWorkerId; }
804 }
805
806 scores.sort((left, right) =>
807 right.neighbors - left.neighbors
808 || left.load - right.load
809 || left.workerId - right.workerId
810 );
811 return scores[0].workerId;
812 }
328
813
814 #ownerOfTile (tileX, tileY)
815 {
816 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
817 }
818
819 #regionKeyForChunk (chunkX, chunkY)
820 {
821 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
822 }
823
824 #regionChunkBlobs (regionX, regionY)
825 {
826 return chunksInRegion(regionX, regionY).map((coord) => ({
827 chunkX: coord.chunkX,
828 chunkY: coord.chunkY,
829 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
830 }));
831 }
832
833 #authoredChunk (chunkX, chunkY)
834 {
835 const key = chunkKey(chunkX, chunkY);
836 if (this.authoredCache.has(key))
837 { return this.authoredCache.get(key); }
329 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
838 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
330 const data = row
839 const data = row
331 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
840 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId)
332 : createEmptyChunkData(this.settings.defaultGroundTypeId);
841 : createEmptyChunkData(this.settings.defaultGroundTypeId);
333 this.chunks.set(key, data);
842 this.authoredCache.set(key, data);
334 return data;
843 return data;
335 }
844 }
336
845
337 #chunkSnapshot (chunkX, chunkY)
846 #syntheticSnapshot (chunkX, chunkY)
338 {
847 {
339 const data = this.#ensureChunk(chunkX, chunkY);
848 const data = this.#authoredChunk(chunkX, chunkY);
340 const entities = [];
341 for (const entity of this.ecs.query("position", "appearance"))
342 {
343 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
344 { continue; }
345 const movement = this.ecs.get(entity.id, "movement");
346 const character = this.ecs.get(entity.id, "character");
347 entities.push({
348 entityId: entity.id,
349 characterId: character?.characterId ?? null,
350 tileX: entity.position.tileX,
351 tileY: entity.position.tileY,
352 gait: movement?.gait ?? GAIT.walk,
353 sex: entity.appearance.sex,
354 firstName: entity.appearance.firstName,
355 lastName: entity.appearance.lastName
356 });
357 }
358 return {
849 return {
359 chunkX,
850 chunkX,
360 chunkY,
851 chunkY,
361 open: data.open,
852 open: data.open,
362 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#ensureChunk(x, y).open),
853 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
363 grounds: data.grounds,
854 grounds: data.grounds,
364 blocks: data.blocks,
855 blocks: data.blocks,
365 light: data.light,
856 light: data.light,
366 entities
857 entities: [],
858 groundItems: []
367 };
859 };
368 }
860 }
369
861
370 #occupy (entityId, tileX, tileY)
862 #occupiedTile (tileX, tileY)
863 {
864 for (const record of this.directory.values())
865 {
866 if (record.tileX === tileX && record.tileY === tileY)
867 { return record.entityId; }
868 }
869 return null;
870 }
871
872 #queueReplication (event)
873 {
874 if (event)
875 { this.replication.push(event); }
876 }
877
878 #stepSpawners ()
879 {
880 const events = [];
881 for (const worker of this.workers)
882 {
883 const result = worker.call({ type: WorkerMessage.stepSpawners });
884 for (const request of result?.spawnRequests ?? [])
885 {
886 try
887 {
888 this.spawnEntity(mobComponents(request));
889 }
890 catch
891 { continue; }
892 }
893 }
894 return events;
895 }
896
897 #restoreGroundItems (regionX, regionY, workerId)
371 {
898 {
372 this.occupancy.set(tileKey(tileX, tileY), entityId);
899 const bounds = regionTileBounds(regionX, regionY);
900 const items = this.stateDb.listGroundItemsInRegion(bounds.minX, bounds.minY, bounds.maxX, bounds.maxY)
901 .filter((item) => item.expiresAt > this.now);
902 this.nextGroundItemId = Math.max(this.nextGroundItemId, this.stateDb.nextGroundItemId());
903 this.workers[workerId].call({
904 type: WorkerMessage.setGroundItems,
905 regionX,
906 regionY,
907 items
908 });
909 }
910
911 #persistGroundEvent (event)
912 {
913 if (event.type === "ground-item-appear")
914 {
915 this.stateDb.upsertGroundItem({
916 groundItemId: event.groundItemId,
917 tileX: event.tileX,
918 tileY: event.tileY,
919 stack: event.stack ?? { itemId: event.itemId, quantity: event.quantity },
920 droppedAt: event.droppedAt ?? this.now,
921 expiresAt: event.expiresAt,
922 source: event.source ?? "player-drop",
923 droppedByCharacterId: event.droppedByCharacterId ?? null
924 });
925 }
926 if (event.type === "ground-item-despawn")
927 { this.stateDb.deleteGroundItem(event.groundItemId); }
373 }
928 }
374
929
375 #vacate (entityId, tileX, tileY)
930 #saveBag (entityId, workerId)
376 {
931 {
377 const key = tileKey(tileX, tileY);
932 const record = this.directory.get(entityId);
378 if (this.occupancy.get(key) === entityId)
933 const bag = this.workers[workerId].call({
379 { this.occupancy.delete(key); }
934 type: WorkerMessage.inspectBag,
935 entityId
936 });
937 if (!bag || !record?.characterId)
938 { return; }
939 this.#saveBagFromView(record.characterId, bag);
940 }
941
942 #saveBagFromView (characterId, bag)
943 {
944 this.stateDb.saveBag(characterId, {
945 inventory: bag.inventory,
946 equipment: bag.equipment,
947 currency: bag.currency,
948 vault: bag.vault,
949 vaultCurrency: bag.vaultCurrency
950 });
951 }
952
953 #remember (view, workerId)
954 {
955 if (!view)
956 { return; }
957 this.directory.set(view.entityId, { ...view, workerId });
958 if (view.characterId)
959 { this.characterEntities.set(view.characterId, view.entityId); }
960 }
961
962 #applyMoveToDirectory (event)
963 {
964 const record = this.directory.get(event.entityId);
965 if (!record)
966 { return; }
967 record.tileX = event.tileX;
968 record.tileY = event.tileY;
969 record.gait = event.gait;
380 }
970 }
381
971
382 #occupied (tileX, tileY)
972 #forget (entityId)
383 {
973 {
384 return this.occupancy.get(tileKey(tileX, tileY)) ?? null;
974 const record = this.directory.get(entityId);
975 if (record?.characterId)
976 { this.characterEntities.delete(record.characterId); }
977 this.directory.delete(entityId);
385 }
978 }
386}
979}
server/src/simulation/spawners.js added +96 −0
@@ -0,0 +1,96 @@
1 import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 import { BlockType } from "../../../shared/definitions/tiles.js";
3 import { defaultSpawnerConfig, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4 import { Component } from "../ecs/components.js";
5 import { tileToRegion } from "../world/coordinates.js";
6
7 export function collectSpawnRequests (world)
8 {
9 const requests = [];
10 const counts = countBySpawner(world);
11 for (const [key, chunk] of world.chunks)
12 {
13 if (chunk.replica || !chunk.simulating || !chunk.data.open)
14 { continue; }
15 const [chunkX, chunkY] = key.split(",").map(Number);
16 for (let localY = 0; localY < CHUNK_SIZE; localY++)
17 {
18 for (let localX = 0; localX < CHUNK_SIZE; localX++)
19 {
20 const block = chunk.data.blocks[localY * CHUNK_SIZE + localX];
21 if (block?.typeId !== BlockType.spawner)
22 { continue; }
23 const config = { ...defaultSpawnerConfig(`${chunkX}:${chunkY}:${localY * CHUNK_SIZE + localX}`), ...(block.config ?? {}) };
24 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
25 { continue; }
26 const originX = chunkX * CHUNK_SIZE + localX;
27 const originY = chunkY * CHUNK_SIZE + localY;
28 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles);
29 if (!tile)
30 { continue; }
31 requests.push({
32 ...tile,
33 mobTypeId: config.mobTypeId,
34 spawnerId: config.spawnerId,
35 persistent: !!mobDefinition(config.mobTypeId)?.persistent
36 });
37 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
38 }
39 }
40 }
41 return requests;
42 }
43
44 export function mobComponents (request)
45 {
46 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
47 const components = {
48 position: { tileX: request.tileX, tileY: request.tileY },
49 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
50 path: { tiles: [] },
51 appearance: {
52 sex: def.sex ?? "male",
53 firstName: def.displayName,
54 lastName: "",
55 sprite: mobSpriteName(def.mobTypeId)
56 },
57 creature: { mobTypeId: def.mobTypeId },
58 health: { current: def.health ?? 8, max: def.health ?? 8 },
59 spawnOrigin: { spawnerId: request.spawnerId }
60 };
61 if (def.persistent)
62 { components.persistent = {}; }
63 return components;
64 }
65
66 function countBySpawner (world)
67 {
68 const counts = new Map();
69 for (const entity of world.ecs.query(Component.spawnOrigin))
70 {
71 const id = entity.spawnOrigin.spawnerId;
72 counts.set(id, (counts.get(id) ?? 0) + 1);
73 }
74 return counts;
75 }
76
77 function pickSpawnTile (world, originX, originY, range)
78 {
79 const radius = Math.max(1, range | 0);
80 for (let attempt = 0; attempt < 24; attempt++)
81 {
82 const tileX = originX + randInt(-radius, radius);
83 const tileY = originY + randInt(-radius, radius);
84 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
85 { continue; }
86 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
87 { continue; }
88 return { tileX, tileY };
89 }
90 return null;
91 }
92
93 function randInt (min, max)
94 {
95 return min + Math.floor(Math.random() * (max - min + 1));
96 }
@@ -0,0 +1,96 @@
1import { GAIT, CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { BlockType } from "../../../shared/definitions/tiles.js";
3import { defaultSpawnerConfig, mobDefinition, mobSpriteName } from "../../../shared/definitions/mobs.js";
4import { Component } from "../ecs/components.js";
5import { tileToRegion } from "../world/coordinates.js";
6
7export function collectSpawnRequests (world)
8{
9 const requests = [];
10 const counts = countBySpawner(world);
11 for (const [key, chunk] of world.chunks)
12 {
13 if (chunk.replica || !chunk.simulating || !chunk.data.open)
14 { continue; }
15 const [chunkX, chunkY] = key.split(",").map(Number);
16 for (let localY = 0; localY < CHUNK_SIZE; localY++)
17 {
18 for (let localX = 0; localX < CHUNK_SIZE; localX++)
19 {
20 const block = chunk.data.blocks[localY * CHUNK_SIZE + localX];
21 if (block?.typeId !== BlockType.spawner)
22 { continue; }
23 const config = { ...defaultSpawnerConfig(`${chunkX}:${chunkY}:${localY * CHUNK_SIZE + localX}`), ...(block.config ?? {}) };
24 if ((counts.get(config.spawnerId) ?? 0) >= config.maxAlive)
25 { continue; }
26 const originX = chunkX * CHUNK_SIZE + localX;
27 const originY = chunkY * CHUNK_SIZE + localY;
28 const tile = pickSpawnTile(world, originX, originY, config.spawnRangeTiles);
29 if (!tile)
30 { continue; }
31 requests.push({
32 ...tile,
33 mobTypeId: config.mobTypeId,
34 spawnerId: config.spawnerId,
35 persistent: !!mobDefinition(config.mobTypeId)?.persistent
36 });
37 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
38 }
39 }
40 }
41 return requests;
42}
43
44export function mobComponents (request)
45{
46 const def = mobDefinition(request.mobTypeId) ?? mobDefinition("deer");
47 const components = {
48 position: { tileX: request.tileX, tileY: request.tileY },
49 movement: { gait: def.gait ?? GAIT.walk, walkCarry: 0 },
50 path: { tiles: [] },
51 appearance: {
52 sex: def.sex ?? "male",
53 firstName: def.displayName,
54 lastName: "",
55 sprite: mobSpriteName(def.mobTypeId)
56 },
57 creature: { mobTypeId: def.mobTypeId },
58 health: { current: def.health ?? 8, max: def.health ?? 8 },
59 spawnOrigin: { spawnerId: request.spawnerId }
60 };
61 if (def.persistent)
62 { components.persistent = {}; }
63 return components;
64}
65
66function countBySpawner (world)
67{
68 const counts = new Map();
69 for (const entity of world.ecs.query(Component.spawnOrigin))
70 {
71 const id = entity.spawnOrigin.spawnerId;
72 counts.set(id, (counts.get(id) ?? 0) + 1);
73 }
74 return counts;
75}
76
77function pickSpawnTile (world, originX, originY, range)
78{
79 const radius = Math.max(1, range | 0);
80 for (let attempt = 0; attempt < 24; attempt++)
81 {
82 const tileX = originX + randInt(-radius, radius);
83 const tileY = originY + randInt(-radius, radius);
84 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
85 { continue; }
86 if (!world.isEnterable(tileX, tileY) || world.occupied(tileX, tileY))
87 { continue; }
88 return { tileX, tileY };
89 }
90 return null;
91}
92
93function randInt (min, max)
94{
95 return min + Math.floor(Math.random() * (max - min + 1));
96}
server/src/simulation/threadWorker.js added +54 −0
@@ -0,0 +1,54 @@
1 import { Worker, receiveMessageOnPort, MessageChannel } from "node:worker_threads";
2 import { fileURLToPath } from "node:url";
3
4 const workerMainPath = fileURLToPath(new URL("./threadWorkerMain.js", import.meta.url));
5
6 export class ThreadWorker
7 {
8 constructor (workerId)
9 {
10 this.workerId = workerId;
11 this.sync = new Int32Array(new SharedArrayBuffer(4));
12 this.worker = new Worker(workerMainPath, {
13 workerData: { workerId, sync: this.sync.buffer }
14 });
15 this.worker.on("error", (error) =>
16 {
17 this.error = error;
18 });
19 }
20
21 call (message)
22 {
23 if (this.error)
24 { throw this.error; }
25 const { port1, port2 } = new MessageChannel();
26 Atomics.store(this.sync, 0, 0);
27 this.worker.postMessage({ message, port: port2 }, [port2]);
28 const status = Atomics.wait(this.sync, 0, 0, 10_000);
29 if (status === "timed-out")
30 {
31 port1.close();
32 throw new Error(`Simulation worker ${this.workerId} timed out.`);
33 }
34 const received = receiveMessageOnPort(port1);
35 port1.close();
36 if (this.error)
37 { throw this.error; }
38 if (!received)
39 { throw new Error(`Simulation worker ${this.workerId} returned no result.`); }
40 const result = received.message;
41 if (result?.__error)
42 {
43 const error = new Error(result.__error.message);
44 error.userFacing = result.__error.userFacing;
45 throw error;
46 }
47 return result;
48 }
49
50 async terminate ()
51 {
52 await this.worker.terminate();
53 }
54 }
@@ -0,0 +1,54 @@
1import { Worker, receiveMessageOnPort, MessageChannel } from "node:worker_threads";
2import { fileURLToPath } from "node:url";
3
4const workerMainPath = fileURLToPath(new URL("./threadWorkerMain.js", import.meta.url));
5
6export class ThreadWorker
7{
8 constructor (workerId)
9 {
10 this.workerId = workerId;
11 this.sync = new Int32Array(new SharedArrayBuffer(4));
12 this.worker = new Worker(workerMainPath, {
13 workerData: { workerId, sync: this.sync.buffer }
14 });
15 this.worker.on("error", (error) =>
16 {
17 this.error = error;
18 });
19 }
20
21 call (message)
22 {
23 if (this.error)
24 { throw this.error; }
25 const { port1, port2 } = new MessageChannel();
26 Atomics.store(this.sync, 0, 0);
27 this.worker.postMessage({ message, port: port2 }, [port2]);
28 const status = Atomics.wait(this.sync, 0, 0, 10_000);
29 if (status === "timed-out")
30 {
31 port1.close();
32 throw new Error(`Simulation worker ${this.workerId} timed out.`);
33 }
34 const received = receiveMessageOnPort(port1);
35 port1.close();
36 if (this.error)
37 { throw this.error; }
38 if (!received)
39 { throw new Error(`Simulation worker ${this.workerId} returned no result.`); }
40 const result = received.message;
41 if (result?.__error)
42 {
43 const error = new Error(result.__error.message);
44 error.userFacing = result.__error.userFacing;
45 throw error;
46 }
47 return result;
48 }
49
50 async terminate ()
51 {
52 await this.worker.terminate();
53 }
54}
server/src/simulation/threadWorkerMain.js added +24 −0
@@ -0,0 +1,24 @@
1 import { parentPort, workerData } from "node:worker_threads";
2 import { WorkerWorld } from "./workerWorld.js";
3
4 const sync = new Int32Array(workerData.sync);
5 const world = new WorkerWorld(workerData.workerId);
6
7 parentPort.on("message", ({ message, port }) =>
8 {
9 let result;
10 try
11 { result = world.handle(message); }
12 catch (error)
13 {
14 result = {
15 __error: {
16 message: error.message,
17 userFacing: !!error.userFacing
18 }
19 };
20 }
21 port.postMessage(result);
22 Atomics.store(sync, 0, 1);
23 Atomics.notify(sync, 0);
24 });
@@ -0,0 +1,24 @@
1import { parentPort, workerData } from "node:worker_threads";
2import { WorkerWorld } from "./workerWorld.js";
3
4const sync = new Int32Array(workerData.sync);
5const world = new WorkerWorld(workerData.workerId);
6
7parentPort.on("message", ({ message, port }) =>
8{
9 let result;
10 try
11 { result = world.handle(message); }
12 catch (error)
13 {
14 result = {
15 __error: {
16 message: error.message,
17 userFacing: !!error.userFacing
18 }
19 };
20 }
21 port.postMessage(result);
22 Atomics.store(sync, 0, 1);
23 Atomics.notify(sync, 0);
24});
server/src/simulation/workerWorld.js added +616 −0
@@ -0,0 +1,616 @@
1 import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 import {
3 chunkKey,
4 chunkToRegion,
5 parseChunkKey,
6 regionKey,
7 tileKey,
8 tileToChunk,
9 tileToLocal,
10 tileToRegion
11 } from "../world/coordinates.js";
12 import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
13 import { closedNeighborEdges } from "../world/chunkFlags.js";
14 import { EcsWorld } from "../ecs/world.js";
15 import { Component } from "../ecs/components.js";
16 import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
17 import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18 import { WorkerMessage } from "./protocol.js";
19 import { collectSpawnRequests } from "./spawners.js";
20 import {
21 bagView,
22 expireGroundItems,
23 groundItemsInChunk,
24 groundItemsInRegion,
25 handleItemCommand,
26 removeGroundItem,
27 setGroundItemsForRegion
28 } from "../items/bags.js";
29
30 export class WorkerWorld
31 {
32 constructor (workerId)
33 {
34 this.workerId = workerId;
35 this.ecs = new EcsWorld();
36 this.chunks = new Map();
37 this.ownedRegions = new Set();
38 this.occupancy = new Map();
39 this.ghosts = new Map();
40 this.ghostOccupancy = new Map();
41 this.characterEntities = new Map();
42 this.frozen = new Set();
43 this.groundItems = new Map();
44 this.groundByTile = new Map();
45 this.settings = { ...DEFAULT_WORLD_SETTINGS };
46 this.activeRevisionId = 1;
47 }
48
49 handle (message)
50 {
51 switch (message.type)
52 {
53 case WorkerMessage.configure:
54 return this.#configure(message);
55 case WorkerMessage.assignRegion:
56 return this.#assignRegion(message);
57 case WorkerMessage.dropRegion:
58 return this.#dropRegion(message);
59 case WorkerMessage.replaceRegionChunks:
60 return this.#replaceRegionChunks(message);
61 case WorkerMessage.setReplicas:
62 return this.#setReplicas(message);
63 case WorkerMessage.setSimulatingChunks:
64 return this.#setSimulatingChunks(message);
65 case WorkerMessage.setGhosts:
66 return this.#setGhosts(message);
67 case WorkerMessage.spawn:
68 return this.#spawn(message);
69 case WorkerMessage.despawn:
70 return this.#despawn(message.entityId);
71 case WorkerMessage.despawnCharacter:
72 return this.#despawnCharacter(message.characterId);
73 case WorkerMessage.command:
74 return this.#command(message);
75 case WorkerMessage.stepMovement:
76 return this.#stepMovement(message.now);
77 case WorkerMessage.stepSpawners:
78 return { spawnRequests: collectSpawnRequests(this) };
79 case WorkerMessage.setGroundItems:
80 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
81 return { ok: true };
82 case WorkerMessage.inspectBag:
83 return this.#inspectBag(message.entityId);
84 case WorkerMessage.applyTransfer:
85 return this.#applyTransfer(message);
86 case WorkerMessage.commitTransfer:
87 return this.#commitTransfer(message.entityId);
88 case WorkerMessage.abortTransfer:
89 return this.#abortTransfer(message.entityId);
90 case WorkerMessage.snapshotChunk:
91 return this.#chunkSnapshot(message.chunkX, message.chunkY);
92 case WorkerMessage.listLoaders:
93 return this.#listLoaders();
94 case WorkerMessage.listPublicEntities:
95 return this.#listPublicEntities();
96 case WorkerMessage.entitiesInRegion:
97 return this.#entitiesInRegion(message.regionX, message.regionY);
98 case WorkerMessage.inspect:
99 return publicEntityView(this.ecs, message.entityId);
100 default:
101 throw new Error(`Unknown worker message ${message.type}`);
102 }
103 }
104
105 ownsRegion (regionX, regionY)
106 {
107 return this.ownedRegions.has(regionKey(regionX, regionY));
108 }
109
110 requireOwnedEntity (sessionId, characterId)
111 {
112 return this.#requireOwnedEntity(sessionId, characterId);
113 }
114
115 chunkData (chunkX, chunkY)
116 {
117 return this.#chunkData(chunkX, chunkY);
118 }
119
120 occupied (tileX, tileY)
121 {
122 return this.#occupied(tileX, tileY);
123 }
124
125 #configure (message)
126 {
127 if (message.settings)
128 { this.settings = { ...this.settings, ...message.settings }; }
129 if (message.activeRevisionId != null)
130 { this.activeRevisionId = message.activeRevisionId; }
131 return { ok: true };
132 }
133
134 #assignRegion (message)
135 {
136 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
137 for (const chunk of message.chunks ?? [])
138 {
139 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
140 data: cloneChunkData(chunk.data),
141 simulating: false,
142 replica: false
143 });
144 }
145 return { ok: true };
146 }
147
148 #replaceRegionChunks (message)
149 {
150 for (const chunk of message.chunks ?? [])
151 {
152 const key = chunkKey(chunk.chunkX, chunk.chunkY);
153 const existing = this.chunks.get(key);
154 this.chunks.set(key, {
155 data: cloneChunkData(chunk.data),
156 simulating: existing?.simulating ?? false,
157 replica: existing?.replica ?? false
158 });
159 }
160 return { ok: true };
161 }
162
163 #dropRegion (message)
164 {
165 const dropped = [];
166 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
167 {
168 dropped.push(record);
169 this.#destroyEntity(record.entityId);
170 }
171 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
172 for (const item of groundItems)
173 { removeGroundItem(this, item.groundItemId); }
174 for (const [key, chunk] of [...this.chunks.entries()])
175 {
176 const { chunkX, chunkY } = parseChunkKey(key);
177 if (chunk.replica)
178 { continue; }
179 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
180 { this.chunks.delete(key); }
181 }
182 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
183 return { dropped, groundItems };
184 }
185
186 #setReplicas (message)
187 {
188 const keep = new Set();
189 for (const chunk of message.chunks ?? [])
190 {
191 const key = chunkKey(chunk.chunkX, chunk.chunkY);
192 keep.add(key);
193 const existing = this.chunks.get(key);
194 if (existing && !existing.replica)
195 { continue; }
196 this.chunks.set(key, {
197 data: cloneChunkData(chunk.data),
198 simulating: false,
199 replica: true
200 });
201 }
202 for (const [key, chunk] of [...this.chunks.entries()])
203 {
204 if (chunk.replica && !keep.has(key))
205 { this.chunks.delete(key); }
206 }
207 return { ok: true };
208 }
209
210 #setSimulatingChunks (message)
211 {
212 const simulating = new Set(message.chunkKeys ?? []);
213 for (const [key, chunk] of this.chunks)
214 {
215 if (chunk.replica)
216 {
217 chunk.simulating = false;
218 continue;
219 }
220 chunk.simulating = simulating.has(key);
221 }
222 return { ok: true };
223 }
224
225 #setGhosts (message)
226 {
227 this.ghosts.clear();
228 this.ghostOccupancy.clear();
229 for (const ghost of message.ghosts ?? [])
230 {
231 this.ghosts.set(ghost.entityId, ghost);
232 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
233 }
234 return { ok: true };
235 }
236
237 #spawn (message)
238 {
239 const entityId = deserializeEntity(this.ecs, message);
240 const handle = this.ecs.handleOf(entityId);
241 const position = this.ecs.get(handle, Component.position);
242 if (!position)
243 {
244 this.ecs.destroy(handle);
245 throw new Error("Spawned entity is missing position.");
246 }
247 const occupant = this.#occupied(position.tileX, position.tileY);
248 if (occupant && occupant !== entityId)
249 {
250 this.ecs.destroy(handle);
251 const error = new Error("That tile is occupied.");
252 error.userFacing = true;
253 throw error;
254 }
255 this.#occupy(entityId, position.tileX, position.tileY);
256 const character = this.ecs.get(handle, Component.character);
257 if (character?.characterId)
258 { this.characterEntities.set(character.characterId, entityId); }
259 return publicEntityView(this.ecs, entityId);
260 }
261
262 #despawn (entityId)
263 {
264 return this.#destroyEntity(entityId);
265 }
266
267 #despawnCharacter (characterId)
268 {
269 const entityId = this.characterEntities.get(characterId);
270 if (!entityId)
271 { return null; }
272 return this.#destroyEntity(entityId);
273 }
274
275 #destroyEntity (entityId)
276 {
277 const handle = this.ecs.handleOf(entityId);
278 if (handle == null)
279 { return null; }
280 const view = publicEntityView(this.ecs, entityId);
281 const position = this.ecs.get(handle, Component.position);
282 const character = this.ecs.get(handle, Component.character);
283 if (position)
284 { this.#vacate(entityId, position.tileX, position.tileY); }
285 if (character?.characterId)
286 { this.characterEntities.delete(character.characterId); }
287 this.frozen.delete(entityId);
288 this.ecs.destroy(handle);
289 return view;
290 }
291
292 #command (message)
293 {
294 const { sessionId, command } = message;
295 switch (command.type)
296 {
297 case "move-to":
298 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
299 return { events: [] };
300 case "set-gait":
301 this.#setGait(sessionId, command.characterId, command.gait);
302 return { events: [] };
303 default:
304 {
305 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
306 return result ?? { events: [] };
307 }
308 }
309 }
310
311 #inspectBag (entityId)
312 {
313 const handle = this.ecs.handleOf(entityId);
314 if (handle == null)
315 { return null; }
316 return bagView(this.ecs, handle);
317 }
318
319 #moveTo (sessionId, characterId, tileX, tileY)
320 {
321 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
322 if (this.frozen.has(entityId))
323 { return; }
324 const position = this.ecs.get(handle, Component.position);
325 const movement = this.ecs.get(handle, Component.movement);
326 let path = this.ecs.get(handle, Component.path);
327 if (!path)
328 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
329 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
330 path.tiles = findPath(
331 position.tileX,
332 position.tileY,
333 tileX,
334 tileY,
335 (x, y) => this.#walkableFor(entityId, x, y),
336 bounds.minX,
337 bounds.minY,
338 bounds.maxX,
339 bounds.maxY
340 );
341 movement.walkCarry = 0;
342 }
343
344 #setGait (sessionId, characterId, gait)
345 {
346 if (gait !== GAIT.walk && gait !== GAIT.run)
347 {
348 const error = new Error("Gait must be walk or run.");
349 error.userFacing = true;
350 throw error;
351 }
352 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
353 this.ecs.get(handle, Component.movement).gait = gait;
354 }
355
356 #requireOwnedEntity (sessionId, characterId)
357 {
358 const entityId = this.characterEntities.get(characterId);
359 if (!entityId)
360 {
361 const error = new Error("Character is not in the world.");
362 error.userFacing = true;
363 throw error;
364 }
365 const handle = this.ecs.handleOf(entityId);
366 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
367 if (!identity || identity.sessionId !== sessionId)
368 {
369 const error = new Error("Character is not in the world.");
370 error.userFacing = true;
371 throw error;
372 }
373 return { handle, entityId };
374 }
375
376 #stepMovement (now = Date.now())
377 {
378 const events = expireGroundItems(this, now);
379 const transferRequests = [];
380 for (const entity of this.ecs.query(Component.position, Component.movement))
381 {
382 const { handle, entityId, position, movement } = entity;
383 const path = this.ecs.get(handle, Component.path);
384 const tiles = path?.tiles;
385 if (this.frozen.has(entityId) || !tiles?.length)
386 { continue; }
387 if (!this.#chunkIsSimulating(position.tileX, position.tileY))
388 { continue; }
389
390 const isWalk = movement.gait !== GAIT.run;
391 if (isWalk)
392 {
393 movement.walkCarry = (movement.walkCarry + 1) % 2;
394 if (movement.walkCarry !== 0)
395 { continue; }
396 }
397
398 const next = tiles[0];
399 const destRegionX = tileToRegion(next.x);
400 const destRegionY = tileToRegion(next.y);
401 if (!this.ownsRegion(destRegionX, destRegionY))
402 {
403 this.frozen.add(entityId);
404 transferRequests.push({
405 entityId,
406 fromTileX: position.tileX,
407 fromTileY: position.tileY,
408 destTileX: next.x,
409 destTileY: next.y,
410 toRegionX: destRegionX,
411 toRegionY: destRegionY,
412 payload: serializeEntity(this.ecs, entityId)
413 });
414 continue;
415 }
416
417 if (!this.#walkableFor(entityId, next.x, next.y))
418 { continue; }
419
420 const fromTileX = position.tileX;
421 const fromTileY = position.tileY;
422 this.#vacate(entityId, fromTileX, fromTileY);
423 position.tileX = next.x;
424 position.tileY = next.y;
425 tiles.shift();
426 this.#occupy(entityId, position.tileX, position.tileY);
427 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
428 }
429 return { events, transferRequests };
430 }
431
432 #applyTransfer (message)
433 {
434 const payload = message.payload;
435 const entityId = payload.entityId;
436 if (this.ecs.hasEntity(entityId))
437 { return { accepted: false, reason: "already-present" }; }
438
439 const position = payload.components?.position;
440 const destTileX = message.destTileX ?? position?.tileX;
441 const destTileY = message.destTileY ?? position?.tileY;
442 if (destTileX == null || destTileY == null)
443 { return { accepted: false, reason: "missing-destination" }; }
444 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
445 { return { accepted: false, reason: "not-owner" }; }
446 if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
447 { return { accepted: false, reason: "blocked" }; }
448
449 deserializeEntity(this.ecs, payload);
450 const handle = this.ecs.handleOf(entityId);
451 const livePosition = this.ecs.get(handle, Component.position);
452 const path = this.ecs.get(handle, Component.path);
453 livePosition.tileX = destTileX;
454 livePosition.tileY = destTileY;
455 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
456 { path.tiles.shift(); }
457 this.#occupy(entityId, destTileX, destTileY);
458 const character = this.ecs.get(handle, Component.character);
459 if (character?.characterId)
460 { this.characterEntities.set(character.characterId, entityId); }
461 this.frozen.delete(entityId);
462 return {
463 accepted: true,
464 entity: publicEntityView(this.ecs, entityId)
465 };
466 }
467
468 #commitTransfer (entityId)
469 {
470 if (!this.ecs.hasEntity(entityId))
471 { return null; }
472 return this.#destroyEntity(entityId);
473 }
474
475 #abortTransfer (entityId)
476 {
477 this.frozen.delete(entityId);
478 return publicEntityView(this.ecs, entityId);
479 }
480
481 #listLoaders ()
482 {
483 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
484 entityId: entity.entityId,
485 tileX: entity.position.tileX,
486 tileY: entity.position.tileY,
487 chunkLoader: { ...entity.chunkLoader }
488 }));
489 }
490
491 #listPublicEntities ()
492 {
493 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
494 }
495
496 #entitiesInRegion (regionX, regionY)
497 {
498 const records = [];
499 for (const entity of this.ecs.query(Component.position))
500 {
501 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
502 { continue; }
503 records.push({
504 ...publicEntityView(this.ecs, entity.entityId),
505 persistent: this.ecs.has(entity.handle, Component.persistent),
506 payload: serializeEntity(this.ecs, entity.entityId)
507 });
508 }
509 return records;
510 }
511
512 #chunkSnapshot (chunkX, chunkY)
513 {
514 const data = this.#chunkData(chunkX, chunkY);
515 const entities = [];
516 for (const entity of this.ecs.query(Component.position, Component.appearance))
517 {
518 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
519 { continue; }
520 entities.push(publicEntityView(this.ecs, entity.entityId));
521 }
522 return {
523 chunkX,
524 chunkY,
525 open: data.open,
526 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
527 grounds: data.grounds,
528 blocks: data.blocks,
529 light: data.light,
530 entities,
531 groundItems: groundItemsInChunk(this, chunkX, chunkY)
532 };
533 }
534
535 #moveEvent (entityId, fromTileX, fromTileY)
536 {
537 const view = publicEntityView(this.ecs, entityId);
538 return {
539 type: "entity-move",
540 entityId,
541 fromTileX,
542 fromTileY,
543 tileX: view.tileX,
544 tileY: view.tileY,
545 gait: view.gait
546 };
547 }
548
549 #chunkIsSimulating (tileX, tileY)
550 {
551 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
552 return !!chunk && !chunk.replica && chunk.simulating;
553 }
554
555 #chunkData (chunkX, chunkY)
556 {
557 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
558 if (loaded)
559 { return loaded.data; }
560 return createEmptyChunkData(this.settings.defaultGroundTypeId);
561 }
562
563 isEnterable (tileX, tileY)
564 {
565 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
566 if (!data.open)
567 { return false; }
568 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
569 }
570
571 #walkableFor (entityId, tileX, tileY)
572 {
573 if (!this.isEnterable(tileX, tileY))
574 { return false; }
575 const occupant = this.#occupied(tileX, tileY);
576 return !occupant || occupant === entityId;
577 }
578
579 #occupy (entityId, tileX, tileY)
580 {
581 this.occupancy.set(tileKey(tileX, tileY), entityId);
582 }
583
584 #vacate (entityId, tileX, tileY)
585 {
586 const key = tileKey(tileX, tileY);
587 if (this.occupancy.get(key) === entityId)
588 { this.occupancy.delete(key); }
589 }
590
591 #occupied (tileX, tileY)
592 {
593 return this.occupancy.get(tileKey(tileX, tileY))
594 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
595 ?? null;
596 }
597 }
598
599 export function replicaNeededForOwnedChunks (ownedChunkKeys)
600 {
601 const needed = new Set();
602 for (const key of ownedChunkKeys)
603 {
604 const { chunkX, chunkY } = parseChunkKey(key);
605 for (let dy = -1; dy <= 1; dy++)
606 {
607 for (let dx = -1; dx <= 1; dx++)
608 {
609 if (dx === 0 && dy === 0)
610 { continue; }
611 needed.add(chunkKey(chunkX + dx, chunkY + dy));
612 }
613 }
614 }
615 return needed;
616 }
@@ -0,0 +1,616 @@
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import {
3 chunkKey,
4 chunkToRegion,
5 parseChunkKey,
6 regionKey,
7 tileKey,
8 tileToChunk,
9 tileToLocal,
10 tileToRegion
11} from "../world/coordinates.js";
12import { cloneChunkData, createEmptyChunkData, isChunkTilePassable } from "../world/chunkData.js";
13import { closedNeighborEdges } from "../world/chunkFlags.js";
14import { EcsWorld } from "../ecs/world.js";
15import { Component } from "../ecs/components.js";
16import { deserializeEntity, publicEntityView, serializeEntity } from "../ecs/serialize.js";
17import { chunkBoundsAround, findPath } from "../navigation/astar.js";
18import { WorkerMessage } from "./protocol.js";
19import { collectSpawnRequests } from "./spawners.js";
20import {
21 bagView,
22 expireGroundItems,
23 groundItemsInChunk,
24 groundItemsInRegion,
25 handleItemCommand,
26 removeGroundItem,
27 setGroundItemsForRegion
28} from "../items/bags.js";
29
30export class WorkerWorld
31{
32 constructor (workerId)
33 {
34 this.workerId = workerId;
35 this.ecs = new EcsWorld();
36 this.chunks = new Map();
37 this.ownedRegions = new Set();
38 this.occupancy = new Map();
39 this.ghosts = new Map();
40 this.ghostOccupancy = new Map();
41 this.characterEntities = new Map();
42 this.frozen = new Set();
43 this.groundItems = new Map();
44 this.groundByTile = new Map();
45 this.settings = { ...DEFAULT_WORLD_SETTINGS };
46 this.activeRevisionId = 1;
47 }
48
49 handle (message)
50 {
51 switch (message.type)
52 {
53 case WorkerMessage.configure:
54 return this.#configure(message);
55 case WorkerMessage.assignRegion:
56 return this.#assignRegion(message);
57 case WorkerMessage.dropRegion:
58 return this.#dropRegion(message);
59 case WorkerMessage.replaceRegionChunks:
60 return this.#replaceRegionChunks(message);
61 case WorkerMessage.setReplicas:
62 return this.#setReplicas(message);
63 case WorkerMessage.setSimulatingChunks:
64 return this.#setSimulatingChunks(message);
65 case WorkerMessage.setGhosts:
66 return this.#setGhosts(message);
67 case WorkerMessage.spawn:
68 return this.#spawn(message);
69 case WorkerMessage.despawn:
70 return this.#despawn(message.entityId);
71 case WorkerMessage.despawnCharacter:
72 return this.#despawnCharacter(message.characterId);
73 case WorkerMessage.command:
74 return this.#command(message);
75 case WorkerMessage.stepMovement:
76 return this.#stepMovement(message.now);
77 case WorkerMessage.stepSpawners:
78 return { spawnRequests: collectSpawnRequests(this) };
79 case WorkerMessage.setGroundItems:
80 setGroundItemsForRegion(this, message.regionX, message.regionY, message.items, tileToRegion);
81 return { ok: true };
82 case WorkerMessage.inspectBag:
83 return this.#inspectBag(message.entityId);
84 case WorkerMessage.applyTransfer:
85 return this.#applyTransfer(message);
86 case WorkerMessage.commitTransfer:
87 return this.#commitTransfer(message.entityId);
88 case WorkerMessage.abortTransfer:
89 return this.#abortTransfer(message.entityId);
90 case WorkerMessage.snapshotChunk:
91 return this.#chunkSnapshot(message.chunkX, message.chunkY);
92 case WorkerMessage.listLoaders:
93 return this.#listLoaders();
94 case WorkerMessage.listPublicEntities:
95 return this.#listPublicEntities();
96 case WorkerMessage.entitiesInRegion:
97 return this.#entitiesInRegion(message.regionX, message.regionY);
98 case WorkerMessage.inspect:
99 return publicEntityView(this.ecs, message.entityId);
100 default:
101 throw new Error(`Unknown worker message ${message.type}`);
102 }
103 }
104
105 ownsRegion (regionX, regionY)
106 {
107 return this.ownedRegions.has(regionKey(regionX, regionY));
108 }
109
110 requireOwnedEntity (sessionId, characterId)
111 {
112 return this.#requireOwnedEntity(sessionId, characterId);
113 }
114
115 chunkData (chunkX, chunkY)
116 {
117 return this.#chunkData(chunkX, chunkY);
118 }
119
120 occupied (tileX, tileY)
121 {
122 return this.#occupied(tileX, tileY);
123 }
124
125 #configure (message)
126 {
127 if (message.settings)
128 { this.settings = { ...this.settings, ...message.settings }; }
129 if (message.activeRevisionId != null)
130 { this.activeRevisionId = message.activeRevisionId; }
131 return { ok: true };
132 }
133
134 #assignRegion (message)
135 {
136 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
137 for (const chunk of message.chunks ?? [])
138 {
139 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
140 data: cloneChunkData(chunk.data),
141 simulating: false,
142 replica: false
143 });
144 }
145 return { ok: true };
146 }
147
148 #replaceRegionChunks (message)
149 {
150 for (const chunk of message.chunks ?? [])
151 {
152 const key = chunkKey(chunk.chunkX, chunk.chunkY);
153 const existing = this.chunks.get(key);
154 this.chunks.set(key, {
155 data: cloneChunkData(chunk.data),
156 simulating: existing?.simulating ?? false,
157 replica: existing?.replica ?? false
158 });
159 }
160 return { ok: true };
161 }
162
163 #dropRegion (message)
164 {
165 const dropped = [];
166 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
167 {
168 dropped.push(record);
169 this.#destroyEntity(record.entityId);
170 }
171 const groundItems = groundItemsInRegion(this, message.regionX, message.regionY, tileToRegion);
172 for (const item of groundItems)
173 { removeGroundItem(this, item.groundItemId); }
174 for (const [key, chunk] of [...this.chunks.entries()])
175 {
176 const { chunkX, chunkY } = parseChunkKey(key);
177 if (chunk.replica)
178 { continue; }
179 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
180 { this.chunks.delete(key); }
181 }
182 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
183 return { dropped, groundItems };
184 }
185
186 #setReplicas (message)
187 {
188 const keep = new Set();
189 for (const chunk of message.chunks ?? [])
190 {
191 const key = chunkKey(chunk.chunkX, chunk.chunkY);
192 keep.add(key);
193 const existing = this.chunks.get(key);
194 if (existing && !existing.replica)
195 { continue; }
196 this.chunks.set(key, {
197 data: cloneChunkData(chunk.data),
198 simulating: false,
199 replica: true
200 });
201 }
202 for (const [key, chunk] of [...this.chunks.entries()])
203 {
204 if (chunk.replica && !keep.has(key))
205 { this.chunks.delete(key); }
206 }
207 return { ok: true };
208 }
209
210 #setSimulatingChunks (message)
211 {
212 const simulating = new Set(message.chunkKeys ?? []);
213 for (const [key, chunk] of this.chunks)
214 {
215 if (chunk.replica)
216 {
217 chunk.simulating = false;
218 continue;
219 }
220 chunk.simulating = simulating.has(key);
221 }
222 return { ok: true };
223 }
224
225 #setGhosts (message)
226 {
227 this.ghosts.clear();
228 this.ghostOccupancy.clear();
229 for (const ghost of message.ghosts ?? [])
230 {
231 this.ghosts.set(ghost.entityId, ghost);
232 this.ghostOccupancy.set(tileKey(ghost.tileX, ghost.tileY), ghost.entityId);
233 }
234 return { ok: true };
235 }
236
237 #spawn (message)
238 {
239 const entityId = deserializeEntity(this.ecs, message);
240 const handle = this.ecs.handleOf(entityId);
241 const position = this.ecs.get(handle, Component.position);
242 if (!position)
243 {
244 this.ecs.destroy(handle);
245 throw new Error("Spawned entity is missing position.");
246 }
247 const occupant = this.#occupied(position.tileX, position.tileY);
248 if (occupant && occupant !== entityId)
249 {
250 this.ecs.destroy(handle);
251 const error = new Error("That tile is occupied.");
252 error.userFacing = true;
253 throw error;
254 }
255 this.#occupy(entityId, position.tileX, position.tileY);
256 const character = this.ecs.get(handle, Component.character);
257 if (character?.characterId)
258 { this.characterEntities.set(character.characterId, entityId); }
259 return publicEntityView(this.ecs, entityId);
260 }
261
262 #despawn (entityId)
263 {
264 return this.#destroyEntity(entityId);
265 }
266
267 #despawnCharacter (characterId)
268 {
269 const entityId = this.characterEntities.get(characterId);
270 if (!entityId)
271 { return null; }
272 return this.#destroyEntity(entityId);
273 }
274
275 #destroyEntity (entityId)
276 {
277 const handle = this.ecs.handleOf(entityId);
278 if (handle == null)
279 { return null; }
280 const view = publicEntityView(this.ecs, entityId);
281 const position = this.ecs.get(handle, Component.position);
282 const character = this.ecs.get(handle, Component.character);
283 if (position)
284 { this.#vacate(entityId, position.tileX, position.tileY); }
285 if (character?.characterId)
286 { this.characterEntities.delete(character.characterId); }
287 this.frozen.delete(entityId);
288 this.ecs.destroy(handle);
289 return view;
290 }
291
292 #command (message)
293 {
294 const { sessionId, command } = message;
295 switch (command.type)
296 {
297 case "move-to":
298 this.#moveTo(sessionId, command.characterId, command.tileX, command.tileY);
299 return { events: [] };
300 case "set-gait":
301 this.#setGait(sessionId, command.characterId, command.gait);
302 return { events: [] };
303 default:
304 {
305 const result = handleItemCommand(this, sessionId, command, message.now ?? Date.now());
306 return result ?? { events: [] };
307 }
308 }
309 }
310
311 #inspectBag (entityId)
312 {
313 const handle = this.ecs.handleOf(entityId);
314 if (handle == null)
315 { return null; }
316 return bagView(this.ecs, handle);
317 }
318
319 #moveTo (sessionId, characterId, tileX, tileY)
320 {
321 const { handle, entityId } = this.#requireOwnedEntity(sessionId, characterId);
322 if (this.frozen.has(entityId))
323 { return; }
324 const position = this.ecs.get(handle, Component.position);
325 const movement = this.ecs.get(handle, Component.movement);
326 let path = this.ecs.get(handle, Component.path);
327 if (!path)
328 { path = this.ecs.add(handle, Component.path, { tiles: [] }); }
329 const bounds = chunkBoundsAround(position.tileX, position.tileY, VISIBLE_CHUNK_RADIUS);
330 path.tiles = findPath(
331 position.tileX,
332 position.tileY,
333 tileX,
334 tileY,
335 (x, y) => this.#walkableFor(entityId, x, y),
336 bounds.minX,
337 bounds.minY,
338 bounds.maxX,
339 bounds.maxY
340 );
341 movement.walkCarry = 0;
342 }
343
344 #setGait (sessionId, characterId, gait)
345 {
346 if (gait !== GAIT.walk && gait !== GAIT.run)
347 {
348 const error = new Error("Gait must be walk or run.");
349 error.userFacing = true;
350 throw error;
351 }
352 const { handle } = this.#requireOwnedEntity(sessionId, characterId);
353 this.ecs.get(handle, Component.movement).gait = gait;
354 }
355
356 #requireOwnedEntity (sessionId, characterId)
357 {
358 const entityId = this.characterEntities.get(characterId);
359 if (!entityId)
360 {
361 const error = new Error("Character is not in the world.");
362 error.userFacing = true;
363 throw error;
364 }
365 const handle = this.ecs.handleOf(entityId);
366 const identity = handle != null ? this.ecs.get(handle, Component.networkIdentity) : null;
367 if (!identity || identity.sessionId !== sessionId)
368 {
369 const error = new Error("Character is not in the world.");
370 error.userFacing = true;
371 throw error;
372 }
373 return { handle, entityId };
374 }
375
376 #stepMovement (now = Date.now())
377 {
378 const events = expireGroundItems(this, now);
379 const transferRequests = [];
380 for (const entity of this.ecs.query(Component.position, Component.movement))
381 {
382 const { handle, entityId, position, movement } = entity;
383 const path = this.ecs.get(handle, Component.path);
384 const tiles = path?.tiles;
385 if (this.frozen.has(entityId) || !tiles?.length)
386 { continue; }
387 if (!this.#chunkIsSimulating(position.tileX, position.tileY))
388 { continue; }
389
390 const isWalk = movement.gait !== GAIT.run;
391 if (isWalk)
392 {
393 movement.walkCarry = (movement.walkCarry + 1) % 2;
394 if (movement.walkCarry !== 0)
395 { continue; }
396 }
397
398 const next = tiles[0];
399 const destRegionX = tileToRegion(next.x);
400 const destRegionY = tileToRegion(next.y);
401 if (!this.ownsRegion(destRegionX, destRegionY))
402 {
403 this.frozen.add(entityId);
404 transferRequests.push({
405 entityId,
406 fromTileX: position.tileX,
407 fromTileY: position.tileY,
408 destTileX: next.x,
409 destTileY: next.y,
410 toRegionX: destRegionX,
411 toRegionY: destRegionY,
412 payload: serializeEntity(this.ecs, entityId)
413 });
414 continue;
415 }
416
417 if (!this.#walkableFor(entityId, next.x, next.y))
418 { continue; }
419
420 const fromTileX = position.tileX;
421 const fromTileY = position.tileY;
422 this.#vacate(entityId, fromTileX, fromTileY);
423 position.tileX = next.x;
424 position.tileY = next.y;
425 tiles.shift();
426 this.#occupy(entityId, position.tileX, position.tileY);
427 events.push(this.#moveEvent(entityId, fromTileX, fromTileY));
428 }
429 return { events, transferRequests };
430 }
431
432 #applyTransfer (message)
433 {
434 const payload = message.payload;
435 const entityId = payload.entityId;
436 if (this.ecs.hasEntity(entityId))
437 { return { accepted: false, reason: "already-present" }; }
438
439 const position = payload.components?.position;
440 const destTileX = message.destTileX ?? position?.tileX;
441 const destTileY = message.destTileY ?? position?.tileY;
442 if (destTileX == null || destTileY == null)
443 { return { accepted: false, reason: "missing-destination" }; }
444 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
445 { return { accepted: false, reason: "not-owner" }; }
446 if (!this.isEnterable(destTileX, destTileY) || this.#occupied(destTileX, destTileY))
447 { return { accepted: false, reason: "blocked" }; }
448
449 deserializeEntity(this.ecs, payload);
450 const handle = this.ecs.handleOf(entityId);
451 const livePosition = this.ecs.get(handle, Component.position);
452 const path = this.ecs.get(handle, Component.path);
453 livePosition.tileX = destTileX;
454 livePosition.tileY = destTileY;
455 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
456 { path.tiles.shift(); }
457 this.#occupy(entityId, destTileX, destTileY);
458 const character = this.ecs.get(handle, Component.character);
459 if (character?.characterId)
460 { this.characterEntities.set(character.characterId, entityId); }
461 this.frozen.delete(entityId);
462 return {
463 accepted: true,
464 entity: publicEntityView(this.ecs, entityId)
465 };
466 }
467
468 #commitTransfer (entityId)
469 {
470 if (!this.ecs.hasEntity(entityId))
471 { return null; }
472 return this.#destroyEntity(entityId);
473 }
474
475 #abortTransfer (entityId)
476 {
477 this.frozen.delete(entityId);
478 return publicEntityView(this.ecs, entityId);
479 }
480
481 #listLoaders ()
482 {
483 return this.ecs.query(Component.position, Component.chunkLoader).map((entity) => ({
484 entityId: entity.entityId,
485 tileX: entity.position.tileX,
486 tileY: entity.position.tileY,
487 chunkLoader: { ...entity.chunkLoader }
488 }));
489 }
490
491 #listPublicEntities ()
492 {
493 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
494 }
495
496 #entitiesInRegion (regionX, regionY)
497 {
498 const records = [];
499 for (const entity of this.ecs.query(Component.position))
500 {
501 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
502 { continue; }
503 records.push({
504 ...publicEntityView(this.ecs, entity.entityId),
505 persistent: this.ecs.has(entity.handle, Component.persistent),
506 payload: serializeEntity(this.ecs, entity.entityId)
507 });
508 }
509 return records;
510 }
511
512 #chunkSnapshot (chunkX, chunkY)
513 {
514 const data = this.#chunkData(chunkX, chunkY);
515 const entities = [];
516 for (const entity of this.ecs.query(Component.position, Component.appearance))
517 {
518 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
519 { continue; }
520 entities.push(publicEntityView(this.ecs, entity.entityId));
521 }
522 return {
523 chunkX,
524 chunkY,
525 open: data.open,
526 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
527 grounds: data.grounds,
528 blocks: data.blocks,
529 light: data.light,
530 entities,
531 groundItems: groundItemsInChunk(this, chunkX, chunkY)
532 };
533 }
534
535 #moveEvent (entityId, fromTileX, fromTileY)
536 {
537 const view = publicEntityView(this.ecs, entityId);
538 return {
539 type: "entity-move",
540 entityId,
541 fromTileX,
542 fromTileY,
543 tileX: view.tileX,
544 tileY: view.tileY,
545 gait: view.gait
546 };
547 }
548
549 #chunkIsSimulating (tileX, tileY)
550 {
551 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
552 return !!chunk && !chunk.replica && chunk.simulating;
553 }
554
555 #chunkData (chunkX, chunkY)
556 {
557 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
558 if (loaded)
559 { return loaded.data; }
560 return createEmptyChunkData(this.settings.defaultGroundTypeId);
561 }
562
563 isEnterable (tileX, tileY)
564 {
565 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
566 if (!data.open)
567 { return false; }
568 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
569 }
570
571 #walkableFor (entityId, tileX, tileY)
572 {
573 if (!this.isEnterable(tileX, tileY))
574 { return false; }
575 const occupant = this.#occupied(tileX, tileY);
576 return !occupant || occupant === entityId;
577 }
578
579 #occupy (entityId, tileX, tileY)
580 {
581 this.occupancy.set(tileKey(tileX, tileY), entityId);
582 }
583
584 #vacate (entityId, tileX, tileY)
585 {
586 const key = tileKey(tileX, tileY);
587 if (this.occupancy.get(key) === entityId)
588 { this.occupancy.delete(key); }
589 }
590
591 #occupied (tileX, tileY)
592 {
593 return this.occupancy.get(tileKey(tileX, tileY))
594 ?? this.ghostOccupancy.get(tileKey(tileX, tileY))
595 ?? null;
596 }
597}
598
599export function replicaNeededForOwnedChunks (ownedChunkKeys)
600{
601 const needed = new Set();
602 for (const key of ownedChunkKeys)
603 {
604 const { chunkX, chunkY } = parseChunkKey(key);
605 for (let dy = -1; dy <= 1; dy++)
606 {
607 for (let dx = -1; dx <= 1; dx++)
608 {
609 if (dx === 0 && dy === 0)
610 { continue; }
611 needed.add(chunkKey(chunkX + dx, chunkY + dy));
612 }
613 }
614 }
615 return needed;
616}
server/src/world/chunkData.js +1 −1
@@ -21,7 +21,7 @@ export function cloneChunkData (data)
21 21 return {
22 22 open: data.open,
23 23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 blocks: data.blocks.map((block) => normalizeBlock(block)),
24 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
25 25 light: data.light.slice()
26 26 };
27 27 }
@@ -21,7 +21,7 @@ export function cloneChunkData (data)
21 return {
21 return {
22 open: data.open,
22 open: data.open,
23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 blocks: data.blocks.map((block) => normalizeBlock(block)),
24 blocks: data.blocks.map((block) => structuredClone(normalizeBlock(block))),
25 light: data.light.slice()
25 light: data.light.slice()
26 };
26 };
27}
27}
server/src/world/coordinates.js +57 −0
@@ -43,6 +43,63 @@ export function indexToLocal (index)
43 43 };
44 44 }
45 45
46 export function regionKey (regionX, regionY)
47 {
48 return `${regionX},${regionY}`;
49 }
50
51 export function parseRegionKey (key)
52 {
53 const [regionX, regionY] = key.split(",").map(Number);
54 return { regionX, regionY };
55 }
56
57 export function tileToRegion (tile)
58 {
59 return chunkToRegion(tileToChunk(tile));
60 }
61
62 export function regionOriginChunk (region)
63 {
64 return region * REGION_CHUNKS;
65 }
66
67 export function chunksInRegion (regionX, regionY)
68 {
69 const originX = regionOriginChunk(regionX);
70 const originY = regionOriginChunk(regionY);
71 const coords = [];
72 for (let localY = 0; localY < REGION_CHUNKS; localY++)
73 {
74 for (let localX = 0; localX < REGION_CHUNKS; localX++)
75 { coords.push({ chunkX: originX + localX, chunkY: originY + localY }); }
76 }
77 return coords;
78 }
79
80 export function regionTileBounds (regionX, regionY)
81 {
82 const minChunkX = regionOriginChunk(regionX);
83 const minChunkY = regionOriginChunk(regionY);
84 return {
85 minX: minChunkX * CHUNK_SIZE,
86 minY: minChunkY * CHUNK_SIZE,
87 maxX: (minChunkX + REGION_CHUNKS) * CHUNK_SIZE - 1,
88 maxY: (minChunkY + REGION_CHUNKS) * CHUNK_SIZE - 1
89 };
90 }
91
92 export function visibleRegionCoords (regionX, regionY, radius = 1)
93 {
94 const coords = [];
95 for (let dy = -radius; dy <= radius; dy++)
96 {
97 for (let dx = -radius; dx <= radius; dx++)
98 { coords.push({ regionX: regionX + dx, regionY: regionY + dy }); }
99 }
100 return coords;
101 }
102
46 103 export function chunkKey (chunkX, chunkY)
47 104 {
48 105 return `${chunkX},${chunkY}`;
@@ -43,6 +43,63 @@ export function indexToLocal (index)
43 };
43 };
44}
44}
45
45
46export function regionKey (regionX, regionY)
47{
48 return `${regionX},${regionY}`;
49}
50
51export function parseRegionKey (key)
52{
53 const [regionX, regionY] = key.split(",").map(Number);
54 return { regionX, regionY };
55}
56
57export function tileToRegion (tile)
58{
59 return chunkToRegion(tileToChunk(tile));
60}
61
62export function regionOriginChunk (region)
63{
64 return region * REGION_CHUNKS;
65}
66
67export function chunksInRegion (regionX, regionY)
68{
69 const originX = regionOriginChunk(regionX);
70 const originY = regionOriginChunk(regionY);
71 const coords = [];
72 for (let localY = 0; localY < REGION_CHUNKS; localY++)
73 {
74 for (let localX = 0; localX < REGION_CHUNKS; localX++)
75 { coords.push({ chunkX: originX + localX, chunkY: originY + localY }); }
76 }
77 return coords;
78}
79
80export function regionTileBounds (regionX, regionY)
81{
82 const minChunkX = regionOriginChunk(regionX);
83 const minChunkY = regionOriginChunk(regionY);
84 return {
85 minX: minChunkX * CHUNK_SIZE,
86 minY: minChunkY * CHUNK_SIZE,
87 maxX: (minChunkX + REGION_CHUNKS) * CHUNK_SIZE - 1,
88 maxY: (minChunkY + REGION_CHUNKS) * CHUNK_SIZE - 1
89 };
90}
91
92export function visibleRegionCoords (regionX, regionY, radius = 1)
93{
94 const coords = [];
95 for (let dy = -radius; dy <= radius; dy++)
96 {
97 for (let dx = -radius; dx <= radius; dx++)
98 { coords.push({ regionX: regionX + dx, regionY: regionY + dy }); }
99 }
100 return coords;
101}
102
46export function chunkKey (chunkX, chunkY)
103export function chunkKey (chunkX, chunkY)
47{
104{
48 return `${chunkX},${chunkY}`;
105 return `${chunkX},${chunkY}`;
server/tests/coordinates.test.js +64 −10
@@ -1,14 +1,41 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 import { CHUNK_SIZE, REGION_CHUNKS } from "../../shared/protocol/constants.js";
3 import { CHUNK_SIZE, REGION_CHUNKS, DEFAULT_CHUNK_LOADER } from "../../shared/protocol/constants.js";
4 4 import {
5 chunkKey,
6 chunkToRegion,
7 chunksInRegion,
5 8 floorDiv,
9 localToTile,
10 regionKey,
11 regionTileBounds,
6 12 tileToChunk,
7 chunkToRegion,
8 13 tileToLocal,
9 localToTile,
10 chunkKey
14 tileToRegion,
15 visibleRegionCoords
11 16 } from "../src/world/coordinates.js";
17 import { accumulateLoaderRefs, loaderCoverage } from "../src/simulation/chunkLoader.js";
18 import { EcsWorld } from "../src/ecs/world.js";
19 import { deserializeEntity, serializeEntity } from "../src/ecs/serialize.js";
20
21 test("chunk and region sizes match the design", () =>
22 {
23 assert.equal(CHUNK_SIZE, 16);
24 assert.equal(REGION_CHUNKS, 4);
25 assert.equal(tileToChunk(16), 1);
26 assert.equal(chunkToRegion(4), 1);
27 assert.equal(chunkKey(2, -3), "2,-3");
28 assert.equal(tileToRegion(64), 1);
29 assert.equal(tileToRegion(63), 0);
30 assert.equal(regionKey(-2, 3), "-2,3");
31 assert.deepEqual(chunksInRegion(1, 0).slice(0, 2), [
32 { chunkX: 4, chunkY: 0 },
33 { chunkX: 5, chunkY: 0 }
34 ]);
35 assert.equal(chunksInRegion(0, 0).length, 16);
36 assert.deepEqual(regionTileBounds(1, 0), { minX: 64, minY: 0, maxX: 127, maxY: 63 });
37 assert.equal(visibleRegionCoords(0, 0, 1).length, 9);
38 });
12 39
13 40 test("true floor division for negative coordinates", () =>
14 41 {
@@ -19,13 +46,40 @@ test("true floor division for negative coordinates", () =>
19 46 assert.equal(chunkToRegion(-1), -1);
20 47 assert.equal(chunkToRegion(-4), -1);
21 48 assert.equal(chunkToRegion(-5), -2);
49 assert.equal(tileToRegion(-1), -1);
22 50 });
23 51
24 test("chunk and region sizes match the design", () =>
52 test("a player ChunkLoader stimulates 3x3 chunks and keeps 3x3 regions resident", () =>
25 53 {
26 assert.equal(CHUNK_SIZE, 16);
27 assert.equal(REGION_CHUNKS, 4);
28 assert.equal(tileToChunk(16), 1);
29 assert.equal(chunkToRegion(4), 1);
30 assert.equal(chunkKey(2, -3), "2,-3");
54 const coverage = loaderCoverage(8, 8, DEFAULT_CHUNK_LOADER);
55 assert.equal(coverage.simulationChunks.length, 9);
56 assert.ok(coverage.simulationChunks.some((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0));
57 assert.ok(coverage.simulationChunks.some((chunk) => chunk.chunkX === 1 && chunk.chunkY === 1));
58 assert.equal(coverage.residentRegions.length, 9);
59 assert.ok(coverage.residentRegions.some((region) => region.regionX === 0 && region.regionY === 0));
60 assert.ok(coverage.residentRegions.some((region) => region.regionX === 1 && region.regionY === 0));
61 });
62
63 test("overlapping loaders share reference counts", () =>
64 {
65 const { chunkSim, regionRes } = accumulateLoaderRefs([
66 { tileX: 8, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER },
67 { tileX: 9, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER }
68 ]);
69 assert.equal(chunkSim.get("0,0"), 2);
70 assert.equal(regionRes.get("0,0"), 2);
71 });
72
73 test("global entity ids survive serialize and adopt on another world", () =>
74 {
75 const source = new EcsWorld();
76 const handle = source.adopt(42);
77 source.add(handle, "position", { tileX: 3, tileY: 4 });
78 const payload = serializeEntity(source, 42);
79 const dest = new EcsWorld();
80 const restored = deserializeEntity(dest, payload);
81 assert.equal(restored, 42);
82 assert.equal(dest.entityIdOf(dest.handleOf(42)), 42);
83 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4 });
84 assert.equal(dest.entityIdOf(dest.entity()), 43);
31 85 });
@@ -1,14 +1,41 @@
1import test from "node:test";
1import test from "node:test";
2import assert from "node:assert/strict";
2import assert from "node:assert/strict";
3import { CHUNK_SIZE, REGION_CHUNKS } from "../../shared/protocol/constants.js";
3import { CHUNK_SIZE, REGION_CHUNKS, DEFAULT_CHUNK_LOADER } from "../../shared/protocol/constants.js";
4import {
4import {
5 chunkKey,
6 chunkToRegion,
7 chunksInRegion,
5 floorDiv,
8 floorDiv,
9 localToTile,
10 regionKey,
11 regionTileBounds,
6 tileToChunk,
12 tileToChunk,
7 chunkToRegion,
8 tileToLocal,
13 tileToLocal,
9 localToTile,
14 tileToRegion,
10 chunkKey
15 visibleRegionCoords
11} from "../src/world/coordinates.js";
16} from "../src/world/coordinates.js";
17import { accumulateLoaderRefs, loaderCoverage } from "../src/simulation/chunkLoader.js";
18import { EcsWorld } from "../src/ecs/world.js";
19import { deserializeEntity, serializeEntity } from "../src/ecs/serialize.js";
20
21test("chunk and region sizes match the design", () =>
22{
23 assert.equal(CHUNK_SIZE, 16);
24 assert.equal(REGION_CHUNKS, 4);
25 assert.equal(tileToChunk(16), 1);
26 assert.equal(chunkToRegion(4), 1);
27 assert.equal(chunkKey(2, -3), "2,-3");
28 assert.equal(tileToRegion(64), 1);
29 assert.equal(tileToRegion(63), 0);
30 assert.equal(regionKey(-2, 3), "-2,3");
31 assert.deepEqual(chunksInRegion(1, 0).slice(0, 2), [
32 { chunkX: 4, chunkY: 0 },
33 { chunkX: 5, chunkY: 0 }
34 ]);
35 assert.equal(chunksInRegion(0, 0).length, 16);
36 assert.deepEqual(regionTileBounds(1, 0), { minX: 64, minY: 0, maxX: 127, maxY: 63 });
37 assert.equal(visibleRegionCoords(0, 0, 1).length, 9);
38});
12
39
13test("true floor division for negative coordinates", () =>
40test("true floor division for negative coordinates", () =>
14{
41{
@@ -19,13 +46,40 @@ test("true floor division for negative coordinates", () =>
19 assert.equal(chunkToRegion(-1), -1);
46 assert.equal(chunkToRegion(-1), -1);
20 assert.equal(chunkToRegion(-4), -1);
47 assert.equal(chunkToRegion(-4), -1);
21 assert.equal(chunkToRegion(-5), -2);
48 assert.equal(chunkToRegion(-5), -2);
49 assert.equal(tileToRegion(-1), -1);
22});
50});
23
51
24test("chunk and region sizes match the design", () =>
52test("a player ChunkLoader stimulates 3x3 chunks and keeps 3x3 regions resident", () =>
25{
53{
26 assert.equal(CHUNK_SIZE, 16);
54 const coverage = loaderCoverage(8, 8, DEFAULT_CHUNK_LOADER);
27 assert.equal(REGION_CHUNKS, 4);
55 assert.equal(coverage.simulationChunks.length, 9);
28 assert.equal(tileToChunk(16), 1);
56 assert.ok(coverage.simulationChunks.some((chunk) => chunk.chunkX === 0 && chunk.chunkY === 0));
29 assert.equal(chunkToRegion(4), 1);
57 assert.ok(coverage.simulationChunks.some((chunk) => chunk.chunkX === 1 && chunk.chunkY === 1));
30 assert.equal(chunkKey(2, -3), "2,-3");
58 assert.equal(coverage.residentRegions.length, 9);
59 assert.ok(coverage.residentRegions.some((region) => region.regionX === 0 && region.regionY === 0));
60 assert.ok(coverage.residentRegions.some((region) => region.regionX === 1 && region.regionY === 0));
61});
62
63test("overlapping loaders share reference counts", () =>
64{
65 const { chunkSim, regionRes } = accumulateLoaderRefs([
66 { tileX: 8, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER },
67 { tileX: 9, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER }
68 ]);
69 assert.equal(chunkSim.get("0,0"), 2);
70 assert.equal(regionRes.get("0,0"), 2);
71});
72
73test("global entity ids survive serialize and adopt on another world", () =>
74{
75 const source = new EcsWorld();
76 const handle = source.adopt(42);
77 source.add(handle, "position", { tileX: 3, tileY: 4 });
78 const payload = serializeEntity(source, 42);
79 const dest = new EcsWorld();
80 const restored = deserializeEntity(dest, payload);
81 assert.equal(restored, 42);
82 assert.equal(dest.entityIdOf(dest.handleOf(42)), 42);
83 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4 });
84 assert.equal(dest.entityIdOf(dest.entity()), 43);
31});
85});
server/tests/ecs.test.js added +54 −0
@@ -0,0 +1,54 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { EcsWorld } from "../src/ecs/world.js";
4 import { deserializeEntity, normalizeMobileComponents, serializeEntity } from "../src/ecs/serialize.js";
5
6 test("worker-local handles recycle independently of global entity ids", () =>
7 {
8 const world = new EcsWorld();
9 const first = world.spawn(100);
10 assert.equal(first, 1);
11 assert.equal(world.entityIdOf(first), 100);
12 world.destroy(first);
13 const second = world.spawn(200);
14 assert.equal(second, 1);
15 assert.equal(world.entityIdOf(second), 200);
16 assert.equal(world.handleOf(100), null);
17 assert.equal(world.hasEntity(200), true);
18 assert.equal(world.hasEntity(100), false);
19 });
20
21 test("legacy movement.path and character.sessionId become Path and NetworkIdentity", () =>
22 {
23 const normalized = normalizeMobileComponents({
24 movement: { gait: "walk", path: [{ x: 1, y: 2 }], walkCarry: 0 },
25 character: { characterId: 9, accountId: 3, sessionId: 4 }
26 });
27 assert.deepEqual(normalized.movement, { gait: "walk", walkCarry: 0 });
28 assert.deepEqual(normalized.path, { tiles: [{ x: 1, y: 2 }] });
29 assert.deepEqual(normalized.character, { characterId: 9, accountId: 3 });
30 assert.deepEqual(normalized.networkIdentity, { sessionId: 4 });
31 });
32
33 test("query returns both handle and entity id", () =>
34 {
35 const world = new EcsWorld();
36 const handle = world.spawn(50);
37 world.add(handle, "position", { tileX: 1, tileY: 2 });
38 const [row] = world.query("position");
39 assert.equal(row.handle, handle);
40 assert.equal(row.entityId, 50);
41 assert.deepEqual(row.position, { tileX: 1, tileY: 2 });
42 });
43
44 test("deserialize adopts the same entity id with a new local handle", () =>
45 {
46 const source = new EcsWorld();
47 source.add(source.spawn(7), "position", { tileX: 4, tileY: 5 });
48 const dest = new EcsWorld();
49 dest.spawn(1);
50 const restored = deserializeEntity(dest, serializeEntity(source, 7));
51 assert.equal(restored, 7);
52 assert.notEqual(dest.handleOf(7), source.handleOf(7));
53 assert.equal(dest.entityIdOf(dest.handleOf(7)), 7);
54 });
@@ -0,0 +1,54 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { EcsWorld } from "../src/ecs/world.js";
4import { deserializeEntity, normalizeMobileComponents, serializeEntity } from "../src/ecs/serialize.js";
5
6test("worker-local handles recycle independently of global entity ids", () =>
7{
8 const world = new EcsWorld();
9 const first = world.spawn(100);
10 assert.equal(first, 1);
11 assert.equal(world.entityIdOf(first), 100);
12 world.destroy(first);
13 const second = world.spawn(200);
14 assert.equal(second, 1);
15 assert.equal(world.entityIdOf(second), 200);
16 assert.equal(world.handleOf(100), null);
17 assert.equal(world.hasEntity(200), true);
18 assert.equal(world.hasEntity(100), false);
19});
20
21test("legacy movement.path and character.sessionId become Path and NetworkIdentity", () =>
22{
23 const normalized = normalizeMobileComponents({
24 movement: { gait: "walk", path: [{ x: 1, y: 2 }], walkCarry: 0 },
25 character: { characterId: 9, accountId: 3, sessionId: 4 }
26 });
27 assert.deepEqual(normalized.movement, { gait: "walk", walkCarry: 0 });
28 assert.deepEqual(normalized.path, { tiles: [{ x: 1, y: 2 }] });
29 assert.deepEqual(normalized.character, { characterId: 9, accountId: 3 });
30 assert.deepEqual(normalized.networkIdentity, { sessionId: 4 });
31});
32
33test("query returns both handle and entity id", () =>
34{
35 const world = new EcsWorld();
36 const handle = world.spawn(50);
37 world.add(handle, "position", { tileX: 1, tileY: 2 });
38 const [row] = world.query("position");
39 assert.equal(row.handle, handle);
40 assert.equal(row.entityId, 50);
41 assert.deepEqual(row.position, { tileX: 1, tileY: 2 });
42});
43
44test("deserialize adopts the same entity id with a new local handle", () =>
45{
46 const source = new EcsWorld();
47 source.add(source.spawn(7), "position", { tileX: 4, tileY: 5 });
48 const dest = new EcsWorld();
49 dest.spawn(1);
50 const restored = deserializeEntity(dest, serializeEntity(source, 7));
51 assert.equal(restored, 7);
52 assert.notEqual(dest.handleOf(7), source.handleOf(7));
53 assert.equal(dest.entityIdOf(dest.handleOf(7)), 7);
54});
server/tests/helpers/simulationHarness.js added +102 −0
@@ -0,0 +1,102 @@
1 import { mkdtempSync } from "node:fs";
2 import { tmpdir } from "node:os";
3 import { join } from "node:path";
4 import { WorldDatabase } from "../../src/persistence/worldDb.js";
5 import { StateDatabase } from "../../src/persistence/stateDb.js";
6 import { Simulation } from "../../src/simulation/simulation.js";
7 import { createEmptyChunkData, encodeChunkBlob } from "../../src/world/chunkData.js";
8
9 let surname = 1;
10
11 export function writeOpenChunk (worldDb, chunkX, chunkY)
12 {
13 const data = createEmptyChunkData();
14 data.open = true;
15 worldDb.saveChunkVersion(
16 chunkX,
17 chunkY,
18 worldDb.getActiveRevisionId(),
19 true,
20 encodeChunkBlob(data)
21 );
22 }
23
24 export function openChunkStrip (worldDb, maxChunkX = 5)
25 {
26 for (let chunkX = 0; chunkX <= maxChunkX; chunkX++)
27 { writeOpenChunk(worldDb, chunkX, 0); }
28 }
29
30 export function makeSimulation (options = {})
31 {
32 const dir = mkdtempSync(join(tmpdir(), "mmo-workers-"));
33 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
34 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
35 openChunkStrip(worldDb, options.maxChunkX ?? 5);
36 for (const coord of options.extraChunks ?? [])
37 { writeOpenChunk(worldDb, coord[0], coord[1]); }
38 let now = options.now ?? 1_000;
39 const simulation = new Simulation(worldDb, stateDb, {
40 workerCount: options.workerCount ?? 2,
41 workerMode: options.workerMode ?? "inprocess",
42 pinRegion: options.pinRegion ?? null,
43 now: () => now
44 });
45 if (options.graceMs != null)
46 { simulation.applySettings({ regionUnloadGracePeriodMs: options.graceMs }); }
47 return {
48 simulation,
49 worldDb,
50 stateDb,
51 now ()
52 {
53 return now;
54 },
55 setNow (value)
56 {
57 now = value;
58 },
59 advance (ms)
60 {
61 now += ms;
62 },
63 close ()
64 {
65 simulation.forceUnloadAll();
66 worldDb.close();
67 stateDb.close();
68 }
69 };
70 }
71
72 export function makeCharacter (stateDb, options = {})
73 {
74 const lastName = options.lastName ?? `Worker${surname++}`;
75 const account = stateDb.createAccount(`admin-${lastName.toLowerCase()}`, true);
76 return stateDb.createCharacter(
77 account.account_id,
78 options.firstName ?? "Ada",
79 lastName,
80 options.sex ?? "female",
81 options.tileX ?? 8,
82 options.tileY ?? 8
83 );
84 }
85
86 export function pinEastSplit (regionX)
87 {
88 return regionX >= 1 ? 1 : 0;
89 }
90
91 export function stepTimes (simulation, count)
92 {
93 const events = [];
94 for (let i = 0; i < count; i++)
95 { events.push(...simulation.step().events); }
96 return events;
97 }
98
99 export function walkTicks (tiles = 1)
100 {
101 return tiles * 10;
102 }
@@ -0,0 +1,102 @@
1import { mkdtempSync } from "node:fs";
2import { tmpdir } from "node:os";
3import { join } from "node:path";
4import { WorldDatabase } from "../../src/persistence/worldDb.js";
5import { StateDatabase } from "../../src/persistence/stateDb.js";
6import { Simulation } from "../../src/simulation/simulation.js";
7import { createEmptyChunkData, encodeChunkBlob } from "../../src/world/chunkData.js";
8
9let surname = 1;
10
11export function writeOpenChunk (worldDb, chunkX, chunkY)
12{
13 const data = createEmptyChunkData();
14 data.open = true;
15 worldDb.saveChunkVersion(
16 chunkX,
17 chunkY,
18 worldDb.getActiveRevisionId(),
19 true,
20 encodeChunkBlob(data)
21 );
22}
23
24export function openChunkStrip (worldDb, maxChunkX = 5)
25{
26 for (let chunkX = 0; chunkX <= maxChunkX; chunkX++)
27 { writeOpenChunk(worldDb, chunkX, 0); }
28}
29
30export function makeSimulation (options = {})
31{
32 const dir = mkdtempSync(join(tmpdir(), "mmo-workers-"));
33 const worldDb = new WorldDatabase(join(dir, "world.sqlite"));
34 const stateDb = new StateDatabase(join(dir, "state.sqlite"));
35 openChunkStrip(worldDb, options.maxChunkX ?? 5);
36 for (const coord of options.extraChunks ?? [])
37 { writeOpenChunk(worldDb, coord[0], coord[1]); }
38 let now = options.now ?? 1_000;
39 const simulation = new Simulation(worldDb, stateDb, {
40 workerCount: options.workerCount ?? 2,
41 workerMode: options.workerMode ?? "inprocess",
42 pinRegion: options.pinRegion ?? null,
43 now: () => now
44 });
45 if (options.graceMs != null)
46 { simulation.applySettings({ regionUnloadGracePeriodMs: options.graceMs }); }
47 return {
48 simulation,
49 worldDb,
50 stateDb,
51 now ()
52 {
53 return now;
54 },
55 setNow (value)
56 {
57 now = value;
58 },
59 advance (ms)
60 {
61 now += ms;
62 },
63 close ()
64 {
65 simulation.forceUnloadAll();
66 worldDb.close();
67 stateDb.close();
68 }
69 };
70}
71
72export function makeCharacter (stateDb, options = {})
73{
74 const lastName = options.lastName ?? `Worker${surname++}`;
75 const account = stateDb.createAccount(`admin-${lastName.toLowerCase()}`, true);
76 return stateDb.createCharacter(
77 account.account_id,
78 options.firstName ?? "Ada",
79 lastName,
80 options.sex ?? "female",
81 options.tileX ?? 8,
82 options.tileY ?? 8
83 );
84}
85
86export function pinEastSplit (regionX)
87{
88 return regionX >= 1 ? 1 : 0;
89}
90
91export function stepTimes (simulation, count)
92{
93 const events = [];
94 for (let i = 0; i < count; i++)
95 { events.push(...simulation.step().events); }
96 return events;
97}
98
99export function walkTicks (tiles = 1)
100{
101 return tiles * 10;
102}
server/tests/inventory.test.js added +133 −0
@@ -0,0 +1,133 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4 import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5 import { BlockType } from "../../shared/definitions/tiles.js";
6 import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7 import {
8 makeCharacter,
9 makeSimulation,
10 stepTimes
11 } from "./helpers/simulationHarness.js";
12
13 test("stackable items merge until max stack then need a new slot", () =>
14 {
15 const slots = emptySlots();
16 const def = itemDefinition(ItemId.apple);
17 assert.equal(insertStack(slots, { itemId: ItemId.apple, quantity: 40 }, def).ok, true);
18 const first = insertStack(slots, { itemId: ItemId.apple, quantity: 40 }, def);
19 assert.equal(first.ok, true);
20 const second = insertStack(first.slots, { itemId: ItemId.apple, quantity: 40 }, def);
21 assert.equal(second.ok, true);
22 const taken = takeFromSlot(second.slots, 0, 10);
23 assert.equal(taken.ok, true);
24 assert.equal(taken.taken.quantity, 10);
25 assert.equal(taken.slots[0].quantity, 70);
26 });
27
28 test("a player can drop and pick up an item on their tile", () =>
29 {
30 const harness = makeSimulation({ workerCount: 1 });
31 try
32 {
33 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
34 const entityId = harness.simulation.spawnCharacter(1, character);
35 const bag = harness.simulation.bagOf(entityId);
36 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
37 assert.ok(appleSlot >= 0);
38 harness.simulation.enqueue(1, {
39 type: "drop-item",
40 characterId: character.character_id,
41 slotIndex: appleSlot,
42 quantity: 1
43 });
44 const events = harness.simulation.step().events;
45 const appear = events.find((event) => event.type === "ground-item-appear");
46 assert.ok(appear);
47 assert.equal(appear.tileX, 8);
48 assert.equal(appear.itemId, ItemId.apple);
49 const afterDrop = harness.simulation.bagOf(entityId);
50 assert.equal(afterDrop.inventory[appleSlot].quantity, 2);
51 harness.simulation.enqueue(1, {
52 type: "pickup-item",
53 characterId: character.character_id,
54 groundItemId: appear.groundItemId
55 });
56 harness.simulation.step();
57 const afterPick = harness.simulation.bagOf(entityId);
58 assert.equal(afterPick.inventory[appleSlot].quantity, 3);
59 const snapshot = harness.simulation.snapshotChunk(0, 0);
60 assert.equal((snapshot.groundItems ?? []).length, 0);
61 }
62 finally
63 { harness.close(); }
64 });
65
66 test("walkTilesPerSecond controls how many tiles move per simulated second", () =>
67 {
68 const harness = makeSimulation({ workerCount: 1 });
69 try
70 {
71 harness.simulation.applySettings({ walkTilesPerSecond: 2, simulationTickHz: 20 });
72 const slow = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
73 const slowId = harness.simulation.spawnCharacter(1, slow);
74 harness.simulation.enqueue(1, { type: "move-to", characterId: slow.character_id, tileX: 20, tileY: 8 });
75 stepTimes(harness.simulation, 20);
76 assert.equal(harness.simulation.entityRecord(slowId).tileX, 4);
77
78 harness.simulation.applySettings({ walkTilesPerSecond: 4, simulationTickHz: 20 });
79 harness.simulation.enqueue(1, { type: "move-to", characterId: slow.character_id, tileX: 20, tileY: 8 });
80 stepTimes(harness.simulation, 20);
81 assert.equal(harness.simulation.entityRecord(slowId).tileX, 8);
82 }
83 finally
84 { harness.close(); }
85 });
86
87 test("equip uses the item key-equip sprite for appearance layers", () =>
88 {
89 const harness = makeSimulation({ workerCount: 1 });
90 try
91 {
92 const character = makeCharacter(harness.stateDb);
93 const entityId = harness.simulation.spawnCharacter(1, character);
94 const bag = harness.simulation.bagOf(entityId);
95 const shirtSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.clothShirt);
96 harness.simulation.enqueue(1, {
97 type: "equip-item",
98 characterId: character.character_id,
99 slotIndex: shirtSlot
100 });
101 harness.simulation.step();
102 const view = harness.simulation.entityRecord(entityId);
103 assert.ok(view.layers.some((layer) => layer.sprite === "item:cloth-shirt:cloth-shirt:equip"));
104 }
105 finally
106 { harness.close(); }
107 });
108
109 test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
110 {
111 const harness = makeSimulation({ workerCount: 1 });
112 try
113 {
114 const data = createEmptyChunkData();
115 data.open = true;
116 data.blocks[8 * 16 + 8] = {
117 typeId: BlockType.spawner,
118 state: null,
119 config: { spawnerId: "0:0:136", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 3 }
120 };
121 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
122 harness.simulation.reloadWorld();
123 const character = makeCharacter(harness.stateDb, { tileX: 4, tileY: 4 });
124 harness.simulation.spawnCharacter(1, character);
125 for (let i = 0; i < 80; i++)
126 { harness.simulation.step(); }
127 const deer = harness.simulation.debugWorld().entities.filter((entity) => !entity.characterId);
128 assert.ok(deer.length >= 1);
129 assert.ok(deer.length <= 2);
130 }
131 finally
132 { harness.close(); }
133 });
@@ -0,0 +1,133 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { emptySlots, insertStack, takeFromSlot } from "../../shared/items/inventory.js";
4import { ItemId, itemDefinition } from "../../shared/definitions/items.js";
5import { BlockType } from "../../shared/definitions/tiles.js";
6import { encodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7import {
8 makeCharacter,
9 makeSimulation,
10 stepTimes
11} from "./helpers/simulationHarness.js";
12
13test("stackable items merge until max stack then need a new slot", () =>
14{
15 const slots = emptySlots();
16 const def = itemDefinition(ItemId.apple);
17 assert.equal(insertStack(slots, { itemId: ItemId.apple, quantity: 40 }, def).ok, true);
18 const first = insertStack(slots, { itemId: ItemId.apple, quantity: 40 }, def);
19 assert.equal(first.ok, true);
20 const second = insertStack(first.slots, { itemId: ItemId.apple, quantity: 40 }, def);
21 assert.equal(second.ok, true);
22 const taken = takeFromSlot(second.slots, 0, 10);
23 assert.equal(taken.ok, true);
24 assert.equal(taken.taken.quantity, 10);
25 assert.equal(taken.slots[0].quantity, 70);
26});
27
28test("a player can drop and pick up an item on their tile", () =>
29{
30 const harness = makeSimulation({ workerCount: 1 });
31 try
32 {
33 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
34 const entityId = harness.simulation.spawnCharacter(1, character);
35 const bag = harness.simulation.bagOf(entityId);
36 const appleSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.apple);
37 assert.ok(appleSlot >= 0);
38 harness.simulation.enqueue(1, {
39 type: "drop-item",
40 characterId: character.character_id,
41 slotIndex: appleSlot,
42 quantity: 1
43 });
44 const events = harness.simulation.step().events;
45 const appear = events.find((event) => event.type === "ground-item-appear");
46 assert.ok(appear);
47 assert.equal(appear.tileX, 8);
48 assert.equal(appear.itemId, ItemId.apple);
49 const afterDrop = harness.simulation.bagOf(entityId);
50 assert.equal(afterDrop.inventory[appleSlot].quantity, 2);
51 harness.simulation.enqueue(1, {
52 type: "pickup-item",
53 characterId: character.character_id,
54 groundItemId: appear.groundItemId
55 });
56 harness.simulation.step();
57 const afterPick = harness.simulation.bagOf(entityId);
58 assert.equal(afterPick.inventory[appleSlot].quantity, 3);
59 const snapshot = harness.simulation.snapshotChunk(0, 0);
60 assert.equal((snapshot.groundItems ?? []).length, 0);
61 }
62 finally
63 { harness.close(); }
64});
65
66test("walkTilesPerSecond controls how many tiles move per simulated second", () =>
67{
68 const harness = makeSimulation({ workerCount: 1 });
69 try
70 {
71 harness.simulation.applySettings({ walkTilesPerSecond: 2, simulationTickHz: 20 });
72 const slow = makeCharacter(harness.stateDb, { tileX: 2, tileY: 8 });
73 const slowId = harness.simulation.spawnCharacter(1, slow);
74 harness.simulation.enqueue(1, { type: "move-to", characterId: slow.character_id, tileX: 20, tileY: 8 });
75 stepTimes(harness.simulation, 20);
76 assert.equal(harness.simulation.entityRecord(slowId).tileX, 4);
77
78 harness.simulation.applySettings({ walkTilesPerSecond: 4, simulationTickHz: 20 });
79 harness.simulation.enqueue(1, { type: "move-to", characterId: slow.character_id, tileX: 20, tileY: 8 });
80 stepTimes(harness.simulation, 20);
81 assert.equal(harness.simulation.entityRecord(slowId).tileX, 8);
82 }
83 finally
84 { harness.close(); }
85});
86
87test("equip uses the item key-equip sprite for appearance layers", () =>
88{
89 const harness = makeSimulation({ workerCount: 1 });
90 try
91 {
92 const character = makeCharacter(harness.stateDb);
93 const entityId = harness.simulation.spawnCharacter(1, character);
94 const bag = harness.simulation.bagOf(entityId);
95 const shirtSlot = bag.inventory.findIndex((slot) => slot?.itemId === ItemId.clothShirt);
96 harness.simulation.enqueue(1, {
97 type: "equip-item",
98 characterId: character.character_id,
99 slotIndex: shirtSlot
100 });
101 harness.simulation.step();
102 const view = harness.simulation.entityRecord(entityId);
103 assert.ok(view.layers.some((layer) => layer.sprite === "item:cloth-shirt:cloth-shirt:equip"));
104 }
105 finally
106 { harness.close(); }
107});
108
109test("a spawner in a simulating open chunk creates deer up to maxAlive", () =>
110{
111 const harness = makeSimulation({ workerCount: 1 });
112 try
113 {
114 const data = createEmptyChunkData();
115 data.open = true;
116 data.blocks[8 * 16 + 8] = {
117 typeId: BlockType.spawner,
118 state: null,
119 config: { spawnerId: "0:0:136", mobTypeId: "deer", maxAlive: 2, spawnRangeTiles: 3 }
120 };
121 harness.worldDb.saveChunkVersion(0, 0, harness.worldDb.getActiveRevisionId(), true, encodeChunkBlob(data));
122 harness.simulation.reloadWorld();
123 const character = makeCharacter(harness.stateDb, { tileX: 4, tileY: 4 });
124 harness.simulation.spawnCharacter(1, character);
125 for (let i = 0; i < 80; i++)
126 { harness.simulation.step(); }
127 const deer = harness.simulation.debugWorld().entities.filter((entity) => !entity.characterId);
128 assert.ok(deer.length >= 1);
129 assert.ok(deer.length <= 2);
130 }
131 finally
132 { harness.close(); }
133});
server/tests/proximity-speech.test.js added +80 −0
@@ -0,0 +1,80 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { CHUNK_SIZE, MessageType } from "../../shared/protocol/constants.js";
4 import { obscureSpeech, speechReadability } from "../../shared/speech/proximity.js";
5 import { broadcastSpeech } from "../src/chat/speech.js";
6
7 test("speech stays clear until half a chunk, then falls to zero at one chunk", () =>
8 {
9 assert.equal(speechReadability(0), 1);
10 assert.equal(speechReadability(CHUNK_SIZE * 0.5), 1);
11 assert.equal(speechReadability(CHUNK_SIZE * 0.75), 0.5);
12 assert.equal(speechReadability(CHUNK_SIZE), 0);
13 assert.equal(speechReadability(CHUNK_SIZE + 4), 0);
14 });
15
16 test("obscured speech is deterministic and hides letters with distance", () =>
17 {
18 const source = "Hello there";
19 assert.equal(obscureSpeech(source, 1, 7), source);
20 assert.equal(obscureSpeech(source, 0, 7), "");
21 const far = obscureSpeech(source, 0.4, 7);
22 assert.equal(obscureSpeech(source, 0.4, 7), far);
23 assert.match(far, /\./);
24 assert.match(far, / /);
25 });
26
27 test("broadcastSpeech trims, caps length, and only sends audible bubbles", () =>
28 {
29 function session (id, entityId)
30 {
31 const sent = [];
32 return {
33 id,
34 entityId,
35 characterId: entityId,
36 socket: { readyState: 1, send (raw) { sent.push(JSON.parse(raw)); } },
37 sent
38 };
39 }
40
41 const speaker = session(1, 10);
42 const near = session(2, 20);
43 const mid = session(3, 30);
44 const silent = session(4, 40);
45 const positions = new Map([
46 [10, { tileX: 0, tileY: 0 }],
47 [20, { tileX: 4, tileY: 0 }],
48 [30, { tileX: 12, tileY: 0 }],
49 [40, { tileX: 16, tileY: 0 }]
50 ]);
51 const simulation = {
52 settings: { chatMaxCharacters: 8 },
53 positionOf (id)
54 {
55 return positions.get(id) ?? null;
56 }
57 };
58 const sessions = new Map([
59 [speaker.id, speaker],
60 [near.id, near],
61 [mid.id, mid],
62 [silent.id, silent]
63 ]);
64
65 broadcastSpeech(sessions, simulation, speaker, " hello world ");
66 assert.equal(speaker.sent.length, 1);
67 assert.equal(speaker.sent[0].type, MessageType.chatBubble);
68 assert.equal(speaker.sent[0].text, "hello wo");
69 assert.equal(near.sent[0].text, "hello wo");
70 assert.equal(
71 mid.sent[0].text,
72 obscureSpeech("hello wo", speechReadability(12), speaker.sent[0].messageId ^ mid.id)
73 );
74 assert.equal(silent.sent.length, 0);
75
76 for (const entry of sessions.values())
77 { entry.sent.length = 0; }
78 broadcastSpeech(sessions, simulation, speaker, " ");
79 assert.equal(speaker.sent.length, 0);
80 });
@@ -0,0 +1,80 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { CHUNK_SIZE, MessageType } from "../../shared/protocol/constants.js";
4import { obscureSpeech, speechReadability } from "../../shared/speech/proximity.js";
5import { broadcastSpeech } from "../src/chat/speech.js";
6
7test("speech stays clear until half a chunk, then falls to zero at one chunk", () =>
8{
9 assert.equal(speechReadability(0), 1);
10 assert.equal(speechReadability(CHUNK_SIZE * 0.5), 1);
11 assert.equal(speechReadability(CHUNK_SIZE * 0.75), 0.5);
12 assert.equal(speechReadability(CHUNK_SIZE), 0);
13 assert.equal(speechReadability(CHUNK_SIZE + 4), 0);
14});
15
16test("obscured speech is deterministic and hides letters with distance", () =>
17{
18 const source = "Hello there";
19 assert.equal(obscureSpeech(source, 1, 7), source);
20 assert.equal(obscureSpeech(source, 0, 7), "");
21 const far = obscureSpeech(source, 0.4, 7);
22 assert.equal(obscureSpeech(source, 0.4, 7), far);
23 assert.match(far, /\./);
24 assert.match(far, / /);
25});
26
27test("broadcastSpeech trims, caps length, and only sends audible bubbles", () =>
28{
29 function session (id, entityId)
30 {
31 const sent = [];
32 return {
33 id,
34 entityId,
35 characterId: entityId,
36 socket: { readyState: 1, send (raw) { sent.push(JSON.parse(raw)); } },
37 sent
38 };
39 }
40
41 const speaker = session(1, 10);
42 const near = session(2, 20);
43 const mid = session(3, 30);
44 const silent = session(4, 40);
45 const positions = new Map([
46 [10, { tileX: 0, tileY: 0 }],
47 [20, { tileX: 4, tileY: 0 }],
48 [30, { tileX: 12, tileY: 0 }],
49 [40, { tileX: 16, tileY: 0 }]
50 ]);
51 const simulation = {
52 settings: { chatMaxCharacters: 8 },
53 positionOf (id)
54 {
55 return positions.get(id) ?? null;
56 }
57 };
58 const sessions = new Map([
59 [speaker.id, speaker],
60 [near.id, near],
61 [mid.id, mid],
62 [silent.id, silent]
63 ]);
64
65 broadcastSpeech(sessions, simulation, speaker, " hello world ");
66 assert.equal(speaker.sent.length, 1);
67 assert.equal(speaker.sent[0].type, MessageType.chatBubble);
68 assert.equal(speaker.sent[0].text, "hello wo");
69 assert.equal(near.sent[0].text, "hello wo");
70 assert.equal(
71 mid.sent[0].text,
72 obscureSpeech("hello wo", speechReadability(12), speaker.sent[0].messageId ^ mid.id)
73 );
74 assert.equal(silent.sent.length, 0);
75
76 for (const entry of sessions.values())
77 { entry.sent.length = 0; }
78 broadcastSpeech(sessions, simulation, speaker, " ");
79 assert.equal(speaker.sent.length, 0);
80});
server/tests/replication.test.js added +52 −0
@@ -0,0 +1,52 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5 test("joining and leaving emit spawn and despawn replication instead of extra snapshots", () =>
6 {
7 const harness = makeSimulation({ workerCount: 1 });
8 try
9 {
10 const first = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
11 const firstId = harness.simulation.spawnCharacter(1, first);
12 assert.ok(harness.simulation.drainReplication().some((event) =>
13 event.type === "entity-spawn" && event.entityId === firstId && event.firstName === "Ada"
14 ));
15
16 const second = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Ben" });
17 const secondId = harness.simulation.spawnCharacter(2, second);
18 const spawned = harness.simulation.drainReplication();
19 assert.ok(spawned.some((event) => event.type === "entity-spawn" && event.entityId === secondId));
20 assert.equal(spawned.some((event) => event.sessionId != null), false);
21
22 harness.simulation.despawnCharacter(second.character_id);
23 const gone = harness.simulation.drainReplication();
24 assert.ok(gone.some((event) =>
25 event.type === "entity-despawn" && event.entityId === secondId && event.tileX === 9 && event.tileY === 8
26 ));
27 }
28 finally
29 { harness.close(); }
30 });
31
32 test("movement replication carries tile and gait only", () =>
33 {
34 const harness = makeSimulation({ workerCount: 1 });
35 try
36 {
37 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
38 const entityId = harness.simulation.spawnCharacter(1, character);
39 harness.simulation.drainReplication();
40 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 10, tileY: 8 });
41 const events = stepTimes(harness.simulation, walkTicks(3));
42 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
43 assert.ok(move);
44 assert.equal(move.tileX, 9);
45 assert.equal(move.gait, "walk");
46 assert.equal(move.firstName, undefined);
47 assert.equal(move.sex, undefined);
48 assert.equal(move.characterId, undefined);
49 }
50 finally
51 { harness.close(); }
52 });
@@ -0,0 +1,52 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { makeCharacter, makeSimulation, stepTimes, walkTicks } from "./helpers/simulationHarness.js";
4
5test("joining and leaving emit spawn and despawn replication instead of extra snapshots", () =>
6{
7 const harness = makeSimulation({ workerCount: 1 });
8 try
9 {
10 const first = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
11 const firstId = harness.simulation.spawnCharacter(1, first);
12 assert.ok(harness.simulation.drainReplication().some((event) =>
13 event.type === "entity-spawn" && event.entityId === firstId && event.firstName === "Ada"
14 ));
15
16 const second = makeCharacter(harness.stateDb, { tileX: 9, tileY: 8, firstName: "Ben" });
17 const secondId = harness.simulation.spawnCharacter(2, second);
18 const spawned = harness.simulation.drainReplication();
19 assert.ok(spawned.some((event) => event.type === "entity-spawn" && event.entityId === secondId));
20 assert.equal(spawned.some((event) => event.sessionId != null), false);
21
22 harness.simulation.despawnCharacter(second.character_id);
23 const gone = harness.simulation.drainReplication();
24 assert.ok(gone.some((event) =>
25 event.type === "entity-despawn" && event.entityId === secondId && event.tileX === 9 && event.tileY === 8
26 ));
27 }
28 finally
29 { harness.close(); }
30});
31
32test("movement replication carries tile and gait only", () =>
33{
34 const harness = makeSimulation({ workerCount: 1 });
35 try
36 {
37 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
38 const entityId = harness.simulation.spawnCharacter(1, character);
39 harness.simulation.drainReplication();
40 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 10, tileY: 8 });
41 const events = stepTimes(harness.simulation, walkTicks(3));
42 const move = events.find((event) => event.type === "entity-move" && event.entityId === entityId);
43 assert.ok(move);
44 assert.equal(move.tileX, 9);
45 assert.equal(move.gait, "walk");
46 assert.equal(move.firstName, undefined);
47 assert.equal(move.sex, undefined);
48 assert.equal(move.characterId, undefined);
49 }
50 finally
51 { harness.close(); }
52});
server/tests/tile-states.test.js +29 −1
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3 3 import { fileURLToPath } from "node:url";
4 4 import { join } from "node:path";
5 5 import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6 import { cycleState, resolveState } from "../../shared/definitions/tileSprites.js";
6 import { cycleState, isCompanionSpriteStem, parseSpriteStem, resolveState } from "../../shared/definitions/tileSprites.js";
7 7 import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
8 8 import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
9 9 import { diffChunks } from "../src/editor/service.js";
@@ -20,6 +20,34 @@ test("sprite folders expose alphabetical states; first is default", () =>
20 20 assert.equal(catalog.images[0].perRow, 1);
21 21 });
22 22
23 test("bloom companions are not visual states", () =>
24 {
25 const catalog = buildSpriteCatalog(ASSET_ROOT);
26 assert.deepEqual(catalog.blocks.torch.states, ["torch"]);
27 assert.equal(catalog.blocks.torch.blooms.torch, true);
28 assert.ok(catalog.images.some((image) => image.name === "block:torch:torch:bloom"));
29 assert.ok(catalog.images.some((image) => image.name === "item:stick:stick:equip"));
30 assert.ok(!catalog.images.some((image) => image.name === "item:stick:stick:equip:bloom"));
31 assert.ok(catalog.images.some((image) => image.name === "item:paper:paper"));
32 assert.ok(catalog.images.some((image) => image.name === "mob:deer:deer"));
33 assert.ok(catalog.images.some((image) => image.name === "character:player-body-male:player-body-male"));
34 assert.ok(!catalog.blocks.torch.states.includes("torch-bloom"));
35 assert.ok(!catalog.blocks.torch.states.some((state) => state.includes("equip")));
36 assert.deepEqual(catalog.items.stick.states, ["stick"]);
37 assert.equal(catalog.items.stick.equips.stick, true);
38 });
39
40 test("sprite companion stems peel equip-bloom combinations", () =>
41 {
42 assert.deepEqual(parseSpriteStem("torch"), { base: "torch", companion: false, bloom: false, equip: false });
43 assert.deepEqual(parseSpriteStem("torch-bloom"), { base: "torch", companion: true, bloom: true, equip: false });
44 assert.deepEqual(parseSpriteStem("stick-equip"), { base: "stick", companion: true, bloom: false, equip: true });
45 assert.deepEqual(parseSpriteStem("stick-equip-bloom"), { base: "stick", companion: true, bloom: true, equip: true });
46 assert.equal(isCompanionSpriteStem("1-equip-bloom"), true);
47 assert.equal(isCompanionSpriteStem("1"), false);
48 assert.equal(resolveState(["1", "2"], "1-bloom"), "1");
49 });
50
23 51 test("state cycling wraps and unknown values fall back to default", () =>
24 52 {
25 53 assert.equal(resolveState(["closed", "open"], null), "closed");
@@ -3,7 +3,7 @@ import assert from "node:assert/strict";
3import { fileURLToPath } from "node:url";
3import { fileURLToPath } from "node:url";
4import { join } from "node:path";
4import { join } from "node:path";
5import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
5import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6import { cycleState, resolveState } from "../../shared/definitions/tileSprites.js";
6import { cycleState, isCompanionSpriteStem, parseSpriteStem, resolveState } from "../../shared/definitions/tileSprites.js";
7import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
7import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
8import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
8import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
9import { diffChunks } from "../src/editor/service.js";
9import { diffChunks } from "../src/editor/service.js";
@@ -20,6 +20,34 @@ test("sprite folders expose alphabetical states; first is default", () =>
20 assert.equal(catalog.images[0].perRow, 1);
20 assert.equal(catalog.images[0].perRow, 1);
21});
21});
22
22
23test("bloom companions are not visual states", () =>
24{
25 const catalog = buildSpriteCatalog(ASSET_ROOT);
26 assert.deepEqual(catalog.blocks.torch.states, ["torch"]);
27 assert.equal(catalog.blocks.torch.blooms.torch, true);
28 assert.ok(catalog.images.some((image) => image.name === "block:torch:torch:bloom"));
29 assert.ok(catalog.images.some((image) => image.name === "item:stick:stick:equip"));
30 assert.ok(!catalog.images.some((image) => image.name === "item:stick:stick:equip:bloom"));
31 assert.ok(catalog.images.some((image) => image.name === "item:paper:paper"));
32 assert.ok(catalog.images.some((image) => image.name === "mob:deer:deer"));
33 assert.ok(catalog.images.some((image) => image.name === "character:player-body-male:player-body-male"));
34 assert.ok(!catalog.blocks.torch.states.includes("torch-bloom"));
35 assert.ok(!catalog.blocks.torch.states.some((state) => state.includes("equip")));
36 assert.deepEqual(catalog.items.stick.states, ["stick"]);
37 assert.equal(catalog.items.stick.equips.stick, true);
38});
39
40test("sprite companion stems peel equip-bloom combinations", () =>
41{
42 assert.deepEqual(parseSpriteStem("torch"), { base: "torch", companion: false, bloom: false, equip: false });
43 assert.deepEqual(parseSpriteStem("torch-bloom"), { base: "torch", companion: true, bloom: true, equip: false });
44 assert.deepEqual(parseSpriteStem("stick-equip"), { base: "stick", companion: true, bloom: false, equip: true });
45 assert.deepEqual(parseSpriteStem("stick-equip-bloom"), { base: "stick", companion: true, bloom: true, equip: true });
46 assert.equal(isCompanionSpriteStem("1-equip-bloom"), true);
47 assert.equal(isCompanionSpriteStem("1"), false);
48 assert.equal(resolveState(["1", "2"], "1-bloom"), "1");
49});
50
23test("state cycling wraps and unknown values fall back to default", () =>
51test("state cycling wraps and unknown values fall back to default", () =>
24{
52{
25 assert.equal(resolveState(["closed", "open"], null), "closed");
53 assert.equal(resolveState(["closed", "open"], null), "closed");
server/tests/worker-lifecycle.test.js added +122 −0
@@ -0,0 +1,122 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { GAIT } from "../../shared/protocol/constants.js";
4 import {
5 makeCharacter,
6 makeSimulation,
7 pinEastSplit,
8 stepTimes,
9 walkTicks
10 } from "./helpers/simulationHarness.js";
11
12 function entityOn (simulation, entityId)
13 {
14 return simulation.entityRecord(entityId);
15 }
16
17 test("a player keeps nearby chunks simulating and surrounding regions resident", () =>
18 {
19 const harness = makeSimulation({ workerCount: 1, graceMs: 30_000 });
20 try
21 {
22 const character = makeCharacter(harness.stateDb);
23 const entityId = harness.simulation.spawnCharacter(1, character);
24 const debug = harness.simulation.debugWorld();
25 assert.equal(debug.workerCount, 1);
26 assert.ok(debug.simulatingChunks.includes("0,0"));
27 assert.ok(debug.simulatingChunks.includes("1,0"));
28 assert.ok(!debug.simulatingChunks.includes("3,0"));
29 assert.ok(debug.regions.some((region) => region.regionX === 0 && region.regionY === 0 && region.refs > 0));
30 assert.ok(debug.regions.some((region) => region.regionX === 1 && region.regionY === 0 && region.refs > 0));
31 assert.equal(entityOn(harness.simulation, entityId).workerId, 0);
32 }
33 finally
34 { harness.close(); }
35 });
36
37 test("dormant chunks do not simulate movement", () =>
38 {
39 const harness = makeSimulation({ workerCount: 1, graceMs: 30_000 });
40 try
41 {
42 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
43 harness.simulation.spawnCharacter(1, character);
44 const npcId = harness.simulation.spawnEntity({
45 position: { tileX: 50, tileY: 8 },
46 movement: { gait: GAIT.walk, path: [{ x: 51, y: 8 }], walkCarry: 0 },
47 appearance: { sex: "male", firstName: "Ned", lastName: "Still" }
48 });
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("3,0"));
50 stepTimes(harness.simulation, walkTicks(4));
51 const npc = entityOn(harness.simulation, npcId);
52 assert.equal(npc.tileX, 50);
53 assert.equal(npc.tileY, 8);
54 }
55 finally
56 { harness.close(); }
57 });
58
59 test("regions unload after the grace period once the last ChunkLoader leaves", () =>
60 {
61 const harness = makeSimulation({ workerCount: 1, graceMs: 10 });
62 try
63 {
64 const character = makeCharacter(harness.stateDb);
65 harness.simulation.spawnCharacter(1, character);
66 assert.ok(harness.simulation.debugWorld().regions.length > 0);
67 harness.simulation.despawnCharacter(character.character_id);
68 harness.simulation.step(harness.now());
69 assert.ok(harness.simulation.debugWorld().regions.length > 0, "still in grace");
70 harness.advance(10);
71 harness.simulation.step(harness.now());
72 assert.equal(harness.simulation.debugWorld().regions.length, 0);
73 }
74 finally
75 { harness.close(); }
76 });
77
78 test("persistent entities are saved on unload and restored when the region returns", () =>
79 {
80 const harness = makeSimulation({ workerCount: 1, graceMs: 0 });
81 try
82 {
83 const character = makeCharacter(harness.stateDb);
84 harness.simulation.spawnCharacter(1, character);
85 const npcId = harness.simulation.spawnEntity({
86 position: { tileX: 8, tileY: 9 },
87 appearance: { sex: "male", firstName: "Ned", lastName: "Keep" },
88 persistent: {}
89 });
90 harness.simulation.despawnCharacter(character.character_id);
91 harness.simulation.step(harness.now());
92 assert.equal(harness.simulation.entityRecord(npcId), null);
93 assert.equal(harness.stateDb.listPersistentInRegion(0, 0, 63, 63).length, 1);
94
95 harness.simulation.spawnCharacter(1, character);
96 const restored = harness.simulation.entityRecord(npcId);
97 assert.ok(restored);
98 assert.equal(restored.tileX, 8);
99 assert.equal(restored.tileY, 9);
100 assert.equal(restored.firstName, "Ned");
101 }
102 finally
103 { harness.close(); }
104 });
105
106 test("mutating a snapshot does not mutate worker memory", () =>
107 {
108 const harness = makeSimulation({ workerCount: 1 });
109 try
110 {
111 const character = makeCharacter(harness.stateDb);
112 harness.simulation.spawnCharacter(1, character);
113 const snapshot = harness.simulation.snapshotChunk(0, 0);
114 snapshot.open = false;
115 snapshot.entities.push({ entityId: 999 });
116 const again = harness.simulation.snapshotChunk(0, 0);
117 assert.equal(again.open, true);
118 assert.equal(again.entities.some((entity) => entity.entityId === 999), false);
119 }
120 finally
121 { harness.close(); }
122 });
@@ -0,0 +1,122 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { GAIT } from "../../shared/protocol/constants.js";
4import {
5 makeCharacter,
6 makeSimulation,
7 pinEastSplit,
8 stepTimes,
9 walkTicks
10} from "./helpers/simulationHarness.js";
11
12function entityOn (simulation, entityId)
13{
14 return simulation.entityRecord(entityId);
15}
16
17test("a player keeps nearby chunks simulating and surrounding regions resident", () =>
18{
19 const harness = makeSimulation({ workerCount: 1, graceMs: 30_000 });
20 try
21 {
22 const character = makeCharacter(harness.stateDb);
23 const entityId = harness.simulation.spawnCharacter(1, character);
24 const debug = harness.simulation.debugWorld();
25 assert.equal(debug.workerCount, 1);
26 assert.ok(debug.simulatingChunks.includes("0,0"));
27 assert.ok(debug.simulatingChunks.includes("1,0"));
28 assert.ok(!debug.simulatingChunks.includes("3,0"));
29 assert.ok(debug.regions.some((region) => region.regionX === 0 && region.regionY === 0 && region.refs > 0));
30 assert.ok(debug.regions.some((region) => region.regionX === 1 && region.regionY === 0 && region.refs > 0));
31 assert.equal(entityOn(harness.simulation, entityId).workerId, 0);
32 }
33 finally
34 { harness.close(); }
35});
36
37test("dormant chunks do not simulate movement", () =>
38{
39 const harness = makeSimulation({ workerCount: 1, graceMs: 30_000 });
40 try
41 {
42 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
43 harness.simulation.spawnCharacter(1, character);
44 const npcId = harness.simulation.spawnEntity({
45 position: { tileX: 50, tileY: 8 },
46 movement: { gait: GAIT.walk, path: [{ x: 51, y: 8 }], walkCarry: 0 },
47 appearance: { sex: "male", firstName: "Ned", lastName: "Still" }
48 });
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("3,0"));
50 stepTimes(harness.simulation, walkTicks(4));
51 const npc = entityOn(harness.simulation, npcId);
52 assert.equal(npc.tileX, 50);
53 assert.equal(npc.tileY, 8);
54 }
55 finally
56 { harness.close(); }
57});
58
59test("regions unload after the grace period once the last ChunkLoader leaves", () =>
60{
61 const harness = makeSimulation({ workerCount: 1, graceMs: 10 });
62 try
63 {
64 const character = makeCharacter(harness.stateDb);
65 harness.simulation.spawnCharacter(1, character);
66 assert.ok(harness.simulation.debugWorld().regions.length > 0);
67 harness.simulation.despawnCharacter(character.character_id);
68 harness.simulation.step(harness.now());
69 assert.ok(harness.simulation.debugWorld().regions.length > 0, "still in grace");
70 harness.advance(10);
71 harness.simulation.step(harness.now());
72 assert.equal(harness.simulation.debugWorld().regions.length, 0);
73 }
74 finally
75 { harness.close(); }
76});
77
78test("persistent entities are saved on unload and restored when the region returns", () =>
79{
80 const harness = makeSimulation({ workerCount: 1, graceMs: 0 });
81 try
82 {
83 const character = makeCharacter(harness.stateDb);
84 harness.simulation.spawnCharacter(1, character);
85 const npcId = harness.simulation.spawnEntity({
86 position: { tileX: 8, tileY: 9 },
87 appearance: { sex: "male", firstName: "Ned", lastName: "Keep" },
88 persistent: {}
89 });
90 harness.simulation.despawnCharacter(character.character_id);
91 harness.simulation.step(harness.now());
92 assert.equal(harness.simulation.entityRecord(npcId), null);
93 assert.equal(harness.stateDb.listPersistentInRegion(0, 0, 63, 63).length, 1);
94
95 harness.simulation.spawnCharacter(1, character);
96 const restored = harness.simulation.entityRecord(npcId);
97 assert.ok(restored);
98 assert.equal(restored.tileX, 8);
99 assert.equal(restored.tileY, 9);
100 assert.equal(restored.firstName, "Ned");
101 }
102 finally
103 { harness.close(); }
104});
105
106test("mutating a snapshot does not mutate worker memory", () =>
107{
108 const harness = makeSimulation({ workerCount: 1 });
109 try
110 {
111 const character = makeCharacter(harness.stateDb);
112 harness.simulation.spawnCharacter(1, character);
113 const snapshot = harness.simulation.snapshotChunk(0, 0);
114 snapshot.open = false;
115 snapshot.entities.push({ entityId: 999 });
116 const again = harness.simulation.snapshotChunk(0, 0);
117 assert.equal(again.open, true);
118 assert.equal(again.entities.some((entity) => entity.entityId === 999), false);
119 }
120 finally
121 { harness.close(); }
122});
server/tests/worker-replication.test.js added +68 −0
@@ -0,0 +1,68 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 makeCharacter,
5 makeSimulation,
6 pinEastSplit,
7 stepTimes,
8 walkTicks
9 } from "./helpers/simulationHarness.js";
10
11 test("a player at a region edge receives snapshots from both workers", () =>
12 {
13 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
14 try
15 {
16 const west = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
17 const east = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Ben" });
18 const westId = harness.simulation.spawnCharacter(1, west);
19 const eastId = harness.simulation.spawnCharacter(2, east);
20 assert.equal(harness.simulation.entityRecord(westId).workerId, 0);
21 assert.equal(harness.simulation.entityRecord(eastId).workerId, 1);
22
23 const snapshots = harness.simulation.snapshotFor(westId);
24 assert.equal(snapshots.length, 9);
25 const chunkFour = snapshots.find((snapshot) => snapshot.chunkX === 4 && snapshot.chunkY === 0);
26 assert.ok(chunkFour);
27 assert.equal(chunkFour.open, true);
28 assert.ok(chunkFour.entities.some((entity) => entity.entityId === eastId));
29 const chunkThree = snapshots.find((snapshot) => snapshot.chunkX === 3 && snapshot.chunkY === 0);
30 assert.ok(chunkThree.entities.some((entity) => entity.entityId === westId));
31 }
32 finally
33 { harness.close(); }
34 });
35
36 test("border occupancy from another worker blocks pathfinding", () =>
37 {
38 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
39 try
40 {
41 const walker = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
42 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
43 const walkerId = harness.simulation.spawnCharacter(1, walker);
44 harness.simulation.spawnCharacter(2, blocker);
45 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
46 stepTimes(harness.simulation, walkTicks(2));
47 assert.equal(harness.simulation.entityRecord(walkerId).tileX, 63);
48 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
49 }
50 finally
51 { harness.close(); }
52 });
53
54 test("local movement still works on a single worker", () =>
55 {
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
60 const entityId = harness.simulation.spawnCharacter(1, character);
61 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 10, tileY: 8 });
62 stepTimes(harness.simulation, walkTicks(3));
63 assert.equal(harness.simulation.entityRecord(entityId).tileX, 10);
64 assert.equal(harness.simulation.entityRecord(entityId).tileY, 8);
65 }
66 finally
67 { harness.close(); }
68 });
@@ -0,0 +1,68 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 makeCharacter,
5 makeSimulation,
6 pinEastSplit,
7 stepTimes,
8 walkTicks
9} from "./helpers/simulationHarness.js";
10
11test("a player at a region edge receives snapshots from both workers", () =>
12{
13 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
14 try
15 {
16 const west = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
17 const east = makeCharacter(harness.stateDb, { tileX: 70, tileY: 8, firstName: "Ben" });
18 const westId = harness.simulation.spawnCharacter(1, west);
19 const eastId = harness.simulation.spawnCharacter(2, east);
20 assert.equal(harness.simulation.entityRecord(westId).workerId, 0);
21 assert.equal(harness.simulation.entityRecord(eastId).workerId, 1);
22
23 const snapshots = harness.simulation.snapshotFor(westId);
24 assert.equal(snapshots.length, 9);
25 const chunkFour = snapshots.find((snapshot) => snapshot.chunkX === 4 && snapshot.chunkY === 0);
26 assert.ok(chunkFour);
27 assert.equal(chunkFour.open, true);
28 assert.ok(chunkFour.entities.some((entity) => entity.entityId === eastId));
29 const chunkThree = snapshots.find((snapshot) => snapshot.chunkX === 3 && snapshot.chunkY === 0);
30 assert.ok(chunkThree.entities.some((entity) => entity.entityId === westId));
31 }
32 finally
33 { harness.close(); }
34});
35
36test("border occupancy from another worker blocks pathfinding", () =>
37{
38 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
39 try
40 {
41 const walker = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
42 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
43 const walkerId = harness.simulation.spawnCharacter(1, walker);
44 harness.simulation.spawnCharacter(2, blocker);
45 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
46 stepTimes(harness.simulation, walkTicks(2));
47 assert.equal(harness.simulation.entityRecord(walkerId).tileX, 63);
48 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
49 }
50 finally
51 { harness.close(); }
52});
53
54test("local movement still works on a single worker", () =>
55{
56 const harness = makeSimulation({ workerCount: 1 });
57 try
58 {
59 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
60 const entityId = harness.simulation.spawnCharacter(1, character);
61 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 10, tileY: 8 });
62 stepTimes(harness.simulation, walkTicks(3));
63 assert.equal(harness.simulation.entityRecord(entityId).tileX, 10);
64 assert.equal(harness.simulation.entityRecord(entityId).tileY, 8);
65 }
66 finally
67 { harness.close(); }
68});
server/tests/worker-threads.test.js added +22 −0
@@ -0,0 +1,22 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
4
5 test("thread workers speak the same protocol as in-process workers", { timeout: 20_000 }, async () =>
6 {
7 const harness = makeSimulation({ workerCount: 1, workerMode: "thread" });
8 try
9 {
10 const character = makeCharacter(harness.stateDb);
11 const entityId = harness.simulation.spawnCharacter(1, character);
12 const snapshots = harness.simulation.snapshotFor(entityId);
13 assert.equal(snapshots.length, 9);
14 assert.ok(snapshots.some((snapshot) => snapshot.entities.some((entity) => entity.entityId === entityId)));
15 }
16 finally
17 {
18 await harness.simulation.shutdown();
19 harness.worldDb.close();
20 harness.stateDb.close();
21 }
22 });
@@ -0,0 +1,22 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { makeCharacter, makeSimulation } from "./helpers/simulationHarness.js";
4
5test("thread workers speak the same protocol as in-process workers", { timeout: 20_000 }, async () =>
6{
7 const harness = makeSimulation({ workerCount: 1, workerMode: "thread" });
8 try
9 {
10 const character = makeCharacter(harness.stateDb);
11 const entityId = harness.simulation.spawnCharacter(1, character);
12 const snapshots = harness.simulation.snapshotFor(entityId);
13 assert.equal(snapshots.length, 9);
14 assert.ok(snapshots.some((snapshot) => snapshot.entities.some((entity) => entity.entityId === entityId)));
15 }
16 finally
17 {
18 await harness.simulation.shutdown();
19 harness.worldDb.close();
20 harness.stateDb.close();
21 }
22});
server/tests/worker-transfer.test.js added +107 −0
@@ -0,0 +1,107 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 makeCharacter,
5 makeSimulation,
6 pinEastSplit,
7 stepTimes,
8 walkTicks
9 } from "./helpers/simulationHarness.js";
10
11 test("walking into a foreign region transfers the only authoritative copy", () =>
12 {
13 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
14 try
15 {
16 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
17 const entityId = harness.simulation.spawnCharacter(1, character);
18 assert.equal(harness.simulation.entityRecord(entityId).workerId, 0);
19
20 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
21 const events = stepTimes(harness.simulation, walkTicks(2));
22 const record = harness.simulation.entityRecord(entityId);
23 assert.equal(record.tileX, 64);
24 assert.equal(record.tileY, 8);
25 assert.equal(record.workerId, 1);
26 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === entityId).length, 1);
27 assert.ok(events.some((event) => event.type === "entity-move" && event.entityId === entityId && event.tileX === 64));
28
29 const onSource = harness.simulation.workers[0].call({ type: "listPublicEntities" });
30 const onDest = harness.simulation.workers[1].call({ type: "listPublicEntities" });
31 assert.equal(onSource.some((entity) => entity.entityId === entityId), false);
32 assert.equal(onDest.some((entity) => entity.entityId === entityId), true);
33 }
34 finally
35 { harness.close(); }
36 });
37
38 test("a transferred entity keeps its entity id and receives a new local handle", () =>
39 {
40 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
41 try
42 {
43 harness.simulation.spawnEntity({
44 position: { tileX: 70, tileY: 8 },
45 appearance: { sex: "male", firstName: "Pad", lastName: "East" }
46 });
47 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
48 const entityId = harness.simulation.spawnCharacter(1, character);
49 const sourceHandle = harness.simulation.workers[0].world.ecs.handleOf(entityId);
50 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
51 stepTimes(harness.simulation, walkTicks(2));
52 const destHandle = harness.simulation.workers[1].world.ecs.handleOf(entityId);
53 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
54 assert.equal(harness.simulation.workers[0].world.ecs.handleOf(entityId), null);
55 assert.notEqual(destHandle, sourceHandle);
56 assert.equal(harness.simulation.workers[1].world.ecs.entityIdOf(destHandle), entityId);
57 }
58 finally
59 { harness.close(); }
60 });
61
62 test("a blocked destination rejects the transfer and leaves one copy on the source worker", () =>
63 {
64 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
65 try
66 {
67 const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
69 const walkerId = harness.simulation.spawnCharacter(1, walker);
70 const blockerId = harness.simulation.spawnCharacter(2, blocker);
71 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72 assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);
73
74 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
75 stepTimes(harness.simulation, walkTicks(3));
76 const walking = harness.simulation.entityRecord(walkerId);
77 assert.ok(walking.tileX < 64);
78 assert.equal(walking.workerId, 0);
79 assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);
80 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
81 }
82 finally
83 { harness.close(); }
84 });
85
86 test("commands keep working after a transfer", () =>
87 {
88 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
89 try
90 {
91 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
92 const entityId = harness.simulation.spawnCharacter(1, character);
93 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
94 stepTimes(harness.simulation, walkTicks(2));
95 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
96
97 harness.simulation.enqueue(1, { type: "set-gait", characterId: character.character_id, gait: "run" });
98 harness.simulation.step();
99 assert.equal(harness.simulation.entityRecord(entityId).gait, "run");
100 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 65, tileY: 8 });
101 stepTimes(harness.simulation, 6);
102 assert.equal(harness.simulation.entityRecord(entityId).tileX, 65);
103 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
104 }
105 finally
106 { harness.close(); }
107 });
@@ -0,0 +1,107 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 makeCharacter,
5 makeSimulation,
6 pinEastSplit,
7 stepTimes,
8 walkTicks
9} from "./helpers/simulationHarness.js";
10
11test("walking into a foreign region transfers the only authoritative copy", () =>
12{
13 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
14 try
15 {
16 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
17 const entityId = harness.simulation.spawnCharacter(1, character);
18 assert.equal(harness.simulation.entityRecord(entityId).workerId, 0);
19
20 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
21 const events = stepTimes(harness.simulation, walkTicks(2));
22 const record = harness.simulation.entityRecord(entityId);
23 assert.equal(record.tileX, 64);
24 assert.equal(record.tileY, 8);
25 assert.equal(record.workerId, 1);
26 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === entityId).length, 1);
27 assert.ok(events.some((event) => event.type === "entity-move" && event.entityId === entityId && event.tileX === 64));
28
29 const onSource = harness.simulation.workers[0].call({ type: "listPublicEntities" });
30 const onDest = harness.simulation.workers[1].call({ type: "listPublicEntities" });
31 assert.equal(onSource.some((entity) => entity.entityId === entityId), false);
32 assert.equal(onDest.some((entity) => entity.entityId === entityId), true);
33 }
34 finally
35 { harness.close(); }
36});
37
38test("a transferred entity keeps its entity id and receives a new local handle", () =>
39{
40 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
41 try
42 {
43 harness.simulation.spawnEntity({
44 position: { tileX: 70, tileY: 8 },
45 appearance: { sex: "male", firstName: "Pad", lastName: "East" }
46 });
47 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
48 const entityId = harness.simulation.spawnCharacter(1, character);
49 const sourceHandle = harness.simulation.workers[0].world.ecs.handleOf(entityId);
50 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
51 stepTimes(harness.simulation, walkTicks(2));
52 const destHandle = harness.simulation.workers[1].world.ecs.handleOf(entityId);
53 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
54 assert.equal(harness.simulation.workers[0].world.ecs.handleOf(entityId), null);
55 assert.notEqual(destHandle, sourceHandle);
56 assert.equal(harness.simulation.workers[1].world.ecs.entityIdOf(destHandle), entityId);
57 }
58 finally
59 { harness.close(); }
60});
61
62test("a blocked destination rejects the transfer and leaves one copy on the source worker", () =>
63{
64 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
65 try
66 {
67 const walker = makeCharacter(harness.stateDb, { tileX: 62, tileY: 8 });
68 const blocker = makeCharacter(harness.stateDb, { tileX: 64, tileY: 8, firstName: "Bob" });
69 const walkerId = harness.simulation.spawnCharacter(1, walker);
70 const blockerId = harness.simulation.spawnCharacter(2, blocker);
71 assert.equal(harness.simulation.entityRecord(walkerId).workerId, 0);
72 assert.equal(harness.simulation.entityRecord(blockerId).workerId, 1);
73
74 harness.simulation.enqueue(1, { type: "move-to", characterId: walker.character_id, tileX: 64, tileY: 8 });
75 stepTimes(harness.simulation, walkTicks(3));
76 const walking = harness.simulation.entityRecord(walkerId);
77 assert.ok(walking.tileX < 64);
78 assert.equal(walking.workerId, 0);
79 assert.equal(harness.simulation.entityRecord(blockerId).tileX, 64);
80 assert.equal(harness.simulation.debugWorld().entities.filter((entity) => entity.entityId === walkerId).length, 1);
81 }
82 finally
83 { harness.close(); }
84});
85
86test("commands keep working after a transfer", () =>
87{
88 const harness = makeSimulation({ pinRegion: pinEastSplit, workerCount: 2 });
89 try
90 {
91 const character = makeCharacter(harness.stateDb, { tileX: 63, tileY: 8 });
92 const entityId = harness.simulation.spawnCharacter(1, character);
93 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 64, tileY: 8 });
94 stepTimes(harness.simulation, walkTicks(2));
95 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
96
97 harness.simulation.enqueue(1, { type: "set-gait", characterId: character.character_id, gait: "run" });
98 harness.simulation.step();
99 assert.equal(harness.simulation.entityRecord(entityId).gait, "run");
100 harness.simulation.enqueue(1, { type: "move-to", characterId: character.character_id, tileX: 65, tileY: 8 });
101 stepTimes(harness.simulation, 6);
102 assert.equal(harness.simulation.entityRecord(entityId).tileX, 65);
103 assert.equal(harness.simulation.entityRecord(entityId).workerId, 1);
104 }
105 finally
106 { harness.close(); }
107});
shared/definitions/items.js added +139 −0
@@ -0,0 +1,139 @@
1 import { equipImageName, spriteImageName } from "./tileSprites.js";
2
3 export const ItemId = Object.freeze({
4 paper: 1,
5 apple: 2,
6 stick: 3,
7 blankCheque: 4,
8 clothShirt: 5
9 });
10
11 export const EQUIPMENT_SLOT = Object.freeze({
12 head: "head",
13 chest: "chest",
14 legs: "legs",
15 boots: "boots",
16 weapon: "weapon",
17 offhand: "offhand"
18 });
19
20 export const EQUIPMENT_DRAW_ORDER = Object.freeze([
21 EQUIPMENT_SLOT.boots,
22 EQUIPMENT_SLOT.legs,
23 EQUIPMENT_SLOT.chest,
24 EQUIPMENT_SLOT.head,
25 EQUIPMENT_SLOT.offhand,
26 EQUIPMENT_SLOT.weapon
27 ]);
28
29 export const DEFAULT_MAX_STACK = 99;
30
31 export const ITEM_DEFINITIONS = Object.freeze({
32 [ItemId.paper]: Object.freeze({
33 itemId: ItemId.paper,
34 key: "paper",
35 displayName: "Paper",
36 description: "Blank paper. Later used to write letters.",
37 seedValue: 2,
38 stackable: true,
39 maxStackSize: DEFAULT_MAX_STACK,
40 uniqueInstance: false,
41 category: "document"
42 }),
43 [ItemId.apple]: Object.freeze({
44 itemId: ItemId.apple,
45 key: "apple",
46 displayName: "Apple",
47 description: "A placeholder fruit.",
48 seedValue: 1,
49 stackable: true,
50 maxStackSize: DEFAULT_MAX_STACK,
51 uniqueInstance: false,
52 category: "other"
53 }),
54 [ItemId.stick]: Object.freeze({
55 itemId: ItemId.stick,
56 key: "stick",
57 displayName: "Stick",
58 description: "A wooden stick. Can be wielded.",
59 seedValue: 3,
60 stackable: true,
61 maxStackSize: DEFAULT_MAX_STACK,
62 uniqueInstance: false,
63 category: "finished",
64 equipment: Object.freeze({
65 slot: EQUIPMENT_SLOT.weapon
66 })
67 }),
68 [ItemId.blankCheque]: Object.freeze({
69 itemId: ItemId.blankCheque,
70 key: "blank-cheque",
71 displayName: "Blank cheque",
72 description: "Placeholder bank paper. Filling comes with the bank.",
73 seedValue: 5,
74 stackable: true,
75 maxStackSize: DEFAULT_MAX_STACK,
76 uniqueInstance: false,
77 category: "document"
78 }),
79 [ItemId.clothShirt]: Object.freeze({
80 itemId: ItemId.clothShirt,
81 key: "cloth-shirt",
82 displayName: "Cloth shirt",
83 description: "A placeholder shirt worn on the chest.",
84 seedValue: 8,
85 stackable: false,
86 maxStackSize: 1,
87 uniqueInstance: false,
88 category: "finished",
89 equipment: Object.freeze({
90 slot: EQUIPMENT_SLOT.chest
91 })
92 })
93 });
94
95 export function itemDefinition (itemId)
96 {
97 return ITEM_DEFINITIONS[itemId] ?? null;
98 }
99
100 export function itemDefaultState (def)
101 {
102 return def?.defaultState ?? def?.key ?? "paper";
103 }
104
105 export function itemSpriteName (itemId)
106 {
107 const def = itemDefinition(itemId);
108 if (!def)
109 { return spriteImageName("item", "paper", "paper"); }
110 return def.sprite ?? spriteImageName("item", def.key, itemDefaultState(def));
111 }
112
113 export function itemEquipSprite (itemId)
114 {
115 const def = itemDefinition(itemId);
116 const equipment = def?.equipment;
117 if (!equipment)
118 { return null; }
119 return equipment.equipSprite
120 ?? equipment.overlaySpriteId
121 ?? equipImageName("item", def.key, itemDefaultState(def));
122 }
123
124 export function itemAssetPath (itemId, companion = null)
125 {
126 const def = itemDefinition(itemId);
127 const key = def?.key ?? "paper";
128 const state = itemDefaultState(def ?? { key });
129 const suffix = companion ? `-${companion}` : "";
130 return `/assets/items/${key}/${state}${suffix}.png`;
131 }
132
133 export const STARTER_CURRENCY = 25;
134 export const STARTER_ITEMS = Object.freeze([
135 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
136 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
137 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
138 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 })
139 ]);
@@ -0,0 +1,139 @@
1import { equipImageName, spriteImageName } from "./tileSprites.js";
2
3export const ItemId = Object.freeze({
4 paper: 1,
5 apple: 2,
6 stick: 3,
7 blankCheque: 4,
8 clothShirt: 5
9});
10
11export const EQUIPMENT_SLOT = Object.freeze({
12 head: "head",
13 chest: "chest",
14 legs: "legs",
15 boots: "boots",
16 weapon: "weapon",
17 offhand: "offhand"
18});
19
20export const EQUIPMENT_DRAW_ORDER = Object.freeze([
21 EQUIPMENT_SLOT.boots,
22 EQUIPMENT_SLOT.legs,
23 EQUIPMENT_SLOT.chest,
24 EQUIPMENT_SLOT.head,
25 EQUIPMENT_SLOT.offhand,
26 EQUIPMENT_SLOT.weapon
27]);
28
29export const DEFAULT_MAX_STACK = 99;
30
31export const ITEM_DEFINITIONS = Object.freeze({
32 [ItemId.paper]: Object.freeze({
33 itemId: ItemId.paper,
34 key: "paper",
35 displayName: "Paper",
36 description: "Blank paper. Later used to write letters.",
37 seedValue: 2,
38 stackable: true,
39 maxStackSize: DEFAULT_MAX_STACK,
40 uniqueInstance: false,
41 category: "document"
42 }),
43 [ItemId.apple]: Object.freeze({
44 itemId: ItemId.apple,
45 key: "apple",
46 displayName: "Apple",
47 description: "A placeholder fruit.",
48 seedValue: 1,
49 stackable: true,
50 maxStackSize: DEFAULT_MAX_STACK,
51 uniqueInstance: false,
52 category: "other"
53 }),
54 [ItemId.stick]: Object.freeze({
55 itemId: ItemId.stick,
56 key: "stick",
57 displayName: "Stick",
58 description: "A wooden stick. Can be wielded.",
59 seedValue: 3,
60 stackable: true,
61 maxStackSize: DEFAULT_MAX_STACK,
62 uniqueInstance: false,
63 category: "finished",
64 equipment: Object.freeze({
65 slot: EQUIPMENT_SLOT.weapon
66 })
67 }),
68 [ItemId.blankCheque]: Object.freeze({
69 itemId: ItemId.blankCheque,
70 key: "blank-cheque",
71 displayName: "Blank cheque",
72 description: "Placeholder bank paper. Filling comes with the bank.",
73 seedValue: 5,
74 stackable: true,
75 maxStackSize: DEFAULT_MAX_STACK,
76 uniqueInstance: false,
77 category: "document"
78 }),
79 [ItemId.clothShirt]: Object.freeze({
80 itemId: ItemId.clothShirt,
81 key: "cloth-shirt",
82 displayName: "Cloth shirt",
83 description: "A placeholder shirt worn on the chest.",
84 seedValue: 8,
85 stackable: false,
86 maxStackSize: 1,
87 uniqueInstance: false,
88 category: "finished",
89 equipment: Object.freeze({
90 slot: EQUIPMENT_SLOT.chest
91 })
92 })
93});
94
95export function itemDefinition (itemId)
96{
97 return ITEM_DEFINITIONS[itemId] ?? null;
98}
99
100export function itemDefaultState (def)
101{
102 return def?.defaultState ?? def?.key ?? "paper";
103}
104
105export function itemSpriteName (itemId)
106{
107 const def = itemDefinition(itemId);
108 if (!def)
109 { return spriteImageName("item", "paper", "paper"); }
110 return def.sprite ?? spriteImageName("item", def.key, itemDefaultState(def));
111}
112
113export function itemEquipSprite (itemId)
114{
115 const def = itemDefinition(itemId);
116 const equipment = def?.equipment;
117 if (!equipment)
118 { return null; }
119 return equipment.equipSprite
120 ?? equipment.overlaySpriteId
121 ?? equipImageName("item", def.key, itemDefaultState(def));
122}
123
124export function itemAssetPath (itemId, companion = null)
125{
126 const def = itemDefinition(itemId);
127 const key = def?.key ?? "paper";
128 const state = itemDefaultState(def ?? { key });
129 const suffix = companion ? `-${companion}` : "";
130 return `/assets/items/${key}/${state}${suffix}.png`;
131}
132
133export const STARTER_CURRENCY = 25;
134export const STARTER_ITEMS = Object.freeze([
135 Object.freeze({ itemId: ItemId.paper, quantity: 5 }),
136 Object.freeze({ itemId: ItemId.apple, quantity: 3 }),
137 Object.freeze({ itemId: ItemId.stick, quantity: 1 }),
138 Object.freeze({ itemId: ItemId.clothShirt, quantity: 1 })
139]);
shared/definitions/mobs.js added +39 −0
@@ -0,0 +1,39 @@
1 import { spriteImageName } from "./tileSprites.js";
2
3 export const MobId = Object.freeze({
4 deer: "deer"
5 });
6
7 export const MOB_DEFINITIONS = Object.freeze({
8 [MobId.deer]: Object.freeze({
9 mobTypeId: MobId.deer,
10 key: "deer",
11 displayName: "Deer",
12 persistent: false,
13 gait: "walk",
14 sex: "male",
15 health: 8
16 })
17 });
18
19 export function mobDefinition (mobTypeId)
20 {
21 return MOB_DEFINITIONS[mobTypeId] ?? null;
22 }
23
24 export function mobSpriteName (mobTypeId)
25 {
26 const def = mobDefinition(mobTypeId);
27 const key = def?.key ?? def?.mobTypeId ?? "deer";
28 return def?.sprite ?? spriteImageName("mob", key, key);
29 }
30
31 export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
32 {
33 return {
34 spawnerId,
35 mobTypeId,
36 maxAlive: 3,
37 spawnRangeTiles: 4
38 };
39 }
@@ -0,0 +1,39 @@
1import { spriteImageName } from "./tileSprites.js";
2
3export const MobId = Object.freeze({
4 deer: "deer"
5});
6
7export const MOB_DEFINITIONS = Object.freeze({
8 [MobId.deer]: Object.freeze({
9 mobTypeId: MobId.deer,
10 key: "deer",
11 displayName: "Deer",
12 persistent: false,
13 gait: "walk",
14 sex: "male",
15 health: 8
16 })
17});
18
19export function mobDefinition (mobTypeId)
20{
21 return MOB_DEFINITIONS[mobTypeId] ?? null;
22}
23
24export function mobSpriteName (mobTypeId)
25{
26 const def = mobDefinition(mobTypeId);
27 const key = def?.key ?? def?.mobTypeId ?? "deer";
28 return def?.sprite ?? spriteImageName("mob", key, key);
29}
30
31export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
32{
33 return {
34 spawnerId,
35 mobTypeId,
36 maxAlive: 3,
37 spawnRangeTiles: 4
38 };
39}
shared/definitions/tileSprites.js +78 −7
@@ -1,8 +1,69 @@
1 export function spriteImageName (layer, key, state)
2 {
3 return `${layer}:${key}:${state}`;
4 }
5
6 export function bloomImageName (layer, key, state)
7 {
8 return `${spriteImageName(layer, key, state)}:bloom`;
9 }
10
11 export function equipImageName (layer, key, state)
12 {
13 return `${spriteImageName(layer, key, state)}:equip`;
14 }
15
16 export function equipBloomImageName (layer, key, state)
17 {
18 return `${equipImageName(layer, key, state)}:bloom`;
19 }
20
21 /** Bloom companion for any registered image name (`item:stick:stick:equip` → `…:equip:bloom`). */
22 export function bloomCompanionName (imageName)
23 {
24 return `${imageName}:bloom`;
25 }
26
27 /**
28 * Companion suffixes peel from the right in fixed order.
29 * `torch-equip-bloom` → base torch, equip + bloom.
30 * `torch-bloom` → base torch, bloom.
31 * `stick-equip` → base stick, equip.
32 */
33 export function parseSpriteStem (stem)
34 {
35 let rest = String(stem ?? "");
36 let bloom = false;
37 let equip = false;
38 if (rest.endsWith("-bloom") && rest.length > "-bloom".length)
39 {
40 bloom = true;
41 rest = rest.slice(0, -"-bloom".length);
42 }
43 if (rest.endsWith("-equip") && rest.length > "-equip".length)
44 {
45 equip = true;
46 rest = rest.slice(0, -"-equip".length);
47 }
48 const companion = bloom || equip;
49 return {
50 base: companion ? rest : String(stem ?? ""),
51 companion,
52 bloom,
53 equip
54 };
55 }
56
57 export function isCompanionSpriteStem (stem)
58 {
59 return parseSpriteStem(stem).companion;
60 }
61
1 62 export function resolveState (states, requested)
2 63 {
3 64 if (!states?.length)
4 65 { return null; }
5 if (requested && states.includes(requested))
66 if (requested && !isCompanionSpriteStem(requested) && states.includes(requested))
6 67 { return requested; }
7 68 return states[0];
8 69 }
@@ -17,19 +78,29 @@ export function cycleState (states, current, direction)
17 78 return states[(index + step + states.length) % states.length];
18 79 }
19 80
20 export function spriteImageName (layer, key, state)
81 export function catalogGroup (catalog, layer)
21 82 {
22 return `${layer}:${key}:${state}`;
83 if (layer === "ground")
84 { return catalog?.grounds; }
85 if (layer === "block")
86 { return catalog?.blocks; }
87 if (layer === "item")
88 { return catalog?.items; }
89 if (layer === "mob")
90 { return catalog?.mobs; }
91 if (layer === "character")
92 { return catalog?.characters; }
93 return null;
23 94 }
24 95
25 96 export function statesForType (catalog, layer, key)
26 97 {
27 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
28 return group?.[key]?.states ?? [];
98 return (catalogGroup(catalog, layer)?.[key]?.states ?? [])
99 .filter((state) => !isCompanionSpriteStem(state));
29 100 }
30 101
31 102 export function defaultStateForType (catalog, layer, key)
32 103 {
33 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
34 return group?.[key]?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
104 const group = catalogGroup(catalog, layer)?.[key];
105 return group?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
35 106 }
@@ -1,8 +1,69 @@
1export function spriteImageName (layer, key, state)
2{
3 return `${layer}:${key}:${state}`;
4}
5
6export function bloomImageName (layer, key, state)
7{
8 return `${spriteImageName(layer, key, state)}:bloom`;
9}
10
11export function equipImageName (layer, key, state)
12{
13 return `${spriteImageName(layer, key, state)}:equip`;
14}
15
16export function equipBloomImageName (layer, key, state)
17{
18 return `${equipImageName(layer, key, state)}:bloom`;
19}
20
21/** Bloom companion for any registered image name (`item:stick:stick:equip` → `…:equip:bloom`). */
22export function bloomCompanionName (imageName)
23{
24 return `${imageName}:bloom`;
25}
26
27/**
28 * Companion suffixes peel from the right in fixed order.
29 * `torch-equip-bloom` → base torch, equip + bloom.
30 * `torch-bloom` → base torch, bloom.
31 * `stick-equip` → base stick, equip.
32 */
33export function parseSpriteStem (stem)
34{
35 let rest = String(stem ?? "");
36 let bloom = false;
37 let equip = false;
38 if (rest.endsWith("-bloom") && rest.length > "-bloom".length)
39 {
40 bloom = true;
41 rest = rest.slice(0, -"-bloom".length);
42 }
43 if (rest.endsWith("-equip") && rest.length > "-equip".length)
44 {
45 equip = true;
46 rest = rest.slice(0, -"-equip".length);
47 }
48 const companion = bloom || equip;
49 return {
50 base: companion ? rest : String(stem ?? ""),
51 companion,
52 bloom,
53 equip
54 };
55}
56
57export function isCompanionSpriteStem (stem)
58{
59 return parseSpriteStem(stem).companion;
60}
61
1export function resolveState (states, requested)
62export function resolveState (states, requested)
2{
63{
3 if (!states?.length)
64 if (!states?.length)
4 { return null; }
65 { return null; }
5 if (requested && states.includes(requested))
66 if (requested && !isCompanionSpriteStem(requested) && states.includes(requested))
6 { return requested; }
67 { return requested; }
7 return states[0];
68 return states[0];
8}
69}
@@ -17,19 +78,29 @@ export function cycleState (states, current, direction)
17 return states[(index + step + states.length) % states.length];
78 return states[(index + step + states.length) % states.length];
18}
79}
19
80
20export function spriteImageName (layer, key, state)
81export function catalogGroup (catalog, layer)
21{
82{
22 return `${layer}:${key}:${state}`;
83 if (layer === "ground")
84 { return catalog?.grounds; }
85 if (layer === "block")
86 { return catalog?.blocks; }
87 if (layer === "item")
88 { return catalog?.items; }
89 if (layer === "mob")
90 { return catalog?.mobs; }
91 if (layer === "character")
92 { return catalog?.characters; }
93 return null;
23}
94}
24
95
25export function statesForType (catalog, layer, key)
96export function statesForType (catalog, layer, key)
26{
97{
27 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
98 return (catalogGroup(catalog, layer)?.[key]?.states ?? [])
28 return group?.[key]?.states ?? [];
99 .filter((state) => !isCompanionSpriteStem(state));
29}
100}
30
101
31export function defaultStateForType (catalog, layer, key)
102export function defaultStateForType (catalog, layer, key)
32{
103{
33 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
104 const group = catalogGroup(catalog, layer)?.[key];
34 return group?.[key]?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
105 return group?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
35}
106}
shared/definitions/tiles.js +23 −1
@@ -5,7 +5,9 @@ export const GroundType = Object.freeze({
5 5
6 6 export const BlockType = Object.freeze({
7 7 stoneWall: 1,
8 torch: 2
8 torch: 2,
9 spawner: 3,
10 bank: 4
9 11 });
10 12
11 13 export const GROUND_DEFINITIONS = Object.freeze({
@@ -47,6 +49,26 @@ export const BLOCK_DEFINITIONS = Object.freeze({
47 49 frames: 1,
48 50 framesPerRow: 1,
49 51 animationSpeed: 0
52 }),
53 [BlockType.spawner]: Object.freeze({
54 id: BlockType.spawner,
55 key: "spawner",
56 displayName: "Spawner",
57 passable: false,
58 lightRangeTiles: 0,
59 frames: 1,
60 framesPerRow: 1,
61 animationSpeed: 0
62 }),
63 [BlockType.bank]: Object.freeze({
64 id: BlockType.bank,
65 key: "bank",
66 displayName: "Bank",
67 passable: false,
68 lightRangeTiles: 0,
69 frames: 1,
70 framesPerRow: 1,
71 animationSpeed: 0
50 72 })
51 73 });
52 74
@@ -5,7 +5,9 @@ export const GroundType = Object.freeze({
5
5
6export const BlockType = Object.freeze({
6export const BlockType = Object.freeze({
7 stoneWall: 1,
7 stoneWall: 1,
8 torch: 2
8 torch: 2,
9 spawner: 3,
10 bank: 4
9});
11});
10
12
11export const GROUND_DEFINITIONS = Object.freeze({
13export const GROUND_DEFINITIONS = Object.freeze({
@@ -47,6 +49,26 @@ export const BLOCK_DEFINITIONS = Object.freeze({
47 frames: 1,
49 frames: 1,
48 framesPerRow: 1,
50 framesPerRow: 1,
49 animationSpeed: 0
51 animationSpeed: 0
52 }),
53 [BlockType.spawner]: Object.freeze({
54 id: BlockType.spawner,
55 key: "spawner",
56 displayName: "Spawner",
57 passable: false,
58 lightRangeTiles: 0,
59 frames: 1,
60 framesPerRow: 1,
61 animationSpeed: 0
62 }),
63 [BlockType.bank]: Object.freeze({
64 id: BlockType.bank,
65 key: "bank",
66 displayName: "Bank",
67 passable: false,
68 lightRangeTiles: 0,
69 frames: 1,
70 framesPerRow: 1,
71 animationSpeed: 0
50 })
72 })
51});
73});
52
74
shared/definitions/worldSettings.js +125 −21
@@ -1,7 +1,7 @@
1 1 export const WORLD_SETTING_CATEGORIES = [
2 2 {
3 id: "movement",
4 label: "Movement",
3 id: "simulation",
4 label: "Simulation",
5 5 fields: [
6 6 {
7 7 key: "walkTilesPerSecond",
@@ -11,13 +11,7 @@ export const WORLD_SETTING_CATEGORIES = [
11 11 min: 0.25,
12 12 max: 20,
13 13 step: 0.25
14 }
15 ]
16 },
17 {
18 id: "simulation",
19 label: "Simulation",
20 fields: [
14 },
21 15 {
22 16 key: "simulationTickHz",
23 17 label: "Simulation tick (Hz)",
@@ -38,17 +32,99 @@ export const WORLD_SETTING_CATEGORIES = [
38 32 ]
39 33 },
40 34 {
41 id: "lighting",
42 label: "Lighting",
35 id: "graphics",
36 label: "Graphics",
43 37 fields: [
44 38 {
45 39 key: "nightDarkness",
46 40 label: "Night darkness",
47 hint: "How dark unlit tiles become at night. 0 is no extra darkening, 1 is fully black.",
41 hint: "Peak ambient darkening for unlit tiles at night (22–5). Daytime (8–16) stays 0 — use the editor Night preview slider (or save while editing this) to see the effect.",
42 type: "range",
43 min: 0,
44 max: 1,
45 step: 0.01,
46 previewNightHour: 23
47 },
48 {
49 key: "bloomThreshold",
50 label: "Bloom threshold",
51 hint: "Brightness above which bloom-layer pixels start glowing.",
48 52 type: "range",
49 53 min: 0,
50 54 max: 1,
51 55 step: 0.01
56 },
57 {
58 key: "bloomSoftKnee",
59 label: "Bloom soft knee",
60 hint: "Softens the threshold edge.",
61 type: "range",
62 min: 0,
63 max: 1,
64 step: 0.01
65 },
66 {
67 key: "bloomIntensity",
68 label: "Bloom intensity",
69 hint: "How strong the bloom glow is.",
70 type: "range",
71 min: 0,
72 max: 4,
73 step: 0.05
74 },
75 {
76 key: "bloomBlurSize",
77 label: "Bloom blur size",
78 hint: "Base blur kernel size for the bloom glow.",
79 type: "range",
80 min: 0.5,
81 max: 12,
82 step: 0.25
83 },
84 {
85 key: "bloomSaturation",
86 label: "Bloom saturation",
87 hint: "1 is neutral; higher values punch bloom chroma.",
88 type: "range",
89 min: 0,
90 max: 3,
91 step: 0.05
92 },
93 {
94 key: "bloomColorPreserve",
95 label: "Bloom colour preserve",
96 hint: "0–1 tint of bloom toward the source sprite hue.",
97 type: "range",
98 min: 0,
99 max: 1,
100 step: 0.01
101 },
102 {
103 key: "bloomDilate",
104 label: "Bloom dilate",
105 hint: "Expands tiny bright pixels before blur (texels). 0 disables.",
106 type: "range",
107 min: 0,
108 max: 12,
109 step: 0.25
110 },
111 {
112 key: "bloomScales",
113 label: "Bloom scales",
114 hint: "Number of horizontal/vertical blur scale pairs.",
115 type: "number",
116 min: 1,
117 max: 4,
118 step: 1
119 },
120 {
121 key: "bloomHalfRes",
122 label: "Bloom half-res",
123 hint: "1 runs dilate/blur at half resolution (cheaper). 0 keeps full resolution.",
124 type: "number",
125 min: 0,
126 max: 1,
127 step: 1
52 128 }
53 129 ]
54 130 },
@@ -81,17 +157,24 @@ export const WORLD_SETTING_CATEGORIES = [
81 157 ]
82 158 },
83 159 {
84 id: "economy",
85 label: "Economy & items",
160 id: "communication",
161 label: "Communication",
86 162 fields: [
87 163 {
88 key: "shopPriceLerpDurationMs",
89 label: "Shop price lerp (ms)",
90 hint: "How long shop prices take to move toward the last market sale.",
164 key: "chatMaxCharacters",
165 label: "Chat max characters",
166 hint: "Maximum length of a proximity chat line after trimming.",
91 167 type: "number",
92 min: 0,
93 step: 1000
94 },
168 min: 1,
169 max: 500,
170 step: 1
171 }
172 ]
173 },
174 {
175 id: "inventory",
176 label: "Inventory",
177 fields: [
95 178 {
96 179 key: "groundItemDespawnDurationMs",
97 180 label: "Ground item despawn (ms)",
@@ -101,6 +184,20 @@ export const WORLD_SETTING_CATEGORIES = [
101 184 step: 1000
102 185 }
103 186 ]
187 },
188 {
189 id: "economy",
190 label: "Economy",
191 fields: [
192 {
193 key: "shopPriceLerpDurationMs",
194 label: "Shop price lerp (ms)",
195 hint: "How long shop prices take to move toward the last market sale.",
196 type: "number",
197 min: 0,
198 step: 1000
199 }
200 ]
104 201 }
105 202 ];
106 203
@@ -131,6 +228,13 @@ export function coerceSettingValue (field, raw)
131 228 return next;
132 229 }
133 230
231 export function settingsValuesEqual (a, b)
232 {
233 if (typeof a === "number" && typeof b === "number")
234 { return Math.abs(a - b) < 1e-9; }
235 return a === b;
236 }
237
134 238 export function diffSettings (previous, next, fields = allSettingFields())
135 239 {
136 240 const bullets = [];
@@ -141,7 +245,7 @@ export function diffSettings (previous, next, fields = allSettingFields())
141 245 { continue; }
142 246 const from = previous[field.key];
143 247 const to = next[field.key];
144 if (from === to)
248 if (settingsValuesEqual(from, to))
145 249 { continue; }
146 250 changed[field.key] = to;
147 251 bullets.push(`${field.label} changed from ${formatSettingValue(from)} to ${formatSettingValue(to)}.`);
@@ -1,7 +1,7 @@
1export const WORLD_SETTING_CATEGORIES = [
1export const WORLD_SETTING_CATEGORIES = [
2 {
2 {
3 id: "movement",
3 id: "simulation",
4 label: "Movement",
4 label: "Simulation",
5 fields: [
5 fields: [
6 {
6 {
7 key: "walkTilesPerSecond",
7 key: "walkTilesPerSecond",
@@ -11,13 +11,7 @@ export const WORLD_SETTING_CATEGORIES = [
11 min: 0.25,
11 min: 0.25,
12 max: 20,
12 max: 20,
13 step: 0.25
13 step: 0.25
14 }
14 },
15 ]
16 },
17 {
18 id: "simulation",
19 label: "Simulation",
20 fields: [
21 {
15 {
22 key: "simulationTickHz",
16 key: "simulationTickHz",
23 label: "Simulation tick (Hz)",
17 label: "Simulation tick (Hz)",
@@ -38,17 +32,99 @@ export const WORLD_SETTING_CATEGORIES = [
38 ]
32 ]
39 },
33 },
40 {
34 {
41 id: "lighting",
35 id: "graphics",
42 label: "Lighting",
36 label: "Graphics",
43 fields: [
37 fields: [
44 {
38 {
45 key: "nightDarkness",
39 key: "nightDarkness",
46 label: "Night darkness",
40 label: "Night darkness",
47 hint: "How dark unlit tiles become at night. 0 is no extra darkening, 1 is fully black.",
41 hint: "Peak ambient darkening for unlit tiles at night (22–5). Daytime (8–16) stays 0 — use the editor Night preview slider (or save while editing this) to see the effect.",
42 type: "range",
43 min: 0,
44 max: 1,
45 step: 0.01,
46 previewNightHour: 23
47 },
48 {
49 key: "bloomThreshold",
50 label: "Bloom threshold",
51 hint: "Brightness above which bloom-layer pixels start glowing.",
48 type: "range",
52 type: "range",
49 min: 0,
53 min: 0,
50 max: 1,
54 max: 1,
51 step: 0.01
55 step: 0.01
56 },
57 {
58 key: "bloomSoftKnee",
59 label: "Bloom soft knee",
60 hint: "Softens the threshold edge.",
61 type: "range",
62 min: 0,
63 max: 1,
64 step: 0.01
65 },
66 {
67 key: "bloomIntensity",
68 label: "Bloom intensity",
69 hint: "How strong the bloom glow is.",
70 type: "range",
71 min: 0,
72 max: 4,
73 step: 0.05
74 },
75 {
76 key: "bloomBlurSize",
77 label: "Bloom blur size",
78 hint: "Base blur kernel size for the bloom glow.",
79 type: "range",
80 min: 0.5,
81 max: 12,
82 step: 0.25
83 },
84 {
85 key: "bloomSaturation",
86 label: "Bloom saturation",
87 hint: "1 is neutral; higher values punch bloom chroma.",
88 type: "range",
89 min: 0,
90 max: 3,
91 step: 0.05
92 },
93 {
94 key: "bloomColorPreserve",
95 label: "Bloom colour preserve",
96 hint: "0–1 tint of bloom toward the source sprite hue.",
97 type: "range",
98 min: 0,
99 max: 1,
100 step: 0.01
101 },
102 {
103 key: "bloomDilate",
104 label: "Bloom dilate",
105 hint: "Expands tiny bright pixels before blur (texels). 0 disables.",
106 type: "range",
107 min: 0,
108 max: 12,
109 step: 0.25
110 },
111 {
112 key: "bloomScales",
113 label: "Bloom scales",
114 hint: "Number of horizontal/vertical blur scale pairs.",
115 type: "number",
116 min: 1,
117 max: 4,
118 step: 1
119 },
120 {
121 key: "bloomHalfRes",
122 label: "Bloom half-res",
123 hint: "1 runs dilate/blur at half resolution (cheaper). 0 keeps full resolution.",
124 type: "number",
125 min: 0,
126 max: 1,
127 step: 1
52 }
128 }
53 ]
129 ]
54 },
130 },
@@ -81,17 +157,24 @@ export const WORLD_SETTING_CATEGORIES = [
81 ]
157 ]
82 },
158 },
83 {
159 {
84 id: "economy",
160 id: "communication",
85 label: "Economy & items",
161 label: "Communication",
86 fields: [
162 fields: [
87 {
163 {
88 key: "shopPriceLerpDurationMs",
164 key: "chatMaxCharacters",
89 label: "Shop price lerp (ms)",
165 label: "Chat max characters",
90 hint: "How long shop prices take to move toward the last market sale.",
166 hint: "Maximum length of a proximity chat line after trimming.",
91 type: "number",
167 type: "number",
92 min: 0,
168 min: 1,
93 step: 1000
169 max: 500,
94 },
170 step: 1
171 }
172 ]
173 },
174 {
175 id: "inventory",
176 label: "Inventory",
177 fields: [
95 {
178 {
96 key: "groundItemDespawnDurationMs",
179 key: "groundItemDespawnDurationMs",
97 label: "Ground item despawn (ms)",
180 label: "Ground item despawn (ms)",
@@ -101,6 +184,20 @@ export const WORLD_SETTING_CATEGORIES = [
101 step: 1000
184 step: 1000
102 }
185 }
103 ]
186 ]
187 },
188 {
189 id: "economy",
190 label: "Economy",
191 fields: [
192 {
193 key: "shopPriceLerpDurationMs",
194 label: "Shop price lerp (ms)",
195 hint: "How long shop prices take to move toward the last market sale.",
196 type: "number",
197 min: 0,
198 step: 1000
199 }
200 ]
104 }
201 }
105];
202];
106
203
@@ -131,6 +228,13 @@ export function coerceSettingValue (field, raw)
131 return next;
228 return next;
132}
229}
133
230
231export function settingsValuesEqual (a, b)
232{
233 if (typeof a === "number" && typeof b === "number")
234 { return Math.abs(a - b) < 1e-9; }
235 return a === b;
236}
237
134export function diffSettings (previous, next, fields = allSettingFields())
238export function diffSettings (previous, next, fields = allSettingFields())
135{
239{
136 const bullets = [];
240 const bullets = [];
@@ -141,7 +245,7 @@ export function diffSettings (previous, next, fields = allSettingFields())
141 { continue; }
245 { continue; }
142 const from = previous[field.key];
246 const from = previous[field.key];
143 const to = next[field.key];
247 const to = next[field.key];
144 if (from === to)
248 if (settingsValuesEqual(from, to))
145 { continue; }
249 { continue; }
146 changed[field.key] = to;
250 changed[field.key] = to;
147 bullets.push(`${field.label} changed from ${formatSettingValue(from)} to ${formatSettingValue(to)}.`);
251 bullets.push(`${field.label} changed from ${formatSettingValue(from)} to ${formatSettingValue(to)}.`);
shared/items/inventory.js added +109 −0
@@ -0,0 +1,109 @@
1 export const INVENTORY_SLOTS = 32;
2 export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
3
4 export function emptySlots (count = INVENTORY_SLOTS)
5 {
6 return Array.from({ length: count }, () => null);
7 }
8
9 export function emptyEquipment ()
10 {
11 const slots = {};
12 for (const slot of EQUIPMENT_SLOTS)
13 { slots[slot] = null; }
14 return { slots };
15 }
16
17 export function cloneStack (stack)
18 {
19 return stack ? structuredClone(stack) : null;
20 }
21
22 export function stacksMatch (left, right)
23 {
24 if (!left || !right)
25 { return false; }
26 if (left.itemId !== right.itemId)
27 { return false; }
28 return JSON.stringify(left.origin ?? null) === JSON.stringify(right.origin ?? null)
29 && JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
30 }
31
32 export function insertStack (slots, stack, definition)
33 {
34 if (!stack || stack.quantity <= 0)
35 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
36 const next = slots.map(cloneStack);
37 let remaining = stack.quantity;
38 if (definition.stackable && !definition.uniqueInstance)
39 {
40 for (const slot of next)
41 {
42 if (!stacksMatch(slot, stack))
43 { continue; }
44 const space = (definition.maxStackSize ?? 99) - slot.quantity;
45 if (space <= 0)
46 { continue; }
47 const add = Math.min(space, remaining);
48 slot.quantity += add;
49 remaining -= add;
50 if (remaining === 0)
51 { return { ok: true, slots: next, remainder: 0 }; }
52 }
53 }
54 for (let i = 0; i < next.length; i++)
55 {
56 if (next[i])
57 { continue; }
58 const amount = definition.stackable && !definition.uniqueInstance
59 ? Math.min(remaining, definition.maxStackSize ?? 99)
60 : 1;
61 next[i] = {
62 itemId: stack.itemId,
63 quantity: amount,
64 origin: stack.origin ?? null,
65 instance: stack.instance ?? null
66 };
67 remaining -= amount;
68 if (remaining === 0)
69 { return { ok: true, slots: next, remainder: 0 }; }
70 if (!definition.stackable || definition.uniqueInstance)
71 { break; }
72 }
73 return { ok: false, slots, remainder: remaining };
74 }
75
76 export function takeFromSlot (slots, slotIndex, quantity = null)
77 {
78 const next = slots.map(cloneStack);
79 const slot = next[slotIndex];
80 if (!slot)
81 { return { ok: false, slots, taken: null }; }
82 const amount = quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, quantity | 0));
83 if (amount <= 0)
84 { return { ok: false, slots, taken: null }; }
85 const taken = { ...cloneStack(slot), quantity: amount };
86 if (amount >= slot.quantity)
87 { next[slotIndex] = null; }
88 else
89 { slot.quantity -= amount; }
90 return { ok: true, slots: next, taken };
91 }
92
93 export function publicSlots (slots)
94 {
95 return (slots ?? emptySlots()).map((slot) => slot ? {
96 itemId: slot.itemId,
97 quantity: slot.quantity,
98 origin: slot.origin ?? null,
99 instance: slot.instance ?? null
100 } : null);
101 }
102
103 export function publicEquipment (equipment)
104 {
105 const slots = {};
106 for (const slot of EQUIPMENT_SLOTS)
107 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
108 return { slots };
109 }
@@ -0,0 +1,109 @@
1export const INVENTORY_SLOTS = 32;
2export const EQUIPMENT_SLOTS = Object.freeze(["head", "chest", "legs", "boots", "weapon", "offhand"]);
3
4export function emptySlots (count = INVENTORY_SLOTS)
5{
6 return Array.from({ length: count }, () => null);
7}
8
9export function emptyEquipment ()
10{
11 const slots = {};
12 for (const slot of EQUIPMENT_SLOTS)
13 { slots[slot] = null; }
14 return { slots };
15}
16
17export function cloneStack (stack)
18{
19 return stack ? structuredClone(stack) : null;
20}
21
22export function stacksMatch (left, right)
23{
24 if (!left || !right)
25 { return false; }
26 if (left.itemId !== right.itemId)
27 { return false; }
28 return JSON.stringify(left.origin ?? null) === JSON.stringify(right.origin ?? null)
29 && JSON.stringify(left.instance ?? null) === JSON.stringify(right.instance ?? null);
30}
31
32export function insertStack (slots, stack, definition)
33{
34 if (!stack || stack.quantity <= 0)
35 { return { ok: true, slots: slots.map(cloneStack), remainder: 0 }; }
36 const next = slots.map(cloneStack);
37 let remaining = stack.quantity;
38 if (definition.stackable && !definition.uniqueInstance)
39 {
40 for (const slot of next)
41 {
42 if (!stacksMatch(slot, stack))
43 { continue; }
44 const space = (definition.maxStackSize ?? 99) - slot.quantity;
45 if (space <= 0)
46 { continue; }
47 const add = Math.min(space, remaining);
48 slot.quantity += add;
49 remaining -= add;
50 if (remaining === 0)
51 { return { ok: true, slots: next, remainder: 0 }; }
52 }
53 }
54 for (let i = 0; i < next.length; i++)
55 {
56 if (next[i])
57 { continue; }
58 const amount = definition.stackable && !definition.uniqueInstance
59 ? Math.min(remaining, definition.maxStackSize ?? 99)
60 : 1;
61 next[i] = {
62 itemId: stack.itemId,
63 quantity: amount,
64 origin: stack.origin ?? null,
65 instance: stack.instance ?? null
66 };
67 remaining -= amount;
68 if (remaining === 0)
69 { return { ok: true, slots: next, remainder: 0 }; }
70 if (!definition.stackable || definition.uniqueInstance)
71 { break; }
72 }
73 return { ok: false, slots, remainder: remaining };
74}
75
76export function takeFromSlot (slots, slotIndex, quantity = null)
77{
78 const next = slots.map(cloneStack);
79 const slot = next[slotIndex];
80 if (!slot)
81 { return { ok: false, slots, taken: null }; }
82 const amount = quantity == null ? slot.quantity : Math.min(slot.quantity, Math.max(1, quantity | 0));
83 if (amount <= 0)
84 { return { ok: false, slots, taken: null }; }
85 const taken = { ...cloneStack(slot), quantity: amount };
86 if (amount >= slot.quantity)
87 { next[slotIndex] = null; }
88 else
89 { slot.quantity -= amount; }
90 return { ok: true, slots: next, taken };
91}
92
93export function publicSlots (slots)
94{
95 return (slots ?? emptySlots()).map((slot) => slot ? {
96 itemId: slot.itemId,
97 quantity: slot.quantity,
98 origin: slot.origin ?? null,
99 instance: slot.instance ?? null
100 } : null);
101}
102
103export function publicEquipment (equipment)
104{
105 const slots = {};
106 for (const slot of EQUIPMENT_SLOTS)
107 { slots[slot] = equipment?.slots?.[slot] ? cloneStack(equipment.slots[slot]) : null; }
108 return { slots };
109}
shared/protocol/constants.js +43 −2
@@ -4,6 +4,21 @@ export const SPRITE_SIZE_PX = 16;
4 4 export const PIVOT_FROM_BOTTOM_PX = 8;
5 5 export const VISIBLE_CHUNK_RADIUS = 1;
6 6
7 export const DEFAULT_CHUNK_LOADER = Object.freeze({
8 simulationRadiusChunks: 1,
9 regionLoadRadius: 1
10 });
11
12 export const CHUNK_RUNTIME_STATE = Object.freeze({
13 dormant: "dormant",
14 simulating: "simulating"
15 });
16
17 export const REGION_RUNTIME_STATE = Object.freeze({
18 unloaded: "unloaded",
19 resident: "resident"
20 });
21
7 22 export const WORLD_YEAR_OFFSET = 1200;
8 23
9 24 export const DEFAULT_WORLD_SETTINGS = Object.freeze({
@@ -14,7 +29,17 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
14 29 regionUnloadGracePeriodMs: 30 * 1000,
15 30 defaultGroundTypeId: 1,
16 31 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
17 nightDarkness: 0.72
32 nightDarkness: 0.72,
33 chatMaxCharacters: 100,
34 bloomThreshold: 0.35,
35 bloomSoftKnee: 0.3,
36 bloomIntensity: 1.35,
37 bloomBlurSize: 3,
38 bloomSaturation: 1.15,
39 bloomColorPreserve: 0.35,
40 bloomDilate: 2,
41 bloomScales: 2,
42 bloomHalfRes: 1
18 43 });
19 44
20 45 export const GAIT = Object.freeze({
@@ -43,6 +68,7 @@ export const MessageType = Object.freeze({
43 68 chunkSnapshot: "CHUNK_SNAPSHOT",
44 69 chunkDelta: "CHUNK_DELTA",
45 70 unsubscribeChunk: "UNSUBSCRIBE_CHUNK",
71 entitySpawn: "ENTITY_SPAWN",
46 72 entityMove: "ENTITY_MOVE",
47 73 entityDespawn: "ENTITY_DESPAWN",
48 74 worldStatus: "WORLD_STATUS",
@@ -57,6 +83,21 @@ export const MessageType = Object.freeze({
57 83 friendAccept: "FRIEND_ACCEPT",
58 84 friendDecline: "FRIEND_DECLINE",
59 85 friendRemove: "FRIEND_REMOVE",
60 friends: "FRIENDS"
86 friends: "FRIENDS",
87 chatSay: "CHAT_SAY",
88 chatBubble: "CHAT_BUBBLE",
89 dropItem: "DROP_ITEM",
90 pickupItem: "PICKUP_ITEM",
91 equipItem: "EQUIP_ITEM",
92 unequipItem: "UNEQUIP_ITEM",
93 inventory: "INVENTORY",
94 groundItemAppear: "GROUND_ITEM_APPEAR",
95 groundItemDespawn: "GROUND_ITEM_DESPAWN",
96 entityAppearance: "ENTITY_APPEARANCE",
97 openBank: "OPEN_BANK",
98 bankSnapshot: "BANK_SNAPSHOT",
99 bankDeposit: "BANK_DEPOSIT",
100 bankWithdraw: "BANK_WITHDRAW",
101 claimInheritance: "CLAIM_INHERITANCE"
61 102 });
62 103
@@ -4,6 +4,21 @@ export const SPRITE_SIZE_PX = 16;
4export const PIVOT_FROM_BOTTOM_PX = 8;
4export const PIVOT_FROM_BOTTOM_PX = 8;
5export const VISIBLE_CHUNK_RADIUS = 1;
5export const VISIBLE_CHUNK_RADIUS = 1;
6
6
7export const DEFAULT_CHUNK_LOADER = Object.freeze({
8 simulationRadiusChunks: 1,
9 regionLoadRadius: 1
10});
11
12export const CHUNK_RUNTIME_STATE = Object.freeze({
13 dormant: "dormant",
14 simulating: "simulating"
15});
16
17export const REGION_RUNTIME_STATE = Object.freeze({
18 unloaded: "unloaded",
19 resident: "resident"
20});
21
7export const WORLD_YEAR_OFFSET = 1200;
22export const WORLD_YEAR_OFFSET = 1200;
8
23
9export const DEFAULT_WORLD_SETTINGS = Object.freeze({
24export const DEFAULT_WORLD_SETTINGS = Object.freeze({
@@ -14,7 +29,17 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
14 regionUnloadGracePeriodMs: 30 * 1000,
29 regionUnloadGracePeriodMs: 30 * 1000,
15 defaultGroundTypeId: 1,
30 defaultGroundTypeId: 1,
16 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
31 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
17 nightDarkness: 0.72
32 nightDarkness: 0.72,
33 chatMaxCharacters: 100,
34 bloomThreshold: 0.35,
35 bloomSoftKnee: 0.3,
36 bloomIntensity: 1.35,
37 bloomBlurSize: 3,
38 bloomSaturation: 1.15,
39 bloomColorPreserve: 0.35,
40 bloomDilate: 2,
41 bloomScales: 2,
42 bloomHalfRes: 1
18});
43});
19
44
20export const GAIT = Object.freeze({
45export const GAIT = Object.freeze({
@@ -43,6 +68,7 @@ export const MessageType = Object.freeze({
43 chunkSnapshot: "CHUNK_SNAPSHOT",
68 chunkSnapshot: "CHUNK_SNAPSHOT",
44 chunkDelta: "CHUNK_DELTA",
69 chunkDelta: "CHUNK_DELTA",
45 unsubscribeChunk: "UNSUBSCRIBE_CHUNK",
70 unsubscribeChunk: "UNSUBSCRIBE_CHUNK",
71 entitySpawn: "ENTITY_SPAWN",
46 entityMove: "ENTITY_MOVE",
72 entityMove: "ENTITY_MOVE",
47 entityDespawn: "ENTITY_DESPAWN",
73 entityDespawn: "ENTITY_DESPAWN",
48 worldStatus: "WORLD_STATUS",
74 worldStatus: "WORLD_STATUS",
@@ -57,6 +83,21 @@ export const MessageType = Object.freeze({
57 friendAccept: "FRIEND_ACCEPT",
83 friendAccept: "FRIEND_ACCEPT",
58 friendDecline: "FRIEND_DECLINE",
84 friendDecline: "FRIEND_DECLINE",
59 friendRemove: "FRIEND_REMOVE",
85 friendRemove: "FRIEND_REMOVE",
60 friends: "FRIENDS"
86 friends: "FRIENDS",
87 chatSay: "CHAT_SAY",
88 chatBubble: "CHAT_BUBBLE",
89 dropItem: "DROP_ITEM",
90 pickupItem: "PICKUP_ITEM",
91 equipItem: "EQUIP_ITEM",
92 unequipItem: "UNEQUIP_ITEM",
93 inventory: "INVENTORY",
94 groundItemAppear: "GROUND_ITEM_APPEAR",
95 groundItemDespawn: "GROUND_ITEM_DESPAWN",
96 entityAppearance: "ENTITY_APPEARANCE",
97 openBank: "OPEN_BANK",
98 bankSnapshot: "BANK_SNAPSHOT",
99 bankDeposit: "BANK_DEPOSIT",
100 bankWithdraw: "BANK_WITHDRAW",
101 claimInheritance: "CLAIM_INHERITANCE"
61});
102});
62
103
shared/speech/proximity.js added +42 −0
@@ -0,0 +1,42 @@
1 import { CHUNK_SIZE } from "../protocol/constants.js";
2
3 export function speechReadability (distanceTiles, chunkSize = CHUNK_SIZE)
4 {
5 const dropStart = chunkSize * 0.5;
6 const silent = chunkSize;
7 if (distanceTiles <= dropStart)
8 { return 1; }
9 if (distanceTiles >= silent)
10 { return 0; }
11 return (silent - distanceTiles) / (silent - dropStart);
12 }
13
14 export function obscureSpeech (text, readability, seed = 1)
15 {
16 if (readability >= 1)
17 { return text; }
18 if (readability <= 0)
19 { return ""; }
20
21 let rng = seed >>> 0 || 1;
22 let result = "";
23 for (const char of text)
24 {
25 rng = stepRng(rng);
26 if (isStableSpeechChar(char) || rng / 0x100000000 <= readability)
27 { result += char; }
28 else
29 { result += "."; }
30 }
31 return result;
32 }
33
34 function isStableSpeechChar (char)
35 {
36 return !/[\p{L}\p{N}]/u.test(char);
37 }
38
39 function stepRng (value)
40 {
41 return (Math.imul(value, 1664525) + 1013904223) >>> 0;
42 }
@@ -0,0 +1,42 @@
1import { CHUNK_SIZE } from "../protocol/constants.js";
2
3export function speechReadability (distanceTiles, chunkSize = CHUNK_SIZE)
4{
5 const dropStart = chunkSize * 0.5;
6 const silent = chunkSize;
7 if (distanceTiles <= dropStart)
8 { return 1; }
9 if (distanceTiles >= silent)
10 { return 0; }
11 return (silent - distanceTiles) / (silent - dropStart);
12}
13
14export function obscureSpeech (text, readability, seed = 1)
15{
16 if (readability >= 1)
17 { return text; }
18 if (readability <= 0)
19 { return ""; }
20
21 let rng = seed >>> 0 || 1;
22 let result = "";
23 for (const char of text)
24 {
25 rng = stepRng(rng);
26 if (isStableSpeechChar(char) || rng / 0x100000000 <= readability)
27 { result += char; }
28 else
29 { result += "."; }
30 }
31 return result;
32}
33
34function isStableSpeechChar (char)
35{
36 return !/[\p{L}\p{N}]/u.test(char);
37}
38
39function stepRng (value)
40{
41 return (Math.imul(value, 1664525) + 1013904223) >>> 0;
42}
tile_mmo_server_technical_design_v0.6.md +114 −32
@@ -1,13 +1,13 @@
1 1 ---
2 2 title: Tile MMO Server Technical Design
3 version: 0.15
3 version: 0.20
4 4 status: proposed
5 5 format: living-design-document
6 6 ---
7 7
8 8 # Tile MMO Server Technical Design
9 9
10 **Version:** 0.15
10 **Version:** 0.20
11 11 **Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12 12 **Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13 13
@@ -538,16 +538,23 @@ they are regenerated on save (section 8.6).
538 538
539 539 Global gameplay constants live in authored `world_live_settings`. They
540 540 are **not** per-mob, **not** client-authored, and **not** pinned to a
541 map revision. Admins edit them from a large categorised modal in the
542 world-editor UI. The modal fills most of the screen: the left pane is a
543 scrollable form grouped by category; the right pane is a settings edit
544 log (which option changed, from/to, which admin, date/time).
541 map revision. Admins edit them from a large tabbed modal in the
542 world-editor UI. The modal fills most of the screen: the left pane has
543 category tabs (Simulation, Graphics, World, Characters, Communication,
544 Inventory, Economy) with one panel visible at a time; the right pane is
545 a settings edit log (which option changed, from/to, which admin,
546 date/time).
545 547
546 548 Rows the admin has edited in this session are marked with a distinct
547 549 background. Save writes **only** those dirty fields. The running
548 550 process applies them immediately (walk cadence, tick rate, night
549 darkness, and other consumed timers). Chunk **Apply now** is not
550 required.
551 darkness, bloom post-chain knobs, and other consumed timers). Chunk
552 **Apply now** is not required.
553
554 `nightDarkness` only darkens during dusk/night/dawn (peak hours 22–5).
555 Daytime hours 8–16 stay fully bright on the client. Editing night
556 darkness in the editor snaps the Night preview slider to night so the
557 change is visible immediately.
551 558
552 559 Minimum initial settings and defaults:
553 560
@@ -561,6 +568,16 @@ WorldSettings
561 568 - defaultGroundTypeId // grass used for never-edited chunks
562 569 - characterDeletionDelay // default 24 hours
563 570 - nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
571 - chatMaxCharacters // default 100; trimmed proximity-chat line length
572 - bloomThreshold // default 0.35; Framework bloom bright-pass
573 - bloomSoftKnee // default 0.3
574 - bloomIntensity // default 1.35
575 - bloomBlurSize // default 3
576 - bloomSaturation // default 1.15
577 - bloomColorPreserve // default 0.35
578 - bloomDilate // default 2; 0 disables dilate
579 - bloomScales // default 2; H/V blur scale pairs
580 - bloomHalfRes // default 1; 1 = half-res blur, 0 = full-res
564 581 ```
565 582
566 583 Running is always **double** walking speed. It is not a separate per-entity
@@ -798,9 +815,16 @@ raw region count.
798 815
799 816 ## 11.4 Node.js implementation
800 817
801 Start with Node.js worker_threads for simulation workers. Keep mutable
802 ECS worlds isolated per worker and use message passing between them. Do
803 not begin with a shared mutable ECS in SharedArrayBuffer.
818 Simulation workers keep mutable ECS worlds isolated and talk only through
819 structured-cloneable messages. The default runtime is in-process workers
820 with clone-on-boundary (so the protocol is real even without OS threads).
821 `SIMULATION_WORKER_MODE=thread` runs the same `WorkerWorld` inside
822 `worker_threads`. Do not share a mutable ECS in SharedArrayBuffer.
823
824 A coordinator on the gateway thread owns region assignment (neighbour-sticky,
825 least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange,
826 and SQLite. `SIMULATION_WORKERS` defaults to 2. Dynamic load rebalance is
827 later.
804 828
805 829 # 12. Cross-worker communication
806 830
@@ -1580,13 +1604,25 @@ and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1580 1604 tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1581 1605 stands on the same feet line and extends upward.
1582 1606
1583 Each **ground** and **block** type has its own asset folder
1584 (`client/assets/grounds/<key>/`, `client/assets/blocks/<key>/`). Every
1585 PNG in that folder is a **visual state**. States are not listed in the
1586 type definition: the first filename in alphabetical (numeric) order is
1587 the default. A later gameplay system may set a named state on a placed
1588 tile (for example a door `closed` / `open`); unknown names fall back to
1589 the default. The editor mouse wheel cycles these states.
1607 Each sprite kind — **grounds**, **blocks**, **items**, **mobs**, and
1608 **characters** — uses its own per-type asset folder
1609 (`client/assets/<kind>/<key>/`). Every base PNG in that folder is a
1610 **visual state**. Filenames ending in `-bloom`, `-equip`, or combinations
1611 such as `-equip-bloom` are **companions**, not states: `torch-bloom.png`
1612 is the bloom overlay for state `torch`, `{state}-equip.png` is the worn
1613 equipment overlay for that state, and `{state}-equip-bloom.png` is the
1614 bloom overlay for that equip sprite. Companions always live in the same
1615 folder as their base state and are never listed as placeable editor
1616 states. Image names follow `layer:key:state` (plus `:equip` / `:bloom`
1617 suffixes). States are not listed in the type definition: the first base
1618 filename in alphabetical (numeric) order is the default. A later gameplay
1619 system may set a named state on a placed tile (for example a door
1620 `closed` / `open`); unknown names fall back to the default. The editor
1621 mouse wheel cycles these states.
1622
1623 Bloom companions are drawn on a separate Framework **bloom** render
1624 layer that uses `Shader.getBloomPostChain(...)`. Bloom post-chain
1625 parameters are live world settings under the Graphics tab.
1590 1626
1591 1627 Each type definition may set sprite-sheet playback for every state PNG:
1592 1628
@@ -1939,6 +1975,23 @@ Ordinary chat is spatial. A player speaks from a world position and only nearby
1939 1975 players receive a useful version of the message. Legibility decreases as the
1940 1976 recipient gets farther from the speaker.
1941 1977
1978 Readability uses Euclidean tile distance against the 16-tile chunk size:
1979
1980 ```text
1981 distance <= 8 tiles // half a chunk: full plaintext
1982 8 < distance < 16 // linear falloff, e.g. 12 tiles → 50% readability
1983 distance >= 16 tiles // a full chunk: 0% readability, no bubble
1984 ```
1985
1986 The speaker always receives their own trimmed plaintext. Other recipients receive
1987 a server-obscured copy: letters and digits may become `.` with probability
1988 `1 - readability`; spaces and punctuation stay. At 0% readability the server
1989 sends nothing, so the client never draws a bubble.
1990
1991 Enter opens a bottom-of-screen line (max `chatMaxCharacters`, default 100).
1992 Enter again trims and sends `CHAT_SAY`. Escape cancels. The client shows
1993 `CHAT_BUBBLE` above the speaker.
1994
1942 1995 For example:
1943 1996
1944 1997 ```text
@@ -1948,8 +2001,6 @@ Very far: I'...re..ly..ar.aw.y
1948 2001 Beyond range: no message
1949 2002 ```
1950 2003
1951 The exact distance bands/function are configurable game rules.
1952
1953 2004 Crucially, degradation is performed **server-side**. The server must not send the
1954 2005 full plaintext to a distant client and merely ask that client to obscure it,
1955 2006 because a modified client could then recover speech it was not supposed to
@@ -2828,8 +2879,8 @@ players; they do not buy player goods unless a later iteration adds that.
2828 2879
2829 2880 - ChunkLoader reference counting and sleeping/unloading.
2830 2881
2831 - Single simulation worker behind the same worker interface planned for
2832 later scaling.
2882 - Isolated simulation workers behind a clone-on-boundary protocol
2883 (in-process default; `worker_threads` optional).
2833 2884
2834 2885 - world.sqlite read path and state.sqlite persistence service.
2835 2886
@@ -2887,17 +2938,16 @@ players; they do not buy player goods unless a later iteration adds that.
2887 2938
2888 2939 ## Phase 3 — Multi-worker world
2889 2940
2890 - Multiple worker_threads simulation workers.
2891
2892 - Region coordinator and dynamic region ownership.
2941 - Multiple isolated simulation workers and neighbour-sticky region ownership
2942 (shipped); dynamic load rebalance remains.
2893 2943
2894 - Cross-worker entity transfers.
2944 - Cross-worker entity transfers (shipped).
2895 2945
2896 - Border ghosts and remote actions.
2946 - Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
2897 2947
2898 - Gateway subscriptions spanning multiple workers.
2948 - Gateway subscriptions spanning multiple workers (shipped).
2899 2949
2900 - Load metrics and neighbour-aware region balancing.
2950 - Load metrics and neighbour-aware region balancing remain.
2901 2951
2902 2952 ## Phase 4 — World depth, social systems and economy
2903 2953
@@ -3328,9 +3378,6 @@ specified explicitly:
3328 3378
3329 3379 - Future scripting language syntax, event model and resource quotas.
3330 3380
3331 - Exact proximity-chat distance curve, maximum range and character degradation
3332 algorithm.
3333
3334 3381 - Group naming/roles, membership limits and whether group-wide letter sending
3335 3382 is offered as an addressing convenience that still dispatches one pigeon and
3336 3383 consumes one paper/letter per recipient.
@@ -3402,6 +3449,41 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3402 3449
3403 3450 # 34. Version history
3404 3451
3452 ## 0.19
3453
3454 - Playable item basis: 32-slot inventory, equipment overlays, carried coins,
3455 ground drops (10-minute player drops, pickup on the tile), bank vaults,
3456 and account inheritance on character delete. Spawner and bank blocks can
3457 be painted in the editor; spawners produce placeholder deer up to
3458 `maxAlive`. Missing art is temporary 16×16 PNGs under `client/assets/`
3459 so real sprites can drop in later by replacing those files.
3460
3461 ## 0.18
3462
3463 - Server ECS uses compact worker-local `EntityHandle`s (recycled free list)
3464 alongside global `EntityId`s for storage, networking and transfer. `Path`
3465 is a separate component from `Movement`; players carry `NetworkIdentity`
3466 instead of putting `sessionId` on `character`. Nearby clients get
3467 `ENTITY_SPAWN` / compact `ENTITY_MOVE` (tile + gait) / `ENTITY_DESPAWN`
3468 rather than appearance-heavy moves or extra snapshots.
3469
3470 ## 0.17
3471
3472 - Region workers own ECS worlds behind a clone-on-boundary protocol
3473 (optional `worker_threads`). ChunkLoader reference counts keep 3×3
3474 chunks simulating and 3×3 regions resident; other resident chunks stay
3475 dormant. Regions unload after the grace period and persist flagged
3476 entities. Crossing a foreign region transfers the only authoritative
3477 copy; ghosts cover border occupancy; client snapshots may span workers.
3478
3479 ## 0.16
3480
3481 - Proximity chat: Enter opens a bottom input (max `chatMaxCharacters`,
3482 default 100). Enter sends a trimmed line; the speaker always sees their
3483 own text. Other players get a server-obscured bubble (full until 8
3484 tiles, linear to silent at 16 tiles). At 0% readability no bubble is
3485 sent. Walk/run `R` is ignored while the chat line is open.
3486
3405 3487 ## 0.15
3406 3488
3407 3489 - Hovering another player shows their first name. Clicking them opens an
@@ -1,13 +1,13 @@
1---
1---
2title: Tile MMO Server Technical Design
2title: Tile MMO Server Technical Design
3version: 0.15
3version: 0.20
4status: proposed
4status: proposed
5format: living-design-document
5format: living-design-document
6---
6---
7
7
8# Tile MMO Server Technical Design
8# Tile MMO Server Technical Design
9
9
10**Version:** 0.15
10**Version:** 0.20
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
13
@@ -538,16 +538,23 @@ they are regenerated on save (section 8.6).
538
538
539Global gameplay constants live in authored `world_live_settings`. They
539Global gameplay constants live in authored `world_live_settings`. They
540are **not** per-mob, **not** client-authored, and **not** pinned to a
540are **not** per-mob, **not** client-authored, and **not** pinned to a
541map revision. Admins edit them from a large categorised modal in the
541map revision. Admins edit them from a large tabbed modal in the
542world-editor UI. The modal fills most of the screen: the left pane is a
542world-editor UI. The modal fills most of the screen: the left pane has
543scrollable form grouped by category; the right pane is a settings edit
543category tabs (Simulation, Graphics, World, Characters, Communication,
544log (which option changed, from/to, which admin, date/time).
544Inventory, Economy) with one panel visible at a time; the right pane is
545a settings edit log (which option changed, from/to, which admin,
546date/time).
545
547
546Rows the admin has edited in this session are marked with a distinct
548Rows the admin has edited in this session are marked with a distinct
547background. Save writes **only** those dirty fields. The running
549background. Save writes **only** those dirty fields. The running
548process applies them immediately (walk cadence, tick rate, night
550process applies them immediately (walk cadence, tick rate, night
549darkness, and other consumed timers). Chunk **Apply now** is not
551darkness, bloom post-chain knobs, and other consumed timers). Chunk
550required.
552**Apply now** is not required.
553
554`nightDarkness` only darkens during dusk/night/dawn (peak hours 22–5).
555Daytime hours 8–16 stay fully bright on the client. Editing night
556darkness in the editor snaps the Night preview slider to night so the
557change is visible immediately.
551
558
552Minimum initial settings and defaults:
559Minimum initial settings and defaults:
553
560
@@ -561,6 +568,16 @@ WorldSettings
561- defaultGroundTypeId // grass used for never-edited chunks
568- defaultGroundTypeId // grass used for never-edited chunks
562- characterDeletionDelay // default 24 hours
569- characterDeletionDelay // default 24 hours
563- nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
570- nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
571- chatMaxCharacters // default 100; trimmed proximity-chat line length
572- bloomThreshold // default 0.35; Framework bloom bright-pass
573- bloomSoftKnee // default 0.3
574- bloomIntensity // default 1.35
575- bloomBlurSize // default 3
576- bloomSaturation // default 1.15
577- bloomColorPreserve // default 0.35
578- bloomDilate // default 2; 0 disables dilate
579- bloomScales // default 2; H/V blur scale pairs
580- bloomHalfRes // default 1; 1 = half-res blur, 0 = full-res
564```
581```
565
582
566Running is always **double** walking speed. It is not a separate per-entity
583Running is always **double** walking speed. It is not a separate per-entity
@@ -798,9 +815,16 @@ raw region count.
798
815
799## 11.4 Node.js implementation
816## 11.4 Node.js implementation
800
817
801Start with Node.js worker_threads for simulation workers. Keep mutable
818Simulation workers keep mutable ECS worlds isolated and talk only through
802ECS worlds isolated per worker and use message passing between them. Do
819structured-cloneable messages. The default runtime is in-process workers
803not begin with a shared mutable ECS in SharedArrayBuffer.
820with clone-on-boundary (so the protocol is real even without OS threads).
821`SIMULATION_WORKER_MODE=thread` runs the same `WorkerWorld` inside
822`worker_threads`. Do not share a mutable ECS in SharedArrayBuffer.
823
824A coordinator on the gateway thread owns region assignment (neighbour-sticky,
825least-loaded tie-break), global EntityIds, transfer handoff, ghost exchange,
826and SQLite. `SIMULATION_WORKERS` defaults to 2. Dynamic load rebalance is
827later.
804
828
805# 12. Cross-worker communication
829# 12. Cross-worker communication
806
830
@@ -1580,13 +1604,25 @@ and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1580tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1604tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1581stands on the same feet line and extends upward.
1605stands on the same feet line and extends upward.
1582
1606
1583Each **ground** and **block** type has its own asset folder
1607Each sprite kind — **grounds**, **blocks**, **items**, **mobs**, and
1584(`client/assets/grounds/<key>/`, `client/assets/blocks/<key>/`). Every
1608**characters** — uses its own per-type asset folder
1585PNG in that folder is a **visual state**. States are not listed in the
1609(`client/assets/<kind>/<key>/`). Every base PNG in that folder is a
1586type definition: the first filename in alphabetical (numeric) order is
1610**visual state**. Filenames ending in `-bloom`, `-equip`, or combinations
1587the default. A later gameplay system may set a named state on a placed
1611such as `-equip-bloom` are **companions**, not states: `torch-bloom.png`
1588tile (for example a door `closed` / `open`); unknown names fall back to
1612is the bloom overlay for state `torch`, `{state}-equip.png` is the worn
1589the default. The editor mouse wheel cycles these states.
1613equipment overlay for that state, and `{state}-equip-bloom.png` is the
1614bloom overlay for that equip sprite. Companions always live in the same
1615folder as their base state and are never listed as placeable editor
1616states. Image names follow `layer:key:state` (plus `:equip` / `:bloom`
1617suffixes). States are not listed in the type definition: the first base
1618filename in alphabetical (numeric) order is the default. A later gameplay
1619system may set a named state on a placed tile (for example a door
1620`closed` / `open`); unknown names fall back to the default. The editor
1621mouse wheel cycles these states.
1622
1623Bloom companions are drawn on a separate Framework **bloom** render
1624layer that uses `Shader.getBloomPostChain(...)`. Bloom post-chain
1625parameters are live world settings under the Graphics tab.
1590
1626
1591Each type definition may set sprite-sheet playback for every state PNG:
1627Each type definition may set sprite-sheet playback for every state PNG:
1592
1628
@@ -1939,6 +1975,23 @@ Ordinary chat is spatial. A player speaks from a world position and only nearby
1939players receive a useful version of the message. Legibility decreases as the
1975players receive a useful version of the message. Legibility decreases as the
1940recipient gets farther from the speaker.
1976recipient gets farther from the speaker.
1941
1977
1978Readability uses Euclidean tile distance against the 16-tile chunk size:
1979
1980```text
1981distance <= 8 tiles // half a chunk: full plaintext
19828 < distance < 16 // linear falloff, e.g. 12 tiles → 50% readability
1983distance >= 16 tiles // a full chunk: 0% readability, no bubble
1984```
1985
1986The speaker always receives their own trimmed plaintext. Other recipients receive
1987a server-obscured copy: letters and digits may become `.` with probability
1988`1 - readability`; spaces and punctuation stay. At 0% readability the server
1989sends nothing, so the client never draws a bubble.
1990
1991Enter opens a bottom-of-screen line (max `chatMaxCharacters`, default 100).
1992Enter again trims and sends `CHAT_SAY`. Escape cancels. The client shows
1993`CHAT_BUBBLE` above the speaker.
1994
1942For example:
1995For example:
1943
1996
1944```text
1997```text
@@ -1948,8 +2001,6 @@ Very far: I'...re..ly..ar.aw.y
1948Beyond range: no message
2001Beyond range: no message
1949```
2002```
1950
2003
1951The exact distance bands/function are configurable game rules.
1952
1953Crucially, degradation is performed **server-side**. The server must not send the
2004Crucially, degradation is performed **server-side**. The server must not send the
1954full plaintext to a distant client and merely ask that client to obscure it,
2005full plaintext to a distant client and merely ask that client to obscure it,
1955because a modified client could then recover speech it was not supposed to
2006because a modified client could then recover speech it was not supposed to
@@ -2828,8 +2879,8 @@ players; they do not buy player goods unless a later iteration adds that.
2828
2879
2829- ChunkLoader reference counting and sleeping/unloading.
2880- ChunkLoader reference counting and sleeping/unloading.
2830
2881
2831- Single simulation worker behind the same worker interface planned for
2882- Isolated simulation workers behind a clone-on-boundary protocol
2832 later scaling.
2883 (in-process default; `worker_threads` optional).
2833
2884
2834- world.sqlite read path and state.sqlite persistence service.
2885- world.sqlite read path and state.sqlite persistence service.
2835
2886
@@ -2887,17 +2938,16 @@ players; they do not buy player goods unless a later iteration adds that.
2887
2938
2888## Phase 3 — Multi-worker world
2939## Phase 3 — Multi-worker world
2889
2940
2890- Multiple worker_threads simulation workers.
2941- Multiple isolated simulation workers and neighbour-sticky region ownership
2891
2942 (shipped); dynamic load rebalance remains.
2892- Region coordinator and dynamic region ownership.
2893
2943
2894- Cross-worker entity transfers.
2944- Cross-worker entity transfers (shipped).
2895
2945
2896- Border ghosts and remote actions.
2946- Border ghosts for occupancy/pathfinding (shipped); remote combat actions remain.
2897
2947
2898- Gateway subscriptions spanning multiple workers.
2948- Gateway subscriptions spanning multiple workers (shipped).
2899
2949
2900- Load metrics and neighbour-aware region balancing.
2950- Load metrics and neighbour-aware region balancing remain.
2901
2951
2902## Phase 4 — World depth, social systems and economy
2952## Phase 4 — World depth, social systems and economy
2903
2953
@@ -3328,9 +3378,6 @@ specified explicitly:
3328
3378
3329- Future scripting language syntax, event model and resource quotas.
3379- Future scripting language syntax, event model and resource quotas.
3330
3380
3331- Exact proximity-chat distance curve, maximum range and character degradation
3332 algorithm.
3333
3334- Group naming/roles, membership limits and whether group-wide letter sending
3381- Group naming/roles, membership limits and whether group-wide letter sending
3335 is offered as an addressing convenience that still dispatches one pigeon and
3382 is offered as an addressing convenience that still dispatches one pigeon and
3336 consumes one paper/letter per recipient.
3383 consumes one paper/letter per recipient.
@@ -3402,6 +3449,41 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3402
3449
3403# 34. Version history
3450# 34. Version history
3404
3451
3452## 0.19
3453
3454- Playable item basis: 32-slot inventory, equipment overlays, carried coins,
3455 ground drops (10-minute player drops, pickup on the tile), bank vaults,
3456 and account inheritance on character delete. Spawner and bank blocks can
3457 be painted in the editor; spawners produce placeholder deer up to
3458 `maxAlive`. Missing art is temporary 16×16 PNGs under `client/assets/`
3459 so real sprites can drop in later by replacing those files.
3460
3461## 0.18
3462
3463- Server ECS uses compact worker-local `EntityHandle`s (recycled free list)
3464 alongside global `EntityId`s for storage, networking and transfer. `Path`
3465 is a separate component from `Movement`; players carry `NetworkIdentity`
3466 instead of putting `sessionId` on `character`. Nearby clients get
3467 `ENTITY_SPAWN` / compact `ENTITY_MOVE` (tile + gait) / `ENTITY_DESPAWN`
3468 rather than appearance-heavy moves or extra snapshots.
3469
3470## 0.17
3471
3472- Region workers own ECS worlds behind a clone-on-boundary protocol
3473 (optional `worker_threads`). ChunkLoader reference counts keep 3×3
3474 chunks simulating and 3×3 regions resident; other resident chunks stay
3475 dormant. Regions unload after the grace period and persist flagged
3476 entities. Crossing a foreign region transfers the only authoritative
3477 copy; ghosts cover border occupancy; client snapshots may span workers.
3478
3479## 0.16
3480
3481- Proximity chat: Enter opens a bottom input (max `chatMaxCharacters`,
3482 default 100). Enter sends a trimmed line; the speaker always sees their
3483 own text. Other players get a server-obscured bubble (full until 8
3484 tiles, linear to silent at 16 tiles). At 0% readability no bubble is
3485 sent. Walk/run `R` is ignored while the chat line is open.
3486
3405## 0.15
3487## 0.15
3406
3488
3407- Hovering another player shows their first name. Clicking them opens an
3489- Hovering another player shows their first name. Clicking them opens an