BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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