BlueGit

timfa questward

Add interior dimensions, doorways, and related gameplay fixes.

Introduce dimension-scoped chunks with editor create/soft-delete, doorway teleports, visit tracking, and dim-aware quest conditions. Also fix tight-fit clothing UVs, mob-drop origins, and allow gathering with a tool one tier below the node.

timfa Tim Falken · pushed by timfa

Authored 2026-08-27 · 2 months ago

Hash
8b0ae105c5b53375eb3332edca503c3e772fa6dd
Parent
9f43f5fb
56 files changed +7574 −709
client/assets/blocks/doorway/cave.png added Binary file +0 −0

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

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

The contents of this binary file are not shown.

client/editor.html +75 −0
@@ -16,6 +16,11 @@
16 16 <p id="revision"></p>
17 17 <p id="authored"></p>
18 18 <label class="open-toggle"><input id="open" type="checkbox"> Open (enterable)</label>
19 <div class="dimension-picker">
20 <span class="dimension-picker-label">Dimension</span>
21 <div id="dimension-combo"></div>
22 <p id="dimension-purge-hint" class="hint" hidden></p>
23 </div>
19 24 <div class="nav">
20 25 <button id="north" type="button">Up</button>
21 26 <div>
@@ -24,6 +29,33 @@
24 29 </div>
25 30 <button id="south" type="button">Down</button>
26 31 </div>
32 <div id="dimension-settings" class="dimension-settings">
33 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
34 <label>Lighting
35 <select id="dim-lighting">
36 <option value="dayNight">Day / night</option>
37 <option value="alwaysLit">Always lit</option>
38 <option value="alwaysDark">Always dark</option>
39 </select>
40 </label>
41 <label>Season
42 <select id="dim-season">
43 <option value="auto">Auto (calendar)</option>
44 <option value="summer">Summer</option>
45 <option value="spring">Spring</option>
46 <option value="autumn">Autumn</option>
47 <option value="winter">Winter</option>
48 </select>
49 </label>
50 <label>Default ground
51 <select id="dim-default-ground"></select>
52 </label>
53 <div class="dimension-settings-actions">
54 <button id="dim-save" type="button">Save dimension</button>
55 <button id="dim-delete" type="button" hidden>Delete dimension</button>
56 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
57 </div>
58 </div>
27 59 <p>Tool: <strong id="tool"></strong></p>
28 60 <div class="palette">
29 61 <button id="open-palette" type="button">Select block…</button>
@@ -41,6 +73,8 @@
41 73 </select>
42 74 </label>
43 75 <button id="open-settings" type="button">World settings</button>
76 <button id="open-quests" type="button">Quests</button>
77 <button id="open-dialogues" type="button">Dialogues</button>
44 78 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle summer/fall/winter and update Season preview).</p>
45 79 </aside>
46 80 <section id="changelog-wrap">
@@ -49,6 +83,9 @@
49 83 </section>
50 84 <div id="selection-border" aria-hidden="true"></div>
51 85 <div id="tile-tooltip" hidden></div>
86 <footer id="hover-status" aria-live="polite">
87 <span id="hover-status-text">Hover a tile for coordinates</span>
88 </footer>
52 89 <div id="settings-backdrop" hidden></div>
53 90 <div id="settings-modal" hidden>
54 91 <div id="settings-main">
@@ -67,6 +104,44 @@
67 104 <div id="settings-log"></div>
68 105 </aside>
69 106 </div>
107 <div id="quests-backdrop" hidden></div>
108 <div id="quests-modal" hidden>
109 <header>
110 <h2>Quests</h2>
111 <button id="quests-close" type="button">Close</button>
112 </header>
113 <div class="content-editor-layout">
114 <aside class="content-editor-list-pane">
115 <button id="quests-new" type="button">New</button>
116 <div id="quests-list" class="content-editor-list"></div>
117 </aside>
118 <div id="quests-editor" class="content-editor-detail"></div>
119 </div>
120 <footer>
121 <button id="quests-delete" type="button" disabled>Delete</button>
122 <button id="quests-save" type="button" disabled>Save</button>
123 </footer>
124 </div>
125
126 <div id="dialogues-backdrop" hidden></div>
127 <div id="dialogues-modal" hidden>
128 <header>
129 <h2>Dialogues</h2>
130 <button id="dialogues-close" type="button">Close</button>
131 </header>
132 <div class="content-editor-layout">
133 <aside class="content-editor-list-pane">
134 <button id="dialogues-new" type="button">New</button>
135 <div id="dialogues-list" class="content-editor-list"></div>
136 </aside>
137 <div id="dialogues-editor" class="content-editor-detail"></div>
138 </div>
139 <footer>
140 <button id="dialogues-delete" type="button" disabled>Delete</button>
141 <button id="dialogues-save" type="button" disabled>Save</button>
142 </footer>
143 </div>
144
70 145 <div id="palette-backdrop" hidden></div>
71 146 <div id="palette-modal" hidden>
72 147 <header>
@@ -16,6 +16,11 @@
16 <p id="revision"></p>
16 <p id="revision"></p>
17 <p id="authored"></p>
17 <p id="authored"></p>
18 <label class="open-toggle"><input id="open" type="checkbox"> Open (enterable)</label>
18 <label class="open-toggle"><input id="open" type="checkbox"> Open (enterable)</label>
19 <div class="dimension-picker">
20 <span class="dimension-picker-label">Dimension</span>
21 <div id="dimension-combo"></div>
22 <p id="dimension-purge-hint" class="hint" hidden></p>
23 </div>
19 <div class="nav">
24 <div class="nav">
20 <button id="north" type="button">Up</button>
25 <button id="north" type="button">Up</button>
21 <div>
26 <div>
@@ -24,6 +29,33 @@
24 </div>
29 </div>
25 <button id="south" type="button">Down</button>
30 <button id="south" type="button">Down</button>
26 </div>
31 </div>
32 <div id="dimension-settings" class="dimension-settings">
33 <label>Display name <input id="dim-display-name" type="text" autocomplete="off"></label>
34 <label>Lighting
35 <select id="dim-lighting">
36 <option value="dayNight">Day / night</option>
37 <option value="alwaysLit">Always lit</option>
38 <option value="alwaysDark">Always dark</option>
39 </select>
40 </label>
41 <label>Season
42 <select id="dim-season">
43 <option value="auto">Auto (calendar)</option>
44 <option value="summer">Summer</option>
45 <option value="spring">Spring</option>
46 <option value="autumn">Autumn</option>
47 <option value="winter">Winter</option>
48 </select>
49 </label>
50 <label>Default ground
51 <select id="dim-default-ground"></select>
52 </label>
53 <div class="dimension-settings-actions">
54 <button id="dim-save" type="button">Save dimension</button>
55 <button id="dim-delete" type="button" hidden>Delete dimension</button>
56 <button id="dim-cancel-delete" type="button" hidden>Cancel deletion</button>
57 </div>
58 </div>
27 <p>Tool: <strong id="tool"></strong></p>
59 <p>Tool: <strong id="tool"></strong></p>
28 <div class="palette">
60 <div class="palette">
29 <button id="open-palette" type="button">Select block…</button>
61 <button id="open-palette" type="button">Select block…</button>
@@ -41,6 +73,8 @@
41 </select>
73 </select>
42 </label>
74 </label>
43 <button id="open-settings" type="button">World settings</button>
75 <button id="open-settings" type="button">World settings</button>
76 <button id="open-quests" type="button">Quests</button>
77 <button id="open-dialogues" type="button">Dialogues</button>
44 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle summer/fall/winter and update Season preview).</p>
78 <p class="hint">The red border is the chunk you are editing. Paint only inside the border. Hover shows tile config tooltips. Right-click a spawner to edit or remove it. Spawners are editor-only markers (invisible and non-blocking in play). Mouse wheel zooms; Shift+wheel cycles visual states (seasonal outdoor tiles cycle summer/fall/winter and update Season preview).</p>
45 </aside>
79 </aside>
46 <section id="changelog-wrap">
80 <section id="changelog-wrap">
@@ -49,6 +83,9 @@
49 </section>
83 </section>
50 <div id="selection-border" aria-hidden="true"></div>
84 <div id="selection-border" aria-hidden="true"></div>
51 <div id="tile-tooltip" hidden></div>
85 <div id="tile-tooltip" hidden></div>
86 <footer id="hover-status" aria-live="polite">
87 <span id="hover-status-text">Hover a tile for coordinates</span>
88 </footer>
52 <div id="settings-backdrop" hidden></div>
89 <div id="settings-backdrop" hidden></div>
53 <div id="settings-modal" hidden>
90 <div id="settings-modal" hidden>
54 <div id="settings-main">
91 <div id="settings-main">
@@ -67,6 +104,44 @@
67 <div id="settings-log"></div>
104 <div id="settings-log"></div>
68 </aside>
105 </aside>
69 </div>
106 </div>
107 <div id="quests-backdrop" hidden></div>
108 <div id="quests-modal" hidden>
109 <header>
110 <h2>Quests</h2>
111 <button id="quests-close" type="button">Close</button>
112 </header>
113 <div class="content-editor-layout">
114 <aside class="content-editor-list-pane">
115 <button id="quests-new" type="button">New</button>
116 <div id="quests-list" class="content-editor-list"></div>
117 </aside>
118 <div id="quests-editor" class="content-editor-detail"></div>
119 </div>
120 <footer>
121 <button id="quests-delete" type="button" disabled>Delete</button>
122 <button id="quests-save" type="button" disabled>Save</button>
123 </footer>
124 </div>
125
126 <div id="dialogues-backdrop" hidden></div>
127 <div id="dialogues-modal" hidden>
128 <header>
129 <h2>Dialogues</h2>
130 <button id="dialogues-close" type="button">Close</button>
131 </header>
132 <div class="content-editor-layout">
133 <aside class="content-editor-list-pane">
134 <button id="dialogues-new" type="button">New</button>
135 <div id="dialogues-list" class="content-editor-list"></div>
136 </aside>
137 <div id="dialogues-editor" class="content-editor-detail"></div>
138 </div>
139 <footer>
140 <button id="dialogues-delete" type="button" disabled>Delete</button>
141 <button id="dialogues-save" type="button" disabled>Save</button>
142 </footer>
143 </div>
144
70 <div id="palette-backdrop" hidden></div>
145 <div id="palette-backdrop" hidden></div>
71 <div id="palette-modal" hidden>
146 <div id="palette-modal" hidden>
72 <header>
147 <header>
client/index.html +41 −0
@@ -11,6 +11,7 @@
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="quests-toggle" type="button">Quests</button>
14 15 <button id="skills-toggle" type="button">Skills</button>
15 16 <button id="spells-toggle" type="button">Spells</button>
16 17 <button id="bag-toggle" type="button">Bag</button>
@@ -46,6 +47,46 @@
46 47 </aside>
47 48 <div id="toast-stack" aria-live="polite"></div>
48 49 <div id="world-tooltip" hidden></div>
50
51 <div id="quests-list-backdrop" class="modal-backdrop" hidden></div>
52 <div id="quests-list-panel" hidden>
53 <header>
54 <h2>Quests</h2>
55 <button id="quests-list-close" type="button">Close</button>
56 </header>
57 <div id="quests-list-body"></div>
58 </div>
59
60 <div id="quests-detail-backdrop" class="modal-backdrop" hidden></div>
61 <div id="quests-detail-panel" hidden>
62 <header>
63 <h2 id="quests-detail-title">Quest</h2>
64 <div class="quests-detail-actions">
65 <button id="quests-detail-back" type="button">Back</button>
66 <button id="quests-detail-close" type="button">Close</button>
67 </div>
68 </header>
69 <div class="quests-detail-layout">
70 <section>
71 <h3>Journal</h3>
72 <div id="quests-detail-journal"></div>
73 </section>
74 <section>
75 <h3>Current</h3>
76 <div id="quests-detail-step"></div>
77 </section>
78 </div>
79 </div>
80
81 <div id="dialogue-panel" hidden>
82 <header>
83 <h2 id="dialogue-title"></h2>
84 <button id="dialogue-close" type="button">Close</button>
85 </header>
86 <div id="dialogue-lines"></div>
87 <div id="dialogue-triggers" class="dialogue-triggers"></div>
88 </div>
89
49 90 <aside id="bag-panel" hidden>
50 91 <h2>Bag</h2>
51 92 <p id="bag-coins" hidden>0 coins</p>
@@ -11,6 +11,7 @@
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="quests-toggle" type="button">Quests</button>
14 <button id="skills-toggle" type="button">Skills</button>
15 <button id="skills-toggle" type="button">Skills</button>
15 <button id="spells-toggle" type="button">Spells</button>
16 <button id="spells-toggle" type="button">Spells</button>
16 <button id="bag-toggle" type="button">Bag</button>
17 <button id="bag-toggle" type="button">Bag</button>
@@ -46,6 +47,46 @@
46 </aside>
47 </aside>
47 <div id="toast-stack" aria-live="polite"></div>
48 <div id="toast-stack" aria-live="polite"></div>
48 <div id="world-tooltip" hidden></div>
49 <div id="world-tooltip" hidden></div>
50
51 <div id="quests-list-backdrop" class="modal-backdrop" hidden></div>
52 <div id="quests-list-panel" hidden>
53 <header>
54 <h2>Quests</h2>
55 <button id="quests-list-close" type="button">Close</button>
56 </header>
57 <div id="quests-list-body"></div>
58 </div>
59
60 <div id="quests-detail-backdrop" class="modal-backdrop" hidden></div>
61 <div id="quests-detail-panel" hidden>
62 <header>
63 <h2 id="quests-detail-title">Quest</h2>
64 <div class="quests-detail-actions">
65 <button id="quests-detail-back" type="button">Back</button>
66 <button id="quests-detail-close" type="button">Close</button>
67 </div>
68 </header>
69 <div class="quests-detail-layout">
70 <section>
71 <h3>Journal</h3>
72 <div id="quests-detail-journal"></div>
73 </section>
74 <section>
75 <h3>Current</h3>
76 <div id="quests-detail-step"></div>
77 </section>
78 </div>
79 </div>
80
81 <div id="dialogue-panel" hidden>
82 <header>
83 <h2 id="dialogue-title"></h2>
84 <button id="dialogue-close" type="button">Close</button>
85 </header>
86 <div id="dialogue-lines"></div>
87 <div id="dialogue-triggers" class="dialogue-triggers"></div>
88 </div>
89
49 <aside id="bag-panel" hidden>
90 <aside id="bag-panel" hidden>
50 <h2>Bag</h2>
91 <h2>Bag</h2>
51 <p id="bag-coins" hidden>0 coins</p>
92 <p id="bag-coins" hidden>0 coins</p>
client/src/editor/dialoguesModal.js added +444 −0
@@ -0,0 +1,444 @@
1 import { normalizeDialogueTree } from "/shared/quests/normalize.js";
2 import { emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
3
4 export function initDialoguesModal ({ socket, MessageType })
5 {
6 const backdrop = document.getElementById("dialogues-backdrop");
7 const modal = document.getElementById("dialogues-modal");
8 const listEl = document.getElementById("dialogues-list");
9 const editorEl = document.getElementById("dialogues-editor");
10 const saveBtn = document.getElementById("dialogues-save");
11 const deleteBtn = document.getElementById("dialogues-delete");
12 let open = false;
13 /** @type {any[]} */
14 let dialogues = [];
15 /** @type {any|null} */
16 let draft = null;
17 let selectedId = null;
18
19 function show (visible)
20 {
21 open = visible;
22 backdrop.hidden = !visible;
23 modal.hidden = !visible;
24 if (!visible)
25 {
26 draft = null;
27 selectedId = null;
28 }
29 }
30
31 function selectDialogue (dialogueId)
32 {
33 const found = dialogues.find((d) => d.dialogueId === dialogueId);
34 if (!found)
35 {
36 draft = null;
37 selectedId = null;
38 render();
39 return;
40 }
41 selectedId = found.dialogueId;
42 draft = structuredClone(found);
43 render();
44 }
45
46 function renderList ()
47 {
48 listEl.replaceChildren();
49 for (const tree of dialogues)
50 {
51 const btn = document.createElement("button");
52 btn.type = "button";
53 const unique = tree.unique ? " · unique" : "";
54 const assigned = tree.assignedSpawnerCount != null
55 ? ` (${tree.assignedSpawnerCount})`
56 : "";
57 btn.textContent = `${tree.label || tree.dialogueId}${unique}${assigned}`;
58 if (tree.dialogueId === selectedId)
59 { btn.classList.add("active"); }
60 btn.addEventListener("click", () => selectDialogue(tree.dialogueId));
61 listEl.append(btn);
62 }
63 }
64
65 function renderEditor ()
66 {
67 editorEl.replaceChildren();
68 saveBtn.disabled = !draft;
69 deleteBtn.disabled = !draft;
70 if (!draft)
71 {
72 const hint = document.createElement("p");
73 hint.className = "content-editor-hint";
74 hint.textContent = "Select a dialogue or create a new one.";
75 editorEl.append(hint);
76 return;
77 }
78
79 editorEl.append(
80 field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })),
81 field("Label", textInput(draft.label, (v) => { draft.label = v; }))
82 );
83
84 const uniqueLabel = document.createElement("label");
85 const uniqueBox = document.createElement("input");
86 uniqueBox.type = "checkbox";
87 uniqueBox.checked = !!draft.unique;
88 uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; });
89 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
90 editorEl.append(uniqueLabel);
91
92 const assigned = document.createElement("p");
93 assigned.className = "content-editor-hint";
94 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
95 editorEl.append(assigned);
96
97 editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
98 {
99 draft.entryStepId = v;
100 })));
101
102 const stepsHeader = sectionHeader("Steps", () =>
103 {
104 draft.steps.push({
105 stepId: `step-${draft.steps.length + 1}`,
106 label: "New step",
107 lines: [{ speaker: "npc", text: "…", effects: [] }],
108 exit: { kind: "end" }
109 });
110 renderEditor();
111 });
112 editorEl.append(stepsHeader);
113
114 draft.steps.forEach((step, stepIndex) =>
115 {
116 const box = document.createElement("div");
117 box.className = "content-editor-section";
118 box.append(sectionHeader(`Step ${stepIndex + 1}`, null, () =>
119 {
120 draft.steps.splice(stepIndex, 1);
121 if (draft.steps.length === 0)
122 {
123 draft.steps.push({
124 stepId: "greeting",
125 label: "Greeting",
126 lines: [{ speaker: "npc", text: "…", effects: [] }],
127 exit: { kind: "end" }
128 });
129 }
130 renderEditor();
131 }));
132 box.append(
133 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
134 field("Label", textInput(step.label, (v) => { step.label = v; }))
135 );
136
137 const linesHead = sectionHeader("Lines", () =>
138 {
139 step.lines.push({ speaker: "npc", text: "…", effects: [] });
140 renderEditor();
141 });
142 box.append(linesHead);
143 step.lines.forEach((line, lineIndex) =>
144 {
145 const row = document.createElement("div");
146 row.className = "content-editor-row";
147 const speaker = document.createElement("select");
148 for (const s of ["npc", "player"])
149 {
150 const opt = document.createElement("option");
151 opt.value = s;
152 opt.textContent = s;
153 if (line.speaker === s)
154 { opt.selected = true; }
155 speaker.append(opt);
156 }
157 speaker.addEventListener("change", () =>
158 {
159 line.speaker = speaker.value;
160 });
161 const text = document.createElement("input");
162 text.type = "text";
163 text.value = line.text ?? "";
164 text.style.flex = "1";
165 text.addEventListener("input", () => { line.text = text.value; });
166 const remove = document.createElement("button");
167 remove.type = "button";
168 remove.textContent = "×";
169 remove.addEventListener("click", () =>
170 {
171 step.lines.splice(lineIndex, 1);
172 if (step.lines.length === 0)
173 { step.lines.push({ speaker: "npc", text: "…", effects: [] }); }
174 renderEditor();
175 });
176 row.append(speaker, text, remove);
177 box.append(row);
178 });
179
180 const exitKind = document.createElement("select");
181 for (const k of ["end", "triggers", "branches"])
182 {
183 const opt = document.createElement("option");
184 opt.value = k;
185 opt.textContent = k;
186 if ((step.exit?.kind ?? "end") === k)
187 { opt.selected = true; }
188 exitKind.append(opt);
189 }
190 exitKind.addEventListener("change", () =>
191 {
192 if (exitKind.value === "triggers")
193 {
194 step.exit = {
195 kind: "triggers",
196 triggers: step.exit?.triggers?.length
197 ? step.exit.triggers
198 : [{
199 trigger: "continue",
200 label: "Continue",
201 text: "Continue",
202 nextStepId: null,
203 when: emptyConditionSet(),
204 effects: []
205 }]
206 };
207 }
208 else if (exitKind.value === "branches")
209 {
210 step.exit = {
211 kind: "branches",
212 branches: step.exit?.branches?.length
213 ? step.exit.branches
214 : [{
215 label: "default",
216 when: emptyConditionSet(),
217 nextStepId: null,
218 effects: []
219 }]
220 };
221 }
222 else
223 { step.exit = { kind: "end" }; }
224 renderEditor();
225 });
226 box.append(field("Exit kind", exitKind));
227
228 if (step.exit?.kind === "triggers")
229 {
230 const trigHead = sectionHeader("Triggers", () =>
231 {
232 step.exit.triggers.push({
233 trigger: `choice-${step.exit.triggers.length + 1}`,
234 label: "Choice",
235 text: "Choice",
236 nextStepId: null,
237 when: emptyConditionSet(),
238 effects: []
239 });
240 renderEditor();
241 });
242 box.append(trigHead);
243 step.exit.triggers.forEach((trig, trigIndex) =>
244 {
245 const tBox = document.createElement("div");
246 tBox.className = "content-editor-section";
247 tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () =>
248 {
249 step.exit.triggers.splice(trigIndex, 1);
250 renderEditor();
251 }));
252 tBox.append(
253 field("trigger", textInput(trig.trigger, (v) => { trig.trigger = v; })),
254 field("label", textInput(trig.label, (v) => { trig.label = v; })),
255 field("text (button)", textInput(trig.text, (v) => { trig.text = v; })),
256 field("nextStepId (blank=end)", textInput(trig.nextStepId ?? "", (v) =>
257 {
258 trig.nextStepId = v.trim() || null;
259 }))
260 );
261 tBox.append(whenJson(trig.when, (next) => { trig.when = next; }));
262 box.append(tBox);
263 });
264 }
265 else if (step.exit?.kind === "branches")
266 {
267 const branchHead = sectionHeader("Branches", () =>
268 {
269 step.exit.branches.push({
270 label: `branch-${step.exit.branches.length + 1}`,
271 when: emptyConditionSet(),
272 nextStepId: null,
273 effects: []
274 });
275 renderEditor();
276 });
277 box.append(branchHead);
278 step.exit.branches.forEach((branch, branchIndex) =>
279 {
280 const bBox = document.createElement("div");
281 bBox.className = "content-editor-section";
282 bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () =>
283 {
284 step.exit.branches.splice(branchIndex, 1);
285 renderEditor();
286 }));
287 bBox.append(
288 field("label", textInput(branch.label ?? "", (v) => { branch.label = v; })),
289 field("nextStepId (blank=end)", textInput(branch.nextStepId ?? "", (v) =>
290 {
291 branch.nextStepId = v.trim() || null;
292 }))
293 );
294 bBox.append(whenJson(branch.when, (next) => { branch.when = next; }));
295 box.append(bBox);
296 });
297 }
298
299 editorEl.append(box);
300 });
301 }
302
303 function render ()
304 {
305 renderList();
306 renderEditor();
307 }
308
309 document.getElementById("open-dialogues").addEventListener("click", () =>
310 {
311 socket.send({ type: MessageType.editorLoadDialogues });
312 show(true);
313 render();
314 });
315 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
316 backdrop.addEventListener("click", () => show(false));
317 document.getElementById("dialogues-new").addEventListener("click", () =>
318 {
319 const base = normalizeDialogueTree({
320 dialogueId: `dialogue-${dialogues.length + 1}`,
321 label: "New dialogue",
322 unique: false
323 });
324 draft = { ...structuredClone(base), assignedSpawnerCount: 0 };
325 selectedId = null;
326 render();
327 });
328 saveBtn.addEventListener("click", () =>
329 {
330 if (!draft)
331 { return; }
332 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
333 });
334 deleteBtn.addEventListener("click", () =>
335 {
336 if (!draft?.dialogueId)
337 { return; }
338 if (!window.confirm(`Delete dialogue "${draft.dialogueId}"?`))
339 { return; }
340 socket.send({ type: MessageType.editorDeleteDialogue, dialogueId: draft.dialogueId });
341 });
342
343 return {
344 isOpen: () => open,
345 getDialogues: () => dialogues,
346 handleMessage (message)
347 {
348 if (message.type !== MessageType.editorDialogues)
349 { return; }
350 dialogues = (message.dialogues ?? []).map((d) =>
351 {
352 const tree = normalizeDialogueTree(d);
353 return {
354 ...tree,
355 assignedSpawnerCount: d.assignedSpawnerCount ?? 0
356 };
357 });
358 if (draft)
359 {
360 const still = dialogues.find((d) => d.dialogueId === draft.dialogueId);
361 if (still)
362 {
363 selectedId = still.dialogueId;
364 draft = structuredClone(still);
365 }
366 else if (selectedId)
367 {
368 draft = null;
369 selectedId = null;
370 }
371 }
372 if (open)
373 { render(); }
374 }
375 };
376 }
377
378 function field (label, input)
379 {
380 const wrap = document.createElement("label");
381 wrap.append(document.createTextNode(label), input);
382 return wrap;
383 }
384
385 function textInput (value, onChange)
386 {
387 const input = document.createElement("input");
388 input.type = "text";
389 input.value = value ?? "";
390 input.addEventListener("input", () => onChange(input.value));
391 return input;
392 }
393
394 function sectionHeader (title, onAdd, onRemove)
395 {
396 const head = document.createElement("div");
397 head.className = "content-editor-section-header";
398 const strong = document.createElement("strong");
399 strong.textContent = title;
400 head.append(strong);
401 const actions = document.createElement("div");
402 actions.className = "content-editor-row";
403 if (onAdd)
404 {
405 const add = document.createElement("button");
406 add.type = "button";
407 add.textContent = "+";
408 add.title = "Add";
409 add.addEventListener("click", onAdd);
410 actions.append(add);
411 }
412 if (onRemove)
413 {
414 const remove = document.createElement("button");
415 remove.type = "button";
416 remove.textContent = "×";
417 remove.title = "Remove";
418 remove.addEventListener("click", onRemove);
419 actions.append(remove);
420 }
421 head.append(actions);
422 return head;
423 }
424
425 function whenJson (when, onChange)
426 {
427 const details = document.createElement("details");
428 const summary = document.createElement("summary");
429 summary.textContent = "when (condition JSON)";
430 const area = document.createElement("textarea");
431 area.rows = 4;
432 area.value = JSON.stringify(normalizeConditionSet(when), null, 2);
433 area.addEventListener("change", () =>
434 {
435 try
436 {
437 onChange(normalizeConditionSet(JSON.parse(area.value)));
438 }
439 catch
440 { /* ignore invalid */ }
441 });
442 details.append(summary, area);
443 return details;
444 }
@@ -0,0 +1,444 @@
1import { normalizeDialogueTree } from "/shared/quests/normalize.js";
2import { emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
3
4export function initDialoguesModal ({ socket, MessageType })
5{
6 const backdrop = document.getElementById("dialogues-backdrop");
7 const modal = document.getElementById("dialogues-modal");
8 const listEl = document.getElementById("dialogues-list");
9 const editorEl = document.getElementById("dialogues-editor");
10 const saveBtn = document.getElementById("dialogues-save");
11 const deleteBtn = document.getElementById("dialogues-delete");
12 let open = false;
13 /** @type {any[]} */
14 let dialogues = [];
15 /** @type {any|null} */
16 let draft = null;
17 let selectedId = null;
18
19 function show (visible)
20 {
21 open = visible;
22 backdrop.hidden = !visible;
23 modal.hidden = !visible;
24 if (!visible)
25 {
26 draft = null;
27 selectedId = null;
28 }
29 }
30
31 function selectDialogue (dialogueId)
32 {
33 const found = dialogues.find((d) => d.dialogueId === dialogueId);
34 if (!found)
35 {
36 draft = null;
37 selectedId = null;
38 render();
39 return;
40 }
41 selectedId = found.dialogueId;
42 draft = structuredClone(found);
43 render();
44 }
45
46 function renderList ()
47 {
48 listEl.replaceChildren();
49 for (const tree of dialogues)
50 {
51 const btn = document.createElement("button");
52 btn.type = "button";
53 const unique = tree.unique ? " · unique" : "";
54 const assigned = tree.assignedSpawnerCount != null
55 ? ` (${tree.assignedSpawnerCount})`
56 : "";
57 btn.textContent = `${tree.label || tree.dialogueId}${unique}${assigned}`;
58 if (tree.dialogueId === selectedId)
59 { btn.classList.add("active"); }
60 btn.addEventListener("click", () => selectDialogue(tree.dialogueId));
61 listEl.append(btn);
62 }
63 }
64
65 function renderEditor ()
66 {
67 editorEl.replaceChildren();
68 saveBtn.disabled = !draft;
69 deleteBtn.disabled = !draft;
70 if (!draft)
71 {
72 const hint = document.createElement("p");
73 hint.className = "content-editor-hint";
74 hint.textContent = "Select a dialogue or create a new one.";
75 editorEl.append(hint);
76 return;
77 }
78
79 editorEl.append(
80 field("Dialogue id", textInput(draft.dialogueId, (v) => { draft.dialogueId = v; })),
81 field("Label", textInput(draft.label, (v) => { draft.label = v; }))
82 );
83
84 const uniqueLabel = document.createElement("label");
85 const uniqueBox = document.createElement("input");
86 uniqueBox.type = "checkbox";
87 uniqueBox.checked = !!draft.unique;
88 uniqueBox.addEventListener("change", () => { draft.unique = uniqueBox.checked; });
89 uniqueLabel.append(uniqueBox, document.createTextNode(" Unique (at most one spawner)"));
90 editorEl.append(uniqueLabel);
91
92 const assigned = document.createElement("p");
93 assigned.className = "content-editor-hint";
94 assigned.textContent = `Assigned spawners: ${draft.assignedSpawnerCount ?? 0}`;
95 editorEl.append(assigned);
96
97 editorEl.append(field("Entry step id", textInput(draft.entryStepId ?? "", (v) =>
98 {
99 draft.entryStepId = v;
100 })));
101
102 const stepsHeader = sectionHeader("Steps", () =>
103 {
104 draft.steps.push({
105 stepId: `step-${draft.steps.length + 1}`,
106 label: "New step",
107 lines: [{ speaker: "npc", text: "…", effects: [] }],
108 exit: { kind: "end" }
109 });
110 renderEditor();
111 });
112 editorEl.append(stepsHeader);
113
114 draft.steps.forEach((step, stepIndex) =>
115 {
116 const box = document.createElement("div");
117 box.className = "content-editor-section";
118 box.append(sectionHeader(`Step ${stepIndex + 1}`, null, () =>
119 {
120 draft.steps.splice(stepIndex, 1);
121 if (draft.steps.length === 0)
122 {
123 draft.steps.push({
124 stepId: "greeting",
125 label: "Greeting",
126 lines: [{ speaker: "npc", text: "…", effects: [] }],
127 exit: { kind: "end" }
128 });
129 }
130 renderEditor();
131 }));
132 box.append(
133 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
134 field("Label", textInput(step.label, (v) => { step.label = v; }))
135 );
136
137 const linesHead = sectionHeader("Lines", () =>
138 {
139 step.lines.push({ speaker: "npc", text: "…", effects: [] });
140 renderEditor();
141 });
142 box.append(linesHead);
143 step.lines.forEach((line, lineIndex) =>
144 {
145 const row = document.createElement("div");
146 row.className = "content-editor-row";
147 const speaker = document.createElement("select");
148 for (const s of ["npc", "player"])
149 {
150 const opt = document.createElement("option");
151 opt.value = s;
152 opt.textContent = s;
153 if (line.speaker === s)
154 { opt.selected = true; }
155 speaker.append(opt);
156 }
157 speaker.addEventListener("change", () =>
158 {
159 line.speaker = speaker.value;
160 });
161 const text = document.createElement("input");
162 text.type = "text";
163 text.value = line.text ?? "";
164 text.style.flex = "1";
165 text.addEventListener("input", () => { line.text = text.value; });
166 const remove = document.createElement("button");
167 remove.type = "button";
168 remove.textContent = "×";
169 remove.addEventListener("click", () =>
170 {
171 step.lines.splice(lineIndex, 1);
172 if (step.lines.length === 0)
173 { step.lines.push({ speaker: "npc", text: "…", effects: [] }); }
174 renderEditor();
175 });
176 row.append(speaker, text, remove);
177 box.append(row);
178 });
179
180 const exitKind = document.createElement("select");
181 for (const k of ["end", "triggers", "branches"])
182 {
183 const opt = document.createElement("option");
184 opt.value = k;
185 opt.textContent = k;
186 if ((step.exit?.kind ?? "end") === k)
187 { opt.selected = true; }
188 exitKind.append(opt);
189 }
190 exitKind.addEventListener("change", () =>
191 {
192 if (exitKind.value === "triggers")
193 {
194 step.exit = {
195 kind: "triggers",
196 triggers: step.exit?.triggers?.length
197 ? step.exit.triggers
198 : [{
199 trigger: "continue",
200 label: "Continue",
201 text: "Continue",
202 nextStepId: null,
203 when: emptyConditionSet(),
204 effects: []
205 }]
206 };
207 }
208 else if (exitKind.value === "branches")
209 {
210 step.exit = {
211 kind: "branches",
212 branches: step.exit?.branches?.length
213 ? step.exit.branches
214 : [{
215 label: "default",
216 when: emptyConditionSet(),
217 nextStepId: null,
218 effects: []
219 }]
220 };
221 }
222 else
223 { step.exit = { kind: "end" }; }
224 renderEditor();
225 });
226 box.append(field("Exit kind", exitKind));
227
228 if (step.exit?.kind === "triggers")
229 {
230 const trigHead = sectionHeader("Triggers", () =>
231 {
232 step.exit.triggers.push({
233 trigger: `choice-${step.exit.triggers.length + 1}`,
234 label: "Choice",
235 text: "Choice",
236 nextStepId: null,
237 when: emptyConditionSet(),
238 effects: []
239 });
240 renderEditor();
241 });
242 box.append(trigHead);
243 step.exit.triggers.forEach((trig, trigIndex) =>
244 {
245 const tBox = document.createElement("div");
246 tBox.className = "content-editor-section";
247 tBox.append(sectionHeader(`Trigger ${trigIndex + 1}`, null, () =>
248 {
249 step.exit.triggers.splice(trigIndex, 1);
250 renderEditor();
251 }));
252 tBox.append(
253 field("trigger", textInput(trig.trigger, (v) => { trig.trigger = v; })),
254 field("label", textInput(trig.label, (v) => { trig.label = v; })),
255 field("text (button)", textInput(trig.text, (v) => { trig.text = v; })),
256 field("nextStepId (blank=end)", textInput(trig.nextStepId ?? "", (v) =>
257 {
258 trig.nextStepId = v.trim() || null;
259 }))
260 );
261 tBox.append(whenJson(trig.when, (next) => { trig.when = next; }));
262 box.append(tBox);
263 });
264 }
265 else if (step.exit?.kind === "branches")
266 {
267 const branchHead = sectionHeader("Branches", () =>
268 {
269 step.exit.branches.push({
270 label: `branch-${step.exit.branches.length + 1}`,
271 when: emptyConditionSet(),
272 nextStepId: null,
273 effects: []
274 });
275 renderEditor();
276 });
277 box.append(branchHead);
278 step.exit.branches.forEach((branch, branchIndex) =>
279 {
280 const bBox = document.createElement("div");
281 bBox.className = "content-editor-section";
282 bBox.append(sectionHeader(`Branch ${branchIndex + 1}`, null, () =>
283 {
284 step.exit.branches.splice(branchIndex, 1);
285 renderEditor();
286 }));
287 bBox.append(
288 field("label", textInput(branch.label ?? "", (v) => { branch.label = v; })),
289 field("nextStepId (blank=end)", textInput(branch.nextStepId ?? "", (v) =>
290 {
291 branch.nextStepId = v.trim() || null;
292 }))
293 );
294 bBox.append(whenJson(branch.when, (next) => { branch.when = next; }));
295 box.append(bBox);
296 });
297 }
298
299 editorEl.append(box);
300 });
301 }
302
303 function render ()
304 {
305 renderList();
306 renderEditor();
307 }
308
309 document.getElementById("open-dialogues").addEventListener("click", () =>
310 {
311 socket.send({ type: MessageType.editorLoadDialogues });
312 show(true);
313 render();
314 });
315 document.getElementById("dialogues-close").addEventListener("click", () => show(false));
316 backdrop.addEventListener("click", () => show(false));
317 document.getElementById("dialogues-new").addEventListener("click", () =>
318 {
319 const base = normalizeDialogueTree({
320 dialogueId: `dialogue-${dialogues.length + 1}`,
321 label: "New dialogue",
322 unique: false
323 });
324 draft = { ...structuredClone(base), assignedSpawnerCount: 0 };
325 selectedId = null;
326 render();
327 });
328 saveBtn.addEventListener("click", () =>
329 {
330 if (!draft)
331 { return; }
332 socket.send({ type: MessageType.editorSaveDialogue, dialogue: draft });
333 });
334 deleteBtn.addEventListener("click", () =>
335 {
336 if (!draft?.dialogueId)
337 { return; }
338 if (!window.confirm(`Delete dialogue "${draft.dialogueId}"?`))
339 { return; }
340 socket.send({ type: MessageType.editorDeleteDialogue, dialogueId: draft.dialogueId });
341 });
342
343 return {
344 isOpen: () => open,
345 getDialogues: () => dialogues,
346 handleMessage (message)
347 {
348 if (message.type !== MessageType.editorDialogues)
349 { return; }
350 dialogues = (message.dialogues ?? []).map((d) =>
351 {
352 const tree = normalizeDialogueTree(d);
353 return {
354 ...tree,
355 assignedSpawnerCount: d.assignedSpawnerCount ?? 0
356 };
357 });
358 if (draft)
359 {
360 const still = dialogues.find((d) => d.dialogueId === draft.dialogueId);
361 if (still)
362 {
363 selectedId = still.dialogueId;
364 draft = structuredClone(still);
365 }
366 else if (selectedId)
367 {
368 draft = null;
369 selectedId = null;
370 }
371 }
372 if (open)
373 { render(); }
374 }
375 };
376}
377
378function field (label, input)
379{
380 const wrap = document.createElement("label");
381 wrap.append(document.createTextNode(label), input);
382 return wrap;
383}
384
385function textInput (value, onChange)
386{
387 const input = document.createElement("input");
388 input.type = "text";
389 input.value = value ?? "";
390 input.addEventListener("input", () => onChange(input.value));
391 return input;
392}
393
394function sectionHeader (title, onAdd, onRemove)
395{
396 const head = document.createElement("div");
397 head.className = "content-editor-section-header";
398 const strong = document.createElement("strong");
399 strong.textContent = title;
400 head.append(strong);
401 const actions = document.createElement("div");
402 actions.className = "content-editor-row";
403 if (onAdd)
404 {
405 const add = document.createElement("button");
406 add.type = "button";
407 add.textContent = "+";
408 add.title = "Add";
409 add.addEventListener("click", onAdd);
410 actions.append(add);
411 }
412 if (onRemove)
413 {
414 const remove = document.createElement("button");
415 remove.type = "button";
416 remove.textContent = "×";
417 remove.title = "Remove";
418 remove.addEventListener("click", onRemove);
419 actions.append(remove);
420 }
421 head.append(actions);
422 return head;
423}
424
425function whenJson (when, onChange)
426{
427 const details = document.createElement("details");
428 const summary = document.createElement("summary");
429 summary.textContent = "when (condition JSON)";
430 const area = document.createElement("textarea");
431 area.rows = 4;
432 area.value = JSON.stringify(normalizeConditionSet(when), null, 2);
433 area.addEventListener("change", () =>
434 {
435 try
436 {
437 onChange(normalizeConditionSet(JSON.parse(area.value)));
438 }
439 catch
440 { /* ignore invalid */ }
441 });
442 details.append(summary, area);
443 return details;
444}
client/src/editor/dimensionCombobox.js added +236 −0
@@ -0,0 +1,236 @@
1 /**
2 * Searchable combobox for editor dimension picking.
3 * options: { id, label, disabled?, hint? }[]
4 */
5 export function createDimensionCombobox ({
6 root,
7 allowCreate = false,
8 placeholder = "Dimension…",
9 onSelect,
10 onCreate
11 })
12 {
13 root.classList.add("dim-combo");
14 root.innerHTML = "";
15
16 const input = document.createElement("input");
17 input.type = "text";
18 input.className = "dim-combo-input";
19 input.placeholder = placeholder;
20 input.autocomplete = "off";
21 input.setAttribute("role", "combobox");
22 input.setAttribute("aria-autocomplete", "list");
23 input.setAttribute("aria-expanded", "false");
24
25 const list = document.createElement("ul");
26 list.className = "dim-combo-list";
27 list.hidden = true;
28 list.setAttribute("role", "listbox");
29
30 root.append(input, list);
31
32 /** @type {{ id: string, label: string, disabled?: boolean, hint?: string }[]} */
33 let options = [];
34 let selectedId = null;
35 let open = false;
36
37 function selectedOption ()
38 {
39 return options.find((opt) => opt.id === selectedId) ?? null;
40 }
41
42 function displayLabel (opt)
43 {
44 if (!opt)
45 { return ""; }
46 return opt.label && opt.label !== opt.id ? `${opt.label} (${opt.id})` : opt.id;
47 }
48
49 function syncInputFromSelection ()
50 {
51 const opt = selectedOption();
52 input.value = opt ? displayLabel(opt) : (selectedId ?? "");
53 }
54
55 function setOpen (next)
56 {
57 open = next;
58 list.hidden = !open;
59 input.setAttribute("aria-expanded", open ? "true" : "false");
60 if (open)
61 { renderList(); }
62 }
63
64 function filtered ()
65 {
66 const q = input.value.trim().toLowerCase();
67 if (!q)
68 { return options.slice(); }
69 return options.filter((opt) =>
70 opt.id.toLowerCase().includes(q)
71 || (opt.label ?? "").toLowerCase().includes(q)
72 || (opt.hint ?? "").toLowerCase().includes(q)
73 );
74 }
75
76 function exactMatchId (text)
77 {
78 const q = String(text ?? "").trim().toLowerCase();
79 if (!q)
80 { return null; }
81 const hit = options.find((opt) => opt.id.toLowerCase() === q || (opt.label ?? "").toLowerCase() === q);
82 return hit?.id ?? null;
83 }
84
85 function renderList ()
86 {
87 list.innerHTML = "";
88 const rows = filtered();
89 const typed = input.value.trim();
90 const typedLower = typed.toLowerCase();
91 const hasExact = options.some((opt) =>
92 opt.id.toLowerCase() === typedLower || (opt.label ?? "").toLowerCase() === typedLower
93 );
94
95 for (const opt of rows)
96 {
97 const li = document.createElement("li");
98 li.className = "dim-combo-option";
99 if (opt.disabled)
100 { li.classList.add("disabled"); }
101 if (opt.id === selectedId)
102 { li.classList.add("selected"); }
103 li.setAttribute("role", "option");
104 li.dataset.id = opt.id;
105 const main = document.createElement("span");
106 main.className = "dim-combo-option-label";
107 main.textContent = displayLabel(opt);
108 li.append(main);
109 if (opt.hint)
110 {
111 const hint = document.createElement("span");
112 hint.className = "dim-combo-option-hint";
113 hint.textContent = opt.hint;
114 li.append(hint);
115 }
116 li.addEventListener("mousedown", (event) =>
117 {
118 event.preventDefault();
119 choose(opt.id);
120 });
121 list.append(li);
122 }
123
124 if (allowCreate && typed && !hasExact)
125 {
126 const li = document.createElement("li");
127 li.className = "dim-combo-option create";
128 li.setAttribute("role", "option");
129 li.textContent = `Create «${typed}»`;
130 li.addEventListener("mousedown", (event) =>
131 {
132 event.preventDefault();
133 setOpen(false);
134 onCreate?.(typed);
135 });
136 list.append(li);
137 }
138
139 if (!list.children.length)
140 {
141 const empty = document.createElement("li");
142 empty.className = "dim-combo-empty";
143 empty.textContent = "No dimensions";
144 list.append(empty);
145 }
146 }
147
148 function choose (id)
149 {
150 selectedId = id;
151 syncInputFromSelection();
152 setOpen(false);
153 onSelect?.(id);
154 }
155
156 input.addEventListener("focus", () =>
157 {
158 input.select();
159 setOpen(true);
160 });
161 input.addEventListener("input", () =>
162 {
163 setOpen(true);
164 renderList();
165 });
166 input.addEventListener("keydown", (event) =>
167 {
168 if (event.key === "Escape")
169 {
170 syncInputFromSelection();
171 setOpen(false);
172 input.blur();
173 return;
174 }
175 if (event.key === "Enter")
176 {
177 event.preventDefault();
178 const typed = input.value.trim();
179 const exact = exactMatchId(typed);
180 if (exact)
181 {
182 choose(exact);
183 return;
184 }
185 const rows = filtered().filter((opt) => !opt.disabled);
186 if (rows.length === 1)
187 {
188 choose(rows[0].id);
189 return;
190 }
191 if (allowCreate && typed && !exactMatchId(typed))
192 {
193 setOpen(false);
194 onCreate?.(typed);
195 }
196 }
197 });
198 input.addEventListener("blur", () =>
199 {
200 window.setTimeout(() =>
201 {
202 if (!root.contains(document.activeElement))
203 {
204 syncInputFromSelection();
205 setOpen(false);
206 }
207 }, 0);
208 });
209
210 return {
211 setOptions (nextOptions)
212 {
213 options = Array.isArray(nextOptions) ? nextOptions.slice() : [];
214 if (selectedId && !options.some((opt) => opt.id === selectedId))
215 { selectedId = options[0]?.id ?? null; }
216 syncInputFromSelection();
217 if (open)
218 { renderList(); }
219 },
220 setValue (id)
221 {
222 selectedId = id;
223 syncInputFromSelection();
224 if (open)
225 { renderList(); }
226 },
227 getValue ()
228 {
229 return selectedId;
230 },
231 close ()
232 {
233 setOpen(false);
234 }
235 };
236 }
@@ -0,0 +1,236 @@
1/**
2 * Searchable combobox for editor dimension picking.
3 * options: { id, label, disabled?, hint? }[]
4 */
5export function createDimensionCombobox ({
6 root,
7 allowCreate = false,
8 placeholder = "Dimension…",
9 onSelect,
10 onCreate
11})
12{
13 root.classList.add("dim-combo");
14 root.innerHTML = "";
15
16 const input = document.createElement("input");
17 input.type = "text";
18 input.className = "dim-combo-input";
19 input.placeholder = placeholder;
20 input.autocomplete = "off";
21 input.setAttribute("role", "combobox");
22 input.setAttribute("aria-autocomplete", "list");
23 input.setAttribute("aria-expanded", "false");
24
25 const list = document.createElement("ul");
26 list.className = "dim-combo-list";
27 list.hidden = true;
28 list.setAttribute("role", "listbox");
29
30 root.append(input, list);
31
32 /** @type {{ id: string, label: string, disabled?: boolean, hint?: string }[]} */
33 let options = [];
34 let selectedId = null;
35 let open = false;
36
37 function selectedOption ()
38 {
39 return options.find((opt) => opt.id === selectedId) ?? null;
40 }
41
42 function displayLabel (opt)
43 {
44 if (!opt)
45 { return ""; }
46 return opt.label && opt.label !== opt.id ? `${opt.label} (${opt.id})` : opt.id;
47 }
48
49 function syncInputFromSelection ()
50 {
51 const opt = selectedOption();
52 input.value = opt ? displayLabel(opt) : (selectedId ?? "");
53 }
54
55 function setOpen (next)
56 {
57 open = next;
58 list.hidden = !open;
59 input.setAttribute("aria-expanded", open ? "true" : "false");
60 if (open)
61 { renderList(); }
62 }
63
64 function filtered ()
65 {
66 const q = input.value.trim().toLowerCase();
67 if (!q)
68 { return options.slice(); }
69 return options.filter((opt) =>
70 opt.id.toLowerCase().includes(q)
71 || (opt.label ?? "").toLowerCase().includes(q)
72 || (opt.hint ?? "").toLowerCase().includes(q)
73 );
74 }
75
76 function exactMatchId (text)
77 {
78 const q = String(text ?? "").trim().toLowerCase();
79 if (!q)
80 { return null; }
81 const hit = options.find((opt) => opt.id.toLowerCase() === q || (opt.label ?? "").toLowerCase() === q);
82 return hit?.id ?? null;
83 }
84
85 function renderList ()
86 {
87 list.innerHTML = "";
88 const rows = filtered();
89 const typed = input.value.trim();
90 const typedLower = typed.toLowerCase();
91 const hasExact = options.some((opt) =>
92 opt.id.toLowerCase() === typedLower || (opt.label ?? "").toLowerCase() === typedLower
93 );
94
95 for (const opt of rows)
96 {
97 const li = document.createElement("li");
98 li.className = "dim-combo-option";
99 if (opt.disabled)
100 { li.classList.add("disabled"); }
101 if (opt.id === selectedId)
102 { li.classList.add("selected"); }
103 li.setAttribute("role", "option");
104 li.dataset.id = opt.id;
105 const main = document.createElement("span");
106 main.className = "dim-combo-option-label";
107 main.textContent = displayLabel(opt);
108 li.append(main);
109 if (opt.hint)
110 {
111 const hint = document.createElement("span");
112 hint.className = "dim-combo-option-hint";
113 hint.textContent = opt.hint;
114 li.append(hint);
115 }
116 li.addEventListener("mousedown", (event) =>
117 {
118 event.preventDefault();
119 choose(opt.id);
120 });
121 list.append(li);
122 }
123
124 if (allowCreate && typed && !hasExact)
125 {
126 const li = document.createElement("li");
127 li.className = "dim-combo-option create";
128 li.setAttribute("role", "option");
129 li.textContent = `Create «${typed}»`;
130 li.addEventListener("mousedown", (event) =>
131 {
132 event.preventDefault();
133 setOpen(false);
134 onCreate?.(typed);
135 });
136 list.append(li);
137 }
138
139 if (!list.children.length)
140 {
141 const empty = document.createElement("li");
142 empty.className = "dim-combo-empty";
143 empty.textContent = "No dimensions";
144 list.append(empty);
145 }
146 }
147
148 function choose (id)
149 {
150 selectedId = id;
151 syncInputFromSelection();
152 setOpen(false);
153 onSelect?.(id);
154 }
155
156 input.addEventListener("focus", () =>
157 {
158 input.select();
159 setOpen(true);
160 });
161 input.addEventListener("input", () =>
162 {
163 setOpen(true);
164 renderList();
165 });
166 input.addEventListener("keydown", (event) =>
167 {
168 if (event.key === "Escape")
169 {
170 syncInputFromSelection();
171 setOpen(false);
172 input.blur();
173 return;
174 }
175 if (event.key === "Enter")
176 {
177 event.preventDefault();
178 const typed = input.value.trim();
179 const exact = exactMatchId(typed);
180 if (exact)
181 {
182 choose(exact);
183 return;
184 }
185 const rows = filtered().filter((opt) => !opt.disabled);
186 if (rows.length === 1)
187 {
188 choose(rows[0].id);
189 return;
190 }
191 if (allowCreate && typed && !exactMatchId(typed))
192 {
193 setOpen(false);
194 onCreate?.(typed);
195 }
196 }
197 });
198 input.addEventListener("blur", () =>
199 {
200 window.setTimeout(() =>
201 {
202 if (!root.contains(document.activeElement))
203 {
204 syncInputFromSelection();
205 setOpen(false);
206 }
207 }, 0);
208 });
209
210 return {
211 setOptions (nextOptions)
212 {
213 options = Array.isArray(nextOptions) ? nextOptions.slice() : [];
214 if (selectedId && !options.some((opt) => opt.id === selectedId))
215 { selectedId = options[0]?.id ?? null; }
216 syncInputFromSelection();
217 if (open)
218 { renderList(); }
219 },
220 setValue (id)
221 {
222 selectedId = id;
223 syncInputFromSelection();
224 if (open)
225 { renderList(); }
226 },
227 getValue ()
228 {
229 return selectedId;
230 },
231 close ()
232 {
233 setOpen(false);
234 }
235 };
236}
client/src/editor/main.js +350 −23
@@ -27,9 +27,17 @@ import {
27 27 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
28 28 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
29 29 import { WorldView } from "../render/worldView.js";
30 import { initSettingsModal } from "./settingsModal.js";
30 import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
31 31 import { initPaletteModal } from "./paletteModal.js";
32 32 import { initTileConfigModal } from "./tileConfigModal.js";
33 import { initQuestsModal } from "./questsModal.js";
34 import { initDialoguesModal } from "./dialoguesModal.js";
35 import { createDimensionCombobox } from "./dimensionCombobox.js";
36 import {
37 OVERWORLD_ID,
38 normalizeDimensionId,
39 isOverworld
40 } from "/shared/world/dimensions.js";
33 41
34 42 const game = new Game();
35 43 let socket;
@@ -38,16 +46,25 @@ let view;
38 46 let draft = null;
39 47 /** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
40 48 let draftBaseline = null;
41 /** @type {{ chunkX: number, chunkY: number }|null} */
49 /** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
42 50 let pendingNavigate = null;
43 51 /** When true, next matching editorChunk after save should navigate to pendingNavigate. */
44 52 let navigateAfterSave = false;
45 53 let chunkX = 0;
46 54 let chunkY = 0;
55 let selectedDimensionId = OVERWORLD_ID;
56 /** @type {string|null} */
57 let pendingCreatedDimensionId = null;
58 /** @type {Map<string, object>} */
59 let dimensionsById = new Map();
60 let dimensionCombo = null;
61 let dimensionSettings = null;
47 62 let tool = { kind: "ground", typeId: GroundType.grass, state: null };
48 63 let settingsModal;
49 64 let paletteModal;
50 65 let tileConfigModal;
66 let questsModal;
67 let dialoguesModal;
51 68 let catalog = { grounds: {}, blocks: {}, images: [] };
52 69 let imageUrlByName = new Map();
53 70 let hoverLocal = null;
@@ -204,10 +221,15 @@ function syncSaveButton ()
204 221 const btn = $("save");
205 222 if (!btn)
206 223 { return; }
224 const softDeleted = isSelectedDimensionSoftDeleted();
207 225 const dirty = isDraftDirty();
208 btn.disabled = !dirty;
209 btn.classList.toggle("save-dirty", dirty);
210 btn.title = dirty ? "Save unsaved chunk changes" : "No unsaved changes";
226 btn.disabled = !dirty || softDeleted;
227 btn.classList.toggle("save-dirty", dirty && !softDeleted);
228 btn.title = softDeleted
229 ? "Cannot save while this dimension is soft-deleted"
230 : dirty
231 ? "Save unsaved chunk changes"
232 : "No unsaved changes";
211 233 }
212 234
213 235 function afterDraftMutation ()
@@ -232,6 +254,11 @@ function saveSelectedChunk ()
232 254 {
233 255 if (!draft || !isDraftDirty())
234 256 { return false; }
257 if (isSelectedDimensionSoftDeleted())
258 {
259 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
260 return false;
261 }
235 262 $("error").textContent = "";
236 263 $("apply-status").textContent = "";
237 264 $("apply-status").className = "hint";
@@ -239,6 +266,7 @@ function saveSelectedChunk ()
239 266 type: MessageType.editorSaveChunk,
240 267 chunkX,
241 268 chunkY,
269 dimensionId: selectedDimensionId,
242 270 draft: {
243 271 open: $("open").checked,
244 272 grounds: draft.grounds,
@@ -250,10 +278,126 @@ function saveSelectedChunk ()
250 278 return true;
251 279 }
252 280
281 function isSelectedDimensionSoftDeleted ()
282 {
283 const record = dimensionsById.get(selectedDimensionId);
284 return record?.deletedAt != null;
285 }
286
287 function formatPurgeHint (record)
288 {
289 if (!record?.purgeAfter)
290 { return "Soft-deleted — painting disabled."; }
291 const when = new Date(record.purgeAfter);
292 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
293 }
294
295 function syncDimensionUi ()
296 {
297 const record = dimensionsById.get(selectedDimensionId);
298 const softDeleted = record?.deletedAt != null;
299 const hint = $("dimension-purge-hint");
300 if (hint)
301 {
302 hint.hidden = !softDeleted;
303 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
304 }
305 const openToggle = $("open");
306 if (openToggle)
307 { openToggle.disabled = softDeleted; }
308 dimensionCombo?.setValue(selectedDimensionId);
309 dimensionSettings?.refresh();
310 syncSaveButton();
311 }
312
313 function applyDimensionsList (payload)
314 {
315 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
316 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
317 if (!dimensionsById.has(OVERWORLD_ID))
318 {
319 dimensionsById.set(OVERWORLD_ID, {
320 dimensionId: OVERWORLD_ID,
321 displayName: "Overworld",
322 lightingMode: "dayNight",
323 seasonMode: "auto",
324 defaultGroundTypeId: 1,
325 deletedAt: null,
326 purgeAfter: null
327 });
328 }
329 const options = [...dimensionsById.values()].map((dim) => ({
330 id: dim.dimensionId,
331 label: dim.displayName || dim.dimensionId,
332 disabled: dim.deletedAt != null,
333 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
334 }));
335 dimensionCombo?.setOptions(options);
336 const createdId = pendingCreatedDimensionId;
337 pendingCreatedDimensionId = null;
338 if (createdId && dimensionsById.has(createdId))
339 {
340 setRevisionState({
341 activeRevisionId: payload.activeRevisionId,
342 pendingRevisionId: payload.pendingRevisionId
343 });
344 selectDimension(createdId, { force: true });
345 return;
346 }
347 if (!dimensionsById.has(selectedDimensionId))
348 { selectedDimensionId = OVERWORLD_ID; }
349 setRevisionState({
350 activeRevisionId: payload.activeRevisionId,
351 pendingRevisionId: payload.pendingRevisionId
352 });
353 syncDimensionUi();
354 if (!isDraftDirty())
355 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
356 }
357
358 function requestDimensions ()
359 {
360 socket.send({ type: MessageType.editorListDimensions });
361 }
362
363 function selectDimension (dimensionId, { force = false } = {})
364 {
365 const nextId = normalizeDimensionId(dimensionId);
366 if (!force && nextId === selectedDimensionId)
367 { return; }
368 if (!force && isDraftDirty())
369 {
370 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
371 dimensionCombo?.setValue(selectedDimensionId);
372 return;
373 }
374 selectedDimensionId = nextId;
375 syncDimensionUi();
376 clearNeighborhoodView();
377 doLoadNeighborhood(chunkX, chunkY);
378 }
379
380 function clearNeighborhoodView ()
381 {
382 draft = null;
383 draftBaseline = null;
384 if (!view)
385 { return; }
386 for (const key of [...view.chunks.keys()])
387 {
388 const [x, y] = key.split(",").map(Number);
389 view.removeChunk(x, y);
390 }
391 view.clearEditorSpawners?.();
392 syncSaveButton();
393 }
394
253 395 function paintAt (localX, localY)
254 396 {
255 397 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
256 398 { return; }
399 if (isSelectedDimensionSoftDeleted())
400 { return; }
257 401 const index = localY * CHUNK_SIZE + localX;
258 402 const state = placeableToolState();
259 403 if (tool.kind === "ground")
@@ -300,7 +444,16 @@ function paintAt (localX, localY)
300 444 : state;
301 445 if (def?.id === BlockType.flower)
302 446 { nextState = flowerBlockState(randomFlowerColorId()); }
303 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
447 const config = def?.id === BlockType.doorway
448 ? {
449 targetDimensionId: selectedDimensionId,
450 tileX: chunkX * CHUNK_SIZE + localX,
451 tileY: chunkY * CHUNK_SIZE + localY
452 }
453 : null;
454 if (def?.id === BlockType.doorway && !nextState)
455 { nextState = "door"; }
456 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
304 457 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
305 458 ground: draft.grounds[index],
306 459 block: draft.blocks[index],
@@ -395,7 +548,7 @@ function showSelectedChunk (payload)
395 548 activeRevisionId: payload.activeRevisionId,
396 549 pendingRevisionId: payload.pendingRevisionId
397 550 });
398 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
551 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
399 552 const log = $("changelog");
400 553 log.innerHTML = "";
401 554 for (const entry of payload.changelog ?? [])
@@ -420,6 +573,13 @@ function showSelectedChunk (payload)
420 573 const next = pendingNavigate;
421 574 navigateAfterSave = false;
422 575 pendingNavigate = null;
576 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
577 if (nextDim !== selectedDimensionId)
578 {
579 selectedDimensionId = nextDim;
580 syncDimensionUi();
581 clearNeighborhoodView();
582 }
423 583 doLoadNeighborhood(next.chunkX, next.chunkY);
424 584 }
425 585 }
@@ -505,7 +665,12 @@ function requestChunks (coords)
505 665 {
506 666 for (const coord of coords)
507 667 {
508 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
668 socket.send({
669 type: MessageType.editorLoadChunk,
670 chunkX: coord.chunkX,
671 chunkY: coord.chunkY,
672 dimensionId: selectedDimensionId
673 });
509 674 }
510 675 }
511 676
@@ -521,7 +686,7 @@ function loadNeighborhood (x, y)
521 686 {
522 687 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
523 688 {
524 showUnsavedModal({ chunkX: x, chunkY: y });
689 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
525 690 return;
526 691 }
527 692 doLoadNeighborhood(x, y);
@@ -537,11 +702,30 @@ function anyModalOpen ()
537 702 return settingsModal?.isOpen()
538 703 || paletteModal?.isOpen()
539 704 || tileConfigModal?.isOpen()
705 || questsModal?.isOpen()
706 || dialoguesModal?.isOpen()
540 707 || !$("unsaved-chunk-modal")?.hidden;
541 708 }
542 709
543 function updateTooltip (local)
710 function updateHoverStatus (local)
544 711 {
712 const el = $("hover-status-text");
713 if (!el)
714 { return; }
715 if (!local)
716 {
717 el.textContent = "Hover a tile for coordinates";
718 return;
719 }
720 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
721 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
722 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
723 }
724
725 function updateTooltip (local, options = {})
726 {
727 if (!options.keepStatus)
728 { updateHoverStatus(local); }
545 729 const tip = $("tile-tooltip");
546 730 if (!tip || !local || !draft)
547 731 {
@@ -636,10 +820,44 @@ async function main ()
636 820 });
637 821
638 822 tileConfigModal = initTileConfigModal({
823 socket: {
824 send (payload)
825 {
826 socket?.send(payload);
827 }
828 },
829 MessageType,
830 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
831 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
832 id: dim.dimensionId,
833 label: dim.displayName || dim.dimensionId,
834 disabled: !!dim.deletedAt,
835 hint: dim.deletedAt ? "soft-deleted" : undefined
836 })),
639 837 onSave (ctx, config)
640 838 {
641 839 if (!draft)
642 840 { return; }
841 if (ctx.kind === "doorway")
842 {
843 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
844 draft.blocks[index] = {
845 typeId: BlockType.doorway,
846 state: config.state || "door",
847 config: {
848 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
849 tileX: Number(config.tileX) || 0,
850 tileY: Number(config.tileY) || 0
851 }
852 };
853 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
854 ground: draft.grounds[index],
855 block: draft.blocks[index],
856 light: draft.light[index]
857 });
858 afterDraftMutation();
859 return;
860 }
643 861 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
644 862 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
645 863 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -649,6 +867,18 @@ async function main ()
649 867 {
650 868 if (!draft)
651 869 { return; }
870 if (ctx.kind === "doorway")
871 {
872 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
873 draft.blocks[index] = null;
874 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
875 ground: draft.grounds[index],
876 block: draft.blocks[index],
877 light: draft.light[index]
878 });
879 afterDraftMutation();
880 return;
881 }
652 882 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
653 883 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
654 884 afterDraftMutation();
@@ -669,6 +899,16 @@ async function main ()
669 899 const tile = view.screenToTile(mouseX, mouseY);
670 900 const localX = tile.tileX - chunkX * CHUNK_SIZE;
671 901 const localY = tile.tileY - chunkY * CHUNK_SIZE;
902 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
903 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
904 updateHoverStatus({
905 tileX: tile.tileX,
906 tileY: tile.tileY,
907 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
908 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
909 chunkX: hoverChunkX,
910 chunkY: hoverChunkY
911 });
672 912 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
673 913 {
674 914 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
@@ -679,8 +919,9 @@ async function main ()
679 919 }
680 920 else
681 921 {
922 hoverLocal = null;
682 923 view.clearTilePreview();
683 updateTooltip(null);
924 updateTooltip(null, { keepStatus: true });
684 925 }
685 926 }
686 927 else
@@ -700,12 +941,27 @@ async function main ()
700 941 {
701 942 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
702 943 socket.send({ type: MessageType.editorLoadSettings });
944 requestDimensions();
703 945 loadNeighborhood(0, 0);
704 946 }
705 947 else if (message.type === MessageType.editorSettings)
706 948 { settingsModal.handleMessage(message); }
949 else if (message.type === MessageType.editorDimensions)
950 {
951 applyDimensionsList(message);
952 }
953 else if (message.type === MessageType.editorQuests)
954 { questsModal?.handleMessage(message); }
955 else if (message.type === MessageType.editorDialogues)
956 {
957 dialoguesModal?.handleMessage(message);
958 tileConfigModal?.handleMessage(message);
959 }
707 960 else if (message.type === MessageType.editorChunk)
708 961 {
962 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
963 if (msgDim !== selectedDimensionId)
964 { return; }
709 965 if (message.settings)
710 966 { view.setSettings(message.settings); }
711 967 if (!inEditorView(message.chunkX, message.chunkY))
@@ -729,12 +985,15 @@ async function main ()
729 985 const status = $("apply-status");
730 986 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
731 987 status.className = "hint ok";
988 requestDimensions();
732 989 requestChunks(neighborhoodCoords(chunkX, chunkY));
733 990 }
734 991 else if (message.type === MessageType.error)
735 992 {
736 993 $("error").textContent = message.message;
994 pendingCreatedDimensionId = null;
737 995 navigateAfterSave = false;
996 dimensionCombo?.setValue(selectedDimensionId);
738 997 if (applyInFlight)
739 998 {
740 999 applyInFlight = false;
@@ -758,6 +1017,37 @@ async function main ()
758 1017 $("night-label").textContent = Number(hour).toFixed(1);
759 1018 }
760 1019 });
1020 dimensionCombo = createDimensionCombobox({
1021 root: $("dimension-combo"),
1022 allowCreate: true,
1023 placeholder: "Search or create dimension…",
1024 onSelect (id)
1025 {
1026 selectDimension(id);
1027 },
1028 onCreate (rawId)
1029 {
1030 const id = normalizeDimensionId(rawId);
1031 $("error").textContent = "";
1032 pendingCreatedDimensionId = id;
1033 socket.send({
1034 type: MessageType.editorCreateDimension,
1035 dimensionId: id,
1036 displayName: rawId.trim()
1037 });
1038 }
1039 });
1040 dimensionSettings = initDimensionSettings({
1041 socket,
1042 MessageType,
1043 GROUND_DEFINITIONS,
1044 OVERWORLD_ID,
1045 getSelectedDimensionId: () => selectedDimensionId,
1046 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1047 isOverworld
1048 });
1049 questsModal = initQuestsModal({ socket, MessageType });
1050 dialoguesModal = initDialoguesModal({ socket, MessageType });
761 1051 game.startGame();
762 1052 await socket.connect();
763 1053 }
@@ -775,6 +1065,11 @@ $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
775 1065 $("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
776 1066 $("open").addEventListener("change", () =>
777 1067 {
1068 if (isSelectedDimensionSoftDeleted())
1069 {
1070 $("open").checked = !!draft?.open;
1071 return;
1072 }
778 1073 if (draft)
779 1074 {
780 1075 draft.open = $("open").checked;
@@ -804,8 +1099,16 @@ $("unsaved-chunk-discard")?.addEventListener("click", () =>
804 1099 hideUnsavedModal();
805 1100 pendingNavigate = null;
806 1101 navigateAfterSave = false;
807 if (next)
808 { doLoadNeighborhood(next.chunkX, next.chunkY); }
1102 if (!next)
1103 { return; }
1104 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1105 if (nextDim !== selectedDimensionId)
1106 {
1107 selectedDimensionId = nextDim;
1108 syncDimensionUi();
1109 clearNeighborhoodView();
1110 }
1111 doLoadNeighborhood(next.chunkX, next.chunkY);
809 1112 });
810 1113 $("unsaved-chunk-save")?.addEventListener("click", () =>
811 1114 {
@@ -819,7 +1122,16 @@ $("unsaved-chunk-save")?.addEventListener("click", () =>
819 1122 const next = pendingNavigate;
820 1123 pendingNavigate = null;
821 1124 if (next)
822 { doLoadNeighborhood(next.chunkX, next.chunkY); }
1125 {
1126 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1127 if (nextDim !== selectedDimensionId)
1128 {
1129 selectedDimensionId = nextDim;
1130 syncDimensionUi();
1131 clearNeighborhoodView();
1132 }
1133 doLoadNeighborhood(next.chunkX, next.chunkY);
1134 }
823 1135 }
824 1136 });
825 1137 $("apply").addEventListener("click", () =>
@@ -919,15 +1231,30 @@ document.addEventListener("contextmenu", (event) =>
919 1231 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
920 1232 { return; }
921 1233 const spawner = spawnerAt(localX, localY);
922 if (!spawner)
923 { return; }
924 tileConfigModal.openSpawner({
925 localX,
926 localY,
927 tileX: tile.tileX,
928 tileY: tile.tileY,
929 config: { ...spawner.config }
930 });
1234 if (spawner)
1235 {
1236 tileConfigModal.openSpawner({
1237 localX,
1238 localY,
1239 tileX: tile.tileX,
1240 tileY: tile.tileY,
1241 config: { ...spawner.config }
1242 });
1243 return;
1244 }
1245 const index = localY * CHUNK_SIZE + localX;
1246 const block = draft.blocks[index];
1247 if (block?.typeId === BlockType.doorway)
1248 {
1249 tileConfigModal.openDoorway({
1250 localX,
1251 localY,
1252 tileX: tile.tileX,
1253 tileY: tile.tileY,
1254 state: block.state ?? "door",
1255 config: block.config ? { ...block.config } : {}
1256 });
1257 }
931 1258 });
932 1259
933 1260 main().catch((error) =>
@@ -27,9 +27,17 @@ import {
27import { GameSocket, defaultSocketUrl } from "../net/socket.js";
27import { GameSocket, defaultSocketUrl } from "../net/socket.js";
28import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
28import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
29import { WorldView } from "../render/worldView.js";
29import { WorldView } from "../render/worldView.js";
30import { initSettingsModal } from "./settingsModal.js";
30import { initSettingsModal, initDimensionSettings } from "./settingsModal.js";
31import { initPaletteModal } from "./paletteModal.js";
31import { initPaletteModal } from "./paletteModal.js";
32import { initTileConfigModal } from "./tileConfigModal.js";
32import { initTileConfigModal } from "./tileConfigModal.js";
33import { initQuestsModal } from "./questsModal.js";
34import { initDialoguesModal } from "./dialoguesModal.js";
35import { createDimensionCombobox } from "./dimensionCombobox.js";
36import {
37 OVERWORLD_ID,
38 normalizeDimensionId,
39 isOverworld
40} from "/shared/world/dimensions.js";
33
41
34const game = new Game();
42const game = new Game();
35let socket;
43let socket;
@@ -38,16 +46,25 @@ let view;
38let draft = null;
46let draft = null;
39/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
47/** @type {string|null} JSON snapshot of last loaded/saved draft (grounds/blocks/spawners/open). */
40let draftBaseline = null;
48let draftBaseline = null;
41/** @type {{ chunkX: number, chunkY: number }|null} */
49/** @type {{ chunkX: number, chunkY: number, dimensionId?: string }|null} */
42let pendingNavigate = null;
50let pendingNavigate = null;
43/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
51/** When true, next matching editorChunk after save should navigate to pendingNavigate. */
44let navigateAfterSave = false;
52let navigateAfterSave = false;
45let chunkX = 0;
53let chunkX = 0;
46let chunkY = 0;
54let chunkY = 0;
55let selectedDimensionId = OVERWORLD_ID;
56/** @type {string|null} */
57let pendingCreatedDimensionId = null;
58/** @type {Map<string, object>} */
59let dimensionsById = new Map();
60let dimensionCombo = null;
61let dimensionSettings = null;
47let tool = { kind: "ground", typeId: GroundType.grass, state: null };
62let tool = { kind: "ground", typeId: GroundType.grass, state: null };
48let settingsModal;
63let settingsModal;
49let paletteModal;
64let paletteModal;
50let tileConfigModal;
65let tileConfigModal;
66let questsModal;
67let dialoguesModal;
51let catalog = { grounds: {}, blocks: {}, images: [] };
68let catalog = { grounds: {}, blocks: {}, images: [] };
52let imageUrlByName = new Map();
69let imageUrlByName = new Map();
53let hoverLocal = null;
70let hoverLocal = null;
@@ -204,10 +221,15 @@ function syncSaveButton ()
204 const btn = $("save");
221 const btn = $("save");
205 if (!btn)
222 if (!btn)
206 { return; }
223 { return; }
224 const softDeleted = isSelectedDimensionSoftDeleted();
207 const dirty = isDraftDirty();
225 const dirty = isDraftDirty();
208 btn.disabled = !dirty;
226 btn.disabled = !dirty || softDeleted;
209 btn.classList.toggle("save-dirty", dirty);
227 btn.classList.toggle("save-dirty", dirty && !softDeleted);
210 btn.title = dirty ? "Save unsaved chunk changes" : "No unsaved changes";
228 btn.title = softDeleted
229 ? "Cannot save while this dimension is soft-deleted"
230 : dirty
231 ? "Save unsaved chunk changes"
232 : "No unsaved changes";
211}
233}
212
234
213function afterDraftMutation ()
235function afterDraftMutation ()
@@ -232,6 +254,11 @@ function saveSelectedChunk ()
232{
254{
233 if (!draft || !isDraftDirty())
255 if (!draft || !isDraftDirty())
234 { return false; }
256 { return false; }
257 if (isSelectedDimensionSoftDeleted())
258 {
259 $("error").textContent = "Cannot save while this dimension is soft-deleted.";
260 return false;
261 }
235 $("error").textContent = "";
262 $("error").textContent = "";
236 $("apply-status").textContent = "";
263 $("apply-status").textContent = "";
237 $("apply-status").className = "hint";
264 $("apply-status").className = "hint";
@@ -239,6 +266,7 @@ function saveSelectedChunk ()
239 type: MessageType.editorSaveChunk,
266 type: MessageType.editorSaveChunk,
240 chunkX,
267 chunkX,
241 chunkY,
268 chunkY,
269 dimensionId: selectedDimensionId,
242 draft: {
270 draft: {
243 open: $("open").checked,
271 open: $("open").checked,
244 grounds: draft.grounds,
272 grounds: draft.grounds,
@@ -250,10 +278,126 @@ function saveSelectedChunk ()
250 return true;
278 return true;
251}
279}
252
280
281function isSelectedDimensionSoftDeleted ()
282{
283 const record = dimensionsById.get(selectedDimensionId);
284 return record?.deletedAt != null;
285}
286
287function formatPurgeHint (record)
288{
289 if (!record?.purgeAfter)
290 { return "Soft-deleted — painting disabled."; }
291 const when = new Date(record.purgeAfter);
292 return `Soft-deleted — purges ${when.toLocaleString()} (painting disabled).`;
293}
294
295function syncDimensionUi ()
296{
297 const record = dimensionsById.get(selectedDimensionId);
298 const softDeleted = record?.deletedAt != null;
299 const hint = $("dimension-purge-hint");
300 if (hint)
301 {
302 hint.hidden = !softDeleted;
303 hint.textContent = softDeleted ? formatPurgeHint(record) : "";
304 }
305 const openToggle = $("open");
306 if (openToggle)
307 { openToggle.disabled = softDeleted; }
308 dimensionCombo?.setValue(selectedDimensionId);
309 dimensionSettings?.refresh();
310 syncSaveButton();
311}
312
313function applyDimensionsList (payload)
314{
315 const list = Array.isArray(payload?.dimensions) ? payload.dimensions : [];
316 dimensionsById = new Map(list.map((dim) => [dim.dimensionId, dim]));
317 if (!dimensionsById.has(OVERWORLD_ID))
318 {
319 dimensionsById.set(OVERWORLD_ID, {
320 dimensionId: OVERWORLD_ID,
321 displayName: "Overworld",
322 lightingMode: "dayNight",
323 seasonMode: "auto",
324 defaultGroundTypeId: 1,
325 deletedAt: null,
326 purgeAfter: null
327 });
328 }
329 const options = [...dimensionsById.values()].map((dim) => ({
330 id: dim.dimensionId,
331 label: dim.displayName || dim.dimensionId,
332 disabled: dim.deletedAt != null,
333 hint: dim.deletedAt != null ? formatPurgeHint(dim) : null
334 }));
335 dimensionCombo?.setOptions(options);
336 const createdId = pendingCreatedDimensionId;
337 pendingCreatedDimensionId = null;
338 if (createdId && dimensionsById.has(createdId))
339 {
340 setRevisionState({
341 activeRevisionId: payload.activeRevisionId,
342 pendingRevisionId: payload.pendingRevisionId
343 });
344 selectDimension(createdId, { force: true });
345 return;
346 }
347 if (!dimensionsById.has(selectedDimensionId))
348 { selectedDimensionId = OVERWORLD_ID; }
349 setRevisionState({
350 activeRevisionId: payload.activeRevisionId,
351 pendingRevisionId: payload.pendingRevisionId
352 });
353 syncDimensionUi();
354 if (!isDraftDirty())
355 { requestChunks(neighborhoodCoords(chunkX, chunkY)); }
356}
357
358function requestDimensions ()
359{
360 socket.send({ type: MessageType.editorListDimensions });
361}
362
363function selectDimension (dimensionId, { force = false } = {})
364{
365 const nextId = normalizeDimensionId(dimensionId);
366 if (!force && nextId === selectedDimensionId)
367 { return; }
368 if (!force && isDraftDirty())
369 {
370 showUnsavedModal({ chunkX, chunkY, dimensionId: nextId });
371 dimensionCombo?.setValue(selectedDimensionId);
372 return;
373 }
374 selectedDimensionId = nextId;
375 syncDimensionUi();
376 clearNeighborhoodView();
377 doLoadNeighborhood(chunkX, chunkY);
378}
379
380function clearNeighborhoodView ()
381{
382 draft = null;
383 draftBaseline = null;
384 if (!view)
385 { return; }
386 for (const key of [...view.chunks.keys()])
387 {
388 const [x, y] = key.split(",").map(Number);
389 view.removeChunk(x, y);
390 }
391 view.clearEditorSpawners?.();
392 syncSaveButton();
393}
394
253function paintAt (localX, localY)
395function paintAt (localX, localY)
254{
396{
255 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
397 if (!draft || localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
256 { return; }
398 { return; }
399 if (isSelectedDimensionSoftDeleted())
400 { return; }
257 const index = localY * CHUNK_SIZE + localX;
401 const index = localY * CHUNK_SIZE + localX;
258 const state = placeableToolState();
402 const state = placeableToolState();
259 if (tool.kind === "ground")
403 if (tool.kind === "ground")
@@ -300,7 +444,16 @@ function paintAt (localX, localY)
300 : state;
444 : state;
301 if (def?.id === BlockType.flower)
445 if (def?.id === BlockType.flower)
302 { nextState = flowerBlockState(randomFlowerColorId()); }
446 { nextState = flowerBlockState(randomFlowerColorId()); }
303 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config: null };
447 const config = def?.id === BlockType.doorway
448 ? {
449 targetDimensionId: selectedDimensionId,
450 tileX: chunkX * CHUNK_SIZE + localX,
451 tileY: chunkY * CHUNK_SIZE + localY
452 }
453 : null;
454 if (def?.id === BlockType.doorway && !nextState)
455 { nextState = "door"; }
456 draft.blocks[index] = { typeId: tool.typeId, state: nextState, config };
304 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
457 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
305 ground: draft.grounds[index],
458 ground: draft.grounds[index],
306 block: draft.blocks[index],
459 block: draft.blocks[index],
@@ -395,7 +548,7 @@ function showSelectedChunk (payload)
395 activeRevisionId: payload.activeRevisionId,
548 activeRevisionId: payload.activeRevisionId,
396 pendingRevisionId: payload.pendingRevisionId
549 pendingRevisionId: payload.pendingRevisionId
397 });
550 });
398 $("authored").textContent = payload.authored ? "authored" : "default grass (closed until saved open)";
551 $("authored").textContent = payload.authored ? "authored" : "unauthored (dimension default ground)";
399 const log = $("changelog");
552 const log = $("changelog");
400 log.innerHTML = "";
553 log.innerHTML = "";
401 for (const entry of payload.changelog ?? [])
554 for (const entry of payload.changelog ?? [])
@@ -420,6 +573,13 @@ function showSelectedChunk (payload)
420 const next = pendingNavigate;
573 const next = pendingNavigate;
421 navigateAfterSave = false;
574 navigateAfterSave = false;
422 pendingNavigate = null;
575 pendingNavigate = null;
576 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
577 if (nextDim !== selectedDimensionId)
578 {
579 selectedDimensionId = nextDim;
580 syncDimensionUi();
581 clearNeighborhoodView();
582 }
423 doLoadNeighborhood(next.chunkX, next.chunkY);
583 doLoadNeighborhood(next.chunkX, next.chunkY);
424 }
584 }
425}
585}
@@ -505,7 +665,12 @@ function requestChunks (coords)
505{
665{
506 for (const coord of coords)
666 for (const coord of coords)
507 {
667 {
508 socket.send({ type: MessageType.editorLoadChunk, chunkX: coord.chunkX, chunkY: coord.chunkY });
668 socket.send({
669 type: MessageType.editorLoadChunk,
670 chunkX: coord.chunkX,
671 chunkY: coord.chunkY,
672 dimensionId: selectedDimensionId
673 });
509 }
674 }
510}
675}
511
676
@@ -521,7 +686,7 @@ function loadNeighborhood (x, y)
521{
686{
522 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
687 if ((x !== chunkX || y !== chunkY) && isDraftDirty())
523 {
688 {
524 showUnsavedModal({ chunkX: x, chunkY: y });
689 showUnsavedModal({ chunkX: x, chunkY: y, dimensionId: selectedDimensionId });
525 return;
690 return;
526 }
691 }
527 doLoadNeighborhood(x, y);
692 doLoadNeighborhood(x, y);
@@ -537,11 +702,30 @@ function anyModalOpen ()
537 return settingsModal?.isOpen()
702 return settingsModal?.isOpen()
538 || paletteModal?.isOpen()
703 || paletteModal?.isOpen()
539 || tileConfigModal?.isOpen()
704 || tileConfigModal?.isOpen()
705 || questsModal?.isOpen()
706 || dialoguesModal?.isOpen()
540 || !$("unsaved-chunk-modal")?.hidden;
707 || !$("unsaved-chunk-modal")?.hidden;
541}
708}
542
709
543function updateTooltip (local)
710function updateHoverStatus (local)
544{
711{
712 const el = $("hover-status-text");
713 if (!el)
714 { return; }
715 if (!local)
716 {
717 el.textContent = "Hover a tile for coordinates";
718 return;
719 }
720 const hoverChunkX = local.chunkX ?? Math.floor(local.tileX / CHUNK_SIZE);
721 const hoverChunkY = local.chunkY ?? Math.floor(local.tileY / CHUNK_SIZE);
722 el.textContent = `Tile (${local.tileX}, ${local.tileY}) · Chunk (${hoverChunkX}, ${hoverChunkY})`;
723}
724
725function updateTooltip (local, options = {})
726{
727 if (!options.keepStatus)
728 { updateHoverStatus(local); }
545 const tip = $("tile-tooltip");
729 const tip = $("tile-tooltip");
546 if (!tip || !local || !draft)
730 if (!tip || !local || !draft)
547 {
731 {
@@ -636,10 +820,44 @@ async function main ()
636 });
820 });
637
821
638 tileConfigModal = initTileConfigModal({
822 tileConfigModal = initTileConfigModal({
823 socket: {
824 send (payload)
825 {
826 socket?.send(payload);
827 }
828 },
829 MessageType,
830 getDialogues: () => dialoguesModal?.getDialogues?.() ?? [],
831 getDimensionOptions: () => [...dimensionsById.values()].map((dim) => ({
832 id: dim.dimensionId,
833 label: dim.displayName || dim.dimensionId,
834 disabled: !!dim.deletedAt,
835 hint: dim.deletedAt ? "soft-deleted" : undefined
836 })),
639 onSave (ctx, config)
837 onSave (ctx, config)
640 {
838 {
641 if (!draft)
839 if (!draft)
642 { return; }
840 { return; }
841 if (ctx.kind === "doorway")
842 {
843 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
844 draft.blocks[index] = {
845 typeId: BlockType.doorway,
846 state: config.state || "door",
847 config: {
848 targetDimensionId: normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID),
849 tileX: Number(config.tileX) || 0,
850 tileY: Number(config.tileY) || 0
851 }
852 };
853 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
854 ground: draft.grounds[index],
855 block: draft.blocks[index],
856 light: draft.light[index]
857 });
858 afterDraftMutation();
859 return;
860 }
643 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
861 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
644 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
862 draft.spawners.push({ localX: ctx.localX, localY: ctx.localY, config });
645 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
863 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
@@ -649,6 +867,18 @@ async function main ()
649 {
867 {
650 if (!draft)
868 if (!draft)
651 { return; }
869 { return; }
870 if (ctx.kind === "doorway")
871 {
872 const index = ctx.localY * CHUNK_SIZE + ctx.localX;
873 draft.blocks[index] = null;
874 view.updateAuthoredTile(chunkX, chunkY, ctx.localX, ctx.localY, {
875 ground: draft.grounds[index],
876 block: draft.blocks[index],
877 light: draft.light[index]
878 });
879 afterDraftMutation();
880 return;
881 }
652 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
882 draft.spawners = (draft.spawners ?? []).filter((s) => s.localX !== ctx.localX || s.localY !== ctx.localY);
653 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
883 syncSpawnersOverlay(chunkX, chunkY, draft.spawners);
654 afterDraftMutation();
884 afterDraftMutation();
@@ -669,6 +899,16 @@ async function main ()
669 const tile = view.screenToTile(mouseX, mouseY);
899 const tile = view.screenToTile(mouseX, mouseY);
670 const localX = tile.tileX - chunkX * CHUNK_SIZE;
900 const localX = tile.tileX - chunkX * CHUNK_SIZE;
671 const localY = tile.tileY - chunkY * CHUNK_SIZE;
901 const localY = tile.tileY - chunkY * CHUNK_SIZE;
902 const hoverChunkX = Math.floor(tile.tileX / CHUNK_SIZE);
903 const hoverChunkY = Math.floor(tile.tileY / CHUNK_SIZE);
904 updateHoverStatus({
905 tileX: tile.tileX,
906 tileY: tile.tileY,
907 x: ((tile.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
908 y: ((tile.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE,
909 chunkX: hoverChunkX,
910 chunkY: hoverChunkY
911 });
672 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
912 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
673 {
913 {
674 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
914 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
@@ -679,8 +919,9 @@ async function main ()
679 }
919 }
680 else
920 else
681 {
921 {
922 hoverLocal = null;
682 view.clearTilePreview();
923 view.clearTilePreview();
683 updateTooltip(null);
924 updateTooltip(null, { keepStatus: true });
684 }
925 }
685 }
926 }
686 else
927 else
@@ -700,12 +941,27 @@ async function main ()
700 {
941 {
701 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
942 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
702 socket.send({ type: MessageType.editorLoadSettings });
943 socket.send({ type: MessageType.editorLoadSettings });
944 requestDimensions();
703 loadNeighborhood(0, 0);
945 loadNeighborhood(0, 0);
704 }
946 }
705 else if (message.type === MessageType.editorSettings)
947 else if (message.type === MessageType.editorSettings)
706 { settingsModal.handleMessage(message); }
948 { settingsModal.handleMessage(message); }
949 else if (message.type === MessageType.editorDimensions)
950 {
951 applyDimensionsList(message);
952 }
953 else if (message.type === MessageType.editorQuests)
954 { questsModal?.handleMessage(message); }
955 else if (message.type === MessageType.editorDialogues)
956 {
957 dialoguesModal?.handleMessage(message);
958 tileConfigModal?.handleMessage(message);
959 }
707 else if (message.type === MessageType.editorChunk)
960 else if (message.type === MessageType.editorChunk)
708 {
961 {
962 const msgDim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
963 if (msgDim !== selectedDimensionId)
964 { return; }
709 if (message.settings)
965 if (message.settings)
710 { view.setSettings(message.settings); }
966 { view.setSettings(message.settings); }
711 if (!inEditorView(message.chunkX, message.chunkY))
967 if (!inEditorView(message.chunkX, message.chunkY))
@@ -729,12 +985,15 @@ async function main ()
729 const status = $("apply-status");
985 const status = $("apply-status");
730 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
986 status.textContent = `Applied revision ${message.appliedRevisionId}. Live world reloaded.`;
731 status.className = "hint ok";
987 status.className = "hint ok";
988 requestDimensions();
732 requestChunks(neighborhoodCoords(chunkX, chunkY));
989 requestChunks(neighborhoodCoords(chunkX, chunkY));
733 }
990 }
734 else if (message.type === MessageType.error)
991 else if (message.type === MessageType.error)
735 {
992 {
736 $("error").textContent = message.message;
993 $("error").textContent = message.message;
994 pendingCreatedDimensionId = null;
737 navigateAfterSave = false;
995 navigateAfterSave = false;
996 dimensionCombo?.setValue(selectedDimensionId);
738 if (applyInFlight)
997 if (applyInFlight)
739 {
998 {
740 applyInFlight = false;
999 applyInFlight = false;
@@ -758,6 +1017,37 @@ async function main ()
758 $("night-label").textContent = Number(hour).toFixed(1);
1017 $("night-label").textContent = Number(hour).toFixed(1);
759 }
1018 }
760 });
1019 });
1020 dimensionCombo = createDimensionCombobox({
1021 root: $("dimension-combo"),
1022 allowCreate: true,
1023 placeholder: "Search or create dimension…",
1024 onSelect (id)
1025 {
1026 selectDimension(id);
1027 },
1028 onCreate (rawId)
1029 {
1030 const id = normalizeDimensionId(rawId);
1031 $("error").textContent = "";
1032 pendingCreatedDimensionId = id;
1033 socket.send({
1034 type: MessageType.editorCreateDimension,
1035 dimensionId: id,
1036 displayName: rawId.trim()
1037 });
1038 }
1039 });
1040 dimensionSettings = initDimensionSettings({
1041 socket,
1042 MessageType,
1043 GROUND_DEFINITIONS,
1044 OVERWORLD_ID,
1045 getSelectedDimensionId: () => selectedDimensionId,
1046 getDimensionRecord: (id) => dimensionsById.get(id) ?? null,
1047 isOverworld
1048 });
1049 questsModal = initQuestsModal({ socket, MessageType });
1050 dialoguesModal = initDialoguesModal({ socket, MessageType });
761 game.startGame();
1051 game.startGame();
762 await socket.connect();
1052 await socket.connect();
763}
1053}
@@ -775,6 +1065,11 @@ $("west").addEventListener("click", () => loadNeighborhood(chunkX - 1, chunkY));
775$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
1065$("east").addEventListener("click", () => loadNeighborhood(chunkX + 1, chunkY));
776$("open").addEventListener("change", () =>
1066$("open").addEventListener("change", () =>
777{
1067{
1068 if (isSelectedDimensionSoftDeleted())
1069 {
1070 $("open").checked = !!draft?.open;
1071 return;
1072 }
778 if (draft)
1073 if (draft)
779 {
1074 {
780 draft.open = $("open").checked;
1075 draft.open = $("open").checked;
@@ -804,8 +1099,16 @@ $("unsaved-chunk-discard")?.addEventListener("click", () =>
804 hideUnsavedModal();
1099 hideUnsavedModal();
805 pendingNavigate = null;
1100 pendingNavigate = null;
806 navigateAfterSave = false;
1101 navigateAfterSave = false;
807 if (next)
1102 if (!next)
808 { doLoadNeighborhood(next.chunkX, next.chunkY); }
1103 { return; }
1104 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1105 if (nextDim !== selectedDimensionId)
1106 {
1107 selectedDimensionId = nextDim;
1108 syncDimensionUi();
1109 clearNeighborhoodView();
1110 }
1111 doLoadNeighborhood(next.chunkX, next.chunkY);
809});
1112});
810$("unsaved-chunk-save")?.addEventListener("click", () =>
1113$("unsaved-chunk-save")?.addEventListener("click", () =>
811{
1114{
@@ -819,7 +1122,16 @@ $("unsaved-chunk-save")?.addEventListener("click", () =>
819 const next = pendingNavigate;
1122 const next = pendingNavigate;
820 pendingNavigate = null;
1123 pendingNavigate = null;
821 if (next)
1124 if (next)
822 { doLoadNeighborhood(next.chunkX, next.chunkY); }
1125 {
1126 const nextDim = next.dimensionId != null ? normalizeDimensionId(next.dimensionId) : selectedDimensionId;
1127 if (nextDim !== selectedDimensionId)
1128 {
1129 selectedDimensionId = nextDim;
1130 syncDimensionUi();
1131 clearNeighborhoodView();
1132 }
1133 doLoadNeighborhood(next.chunkX, next.chunkY);
1134 }
823 }
1135 }
824});
1136});
825$("apply").addEventListener("click", () =>
1137$("apply").addEventListener("click", () =>
@@ -919,15 +1231,30 @@ document.addEventListener("contextmenu", (event) =>
919 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
1231 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
920 { return; }
1232 { return; }
921 const spawner = spawnerAt(localX, localY);
1233 const spawner = spawnerAt(localX, localY);
922 if (!spawner)
1234 if (spawner)
923 { return; }
1235 {
924 tileConfigModal.openSpawner({
1236 tileConfigModal.openSpawner({
925 localX,
1237 localX,
926 localY,
1238 localY,
927 tileX: tile.tileX,
1239 tileX: tile.tileX,
928 tileY: tile.tileY,
1240 tileY: tile.tileY,
929 config: { ...spawner.config }
1241 config: { ...spawner.config }
930 });
1242 });
1243 return;
1244 }
1245 const index = localY * CHUNK_SIZE + localX;
1246 const block = draft.blocks[index];
1247 if (block?.typeId === BlockType.doorway)
1248 {
1249 tileConfigModal.openDoorway({
1250 localX,
1251 localY,
1252 tileX: tile.tileX,
1253 tileY: tile.tileY,
1254 state: block.state ?? "door",
1255 config: block.config ? { ...block.config } : {}
1256 });
1257 }
931});
1258});
932
1259
933main().catch((error) =>
1260main().catch((error) =>
client/src/editor/questsModal.js added +536 −0
@@ -0,0 +1,536 @@
1 import { normalizeQuestDef } from "/shared/quests/normalize.js";
2 import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
3
4 const SIMPLE_KINDS = [
5 ConditionKind.hasItem,
6 ConditionKind.questState,
7 ConditionKind.dialogueHeard,
8 ConditionKind.killCount,
9 ConditionKind.atTile,
10 ConditionKind.inDimension,
11 ConditionKind.hasVisitedDimension
12 ];
13
14 export function initQuestsModal ({ socket, MessageType })
15 {
16 const backdrop = document.getElementById("quests-backdrop");
17 const modal = document.getElementById("quests-modal");
18 const listEl = document.getElementById("quests-list");
19 const editorEl = document.getElementById("quests-editor");
20 const saveBtn = document.getElementById("quests-save");
21 const deleteBtn = document.getElementById("quests-delete");
22 let open = false;
23 /** @type {ReturnType<typeof normalizeQuestDef>[]} */
24 let quests = [];
25 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
26 let draft = null;
27 let selectedId = null;
28
29 function show (visible)
30 {
31 open = visible;
32 backdrop.hidden = !visible;
33 modal.hidden = !visible;
34 if (!visible)
35 {
36 draft = null;
37 selectedId = null;
38 }
39 }
40
41 function selectQuest (questId)
42 {
43 const found = quests.find((q) => q.questId === questId);
44 if (!found)
45 {
46 draft = null;
47 selectedId = null;
48 render();
49 return;
50 }
51 selectedId = found.questId;
52 draft = structuredClone(found);
53 render();
54 }
55
56 function renderList ()
57 {
58 listEl.replaceChildren();
59 for (const quest of quests)
60 {
61 const btn = document.createElement("button");
62 btn.type = "button";
63 btn.textContent = quest.title || quest.questId;
64 if (quest.questId === selectedId)
65 { btn.classList.add("active"); }
66 btn.addEventListener("click", () => selectQuest(quest.questId));
67 listEl.append(btn);
68 }
69 }
70
71 function renderEditor ()
72 {
73 editorEl.replaceChildren();
74 saveBtn.disabled = !draft;
75 deleteBtn.disabled = !draft;
76 if (!draft)
77 {
78 const hint = document.createElement("p");
79 hint.className = "content-editor-hint";
80 hint.textContent = "Select a quest or create a new one.";
81 editorEl.append(hint);
82 return;
83 }
84
85 editorEl.append(
86 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
87 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
88 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
89 );
90
91 const stepsHeader = sectionHeader("Steps", () =>
92 {
93 draft.steps.push({
94 stepId: `step-${draft.steps.length + 1}`,
95 title: "New step",
96 description: "",
97 completionJournalText: "",
98 objectives: [{
99 objectiveId: "obj-1",
100 text: "Complete this step",
101 when: emptyConditionSet()
102 }],
103 onEnter: [],
104 onComplete: []
105 });
106 renderEditor();
107 });
108 editorEl.append(stepsHeader);
109
110 draft.steps.forEach((step, stepIndex) =>
111 {
112 const box = document.createElement("div");
113 box.className = "content-editor-section";
114 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
115 {
116 draft.steps.splice(stepIndex, 1);
117 if (draft.steps.length === 0)
118 {
119 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
120 }
121 renderEditor();
122 });
123 box.append(head);
124 box.append(
125 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
126 field("Title", textInput(step.title, (v) => { step.title = v; })),
127 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
128 field("Completion journal", textArea(step.completionJournalText, (v) =>
129 {
130 step.completionJournalText = v;
131 }, 2))
132 );
133
134 const objHead = sectionHeader("Objectives", () =>
135 {
136 step.objectives.push({
137 objectiveId: `obj-${step.objectives.length + 1}`,
138 text: "New objective",
139 when: emptyConditionSet()
140 });
141 renderEditor();
142 });
143 box.append(objHead);
144
145 step.objectives.forEach((obj, objIndex) =>
146 {
147 const objBox = document.createElement("div");
148 objBox.className = "content-editor-section";
149 objBox.append(
150 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
151 {
152 step.objectives.splice(objIndex, 1);
153 if (step.objectives.length === 0)
154 {
155 step.objectives.push({
156 objectiveId: "obj-1",
157 text: "Complete this step",
158 when: emptyConditionSet()
159 });
160 }
161 renderEditor();
162 }),
163 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
164 );
165 objBox.append(renderConditionSet(obj.when, (next) =>
166 {
167 obj.when = next;
168 renderEditor();
169 }));
170 box.append(objBox);
171 });
172 editorEl.append(box);
173 });
174 }
175
176 function render ()
177 {
178 renderList();
179 renderEditor();
180 }
181
182 document.getElementById("open-quests").addEventListener("click", () =>
183 {
184 socket.send({ type: MessageType.editorLoadQuests });
185 show(true);
186 render();
187 });
188 document.getElementById("quests-close").addEventListener("click", () => show(false));
189 backdrop.addEventListener("click", () => show(false));
190 document.getElementById("quests-new").addEventListener("click", () =>
191 {
192 const base = normalizeQuestDef({
193 questId: `quest-${quests.length + 1}`,
194 title: "New quest",
195 description: ""
196 });
197 draft = structuredClone(base);
198 selectedId = null;
199 render();
200 });
201 saveBtn.addEventListener("click", () =>
202 {
203 if (!draft)
204 { return; }
205 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
206 });
207 deleteBtn.addEventListener("click", () =>
208 {
209 if (!draft?.questId)
210 { return; }
211 if (!window.confirm(`Delete quest "${draft.questId}"?`))
212 { return; }
213 socket.send({ type: MessageType.editorDeleteQuest, questId: draft.questId });
214 });
215
216 return {
217 isOpen: () => open,
218 handleMessage (message)
219 {
220 if (message.type !== MessageType.editorQuests)
221 { return; }
222 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
223 if (draft)
224 {
225 const still = quests.find((q) => q.questId === draft.questId);
226 if (still)
227 {
228 selectedId = still.questId;
229 draft = structuredClone(still);
230 }
231 else if (selectedId)
232 {
233 draft = null;
234 selectedId = null;
235 }
236 }
237 if (open)
238 { render(); }
239 }
240 };
241 }
242
243 function field (label, input)
244 {
245 const wrap = document.createElement("label");
246 wrap.append(document.createTextNode(label), input);
247 return wrap;
248 }
249
250 function textInput (value, onChange)
251 {
252 const input = document.createElement("input");
253 input.type = "text";
254 input.value = value ?? "";
255 input.addEventListener("input", () => onChange(input.value));
256 return input;
257 }
258
259 function textArea (value, onChange, rows = 3)
260 {
261 const input = document.createElement("textarea");
262 input.rows = rows;
263 input.value = value ?? "";
264 input.addEventListener("input", () => onChange(input.value));
265 return input;
266 }
267
268 function sectionHeader (title, onAdd, onRemove)
269 {
270 const head = document.createElement("div");
271 head.className = "content-editor-section-header";
272 const strong = document.createElement("strong");
273 strong.textContent = title;
274 head.append(strong);
275 const actions = document.createElement("div");
276 actions.className = "content-editor-row";
277 if (onAdd)
278 {
279 const add = document.createElement("button");
280 add.type = "button";
281 add.textContent = "+";
282 add.title = "Add";
283 add.addEventListener("click", onAdd);
284 actions.append(add);
285 }
286 if (onRemove)
287 {
288 const remove = document.createElement("button");
289 remove.type = "button";
290 remove.textContent = "×";
291 remove.title = "Remove";
292 remove.addEventListener("click", onRemove);
293 actions.append(remove);
294 }
295 head.append(actions);
296 return head;
297 }
298
299 function renderConditionSet (when, onChange)
300 {
301 const wrap = document.createElement("div");
302 const set = normalizeConditionSet(when);
303 const title = document.createElement("strong");
304 title.textContent = "When (all of)";
305 wrap.append(title);
306
307 set.all.forEach((clause, index) =>
308 {
309 const row = document.createElement("div");
310 row.className = "content-editor-clause";
311 const notLabel = document.createElement("label");
312 const notBox = document.createElement("input");
313 notBox.type = "checkbox";
314 notBox.checked = !!clause.not;
315 notBox.addEventListener("change", () =>
316 {
317 set.all[index].not = notBox.checked;
318 onChange(set);
319 });
320 notLabel.append(notBox, document.createTextNode(" NOT"));
321 row.append(notLabel);
322
323 const kind = document.createElement("select");
324 for (const k of SIMPLE_KINDS)
325 {
326 const opt = document.createElement("option");
327 opt.value = k;
328 opt.textContent = k;
329 if ((clause.condition?.kind ?? "") === k)
330 { opt.selected = true; }
331 kind.append(opt);
332 }
333 const otherOpt = document.createElement("option");
334 otherOpt.value = "__other__";
335 otherOpt.textContent = "(other / JSON)";
336 if (!SIMPLE_KINDS.includes(clause.condition?.kind))
337 { otherOpt.selected = true; }
338 kind.append(otherOpt);
339 kind.addEventListener("change", () =>
340 {
341 if (kind.value === "__other__")
342 { return; }
343 set.all[index].condition = defaultCondition(kind.value);
344 onChange(set);
345 });
346 row.append(kind);
347
348 const cond = clause.condition ?? { kind: ConditionKind.hasItem };
349 if (cond.kind === ConditionKind.hasItem)
350 {
351 row.append(miniField("itemId", cond.itemId ?? "", (v) =>
352 {
353 cond.itemId = Number(v) || 0;
354 set.all[index].condition = cond;
355 onChange(set);
356 }));
357 row.append(miniField("qty", cond.quantity ?? 1, (v) =>
358 {
359 cond.quantity = Number(v) || 1;
360 set.all[index].condition = cond;
361 onChange(set);
362 }));
363 }
364 else if (cond.kind === ConditionKind.questState)
365 {
366 row.append(miniField("questId", cond.questId ?? "", (v) =>
367 {
368 cond.questId = v;
369 set.all[index].condition = cond;
370 onChange(set);
371 }));
372 row.append(miniField("state", cond.state ?? "not-started", (v) =>
373 {
374 const n = Number(v);
375 cond.state = Number.isFinite(n) && String(n) === String(v).trim() ? n : v;
376 set.all[index].condition = cond;
377 onChange(set);
378 }));
379 }
380 else if (cond.kind === ConditionKind.dialogueHeard)
381 {
382 row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>
383 {
384 cond.dialogueId = v;
385 set.all[index].condition = cond;
386 onChange(set);
387 }));
388 row.append(miniField("stepId", cond.stepId ?? "", (v) =>
389 {
390 cond.stepId = v;
391 set.all[index].condition = cond;
392 onChange(set);
393 }));
394 }
395 else if (cond.kind === ConditionKind.killCount)
396 {
397 row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) =>
398 {
399 cond.mobTypeId = v || undefined;
400 set.all[index].condition = cond;
401 onChange(set);
402 }));
403 row.append(miniField("count", cond.count ?? 1, (v) =>
404 {
405 cond.count = Number(v) || 1;
406 set.all[index].condition = cond;
407 onChange(set);
408 }));
409 }
410 else if (cond.kind === ConditionKind.atTile)
411 {
412 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
413 {
414 cond.dimensionId = String(v || "overworld");
415 set.all[index].condition = cond;
416 onChange(set);
417 }));
418 row.append(miniField("tileX", cond.tileX ?? 0, (v) =>
419 {
420 cond.tileX = Number(v) | 0;
421 set.all[index].condition = cond;
422 onChange(set);
423 }));
424 row.append(miniField("tileY", cond.tileY ?? 0, (v) =>
425 {
426 cond.tileY = Number(v) | 0;
427 set.all[index].condition = cond;
428 onChange(set);
429 }));
430 }
431 else if (
432 cond.kind === ConditionKind.inDimension
433 || cond.kind === ConditionKind.hasVisitedDimension
434 )
435 {
436 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
437 {
438 cond.dimensionId = String(v || "overworld");
439 set.all[index].condition = cond;
440 onChange(set);
441 }));
442 }
443 else
444 {
445 const json = document.createElement("textarea");
446 json.rows = 3;
447 json.value = JSON.stringify(cond, null, 2);
448 json.addEventListener("change", () =>
449 {
450 try
451 {
452 set.all[index].condition = JSON.parse(json.value);
453 onChange(set);
454 }
455 catch
456 { /* keep typing */ }
457 });
458 row.append(json);
459 }
460
461 const remove = document.createElement("button");
462 remove.type = "button";
463 remove.textContent = "×";
464 remove.addEventListener("click", () =>
465 {
466 set.all.splice(index, 1);
467 onChange(set);
468 });
469 row.append(remove);
470 wrap.append(row);
471 });
472
473 const add = document.createElement("button");
474 add.type = "button";
475 add.textContent = "Add clause";
476 add.addEventListener("click", () =>
477 {
478 set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });
479 onChange(set);
480 });
481 wrap.append(add);
482
483 const jsonFallback = document.createElement("details");
484 const summary = document.createElement("summary");
485 summary.textContent = "Edit condition set as JSON";
486 const area = document.createElement("textarea");
487 area.rows = 5;
488 area.value = JSON.stringify(set, null, 2);
489 area.addEventListener("change", () =>
490 {
491 try
492 {
493 onChange(normalizeConditionSet(JSON.parse(area.value)));
494 }
495 catch
496 { /* ignore */ }
497 });
498 jsonFallback.append(summary, area);
499 wrap.append(jsonFallback);
500 return wrap;
501 }
502
503 function miniField (label, value, onChange)
504 {
505 const wrap = document.createElement("label");
506 wrap.textContent = `${label} `;
507 const input = document.createElement("input");
508 input.type = "text";
509 input.value = String(value ?? "");
510 input.style.width = "7rem";
511 input.addEventListener("input", () => onChange(input.value));
512 wrap.append(input);
513 return wrap;
514 }
515
516 function defaultCondition (kind)
517 {
518 switch (kind)
519 {
520 case ConditionKind.hasItem:
521 return { kind, itemId: 1, quantity: 1 };
522 case ConditionKind.questState:
523 return { kind, questId: "", state: "not-started" };
524 case ConditionKind.dialogueHeard:
525 return { kind, dialogueId: "", stepId: "" };
526 case ConditionKind.killCount:
527 return { kind, mobTypeId: "deer", count: 1 };
528 case ConditionKind.atTile:
529 return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 };
530 case ConditionKind.inDimension:
531 case ConditionKind.hasVisitedDimension:
532 return { kind, dimensionId: "overworld" };
533 default:
534 return { kind };
535 }
536 }
@@ -0,0 +1,536 @@
1import { normalizeQuestDef } from "/shared/quests/normalize.js";
2import { ConditionKind, emptyConditionSet, normalizeConditionSet } from "/shared/quests/conditions.js";
3
4const SIMPLE_KINDS = [
5 ConditionKind.hasItem,
6 ConditionKind.questState,
7 ConditionKind.dialogueHeard,
8 ConditionKind.killCount,
9 ConditionKind.atTile,
10 ConditionKind.inDimension,
11 ConditionKind.hasVisitedDimension
12];
13
14export function initQuestsModal ({ socket, MessageType })
15{
16 const backdrop = document.getElementById("quests-backdrop");
17 const modal = document.getElementById("quests-modal");
18 const listEl = document.getElementById("quests-list");
19 const editorEl = document.getElementById("quests-editor");
20 const saveBtn = document.getElementById("quests-save");
21 const deleteBtn = document.getElementById("quests-delete");
22 let open = false;
23 /** @type {ReturnType<typeof normalizeQuestDef>[]} */
24 let quests = [];
25 /** @type {ReturnType<typeof normalizeQuestDef>|null} */
26 let draft = null;
27 let selectedId = null;
28
29 function show (visible)
30 {
31 open = visible;
32 backdrop.hidden = !visible;
33 modal.hidden = !visible;
34 if (!visible)
35 {
36 draft = null;
37 selectedId = null;
38 }
39 }
40
41 function selectQuest (questId)
42 {
43 const found = quests.find((q) => q.questId === questId);
44 if (!found)
45 {
46 draft = null;
47 selectedId = null;
48 render();
49 return;
50 }
51 selectedId = found.questId;
52 draft = structuredClone(found);
53 render();
54 }
55
56 function renderList ()
57 {
58 listEl.replaceChildren();
59 for (const quest of quests)
60 {
61 const btn = document.createElement("button");
62 btn.type = "button";
63 btn.textContent = quest.title || quest.questId;
64 if (quest.questId === selectedId)
65 { btn.classList.add("active"); }
66 btn.addEventListener("click", () => selectQuest(quest.questId));
67 listEl.append(btn);
68 }
69 }
70
71 function renderEditor ()
72 {
73 editorEl.replaceChildren();
74 saveBtn.disabled = !draft;
75 deleteBtn.disabled = !draft;
76 if (!draft)
77 {
78 const hint = document.createElement("p");
79 hint.className = "content-editor-hint";
80 hint.textContent = "Select a quest or create a new one.";
81 editorEl.append(hint);
82 return;
83 }
84
85 editorEl.append(
86 field("Quest id", textInput(draft.questId, (v) => { draft.questId = v; })),
87 field("Title", textInput(draft.title, (v) => { draft.title = v; })),
88 field("Description", textArea(draft.description, (v) => { draft.description = v; }, 3))
89 );
90
91 const stepsHeader = sectionHeader("Steps", () =>
92 {
93 draft.steps.push({
94 stepId: `step-${draft.steps.length + 1}`,
95 title: "New step",
96 description: "",
97 completionJournalText: "",
98 objectives: [{
99 objectiveId: "obj-1",
100 text: "Complete this step",
101 when: emptyConditionSet()
102 }],
103 onEnter: [],
104 onComplete: []
105 });
106 renderEditor();
107 });
108 editorEl.append(stepsHeader);
109
110 draft.steps.forEach((step, stepIndex) =>
111 {
112 const box = document.createElement("div");
113 box.className = "content-editor-section";
114 const head = sectionHeader(`Step ${stepIndex + 1}`, null, () =>
115 {
116 draft.steps.splice(stepIndex, 1);
117 if (draft.steps.length === 0)
118 {
119 draft.steps.push(normalizeQuestDef({ questId: draft.questId }).steps[0]);
120 }
121 renderEditor();
122 });
123 box.append(head);
124 box.append(
125 field("stepId", textInput(step.stepId, (v) => { step.stepId = v; })),
126 field("Title", textInput(step.title, (v) => { step.title = v; })),
127 field("Description", textArea(step.description, (v) => { step.description = v; }, 2)),
128 field("Completion journal", textArea(step.completionJournalText, (v) =>
129 {
130 step.completionJournalText = v;
131 }, 2))
132 );
133
134 const objHead = sectionHeader("Objectives", () =>
135 {
136 step.objectives.push({
137 objectiveId: `obj-${step.objectives.length + 1}`,
138 text: "New objective",
139 when: emptyConditionSet()
140 });
141 renderEditor();
142 });
143 box.append(objHead);
144
145 step.objectives.forEach((obj, objIndex) =>
146 {
147 const objBox = document.createElement("div");
148 objBox.className = "content-editor-section";
149 objBox.append(
150 sectionHeader(`Objective ${objIndex + 1}`, null, () =>
151 {
152 step.objectives.splice(objIndex, 1);
153 if (step.objectives.length === 0)
154 {
155 step.objectives.push({
156 objectiveId: "obj-1",
157 text: "Complete this step",
158 when: emptyConditionSet()
159 });
160 }
161 renderEditor();
162 }),
163 field("Text", textInput(obj.text, (v) => { obj.text = v; }))
164 );
165 objBox.append(renderConditionSet(obj.when, (next) =>
166 {
167 obj.when = next;
168 renderEditor();
169 }));
170 box.append(objBox);
171 });
172 editorEl.append(box);
173 });
174 }
175
176 function render ()
177 {
178 renderList();
179 renderEditor();
180 }
181
182 document.getElementById("open-quests").addEventListener("click", () =>
183 {
184 socket.send({ type: MessageType.editorLoadQuests });
185 show(true);
186 render();
187 });
188 document.getElementById("quests-close").addEventListener("click", () => show(false));
189 backdrop.addEventListener("click", () => show(false));
190 document.getElementById("quests-new").addEventListener("click", () =>
191 {
192 const base = normalizeQuestDef({
193 questId: `quest-${quests.length + 1}`,
194 title: "New quest",
195 description: ""
196 });
197 draft = structuredClone(base);
198 selectedId = null;
199 render();
200 });
201 saveBtn.addEventListener("click", () =>
202 {
203 if (!draft)
204 { return; }
205 socket.send({ type: MessageType.editorSaveQuest, quest: draft });
206 });
207 deleteBtn.addEventListener("click", () =>
208 {
209 if (!draft?.questId)
210 { return; }
211 if (!window.confirm(`Delete quest "${draft.questId}"?`))
212 { return; }
213 socket.send({ type: MessageType.editorDeleteQuest, questId: draft.questId });
214 });
215
216 return {
217 isOpen: () => open,
218 handleMessage (message)
219 {
220 if (message.type !== MessageType.editorQuests)
221 { return; }
222 quests = (message.quests ?? []).map((q) => normalizeQuestDef(q));
223 if (draft)
224 {
225 const still = quests.find((q) => q.questId === draft.questId);
226 if (still)
227 {
228 selectedId = still.questId;
229 draft = structuredClone(still);
230 }
231 else if (selectedId)
232 {
233 draft = null;
234 selectedId = null;
235 }
236 }
237 if (open)
238 { render(); }
239 }
240 };
241}
242
243function field (label, input)
244{
245 const wrap = document.createElement("label");
246 wrap.append(document.createTextNode(label), input);
247 return wrap;
248}
249
250function textInput (value, onChange)
251{
252 const input = document.createElement("input");
253 input.type = "text";
254 input.value = value ?? "";
255 input.addEventListener("input", () => onChange(input.value));
256 return input;
257}
258
259function textArea (value, onChange, rows = 3)
260{
261 const input = document.createElement("textarea");
262 input.rows = rows;
263 input.value = value ?? "";
264 input.addEventListener("input", () => onChange(input.value));
265 return input;
266}
267
268function sectionHeader (title, onAdd, onRemove)
269{
270 const head = document.createElement("div");
271 head.className = "content-editor-section-header";
272 const strong = document.createElement("strong");
273 strong.textContent = title;
274 head.append(strong);
275 const actions = document.createElement("div");
276 actions.className = "content-editor-row";
277 if (onAdd)
278 {
279 const add = document.createElement("button");
280 add.type = "button";
281 add.textContent = "+";
282 add.title = "Add";
283 add.addEventListener("click", onAdd);
284 actions.append(add);
285 }
286 if (onRemove)
287 {
288 const remove = document.createElement("button");
289 remove.type = "button";
290 remove.textContent = "×";
291 remove.title = "Remove";
292 remove.addEventListener("click", onRemove);
293 actions.append(remove);
294 }
295 head.append(actions);
296 return head;
297}
298
299function renderConditionSet (when, onChange)
300{
301 const wrap = document.createElement("div");
302 const set = normalizeConditionSet(when);
303 const title = document.createElement("strong");
304 title.textContent = "When (all of)";
305 wrap.append(title);
306
307 set.all.forEach((clause, index) =>
308 {
309 const row = document.createElement("div");
310 row.className = "content-editor-clause";
311 const notLabel = document.createElement("label");
312 const notBox = document.createElement("input");
313 notBox.type = "checkbox";
314 notBox.checked = !!clause.not;
315 notBox.addEventListener("change", () =>
316 {
317 set.all[index].not = notBox.checked;
318 onChange(set);
319 });
320 notLabel.append(notBox, document.createTextNode(" NOT"));
321 row.append(notLabel);
322
323 const kind = document.createElement("select");
324 for (const k of SIMPLE_KINDS)
325 {
326 const opt = document.createElement("option");
327 opt.value = k;
328 opt.textContent = k;
329 if ((clause.condition?.kind ?? "") === k)
330 { opt.selected = true; }
331 kind.append(opt);
332 }
333 const otherOpt = document.createElement("option");
334 otherOpt.value = "__other__";
335 otherOpt.textContent = "(other / JSON)";
336 if (!SIMPLE_KINDS.includes(clause.condition?.kind))
337 { otherOpt.selected = true; }
338 kind.append(otherOpt);
339 kind.addEventListener("change", () =>
340 {
341 if (kind.value === "__other__")
342 { return; }
343 set.all[index].condition = defaultCondition(kind.value);
344 onChange(set);
345 });
346 row.append(kind);
347
348 const cond = clause.condition ?? { kind: ConditionKind.hasItem };
349 if (cond.kind === ConditionKind.hasItem)
350 {
351 row.append(miniField("itemId", cond.itemId ?? "", (v) =>
352 {
353 cond.itemId = Number(v) || 0;
354 set.all[index].condition = cond;
355 onChange(set);
356 }));
357 row.append(miniField("qty", cond.quantity ?? 1, (v) =>
358 {
359 cond.quantity = Number(v) || 1;
360 set.all[index].condition = cond;
361 onChange(set);
362 }));
363 }
364 else if (cond.kind === ConditionKind.questState)
365 {
366 row.append(miniField("questId", cond.questId ?? "", (v) =>
367 {
368 cond.questId = v;
369 set.all[index].condition = cond;
370 onChange(set);
371 }));
372 row.append(miniField("state", cond.state ?? "not-started", (v) =>
373 {
374 const n = Number(v);
375 cond.state = Number.isFinite(n) && String(n) === String(v).trim() ? n : v;
376 set.all[index].condition = cond;
377 onChange(set);
378 }));
379 }
380 else if (cond.kind === ConditionKind.dialogueHeard)
381 {
382 row.append(miniField("dialogueId", cond.dialogueId ?? "", (v) =>
383 {
384 cond.dialogueId = v;
385 set.all[index].condition = cond;
386 onChange(set);
387 }));
388 row.append(miniField("stepId", cond.stepId ?? "", (v) =>
389 {
390 cond.stepId = v;
391 set.all[index].condition = cond;
392 onChange(set);
393 }));
394 }
395 else if (cond.kind === ConditionKind.killCount)
396 {
397 row.append(miniField("mobTypeId", cond.mobTypeId ?? "", (v) =>
398 {
399 cond.mobTypeId = v || undefined;
400 set.all[index].condition = cond;
401 onChange(set);
402 }));
403 row.append(miniField("count", cond.count ?? 1, (v) =>
404 {
405 cond.count = Number(v) || 1;
406 set.all[index].condition = cond;
407 onChange(set);
408 }));
409 }
410 else if (cond.kind === ConditionKind.atTile)
411 {
412 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
413 {
414 cond.dimensionId = String(v || "overworld");
415 set.all[index].condition = cond;
416 onChange(set);
417 }));
418 row.append(miniField("tileX", cond.tileX ?? 0, (v) =>
419 {
420 cond.tileX = Number(v) | 0;
421 set.all[index].condition = cond;
422 onChange(set);
423 }));
424 row.append(miniField("tileY", cond.tileY ?? 0, (v) =>
425 {
426 cond.tileY = Number(v) | 0;
427 set.all[index].condition = cond;
428 onChange(set);
429 }));
430 }
431 else if (
432 cond.kind === ConditionKind.inDimension
433 || cond.kind === ConditionKind.hasVisitedDimension
434 )
435 {
436 row.append(miniField("dimensionId", cond.dimensionId ?? "overworld", (v) =>
437 {
438 cond.dimensionId = String(v || "overworld");
439 set.all[index].condition = cond;
440 onChange(set);
441 }));
442 }
443 else
444 {
445 const json = document.createElement("textarea");
446 json.rows = 3;
447 json.value = JSON.stringify(cond, null, 2);
448 json.addEventListener("change", () =>
449 {
450 try
451 {
452 set.all[index].condition = JSON.parse(json.value);
453 onChange(set);
454 }
455 catch
456 { /* keep typing */ }
457 });
458 row.append(json);
459 }
460
461 const remove = document.createElement("button");
462 remove.type = "button";
463 remove.textContent = "×";
464 remove.addEventListener("click", () =>
465 {
466 set.all.splice(index, 1);
467 onChange(set);
468 });
469 row.append(remove);
470 wrap.append(row);
471 });
472
473 const add = document.createElement("button");
474 add.type = "button";
475 add.textContent = "Add clause";
476 add.addEventListener("click", () =>
477 {
478 set.all.push({ not: false, condition: defaultCondition(ConditionKind.hasItem) });
479 onChange(set);
480 });
481 wrap.append(add);
482
483 const jsonFallback = document.createElement("details");
484 const summary = document.createElement("summary");
485 summary.textContent = "Edit condition set as JSON";
486 const area = document.createElement("textarea");
487 area.rows = 5;
488 area.value = JSON.stringify(set, null, 2);
489 area.addEventListener("change", () =>
490 {
491 try
492 {
493 onChange(normalizeConditionSet(JSON.parse(area.value)));
494 }
495 catch
496 { /* ignore */ }
497 });
498 jsonFallback.append(summary, area);
499 wrap.append(jsonFallback);
500 return wrap;
501}
502
503function miniField (label, value, onChange)
504{
505 const wrap = document.createElement("label");
506 wrap.textContent = `${label} `;
507 const input = document.createElement("input");
508 input.type = "text";
509 input.value = String(value ?? "");
510 input.style.width = "7rem";
511 input.addEventListener("input", () => onChange(input.value));
512 wrap.append(input);
513 return wrap;
514}
515
516function defaultCondition (kind)
517{
518 switch (kind)
519 {
520 case ConditionKind.hasItem:
521 return { kind, itemId: 1, quantity: 1 };
522 case ConditionKind.questState:
523 return { kind, questId: "", state: "not-started" };
524 case ConditionKind.dialogueHeard:
525 return { kind, dialogueId: "", stepId: "" };
526 case ConditionKind.killCount:
527 return { kind, mobTypeId: "deer", count: 1 };
528 case ConditionKind.atTile:
529 return { kind, dimensionId: "overworld", tileX: 0, tileY: 0 };
530 case ConditionKind.inDimension:
531 case ConditionKind.hasVisitedDimension:
532 return { kind, dimensionId: "overworld" };
533 default:
534 return { kind };
535 }
536}
client/src/editor/settingsModal.js +110 −0
@@ -717,3 +717,113 @@ function escapeHtml (text)
717 717 .replaceAll(">", "&gt;")
718 718 .replaceAll("\"", "&quot;");
719 719 }
720
721 /**
722 * Aside panel for the selected dimension's lighting / season / ground / soft-delete.
723 */
724 export function initDimensionSettings ({
725 socket,
726 MessageType,
727 GROUND_DEFINITIONS,
728 OVERWORLD_ID,
729 getSelectedDimensionId,
730 getDimensionRecord,
731 isOverworld
732 })
733 {
734 const displayName = document.getElementById("dim-display-name");
735 const lighting = document.getElementById("dim-lighting");
736 const season = document.getElementById("dim-season");
737 const ground = document.getElementById("dim-default-ground");
738 const saveBtn = document.getElementById("dim-save");
739 const deleteBtn = document.getElementById("dim-delete");
740 const cancelBtn = document.getElementById("dim-cancel-delete");
741 const panel = document.getElementById("dimension-settings");
742
743 if (ground && !ground.options.length)
744 {
745 for (const def of Object.values(GROUND_DEFINITIONS))
746 {
747 const opt = document.createElement("option");
748 opt.value = String(def.id);
749 opt.textContent = def.displayName;
750 ground.append(opt);
751 }
752 }
753
754 function refresh ()
755 {
756 const id = getSelectedDimensionId?.() ?? OVERWORLD_ID;
757 const record = getDimensionRecord?.(id);
758 const overworld = isOverworld?.(id) ?? id === OVERWORLD_ID;
759 const softDeleted = record?.deletedAt != null;
760 if (panel)
761 { panel.hidden = false; }
762 if (displayName)
763 {
764 displayName.value = record?.displayName ?? id;
765 displayName.disabled = softDeleted;
766 }
767 if (lighting)
768 {
769 lighting.value = record?.lightingMode ?? "dayNight";
770 lighting.disabled = softDeleted;
771 }
772 if (season)
773 {
774 season.value = record?.seasonMode ?? "auto";
775 season.disabled = softDeleted;
776 }
777 if (ground)
778 {
779 ground.value = String(record?.defaultGroundTypeId ?? 1);
780 ground.disabled = softDeleted;
781 }
782 if (saveBtn)
783 { saveBtn.disabled = softDeleted; }
784 if (deleteBtn)
785 {
786 deleteBtn.hidden = overworld || softDeleted;
787 deleteBtn.disabled = overworld;
788 }
789 if (cancelBtn)
790 { cancelBtn.hidden = !softDeleted; }
791 }
792
793 saveBtn?.addEventListener("click", () =>
794 {
795 const id = getSelectedDimensionId?.();
796 if (!id)
797 { return; }
798 socket.send({
799 type: MessageType.editorSaveDimension,
800 dimension: {
801 dimensionId: id,
802 displayName: displayName?.value?.trim() || id,
803 lightingMode: lighting?.value,
804 seasonMode: season?.value,
805 defaultGroundTypeId: Number(ground?.value) || 1
806 }
807 });
808 });
809
810 deleteBtn?.addEventListener("click", () =>
811 {
812 const id = getSelectedDimensionId?.();
813 if (!id || isOverworld?.(id))
814 { return; }
815 if (!window.confirm(`Soft-delete dimension «${id}»? Chunks remain until purge.`))
816 { return; }
817 socket.send({ type: MessageType.editorSoftDeleteDimension, dimensionId: id });
818 });
819
820 cancelBtn?.addEventListener("click", () =>
821 {
822 const id = getSelectedDimensionId?.();
823 if (!id)
824 { return; }
825 socket.send({ type: MessageType.editorCancelDimensionDeletion, dimensionId: id });
826 });
827
828 return { refresh };
829 }
@@ -717,3 +717,113 @@ function escapeHtml (text)
717 .replaceAll(">", "&gt;")
717 .replaceAll(">", "&gt;")
718 .replaceAll("\"", "&quot;");
718 .replaceAll("\"", "&quot;");
719}
719}
720
721/**
722 * Aside panel for the selected dimension's lighting / season / ground / soft-delete.
723 */
724export function initDimensionSettings ({
725 socket,
726 MessageType,
727 GROUND_DEFINITIONS,
728 OVERWORLD_ID,
729 getSelectedDimensionId,
730 getDimensionRecord,
731 isOverworld
732})
733{
734 const displayName = document.getElementById("dim-display-name");
735 const lighting = document.getElementById("dim-lighting");
736 const season = document.getElementById("dim-season");
737 const ground = document.getElementById("dim-default-ground");
738 const saveBtn = document.getElementById("dim-save");
739 const deleteBtn = document.getElementById("dim-delete");
740 const cancelBtn = document.getElementById("dim-cancel-delete");
741 const panel = document.getElementById("dimension-settings");
742
743 if (ground && !ground.options.length)
744 {
745 for (const def of Object.values(GROUND_DEFINITIONS))
746 {
747 const opt = document.createElement("option");
748 opt.value = String(def.id);
749 opt.textContent = def.displayName;
750 ground.append(opt);
751 }
752 }
753
754 function refresh ()
755 {
756 const id = getSelectedDimensionId?.() ?? OVERWORLD_ID;
757 const record = getDimensionRecord?.(id);
758 const overworld = isOverworld?.(id) ?? id === OVERWORLD_ID;
759 const softDeleted = record?.deletedAt != null;
760 if (panel)
761 { panel.hidden = false; }
762 if (displayName)
763 {
764 displayName.value = record?.displayName ?? id;
765 displayName.disabled = softDeleted;
766 }
767 if (lighting)
768 {
769 lighting.value = record?.lightingMode ?? "dayNight";
770 lighting.disabled = softDeleted;
771 }
772 if (season)
773 {
774 season.value = record?.seasonMode ?? "auto";
775 season.disabled = softDeleted;
776 }
777 if (ground)
778 {
779 ground.value = String(record?.defaultGroundTypeId ?? 1);
780 ground.disabled = softDeleted;
781 }
782 if (saveBtn)
783 { saveBtn.disabled = softDeleted; }
784 if (deleteBtn)
785 {
786 deleteBtn.hidden = overworld || softDeleted;
787 deleteBtn.disabled = overworld;
788 }
789 if (cancelBtn)
790 { cancelBtn.hidden = !softDeleted; }
791 }
792
793 saveBtn?.addEventListener("click", () =>
794 {
795 const id = getSelectedDimensionId?.();
796 if (!id)
797 { return; }
798 socket.send({
799 type: MessageType.editorSaveDimension,
800 dimension: {
801 dimensionId: id,
802 displayName: displayName?.value?.trim() || id,
803 lightingMode: lighting?.value,
804 seasonMode: season?.value,
805 defaultGroundTypeId: Number(ground?.value) || 1
806 }
807 });
808 });
809
810 deleteBtn?.addEventListener("click", () =>
811 {
812 const id = getSelectedDimensionId?.();
813 if (!id || isOverworld?.(id))
814 { return; }
815 if (!window.confirm(`Soft-delete dimension «${id}»? Chunks remain until purge.`))
816 { return; }
817 socket.send({ type: MessageType.editorSoftDeleteDimension, dimensionId: id });
818 });
819
820 cancelBtn?.addEventListener("click", () =>
821 {
822 const id = getSelectedDimensionId?.();
823 if (!id)
824 { return; }
825 socket.send({ type: MessageType.editorCancelDimensionDeletion, dimensionId: id });
826 });
827
828 return { refresh };
829}
client/src/editor/tileConfigModal.js +138 −4
@@ -1,5 +1,5 @@
1 1 /**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
2 * Right-click config modal for editor tiles that have configurable data (spawners, doorways).
3 3 */
4 4 import {
5 5 listSpawnableMobTypes,
@@ -16,6 +16,10 @@ import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/def
16 16 import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17 17 import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
18 18 import { normalizeRgb } from "/shared/render/tint.js";
19 import { createDimensionCombobox } from "./dimensionCombobox.js";
20 import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
21
22 const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
19 23
20 24 /** Items that can be worn in a given equipment slot. */
21 25 export function listEquippableItemsForSlot (slot)
@@ -68,7 +72,14 @@ function rgbToCss (color)
68 72 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
69 73 }
70 74
71 export function initTileConfigModal ({ onSave, onRemove })
75 export function initTileConfigModal ({
76 onSave,
77 onRemove,
78 socket,
79 MessageType,
80 getDialogues,
81 getDimensionOptions
82 })
72 83 {
73 84 const backdrop = document.getElementById("tile-config-backdrop");
74 85 const modal = document.getElementById("tile-config-modal");
@@ -101,6 +112,11 @@ export function initTileConfigModal ({ onSave, onRemove })
101 112 let itemSearchMode = null;
102 113 /** @type {string|null} */
103 114 let dyeEditSlot = null;
115 /** @type {{ dialogueId: string, label: string, unique?: boolean }[]} */
116 let dialogueOptions = [];
117 let pendingDialogueId = null;
118 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
119 let doorwayDimCombo = null;
104 120
105 121 function show (visible)
106 122 {
@@ -110,6 +126,7 @@ export function initTileConfigModal ({ onSave, onRemove })
110 126 if (!visible)
111 127 {
112 128 context = null;
129 doorwayDimCombo = null;
113 130 closeItemSearch();
114 131 closeDyePicker();
115 132 }
@@ -425,6 +442,8 @@ export function initTileConfigModal ({ onSave, onRemove })
425 442 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
426 443 wrap.append(aggressiveHint);
427 444
445 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
446
428 447 const equipHeader = document.createElement("div");
429 448 equipHeader.className = "spawner-sells-header";
430 449 const equipTitle = document.createElement("strong");
@@ -648,6 +667,10 @@ export function initTileConfigModal ({ onSave, onRemove })
648 667 {
649 668 context = { kind: "spawner", ...ctx };
650 669 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
670 pendingDialogueId = config.dialogueId ?? null;
671 dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions;
672 if (socket && MessageType)
673 { socket.send({ type: MessageType.editorLoadDialogues }); }
651 674 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
652 675 form.innerHTML = "";
653 676 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
@@ -695,6 +718,35 @@ export function initTileConfigModal ({ onSave, onRemove })
695 718 show(true);
696 719 }
697 720
721 function openDoorway (ctx)
722 {
723 context = { kind: "doorway", ...ctx };
724 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
725 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
726 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
727 form.innerHTML = "";
728 form.append(
729 field("Appearance", doorwayStateSelect("state", state)),
730 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
731 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
732 );
733 const dimWrap = document.createElement("label");
734 dimWrap.append(document.createTextNode("Target dimension"));
735 const dimRoot = document.createElement("div");
736 dimRoot.className = "doorway-dim-combo";
737 dimWrap.append(dimRoot);
738 form.append(dimWrap);
739 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
740 doorwayDimCombo = createDimensionCombobox({
741 root: dimRoot,
742 placeholder: "Target dimension…",
743 onSelect () {}
744 });
745 doorwayDimCombo.setOptions(options);
746 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
747 show(true);
748 }
749
698 750 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
699 751 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
700 752 backdrop.addEventListener("click", () => show(false));
@@ -724,6 +776,19 @@ export function initTileConfigModal ({ onSave, onRemove })
724 776 {
725 777 if (!context)
726 778 { return; }
779 if (context.kind === "doorway")
780 {
781 const data = new FormData(form);
782 const stateRaw = String(data.get("state") || "door");
783 onSave?.(context, {
784 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
785 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
786 tileX: Number(data.get("tileX")) || 0,
787 tileY: Number(data.get("tileY")) || 0
788 });
789 show(false);
790 return;
791 }
727 792 const data = new FormData(form);
728 793 const equipment = {};
729 794 for (const slot of EQUIPMENT_SLOTS)
@@ -744,7 +809,8 @@ export function initTileConfigModal ({ onSave, onRemove })
744 809 spells: spellsDraft,
745 810 buysItems: data.get("buysItems") === "on",
746 811 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
747 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
812 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
813 dialogueId: String(data.get("dialogueId") || "").trim() || null
748 814 }, context.config.spawnerId));
749 815 show(false);
750 816 });
@@ -759,10 +825,43 @@ export function initTileConfigModal ({ onSave, onRemove })
759 825 return {
760 826 isOpen: () => open,
761 827 openSpawner,
762 close: () => show(false)
828 openDoorway,
829 close: () => show(false),
830 handleMessage (message)
831 {
832 if (!MessageType || message.type !== MessageType.editorDialogues)
833 { return; }
834 dialogueOptions = (message.dialogues ?? []).map((d) => ({
835 dialogueId: String(d.dialogueId ?? ""),
836 label: String(d.label ?? d.dialogueId ?? ""),
837 unique: !!d.unique
838 })).filter((d) => d.dialogueId);
839 const select = form.querySelector('[name="dialogueId"]');
840 if (select && open)
841 {
842 const current = select.value || pendingDialogueId || "";
843 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
844 }
845 }
763 846 };
764 847 }
765 848
849 function doorwayStateSelect (name, value)
850 {
851 const select = document.createElement("select");
852 select.name = name;
853 for (const state of DOORWAY_STATES)
854 {
855 const opt = document.createElement("option");
856 opt.value = state;
857 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
858 if (state === value)
859 { opt.selected = true; }
860 select.append(opt);
861 }
862 return select;
863 }
864
766 865 function field (label, input)
767 866 {
768 867 const wrap = document.createElement("label");
@@ -823,3 +922,38 @@ function mobSelect (name, value)
823 922 }
824 923 return select;
825 924 }
925
926 function dialogueSelect (name, value, options = [])
927 {
928 const select = document.createElement("select");
929 select.name = name;
930 const none = document.createElement("option");
931 none.value = "";
932 none.textContent = "(none)";
933 select.append(none);
934 const selected = String(value ?? "");
935 let found = !selected;
936 for (const entry of options)
937 {
938 const option = document.createElement("option");
939 option.value = entry.dialogueId;
940 option.textContent = entry.unique
941 ? `${entry.label} [${entry.dialogueId}] · unique`
942 : `${entry.label} [${entry.dialogueId}]`;
943 if (entry.dialogueId === selected)
944 {
945 option.selected = true;
946 found = true;
947 }
948 select.append(option);
949 }
950 if (selected && !found)
951 {
952 const orphan = document.createElement("option");
953 orphan.value = selected;
954 orphan.textContent = `${selected} (missing)`;
955 orphan.selected = true;
956 select.append(orphan);
957 }
958 return select;
959 }
@@ -1,5 +1,5 @@
1/**
1/**
2 * Right-click config modal for editor tiles that have configurable data (spawners).
2 * Right-click config modal for editor tiles that have configurable data (spawners, doorways).
3 */
3 */
4import {
4import {
5 listSpawnableMobTypes,
5 listSpawnableMobTypes,
@@ -16,6 +16,10 @@ import { ITEM_DEFINITIONS, itemDefinition, isDyeableClothing } from "/shared/def
16import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
16import { EQUIPMENT_SLOTS } from "/shared/items/inventory.js";
17import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
17import { listNpcShopSellableItems } from "/shared/shop/pricing.js";
18import { normalizeRgb } from "/shared/render/tint.js";
18import { normalizeRgb } from "/shared/render/tint.js";
19import { createDimensionCombobox } from "./dimensionCombobox.js";
20import { OVERWORLD_ID, normalizeDimensionId } from "/shared/world/dimensions.js";
21
22const DOORWAY_STATES = Object.freeze(["door", "ladder", "hole", "cave"]);
19
23
20/** Items that can be worn in a given equipment slot. */
24/** Items that can be worn in a given equipment slot. */
21export function listEquippableItemsForSlot (slot)
25export function listEquippableItemsForSlot (slot)
@@ -68,7 +72,14 @@ function rgbToCss (color)
68 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
72 return `rgb(${Math.round(c.r * 255)}, ${Math.round(c.g * 255)}, ${Math.round(c.b * 255)})`;
69}
73}
70
74
71export function initTileConfigModal ({ onSave, onRemove })
75export function initTileConfigModal ({
76 onSave,
77 onRemove,
78 socket,
79 MessageType,
80 getDialogues,
81 getDimensionOptions
82})
72{
83{
73 const backdrop = document.getElementById("tile-config-backdrop");
84 const backdrop = document.getElementById("tile-config-backdrop");
74 const modal = document.getElementById("tile-config-modal");
85 const modal = document.getElementById("tile-config-modal");
@@ -101,6 +112,11 @@ export function initTileConfigModal ({ onSave, onRemove })
101 let itemSearchMode = null;
112 let itemSearchMode = null;
102 /** @type {string|null} */
113 /** @type {string|null} */
103 let dyeEditSlot = null;
114 let dyeEditSlot = null;
115 /** @type {{ dialogueId: string, label: string, unique?: boolean }[]} */
116 let dialogueOptions = [];
117 let pendingDialogueId = null;
118 /** @type {ReturnType<typeof createDimensionCombobox>|null} */
119 let doorwayDimCombo = null;
104
120
105 function show (visible)
121 function show (visible)
106 {
122 {
@@ -110,6 +126,7 @@ export function initTileConfigModal ({ onSave, onRemove })
110 if (!visible)
126 if (!visible)
111 {
127 {
112 context = null;
128 context = null;
129 doorwayDimCombo = null;
113 closeItemSearch();
130 closeItemSearch();
114 closeDyePicker();
131 closeDyePicker();
115 }
132 }
@@ -425,6 +442,8 @@ export function initTileConfigModal ({ onSave, onRemove })
425 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
442 aggressiveHint.textContent = "When Aggressive is on, Bounty is forced to 0.";
426 wrap.append(aggressiveHint);
443 wrap.append(aggressiveHint);
427
444
445 wrap.append(field("Dialogue", dialogueSelect("dialogueId", config.dialogueId ?? "", dialogueOptions)));
446
428 const equipHeader = document.createElement("div");
447 const equipHeader = document.createElement("div");
429 equipHeader.className = "spawner-sells-header";
448 equipHeader.className = "spawner-sells-header";
430 const equipTitle = document.createElement("strong");
449 const equipTitle = document.createElement("strong");
@@ -648,6 +667,10 @@ export function initTileConfigModal ({ onSave, onRemove })
648 {
667 {
649 context = { kind: "spawner", ...ctx };
668 context = { kind: "spawner", ...ctx };
650 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
669 const config = normalizeSpawnerConfig(ctx.config, ctx.config.spawnerId);
670 pendingDialogueId = config.dialogueId ?? null;
671 dialogueOptions = typeof getDialogues === "function" ? (getDialogues() ?? []) : dialogueOptions;
672 if (socket && MessageType)
673 { socket.send({ type: MessageType.editorLoadDialogues }); }
651 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
674 title.textContent = `Spawner · ${ctx.tileX}, ${ctx.tileY}`;
652 form.innerHTML = "";
675 form.innerHTML = "";
653 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
676 const mobField = field("Mob type", mobSelect("mobTypeId", config.mobTypeId));
@@ -695,6 +718,35 @@ export function initTileConfigModal ({ onSave, onRemove })
695 show(true);
718 show(true);
696 }
719 }
697
720
721 function openDoorway (ctx)
722 {
723 context = { kind: "doorway", ...ctx };
724 const config = ctx.config && typeof ctx.config === "object" ? ctx.config : {};
725 const state = DOORWAY_STATES.includes(ctx.state) ? ctx.state : "door";
726 title.textContent = `Doorway · ${ctx.tileX}, ${ctx.tileY}`;
727 form.innerHTML = "";
728 form.append(
729 field("Appearance", doorwayStateSelect("state", state)),
730 field("Target tile X", numberInput("tileX", Number.isFinite(Number(config.tileX)) ? Number(config.tileX) : 0, -1_000_000, 1_000_000)),
731 field("Target tile Y", numberInput("tileY", Number.isFinite(Number(config.tileY)) ? Number(config.tileY) : 0, -1_000_000, 1_000_000))
732 );
733 const dimWrap = document.createElement("label");
734 dimWrap.append(document.createTextNode("Target dimension"));
735 const dimRoot = document.createElement("div");
736 dimRoot.className = "doorway-dim-combo";
737 dimWrap.append(dimRoot);
738 form.append(dimWrap);
739 const options = typeof getDimensionOptions === "function" ? (getDimensionOptions() ?? []) : [];
740 doorwayDimCombo = createDimensionCombobox({
741 root: dimRoot,
742 placeholder: "Target dimension…",
743 onSelect () {}
744 });
745 doorwayDimCombo.setOptions(options);
746 doorwayDimCombo.setValue(normalizeDimensionId(config.targetDimensionId ?? OVERWORLD_ID));
747 show(true);
748 }
749
698 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
750 document.getElementById("tile-config-close").addEventListener("click", () => show(false));
699 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
751 document.getElementById("tile-config-cancel").addEventListener("click", () => show(false));
700 backdrop.addEventListener("click", () => show(false));
752 backdrop.addEventListener("click", () => show(false));
@@ -724,6 +776,19 @@ export function initTileConfigModal ({ onSave, onRemove })
724 {
776 {
725 if (!context)
777 if (!context)
726 { return; }
778 { return; }
779 if (context.kind === "doorway")
780 {
781 const data = new FormData(form);
782 const stateRaw = String(data.get("state") || "door");
783 onSave?.(context, {
784 state: DOORWAY_STATES.includes(stateRaw) ? stateRaw : "door",
785 targetDimensionId: normalizeDimensionId(doorwayDimCombo?.getValue() ?? OVERWORLD_ID),
786 tileX: Number(data.get("tileX")) || 0,
787 tileY: Number(data.get("tileY")) || 0
788 });
789 show(false);
790 return;
791 }
727 const data = new FormData(form);
792 const data = new FormData(form);
728 const equipment = {};
793 const equipment = {};
729 for (const slot of EQUIPMENT_SLOTS)
794 for (const slot of EQUIPMENT_SLOTS)
@@ -744,7 +809,8 @@ export function initTileConfigModal ({ onSave, onRemove })
744 spells: spellsDraft,
809 spells: spellsDraft,
745 buysItems: data.get("buysItems") === "on",
810 buysItems: data.get("buysItems") === "on",
746 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
811 hiddenDiscount: Number(data.get("hiddenDiscount") || 0.9),
747 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || ""))
812 centralExchange: isCentralExchangeSpawner(String(data.get("mobTypeId") || "")),
813 dialogueId: String(data.get("dialogueId") || "").trim() || null
748 }, context.config.spawnerId));
814 }, context.config.spawnerId));
749 show(false);
815 show(false);
750 });
816 });
@@ -759,10 +825,43 @@ export function initTileConfigModal ({ onSave, onRemove })
759 return {
825 return {
760 isOpen: () => open,
826 isOpen: () => open,
761 openSpawner,
827 openSpawner,
762 close: () => show(false)
828 openDoorway,
829 close: () => show(false),
830 handleMessage (message)
831 {
832 if (!MessageType || message.type !== MessageType.editorDialogues)
833 { return; }
834 dialogueOptions = (message.dialogues ?? []).map((d) => ({
835 dialogueId: String(d.dialogueId ?? ""),
836 label: String(d.label ?? d.dialogueId ?? ""),
837 unique: !!d.unique
838 })).filter((d) => d.dialogueId);
839 const select = form.querySelector('[name="dialogueId"]');
840 if (select && open)
841 {
842 const current = select.value || pendingDialogueId || "";
843 select.replaceWith(dialogueSelect("dialogueId", current, dialogueOptions));
844 }
845 }
763 };
846 };
764}
847}
765
848
849function doorwayStateSelect (name, value)
850{
851 const select = document.createElement("select");
852 select.name = name;
853 for (const state of DOORWAY_STATES)
854 {
855 const opt = document.createElement("option");
856 opt.value = state;
857 opt.textContent = state.charAt(0).toUpperCase() + state.slice(1);
858 if (state === value)
859 { opt.selected = true; }
860 select.append(opt);
861 }
862 return select;
863}
864
766function field (label, input)
865function field (label, input)
767{
866{
768 const wrap = document.createElement("label");
867 const wrap = document.createElement("label");
@@ -823,3 +922,38 @@ function mobSelect (name, value)
823 }
922 }
824 return select;
923 return select;
825}
924}
925
926function dialogueSelect (name, value, options = [])
927{
928 const select = document.createElement("select");
929 select.name = name;
930 const none = document.createElement("option");
931 none.value = "";
932 none.textContent = "(none)";
933 select.append(none);
934 const selected = String(value ?? "");
935 let found = !selected;
936 for (const entry of options)
937 {
938 const option = document.createElement("option");
939 option.value = entry.dialogueId;
940 option.textContent = entry.unique
941 ? `${entry.label} [${entry.dialogueId}] · unique`
942 : `${entry.label} [${entry.dialogueId}]`;
943 if (entry.dialogueId === selected)
944 {
945 option.selected = true;
946 found = true;
947 }
948 select.append(option);
949 }
950 if (selected && !found)
951 {
952 const orphan = document.createElement("option");
953 orphan.value = selected;
954 orphan.textContent = `${selected} (missing)`;
955 orphan.selected = true;
956 select.append(orphan);
957 }
958 return select;
959}
client/src/play/characterPreview.js +116 −0
@@ -42,6 +42,108 @@ export async function paintCharacterPreview (canvas, {
42 42 }
43 43 }
44 44
45 /**
46 * Sync composite of live `appearanceLayers` onto a fixed-size canvas.
47 * Crops a top-aligned square from each frame (e.g. 16×16 from a 16×24 body)
48 * then scales that crop up to `size` (e.g. 64) without squishing the tall frame.
49 * `resolveImage(name)` should return a Framework `image` (with `g_image` /
50 * `getSubImage`) or a plain HTMLImageElement / canvas already in memory.
51 */
52 export function paintAppearanceSnapshot (canvas, layers, {
53 resolveImage,
54 size = 64,
55 frame = 0
56 } = {})
57 {
58 if (!canvas)
59 { return false; }
60 const draws = [];
61 for (const layer of layers ?? [])
62 {
63 const name = layer?.sprite;
64 if (!name)
65 { continue; }
66 const entry = resolveImage?.(name);
67 if (!entry)
68 { continue; }
69 draws.push({ entry, tint: layer.tint ?? null, frame });
70 }
71 return paintDrawListSnapshot(canvas, draws, { size });
72 }
73
74 /**
75 * Composite the live world render stack (body GameObject + overlays + tints).
76 * Matches what the player sees in-world, including hair overlays.
77 */
78 export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
79 {
80 if (!canvas || !entity?.object?.renderer?.sprite)
81 { return false; }
82 const draws = [{
83 entry: entity.object.renderer.sprite,
84 tint: null,
85 frame: entity.object.renderer.subImage | 0
86 }];
87 const overlays = entity.overlays ?? [];
88 const tints = entity.overlayTints ?? [];
89 for (let index = 0; index < overlays.length; index++)
90 {
91 const sprite = overlays[index]?.renderer?.sprite;
92 if (!sprite)
93 { continue; }
94 draws.push({
95 entry: sprite,
96 tint: tints[index] ?? null,
97 frame: overlays[index].renderer.subImage | 0
98 });
99 }
100 return paintDrawListSnapshot(canvas, draws, { size });
101 }
102
103 function paintDrawListSnapshot (canvas, draws, { size = 64 } = {})
104 {
105 if (!canvas || !draws?.length)
106 { return false; }
107 canvas.width = size;
108 canvas.height = size;
109 const ctx = canvas.getContext("2d");
110 ctx.imageSmoothingEnabled = false;
111 ctx.clearRect(0, 0, size, size);
112 let drew = false;
113 for (const draw of draws)
114 {
115 const entry = draw.entry;
116 const html = entry?.g_image ?? entry;
117 if (!html || !(html.naturalWidth || html.width))
118 { continue; }
119 let sx = 0;
120 let sy = 0;
121 let sw = html.naturalWidth || html.width;
122 let sh = html.naturalHeight || html.height;
123 if (typeof entry?.getSubImage === "function")
124 {
125 const sub = entry.getSubImage(draw.frame | 0);
126 sx = sub.sx;
127 sy = sub.sy;
128 sw = sub.sw;
129 sh = sub.sh;
130 }
131 // Top-aligned square crop of the frame (e.g. 16×16 from 16×24).
132 const crop = Math.min(sw, sh);
133 const cropSx = sx + Math.floor((sw - crop) / 2);
134 const cropSy = sy;
135 const source = draw.tint
136 ? tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint)
137 : null;
138 if (source)
139 { ctx.drawImage(source, 0, 0, size, size); }
140 else
141 { ctx.drawImage(html, cropSx, cropSy, crop, crop, 0, 0, size, size); }
142 drew = true;
143 }
144 return drew;
145 }
146
45 147 function loadHtmlImage (url)
46 148 {
47 149 return new Promise((resolve, reject) =>
@@ -66,3 +168,17 @@ function tintedCanvas (sourceImg, tintRgb)
66 168 ctx.putImageData(imageData, 0, 0);
67 169 return canvas;
68 170 }
171
172 function tintedSubCanvas (sourceImg, sx, sy, sw, sh, tintRgb)
173 {
174 const canvas = document.createElement("canvas");
175 canvas.width = sw;
176 canvas.height = sh;
177 const ctx = canvas.getContext("2d");
178 ctx.imageSmoothingEnabled = false;
179 ctx.drawImage(sourceImg, sx, sy, sw, sh, 0, 0, sw, sh);
180 const imageData = ctx.getImageData(0, 0, sw, sh);
181 applyMagentaTintToImageData(imageData, tintRgb);
182 ctx.putImageData(imageData, 0, 0);
183 return canvas;
184 }
@@ -42,6 +42,108 @@ export async function paintCharacterPreview (canvas, {
42 }
42 }
43}
43}
44
44
45/**
46 * Sync composite of live `appearanceLayers` onto a fixed-size canvas.
47 * Crops a top-aligned square from each frame (e.g. 16×16 from a 16×24 body)
48 * then scales that crop up to `size` (e.g. 64) without squishing the tall frame.
49 * `resolveImage(name)` should return a Framework `image` (with `g_image` /
50 * `getSubImage`) or a plain HTMLImageElement / canvas already in memory.
51 */
52export function paintAppearanceSnapshot (canvas, layers, {
53 resolveImage,
54 size = 64,
55 frame = 0
56} = {})
57{
58 if (!canvas)
59 { return false; }
60 const draws = [];
61 for (const layer of layers ?? [])
62 {
63 const name = layer?.sprite;
64 if (!name)
65 { continue; }
66 const entry = resolveImage?.(name);
67 if (!entry)
68 { continue; }
69 draws.push({ entry, tint: layer.tint ?? null, frame });
70 }
71 return paintDrawListSnapshot(canvas, draws, { size });
72}
73
74/**
75 * Composite the live world render stack (body GameObject + overlays + tints).
76 * Matches what the player sees in-world, including hair overlays.
77 */
78export function paintLiveEntitySnapshot (canvas, entity, { size = 64 } = {})
79{
80 if (!canvas || !entity?.object?.renderer?.sprite)
81 { return false; }
82 const draws = [{
83 entry: entity.object.renderer.sprite,
84 tint: null,
85 frame: entity.object.renderer.subImage | 0
86 }];
87 const overlays = entity.overlays ?? [];
88 const tints = entity.overlayTints ?? [];
89 for (let index = 0; index < overlays.length; index++)
90 {
91 const sprite = overlays[index]?.renderer?.sprite;
92 if (!sprite)
93 { continue; }
94 draws.push({
95 entry: sprite,
96 tint: tints[index] ?? null,
97 frame: overlays[index].renderer.subImage | 0
98 });
99 }
100 return paintDrawListSnapshot(canvas, draws, { size });
101}
102
103function paintDrawListSnapshot (canvas, draws, { size = 64 } = {})
104{
105 if (!canvas || !draws?.length)
106 { return false; }
107 canvas.width = size;
108 canvas.height = size;
109 const ctx = canvas.getContext("2d");
110 ctx.imageSmoothingEnabled = false;
111 ctx.clearRect(0, 0, size, size);
112 let drew = false;
113 for (const draw of draws)
114 {
115 const entry = draw.entry;
116 const html = entry?.g_image ?? entry;
117 if (!html || !(html.naturalWidth || html.width))
118 { continue; }
119 let sx = 0;
120 let sy = 0;
121 let sw = html.naturalWidth || html.width;
122 let sh = html.naturalHeight || html.height;
123 if (typeof entry?.getSubImage === "function")
124 {
125 const sub = entry.getSubImage(draw.frame | 0);
126 sx = sub.sx;
127 sy = sub.sy;
128 sw = sub.sw;
129 sh = sub.sh;
130 }
131 // Top-aligned square crop of the frame (e.g. 16×16 from 16×24).
132 const crop = Math.min(sw, sh);
133 const cropSx = sx + Math.floor((sw - crop) / 2);
134 const cropSy = sy;
135 const source = draw.tint
136 ? tintedSubCanvas(html, cropSx, cropSy, crop, crop, draw.tint)
137 : null;
138 if (source)
139 { ctx.drawImage(source, 0, 0, size, size); }
140 else
141 { ctx.drawImage(html, cropSx, cropSy, crop, crop, 0, 0, size, size); }
142 drew = true;
143 }
144 return drew;
145}
146
45function loadHtmlImage (url)
147function loadHtmlImage (url)
46{
148{
47 return new Promise((resolve, reject) =>
149 return new Promise((resolve, reject) =>
@@ -66,3 +168,17 @@ function tintedCanvas (sourceImg, tintRgb)
66 ctx.putImageData(imageData, 0, 0);
168 ctx.putImageData(imageData, 0, 0);
67 return canvas;
169 return canvas;
68}
170}
171
172function tintedSubCanvas (sourceImg, sx, sy, sw, sh, tintRgb)
173{
174 const canvas = document.createElement("canvas");
175 canvas.width = sw;
176 canvas.height = sh;
177 const ctx = canvas.getContext("2d");
178 ctx.imageSmoothingEnabled = false;
179 ctx.drawImage(sourceImg, sx, sy, sw, sh, 0, 0, sw, sh);
180 const imageData = ctx.getImageData(0, 0, sw, sh);
181 applyMagentaTintToImageData(imageData, tintRgb);
182 ctx.putImageData(imageData, 0, 0);
183 return canvas;
184}
client/src/play/dialogue.js added +208 −0
@@ -0,0 +1,208 @@
1 /**
2 * Play dialogue panel: page lines one-by-one, then choices / end.
3 * Speaker icons are live WebGL portraits from WorldView (same stack as the world).
4 */
5
6 const SPEAKER_ICON_SIZE = 64;
7
8 export function initDialogue ({ socket, MessageType, getEntity, captureSpeakerIcon })
9 {
10 const panel = document.getElementById("dialogue-panel");
11 const titleEl = document.getElementById("dialogue-title");
12 const linesEl = document.getElementById("dialogue-lines");
13 const triggersEl = document.getElementById("dialogue-triggers");
14 let open = false;
15 /** @type {null | { label: string, npcEntityId: number|null, lines: object[], lineIndex: number, triggers: object[]|null }} */
16 let current = null;
17
18 function show (visible)
19 {
20 open = visible;
21 if (panel)
22 { panel.hidden = !visible; }
23 if (!visible)
24 { current = null; }
25 }
26
27 function speakerEntity (speaker)
28 {
29 if (speaker === "player")
30 { return getEntity?.("local") ?? null; }
31 const id = current?.npcEntityId;
32 if (id == null)
33 { return null; }
34 return getEntity?.(id) ?? getEntity?.(Number(id)) ?? null;
35 }
36
37 function speakerIconCanvas (speaker)
38 {
39 const entity = speakerEntity(speaker);
40 const captured = entity?.entityId != null
41 ? captureSpeakerIcon?.(entity.entityId, SPEAKER_ICON_SIZE)
42 : null;
43 if (captured)
44 {
45 captured.className = "dialogue-speaker-icon";
46 return captured;
47 }
48 const canvas = document.createElement("canvas");
49 canvas.className = "dialogue-speaker-icon";
50 canvas.width = SPEAKER_ICON_SIZE;
51 canvas.height = SPEAKER_ICON_SIZE;
52 const ctx = canvas.getContext("2d");
53 ctx.fillStyle = speaker === "player" ? "#6a8caf" : "#8a6a4a";
54 ctx.fillRect(0, 0, SPEAKER_ICON_SIZE, SPEAKER_ICON_SIZE);
55 return canvas;
56 }
57
58 function npcDisplayName ()
59 {
60 const entity = speakerEntity("npc");
61 const first = (entity?.firstName ?? "").trim();
62 const last = (entity?.lastName ?? "").trim();
63 if (first && last)
64 { return `${first} ${last}`; }
65 return first || "…";
66 }
67
68 function renderLine ()
69 {
70 if (!current)
71 { return; }
72 if (titleEl)
73 { titleEl.textContent = npcDisplayName(); }
74 linesEl?.replaceChildren();
75 triggersEl?.replaceChildren();
76
77 const line = current.lines[current.lineIndex];
78 if (line)
79 {
80 const row = document.createElement("div");
81 row.className = `dialogue-line dialogue-line-${line.speaker === "player" ? "player" : "npc"}`;
82 row.append(speakerIconCanvas(line.speaker === "player" ? "player" : "npc"));
83 const text = document.createElement("span");
84 text.className = "dialogue-line-text";
85 text.textContent = line.text ?? "";
86 row.append(text);
87 linesEl?.append(row);
88 }
89
90 const atLast = current.lineIndex >= (current.lines?.length ?? 1) - 1;
91 if (!atLast)
92 {
93 const nextBtn = document.createElement("button");
94 nextBtn.type = "button";
95 nextBtn.className = "dialogue-next";
96 nextBtn.textContent = "Next";
97 nextBtn.addEventListener("click", () =>
98 {
99 current.lineIndex += 1;
100 renderLine();
101 });
102 triggersEl?.append(nextBtn);
103 return;
104 }
105
106 if (Array.isArray(current.triggers))
107 {
108 renderTriggers(current.triggers);
109 return;
110 }
111 const cont = document.createElement("button");
112 cont.type = "button";
113 cont.className = "dialogue-next";
114 cont.textContent = "Continue";
115 cont.addEventListener("click", () =>
116 {
117 socket.send({ type: MessageType.dialogueAdvance });
118 });
119 triggersEl?.append(cont);
120 }
121
122 function renderTriggers (triggers)
123 {
124 triggersEl?.replaceChildren();
125 if (!triggers.length)
126 {
127 const closeBtn = document.createElement("button");
128 closeBtn.type = "button";
129 closeBtn.textContent = "Close";
130 closeBtn.addEventListener("click", () =>
131 {
132 socket.send({ type: MessageType.closeDialogue });
133 show(false);
134 });
135 triggersEl?.append(closeBtn);
136 return;
137 }
138 for (const trig of triggers)
139 {
140 const btn = document.createElement("button");
141 btn.type = "button";
142 btn.textContent = trig.text || trig.trigger || "…";
143 btn.addEventListener("click", () =>
144 {
145 socket.send({
146 type: MessageType.dialogueChoose,
147 trigger: trig.trigger
148 });
149 });
150 triggersEl?.append(btn);
151 }
152 }
153
154 document.getElementById("dialogue-close")?.addEventListener("click", () =>
155 {
156 socket.send({ type: MessageType.closeDialogue });
157 show(false);
158 });
159
160 return {
161 isBlocking ()
162 {
163 return open;
164 },
165 handleStep (message)
166 {
167 current = {
168 label: message.label,
169 npcEntityId: message.npcEntityId ?? null,
170 lines: message.lines?.length ? message.lines : [{ speaker: "npc", text: "…" }],
171 lineIndex: 0,
172 triggers: null
173 };
174 show(true);
175 renderLine();
176 },
177 handleChoices (message)
178 {
179 if (!current)
180 {
181 current = {
182 label: "Dialogue",
183 npcEntityId: message.npcEntityId ?? null,
184 lines: [],
185 lineIndex: 0,
186 triggers: message.triggers ?? []
187 };
188 show(true);
189 }
190 else
191 { current.triggers = message.triggers ?? []; }
192 current.lineIndex = Math.max(0, (current.lines?.length ?? 1) - 1);
193 renderLine();
194 },
195 handleClose ()
196 {
197 show(false);
198 },
199 hide ()
200 {
201 show(false);
202 },
203 reset ()
204 {
205 show(false);
206 }
207 };
208 }
@@ -0,0 +1,208 @@
1/**
2 * Play dialogue panel: page lines one-by-one, then choices / end.
3 * Speaker icons are live WebGL portraits from WorldView (same stack as the world).
4 */
5
6const SPEAKER_ICON_SIZE = 64;
7
8export function initDialogue ({ socket, MessageType, getEntity, captureSpeakerIcon })
9{
10 const panel = document.getElementById("dialogue-panel");
11 const titleEl = document.getElementById("dialogue-title");
12 const linesEl = document.getElementById("dialogue-lines");
13 const triggersEl = document.getElementById("dialogue-triggers");
14 let open = false;
15 /** @type {null | { label: string, npcEntityId: number|null, lines: object[], lineIndex: number, triggers: object[]|null }} */
16 let current = null;
17
18 function show (visible)
19 {
20 open = visible;
21 if (panel)
22 { panel.hidden = !visible; }
23 if (!visible)
24 { current = null; }
25 }
26
27 function speakerEntity (speaker)
28 {
29 if (speaker === "player")
30 { return getEntity?.("local") ?? null; }
31 const id = current?.npcEntityId;
32 if (id == null)
33 { return null; }
34 return getEntity?.(id) ?? getEntity?.(Number(id)) ?? null;
35 }
36
37 function speakerIconCanvas (speaker)
38 {
39 const entity = speakerEntity(speaker);
40 const captured = entity?.entityId != null
41 ? captureSpeakerIcon?.(entity.entityId, SPEAKER_ICON_SIZE)
42 : null;
43 if (captured)
44 {
45 captured.className = "dialogue-speaker-icon";
46 return captured;
47 }
48 const canvas = document.createElement("canvas");
49 canvas.className = "dialogue-speaker-icon";
50 canvas.width = SPEAKER_ICON_SIZE;
51 canvas.height = SPEAKER_ICON_SIZE;
52 const ctx = canvas.getContext("2d");
53 ctx.fillStyle = speaker === "player" ? "#6a8caf" : "#8a6a4a";
54 ctx.fillRect(0, 0, SPEAKER_ICON_SIZE, SPEAKER_ICON_SIZE);
55 return canvas;
56 }
57
58 function npcDisplayName ()
59 {
60 const entity = speakerEntity("npc");
61 const first = (entity?.firstName ?? "").trim();
62 const last = (entity?.lastName ?? "").trim();
63 if (first && last)
64 { return `${first} ${last}`; }
65 return first || "…";
66 }
67
68 function renderLine ()
69 {
70 if (!current)
71 { return; }
72 if (titleEl)
73 { titleEl.textContent = npcDisplayName(); }
74 linesEl?.replaceChildren();
75 triggersEl?.replaceChildren();
76
77 const line = current.lines[current.lineIndex];
78 if (line)
79 {
80 const row = document.createElement("div");
81 row.className = `dialogue-line dialogue-line-${line.speaker === "player" ? "player" : "npc"}`;
82 row.append(speakerIconCanvas(line.speaker === "player" ? "player" : "npc"));
83 const text = document.createElement("span");
84 text.className = "dialogue-line-text";
85 text.textContent = line.text ?? "";
86 row.append(text);
87 linesEl?.append(row);
88 }
89
90 const atLast = current.lineIndex >= (current.lines?.length ?? 1) - 1;
91 if (!atLast)
92 {
93 const nextBtn = document.createElement("button");
94 nextBtn.type = "button";
95 nextBtn.className = "dialogue-next";
96 nextBtn.textContent = "Next";
97 nextBtn.addEventListener("click", () =>
98 {
99 current.lineIndex += 1;
100 renderLine();
101 });
102 triggersEl?.append(nextBtn);
103 return;
104 }
105
106 if (Array.isArray(current.triggers))
107 {
108 renderTriggers(current.triggers);
109 return;
110 }
111 const cont = document.createElement("button");
112 cont.type = "button";
113 cont.className = "dialogue-next";
114 cont.textContent = "Continue";
115 cont.addEventListener("click", () =>
116 {
117 socket.send({ type: MessageType.dialogueAdvance });
118 });
119 triggersEl?.append(cont);
120 }
121
122 function renderTriggers (triggers)
123 {
124 triggersEl?.replaceChildren();
125 if (!triggers.length)
126 {
127 const closeBtn = document.createElement("button");
128 closeBtn.type = "button";
129 closeBtn.textContent = "Close";
130 closeBtn.addEventListener("click", () =>
131 {
132 socket.send({ type: MessageType.closeDialogue });
133 show(false);
134 });
135 triggersEl?.append(closeBtn);
136 return;
137 }
138 for (const trig of triggers)
139 {
140 const btn = document.createElement("button");
141 btn.type = "button";
142 btn.textContent = trig.text || trig.trigger || "…";
143 btn.addEventListener("click", () =>
144 {
145 socket.send({
146 type: MessageType.dialogueChoose,
147 trigger: trig.trigger
148 });
149 });
150 triggersEl?.append(btn);
151 }
152 }
153
154 document.getElementById("dialogue-close")?.addEventListener("click", () =>
155 {
156 socket.send({ type: MessageType.closeDialogue });
157 show(false);
158 });
159
160 return {
161 isBlocking ()
162 {
163 return open;
164 },
165 handleStep (message)
166 {
167 current = {
168 label: message.label,
169 npcEntityId: message.npcEntityId ?? null,
170 lines: message.lines?.length ? message.lines : [{ speaker: "npc", text: "…" }],
171 lineIndex: 0,
172 triggers: null
173 };
174 show(true);
175 renderLine();
176 },
177 handleChoices (message)
178 {
179 if (!current)
180 {
181 current = {
182 label: "Dialogue",
183 npcEntityId: message.npcEntityId ?? null,
184 lines: [],
185 lineIndex: 0,
186 triggers: message.triggers ?? []
187 };
188 show(true);
189 }
190 else
191 { current.triggers = message.triggers ?? []; }
192 current.lineIndex = Math.max(0, (current.lines?.length ?? 1) - 1);
193 renderLine();
194 },
195 handleClose ()
196 {
197 show(false);
198 },
199 hide ()
200 {
201 show(false);
202 },
203 reset ()
204 {
205 show(false);
206 }
207 };
208}
client/src/play/main.js +123 −9
@@ -1,6 +1,7 @@
1 1 import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2 2 import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3 3 import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4 import { OVERWORLD_ID } from "/shared/world/dimensions.js";
4 5 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5 6 import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6 7 import { WorldView } from "../render/worldView.js";
@@ -17,6 +18,8 @@ import { initStatusEffects } from "./statusEffects.js";
17 18 import { initContextMenu } from "./contextMenu.js";
18 19 import { initDeath } from "./death.js";
19 20 import { initToasts } from "./toasts.js";
21 import { initQuests } from "./quests.js";
22 import { initDialogue } from "./dialogue.js";
20 23 import { initShop } from "./shop.js";
21 24 import { initMarket } from "./market.js";
22 25 import { initBounty } from "./bounty.js";
@@ -58,13 +61,15 @@ let statusEffectsUi;
58 61 let contextMenu;
59 62 let death;
60 63 let toasts;
64 let questsUi;
65 let dialogueUi;
61 66 let shop;
62 67 let market;
63 68 let bounty;
64 69 let barber;
65 70 let createHairControls;
66 71 let pendingPickup = null;
67 /** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
72 /** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
68 73 let pendingInteract = null;
69 74 /** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
70 75 let approachMove = null;
@@ -115,6 +120,7 @@ function uiBlocked ()
115 120 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
116 121 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
117 122 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
123 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
118 124 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
119 125 || pointerOverSpellUi());
120 126 }
@@ -223,6 +229,17 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})
223 229 { approachAdjacentTile(tileX, tileY); }
224 230 }
225 231
232 function requestEnterDoorway (tileX, tileY)
233 {
234 clearAllPendingActions();
235 pendingInteract = { kind: "doorway", tileX, tileY };
236 const local = view?.entities.get(view.localEntityId);
237 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
238 { flushPendingInteract(); }
239 else
240 { approachAdjacentTile(tileX, tileY); }
241 }
242
226 243 function requestOpenMarket (tileX, tileY)
227 244 {
228 245 clearAllPendingActions();
@@ -316,10 +333,10 @@ function requestPick (tileX, tileY)
316 333 { approachAdjacentTile(tileX, tileY); }
317 334 }
318 335
319 function requestTalk (targetEntityId)
336 function requestTalk (targetEntityId, purpose = null)
320 337 {
321 338 clearAllPendingActions();
322 pendingInteract = { kind: "talk", targetEntityId };
339 pendingInteract = { kind: "talk", targetEntityId, purpose };
323 340 const target = view?.entities.get(targetEntityId);
324 341 if (!target)
325 342 {
@@ -350,6 +367,19 @@ function flushPendingInteract ()
350 367 return;
351 368 }
352 369
370 if (pendingInteract.kind === "doorway")
371 {
372 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
373 { return; }
374 socket.send({
375 type: MessageType.enterDoorway,
376 tileX: pendingInteract.tileX,
377 tileY: pendingInteract.tileY
378 });
379 clearPendingInteract();
380 return;
381 }
382
353 383 if (pendingInteract.kind === "market")
354 384 {
355 385 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -451,7 +481,11 @@ function flushPendingInteract ()
451 481 approachAdjacentTile(target.tileX, target.tileY);
452 482 return;
453 483 }
454 socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId });
484 socket.send({
485 type: MessageType.interact,
486 targetEntityId: pendingInteract.targetEntityId,
487 purpose: pendingInteract.purpose || undefined
488 });
455 489 clearPendingInteract();
456 490 }
457 491 }
@@ -510,6 +544,11 @@ function isAttackableEntity (entity)
510 544 return !!entity.mobTypeId && !entity.talkable;
511 545 }
512 546
547 function canTalkToEntity (entity)
548 {
549 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
550 }
551
513 552 function handleLeftClick (mouseX, mouseY)
514 553 {
515 554 const tile = view.screenToTile(mouseX, mouseY);
@@ -527,9 +566,14 @@ function handleLeftClick (mouseX, mouseY)
527 566 social.inspect(entity);
528 567 return;
529 568 }
530 if (entity.talkable)
569 // Dialogue (or shop/talkable) wins over attack as the default click.
570 if (canTalkToEntity(entity))
531 571 {
532 requestTalk(entity.entityId);
572 // Same intent as context-menu Talk / Shop so dialogue pin matches.
573 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
574 ? "talk"
575 : (entity.hasShop ? "shop" : "talk");
576 requestTalk(entity.entityId, purpose);
533 577 return;
534 578 }
535 579 if (isAttackableEntity(entity))
@@ -548,6 +592,8 @@ function handleLeftClick (mouseX, mouseY)
548 592 { requestPickup(ground); }
549 593 else if (isBankTile(view, tile.tileX, tile.tileY))
550 594 { requestOpenBank(tile.tileX, tile.tileY); }
595 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
596 { requestEnterDoorway(tile.tileX, tile.tileY); }
551 597 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
552 598 { requestOpenMarket(tile.tileX, tile.tileY); }
553 599 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
@@ -625,14 +671,14 @@ function handleRightClick (event, mouseX, mouseY)
625 671 {
626 672 items.push({
627 673 label: `Shop ${targetName}`,
628 onSelect: () => requestTalk(entity.entityId)
674 onSelect: () => requestTalk(entity.entityId, "shop")
629 675 });
630 676 }
631 else if (entity.talkable)
677 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
632 678 {
633 679 items.push({
634 680 label: `Talk to ${targetName}`,
635 onSelect: () => requestTalk(entity.entityId)
681 onSelect: () => requestTalk(entity.entityId, "talk")
636 682 });
637 683 }
638 684 if (entity.characterId)
@@ -673,6 +719,14 @@ function handleRightClick (event, mouseX, mouseY)
673 719 });
674 720 }
675 721
722 if (isDoorwayTile(view, tile.tileX, tile.tileY))
723 {
724 items.push({
725 label: "Enter",
726 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
727 });
728 }
729
676 730 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
677 731 {
678 732 items.push({
@@ -909,6 +963,8 @@ function startPlay (payload)
909 963 view.setSettings(payload.settings ?? view.settings);
910 964 chat?.syncSettings();
911 965 view.worldHour = payload.worldTime?.hour ?? 12;
966 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
967 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
912 968 view.setWorldSeason(payload.worldTime?.season);
913 969 view.setLocalEntity(
914 970 payload.entityId,
@@ -1001,6 +1057,25 @@ async function main ()
1001 1057 healthUi = initHealth();
1002 1058 statusEffectsUi = initStatusEffects();
1003 1059 toasts = initToasts();
1060 questsUi = initQuests({
1061 socket: { send (payload) { socket.send(payload); } },
1062 MessageType,
1063 toasts
1064 });
1065 dialogueUi = initDialogue({
1066 socket: { send (payload) { socket.send(payload); } },
1067 MessageType,
1068 getEntity (id)
1069 {
1070 if (id === "local")
1071 { return view?.entities.get(view.localEntityId) ?? null; }
1072 return view?.entities.get(id) ?? null;
1073 },
1074 captureSpeakerIcon (entityId, size = 64)
1075 {
1076 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1077 }
1078 });
1004 1079 shop = initShop({
1005 1080 socket: { send (payload) { socket.send(payload); } },
1006 1081 MessageType,
@@ -1081,10 +1156,27 @@ async function main ()
1081 1156 closeCreateModal();
1082 1157 startPlay(message);
1083 1158 inventory?.setLocalCharacterId(message.characterId);
1159 socket.send({ type: MessageType.requestQuests });
1084 1160 break;
1085 1161 case MessageType.chunkSnapshot:
1086 1162 view?.applySnapshot(message);
1087 1163 break;
1164 case MessageType.dimensionChanged:
1165 if (view)
1166 {
1167 view.setDimensionId(message.dimensionId);
1168 view.setDimensionModes(message.lightingMode, message.seasonMode);
1169 view.clearAllChunks();
1170 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1171 {
1172 view.moveEntity({
1173 entityId: view.localEntityId,
1174 tileX: message.tileX,
1175 tileY: message.tileY
1176 });
1177 }
1178 }
1179 break;
1088 1180 case MessageType.chunkDelta:
1089 1181 for (const tile of message.tiles ?? [])
1090 1182 {
@@ -1341,6 +1433,21 @@ async function main ()
1341 1433 if (playing)
1342 1434 { toasts?.show(message.message); }
1343 1435 break;
1436 case MessageType.questsSnapshot:
1437 questsUi?.applySnapshot(message);
1438 break;
1439 case MessageType.questStepComplete:
1440 questsUi?.handleStepComplete(message);
1441 break;
1442 case MessageType.dialogueStep:
1443 dialogueUi?.handleStep(message);
1444 break;
1445 case MessageType.dialogueChoices:
1446 dialogueUi?.handleChoices(message);
1447 break;
1448 case MessageType.dialogueClose:
1449 dialogueUi?.handleClose(message);
1450 break;
1344 1451 case MessageType.forceLogout:
1345 1452 returnToMenu(message.reason);
1346 1453 break;
@@ -1381,6 +1488,8 @@ function returnToMenu (reason = "")
1381 1488 shop?.close({ notifyServer: false });
1382 1489 bounty?.close();
1383 1490 barber?.close();
1491 questsUi?.reset();
1492 dialogueUi?.reset();
1384 1493 hideWorldTooltip();
1385 1494 if (view)
1386 1495 {
@@ -1453,6 +1562,11 @@ function isBankTile (view, tileX, tileY)
1453 1562 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1454 1563 }
1455 1564
1565 function isDoorwayTile (view, tileX, tileY)
1566 {
1567 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
1568 }
1569
1456 1570 function isMarketplaceTile (view, tileX, tileY)
1457 1571 {
1458 1572 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
@@ -1,6 +1,7 @@
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
1import { MessageType, GAIT, CHUNK_SIZE } from "/shared/protocol/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
2import { COMBAT_RANGE_TILES } from "/shared/spells/constants.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
3import { BlockType, BLOCK_DEFINITIONS, GROUND_DEFINITIONS, normalizeGround, resourceNodeDisplayName, isChopableTreeBlock, isPickablePlantBlock } from "/shared/definitions/tiles.js";
4import { OVERWORLD_ID } from "/shared/world/dimensions.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { GameSocket, defaultSocketUrl } from "../net/socket.js";
5import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { loadSpriteCatalog, preloadCatalogImages, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
6import { WorldView } from "../render/worldView.js";
7import { WorldView } from "../render/worldView.js";
@@ -17,6 +18,8 @@ import { initStatusEffects } from "./statusEffects.js";
17import { initContextMenu } from "./contextMenu.js";
18import { initContextMenu } from "./contextMenu.js";
18import { initDeath } from "./death.js";
19import { initDeath } from "./death.js";
19import { initToasts } from "./toasts.js";
20import { initToasts } from "./toasts.js";
21import { initQuests } from "./quests.js";
22import { initDialogue } from "./dialogue.js";
20import { initShop } from "./shop.js";
23import { initShop } from "./shop.js";
21import { initMarket } from "./market.js";
24import { initMarket } from "./market.js";
22import { initBounty } from "./bounty.js";
25import { initBounty } from "./bounty.js";
@@ -58,13 +61,15 @@ let statusEffectsUi;
58let contextMenu;
61let contextMenu;
59let death;
62let death;
60let toasts;
63let toasts;
64let questsUi;
65let dialogueUi;
61let shop;
66let shop;
62let market;
67let market;
63let bounty;
68let bounty;
64let barber;
69let barber;
65let createHairControls;
70let createHairControls;
66let pendingPickup = null;
71let pendingPickup = null;
67/** @type {{ kind: "bank" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
72/** @type {{ kind: "bank" | "doorway" | "cauldron" | "station" | "mine" | "chop", tileX: number, tileY: number, stationId?: string, getCheques?: boolean } | { kind: "talk", targetEntityId: number } | null } */
68let pendingInteract = null;
73let pendingInteract = null;
69/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
74/** Last approach moveTo so we do not re-path every frame (resets server walkCarry). */
70let approachMove = null;
75let approachMove = null;
@@ -115,6 +120,7 @@ function uiBlocked ()
115 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
120 return !!(social?.isBlocking() || chat?.isBlocking() || inventory?.isBlocking()
116 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
121 || crafting?.isBlocking() || alchemy?.isBlocking() || shop?.isBlocking()
117 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
122 || market?.isBlocking() || bounty?.isBlocking() || barber?.isBlocking()
123 || questsUi?.isBlocking() || dialogueUi?.isBlocking()
118 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
124 || contextMenu?.isOpen() || death?.isBlocking() || spells?.isBlocking()
119 || pointerOverSpellUi());
125 || pointerOverSpellUi());
120}
126}
@@ -223,6 +229,17 @@ function requestOpenBank (tileX, tileY, { getCheques = false } = {})
223 { approachAdjacentTile(tileX, tileY); }
229 { approachAdjacentTile(tileX, tileY); }
224}
230}
225
231
232function requestEnterDoorway (tileX, tileY)
233{
234 clearAllPendingActions();
235 pendingInteract = { kind: "doorway", tileX, tileY };
236 const local = view?.entities.get(view.localEntityId);
237 if (local && chebyshev(local.tileX, local.tileY, tileX, tileY) <= 1)
238 { flushPendingInteract(); }
239 else
240 { approachAdjacentTile(tileX, tileY); }
241}
242
226function requestOpenMarket (tileX, tileY)
243function requestOpenMarket (tileX, tileY)
227{
244{
228 clearAllPendingActions();
245 clearAllPendingActions();
@@ -316,10 +333,10 @@ function requestPick (tileX, tileY)
316 { approachAdjacentTile(tileX, tileY); }
333 { approachAdjacentTile(tileX, tileY); }
317}
334}
318
335
319function requestTalk (targetEntityId)
336function requestTalk (targetEntityId, purpose = null)
320{
337{
321 clearAllPendingActions();
338 clearAllPendingActions();
322 pendingInteract = { kind: "talk", targetEntityId };
339 pendingInteract = { kind: "talk", targetEntityId, purpose };
323 const target = view?.entities.get(targetEntityId);
340 const target = view?.entities.get(targetEntityId);
324 if (!target)
341 if (!target)
325 {
342 {
@@ -350,6 +367,19 @@ function flushPendingInteract ()
350 return;
367 return;
351 }
368 }
352
369
370 if (pendingInteract.kind === "doorway")
371 {
372 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
373 { return; }
374 socket.send({
375 type: MessageType.enterDoorway,
376 tileX: pendingInteract.tileX,
377 tileY: pendingInteract.tileY
378 });
379 clearPendingInteract();
380 return;
381 }
382
353 if (pendingInteract.kind === "market")
383 if (pendingInteract.kind === "market")
354 {
384 {
355 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
385 if (chebyshev(local.tileX, local.tileY, pendingInteract.tileX, pendingInteract.tileY) > 1)
@@ -451,7 +481,11 @@ function flushPendingInteract ()
451 approachAdjacentTile(target.tileX, target.tileY);
481 approachAdjacentTile(target.tileX, target.tileY);
452 return;
482 return;
453 }
483 }
454 socket.send({ type: MessageType.interact, targetEntityId: pendingInteract.targetEntityId });
484 socket.send({
485 type: MessageType.interact,
486 targetEntityId: pendingInteract.targetEntityId,
487 purpose: pendingInteract.purpose || undefined
488 });
455 clearPendingInteract();
489 clearPendingInteract();
456 }
490 }
457}
491}
@@ -510,6 +544,11 @@ function isAttackableEntity (entity)
510 return !!entity.mobTypeId && !entity.talkable;
544 return !!entity.mobTypeId && !entity.talkable;
511}
545}
512
546
547function canTalkToEntity (entity)
548{
549 return !!(entity && (entity.hasDialogue || entity.talkable || entity.hasShop));
550}
551
513function handleLeftClick (mouseX, mouseY)
552function handleLeftClick (mouseX, mouseY)
514{
553{
515 const tile = view.screenToTile(mouseX, mouseY);
554 const tile = view.screenToTile(mouseX, mouseY);
@@ -527,9 +566,14 @@ function handleLeftClick (mouseX, mouseY)
527 social.inspect(entity);
566 social.inspect(entity);
528 return;
567 return;
529 }
568 }
530 if (entity.talkable)
569 // Dialogue (or shop/talkable) wins over attack as the default click.
570 if (canTalkToEntity(entity))
531 {
571 {
532 requestTalk(entity.entityId);
572 // Same intent as context-menu Talk / Shop so dialogue pin matches.
573 const purpose = entity.hasDialogue || (entity.talkable && !entity.hasShop)
574 ? "talk"
575 : (entity.hasShop ? "shop" : "talk");
576 requestTalk(entity.entityId, purpose);
533 return;
577 return;
534 }
578 }
535 if (isAttackableEntity(entity))
579 if (isAttackableEntity(entity))
@@ -548,6 +592,8 @@ function handleLeftClick (mouseX, mouseY)
548 { requestPickup(ground); }
592 { requestPickup(ground); }
549 else if (isBankTile(view, tile.tileX, tile.tileY))
593 else if (isBankTile(view, tile.tileX, tile.tileY))
550 { requestOpenBank(tile.tileX, tile.tileY); }
594 { requestOpenBank(tile.tileX, tile.tileY); }
595 else if (isDoorwayTile(view, tile.tileX, tile.tileY))
596 { requestEnterDoorway(tile.tileX, tile.tileY); }
551 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
597 else if (isMarketplaceTile(view, tile.tileX, tile.tileY))
552 { requestOpenMarket(tile.tileX, tile.tileY); }
598 { requestOpenMarket(tile.tileX, tile.tileY); }
553 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
599 else if (isBountyOfficeTile(view, tile.tileX, tile.tileY))
@@ -625,14 +671,14 @@ function handleRightClick (event, mouseX, mouseY)
625 {
671 {
626 items.push({
672 items.push({
627 label: `Shop ${targetName}`,
673 label: `Shop ${targetName}`,
628 onSelect: () => requestTalk(entity.entityId)
674 onSelect: () => requestTalk(entity.entityId, "shop")
629 });
675 });
630 }
676 }
631 else if (entity.talkable)
677 if (entity.hasDialogue || (entity.talkable && !entity.hasShop))
632 {
678 {
633 items.push({
679 items.push({
634 label: `Talk to ${targetName}`,
680 label: `Talk to ${targetName}`,
635 onSelect: () => requestTalk(entity.entityId)
681 onSelect: () => requestTalk(entity.entityId, "talk")
636 });
682 });
637 }
683 }
638 if (entity.characterId)
684 if (entity.characterId)
@@ -673,6 +719,14 @@ function handleRightClick (event, mouseX, mouseY)
673 });
719 });
674 }
720 }
675
721
722 if (isDoorwayTile(view, tile.tileX, tile.tileY))
723 {
724 items.push({
725 label: "Enter",
726 onSelect: () => requestEnterDoorway(tile.tileX, tile.tileY)
727 });
728 }
729
676 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
730 if (isMarketplaceTile(view, tile.tileX, tile.tileY))
677 {
731 {
678 items.push({
732 items.push({
@@ -909,6 +963,8 @@ function startPlay (payload)
909 view.setSettings(payload.settings ?? view.settings);
963 view.setSettings(payload.settings ?? view.settings);
910 chat?.syncSettings();
964 chat?.syncSettings();
911 view.worldHour = payload.worldTime?.hour ?? 12;
965 view.worldHour = payload.worldTime?.hour ?? 12;
966 view.setDimensionId(payload.dimensionId ?? OVERWORLD_ID);
967 view.setDimensionModes(payload.lightingMode, payload.seasonMode);
912 view.setWorldSeason(payload.worldTime?.season);
968 view.setWorldSeason(payload.worldTime?.season);
913 view.setLocalEntity(
969 view.setLocalEntity(
914 payload.entityId,
970 payload.entityId,
@@ -1001,6 +1057,25 @@ async function main ()
1001 healthUi = initHealth();
1057 healthUi = initHealth();
1002 statusEffectsUi = initStatusEffects();
1058 statusEffectsUi = initStatusEffects();
1003 toasts = initToasts();
1059 toasts = initToasts();
1060 questsUi = initQuests({
1061 socket: { send (payload) { socket.send(payload); } },
1062 MessageType,
1063 toasts
1064 });
1065 dialogueUi = initDialogue({
1066 socket: { send (payload) { socket.send(payload); } },
1067 MessageType,
1068 getEntity (id)
1069 {
1070 if (id === "local")
1071 { return view?.entities.get(view.localEntityId) ?? null; }
1072 return view?.entities.get(id) ?? null;
1073 },
1074 captureSpeakerIcon (entityId, size = 64)
1075 {
1076 return view?.captureEntityPortrait?.(entityId, { size }) ?? null;
1077 }
1078 });
1004 shop = initShop({
1079 shop = initShop({
1005 socket: { send (payload) { socket.send(payload); } },
1080 socket: { send (payload) { socket.send(payload); } },
1006 MessageType,
1081 MessageType,
@@ -1081,10 +1156,27 @@ async function main ()
1081 closeCreateModal();
1156 closeCreateModal();
1082 startPlay(message);
1157 startPlay(message);
1083 inventory?.setLocalCharacterId(message.characterId);
1158 inventory?.setLocalCharacterId(message.characterId);
1159 socket.send({ type: MessageType.requestQuests });
1084 break;
1160 break;
1085 case MessageType.chunkSnapshot:
1161 case MessageType.chunkSnapshot:
1086 view?.applySnapshot(message);
1162 view?.applySnapshot(message);
1087 break;
1163 break;
1164 case MessageType.dimensionChanged:
1165 if (view)
1166 {
1167 view.setDimensionId(message.dimensionId);
1168 view.setDimensionModes(message.lightingMode, message.seasonMode);
1169 view.clearAllChunks();
1170 if (message.tileX != null && message.tileY != null && view.localEntityId != null)
1171 {
1172 view.moveEntity({
1173 entityId: view.localEntityId,
1174 tileX: message.tileX,
1175 tileY: message.tileY
1176 });
1177 }
1178 }
1179 break;
1088 case MessageType.chunkDelta:
1180 case MessageType.chunkDelta:
1089 for (const tile of message.tiles ?? [])
1181 for (const tile of message.tiles ?? [])
1090 {
1182 {
@@ -1341,6 +1433,21 @@ async function main ()
1341 if (playing)
1433 if (playing)
1342 { toasts?.show(message.message); }
1434 { toasts?.show(message.message); }
1343 break;
1435 break;
1436 case MessageType.questsSnapshot:
1437 questsUi?.applySnapshot(message);
1438 break;
1439 case MessageType.questStepComplete:
1440 questsUi?.handleStepComplete(message);
1441 break;
1442 case MessageType.dialogueStep:
1443 dialogueUi?.handleStep(message);
1444 break;
1445 case MessageType.dialogueChoices:
1446 dialogueUi?.handleChoices(message);
1447 break;
1448 case MessageType.dialogueClose:
1449 dialogueUi?.handleClose(message);
1450 break;
1344 case MessageType.forceLogout:
1451 case MessageType.forceLogout:
1345 returnToMenu(message.reason);
1452 returnToMenu(message.reason);
1346 break;
1453 break;
@@ -1381,6 +1488,8 @@ function returnToMenu (reason = "")
1381 shop?.close({ notifyServer: false });
1488 shop?.close({ notifyServer: false });
1382 bounty?.close();
1489 bounty?.close();
1383 barber?.close();
1490 barber?.close();
1491 questsUi?.reset();
1492 dialogueUi?.reset();
1384 hideWorldTooltip();
1493 hideWorldTooltip();
1385 if (view)
1494 if (view)
1386 {
1495 {
@@ -1453,6 +1562,11 @@ function isBankTile (view, tileX, tileY)
1453 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1562 return blockTypeAt(view, tileX, tileY) === BlockType.bank;
1454}
1563}
1455
1564
1565function isDoorwayTile (view, tileX, tileY)
1566{
1567 return blockTypeAt(view, tileX, tileY) === BlockType.doorway;
1568}
1569
1456function isMarketplaceTile (view, tileX, tileY)
1570function isMarketplaceTile (view, tileX, tileY)
1457{
1571{
1458 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
1572 return blockTypeAt(view, tileX, tileY) === BlockType.marketplace;
client/src/play/quests.js added +204 −0
@@ -0,0 +1,204 @@
1 /**
2 * Play HUD Quests list + detail modals.
3 */
4 export function initQuests ({ socket, MessageType, toasts })
5 {
6 const listBackdrop = document.getElementById("quests-list-backdrop");
7 const listPanel = document.getElementById("quests-list-panel");
8 const listBody = document.getElementById("quests-list-body");
9 const detailBackdrop = document.getElementById("quests-detail-backdrop");
10 const detailPanel = document.getElementById("quests-detail-panel");
11 const detailTitle = document.getElementById("quests-detail-title");
12 const journalEl = document.getElementById("quests-detail-journal");
13 const stepEl = document.getElementById("quests-detail-step");
14 /** @type {any[]} */
15 let quests = [];
16 let listOpen = false;
17 let detailOpen = false;
18 let detailQuestId = null;
19
20 function showList (visible)
21 {
22 listOpen = visible;
23 if (listBackdrop)
24 { listBackdrop.hidden = !visible; }
25 if (listPanel)
26 { listPanel.hidden = !visible; }
27 if (visible)
28 { renderList(); }
29 }
30
31 function showDetail (visible, questId = null)
32 {
33 detailOpen = visible;
34 detailQuestId = visible ? questId : null;
35 if (detailBackdrop)
36 { detailBackdrop.hidden = !visible; }
37 if (detailPanel)
38 { detailPanel.hidden = !visible; }
39 if (visible)
40 { renderDetail(); }
41 }
42
43 function renderList ()
44 {
45 if (!listBody)
46 { return; }
47 listBody.replaceChildren();
48 if (!quests.length)
49 {
50 const empty = document.createElement("p");
51 empty.className = "hint";
52 empty.textContent = "No quests yet.";
53 listBody.append(empty);
54 return;
55 }
56 for (const quest of quests)
57 {
58 const btn = document.createElement("button");
59 btn.type = "button";
60 btn.className = "quests-list-item";
61 const status = quest.state === "completed"
62 ? "Completed"
63 : (quest.orphaned ? "Unavailable" : "Active");
64 btn.textContent = `${quest.title} — ${status}`;
65 btn.addEventListener("click", () =>
66 {
67 showList(false);
68 showDetail(true, quest.questId);
69 });
70 listBody.append(btn);
71 }
72 }
73
74 function renderDetail ()
75 {
76 const quest = quests.find((q) => q.questId === detailQuestId);
77 if (!quest)
78 {
79 if (detailTitle)
80 { detailTitle.textContent = "Quest"; }
81 journalEl?.replaceChildren();
82 stepEl?.replaceChildren();
83 return;
84 }
85 if (detailTitle)
86 { detailTitle.textContent = quest.title; }
87
88 journalEl?.replaceChildren();
89 const journal = quest.journal ?? [];
90 if (!journal.length)
91 {
92 const empty = document.createElement("p");
93 empty.className = "hint";
94 empty.textContent = "No journal entries yet.";
95 journalEl?.append(empty);
96 }
97 else
98 {
99 for (const entry of journal)
100 {
101 const p = document.createElement("p");
102 p.className = "quests-journal-entry";
103 p.textContent = entry.text || "";
104 journalEl?.append(p);
105 }
106 }
107
108 stepEl?.replaceChildren();
109 if (quest.state === "completed")
110 {
111 const done = document.createElement("p");
112 done.textContent = "Quest complete.";
113 stepEl?.append(done);
114 return;
115 }
116 if (quest.orphaned || !quest.step)
117 {
118 const miss = document.createElement("p");
119 miss.className = "hint";
120 miss.textContent = quest.description || "Quest data unavailable.";
121 stepEl?.append(miss);
122 return;
123 }
124 const title = document.createElement("h3");
125 title.textContent = quest.step.title || "Current step";
126 const desc = document.createElement("p");
127 desc.textContent = quest.step.description || "";
128 stepEl?.append(title, desc);
129 const ul = document.createElement("ul");
130 ul.className = "quests-objectives";
131 for (const obj of quest.step.objectives ?? [])
132 {
133 const li = document.createElement("li");
134 li.textContent = obj.text || "";
135 if (obj.done)
136 { li.classList.add("done"); }
137 ul.append(li);
138 }
139 stepEl?.append(ul);
140 }
141
142 document.getElementById("quests-toggle")?.addEventListener("click", () =>
143 {
144 if (listOpen)
145 { showList(false); }
146 else
147 {
148 showDetail(false);
149 socket.send({ type: MessageType.requestQuests });
150 showList(true);
151 }
152 });
153 document.getElementById("quests-list-close")?.addEventListener("click", () => showList(false));
154 listBackdrop?.addEventListener("click", () => showList(false));
155 document.getElementById("quests-detail-close")?.addEventListener("click", () => showDetail(false));
156 document.getElementById("quests-detail-back")?.addEventListener("click", () =>
157 {
158 showDetail(false);
159 showList(true);
160 });
161 detailBackdrop?.addEventListener("click", () => showDetail(false));
162
163 return {
164 isBlocking ()
165 {
166 return listOpen || detailOpen;
167 },
168 applySnapshot (message)
169 {
170 quests = Array.isArray(message?.quests) ? message.quests : [];
171 if (listOpen)
172 { renderList(); }
173 if (detailOpen)
174 { renderDetail(); }
175 },
176 handleStepComplete (message)
177 {
178 const questId = message?.questId;
179 toasts?.show("Quest objectives achieved", {
180 onClick: () =>
181 {
182 showList(false);
183 if (questId)
184 { showDetail(true, questId); }
185 }
186 });
187 },
188 openQuest (questId)
189 {
190 showList(false);
191 showDetail(true, questId);
192 },
193 hide ()
194 {
195 showList(false);
196 showDetail(false);
197 },
198 reset ()
199 {
200 quests = [];
201 this.hide();
202 }
203 };
204 }
@@ -0,0 +1,204 @@
1/**
2 * Play HUD Quests list + detail modals.
3 */
4export function initQuests ({ socket, MessageType, toasts })
5{
6 const listBackdrop = document.getElementById("quests-list-backdrop");
7 const listPanel = document.getElementById("quests-list-panel");
8 const listBody = document.getElementById("quests-list-body");
9 const detailBackdrop = document.getElementById("quests-detail-backdrop");
10 const detailPanel = document.getElementById("quests-detail-panel");
11 const detailTitle = document.getElementById("quests-detail-title");
12 const journalEl = document.getElementById("quests-detail-journal");
13 const stepEl = document.getElementById("quests-detail-step");
14 /** @type {any[]} */
15 let quests = [];
16 let listOpen = false;
17 let detailOpen = false;
18 let detailQuestId = null;
19
20 function showList (visible)
21 {
22 listOpen = visible;
23 if (listBackdrop)
24 { listBackdrop.hidden = !visible; }
25 if (listPanel)
26 { listPanel.hidden = !visible; }
27 if (visible)
28 { renderList(); }
29 }
30
31 function showDetail (visible, questId = null)
32 {
33 detailOpen = visible;
34 detailQuestId = visible ? questId : null;
35 if (detailBackdrop)
36 { detailBackdrop.hidden = !visible; }
37 if (detailPanel)
38 { detailPanel.hidden = !visible; }
39 if (visible)
40 { renderDetail(); }
41 }
42
43 function renderList ()
44 {
45 if (!listBody)
46 { return; }
47 listBody.replaceChildren();
48 if (!quests.length)
49 {
50 const empty = document.createElement("p");
51 empty.className = "hint";
52 empty.textContent = "No quests yet.";
53 listBody.append(empty);
54 return;
55 }
56 for (const quest of quests)
57 {
58 const btn = document.createElement("button");
59 btn.type = "button";
60 btn.className = "quests-list-item";
61 const status = quest.state === "completed"
62 ? "Completed"
63 : (quest.orphaned ? "Unavailable" : "Active");
64 btn.textContent = `${quest.title} — ${status}`;
65 btn.addEventListener("click", () =>
66 {
67 showList(false);
68 showDetail(true, quest.questId);
69 });
70 listBody.append(btn);
71 }
72 }
73
74 function renderDetail ()
75 {
76 const quest = quests.find((q) => q.questId === detailQuestId);
77 if (!quest)
78 {
79 if (detailTitle)
80 { detailTitle.textContent = "Quest"; }
81 journalEl?.replaceChildren();
82 stepEl?.replaceChildren();
83 return;
84 }
85 if (detailTitle)
86 { detailTitle.textContent = quest.title; }
87
88 journalEl?.replaceChildren();
89 const journal = quest.journal ?? [];
90 if (!journal.length)
91 {
92 const empty = document.createElement("p");
93 empty.className = "hint";
94 empty.textContent = "No journal entries yet.";
95 journalEl?.append(empty);
96 }
97 else
98 {
99 for (const entry of journal)
100 {
101 const p = document.createElement("p");
102 p.className = "quests-journal-entry";
103 p.textContent = entry.text || "";
104 journalEl?.append(p);
105 }
106 }
107
108 stepEl?.replaceChildren();
109 if (quest.state === "completed")
110 {
111 const done = document.createElement("p");
112 done.textContent = "Quest complete.";
113 stepEl?.append(done);
114 return;
115 }
116 if (quest.orphaned || !quest.step)
117 {
118 const miss = document.createElement("p");
119 miss.className = "hint";
120 miss.textContent = quest.description || "Quest data unavailable.";
121 stepEl?.append(miss);
122 return;
123 }
124 const title = document.createElement("h3");
125 title.textContent = quest.step.title || "Current step";
126 const desc = document.createElement("p");
127 desc.textContent = quest.step.description || "";
128 stepEl?.append(title, desc);
129 const ul = document.createElement("ul");
130 ul.className = "quests-objectives";
131 for (const obj of quest.step.objectives ?? [])
132 {
133 const li = document.createElement("li");
134 li.textContent = obj.text || "";
135 if (obj.done)
136 { li.classList.add("done"); }
137 ul.append(li);
138 }
139 stepEl?.append(ul);
140 }
141
142 document.getElementById("quests-toggle")?.addEventListener("click", () =>
143 {
144 if (listOpen)
145 { showList(false); }
146 else
147 {
148 showDetail(false);
149 socket.send({ type: MessageType.requestQuests });
150 showList(true);
151 }
152 });
153 document.getElementById("quests-list-close")?.addEventListener("click", () => showList(false));
154 listBackdrop?.addEventListener("click", () => showList(false));
155 document.getElementById("quests-detail-close")?.addEventListener("click", () => showDetail(false));
156 document.getElementById("quests-detail-back")?.addEventListener("click", () =>
157 {
158 showDetail(false);
159 showList(true);
160 });
161 detailBackdrop?.addEventListener("click", () => showDetail(false));
162
163 return {
164 isBlocking ()
165 {
166 return listOpen || detailOpen;
167 },
168 applySnapshot (message)
169 {
170 quests = Array.isArray(message?.quests) ? message.quests : [];
171 if (listOpen)
172 { renderList(); }
173 if (detailOpen)
174 { renderDetail(); }
175 },
176 handleStepComplete (message)
177 {
178 const questId = message?.questId;
179 toasts?.show("Quest objectives achieved", {
180 onClick: () =>
181 {
182 showList(false);
183 if (questId)
184 { showDetail(true, questId); }
185 }
186 });
187 },
188 openQuest (questId)
189 {
190 showList(false);
191 showDetail(true, questId);
192 },
193 hide ()
194 {
195 showList(false);
196 showDetail(false);
197 },
198 reset ()
199 {
200 quests = [];
201 this.hide();
202 }
203 };
204}
client/src/play/toasts.js +22 −6
@@ -21,21 +21,37 @@ export function initToasts ()
21 21 if (!text)
22 22 { return; }
23 23 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
24 const onClick = typeof options.onClick === "function" ? options.onClick : null;
24 25 const el = document.createElement("div");
25 26 el.className = "toast";
26 27 el.setAttribute("role", "status");
27 28 el.textContent = text;
29 let dismissed = false;
30 const dismiss = () =>
31 {
32 if (dismissed)
33 { return; }
34 dismissed = true;
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 };
39 if (onClick)
40 {
41 el.classList.add("toast-clickable");
42 el.style.cursor = "pointer";
43 el.addEventListener("click", () =>
44 {
45 onClick();
46 dismiss();
47 });
48 }
28 49 root.appendChild(el);
29 50 requestAnimationFrame(() =>
30 51 {
31 52 el.classList.add("toast-visible");
32 53 });
33 window.setTimeout(() =>
34 {
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 }, durationMs);
54 window.setTimeout(dismiss, durationMs);
39 55 }
40 56
41 57 return { show };
@@ -21,21 +21,37 @@ export function initToasts ()
21 if (!text)
21 if (!text)
22 { return; }
22 { return; }
23 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
23 const durationMs = Math.max(800, options.durationMs ?? DEFAULT_DURATION_MS);
24 const onClick = typeof options.onClick === "function" ? options.onClick : null;
24 const el = document.createElement("div");
25 const el = document.createElement("div");
25 el.className = "toast";
26 el.className = "toast";
26 el.setAttribute("role", "status");
27 el.setAttribute("role", "status");
27 el.textContent = text;
28 el.textContent = text;
29 let dismissed = false;
30 const dismiss = () =>
31 {
32 if (dismissed)
33 { return; }
34 dismissed = true;
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 };
39 if (onClick)
40 {
41 el.classList.add("toast-clickable");
42 el.style.cursor = "pointer";
43 el.addEventListener("click", () =>
44 {
45 onClick();
46 dismiss();
47 });
48 }
28 root.appendChild(el);
49 root.appendChild(el);
29 requestAnimationFrame(() =>
50 requestAnimationFrame(() =>
30 {
51 {
31 el.classList.add("toast-visible");
52 el.classList.add("toast-visible");
32 });
53 });
33 window.setTimeout(() =>
54 window.setTimeout(dismiss, durationMs);
34 {
35 el.classList.remove("toast-visible");
36 el.classList.add("toast-leaving");
37 window.setTimeout(() => el.remove(), LEAVE_MS);
38 }, durationMs);
39 }
55 }
40
56
41 return { show };
57 return { show };
client/src/render/worldView.js +381 −25
@@ -13,6 +13,14 @@ import {
13 13 } from "./canvasSprite.js";
14 14 import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15 15 import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16 import {
17 OVERWORLD_ID,
18 normalizeDimensionId,
19 normalizeLightingMode,
20 normalizeSeasonMode,
21 resolveDimensionDarknessFactor,
22 resolveDimensionSeasonId
23 } from "/shared/world/dimensions.js";
16 24 import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
17 25
18 26 const LAYER_GROUND = 0;
@@ -179,6 +187,39 @@ const DUAL_TINT_LIT_SPRITE_FRAG = [
179 187 ].join("\n");
180 188
181 189 /** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
190 /**
191 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
192 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
193 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
194 */
195 const TIGHT_FIT_BODY_MASK_GLSL = [
196 "uniform vec2 u_clothSize;",
197 "uniform vec2 u_bodySize;",
198 "uniform float u_pivotFromBottom;",
199 "uniform vec4 u_clothUvRect;",
200 "uniform vec4 u_bodyUvRect;",
201 "float tightFitBodyAlpha() {",
202 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
203 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
204 " float ox = (nu.x - 0.5) * u_clothSize.x;",
205 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
206 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
207 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
208 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
209 " vec2 texel = 1.0 / bodySize;",
210 " float bodyA = 0.0;",
211 " for (int dy = -1; dy <= 1; dy++) {",
212 " for (int dx = -1; dx <= 1; dx++) {",
213 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
214 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
215 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
216 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
217 " }",
218 " }",
219 " return bodyA;",
220 "}"
221 ].join("\n");
222
182 223 const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
183 224 "precision mediump float;",
184 225 "varying vec2 v_texCoord;",
@@ -190,6 +231,7 @@ const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
190 231 "uniform float u_spriteHeight;",
191 232 "uniform float u_useTint;",
192 233 "uniform vec3 u_tintColor;",
234 TIGHT_FIT_BODY_MASK_GLSL,
193 235 "void main() {",
194 236 " vec4 color = texture2D(u_texture, v_texCoord);",
195 237 " if (color.a <= 0.0) { discard; }",
@@ -209,8 +251,7 @@ const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
209 251 " }",
210 252 " rgb = mix(rgb, vec3(0.0), u_darkness);",
211 253 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
212 " vec4 bodyPx = texture2D(u_secondary, v_texCoord);",
213 " float alpha = min(bodyPx.a, color.a);",
254 " float alpha = min(tightFitBodyAlpha(), color.a);",
214 255 " if (alpha <= 0.0) { discard; }",
215 256 " gl_FragColor = vec4(rgb, alpha);",
216 257 "}"
@@ -226,6 +267,7 @@ const TIGHT_FIT_LIT_SPRITE_FRAG = [
226 267 "uniform float u_strength;",
227 268 "uniform float u_wade;",
228 269 "uniform float u_spriteHeight;",
270 TIGHT_FIT_BODY_MASK_GLSL,
229 271 "void main() {",
230 272 " vec4 color = texture2D(u_texture, v_texCoord);",
231 273 " if (color.a <= 0.0) { discard; }",
@@ -237,8 +279,7 @@ const TIGHT_FIT_LIT_SPRITE_FRAG = [
237 279 " }",
238 280 " rgb = mix(rgb, vec3(0.0), u_darkness);",
239 281 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
240 " vec4 bodyPx = texture2D(u_secondary, v_texCoord);",
241 " float alpha = min(bodyPx.a, color.a);",
282 " float alpha = min(tightFitBodyAlpha(), color.a);",
242 283 " if (alpha <= 0.0) { discard; }",
243 284 " gl_FragColor = vec4(rgb, alpha);",
244 285 "}"
@@ -339,6 +380,14 @@ export class WorldView
339 380 this.edges = new Map();
340 381 this.localEntityId = null;
341 382 this.localBlind = false;
383 /** @type {string} */
384 this.dimensionId = OVERWORLD_ID;
385 /** @type {string} */
386 this.dimensionLightingMode = "dayNight";
387 /** @type {string} */
388 this.dimensionSeasonMode = "auto";
389 /** Calendar season from worldStatus when dimension season is auto. */
390 this.calendarSeason = seasonIdAt();
342 391 /** @type {"soft"|"simple"} */
343 392 this.lightingMode = "soft";
344 393 /** @type {boolean} */
@@ -394,35 +443,58 @@ export class WorldView
394 443 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
395 444 setWorldSeason (season)
396 445 {
397 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
446 const calendar = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
398 447 ? season
399 448 : seasonIdAt();
449 this.calendarSeason = calendar;
450 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
451 const next = forced ?? calendar;
400 452 if (next === this.worldSeason)
401 453 { return; }
402 454 this.worldSeason = next;
403 455 this.#rebakeAllChunks();
404 456 }
405 457
406 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
458 setDimensionId (dimensionId)
407 459 {
408 this.localEntityId = entityId;
409 this.#upsertEntity({
410 entityId,
411 characterId,
412 tileX,
413 tileY,
414 gait,
415 sex,
416 firstName,
417 lastName,
418 layers: layers ?? undefined,
419 ...(health != null ? { health } : {}),
420 ...(maxHealth != null ? { maxHealth } : {})
421 });
460 this.dimensionId = normalizeDimensionId(dimensionId);
461 }
462
463 setDimensionModes (lightingMode, seasonMode)
464 {
465 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
466 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
467 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
468 const next = forced ?? this.calendarSeason ?? seasonIdAt();
469 if (next !== this.worldSeason)
470 {
471 this.worldSeason = next;
472 this.#rebakeAllChunks();
473 }
474 }
475
476 clearAllChunks ()
477 {
478 for (const key of [...this.chunks.keys()])
479 {
480 const [chunkX, chunkY] = key.split(",").map(Number);
481 this.removeChunk(chunkX, chunkY);
482 }
483 for (const [id] of [...this.entities.entries()])
484 {
485 if (id === this.localEntityId)
486 { continue; }
487 this.despawnEntity(id);
488 }
489 for (const [id] of [...this.groundItems.entries()])
490 { this.despawnGroundItem(id); }
422 491 }
423 492
424 493 applySnapshot (snapshot)
425 494 {
495 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
496 if (normalizeDimensionId(this.dimensionId) !== snapDim)
497 { return; }
426 498 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
427 499 this.chunks.set(key, snapshot);
428 500 this.#rebuildChunk(snapshot);
@@ -436,7 +508,6 @@ export class WorldView
436 508 }
437 509 for (const entity of snapshot.entities ?? [])
438 510 { this.#upsertEntity(entity); }
439 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
440 511 for (const [id, item] of [...this.groundItems.entries()])
441 512 {
442 513 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
@@ -447,6 +518,24 @@ export class WorldView
447 518 this.#rebuildAllEdges();
448 519 }
449 520
521 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
522 {
523 this.localEntityId = entityId;
524 this.#upsertEntity({
525 entityId,
526 characterId,
527 tileX,
528 tileY,
529 gait,
530 sex,
531 firstName,
532 lastName,
533 layers: layers ?? undefined,
534 ...(health != null ? { health } : {}),
535 ...(maxHealth != null ? { maxHealth } : {})
536 });
537 }
538
450 539 #stripChunkDynamic (chunkX, chunkY)
451 540 {
452 541 for (const [id, item] of [...this.groundItems.entries()])
@@ -625,6 +714,245 @@ export class WorldView
625 714 this.#placeEntity(existing);
626 715 }
627 716
717 /**
718 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
719 * world, unlit) into an offscreen FBO, crop the top square, and return a
720 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
721 * @param {number} entityId
722 * @param {{ size?: number }} [options]
723 * @returns {HTMLCanvasElement | null}
724 */
725 captureEntityPortrait (entityId, { size = 64 } = {})
726 {
727 const entity = this.entities.get(entityId);
728 const body = entity?.object?.renderer?.sprite;
729 const glCtx = this.scene?.glContext;
730 const gl = glCtx?.gl;
731 if (!entity || !body || !gl)
732 { return null; }
733
734 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
735 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
736 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
737 { return null; }
738
739 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
740 const prevViewport = gl.getParameter(gl.VIEWPORT);
741 const prevW = glCtx._lastWidth;
742 const prevH = glCtx._lastHeight;
743 const prevBlend = gl.isEnabled(gl.BLEND);
744
745 try
746 {
747 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
748 glCtx._lastWidth = frameW;
749 glCtx._lastHeight = frameH;
750 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
751 gl.viewport(0, 0, frameW, frameH);
752 gl.enable(gl.BLEND);
753 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
754 gl.clearColor(0, 0, 0, 0);
755 gl.clear(gl.COLOR_BUFFER_BIT);
756
757 const pivotX = frameW * 0.5;
758 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
759 this._portraitBodyMap = body.g_image ?? null;
760 this._portraitTightFitEntity = entity;
761 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
762
763 const overlays = entity.overlays ?? [];
764 const tints = entity.overlayTints ?? [];
765 const tight = entity.overlayTightFit ?? [];
766 for (let index = 0; index < overlays.length; index++)
767 {
768 this.#drawPortraitLayer(
769 glCtx,
770 overlays[index],
771 pivotX,
772 pivotY,
773 tints[index] ?? null,
774 !!tight[index]
775 );
776 }
777 this._portraitBodyMap = null;
778 this._portraitTightFitEntity = null;
779
780 const pixels = this._portrait.pixels;
781 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
782 }
783 finally
784 {
785 glCtx._lastWidth = prevW;
786 glCtx._lastHeight = prevH;
787 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
788 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
789 if (!prevBlend)
790 { gl.disable(gl.BLEND); }
791 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
792 }
793
794 return this.#portraitPixelsToCanvas(frameW, frameH, size);
795 }
796
797 #ensurePortraitTarget (gl, width, height)
798 {
799 const prev = this._portrait;
800 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
801 { return true; }
802 if (prev?.fb)
803 { gl.deleteFramebuffer(prev.fb); }
804 if (prev?.tex)
805 { gl.deleteTexture(prev.tex); }
806
807 const tex = gl.createTexture();
808 gl.bindTexture(gl.TEXTURE_2D, tex);
809 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
810 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
811 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
812 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
813 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
814
815 const fb = gl.createFramebuffer();
816 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
817 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
818 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
819 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
820 if (status !== gl.FRAMEBUFFER_COMPLETE)
821 {
822 gl.deleteFramebuffer(fb);
823 gl.deleteTexture(tex);
824 this._portrait = null;
825 return false;
826 }
827 this._portrait = {
828 fb,
829 tex,
830 w: width,
831 h: height,
832 pixels: new Uint8Array(width * height * 4),
833 scratch: document.createElement("canvas")
834 };
835 return true;
836 }
837
838 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit)
839 {
840 const sprite = object?.renderer?.sprite;
841 if (!sprite?.g_image)
842 { return; }
843 const subImage = object.renderer.subImage | 0;
844 const height = sprite.height || SPRITE_SIZE_PX;
845 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
846 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
847 const tint = tintColor ? normalizeRgb(tintColor) : null;
848 let shader = glCtx.defaultShader;
849 let uniforms = null;
850 let secondaryHtml = null;
851
852 const bodyHtml = this._portraitBodyMap;
853 const portraitEntity = this._portraitTightFitEntity;
854 const maskUniforms = tightFit && portraitEntity
855 ? this.#tightFitMaskUniforms(object, portraitEntity)
856 : null;
857 if (tightFit && bodyHtml && maskUniforms)
858 {
859 secondaryHtml = bodyHtml;
860 if (tint)
861 {
862 shader = getTightFitTintLitSpriteShader();
863 uniforms = {
864 u_darkness: 0,
865 u_strength: 0,
866 u_wade: 0,
867 u_spriteHeight: height,
868 u_useTint: 1,
869 u_tintColor: [tint.r, tint.g, tint.b],
870 ...maskUniforms
871 };
872 }
873 else
874 {
875 shader = getTightFitLitSpriteShader();
876 uniforms = {
877 u_darkness: 0,
878 u_strength: 0,
879 u_wade: 0,
880 u_spriteHeight: height,
881 ...maskUniforms
882 };
883 }
884 }
885 else if (tint)
886 {
887 shader = getTintLitSpriteShader();
888 uniforms = {
889 u_darkness: 0,
890 u_strength: 0,
891 u_wade: 0,
892 u_spriteHeight: height,
893 u_useTint: 1,
894 u_tintColor: [tint.r, tint.g, tint.b]
895 };
896 }
897 else
898 {
899 shader = getSpriteLightingShader();
900 uniforms = {
901 u_darkness: 0,
902 u_strength: 0,
903 u_wade: 0,
904 u_spriteHeight: height
905 };
906 }
907
908 glCtx.drawSprite({
909 texture: glCtx.getTexture(sprite.g_image),
910 x: center.x,
911 y: center.y,
912 w: draw.w,
913 h: draw.h,
914 rotationDeg: 0,
915 mirrorX: false,
916 mirrorY: false,
917 alpha: 1,
918 uvRect: sprite.getUvRect(subImage),
919 shader,
920 uniforms,
921 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
922 lights: null
923 });
924 }
925
926 #portraitPixelsToCanvas (frameW, frameH, size)
927 {
928 const pixels = this._portrait?.pixels;
929 if (!pixels)
930 { return null; }
931 const scratch = this._portrait.scratch;
932 scratch.width = frameW;
933 scratch.height = frameH;
934 const sctx = scratch.getContext("2d");
935 const imageData = sctx.createImageData(frameW, frameH);
936 // WebGL y=0 is bottom — flip to top-down image order.
937 for (let y = 0; y < frameH; y++)
938 {
939 const src = (frameH - 1 - y) * frameW * 4;
940 const dst = y * frameW * 4;
941 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
942 }
943 sctx.putImageData(imageData, 0, 0);
944
945 const crop = Math.min(frameW, frameH);
946 const out = document.createElement("canvas");
947 out.width = size;
948 out.height = size;
949 const octx = out.getContext("2d");
950 octx.imageSmoothingEnabled = false;
951 octx.clearRect(0, 0, size, size);
952 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
953 return out;
954 }
955
628 956 upsertGroundItem (payload)
629 957 {
630 958 const size = this.tileSize();
@@ -1468,6 +1796,7 @@ export class WorldView
1468 1796 ? !!payload.canFight
1469 1797 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1470 1798 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1799 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
1471 1800 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1472 1801 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1473 1802 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
@@ -1715,12 +2044,34 @@ export class WorldView
1715 2044 return entity?.object?.renderer?.sprite?.g_image ?? null;
1716 2045 }
1717 2046
2047 #tightFitMaskUniforms (overlay, entity)
2048 {
2049 const bodyRenderer = entity?.object?.renderer;
2050 const clothRenderer = overlay?.renderer;
2051 const bodySprite = bodyRenderer?.sprite;
2052 const clothSprite = clothRenderer?.sprite;
2053 if (!bodySprite || !clothSprite)
2054 { return null; }
2055 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2056 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2057 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2058 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2059 return {
2060 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2061 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2062 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2063 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2064 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2065 };
2066 }
2067
1718 2068 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
1719 2069 {
1720 2070 if (!overlay?.renderer || entity?.object?.renderer == null)
1721 2071 { return; }
1722 2072 const bodyMap = this.#bodySecondaryMap(entity);
1723 if (!bodyMap)
2073 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2074 if (!bodyMap || !maskUniforms)
1724 2075 {
1725 2076 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
1726 2077 return;
@@ -1740,7 +2091,8 @@ export class WorldView
1740 2091 u_wade: wade ? 1 : 0,
1741 2092 u_spriteHeight: height,
1742 2093 u_useTint: 1,
1743 u_tintColor: [tint.r, tint.g, tint.b]
2094 u_tintColor: [tint.r, tint.g, tint.b],
2095 ...maskUniforms
1744 2096 };
1745 2097 }
1746 2098 else
@@ -1750,7 +2102,8 @@ export class WorldView
1750 2102 u_darkness: dark,
1751 2103 u_strength: flash,
1752 2104 u_wade: wade ? 1 : 0,
1753 u_spriteHeight: height
2105 u_spriteHeight: height,
2106 ...maskUniforms
1754 2107 };
1755 2108 }
1756 2109 }
@@ -1884,7 +2237,10 @@ export class WorldView
1884 2237 #ambientDarkness ()
1885 2238 {
1886 2239 const hour = this.nightPreview ?? this.worldHour;
1887 let dark = nightFactor(hour, this.settings.nightDarkness);
2240 const calendar = nightFactor(hour, this.settings.nightDarkness);
2241 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2242 if (dark == null)
2243 { dark = calendar; }
1888 2244 if (this.localBlind)
1889 2245 { dark = Math.min(1, dark + 0.85); }
1890 2246 return dark;
@@ -13,6 +13,14 @@ import {
13} from "./canvasSprite.js";
13} from "./canvasSprite.js";
14import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
14import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
15import { SeasonId, seasonIdAt } from "/shared/world/season.js";
15import { SeasonId, seasonIdAt } from "/shared/world/season.js";
16import {
17 OVERWORLD_ID,
18 normalizeDimensionId,
19 normalizeLightingMode,
20 normalizeSeasonMode,
21 resolveDimensionDarknessFactor,
22 resolveDimensionSeasonId
23} from "/shared/world/dimensions.js";
16import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
24import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
17
25
18const LAYER_GROUND = 0;
26const LAYER_GROUND = 0;
@@ -179,6 +187,39 @@ const DUAL_TINT_LIT_SPRITE_FRAG = [
179].join("\n");
187].join("\n");
180
188
181/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
189/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
190/**
191 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
192 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
193 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
194 */
195const TIGHT_FIT_BODY_MASK_GLSL = [
196 "uniform vec2 u_clothSize;",
197 "uniform vec2 u_bodySize;",
198 "uniform float u_pivotFromBottom;",
199 "uniform vec4 u_clothUvRect;",
200 "uniform vec4 u_bodyUvRect;",
201 "float tightFitBodyAlpha() {",
202 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
203 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
204 " float ox = (nu.x - 0.5) * u_clothSize.x;",
205 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
206 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
207 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
208 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
209 " vec2 texel = 1.0 / bodySize;",
210 " float bodyA = 0.0;",
211 " for (int dy = -1; dy <= 1; dy++) {",
212 " for (int dx = -1; dx <= 1; dx++) {",
213 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
214 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
215 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
216 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
217 " }",
218 " }",
219 " return bodyA;",
220 "}"
221].join("\n");
222
182const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
223const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
183 "precision mediump float;",
224 "precision mediump float;",
184 "varying vec2 v_texCoord;",
225 "varying vec2 v_texCoord;",
@@ -190,6 +231,7 @@ const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
190 "uniform float u_spriteHeight;",
231 "uniform float u_spriteHeight;",
191 "uniform float u_useTint;",
232 "uniform float u_useTint;",
192 "uniform vec3 u_tintColor;",
233 "uniform vec3 u_tintColor;",
234 TIGHT_FIT_BODY_MASK_GLSL,
193 "void main() {",
235 "void main() {",
194 " vec4 color = texture2D(u_texture, v_texCoord);",
236 " vec4 color = texture2D(u_texture, v_texCoord);",
195 " if (color.a <= 0.0) { discard; }",
237 " if (color.a <= 0.0) { discard; }",
@@ -209,8 +251,7 @@ const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
209 " }",
251 " }",
210 " rgb = mix(rgb, vec3(0.0), u_darkness);",
252 " rgb = mix(rgb, vec3(0.0), u_darkness);",
211 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
253 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
212 " vec4 bodyPx = texture2D(u_secondary, v_texCoord);",
254 " float alpha = min(tightFitBodyAlpha(), color.a);",
213 " float alpha = min(bodyPx.a, color.a);",
214 " if (alpha <= 0.0) { discard; }",
255 " if (alpha <= 0.0) { discard; }",
215 " gl_FragColor = vec4(rgb, alpha);",
256 " gl_FragColor = vec4(rgb, alpha);",
216 "}"
257 "}"
@@ -226,6 +267,7 @@ const TIGHT_FIT_LIT_SPRITE_FRAG = [
226 "uniform float u_strength;",
267 "uniform float u_strength;",
227 "uniform float u_wade;",
268 "uniform float u_wade;",
228 "uniform float u_spriteHeight;",
269 "uniform float u_spriteHeight;",
270 TIGHT_FIT_BODY_MASK_GLSL,
229 "void main() {",
271 "void main() {",
230 " vec4 color = texture2D(u_texture, v_texCoord);",
272 " vec4 color = texture2D(u_texture, v_texCoord);",
231 " if (color.a <= 0.0) { discard; }",
273 " if (color.a <= 0.0) { discard; }",
@@ -237,8 +279,7 @@ const TIGHT_FIT_LIT_SPRITE_FRAG = [
237 " }",
279 " }",
238 " rgb = mix(rgb, vec3(0.0), u_darkness);",
280 " rgb = mix(rgb, vec3(0.0), u_darkness);",
239 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
281 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
240 " vec4 bodyPx = texture2D(u_secondary, v_texCoord);",
282 " float alpha = min(tightFitBodyAlpha(), color.a);",
241 " float alpha = min(bodyPx.a, color.a);",
242 " if (alpha <= 0.0) { discard; }",
283 " if (alpha <= 0.0) { discard; }",
243 " gl_FragColor = vec4(rgb, alpha);",
284 " gl_FragColor = vec4(rgb, alpha);",
244 "}"
285 "}"
@@ -339,6 +380,14 @@ export class WorldView
339 this.edges = new Map();
380 this.edges = new Map();
340 this.localEntityId = null;
381 this.localEntityId = null;
341 this.localBlind = false;
382 this.localBlind = false;
383 /** @type {string} */
384 this.dimensionId = OVERWORLD_ID;
385 /** @type {string} */
386 this.dimensionLightingMode = "dayNight";
387 /** @type {string} */
388 this.dimensionSeasonMode = "auto";
389 /** Calendar season from worldStatus when dimension season is auto. */
390 this.calendarSeason = seasonIdAt();
342 /** @type {"soft"|"simple"} */
391 /** @type {"soft"|"simple"} */
343 this.lightingMode = "soft";
392 this.lightingMode = "soft";
344 /** @type {boolean} */
393 /** @type {boolean} */
@@ -394,35 +443,58 @@ export class WorldView
394 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
443 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
395 setWorldSeason (season)
444 setWorldSeason (season)
396 {
445 {
397 const next = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
446 const calendar = season === SeasonId.fall || season === SeasonId.winter || season === SeasonId.summer
398 ? season
447 ? season
399 : seasonIdAt();
448 : seasonIdAt();
449 this.calendarSeason = calendar;
450 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
451 const next = forced ?? calendar;
400 if (next === this.worldSeason)
452 if (next === this.worldSeason)
401 { return; }
453 { return; }
402 this.worldSeason = next;
454 this.worldSeason = next;
403 this.#rebakeAllChunks();
455 this.#rebakeAllChunks();
404 }
456 }
405
457
406 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
458 setDimensionId (dimensionId)
407 {
459 {
408 this.localEntityId = entityId;
460 this.dimensionId = normalizeDimensionId(dimensionId);
409 this.#upsertEntity({
461 }
410 entityId,
462
411 characterId,
463 setDimensionModes (lightingMode, seasonMode)
412 tileX,
464 {
413 tileY,
465 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
414 gait,
466 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
415 sex,
467 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
416 firstName,
468 const next = forced ?? this.calendarSeason ?? seasonIdAt();
417 lastName,
469 if (next !== this.worldSeason)
418 layers: layers ?? undefined,
470 {
419 ...(health != null ? { health } : {}),
471 this.worldSeason = next;
420 ...(maxHealth != null ? { maxHealth } : {})
472 this.#rebakeAllChunks();
421 });
473 }
474 }
475
476 clearAllChunks ()
477 {
478 for (const key of [...this.chunks.keys()])
479 {
480 const [chunkX, chunkY] = key.split(",").map(Number);
481 this.removeChunk(chunkX, chunkY);
482 }
483 for (const [id] of [...this.entities.entries()])
484 {
485 if (id === this.localEntityId)
486 { continue; }
487 this.despawnEntity(id);
488 }
489 for (const [id] of [...this.groundItems.entries()])
490 { this.despawnGroundItem(id); }
422 }
491 }
423
492
424 applySnapshot (snapshot)
493 applySnapshot (snapshot)
425 {
494 {
495 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
496 if (normalizeDimensionId(this.dimensionId) !== snapDim)
497 { return; }
426 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
498 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
427 this.chunks.set(key, snapshot);
499 this.chunks.set(key, snapshot);
428 this.#rebuildChunk(snapshot);
500 this.#rebuildChunk(snapshot);
@@ -436,7 +508,6 @@ export class WorldView
436 }
508 }
437 for (const entity of snapshot.entities ?? [])
509 for (const entity of snapshot.entities ?? [])
438 { this.#upsertEntity(entity); }
510 { this.#upsertEntity(entity); }
439 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
440 for (const [id, item] of [...this.groundItems.entries()])
511 for (const [id, item] of [...this.groundItems.entries()])
441 {
512 {
442 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
513 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
@@ -447,6 +518,24 @@ export class WorldView
447 this.#rebuildAllEdges();
518 this.#rebuildAllEdges();
448 }
519 }
449
520
521 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
522 {
523 this.localEntityId = entityId;
524 this.#upsertEntity({
525 entityId,
526 characterId,
527 tileX,
528 tileY,
529 gait,
530 sex,
531 firstName,
532 lastName,
533 layers: layers ?? undefined,
534 ...(health != null ? { health } : {}),
535 ...(maxHealth != null ? { maxHealth } : {})
536 });
537 }
538
450 #stripChunkDynamic (chunkX, chunkY)
539 #stripChunkDynamic (chunkX, chunkY)
451 {
540 {
452 for (const [id, item] of [...this.groundItems.entries()])
541 for (const [id, item] of [...this.groundItems.entries()])
@@ -625,6 +714,245 @@ export class WorldView
625 this.#placeEntity(existing);
714 this.#placeEntity(existing);
626 }
715 }
627
716
717 /**
718 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
719 * world, unlit) into an offscreen FBO, crop the top square, and return a
720 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
721 * @param {number} entityId
722 * @param {{ size?: number }} [options]
723 * @returns {HTMLCanvasElement | null}
724 */
725 captureEntityPortrait (entityId, { size = 64 } = {})
726 {
727 const entity = this.entities.get(entityId);
728 const body = entity?.object?.renderer?.sprite;
729 const glCtx = this.scene?.glContext;
730 const gl = glCtx?.gl;
731 if (!entity || !body || !gl)
732 { return null; }
733
734 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
735 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
736 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
737 { return null; }
738
739 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
740 const prevViewport = gl.getParameter(gl.VIEWPORT);
741 const prevW = glCtx._lastWidth;
742 const prevH = glCtx._lastHeight;
743 const prevBlend = gl.isEnabled(gl.BLEND);
744
745 try
746 {
747 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
748 glCtx._lastWidth = frameW;
749 glCtx._lastHeight = frameH;
750 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
751 gl.viewport(0, 0, frameW, frameH);
752 gl.enable(gl.BLEND);
753 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
754 gl.clearColor(0, 0, 0, 0);
755 gl.clear(gl.COLOR_BUFFER_BIT);
756
757 const pivotX = frameW * 0.5;
758 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
759 this._portraitBodyMap = body.g_image ?? null;
760 this._portraitTightFitEntity = entity;
761 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
762
763 const overlays = entity.overlays ?? [];
764 const tints = entity.overlayTints ?? [];
765 const tight = entity.overlayTightFit ?? [];
766 for (let index = 0; index < overlays.length; index++)
767 {
768 this.#drawPortraitLayer(
769 glCtx,
770 overlays[index],
771 pivotX,
772 pivotY,
773 tints[index] ?? null,
774 !!tight[index]
775 );
776 }
777 this._portraitBodyMap = null;
778 this._portraitTightFitEntity = null;
779
780 const pixels = this._portrait.pixels;
781 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
782 }
783 finally
784 {
785 glCtx._lastWidth = prevW;
786 glCtx._lastHeight = prevH;
787 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
788 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
789 if (!prevBlend)
790 { gl.disable(gl.BLEND); }
791 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
792 }
793
794 return this.#portraitPixelsToCanvas(frameW, frameH, size);
795 }
796
797 #ensurePortraitTarget (gl, width, height)
798 {
799 const prev = this._portrait;
800 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
801 { return true; }
802 if (prev?.fb)
803 { gl.deleteFramebuffer(prev.fb); }
804 if (prev?.tex)
805 { gl.deleteTexture(prev.tex); }
806
807 const tex = gl.createTexture();
808 gl.bindTexture(gl.TEXTURE_2D, tex);
809 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
810 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
811 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
812 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
813 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
814
815 const fb = gl.createFramebuffer();
816 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
817 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
818 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
819 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
820 if (status !== gl.FRAMEBUFFER_COMPLETE)
821 {
822 gl.deleteFramebuffer(fb);
823 gl.deleteTexture(tex);
824 this._portrait = null;
825 return false;
826 }
827 this._portrait = {
828 fb,
829 tex,
830 w: width,
831 h: height,
832 pixels: new Uint8Array(width * height * 4),
833 scratch: document.createElement("canvas")
834 };
835 return true;
836 }
837
838 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit)
839 {
840 const sprite = object?.renderer?.sprite;
841 if (!sprite?.g_image)
842 { return; }
843 const subImage = object.renderer.subImage | 0;
844 const height = sprite.height || SPRITE_SIZE_PX;
845 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
846 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
847 const tint = tintColor ? normalizeRgb(tintColor) : null;
848 let shader = glCtx.defaultShader;
849 let uniforms = null;
850 let secondaryHtml = null;
851
852 const bodyHtml = this._portraitBodyMap;
853 const portraitEntity = this._portraitTightFitEntity;
854 const maskUniforms = tightFit && portraitEntity
855 ? this.#tightFitMaskUniforms(object, portraitEntity)
856 : null;
857 if (tightFit && bodyHtml && maskUniforms)
858 {
859 secondaryHtml = bodyHtml;
860 if (tint)
861 {
862 shader = getTightFitTintLitSpriteShader();
863 uniforms = {
864 u_darkness: 0,
865 u_strength: 0,
866 u_wade: 0,
867 u_spriteHeight: height,
868 u_useTint: 1,
869 u_tintColor: [tint.r, tint.g, tint.b],
870 ...maskUniforms
871 };
872 }
873 else
874 {
875 shader = getTightFitLitSpriteShader();
876 uniforms = {
877 u_darkness: 0,
878 u_strength: 0,
879 u_wade: 0,
880 u_spriteHeight: height,
881 ...maskUniforms
882 };
883 }
884 }
885 else if (tint)
886 {
887 shader = getTintLitSpriteShader();
888 uniforms = {
889 u_darkness: 0,
890 u_strength: 0,
891 u_wade: 0,
892 u_spriteHeight: height,
893 u_useTint: 1,
894 u_tintColor: [tint.r, tint.g, tint.b]
895 };
896 }
897 else
898 {
899 shader = getSpriteLightingShader();
900 uniforms = {
901 u_darkness: 0,
902 u_strength: 0,
903 u_wade: 0,
904 u_spriteHeight: height
905 };
906 }
907
908 glCtx.drawSprite({
909 texture: glCtx.getTexture(sprite.g_image),
910 x: center.x,
911 y: center.y,
912 w: draw.w,
913 h: draw.h,
914 rotationDeg: 0,
915 mirrorX: false,
916 mirrorY: false,
917 alpha: 1,
918 uvRect: sprite.getUvRect(subImage),
919 shader,
920 uniforms,
921 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
922 lights: null
923 });
924 }
925
926 #portraitPixelsToCanvas (frameW, frameH, size)
927 {
928 const pixels = this._portrait?.pixels;
929 if (!pixels)
930 { return null; }
931 const scratch = this._portrait.scratch;
932 scratch.width = frameW;
933 scratch.height = frameH;
934 const sctx = scratch.getContext("2d");
935 const imageData = sctx.createImageData(frameW, frameH);
936 // WebGL y=0 is bottom — flip to top-down image order.
937 for (let y = 0; y < frameH; y++)
938 {
939 const src = (frameH - 1 - y) * frameW * 4;
940 const dst = y * frameW * 4;
941 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
942 }
943 sctx.putImageData(imageData, 0, 0);
944
945 const crop = Math.min(frameW, frameH);
946 const out = document.createElement("canvas");
947 out.width = size;
948 out.height = size;
949 const octx = out.getContext("2d");
950 octx.imageSmoothingEnabled = false;
951 octx.clearRect(0, 0, size, size);
952 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
953 return out;
954 }
955
628 upsertGroundItem (payload)
956 upsertGroundItem (payload)
629 {
957 {
630 const size = this.tileSize();
958 const size = this.tileSize();
@@ -1468,6 +1796,7 @@ export class WorldView
1468 ? !!payload.canFight
1796 ? !!payload.canFight
1469 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1797 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1470 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1798 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1799 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
1471 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1800 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1472 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1801 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1473 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1802 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
@@ -1715,12 +2044,34 @@ export class WorldView
1715 return entity?.object?.renderer?.sprite?.g_image ?? null;
2044 return entity?.object?.renderer?.sprite?.g_image ?? null;
1716 }
2045 }
1717
2046
2047 #tightFitMaskUniforms (overlay, entity)
2048 {
2049 const bodyRenderer = entity?.object?.renderer;
2050 const clothRenderer = overlay?.renderer;
2051 const bodySprite = bodyRenderer?.sprite;
2052 const clothSprite = clothRenderer?.sprite;
2053 if (!bodySprite || !clothSprite)
2054 { return null; }
2055 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2056 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2057 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2058 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2059 return {
2060 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2061 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2062 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2063 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2064 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2065 };
2066 }
2067
1718 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
2068 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
1719 {
2069 {
1720 if (!overlay?.renderer || entity?.object?.renderer == null)
2070 if (!overlay?.renderer || entity?.object?.renderer == null)
1721 { return; }
2071 { return; }
1722 const bodyMap = this.#bodySecondaryMap(entity);
2072 const bodyMap = this.#bodySecondaryMap(entity);
1723 if (!bodyMap)
2073 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2074 if (!bodyMap || !maskUniforms)
1724 {
2075 {
1725 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
2076 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
1726 return;
2077 return;
@@ -1740,7 +2091,8 @@ export class WorldView
1740 u_wade: wade ? 1 : 0,
2091 u_wade: wade ? 1 : 0,
1741 u_spriteHeight: height,
2092 u_spriteHeight: height,
1742 u_useTint: 1,
2093 u_useTint: 1,
1743 u_tintColor: [tint.r, tint.g, tint.b]
2094 u_tintColor: [tint.r, tint.g, tint.b],
2095 ...maskUniforms
1744 };
2096 };
1745 }
2097 }
1746 else
2098 else
@@ -1750,7 +2102,8 @@ export class WorldView
1750 u_darkness: dark,
2102 u_darkness: dark,
1751 u_strength: flash,
2103 u_strength: flash,
1752 u_wade: wade ? 1 : 0,
2104 u_wade: wade ? 1 : 0,
1753 u_spriteHeight: height
2105 u_spriteHeight: height,
2106 ...maskUniforms
1754 };
2107 };
1755 }
2108 }
1756 }
2109 }
@@ -1884,7 +2237,10 @@ export class WorldView
1884 #ambientDarkness ()
2237 #ambientDarkness ()
1885 {
2238 {
1886 const hour = this.nightPreview ?? this.worldHour;
2239 const hour = this.nightPreview ?? this.worldHour;
1887 let dark = nightFactor(hour, this.settings.nightDarkness);
2240 const calendar = nightFactor(hour, this.settings.nightDarkness);
2241 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2242 if (dark == null)
2243 { dark = calendar; }
1888 if (this.localBlind)
2244 if (this.localBlind)
1889 { dark = Math.min(1, dark + 0.85); }
2245 { dark = Math.min(1, dark + 0.85); }
1890 return dark;
2246 return dark;
client/ui/editor.css +244 −0
@@ -48,6 +48,94 @@ body > aside {
48 48 margin: 0.75rem 0;
49 49 }
50 50
51 .dimension-picker {
52 margin: 0.75rem 0 0.35rem;
53 display: flex;
54 flex-direction: column;
55 gap: 0.35rem;
56 }
57 .dimension-picker > label,
58 .dimension-picker-label {
59 font-size: 0.85rem;
60 color: #9aa3b2;
61 }
62 .dim-combo {
63 position: relative;
64 }
65 .dim-combo-input {
66 width: 100%;
67 box-sizing: border-box;
68 }
69 .dim-combo-list {
70 position: absolute;
71 left: 0;
72 right: 0;
73 top: calc(100% + 2px);
74 z-index: 20;
75 margin: 0;
76 padding: 0.2rem 0;
77 list-style: none;
78 max-height: 220px;
79 overflow: auto;
80 background: #101216;
81 border: 1px solid #3a4250;
82 box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
83 }
84 .dim-combo-option,
85 .dim-combo-empty {
86 display: flex;
87 flex-direction: column;
88 gap: 0.1rem;
89 padding: 0.35rem 0.55rem;
90 cursor: pointer;
91 }
92 .dim-combo-option:hover,
93 .dim-combo-option.selected {
94 background: #243044;
95 }
96 .dim-combo-option.disabled {
97 opacity: 0.55;
98 }
99 .dim-combo-option.create {
100 color: #b8d4a0;
101 border-top: 1px solid #2c3340;
102 }
103 .dim-combo-option-hint,
104 .dim-combo-empty {
105 font-size: 0.78rem;
106 color: #9aa3b2;
107 }
108 .dimension-settings {
109 display: flex;
110 flex-direction: column;
111 gap: 0.45rem;
112 margin: 0.5rem 0 0.85rem;
113 padding: 0.55rem 0.6rem;
114 border: 1px solid #2c3340;
115 background: #151922;
116 }
117 .dimension-settings label {
118 display: flex;
119 flex-direction: column;
120 gap: 0.2rem;
121 font-size: 0.85rem;
122 color: #9aa3b2;
123 }
124 .dimension-settings input,
125 .dimension-settings select {
126 width: 100%;
127 box-sizing: border-box;
128 }
129 .dimension-settings-actions {
130 display: flex;
131 flex-wrap: wrap;
132 gap: 0.35rem;
133 }
134 #dim-delete {
135 border-color: #8a3a3a;
136 color: #f0a0a0;
137 }
138
51 139 button, input {
52 140 font: inherit;
53 141 background: #101216;
@@ -755,3 +843,159 @@ label { display: block; margin: 0.4rem 0; }
755 843 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
756 844 }
757 845
846 #hover-status {
847 position: fixed;
848 left: 250px;
849 right: 280px;
850 bottom: 0;
851 z-index: 5;
852 margin: 0;
853 padding: 0.35rem 0.75rem;
854 border-top: 1px solid #2c3340;
855 background: #1a1e26;
856 color: #c5c9d2;
857 font-size: 0.85rem;
858 pointer-events: none;
859 }
860 #hover-status-text {
861 font-variant-numeric: tabular-nums;
862 }
863
864
865 #quests-backdrop,
866 #dialogues-backdrop {
867 position: fixed;
868 inset: 0;
869 background: rgba(0, 0, 0, 0.62);
870 z-index: 19;
871 }
872
873 #quests-modal,
874 #dialogues-modal {
875 position: fixed;
876 inset: 5vh 5vw;
877 z-index: 20;
878 display: flex;
879 flex-direction: column;
880 background: #161a22;
881 border: 1px solid #3a4250;
882 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
883 }
884
885 #quests-modal[hidden],
886 #quests-backdrop[hidden],
887 #dialogues-modal[hidden],
888 #dialogues-backdrop[hidden] {
889 display: none !important;
890 }
891
892 #quests-modal > header,
893 #dialogues-modal > header,
894 #quests-modal > footer,
895 #dialogues-modal > footer {
896 display: flex;
897 align-items: center;
898 justify-content: space-between;
899 gap: 0.75rem;
900 padding: 0.75rem 1rem;
901 border-bottom: 1px solid #2c3340;
902 }
903
904 #quests-modal > footer,
905 #dialogues-modal > footer {
906 border-bottom: 0;
907 border-top: 1px solid #2c3340;
908 justify-content: flex-end;
909 }
910
911 .content-editor-layout {
912 flex: 1;
913 min-height: 0;
914 display: flex;
915 overflow: hidden;
916 }
917
918 .content-editor-list-pane {
919 width: 220px;
920 flex-shrink: 0;
921 border-right: 1px solid #2c3340;
922 padding: 0.65rem;
923 display: flex;
924 flex-direction: column;
925 gap: 0.5rem;
926 overflow: auto;
927 background: #12151c;
928 }
929
930 .content-editor-list {
931 display: flex;
932 flex-direction: column;
933 gap: 0.25rem;
934 }
935
936 .content-editor-list button {
937 text-align: left;
938 width: 100%;
939 }
940
941 .content-editor-list button.active {
942 border-color: #6b8cae;
943 background: #1c2838;
944 }
945
946 .content-editor-detail {
947 flex: 1;
948 min-width: 0;
949 overflow: auto;
950 padding: 0.75rem 1rem 1rem;
951 }
952
953 .content-editor-detail label {
954 display: block;
955 margin: 0.4rem 0;
956 }
957
958 .content-editor-detail input[type="text"],
959 .content-editor-detail input[type="number"],
960 .content-editor-detail textarea,
961 .content-editor-detail select {
962 display: block;
963 width: 100%;
964 margin-top: 0.2rem;
965 box-sizing: border-box;
966 }
967
968 .content-editor-section {
969 border: 1px solid #2c3340;
970 padding: 0.55rem 0.65rem;
971 margin: 0.55rem 0;
972 background: #12151c;
973 }
974
975 .content-editor-section-header {
976 display: flex;
977 align-items: center;
978 justify-content: space-between;
979 gap: 0.5rem;
980 margin-bottom: 0.35rem;
981 }
982
983 .content-editor-row {
984 display: flex;
985 flex-wrap: wrap;
986 gap: 0.35rem;
987 align-items: center;
988 margin: 0.35rem 0;
989 }
990
991 .content-editor-clause {
992 border: 1px dashed #3a4250;
993 padding: 0.4rem;
994 margin: 0.35rem 0;
995 }
996
997 .content-editor-hint {
998 color: #8a909c;
999 font-size: 0.85rem;
1000 margin: 0.25rem 0 0.5rem;
1001 }
@@ -48,6 +48,94 @@ body > aside {
48 margin: 0.75rem 0;
48 margin: 0.75rem 0;
49}
49}
50
50
51.dimension-picker {
52 margin: 0.75rem 0 0.35rem;
53 display: flex;
54 flex-direction: column;
55 gap: 0.35rem;
56}
57.dimension-picker > label,
58.dimension-picker-label {
59 font-size: 0.85rem;
60 color: #9aa3b2;
61}
62.dim-combo {
63 position: relative;
64}
65.dim-combo-input {
66 width: 100%;
67 box-sizing: border-box;
68}
69.dim-combo-list {
70 position: absolute;
71 left: 0;
72 right: 0;
73 top: calc(100% + 2px);
74 z-index: 20;
75 margin: 0;
76 padding: 0.2rem 0;
77 list-style: none;
78 max-height: 220px;
79 overflow: auto;
80 background: #101216;
81 border: 1px solid #3a4250;
82 box-shadow: 0 8px 24px rgba(0, 0, 0, 0.45);
83}
84.dim-combo-option,
85.dim-combo-empty {
86 display: flex;
87 flex-direction: column;
88 gap: 0.1rem;
89 padding: 0.35rem 0.55rem;
90 cursor: pointer;
91}
92.dim-combo-option:hover,
93.dim-combo-option.selected {
94 background: #243044;
95}
96.dim-combo-option.disabled {
97 opacity: 0.55;
98}
99.dim-combo-option.create {
100 color: #b8d4a0;
101 border-top: 1px solid #2c3340;
102}
103.dim-combo-option-hint,
104.dim-combo-empty {
105 font-size: 0.78rem;
106 color: #9aa3b2;
107}
108.dimension-settings {
109 display: flex;
110 flex-direction: column;
111 gap: 0.45rem;
112 margin: 0.5rem 0 0.85rem;
113 padding: 0.55rem 0.6rem;
114 border: 1px solid #2c3340;
115 background: #151922;
116}
117.dimension-settings label {
118 display: flex;
119 flex-direction: column;
120 gap: 0.2rem;
121 font-size: 0.85rem;
122 color: #9aa3b2;
123}
124.dimension-settings input,
125.dimension-settings select {
126 width: 100%;
127 box-sizing: border-box;
128}
129.dimension-settings-actions {
130 display: flex;
131 flex-wrap: wrap;
132 gap: 0.35rem;
133}
134#dim-delete {
135 border-color: #8a3a3a;
136 color: #f0a0a0;
137}
138
51button, input {
139button, input {
52 font: inherit;
140 font: inherit;
53 background: #101216;
141 background: #101216;
@@ -755,3 +843,159 @@ label { display: block; margin: 0.4rem 0; }
755 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
843 box-shadow: 0 6px 18px rgba(0, 0, 0, 0.4);
756}
844}
757
845
846#hover-status {
847 position: fixed;
848 left: 250px;
849 right: 280px;
850 bottom: 0;
851 z-index: 5;
852 margin: 0;
853 padding: 0.35rem 0.75rem;
854 border-top: 1px solid #2c3340;
855 background: #1a1e26;
856 color: #c5c9d2;
857 font-size: 0.85rem;
858 pointer-events: none;
859}
860#hover-status-text {
861 font-variant-numeric: tabular-nums;
862}
863
864
865#quests-backdrop,
866#dialogues-backdrop {
867 position: fixed;
868 inset: 0;
869 background: rgba(0, 0, 0, 0.62);
870 z-index: 19;
871}
872
873#quests-modal,
874#dialogues-modal {
875 position: fixed;
876 inset: 5vh 5vw;
877 z-index: 20;
878 display: flex;
879 flex-direction: column;
880 background: #161a22;
881 border: 1px solid #3a4250;
882 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
883}
884
885#quests-modal[hidden],
886#quests-backdrop[hidden],
887#dialogues-modal[hidden],
888#dialogues-backdrop[hidden] {
889 display: none !important;
890}
891
892#quests-modal > header,
893#dialogues-modal > header,
894#quests-modal > footer,
895#dialogues-modal > footer {
896 display: flex;
897 align-items: center;
898 justify-content: space-between;
899 gap: 0.75rem;
900 padding: 0.75rem 1rem;
901 border-bottom: 1px solid #2c3340;
902}
903
904#quests-modal > footer,
905#dialogues-modal > footer {
906 border-bottom: 0;
907 border-top: 1px solid #2c3340;
908 justify-content: flex-end;
909}
910
911.content-editor-layout {
912 flex: 1;
913 min-height: 0;
914 display: flex;
915 overflow: hidden;
916}
917
918.content-editor-list-pane {
919 width: 220px;
920 flex-shrink: 0;
921 border-right: 1px solid #2c3340;
922 padding: 0.65rem;
923 display: flex;
924 flex-direction: column;
925 gap: 0.5rem;
926 overflow: auto;
927 background: #12151c;
928}
929
930.content-editor-list {
931 display: flex;
932 flex-direction: column;
933 gap: 0.25rem;
934}
935
936.content-editor-list button {
937 text-align: left;
938 width: 100%;
939}
940
941.content-editor-list button.active {
942 border-color: #6b8cae;
943 background: #1c2838;
944}
945
946.content-editor-detail {
947 flex: 1;
948 min-width: 0;
949 overflow: auto;
950 padding: 0.75rem 1rem 1rem;
951}
952
953.content-editor-detail label {
954 display: block;
955 margin: 0.4rem 0;
956}
957
958.content-editor-detail input[type="text"],
959.content-editor-detail input[type="number"],
960.content-editor-detail textarea,
961.content-editor-detail select {
962 display: block;
963 width: 100%;
964 margin-top: 0.2rem;
965 box-sizing: border-box;
966}
967
968.content-editor-section {
969 border: 1px solid #2c3340;
970 padding: 0.55rem 0.65rem;
971 margin: 0.55rem 0;
972 background: #12151c;
973}
974
975.content-editor-section-header {
976 display: flex;
977 align-items: center;
978 justify-content: space-between;
979 gap: 0.5rem;
980 margin-bottom: 0.35rem;
981}
982
983.content-editor-row {
984 display: flex;
985 flex-wrap: wrap;
986 gap: 0.35rem;
987 align-items: center;
988 margin: 0.35rem 0;
989}
990
991.content-editor-clause {
992 border: 1px dashed #3a4250;
993 padding: 0.4rem;
994 margin: 0.35rem 0;
995}
996
997.content-editor-hint {
998 color: #8a909c;
999 font-size: 0.85rem;
1000 margin: 0.25rem 0 0.5rem;
1001}
client/ui/play.css +156 −0
@@ -1963,3 +1963,159 @@ a { color: #d4c48a; }
1963 1963 font-weight: 700;
1964 1964 margin: 0.5rem 0 0;
1965 1965 }
1966
1967 .toast.toast-clickable:hover {
1968 border-color: #7a889c;
1969 background: rgba(22, 26, 34, 0.96);
1970 }
1971
1972 #quests-list-panel,
1973 #quests-detail-panel {
1974 position: fixed;
1975 z-index: 6;
1976 top: 50%;
1977 left: 50%;
1978 transform: translate(-50%, -50%);
1979 width: min(520px, 94vw);
1980 max-height: min(80vh, 640px);
1981 overflow: auto;
1982 background: #1a1e26;
1983 border: 1px solid #2c3340;
1984 padding: 0.85rem 1rem 1rem;
1985 }
1986
1987 #quests-detail-panel {
1988 width: min(720px, 96vw);
1989 }
1990
1991 #quests-list-panel header,
1992 #quests-detail-panel header {
1993 display: flex;
1994 justify-content: space-between;
1995 align-items: center;
1996 gap: 0.5rem;
1997 margin-bottom: 0.65rem;
1998 }
1999
2000 .quests-detail-actions {
2001 display: flex;
2002 gap: 0.35rem;
2003 }
2004
2005 #quests-list-body {
2006 display: flex;
2007 flex-direction: column;
2008 gap: 0.35rem;
2009 }
2010
2011 .quests-list-item {
2012 text-align: left;
2013 width: 100%;
2014 }
2015
2016 .quests-detail-layout {
2017 display: grid;
2018 grid-template-columns: 1fr 1fr;
2019 gap: 1rem;
2020 }
2021
2022 .quests-detail-layout section h3 {
2023 margin: 0 0 0.4rem;
2024 font-size: 0.95rem;
2025 }
2026
2027 .quests-journal-entry {
2028 margin: 0 0 0.55rem;
2029 padding-bottom: 0.45rem;
2030 border-bottom: 1px solid #2c3340;
2031 color: #d6d1c4;
2032 }
2033
2034 .quests-objectives {
2035 margin: 0.5rem 0 0;
2036 padding-left: 1.1rem;
2037 }
2038
2039 .quests-objectives li.done {
2040 text-decoration: line-through;
2041 color: #8a909c;
2042 }
2043
2044 #dialogue-panel {
2045 position: fixed;
2046 z-index: 6;
2047 left: 50%;
2048 bottom: 1.25rem;
2049 transform: translateX(-50%);
2050 width: min(520px, 94vw);
2051 max-height: min(45vh, 360px);
2052 overflow: auto;
2053 background: #1a1e26;
2054 border: 1px solid #2c3340;
2055 padding: 0.75rem 1rem 1rem;
2056 }
2057
2058 #dialogue-panel header {
2059 display: flex;
2060 justify-content: space-between;
2061 align-items: center;
2062 margin-bottom: 0.5rem;
2063 }
2064
2065 #dialogue-title {
2066 margin: 0;
2067 font-size: 0.85rem;
2068 font-weight: 600;
2069 color: #a8b0bc;
2070 letter-spacing: 0.02em;
2071 }
2072
2073 .dialogue-line {
2074 display: flex;
2075 align-items: flex-start;
2076 gap: 0.55rem;
2077 margin: 0.35rem 0;
2078 line-height: 1.35;
2079 }
2080
2081 .dialogue-speaker-icon {
2082 width: 64px;
2083 height: 64px;
2084 flex: 0 0 64px;
2085 image-rendering: pixelated;
2086 margin-top: 0;
2087 }
2088
2089 .dialogue-line-text {
2090 flex: 1;
2091 }
2092
2093 .dialogue-line-player {
2094 color: #c9d4e8;
2095 }
2096
2097 .dialogue-triggers {
2098 display: flex;
2099 flex-wrap: wrap;
2100 justify-content: flex-end;
2101 gap: 0.4rem;
2102 margin-top: 0.75rem;
2103 }
2104
2105 .dialogue-next {
2106 margin-left: auto;
2107 }
2108
2109 @media (max-width: 640px) {
2110 .quests-detail-layout {
2111 grid-template-columns: 1fr;
2112 }
2113 }
2114
2115 #quests-list-panel[hidden],
2116 #quests-detail-panel[hidden],
2117 #dialogue-panel[hidden],
2118 #quests-list-backdrop[hidden],
2119 #quests-detail-backdrop[hidden] {
2120 display: none !important;
2121 }
@@ -1963,3 +1963,159 @@ a { color: #d4c48a; }
1963 font-weight: 700;
1963 font-weight: 700;
1964 margin: 0.5rem 0 0;
1964 margin: 0.5rem 0 0;
1965}
1965}
1966
1967.toast.toast-clickable:hover {
1968 border-color: #7a889c;
1969 background: rgba(22, 26, 34, 0.96);
1970}
1971
1972#quests-list-panel,
1973#quests-detail-panel {
1974 position: fixed;
1975 z-index: 6;
1976 top: 50%;
1977 left: 50%;
1978 transform: translate(-50%, -50%);
1979 width: min(520px, 94vw);
1980 max-height: min(80vh, 640px);
1981 overflow: auto;
1982 background: #1a1e26;
1983 border: 1px solid #2c3340;
1984 padding: 0.85rem 1rem 1rem;
1985}
1986
1987#quests-detail-panel {
1988 width: min(720px, 96vw);
1989}
1990
1991#quests-list-panel header,
1992#quests-detail-panel header {
1993 display: flex;
1994 justify-content: space-between;
1995 align-items: center;
1996 gap: 0.5rem;
1997 margin-bottom: 0.65rem;
1998}
1999
2000.quests-detail-actions {
2001 display: flex;
2002 gap: 0.35rem;
2003}
2004
2005#quests-list-body {
2006 display: flex;
2007 flex-direction: column;
2008 gap: 0.35rem;
2009}
2010
2011.quests-list-item {
2012 text-align: left;
2013 width: 100%;
2014}
2015
2016.quests-detail-layout {
2017 display: grid;
2018 grid-template-columns: 1fr 1fr;
2019 gap: 1rem;
2020}
2021
2022.quests-detail-layout section h3 {
2023 margin: 0 0 0.4rem;
2024 font-size: 0.95rem;
2025}
2026
2027.quests-journal-entry {
2028 margin: 0 0 0.55rem;
2029 padding-bottom: 0.45rem;
2030 border-bottom: 1px solid #2c3340;
2031 color: #d6d1c4;
2032}
2033
2034.quests-objectives {
2035 margin: 0.5rem 0 0;
2036 padding-left: 1.1rem;
2037}
2038
2039.quests-objectives li.done {
2040 text-decoration: line-through;
2041 color: #8a909c;
2042}
2043
2044#dialogue-panel {
2045 position: fixed;
2046 z-index: 6;
2047 left: 50%;
2048 bottom: 1.25rem;
2049 transform: translateX(-50%);
2050 width: min(520px, 94vw);
2051 max-height: min(45vh, 360px);
2052 overflow: auto;
2053 background: #1a1e26;
2054 border: 1px solid #2c3340;
2055 padding: 0.75rem 1rem 1rem;
2056}
2057
2058#dialogue-panel header {
2059 display: flex;
2060 justify-content: space-between;
2061 align-items: center;
2062 margin-bottom: 0.5rem;
2063}
2064
2065#dialogue-title {
2066 margin: 0;
2067 font-size: 0.85rem;
2068 font-weight: 600;
2069 color: #a8b0bc;
2070 letter-spacing: 0.02em;
2071}
2072
2073.dialogue-line {
2074 display: flex;
2075 align-items: flex-start;
2076 gap: 0.55rem;
2077 margin: 0.35rem 0;
2078 line-height: 1.35;
2079}
2080
2081.dialogue-speaker-icon {
2082 width: 64px;
2083 height: 64px;
2084 flex: 0 0 64px;
2085 image-rendering: pixelated;
2086 margin-top: 0;
2087}
2088
2089.dialogue-line-text {
2090 flex: 1;
2091}
2092
2093.dialogue-line-player {
2094 color: #c9d4e8;
2095}
2096
2097.dialogue-triggers {
2098 display: flex;
2099 flex-wrap: wrap;
2100 justify-content: flex-end;
2101 gap: 0.4rem;
2102 margin-top: 0.75rem;
2103}
2104
2105.dialogue-next {
2106 margin-left: auto;
2107}
2108
2109@media (max-width: 640px) {
2110 .quests-detail-layout {
2111 grid-template-columns: 1fr;
2112 }
2113}
2114
2115#quests-list-panel[hidden],
2116#quests-detail-panel[hidden],
2117#dialogue-panel[hidden],
2118#quests-list-backdrop[hidden],
2119#quests-detail-backdrop[hidden] {
2120 display: none !important;
2121}
docs/FEATURES.md +363 −357
@@ -1,357 +1,363 @@
1 # Feature implementation tracker
2
3 Living companion to `tile_mmo_server_technical_design_v0.6.md`.
4 Statuses: **not implemented** · **partial** · **full**.
5
6 Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
7
8 ---
9
10 ## World coordinates and spatial hierarchy
11
12 **Status:** full
13 **Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division.
14 **Code:** `server/src/world/coordinates.js`, tests in `server/tests/coordinates.test.js`
15
16 ## Ground and block tile layers
17
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. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **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. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
21
22 ## Open and closed chunks
23
24 **Status:** full
25 **Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
26 **Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
27
28 ## ECS registry and components
29
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
34 ## Simulation tick
35
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 **Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
39
40 ## Authored world and runtime state persistence
41
42 **Status:** full
43 **Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
44 **Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
45
46 ## World revisions and pending editor saves
47
48 **Status:** partial
49 **Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
50 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
51
52 ## World settings
53
54 **Status:** full
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, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. 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`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `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
58 ## Baked lighting
59
60 **Status:** full
61 **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
62 **Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
63
64 ## World editor (server)
65
66 **Status:** full
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
68 **Code:** `server/src/editor/service.js`
69
70 ## World editor (client)
71
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 zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
75
76 ## Per-chunk changelog
77
78 **Status:** full
79 **Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
80 **Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
81
82 ## WebSocket gateway
83
84 **Status:** full
85 **Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
86 **Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
87
88 ## Stub authentication
89
90 **Status:** full
91 **Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
92 **Code:** `server/src/auth/stub.js`
93
94 ## Characters
95
96 **Status:** full
97 **Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
98 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
99
100 ## Character deletion and inheritance
101
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
106 ## 3×3 chunk replication
107
108 **Status:** full
109 **Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. 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` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
111
112 ## Click-to-move and A\* pathfinding
113
114 **Status:** full
115 **Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
116 **Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
117
118 ## Global walk/run cadence
119
120 **Status:** full
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/workerWorld.js` (`#stepMovement`, `#setGait`)
123
124 ## Client movement interpolation
125
126 **Status:** full
127 **Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
128 **Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
129
130 ## Play viewport and camera
131
132 **Status:** full
133 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
134 **Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
135
136 ## Client graphics settings
137
138 **Status:** full
139 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
140 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
141
142 ## Night shading
143
144 **Status:** full
145 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
146 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
147
148 ## FrameworkV3 client bootstrap
149
150 **Status:** full
151 **Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
152 **Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
153
154 ## Sprite size, pivot and Y-sort
155
156 **Status:** full
157 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
158 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
159
160 ## Visual tile states
161
162 **Status:** full
163 **Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter, calendar season overrides authored state in play; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
164 **Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
165
166 ## Region workers and cross-worker transfer
167
168 **Status:** full
169 **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.
170 **Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
171
172 ## ChunkLoader activation and unload persistence
173
174 **Status:** full
175 **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.
176 **Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
177
178 ## Midnight restart and Git deploy
179
180 **Status:** full
181 **Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
182 **Code:** —
183
184 ## Spawners
185
186 **Status:** full
187 **Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
188 **Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
189
190 ## Mob definitions (content schema)
191
192 **Status:** partial
193 **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
194 **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
195
196 ## Quests
197
198 **Status:** not implemented (design)
199 **Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
200 **Code:** —
201
202 ## Character logout resume
203
204 **Status:** full
205 **Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
206 **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
207
208 ## Combat resolution (rolls)
209
210 **Status:** partial
211 **Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later.
212 **Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`
213
214 ## Combat, skills, groups, pigeons
215
216 **Status:** partial
217 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
218 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
219
220 ## Player death and respawn
221
222 **Status:** full
223 **Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
224
225 1. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
226 2. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
227 3. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
228 4. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
229 5. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
230
231 **TODO:** Revisit player-loot penalties if PK rules are added.
232 **Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
233
234 ## Equipment tiers and worn stat bonuses
235
236 **Status:** partial
237 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
238 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
239 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
240 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
241
242 ## Gathering, crafting, and production skills
243
244 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
245 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
246 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
247
248 ## Cloth, dyes, and tailoring
249
250 **Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
251 **Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
252 **TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
253 **Later design (document only for now):**
254 - **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
255 - **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
256 - **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
257 **Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
258
259 ## Crafting stations
260
261 **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
262 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
263 **TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
264 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
265
266 ## Stamina and running
267
268 **Status:** full
269 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
270 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
271
272 ## Alchemy / cauldron
273
274 **Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
275 **Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
276 **Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
277
278 ### Folklore herb associations (design only — not in code)
279
280 Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
281
282 | Tier | Herb | Associations |
283 | --- | --- | --- |
284 | 1 | Mint | Refreshment, stamina, antidotes |
285 | 1 | Garlic | Undead protection, disease resistance |
286 | 2 | Thyme | Courage, vitality, resistance |
287 | 2 | Sage | Healing, wisdom, longevity |
288 | 2 | Rosemary | Memory, protection, clarity |
289 | 3 | Lavender | Sleep, calm, dreams |
290 | 3 | Chamomile | Restoration, sleep, soothing |
291 | 3 | Nettle | Vigour, resilience, protection |
292 | 4 | Yarrow | Wound healing, battle medicine |
293 | 4 | Juniper | Purification, disease resistance |
294 | 4 | Elder | Spirits, protection, healing |
295 | 4 | Rue | Curse resistance, purification |
296 | 5 | Valerian | Sleep, sedation, tranquillity |
297 | 5 | Mugwort | Dreams, visions, divination |
298 | 5 | Wormwood | Poison resistance, spirits, bitterness |
299 | 5 | St. John's wort | Holy protection, dispel darkness |
300 | 6 | Hawthorn | Fey, barriers, enchantment |
301 | 6 | Foxglove | Fairy magic, heart magic, poison |
302 | 6 | Mistletoe | Life, fertility, druidic magic |
303 | 6 | Datura | Visions, insanity, spirit walking |
304 | 7 | Belladonna | Poison, hallucination, witchcraft |
305 | 7 | Henbane | Trance, madness, sleep, poison |
306 | 7 | Mandrake | Powerful potions, curses, life magic |
307 | 7 | Aconite | Werewolves, lethal poison, curses |
308
309 ## Inventory, items, equipment, ground drops
310
311 **Status:** full
312 **Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) 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. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
313 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
314
315 ## Proximity chat
316
317 **Status:** full
318 **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.
319 **Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
320
321 ## Friends
322
323 **Status:** full
324 **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
325 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
326
327 ## Hair & barber
328
329 **Status:** full
330 **Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
331 **Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
332
333 ## Bounty offices
334
335 **Status:** full
336 **Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
337
338 1. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
339 2. **My bounty** — Shows how much coin is currently on **your** head.
340
341 **Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
342
343 **Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
344
345 **Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
346
347 ## Banking, cheques, shops, player-driven marketplace
348
349 **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
350 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
351 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
352
353 ## Player scripting (AFK / offline)
354
355 **Status:** not implemented
356 **Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
357 **Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
1 # Feature implementation tracker
2
3 Living companion to `tile_mmo_server_technical_design_v0.6.md`.
4 Statuses: **not implemented** · **partial** · **full**.
5
6 Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
7
8 ---
9
10 ## World coordinates and spatial hierarchy
11
12 **Status:** full
13 **Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division. Positions are scoped by **dimensionId** (default `overworld`); chunk/region keys are `dim|x,y`.
14 **Code:** `server/src/world/coordinates.js`, `shared/world/dimensions.js`, tests in `server/tests/coordinates.test.js`
15
16 ## Interior dimensions
17
18 **Status:** partial
19 **Spec:** Besides the **overworld**, the world may contain named **dimensions** (caves, houses, …), each with its own chunk grid, default ground, open/closed map, **lighting mode** (`dayNight` / `alwaysLit` / `alwaysDark`), and **season mode** (`auto` / `summer` / `spring` / `autumn` / `winter`; spring→summer art, autumn→fall). Soft-delete marks a non-overworld dim unusable; after **7 days** it is purged (chunks + metadata). Cancel deletion before purge. **Doorway** blocks (`ladder` / `door` / `hole` / `cave`) teleport the player to `{ targetDimensionId, tileX, tileY }` (server-authoritative). Characters persist `dimension_id` + visits for quest conditions. Editor: searchable dim picker with inline create; per-dim settings while selected.
20 **Code:** `shared/world/dimensions.js`, `server/src/persistence/worldDb.js` (`world_dimensions`), `server/src/simulation/simulation.js` (`#relocateCharacterThroughDoorway`), `client/src/editor/dimensionCombobox.js`, `BlockType.doorway`
21
22 ## Ground and block tile layers
23
24 **Status:** full
25 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **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. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27
28 ## Open and closed chunks
29
30 **Status:** full
31 **Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
32 **Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
33
34 ## ECS registry and components
35
36 **Status:** full
37 **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.
38 **Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
39
40 ## Simulation tick
41
42 **Status:** full
43 **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.
44 **Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
45
46 ## Authored world and runtime state persistence
47
48 **Status:** full
49 **Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
50 **Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
51
52 ## World revisions and pending editor saves
53
54 **Status:** partial
55 **Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
56 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57
58 ## World settings
59
60 **Status:** full
61 **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, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. 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.
62 **Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63
64 ## Baked lighting
65
66 **Status:** full
67 **Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
68 **Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
69
70 ## World editor (server)
71
72 **Status:** full
73 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
74 **Code:** `server/src/editor/service.js`
75
76 ## World editor (client)
77
78 **Status:** full
79 **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 (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81
82 ## Per-chunk changelog
83
84 **Status:** full
85 **Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
86 **Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
87
88 ## WebSocket gateway
89
90 **Status:** full
91 **Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92 **Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
94 ## Stub authentication
95
96 **Status:** full
97 **Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
98 **Code:** `server/src/auth/stub.js`
99
100 ## Characters
101
102 **Status:** full
103 **Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
104 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
105
106 ## Character deletion and inheritance
107
108 **Status:** full
109 **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.
110 **Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
111
112 ## 3×3 chunk replication
113
114 **Status:** full
115 **Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. 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.
116 **Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
117
118 ## Click-to-move and A\* pathfinding
119
120 **Status:** full
121 **Spec:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
122 **Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
123
124 ## Global walk/run cadence
125
126 **Status:** full
127 **Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
128 **Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
129
130 ## Client movement interpolation
131
132 **Status:** full
133 **Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
134 **Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
135
136 ## Play viewport and camera
137
138 **Status:** full
139 **Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
140 **Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
141
142 ## Client graphics settings
143
144 **Status:** full
145 **Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
146 **Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
147
148 ## Night shading
149
150 **Status:** full
151 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
152 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
153
154 ## FrameworkV3 client bootstrap
155
156 **Status:** full
157 **Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
158 **Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
159
160 ## Sprite size, pivot and Y-sort
161
162 **Status:** full
163 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
164 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
165
166 ## Visual tile states
167
168 **Status:** full
169 **Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter, calendar season overrides authored state in play; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
170 **Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
171
172 ## Region workers and cross-worker transfer
173
174 **Status:** full
175 **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.
176 **Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
177
178 ## ChunkLoader activation and unload persistence
179
180 **Status:** full
181 **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.
182 **Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
183
184 ## Midnight restart and Git deploy
185
186 **Status:** full
187 **Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
188 **Code:** —
189
190 ## Spawners
191
192 **Status:** full
193 **Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
194 **Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
195
196 ## Mob definitions (content schema)
197
198 **Status:** partial
199 **Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
200 **Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
201
202 ## Quests
203
204 **Status:** partial
205 **Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
206 **Code:** `shared/quests/`, `server/src/quests/`, `server/src/persistence/worldDb.js`, `server/src/persistence/stateDb.js`, `client/src/editor/questsModal.js`, `client/src/editor/dialoguesModal.js`, `client/src/play/quests.js`, `client/src/play/dialogue.js`
207
208 ## Character logout resume
209
210 **Status:** full
211 **Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
212 **Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
213
214 ## Combat resolution (rolls)
215
216 **Status:** partial
217 **Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later.
218 **Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`
219
220 ## Combat, skills, groups, pigeons
221
222 **Status:** partial
223 **Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
224 **Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
225
226 ## Player death and respawn
227
228 **Status:** full
229 **Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
230
231 1. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
232 2. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
233 3. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
234 4. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
235 5. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
236
237 **TODO:** Revisit player-loot penalties if PK rules are added.
238 **Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
239
240 ## Equipment tiers and worn stat bonuses
241
242 **Status:** partial
243 **Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
244 **Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
245 **TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
246 **Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
247
248 ## Gathering, crafting, and production skills
249
250 **Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
251 **Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
252 **Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
253
254 ## Cloth, dyes, and tailoring
255
256 **Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
257 **Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
258 **TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
259 **Later design (document only for now):**
260 - **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
261 - **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
262 - **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
263 **Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
264
265 ## Crafting stations
266
267 **Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
268 **Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
269 **TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
270 **Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
271
272 ## Stamina and running
273
274 **Status:** full
275 **Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
276 **Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
277
278 ## Alchemy / cauldron
279
280 **Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
281 **Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
282 **Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
283
284 ### Folklore herb associations (design only — not in code)
285
286 Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
287
288 | Tier | Herb | Associations |
289 | --- | --- | --- |
290 | 1 | Mint | Refreshment, stamina, antidotes |
291 | 1 | Garlic | Undead protection, disease resistance |
292 | 2 | Thyme | Courage, vitality, resistance |
293 | 2 | Sage | Healing, wisdom, longevity |
294 | 2 | Rosemary | Memory, protection, clarity |
295 | 3 | Lavender | Sleep, calm, dreams |
296 | 3 | Chamomile | Restoration, sleep, soothing |
297 | 3 | Nettle | Vigour, resilience, protection |
298 | 4 | Yarrow | Wound healing, battle medicine |
299 | 4 | Juniper | Purification, disease resistance |
300 | 4 | Elder | Spirits, protection, healing |
301 | 4 | Rue | Curse resistance, purification |
302 | 5 | Valerian | Sleep, sedation, tranquillity |
303 | 5 | Mugwort | Dreams, visions, divination |
304 | 5 | Wormwood | Poison resistance, spirits, bitterness |
305 | 5 | St. John's wort | Holy protection, dispel darkness |
306 | 6 | Hawthorn | Fey, barriers, enchantment |
307 | 6 | Foxglove | Fairy magic, heart magic, poison |
308 | 6 | Mistletoe | Life, fertility, druidic magic |
309 | 6 | Datura | Visions, insanity, spirit walking |
310 | 7 | Belladonna | Poison, hallucination, witchcraft |
311 | 7 | Henbane | Trance, madness, sleep, poison |
312 | 7 | Mandrake | Powerful potions, curses, life magic |
313 | 7 | Aconite | Werewolves, lethal poison, curses |
314
315 ## Inventory, items, equipment, ground drops
316
317 **Status:** full
318 **Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) 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. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
319 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
320
321 ## Proximity chat
322
323 **Status:** full
324 **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.
325 **Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
326
327 ## Friends
328
329 **Status:** full
330 **Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
331 **Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
332
333 ## Hair & barber
334
335 **Status:** full
336 **Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
337 **Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
338
339 ## Bounty offices
340
341 **Status:** full
342 **Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
343
344 1. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
345 2. **My bounty** — Shows how much coin is currently on **your** head.
346
347 **Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
348
349 **Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
350
351 **Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
352
353 ## Banking, cheques, shops, player-driven marketplace
354
355 **Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
356 **Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
357 **Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
358
359 ## Player scripting (AFK / offline)
360
361 **Status:** not implemented
362 **Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
363 **Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
@@ -1,357 +1,363 @@
1# Feature implementation tracker
1# Feature implementation tracker
2
2
3Living companion to `tile_mmo_server_technical_design_v0.6.md`.
3Living companion to `tile_mmo_server_technical_design_v0.6.md`.
4Statuses: **not implemented** · **partial** · **full**.
4Statuses: **not implemented** · **partial** · **full**.
5
5
6Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
6Each entry is a short note on behaviour and where the code lives. Update this file in the same commit as the feature it describes.
7
7
8---
8---
9
9
10## World coordinates and spatial hierarchy
10## World coordinates and spatial hierarchy
11
11
12**Status:** full
12**Status:** full
13**Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division.
13**Spec:** World tile coordinates are canonical. Chunks are 16×16 tiles; regions are 4×4 chunks. Negative coordinates use true floor division. Positions are scoped by **dimensionId** (default `overworld`); chunk/region keys are `dim|x,y`.
14**Code:** `server/src/world/coordinates.js`, tests in `server/tests/coordinates.test.js`
14**Code:** `server/src/world/coordinates.js`, `shared/world/dimensions.js`, tests in `server/tests/coordinates.test.js`
15
15
16## Ground and block tile layers
16## Interior dimensions
17
17
18**Status:** full
18**Status:** partial
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **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. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
19**Spec:** Besides the **overworld**, the world may contain named **dimensions** (caves, houses, …), each with its own chunk grid, default ground, open/closed map, **lighting mode** (`dayNight` / `alwaysLit` / `alwaysDark`), and **season mode** (`auto` / `summer` / `spring` / `autumn` / `winter`; spring→summer art, autumn→fall). Soft-delete marks a non-overworld dim unusable; after **7 days** it is purged (chunks + metadata). Cancel deletion before purge. **Doorway** blocks (`ladder` / `door` / `hole` / `cave`) teleport the player to `{ targetDimensionId, tileX, tileY }` (server-authoritative). Characters persist `dimension_id` + visits for quest conditions. Editor: searchable dim picker with inline create; per-dim settings while selected.
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
20**Code:** `shared/world/dimensions.js`, `server/src/persistence/worldDb.js` (`world_dimensions`), `server/src/simulation/simulation.js` (`#relocateCharacterThroughDoorway`), `client/src/editor/dimensionCombobox.js`, `BlockType.doorway`
21
21
22## Open and closed chunks
22## Ground and block tile layers
23
23
24**Status:** full
24**Status:** full
25**Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
25**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. Live ground types include grass, wood, **water** (passable, animated; wading clips the bottom of entity sprites), and **deep water** (impassable, darker, animated). In **winter**, shallow water uses a static **`water-winter` ice** overlay (no animation, no wade clip, no coast foam); **deep water** keeps coast foam on edges against ice or land. Fishing spots in shallow water are unavailable in winter (fishing TBD). Live block types include stone wall, torch, bank, **church altar** (respawn destination — see **Player death and respawn**), crafting stations, ore boulders, and **pine tree** (32×48 seasonal sprite). Mob spawners are **not** blocks: they are authored chunk markers (`data.spawners[]`), editor-visible only, invisible/non-blocking in play, and may share a tile with a real block. **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. The client bakes immobile ≤16×16 ground/block tiles (plus bloom companions) into per-chunk atlases: one ground layer, per-row block strips for Y-sort, and one bloom layer. Oversized or animated blocks/grounds stay individual sprites so mobiles can Y-sort behind them / water can animate. Liquid water tiles use a coast-foam shader on edges against non-liquid neighbours; entity sprites use a wade clip+foam tint that respects night darkness. Grounds/blocks are marked **`outdoor`** or indoor (building walls and interior props are indoor). Only **outdoor** types may use calendar **seasonal** sprites (`summer` / `fall` / `winter`; grass also keeps legacy `grass`) or optional overlays (e.g. `*-winter` only); play picks those from **server local calendar** (spring+summer share summer: Mar–Aug; fall Sep–Nov; winter Dec–Feb) via `worldTime.season`. Indoor types never need seasonal variants.
26**Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
26**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `server/src/assets/spriteCatalog.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`
27
27
28## ECS registry and components
28## Open and closed chunks
29
29
30**Status:** full
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.
31**Spec:** Never-edited chunks are closed grass. Closed chunks can be replicated but cannot be entered; pathfinding treats them as impassable. Open chunks draw a red border on edges that touch a closed neighbour.
32**Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
32**Code:** `server/src/world/chunkData.js` (`open` flag), `server/src/world/chunkFlags.js`, `server/src/simulation/simulation.js` (`isEnterable`, `#walkableFor`, `closedEdges`), `client/src/render/worldView.js` (`#rebuildChunkEdges`)
33
33
34## Simulation tick
34## ECS registry and components
35
35
36**Status:** full
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.
37**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.
38**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
38**Code:** `server/src/ecs/world.js`, `server/src/ecs/serialize.js`, `server/src/ecs/components.js`
39
39
40## Authored world and runtime state persistence
40## Simulation tick
41
41
42**Status:** full
42**Status:** full
43**Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
43**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.
44**Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
44**Code:** `server/src/simulation/simulation.js` (`step`), `server/src/index.js`
45
45
46## World revisions and pending editor saves
46## Authored world and runtime state persistence
47
47
48**Status:** partial
48**Status:** full
49**Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
49**Spec:** `world.sqlite` holds revisioned authored chunks, live world settings, and settings/chunk changelogs. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
50**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
50**Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
51
51
52## World settings
52## World revisions and pending editor saves
53
53
54**Status:** full
54**Status:** partial
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, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. 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.
55**Spec:** Editor chunk saves write a pending world revision. The running process stays pinned to the map revision loaded at startup until an admin **Apply now** (in-process reload). Live world settings do not use this path. Midnight restart/Git deploy is not implemented yet.
56**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `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:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
57
57
58## Baked lighting
58## World settings
59
59
60**Status:** full
60**Status:** full
61**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
61**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, Economy, **Base prices**, **Starter Equipment**, …), marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). **Base prices** is a searchable, paginated item list for world `itemSeedValues` overrides (seed = base price); Market shows last-sale lerp when known, Shop shows the undiscounted catalog price from the current seed. **Starter Equipment** configures equipped slots and inventory stacks granted only to newly created characters. 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.
62**Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
62**Code:** `shared/definitions/worldSettings.js`, `shared/shop/pricing.js` (`effectiveSeedValue`, `itemPriceSnapshot`), `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
63
63
64## World editor (server)
64## Baked lighting
65
65
66**Status:** full
66**Status:** full
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
67**Spec:** On chunk save, raycast light from blocks with `lightRangeTiles` through tiles that do not occlude light, including across chunk borders. Occlusion defaults to `!passable`; set `blocksLight: false` on furniture (tables, marketplace counters, crafting stations, ore nodes, cauldron) to let light through while remaining impassable. Set `blocksLight: "partial"` on standing trees so the ray continues but each canopy tile adds +1 to falloff distance; **tree stumps** (`*-stump` state from woodcutting) clear that occlusion at runtime via live chunk snapshots (same dynamic path as torches, without rebaking). Store a 16×16 intensity map (0–255, smoothstep falloff by effective tile distance). Torch range is 8 tiles; furnace is 4.
68**Code:** `server/src/editor/service.js`
68**Code:** `server/src/lighting/baker.js`, `shared/lighting/raycast.js`, `shared/definitions/tiles.js` (`LightOcclusion` / `blocksLight`), tests in `server/tests/lighting.test.js`
69
69
70## World editor (client)
70## World editor (server)
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 zoom (centred on the selected chunk) and Shift+wheel to cycle visual states (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
73**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks/spawners, write changelog bullets, edit live world settings, and apply the pending map revision. Central Exchange counters (`BlockType.marketplace`, neighbor-connect autotile), **wooden tables** (`BlockType.table`, magenta autotile `0`–`15` tinted per wood tier; joins only the same material), and **Central Exchange staff** spawners are placeable.
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
74**Code:** `server/src/editor/service.js`
75
75
76## Per-chunk changelog
76## World editor (client)
77
77
78**Status:** full
78**Status:** full
79**Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
79**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 (for outdoor seasonal tiles: summer/fall/winter, which also updates Season preview), open/closed, per-chunk changelog, night preview slider, **season preview** dropdown, world-settings modal, **Quests** and **Dialogues** buttons under Settings (see docs/QUESTS.md), save chunk and Apply now. **Save chunk** is disabled when clean and **pulses** when the draft is dirty; navigating N/S/E/W with unsaved edits opens a confirm modal (Cancel / Discard / Save). Bottom status bar shows hovered **tile** and **chunk** coordinates. **Select block…** opens a modal with auto-loaded tabs (Ground tiles / Blocks / Spawners — one entry per mob type with mob icon). **Flower** is a single palette entry; each paint rolls a random colour (same as harvest respawn). Hover shows a tooltip of tile/spawner config and highlights a spawner’s spawn range (cyan) and wander range (amber); right-click a spawner opens its config modal. Spawners render as mob icons in the editor only.
80**Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
80**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/src/editor/paletteModal.js`, `client/src/editor/tileConfigModal.js`, `client/ui/editor.css`
81
81
82## WebSocket gateway
82## Per-chunk changelog
83
83
84**Status:** full
84**Status:** full
85**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
85**Spec:** Each save stores who, when, and structured bullets of ground/block/spawner/open-closed diffs.
86**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
86**Code:** `server/src/editor/service.js` (`diffChunks`), `server/src/persistence/worldDb.js` (`world_chunk_edit_log`), tests in `server/tests/editor-diff.test.js`
87
87
88## Stub authentication
88## WebSocket gateway
89
89
90**Status:** full
90**Status:** full
91**Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
91**Spec:** JSON WebSocket on `/ws`, HTTP static files for the client. Connections belong to the gateway. Clients send intentions that are queued onto the simulation tick. Editor messages are admin-only.
92**Code:** `server/src/auth/stub.js`
92**Code:** `server/src/gateway/websocket.js`, `server/src/gateway/http.js`, `server/src/index.js`
93
93
94## Characters
94## Stub authentication
95
95
96**Status:** full
96**Status:** full
97**Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
97**Spec:** Until auth.timfalken.com exists, each connection is `admin-<n>`. `n` starts at connected-count+1 and skips names already in use so two live sessions cannot share a stub id. Stub accounts are admins.
98**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
98**Code:** `server/src/auth/stub.js`
99
99
100## Character deletion and inheritance
100## Characters
101
101
102**Status:** full
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.
103**Spec:** Unlimited characters per account, one in the world. First name is not globally unique; last name is globally unique per account; first+last unique per account, case-insensitive. Male/female body. Spawn requires an open tile. The login screen lists characters first; **Create Character** opens a modal and successful creation enters the world immediately. New characters receive **Starter Equipment** / inventory from live world settings (origin: “Received from the gods”); existing characters are unaffected.
104**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
104**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js`, `shared/items/starterLoadout.js`, `client/index.html`
105
105
106## 3×3 chunk replication
106## Character deletion and inheritance
107
107
108**Status:** full
108**Status:** full
109**Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. 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.
109**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.
110**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
110**Code:** `server/src/characters/service.js`, `server/src/persistence/stateDb.js` (`account_inheritance`)
111
111
112## Click-to-move and A\* pathfinding
112## 3×3 chunk replication
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. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
115**Spec:** Entity and ground-item replication uses the current chunk and eight neighbours. Map tiles (static snapshots) default to a **5×5** ring (`STATIC_CHUNK_RADIUS = 2`); clients may request **Short** viewing distance so the map ring matches the 3×3 entity ring. 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.
116**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
116**Code:** `server/src/simulation/simulation.js` (`snapshotsForView`, `snapshotChunk`, `drainReplication`), `server/src/gateway/websocket.js` (`syncSubscriptions`, `publishEntity`), `shared/graphics/settings.js`
117
117
118## Global walk/run cadence
118## Click-to-move and A\* pathfinding
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:** `MOVE_TO` runs A\* over the visible 3×3 using block passability and open-chunk bounds. Entities do **not** block each other’s movement (players and mobs pass through). Occupied tiles are still preferred-away for mob wander goals and required to be clear for melee attack stance. Client spreads stacked entities evenly on a circle (`ENTITY_STACK_SPREAD_DIAMETER_PX`, centred on the tile) with a short lerp into place; within-tile y-sort still uses each sprite’s visual Y. Server commits integer tiles on the movement cadence. Neighbour expansion prefers steps that most reduce Manhattan distance to the goal; remaining ties break by axis — **players prefer vertical**, **mobs prefer horizontal** — so mutual approaches are less likely to oscillate sideways.
122**Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
122**Code:** `server/src/navigation/astar.js`, `server/src/simulation/workerWorld.js` (`#moveTo`, `#stepMovement`, `walkableFor`, `isClearStanding`)
123
123
124## Client movement interpolation
124## Global walk/run cadence
125
125
126**Status:** full
126**Status:** full
127**Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
127**Spec:** Walk 2 tiles/s, run double. Movement ticks at run rate. `SetGait` chooses every-other vs every movement tick.
128**Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
128**Code:** `server/src/simulation/workerWorld.js` (`#stepMovement`, `#setGait`)
129
129
130## Play viewport and camera
130## Client movement interpolation
131
131
132**Status:** full
132**Status:** full
133**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
133**Spec:** Client lerps sprites between replicated tiles over the walk or run interval from world settings.
134**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
134**Code:** `client/src/render/worldView.js` (`moveEntity`, `update`)
135
135
136## Client graphics settings
136## Play viewport and camera
137
137
138**Status:** full
138**Status:** full
139**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
139**Spec:** Camera stays centered on the local player. Scroll-wheel zoom is viewport-only (1×–4×) and does not change server visibility. Tiles and chunk atlases more than half a tile outside the screen (zoom-aware) are not drawn and skip per-frame lighting work. Hovering another player shows their first name; clicking them inspects instead of issuing move.
140**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
140**Code:** `client/src/render/worldView.js` (`#cullOffscreenDrawables`, `#drawBounds`), `client/src/play/main.js`, `client/index.html`
141
141
142## Night shading
142## Client graphics settings
143
143
144**Status:** full
144**Status:** full
145**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
145**Spec:** Gear button (top-right) opens a client settings panel persisted in `localStorage`. **Viewing distance** Long (default) keeps the 5×5 map ring; Short limits map subscriptions to the 3×3 around the player (`SET_GRAPHICS_SETTINGS`). **Lighting** Soft (default) uses corner-blended lightmaps; Simple fills each tile flat. **Bloom** On/Off toggles the bloom render layer.
146**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
146**Code:** `shared/graphics/settings.js`, `client/src/play/graphicsSettings.js`, `client/src/render/worldView.js` (`setGraphicsPrefs`), `server/src/gateway/websocket.js`
147
147
148## FrameworkV3 client bootstrap
148## Night shading
149
149
150**Status:** full
150**Status:** full
151**Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
151**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened by `nightDarkness` (a live world setting) and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle. With **Soft** lighting, baked ground/block atlases sample a per-chunk lightmap with neighbour blending; **Simple** lighting uses a flat per-tile intensity (no corner blend). **Animated liquid water** uses the same lit values via shader uniforms. **Light-occluding tiles** (`blocksLight` / impassable ground) stay flat and contribute **0** into open neighbours (and diagonals need both cardinals clear), so a torch beside a wall does not soft-light the far side. Oversized/animated blocks and mobiles still use a uniform darkness for their standing tile (entities lerp shade while moving). `worldTime` also carries the real **server-local calendar season** (`summer` / `fall` / `winter`) for seasonal tile visuals.
152**Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
152**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`, `#writeChunkLightmap`, `#placeSpriteShade`, `setWorldSeason`), `server/src/simulation/simulation.js` (`worldTime`), `shared/world/season.js`
153
153
154## Sprite size, pivot and Y-sort
154## FrameworkV3 client bootstrap
155
155
156**Status:** full
156**Status:** full
157**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
157**Spec:** FrameworkV3 is a git submodule at `client/frameworkv3`, built first via `npm run build:client`. Game code lives in `client/src`. Server does not import it.
158**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
158**Code:** `.gitmodules`, `client/frameworkv3`, `client/scripts/build-framework.mjs`
159
159
160## Visual tile states
160## Sprite size, pivot and Y-sort
161
161
162**Status:** full
162**Status:** full
163**Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter, calendar season overrides authored state in play; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
163**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets. Immobile ≤16×16 blocks bake into per-row chunk strips; taller sprites stay individually Y-sorted.
164**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
164**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, `client/src/render/chunkBake.js`, tests in `server/tests/pivot.test.js`
165
165
166## Region workers and cross-worker transfer
166## Visual tile states
167
167
168**Status:** full
168**Status:** full
169**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.
169**Spec:** Each ground and block type has a folder of PNG states. Non-seasonal types use the first alphabetical file as the default; outdoor seasonal types prefer `summer` (or legacy `grass`). States are visual only; the game may set a named state (for example a door or ore). For outdoor types that expose summer/fall/winter, calendar season overrides authored state in play; the editor Season preview (and Shift+wheel on seasonal tools) chooses which seasonal look to show while editing. Indoor types (floors, walls, furniture) do not need seasonal art. The editor wheel cycles states; hover previews the selected tool on the target tile.
170**Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
170**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `shared/world/season.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`, `server/tests/season.test.js`
171
171
172## ChunkLoader activation and unload persistence
172## Region workers and cross-worker transfer
173
173
174**Status:** full
174**Status:** full
175**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.
175**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.
176**Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
176**Code:** `server/src/simulation/simulation.js`, `workerWorld.js`, `inProcessWorker.js`, `threadWorker.js`, tests in `server/tests/worker-*.test.js`
177
177
178## Midnight restart and Git deploy
178## ChunkLoader activation and unload persistence
179
179
180**Status:** full
180**Status:** full
181**Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
181**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.
182**Code:** —
182**Code:** `server/src/simulation/chunkLoader.js`, `server/src/simulation/simulation.js`, `server/src/persistence/stateDb.js` (`persistent_entities`)
183
183
184## Spawners
184## Midnight restart and Git deploy
185
185
186**Status:** full
186**Status:** full
187**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
187**Spec:** systemd + manifest-driven Git deploy. Pending world/code changes apply at server-local midnight, with an admin immediate-restart path. Crashes must not pull.
188**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
188**Code:** —
189
189
190## Mob definitions (content schema)
190## Spawners
191
191
192**Status:** partial
192**Status:** full
193**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
193**Spec:** Authored chunk spawners (`data.spawners[]`) with mob type, max alive, spawn range, and **max wander range** (≥ spawn range). Legacy `BlockType.spawner` tiles migrate into this array on decode. They fire only in open, simulating chunks. When a chunk first becomes simulating, spawners **pre-heat** and place up to `maxAlive` immediately so the area looks populated. Spawned mobs get `SpawnOrigin` (origin tile + wander range); idle wander goals must stay inside max wander range, while combat chase / approach may leave the area. Persistence follows the mob definition (deer are not persistent). In play, spawners are invisible and non-blocking; players may place real blocks on the same tile. Wildlife options include deer and rats; the editor lists every mob definition as a placeable spawner. Hovering a spawner in the world editor highlights spawn range (cyan) and wander range (amber). Pigeons are not ambient wildlife. Living mobs (deer, rats, etc.) can always fight back when attacked (retaliate on first swing); **rats are aggressive** and auto-engage players within 5 tiles with line of sight. **Humanoid** spawners (incl. town guards / exchange) have an editor **Aggressive** flag for the same in-range aggro; Aggressive forces **Bounty** to 0. Spawner **Level** sets skills/HP and **spell cast chance %** (= level, capped 1–100; shown as a label, not editable).; courier pigeons cannot.
194**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
194**Code:** `server/src/simulation/spawners.js`, `server/src/simulation/workerWorld.js`, `server/src/world/chunkData.js`, `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`, `client/src/editor/tileConfigModal.js`, `client/assets/mobs/deer/`, `client/assets/mobs/rat/`
195
195
196## Quests
196## Mob definitions (content schema)
197
197
198**Status:** not implemented (design)
198**Status:** partial
199**Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
199**Spec:** Target mob content shape: `displayName`, `maxHealth`, `attackSkill`, `drops`, `sells`. **Dialogue trees** are world-scoped assets (Dialogues editor); humanoid spawners assign `config.dialogueId`. See [`docs/QUESTS.md`](QUESTS.md).
200**Code:** —
200**Code:** `shared/definitions/mobs.js`, `shared/definitions/mobCombat.js`
201
201
202## Character logout resume
202## Quests
203
203
204**Status:** full
204**Status:** partial
205**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
205**Spec:** Full design in [`docs/QUESTS.md`](QUESTS.md). World editor **Quests** / **Dialogues** buttons (under Settings) author world-scoped defs. Spawners link `dialogueId`; unique dialogues require one spawner with `maxAlive: 1`. Shared `ConditionSet` (AND + per-clause NOT). Play **Quests** UI + step-complete toast “Quest objectives achieved”. Progress / journal / `dialogueHeard` in `state.sqlite`.
206**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
206**Code:** `shared/quests/`, `server/src/quests/`, `server/src/persistence/worldDb.js`, `server/src/persistence/stateDb.js`, `client/src/editor/questsModal.js`, `client/src/editor/dialoguesModal.js`, `client/src/play/quests.js`, `client/src/play/dialogue.js`
207
207
208## Combat resolution (rolls)
208## Character logout resume
209
209
210**Status:** partial
210**Status:** full
211**Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later.
211**Spec:** Despawning a character (logout / disconnect) writes their live tile to `characters`. The next login reloads that row after despawn and resumes there (or the nearest free enterable tile within a short spiral if blocked), instead of jumping to a distant world spawn.
212**Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`
212**Code:** `server/src/simulation/simulation.js` (`spawnCharacter`, `despawnCharacter`), tests in `server/tests/character-resume.test.js`
213
213
214## Combat, skills, groups, pigeons
214## Combat resolution (rolls)
215
215
216**Status:** partial
216**Status:** partial
217**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
217**Spec:** Authoritative server rolls; clients only show outcomes. **Melee & ranged (physical):** roll hit skill vs defender **Dexterity (agility)** — miss if attack roll < agility roll, hit on tie or higher; on hit roll damage skill (Strength for melee, Dexterity for ranged) for `baseDamage + roll − 1`; on hit defender rolls Defence — **block** if defence roll > attacker's to-hit roll; otherwise apply damage. **Effective combat levels** add worn equipment tier bonuses to damage/agility/defence rolls (e.g. Strength 10 + bronze weapon +1 → damage roll uses 11). Hit skills (Club/Sword fighting, Archery) use base skill only. XP only on damage hits. **Attack types** (slashing / piercing / blunt) are defined on weapons; mob weak/resist multipliers remain later. **Magic:** roll Magic vs per-spell **difficulty** (contest, tie or higher succeeds); on success roll Mind for damage; multiply by elemental weak ×2 / neutral ×1 / resistant ×0.5; non-damage spells only need a successful cast roll then apply an effect. Spell defs in `shared/definitions/spells.js`. Full casting UI, LOS, and effect system remain later.
218**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
218**Code:** `shared/combat/rolls.js` (physical, live), `shared/combat/magic.js` (cast + damage rules, shared only), `shared/definitions/spells.js`, `shared/definitions/attackTypes.js`, `shared/equipment/stats.js`, `server/src/combat/service.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/magic.test.js`, `server/tests/equipment.test.js`
219
219
220## Player death and respawn
220## Combat, skills, groups, pigeons
221
221
222**Status:** full
222**Status:** partial
223**Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
223**Spec:** Melee auto-attack with stick (Clubfighting + Strength), LMB/RMB targeting and context menu (including **Follow \<name\>** / **Attack \<name\>**), engage/retaliate, swipe VFX, shove animation, damage flash, HP bars above **mobs and players** when below max HP, and client dynamic-light hooks. Fightable mobs **retaliate on the first resolved swing** (hit or miss), not when Attack is merely clicked. **Players likewise auto-retaliate** when a mob’s first swing resolves against them (clears follow/gather). Melee requires Chebyshev distance 1 (**diagonals allowed**) while the attacker stands alone on their tile; if stacked with others they path to the nearest clear adjacent stance. Approach pathfinding may pass through entities but prefers clear goal tiles. **Aggressive** mobs (e.g. rats: `aggressive` + `aggroRangeTiles`, default 5) auto-engage player characters in Chebyshev range with line of sight through enterable tiles; passive wildlife (deer) does not. Engaged mobs keep pursuing if the player cancels attack. Physical combat uses skill rolls (see **Combat resolution**). **Health** skill sets max HP; taking damage awards Health XP equal to damage taken. Reaching **0 HP** is player death (see **Player death and respawn**). Follow reuses the target's vacated trail and remaining path (stop one tile short, wait for vacancy, walkability each step); catch-up A* only when no shared trail yet. Break beyond one chunk width. **Carrier pigeons** dispatch money or one inventory stack to Bank or Player. **Skills:** persistent XP, 50 XP to level 2 then double each level, cap 99; Health starts at 10, others at 1; **login enforces those minima** (raises and persists under-leveled skills). Skills panel. Ranged combat, magic, groups, and non-combat skill XP (except Health from damage) remain later.
224
224**Code:** `shared/combat/rolls.js`, `shared/skills/progression.js`, `shared/skills/state.js`, `shared/definitions/skills.js`, `shared/definitions/mobCombat.js`, `shared/definitions/mobs.js`, `server/src/skills/service.js`, `server/src/combat/service.js`, `client/src/play/skills.js`, `client/src/render/worldView.js`, tests in `server/tests/combatRolls.test.js`, `server/tests/skills.test.js`, `server/tests/mobCombat.test.js` (+ combat/follow/courier tests)
2251. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
225
2262. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
226## Player death and respawn
2273. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
227
2284. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
228**Status:** full
2295. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
229**Spec:** When a **player** reaches **0 HP**, they **die** immediately (authoritative on the server):
230
230
231**TODO:** Revisit player-loot penalties if PK rules are added.
2311. **Corpse drops** on the death tile: a **bones** ground item and a **skull** ground item (new item definitions + sprites). These use normal ground-item rules (pickup, despawn timer). Inventory/equipment are **not** dropped by default (death penalty is the corpse markers + travel to church — revisit if PK/loot rules are added later).
232**Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
2322. **Combat ends** for the dead player and anyone targeting them (clear engage both ways). The dead player cannot move, attack, follow, pick up, bank, chat-actions that affect the world, or otherwise act until they respawn.
233
2333. **Death modal (client):** a blocking modal that is the **only** interactable UI while dead (world clicks, hotkeys, bag, etc. are ignored). Copy states that the player is dead; primary action is **Respawn**. Closing the tab/disconnect while dead keeps them dead until they log in and respawn (or auto-prompt the same modal on re-enter).
234## Equipment tiers and worn stat bonuses
2344. **Respawn:** server moves the character to the **nearest church altar** block (Chebyshev / path distance TBD — prefer enterable tile adjacent to the altar if the altar tile itself is impassable). New **block type: church altar** (`BlockType` + editor placeable + sprite folder), passable or adjacent-use like bank (exact interaction: respawn destination only for now, not a usable station).
235
2355. After respawn the player is restored to **full Health** and **full Stamina** (max from skills), cleared of death state, and may fight again.
236**Status:** partial
236
237**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
237**TODO:** Revisit player-loot penalties if PK rules are added.
238**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
238**Code:** `shared/definitions/items.js`, `shared/definitions/tiles.js`, `shared/protocol/constants.js`, `server/src/combat/service.js`, `server/src/simulation/simulation.js`, `server/src/simulation/workerWorld.js`, `server/src/persistence/stateDb.js`, `server/src/gateway/websocket.js`, `client/src/play/death.js`, tests in `server/tests/death.test.js`
239**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
239
240**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
240## Equipment tiers and worn stat bonuses
241
241
242## Gathering, crafting, and production skills
242**Status:** partial
243
243**Spec:** Metal gear exists in seven material tiers (lowest → highest): **Bronze**, **Iron**, **Steel**, **Mithril**, **Adamantium**, **Orichalcum**, **Dragon**. Each has a **rank** (1–7), display **tint**, and equip min skill: 1 / 10 / 20 / 35 / 50 / 70 / 90. Mining a material requires **half** of that equip gate (ceil); smelting requires **75%** (ceil). Worn combat bonuses still use `TIER_STAT_BONUS`. Tools (pickaxes) gate on Mining. **Tin** and **copper** ores (no bronze ore) and **coal** use their associated bar tier for mine/smelt timing and gates (tin/copper → bronze, coal → steel). **Silver** and **Gold** are precious-only (ore + bars, no tools; silver mine/smelt like iron rank 2 / skill 10, gold like steel rank 3 / skill 20). **Wood tiers** (same gates/ranks): **Pine**, **Birch**, **Oak**, **Ebony**, **Lignum**, **Heartwood**, **Elder** (match metal ranks for hafts). **Cloth tiers** (same gates/ranks): **Cotton**, **Wool**, **Linen**, **Cashmere**, **Silk**, **Fairy silk**, **Dragonweave**. Logs/handles tint from shared `wood` sprites; **pine trees** are chopable resource nodes (more tree tiers later) — axe sprites (`items/axe`) match pickaxe style for woodcutting. Armour pieces share one set of overlays under `items/armour/` tinted per metal tier (no per-tier icon copies).
244**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
244**Shared sprites + magenta tint:** one base sprite per shape under `items/metal` (`ore`, `bar`), `items/pickaxe`, `items/axe` (`axe`, `axe-head`, `axe-equip`), `items/wood` (`log`, `handle`), `items/cloth` (`wool`, `yarn`, `cloth`), `items/clothing` (`sweater`), boulder-ore, and **tables** (`blocks/table/0`–`15`); tintable pixels use magenta rules in `shared/render/tint.js`. Boulder ore states are catalog aliases of `boulder-ore.png` with per-material tint. Table states are `${woodTier}-${mask}` aliases of mask PNGs with wood-tier tint; tables autotile only with the same wood. Trees use per-season live + **`-stump`** PNGs (mandatory for every tree type).
245**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
245**TODO:** full combat gear catalog; more tree tiers / fishing / herbs; silver/gold jewelry / other precious recipes; cloth sources beyond cotton.
246**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
246**Code:** `shared/definitions/materialTiers.js`, `shared/render/tint.js`, `shared/definitions/metalItems.js`, `shared/definitions/woodItems.js`, `shared/equipment/stats.js`, tests in `server/tests/equipment.test.js`, `server/tests/mining.test.js`, `server/tests/tint.test.js`
247
247
248## Cloth, dyes, and tailoring
248## Gathering, crafting, and production skills
249
249
250**Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
250**Status:** partial (mining + smelting + pickaxe/axe craft chains + pine woodcutting + cotton/flower/herb herbalism live)
251**Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
251**Spec:** **Mining:** LMB/RMB on ore boulder (states `tin-ore`, `copper-ore`, `iron-ore`, `silver-ore`, `gold-ore` … `dragon-ore`, `coal`). Uses the **best usable pickaxe in inventory** (or weapon slot) — tools need not be equipped. Tool rank ≥ associated bar rank and Mining ≥ mine gate; otherwise toast *"You need a pickaxe to mine this!"*. Duration `(rank×8s) − (toolRank×3s)` (min 0.5s). Attack shove animation, **no** swipe FX; while swinging, the gather tool's **equip sprite** is shown in the weapon overlay (even if a different weapon is equipped). Awards Mining XP (`rank×5`). On success the node becomes **exhausted** (plain `boulder` sprite, not mineable) for `10s × associated bar rank`, then restores its ore state via runtime `CHUNK_DELTA`. Hovering an active ore/tree/plant node shows a cursor tooltip (`resourceNodeDisplayName`). Outdoor blocks may also use **optional seasonal overlays** (e.g. boulder / ore `*-winter` only — other seasons keep the base sprite). **Woodcutting:** LMB/RMB / **Chop** on outdoor tree blocks (**pine** today). Best usable **axe** in inventory/weapon; Woodcutting + axe tier gates match mining (pine = rank 1). Same duration/exhaust curves. Success grants a **pine log**, stamps **`Felled by <name>`**, awards Woodcutting XP, and sets a **seasonal stump** (`summer-stump` / `fall-stump` / `winter-stump` — required for every tree type). Calendar season still drives stump look while exhausted; after exhaust the live tree returns. **Herbalism (plants):** **Flower** nodes need **no tool** (~1s); each flower block carries a fixed colour tint (chosen on respawn / editor place) and picking yields that colour, stamps **`Picked by <name>`**. **Cotton plant** needs **no tool** (RMB Pick / LMB); yields cotton fibre. Both exhaust ~15s then respawn. **Smelting:** furnace block opens craft UI; duration `rank×2s` by output bar tier. Recipes 1 ore → 1 bar except **bronze** = 1 tin + 1 copper, **steel** = 1 iron ore + 1 coal, **adamantium** = 1 ore + 1 coal, **orichalcum** = 1 ore + 3 coal, **dragon** = 1 ore + 5 coal. Smithing XP on success. **Pickaxe / axe craft:** woodworking bench shapes 1 log → 1 handle; anvil smiths 1 bar → 1 pickaxe head or axe head; **crafting bench** assembles matching-tier handle + head → pickaxe or axe (pine↔bronze … elder↔dragon). Gold bars are smeltable but have no tool recipes. Server-authoritative `START_CRAFT` / timer. Play errors (mine gates, full bag, …) show as temporary **toasts** at the top of the screen. More tree tiers / fishing / other stations later.
252**TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
252**Code:** `shared/definitions/gathering.js`, `shared/definitions/tiles.js` (`resourceNodeDisplayName`, `isChopableTreeBlock`, `isPickablePlantBlock`), `shared/world/season.js` (`treeStumpStateForSeason`), `server/src/gathering/service.js`, `server/src/crafting/service.js`, `shared/crafting/stationRecipes.js`, `client/src/play/main.js`, `client/src/render/worldView.js` (`spawnGatherSwing`), tests in `server/tests/mining.test.js`, `server/tests/woodcutting.test.js`, `server/tests/crafting.test.js`
253**Later design (document only for now):**
253
254- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
254## Cloth, dyes, and tailoring
255- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
255
256- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
256**Status:** partial (cotton loop + flower dyes + sweater live; higher cloth sources TBD)
257**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
257**Spec:** **Cloth tiers** (same skill gates/ranks as metal/wood): Cotton, Wool, Linen, Cashmere, Silk, Fairy silk, Dragonweave. Shared magenta sprites under `items/cloth` (`wool` fibre, `yarn`, `cloth`) and `items/clothing` (`sweater` + equip) tinted per tier (or optional dye colour on clothing instances). **Spinning wheel** (Tailoring): fibre → yarn. **Loom**: yarn → cloth. **Tailor bench** UI is template-first: pick clothing template (sweater today; shirt/robe later) → cloth tier → optional dye from bag → sidebar shows resolved ingredients (sweater = 3 yarn). Crafted clothing can carry `instance.dyeColor`; otherwise material tint. **Flowers** (9 colours) brew 1:1 into **dye** bottles at a cauldron (needs **glass bottles** / `potion-0`). Two different dye colours mix paint-style (weighted by fill); bottle count follows inserted dyes; fill packs with overflow into the next bottle (extra glass only if overflow needs more bottles than inputs). Cannot mix flowers with dyes in one brew. Dye uses on tailor consume one fill level per craft.
258
258**TODO (sources):** shear animals / pick plants for wool–silk; fairy silk + dragonweave as mob drops later.
259## Crafting stations
259**Later design (document only for now):**
260
260- **Wizard cloth gear** — robes and similar give Magic skill bonuses (`EquipmentKind.wizardCloth`).
261**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
261- **Cosmetic cloth gear** — sum equipped cosmetic item tiers as **Style points** (quests / exclusive areas).
262**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
262- **Warm clothing** — sweaters and other warm pieces reduce cold-season debuffs (e.g. winter halves stamina regen; each warm-equipped slot except hands mitigates; full warm set nullifies cold; summer reverses). **Padding** from cloth + matching-tier plate at a crafting bench → **padded armour** per slot.
263**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
263**Code:** `shared/definitions/materialTiers.js` (`ClothTier`), `shared/definitions/clothItems.js`, `shared/definitions/dyes.js`, `shared/crafting/tailor.js`, `shared/crafting/stationRecipes.js`, `server/src/alchemy/service.js`, `server/src/crafting/service.js`, `server/src/gathering/service.js`, `client/src/play/crafting.js`, `client/src/play/alchemy.js`
264**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
264
265
265## Crafting stations
266## Stamina and running
266
267
267**Status:** partial (furnace, anvil, woodworking, crafting, spinning wheel, loom, tailor bench live)
268**Status:** full
268**Spec:** Furnace / anvil / woodworking-bench / crafting-bench / spinning-wheel / loom / tailor-bench blocks + adjacency craft panel. Recipes in `stationRecipes.js`. Furnace/anvil/woodworking/crafting craft timer = `smeltingDurationMs` (`rank × 2s`) when `xpMaterial` is set; other stations still use `CRAFT_DURATION_MS` (2s) / UI/dev only (`__craftDev`). Woodworking shapes components (handles); crafting bench joins finished parts (pickaxe/axe head + handle). Spinning wheel / loom / tailor use Tailoring. **Anvil**, **woodworking**, and **tailor** craft UIs use a material dropdown so tier variants share one recipe cell (plant clippers = 1 bar per metal tier). **Hard rule (all stations + cauldron, player and scripts):** items in station slots are never committed out of the inventory — slots are a reservation/view over the bag (**client-side UI**; even if it looks like mats sit in the station, they do not). Server soft-tracks steps/claims only and consumes on successful craft/brew. Closing the UI, cancelling, or dying mid-craft/brew cannot destroy reserved mats. Station progress is **per player**, not tile-global. See `.cursor/rules/station-inventory.mdc`.
269**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
269**TODO:** oven/campfire burn; dedicated station sprites where still placeholder.
270**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
270**Code:** `shared/definitions/craftingStations.js`, `shared/definitions/tiles.js`, `server/src/crafting/service.js`, `client/src/play/crafting.js`
271
271
272## Alchemy / cauldron
272## Stamina and running
273
273
274**Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
274**Status:** full
275**Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
275**Spec:** **Stamina** skill sets max stamina (= skill level). Login / new characters floor Stamina at **level 5**. Each stamina point equals **one second of running** (drains on successful run tile steps). Running awards **1 Stamina XP** per stamina point spent. Walking, idle, or **run gait with no active path** regenerates **1 stamina per second**. At 0 stamina, run gait is forced back to walk; you cannot toggle run until stamina recovers. Client shows vertical **HP** (always) and **stamina** bars bottom-right.
276**Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
276**Code:** `shared/stamina/rules.js`, `shared/definitions/skills.js` (`playerMaxStamina`, `DEFAULT_PLAYER_SKILL_LEVELS`), `server/src/simulation/workerWorld.js`, `server/src/skills/service.js` (`syncPlayerStamina`), `client/src/play/stamina.js`, tests in `server/tests/stamina.test.js`
277
277
278### Folklore herb associations (design only — not in code)
278## Alchemy / cauldron
279
279
280Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
280**Status:** partial (starter herb potions + failed-effect list + status ticks live; more recipes TBD)
281
281**Spec:** **Herbalism** gathers flowers, cotton, and **24 folklore herbs** (`BlockType.herbPlant`). Flowers/cotton need **no tool**; clipper herbs require **plant clippers** and Herbalism gates by tier. **Alchemy** cauldron tabs **Alchemy** / **Dyes**. Starter potions: **Lesser health tonic** (thyme→heat→mint→stir; health regen 1/s for 10s, re-drink extends), **Lesser haste draught** (2 mint→heat→stir→lavender→cool; stamina regen 1/s for 10s), **Strength potion** (3 thyme→stir→2 nettle→heat; +5 Strength for 1 min), **Clarity potion** (rosemary→cool→2 chamomile→stir; +5 Mind for 1 min). Failed brews hash to unstable effects: stamina drain 1/s 15s, weak glow light 10s, shrink to 50% scale 30s, blindness 20s (extra darkness + local vision bubble). Active effects show as HUD icons left of the HP/stamina bars (`assets/status-effects/`; hover shows description + remaining time). Opening needs empty glass bottles. **Dyes** unchanged (flowers).
282| Tier | Herb | Associations |
282**Code:** `shared/definitions/alchemy.js`, `shared/statusEffects/rules.js`, `shared/statusEffects/display.js`, `server/src/statusEffects/service.js`, `client/src/play/statusEffects.js`, `shared/definitions/herbs.js`, `server/src/alchemy/service.js`, `server/src/items/bags.js`, `client/src/render/worldView.js`, tests in `server/tests/alchemy.test.js`, `server/tests/herbalism.test.js`
283| --- | --- | --- |
283
284| 1 | Mint | Refreshment, stamina, antidotes |
284### Folklore herb associations (design only — not in code)
285| 1 | Garlic | Undead protection, disease resistance |
285
286| 2 | Thyme | Courage, vitality, resistance |
286Use later when deciding which ingredients fit which potions. Tiers: **2 / 3 / 3 / 4 / 4 / 4 / 4** for T1–T7.
287| 2 | Sage | Healing, wisdom, longevity |
287
288| 2 | Rosemary | Memory, protection, clarity |
288| Tier | Herb | Associations |
289| 3 | Lavender | Sleep, calm, dreams |
289| --- | --- | --- |
290| 3 | Chamomile | Restoration, sleep, soothing |
290| 1 | Mint | Refreshment, stamina, antidotes |
291| 3 | Nettle | Vigour, resilience, protection |
291| 1 | Garlic | Undead protection, disease resistance |
292| 4 | Yarrow | Wound healing, battle medicine |
292| 2 | Thyme | Courage, vitality, resistance |
293| 4 | Juniper | Purification, disease resistance |
293| 2 | Sage | Healing, wisdom, longevity |
294| 4 | Elder | Spirits, protection, healing |
294| 2 | Rosemary | Memory, protection, clarity |
295| 4 | Rue | Curse resistance, purification |
295| 3 | Lavender | Sleep, calm, dreams |
296| 5 | Valerian | Sleep, sedation, tranquillity |
296| 3 | Chamomile | Restoration, sleep, soothing |
297| 5 | Mugwort | Dreams, visions, divination |
297| 3 | Nettle | Vigour, resilience, protection |
298| 5 | Wormwood | Poison resistance, spirits, bitterness |
298| 4 | Yarrow | Wound healing, battle medicine |
299| 5 | St. John's wort | Holy protection, dispel darkness |
299| 4 | Juniper | Purification, disease resistance |
300| 6 | Hawthorn | Fey, barriers, enchantment |
300| 4 | Elder | Spirits, protection, healing |
301| 6 | Foxglove | Fairy magic, heart magic, poison |
301| 4 | Rue | Curse resistance, purification |
302| 6 | Mistletoe | Life, fertility, druidic magic |
302| 5 | Valerian | Sleep, sedation, tranquillity |
303| 6 | Datura | Visions, insanity, spirit walking |
303| 5 | Mugwort | Dreams, visions, divination |
304| 7 | Belladonna | Poison, hallucination, witchcraft |
304| 5 | Wormwood | Poison resistance, spirits, bitterness |
305| 7 | Henbane | Trance, madness, sleep, poison |
305| 5 | St. John's wort | Holy protection, dispel darkness |
306| 7 | Mandrake | Powerful potions, curses, life magic |
306| 6 | Hawthorn | Fey, barriers, enchantment |
307| 7 | Aconite | Werewolves, lethal poison, curses |
307| 6 | Foxglove | Fairy magic, heart magic, poison |
308
308| 6 | Mistletoe | Life, fertility, druidic magic |
309## Inventory, items, equipment, ground drops
309| 6 | Datura | Visions, insanity, spirit walking |
310
310| 7 | Belladonna | Poison, hallucination, witchcraft |
311**Status:** full
311| 7 | Henbane | Trance, madness, sleep, poison |
312**Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) 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. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
312| 7 | Mandrake | Powerful potions, curses, life magic |
313**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
313| 7 | Aconite | Werewolves, lethal poison, curses |
314
314
315## Proximity chat
315## Inventory, items, equipment, ground drops
316
316
317**Status:** full
317**Status:** full
318**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.
318**Spec:** 32-slot inventory, stacking, equipment slots (head, chest, legs, boots, weapon, **offhand** for shields) 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. Right-click bag items for Send / Equip / Drop / Eat (food); paper can be written into unique **letter** instances (signed on Save; only the signer may edit). Equipping always takes **one** item from a stack (never the whole stack); unequipping returns one item and merges into an existing compatible inventory stack when stack rules allow. Equip enforces tier min-skill gates. Eating food heals (see Health skill).
319**Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
319**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `server/src/items/bags.js`, `client/src/play/inventory.js`
320
320
321## Friends
321## Proximity chat
322
322
323**Status:** full
323**Status:** full
324**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
324**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.
325**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
325**Code:** `shared/speech/proximity.js`, `server/src/chat/speech.js`, `client/src/play/chat.js`, tests in `server/tests/proximity-speech.test.js`
326
326
327## Hair & barber
327## Friends
328
328
329**Status:** full
329**Status:** full
330**Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
330**Spec:** Character-to-character friends in `state.sqlite`. Hover shows first name; click opens inspect (full name, request/accept/remove). Requests must be accepted. Unfriend is symmetric. Incoming/outgoing lists live in the Friends panel.
331**Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
331**Code:** `server/src/friends/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/social.js`, tests in `server/tests/friends.test.js`
332
332
333## Bounty offices
333## Hair & barber
334
334
335**Status:** full
335**Status:** full
336**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
336**Spec:** Character creation picks a hair style (per sex body folder) plus hue/saturation/darkness; live preview tints magenta hair sprites. Hair is stored on the character and drawn as a head overlay unless headgear is worn (item defs may set `equipment.keepHair` to keep hair under a hat — none yet). Placeable **Barber** blocks reopen the same UI to restyle (preview hides headgear).
337
337**Code:** `shared/appearance/hair.js`, `server/src/barber/service.js`, `client/src/play/hairControls.js`, `client/src/play/barber.js`, `client/assets/blocks/barber/`
3381. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
338
3392. **My bounty** — Shows how much coin is currently on **your** head.
339## Bounty offices
340
340
341**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
341**Status:** full
342
342**Spec:** Placeable **Bounty Office** blocks. Interacting opens a modal with two tabs:
343**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
343
344
3441. **Place / raise bounty** — Search a character by first + last name. If found, show a small character preview and the **current bounty** already on that head. The player may spend **coins** from inventory to add any positive amount to that bounty (server-authoritative; coins consumed only on success).
345**Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
3452. **My bounty** — Shows how much coin is currently on **your** head.
346
346
347## Banking, cheques, shops, player-driven marketplace
347**Payout on kill:** When a player who still has bounty \> 0 is **killed by another player** (attacker dealt the killing blow / engaged death), a **carrier pigeon** is dispatched from the **nearest bounty office** to the **killer's bank**, delivering a letter stating they received a bounty of **N** coins, where **N** is the **full sum** of all coin placed on the victim. Those **N** coins are **deposited immediately into the killer's bank vault** (not inventory). The victim's bounty is then reset to **0**.
348
348
349**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
349**Inspect UI:** Viewing another player's inspect/info modal also shows their bounty amount; if the amount is **0**, omit the bounty line entirely.
350**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
350
351**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
351**Code:** `shared/bounty/pricing.js`, `shared/definitions/tiles.js` (`BlockType.bountyOffice`), `server/src/bounty/service.js`, `server/src/courier/service.js`, `server/src/persistence/stateDb.js`, `client/src/play/bounty.js`, `client/assets/blocks/bounty-office/`, tests in `server/tests/bounty.test.js`
352
352
353## Player scripting (AFK / offline)
353## Banking, cheques, shops, player-driven marketplace
354
354
355**Status:** not implemented
355**Status:** partial (banks/cheques/origins/NPC shops live; Central Exchange order book live)
356**Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
356**Spec:** Bank blocks open bag + vault UI when used (LMB / RMB **Bank**). Click transfers between bag and vault; RMB offers Transfer all / half / one / X (or **Transfer** for stacks of 1). Vault slots are unlimited and ignore normal stack caps (except coins still cap at 999B per stack); unique-instance items such as letters never merge, even in the vault. Equipment and weapons max stack to 1 in inventory but may stack in the vault. Stacks track crafter/shop/gather origins; mixed stacks show breakdown labels and splits preserve origin quantities FIFO. Gathered ores stamp **`Mined by <name>`**; woodcutting stamps **`Felled by <name>`**. Crafted goods stamp a station verb: furnace **`Forged by`**, anvil **`Smithed by`**, woodworking **`Carved by`**, crafting bench **`Assembled by`**. NPC catalog purchases stamp **`Bought from <npc>`**; player-sold resale stock keeps the original origin (not re-stamped as shop). **Get Blank Cheques** tops inventory blanks up to 99; **Return \<n\>** discards free blanks. Blank cheques on the ground can only be picked up until inventory again holds 99; they do not count toward limits on written cheques. **Write Cheque** works anywhere (pick vault goods to reserve; Reserved tab). **Written cheques** can be sent by pigeon, sold on the marketplace, and redeemed at a bank (LMB deposit or **Redeem Cheque**) — redeemed goods go into the **vault**, not inventory. Blank cheques cannot be sent by pigeon or listed on the marketplace. Coins are a physical stackable inventory item (not a separate counter). Character delete voids that character's outstanding cheque reservations back into the vault before inheritance. **NPC shops:** Humanoid spawners (sex, equipment, sells list with optional daily quantity, buysItems, hidden discount) spawn shopkeepers. Context menu **Shop \<name\>** opens a buy panel (grid + sidebar, Buy 1/5/10/x, coin balance, bank-overflow warning). Catalog stock restocks at **00:00 server local time** (quantity 0 = infinite) and remains **ingredient-only** (`npcShopAllowed`). With **Buys items**, the NPC buys **any transferable bag item except blank cheques** (and not coins) at **80%** market; **filled cheques** sell as their reserved goods with a **5% administrative fee** (fee = ceil(5% of payout base); UI shows "`<n> coins charged as administrative fee`" while selected). Limited catalog refills first; extras hold for the day at **120%** resale until restock (non-catalog goods still absorb into bought stock). Prices use `seedValue` (pine log / tin / copper = 5) with market last-sale lerp × discount. **Central Exchange (player marketplace):** Modal with tabs **Your Orders** / **Sell** / **Buy**. Sell picks a bag item (or written cheque treated as its reserved goods with quantity locked), sets min price, and escrows the goods. Buy searches item names (Enter, max 10 hits), sets qty + max price, and escrows coins (coin-filled cheques count as funds but are spent whole only). Placing either order charges a **non-refundable 3% listing fee** (`ceil(unitPrice × quantity × 3%)`, min 1) paid immediately from bag funds. `BlockType.marketplace` wooden counters use **neighbor-connect** autotile states (`0`–`15` from N/E/S/W bitmask; generic in `shared/world/neighborConnect.js`). Counters require adjacency. **Central Exchange staff** spawner (`MobId.centralExchange`) always spawns every clerk from `CENTRAL_EXCHANGE_STAFF` (name + sex) with shared authored equipment; no shop UI. Opening a counter paths an idle clerk to the opposite side when free; closing the UI or walking away from that counter releases the clerk so wander resumes, unless another player is still using the same staff station. Hidden order book: match when `buyerMax >= sellerMin` at deterministic midpoint price; triggering player settles immediately, counterparty gets pigeon→bank cargo plus a staff-signed letter. Open orders auto-cancel after **30 days** with escrow returned to bank by pigeon and an expiry letter (listing fee is not returned). Matches update durable `item_last_sales` for shop/tooltip lerp.
357**Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
357**Code:** `shared/definitions/items.js`, `shared/items/inventory.js`, `shared/items/origin.js`, `shared/items/stackRules.js`, `shared/items/marketplace.js`, `shared/market/exchange.js`, `shared/market/funds.js`, `shared/world/neighborConnect.js`, `shared/shop/pricing.js`, `shared/definitions/mobs.js`, `server/src/shop/service.js`, `server/src/market/service.js`, `server/src/simulation/spawners.js`, `client/src/play/shop.js`, `client/src/play/market.js`, `client/src/editor/tileConfigModal.js`, `server/src/items/bags.js`, `server/src/courier/service.js`, `client/src/play/inventory.js`, `client/assets/blocks/bank/`, `client/assets/blocks/marketplace/`, tests in `server/tests/bank.test.js`, `server/tests/marketplace.test.js`, `server/tests/central-exchange.test.js`, `server/tests/shop.test.js`, `server/tests/origins.test.js`
358
359## Player scripting (AFK / offline)
360
361**Status:** not implemented
362**Spec:** Full language + UI + online/AFK/offline behaviour is documented in [`docs/SCRIPTS.md`](SCRIPTS.md). Scripts are a sandboxed, server-interpreted language that emits normal player intents. Names match **exactly** (case-insensitive). `find` / nearest only searches the **visible 3×3** chunks (what a player sees). `@` variables + `set` hold targets/coords for waypoints; `go` fails beyond **2 chunks** (`Too far away.`). Universal `can <action>` dry-runs any verb. Station/cauldron state is **per player**; station slots never commit items out of the bag until craft/brew succeeds. AFK auto-start after **30 minutes** idle. Death while scripting stops the script and fully logs the instance out. Friends/barber/follow/graphics/editor are out of scope. Architecture hooks remain in design doc §18.
363**Code:** — (planned: `shared/scripts/`, `server/src/scripts/`, `client/src/play/scripts.js`, state DB script rows)
docs/QUESTS.md +8 −6
@@ -1,6 +1,6 @@
1 1 # Quests & NPC dialogue (world editor)
2 2
3 **Status:** not implemented (design only)
3 **Status:** partial (v1 runtime + editors; polish / graph / effects UI later)
4 4 **Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5 5
6 6 Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
@@ -155,10 +155,12 @@ Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
155 155 | Kind | Fields | Meaning |
156 156 |------|--------|---------|
157 157 | `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158 | `atTile` | `tileX`, `tileY` | Exact tile |
159 | `nearTile` | `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range |
160 | `inRect` | `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB |
161 | `atChunk` | `chunkX`, `chunkY` | Player chunk |
158 | `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) |
159 | `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim |
160 | `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim |
161 | `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim |
162 | `inDimension` | `dimensionId` | Currently in that dimension |
163 | `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once |
162 164 | `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
163 165 | `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
164 166 | `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
@@ -169,7 +171,7 @@ Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
169 171 | `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
170 172 | `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
171 173 | `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
172 | `interactBlock` | tile and/or `blockTypeId` | Successful interact (once per quest step) |
174 | `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) |
173 175
174 176 **Notes:**
175 177
@@ -1,6 +1,6 @@
1# Quests & NPC dialogue (world editor)
1# Quests & NPC dialogue (world editor)
2
2
3**Status:** not implemented (design only)
3**Status:** partial (v1 runtime + editors; polish / graph / effects UI later)
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
4**Related:** `docs/FEATURES.md` (Quests, Mob definitions), `docs/SCRIPTS.md` (parity reminder for future script verbs), server authority rules
5
5
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
6Quests and NPC dialogue are **admin-authored content**. Authors create and edit them entirely in the **world editor**. Runtime evaluation is **server-authoritative**; clients only display dialogue UI and quest log snapshots.
@@ -155,10 +155,12 @@ Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
155| Kind | Fields | Meaning |
155| Kind | Fields | Meaning |
156|------|--------|---------|
156|------|--------|---------|
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
157| `hasItem` | `itemId`, `quantity` (≥ 1) | Bag (not vault) has ≥ N |
158| `atTile` | `tileX`, `tileY` | Exact tile |
158| `atTile` | `dimensionId`, `tileX`, `tileY` | Exact tile in that dimension (default `overworld`) |
159| `nearTile` | `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range |
159| `nearTile` | `dimensionId`, `tileX`, `tileY`, `range` (≥ 1) | Chebyshev ≤ range in dim |
160| `inRect` | `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB |
160| `inRect` | `dimensionId`, `minTileX`, `minTileY`, `maxTileX`, `maxTileY` | Inclusive AABB in dim |
161| `atChunk` | `chunkX`, `chunkY` | Player chunk |
161| `atChunk` | `dimensionId`, `chunkX`, `chunkY` | Player chunk in dim |
162| `inDimension` | `dimensionId` | Currently in that dimension |
163| `hasVisitedDimension` | `dimensionId` | Has entered that dim at least once |
162| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
164| `questState` | `questId`, `state` | Equals `not-started` \| `completed` \| number `n` |
163| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
165| `questStepAtLeast` | `questId`, `step` (≥ 1) | Active index ≥ step **or** `completed` |
164| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
166| `dialogueHeard` | `dialogueId`, `stepId` | Heard row exists |
@@ -169,7 +171,7 @@ Editor: condition picker rows with a **NOT** toggle per row; add/remove rows.
169| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
171| `staminaPercentAtLeast` | `percent` (0–100) | currentStamina / maxStamina × 100 ≥ percent |
170| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
172| `skillLevelAtLeast` | `skillId`, `level` (1–99) | `skillLevel(skills, skillId) ≥ level` |
171| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
173| `killCount` | `mobTypeId` **or** `spawnerId`, `count` N | Kills while this quest step active |
172| `interactBlock` | tile and/or `blockTypeId` | Successful interact (once per quest step) |
174| `interactBlock` | `dimensionId`, tile and/or `blockTypeId` | Successful interact (once per quest step) |
173
175
174**Notes:**
176**Notes:**
175
177
server/src/combat/service.js +37 −3
@@ -38,6 +38,7 @@ import { stackQuantity } from "../../../shared/items/inventory.js";
38 38 import { addGroundItem, publicGroundItem } from "../items/bags.js";
39 39 import { resolveItemDualTint } from "../../../shared/render/tint.js";
40 40 import { castMobAttackSpell } from "../spells/mobCast.js";
41 import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
41 42
42 43 export function chebyshev (ax, ay, bx, by)
43 44 {
@@ -225,23 +226,40 @@ function consumeArrow (ecs, handle)
225 226 return true;
226 227 }
227 228
228 function spawnMobDrops (world, targetHandle, tileX, tileY, now)
229 function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null)
229 230 {
230 231 const creature = world.ecs.get(targetHandle, Component.creature);
231 232 if (!creature)
232 233 { return []; }
233 234 const def = mobDefinition(creature.mobTypeId);
235 const mobName = entityCombatDisplayName(world.ecs, targetHandle)
236 || def?.displayName
237 || "a creature";
238 let killerName = "someone";
239 if (attackerId != null)
240 {
241 const attackerHandle = world.ecs.handleOf(attackerId);
242 if (attackerHandle != null)
243 { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; }
244 }
245 const origin = lootOrigin(mobName, killerName);
234 246 const events = [];
235 247 for (const drop of def?.drops ?? [])
236 248 {
237 249 if (Math.random() > (drop.chance ?? 1))
238 250 { continue; }
251 const quantity = drop.quantity ?? 1;
239 252 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
253 const stack = attachOrigins({
254 itemId: drop.itemId,
255 quantity,
256 origins: [{ origin, quantity }]
257 });
240 258 const item = {
241 259 groundItemId,
242 260 tileX,
243 261 tileY,
244 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
262 stack,
245 263 droppedAt: now,
246 264 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
247 265 source: "mob-drop"
@@ -259,6 +277,22 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now)
259 277 return events;
260 278 }
261 279
280 function entityCombatDisplayName (ecs, handle)
281 {
282 const appearance = ecs.get(handle, Component.appearance);
283 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
284 if (fromAppearance)
285 { return fromAppearance; }
286 const creature = ecs.get(handle, Component.creature);
287 if (creature?.mobTypeId)
288 {
289 const def = mobDefinition(creature.mobTypeId);
290 if (def?.displayName)
291 { return def.displayName; }
292 }
293 return null;
294 }
295
262 296 function projectileDualTintFromAttacker (ecs, handle)
263 297 {
264 298 const equipment = ecs.get(handle, Component.equipment);
@@ -1323,7 +1357,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
1323 1357 const creature = world.ecs.get(handle, Component.creature);
1324 1358 const origin = world.ecs.get(handle, Component.spawnOrigin);
1325 1359 const appearance = world.ecs.get(handle, Component.appearance);
1326 events.push(...spawnMobDrops(world, handle, tileX, tileY, now));
1360 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
1327 1361 events.push({
1328 1362 type: "mob-killed",
1329 1363 entityId: targetId,
@@ -38,6 +38,7 @@ import { stackQuantity } from "../../../shared/items/inventory.js";
38import { addGroundItem, publicGroundItem } from "../items/bags.js";
38import { addGroundItem, publicGroundItem } from "../items/bags.js";
39import { resolveItemDualTint } from "../../../shared/render/tint.js";
39import { resolveItemDualTint } from "../../../shared/render/tint.js";
40import { castMobAttackSpell } from "../spells/mobCast.js";
40import { castMobAttackSpell } from "../spells/mobCast.js";
41import { attachOrigins, lootOrigin } from "../../../shared/items/origin.js";
41
42
42export function chebyshev (ax, ay, bx, by)
43export function chebyshev (ax, ay, bx, by)
43{
44{
@@ -225,23 +226,40 @@ function consumeArrow (ecs, handle)
225 return true;
226 return true;
226}
227}
227
228
228function spawnMobDrops (world, targetHandle, tileX, tileY, now)
229function spawnMobDrops (world, targetHandle, tileX, tileY, now, attackerId = null)
229{
230{
230 const creature = world.ecs.get(targetHandle, Component.creature);
231 const creature = world.ecs.get(targetHandle, Component.creature);
231 if (!creature)
232 if (!creature)
232 { return []; }
233 { return []; }
233 const def = mobDefinition(creature.mobTypeId);
234 const def = mobDefinition(creature.mobTypeId);
235 const mobName = entityCombatDisplayName(world.ecs, targetHandle)
236 || def?.displayName
237 || "a creature";
238 let killerName = "someone";
239 if (attackerId != null)
240 {
241 const attackerHandle = world.ecs.handleOf(attackerId);
242 if (attackerHandle != null)
243 { killerName = entityCombatDisplayName(world.ecs, attackerHandle) || "someone"; }
244 }
245 const origin = lootOrigin(mobName, killerName);
234 const events = [];
246 const events = [];
235 for (const drop of def?.drops ?? [])
247 for (const drop of def?.drops ?? [])
236 {
248 {
237 if (Math.random() > (drop.chance ?? 1))
249 if (Math.random() > (drop.chance ?? 1))
238 { continue; }
250 { continue; }
251 const quantity = drop.quantity ?? 1;
239 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
252 const groundItemId = (world.nextGroundItemId = (world.nextGroundItemId ?? 1) + 1);
253 const stack = attachOrigins({
254 itemId: drop.itemId,
255 quantity,
256 origins: [{ origin, quantity }]
257 });
240 const item = {
258 const item = {
241 groundItemId,
259 groundItemId,
242 tileX,
260 tileX,
243 tileY,
261 tileY,
244 stack: { itemId: drop.itemId, quantity: drop.quantity ?? 1 },
262 stack,
245 droppedAt: now,
263 droppedAt: now,
246 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
264 expiresAt: now + (world.settings?.groundItemDespawnDurationMs ?? 600_000),
247 source: "mob-drop"
265 source: "mob-drop"
@@ -259,6 +277,22 @@ function spawnMobDrops (world, targetHandle, tileX, tileY, now)
259 return events;
277 return events;
260}
278}
261
279
280function entityCombatDisplayName (ecs, handle)
281{
282 const appearance = ecs.get(handle, Component.appearance);
283 const fromAppearance = [appearance?.firstName, appearance?.lastName].filter(Boolean).join(" ").trim();
284 if (fromAppearance)
285 { return fromAppearance; }
286 const creature = ecs.get(handle, Component.creature);
287 if (creature?.mobTypeId)
288 {
289 const def = mobDefinition(creature.mobTypeId);
290 if (def?.displayName)
291 { return def.displayName; }
292 }
293 return null;
294}
295
262function projectileDualTintFromAttacker (ecs, handle)
296function projectileDualTintFromAttacker (ecs, handle)
263{
297{
264 const equipment = ecs.get(handle, Component.equipment);
298 const equipment = ecs.get(handle, Component.equipment);
@@ -1323,7 +1357,7 @@ export function finalizeMobKill (world, attackerId, targetId, targetHandle, tile
1323 const creature = world.ecs.get(handle, Component.creature);
1357 const creature = world.ecs.get(handle, Component.creature);
1324 const origin = world.ecs.get(handle, Component.spawnOrigin);
1358 const origin = world.ecs.get(handle, Component.spawnOrigin);
1325 const appearance = world.ecs.get(handle, Component.appearance);
1359 const appearance = world.ecs.get(handle, Component.appearance);
1326 events.push(...spawnMobDrops(world, handle, tileX, tileY, now));
1360 events.push(...spawnMobDrops(world, handle, tileX, tileY, now, attackerId));
1327 events.push({
1361 events.push({
1328 type: "mob-killed",
1362 type: "mob-killed",
1329 entityId: targetId,
1363 entityId: targetId,
server/src/ecs/components.js +9 −0
@@ -1,3 +1,5 @@
1 import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
2
1 3 export const Component = Object.freeze({
2 4 position: "position",
3 5 movement: "movement",
@@ -25,3 +27,10 @@ export const Component = Object.freeze({
25 27 spells: "spells",
26 28 spellcasting: "spellcasting"
27 29 });
30
31 /** Default position component fields (tile coords + dimension). */
32 export const PositionDefault = Object.freeze({
33 tileX: 0,
34 tileY: 0,
35 dimensionId: OVERWORLD_ID
36 });
@@ -1,3 +1,5 @@
1import { OVERWORLD_ID } from "../../../shared/world/dimensions.js";
2
1export const Component = Object.freeze({
3export const Component = Object.freeze({
2 position: "position",
4 position: "position",
3 movement: "movement",
5 movement: "movement",
@@ -25,3 +27,10 @@ export const Component = Object.freeze({
25 spells: "spells",
27 spells: "spells",
26 spellcasting: "spellcasting"
28 spellcasting: "spellcasting"
27});
29});
30
31/** Default position component fields (tile coords + dimension). */
32export const PositionDefault = Object.freeze({
33 tileX: 0,
34 tileY: 0,
35 dimensionId: OVERWORLD_ID
36});
server/src/ecs/serialize.js +11 −0
@@ -1,4 +1,5 @@
1 1 import { Component } from "./components.js";
2 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2 3 import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
3 4 import {
4 5 statusExtraLightRadius,
@@ -13,6 +14,13 @@ import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";
13 14 export function normalizeMobileComponents (components)
14 15 {
15 16 const next = { ...(components ?? {}) };
17 if (next.position && typeof next.position === "object")
18 {
19 next.position = {
20 ...next.position,
21 dimensionId: normalizeDimensionId(next.position.dimensionId ?? OVERWORLD_ID)
22 };
23 }
16 24 if (next.movement && Array.isArray(next.movement.path) && !next.path)
17 25 {
18 26 const { path, ...movement } = next.movement;
@@ -77,6 +85,7 @@ export function publicEntityView (ecs, entityId)
77 85 entityId,
78 86 tileX: position.tileX,
79 87 tileY: position.tileY,
88 dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
80 89 worldX: flight?.x ?? position.tileX + 0.5,
81 90 worldY: flight?.y ?? position.tileY + 0.5,
82 91 gait: movement?.gait ?? "walk",
@@ -88,6 +97,7 @@ export function publicEntityView (ecs, entityId)
88 97 canFight: mob ? mobCanFight(mob) : !!character,
89 98 hostile: !!mob?.hostile,
90 99 talkable: !!mob?.talkable || shopHasInterface(ecs.get(handle, Component.shop)),
100 hasDialogue: !!(ecs.get(handle, Component.spawnOrigin)?.dialogueId),
91 101 hasShop: shopHasInterface(ecs.get(handle, Component.shop)),
92 102 untargetable: !!mob?.untargetable,
93 103 freeFlight: !!mob?.freeFlight,
@@ -130,6 +140,7 @@ export function replicationSpawn (view)
130 140 canFight: !!view.canFight,
131 141 hostile: !!view.hostile,
132 142 talkable: !!view.talkable,
143 hasDialogue: !!view.hasDialogue,
133 144 hasShop: !!view.hasShop,
134 145 untargetable: !!view.untargetable,
135 146 freeFlight: !!view.freeFlight,
@@ -1,4 +1,5 @@
1import { Component } from "./components.js";
1import { Component } from "./components.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
3import { equippedLightRadiusTiles } from "../../../shared/definitions/items.js";
3import {
4import {
4 statusExtraLightRadius,
5 statusExtraLightRadius,
@@ -13,6 +14,13 @@ import { composeAppearanceLayers } from "../../../shared/appearance/hair.js";
13export function normalizeMobileComponents (components)
14export function normalizeMobileComponents (components)
14{
15{
15 const next = { ...(components ?? {}) };
16 const next = { ...(components ?? {}) };
17 if (next.position && typeof next.position === "object")
18 {
19 next.position = {
20 ...next.position,
21 dimensionId: normalizeDimensionId(next.position.dimensionId ?? OVERWORLD_ID)
22 };
23 }
16 if (next.movement && Array.isArray(next.movement.path) && !next.path)
24 if (next.movement && Array.isArray(next.movement.path) && !next.path)
17 {
25 {
18 const { path, ...movement } = next.movement;
26 const { path, ...movement } = next.movement;
@@ -77,6 +85,7 @@ export function publicEntityView (ecs, entityId)
77 entityId,
85 entityId,
78 tileX: position.tileX,
86 tileX: position.tileX,
79 tileY: position.tileY,
87 tileY: position.tileY,
88 dimensionId: normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID),
80 worldX: flight?.x ?? position.tileX + 0.5,
89 worldX: flight?.x ?? position.tileX + 0.5,
81 worldY: flight?.y ?? position.tileY + 0.5,
90 worldY: flight?.y ?? position.tileY + 0.5,
82 gait: movement?.gait ?? "walk",
91 gait: movement?.gait ?? "walk",
@@ -88,6 +97,7 @@ export function publicEntityView (ecs, entityId)
88 canFight: mob ? mobCanFight(mob) : !!character,
97 canFight: mob ? mobCanFight(mob) : !!character,
89 hostile: !!mob?.hostile,
98 hostile: !!mob?.hostile,
90 talkable: !!mob?.talkable || shopHasInterface(ecs.get(handle, Component.shop)),
99 talkable: !!mob?.talkable || shopHasInterface(ecs.get(handle, Component.shop)),
100 hasDialogue: !!(ecs.get(handle, Component.spawnOrigin)?.dialogueId),
91 hasShop: shopHasInterface(ecs.get(handle, Component.shop)),
101 hasShop: shopHasInterface(ecs.get(handle, Component.shop)),
92 untargetable: !!mob?.untargetable,
102 untargetable: !!mob?.untargetable,
93 freeFlight: !!mob?.freeFlight,
103 freeFlight: !!mob?.freeFlight,
@@ -130,6 +140,7 @@ export function replicationSpawn (view)
130 canFight: !!view.canFight,
140 canFight: !!view.canFight,
131 hostile: !!view.hostile,
141 hostile: !!view.hostile,
132 talkable: !!view.talkable,
142 talkable: !!view.talkable,
143 hasDialogue: !!view.hasDialogue,
133 hasShop: !!view.hasShop,
144 hasShop: !!view.hasShop,
134 untargetable: !!view.untargetable,
145 untargetable: !!view.untargetable,
135 freeFlight: !!view.freeFlight,
146 freeFlight: !!view.freeFlight,
server/src/editor/service.js +337 −18
@@ -14,6 +14,16 @@ import {
14 14 starterLoadoutsEqual,
15 15 diffStarterLoadout
16 16 } from "../../../shared/items/starterLoadout.js";
17 import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
18 import {
19 OVERWORLD_ID,
20 normalizeDimensionId,
21 normalizeDimensionRecord,
22 defaultDimensionRecord,
23 isOverworld,
24 normalizeLightingMode,
25 normalizeSeasonMode
26 } from "../../../shared/world/dimensions.js";
17 27
18 28 export class EditorService
19 29 {
@@ -22,24 +32,37 @@ export class EditorService
22 32 this.worldDb = worldDb;
23 33 }
24 34
25 loadChunk (chunkX, chunkY)
35 #defaultGroundForDimension (dimensionId, revisionId = null)
36 {
37 const rev = revisionId ?? this.worldDb.getEditorRevisionId();
38 const dimId = normalizeDimensionId(dimensionId);
39 const settings = this.worldDb.getLiveSettings();
40 const record = this.worldDb.getDimension(rev, dimId)
41 ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId });
42 return record.defaultGroundTypeId;
43 }
44
45 loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
26 46 {
47 const dimId = normalizeDimensionId(dimensionId);
27 48 const revisionId = this.worldDb.getEditorRevisionId();
28 49 const settings = this.worldDb.getLiveSettings();
29 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
50 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId);
51 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
30 52 const data = row
31 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY)
32 : createEmptyChunkData(settings.defaultGroundTypeId);
53 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
54 : createEmptyChunkData(defaultGroundTypeId);
33 55 const isOpen = (x, y) =>
34 56 {
35 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
57 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId);
36 58 if (!neighbor)
37 59 { return false; }
38 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open;
60 return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open;
39 61 };
40 62 return {
41 63 chunkX,
42 64 chunkY,
65 dimensionId: dimId,
43 66 revisionId,
44 67 pendingRevisionId: this.worldDb.getPendingRevisionId(),
45 68 activeRevisionId: this.worldDb.getActiveRevisionId(),
@@ -47,36 +70,39 @@ export class EditorService
47 70 settings,
48 71 data,
49 72 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
50 changelog: this.worldDb.listChangelog(chunkX, chunkY)
73 changelog: this.worldDb.listChangelog(chunkX, chunkY, dimId)
51 74 };
52 75 }
53 76
54 saveChunk (chunkX, chunkY, draft, editorAdminId)
77 saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID)
55 78 {
56 const previous = this.loadChunk(chunkX, chunkY);
79 const dimId = normalizeDimensionId(dimensionId);
80 const previous = this.loadChunk(chunkX, chunkY, dimId);
57 81 const next = cloneChunkData(previous.data);
58 const settings = previous.settings ?? this.worldDb.getLiveSettings();
82 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId);
59 83 next.open = !!draft.open;
60 84 if (Array.isArray(draft.grounds))
61 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
85 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); }
62 86 if (Array.isArray(draft.blocks))
63 87 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
64 88 if (Array.isArray(draft.spawners))
65 89 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
66 90
91 this.validateSpawnerDialogues(chunkX, chunkY, next.spawners);
92
67 93 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
68 94 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
69 95 const baked = bakeLightMaps(
70 96 chunkX,
71 97 chunkY,
72 (x, y) => this.#loadForBake(x, y, revisionId, settings.defaultGroundTypeId, chunkX, chunkY, next),
98 (x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),
73 99 maxDefinitionLightRange(BLOCK_DEFINITIONS)
74 100 );
75 101
76 102 for (const result of baked)
77 103 {
78 104 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
79 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId)
105 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
80 106 || result.data.light.some((value) => value > 0);
81 107
82 108 if (!shouldStore)
@@ -87,14 +113,122 @@ export class EditorService
87 113 result.chunkY,
88 114 revisionId,
89 115 result.data.open ? 1 : 0,
90 encodeChunkBlob(result.data)
116 encodeChunkBlob(result.data),
117 dimId
91 118 );
92 119 }
93 120
94 121 if (diffEntries.length > 0)
95 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries); }
122 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); }
96 123
97 return this.loadChunk(chunkX, chunkY);
124 return this.loadChunk(chunkX, chunkY, dimId);
125 }
126
127 listDimensions ()
128 {
129 const revisionId = this.worldDb.getEditorRevisionId();
130 return {
131 revisionId,
132 pendingRevisionId: this.worldDb.getPendingRevisionId(),
133 activeRevisionId: this.worldDb.getActiveRevisionId(),
134 dimensions: this.worldDb.listDimensions(revisionId)
135 };
136 }
137
138 createDimension (rawId, displayName, editorAdminId)
139 {
140 const trimmed = String(rawId ?? "").trim();
141 if (!trimmed)
142 {
143 const err = new Error("Dimension id is required.");
144 err.userFacing = true;
145 throw err;
146 }
147 const dimensionId = normalizeDimensionId(trimmed);
148 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
149 if (this.worldDb.getDimension(revisionId, dimensionId))
150 {
151 const err = new Error(`Dimension "${dimensionId}" already exists.`);
152 err.userFacing = true;
153 throw err;
154 }
155 const settings = this.worldDb.getLiveSettings();
156 const record = defaultDimensionRecord(dimensionId, {
157 displayName: displayName != null && String(displayName).trim()
158 ? String(displayName).trim()
159 : dimensionId,
160 defaultGroundTypeId: settings.defaultGroundTypeId
161 });
162 this.worldDb.saveDimension(revisionId, record);
163 return this.listDimensions();
164 }
165
166 saveDimension (raw, editorAdminId)
167 {
168 if (!raw || typeof raw !== "object")
169 {
170 const err = new Error("Dimension payload required.");
171 err.userFacing = true;
172 throw err;
173 }
174 const dimensionId = normalizeDimensionId(raw.dimensionId);
175 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
176 const settings = this.worldDb.getLiveSettings();
177 const existing = this.worldDb.getDimension(revisionId, dimensionId)
178 ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId });
179 const next = normalizeDimensionRecord({
180 ...existing,
181 displayName: Object.prototype.hasOwnProperty.call(raw, "displayName")
182 ? raw.displayName
183 : existing.displayName,
184 lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode")
185 ? normalizeLightingMode(raw.lightingMode)
186 : existing.lightingMode,
187 seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode")
188 ? normalizeSeasonMode(raw.seasonMode)
189 : existing.seasonMode,
190 defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId")
191 ? raw.defaultGroundTypeId
192 : existing.defaultGroundTypeId,
193 deletedAt: existing.deletedAt,
194 purgeAfter: existing.purgeAfter
195 });
196 this.worldDb.saveDimension(revisionId, next);
197 return this.listDimensions();
198 }
199
200 softDeleteDimension (dimensionId, editorAdminId)
201 {
202 const id = normalizeDimensionId(dimensionId);
203 if (isOverworld(id))
204 {
205 const err = new Error("Cannot delete overworld.");
206 err.userFacing = true;
207 throw err;
208 }
209 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
210 const result = this.worldDb.softDeleteDimension(revisionId, id);
211 if (!result.ok)
212 {
213 const err = new Error(result.error ?? "Delete failed.");
214 err.userFacing = true;
215 throw err;
216 }
217 return this.listDimensions();
218 }
219
220 cancelDimensionDeletion (dimensionId, editorAdminId)
221 {
222 const id = normalizeDimensionId(dimensionId);
223 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
224 const result = this.worldDb.cancelDimensionDeletion(revisionId, id);
225 if (!result.ok)
226 {
227 const err = new Error(result.error ?? "Cancel failed.");
228 err.userFacing = true;
229 throw err;
230 }
231 return this.listDimensions();
98 232 }
99 233
100 234 loadSettings ()
@@ -213,12 +347,197 @@ export class EditorService
213 347 };
214 348 }
215 349
216 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData)
350 loadQuests ()
351 {
352 const revisionId = this.worldDb.getEditorRevisionId();
353 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
354 return {
355 revisionId,
356 pendingRevisionId: this.worldDb.getPendingRevisionId(),
357 activeRevisionId: this.worldDb.getActiveRevisionId(),
358 quests
359 };
360 }
361
362 saveQuest (raw, editorAdminId)
363 {
364 const def = normalizeQuestDef(raw);
365 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
366 this.worldDb.saveQuestDef(revisionId, def);
367 return this.loadQuests();
368 }
369
370 deleteQuest (questId, editorAdminId)
371 {
372 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
373 this.worldDb.deleteQuestDef(revisionId, String(questId));
374 return this.loadQuests();
375 }
376
377 loadDialogues ()
378 {
379 const revisionId = this.worldDb.getEditorRevisionId();
380 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
381 const assignmentCounts = this.#countDialogueAssignments(revisionId);
382 return {
383 revisionId,
384 pendingRevisionId: this.worldDb.getPendingRevisionId(),
385 activeRevisionId: this.worldDb.getActiveRevisionId(),
386 dialogues: trees.map((tree) => ({
387 ...tree,
388 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
389 }))
390 };
391 }
392
393 saveDialogue (raw, editorAdminId)
394 {
395 const tree = normalizeDialogueTree(raw);
396 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
397 const assignmentCounts = this.#countDialogueAssignments(revisionId);
398 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
399 if (tree.unique && assigned > 1)
400 {
401 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
402 err.userFacing = true;
403 throw err;
404 }
405 if (tree.unique && assigned === 1)
406 {
407 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
408 if (violation)
409 {
410 const err = new Error(violation);
411 err.userFacing = true;
412 throw err;
413 }
414 }
415 this.worldDb.saveDialogueTree(revisionId, tree);
416 return this.loadDialogues();
417 }
418
419 deleteDialogue (dialogueId, editorAdminId)
420 {
421 const id = String(dialogueId);
422 const revisionId = this.worldDb.getEditorRevisionId();
423 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
424 if (assigned > 0)
425 {
426 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
427 err.userFacing = true;
428 throw err;
429 }
430 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
431 this.worldDb.deleteDialogueTree(pendingId, id);
432 return this.loadDialogues();
433 }
434
435 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
436 validateSpawnerDialogues (chunkX, chunkY, spawners)
437 {
438 const revisionId = this.worldDb.getEditorRevisionId();
439 const trees = new Map(
440 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
441 {
442 const tree = normalizeDialogueTree(raw);
443 return [tree.dialogueId, tree];
444 })
445 );
446 for (const entry of spawners ?? [])
447 {
448 const dialogueId = entry?.config?.dialogueId;
449 if (!dialogueId)
450 { continue; }
451 const tree = trees.get(dialogueId);
452 if (!tree)
453 {
454 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
455 err.userFacing = true;
456 throw err;
457 }
458 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
459 {
460 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
461 err.userFacing = true;
462 throw err;
463 }
464 }
465 const counts = this.#countDialogueAssignments(revisionId, { chunkX, chunkY, spawners });
466 for (const [dialogueId, tree] of trees)
467 {
468 const n = counts.get(dialogueId) ?? 0;
469 if (tree.unique && n > 1)
470 {
471 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
472 err.userFacing = true;
473 throw err;
474 }
475 }
476 }
477
478 #countDialogueAssignments (revisionId, replaceChunk = null)
479 {
480 const settings = this.worldDb.getLiveSettings();
481 const counts = new Map();
482 const coords = this.worldDb.listChunkCoords(revisionId);
483 for (const { chunk_x: cx, chunk_y: cy } of coords)
484 {
485 if (replaceChunk && cx === replaceChunk.chunkX && cy === replaceChunk.chunkY)
486 { continue; }
487 const row = this.worldDb.getChunkVersion(cx, cy, revisionId);
488 if (!row)
489 { continue; }
490 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
491 for (const entry of data.spawners ?? [])
492 {
493 const id = entry?.config?.dialogueId;
494 if (!id)
495 { continue; }
496 counts.set(id, (counts.get(id) ?? 0) + 1);
497 }
498 }
499 if (replaceChunk?.spawners)
500 {
501 for (const entry of replaceChunk.spawners)
502 {
503 const id = entry?.config?.dialogueId;
504 if (!id)
505 { continue; }
506 counts.set(id, (counts.get(id) ?? 0) + 1);
507 }
508 }
509 return counts;
510 }
511
512 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
513 {
514 const settings = this.worldDb.getLiveSettings();
515 const coords = this.worldDb.listChunkCoords(revisionId);
516 for (const { chunk_x: chunkX, chunk_y: chunkY } of coords)
517 {
518 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
519 if (!row)
520 { continue; }
521 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
522 for (const entry of data.spawners ?? [])
523 {
524 if (entry?.config?.dialogueId !== dialogueId)
525 { continue; }
526 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
527 if (maxAlive !== 1)
528 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
529 }
530 }
531 return null;
532 }
533
534 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
217 535 {
218 536 if (chunkX === savedX && chunkY === savedY)
219 537 { return savedData; }
220 538
221 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
539 const dimId = normalizeDimensionId(dimensionId);
540 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
222 541 return row
223 542 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
224 543 : createEmptyChunkData(defaultGroundTypeId);
@@ -14,6 +14,16 @@ import {
14 starterLoadoutsEqual,
14 starterLoadoutsEqual,
15 diffStarterLoadout
15 diffStarterLoadout
16} from "../../../shared/items/starterLoadout.js";
16} from "../../../shared/items/starterLoadout.js";
17import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
18import {
19 OVERWORLD_ID,
20 normalizeDimensionId,
21 normalizeDimensionRecord,
22 defaultDimensionRecord,
23 isOverworld,
24 normalizeLightingMode,
25 normalizeSeasonMode
26} from "../../../shared/world/dimensions.js";
17
27
18export class EditorService
28export class EditorService
19{
29{
@@ -22,24 +32,37 @@ export class EditorService
22 this.worldDb = worldDb;
32 this.worldDb = worldDb;
23 }
33 }
24
34
25 loadChunk (chunkX, chunkY)
35 #defaultGroundForDimension (dimensionId, revisionId = null)
36 {
37 const rev = revisionId ?? this.worldDb.getEditorRevisionId();
38 const dimId = normalizeDimensionId(dimensionId);
39 const settings = this.worldDb.getLiveSettings();
40 const record = this.worldDb.getDimension(rev, dimId)
41 ?? defaultDimensionRecord(dimId, { defaultGroundTypeId: settings.defaultGroundTypeId });
42 return record.defaultGroundTypeId;
43 }
44
45 loadChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
26 {
46 {
47 const dimId = normalizeDimensionId(dimensionId);
27 const revisionId = this.worldDb.getEditorRevisionId();
48 const revisionId = this.worldDb.getEditorRevisionId();
28 const settings = this.worldDb.getLiveSettings();
49 const settings = this.worldDb.getLiveSettings();
29 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
50 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId, revisionId);
51 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
30 const data = row
52 const data = row
31 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY)
53 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
32 : createEmptyChunkData(settings.defaultGroundTypeId);
54 : createEmptyChunkData(defaultGroundTypeId);
33 const isOpen = (x, y) =>
55 const isOpen = (x, y) =>
34 {
56 {
35 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId);
57 const neighbor = this.worldDb.getChunkVersion(x, y, revisionId, dimId);
36 if (!neighbor)
58 if (!neighbor)
37 { return false; }
59 { return false; }
38 return !!decodeChunkBlob(neighbor.data_blob, settings.defaultGroundTypeId, x, y).open;
60 return !!decodeChunkBlob(neighbor.data_blob, defaultGroundTypeId, x, y).open;
39 };
61 };
40 return {
62 return {
41 chunkX,
63 chunkX,
42 chunkY,
64 chunkY,
65 dimensionId: dimId,
43 revisionId,
66 revisionId,
44 pendingRevisionId: this.worldDb.getPendingRevisionId(),
67 pendingRevisionId: this.worldDb.getPendingRevisionId(),
45 activeRevisionId: this.worldDb.getActiveRevisionId(),
68 activeRevisionId: this.worldDb.getActiveRevisionId(),
@@ -47,36 +70,39 @@ export class EditorService
47 settings,
70 settings,
48 data,
71 data,
49 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
72 closedEdges: closedNeighborEdges(chunkX, chunkY, isOpen),
50 changelog: this.worldDb.listChangelog(chunkX, chunkY)
73 changelog: this.worldDb.listChangelog(chunkX, chunkY, dimId)
51 };
74 };
52 }
75 }
53
76
54 saveChunk (chunkX, chunkY, draft, editorAdminId)
77 saveChunk (chunkX, chunkY, draft, editorAdminId, dimensionId = OVERWORLD_ID)
55 {
78 {
56 const previous = this.loadChunk(chunkX, chunkY);
79 const dimId = normalizeDimensionId(dimensionId);
80 const previous = this.loadChunk(chunkX, chunkY, dimId);
57 const next = cloneChunkData(previous.data);
81 const next = cloneChunkData(previous.data);
58 const settings = previous.settings ?? this.worldDb.getLiveSettings();
82 const defaultGroundTypeId = this.#defaultGroundForDimension(dimId);
59 next.open = !!draft.open;
83 next.open = !!draft.open;
60 if (Array.isArray(draft.grounds))
84 if (Array.isArray(draft.grounds))
61 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
85 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, defaultGroundTypeId)); }
62 if (Array.isArray(draft.blocks))
86 if (Array.isArray(draft.blocks))
63 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
87 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
64 if (Array.isArray(draft.spawners))
88 if (Array.isArray(draft.spawners))
65 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
89 { next.spawners = draft.spawners.map((entry) => normalizeSpawner(entry)).filter(Boolean); }
66
90
91 this.validateSpawnerDialogues(chunkX, chunkY, next.spawners);
92
67 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
93 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
68 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
94 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
69 const baked = bakeLightMaps(
95 const baked = bakeLightMaps(
70 chunkX,
96 chunkX,
71 chunkY,
97 chunkY,
72 (x, y) => this.#loadForBake(x, y, revisionId, settings.defaultGroundTypeId, chunkX, chunkY, next),
98 (x, y) => this.#loadForBake(x, y, revisionId, defaultGroundTypeId, chunkX, chunkY, next, dimId),
73 maxDefinitionLightRange(BLOCK_DEFINITIONS)
99 maxDefinitionLightRange(BLOCK_DEFINITIONS)
74 );
100 );
75
101
76 for (const result of baked)
102 for (const result of baked)
77 {
103 {
78 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
104 const shouldStore = result.chunkX === chunkX && result.chunkY === chunkY
79 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId)
105 || this.worldDb.getChunkVersion(result.chunkX, result.chunkY, revisionId, dimId)
80 || result.data.light.some((value) => value > 0);
106 || result.data.light.some((value) => value > 0);
81
107
82 if (!shouldStore)
108 if (!shouldStore)
@@ -87,14 +113,122 @@ export class EditorService
87 result.chunkY,
113 result.chunkY,
88 revisionId,
114 revisionId,
89 result.data.open ? 1 : 0,
115 result.data.open ? 1 : 0,
90 encodeChunkBlob(result.data)
116 encodeChunkBlob(result.data),
117 dimId
91 );
118 );
92 }
119 }
93
120
94 if (diffEntries.length > 0)
121 if (diffEntries.length > 0)
95 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries); }
122 { this.worldDb.appendChangelog(chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimId); }
96
123
97 return this.loadChunk(chunkX, chunkY);
124 return this.loadChunk(chunkX, chunkY, dimId);
125 }
126
127 listDimensions ()
128 {
129 const revisionId = this.worldDb.getEditorRevisionId();
130 return {
131 revisionId,
132 pendingRevisionId: this.worldDb.getPendingRevisionId(),
133 activeRevisionId: this.worldDb.getActiveRevisionId(),
134 dimensions: this.worldDb.listDimensions(revisionId)
135 };
136 }
137
138 createDimension (rawId, displayName, editorAdminId)
139 {
140 const trimmed = String(rawId ?? "").trim();
141 if (!trimmed)
142 {
143 const err = new Error("Dimension id is required.");
144 err.userFacing = true;
145 throw err;
146 }
147 const dimensionId = normalizeDimensionId(trimmed);
148 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
149 if (this.worldDb.getDimension(revisionId, dimensionId))
150 {
151 const err = new Error(`Dimension "${dimensionId}" already exists.`);
152 err.userFacing = true;
153 throw err;
154 }
155 const settings = this.worldDb.getLiveSettings();
156 const record = defaultDimensionRecord(dimensionId, {
157 displayName: displayName != null && String(displayName).trim()
158 ? String(displayName).trim()
159 : dimensionId,
160 defaultGroundTypeId: settings.defaultGroundTypeId
161 });
162 this.worldDb.saveDimension(revisionId, record);
163 return this.listDimensions();
164 }
165
166 saveDimension (raw, editorAdminId)
167 {
168 if (!raw || typeof raw !== "object")
169 {
170 const err = new Error("Dimension payload required.");
171 err.userFacing = true;
172 throw err;
173 }
174 const dimensionId = normalizeDimensionId(raw.dimensionId);
175 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
176 const settings = this.worldDb.getLiveSettings();
177 const existing = this.worldDb.getDimension(revisionId, dimensionId)
178 ?? defaultDimensionRecord(dimensionId, { defaultGroundTypeId: settings.defaultGroundTypeId });
179 const next = normalizeDimensionRecord({
180 ...existing,
181 displayName: Object.prototype.hasOwnProperty.call(raw, "displayName")
182 ? raw.displayName
183 : existing.displayName,
184 lightingMode: Object.prototype.hasOwnProperty.call(raw, "lightingMode")
185 ? normalizeLightingMode(raw.lightingMode)
186 : existing.lightingMode,
187 seasonMode: Object.prototype.hasOwnProperty.call(raw, "seasonMode")
188 ? normalizeSeasonMode(raw.seasonMode)
189 : existing.seasonMode,
190 defaultGroundTypeId: Object.prototype.hasOwnProperty.call(raw, "defaultGroundTypeId")
191 ? raw.defaultGroundTypeId
192 : existing.defaultGroundTypeId,
193 deletedAt: existing.deletedAt,
194 purgeAfter: existing.purgeAfter
195 });
196 this.worldDb.saveDimension(revisionId, next);
197 return this.listDimensions();
198 }
199
200 softDeleteDimension (dimensionId, editorAdminId)
201 {
202 const id = normalizeDimensionId(dimensionId);
203 if (isOverworld(id))
204 {
205 const err = new Error("Cannot delete overworld.");
206 err.userFacing = true;
207 throw err;
208 }
209 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
210 const result = this.worldDb.softDeleteDimension(revisionId, id);
211 if (!result.ok)
212 {
213 const err = new Error(result.error ?? "Delete failed.");
214 err.userFacing = true;
215 throw err;
216 }
217 return this.listDimensions();
218 }
219
220 cancelDimensionDeletion (dimensionId, editorAdminId)
221 {
222 const id = normalizeDimensionId(dimensionId);
223 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
224 const result = this.worldDb.cancelDimensionDeletion(revisionId, id);
225 if (!result.ok)
226 {
227 const err = new Error(result.error ?? "Cancel failed.");
228 err.userFacing = true;
229 throw err;
230 }
231 return this.listDimensions();
98 }
232 }
99
233
100 loadSettings ()
234 loadSettings ()
@@ -213,12 +347,197 @@ export class EditorService
213 };
347 };
214 }
348 }
215
349
216 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData)
350 loadQuests ()
351 {
352 const revisionId = this.worldDb.getEditorRevisionId();
353 const quests = this.worldDb.listQuestDefs(revisionId).map((raw) => normalizeQuestDef(raw));
354 return {
355 revisionId,
356 pendingRevisionId: this.worldDb.getPendingRevisionId(),
357 activeRevisionId: this.worldDb.getActiveRevisionId(),
358 quests
359 };
360 }
361
362 saveQuest (raw, editorAdminId)
363 {
364 const def = normalizeQuestDef(raw);
365 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
366 this.worldDb.saveQuestDef(revisionId, def);
367 return this.loadQuests();
368 }
369
370 deleteQuest (questId, editorAdminId)
371 {
372 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
373 this.worldDb.deleteQuestDef(revisionId, String(questId));
374 return this.loadQuests();
375 }
376
377 loadDialogues ()
378 {
379 const revisionId = this.worldDb.getEditorRevisionId();
380 const trees = this.worldDb.listDialogueTrees(revisionId).map((raw) => normalizeDialogueTree(raw));
381 const assignmentCounts = this.#countDialogueAssignments(revisionId);
382 return {
383 revisionId,
384 pendingRevisionId: this.worldDb.getPendingRevisionId(),
385 activeRevisionId: this.worldDb.getActiveRevisionId(),
386 dialogues: trees.map((tree) => ({
387 ...tree,
388 assignedSpawnerCount: assignmentCounts.get(tree.dialogueId) ?? 0
389 }))
390 };
391 }
392
393 saveDialogue (raw, editorAdminId)
394 {
395 const tree = normalizeDialogueTree(raw);
396 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
397 const assignmentCounts = this.#countDialogueAssignments(revisionId);
398 const assigned = assignmentCounts.get(tree.dialogueId) ?? 0;
399 if (tree.unique && assigned > 1)
400 {
401 const err = new Error("Unique dialogue can be assigned to at most one spawner.");
402 err.userFacing = true;
403 throw err;
404 }
405 if (tree.unique && assigned === 1)
406 {
407 const violation = this.#uniqueDialogueMaxAliveViolation(revisionId, tree.dialogueId);
408 if (violation)
409 {
410 const err = new Error(violation);
411 err.userFacing = true;
412 throw err;
413 }
414 }
415 this.worldDb.saveDialogueTree(revisionId, tree);
416 return this.loadDialogues();
417 }
418
419 deleteDialogue (dialogueId, editorAdminId)
420 {
421 const id = String(dialogueId);
422 const revisionId = this.worldDb.getEditorRevisionId();
423 const assigned = this.#countDialogueAssignments(revisionId).get(id) ?? 0;
424 if (assigned > 0)
425 {
426 const err = new Error(`Dialogue is still assigned to ${assigned} spawner(s). Unassign first.`);
427 err.userFacing = true;
428 throw err;
429 }
430 const pendingId = this.worldDb.ensurePendingRevision(editorAdminId);
431 this.worldDb.deleteDialogueTree(pendingId, id);
432 return this.loadDialogues();
433 }
434
435 /** Validate dialogueId / unique / maxAlive when saving a chunk's spawners. */
436 validateSpawnerDialogues (chunkX, chunkY, spawners)
437 {
438 const revisionId = this.worldDb.getEditorRevisionId();
439 const trees = new Map(
440 this.worldDb.listDialogueTrees(revisionId).map((raw) =>
441 {
442 const tree = normalizeDialogueTree(raw);
443 return [tree.dialogueId, tree];
444 })
445 );
446 for (const entry of spawners ?? [])
447 {
448 const dialogueId = entry?.config?.dialogueId;
449 if (!dialogueId)
450 { continue; }
451 const tree = trees.get(dialogueId);
452 if (!tree)
453 {
454 const err = new Error(`Unknown dialogue "${dialogueId}" on a spawner.`);
455 err.userFacing = true;
456 throw err;
457 }
458 if (tree.unique && (Math.max(1, Number(entry.config.maxAlive) || 1) !== 1))
459 {
460 const err = new Error(`Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`);
461 err.userFacing = true;
462 throw err;
463 }
464 }
465 const counts = this.#countDialogueAssignments(revisionId, { chunkX, chunkY, spawners });
466 for (const [dialogueId, tree] of trees)
467 {
468 const n = counts.get(dialogueId) ?? 0;
469 if (tree.unique && n > 1)
470 {
471 const err = new Error(`Unique dialogue "${dialogueId}" would be on ${n} spawners.`);
472 err.userFacing = true;
473 throw err;
474 }
475 }
476 }
477
478 #countDialogueAssignments (revisionId, replaceChunk = null)
479 {
480 const settings = this.worldDb.getLiveSettings();
481 const counts = new Map();
482 const coords = this.worldDb.listChunkCoords(revisionId);
483 for (const { chunk_x: cx, chunk_y: cy } of coords)
484 {
485 if (replaceChunk && cx === replaceChunk.chunkX && cy === replaceChunk.chunkY)
486 { continue; }
487 const row = this.worldDb.getChunkVersion(cx, cy, revisionId);
488 if (!row)
489 { continue; }
490 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, cx, cy);
491 for (const entry of data.spawners ?? [])
492 {
493 const id = entry?.config?.dialogueId;
494 if (!id)
495 { continue; }
496 counts.set(id, (counts.get(id) ?? 0) + 1);
497 }
498 }
499 if (replaceChunk?.spawners)
500 {
501 for (const entry of replaceChunk.spawners)
502 {
503 const id = entry?.config?.dialogueId;
504 if (!id)
505 { continue; }
506 counts.set(id, (counts.get(id) ?? 0) + 1);
507 }
508 }
509 return counts;
510 }
511
512 #uniqueDialogueMaxAliveViolation (revisionId, dialogueId)
513 {
514 const settings = this.worldDb.getLiveSettings();
515 const coords = this.worldDb.listChunkCoords(revisionId);
516 for (const { chunk_x: chunkX, chunk_y: chunkY } of coords)
517 {
518 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
519 if (!row)
520 { continue; }
521 const data = decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId, chunkX, chunkY);
522 for (const entry of data.spawners ?? [])
523 {
524 if (entry?.config?.dialogueId !== dialogueId)
525 { continue; }
526 const maxAlive = Math.max(1, Number(entry.config.maxAlive) || 1);
527 if (maxAlive !== 1)
528 { return `Unique dialogue "${dialogueId}" requires spawner maxAlive = 1.`; }
529 }
530 }
531 return null;
532 }
533
534 #loadForBake (chunkX, chunkY, revisionId, defaultGroundTypeId, savedX, savedY, savedData, dimensionId = OVERWORLD_ID)
217 {
535 {
218 if (chunkX === savedX && chunkY === savedY)
536 if (chunkX === savedX && chunkY === savedY)
219 { return savedData; }
537 { return savedData; }
220
538
221 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
539 const dimId = normalizeDimensionId(dimensionId);
540 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId, dimId);
222 return row
541 return row
223 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
542 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
224 : createEmptyChunkData(defaultGroundTypeId);
543 : createEmptyChunkData(defaultGroundTypeId);
server/src/gateway/websocket.js +249 −11
@@ -1,11 +1,12 @@
1 1 import { WebSocketServer } from "ws";
2 2 import { MessageType, GAIT } from "../../../shared/protocol/constants.js";
3 import { chunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
3 import { chunkKey, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4 4 import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5 5 import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
6 6 import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
7 7 import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
8 8 import { publicSkillsView } from "../../../shared/skills/state.js";
9 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
9 10
10 11 let nextSessionId = 1;
11 12
@@ -216,6 +217,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
216 217 characterId: session.characterId
217 218 });
218 219 break;
220 case MessageType.enterDoorway:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "enter-doorway",
224 characterId: session.characterId,
225 tileX: message.tileX | 0,
226 tileY: message.tileY | 0
227 });
228 break;
219 229 case MessageType.openBounty:
220 230 requirePlaying(session);
221 231 simulation.enqueue(session.id, {
@@ -581,7 +591,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
581 591 simulation.enqueue(session.id, {
582 592 type: "interact",
583 593 characterId: session.characterId,
584 targetEntityId: message.targetEntityId | 0
594 targetEntityId: message.targetEntityId | 0,
595 purpose: message.purpose === "shop" || message.purpose === "talk"
596 ? message.purpose
597 : null
585 598 });
586 599 break;
587 600 case MessageType.buyFromShop:
@@ -726,13 +739,54 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
726 739 break;
727 740 case MessageType.editorLoadChunk:
728 741 requireAdmin(session);
729 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
742 send(session, {
743 type: MessageType.editorChunk,
744 ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0, message.dimensionId)
745 });
730 746 break;
731 747 case MessageType.editorSaveChunk:
732 748 requireAdmin(session);
733 749 send(session, {
734 750 type: MessageType.editorChunk,
735 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
751 ...editor.saveChunk(
752 message.chunkX | 0,
753 message.chunkY | 0,
754 message.draft,
755 session.authSubject,
756 message.dimensionId
757 )
758 });
759 break;
760 case MessageType.editorListDimensions:
761 requireAdmin(session);
762 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
763 break;
764 case MessageType.editorCreateDimension:
765 requireAdmin(session);
766 send(session, {
767 type: MessageType.editorDimensions,
768 ...editor.createDimension(message.dimensionId, message.displayName, session.authSubject)
769 });
770 break;
771 case MessageType.editorSaveDimension:
772 requireAdmin(session);
773 send(session, {
774 type: MessageType.editorDimensions,
775 ...editor.saveDimension(message.dimension ?? message, session.authSubject)
776 });
777 break;
778 case MessageType.editorSoftDeleteDimension:
779 requireAdmin(session);
780 send(session, {
781 type: MessageType.editorDimensions,
782 ...editor.softDeleteDimension(message.dimensionId, session.authSubject)
783 });
784 break;
785 case MessageType.editorCancelDimensionDeletion:
786 requireAdmin(session);
787 send(session, {
788 type: MessageType.editorDimensions,
789 ...editor.cancelDimensionDeletion(message.dimensionId, session.authSubject)
736 790 });
737 791 break;
738 792 case MessageType.editorLoadSettings:
@@ -775,6 +829,71 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
775 829 });
776 830 }
777 831 break;
832 case MessageType.editorLoadQuests:
833 requireAdmin(session);
834 send(session, { type: MessageType.editorQuests, ...editor.loadQuests() });
835 break;
836 case MessageType.editorSaveQuest:
837 requireAdmin(session);
838 send(session, {
839 type: MessageType.editorQuests,
840 ...editor.saveQuest(message.quest ?? message, session.authSubject)
841 });
842 break;
843 case MessageType.editorDeleteQuest:
844 requireAdmin(session);
845 send(session, {
846 type: MessageType.editorQuests,
847 ...editor.deleteQuest(message.questId, session.authSubject)
848 });
849 break;
850 case MessageType.editorLoadDialogues:
851 requireAdmin(session);
852 send(session, { type: MessageType.editorDialogues, ...editor.loadDialogues() });
853 break;
854 case MessageType.editorSaveDialogue:
855 requireAdmin(session);
856 send(session, {
857 type: MessageType.editorDialogues,
858 ...editor.saveDialogue(message.dialogue ?? message, session.authSubject)
859 });
860 break;
861 case MessageType.editorDeleteDialogue:
862 requireAdmin(session);
863 send(session, {
864 type: MessageType.editorDialogues,
865 ...editor.deleteDialogue(message.dialogueId, session.authSubject)
866 });
867 break;
868 case MessageType.dialogueChoose:
869 requirePlaying(session);
870 simulation.enqueue(session.id, {
871 type: "dialogue-choose",
872 characterId: session.characterId,
873 trigger: String(message.trigger ?? "")
874 });
875 break;
876 case MessageType.dialogueAdvance:
877 requirePlaying(session);
878 simulation.enqueue(session.id, {
879 type: "dialogue-advance",
880 characterId: session.characterId
881 });
882 break;
883 case MessageType.closeDialogue:
884 requirePlaying(session);
885 simulation.enqueue(session.id, {
886 type: "close-dialogue",
887 characterId: session.characterId
888 });
889 break;
890 case MessageType.requestQuests:
891 requirePlaying(session);
892 simulation.enqueue(session.id, {
893 type: "request-quests",
894 characterId: session.characterId
895 });
896 break;
778 897 case MessageType.setGraphicsSettings:
779 898 {
780 899 const next = normalizeGraphicsSettings({
@@ -813,12 +932,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
813 932 session.characterId = character.character_id;
814 933 session.entityId = simulation.spawnCharacter(session.id, character);
815 934 const spawned = simulation.entityRecord(session.entityId);
935 const enterDim = normalizeDimensionId(spawned.dimensionId ?? OVERWORLD_ID);
936 const dimRecord = simulation.getDimensionRecord?.(enterDim);
816 937 send(session, {
817 938 type: MessageType.enterWorld,
818 939 entityId: session.entityId,
819 940 characterId: session.characterId,
820 941 tileX: spawned.tileX,
821 942 tileY: spawned.tileY,
943 dimensionId: enterDim,
944 lightingMode: dimRecord?.lightingMode ?? "dayNight",
945 seasonMode: dimRecord?.seasonMode ?? "auto",
822 946 gait: spawned.gait,
823 947 sex: spawned.sex,
824 948 firstName: spawned.firstName,
@@ -887,6 +1011,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
887 1011 if (!position)
888 1012 { return; }
889 1013
1014 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
890 1015 const centerChunkX = tileToChunk(position.tileX);
891 1016 const centerChunkY = tileToChunk(position.tileY);
892 1017 const mapRadius = staticChunkRadiusForViewDistance(
@@ -896,14 +1021,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
896 1021 );
897 1022 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
898 1023 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
899 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
900 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
1024 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)));
1025 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)));
901 1026
902 1027 for (const key of session.staticSubscribed)
903 1028 {
904 1029 if (!staticNext.has(key))
905 1030 {
906 const [chunkX, chunkY] = key.split(",").map(Number);
1031 const { chunkX, chunkY } = parseChunkKey(key);
907 1032 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
908 1033 }
909 1034 }
@@ -911,7 +1036,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
911 1036 const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
912 1037 for (const snapshot of snapshots)
913 1038 {
914 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
1039 const key = chunkKey(snapshot.chunkX, snapshot.chunkY, dimensionId);
915 1040 const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
916 1041 if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
917 1042 {
@@ -1107,6 +1232,84 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1107 1232 { send(session, { type: MessageType.toast, message: event.message }); }
1108 1233 continue;
1109 1234 }
1235 if (event.type === "quests-snapshot")
1236 {
1237 const session = event.sessionId != null
1238 ? sessions.get(event.sessionId)
1239 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1240 if (session)
1241 {
1242 send(session, {
1243 type: MessageType.questsSnapshot,
1244 quests: event.quests ?? []
1245 });
1246 }
1247 continue;
1248 }
1249 if (event.type === "quest-step-complete")
1250 {
1251 const session = event.sessionId != null
1252 ? sessions.get(event.sessionId)
1253 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1254 if (session)
1255 {
1256 send(session, {
1257 type: MessageType.questStepComplete,
1258 questId: event.questId,
1259 title: event.title
1260 });
1261 }
1262 continue;
1263 }
1264 if (event.type === "dialogue-step")
1265 {
1266 const session = event.sessionId != null
1267 ? sessions.get(event.sessionId)
1268 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1269 if (session)
1270 {
1271 send(session, {
1272 type: MessageType.dialogueStep,
1273 dialogueId: event.dialogueId,
1274 stepId: event.stepId,
1275 label: event.label,
1276 npcEntityId: event.npcEntityId ?? null,
1277 lines: event.lines ?? []
1278 });
1279 }
1280 continue;
1281 }
1282 if (event.type === "dialogue-choices")
1283 {
1284 const session = event.sessionId != null
1285 ? sessions.get(event.sessionId)
1286 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1287 if (session)
1288 {
1289 send(session, {
1290 type: MessageType.dialogueChoices,
1291 dialogueId: event.dialogueId,
1292 stepId: event.stepId,
1293 npcEntityId: event.npcEntityId ?? null,
1294 triggers: event.triggers ?? []
1295 });
1296 }
1297 continue;
1298 }
1299 if (event.type === "dialogue-close")
1300 {
1301 const session = event.sessionId != null
1302 ? sessions.get(event.sessionId)
1303 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1304 if (session)
1305 {
1306 send(session, {
1307 type: MessageType.dialogueClose,
1308 reason: event.reason ?? null
1309 });
1310 }
1311 continue;
1312 }
1110 1313 if (event.type === "pigeon-delivered")
1111 1314 {
1112 1315 for (const session of sessions.values())
@@ -1156,6 +1359,25 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1156 1359 }
1157 1360 continue;
1158 1361 }
1362 if (event.type === "dimension-changed")
1363 {
1364 const session = sessions.get(event.sessionId);
1365 if (session)
1366 {
1367 session.entitySubscribed.clear();
1368 session.staticSubscribed.clear();
1369 send(session, {
1370 type: MessageType.dimensionChanged,
1371 dimensionId: event.dimensionId,
1372 tileX: event.tileX,
1373 tileY: event.tileY,
1374 lightingMode: event.lightingMode,
1375 seasonMode: event.seasonMode
1376 });
1377 syncSubscriptions(session, true);
1378 }
1379 continue;
1380 }
1159 1381 if (event.type === "combat-no-arrows")
1160 1382 {
1161 1383 const session = sessions.get(event.sessionId);
@@ -1369,10 +1591,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1369 1591
1370 1592 function publishEntity (event)
1371 1593 {
1594 const toDim = normalizeDimensionId(event.dimensionId
1595 ?? simulation.entityRecord(event.entityId)?.dimensionId
1596 ?? OVERWORLD_ID);
1597 const fromDim = event.fromDimensionId != null
1598 ? normalizeDimensionId(event.fromDimensionId)
1599 : toDim;
1372 1600 const fromKey = event.fromTileX != null
1373 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY))
1601 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY), fromDim)
1602 : null;
1603 const toKey = event.tileX != null
1604 ? chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY), toDim)
1374 1605 : null;
1375 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
1376 1606 for (const session of sessions.values())
1377 1607 {
1378 1608 if (!session.entityId)
@@ -1636,7 +1866,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1636 1866 else if (seesFrom)
1637 1867 { send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); }
1638 1868 if (session.entityId === event.entityId)
1639 { syncSubscriptions(session, false); }
1869 {
1870 const crossedDimension = event.fromDimensionId != null
1871 && event.dimensionId != null
1872 && normalizeDimensionId(event.fromDimensionId) !== normalizeDimensionId(event.dimensionId);
1873 if (!crossedDimension)
1874 { syncSubscriptions(session, false); }
1875 }
1640 1876 }
1641 1877 }
1642 1878
@@ -1661,6 +1897,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1661 1897 canFight: !!(record.canFight ?? event.canFight),
1662 1898 hostile: !!(record.hostile ?? event.hostile),
1663 1899 talkable: !!(record.talkable ?? event.talkable),
1900 hasDialogue: !!(record.hasDialogue ?? event.hasDialogue),
1901 hasShop: !!(record.hasShop ?? event.hasShop),
1664 1902 untargetable: !!(record.untargetable ?? event.untargetable),
1665 1903 freeFlight: !!(record.freeFlight ?? event.freeFlight),
1666 1904 health: record.health ?? event.health,
@@ -1,11 +1,12 @@
1import { WebSocketServer } from "ws";
1import { 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, parseChunkKey, tileToChunk, visibleChunkCoords } from "../world/coordinates.js";
4import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
4import { VISIBLE_CHUNK_RADIUS, STATIC_CHUNK_RADIUS } from "../../../shared/protocol/constants.js";
5import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
5import { staticChunkRadiusForViewDistance, ViewDistance, normalizeGraphicsSettings } from "../../../shared/graphics/settings.js";
6import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
6import { broadcastSpeech, broadcastItemBubble } from "../chat/speech.js";
7import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
7import { CraftingStationId, craftingStationDefinition } from "../../../shared/definitions/craftingStations.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
8import { publicSkillsView } from "../../../shared/skills/state.js";
9import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
9
10
10let nextSessionId = 1;
11let nextSessionId = 1;
11
12
@@ -216,6 +217,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
216 characterId: session.characterId
217 characterId: session.characterId
217 });
218 });
218 break;
219 break;
220 case MessageType.enterDoorway:
221 requirePlaying(session);
222 simulation.enqueue(session.id, {
223 type: "enter-doorway",
224 characterId: session.characterId,
225 tileX: message.tileX | 0,
226 tileY: message.tileY | 0
227 });
228 break;
219 case MessageType.openBounty:
229 case MessageType.openBounty:
220 requirePlaying(session);
230 requirePlaying(session);
221 simulation.enqueue(session.id, {
231 simulation.enqueue(session.id, {
@@ -581,7 +591,10 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
581 simulation.enqueue(session.id, {
591 simulation.enqueue(session.id, {
582 type: "interact",
592 type: "interact",
583 characterId: session.characterId,
593 characterId: session.characterId,
584 targetEntityId: message.targetEntityId | 0
594 targetEntityId: message.targetEntityId | 0,
595 purpose: message.purpose === "shop" || message.purpose === "talk"
596 ? message.purpose
597 : null
585 });
598 });
586 break;
599 break;
587 case MessageType.buyFromShop:
600 case MessageType.buyFromShop:
@@ -726,13 +739,54 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
726 break;
739 break;
727 case MessageType.editorLoadChunk:
740 case MessageType.editorLoadChunk:
728 requireAdmin(session);
741 requireAdmin(session);
729 send(session, { type: MessageType.editorChunk, ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0) });
742 send(session, {
743 type: MessageType.editorChunk,
744 ...editor.loadChunk(message.chunkX | 0, message.chunkY | 0, message.dimensionId)
745 });
730 break;
746 break;
731 case MessageType.editorSaveChunk:
747 case MessageType.editorSaveChunk:
732 requireAdmin(session);
748 requireAdmin(session);
733 send(session, {
749 send(session, {
734 type: MessageType.editorChunk,
750 type: MessageType.editorChunk,
735 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
751 ...editor.saveChunk(
752 message.chunkX | 0,
753 message.chunkY | 0,
754 message.draft,
755 session.authSubject,
756 message.dimensionId
757 )
758 });
759 break;
760 case MessageType.editorListDimensions:
761 requireAdmin(session);
762 send(session, { type: MessageType.editorDimensions, ...editor.listDimensions() });
763 break;
764 case MessageType.editorCreateDimension:
765 requireAdmin(session);
766 send(session, {
767 type: MessageType.editorDimensions,
768 ...editor.createDimension(message.dimensionId, message.displayName, session.authSubject)
769 });
770 break;
771 case MessageType.editorSaveDimension:
772 requireAdmin(session);
773 send(session, {
774 type: MessageType.editorDimensions,
775 ...editor.saveDimension(message.dimension ?? message, session.authSubject)
776 });
777 break;
778 case MessageType.editorSoftDeleteDimension:
779 requireAdmin(session);
780 send(session, {
781 type: MessageType.editorDimensions,
782 ...editor.softDeleteDimension(message.dimensionId, session.authSubject)
783 });
784 break;
785 case MessageType.editorCancelDimensionDeletion:
786 requireAdmin(session);
787 send(session, {
788 type: MessageType.editorDimensions,
789 ...editor.cancelDimensionDeletion(message.dimensionId, session.authSubject)
736 });
790 });
737 break;
791 break;
738 case MessageType.editorLoadSettings:
792 case MessageType.editorLoadSettings:
@@ -775,6 +829,71 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
775 });
829 });
776 }
830 }
777 break;
831 break;
832 case MessageType.editorLoadQuests:
833 requireAdmin(session);
834 send(session, { type: MessageType.editorQuests, ...editor.loadQuests() });
835 break;
836 case MessageType.editorSaveQuest:
837 requireAdmin(session);
838 send(session, {
839 type: MessageType.editorQuests,
840 ...editor.saveQuest(message.quest ?? message, session.authSubject)
841 });
842 break;
843 case MessageType.editorDeleteQuest:
844 requireAdmin(session);
845 send(session, {
846 type: MessageType.editorQuests,
847 ...editor.deleteQuest(message.questId, session.authSubject)
848 });
849 break;
850 case MessageType.editorLoadDialogues:
851 requireAdmin(session);
852 send(session, { type: MessageType.editorDialogues, ...editor.loadDialogues() });
853 break;
854 case MessageType.editorSaveDialogue:
855 requireAdmin(session);
856 send(session, {
857 type: MessageType.editorDialogues,
858 ...editor.saveDialogue(message.dialogue ?? message, session.authSubject)
859 });
860 break;
861 case MessageType.editorDeleteDialogue:
862 requireAdmin(session);
863 send(session, {
864 type: MessageType.editorDialogues,
865 ...editor.deleteDialogue(message.dialogueId, session.authSubject)
866 });
867 break;
868 case MessageType.dialogueChoose:
869 requirePlaying(session);
870 simulation.enqueue(session.id, {
871 type: "dialogue-choose",
872 characterId: session.characterId,
873 trigger: String(message.trigger ?? "")
874 });
875 break;
876 case MessageType.dialogueAdvance:
877 requirePlaying(session);
878 simulation.enqueue(session.id, {
879 type: "dialogue-advance",
880 characterId: session.characterId
881 });
882 break;
883 case MessageType.closeDialogue:
884 requirePlaying(session);
885 simulation.enqueue(session.id, {
886 type: "close-dialogue",
887 characterId: session.characterId
888 });
889 break;
890 case MessageType.requestQuests:
891 requirePlaying(session);
892 simulation.enqueue(session.id, {
893 type: "request-quests",
894 characterId: session.characterId
895 });
896 break;
778 case MessageType.setGraphicsSettings:
897 case MessageType.setGraphicsSettings:
779 {
898 {
780 const next = normalizeGraphicsSettings({
899 const next = normalizeGraphicsSettings({
@@ -813,12 +932,17 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
813 session.characterId = character.character_id;
932 session.characterId = character.character_id;
814 session.entityId = simulation.spawnCharacter(session.id, character);
933 session.entityId = simulation.spawnCharacter(session.id, character);
815 const spawned = simulation.entityRecord(session.entityId);
934 const spawned = simulation.entityRecord(session.entityId);
935 const enterDim = normalizeDimensionId(spawned.dimensionId ?? OVERWORLD_ID);
936 const dimRecord = simulation.getDimensionRecord?.(enterDim);
816 send(session, {
937 send(session, {
817 type: MessageType.enterWorld,
938 type: MessageType.enterWorld,
818 entityId: session.entityId,
939 entityId: session.entityId,
819 characterId: session.characterId,
940 characterId: session.characterId,
820 tileX: spawned.tileX,
941 tileX: spawned.tileX,
821 tileY: spawned.tileY,
942 tileY: spawned.tileY,
943 dimensionId: enterDim,
944 lightingMode: dimRecord?.lightingMode ?? "dayNight",
945 seasonMode: dimRecord?.seasonMode ?? "auto",
822 gait: spawned.gait,
946 gait: spawned.gait,
823 sex: spawned.sex,
947 sex: spawned.sex,
824 firstName: spawned.firstName,
948 firstName: spawned.firstName,
@@ -887,6 +1011,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
887 if (!position)
1011 if (!position)
888 { return; }
1012 { return; }
889
1013
1014 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
890 const centerChunkX = tileToChunk(position.tileX);
1015 const centerChunkX = tileToChunk(position.tileX);
891 const centerChunkY = tileToChunk(position.tileY);
1016 const centerChunkY = tileToChunk(position.tileY);
892 const mapRadius = staticChunkRadiusForViewDistance(
1017 const mapRadius = staticChunkRadiusForViewDistance(
@@ -896,14 +1021,14 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
896 );
1021 );
897 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
1022 const entityCoords = visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS);
898 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
1023 const staticCoords = visibleChunkCoords(centerChunkX, centerChunkY, mapRadius);
899 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
1024 const entityNext = new Set(entityCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)));
900 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY)));
1025 const staticNext = new Set(staticCoords.map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId)));
901
1026
902 for (const key of session.staticSubscribed)
1027 for (const key of session.staticSubscribed)
903 {
1028 {
904 if (!staticNext.has(key))
1029 if (!staticNext.has(key))
905 {
1030 {
906 const [chunkX, chunkY] = key.split(",").map(Number);
1031 const { chunkX, chunkY } = parseChunkKey(key);
907 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
1032 send(session, { type: MessageType.unsubscribeChunk, chunkX, chunkY });
908 }
1033 }
909 }
1034 }
@@ -911,7 +1036,7 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
911 const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
1036 const snapshots = simulation.snapshotsForView(session.entityId, mapRadius);
912 for (const snapshot of snapshots)
1037 for (const snapshot of snapshots)
913 {
1038 {
914 const key = chunkKey(snapshot.chunkX, snapshot.chunkY);
1039 const key = chunkKey(snapshot.chunkX, snapshot.chunkY, dimensionId);
915 const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
1040 const entityChanged = entityNext.has(key) !== session.entitySubscribed.has(key);
916 if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
1041 if (forceSnapshots || !session.staticSubscribed.has(key) || entityChanged)
917 {
1042 {
@@ -1107,6 +1232,84 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1107 { send(session, { type: MessageType.toast, message: event.message }); }
1232 { send(session, { type: MessageType.toast, message: event.message }); }
1108 continue;
1233 continue;
1109 }
1234 }
1235 if (event.type === "quests-snapshot")
1236 {
1237 const session = event.sessionId != null
1238 ? sessions.get(event.sessionId)
1239 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1240 if (session)
1241 {
1242 send(session, {
1243 type: MessageType.questsSnapshot,
1244 quests: event.quests ?? []
1245 });
1246 }
1247 continue;
1248 }
1249 if (event.type === "quest-step-complete")
1250 {
1251 const session = event.sessionId != null
1252 ? sessions.get(event.sessionId)
1253 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1254 if (session)
1255 {
1256 send(session, {
1257 type: MessageType.questStepComplete,
1258 questId: event.questId,
1259 title: event.title
1260 });
1261 }
1262 continue;
1263 }
1264 if (event.type === "dialogue-step")
1265 {
1266 const session = event.sessionId != null
1267 ? sessions.get(event.sessionId)
1268 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1269 if (session)
1270 {
1271 send(session, {
1272 type: MessageType.dialogueStep,
1273 dialogueId: event.dialogueId,
1274 stepId: event.stepId,
1275 label: event.label,
1276 npcEntityId: event.npcEntityId ?? null,
1277 lines: event.lines ?? []
1278 });
1279 }
1280 continue;
1281 }
1282 if (event.type === "dialogue-choices")
1283 {
1284 const session = event.sessionId != null
1285 ? sessions.get(event.sessionId)
1286 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1287 if (session)
1288 {
1289 send(session, {
1290 type: MessageType.dialogueChoices,
1291 dialogueId: event.dialogueId,
1292 stepId: event.stepId,
1293 npcEntityId: event.npcEntityId ?? null,
1294 triggers: event.triggers ?? []
1295 });
1296 }
1297 continue;
1298 }
1299 if (event.type === "dialogue-close")
1300 {
1301 const session = event.sessionId != null
1302 ? sessions.get(event.sessionId)
1303 : [...sessions.values()].find((entry) => entry.characterId === event.characterId);
1304 if (session)
1305 {
1306 send(session, {
1307 type: MessageType.dialogueClose,
1308 reason: event.reason ?? null
1309 });
1310 }
1311 continue;
1312 }
1110 if (event.type === "pigeon-delivered")
1313 if (event.type === "pigeon-delivered")
1111 {
1314 {
1112 for (const session of sessions.values())
1315 for (const session of sessions.values())
@@ -1156,6 +1359,25 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1156 }
1359 }
1157 continue;
1360 continue;
1158 }
1361 }
1362 if (event.type === "dimension-changed")
1363 {
1364 const session = sessions.get(event.sessionId);
1365 if (session)
1366 {
1367 session.entitySubscribed.clear();
1368 session.staticSubscribed.clear();
1369 send(session, {
1370 type: MessageType.dimensionChanged,
1371 dimensionId: event.dimensionId,
1372 tileX: event.tileX,
1373 tileY: event.tileY,
1374 lightingMode: event.lightingMode,
1375 seasonMode: event.seasonMode
1376 });
1377 syncSubscriptions(session, true);
1378 }
1379 continue;
1380 }
1159 if (event.type === "combat-no-arrows")
1381 if (event.type === "combat-no-arrows")
1160 {
1382 {
1161 const session = sessions.get(event.sessionId);
1383 const session = sessions.get(event.sessionId);
@@ -1369,10 +1591,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1369
1591
1370 function publishEntity (event)
1592 function publishEntity (event)
1371 {
1593 {
1594 const toDim = normalizeDimensionId(event.dimensionId
1595 ?? simulation.entityRecord(event.entityId)?.dimensionId
1596 ?? OVERWORLD_ID);
1597 const fromDim = event.fromDimensionId != null
1598 ? normalizeDimensionId(event.fromDimensionId)
1599 : toDim;
1372 const fromKey = event.fromTileX != null
1600 const fromKey = event.fromTileX != null
1373 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY))
1601 ? chunkKey(tileToChunk(event.fromTileX), tileToChunk(event.fromTileY), fromDim)
1602 : null;
1603 const toKey = event.tileX != null
1604 ? chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY), toDim)
1374 : null;
1605 : null;
1375 const toKey = chunkKey(tileToChunk(event.tileX), tileToChunk(event.tileY));
1376 for (const session of sessions.values())
1606 for (const session of sessions.values())
1377 {
1607 {
1378 if (!session.entityId)
1608 if (!session.entityId)
@@ -1636,7 +1866,13 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1636 else if (seesFrom)
1866 else if (seesFrom)
1637 { send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); }
1867 { send(session, { type: MessageType.entityDespawn, entityId: event.entityId }); }
1638 if (session.entityId === event.entityId)
1868 if (session.entityId === event.entityId)
1639 { syncSubscriptions(session, false); }
1869 {
1870 const crossedDimension = event.fromDimensionId != null
1871 && event.dimensionId != null
1872 && normalizeDimensionId(event.fromDimensionId) !== normalizeDimensionId(event.dimensionId);
1873 if (!crossedDimension)
1874 { syncSubscriptions(session, false); }
1875 }
1640 }
1876 }
1641 }
1877 }
1642
1878
@@ -1661,6 +1897,8 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, friends,
1661 canFight: !!(record.canFight ?? event.canFight),
1897 canFight: !!(record.canFight ?? event.canFight),
1662 hostile: !!(record.hostile ?? event.hostile),
1898 hostile: !!(record.hostile ?? event.hostile),
1663 talkable: !!(record.talkable ?? event.talkable),
1899 talkable: !!(record.talkable ?? event.talkable),
1900 hasDialogue: !!(record.hasDialogue ?? event.hasDialogue),
1901 hasShop: !!(record.hasShop ?? event.hasShop),
1664 untargetable: !!(record.untargetable ?? event.untargetable),
1902 untargetable: !!(record.untargetable ?? event.untargetable),
1665 freeFlight: !!(record.freeFlight ?? event.freeFlight),
1903 freeFlight: !!(record.freeFlight ?? event.freeFlight),
1666 health: record.health ?? event.health,
1904 health: record.health ?? event.health,
server/src/lighting/baker.js +6 −3
@@ -1,5 +1,6 @@
1 1 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2 2 import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
3 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3 4 import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4 5 import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5 6
@@ -13,15 +14,16 @@ export function maxDefinitionLightRange (blockDefs)
13 14 return max;
14 15 }
15 16
16 export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
17 export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange, dimensionId = OVERWORLD_ID)
17 18 {
19 const dim = normalizeDimensionId(dimensionId);
18 20 const halo = maxLightChunkRadius(maxRange);
19 21 const affected = chebyshevChunks(centerChunkX, centerChunkY, halo);
20 22 const loaded = new Map();
21 23
22 24 function getData (chunkX, chunkY)
23 25 {
24 const key = chunkKey(chunkX, chunkY);
26 const key = chunkKey(chunkX, chunkY, dim);
25 27 if (!loaded.has(key))
26 28 { loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }
27 29 return loaded.get(key);
@@ -69,7 +71,8 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
69 71 return affected.map((coord) => ({
70 72 chunkX: coord.chunkX,
71 73 chunkY: coord.chunkY,
72 data: loaded.get(chunkKey(coord.chunkX, coord.chunkY))
74 dimensionId: dim,
75 data: loaded.get(chunkKey(coord.chunkX, coord.chunkY, dim))
73 76 }));
74 77 }
75 78
@@ -1,5 +1,6 @@
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
2import { encodeLight, evaluateLightRay, lightIntensity } from "../../../shared/lighting/raycast.js";
3import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4import { tileToChunk, tileToLocal, chunkKey, maxLightChunkRadius, chebyshevChunks } from "../world/coordinates.js";
4import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5import { cloneChunkData, collectLightSources, createEmptyChunkData, chunkTileLightOcclusion } from "../world/chunkData.js";
5
6
@@ -13,15 +14,16 @@ export function maxDefinitionLightRange (blockDefs)
13 return max;
14 return max;
14}
15}
15
16
16export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
17export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange, dimensionId = OVERWORLD_ID)
17{
18{
19 const dim = normalizeDimensionId(dimensionId);
18 const halo = maxLightChunkRadius(maxRange);
20 const halo = maxLightChunkRadius(maxRange);
19 const affected = chebyshevChunks(centerChunkX, centerChunkY, halo);
21 const affected = chebyshevChunks(centerChunkX, centerChunkY, halo);
20 const loaded = new Map();
22 const loaded = new Map();
21
23
22 function getData (chunkX, chunkY)
24 function getData (chunkX, chunkY)
23 {
25 {
24 const key = chunkKey(chunkX, chunkY);
26 const key = chunkKey(chunkX, chunkY, dim);
25 if (!loaded.has(key))
27 if (!loaded.has(key))
26 { loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }
28 { loaded.set(key, cloneChunkData(loadChunk(chunkX, chunkY))); }
27 return loaded.get(key);
29 return loaded.get(key);
@@ -69,7 +71,8 @@ export function bakeLightMaps (centerChunkX, centerChunkY, loadChunk, maxRange)
69 return affected.map((coord) => ({
71 return affected.map((coord) => ({
70 chunkX: coord.chunkX,
72 chunkX: coord.chunkX,
71 chunkY: coord.chunkY,
73 chunkY: coord.chunkY,
72 data: loaded.get(chunkKey(coord.chunkX, coord.chunkY))
74 dimensionId: dim,
75 data: loaded.get(chunkKey(coord.chunkX, coord.chunkY, dim))
73 }));
76 }));
74}
77}
75
78
server/src/persistence/stateDb.js +240 −4
@@ -161,6 +161,48 @@ CREATE TABLE IF NOT EXISTS character_bounties (
161 161 character_id INTEGER PRIMARY KEY,
162 162 amount INTEGER NOT NULL DEFAULT 0
163 163 );
164
165 CREATE TABLE IF NOT EXISTS character_quest_state (
166 character_id INTEGER NOT NULL,
167 quest_id TEXT NOT NULL,
168 state_value TEXT NOT NULL,
169 progress_blob TEXT NOT NULL DEFAULT '{}',
170 started_at INTEGER,
171 completed_at INTEGER,
172 PRIMARY KEY (character_id, quest_id)
173 );
174
175 CREATE TABLE IF NOT EXISTS character_dialogue_heard (
176 character_id INTEGER NOT NULL,
177 dialogue_id TEXT NOT NULL,
178 step_id TEXT NOT NULL,
179 heard_at INTEGER NOT NULL,
180 PRIMARY KEY (character_id, dialogue_id, step_id)
181 );
182
183 CREATE TABLE IF NOT EXISTS character_quest_journal (
184 entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
185 character_id INTEGER NOT NULL,
186 quest_id TEXT NOT NULL,
187 step_id TEXT NOT NULL,
188 text TEXT NOT NULL,
189 written_at INTEGER NOT NULL
190 );
191
192 CREATE TABLE IF NOT EXISTS character_dialogue_triggers (
193 character_id INTEGER NOT NULL,
194 dialogue_id TEXT NOT NULL,
195 trigger_id TEXT NOT NULL,
196 latched_at INTEGER NOT NULL,
197 PRIMARY KEY (character_id, dialogue_id, trigger_id)
198 );
199
200 CREATE TABLE IF NOT EXISTS character_visited_dimensions (
201 character_id INTEGER NOT NULL,
202 dimension_id TEXT NOT NULL,
203 first_visited_at INTEGER NOT NULL,
204 PRIMARY KEY (character_id, dimension_id)
205 );
164 206 `;
165 207
166 208 export class StateDatabase
@@ -189,6 +231,16 @@ export class StateDatabase
189 231 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
190 232 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
191 233 }
234 if (!characterColumns.some((column) => column.name === "dimension_id"))
235 { this.db.exec("ALTER TABLE characters ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
236 this.db.exec(`
237 CREATE TABLE IF NOT EXISTS character_visited_dimensions (
238 character_id INTEGER NOT NULL,
239 dimension_id TEXT NOT NULL,
240 first_visited_at INTEGER NOT NULL,
241 PRIMARY KEY (character_id, dimension_id)
242 )
243 `);
192 244 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
193 245 if (!courierColumns.some((column) => column.name === "vault_character_id"))
194 246 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
@@ -291,8 +343,8 @@ export class StateDatabase
291 343 this.db.prepare(`
292 344 INSERT INTO characters (
293 345 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
294 hair_style, hair_hue, hair_saturation, hair_darkness
295 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
346 dimension_id, hair_style, hair_hue, hair_saturation, hair_darkness
347 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'overworld', ?, ?, ?, ?)
296 348 `).run(
297 349 accountId,
298 350 firstName,
@@ -395,16 +447,52 @@ export class StateDatabase
395 447 }
396 448 }
397 449
398 saveCharacterPosition (characterId, tileX, tileY, gait)
450 saveCharacterPosition (characterId, tileX, tileY, gait, dimensionId = "overworld")
399 451 {
400 this.db.prepare("UPDATE characters SET tile_x = ?, tile_y = ?, gait = ? WHERE character_id = ?").run(
452 this.db.prepare(`
453 UPDATE characters SET tile_x = ?, tile_y = ?, gait = ?, dimension_id = ?
454 WHERE character_id = ?
455 `).run(
401 456 tileX,
402 457 tileY,
403 458 gait,
459 String(dimensionId ?? "overworld"),
404 460 characterId
405 461 );
406 462 }
407 463
464 markDimensionVisited (characterId, dimensionId, now = Date.now())
465 {
466 const dim = String(dimensionId ?? "overworld");
467 this.db.prepare(`
468 INSERT INTO character_visited_dimensions (character_id, dimension_id, first_visited_at)
469 VALUES (?, ?, ?)
470 ON CONFLICT(character_id, dimension_id) DO NOTHING
471 `).run(characterId | 0, dim, now);
472 }
473
474 hasVisitedDimension (characterId, dimensionId)
475 {
476 const row = this.db.prepare(`
477 SELECT 1 AS ok FROM character_visited_dimensions
478 WHERE character_id = ? AND dimension_id = ?
479 `).get(characterId | 0, String(dimensionId ?? "overworld"));
480 return !!row;
481 }
482
483 listVisitedDimensions (characterId)
484 {
485 return this.db.prepare(`
486 SELECT dimension_id, first_visited_at
487 FROM character_visited_dimensions
488 WHERE character_id = ?
489 ORDER BY first_visited_at ASC
490 `).all(characterId | 0).map((row) => ({
491 dimensionId: row.dimension_id,
492 firstVisitedAt: row.first_visited_at
493 }));
494 }
495
408 496 saveCharacterHealth (characterId, current)
409 497 {
410 498 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
@@ -473,6 +561,154 @@ export class StateDatabase
473 561 return amount;
474 562 }
475 563
564 getQuestState (characterId, questId)
565 {
566 const row = this.db.prepare(`
567 SELECT state_value, progress_blob, started_at, completed_at
568 FROM character_quest_state
569 WHERE character_id = ? AND quest_id = ?
570 `).get(characterId | 0, String(questId));
571 if (!row)
572 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
573 const progress = JSON.parse(row.progress_blob || "{}");
574 let state = row.state_value;
575 if (state !== "not-started" && state !== "completed")
576 { state = Number(state) | 0; }
577 return {
578 state,
579 progress,
580 startedAt: row.started_at ?? null,
581 completedAt: row.completed_at ?? null
582 };
583 }
584
585 listQuestStates (characterId)
586 {
587 return this.db.prepare(`
588 SELECT quest_id, state_value, progress_blob, started_at, completed_at
589 FROM character_quest_state
590 WHERE character_id = ?
591 `).all(characterId | 0).map((row) =>
592 {
593 let state = row.state_value;
594 if (state !== "not-started" && state !== "completed")
595 { state = Number(state) | 0; }
596 return {
597 questId: row.quest_id,
598 state,
599 progress: JSON.parse(row.progress_blob || "{}"),
600 startedAt: row.started_at ?? null,
601 completedAt: row.completed_at ?? null
602 };
603 });
604 }
605
606 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
607 {
608 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
609 this.db.prepare(`
610 INSERT INTO character_quest_state
611 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
612 VALUES (?, ?, ?, ?, ?, ?)
613 ON CONFLICT(character_id, quest_id) DO UPDATE SET
614 state_value = excluded.state_value,
615 progress_blob = excluded.progress_blob,
616 started_at = excluded.started_at,
617 completed_at = excluded.completed_at
618 `).run(
619 characterId | 0,
620 String(questId),
621 stateValue,
622 JSON.stringify(progress ?? {}),
623 startedAt,
624 completedAt
625 );
626 }
627
628 isDialogueHeard (characterId, dialogueId, stepId)
629 {
630 const row = this.db.prepare(`
631 SELECT 1 FROM character_dialogue_heard
632 WHERE character_id = ? AND dialogue_id = ? AND step_id = ?
633 `).get(characterId | 0, String(dialogueId), String(stepId));
634 return !!row;
635 }
636
637 markDialogueHeard (characterId, dialogueId, stepId)
638 {
639 this.db.prepare(`
640 INSERT OR IGNORE INTO character_dialogue_heard
641 (character_id, dialogue_id, step_id, heard_at)
642 VALUES (?, ?, ?, ?)
643 `).run(characterId | 0, String(dialogueId), String(stepId), Date.now());
644 }
645
646 listDialogueHeard (characterId)
647 {
648 return this.db.prepare(`
649 SELECT dialogue_id, step_id, heard_at
650 FROM character_dialogue_heard
651 WHERE character_id = ?
652 `).all(characterId | 0);
653 }
654
655 isDialogueTriggerLatched (characterId, dialogueId, triggerId)
656 {
657 const row = this.db.prepare(`
658 SELECT 1 FROM character_dialogue_triggers
659 WHERE character_id = ? AND dialogue_id = ? AND trigger_id = ?
660 `).get(characterId | 0, String(dialogueId), String(triggerId));
661 return !!row;
662 }
663
664 latchDialogueTrigger (characterId, dialogueId, triggerId)
665 {
666 this.db.prepare(`
667 INSERT OR IGNORE INTO character_dialogue_triggers
668 (character_id, dialogue_id, trigger_id, latched_at)
669 VALUES (?, ?, ?, ?)
670 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
671 }
672
673 appendQuestJournal (characterId, questId, stepId, text)
674 {
675 const trimmed = String(text ?? "").trim();
676 if (!trimmed)
677 { return null; }
678 const writtenAt = Date.now();
679 const result = this.db.prepare(`
680 INSERT INTO character_quest_journal
681 (character_id, quest_id, step_id, text, written_at)
682 VALUES (?, ?, ?, ?, ?)
683 `).run(characterId | 0, String(questId), String(stepId), trimmed, writtenAt);
684 return {
685 entryId: Number(result.lastInsertRowid),
686 questId: String(questId),
687 stepId: String(stepId),
688 text: trimmed,
689 writtenAt
690 };
691 }
692
693 listQuestJournal (characterId, questId = null)
694 {
695 if (questId)
696 {
697 return this.db.prepare(`
698 SELECT entry_id, quest_id, step_id, text, written_at
699 FROM character_quest_journal
700 WHERE character_id = ? AND quest_id = ?
701 ORDER BY written_at ASC, entry_id ASC
702 `).all(characterId | 0, String(questId));
703 }
704 return this.db.prepare(`
705 SELECT entry_id, quest_id, step_id, text, written_at
706 FROM character_quest_journal
707 WHERE character_id = ?
708 ORDER BY written_at ASC, entry_id ASC
709 `).all(characterId | 0);
710 }
711
476 712 listFriendRecords (characterId)
477 713 {
478 714 return this.db.prepare(`
@@ -161,6 +161,48 @@ CREATE TABLE IF NOT EXISTS character_bounties (
161 character_id INTEGER PRIMARY KEY,
161 character_id INTEGER PRIMARY KEY,
162 amount INTEGER NOT NULL DEFAULT 0
162 amount INTEGER NOT NULL DEFAULT 0
163);
163);
164
165CREATE TABLE IF NOT EXISTS character_quest_state (
166 character_id INTEGER NOT NULL,
167 quest_id TEXT NOT NULL,
168 state_value TEXT NOT NULL,
169 progress_blob TEXT NOT NULL DEFAULT '{}',
170 started_at INTEGER,
171 completed_at INTEGER,
172 PRIMARY KEY (character_id, quest_id)
173);
174
175CREATE TABLE IF NOT EXISTS character_dialogue_heard (
176 character_id INTEGER NOT NULL,
177 dialogue_id TEXT NOT NULL,
178 step_id TEXT NOT NULL,
179 heard_at INTEGER NOT NULL,
180 PRIMARY KEY (character_id, dialogue_id, step_id)
181);
182
183CREATE TABLE IF NOT EXISTS character_quest_journal (
184 entry_id INTEGER PRIMARY KEY AUTOINCREMENT,
185 character_id INTEGER NOT NULL,
186 quest_id TEXT NOT NULL,
187 step_id TEXT NOT NULL,
188 text TEXT NOT NULL,
189 written_at INTEGER NOT NULL
190);
191
192CREATE TABLE IF NOT EXISTS character_dialogue_triggers (
193 character_id INTEGER NOT NULL,
194 dialogue_id TEXT NOT NULL,
195 trigger_id TEXT NOT NULL,
196 latched_at INTEGER NOT NULL,
197 PRIMARY KEY (character_id, dialogue_id, trigger_id)
198);
199
200CREATE TABLE IF NOT EXISTS character_visited_dimensions (
201 character_id INTEGER NOT NULL,
202 dimension_id TEXT NOT NULL,
203 first_visited_at INTEGER NOT NULL,
204 PRIMARY KEY (character_id, dimension_id)
205);
164`;
206`;
165
207
166export class StateDatabase
208export class StateDatabase
@@ -189,6 +231,16 @@ export class StateDatabase
189 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
231 this.db.exec("ALTER TABLE characters ADD COLUMN hair_saturation REAL NOT NULL DEFAULT 0.55");
190 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
232 this.db.exec("ALTER TABLE characters ADD COLUMN hair_darkness REAL NOT NULL DEFAULT 0.45");
191 }
233 }
234 if (!characterColumns.some((column) => column.name === "dimension_id"))
235 { this.db.exec("ALTER TABLE characters ADD COLUMN dimension_id TEXT NOT NULL DEFAULT 'overworld'"); }
236 this.db.exec(`
237 CREATE TABLE IF NOT EXISTS character_visited_dimensions (
238 character_id INTEGER NOT NULL,
239 dimension_id TEXT NOT NULL,
240 first_visited_at INTEGER NOT NULL,
241 PRIMARY KEY (character_id, dimension_id)
242 )
243 `);
192 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
244 const courierColumns = this.db.prepare("PRAGMA table_info(courier_transits)").all();
193 if (!courierColumns.some((column) => column.name === "vault_character_id"))
245 if (!courierColumns.some((column) => column.name === "vault_character_id"))
194 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
246 { this.db.exec("ALTER TABLE courier_transits ADD COLUMN vault_character_id INTEGER"); }
@@ -291,8 +343,8 @@ export class StateDatabase
291 this.db.prepare(`
343 this.db.prepare(`
292 INSERT INTO characters (
344 INSERT INTO characters (
293 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
345 account_id, first_name, last_name, first_normalized, last_normalized, sex, tile_x, tile_y,
294 hair_style, hair_hue, hair_saturation, hair_darkness
346 dimension_id, hair_style, hair_hue, hair_saturation, hair_darkness
295 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
347 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, 'overworld', ?, ?, ?, ?)
296 `).run(
348 `).run(
297 accountId,
349 accountId,
298 firstName,
350 firstName,
@@ -395,16 +447,52 @@ export class StateDatabase
395 }
447 }
396 }
448 }
397
449
398 saveCharacterPosition (characterId, tileX, tileY, gait)
450 saveCharacterPosition (characterId, tileX, tileY, gait, dimensionId = "overworld")
399 {
451 {
400 this.db.prepare("UPDATE characters SET tile_x = ?, tile_y = ?, gait = ? WHERE character_id = ?").run(
452 this.db.prepare(`
453 UPDATE characters SET tile_x = ?, tile_y = ?, gait = ?, dimension_id = ?
454 WHERE character_id = ?
455 `).run(
401 tileX,
456 tileX,
402 tileY,
457 tileY,
403 gait,
458 gait,
459 String(dimensionId ?? "overworld"),
404 characterId
460 characterId
405 );
461 );
406 }
462 }
407
463
464 markDimensionVisited (characterId, dimensionId, now = Date.now())
465 {
466 const dim = String(dimensionId ?? "overworld");
467 this.db.prepare(`
468 INSERT INTO character_visited_dimensions (character_id, dimension_id, first_visited_at)
469 VALUES (?, ?, ?)
470 ON CONFLICT(character_id, dimension_id) DO NOTHING
471 `).run(characterId | 0, dim, now);
472 }
473
474 hasVisitedDimension (characterId, dimensionId)
475 {
476 const row = this.db.prepare(`
477 SELECT 1 AS ok FROM character_visited_dimensions
478 WHERE character_id = ? AND dimension_id = ?
479 `).get(characterId | 0, String(dimensionId ?? "overworld"));
480 return !!row;
481 }
482
483 listVisitedDimensions (characterId)
484 {
485 return this.db.prepare(`
486 SELECT dimension_id, first_visited_at
487 FROM character_visited_dimensions
488 WHERE character_id = ?
489 ORDER BY first_visited_at ASC
490 `).all(characterId | 0).map((row) => ({
491 dimensionId: row.dimension_id,
492 firstVisitedAt: row.first_visited_at
493 }));
494 }
495
408 saveCharacterHealth (characterId, current)
496 saveCharacterHealth (characterId, current)
409 {
497 {
410 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
498 this.db.prepare("UPDATE characters SET health_current = ? WHERE character_id = ?").run(
@@ -473,6 +561,154 @@ export class StateDatabase
473 return amount;
561 return amount;
474 }
562 }
475
563
564 getQuestState (characterId, questId)
565 {
566 const row = this.db.prepare(`
567 SELECT state_value, progress_blob, started_at, completed_at
568 FROM character_quest_state
569 WHERE character_id = ? AND quest_id = ?
570 `).get(characterId | 0, String(questId));
571 if (!row)
572 { return { state: "not-started", progress: {}, startedAt: null, completedAt: null }; }
573 const progress = JSON.parse(row.progress_blob || "{}");
574 let state = row.state_value;
575 if (state !== "not-started" && state !== "completed")
576 { state = Number(state) | 0; }
577 return {
578 state,
579 progress,
580 startedAt: row.started_at ?? null,
581 completedAt: row.completed_at ?? null
582 };
583 }
584
585 listQuestStates (characterId)
586 {
587 return this.db.prepare(`
588 SELECT quest_id, state_value, progress_blob, started_at, completed_at
589 FROM character_quest_state
590 WHERE character_id = ?
591 `).all(characterId | 0).map((row) =>
592 {
593 let state = row.state_value;
594 if (state !== "not-started" && state !== "completed")
595 { state = Number(state) | 0; }
596 return {
597 questId: row.quest_id,
598 state,
599 progress: JSON.parse(row.progress_blob || "{}"),
600 startedAt: row.started_at ?? null,
601 completedAt: row.completed_at ?? null
602 };
603 });
604 }
605
606 saveQuestState (characterId, questId, state, progress = {}, startedAt = null, completedAt = null)
607 {
608 const stateValue = state === "not-started" || state === "completed" ? state : String(state | 0);
609 this.db.prepare(`
610 INSERT INTO character_quest_state
611 (character_id, quest_id, state_value, progress_blob, started_at, completed_at)
612 VALUES (?, ?, ?, ?, ?, ?)
613 ON CONFLICT(character_id, quest_id) DO UPDATE SET
614 state_value = excluded.state_value,
615 progress_blob = excluded.progress_blob,
616 started_at = excluded.started_at,
617 completed_at = excluded.completed_at
618 `).run(
619 characterId | 0,
620 String(questId),
621 stateValue,
622 JSON.stringify(progress ?? {}),
623 startedAt,
624 completedAt
625 );
626 }
627
628 isDialogueHeard (characterId, dialogueId, stepId)
629 {
630 const row = this.db.prepare(`
631 SELECT 1 FROM character_dialogue_heard
632 WHERE character_id = ? AND dialogue_id = ? AND step_id = ?
633 `).get(characterId | 0, String(dialogueId), String(stepId));
634 return !!row;
635 }
636
637 markDialogueHeard (characterId, dialogueId, stepId)
638 {
639 this.db.prepare(`
640 INSERT OR IGNORE INTO character_dialogue_heard
641 (character_id, dialogue_id, step_id, heard_at)
642 VALUES (?, ?, ?, ?)
643 `).run(characterId | 0, String(dialogueId), String(stepId), Date.now());
644 }
645
646 listDialogueHeard (characterId)
647 {
648 return this.db.prepare(`
649 SELECT dialogue_id, step_id, heard_at
650 FROM character_dialogue_heard
651 WHERE character_id = ?
652 `).all(characterId | 0);
653 }
654
655 isDialogueTriggerLatched (characterId, dialogueId, triggerId)
656 {
657 const row = this.db.prepare(`
658 SELECT 1 FROM character_dialogue_triggers
659 WHERE character_id = ? AND dialogue_id = ? AND trigger_id = ?
660 `).get(characterId | 0, String(dialogueId), String(triggerId));
661 return !!row;
662 }
663
664 latchDialogueTrigger (characterId, dialogueId, triggerId)
665 {
666 this.db.prepare(`
667 INSERT OR IGNORE INTO character_dialogue_triggers
668 (character_id, dialogue_id, trigger_id, latched_at)
669 VALUES (?, ?, ?, ?)
670 `).run(characterId | 0, String(dialogueId), String(triggerId), Date.now());
671 }
672
673 appendQuestJournal (characterId, questId, stepId, text)
674 {
675 const trimmed = String(text ?? "").trim();
676 if (!trimmed)
677 { return null; }
678 const writtenAt = Date.now();
679 const result = this.db.prepare(`
680 INSERT INTO character_quest_journal
681 (character_id, quest_id, step_id, text, written_at)
682 VALUES (?, ?, ?, ?, ?)
683 `).run(characterId | 0, String(questId), String(stepId), trimmed, writtenAt);
684 return {
685 entryId: Number(result.lastInsertRowid),
686 questId: String(questId),
687 stepId: String(stepId),
688 text: trimmed,
689 writtenAt
690 };
691 }
692
693 listQuestJournal (characterId, questId = null)
694 {
695 if (questId)
696 {
697 return this.db.prepare(`
698 SELECT entry_id, quest_id, step_id, text, written_at
699 FROM character_quest_journal
700 WHERE character_id = ? AND quest_id = ?
701 ORDER BY written_at ASC, entry_id ASC
702 `).all(characterId | 0, String(questId));
703 }
704 return this.db.prepare(`
705 SELECT entry_id, quest_id, step_id, text, written_at
706 FROM character_quest_journal
707 WHERE character_id = ?
708 ORDER BY written_at ASC, entry_id ASC
709 `).all(characterId | 0);
710 }
711
476 listFriendRecords (characterId)
712 listFriendRecords (characterId)
477 {
713 {
478 return this.db.prepare(`
714 return this.db.prepare(`
server/src/persistence/worldDb.js +386 −21
@@ -1,5 +1,13 @@
1 1 import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 2 import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
3 import {
4 OVERWORLD_ID,
5 DIMENSION_PURGE_MS,
6 defaultDimensionRecord,
7 normalizeDimensionRecord,
8 normalizeDimensionId,
9 isOverworld
10 } from "../../../shared/world/dimensions.js";
3 11 import { openDatabase, withTransaction } from "./database.js";
4 12
5 13 const WORLD_SCHEMA = `
@@ -11,12 +19,13 @@ CREATE TABLE IF NOT EXISTS world_revisions (
11 19 );
12 20
13 21 CREATE TABLE IF NOT EXISTS world_chunk_versions (
22 dimension_id TEXT NOT NULL DEFAULT 'overworld',
14 23 chunk_x INTEGER NOT NULL,
15 24 chunk_y INTEGER NOT NULL,
16 25 revision_id INTEGER NOT NULL,
17 26 open INTEGER NOT NULL,
18 27 data_blob TEXT NOT NULL,
19 PRIMARY KEY (chunk_x, chunk_y, revision_id)
28 PRIMARY KEY (dimension_id, chunk_x, chunk_y, revision_id)
20 29 );
21 30
22 31 CREATE TABLE IF NOT EXISTS world_meta (
@@ -31,6 +40,7 @@ CREATE TABLE IF NOT EXISTS world_settings (
31 40
32 41 CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
33 42 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
43 dimension_id TEXT NOT NULL DEFAULT 'overworld',
34 44 chunk_x INTEGER NOT NULL,
35 45 chunk_y INTEGER NOT NULL,
36 46 revision_id INTEGER NOT NULL,
@@ -52,6 +62,32 @@ CREATE TABLE IF NOT EXISTS world_settings_edit_log (
52 62 edited_at INTEGER NOT NULL,
53 63 diff_entries TEXT NOT NULL
54 64 );
65
66 CREATE TABLE IF NOT EXISTS world_quest_defs (
67 revision_id INTEGER NOT NULL,
68 quest_id TEXT NOT NULL,
69 def_blob TEXT NOT NULL,
70 PRIMARY KEY (revision_id, quest_id)
71 );
72
73 CREATE TABLE IF NOT EXISTS world_dialogue_trees (
74 revision_id INTEGER NOT NULL,
75 dialogue_id TEXT NOT NULL,
76 tree_blob TEXT NOT NULL,
77 PRIMARY KEY (revision_id, dialogue_id)
78 );
79
80 CREATE TABLE IF NOT EXISTS world_dimensions (
81 revision_id INTEGER NOT NULL,
82 dimension_id TEXT NOT NULL,
83 display_name TEXT NOT NULL,
84 lighting_mode TEXT NOT NULL,
85 season_mode TEXT NOT NULL,
86 default_ground_type_id INTEGER NOT NULL,
87 deleted_at INTEGER,
88 purge_after INTEGER,
89 PRIMARY KEY (revision_id, dimension_id)
90 );
55 91 `;
56 92
57 93 export class WorldDatabase
@@ -60,8 +96,72 @@ export class WorldDatabase
60 96 {
61 97 this.db = openDatabase(filePath);
62 98 this.db.exec(WORLD_SCHEMA);
99 this.#migrateChunkDimensionColumn();
63 100 this.#ensureInitialRevision();
64 101 this.#ensureLiveSettings();
102 this.#ensureOverworldDimension(this.getActiveRevisionId());
103 }
104
105 #migrateChunkDimensionColumn ()
106 {
107 const cols = this.db.prepare("PRAGMA table_info(world_chunk_versions)").all();
108 const hasDim = cols.some((col) => col.name === "dimension_id");
109 if (hasDim)
110 {
111 this.#migrateEditLogDimensionColumn();
112 return;
113 }
114
115 withTransaction(this.db, () =>
116 {
117 this.db.exec(`
118 CREATE TABLE world_chunk_versions_v2 (
119 dimension_id TEXT NOT NULL DEFAULT 'overworld',
120 chunk_x INTEGER NOT NULL,
121 chunk_y INTEGER NOT NULL,
122 revision_id INTEGER NOT NULL,
123 open INTEGER NOT NULL,
124 data_blob TEXT NOT NULL,
125 PRIMARY KEY (dimension_id, chunk_x, chunk_y, revision_id)
126 );
127 INSERT INTO world_chunk_versions_v2
128 (dimension_id, chunk_x, chunk_y, revision_id, open, data_blob)
129 SELECT 'overworld', chunk_x, chunk_y, revision_id, open, data_blob
130 FROM world_chunk_versions;
131 DROP TABLE world_chunk_versions;
132 ALTER TABLE world_chunk_versions_v2 RENAME TO world_chunk_versions;
133 `);
134 });
135 this.#migrateEditLogDimensionColumn();
136 }
137
138 #migrateEditLogDimensionColumn ()
139 {
140 const cols = this.db.prepare("PRAGMA table_info(world_chunk_edit_log)").all();
141 const hasDim = cols.some((col) => col.name === "dimension_id");
142 if (hasDim)
143 { return; }
144 withTransaction(this.db, () =>
145 {
146 this.db.exec(`
147 CREATE TABLE world_chunk_edit_log_v2 (
148 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
149 dimension_id TEXT NOT NULL DEFAULT 'overworld',
150 chunk_x INTEGER NOT NULL,
151 chunk_y INTEGER NOT NULL,
152 revision_id INTEGER NOT NULL,
153 editor_admin_id TEXT NOT NULL,
154 edited_at INTEGER NOT NULL,
155 diff_entries TEXT NOT NULL
156 );
157 INSERT INTO world_chunk_edit_log_v2
158 (log_id, dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
159 SELECT log_id, 'overworld', chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
160 FROM world_chunk_edit_log;
161 DROP TABLE world_chunk_edit_log;
162 ALTER TABLE world_chunk_edit_log_v2 RENAME TO world_chunk_edit_log;
163 `);
164 });
65 165 }
66 166
67 167 #ensureInitialRevision ()
@@ -82,6 +182,64 @@ export class WorldDatabase
82 182 revisionId,
83 183 JSON.stringify(DEFAULT_WORLD_SETTINGS)
84 184 );
185 this.#upsertDimensionRow(revisionId, defaultDimensionRecord(OVERWORLD_ID, {
186 defaultGroundTypeId: DEFAULT_WORLD_SETTINGS.defaultGroundTypeId
187 }));
188 });
189 }
190
191 #ensureOverworldDimension (revisionId)
192 {
193 if (revisionId == null)
194 { return; }
195 const existing = this.getDimension(revisionId, OVERWORLD_ID);
196 if (existing)
197 { return; }
198 const settings = this.getSettings(revisionId);
199 this.#upsertDimensionRow(revisionId, defaultDimensionRecord(OVERWORLD_ID, {
200 defaultGroundTypeId: settings.defaultGroundTypeId
201 }));
202 }
203
204 #upsertDimensionRow (revisionId, record)
205 {
206 const dim = normalizeDimensionRecord(record);
207 this.db.prepare(`
208 INSERT INTO world_dimensions (
209 revision_id, dimension_id, display_name, lighting_mode, season_mode,
210 default_ground_type_id, deleted_at, purge_after
211 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
212 ON CONFLICT(revision_id, dimension_id) DO UPDATE SET
213 display_name = excluded.display_name,
214 lighting_mode = excluded.lighting_mode,
215 season_mode = excluded.season_mode,
216 default_ground_type_id = excluded.default_ground_type_id,
217 deleted_at = excluded.deleted_at,
218 purge_after = excluded.purge_after
219 `).run(
220 revisionId,
221 dim.dimensionId,
222 dim.displayName,
223 dim.lightingMode,
224 dim.seasonMode,
225 dim.defaultGroundTypeId,
226 dim.deletedAt,
227 dim.purgeAfter
228 );
229 }
230
231 #rowToDimension (row)
232 {
233 if (!row)
234 { return null; }
235 return normalizeDimensionRecord({
236 dimensionId: row.dimension_id,
237 displayName: row.display_name,
238 lightingMode: row.lighting_mode,
239 seasonMode: row.season_mode,
240 defaultGroundTypeId: row.default_ground_type_id,
241 deletedAt: row.deleted_at,
242 purgeAfter: row.purge_after
85 243 });
86 244 }
87 245
@@ -171,24 +329,132 @@ export class WorldDatabase
171 329 : { ...DEFAULT_WORLD_SETTINGS };
172 330 }
173 331
174 getChunkVersion (chunkX, chunkY, revisionId)
332 listDimensions (revisionId)
175 333 {
334 this.#ensureOverworldDimension(revisionId);
176 335 return this.db.prepare(`
177 SELECT chunk_x, chunk_y, revision_id, open, data_blob
336 SELECT dimension_id, display_name, lighting_mode, season_mode,
337 default_ground_type_id, deleted_at, purge_after
338 FROM world_dimensions
339 WHERE revision_id = ?
340 ORDER BY dimension_id ASC
341 `).all(revisionId).map((row) => this.#rowToDimension(row));
342 }
343
344 getDimension (revisionId, dimensionId)
345 {
346 const id = normalizeDimensionId(dimensionId);
347 const row = this.db.prepare(`
348 SELECT dimension_id, display_name, lighting_mode, season_mode,
349 default_ground_type_id, deleted_at, purge_after
350 FROM world_dimensions
351 WHERE revision_id = ? AND dimension_id = ?
352 `).get(revisionId, id);
353 return this.#rowToDimension(row);
354 }
355
356 /** Latest dimension row at or before revision (for live fallback). */
357 getDimensionAtOrBefore (revisionId, dimensionId)
358 {
359 const id = normalizeDimensionId(dimensionId);
360 const row = this.db.prepare(`
361 SELECT dimension_id, display_name, lighting_mode, season_mode,
362 default_ground_type_id, deleted_at, purge_after
363 FROM world_dimensions
364 WHERE dimension_id = ? AND revision_id <= ?
365 ORDER BY revision_id DESC
366 LIMIT 1
367 `).get(id, revisionId);
368 return this.#rowToDimension(row);
369 }
370
371 saveDimension (revisionId, record)
372 {
373 const dim = normalizeDimensionRecord(record);
374 if (isOverworld(dim.dimensionId))
375 {
376 dim.deletedAt = null;
377 dim.purgeAfter = null;
378 }
379 this.#upsertDimensionRow(revisionId, dim);
380 return dim;
381 }
382
383 softDeleteDimension (revisionId, dimensionId, now = Date.now())
384 {
385 const id = normalizeDimensionId(dimensionId);
386 if (isOverworld(id))
387 { return { ok: false, error: "Cannot delete overworld." }; }
388 const existing = this.getDimension(revisionId, id) ?? defaultDimensionRecord(id);
389 existing.deletedAt = now;
390 existing.purgeAfter = now + DIMENSION_PURGE_MS;
391 this.#upsertDimensionRow(revisionId, existing);
392 return { ok: true, dimension: existing };
393 }
394
395 cancelDimensionDeletion (revisionId, dimensionId)
396 {
397 const id = normalizeDimensionId(dimensionId);
398 const existing = this.getDimension(revisionId, id);
399 if (!existing)
400 { return { ok: false, error: "Unknown dimension." }; }
401 existing.deletedAt = null;
402 existing.purgeAfter = null;
403 this.#upsertDimensionRow(revisionId, existing);
404 return { ok: true, dimension: existing };
405 }
406
407 /** Permanently remove dimensions past purge_after and all their chunk versions. */
408 purgeExpiredDimensions (now = Date.now())
409 {
410 const rows = this.db.prepare(`
411 SELECT DISTINCT dimension_id FROM world_dimensions
412 WHERE purge_after IS NOT NULL AND purge_after <= ? AND dimension_id != ?
413 `).all(now, OVERWORLD_ID);
414 let purged = 0;
415 for (const row of rows)
416 {
417 const id = row.dimension_id;
418 withTransaction(this.db, () =>
419 {
420 this.db.prepare("DELETE FROM world_chunk_versions WHERE dimension_id = ?").run(id);
421 this.db.prepare("DELETE FROM world_chunk_edit_log WHERE dimension_id = ?").run(id);
422 this.db.prepare("DELETE FROM world_dimensions WHERE dimension_id = ?").run(id);
423 });
424 purged += 1;
425 }
426 return purged;
427 }
428
429 getChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
430 {
431 const dim = normalizeDimensionId(dimensionId);
432 return this.db.prepare(`
433 SELECT dimension_id, chunk_x, chunk_y, revision_id, open, data_blob
178 434 FROM world_chunk_versions
179 WHERE chunk_x = ? AND chunk_y = ? AND revision_id <= ?
435 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ? AND revision_id <= ?
180 436 ORDER BY revision_id DESC
181 437 LIMIT 1
182 `).get(chunkX, chunkY, revisionId) ?? null;
438 `).get(dim, chunkX, chunkY, revisionId) ?? null;
183 439 }
184 440
185 listChunkCoords (revisionId)
441 listChunkCoords (revisionId, dimensionId = null)
186 442 {
443 if (dimensionId != null)
444 {
445 const dim = normalizeDimensionId(dimensionId);
446 return this.db.prepare(`
447 SELECT dimension_id, chunk_x, chunk_y, MAX(revision_id) AS revision_id
448 FROM world_chunk_versions
449 WHERE revision_id <= ? AND dimension_id = ?
450 GROUP BY dimension_id, chunk_x, chunk_y
451 `).all(revisionId, dim);
452 }
187 453 return this.db.prepare(`
188 SELECT chunk_x, chunk_y, MAX(revision_id) AS revision_id
454 SELECT dimension_id, chunk_x, chunk_y, MAX(revision_id) AS revision_id
189 455 FROM world_chunk_versions
190 456 WHERE revision_id <= ?
191 GROUP BY chunk_x, chunk_y
457 GROUP BY dimension_id, chunk_x, chunk_y
192 458 `).all(revisionId);
193 459 }
194 460
@@ -212,19 +478,115 @@ export class WorldDatabase
212 478 revisionId,
213 479 JSON.stringify(settings)
214 480 );
481 this.#copyQuestDefs(activeId, revisionId);
482 this.#copyDialogueTrees(activeId, revisionId);
483 this.#copyDimensions(activeId, revisionId);
215 484 return revisionId;
216 485 });
217 486 }
218 487
219 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob)
488 #copyDimensions (fromRevisionId, toRevisionId)
489 {
490 const rows = this.listDimensions(fromRevisionId);
491 for (const dim of rows)
492 { this.#upsertDimensionRow(toRevisionId, dim); }
493 this.#ensureOverworldDimension(toRevisionId);
494 }
495
496 #copyQuestDefs (fromRevisionId, toRevisionId)
497 {
498 const rows = this.listQuestDefs(fromRevisionId);
499 const insert = this.db.prepare(`
500 INSERT INTO world_quest_defs (revision_id, quest_id, def_blob)
501 VALUES (?, ?, ?)
502 `);
503 for (const def of rows)
504 { insert.run(toRevisionId, def.questId, JSON.stringify(def)); }
505 }
506
507 #copyDialogueTrees (fromRevisionId, toRevisionId)
508 {
509 const rows = this.listDialogueTrees(fromRevisionId);
510 const insert = this.db.prepare(`
511 INSERT INTO world_dialogue_trees (revision_id, dialogue_id, tree_blob)
512 VALUES (?, ?, ?)
513 `);
514 for (const tree of rows)
515 { insert.run(toRevisionId, tree.dialogueId, JSON.stringify(tree)); }
516 }
517
518 listQuestDefs (revisionId)
519 {
520 return this.db.prepare(`
521 SELECT quest_id, def_blob FROM world_quest_defs WHERE revision_id = ?
522 `).all(revisionId).map((row) => JSON.parse(row.def_blob));
523 }
524
525 getQuestDef (revisionId, questId)
526 {
527 const row = this.db.prepare(`
528 SELECT def_blob FROM world_quest_defs WHERE revision_id = ? AND quest_id = ?
529 `).get(revisionId, questId);
530 return row ? JSON.parse(row.def_blob) : null;
531 }
532
533 saveQuestDef (revisionId, def)
220 534 {
221 535 this.db.prepare(`
222 INSERT INTO world_chunk_versions (chunk_x, chunk_y, revision_id, open, data_blob)
223 VALUES (?, ?, ?, ?, ?)
224 ON CONFLICT(chunk_x, chunk_y, revision_id) DO UPDATE SET
536 INSERT INTO world_quest_defs (revision_id, quest_id, def_blob)
537 VALUES (?, ?, ?)
538 ON CONFLICT(revision_id, quest_id) DO UPDATE SET def_blob = excluded.def_blob
539 `).run(revisionId, def.questId, JSON.stringify(def));
540 }
541
542 deleteQuestDef (revisionId, questId)
543 {
544 this.db.prepare(`
545 DELETE FROM world_quest_defs WHERE revision_id = ? AND quest_id = ?
546 `).run(revisionId, questId);
547 }
548
549 listDialogueTrees (revisionId)
550 {
551 return this.db.prepare(`
552 SELECT dialogue_id, tree_blob FROM world_dialogue_trees WHERE revision_id = ?
553 `).all(revisionId).map((row) => JSON.parse(row.tree_blob));
554 }
555
556 getDialogueTree (revisionId, dialogueId)
557 {
558 const row = this.db.prepare(`
559 SELECT tree_blob FROM world_dialogue_trees WHERE revision_id = ? AND dialogue_id = ?
560 `).get(revisionId, dialogueId);
561 return row ? JSON.parse(row.tree_blob) : null;
562 }
563
564 saveDialogueTree (revisionId, tree)
565 {
566 this.db.prepare(`
567 INSERT INTO world_dialogue_trees (revision_id, dialogue_id, tree_blob)
568 VALUES (?, ?, ?)
569 ON CONFLICT(revision_id, dialogue_id) DO UPDATE SET tree_blob = excluded.tree_blob
570 `).run(revisionId, tree.dialogueId, JSON.stringify(tree));
571 }
572
573 deleteDialogueTree (revisionId, dialogueId)
574 {
575 this.db.prepare(`
576 DELETE FROM world_dialogue_trees WHERE revision_id = ? AND dialogue_id = ?
577 `).run(revisionId, dialogueId);
578 }
579
580 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob, dimensionId = OVERWORLD_ID)
581 {
582 const dim = normalizeDimensionId(dimensionId);
583 this.db.prepare(`
584 INSERT INTO world_chunk_versions (dimension_id, chunk_x, chunk_y, revision_id, open, data_blob)
585 VALUES (?, ?, ?, ?, ?, ?)
586 ON CONFLICT(dimension_id, chunk_x, chunk_y, revision_id) DO UPDATE SET
225 587 open = excluded.open,
226 588 data_blob = excluded.data_blob
227 `).run(chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
589 `).run(dim, chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
228 590 }
229 591
230 592 saveSettings (revisionId, settings)
@@ -236,24 +598,27 @@ export class WorldDatabase
236 598 `).run(revisionId, JSON.stringify(settings));
237 599 }
238 600
239 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries)
601 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimensionId = OVERWORLD_ID)
240 602 {
603 const dim = normalizeDimensionId(dimensionId);
241 604 this.db.prepare(`
242 605 INSERT INTO world_chunk_edit_log
243 (chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
244 VALUES (?, ?, ?, ?, ?, ?)
245 `).run(chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
606 (dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
607 VALUES (?, ?, ?, ?, ?, ?, ?)
608 `).run(dim, chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
246 609 }
247 610
248 listChangelog (chunkX, chunkY)
611 listChangelog (chunkX, chunkY, dimensionId = OVERWORLD_ID)
249 612 {
613 const dim = normalizeDimensionId(dimensionId);
250 614 return this.db.prepare(`
251 SELECT log_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
615 SELECT log_id, dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
252 616 FROM world_chunk_edit_log
253 WHERE chunk_x = ? AND chunk_y = ?
617 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ?
254 618 ORDER BY edited_at ASC, log_id ASC
255 `).all(chunkX, chunkY).map((row) => ({
619 `).all(dim, chunkX, chunkY).map((row) => ({
256 620 ...row,
621 dimensionId: row.dimension_id,
257 622 diffEntries: JSON.parse(row.diff_entries)
258 623 }));
259 624 }
@@ -1,5 +1,13 @@
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
2import { normalizeStarterLoadout } from "../../../shared/items/starterLoadout.js";
3import {
4 OVERWORLD_ID,
5 DIMENSION_PURGE_MS,
6 defaultDimensionRecord,
7 normalizeDimensionRecord,
8 normalizeDimensionId,
9 isOverworld
10} from "../../../shared/world/dimensions.js";
3import { openDatabase, withTransaction } from "./database.js";
11import { openDatabase, withTransaction } from "./database.js";
4
12
5const WORLD_SCHEMA = `
13const WORLD_SCHEMA = `
@@ -11,12 +19,13 @@ CREATE TABLE IF NOT EXISTS world_revisions (
11);
19);
12
20
13CREATE TABLE IF NOT EXISTS world_chunk_versions (
21CREATE TABLE IF NOT EXISTS world_chunk_versions (
22 dimension_id TEXT NOT NULL DEFAULT 'overworld',
14 chunk_x INTEGER NOT NULL,
23 chunk_x INTEGER NOT NULL,
15 chunk_y INTEGER NOT NULL,
24 chunk_y INTEGER NOT NULL,
16 revision_id INTEGER NOT NULL,
25 revision_id INTEGER NOT NULL,
17 open INTEGER NOT NULL,
26 open INTEGER NOT NULL,
18 data_blob TEXT NOT NULL,
27 data_blob TEXT NOT NULL,
19 PRIMARY KEY (chunk_x, chunk_y, revision_id)
28 PRIMARY KEY (dimension_id, chunk_x, chunk_y, revision_id)
20);
29);
21
30
22CREATE TABLE IF NOT EXISTS world_meta (
31CREATE TABLE IF NOT EXISTS world_meta (
@@ -31,6 +40,7 @@ CREATE TABLE IF NOT EXISTS world_settings (
31
40
32CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
41CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
33 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
42 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
43 dimension_id TEXT NOT NULL DEFAULT 'overworld',
34 chunk_x INTEGER NOT NULL,
44 chunk_x INTEGER NOT NULL,
35 chunk_y INTEGER NOT NULL,
45 chunk_y INTEGER NOT NULL,
36 revision_id INTEGER NOT NULL,
46 revision_id INTEGER NOT NULL,
@@ -52,6 +62,32 @@ CREATE TABLE IF NOT EXISTS world_settings_edit_log (
52 edited_at INTEGER NOT NULL,
62 edited_at INTEGER NOT NULL,
53 diff_entries TEXT NOT NULL
63 diff_entries TEXT NOT NULL
54);
64);
65
66CREATE TABLE IF NOT EXISTS world_quest_defs (
67 revision_id INTEGER NOT NULL,
68 quest_id TEXT NOT NULL,
69 def_blob TEXT NOT NULL,
70 PRIMARY KEY (revision_id, quest_id)
71);
72
73CREATE TABLE IF NOT EXISTS world_dialogue_trees (
74 revision_id INTEGER NOT NULL,
75 dialogue_id TEXT NOT NULL,
76 tree_blob TEXT NOT NULL,
77 PRIMARY KEY (revision_id, dialogue_id)
78);
79
80CREATE TABLE IF NOT EXISTS world_dimensions (
81 revision_id INTEGER NOT NULL,
82 dimension_id TEXT NOT NULL,
83 display_name TEXT NOT NULL,
84 lighting_mode TEXT NOT NULL,
85 season_mode TEXT NOT NULL,
86 default_ground_type_id INTEGER NOT NULL,
87 deleted_at INTEGER,
88 purge_after INTEGER,
89 PRIMARY KEY (revision_id, dimension_id)
90);
55`;
91`;
56
92
57export class WorldDatabase
93export class WorldDatabase
@@ -60,8 +96,72 @@ export class WorldDatabase
60 {
96 {
61 this.db = openDatabase(filePath);
97 this.db = openDatabase(filePath);
62 this.db.exec(WORLD_SCHEMA);
98 this.db.exec(WORLD_SCHEMA);
99 this.#migrateChunkDimensionColumn();
63 this.#ensureInitialRevision();
100 this.#ensureInitialRevision();
64 this.#ensureLiveSettings();
101 this.#ensureLiveSettings();
102 this.#ensureOverworldDimension(this.getActiveRevisionId());
103 }
104
105 #migrateChunkDimensionColumn ()
106 {
107 const cols = this.db.prepare("PRAGMA table_info(world_chunk_versions)").all();
108 const hasDim = cols.some((col) => col.name === "dimension_id");
109 if (hasDim)
110 {
111 this.#migrateEditLogDimensionColumn();
112 return;
113 }
114
115 withTransaction(this.db, () =>
116 {
117 this.db.exec(`
118 CREATE TABLE world_chunk_versions_v2 (
119 dimension_id TEXT NOT NULL DEFAULT 'overworld',
120 chunk_x INTEGER NOT NULL,
121 chunk_y INTEGER NOT NULL,
122 revision_id INTEGER NOT NULL,
123 open INTEGER NOT NULL,
124 data_blob TEXT NOT NULL,
125 PRIMARY KEY (dimension_id, chunk_x, chunk_y, revision_id)
126 );
127 INSERT INTO world_chunk_versions_v2
128 (dimension_id, chunk_x, chunk_y, revision_id, open, data_blob)
129 SELECT 'overworld', chunk_x, chunk_y, revision_id, open, data_blob
130 FROM world_chunk_versions;
131 DROP TABLE world_chunk_versions;
132 ALTER TABLE world_chunk_versions_v2 RENAME TO world_chunk_versions;
133 `);
134 });
135 this.#migrateEditLogDimensionColumn();
136 }
137
138 #migrateEditLogDimensionColumn ()
139 {
140 const cols = this.db.prepare("PRAGMA table_info(world_chunk_edit_log)").all();
141 const hasDim = cols.some((col) => col.name === "dimension_id");
142 if (hasDim)
143 { return; }
144 withTransaction(this.db, () =>
145 {
146 this.db.exec(`
147 CREATE TABLE world_chunk_edit_log_v2 (
148 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
149 dimension_id TEXT NOT NULL DEFAULT 'overworld',
150 chunk_x INTEGER NOT NULL,
151 chunk_y INTEGER NOT NULL,
152 revision_id INTEGER NOT NULL,
153 editor_admin_id TEXT NOT NULL,
154 edited_at INTEGER NOT NULL,
155 diff_entries TEXT NOT NULL
156 );
157 INSERT INTO world_chunk_edit_log_v2
158 (log_id, dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
159 SELECT log_id, 'overworld', chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
160 FROM world_chunk_edit_log;
161 DROP TABLE world_chunk_edit_log;
162 ALTER TABLE world_chunk_edit_log_v2 RENAME TO world_chunk_edit_log;
163 `);
164 });
65 }
165 }
66
166
67 #ensureInitialRevision ()
167 #ensureInitialRevision ()
@@ -82,6 +182,64 @@ export class WorldDatabase
82 revisionId,
182 revisionId,
83 JSON.stringify(DEFAULT_WORLD_SETTINGS)
183 JSON.stringify(DEFAULT_WORLD_SETTINGS)
84 );
184 );
185 this.#upsertDimensionRow(revisionId, defaultDimensionRecord(OVERWORLD_ID, {
186 defaultGroundTypeId: DEFAULT_WORLD_SETTINGS.defaultGroundTypeId
187 }));
188 });
189 }
190
191 #ensureOverworldDimension (revisionId)
192 {
193 if (revisionId == null)
194 { return; }
195 const existing = this.getDimension(revisionId, OVERWORLD_ID);
196 if (existing)
197 { return; }
198 const settings = this.getSettings(revisionId);
199 this.#upsertDimensionRow(revisionId, defaultDimensionRecord(OVERWORLD_ID, {
200 defaultGroundTypeId: settings.defaultGroundTypeId
201 }));
202 }
203
204 #upsertDimensionRow (revisionId, record)
205 {
206 const dim = normalizeDimensionRecord(record);
207 this.db.prepare(`
208 INSERT INTO world_dimensions (
209 revision_id, dimension_id, display_name, lighting_mode, season_mode,
210 default_ground_type_id, deleted_at, purge_after
211 ) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
212 ON CONFLICT(revision_id, dimension_id) DO UPDATE SET
213 display_name = excluded.display_name,
214 lighting_mode = excluded.lighting_mode,
215 season_mode = excluded.season_mode,
216 default_ground_type_id = excluded.default_ground_type_id,
217 deleted_at = excluded.deleted_at,
218 purge_after = excluded.purge_after
219 `).run(
220 revisionId,
221 dim.dimensionId,
222 dim.displayName,
223 dim.lightingMode,
224 dim.seasonMode,
225 dim.defaultGroundTypeId,
226 dim.deletedAt,
227 dim.purgeAfter
228 );
229 }
230
231 #rowToDimension (row)
232 {
233 if (!row)
234 { return null; }
235 return normalizeDimensionRecord({
236 dimensionId: row.dimension_id,
237 displayName: row.display_name,
238 lightingMode: row.lighting_mode,
239 seasonMode: row.season_mode,
240 defaultGroundTypeId: row.default_ground_type_id,
241 deletedAt: row.deleted_at,
242 purgeAfter: row.purge_after
85 });
243 });
86 }
244 }
87
245
@@ -171,24 +329,132 @@ export class WorldDatabase
171 : { ...DEFAULT_WORLD_SETTINGS };
329 : { ...DEFAULT_WORLD_SETTINGS };
172 }
330 }
173
331
174 getChunkVersion (chunkX, chunkY, revisionId)
332 listDimensions (revisionId)
175 {
333 {
334 this.#ensureOverworldDimension(revisionId);
176 return this.db.prepare(`
335 return this.db.prepare(`
177 SELECT chunk_x, chunk_y, revision_id, open, data_blob
336 SELECT dimension_id, display_name, lighting_mode, season_mode,
337 default_ground_type_id, deleted_at, purge_after
338 FROM world_dimensions
339 WHERE revision_id = ?
340 ORDER BY dimension_id ASC
341 `).all(revisionId).map((row) => this.#rowToDimension(row));
342 }
343
344 getDimension (revisionId, dimensionId)
345 {
346 const id = normalizeDimensionId(dimensionId);
347 const row = this.db.prepare(`
348 SELECT dimension_id, display_name, lighting_mode, season_mode,
349 default_ground_type_id, deleted_at, purge_after
350 FROM world_dimensions
351 WHERE revision_id = ? AND dimension_id = ?
352 `).get(revisionId, id);
353 return this.#rowToDimension(row);
354 }
355
356 /** Latest dimension row at or before revision (for live fallback). */
357 getDimensionAtOrBefore (revisionId, dimensionId)
358 {
359 const id = normalizeDimensionId(dimensionId);
360 const row = this.db.prepare(`
361 SELECT dimension_id, display_name, lighting_mode, season_mode,
362 default_ground_type_id, deleted_at, purge_after
363 FROM world_dimensions
364 WHERE dimension_id = ? AND revision_id <= ?
365 ORDER BY revision_id DESC
366 LIMIT 1
367 `).get(id, revisionId);
368 return this.#rowToDimension(row);
369 }
370
371 saveDimension (revisionId, record)
372 {
373 const dim = normalizeDimensionRecord(record);
374 if (isOverworld(dim.dimensionId))
375 {
376 dim.deletedAt = null;
377 dim.purgeAfter = null;
378 }
379 this.#upsertDimensionRow(revisionId, dim);
380 return dim;
381 }
382
383 softDeleteDimension (revisionId, dimensionId, now = Date.now())
384 {
385 const id = normalizeDimensionId(dimensionId);
386 if (isOverworld(id))
387 { return { ok: false, error: "Cannot delete overworld." }; }
388 const existing = this.getDimension(revisionId, id) ?? defaultDimensionRecord(id);
389 existing.deletedAt = now;
390 existing.purgeAfter = now + DIMENSION_PURGE_MS;
391 this.#upsertDimensionRow(revisionId, existing);
392 return { ok: true, dimension: existing };
393 }
394
395 cancelDimensionDeletion (revisionId, dimensionId)
396 {
397 const id = normalizeDimensionId(dimensionId);
398 const existing = this.getDimension(revisionId, id);
399 if (!existing)
400 { return { ok: false, error: "Unknown dimension." }; }
401 existing.deletedAt = null;
402 existing.purgeAfter = null;
403 this.#upsertDimensionRow(revisionId, existing);
404 return { ok: true, dimension: existing };
405 }
406
407 /** Permanently remove dimensions past purge_after and all their chunk versions. */
408 purgeExpiredDimensions (now = Date.now())
409 {
410 const rows = this.db.prepare(`
411 SELECT DISTINCT dimension_id FROM world_dimensions
412 WHERE purge_after IS NOT NULL AND purge_after <= ? AND dimension_id != ?
413 `).all(now, OVERWORLD_ID);
414 let purged = 0;
415 for (const row of rows)
416 {
417 const id = row.dimension_id;
418 withTransaction(this.db, () =>
419 {
420 this.db.prepare("DELETE FROM world_chunk_versions WHERE dimension_id = ?").run(id);
421 this.db.prepare("DELETE FROM world_chunk_edit_log WHERE dimension_id = ?").run(id);
422 this.db.prepare("DELETE FROM world_dimensions WHERE dimension_id = ?").run(id);
423 });
424 purged += 1;
425 }
426 return purged;
427 }
428
429 getChunkVersion (chunkX, chunkY, revisionId, dimensionId = OVERWORLD_ID)
430 {
431 const dim = normalizeDimensionId(dimensionId);
432 return this.db.prepare(`
433 SELECT dimension_id, chunk_x, chunk_y, revision_id, open, data_blob
178 FROM world_chunk_versions
434 FROM world_chunk_versions
179 WHERE chunk_x = ? AND chunk_y = ? AND revision_id <= ?
435 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ? AND revision_id <= ?
180 ORDER BY revision_id DESC
436 ORDER BY revision_id DESC
181 LIMIT 1
437 LIMIT 1
182 `).get(chunkX, chunkY, revisionId) ?? null;
438 `).get(dim, chunkX, chunkY, revisionId) ?? null;
183 }
439 }
184
440
185 listChunkCoords (revisionId)
441 listChunkCoords (revisionId, dimensionId = null)
186 {
442 {
443 if (dimensionId != null)
444 {
445 const dim = normalizeDimensionId(dimensionId);
446 return this.db.prepare(`
447 SELECT dimension_id, chunk_x, chunk_y, MAX(revision_id) AS revision_id
448 FROM world_chunk_versions
449 WHERE revision_id <= ? AND dimension_id = ?
450 GROUP BY dimension_id, chunk_x, chunk_y
451 `).all(revisionId, dim);
452 }
187 return this.db.prepare(`
453 return this.db.prepare(`
188 SELECT chunk_x, chunk_y, MAX(revision_id) AS revision_id
454 SELECT dimension_id, chunk_x, chunk_y, MAX(revision_id) AS revision_id
189 FROM world_chunk_versions
455 FROM world_chunk_versions
190 WHERE revision_id <= ?
456 WHERE revision_id <= ?
191 GROUP BY chunk_x, chunk_y
457 GROUP BY dimension_id, chunk_x, chunk_y
192 `).all(revisionId);
458 `).all(revisionId);
193 }
459 }
194
460
@@ -212,19 +478,115 @@ export class WorldDatabase
212 revisionId,
478 revisionId,
213 JSON.stringify(settings)
479 JSON.stringify(settings)
214 );
480 );
481 this.#copyQuestDefs(activeId, revisionId);
482 this.#copyDialogueTrees(activeId, revisionId);
483 this.#copyDimensions(activeId, revisionId);
215 return revisionId;
484 return revisionId;
216 });
485 });
217 }
486 }
218
487
219 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob)
488 #copyDimensions (fromRevisionId, toRevisionId)
489 {
490 const rows = this.listDimensions(fromRevisionId);
491 for (const dim of rows)
492 { this.#upsertDimensionRow(toRevisionId, dim); }
493 this.#ensureOverworldDimension(toRevisionId);
494 }
495
496 #copyQuestDefs (fromRevisionId, toRevisionId)
497 {
498 const rows = this.listQuestDefs(fromRevisionId);
499 const insert = this.db.prepare(`
500 INSERT INTO world_quest_defs (revision_id, quest_id, def_blob)
501 VALUES (?, ?, ?)
502 `);
503 for (const def of rows)
504 { insert.run(toRevisionId, def.questId, JSON.stringify(def)); }
505 }
506
507 #copyDialogueTrees (fromRevisionId, toRevisionId)
508 {
509 const rows = this.listDialogueTrees(fromRevisionId);
510 const insert = this.db.prepare(`
511 INSERT INTO world_dialogue_trees (revision_id, dialogue_id, tree_blob)
512 VALUES (?, ?, ?)
513 `);
514 for (const tree of rows)
515 { insert.run(toRevisionId, tree.dialogueId, JSON.stringify(tree)); }
516 }
517
518 listQuestDefs (revisionId)
519 {
520 return this.db.prepare(`
521 SELECT quest_id, def_blob FROM world_quest_defs WHERE revision_id = ?
522 `).all(revisionId).map((row) => JSON.parse(row.def_blob));
523 }
524
525 getQuestDef (revisionId, questId)
526 {
527 const row = this.db.prepare(`
528 SELECT def_blob FROM world_quest_defs WHERE revision_id = ? AND quest_id = ?
529 `).get(revisionId, questId);
530 return row ? JSON.parse(row.def_blob) : null;
531 }
532
533 saveQuestDef (revisionId, def)
220 {
534 {
221 this.db.prepare(`
535 this.db.prepare(`
222 INSERT INTO world_chunk_versions (chunk_x, chunk_y, revision_id, open, data_blob)
536 INSERT INTO world_quest_defs (revision_id, quest_id, def_blob)
223 VALUES (?, ?, ?, ?, ?)
537 VALUES (?, ?, ?)
224 ON CONFLICT(chunk_x, chunk_y, revision_id) DO UPDATE SET
538 ON CONFLICT(revision_id, quest_id) DO UPDATE SET def_blob = excluded.def_blob
539 `).run(revisionId, def.questId, JSON.stringify(def));
540 }
541
542 deleteQuestDef (revisionId, questId)
543 {
544 this.db.prepare(`
545 DELETE FROM world_quest_defs WHERE revision_id = ? AND quest_id = ?
546 `).run(revisionId, questId);
547 }
548
549 listDialogueTrees (revisionId)
550 {
551 return this.db.prepare(`
552 SELECT dialogue_id, tree_blob FROM world_dialogue_trees WHERE revision_id = ?
553 `).all(revisionId).map((row) => JSON.parse(row.tree_blob));
554 }
555
556 getDialogueTree (revisionId, dialogueId)
557 {
558 const row = this.db.prepare(`
559 SELECT tree_blob FROM world_dialogue_trees WHERE revision_id = ? AND dialogue_id = ?
560 `).get(revisionId, dialogueId);
561 return row ? JSON.parse(row.tree_blob) : null;
562 }
563
564 saveDialogueTree (revisionId, tree)
565 {
566 this.db.prepare(`
567 INSERT INTO world_dialogue_trees (revision_id, dialogue_id, tree_blob)
568 VALUES (?, ?, ?)
569 ON CONFLICT(revision_id, dialogue_id) DO UPDATE SET tree_blob = excluded.tree_blob
570 `).run(revisionId, tree.dialogueId, JSON.stringify(tree));
571 }
572
573 deleteDialogueTree (revisionId, dialogueId)
574 {
575 this.db.prepare(`
576 DELETE FROM world_dialogue_trees WHERE revision_id = ? AND dialogue_id = ?
577 `).run(revisionId, dialogueId);
578 }
579
580 saveChunkVersion (chunkX, chunkY, revisionId, open, dataBlob, dimensionId = OVERWORLD_ID)
581 {
582 const dim = normalizeDimensionId(dimensionId);
583 this.db.prepare(`
584 INSERT INTO world_chunk_versions (dimension_id, chunk_x, chunk_y, revision_id, open, data_blob)
585 VALUES (?, ?, ?, ?, ?, ?)
586 ON CONFLICT(dimension_id, chunk_x, chunk_y, revision_id) DO UPDATE SET
225 open = excluded.open,
587 open = excluded.open,
226 data_blob = excluded.data_blob
588 data_blob = excluded.data_blob
227 `).run(chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
589 `).run(dim, chunkX, chunkY, revisionId, open ? 1 : 0, dataBlob);
228 }
590 }
229
591
230 saveSettings (revisionId, settings)
592 saveSettings (revisionId, settings)
@@ -236,24 +598,27 @@ export class WorldDatabase
236 `).run(revisionId, JSON.stringify(settings));
598 `).run(revisionId, JSON.stringify(settings));
237 }
599 }
238
600
239 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries)
601 appendChangelog (chunkX, chunkY, revisionId, editorAdminId, diffEntries, dimensionId = OVERWORLD_ID)
240 {
602 {
603 const dim = normalizeDimensionId(dimensionId);
241 this.db.prepare(`
604 this.db.prepare(`
242 INSERT INTO world_chunk_edit_log
605 INSERT INTO world_chunk_edit_log
243 (chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
606 (dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries)
244 VALUES (?, ?, ?, ?, ?, ?)
607 VALUES (?, ?, ?, ?, ?, ?, ?)
245 `).run(chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
608 `).run(dim, chunkX, chunkY, revisionId, editorAdminId, Date.now(), JSON.stringify(diffEntries));
246 }
609 }
247
610
248 listChangelog (chunkX, chunkY)
611 listChangelog (chunkX, chunkY, dimensionId = OVERWORLD_ID)
249 {
612 {
613 const dim = normalizeDimensionId(dimensionId);
250 return this.db.prepare(`
614 return this.db.prepare(`
251 SELECT log_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
615 SELECT log_id, dimension_id, chunk_x, chunk_y, revision_id, editor_admin_id, edited_at, diff_entries
252 FROM world_chunk_edit_log
616 FROM world_chunk_edit_log
253 WHERE chunk_x = ? AND chunk_y = ?
617 WHERE dimension_id = ? AND chunk_x = ? AND chunk_y = ?
254 ORDER BY edited_at ASC, log_id ASC
618 ORDER BY edited_at ASC, log_id ASC
255 `).all(chunkX, chunkY).map((row) => ({
619 `).all(dim, chunkX, chunkY).map((row) => ({
256 ...row,
620 ...row,
621 dimensionId: row.dimension_id,
257 diffEntries: JSON.parse(row.diff_entries)
622 diffEntries: JSON.parse(row.diff_entries)
258 }));
623 }));
259 }
624 }
server/src/quests/contentCache.js added +47 −0
@@ -0,0 +1,47 @@
1 import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
2
3 /** Active-revision quest + dialogue defs for the live sim. */
4 export class QuestContentCache
5 {
6 constructor (worldDb)
7 {
8 this.worldDb = worldDb;
9 this.quests = new Map();
10 this.dialogues = new Map();
11 this.reload();
12 }
13
14 reload ()
15 {
16 const revisionId = this.worldDb.getActiveRevisionId();
17 this.quests = new Map();
18 this.dialogues = new Map();
19 if (revisionId == null)
20 { return; }
21 for (const raw of this.worldDb.listQuestDefs(revisionId))
22 {
23 const def = normalizeQuestDef(raw);
24 this.quests.set(def.questId, def);
25 }
26 for (const raw of this.worldDb.listDialogueTrees(revisionId))
27 {
28 const tree = normalizeDialogueTree(raw);
29 this.dialogues.set(tree.dialogueId, tree);
30 }
31 }
32
33 quest (questId)
34 {
35 return this.quests.get(String(questId)) ?? null;
36 }
37
38 dialogue (dialogueId)
39 {
40 return this.dialogues.get(String(dialogueId)) ?? null;
41 }
42
43 allQuests ()
44 {
45 return [...this.quests.values()];
46 }
47 }
@@ -0,0 +1,47 @@
1import { normalizeQuestDef, normalizeDialogueTree } from "../../../shared/quests/normalize.js";
2
3/** Active-revision quest + dialogue defs for the live sim. */
4export class QuestContentCache
5{
6 constructor (worldDb)
7 {
8 this.worldDb = worldDb;
9 this.quests = new Map();
10 this.dialogues = new Map();
11 this.reload();
12 }
13
14 reload ()
15 {
16 const revisionId = this.worldDb.getActiveRevisionId();
17 this.quests = new Map();
18 this.dialogues = new Map();
19 if (revisionId == null)
20 { return; }
21 for (const raw of this.worldDb.listQuestDefs(revisionId))
22 {
23 const def = normalizeQuestDef(raw);
24 this.quests.set(def.questId, def);
25 }
26 for (const raw of this.worldDb.listDialogueTrees(revisionId))
27 {
28 const tree = normalizeDialogueTree(raw);
29 this.dialogues.set(tree.dialogueId, tree);
30 }
31 }
32
33 quest (questId)
34 {
35 return this.quests.get(String(questId)) ?? null;
36 }
37
38 dialogue (dialogueId)
39 {
40 return this.dialogues.get(String(dialogueId)) ?? null;
41 }
42
43 allQuests ()
44 {
45 return [...this.quests.values()];
46 }
47}
server/src/quests/runtime.js added +593 −0
@@ -0,0 +1,593 @@
1 import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2 import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3 import { itemDefinition } from "../../../shared/definitions/items.js";
4 import { applySkillXp } from "../../../shared/skills/state.js";
5 import { skillLevel } from "../../../shared/definitions/skills.js";
6 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
7 import { floorDiv } from "../world/coordinates.js";
8 import { WorkerMessage } from "../simulation/protocol.js";
9
10 /**
11 * Quest progress + dialogue sessions (main simulation thread).
12 */
13 export class QuestRuntime
14 {
15 constructor ({ stateDb, content, simulation })
16 {
17 this.stateDb = stateDb;
18 this.content = content;
19 this.simulation = simulation;
20 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
21 this.sessions = new Map();
22 }
23
24 reloadContent ()
25 {
26 this.content.reload();
27 }
28
29 closeAllSessions ()
30 {
31 for (const characterId of [...this.sessions.keys()])
32 { this.closeDialogue(characterId, "revision"); }
33 }
34
35 questSnapshot (characterId)
36 {
37 const states = this.stateDb.listQuestStates(characterId)
38 .filter((row) => row.state !== "not-started");
39 const quests = [];
40 for (const row of states)
41 {
42 const def = this.content.quest(row.questId);
43 if (!def)
44 {
45 quests.push({
46 questId: row.questId,
47 title: "Quest unavailable",
48 orphaned: true,
49 state: row.state,
50 description: "",
51 step: null,
52 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
53 });
54 continue;
55 }
56 const stepIndex = typeof row.state === "number" ? row.state : null;
57 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
58 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
59 quests.push({
60 questId: def.questId,
61 title: def.title,
62 orphaned: false,
63 state: row.state,
64 description: def.description,
65 step: stepDef
66 ? {
67 stepId: stepDef.stepId,
68 title: stepDef.title,
69 description: stepDef.description,
70 objectives: stepDef.objectives.map((obj) => ({
71 objectiveId: obj.objectiveId,
72 text: obj.text,
73 done: completedObjectiveIds.includes(obj.objectiveId)
74 }))
75 }
76 : null,
77 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
78 });
79 }
80 quests.sort((a, b) =>
81 {
82 const aDone = a.state === "completed" ? 1 : 0;
83 const bDone = b.state === "completed" ? 1 : 0;
84 if (aDone !== bDone)
85 { return aDone - bDone; }
86 return String(a.title).localeCompare(String(b.title));
87 });
88 return { quests };
89 }
90
91 playerViewFor (characterId)
92 {
93 const entityId = this.simulation.characterEntities.get(characterId | 0);
94 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
95 const skills = this.stateDb.getSkills(characterId) ?? {};
96 let hp = 1;
97 let maxHp = 1;
98 let stamina = 1;
99 let maxStamina = 1;
100 if (entityId != null && record)
101 {
102 const staminaComp = this.simulation.staminaOf(entityId);
103 if (staminaComp)
104 {
105 stamina = Number(staminaComp.current) || 0;
106 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
107 }
108 const worker = this.simulation.workers[record.workerId];
109 const view = worker?.call?.({
110 type: WorkerMessage.inspect,
111 entityId
112 });
113 if (view && view.health != null)
114 {
115 hp = Number(view.health) || 0;
116 maxHp = Math.max(1, Number(view.maxHealth) || 1);
117 }
118 }
119 return {
120 tileX: record?.tileX | 0,
121 tileY: record?.tileY | 0,
122 dimensionId: record?.dimensionId ?? "overworld",
123 skills,
124 hp,
125 maxHp,
126 stamina,
127 maxStamina
128 };
129 }
130
131 buildConditionContext (characterId, playerView, activeQuestId = null)
132 {
133 const bag = this.#loadBag(characterId);
134 const inventory = bag?.inventory ?? [];
135 const tileX = playerView?.tileX | 0;
136 const tileY = playerView?.tileY | 0;
137 const dimensionId = playerView?.dimensionId ?? "overworld";
138 const chunkX = floorDiv(tileX, CHUNK_SIZE);
139 const chunkY = floorDiv(tileY, CHUNK_SIZE);
140 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
141 return {
142 tileX,
143 tileY,
144 chunkX,
145 chunkY,
146 dimensionId,
147 hp: playerView?.hp ?? 0,
148 maxHp: playerView?.maxHp ?? 1,
149 stamina: playerView?.stamina ?? 0,
150 maxStamina: playerView?.maxStamina ?? 1,
151 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
152 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
153 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
154 dialogueTriggerLatched: (dialogueId, trigger) =>
155 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
156 skillLevel: (skillId) => skillLevel(playerView?.skills ?? {}, skillId),
157 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
158 killCount: (condition) =>
159 {
160 if (!questRow)
161 { return 0; }
162 return questRow.progress?.counters?.[killKey(condition)] | 0;
163 },
164 interactBlockDone: (condition) =>
165 {
166 if (!questRow)
167 { return false; }
168 return !!questRow.progress?.interacts?.[interactKey(condition)];
169 }
170 };
171 }
172
173 tryOpenDialogue (characterId, entityId, dialogueId)
174 {
175 const tree = this.content.dialogue(dialogueId);
176 if (!tree)
177 { return { ok: false, error: "Nothing to say." }; }
178 this.closeDialogue(characterId, "replace");
179 const playerView = this.playerViewFor(characterId);
180 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
181 }
182
183 chooseDialogue (characterId, triggerId)
184 {
185 const session = this.sessions.get(characterId | 0);
186 if (!session)
187 { return { ok: false, error: "No dialogue open." }; }
188 if (session.phase === "lines")
189 { return { ok: false, error: "Finish reading first." }; }
190 const tree = this.content.dialogue(session.dialogueId);
191 if (!tree)
192 {
193 this.closeDialogue(characterId, "missing");
194 return { ok: false, error: "Dialogue missing." };
195 }
196 const step = tree.steps.find((s) => s.stepId === session.stepId);
197 if (!step || step.exit?.kind !== "triggers")
198 { return { ok: false, error: "Cannot choose now." }; }
199 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
200 if (!trigger)
201 { return { ok: false, error: "Unknown choice." }; }
202 const playerView = this.playerViewFor(characterId);
203 const ctx = this.buildConditionContext(characterId, playerView);
204 if (!evaluateConditionSet(trigger.when, ctx))
205 { return { ok: false, error: "That choice is unavailable." }; }
206 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
207 const events = [];
208 this.#applyEffects(characterId, trigger.effects, playerView, events);
209 this.#reevaluateQuests(characterId, playerView, events);
210 if (!trigger.nextStepId)
211 {
212 const npcEntityId = session.entityId;
213 this.sessions.delete(characterId | 0);
214 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
215 return { ok: true, events };
216 }
217 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
218 }
219
220 closeDialogue (characterId, reason = "close")
221 {
222 const id = characterId | 0;
223 const session = this.sessions.get(id);
224 if (!session)
225 { return { events: [] }; }
226 this.sessions.delete(id);
227 return {
228 events: [{
229 type: "dialogueClose",
230 reason,
231 npcEntityId: session.entityId
232 }]
233 };
234 }
235
236 interruptDialogueForEntity (entityId)
237 {
238 const events = [];
239 for (const [characterId, session] of [...this.sessions])
240 {
241 if (session.entityId === (entityId | 0))
242 {
243 const closed = this.closeDialogue(characterId, "attacked");
244 events.push(...closed.events.map((e) => ({ ...e, characterId })));
245 }
246 }
247 return events;
248 }
249
250 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
251 {
252 const step = tree.steps.find((s) => s.stepId === stepId);
253 if (!step)
254 {
255 this.sessions.delete(characterId | 0);
256 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
257 return { ok: false, error: "Broken dialogue.", events: priorEvents };
258 }
259 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, step.stepId);
260 const events = [...priorEvents];
261 const linePayloads = [];
262 for (const line of step.lines)
263 {
264 this.#applyEffects(characterId, line.effects, playerView, events);
265 linePayloads.push({ speaker: line.speaker, text: line.text });
266 }
267 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
268 this.sessions.set(characterId | 0, {
269 entityId: entityId | 0,
270 dialogueId: tree.dialogueId,
271 stepId: step.stepId,
272 phase: "lines",
273 pendingExit: step.exit ?? { kind: "end" }
274 });
275 events.push({
276 type: "dialogueStep",
277 dialogueId: tree.dialogueId,
278 stepId: step.stepId,
279 label: step.label,
280 npcEntityId: entityId | 0,
281 lines: linePayloads
282 });
283 this.#reevaluateQuests(characterId, playerView, events);
284 return { ok: true, events };
285 }
286
287 /** Client finished reading all lines of the current step. */
288 advanceDialogue (characterId)
289 {
290 const session = this.sessions.get(characterId | 0);
291 if (!session || session.phase !== "lines")
292 { return { ok: false, error: "No dialogue lines to advance." }; }
293 const tree = this.content.dialogue(session.dialogueId);
294 if (!tree)
295 {
296 this.sessions.delete(characterId | 0);
297 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
298 }
299 const playerView = this.playerViewFor(characterId);
300 const exit = session.pendingExit ?? { kind: "end" };
301 const events = [];
302
303 if (exit.kind === "branches")
304 {
305 const ctx = this.buildConditionContext(characterId, playerView);
306 let matched = null;
307 for (const branch of exit.branches ?? [])
308 {
309 if (evaluateConditionSet(branch.when, ctx))
310 {
311 matched = branch;
312 break;
313 }
314 }
315 if (!matched || !matched.nextStepId)
316 {
317 this.#applyEffects(characterId, matched?.effects, playerView, events);
318 const npcEntityId = session.entityId;
319 this.sessions.delete(characterId | 0);
320 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
321 return { ok: true, events };
322 }
323 this.#applyEffects(characterId, matched.effects, playerView, events);
324 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
325 }
326
327 if (exit.kind === "triggers")
328 {
329 const ctx = this.buildConditionContext(characterId, playerView);
330 const triggers = (exit.triggers ?? [])
331 .filter((t) => evaluateConditionSet(t.when, ctx))
332 .map((t) => ({ trigger: t.trigger, text: t.text }));
333 if (triggers.length === 0)
334 {
335 const npcEntityId = session.entityId;
336 this.sessions.delete(characterId | 0);
337 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
338 return { ok: true, events };
339 }
340 session.phase = "choices";
341 session.pendingExit = null;
342 events.push({
343 type: "dialogueChoices",
344 dialogueId: session.dialogueId,
345 stepId: session.stepId,
346 npcEntityId: session.entityId,
347 triggers
348 });
349 return { ok: true, events };
350 }
351
352 const npcEntityId = session.entityId;
353 this.sessions.delete(characterId | 0);
354 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
355 return { ok: true, events };
356 }
357
358 #loadBag (characterId)
359 {
360 const onlineId = this.simulation.characterEntities.get(characterId | 0);
361 const bag = onlineId
362 ? this.simulation.bagOf(onlineId)
363 : this.stateDb.getBag(characterId);
364 return bag;
365 }
366
367 #persistBag (characterId, bag)
368 {
369 this.stateDb.saveBag(characterId, bag);
370 const onlineId = this.simulation.characterEntities.get(characterId | 0);
371 if (onlineId)
372 {
373 this.simulation.applyBag?.(onlineId, bag);
374 this.simulation.pushInventory?.(characterId, bag);
375 }
376 }
377
378 #applyEffects (characterId, effects, playerView, events)
379 {
380 if (!Array.isArray(effects) || effects.length === 0)
381 { return; }
382 for (const effect of effects)
383 {
384 if (effect.kind === EffectKind.giveItem)
385 {
386 const bag = this.#loadBag(characterId);
387 if (!bag)
388 { continue; }
389 const def = itemDefinition(effect.itemId | 0);
390 const quantity = Math.max(1, Number(effect.quantity) || 1);
391 const result = insertStack(bag.inventory, { itemId: effect.itemId | 0, quantity }, def);
392 bag.inventory = result.slots;
393 if (result.remainder > 0)
394 {
395 const vaultResult = insertStackGrowable(
396 bag.vault,
397 { itemId: effect.itemId | 0, quantity: result.remainder },
398 def
399 );
400 bag.vault = vaultResult.slots;
401 }
402 this.#persistBag(characterId, bag);
403 events.push({ type: "inventoryDirty" });
404 }
405 else if (effect.kind === EffectKind.takeItem)
406 {
407 const bag = this.#loadBag(characterId);
408 if (!bag)
409 { continue; }
410 const taken = takeMatchingFromSlots(bag.inventory, {
411 itemId: effect.itemId | 0,
412 quantity: Math.max(1, Number(effect.quantity) || 1),
413 compact: false
414 });
415 if (taken.ok)
416 {
417 bag.inventory = taken.slots;
418 this.#persistBag(characterId, bag);
419 events.push({ type: "inventoryDirty" });
420 }
421 }
422 else if (effect.kind === EffectKind.giveXp)
423 {
424 const skills = this.stateDb.getSkills(characterId);
425 if (skills)
426 {
427 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
428 this.stateDb.saveSkills(characterId, skills);
429 if (playerView)
430 { playerView.skills = skills; }
431 events.push({ type: "skillsDirty" });
432 }
433 }
434 else if (effect.kind === EffectKind.startQuest)
435 { this.startQuest(characterId, effect.questId, playerView, events); }
436 }
437 }
438
439 startQuest (characterId, questId, playerView, events = [])
440 {
441 const def = this.content.quest(questId);
442 if (!def)
443 { return; }
444 const current = this.stateDb.getQuestState(characterId, questId);
445 if (current.state !== "not-started")
446 { return; }
447 this.stateDb.saveQuestState(characterId, questId, 1, {
448 completedObjectiveIds: [],
449 counters: {},
450 interacts: {}
451 }, Date.now(), null);
452 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
453 events.push({ type: "questsDirty" });
454 this.#reevaluateQuests(characterId, playerView, events);
455 }
456
457 #reevaluateQuests (characterId, playerView, events)
458 {
459 const states = this.stateDb.listQuestStates(characterId)
460 .filter((row) => typeof row.state === "number");
461 for (const row of states)
462 {
463 const def = this.content.quest(row.questId);
464 if (!def)
465 { continue; }
466 const stepDef = def.steps[row.state - 1];
467 if (!stepDef)
468 { continue; }
469 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
470 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
471 let changed = false;
472 for (const obj of stepDef.objectives)
473 {
474 if (completed.has(obj.objectiveId))
475 { continue; }
476 if (evaluateConditionSet(obj.when, ctx))
477 {
478 completed.add(obj.objectiveId);
479 changed = true;
480 }
481 }
482 if (!changed)
483 { continue; }
484 const progress = {
485 ...row.progress,
486 completedObjectiveIds: [...completed]
487 };
488 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
489 if (!allDone)
490 {
491 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
492 events.push({ type: "questsDirty" });
493 continue;
494 }
495 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
496 const journal = this.stateDb.appendQuestJournal(
497 characterId,
498 row.questId,
499 stepDef.stepId,
500 stepDef.completionJournalText
501 );
502 const nextIndex = row.state + 1;
503 if (nextIndex > def.steps.length)
504 {
505 this.#applyEffects(characterId, def.rewards, playerView, events);
506 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
507 }
508 else
509 {
510 const nextStep = def.steps[nextIndex - 1];
511 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
512 completedObjectiveIds: [],
513 counters: {},
514 interacts: {}
515 }, row.startedAt, null);
516 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
517 }
518 events.push({
519 type: "questStepComplete",
520 questId: row.questId,
521 title: def.title,
522 journalText: journal?.text ?? null
523 });
524 events.push({ type: "questsDirty" });
525 }
526 }
527
528 noteKill (characterId, { mobTypeId, spawnerId })
529 {
530 const events = [];
531 const playerView = this.playerViewFor(characterId);
532 const states = this.stateDb.listQuestStates(characterId)
533 .filter((row) => typeof row.state === "number");
534 for (const row of states)
535 {
536 const def = this.content.quest(row.questId);
537 const stepDef = def?.steps[row.state - 1];
538 if (!stepDef)
539 { continue; }
540 let changed = false;
541 const counters = { ...(row.progress?.counters ?? {}) };
542 for (const obj of stepDef.objectives)
543 {
544 for (const clause of obj.when?.all ?? [])
545 {
546 const c = clause.condition;
547 if (c?.kind !== "killCount")
548 { continue; }
549 const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
550 const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
551 if (!matchMob && !matchSpawner)
552 { continue; }
553 const key = killKey(c);
554 counters[key] = (counters[key] | 0) + 1;
555 changed = true;
556 }
557 }
558 if (!changed)
559 { continue; }
560 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
561 ...row.progress,
562 counters
563 }, row.startedAt, row.completedAt);
564 }
565 this.#reevaluateQuests(characterId, playerView, events);
566 return events;
567 }
568 }
569
570 function journalPublic (row)
571 {
572 return {
573 entryId: row.entry_id ?? row.entryId,
574 questId: row.quest_id ?? row.questId,
575 stepId: row.step_id ?? row.stepId,
576 text: row.text,
577 writtenAt: row.written_at ?? row.writtenAt
578 };
579 }
580
581 function killKey (condition)
582 {
583 if (condition.spawnerId)
584 { return `spawner:${condition.spawnerId}`; }
585 return `mob:${condition.mobTypeId}`;
586 }
587
588 function interactKey (condition)
589 {
590 if (condition.tileX != null)
591 { return `tile:${condition.tileX},${condition.tileY}`; }
592 return `block:${condition.blockTypeId}`;
593 }
@@ -0,0 +1,593 @@
1import { evaluateConditionSet, EffectKind } from "../../../shared/quests/conditions.js";
2import { countItemInSlots, insertStack, takeMatchingFromSlots, insertStackGrowable } from "../../../shared/items/inventory.js";
3import { itemDefinition } from "../../../shared/definitions/items.js";
4import { applySkillXp } from "../../../shared/skills/state.js";
5import { skillLevel } from "../../../shared/definitions/skills.js";
6import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
7import { floorDiv } from "../world/coordinates.js";
8import { WorkerMessage } from "../simulation/protocol.js";
9
10/**
11 * Quest progress + dialogue sessions (main simulation thread).
12 */
13export class QuestRuntime
14{
15 constructor ({ stateDb, content, simulation })
16 {
17 this.stateDb = stateDb;
18 this.content = content;
19 this.simulation = simulation;
20 /** @type {Map<number, { entityId: number, dialogueId: string, stepId: string }>} */
21 this.sessions = new Map();
22 }
23
24 reloadContent ()
25 {
26 this.content.reload();
27 }
28
29 closeAllSessions ()
30 {
31 for (const characterId of [...this.sessions.keys()])
32 { this.closeDialogue(characterId, "revision"); }
33 }
34
35 questSnapshot (characterId)
36 {
37 const states = this.stateDb.listQuestStates(characterId)
38 .filter((row) => row.state !== "not-started");
39 const quests = [];
40 for (const row of states)
41 {
42 const def = this.content.quest(row.questId);
43 if (!def)
44 {
45 quests.push({
46 questId: row.questId,
47 title: "Quest unavailable",
48 orphaned: true,
49 state: row.state,
50 description: "",
51 step: null,
52 journal: this.stateDb.listQuestJournal(characterId, row.questId).map(journalPublic)
53 });
54 continue;
55 }
56 const stepIndex = typeof row.state === "number" ? row.state : null;
57 const stepDef = stepIndex != null ? def.steps[stepIndex - 1] : null;
58 const completedObjectiveIds = row.progress?.completedObjectiveIds ?? [];
59 quests.push({
60 questId: def.questId,
61 title: def.title,
62 orphaned: false,
63 state: row.state,
64 description: def.description,
65 step: stepDef
66 ? {
67 stepId: stepDef.stepId,
68 title: stepDef.title,
69 description: stepDef.description,
70 objectives: stepDef.objectives.map((obj) => ({
71 objectiveId: obj.objectiveId,
72 text: obj.text,
73 done: completedObjectiveIds.includes(obj.objectiveId)
74 }))
75 }
76 : null,
77 journal: this.stateDb.listQuestJournal(characterId, def.questId).map(journalPublic)
78 });
79 }
80 quests.sort((a, b) =>
81 {
82 const aDone = a.state === "completed" ? 1 : 0;
83 const bDone = b.state === "completed" ? 1 : 0;
84 if (aDone !== bDone)
85 { return aDone - bDone; }
86 return String(a.title).localeCompare(String(b.title));
87 });
88 return { quests };
89 }
90
91 playerViewFor (characterId)
92 {
93 const entityId = this.simulation.characterEntities.get(characterId | 0);
94 const record = entityId != null ? this.simulation.directory.get(entityId) : null;
95 const skills = this.stateDb.getSkills(characterId) ?? {};
96 let hp = 1;
97 let maxHp = 1;
98 let stamina = 1;
99 let maxStamina = 1;
100 if (entityId != null && record)
101 {
102 const staminaComp = this.simulation.staminaOf(entityId);
103 if (staminaComp)
104 {
105 stamina = Number(staminaComp.current) || 0;
106 maxStamina = Math.max(1, Number(staminaComp.max) || 1);
107 }
108 const worker = this.simulation.workers[record.workerId];
109 const view = worker?.call?.({
110 type: WorkerMessage.inspect,
111 entityId
112 });
113 if (view && view.health != null)
114 {
115 hp = Number(view.health) || 0;
116 maxHp = Math.max(1, Number(view.maxHealth) || 1);
117 }
118 }
119 return {
120 tileX: record?.tileX | 0,
121 tileY: record?.tileY | 0,
122 dimensionId: record?.dimensionId ?? "overworld",
123 skills,
124 hp,
125 maxHp,
126 stamina,
127 maxStamina
128 };
129 }
130
131 buildConditionContext (characterId, playerView, activeQuestId = null)
132 {
133 const bag = this.#loadBag(characterId);
134 const inventory = bag?.inventory ?? [];
135 const tileX = playerView?.tileX | 0;
136 const tileY = playerView?.tileY | 0;
137 const dimensionId = playerView?.dimensionId ?? "overworld";
138 const chunkX = floorDiv(tileX, CHUNK_SIZE);
139 const chunkY = floorDiv(tileY, CHUNK_SIZE);
140 const questRow = activeQuestId ? this.stateDb.getQuestState(characterId, activeQuestId) : null;
141 return {
142 tileX,
143 tileY,
144 chunkX,
145 chunkY,
146 dimensionId,
147 hp: playerView?.hp ?? 0,
148 maxHp: playerView?.maxHp ?? 1,
149 stamina: playerView?.stamina ?? 0,
150 maxStamina: playerView?.maxStamina ?? 1,
151 countItem: (itemId) => countItemInSlots(inventory, itemId | 0),
152 questState: (questId) => this.stateDb.getQuestState(characterId, questId).state,
153 dialogueHeard: (dialogueId, stepId) => this.stateDb.isDialogueHeard(characterId, dialogueId, stepId),
154 dialogueTriggerLatched: (dialogueId, trigger) =>
155 this.stateDb.isDialogueTriggerLatched(characterId, dialogueId, trigger),
156 skillLevel: (skillId) => skillLevel(playerView?.skills ?? {}, skillId),
157 hasVisitedDimension: (dimId) => this.stateDb.hasVisitedDimension(characterId, dimId),
158 killCount: (condition) =>
159 {
160 if (!questRow)
161 { return 0; }
162 return questRow.progress?.counters?.[killKey(condition)] | 0;
163 },
164 interactBlockDone: (condition) =>
165 {
166 if (!questRow)
167 { return false; }
168 return !!questRow.progress?.interacts?.[interactKey(condition)];
169 }
170 };
171 }
172
173 tryOpenDialogue (characterId, entityId, dialogueId)
174 {
175 const tree = this.content.dialogue(dialogueId);
176 if (!tree)
177 { return { ok: false, error: "Nothing to say." }; }
178 this.closeDialogue(characterId, "replace");
179 const playerView = this.playerViewFor(characterId);
180 return this.#enterStep(characterId, entityId, tree, tree.entryStepId, playerView);
181 }
182
183 chooseDialogue (characterId, triggerId)
184 {
185 const session = this.sessions.get(characterId | 0);
186 if (!session)
187 { return { ok: false, error: "No dialogue open." }; }
188 if (session.phase === "lines")
189 { return { ok: false, error: "Finish reading first." }; }
190 const tree = this.content.dialogue(session.dialogueId);
191 if (!tree)
192 {
193 this.closeDialogue(characterId, "missing");
194 return { ok: false, error: "Dialogue missing." };
195 }
196 const step = tree.steps.find((s) => s.stepId === session.stepId);
197 if (!step || step.exit?.kind !== "triggers")
198 { return { ok: false, error: "Cannot choose now." }; }
199 const trigger = step.exit.triggers.find((t) => t.trigger === String(triggerId));
200 if (!trigger)
201 { return { ok: false, error: "Unknown choice." }; }
202 const playerView = this.playerViewFor(characterId);
203 const ctx = this.buildConditionContext(characterId, playerView);
204 if (!evaluateConditionSet(trigger.when, ctx))
205 { return { ok: false, error: "That choice is unavailable." }; }
206 this.stateDb.latchDialogueTrigger(characterId, tree.dialogueId, trigger.trigger);
207 const events = [];
208 this.#applyEffects(characterId, trigger.effects, playerView, events);
209 this.#reevaluateQuests(characterId, playerView, events);
210 if (!trigger.nextStepId)
211 {
212 const npcEntityId = session.entityId;
213 this.sessions.delete(characterId | 0);
214 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
215 return { ok: true, events };
216 }
217 return this.#enterStep(characterId, session.entityId, tree, trigger.nextStepId, playerView, events);
218 }
219
220 closeDialogue (characterId, reason = "close")
221 {
222 const id = characterId | 0;
223 const session = this.sessions.get(id);
224 if (!session)
225 { return { events: [] }; }
226 this.sessions.delete(id);
227 return {
228 events: [{
229 type: "dialogueClose",
230 reason,
231 npcEntityId: session.entityId
232 }]
233 };
234 }
235
236 interruptDialogueForEntity (entityId)
237 {
238 const events = [];
239 for (const [characterId, session] of [...this.sessions])
240 {
241 if (session.entityId === (entityId | 0))
242 {
243 const closed = this.closeDialogue(characterId, "attacked");
244 events.push(...closed.events.map((e) => ({ ...e, characterId })));
245 }
246 }
247 return events;
248 }
249
250 #enterStep (characterId, entityId, tree, stepId, playerView, priorEvents = [])
251 {
252 const step = tree.steps.find((s) => s.stepId === stepId);
253 if (!step)
254 {
255 this.sessions.delete(characterId | 0);
256 priorEvents.push({ type: "dialogueClose", reason: "missing-step" });
257 return { ok: false, error: "Broken dialogue.", events: priorEvents };
258 }
259 this.stateDb.markDialogueHeard(characterId, tree.dialogueId, step.stepId);
260 const events = [...priorEvents];
261 const linePayloads = [];
262 for (const line of step.lines)
263 {
264 this.#applyEffects(characterId, line.effects, playerView, events);
265 linePayloads.push({ speaker: line.speaker, text: line.text });
266 }
267 // Stay open while the client pages lines; resolve exit only on dialogueAdvance.
268 this.sessions.set(characterId | 0, {
269 entityId: entityId | 0,
270 dialogueId: tree.dialogueId,
271 stepId: step.stepId,
272 phase: "lines",
273 pendingExit: step.exit ?? { kind: "end" }
274 });
275 events.push({
276 type: "dialogueStep",
277 dialogueId: tree.dialogueId,
278 stepId: step.stepId,
279 label: step.label,
280 npcEntityId: entityId | 0,
281 lines: linePayloads
282 });
283 this.#reevaluateQuests(characterId, playerView, events);
284 return { ok: true, events };
285 }
286
287 /** Client finished reading all lines of the current step. */
288 advanceDialogue (characterId)
289 {
290 const session = this.sessions.get(characterId | 0);
291 if (!session || session.phase !== "lines")
292 { return { ok: false, error: "No dialogue lines to advance." }; }
293 const tree = this.content.dialogue(session.dialogueId);
294 if (!tree)
295 {
296 this.sessions.delete(characterId | 0);
297 return { ok: true, events: [{ type: "dialogueClose", reason: "missing" }] };
298 }
299 const playerView = this.playerViewFor(characterId);
300 const exit = session.pendingExit ?? { kind: "end" };
301 const events = [];
302
303 if (exit.kind === "branches")
304 {
305 const ctx = this.buildConditionContext(characterId, playerView);
306 let matched = null;
307 for (const branch of exit.branches ?? [])
308 {
309 if (evaluateConditionSet(branch.when, ctx))
310 {
311 matched = branch;
312 break;
313 }
314 }
315 if (!matched || !matched.nextStepId)
316 {
317 this.#applyEffects(characterId, matched?.effects, playerView, events);
318 const npcEntityId = session.entityId;
319 this.sessions.delete(characterId | 0);
320 events.push({ type: "dialogueClose", reason: "branch-end", npcEntityId });
321 return { ok: true, events };
322 }
323 this.#applyEffects(characterId, matched.effects, playerView, events);
324 return this.#enterStep(characterId, session.entityId, tree, matched.nextStepId, playerView, events);
325 }
326
327 if (exit.kind === "triggers")
328 {
329 const ctx = this.buildConditionContext(characterId, playerView);
330 const triggers = (exit.triggers ?? [])
331 .filter((t) => evaluateConditionSet(t.when, ctx))
332 .map((t) => ({ trigger: t.trigger, text: t.text }));
333 if (triggers.length === 0)
334 {
335 const npcEntityId = session.entityId;
336 this.sessions.delete(characterId | 0);
337 events.push({ type: "dialogueClose", reason: "no-triggers", npcEntityId });
338 return { ok: true, events };
339 }
340 session.phase = "choices";
341 session.pendingExit = null;
342 events.push({
343 type: "dialogueChoices",
344 dialogueId: session.dialogueId,
345 stepId: session.stepId,
346 npcEntityId: session.entityId,
347 triggers
348 });
349 return { ok: true, events };
350 }
351
352 const npcEntityId = session.entityId;
353 this.sessions.delete(characterId | 0);
354 events.push({ type: "dialogueClose", reason: "end", npcEntityId });
355 return { ok: true, events };
356 }
357
358 #loadBag (characterId)
359 {
360 const onlineId = this.simulation.characterEntities.get(characterId | 0);
361 const bag = onlineId
362 ? this.simulation.bagOf(onlineId)
363 : this.stateDb.getBag(characterId);
364 return bag;
365 }
366
367 #persistBag (characterId, bag)
368 {
369 this.stateDb.saveBag(characterId, bag);
370 const onlineId = this.simulation.characterEntities.get(characterId | 0);
371 if (onlineId)
372 {
373 this.simulation.applyBag?.(onlineId, bag);
374 this.simulation.pushInventory?.(characterId, bag);
375 }
376 }
377
378 #applyEffects (characterId, effects, playerView, events)
379 {
380 if (!Array.isArray(effects) || effects.length === 0)
381 { return; }
382 for (const effect of effects)
383 {
384 if (effect.kind === EffectKind.giveItem)
385 {
386 const bag = this.#loadBag(characterId);
387 if (!bag)
388 { continue; }
389 const def = itemDefinition(effect.itemId | 0);
390 const quantity = Math.max(1, Number(effect.quantity) || 1);
391 const result = insertStack(bag.inventory, { itemId: effect.itemId | 0, quantity }, def);
392 bag.inventory = result.slots;
393 if (result.remainder > 0)
394 {
395 const vaultResult = insertStackGrowable(
396 bag.vault,
397 { itemId: effect.itemId | 0, quantity: result.remainder },
398 def
399 );
400 bag.vault = vaultResult.slots;
401 }
402 this.#persistBag(characterId, bag);
403 events.push({ type: "inventoryDirty" });
404 }
405 else if (effect.kind === EffectKind.takeItem)
406 {
407 const bag = this.#loadBag(characterId);
408 if (!bag)
409 { continue; }
410 const taken = takeMatchingFromSlots(bag.inventory, {
411 itemId: effect.itemId | 0,
412 quantity: Math.max(1, Number(effect.quantity) || 1),
413 compact: false
414 });
415 if (taken.ok)
416 {
417 bag.inventory = taken.slots;
418 this.#persistBag(characterId, bag);
419 events.push({ type: "inventoryDirty" });
420 }
421 }
422 else if (effect.kind === EffectKind.giveXp)
423 {
424 const skills = this.stateDb.getSkills(characterId);
425 if (skills)
426 {
427 applySkillXp(skills, effect.skillId, Math.max(0, Number(effect.amount) || 0));
428 this.stateDb.saveSkills(characterId, skills);
429 if (playerView)
430 { playerView.skills = skills; }
431 events.push({ type: "skillsDirty" });
432 }
433 }
434 else if (effect.kind === EffectKind.startQuest)
435 { this.startQuest(characterId, effect.questId, playerView, events); }
436 }
437 }
438
439 startQuest (characterId, questId, playerView, events = [])
440 {
441 const def = this.content.quest(questId);
442 if (!def)
443 { return; }
444 const current = this.stateDb.getQuestState(characterId, questId);
445 if (current.state !== "not-started")
446 { return; }
447 this.stateDb.saveQuestState(characterId, questId, 1, {
448 completedObjectiveIds: [],
449 counters: {},
450 interacts: {}
451 }, Date.now(), null);
452 this.#applyEffects(characterId, def.steps[0]?.onEnter, playerView, events);
453 events.push({ type: "questsDirty" });
454 this.#reevaluateQuests(characterId, playerView, events);
455 }
456
457 #reevaluateQuests (characterId, playerView, events)
458 {
459 const states = this.stateDb.listQuestStates(characterId)
460 .filter((row) => typeof row.state === "number");
461 for (const row of states)
462 {
463 const def = this.content.quest(row.questId);
464 if (!def)
465 { continue; }
466 const stepDef = def.steps[row.state - 1];
467 if (!stepDef)
468 { continue; }
469 const ctx = this.buildConditionContext(characterId, playerView, row.questId);
470 const completed = new Set(row.progress?.completedObjectiveIds ?? []);
471 let changed = false;
472 for (const obj of stepDef.objectives)
473 {
474 if (completed.has(obj.objectiveId))
475 { continue; }
476 if (evaluateConditionSet(obj.when, ctx))
477 {
478 completed.add(obj.objectiveId);
479 changed = true;
480 }
481 }
482 if (!changed)
483 { continue; }
484 const progress = {
485 ...row.progress,
486 completedObjectiveIds: [...completed]
487 };
488 const allDone = stepDef.objectives.every((obj) => completed.has(obj.objectiveId));
489 if (!allDone)
490 {
491 this.stateDb.saveQuestState(characterId, row.questId, row.state, progress, row.startedAt, row.completedAt);
492 events.push({ type: "questsDirty" });
493 continue;
494 }
495 this.#applyEffects(characterId, stepDef.onComplete, playerView, events);
496 const journal = this.stateDb.appendQuestJournal(
497 characterId,
498 row.questId,
499 stepDef.stepId,
500 stepDef.completionJournalText
501 );
502 const nextIndex = row.state + 1;
503 if (nextIndex > def.steps.length)
504 {
505 this.#applyEffects(characterId, def.rewards, playerView, events);
506 this.stateDb.saveQuestState(characterId, row.questId, "completed", progress, row.startedAt, Date.now());
507 }
508 else
509 {
510 const nextStep = def.steps[nextIndex - 1];
511 this.stateDb.saveQuestState(characterId, row.questId, nextIndex, {
512 completedObjectiveIds: [],
513 counters: {},
514 interacts: {}
515 }, row.startedAt, null);
516 this.#applyEffects(characterId, nextStep?.onEnter, playerView, events);
517 }
518 events.push({
519 type: "questStepComplete",
520 questId: row.questId,
521 title: def.title,
522 journalText: journal?.text ?? null
523 });
524 events.push({ type: "questsDirty" });
525 }
526 }
527
528 noteKill (characterId, { mobTypeId, spawnerId })
529 {
530 const events = [];
531 const playerView = this.playerViewFor(characterId);
532 const states = this.stateDb.listQuestStates(characterId)
533 .filter((row) => typeof row.state === "number");
534 for (const row of states)
535 {
536 const def = this.content.quest(row.questId);
537 const stepDef = def?.steps[row.state - 1];
538 if (!stepDef)
539 { continue; }
540 let changed = false;
541 const counters = { ...(row.progress?.counters ?? {}) };
542 for (const obj of stepDef.objectives)
543 {
544 for (const clause of obj.when?.all ?? [])
545 {
546 const c = clause.condition;
547 if (c?.kind !== "killCount")
548 { continue; }
549 const matchMob = c.mobTypeId != null && String(c.mobTypeId) === String(mobTypeId);
550 const matchSpawner = c.spawnerId != null && String(c.spawnerId) === String(spawnerId);
551 if (!matchMob && !matchSpawner)
552 { continue; }
553 const key = killKey(c);
554 counters[key] = (counters[key] | 0) + 1;
555 changed = true;
556 }
557 }
558 if (!changed)
559 { continue; }
560 this.stateDb.saveQuestState(characterId, row.questId, row.state, {
561 ...row.progress,
562 counters
563 }, row.startedAt, row.completedAt);
564 }
565 this.#reevaluateQuests(characterId, playerView, events);
566 return events;
567 }
568}
569
570function journalPublic (row)
571{
572 return {
573 entryId: row.entry_id ?? row.entryId,
574 questId: row.quest_id ?? row.questId,
575 stepId: row.step_id ?? row.stepId,
576 text: row.text,
577 writtenAt: row.written_at ?? row.writtenAt
578 };
579}
580
581function killKey (condition)
582{
583 if (condition.spawnerId)
584 { return `spawner:${condition.spawnerId}`; }
585 return `mob:${condition.mobTypeId}`;
586}
587
588function interactKey (condition)
589{
590 if (condition.tileX != null)
591 { return `tile:${condition.tileX},${condition.tileY}`; }
592 return `block:${condition.blockTypeId}`;
593}
server/src/simulation/chunkLoader.js +11 −6
@@ -1,4 +1,5 @@
1 1 import { DEFAULT_CHUNK_LOADER } from "../../../shared/protocol/constants.js";
2 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2 3 import {
3 4 chunkKey,
4 5 chunkToRegion,
@@ -16,18 +17,21 @@ export function normalizeChunkLoader (loader)
16 17 };
17 18 }
18 19
19 export function loaderCoverage (tileX, tileY, loader)
20 export function loaderCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
20 21 {
22 const dim = normalizeDimensionId(dimensionId);
21 23 const chunkLoader = normalizeChunkLoader(loader);
22 24 const chunkX = tileToChunk(tileX);
23 25 const chunkY = tileToChunk(tileY);
24 26 return {
25 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks),
27 dimensionId: dim,
28 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks)
29 .map((coord) => ({ ...coord, dimensionId: dim })),
26 30 residentRegions: visibleRegionCoords(
27 31 chunkToRegion(chunkX),
28 32 chunkToRegion(chunkY),
29 33 chunkLoader.regionLoadRadius
30 )
34 ).map((coord) => ({ ...coord, dimensionId: dim }))
31 35 };
32 36 }
33 37
@@ -37,15 +41,16 @@ export function accumulateLoaderRefs (loaders)
37 41 const regionRes = new Map();
38 42 for (const loader of loaders)
39 43 {
40 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
44 const dim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
45 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
41 46 for (const chunk of coverage.simulationChunks)
42 47 {
43 const key = chunkKey(chunk.chunkX, chunk.chunkY);
48 const key = chunkKey(chunk.chunkX, chunk.chunkY, dim);
44 49 chunkSim.set(key, (chunkSim.get(key) ?? 0) + 1);
45 50 }
46 51 for (const region of coverage.residentRegions)
47 52 {
48 const key = regionKey(region.regionX, region.regionY);
53 const key = regionKey(region.regionX, region.regionY, dim);
49 54 regionRes.set(key, (regionRes.get(key) ?? 0) + 1);
50 55 }
51 56 }
@@ -1,4 +1,5 @@
1import { DEFAULT_CHUNK_LOADER } from "../../../shared/protocol/constants.js";
1import { DEFAULT_CHUNK_LOADER } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2import {
3import {
3 chunkKey,
4 chunkKey,
4 chunkToRegion,
5 chunkToRegion,
@@ -16,18 +17,21 @@ export function normalizeChunkLoader (loader)
16 };
17 };
17}
18}
18
19
19export function loaderCoverage (tileX, tileY, loader)
20export function loaderCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
20{
21{
22 const dim = normalizeDimensionId(dimensionId);
21 const chunkLoader = normalizeChunkLoader(loader);
23 const chunkLoader = normalizeChunkLoader(loader);
22 const chunkX = tileToChunk(tileX);
24 const chunkX = tileToChunk(tileX);
23 const chunkY = tileToChunk(tileY);
25 const chunkY = tileToChunk(tileY);
24 return {
26 return {
25 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks),
27 dimensionId: dim,
28 simulationChunks: visibleChunkCoords(chunkX, chunkY, chunkLoader.simulationRadiusChunks)
29 .map((coord) => ({ ...coord, dimensionId: dim })),
26 residentRegions: visibleRegionCoords(
30 residentRegions: visibleRegionCoords(
27 chunkToRegion(chunkX),
31 chunkToRegion(chunkX),
28 chunkToRegion(chunkY),
32 chunkToRegion(chunkY),
29 chunkLoader.regionLoadRadius
33 chunkLoader.regionLoadRadius
30 )
34 ).map((coord) => ({ ...coord, dimensionId: dim }))
31 };
35 };
32}
36}
33
37
@@ -37,15 +41,16 @@ export function accumulateLoaderRefs (loaders)
37 const regionRes = new Map();
41 const regionRes = new Map();
38 for (const loader of loaders)
42 for (const loader of loaders)
39 {
43 {
40 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
44 const dim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
45 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
41 for (const chunk of coverage.simulationChunks)
46 for (const chunk of coverage.simulationChunks)
42 {
47 {
43 const key = chunkKey(chunk.chunkX, chunk.chunkY);
48 const key = chunkKey(chunk.chunkX, chunk.chunkY, dim);
44 chunkSim.set(key, (chunkSim.get(key) ?? 0) + 1);
49 chunkSim.set(key, (chunkSim.get(key) ?? 0) + 1);
45 }
50 }
46 for (const region of coverage.residentRegions)
51 for (const region of coverage.residentRegions)
47 {
52 {
48 const key = regionKey(region.regionX, region.regionY);
53 const key = regionKey(region.regionX, region.regionY, dim);
49 regionRes.set(key, (regionRes.get(key) ?? 0) + 1);
54 regionRes.set(key, (regionRes.get(key) ?? 0) + 1);
50 }
55 }
51 }
56 }
server/src/simulation/freeFlight.js +11 −7
@@ -1,5 +1,6 @@
1 1 import { Component } from "../ecs/components.js";
2 2 import { mobDefinition } from "../../../shared/definitions/mobs.js";
3 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3 4 import { tileToChunk, tileToRegion } from "../world/coordinates.js";
4 5
5 6 export function ensureFlightComponent (ecs, handle, position, def)
@@ -32,7 +33,8 @@ export function stepFreeFlight (world, now = Date.now())
32 33 const existingFlight = world.ecs.get(entity.handle, Component.flight);
33 34 if (existingFlight?.courierId != null)
34 35 { continue; }
35 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
36 const dimensionId = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
37 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY, dimensionId))
36 38 { continue; }
37 39 if (world.frozen?.has?.(entity.entityId))
38 40 { continue; }
@@ -46,7 +48,7 @@ export function stepFreeFlight (world, now = Date.now())
46 48 const arrived = Math.hypot(flight.targetX - flight.x, flight.targetY - flight.y) < 0.08;
47 49 if (arrived || now >= (flight.nextPickAt || 0))
48 50 {
49 const next = pickFlightTarget(world, flight.x, flight.y);
51 const next = pickFlightTarget(world, flight.x, flight.y, dimensionId);
50 52 if (next)
51 53 {
52 54 flight.targetX = next.x;
@@ -76,7 +78,7 @@ export function stepFreeFlight (world, now = Date.now())
76 78
77 79 const destRegionX = tileToRegion(tileX);
78 80 const destRegionY = tileToRegion(tileY);
79 if (!world.ownsRegion(destRegionX, destRegionY))
81 if (!world.ownsRegion(destRegionX, destRegionY, dimensionId))
80 82 {
81 83 world.frozen.add(entity.entityId);
82 84 events.push({
@@ -87,7 +89,8 @@ export function stepFreeFlight (world, now = Date.now())
87 89 destTileX: tileX,
88 90 destTileY: tileY,
89 91 toRegionX: destRegionX,
90 toRegionY: destRegionY
92 toRegionY: destRegionY,
93 dimensionId
91 94 });
92 95 continue;
93 96 }
@@ -110,8 +113,9 @@ export function stepFreeFlight (world, now = Date.now())
110 113 return events;
111 114 }
112 115
113 function pickFlightTarget (world, fromX, fromY)
116 function pickFlightTarget (world, fromX, fromY, dimensionId = OVERWORLD_ID)
114 117 {
118 const dim = normalizeDimensionId(dimensionId);
115 119 for (let attempt = 0; attempt < 16; attempt++)
116 120 {
117 121 const angle = Math.random() * Math.PI * 2;
@@ -120,9 +124,9 @@ function pickFlightTarget (world, fromX, fromY)
120 124 const y = fromY + Math.sin(angle) * dist;
121 125 const tileX = Math.floor(x);
122 126 const tileY = Math.floor(y);
123 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
127 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim))
124 128 { continue; }
125 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
129 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
126 130 if (!data?.open)
127 131 { continue; }
128 132 return { x: tileX + 0.5, y: tileY + 0.5 };
@@ -1,5 +1,6 @@
1import { Component } from "../ecs/components.js";
1import { Component } from "../ecs/components.js";
2import { mobDefinition } from "../../../shared/definitions/mobs.js";
2import { mobDefinition } from "../../../shared/definitions/mobs.js";
3import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
3import { tileToChunk, tileToRegion } from "../world/coordinates.js";
4import { tileToChunk, tileToRegion } from "../world/coordinates.js";
4
5
5export function ensureFlightComponent (ecs, handle, position, def)
6export function ensureFlightComponent (ecs, handle, position, def)
@@ -32,7 +33,8 @@ export function stepFreeFlight (world, now = Date.now())
32 const existingFlight = world.ecs.get(entity.handle, Component.flight);
33 const existingFlight = world.ecs.get(entity.handle, Component.flight);
33 if (existingFlight?.courierId != null)
34 if (existingFlight?.courierId != null)
34 { continue; }
35 { continue; }
35 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
36 const dimensionId = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
37 if (!world.chunkIsSimulating(entity.position.tileX, entity.position.tileY, dimensionId))
36 { continue; }
38 { continue; }
37 if (world.frozen?.has?.(entity.entityId))
39 if (world.frozen?.has?.(entity.entityId))
38 { continue; }
40 { continue; }
@@ -46,7 +48,7 @@ export function stepFreeFlight (world, now = Date.now())
46 const arrived = Math.hypot(flight.targetX - flight.x, flight.targetY - flight.y) < 0.08;
48 const arrived = Math.hypot(flight.targetX - flight.x, flight.targetY - flight.y) < 0.08;
47 if (arrived || now >= (flight.nextPickAt || 0))
49 if (arrived || now >= (flight.nextPickAt || 0))
48 {
50 {
49 const next = pickFlightTarget(world, flight.x, flight.y);
51 const next = pickFlightTarget(world, flight.x, flight.y, dimensionId);
50 if (next)
52 if (next)
51 {
53 {
52 flight.targetX = next.x;
54 flight.targetX = next.x;
@@ -76,7 +78,7 @@ export function stepFreeFlight (world, now = Date.now())
76
78
77 const destRegionX = tileToRegion(tileX);
79 const destRegionX = tileToRegion(tileX);
78 const destRegionY = tileToRegion(tileY);
80 const destRegionY = tileToRegion(tileY);
79 if (!world.ownsRegion(destRegionX, destRegionY))
81 if (!world.ownsRegion(destRegionX, destRegionY, dimensionId))
80 {
82 {
81 world.frozen.add(entity.entityId);
83 world.frozen.add(entity.entityId);
82 events.push({
84 events.push({
@@ -87,7 +89,8 @@ export function stepFreeFlight (world, now = Date.now())
87 destTileX: tileX,
89 destTileX: tileX,
88 destTileY: tileY,
90 destTileY: tileY,
89 toRegionX: destRegionX,
91 toRegionX: destRegionX,
90 toRegionY: destRegionY
92 toRegionY: destRegionY,
93 dimensionId
91 });
94 });
92 continue;
95 continue;
93 }
96 }
@@ -110,8 +113,9 @@ export function stepFreeFlight (world, now = Date.now())
110 return events;
113 return events;
111}
114}
112
115
113function pickFlightTarget (world, fromX, fromY)
116function pickFlightTarget (world, fromX, fromY, dimensionId = OVERWORLD_ID)
114{
117{
118 const dim = normalizeDimensionId(dimensionId);
115 for (let attempt = 0; attempt < 16; attempt++)
119 for (let attempt = 0; attempt < 16; attempt++)
116 {
120 {
117 const angle = Math.random() * Math.PI * 2;
121 const angle = Math.random() * Math.PI * 2;
@@ -120,9 +124,9 @@ function pickFlightTarget (world, fromX, fromY)
120 const y = fromY + Math.sin(angle) * dist;
124 const y = fromY + Math.sin(angle) * dist;
121 const tileX = Math.floor(x);
125 const tileX = Math.floor(x);
122 const tileY = Math.floor(y);
126 const tileY = Math.floor(y);
123 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY)))
127 if (!world.ownsRegion(tileToRegion(tileX), tileToRegion(tileY), dim))
124 { continue; }
128 { continue; }
125 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY));
129 const data = world.chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
126 if (!data?.open)
130 if (!data?.open)
127 { continue; }
131 { continue; }
128 return { x: tileX + 0.5, y: tileY + 0.5 };
132 return { x: tileX + 0.5, y: tileY + 0.5 };
server/src/simulation/protocol.js +4 −1
@@ -35,11 +35,14 @@ export const WorkerMessage = Object.freeze({
35 35 applyCombatHitXp: "applyCombatHitXp",
36 36 spawnCorpseDrops: "spawnCorpseDrops",
37 37 applyRespawn: "applyRespawn",
38 relocateEntity: "relocateEntity",
38 39 clearCombat: "clearCombat",
39 40 setItemLastSales: "setItemLastSales",
40 41 stationExchangeClerk: "stationExchangeClerk",
41 42 releaseExchangeClerk: "releaseExchangeClerk",
42 43 applyAppearance: "applyAppearance",
43 44 engageTarget: "engageTarget",
44 listTownGuardsNear: "listTownGuardsNear"
45 listTownGuardsNear: "listTownGuardsNear",
46 pinDialogue: "pinDialogue",
47 unpinDialogue: "unpinDialogue"
45 48 });
@@ -35,11 +35,14 @@ export const WorkerMessage = Object.freeze({
35 applyCombatHitXp: "applyCombatHitXp",
35 applyCombatHitXp: "applyCombatHitXp",
36 spawnCorpseDrops: "spawnCorpseDrops",
36 spawnCorpseDrops: "spawnCorpseDrops",
37 applyRespawn: "applyRespawn",
37 applyRespawn: "applyRespawn",
38 relocateEntity: "relocateEntity",
38 clearCombat: "clearCombat",
39 clearCombat: "clearCombat",
39 setItemLastSales: "setItemLastSales",
40 setItemLastSales: "setItemLastSales",
40 stationExchangeClerk: "stationExchangeClerk",
41 stationExchangeClerk: "stationExchangeClerk",
41 releaseExchangeClerk: "releaseExchangeClerk",
42 releaseExchangeClerk: "releaseExchangeClerk",
42 applyAppearance: "applyAppearance",
43 applyAppearance: "applyAppearance",
43 engageTarget: "engageTarget",
44 engageTarget: "engageTarget",
44 listTownGuardsNear: "listTownGuardsNear"
45 listTownGuardsNear: "listTownGuardsNear",
46 pinDialogue: "pinDialogue",
47 unpinDialogue: "unpinDialogue"
45});
48});
server/src/simulation/simulation.js +594 −101
@@ -7,6 +7,7 @@ import {
7 7 STATIC_CHUNK_RADIUS,
8 8 WORLD_YEAR_OFFSET
9 9 } from "../../../shared/protocol/constants.js";
10 import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
10 11 import {
11 12 chunkKey,
12 13 chunkToRegion,
@@ -42,7 +43,9 @@ import { BountyService } from "../bounty/service.js";
42 43 import { BarberService } from "../barber/service.js";
43 44 import { findReservedChequeIndex } from "../items/bags.js";
44 45 import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
45
46 import { QuestContentCache } from "../quests/contentCache.js";
47 import { QuestRuntime } from "../quests/runtime.js";
48 import { chebyshev } from "../combat/service.js";
46 49
47 50 export class Simulation
48 51 {
@@ -75,6 +78,9 @@ export class Simulation
75 78 this.movementAccumulator = 0;
76 79 this.activeRevisionId = worldDb.getActiveRevisionId();
77 80 this.settings = worldDb.getLiveSettings();
81 this.questContent = new QuestContentCache(worldDb);
82 this.dimensions = this.#loadDimensionsCache();
83 this.quests = null;
78 84
79 85 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
80 86 for (let workerId = 0; workerId < this.workerCount; workerId++)
@@ -106,6 +112,11 @@ export class Simulation
106 112 });
107 113 this.bounty = new BountyService(this.stateDb, this, this.courier);
108 114 this.barber = new BarberService(this.stateDb, this);
115 this.quests = new QuestRuntime({
116 stateDb: this.stateDb,
117 content: this.questContent,
118 simulation: this
119 });
109 120 this.#refreshAltarIndex();
110 121 }
111 122
@@ -144,20 +155,26 @@ export class Simulation
144 155 {
145 156 this.activeRevisionId = this.worldDb.getActiveRevisionId();
146 157 this.settings = this.worldDb.getLiveSettings();
158 this.dimensions = this.#loadDimensionsCache();
147 159 this.authoredCache.clear();
148 160 this.#configureWorkers();
149 161 for (const [key, workerId] of this.regionOwner)
150 162 {
151 const { regionX, regionY } = parseRegionKey(key);
163 const { regionX, regionY, dimensionId } = parseRegionKey(key);
152 164 this.workers[workerId].call({
153 165 type: WorkerMessage.replaceRegionChunks,
154 chunks: this.#regionChunkBlobs(regionX, regionY)
166 regionX,
167 regionY,
168 dimensionId,
169 chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId)
155 170 });
156 171 }
157 172 this.#syncAllReplicas();
158 173 this.courier?.refreshBankIndex();
159 174 this.courier?.refreshBountyOfficeIndex();
160 175 this.market?.refreshIndex();
176 this.questContent.reload();
177 this.quests?.closeAllSessions();
161 178 this.#refreshAltarIndex();
162 179 }
163 180
@@ -169,6 +186,8 @@ export class Simulation
169 186 step (now = this.now)
170 187 {
171 188 this.tickIndex += 1;
189 if ((this.tickIndex % 1200) === 0)
190 { this.worldDb.purgeExpiredDimensions(now); }
172 191 const events = [];
173 192 const commands = this.commandQueue.splice(0);
174 193 for (const item of commands)
@@ -249,6 +268,16 @@ export class Simulation
249 268 events.push(...this.#applyMobKilled(event));
250 269 continue;
251 270 }
271 if (event.type === "dialogue-walk-away")
272 {
273 const closed = this.quests?.closeDialogue(event.characterId, "walk-away");
274 events.push(...this.#mapQuestPrivateEvents(
275 closed?.events ?? [],
276 event.sessionId,
277 event.characterId
278 ));
279 continue;
280 }
252 281 this.#persistGroundEvent(event);
253 282 if (event.type !== "skills-updated")
254 283 { events.push(event); }
@@ -341,19 +370,42 @@ export class Simulation
341 370 const row = this.stateDb.getCharacter(character.character_id) ?? character;
342 371 let tileX = row.tile_x;
343 372 let tileY = row.tile_y;
373 let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID);
344 374 const gait = row.gait || character.gait || GAIT.walk;
345 const preferred = this.#findResumeTile(tileX, tileY);
375
376 // Soft-deleted / purged interiors eject to overworld spawn.
377 if (!this.#isDimensionUsable(dimensionId))
378 {
379 dimensionId = OVERWORLD_ID;
380 const spawn = this.findOpenSpawn();
381 if (!spawn)
382 {
383 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
384 error.userFacing = true;
385 throw error;
386 }
387 tileX = spawn.tileX;
388 tileY = spawn.tileY;
389 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
390 }
391
392 const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId);
346 393 if (!preferred)
347 394 {
348 395 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
349 396 error.userFacing = true;
350 397 throw error;
351 398 }
352 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
399 if (
400 preferred.tileX !== tileX
401 || preferred.tileY !== tileY
402 || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId
403 )
353 404 {
354 405 tileX = preferred.tileX;
355 406 tileY = preferred.tileY;
356 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
407 dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId);
408 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
357 409 }
358 410
359 411 const bag = this.stateDb.getBag(character.character_id) ?? {
@@ -378,7 +430,7 @@ export class Simulation
378 430 : maxHealth;
379 431 const entityId = this.nextEntityId++;
380 432 const components = {
381 position: { tileX, tileY },
433 position: { tileX, tileY, dimensionId },
382 434 movement: { gait, walkCarry: 0 },
383 435 path: { tiles: [] },
384 436 appearance: {
@@ -413,14 +465,15 @@ export class Simulation
413 465 };
414 466 if (isDead)
415 467 { components.dead = {}; }
416 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
417 const workerId = this.#ownerOfTile(tileX, tileY);
468 this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId);
469 const workerId = this.#ownerOfTile(tileX, tileY, dimensionId);
418 470 const view = this.workers[workerId].call({
419 471 type: WorkerMessage.spawn,
420 472 entityId,
421 473 components
422 474 });
423 475 this.#remember(view, workerId);
476 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
424 477 this.#queueReplication(replicationSpawn(view));
425 478 this.#recalculateActivation(this.now);
426 479 this.#syncGhosts();
@@ -440,10 +493,12 @@ export class Simulation
440 493 const position = components.position;
441 494 if (!position)
442 495 { throw new Error("spawnEntity requires position."); }
496 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
497 position.dimensionId = dimensionId;
443 498 if (options.requireResident)
444 499 {
445 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
446 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
500 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
501 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
447 502 { return null; }
448 503 const view = this.workers[workerId].call({
449 504 type: WorkerMessage.spawn,
@@ -457,16 +512,17 @@ export class Simulation
457 512 return entityId;
458 513 }
459 514 if (components.chunkLoader)
460 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
515 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
461 516 else
462 517 {
463 518 this.#ensureRegion(
464 519 tileToRegion(position.tileX),
465 520 tileToRegion(position.tileY),
466 null
521 null,
522 dimensionId
467 523 );
468 524 }
469 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
525 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
470 526 const view = this.workers[workerId].call({
471 527 type: WorkerMessage.spawn,
472 528 entityId,
@@ -494,11 +550,11 @@ export class Simulation
494 550 this.#forget(entityId);
495 551 }
496 552
497 chunkIsSimulating (tileX, tileY)
553 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
498 554 {
499 555 const loaders = this.#allLoaders();
500 556 const { chunkSim } = accumulateLoaderRefs(loaders);
501 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
557 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
502 558 }
503 559
504 560 updateCourierFlight (entityId, flightPatch, now = this.now)
@@ -508,7 +564,8 @@ export class Simulation
508 564 { return { despawned: true, entityId }; }
509 565 const tileX = Math.floor(flightPatch.x);
510 566 const tileY = Math.floor(flightPatch.y);
511 const owner = this.#ownerOfTile(tileX, tileY);
567 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
568 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
512 569 if (owner == null || owner !== record.workerId)
513 570 {
514 571 this.despawnEntity(entityId);
@@ -672,7 +729,7 @@ export class Simulation
672 729 */
673 730 stationExchangeClerk (stationTileX, stationTileY)
674 731 {
675 const owner = this.#ownerOfTile(stationTileX, stationTileY);
732 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
676 733 if (owner == null)
677 734 { return { ok: false, reason: "unowned" }; }
678 735 return this.workers[owner].call({
@@ -707,7 +764,7 @@ export class Simulation
707 764 /** Release a CE clerk stationed at the given staff-side tile. */
708 765 releaseExchangeClerk (stationTileX, stationTileY)
709 766 {
710 const owner = this.#ownerOfTile(stationTileX, stationTileY);
767 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
711 768 if (owner == null)
712 769 { return { ok: false, reason: "unowned" }; }
713 770 return this.workers[owner].call({
@@ -740,7 +797,8 @@ export class Simulation
740 797 characterId,
741 798 dropped.tileX,
742 799 dropped.tileY,
743 dropped.gait ?? GAIT.walk
800 dropped.gait ?? GAIT.walk,
801 dropped.dimensionId ?? OVERWORLD_ID
744 802 );
745 803 if (dropped.health != null)
746 804 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
@@ -765,7 +823,13 @@ export class Simulation
765 823 positionOf (entityId)
766 824 {
767 825 const record = this.directory.get(entityId);
768 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
826 return record
827 ? {
828 tileX: record.tileX,
829 tileY: record.tileY,
830 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
831 }
832 : null;
769 833 }
770 834
771 835 bagOf (entityId)
@@ -784,8 +848,9 @@ export class Simulation
784 848 const record = this.directory.get(entityId);
785 849 if (!record)
786 850 { return []; }
851 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
787 852 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
788 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
853 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
789 854 }
790 855
791 856 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
@@ -794,42 +859,45 @@ export class Simulation
794 859 const record = this.directory.get(entityId);
795 860 if (!record)
796 861 { return []; }
862 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
797 863 const centerChunkX = tileToChunk(record.tileX);
798 864 const centerChunkY = tileToChunk(record.tileY);
799 865 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
800 866 const entityKeys = new Set(
801 867 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
802 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
868 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
803 869 );
804 870 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
805 871 .map((coord) =>
806 872 {
807 const key = chunkKey(coord.chunkX, coord.chunkY);
873 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
808 874 const staticOnly = !entityKeys.has(key);
809 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly);
875 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
810 876 return { ...snapshot, staticOnly };
811 877 });
812 878 }
813 879
814 snapshotChunk (chunkX, chunkY, staticOnly = false)
880 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
815 881 {
816 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
882 const dim = normalizeDimensionId(dimensionId);
883 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
817 884 if (owner == null)
818 { return this.#syntheticSnapshot(chunkX, chunkY, staticOnly); }
885 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
819 886 return this.workers[owner].call({
820 887 type: WorkerMessage.snapshotChunk,
821 888 chunkX,
822 889 chunkY,
890 dimensionId: dim,
823 891 staticOnly: !!staticOnly
824 892 });
825 893 }
826 894
827 895 findOpenSpawn ()
828 896 {
829 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
897 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
830 898 for (const coord of coords)
831 899 {
832 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
900 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
833 901 if (!data.open)
834 902 { continue; }
835 903 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -838,8 +906,8 @@ export class Simulation
838 906 {
839 907 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
840 908 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
841 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
842 { return { tileX, tileY }; }
909 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
910 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
843 911 }
844 912 }
845 913 }
@@ -847,13 +915,62 @@ export class Simulation
847 915 }
848 916
849 917 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
850 #findResumeTile (tileX, tileY, radius = 24)
918 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
851 919 {
852 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
920 const dim = normalizeDimensionId(dimensionId);
921 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
922 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
853 923 }
854 924
855 #findNearbyEnterable (originX, originY, maxRadius)
925 #isDimensionUsable (dimensionId)
856 926 {
927 const dim = normalizeDimensionId(dimensionId);
928 if (dim === OVERWORLD_ID)
929 { return true; }
930 const record = this.getDimensionRecord(dim);
931 if (!record)
932 { return false; }
933 if (record.deletedAt != null)
934 { return false; }
935 if (record.purgeAfter != null && record.purgeAfter <= this.now)
936 { return false; }
937 return true;
938 }
939
940 #loadDimensionsCache ()
941 {
942 const map = new Map();
943 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
944 { map.set(dim.dimensionId, dim); }
945 if (!map.has(OVERWORLD_ID))
946 {
947 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
948 defaultGroundTypeId: this.settings.defaultGroundTypeId
949 }));
950 }
951 return map;
952 }
953
954 getDimensionRecord (dimensionId)
955 {
956 const dim = normalizeDimensionId(dimensionId);
957 return this.dimensions?.get(dim)
958 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
959 ?? (dim === OVERWORLD_ID
960 ? defaultDimensionRecord(OVERWORLD_ID, {
961 defaultGroundTypeId: this.settings.defaultGroundTypeId
962 })
963 : null);
964 }
965
966 listDimensionRecords ()
967 {
968 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
969 }
970
971 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
972 {
973 const dim = normalizeDimensionId(dimensionId);
857 974 for (let radius = 0; radius <= maxRadius; radius++)
858 975 {
859 976 for (let dy = -radius; dy <= radius; dy++)
@@ -864,17 +981,17 @@ export class Simulation
864 981 { continue; }
865 982 const tileX = originX + dx;
866 983 const tileY = originY + dy;
867 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
868 { return { tileX, tileY }; }
984 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
985 { return { tileX, tileY, dimensionId: dim }; }
869 986 }
870 987 }
871 988 }
872 989 return null;
873 990 }
874 991
875 isEnterable (tileX, tileY)
992 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
876 993 {
877 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
994 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
878 995 if (!data.open)
879 996 { return false; }
880 997 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
@@ -943,6 +1060,15 @@ export class Simulation
943 1060 {
944 1061 if (item.command.type === "respawn")
945 1062 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1063 if (item.command.type === "enter-doorway")
1064 {
1065 return this.#relocateCharacterThroughDoorway(
1066 item.sessionId,
1067 item.command.characterId,
1068 item.command.tileX,
1069 item.command.tileY
1070 );
1071 }
946 1072 if (
947 1073 item.command.type === "open-market"
948 1074 || item.command.type === "place-market-sell"
@@ -973,6 +1099,13 @@ export class Simulation
973 1099 const result = this.barber.handleCommand(item.sessionId, item.command);
974 1100 return result?.events ?? [];
975 1101 }
1102 if (
1103 item.command.type === "dialogue-choose"
1104 || item.command.type === "dialogue-advance"
1105 || item.command.type === "close-dialogue"
1106 || item.command.type === "request-quests"
1107 )
1108 { return this.#handleQuestCommand(item); }
976 1109 const entityId = this.characterEntities.get(item.command.characterId);
977 1110 const record = entityId ? this.directory.get(entityId) : null;
978 1111 if (!record)
@@ -1042,8 +1175,19 @@ export class Simulation
1042 1175 this.#applySpellsUpdated(event);
1043 1176 continue;
1044 1177 }
1178 if (event.type === "open-dialogue")
1179 {
1180 events.push(...this.#handleOpenDialogue(event));
1181 continue;
1182 }
1045 1183 events.push(event);
1046 1184 }
1185 if (item.command.type === "attack" && item.command.targetEntityId != null)
1186 {
1187 events.push(...this.#mapQuestPrivateEvents(
1188 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1189 ));
1190 }
1047 1191 if (result?.private)
1048 1192 {
1049 1193 events.push({
@@ -1213,6 +1357,175 @@ export class Simulation
1213 1357 return events;
1214 1358 }
1215 1359
1360 #handleQuestCommand (item)
1361 {
1362 const characterId = item.command.characterId | 0;
1363 const sessionId = item.sessionId;
1364 if (!this.quests)
1365 { return []; }
1366 if (item.command.type === "request-quests")
1367 {
1368 const snap = this.quests.questSnapshot(characterId);
1369 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1370 }
1371 if (item.command.type === "close-dialogue")
1372 {
1373 const closed = this.quests.closeDialogue(characterId, "client");
1374 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1375 }
1376 if (item.command.type === "dialogue-choose")
1377 {
1378 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1379 if (!result.ok)
1380 {
1381 const error = new Error(result.error || "Choice failed.");
1382 error.userFacing = true;
1383 throw error;
1384 }
1385 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1386 }
1387 if (item.command.type === "dialogue-advance")
1388 {
1389 const result = this.quests.advanceDialogue(characterId);
1390 if (!result.ok)
1391 {
1392 const error = new Error(result.error || "Cannot advance.");
1393 error.userFacing = true;
1394 throw error;
1395 }
1396 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1397 }
1398 return [];
1399 }
1400
1401 #handleOpenDialogue (event)
1402 {
1403 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1404 if (!result.ok)
1405 {
1406 return [{
1407 type: "toast",
1408 characterId: event.characterId,
1409 sessionId: event.sessionId,
1410 message: result.error || "Nothing to say."
1411 }];
1412 }
1413 this.#pinDialogueNpc(event.entityId, event.characterId);
1414 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1415 }
1416
1417 #pinDialogueNpc (entityId, characterId)
1418 {
1419 const record = this.directory.get(entityId | 0);
1420 if (!record)
1421 { return; }
1422 this.workers[record.workerId]?.call?.({
1423 type: WorkerMessage.pinDialogue,
1424 entityId: entityId | 0,
1425 characterId: characterId | 0
1426 });
1427 }
1428
1429 #unpinDialogueNpc (entityId, characterId)
1430 {
1431 const record = this.directory.get(entityId | 0);
1432 if (!record)
1433 { return; }
1434 this.workers[record.workerId]?.call?.({
1435 type: WorkerMessage.unpinDialogue,
1436 entityId: entityId | 0,
1437 characterId: characterId | 0
1438 });
1439 }
1440
1441 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1442 {
1443 const out = [];
1444 let needSnapshot = false;
1445 for (const event of events ?? [])
1446 {
1447 const cid = event.characterId ?? characterId;
1448 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1449 if (event.type === "dialogueStep")
1450 {
1451 out.push({
1452 type: "dialogue-step",
1453 sessionId: sid,
1454 characterId: cid,
1455 dialogueId: event.dialogueId,
1456 stepId: event.stepId,
1457 label: event.label,
1458 npcEntityId: event.npcEntityId,
1459 lines: event.lines
1460 });
1461 }
1462 else if (event.type === "dialogueChoices")
1463 {
1464 out.push({
1465 type: "dialogue-choices",
1466 sessionId: sid,
1467 characterId: cid,
1468 dialogueId: event.dialogueId,
1469 stepId: event.stepId,
1470 npcEntityId: event.npcEntityId,
1471 triggers: event.triggers
1472 });
1473 }
1474 else if (event.type === "dialogueClose")
1475 {
1476 if (event.npcEntityId != null && cid != null)
1477 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1478 out.push({
1479 type: "dialogue-close",
1480 sessionId: sid,
1481 characterId: cid,
1482 reason: event.reason
1483 });
1484 }
1485 else if (event.type === "questStepComplete")
1486 {
1487 out.push({
1488 type: "quest-step-complete",
1489 sessionId: sid,
1490 characterId: cid,
1491 questId: event.questId,
1492 title: event.title
1493 });
1494 needSnapshot = true;
1495 }
1496 else if (event.type === "questsDirty")
1497 { needSnapshot = true; }
1498 else if (event.type === "inventoryDirty" && cid != null)
1499 {
1500 const onlineId = this.characterEntities.get(cid | 0);
1501 if (onlineId)
1502 {
1503 const live = this.bagOf(onlineId);
1504 if (live)
1505 { this.pushInventory(cid, live); }
1506 }
1507 }
1508 }
1509 if (needSnapshot && characterId != null)
1510 {
1511 const snap = this.quests.questSnapshot(characterId);
1512 out.push({
1513 type: "quests-snapshot",
1514 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1515 characterId,
1516 ...snap
1517 });
1518 }
1519 return out;
1520 }
1521
1522 #sessionIdForCharacter (characterId)
1523 {
1524 const entityId = this.characterEntities.get(characterId | 0);
1525 const record = entityId != null ? this.directory.get(entityId) : null;
1526 return record?.sessionId ?? null;
1527 }
1528
1216 1529 #applyMobKilled (event)
1217 1530 {
1218 1531 const out = [event];
@@ -1221,6 +1534,16 @@ export class Simulation
1221 1534 const killerPos = attackerRecord
1222 1535 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1223 1536 : null;
1537 if (killerCharacterId && this.quests)
1538 {
1539 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1540 mobTypeId: event.mobTypeId,
1541 spawnerId: event.spawnerId
1542 })));
1543 }
1544 out.push(...this.#mapQuestPrivateEvents(
1545 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1546 ));
1224 1547 let bountyAwarded = 0;
1225 1548 if (killerCharacterId && (event.bounty | 0) > 0)
1226 1549 {
@@ -1296,7 +1619,8 @@ export class Simulation
1296 1619 event.characterId,
1297 1620 event.tileX,
1298 1621 event.tileY,
1299 record.gait ?? GAIT.walk
1622 record.gait ?? GAIT.walk,
1623 record.dimensionId ?? OVERWORLD_ID
1300 1624 );
1301 1625 this.bounty?.settleKill(
1302 1626 event.characterId,
@@ -1332,6 +1656,133 @@ export class Simulation
1332 1656 return events;
1333 1657 }
1334 1658
1659 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1660 {
1661 const entityId = this.characterEntities.get(characterId);
1662 const record = entityId ? this.directory.get(entityId) : null;
1663 if (!record)
1664 {
1665 const error = new Error("Character is not in the world.");
1666 error.userFacing = true;
1667 throw error;
1668 }
1669 const tileX = doorwayTileX | 0;
1670 const tileY = doorwayTileY | 0;
1671 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1672 {
1673 const error = new Error("You are too far from that doorway.");
1674 error.userFacing = true;
1675 throw error;
1676 }
1677 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1678 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1679 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1680 if (block?.typeId !== BlockType.doorway)
1681 {
1682 const error = new Error("There is no doorway there.");
1683 error.userFacing = true;
1684 throw error;
1685 }
1686 const config = block.config && typeof block.config === "object" ? block.config : null;
1687 const targetRaw = config?.targetDimensionId;
1688 if (targetRaw == null || String(targetRaw).trim() === "")
1689 {
1690 const error = new Error("That doorway leads nowhere.");
1691 error.userFacing = true;
1692 throw error;
1693 }
1694 const targetDimensionId = normalizeDimensionId(targetRaw);
1695 const destTileX = Number(config.tileX);
1696 const destTileY = Number(config.tileY);
1697 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1698 {
1699 const error = new Error("That doorway leads nowhere.");
1700 error.userFacing = true;
1701 throw error;
1702 }
1703 const destX = destTileX | 0;
1704 const destY = destTileY | 0;
1705 if (!this.#isDimensionUsable(targetDimensionId))
1706 {
1707 const error = new Error("That place is no longer reachable.");
1708 error.userFacing = true;
1709 throw error;
1710 }
1711 if (!this.isEnterable(destX, destY, targetDimensionId))
1712 {
1713 const error = new Error("The other side is blocked.");
1714 error.userFacing = true;
1715 throw error;
1716 }
1717
1718 const events = [];
1719 if (this.quests)
1720 {
1721 const closed = this.quests.closeDialogue(characterId, "doorway");
1722 if (closed?.events?.length)
1723 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1724 }
1725
1726 const loader = { ...DEFAULT_CHUNK_LOADER };
1727 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1728 const result = this.workers[record.workerId].call({
1729 type: WorkerMessage.relocateEntity,
1730 entityId,
1731 tileX: destX,
1732 tileY: destY,
1733 dimensionId: targetDimensionId
1734 });
1735 if (!result?.accepted)
1736 {
1737 const error = new Error("Could not enter that doorway.");
1738 error.userFacing = true;
1739 throw error;
1740 }
1741 let moveEvents = [];
1742 if (result.transferRequest)
1743 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1744 else if (result.event)
1745 {
1746 this.#applyMoveToDirectory(result.event);
1747 moveEvents = [result.event];
1748 const view = this.workers[record.workerId].call({
1749 type: WorkerMessage.inspect,
1750 entityId
1751 });
1752 if (view)
1753 { this.#remember(view, record.workerId); }
1754 }
1755 if (!moveEvents.length)
1756 {
1757 const error = new Error("Could not enter that doorway.");
1758 error.userFacing = true;
1759 throw error;
1760 }
1761 this.stateDb.saveCharacterPosition(
1762 characterId,
1763 destX,
1764 destY,
1765 record.gait ?? GAIT.walk,
1766 targetDimensionId
1767 );
1768 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1769 this.#recalculateActivation(this.now);
1770 this.#syncGhosts();
1771 const dimRecord = this.getDimensionRecord(targetDimensionId);
1772 events.push(...moveEvents, {
1773 type: "dimension-changed",
1774 sessionId,
1775 characterId,
1776 entityId,
1777 dimensionId: targetDimensionId,
1778 tileX: destX,
1779 tileY: destY,
1780 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1781 seasonMode: dimRecord?.seasonMode ?? "auto"
1782 });
1783 return events;
1784 }
1785
1335 1786 #respawnCharacter (sessionId, characterId)
1336 1787 {
1337 1788 const row = this.stateDb.getCharacter(characterId);
@@ -1358,7 +1809,7 @@ export class Simulation
1358 1809 }
1359 1810 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1360 1811 const loader = { ...DEFAULT_CHUNK_LOADER };
1361 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
1812 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
1362 1813 const result = this.workers[record.workerId].call({
1363 1814 type: WorkerMessage.applyRespawn,
1364 1815 entityId,
@@ -1401,7 +1852,8 @@ export class Simulation
1401 1852 characterId,
1402 1853 destination.tileX,
1403 1854 destination.tileY,
1404 record.gait ?? GAIT.walk
1855 record.gait ?? GAIT.walk,
1856 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
1405 1857 );
1406 1858 this.#recalculateActivation(this.now);
1407 1859 this.#syncGhosts();
@@ -1427,7 +1879,8 @@ export class Simulation
1427 1879 const altars = [];
1428 1880 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1429 1881 {
1430 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1882 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
1883 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
1431 1884 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1432 1885 {
1433 1886 for (let localX = 0; localX < CHUNK_SIZE; localX++)
@@ -1437,7 +1890,8 @@ export class Simulation
1437 1890 { continue; }
1438 1891 altars.push({
1439 1892 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1440 tileY: coord.chunk_y * CHUNK_SIZE + localY
1893 tileY: coord.chunk_y * CHUNK_SIZE + localY,
1894 dimensionId: dim
1441 1895 });
1442 1896 }
1443 1897 }
@@ -1447,6 +1901,8 @@ export class Simulation
1447 1901
1448 1902 #findRespawnDestination (originX, originY, entityId)
1449 1903 {
1904 const record = this.directory.get(entityId);
1905 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
1450 1906 const ordered = [...this.altarTiles].sort((left, right) =>
1451 1907 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1452 1908 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
@@ -1460,7 +1916,7 @@ export class Simulation
1460 1916 {
1461 1917 if (dx === 0 && dy === 0)
1462 1918 { continue; }
1463 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1919 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
1464 1920 }
1465 1921 }
1466 1922 adjacent.sort((left, right) =>
@@ -1468,8 +1924,8 @@ export class Simulation
1468 1924 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1469 1925 );
1470 1926 const tile = adjacent.find((entry) =>
1471 this.isEnterable(entry.tileX, entry.tileY)
1472 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1927 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
1928 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
1473 1929 );
1474 1930 if (tile)
1475 1931 { return tile; }
@@ -1484,20 +1940,22 @@ export class Simulation
1484 1940 { continue; }
1485 1941 const tileX = originX + dx;
1486 1942 const tileY = originY + dy;
1487 if (this.isEnterable(tileX, tileY)
1488 && !this.#occupiedByOther(tileX, tileY, entityId))
1489 { return { tileX, tileY }; }
1943 if (this.isEnterable(tileX, tileY, dimensionId)
1944 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
1945 { return { tileX, tileY, dimensionId }; }
1490 1946 }
1491 1947 }
1492 1948 }
1493 1949 return this.findOpenSpawn();
1494 1950 }
1495 1951
1496 #occupiedByOther (tileX, tileY, entityId)
1952 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
1497 1953 {
1954 const dim = normalizeDimensionId(dimensionId);
1498 1955 for (const record of this.directory.values())
1499 1956 {
1500 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1957 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1958 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
1501 1959 { return true; }
1502 1960 }
1503 1961 return false;
@@ -1512,8 +1970,8 @@ export class Simulation
1512 1970 {
1513 1971 if (count <= 0)
1514 1972 { continue; }
1515 const { regionX, regionY } = parseRegionKey(key);
1516 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1973 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1974 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
1517 1975 this.regionGraceUntil.delete(key);
1518 1976 }
1519 1977
@@ -1525,8 +1983,8 @@ export class Simulation
1525 1983 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1526 1984 if (now >= this.regionGraceUntil.get(key))
1527 1985 {
1528 const { regionX, regionY } = parseRegionKey(key);
1529 this.#unloadRegion(regionX, regionY);
1986 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1987 this.#unloadRegion(regionX, regionY, dimensionId);
1530 1988 }
1531 1989 }
1532 1990
@@ -1537,8 +1995,8 @@ export class Simulation
1537 1995 {
1538 1996 if (count <= 0)
1539 1997 { continue; }
1540 const { chunkX, chunkY } = parseChunkKey(key);
1541 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1998 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1999 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
1542 2000 { chunkKeys.push(key); }
1543 2001 }
1544 2002 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
@@ -1565,29 +2023,32 @@ export class Simulation
1565 2023 { this.#stepSpawners(); }
1566 2024 }
1567 2025
1568 #ensureCoverage (tileX, tileY, loader)
2026 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
1569 2027 {
1570 const coverage = loaderCoverage(tileX, tileY, loader);
1571 let preferred = this.#ownerOfTile(tileX, tileY);
2028 const dim = normalizeDimensionId(dimensionId);
2029 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2030 let preferred = this.#ownerOfTile(tileX, tileY, dim);
1572 2031 for (const region of coverage.residentRegions)
1573 2032 {
1574 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
2033 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
1575 2034 if (preferred == null)
1576 2035 { preferred = owner; }
1577 2036 }
1578 2037 }
1579 2038
1580 #ensureRegion (regionX, regionY, preferredWorkerId)
2039 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
1581 2040 {
1582 const key = regionKey(regionX, regionY);
2041 const dim = normalizeDimensionId(dimensionId);
2042 const key = regionKey(regionX, regionY, dim);
1583 2043 if (this.regionOwner.has(key))
1584 2044 { return this.regionOwner.get(key); }
1585 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
2045 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
1586 2046 this.workers[workerId].call({
1587 2047 type: WorkerMessage.assignRegion,
1588 2048 regionX,
1589 2049 regionY,
1590 chunks: this.#regionChunkBlobs(regionX, regionY)
2050 dimensionId: dim,
2051 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
1591 2052 });
1592 2053 this.regionOwner.set(key, workerId);
1593 2054 this.#restorePersistent(regionX, regionY, workerId);
@@ -1595,9 +2056,10 @@ export class Simulation
1595 2056 return workerId;
1596 2057 }
1597 2058
1598 #unloadRegion (regionX, regionY)
2059 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
1599 2060 {
1600 const key = regionKey(regionX, regionY);
2061 const dim = normalizeDimensionId(dimensionId);
2062 const key = regionKey(regionX, regionY, dim);
1601 2063 const workerId = this.regionOwner.get(key);
1602 2064 if (workerId == null)
1603 2065 { return; }
@@ -1605,7 +2067,8 @@ export class Simulation
1605 2067 const { dropped, groundItems } = this.workers[workerId].call({
1606 2068 type: WorkerMessage.dropRegion,
1607 2069 regionX,
1608 regionY
2070 regionY,
2071 dimensionId: dim
1609 2072 });
1610 2073 const persistent = [];
1611 2074 for (const record of dropped ?? [])
@@ -1616,7 +2079,8 @@ export class Simulation
1616 2079 record.characterId,
1617 2080 record.tileX,
1618 2081 record.tileY,
1619 record.gait ?? GAIT.walk
2082 record.gait ?? GAIT.walk,
2083 record.dimensionId ?? OVERWORLD_ID
1620 2084 );
1621 2085 }
1622 2086 if (record.persistent)
@@ -1654,7 +2118,12 @@ export class Simulation
1654 2118 const events = [];
1655 2119 for (const request of requests)
1656 2120 {
1657 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
2121 const destWorkerId = this.#ensureRegion(
2122 request.toRegionX,
2123 request.toRegionY,
2124 request.fromWorkerId,
2125 request.dimensionId ?? OVERWORLD_ID
2126 );
1658 2127 if (destWorkerId === request.fromWorkerId)
1659 2128 {
1660 2129 this.workers[request.fromWorkerId].call({
@@ -1670,7 +2139,8 @@ export class Simulation
1670 2139 type: WorkerMessage.applyTransfer,
1671 2140 payload: request.payload,
1672 2141 destTileX: request.destTileX,
1673 destTileY: request.destTileY
2142 destTileY: request.destTileY,
2143 dimensionId: request.dimensionId ?? OVERWORLD_ID
1674 2144 });
1675 2145 }
1676 2146 catch
@@ -1695,8 +2165,10 @@ export class Simulation
1695 2165 entityId: request.entityId,
1696 2166 fromTileX: request.fromTileX,
1697 2167 fromTileY: request.fromTileY,
2168 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
1698 2169 tileX: result.entity.tileX,
1699 2170 tileY: result.entity.tileY,
2171 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
1700 2172 gait: result.entity.gait
1701 2173 });
1702 2174 }
@@ -1712,20 +2184,21 @@ export class Simulation
1712 2184 {
1713 2185 if (owner !== workerId)
1714 2186 { continue; }
1715 const { regionX, regionY } = parseRegionKey(key);
2187 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1716 2188 for (const chunk of chunksInRegion(regionX, regionY))
1717 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
2189 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
1718 2190 }
1719 2191 const replicas = [];
1720 2192 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1721 2193 {
1722 2194 if (ownedKeys.has(key))
1723 2195 { continue; }
1724 const { chunkX, chunkY } = parseChunkKey(key);
2196 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1725 2197 replicas.push({
1726 2198 chunkX,
1727 2199 chunkY,
1728 data: this.#authoredChunk(chunkX, chunkY)
2200 dimensionId,
2201 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
1729 2202 });
1730 2203 }
1731 2204 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
@@ -1741,23 +2214,27 @@ export class Simulation
1741 2214 {
1742 2215 const ghosts = entities.filter((entity) =>
1743 2216 {
1744 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
2217 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2218 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
1745 2219 { return false; }
1746 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
2220 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
1747 2221 });
1748 2222 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1749 2223 }
1750 2224 }
1751 2225
1752 #nearWorker (workerId, tileX, tileY)
2226 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
1753 2227 {
2228 const dim = normalizeDimensionId(dimensionId);
1754 2229 const chunkX = tileToChunk(tileX);
1755 2230 const chunkY = tileToChunk(tileY);
1756 2231 for (const [key, owner] of this.regionOwner)
1757 2232 {
1758 2233 if (owner !== workerId)
1759 2234 { continue; }
1760 const { regionX, regionY } = parseRegionKey(key);
2235 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2236 if (regionDim !== dim)
2237 { continue; }
1761 2238 for (const chunk of chunksInRegion(regionX, regionY))
1762 2239 {
1763 2240 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
@@ -1775,12 +2252,16 @@ export class Simulation
1775 2252 return loaders;
1776 2253 }
1777 2254
1778 #preferredWorkerForRegion (loaders, regionX, regionY)
2255 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
1779 2256 {
2257 const dim = normalizeDimensionId(dimensionId);
1780 2258 const votes = new Map();
1781 2259 for (const loader of loaders)
1782 2260 {
1783 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
2261 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2262 if (loaderDim !== dim)
2263 { continue; }
2264 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
1784 2265 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1785 2266 { continue; }
1786 2267 const record = this.directory.get(loader.entityId);
@@ -1801,9 +2282,10 @@ export class Simulation
1801 2282 return best;
1802 2283 }
1803 2284
1804 #pickWorker (regionX, regionY, preferredWorkerId)
2285 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
1805 2286 {
1806 const pinned = this.pinRegion?.(regionX, regionY);
2287 const dim = normalizeDimensionId(dimensionId);
2288 const pinned = this.pinRegion?.(regionX, regionY, dim);
1807 2289 if (pinned != null)
1808 2290 { return pinned; }
1809 2291
@@ -1814,7 +2296,7 @@ export class Simulation
1814 2296 {
1815 2297 if (dx === 0 && dy === 0)
1816 2298 { continue; }
1817 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
2299 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
1818 2300 if (owner != null)
1819 2301 { neighborOwners.push(owner); }
1820 2302 }
@@ -1841,46 +2323,53 @@ export class Simulation
1841 2323 return scores[0].workerId;
1842 2324 }
1843 2325
1844 #ownerOfTile (tileX, tileY)
2326 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
1845 2327 {
1846 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
2328 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
1847 2329 }
1848 2330
1849 #regionKeyForChunk (chunkX, chunkY)
2331 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1850 2332 {
1851 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
2333 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
1852 2334 }
1853 2335
1854 #regionChunkBlobs (regionX, regionY)
2336 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
1855 2337 {
2338 const dim = normalizeDimensionId(dimensionId);
1856 2339 return chunksInRegion(regionX, regionY).map((coord) => ({
1857 2340 chunkX: coord.chunkX,
1858 2341 chunkY: coord.chunkY,
1859 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
2342 dimensionId: dim,
2343 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
1860 2344 }));
1861 2345 }
1862 2346
1863 #authoredChunk (chunkX, chunkY)
2347 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1864 2348 {
1865 const key = chunkKey(chunkX, chunkY);
2349 const dim = normalizeDimensionId(dimensionId);
2350 const key = chunkKey(chunkX, chunkY, dim);
1866 2351 if (this.authoredCache.has(key))
1867 2352 { return this.authoredCache.get(key); }
1868 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
2353 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2354 const dimRecord = this.getDimensionRecord(dim);
2355 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
1869 2356 const data = row
1870 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
1871 : createEmptyChunkData(this.settings.defaultGroundTypeId);
2357 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
2358 : createEmptyChunkData(defaultGroundTypeId);
1872 2359 this.authoredCache.set(key, data);
1873 2360 return data;
1874 2361 }
1875 2362
1876 #syntheticSnapshot (chunkX, chunkY)
2363 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1877 2364 {
1878 const data = this.#authoredChunk(chunkX, chunkY);
2365 const dim = normalizeDimensionId(dimensionId);
2366 const data = this.#authoredChunk(chunkX, chunkY, dim);
1879 2367 return {
1880 2368 chunkX,
1881 2369 chunkY,
2370 dimensionId: dim,
1882 2371 open: data.open,
1883 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
2372 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
1884 2373 grounds: data.grounds,
1885 2374 blocks: data.blocks,
1886 2375 light: data.light,
@@ -1889,11 +2378,13 @@ export class Simulation
1889 2378 };
1890 2379 }
1891 2380
1892 #occupiedTile (tileX, tileY)
2381 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
1893 2382 {
2383 const dim = normalizeDimensionId(dimensionId);
1894 2384 for (const record of this.directory.values())
1895 2385 {
1896 if (record.tileX === tileX && record.tileY === tileY)
2386 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2387 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
1897 2388 { return record.entityId; }
1898 2389 }
1899 2390 return null;
@@ -2081,6 +2572,8 @@ export class Simulation
2081 2572 record.tileX = event.tileX;
2082 2573 record.tileY = event.tileY;
2083 2574 record.gait = event.gait;
2575 if (event.dimensionId != null)
2576 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2084 2577 if (event.worldX != null)
2085 2578 { record.worldX = event.worldX; }
2086 2579 if (event.worldY != null)
@@ -7,6 +7,7 @@ import {
7 STATIC_CHUNK_RADIUS,
7 STATIC_CHUNK_RADIUS,
8 WORLD_YEAR_OFFSET
8 WORLD_YEAR_OFFSET
9} from "../../../shared/protocol/constants.js";
9} from "../../../shared/protocol/constants.js";
10import { OVERWORLD_ID, normalizeDimensionId, defaultDimensionRecord } from "../../../shared/world/dimensions.js";
10import {
11import {
11 chunkKey,
12 chunkKey,
12 chunkToRegion,
13 chunkToRegion,
@@ -42,7 +43,9 @@ import { BountyService } from "../bounty/service.js";
42import { BarberService } from "../barber/service.js";
43import { BarberService } from "../barber/service.js";
43import { findReservedChequeIndex } from "../items/bags.js";
44import { findReservedChequeIndex } from "../items/bags.js";
44import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
45import { hairFromCharacterRow, appearanceHairFields } from "../../../shared/appearance/hair.js";
45
46import { QuestContentCache } from "../quests/contentCache.js";
47import { QuestRuntime } from "../quests/runtime.js";
48import { chebyshev } from "../combat/service.js";
46
49
47export class Simulation
50export class Simulation
48{
51{
@@ -75,6 +78,9 @@ export class Simulation
75 this.movementAccumulator = 0;
78 this.movementAccumulator = 0;
76 this.activeRevisionId = worldDb.getActiveRevisionId();
79 this.activeRevisionId = worldDb.getActiveRevisionId();
77 this.settings = worldDb.getLiveSettings();
80 this.settings = worldDb.getLiveSettings();
81 this.questContent = new QuestContentCache(worldDb);
82 this.dimensions = this.#loadDimensionsCache();
83 this.quests = null;
78
84
79 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
85 const WorkerImpl = this.workerMode === "thread" ? ThreadWorker : InProcessWorker;
80 for (let workerId = 0; workerId < this.workerCount; workerId++)
86 for (let workerId = 0; workerId < this.workerCount; workerId++)
@@ -106,6 +112,11 @@ export class Simulation
106 });
112 });
107 this.bounty = new BountyService(this.stateDb, this, this.courier);
113 this.bounty = new BountyService(this.stateDb, this, this.courier);
108 this.barber = new BarberService(this.stateDb, this);
114 this.barber = new BarberService(this.stateDb, this);
115 this.quests = new QuestRuntime({
116 stateDb: this.stateDb,
117 content: this.questContent,
118 simulation: this
119 });
109 this.#refreshAltarIndex();
120 this.#refreshAltarIndex();
110 }
121 }
111
122
@@ -144,20 +155,26 @@ export class Simulation
144 {
155 {
145 this.activeRevisionId = this.worldDb.getActiveRevisionId();
156 this.activeRevisionId = this.worldDb.getActiveRevisionId();
146 this.settings = this.worldDb.getLiveSettings();
157 this.settings = this.worldDb.getLiveSettings();
158 this.dimensions = this.#loadDimensionsCache();
147 this.authoredCache.clear();
159 this.authoredCache.clear();
148 this.#configureWorkers();
160 this.#configureWorkers();
149 for (const [key, workerId] of this.regionOwner)
161 for (const [key, workerId] of this.regionOwner)
150 {
162 {
151 const { regionX, regionY } = parseRegionKey(key);
163 const { regionX, regionY, dimensionId } = parseRegionKey(key);
152 this.workers[workerId].call({
164 this.workers[workerId].call({
153 type: WorkerMessage.replaceRegionChunks,
165 type: WorkerMessage.replaceRegionChunks,
154 chunks: this.#regionChunkBlobs(regionX, regionY)
166 regionX,
167 regionY,
168 dimensionId,
169 chunks: this.#regionChunkBlobs(regionX, regionY, dimensionId)
155 });
170 });
156 }
171 }
157 this.#syncAllReplicas();
172 this.#syncAllReplicas();
158 this.courier?.refreshBankIndex();
173 this.courier?.refreshBankIndex();
159 this.courier?.refreshBountyOfficeIndex();
174 this.courier?.refreshBountyOfficeIndex();
160 this.market?.refreshIndex();
175 this.market?.refreshIndex();
176 this.questContent.reload();
177 this.quests?.closeAllSessions();
161 this.#refreshAltarIndex();
178 this.#refreshAltarIndex();
162 }
179 }
163
180
@@ -169,6 +186,8 @@ export class Simulation
169 step (now = this.now)
186 step (now = this.now)
170 {
187 {
171 this.tickIndex += 1;
188 this.tickIndex += 1;
189 if ((this.tickIndex % 1200) === 0)
190 { this.worldDb.purgeExpiredDimensions(now); }
172 const events = [];
191 const events = [];
173 const commands = this.commandQueue.splice(0);
192 const commands = this.commandQueue.splice(0);
174 for (const item of commands)
193 for (const item of commands)
@@ -249,6 +268,16 @@ export class Simulation
249 events.push(...this.#applyMobKilled(event));
268 events.push(...this.#applyMobKilled(event));
250 continue;
269 continue;
251 }
270 }
271 if (event.type === "dialogue-walk-away")
272 {
273 const closed = this.quests?.closeDialogue(event.characterId, "walk-away");
274 events.push(...this.#mapQuestPrivateEvents(
275 closed?.events ?? [],
276 event.sessionId,
277 event.characterId
278 ));
279 continue;
280 }
252 this.#persistGroundEvent(event);
281 this.#persistGroundEvent(event);
253 if (event.type !== "skills-updated")
282 if (event.type !== "skills-updated")
254 { events.push(event); }
283 { events.push(event); }
@@ -341,19 +370,42 @@ export class Simulation
341 const row = this.stateDb.getCharacter(character.character_id) ?? character;
370 const row = this.stateDb.getCharacter(character.character_id) ?? character;
342 let tileX = row.tile_x;
371 let tileX = row.tile_x;
343 let tileY = row.tile_y;
372 let tileY = row.tile_y;
373 let dimensionId = normalizeDimensionId(row.dimension_id ?? OVERWORLD_ID);
344 const gait = row.gait || character.gait || GAIT.walk;
374 const gait = row.gait || character.gait || GAIT.walk;
345 const preferred = this.#findResumeTile(tileX, tileY);
375
376 // Soft-deleted / purged interiors eject to overworld spawn.
377 if (!this.#isDimensionUsable(dimensionId))
378 {
379 dimensionId = OVERWORLD_ID;
380 const spawn = this.findOpenSpawn();
381 if (!spawn)
382 {
383 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
384 error.userFacing = true;
385 throw error;
386 }
387 tileX = spawn.tileX;
388 tileY = spawn.tileY;
389 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
390 }
391
392 const preferred = this.#findResumeTile(tileX, tileY, 24, dimensionId);
346 if (!preferred)
393 if (!preferred)
347 {
394 {
348 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
395 const error = new Error("No open chunk is available to enter. Open a chunk in the world editor first.");
349 error.userFacing = true;
396 error.userFacing = true;
350 throw error;
397 throw error;
351 }
398 }
352 if (preferred.tileX !== tileX || preferred.tileY !== tileY)
399 if (
400 preferred.tileX !== tileX
401 || preferred.tileY !== tileY
402 || normalizeDimensionId(preferred.dimensionId ?? dimensionId) !== dimensionId
403 )
353 {
404 {
354 tileX = preferred.tileX;
405 tileX = preferred.tileX;
355 tileY = preferred.tileY;
406 tileY = preferred.tileY;
356 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait);
407 dimensionId = normalizeDimensionId(preferred.dimensionId ?? dimensionId);
408 this.stateDb.saveCharacterPosition(character.character_id, tileX, tileY, gait, dimensionId);
357 }
409 }
358
410
359 const bag = this.stateDb.getBag(character.character_id) ?? {
411 const bag = this.stateDb.getBag(character.character_id) ?? {
@@ -378,7 +430,7 @@ export class Simulation
378 : maxHealth;
430 : maxHealth;
379 const entityId = this.nextEntityId++;
431 const entityId = this.nextEntityId++;
380 const components = {
432 const components = {
381 position: { tileX, tileY },
433 position: { tileX, tileY, dimensionId },
382 movement: { gait, walkCarry: 0 },
434 movement: { gait, walkCarry: 0 },
383 path: { tiles: [] },
435 path: { tiles: [] },
384 appearance: {
436 appearance: {
@@ -413,14 +465,15 @@ export class Simulation
413 };
465 };
414 if (isDead)
466 if (isDead)
415 { components.dead = {}; }
467 { components.dead = {}; }
416 this.#ensureCoverage(tileX, tileY, components.chunkLoader);
468 this.#ensureCoverage(tileX, tileY, components.chunkLoader, dimensionId);
417 const workerId = this.#ownerOfTile(tileX, tileY);
469 const workerId = this.#ownerOfTile(tileX, tileY, dimensionId);
418 const view = this.workers[workerId].call({
470 const view = this.workers[workerId].call({
419 type: WorkerMessage.spawn,
471 type: WorkerMessage.spawn,
420 entityId,
472 entityId,
421 components
473 components
422 });
474 });
423 this.#remember(view, workerId);
475 this.#remember(view, workerId);
476 this.stateDb.markDimensionVisited(character.character_id, dimensionId);
424 this.#queueReplication(replicationSpawn(view));
477 this.#queueReplication(replicationSpawn(view));
425 this.#recalculateActivation(this.now);
478 this.#recalculateActivation(this.now);
426 this.#syncGhosts();
479 this.#syncGhosts();
@@ -440,10 +493,12 @@ export class Simulation
440 const position = components.position;
493 const position = components.position;
441 if (!position)
494 if (!position)
442 { throw new Error("spawnEntity requires position."); }
495 { throw new Error("spawnEntity requires position."); }
496 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
497 position.dimensionId = dimensionId;
443 if (options.requireResident)
498 if (options.requireResident)
444 {
499 {
445 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
500 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
446 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY))
501 if (workerId == null || !this.chunkIsSimulating(position.tileX, position.tileY, dimensionId))
447 { return null; }
502 { return null; }
448 const view = this.workers[workerId].call({
503 const view = this.workers[workerId].call({
449 type: WorkerMessage.spawn,
504 type: WorkerMessage.spawn,
@@ -457,16 +512,17 @@ export class Simulation
457 return entityId;
512 return entityId;
458 }
513 }
459 if (components.chunkLoader)
514 if (components.chunkLoader)
460 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader); }
515 { this.#ensureCoverage(position.tileX, position.tileY, components.chunkLoader, dimensionId); }
461 else
516 else
462 {
517 {
463 this.#ensureRegion(
518 this.#ensureRegion(
464 tileToRegion(position.tileX),
519 tileToRegion(position.tileX),
465 tileToRegion(position.tileY),
520 tileToRegion(position.tileY),
466 null
521 null,
522 dimensionId
467 );
523 );
468 }
524 }
469 const workerId = this.#ownerOfTile(position.tileX, position.tileY);
525 const workerId = this.#ownerOfTile(position.tileX, position.tileY, dimensionId);
470 const view = this.workers[workerId].call({
526 const view = this.workers[workerId].call({
471 type: WorkerMessage.spawn,
527 type: WorkerMessage.spawn,
472 entityId,
528 entityId,
@@ -494,11 +550,11 @@ export class Simulation
494 this.#forget(entityId);
550 this.#forget(entityId);
495 }
551 }
496
552
497 chunkIsSimulating (tileX, tileY)
553 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
498 {
554 {
499 const loaders = this.#allLoaders();
555 const loaders = this.#allLoaders();
500 const { chunkSim } = accumulateLoaderRefs(loaders);
556 const { chunkSim } = accumulateLoaderRefs(loaders);
501 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY))) ?? 0) > 0;
557 return (chunkSim.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId)) ?? 0) > 0;
502 }
558 }
503
559
504 updateCourierFlight (entityId, flightPatch, now = this.now)
560 updateCourierFlight (entityId, flightPatch, now = this.now)
@@ -508,7 +564,8 @@ export class Simulation
508 { return { despawned: true, entityId }; }
564 { return { despawned: true, entityId }; }
509 const tileX = Math.floor(flightPatch.x);
565 const tileX = Math.floor(flightPatch.x);
510 const tileY = Math.floor(flightPatch.y);
566 const tileY = Math.floor(flightPatch.y);
511 const owner = this.#ownerOfTile(tileX, tileY);
567 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
568 const owner = this.#ownerOfTile(tileX, tileY, dimensionId);
512 if (owner == null || owner !== record.workerId)
569 if (owner == null || owner !== record.workerId)
513 {
570 {
514 this.despawnEntity(entityId);
571 this.despawnEntity(entityId);
@@ -672,7 +729,7 @@ export class Simulation
672 */
729 */
673 stationExchangeClerk (stationTileX, stationTileY)
730 stationExchangeClerk (stationTileX, stationTileY)
674 {
731 {
675 const owner = this.#ownerOfTile(stationTileX, stationTileY);
732 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
676 if (owner == null)
733 if (owner == null)
677 { return { ok: false, reason: "unowned" }; }
734 { return { ok: false, reason: "unowned" }; }
678 return this.workers[owner].call({
735 return this.workers[owner].call({
@@ -707,7 +764,7 @@ export class Simulation
707 /** Release a CE clerk stationed at the given staff-side tile. */
764 /** Release a CE clerk stationed at the given staff-side tile. */
708 releaseExchangeClerk (stationTileX, stationTileY)
765 releaseExchangeClerk (stationTileX, stationTileY)
709 {
766 {
710 const owner = this.#ownerOfTile(stationTileX, stationTileY);
767 const owner = this.#ownerOfTile(stationTileX, stationTileY, OVERWORLD_ID);
711 if (owner == null)
768 if (owner == null)
712 { return { ok: false, reason: "unowned" }; }
769 { return { ok: false, reason: "unowned" }; }
713 return this.workers[owner].call({
770 return this.workers[owner].call({
@@ -740,7 +797,8 @@ export class Simulation
740 characterId,
797 characterId,
741 dropped.tileX,
798 dropped.tileX,
742 dropped.tileY,
799 dropped.tileY,
743 dropped.gait ?? GAIT.walk
800 dropped.gait ?? GAIT.walk,
801 dropped.dimensionId ?? OVERWORLD_ID
744 );
802 );
745 if (dropped.health != null)
803 if (dropped.health != null)
746 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
804 { this.stateDb.saveCharacterHealth(characterId, dropped.health); }
@@ -765,7 +823,13 @@ export class Simulation
765 positionOf (entityId)
823 positionOf (entityId)
766 {
824 {
767 const record = this.directory.get(entityId);
825 const record = this.directory.get(entityId);
768 return record ? { tileX: record.tileX, tileY: record.tileY } : null;
826 return record
827 ? {
828 tileX: record.tileX,
829 tileY: record.tileY,
830 dimensionId: normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID)
831 }
832 : null;
769 }
833 }
770
834
771 bagOf (entityId)
835 bagOf (entityId)
@@ -784,8 +848,9 @@ export class Simulation
784 const record = this.directory.get(entityId);
848 const record = this.directory.get(entityId);
785 if (!record)
849 if (!record)
786 { return []; }
850 { return []; }
851 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
787 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
852 const coords = visibleChunkCoords(tileToChunk(record.tileX), tileToChunk(record.tileY), VISIBLE_CHUNK_RADIUS);
788 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false));
853 return coords.map((coord) => this.snapshotChunk(coord.chunkX, coord.chunkY, false, dimensionId));
789 }
854 }
790
855
791 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
856 /** Client view: map ring uses `staticRadius` (default STATIC_CHUNK_RADIUS); entities stay at VISIBLE_CHUNK_RADIUS. */
@@ -794,42 +859,45 @@ export class Simulation
794 const record = this.directory.get(entityId);
859 const record = this.directory.get(entityId);
795 if (!record)
860 if (!record)
796 { return []; }
861 { return []; }
862 const dimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
797 const centerChunkX = tileToChunk(record.tileX);
863 const centerChunkX = tileToChunk(record.tileX);
798 const centerChunkY = tileToChunk(record.tileY);
864 const centerChunkY = tileToChunk(record.tileY);
799 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
865 const mapRadius = Math.max(VISIBLE_CHUNK_RADIUS, staticRadius | 0);
800 const entityKeys = new Set(
866 const entityKeys = new Set(
801 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
867 visibleChunkCoords(centerChunkX, centerChunkY, VISIBLE_CHUNK_RADIUS)
802 .map((coord) => chunkKey(coord.chunkX, coord.chunkY))
868 .map((coord) => chunkKey(coord.chunkX, coord.chunkY, dimensionId))
803 );
869 );
804 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
870 return visibleChunkCoords(centerChunkX, centerChunkY, mapRadius)
805 .map((coord) =>
871 .map((coord) =>
806 {
872 {
807 const key = chunkKey(coord.chunkX, coord.chunkY);
873 const key = chunkKey(coord.chunkX, coord.chunkY, dimensionId);
808 const staticOnly = !entityKeys.has(key);
874 const staticOnly = !entityKeys.has(key);
809 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly);
875 const snapshot = this.snapshotChunk(coord.chunkX, coord.chunkY, staticOnly, dimensionId);
810 return { ...snapshot, staticOnly };
876 return { ...snapshot, staticOnly };
811 });
877 });
812 }
878 }
813
879
814 snapshotChunk (chunkX, chunkY, staticOnly = false)
880 snapshotChunk (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
815 {
881 {
816 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY));
882 const dim = normalizeDimensionId(dimensionId);
883 const owner = this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dim));
817 if (owner == null)
884 if (owner == null)
818 { return this.#syntheticSnapshot(chunkX, chunkY, staticOnly); }
885 { return this.#syntheticSnapshot(chunkX, chunkY, dim); }
819 return this.workers[owner].call({
886 return this.workers[owner].call({
820 type: WorkerMessage.snapshotChunk,
887 type: WorkerMessage.snapshotChunk,
821 chunkX,
888 chunkX,
822 chunkY,
889 chunkY,
890 dimensionId: dim,
823 staticOnly: !!staticOnly
891 staticOnly: !!staticOnly
824 });
892 });
825 }
893 }
826
894
827 findOpenSpawn ()
895 findOpenSpawn ()
828 {
896 {
829 const coords = this.worldDb.listChunkCoords(this.activeRevisionId);
897 const coords = this.worldDb.listChunkCoords(this.activeRevisionId, OVERWORLD_ID);
830 for (const coord of coords)
898 for (const coord of coords)
831 {
899 {
832 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
900 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, OVERWORLD_ID);
833 if (!data.open)
901 if (!data.open)
834 { continue; }
902 { continue; }
835 for (let localY = 0; localY < CHUNK_SIZE; localY++)
903 for (let localY = 0; localY < CHUNK_SIZE; localY++)
@@ -838,8 +906,8 @@ export class Simulation
838 {
906 {
839 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
907 const tileX = coord.chunk_x * CHUNK_SIZE + localX;
840 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
908 const tileY = coord.chunk_y * CHUNK_SIZE + localY;
841 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
909 if (this.isEnterable(tileX, tileY, OVERWORLD_ID) && !this.#occupiedTile(tileX, tileY, OVERWORLD_ID))
842 { return { tileX, tileY }; }
910 { return { tileX, tileY, dimensionId: OVERWORLD_ID }; }
843 }
911 }
844 }
912 }
845 }
913 }
@@ -847,13 +915,62 @@ export class Simulation
847 }
915 }
848
916
849 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
917 /** Prefer the saved tile; otherwise spiral nearby before falling back to a world spawn. */
850 #findResumeTile (tileX, tileY, radius = 24)
918 #findResumeTile (tileX, tileY, radius = 24, dimensionId = OVERWORLD_ID)
851 {
919 {
852 return this.#findNearbyEnterable(tileX, tileY, radius) ?? this.findOpenSpawn();
920 const dim = normalizeDimensionId(dimensionId);
921 return this.#findNearbyEnterable(tileX, tileY, radius, dim)
922 ?? (dim === OVERWORLD_ID ? this.findOpenSpawn() : this.findOpenSpawn());
853 }
923 }
854
924
855 #findNearbyEnterable (originX, originY, maxRadius)
925 #isDimensionUsable (dimensionId)
856 {
926 {
927 const dim = normalizeDimensionId(dimensionId);
928 if (dim === OVERWORLD_ID)
929 { return true; }
930 const record = this.getDimensionRecord(dim);
931 if (!record)
932 { return false; }
933 if (record.deletedAt != null)
934 { return false; }
935 if (record.purgeAfter != null && record.purgeAfter <= this.now)
936 { return false; }
937 return true;
938 }
939
940 #loadDimensionsCache ()
941 {
942 const map = new Map();
943 for (const dim of this.worldDb.listDimensions(this.activeRevisionId))
944 { map.set(dim.dimensionId, dim); }
945 if (!map.has(OVERWORLD_ID))
946 {
947 map.set(OVERWORLD_ID, defaultDimensionRecord(OVERWORLD_ID, {
948 defaultGroundTypeId: this.settings.defaultGroundTypeId
949 }));
950 }
951 return map;
952 }
953
954 getDimensionRecord (dimensionId)
955 {
956 const dim = normalizeDimensionId(dimensionId);
957 return this.dimensions?.get(dim)
958 ?? this.worldDb.getDimensionAtOrBefore(this.activeRevisionId, dim)
959 ?? (dim === OVERWORLD_ID
960 ? defaultDimensionRecord(OVERWORLD_ID, {
961 defaultGroundTypeId: this.settings.defaultGroundTypeId
962 })
963 : null);
964 }
965
966 listDimensionRecords ()
967 {
968 return [...(this.dimensions?.values?.() ?? this.worldDb.listDimensions(this.activeRevisionId))];
969 }
970
971 #findNearbyEnterable (originX, originY, maxRadius, dimensionId = OVERWORLD_ID)
972 {
973 const dim = normalizeDimensionId(dimensionId);
857 for (let radius = 0; radius <= maxRadius; radius++)
974 for (let radius = 0; radius <= maxRadius; radius++)
858 {
975 {
859 for (let dy = -radius; dy <= radius; dy++)
976 for (let dy = -radius; dy <= radius; dy++)
@@ -864,17 +981,17 @@ export class Simulation
864 { continue; }
981 { continue; }
865 const tileX = originX + dx;
982 const tileX = originX + dx;
866 const tileY = originY + dy;
983 const tileY = originY + dy;
867 if (this.isEnterable(tileX, tileY) && !this.#occupiedTile(tileX, tileY))
984 if (this.isEnterable(tileX, tileY, dim) && !this.#occupiedTile(tileX, tileY, dim))
868 { return { tileX, tileY }; }
985 { return { tileX, tileY, dimensionId: dim }; }
869 }
986 }
870 }
987 }
871 }
988 }
872 return null;
989 return null;
873 }
990 }
874
991
875 isEnterable (tileX, tileY)
992 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
876 {
993 {
877 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY));
994 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
878 if (!data.open)
995 if (!data.open)
879 { return false; }
996 { return false; }
880 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
997 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
@@ -943,6 +1060,15 @@ export class Simulation
943 {
1060 {
944 if (item.command.type === "respawn")
1061 if (item.command.type === "respawn")
945 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1062 { return this.#respawnCharacter(item.sessionId, item.command.characterId); }
1063 if (item.command.type === "enter-doorway")
1064 {
1065 return this.#relocateCharacterThroughDoorway(
1066 item.sessionId,
1067 item.command.characterId,
1068 item.command.tileX,
1069 item.command.tileY
1070 );
1071 }
946 if (
1072 if (
947 item.command.type === "open-market"
1073 item.command.type === "open-market"
948 || item.command.type === "place-market-sell"
1074 || item.command.type === "place-market-sell"
@@ -973,6 +1099,13 @@ export class Simulation
973 const result = this.barber.handleCommand(item.sessionId, item.command);
1099 const result = this.barber.handleCommand(item.sessionId, item.command);
974 return result?.events ?? [];
1100 return result?.events ?? [];
975 }
1101 }
1102 if (
1103 item.command.type === "dialogue-choose"
1104 || item.command.type === "dialogue-advance"
1105 || item.command.type === "close-dialogue"
1106 || item.command.type === "request-quests"
1107 )
1108 { return this.#handleQuestCommand(item); }
976 const entityId = this.characterEntities.get(item.command.characterId);
1109 const entityId = this.characterEntities.get(item.command.characterId);
977 const record = entityId ? this.directory.get(entityId) : null;
1110 const record = entityId ? this.directory.get(entityId) : null;
978 if (!record)
1111 if (!record)
@@ -1042,8 +1175,19 @@ export class Simulation
1042 this.#applySpellsUpdated(event);
1175 this.#applySpellsUpdated(event);
1043 continue;
1176 continue;
1044 }
1177 }
1178 if (event.type === "open-dialogue")
1179 {
1180 events.push(...this.#handleOpenDialogue(event));
1181 continue;
1182 }
1045 events.push(event);
1183 events.push(event);
1046 }
1184 }
1185 if (item.command.type === "attack" && item.command.targetEntityId != null)
1186 {
1187 events.push(...this.#mapQuestPrivateEvents(
1188 this.quests?.interruptDialogueForEntity(item.command.targetEntityId) ?? []
1189 ));
1190 }
1047 if (result?.private)
1191 if (result?.private)
1048 {
1192 {
1049 events.push({
1193 events.push({
@@ -1213,6 +1357,175 @@ export class Simulation
1213 return events;
1357 return events;
1214 }
1358 }
1215
1359
1360 #handleQuestCommand (item)
1361 {
1362 const characterId = item.command.characterId | 0;
1363 const sessionId = item.sessionId;
1364 if (!this.quests)
1365 { return []; }
1366 if (item.command.type === "request-quests")
1367 {
1368 const snap = this.quests.questSnapshot(characterId);
1369 return [{ type: "quests-snapshot", sessionId, characterId, ...snap }];
1370 }
1371 if (item.command.type === "close-dialogue")
1372 {
1373 const closed = this.quests.closeDialogue(characterId, "client");
1374 return this.#mapQuestPrivateEvents(closed.events, sessionId, characterId);
1375 }
1376 if (item.command.type === "dialogue-choose")
1377 {
1378 const result = this.quests.chooseDialogue(characterId, item.command.trigger);
1379 if (!result.ok)
1380 {
1381 const error = new Error(result.error || "Choice failed.");
1382 error.userFacing = true;
1383 throw error;
1384 }
1385 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1386 }
1387 if (item.command.type === "dialogue-advance")
1388 {
1389 const result = this.quests.advanceDialogue(characterId);
1390 if (!result.ok)
1391 {
1392 const error = new Error(result.error || "Cannot advance.");
1393 error.userFacing = true;
1394 throw error;
1395 }
1396 return this.#mapQuestPrivateEvents(result.events, sessionId, characterId);
1397 }
1398 return [];
1399 }
1400
1401 #handleOpenDialogue (event)
1402 {
1403 const result = this.quests.tryOpenDialogue(event.characterId, event.entityId, event.dialogueId);
1404 if (!result.ok)
1405 {
1406 return [{
1407 type: "toast",
1408 characterId: event.characterId,
1409 sessionId: event.sessionId,
1410 message: result.error || "Nothing to say."
1411 }];
1412 }
1413 this.#pinDialogueNpc(event.entityId, event.characterId);
1414 return this.#mapQuestPrivateEvents(result.events, event.sessionId, event.characterId);
1415 }
1416
1417 #pinDialogueNpc (entityId, characterId)
1418 {
1419 const record = this.directory.get(entityId | 0);
1420 if (!record)
1421 { return; }
1422 this.workers[record.workerId]?.call?.({
1423 type: WorkerMessage.pinDialogue,
1424 entityId: entityId | 0,
1425 characterId: characterId | 0
1426 });
1427 }
1428
1429 #unpinDialogueNpc (entityId, characterId)
1430 {
1431 const record = this.directory.get(entityId | 0);
1432 if (!record)
1433 { return; }
1434 this.workers[record.workerId]?.call?.({
1435 type: WorkerMessage.unpinDialogue,
1436 entityId: entityId | 0,
1437 characterId: characterId | 0
1438 });
1439 }
1440
1441 #mapQuestPrivateEvents (events, sessionId = null, characterId = null)
1442 {
1443 const out = [];
1444 let needSnapshot = false;
1445 for (const event of events ?? [])
1446 {
1447 const cid = event.characterId ?? characterId;
1448 const sid = sessionId ?? this.#sessionIdForCharacter(cid);
1449 if (event.type === "dialogueStep")
1450 {
1451 out.push({
1452 type: "dialogue-step",
1453 sessionId: sid,
1454 characterId: cid,
1455 dialogueId: event.dialogueId,
1456 stepId: event.stepId,
1457 label: event.label,
1458 npcEntityId: event.npcEntityId,
1459 lines: event.lines
1460 });
1461 }
1462 else if (event.type === "dialogueChoices")
1463 {
1464 out.push({
1465 type: "dialogue-choices",
1466 sessionId: sid,
1467 characterId: cid,
1468 dialogueId: event.dialogueId,
1469 stepId: event.stepId,
1470 npcEntityId: event.npcEntityId,
1471 triggers: event.triggers
1472 });
1473 }
1474 else if (event.type === "dialogueClose")
1475 {
1476 if (event.npcEntityId != null && cid != null)
1477 { this.#unpinDialogueNpc(event.npcEntityId, cid); }
1478 out.push({
1479 type: "dialogue-close",
1480 sessionId: sid,
1481 characterId: cid,
1482 reason: event.reason
1483 });
1484 }
1485 else if (event.type === "questStepComplete")
1486 {
1487 out.push({
1488 type: "quest-step-complete",
1489 sessionId: sid,
1490 characterId: cid,
1491 questId: event.questId,
1492 title: event.title
1493 });
1494 needSnapshot = true;
1495 }
1496 else if (event.type === "questsDirty")
1497 { needSnapshot = true; }
1498 else if (event.type === "inventoryDirty" && cid != null)
1499 {
1500 const onlineId = this.characterEntities.get(cid | 0);
1501 if (onlineId)
1502 {
1503 const live = this.bagOf(onlineId);
1504 if (live)
1505 { this.pushInventory(cid, live); }
1506 }
1507 }
1508 }
1509 if (needSnapshot && characterId != null)
1510 {
1511 const snap = this.quests.questSnapshot(characterId);
1512 out.push({
1513 type: "quests-snapshot",
1514 sessionId: sessionId ?? this.#sessionIdForCharacter(characterId),
1515 characterId,
1516 ...snap
1517 });
1518 }
1519 return out;
1520 }
1521
1522 #sessionIdForCharacter (characterId)
1523 {
1524 const entityId = this.characterEntities.get(characterId | 0);
1525 const record = entityId != null ? this.directory.get(entityId) : null;
1526 return record?.sessionId ?? null;
1527 }
1528
1216 #applyMobKilled (event)
1529 #applyMobKilled (event)
1217 {
1530 {
1218 const out = [event];
1531 const out = [event];
@@ -1221,6 +1534,16 @@ export class Simulation
1221 const killerPos = attackerRecord
1534 const killerPos = attackerRecord
1222 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1535 ? { tileX: attackerRecord.tileX, tileY: attackerRecord.tileY }
1223 : null;
1536 : null;
1537 if (killerCharacterId && this.quests)
1538 {
1539 out.push(...this.#mapQuestPrivateEvents(this.quests.noteKill(killerCharacterId, {
1540 mobTypeId: event.mobTypeId,
1541 spawnerId: event.spawnerId
1542 })));
1543 }
1544 out.push(...this.#mapQuestPrivateEvents(
1545 this.quests?.interruptDialogueForEntity(event.entityId) ?? []
1546 ));
1224 let bountyAwarded = 0;
1547 let bountyAwarded = 0;
1225 if (killerCharacterId && (event.bounty | 0) > 0)
1548 if (killerCharacterId && (event.bounty | 0) > 0)
1226 {
1549 {
@@ -1296,7 +1619,8 @@ export class Simulation
1296 event.characterId,
1619 event.characterId,
1297 event.tileX,
1620 event.tileX,
1298 event.tileY,
1621 event.tileY,
1299 record.gait ?? GAIT.walk
1622 record.gait ?? GAIT.walk,
1623 record.dimensionId ?? OVERWORLD_ID
1300 );
1624 );
1301 this.bounty?.settleKill(
1625 this.bounty?.settleKill(
1302 event.characterId,
1626 event.characterId,
@@ -1332,6 +1656,133 @@ export class Simulation
1332 return events;
1656 return events;
1333 }
1657 }
1334
1658
1659 #relocateCharacterThroughDoorway (sessionId, characterId, doorwayTileX, doorwayTileY)
1660 {
1661 const entityId = this.characterEntities.get(characterId);
1662 const record = entityId ? this.directory.get(entityId) : null;
1663 if (!record)
1664 {
1665 const error = new Error("Character is not in the world.");
1666 error.userFacing = true;
1667 throw error;
1668 }
1669 const tileX = doorwayTileX | 0;
1670 const tileY = doorwayTileY | 0;
1671 if (chebyshev(record.tileX, record.tileY, tileX, tileY) > 1)
1672 {
1673 const error = new Error("You are too far from that doorway.");
1674 error.userFacing = true;
1675 throw error;
1676 }
1677 const fromDimensionId = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1678 const data = this.#authoredChunk(tileToChunk(tileX), tileToChunk(tileY), fromDimensionId);
1679 const block = data.blocks[tileToLocal(tileY) * CHUNK_SIZE + tileToLocal(tileX)];
1680 if (block?.typeId !== BlockType.doorway)
1681 {
1682 const error = new Error("There is no doorway there.");
1683 error.userFacing = true;
1684 throw error;
1685 }
1686 const config = block.config && typeof block.config === "object" ? block.config : null;
1687 const targetRaw = config?.targetDimensionId;
1688 if (targetRaw == null || String(targetRaw).trim() === "")
1689 {
1690 const error = new Error("That doorway leads nowhere.");
1691 error.userFacing = true;
1692 throw error;
1693 }
1694 const targetDimensionId = normalizeDimensionId(targetRaw);
1695 const destTileX = Number(config.tileX);
1696 const destTileY = Number(config.tileY);
1697 if (!Number.isFinite(destTileX) || !Number.isFinite(destTileY))
1698 {
1699 const error = new Error("That doorway leads nowhere.");
1700 error.userFacing = true;
1701 throw error;
1702 }
1703 const destX = destTileX | 0;
1704 const destY = destTileY | 0;
1705 if (!this.#isDimensionUsable(targetDimensionId))
1706 {
1707 const error = new Error("That place is no longer reachable.");
1708 error.userFacing = true;
1709 throw error;
1710 }
1711 if (!this.isEnterable(destX, destY, targetDimensionId))
1712 {
1713 const error = new Error("The other side is blocked.");
1714 error.userFacing = true;
1715 throw error;
1716 }
1717
1718 const events = [];
1719 if (this.quests)
1720 {
1721 const closed = this.quests.closeDialogue(characterId, "doorway");
1722 if (closed?.events?.length)
1723 { events.push(...this.#mapQuestPrivateEvents(closed.events, sessionId, characterId)); }
1724 }
1725
1726 const loader = { ...DEFAULT_CHUNK_LOADER };
1727 this.#ensureCoverage(destX, destY, loader, targetDimensionId);
1728 const result = this.workers[record.workerId].call({
1729 type: WorkerMessage.relocateEntity,
1730 entityId,
1731 tileX: destX,
1732 tileY: destY,
1733 dimensionId: targetDimensionId
1734 });
1735 if (!result?.accepted)
1736 {
1737 const error = new Error("Could not enter that doorway.");
1738 error.userFacing = true;
1739 throw error;
1740 }
1741 let moveEvents = [];
1742 if (result.transferRequest)
1743 { moveEvents = this.#applyTransfers([{ ...result.transferRequest, fromWorkerId: record.workerId }]); }
1744 else if (result.event)
1745 {
1746 this.#applyMoveToDirectory(result.event);
1747 moveEvents = [result.event];
1748 const view = this.workers[record.workerId].call({
1749 type: WorkerMessage.inspect,
1750 entityId
1751 });
1752 if (view)
1753 { this.#remember(view, record.workerId); }
1754 }
1755 if (!moveEvents.length)
1756 {
1757 const error = new Error("Could not enter that doorway.");
1758 error.userFacing = true;
1759 throw error;
1760 }
1761 this.stateDb.saveCharacterPosition(
1762 characterId,
1763 destX,
1764 destY,
1765 record.gait ?? GAIT.walk,
1766 targetDimensionId
1767 );
1768 this.stateDb.markDimensionVisited(characterId, targetDimensionId);
1769 this.#recalculateActivation(this.now);
1770 this.#syncGhosts();
1771 const dimRecord = this.getDimensionRecord(targetDimensionId);
1772 events.push(...moveEvents, {
1773 type: "dimension-changed",
1774 sessionId,
1775 characterId,
1776 entityId,
1777 dimensionId: targetDimensionId,
1778 tileX: destX,
1779 tileY: destY,
1780 lightingMode: dimRecord?.lightingMode ?? "dayNight",
1781 seasonMode: dimRecord?.seasonMode ?? "auto"
1782 });
1783 return events;
1784 }
1785
1335 #respawnCharacter (sessionId, characterId)
1786 #respawnCharacter (sessionId, characterId)
1336 {
1787 {
1337 const row = this.stateDb.getCharacter(characterId);
1788 const row = this.stateDb.getCharacter(characterId);
@@ -1358,7 +1809,7 @@ export class Simulation
1358 }
1809 }
1359 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1810 const skills = this.stateDb.getSkills(characterId) ?? defaultPlayerSkills();
1360 const loader = { ...DEFAULT_CHUNK_LOADER };
1811 const loader = { ...DEFAULT_CHUNK_LOADER };
1361 this.#ensureCoverage(destination.tileX, destination.tileY, loader);
1812 this.#ensureCoverage(destination.tileX, destination.tileY, loader, destination.dimensionId ?? OVERWORLD_ID);
1362 const result = this.workers[record.workerId].call({
1813 const result = this.workers[record.workerId].call({
1363 type: WorkerMessage.applyRespawn,
1814 type: WorkerMessage.applyRespawn,
1364 entityId,
1815 entityId,
@@ -1401,7 +1852,8 @@ export class Simulation
1401 characterId,
1852 characterId,
1402 destination.tileX,
1853 destination.tileX,
1403 destination.tileY,
1854 destination.tileY,
1404 record.gait ?? GAIT.walk
1855 record.gait ?? GAIT.walk,
1856 destination.dimensionId ?? record.dimensionId ?? OVERWORLD_ID
1405 );
1857 );
1406 this.#recalculateActivation(this.now);
1858 this.#recalculateActivation(this.now);
1407 this.#syncGhosts();
1859 this.#syncGhosts();
@@ -1427,7 +1879,8 @@ export class Simulation
1427 const altars = [];
1879 const altars = [];
1428 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1880 for (const coord of this.worldDb.listChunkCoords(this.activeRevisionId))
1429 {
1881 {
1430 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y);
1882 const dim = normalizeDimensionId(coord.dimension_id ?? OVERWORLD_ID);
1883 const data = this.#authoredChunk(coord.chunk_x, coord.chunk_y, dim);
1431 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1884 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1432 {
1885 {
1433 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1886 for (let localX = 0; localX < CHUNK_SIZE; localX++)
@@ -1437,7 +1890,8 @@ export class Simulation
1437 { continue; }
1890 { continue; }
1438 altars.push({
1891 altars.push({
1439 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1892 tileX: coord.chunk_x * CHUNK_SIZE + localX,
1440 tileY: coord.chunk_y * CHUNK_SIZE + localY
1893 tileY: coord.chunk_y * CHUNK_SIZE + localY,
1894 dimensionId: dim
1441 });
1895 });
1442 }
1896 }
1443 }
1897 }
@@ -1447,6 +1901,8 @@ export class Simulation
1447
1901
1448 #findRespawnDestination (originX, originY, entityId)
1902 #findRespawnDestination (originX, originY, entityId)
1449 {
1903 {
1904 const record = this.directory.get(entityId);
1905 const dimensionId = normalizeDimensionId(record?.dimensionId ?? OVERWORLD_ID);
1450 const ordered = [...this.altarTiles].sort((left, right) =>
1906 const ordered = [...this.altarTiles].sort((left, right) =>
1451 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1907 Math.max(Math.abs(left.tileX - originX), Math.abs(left.tileY - originY))
1452 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1908 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
@@ -1460,7 +1916,7 @@ export class Simulation
1460 {
1916 {
1461 if (dx === 0 && dy === 0)
1917 if (dx === 0 && dy === 0)
1462 { continue; }
1918 { continue; }
1463 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy });
1919 adjacent.push({ tileX: altar.tileX + dx, tileY: altar.tileY + dy, dimensionId });
1464 }
1920 }
1465 }
1921 }
1466 adjacent.sort((left, right) =>
1922 adjacent.sort((left, right) =>
@@ -1468,8 +1924,8 @@ export class Simulation
1468 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1924 - Math.max(Math.abs(right.tileX - originX), Math.abs(right.tileY - originY))
1469 );
1925 );
1470 const tile = adjacent.find((entry) =>
1926 const tile = adjacent.find((entry) =>
1471 this.isEnterable(entry.tileX, entry.tileY)
1927 this.isEnterable(entry.tileX, entry.tileY, dimensionId)
1472 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId)
1928 && !this.#occupiedByOther(entry.tileX, entry.tileY, entityId, dimensionId)
1473 );
1929 );
1474 if (tile)
1930 if (tile)
1475 { return tile; }
1931 { return tile; }
@@ -1484,20 +1940,22 @@ export class Simulation
1484 { continue; }
1940 { continue; }
1485 const tileX = originX + dx;
1941 const tileX = originX + dx;
1486 const tileY = originY + dy;
1942 const tileY = originY + dy;
1487 if (this.isEnterable(tileX, tileY)
1943 if (this.isEnterable(tileX, tileY, dimensionId)
1488 && !this.#occupiedByOther(tileX, tileY, entityId))
1944 && !this.#occupiedByOther(tileX, tileY, entityId, dimensionId))
1489 { return { tileX, tileY }; }
1945 { return { tileX, tileY, dimensionId }; }
1490 }
1946 }
1491 }
1947 }
1492 }
1948 }
1493 return this.findOpenSpawn();
1949 return this.findOpenSpawn();
1494 }
1950 }
1495
1951
1496 #occupiedByOther (tileX, tileY, entityId)
1952 #occupiedByOther (tileX, tileY, entityId, dimensionId = OVERWORLD_ID)
1497 {
1953 {
1954 const dim = normalizeDimensionId(dimensionId);
1498 for (const record of this.directory.values())
1955 for (const record of this.directory.values())
1499 {
1956 {
1500 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY)
1957 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
1958 if (record.entityId !== entityId && record.tileX === tileX && record.tileY === tileY && recordDim === dim)
1501 { return true; }
1959 { return true; }
1502 }
1960 }
1503 return false;
1961 return false;
@@ -1512,8 +1970,8 @@ export class Simulation
1512 {
1970 {
1513 if (count <= 0)
1971 if (count <= 0)
1514 { continue; }
1972 { continue; }
1515 const { regionX, regionY } = parseRegionKey(key);
1973 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1516 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY));
1974 this.#ensureRegion(regionX, regionY, this.#preferredWorkerForRegion(loaders, regionX, regionY, dimensionId), dimensionId);
1517 this.regionGraceUntil.delete(key);
1975 this.regionGraceUntil.delete(key);
1518 }
1976 }
1519
1977
@@ -1525,8 +1983,8 @@ export class Simulation
1525 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1983 { this.regionGraceUntil.set(key, now + (this.settings.regionUnloadGracePeriodMs ?? 0)); }
1526 if (now >= this.regionGraceUntil.get(key))
1984 if (now >= this.regionGraceUntil.get(key))
1527 {
1985 {
1528 const { regionX, regionY } = parseRegionKey(key);
1986 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1529 this.#unloadRegion(regionX, regionY);
1987 this.#unloadRegion(regionX, regionY, dimensionId);
1530 }
1988 }
1531 }
1989 }
1532
1990
@@ -1537,8 +1995,8 @@ export class Simulation
1537 {
1995 {
1538 if (count <= 0)
1996 if (count <= 0)
1539 { continue; }
1997 { continue; }
1540 const { chunkX, chunkY } = parseChunkKey(key);
1998 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1541 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY)) === workerId)
1999 if (this.regionOwner.get(this.#regionKeyForChunk(chunkX, chunkY, dimensionId)) === workerId)
1542 { chunkKeys.push(key); }
2000 { chunkKeys.push(key); }
1543 }
2001 }
1544 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
2002 worker.call({ type: WorkerMessage.setSimulatingChunks, chunkKeys });
@@ -1565,29 +2023,32 @@ export class Simulation
1565 { this.#stepSpawners(); }
2023 { this.#stepSpawners(); }
1566 }
2024 }
1567
2025
1568 #ensureCoverage (tileX, tileY, loader)
2026 #ensureCoverage (tileX, tileY, loader, dimensionId = OVERWORLD_ID)
1569 {
2027 {
1570 const coverage = loaderCoverage(tileX, tileY, loader);
2028 const dim = normalizeDimensionId(dimensionId);
1571 let preferred = this.#ownerOfTile(tileX, tileY);
2029 const coverage = loaderCoverage(tileX, tileY, loader, dim);
2030 let preferred = this.#ownerOfTile(tileX, tileY, dim);
1572 for (const region of coverage.residentRegions)
2031 for (const region of coverage.residentRegions)
1573 {
2032 {
1574 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred);
2033 const owner = this.#ensureRegion(region.regionX, region.regionY, preferred, dim);
1575 if (preferred == null)
2034 if (preferred == null)
1576 { preferred = owner; }
2035 { preferred = owner; }
1577 }
2036 }
1578 }
2037 }
1579
2038
1580 #ensureRegion (regionX, regionY, preferredWorkerId)
2039 #ensureRegion (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
1581 {
2040 {
1582 const key = regionKey(regionX, regionY);
2041 const dim = normalizeDimensionId(dimensionId);
2042 const key = regionKey(regionX, regionY, dim);
1583 if (this.regionOwner.has(key))
2043 if (this.regionOwner.has(key))
1584 { return this.regionOwner.get(key); }
2044 { return this.regionOwner.get(key); }
1585 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId);
2045 const workerId = this.#pickWorker(regionX, regionY, preferredWorkerId, dim);
1586 this.workers[workerId].call({
2046 this.workers[workerId].call({
1587 type: WorkerMessage.assignRegion,
2047 type: WorkerMessage.assignRegion,
1588 regionX,
2048 regionX,
1589 regionY,
2049 regionY,
1590 chunks: this.#regionChunkBlobs(regionX, regionY)
2050 dimensionId: dim,
2051 chunks: this.#regionChunkBlobs(regionX, regionY, dim)
1591 });
2052 });
1592 this.regionOwner.set(key, workerId);
2053 this.regionOwner.set(key, workerId);
1593 this.#restorePersistent(regionX, regionY, workerId);
2054 this.#restorePersistent(regionX, regionY, workerId);
@@ -1595,9 +2056,10 @@ export class Simulation
1595 return workerId;
2056 return workerId;
1596 }
2057 }
1597
2058
1598 #unloadRegion (regionX, regionY)
2059 #unloadRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
1599 {
2060 {
1600 const key = regionKey(regionX, regionY);
2061 const dim = normalizeDimensionId(dimensionId);
2062 const key = regionKey(regionX, regionY, dim);
1601 const workerId = this.regionOwner.get(key);
2063 const workerId = this.regionOwner.get(key);
1602 if (workerId == null)
2064 if (workerId == null)
1603 { return; }
2065 { return; }
@@ -1605,7 +2067,8 @@ export class Simulation
1605 const { dropped, groundItems } = this.workers[workerId].call({
2067 const { dropped, groundItems } = this.workers[workerId].call({
1606 type: WorkerMessage.dropRegion,
2068 type: WorkerMessage.dropRegion,
1607 regionX,
2069 regionX,
1608 regionY
2070 regionY,
2071 dimensionId: dim
1609 });
2072 });
1610 const persistent = [];
2073 const persistent = [];
1611 for (const record of dropped ?? [])
2074 for (const record of dropped ?? [])
@@ -1616,7 +2079,8 @@ export class Simulation
1616 record.characterId,
2079 record.characterId,
1617 record.tileX,
2080 record.tileX,
1618 record.tileY,
2081 record.tileY,
1619 record.gait ?? GAIT.walk
2082 record.gait ?? GAIT.walk,
2083 record.dimensionId ?? OVERWORLD_ID
1620 );
2084 );
1621 }
2085 }
1622 if (record.persistent)
2086 if (record.persistent)
@@ -1654,7 +2118,12 @@ export class Simulation
1654 const events = [];
2118 const events = [];
1655 for (const request of requests)
2119 for (const request of requests)
1656 {
2120 {
1657 const destWorkerId = this.#ensureRegion(request.toRegionX, request.toRegionY, request.fromWorkerId);
2121 const destWorkerId = this.#ensureRegion(
2122 request.toRegionX,
2123 request.toRegionY,
2124 request.fromWorkerId,
2125 request.dimensionId ?? OVERWORLD_ID
2126 );
1658 if (destWorkerId === request.fromWorkerId)
2127 if (destWorkerId === request.fromWorkerId)
1659 {
2128 {
1660 this.workers[request.fromWorkerId].call({
2129 this.workers[request.fromWorkerId].call({
@@ -1670,7 +2139,8 @@ export class Simulation
1670 type: WorkerMessage.applyTransfer,
2139 type: WorkerMessage.applyTransfer,
1671 payload: request.payload,
2140 payload: request.payload,
1672 destTileX: request.destTileX,
2141 destTileX: request.destTileX,
1673 destTileY: request.destTileY
2142 destTileY: request.destTileY,
2143 dimensionId: request.dimensionId ?? OVERWORLD_ID
1674 });
2144 });
1675 }
2145 }
1676 catch
2146 catch
@@ -1695,8 +2165,10 @@ export class Simulation
1695 entityId: request.entityId,
2165 entityId: request.entityId,
1696 fromTileX: request.fromTileX,
2166 fromTileX: request.fromTileX,
1697 fromTileY: request.fromTileY,
2167 fromTileY: request.fromTileY,
2168 fromDimensionId: request.fromDimensionId ?? request.payload?.components?.position?.dimensionId,
1698 tileX: result.entity.tileX,
2169 tileX: result.entity.tileX,
1699 tileY: result.entity.tileY,
2170 tileY: result.entity.tileY,
2171 dimensionId: result.entity.dimensionId ?? request.dimensionId ?? OVERWORLD_ID,
1700 gait: result.entity.gait
2172 gait: result.entity.gait
1701 });
2173 });
1702 }
2174 }
@@ -1712,20 +2184,21 @@ export class Simulation
1712 {
2184 {
1713 if (owner !== workerId)
2185 if (owner !== workerId)
1714 { continue; }
2186 { continue; }
1715 const { regionX, regionY } = parseRegionKey(key);
2187 const { regionX, regionY, dimensionId } = parseRegionKey(key);
1716 for (const chunk of chunksInRegion(regionX, regionY))
2188 for (const chunk of chunksInRegion(regionX, regionY))
1717 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY)); }
2189 { ownedKeys.add(chunkKey(chunk.chunkX, chunk.chunkY, dimensionId)); }
1718 }
2190 }
1719 const replicas = [];
2191 const replicas = [];
1720 for (const key of replicaNeededForOwnedChunks(ownedKeys))
2192 for (const key of replicaNeededForOwnedChunks(ownedKeys))
1721 {
2193 {
1722 if (ownedKeys.has(key))
2194 if (ownedKeys.has(key))
1723 { continue; }
2195 { continue; }
1724 const { chunkX, chunkY } = parseChunkKey(key);
2196 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1725 replicas.push({
2197 replicas.push({
1726 chunkX,
2198 chunkX,
1727 chunkY,
2199 chunkY,
1728 data: this.#authoredChunk(chunkX, chunkY)
2200 dimensionId,
2201 data: this.#authoredChunk(chunkX, chunkY, dimensionId)
1729 });
2202 });
1730 }
2203 }
1731 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
2204 worker.call({ type: WorkerMessage.setReplicas, chunks: replicas });
@@ -1741,23 +2214,27 @@ export class Simulation
1741 {
2214 {
1742 const ghosts = entities.filter((entity) =>
2215 const ghosts = entities.filter((entity) =>
1743 {
2216 {
1744 if (this.#ownerOfTile(entity.tileX, entity.tileY) === workerId)
2217 const dim = normalizeDimensionId(entity.dimensionId ?? OVERWORLD_ID);
2218 if (this.#ownerOfTile(entity.tileX, entity.tileY, dim) === workerId)
1745 { return false; }
2219 { return false; }
1746 return this.#nearWorker(workerId, entity.tileX, entity.tileY);
2220 return this.#nearWorker(workerId, entity.tileX, entity.tileY, dim);
1747 });
2221 });
1748 worker.call({ type: WorkerMessage.setGhosts, ghosts });
2222 worker.call({ type: WorkerMessage.setGhosts, ghosts });
1749 }
2223 }
1750 }
2224 }
1751
2225
1752 #nearWorker (workerId, tileX, tileY)
2226 #nearWorker (workerId, tileX, tileY, dimensionId = OVERWORLD_ID)
1753 {
2227 {
2228 const dim = normalizeDimensionId(dimensionId);
1754 const chunkX = tileToChunk(tileX);
2229 const chunkX = tileToChunk(tileX);
1755 const chunkY = tileToChunk(tileY);
2230 const chunkY = tileToChunk(tileY);
1756 for (const [key, owner] of this.regionOwner)
2231 for (const [key, owner] of this.regionOwner)
1757 {
2232 {
1758 if (owner !== workerId)
2233 if (owner !== workerId)
1759 { continue; }
2234 { continue; }
1760 const { regionX, regionY } = parseRegionKey(key);
2235 const { regionX, regionY, dimensionId: regionDim } = parseRegionKey(key);
2236 if (regionDim !== dim)
2237 { continue; }
1761 for (const chunk of chunksInRegion(regionX, regionY))
2238 for (const chunk of chunksInRegion(regionX, regionY))
1762 {
2239 {
1763 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
2240 if (Math.max(Math.abs(chunk.chunkX - chunkX), Math.abs(chunk.chunkY - chunkY)) <= 2)
@@ -1775,12 +2252,16 @@ export class Simulation
1775 return loaders;
2252 return loaders;
1776 }
2253 }
1777
2254
1778 #preferredWorkerForRegion (loaders, regionX, regionY)
2255 #preferredWorkerForRegion (loaders, regionX, regionY, dimensionId = OVERWORLD_ID)
1779 {
2256 {
2257 const dim = normalizeDimensionId(dimensionId);
1780 const votes = new Map();
2258 const votes = new Map();
1781 for (const loader of loaders)
2259 for (const loader of loaders)
1782 {
2260 {
1783 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader);
2261 const loaderDim = normalizeDimensionId(loader.dimensionId ?? OVERWORLD_ID);
2262 if (loaderDim !== dim)
2263 { continue; }
2264 const coverage = loaderCoverage(loader.tileX, loader.tileY, loader.chunkLoader, dim);
1784 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
2265 if (!coverage.residentRegions.some((region) => region.regionX === regionX && region.regionY === regionY))
1785 { continue; }
2266 { continue; }
1786 const record = this.directory.get(loader.entityId);
2267 const record = this.directory.get(loader.entityId);
@@ -1801,9 +2282,10 @@ export class Simulation
1801 return best;
2282 return best;
1802 }
2283 }
1803
2284
1804 #pickWorker (regionX, regionY, preferredWorkerId)
2285 #pickWorker (regionX, regionY, preferredWorkerId, dimensionId = OVERWORLD_ID)
1805 {
2286 {
1806 const pinned = this.pinRegion?.(regionX, regionY);
2287 const dim = normalizeDimensionId(dimensionId);
2288 const pinned = this.pinRegion?.(regionX, regionY, dim);
1807 if (pinned != null)
2289 if (pinned != null)
1808 { return pinned; }
2290 { return pinned; }
1809
2291
@@ -1814,7 +2296,7 @@ export class Simulation
1814 {
2296 {
1815 if (dx === 0 && dy === 0)
2297 if (dx === 0 && dy === 0)
1816 { continue; }
2298 { continue; }
1817 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy));
2299 const owner = this.regionOwner.get(regionKey(regionX + dx, regionY + dy, dim));
1818 if (owner != null)
2300 if (owner != null)
1819 { neighborOwners.push(owner); }
2301 { neighborOwners.push(owner); }
1820 }
2302 }
@@ -1841,46 +2323,53 @@ export class Simulation
1841 return scores[0].workerId;
2323 return scores[0].workerId;
1842 }
2324 }
1843
2325
1844 #ownerOfTile (tileX, tileY)
2326 #ownerOfTile (tileX, tileY, dimensionId = OVERWORLD_ID)
1845 {
2327 {
1846 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY))) ?? null;
2328 return this.regionOwner.get(regionKey(tileToRegion(tileX), tileToRegion(tileY), dimensionId)) ?? null;
1847 }
2329 }
1848
2330
1849 #regionKeyForChunk (chunkX, chunkY)
2331 #regionKeyForChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1850 {
2332 {
1851 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY));
2333 return regionKey(chunkToRegion(chunkX), chunkToRegion(chunkY), dimensionId);
1852 }
2334 }
1853
2335
1854 #regionChunkBlobs (regionX, regionY)
2336 #regionChunkBlobs (regionX, regionY, dimensionId = OVERWORLD_ID)
1855 {
2337 {
2338 const dim = normalizeDimensionId(dimensionId);
1856 return chunksInRegion(regionX, regionY).map((coord) => ({
2339 return chunksInRegion(regionX, regionY).map((coord) => ({
1857 chunkX: coord.chunkX,
2340 chunkX: coord.chunkX,
1858 chunkY: coord.chunkY,
2341 chunkY: coord.chunkY,
1859 data: this.#authoredChunk(coord.chunkX, coord.chunkY)
2342 dimensionId: dim,
2343 data: this.#authoredChunk(coord.chunkX, coord.chunkY, dim)
1860 }));
2344 }));
1861 }
2345 }
1862
2346
1863 #authoredChunk (chunkX, chunkY)
2347 #authoredChunk (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1864 {
2348 {
1865 const key = chunkKey(chunkX, chunkY);
2349 const dim = normalizeDimensionId(dimensionId);
2350 const key = chunkKey(chunkX, chunkY, dim);
1866 if (this.authoredCache.has(key))
2351 if (this.authoredCache.has(key))
1867 { return this.authoredCache.get(key); }
2352 { return this.authoredCache.get(key); }
1868 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId);
2353 const row = this.worldDb.getChunkVersion(chunkX, chunkY, this.activeRevisionId, dim);
2354 const dimRecord = this.getDimensionRecord(dim);
2355 const defaultGroundTypeId = dimRecord?.defaultGroundTypeId ?? this.settings.defaultGroundTypeId;
1869 const data = row
2356 const data = row
1870 ? decodeChunkBlob(row.data_blob, this.settings.defaultGroundTypeId, chunkX, chunkY)
2357 ? decodeChunkBlob(row.data_blob, defaultGroundTypeId, chunkX, chunkY)
1871 : createEmptyChunkData(this.settings.defaultGroundTypeId);
2358 : createEmptyChunkData(defaultGroundTypeId);
1872 this.authoredCache.set(key, data);
2359 this.authoredCache.set(key, data);
1873 return data;
2360 return data;
1874 }
2361 }
1875
2362
1876 #syntheticSnapshot (chunkX, chunkY)
2363 #syntheticSnapshot (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1877 {
2364 {
1878 const data = this.#authoredChunk(chunkX, chunkY);
2365 const dim = normalizeDimensionId(dimensionId);
2366 const data = this.#authoredChunk(chunkX, chunkY, dim);
1879 return {
2367 return {
1880 chunkX,
2368 chunkX,
1881 chunkY,
2369 chunkY,
2370 dimensionId: dim,
1882 open: data.open,
2371 open: data.open,
1883 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y).open),
2372 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#authoredChunk(x, y, dim).open),
1884 grounds: data.grounds,
2373 grounds: data.grounds,
1885 blocks: data.blocks,
2374 blocks: data.blocks,
1886 light: data.light,
2375 light: data.light,
@@ -1889,11 +2378,13 @@ export class Simulation
1889 };
2378 };
1890 }
2379 }
1891
2380
1892 #occupiedTile (tileX, tileY)
2381 #occupiedTile (tileX, tileY, dimensionId = OVERWORLD_ID)
1893 {
2382 {
2383 const dim = normalizeDimensionId(dimensionId);
1894 for (const record of this.directory.values())
2384 for (const record of this.directory.values())
1895 {
2385 {
1896 if (record.tileX === tileX && record.tileY === tileY)
2386 const recordDim = normalizeDimensionId(record.dimensionId ?? OVERWORLD_ID);
2387 if (record.tileX === tileX && record.tileY === tileY && recordDim === dim)
1897 { return record.entityId; }
2388 { return record.entityId; }
1898 }
2389 }
1899 return null;
2390 return null;
@@ -2081,6 +2572,8 @@ export class Simulation
2081 record.tileX = event.tileX;
2572 record.tileX = event.tileX;
2082 record.tileY = event.tileY;
2573 record.tileY = event.tileY;
2083 record.gait = event.gait;
2574 record.gait = event.gait;
2575 if (event.dimensionId != null)
2576 { record.dimensionId = normalizeDimensionId(event.dimensionId); }
2084 if (event.worldX != null)
2577 if (event.worldX != null)
2085 { record.worldX = event.worldX; }
2578 { record.worldX = event.worldX; }
2086 if (event.worldY != null)
2579 if (event.worldY != null)
server/src/simulation/spawners.js +6 −3
@@ -84,7 +84,8 @@ export function collectSpawnRequests (world)
84 84 buysItems: false,
85 85 hiddenDiscount: config.hiddenDiscount,
86 86 centralExchange: true,
87 townGuard: false
87 townGuard: false,
88 dialogueId: config.dialogueId || null
88 89 });
89 90 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
90 91 }
@@ -118,7 +119,8 @@ export function collectSpawnRequests (world)
118 119 buysItems: config.buysItems,
119 120 hiddenDiscount: config.hiddenDiscount,
120 121 centralExchange: false,
121 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId)
122 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId),
123 dialogueId: config.dialogueId || null
122 124 });
123 125 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
124 126 }
@@ -181,7 +183,8 @@ export function mobComponents (request)
181 183 centralExchange: !!request.centralExchange,
182 184 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
183 185 stationTileX: null,
184 stationTileY: null
186 stationTileY: null,
187 dialogueId: request.dialogueId ? String(request.dialogueId) : null
185 188 };
186 189 }
187 190 if (def.persistent)
@@ -84,7 +84,8 @@ export function collectSpawnRequests (world)
84 buysItems: false,
84 buysItems: false,
85 hiddenDiscount: config.hiddenDiscount,
85 hiddenDiscount: config.hiddenDiscount,
86 centralExchange: true,
86 centralExchange: true,
87 townGuard: false
87 townGuard: false,
88 dialogueId: config.dialogueId || null
88 });
89 });
89 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
90 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
90 }
91 }
@@ -118,7 +119,8 @@ export function collectSpawnRequests (world)
118 buysItems: config.buysItems,
119 buysItems: config.buysItems,
119 hiddenDiscount: config.hiddenDiscount,
120 hiddenDiscount: config.hiddenDiscount,
120 centralExchange: false,
121 centralExchange: false,
121 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId)
122 townGuard: !!config.townGuard || isTownGuardMob(config.mobTypeId),
123 dialogueId: config.dialogueId || null
122 });
124 });
123 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
125 counts.set(config.spawnerId, (counts.get(config.spawnerId) ?? 0) + 1);
124 }
126 }
@@ -181,7 +183,8 @@ export function mobComponents (request)
181 centralExchange: !!request.centralExchange,
183 centralExchange: !!request.centralExchange,
182 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
184 townGuard: !!request.townGuard || isTownGuardMob(def.mobTypeId),
183 stationTileX: null,
185 stationTileX: null,
184 stationTileY: null
186 stationTileY: null,
187 dialogueId: request.dialogueId ? String(request.dialogueId) : null
185 };
188 };
186 }
189 }
187 if (def.persistent)
190 if (def.persistent)
server/src/simulation/workerWorld.js +318 −66
@@ -1,4 +1,5 @@
1 1 import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2 3 import {
3 4 chunkKey,
4 5 chunkToRegion,
@@ -55,7 +56,8 @@ import {
55 56 queueStandInRangeApproach,
56 57 resolveCombatTarget,
57 58 stepAggression,
58 stepCombat
59 stepCombat,
60 chebyshev
59 61 } from "../combat/service.js";
60 62 import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
61 63 import { SkillId } from "../../../shared/definitions/skills.js";
@@ -146,7 +148,7 @@ export class WorkerWorld
146 148 case WorkerMessage.updateFlight:
147 149 return this.#updateFlight(message.entityId, message.flight, message.now);
148 150 case WorkerMessage.chunkIsSimulating:
149 return this.chunkIsSimulating(message.tileX, message.tileY);
151 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
150 152 case WorkerMessage.applyTransfer:
151 153 return this.#applyTransfer(message);
152 154 case WorkerMessage.commitTransfer:
@@ -154,13 +156,13 @@ export class WorkerWorld
154 156 case WorkerMessage.abortTransfer:
155 157 return this.#abortTransfer(message.entityId);
156 158 case WorkerMessage.snapshotChunk:
157 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly);
159 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
158 160 case WorkerMessage.listLoaders:
159 161 return this.#listLoaders();
160 162 case WorkerMessage.listPublicEntities:
161 163 return this.#listPublicEntities();
162 164 case WorkerMessage.entitiesInRegion:
163 return this.#entitiesInRegion(message.regionX, message.regionY);
165 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
164 166 case WorkerMessage.inspect:
165 167 return publicEntityView(this.ecs, message.entityId);
166 168 case WorkerMessage.remoteCombatEngage:
@@ -175,6 +177,8 @@ export class WorkerWorld
175 177 return this.#spawnCorpseDrops(message);
176 178 case WorkerMessage.applyRespawn:
177 179 return this.#applyRespawn(message);
180 case WorkerMessage.relocateEntity:
181 return this.#relocateEntity(message);
178 182 case WorkerMessage.clearCombat:
179 183 clearEngage(this.ecs, message.entityId);
180 184 for (const entity of this.ecs.query(Component.combat))
@@ -194,14 +198,18 @@ export class WorkerWorld
194 198 return this.#stationExchangeClerk(message);
195 199 case WorkerMessage.releaseExchangeClerk:
196 200 return this.#releaseExchangeClerk(message);
201 case WorkerMessage.pinDialogue:
202 return this.#pinDialogue(message.entityId, message.characterId);
203 case WorkerMessage.unpinDialogue:
204 return this.#unpinDialogue(message.entityId, message.characterId);
197 205 default:
198 206 throw new Error(`Unknown worker message ${message.type}`);
199 207 }
200 208 }
201 209
202 ownsRegion (regionX, regionY)
210 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
203 211 {
204 return this.ownedRegions.has(regionKey(regionX, regionY));
212 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
205 213 }
206 214
207 215 requireOwnedEntity (sessionId, characterId)
@@ -209,9 +217,9 @@ export class WorkerWorld
209 217 return this.#requireOwnedEntity(sessionId, characterId);
210 218 }
211 219
212 chunkData (chunkX, chunkY)
220 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
213 221 {
214 return this.#chunkData(chunkX, chunkY);
222 return this.#chunkData(chunkX, chunkY, dimensionId);
215 223 }
216 224
217 225 #configure (message)
@@ -225,16 +233,19 @@ export class WorkerWorld
225 233
226 234 #assignRegion (message)
227 235 {
228 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
236 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
237 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
229 238 for (const chunk of message.chunks ?? [])
230 239 {
240 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
231 241 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
232 242 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
233 243 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
234 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
244 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
235 245 data: cloneChunkData(chunk.data),
236 246 simulating: false,
237 replica: false
247 replica: false,
248 dimensionId: chunkDim
238 249 });
239 250 }
240 251 return { ok: true };
@@ -242,9 +253,11 @@ export class WorkerWorld
242 253
243 254 #replaceRegionChunks (message)
244 255 {
256 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
245 257 for (const chunk of message.chunks ?? [])
246 258 {
247 const key = chunkKey(chunk.chunkX, chunk.chunkY);
259 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
260 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
248 261 const existing = this.chunks.get(key);
249 262 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
250 263 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
@@ -252,7 +265,8 @@ export class WorkerWorld
252 265 this.chunks.set(key, {
253 266 data: cloneChunkData(chunk.data),
254 267 simulating: existing?.simulating ?? false,
255 replica: existing?.replica ?? false
268 replica: existing?.replica ?? false,
269 dimensionId: chunkDim
256 270 });
257 271 }
258 272 return { ok: true };
@@ -260,8 +274,9 @@ export class WorkerWorld
260 274
261 275 #dropRegion (message)
262 276 {
277 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
263 278 const dropped = [];
264 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
279 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
265 280 {
266 281 const components = record.payload?.components;
267 282 if (components?.creature && !components?.character && components?.health)
@@ -274,9 +289,11 @@ export class WorkerWorld
274 289 { removeGroundItem(this, item.groundItemId); }
275 290 for (const [key, chunk] of [...this.chunks.entries()])
276 291 {
277 const { chunkX, chunkY } = parseChunkKey(key);
292 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
278 293 if (chunk.replica)
279 294 { continue; }
295 if (dimensionId !== dim)
296 { continue; }
280 297 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
281 298 {
282 299 clearOreRespawnsForChunk(this, chunkX, chunkY);
@@ -285,7 +302,7 @@ export class WorkerWorld
285 302 this.chunks.delete(key);
286 303 }
287 304 }
288 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
305 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
289 306 return { dropped, groundItems };
290 307 }
291 308
@@ -294,7 +311,8 @@ export class WorkerWorld
294 311 const keep = new Set();
295 312 for (const chunk of message.chunks ?? [])
296 313 {
297 const key = chunkKey(chunk.chunkX, chunk.chunkY);
314 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
315 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
298 316 keep.add(key);
299 317 const existing = this.chunks.get(key);
300 318 if (existing && !existing.replica)
@@ -302,7 +320,8 @@ export class WorkerWorld
302 320 this.chunks.set(key, {
303 321 data: cloneChunkData(chunk.data),
304 322 simulating: false,
305 replica: true
323 replica: true,
324 dimensionId: chunkDim
306 325 });
307 326 }
308 327 for (const [key, chunk] of [...this.chunks.entries()])
@@ -335,7 +354,8 @@ export class WorkerWorld
335 354 for (const ghost of message.ghosts ?? [])
336 355 {
337 356 this.ghosts.set(ghost.entityId, ghost);
338 const key = tileKey(ghost.tileX, ghost.tileY);
357 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
358 const key = tileKey(ghost.tileX, ghost.tileY, dim);
339 359 let set = this.ghostOccupancy.get(key);
340 360 if (!set)
341 361 {
@@ -425,7 +445,7 @@ export class WorkerWorld
425 445 case "cancel-attack":
426 446 return this.#cancelAttack(sessionId, command.characterId);
427 447 case "interact":
428 return this.#interact(sessionId, command.characterId, command.targetEntityId);
448 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
429 449 case "follow":
430 450 return this.#follow(sessionId, command.characterId, command.targetEntityId);
431 451 case "cancel-follow":
@@ -518,7 +538,8 @@ export class WorkerWorld
518 538
519 539 const destRegionX = tileToRegion(message.tileX);
520 540 const destRegionY = tileToRegion(message.tileY);
521 if (!this.ownsRegion(destRegionX, destRegionY))
541 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
542 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
522 543 {
523 544 this.frozen.add(message.entityId);
524 545 return {
@@ -531,11 +552,12 @@ export class WorkerWorld
531 552 destTileY: message.tileY,
532 553 toRegionX: destRegionX,
533 554 toRegionY: destRegionY,
555 dimensionId,
534 556 payload: serializeEntity(this.ecs, message.entityId)
535 557 }
536 558 };
537 559 }
538 if (!this.isEnterable(message.tileX, message.tileY))
560 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
539 561 { return { accepted: false }; }
540 562 this.#vacate(message.entityId, fromTileX, fromTileY);
541 563 position.tileX = message.tileX;
@@ -550,6 +572,82 @@ export class WorkerWorld
550 572 fromTileY,
551 573 tileX: position.tileX,
552 574 tileY: position.tileY,
575 dimensionId,
576 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
577 }
578 };
579 }
580
581 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
582 #relocateEntity (message)
583 {
584 const handle = this.ecs.handleOf(message.entityId);
585 if (handle == null)
586 { return { accepted: false }; }
587 const position = this.ecs.get(handle, Component.position);
588 if (!position)
589 { return { accepted: false }; }
590 const fromTileX = position.tileX;
591 const fromTileY = position.tileY;
592 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
593 const destTileX = message.tileX | 0;
594 const destTileY = message.tileY | 0;
595 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
596
597 clearEngage(this.ecs, message.entityId);
598 const path = this.ecs.get(handle, Component.path);
599 if (path)
600 { path.tiles = []; }
601 clearFollow(this.ecs, message.entityId);
602
603 const destRegionX = tileToRegion(destTileX);
604 const destRegionY = tileToRegion(destTileY);
605 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
606 {
607 this.frozen.add(message.entityId);
608 const payload = serializeEntity(this.ecs, message.entityId);
609 if (payload.components?.position)
610 {
611 payload.components.position.tileX = destTileX;
612 payload.components.position.tileY = destTileY;
613 payload.components.position.dimensionId = dimensionId;
614 }
615 return {
616 accepted: true,
617 transferRequest: {
618 entityId: message.entityId,
619 fromTileX,
620 fromTileY,
621 fromDimensionId,
622 destTileX,
623 destTileY,
624 toRegionX: destRegionX,
625 toRegionY: destRegionY,
626 dimensionId,
627 payload
628 }
629 };
630 }
631 if (!this.isEnterable(destTileX, destTileY, dimensionId))
632 { return { accepted: false }; }
633 if (!this.#isFlying(handle))
634 { this.#vacate(message.entityId, fromTileX, fromTileY); }
635 position.tileX = destTileX;
636 position.tileY = destTileY;
637 position.dimensionId = dimensionId;
638 if (!this.#isFlying(handle))
639 { this.#occupy(message.entityId, destTileX, destTileY); }
640 return {
641 accepted: true,
642 event: {
643 type: "entity-move",
644 entityId: message.entityId,
645 fromTileX,
646 fromTileY,
647 fromDimensionId,
648 tileX: destTileX,
649 tileY: destTileY,
650 dimensionId,
553 651 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
554 652 }
555 653 };
@@ -646,7 +744,8 @@ export class WorkerWorld
646 744 position.tileY = tileY;
647 745 const destRegionX = tileToRegion(tileX);
648 746 const destRegionY = tileToRegion(tileY);
649 if (!this.ownsRegion(destRegionX, destRegionY))
747 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
748 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
650 749 {
651 750 this.frozen.add(entityId);
652 751 return {
@@ -658,7 +757,8 @@ export class WorkerWorld
658 757 destTileX: tileX,
659 758 destTileY: tileY,
660 759 toRegionX: destRegionX,
661 toRegionY: destRegionY
760 toRegionY: destRegionY,
761 dimensionId
662 762 }
663 763 };
664 764 }
@@ -859,7 +959,7 @@ export class WorkerWorld
859 959 return { events: [] };
860 960 }
861 961
862 #interact (sessionId, characterId, targetEntityId)
962 #interact (sessionId, characterId, targetEntityId, purpose = null)
863 963 {
864 964 this.#requireOwnedEntity(sessionId, characterId);
865 965 const targetHandle = this.ecs.handleOf(targetEntityId);
@@ -878,7 +978,45 @@ export class WorkerWorld
878 978 const creature = this.ecs.get(targetHandle, Component.creature);
879 979 const def = creature ? mobDefinition(creature.mobTypeId) : null;
880 980 const shop = this.ecs.get(targetHandle, Component.shop);
881 if (shopHasInterface(shop))
981 const hasShop = shopHasInterface(shop);
982 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
983 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
984 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
985
986 if (intent === "shop" && hasShop)
987 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
988 if (intent === "talk" && dialogueId)
989 {
990 // Pin in-worker before return so wander cannot start before the sim thread pins.
991 this.#pinDialogue(targetEntityId, characterId);
992 return {
993 events: [{
994 type: "open-dialogue",
995 sessionId,
996 characterId,
997 entityId: targetEntityId,
998 dialogueId
999 }]
1000 };
1001 }
1002 if (intent === "talk" && hasShop)
1003 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1004
1005 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1006 if (dialogueId)
1007 {
1008 this.#pinDialogue(targetEntityId, characterId);
1009 return {
1010 events: [{
1011 type: "open-dialogue",
1012 sessionId,
1013 characterId,
1014 entityId: targetEntityId,
1015 dialogueId
1016 }]
1017 };
1018 }
1019 if (hasShop)
882 1020 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
883 1021 if (!def?.talkable)
884 1022 {
@@ -886,7 +1024,6 @@ export class WorkerWorld
886 1024 error.userFacing = true;
887 1025 throw error;
888 1026 }
889 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
890 1027 return { events: [] };
891 1028 }
892 1029
@@ -1085,6 +1222,7 @@ export class WorkerWorld
1085 1222 destTileY: event.destTileY,
1086 1223 toRegionX: event.toRegionX,
1087 1224 toRegionY: event.toRegionY,
1225 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1088 1226 payload
1089 1227 });
1090 1228 continue;
@@ -1126,6 +1264,7 @@ export class WorkerWorld
1126 1264 const events = expireGroundItems(this, now);
1127 1265 const transferRequests = [];
1128 1266 events.push(...pruneShopBrowsers(this));
1267 events.push(...this.#pruneDialogueBrowsers());
1129 1268 this.#queueAmbientWander();
1130 1269 this.#queueSpawnerWander();
1131 1270 this.#queueExchangeStations();
@@ -1144,7 +1283,7 @@ export class WorkerWorld
1144 1283 { path.stuckSince = null; }
1145 1284 continue;
1146 1285 }
1147 if (!this.chunkIsSimulating(position.tileX, position.tileY))
1286 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1148 1287 { continue; }
1149 1288
1150 1289 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
@@ -1165,7 +1304,8 @@ export class WorkerWorld
1165 1304 { continue; }
1166 1305 const destRegionX = tileToRegion(next.x);
1167 1306 const destRegionY = tileToRegion(next.y);
1168 if (!this.ownsRegion(destRegionX, destRegionY))
1307 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1308 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1169 1309 {
1170 1310 this.frozen.add(entityId);
1171 1311 transferRequests.push({
@@ -1176,6 +1316,7 @@ export class WorkerWorld
1176 1316 destTileY: next.y,
1177 1317 toRegionX: destRegionX,
1178 1318 toRegionY: destRegionY,
1319 dimensionId,
1179 1320 payload: serializeEntity(this.ecs, entityId)
1180 1321 });
1181 1322 continue;
@@ -1288,7 +1429,7 @@ export class WorkerWorld
1288 1429 { continue; }
1289 1430 if (path.tiles?.length)
1290 1431 { continue; }
1291 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1432 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1292 1433 { continue; }
1293 1434 if (Math.random() > 0.35)
1294 1435 { continue; }
@@ -1320,6 +1461,8 @@ export class WorkerWorld
1320 1461 if (shopHasActiveBrowsers(shop))
1321 1462 { continue; }
1322 1463 const origin = entity.spawnOrigin;
1464 if (hasDialogueBrowsers(origin))
1465 { continue; }
1323 1466 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1324 1467 { continue; }
1325 1468 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
@@ -1328,9 +1471,10 @@ export class WorkerWorld
1328 1471 const path = this.ecs.get(entity.handle, Component.path);
1329 1472 if (!path || path.tiles?.length)
1330 1473 { continue; }
1331 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1474 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1332 1475 { continue; }
1333 if (Math.random() > 0.4)
1476 // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk).
1477 if (Math.random() > 0.1)
1334 1478 { continue; }
1335 1479
1336 1480 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
@@ -1452,6 +1596,81 @@ export class WorkerWorld
1452 1596 return { ok: true, released };
1453 1597 }
1454 1598
1599 #pinDialogue (entityId, characterId)
1600 {
1601 const handle = this.ecs.handleOf(entityId | 0);
1602 if (handle == null)
1603 { return { ok: false }; }
1604 const origin = this.ecs.get(handle, Component.spawnOrigin);
1605 if (!origin)
1606 { return { ok: false }; }
1607 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
1608 { origin.dialogueBrowsers = Object.create(null); }
1609 origin.dialogueBrowsers[characterId | 0] = true;
1610 const path = this.ecs.get(handle, Component.path);
1611 if (path)
1612 { path.tiles = []; }
1613 return { ok: true };
1614 }
1615
1616 #unpinDialogue (entityId, characterId)
1617 {
1618 const handle = this.ecs.handleOf(entityId | 0);
1619 if (handle == null)
1620 { return { ok: false }; }
1621 const origin = this.ecs.get(handle, Component.spawnOrigin);
1622 if (!origin?.dialogueBrowsers)
1623 { return { ok: true }; }
1624 delete origin.dialogueBrowsers[characterId | 0];
1625 return { ok: true };
1626 }
1627
1628 #pruneDialogueBrowsers ()
1629 {
1630 const events = [];
1631 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1632 {
1633 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1634 if (!browsers || typeof browsers !== "object")
1635 { continue; }
1636 const ids = Object.keys(browsers).map((id) => Number(id));
1637 if (!ids.length)
1638 { continue; }
1639 const path = this.ecs.get(entity.handle, Component.path);
1640 if (path)
1641 { path.tiles = []; }
1642 for (const characterId of ids)
1643 {
1644 const playerEntityId = this.characterEntities.get(characterId);
1645 if (playerEntityId == null)
1646 {
1647 delete browsers[characterId];
1648 continue;
1649 }
1650 const playerHandle = this.ecs.handleOf(playerEntityId);
1651 const playerPos = this.ecs.get(playerHandle, Component.position);
1652 const stillNear = playerPos
1653 && chebyshev(
1654 playerPos.tileX,
1655 playerPos.tileY,
1656 entity.position.tileX,
1657 entity.position.tileY
1658 ) <= 1;
1659 if (stillNear)
1660 { continue; }
1661 delete browsers[characterId];
1662 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
1663 events.push({
1664 type: "dialogue-walk-away",
1665 sessionId: identity?.sessionId ?? null,
1666 characterId,
1667 npcEntityId: entity.entityId
1668 });
1669 }
1670 }
1671 return events;
1672 }
1673
1455 1674 /** Keep stationed CE clerks at their counter tile. */
1456 1675 #queueExchangeStations ()
1457 1676 {
@@ -1497,20 +1716,23 @@ export class WorkerWorld
1497 1716 const position = payload.components?.position;
1498 1717 const destTileX = message.destTileX ?? position?.tileX;
1499 1718 const destTileY = message.destTileY ?? position?.tileY;
1719 const dimensionId = normalizeDimensionId(
1720 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
1721 );
1500 1722 if (destTileX == null || destTileY == null)
1501 1723 { return { accepted: false, reason: "missing-destination" }; }
1502 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
1724 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
1503 1725 { return { accepted: false, reason: "not-owner" }; }
1504 1726
1505 1727 const creature = payload.components?.creature;
1506 1728 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1507 1729 if (flying)
1508 1730 {
1509 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
1731 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
1510 1732 if (!data?.open)
1511 1733 { return { accepted: false, reason: "blocked" }; }
1512 1734 }
1513 else if (!this.isEnterable(destTileX, destTileY))
1735 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
1514 1736 { return { accepted: false, reason: "blocked" }; }
1515 1737
1516 1738 deserializeEntity(this.ecs, payload);
@@ -1519,6 +1741,7 @@ export class WorkerWorld
1519 1741 const path = this.ecs.get(handle, Component.path);
1520 1742 livePosition.tileX = destTileX;
1521 1743 livePosition.tileY = destTileY;
1744 livePosition.dimensionId = dimensionId;
1522 1745 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1523 1746 { path.tiles.shift(); }
1524 1747 if (!flying)
@@ -1552,6 +1775,7 @@ export class WorkerWorld
1552 1775 entityId: entity.entityId,
1553 1776 tileX: entity.position.tileX,
1554 1777 tileY: entity.position.tileY,
1778 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
1555 1779 chunkLoader: { ...entity.chunkLoader }
1556 1780 }));
1557 1781 }
@@ -1561,11 +1785,15 @@ export class WorkerWorld
1561 1785 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1562 1786 }
1563 1787
1564 #entitiesInRegion (regionX, regionY)
1788 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
1565 1789 {
1790 const dim = normalizeDimensionId(dimensionId);
1566 1791 const records = [];
1567 1792 for (const entity of this.ecs.query(Component.position))
1568 1793 {
1794 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1795 if (entityDim !== dim)
1796 { continue; }
1569 1797 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1570 1798 { continue; }
1571 1799 records.push({
@@ -1577,16 +1805,18 @@ export class WorkerWorld
1577 1805 return records;
1578 1806 }
1579 1807
1580 #chunkSnapshot (chunkX, chunkY, staticOnly = false)
1808 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
1581 1809 {
1582 const data = this.#chunkData(chunkX, chunkY);
1810 const dim = normalizeDimensionId(dimensionId);
1811 const data = this.#chunkData(chunkX, chunkY, dim);
1583 1812 if (staticOnly)
1584 1813 {
1585 1814 return {
1586 1815 chunkX,
1587 1816 chunkY,
1817 dimensionId: dim,
1588 1818 open: data.open,
1589 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1819 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1590 1820 grounds: data.grounds,
1591 1821 blocks: data.blocks,
1592 1822 light: data.light,
@@ -1597,6 +1827,9 @@ export class WorkerWorld
1597 1827 const entities = [];
1598 1828 for (const entity of this.ecs.query(Component.position, Component.appearance))
1599 1829 {
1830 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1831 if (entityDim !== dim)
1832 { continue; }
1600 1833 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1601 1834 { continue; }
1602 1835 entities.push(publicEntityView(this.ecs, entity.entityId));
@@ -1604,8 +1837,9 @@ export class WorkerWorld
1604 1837 return {
1605 1838 chunkX,
1606 1839 chunkY,
1840 dimensionId: dim,
1607 1841 open: data.open,
1608 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1842 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1609 1843 grounds: data.grounds,
1610 1844 blocks: data.blocks,
1611 1845 light: data.light,
@@ -1631,22 +1865,23 @@ export class WorkerWorld
1631 1865 };
1632 1866 }
1633 1867
1634 chunkIsSimulating (tileX, tileY)
1868 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1635 1869 {
1636 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1870 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
1637 1871 return !!chunk && !chunk.replica && chunk.simulating;
1638 1872 }
1639 1873
1640 1874 walkableFor (entityId, tileX, tileY)
1641 1875 {
1876 const dim = this.#entityDimensionId(entityId);
1642 1877 const handle = this.ecs.handleOf(entityId);
1643 1878 if (this.#isFlying(handle))
1644 1879 {
1645 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1880 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
1646 1881 return !!data?.open;
1647 1882 }
1648 1883 // Entities pass through each other; only terrain / closed chunks block movement.
1649 return this.isEnterable(tileX, tileY);
1884 return this.isEnterable(tileX, tileY, dim);
1650 1885 }
1651 1886
1652 1887 /**
@@ -1655,9 +1890,10 @@ export class WorkerWorld
1655 1890 */
1656 1891 isClearStanding (entityId, tileX, tileY)
1657 1892 {
1658 if (!this.isEnterable(tileX, tileY))
1893 const dim = this.#entityDimensionId(entityId);
1894 if (!this.isEnterable(tileX, tileY, dim))
1659 1895 { return false; }
1660 return !this.#hasOtherOccupant(entityId, tileX, tileY);
1896 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
1661 1897 }
1662 1898
1663 1899 destroyEntity (entityId)
@@ -1665,35 +1901,35 @@ export class WorkerWorld
1665 1901 return this.#destroyEntity(entityId);
1666 1902 }
1667 1903
1668 occupied (tileX, tileY)
1904 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
1669 1905 {
1670 return this.#anyOccupant(tileX, tileY);
1906 return this.#anyOccupant(tileX, tileY, dimensionId);
1671 1907 }
1672 1908
1673 #chunkIsSimulating (tileX, tileY)
1909 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1674 1910 {
1675 return this.chunkIsSimulating(tileX, tileY);
1911 return this.chunkIsSimulating(tileX, tileY, dimensionId);
1676 1912 }
1677 1913
1678 #chunkData (chunkX, chunkY)
1914 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1679 1915 {
1680 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1916 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
1681 1917 if (loaded)
1682 1918 { return loaded.data; }
1683 1919 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1684 1920 }
1685 1921
1686 isEnterable (tileX, tileY)
1922 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1687 1923 {
1688 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1924 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1689 1925 if (!data.open)
1690 1926 { return false; }
1691 1927 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1692 1928 }
1693 1929
1694 isClearForRangedAttack (tileX, tileY)
1930 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
1695 1931 {
1696 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1932 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1697 1933 if (!data.open)
1698 1934 { return false; }
1699 1935 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
@@ -1712,9 +1948,16 @@ export class WorkerWorld
1712 1948 return !!mobDefinition(creature?.mobTypeId)?.flying;
1713 1949 }
1714 1950
1951 #entityDimensionId (entityId)
1952 {
1953 const handle = this.ecs.handleOf(entityId);
1954 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
1955 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
1956 }
1957
1715 1958 #occupy (entityId, tileX, tileY)
1716 1959 {
1717 const key = tileKey(tileX, tileY);
1960 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1718 1961 let set = this.occupancy.get(key);
1719 1962 if (!set)
1720 1963 {
@@ -1726,7 +1969,7 @@ export class WorkerWorld
1726 1969
1727 1970 #vacate (entityId, tileX, tileY)
1728 1971 {
1729 const key = tileKey(tileX, tileY);
1972 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1730 1973 const set = this.occupancy.get(key);
1731 1974 if (!set)
1732 1975 { return; }
@@ -1735,9 +1978,9 @@ export class WorkerWorld
1735 1978 { this.occupancy.delete(key); }
1736 1979 }
1737 1980
1738 #anyOccupant (tileX, tileY)
1981 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
1739 1982 {
1740 const key = tileKey(tileX, tileY);
1983 const key = tileKey(tileX, tileY, dimensionId);
1741 1984 const local = this.occupancy.get(key);
1742 1985 if (local?.size)
1743 1986 { return local.values().next().value; }
@@ -1747,9 +1990,10 @@ export class WorkerWorld
1747 1990 return null;
1748 1991 }
1749 1992
1750 #hasOtherOccupant (entityId, tileX, tileY)
1993 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
1751 1994 {
1752 const key = tileKey(tileX, tileY);
1995 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
1996 const key = tileKey(tileX, tileY, dim);
1753 1997 const local = this.occupancy.get(key);
1754 1998 if (local)
1755 1999 {
@@ -1772,9 +2016,9 @@ export class WorkerWorld
1772 2016 }
1773 2017
1774 2018 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
1775 #occupied (tileX, tileY)
2019 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
1776 2020 {
1777 return this.#anyOccupant(tileX, tileY);
2021 return this.#anyOccupant(tileX, tileY, dimensionId);
1778 2022 }
1779 2023 }
1780 2024
@@ -1792,6 +2036,14 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
1792 2036 return null;
1793 2037 }
1794 2038
2039 function hasDialogueBrowsers (origin)
2040 {
2041 const browsers = origin?.dialogueBrowsers;
2042 if (!browsers || typeof browsers !== "object")
2043 { return false; }
2044 return Object.keys(browsers).length > 0;
2045 }
2046
1795 2047 function randInt (min, max)
1796 2048 {
1797 2049 return min + Math.floor(Math.random() * (max - min + 1));
@@ -1802,14 +2054,14 @@ export function replicaNeededForOwnedChunks (ownedChunkKeys)
1802 2054 const needed = new Set();
1803 2055 for (const key of ownedChunkKeys)
1804 2056 {
1805 const { chunkX, chunkY } = parseChunkKey(key);
2057 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1806 2058 for (let dy = -1; dy <= 1; dy++)
1807 2059 {
1808 2060 for (let dx = -1; dx <= 1; dx++)
1809 2061 {
1810 2062 if (dx === 0 && dy === 0)
1811 2063 { continue; }
1812 needed.add(chunkKey(chunkX + dx, chunkY + dy));
2064 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
1813 2065 }
1814 2066 }
1815 2067 }
@@ -1,4 +1,5 @@
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
1import { GAIT, VISIBLE_CHUNK_RADIUS, DEFAULT_WORLD_SETTINGS, NAV_STUCK_MS } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2import {
3import {
3 chunkKey,
4 chunkKey,
4 chunkToRegion,
5 chunkToRegion,
@@ -55,7 +56,8 @@ import {
55 queueStandInRangeApproach,
56 queueStandInRangeApproach,
56 resolveCombatTarget,
57 resolveCombatTarget,
57 stepAggression,
58 stepAggression,
58 stepCombat
59 stepCombat,
60 chebyshev
59} from "../combat/service.js";
61} from "../combat/service.js";
60import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
62import { awardCombatHitXp, syncPlayerStamina } from "../skills/service.js";
61import { SkillId } from "../../../shared/definitions/skills.js";
63import { SkillId } from "../../../shared/definitions/skills.js";
@@ -146,7 +148,7 @@ export class WorkerWorld
146 case WorkerMessage.updateFlight:
148 case WorkerMessage.updateFlight:
147 return this.#updateFlight(message.entityId, message.flight, message.now);
149 return this.#updateFlight(message.entityId, message.flight, message.now);
148 case WorkerMessage.chunkIsSimulating:
150 case WorkerMessage.chunkIsSimulating:
149 return this.chunkIsSimulating(message.tileX, message.tileY);
151 return this.chunkIsSimulating(message.tileX, message.tileY, message.dimensionId);
150 case WorkerMessage.applyTransfer:
152 case WorkerMessage.applyTransfer:
151 return this.#applyTransfer(message);
153 return this.#applyTransfer(message);
152 case WorkerMessage.commitTransfer:
154 case WorkerMessage.commitTransfer:
@@ -154,13 +156,13 @@ export class WorkerWorld
154 case WorkerMessage.abortTransfer:
156 case WorkerMessage.abortTransfer:
155 return this.#abortTransfer(message.entityId);
157 return this.#abortTransfer(message.entityId);
156 case WorkerMessage.snapshotChunk:
158 case WorkerMessage.snapshotChunk:
157 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly);
159 return this.#chunkSnapshot(message.chunkX, message.chunkY, !!message.staticOnly, message.dimensionId);
158 case WorkerMessage.listLoaders:
160 case WorkerMessage.listLoaders:
159 return this.#listLoaders();
161 return this.#listLoaders();
160 case WorkerMessage.listPublicEntities:
162 case WorkerMessage.listPublicEntities:
161 return this.#listPublicEntities();
163 return this.#listPublicEntities();
162 case WorkerMessage.entitiesInRegion:
164 case WorkerMessage.entitiesInRegion:
163 return this.#entitiesInRegion(message.regionX, message.regionY);
165 return this.#entitiesInRegion(message.regionX, message.regionY, message.dimensionId);
164 case WorkerMessage.inspect:
166 case WorkerMessage.inspect:
165 return publicEntityView(this.ecs, message.entityId);
167 return publicEntityView(this.ecs, message.entityId);
166 case WorkerMessage.remoteCombatEngage:
168 case WorkerMessage.remoteCombatEngage:
@@ -175,6 +177,8 @@ export class WorkerWorld
175 return this.#spawnCorpseDrops(message);
177 return this.#spawnCorpseDrops(message);
176 case WorkerMessage.applyRespawn:
178 case WorkerMessage.applyRespawn:
177 return this.#applyRespawn(message);
179 return this.#applyRespawn(message);
180 case WorkerMessage.relocateEntity:
181 return this.#relocateEntity(message);
178 case WorkerMessage.clearCombat:
182 case WorkerMessage.clearCombat:
179 clearEngage(this.ecs, message.entityId);
183 clearEngage(this.ecs, message.entityId);
180 for (const entity of this.ecs.query(Component.combat))
184 for (const entity of this.ecs.query(Component.combat))
@@ -194,14 +198,18 @@ export class WorkerWorld
194 return this.#stationExchangeClerk(message);
198 return this.#stationExchangeClerk(message);
195 case WorkerMessage.releaseExchangeClerk:
199 case WorkerMessage.releaseExchangeClerk:
196 return this.#releaseExchangeClerk(message);
200 return this.#releaseExchangeClerk(message);
201 case WorkerMessage.pinDialogue:
202 return this.#pinDialogue(message.entityId, message.characterId);
203 case WorkerMessage.unpinDialogue:
204 return this.#unpinDialogue(message.entityId, message.characterId);
197 default:
205 default:
198 throw new Error(`Unknown worker message ${message.type}`);
206 throw new Error(`Unknown worker message ${message.type}`);
199 }
207 }
200 }
208 }
201
209
202 ownsRegion (regionX, regionY)
210 ownsRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
203 {
211 {
204 return this.ownedRegions.has(regionKey(regionX, regionY));
212 return this.ownedRegions.has(regionKey(regionX, regionY, dimensionId));
205 }
213 }
206
214
207 requireOwnedEntity (sessionId, characterId)
215 requireOwnedEntity (sessionId, characterId)
@@ -209,9 +217,9 @@ export class WorkerWorld
209 return this.#requireOwnedEntity(sessionId, characterId);
217 return this.#requireOwnedEntity(sessionId, characterId);
210 }
218 }
211
219
212 chunkData (chunkX, chunkY)
220 chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
213 {
221 {
214 return this.#chunkData(chunkX, chunkY);
222 return this.#chunkData(chunkX, chunkY, dimensionId);
215 }
223 }
216
224
217 #configure (message)
225 #configure (message)
@@ -225,16 +233,19 @@ export class WorkerWorld
225
233
226 #assignRegion (message)
234 #assignRegion (message)
227 {
235 {
228 this.ownedRegions.add(regionKey(message.regionX, message.regionY));
236 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
237 this.ownedRegions.add(regionKey(message.regionX, message.regionY, dim));
229 for (const chunk of message.chunks ?? [])
238 for (const chunk of message.chunks ?? [])
230 {
239 {
240 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
231 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
241 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
232 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
242 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
233 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
243 clearPlantRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
234 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY), {
244 this.chunks.set(chunkKey(chunk.chunkX, chunk.chunkY, chunkDim), {
235 data: cloneChunkData(chunk.data),
245 data: cloneChunkData(chunk.data),
236 simulating: false,
246 simulating: false,
237 replica: false
247 replica: false,
248 dimensionId: chunkDim
238 });
249 });
239 }
250 }
240 return { ok: true };
251 return { ok: true };
@@ -242,9 +253,11 @@ export class WorkerWorld
242
253
243 #replaceRegionChunks (message)
254 #replaceRegionChunks (message)
244 {
255 {
256 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
245 for (const chunk of message.chunks ?? [])
257 for (const chunk of message.chunks ?? [])
246 {
258 {
247 const key = chunkKey(chunk.chunkX, chunk.chunkY);
259 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? dim);
260 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
248 const existing = this.chunks.get(key);
261 const existing = this.chunks.get(key);
249 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
262 clearOreRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
250 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
263 clearTreeRespawnsForChunk(this, chunk.chunkX, chunk.chunkY);
@@ -252,7 +265,8 @@ export class WorkerWorld
252 this.chunks.set(key, {
265 this.chunks.set(key, {
253 data: cloneChunkData(chunk.data),
266 data: cloneChunkData(chunk.data),
254 simulating: existing?.simulating ?? false,
267 simulating: existing?.simulating ?? false,
255 replica: existing?.replica ?? false
268 replica: existing?.replica ?? false,
269 dimensionId: chunkDim
256 });
270 });
257 }
271 }
258 return { ok: true };
272 return { ok: true };
@@ -260,8 +274,9 @@ export class WorkerWorld
260
274
261 #dropRegion (message)
275 #dropRegion (message)
262 {
276 {
277 const dim = normalizeDimensionId(message.dimensionId ?? OVERWORLD_ID);
263 const dropped = [];
278 const dropped = [];
264 for (const record of this.#entitiesInRegion(message.regionX, message.regionY))
279 for (const record of this.#entitiesInRegion(message.regionX, message.regionY, dim))
265 {
280 {
266 const components = record.payload?.components;
281 const components = record.payload?.components;
267 if (components?.creature && !components?.character && components?.health)
282 if (components?.creature && !components?.character && components?.health)
@@ -274,9 +289,11 @@ export class WorkerWorld
274 { removeGroundItem(this, item.groundItemId); }
289 { removeGroundItem(this, item.groundItemId); }
275 for (const [key, chunk] of [...this.chunks.entries()])
290 for (const [key, chunk] of [...this.chunks.entries()])
276 {
291 {
277 const { chunkX, chunkY } = parseChunkKey(key);
292 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
278 if (chunk.replica)
293 if (chunk.replica)
279 { continue; }
294 { continue; }
295 if (dimensionId !== dim)
296 { continue; }
280 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
297 if (chunkToRegion(chunkX) === message.regionX && chunkToRegion(chunkY) === message.regionY)
281 {
298 {
282 clearOreRespawnsForChunk(this, chunkX, chunkY);
299 clearOreRespawnsForChunk(this, chunkX, chunkY);
@@ -285,7 +302,7 @@ export class WorkerWorld
285 this.chunks.delete(key);
302 this.chunks.delete(key);
286 }
303 }
287 }
304 }
288 this.ownedRegions.delete(regionKey(message.regionX, message.regionY));
305 this.ownedRegions.delete(regionKey(message.regionX, message.regionY, dim));
289 return { dropped, groundItems };
306 return { dropped, groundItems };
290 }
307 }
291
308
@@ -294,7 +311,8 @@ export class WorkerWorld
294 const keep = new Set();
311 const keep = new Set();
295 for (const chunk of message.chunks ?? [])
312 for (const chunk of message.chunks ?? [])
296 {
313 {
297 const key = chunkKey(chunk.chunkX, chunk.chunkY);
314 const chunkDim = normalizeDimensionId(chunk.dimensionId ?? OVERWORLD_ID);
315 const key = chunkKey(chunk.chunkX, chunk.chunkY, chunkDim);
298 keep.add(key);
316 keep.add(key);
299 const existing = this.chunks.get(key);
317 const existing = this.chunks.get(key);
300 if (existing && !existing.replica)
318 if (existing && !existing.replica)
@@ -302,7 +320,8 @@ export class WorkerWorld
302 this.chunks.set(key, {
320 this.chunks.set(key, {
303 data: cloneChunkData(chunk.data),
321 data: cloneChunkData(chunk.data),
304 simulating: false,
322 simulating: false,
305 replica: true
323 replica: true,
324 dimensionId: chunkDim
306 });
325 });
307 }
326 }
308 for (const [key, chunk] of [...this.chunks.entries()])
327 for (const [key, chunk] of [...this.chunks.entries()])
@@ -335,7 +354,8 @@ export class WorkerWorld
335 for (const ghost of message.ghosts ?? [])
354 for (const ghost of message.ghosts ?? [])
336 {
355 {
337 this.ghosts.set(ghost.entityId, ghost);
356 this.ghosts.set(ghost.entityId, ghost);
338 const key = tileKey(ghost.tileX, ghost.tileY);
357 const dim = normalizeDimensionId(ghost.dimensionId ?? OVERWORLD_ID);
358 const key = tileKey(ghost.tileX, ghost.tileY, dim);
339 let set = this.ghostOccupancy.get(key);
359 let set = this.ghostOccupancy.get(key);
340 if (!set)
360 if (!set)
341 {
361 {
@@ -425,7 +445,7 @@ export class WorkerWorld
425 case "cancel-attack":
445 case "cancel-attack":
426 return this.#cancelAttack(sessionId, command.characterId);
446 return this.#cancelAttack(sessionId, command.characterId);
427 case "interact":
447 case "interact":
428 return this.#interact(sessionId, command.characterId, command.targetEntityId);
448 return this.#interact(sessionId, command.characterId, command.targetEntityId, command.purpose);
429 case "follow":
449 case "follow":
430 return this.#follow(sessionId, command.characterId, command.targetEntityId);
450 return this.#follow(sessionId, command.characterId, command.targetEntityId);
431 case "cancel-follow":
451 case "cancel-follow":
@@ -518,7 +538,8 @@ export class WorkerWorld
518
538
519 const destRegionX = tileToRegion(message.tileX);
539 const destRegionX = tileToRegion(message.tileX);
520 const destRegionY = tileToRegion(message.tileY);
540 const destRegionY = tileToRegion(message.tileY);
521 if (!this.ownsRegion(destRegionX, destRegionY))
541 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
542 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
522 {
543 {
523 this.frozen.add(message.entityId);
544 this.frozen.add(message.entityId);
524 return {
545 return {
@@ -531,11 +552,12 @@ export class WorkerWorld
531 destTileY: message.tileY,
552 destTileY: message.tileY,
532 toRegionX: destRegionX,
553 toRegionX: destRegionX,
533 toRegionY: destRegionY,
554 toRegionY: destRegionY,
555 dimensionId,
534 payload: serializeEntity(this.ecs, message.entityId)
556 payload: serializeEntity(this.ecs, message.entityId)
535 }
557 }
536 };
558 };
537 }
559 }
538 if (!this.isEnterable(message.tileX, message.tileY))
560 if (!this.isEnterable(message.tileX, message.tileY, dimensionId))
539 { return { accepted: false }; }
561 { return { accepted: false }; }
540 this.#vacate(message.entityId, fromTileX, fromTileY);
562 this.#vacate(message.entityId, fromTileX, fromTileY);
541 position.tileX = message.tileX;
563 position.tileX = message.tileX;
@@ -550,6 +572,82 @@ export class WorkerWorld
550 fromTileY,
572 fromTileY,
551 tileX: position.tileX,
573 tileX: position.tileX,
552 tileY: position.tileY,
574 tileY: position.tileY,
575 dimensionId,
576 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
577 }
578 };
579 }
580
581 /** Move an entity to a tile/dimension; clears path and updates occupancy. */
582 #relocateEntity (message)
583 {
584 const handle = this.ecs.handleOf(message.entityId);
585 if (handle == null)
586 { return { accepted: false }; }
587 const position = this.ecs.get(handle, Component.position);
588 if (!position)
589 { return { accepted: false }; }
590 const fromTileX = position.tileX;
591 const fromTileY = position.tileY;
592 const fromDimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
593 const destTileX = message.tileX | 0;
594 const destTileY = message.tileY | 0;
595 const dimensionId = normalizeDimensionId(message.dimensionId ?? fromDimensionId);
596
597 clearEngage(this.ecs, message.entityId);
598 const path = this.ecs.get(handle, Component.path);
599 if (path)
600 { path.tiles = []; }
601 clearFollow(this.ecs, message.entityId);
602
603 const destRegionX = tileToRegion(destTileX);
604 const destRegionY = tileToRegion(destTileY);
605 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
606 {
607 this.frozen.add(message.entityId);
608 const payload = serializeEntity(this.ecs, message.entityId);
609 if (payload.components?.position)
610 {
611 payload.components.position.tileX = destTileX;
612 payload.components.position.tileY = destTileY;
613 payload.components.position.dimensionId = dimensionId;
614 }
615 return {
616 accepted: true,
617 transferRequest: {
618 entityId: message.entityId,
619 fromTileX,
620 fromTileY,
621 fromDimensionId,
622 destTileX,
623 destTileY,
624 toRegionX: destRegionX,
625 toRegionY: destRegionY,
626 dimensionId,
627 payload
628 }
629 };
630 }
631 if (!this.isEnterable(destTileX, destTileY, dimensionId))
632 { return { accepted: false }; }
633 if (!this.#isFlying(handle))
634 { this.#vacate(message.entityId, fromTileX, fromTileY); }
635 position.tileX = destTileX;
636 position.tileY = destTileY;
637 position.dimensionId = dimensionId;
638 if (!this.#isFlying(handle))
639 { this.#occupy(message.entityId, destTileX, destTileY); }
640 return {
641 accepted: true,
642 event: {
643 type: "entity-move",
644 entityId: message.entityId,
645 fromTileX,
646 fromTileY,
647 fromDimensionId,
648 tileX: destTileX,
649 tileY: destTileY,
650 dimensionId,
553 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
651 gait: this.ecs.get(handle, Component.movement)?.gait ?? GAIT.walk
554 }
652 }
555 };
653 };
@@ -646,7 +744,8 @@ export class WorkerWorld
646 position.tileY = tileY;
744 position.tileY = tileY;
647 const destRegionX = tileToRegion(tileX);
745 const destRegionX = tileToRegion(tileX);
648 const destRegionY = tileToRegion(tileY);
746 const destRegionY = tileToRegion(tileY);
649 if (!this.ownsRegion(destRegionX, destRegionY))
747 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
748 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
650 {
749 {
651 this.frozen.add(entityId);
750 this.frozen.add(entityId);
652 return {
751 return {
@@ -658,7 +757,8 @@ export class WorkerWorld
658 destTileX: tileX,
757 destTileX: tileX,
659 destTileY: tileY,
758 destTileY: tileY,
660 toRegionX: destRegionX,
759 toRegionX: destRegionX,
661 toRegionY: destRegionY
760 toRegionY: destRegionY,
761 dimensionId
662 }
762 }
663 };
763 };
664 }
764 }
@@ -859,7 +959,7 @@ export class WorkerWorld
859 return { events: [] };
959 return { events: [] };
860 }
960 }
861
961
862 #interact (sessionId, characterId, targetEntityId)
962 #interact (sessionId, characterId, targetEntityId, purpose = null)
863 {
963 {
864 this.#requireOwnedEntity(sessionId, characterId);
964 this.#requireOwnedEntity(sessionId, characterId);
865 const targetHandle = this.ecs.handleOf(targetEntityId);
965 const targetHandle = this.ecs.handleOf(targetEntityId);
@@ -878,7 +978,45 @@ export class WorkerWorld
878 const creature = this.ecs.get(targetHandle, Component.creature);
978 const creature = this.ecs.get(targetHandle, Component.creature);
879 const def = creature ? mobDefinition(creature.mobTypeId) : null;
979 const def = creature ? mobDefinition(creature.mobTypeId) : null;
880 const shop = this.ecs.get(targetHandle, Component.shop);
980 const shop = this.ecs.get(targetHandle, Component.shop);
881 if (shopHasInterface(shop))
981 const hasShop = shopHasInterface(shop);
982 const origin = this.ecs.get(targetHandle, Component.spawnOrigin);
983 const dialogueId = origin?.dialogueId ? String(origin.dialogueId) : "";
984 const intent = purpose === "shop" || purpose === "talk" ? purpose : null;
985
986 if (intent === "shop" && hasShop)
987 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
988 if (intent === "talk" && dialogueId)
989 {
990 // Pin in-worker before return so wander cannot start before the sim thread pins.
991 this.#pinDialogue(targetEntityId, characterId);
992 return {
993 events: [{
994 type: "open-dialogue",
995 sessionId,
996 characterId,
997 entityId: targetEntityId,
998 dialogueId
999 }]
1000 };
1001 }
1002 if (intent === "talk" && hasShop)
1003 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1004
1005 // Default click: prefer dialogue when assigned, else shop, else talkable no-op.
1006 if (dialogueId)
1007 {
1008 this.#pinDialogue(targetEntityId, characterId);
1009 return {
1010 events: [{
1011 type: "open-dialogue",
1012 sessionId,
1013 characterId,
1014 entityId: targetEntityId,
1015 dialogueId
1016 }]
1017 };
1018 }
1019 if (hasShop)
882 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
1020 { return openShop(this, sessionId, characterId, targetEntityId, Date.now()); }
883 if (!def?.talkable)
1021 if (!def?.talkable)
884 {
1022 {
@@ -886,7 +1024,6 @@ export class WorkerWorld
886 error.userFacing = true;
1024 error.userFacing = true;
887 throw error;
1025 throw error;
888 }
1026 }
889 // Dialogue comes later; talkable NPCs without stock are a no-op for now.
890 return { events: [] };
1027 return { events: [] };
891 }
1028 }
892
1029
@@ -1085,6 +1222,7 @@ export class WorkerWorld
1085 destTileY: event.destTileY,
1222 destTileY: event.destTileY,
1086 toRegionX: event.toRegionX,
1223 toRegionX: event.toRegionX,
1087 toRegionY: event.toRegionY,
1224 toRegionY: event.toRegionY,
1225 dimensionId: event.dimensionId ?? OVERWORLD_ID,
1088 payload
1226 payload
1089 });
1227 });
1090 continue;
1228 continue;
@@ -1126,6 +1264,7 @@ export class WorkerWorld
1126 const events = expireGroundItems(this, now);
1264 const events = expireGroundItems(this, now);
1127 const transferRequests = [];
1265 const transferRequests = [];
1128 events.push(...pruneShopBrowsers(this));
1266 events.push(...pruneShopBrowsers(this));
1267 events.push(...this.#pruneDialogueBrowsers());
1129 this.#queueAmbientWander();
1268 this.#queueAmbientWander();
1130 this.#queueSpawnerWander();
1269 this.#queueSpawnerWander();
1131 this.#queueExchangeStations();
1270 this.#queueExchangeStations();
@@ -1144,7 +1283,7 @@ export class WorkerWorld
1144 { path.stuckSince = null; }
1283 { path.stuckSince = null; }
1145 continue;
1284 continue;
1146 }
1285 }
1147 if (!this.chunkIsSimulating(position.tileX, position.tileY))
1286 if (!this.chunkIsSimulating(position.tileX, position.tileY, position.dimensionId ?? OVERWORLD_ID))
1148 { continue; }
1287 { continue; }
1149
1288
1150 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
1289 this.#repathIfNavigationStuck(entityId, position, movement, path, now);
@@ -1165,7 +1304,8 @@ export class WorkerWorld
1165 { continue; }
1304 { continue; }
1166 const destRegionX = tileToRegion(next.x);
1305 const destRegionX = tileToRegion(next.x);
1167 const destRegionY = tileToRegion(next.y);
1306 const destRegionY = tileToRegion(next.y);
1168 if (!this.ownsRegion(destRegionX, destRegionY))
1307 const dimensionId = normalizeDimensionId(position.dimensionId ?? OVERWORLD_ID);
1308 if (!this.ownsRegion(destRegionX, destRegionY, dimensionId))
1169 {
1309 {
1170 this.frozen.add(entityId);
1310 this.frozen.add(entityId);
1171 transferRequests.push({
1311 transferRequests.push({
@@ -1176,6 +1316,7 @@ export class WorkerWorld
1176 destTileY: next.y,
1316 destTileY: next.y,
1177 toRegionX: destRegionX,
1317 toRegionX: destRegionX,
1178 toRegionY: destRegionY,
1318 toRegionY: destRegionY,
1319 dimensionId,
1179 payload: serializeEntity(this.ecs, entityId)
1320 payload: serializeEntity(this.ecs, entityId)
1180 });
1321 });
1181 continue;
1322 continue;
@@ -1288,7 +1429,7 @@ export class WorkerWorld
1288 { continue; }
1429 { continue; }
1289 if (path.tiles?.length)
1430 if (path.tiles?.length)
1290 { continue; }
1431 { continue; }
1291 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1432 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1292 { continue; }
1433 { continue; }
1293 if (Math.random() > 0.35)
1434 if (Math.random() > 0.35)
1294 { continue; }
1435 { continue; }
@@ -1320,6 +1461,8 @@ export class WorkerWorld
1320 if (shopHasActiveBrowsers(shop))
1461 if (shopHasActiveBrowsers(shop))
1321 { continue; }
1462 { continue; }
1322 const origin = entity.spawnOrigin;
1463 const origin = entity.spawnOrigin;
1464 if (hasDialogueBrowsers(origin))
1465 { continue; }
1323 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1466 if (origin?.centralExchange && Number.isInteger(origin.stationTileX) && Number.isInteger(origin.stationTileY))
1324 { continue; }
1467 { continue; }
1325 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
1468 const def = mobDefinition(this.ecs.get(entity.handle, Component.creature)?.mobTypeId);
@@ -1328,9 +1471,10 @@ export class WorkerWorld
1328 const path = this.ecs.get(entity.handle, Component.path);
1471 const path = this.ecs.get(entity.handle, Component.path);
1329 if (!path || path.tiles?.length)
1472 if (!path || path.tiles?.length)
1330 { continue; }
1473 { continue; }
1331 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY))
1474 if (!this.chunkIsSimulating(entity.position.tileX, entity.position.tileY, entity.position.dimensionId ?? OVERWORLD_ID))
1332 { continue; }
1475 { continue; }
1333 if (Math.random() > 0.4)
1476 // ~4× longer idle stands than the old 0.4 chance (mobs mostly idle, rarely walk).
1477 if (Math.random() > 0.1)
1334 { continue; }
1478 { continue; }
1335
1479
1336 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
1480 const originX = Number.isInteger(origin.originTileX) ? origin.originTileX : entity.position.tileX;
@@ -1452,6 +1596,81 @@ export class WorkerWorld
1452 return { ok: true, released };
1596 return { ok: true, released };
1453 }
1597 }
1454
1598
1599 #pinDialogue (entityId, characterId)
1600 {
1601 const handle = this.ecs.handleOf(entityId | 0);
1602 if (handle == null)
1603 { return { ok: false }; }
1604 const origin = this.ecs.get(handle, Component.spawnOrigin);
1605 if (!origin)
1606 { return { ok: false }; }
1607 if (!origin.dialogueBrowsers || typeof origin.dialogueBrowsers !== "object")
1608 { origin.dialogueBrowsers = Object.create(null); }
1609 origin.dialogueBrowsers[characterId | 0] = true;
1610 const path = this.ecs.get(handle, Component.path);
1611 if (path)
1612 { path.tiles = []; }
1613 return { ok: true };
1614 }
1615
1616 #unpinDialogue (entityId, characterId)
1617 {
1618 const handle = this.ecs.handleOf(entityId | 0);
1619 if (handle == null)
1620 { return { ok: false }; }
1621 const origin = this.ecs.get(handle, Component.spawnOrigin);
1622 if (!origin?.dialogueBrowsers)
1623 { return { ok: true }; }
1624 delete origin.dialogueBrowsers[characterId | 0];
1625 return { ok: true };
1626 }
1627
1628 #pruneDialogueBrowsers ()
1629 {
1630 const events = [];
1631 for (const entity of this.ecs.query(Component.spawnOrigin, Component.position))
1632 {
1633 const browsers = entity.spawnOrigin?.dialogueBrowsers;
1634 if (!browsers || typeof browsers !== "object")
1635 { continue; }
1636 const ids = Object.keys(browsers).map((id) => Number(id));
1637 if (!ids.length)
1638 { continue; }
1639 const path = this.ecs.get(entity.handle, Component.path);
1640 if (path)
1641 { path.tiles = []; }
1642 for (const characterId of ids)
1643 {
1644 const playerEntityId = this.characterEntities.get(characterId);
1645 if (playerEntityId == null)
1646 {
1647 delete browsers[characterId];
1648 continue;
1649 }
1650 const playerHandle = this.ecs.handleOf(playerEntityId);
1651 const playerPos = this.ecs.get(playerHandle, Component.position);
1652 const stillNear = playerPos
1653 && chebyshev(
1654 playerPos.tileX,
1655 playerPos.tileY,
1656 entity.position.tileX,
1657 entity.position.tileY
1658 ) <= 1;
1659 if (stillNear)
1660 { continue; }
1661 delete browsers[characterId];
1662 const identity = this.ecs.get(playerHandle, Component.networkIdentity);
1663 events.push({
1664 type: "dialogue-walk-away",
1665 sessionId: identity?.sessionId ?? null,
1666 characterId,
1667 npcEntityId: entity.entityId
1668 });
1669 }
1670 }
1671 return events;
1672 }
1673
1455 /** Keep stationed CE clerks at their counter tile. */
1674 /** Keep stationed CE clerks at their counter tile. */
1456 #queueExchangeStations ()
1675 #queueExchangeStations ()
1457 {
1676 {
@@ -1497,20 +1716,23 @@ export class WorkerWorld
1497 const position = payload.components?.position;
1716 const position = payload.components?.position;
1498 const destTileX = message.destTileX ?? position?.tileX;
1717 const destTileX = message.destTileX ?? position?.tileX;
1499 const destTileY = message.destTileY ?? position?.tileY;
1718 const destTileY = message.destTileY ?? position?.tileY;
1719 const dimensionId = normalizeDimensionId(
1720 message.dimensionId ?? position?.dimensionId ?? OVERWORLD_ID
1721 );
1500 if (destTileX == null || destTileY == null)
1722 if (destTileX == null || destTileY == null)
1501 { return { accepted: false, reason: "missing-destination" }; }
1723 { return { accepted: false, reason: "missing-destination" }; }
1502 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY)))
1724 if (!this.ownsRegion(tileToRegion(destTileX), tileToRegion(destTileY), dimensionId))
1503 { return { accepted: false, reason: "not-owner" }; }
1725 { return { accepted: false, reason: "not-owner" }; }
1504
1726
1505 const creature = payload.components?.creature;
1727 const creature = payload.components?.creature;
1506 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1728 const flying = !!mobDefinition(creature?.mobTypeId)?.flying;
1507 if (flying)
1729 if (flying)
1508 {
1730 {
1509 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY));
1731 const data = this.#chunkData(tileToChunk(destTileX), tileToChunk(destTileY), dimensionId);
1510 if (!data?.open)
1732 if (!data?.open)
1511 { return { accepted: false, reason: "blocked" }; }
1733 { return { accepted: false, reason: "blocked" }; }
1512 }
1734 }
1513 else if (!this.isEnterable(destTileX, destTileY))
1735 else if (!this.isEnterable(destTileX, destTileY, dimensionId))
1514 { return { accepted: false, reason: "blocked" }; }
1736 { return { accepted: false, reason: "blocked" }; }
1515
1737
1516 deserializeEntity(this.ecs, payload);
1738 deserializeEntity(this.ecs, payload);
@@ -1519,6 +1741,7 @@ export class WorkerWorld
1519 const path = this.ecs.get(handle, Component.path);
1741 const path = this.ecs.get(handle, Component.path);
1520 livePosition.tileX = destTileX;
1742 livePosition.tileX = destTileX;
1521 livePosition.tileY = destTileY;
1743 livePosition.tileY = destTileY;
1744 livePosition.dimensionId = dimensionId;
1522 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1745 if (path?.tiles?.length && path.tiles[0].x === destTileX && path.tiles[0].y === destTileY)
1523 { path.tiles.shift(); }
1746 { path.tiles.shift(); }
1524 if (!flying)
1747 if (!flying)
@@ -1552,6 +1775,7 @@ export class WorkerWorld
1552 entityId: entity.entityId,
1775 entityId: entity.entityId,
1553 tileX: entity.position.tileX,
1776 tileX: entity.position.tileX,
1554 tileY: entity.position.tileY,
1777 tileY: entity.position.tileY,
1778 dimensionId: normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID),
1555 chunkLoader: { ...entity.chunkLoader }
1779 chunkLoader: { ...entity.chunkLoader }
1556 }));
1780 }));
1557 }
1781 }
@@ -1561,11 +1785,15 @@ export class WorkerWorld
1561 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1785 return this.ecs.query(Component.position).map((entity) => publicEntityView(this.ecs, entity.entityId)).filter(Boolean);
1562 }
1786 }
1563
1787
1564 #entitiesInRegion (regionX, regionY)
1788 #entitiesInRegion (regionX, regionY, dimensionId = OVERWORLD_ID)
1565 {
1789 {
1790 const dim = normalizeDimensionId(dimensionId);
1566 const records = [];
1791 const records = [];
1567 for (const entity of this.ecs.query(Component.position))
1792 for (const entity of this.ecs.query(Component.position))
1568 {
1793 {
1794 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1795 if (entityDim !== dim)
1796 { continue; }
1569 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1797 if (tileToRegion(entity.position.tileX) !== regionX || tileToRegion(entity.position.tileY) !== regionY)
1570 { continue; }
1798 { continue; }
1571 records.push({
1799 records.push({
@@ -1577,16 +1805,18 @@ export class WorkerWorld
1577 return records;
1805 return records;
1578 }
1806 }
1579
1807
1580 #chunkSnapshot (chunkX, chunkY, staticOnly = false)
1808 #chunkSnapshot (chunkX, chunkY, staticOnly = false, dimensionId = OVERWORLD_ID)
1581 {
1809 {
1582 const data = this.#chunkData(chunkX, chunkY);
1810 const dim = normalizeDimensionId(dimensionId);
1811 const data = this.#chunkData(chunkX, chunkY, dim);
1583 if (staticOnly)
1812 if (staticOnly)
1584 {
1813 {
1585 return {
1814 return {
1586 chunkX,
1815 chunkX,
1587 chunkY,
1816 chunkY,
1817 dimensionId: dim,
1588 open: data.open,
1818 open: data.open,
1589 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1819 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1590 grounds: data.grounds,
1820 grounds: data.grounds,
1591 blocks: data.blocks,
1821 blocks: data.blocks,
1592 light: data.light,
1822 light: data.light,
@@ -1597,6 +1827,9 @@ export class WorkerWorld
1597 const entities = [];
1827 const entities = [];
1598 for (const entity of this.ecs.query(Component.position, Component.appearance))
1828 for (const entity of this.ecs.query(Component.position, Component.appearance))
1599 {
1829 {
1830 const entityDim = normalizeDimensionId(entity.position.dimensionId ?? OVERWORLD_ID);
1831 if (entityDim !== dim)
1832 { continue; }
1600 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1833 if (tileToChunk(entity.position.tileX) !== chunkX || tileToChunk(entity.position.tileY) !== chunkY)
1601 { continue; }
1834 { continue; }
1602 entities.push(publicEntityView(this.ecs, entity.entityId));
1835 entities.push(publicEntityView(this.ecs, entity.entityId));
@@ -1604,8 +1837,9 @@ export class WorkerWorld
1604 return {
1837 return {
1605 chunkX,
1838 chunkX,
1606 chunkY,
1839 chunkY,
1840 dimensionId: dim,
1607 open: data.open,
1841 open: data.open,
1608 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y).open),
1842 closedEdges: closedNeighborEdges(chunkX, chunkY, (x, y) => this.#chunkData(x, y, dim).open),
1609 grounds: data.grounds,
1843 grounds: data.grounds,
1610 blocks: data.blocks,
1844 blocks: data.blocks,
1611 light: data.light,
1845 light: data.light,
@@ -1631,22 +1865,23 @@ export class WorkerWorld
1631 };
1865 };
1632 }
1866 }
1633
1867
1634 chunkIsSimulating (tileX, tileY)
1868 chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1635 {
1869 {
1636 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY)));
1870 const chunk = this.chunks.get(chunkKey(tileToChunk(tileX), tileToChunk(tileY), dimensionId));
1637 return !!chunk && !chunk.replica && chunk.simulating;
1871 return !!chunk && !chunk.replica && chunk.simulating;
1638 }
1872 }
1639
1873
1640 walkableFor (entityId, tileX, tileY)
1874 walkableFor (entityId, tileX, tileY)
1641 {
1875 {
1876 const dim = this.#entityDimensionId(entityId);
1642 const handle = this.ecs.handleOf(entityId);
1877 const handle = this.ecs.handleOf(entityId);
1643 if (this.#isFlying(handle))
1878 if (this.#isFlying(handle))
1644 {
1879 {
1645 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1880 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dim);
1646 return !!data?.open;
1881 return !!data?.open;
1647 }
1882 }
1648 // Entities pass through each other; only terrain / closed chunks block movement.
1883 // Entities pass through each other; only terrain / closed chunks block movement.
1649 return this.isEnterable(tileX, tileY);
1884 return this.isEnterable(tileX, tileY, dim);
1650 }
1885 }
1651
1886
1652 /**
1887 /**
@@ -1655,9 +1890,10 @@ export class WorkerWorld
1655 */
1890 */
1656 isClearStanding (entityId, tileX, tileY)
1891 isClearStanding (entityId, tileX, tileY)
1657 {
1892 {
1658 if (!this.isEnterable(tileX, tileY))
1893 const dim = this.#entityDimensionId(entityId);
1894 if (!this.isEnterable(tileX, tileY, dim))
1659 { return false; }
1895 { return false; }
1660 return !this.#hasOtherOccupant(entityId, tileX, tileY);
1896 return !this.#hasOtherOccupant(entityId, tileX, tileY, dim);
1661 }
1897 }
1662
1898
1663 destroyEntity (entityId)
1899 destroyEntity (entityId)
@@ -1665,35 +1901,35 @@ export class WorkerWorld
1665 return this.#destroyEntity(entityId);
1901 return this.#destroyEntity(entityId);
1666 }
1902 }
1667
1903
1668 occupied (tileX, tileY)
1904 occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
1669 {
1905 {
1670 return this.#anyOccupant(tileX, tileY);
1906 return this.#anyOccupant(tileX, tileY, dimensionId);
1671 }
1907 }
1672
1908
1673 #chunkIsSimulating (tileX, tileY)
1909 #chunkIsSimulating (tileX, tileY, dimensionId = OVERWORLD_ID)
1674 {
1910 {
1675 return this.chunkIsSimulating(tileX, tileY);
1911 return this.chunkIsSimulating(tileX, tileY, dimensionId);
1676 }
1912 }
1677
1913
1678 #chunkData (chunkX, chunkY)
1914 #chunkData (chunkX, chunkY, dimensionId = OVERWORLD_ID)
1679 {
1915 {
1680 const loaded = this.chunks.get(chunkKey(chunkX, chunkY));
1916 const loaded = this.chunks.get(chunkKey(chunkX, chunkY, dimensionId));
1681 if (loaded)
1917 if (loaded)
1682 { return loaded.data; }
1918 { return loaded.data; }
1683 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1919 return createEmptyChunkData(this.settings.defaultGroundTypeId);
1684 }
1920 }
1685
1921
1686 isEnterable (tileX, tileY)
1922 isEnterable (tileX, tileY, dimensionId = OVERWORLD_ID)
1687 {
1923 {
1688 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1924 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1689 if (!data.open)
1925 if (!data.open)
1690 { return false; }
1926 { return false; }
1691 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1927 return isChunkTilePassable(data, tileToLocal(tileX), tileToLocal(tileY));
1692 }
1928 }
1693
1929
1694 isClearForRangedAttack (tileX, tileY)
1930 isClearForRangedAttack (tileX, tileY, dimensionId = OVERWORLD_ID)
1695 {
1931 {
1696 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY));
1932 const data = this.#chunkData(tileToChunk(tileX), tileToChunk(tileY), dimensionId);
1697 if (!data.open)
1933 if (!data.open)
1698 { return false; }
1934 { return false; }
1699 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
1935 return isChunkTileClearForRangedAttacks(data, tileToLocal(tileX), tileToLocal(tileY));
@@ -1712,9 +1948,16 @@ export class WorkerWorld
1712 return !!mobDefinition(creature?.mobTypeId)?.flying;
1948 return !!mobDefinition(creature?.mobTypeId)?.flying;
1713 }
1949 }
1714
1950
1951 #entityDimensionId (entityId)
1952 {
1953 const handle = this.ecs.handleOf(entityId);
1954 const position = handle != null ? this.ecs.get(handle, Component.position) : null;
1955 return normalizeDimensionId(position?.dimensionId ?? OVERWORLD_ID);
1956 }
1957
1715 #occupy (entityId, tileX, tileY)
1958 #occupy (entityId, tileX, tileY)
1716 {
1959 {
1717 const key = tileKey(tileX, tileY);
1960 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1718 let set = this.occupancy.get(key);
1961 let set = this.occupancy.get(key);
1719 if (!set)
1962 if (!set)
1720 {
1963 {
@@ -1726,7 +1969,7 @@ export class WorkerWorld
1726
1969
1727 #vacate (entityId, tileX, tileY)
1970 #vacate (entityId, tileX, tileY)
1728 {
1971 {
1729 const key = tileKey(tileX, tileY);
1972 const key = tileKey(tileX, tileY, this.#entityDimensionId(entityId));
1730 const set = this.occupancy.get(key);
1973 const set = this.occupancy.get(key);
1731 if (!set)
1974 if (!set)
1732 { return; }
1975 { return; }
@@ -1735,9 +1978,9 @@ export class WorkerWorld
1735 { this.occupancy.delete(key); }
1978 { this.occupancy.delete(key); }
1736 }
1979 }
1737
1980
1738 #anyOccupant (tileX, tileY)
1981 #anyOccupant (tileX, tileY, dimensionId = OVERWORLD_ID)
1739 {
1982 {
1740 const key = tileKey(tileX, tileY);
1983 const key = tileKey(tileX, tileY, dimensionId);
1741 const local = this.occupancy.get(key);
1984 const local = this.occupancy.get(key);
1742 if (local?.size)
1985 if (local?.size)
1743 { return local.values().next().value; }
1986 { return local.values().next().value; }
@@ -1747,9 +1990,10 @@ export class WorkerWorld
1747 return null;
1990 return null;
1748 }
1991 }
1749
1992
1750 #hasOtherOccupant (entityId, tileX, tileY)
1993 #hasOtherOccupant (entityId, tileX, tileY, dimensionId = null)
1751 {
1994 {
1752 const key = tileKey(tileX, tileY);
1995 const dim = dimensionId != null ? normalizeDimensionId(dimensionId) : this.#entityDimensionId(entityId);
1996 const key = tileKey(tileX, tileY, dim);
1753 const local = this.occupancy.get(key);
1997 const local = this.occupancy.get(key);
1754 if (local)
1998 if (local)
1755 {
1999 {
@@ -1772,9 +2016,9 @@ export class WorkerWorld
1772 }
2016 }
1773
2017
1774 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
2018 /** @deprecated use #anyOccupant — kept name for call sites expecting a single id */
1775 #occupied (tileX, tileY)
2019 #occupied (tileX, tileY, dimensionId = OVERWORLD_ID)
1776 {
2020 {
1777 return this.#anyOccupant(tileX, tileY);
2021 return this.#anyOccupant(tileX, tileY, dimensionId);
1778 }
2022 }
1779}
2023}
1780
2024
@@ -1792,6 +2036,14 @@ function pickWanderGoalInRange (world, entityId, originX, originY, range)
1792 return null;
2036 return null;
1793}
2037}
1794
2038
2039function hasDialogueBrowsers (origin)
2040{
2041 const browsers = origin?.dialogueBrowsers;
2042 if (!browsers || typeof browsers !== "object")
2043 { return false; }
2044 return Object.keys(browsers).length > 0;
2045}
2046
1795function randInt (min, max)
2047function randInt (min, max)
1796{
2048{
1797 return min + Math.floor(Math.random() * (max - min + 1));
2049 return min + Math.floor(Math.random() * (max - min + 1));
@@ -1802,14 +2054,14 @@ export function replicaNeededForOwnedChunks (ownedChunkKeys)
1802 const needed = new Set();
2054 const needed = new Set();
1803 for (const key of ownedChunkKeys)
2055 for (const key of ownedChunkKeys)
1804 {
2056 {
1805 const { chunkX, chunkY } = parseChunkKey(key);
2057 const { chunkX, chunkY, dimensionId } = parseChunkKey(key);
1806 for (let dy = -1; dy <= 1; dy++)
2058 for (let dy = -1; dy <= 1; dy++)
1807 {
2059 {
1808 for (let dx = -1; dx <= 1; dx++)
2060 for (let dx = -1; dx <= 1; dx++)
1809 {
2061 {
1810 if (dx === 0 && dy === 0)
2062 if (dx === 0 && dy === 0)
1811 { continue; }
2063 { continue; }
1812 needed.add(chunkKey(chunkX + dx, chunkY + dy));
2064 needed.add(chunkKey(chunkX + dx, chunkY + dy, dimensionId));
1813 }
2065 }
1814 }
2066 }
1815 }
2067 }
server/src/statusEffects/service.js +4 −3
@@ -42,9 +42,10 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
42 42 { continue; }
43 43 if (entry.type === StatusEffectType.healthRegen && health)
44 44 {
45 const before = health.current | 0;
46 health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
47 if ((health.current | 0) !== before)
45 const beforeInt = health.current | 0;
46 const next = Math.min(health.max | 0, (Number(health.current) || 0) + rate * dt);
47 health.current = next;
48 if ((next | 0) !== beforeInt)
48 49 { healthChanged = true; }
49 50 }
50 51 if (entry.type === StatusEffectType.staminaRegen && stamina)
@@ -42,9 +42,10 @@ export function stepStatusEffects (world, now = Date.now(), dt = 1 / 20)
42 { continue; }
42 { continue; }
43 if (entry.type === StatusEffectType.healthRegen && health)
43 if (entry.type === StatusEffectType.healthRegen && health)
44 {
44 {
45 const before = health.current | 0;
45 const beforeInt = health.current | 0;
46 health.current = Math.min(health.max | 0, (health.current | 0) + rate * dt);
46 const next = Math.min(health.max | 0, (Number(health.current) || 0) + rate * dt);
47 if ((health.current | 0) !== before)
47 health.current = next;
48 if ((next | 0) !== beforeInt)
48 { healthChanged = true; }
49 { healthChanged = true; }
49 }
50 }
50 if (entry.type === StatusEffectType.staminaRegen && stamina)
51 if (entry.type === StatusEffectType.staminaRegen && stamina)
server/src/world/coordinates.js +32 −10
@@ -1,4 +1,5 @@
1 1 import { CHUNK_SIZE, REGION_CHUNKS } from "../../../shared/protocol/constants.js";
2 import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2 3
3 4 export function floorDiv (value, divisor)
4 5 {
@@ -43,15 +44,25 @@ export function indexToLocal (index)
43 44 };
44 45 }
45 46
46 export function regionKey (regionX, regionY)
47 /** @param {string} [dimensionId] */
48 export function regionKey (regionX, regionY, dimensionId = OVERWORLD_ID)
47 49 {
48 return `${regionX},${regionY}`;
50 const dim = normalizeDimensionId(dimensionId);
51 return `${dim}|${regionX},${regionY}`;
49 52 }
50 53
51 54 export function parseRegionKey (key)
52 55 {
53 const [regionX, regionY] = key.split(",").map(Number);
54 return { regionX, regionY };
56 const raw = String(key ?? "");
57 const pipe = raw.indexOf("|");
58 if (pipe < 0)
59 {
60 const [regionX, regionY] = raw.split(",").map(Number);
61 return { dimensionId: OVERWORLD_ID, regionX, regionY };
62 }
63 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
64 const [regionX, regionY] = raw.slice(pipe + 1).split(",").map(Number);
65 return { dimensionId, regionX, regionY };
55 66 }
56 67
57 68 export function tileToRegion (tile)
@@ -100,20 +111,31 @@ export function visibleRegionCoords (regionX, regionY, radius = 1)
100 111 return coords;
101 112 }
102 113
103 export function chunkKey (chunkX, chunkY)
114 /** @param {string} [dimensionId] */
115 export function chunkKey (chunkX, chunkY, dimensionId = OVERWORLD_ID)
104 116 {
105 return `${chunkX},${chunkY}`;
117 const dim = normalizeDimensionId(dimensionId);
118 return `${dim}|${chunkX},${chunkY}`;
106 119 }
107 120
108 121 export function parseChunkKey (key)
109 122 {
110 const [chunkX, chunkY] = key.split(",").map(Number);
111 return { chunkX, chunkY };
123 const raw = String(key ?? "");
124 const pipe = raw.indexOf("|");
125 if (pipe < 0)
126 {
127 const [chunkX, chunkY] = raw.split(",").map(Number);
128 return { dimensionId: OVERWORLD_ID, chunkX, chunkY };
129 }
130 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
131 const [chunkX, chunkY] = raw.slice(pipe + 1).split(",").map(Number);
132 return { dimensionId, chunkX, chunkY };
112 133 }
113 134
114 export function tileKey (tileX, tileY)
135 export function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
115 136 {
116 return `${tileX},${tileY}`;
137 const dim = normalizeDimensionId(dimensionId);
138 return `${dim}|${tileX},${tileY}`;
117 139 }
118 140
119 141 export function visibleChunkCoords (chunkX, chunkY, radius = 1)
@@ -1,4 +1,5 @@
1import { CHUNK_SIZE, REGION_CHUNKS } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE, REGION_CHUNKS } from "../../../shared/protocol/constants.js";
2import { OVERWORLD_ID, normalizeDimensionId } from "../../../shared/world/dimensions.js";
2
3
3export function floorDiv (value, divisor)
4export function floorDiv (value, divisor)
4{
5{
@@ -43,15 +44,25 @@ export function indexToLocal (index)
43 };
44 };
44}
45}
45
46
46export function regionKey (regionX, regionY)
47/** @param {string} [dimensionId] */
48export function regionKey (regionX, regionY, dimensionId = OVERWORLD_ID)
47{
49{
48 return `${regionX},${regionY}`;
50 const dim = normalizeDimensionId(dimensionId);
51 return `${dim}|${regionX},${regionY}`;
49}
52}
50
53
51export function parseRegionKey (key)
54export function parseRegionKey (key)
52{
55{
53 const [regionX, regionY] = key.split(",").map(Number);
56 const raw = String(key ?? "");
54 return { regionX, regionY };
57 const pipe = raw.indexOf("|");
58 if (pipe < 0)
59 {
60 const [regionX, regionY] = raw.split(",").map(Number);
61 return { dimensionId: OVERWORLD_ID, regionX, regionY };
62 }
63 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
64 const [regionX, regionY] = raw.slice(pipe + 1).split(",").map(Number);
65 return { dimensionId, regionX, regionY };
55}
66}
56
67
57export function tileToRegion (tile)
68export function tileToRegion (tile)
@@ -100,20 +111,31 @@ export function visibleRegionCoords (regionX, regionY, radius = 1)
100 return coords;
111 return coords;
101}
112}
102
113
103export function chunkKey (chunkX, chunkY)
114/** @param {string} [dimensionId] */
115export function chunkKey (chunkX, chunkY, dimensionId = OVERWORLD_ID)
104{
116{
105 return `${chunkX},${chunkY}`;
117 const dim = normalizeDimensionId(dimensionId);
118 return `${dim}|${chunkX},${chunkY}`;
106}
119}
107
120
108export function parseChunkKey (key)
121export function parseChunkKey (key)
109{
122{
110 const [chunkX, chunkY] = key.split(",").map(Number);
123 const raw = String(key ?? "");
111 return { chunkX, chunkY };
124 const pipe = raw.indexOf("|");
125 if (pipe < 0)
126 {
127 const [chunkX, chunkY] = raw.split(",").map(Number);
128 return { dimensionId: OVERWORLD_ID, chunkX, chunkY };
129 }
130 const dimensionId = normalizeDimensionId(raw.slice(0, pipe));
131 const [chunkX, chunkY] = raw.slice(pipe + 1).split(",").map(Number);
132 return { dimensionId, chunkX, chunkY };
112}
133}
113
134
114export function tileKey (tileX, tileY)
135export function tileKey (tileX, tileY, dimensionId = OVERWORLD_ID)
115{
136{
116 return `${tileX},${tileY}`;
137 const dim = normalizeDimensionId(dimensionId);
138 return `${dim}|${tileX},${tileY}`;
117}
139}
118
140
119export function visibleChunkCoords (chunkX, chunkY, radius = 1)
141export function visibleChunkCoords (chunkX, chunkY, radius = 1)
server/tests/coordinates.test.js +8 −5
@@ -1,6 +1,7 @@
1 1 import test from "node:test";
2 2 import assert from "node:assert/strict";
3 3 import { CHUNK_SIZE, REGION_CHUNKS, DEFAULT_CHUNK_LOADER } from "../../shared/protocol/constants.js";
4 import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
4 5 import {
5 6 chunkKey,
6 7 chunkToRegion,
@@ -24,10 +25,12 @@ test("chunk and region sizes match the design", () =>
24 25 assert.equal(REGION_CHUNKS, 4);
25 26 assert.equal(tileToChunk(16), 1);
26 27 assert.equal(chunkToRegion(4), 1);
27 assert.equal(chunkKey(2, -3), "2,-3");
28 assert.equal(chunkKey(2, -3), `${OVERWORLD_ID}|2,-3`);
29 assert.equal(chunkKey(2, -3, "cave"), "cave|2,-3");
28 30 assert.equal(tileToRegion(64), 1);
29 31 assert.equal(tileToRegion(63), 0);
30 assert.equal(regionKey(-2, 3), "-2,3");
32 assert.equal(regionKey(-2, 3), `${OVERWORLD_ID}|-2,3`);
33 assert.equal(regionKey(-2, 3, "cave"), "cave|-2,3");
31 34 assert.deepEqual(chunksInRegion(1, 0).slice(0, 2), [
32 35 { chunkX: 4, chunkY: 0 },
33 36 { chunkX: 5, chunkY: 0 }
@@ -66,8 +69,8 @@ test("overlapping loaders share reference counts", () =>
66 69 { tileX: 8, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER },
67 70 { tileX: 9, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER }
68 71 ]);
69 assert.equal(chunkSim.get("0,0"), 2);
70 assert.equal(regionRes.get("0,0"), 2);
72 assert.equal(chunkSim.get(`${OVERWORLD_ID}|0,0`), 2);
73 assert.equal(regionRes.get(`${OVERWORLD_ID}|0,0`), 2);
71 74 });
72 75
73 76 test("global entity ids survive serialize and adopt on another world", () =>
@@ -80,6 +83,6 @@ test("global entity ids survive serialize and adopt on another world", () =>
80 83 const restored = deserializeEntity(dest, payload);
81 84 assert.equal(restored, 42);
82 85 assert.equal(dest.entityIdOf(dest.handleOf(42)), 42);
83 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4 });
86 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4, dimensionId: OVERWORLD_ID });
84 87 assert.equal(dest.entityIdOf(dest.entity()), 43);
85 88 });
@@ -1,6 +1,7 @@
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, DEFAULT_CHUNK_LOADER } from "../../shared/protocol/constants.js";
3import { CHUNK_SIZE, REGION_CHUNKS, DEFAULT_CHUNK_LOADER } from "../../shared/protocol/constants.js";
4import { OVERWORLD_ID } from "../../shared/world/dimensions.js";
4import {
5import {
5 chunkKey,
6 chunkKey,
6 chunkToRegion,
7 chunkToRegion,
@@ -24,10 +25,12 @@ test("chunk and region sizes match the design", () =>
24 assert.equal(REGION_CHUNKS, 4);
25 assert.equal(REGION_CHUNKS, 4);
25 assert.equal(tileToChunk(16), 1);
26 assert.equal(tileToChunk(16), 1);
26 assert.equal(chunkToRegion(4), 1);
27 assert.equal(chunkToRegion(4), 1);
27 assert.equal(chunkKey(2, -3), "2,-3");
28 assert.equal(chunkKey(2, -3), `${OVERWORLD_ID}|2,-3`);
29 assert.equal(chunkKey(2, -3, "cave"), "cave|2,-3");
28 assert.equal(tileToRegion(64), 1);
30 assert.equal(tileToRegion(64), 1);
29 assert.equal(tileToRegion(63), 0);
31 assert.equal(tileToRegion(63), 0);
30 assert.equal(regionKey(-2, 3), "-2,3");
32 assert.equal(regionKey(-2, 3), `${OVERWORLD_ID}|-2,3`);
33 assert.equal(regionKey(-2, 3, "cave"), "cave|-2,3");
31 assert.deepEqual(chunksInRegion(1, 0).slice(0, 2), [
34 assert.deepEqual(chunksInRegion(1, 0).slice(0, 2), [
32 { chunkX: 4, chunkY: 0 },
35 { chunkX: 4, chunkY: 0 },
33 { chunkX: 5, chunkY: 0 }
36 { chunkX: 5, chunkY: 0 }
@@ -66,8 +69,8 @@ test("overlapping loaders share reference counts", () =>
66 { tileX: 8, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER },
69 { tileX: 8, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER },
67 { tileX: 9, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER }
70 { tileX: 9, tileY: 8, chunkLoader: DEFAULT_CHUNK_LOADER }
68 ]);
71 ]);
69 assert.equal(chunkSim.get("0,0"), 2);
72 assert.equal(chunkSim.get(`${OVERWORLD_ID}|0,0`), 2);
70 assert.equal(regionRes.get("0,0"), 2);
73 assert.equal(regionRes.get(`${OVERWORLD_ID}|0,0`), 2);
71});
74});
72
75
73test("global entity ids survive serialize and adopt on another world", () =>
76test("global entity ids survive serialize and adopt on another world", () =>
@@ -80,6 +83,6 @@ test("global entity ids survive serialize and adopt on another world", () =>
80 const restored = deserializeEntity(dest, payload);
83 const restored = deserializeEntity(dest, payload);
81 assert.equal(restored, 42);
84 assert.equal(restored, 42);
82 assert.equal(dest.entityIdOf(dest.handleOf(42)), 42);
85 assert.equal(dest.entityIdOf(dest.handleOf(42)), 42);
83 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4 });
86 assert.deepEqual(dest.get(dest.handleOf(42), "position"), { tileX: 3, tileY: 4, dimensionId: OVERWORLD_ID });
84 assert.equal(dest.entityIdOf(dest.entity()), 43);
87 assert.equal(dest.entityIdOf(dest.entity()), 43);
85});
88});
server/tests/dimensions.test.js added +153 −0
@@ -0,0 +1,153 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync, rmSync } from "node:fs";
4 import { tmpdir } from "node:os";
5 import { join } from "node:path";
6 import { WorldDatabase } from "../src/persistence/worldDb.js";
7 import { StateDatabase } from "../src/persistence/stateDb.js";
8 import {
9 OVERWORLD_ID,
10 normalizeDimensionId,
11 resolveDimensionDarknessFactor,
12 resolveDimensionSeasonId,
13 DimensionLightingMode,
14 DimensionSeasonMode
15 } from "../../shared/world/dimensions.js";
16 import { ConditionKind, evaluateCondition, normalizeConditionSet } from "../../shared/quests/conditions.js";
17 import { chunkKey, parseChunkKey, regionKey, parseRegionKey } from "../src/world/coordinates.js";
18
19 test("dimension ids normalize to slugs", () =>
20 {
21 assert.equal(normalizeDimensionId("Cave One"), "cave-one");
22 assert.equal(normalizeDimensionId(""), OVERWORLD_ID);
23 });
24
25 test("chunk and region keys include dimension", () =>
26 {
27 assert.equal(chunkKey(2, -3), "overworld|2,-3");
28 assert.equal(chunkKey(0, 0, "cave_1"), "cave_1|0,0");
29 assert.deepEqual(parseChunkKey("cave_1|1,2"), { dimensionId: "cave_1", chunkX: 1, chunkY: 2 });
30 assert.equal(regionKey(0, 1, "house"), "house|0,1");
31 assert.deepEqual(parseRegionKey("house|0,1"), { dimensionId: "house", regionX: 0, regionY: 1 });
32 });
33
34 test("lighting and season resolve helpers", () =>
35 {
36 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysLit, 0.8), 0);
37 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysDark, 0.1), 1);
38 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.dayNight, 0.55), 0.55);
39 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.auto), null);
40 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "summer");
41 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.autumn), "fall");
42 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.winter), "winter");
43 });
44
45 test("worldDb dimensions and chunk PK migration", () =>
46 {
47 const dir = mkdtempSync(join(tmpdir(), "mmo-dim-"));
48 const db = new WorldDatabase(join(dir, "world.sqlite"));
49 try
50 {
51 const rev = db.getActiveRevisionId();
52 const overworld = db.getDimension(rev, OVERWORLD_ID);
53 assert.ok(overworld);
54 assert.equal(overworld.dimensionId, OVERWORLD_ID);
55
56 db.saveDimension(rev, {
57 dimensionId: "cave_a",
58 displayName: "Cave A",
59 lightingMode: DimensionLightingMode.alwaysDark,
60 seasonMode: DimensionSeasonMode.winter,
61 defaultGroundTypeId: 2
62 });
63 const cave = db.getDimension(rev, "cave_a");
64 assert.equal(cave.lightingMode, DimensionLightingMode.alwaysDark);
65 assert.equal(cave.defaultGroundTypeId, 2);
66
67 db.saveChunkVersion(0, 0, rev, true, JSON.stringify({ open: true, grounds: [], blocks: [], light: [], spawners: [] }), "cave_a");
68 const row = db.getChunkVersion(0, 0, rev, "cave_a");
69 assert.ok(row);
70 assert.equal(row.dimension_id, "cave_a");
71 assert.equal(db.getChunkVersion(0, 0, rev, OVERWORLD_ID), null);
72
73 const soft = db.softDeleteDimension(rev, "cave_a");
74 assert.equal(soft.ok, true);
75 assert.ok(soft.dimension.deletedAt);
76 const cancel = db.cancelDimensionDeletion(rev, "cave_a");
77 assert.equal(cancel.ok, true);
78 assert.equal(cancel.dimension.deletedAt, null);
79
80 assert.equal(db.softDeleteDimension(rev, OVERWORLD_ID).ok, false);
81 }
82 finally
83 {
84 db.close();
85 rmSync(dir, { recursive: true, force: true });
86 }
87 });
88
89 test("character dimension + visited persistence", () =>
90 {
91 const dir = mkdtempSync(join(tmpdir(), "mmo-state-dim-"));
92 const db = new StateDatabase(join(dir, "state.sqlite"));
93 try
94 {
95 const account = db.createAccount("subj-dim", false, "a@b.c");
96 const ch = db.createCharacter(account.account_id, "Ada", "Test", "female", 8, 8);
97 assert.equal(ch.dimension_id, OVERWORLD_ID);
98 db.saveCharacterPosition(ch.character_id, 10, 12, "walk", "cave_a");
99 const again = db.getCharacter(ch.character_id);
100 assert.equal(again.dimension_id, "cave_a");
101 assert.equal(again.tile_x, 10);
102 db.markDimensionVisited(ch.character_id, "cave_a");
103 assert.equal(db.hasVisitedDimension(ch.character_id, "cave_a"), true);
104 assert.equal(db.hasVisitedDimension(ch.character_id, "other"), false);
105 }
106 finally
107 {
108 db.close();
109 rmSync(dir, { recursive: true, force: true });
110 }
111 });
112
113 test("place conditions require matching dimension", () =>
114 {
115 const set = normalizeConditionSet({
116 all: [{ condition: { kind: ConditionKind.atTile, tileX: 5, tileY: 6 } }]
117 });
118 assert.equal(set.all[0].condition.dimensionId, OVERWORLD_ID);
119 const ctx = { tileX: 5, tileY: 6, dimensionId: OVERWORLD_ID };
120 assert.equal(evaluateCondition(set.all[0].condition, ctx), true);
121 assert.equal(evaluateCondition(set.all[0].condition, { ...ctx, dimensionId: "cave" }), false);
122
123 assert.equal(evaluateCondition(
124 { kind: ConditionKind.inDimension, dimensionId: "cave" },
125 { dimensionId: "cave" }
126 ), true);
127 assert.equal(evaluateCondition(
128 { kind: ConditionKind.hasVisitedDimension, dimensionId: "cave" },
129 { hasVisitedDimension: (id) => id === "cave" }
130 ), true);
131 });
132
133 test("purgeExpiredDimensions removes soft-deleted dims past purge_after", () =>
134 {
135 const dir = mkdtempSync(join(tmpdir(), "mmo-purge-"));
136 const db = new WorldDatabase(join(dir, "world.sqlite"));
137 try
138 {
139 const rev = db.getActiveRevisionId();
140 db.saveDimension(rev, { dimensionId: "old_cave", displayName: "Old" });
141 db.softDeleteDimension(rev, "old_cave", Date.now() - 8 * 24 * 60 * 60 * 1000);
142 db.saveChunkVersion(1, 1, rev, true, JSON.stringify({ open: true, grounds: [], blocks: [], light: [], spawners: [] }), "old_cave");
143 const purged = db.purgeExpiredDimensions(Date.now());
144 assert.ok(purged >= 1);
145 assert.equal(db.getDimension(rev, "old_cave"), null);
146 assert.equal(db.getChunkVersion(1, 1, rev, "old_cave"), null);
147 }
148 finally
149 {
150 db.close();
151 rmSync(dir, { recursive: true, force: true });
152 }
153 });
@@ -0,0 +1,153 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync, rmSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { WorldDatabase } from "../src/persistence/worldDb.js";
7import { StateDatabase } from "../src/persistence/stateDb.js";
8import {
9 OVERWORLD_ID,
10 normalizeDimensionId,
11 resolveDimensionDarknessFactor,
12 resolveDimensionSeasonId,
13 DimensionLightingMode,
14 DimensionSeasonMode
15} from "../../shared/world/dimensions.js";
16import { ConditionKind, evaluateCondition, normalizeConditionSet } from "../../shared/quests/conditions.js";
17import { chunkKey, parseChunkKey, regionKey, parseRegionKey } from "../src/world/coordinates.js";
18
19test("dimension ids normalize to slugs", () =>
20{
21 assert.equal(normalizeDimensionId("Cave One"), "cave-one");
22 assert.equal(normalizeDimensionId(""), OVERWORLD_ID);
23});
24
25test("chunk and region keys include dimension", () =>
26{
27 assert.equal(chunkKey(2, -3), "overworld|2,-3");
28 assert.equal(chunkKey(0, 0, "cave_1"), "cave_1|0,0");
29 assert.deepEqual(parseChunkKey("cave_1|1,2"), { dimensionId: "cave_1", chunkX: 1, chunkY: 2 });
30 assert.equal(regionKey(0, 1, "house"), "house|0,1");
31 assert.deepEqual(parseRegionKey("house|0,1"), { dimensionId: "house", regionX: 0, regionY: 1 });
32});
33
34test("lighting and season resolve helpers", () =>
35{
36 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysLit, 0.8), 0);
37 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.alwaysDark, 0.1), 1);
38 assert.equal(resolveDimensionDarknessFactor(DimensionLightingMode.dayNight, 0.55), 0.55);
39 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.auto), null);
40 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.spring), "summer");
41 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.autumn), "fall");
42 assert.equal(resolveDimensionSeasonId(DimensionSeasonMode.winter), "winter");
43});
44
45test("worldDb dimensions and chunk PK migration", () =>
46{
47 const dir = mkdtempSync(join(tmpdir(), "mmo-dim-"));
48 const db = new WorldDatabase(join(dir, "world.sqlite"));
49 try
50 {
51 const rev = db.getActiveRevisionId();
52 const overworld = db.getDimension(rev, OVERWORLD_ID);
53 assert.ok(overworld);
54 assert.equal(overworld.dimensionId, OVERWORLD_ID);
55
56 db.saveDimension(rev, {
57 dimensionId: "cave_a",
58 displayName: "Cave A",
59 lightingMode: DimensionLightingMode.alwaysDark,
60 seasonMode: DimensionSeasonMode.winter,
61 defaultGroundTypeId: 2
62 });
63 const cave = db.getDimension(rev, "cave_a");
64 assert.equal(cave.lightingMode, DimensionLightingMode.alwaysDark);
65 assert.equal(cave.defaultGroundTypeId, 2);
66
67 db.saveChunkVersion(0, 0, rev, true, JSON.stringify({ open: true, grounds: [], blocks: [], light: [], spawners: [] }), "cave_a");
68 const row = db.getChunkVersion(0, 0, rev, "cave_a");
69 assert.ok(row);
70 assert.equal(row.dimension_id, "cave_a");
71 assert.equal(db.getChunkVersion(0, 0, rev, OVERWORLD_ID), null);
72
73 const soft = db.softDeleteDimension(rev, "cave_a");
74 assert.equal(soft.ok, true);
75 assert.ok(soft.dimension.deletedAt);
76 const cancel = db.cancelDimensionDeletion(rev, "cave_a");
77 assert.equal(cancel.ok, true);
78 assert.equal(cancel.dimension.deletedAt, null);
79
80 assert.equal(db.softDeleteDimension(rev, OVERWORLD_ID).ok, false);
81 }
82 finally
83 {
84 db.close();
85 rmSync(dir, { recursive: true, force: true });
86 }
87});
88
89test("character dimension + visited persistence", () =>
90{
91 const dir = mkdtempSync(join(tmpdir(), "mmo-state-dim-"));
92 const db = new StateDatabase(join(dir, "state.sqlite"));
93 try
94 {
95 const account = db.createAccount("subj-dim", false, "a@b.c");
96 const ch = db.createCharacter(account.account_id, "Ada", "Test", "female", 8, 8);
97 assert.equal(ch.dimension_id, OVERWORLD_ID);
98 db.saveCharacterPosition(ch.character_id, 10, 12, "walk", "cave_a");
99 const again = db.getCharacter(ch.character_id);
100 assert.equal(again.dimension_id, "cave_a");
101 assert.equal(again.tile_x, 10);
102 db.markDimensionVisited(ch.character_id, "cave_a");
103 assert.equal(db.hasVisitedDimension(ch.character_id, "cave_a"), true);
104 assert.equal(db.hasVisitedDimension(ch.character_id, "other"), false);
105 }
106 finally
107 {
108 db.close();
109 rmSync(dir, { recursive: true, force: true });
110 }
111});
112
113test("place conditions require matching dimension", () =>
114{
115 const set = normalizeConditionSet({
116 all: [{ condition: { kind: ConditionKind.atTile, tileX: 5, tileY: 6 } }]
117 });
118 assert.equal(set.all[0].condition.dimensionId, OVERWORLD_ID);
119 const ctx = { tileX: 5, tileY: 6, dimensionId: OVERWORLD_ID };
120 assert.equal(evaluateCondition(set.all[0].condition, ctx), true);
121 assert.equal(evaluateCondition(set.all[0].condition, { ...ctx, dimensionId: "cave" }), false);
122
123 assert.equal(evaluateCondition(
124 { kind: ConditionKind.inDimension, dimensionId: "cave" },
125 { dimensionId: "cave" }
126 ), true);
127 assert.equal(evaluateCondition(
128 { kind: ConditionKind.hasVisitedDimension, dimensionId: "cave" },
129 { hasVisitedDimension: (id) => id === "cave" }
130 ), true);
131});
132
133test("purgeExpiredDimensions removes soft-deleted dims past purge_after", () =>
134{
135 const dir = mkdtempSync(join(tmpdir(), "mmo-purge-"));
136 const db = new WorldDatabase(join(dir, "world.sqlite"));
137 try
138 {
139 const rev = db.getActiveRevisionId();
140 db.saveDimension(rev, { dimensionId: "old_cave", displayName: "Old" });
141 db.softDeleteDimension(rev, "old_cave", Date.now() - 8 * 24 * 60 * 60 * 1000);
142 db.saveChunkVersion(1, 1, rev, true, JSON.stringify({ open: true, grounds: [], blocks: [], light: [], spawners: [] }), "old_cave");
143 const purged = db.purgeExpiredDimensions(Date.now());
144 assert.ok(purged >= 1);
145 assert.equal(db.getDimension(rev, "old_cave"), null);
146 assert.equal(db.getChunkVersion(1, 1, rev, "old_cave"), null);
147 }
148 finally
149 {
150 db.close();
151 rmSync(dir, { recursive: true, force: true });
152 }
153});
server/tests/mining.test.js +34 −4
@@ -138,8 +138,10 @@ test("iron pickaxe requires Mining 10", () =>
138 138 test("canMineMaterial enforces skill and tool tier", () =>
139 139 {
140 140 assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
141 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);
141 // One tier below is allowed once the Mining skill gate is met.
142 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, true);
142 143 assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
144 assert.equal(canMineMaterial(10, MaterialTier.bronze, MaterialTier.steel).ok, false);
143 145 });
144 146
145 147 test("mining without a pickaxe is rejected", () =>
@@ -195,7 +197,7 @@ test("plain boulder cannot be mined", () =>
195 197 { harness.close(); }
196 198 });
197 199
198 test("weak pickaxe cannot mine higher-tier ore", () =>
200 test("pickaxe two tiers below cannot mine the ore", () =>
199 201 {
200 202 const harness = makeSimulation({ workerCount: 1 });
201 203 try
@@ -205,8 +207,8 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
205 207 const record = harness.simulation.entityRecord(playerId);
206 208 const worker = harness.simulation.workers[record.workerId];
207 209 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
208 setSkillLevel(worker, playerId, SkillId.mining, 10);
209 placeOre(worker, 9, 8, "iron-ore");
210 setSkillLevel(worker, playerId, SkillId.mining, 20);
211 placeOre(worker, 9, 8, "coal");
210 212
211 213 harness.simulation.enqueue(1, {
212 214 type: "mine",
@@ -223,6 +225,34 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
223 225 { harness.close(); }
224 226 });
225 227
228 test("bronze pickaxe can mine iron ore (one tier below)", () =>
229 {
230 const harness = makeSimulation({ workerCount: 1 });
231 try
232 {
233 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
234 const playerId = harness.simulation.spawnCharacter(1, character);
235 const record = harness.simulation.entityRecord(playerId);
236 const worker = harness.simulation.workers[record.workerId];
237 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
238 setSkillLevel(worker, playerId, SkillId.mining, 10);
239 placeOre(worker, 9, 8, "iron-ore");
240
241 harness.simulation.enqueue(1, {
242 type: "mine",
243 characterId: character.character_id,
244 tileX: 9,
245 tileY: 8
246 });
247 const start = harness.simulation.step();
248 assert.ok(start.events.some((event) =>
249 event.type === "gather-swing"
250 && event.toolItemId === ItemId.bronzePickaxe), JSON.stringify(start.events));
251 }
252 finally
253 { harness.close(); }
254 });
255
226 256 test("mining uses the best pickaxe in inventory without equipping", () =>
227 257 {
228 258 const harness = makeSimulation({ workerCount: 1 });
@@ -138,8 +138,10 @@ test("iron pickaxe requires Mining 10", () =>
138test("canMineMaterial enforces skill and tool tier", () =>
138test("canMineMaterial enforces skill and tool tier", () =>
139{
139{
140 assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
140 assert.equal(canMineMaterial(1, MaterialTier.bronze, MaterialTier.iron).ok, false);
141 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, false);
141 // One tier below is allowed once the Mining skill gate is met.
142 assert.equal(canMineMaterial(5, MaterialTier.bronze, MaterialTier.iron).ok, true);
142 assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
143 assert.equal(canMineMaterial(5, MaterialTier.iron, MaterialTier.iron).ok, true);
144 assert.equal(canMineMaterial(10, MaterialTier.bronze, MaterialTier.steel).ok, false);
143});
145});
144
146
145test("mining without a pickaxe is rejected", () =>
147test("mining without a pickaxe is rejected", () =>
@@ -195,7 +197,7 @@ test("plain boulder cannot be mined", () =>
195 { harness.close(); }
197 { harness.close(); }
196});
198});
197
199
198test("weak pickaxe cannot mine higher-tier ore", () =>
200test("pickaxe two tiers below cannot mine the ore", () =>
199{
201{
200 const harness = makeSimulation({ workerCount: 1 });
202 const harness = makeSimulation({ workerCount: 1 });
201 try
203 try
@@ -205,8 +207,8 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
205 const record = harness.simulation.entityRecord(playerId);
207 const record = harness.simulation.entityRecord(playerId);
206 const worker = harness.simulation.workers[record.workerId];
208 const worker = harness.simulation.workers[record.workerId];
207 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
209 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
208 setSkillLevel(worker, playerId, SkillId.mining, 10);
210 setSkillLevel(worker, playerId, SkillId.mining, 20);
209 placeOre(worker, 9, 8, "iron-ore");
211 placeOre(worker, 9, 8, "coal");
210
212
211 harness.simulation.enqueue(1, {
213 harness.simulation.enqueue(1, {
212 type: "mine",
214 type: "mine",
@@ -223,6 +225,34 @@ test("weak pickaxe cannot mine higher-tier ore", () =>
223 { harness.close(); }
225 { harness.close(); }
224});
226});
225
227
228test("bronze pickaxe can mine iron ore (one tier below)", () =>
229{
230 const harness = makeSimulation({ workerCount: 1 });
231 try
232 {
233 const character = makeCharacter(harness.stateDb, { tileX: 8, tileY: 8 });
234 const playerId = harness.simulation.spawnCharacter(1, character);
235 const record = harness.simulation.entityRecord(playerId);
236 const worker = harness.simulation.workers[record.workerId];
237 bagPickaxe(worker, playerId, ItemId.bronzePickaxe);
238 setSkillLevel(worker, playerId, SkillId.mining, 10);
239 placeOre(worker, 9, 8, "iron-ore");
240
241 harness.simulation.enqueue(1, {
242 type: "mine",
243 characterId: character.character_id,
244 tileX: 9,
245 tileY: 8
246 });
247 const start = harness.simulation.step();
248 assert.ok(start.events.some((event) =>
249 event.type === "gather-swing"
250 && event.toolItemId === ItemId.bronzePickaxe), JSON.stringify(start.events));
251 }
252 finally
253 { harness.close(); }
254});
255
226test("mining uses the best pickaxe in inventory without equipping", () =>
256test("mining uses the best pickaxe in inventory without equipping", () =>
227{
257{
228 const harness = makeSimulation({ workerCount: 1 });
258 const harness = makeSimulation({ workerCount: 1 });
server/tests/origins.test.js +13 −0
@@ -5,6 +5,7 @@ import {
5 5 GatherOriginVerb,
6 6 CraftOriginVerb,
7 7 gatherOrigin,
8 lootOrigin,
8 9 craftOrigin,
9 10 craftOriginVerbForStation,
10 11 originLabel,
@@ -32,6 +33,18 @@ test("gathered origins use Mined by / Felled by labels", () =>
32 33 assert.equal(originLabel(gatherOrigin(GatherOriginVerb.felled, "Bob")), "Felled by Bob");
33 34 });
34 35
36 test("loot origins name the mob and killer", () =>
37 {
38 const origin = lootOrigin("Rat", "Ada Miner");
39 assert.equal(origin.kind, ItemOriginKind.loot);
40 assert.equal(originLabel(origin), "Dropped by Rat, slain by Ada Miner.");
41 assert.equal(formatOriginBreakdown({
42 itemId: ItemId.bones,
43 quantity: 1,
44 origins: [{ origin, quantity: 1 }]
45 }), "Dropped by Rat, slain by Ada Miner.");
46 });
47
35 48 test("craft origins use station verbs", () =>
36 49 {
37 50 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
@@ -5,6 +5,7 @@ import {
5 GatherOriginVerb,
5 GatherOriginVerb,
6 CraftOriginVerb,
6 CraftOriginVerb,
7 gatherOrigin,
7 gatherOrigin,
8 lootOrigin,
8 craftOrigin,
9 craftOrigin,
9 craftOriginVerbForStation,
10 craftOriginVerbForStation,
10 originLabel,
11 originLabel,
@@ -32,6 +33,18 @@ test("gathered origins use Mined by / Felled by labels", () =>
32 assert.equal(originLabel(gatherOrigin(GatherOriginVerb.felled, "Bob")), "Felled by Bob");
33 assert.equal(originLabel(gatherOrigin(GatherOriginVerb.felled, "Bob")), "Felled by Bob");
33});
34});
34
35
36test("loot origins name the mob and killer", () =>
37{
38 const origin = lootOrigin("Rat", "Ada Miner");
39 assert.equal(origin.kind, ItemOriginKind.loot);
40 assert.equal(originLabel(origin), "Dropped by Rat, slain by Ada Miner.");
41 assert.equal(formatOriginBreakdown({
42 itemId: ItemId.bones,
43 quantity: 1,
44 origins: [{ origin, quantity: 1 }]
45 }), "Dropped by Rat, slain by Ada Miner.");
46});
47
35test("craft origins use station verbs", () =>
48test("craft origins use station verbs", () =>
36{
49{
37 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
50 assert.equal(craftOriginVerbForStation(CraftingStationId.furnace), CraftOriginVerb.forged);
server/tests/quests-conditions.test.js added +52 −0
@@ -0,0 +1,52 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import {
4 evaluateConditionSet,
5 normalizeConditionSet,
6 ConditionKind
7 } from "../../shared/quests/conditions.js";
8 import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
9
10 test("ConditionSet AND + NOT", () =>
11 {
12 const set = normalizeConditionSet({
13 all: [
14 { condition: { kind: ConditionKind.hasItem, itemId: 1, quantity: 1 } },
15 { not: true, condition: { kind: ConditionKind.questState, questId: "q1", state: "completed" } }
16 ]
17 });
18 assert.equal(evaluateConditionSet(set, {
19 countItem: (id) => (id === 1 ? 2 : 0),
20 questState: () => "not-started"
21 }), true);
22 assert.equal(evaluateConditionSet(set, {
23 countItem: (id) => (id === 1 ? 2 : 0),
24 questState: () => "completed"
25 }), false);
26 });
27
28 test("normalize quest and dialogue", () =>
29 {
30 const quest = normalizeQuestDef({
31 questId: "Fetch Ore!",
32 title: "Fetch Ore",
33 steps: [{
34 objectives: [{ text: "Have tin", when: { all: [{ kind: "hasItem", itemId: 10, quantity: 1 }] } }]
35 }]
36 });
37 assert.equal(quest.questId, "fetch-ore");
38 assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
39
40 const tree = normalizeDialogueTree({
41 dialogueId: "Smith",
42 unique: true,
43 steps: [{
44 stepId: "hi",
45 lines: [{ speaker: "npc", text: "Hello" }],
46 exit: { kind: "end" }
47 }]
48 });
49 assert.equal(tree.dialogueId, "smith");
50 assert.equal(tree.unique, true);
51 assert.equal(tree.steps[0].exit.kind, "end");
52 });
@@ -0,0 +1,52 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import {
4 evaluateConditionSet,
5 normalizeConditionSet,
6 ConditionKind
7} from "../../shared/quests/conditions.js";
8import { normalizeQuestDef, normalizeDialogueTree } from "../../shared/quests/normalize.js";
9
10test("ConditionSet AND + NOT", () =>
11{
12 const set = normalizeConditionSet({
13 all: [
14 { condition: { kind: ConditionKind.hasItem, itemId: 1, quantity: 1 } },
15 { not: true, condition: { kind: ConditionKind.questState, questId: "q1", state: "completed" } }
16 ]
17 });
18 assert.equal(evaluateConditionSet(set, {
19 countItem: (id) => (id === 1 ? 2 : 0),
20 questState: () => "not-started"
21 }), true);
22 assert.equal(evaluateConditionSet(set, {
23 countItem: (id) => (id === 1 ? 2 : 0),
24 questState: () => "completed"
25 }), false);
26});
27
28test("normalize quest and dialogue", () =>
29{
30 const quest = normalizeQuestDef({
31 questId: "Fetch Ore!",
32 title: "Fetch Ore",
33 steps: [{
34 objectives: [{ text: "Have tin", when: { all: [{ kind: "hasItem", itemId: 10, quantity: 1 }] } }]
35 }]
36 });
37 assert.equal(quest.questId, "fetch-ore");
38 assert.equal(quest.steps[0].objectives[0].when.all[0].condition.kind, "hasItem");
39
40 const tree = normalizeDialogueTree({
41 dialogueId: "Smith",
42 unique: true,
43 steps: [{
44 stepId: "hi",
45 lines: [{ speaker: "npc", text: "Hello" }],
46 exit: { kind: "end" }
47 }]
48 });
49 assert.equal(tree.dialogueId, "smith");
50 assert.equal(tree.unique, true);
51 assert.equal(tree.steps[0].exit.kind, "end");
52});
server/tests/status-regen.test.js added +27 −0
@@ -0,0 +1,27 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { EcsWorld } from "../src/ecs/world.js";
4 import { Component } from "../src/ecs/components.js";
5 import { stepStatusEffects } from "../src/statusEffects/service.js";
6 import { applyStatusEffect, emptyStatusEffects, StatusEffectType } from "../../shared/statusEffects/rules.js";
7
8 test("health regen accumulates fractional HP across ticks", () =>
9 {
10 const ecs = new EcsWorld();
11 const entityId = 1;
12 const handle = ecs.spawn(entityId);
13 ecs.add(handle, Component.character, { characterId: 9 });
14 ecs.add(handle, Component.health, { current: 10, max: 100 });
15 const status = ecs.add(handle, Component.statusEffects, emptyStatusEffects());
16 applyStatusEffect(status, {
17 type: StatusEffectType.healthRegen,
18 amountPerSecond: 1,
19 durationMs: 60_000
20 }, 1_000_000);
21 const world = { ecs };
22 const dt = 1 / 20;
23 for (let i = 0; i < 20; i++)
24 { stepStatusEffects(world, 1_000_000 + i * 50, dt); }
25 const health = ecs.get(handle, Component.health);
26 assert.ok(health.current >= 10.9, `expected ~11 HP after 1s, got ${health.current}`);
27 });
@@ -0,0 +1,27 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { EcsWorld } from "../src/ecs/world.js";
4import { Component } from "../src/ecs/components.js";
5import { stepStatusEffects } from "../src/statusEffects/service.js";
6import { applyStatusEffect, emptyStatusEffects, StatusEffectType } from "../../shared/statusEffects/rules.js";
7
8test("health regen accumulates fractional HP across ticks", () =>
9{
10 const ecs = new EcsWorld();
11 const entityId = 1;
12 const handle = ecs.spawn(entityId);
13 ecs.add(handle, Component.character, { characterId: 9 });
14 ecs.add(handle, Component.health, { current: 10, max: 100 });
15 const status = ecs.add(handle, Component.statusEffects, emptyStatusEffects());
16 applyStatusEffect(status, {
17 type: StatusEffectType.healthRegen,
18 amountPerSecond: 1,
19 durationMs: 60_000
20 }, 1_000_000);
21 const world = { ecs };
22 const dt = 1 / 20;
23 for (let i = 0; i < 20; i++)
24 { stepStatusEffects(world, 1_000_000 + i * 50, dt); }
25 const health = ecs.get(handle, Component.health);
26 assert.ok(health.current >= 10.9, `expected ~11 HP after 1s, got ${health.current}`);
27});
server/tests/woodcutting.test.js +3 −0
@@ -66,7 +66,10 @@ test("pine tree yields pine logs and uses axe gates", () =>
66 66 assert.equal(logItemIdForWoodTier(WoodTier.pine), ItemId.pineLog);
67 67 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
68 68 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.pine).ok, true);
69 // Birch needs Woodcutting 10; tool may be one tier below once skill is met.
69 70 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.birch).ok, false);
71 assert.equal(canChopWood(10, WoodTier.pine, WoodTier.birch).ok, true);
72 assert.equal(canChopWood(10, WoodTier.pine, WoodTier.oak).ok, false);
70 73 assert.equal(woodcuttingDurationMs(WoodTier.pine, WoodTier.pine), 5000);
71 74 assert.equal(treeExhaustDurationMs(WoodTier.pine), 10_000);
72 75 });
@@ -66,7 +66,10 @@ test("pine tree yields pine logs and uses axe gates", () =>
66 assert.equal(logItemIdForWoodTier(WoodTier.pine), ItemId.pineLog);
66 assert.equal(logItemIdForWoodTier(WoodTier.pine), ItemId.pineLog);
67 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
67 assert.equal(itemDefinition(ItemId.bronzeAxe)?.equipment?.kind, "axeTool");
68 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.pine).ok, true);
68 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.pine).ok, true);
69 // Birch needs Woodcutting 10; tool may be one tier below once skill is met.
69 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.birch).ok, false);
70 assert.equal(canChopWood(1, WoodTier.pine, WoodTier.birch).ok, false);
71 assert.equal(canChopWood(10, WoodTier.pine, WoodTier.birch).ok, true);
72 assert.equal(canChopWood(10, WoodTier.pine, WoodTier.oak).ok, false);
70 assert.equal(woodcuttingDurationMs(WoodTier.pine, WoodTier.pine), 5000);
73 assert.equal(woodcuttingDurationMs(WoodTier.pine, WoodTier.pine), 5000);
71 assert.equal(treeExhaustDurationMs(WoodTier.pine), 10_000);
74 assert.equal(treeExhaustDurationMs(WoodTier.pine), 10_000);
72});
75});
server/tests/worker-lifecycle.test.js +4 −4
@@ -23,9 +23,9 @@ test("a player keeps nearby chunks simulating and surrounding regions resident",
23 23 const entityId = harness.simulation.spawnCharacter(1, character);
24 24 const debug = harness.simulation.debugWorld();
25 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"));
26 assert.ok(debug.simulatingChunks.includes("overworld|0,0"));
27 assert.ok(debug.simulatingChunks.includes("overworld|1,0"));
28 assert.ok(!debug.simulatingChunks.includes("overworld|3,0"));
29 29 assert.ok(debug.regions.some((region) => region.regionX === 0 && region.regionY === 0 && region.refs > 0));
30 30 assert.ok(debug.regions.some((region) => region.regionX === 1 && region.regionY === 0 && region.refs > 0));
31 31 assert.equal(entityOn(harness.simulation, entityId).workerId, 0);
@@ -46,7 +46,7 @@ test("dormant chunks do not simulate movement", () =>
46 46 movement: { gait: GAIT.walk, path: [{ x: 51, y: 8 }], walkCarry: 0 },
47 47 appearance: { sex: "male", firstName: "Ned", lastName: "Still" }
48 48 });
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("3,0"));
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("overworld|3,0"));
50 50 stepTimes(harness.simulation, walkTicks(4));
51 51 const npc = entityOn(harness.simulation, npcId);
52 52 assert.equal(npc.tileX, 50);
@@ -23,9 +23,9 @@ test("a player keeps nearby chunks simulating and surrounding regions resident",
23 const entityId = harness.simulation.spawnCharacter(1, character);
23 const entityId = harness.simulation.spawnCharacter(1, character);
24 const debug = harness.simulation.debugWorld();
24 const debug = harness.simulation.debugWorld();
25 assert.equal(debug.workerCount, 1);
25 assert.equal(debug.workerCount, 1);
26 assert.ok(debug.simulatingChunks.includes("0,0"));
26 assert.ok(debug.simulatingChunks.includes("overworld|0,0"));
27 assert.ok(debug.simulatingChunks.includes("1,0"));
27 assert.ok(debug.simulatingChunks.includes("overworld|1,0"));
28 assert.ok(!debug.simulatingChunks.includes("3,0"));
28 assert.ok(!debug.simulatingChunks.includes("overworld|3,0"));
29 assert.ok(debug.regions.some((region) => region.regionX === 0 && region.regionY === 0 && region.refs > 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));
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);
31 assert.equal(entityOn(harness.simulation, entityId).workerId, 0);
@@ -46,7 +46,7 @@ test("dormant chunks do not simulate movement", () =>
46 movement: { gait: GAIT.walk, path: [{ x: 51, y: 8 }], walkCarry: 0 },
46 movement: { gait: GAIT.walk, path: [{ x: 51, y: 8 }], walkCarry: 0 },
47 appearance: { sex: "male", firstName: "Ned", lastName: "Still" }
47 appearance: { sex: "male", firstName: "Ned", lastName: "Still" }
48 });
48 });
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("3,0"));
49 assert.ok(!harness.simulation.debugWorld().simulatingChunks.includes("overworld|3,0"));
50 stepTimes(harness.simulation, walkTicks(4));
50 stepTimes(harness.simulation, walkTicks(4));
51 const npc = entityOn(harness.simulation, npcId);
51 const npc = entityOn(harness.simulation, npcId);
52 assert.equal(npc.tileX, 50);
52 assert.equal(npc.tileX, 50);
shared/definitions/gathering.js +13 −4
@@ -121,7 +121,7 @@ export function canMineMaterial (miningLevel, toolTier, materialId)
121 121 {
122 122 return { ok: false, reason: `Requires Mining ${needSkill}.` };
123 123 }
124 if (tierRank(toolTier) < tierRank(gateTier))
124 if (!toolTierMeetsResource(toolTier, gateTier))
125 125 {
126 126 return { ok: false, reason: "You need a pickaxe to mine this!" };
127 127 }
@@ -135,13 +135,22 @@ export function canChopWood (woodcuttingLevel, toolTier, woodTier)
135 135 {
136 136 return { ok: false, reason: `Requires Woodcutting ${needSkill}.` };
137 137 }
138 if (tierRank(toolTier) < tierRank(woodTier))
138 if (!toolTierMeetsResource(toolTier, woodTier))
139 139 {
140 140 return { ok: false, reason: "You need an axe to chop this!" };
141 141 }
142 142 return { ok: true };
143 143 }
144 144
145 /**
146 * Gathering tools may be one material tier below the resource node.
147 * Pine/bronze (rank 1) still need a bronze tool; birch accepts bronze or iron, etc.
148 */
149 export function toolTierMeetsResource (toolTier, resourceTier)
150 {
151 return tierRank(toolTier) + 1 >= tierRank(resourceTier);
152 }
153
145 154 /**
146 155 * Tools of a given equipment kind in bag slots and/or the weapon slot.
147 156 * Gathering uses inventory tools without requiring them to be equipped.
@@ -183,7 +192,7 @@ export function resolveMiningPickaxe ({ inventorySlots, equipmentSlots, skills,
183 192 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.pickaxeTool);
184 193 const usable = tools
185 194 .filter((tool) => canEquipItem(skills, tool.def).ok)
186 .filter((tool) => tierRank(tool.tier) >= tierRank(gateTier))
195 .filter((tool) => toolTierMeetsResource(tool.tier, gateTier))
187 196 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
188 197
189 198 if (!usable.length)
@@ -205,7 +214,7 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
205 214 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.axeTool);
206 215 const usable = tools
207 216 .filter((tool) => canEquipItem(skills, tool.def).ok)
208 .filter((tool) => tierRank(tool.tier) >= tierRank(woodTier))
217 .filter((tool) => toolTierMeetsResource(tool.tier, woodTier))
209 218 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
210 219
211 220 if (!usable.length)
@@ -121,7 +121,7 @@ export function canMineMaterial (miningLevel, toolTier, materialId)
121 {
121 {
122 return { ok: false, reason: `Requires Mining ${needSkill}.` };
122 return { ok: false, reason: `Requires Mining ${needSkill}.` };
123 }
123 }
124 if (tierRank(toolTier) < tierRank(gateTier))
124 if (!toolTierMeetsResource(toolTier, gateTier))
125 {
125 {
126 return { ok: false, reason: "You need a pickaxe to mine this!" };
126 return { ok: false, reason: "You need a pickaxe to mine this!" };
127 }
127 }
@@ -135,13 +135,22 @@ export function canChopWood (woodcuttingLevel, toolTier, woodTier)
135 {
135 {
136 return { ok: false, reason: `Requires Woodcutting ${needSkill}.` };
136 return { ok: false, reason: `Requires Woodcutting ${needSkill}.` };
137 }
137 }
138 if (tierRank(toolTier) < tierRank(woodTier))
138 if (!toolTierMeetsResource(toolTier, woodTier))
139 {
139 {
140 return { ok: false, reason: "You need an axe to chop this!" };
140 return { ok: false, reason: "You need an axe to chop this!" };
141 }
141 }
142 return { ok: true };
142 return { ok: true };
143}
143}
144
144
145/**
146 * Gathering tools may be one material tier below the resource node.
147 * Pine/bronze (rank 1) still need a bronze tool; birch accepts bronze or iron, etc.
148 */
149export function toolTierMeetsResource (toolTier, resourceTier)
150{
151 return tierRank(toolTier) + 1 >= tierRank(resourceTier);
152}
153
145/**
154/**
146 * Tools of a given equipment kind in bag slots and/or the weapon slot.
155 * Tools of a given equipment kind in bag slots and/or the weapon slot.
147 * Gathering uses inventory tools without requiring them to be equipped.
156 * Gathering uses inventory tools without requiring them to be equipped.
@@ -183,7 +192,7 @@ export function resolveMiningPickaxe ({ inventorySlots, equipmentSlots, skills,
183 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.pickaxeTool);
192 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.pickaxeTool);
184 const usable = tools
193 const usable = tools
185 .filter((tool) => canEquipItem(skills, tool.def).ok)
194 .filter((tool) => canEquipItem(skills, tool.def).ok)
186 .filter((tool) => tierRank(tool.tier) >= tierRank(gateTier))
195 .filter((tool) => toolTierMeetsResource(tool.tier, gateTier))
187 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
196 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
188
197
189 if (!usable.length)
198 if (!usable.length)
@@ -205,7 +214,7 @@ export function resolveWoodcuttingAxe ({ inventorySlots, equipmentSlots, skills,
205 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.axeTool);
214 const tools = listGatherTools(inventorySlots, equipmentSlots, EquipmentKind.axeTool);
206 const usable = tools
215 const usable = tools
207 .filter((tool) => canEquipItem(skills, tool.def).ok)
216 .filter((tool) => canEquipItem(skills, tool.def).ok)
208 .filter((tool) => tierRank(tool.tier) >= tierRank(woodTier))
217 .filter((tool) => toolTierMeetsResource(tool.tier, woodTier))
209 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
218 .sort((a, b) => tierRank(b.tier) - tierRank(a.tier));
210
219
211 if (!usable.length)
220 if (!usable.length)
shared/definitions/mobs.js +6 −2
@@ -264,7 +264,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
264 264 buysItems: false,
265 265 hiddenDiscount: 0.9,
266 266 centralExchange,
267 townGuard
267 townGuard,
268 dialogueId: null
268 269 };
269 270 }
270 271
@@ -434,7 +435,10 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
434 435 buysItems: centralExchange ? false : !!merged.buysItems,
435 436 hiddenDiscount,
436 437 centralExchange,
437 townGuard
438 townGuard,
439 dialogueId: bodyNpc
440 ? (String(merged.dialogueId ?? "").trim().slice(0, 64) || null)
441 : null
438 442 };
439 443 }
440 444
@@ -264,7 +264,8 @@ export function defaultSpawnerConfig (spawnerId, mobTypeId = MobId.deer)
264 buysItems: false,
264 buysItems: false,
265 hiddenDiscount: 0.9,
265 hiddenDiscount: 0.9,
266 centralExchange,
266 centralExchange,
267 townGuard
267 townGuard,
268 dialogueId: null
268 };
269 };
269}
270}
270
271
@@ -434,7 +435,10 @@ export function normalizeSpawnerConfig (config, spawnerId = "spawner")
434 buysItems: centralExchange ? false : !!merged.buysItems,
435 buysItems: centralExchange ? false : !!merged.buysItems,
435 hiddenDiscount,
436 hiddenDiscount,
436 centralExchange,
437 centralExchange,
437 townGuard
438 townGuard,
439 dialogueId: bodyNpc
440 ? (String(merged.dialogueId ?? "").trim().slice(0, 64) || null)
441 : null
438 };
442 };
439}
443}
440
444
shared/definitions/tiles.js +18 −2
@@ -61,7 +61,8 @@ export const BlockType = Object.freeze({
61 61 lignumTree: 26,
62 62 heartwoodTree: 27,
63 63 elderTree: 28,
64 leatherworkingTable: 29
64 leatherworkingTable: 29,
65 doorway: 30
65 66 });
66 67
67 68 export const GROUND_DEFINITIONS = Object.freeze({
@@ -417,6 +418,21 @@ export const BLOCK_DEFINITIONS = Object.freeze({
417 418 animationSpeed: 0,
418 419 outdoor: false
419 420 }),
421 [BlockType.doorway]: Object.freeze({
422 id: BlockType.doorway,
423 key: "doorway",
424 displayName: "Doorway",
425 passable: true,
426 blocksLight: false,
427 lightRangeTiles: 0,
428 frames: 1,
429 framesPerRow: 1,
430 animationSpeed: 0,
431 outdoor: false,
432 /** Visual variants under `blocks/doorway/`. */
433 doorway: true,
434 defaultState: "door"
435 }),
420 436 [BlockType.herbPlant]: Object.freeze({
421 437 id: BlockType.herbPlant,
422 438 key: "herb",
@@ -607,7 +623,7 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
607 623 continue;
608 624 }
609 625 const states = catalog?.blocks?.[def.key]?.states ?? [];
610 const state = resolveState(states, null);
626 const state = resolveState(states, def.defaultState ?? null) ?? def.defaultState ?? null;
611 627 entries.push({
612 628 typeId: def.id,
613 629 state,
@@ -61,7 +61,8 @@ export const BlockType = Object.freeze({
61 lignumTree: 26,
61 lignumTree: 26,
62 heartwoodTree: 27,
62 heartwoodTree: 27,
63 elderTree: 28,
63 elderTree: 28,
64 leatherworkingTable: 29
64 leatherworkingTable: 29,
65 doorway: 30
65});
66});
66
67
67export const GROUND_DEFINITIONS = Object.freeze({
68export const GROUND_DEFINITIONS = Object.freeze({
@@ -417,6 +418,21 @@ export const BLOCK_DEFINITIONS = Object.freeze({
417 animationSpeed: 0,
418 animationSpeed: 0,
418 outdoor: false
419 outdoor: false
419 }),
420 }),
421 [BlockType.doorway]: Object.freeze({
422 id: BlockType.doorway,
423 key: "doorway",
424 displayName: "Doorway",
425 passable: true,
426 blocksLight: false,
427 lightRangeTiles: 0,
428 frames: 1,
429 framesPerRow: 1,
430 animationSpeed: 0,
431 outdoor: false,
432 /** Visual variants under `blocks/doorway/`. */
433 doorway: true,
434 defaultState: "door"
435 }),
420 [BlockType.herbPlant]: Object.freeze({
436 [BlockType.herbPlant]: Object.freeze({
421 id: BlockType.herbPlant,
437 id: BlockType.herbPlant,
422 key: "herb",
438 key: "herb",
@@ -607,7 +623,7 @@ export function listPlaceableBlockPaletteEntries (catalog = null)
607 continue;
623 continue;
608 }
624 }
609 const states = catalog?.blocks?.[def.key]?.states ?? [];
625 const states = catalog?.blocks?.[def.key]?.states ?? [];
610 const state = resolveState(states, null);
626 const state = resolveState(states, def.defaultState ?? null) ?? def.defaultState ?? null;
611 entries.push({
627 entries.push({
612 typeId: def.id,
628 typeId: def.id,
613 state,
629 state,
shared/items/origin.js +20 −0
@@ -3,6 +3,7 @@ export const ItemOriginKind = Object.freeze({
3 3 shop: "shop",
4 4 gathered: "gathered",
5 5 gods: "gods",
6 loot: "loot",
6 7 unknown: "unknown"
7 8 });
8 9
@@ -76,6 +77,15 @@ export function originLabel (origin, { lowercaseVerb = false } = {})
76 77 const name = origin.displayName?.trim() || "someone";
77 78 return `${verb} by ${name}`;
78 79 }
80 if (origin.kind === ItemOriginKind.loot)
81 {
82 const mob = origin.mobName?.trim() || "a creature";
83 const killer = origin.killerName?.trim() || "someone";
84 const label = `Dropped by ${mob}, slain by ${killer}.`;
85 if (!lowercaseVerb)
86 { return label; }
87 return label.charAt(0).toLowerCase() + label.slice(1);
88 }
79 89 if (origin.kind === ItemOriginKind.gods)
80 90 { return "Received from the gods"; }
81 91 return "unknown origin";
@@ -107,6 +117,16 @@ export function gatherOrigin (verb, displayName)
107 117 };
108 118 }
109 119
120 /** Build a mob-drop origin (`Dropped by Rat, slain by Ada.`). */
121 export function lootOrigin (mobName, killerName)
122 {
123 return {
124 kind: ItemOriginKind.loot,
125 mobName: String(mobName ?? "").trim() || "a creature",
126 killerName: String(killerName ?? "").trim() || "someone"
127 };
128 }
129
110 130 /** Starter gear granted at character creation. */
111 131 export function godsOrigin ()
112 132 {
@@ -3,6 +3,7 @@ export const ItemOriginKind = Object.freeze({
3 shop: "shop",
3 shop: "shop",
4 gathered: "gathered",
4 gathered: "gathered",
5 gods: "gods",
5 gods: "gods",
6 loot: "loot",
6 unknown: "unknown"
7 unknown: "unknown"
7});
8});
8
9
@@ -76,6 +77,15 @@ export function originLabel (origin, { lowercaseVerb = false } = {})
76 const name = origin.displayName?.trim() || "someone";
77 const name = origin.displayName?.trim() || "someone";
77 return `${verb} by ${name}`;
78 return `${verb} by ${name}`;
78 }
79 }
80 if (origin.kind === ItemOriginKind.loot)
81 {
82 const mob = origin.mobName?.trim() || "a creature";
83 const killer = origin.killerName?.trim() || "someone";
84 const label = `Dropped by ${mob}, slain by ${killer}.`;
85 if (!lowercaseVerb)
86 { return label; }
87 return label.charAt(0).toLowerCase() + label.slice(1);
88 }
79 if (origin.kind === ItemOriginKind.gods)
89 if (origin.kind === ItemOriginKind.gods)
80 { return "Received from the gods"; }
90 { return "Received from the gods"; }
81 return "unknown origin";
91 return "unknown origin";
@@ -107,6 +117,16 @@ export function gatherOrigin (verb, displayName)
107 };
117 };
108}
118}
109
119
120/** Build a mob-drop origin (`Dropped by Rat, slain by Ada.`). */
121export function lootOrigin (mobName, killerName)
122{
123 return {
124 kind: ItemOriginKind.loot,
125 mobName: String(mobName ?? "").trim() || "a creature",
126 killerName: String(killerName ?? "").trim() || "someone"
127 };
128}
129
110/** Starter gear granted at character creation. */
130/** Starter gear granted at character creation. */
111export function godsOrigin ()
131export function godsOrigin ()
112{
132{
shared/protocol/constants.js +27 −1
@@ -141,6 +141,8 @@ export const MessageType = Object.freeze({
141 141 attack: "ATTACK",
142 142 cancelAttack: "CANCEL_ATTACK",
143 143 interact: "INTERACT",
144 enterDoorway: "ENTER_DOORWAY",
145 dimensionChanged: "DIMENSION_CHANGED",
144 146 combatSwing: "COMBAT_SWING",
145 147 combatHit: "COMBAT_HIT",
146 148 combatMiss: "COMBAT_MISS",
@@ -224,6 +226,30 @@ export const MessageType = Object.freeze({
224 226 spellLightAppear: "SPELL_LIGHT_APPEAR",
225 227 spellLightUpdate: "SPELL_LIGHT_UPDATE",
226 228 spellLightRemove: "SPELL_LIGHT_REMOVE",
227 toast: "TOAST"
229 toast: "TOAST",
230 editorLoadQuests: "EDITOR_LOAD_QUESTS",
231 editorQuests: "EDITOR_QUESTS",
232 editorSaveQuest: "EDITOR_SAVE_QUEST",
233 editorDeleteQuest: "EDITOR_DELETE_QUEST",
234 editorLoadDialogues: "EDITOR_LOAD_DIALOGUES",
235 editorDialogues: "EDITOR_DIALOGUES",
236 editorSaveDialogue: "EDITOR_SAVE_DIALOGUE",
237 editorDeleteDialogue: "EDITOR_DELETE_DIALOGUE",
238 editorListDimensions: "EDITOR_LIST_DIMENSIONS",
239 editorDimensions: "EDITOR_DIMENSIONS",
240 editorCreateDimension: "EDITOR_CREATE_DIMENSION",
241 editorSaveDimension: "EDITOR_SAVE_DIMENSION",
242 editorSoftDeleteDimension: "EDITOR_SOFT_DELETE_DIMENSION",
243 editorCancelDimensionDeletion: "EDITOR_CANCEL_DIMENSION_DELETION",
244 dialogueOpen: "DIALOGUE_OPEN",
245 dialogueStep: "DIALOGUE_STEP",
246 dialogueClose: "DIALOGUE_CLOSE",
247 dialogueChoose: "DIALOGUE_CHOOSE",
248 dialogueAdvance: "DIALOGUE_ADVANCE",
249 closeDialogue: "CLOSE_DIALOGUE",
250 dialogueChoices: "DIALOGUE_CHOICES",
251 requestQuests: "REQUEST_QUESTS",
252 questsSnapshot: "QUESTS_SNAPSHOT",
253 questStepComplete: "QUEST_STEP_COMPLETE"
228 254 });
229 255
@@ -141,6 +141,8 @@ export const MessageType = Object.freeze({
141 attack: "ATTACK",
141 attack: "ATTACK",
142 cancelAttack: "CANCEL_ATTACK",
142 cancelAttack: "CANCEL_ATTACK",
143 interact: "INTERACT",
143 interact: "INTERACT",
144 enterDoorway: "ENTER_DOORWAY",
145 dimensionChanged: "DIMENSION_CHANGED",
144 combatSwing: "COMBAT_SWING",
146 combatSwing: "COMBAT_SWING",
145 combatHit: "COMBAT_HIT",
147 combatHit: "COMBAT_HIT",
146 combatMiss: "COMBAT_MISS",
148 combatMiss: "COMBAT_MISS",
@@ -224,6 +226,30 @@ export const MessageType = Object.freeze({
224 spellLightAppear: "SPELL_LIGHT_APPEAR",
226 spellLightAppear: "SPELL_LIGHT_APPEAR",
225 spellLightUpdate: "SPELL_LIGHT_UPDATE",
227 spellLightUpdate: "SPELL_LIGHT_UPDATE",
226 spellLightRemove: "SPELL_LIGHT_REMOVE",
228 spellLightRemove: "SPELL_LIGHT_REMOVE",
227 toast: "TOAST"
229 toast: "TOAST",
230 editorLoadQuests: "EDITOR_LOAD_QUESTS",
231 editorQuests: "EDITOR_QUESTS",
232 editorSaveQuest: "EDITOR_SAVE_QUEST",
233 editorDeleteQuest: "EDITOR_DELETE_QUEST",
234 editorLoadDialogues: "EDITOR_LOAD_DIALOGUES",
235 editorDialogues: "EDITOR_DIALOGUES",
236 editorSaveDialogue: "EDITOR_SAVE_DIALOGUE",
237 editorDeleteDialogue: "EDITOR_DELETE_DIALOGUE",
238 editorListDimensions: "EDITOR_LIST_DIMENSIONS",
239 editorDimensions: "EDITOR_DIMENSIONS",
240 editorCreateDimension: "EDITOR_CREATE_DIMENSION",
241 editorSaveDimension: "EDITOR_SAVE_DIMENSION",
242 editorSoftDeleteDimension: "EDITOR_SOFT_DELETE_DIMENSION",
243 editorCancelDimensionDeletion: "EDITOR_CANCEL_DIMENSION_DELETION",
244 dialogueOpen: "DIALOGUE_OPEN",
245 dialogueStep: "DIALOGUE_STEP",
246 dialogueClose: "DIALOGUE_CLOSE",
247 dialogueChoose: "DIALOGUE_CHOOSE",
248 dialogueAdvance: "DIALOGUE_ADVANCE",
249 closeDialogue: "CLOSE_DIALOGUE",
250 dialogueChoices: "DIALOGUE_CHOICES",
251 requestQuests: "REQUEST_QUESTS",
252 questsSnapshot: "QUESTS_SNAPSHOT",
253 questStepComplete: "QUEST_STEP_COMPLETE"
228});
254});
229
255
shared/quests/conditions.js added +224 −0
@@ -0,0 +1,224 @@
1 /** Shared condition kinds + ConditionSet evaluation (server provides snapshot). */
2
3 import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
4
5 export const ConditionKind = Object.freeze({
6 hasItem: "hasItem",
7 atTile: "atTile",
8 nearTile: "nearTile",
9 inRect: "inRect",
10 atChunk: "atChunk",
11 inDimension: "inDimension",
12 hasVisitedDimension: "hasVisitedDimension",
13 questState: "questState",
14 questStepAtLeast: "questStepAtLeast",
15 dialogueHeard: "dialogueHeard",
16 dialogueTrigger: "dialogueTrigger",
17 hpAtLeast: "hpAtLeast",
18 staminaAtLeast: "staminaAtLeast",
19 hpPercentAtLeast: "hpPercentAtLeast",
20 staminaPercentAtLeast: "staminaPercentAtLeast",
21 skillLevelAtLeast: "skillLevelAtLeast",
22 killCount: "killCount",
23 interactBlock: "interactBlock"
24 });
25
26 export function emptyConditionSet ()
27 {
28 return { all: [] };
29 }
30
31 export function normalizeConditionSet (raw)
32 {
33 const all = [];
34 const list = Array.isArray(raw?.all) ? raw.all : (Array.isArray(raw) ? raw : []);
35 for (const entry of list)
36 {
37 const clause = normalizeConditionClause(entry);
38 if (clause)
39 { all.push(clause); }
40 }
41 return { all };
42 }
43
44 function normalizeConditionClause (entry)
45 {
46 if (!entry || typeof entry !== "object")
47 { return null; }
48 const condition = entry.condition && typeof entry.condition === "object"
49 ? entry.condition
50 : entry;
51 const kind = String(condition.kind ?? "").trim();
52 if (!kind)
53 { return null; }
54 return {
55 not: !!entry.not,
56 condition: normalizeConditionFields({ ...condition, kind })
57 };
58 }
59
60 /** Ensure place conditions carry dimensionId (default overworld). */
61 function normalizeConditionFields (condition)
62 {
63 const kind = condition.kind;
64 if (
65 kind === ConditionKind.atTile
66 || kind === ConditionKind.nearTile
67 || kind === ConditionKind.inRect
68 || kind === ConditionKind.atChunk
69 || kind === ConditionKind.interactBlock
70 || kind === ConditionKind.inDimension
71 || kind === ConditionKind.hasVisitedDimension
72 )
73 {
74 return {
75 ...condition,
76 dimensionId: normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
77 };
78 }
79 return condition;
80 }
81
82 /**
83 * @param {ReturnType<typeof normalizeConditionSet>} set
84 * @param {object} ctx — snapshot from server (see evaluateCondition)
85 */
86 export function evaluateConditionSet (set, ctx)
87 {
88 const clauses = set?.all ?? [];
89 if (clauses.length === 0)
90 { return true; }
91 for (const clause of clauses)
92 {
93 const raw = evaluateCondition(clause.condition, ctx);
94 const ok = clause.not ? !raw : raw;
95 if (!ok)
96 { return false; }
97 }
98 return true;
99 }
100
101 function sameDimension (condition, ctx)
102 {
103 const want = normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID);
104 const have = normalizeDimensionId(ctx.dimensionId ?? OVERWORLD_ID);
105 return want === have;
106 }
107
108 export function evaluateCondition (condition, ctx)
109 {
110 if (!condition || typeof condition !== "object")
111 { return false; }
112 const kind = condition.kind;
113 switch (kind)
114 {
115 case ConditionKind.hasItem:
116 return (ctx.countItem?.(condition.itemId) ?? 0) >= Math.max(1, Number(condition.quantity) || 1);
117 case ConditionKind.atTile:
118 return sameDimension(condition, ctx)
119 && ctx.tileX === (Number(condition.tileX) | 0)
120 && ctx.tileY === (Number(condition.tileY) | 0);
121 case ConditionKind.nearTile:
122 {
123 if (!sameDimension(condition, ctx))
124 { return false; }
125 const range = Math.max(1, Number(condition.range) || 1);
126 const dx = Math.abs(ctx.tileX - (Number(condition.tileX) | 0));
127 const dy = Math.abs(ctx.tileY - (Number(condition.tileY) | 0));
128 return Math.max(dx, dy) <= range;
129 }
130 case ConditionKind.inRect:
131 {
132 if (!sameDimension(condition, ctx))
133 { return false; }
134 const minX = Math.min(Number(condition.minTileX) | 0, Number(condition.maxTileX) | 0);
135 const maxX = Math.max(Number(condition.minTileX) | 0, Number(condition.maxTileX) | 0);
136 const minY = Math.min(Number(condition.minTileY) | 0, Number(condition.maxTileY) | 0);
137 const maxY = Math.max(Number(condition.minTileY) | 0, Number(condition.maxTileY) | 0);
138 return ctx.tileX >= minX && ctx.tileX <= maxX && ctx.tileY >= minY && ctx.tileY <= maxY;
139 }
140 case ConditionKind.atChunk:
141 return sameDimension(condition, ctx)
142 && ctx.chunkX === (Number(condition.chunkX) | 0)
143 && ctx.chunkY === (Number(condition.chunkY) | 0);
144 case ConditionKind.inDimension:
145 return normalizeDimensionId(ctx.dimensionId ?? OVERWORLD_ID)
146 === normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID);
147 case ConditionKind.hasVisitedDimension:
148 return !!ctx.hasVisitedDimension?.(
149 normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
150 );
151 case ConditionKind.questState:
152 return questStatesEqual(ctx.questState?.(condition.questId), condition.state);
153 case ConditionKind.questStepAtLeast:
154 {
155 const state = ctx.questState?.(condition.questId);
156 const step = Math.max(1, Number(condition.step) || 1);
157 if (state === "completed")
158 { return true; }
159 if (typeof state === "number")
160 { return state >= step; }
161 return false;
162 }
163 case ConditionKind.dialogueHeard:
164 return !!ctx.dialogueHeard?.(condition.dialogueId, condition.stepId);
165 case ConditionKind.dialogueTrigger:
166 return !!ctx.dialogueTriggerLatched?.(condition.dialogueId, condition.trigger);
167 case ConditionKind.hpAtLeast:
168 return (ctx.hp ?? 0) >= Math.max(0, Number(condition.amount) || 0);
169 case ConditionKind.staminaAtLeast:
170 return (ctx.stamina ?? 0) >= Math.max(0, Number(condition.amount) || 0);
171 case ConditionKind.hpPercentAtLeast:
172 {
173 const max = Math.max(1, ctx.maxHp ?? 1);
174 const pct = ((ctx.hp ?? 0) / max) * 100;
175 return pct >= Math.min(100, Math.max(0, Number(condition.percent) || 0));
176 }
177 case ConditionKind.staminaPercentAtLeast:
178 {
179 const max = Math.max(1, ctx.maxStamina ?? 1);
180 const pct = ((ctx.stamina ?? 0) / max) * 100;
181 return pct >= Math.min(100, Math.max(0, Number(condition.percent) || 0));
182 }
183 case ConditionKind.skillLevelAtLeast:
184 return (ctx.skillLevel?.(condition.skillId) ?? 1) >= Math.max(1, Math.min(99, Number(condition.level) || 1));
185 case ConditionKind.killCount:
186 return (ctx.killCount?.(condition) ?? 0) >= Math.max(1, Number(condition.count) || 1);
187 case ConditionKind.interactBlock:
188 return sameDimension(condition, ctx) && !!ctx.interactBlockDone?.(condition);
189 default:
190 return false;
191 }
192 }
193
194 function questStatesEqual (actual, expected)
195 {
196 if (expected === "not-started" || expected === "completed")
197 { return actual === expected || (expected === "not-started" && (actual == null || actual === "not-started")); }
198 const n = Number(expected);
199 return Number.isFinite(n) && actual === (n | 0);
200 }
201
202 export const EffectKind = Object.freeze({
203 giveItem: "giveItem",
204 giveXp: "giveXp",
205 takeItem: "takeItem",
206 startQuest: "startQuest"
207 });
208
209 export function normalizeEffects (raw)
210 {
211 if (!Array.isArray(raw))
212 { return []; }
213 const out = [];
214 for (const entry of raw)
215 {
216 if (!entry || typeof entry !== "object")
217 { continue; }
218 const kind = String(entry.kind ?? "").trim();
219 if (!Object.values(EffectKind).includes(kind))
220 { continue; }
221 out.push({ ...entry, kind });
222 }
223 return out;
224 }
@@ -0,0 +1,224 @@
1/** Shared condition kinds + ConditionSet evaluation (server provides snapshot). */
2
3import { OVERWORLD_ID, normalizeDimensionId } from "../world/dimensions.js";
4
5export const ConditionKind = Object.freeze({
6 hasItem: "hasItem",
7 atTile: "atTile",
8 nearTile: "nearTile",
9 inRect: "inRect",
10 atChunk: "atChunk",
11 inDimension: "inDimension",
12 hasVisitedDimension: "hasVisitedDimension",
13 questState: "questState",
14 questStepAtLeast: "questStepAtLeast",
15 dialogueHeard: "dialogueHeard",
16 dialogueTrigger: "dialogueTrigger",
17 hpAtLeast: "hpAtLeast",
18 staminaAtLeast: "staminaAtLeast",
19 hpPercentAtLeast: "hpPercentAtLeast",
20 staminaPercentAtLeast: "staminaPercentAtLeast",
21 skillLevelAtLeast: "skillLevelAtLeast",
22 killCount: "killCount",
23 interactBlock: "interactBlock"
24});
25
26export function emptyConditionSet ()
27{
28 return { all: [] };
29}
30
31export function normalizeConditionSet (raw)
32{
33 const all = [];
34 const list = Array.isArray(raw?.all) ? raw.all : (Array.isArray(raw) ? raw : []);
35 for (const entry of list)
36 {
37 const clause = normalizeConditionClause(entry);
38 if (clause)
39 { all.push(clause); }
40 }
41 return { all };
42}
43
44function normalizeConditionClause (entry)
45{
46 if (!entry || typeof entry !== "object")
47 { return null; }
48 const condition = entry.condition && typeof entry.condition === "object"
49 ? entry.condition
50 : entry;
51 const kind = String(condition.kind ?? "").trim();
52 if (!kind)
53 { return null; }
54 return {
55 not: !!entry.not,
56 condition: normalizeConditionFields({ ...condition, kind })
57 };
58}
59
60/** Ensure place conditions carry dimensionId (default overworld). */
61function normalizeConditionFields (condition)
62{
63 const kind = condition.kind;
64 if (
65 kind === ConditionKind.atTile
66 || kind === ConditionKind.nearTile
67 || kind === ConditionKind.inRect
68 || kind === ConditionKind.atChunk
69 || kind === ConditionKind.interactBlock
70 || kind === ConditionKind.inDimension
71 || kind === ConditionKind.hasVisitedDimension
72 )
73 {
74 return {
75 ...condition,
76 dimensionId: normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
77 };
78 }
79 return condition;
80}
81
82/**
83 * @param {ReturnType<typeof normalizeConditionSet>} set
84 * @param {object} ctx — snapshot from server (see evaluateCondition)
85 */
86export function evaluateConditionSet (set, ctx)
87{
88 const clauses = set?.all ?? [];
89 if (clauses.length === 0)
90 { return true; }
91 for (const clause of clauses)
92 {
93 const raw = evaluateCondition(clause.condition, ctx);
94 const ok = clause.not ? !raw : raw;
95 if (!ok)
96 { return false; }
97 }
98 return true;
99}
100
101function sameDimension (condition, ctx)
102{
103 const want = normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID);
104 const have = normalizeDimensionId(ctx.dimensionId ?? OVERWORLD_ID);
105 return want === have;
106}
107
108export function evaluateCondition (condition, ctx)
109{
110 if (!condition || typeof condition !== "object")
111 { return false; }
112 const kind = condition.kind;
113 switch (kind)
114 {
115 case ConditionKind.hasItem:
116 return (ctx.countItem?.(condition.itemId) ?? 0) >= Math.max(1, Number(condition.quantity) || 1);
117 case ConditionKind.atTile:
118 return sameDimension(condition, ctx)
119 && ctx.tileX === (Number(condition.tileX) | 0)
120 && ctx.tileY === (Number(condition.tileY) | 0);
121 case ConditionKind.nearTile:
122 {
123 if (!sameDimension(condition, ctx))
124 { return false; }
125 const range = Math.max(1, Number(condition.range) || 1);
126 const dx = Math.abs(ctx.tileX - (Number(condition.tileX) | 0));
127 const dy = Math.abs(ctx.tileY - (Number(condition.tileY) | 0));
128 return Math.max(dx, dy) <= range;
129 }
130 case ConditionKind.inRect:
131 {
132 if (!sameDimension(condition, ctx))
133 { return false; }
134 const minX = Math.min(Number(condition.minTileX) | 0, Number(condition.maxTileX) | 0);
135 const maxX = Math.max(Number(condition.minTileX) | 0, Number(condition.maxTileX) | 0);
136 const minY = Math.min(Number(condition.minTileY) | 0, Number(condition.maxTileY) | 0);
137 const maxY = Math.max(Number(condition.minTileY) | 0, Number(condition.maxTileY) | 0);
138 return ctx.tileX >= minX && ctx.tileX <= maxX && ctx.tileY >= minY && ctx.tileY <= maxY;
139 }
140 case ConditionKind.atChunk:
141 return sameDimension(condition, ctx)
142 && ctx.chunkX === (Number(condition.chunkX) | 0)
143 && ctx.chunkY === (Number(condition.chunkY) | 0);
144 case ConditionKind.inDimension:
145 return normalizeDimensionId(ctx.dimensionId ?? OVERWORLD_ID)
146 === normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID);
147 case ConditionKind.hasVisitedDimension:
148 return !!ctx.hasVisitedDimension?.(
149 normalizeDimensionId(condition.dimensionId ?? OVERWORLD_ID)
150 );
151 case ConditionKind.questState:
152 return questStatesEqual(ctx.questState?.(condition.questId), condition.state);
153 case ConditionKind.questStepAtLeast:
154 {
155 const state = ctx.questState?.(condition.questId);
156 const step = Math.max(1, Number(condition.step) || 1);
157 if (state === "completed")
158 { return true; }
159 if (typeof state === "number")
160 { return state >= step; }
161 return false;
162 }
163 case ConditionKind.dialogueHeard:
164 return !!ctx.dialogueHeard?.(condition.dialogueId, condition.stepId);
165 case ConditionKind.dialogueTrigger:
166 return !!ctx.dialogueTriggerLatched?.(condition.dialogueId, condition.trigger);
167 case ConditionKind.hpAtLeast:
168 return (ctx.hp ?? 0) >= Math.max(0, Number(condition.amount) || 0);
169 case ConditionKind.staminaAtLeast:
170 return (ctx.stamina ?? 0) >= Math.max(0, Number(condition.amount) || 0);
171 case ConditionKind.hpPercentAtLeast:
172 {
173 const max = Math.max(1, ctx.maxHp ?? 1);
174 const pct = ((ctx.hp ?? 0) / max) * 100;
175 return pct >= Math.min(100, Math.max(0, Number(condition.percent) || 0));
176 }
177 case ConditionKind.staminaPercentAtLeast:
178 {
179 const max = Math.max(1, ctx.maxStamina ?? 1);
180 const pct = ((ctx.stamina ?? 0) / max) * 100;
181 return pct >= Math.min(100, Math.max(0, Number(condition.percent) || 0));
182 }
183 case ConditionKind.skillLevelAtLeast:
184 return (ctx.skillLevel?.(condition.skillId) ?? 1) >= Math.max(1, Math.min(99, Number(condition.level) || 1));
185 case ConditionKind.killCount:
186 return (ctx.killCount?.(condition) ?? 0) >= Math.max(1, Number(condition.count) || 1);
187 case ConditionKind.interactBlock:
188 return sameDimension(condition, ctx) && !!ctx.interactBlockDone?.(condition);
189 default:
190 return false;
191 }
192}
193
194function questStatesEqual (actual, expected)
195{
196 if (expected === "not-started" || expected === "completed")
197 { return actual === expected || (expected === "not-started" && (actual == null || actual === "not-started")); }
198 const n = Number(expected);
199 return Number.isFinite(n) && actual === (n | 0);
200}
201
202export const EffectKind = Object.freeze({
203 giveItem: "giveItem",
204 giveXp: "giveXp",
205 takeItem: "takeItem",
206 startQuest: "startQuest"
207});
208
209export function normalizeEffects (raw)
210{
211 if (!Array.isArray(raw))
212 { return []; }
213 const out = [];
214 for (const entry of raw)
215 {
216 if (!entry || typeof entry !== "object")
217 { continue; }
218 const kind = String(entry.kind ?? "").trim();
219 if (!Object.values(EffectKind).includes(kind))
220 { continue; }
221 out.push({ ...entry, kind });
222 }
223 return out;
224}
shared/quests/normalize.js added +188 −0
@@ -0,0 +1,188 @@
1 import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
2
3 export function normalizeQuestDef (raw)
4 {
5 const questId = slugId(raw?.questId ?? raw?.id, "quest");
6 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
7 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index)).filter(Boolean);
8 return {
9 questId,
10 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
11 description: String(raw?.description ?? "").trim().slice(0, 500),
12 steps: steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0)],
13 rewards: normalizeEffects(raw?.rewards),
14 cancelable: !!raw?.cancelable
15 };
16 }
17
18 function normalizeQuestStep (raw, index)
19 {
20 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
21 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
22 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i)).filter(Boolean);
23 if (objectives.length === 0)
24 {
25 objectives = [normalizeObjective({
26 objectiveId: "obj-1",
27 text: "Complete this step",
28 when: emptyConditionSet()
29 }, 0)];
30 }
31 return {
32 stepId,
33 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
34 description: String(raw?.description ?? "").trim().slice(0, 500),
35 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
36 objectives,
37 onEnter: normalizeEffects(raw?.onEnter),
38 onComplete: normalizeEffects(raw?.onComplete)
39 };
40 }
41
42 function normalizeObjective (raw, index)
43 {
44 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
45 const when = normalizeConditionSet(raw?.when ?? raw?.require);
46 return {
47 objectiveId,
48 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
49 when
50 };
51 }
52
53 export function normalizeDialogueTree (raw)
54 {
55 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
56 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
57 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index)).filter(Boolean);
58 const safeSteps = steps.length > 0
59 ? steps
60 : [normalizeDialogueStep({
61 stepId: "greeting",
62 label: "Greeting",
63 lines: [{ speaker: "npc", text: "…" }],
64 exit: { kind: "end" }
65 }, 0)];
66 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
67 const ids = new Set(safeSteps.map((s) => s.stepId));
68 return {
69 dialogueId,
70 label: String(raw?.label ?? dialogueId).trim().slice(0, 80) || dialogueId,
71 unique: !!raw?.unique,
72 entryStepId: ids.has(entryStepId) ? entryStepId : safeSteps[0].stepId,
73 steps: safeSteps
74 };
75 }
76
77 function normalizeDialogueStep (raw, index)
78 {
79 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 const exit = normalizeExit(raw?.exit, raw);
83 return {
84 stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
87 exit
88 };
89 }
90
91 function normalizeDialogueLine (raw)
92 {
93 if (!raw || typeof raw !== "object")
94 { return null; }
95 const text = String(raw.text ?? "").trim().slice(0, 500);
96 if (!text)
97 { return null; }
98 const speaker = raw.speaker === "player" ? "player" : "npc";
99 return { speaker, text, effects: normalizeEffects(raw.effects) };
100 }
101
102 function normalizeExit (exit, legacy)
103 {
104 if (exit && typeof exit === "object" && exit.kind)
105 {
106 if (exit.kind === "triggers")
107 {
108 return {
109 kind: "triggers",
110 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
111 .map(normalizeTrigger)
112 .filter(Boolean)
113 };
114 }
115 if (exit.kind === "branches")
116 {
117 return {
118 kind: "branches",
119 branches: (Array.isArray(exit.branches) ? exit.branches : [])
120 .map(normalizeBranch)
121 .filter(Boolean)
122 };
123 }
124 return { kind: "end" };
125 }
126 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)
127 {
128 return {
129 kind: "triggers",
130 triggers: legacy.triggers.map(normalizeTrigger).filter(Boolean)
131 };
132 }
133 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
134 {
135 return {
136 kind: "branches",
137 branches: legacy.branches.map(normalizeBranch).filter(Boolean)
138 };
139 }
140 return { kind: "end" };
141 }
142
143 function normalizeTrigger (raw)
144 {
145 if (!raw || typeof raw !== "object")
146 { return null; }
147 const trigger = slugId(raw.trigger ?? raw.id, "choice");
148 const text = String(raw.text ?? "").trim().slice(0, 120);
149 if (!text)
150 { return null; }
151 const next = raw.nextStepId == null || raw.nextStepId === ""
152 ? null
153 : slugId(raw.nextStepId, "");
154 return {
155 trigger,
156 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
157 text,
158 nextStepId: next || null,
159 when: normalizeConditionSet(raw.when ?? raw.require),
160 effects: normalizeEffects(raw.effects)
161 };
162 }
163
164 function normalizeBranch (raw)
165 {
166 if (!raw || typeof raw !== "object")
167 { return null; }
168 const next = raw.nextStepId == null || raw.nextStepId === ""
169 ? null
170 : slugId(raw.nextStepId, "");
171 return {
172 label: String(raw.label ?? "").trim().slice(0, 80),
173 when: normalizeConditionSet(raw.when ?? raw.require),
174 nextStepId: next || null,
175 effects: normalizeEffects(raw.effects)
176 };
177 }
178
179 function slugId (raw, fallback)
180 {
181 const s = String(raw ?? "")
182 .trim()
183 .toLowerCase()
184 .replace(/[^a-z0-9_-]+/g, "-")
185 .replace(/^-+|-+$/g, "")
186 .slice(0, 64);
187 return s || fallback;
188 }
@@ -0,0 +1,188 @@
1import { normalizeConditionSet, normalizeEffects, emptyConditionSet } from "./conditions.js";
2
3export function normalizeQuestDef (raw)
4{
5 const questId = slugId(raw?.questId ?? raw?.id, "quest");
6 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
7 const steps = stepsIn.map((step, index) => normalizeQuestStep(step, index)).filter(Boolean);
8 return {
9 questId,
10 title: String(raw?.title ?? questId).trim().slice(0, 80) || questId,
11 description: String(raw?.description ?? "").trim().slice(0, 500),
12 steps: steps.length > 0 ? steps : [normalizeQuestStep({ stepId: "step-1" }, 0)],
13 rewards: normalizeEffects(raw?.rewards),
14 cancelable: !!raw?.cancelable
15 };
16}
17
18function normalizeQuestStep (raw, index)
19{
20 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
21 const objectivesIn = Array.isArray(raw?.objectives) ? raw.objectives : [];
22 let objectives = objectivesIn.map((obj, i) => normalizeObjective(obj, i)).filter(Boolean);
23 if (objectives.length === 0)
24 {
25 objectives = [normalizeObjective({
26 objectiveId: "obj-1",
27 text: "Complete this step",
28 when: emptyConditionSet()
29 }, 0)];
30 }
31 return {
32 stepId,
33 title: String(raw?.title ?? stepId).trim().slice(0, 80) || stepId,
34 description: String(raw?.description ?? "").trim().slice(0, 500),
35 completionJournalText: String(raw?.completionJournalText ?? "").trim().slice(0, 500),
36 objectives,
37 onEnter: normalizeEffects(raw?.onEnter),
38 onComplete: normalizeEffects(raw?.onComplete)
39 };
40}
41
42function normalizeObjective (raw, index)
43{
44 const objectiveId = slugId(raw?.objectiveId ?? raw?.id, `obj-${index + 1}`);
45 const when = normalizeConditionSet(raw?.when ?? raw?.require);
46 return {
47 objectiveId,
48 text: String(raw?.text ?? objectiveId).trim().slice(0, 200) || objectiveId,
49 when
50 };
51}
52
53export function normalizeDialogueTree (raw)
54{
55 const dialogueId = slugId(raw?.dialogueId ?? raw?.id, "dialogue");
56 const stepsIn = Array.isArray(raw?.steps) ? raw.steps : [];
57 const steps = stepsIn.map((step, index) => normalizeDialogueStep(step, index)).filter(Boolean);
58 const safeSteps = steps.length > 0
59 ? steps
60 : [normalizeDialogueStep({
61 stepId: "greeting",
62 label: "Greeting",
63 lines: [{ speaker: "npc", text: "…" }],
64 exit: { kind: "end" }
65 }, 0)];
66 const entryStepId = slugId(raw?.entryStepId ?? safeSteps[0].stepId, safeSteps[0].stepId);
67 const ids = new Set(safeSteps.map((s) => s.stepId));
68 return {
69 dialogueId,
70 label: String(raw?.label ?? dialogueId).trim().slice(0, 80) || dialogueId,
71 unique: !!raw?.unique,
72 entryStepId: ids.has(entryStepId) ? entryStepId : safeSteps[0].stepId,
73 steps: safeSteps
74 };
75}
76
77function normalizeDialogueStep (raw, index)
78{
79 const stepId = slugId(raw?.stepId ?? raw?.id, `step-${index + 1}`);
80 const linesIn = Array.isArray(raw?.lines) ? raw.lines : [];
81 const lines = linesIn.map(normalizeDialogueLine).filter(Boolean);
82 const exit = normalizeExit(raw?.exit, raw);
83 return {
84 stepId,
85 label: String(raw?.label ?? stepId).trim().slice(0, 80) || stepId,
86 lines: lines.length > 0 ? lines : [{ speaker: "npc", text: "…", effects: [] }],
87 exit
88 };
89}
90
91function normalizeDialogueLine (raw)
92{
93 if (!raw || typeof raw !== "object")
94 { return null; }
95 const text = String(raw.text ?? "").trim().slice(0, 500);
96 if (!text)
97 { return null; }
98 const speaker = raw.speaker === "player" ? "player" : "npc";
99 return { speaker, text, effects: normalizeEffects(raw.effects) };
100}
101
102function normalizeExit (exit, legacy)
103{
104 if (exit && typeof exit === "object" && exit.kind)
105 {
106 if (exit.kind === "triggers")
107 {
108 return {
109 kind: "triggers",
110 triggers: (Array.isArray(exit.triggers) ? exit.triggers : [])
111 .map(normalizeTrigger)
112 .filter(Boolean)
113 };
114 }
115 if (exit.kind === "branches")
116 {
117 return {
118 kind: "branches",
119 branches: (Array.isArray(exit.branches) ? exit.branches : [])
120 .map(normalizeBranch)
121 .filter(Boolean)
122 };
123 }
124 return { kind: "end" };
125 }
126 if (Array.isArray(legacy?.triggers) && legacy.triggers.length > 0)
127 {
128 return {
129 kind: "triggers",
130 triggers: legacy.triggers.map(normalizeTrigger).filter(Boolean)
131 };
132 }
133 if (Array.isArray(legacy?.branches) && legacy.branches.length > 0)
134 {
135 return {
136 kind: "branches",
137 branches: legacy.branches.map(normalizeBranch).filter(Boolean)
138 };
139 }
140 return { kind: "end" };
141}
142
143function normalizeTrigger (raw)
144{
145 if (!raw || typeof raw !== "object")
146 { return null; }
147 const trigger = slugId(raw.trigger ?? raw.id, "choice");
148 const text = String(raw.text ?? "").trim().slice(0, 120);
149 if (!text)
150 { return null; }
151 const next = raw.nextStepId == null || raw.nextStepId === ""
152 ? null
153 : slugId(raw.nextStepId, "");
154 return {
155 trigger,
156 label: String(raw.label ?? trigger).trim().slice(0, 80) || trigger,
157 text,
158 nextStepId: next || null,
159 when: normalizeConditionSet(raw.when ?? raw.require),
160 effects: normalizeEffects(raw.effects)
161 };
162}
163
164function normalizeBranch (raw)
165{
166 if (!raw || typeof raw !== "object")
167 { return null; }
168 const next = raw.nextStepId == null || raw.nextStepId === ""
169 ? null
170 : slugId(raw.nextStepId, "");
171 return {
172 label: String(raw.label ?? "").trim().slice(0, 80),
173 when: normalizeConditionSet(raw.when ?? raw.require),
174 nextStepId: next || null,
175 effects: normalizeEffects(raw.effects)
176 };
177}
178
179function slugId (raw, fallback)
180{
181 const s = String(raw ?? "")
182 .trim()
183 .toLowerCase()
184 .replace(/[^a-z0-9_-]+/g, "-")
185 .replace(/^-+|-+$/g, "")
186 .slice(0, 64);
187 return s || fallback;
188}
shared/world/dimensions.js added +134 −0
@@ -0,0 +1,134 @@
1 /**
2 * World dimensions (overworld + interiors).
3 * Spatial identity is { dimensionId, tileX, tileY }.
4 */
5
6 export const OVERWORLD_ID = "overworld";
7
8 export const DimensionLightingMode = Object.freeze({
9 dayNight: "dayNight",
10 alwaysLit: "alwaysLit",
11 alwaysDark: "alwaysDark"
12 });
13
14 /** Authoring values; render resolves spring→summer, autumn→fall. */
15 export const DimensionSeasonMode = Object.freeze({
16 auto: "auto",
17 summer: "summer",
18 spring: "spring",
19 autumn: "autumn",
20 winter: "winter"
21 });
22
23 export const DIMENSION_PURGE_MS = 7 * 24 * 60 * 60 * 1000;
24
25 export function normalizeDimensionId (raw)
26 {
27 const id = String(raw ?? "").trim().toLowerCase();
28 if (!id)
29 { return OVERWORLD_ID; }
30 // Slug: letters, digits, underscore, hyphen
31 const cleaned = id.replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
32 return cleaned || OVERWORLD_ID;
33 }
34
35 export function isOverworld (dimensionId)
36 {
37 return normalizeDimensionId(dimensionId) === OVERWORLD_ID;
38 }
39
40 export function normalizeLightingMode (raw)
41 {
42 const mode = String(raw ?? "").trim();
43 if (mode === DimensionLightingMode.alwaysLit || mode === DimensionLightingMode.alwaysDark)
44 { return mode; }
45 return DimensionLightingMode.dayNight;
46 }
47
48 export function normalizeSeasonMode (raw)
49 {
50 const mode = String(raw ?? "").trim();
51 if (
52 mode === DimensionSeasonMode.summer
53 || mode === DimensionSeasonMode.spring
54 || mode === DimensionSeasonMode.autumn
55 || mode === DimensionSeasonMode.winter
56 )
57 { return mode; }
58 return DimensionSeasonMode.auto;
59 }
60
61 /**
62 * Map dimension season mode to a SeasonId for sprite bake, or null for calendar auto.
63 * @returns {null | "summer" | "fall" | "winter"}
64 */
65 export function resolveDimensionSeasonId (seasonMode)
66 {
67 const mode = normalizeSeasonMode(seasonMode);
68 if (mode === DimensionSeasonMode.auto)
69 { return null; }
70 if (mode === DimensionSeasonMode.autumn)
71 { return "fall"; }
72 if (mode === DimensionSeasonMode.spring || mode === DimensionSeasonMode.summer)
73 { return "summer"; }
74 return "winter";
75 }
76
77 /**
78 * Night darkness factor override for a dimension (null = use calendar/world hour).
79 * @returns {null | number} 0 = fully lit, 1 = fully dark ambient
80 */
81 export function resolveDimensionDarknessFactor (lightingMode, calendarNightFactor)
82 {
83 const mode = normalizeLightingMode(lightingMode);
84 if (mode === DimensionLightingMode.alwaysLit)
85 { return 0; }
86 if (mode === DimensionLightingMode.alwaysDark)
87 { return 1; }
88 return calendarNightFactor ?? 0;
89 }
90
91 export function defaultDimensionRecord (dimensionId, {
92 displayName = null,
93 lightingMode = DimensionLightingMode.dayNight,
94 seasonMode = DimensionSeasonMode.auto,
95 defaultGroundTypeId = 1,
96 deletedAt = null,
97 purgeAfter = null
98 } = {})
99 {
100 const id = normalizeDimensionId(dimensionId);
101 return {
102 dimensionId: id,
103 displayName: displayName != null ? String(displayName) : id,
104 lightingMode: normalizeLightingMode(lightingMode),
105 seasonMode: normalizeSeasonMode(seasonMode),
106 defaultGroundTypeId: Math.max(1, Number(defaultGroundTypeId) || 1) | 0,
107 deletedAt: deletedAt == null ? null : Number(deletedAt),
108 purgeAfter: purgeAfter == null ? null : Number(purgeAfter)
109 };
110 }
111
112 export function normalizeDimensionRecord (raw)
113 {
114 if (!raw || typeof raw !== "object")
115 { return defaultDimensionRecord(OVERWORLD_ID); }
116 return defaultDimensionRecord(raw.dimensionId ?? raw.dimension_id ?? OVERWORLD_ID, {
117 displayName: raw.displayName ?? raw.display_name,
118 lightingMode: raw.lightingMode ?? raw.lighting_mode,
119 seasonMode: raw.seasonMode ?? raw.season_mode,
120 defaultGroundTypeId: raw.defaultGroundTypeId ?? raw.default_ground_type_id,
121 deletedAt: raw.deletedAt ?? raw.deleted_at,
122 purgeAfter: raw.purgeAfter ?? raw.purge_after
123 });
124 }
125
126 export function isDimensionUsable (record, now = Date.now())
127 {
128 const dim = normalizeDimensionRecord(record);
129 if (dim.deletedAt != null)
130 { return false; }
131 if (dim.purgeAfter != null && dim.purgeAfter <= now)
132 { return false; }
133 return true;
134 }
@@ -0,0 +1,134 @@
1/**
2 * World dimensions (overworld + interiors).
3 * Spatial identity is { dimensionId, tileX, tileY }.
4 */
5
6export const OVERWORLD_ID = "overworld";
7
8export const DimensionLightingMode = Object.freeze({
9 dayNight: "dayNight",
10 alwaysLit: "alwaysLit",
11 alwaysDark: "alwaysDark"
12});
13
14/** Authoring values; render resolves spring→summer, autumn→fall. */
15export const DimensionSeasonMode = Object.freeze({
16 auto: "auto",
17 summer: "summer",
18 spring: "spring",
19 autumn: "autumn",
20 winter: "winter"
21});
22
23export const DIMENSION_PURGE_MS = 7 * 24 * 60 * 60 * 1000;
24
25export function normalizeDimensionId (raw)
26{
27 const id = String(raw ?? "").trim().toLowerCase();
28 if (!id)
29 { return OVERWORLD_ID; }
30 // Slug: letters, digits, underscore, hyphen
31 const cleaned = id.replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "");
32 return cleaned || OVERWORLD_ID;
33}
34
35export function isOverworld (dimensionId)
36{
37 return normalizeDimensionId(dimensionId) === OVERWORLD_ID;
38}
39
40export function normalizeLightingMode (raw)
41{
42 const mode = String(raw ?? "").trim();
43 if (mode === DimensionLightingMode.alwaysLit || mode === DimensionLightingMode.alwaysDark)
44 { return mode; }
45 return DimensionLightingMode.dayNight;
46}
47
48export function normalizeSeasonMode (raw)
49{
50 const mode = String(raw ?? "").trim();
51 if (
52 mode === DimensionSeasonMode.summer
53 || mode === DimensionSeasonMode.spring
54 || mode === DimensionSeasonMode.autumn
55 || mode === DimensionSeasonMode.winter
56 )
57 { return mode; }
58 return DimensionSeasonMode.auto;
59}
60
61/**
62 * Map dimension season mode to a SeasonId for sprite bake, or null for calendar auto.
63 * @returns {null | "summer" | "fall" | "winter"}
64 */
65export function resolveDimensionSeasonId (seasonMode)
66{
67 const mode = normalizeSeasonMode(seasonMode);
68 if (mode === DimensionSeasonMode.auto)
69 { return null; }
70 if (mode === DimensionSeasonMode.autumn)
71 { return "fall"; }
72 if (mode === DimensionSeasonMode.spring || mode === DimensionSeasonMode.summer)
73 { return "summer"; }
74 return "winter";
75}
76
77/**
78 * Night darkness factor override for a dimension (null = use calendar/world hour).
79 * @returns {null | number} 0 = fully lit, 1 = fully dark ambient
80 */
81export function resolveDimensionDarknessFactor (lightingMode, calendarNightFactor)
82{
83 const mode = normalizeLightingMode(lightingMode);
84 if (mode === DimensionLightingMode.alwaysLit)
85 { return 0; }
86 if (mode === DimensionLightingMode.alwaysDark)
87 { return 1; }
88 return calendarNightFactor ?? 0;
89}
90
91export function defaultDimensionRecord (dimensionId, {
92 displayName = null,
93 lightingMode = DimensionLightingMode.dayNight,
94 seasonMode = DimensionSeasonMode.auto,
95 defaultGroundTypeId = 1,
96 deletedAt = null,
97 purgeAfter = null
98} = {})
99{
100 const id = normalizeDimensionId(dimensionId);
101 return {
102 dimensionId: id,
103 displayName: displayName != null ? String(displayName) : id,
104 lightingMode: normalizeLightingMode(lightingMode),
105 seasonMode: normalizeSeasonMode(seasonMode),
106 defaultGroundTypeId: Math.max(1, Number(defaultGroundTypeId) || 1) | 0,
107 deletedAt: deletedAt == null ? null : Number(deletedAt),
108 purgeAfter: purgeAfter == null ? null : Number(purgeAfter)
109 };
110}
111
112export function normalizeDimensionRecord (raw)
113{
114 if (!raw || typeof raw !== "object")
115 { return defaultDimensionRecord(OVERWORLD_ID); }
116 return defaultDimensionRecord(raw.dimensionId ?? raw.dimension_id ?? OVERWORLD_ID, {
117 displayName: raw.displayName ?? raw.display_name,
118 lightingMode: raw.lightingMode ?? raw.lighting_mode,
119 seasonMode: raw.seasonMode ?? raw.season_mode,
120 defaultGroundTypeId: raw.defaultGroundTypeId ?? raw.default_ground_type_id,
121 deletedAt: raw.deletedAt ?? raw.deleted_at,
122 purgeAfter: raw.purgeAfter ?? raw.purge_after
123 });
124}
125
126export function isDimensionUsable (record, now = Date.now())
127{
128 const dim = normalizeDimensionRecord(record);
129 if (dim.deletedAt != null)
130 { return false; }
131 if (dim.purgeAfter != null && dim.purgeAfter <= now)
132 { return false; }
133 return true;
134}