BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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