BlueGit

timfa questward

Apply world settings immediately from a categorised editor modal.

Night darkness and other global timers are live settings with a settings edit log, rather than waiting on a map revision.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
215995531990a4fd4f619b37ba05d51bb8811c43
Parent
a54d0510
16 files changed +771 −94
client/editor.html +20 −7
@@ -35,19 +35,32 @@
35 35 <button id="save" type="button">Save chunk</button>
36 36 <button id="apply" type="button">Apply now</button>
37 37 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
38 <fieldset>
39 <legend>World settings</legend>
40 <label>Walk tiles/s <input id="walk-speed" type="number" min="0.5" step="0.5" value="2"></label>
41 <label>Sim tick Hz <input id="tick-hz" type="number" min="5" step="1" value="20"></label>
42 <button id="save-settings" type="button">Save settings</button>
43 </fieldset>
44 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Saves write a pending revision. Apply now reloads the live world. Marketplace placement waits on assets.</p>
38 <button id="open-settings" type="button">World settings</button>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
45 40 </aside>
46 41 <section id="changelog-wrap">
47 42 <h2>Changelog</h2>
48 43 <div id="changelog"></div>
49 44 </section>
50 45 <div id="selection-border" aria-hidden="true"></div>
46 <div id="settings-backdrop" hidden></div>
47 <div id="settings-modal" hidden>
48 <div id="settings-main">
49 <header>
50 <h2>World settings</h2>
51 <button id="settings-close" type="button">Close</button>
52 </header>
53 <div id="settings-form"></div>
54 <footer>
55 <button id="settings-cancel" type="button">Cancel</button>
56 <button id="settings-save" type="button" disabled>Save</button>
57 </footer>
58 </div>
59 <aside id="settings-log-wrap">
60 <h2>Settings log</h2>
61 <div id="settings-log"></div>
62 </aside>
63 </div>
51 64 <script src="/framework/framework.js"></script>
52 65 <script type="module" src="/src/editor/main.js"></script>
53 66 </body>
@@ -35,19 +35,32 @@
35 <button id="save" type="button">Save chunk</button>
35 <button id="save" type="button">Save chunk</button>
36 <button id="apply" type="button">Apply now</button>
36 <button id="apply" type="button">Apply now</button>
37 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
37 <label>Night preview <input id="night" type="range" min="0" max="24" step="0.1" value="12"><span id="night-label">12.0</span></label>
38 <fieldset>
38 <button id="open-settings" type="button">World settings</button>
39 <legend>World settings</legend>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
40 <label>Walk tiles/s <input id="walk-speed" type="number" min="0.5" step="0.5" value="2"></label>
41 <label>Sim tick Hz <input id="tick-hz" type="number" min="5" step="1" value="20"></label>
42 <button id="save-settings" type="button">Save settings</button>
43 </fieldset>
44 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Saves write a pending revision. Apply now reloads the live world. Marketplace placement waits on assets.</p>
45 </aside>
40 </aside>
46 <section id="changelog-wrap">
41 <section id="changelog-wrap">
47 <h2>Changelog</h2>
42 <h2>Changelog</h2>
48 <div id="changelog"></div>
43 <div id="changelog"></div>
49 </section>
44 </section>
50 <div id="selection-border" aria-hidden="true"></div>
45 <div id="selection-border" aria-hidden="true"></div>
46 <div id="settings-backdrop" hidden></div>
47 <div id="settings-modal" hidden>
48 <div id="settings-main">
49 <header>
50 <h2>World settings</h2>
51 <button id="settings-close" type="button">Close</button>
52 </header>
53 <div id="settings-form"></div>
54 <footer>
55 <button id="settings-cancel" type="button">Cancel</button>
56 <button id="settings-save" type="button" disabled>Save</button>
57 </footer>
58 </div>
59 <aside id="settings-log-wrap">
60 <h2>Settings log</h2>
61 <div id="settings-log"></div>
62 </aside>
63 </div>
51 <script src="/framework/framework.js"></script>
64 <script src="/framework/framework.js"></script>
52 <script type="module" src="/src/editor/main.js"></script>
65 <script type="module" src="/src/editor/main.js"></script>
53</body>
66</body>
client/src/editor/main.js +19 −19
@@ -3,6 +3,7 @@ import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/defin
3 3 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4 4 import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
5 5 import { WorldView } from "../render/worldView.js";
6 import { initSettingsModal } from "./settingsModal.js";
6 7
7 8 const game = new Game();
8 9 let socket;
@@ -12,6 +13,7 @@ let draft = null;
12 13 let chunkX = 0;
13 14 let chunkY = 0;
14 15 let tool = { kind: "ground", typeId: GroundType.grass };
16 let settingsModal;
15 17
16 18 function $ (id)
17 19 {
@@ -153,8 +155,8 @@ function updateSelectionBorder ()
153 155
154 156 function layoutScene ()
155 157 {
156 const header = document.querySelector("header");
157 const aside = document.querySelector("aside");
158 const header = document.querySelector("body > header");
159 const aside = document.querySelector("body > aside");
158 160 const changelog = $("changelog-wrap");
159 161 const top = header.offsetHeight;
160 162 aside.style.top = `${top}px`;
@@ -207,7 +209,7 @@ async function main ()
207 209 const ticker = new GameObject(0, 0, null, 10);
208 210 ticker.update = (dt) =>
209 211 {
210 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft)
212 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft && !settingsModal?.isOpen())
211 213 {
212 214 const canvas = scene.canvas;
213 215 const rect = canvas.getBoundingClientRect();
@@ -223,7 +225,6 @@ async function main ()
223 225 frameNeighborhood();
224 226 };
225 227 scene.addObject(ticker);
226 game.startGame();
227 228 window.addEventListener("resize", layoutScene);
228 229
229 230 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -231,15 +232,15 @@ async function main ()
231 232 if (message.type === MessageType.session)
232 233 {
233 234 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
235 socket.send({ type: MessageType.editorLoadSettings });
234 236 loadNeighborhood(0, 0);
235 237 }
238 else if (message.type === MessageType.editorSettings)
239 { settingsModal.handleMessage(message); }
236 240 else if (message.type === MessageType.editorChunk)
237 241 {
238 if (message.settingsSaved)
239 {
240 $("revision").textContent = `settings saved on pending ${message.settingsSaved.revisionId}`;
241 return;
242 }
242 if (message.settings)
243 { view.settings = message.settings; }
243 244 if (!inEditorView(message.chunkX, message.chunkY))
244 245 { return; }
245 246 if (message.chunkX === chunkX && message.chunkY === chunkY)
@@ -251,6 +252,15 @@ async function main ()
251 252 else if (message.type === MessageType.error)
252 253 { $("error").textContent = message.message; }
253 254 });
255 settingsModal = initSettingsModal({
256 socket,
257 MessageType,
258 onApplied (settings)
259 {
260 view.settings = settings;
261 }
262 });
263 game.startGame();
254 264 await socket.connect();
255 265 }
256 266
@@ -293,16 +303,6 @@ $("night").addEventListener("input", () =>
293 303 view.nightPreview = Number($("night").value);
294 304 $("night-label").textContent = view.nightPreview.toFixed(1);
295 305 });
296 $("save-settings").addEventListener("click", () =>
297 {
298 socket.send({
299 type: MessageType.editorSaveSettings,
300 settings: {
301 walkTilesPerSecond: Number($("walk-speed").value),
302 simulationTickHz: Number($("tick-hz").value)
303 }
304 });
305 });
306 306
307 307 main().catch((error) =>
308 308 {
@@ -3,6 +3,7 @@ import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/defin
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
4import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
5import { WorldView } from "../render/worldView.js";
6import { initSettingsModal } from "./settingsModal.js";
6
7
7const game = new Game();
8const game = new Game();
8let socket;
9let socket;
@@ -12,6 +13,7 @@ let draft = null;
12let chunkX = 0;
13let chunkX = 0;
13let chunkY = 0;
14let chunkY = 0;
14let tool = { kind: "ground", typeId: GroundType.grass };
15let tool = { kind: "ground", typeId: GroundType.grass };
16let settingsModal;
15
17
16function $ (id)
18function $ (id)
17{
19{
@@ -153,8 +155,8 @@ function updateSelectionBorder ()
153
155
154function layoutScene ()
156function layoutScene ()
155{
157{
156 const header = document.querySelector("header");
158 const header = document.querySelector("body > header");
157 const aside = document.querySelector("aside");
159 const aside = document.querySelector("body > aside");
158 const changelog = $("changelog-wrap");
160 const changelog = $("changelog-wrap");
159 const top = header.offsetHeight;
161 const top = header.offsetHeight;
160 aside.style.top = `${top}px`;
162 aside.style.top = `${top}px`;
@@ -207,7 +209,7 @@ async function main ()
207 const ticker = new GameObject(0, 0, null, 10);
209 const ticker = new GameObject(0, 0, null, 10);
208 ticker.update = (dt) =>
210 ticker.update = (dt) =>
209 {
211 {
210 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft)
212 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft && !settingsModal?.isOpen())
211 {
213 {
212 const canvas = scene.canvas;
214 const canvas = scene.canvas;
213 const rect = canvas.getBoundingClientRect();
215 const rect = canvas.getBoundingClientRect();
@@ -223,7 +225,6 @@ async function main ()
223 frameNeighborhood();
225 frameNeighborhood();
224 };
226 };
225 scene.addObject(ticker);
227 scene.addObject(ticker);
226 game.startGame();
227 window.addEventListener("resize", layoutScene);
228 window.addEventListener("resize", layoutScene);
228
229
229 socket = new GameSocket(defaultSocketUrl(), (message) =>
230 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -231,15 +232,15 @@ async function main ()
231 if (message.type === MessageType.session)
232 if (message.type === MessageType.session)
232 {
233 {
233 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
234 $("who").textContent = `${message.authSubject}${message.isAdmin ? " · admin" : ""}`;
235 socket.send({ type: MessageType.editorLoadSettings });
234 loadNeighborhood(0, 0);
236 loadNeighborhood(0, 0);
235 }
237 }
238 else if (message.type === MessageType.editorSettings)
239 { settingsModal.handleMessage(message); }
236 else if (message.type === MessageType.editorChunk)
240 else if (message.type === MessageType.editorChunk)
237 {
241 {
238 if (message.settingsSaved)
242 if (message.settings)
239 {
243 { view.settings = message.settings; }
240 $("revision").textContent = `settings saved on pending ${message.settingsSaved.revisionId}`;
241 return;
242 }
243 if (!inEditorView(message.chunkX, message.chunkY))
244 if (!inEditorView(message.chunkX, message.chunkY))
244 { return; }
245 { return; }
245 if (message.chunkX === chunkX && message.chunkY === chunkY)
246 if (message.chunkX === chunkX && message.chunkY === chunkY)
@@ -251,6 +252,15 @@ async function main ()
251 else if (message.type === MessageType.error)
252 else if (message.type === MessageType.error)
252 { $("error").textContent = message.message; }
253 { $("error").textContent = message.message; }
253 });
254 });
255 settingsModal = initSettingsModal({
256 socket,
257 MessageType,
258 onApplied (settings)
259 {
260 view.settings = settings;
261 }
262 });
263 game.startGame();
254 await socket.connect();
264 await socket.connect();
255}
265}
256
266
@@ -293,16 +303,6 @@ $("night").addEventListener("input", () =>
293 view.nightPreview = Number($("night").value);
303 view.nightPreview = Number($("night").value);
294 $("night-label").textContent = view.nightPreview.toFixed(1);
304 $("night-label").textContent = view.nightPreview.toFixed(1);
295});
305});
296$("save-settings").addEventListener("click", () =>
297{
298 socket.send({
299 type: MessageType.editorSaveSettings,
300 settings: {
301 walkTilesPerSecond: Number($("walk-speed").value),
302 simulationTickHz: Number($("tick-hz").value)
303 }
304 });
305});
306
306
307main().catch((error) =>
307main().catch((error) =>
308{
308{
client/src/editor/settingsModal.js added +184 −0
@@ -0,0 +1,184 @@
1 import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue } from "/shared/definitions/worldSettings.js";
2
3 export function initSettingsModal ({ socket, MessageType, onApplied })
4 {
5 const backdrop = document.getElementById("settings-backdrop");
6 const modal = document.getElementById("settings-modal");
7 const form = document.getElementById("settings-form");
8 const log = document.getElementById("settings-log");
9 const save = document.getElementById("settings-save");
10 let baseline = {};
11 let open = false;
12 let loaded = false;
13
14 buildForm(form);
15 form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
16 form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
17
18 function show (visible)
19 {
20 if (!visible)
21 {
22 fillForm(form, baseline);
23 refreshDirty(form, baseline, loaded);
24 }
25 open = visible;
26 backdrop.hidden = !visible;
27 modal.hidden = !visible;
28 }
29
30 document.getElementById("open-settings").addEventListener("click", () =>
31 {
32 socket.send({ type: MessageType.editorLoadSettings });
33 show(true);
34 });
35 document.getElementById("settings-close").addEventListener("click", () => show(false));
36 document.getElementById("settings-cancel").addEventListener("click", () => show(false));
37 backdrop.addEventListener("click", () => show(false));
38 save.addEventListener("click", () =>
39 {
40 if (!loaded)
41 { return; }
42 const changed = dirtyValues(form, baseline);
43 if (Object.keys(changed).length === 0)
44 { return; }
45 socket.send({ type: MessageType.editorSaveSettings, settings: changed });
46 });
47
48 return {
49 isOpen: () => open,
50 handleMessage (message)
51 {
52 loaded = true;
53 baseline = { ...message.settings };
54 fillForm(form, baseline);
55 refreshDirty(form, baseline, loaded);
56 renderLog(log, message.changelog ?? []);
57 onApplied?.(message.settings);
58 }
59 };
60 }
61
62 function buildForm (form)
63 {
64 form.innerHTML = "";
65 for (const category of WORLD_SETTING_CATEGORIES)
66 {
67 const section = document.createElement("section");
68 section.className = "settings-category";
69 const heading = document.createElement("h3");
70 heading.textContent = category.label;
71 section.append(heading);
72 for (const field of category.fields)
73 {
74 const row = document.createElement("label");
75 row.className = "setting-row";
76 row.dataset.key = field.key;
77 const title = document.createElement("span");
78 title.className = "setting-label";
79 title.textContent = field.label;
80 const input = document.createElement("input");
81 input.id = `setting-${field.key}`;
82 input.dataset.key = field.key;
83 input.type = field.type === "range" ? "range" : "number";
84 if (field.min != null)
85 { input.min = String(field.min); }
86 if (field.max != null)
87 { input.max = String(field.max); }
88 if (field.step != null)
89 { input.step = String(field.step); }
90 const valueLabel = document.createElement("span");
91 valueLabel.className = "setting-value";
92 input.addEventListener("input", () =>
93 {
94 valueLabel.textContent = formatSettingValue(Number(input.value));
95 });
96 row.append(title, input, valueLabel);
97 if (field.hint)
98 {
99 const hint = document.createElement("small");
100 hint.className = "hint";
101 hint.textContent = field.hint;
102 row.append(hint);
103 }
104 section.append(row);
105 }
106 form.append(section);
107 }
108 }
109
110 function fillForm (form, settings)
111 {
112 for (const input of form.querySelectorAll("input[data-key]"))
113 {
114 const value = settings[input.dataset.key];
115 input.value = value ?? "";
116 const label = input.parentElement.querySelector(".setting-value");
117 if (label)
118 { label.textContent = formatSettingValue(value); }
119 }
120 }
121
122 function dirtyValues (form, baseline)
123 {
124 const changed = {};
125 for (const input of form.querySelectorAll("input[data-key]"))
126 {
127 const field = findField(input.dataset.key);
128 const next = coerceSettingValue(field, input.value);
129 if (next == null || next === baseline[field.key])
130 { continue; }
131 changed[field.key] = next;
132 }
133 return changed;
134 }
135
136 function refreshDirty (form, baseline, loaded)
137 {
138 const changed = loaded ? dirtyValues(form, baseline) : {};
139 for (const row of form.querySelectorAll(".setting-row"))
140 {
141 row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));
142 }
143 const save = document.getElementById("settings-save");
144 save.disabled = Object.keys(changed).length === 0;
145 save.textContent = Object.keys(changed).length
146 ? `Save ${Object.keys(changed).length} change${Object.keys(changed).length === 1 ? "" : "s"}`
147 : "Save";
148 }
149
150 function renderLog (log, changelog)
151 {
152 log.innerHTML = "";
153 if (!changelog.length)
154 {
155 log.innerHTML = "<p class=\"hint\">No settings have been saved yet.</p>";
156 return;
157 }
158 for (const entry of changelog)
159 {
160 const item = document.createElement("article");
161 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
162 const list = document.createElement("ul");
163 for (const bullet of entry.diffEntries)
164 {
165 const li = document.createElement("li");
166 li.textContent = bullet;
167 list.append(li);
168 }
169 item.append(list);
170 log.append(item);
171 }
172 log.scrollTop = log.scrollHeight;
173 }
174
175 function findField (key)
176 {
177 for (const category of WORLD_SETTING_CATEGORIES)
178 {
179 const field = category.fields.find((entry) => entry.key === key);
180 if (field)
181 { return field; }
182 }
183 return { key };
184 }
@@ -0,0 +1,184 @@
1import { WORLD_SETTING_CATEGORIES, coerceSettingValue, formatSettingValue } from "/shared/definitions/worldSettings.js";
2
3export function initSettingsModal ({ socket, MessageType, onApplied })
4{
5 const backdrop = document.getElementById("settings-backdrop");
6 const modal = document.getElementById("settings-modal");
7 const form = document.getElementById("settings-form");
8 const log = document.getElementById("settings-log");
9 const save = document.getElementById("settings-save");
10 let baseline = {};
11 let open = false;
12 let loaded = false;
13
14 buildForm(form);
15 form.addEventListener("input", () => refreshDirty(form, baseline, loaded));
16 form.addEventListener("change", () => refreshDirty(form, baseline, loaded));
17
18 function show (visible)
19 {
20 if (!visible)
21 {
22 fillForm(form, baseline);
23 refreshDirty(form, baseline, loaded);
24 }
25 open = visible;
26 backdrop.hidden = !visible;
27 modal.hidden = !visible;
28 }
29
30 document.getElementById("open-settings").addEventListener("click", () =>
31 {
32 socket.send({ type: MessageType.editorLoadSettings });
33 show(true);
34 });
35 document.getElementById("settings-close").addEventListener("click", () => show(false));
36 document.getElementById("settings-cancel").addEventListener("click", () => show(false));
37 backdrop.addEventListener("click", () => show(false));
38 save.addEventListener("click", () =>
39 {
40 if (!loaded)
41 { return; }
42 const changed = dirtyValues(form, baseline);
43 if (Object.keys(changed).length === 0)
44 { return; }
45 socket.send({ type: MessageType.editorSaveSettings, settings: changed });
46 });
47
48 return {
49 isOpen: () => open,
50 handleMessage (message)
51 {
52 loaded = true;
53 baseline = { ...message.settings };
54 fillForm(form, baseline);
55 refreshDirty(form, baseline, loaded);
56 renderLog(log, message.changelog ?? []);
57 onApplied?.(message.settings);
58 }
59 };
60}
61
62function buildForm (form)
63{
64 form.innerHTML = "";
65 for (const category of WORLD_SETTING_CATEGORIES)
66 {
67 const section = document.createElement("section");
68 section.className = "settings-category";
69 const heading = document.createElement("h3");
70 heading.textContent = category.label;
71 section.append(heading);
72 for (const field of category.fields)
73 {
74 const row = document.createElement("label");
75 row.className = "setting-row";
76 row.dataset.key = field.key;
77 const title = document.createElement("span");
78 title.className = "setting-label";
79 title.textContent = field.label;
80 const input = document.createElement("input");
81 input.id = `setting-${field.key}`;
82 input.dataset.key = field.key;
83 input.type = field.type === "range" ? "range" : "number";
84 if (field.min != null)
85 { input.min = String(field.min); }
86 if (field.max != null)
87 { input.max = String(field.max); }
88 if (field.step != null)
89 { input.step = String(field.step); }
90 const valueLabel = document.createElement("span");
91 valueLabel.className = "setting-value";
92 input.addEventListener("input", () =>
93 {
94 valueLabel.textContent = formatSettingValue(Number(input.value));
95 });
96 row.append(title, input, valueLabel);
97 if (field.hint)
98 {
99 const hint = document.createElement("small");
100 hint.className = "hint";
101 hint.textContent = field.hint;
102 row.append(hint);
103 }
104 section.append(row);
105 }
106 form.append(section);
107 }
108}
109
110function fillForm (form, settings)
111{
112 for (const input of form.querySelectorAll("input[data-key]"))
113 {
114 const value = settings[input.dataset.key];
115 input.value = value ?? "";
116 const label = input.parentElement.querySelector(".setting-value");
117 if (label)
118 { label.textContent = formatSettingValue(value); }
119 }
120}
121
122function dirtyValues (form, baseline)
123{
124 const changed = {};
125 for (const input of form.querySelectorAll("input[data-key]"))
126 {
127 const field = findField(input.dataset.key);
128 const next = coerceSettingValue(field, input.value);
129 if (next == null || next === baseline[field.key])
130 { continue; }
131 changed[field.key] = next;
132 }
133 return changed;
134}
135
136function refreshDirty (form, baseline, loaded)
137{
138 const changed = loaded ? dirtyValues(form, baseline) : {};
139 for (const row of form.querySelectorAll(".setting-row"))
140 {
141 row.classList.toggle("dirty", Object.prototype.hasOwnProperty.call(changed, row.dataset.key));
142 }
143 const save = document.getElementById("settings-save");
144 save.disabled = Object.keys(changed).length === 0;
145 save.textContent = Object.keys(changed).length
146 ? `Save ${Object.keys(changed).length} change${Object.keys(changed).length === 1 ? "" : "s"}`
147 : "Save";
148}
149
150function renderLog (log, changelog)
151{
152 log.innerHTML = "";
153 if (!changelog.length)
154 {
155 log.innerHTML = "<p class=\"hint\">No settings have been saved yet.</p>";
156 return;
157 }
158 for (const entry of changelog)
159 {
160 const item = document.createElement("article");
161 item.innerHTML = `<header>${entry.editor_admin_id} · ${new Date(entry.edited_at).toLocaleString()}</header>`;
162 const list = document.createElement("ul");
163 for (const bullet of entry.diffEntries)
164 {
165 const li = document.createElement("li");
166 li.textContent = bullet;
167 list.append(li);
168 }
169 item.append(list);
170 log.append(item);
171 }
172 log.scrollTop = log.scrollHeight;
173}
174
175function findField (key)
176{
177 for (const category of WORLD_SETTING_CATEGORIES)
178 {
179 const field = category.fields.find((entry) => entry.key === key);
180 if (field)
181 { return field; }
182 }
183 return { key };
184}
client/src/render/worldView.js +8 −7
@@ -1,4 +1,4 @@
1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT } from "/shared/protocol/constants.js";
1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2 2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
3 3 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4 4
@@ -20,7 +20,7 @@ export class WorldView
20 20 this.entities = new Map();
21 21 this.edges = new Map();
22 22 this.localEntityId = null;
23 this.settings = { walkTilesPerSecond: 2 };
23 this.settings = { ...DEFAULT_WORLD_SETTINGS };
24 24 this.worldHour = 12;
25 25 this.nightPreview = null;
26 26 this.followPlayer = true;
@@ -391,7 +391,7 @@ export class WorldView
391 391 #updateShade ()
392 392 {
393 393 const hour = this.nightPreview ?? this.worldHour;
394 const ambientDark = nightFactor(hour);
394 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
395 395 for (const objects of this.tiles.values())
396 396 {
397 397 if (!objects.shade)
@@ -402,15 +402,16 @@ export class WorldView
402 402 }
403 403 }
404 404
405 export function nightFactor (hour)
405 export function nightFactor (hour, nightDarkness = 0.72)
406 406 {
407 const peak = Math.min(1, Math.max(0, nightDarkness));
407 408 if (hour >= 8 && hour <= 16)
408 409 { return 0; }
409 410 if (hour >= 22 || hour <= 5)
410 { return 0.72; }
411 { return peak; }
411 412 if (hour < 8)
412 { return lerp(0.72, 0, (hour - 5) / 3); }
413 return lerp(0, 0.72, (hour - 16) / 6);
413 { return lerp(peak, 0, (hour - 5) / 3); }
414 return lerp(0, peak, (hour - 16) / 6);
414 415 }
415 416
416 417 function lerp (a, b, t)
@@ -1,4 +1,4 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
3import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
3import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4
4
@@ -20,7 +20,7 @@ export class WorldView
20 this.entities = new Map();
20 this.entities = new Map();
21 this.edges = new Map();
21 this.edges = new Map();
22 this.localEntityId = null;
22 this.localEntityId = null;
23 this.settings = { walkTilesPerSecond: 2 };
23 this.settings = { ...DEFAULT_WORLD_SETTINGS };
24 this.worldHour = 12;
24 this.worldHour = 12;
25 this.nightPreview = null;
25 this.nightPreview = null;
26 this.followPlayer = true;
26 this.followPlayer = true;
@@ -391,7 +391,7 @@ export class WorldView
391 #updateShade ()
391 #updateShade ()
392 {
392 {
393 const hour = this.nightPreview ?? this.worldHour;
393 const hour = this.nightPreview ?? this.worldHour;
394 const ambientDark = nightFactor(hour);
394 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
395 for (const objects of this.tiles.values())
395 for (const objects of this.tiles.values())
396 {
396 {
397 if (!objects.shade)
397 if (!objects.shade)
@@ -402,15 +402,16 @@ export class WorldView
402 }
402 }
403}
403}
404
404
405export function nightFactor (hour)
405export function nightFactor (hour, nightDarkness = 0.72)
406{
406{
407 const peak = Math.min(1, Math.max(0, nightDarkness));
407 if (hour >= 8 && hour <= 16)
408 if (hour >= 8 && hour <= 16)
408 { return 0; }
409 { return 0; }
409 if (hour >= 22 || hour <= 5)
410 if (hour >= 22 || hour <= 5)
410 { return 0.72; }
411 { return peak; }
411 if (hour < 8)
412 if (hour < 8)
412 { return lerp(0.72, 0, (hour - 5) / 3); }
413 { return lerp(peak, 0, (hour - 5) / 3); }
413 return lerp(0, 0.72, (hour - 16) / 6);
414 return lerp(0, peak, (hour - 16) / 6);
414}
415}
415
416
416function lerp (a, b, t)
417function lerp (a, b, t)
client/ui/editor.css +113 −2
@@ -10,12 +10,12 @@ html, body {
10 10 min-height: 100%;
11 11 }
12 12
13 header {
13 body > header {
14 14 padding: 0.6rem 1rem;
15 15 border-bottom: 1px solid #2c3340;
16 16 }
17 17
18 aside {
18 body > aside {
19 19 position: absolute;
20 20 left: 0;
21 21 top: 56px;
@@ -70,3 +70,114 @@ fieldset { border-color: #3a4250; margin-top: 1rem; }
70 70 box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.55);
71 71 z-index: 4;
72 72 }
73
74 label { display: block; margin: 0.4rem 0; }
75
76 #settings-backdrop {
77 position: fixed;
78 inset: 0;
79 background: rgba(0, 0, 0, 0.62);
80 z-index: 19;
81 }
82
83 #settings-modal {
84 position: fixed;
85 inset: 4vh 4vw;
86 z-index: 20;
87 display: flex;
88 background: #161a22;
89 border: 1px solid #3a4250;
90 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
91 }
92
93 #settings-modal[hidden],
94 #settings-backdrop[hidden] {
95 display: none !important;
96 }
97
98 #settings-main {
99 flex: 1;
100 min-width: 0;
101 display: flex;
102 flex-direction: column;
103 }
104
105 #settings-main header,
106 #settings-main footer {
107 display: flex;
108 align-items: center;
109 justify-content: space-between;
110 gap: 0.75rem;
111 padding: 0.75rem 1rem;
112 border-bottom: 1px solid #2c3340;
113 }
114
115 #settings-main footer {
116 border-bottom: 0;
117 border-top: 1px solid #2c3340;
118 }
119
120 #settings-form {
121 flex: 1;
122 overflow: auto;
123 padding: 0.75rem 1rem 1.25rem;
124 }
125
126 .settings-category {
127 margin-bottom: 1.25rem;
128 }
129
130 .settings-category h3 {
131 margin: 0 0 0.5rem;
132 font-size: 0.95rem;
133 color: #d4c48a;
134 border-bottom: 1px solid #2c3340;
135 padding-bottom: 0.25rem;
136 }
137
138 .setting-row {
139 display: grid;
140 grid-template-columns: minmax(12rem, 1fr) minmax(8rem, 14rem) 4rem;
141 gap: 0.4rem 0.75rem;
142 align-items: center;
143 padding: 0.45rem 0.5rem;
144 margin: 0.2rem 0;
145 border-radius: 4px;
146 }
147
148 .setting-row .hint {
149 grid-column: 1 / -1;
150 margin: 0;
151 }
152
153 .setting-row.dirty {
154 background: #4a3d18;
155 box-shadow: inset 0 0 0 1px #c4a35a;
156 }
157
158 .setting-value {
159 font-variant-numeric: tabular-nums;
160 color: #c5c0b4;
161 }
162
163 #settings-log-wrap {
164 width: min(340px, 32vw);
165 flex-shrink: 0;
166 border-left: 1px solid #2c3340;
167 display: flex;
168 flex-direction: column;
169 background: #1a1e26;
170 }
171
172 #settings-log-wrap h2 {
173 margin: 0;
174 padding: 0.75rem 1rem;
175 border-bottom: 1px solid #2c3340;
176 font-size: 1rem;
177 }
178
179 #settings-log {
180 flex: 1;
181 overflow: auto;
182 padding: 0.75rem 1rem;
183 }
@@ -10,12 +10,12 @@ html, body {
10 min-height: 100%;
10 min-height: 100%;
11}
11}
12
12
13header {
13body > header {
14 padding: 0.6rem 1rem;
14 padding: 0.6rem 1rem;
15 border-bottom: 1px solid #2c3340;
15 border-bottom: 1px solid #2c3340;
16}
16}
17
17
18aside {
18body > aside {
19 position: absolute;
19 position: absolute;
20 left: 0;
20 left: 0;
21 top: 56px;
21 top: 56px;
@@ -70,3 +70,114 @@ fieldset { border-color: #3a4250; margin-top: 1rem; }
70 box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.55);
70 box-shadow: 0 0 0 1px rgba(0, 0, 0, 0.55);
71 z-index: 4;
71 z-index: 4;
72}
72}
73
74label { display: block; margin: 0.4rem 0; }
75
76#settings-backdrop {
77 position: fixed;
78 inset: 0;
79 background: rgba(0, 0, 0, 0.62);
80 z-index: 19;
81}
82
83#settings-modal {
84 position: fixed;
85 inset: 4vh 4vw;
86 z-index: 20;
87 display: flex;
88 background: #161a22;
89 border: 1px solid #3a4250;
90 box-shadow: 0 12px 40px rgba(0, 0, 0, 0.45);
91}
92
93#settings-modal[hidden],
94#settings-backdrop[hidden] {
95 display: none !important;
96}
97
98#settings-main {
99 flex: 1;
100 min-width: 0;
101 display: flex;
102 flex-direction: column;
103}
104
105#settings-main header,
106#settings-main footer {
107 display: flex;
108 align-items: center;
109 justify-content: space-between;
110 gap: 0.75rem;
111 padding: 0.75rem 1rem;
112 border-bottom: 1px solid #2c3340;
113}
114
115#settings-main footer {
116 border-bottom: 0;
117 border-top: 1px solid #2c3340;
118}
119
120#settings-form {
121 flex: 1;
122 overflow: auto;
123 padding: 0.75rem 1rem 1.25rem;
124}
125
126.settings-category {
127 margin-bottom: 1.25rem;
128}
129
130.settings-category h3 {
131 margin: 0 0 0.5rem;
132 font-size: 0.95rem;
133 color: #d4c48a;
134 border-bottom: 1px solid #2c3340;
135 padding-bottom: 0.25rem;
136}
137
138.setting-row {
139 display: grid;
140 grid-template-columns: minmax(12rem, 1fr) minmax(8rem, 14rem) 4rem;
141 gap: 0.4rem 0.75rem;
142 align-items: center;
143 padding: 0.45rem 0.5rem;
144 margin: 0.2rem 0;
145 border-radius: 4px;
146}
147
148.setting-row .hint {
149 grid-column: 1 / -1;
150 margin: 0;
151}
152
153.setting-row.dirty {
154 background: #4a3d18;
155 box-shadow: inset 0 0 0 1px #c4a35a;
156}
157
158.setting-value {
159 font-variant-numeric: tabular-nums;
160 color: #c5c0b4;
161}
162
163#settings-log-wrap {
164 width: min(340px, 32vw);
165 flex-shrink: 0;
166 border-left: 1px solid #2c3340;
167 display: flex;
168 flex-direction: column;
169 background: #1a1e26;
170}
171
172#settings-log-wrap h2 {
173 margin: 0;
174 padding: 0.75rem 1rem;
175 border-bottom: 1px solid #2c3340;
176 font-size: 1rem;
177}
178
179#settings-log {
180 flex: 1;
181 overflow: auto;
182 padding: 0.75rem 1rem;
183}
docs/FEATURES.md +8 −8
@@ -40,20 +40,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
40 40 ## Authored world and runtime state persistence
41 41
42 42 **Status:** full
43 **Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
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 44 **Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
45 45
46 46 ## World revisions and pending editor saves
47 47
48 48 **Status:** partial
49 **Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until an admin **Apply now** (in-process reload). Midnight restart/Git deploy is not implemented yet.
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 50 **Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
51 51
52 52 ## World settings
53 53
54 **Status:** partial
55 **Spec:** Global cadence and timers live in authored `world_settings` per revision, with design defaults. Walk speed and tick rate can be saved from the editor. Other timers are stored but not all are consumed yet.
56 **Code:** `server/src/persistence/worldDb.js`, `shared/protocol/constants.js` (`DEFAULT_WORLD_SETTINGS`)
54 **Status:** full
55 **Spec:** Global cadence, timers, and night darkness live in `world_live_settings` and apply as soon as an admin saves. The editor modal is categorised and scrollable, marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56 **Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57 57
58 58 ## Baked lighting
59 59
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64 64 ## World editor (server)
65 65
66 66 **Status:** full
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit world settings, and apply the pending revision. Marketplace/bank/spawner placement is later.
67 **Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace/bank/spawner placement is later.
68 68 **Code:** `server/src/editor/service.js`
69 69
70 70 ## World editor (client)
71 71
72 72 **Status:** full
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, open/closed, changelog, night preview slider, settings fields, save and Apply now. Marketplace placement waits on assets.
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
74 74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
75 75
76 76 ## Per-chunk changelog
@@ -136,7 +136,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136 136 ## Night shading
137 137
138 138 **Status:** full
139 **Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle.
139 **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.
140 140 **Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
141 141
142 142 ## FrameworkV3 client bootstrap
@@ -40,20 +40,20 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
40## Authored world and runtime state persistence
40## Authored world and runtime state persistence
41
41
42**Status:** full
42**Status:** full
43**Spec:** `world.sqlite` holds revisioned authored chunks and settings. `state.sqlite` holds accounts, characters, and runtime entity state. Databases live under `server/data/` and use Node's SQLite binding.
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`
44**Code:** `server/src/persistence/database.js`, `worldDb.js`, `stateDb.js`
45
45
46## World revisions and pending editor saves
46## World revisions and pending editor saves
47
47
48**Status:** partial
48**Status:** partial
49**Spec:** Editor saves write a pending world revision. The running process stays pinned to the revision loaded at startup until an admin **Apply now** (in-process reload). Midnight restart/Git deploy is not implemented yet.
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`)
50**Code:** `server/src/persistence/worldDb.js` (`ensurePendingRevision`, `promotePendingRevision`)
51
51
52## World settings
52## World settings
53
53
54**Status:** partial
54**Status:** full
55**Spec:** Global cadence and timers live in authored `world_settings` per revision, with design defaults. Walk speed and tick rate can be saved from the editor. Other timers are stored but not all are consumed yet.
55**Spec:** Global cadence, timers, and night darkness live in `world_live_settings` and apply as soon as an admin saves. The editor modal is categorised and scrollable, marks dirty fields, writes only those fields, and shows a settings edit log (who/when/from/to). Chunk Apply now is not required. Some timers are stored before the systems that consume them exist.
56**Code:** `server/src/persistence/worldDb.js`, `shared/protocol/constants.js` (`DEFAULT_WORLD_SETTINGS`)
56**Code:** `shared/definitions/worldSettings.js`, `server/src/persistence/worldDb.js` (`world_live_settings`, `world_settings_edit_log`), `server/src/editor/service.js` (`loadSettings`, `saveSettings`), `client/src/editor/settingsModal.js`
57
57
58## Baked lighting
58## Baked lighting
59
59
@@ -64,13 +64,13 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
64## World editor (server)
64## World editor (server)
65
65
66**Status:** full
66**Status:** full
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit world settings, and apply the pending revision. Marketplace/bank/spawner placement is later.
67**Spec:** Admin API to load/save a chunk, toggle open/closed, paint ground/blocks, write changelog bullets, edit live world settings, and apply the pending map revision. Marketplace/bank/spawner placement is later.
68**Code:** `server/src/editor/service.js`
68**Code:** `server/src/editor/service.js`
69
69
70## World editor (client)
70## World editor (client)
71
71
72**Status:** full
72**Status:** full
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, open/closed, changelog, night preview slider, settings fields, save and Apply now. Marketplace placement waits on assets.
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
74**Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
75
75
76## Per-chunk changelog
76## Per-chunk changelog
@@ -136,7 +136,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
136## Night shading
136## Night shading
137
137
138**Status:** full
138**Status:** full
139**Spec:** World time is server time minus 1200 years. At night, unlit tiles are darkened and reachable tiles use the baked 0–255 intensity so a torch fades tile-by-tile instead of a hard circle.
139**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.
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
140**Code:** `client/src/render/worldView.js` (`nightFactor`, `#updateShade`), `server/src/simulation/simulation.js` (`worldTime`)
141
141
142## FrameworkV3 client bootstrap
142## FrameworkV3 client bootstrap
server/src/editor/service.js +40 −7
@@ -5,6 +5,7 @@ import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob
5 5 import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6 6 import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7 7 import { closedNeighborEdges } from "../world/chunkFlags.js";
8 import { coerceSettingValue, diffSettings, allSettingFields } from "../../../shared/definitions/worldSettings.js";
8 9
9 10 export class EditorService
10 11 {
@@ -16,7 +17,7 @@ export class EditorService
16 17 loadChunk (chunkX, chunkY)
17 18 {
18 19 const revisionId = this.worldDb.getEditorRevisionId();
19 const settings = this.worldDb.getSettings(revisionId);
20 const settings = this.worldDb.getLiveSettings();
20 21 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
21 22 const data = row
22 23 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
@@ -54,7 +55,7 @@ export class EditorService
54 55
55 56 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
56 57 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
57 const settings = this.worldDb.getSettings(revisionId);
58 const settings = this.worldDb.getLiveSettings();
58 59 const baked = bakeLightMaps(
59 60 chunkX,
60 61 chunkY,
@@ -86,13 +87,45 @@ export class EditorService
86 87 return this.loadChunk(chunkX, chunkY);
87 88 }
88 89
90 loadSettings ()
91 {
92 return {
93 settings: this.worldDb.getLiveSettings(),
94 changelog: this.worldDb.listSettingsChangelog()
95 };
96 }
97
89 98 saveSettings (partial, editorAdminId)
90 99 {
91 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
92 const current = this.worldDb.getSettings(revisionId);
93 const next = { ...current, ...partial };
94 this.worldDb.saveSettings(revisionId, next);
95 return { revisionId, settings: next };
100 const current = this.worldDb.getLiveSettings();
101 const next = { ...current };
102 for (const field of allSettingFields())
103 {
104 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
105 { continue; }
106 const value = coerceSettingValue(field, partial[field.key]);
107 if (value == null)
108 { continue; }
109 next[field.key] = value;
110 }
111 const { bullets, changed } = diffSettings(current, next);
112 if (Object.keys(changed).length === 0)
113 {
114 return {
115 settings: current,
116 changelog: this.worldDb.listSettingsChangelog(),
117 changed: {}
118 };
119 }
120 const settings = { ...current, ...changed };
121 this.worldDb.saveLiveSettings(settings, editorAdminId);
122 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
123 return {
124 settings,
125 changelog: this.worldDb.listSettingsChangelog(),
126 changed,
127 diffEntries: bullets
128 };
96 129 }
97 130
98 131 applyPendingRevision ()
@@ -5,6 +5,7 @@ import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
5import { BLOCK_DEFINITIONS } from "../../../shared/definitions/tiles.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
6import { bakeLightMaps, maxDefinitionLightRange } from "../lighting/baker.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
7import { closedNeighborEdges } from "../world/chunkFlags.js";
8import { coerceSettingValue, diffSettings, allSettingFields } from "../../../shared/definitions/worldSettings.js";
8
9
9export class EditorService
10export class EditorService
10{
11{
@@ -16,7 +17,7 @@ export class EditorService
16 loadChunk (chunkX, chunkY)
17 loadChunk (chunkX, chunkY)
17 {
18 {
18 const revisionId = this.worldDb.getEditorRevisionId();
19 const revisionId = this.worldDb.getEditorRevisionId();
19 const settings = this.worldDb.getSettings(revisionId);
20 const settings = this.worldDb.getLiveSettings();
20 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
21 const row = this.worldDb.getChunkVersion(chunkX, chunkY, revisionId);
21 const data = row
22 const data = row
22 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
23 ? decodeChunkBlob(row.data_blob, settings.defaultGroundTypeId)
@@ -54,7 +55,7 @@ export class EditorService
54
55
55 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
56 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
56 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
57 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
57 const settings = this.worldDb.getSettings(revisionId);
58 const settings = this.worldDb.getLiveSettings();
58 const baked = bakeLightMaps(
59 const baked = bakeLightMaps(
59 chunkX,
60 chunkX,
60 chunkY,
61 chunkY,
@@ -86,13 +87,45 @@ export class EditorService
86 return this.loadChunk(chunkX, chunkY);
87 return this.loadChunk(chunkX, chunkY);
87 }
88 }
88
89
90 loadSettings ()
91 {
92 return {
93 settings: this.worldDb.getLiveSettings(),
94 changelog: this.worldDb.listSettingsChangelog()
95 };
96 }
97
89 saveSettings (partial, editorAdminId)
98 saveSettings (partial, editorAdminId)
90 {
99 {
91 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
100 const current = this.worldDb.getLiveSettings();
92 const current = this.worldDb.getSettings(revisionId);
101 const next = { ...current };
93 const next = { ...current, ...partial };
102 for (const field of allSettingFields())
94 this.worldDb.saveSettings(revisionId, next);
103 {
95 return { revisionId, settings: next };
104 if (!Object.prototype.hasOwnProperty.call(partial, field.key))
105 { continue; }
106 const value = coerceSettingValue(field, partial[field.key]);
107 if (value == null)
108 { continue; }
109 next[field.key] = value;
110 }
111 const { bullets, changed } = diffSettings(current, next);
112 if (Object.keys(changed).length === 0)
113 {
114 return {
115 settings: current,
116 changelog: this.worldDb.listSettingsChangelog(),
117 changed: {}
118 };
119 }
120 const settings = { ...current, ...changed };
121 this.worldDb.saveLiveSettings(settings, editorAdminId);
122 this.worldDb.appendSettingsChangelog(editorAdminId, bullets);
123 return {
124 settings,
125 changelog: this.worldDb.listSettingsChangelog(),
126 changed,
127 diffEntries: bullets
128 };
96 }
129 }
97
130
98 applyPendingRevision ()
131 applyPendingRevision ()
server/src/gateway/websocket.js +19 −4
@@ -113,12 +113,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
113 113 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
114 114 });
115 115 break;
116 case MessageType.editorLoadSettings:
117 requireAdmin(session);
118 send(session, { type: MessageType.editorSettings, ...editor.loadSettings() });
119 break;
116 120 case MessageType.editorSaveSettings:
117 121 requireAdmin(session);
118 send(session, {
119 type: MessageType.editorChunk,
120 settingsSaved: editor.saveSettings(message.settings ?? {}, session.authSubject)
121 });
122 {
123 const saved = editor.saveSettings(message.settings ?? {}, session.authSubject);
124 simulation.applySettings(saved.settings);
125 broadcastStatus();
126 broadcastSettings(saved);
127 }
122 128 break;
123 129 case MessageType.editorApplyRevision:
124 130 requireAdmin(session);
@@ -252,6 +258,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
252 258 }
253 259 }
254 260
261 function broadcastSettings (payload)
262 {
263 for (const session of sessions.values())
264 {
265 if (session.account.is_admin)
266 { send(session, { type: MessageType.editorSettings, ...payload }); }
267 }
268 }
269
255 270 function onTickResult (result)
256 271 {
257 272 for (const event of result.events)
@@ -113,12 +113,18 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
113 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
113 ...editor.saveChunk(message.chunkX | 0, message.chunkY | 0, message.draft, session.authSubject)
114 });
114 });
115 break;
115 break;
116 case MessageType.editorLoadSettings:
117 requireAdmin(session);
118 send(session, { type: MessageType.editorSettings, ...editor.loadSettings() });
119 break;
116 case MessageType.editorSaveSettings:
120 case MessageType.editorSaveSettings:
117 requireAdmin(session);
121 requireAdmin(session);
118 send(session, {
122 {
119 type: MessageType.editorChunk,
123 const saved = editor.saveSettings(message.settings ?? {}, session.authSubject);
120 settingsSaved: editor.saveSettings(message.settings ?? {}, session.authSubject)
124 simulation.applySettings(saved.settings);
121 });
125 broadcastStatus();
126 broadcastSettings(saved);
127 }
122 break;
128 break;
123 case MessageType.editorApplyRevision:
129 case MessageType.editorApplyRevision:
124 requireAdmin(session);
130 requireAdmin(session);
@@ -252,6 +258,15 @@ export function attachGateway ({ httpServer, auth, stateDb, characters, editor,
252 }
258 }
253 }
259 }
254
260
261 function broadcastSettings (payload)
262 {
263 for (const session of sessions.values())
264 {
265 if (session.account.is_admin)
266 { send(session, { type: MessageType.editorSettings, ...payload }); }
267 }
268 }
269
255 function onTickResult (result)
270 function onTickResult (result)
256 {
271 {
257 for (const event of result.events)
272 for (const event of result.events)
server/src/index.js +13 −7
@@ -21,13 +21,19 @@ const auth = new StubAuth();
21 21 const httpServer = createHttpServer(rootDir);
22 22 const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
23 23
24 const tickMs = Math.round(1000 / simulation.settings.simulationTickHz);
25 const tickTimer = setInterval(() =>
24 let tickTimer = null;
25 function scheduleTick ()
26 26 {
27 characters.processDueDeletions();
28 const result = simulation.step();
29 gateway.onTickResult(result);
30 }, tickMs);
27 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
28 tickTimer = setTimeout(() =>
29 {
30 characters.processDueDeletions();
31 const result = simulation.step();
32 gateway.onTickResult(result);
33 scheduleTick();
34 }, tickMs);
35 }
36 scheduleTick();
31 37
32 38 httpServer.listen(port, () =>
33 39 {
@@ -37,7 +43,7 @@ httpServer.listen(port, () =>
37 43
38 44 function shutdown ()
39 45 {
40 clearInterval(tickTimer);
46 clearTimeout(tickTimer);
41 47 for (const session of gateway.sessions.values())
42 48 {
43 49 if (session.characterId)
@@ -21,13 +21,19 @@ const auth = new StubAuth();
21const httpServer = createHttpServer(rootDir);
21const httpServer = createHttpServer(rootDir);
22const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
22const gateway = attachGateway({ httpServer, auth, stateDb, characters, editor, simulation });
23
23
24const tickMs = Math.round(1000 / simulation.settings.simulationTickHz);
24let tickTimer = null;
25const tickTimer = setInterval(() =>
25function scheduleTick ()
26{
26{
27 characters.processDueDeletions();
27 const tickMs = Math.max(16, Math.round(1000 / (simulation.settings.simulationTickHz || 20)));
28 const result = simulation.step();
28 tickTimer = setTimeout(() =>
29 gateway.onTickResult(result);
29 {
30}, tickMs);
30 characters.processDueDeletions();
31 const result = simulation.step();
32 gateway.onTickResult(result);
33 scheduleTick();
34 }, tickMs);
35}
36scheduleTick();
31
37
32httpServer.listen(port, () =>
38httpServer.listen(port, () =>
33{
39{
@@ -37,7 +43,7 @@ httpServer.listen(port, () =>
37
43
38function shutdown ()
44function shutdown ()
39{
45{
40 clearInterval(tickTimer);
46 clearTimeout(tickTimer);
41 for (const session of gateway.sessions.values())
47 for (const session of gateway.sessions.values())
42 {
48 {
43 if (session.characterId)
49 if (session.characterId)
server/src/persistence/worldDb.js +68 −0
@@ -37,6 +37,20 @@ CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
37 37 edited_at INTEGER NOT NULL,
38 38 diff_entries TEXT NOT NULL
39 39 );
40
41 CREATE TABLE IF NOT EXISTS world_live_settings (
42 id INTEGER PRIMARY KEY CHECK (id = 1),
43 settings_blob TEXT NOT NULL,
44 updated_at INTEGER NOT NULL,
45 updated_by TEXT NOT NULL
46 );
47
48 CREATE TABLE IF NOT EXISTS world_settings_edit_log (
49 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
50 editor_admin_id TEXT NOT NULL,
51 edited_at INTEGER NOT NULL,
52 diff_entries TEXT NOT NULL
53 );
40 54 `;
41 55
42 56 export class WorldDatabase
@@ -46,6 +60,7 @@ export class WorldDatabase
46 60 this.db = openDatabase(filePath);
47 61 this.db.exec(WORLD_SCHEMA);
48 62 this.#ensureInitialRevision();
63 this.#ensureLiveSettings();
49 64 }
50 65
51 66 #ensureInitialRevision ()
@@ -69,6 +84,59 @@ export class WorldDatabase
69 84 });
70 85 }
71 86
87 #ensureLiveSettings ()
88 {
89 const existing = this.db.prepare("SELECT id FROM world_live_settings WHERE id = 1").get();
90 if (existing)
91 { return; }
92
93 const settings = this.getSettings(this.getActiveRevisionId());
94 this.db.prepare(
95 "INSERT INTO world_live_settings (id, settings_blob, updated_at, updated_by) VALUES (1, ?, ?, ?)"
96 ).run(JSON.stringify(settings), Date.now(), "system");
97 }
98
99 getLiveSettings ()
100 {
101 this.#ensureLiveSettings();
102 const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
103 return row
104 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
105 : { ...DEFAULT_WORLD_SETTINGS };
106 }
107
108 saveLiveSettings (settings, updatedBy)
109 {
110 this.db.prepare(`
111 INSERT INTO world_live_settings (id, settings_blob, updated_at, updated_by)
112 VALUES (1, ?, ?, ?)
113 ON CONFLICT(id) DO UPDATE SET
114 settings_blob = excluded.settings_blob,
115 updated_at = excluded.updated_at,
116 updated_by = excluded.updated_by
117 `).run(JSON.stringify(settings), Date.now(), updatedBy);
118 }
119
120 appendSettingsChangelog (editorAdminId, diffEntries)
121 {
122 this.db.prepare(`
123 INSERT INTO world_settings_edit_log (editor_admin_id, edited_at, diff_entries)
124 VALUES (?, ?, ?)
125 `).run(editorAdminId, Date.now(), JSON.stringify(diffEntries));
126 }
127
128 listSettingsChangelog ()
129 {
130 return this.db.prepare(`
131 SELECT log_id, editor_admin_id, edited_at, diff_entries
132 FROM world_settings_edit_log
133 ORDER BY edited_at ASC, log_id ASC
134 `).all().map((row) => ({
135 ...row,
136 diffEntries: JSON.parse(row.diff_entries)
137 }));
138 }
139
72 140 getActiveRevisionId ()
73 141 {
74 142 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'active_revision'").get()?.value ?? null;
@@ -37,6 +37,20 @@ CREATE TABLE IF NOT EXISTS world_chunk_edit_log (
37 edited_at INTEGER NOT NULL,
37 edited_at INTEGER NOT NULL,
38 diff_entries TEXT NOT NULL
38 diff_entries TEXT NOT NULL
39);
39);
40
41CREATE TABLE IF NOT EXISTS world_live_settings (
42 id INTEGER PRIMARY KEY CHECK (id = 1),
43 settings_blob TEXT NOT NULL,
44 updated_at INTEGER NOT NULL,
45 updated_by TEXT NOT NULL
46);
47
48CREATE TABLE IF NOT EXISTS world_settings_edit_log (
49 log_id INTEGER PRIMARY KEY AUTOINCREMENT,
50 editor_admin_id TEXT NOT NULL,
51 edited_at INTEGER NOT NULL,
52 diff_entries TEXT NOT NULL
53);
40`;
54`;
41
55
42export class WorldDatabase
56export class WorldDatabase
@@ -46,6 +60,7 @@ export class WorldDatabase
46 this.db = openDatabase(filePath);
60 this.db = openDatabase(filePath);
47 this.db.exec(WORLD_SCHEMA);
61 this.db.exec(WORLD_SCHEMA);
48 this.#ensureInitialRevision();
62 this.#ensureInitialRevision();
63 this.#ensureLiveSettings();
49 }
64 }
50
65
51 #ensureInitialRevision ()
66 #ensureInitialRevision ()
@@ -69,6 +84,59 @@ export class WorldDatabase
69 });
84 });
70 }
85 }
71
86
87 #ensureLiveSettings ()
88 {
89 const existing = this.db.prepare("SELECT id FROM world_live_settings WHERE id = 1").get();
90 if (existing)
91 { return; }
92
93 const settings = this.getSettings(this.getActiveRevisionId());
94 this.db.prepare(
95 "INSERT INTO world_live_settings (id, settings_blob, updated_at, updated_by) VALUES (1, ?, ?, ?)"
96 ).run(JSON.stringify(settings), Date.now(), "system");
97 }
98
99 getLiveSettings ()
100 {
101 this.#ensureLiveSettings();
102 const row = this.db.prepare("SELECT settings_blob FROM world_live_settings WHERE id = 1").get();
103 return row
104 ? { ...DEFAULT_WORLD_SETTINGS, ...JSON.parse(row.settings_blob) }
105 : { ...DEFAULT_WORLD_SETTINGS };
106 }
107
108 saveLiveSettings (settings, updatedBy)
109 {
110 this.db.prepare(`
111 INSERT INTO world_live_settings (id, settings_blob, updated_at, updated_by)
112 VALUES (1, ?, ?, ?)
113 ON CONFLICT(id) DO UPDATE SET
114 settings_blob = excluded.settings_blob,
115 updated_at = excluded.updated_at,
116 updated_by = excluded.updated_by
117 `).run(JSON.stringify(settings), Date.now(), updatedBy);
118 }
119
120 appendSettingsChangelog (editorAdminId, diffEntries)
121 {
122 this.db.prepare(`
123 INSERT INTO world_settings_edit_log (editor_admin_id, edited_at, diff_entries)
124 VALUES (?, ?, ?)
125 `).run(editorAdminId, Date.now(), JSON.stringify(diffEntries));
126 }
127
128 listSettingsChangelog ()
129 {
130 return this.db.prepare(`
131 SELECT log_id, editor_admin_id, edited_at, diff_entries
132 FROM world_settings_edit_log
133 ORDER BY edited_at ASC, log_id ASC
134 `).all().map((row) => ({
135 ...row,
136 diffEntries: JSON.parse(row.diff_entries)
137 }));
138 }
139
72 getActiveRevisionId ()
140 getActiveRevisionId ()
73 {
141 {
74 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'active_revision'").get()?.value ?? null;
142 return this.db.prepare("SELECT value FROM world_meta WHERE key = 'active_revision'").get()?.value ?? null;
server/src/simulation/simulation.js +7 −2
@@ -18,15 +18,20 @@ export class Simulation
18 18 this.commandQueue = [];
19 19 this.movementTickCounter = 0;
20 20 this.activeRevisionId = worldDb.getActiveRevisionId();
21 this.settings = worldDb.getSettings(this.activeRevisionId);
21 this.settings = worldDb.getLiveSettings();
22 22 this.tickIndex = 0;
23 23 this.reloadWorld();
24 24 }
25 25
26 applySettings (settings)
27 {
28 this.settings = { ...this.settings, ...settings };
29 }
30
26 31 reloadWorld ()
27 32 {
28 33 this.activeRevisionId = this.worldDb.getActiveRevisionId();
29 this.settings = this.worldDb.getSettings(this.activeRevisionId);
34 this.settings = this.worldDb.getLiveSettings();
30 35 this.chunks.clear();
31 36 for (const entity of this.ecs.query("position"))
32 37 {
@@ -18,15 +18,20 @@ export class Simulation
18 this.commandQueue = [];
18 this.commandQueue = [];
19 this.movementTickCounter = 0;
19 this.movementTickCounter = 0;
20 this.activeRevisionId = worldDb.getActiveRevisionId();
20 this.activeRevisionId = worldDb.getActiveRevisionId();
21 this.settings = worldDb.getSettings(this.activeRevisionId);
21 this.settings = worldDb.getLiveSettings();
22 this.tickIndex = 0;
22 this.tickIndex = 0;
23 this.reloadWorld();
23 this.reloadWorld();
24 }
24 }
25
25
26 applySettings (settings)
27 {
28 this.settings = { ...this.settings, ...settings };
29 }
30
26 reloadWorld ()
31 reloadWorld ()
27 {
32 {
28 this.activeRevisionId = this.worldDb.getActiveRevisionId();
33 this.activeRevisionId = this.worldDb.getActiveRevisionId();
29 this.settings = this.worldDb.getSettings(this.activeRevisionId);
34 this.settings = this.worldDb.getLiveSettings();
30 this.chunks.clear();
35 this.chunks.clear();
31 for (const entity of this.ecs.query("position"))
36 for (const entity of this.ecs.query("position"))
32 {
37 {
server/tests/live-settings.test.js added +37 −0
@@ -0,0 +1,37 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { mkdtempSync } 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 { EditorService } from "../src/editor/service.js";
8
9 function tempWorld ()
10 {
11 const dir = mkdtempSync(join(tmpdir(), "mmo-settings-"));
12 return new WorldDatabase(join(dir, "world.sqlite"));
13 }
14
15 test("live settings save writes only changed fields and appends a log", () =>
16 {
17 const worldDb = tempWorld();
18 try
19 {
20 const editor = new EditorService(worldDb);
21 const first = editor.saveSettings({ nightDarkness: 0.4 }, "admin-1");
22 assert.equal(first.settings.nightDarkness, 0.4);
23 assert.deepEqual(first.changed, { nightDarkness: 0.4 });
24 assert.equal(worldDb.getLiveSettings().nightDarkness, 0.4);
25 assert.equal(first.changelog.length, 1);
26 assert.equal(first.changelog[0].editor_admin_id, "admin-1");
27 assert.match(first.changelog[0].diffEntries[0], /Night darkness/);
28 assert.match(first.changelog[0].diffEntries[0], /0.72/);
29 assert.match(first.changelog[0].diffEntries[0], /0.4/);
30
31 const noop = editor.saveSettings({ nightDarkness: 0.4 }, "admin-2");
32 assert.deepEqual(noop.changed, {});
33 assert.equal(noop.changelog.length, 1);
34 }
35 finally
36 { worldDb.close(); }
37 });
@@ -0,0 +1,37 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { mkdtempSync } from "node:fs";
4import { tmpdir } from "node:os";
5import { join } from "node:path";
6import { WorldDatabase } from "../src/persistence/worldDb.js";
7import { EditorService } from "../src/editor/service.js";
8
9function tempWorld ()
10{
11 const dir = mkdtempSync(join(tmpdir(), "mmo-settings-"));
12 return new WorldDatabase(join(dir, "world.sqlite"));
13}
14
15test("live settings save writes only changed fields and appends a log", () =>
16{
17 const worldDb = tempWorld();
18 try
19 {
20 const editor = new EditorService(worldDb);
21 const first = editor.saveSettings({ nightDarkness: 0.4 }, "admin-1");
22 assert.equal(first.settings.nightDarkness, 0.4);
23 assert.deepEqual(first.changed, { nightDarkness: 0.4 });
24 assert.equal(worldDb.getLiveSettings().nightDarkness, 0.4);
25 assert.equal(first.changelog.length, 1);
26 assert.equal(first.changelog[0].editor_admin_id, "admin-1");
27 assert.match(first.changelog[0].diffEntries[0], /Night darkness/);
28 assert.match(first.changelog[0].diffEntries[0], /0.72/);
29 assert.match(first.changelog[0].diffEntries[0], /0.4/);
30
31 const noop = editor.saveSettings({ nightDarkness: 0.4 }, "admin-2");
32 assert.deepEqual(noop.changed, {});
33 assert.equal(noop.changelog.length, 1);
34 }
35 finally
36 { worldDb.close(); }
37});
server/tests/settings-diff.test.js added +16 −0
@@ -0,0 +1,16 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { diffSettings } from "../../shared/definitions/worldSettings.js";
4
5 test("settings diffs only mention keys that actually changed", () =>
6 {
7 const { bullets, changed } = diffSettings(
8 { walkTilesPerSecond: 2, nightDarkness: 0.72 },
9 { walkTilesPerSecond: 3, nightDarkness: 0.72, extra: 1 }
10 );
11 assert.deepEqual(changed, { walkTilesPerSecond: 3 });
12 assert.equal(bullets.length, 1);
13 assert.match(bullets[0], /Walk speed/);
14 assert.match(bullets[0], /2/);
15 assert.match(bullets[0], /3/);
16 });
@@ -0,0 +1,16 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { diffSettings } from "../../shared/definitions/worldSettings.js";
4
5test("settings diffs only mention keys that actually changed", () =>
6{
7 const { bullets, changed } = diffSettings(
8 { walkTilesPerSecond: 2, nightDarkness: 0.72 },
9 { walkTilesPerSecond: 3, nightDarkness: 0.72, extra: 1 }
10 );
11 assert.deepEqual(changed, { walkTilesPerSecond: 3 });
12 assert.equal(bullets.length, 1);
13 assert.match(bullets[0], /Walk speed/);
14 assert.match(bullets[0], /2/);
15 assert.match(bullets[0], /3/);
16});
shared/definitions/worldSettings.js added +150 −0
@@ -0,0 +1,150 @@
1 export const WORLD_SETTING_CATEGORIES = [
2 {
3 id: "movement",
4 label: "Movement",
5 fields: [
6 {
7 key: "walkTilesPerSecond",
8 label: "Walk speed (tiles/s)",
9 hint: "Run is always double this value.",
10 type: "number",
11 min: 0.25,
12 max: 20,
13 step: 0.25
14 }
15 ]
16 },
17 {
18 id: "simulation",
19 label: "Simulation",
20 fields: [
21 {
22 key: "simulationTickHz",
23 label: "Simulation tick (Hz)",
24 hint: "How often the server steps. Movement still uses the walk/run cadence.",
25 type: "number",
26 min: 5,
27 max: 60,
28 step: 1
29 },
30 {
31 key: "regionUnloadGracePeriodMs",
32 label: "Region unload grace (ms)",
33 hint: "How long a region stays resident after the last player leaves.",
34 type: "number",
35 min: 0,
36 step: 1000
37 }
38 ]
39 },
40 {
41 id: "lighting",
42 label: "Lighting",
43 fields: [
44 {
45 key: "nightDarkness",
46 label: "Night darkness",
47 hint: "How dark unlit tiles become at night. 0 is no extra darkening, 1 is fully black.",
48 type: "range",
49 min: 0,
50 max: 1,
51 step: 0.01
52 }
53 ]
54 },
55 {
56 id: "world",
57 label: "World",
58 fields: [
59 {
60 key: "defaultGroundTypeId",
61 label: "Default ground type id",
62 hint: "Ground used for never-edited chunks (1 = grass).",
63 type: "number",
64 min: 1,
65 step: 1
66 }
67 ]
68 },
69 {
70 id: "characters",
71 label: "Characters",
72 fields: [
73 {
74 key: "characterDeletionDelayMs",
75 label: "Character deletion delay (ms)",
76 hint: "Wait time after a character is marked for deletion.",
77 type: "number",
78 min: 0,
79 step: 1000
80 }
81 ]
82 },
83 {
84 id: "economy",
85 label: "Economy & items",
86 fields: [
87 {
88 key: "shopPriceLerpDurationMs",
89 label: "Shop price lerp (ms)",
90 hint: "How long shop prices take to move toward the last market sale.",
91 type: "number",
92 min: 0,
93 step: 1000
94 },
95 {
96 key: "groundItemDespawnDurationMs",
97 label: "Ground item despawn (ms)",
98 hint: "How long dropped items remain on the ground.",
99 type: "number",
100 min: 0,
101 step: 1000
102 }
103 ]
104 }
105 ];
106
107 export function allSettingFields ()
108 {
109 return WORLD_SETTING_CATEGORIES.flatMap((category) => category.fields);
110 }
111
112 export function formatSettingValue (value)
113 {
114 if (typeof value === "number" && !Number.isInteger(value))
115 { return String(Math.round(value * 1000) / 1000); }
116 return String(value);
117 }
118
119 export function coerceSettingValue (field, raw)
120 {
121 if (raw === "" || raw == null)
122 { return null; }
123 const value = Number(raw);
124 if (!Number.isFinite(value))
125 { return null; }
126 let next = value;
127 if (field.min != null)
128 { next = Math.max(field.min, next); }
129 if (field.max != null)
130 { next = Math.min(field.max, next); }
131 return next;
132 }
133
134 export function diffSettings (previous, next, fields = allSettingFields())
135 {
136 const bullets = [];
137 const changed = {};
138 for (const field of fields)
139 {
140 if (!Object.prototype.hasOwnProperty.call(next, field.key))
141 { continue; }
142 const from = previous[field.key];
143 const to = next[field.key];
144 if (from === to)
145 { continue; }
146 changed[field.key] = to;
147 bullets.push(`${field.label} changed from ${formatSettingValue(from)} to ${formatSettingValue(to)}.`);
148 }
149 return { bullets, changed };
150 }
@@ -0,0 +1,150 @@
1export const WORLD_SETTING_CATEGORIES = [
2 {
3 id: "movement",
4 label: "Movement",
5 fields: [
6 {
7 key: "walkTilesPerSecond",
8 label: "Walk speed (tiles/s)",
9 hint: "Run is always double this value.",
10 type: "number",
11 min: 0.25,
12 max: 20,
13 step: 0.25
14 }
15 ]
16 },
17 {
18 id: "simulation",
19 label: "Simulation",
20 fields: [
21 {
22 key: "simulationTickHz",
23 label: "Simulation tick (Hz)",
24 hint: "How often the server steps. Movement still uses the walk/run cadence.",
25 type: "number",
26 min: 5,
27 max: 60,
28 step: 1
29 },
30 {
31 key: "regionUnloadGracePeriodMs",
32 label: "Region unload grace (ms)",
33 hint: "How long a region stays resident after the last player leaves.",
34 type: "number",
35 min: 0,
36 step: 1000
37 }
38 ]
39 },
40 {
41 id: "lighting",
42 label: "Lighting",
43 fields: [
44 {
45 key: "nightDarkness",
46 label: "Night darkness",
47 hint: "How dark unlit tiles become at night. 0 is no extra darkening, 1 is fully black.",
48 type: "range",
49 min: 0,
50 max: 1,
51 step: 0.01
52 }
53 ]
54 },
55 {
56 id: "world",
57 label: "World",
58 fields: [
59 {
60 key: "defaultGroundTypeId",
61 label: "Default ground type id",
62 hint: "Ground used for never-edited chunks (1 = grass).",
63 type: "number",
64 min: 1,
65 step: 1
66 }
67 ]
68 },
69 {
70 id: "characters",
71 label: "Characters",
72 fields: [
73 {
74 key: "characterDeletionDelayMs",
75 label: "Character deletion delay (ms)",
76 hint: "Wait time after a character is marked for deletion.",
77 type: "number",
78 min: 0,
79 step: 1000
80 }
81 ]
82 },
83 {
84 id: "economy",
85 label: "Economy & items",
86 fields: [
87 {
88 key: "shopPriceLerpDurationMs",
89 label: "Shop price lerp (ms)",
90 hint: "How long shop prices take to move toward the last market sale.",
91 type: "number",
92 min: 0,
93 step: 1000
94 },
95 {
96 key: "groundItemDespawnDurationMs",
97 label: "Ground item despawn (ms)",
98 hint: "How long dropped items remain on the ground.",
99 type: "number",
100 min: 0,
101 step: 1000
102 }
103 ]
104 }
105];
106
107export function allSettingFields ()
108{
109 return WORLD_SETTING_CATEGORIES.flatMap((category) => category.fields);
110}
111
112export function formatSettingValue (value)
113{
114 if (typeof value === "number" && !Number.isInteger(value))
115 { return String(Math.round(value * 1000) / 1000); }
116 return String(value);
117}
118
119export function coerceSettingValue (field, raw)
120{
121 if (raw === "" || raw == null)
122 { return null; }
123 const value = Number(raw);
124 if (!Number.isFinite(value))
125 { return null; }
126 let next = value;
127 if (field.min != null)
128 { next = Math.max(field.min, next); }
129 if (field.max != null)
130 { next = Math.min(field.max, next); }
131 return next;
132}
133
134export function diffSettings (previous, next, fields = allSettingFields())
135{
136 const bullets = [];
137 const changed = {};
138 for (const field of fields)
139 {
140 if (!Object.prototype.hasOwnProperty.call(next, field.key))
141 { continue; }
142 const from = previous[field.key];
143 const to = next[field.key];
144 if (from === to)
145 { continue; }
146 changed[field.key] = to;
147 bullets.push(`${field.label} changed from ${formatSettingValue(from)} to ${formatSettingValue(to)}.`);
148 }
149 return { bullets, changed };
150}
shared/protocol/constants.js +4 −1
@@ -13,7 +13,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
13 13 groundItemDespawnDurationMs: 10 * 60 * 1000,
14 14 regionUnloadGracePeriodMs: 30 * 1000,
15 15 defaultGroundTypeId: 1,
16 characterDeletionDelayMs: 24 * 60 * 60 * 1000
16 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
17 nightDarkness: 0.72
17 18 });
18 19
19 20 export const GAIT = Object.freeze({
@@ -49,6 +50,8 @@ export const MessageType = Object.freeze({
49 50 editorChunk: "EDITOR_CHUNK",
50 51 editorSaveChunk: "EDITOR_SAVE_CHUNK",
51 52 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
53 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
54 editorSettings: "EDITOR_SETTINGS",
52 55 editorApplyRevision: "EDITOR_APPLY_REVISION",
53 56 editorChangelog: "EDITOR_CHANGELOG"
54 57 });
@@ -13,7 +13,8 @@ export const DEFAULT_WORLD_SETTINGS = Object.freeze({
13 groundItemDespawnDurationMs: 10 * 60 * 1000,
13 groundItemDespawnDurationMs: 10 * 60 * 1000,
14 regionUnloadGracePeriodMs: 30 * 1000,
14 regionUnloadGracePeriodMs: 30 * 1000,
15 defaultGroundTypeId: 1,
15 defaultGroundTypeId: 1,
16 characterDeletionDelayMs: 24 * 60 * 60 * 1000
16 characterDeletionDelayMs: 24 * 60 * 60 * 1000,
17 nightDarkness: 0.72
17});
18});
18
19
19export const GAIT = Object.freeze({
20export const GAIT = Object.freeze({
@@ -49,6 +50,8 @@ export const MessageType = Object.freeze({
49 editorChunk: "EDITOR_CHUNK",
50 editorChunk: "EDITOR_CHUNK",
50 editorSaveChunk: "EDITOR_SAVE_CHUNK",
51 editorSaveChunk: "EDITOR_SAVE_CHUNK",
51 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
52 editorSaveSettings: "EDITOR_SAVE_SETTINGS",
53 editorLoadSettings: "EDITOR_LOAD_SETTINGS",
54 editorSettings: "EDITOR_SETTINGS",
52 editorApplyRevision: "EDITOR_APPLY_REVISION",
55 editorApplyRevision: "EDITOR_APPLY_REVISION",
53 editorChangelog: "EDITOR_CHANGELOG"
56 editorChangelog: "EDITOR_CHANGELOG"
54});
57});
tile_mmo_server_technical_design_v0.6.md +65 −30
@@ -1,13 +1,13 @@
1 1 ---
2 2 title: Tile MMO Server Technical Design
3 version: 0.12
3 version: 0.13
4 4 status: proposed
5 5 format: living-design-document
6 6 ---
7 7
8 8 # Tile MMO Server Technical Design
9 9
10 **Version:** 0.12
10 **Version:** 0.13
11 11 **Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12 12 **Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13 13
@@ -63,10 +63,11 @@ format: living-design-document
63 63
64 64 - Authoritative movement is tile-to-tile at a **global** walk/run cadence
65 65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
66 that cadence and other tick timers in a world-settings modal. World
66 that cadence and other tick timers in a world-settings modal. Saving
67 those settings applies immediately to the live world. World
67 68 calendar time is server time minus 1200 years. At night the client
68 darkens unlit tiles; static light reach is baked by raycast when a
69 chunk is saved.
69 darkens unlit tiles (how dark is a world setting); static light reach
70 is baked by raycast when a chunk is saved.
70 71
71 72 - Give every player a 32-slot inventory in which stackable items occupy a
72 73 single slot, and treat dropped items as temporary, non-blocking ground
@@ -340,7 +341,7 @@ Use two SQLite databases with different responsibilities.
340 341
341 342 | **Database** | **Responsibility** |
342 343 |--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
343 | world.sqlite | Admin-authored ground tiles, block tiles, light maps, world settings, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
344 | world.sqlite | Admin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
344 345 | state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
345 346
346 347 This prevents editor authoring changes from becoming entangled with live
@@ -405,8 +406,10 @@ part of the normal player client.
405 406 Marketplace and light-emitting blocks (`lightRangeTiles`).
406 407
407 408 - Open a **world settings** modal for global tick timers and constants
408 (movement cadence, shop lerp duration, drop lifetime, and other values
409 listed in section 8.5).
409 (movement cadence, night darkness, shop lerp duration, drop lifetime,
410 and other values listed in section 8.5). The form is categorised and
411 scrollable; a settings edit log sits beside it. Edited rows are marked
412 until Save, and only those rows are written.
410 413
411 414 - Provide a **night-to-day slider** that only previews lighting; it does
412 415 not change live world time. Preview uses the same baked light maps as
@@ -427,15 +430,19 @@ player-centered play viewport in section 21.4.
427 430
428 431 ## 8.2 World editor save behaviour
429 432
430 Saving a chunk **or world settings** writes the authored result to
431 world.sqlite. It does not live-patch the currently running simulation.
432 Instead, the change creates or updates a pending world revision and
433 schedules a server restart for the next server-local midnight.
433 Saving a **chunk** writes the authored result to world.sqlite. It does
434 not live-patch the currently running simulation map. Instead, the change
435 creates or updates a pending world revision and schedules a server
436 restart for the next server-local midnight (or Apply now).
434 437
435 The running game remains pinned to the world revision selected at its
436 own startup. This avoids a dangerous mixed state where some loaded
437 chunks use old authored data and newly loaded chunks use newer editor
438 data.
438 Saving **world settings** is different: it updates the live settings
439 row immediately, records a settings changelog entry, and the running
440 process applies the new values without waiting for a world revision.
441
442 The running game remains pinned to the **chunk** world revision selected
443 at its own startup. This avoids a dangerous mixed state where some
444 loaded chunks use old authored data and newly loaded chunks use newer
445 editor data. Settings are not revision-pinned.
439 446
440 447 ## 8.3 Versioned authored chunks
441 448
@@ -463,7 +470,19 @@ pending_revision
463 470
464 471 world_settings
465 472 revision_id
466 settings_blob // walk speed, tick timers, shop lerp, drop TTL, ...
473 settings_blob // historical snapshot copied onto a map revision
474
475 world_live_settings
476 id // singleton row, always 1
477 settings_blob // the live, immediately applied settings
478 updated_at
479 updated_by
480
481 world_settings_edit_log
482 log_id
483 editor_admin_id
484 edited_at
485 diff_entries // which options changed, from/to
467 486
468 487 world_chunk_edit_log
469 488 log_id
@@ -509,12 +528,18 @@ they are regenerated on save (section 8.6).
509 528
510 529 ## 8.5 World settings
511 530
512 Global gameplay constants live in authored `world_settings` for the world
513 revision. They are **not** per-mob and **not** client-authored. Admins
514 edit them from a modal in the world-editor UI. Saving the modal writes
515 into the pending world revision and schedules the same midnight restart
516 as a chunk save. The running process keeps the settings it loaded at
517 startup.
531 Global gameplay constants live in authored `world_live_settings`. They
532 are **not** per-mob, **not** client-authored, and **not** pinned to a
533 map revision. Admins edit them from a large categorised modal in the
534 world-editor UI. The modal fills most of the screen: the left pane is a
535 scrollable form grouped by category; the right pane is a settings edit
536 log (which option changed, from/to, which admin, date/time).
537
538 Rows the admin has edited in this session are marked with a distinct
539 background. Save writes **only** those dirty fields. The running
540 process applies them immediately (walk cadence, tick rate, night
541 darkness, and other consumed timers). Chunk **Apply now** is not
542 required.
518 543
519 544 Minimum initial settings and defaults:
520 545
@@ -527,6 +552,7 @@ WorldSettings
527 552 - regionUnloadGracePeriod // configurable grace after last residency
528 553 - defaultGroundTypeId // grass used for never-edited chunks
529 554 - characterDeletionDelay // default 24 hours
555 - nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
530 556 ```
531 557
532 558 Running is always **double** walking speed. It is not a separate per-entity
@@ -577,7 +603,8 @@ into the same pending revision so play never mixes old and new lighting.
577 603 The light map is stored in the chunk `data_blob` as a 16×16 intensity
578 604 (0 = unreachable, 1–255 = falloff by distance from the strongest
579 605 reaching source). The client darkens tiles by that intensity at night,
580 so a torch fades tile-by-tile rather than lighting a hard disc. It is
606 so a torch fades tile-by-tile rather than lighting a hard disc. Peak
607 unlit darkness is `nightDarkness` (a live world setting). It is
581 608 replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
582 609
583 610 Runtime door open/close does not rebake static light unless a later
@@ -2754,8 +2781,9 @@ players; they do not buy player goods unless a later iteration adds that.
2754 2781
2755 2782 - Admin world editor: chunk navigation, open/closed flag, default grass for
2756 2783 unsaved chunks, ground/block paint, light-emitting blocks, baked
2757 cross-chunk light maps, night-to-day preview slider, world settings modal,
2758 per-chunk changelog, save to pending revision.
2784 cross-chunk light maps, night-to-day preview slider, world settings modal
2785 with live apply and a settings edit log, per-chunk changelog, chunk save
2786 to pending revision.
2759 2787
2760 2788 - SpawnerSystem for at least one non-persistent mob archetype.
2761 2789
@@ -2887,7 +2915,7 @@ players; they do not buy player goods unless a later iteration adds that.
2887 2915 | Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2888 2916 | Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
2889 2917 | World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
2890 | World settings | Tick timers and global constants are authored in the editor modal, pinned to the world revision, and not hot-patched into a live process. |
2918 | World settings | Tick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned. |
2891 2919 | Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
2892 2920 | Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
2893 2921 | Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
@@ -3099,8 +3127,9 @@ players; they do not buy player goods unless a later iteration adds that.
3099 3127 lerp for visuals only and never send interpolated positions.
3100 3128
3101 3129 - Admins edit global tick timers and constants in a world-settings modal.
3102 Those values live in the pending world revision and apply on the next
3103 process start, like other editor saves.
3130 Saving applies those values immediately to the live process and appends
3131 a settings changelog. Chunk map saves still wait on the pending world
3132 revision.
3104 3133
3105 3134 - World calendar time is server time minus 1200 years, same IANA zone as
3106 3135 midnight restarts. At night the client darkens tiles the baked light map
@@ -3302,7 +3331,7 @@ Camera → play view centered on the local player; bounded zoom; editor is chunk
3302 3331 Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3303 3332 World time → server clock minus 1200 years; night darkens unlit tiles
3304 3333 Light → baked passable-tile raycast on editor save; shines across chunks
3305 World settings → admin modal for tick timers and global constants; pending revision
3334 World settings → admin modal for tick timers and global constants; live apply
3306 3335 Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3307 3336 Bank → per-character vault; account inheritance tab on character delete
3308 3337 Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
@@ -3319,6 +3348,12 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3319 3348
3320 3349 # 34. Version history
3321 3350
3351 ## 0.13
3352
3353 - World settings are live: an admin modal with categories, dirty-field
3354 highlighting, and a settings edit log. Save applies immediately
3355 (including `nightDarkness`) rather than waiting on a map revision.
3356
3322 3357 ## 0.12
3323 3358
3324 3359 - Chunks are open or closed in the world editor. Closed chunks stay visible
@@ -1,13 +1,13 @@
1---
1---
2title: Tile MMO Server Technical Design
2title: Tile MMO Server Technical Design
3version: 0.12
3version: 0.13
4status: proposed
4status: proposed
5format: living-design-document
5format: living-design-document
6---
6---
7
7
8# Tile MMO Server Technical Design
8# Tile MMO Server Technical Design
9
9
10**Version:** 0.12
10**Version:** 0.13
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
11**Status:** Proposed architecture; intended to be iterated as implementation decisions are made.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
12**Scope:** Authoritative Node.js/ECS backend, FrameworkV3-based game client (16×16 sprites, player-centered viewport), chunk/region streaming, SQLite persistence, admin world editor with per-chunk changelogs, player inventory and items, combat, player communication, banking/cheques, shopkeepers, marketplace/economy systems, skill progression, automatic restart/update orchestration, and future player scripting hooks.
13
13
@@ -63,10 +63,11 @@ format: living-design-document
63
63
64- Authoritative movement is tile-to-tile at a **global** walk/run cadence
64- Authoritative movement is tile-to-tile at a **global** walk/run cadence
65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
65 (default walk 2 tiles/s, run double), not a per-mob speed. Admins edit
66 that cadence and other tick timers in a world-settings modal. World
66 that cadence and other tick timers in a world-settings modal. Saving
67 those settings applies immediately to the live world. World
67 calendar time is server time minus 1200 years. At night the client
68 calendar time is server time minus 1200 years. At night the client
68 darkens unlit tiles; static light reach is baked by raycast when a
69 darkens unlit tiles (how dark is a world setting); static light reach
69 chunk is saved.
70 is baked by raycast when a chunk is saved.
70
71
71- Give every player a 32-slot inventory in which stackable items occupy a
72- Give every player a 32-slot inventory in which stackable items occupy a
72 single slot, and treat dropped items as temporary, non-blocking ground
73 single slot, and treat dropped items as temporary, non-blocking ground
@@ -340,7 +341,7 @@ Use two SQLite databases with different responsibilities.
340
341
341| **Database** | **Responsibility** |
342| **Database** | **Responsibility** |
342|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
343|--------------|-----------------------------------------------------------------------------------------------------------------------------------------|
343| world.sqlite | Admin-authored ground tiles, block tiles, light maps, world settings, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
344| world.sqlite | Admin-authored ground tiles, block tiles, light maps, live world settings and their edit log, spawner configuration, per-chunk editor changelogs, world revisions and world metadata. |
344| state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
345| state.sqlite | Accounts, characters, inventories, carried currency, character vaults, inheritance tabs, cheque reservations, skills, groups, courier cargo/transit, unexpired ground items, market orders/escrow/trades, per-item last player-market sale, persistent ECS entities, offline-script state, optional persistent runtime chunk overrides, and other durable live-game state. |
345
346
346This prevents editor authoring changes from becoming entangled with live
347This prevents editor authoring changes from becoming entangled with live
@@ -405,8 +406,10 @@ part of the normal player client.
405 Marketplace and light-emitting blocks (`lightRangeTiles`).
406 Marketplace and light-emitting blocks (`lightRangeTiles`).
406
407
407- Open a **world settings** modal for global tick timers and constants
408- Open a **world settings** modal for global tick timers and constants
408 (movement cadence, shop lerp duration, drop lifetime, and other values
409 (movement cadence, night darkness, shop lerp duration, drop lifetime,
409 listed in section 8.5).
410 and other values listed in section 8.5). The form is categorised and
411 scrollable; a settings edit log sits beside it. Edited rows are marked
412 until Save, and only those rows are written.
410
413
411- Provide a **night-to-day slider** that only previews lighting; it does
414- Provide a **night-to-day slider** that only previews lighting; it does
412 not change live world time. Preview uses the same baked light maps as
415 not change live world time. Preview uses the same baked light maps as
@@ -427,15 +430,19 @@ player-centered play viewport in section 21.4.
427
430
428## 8.2 World editor save behaviour
431## 8.2 World editor save behaviour
429
432
430Saving a chunk **or world settings** writes the authored result to
433Saving a **chunk** writes the authored result to world.sqlite. It does
431world.sqlite. It does not live-patch the currently running simulation.
434not live-patch the currently running simulation map. Instead, the change
432Instead, the change creates or updates a pending world revision and
435creates or updates a pending world revision and schedules a server
433schedules a server restart for the next server-local midnight.
436restart for the next server-local midnight (or Apply now).
434
437
435The running game remains pinned to the world revision selected at its
438Saving **world settings** is different: it updates the live settings
436own startup. This avoids a dangerous mixed state where some loaded
439row immediately, records a settings changelog entry, and the running
437chunks use old authored data and newly loaded chunks use newer editor
440process applies the new values without waiting for a world revision.
438data.
441
442The running game remains pinned to the **chunk** world revision selected
443at its own startup. This avoids a dangerous mixed state where some
444loaded chunks use old authored data and newly loaded chunks use newer
445editor data. Settings are not revision-pinned.
439
446
440## 8.3 Versioned authored chunks
447## 8.3 Versioned authored chunks
441
448
@@ -463,7 +470,19 @@ pending_revision
463
470
464world_settings
471world_settings
465revision_id
472revision_id
466settings_blob // walk speed, tick timers, shop lerp, drop TTL, ...
473settings_blob // historical snapshot copied onto a map revision
474
475world_live_settings
476id // singleton row, always 1
477settings_blob // the live, immediately applied settings
478updated_at
479updated_by
480
481world_settings_edit_log
482log_id
483editor_admin_id
484edited_at
485diff_entries // which options changed, from/to
467
486
468world_chunk_edit_log
487world_chunk_edit_log
469log_id
488log_id
@@ -509,12 +528,18 @@ they are regenerated on save (section 8.6).
509
528
510## 8.5 World settings
529## 8.5 World settings
511
530
512Global gameplay constants live in authored `world_settings` for the world
531Global gameplay constants live in authored `world_live_settings`. They
513revision. They are **not** per-mob and **not** client-authored. Admins
532are **not** per-mob, **not** client-authored, and **not** pinned to a
514edit them from a modal in the world-editor UI. Saving the modal writes
533map revision. Admins edit them from a large categorised modal in the
515into the pending world revision and schedules the same midnight restart
534world-editor UI. The modal fills most of the screen: the left pane is a
516as a chunk save. The running process keeps the settings it loaded at
535scrollable form grouped by category; the right pane is a settings edit
517startup.
536log (which option changed, from/to, which admin, date/time).
537
538Rows the admin has edited in this session are marked with a distinct
539background. Save writes **only** those dirty fields. The running
540process applies them immediately (walk cadence, tick rate, night
541darkness, and other consumed timers). Chunk **Apply now** is not
542required.
518
543
519Minimum initial settings and defaults:
544Minimum initial settings and defaults:
520
545
@@ -527,6 +552,7 @@ WorldSettings
527- regionUnloadGracePeriod // configurable grace after last residency
552- regionUnloadGracePeriod // configurable grace after last residency
528- defaultGroundTypeId // grass used for never-edited chunks
553- defaultGroundTypeId // grass used for never-edited chunks
529- characterDeletionDelay // default 24 hours
554- characterDeletionDelay // default 24 hours
555- nightDarkness // default 0.72; 0 = no extra night darkening, 1 = fully black unlit tiles
530```
556```
531
557
532Running is always **double** walking speed. It is not a separate per-entity
558Running is always **double** walking speed. It is not a separate per-entity
@@ -577,7 +603,8 @@ into the same pending revision so play never mixes old and new lighting.
577The light map is stored in the chunk `data_blob` as a 16×16 intensity
603The light map is stored in the chunk `data_blob` as a 16×16 intensity
578(0 = unreachable, 1–255 = falloff by distance from the strongest
604(0 = unreachable, 1–255 = falloff by distance from the strongest
579reaching source). The client darkens tiles by that intensity at night,
605reaching source). The client darkens tiles by that intensity at night,
580so a torch fades tile-by-tile rather than lighting a hard disc. It is
606so a torch fades tile-by-tile rather than lighting a hard disc. Peak
607unlit darkness is `nightDarkness` (a live world setting). It is
581replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
608replicated to clients in `CHUNK_SNAPSHOT` / `CHUNK_DELTA`.
582
609
583Runtime door open/close does not rebake static light unless a later
610Runtime door open/close does not rebake static light unless a later
@@ -2754,8 +2781,9 @@ players; they do not buy player goods unless a later iteration adds that.
2754
2781
2755- Admin world editor: chunk navigation, open/closed flag, default grass for
2782- Admin world editor: chunk navigation, open/closed flag, default grass for
2756 unsaved chunks, ground/block paint, light-emitting blocks, baked
2783 unsaved chunks, ground/block paint, light-emitting blocks, baked
2757 cross-chunk light maps, night-to-day preview slider, world settings modal,
2784 cross-chunk light maps, night-to-day preview slider, world settings modal
2758 per-chunk changelog, save to pending revision.
2785 with live apply and a settings edit log, per-chunk changelog, chunk save
2786 to pending revision.
2759
2787
2760- SpawnerSystem for at least one non-persistent mob archetype.
2788- SpawnerSystem for at least one non-persistent mob archetype.
2761
2789
@@ -2887,7 +2915,7 @@ players; they do not buy player goods unless a later iteration adds that.
2887| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2915| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2888| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
2916| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
2889| World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
2917| World time | World calendar time is server time minus 1200 years. Night darkens tiles the baked light map cannot reach. |
2890| World settings | Tick timers and global constants are authored in the editor modal, pinned to the world revision, and not hot-patched into a live process. |
2918| World settings | Tick timers and global constants (including night darkness) are authored in the editor modal, applied immediately on save, and recorded in a settings edit log. Chunk map data remains revision-pinned. |
2891| Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
2919| Baked light | Static light reach is raycast through passable tiles on chunk save, may cross chunks, and is not recomputed every tick. |
2892| Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
2920| Ground items | Player drops last `groundItemDespawnDuration` (default 10 minutes), block nobody, and are picked up only by a player standing on that tile. |
2893| Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
2921| Shop prices | NPC shop prices lerp from the captured pre-sale value toward the last player-market unit price over `shopPriceLerpDuration` (default one hour), times a hidden per-shop discount. |
@@ -3099,8 +3127,9 @@ players; they do not buy player goods unless a later iteration adds that.
3099 lerp for visuals only and never send interpolated positions.
3127 lerp for visuals only and never send interpolated positions.
3100
3128
3101- Admins edit global tick timers and constants in a world-settings modal.
3129- Admins edit global tick timers and constants in a world-settings modal.
3102 Those values live in the pending world revision and apply on the next
3130 Saving applies those values immediately to the live process and appends
3103 process start, like other editor saves.
3131 a settings changelog. Chunk map saves still wait on the pending world
3132 revision.
3104
3133
3105- World calendar time is server time minus 1200 years, same IANA zone as
3134- World calendar time is server time minus 1200 years, same IANA zone as
3106 midnight restarts. At night the client darkens tiles the baked light map
3135 midnight restarts. At night the client darkens tiles the baked light map
@@ -3302,7 +3331,7 @@ Camera → play view centered on the local player; bounded zoom; editor is chunk
3302Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3331Movement → global walk/run cadence (default 2 tiles/s walk, run double); server tile steps; client visual lerp
3303World time → server clock minus 1200 years; night darkens unlit tiles
3332World time → server clock minus 1200 years; night darkens unlit tiles
3304Light → baked passable-tile raycast on editor save; shines across chunks
3333Light → baked passable-tile raycast on editor save; shines across chunks
3305World settings → admin modal for tick timers and global constants; pending revision
3334World settings → admin modal for tick timers and global constants; live apply
3306Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3335Inventory → 32 slots; stacks occupy one slot; letters are written paper items
3307Bank → per-character vault; account inheritance tab on character delete
3336Bank → per-character vault; account inheritance tab on character delete
3308Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
3337Auth → auth.timfalken.com, stub admin-<n> until live; unlimited characters, one in world
@@ -3319,6 +3348,12 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3319
3348
3320# 34. Version history
3349# 34. Version history
3321
3350
3351## 0.13
3352
3353- World settings are live: an admin modal with categories, dirty-field
3354 highlighting, and a settings edit log. Save applies immediately
3355 (including `nightDarkness`) rather than waiting on a map revision.
3356
3322## 0.12
3357## 0.12
3323
3358
3324- Chunks are open or closed in the world editor. Closed chunks stay visible
3359- Chunks are open or closed in the world editor. Closed chunks stay visible