BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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