BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

sprites.js 3.9 KiB Download Raw
1import { SPRITE_SIZE_PX } from "/shared/protocol/constants.js";
2
3export const UTILITY_IMAGES = [
4 { name: "night-shade", url: shadeDataUrl("#000000") },
5 { name: "chunk-edge", url: shadeDataUrl("#e23d3d") }
6];
7
8export function playImagesFromCatalog (catalog)
9{
10 return [...(catalog?.images ?? []), ...UTILITY_IMAGES];
11}
12
13export async function loadSpriteCatalog ()
14{
15 const response = await fetch("/assets/catalog.json");
16 if (!response.ok)
17 { throw new Error("Failed to load sprite catalog."); }
18 return response.json();
19}
20
21/**
22 * Load catalog images without aborting the whole client when one file is missing.
23 * Failed entries are logged and omitted from `game.images`.
24 */
25export async function preloadCatalogImages (game, catalog)
26{
27 const failed = [];
28 await Promise.all(playImagesFromCatalog(catalog).map((imageData) => loadOneImage(game, imageData).catch((error) =>
29 {
30 console.error(error.message ?? error);
31 failed.push({ name: imageData.name, url: imageData.url });
32 })));
33 if (failed.length)
34 { console.warn(`Skipped ${failed.length} missing/broken sprite(s).`, failed.map((entry) => entry.name)); }
35 return failed;
36}
37
38function loadOneImage (game, imageData)
39{
40 return new Promise((resolve, reject) =>
41 {
42 const img = new Image();
43 img.onload = () =>
44 {
45 const finalImage = new image(
46 img,
47 imageData.subImgTotal,
48 imageData.perRow,
49 imageData.loop,
50 imageData.chain
51 );
52 finalImage.name = imageData.name;
53 game.images[imageData.name] = finalImage;
54 resolve(finalImage);
55 };
56 img.onerror = () =>
57 {
58 reject(new Error(`Failed to load image '${imageData.name}' from ${imageData.url}`));
59 };
60 img.src = imageData.url;
61 });
62}
63
64export function applySpriteSheets (images, catalog)
65{
66 for (const entry of catalog?.images ?? [])
67 {
68 const sprite = images[entry.name];
69 if (!sprite)
70 { continue; }
71 sprite._animationSpeed = entry.animationSpeed ?? 0;
72 const frames = entry.subImgTotal || 1;
73 if (frames > 1)
74 {
75 sprite.addAnimationCycle(
76 "idle",
77 Array.from({ length: frames }, (_, index) => index),
78 true
79 );
80 }
81 }
82}
83
84export function shadeDataUrl (fill = "#000000")
85{
86 const canvas = document.createElement("canvas");
87 canvas.width = SPRITE_SIZE_PX;
88 canvas.height = SPRITE_SIZE_PX;
89 const context = canvas.getContext("2d");
90 context.fillStyle = fill;
91 context.fillRect(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX);
92 return canvas.toDataURL("image/png");
93}
94
95function setGlNearest (gl, texture)
96{
97 if (!gl || !texture)
98 { return; }
99 gl.bindTexture(gl.TEXTURE_2D, texture);
100 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
101 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
102}
103
104/** Framework defaults to LINEAR; patch uploads so pixel art stays crisp when scaled. */
105export function patchNearestNeighbourTextures (scene)
106{
107 const glContext = scene?.glContext;
108 if (!glContext || glContext._nearestPatched)
109 { return; }
110 const original = glContext.getTexture.bind(glContext);
111 glContext.getTexture = (htmlImage) =>
112 {
113 const texture = original(htmlImage);
114 if (texture)
115 { setGlNearest(glContext.gl, texture); }
116 return texture;
117 };
118 glContext._nearestPatched = true;
119}
120
121/** Canvas atlases and dynamic sprites — call after invalidate/reupload. */
122export function setNearestFilter (scene, source)
123{
124 if (!source)
125 { return; }
126 patchNearestNeighbourTextures(scene);
127 const glContext = scene?.glContext;
128 if (!glContext)
129 { return; }
130 const htmlImage = source.g_image ?? source;
131 const texture = glContext.getTexture(htmlImage);
132 if (texture)
133 { setGlNearest(glContext.gl, texture); }
134}
135
136export function applyNearestToAllTextures (scene, images)
137{
138 patchNearestNeighbourTextures(scene);
139 const glContext = scene?.glContext;
140 if (!glContext)
141 { return; }
142 for (const sprite of Object.values(images ?? {}))
143 {
144 const htmlImage = sprite?.g_image ?? sprite;
145 if (htmlImage)
146 { glContext.getTexture(htmlImage); }
147 }
148}
149
150export function useNearestNeighbour (scene, images)
151{
152 applyNearestToAllTextures(scene, images);
153}