BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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