BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

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