BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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