BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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