BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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