BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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