BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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