BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

spriteCatalog.js 11.8 KiB Download Raw
1import { readdirSync } from "node:fs";
2import { extname, join } from "node:path";
3import { BLOCK_DEFINITIONS, GROUND_DEFINITIONS, BlockType } from "../../../shared/definitions/tiles.js";
4import { ITEM_DEFINITIONS } from "../../../shared/definitions/items.js";
5import { MOB_DEFINITIONS } from "../../../shared/definitions/mobs.js";
6import { HERB_ORDER } from "../../../shared/definitions/herbs.js";
7import {
8 ORE_BEARING_MATERIALS,
9 oreBoulderState,
10 materialTintColor,
11 WOOD_TIER_ORDER
12} from "../../../shared/definitions/materialTiers.js";
13import {
14 FLOWER_COLOR_ORDER,
15 flowerBlockState,
16 flowerColorRgb
17} from "../../../shared/definitions/dyes.js";
18import {
19 bloomImageName,
20 equipBloomImageName,
21 equipImageName,
22 isCompanionSpriteStem,
23 parseSpriteStem,
24 spriteImageName
25} from "../../../shared/definitions/tileSprites.js";
26import { preferredSeasonalDefaultState, typeHasSeasonalStates, isSeasonalOverlayVariant } from "../../../shared/world/season.js";
27import { composeNeighborConnectState, NEIGHBOR_CONNECT_MASK_COUNT } from "../../../shared/world/neighborConnect.js";
28
29const CHARACTER_DEFINITIONS = Object.freeze({
30 "player-body-male": Object.freeze({ key: "player-body-male", id: "player-body-male" }),
31 "player-body-female": Object.freeze({ key: "player-body-female", id: "player-body-female" })
32});
33
34export function buildSpriteCatalog (assetRoot)
35{
36 const blockDefs = Object.fromEntries(
37 Object.entries(BLOCK_DEFINITIONS).filter(([, def]) => def.key !== "herb")
38 );
39 const grounds = scanLayer(join(assetRoot, "grounds"), GROUND_DEFINITIONS, "ground", "grounds");
40 const blocks = scanLayer(join(assetRoot, "blocks"), blockDefs, "block", "blocks");
41 const items = scanLayer(join(assetRoot, "items"), itemScanDefs(), "item", "items");
42 const herbs = scanHerbAssets(join(assetRoot, "herbs"));
43 Object.assign(blocks.types, herbs.blockTypes);
44 Object.assign(items.types, herbs.itemTypes);
45 const mobs = scanMobLayers(assetRoot);
46 const characters = scanLayer(join(assetRoot, "characters"), CHARACTER_DEFINITIONS, "character", "characters");
47 const fx = scanFx(join(assetRoot, "fx"));
48 return {
49 grounds: grounds.types,
50 blocks: blocks.types,
51 items: items.types,
52 mobs: mobs.types,
53 characters: characters.types,
54 fx: fx.types,
55 images: [
56 ...grounds.images,
57 ...blocks.images,
58 ...items.images,
59 ...herbs.images,
60 ...mobs.images,
61 ...characters.images,
62 ...fx.images
63 ]
64 };
65}
66
67/**
68 * Shared `assets/herbs/<herbId>.png` — registered as both world block states and item icons.
69 */
70function scanHerbAssets (herbRoot)
71{
72 const stems = new Set(listPngStems(herbRoot));
73 const missing = HERB_ORDER.filter((id) => !stems.has(id));
74 if (missing.length)
75 { throw new Error(`Missing herb sprites in ${herbRoot}: ${missing.join(", ")}`); }
76
77 const images = [];
78 for (const herbId of HERB_ORDER)
79 {
80 const url = `/assets/herbs/${herbId}.png`;
81 images.push({
82 name: spriteImageName("block", "herb", herbId),
83 url,
84 subImgTotal: 1,
85 perRow: 1,
86 loop: false,
87 animationSpeed: 0
88 });
89 images.push({
90 name: spriteImageName("item", "herbs", herbId),
91 url,
92 subImgTotal: 1,
93 perRow: 1,
94 loop: false,
95 animationSpeed: 0
96 });
97 }
98
99 const blockTypes = {
100 herb: {
101 key: "herb",
102 typeId: BlockType.herbPlant,
103 states: [...HERB_ORDER],
104 defaultState: HERB_ORDER[0],
105 blooms: {},
106 equips: {},
107 equipBlooms: {},
108 frames: 1,
109 framesPerRow: 1,
110 animationSpeed: 0,
111 outdoor: true,
112 seasonal: false
113 }
114 };
115 const itemTypes = {
116 herbs: {
117 key: "herbs",
118 typeId: "herbs",
119 states: [...HERB_ORDER],
120 defaultState: HERB_ORDER[0],
121 blooms: {},
122 equips: {},
123 equipBlooms: {},
124 frames: 1,
125 framesPerRow: 1,
126 animationSpeed: 0,
127 outdoor: false,
128 seasonal: false
129 }
130 };
131 return { images, blockTypes, itemTypes };
132}
133
134function itemScanDefs ()
135{
136 const defs = {};
137 for (const def of Object.values(ITEM_DEFINITIONS))
138 {
139 if (def?.herb)
140 { continue; }
141 const folderKey = def.iconKey && def.iconKey !== def.key ? def.iconKey : def.key;
142 if (!folderKey || defs[folderKey])
143 { continue; }
144 defs[folderKey] = {
145 key: folderKey,
146 id: def.itemId,
147 frames: def.frames ?? 1,
148 framesPerRow: def.framesPerRow ?? 1,
149 animationSpeed: def.animationSpeed ?? 0
150 };
151 }
152 /** Shared metal armour worn overlays (items/armour/*-equip.png). */
153 if (!defs.armour)
154 {
155 defs.armour = {
156 key: "armour",
157 id: "armour-overlays",
158 frames: 1,
159 framesPerRow: 1,
160 animationSpeed: 0
161 };
162 }
163 return defs;
164}
165
166function mobScanDefs ()
167{
168 const defs = {};
169 for (const def of Object.values(MOB_DEFINITIONS))
170 {
171 if (def.usePlayerBody)
172 { continue; }
173 const key = def.key ?? def.mobTypeId;
174 defs[key] = {
175 key,
176 id: def.mobTypeId,
177 frames: def.frames ?? 1,
178 framesPerRow: def.framesPerRow ?? 1,
179 animationSpeed: def.animationSpeed ?? 0,
180 assetFolder: def.assetFolder ?? "mobs"
181 };
182 }
183 return defs;
184}
185
186function scanMobLayers (assetRoot)
187{
188 const byFolder = new Map();
189 for (const def of Object.values(mobScanDefs()))
190 {
191 const folder = def.assetFolder ?? "mobs";
192 if (!byFolder.has(folder))
193 { byFolder.set(folder, {}); }
194 byFolder.get(folder)[def.key] = def;
195 }
196 const types = {};
197 const images = [];
198 for (const [folder, defs] of byFolder)
199 {
200 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
201 Object.assign(types, scanned.types);
202 images.push(...scanned.images);
203 }
204 return { types, images };
205}
206
207function scanFx (fxRoot)
208{
209 const types = {};
210 const images = [];
211 let folders;
212 try
213 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
214 catch (error)
215 {
216 if (error.code === "ENOENT")
217 { return { types, images }; }
218 throw error;
219 }
220 for (const entry of folders)
221 {
222 const key = entry.name;
223 const defs = {
224 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
225 };
226 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
227 Object.assign(types, scanned.types);
228 images.push(...scanned.images);
229 }
230 return { types, images };
231}
232
233function scanLayer (layerDir, definitions, layer, urlFolder)
234{
235 const types = {};
236 const images = [];
237 for (const def of Object.values(definitions))
238 {
239 const folder = join(layerDir, def.key);
240 const { states: fileStates, blooms, equips, equipBlooms } = listVisualStates(folder);
241 if (fileStates.length === 0)
242 { throw new Error(`No PNG states in ${folder}`); }
243
244 const frames = Math.max(1, def.frames ?? 1);
245 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
246 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
247 let states = [...fileStates];
248 const imagesForType = [];
249
250 if (layer === "block" && def.key === "boulder")
251 {
252 states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");
253 if (!states.includes("boulder"))
254 { states.unshift("boulder"); }
255 for (const material of ORE_BEARING_MATERIALS)
256 {
257 const state = oreBoulderState(material);
258 if (!states.includes(state))
259 { states.push(state); }
260 const tint = materialTintColor(material, { ore: true });
261 imagesForType.push({
262 name: spriteImageName(layer, def.key, state),
263 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
264 subImgTotal: frames,
265 perRow: framesPerRow,
266 loop: animationSpeed > 0,
267 animationSpeed,
268 tint: { r: tint.r, g: tint.g, b: tint.b }
269 });
270 const winterState = `${state}-winter`;
271 if (!states.includes(winterState))
272 { states.push(winterState); }
273 imagesForType.push({
274 name: spriteImageName(layer, def.key, winterState),
275 url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,
276 subImgTotal: frames,
277 perRow: framesPerRow,
278 loop: animationSpeed > 0,
279 animationSpeed,
280 tint: { r: tint.r, g: tint.g, b: tint.b }
281 });
282 }
283 }
284
285 if (layer === "block" && def.key === "flower")
286 {
287 states = [];
288 for (const colorId of FLOWER_COLOR_ORDER)
289 {
290 const state = flowerBlockState(colorId);
291 states.push(state);
292 const tint = flowerColorRgb(colorId);
293 imagesForType.push({
294 name: spriteImageName(layer, def.key, state),
295 url: `/assets/${urlFolder}/${def.key}/flower.png`,
296 subImgTotal: frames,
297 perRow: framesPerRow,
298 loop: animationSpeed > 0,
299 animationSpeed,
300 tint: { r: tint.r, g: tint.g, b: tint.b }
301 });
302 }
303 }
304
305 if (layer === "block" && def.key === "table")
306 {
307 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
308 states = [];
309 for (const material of WOOD_TIER_ORDER)
310 {
311 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
312 {
313 const state = composeNeighborConnectState(def, material, mask);
314 states.push(state);
315 const tint = materialTintColor(material);
316 imagesForType.push({
317 name: spriteImageName(layer, def.key, state),
318 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
319 subImgTotal: frames,
320 perRow: framesPerRow,
321 loop: animationSpeed > 0,
322 animationSpeed,
323 tint: { r: tint.r, g: tint.g, b: tint.b }
324 });
325 }
326 }
327 }
328
329 types[def.key] = {
330 key: def.key,
331 typeId: def.id,
332 states,
333 defaultState: def.key === "boulder" && states.includes("boulder")
334 ? "boulder"
335 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
336 blooms,
337 equips,
338 equipBlooms,
339 frames,
340 framesPerRow,
341 animationSpeed,
342 outdoor: !!def.outdoor,
343 /** Calendar-driven only when outdoor and summer/fall/winter states exist. */
344 seasonal: !!def.outdoor && typeHasSeasonalStates(states)
345 };
346 for (const state of states)
347 {
348 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
349 { continue; }
350 /** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */
351 const overlay = isSeasonalOverlayVariant(state);
352 const sheet = {
353 subImgTotal: overlay ? 1 : frames,
354 perRow: overlay ? 1 : framesPerRow,
355 loop: !overlay && animationSpeed > 0,
356 animationSpeed: overlay ? 0 : animationSpeed
357 };
358 images.push({
359 name: spriteImageName(layer, def.key, state),
360 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
361 ...sheet
362 });
363 if (blooms[state])
364 {
365 images.push({
366 name: bloomImageName(layer, def.key, state),
367 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
368 ...sheet
369 });
370 }
371 if (equips[state])
372 {
373 images.push({
374 name: equipImageName(layer, def.key, state),
375 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
376 ...sheet
377 });
378 }
379 if (equipBlooms[state])
380 {
381 images.push({
382 name: equipBloomImageName(layer, def.key, state),
383 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
384 ...sheet
385 });
386 }
387 }
388 images.push(...imagesForType);
389 }
390 return { types, images };
391}
392
393function listVisualStates (folder)
394{
395 const stems = listPngStems(folder);
396 const blooms = {};
397 const equips = {};
398 const equipBlooms = {};
399 const states = [];
400 for (const stem of stems)
401 {
402 const parsed = parseSpriteStem(stem);
403 if (parsed.companion)
404 {
405 if (!parsed.base)
406 { continue; }
407 if (parsed.equip && parsed.bloom)
408 { equipBlooms[parsed.base] = true; }
409 else if (parsed.equip)
410 { equips[parsed.base] = true; }
411 else if (parsed.bloom)
412 { blooms[parsed.base] = true; }
413 continue;
414 }
415 if (isCompanionSpriteStem(stem))
416 { continue; }
417 states.push(stem);
418 }
419 const filterMap = (map) =>
420 {
421 const next = {};
422 for (const state of states)
423 {
424 if (map[state])
425 { next[state] = true; }
426 }
427 return next;
428 };
429 return {
430 states,
431 blooms: filterMap(blooms),
432 equips: filterMap(equips),
433 equipBlooms: filterMap(equipBlooms)
434 };
435}
436
437function listPngStems (folder)
438{
439 let entries;
440 try
441 { entries = readdirSync(folder, { withFileTypes: true }); }
442 catch (error)
443 {
444 if (error.code === "ENOENT")
445 { return []; }
446 throw error;
447 }
448
449 return entries
450 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
451 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
452 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
453}