BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 162.3 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion, tileLightOcclusionAt } from "/shared/lighting/chunkOcclusion.js";
5import { collectBlockLightSources, maxBlockLightRangeTiles } from "/shared/lighting/blockLights.js";
6import { smoothLitCorner } from "/shared/lighting/lightCorners.js";
7import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
8import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemSpriteNameForStack, itemDefinition } from "/shared/definitions/items.js";
9import
10{
11 resolveItemTint,
12 resolveEquipTint,
13 resolveItemDualTint,
14 resolveEquipDualTint,
15 normalizeRgb
16} from "/shared/render/tint.js";
17import { layersFromSpawnerConfig } from "/shared/appearance/layers.js";
18import { chargeSpriteFrameIndex, itemMaxCharges } from "/shared/items/charges.js";
19import { normalizeGround, normalizeBlock, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, LightOcclusion, blockDefinition, blockLightOcclusionForBlock, GroundType, GROUND_DEFINITIONS } from "/shared/definitions/tiles.js";
20import { doorSortSubOrder, doorRestingState } from "/shared/world/doors.js";
21import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer, flightSortLayer } from "/shared/render/pivot.js";
22import { bakeChunkAtlases, tileBlockSpriteEntry } from "./chunkBake.js";
23import { createChunkAtlasCache } from "./chunkAtlasCache.js";
24import
25{
26 frameworkImageFromCanvas,
27 invalidateCanvasTexture
28} from "./canvasSprite.js";
29import { setNearestFilter } from "./sprites.js";
30import { SeasonId, seasonIdAt, resolveSeasonalVisualState } from "/shared/world/season.js";
31import
32{
33 OVERWORLD_ID,
34 normalizeDimensionId,
35 normalizeLightingMode,
36 normalizeSeasonMode,
37 resolveDimensionDarknessFactor,
38 resolveDimensionSeasonId
39} from "/shared/world/dimensions.js";
40import { spellDefinition, spellProjectileTint } from "/shared/definitions/spells.js";
41import { skullTintColor } from "/shared/combat/skull.js";
42
43const LAYER_GROUND = 0;
44const LAYER_EDGE = 900000;
45const SORT_BLOCK = 2;
46const SORT_ENTITY = 3;
47/** Equipment overlays use SORT_ENTITY + 1 + index (same sortY band). */
48const SORT_HP_BAR = 14;
49const SORT_FX = 5;
50const RENDER_LAYER_BLOOM = "bloom";
51const SKULL_SPRITE = "fx:skull:skull";
52
53const HP_BAR_W = 14;
54const HP_BAR_H = 4;
55const WALK_TILT_DEG = 6;
56const RUN_TILT_DEG = 8;
57const SHOVE_TILE_FRACTION = 0.25;
58const SHOVE_MS = 280;
59/** Soft reflow when stack circle targets change (join/leave a shared tile). */
60const STACK_SPREAD_LERP_MS = 280;
61/** Melee swipe fade: full opacity → transparent over this duration, then remove. */
62const MELEE_SWIPE_MS = 500;
63/** Extra random yaw (±deg) on top of aim rotation. */
64const MELEE_SWIPE_JITTER_DEG = 10;
65/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
66const GATHER_TOOL_HOLD_MS = 1100;
67const DAMAGE_FLASH_MS = 180;
68const FLASH_COLOR_DAMAGE = Object.freeze([1.0, 0.12, 0.12]);
69const FLASH_COLOR_BLOCK = Object.freeze([1.0, 1.0, 1.0]);
70/** Combat death: full red silhouette fades to transparent after the killing blow. */
71const DEATH_FADE_MS = 500;
72/** Interest leave / non-combat despawn: plain alpha fade (still lit / darkened). */
73const DESPAWN_FADE_MS = 500;
74const DAMAGE_FLOAT_MS = 900;
75const SKILL_LEVEL_FLOAT_MS = 2800;
76/** Projectiles spawn this many sprite-pixels below the caster sprite top. */
77const PROJECTILE_LAUNCH_FROM_TOP_PX = 4;
78
79const SPRITE_LIGHTING_FRAG = [
80 "precision mediump float;",
81 "varying vec2 v_texCoord;",
82 "uniform sampler2D u_texture;",
83 "uniform float u_alpha;",
84 "uniform float u_darkness;",
85 "uniform float u_strength;",
86 "uniform vec3 u_flashColor;",
87 "uniform float u_wade;",
88 "uniform float u_spriteHeight;",
89 "void main() {",
90 " vec4 color = texture2D(u_texture, v_texCoord);",
91 " if (color.a <= 0.0) { discard; }",
92 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
93 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
94 " vec3 rgb = color.rgb;",
95 " if (u_wade > 0.5 && fromBottom < 5.0) {",
96 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
97 " }",
98 " rgb = mix(rgb, vec3(0.0), u_darkness);",
99 " rgb = mix(rgb, u_flashColor, u_strength);",
100 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
101 "}"
102].join("\n");
103
104const WATER_GROUND_FRAG = [
105 "precision mediump float;",
106 "varying vec2 v_texCoord;",
107 "uniform sampler2D u_texture;",
108 "uniform sampler2D u_secondary;",
109 "uniform float u_alpha;",
110 "uniform float u_ambientDark;",
111 "uniform float u_litNW;",
112 "uniform float u_litNE;",
113 "uniform float u_litSW;",
114 "uniform float u_litSE;",
115 "uniform float u_time;",
116 "uniform float u_tileX;",
117 "uniform float u_tileY;",
118 "uniform float u_deep;",
119 "uniform float u_edgeN;",
120 "uniform float u_edgeE;",
121 "uniform float u_edgeS;",
122 "uniform float u_edgeW;",
123 "uniform float u_hasShore;",
124 "uniform float u_shoreEdgeN;",
125 "uniform float u_shoreEdgeE;",
126 "uniform float u_shoreEdgeS;",
127 "uniform float u_shoreEdgeW;",
128 "uniform vec4 u_shoreUvRect;",
129 "void main() {",
130 // Pixel grid (16x16) for body waves — stable across the tile.
131 " vec2 px = floor(v_texCoord * 16.0) + 0.5;",
132 " vec2 puv = px / 16.0;",
133 " vec2 world = vec2(u_tileX, u_tileY) + puv;",
134 " float w1 = sin(u_time * 1.7 + world.x * 5.1 + world.y * 3.3);",
135 " float w2 = sin(u_time * 2.3 + world.x * -3.7 + world.y * 6.2 + 1.7);",
136 " float body = 0.55 + 0.28 * w1 + 0.17 * w2;",
137 " vec3 shallowA = vec3(0.19, 0.46, 0.66);",
138 " vec3 shallowB = vec3(0.35, 0.67, 0.82);",
139 " vec3 deepA = vec3(0.11, 0.28, 0.46);",
140 " vec3 deepB = vec3(0.22, 0.47, 0.67);",
141 " vec3 baseA = mix(shallowA, deepA, u_deep);",
142 " vec3 baseB = mix(shallowB, deepB, u_deep);",
143 " vec3 rgb = mix(baseA, baseB, clamp(body, 0.0, 1.0));",
144 " vec3 foamCol = vec3(0.78, 0.92, 1.0);",
145 " float foam = 0.0;",
146 " float shoreMix = 0.0;",
147 " vec3 shoreRgb = rgb;",
148 // Top-down sine coastline: surge = foam, retreat = neighbor shore pixels.
149 " float coastAmp = 0.09;",
150 " float coastBase = 0.14;",
151 " if (u_edgeN > 0.5) {",
152 " float along = puv.x;",
153 " float wave = sin(u_time * 2.6 + along * 14.0 + u_tileX * 0.9 + u_tileY * 0.4);",
154 " float band = coastBase + coastAmp * wave;",
155 " float dist = puv.y;",
156 " if (dist < band) {",
157 " float t = 1.0 - dist / max(band, 0.001);",
158 " if (wave < -0.2 && u_hasShore > 0.5 && u_shoreEdgeN > 0.5) {",
159 " vec2 shoreNu = vec2(puv.x, 1.0 - dist);",
160 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
161 " vec4 shore = texture2D(u_secondary, shoreUv);",
162 " if (shore.a > 0.1) { shoreRgb = shore.rgb; shoreMix = max(shoreMix, t); }",
163 " else { foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave))); }",
164 " } else {",
165 " foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave)));",
166 " }",
167 " }",
168 " }",
169 " if (u_edgeS > 0.5) {",
170 " float along = puv.x;",
171 " float wave = sin(u_time * 2.6 + along * 14.0 + u_tileX * 0.7 + u_tileY * 1.1 + 2.1);",
172 " float band = coastBase + coastAmp * wave;",
173 " float dist = 1.0 - puv.y;",
174 " if (dist < band) {",
175 " float t = 1.0 - dist / max(band, 0.001);",
176 " if (wave < -0.2 && u_hasShore > 0.5 && u_shoreEdgeS > 0.5) {",
177 " vec2 shoreNu = vec2(puv.x, dist);",
178 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
179 " vec4 shore = texture2D(u_secondary, shoreUv);",
180 " if (shore.a > 0.1) { shoreRgb = shore.rgb; shoreMix = max(shoreMix, t); }",
181 " else { foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave))); }",
182 " } else {",
183 " foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave)));",
184 " }",
185 " }",
186 " }",
187 " if (u_edgeW > 0.5) {",
188 " float along = puv.y;",
189 " float wave = sin(u_time * 2.6 + along * 14.0 + u_tileX * 1.2 + u_tileY * 0.5 + 0.8);",
190 " float band = coastBase + coastAmp * wave;",
191 " float dist = puv.x;",
192 " if (dist < band) {",
193 " float t = 1.0 - dist / max(band, 0.001);",
194 " if (wave < -0.2 && u_hasShore > 0.5 && u_shoreEdgeW > 0.5) {",
195 " vec2 shoreNu = vec2(1.0 - dist, puv.y);",
196 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
197 " vec4 shore = texture2D(u_secondary, shoreUv);",
198 " if (shore.a > 0.1) { shoreRgb = shore.rgb; shoreMix = max(shoreMix, t); }",
199 " else { foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave))); }",
200 " } else {",
201 " foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave)));",
202 " }",
203 " }",
204 " }",
205 " if (u_edgeE > 0.5) {",
206 " float along = puv.y;",
207 " float wave = sin(u_time * 2.6 + along * 14.0 + u_tileX * 0.4 + u_tileY * 0.9 + 3.3);",
208 " float band = coastBase + coastAmp * wave;",
209 " float dist = 1.0 - puv.x;",
210 " if (dist < band) {",
211 " float t = 1.0 - dist / max(band, 0.001);",
212 " if (wave < -0.2 && u_hasShore > 0.5 && u_shoreEdgeE > 0.5) {",
213 " vec2 shoreNu = vec2(dist, puv.y);",
214 " vec2 shoreUv = u_shoreUvRect.xy + shoreNu * (u_shoreUvRect.zw - u_shoreUvRect.xy);",
215 " vec4 shore = texture2D(u_secondary, shoreUv);",
216 " if (shore.a > 0.1) { shoreRgb = shore.rgb; shoreMix = max(shoreMix, t); }",
217 " else { foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave))); }",
218 " } else {",
219 " foam = max(foam, t * (0.35 + 0.45 * max(0.0, wave)));",
220 " }",
221 " }",
222 " }",
223 " rgb = mix(rgb, foamCol, clamp(foam, 0.0, 0.85));",
224 " rgb = mix(rgb, shoreRgb, clamp(shoreMix, 0.0, 1.0));",
225 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
226 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
227 " float lit = mix(litTop, litBottom, v_texCoord.y);",
228 " float darkness = u_ambientDark * (1.0 - lit);",
229 " rgb = mix(rgb, vec3(0.0), darkness);",
230 " gl_FragColor = vec4(rgb, u_alpha);",
231 "}"
232].join("\n");
233
234/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
235const TINT_LIT_SPRITE_FRAG = [
236 "precision mediump float;",
237 "varying vec2 v_texCoord;",
238 "uniform sampler2D u_texture;",
239 "uniform float u_alpha;",
240 "uniform float u_darkness;",
241 "uniform float u_strength;",
242 "uniform vec3 u_flashColor;",
243 "uniform float u_wade;",
244 "uniform float u_spriteHeight;",
245 "uniform float u_useTint;",
246 "uniform vec3 u_tintColor;",
247 "void main() {",
248 " vec4 color = texture2D(u_texture, v_texCoord);",
249 " if (color.a <= 0.0) { discard; }",
250 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
251 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
252 " vec3 rgb = color.rgb;",
253 " if (u_useTint > 0.5) {",
254 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
255 " float L = color.r;",
256 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
257 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
258 " }",
259 " }",
260 " if (u_wade > 0.5 && fromBottom < 5.0) {",
261 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
262 " }",
263 " rgb = mix(rgb, vec3(0.0), u_darkness);",
264 " rgb = mix(rgb, u_flashColor, u_strength);",
265 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
266 "}"
267].join("\n");
268
269/** Dual/triple-channel tint: red = shaft, blue = tip, green = coat; then darkness.
270 * Only when the primary channel is highest and the other two are equal;
271 * equal non-zero secondaries lighten the assigned tint toward white. */
272const DUAL_TINT_LIT_SPRITE_FRAG = [
273 "precision mediump float;",
274 "varying vec2 v_texCoord;",
275 "uniform sampler2D u_texture;",
276 "uniform float u_alpha;",
277 "uniform float u_darkness;",
278 "uniform float u_strength;",
279 "uniform vec3 u_flashColor;",
280 "uniform float u_wade;",
281 "uniform float u_spriteHeight;",
282 "uniform vec3 u_shaftTint;",
283 "uniform vec3 u_tipTint;",
284 "uniform vec3 u_coatTint;",
285 "uniform float u_hasCoat;",
286 "vec3 channelTint(float L, float secondary, vec3 tint) {",
287 " float blend = L > 0.0 ? clamp(secondary / L, 0.0, 1.0) : 0.0;",
288 " return mix(tint, vec3(1.0), blend) * L;",
289 "}",
290 "float channelMask(float primary, float o1, float o2) {",
291 " float equal = step(abs(o1 - o2), 0.04);",
292 " return clamp((primary - max(o1, o2)) * 1.75, 0.0, 1.0) * equal;",
293 "}",
294 "void main() {",
295 " vec4 color = texture2D(u_texture, v_texCoord);",
296 " if (color.a <= 0.0) { discard; }",
297 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
298 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
299 " vec3 rgb = color.rgb;",
300 " if (u_hasCoat > 0.5) {",
301 " float coatMask = channelMask(color.g, color.r, color.b);",
302 " if (coatMask > 0.0) {",
303 " vec3 coatCol = channelTint(color.g, color.r, u_coatTint);",
304 " rgb = mix(rgb, coatCol, coatMask);",
305 " }",
306 " }",
307 " float tipMask = channelMask(color.b, color.r, color.g);",
308 " if (tipMask > 0.0) {",
309 " vec3 tipCol = channelTint(color.b, color.r, u_tipTint);",
310 " rgb = mix(rgb, tipCol, tipMask);",
311 " }",
312 " float shaftMask = channelMask(color.r, color.g, color.b);",
313 " if (shaftMask > 0.0) {",
314 " vec3 shaftCol = channelTint(color.r, color.g, u_shaftTint);",
315 " rgb = mix(rgb, shaftCol, shaftMask);",
316 " }",
317 " if (u_wade > 0.5 && fromBottom < 5.0) {",
318 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
319 " }",
320 " rgb = mix(rgb, vec3(0.0), u_darkness);",
321 " rgb = mix(rgb, u_flashColor, u_strength);",
322 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
323 "}"
324].join("\n");
325
326/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
327/**
328 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
329 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
330 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
331 */
332const TIGHT_FIT_BODY_MASK_GLSL = [
333 "uniform vec2 u_clothSize;",
334 "uniform vec2 u_bodySize;",
335 "uniform float u_pivotFromBottom;",
336 "uniform vec4 u_clothUvRect;",
337 "uniform vec4 u_bodyUvRect;",
338 "float tightFitBodyAlpha() {",
339 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
340 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
341 " float ox = (nu.x - 0.5) * u_clothSize.x;",
342 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
343 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
344 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
345 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
346 " vec2 texel = 1.0 / bodySize;",
347 " float bodyA = 0.0;",
348 " for (int dy = -1; dy <= 1; dy++) {",
349 " for (int dx = -1; dx <= 1; dx++) {",
350 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
351 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
352 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
353 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
354 " }",
355 " }",
356 " return bodyA;",
357 "}"
358].join("\n");
359
360const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
361 "precision mediump float;",
362 "varying vec2 v_texCoord;",
363 "uniform sampler2D u_texture;",
364 "uniform sampler2D u_secondary;",
365 "uniform float u_alpha;",
366 "uniform float u_darkness;",
367 "uniform float u_strength;",
368 "uniform vec3 u_flashColor;",
369 "uniform float u_wade;",
370 "uniform float u_spriteHeight;",
371 "uniform float u_useTint;",
372 "uniform vec3 u_tintColor;",
373 TIGHT_FIT_BODY_MASK_GLSL,
374 "void main() {",
375 " vec4 color = texture2D(u_texture, v_texCoord);",
376 " if (color.a <= 0.0) { discard; }",
377 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
378 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
379 " vec3 rgb = color.rgb;",
380 " if (u_useTint > 0.5) {",
381 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
382 " float L = color.r;",
383 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
384 " rgb = mix(u_tintColor, vec3(1.0), gBlend) * L;",
385 " }",
386 " }",
387 " if (u_wade > 0.5 && fromBottom < 5.0) {",
388 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
389 " }",
390 " rgb = mix(rgb, vec3(0.0), u_darkness);",
391 " rgb = mix(rgb, u_flashColor, u_strength);",
392 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
393 " if (alpha <= 0.0) { discard; }",
394 " gl_FragColor = vec4(rgb, alpha);",
395 "}"
396].join("\n");
397
398/** Body-clipped equip overlay without dye recolour. */
399const TIGHT_FIT_LIT_SPRITE_FRAG = [
400 "precision mediump float;",
401 "varying vec2 v_texCoord;",
402 "uniform sampler2D u_texture;",
403 "uniform sampler2D u_secondary;",
404 "uniform float u_alpha;",
405 "uniform float u_darkness;",
406 "uniform float u_strength;",
407 "uniform vec3 u_flashColor;",
408 "uniform float u_wade;",
409 "uniform float u_spriteHeight;",
410 TIGHT_FIT_BODY_MASK_GLSL,
411 "void main() {",
412 " vec4 color = texture2D(u_texture, v_texCoord);",
413 " if (color.a <= 0.0) { discard; }",
414 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
415 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
416 " vec3 rgb = color.rgb;",
417 " if (u_wade > 0.5 && fromBottom < 5.0) {",
418 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
419 " }",
420 " rgb = mix(rgb, vec3(0.0), u_darkness);",
421 " rgb = mix(rgb, u_flashColor, u_strength);",
422 " float alpha = min(tightFitBodyAlpha(), color.a) * u_alpha;",
423 " if (alpha <= 0.0) { discard; }",
424 " gl_FragColor = vec4(rgb, alpha);",
425 "}"
426].join("\n");
427
428const ATLAS_LIGHTING_FRAG = [
429 "precision mediump float;",
430 "varying vec2 v_texCoord;",
431 "uniform sampler2D u_texture;",
432 "uniform sampler2D u_secondary;",
433 "uniform float u_alpha;",
434 "uniform float u_ambientDark;",
435 "uniform float u_lightRow;",
436 "void main() {",
437 " vec4 color = texture2D(u_texture, v_texCoord);",
438 " if (color.a <= 0.0) { discard; }",
439 " vec2 lightUV = v_texCoord;",
440 " if (u_lightRow >= 0.0) {",
441 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
442 " }",
443 " float lit = texture2D(u_secondary, lightUV).r;",
444 " float darkness = u_ambientDark * (1.0 - lit);",
445 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
446 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
447 "}"
448].join("\n");
449
450/**
451 * Per-tile cliff sprite: high-chroma / authored magenta top → sample this chunk's
452 * ground atlas (u_bump) at the cliff's tile-local UV. Only assigned to
453 * `cliffGroundTop` blocks — never to chunk block-row atlases (those keep normal
454 * lighting so magenta wood tints are not mistaken for cliff tops).
455 */
456const SPRITE_CLIFF_GROUND_TOP_FRAG = [
457 "precision mediump float;",
458 "varying vec2 v_texCoord;",
459 "uniform sampler2D u_texture;",
460 "uniform sampler2D u_bump;",
461 "uniform float u_alpha;",
462 "uniform float u_darkness;",
463 "uniform vec2 u_tileLocal;",
464 "void main() {",
465 " vec4 color = texture2D(u_texture, v_texCoord);",
466 " if (color.a <= 0.0) { discard; }",
467 " vec3 rgb = color.rgb;",
468 " float rbDiff = abs(rgb.r - rgb.b);",
469 " if (rbDiff < 0.02 && rgb.g < rgb.r) {",
470 " vec2 groundUV = (u_tileLocal + v_texCoord) / 16.0;",
471 " rgb = texture2D(u_bump, groundUV).rgb;",
472 " }",
473 " rgb = mix(rgb, vec3(0.0), u_darkness);",
474 " gl_FragColor = vec4(rgb, color.a * u_alpha);",
475 "}"
476].join("\n");
477
478let spriteLightingShader = null;
479let atlasLightingShader = null;
480let cliffGroundTopShader = null;
481let waterGroundShader = null;
482let tintLitSpriteShader = null;
483let dualTintLitSpriteShader = null;
484let tightFitTintLitSpriteShader = null;
485let tightFitLitSpriteShader = null;
486
487function getSpriteLightingShader ()
488{
489 if (!spriteLightingShader)
490 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
491 return spriteLightingShader;
492}
493
494function getAtlasLightingShader ()
495{
496 if (!atlasLightingShader)
497 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
498 return atlasLightingShader;
499}
500
501function getCliffGroundTopShader ()
502{
503 if (!cliffGroundTopShader)
504 { cliffGroundTopShader = Shader.fragment(SPRITE_CLIFF_GROUND_TOP_FRAG); }
505 return cliffGroundTopShader;
506}
507
508function getWaterGroundShader ()
509{
510 if (!waterGroundShader)
511 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
512 return waterGroundShader;
513}
514
515function getTintLitSpriteShader ()
516{
517 if (!tintLitSpriteShader)
518 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
519 return tintLitSpriteShader;
520}
521
522function getDualTintLitSpriteShader ()
523{
524 if (!dualTintLitSpriteShader)
525 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
526 return dualTintLitSpriteShader;
527}
528
529function getTightFitTintLitSpriteShader ()
530{
531 if (!tightFitTintLitSpriteShader)
532 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
533 return tightFitTintLitSpriteShader;
534}
535
536function getTightFitLitSpriteShader ()
537{
538 if (!tightFitLitSpriteShader)
539 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
540 return tightFitLitSpriteShader;
541}
542
543export class WorldView
544{
545 #chunkRebuildKeys = new Set();
546 #chunkRebuildRaf = 0;
547 #edgesDirty = false;
548 #CHUNK_REBUILD_BATCH = 2;
549 #pendingTextureCanvases = [];
550 #pendingTextureCanvasSet = new Set();
551 #textureWarmRaf = 0;
552 #TEXTURE_WARM_BATCH = 3;
553 #atlasCache = createChunkAtlasCache();
554 #idlePrefetchId = 0;
555 #playerChunkX = null;
556 #playerChunkY = null;
557 #playerMoveChunkDx = 0;
558 #playerMoveChunkDy = 0;
559
560 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
561 {
562 this.game = game;
563 this.scene = scene;
564 this.catalog = catalog;
565 this.preview = null;
566 this.zoom = 2;
567 /** Chunk-quantised world-Y origin for the depth sort (see {@link #depthLayer}). */
568 this.ySortOrigin = null;
569 this.chunks = new Map();
570 this.bakedChunks = new Map();
571 this.tiles = new Map();
572 this.entities = new Map();
573 this.groundItems = new Map();
574 this.edges = new Map();
575 this.localEntityId = null;
576 this.localBlind = false;
577 /** @type {string} */
578 this.dimensionId = OVERWORLD_ID;
579 /** @type {string} */
580 this.dimensionLightingMode = "dayNight";
581 /** @type {string} */
582 this.dimensionSeasonMode = "auto";
583 /** Calendar season from worldStatus when dimension season is auto. */
584 this.calendarSeason = seasonIdAt();
585 /** @type {"soft"|"simple"} */
586 this.lightingMode = "soft";
587 /** @type {boolean} */
588 this.bloomEnabled = true;
589 /** Soft edge blend for blendable grounds (grass, dirt, …). */
590 this.softTerrain = false;
591 this.settings = { ...DEFAULT_WORLD_SETTINGS };
592 this.worldHour = 12;
593 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
594 this.worldSeason = seasonIdAt();
595 this.nightPreview = null;
596 this.followPlayer = true;
597 this.dynamicLights = [];
598 /** Persistent Light-spell tile lights (server-driven). */
599 this.spellLights = new Map();
600 /** Persistent Dark-spell tile darkness (server-driven). */
601 this.spellDarks = new Map();
602 this.swipes = [];
603 this.damageFloats = [];
604 this.damageNumbersEl = document.getElementById("damage-numbers");
605 this.skillLevelFloats = [];
606 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
607 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
608 this.editorSpawners = new Map();
609 this.spawnRangeHighlight = null;
610 this.wanderRangeHighlight = null;
611 this.spellTargetHighlight = null;
612 this.#syncBloomLayer();
613 }
614
615 setSettings (settings)
616 {
617 const previous = this.settings;
618 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
619 this.#syncBloomLayer();
620 const prevBand = Number(previous?.wetSandBand);
621 const nextBand = Number(this.settings.wetSandBand);
622 if (Number.isFinite(nextBand) && prevBand !== nextBand)
623 { this.#rebakeAllChunks(); }
624 }
625
626 /**
627 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
628 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
629 */
630 setGraphicsPrefs (prefs)
631 {
632 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
633 { this.lightingMode = prefs.lighting; }
634 if (prefs?.bloom === "off" || prefs?.bloom === "on")
635 {
636 const enabled = prefs.bloom !== "off";
637 if (enabled !== this.bloomEnabled)
638 {
639 this.bloomEnabled = enabled;
640 this.#syncBloomLayer();
641 }
642 else
643 { this.bloomEnabled = enabled; }
644 }
645 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
646 {
647 const enabled = prefs.softTerrain === "on";
648 if (enabled !== this.softTerrain)
649 {
650 this.softTerrain = enabled;
651 this.#rebakeAllChunks();
652 }
653 }
654 }
655
656 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
657 setWorldSeason (season)
658 {
659 const calendar = season === SeasonId.spring
660 || season === SeasonId.fall
661 || season === SeasonId.winter
662 || season === SeasonId.summer
663 ? season
664 : seasonIdAt();
665 this.calendarSeason = calendar;
666 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
667 const next = forced ?? calendar;
668 if (next === this.worldSeason)
669 { return; }
670 this.worldSeason = next;
671 this.#rebakeAllChunks();
672 }
673
674 setDimensionId (dimensionId)
675 {
676 this.dimensionId = normalizeDimensionId(dimensionId);
677 }
678
679 setDimensionModes (lightingMode, seasonMode)
680 {
681 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
682 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
683 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
684 const next = forced ?? this.calendarSeason ?? seasonIdAt();
685 if (next !== this.worldSeason)
686 {
687 this.worldSeason = next;
688 this.#rebakeAllChunks();
689 }
690 }
691
692 clearAllChunks ()
693 {
694 for (const key of [...this.chunks.keys()])
695 {
696 const [chunkX, chunkY] = key.split(",").map(Number);
697 this.removeChunk(chunkX, chunkY);
698 }
699 for (const [id] of [...this.entities.entries()])
700 {
701 if (id === this.localEntityId)
702 { continue; }
703 this.despawnEntity(id, { immediate: true });
704 }
705 for (const [id] of [...this.groundItems.entries()])
706 { this.despawnGroundItem(id); }
707 }
708
709 /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
710 clearPlaySession ()
711 {
712 this.#cancelIdlePrefetch();
713 this.#chunkRebuildKeys.clear();
714 this.#playerChunkX = null;
715 this.#playerChunkY = null;
716 this.#playerMoveChunkDx = 0;
717 this.#playerMoveChunkDy = 0;
718 this.localEntityId = null;
719 for (const key of [...this.chunks.keys()])
720 {
721 const [chunkX, chunkY] = key.split(",").map(Number);
722 this.removeChunk(chunkX, chunkY);
723 }
724 for (const [id] of [...this.entities.entries()])
725 { this.despawnEntity(id, { immediate: true }); }
726 for (const [id] of [...this.groundItems.entries()])
727 { this.despawnGroundItem(id); }
728 }
729
730 applySnapshot (snapshot)
731 {
732 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
733 if (normalizeDimensionId(this.dimensionId) !== snapDim)
734 { return; }
735 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
736 snapshot.occlusion = bakeChunkOcclusion(snapshot);
737 this.chunks.set(key, snapshot);
738 this.#scheduleChunkRebuild(snapshot);
739 this.#redrawPreview();
740 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
741 if (snapshot.staticOnly)
742 {
743 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
744 this.#scheduleEdgeRebuild();
745 return;
746 }
747 for (const entity of snapshot.entities ?? [])
748 { this.#upsertEntity(entity); }
749 for (const [id, item] of [...this.groundItems.entries()])
750 {
751 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
752 { this.despawnGroundItem(id); }
753 }
754 for (const item of snapshot.groundItems ?? [])
755 { this.upsertGroundItem(item); }
756 this.#scheduleEdgeRebuild();
757 }
758
759 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null, skullValue = 0)
760 {
761 this.localEntityId = entityId;
762 this.#upsertEntity({
763 entityId,
764 characterId,
765 tileX,
766 tileY,
767 gait,
768 sex,
769 firstName,
770 lastName,
771 layers: layers ?? undefined,
772 skullValue: skullValue | 0,
773 ...(health != null ? { health } : {}),
774 ...(maxHealth != null ? { maxHealth } : {})
775 });
776 this.#notePlayerTile(tileX, tileY);
777 }
778
779 #stripChunkDynamic (chunkX, chunkY)
780 {
781 for (const [id, item] of [...this.groundItems.entries()])
782 {
783 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
784 { this.despawnGroundItem(id); }
785 }
786 for (const [id, entity] of [...this.entities.entries()])
787 {
788 if (id === this.localEntityId)
789 { continue; }
790 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
791 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
792 { this.despawnEntity(id, { immediate: true }); }
793 }
794 }
795
796 removeChunk (chunkX, chunkY)
797 {
798 const key = `${chunkX},${chunkY}`;
799 this.chunks.delete(key);
800 this.#destroyBakedChunk(key);
801 this.#destroyEdges(key);
802 const prefix = `${chunkX},${chunkY}:`;
803 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
804 {
805 if (!spawnerKey.startsWith(prefix))
806 { continue; }
807 this.#destroyEditorSpawnerEntry(entry);
808 this.editorSpawners.delete(spawnerKey);
809 }
810 for (const [tileKey, objects] of [...this.tiles.entries()])
811 {
812 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
813 {
814 objects.ground?.destroy();
815 objects.groundBloom?.destroy();
816 objects.block?.destroy();
817 objects.blockBloom?.destroy();
818 this.tiles.delete(tileKey);
819 }
820 }
821 for (const [id, item] of [...this.groundItems.entries()])
822 {
823 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
824 { this.despawnGroundItem(id); }
825 }
826 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
827 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
828 for (const [id, entity] of [...this.entities.entries()])
829 {
830 if (id === this.localEntityId)
831 { continue; }
832 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
833 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
834 { this.despawnEntity(id, { immediate: true }); }
835 }
836 this.#rebuildAllEdges();
837 }
838
839 setChunkOpen (chunkX, chunkY, open)
840 {
841 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
842 if (!snapshot)
843 { return; }
844 snapshot.open = !!open;
845 this.#rebuildAllEdges();
846 }
847
848 spawnEntity (payload)
849 {
850 // Fresh spawn is authoritative; do not let an older deferred hit overwrite HP.
851 this.cancelDeferredCombatHits(payload?.entityId);
852 this.#upsertEntity(payload);
853 }
854
855 moveEntity (payload)
856 {
857 const existing = this.entities.get(payload.entityId);
858 // Move payloads lack appearance/mobTypeId — never invent a stub entity
859 // (that looked like a nameless humanoid "target"). Wait for entity-spawn.
860 if (!existing)
861 { return; }
862 // Fading corpses stay put; respawn restores via reviveAfterDeath / spawn.
863 if (existing.dying)
864 { return; }
865 const size = this.tileSize();
866 existing.fromX = existing.visualX;
867 existing.fromY = existing.visualY;
868 existing.shadeFromTileX = existing.tileX;
869 existing.shadeFromTileY = existing.tileY;
870 if (existing.tileX !== payload.tileX || existing.tileY !== payload.tileY)
871 {
872 existing.previousTileX = existing.tileX;
873 existing.previousTileY = existing.tileY;
874 }
875 existing.tileX = payload.tileX;
876 existing.tileY = payload.tileY;
877 existing.gait = payload.gait;
878 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
879 if (payload.worldX != null && payload.worldY != null)
880 {
881 existing.worldX = payload.worldX;
882 existing.worldY = payload.worldY;
883 existing.targetX = payload.worldX * size;
884 existing.targetY = payload.worldY * size;
885 }
886 else
887 {
888 const pivot = tilePivot(payload.tileX, payload.tileY, size);
889 existing.targetX = pivot.x;
890 existing.targetY = pivot.y;
891 }
892 existing.lerpStarted = performance.now();
893 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
894 if (payload.entityId === this.localEntityId)
895 { this.#notePlayerTile(payload.tileX, payload.tileY); }
896 }
897
898 despawnEntity (entityId, { immediate = false, combatDeath = false } = {})
899 {
900 const existing = this.entities.get(entityId);
901 if (!existing)
902 { return; }
903 if (existing.dying)
904 {
905 if (immediate)
906 { this.#finishEntityFade(entityId); }
907 else if (combatDeath)
908 { this.#upgradeToDeathDissolve(existing); }
909 return;
910 }
911 // Chunk unload / session wipe: drop instantly.
912 if (immediate)
913 {
914 this.cancelDeferredCombatHits(entityId);
915 this.#destroyEntityVisuals(existing);
916 this.entities.delete(entityId);
917 return;
918 }
919 // Combat death → red silhouette. Leaving 3×3 / summons / etc. → plain fade.
920 if (combatDeath)
921 { this.#beginDeathDissolve(existing); }
922 else
923 { this.#beginDespawnFade(existing); }
924 }
925
926 /**
927 * Start the red silhouette fade without requiring a despawn message
928 * (e.g. local playerDied arrives before entityDespawn).
929 */
930 beginDeathDissolve (entityId)
931 {
932 const existing = this.entities.get(entityId);
933 if (!existing)
934 { return; }
935 if (existing.dying)
936 {
937 this.#upgradeToDeathDissolve(existing);
938 return;
939 }
940 this.#beginDeathDissolve(existing);
941 }
942
943 /**
944 * Abort an in-progress (or finished) death fade and snap the sprite back.
945 * Local players are never entity-despawned, so respawn must restore — not
946 * destroy — the visual. Remotes get a fresh entity-spawn instead.
947 */
948 reviveAfterDeath (entityId, { tileX, tileY, health, maxHealth, skullValue } = {})
949 {
950 const entity = this.entities.get(entityId);
951 if (!entity)
952 { return false; }
953 this.#abortEntityFade(entity);
954 if (tileX != null && tileY != null)
955 { this.#snapEntityToTile(entity, tileX, tileY); }
956 if (health != null)
957 { entity.health = health; }
958 if (maxHealth != null)
959 { entity.maxHealth = maxHealth; }
960 if (skullValue != null)
961 { entity.skullValue = Math.max(0, skullValue | 0); }
962 this.#syncHpBar(entity);
963 this.#syncSkullMarker(entity);
964 this.#placeEntity(entity, performance.now());
965 return true;
966 }
967
968 #destroyEntityVisuals (existing)
969 {
970 existing.object?.destroy();
971 existing.hpBar?.destroy();
972 existing.skullMarker?.destroy();
973 for (const overlay of existing.overlays ?? [])
974 { overlay.destroy(); }
975 for (const overlay of existing.bloomOverlays ?? [])
976 { overlay.destroy(); }
977 }
978
979 #stripEntityChrome (entity)
980 {
981 entity.hpBar?.destroy();
982 entity.hpBar = null;
983 entity.skullMarker?.destroy();
984 entity.skullMarker = null;
985 }
986
987 #beginDespawnFade (entity)
988 {
989 const now = performance.now();
990 entity.dying = true;
991 entity.deathDissolve = false;
992 entity.untargetable = true;
993 entity.deathFadeStarted = now;
994 entity.deathFadeMs = DESPAWN_FADE_MS;
995 this.#stripEntityChrome(entity);
996 }
997
998 #beginDeathDissolve (entity)
999 {
1000 const now = performance.now();
1001 entity.dying = true;
1002 entity.deathDissolve = true;
1003 entity.untargetable = true;
1004 entity.deathFadeStarted = now;
1005 entity.deathFadeMs = DEATH_FADE_MS;
1006 // Keep a full red silhouette for the whole fade (hit flash may already be running).
1007 entity.damageFlashUntil = now + DEATH_FADE_MS;
1008 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
1009 this.#stripEntityChrome(entity);
1010 // Leave deferred projectile impacts queued so knockback / float still play on arrival.
1011 }
1012
1013 /** Promote an in-progress plain despawn fade to the red combat dissolve. */
1014 #upgradeToDeathDissolve (entity)
1015 {
1016 if (entity.deathDissolve)
1017 { return; }
1018 const now = performance.now();
1019 const elapsed = Math.max(0, now - (entity.deathFadeStarted ?? now));
1020 const remaining = Math.max(1, (entity.deathFadeMs ?? DESPAWN_FADE_MS) - elapsed);
1021 entity.deathDissolve = true;
1022 entity.deathFadeStarted = now;
1023 entity.deathFadeMs = Math.min(DEATH_FADE_MS, remaining);
1024 entity.damageFlashUntil = now + entity.deathFadeMs;
1025 entity.damageFlashColor = FLASH_COLOR_DAMAGE;
1026 }
1027
1028 #abortEntityFade (entity)
1029 {
1030 entity.dying = false;
1031 entity.deathDissolve = false;
1032 entity.untargetable = false;
1033 entity.deathFadeStarted = null;
1034 entity.deathFadeMs = null;
1035 entity.damageFlashUntil = 0;
1036 entity.damageFlashColor = null;
1037 if (entity.object?.renderer)
1038 { entity.object.renderer.alpha = 1; }
1039 for (const overlay of entity.overlays ?? [])
1040 {
1041 if (overlay.renderer)
1042 { overlay.renderer.alpha = 1; }
1043 }
1044 for (const overlay of entity.bloomOverlays ?? [])
1045 {
1046 if (overlay.renderer)
1047 { overlay.renderer.alpha = 1; }
1048 }
1049 }
1050
1051 #snapEntityToTile (entity, tileX, tileY)
1052 {
1053 const size = this.tileSize();
1054 const pivot = tilePivot(tileX, tileY, size);
1055 entity.tileX = tileX;
1056 entity.tileY = tileY;
1057 entity.visualX = pivot.x;
1058 entity.visualY = pivot.y;
1059 entity.targetX = pivot.x;
1060 entity.targetY = pivot.y;
1061 entity.fromX = pivot.x;
1062 entity.fromY = pivot.y;
1063 entity.lerpStarted = null;
1064 entity.previousTileX = null;
1065 entity.previousTileY = null;
1066 entity.shadeFromTileX = null;
1067 entity.shadeFromTileY = null;
1068 entity.shoveOffsetX = 0;
1069 entity.shoveOffsetY = 0;
1070 if (entity.entityId === this.localEntityId)
1071 { this.#notePlayerTile(tileX, tileY); }
1072 }
1073
1074 #finishEntityFade (entityId)
1075 {
1076 this.cancelDeferredCombatHits(entityId);
1077 const existing = this.entities.get(entityId);
1078 if (!existing)
1079 { return; }
1080 this.#destroyEntityVisuals(existing);
1081 this.entities.delete(entityId);
1082 }
1083
1084 /**
1085 * Drop queued combat-hit/block presentation for a target.
1086 * Killing blows often defer health=0 until a projectile lands; if the
1087 * target already finished dissolving or respawned, that stale apply must not run.
1088 */
1089 cancelDeferredCombatHits (targetId)
1090 {
1091 if (targetId == null)
1092 { return; }
1093 for (const swipe of this.swipes)
1094 {
1095 if (swipe.targetId !== targetId)
1096 { continue; }
1097 swipe.onImpact = null;
1098 swipe.trackTarget = false;
1099 }
1100 }
1101
1102 updateEntitySkull (entityId, skullValue)
1103 {
1104 const entity = this.entities.get(entityId);
1105 if (!entity)
1106 { return; }
1107 entity.skullValue = Math.max(0, skullValue | 0);
1108 const pivotX = (entity.visualX ?? 0) + (entity.shoveOffsetX ?? 0) + (entity.stackOffsetX ?? 0);
1109 const pivotY = (entity.visualY ?? 0) + (entity.shoveOffsetY ?? 0) + (entity.stackOffsetY ?? 0);
1110 const tileShade = this.#entityShadeAlpha?.(entity, performance.now())
1111 ?? this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha
1112 ?? 0;
1113 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
1114 }
1115
1116 updateEntityHealth (entityId, health, maxHealth)
1117 {
1118 const entity = this.entities.get(entityId);
1119 if (!entity || entity.dying)
1120 { return; }
1121 entity.health = health;
1122 entity.maxHealth = maxHealth;
1123 this.#syncHpBar(entity);
1124 }
1125
1126 flashDamage (entityId)
1127 {
1128 this.#flashEntity(entityId, FLASH_COLOR_DAMAGE);
1129 }
1130
1131 flashBlock (entityId)
1132 {
1133 this.#flashEntity(entityId, FLASH_COLOR_BLOCK);
1134 }
1135
1136 #flashEntity (entityId, color)
1137 {
1138 const entity = this.entities.get(entityId);
1139 if (!entity)
1140 { return; }
1141 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
1142 entity.damageFlashColor = color ?? FLASH_COLOR_DAMAGE;
1143 }
1144
1145 /** Target knocks back away from attacker (hit). */
1146 spawnCombatKnockback (payload)
1147 {
1148 const attacker = this.entities.get(payload?.attackerId);
1149 const target = this.entities.get(payload?.targetId);
1150 if (!attacker || !target)
1151 { return; }
1152 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1153 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1154 const tx = target.visualX + (target.stackOffsetX ?? 0);
1155 const ty = target.visualY + (target.stackOffsetY ?? 0);
1156 this.#applyShoveInDirection(target, tx - ax, ty - ay);
1157 }
1158
1159 /** Target sidesteps perpendicular to the attack (dodge / miss). */
1160 spawnCombatDodge (payload)
1161 {
1162 const attacker = this.entities.get(payload?.attackerId);
1163 const target = this.entities.get(payload?.targetId);
1164 if (!attacker || !target)
1165 { return; }
1166 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1167 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1168 const tx = target.visualX + (target.stackOffsetX ?? 0);
1169 const ty = target.visualY + (target.stackOffsetY ?? 0);
1170 const dx = tx - ax;
1171 const dy = ty - ay;
1172 const side = Math.random() < 0.5 ? 1 : -1;
1173 this.#applyShoveInDirection(target, -dy * side, dx * side);
1174 }
1175
1176 spawnDamageNumber (entityId, damage)
1177 {
1178 const amount = damage | 0;
1179 if (amount <= 0)
1180 { return; }
1181 this.damageFloats.push({
1182 entityId,
1183 damage: amount,
1184 started: performance.now()
1185 });
1186 }
1187
1188 /**
1189 * Queue combat-hit presentation until a matching in-flight projectile lands.
1190 * Returns true when deferred; caller should apply immediately when false.
1191 */
1192 deferCombatHit (message, apply)
1193 {
1194 if (typeof apply !== "function" || message?.targetId == null)
1195 { return false; }
1196 const attackerId = message.attackerId ?? null;
1197 const targetId = message.targetId;
1198 const swipe = this.swipes.find((entry) =>
1199 entry.lerp
1200 && entry.onImpact == null
1201 && entry.targetId === targetId
1202 && (attackerId == null || entry.attackerId === attackerId)
1203 && (entry.until ?? 0) > performance.now());
1204 if (!swipe)
1205 { return false; }
1206 swipe.onImpact = apply;
1207 swipe.trackTarget = true;
1208 return true;
1209 }
1210
1211 /** Stop tracking a living target (misses fly to a fixed tile). */
1212 markProjectileMiss (message)
1213 {
1214 const attackerId = message?.attackerId ?? null;
1215 const targetId = message?.targetId ?? null;
1216 for (const swipe of this.swipes)
1217 {
1218 if (!swipe.lerp || swipe.onImpact != null)
1219 { continue; }
1220 if (targetId != null && swipe.targetId !== targetId)
1221 { continue; }
1222 if (attackerId != null && swipe.attackerId !== attackerId)
1223 { continue; }
1224 swipe.trackTarget = false;
1225 if (message.tileX != null)
1226 { swipe.tileX = message.tileX; }
1227 if (message.tileY != null)
1228 { swipe.tileY = message.tileY; }
1229 }
1230 }
1231
1232 spawnSkillLevelUp (entityId, payload)
1233 {
1234 const level = payload?.level | 0;
1235 if (level <= 0 || !payload?.icon)
1236 { return; }
1237 this.skillLevelFloats.push({
1238 entityId,
1239 level,
1240 icon: payload.icon,
1241 displayName: payload.displayName ?? payload.skillId ?? "",
1242 started: performance.now()
1243 });
1244 }
1245
1246 setAppearance (payload)
1247 {
1248 const existing = this.entities.get(payload.entityId);
1249 if (!existing)
1250 { return; }
1251 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
1252 if (payload.lightIntensity != null)
1253 { existing.lightIntensity = Number(payload.lightIntensity) || 1; }
1254 if (payload.visualScale != null)
1255 { existing.visualScale = Number(payload.visualScale) || 1; }
1256 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
1257 this.#placeEntity(existing);
1258 }
1259
1260 /**
1261 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
1262 * world, unlit) into an offscreen FBO, crop the top square, and return a
1263 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
1264 * @param {number} entityId
1265 * @param {{ size?: number }} [options]
1266 * @returns {HTMLCanvasElement | null}
1267 */
1268 captureEntityPortrait (entityId, { size = 64 } = {})
1269 {
1270 const entity = this.entities.get(entityId);
1271 const body = entity?.object?.renderer?.sprite;
1272 const glCtx = this.scene?.glContext;
1273 const gl = glCtx?.gl;
1274 if (!entity || !body || !gl)
1275 { return null; }
1276
1277 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
1278 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
1279 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
1280 { return null; }
1281
1282 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
1283 const prevViewport = gl.getParameter(gl.VIEWPORT);
1284 const prevW = glCtx._lastWidth;
1285 const prevH = glCtx._lastHeight;
1286 const prevBlend = gl.isEnabled(gl.BLEND);
1287
1288 try
1289 {
1290 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
1291 glCtx._lastWidth = frameW;
1292 glCtx._lastHeight = frameH;
1293 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
1294 gl.viewport(0, 0, frameW, frameH);
1295 gl.enable(gl.BLEND);
1296 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1297 gl.clearColor(0, 0, 0, 0);
1298 gl.clear(gl.COLOR_BUFFER_BIT);
1299
1300 const pivotX = frameW * 0.5;
1301 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
1302 this._portraitBodyMap = body.g_image ?? null;
1303 this._portraitTightFitEntity = entity;
1304 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
1305
1306 const overlays = entity.overlays ?? [];
1307 const tints = entity.overlayTints ?? [];
1308 const dualTints = entity.overlayDualTints ?? [];
1309 const tight = entity.overlayTightFit ?? [];
1310 for (let index = 0; index < overlays.length; index++)
1311 {
1312 this.#drawPortraitLayer(
1313 glCtx,
1314 overlays[index],
1315 pivotX,
1316 pivotY,
1317 tints[index] ?? null,
1318 !!tight[index],
1319 dualTints[index] ?? null
1320 );
1321 }
1322 this._portraitBodyMap = null;
1323 this._portraitTightFitEntity = null;
1324
1325 const pixels = this._portrait.pixels;
1326 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
1327 }
1328 finally
1329 {
1330 glCtx._lastWidth = prevW;
1331 glCtx._lastHeight = prevH;
1332 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
1333 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
1334 if (!prevBlend)
1335 { gl.disable(gl.BLEND); }
1336 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
1337 }
1338
1339 return this.#portraitPixelsToCanvas(frameW, frameH, size);
1340 }
1341
1342 #ensurePortraitTarget (gl, width, height)
1343 {
1344 const prev = this._portrait;
1345 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
1346 { return true; }
1347 if (prev?.fb)
1348 { gl.deleteFramebuffer(prev.fb); }
1349 if (prev?.tex)
1350 { gl.deleteTexture(prev.tex); }
1351
1352 const tex = gl.createTexture();
1353 gl.bindTexture(gl.TEXTURE_2D, tex);
1354 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
1355 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
1356 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
1357 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
1358 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
1359
1360 const fb = gl.createFramebuffer();
1361 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
1362 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
1363 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
1364 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
1365 if (status !== gl.FRAMEBUFFER_COMPLETE)
1366 {
1367 gl.deleteFramebuffer(fb);
1368 gl.deleteTexture(tex);
1369 this._portrait = null;
1370 return false;
1371 }
1372 this._portrait = {
1373 fb,
1374 tex,
1375 w: width,
1376 h: height,
1377 pixels: new Uint8Array(width * height * 4),
1378 scratch: document.createElement("canvas")
1379 };
1380 return true;
1381 }
1382
1383 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
1384 {
1385 const sprite = object?.renderer?.sprite;
1386 if (!sprite?.g_image)
1387 { return; }
1388 const subImage = object.renderer.subImage | 0;
1389 const height = sprite.height || SPRITE_SIZE_PX;
1390 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
1391 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
1392 const tint = tintColor ? normalizeRgb(tintColor) : null;
1393 let shader = glCtx.defaultShader;
1394 let uniforms = null;
1395 let secondaryHtml = null;
1396
1397 const bodyHtml = this._portraitBodyMap;
1398 const portraitEntity = this._portraitTightFitEntity;
1399 const maskUniforms = tightFit && portraitEntity
1400 ? this.#tightFitMaskUniforms(object, portraitEntity)
1401 : null;
1402 if (dualTint)
1403 {
1404 const shaft = normalizeRgb(dualTint.shaft);
1405 const tip = normalizeRgb(dualTint.tip);
1406 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
1407 shader = getDualTintLitSpriteShader();
1408 uniforms = {
1409 u_darkness: 0,
1410 u_strength: 0,
1411 u_flashColor: FLASH_COLOR_DAMAGE,
1412 u_wade: 0,
1413 u_spriteHeight: height,
1414 u_shaftTint: [shaft.r, shaft.g, shaft.b],
1415 u_tipTint: [tip.r, tip.g, tip.b],
1416 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
1417 u_hasCoat: coat ? 1 : 0
1418 };
1419 }
1420 else if (tightFit && bodyHtml && maskUniforms)
1421 {
1422 secondaryHtml = bodyHtml;
1423 if (tint)
1424 {
1425 shader = getTightFitTintLitSpriteShader();
1426 uniforms = {
1427 u_darkness: 0,
1428 u_strength: 0,
1429 u_flashColor: FLASH_COLOR_DAMAGE,
1430 u_wade: 0,
1431 u_spriteHeight: height,
1432 u_useTint: 1,
1433 u_tintColor: [tint.r, tint.g, tint.b],
1434 ...maskUniforms
1435 };
1436 }
1437 else
1438 {
1439 shader = getTightFitLitSpriteShader();
1440 uniforms = {
1441 u_darkness: 0,
1442 u_strength: 0,
1443 u_flashColor: FLASH_COLOR_DAMAGE,
1444 u_wade: 0,
1445 u_spriteHeight: height,
1446 ...maskUniforms
1447 };
1448 }
1449 }
1450 else if (tint)
1451 {
1452 shader = getTintLitSpriteShader();
1453 uniforms = {
1454 u_darkness: 0,
1455 u_strength: 0,
1456 u_flashColor: FLASH_COLOR_DAMAGE,
1457 u_wade: 0,
1458 u_spriteHeight: height,
1459 u_useTint: 1,
1460 u_tintColor: [tint.r, tint.g, tint.b]
1461 };
1462 }
1463 else
1464 {
1465 shader = getSpriteLightingShader();
1466 uniforms = {
1467 u_darkness: 0,
1468 u_strength: 0,
1469 u_flashColor: FLASH_COLOR_DAMAGE,
1470 u_wade: 0,
1471 u_spriteHeight: height
1472 };
1473 }
1474
1475 glCtx.drawSprite({
1476 texture: glCtx.getTexture(sprite.g_image),
1477 x: center.x,
1478 y: center.y,
1479 w: draw.w,
1480 h: draw.h,
1481 rotationDeg: 0,
1482 mirrorX: false,
1483 mirrorY: false,
1484 alpha: 1,
1485 uvRect: sprite.getUvRect(subImage),
1486 shader,
1487 uniforms,
1488 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
1489 lights: null
1490 });
1491 }
1492
1493 #portraitPixelsToCanvas (frameW, frameH, size)
1494 {
1495 const pixels = this._portrait?.pixels;
1496 if (!pixels)
1497 { return null; }
1498 const scratch = this._portrait.scratch;
1499 scratch.width = frameW;
1500 scratch.height = frameH;
1501 const sctx = scratch.getContext("2d");
1502 const imageData = sctx.createImageData(frameW, frameH);
1503 // WebGL y=0 is bottom — flip to top-down image order.
1504 for (let y = 0; y < frameH; y++)
1505 {
1506 const src = (frameH - 1 - y) * frameW * 4;
1507 const dst = y * frameW * 4;
1508 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
1509 }
1510 sctx.putImageData(imageData, 0, 0);
1511
1512 const crop = Math.min(frameW, frameH);
1513 const out = document.createElement("canvas");
1514 out.width = size;
1515 out.height = size;
1516 const octx = out.getContext("2d");
1517 octx.imageSmoothingEnabled = false;
1518 octx.clearRect(0, 0, size, size);
1519 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
1520 return out;
1521 }
1522
1523 upsertGroundItem (payload)
1524 {
1525 const size = this.tileSize();
1526 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1527 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
1528 const spriteName = potion
1529 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
1530 : (payload.sprite ?? itemSpriteNameForStack({
1531 itemId: payload.itemId,
1532 instance: payload.instance,
1533 quantity: payload.quantity
1534 }));
1535 let item = this.groundItems.get(payload.groundItemId);
1536 if (!item)
1537 {
1538 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
1539 this.scene.addObject(object);
1540 item = { object };
1541 this.groundItems.set(payload.groundItemId, item);
1542 }
1543 else if (item.object?.renderer && this.game.images[spriteName])
1544 { item.object.renderer.sprite = this.game.images[spriteName]; }
1545 item.groundItemId = payload.groundItemId;
1546 item.tileX = payload.tileX;
1547 item.tileY = payload.tileY;
1548 item.itemId = payload.itemId;
1549 item.quantity = payload.quantity;
1550 item.displayName = payload.displayName;
1551 item.sprite = spriteName;
1552 item.instance = payload.instance ?? null;
1553 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
1554 const def = itemDefinition(payload.itemId);
1555 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
1556 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
1557 if (item.object?.renderer && itemMaxCharges(def) != null)
1558 { item.object.renderer.setSubImage?.(chargeSpriteFrameIndex(stack)); }
1559 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1560 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
1561 }
1562
1563 despawnGroundItem (groundItemId)
1564 {
1565 const item = this.groundItems.get(groundItemId);
1566 if (!item)
1567 { return; }
1568 item.object?.destroy();
1569 this.groundItems.delete(groundItemId);
1570 }
1571
1572 groundItemAtTile (tileX, tileY)
1573 {
1574 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1575 }
1576
1577 groundItemsAtTile (tileX, tileY)
1578 {
1579 const items = [];
1580 for (const item of this.groundItems.values())
1581 {
1582 if (item.tileX === tileX && item.tileY === tileY)
1583 { items.push(item); }
1584 }
1585 return items;
1586 }
1587
1588 entitiesAtTile (tileX, tileY, options = {})
1589 {
1590 const includePrevious = !!options.includePrevious;
1591 const matches = [];
1592 for (const entity of this.entities.values())
1593 {
1594 if (entity.tileX === tileX && entity.tileY === tileY)
1595 {
1596 matches.push(entity);
1597 continue;
1598 }
1599 if (
1600 includePrevious
1601 && entity.lerpStarted != null
1602 && entity.previousTileX === tileX
1603 && entity.previousTileY === tileY
1604 )
1605 { matches.push(entity); }
1606 }
1607 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1608 return matches;
1609 }
1610
1611 setZoom (zoom, limits = { min: 2, max: 4 })
1612 {
1613 const min = limits.min ?? 1;
1614 const max = limits.max ?? 4;
1615 this.zoom = Math.min(max, Math.max(min, zoom));
1616 for (const snapshot of this.chunks.values())
1617 { this.#relayoutChunk(snapshot); }
1618 const size = this.tileSize();
1619 for (const entity of this.entities.values())
1620 {
1621 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1622 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1623 entity.fromX = entity.visualX;
1624 entity.fromY = entity.visualY;
1625 entity.targetX = entity.visualX;
1626 entity.targetY = entity.visualY;
1627 entity.lerpStarted = null;
1628 this.#placeEntity(entity);
1629 }
1630 for (const item of this.groundItems.values())
1631 {
1632 const pivot = tilePivot(item.tileX, item.tileY, size);
1633 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1634 }
1635 this.#rebuildAllEdges();
1636 this.#relayoutEditorSpawners();
1637 this.#relayoutSpawnRangeHighlight();
1638 this.#relayoutSpellTargetHighlight();
1639 // Play: recenter + refresh cull flags with the new tile size immediately.
1640 // Editor sets the camera via frameNeighborhood after setZoom — call refreshViewport there.
1641 if (this.followPlayer)
1642 { this.refreshViewport(); }
1643 }
1644
1645 /** Recenter (when following) and refresh off-screen cull flags after zoom/layout. */
1646 refreshViewport ()
1647 {
1648 this.#centerCamera();
1649 this.#syncYSortOrigin();
1650 this.#refreshDepthLayers();
1651 this.#cullOffscreenDrawables();
1652 }
1653
1654 tileSize ()
1655 {
1656 return SPRITE_SIZE_PX * this.zoom;
1657 }
1658
1659 screenToTile (mouseX, mouseY)
1660 {
1661 const size = this.tileSize();
1662 const worldX = mouseX - this.scene.cameraPosition.x;
1663 const worldY = mouseY - this.scene.cameraPosition.y;
1664 return {
1665 tileX: Math.floor(worldX / size),
1666 tileY: Math.floor(worldY / size)
1667 };
1668 }
1669
1670 entityAtScreen (mouseX, mouseY)
1671 {
1672 let best = null;
1673 let bestLayer = -Infinity;
1674 for (const entity of this.entities.values())
1675 {
1676 const box = this.#entityScreenBox(entity);
1677 if (!box)
1678 { continue; }
1679 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1680 {
1681 const layer = entity.object?.layer ?? 0;
1682 if (layer >= bestLayer)
1683 {
1684 best = entity;
1685 bestLayer = layer;
1686 }
1687 }
1688 }
1689 return best;
1690 }
1691
1692 nametagAnchor (entity)
1693 {
1694 const box = this.#entityScreenBox(entity);
1695 if (!box)
1696 { return null; }
1697 return { x: (box.left + box.right) / 2, y: box.top };
1698 }
1699
1700 #entityScreenBox (entity)
1701 {
1702 const object = entity?.object;
1703 if (!object)
1704 { return null; }
1705 const size = object.transform.size;
1706 const x = object.transform.position.x + this.scene.cameraPosition.x;
1707 const y = object.transform.position.y + this.scene.cameraPosition.y;
1708 return {
1709 left: x - size.x / 2,
1710 right: x + size.x / 2,
1711 top: y - size.y / 2,
1712 bottom: y + size.y / 2
1713 };
1714 }
1715
1716 update (deltaTime)
1717 {
1718 const now = performance.now();
1719 const size = this.tileSize();
1720 this.#refreshStackTargets();
1721 for (const entity of this.entities.values())
1722 {
1723 const target = entity.targetX != null && entity.targetY != null
1724 ? { x: entity.targetX, y: entity.targetY }
1725 : tilePivot(entity.tileX, entity.tileY, size);
1726 if (entity.lerpStarted != null)
1727 {
1728 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1729 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1730 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1731 if (t >= 1)
1732 {
1733 entity.lerpStarted = null;
1734 entity.previousTileX = null;
1735 entity.previousTileY = null;
1736 }
1737 }
1738 else
1739 {
1740 entity.visualX = target.x;
1741 entity.visualY = target.y;
1742 }
1743 this.#updateStackOffset(entity, now);
1744 this.#updateShove(entity, now, size);
1745 this.#expireGatherToolOverlay(entity, now);
1746 }
1747
1748 // The y-sort origin must settle before any layer is computed this frame,
1749 // otherwise entities and blocks end up sorted against different origins.
1750 // It only moves when the view crosses a chunk row; the static world then
1751 // needs one re-layer pass, and nothing at all on every other frame.
1752 this.#centerCamera();
1753 if (this.#syncYSortOrigin())
1754 { this.#refreshDepthLayers(); }
1755
1756 for (const entity of this.entities.values())
1757 { this.#placeEntity(entity, now); }
1758
1759 this.#updateSwipes(now);
1760 this.#updateDamageNumbers(now);
1761 this.#updateSkillLevelFloats(now);
1762 this.#relayoutSpellTargetHighlight();
1763 this.#cullOffscreenDrawables();
1764 this.#updateShade(deltaTime);
1765 }
1766
1767 /**
1768 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1769 * Stable assignment by entityId; free-flight entities stay unshifted.
1770 */
1771 #refreshStackTargets ()
1772 {
1773 const byTile = new Map();
1774 for (const entity of this.entities.values())
1775 {
1776 if (entity.freeFlight || entity.dying)
1777 {
1778 entity.stackTargetX = 0;
1779 entity.stackTargetY = 0;
1780 continue;
1781 }
1782 const key = `${entity.tileX},${entity.tileY}`;
1783 let list = byTile.get(key);
1784 if (!list)
1785 {
1786 list = [];
1787 byTile.set(key, list);
1788 }
1789 list.push(entity);
1790 }
1791 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1792 for (const list of byTile.values())
1793 {
1794 if (list.length <= 1)
1795 {
1796 for (const entity of list)
1797 {
1798 entity.stackTargetX = 0;
1799 entity.stackTargetY = 0;
1800 }
1801 continue;
1802 }
1803 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1804 const n = list.length;
1805 for (let i = 0; i < n; i++)
1806 {
1807 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1808 list[i].stackTargetX = Math.cos(angle) * radius;
1809 list[i].stackTargetY = Math.sin(angle) * radius;
1810 }
1811 }
1812 }
1813
1814 #updateStackOffset (entity, now)
1815 {
1816 const tx = entity.stackTargetX ?? 0;
1817 const ty = entity.stackTargetY ?? 0;
1818 const cx = entity.stackOffsetX ?? 0;
1819 const cy = entity.stackOffsetY ?? 0;
1820 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1821 {
1822 entity.stackFromX = cx;
1823 entity.stackFromY = cy;
1824 entity.stackLerpToX = tx;
1825 entity.stackLerpToY = ty;
1826 entity.stackLerpStarted = now;
1827 }
1828 if (entity.stackLerpStarted == null)
1829 {
1830 entity.stackOffsetX = tx;
1831 entity.stackOffsetY = ty;
1832 return;
1833 }
1834 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1835 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1836 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1837 if (t >= 1)
1838 {
1839 entity.stackOffsetX = tx;
1840 entity.stackOffsetY = ty;
1841 entity.stackLerpStarted = null;
1842 }
1843 }
1844
1845 #updateShove (entity, now, tileSize)
1846 {
1847 if (!entity.shove)
1848 {
1849 entity.shoveOffsetX = 0;
1850 entity.shoveOffsetY = 0;
1851 return;
1852 }
1853 const elapsed = now - entity.shove.started;
1854 const t = Math.min(1, elapsed / entity.shove.durationMs);
1855 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1856 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1857 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1858 const dist = Math.hypot(dx, dy) || 1;
1859 const ux = dx / dist;
1860 const uy = dy / dist;
1861 let phase;
1862 if (t < 0.45)
1863 { phase = t / 0.45; }
1864 else
1865 { phase = 1 - (t - 0.45) / 0.55; }
1866 entity.shoveOffsetX = ux * maxDist * phase;
1867 entity.shoveOffsetY = uy * maxDist * phase;
1868 if (t >= 1)
1869 { entity.shove = null; }
1870 }
1871
1872 spawnCombatSwing (payload)
1873 {
1874 const attacker = this.entities.get(payload.attackerId);
1875 const target = this.entities.get(payload.targetId);
1876 if (!attacker || !target)
1877 { return; }
1878 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1879 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1880 const tx = target.visualX + (target.stackOffsetX ?? 0);
1881 const ty = target.visualY + (target.stackOffsetY ?? 0);
1882 this.#applyShove(attacker, tx, ty);
1883 const midX = (ax + tx) / 2;
1884 const midY = (ay + ty) / 2;
1885 const sortY = Math.max(ay, ty) + 0.02;
1886 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1887 const jitter = (Math.random() * 2 - 1) * MELEE_SWIPE_JITTER_DEG;
1888 const spriteName = "fx:melee-swipe:melee-swipe";
1889 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1890 if (object.transform)
1891 { object.transform.rotation = angle + jitter; }
1892 if (object.renderer)
1893 { object.renderer.alpha = 1; }
1894 this.scene.addObject(object);
1895 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1896 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1897 const started = performance.now();
1898 this.swipes.push({
1899 object,
1900 until: started + MELEE_SWIPE_MS,
1901 started,
1902 durationMs: MELEE_SWIPE_MS,
1903 sortY,
1904 fadeOpacity: true,
1905 fromTileX: payload.fromTileX,
1906 fromTileY: payload.fromTileY,
1907 tileX: payload.tileX,
1908 tileY: payload.tileY
1909 });
1910 }
1911
1912 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1913 spawnGatherSwing (payload)
1914 {
1915 const attacker = this.entities.get(payload.attackerId);
1916 if (!attacker)
1917 { return; }
1918 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1919 this.#applyShove(attacker, pivot.x, pivot.y);
1920 if (payload.toolItemId != null)
1921 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1922 }
1923
1924 #applyShove (entity, targetVisualX, targetVisualY)
1925 {
1926 entity.shove = {
1927 startVisualX: entity.visualX,
1928 startVisualY: entity.visualY,
1929 targetVisualX,
1930 targetVisualY,
1931 started: performance.now(),
1932 durationMs: SHOVE_MS
1933 };
1934 }
1935
1936 #applyShoveInDirection (entity, dirX, dirY)
1937 {
1938 const len = Math.hypot(dirX, dirY);
1939 if (len < 1e-4)
1940 { return; }
1941 const tileSize = this.tileSize();
1942 const ux = dirX / len;
1943 const uy = dirY / len;
1944 this.#applyShove(
1945 entity,
1946 entity.visualX + ux * tileSize,
1947 entity.visualY + uy * tileSize
1948 );
1949 }
1950
1951 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1952 spawnPhysicalProjectileFx (payload)
1953 {
1954 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1955 const image = this.game.images[spriteName];
1956 if (!image)
1957 { return; }
1958 const dualTint = this.#dualTintFromPayload(payload);
1959 const fromPivot = this.#projectileLaunchPoint(
1960 payload.attackerId ?? null,
1961 payload.fromTileX,
1962 payload.fromTileY
1963 );
1964 const toPivot = this.#projectileAimPoint(
1965 payload.targetId ?? null,
1966 payload.tileX,
1967 payload.tileY
1968 );
1969 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1970 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1971 const object = new GameObject(0, 0, image, SORT_FX);
1972 if (object.transform)
1973 { object.transform.rotation = angle; }
1974 this.scene.addObject(object);
1975 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1976 this.#applyPhysicalCombatFxDarkness(
1977 object,
1978 payload.fromTileX,
1979 payload.fromTileY,
1980 payload.tileX,
1981 payload.tileY,
1982 dualTint
1983 );
1984 const started = performance.now();
1985 const durationMs = payload.durationMs ?? 400;
1986 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1987 this.swipes.push({
1988 object,
1989 until: started + durationMs,
1990 started,
1991 durationMs,
1992 lerp: true,
1993 dualTint,
1994 fromTileX: payload.fromTileX,
1995 fromTileY: payload.fromTileY,
1996 tileX: payload.tileX,
1997 tileY: payload.tileY,
1998 attackerId: payload.attackerId ?? null,
1999 targetId: payload.targetId ?? null,
2000 trackTarget,
2001 onImpact: null
2002 });
2003 }
2004
2005 /** Bloom-layer spell projectiles — magenta-tinted, unique art per spell. */
2006 spawnSpellProjectileFx (payload)
2007 {
2008 const spellId = payload.spellId ?? null;
2009 const def = spellId != null ? spellDefinition(spellId) : null;
2010 const spriteName = payload.sprite
2011 ?? def?.projectileSprite
2012 ?? "fx:projectile:spell-none-1-mana-bullet";
2013 const image = this.game.images[spriteName];
2014 if (!image)
2015 { return; }
2016 const tint = spellProjectileTint(def?.element);
2017 const fromPivot = this.#projectileLaunchPoint(
2018 payload.casterId ?? null,
2019 payload.fromTileX,
2020 payload.fromTileY
2021 );
2022 const toPivot = this.#projectileAimPoint(
2023 payload.targetId ?? null,
2024 payload.tileX,
2025 payload.tileY
2026 );
2027 // Spell casts push the caster visually toward the spell's target.
2028 // (Presentation only; server authority remains combat-resolution.)
2029 const caster = payload.casterId != null
2030 ? this.entities.get(payload.casterId)
2031 : null;
2032 if (caster && !caster.dying)
2033 {
2034 const casterPivotX = caster.visualX + (caster.stackOffsetX ?? 0);
2035 const casterPivotY = caster.visualY + (caster.stackOffsetY ?? 0);
2036 this.#applyShoveInDirection(caster, toPivot.x - casterPivotX, toPivot.y - casterPivotY);
2037 }
2038 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
2039 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
2040 const object = new GameObject(0, 0, image, SORT_FX);
2041 object.renderer.layer = RENDER_LAYER_BLOOM;
2042 this.#markUnlit(object);
2043 this.#syncUnlitTintSprite(object, tint);
2044 if (object.transform)
2045 { object.transform.rotation = angle; }
2046 this.scene.addObject(object);
2047 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
2048 const started = performance.now();
2049 const durationMs = payload.durationMs ?? 2000;
2050 this.swipes.push({
2051 object,
2052 until: started + durationMs,
2053 started,
2054 durationMs,
2055 lerp: true,
2056 spellProjectile: true,
2057 tint,
2058 fromTileX: payload.fromTileX,
2059 fromTileY: payload.fromTileY,
2060 tileX: payload.tileX,
2061 tileY: payload.tileY,
2062 attackerId: payload.casterId ?? null,
2063 targetId: payload.targetId ?? null,
2064 trackTarget: payload.targetId != null,
2065 onImpact: null
2066 });
2067 }
2068
2069 spawnSpellFizzleFx (_payload)
2070 {
2071 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
2072 }
2073
2074 /**
2075 * Authoritative Light-spell tile light from the server.
2076 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
2077 */
2078 setSpellLight (payload)
2079 {
2080 const key = `${payload.tileX},${payload.tileY}`;
2081 this.spellLights.set(key, {
2082 tileX: payload.tileX,
2083 tileY: payload.tileY,
2084 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
2085 range: payload.rangeTiles ?? 6,
2086 intensity: payload.intensity ?? 0.88
2087 });
2088 this.#invalidateNeighborLightmapCaches(
2089 Math.floor(payload.tileX / CHUNK_SIZE),
2090 Math.floor(payload.tileY / CHUNK_SIZE)
2091 );
2092 }
2093
2094 removeSpellLight (payload)
2095 {
2096 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
2097 this.#invalidateNeighborLightmapCaches(
2098 Math.floor(payload.tileX / CHUNK_SIZE),
2099 Math.floor(payload.tileY / CHUNK_SIZE)
2100 );
2101 }
2102
2103 setSpellDark (payload)
2104 {
2105 const key = `${payload.tileX},${payload.tileY}`;
2106 this.spellDarks.set(key, {
2107 tileX: payload.tileX,
2108 tileY: payload.tileY,
2109 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
2110 range: payload.rangeTiles ?? 6,
2111 intensity: payload.intensity ?? 0.88
2112 });
2113 this.#invalidateNeighborLightmapCaches(
2114 Math.floor(payload.tileX / CHUNK_SIZE),
2115 Math.floor(payload.tileY / CHUNK_SIZE)
2116 );
2117 }
2118
2119 removeSpellDark (payload)
2120 {
2121 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
2122 this.#invalidateNeighborLightmapCaches(
2123 Math.floor(payload.tileX / CHUNK_SIZE),
2124 Math.floor(payload.tileY / CHUNK_SIZE)
2125 );
2126 }
2127
2128 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
2129 {
2130 this.dynamicLights.push({
2131 tileX: Math.floor(worldX),
2132 tileY: Math.floor(worldY),
2133 range: radiusTiles,
2134 intensity,
2135 until: performance.now() + durationMs
2136 });
2137 }
2138
2139 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
2140 {
2141 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2142 if (!snapshot)
2143 { return; }
2144 const index = localY * CHUNK_SIZE + localX;
2145 if (ground !== undefined)
2146 { snapshot.grounds[index] = ground; }
2147 if (block !== undefined)
2148 { snapshot.blocks[index] = block; }
2149 if (light !== undefined)
2150 { snapshot.light[index] = light; }
2151 if (ground !== undefined || block !== undefined)
2152 {
2153 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
2154 { snapshot.occlusion = bakeChunkOcclusion(snapshot); }
2155 else
2156 { snapshot.occlusion[index] = tileLightOcclusionAt(snapshot.grounds, snapshot.blocks, localX, localY); }
2157 }
2158 const tileX = chunkX * CHUNK_SIZE + localX;
2159 const tileY = chunkY * CHUNK_SIZE + localY;
2160 if (block !== undefined)
2161 {
2162 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
2163 this.#drawTile(tileX, tileY);
2164 return;
2165 }
2166 this.#scheduleChunkRebuild(snapshot);
2167 if (ground !== undefined)
2168 { this.#drawTile(tileX, tileY); }
2169 }
2170
2171 /**
2172 * Editor-only mob markers for authored spawners (invisible during play).
2173 * Humanoid / town guard / CE show body + equipment overlays.
2174 * @param {number} chunkX
2175 * @param {number} chunkY
2176 * @param {Array<{ localX: number, localY: number, config?: object }>} spawners
2177 * @param {(mobTypeId: number) => string} resolveSprite
2178 */
2179 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
2180 {
2181 const prefix = `${chunkX},${chunkY}:`;
2182 for (const [key, entry] of [...this.editorSpawners.entries()])
2183 {
2184 if (!key.startsWith(prefix))
2185 { continue; }
2186 this.#destroyEditorSpawnerEntry(entry);
2187 this.editorSpawners.delete(key);
2188 }
2189 const size = this.tileSize();
2190 for (const spawner of spawners ?? [])
2191 {
2192 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
2193 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
2194 const layers = layersFromSpawnerConfig(spawner.config);
2195 const bodySpriteName = layers?.[0]?.sprite
2196 ?? resolveSprite?.(spawner.config?.mobTypeId)
2197 ?? null;
2198 if (!bodySpriteName)
2199 { continue; }
2200 const key = `${prefix}${spawner.localX},${spawner.localY}`;
2201 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
2202 if (!object)
2203 { continue; }
2204 object.renderer.alpha = 0.85;
2205 const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2206 if (bodyTint)
2207 { this.#syncUnlitTintSprite(object, bodyTint); }
2208 else
2209 { this.#markUnlit(object); }
2210 const overlays = [];
2211 for (const layer of layers?.slice(1) ?? [])
2212 {
2213 const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY);
2214 if (!overlay)
2215 { continue; }
2216 overlay.renderer.alpha = 0.85;
2217 this.#applyEditorSpawnerOverlayLook(overlay, layer);
2218 overlays.push(overlay);
2219 }
2220 const pivot = tilePivot(tileX, tileY, size);
2221 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
2222 for (let i = 0; i < overlays.length; i++)
2223 {
2224 this.#placePivoted(
2225 overlays[i],
2226 pivot.x,
2227 pivot.y,
2228 pivot.y + 0.05 + 0.001 * (i + 1),
2229 SORT_ENTITY
2230 );
2231 }
2232 this.editorSpawners.set(key, {
2233 object,
2234 overlays,
2235 tileX,
2236 tileY,
2237 spriteName: bodySpriteName
2238 });
2239 }
2240 }
2241
2242 #destroyEditorSpawnerEntry (entry)
2243 {
2244 entry?.object?.destroy();
2245 for (const overlay of entry?.overlays ?? [])
2246 { overlay?.destroy(); }
2247 }
2248
2249 #applyEditorSpawnerOverlayLook (overlay, layer)
2250 {
2251 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2252 const dualTint = layerDef?.iconTintFromTier
2253 ? null
2254 : (layer.itemId != null
2255 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2256 : null);
2257 const tint = layer.tint
2258 ? normalizeRgb(layer.tint)
2259 : (dualTint
2260 ? null
2261 : (layerDef?.iconTintFromTier
2262 ? resolveItemTint({ itemId: layer.itemId }, layerDef)
2263 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)));
2264 if (dualTint)
2265 {
2266 overlay._lit = true;
2267 this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false);
2268 return;
2269 }
2270 if (tint)
2271 {
2272 this.#syncUnlitTintSprite(overlay, tint);
2273 return;
2274 }
2275 this.#markUnlit(overlay);
2276 }
2277
2278 clearEditorSpawners ()
2279 {
2280 for (const entry of this.editorSpawners.values())
2281 { this.#destroyEditorSpawnerEntry(entry); }
2282 this.editorSpawners.clear();
2283 }
2284
2285 #relayoutEditorSpawners ()
2286 {
2287 const size = this.tileSize();
2288 for (const entry of this.editorSpawners.values())
2289 {
2290 if (!entry.object)
2291 { continue; }
2292 const pivot = tilePivot(entry.tileX, entry.tileY, size);
2293 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
2294 const overlays = entry.overlays ?? [];
2295 for (let i = 0; i < overlays.length; i++)
2296 {
2297 this.#placePivoted(
2298 overlays[i],
2299 pivot.x,
2300 pivot.y,
2301 pivot.y + 0.05 + 0.001 * (i + 1),
2302 SORT_ENTITY
2303 );
2304 }
2305 }
2306 }
2307
2308 /**
2309 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
2310 */
2311 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
2312 {
2313 const spawnRadius = Math.max(0, spawnRange | 0);
2314 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
2315 if (this.spawnRangeHighlight
2316 && this.wanderRangeHighlight
2317 && this.spawnRangeHighlight.tileX === tileX
2318 && this.spawnRangeHighlight.tileY === tileY
2319 && this.spawnRangeHighlight.range === spawnRadius
2320 && this.wanderRangeHighlight.range === wanderRadius)
2321 {
2322 this.#relayoutSpawnRangeHighlight();
2323 return;
2324 }
2325 this.clearSpawnRangeHighlight();
2326 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
2327 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
2328 if (wanderObject)
2329 {
2330 this.#markUnlit(wanderObject);
2331 wanderObject.renderer.alpha = 1;
2332 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
2333 }
2334 if (spawnObject)
2335 {
2336 this.#markUnlit(spawnObject);
2337 spawnObject.renderer.alpha = 1;
2338 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
2339 }
2340 this.#relayoutSpawnRangeHighlight();
2341 }
2342
2343 clearSpawnRangeHighlight ()
2344 {
2345 this.spawnRangeHighlight?.object?.destroy();
2346 this.wanderRangeHighlight?.object?.destroy();
2347 this.spawnRangeHighlight = null;
2348 this.wanderRangeHighlight = null;
2349 }
2350
2351 setSpellTargetHighlight (tileX, tileY, inRange = true)
2352 {
2353 if (
2354 this.spellTargetHighlight
2355 && this.spellTargetHighlight.mode === "tile"
2356 && this.spellTargetHighlight.tileX === tileX
2357 && this.spellTargetHighlight.tileY === tileY
2358 && this.spellTargetHighlight.inRange === inRange
2359 )
2360 {
2361 this.#relayoutSpellTargetHighlight();
2362 return;
2363 }
2364 this.clearSpellTargetHighlight();
2365 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
2366 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2367 if (!object)
2368 { return; }
2369 this.#markUnlit(object);
2370 object.renderer.alpha = 1;
2371 this.spellTargetHighlight = {
2372 mode: "tile",
2373 object,
2374 tileX,
2375 tileY,
2376 entityId: null,
2377 inRange,
2378 spriteName
2379 };
2380 this.#relayoutSpellTargetHighlight();
2381 }
2382
2383 /** Outline box around a living entity (mob / player) for entity-target spells. */
2384 setSpellEntityTargetHighlight (entityId, inRange = true)
2385 {
2386 const id = entityId | 0;
2387 if (
2388 this.spellTargetHighlight
2389 && this.spellTargetHighlight.mode === "entity"
2390 && this.spellTargetHighlight.entityId === id
2391 && this.spellTargetHighlight.inRange === inRange
2392 )
2393 {
2394 this.#relayoutSpellTargetHighlight();
2395 return;
2396 }
2397 this.clearSpellTargetHighlight();
2398 if (!this.entities.has(id))
2399 { return; }
2400 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
2401 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
2402 if (!object)
2403 { return; }
2404 this.#markUnlit(object);
2405 object.renderer.alpha = 1;
2406 this.spellTargetHighlight = {
2407 mode: "entity",
2408 object,
2409 tileX: 0,
2410 tileY: 0,
2411 entityId: id,
2412 inRange,
2413 spriteName
2414 };
2415 this.#relayoutSpellTargetHighlight();
2416 }
2417
2418 clearSpellTargetHighlight ()
2419 {
2420 this.spellTargetHighlight?.object?.destroy();
2421 this.spellTargetHighlight = null;
2422 }
2423
2424 #relayoutSpellTargetHighlight ()
2425 {
2426 const highlight = this.spellTargetHighlight;
2427 if (!highlight?.object)
2428 { return; }
2429 if (highlight.mode === "entity")
2430 {
2431 const entity = this.entities.get(highlight.entityId);
2432 if (!entity?.object)
2433 {
2434 this.clearSpellTargetHighlight();
2435 return;
2436 }
2437 const pad = this.tileSize() * 0.12;
2438 const src = entity.object.transform;
2439 highlight.object.transform.position.x = src.position.x;
2440 highlight.object.transform.position.y = src.position.y;
2441 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
2442 this.#setLayer(highlight.object, LAYER_EDGE - 1);
2443 highlight.tileX = entity.tileX;
2444 highlight.tileY = entity.tileY;
2445 return;
2446 }
2447 const size = this.tileSize();
2448 const left = highlight.tileX * size;
2449 const top = highlight.tileY * size;
2450 highlight.object.transform.position.x = left + size / 2;
2451 highlight.object.transform.position.y = top + size / 2;
2452 highlight.object.transform.size = new vector(size, size);
2453 this.#setLayer(highlight.object, LAYER_EDGE - 1);
2454 }
2455
2456 #relayoutSpawnRangeHighlight ()
2457 {
2458 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
2459 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
2460 }
2461
2462 #layoutRangeOverlay (highlight, layer)
2463 {
2464 if (!highlight?.object)
2465 { return; }
2466 const size = this.tileSize();
2467 const side = (2 * highlight.range + 1) * size;
2468 const left = (highlight.tileX - highlight.range) * size;
2469 const top = (highlight.tileY - highlight.range) * size;
2470 highlight.object.transform.position.x = left + side / 2;
2471 highlight.object.transform.position.y = top + side / 2;
2472 highlight.object.transform.size = new vector(side, side);
2473 this.#setLayer(highlight.object, layer);
2474 }
2475
2476 setTilePreview (tileX, tileY, override)
2477 {
2478 const next = { tileX, tileY, ...override };
2479 if (this.#previewEqual(this.preview, next))
2480 { return; }
2481 const previous = this.preview;
2482 this.preview = next;
2483 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2484 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2485 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
2486 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
2487 {
2488 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
2489 if (prevKey !== `${chunkX},${chunkY}`)
2490 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
2491 // Per-tile blocks (doors, campfires, …) are not in the atlas — refresh sprites.
2492 this.#drawTile(previous.tileX, previous.tileY);
2493 }
2494 this.#drawTile(tileX, tileY);
2495 }
2496
2497 clearTilePreview ()
2498 {
2499 if (!this.preview)
2500 { return; }
2501 const previous = this.preview;
2502 this.preview = null;
2503 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
2504 this.#scheduleChunkRebuild(snapshot);
2505 this.#drawTile(previous.tileX, previous.tileY);
2506 }
2507
2508 #lerpMs (gait)
2509 {
2510 const walk = this.settings.walkTilesPerSecond || 2;
2511 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
2512 return seconds * 1000;
2513 }
2514
2515 #centerCamera ()
2516 {
2517 if (!this.followPlayer)
2518 { return; }
2519 const local = this.entities.get(this.localEntityId);
2520 if (!local)
2521 { return; }
2522 const x = local.visualX + (local.stackOffsetX ?? 0);
2523 const y = local.visualY + (local.stackOffsetY ?? 0);
2524 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
2525 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
2526 }
2527
2528 /**
2529 * World Y the depth sort is measured against, so layers stay bounded
2530 * (absolute tileY×zoom otherwise overflows past LAYER_EDGE).
2531 *
2532 * Quantised to the chunk row under the viewport centre: every sprite's layer
2533 * is relative to this, so an origin that moved with the camera would mean
2534 * re-layering the whole world every frame. Chunks only span the static 5×5
2535 * ring, so relative sortY stays far inside LAYER_EDGE.
2536 *
2537 * @returns {boolean} whether the origin moved, i.e. callers must re-layer.
2538 */
2539 #syncYSortOrigin ()
2540 {
2541 const camY = this.scene.cameraPosition.y;
2542 const screenH = this.scene.real_size.y;
2543 const chunkPx = CHUNK_SIZE * this.tileSize();
2544 const origin = Math.floor((-camY + screenH / 2) / chunkPx) * chunkPx;
2545 if (origin === this.ySortOrigin)
2546 { return false; }
2547 this.ySortOrigin = origin;
2548 return true;
2549 }
2550
2551 /** Viewport-relative y-sort layer for world sprites. */
2552 #depthLayer (sortY, subOrder, flight = false)
2553 {
2554 const relative = sortY - (this.ySortOrigin ?? 0);
2555 return flight ? flightSortLayer(relative, subOrder) : ySortLayer(relative, subOrder);
2556 }
2557
2558 /**
2559 * Re-apply depth for every world sprite that is not repositioned each frame.
2560 * Their layer is relative to the y-sort origin, so a layer assigned once at
2561 * draw time goes stale as soon as that origin moves.
2562 *
2563 * Only run when {@link #syncYSortOrigin} reports a move (or after a zoom /
2564 * layout change) — entities carry their own per-frame layer via #placeEntity.
2565 */
2566 #refreshDepthLayers ()
2567 {
2568 const size = this.tileSize();
2569 for (const baked of this.bakedChunks.values())
2570 {
2571 const top = baked.chunkY * CHUNK_SIZE * size;
2572 const chunkPx = CHUNK_SIZE * size;
2573 for (let row = 0; row < CHUNK_SIZE; row++)
2574 {
2575 const rowY = top + row * size + size / 2;
2576 this.#setLayer(baked.blockObjects?.[row], this.#depthLayer(rowY, SORT_BLOCK));
2577 }
2578 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
2579 }
2580 // Unbaked tile sprites: tall blocks, doors and animated grounds.
2581 for (const objects of this.tiles.values())
2582 {
2583 if (!objects.block && !objects.blockBloom && !objects.groundBloom)
2584 { continue; }
2585 const pivotY = objects.tileY * size + size / 2;
2586 this.#setLayer(objects.block, this.#depthLayer(pivotY, objects.blockSort ?? SORT_ENTITY));
2587 this.#setLayer(objects.blockBloom, this.#depthLayer(pivotY, SORT_ENTITY));
2588 this.#setLayer(objects.groundBloom, this.#depthLayer(pivotY, LAYER_GROUND));
2589 }
2590 for (const item of this.groundItems.values())
2591 {
2592 this.#setLayer(
2593 item.object,
2594 this.#depthLayer(item.tileY * size + size / 2 - 0.01, SORT_BLOCK)
2595 );
2596 }
2597 // Lerping FX are re-placed in #updateSwipes; static ones need the refresh.
2598 for (const swipe of this.swipes)
2599 {
2600 if (swipe.lerp || swipe.sortY == null)
2601 { continue; }
2602 this.#setLayer(swipe.object, this.#depthLayer(swipe.sortY, SORT_FX));
2603 }
2604 for (const entry of this.editorSpawners.values())
2605 {
2606 const pivotY = entry.tileY * size + size / 2;
2607 this.#setLayer(entry.object, this.#depthLayer(pivotY + 0.05, SORT_ENTITY));
2608 const overlays = entry.overlays ?? [];
2609 for (let i = 0; i < overlays.length; i++)
2610 {
2611 this.#setLayer(
2612 overlays[i],
2613 this.#depthLayer(pivotY + 0.05 + 0.001 * (i + 1), SORT_ENTITY)
2614 );
2615 }
2616 }
2617 }
2618
2619 /**
2620 * World-pixel AABB of the screen, expanded for tall block sprites (zoom-aware).
2621 * Tiles fully outside this rect are not drawn.
2622 */
2623 #drawBounds ()
2624 {
2625 const pad = this.tileSize() * 2;
2626 const camX = this.scene.cameraPosition.x;
2627 const camY = this.scene.cameraPosition.y;
2628 const w = this.scene.real_size.x;
2629 const h = this.scene.real_size.y;
2630 return {
2631 left: -camX - pad,
2632 right: -camX + w + pad,
2633 top: -camY - pad,
2634 bottom: -camY + h + pad
2635 };
2636 }
2637
2638 #rectIntersects (left, top, right, bottom, bounds)
2639 {
2640 return right >= bounds.left
2641 && left <= bounds.right
2642 && bottom >= bounds.top
2643 && top <= bounds.bottom;
2644 }
2645
2646 #setRendererVisible (object, visible)
2647 {
2648 if (object?.renderer)
2649 { object.renderer.visible = !!visible; }
2650 }
2651
2652 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
2653 #cullOffscreenDrawables ()
2654 {
2655 const bounds = this.#drawBounds();
2656 const size = this.tileSize();
2657
2658 for (const baked of this.bakedChunks.values())
2659 {
2660 const left = baked.chunkX * CHUNK_SIZE * size;
2661 const top = baked.chunkY * CHUNK_SIZE * size;
2662 const chunkPx = CHUNK_SIZE * size;
2663 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
2664 this.#setRendererVisible(baked.groundObject, chunkVisible);
2665 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
2666 baked._inViewport = chunkVisible;
2667 for (let row = 0; row < CHUNK_SIZE; row++)
2668 {
2669 const rowTop = top + row * size;
2670 const rowVisible = chunkVisible && this.#rectIntersects(
2671 left, rowTop, left + chunkPx, rowTop + size, bounds
2672 );
2673 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
2674 }
2675 }
2676
2677 for (const objects of this.tiles.values())
2678 {
2679 const left = objects.tileX * size;
2680 const top = objects.tileY * size;
2681 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
2682 objects._inViewport = visible;
2683 this.#setRendererVisible(objects.ground, visible);
2684 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
2685 this.#setRendererVisible(objects.block, visible);
2686 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
2687 if (objects.waterEdges)
2688 {
2689 for (const edge of Object.values(objects.waterEdges))
2690 { this.#setRendererVisible(edge, visible); }
2691 }
2692 }
2693 }
2694
2695 #upsertEntity (payload)
2696 {
2697 const size = this.tileSize();
2698 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2699 let entity = this.entities.get(payload.entityId);
2700 if (entity?.dying)
2701 {
2702 if (entity.entityId === this.localEntityId)
2703 { this.#abortEntityFade(entity); }
2704 else
2705 {
2706 this.#finishEntityFade(payload.entityId);
2707 entity = null;
2708 }
2709 }
2710 if (!entity)
2711 {
2712 const spriteName = payload.layers?.[0]?.sprite
2713 ?? payload.sprite
2714 ?? bodySpriteName(payload.sex);
2715 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
2716 this.scene.addObject(object);
2717 this.#startIdleAnimation(object);
2718 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
2719 this.entities.set(payload.entityId, entity);
2720 }
2721 entity.entityId = payload.entityId;
2722 entity.tileX = payload.tileX;
2723 entity.tileY = payload.tileY;
2724 entity.gait = payload.gait;
2725 entity.sex = payload.sex ?? entity.sex;
2726 entity.characterId = payload.characterId ?? entity.characterId ?? null;
2727 entity.accountId = payload.accountId ?? entity.accountId ?? null;
2728 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
2729 if (payload.level != null)
2730 { entity.level = payload.level | 0; }
2731 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
2732 entity.aggressive = payload.aggressive != null
2733 ? !!payload.aggressive
2734 : (payload.hostile != null ? !!payload.hostile : !!entity.aggressive);
2735 entity.canFight = payload.canFight != null
2736 ? !!payload.canFight
2737 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
2738 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
2739 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
2740 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
2741 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
2742 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
2743 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
2744 if (payload.lightIntensity != null)
2745 { entity.lightIntensity = Number(payload.lightIntensity) || 1; }
2746 else if (entity.lightIntensity == null)
2747 { entity.lightIntensity = 1; }
2748 if (payload.visualScale != null)
2749 { entity.visualScale = Number(payload.visualScale) || 1; }
2750 else if (entity.visualScale == null)
2751 { entity.visualScale = 1; }
2752 if (payload.health != null)
2753 { entity.health = payload.health; }
2754 if (payload.maxHealth != null)
2755 { entity.maxHealth = payload.maxHealth; }
2756 if (payload.skullValue != null)
2757 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2758 else if (entity.skullValue == null)
2759 { entity.skullValue = 0; }
2760 if (payload.firstName)
2761 { entity.firstName = payload.firstName; }
2762 if (payload.lastName)
2763 { entity.lastName = payload.lastName; }
2764 entity.firstName = entity.firstName ?? "";
2765 entity.lastName = entity.lastName ?? "";
2766 if (payload.worldX != null && payload.worldY != null)
2767 {
2768 entity.worldX = payload.worldX;
2769 entity.worldY = payload.worldY;
2770 entity.visualX = payload.worldX * size;
2771 entity.visualY = payload.worldY * size;
2772 entity.targetX = entity.visualX;
2773 entity.targetY = entity.visualY;
2774 }
2775 else
2776 {
2777 entity.visualX = pivot.x;
2778 entity.visualY = pivot.y;
2779 entity.targetX = pivot.x;
2780 entity.targetY = pivot.y;
2781 }
2782 entity.fromX = entity.visualX;
2783 entity.fromY = entity.visualY;
2784 if (payload.layers)
2785 { this.#applyLayers(entity, payload.layers); }
2786 this.#syncHpBar(entity);
2787 this.#syncSkullMarker(entity);
2788 this.#placeEntity(entity, performance.now());
2789 }
2790
2791 #applyLayers (entity, layers)
2792 {
2793 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2794 this.#rebuildOverlays(entity);
2795 }
2796
2797 #setGatherToolOverlay (entity, toolItemId)
2798 {
2799 entity.gatherToolItemId = toolItemId;
2800 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2801 this.#rebuildOverlays(entity);
2802 this.#placeEntity(entity, performance.now());
2803 }
2804
2805 #expireGatherToolOverlay (entity, now)
2806 {
2807 if (entity.gatherToolItemId == null)
2808 { return; }
2809 if ((entity.gatherToolUntil ?? 0) > now)
2810 { return; }
2811 entity.gatherToolItemId = null;
2812 entity.gatherToolUntil = 0;
2813 this.#rebuildOverlays(entity);
2814 }
2815
2816 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2817 #layersForDisplay (entity)
2818 {
2819 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2820 const toolId = entity.gatherToolItemId;
2821 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2822 { return layers; }
2823 const equip = itemEquipSprite(toolId);
2824 if (!equip || !this.game.images[equip])
2825 { return layers; }
2826 const replacement = {
2827 sprite: equip,
2828 itemId: toolId,
2829 tint: resolveEquipTint(toolId)
2830 };
2831 for (let index = layers.length - 1; index >= 1; index--)
2832 {
2833 const def = itemDefinition(layers[index].itemId);
2834 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2835 {
2836 layers[index] = replacement;
2837 return layers;
2838 }
2839 }
2840 layers.push(replacement);
2841 return layers;
2842 }
2843
2844 #rebuildOverlays (entity)
2845 {
2846 const layers = this.#layersForDisplay(entity);
2847 const base = layers[0]?.sprite
2848 ?? bodySpriteName(entity.sex);
2849 if (this.game.images[base])
2850 {
2851 entity.object.renderer.sprite = this.game.images[base];
2852 this.#startIdleAnimation(entity.object);
2853 }
2854 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2855 entity.bodyDualTint = layers[0]?.dualTint
2856 ? {
2857 shaft: normalizeRgb(layers[0].dualTint.shaft),
2858 tip: normalizeRgb(layers[0].dualTint.tip),
2859 ...(layers[0].dualTint.coat
2860 ? { coat: normalizeRgb(layers[0].dualTint.coat) }
2861 : {})
2862 }
2863 : null;
2864 entity.bloomBody = !!layers[0]?.bloomBody;
2865 for (const overlay of entity.overlays ?? [])
2866 { overlay.destroy(); }
2867 for (const overlay of entity.bloomOverlays ?? [])
2868 { overlay.destroy(); }
2869 entity.overlays = [];
2870 entity.overlayTints = [];
2871 entity.overlayDualTints = [];
2872 entity.overlayTightFit = [];
2873 entity.bloomOverlays = [];
2874 entity.bloomOverlayTints = [];
2875 entity.bloomOverlayDualTints = [];
2876 if (entity.bloomBody && this.game.images[base])
2877 {
2878 const bloomName = bloomCompanionName(base);
2879 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2880 if (bloomImage)
2881 {
2882 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2883 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2884 this.#markUnlit(bloom);
2885 this.#startIdleAnimation(bloom);
2886 this.scene.addObject(bloom);
2887 entity.bloomOverlays.push(bloom);
2888 entity.bloomOverlayTints.push(entity.bodyTint);
2889 entity.bloomOverlayDualTints.push(entity.bodyDualTint);
2890 }
2891 }
2892 for (const layer of layers.slice(1))
2893 {
2894 const image = this.game.images[layer.sprite];
2895 if (!image)
2896 { continue; }
2897 const object = new GameObject(0, 0, image, SORT_ENTITY);
2898 this.scene.addObject(object);
2899 entity.overlays.push(object);
2900 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2901 entity.overlayTightFit.push(!!layerDef?.tightFit);
2902 const dualTint = layer.dualTint
2903 ? {
2904 shaft: normalizeRgb(layer.dualTint.shaft),
2905 tip: normalizeRgb(layer.dualTint.tip),
2906 ...(layer.dualTint.coat
2907 ? { coat: normalizeRgb(layer.dualTint.coat) }
2908 : {})
2909 }
2910 : (layer.itemId != null
2911 ? resolveEquipDualTint({ itemId: layer.itemId }, layerDef)
2912 : null);
2913 entity.overlayDualTints.push(dualTint);
2914 entity.overlayTints.push(
2915 dualTint
2916 ? null
2917 : (layer.tint
2918 ? normalizeRgb(layer.tint)
2919 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2920 );
2921 const bloomName = bloomCompanionName(layer.sprite);
2922 const bloomImage = this.game.images[bloomName];
2923 if (!bloomImage)
2924 { continue; }
2925 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2926 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2927 this.#markUnlit(bloom);
2928 this.scene.addObject(bloom);
2929 entity.bloomOverlays.push(bloom);
2930 entity.bloomOverlayTints.push(
2931 layer.tint ? normalizeRgb(layer.tint) : null
2932 );
2933 }
2934 }
2935
2936 #placeEntity (entity, now = performance.now())
2937 {
2938 const zoom = this.zoom;
2939 const offsetX = entity.shoveOffsetX ?? 0;
2940 const offsetY = entity.shoveOffsetY ?? 0;
2941 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2942 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2943 let walkTilt = 0;
2944 if (entity.lerpStarted != null)
2945 {
2946 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2947 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2948 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2949 walkTilt = Math.sin(cycles) * tilt;
2950 }
2951 let flashStrength = (entity.damageFlashUntil ?? 0) > now
2952 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2953 : 0;
2954 let deathAlpha = 1;
2955 if (entity.dying)
2956 {
2957 const fadeMs = Math.max(1, entity.deathFadeMs ?? DEATH_FADE_MS);
2958 const fadeT = (now - (entity.deathFadeStarted ?? now)) / fadeMs;
2959 if (fadeT >= 1 && entity.entityId !== this.localEntityId)
2960 {
2961 this.#finishEntityFade(entity.entityId);
2962 return;
2963 }
2964 deathAlpha = Math.max(0, 1 - fadeT);
2965 // Red silhouette only for combat death; plain despawn keeps lit colours + darkness.
2966 if (entity.deathDissolve)
2967 { flashStrength = 1; }
2968 }
2969 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
2970 const tileShade = this.#entityShadeAlpha(entity, now);
2971 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2972
2973 entity.object.transform.rotation = walkTilt;
2974 if (entity.object.renderer)
2975 { entity.object.renderer.alpha = deathAlpha; }
2976 if (entity.bodyDualTint)
2977 {
2978 this.#syncDualTintLitSprite(
2979 entity.object,
2980 tileShade,
2981 entity.bodyDualTint,
2982 flashStrength,
2983 wade,
2984 flashColor
2985 );
2986 }
2987 else
2988 {
2989 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
2990 }
2991 const flight = !!entity.freeFlight;
2992 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1, flight);
2993 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2994 {
2995 const overlay = entity.overlays[index];
2996 const overlaySort = Math.min(SORT_HP_BAR - 2, SORT_ENTITY + 1 + index);
2997 overlay.transform.rotation = walkTilt;
2998 if (overlay.renderer)
2999 { overlay.renderer.alpha = deathAlpha; }
3000 const dualTint = entity.overlayDualTints?.[index] ?? null;
3001 if (dualTint)
3002 {
3003 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
3004 }
3005 else if (entity.overlayTightFit?.[index])
3006 {
3007 this.#syncTightFitLitSprite(
3008 overlay,
3009 entity,
3010 tileShade,
3011 flashStrength,
3012 wade,
3013 entity.overlayTints?.[index] ?? null,
3014 flashColor
3015 );
3016 }
3017 else
3018 {
3019 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
3020 }
3021 this.#placePivoted(overlay, pivotX, pivotY, pivotY, overlaySort, entity.visualScale ?? 1, flight);
3022 }
3023 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
3024 {
3025 const overlay = entity.bloomOverlays[index];
3026 this.#setRendererVisible(overlay, this.bloomEnabled && deathAlpha > 0.02);
3027 if (!this.bloomEnabled)
3028 { continue; }
3029 /** Multi-frame body bloom locks to the base sprite; static bodies leave bloom free to animate. */
3030 if (entity.bloomBody && index === 0 && entity.object?.renderer)
3031 {
3032 const bodySprite = entity.object.renderer.sprite;
3033 const bloomSprite = overlay.renderer.sprite;
3034 const bodyFrames = Number(bodySprite?.subImages) || Number(bodySprite?.subImgTotal) || 1;
3035 const bloomFrames = Number(bloomSprite?.subImages) || Number(bloomSprite?.subImgTotal) || 1;
3036 if (bodyFrames > 1 && bloomFrames === bodyFrames)
3037 {
3038 overlay.renderer.cycle = null;
3039 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
3040 }
3041 }
3042 overlay.transform.rotation = walkTilt;
3043 if (overlay.renderer)
3044 { overlay.renderer.alpha = deathAlpha; }
3045 const bloomDual = entity.bloomOverlayDualTints?.[index] ?? null;
3046 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
3047 if (bloomDual)
3048 { this.#syncDualTintLitSprite(overlay, 0, bloomDual); }
3049 else if (bloomTint)
3050 { this.#syncUnlitTintSprite(overlay, bloomTint); }
3051 else
3052 { this.#markUnlit(overlay); }
3053 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1, flight);
3054 }
3055 if (!entity.dying)
3056 {
3057 this.#placeHpBar(entity, pivotX, pivotY);
3058 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
3059 }
3060 }
3061
3062 #markUnlit (object)
3063 {
3064 if (!object?.renderer)
3065 { return; }
3066 object._lit = false;
3067 object.renderer.shader = null;
3068 object.renderer.shaderUniforms = null;
3069 object.renderer.secondaryMap = null;
3070 }
3071
3072 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
3073 #syncUnlitTintSprite (object, tintColor)
3074 {
3075 if (!object?.renderer || !tintColor)
3076 { return; }
3077 const tint = normalizeRgb(tintColor);
3078 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3079 object.renderer.shader = getTintLitSpriteShader();
3080 object.renderer.shaderUniforms = {
3081 u_darkness: 0,
3082 u_strength: 0,
3083 u_flashColor: FLASH_COLOR_DAMAGE,
3084 u_wade: 0,
3085 u_spriteHeight: height,
3086 u_useTint: 1,
3087 u_tintColor: [tint.r, tint.g, tint.b]
3088 };
3089 object.renderer.secondaryMap = null;
3090 }
3091
3092 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3093 {
3094 if (!object?.renderer || object._lit === false)
3095 { return; }
3096 object._lit = true;
3097 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3098 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3099 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3100 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3101 const tint = tintColor ? normalizeRgb(tintColor) : null;
3102 if (tint)
3103 {
3104 object.renderer.shader = getTintLitSpriteShader();
3105 object.renderer.shaderUniforms = {
3106 u_darkness: dark,
3107 u_strength: flash,
3108 u_flashColor: flashRgb,
3109 u_wade: wade ? 1 : 0,
3110 u_spriteHeight: height,
3111 u_useTint: 1,
3112 u_tintColor: [tint.r, tint.g, tint.b]
3113 };
3114 }
3115 else
3116 {
3117 object.renderer.shader = getSpriteLightingShader();
3118 object.renderer.shaderUniforms = {
3119 u_darkness: dark,
3120 u_strength: flash,
3121 u_flashColor: flashRgb,
3122 u_wade: wade ? 1 : 0,
3123 u_spriteHeight: height
3124 };
3125 }
3126 object.renderer.secondaryMap = null;
3127 }
3128
3129 #bodySecondaryMap (entity)
3130 {
3131 return entity?.object?.renderer?.sprite?.g_image ?? null;
3132 }
3133
3134 #tightFitMaskUniforms (overlay, entity)
3135 {
3136 const bodyRenderer = entity?.object?.renderer;
3137 const clothRenderer = overlay?.renderer;
3138 const bodySprite = bodyRenderer?.sprite;
3139 const clothSprite = clothRenderer?.sprite;
3140 if (!bodySprite || !clothSprite)
3141 { return null; }
3142 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
3143 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3144 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
3145 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3146 return {
3147 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
3148 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
3149 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
3150 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
3151 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
3152 };
3153 }
3154
3155 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
3156 {
3157 if (!overlay?.renderer || entity?.object?.renderer == null)
3158 { return; }
3159 const bodyMap = this.#bodySecondaryMap(entity);
3160 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
3161 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
3162 if (!bodyMap || !maskUniforms)
3163 {
3164 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
3165 return;
3166 }
3167 overlay._lit = true;
3168 const dark = Math.min(1, Math.max(0, darkness ?? 0));
3169 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3170 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3171 const tint = tintColor ? normalizeRgb(tintColor) : null;
3172 overlay.renderer.secondaryMap = bodyMap;
3173 if (tint)
3174 {
3175 overlay.renderer.shader = getTightFitTintLitSpriteShader();
3176 overlay.renderer.shaderUniforms = {
3177 u_darkness: dark,
3178 u_strength: flash,
3179 u_flashColor: flashRgb,
3180 u_wade: wade ? 1 : 0,
3181 u_spriteHeight: height,
3182 u_useTint: 1,
3183 u_tintColor: [tint.r, tint.g, tint.b],
3184 ...maskUniforms
3185 };
3186 }
3187 else
3188 {
3189 overlay.renderer.shader = getTightFitLitSpriteShader();
3190 overlay.renderer.shaderUniforms = {
3191 u_darkness: dark,
3192 u_strength: flash,
3193 u_flashColor: flashRgb,
3194 u_wade: wade ? 1 : 0,
3195 u_spriteHeight: height,
3196 ...maskUniforms
3197 };
3198 }
3199 }
3200
3201 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
3202 {
3203 if (!object?.renderer || !dualTint)
3204 { return; }
3205 const shaft = normalizeRgb(dualTint.shaft);
3206 const tip = normalizeRgb(dualTint.tip);
3207 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
3208 const dark = object._lit === false
3209 ? 0
3210 : Math.min(1, Math.max(0, darkness ?? 0));
3211 if (object._lit !== false)
3212 { object._lit = true; }
3213 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
3214 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
3215 object.renderer.shader = getDualTintLitSpriteShader();
3216 object.renderer.shaderUniforms = {
3217 u_darkness: dark,
3218 u_strength: flash,
3219 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
3220 u_wade: wade ? 1 : 0,
3221 u_spriteHeight: height,
3222 u_shaftTint: [shaft.r, shaft.g, shaft.b],
3223 u_tipTint: [tip.r, tip.g, tip.b],
3224 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
3225 u_hasCoat: coat ? 1 : 0
3226 };
3227 object.renderer.secondaryMap = null;
3228 }
3229
3230 #syncGroundItemSprite (item, darkness)
3231 {
3232 if (item?.dualTint)
3233 {
3234 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
3235 return;
3236 }
3237 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
3238 }
3239
3240 #groundTypeAt (tileX, tileY)
3241 {
3242 const ground = this.#groundAtTile(tileX, tileY);
3243 return ground == null ? null : normalizeGround(ground).typeId;
3244 }
3245
3246 /** Ground entry at a world tile, including editor hover preview when present. */
3247 #groundAtTile (tileX, tileY)
3248 {
3249 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
3250 && this.preview.ground !== undefined)
3251 { return this.preview.ground; }
3252 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3253 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3254 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3255 if (!snapshot)
3256 { return null; }
3257 const localX = tileX - chunkX * CHUNK_SIZE;
3258 const localY = tileY - chunkY * CHUNK_SIZE;
3259 const index = localY * CHUNK_SIZE + localX;
3260 return snapshot.grounds?.[index] ?? null;
3261 }
3262
3263 #waterCoastEdges (tileX, tileY)
3264 {
3265 const season = this.worldSeason;
3266 return {
3267 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
3268 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
3269 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
3270 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
3271 };
3272 }
3273
3274 /**
3275 * Prefer a wet-shore (sand-wet) neighbor sprite for coast retreat peeks.
3276 * @returns {{ sprite: object|null, edgeN: number, edgeE: number, edgeS: number, edgeW: number }}
3277 */
3278 #waterCoastShore (tileX, tileY, edges)
3279 {
3280 const season = this.worldSeason;
3281 const candidates = [];
3282 if (edges?.n)
3283 { candidates.push({ edge: "n", tileX, tileY: tileY - 1 }); }
3284 if (edges?.e)
3285 { candidates.push({ edge: "e", tileX: tileX + 1, tileY }); }
3286 if (edges?.s)
3287 { candidates.push({ edge: "s", tileX, tileY: tileY + 1 }); }
3288 if (edges?.w)
3289 { candidates.push({ edge: "w", tileX: tileX - 1, tileY }); }
3290 let pick = null;
3291 for (const candidate of candidates)
3292 {
3293 const ground = this.#groundAtTile(candidate.tileX, candidate.tileY);
3294 if (ground == null)
3295 { continue; }
3296 const entry = normalizeGround(ground);
3297 const def = GROUND_DEFINITIONS[entry.typeId];
3298 if (!def)
3299 { continue; }
3300 let spriteName = null;
3301 if (def.wetShore)
3302 {
3303 const wetState = `${def.key}-wet`;
3304 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3305 if (states.includes(wetState))
3306 { spriteName = spriteImageName("ground", def.key, wetState); }
3307 }
3308 if (!spriteName)
3309 {
3310 const states = this.catalog?.grounds?.[def.key]?.states ?? [];
3311 const state = resolveSeasonalVisualState(states, entry.state, season) ?? def.key;
3312 spriteName = spriteImageName("ground", def.key, state);
3313 }
3314 const sprite = spriteName ? this.game.images[spriteName] : null;
3315 if (!sprite)
3316 { continue; }
3317 const ranked = { ...candidate, sprite, wet: !!def.wetShore };
3318 if (ranked.wet)
3319 {
3320 pick = ranked;
3321 break;
3322 }
3323 if (!pick)
3324 { pick = ranked; }
3325 }
3326 const shore = {
3327 sprite: pick?.sprite ?? null,
3328 edgeN: 0,
3329 edgeE: 0,
3330 edgeS: 0,
3331 edgeW: 0
3332 };
3333 if (pick?.edge === "n")
3334 { shore.edgeN = 1; }
3335 else if (pick?.edge === "e")
3336 { shore.edgeE = 1; }
3337 else if (pick?.edge === "s")
3338 { shore.edgeS = 1; }
3339 else if (pick?.edge === "w")
3340 { shore.edgeW = 1; }
3341 return shore;
3342 }
3343
3344 #syncWaterGroundSprite (object, {
3345 corners = null,
3346 ambientDark = 0,
3347 edges = null,
3348 shore = null,
3349 timeSec = 0,
3350 fallbackLit = 1,
3351 tileX = 0,
3352 tileY = 0,
3353 deep = false
3354 } = {})
3355 {
3356 if (!object?.renderer)
3357 { return; }
3358 const lit = corners ?? {
3359 nw: fallbackLit,
3360 ne: fallbackLit,
3361 sw: fallbackLit,
3362 se: fallbackLit
3363 };
3364 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
3365 const shoreSprite = shore?.sprite ?? null;
3366 const shoreUv = shoreSprite?.getUvRect?.(0)
3367 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
3368 object._lit = true;
3369 object.renderer.shader = getWaterGroundShader();
3370 object.renderer.secondaryMap = shoreSprite?.g_image ?? null;
3371 object.renderer.shaderUniforms = {
3372 u_ambientDark: dark,
3373 u_litNW: lit.nw,
3374 u_litNE: lit.ne,
3375 u_litSW: lit.sw,
3376 u_litSE: lit.se,
3377 u_time: timeSec,
3378 u_tileX: tileX | 0,
3379 u_tileY: tileY | 0,
3380 u_deep: deep ? 1 : 0,
3381 u_edgeN: edges?.n ?? 0,
3382 u_edgeE: edges?.e ?? 0,
3383 u_edgeS: edges?.s ?? 0,
3384 u_edgeW: edges?.w ?? 0,
3385 u_hasShore: shoreSprite ? 1 : 0,
3386 u_shoreEdgeN: shore?.edgeN ?? 0,
3387 u_shoreEdgeE: shore?.edgeE ?? 0,
3388 u_shoreEdgeS: shore?.edgeS ?? 0,
3389 u_shoreEdgeW: shore?.edgeW ?? 0,
3390 u_shoreUvRect: [shoreUv.u0, shoreUv.v0, shoreUv.u1, shoreUv.v1]
3391 };
3392 }
3393
3394 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
3395 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
3396 {
3397 if (!objects?.ground)
3398 { return; }
3399 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
3400 {
3401 objects.waterEdges = null;
3402 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
3403 return;
3404 }
3405 const fallbackLit = 1 - (objects.shadeAlpha ?? 0);
3406 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
3407 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
3408 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
3409 const localX = objects.tileX - chunkX * CHUNK_SIZE;
3410 const localY = objects.tileY - chunkY * CHUNK_SIZE;
3411 let litCorners = null;
3412 if (chunkBaked)
3413 {
3414 if (this.lightingMode === "simple")
3415 {
3416 const gridW = CHUNK_SIZE + 2;
3417 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
3418 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
3419 }
3420 else
3421 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
3422 }
3423 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
3424 const shore = this.#waterCoastShore(objects.tileX, objects.tileY, objects.waterEdges);
3425 this.#syncWaterGroundSprite(objects.ground, {
3426 corners: litCorners,
3427 ambientDark,
3428 edges: objects.waterEdges,
3429 shore,
3430 timeSec,
3431 fallbackLit,
3432 tileX: objects.tileX,
3433 tileY: objects.tileY,
3434 deep: objects.groundTypeId === GroundType.deepWater
3435 });
3436 }
3437
3438 #ambientDarkness ()
3439 {
3440 const hour = this.nightPreview ?? this.worldHour;
3441 const calendar = nightFactor(hour, this.settings.nightDarkness);
3442 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
3443 if (dark == null)
3444 { dark = calendar; }
3445 if (this.localBlind)
3446 { dark = Math.min(1, dark + 0.85); }
3447 return dark;
3448 }
3449
3450 setLocalBlind (blind)
3451 {
3452 this.localBlind = !!blind;
3453 }
3454
3455 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
3456 #blindVisionLight ()
3457 {
3458 if (!this.localBlind)
3459 { return null; }
3460 const local = this.entities.get(this.localEntityId);
3461 if (!local)
3462 { return null; }
3463 const tileSize = this.tileSize();
3464 return {
3465 tileX: Math.floor(local.visualX / tileSize),
3466 tileY: Math.floor(local.visualY / tileSize),
3467 range: 2.25,
3468 intensity: 1
3469 };
3470 }
3471
3472 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
3473 {
3474 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
3475 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
3476 const dark = (fromAlpha + toAlpha) / 2;
3477 if (dualTint)
3478 {
3479 this.#syncDualTintLitSprite(object, dark, dualTint);
3480 return;
3481 }
3482 this.#syncLitSprite(object, dark);
3483 }
3484
3485 #dualTintFromPayload (payload)
3486 {
3487 if (!payload?.shaftTint || !payload?.tipTint)
3488 { return null; }
3489 return {
3490 shaft: payload.shaftTint,
3491 tip: payload.tipTint,
3492 ...(payload.coatTint ? { coat: payload.coatTint } : {})
3493 };
3494 }
3495
3496 #syncHpBar (entity)
3497 {
3498 const current = entity.health;
3499 const max = entity.maxHealth;
3500 const show = current != null
3501 && max != null
3502 && max > 0
3503 && current < max;
3504 if (!show)
3505 {
3506 entity.hpBar?.destroy();
3507 entity.hpBar = null;
3508 entity.hpBarCanvas = null;
3509 return;
3510 }
3511 if (!entity.hpBarCanvas)
3512 {
3513 entity.hpBarCanvas = document.createElement("canvas");
3514 entity.hpBarCanvas.width = HP_BAR_W;
3515 entity.hpBarCanvas.height = HP_BAR_H;
3516 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
3517 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
3518 this.#markUnlit(entity.hpBar);
3519 this.scene.addObject(entity.hpBar);
3520 }
3521 drawHpBar(entity.hpBarCanvas, current, max);
3522 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
3523 }
3524
3525 #placeHpBar (entity, pivotX, pivotY)
3526 {
3527 if (!entity.hpBar)
3528 { return; }
3529 const sprite = entity.object?.renderer?.sprite;
3530 if (!sprite)
3531 { return; }
3532 const zoom = this.zoom;
3533 const drawH = sprite.height * zoom;
3534 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
3535 const spriteTop = centerY - drawH / 2;
3536 const barW = HP_BAR_W * zoom;
3537 const barH = HP_BAR_H * zoom;
3538 entity.hpBar.transform.position.x = pivotX;
3539 entity.hpBar.transform.position.y = spriteTop - barH / 2;
3540 entity.hpBar.transform.size = new vector(barW, barH);
3541 this.#setLayer(entity.hpBar, this.#depthLayer(pivotY, SORT_HP_BAR));
3542 }
3543
3544 #syncSkullMarker (entity)
3545 {
3546 if (!entity?.characterId)
3547 {
3548 entity.skullMarker?.destroy();
3549 entity.skullMarker = null;
3550 return;
3551 }
3552 const tint = skullTintColor(entity.skullValue | 0, this.settings);
3553 if (!tint)
3554 {
3555 entity.skullMarker?.destroy();
3556 entity.skullMarker = null;
3557 return;
3558 }
3559 const image = this.game.images[SKULL_SPRITE]
3560 ?? this.game.images["item:skull:skull"];
3561 if (!image)
3562 { return; }
3563 if (!entity.skullMarker)
3564 {
3565 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
3566 this.scene.addObject(entity.skullMarker);
3567 }
3568 entity.skullTint = tint;
3569 entity.skullMarker.renderer.sprite = image;
3570 }
3571
3572 /**
3573 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
3574 */
3575 #placeSkullMarker (entity, pivotX, pivotY, darkness)
3576 {
3577 this.#syncSkullMarker(entity);
3578 if (!entity.skullMarker)
3579 { return; }
3580 const body = entity.object?.renderer?.sprite;
3581 const skull = entity.skullMarker.renderer?.sprite;
3582 if (!body || !skull)
3583 { return; }
3584 const zoom = this.zoom;
3585 const scale = entity.visualScale ?? 1;
3586 const bodyH = body.height * zoom * scale;
3587 const skullH = skull.height * zoom;
3588 const skullW = skull.width * zoom;
3589 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
3590 const bodyTop = bodyCenterY - bodyH / 2;
3591 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
3592 entity.skullMarker.transform.position.x = pivotX;
3593 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
3594 entity.skullMarker.transform.size = new vector(skullW, skullH);
3595 this.#setLayer(entity.skullMarker, this.#depthLayer(pivotY, SORT_HP_BAR));
3596 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
3597 }
3598
3599 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
3600 {
3601 this.#bakeAndPlaceChunk(snapshot);
3602 this.#relayoutChunkTiles(snapshot);
3603 // Soft terrain and wet-sand shorelines both sample cross-chunk neighbors.
3604 if (refreshSoftNeighbors)
3605 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
3606 }
3607
3608 #relayoutChunk (snapshot)
3609 {
3610 this.#layoutBakedChunk(snapshot);
3611 this.#relayoutChunkTiles(snapshot);
3612 }
3613
3614 #relayoutChunkTiles (snapshot)
3615 {
3616 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3617 {
3618 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3619 {
3620 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
3621 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
3622 this.#drawTile(tileX, tileY);
3623 }
3624 }
3625 }
3626
3627 #scheduleChunkRebuild (snapshot)
3628 {
3629 if (!snapshot)
3630 { return; }
3631 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
3632 this.#cancelIdlePrefetch();
3633 this.#ensureChunkFlushScheduled();
3634 }
3635
3636 #scheduleEdgeRebuild ()
3637 {
3638 this.#edgesDirty = true;
3639 this.#cancelIdlePrefetch();
3640 this.#ensureChunkFlushScheduled();
3641 }
3642
3643 #ensureChunkFlushScheduled ()
3644 {
3645 if (this.#chunkRebuildRaf)
3646 { return; }
3647 this.#cancelIdlePrefetch();
3648 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
3649 }
3650
3651 #notePlayerTile (tileX, tileY)
3652 {
3653 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3654 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3655 const prevX = this.#playerChunkX;
3656 const prevY = this.#playerChunkY;
3657 if (prevX != null
3658 && (chunkX !== prevX || chunkY !== prevY))
3659 {
3660 const dx = chunkX - prevX;
3661 const dy = chunkY - prevY;
3662 if (dx !== 0)
3663 { this.#playerMoveChunkDx = Math.sign(dx); }
3664 if (dy !== 0)
3665 { this.#playerMoveChunkDy = Math.sign(dy); }
3666 this.#onActiveLightingCenterChanged(prevX, prevY, chunkX, chunkY);
3667 }
3668 this.#playerChunkX = chunkX;
3669 this.#playerChunkY = chunkY;
3670 }
3671
3672 /** When the 3×3 lighting center moves: refresh door sprites (resting vs live) and lightmaps. */
3673 #onActiveLightingCenterChanged (prevChunkX, prevChunkY, chunkX, chunkY)
3674 {
3675 this.#invalidateNeighborLightmapCaches(prevChunkX, prevChunkY);
3676 this.#invalidateNeighborLightmapCaches(chunkX, chunkY);
3677 const doorChunks = new Set();
3678 for (const [cx, cy] of [[prevChunkX, prevChunkY], [chunkX, chunkY]])
3679 {
3680 for (let dy = -1; dy <= 1; dy++)
3681 {
3682 for (let dx = -1; dx <= 1; dx++)
3683 { doorChunks.add(`${cx + dx},${cy + dy}`); }
3684 }
3685 }
3686 for (const key of doorChunks)
3687 {
3688 const [cx, cy] = key.split(",").map(Number);
3689 this.#redrawDoorTilesInChunk(cx, cy);
3690 }
3691 }
3692
3693 #redrawDoorTilesInChunk (chunkX, chunkY)
3694 {
3695 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3696 if (!snapshot?.blocks)
3697 { return; }
3698 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3699 {
3700 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3701 {
3702 const block = snapshot.blocks[localY * CHUNK_SIZE + localX];
3703 if (!blockDefinition(block?.typeId)?.door)
3704 { continue; }
3705 this.#drawTile(chunkX * CHUNK_SIZE + localX, chunkY * CHUNK_SIZE + localY);
3706 }
3707 }
3708 }
3709
3710 #playerChunkCoords ()
3711 {
3712 const local = this.entities.get(this.localEntityId);
3713 if (local)
3714 {
3715 return {
3716 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3717 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3718 };
3719 }
3720 if (this.#playerChunkX != null && this.#playerChunkY != null)
3721 {
3722 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
3723 }
3724 return null;
3725 }
3726
3727 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
3728 #chunkRebuildScore (key, mode = "urgent")
3729 {
3730 const [chunkX, chunkY] = key.split(",").map(Number);
3731 const player = this.#playerChunkCoords();
3732 if (!player)
3733 { return 0; }
3734 const dx = chunkX - player.chunkX;
3735 const dy = chunkY - player.chunkY;
3736 const dist = Math.abs(dx) + Math.abs(dy);
3737 let ahead = 0;
3738 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
3739 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
3740 if (mode === "idle")
3741 {
3742 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
3743 }
3744 return dist * 10 - Math.max(0, ahead) * 3;
3745 }
3746
3747 #sortedChunkRebuildKeys (mode = "urgent")
3748 {
3749 return [...this.#chunkRebuildKeys].sort((a, b) =>
3750 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
3751 }
3752
3753 #discoverUnbakedChunks ()
3754 {
3755 for (const key of this.chunks.keys())
3756 {
3757 if (!this.bakedChunks.has(key))
3758 { this.#chunkRebuildKeys.add(key); }
3759 }
3760 }
3761
3762 #hasUnbakedChunks ()
3763 {
3764 for (const key of this.chunks.keys())
3765 {
3766 if (!this.bakedChunks.has(key))
3767 { return true; }
3768 }
3769 return false;
3770 }
3771
3772 #pickIdlePrefetchSnapshot ()
3773 {
3774 let best = null;
3775 let bestScore = Infinity;
3776 for (const snapshot of this.chunks.values())
3777 {
3778 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3779 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
3780 { continue; }
3781 const score = this.#chunkRebuildScore(key, "idle");
3782 if (score < bestScore)
3783 {
3784 bestScore = score;
3785 best = snapshot;
3786 }
3787 }
3788 return best;
3789 }
3790
3791 #cancelIdlePrefetch ()
3792 {
3793 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
3794 { cancelIdleCallback(this.#idlePrefetchId); }
3795 this.#idlePrefetchId = 0;
3796 }
3797
3798 #scheduleIdleChunkPrefetch ()
3799 {
3800 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3801 { return; }
3802 if (typeof requestIdleCallback !== "function")
3803 { return; }
3804 if (!this.#hasUnbakedChunks())
3805 { return; }
3806 this.#idlePrefetchId = requestIdleCallback(
3807 (deadline) => this.#runIdleChunkPrefetch(deadline),
3808 { timeout: 2500 }
3809 );
3810 }
3811
3812 #runIdleChunkPrefetch (deadline)
3813 {
3814 this.#idlePrefetchId = 0;
3815 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3816 { return; }
3817 this.#discoverUnbakedChunks();
3818 if (this.#chunkRebuildKeys.size)
3819 {
3820 this.#ensureChunkFlushScheduled();
3821 return;
3822 }
3823 const snapshot = this.#pickIdlePrefetchSnapshot();
3824 if (!snapshot)
3825 { return; }
3826 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
3827 {
3828 this.#scheduleIdleChunkPrefetch();
3829 return;
3830 }
3831 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
3832 if (this.#hasUnbakedChunks())
3833 { this.#scheduleIdleChunkPrefetch(); }
3834 }
3835
3836 #flushChunkWork ()
3837 {
3838 this.#chunkRebuildRaf = 0;
3839 const keys = this.#sortedChunkRebuildKeys("urgent");
3840 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
3841 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
3842 this.#chunkRebuildKeys.clear();
3843 for (const key of rest)
3844 { this.#chunkRebuildKeys.add(key); }
3845 for (const key of batch)
3846 {
3847 const snap = this.chunks.get(key);
3848 if (snap)
3849 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
3850 }
3851 if (this.#chunkRebuildKeys.size)
3852 {
3853 this.#ensureChunkFlushScheduled();
3854 return;
3855 }
3856 if (this.#edgesDirty)
3857 {
3858 this.#rebuildAllEdges();
3859 this.#edgesDirty = false;
3860 }
3861 this.#scheduleIdleChunkPrefetch();
3862 }
3863
3864 #previewEqual (a, b)
3865 {
3866 if (a === b)
3867 { return true; }
3868 if (!a || !b)
3869 { return false; }
3870 return a.tileX === b.tileX
3871 && a.tileY === b.tileY
3872 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
3873 && this.#previewPart(a.block) === this.#previewPart(b.block);
3874 }
3875
3876 #previewPart (value)
3877 {
3878 return value === undefined ? undefined : JSON.stringify(value);
3879 }
3880
3881 #rebuildSoftTerrainNeighborChunks (snapshot)
3882 {
3883 for (let dy = -1; dy <= 1; dy++)
3884 {
3885 for (let dx = -1; dx <= 1; dx++)
3886 {
3887 if (dx === 0 && dy === 0)
3888 { continue; }
3889 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3890 if (neighbor)
3891 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
3892 }
3893 }
3894 }
3895
3896 #rebakeAllChunks ()
3897 {
3898 for (const snapshot of this.chunks.values())
3899 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
3900 }
3901
3902 #bakeAndPlaceChunk (snapshot)
3903 {
3904 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3905 const atlases = bakeChunkAtlases({
3906 snapshot,
3907 catalog: this.catalog,
3908 images: this.game.images,
3909 preview: this.preview,
3910 season: this.worldSeason,
3911 softTerrain: this.softTerrain,
3912 wetSandBandFraction: Math.max(0, Math.min(1, Number(this.settings?.wetSandBand) || 0)),
3913 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
3914 cache: this.#atlasCache
3915 });
3916 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3917 let baked = this.bakedChunks.get(key);
3918 this.#releaseBakedAtlasRefs(baked);
3919
3920 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
3921 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
3922 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
3923 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
3924 ?? frameworkImageFromCanvas(atlases.bloom);
3925
3926 if (!baked)
3927 {
3928 const lightmapCanvas = makeLightmapCanvas(atlasPx);
3929 baked = {
3930 groundCanvas: atlases.ground,
3931 blockCanvases: atlases.blockRows,
3932 bloomCanvas: atlases.bloom,
3933 lightmapCanvas,
3934 groundImage,
3935 blockImages,
3936 bloomImage,
3937 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
3938 groundObject: null,
3939 blockObjects: [],
3940 bloomObject: null,
3941 tallBlocks: atlases.tallBlocks,
3942 animatedGrounds: atlases.animatedGrounds,
3943 lightmapPixels: null,
3944 atlasCacheRefs: atlases.cacheRefs
3945 };
3946 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
3947 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3948 this.scene.addObject(baked.groundObject);
3949 for (let row = 0; row < CHUNK_SIZE; row++)
3950 {
3951 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
3952 this.#applyAtlasLighting(object, baked.lightmapImage, row);
3953 this.scene.addObject(object);
3954 baked.blockObjects.push(object);
3955 }
3956 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
3957 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3958 this.#markUnlit(baked.bloomObject);
3959 this.scene.addObject(baked.bloomObject);
3960 this.bakedChunks.set(key, baked);
3961 }
3962 else
3963 {
3964 if (baked.groundCanvas !== atlases.ground)
3965 {
3966 baked.groundCanvas = atlases.ground;
3967 baked.groundImage = groundImage;
3968 baked.groundObject.renderer.sprite = groundImage;
3969 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3970 }
3971 for (let row = 0; row < CHUNK_SIZE; row++)
3972 {
3973 if (baked.blockCanvases[row] !== atlases.blockRows[row])
3974 {
3975 baked.blockCanvases[row] = atlases.blockRows[row];
3976 baked.blockImages[row] = blockImages[row];
3977 baked.blockObjects[row].renderer.sprite = blockImages[row];
3978 }
3979 this.#applyAtlasLighting(
3980 baked.blockObjects[row],
3981 baked.lightmapImage,
3982 row
3983 );
3984 }
3985 if (baked.bloomCanvas !== atlases.bloom)
3986 {
3987 baked.bloomCanvas = atlases.bloom;
3988 baked.bloomImage = bloomImage;
3989 baked.bloomObject.renderer.sprite = bloomImage;
3990 }
3991 baked.tallBlocks = atlases.tallBlocks;
3992 baked.animatedGrounds = atlases.animatedGrounds;
3993 baked.atlasCacheRefs = atlases.cacheRefs;
3994 }
3995 baked.chunkX = snapshot.chunkX;
3996 baked.chunkY = snapshot.chunkY;
3997 baked.lightmapCacheKey = null;
3998 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3999 this.#layoutBakedChunk(snapshot);
4000 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
4001 }
4002
4003 #releaseBakedAtlasRefs (baked)
4004 {
4005 if (!baked?.atlasCacheRefs)
4006 { return; }
4007 this.#atlasCache.release(baked.atlasCacheRefs.ground);
4008 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
4009 { this.#atlasCache.release(entry); }
4010 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
4011 baked.atlasCacheRefs = null;
4012 }
4013
4014 #chunkTextureWarmPriority (chunkX, chunkY)
4015 {
4016 const local = this.entities.get(this.localEntityId);
4017 if (!local)
4018 { return 999; }
4019 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
4020 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
4021 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
4022 }
4023
4024 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
4025 {
4026 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
4027 { return; }
4028 this.#pendingTextureCanvasSet.add(canvas);
4029 this.#pendingTextureCanvases.push({
4030 canvas,
4031 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
4032 });
4033 this.#scheduleTextureWarm();
4034 }
4035
4036 #queueBakedChunkTextures (baked, chunkX, chunkY)
4037 {
4038 if (!baked)
4039 { return; }
4040 const refs = baked.atlasCacheRefs;
4041 const maybeWarm = (canvas, entry) =>
4042 {
4043 if (!canvas)
4044 { return; }
4045 if (entry && this.#atlasCache.isWarmed(canvas))
4046 { return; }
4047 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
4048 };
4049 maybeWarm(baked.groundCanvas, refs?.ground);
4050 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
4051 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
4052 maybeWarm(baked.bloomCanvas, refs?.bloom);
4053 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
4054 }
4055
4056 #scheduleTextureWarm ()
4057 {
4058 if (this.#textureWarmRaf)
4059 { return; }
4060 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
4061 }
4062
4063 #flushTextureWarm ()
4064 {
4065 this.#textureWarmRaf = 0;
4066 if (!this.#pendingTextureCanvases.length)
4067 { return; }
4068 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
4069 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
4070 for (const entry of batch)
4071 {
4072 this.#pendingTextureCanvasSet.delete(entry.canvas);
4073 setNearestFilter(this.scene, entry.canvas);
4074 this.#atlasCache.markWarmed(entry.canvas);
4075 }
4076 if (this.#pendingTextureCanvases.length)
4077 { this.#scheduleTextureWarm(); }
4078 }
4079
4080 #applyAtlasLighting (object, lightmapImage, lightRow)
4081 {
4082 if (!object?.renderer)
4083 { return; }
4084 object._lit = true;
4085 object.renderer.shader = getAtlasLightingShader();
4086 object.renderer.bumpMap = null;
4087 object.renderer.secondaryMap = lightmapImage;
4088 object.renderer.shaderUniforms = {
4089 u_ambientDark: 0,
4090 u_lightRow: lightRow
4091 };
4092 }
4093
4094 #syncCliffGroundTopSprite (object, darkness, groundImage, localX, localY)
4095 {
4096 if (!object?.renderer)
4097 { return; }
4098 object._lit = true;
4099 const dark = Math.min(1, Math.max(0, darkness ?? 0));
4100 object.renderer.shader = getCliffGroundTopShader();
4101 object.renderer.bumpMap = groundImage ?? null;
4102 object.renderer.secondaryMap = null;
4103 object.renderer.shaderUniforms = {
4104 u_darkness: dark,
4105 u_tileLocal: [localX, localY]
4106 };
4107 }
4108
4109 #layoutBakedChunk (snapshot)
4110 {
4111 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4112 const baked = this.bakedChunks.get(key);
4113 if (!baked)
4114 { return; }
4115 const size = this.tileSize();
4116 const left = snapshot.chunkX * CHUNK_SIZE * size;
4117 const top = snapshot.chunkY * CHUNK_SIZE * size;
4118 const chunkPx = CHUNK_SIZE * size;
4119 baked.groundObject.transform.position.x = left + chunkPx / 2;
4120 baked.groundObject.transform.position.y = top + chunkPx / 2;
4121 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
4122 this.#setLayer(baked.groundObject, LAYER_GROUND);
4123
4124 for (let row = 0; row < CHUNK_SIZE; row++)
4125 {
4126 const object = baked.blockObjects[row];
4127 const rowY = top + row * size + size / 2;
4128 object.transform.position.x = left + chunkPx / 2;
4129 object.transform.position.y = rowY;
4130 object.transform.size = new vector(chunkPx, size);
4131 this.#setLayer(object, this.#depthLayer(rowY, SORT_BLOCK));
4132 }
4133
4134 baked.bloomObject.transform.position.x = left + chunkPx / 2;
4135 baked.bloomObject.transform.position.y = top + chunkPx / 2;
4136 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
4137 this.#setLayer(baked.bloomObject, this.#depthLayer(top + chunkPx, SORT_BLOCK));
4138 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
4139 }
4140
4141 #destroyBakedChunk (key)
4142 {
4143 const baked = this.bakedChunks.get(key);
4144 if (!baked)
4145 { return; }
4146 this.#releaseBakedAtlasRefs(baked);
4147 baked.groundObject?.destroy();
4148 for (const object of baked.blockObjects ?? [])
4149 { object.destroy(); }
4150 baked.bloomObject?.destroy();
4151 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4152 this.bakedChunks.delete(key);
4153 }
4154
4155 #redrawPreview ()
4156 {
4157 if (!this.preview)
4158 { return; }
4159 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
4160 if (snapshot)
4161 { this.#rebuildChunk(snapshot); }
4162 }
4163
4164 #refreshWaterCoastsNear (chunkX, chunkY)
4165 {
4166 const timeSec = performance.now() / 1000;
4167 for (const objects of this.tiles.values())
4168 {
4169 if (!objects.ground || !isWaterGround(objects.groundTypeId))
4170 { continue; }
4171 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
4172 { continue; }
4173 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
4174 this.#syncGroundWaterFx(objects, 1, timeSec);
4175 }
4176 }
4177
4178 #drawTile (tileX, tileY)
4179 {
4180 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4181 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4182 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4183 if (!snapshot)
4184 { return; }
4185 const localX = tileX - chunkX * CHUNK_SIZE;
4186 const localY = tileY - chunkY * CHUNK_SIZE;
4187 const index = localY * CHUNK_SIZE + localX;
4188 const key = `${tileX},${tileY}`;
4189 let objects = this.tiles.get(key);
4190 if (!objects)
4191 {
4192 objects = { chunkX, chunkY, tileX, tileY };
4193 this.tiles.set(key, objects);
4194 }
4195 objects.tileX = tileX;
4196 objects.tileY = tileY;
4197 objects.chunkX = chunkX;
4198 objects.chunkY = chunkY;
4199 objects.light = snapshot.light[index] ?? 0;
4200
4201 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
4202 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
4203 if (animatedGround)
4204 {
4205 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
4206 if (objects.ground)
4207 {
4208 const size = this.tileSize();
4209 objects.ground.transform.position.x = tileX * size + size / 2;
4210 objects.ground.transform.position.y = tileY * size + size / 2;
4211 objects.ground.transform.size = new vector(size, size);
4212 this.#setLayer(objects.ground, LAYER_GROUND);
4213 objects.groundTypeId = animatedGround.typeId;
4214 this.#syncGroundWaterFx(objects, 1, performance.now() / 1000);
4215 }
4216 if (animatedGround.bloom)
4217 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
4218 else
4219 {
4220 objects.groundBloom?.destroy();
4221 objects.groundBloom = null;
4222 }
4223 }
4224 else
4225 {
4226 objects.ground?.destroy();
4227 objects.ground = null;
4228 objects.groundBloom?.destroy();
4229 objects.groundBloom = null;
4230 objects.groundTypeId = null;
4231 objects.waterEdges = null;
4232 }
4233
4234 let blockSource = snapshot.blocks[index];
4235 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY && this.preview.block !== undefined)
4236 { blockSource = this.preview.block; }
4237 // Outer map ring: always show doors at resting (matches baked light; no entities there).
4238 if (
4239 blockSource
4240 && blockDefinition(blockSource.typeId)?.door
4241 && !this.#isActiveLightingChunk(chunkX, chunkY)
4242 )
4243 {
4244 const resting = doorRestingState(blockSource);
4245 if (resting && resting !== blockSource.state)
4246 { blockSource = { ...blockSource, state: resting }; }
4247 }
4248 const tileBlock = tileBlockSpriteEntry(
4249 this.catalog,
4250 this.game.images,
4251 blockSource,
4252 this.worldSeason
4253 );
4254 if (tileBlock)
4255 {
4256 const pivot = tilePivot(tileX, tileY, this.tileSize());
4257 const blockEntry = normalizeBlock(blockSource);
4258 const blockDef = blockDefinition(blockEntry?.typeId);
4259 const blockSort = blockDef?.door
4260 ? doorSortSubOrder(blockEntry?.state, SORT_ENTITY)
4261 : SORT_ENTITY;
4262 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, blockSort);
4263 objects.blockSort = blockSort;
4264 objects.cliffGroundTop = !!blockDef?.cliffGroundTop;
4265 if (objects.block)
4266 {
4267 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, blockSort);
4268 if (objects.cliffGroundTop)
4269 {
4270 const localX = ((tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4271 const localY = ((tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4272 this.#syncCliffGroundTopSprite(
4273 objects.block,
4274 objects.shadeAlpha ?? 0,
4275 baked?.groundImage ?? null,
4276 localX,
4277 localY
4278 );
4279 }
4280 else
4281 { this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0); }
4282 }
4283 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
4284 }
4285 else
4286 {
4287 objects.block?.destroy();
4288 objects.block = null;
4289 objects.blockSort = null;
4290 objects.blockBloom?.destroy();
4291 objects.blockBloom = null;
4292 objects.cliffGroundTop = false;
4293 }
4294 }
4295
4296 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
4297 {
4298 if (!name)
4299 {
4300 existing?.destroy();
4301 return null;
4302 }
4303 const object = this.#ensureSprite(existing, name, sortOrder);
4304 if (!object)
4305 { return null; }
4306 object.renderer.layer = RENDER_LAYER_BLOOM;
4307 this.#markUnlit(object);
4308 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
4309 return object;
4310 }
4311
4312 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1, flight = false)
4313 {
4314 const sprite = object?.renderer?.sprite;
4315 if (!sprite)
4316 { return; }
4317 const zoom = this.zoom;
4318 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
4319 const factor = Math.max(0.1, Number(scale) || 1);
4320 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
4321 object.transform.position.x = center.x;
4322 object.transform.position.y = center.y;
4323 object.transform.size = new vector(draw.w * factor, draw.h * factor);
4324 this.#setLayer(object, this.#depthLayer(sortY, subOrder, flight));
4325 }
4326
4327 #ensureSprite (existing, name, layer)
4328 {
4329 const sprite = this.game.images[name];
4330 if (!sprite)
4331 {
4332 existing?.destroy();
4333 return null;
4334 }
4335 if (!existing || existing.renderer.sprite !== sprite)
4336 {
4337 existing?.destroy();
4338 existing = new GameObject(0, 0, sprite, layer);
4339 this.#syncLitSprite(existing, 0);
4340 this.scene.addObject(existing);
4341 this.#startIdleAnimation(existing);
4342 }
4343 return existing;
4344 }
4345
4346 #startIdleAnimation (object)
4347 {
4348 const sprite = object?.renderer?.sprite;
4349 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
4350 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
4351 }
4352
4353 #neighborClosed (snapshot, dir, dx, dy)
4354 {
4355 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
4356 if (other)
4357 { return !other.open; }
4358 return !!snapshot.closedEdges?.[dir];
4359 }
4360
4361 #rebuildAllEdges ()
4362 {
4363 const seen = new Set();
4364 for (const snapshot of this.chunks.values())
4365 {
4366 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4367 seen.add(key);
4368 this.#rebuildChunkEdges(snapshot);
4369 }
4370 for (const key of [...this.edges.keys()])
4371 {
4372 if (!seen.has(key))
4373 { this.#destroyEdges(key); }
4374 }
4375 }
4376
4377 #rebuildChunkEdges (snapshot)
4378 {
4379 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
4380 let bars = this.edges.get(key);
4381 if (!bars)
4382 {
4383 bars = {};
4384 this.edges.set(key, bars);
4385 }
4386
4387 const size = this.tileSize();
4388 const chunkPx = CHUNK_SIZE * size;
4389 const left = snapshot.chunkX * CHUNK_SIZE * size;
4390 const top = snapshot.chunkY * CHUNK_SIZE * size;
4391 const centerX = left + chunkPx / 2;
4392 const centerY = top + chunkPx / 2;
4393 const thickness = Math.max(2, Math.round(2 * this.zoom));
4394 const draw = snapshot.open === true;
4395
4396 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
4397 centerX, top, chunkPx, thickness, true);
4398 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
4399 centerX, top + chunkPx, chunkPx, thickness, true);
4400 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
4401 left, centerY, chunkPx, thickness, false);
4402 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
4403 left + chunkPx, centerY, chunkPx, thickness, false);
4404 }
4405
4406 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
4407 {
4408 if (!visible)
4409 {
4410 if (existing)
4411 { existing.renderer.visible = false; }
4412 return existing;
4413 }
4414
4415 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
4416 this.#markUnlit(existing);
4417 existing.renderer.visible = true;
4418 existing.transform.position.x = x;
4419 existing.transform.position.y = y;
4420 existing.transform.size = horizontal
4421 ? new vector(length, thickness)
4422 : new vector(thickness, length);
4423 this.#setLayer(existing, LAYER_EDGE);
4424 return existing;
4425 }
4426
4427 #destroyEdges (key)
4428 {
4429 const bars = this.edges.get(key);
4430 if (!bars)
4431 { return; }
4432 bars.north?.destroy();
4433 bars.east?.destroy();
4434 bars.south?.destroy();
4435 bars.west?.destroy();
4436 this.edges.delete(key);
4437 }
4438
4439 #entityShadeAlpha (entity, now)
4440 {
4441 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
4442 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
4443 { return toAlpha; }
4444 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
4445 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
4446 return fromAlpha + (toAlpha - fromAlpha) * t;
4447 }
4448
4449 /** A layer write costs the scene a full re-sort, so only write real changes. */
4450 #setLayer (object, layer)
4451 {
4452 if (!object || object.layer === layer)
4453 { return; }
4454 object.layer = layer;
4455 this.#markSortDirty();
4456 }
4457
4458 #markSortDirty ()
4459 {
4460 this.scene._sortDirty = true;
4461 }
4462
4463 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
4464 #activeLightingCenterChunk ()
4465 {
4466 const local = this.entities.get(this.localEntityId);
4467 if (!local)
4468 { return null; }
4469 return {
4470 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
4471 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
4472 };
4473 }
4474
4475 #isActiveLightingChunk (chunkX, chunkY)
4476 {
4477 const center = this.#activeLightingCenterChunk();
4478 if (!center)
4479 { return true; }
4480 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
4481 }
4482
4483 #isActiveLightingTile (tileX, tileY)
4484 {
4485 return this.#isActiveLightingChunk(
4486 Math.floor(tileX / CHUNK_SIZE),
4487 Math.floor(tileY / CHUNK_SIZE)
4488 );
4489 }
4490
4491 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
4492 #innerDynamicLights (activeLights)
4493 {
4494 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
4495 }
4496
4497 /**
4498 * Lights to simulate for one chunk.
4499 * Inner 3×3: mobile lights from the inner region + authored block lights that reach the chunk.
4500 * Outer ring: baked base + spill from any dynamic source that originates inside the 3×3
4501 * (lanterns, spells, and torches) so the boundary stays seamless.
4502 */
4503 #dynamicLightsForChunk (chunkX, chunkY, mobileLights, blockLights = [])
4504 {
4505 const center = this.#activeLightingCenterChunk();
4506 if (!center)
4507 { return [...mobileLights, ...blockLights]; }
4508 if (this.#isActiveLightingChunk(chunkX, chunkY))
4509 {
4510 const inner = this.#innerDynamicLights(mobileLights);
4511 const blocks = blockLights.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
4512 return [...inner, ...blocks];
4513 }
4514 const spill = this.#innerDynamicLights([...mobileLights, ...blockLights]);
4515 return spill.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
4516 }
4517
4518 #dynamicLightsForTile (tileX, tileY, mobileLights, blockLights = [])
4519 {
4520 return this.#dynamicLightsForChunk(
4521 Math.floor(tileX / CHUNK_SIZE),
4522 Math.floor(tileY / CHUNK_SIZE),
4523 mobileLights,
4524 blockLights
4525 );
4526 }
4527
4528 /** Authored torches/furnaces in chunks that can light the active 3×3 (or all chunks in editor). */
4529 #collectBlockLightsForShading ()
4530 {
4531 const center = this.#activeLightingCenterChunk();
4532 const maxRange = maxBlockLightRangeTiles();
4533 const halo = Math.ceil(maxRange / CHUNK_SIZE) + 1;
4534 const sources = [];
4535 if (!center)
4536 {
4537 for (const snapshot of this.chunks.values())
4538 { sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks)); }
4539 return sources;
4540 }
4541 for (let dy = -1 - halo; dy <= 1 + halo; dy++)
4542 {
4543 for (let dx = -1 - halo; dx <= 1 + halo; dx++)
4544 {
4545 const snapshot = this.chunks.get(`${center.chunkX + dx},${center.chunkY + dy}`);
4546 if (!snapshot?.blocks)
4547 { continue; }
4548 sources.push(...collectBlockLightSources(snapshot.chunkX, snapshot.chunkY, snapshot.blocks));
4549 }
4550 }
4551 return sources;
4552 }
4553
4554 #updateShade ()
4555 {
4556 const ambientDark = this.#ambientDarkness();
4557 const now = performance.now();
4558 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
4559
4560 const mobileLights = [...this.dynamicLights];
4561 for (const light of this.spellLights.values())
4562 {
4563 if (light.until <= now)
4564 { continue; }
4565 mobileLights.push({
4566 tileX: light.tileX,
4567 tileY: light.tileY,
4568 range: light.range,
4569 intensity: light.intensity
4570 });
4571 }
4572 for (const key of [...this.spellLights.keys()])
4573 {
4574 if (this.spellLights.get(key).until <= now)
4575 {
4576 const expired = this.spellLights.get(key);
4577 this.spellLights.delete(key);
4578 this.#invalidateNeighborLightmapCaches(
4579 Math.floor(expired.tileX / CHUNK_SIZE),
4580 Math.floor(expired.tileY / CHUNK_SIZE)
4581 );
4582 }
4583 }
4584 const activeDarks = [];
4585 for (const dark of this.spellDarks.values())
4586 {
4587 if (dark.until <= now)
4588 { continue; }
4589 activeDarks.push({
4590 tileX: dark.tileX,
4591 tileY: dark.tileY,
4592 range: dark.range,
4593 intensity: dark.intensity
4594 });
4595 }
4596 for (const key of [...this.spellDarks.keys()])
4597 {
4598 if (this.spellDarks.get(key).until <= now)
4599 {
4600 const expired = this.spellDarks.get(key);
4601 this.spellDarks.delete(key);
4602 this.#invalidateNeighborLightmapCaches(
4603 Math.floor(expired.tileX / CHUNK_SIZE),
4604 Math.floor(expired.tileY / CHUNK_SIZE)
4605 );
4606 }
4607 }
4608 this._activeSpellDarks = activeDarks;
4609 const tileSize = this.tileSize();
4610 const blindLight = this.#blindVisionLight();
4611 if (blindLight)
4612 { mobileLights.push(blindLight); }
4613 for (const entity of this.entities.values())
4614 {
4615 const range = entity.lightRadiusTiles ?? 0;
4616 if (range <= 0)
4617 { continue; }
4618 mobileLights.push({
4619 tileX: Math.floor(entity.visualX / tileSize),
4620 tileY: Math.floor(entity.visualY / tileSize),
4621 range,
4622 intensity: entity.lightIntensity ?? 1
4623 });
4624 }
4625 const blockLights = this.#collectBlockLightsForShading();
4626
4627 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
4628
4629 for (const objects of this.tiles.values())
4630 {
4631 if (objects._inViewport === false)
4632 { continue; }
4633 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, mobileLights, blockLights);
4634 objects.shadeAlpha = this.#tileShadeAlpha(objects, lights, lightOcclusion, ambientDark);
4635 }
4636
4637 for (const baked of this.bakedChunks.values())
4638 {
4639 if (baked._inViewport === false)
4640 { continue; }
4641 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, mobileLights, blockLights);
4642 this.#writeChunkLightmap(baked, lights, mobileLights, blockLights, lightOcclusion, ambientDark);
4643 // Lightmap stores visible light (1 − shade); shader applies darkness = 1 − lit.
4644 if (baked.groundObject?.renderer?.shaderUniforms)
4645 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = 1; }
4646 for (const object of baked.blockObjects ?? [])
4647 {
4648 if (object?.renderer?.shaderUniforms)
4649 { object.renderer.shaderUniforms.u_ambientDark = 1; }
4650 }
4651 }
4652
4653 const timeSec = now / 1000;
4654 for (const objects of this.tiles.values())
4655 {
4656 if (objects._inViewport === false)
4657 { continue; }
4658 if (objects.block)
4659 {
4660 if (objects.cliffGroundTop)
4661 {
4662 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4663 const localX = ((objects.tileX % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4664 const localY = ((objects.tileY % CHUNK_SIZE) + CHUNK_SIZE) % CHUNK_SIZE;
4665 this.#syncCliffGroundTopSprite(
4666 objects.block,
4667 objects.shadeAlpha,
4668 baked?.groundImage ?? null,
4669 localX,
4670 localY
4671 );
4672 }
4673 else
4674 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
4675 }
4676 if (objects.ground && isWaterGround(objects.groundTypeId))
4677 {
4678 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
4679 // Light intensity grid is visible light (1 − shade); water shader uses ambient=1.
4680 this.#syncGroundWaterFx(objects, 1, timeSec, baked);
4681 }
4682 else if (objects.ground)
4683 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
4684 }
4685
4686 for (const item of this.groundItems.values())
4687 {
4688 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
4689 this.#syncGroundItemSprite(item, alpha);
4690 }
4691 }
4692
4693 #tileLightSources (objects, activeLights, lightOcclusion)
4694 {
4695 // Inner 3×3: ignore baked (stale behind doors); outer ring keeps authored lightmaps.
4696 const useBaked = !this.#isActiveLightingTile(objects.tileX, objects.tileY);
4697 const baked = useBaked ? lightIntensity(objects.light ?? 0) : 0;
4698 const dynamic = dynamicLightAtTile(
4699 objects.tileX,
4700 objects.tileY,
4701 activeLights,
4702 lightOcclusion
4703 );
4704 const dark = dynamicDarknessAtTile(
4705 objects.tileX,
4706 objects.tileY,
4707 this._activeSpellDarks ?? [],
4708 lightOcclusion
4709 );
4710 return { lights: Math.max(baked, dynamic), dark };
4711 }
4712
4713 /** Shade 0–1: night ambient over unlit tiles, plus Dark spell dimming daylight/torches. */
4714 #tileShadeAlpha (objects, activeLights, lightOcclusion, ambientDark)
4715 {
4716 const { lights, dark } = this.#tileLightSources(objects, activeLights, lightOcclusion);
4717 return Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4718 }
4719
4720 #tileLightIntensity (objects, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4721 {
4722 return 1 - this.#tileShadeAlpha(objects, activeLights, lightOcclusion, ambientDark);
4723 }
4724
4725 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
4726 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion, ambientDark = this.#ambientDarkness())
4727 {
4728 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
4729 if (tileObjects)
4730 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion, ambientDark); }
4731 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4732 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4733 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4734 if (!snapshot)
4735 { return 1 - Math.min(1, Math.max(0, ambientDark)); }
4736 const localX = tileX - chunkX * CHUNK_SIZE;
4737 const localY = tileY - chunkY * CHUNK_SIZE;
4738 const index = localY * CHUNK_SIZE + localX;
4739 const useBaked = !this.#isActiveLightingTile(tileX, tileY);
4740 const bakedLit = useBaked ? lightIntensity(snapshot.light[index] ?? 0) : 0;
4741 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
4742 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
4743 const lights = Math.max(bakedLit, dynamic);
4744 const shade = Math.min(1, Math.max(0, ambientDark) * (1 - lights) + dark);
4745 return 1 - shade;
4746 }
4747
4748 /** True when ground or block on this tile occludes light rays (same rules as bake). */
4749 #tileOccludesLight (tileX, tileY)
4750 {
4751 const chunkX = Math.floor(tileX / CHUNK_SIZE);
4752 const chunkY = Math.floor(tileY / CHUNK_SIZE);
4753 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
4754 if (!snapshot)
4755 { return false; }
4756 const localX = tileX - chunkX * CHUNK_SIZE;
4757 const localY = tileY - chunkY * CHUNK_SIZE;
4758 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
4759 { return false; }
4760 const index = localY * CHUNK_SIZE + localX;
4761 const ground = normalizeGround(snapshot.grounds?.[index]);
4762 if (!isGroundPassable(ground.typeId))
4763 { return true; }
4764 return blockLightOcclusionForBlock(snapshot.blocks?.[index]) === LightOcclusion.solid;
4765 }
4766
4767 #fillChunkLightGrids (baked, mobileLights, blockLights, lightOcclusion, ambientDark)
4768 {
4769 const gridW = CHUNK_SIZE + 2;
4770 const gridSize = gridW * gridW;
4771 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
4772 { baked.lightIntensityGrid = new Float32Array(gridSize); }
4773 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
4774 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
4775 const grid = baked.lightIntensityGrid;
4776 const occlude = baked.lightOccludeGrid;
4777 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
4778 {
4779 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
4780 {
4781 const tileX = baked.chunkX * CHUNK_SIZE + lx;
4782 const tileY = baked.chunkY * CHUNK_SIZE + ly;
4783 const gi = (ly + 1) * gridW + (lx + 1);
4784 // Halo tiles may sit in the other lighting region (3×3 vs outer). Resolve
4785 // sources per tile so corner blends match the neighbour chunk's shading.
4786 const lights = this.#dynamicLightsForTile(tileX, tileY, mobileLights, blockLights);
4787 grid[gi] = this.#intensityAtTile(tileX, tileY, lights, lightOcclusion, ambientDark);
4788 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
4789 }
4790 }
4791 return { grid, occlude, gridW };
4792 }
4793
4794 #makeLightCornerSampler (grid, occlude, gridW)
4795 {
4796 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
4797 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
4798 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) => smoothLitCorner({
4799 homeLit: sample(homeLx, homeLy),
4800 homeBlocks: blocks(homeLx, homeLy),
4801 aLit: sample(aLx, aLy),
4802 aBlocks: blocks(aLx, aLy),
4803 bLit: sample(bLx, bLy),
4804 bBlocks: blocks(bLx, bLy),
4805 dLit: sample(dLx, dLy),
4806 dBlocks: blocks(dLx, dLy)
4807 });
4808 return { smoothCorner };
4809 }
4810
4811 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
4812 #tileLitCorners (baked, localX, localY)
4813 {
4814 const grid = baked?.lightIntensityGrid;
4815 const occlude = baked?.lightOccludeGrid;
4816 if (!grid?.length || !occlude?.length)
4817 { return null; }
4818 const gridW = CHUNK_SIZE + 2;
4819 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
4820 return {
4821 nw: smoothCorner(
4822 localX, localY,
4823 localX - 1, localY,
4824 localX, localY - 1,
4825 localX - 1, localY - 1
4826 ),
4827 ne: smoothCorner(
4828 localX, localY,
4829 localX + 1, localY,
4830 localX, localY - 1,
4831 localX + 1, localY - 1
4832 ),
4833 sw: smoothCorner(
4834 localX, localY,
4835 localX - 1, localY,
4836 localX, localY + 1,
4837 localX - 1, localY + 1
4838 ),
4839 se: smoothCorner(
4840 localX, localY,
4841 localX + 1, localY,
4842 localX, localY + 1,
4843 localX + 1, localY + 1
4844 )
4845 };
4846 }
4847
4848 #hashUint8Array (values)
4849 {
4850 let hash = 2166136261;
4851 for (let i = 0; i < values.length; i++)
4852 {
4853 hash ^= values[i];
4854 hash = Math.imul(hash, 16777619);
4855 }
4856 return hash >>> 0;
4857 }
4858
4859 #lightAffectsChunkBounds (light, chunkX, chunkY)
4860 {
4861 const minX = chunkX * CHUNK_SIZE - 1;
4862 const minY = chunkY * CHUNK_SIZE - 1;
4863 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
4864 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
4865 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
4866 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
4867 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
4868 }
4869
4870 #chunkLightmapCacheKey (baked, activeLights, ambientDark = this.#ambientDarkness())
4871 {
4872 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4873 if (!snapshot?.light)
4874 { return null; }
4875 const bakedHash = this.#hashUint8Array(snapshot.light);
4876 // Caller already scoped lights for this chunk (incl. 3×3 spill onto the outer ring).
4877 const lights = activeLights;
4878 const darks = this._activeSpellDarks ?? [];
4879 const mode = this.lightingMode === "simple" ? "s" : "f";
4880 const ambientKey = Math.round(Math.max(0, ambientDark) * 1000);
4881 let lightsKey = "";
4882 for (const light of lights)
4883 {
4884 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
4885 { continue; }
4886 lightsKey += `l${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
4887 }
4888 let darksKey = "";
4889 for (const dark of darks)
4890 {
4891 if (!this.#lightAffectsChunkBounds(dark, baked.chunkX, baked.chunkY))
4892 { continue; }
4893 darksKey += `d${dark.tileX},${dark.tileY},${dark.range},${dark.intensity ?? 1};`;
4894 }
4895 return `a:${mode}:${ambientKey}:${bakedHash}:${lightsKey}|${darksKey}`;
4896 }
4897
4898 #invalidateNeighborLightmapCaches (chunkX, chunkY)
4899 {
4900 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
4901 for (let dy = -2; dy <= 2; dy++)
4902 {
4903 for (let dx = -2; dx <= 2; dx++)
4904 {
4905 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
4906 if (baked)
4907 { baked.lightmapCacheKey = null; }
4908 }
4909 }
4910 }
4911
4912 /**
4913 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
4914 * occluding tiles stay flat and contribute 0 into others so light does not bleed
4915 * through a wall to the far side. Diagonals only when both cardinals are clear.
4916 * @param chunkLights Sources that affect this chunk (cache key + in-chunk samples).
4917 * @param mobileLights / blockLights Full lists so the ±1 halo can sample across the 3×3 boundary.
4918 */
4919 #writeChunkLightmap (
4920 baked,
4921 chunkLights,
4922 mobileLights,
4923 blockLights,
4924 lightOcclusion,
4925 ambientDark = this.#ambientDarkness()
4926 )
4927 {
4928 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4929 if (!snapshot)
4930 { return; }
4931 const cacheKey = this.#chunkLightmapCacheKey(baked, chunkLights, ambientDark);
4932 if (cacheKey && baked.lightmapCacheKey === cacheKey)
4933 { return; }
4934 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4935 const pixelCount = atlasPx * atlasPx * 4;
4936 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
4937 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
4938 const pixels = baked.lightmapPixels;
4939
4940 this.#fillChunkLightGrids(baked, mobileLights, blockLights, lightOcclusion, ambientDark);
4941 const simple = this.lightingMode === "simple";
4942
4943 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4944 {
4945 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4946 {
4947 const baseX = localX * SPRITE_SIZE_PX;
4948 const baseY = localY * SPRITE_SIZE_PX;
4949 if (simple)
4950 {
4951 const gridW = CHUNK_SIZE + 2;
4952 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
4953 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4954 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4955 {
4956 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4957 {
4958 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4959 pixels[offset] = value;
4960 pixels[offset + 1] = value;
4961 pixels[offset + 2] = value;
4962 pixels[offset + 3] = 255;
4963 }
4964 }
4965 continue;
4966 }
4967 const corners = this.#tileLitCorners(baked, localX, localY);
4968 const nw = corners.nw;
4969 const ne = corners.ne;
4970 const sw = corners.sw;
4971 const se = corners.se;
4972 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4973 {
4974 const v = (py + 0.5) / SPRITE_SIZE_PX;
4975 const left = nw + (sw - nw) * v;
4976 const right = ne + (se - ne) * v;
4977 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4978 {
4979 const u = (px + 0.5) / SPRITE_SIZE_PX;
4980 const intensity = left + (right - left) * u;
4981 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4982 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4983 pixels[offset] = value;
4984 pixels[offset + 1] = value;
4985 pixels[offset + 2] = value;
4986 pixels[offset + 3] = 255;
4987 }
4988 }
4989 }
4990 }
4991 const ctx = baked.lightmapCanvas.getContext("2d");
4992 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
4993 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4994 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
4995 baked.lightmapCacheKey = cacheKey;
4996 }
4997
4998 #updateSwipes (now)
4999 {
5000 this.swipes = this.swipes.filter((swipe) =>
5001 {
5002 if (swipe.lerp && swipe.started != null)
5003 {
5004 const durationMs = swipe.durationMs ?? 400;
5005 const t = Math.min(1, (now - swipe.started) / durationMs);
5006 const fromPivot = this.#projectileLaunchPoint(
5007 swipe.attackerId ?? null,
5008 swipe.fromTileX,
5009 swipe.fromTileY
5010 );
5011 const toPivot = this.#projectileEndPivot(swipe);
5012 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
5013 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
5014 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
5015 if (swipe.object?.transform)
5016 {
5017 swipe.object.transform.rotation = Math.atan2(
5018 toPivot.y - fromPivot.y,
5019 toPivot.x - fromPivot.x
5020 ) * (180 / Math.PI);
5021 }
5022 if (swipe.spellProjectile && swipe.tint)
5023 { this.#syncUnlitTintSprite(swipe.object, swipe.tint); }
5024 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
5025 if (!swipe.spellProjectile)
5026 {
5027 this.#applyPhysicalCombatFxDarkness(
5028 swipe.object,
5029 swipe.fromTileX,
5030 swipe.fromTileY,
5031 swipe.tileX,
5032 swipe.tileY,
5033 swipe.dualTint ?? null
5034 );
5035 }
5036 }
5037 else if (swipe.fromTileX != null && !swipe.spellProjectile)
5038 {
5039 this.#applyPhysicalCombatFxDarkness(
5040 swipe.object,
5041 swipe.fromTileX,
5042 swipe.fromTileY,
5043 swipe.tileX,
5044 swipe.tileY,
5045 swipe.dualTint ?? null
5046 );
5047 }
5048 if (swipe.fadeOpacity && swipe.started != null && swipe.object?.renderer)
5049 {
5050 const durationMs = swipe.durationMs ?? MELEE_SWIPE_MS;
5051 const t = Math.min(1, Math.max(0, (now - swipe.started) / durationMs));
5052 swipe.object.renderer.alpha = 1 - t;
5053 }
5054 if (swipe.until > now)
5055 { return true; }
5056 const onImpact = swipe.onImpact;
5057 swipe.onImpact = null;
5058 swipe.object?.destroy();
5059 if (typeof onImpact === "function")
5060 {
5061 try
5062 { onImpact(); }
5063 catch (_)
5064 { /* presentation only */ }
5065 }
5066 return false;
5067 });
5068 }
5069
5070 #projectileEndPivot (swipe)
5071 {
5072 if (swipe.trackTarget && swipe.targetId != null)
5073 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
5074 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
5075 }
5076
5077 /**
5078 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
5079 */
5080 #projectileLaunchPoint (entityId, tileX, tileY)
5081 {
5082 const entity = entityId != null ? this.entities.get(entityId) : null;
5083 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
5084 {
5085 const zoom = this.zoom;
5086 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
5087 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
5088 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
5089 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
5090 return {
5091 x: pivotX,
5092 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
5093 };
5094 }
5095 return tilePivot(tileX, tileY, this.tileSize());
5096 }
5097
5098 /**
5099 * Aim point: sprite centre for creatures, tile centre for tile targets.
5100 */
5101 #projectileAimPoint (entityId, tileX, tileY)
5102 {
5103 const entity = entityId != null ? this.entities.get(entityId) : null;
5104 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
5105 {
5106 const zoom = this.zoom;
5107 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
5108 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
5109 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
5110 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
5111 }
5112 return tilePivot(tileX, tileY, this.tileSize());
5113 }
5114
5115 #updateDamageNumbers (now)
5116 {
5117 const layer = this.damageNumbersEl;
5118 if (!layer)
5119 { return; }
5120 this.damageFloats = this.damageFloats.filter((entry) =>
5121 {
5122 const elapsed = now - entry.started;
5123 if (elapsed >= DAMAGE_FLOAT_MS)
5124 {
5125 entry.element?.remove();
5126 return false;
5127 }
5128 const entity = this.entities.get(entry.entityId);
5129 if (!entity)
5130 {
5131 entry.element?.remove();
5132 return false;
5133 }
5134 if (!entry.element)
5135 {
5136 entry.element = document.createElement("span");
5137 entry.element.className = "damage-number";
5138 entry.element.textContent = String(entry.damage);
5139 layer.append(entry.element);
5140 }
5141 const anchor = this.nametagAnchor(entity);
5142 if (!anchor)
5143 { return true; }
5144 const t = elapsed / DAMAGE_FLOAT_MS;
5145 entry.element.style.left = `${anchor.x}px`;
5146 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
5147 entry.element.style.opacity = String(1 - t);
5148 return true;
5149 });
5150 }
5151
5152 #updateSkillLevelFloats (now)
5153 {
5154 const layer = this.skillLevelFloatsEl;
5155 if (!layer)
5156 { return; }
5157 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
5158 {
5159 const elapsed = now - entry.started;
5160 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
5161 {
5162 entry.element?.remove();
5163 return false;
5164 }
5165 const entity = this.entities.get(entry.entityId);
5166 if (!entity)
5167 {
5168 entry.element?.remove();
5169 return false;
5170 }
5171 if (!entry.element)
5172 {
5173 const root = document.createElement("div");
5174 root.className = "skill-level-float";
5175
5176 const levelEl = document.createElement("div");
5177 levelEl.className = "skill-level-float-level";
5178 levelEl.textContent = `↑${entry.level}↑`;
5179
5180 const icon = document.createElement("img");
5181 icon.className = "skill-level-float-icon";
5182 icon.src = entry.icon;
5183 icon.alt = entry.displayName || "";
5184
5185 root.append(levelEl, icon);
5186 entry.element = root;
5187 layer.append(entry.element);
5188 }
5189 const anchor = this.nametagAnchor(entity);
5190 if (!anchor)
5191 { return true; }
5192 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
5193 entry.element.style.left = `${anchor.x}px`;
5194 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
5195 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
5196 return true;
5197 });
5198 }
5199
5200 #syncBloomLayer ()
5201 {
5202 if (!this.bloomEnabled)
5203 {
5204 this.scene.setLayers([{ name: "default" }]);
5205 return;
5206 }
5207 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
5208 this.scene.setLayers([
5209 { name: "default" },
5210 {
5211 name: RENDER_LAYER_BLOOM,
5212 composite: "add",
5213 postShaders: Shader.getBloomPostChain({
5214 threshold: settings.bloomThreshold,
5215 softKnee: settings.bloomSoftKnee,
5216 intensity: settings.bloomIntensity,
5217 blurSize: settings.bloomBlurSize,
5218 saturation: settings.bloomSaturation,
5219 colorPreserve: settings.bloomColorPreserve,
5220 dilate: settings.bloomDilate,
5221 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
5222 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
5223 })
5224 }
5225 ]);
5226 }
5227}
5228
5229export function nightFactor (hour, nightDarkness = 0.72)
5230{
5231 const peak = Math.min(1, Math.max(0, nightDarkness));
5232 if (hour >= 8 && hour <= 16)
5233 { return 0; }
5234 if (hour >= 22 || hour <= 5)
5235 { return peak; }
5236 if (hour < 8)
5237 { return lerp(peak, 0, (hour - 5) / 3); }
5238 return lerp(0, peak, (hour - 16) / 6);
5239}
5240
5241function bodySpriteName (sex)
5242{
5243 const key = sex === "female" ? "player-body-female" : "player-body-male";
5244 return spriteImageName("character", key, key);
5245}
5246
5247function lerp (a, b, t)
5248{
5249 return a + (b - a) * Math.min(1, Math.max(0, t));
5250}
5251
5252function makeLightmapCanvas (size)
5253{
5254 const canvas = document.createElement("canvas");
5255 canvas.width = size;
5256 canvas.height = size;
5257 return canvas;
5258}
5259
5260function copyCanvas (source, dest)
5261{
5262 const ctx = dest.getContext("2d");
5263 ctx.imageSmoothingEnabled = false;
5264 ctx.clearRect(0, 0, dest.width, dest.height);
5265 ctx.drawImage(source, 0, 0);
5266}
5267
5268function drawHpBar (canvas, current, max)
5269{
5270 const ctx = canvas.getContext("2d");
5271 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
5272 ctx.fillStyle = "#000000";
5273 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
5274 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
5275 const fillW = Math.round(12 * ratio);
5276 if (fillW > 0)
5277 {
5278 ctx.fillStyle = "#ff0000";
5279 ctx.fillRect(1, 1, fillW, 2);
5280 }
5281}