BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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