BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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