BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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