BlueGit

timfa questward

Load ground and block sprites from per-type state folders.

The editor previews the selected tool on hover, the mouse wheel cycles visual states, and sprite definitions can set frames, frames-per-row, and animation speed.

timfa Tim Falken · pushed by timfa

Authored 2026-08-24 · 2 months ago

Hash
4f08b384267f48b4e50a7e9c7f6d994ea0aa5643
Parent
21599553
20 files changed +595 −112
README.md +1 −1
@@ -7,7 +7,7 @@ Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives
7 7 - `shared/` — protocol constants and tile definitions used by server and client
8 8 - `server/src/` — Node.js simulation, persistence, editor API, gateway
9 9 - `client/src/` — game client on top of FrameworkV3
10 - `client/assets/` — world sprites (any size; pivot is 8px from the bottom)
10 - `client/assets/` — world sprites. Grounds and blocks live in a folder per type; each PNG is a visual state (first alphabetical is the default). Pivot is 8px from the bottom.
11 11 - `client/frameworkv3/` — FrameworkV3 git submodule
12 12
13 13 ## Run locally
@@ -7,7 +7,7 @@ Authoritative Node.js tile MMO with a FrameworkV3 web client. Architecture lives
7- `shared/` — protocol constants and tile definitions used by server and client
7- `shared/` — protocol constants and tile definitions used by server and client
8- `server/src/` — Node.js simulation, persistence, editor API, gateway
8- `server/src/` — Node.js simulation, persistence, editor API, gateway
9- `client/src/` — game client on top of FrameworkV3
9- `client/src/` — game client on top of FrameworkV3
10- `client/assets/` — world sprites (any size; pivot is 8px from the bottom)
10- `client/assets/` — world sprites. Grounds and blocks live in a folder per type; each PNG is a visual state (first alphabetical is the default). Pivot is 8px from the bottom.
11- `client/frameworkv3/` — FrameworkV3 git submodule
11- `client/frameworkv3/` — FrameworkV3 git submodule
12
12
13## Run locally
13## Run locally
client/assets/blocks/block-stone-wall.png client/assets/blocks/stone-wall/1.png renamed +0 −0
client/assets/blocks/stone-wall/2.png added Binary file +0 −0

The contents of this binary file are not shown.

client/assets/blocks/block-torch.png client/assets/blocks/torch/torch.png renamed +0 −0
client/assets/grounds/ground-grass.png client/assets/grounds/grass/grass.png renamed +0 −0
client/assets/grounds/ground-wood.png client/assets/grounds/wood/wood.png renamed +0 −0
client/editor.html +1 −1
@@ -36,7 +36,7 @@
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 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>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool; the mouse wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
40 40 </aside>
41 41 <section id="changelog-wrap">
42 42 <h2>Changelog</h2>
@@ -36,7 +36,7 @@
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 <button id="open-settings" type="button">World settings</button>
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>
39 <p class="hint">The red border is the chunk you are editing. Neighbours are shown for alignment and lighting, but paint only applies inside the border. Hover previews the selected tool; the mouse wheel cycles visual states. Chunk saves write a pending revision; world settings apply immediately. Marketplace placement waits on assets.</p>
40 </aside>
40 </aside>
41 <section id="changelog-wrap">
41 <section id="changelog-wrap">
42 <h2>Changelog</h2>
42 <h2>Changelog</h2>
client/src/editor/main.js +103 −28
@@ -1,7 +1,8 @@
1 1 import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/definitions/tiles.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3 import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
3 4 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4 import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
5 import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5 6 import { WorldView } from "../render/worldView.js";
6 7 import { initSettingsModal } from "./settingsModal.js";
7 8
@@ -12,8 +13,10 @@ let view;
12 13 let draft = null;
13 14 let chunkX = 0;
14 15 let chunkY = 0;
15 let tool = { kind: "ground", typeId: GroundType.grass };
16 let tool = { kind: "ground", typeId: GroundType.grass, state: null };
16 17 let settingsModal;
18 let catalog = { grounds: {}, blocks: {} };
19 let hoverLocal = null;
17 20
18 21 function $ (id)
19 22 {
@@ -24,9 +27,38 @@ function selectedToolLabel ()
24 27 {
25 28 if (tool.kind === "erase")
26 29 { return "Erase block"; }
30 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
31 const layer = tool.kind === "ground" ? "ground" : "block";
32 const states = statesForType(catalog, layer, def.key);
33 const state = resolveState(states, tool.state);
34 if (states.length > 1)
35 { return `${def.displayName} (${state})`; }
36 return def.displayName;
37 }
38
39 function selectTool (next)
40 {
41 if (next.kind === "erase")
42 {
43 tool = { kind: "erase" };
44 return;
45 }
46 const layer = next.kind === "ground" ? "ground" : "block";
47 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
48 tool = {
49 kind: next.kind,
50 typeId: next.typeId,
51 state: defaultStateForType(catalog, layer, def.key)
52 };
53 }
54
55 function previewFromTool ()
56 {
57 if (tool.kind === "erase")
58 { return { block: null }; }
27 59 if (tool.kind === "ground")
28 { return GROUND_DEFINITIONS[tool.typeId].displayName; }
29 return BLOCK_DEFINITIONS[tool.typeId].displayName;
60 { return { ground: { typeId: tool.typeId, state: tool.state } }; }
61 return { block: { typeId: tool.typeId, state: tool.state, config: null } };
30 62 }
31 63
32 64 function inEditorView (x, y)
@@ -65,20 +97,15 @@ function paintAt (localX, localY)
65 97 { return; }
66 98 const index = localY * CHUNK_SIZE + localX;
67 99 if (tool.kind === "ground")
68 { draft.grounds[index] = tool.typeId; }
100 { draft.grounds[index] = { typeId: tool.typeId, state: tool.state }; }
69 101 else if (tool.kind === "erase")
70 102 { draft.blocks[index] = null; }
71 103 else
72 { draft.blocks[index] = { typeId: tool.typeId, config: null }; }
73 view.applySnapshot({
74 chunkX,
75 chunkY,
76 open: draft.open,
77 closedEdges: view.chunks.get(`${chunkX},${chunkY}`)?.closedEdges,
78 grounds: draft.grounds,
79 blocks: draft.blocks,
80 light: draft.light,
81 entities: []
104 { draft.blocks[index] = { typeId: tool.typeId, state: tool.state, config: null }; }
105 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
106 ground: draft.grounds[index],
107 block: draft.blocks[index],
108 light: draft.light[index]
82 109 });
83 110 }
84 111
@@ -86,7 +113,7 @@ function showSelectedChunk (payload)
86 113 {
87 114 draft = {
88 115 open: payload.data.open,
89 grounds: payload.data.grounds.slice(),
116 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
90 117 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
91 118 light: payload.data.light.slice()
92 119 };
@@ -199,28 +226,43 @@ function requestNeighbors ()
199 226
200 227 async function main ()
201 228 {
202 await game.preloadImages(PLAY_IMAGES);
229 catalog = await loadSpriteCatalog();
230 await game.preloadImages(playImagesFromCatalog(catalog));
231 applySpriteSheets(game.images, catalog);
203 232 scene = new Scene(250, 56, 64, 64);
204 233 game.loadScene(scene);
205 234 useNearestNeighbour(scene, game.images);
206 view = new WorldView(game, scene);
235 view = new WorldView(game, scene, catalog);
207 236 view.followPlayer = false;
208 237 layoutScene();
238 selectTool(tool);
239 $("tool").textContent = selectedToolLabel();
209 240 const ticker = new GameObject(0, 0, null, 10);
210 241 ticker.update = (dt) =>
211 242 {
212 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft && !settingsModal?.isOpen())
243 hoverLocal = null;
244 const canvas = scene.canvas;
245 const rect = canvas.getBoundingClientRect();
246 const mouseX = GameInput.mousePosition.x - rect.left;
247 const mouseY = GameInput.mousePosition.y - rect.top;
248 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
249 if (overCanvas && draft && !settingsModal?.isOpen())
213 250 {
214 const canvas = scene.canvas;
215 const rect = canvas.getBoundingClientRect();
216 const mouseX = GameInput.mousePosition.x - rect.left;
217 const mouseY = GameInput.mousePosition.y - rect.top;
218 if (mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height)
251 const tile = view.screenToTile(mouseX, mouseY);
252 const localX = tile.tileX - chunkX * CHUNK_SIZE;
253 const localY = tile.tileY - chunkY * CHUNK_SIZE;
254 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
219 255 {
220 const tile = view.screenToTile(mouseX, mouseY);
221 paintAt(tile.tileX - chunkX * CHUNK_SIZE, tile.tileY - chunkY * CHUNK_SIZE);
256 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
257 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
258 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
259 { paintAt(localX, localY); }
222 260 }
261 else
262 { view.clearTilePreview(); }
223 263 }
264 else
265 { view.clearTilePreview(); }
224 266 view.update(dt);
225 267 frameNeighborhood();
226 268 };
@@ -269,7 +311,7 @@ document.querySelectorAll("[data-tool]").forEach((button) =>
269 311 {
270 312 button.addEventListener("click", () =>
271 313 {
272 tool = JSON.parse(button.dataset.tool);
314 selectTool(JSON.parse(button.dataset.tool));
273 315 $("tool").textContent = selectedToolLabel();
274 316 });
275 317 });
@@ -304,6 +346,39 @@ $("night").addEventListener("input", () =>
304 346 $("night-label").textContent = view.nightPreview.toFixed(1);
305 347 });
306 348
349 function cycleToolState (direction)
350 {
351 if (tool.kind === "erase")
352 { return; }
353 const layer = tool.kind === "ground" ? "ground" : "block";
354 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
355 const states = statesForType(catalog, layer, def.key);
356 if (states.length < 2)
357 { return; }
358 tool.state = cycleState(states, tool.state, direction);
359 $("tool").textContent = selectedToolLabel();
360 if (!draft || !hoverLocal)
361 { return; }
362 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
363 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
364 { paintAt(hoverLocal.x, hoverLocal.y); }
365 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
366 { paintAt(hoverLocal.x, hoverLocal.y); }
367 }
368
369 document.addEventListener("wheel", (event) =>
370 {
371 if (!scene?.canvas || settingsModal?.isOpen())
372 { return; }
373 const rect = scene.canvas.getBoundingClientRect();
374 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
375 { return; }
376 event.preventDefault();
377 cycleToolState(event.deltaY < 0 ? 1 : -1);
378 if (hoverLocal)
379 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
380 }, { passive: false });
381
307 382 main().catch((error) =>
308 383 {
309 384 $("error").textContent = error.message;
@@ -1,7 +1,8 @@
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
1import { MessageType, CHUNK_SIZE, SPRITE_SIZE_PX, VISIBLE_CHUNK_RADIUS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround } from "/shared/definitions/tiles.js";
3import { cycleState, defaultStateForType, resolveState, statesForType } from "/shared/definitions/tileSprites.js";
3import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { GameSocket, defaultSocketUrl } from "../net/socket.js";
4import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
5import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
5import { WorldView } from "../render/worldView.js";
6import { WorldView } from "../render/worldView.js";
6import { initSettingsModal } from "./settingsModal.js";
7import { initSettingsModal } from "./settingsModal.js";
7
8
@@ -12,8 +13,10 @@ let view;
12let draft = null;
13let draft = null;
13let chunkX = 0;
14let chunkX = 0;
14let chunkY = 0;
15let chunkY = 0;
15let tool = { kind: "ground", typeId: GroundType.grass };
16let tool = { kind: "ground", typeId: GroundType.grass, state: null };
16let settingsModal;
17let settingsModal;
18let catalog = { grounds: {}, blocks: {} };
19let hoverLocal = null;
17
20
18function $ (id)
21function $ (id)
19{
22{
@@ -24,9 +27,38 @@ function selectedToolLabel ()
24{
27{
25 if (tool.kind === "erase")
28 if (tool.kind === "erase")
26 { return "Erase block"; }
29 { return "Erase block"; }
30 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
31 const layer = tool.kind === "ground" ? "ground" : "block";
32 const states = statesForType(catalog, layer, def.key);
33 const state = resolveState(states, tool.state);
34 if (states.length > 1)
35 { return `${def.displayName} (${state})`; }
36 return def.displayName;
37}
38
39function selectTool (next)
40{
41 if (next.kind === "erase")
42 {
43 tool = { kind: "erase" };
44 return;
45 }
46 const layer = next.kind === "ground" ? "ground" : "block";
47 const def = next.kind === "ground" ? GROUND_DEFINITIONS[next.typeId] : BLOCK_DEFINITIONS[next.typeId];
48 tool = {
49 kind: next.kind,
50 typeId: next.typeId,
51 state: defaultStateForType(catalog, layer, def.key)
52 };
53}
54
55function previewFromTool ()
56{
57 if (tool.kind === "erase")
58 { return { block: null }; }
27 if (tool.kind === "ground")
59 if (tool.kind === "ground")
28 { return GROUND_DEFINITIONS[tool.typeId].displayName; }
60 { return { ground: { typeId: tool.typeId, state: tool.state } }; }
29 return BLOCK_DEFINITIONS[tool.typeId].displayName;
61 return { block: { typeId: tool.typeId, state: tool.state, config: null } };
30}
62}
31
63
32function inEditorView (x, y)
64function inEditorView (x, y)
@@ -65,20 +97,15 @@ function paintAt (localX, localY)
65 { return; }
97 { return; }
66 const index = localY * CHUNK_SIZE + localX;
98 const index = localY * CHUNK_SIZE + localX;
67 if (tool.kind === "ground")
99 if (tool.kind === "ground")
68 { draft.grounds[index] = tool.typeId; }
100 { draft.grounds[index] = { typeId: tool.typeId, state: tool.state }; }
69 else if (tool.kind === "erase")
101 else if (tool.kind === "erase")
70 { draft.blocks[index] = null; }
102 { draft.blocks[index] = null; }
71 else
103 else
72 { draft.blocks[index] = { typeId: tool.typeId, config: null }; }
104 { draft.blocks[index] = { typeId: tool.typeId, state: tool.state, config: null }; }
73 view.applySnapshot({
105 view.updateAuthoredTile(chunkX, chunkY, localX, localY, {
74 chunkX,
106 ground: draft.grounds[index],
75 chunkY,
107 block: draft.blocks[index],
76 open: draft.open,
108 light: draft.light[index]
77 closedEdges: view.chunks.get(`${chunkX},${chunkY}`)?.closedEdges,
78 grounds: draft.grounds,
79 blocks: draft.blocks,
80 light: draft.light,
81 entities: []
82 });
109 });
83}
110}
84
111
@@ -86,7 +113,7 @@ function showSelectedChunk (payload)
86{
113{
87 draft = {
114 draft = {
88 open: payload.data.open,
115 open: payload.data.open,
89 grounds: payload.data.grounds.slice(),
116 grounds: payload.data.grounds.map((ground) => normalizeGround(ground)),
90 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
117 blocks: payload.data.blocks.map((block) => (block ? { ...block } : null)),
91 light: payload.data.light.slice()
118 light: payload.data.light.slice()
92 };
119 };
@@ -199,28 +226,43 @@ function requestNeighbors ()
199
226
200async function main ()
227async function main ()
201{
228{
202 await game.preloadImages(PLAY_IMAGES);
229 catalog = await loadSpriteCatalog();
230 await game.preloadImages(playImagesFromCatalog(catalog));
231 applySpriteSheets(game.images, catalog);
203 scene = new Scene(250, 56, 64, 64);
232 scene = new Scene(250, 56, 64, 64);
204 game.loadScene(scene);
233 game.loadScene(scene);
205 useNearestNeighbour(scene, game.images);
234 useNearestNeighbour(scene, game.images);
206 view = new WorldView(game, scene);
235 view = new WorldView(game, scene, catalog);
207 view.followPlayer = false;
236 view.followPlayer = false;
208 layoutScene();
237 layoutScene();
238 selectTool(tool);
239 $("tool").textContent = selectedToolLabel();
209 const ticker = new GameObject(0, 0, null, 10);
240 const ticker = new GameObject(0, 0, null, 10);
210 ticker.update = (dt) =>
241 ticker.update = (dt) =>
211 {
242 {
212 if (GameInput.mouseHeld(GameInput.MouseButtons.Left) && draft && !settingsModal?.isOpen())
243 hoverLocal = null;
244 const canvas = scene.canvas;
245 const rect = canvas.getBoundingClientRect();
246 const mouseX = GameInput.mousePosition.x - rect.left;
247 const mouseY = GameInput.mousePosition.y - rect.top;
248 const overCanvas = mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height;
249 if (overCanvas && draft && !settingsModal?.isOpen())
213 {
250 {
214 const canvas = scene.canvas;
251 const tile = view.screenToTile(mouseX, mouseY);
215 const rect = canvas.getBoundingClientRect();
252 const localX = tile.tileX - chunkX * CHUNK_SIZE;
216 const mouseX = GameInput.mousePosition.x - rect.left;
253 const localY = tile.tileY - chunkY * CHUNK_SIZE;
217 const mouseY = GameInput.mousePosition.y - rect.top;
254 if (localX >= 0 && localY >= 0 && localX < CHUNK_SIZE && localY < CHUNK_SIZE)
218 if (mouseX >= 0 && mouseY >= 0 && mouseX < rect.width && mouseY < rect.height)
219 {
255 {
220 const tile = view.screenToTile(mouseX, mouseY);
256 hoverLocal = { x: localX, y: localY, tileX: tile.tileX, tileY: tile.tileY };
221 paintAt(tile.tileX - chunkX * CHUNK_SIZE, tile.tileY - chunkY * CHUNK_SIZE);
257 view.setTilePreview(tile.tileX, tile.tileY, previewFromTool());
258 if (GameInput.mouseHeld(GameInput.MouseButtons.Left))
259 { paintAt(localX, localY); }
222 }
260 }
261 else
262 { view.clearTilePreview(); }
223 }
263 }
264 else
265 { view.clearTilePreview(); }
224 view.update(dt);
266 view.update(dt);
225 frameNeighborhood();
267 frameNeighborhood();
226 };
268 };
@@ -269,7 +311,7 @@ document.querySelectorAll("[data-tool]").forEach((button) =>
269{
311{
270 button.addEventListener("click", () =>
312 button.addEventListener("click", () =>
271 {
313 {
272 tool = JSON.parse(button.dataset.tool);
314 selectTool(JSON.parse(button.dataset.tool));
273 $("tool").textContent = selectedToolLabel();
315 $("tool").textContent = selectedToolLabel();
274 });
316 });
275});
317});
@@ -304,6 +346,39 @@ $("night").addEventListener("input", () =>
304 $("night-label").textContent = view.nightPreview.toFixed(1);
346 $("night-label").textContent = view.nightPreview.toFixed(1);
305});
347});
306
348
349function cycleToolState (direction)
350{
351 if (tool.kind === "erase")
352 { return; }
353 const layer = tool.kind === "ground" ? "ground" : "block";
354 const def = tool.kind === "ground" ? GROUND_DEFINITIONS[tool.typeId] : BLOCK_DEFINITIONS[tool.typeId];
355 const states = statesForType(catalog, layer, def.key);
356 if (states.length < 2)
357 { return; }
358 tool.state = cycleState(states, tool.state, direction);
359 $("tool").textContent = selectedToolLabel();
360 if (!draft || !hoverLocal)
361 { return; }
362 const index = hoverLocal.y * CHUNK_SIZE + hoverLocal.x;
363 if (tool.kind === "ground" && normalizeGround(draft.grounds[index]).typeId === tool.typeId)
364 { paintAt(hoverLocal.x, hoverLocal.y); }
365 else if (tool.kind === "block" && draft.blocks[index]?.typeId === tool.typeId)
366 { paintAt(hoverLocal.x, hoverLocal.y); }
367}
368
369document.addEventListener("wheel", (event) =>
370{
371 if (!scene?.canvas || settingsModal?.isOpen())
372 { return; }
373 const rect = scene.canvas.getBoundingClientRect();
374 if (event.clientX < rect.left || event.clientX >= rect.right || event.clientY < rect.top || event.clientY >= rect.bottom)
375 { return; }
376 event.preventDefault();
377 cycleToolState(event.deltaY < 0 ? 1 : -1);
378 if (hoverLocal)
379 { view.setTilePreview(hoverLocal.tileX, hoverLocal.tileY, previewFromTool()); }
380}, { passive: false });
381
307main().catch((error) =>
382main().catch((error) =>
308{
383{
309 $("error").textContent = error.message;
384 $("error").textContent = error.message;
client/src/play/main.js +6 −3
@@ -1,6 +1,6 @@
1 1 import { MessageType, GAIT } from "/shared/protocol/constants.js";
2 2 import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3 import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
3 import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4 4 import { WorldView } from "../render/worldView.js";
5 5
6 6 const game = new Game();
@@ -16,6 +16,7 @@ let playing = false;
16 16 let view = null;
17 17 let scene = null;
18 18 let gait = GAIT.walk;
19 let catalog = { grounds: {}, blocks: {} };
19 20
20 21 function showError (message)
21 22 {
@@ -64,7 +65,7 @@ function startPlay (payload)
64 65 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
65 66 game.loadScene(scene);
66 67 useNearestNeighbour(scene, game.images);
67 view = new WorldView(game, scene);
68 view = new WorldView(game, scene, catalog);
68 69 const ticker = new GameObject(0, 0, null, 10);
69 70 ticker.update = (dt) =>
70 71 {
@@ -103,7 +104,9 @@ function startPlay (payload)
103 104
104 105 async function main ()
105 106 {
106 await game.preloadImages(PLAY_IMAGES);
107 catalog = await loadSpriteCatalog();
108 await game.preloadImages(playImagesFromCatalog(catalog));
109 applySpriteSheets(game.images, catalog);
107 110 game.startGame();
108 111
109 112 socket = new GameSocket(defaultSocketUrl(), (message) =>
@@ -1,6 +1,6 @@
1import { MessageType, GAIT } from "/shared/protocol/constants.js";
1import { MessageType, GAIT } from "/shared/protocol/constants.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
2import { GameSocket, defaultSocketUrl } from "../net/socket.js";
3import { PLAY_IMAGES, useNearestNeighbour } from "../render/sprites.js";
3import { playImagesFromCatalog, loadSpriteCatalog, applySpriteSheets, useNearestNeighbour } from "../render/sprites.js";
4import { WorldView } from "../render/worldView.js";
4import { WorldView } from "../render/worldView.js";
5
5
6const game = new Game();
6const game = new Game();
@@ -16,6 +16,7 @@ let playing = false;
16let view = null;
16let view = null;
17let scene = null;
17let scene = null;
18let gait = GAIT.walk;
18let gait = GAIT.walk;
19let catalog = { grounds: {}, blocks: {} };
19
20
20function showError (message)
21function showError (message)
21{
22{
@@ -64,7 +65,7 @@ function startPlay (payload)
64 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
65 scene = new Scene(0, 0, window.innerWidth, window.innerHeight);
65 game.loadScene(scene);
66 game.loadScene(scene);
66 useNearestNeighbour(scene, game.images);
67 useNearestNeighbour(scene, game.images);
67 view = new WorldView(game, scene);
68 view = new WorldView(game, scene, catalog);
68 const ticker = new GameObject(0, 0, null, 10);
69 const ticker = new GameObject(0, 0, null, 10);
69 ticker.update = (dt) =>
70 ticker.update = (dt) =>
70 {
71 {
@@ -103,7 +104,9 @@ function startPlay (payload)
103
104
104async function main ()
105async function main ()
105{
106{
106 await game.preloadImages(PLAY_IMAGES);
107 catalog = await loadSpriteCatalog();
108 await game.preloadImages(playImagesFromCatalog(catalog));
109 applySpriteSheets(game.images, catalog);
107 game.startGame();
110 game.startGame();
108
111
109 socket = new GameSocket(defaultSocketUrl(), (message) =>
112 socket = new GameSocket(defaultSocketUrl(), (message) =>
client/src/render/sprites.js +34 −5
@@ -1,16 +1,45 @@
1 1 import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2 2
3 export const PLAY_IMAGES = [
4 { name: "ground-grass", url: "/assets/grounds/ground-grass.png" },
5 { name: "ground-wood", url: "/assets/grounds/ground-wood.png" },
6 { name: "block-stone-wall", url: "/assets/blocks/block-stone-wall.png" },
7 { name: "block-torch", url: "/assets/blocks/block-torch.png" },
3 export const UTILITY_IMAGES = [
8 4 { name: "player-body-male", url: "/assets/characters/player-body-male.png" },
9 5 { name: "player-body-female", url: "/assets/characters/player-body-female.png" },
10 6 { name: "night-shade", url: shadeDataUrl("#000000") },
11 7 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
12 8 ];
13 9
10 export function playImagesFromCatalog (catalog)
11 {
12 return [...(catalog?.images ?? []), ...UTILITY_IMAGES];
13 }
14
15 export async function loadSpriteCatalog ()
16 {
17 const response = await fetch("/assets/catalog.json");
18 if (!response.ok)
19 { throw new Error("Failed to load sprite catalog."); }
20 return response.json();
21 }
22
23 export function applySpriteSheets (images, catalog)
24 {
25 for (const entry of catalog?.images ?? [])
26 {
27 const sprite = images[entry.name];
28 if (!sprite)
29 { continue; }
30 sprite._animationSpeed = entry.animationSpeed ?? 0;
31 const frames = entry.subImgTotal || 1;
32 if (frames > 1)
33 {
34 sprite.addAnimationCycle(
35 "idle",
36 Array.from({ length: frames }, (_, index) => index),
37 true
38 );
39 }
40 }
41 }
42
14 43 export function shadeDataUrl (fill = "#000000")
15 44 {
16 45 const canvas = document.createElement("canvas");
@@ -1,16 +1,45 @@
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
2
3export const PLAY_IMAGES = [
3export const UTILITY_IMAGES = [
4 { name: "ground-grass", url: "/assets/grounds/ground-grass.png" },
5 { name: "ground-wood", url: "/assets/grounds/ground-wood.png" },
6 { name: "block-stone-wall", url: "/assets/blocks/block-stone-wall.png" },
7 { name: "block-torch", url: "/assets/blocks/block-torch.png" },
8 { name: "player-body-male", url: "/assets/characters/player-body-male.png" },
4 { name: "player-body-male", url: "/assets/characters/player-body-male.png" },
9 { name: "player-body-female", url: "/assets/characters/player-body-female.png" },
5 { name: "player-body-female", url: "/assets/characters/player-body-female.png" },
10 { name: "night-shade", url: shadeDataUrl("#000000") },
6 { name: "night-shade", url: shadeDataUrl("#000000") },
11 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
7 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
12];
8];
13
9
10export function playImagesFromCatalog (catalog)
11{
12 return [...(catalog?.images ?? []), ...UTILITY_IMAGES];
13}
14
15export async function loadSpriteCatalog ()
16{
17 const response = await fetch("/assets/catalog.json");
18 if (!response.ok)
19 { throw new Error("Failed to load sprite catalog."); }
20 return response.json();
21}
22
23export function applySpriteSheets (images, catalog)
24{
25 for (const entry of catalog?.images ?? [])
26 {
27 const sprite = images[entry.name];
28 if (!sprite)
29 { continue; }
30 sprite._animationSpeed = entry.animationSpeed ?? 0;
31 const frames = entry.subImgTotal || 1;
32 if (frames > 1)
33 {
34 sprite.addAnimationCycle(
35 "idle",
36 Array.from({ length: frames }, (_, index) => index),
37 true
38 );
39 }
40 }
41}
42
14export function shadeDataUrl (fill = "#000000")
43export function shadeDataUrl (fill = "#000000")
15{
44{
16 const canvas = document.createElement("canvas");
45 const canvas = document.createElement("canvas");
client/src/render/worldView.js +139 −36
@@ -1,5 +1,6 @@
1 1 import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
2 import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3 import { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3 4 import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4 5
5 6 const LAYER_GROUND = 0;
@@ -10,10 +11,12 @@ const SORT_ENTITY = 2;
10 11
11 12 export class WorldView
12 13 {
13 constructor (game, scene)
14 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
14 15 {
15 16 this.game = game;
16 17 this.scene = scene;
18 this.catalog = catalog;
19 this.preview = null;
17 20 this.zoom = 2;
18 21 this.chunks = new Map();
19 22 this.tiles = new Map();
@@ -45,6 +48,7 @@ export class WorldView
45 48 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
46 49 this.chunks.set(key, snapshot);
47 50 this.#rebuildChunk(snapshot);
51 this.#redrawPreview();
48 52 for (const entity of snapshot.entities ?? [])
49 53 { this.#upsertEntity(entity); }
50 54 this.#rebuildAllEdges();
@@ -127,6 +131,7 @@ export class WorldView
127 131 this.#placeEntity(entity);
128 132 }
129 133 this.#rebuildAllEdges();
134 this.#redrawPreview();
130 135 }
131 136
132 137 tileSize ()
@@ -172,6 +177,38 @@ export class WorldView
172 177 this.#updateShade(deltaTime);
173 178 }
174 179
180 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
181 {
182 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
183 if (!snapshot)
184 { return; }
185 const index = localY * CHUNK_SIZE + localX;
186 if (ground !== undefined)
187 { snapshot.grounds[index] = ground; }
188 if (block !== undefined)
189 { snapshot.blocks[index] = block; }
190 if (light !== undefined)
191 { snapshot.light[index] = light; }
192 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
193 }
194
195 setTilePreview (tileX, tileY, override)
196 {
197 const previous = this.preview;
198 this.preview = { tileX, tileY, ...override };
199 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
200 { this.#drawTile(previous.tileX, previous.tileY); }
201 this.#drawTile(tileX, tileY);
202 }
203
204 clearTilePreview ()
205 {
206 const previous = this.preview;
207 this.preview = null;
208 if (previous)
209 { this.#drawTile(previous.tileX, previous.tileY); }
210 }
211
175 212 #lerpMs (gait)
176 213 {
177 214 const walk = this.settings.walkTilesPerSecond || 2;
@@ -221,48 +258,105 @@ export class WorldView
221 258
222 259 #rebuildChunk (snapshot)
223 260 {
224 const size = this.tileSize();
225 261 for (let localY = 0; localY < CHUNK_SIZE; localY++)
226 262 {
227 263 for (let localX = 0; localX < CHUNK_SIZE; localX++)
228 {
229 const index = localY * CHUNK_SIZE + localX;
230 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
231 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
232 const key = `${tileX},${tileY}`;
233 let objects = this.tiles.get(key);
234 if (!objects)
235 {
236 objects = { chunkX: snapshot.chunkX, chunkY: snapshot.chunkY };
237 this.tiles.set(key, objects);
238 }
239 const pivot = tilePivot(tileX, tileY, size);
240 const groundName = GROUND_DEFINITIONS[snapshot.grounds[index]]?.sprite ?? "ground-grass";
241 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
242 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
243 objects.ground.layer = LAYER_GROUND;
244 const block = snapshot.blocks[index];
245 const blockName = block ? BLOCK_DEFINITIONS[block.typeId]?.sprite : null;
246 if (blockName)
247 {
248 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
249 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
250 }
251 else if (objects.block)
252 {
253 objects.block.destroy();
254 objects.block = null;
255 }
256 objects.light = snapshot.light[index] ?? 0;
257 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
258 objects.shade.renderer.alpha = 0;
259 }
264 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
265 }
266 }
267
268 #redrawPreview ()
269 {
270 if (this.preview)
271 { this.#drawTile(this.preview.tileX, this.preview.tileY); }
272 }
273
274 #drawTile (tileX, tileY)
275 {
276 const chunkX = Math.floor(tileX / CHUNK_SIZE);
277 const chunkY = Math.floor(tileY / CHUNK_SIZE);
278 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
279 if (!snapshot)
280 { return; }
281 const localX = tileX - chunkX * CHUNK_SIZE;
282 const localY = tileY - chunkY * CHUNK_SIZE;
283 const index = localY * CHUNK_SIZE + localX;
284 const key = `${tileX},${tileY}`;
285 let objects = this.tiles.get(key);
286 if (!objects)
287 {
288 objects = { chunkX, chunkY };
289 this.tiles.set(key, objects);
290 }
291
292 let ground = snapshot.grounds[index];
293 let block = snapshot.blocks[index];
294 const preview = this.preview;
295 if (preview && preview.tileX === tileX && preview.tileY === tileY)
296 {
297 if (preview.ground !== undefined)
298 { ground = preview.ground; }
299 if (preview.block !== undefined)
300 { block = preview.block; }
301 }
302
303 const size = this.tileSize();
304 const pivot = tilePivot(tileX, tileY, size);
305 const groundName = this.#groundSpriteName(ground);
306 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
307 if (objects.ground)
308 {
309 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
310 objects.ground.layer = LAYER_GROUND;
311 }
312
313 const blockName = this.#blockSpriteName(block);
314 if (blockName)
315 {
316 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
317 if (objects.block)
318 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); }
319 }
320 else if (objects.block)
321 {
322 objects.block.destroy();
323 objects.block = null;
260 324 }
325
326 objects.light = snapshot.light[index] ?? 0;
327 const previousShade = objects.shade;
328 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
329 if (objects.shade && objects.shade !== previousShade)
330 { objects.shade.renderer.alpha = 0; }
331 }
332
333 #groundSpriteName (ground)
334 {
335 const entry = normalizeGround(ground);
336 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
337 const states = this.catalog.grounds?.[def.key]?.states ?? [];
338 const state = resolveState(states, entry.state);
339 return spriteImageName("ground", def.key, state);
340 }
341
342 #blockSpriteName (block)
343 {
344 const entry = normalizeBlock(block);
345 if (!entry)
346 { return null; }
347 const def = BLOCK_DEFINITIONS[entry.typeId];
348 if (!def)
349 { return null; }
350 const states = this.catalog.blocks?.[def.key]?.states ?? [];
351 const state = resolveState(states, entry.state);
352 return spriteImageName("block", def.key, state);
261 353 }
262 354
263 355 #tileFill (existing, name, x, y, layer)
264 356 {
265 357 existing = this.#ensureSprite(existing, name, layer);
358 if (!existing)
359 { return null; }
266 360 const size = this.tileSize();
267 361 existing.transform.position.x = x;
268 362 existing.transform.position.y = y;
@@ -274,7 +368,9 @@ export class WorldView
274 368
275 369 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
276 370 {
277 const sprite = object.renderer.sprite;
371 const sprite = object?.renderer?.sprite;
372 if (!sprite)
373 { return; }
278 374 const zoom = this.zoom;
279 375 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
280 376 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
@@ -288,11 +384,18 @@ export class WorldView
288 384 #ensureSprite (existing, name, layer)
289 385 {
290 386 const sprite = this.game.images[name];
387 if (!sprite)
388 {
389 existing?.destroy();
390 return null;
391 }
291 392 if (!existing || existing.renderer.sprite !== sprite)
292 393 {
293 394 existing?.destroy();
294 395 existing = new GameObject(0, 0, sprite, layer);
295 396 this.scene.addObject(existing);
397 if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
398 { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
296 399 }
297 400 return existing;
298 401 }
@@ -1,5 +1,6 @@
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS } from "/shared/protocol/constants.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS } from "/shared/definitions/tiles.js";
2import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock } from "/shared/definitions/tiles.js";
3import { resolveState, spriteImageName } from "/shared/definitions/tileSprites.js";
3import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
4
5
5const LAYER_GROUND = 0;
6const LAYER_GROUND = 0;
@@ -10,10 +11,12 @@ const SORT_ENTITY = 2;
10
11
11export class WorldView
12export class WorldView
12{
13{
13 constructor (game, scene)
14 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
14 {
15 {
15 this.game = game;
16 this.game = game;
16 this.scene = scene;
17 this.scene = scene;
18 this.catalog = catalog;
19 this.preview = null;
17 this.zoom = 2;
20 this.zoom = 2;
18 this.chunks = new Map();
21 this.chunks = new Map();
19 this.tiles = new Map();
22 this.tiles = new Map();
@@ -45,6 +48,7 @@ export class WorldView
45 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
48 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
46 this.chunks.set(key, snapshot);
49 this.chunks.set(key, snapshot);
47 this.#rebuildChunk(snapshot);
50 this.#rebuildChunk(snapshot);
51 this.#redrawPreview();
48 for (const entity of snapshot.entities ?? [])
52 for (const entity of snapshot.entities ?? [])
49 { this.#upsertEntity(entity); }
53 { this.#upsertEntity(entity); }
50 this.#rebuildAllEdges();
54 this.#rebuildAllEdges();
@@ -127,6 +131,7 @@ export class WorldView
127 this.#placeEntity(entity);
131 this.#placeEntity(entity);
128 }
132 }
129 this.#rebuildAllEdges();
133 this.#rebuildAllEdges();
134 this.#redrawPreview();
130 }
135 }
131
136
132 tileSize ()
137 tileSize ()
@@ -172,6 +177,38 @@ export class WorldView
172 this.#updateShade(deltaTime);
177 this.#updateShade(deltaTime);
173 }
178 }
174
179
180 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
181 {
182 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
183 if (!snapshot)
184 { return; }
185 const index = localY * CHUNK_SIZE + localX;
186 if (ground !== undefined)
187 { snapshot.grounds[index] = ground; }
188 if (block !== undefined)
189 { snapshot.blocks[index] = block; }
190 if (light !== undefined)
191 { snapshot.light[index] = light; }
192 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
193 }
194
195 setTilePreview (tileX, tileY, override)
196 {
197 const previous = this.preview;
198 this.preview = { tileX, tileY, ...override };
199 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
200 { this.#drawTile(previous.tileX, previous.tileY); }
201 this.#drawTile(tileX, tileY);
202 }
203
204 clearTilePreview ()
205 {
206 const previous = this.preview;
207 this.preview = null;
208 if (previous)
209 { this.#drawTile(previous.tileX, previous.tileY); }
210 }
211
175 #lerpMs (gait)
212 #lerpMs (gait)
176 {
213 {
177 const walk = this.settings.walkTilesPerSecond || 2;
214 const walk = this.settings.walkTilesPerSecond || 2;
@@ -221,48 +258,105 @@ export class WorldView
221
258
222 #rebuildChunk (snapshot)
259 #rebuildChunk (snapshot)
223 {
260 {
224 const size = this.tileSize();
225 for (let localY = 0; localY < CHUNK_SIZE; localY++)
261 for (let localY = 0; localY < CHUNK_SIZE; localY++)
226 {
262 {
227 for (let localX = 0; localX < CHUNK_SIZE; localX++)
263 for (let localX = 0; localX < CHUNK_SIZE; localX++)
228 {
264 { this.#drawTile(snapshot.chunkX * CHUNK_SIZE + localX, snapshot.chunkY * CHUNK_SIZE + localY); }
229 const index = localY * CHUNK_SIZE + localX;
265 }
230 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
266 }
231 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
267
232 const key = `${tileX},${tileY}`;
268 #redrawPreview ()
233 let objects = this.tiles.get(key);
269 {
234 if (!objects)
270 if (this.preview)
235 {
271 { this.#drawTile(this.preview.tileX, this.preview.tileY); }
236 objects = { chunkX: snapshot.chunkX, chunkY: snapshot.chunkY };
272 }
237 this.tiles.set(key, objects);
273
238 }
274 #drawTile (tileX, tileY)
239 const pivot = tilePivot(tileX, tileY, size);
275 {
240 const groundName = GROUND_DEFINITIONS[snapshot.grounds[index]]?.sprite ?? "ground-grass";
276 const chunkX = Math.floor(tileX / CHUNK_SIZE);
241 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
277 const chunkY = Math.floor(tileY / CHUNK_SIZE);
242 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
278 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
243 objects.ground.layer = LAYER_GROUND;
279 if (!snapshot)
244 const block = snapshot.blocks[index];
280 { return; }
245 const blockName = block ? BLOCK_DEFINITIONS[block.typeId]?.sprite : null;
281 const localX = tileX - chunkX * CHUNK_SIZE;
246 if (blockName)
282 const localY = tileY - chunkY * CHUNK_SIZE;
247 {
283 const index = localY * CHUNK_SIZE + localX;
248 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
284 const key = `${tileX},${tileY}`;
249 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK);
285 let objects = this.tiles.get(key);
250 }
286 if (!objects)
251 else if (objects.block)
287 {
252 {
288 objects = { chunkX, chunkY };
253 objects.block.destroy();
289 this.tiles.set(key, objects);
254 objects.block = null;
290 }
255 }
291
256 objects.light = snapshot.light[index] ?? 0;
292 let ground = snapshot.grounds[index];
257 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
293 let block = snapshot.blocks[index];
258 objects.shade.renderer.alpha = 0;
294 const preview = this.preview;
259 }
295 if (preview && preview.tileX === tileX && preview.tileY === tileY)
296 {
297 if (preview.ground !== undefined)
298 { ground = preview.ground; }
299 if (preview.block !== undefined)
300 { block = preview.block; }
301 }
302
303 const size = this.tileSize();
304 const pivot = tilePivot(tileX, tileY, size);
305 const groundName = this.#groundSpriteName(ground);
306 objects.ground = this.#ensureSprite(objects.ground, groundName, LAYER_GROUND);
307 if (objects.ground)
308 {
309 this.#placePivoted(objects.ground, pivot.x, pivot.y, pivot.y, 0);
310 objects.ground.layer = LAYER_GROUND;
311 }
312
313 const blockName = this.#blockSpriteName(block);
314 if (blockName)
315 {
316 objects.block = this.#ensureSprite(objects.block, blockName, SORT_BLOCK);
317 if (objects.block)
318 { this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_BLOCK); }
319 }
320 else if (objects.block)
321 {
322 objects.block.destroy();
323 objects.block = null;
260 }
324 }
325
326 objects.light = snapshot.light[index] ?? 0;
327 const previousShade = objects.shade;
328 objects.shade = this.#tileFill(objects.shade, "night-shade", pivot.x, pivot.y, LAYER_SHADE + tileY);
329 if (objects.shade && objects.shade !== previousShade)
330 { objects.shade.renderer.alpha = 0; }
331 }
332
333 #groundSpriteName (ground)
334 {
335 const entry = normalizeGround(ground);
336 const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass];
337 const states = this.catalog.grounds?.[def.key]?.states ?? [];
338 const state = resolveState(states, entry.state);
339 return spriteImageName("ground", def.key, state);
340 }
341
342 #blockSpriteName (block)
343 {
344 const entry = normalizeBlock(block);
345 if (!entry)
346 { return null; }
347 const def = BLOCK_DEFINITIONS[entry.typeId];
348 if (!def)
349 { return null; }
350 const states = this.catalog.blocks?.[def.key]?.states ?? [];
351 const state = resolveState(states, entry.state);
352 return spriteImageName("block", def.key, state);
261 }
353 }
262
354
263 #tileFill (existing, name, x, y, layer)
355 #tileFill (existing, name, x, y, layer)
264 {
356 {
265 existing = this.#ensureSprite(existing, name, layer);
357 existing = this.#ensureSprite(existing, name, layer);
358 if (!existing)
359 { return null; }
266 const size = this.tileSize();
360 const size = this.tileSize();
267 existing.transform.position.x = x;
361 existing.transform.position.x = x;
268 existing.transform.position.y = y;
362 existing.transform.position.y = y;
@@ -274,7 +368,9 @@ export class WorldView
274
368
275 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
369 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
276 {
370 {
277 const sprite = object.renderer.sprite;
371 const sprite = object?.renderer?.sprite;
372 if (!sprite)
373 { return; }
278 const zoom = this.zoom;
374 const zoom = this.zoom;
279 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
375 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
280 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
376 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
@@ -288,11 +384,18 @@ export class WorldView
288 #ensureSprite (existing, name, layer)
384 #ensureSprite (existing, name, layer)
289 {
385 {
290 const sprite = this.game.images[name];
386 const sprite = this.game.images[name];
387 if (!sprite)
388 {
389 existing?.destroy();
390 return null;
391 }
291 if (!existing || existing.renderer.sprite !== sprite)
392 if (!existing || existing.renderer.sprite !== sprite)
292 {
393 {
293 existing?.destroy();
394 existing?.destroy();
294 existing = new GameObject(0, 0, sprite, layer);
395 existing = new GameObject(0, 0, sprite, layer);
295 this.scene.addObject(existing);
396 this.scene.addObject(existing);
397 if (sprite.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
398 { existing.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
296 }
399 }
297 return existing;
400 return existing;
298 }
401 }
docs/FEATURES.md +11 −5
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16 16 ## Ground and block tile layers
17 17
18 18 **Status:** full
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch.
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`
19 **Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. Each type's PNGs live in a per-type folder; filenames are visual states (first alphabetical is default).
20 **Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `server/src/assets/spriteCatalog.js`
21 21
22 22 ## Open and closed chunks
23 23
@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
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, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
73 **Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
74 74 **Code:** `client/editor.html`, `client/src/editor/main.js`, `client/ui/editor.css`
75 75
76 76 ## Per-chunk changelog
@@ -148,8 +148,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
148 148 ## Sprite size, pivot and Y-sort
149 149
150 150 **Status:** full
151 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south).
152 **Code:** `shared/render/pivot.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
151 **Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets.
152 **Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
153
154 ## Visual tile states
155
156 **Status:** full
157 **Spec:** Each ground and block type has a folder of PNG states. The first alphabetical file is the default. States are visual only; the game may set a named state (for example a door). The editor wheel cycles states; hover previews the selected tool on the target tile.
158 **Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`
153 159
154 160 ## Region workers and cross-worker transfer
155 161
@@ -16,8 +16,8 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
16## Ground and block tile layers
16## Ground and block tile layers
17
17
18**Status:** full
18**Status:** full
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch.
19**Spec:** Every tile has a visual ground type. An optional block supplies collision and behaviour. Unedited chunks are default grass with no blocks. First-version types are grass, wood, stone wall, and torch. Each type's PNGs live in a per-type folder; filenames are visual states (first alphabetical is default).
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`
20**Code:** `server/src/world/chunkData.js`, `shared/definitions/tiles.js`, `server/src/assets/spriteCatalog.js`
21
21
22## Open and closed chunks
22## Open and closed chunks
23
23
@@ -70,7 +70,7 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
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, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
73**Spec:** Separate `/editor` page. 3×3 chunk view with the selected chunk centred and outlined in red. Chunk-step navigation, paint only inside the selected chunk, hover preview of the selected tool, mouse wheel to cycle visual states, open/closed, per-chunk changelog, night preview slider, world-settings modal (categories, dirty highlighting, settings log), save chunk and Apply now. Marketplace placement waits on assets.
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
@@ -148,8 +148,14 @@ Each entry is a short note on behaviour and where the code lives. Update this fi
148## Sprite size, pivot and Y-sort
148## Sprite size, pivot and Y-sort
149
149
150**Status:** full
150**Status:** full
151**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south).
151**Spec:** World sprites may be any pixel size. Pivot is horizontal centre and 8px from the sprite bottom, placed on the tile centre. Blocks and mobiles are Y-sorted (north behind south). Ground/block definitions set `frames`, `framesPerRow`, and `animationSpeed` for sprite sheets.
152**Code:** `shared/render/pivot.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
152**Code:** `shared/render/pivot.js`, `shared/definitions/tiles.js`, `client/src/render/worldView.js`, tests in `server/tests/pivot.test.js`
153
154## Visual tile states
155
156**Status:** full
157**Spec:** Each ground and block type has a folder of PNG states. The first alphabetical file is the default. States are visual only; the game may set a named state (for example a door). The editor wheel cycles states; hover previews the selected tool on the target tile.
158**Code:** `server/src/assets/spriteCatalog.js`, `shared/definitions/tileSprites.js`, `client/src/editor/main.js`, `client/src/render/worldView.js`, tests in `server/tests/tile-states.test.js`
153
159
154## Region workers and cross-worker transfer
160## Region workers and cross-worker transfer
155
161
server/src/assets/spriteCatalog.js added +71 −0
@@ -0,0 +1,71 @@
1 import { readdirSync } from "node:fs";
2 import { extname, join } from "node:path";
3 import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4 import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
5
6 export function buildSpriteCatalog (assetRoot)
7 {
8 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground");
9 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block");
10 return {
11 grounds: grounds.types,
12 blocks: blocks.types,
13 images: [...grounds.images, ...blocks.images]
14 };
15 }
16
17 function scanLayer (layerDir, definitions, layer)
18 {
19 const types = {};
20 const images = [];
21 for (const def of Object.values(definitions))
22 {
23 const folder = join(layerDir, def.key);
24 const states = listPngStates(folder);
25 if (states.length === 0)
26 { throw new Error(`No PNG states in ${folder}`); }
27
28 const frames = Math.max(1, def.frames ?? 1);
29 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
30 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
31 types[def.key] = {
32 key: def.key,
33 typeId: def.id,
34 states,
35 defaultState: states[0],
36 frames,
37 framesPerRow,
38 animationSpeed
39 };
40 for (const state of states)
41 {
42 images.push({
43 name: spriteImageName(layer, def.key, state),
44 url: `/assets/${layer === "ground" ? "grounds" : "blocks"}/${def.key}/${state}.png`,
45 subImgTotal: frames,
46 perRow: framesPerRow,
47 loop: animationSpeed > 0,
48 animationSpeed
49 });
50 }
51 }
52 return { types, images };
53 }
54
55 function listPngStates (folder)
56 {
57 let entries;
58 try
59 { entries = readdirSync(folder, { withFileTypes: true }); }
60 catch (error)
61 {
62 if (error.code === "ENOENT")
63 { return []; }
64 throw error;
65 }
66
67 return entries
68 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
69 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
70 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
71 }
@@ -0,0 +1,71 @@
1import { readdirSync } from "node:fs";
2import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS } from "../../../shared/definitions/tiles.js";
4import { spriteImageName } from "../../../shared/definitions/tileSprites.js";
5
6export function buildSpriteCatalog (assetRoot)
7{
8 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground");
9 const blocks = scanLayer(join(assetRoot, "blocks"), BLOCK_DEFINITIONS, "block");
10 return {
11 grounds: grounds.types,
12 blocks: blocks.types,
13 images: [...grounds.images, ...blocks.images]
14 };
15}
16
17function scanLayer (layerDir, definitions, layer)
18{
19 const types = {};
20 const images = [];
21 for (const def of Object.values(definitions))
22 {
23 const folder = join(layerDir, def.key);
24 const states = listPngStates(folder);
25 if (states.length === 0)
26 { throw new Error(`No PNG states in ${folder}`); }
27
28 const frames = Math.max(1, def.frames ?? 1);
29 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
30 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
31 types[def.key] = {
32 key: def.key,
33 typeId: def.id,
34 states,
35 defaultState: states[0],
36 frames,
37 framesPerRow,
38 animationSpeed
39 };
40 for (const state of states)
41 {
42 images.push({
43 name: spriteImageName(layer, def.key, state),
44 url: `/assets/${layer === "ground" ? "grounds" : "blocks"}/${def.key}/${state}.png`,
45 subImgTotal: frames,
46 perRow: framesPerRow,
47 loop: animationSpeed > 0,
48 animationSpeed
49 });
50 }
51 }
52 return { types, images };
53}
54
55function listPngStates (folder)
56{
57 let entries;
58 try
59 { entries = readdirSync(folder, { withFileTypes: true }); }
60 catch (error)
61 {
62 if (error.code === "ENOENT")
63 { return []; }
64 throw error;
65 }
66
67 return entries
68 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
69 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
70 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
71}
server/src/editor/service.js +27 −10
@@ -1,4 +1,4 @@
1 import { groundDefinition, blockDefinition } from "../../../shared/definitions/tiles.js";
1 import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2 2 import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3 3 import { localToTile } from "../world/coordinates.js";
4 4 import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../world/chunkData.js";
@@ -47,15 +47,15 @@ export class EditorService
47 47 {
48 48 const previous = this.loadChunk(chunkX, chunkY);
49 49 const next = cloneChunkData(previous.data);
50 const settings = previous.settings ?? this.worldDb.getLiveSettings();
50 51 next.open = !!draft.open;
51 52 if (Array.isArray(draft.grounds))
52 { next.grounds = draft.grounds.slice(); }
53 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
53 54 if (Array.isArray(draft.blocks))
54 { next.blocks = draft.blocks.map((block) => (block ? { typeId: block.typeId, config: block.config ?? null } : null)); }
55 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
55 56
56 57 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
57 58 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
58 const settings = this.worldDb.getLiveSettings();
59 59 const baked = bakeLightMaps(
60 60 chunkX,
61 61 chunkY,
@@ -159,17 +159,23 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
159 159 const index = localY * CHUNK_SIZE + localX;
160 160 const tileX = localToTile(chunkX, localX);
161 161 const tileY = localToTile(chunkY, localY);
162 const prevGround = previous.grounds[index];
163 const nextGround = next.grounds[index];
164 if (prevGround !== nextGround)
162 const prevGround = normalizeGround(previous.grounds[index]);
163 const nextGround = normalizeGround(next.grounds[index]);
164 if (prevGround.typeId !== nextGround.typeId)
165 {
166 bullets.push(
167 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
168 );
169 }
170 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
165 171 {
166 172 bullets.push(
167 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround)} to ${nameGround(nextGround)}.`
173 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
168 174 );
169 175 }
170 176
171 const prevBlock = previous.blocks[index];
172 const nextBlock = next.blocks[index];
177 const prevBlock = normalizeBlock(previous.blocks[index]);
178 const nextBlock = normalizeBlock(next.blocks[index]);
173 179 const prevId = prevBlock?.typeId ?? null;
174 180 const nextId = nextBlock?.typeId ?? null;
175 181 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
@@ -183,6 +189,12 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
183 189 else
184 190 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
185 191 }
192 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
193 {
194 bullets.push(
195 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
196 );
197 }
186 198 }
187 199 }
188 200 return bullets;
@@ -197,3 +209,8 @@ function nameBlock (typeId)
197 209 {
198 210 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
199 211 }
212
213 function stateLabel (state)
214 {
215 return state || "default";
216 }
@@ -1,4 +1,4 @@
1import { groundDefinition, blockDefinition } from "../../../shared/definitions/tiles.js";
1import { groundDefinition, blockDefinition, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
2import { CHUNK_SIZE } from "../../../shared/protocol/constants.js";
3import { localToTile } from "../world/coordinates.js";
3import { localToTile } from "../world/coordinates.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../world/chunkData.js";
4import { cloneChunkData, createEmptyChunkData, decodeChunkBlob, encodeChunkBlob } from "../world/chunkData.js";
@@ -47,15 +47,15 @@ export class EditorService
47 {
47 {
48 const previous = this.loadChunk(chunkX, chunkY);
48 const previous = this.loadChunk(chunkX, chunkY);
49 const next = cloneChunkData(previous.data);
49 const next = cloneChunkData(previous.data);
50 const settings = previous.settings ?? this.worldDb.getLiveSettings();
50 next.open = !!draft.open;
51 next.open = !!draft.open;
51 if (Array.isArray(draft.grounds))
52 if (Array.isArray(draft.grounds))
52 { next.grounds = draft.grounds.slice(); }
53 { next.grounds = draft.grounds.map((ground) => normalizeGround(ground, settings.defaultGroundTypeId)); }
53 if (Array.isArray(draft.blocks))
54 if (Array.isArray(draft.blocks))
54 { next.blocks = draft.blocks.map((block) => (block ? { typeId: block.typeId, config: block.config ?? null } : null)); }
55 { next.blocks = draft.blocks.map((block) => normalizeBlock(block)); }
55
56
56 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
57 const diffEntries = diffChunks(chunkX, chunkY, previous.data, next, previous.authored);
57 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
58 const revisionId = this.worldDb.ensurePendingRevision(editorAdminId);
58 const settings = this.worldDb.getLiveSettings();
59 const baked = bakeLightMaps(
59 const baked = bakeLightMaps(
60 chunkX,
60 chunkX,
61 chunkY,
61 chunkY,
@@ -159,17 +159,23 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
159 const index = localY * CHUNK_SIZE + localX;
159 const index = localY * CHUNK_SIZE + localX;
160 const tileX = localToTile(chunkX, localX);
160 const tileX = localToTile(chunkX, localX);
161 const tileY = localToTile(chunkY, localY);
161 const tileY = localToTile(chunkY, localY);
162 const prevGround = previous.grounds[index];
162 const prevGround = normalizeGround(previous.grounds[index]);
163 const nextGround = next.grounds[index];
163 const nextGround = normalizeGround(next.grounds[index]);
164 if (prevGround !== nextGround)
164 if (prevGround.typeId !== nextGround.typeId)
165 {
166 bullets.push(
167 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround.typeId)} to ${nameGround(nextGround.typeId)}.`
168 );
169 }
170 else if ((prevGround.state ?? "") !== (nextGround.state ?? ""))
165 {
171 {
166 bullets.push(
172 bullets.push(
167 `Ground at ${tileX}, ${tileY} changed from ${nameGround(prevGround)} to ${nameGround(nextGround)}.`
173 `Ground ${nameGround(nextGround.typeId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevGround.state)} to ${stateLabel(nextGround.state)}.`
168 );
174 );
169 }
175 }
170
176
171 const prevBlock = previous.blocks[index];
177 const prevBlock = normalizeBlock(previous.blocks[index]);
172 const nextBlock = next.blocks[index];
178 const nextBlock = normalizeBlock(next.blocks[index]);
173 const prevId = prevBlock?.typeId ?? null;
179 const prevId = prevBlock?.typeId ?? null;
174 const nextId = nextBlock?.typeId ?? null;
180 const nextId = nextBlock?.typeId ?? null;
175 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
181 const prevConfig = JSON.stringify(prevBlock?.config ?? null);
@@ -183,6 +189,12 @@ export function diffChunks (chunkX, chunkY, previous, next, previousAuthored)
183 else
189 else
184 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
190 { bullets.push(`Block at ${tileX}, ${tileY} changed from ${nameBlock(prevId)} to ${nameBlock(nextId)}.`); }
185 }
191 }
192 else if (prevBlock && nextBlock && (prevBlock.state ?? "") !== (nextBlock.state ?? ""))
193 {
194 bullets.push(
195 `Block ${nameBlock(nextId)} at ${tileX}, ${tileY} state changed from ${stateLabel(prevBlock.state)} to ${stateLabel(nextBlock.state)}.`
196 );
197 }
186 }
198 }
187 }
199 }
188 return bullets;
200 return bullets;
@@ -197,3 +209,8 @@ function nameBlock (typeId)
197{
209{
198 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
210 return blockDefinition(typeId)?.displayName ?? `block ${typeId}`;
199}
211}
212
213function stateLabel (state)
214{
215 return state || "default";
216}
server/src/gateway/http.js +15 −0
@@ -2,6 +2,7 @@ import { createServer } from "node:http";
2 2 import { createReadStream, existsSync, statSync } from "node:fs";
3 3 import { extname, join, normalize, relative, sep } from "node:path";
4 4 import { fileURLToPath } from "node:url";
5 import { buildSpriteCatalog } from "../assets/spriteCatalog.js";
5 6
6 7 const MIME = {
7 8 ".html": "text/html; charset=utf-8",
@@ -24,6 +25,13 @@ export function createHttpServer (rootDir)
24 25 try
25 26 {
26 27 const url = new URL(req.url ?? "/", "http://localhost");
28 if (url.pathname === "/assets/catalog.json")
29 {
30 const catalog = spriteCatalogFor(clientDir);
31 res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
32 res.end(JSON.stringify(catalog));
33 return;
34 }
27 35 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
28 36 if (!filePath)
29 37 {
@@ -70,6 +78,13 @@ function safeJoin (root, relativePath)
70 78 return resolved;
71 79 }
72 80
81 function spriteCatalogFor (clientDir)
82 {
83 if (!spriteCatalogFor.cache)
84 { spriteCatalogFor.cache = buildSpriteCatalog(join(clientDir, "assets")); }
85 return spriteCatalogFor.cache;
86 }
87
73 88 export function repoRootFrom (url)
74 89 {
75 90 return join(fileURLToPath(new URL(".", url)), "../..");
@@ -2,6 +2,7 @@ import { createServer } from "node:http";
2import { createReadStream, existsSync, statSync } from "node:fs";
2import { createReadStream, existsSync, statSync } from "node:fs";
3import { extname, join, normalize, relative, sep } from "node:path";
3import { extname, join, normalize, relative, sep } from "node:path";
4import { fileURLToPath } from "node:url";
4import { fileURLToPath } from "node:url";
5import { buildSpriteCatalog } from "../assets/spriteCatalog.js";
5
6
6const MIME = {
7const MIME = {
7 ".html": "text/html; charset=utf-8",
8 ".html": "text/html; charset=utf-8",
@@ -24,6 +25,13 @@ export function createHttpServer (rootDir)
24 try
25 try
25 {
26 {
26 const url = new URL(req.url ?? "/", "http://localhost");
27 const url = new URL(req.url ?? "/", "http://localhost");
28 if (url.pathname === "/assets/catalog.json")
29 {
30 const catalog = spriteCatalogFor(clientDir);
31 res.writeHead(200, { "content-type": "application/json; charset=utf-8" });
32 res.end(JSON.stringify(catalog));
33 return;
34 }
27 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
35 const filePath = resolvePublicPath(url.pathname, clientDir, sharedDir, frameworkDir);
28 if (!filePath)
36 if (!filePath)
29 {
37 {
@@ -70,6 +78,13 @@ function safeJoin (root, relativePath)
70 return resolved;
78 return resolved;
71}
79}
72
80
81function spriteCatalogFor (clientDir)
82{
83 if (!spriteCatalogFor.cache)
84 { spriteCatalogFor.cache = buildSpriteCatalog(join(clientDir, "assets")); }
85 return spriteCatalogFor.cache;
86}
87
73export function repoRootFrom (url)
88export function repoRootFrom (url)
74{
89{
75 return join(fileURLToPath(new URL(".", url)), "../..");
90 return join(fileURLToPath(new URL(".", url)), "../..");
server/src/world/chunkData.js +16 −14
@@ -1,11 +1,11 @@
1 1 import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2 import { GroundType, isBlockPassable, blockLightRange } from "../../../shared/definitions/tiles.js";
2 import { GroundType, isBlockPassable, blockLightRange, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
3 3 import { tileIndex } from "./coordinates.js";
4 4
5 5 export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
6 6 {
7 7 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
8 const grounds = new Array(tileCount).fill(groundTypeId);
8 const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));
9 9 const blocks = new Array(tileCount).fill(null);
10 10 const light = new Array(tileCount).fill(0);
11 11 return {
@@ -20,8 +20,8 @@ export function cloneChunkData (data)
20 20 {
21 21 return {
22 22 open: data.open,
23 grounds: data.grounds.slice(),
24 blocks: data.blocks.map((block) => (block ? { typeId: block.typeId, config: block.config ?? null } : null)),
23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 blocks: data.blocks.map((block) => normalizeBlock(block)),
25 25 light: data.light.slice()
26 26 };
27 27 }
@@ -30,8 +30,8 @@ export function encodeChunkBlob (data)
30 30 {
31 31 return JSON.stringify({
32 32 open: !!data.open,
33 grounds: data.grounds,
34 blocks: data.blocks,
33 grounds: data.grounds.map((ground) => normalizeGround(ground)),
34 blocks: data.blocks.map((block) => normalizeBlock(block)),
35 35 light: data.light
36 36 });
37 37 }
@@ -49,7 +49,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
49 49 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
50 50
51 51 while (grounds.length < tileCount)
52 { grounds.push(groundTypeId); }
52 { grounds.push(normalizeGround(groundTypeId, groundTypeId)); }
53 53 while (blocks.length < tileCount)
54 54 { blocks.push(null); }
55 55 while (light.length < tileCount)
@@ -57,8 +57,8 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
57 57
58 58 return {
59 59 open: !!parsed.open,
60 grounds,
61 blocks,
60 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
61 blocks: blocks.map((block) => normalizeBlock(block)),
62 62 light
63 63 };
64 64 }
@@ -66,21 +66,23 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
66 66 export function getTile (data, localX, localY)
67 67 {
68 68 const index = tileIndex(localX, localY);
69 const ground = normalizeGround(data.grounds[index]);
69 70 return {
70 groundTypeId: data.grounds[index],
71 groundTypeId: ground.typeId,
72 groundState: ground.state,
71 73 block: data.blocks[index],
72 74 light: data.light[index]
73 75 };
74 76 }
75 77
76 export function setGround (data, localX, localY, groundTypeId)
78 export function setGround (data, localX, localY, groundTypeId, state = null)
77 79 {
78 data.grounds[tileIndex(localX, localY)] = groundTypeId;
80 data.grounds[tileIndex(localX, localY)] = normalizeGround({ typeId: groundTypeId, state });
79 81 }
80 82
81 83 export function setBlock (data, localX, localY, block)
82 84 {
83 data.blocks[tileIndex(localX, localY)] = block;
85 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
84 86 }
85 87
86 88 export function isChunkTilePassable (data, localX, localY)
@@ -111,4 +113,4 @@ export function collectLightSources (chunkX, chunkY, data)
111 113 return sources;
112 114 }
113 115
114 export { GroundType };
116 export { GroundType, normalizeGround, normalizeBlock };
@@ -1,11 +1,11 @@
1import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
1import { CHUNK_SIZE, DEFAULT_WORLD_SETTINGS } from "../../../shared/protocol/constants.js";
2import { GroundType, isBlockPassable, blockLightRange } from "../../../shared/definitions/tiles.js";
2import { GroundType, isBlockPassable, blockLightRange, normalizeGround, normalizeBlock } from "../../../shared/definitions/tiles.js";
3import { tileIndex } from "./coordinates.js";
3import { tileIndex } from "./coordinates.js";
4
4
5export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
5export function createEmptyChunkData (groundTypeId = DEFAULT_WORLD_SETTINGS.defaultGroundTypeId)
6{
6{
7 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
7 const tileCount = CHUNK_SIZE * CHUNK_SIZE;
8 const grounds = new Array(tileCount).fill(groundTypeId);
8 const grounds = new Array(tileCount).fill(null).map(() => normalizeGround(groundTypeId, groundTypeId));
9 const blocks = new Array(tileCount).fill(null);
9 const blocks = new Array(tileCount).fill(null);
10 const light = new Array(tileCount).fill(0);
10 const light = new Array(tileCount).fill(0);
11 return {
11 return {
@@ -20,8 +20,8 @@ export function cloneChunkData (data)
20{
20{
21 return {
21 return {
22 open: data.open,
22 open: data.open,
23 grounds: data.grounds.slice(),
23 grounds: data.grounds.map((ground) => normalizeGround(ground)),
24 blocks: data.blocks.map((block) => (block ? { typeId: block.typeId, config: block.config ?? null } : null)),
24 blocks: data.blocks.map((block) => normalizeBlock(block)),
25 light: data.light.slice()
25 light: data.light.slice()
26 };
26 };
27}
27}
@@ -30,8 +30,8 @@ export function encodeChunkBlob (data)
30{
30{
31 return JSON.stringify({
31 return JSON.stringify({
32 open: !!data.open,
32 open: !!data.open,
33 grounds: data.grounds,
33 grounds: data.grounds.map((ground) => normalizeGround(ground)),
34 blocks: data.blocks,
34 blocks: data.blocks.map((block) => normalizeBlock(block)),
35 light: data.light
35 light: data.light
36 });
36 });
37}
37}
@@ -49,7 +49,7 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
49 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
49 const light = Array.isArray(parsed.light) ? parsed.light.slice(0, tileCount) : fallback.light;
50
50
51 while (grounds.length < tileCount)
51 while (grounds.length < tileCount)
52 { grounds.push(groundTypeId); }
52 { grounds.push(normalizeGround(groundTypeId, groundTypeId)); }
53 while (blocks.length < tileCount)
53 while (blocks.length < tileCount)
54 { blocks.push(null); }
54 { blocks.push(null); }
55 while (light.length < tileCount)
55 while (light.length < tileCount)
@@ -57,8 +57,8 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
57
57
58 return {
58 return {
59 open: !!parsed.open,
59 open: !!parsed.open,
60 grounds,
60 grounds: grounds.map((ground) => normalizeGround(ground, groundTypeId)),
61 blocks,
61 blocks: blocks.map((block) => normalizeBlock(block)),
62 light
62 light
63 };
63 };
64}
64}
@@ -66,21 +66,23 @@ export function decodeChunkBlob (blob, groundTypeId = DEFAULT_WORLD_SETTINGS.def
66export function getTile (data, localX, localY)
66export function getTile (data, localX, localY)
67{
67{
68 const index = tileIndex(localX, localY);
68 const index = tileIndex(localX, localY);
69 const ground = normalizeGround(data.grounds[index]);
69 return {
70 return {
70 groundTypeId: data.grounds[index],
71 groundTypeId: ground.typeId,
72 groundState: ground.state,
71 block: data.blocks[index],
73 block: data.blocks[index],
72 light: data.light[index]
74 light: data.light[index]
73 };
75 };
74}
76}
75
77
76export function setGround (data, localX, localY, groundTypeId)
78export function setGround (data, localX, localY, groundTypeId, state = null)
77{
79{
78 data.grounds[tileIndex(localX, localY)] = groundTypeId;
80 data.grounds[tileIndex(localX, localY)] = normalizeGround({ typeId: groundTypeId, state });
79}
81}
80
82
81export function setBlock (data, localX, localY, block)
83export function setBlock (data, localX, localY, block)
82{
84{
83 data.blocks[tileIndex(localX, localY)] = block;
85 data.blocks[tileIndex(localX, localY)] = normalizeBlock(block);
84}
86}
85
87
86export function isChunkTilePassable (data, localX, localY)
88export function isChunkTilePassable (data, localX, localY)
@@ -111,4 +113,4 @@ export function collectLightSources (chunkX, chunkY, data)
111 return sources;
113 return sources;
112}
114}
113
115
114export { GroundType };
116export { GroundType, normalizeGround, normalizeBlock };
server/tests/tile-states.test.js added +63 −0
@@ -0,0 +1,63 @@
1 import test from "node:test";
2 import assert from "node:assert/strict";
3 import { fileURLToPath } from "node:url";
4 import { join } from "node:path";
5 import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6 import { cycleState, resolveState } from "../../shared/definitions/tileSprites.js";
7 import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
8 import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
9 import { diffChunks } from "../src/editor/service.js";
10
11 const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
12
13 test("sprite folders expose alphabetical states; first is default", () =>
14 {
15 const catalog = buildSpriteCatalog(ASSET_ROOT);
16 assert.deepEqual(catalog.blocks["stone-wall"].states, ["1", "2"]);
17 assert.equal(catalog.blocks["stone-wall"].defaultState, "1");
18 assert.ok(catalog.images.some((image) => image.name === "block:stone-wall:2"));
19 assert.equal(catalog.images[0].subImgTotal, 1);
20 assert.equal(catalog.images[0].perRow, 1);
21 });
22
23 test("state cycling wraps and unknown values fall back to default", () =>
24 {
25 assert.equal(resolveState(["closed", "open"], null), "closed");
26 assert.equal(resolveState(["closed", "open"], "open"), "open");
27 assert.equal(resolveState(["closed", "open"], "missing"), "closed");
28 assert.equal(cycleState(["1", "2"], "1", 1), "2");
29 assert.equal(cycleState(["1", "2"], "2", 1), "1");
30 assert.equal(cycleState(["1", "2"], "1", -1), "2");
31 });
32
33 test("old numeric grounds decode as default visual state", () =>
34 {
35 const data = decodeChunkBlob({
36 open: true,
37 grounds: [GroundType.wood],
38 blocks: [{ typeId: BlockType.stoneWall, config: null }],
39 light: [0]
40 });
41 assert.deepEqual(data.grounds[0], { typeId: GroundType.wood, state: null });
42 assert.equal(data.blocks[0].state, null);
43 assert.equal(data.blocks[0].typeId, BlockType.stoneWall);
44 });
45
46 test("gameplay can set a block visual state", () =>
47 {
48 const data = createEmptyChunkData();
49 data.blocks[0] = { typeId: BlockType.stoneWall, state: null, config: null };
50 setBlockVisualState(data.blocks[0], "2");
51 assert.equal(data.blocks[0].state, "2");
52 });
53
54 test("chunk diffs mention visual state changes", () =>
55 {
56 const previous = createEmptyChunkData();
57 const next = createEmptyChunkData();
58 previous.blocks[0] = { typeId: BlockType.stoneWall, state: "1", config: null };
59 next.blocks[0] = { typeId: BlockType.stoneWall, state: "2", config: null };
60 const bullets = diffChunks(0, 0, previous, next, true);
61 assert.ok(bullets.some((line) => line.includes("state changed from 1 to 2")));
62 assert.equal(normalizeGround(GroundType.grass).typeId, GroundType.grass);
63 });
@@ -0,0 +1,63 @@
1import test from "node:test";
2import assert from "node:assert/strict";
3import { fileURLToPath } from "node:url";
4import { join } from "node:path";
5import { buildSpriteCatalog } from "../src/assets/spriteCatalog.js";
6import { cycleState, resolveState } from "../../shared/definitions/tileSprites.js";
7import { decodeChunkBlob, createEmptyChunkData } from "../src/world/chunkData.js";
8import { GroundType, BlockType, normalizeGround, setBlockVisualState } from "../../shared/definitions/tiles.js";
9import { diffChunks } from "../src/editor/service.js";
10
11const ASSET_ROOT = join(fileURLToPath(new URL("../../client/assets", import.meta.url)));
12
13test("sprite folders expose alphabetical states; first is default", () =>
14{
15 const catalog = buildSpriteCatalog(ASSET_ROOT);
16 assert.deepEqual(catalog.blocks["stone-wall"].states, ["1", "2"]);
17 assert.equal(catalog.blocks["stone-wall"].defaultState, "1");
18 assert.ok(catalog.images.some((image) => image.name === "block:stone-wall:2"));
19 assert.equal(catalog.images[0].subImgTotal, 1);
20 assert.equal(catalog.images[0].perRow, 1);
21});
22
23test("state cycling wraps and unknown values fall back to default", () =>
24{
25 assert.equal(resolveState(["closed", "open"], null), "closed");
26 assert.equal(resolveState(["closed", "open"], "open"), "open");
27 assert.equal(resolveState(["closed", "open"], "missing"), "closed");
28 assert.equal(cycleState(["1", "2"], "1", 1), "2");
29 assert.equal(cycleState(["1", "2"], "2", 1), "1");
30 assert.equal(cycleState(["1", "2"], "1", -1), "2");
31});
32
33test("old numeric grounds decode as default visual state", () =>
34{
35 const data = decodeChunkBlob({
36 open: true,
37 grounds: [GroundType.wood],
38 blocks: [{ typeId: BlockType.stoneWall, config: null }],
39 light: [0]
40 });
41 assert.deepEqual(data.grounds[0], { typeId: GroundType.wood, state: null });
42 assert.equal(data.blocks[0].state, null);
43 assert.equal(data.blocks[0].typeId, BlockType.stoneWall);
44});
45
46test("gameplay can set a block visual state", () =>
47{
48 const data = createEmptyChunkData();
49 data.blocks[0] = { typeId: BlockType.stoneWall, state: null, config: null };
50 setBlockVisualState(data.blocks[0], "2");
51 assert.equal(data.blocks[0].state, "2");
52});
53
54test("chunk diffs mention visual state changes", () =>
55{
56 const previous = createEmptyChunkData();
57 const next = createEmptyChunkData();
58 previous.blocks[0] = { typeId: BlockType.stoneWall, state: "1", config: null };
59 next.blocks[0] = { typeId: BlockType.stoneWall, state: "2", config: null };
60 const bullets = diffChunks(0, 0, previous, next, true);
61 assert.ok(bullets.some((line) => line.includes("state changed from 1 to 2")));
62 assert.equal(normalizeGround(GroundType.grass).typeId, GroundType.grass);
63});
shared/definitions/tileSprites.js added +35 −0
@@ -0,0 +1,35 @@
1 export function resolveState (states, requested)
2 {
3 if (!states?.length)
4 { return null; }
5 if (requested && states.includes(requested))
6 { return requested; }
7 return states[0];
8 }
9
10 export function cycleState (states, current, direction)
11 {
12 if (!states?.length)
13 { return null; }
14 const resolved = resolveState(states, current);
15 const index = states.indexOf(resolved);
16 const step = direction < 0 ? -1 : 1;
17 return states[(index + step + states.length) % states.length];
18 }
19
20 export function spriteImageName (layer, key, state)
21 {
22 return `${layer}:${key}:${state}`;
23 }
24
25 export function statesForType (catalog, layer, key)
26 {
27 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
28 return group?.[key]?.states ?? [];
29 }
30
31 export function defaultStateForType (catalog, layer, key)
32 {
33 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
34 return group?.[key]?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
35 }
@@ -0,0 +1,35 @@
1export function resolveState (states, requested)
2{
3 if (!states?.length)
4 { return null; }
5 if (requested && states.includes(requested))
6 { return requested; }
7 return states[0];
8}
9
10export function cycleState (states, current, direction)
11{
12 if (!states?.length)
13 { return null; }
14 const resolved = resolveState(states, current);
15 const index = states.indexOf(resolved);
16 const step = direction < 0 ? -1 : 1;
17 return states[(index + step + states.length) % states.length];
18}
19
20export function spriteImageName (layer, key, state)
21{
22 return `${layer}:${key}:${state}`;
23}
24
25export function statesForType (catalog, layer, key)
26{
27 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
28 return group?.[key]?.states ?? [];
29}
30
31export function defaultStateForType (catalog, layer, key)
32{
33 const group = layer === "ground" ? catalog?.grounds : catalog?.blocks;
34 return group?.[key]?.defaultState ?? resolveState(statesForType(catalog, layer, key), null);
35}
shared/definitions/tiles.js +38 −6
@@ -13,13 +13,17 @@ export const GROUND_DEFINITIONS = Object.freeze({
13 13 id: GroundType.grass,
14 14 key: "grass",
15 15 displayName: "Grass",
16 sprite: "ground-grass"
16 frames: 1,
17 framesPerRow: 1,
18 animationSpeed: 0
17 19 }),
18 20 [GroundType.wood]: Object.freeze({
19 21 id: GroundType.wood,
20 22 key: "wood",
21 23 displayName: "Wood",
22 sprite: "ground-wood"
24 frames: 1,
25 framesPerRow: 1,
26 animationSpeed: 0
23 27 })
24 28 });
25 29
@@ -28,17 +32,21 @@ export const BLOCK_DEFINITIONS = Object.freeze({
28 32 id: BlockType.stoneWall,
29 33 key: "stone-wall",
30 34 displayName: "Stone wall",
31 sprite: "block-stone-wall",
32 35 passable: false,
33 lightRangeTiles: 0
36 lightRangeTiles: 0,
37 frames: 1,
38 framesPerRow: 1,
39 animationSpeed: 0
34 40 }),
35 41 [BlockType.torch]: Object.freeze({
36 42 id: BlockType.torch,
37 43 key: "torch",
38 44 displayName: "Torch",
39 sprite: "block-torch",
40 45 passable: true,
41 lightRangeTiles: 8
46 lightRangeTiles: 8,
47 frames: 1,
48 framesPerRow: 1,
49 animationSpeed: 0
42 50 })
43 51 });
44 52
@@ -66,3 +74,27 @@ export function blockLightRange (typeId)
66 74 const def = blockDefinition(typeId);
67 75 return def ? def.lightRangeTiles : 0;
68 76 }
77
78 export function normalizeGround (value, fallbackTypeId = GroundType.grass)
79 {
80 if (typeof value === "number")
81 { return { typeId: value, state: null }; }
82 if (value && Number.isInteger(value.typeId))
83 { return { typeId: value.typeId, state: value.state ?? null }; }
84 return { typeId: fallbackTypeId, state: null };
85 }
86
87 export function normalizeBlock (value)
88 {
89 if (!value || !Number.isInteger(value.typeId))
90 { return null; }
91 return { typeId: value.typeId, state: value.state ?? null, config: value.config ?? null };
92 }
93
94 export function setBlockVisualState (block, state)
95 {
96 if (!block)
97 { return null; }
98 block.state = state ?? null;
99 return block;
100 }
@@ -13,13 +13,17 @@ export const GROUND_DEFINITIONS = Object.freeze({
13 id: GroundType.grass,
13 id: GroundType.grass,
14 key: "grass",
14 key: "grass",
15 displayName: "Grass",
15 displayName: "Grass",
16 sprite: "ground-grass"
16 frames: 1,
17 framesPerRow: 1,
18 animationSpeed: 0
17 }),
19 }),
18 [GroundType.wood]: Object.freeze({
20 [GroundType.wood]: Object.freeze({
19 id: GroundType.wood,
21 id: GroundType.wood,
20 key: "wood",
22 key: "wood",
21 displayName: "Wood",
23 displayName: "Wood",
22 sprite: "ground-wood"
24 frames: 1,
25 framesPerRow: 1,
26 animationSpeed: 0
23 })
27 })
24});
28});
25
29
@@ -28,17 +32,21 @@ export const BLOCK_DEFINITIONS = Object.freeze({
28 id: BlockType.stoneWall,
32 id: BlockType.stoneWall,
29 key: "stone-wall",
33 key: "stone-wall",
30 displayName: "Stone wall",
34 displayName: "Stone wall",
31 sprite: "block-stone-wall",
32 passable: false,
35 passable: false,
33 lightRangeTiles: 0
36 lightRangeTiles: 0,
37 frames: 1,
38 framesPerRow: 1,
39 animationSpeed: 0
34 }),
40 }),
35 [BlockType.torch]: Object.freeze({
41 [BlockType.torch]: Object.freeze({
36 id: BlockType.torch,
42 id: BlockType.torch,
37 key: "torch",
43 key: "torch",
38 displayName: "Torch",
44 displayName: "Torch",
39 sprite: "block-torch",
40 passable: true,
45 passable: true,
41 lightRangeTiles: 8
46 lightRangeTiles: 8,
47 frames: 1,
48 framesPerRow: 1,
49 animationSpeed: 0
42 })
50 })
43});
51});
44
52
@@ -66,3 +74,27 @@ export function blockLightRange (typeId)
66 const def = blockDefinition(typeId);
74 const def = blockDefinition(typeId);
67 return def ? def.lightRangeTiles : 0;
75 return def ? def.lightRangeTiles : 0;
68}
76}
77
78export function normalizeGround (value, fallbackTypeId = GroundType.grass)
79{
80 if (typeof value === "number")
81 { return { typeId: value, state: null }; }
82 if (value && Number.isInteger(value.typeId))
83 { return { typeId: value.typeId, state: value.state ?? null }; }
84 return { typeId: fallbackTypeId, state: null };
85}
86
87export function normalizeBlock (value)
88{
89 if (!value || !Number.isInteger(value.typeId))
90 { return null; }
91 return { typeId: value.typeId, state: value.state ?? null, config: value.config ?? null };
92}
93
94export function setBlockVisualState (block, state)
95{
96 if (!block)
97 { return null; }
98 block.state = state ?? null;
99 return block;
100}
tile_mmo_server_technical_design_v0.6.md +35 −3
@@ -1,13 +1,13 @@
1 1 ---
2 2 title: Tile MMO Server Technical Design
3 version: 0.13
3 version: 0.14
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.13
10 **Version:** 0.14
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
@@ -398,6 +398,14 @@ part of the normal player client.
398 398
399 399 - Allow painting, replacing or erasing the block type on a tile.
400 400
401 - Hovering a tile in the selected chunk previews the selected tool there:
402 existing content on that layer is hidden and the tool's sprite is shown
403 where a click would place it.
404
405 - Mouse wheel cycles the **visual state** of the selected ground or block
406 type (see section 21.3). If the hovered tile already has that type, the
407 wheel also writes the new state onto it.
408
401 409 - Render both layers together so the block appears on top of the ground.
402 410
403 411 - Do not display ordinary mobile entities as editable map paint.
@@ -1572,6 +1580,22 @@ and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1572 1580 tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1573 1581 stands on the same feet line and extends upward.
1574 1582
1583 Each **ground** and **block** type has its own asset folder
1584 (`client/assets/grounds/<key>/`, `client/assets/blocks/<key>/`). Every
1585 PNG in that folder is a **visual state**. States are not listed in the
1586 type definition: the first filename in alphabetical (numeric) order is
1587 the default. A later gameplay system may set a named state on a placed
1588 tile (for example a door `closed` / `open`); unknown names fall back to
1589 the default. The editor mouse wheel cycles these states.
1590
1591 Each type definition may set sprite-sheet playback for every state PNG:
1592
1593 ```text
1594 frames // sub-images in the sheet; default 1
1595 framesPerRow // columns in the sheet; default 1
1596 animationSpeed // seconds per frame; 0 means still
1597 ```
1598
1575 1599 Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1576 1600 higher on the screen draw behind sprites lower on the screen, using the
1577 1601 pivot's world Y (the occupied tile, or the interpolated foot position
@@ -2910,7 +2934,7 @@ players; they do not buy player goods unless a later iteration adds that.
2910 2934 | Control | Human and future scripted control both emit validated action commands. |
2911 2935 | Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
2912 2936 | Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
2913 | Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Blocks and mobiles Y-sort north-behind-south. |
2937 | Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use `frames`, `framesPerRow`, `animationSpeed`. Blocks and mobiles Y-sort north-behind-south. |
2914 2938 | Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
2915 2939 | Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2916 2940 | Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
@@ -3348,6 +3372,14 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3348 3372
3349 3373 # 34. Version history
3350 3374
3375 ## 0.14
3376
3377 - Ground and block types load visual states from per-type sprite folders
3378 (first alphabetical PNG is the default). Sprite definitions include
3379 `frames`, `framesPerRow` and `animationSpeed`. The editor previews the
3380 selected tool on hover and cycles states with the mouse wheel.
3381 Gameplay may set a named visual state (for example a door).
3382
3351 3383 ## 0.13
3352 3384
3353 3385 - World settings are live: an admin modal with categories, dirty-field
@@ -1,13 +1,13 @@
1---
1---
2title: Tile MMO Server Technical Design
2title: Tile MMO Server Technical Design
3version: 0.13
3version: 0.14
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.13
10**Version:** 0.14
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
@@ -398,6 +398,14 @@ part of the normal player client.
398
398
399- Allow painting, replacing or erasing the block type on a tile.
399- Allow painting, replacing or erasing the block type on a tile.
400
400
401- Hovering a tile in the selected chunk previews the selected tool there:
402 existing content on that layer is hidden and the tool's sprite is shown
403 where a click would place it.
404
405- Mouse wheel cycles the **visual state** of the selected ground or block
406 type (see section 21.3). If the hovered tile already has that type, the
407 wheel also writes the new state onto it.
408
401- Render both layers together so the block appears on top of the ground.
409- Render both layers together so the block appears on top of the ground.
402
410
403- Do not display ordinary mobile entities as editable map paint.
411- Do not display ordinary mobile entities as editable map paint.
@@ -1572,6 +1580,22 @@ and **8 pixels up from the bottom** of the sprite. That pivot sits on the
1572tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1580tile centre, so a 16×16 sprite still fills the tile and a taller sprite
1573stands on the same feet line and extends upward.
1581stands on the same feet line and extends upward.
1574
1582
1583Each **ground** and **block** type has its own asset folder
1584(`client/assets/grounds/<key>/`, `client/assets/blocks/<key>/`). Every
1585PNG in that folder is a **visual state**. States are not listed in the
1586type definition: the first filename in alphabetical (numeric) order is
1587the default. A later gameplay system may set a named state on a placed
1588tile (for example a door `closed` / `open`); unknown names fall back to
1589the default. The editor mouse wheel cycles these states.
1590
1591Each type definition may set sprite-sheet playback for every state PNG:
1592
1593```text
1594frames // sub-images in the sheet; default 1
1595framesPerRow // columns in the sheet; default 1
1596animationSpeed // seconds per frame; 0 means still
1597```
1598
1575Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1599Blocks and mobiles with oversized sprites are **Y-sorted**: sprites
1576higher on the screen draw behind sprites lower on the screen, using the
1600higher on the screen draw behind sprites lower on the screen, using the
1577pivot's world Y (the occupied tile, or the interpolated foot position
1601pivot's world Y (the occupied tile, or the interpolated foot position
@@ -2910,7 +2934,7 @@ players; they do not buy player goods unless a later iteration adds that.
2910| Control | Human and future scripted control both emit validated action commands. |
2934| Control | Human and future scripted control both emit validated action commands. |
2911| Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
2935| Deployment | The game exits gracefully; systemd relaunches it and only pulls/builds when an intentional deployment manifest requests it. |
2912| Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
2936| Client architecture | FrameworkV3 is a git submodule under `client/frameworkv3`, built before game client code; backend ECS internals do not become the client object model. |
2913| Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Blocks and mobiles Y-sort north-behind-south. |
2937| Sprites | World sprites may be any size. Pivot is horizontal centre and 8px from the sprite bottom, on the tile centre. Ground/block types load visual states from a per-type folder (first alphabetical PNG is default). Sheets use `frames`, `framesPerRow`, `animationSpeed`. Blocks and mobiles Y-sort north-behind-south. |
2914| Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
2938| Appearance | Visible gear is layered 16×16 overlays on the mob; recolourable channels (such as metal) use material colour without duplicate art sets. Nearby clients receive appearance layers, not another player's inventory. |
2915| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2939| Play camera | The play viewport is centered on the local player. Only the admin world editor uses a free chunk camera. |
2916| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
2940| Movement | All ground mobiles share a global walk/run cadence from world settings; the server commits integer tiles; clients lerp for presentation only. |
@@ -3348,6 +3372,14 @@ Skills → classless progression; non-combat XP to one skill; attack XP split hi
3348
3372
3349# 34. Version history
3373# 34. Version history
3350
3374
3375## 0.14
3376
3377- Ground and block types load visual states from per-type sprite folders
3378 (first alphabetical PNG is the default). Sprite definitions include
3379 `frames`, `framesPerRow` and `animationSpeed`. The editor previews the
3380 selected tool on hover and cycles states with the mouse wheel.
3381 Gameplay may set a named visual state (for example a door).
3382
3351## 0.13
3383## 0.13
3352
3384
3353- World settings are live: an admin modal with categories, dirty-field
3385- World settings are live: an admin modal with categories, dirty-field