BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

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