BlueGit

timfa questward

Files

questward / client / src / render / sprites.js

sprites.js

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