BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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