BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

gem fix
timfa Tim Falken · pushed by timfa · 2 months ago
b67f970b History
spriteCatalog.js 12.9 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 } 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 (e.g. Shade → rat).
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 assetFolder: def.assetFolder ?? "mobs"
187 };
188 }
189 return defs;
190}
191
192function scanMobLayers (assetRoot)
193{
194 const byFolder = new Map();
195 for (const def of Object.values(mobScanDefs()))
196 {
197 const folder = def.assetFolder ?? "mobs";
198 if (!byFolder.has(folder))
199 { byFolder.set(folder, {}); }
200 byFolder.get(folder)[def.key] = def;
201 }
202 const types = {};
203 const images = [];
204 for (const [folder, defs] of byFolder)
205 {
206 const scanned = scanLayer(join(assetRoot, folder), defs, "mob", folder);
207 Object.assign(types, scanned.types);
208 images.push(...scanned.images);
209 }
210 return { types, images };
211}
212
213function scanFx (fxRoot)
214{
215 const types = {};
216 const images = [];
217 let folders;
218 try
219 { folders = readdirSync(fxRoot, { withFileTypes: true }).filter((entry) => entry.isDirectory()); }
220 catch (error)
221 {
222 if (error.code === "ENOENT")
223 { return { types, images }; }
224 throw error;
225 }
226 for (const entry of folders)
227 {
228 const key = entry.name;
229 const defs = {
230 [key]: { key, id: key, frames: 1, framesPerRow: 1, animationSpeed: 0 }
231 };
232 const scanned = scanLayer(fxRoot, defs, "fx", "fx");
233 Object.assign(types, scanned.types);
234 images.push(...scanned.images);
235 }
236 return { types, images };
237}
238
239function scanLayer (layerDir, definitions, layer, urlFolder)
240{
241 const types = {};
242 const images = [];
243 for (const def of Object.values(definitions))
244 {
245 const folder = join(layerDir, def.key);
246 const { states: fileStates, blooms: fileBlooms, equips, equipBlooms } = listVisualStates(folder);
247 if (fileStates.length === 0)
248 { throw new Error(`No PNG states in ${folder}`); }
249
250 const frames = Math.max(1, def.frames ?? 1);
251 const framesPerRow = Math.max(1, def.framesPerRow ?? 1);
252 const animationSpeed = Math.max(0, def.animationSpeed ?? 0);
253 let states = [...fileStates];
254 let blooms = fileBlooms;
255 const imagesForType = [];
256
257 if (layer === "block" && def.key === "boulder")
258 {
259 states = states.filter((state) => state !== "boulder-ore" && state !== "boulder-ore-winter");
260 if (!states.includes("boulder"))
261 { states.unshift("boulder"); }
262 for (const material of ORE_BEARING_MATERIALS)
263 {
264 const state = oreBoulderState(material);
265 if (!states.includes(state))
266 { states.push(state); }
267 const tint = materialTintColor(material, { ore: true });
268 imagesForType.push({
269 name: spriteImageName(layer, def.key, state),
270 url: `/assets/${urlFolder}/${def.key}/boulder-ore.png`,
271 subImgTotal: frames,
272 perRow: framesPerRow,
273 loop: animationSpeed > 0,
274 animationSpeed,
275 tint: { r: tint.r, g: tint.g, b: tint.b }
276 });
277 const winterState = `${state}-winter`;
278 if (!states.includes(winterState))
279 { states.push(winterState); }
280 imagesForType.push({
281 name: spriteImageName(layer, def.key, winterState),
282 url: `/assets/${urlFolder}/${def.key}/boulder-ore-winter.png`,
283 subImgTotal: frames,
284 perRow: framesPerRow,
285 loop: animationSpeed > 0,
286 animationSpeed,
287 tint: { r: tint.r, g: tint.g, b: tint.b }
288 });
289 }
290 }
291
292 if (layer === "block" && def.key === "flower")
293 {
294 states = [];
295 for (const colorId of FLOWER_COLOR_ORDER)
296 {
297 const state = flowerBlockState(colorId);
298 states.push(state);
299 const tint = flowerColorRgb(colorId);
300 imagesForType.push({
301 name: spriteImageName(layer, def.key, state),
302 url: `/assets/${urlFolder}/${def.key}/flower.png`,
303 subImgTotal: frames,
304 perRow: framesPerRow,
305 loop: animationSpeed > 0,
306 animationSpeed,
307 tint: { r: tint.r, g: tint.g, b: tint.b }
308 });
309 }
310 }
311
312 if (layer === "block" && def.key === "campfire")
313 {
314 states = [];
315 const nextBlooms = {};
316 for (const material of WOOD_TIER_ORDER)
317 {
318 states.push(material);
319 const tint = materialTintColor(material);
320 imagesForType.push({
321 name: spriteImageName(layer, def.key, material),
322 url: `/assets/${urlFolder}/${def.key}/campfire.png`,
323 subImgTotal: frames,
324 perRow: framesPerRow,
325 loop: animationSpeed > 0,
326 animationSpeed,
327 tint: { r: tint.r, g: tint.g, b: tint.b }
328 });
329 imagesForType.push({
330 name: bloomImageName(layer, def.key, material),
331 url: `/assets/${urlFolder}/${def.key}/campfire-bloom.png`,
332 subImgTotal: frames,
333 perRow: framesPerRow,
334 loop: animationSpeed > 0,
335 animationSpeed
336 });
337 nextBlooms[material] = true;
338 }
339 blooms = nextBlooms;
340 }
341
342 if (layer === "block" && def.key === "table")
343 {
344 // Magenta mask sources `0`–`15` (+ optional artist `wood`); expand per wood tier.
345 states = [];
346 for (const material of WOOD_TIER_ORDER)
347 {
348 for (let mask = 0; mask < NEIGHBOR_CONNECT_MASK_COUNT; mask++)
349 {
350 const state = composeNeighborConnectState(def, material, mask);
351 states.push(state);
352 const tint = materialTintColor(material);
353 imagesForType.push({
354 name: spriteImageName(layer, def.key, state),
355 url: `/assets/${urlFolder}/${def.key}/${mask}.png`,
356 subImgTotal: frames,
357 perRow: framesPerRow,
358 loop: animationSpeed > 0,
359 animationSpeed,
360 tint: { r: tint.r, g: tint.g, b: tint.b }
361 });
362 }
363 }
364 }
365
366 types[def.key] = {
367 key: def.key,
368 typeId: def.id,
369 states,
370 defaultState: def.key === "boulder" && states.includes("boulder")
371 ? "boulder"
372 : def.key === "fishing-spot" && states.includes("fishing-spot")
373 ? "fishing-spot"
374 : (def.outdoor && preferredSeasonalDefaultState(states)) || states[0],
375 blooms,
376 equips,
377 equipBlooms,
378 frames,
379 framesPerRow,
380 animationSpeed,
381 outdoor: !!def.outdoor,
382 /** Calendar-driven only when outdoor and summer/fall/winter states exist. */
383 seasonal: !!def.outdoor && typeHasSeasonalStates(states)
384 };
385 for (const state of states)
386 {
387 if (imagesForType.some((entry) => entry.name === spriteImageName(layer, def.key, state)))
388 { continue; }
389 /** Seasonal overlays (e.g. frozen water-winter) are static single-frame sprites. */
390 const overlay = isSeasonalOverlayVariant(state);
391 const sheet = {
392 subImgTotal: overlay ? 1 : frames,
393 perRow: overlay ? 1 : framesPerRow,
394 loop: !overlay && animationSpeed > 0,
395 animationSpeed: overlay ? 0 : animationSpeed
396 };
397 images.push({
398 name: spriteImageName(layer, def.key, state),
399 url: `/assets/${urlFolder}/${def.key}/${state}.png`,
400 ...sheet
401 });
402 if (blooms[state])
403 {
404 images.push({
405 name: bloomImageName(layer, def.key, state),
406 url: `/assets/${urlFolder}/${def.key}/${state}-bloom.png`,
407 ...sheet
408 });
409 }
410 if (equips[state])
411 {
412 images.push({
413 name: equipImageName(layer, def.key, state),
414 url: `/assets/${urlFolder}/${def.key}/${state}-equip.png`,
415 ...sheet
416 });
417 }
418 if (equipBlooms[state])
419 {
420 images.push({
421 name: equipBloomImageName(layer, def.key, state),
422 url: `/assets/${urlFolder}/${def.key}/${state}-equip-bloom.png`,
423 ...sheet
424 });
425 }
426 }
427 images.push(...imagesForType);
428 }
429 return { types, images };
430}
431
432function listVisualStates (folder)
433{
434 const stems = listPngStems(folder);
435 const blooms = {};
436 const equips = {};
437 const equipBlooms = {};
438 const states = [];
439 for (const stem of stems)
440 {
441 const parsed = parseSpriteStem(stem);
442 if (parsed.companion)
443 {
444 if (!parsed.base)
445 { continue; }
446 if (parsed.equip && parsed.bloom)
447 { equipBlooms[parsed.base] = true; }
448 else if (parsed.equip)
449 { equips[parsed.base] = true; }
450 else if (parsed.bloom)
451 { blooms[parsed.base] = true; }
452 continue;
453 }
454 if (isCompanionSpriteStem(stem))
455 { continue; }
456 states.push(stem);
457 }
458 const filterMap = (map) =>
459 {
460 const next = {};
461 for (const state of states)
462 {
463 if (map[state])
464 { next[state] = true; }
465 }
466 return next;
467 };
468 return {
469 states,
470 blooms: filterMap(blooms),
471 equips: filterMap(equips),
472 equipBlooms: filterMap(equipBlooms)
473 };
474}
475
476function listPngStems (folder)
477{
478 let entries;
479 try
480 { entries = readdirSync(folder, { withFileTypes: true }); }
481 catch (error)
482 {
483 if (error.code === "ENOENT")
484 { return []; }
485 throw error;
486 }
487
488 return entries
489 .filter((entry) => entry.isFile() && extname(entry.name).toLowerCase() === ".png")
490 .map((entry) => entry.name.slice(0, -extname(entry.name).length))
491 .sort((a, b) => a.localeCompare(b, "en", { numeric: true, sensitivity: "base" }));
492}