BlueGit

timfa questward

Files

questward / server / src / assets / spriteCatalog.js

spriteCatalog.js

spriteCatalog.js 1.9 KiB Download Raw
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}