BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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