BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 124.3 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 const def = itemDefinition(payload.itemId);
1137 item.dualTint = def?.iconTintFromTier ? null : resolveItemDualTint(stack, def);
1138 item.tintColor = item.dualTint ? null : resolveItemTint(stack, def);
1139 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1140 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
1141 }
1142
1143 despawnGroundItem (groundItemId)
1144 {
1145 const item = this.groundItems.get(groundItemId);
1146 if (!item)
1147 { return; }
1148 item.object?.destroy();
1149 this.groundItems.delete(groundItemId);
1150 }
1151
1152 groundItemAtTile (tileX, tileY)
1153 {
1154 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1155 }
1156
1157 groundItemsAtTile (tileX, tileY)
1158 {
1159 const items = [];
1160 for (const item of this.groundItems.values())
1161 {
1162 if (item.tileX === tileX && item.tileY === tileY)
1163 { items.push(item); }
1164 }
1165 return items;
1166 }
1167
1168 entitiesAtTile (tileX, tileY)
1169 {
1170 const matches = [];
1171 for (const entity of this.entities.values())
1172 {
1173 if (entity.tileX === tileX && entity.tileY === tileY)
1174 { matches.push(entity); }
1175 }
1176 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1177 return matches;
1178 }
1179
1180 setZoom (zoom, limits = { min: 2, max: 4 })
1181 {
1182 const min = limits.min ?? 1;
1183 const max = limits.max ?? 4;
1184 this.zoom = Math.min(max, Math.max(min, zoom));
1185 for (const snapshot of this.chunks.values())
1186 { this.#relayoutChunk(snapshot); }
1187 const size = this.tileSize();
1188 for (const entity of this.entities.values())
1189 {
1190 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1191 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1192 entity.fromX = entity.visualX;
1193 entity.fromY = entity.visualY;
1194 entity.targetX = entity.visualX;
1195 entity.targetY = entity.visualY;
1196 entity.lerpStarted = null;
1197 this.#placeEntity(entity);
1198 }
1199 for (const item of this.groundItems.values())
1200 {
1201 const pivot = tilePivot(item.tileX, item.tileY, size);
1202 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1203 }
1204 this.#rebuildAllEdges();
1205 this.#relayoutEditorSpawners();
1206 this.#relayoutSpawnRangeHighlight();
1207 this.#relayoutSpellTargetHighlight();
1208 }
1209
1210 tileSize ()
1211 {
1212 return SPRITE_SIZE_PX * this.zoom;
1213 }
1214
1215 screenToTile (mouseX, mouseY)
1216 {
1217 const size = this.tileSize();
1218 const worldX = mouseX - this.scene.cameraPosition.x;
1219 const worldY = mouseY - this.scene.cameraPosition.y;
1220 return {
1221 tileX: Math.floor(worldX / size),
1222 tileY: Math.floor(worldY / size)
1223 };
1224 }
1225
1226 entityAtScreen (mouseX, mouseY)
1227 {
1228 let best = null;
1229 let bestLayer = -Infinity;
1230 for (const entity of this.entities.values())
1231 {
1232 const box = this.#entityScreenBox(entity);
1233 if (!box)
1234 { continue; }
1235 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1236 {
1237 const layer = entity.object?.layer ?? 0;
1238 if (layer >= bestLayer)
1239 {
1240 best = entity;
1241 bestLayer = layer;
1242 }
1243 }
1244 }
1245 return best;
1246 }
1247
1248 nametagAnchor (entity)
1249 {
1250 const box = this.#entityScreenBox(entity);
1251 if (!box)
1252 { return null; }
1253 return { x: (box.left + box.right) / 2, y: box.top };
1254 }
1255
1256 #entityScreenBox (entity)
1257 {
1258 const object = entity?.object;
1259 if (!object)
1260 { return null; }
1261 const size = object.transform.size;
1262 const x = object.transform.position.x + this.scene.cameraPosition.x;
1263 const y = object.transform.position.y + this.scene.cameraPosition.y;
1264 return {
1265 left: x - size.x / 2,
1266 right: x + size.x / 2,
1267 top: y - size.y / 2,
1268 bottom: y + size.y / 2
1269 };
1270 }
1271
1272 update (deltaTime)
1273 {
1274 const now = performance.now();
1275 const size = this.tileSize();
1276 this.#refreshStackTargets();
1277 for (const entity of this.entities.values())
1278 {
1279 const target = entity.targetX != null && entity.targetY != null
1280 ? { x: entity.targetX, y: entity.targetY }
1281 : tilePivot(entity.tileX, entity.tileY, size);
1282 if (entity.lerpStarted != null)
1283 {
1284 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1285 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1286 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1287 if (t >= 1)
1288 { entity.lerpStarted = null; }
1289 }
1290 else
1291 {
1292 entity.visualX = target.x;
1293 entity.visualY = target.y;
1294 }
1295 this.#updateStackOffset(entity, now);
1296 this.#updateShove(entity, now, size);
1297 this.#expireGatherToolOverlay(entity, now);
1298 this.#placeEntity(entity, now);
1299 }
1300
1301 this.#updateSwipes(now);
1302 this.#updateDamageNumbers(now);
1303 this.#updateSkillLevelFloats(now);
1304 this.#centerCamera();
1305 this.#cullOffscreenDrawables();
1306 this.#updateShade(deltaTime);
1307 }
1308
1309 /**
1310 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1311 * Stable assignment by entityId; free-flight entities stay unshifted.
1312 */
1313 #refreshStackTargets ()
1314 {
1315 const byTile = new Map();
1316 for (const entity of this.entities.values())
1317 {
1318 if (entity.freeFlight)
1319 {
1320 entity.stackTargetX = 0;
1321 entity.stackTargetY = 0;
1322 continue;
1323 }
1324 const key = `${entity.tileX},${entity.tileY}`;
1325 let list = byTile.get(key);
1326 if (!list)
1327 {
1328 list = [];
1329 byTile.set(key, list);
1330 }
1331 list.push(entity);
1332 }
1333 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1334 for (const list of byTile.values())
1335 {
1336 if (list.length <= 1)
1337 {
1338 for (const entity of list)
1339 {
1340 entity.stackTargetX = 0;
1341 entity.stackTargetY = 0;
1342 }
1343 continue;
1344 }
1345 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1346 const n = list.length;
1347 for (let i = 0; i < n; i++)
1348 {
1349 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1350 list[i].stackTargetX = Math.cos(angle) * radius;
1351 list[i].stackTargetY = Math.sin(angle) * radius;
1352 }
1353 }
1354 }
1355
1356 #updateStackOffset (entity, now)
1357 {
1358 const tx = entity.stackTargetX ?? 0;
1359 const ty = entity.stackTargetY ?? 0;
1360 const cx = entity.stackOffsetX ?? 0;
1361 const cy = entity.stackOffsetY ?? 0;
1362 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1363 {
1364 entity.stackFromX = cx;
1365 entity.stackFromY = cy;
1366 entity.stackLerpToX = tx;
1367 entity.stackLerpToY = ty;
1368 entity.stackLerpStarted = now;
1369 }
1370 if (entity.stackLerpStarted == null)
1371 {
1372 entity.stackOffsetX = tx;
1373 entity.stackOffsetY = ty;
1374 return;
1375 }
1376 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1377 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1378 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1379 if (t >= 1)
1380 {
1381 entity.stackOffsetX = tx;
1382 entity.stackOffsetY = ty;
1383 entity.stackLerpStarted = null;
1384 }
1385 }
1386
1387 #updateShove (entity, now, tileSize)
1388 {
1389 if (!entity.shove)
1390 {
1391 entity.shoveOffsetX = 0;
1392 entity.shoveOffsetY = 0;
1393 return;
1394 }
1395 const elapsed = now - entity.shove.started;
1396 const t = Math.min(1, elapsed / entity.shove.durationMs);
1397 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1398 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1399 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1400 const dist = Math.hypot(dx, dy) || 1;
1401 const ux = dx / dist;
1402 const uy = dy / dist;
1403 let phase;
1404 if (t < 0.45)
1405 { phase = t / 0.45; }
1406 else
1407 { phase = 1 - (t - 0.45) / 0.55; }
1408 entity.shoveOffsetX = ux * maxDist * phase;
1409 entity.shoveOffsetY = uy * maxDist * phase;
1410 if (t >= 1)
1411 { entity.shove = null; }
1412 }
1413
1414 spawnCombatSwing (payload)
1415 {
1416 const attacker = this.entities.get(payload.attackerId);
1417 const target = this.entities.get(payload.targetId);
1418 if (!attacker || !target)
1419 { return; }
1420 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1421 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1422 const tx = target.visualX + (target.stackOffsetX ?? 0);
1423 const ty = target.visualY + (target.stackOffsetY ?? 0);
1424 this.#applyShove(attacker, tx, ty);
1425 const midX = (ax + tx) / 2;
1426 const midY = (ay + ty) / 2;
1427 const sortY = Math.max(ay, ty) + 0.02;
1428 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1429 const spriteName = "fx:melee-swipe:melee-swipe";
1430 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1431 if (object.transform)
1432 { object.transform.rotation = angle; }
1433 this.scene.addObject(object);
1434 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1435 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1436 this.swipes.push({
1437 object,
1438 until: performance.now() + 500,
1439 fromTileX: payload.fromTileX,
1440 fromTileY: payload.fromTileY,
1441 tileX: payload.tileX,
1442 tileY: payload.tileY
1443 });
1444 }
1445
1446 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1447 spawnGatherSwing (payload)
1448 {
1449 const attacker = this.entities.get(payload.attackerId);
1450 if (!attacker)
1451 { return; }
1452 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1453 this.#applyShove(attacker, pivot.x, pivot.y);
1454 if (payload.toolItemId != null)
1455 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1456 }
1457
1458 #applyShove (entity, targetVisualX, targetVisualY)
1459 {
1460 entity.shove = {
1461 startVisualX: entity.visualX,
1462 startVisualY: entity.visualY,
1463 targetVisualX,
1464 targetVisualY,
1465 started: performance.now(),
1466 durationMs: SHOVE_MS
1467 };
1468 }
1469
1470 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1471 spawnPhysicalProjectileFx (payload)
1472 {
1473 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1474 const image = this.game.images[spriteName];
1475 if (!image)
1476 { return; }
1477 const dualTint = this.#dualTintFromPayload(payload);
1478 const fromPivot = this.#projectileLaunchPoint(
1479 payload.attackerId ?? null,
1480 payload.fromTileX,
1481 payload.fromTileY
1482 );
1483 const toPivot = this.#projectileAimPoint(
1484 payload.targetId ?? null,
1485 payload.tileX,
1486 payload.tileY
1487 );
1488 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1489 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1490 const object = new GameObject(0, 0, image, SORT_FX);
1491 if (object.transform)
1492 { object.transform.rotation = angle; }
1493 this.scene.addObject(object);
1494 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1495 this.#applyPhysicalCombatFxDarkness(
1496 object,
1497 payload.fromTileX,
1498 payload.fromTileY,
1499 payload.tileX,
1500 payload.tileY,
1501 dualTint
1502 );
1503 const started = performance.now();
1504 const durationMs = payload.durationMs ?? 400;
1505 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1506 this.swipes.push({
1507 object,
1508 until: started + durationMs,
1509 started,
1510 durationMs,
1511 lerp: true,
1512 dualTint,
1513 fromTileX: payload.fromTileX,
1514 fromTileY: payload.fromTileY,
1515 tileX: payload.tileX,
1516 tileY: payload.tileY,
1517 attackerId: payload.attackerId ?? null,
1518 targetId: payload.targetId ?? null,
1519 trackTarget,
1520 onImpact: null
1521 });
1522 }
1523
1524 /** Bloom-layer spell projectiles — unlit, animated travel. */
1525 spawnSpellProjectileFx (payload)
1526 {
1527 const baseSprite = payload.sprite ?? "fx:projectile:spell-light";
1528 const image = this.#spellProjectileImage(baseSprite, 0);
1529 if (!image)
1530 { return; }
1531 const fromPivot = this.#projectileLaunchPoint(
1532 payload.casterId ?? null,
1533 payload.fromTileX,
1534 payload.fromTileY
1535 );
1536 const toPivot = this.#projectileAimPoint(
1537 payload.targetId ?? null,
1538 payload.tileX,
1539 payload.tileY
1540 );
1541 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1542 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1543 const object = new GameObject(0, 0, image, SORT_FX);
1544 object.renderer.layer = RENDER_LAYER_BLOOM;
1545 this.#markUnlit(object);
1546 if (object.transform)
1547 { object.transform.rotation = angle; }
1548 this.scene.addObject(object);
1549 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1550 const started = performance.now();
1551 const durationMs = payload.durationMs ?? 2000;
1552 this.swipes.push({
1553 object,
1554 until: started + durationMs,
1555 started,
1556 durationMs,
1557 lerp: true,
1558 spellProjectile: true,
1559 baseSprite,
1560 fromTileX: payload.fromTileX,
1561 fromTileY: payload.fromTileY,
1562 tileX: payload.tileX,
1563 tileY: payload.tileY,
1564 attackerId: payload.casterId ?? null,
1565 targetId: payload.targetId ?? null,
1566 trackTarget: payload.targetId != null,
1567 onImpact: null
1568 });
1569 }
1570
1571 spawnSpellFizzleFx (_payload)
1572 {
1573 // Visual-only fizzle; no dynamic light (cast flashes skip lightmap rebakes).
1574 }
1575
1576 /**
1577 * Authoritative Light-spell tile light from the server.
1578 * Kept out of short-lived `dynamicLights` so duration follows `remainingMs` updates.
1579 */
1580 setSpellLight (payload)
1581 {
1582 const key = `${payload.tileX},${payload.tileY}`;
1583 this.spellLights.set(key, {
1584 tileX: payload.tileX,
1585 tileY: payload.tileY,
1586 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1587 range: payload.rangeTiles ?? 6,
1588 intensity: payload.intensity ?? 0.88
1589 });
1590 }
1591
1592 removeSpellLight (payload)
1593 {
1594 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1595 }
1596
1597 setSpellDark (payload)
1598 {
1599 const key = `${payload.tileX},${payload.tileY}`;
1600 this.spellDarks.set(key, {
1601 tileX: payload.tileX,
1602 tileY: payload.tileY,
1603 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1604 range: payload.rangeTiles ?? 6,
1605 intensity: payload.intensity ?? 0.88
1606 });
1607 }
1608
1609 removeSpellDark (payload)
1610 {
1611 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
1612 }
1613
1614 #spellProjectileImage (baseSprite, frameIndex)
1615 {
1616 const frame = Math.max(0, Math.min(2, frameIndex | 0));
1617 const stem = baseSprite.split(":").pop() ?? "spell-light";
1618 const names = [
1619 `${baseSprite}-${frame}`,
1620 `fx:projectile:${stem}-${frame}`,
1621 baseSprite,
1622 `fx:projectile:${stem}`
1623 ];
1624 for (const name of names)
1625 {
1626 if (this.game.images[name])
1627 { return this.game.images[name]; }
1628 }
1629 return null;
1630 }
1631
1632 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1633 {
1634 this.dynamicLights.push({
1635 tileX: Math.floor(worldX),
1636 tileY: Math.floor(worldY),
1637 range: radiusTiles,
1638 intensity,
1639 until: performance.now() + durationMs
1640 });
1641 }
1642
1643 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1644 {
1645 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1646 if (!snapshot)
1647 { return; }
1648 const index = localY * CHUNK_SIZE + localX;
1649 if (ground !== undefined)
1650 { snapshot.grounds[index] = ground; }
1651 if (block !== undefined)
1652 { snapshot.blocks[index] = block; }
1653 if (light !== undefined)
1654 { snapshot.light[index] = light; }
1655 const tileX = chunkX * CHUNK_SIZE + localX;
1656 const tileY = chunkY * CHUNK_SIZE + localY;
1657 if (block !== undefined)
1658 {
1659 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
1660 this.#drawTile(tileX, tileY);
1661 return;
1662 }
1663 this.#scheduleChunkRebuild(snapshot);
1664 if (ground !== undefined)
1665 { this.#drawTile(tileX, tileY); }
1666 }
1667
1668 /**
1669 * Editor-only mob markers for authored spawners (invisible during play).
1670 * @param {number} chunkX
1671 * @param {number} chunkY
1672 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
1673 * @param {(mobTypeId: string) => string} resolveSprite
1674 */
1675 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1676 {
1677 const prefix = `${chunkX},${chunkY}:`;
1678 for (const [key, entry] of [...this.editorSpawners.entries()])
1679 {
1680 if (!key.startsWith(prefix))
1681 { continue; }
1682 entry.object?.destroy();
1683 this.editorSpawners.delete(key);
1684 }
1685 for (const spawner of spawners ?? [])
1686 {
1687 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1688 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1689 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
1690 if (!spriteName)
1691 { continue; }
1692 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1693 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
1694 if (!object)
1695 { continue; }
1696 object.renderer.alpha = 0.85;
1697 const pivot = tilePivot(tileX, tileY, this.tileSize());
1698 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1699 this.#markUnlit(object);
1700 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
1701 }
1702 }
1703
1704 clearEditorSpawners ()
1705 {
1706 for (const entry of this.editorSpawners.values())
1707 { entry.object?.destroy(); }
1708 this.editorSpawners.clear();
1709 }
1710
1711 #relayoutEditorSpawners ()
1712 {
1713 const size = this.tileSize();
1714 for (const entry of this.editorSpawners.values())
1715 {
1716 if (!entry.object)
1717 { continue; }
1718 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1719 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1720 }
1721 }
1722
1723 /**
1724 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
1725 */
1726 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
1727 {
1728 const spawnRadius = Math.max(0, spawnRange | 0);
1729 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
1730 if (this.spawnRangeHighlight
1731 && this.wanderRangeHighlight
1732 && this.spawnRangeHighlight.tileX === tileX
1733 && this.spawnRangeHighlight.tileY === tileY
1734 && this.spawnRangeHighlight.range === spawnRadius
1735 && this.wanderRangeHighlight.range === wanderRadius)
1736 {
1737 this.#relayoutSpawnRangeHighlight();
1738 return;
1739 }
1740 this.clearSpawnRangeHighlight();
1741 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
1742 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
1743 if (wanderObject)
1744 {
1745 this.#markUnlit(wanderObject);
1746 wanderObject.renderer.alpha = 1;
1747 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1748 }
1749 if (spawnObject)
1750 {
1751 this.#markUnlit(spawnObject);
1752 spawnObject.renderer.alpha = 1;
1753 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1754 }
1755 this.#relayoutSpawnRangeHighlight();
1756 }
1757
1758 clearSpawnRangeHighlight ()
1759 {
1760 this.spawnRangeHighlight?.object?.destroy();
1761 this.wanderRangeHighlight?.object?.destroy();
1762 this.spawnRangeHighlight = null;
1763 this.wanderRangeHighlight = null;
1764 }
1765
1766 setSpellTargetHighlight (tileX, tileY, inRange = true)
1767 {
1768 if (
1769 this.spellTargetHighlight
1770 && this.spellTargetHighlight.tileX === tileX
1771 && this.spellTargetHighlight.tileY === tileY
1772 && this.spellTargetHighlight.inRange === inRange
1773 )
1774 {
1775 this.#relayoutSpellTargetHighlight();
1776 return;
1777 }
1778 this.clearSpellTargetHighlight();
1779 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1780 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1781 if (!object)
1782 { return; }
1783 this.#markUnlit(object);
1784 object.renderer.alpha = 1;
1785 this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1786 this.#relayoutSpellTargetHighlight();
1787 }
1788
1789 clearSpellTargetHighlight ()
1790 {
1791 this.spellTargetHighlight?.object?.destroy();
1792 this.spellTargetHighlight = null;
1793 }
1794
1795 #relayoutSpellTargetHighlight ()
1796 {
1797 const highlight = this.spellTargetHighlight;
1798 if (!highlight?.object)
1799 { return; }
1800 const size = this.tileSize();
1801 const left = highlight.tileX * size;
1802 const top = highlight.tileY * size;
1803 highlight.object.transform.position.x = left + size / 2;
1804 highlight.object.transform.position.y = top + size / 2;
1805 highlight.object.transform.size = new vector(size, size);
1806 highlight.object.layer = LAYER_EDGE - 1;
1807 this.#markSortDirty();
1808 }
1809
1810 #relayoutSpawnRangeHighlight ()
1811 {
1812 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1813 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
1814 }
1815
1816 #layoutRangeOverlay (highlight, layer)
1817 {
1818 if (!highlight?.object)
1819 { return; }
1820 const size = this.tileSize();
1821 const side = (2 * highlight.range + 1) * size;
1822 const left = (highlight.tileX - highlight.range) * size;
1823 const top = (highlight.tileY - highlight.range) * size;
1824 highlight.object.transform.position.x = left + side / 2;
1825 highlight.object.transform.position.y = top + side / 2;
1826 highlight.object.transform.size = new vector(side, side);
1827 highlight.object.layer = layer;
1828 this.#markSortDirty();
1829 }
1830
1831 setTilePreview (tileX, tileY, override)
1832 {
1833 const next = { tileX, tileY, ...override };
1834 if (this.#previewEqual(this.preview, next))
1835 { return; }
1836 const previous = this.preview;
1837 this.preview = next;
1838 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1839 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1840 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
1841 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1842 {
1843 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
1844 if (prevKey !== `${chunkX},${chunkY}`)
1845 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
1846 }
1847 }
1848
1849 clearTilePreview ()
1850 {
1851 if (!this.preview)
1852 { return; }
1853 const previous = this.preview;
1854 this.preview = null;
1855 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1856 this.#scheduleChunkRebuild(snapshot);
1857 }
1858
1859 #lerpMs (gait)
1860 {
1861 const walk = this.settings.walkTilesPerSecond || 2;
1862 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1863 return seconds * 1000;
1864 }
1865
1866 #centerCamera ()
1867 {
1868 if (!this.followPlayer)
1869 { return; }
1870 const local = this.entities.get(this.localEntityId);
1871 if (!local)
1872 { return; }
1873 const x = local.visualX + (local.stackOffsetX ?? 0);
1874 const y = local.visualY + (local.stackOffsetY ?? 0);
1875 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1876 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
1877 }
1878
1879 /**
1880 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
1881 * Tiles fully outside this rect are not drawn.
1882 */
1883 #drawBounds ()
1884 {
1885 const pad = this.tileSize() * 0.5;
1886 const camX = this.scene.cameraPosition.x;
1887 const camY = this.scene.cameraPosition.y;
1888 const w = this.scene.real_size.x;
1889 const h = this.scene.real_size.y;
1890 return {
1891 left: -camX - pad,
1892 right: -camX + w + pad,
1893 top: -camY - pad,
1894 bottom: -camY + h + pad
1895 };
1896 }
1897
1898 #rectIntersects (left, top, right, bottom, bounds)
1899 {
1900 return right >= bounds.left
1901 && left <= bounds.right
1902 && bottom >= bounds.top
1903 && top <= bounds.bottom;
1904 }
1905
1906 #setRendererVisible (object, visible)
1907 {
1908 if (object?.renderer)
1909 { object.renderer.visible = !!visible; }
1910 }
1911
1912 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1913 #cullOffscreenDrawables ()
1914 {
1915 const bounds = this.#drawBounds();
1916 const size = this.tileSize();
1917
1918 for (const baked of this.bakedChunks.values())
1919 {
1920 const left = baked.chunkX * CHUNK_SIZE * size;
1921 const top = baked.chunkY * CHUNK_SIZE * size;
1922 const chunkPx = CHUNK_SIZE * size;
1923 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1924 this.#setRendererVisible(baked.groundObject, chunkVisible);
1925 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1926 baked._inViewport = chunkVisible;
1927 for (let row = 0; row < CHUNK_SIZE; row++)
1928 {
1929 const rowTop = top + row * size;
1930 const rowVisible = chunkVisible && this.#rectIntersects(
1931 left, rowTop, left + chunkPx, rowTop + size, bounds
1932 );
1933 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1934 }
1935 }
1936
1937 for (const objects of this.tiles.values())
1938 {
1939 const left = objects.tileX * size;
1940 const top = objects.tileY * size;
1941 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1942 objects._inViewport = visible;
1943 this.#setRendererVisible(objects.ground, visible);
1944 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1945 this.#setRendererVisible(objects.block, visible);
1946 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1947 if (objects.waterEdges)
1948 {
1949 for (const edge of Object.values(objects.waterEdges))
1950 { this.#setRendererVisible(edge, visible); }
1951 }
1952 }
1953 }
1954
1955 #upsertEntity (payload)
1956 {
1957 const size = this.tileSize();
1958 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1959 let entity = this.entities.get(payload.entityId);
1960 if (!entity)
1961 {
1962 const spriteName = payload.layers?.[0]?.sprite
1963 ?? payload.sprite
1964 ?? bodySpriteName(payload.sex);
1965 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
1966 this.scene.addObject(object);
1967 this.#startIdleAnimation(object);
1968 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
1969 this.entities.set(payload.entityId, entity);
1970 }
1971 entity.entityId = payload.entityId;
1972 entity.tileX = payload.tileX;
1973 entity.tileY = payload.tileY;
1974 entity.gait = payload.gait;
1975 entity.sex = payload.sex ?? entity.sex;
1976 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1977 entity.accountId = payload.accountId ?? entity.accountId ?? null;
1978 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1979 if (payload.level != null)
1980 { entity.level = payload.level | 0; }
1981 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1982 entity.canFight = payload.canFight != null
1983 ? !!payload.canFight
1984 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1985 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1986 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
1987 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1988 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1989 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1990 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1991 if (payload.visualScale != null)
1992 { entity.visualScale = Number(payload.visualScale) || 1; }
1993 else if (entity.visualScale == null)
1994 { entity.visualScale = 1; }
1995 if (payload.health != null)
1996 { entity.health = payload.health; }
1997 if (payload.maxHealth != null)
1998 { entity.maxHealth = payload.maxHealth; }
1999 if (payload.skullValue != null)
2000 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2001 else if (entity.skullValue == null)
2002 { entity.skullValue = 0; }
2003 if (payload.firstName)
2004 { entity.firstName = payload.firstName; }
2005 if (payload.lastName)
2006 { entity.lastName = payload.lastName; }
2007 entity.firstName = entity.firstName ?? "";
2008 entity.lastName = entity.lastName ?? "";
2009 if (payload.worldX != null && payload.worldY != null)
2010 {
2011 entity.worldX = payload.worldX;
2012 entity.worldY = payload.worldY;
2013 entity.visualX = payload.worldX * size;
2014 entity.visualY = payload.worldY * size;
2015 entity.targetX = entity.visualX;
2016 entity.targetY = entity.visualY;
2017 }
2018 else
2019 {
2020 entity.visualX = pivot.x;
2021 entity.visualY = pivot.y;
2022 entity.targetX = pivot.x;
2023 entity.targetY = pivot.y;
2024 }
2025 entity.fromX = entity.visualX;
2026 entity.fromY = entity.visualY;
2027 if (payload.layers)
2028 { this.#applyLayers(entity, payload.layers); }
2029 this.#syncHpBar(entity);
2030 this.#syncSkullMarker(entity);
2031 this.#placeEntity(entity, performance.now());
2032 }
2033
2034 #applyLayers (entity, layers)
2035 {
2036 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2037 this.#rebuildOverlays(entity);
2038 }
2039
2040 #setGatherToolOverlay (entity, toolItemId)
2041 {
2042 entity.gatherToolItemId = toolItemId;
2043 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2044 this.#rebuildOverlays(entity);
2045 this.#placeEntity(entity, performance.now());
2046 }
2047
2048 #expireGatherToolOverlay (entity, now)
2049 {
2050 if (entity.gatherToolItemId == null)
2051 { return; }
2052 if ((entity.gatherToolUntil ?? 0) > now)
2053 { return; }
2054 entity.gatherToolItemId = null;
2055 entity.gatherToolUntil = 0;
2056 this.#rebuildOverlays(entity);
2057 }
2058
2059 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2060 #layersForDisplay (entity)
2061 {
2062 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2063 const toolId = entity.gatherToolItemId;
2064 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2065 { return layers; }
2066 const equip = itemEquipSprite(toolId);
2067 if (!equip || !this.game.images[equip])
2068 { return layers; }
2069 const replacement = {
2070 sprite: equip,
2071 itemId: toolId,
2072 tint: resolveEquipTint(toolId)
2073 };
2074 for (let index = layers.length - 1; index >= 1; index--)
2075 {
2076 const def = itemDefinition(layers[index].itemId);
2077 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2078 {
2079 layers[index] = replacement;
2080 return layers;
2081 }
2082 }
2083 layers.push(replacement);
2084 return layers;
2085 }
2086
2087 #rebuildOverlays (entity)
2088 {
2089 const layers = this.#layersForDisplay(entity);
2090 const base = layers[0]?.sprite
2091 ?? bodySpriteName(entity.sex);
2092 if (this.game.images[base])
2093 {
2094 entity.object.renderer.sprite = this.game.images[base];
2095 this.#startIdleAnimation(entity.object);
2096 }
2097 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2098 entity.bloomBody = !!layers[0]?.bloomBody;
2099 for (const overlay of entity.overlays ?? [])
2100 { overlay.destroy(); }
2101 for (const overlay of entity.bloomOverlays ?? [])
2102 { overlay.destroy(); }
2103 entity.overlays = [];
2104 entity.overlayTints = [];
2105 entity.overlayDualTints = [];
2106 entity.overlayTightFit = [];
2107 entity.bloomOverlays = [];
2108 entity.bloomOverlayTints = [];
2109 if (entity.bloomBody && this.game.images[base])
2110 {
2111 const bloomName = bloomCompanionName(base);
2112 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2113 if (bloomImage)
2114 {
2115 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2116 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2117 this.#markUnlit(bloom);
2118 this.scene.addObject(bloom);
2119 entity.bloomOverlays.push(bloom);
2120 entity.bloomOverlayTints.push(entity.bodyTint);
2121 }
2122 }
2123 for (const layer of layers.slice(1))
2124 {
2125 const image = this.game.images[layer.sprite];
2126 if (!image)
2127 { continue; }
2128 const object = new GameObject(0, 0, image, SORT_ENTITY);
2129 this.scene.addObject(object);
2130 entity.overlays.push(object);
2131 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2132 entity.overlayTightFit.push(!!layerDef?.tightFit);
2133 const dualTint = layer.itemId != null
2134 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
2135 : null;
2136 entity.overlayDualTints.push(dualTint);
2137 entity.overlayTints.push(
2138 dualTint
2139 ? null
2140 : (layer.tint
2141 ? normalizeRgb(layer.tint)
2142 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2143 );
2144 const bloomName = bloomCompanionName(layer.sprite);
2145 const bloomImage = this.game.images[bloomName];
2146 if (!bloomImage)
2147 { continue; }
2148 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2149 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2150 this.#markUnlit(bloom);
2151 this.scene.addObject(bloom);
2152 entity.bloomOverlays.push(bloom);
2153 entity.bloomOverlayTints.push(
2154 layer.tint ? normalizeRgb(layer.tint) : null
2155 );
2156 }
2157 }
2158
2159 #placeEntity (entity, now = performance.now())
2160 {
2161 const zoom = this.zoom;
2162 const offsetX = entity.shoveOffsetX ?? 0;
2163 const offsetY = entity.shoveOffsetY ?? 0;
2164 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2165 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2166 let walkTilt = 0;
2167 if (entity.lerpStarted != null)
2168 {
2169 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2170 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2171 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2172 walkTilt = Math.sin(cycles) * tilt;
2173 }
2174 const flashStrength = (entity.damageFlashUntil ?? 0) > now
2175 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2176 : 0;
2177 const tileShade = this.#entityShadeAlpha(entity, now);
2178 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2179
2180 entity.object.transform.rotation = walkTilt;
2181 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null);
2182 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
2183 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2184 {
2185 const overlay = entity.overlays[index];
2186 const overlaySortY = pivotY + 0.5 * (index + 1);
2187 overlay.transform.rotation = walkTilt;
2188 const dualTint = entity.overlayDualTints?.[index] ?? null;
2189 if (dualTint)
2190 {
2191 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade);
2192 }
2193 else if (entity.overlayTightFit?.[index])
2194 {
2195 this.#syncTightFitLitSprite(
2196 overlay,
2197 entity,
2198 tileShade,
2199 flashStrength,
2200 wade,
2201 entity.overlayTints?.[index] ?? null
2202 );
2203 }
2204 else
2205 {
2206 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
2207 }
2208 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
2209 }
2210 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
2211 {
2212 const overlay = entity.bloomOverlays[index];
2213 this.#setRendererVisible(overlay, this.bloomEnabled);
2214 if (!this.bloomEnabled)
2215 { continue; }
2216 /** Body bloom must share the base sprite's animation frame (e.g. elemental sprites). */
2217 if (entity.bloomBody && index === 0 && entity.object?.renderer)
2218 {
2219 overlay.renderer.cycle = null;
2220 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
2221 }
2222 overlay.transform.rotation = walkTilt;
2223 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
2224 if (bloomTint)
2225 { this.#syncUnlitTintSprite(overlay, bloomTint); }
2226 else
2227 { this.#syncLitSprite(overlay, tileShade, flashStrength, wade); }
2228 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2229 }
2230 this.#placeHpBar(entity, pivotX, pivotY);
2231 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2232 }
2233
2234 #markUnlit (object)
2235 {
2236 if (!object?.renderer)
2237 { return; }
2238 object._lit = false;
2239 object.renderer.shader = null;
2240 object.renderer.shaderUniforms = null;
2241 object.renderer.secondaryMap = null;
2242 }
2243
2244 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
2245 #syncUnlitTintSprite (object, tintColor)
2246 {
2247 if (!object?.renderer || !tintColor)
2248 { return; }
2249 const tint = normalizeRgb(tintColor);
2250 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2251 object.renderer.shader = getTintLitSpriteShader();
2252 object.renderer.shaderUniforms = {
2253 u_darkness: 0,
2254 u_strength: 0,
2255 u_wade: 0,
2256 u_spriteHeight: height,
2257 u_useTint: 1,
2258 u_tintColor: [tint.r, tint.g, tint.b]
2259 };
2260 object.renderer.secondaryMap = null;
2261 }
2262
2263 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
2264 {
2265 if (!object?.renderer || object._lit === false)
2266 { return; }
2267 object._lit = true;
2268 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2269 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2270 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2271 const tint = tintColor ? normalizeRgb(tintColor) : null;
2272 if (tint)
2273 {
2274 object.renderer.shader = getTintLitSpriteShader();
2275 object.renderer.shaderUniforms = {
2276 u_darkness: dark,
2277 u_strength: flash,
2278 u_wade: wade ? 1 : 0,
2279 u_spriteHeight: height,
2280 u_useTint: 1,
2281 u_tintColor: [tint.r, tint.g, tint.b]
2282 };
2283 }
2284 else
2285 {
2286 object.renderer.shader = getSpriteLightingShader();
2287 object.renderer.shaderUniforms = {
2288 u_darkness: dark,
2289 u_strength: flash,
2290 u_wade: wade ? 1 : 0,
2291 u_spriteHeight: height
2292 };
2293 }
2294 object.renderer.secondaryMap = null;
2295 }
2296
2297 #bodySecondaryMap (entity)
2298 {
2299 return entity?.object?.renderer?.sprite?.g_image ?? null;
2300 }
2301
2302 #tightFitMaskUniforms (overlay, entity)
2303 {
2304 const bodyRenderer = entity?.object?.renderer;
2305 const clothRenderer = overlay?.renderer;
2306 const bodySprite = bodyRenderer?.sprite;
2307 const clothSprite = clothRenderer?.sprite;
2308 if (!bodySprite || !clothSprite)
2309 { return null; }
2310 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2311 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2312 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2313 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2314 return {
2315 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2316 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2317 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2318 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2319 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2320 };
2321 }
2322
2323 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
2324 {
2325 if (!overlay?.renderer || entity?.object?.renderer == null)
2326 { return; }
2327 const bodyMap = this.#bodySecondaryMap(entity);
2328 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2329 if (!bodyMap || !maskUniforms)
2330 {
2331 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
2332 return;
2333 }
2334 overlay._lit = true;
2335 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2336 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2337 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2338 const tint = tintColor ? normalizeRgb(tintColor) : null;
2339 overlay.renderer.secondaryMap = bodyMap;
2340 if (tint)
2341 {
2342 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2343 overlay.renderer.shaderUniforms = {
2344 u_darkness: dark,
2345 u_strength: flash,
2346 u_wade: wade ? 1 : 0,
2347 u_spriteHeight: height,
2348 u_useTint: 1,
2349 u_tintColor: [tint.r, tint.g, tint.b],
2350 ...maskUniforms
2351 };
2352 }
2353 else
2354 {
2355 overlay.renderer.shader = getTightFitLitSpriteShader();
2356 overlay.renderer.shaderUniforms = {
2357 u_darkness: dark,
2358 u_strength: flash,
2359 u_wade: wade ? 1 : 0,
2360 u_spriteHeight: height,
2361 ...maskUniforms
2362 };
2363 }
2364 }
2365
2366 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false)
2367 {
2368 if (!object?.renderer || object._lit === false || !dualTint)
2369 { return; }
2370 object._lit = true;
2371 const shaft = normalizeRgb(dualTint.shaft);
2372 const tip = normalizeRgb(dualTint.tip);
2373 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
2374 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2375 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2376 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2377 object.renderer.shader = getDualTintLitSpriteShader();
2378 object.renderer.shaderUniforms = {
2379 u_darkness: dark,
2380 u_strength: flash,
2381 u_wade: wade ? 1 : 0,
2382 u_spriteHeight: height,
2383 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2384 u_tipTint: [tip.r, tip.g, tip.b],
2385 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
2386 u_hasCoat: coat ? 1 : 0
2387 };
2388 object.renderer.secondaryMap = null;
2389 }
2390
2391 #syncGroundItemSprite (item, darkness)
2392 {
2393 if (item?.dualTint)
2394 {
2395 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2396 return;
2397 }
2398 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2399 }
2400
2401 #groundTypeAt (tileX, tileY)
2402 {
2403 const ground = this.#groundAtTile(tileX, tileY);
2404 return ground == null ? null : normalizeGround(ground).typeId;
2405 }
2406
2407 /** Ground entry at a world tile, including editor hover preview when present. */
2408 #groundAtTile (tileX, tileY)
2409 {
2410 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2411 && this.preview.ground !== undefined)
2412 { return this.preview.ground; }
2413 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2414 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2415 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2416 if (!snapshot)
2417 { return null; }
2418 const localX = tileX - chunkX * CHUNK_SIZE;
2419 const localY = tileY - chunkY * CHUNK_SIZE;
2420 const index = localY * CHUNK_SIZE + localX;
2421 return snapshot.grounds?.[index] ?? null;
2422 }
2423
2424 #waterCoastEdges (tileX, tileY)
2425 {
2426 const season = this.worldSeason;
2427 return {
2428 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2429 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2430 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2431 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2432 };
2433 }
2434
2435 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2436 {
2437 if (!object?.renderer)
2438 { return; }
2439 const lit = corners ?? {
2440 nw: fallbackLit,
2441 ne: fallbackLit,
2442 sw: fallbackLit,
2443 se: fallbackLit
2444 };
2445 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2446 object._lit = true;
2447 object.renderer.shader = getWaterGroundShader();
2448 object.renderer.secondaryMap = null;
2449 object.renderer.shaderUniforms = {
2450 u_ambientDark: dark,
2451 u_litNW: lit.nw,
2452 u_litNE: lit.ne,
2453 u_litSW: lit.sw,
2454 u_litSE: lit.se,
2455 u_time: timeSec,
2456 u_edgeN: edges?.n ?? 0,
2457 u_edgeE: edges?.e ?? 0,
2458 u_edgeS: edges?.s ?? 0,
2459 u_edgeW: edges?.w ?? 0
2460 };
2461 }
2462
2463 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2464 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2465 {
2466 if (!objects?.ground)
2467 { return; }
2468 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2469 {
2470 objects.waterEdges = null;
2471 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2472 return;
2473 }
2474 const fallbackLit = ambientDark > 0
2475 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
2476 : 1;
2477 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2478 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2479 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2480 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2481 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2482 let litCorners = null;
2483 if (chunkBaked)
2484 {
2485 if (this.lightingMode === "simple")
2486 {
2487 const gridW = CHUNK_SIZE + 2;
2488 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2489 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2490 }
2491 else
2492 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2493 }
2494 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2495 this.#syncWaterGroundSprite(
2496 objects.ground,
2497 litCorners,
2498 ambientDark,
2499 objects.waterEdges,
2500 timeSec,
2501 fallbackLit
2502 );
2503 }
2504
2505 #ambientDarkness ()
2506 {
2507 const hour = this.nightPreview ?? this.worldHour;
2508 const calendar = nightFactor(hour, this.settings.nightDarkness);
2509 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2510 if (dark == null)
2511 { dark = calendar; }
2512 if (this.localBlind)
2513 { dark = Math.min(1, dark + 0.85); }
2514 return dark;
2515 }
2516
2517 setLocalBlind (blind)
2518 {
2519 this.localBlind = !!blind;
2520 }
2521
2522 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2523 #blindVisionLight ()
2524 {
2525 if (!this.localBlind)
2526 { return null; }
2527 const local = this.entities.get(this.localEntityId);
2528 if (!local)
2529 { return null; }
2530 const tileSize = this.tileSize();
2531 return {
2532 tileX: Math.floor(local.visualX / tileSize),
2533 tileY: Math.floor(local.visualY / tileSize),
2534 range: 2.25,
2535 intensity: 1
2536 };
2537 }
2538
2539 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2540 {
2541 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2542 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2543 const dark = (fromAlpha + toAlpha) / 2;
2544 if (dualTint)
2545 {
2546 this.#syncDualTintLitSprite(object, dark, dualTint);
2547 return;
2548 }
2549 this.#syncLitSprite(object, dark);
2550 }
2551
2552 #dualTintFromPayload (payload)
2553 {
2554 if (!payload?.shaftTint || !payload?.tipTint)
2555 { return null; }
2556 return {
2557 shaft: payload.shaftTint,
2558 tip: payload.tipTint,
2559 ...(payload.coatTint ? { coat: payload.coatTint } : {})
2560 };
2561 }
2562
2563 #syncHpBar (entity)
2564 {
2565 const current = entity.health;
2566 const max = entity.maxHealth;
2567 const show = current != null
2568 && max != null
2569 && max > 0
2570 && current < max;
2571 if (!show)
2572 {
2573 entity.hpBar?.destroy();
2574 entity.hpBar = null;
2575 entity.hpBarCanvas = null;
2576 return;
2577 }
2578 if (!entity.hpBarCanvas)
2579 {
2580 entity.hpBarCanvas = document.createElement("canvas");
2581 entity.hpBarCanvas.width = HP_BAR_W;
2582 entity.hpBarCanvas.height = HP_BAR_H;
2583 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2584 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2585 this.#markUnlit(entity.hpBar);
2586 this.scene.addObject(entity.hpBar);
2587 }
2588 drawHpBar(entity.hpBarCanvas, current, max);
2589 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
2590 }
2591
2592 #placeHpBar (entity, pivotX, pivotY)
2593 {
2594 if (!entity.hpBar)
2595 { return; }
2596 const sprite = entity.object?.renderer?.sprite;
2597 if (!sprite)
2598 { return; }
2599 const zoom = this.zoom;
2600 const drawH = sprite.height * zoom;
2601 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
2602 const spriteTop = centerY - drawH / 2;
2603 const barW = HP_BAR_W * zoom;
2604 const barH = HP_BAR_H * zoom;
2605 entity.hpBar.transform.position.x = pivotX;
2606 entity.hpBar.transform.position.y = spriteTop - barH / 2;
2607 entity.hpBar.transform.size = new vector(barW, barH);
2608 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
2609 this.#markSortDirty();
2610 }
2611
2612 #syncSkullMarker (entity)
2613 {
2614 if (!entity?.characterId)
2615 {
2616 entity.skullMarker?.destroy();
2617 entity.skullMarker = null;
2618 return;
2619 }
2620 const tint = skullTintColor(entity.skullValue | 0);
2621 if (!tint)
2622 {
2623 entity.skullMarker?.destroy();
2624 entity.skullMarker = null;
2625 return;
2626 }
2627 const image = this.game.images[SKULL_SPRITE];
2628 if (!image)
2629 { return; }
2630 if (!entity.skullMarker)
2631 {
2632 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2633 this.scene.addObject(entity.skullMarker);
2634 }
2635 entity.skullTint = tint;
2636 entity.skullMarker.renderer.sprite = image;
2637 }
2638
2639 /**
2640 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2641 */
2642 #placeSkullMarker (entity, pivotX, pivotY, darkness)
2643 {
2644 this.#syncSkullMarker(entity);
2645 if (!entity.skullMarker)
2646 { return; }
2647 const body = entity.object?.renderer?.sprite;
2648 const skull = entity.skullMarker.renderer?.sprite;
2649 if (!body || !skull)
2650 { return; }
2651 const zoom = this.zoom;
2652 const scale = entity.visualScale ?? 1;
2653 const bodyH = body.height * zoom * scale;
2654 const skullH = skull.height * zoom;
2655 const skullW = skull.width * zoom;
2656 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2657 const bodyTop = bodyCenterY - bodyH / 2;
2658 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2659 entity.skullMarker.transform.position.x = pivotX;
2660 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2661 entity.skullMarker.transform.size = new vector(skullW, skullH);
2662 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2663 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2664 this.#markSortDirty();
2665 }
2666
2667 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2668 {
2669 this.#bakeAndPlaceChunk(snapshot);
2670 this.#relayoutChunkTiles(snapshot);
2671 if (this.softTerrain && refreshSoftNeighbors)
2672 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2673 }
2674
2675 #relayoutChunk (snapshot)
2676 {
2677 this.#layoutBakedChunk(snapshot);
2678 this.#relayoutChunkTiles(snapshot);
2679 }
2680
2681 #relayoutChunkTiles (snapshot)
2682 {
2683 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2684 {
2685 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2686 {
2687 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
2688 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
2689 this.#drawTile(tileX, tileY);
2690 }
2691 }
2692 }
2693
2694 #scheduleChunkRebuild (snapshot)
2695 {
2696 if (!snapshot)
2697 { return; }
2698 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2699 this.#cancelIdlePrefetch();
2700 this.#ensureChunkFlushScheduled();
2701 }
2702
2703 #scheduleEdgeRebuild ()
2704 {
2705 this.#edgesDirty = true;
2706 this.#cancelIdlePrefetch();
2707 this.#ensureChunkFlushScheduled();
2708 }
2709
2710 #ensureChunkFlushScheduled ()
2711 {
2712 if (this.#chunkRebuildRaf)
2713 { return; }
2714 this.#cancelIdlePrefetch();
2715 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
2716 }
2717
2718 #notePlayerTile (tileX, tileY)
2719 {
2720 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2721 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2722 if (this.#playerChunkX != null
2723 && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
2724 {
2725 const dx = chunkX - this.#playerChunkX;
2726 const dy = chunkY - this.#playerChunkY;
2727 if (dx !== 0)
2728 { this.#playerMoveChunkDx = Math.sign(dx); }
2729 if (dy !== 0)
2730 { this.#playerMoveChunkDy = Math.sign(dy); }
2731 }
2732 this.#playerChunkX = chunkX;
2733 this.#playerChunkY = chunkY;
2734 }
2735
2736 #playerChunkCoords ()
2737 {
2738 const local = this.entities.get(this.localEntityId);
2739 if (local)
2740 {
2741 return {
2742 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
2743 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
2744 };
2745 }
2746 if (this.#playerChunkX != null && this.#playerChunkY != null)
2747 {
2748 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
2749 }
2750 return null;
2751 }
2752
2753 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
2754 #chunkRebuildScore (key, mode = "urgent")
2755 {
2756 const [chunkX, chunkY] = key.split(",").map(Number);
2757 const player = this.#playerChunkCoords();
2758 if (!player)
2759 { return 0; }
2760 const dx = chunkX - player.chunkX;
2761 const dy = chunkY - player.chunkY;
2762 const dist = Math.abs(dx) + Math.abs(dy);
2763 let ahead = 0;
2764 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
2765 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
2766 if (mode === "idle")
2767 {
2768 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
2769 }
2770 return dist * 10 - Math.max(0, ahead) * 3;
2771 }
2772
2773 #sortedChunkRebuildKeys (mode = "urgent")
2774 {
2775 return [...this.#chunkRebuildKeys].sort((a, b) =>
2776 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
2777 }
2778
2779 #discoverUnbakedChunks ()
2780 {
2781 for (const key of this.chunks.keys())
2782 {
2783 if (!this.bakedChunks.has(key))
2784 { this.#chunkRebuildKeys.add(key); }
2785 }
2786 }
2787
2788 #hasUnbakedChunks ()
2789 {
2790 for (const key of this.chunks.keys())
2791 {
2792 if (!this.bakedChunks.has(key))
2793 { return true; }
2794 }
2795 return false;
2796 }
2797
2798 #pickIdlePrefetchSnapshot ()
2799 {
2800 let best = null;
2801 let bestScore = Infinity;
2802 for (const snapshot of this.chunks.values())
2803 {
2804 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2805 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
2806 { continue; }
2807 const score = this.#chunkRebuildScore(key, "idle");
2808 if (score < bestScore)
2809 {
2810 bestScore = score;
2811 best = snapshot;
2812 }
2813 }
2814 return best;
2815 }
2816
2817 #cancelIdlePrefetch ()
2818 {
2819 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
2820 { cancelIdleCallback(this.#idlePrefetchId); }
2821 this.#idlePrefetchId = 0;
2822 }
2823
2824 #scheduleIdleChunkPrefetch ()
2825 {
2826 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2827 { return; }
2828 if (typeof requestIdleCallback !== "function")
2829 { return; }
2830 if (!this.#hasUnbakedChunks())
2831 { return; }
2832 this.#idlePrefetchId = requestIdleCallback(
2833 (deadline) => this.#runIdleChunkPrefetch(deadline),
2834 { timeout: 2500 }
2835 );
2836 }
2837
2838 #runIdleChunkPrefetch (deadline)
2839 {
2840 this.#idlePrefetchId = 0;
2841 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
2842 { return; }
2843 this.#discoverUnbakedChunks();
2844 if (this.#chunkRebuildKeys.size)
2845 {
2846 this.#ensureChunkFlushScheduled();
2847 return;
2848 }
2849 const snapshot = this.#pickIdlePrefetchSnapshot();
2850 if (!snapshot)
2851 { return; }
2852 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
2853 {
2854 this.#scheduleIdleChunkPrefetch();
2855 return;
2856 }
2857 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
2858 if (this.#hasUnbakedChunks())
2859 { this.#scheduleIdleChunkPrefetch(); }
2860 }
2861
2862 #flushChunkWork ()
2863 {
2864 this.#chunkRebuildRaf = 0;
2865 const keys = this.#sortedChunkRebuildKeys("urgent");
2866 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
2867 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
2868 this.#chunkRebuildKeys.clear();
2869 for (const key of rest)
2870 { this.#chunkRebuildKeys.add(key); }
2871 for (const key of batch)
2872 {
2873 const snap = this.chunks.get(key);
2874 if (snap)
2875 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
2876 }
2877 if (this.#chunkRebuildKeys.size)
2878 {
2879 this.#ensureChunkFlushScheduled();
2880 return;
2881 }
2882 if (this.#edgesDirty)
2883 {
2884 this.#rebuildAllEdges();
2885 this.#edgesDirty = false;
2886 }
2887 this.#scheduleIdleChunkPrefetch();
2888 }
2889
2890 #previewEqual (a, b)
2891 {
2892 if (a === b)
2893 { return true; }
2894 if (!a || !b)
2895 { return false; }
2896 return a.tileX === b.tileX
2897 && a.tileY === b.tileY
2898 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
2899 && this.#previewPart(a.block) === this.#previewPart(b.block);
2900 }
2901
2902 #previewPart (value)
2903 {
2904 return value === undefined ? undefined : JSON.stringify(value);
2905 }
2906
2907 #rebuildSoftTerrainNeighborChunks (snapshot)
2908 {
2909 for (let dy = -1; dy <= 1; dy++)
2910 {
2911 for (let dx = -1; dx <= 1; dx++)
2912 {
2913 if (dx === 0 && dy === 0)
2914 { continue; }
2915 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2916 if (neighbor)
2917 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
2918 }
2919 }
2920 }
2921
2922 #rebakeAllChunks ()
2923 {
2924 for (const snapshot of this.chunks.values())
2925 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
2926 }
2927
2928 #bakeAndPlaceChunk (snapshot)
2929 {
2930 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2931 const atlases = bakeChunkAtlases({
2932 snapshot,
2933 catalog: this.catalog,
2934 images: this.game.images,
2935 preview: this.preview,
2936 season: this.worldSeason,
2937 softTerrain: this.softTerrain,
2938 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
2939 cache: this.#atlasCache
2940 });
2941 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2942 let baked = this.bakedChunks.get(key);
2943 this.#releaseBakedAtlasRefs(baked);
2944
2945 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
2946 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
2947 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
2948 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
2949 ?? frameworkImageFromCanvas(atlases.bloom);
2950
2951 if (!baked)
2952 {
2953 const lightmapCanvas = makeLightmapCanvas(atlasPx);
2954 baked = {
2955 groundCanvas: atlases.ground,
2956 blockCanvases: atlases.blockRows,
2957 bloomCanvas: atlases.bloom,
2958 lightmapCanvas,
2959 groundImage,
2960 blockImages,
2961 bloomImage,
2962 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
2963 groundObject: null,
2964 blockObjects: [],
2965 bloomObject: null,
2966 tallBlocks: atlases.tallBlocks,
2967 animatedGrounds: atlases.animatedGrounds,
2968 lightmapPixels: null,
2969 atlasCacheRefs: atlases.cacheRefs
2970 };
2971 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
2972 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
2973 this.scene.addObject(baked.groundObject);
2974 for (let row = 0; row < CHUNK_SIZE; row++)
2975 {
2976 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
2977 this.#applyAtlasLighting(object, baked.lightmapImage, row);
2978 this.scene.addObject(object);
2979 baked.blockObjects.push(object);
2980 }
2981 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
2982 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2983 this.#markUnlit(baked.bloomObject);
2984 this.scene.addObject(baked.bloomObject);
2985 this.bakedChunks.set(key, baked);
2986 }
2987 else
2988 {
2989 if (baked.groundCanvas !== atlases.ground)
2990 {
2991 baked.groundCanvas = atlases.ground;
2992 baked.groundImage = groundImage;
2993 baked.groundObject.renderer.sprite = groundImage;
2994 }
2995 for (let row = 0; row < CHUNK_SIZE; row++)
2996 {
2997 if (baked.blockCanvases[row] !== atlases.blockRows[row])
2998 {
2999 baked.blockCanvases[row] = atlases.blockRows[row];
3000 baked.blockImages[row] = blockImages[row];
3001 baked.blockObjects[row].renderer.sprite = blockImages[row];
3002 }
3003 }
3004 if (baked.bloomCanvas !== atlases.bloom)
3005 {
3006 baked.bloomCanvas = atlases.bloom;
3007 baked.bloomImage = bloomImage;
3008 baked.bloomObject.renderer.sprite = bloomImage;
3009 }
3010 baked.tallBlocks = atlases.tallBlocks;
3011 baked.animatedGrounds = atlases.animatedGrounds;
3012 baked.atlasCacheRefs = atlases.cacheRefs;
3013 }
3014 baked.chunkX = snapshot.chunkX;
3015 baked.chunkY = snapshot.chunkY;
3016 baked.lightmapCacheKey = null;
3017 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3018 this.#layoutBakedChunk(snapshot);
3019 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
3020 }
3021
3022 #releaseBakedAtlasRefs (baked)
3023 {
3024 if (!baked?.atlasCacheRefs)
3025 { return; }
3026 this.#atlasCache.release(baked.atlasCacheRefs.ground);
3027 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
3028 { this.#atlasCache.release(entry); }
3029 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
3030 baked.atlasCacheRefs = null;
3031 }
3032
3033 #chunkTextureWarmPriority (chunkX, chunkY)
3034 {
3035 const local = this.entities.get(this.localEntityId);
3036 if (!local)
3037 { return 999; }
3038 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
3039 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
3040 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
3041 }
3042
3043 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
3044 {
3045 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
3046 { return; }
3047 this.#pendingTextureCanvasSet.add(canvas);
3048 this.#pendingTextureCanvases.push({
3049 canvas,
3050 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
3051 });
3052 this.#scheduleTextureWarm();
3053 }
3054
3055 #queueBakedChunkTextures (baked, chunkX, chunkY)
3056 {
3057 if (!baked)
3058 { return; }
3059 const refs = baked.atlasCacheRefs;
3060 const maybeWarm = (canvas, entry) =>
3061 {
3062 if (!canvas)
3063 { return; }
3064 if (entry && this.#atlasCache.isWarmed(canvas))
3065 { return; }
3066 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
3067 };
3068 maybeWarm(baked.groundCanvas, refs?.ground);
3069 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
3070 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
3071 maybeWarm(baked.bloomCanvas, refs?.bloom);
3072 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
3073 }
3074
3075 #scheduleTextureWarm ()
3076 {
3077 if (this.#textureWarmRaf)
3078 { return; }
3079 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
3080 }
3081
3082 #flushTextureWarm ()
3083 {
3084 this.#textureWarmRaf = 0;
3085 if (!this.#pendingTextureCanvases.length)
3086 { return; }
3087 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
3088 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
3089 for (const entry of batch)
3090 {
3091 this.#pendingTextureCanvasSet.delete(entry.canvas);
3092 setNearestFilter(this.scene, entry.canvas);
3093 this.#atlasCache.markWarmed(entry.canvas);
3094 }
3095 if (this.#pendingTextureCanvases.length)
3096 { this.#scheduleTextureWarm(); }
3097 }
3098
3099 #applyAtlasLighting (object, lightmapImage, lightRow)
3100 {
3101 if (!object?.renderer)
3102 { return; }
3103 object._lit = true;
3104 object.renderer.shader = getAtlasLightingShader();
3105 object.renderer.secondaryMap = lightmapImage;
3106 object.renderer.shaderUniforms = {
3107 u_ambientDark: 0,
3108 u_lightRow: lightRow
3109 };
3110 }
3111
3112 #layoutBakedChunk (snapshot)
3113 {
3114 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3115 const baked = this.bakedChunks.get(key);
3116 if (!baked)
3117 { return; }
3118 const size = this.tileSize();
3119 const left = snapshot.chunkX * CHUNK_SIZE * size;
3120 const top = snapshot.chunkY * CHUNK_SIZE * size;
3121 const chunkPx = CHUNK_SIZE * size;
3122 baked.groundObject.transform.position.x = left + chunkPx / 2;
3123 baked.groundObject.transform.position.y = top + chunkPx / 2;
3124 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
3125 baked.groundObject.layer = LAYER_GROUND;
3126
3127 for (let row = 0; row < CHUNK_SIZE; row++)
3128 {
3129 const object = baked.blockObjects[row];
3130 const rowY = top + row * size + size / 2;
3131 object.transform.position.x = left + chunkPx / 2;
3132 object.transform.position.y = rowY;
3133 object.transform.size = new vector(chunkPx, size);
3134 object.layer = ySortLayer(rowY, SORT_BLOCK);
3135 }
3136
3137 baked.bloomObject.transform.position.x = left + chunkPx / 2;
3138 baked.bloomObject.transform.position.y = top + chunkPx / 2;
3139 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
3140 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
3141 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3142 this.#markSortDirty();
3143 }
3144
3145 #destroyBakedChunk (key)
3146 {
3147 const baked = this.bakedChunks.get(key);
3148 if (!baked)
3149 { return; }
3150 this.#releaseBakedAtlasRefs(baked);
3151 baked.groundObject?.destroy();
3152 for (const object of baked.blockObjects ?? [])
3153 { object.destroy(); }
3154 baked.bloomObject?.destroy();
3155 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3156 this.bakedChunks.delete(key);
3157 }
3158
3159 #redrawPreview ()
3160 {
3161 if (!this.preview)
3162 { return; }
3163 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
3164 if (snapshot)
3165 { this.#rebuildChunk(snapshot); }
3166 }
3167
3168 #refreshWaterCoastsNear (chunkX, chunkY)
3169 {
3170 const timeSec = performance.now() / 1000;
3171 for (const objects of this.tiles.values())
3172 {
3173 if (!objects.ground || !isWaterGround(objects.groundTypeId))
3174 { continue; }
3175 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
3176 { continue; }
3177 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
3178 }
3179 }
3180
3181 #drawTile (tileX, tileY)
3182 {
3183 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3184 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3185 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3186 if (!snapshot)
3187 { return; }
3188 const localX = tileX - chunkX * CHUNK_SIZE;
3189 const localY = tileY - chunkY * CHUNK_SIZE;
3190 const index = localY * CHUNK_SIZE + localX;
3191 const key = `${tileX},${tileY}`;
3192 let objects = this.tiles.get(key);
3193 if (!objects)
3194 {
3195 objects = { chunkX, chunkY, tileX, tileY };
3196 this.tiles.set(key, objects);
3197 }
3198 objects.tileX = tileX;
3199 objects.tileY = tileY;
3200 objects.chunkX = chunkX;
3201 objects.chunkY = chunkY;
3202 objects.light = snapshot.light[index] ?? 0;
3203
3204 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
3205 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
3206 if (animatedGround)
3207 {
3208 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
3209 if (objects.ground)
3210 {
3211 const size = this.tileSize();
3212 objects.ground.transform.position.x = tileX * size + size / 2;
3213 objects.ground.transform.position.y = tileY * size + size / 2;
3214 objects.ground.transform.size = new vector(size, size);
3215 objects.ground.layer = LAYER_GROUND;
3216 objects.groundTypeId = animatedGround.typeId;
3217 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
3218 this.#markSortDirty();
3219 }
3220 if (animatedGround.bloom)
3221 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
3222 else
3223 {
3224 objects.groundBloom?.destroy();
3225 objects.groundBloom = null;
3226 }
3227 }
3228 else
3229 {
3230 objects.ground?.destroy();
3231 objects.ground = null;
3232 objects.groundBloom?.destroy();
3233 objects.groundBloom = null;
3234 objects.groundTypeId = null;
3235 objects.waterEdges = null;
3236 }
3237
3238 const tileBlock = tileBlockSpriteEntry(
3239 this.catalog,
3240 this.game.images,
3241 snapshot.blocks[index],
3242 this.worldSeason
3243 );
3244 if (tileBlock)
3245 {
3246 const pivot = tilePivot(tileX, tileY, this.tileSize());
3247 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY);
3248 if (objects.block)
3249 {
3250 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
3251 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
3252 }
3253 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
3254 }
3255 else
3256 {
3257 objects.block?.destroy();
3258 objects.block = null;
3259 objects.blockBloom?.destroy();
3260 objects.blockBloom = null;
3261 }
3262 }
3263
3264 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
3265 {
3266 if (!name)
3267 {
3268 existing?.destroy();
3269 return null;
3270 }
3271 const object = this.#ensureSprite(existing, name, sortOrder);
3272 if (!object)
3273 { return null; }
3274 object.renderer.layer = RENDER_LAYER_BLOOM;
3275 this.#markUnlit(object);
3276 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
3277 return object;
3278 }
3279
3280 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
3281 {
3282 const sprite = object?.renderer?.sprite;
3283 if (!sprite)
3284 { return; }
3285 const zoom = this.zoom;
3286 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
3287 const factor = Math.max(0.1, Number(scale) || 1);
3288 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
3289 object.transform.position.x = center.x;
3290 object.transform.position.y = center.y;
3291 object.transform.size = new vector(draw.w * factor, draw.h * factor);
3292 object.layer = ySortLayer(sortY, subOrder);
3293 this.#markSortDirty();
3294 }
3295
3296 #ensureSprite (existing, name, layer)
3297 {
3298 const sprite = this.game.images[name];
3299 if (!sprite)
3300 {
3301 existing?.destroy();
3302 return null;
3303 }
3304 if (!existing || existing.renderer.sprite !== sprite)
3305 {
3306 existing?.destroy();
3307 existing = new GameObject(0, 0, sprite, layer);
3308 this.#syncLitSprite(existing, 0);
3309 this.scene.addObject(existing);
3310 this.#startIdleAnimation(existing);
3311 }
3312 return existing;
3313 }
3314
3315 #startIdleAnimation (object)
3316 {
3317 const sprite = object?.renderer?.sprite;
3318 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
3319 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
3320 }
3321
3322 #neighborClosed (snapshot, dir, dx, dy)
3323 {
3324 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3325 if (other)
3326 { return !other.open; }
3327 return !!snapshot.closedEdges?.[dir];
3328 }
3329
3330 #rebuildAllEdges ()
3331 {
3332 const seen = new Set();
3333 for (const snapshot of this.chunks.values())
3334 {
3335 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3336 seen.add(key);
3337 this.#rebuildChunkEdges(snapshot);
3338 }
3339 for (const key of [...this.edges.keys()])
3340 {
3341 if (!seen.has(key))
3342 { this.#destroyEdges(key); }
3343 }
3344 }
3345
3346 #rebuildChunkEdges (snapshot)
3347 {
3348 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3349 let bars = this.edges.get(key);
3350 if (!bars)
3351 {
3352 bars = {};
3353 this.edges.set(key, bars);
3354 }
3355
3356 const size = this.tileSize();
3357 const chunkPx = CHUNK_SIZE * size;
3358 const left = snapshot.chunkX * CHUNK_SIZE * size;
3359 const top = snapshot.chunkY * CHUNK_SIZE * size;
3360 const centerX = left + chunkPx / 2;
3361 const centerY = top + chunkPx / 2;
3362 const thickness = Math.max(2, Math.round(2 * this.zoom));
3363 const draw = snapshot.open === true;
3364
3365 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
3366 centerX, top, chunkPx, thickness, true);
3367 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
3368 centerX, top + chunkPx, chunkPx, thickness, true);
3369 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
3370 left, centerY, chunkPx, thickness, false);
3371 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
3372 left + chunkPx, centerY, chunkPx, thickness, false);
3373 }
3374
3375 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
3376 {
3377 if (!visible)
3378 {
3379 if (existing)
3380 { existing.renderer.visible = false; }
3381 return existing;
3382 }
3383
3384 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
3385 this.#markUnlit(existing);
3386 existing.renderer.visible = true;
3387 existing.transform.position.x = x;
3388 existing.transform.position.y = y;
3389 existing.transform.size = horizontal
3390 ? new vector(length, thickness)
3391 : new vector(thickness, length);
3392 existing.layer = LAYER_EDGE;
3393 this.#markSortDirty();
3394 return existing;
3395 }
3396
3397 #destroyEdges (key)
3398 {
3399 const bars = this.edges.get(key);
3400 if (!bars)
3401 { return; }
3402 bars.north?.destroy();
3403 bars.east?.destroy();
3404 bars.south?.destroy();
3405 bars.west?.destroy();
3406 this.edges.delete(key);
3407 }
3408
3409 #entityShadeAlpha (entity, now)
3410 {
3411 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
3412 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
3413 { return toAlpha; }
3414 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
3415 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
3416 return fromAlpha + (toAlpha - fromAlpha) * t;
3417 }
3418
3419 #markSortDirty ()
3420 {
3421 this.scene._sortDirty = true;
3422 }
3423
3424 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
3425 #activeLightingCenterChunk ()
3426 {
3427 const local = this.entities.get(this.localEntityId);
3428 if (!local)
3429 { return null; }
3430 return {
3431 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3432 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3433 };
3434 }
3435
3436 #isActiveLightingChunk (chunkX, chunkY)
3437 {
3438 const center = this.#activeLightingCenterChunk();
3439 if (!center)
3440 { return true; }
3441 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
3442 }
3443
3444 #isActiveLightingTile (tileX, tileY)
3445 {
3446 return this.#isActiveLightingChunk(
3447 Math.floor(tileX / CHUNK_SIZE),
3448 Math.floor(tileY / CHUNK_SIZE)
3449 );
3450 }
3451
3452 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3453 #innerDynamicLights (activeLights)
3454 {
3455 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3456 }
3457
3458 /**
3459 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3460 * chunks only receive inner sources close enough to reach the chunk bounds.
3461 */
3462 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3463 {
3464 const center = this.#activeLightingCenterChunk();
3465 if (!center)
3466 { return activeLights; }
3467 const inner = this.#innerDynamicLights(activeLights);
3468 if (this.#isActiveLightingChunk(chunkX, chunkY))
3469 { return inner; }
3470 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3471 }
3472
3473 #dynamicLightsForTile (tileX, tileY, activeLights)
3474 {
3475 return this.#dynamicLightsForChunk(
3476 Math.floor(tileX / CHUNK_SIZE),
3477 Math.floor(tileY / CHUNK_SIZE),
3478 activeLights
3479 );
3480 }
3481
3482 #updateShade ()
3483 {
3484 const ambientDark = this.#ambientDarkness();
3485 const now = performance.now();
3486 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3487
3488 const activeLights = [...this.dynamicLights];
3489 for (const light of this.spellLights.values())
3490 {
3491 if (light.until <= now)
3492 { continue; }
3493 activeLights.push({
3494 tileX: light.tileX,
3495 tileY: light.tileY,
3496 range: light.range,
3497 intensity: light.intensity
3498 });
3499 }
3500 for (const key of [...this.spellLights.keys()])
3501 {
3502 if (this.spellLights.get(key).until <= now)
3503 { this.spellLights.delete(key); }
3504 }
3505 const activeDarks = [];
3506 for (const dark of this.spellDarks.values())
3507 {
3508 if (dark.until <= now)
3509 { continue; }
3510 activeDarks.push({
3511 tileX: dark.tileX,
3512 tileY: dark.tileY,
3513 range: dark.range,
3514 intensity: dark.intensity
3515 });
3516 }
3517 for (const key of [...this.spellDarks.keys()])
3518 {
3519 if (this.spellDarks.get(key).until <= now)
3520 { this.spellDarks.delete(key); }
3521 }
3522 this._activeSpellDarks = activeDarks;
3523 const tileSize = this.tileSize();
3524 const blindLight = this.#blindVisionLight();
3525 if (blindLight)
3526 { activeLights.push(blindLight); }
3527 for (const entity of this.entities.values())
3528 {
3529 const range = entity.lightRadiusTiles ?? 0;
3530 if (range <= 0)
3531 { continue; }
3532 activeLights.push({
3533 tileX: Math.floor(entity.visualX / tileSize),
3534 tileY: Math.floor(entity.visualY / tileSize),
3535 range,
3536 intensity: 1
3537 });
3538 }
3539
3540 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
3541
3542 for (const objects of this.tiles.values())
3543 {
3544 if (objects._inViewport === false)
3545 { continue; }
3546 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
3547 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3548 objects.shadeAlpha = ambientDark * (1 - intensity);
3549 }
3550
3551 for (const baked of this.bakedChunks.values())
3552 {
3553 if (baked._inViewport === false)
3554 { continue; }
3555 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3556 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3557 if (baked.groundObject?.renderer?.shaderUniforms)
3558 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3559 for (const object of baked.blockObjects ?? [])
3560 {
3561 if (object?.renderer?.shaderUniforms)
3562 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3563 }
3564 }
3565
3566 const timeSec = now / 1000;
3567 for (const objects of this.tiles.values())
3568 {
3569 if (objects._inViewport === false)
3570 { continue; }
3571 if (objects.block)
3572 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
3573 if (objects.ground && isWaterGround(objects.groundTypeId))
3574 {
3575 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
3576 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
3577 }
3578 else if (objects.ground)
3579 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
3580 }
3581
3582 for (const item of this.groundItems.values())
3583 {
3584 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
3585 this.#syncGroundItemSprite(item, alpha);
3586 }
3587 }
3588
3589 #tileLightIntensity (objects, activeLights, lightOcclusion)
3590 {
3591 const baked = lightIntensity(objects.light ?? 0);
3592 const dynamic = dynamicLightAtTile(
3593 objects.tileX,
3594 objects.tileY,
3595 activeLights,
3596 lightOcclusion
3597 );
3598 const dark = dynamicDarknessAtTile(
3599 objects.tileX,
3600 objects.tileY,
3601 this._activeSpellDarks ?? [],
3602 lightOcclusion
3603 );
3604 return Math.max(0, Math.max(baked, dynamic) - dark);
3605 }
3606
3607 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
3608 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
3609 {
3610 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
3611 if (tileObjects)
3612 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
3613 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3614 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3615 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3616 if (!snapshot)
3617 { return 0; }
3618 const localX = tileX - chunkX * CHUNK_SIZE;
3619 const localY = tileY - chunkY * CHUNK_SIZE;
3620 const index = localY * CHUNK_SIZE + localX;
3621 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
3622 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
3623 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
3624 return Math.max(0, Math.max(bakedLit, dynamic) - dark);
3625 }
3626
3627 /** True when ground or block on this tile occludes light rays (same rules as bake). */
3628 #tileOccludesLight (tileX, tileY)
3629 {
3630 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3631 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3632 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3633 if (!snapshot)
3634 { return false; }
3635 const localX = tileX - chunkX * CHUNK_SIZE;
3636 const localY = tileY - chunkY * CHUNK_SIZE;
3637 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
3638 { return false; }
3639 const index = localY * CHUNK_SIZE + localX;
3640 if (Array.isArray(snapshot.occlusion) && snapshot.occlusion.length > index)
3641 { return (snapshot.occlusion[index] | 0) >= LightOcclusion.solid; }
3642 const ground = normalizeGround(snapshot.grounds?.[index]);
3643 if (!isGroundPassable(ground.typeId))
3644 { return true; }
3645 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
3646 }
3647
3648 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
3649 {
3650 const gridW = CHUNK_SIZE + 2;
3651 const gridSize = gridW * gridW;
3652 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
3653 { baked.lightIntensityGrid = new Float32Array(gridSize); }
3654 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
3655 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
3656 const grid = baked.lightIntensityGrid;
3657 const occlude = baked.lightOccludeGrid;
3658 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
3659 {
3660 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
3661 {
3662 const tileX = baked.chunkX * CHUNK_SIZE + lx;
3663 const tileY = baked.chunkY * CHUNK_SIZE + ly;
3664 const gi = (ly + 1) * gridW + (lx + 1);
3665 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
3666 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
3667 }
3668 }
3669 return { grid, occlude, gridW };
3670 }
3671
3672 #makeLightCornerSampler (grid, occlude, gridW)
3673 {
3674 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
3675 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
3676 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
3677 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
3678 {
3679 const home = sample(homeLx, homeLy);
3680 if (blocks(homeLx, homeLy))
3681 { return home; }
3682 let sum = home;
3683 let count = 1;
3684 sum += openSample(aLx, aLy);
3685 count += 1;
3686 sum += openSample(bLx, bLy);
3687 count += 1;
3688 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
3689 {
3690 sum += openSample(dLx, dLy);
3691 count += 1;
3692 }
3693 return sum / count;
3694 };
3695 return { smoothCorner };
3696 }
3697
3698 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
3699 #tileLitCorners (baked, localX, localY)
3700 {
3701 const grid = baked?.lightIntensityGrid;
3702 const occlude = baked?.lightOccludeGrid;
3703 if (!grid?.length || !occlude?.length)
3704 { return null; }
3705 const gridW = CHUNK_SIZE + 2;
3706 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
3707 return {
3708 nw: smoothCorner(
3709 localX, localY,
3710 localX - 1, localY,
3711 localX, localY - 1,
3712 localX - 1, localY - 1
3713 ),
3714 ne: smoothCorner(
3715 localX, localY,
3716 localX + 1, localY,
3717 localX, localY - 1,
3718 localX + 1, localY - 1
3719 ),
3720 sw: smoothCorner(
3721 localX, localY,
3722 localX - 1, localY,
3723 localX, localY + 1,
3724 localX - 1, localY + 1
3725 ),
3726 se: smoothCorner(
3727 localX, localY,
3728 localX + 1, localY,
3729 localX, localY + 1,
3730 localX + 1, localY + 1
3731 )
3732 };
3733 }
3734
3735 #hashUint8Array (values)
3736 {
3737 let hash = 2166136261;
3738 for (let i = 0; i < values.length; i++)
3739 {
3740 hash ^= values[i];
3741 hash = Math.imul(hash, 16777619);
3742 }
3743 return hash >>> 0;
3744 }
3745
3746 #lightAffectsChunkBounds (light, chunkX, chunkY)
3747 {
3748 const minX = chunkX * CHUNK_SIZE - 1;
3749 const minY = chunkY * CHUNK_SIZE - 1;
3750 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
3751 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
3752 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
3753 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
3754 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
3755 }
3756
3757 #chunkLightmapCacheKey (baked, activeLights)
3758 {
3759 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3760 if (!snapshot?.light)
3761 { return null; }
3762 const bakedHash = this.#hashUint8Array(snapshot.light);
3763 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3764 if (!lights.length)
3765 { return `i:${bakedHash}`; }
3766 const mode = this.lightingMode === "simple" ? "s" : "f";
3767 let lightsKey = "";
3768 for (const light of lights)
3769 {
3770 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3771 { continue; }
3772 lightsKey += `${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
3773 }
3774 return `a:${mode}:${bakedHash}:${lightsKey}`;
3775 }
3776
3777 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3778 {
3779 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
3780 for (let dy = -2; dy <= 2; dy++)
3781 {
3782 for (let dx = -2; dx <= 2; dx++)
3783 {
3784 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3785 if (baked)
3786 { baked.lightmapCacheKey = null; }
3787 }
3788 }
3789 }
3790
3791 /**
3792 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
3793 * occluding tiles stay flat and contribute 0 into others so light does not bleed
3794 * through a wall to the far side. Diagonals only when both cardinals are clear.
3795 */
3796 #writeChunkLightmap (baked, activeLights, lightOcclusion)
3797 {
3798 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3799 if (!snapshot)
3800 { return; }
3801 const cacheKey = this.#chunkLightmapCacheKey(baked, activeLights);
3802 if (cacheKey && baked.lightmapCacheKey === cacheKey)
3803 { return; }
3804 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3805 const pixelCount = atlasPx * atlasPx * 4;
3806 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
3807 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
3808 const pixels = baked.lightmapPixels;
3809
3810 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
3811 const simple = this.lightingMode === "simple";
3812
3813 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3814 {
3815 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3816 {
3817 const baseX = localX * SPRITE_SIZE_PX;
3818 const baseY = localY * SPRITE_SIZE_PX;
3819 if (simple)
3820 {
3821 const gridW = CHUNK_SIZE + 2;
3822 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
3823 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3824 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3825 {
3826 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3827 {
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 continue;
3836 }
3837 const corners = this.#tileLitCorners(baked, localX, localY);
3838 const nw = corners.nw;
3839 const ne = corners.ne;
3840 const sw = corners.sw;
3841 const se = corners.se;
3842 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3843 {
3844 const v = (py + 0.5) / SPRITE_SIZE_PX;
3845 const left = nw + (sw - nw) * v;
3846 const right = ne + (se - ne) * v;
3847 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3848 {
3849 const u = (px + 0.5) / SPRITE_SIZE_PX;
3850 const intensity = left + (right - left) * u;
3851 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3852 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3853 pixels[offset] = value;
3854 pixels[offset + 1] = value;
3855 pixels[offset + 2] = value;
3856 pixels[offset + 3] = 255;
3857 }
3858 }
3859 }
3860 }
3861 const ctx = baked.lightmapCanvas.getContext("2d");
3862 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
3863 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3864 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
3865 baked.lightmapCacheKey = cacheKey;
3866 }
3867
3868 #updateSwipes (now)
3869 {
3870 this.swipes = this.swipes.filter((swipe) =>
3871 {
3872 if (swipe.lerp && swipe.started != null)
3873 {
3874 const durationMs = swipe.durationMs ?? 400;
3875 const t = Math.min(1, (now - swipe.started) / durationMs);
3876 const fromPivot = this.#projectileLaunchPoint(
3877 swipe.attackerId ?? null,
3878 swipe.fromTileX,
3879 swipe.fromTileY
3880 );
3881 const toPivot = this.#projectileEndPivot(swipe);
3882 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
3883 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
3884 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
3885 if (swipe.object?.transform)
3886 {
3887 swipe.object.transform.rotation = Math.atan2(
3888 toPivot.y - fromPivot.y,
3889 toPivot.x - fromPivot.x
3890 ) * (180 / Math.PI);
3891 }
3892 if (swipe.spellProjectile && swipe.baseSprite)
3893 {
3894 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
3895 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
3896 if (image && swipe.object?.renderer)
3897 { swipe.object.renderer.sprite = image; }
3898 }
3899 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
3900 if (!swipe.spellProjectile)
3901 {
3902 this.#applyPhysicalCombatFxDarkness(
3903 swipe.object,
3904 swipe.fromTileX,
3905 swipe.fromTileY,
3906 swipe.tileX,
3907 swipe.tileY,
3908 swipe.dualTint ?? null
3909 );
3910 }
3911 }
3912 else if (swipe.fromTileX != null && !swipe.spellProjectile)
3913 {
3914 this.#applyPhysicalCombatFxDarkness(
3915 swipe.object,
3916 swipe.fromTileX,
3917 swipe.fromTileY,
3918 swipe.tileX,
3919 swipe.tileY,
3920 swipe.dualTint ?? null
3921 );
3922 }
3923 if (swipe.until > now)
3924 { return true; }
3925 const onImpact = swipe.onImpact;
3926 swipe.onImpact = null;
3927 swipe.object?.destroy();
3928 if (typeof onImpact === "function")
3929 {
3930 try
3931 { onImpact(); }
3932 catch (_)
3933 { /* presentation only */ }
3934 }
3935 return false;
3936 });
3937 }
3938
3939 #projectileEndPivot (swipe)
3940 {
3941 if (swipe.trackTarget && swipe.targetId != null)
3942 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
3943 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
3944 }
3945
3946 /**
3947 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
3948 */
3949 #projectileLaunchPoint (entityId, tileX, tileY)
3950 {
3951 const entity = entityId != null ? this.entities.get(entityId) : null;
3952 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
3953 {
3954 const zoom = this.zoom;
3955 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
3956 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
3957 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
3958 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
3959 return {
3960 x: pivotX,
3961 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
3962 };
3963 }
3964 return tilePivot(tileX, tileY, this.tileSize());
3965 }
3966
3967 /**
3968 * Aim point: sprite centre for creatures, tile centre for tile targets.
3969 */
3970 #projectileAimPoint (entityId, tileX, tileY)
3971 {
3972 const entity = entityId != null ? this.entities.get(entityId) : null;
3973 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
3974 {
3975 const zoom = this.zoom;
3976 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
3977 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
3978 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
3979 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
3980 }
3981 return tilePivot(tileX, tileY, this.tileSize());
3982 }
3983
3984 #updateDamageNumbers (now)
3985 {
3986 const layer = this.damageNumbersEl;
3987 if (!layer)
3988 { return; }
3989 this.damageFloats = this.damageFloats.filter((entry) =>
3990 {
3991 const elapsed = now - entry.started;
3992 if (elapsed >= DAMAGE_FLOAT_MS)
3993 {
3994 entry.element?.remove();
3995 return false;
3996 }
3997 const entity = this.entities.get(entry.entityId);
3998 if (!entity)
3999 {
4000 entry.element?.remove();
4001 return false;
4002 }
4003 if (!entry.element)
4004 {
4005 entry.element = document.createElement("span");
4006 entry.element.className = "damage-number";
4007 entry.element.textContent = String(entry.damage);
4008 layer.append(entry.element);
4009 }
4010 const anchor = this.nametagAnchor(entity);
4011 if (!anchor)
4012 { return true; }
4013 const t = elapsed / DAMAGE_FLOAT_MS;
4014 entry.element.style.left = `${anchor.x}px`;
4015 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
4016 entry.element.style.opacity = String(1 - t);
4017 return true;
4018 });
4019 }
4020
4021 #updateSkillLevelFloats (now)
4022 {
4023 const layer = this.skillLevelFloatsEl;
4024 if (!layer)
4025 { return; }
4026 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
4027 {
4028 const elapsed = now - entry.started;
4029 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
4030 {
4031 entry.element?.remove();
4032 return false;
4033 }
4034 const entity = this.entities.get(entry.entityId);
4035 if (!entity)
4036 {
4037 entry.element?.remove();
4038 return false;
4039 }
4040 if (!entry.element)
4041 {
4042 const root = document.createElement("div");
4043 root.className = "skill-level-float";
4044
4045 const levelEl = document.createElement("div");
4046 levelEl.className = "skill-level-float-level";
4047 levelEl.textContent = `↑${entry.level}↑`;
4048
4049 const icon = document.createElement("img");
4050 icon.className = "skill-level-float-icon";
4051 icon.src = entry.icon;
4052 icon.alt = entry.displayName || "";
4053
4054 root.append(levelEl, icon);
4055 entry.element = root;
4056 layer.append(entry.element);
4057 }
4058 const anchor = this.nametagAnchor(entity);
4059 if (!anchor)
4060 { return true; }
4061 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
4062 entry.element.style.left = `${anchor.x}px`;
4063 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
4064 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
4065 return true;
4066 });
4067 }
4068
4069 #syncBloomLayer ()
4070 {
4071 if (!this.bloomEnabled)
4072 {
4073 this.scene.setLayers([{ name: "default" }]);
4074 return;
4075 }
4076 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
4077 this.scene.setLayers([
4078 { name: "default" },
4079 {
4080 name: RENDER_LAYER_BLOOM,
4081 composite: "add",
4082 postShaders: Shader.getBloomPostChain({
4083 threshold: settings.bloomThreshold,
4084 softKnee: settings.bloomSoftKnee,
4085 intensity: settings.bloomIntensity,
4086 blurSize: settings.bloomBlurSize,
4087 saturation: settings.bloomSaturation,
4088 colorPreserve: settings.bloomColorPreserve,
4089 dilate: settings.bloomDilate,
4090 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
4091 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
4092 })
4093 }
4094 ]);
4095 }
4096}
4097
4098export function nightFactor (hour, nightDarkness = 0.72)
4099{
4100 const peak = Math.min(1, Math.max(0, nightDarkness));
4101 if (hour >= 8 && hour <= 16)
4102 { return 0; }
4103 if (hour >= 22 || hour <= 5)
4104 { return peak; }
4105 if (hour < 8)
4106 { return lerp(peak, 0, (hour - 5) / 3); }
4107 return lerp(0, peak, (hour - 16) / 6);
4108}
4109
4110function bodySpriteName (sex)
4111{
4112 const key = sex === "female" ? "player-body-female" : "player-body-male";
4113 return spriteImageName("character", key, key);
4114}
4115
4116function lerp (a, b, t)
4117{
4118 return a + (b - a) * Math.min(1, Math.max(0, t));
4119}
4120
4121function makeLightmapCanvas (size)
4122{
4123 const canvas = document.createElement("canvas");
4124 canvas.width = size;
4125 canvas.height = size;
4126 return canvas;
4127}
4128
4129function copyCanvas (source, dest)
4130{
4131 const ctx = dest.getContext("2d");
4132 ctx.imageSmoothingEnabled = false;
4133 ctx.clearRect(0, 0, dest.width, dest.height);
4134 ctx.drawImage(source, 0, 0);
4135}
4136
4137function drawHpBar (canvas, current, max)
4138{
4139 const ctx = canvas.getContext("2d");
4140 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
4141 ctx.fillStyle = "#000000";
4142 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
4143 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
4144 const fillW = Math.round(12 * ratio);
4145 if (fillW > 0)
4146 {
4147 ctx.fillStyle = "#ff0000";
4148 ctx.fillRect(1, 1, fillW, 2);
4149 }
4150}