BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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