BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 88.3 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 if (payload.level != null)
1465 { entity.level = payload.level | 0; }
1466 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1467 entity.canFight = payload.canFight != null
1468 ? !!payload.canFight
1469 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1470 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1471 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1472 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1473 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1474 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1475 if (payload.visualScale != null)
1476 { entity.visualScale = Number(payload.visualScale) || 1; }
1477 else if (entity.visualScale == null)
1478 { entity.visualScale = 1; }
1479 if (payload.health != null)
1480 { entity.health = payload.health; }
1481 if (payload.maxHealth != null)
1482 { entity.maxHealth = payload.maxHealth; }
1483 if (payload.firstName)
1484 { entity.firstName = payload.firstName; }
1485 if (payload.lastName)
1486 { entity.lastName = payload.lastName; }
1487 entity.firstName = entity.firstName ?? "";
1488 entity.lastName = entity.lastName ?? "";
1489 if (payload.worldX != null && payload.worldY != null)
1490 {
1491 entity.worldX = payload.worldX;
1492 entity.worldY = payload.worldY;
1493 entity.visualX = payload.worldX * size;
1494 entity.visualY = payload.worldY * size;
1495 entity.targetX = entity.visualX;
1496 entity.targetY = entity.visualY;
1497 }
1498 else
1499 {
1500 entity.visualX = pivot.x;
1501 entity.visualY = pivot.y;
1502 entity.targetX = pivot.x;
1503 entity.targetY = pivot.y;
1504 }
1505 entity.fromX = entity.visualX;
1506 entity.fromY = entity.visualY;
1507 if (payload.layers)
1508 { this.#applyLayers(entity, payload.layers); }
1509 this.#syncHpBar(entity);
1510 this.#placeEntity(entity, performance.now());
1511 }
1512
1513 #applyLayers (entity, layers)
1514 {
1515 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
1516 this.#rebuildOverlays(entity);
1517 }
1518
1519 #setGatherToolOverlay (entity, toolItemId)
1520 {
1521 entity.gatherToolItemId = toolItemId;
1522 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
1523 this.#rebuildOverlays(entity);
1524 this.#placeEntity(entity, performance.now());
1525 }
1526
1527 #expireGatherToolOverlay (entity, now)
1528 {
1529 if (entity.gatherToolItemId == null)
1530 { return; }
1531 if ((entity.gatherToolUntil ?? 0) > now)
1532 { return; }
1533 entity.gatherToolItemId = null;
1534 entity.gatherToolUntil = 0;
1535 this.#rebuildOverlays(entity);
1536 }
1537
1538 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
1539 #layersForDisplay (entity)
1540 {
1541 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
1542 const toolId = entity.gatherToolItemId;
1543 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
1544 { return layers; }
1545 const equip = itemEquipSprite(toolId);
1546 if (!equip || !this.game.images[equip])
1547 { return layers; }
1548 const replacement = {
1549 sprite: equip,
1550 itemId: toolId,
1551 tint: resolveEquipTint(toolId)
1552 };
1553 for (let index = layers.length - 1; index >= 1; index--)
1554 {
1555 const def = itemDefinition(layers[index].itemId);
1556 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
1557 {
1558 layers[index] = replacement;
1559 return layers;
1560 }
1561 }
1562 layers.push(replacement);
1563 return layers;
1564 }
1565
1566 #rebuildOverlays (entity)
1567 {
1568 const layers = this.#layersForDisplay(entity);
1569 const base = layers[0]?.sprite
1570 ?? bodySpriteName(entity.sex);
1571 if (this.game.images[base])
1572 {
1573 entity.object.renderer.sprite = this.game.images[base];
1574 this.#startIdleAnimation(entity.object);
1575 }
1576 for (const overlay of entity.overlays ?? [])
1577 { overlay.destroy(); }
1578 for (const overlay of entity.bloomOverlays ?? [])
1579 { overlay.destroy(); }
1580 entity.overlays = [];
1581 entity.overlayTints = [];
1582 entity.overlayTightFit = [];
1583 entity.bloomOverlays = [];
1584 for (const layer of layers.slice(1))
1585 {
1586 const image = this.game.images[layer.sprite];
1587 if (!image)
1588 { continue; }
1589 const object = new GameObject(0, 0, image, SORT_ENTITY);
1590 this.scene.addObject(object);
1591 entity.overlays.push(object);
1592 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1593 entity.overlayTightFit.push(!!layerDef?.tightFit);
1594 entity.overlayTints.push(
1595 layer.tint
1596 ? normalizeRgb(layer.tint)
1597 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)
1598 );
1599 const bloomName = bloomCompanionName(layer.sprite);
1600 const bloomImage = this.game.images[bloomName];
1601 if (!bloomImage)
1602 { continue; }
1603 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
1604 bloom.renderer.layer = RENDER_LAYER_BLOOM;
1605 this.#markUnlit(bloom);
1606 this.scene.addObject(bloom);
1607 entity.bloomOverlays.push(bloom);
1608 }
1609 }
1610
1611 #placeEntity (entity, now = performance.now())
1612 {
1613 const zoom = this.zoom;
1614 const offsetX = entity.shoveOffsetX ?? 0;
1615 const offsetY = entity.shoveOffsetY ?? 0;
1616 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
1617 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
1618 let walkTilt = 0;
1619 if (entity.lerpStarted != null)
1620 {
1621 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
1622 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
1623 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
1624 walkTilt = Math.sin(cycles) * tilt;
1625 }
1626 const flashStrength = (entity.damageFlashUntil ?? 0) > now
1627 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
1628 : 0;
1629 const tileShade = this.#entityShadeAlpha(entity, now);
1630 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
1631
1632 entity.object.transform.rotation = walkTilt;
1633 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
1634 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
1635 for (let index = 0; index < (entity.overlays ?? []).length; index++)
1636 {
1637 const overlay = entity.overlays[index];
1638 const overlaySortY = pivotY + 0.5 * (index + 1);
1639 overlay.transform.rotation = walkTilt;
1640 if (entity.overlayTightFit?.[index])
1641 {
1642 this.#syncTightFitLitSprite(
1643 overlay,
1644 entity,
1645 tileShade,
1646 flashStrength,
1647 wade,
1648 entity.overlayTints?.[index] ?? null
1649 );
1650 }
1651 else
1652 {
1653 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
1654 }
1655 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
1656 }
1657 for (const overlay of entity.bloomOverlays ?? [])
1658 {
1659 this.#setRendererVisible(overlay, this.bloomEnabled);
1660 if (!this.bloomEnabled)
1661 { continue; }
1662 overlay.transform.rotation = walkTilt;
1663 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
1664 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
1665 }
1666 this.#placeHpBar(entity, pivotX, pivotY);
1667 }
1668
1669 #markUnlit (object)
1670 {
1671 if (!object?.renderer)
1672 { return; }
1673 object._lit = false;
1674 object.renderer.shader = null;
1675 object.renderer.shaderUniforms = null;
1676 object.renderer.secondaryMap = null;
1677 }
1678
1679 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
1680 {
1681 if (!object?.renderer || object._lit === false)
1682 { return; }
1683 object._lit = true;
1684 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1685 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1686 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1687 const tint = tintColor ? normalizeRgb(tintColor) : null;
1688 if (tint)
1689 {
1690 object.renderer.shader = getTintLitSpriteShader();
1691 object.renderer.shaderUniforms = {
1692 u_darkness: dark,
1693 u_strength: flash,
1694 u_wade: wade ? 1 : 0,
1695 u_spriteHeight: height,
1696 u_useTint: 1,
1697 u_tintColor: [tint.r, tint.g, tint.b]
1698 };
1699 }
1700 else
1701 {
1702 object.renderer.shader = getSpriteLightingShader();
1703 object.renderer.shaderUniforms = {
1704 u_darkness: dark,
1705 u_strength: flash,
1706 u_wade: wade ? 1 : 0,
1707 u_spriteHeight: height
1708 };
1709 }
1710 object.renderer.secondaryMap = null;
1711 }
1712
1713 #bodySecondaryMap (entity)
1714 {
1715 return entity?.object?.renderer?.sprite?.g_image ?? null;
1716 }
1717
1718 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
1719 {
1720 if (!overlay?.renderer || entity?.object?.renderer == null)
1721 { return; }
1722 const bodyMap = this.#bodySecondaryMap(entity);
1723 if (!bodyMap)
1724 {
1725 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
1726 return;
1727 }
1728 overlay._lit = true;
1729 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1730 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1731 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1732 const tint = tintColor ? normalizeRgb(tintColor) : null;
1733 overlay.renderer.secondaryMap = bodyMap;
1734 if (tint)
1735 {
1736 overlay.renderer.shader = getTightFitTintLitSpriteShader();
1737 overlay.renderer.shaderUniforms = {
1738 u_darkness: dark,
1739 u_strength: flash,
1740 u_wade: wade ? 1 : 0,
1741 u_spriteHeight: height,
1742 u_useTint: 1,
1743 u_tintColor: [tint.r, tint.g, tint.b]
1744 };
1745 }
1746 else
1747 {
1748 overlay.renderer.shader = getTightFitLitSpriteShader();
1749 overlay.renderer.shaderUniforms = {
1750 u_darkness: dark,
1751 u_strength: flash,
1752 u_wade: wade ? 1 : 0,
1753 u_spriteHeight: height
1754 };
1755 }
1756 }
1757
1758 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false)
1759 {
1760 if (!object?.renderer || object._lit === false || !dualTint)
1761 { return; }
1762 object._lit = true;
1763 const shaft = normalizeRgb(dualTint.shaft);
1764 const tip = normalizeRgb(dualTint.tip);
1765 const dark = Math.min(1, Math.max(0, darkness ?? 0));
1766 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
1767 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
1768 object.renderer.shader = getDualTintLitSpriteShader();
1769 object.renderer.shaderUniforms = {
1770 u_darkness: dark,
1771 u_strength: flash,
1772 u_wade: wade ? 1 : 0,
1773 u_spriteHeight: height,
1774 u_shaftTint: [shaft.r, shaft.g, shaft.b],
1775 u_tipTint: [tip.r, tip.g, tip.b]
1776 };
1777 object.renderer.secondaryMap = null;
1778 }
1779
1780 #syncGroundItemSprite (item, darkness)
1781 {
1782 if (item?.dualTint)
1783 {
1784 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
1785 return;
1786 }
1787 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
1788 }
1789
1790 #groundTypeAt (tileX, tileY)
1791 {
1792 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1793 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1794 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1795 if (!snapshot)
1796 { return null; }
1797 const localX = tileX - chunkX * CHUNK_SIZE;
1798 const localY = tileY - chunkY * CHUNK_SIZE;
1799 const index = localY * CHUNK_SIZE + localX;
1800 return normalizeGround(snapshot.grounds?.[index]).typeId;
1801 }
1802
1803 #waterCoastEdges (tileX, tileY)
1804 {
1805 const season = this.worldSeason;
1806 return {
1807 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
1808 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
1809 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
1810 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
1811 };
1812 }
1813
1814 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
1815 {
1816 if (!object?.renderer)
1817 { return; }
1818 const lit = corners ?? {
1819 nw: fallbackLit,
1820 ne: fallbackLit,
1821 sw: fallbackLit,
1822 se: fallbackLit
1823 };
1824 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
1825 object._lit = true;
1826 object.renderer.shader = getWaterGroundShader();
1827 object.renderer.secondaryMap = null;
1828 object.renderer.shaderUniforms = {
1829 u_ambientDark: dark,
1830 u_litNW: lit.nw,
1831 u_litNE: lit.ne,
1832 u_litSW: lit.sw,
1833 u_litSE: lit.se,
1834 u_time: timeSec,
1835 u_edgeN: edges?.n ?? 0,
1836 u_edgeE: edges?.e ?? 0,
1837 u_edgeS: edges?.s ?? 0,
1838 u_edgeW: edges?.w ?? 0
1839 };
1840 }
1841
1842 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
1843 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
1844 {
1845 if (!objects?.ground)
1846 { return; }
1847 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
1848 {
1849 objects.waterEdges = null;
1850 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
1851 return;
1852 }
1853 const fallbackLit = ambientDark > 0
1854 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
1855 : 1;
1856 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
1857 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
1858 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
1859 const localX = objects.tileX - chunkX * CHUNK_SIZE;
1860 const localY = objects.tileY - chunkY * CHUNK_SIZE;
1861 let litCorners = null;
1862 if (chunkBaked)
1863 {
1864 if (this.lightingMode === "simple")
1865 {
1866 const gridW = CHUNK_SIZE + 2;
1867 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
1868 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
1869 }
1870 else
1871 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
1872 }
1873 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
1874 this.#syncWaterGroundSprite(
1875 objects.ground,
1876 litCorners,
1877 ambientDark,
1878 objects.waterEdges,
1879 timeSec,
1880 fallbackLit
1881 );
1882 }
1883
1884 #ambientDarkness ()
1885 {
1886 const hour = this.nightPreview ?? this.worldHour;
1887 let dark = nightFactor(hour, this.settings.nightDarkness);
1888 if (this.localBlind)
1889 { dark = Math.min(1, dark + 0.85); }
1890 return dark;
1891 }
1892
1893 setLocalBlind (blind)
1894 {
1895 this.localBlind = !!blind;
1896 }
1897
1898 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
1899 #blindVisionLight ()
1900 {
1901 if (!this.localBlind)
1902 { return null; }
1903 const local = this.entities.get(this.localEntityId);
1904 if (!local)
1905 { return null; }
1906 const tileSize = this.tileSize();
1907 return {
1908 tileX: Math.floor(local.visualX / tileSize),
1909 tileY: Math.floor(local.visualY / tileSize),
1910 range: 2.25,
1911 intensity: 1
1912 };
1913 }
1914
1915 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
1916 {
1917 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
1918 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
1919 const dark = (fromAlpha + toAlpha) / 2;
1920 if (dualTint)
1921 {
1922 this.#syncDualTintLitSprite(object, dark, dualTint);
1923 return;
1924 }
1925 this.#syncLitSprite(object, dark);
1926 }
1927
1928 #dualTintFromPayload (payload)
1929 {
1930 if (!payload?.shaftTint || !payload?.tipTint)
1931 { return null; }
1932 return { shaft: payload.shaftTint, tip: payload.tipTint };
1933 }
1934
1935 #syncHpBar (entity)
1936 {
1937 const current = entity.health;
1938 const max = entity.maxHealth;
1939 const show = current != null
1940 && max != null
1941 && max > 0
1942 && current < max;
1943 if (!show)
1944 {
1945 entity.hpBar?.destroy();
1946 entity.hpBar = null;
1947 entity.hpBarCanvas = null;
1948 return;
1949 }
1950 if (!entity.hpBarCanvas)
1951 {
1952 entity.hpBarCanvas = document.createElement("canvas");
1953 entity.hpBarCanvas.width = HP_BAR_W;
1954 entity.hpBarCanvas.height = HP_BAR_H;
1955 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
1956 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
1957 this.#markUnlit(entity.hpBar);
1958 this.scene.addObject(entity.hpBar);
1959 }
1960 drawHpBar(entity.hpBarCanvas, current, max);
1961 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
1962 }
1963
1964 #placeHpBar (entity, pivotX, pivotY)
1965 {
1966 if (!entity.hpBar)
1967 { return; }
1968 const sprite = entity.object?.renderer?.sprite;
1969 if (!sprite)
1970 { return; }
1971 const zoom = this.zoom;
1972 const drawH = sprite.height * zoom;
1973 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
1974 const spriteTop = centerY - drawH / 2;
1975 const barW = HP_BAR_W * zoom;
1976 const barH = HP_BAR_H * zoom;
1977 entity.hpBar.transform.position.x = pivotX;
1978 entity.hpBar.transform.position.y = spriteTop - barH / 2;
1979 entity.hpBar.transform.size = new vector(barW, barH);
1980 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
1981 this.#markSortDirty();
1982 }
1983
1984 #rebuildChunk (snapshot)
1985 {
1986 this.#bakeAndPlaceChunk(snapshot);
1987 const tall = new Set(
1988 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
1989 .map((entry) => `${entry.tileX},${entry.tileY}`)
1990 );
1991 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1992 {
1993 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1994 {
1995 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
1996 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
1997 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
1998 }
1999 }
2000 }
2001
2002 #rebakeAllChunks ()
2003 {
2004 for (const snapshot of this.chunks.values())
2005 { this.#rebuildChunk(snapshot); }
2006 }
2007
2008 #bakeAndPlaceChunk (snapshot)
2009 {
2010 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2011 const atlases = bakeChunkAtlases({
2012 snapshot,
2013 catalog: this.catalog,
2014 images: this.game.images,
2015 preview: this.preview,
2016 season: this.worldSeason
2017 });
2018 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2019 let baked = this.bakedChunks.get(key);
2020 if (!baked)
2021 {
2022 const lightmapCanvas = makeLightmapCanvas(atlasPx);
2023 baked = {
2024 groundCanvas: atlases.ground,
2025 blockCanvases: atlases.blockRows,
2026 bloomCanvas: atlases.bloom,
2027 lightmapCanvas,
2028 groundImage: frameworkImageFromCanvas(atlases.ground),
2029 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
2030 bloomImage: frameworkImageFromCanvas(atlases.bloom),
2031 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
2032 groundObject: null,
2033 blockObjects: [],
2034 bloomObject: null,
2035 tallBlocks: atlases.tallBlocks,
2036 animatedGrounds: atlases.animatedGrounds,
2037 lightmapPixels: null
2038 };
2039 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
2040 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
2041 this.scene.addObject(baked.groundObject);
2042 for (let row = 0; row < CHUNK_SIZE; row++)
2043 {
2044 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
2045 this.#applyAtlasLighting(object, baked.lightmapImage, row);
2046 this.scene.addObject(object);
2047 baked.blockObjects.push(object);
2048 }
2049 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
2050 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2051 this.#markUnlit(baked.bloomObject);
2052 this.scene.addObject(baked.bloomObject);
2053 this.bakedChunks.set(key, baked);
2054 }
2055 else
2056 {
2057 copyCanvas(atlases.ground, baked.groundCanvas);
2058 for (let row = 0; row < CHUNK_SIZE; row++)
2059 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
2060 copyCanvas(atlases.bloom, baked.bloomCanvas);
2061 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2062 for (const canvas of baked.blockCanvases)
2063 { invalidateCanvasTexture(this.scene, canvas); }
2064 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2065 baked.tallBlocks = atlases.tallBlocks;
2066 baked.animatedGrounds = atlases.animatedGrounds;
2067 }
2068 baked.chunkX = snapshot.chunkX;
2069 baked.chunkY = snapshot.chunkY;
2070 this.#layoutBakedChunk(snapshot);
2071 }
2072
2073 #applyAtlasLighting (object, lightmapImage, lightRow)
2074 {
2075 if (!object?.renderer)
2076 { return; }
2077 object._lit = true;
2078 object.renderer.shader = getAtlasLightingShader();
2079 object.renderer.secondaryMap = lightmapImage;
2080 object.renderer.shaderUniforms = {
2081 u_ambientDark: 0,
2082 u_lightRow: lightRow
2083 };
2084 }
2085
2086 #layoutBakedChunk (snapshot)
2087 {
2088 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2089 const baked = this.bakedChunks.get(key);
2090 if (!baked)
2091 { return; }
2092 const size = this.tileSize();
2093 const left = snapshot.chunkX * CHUNK_SIZE * size;
2094 const top = snapshot.chunkY * CHUNK_SIZE * size;
2095 const chunkPx = CHUNK_SIZE * size;
2096 baked.groundObject.transform.position.x = left + chunkPx / 2;
2097 baked.groundObject.transform.position.y = top + chunkPx / 2;
2098 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
2099 baked.groundObject.layer = LAYER_GROUND;
2100
2101 for (let row = 0; row < CHUNK_SIZE; row++)
2102 {
2103 const object = baked.blockObjects[row];
2104 const rowY = top + row * size + size / 2;
2105 object.transform.position.x = left + chunkPx / 2;
2106 object.transform.position.y = rowY;
2107 object.transform.size = new vector(chunkPx, size);
2108 object.layer = ySortLayer(rowY, SORT_BLOCK);
2109 }
2110
2111 baked.bloomObject.transform.position.x = left + chunkPx / 2;
2112 baked.bloomObject.transform.position.y = top + chunkPx / 2;
2113 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
2114 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
2115 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2116 this.#markSortDirty();
2117 setNearestFilter(this.scene, baked.groundCanvas);
2118 for (const canvas of baked.blockCanvases)
2119 { setNearestFilter(this.scene, canvas); }
2120 setNearestFilter(this.scene, baked.bloomCanvas);
2121 setNearestFilter(this.scene, baked.lightmapCanvas);
2122 }
2123
2124 #destroyBakedChunk (key)
2125 {
2126 const baked = this.bakedChunks.get(key);
2127 if (!baked)
2128 { return; }
2129 baked.groundObject?.destroy();
2130 for (const object of baked.blockObjects ?? [])
2131 { object.destroy(); }
2132 baked.bloomObject?.destroy();
2133 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2134 for (const canvas of baked.blockCanvases ?? [])
2135 { invalidateCanvasTexture(this.scene, canvas); }
2136 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2137 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2138 this.bakedChunks.delete(key);
2139 }
2140
2141 #redrawPreview ()
2142 {
2143 if (!this.preview)
2144 { return; }
2145 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
2146 if (snapshot)
2147 { this.#rebuildChunk(snapshot); }
2148 }
2149
2150 #refreshWaterCoastsNear (chunkX, chunkY)
2151 {
2152 const timeSec = performance.now() / 1000;
2153 for (const objects of this.tiles.values())
2154 {
2155 if (!objects.ground || !isWaterGround(objects.groundTypeId))
2156 { continue; }
2157 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
2158 { continue; }
2159 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
2160 }
2161 }
2162
2163 #drawTile (tileX, tileY, forceTall = null)
2164 {
2165 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2166 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2167 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2168 if (!snapshot)
2169 { return; }
2170 const localX = tileX - chunkX * CHUNK_SIZE;
2171 const localY = tileY - chunkY * CHUNK_SIZE;
2172 const index = localY * CHUNK_SIZE + localX;
2173 const key = `${tileX},${tileY}`;
2174 let objects = this.tiles.get(key);
2175 if (!objects)
2176 {
2177 objects = { chunkX, chunkY, tileX, tileY };
2178 this.tiles.set(key, objects);
2179 }
2180 objects.tileX = tileX;
2181 objects.tileY = tileY;
2182 objects.chunkX = chunkX;
2183 objects.chunkY = chunkY;
2184 objects.light = snapshot.light[index] ?? 0;
2185
2186 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
2187 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2188 if (animatedGround)
2189 {
2190 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
2191 if (objects.ground)
2192 {
2193 const size = this.tileSize();
2194 objects.ground.transform.position.x = tileX * size + size / 2;
2195 objects.ground.transform.position.y = tileY * size + size / 2;
2196 objects.ground.transform.size = new vector(size, size);
2197 objects.ground.layer = LAYER_GROUND;
2198 objects.groundTypeId = animatedGround.typeId;
2199 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
2200 this.#markSortDirty();
2201 }
2202 if (animatedGround.bloom)
2203 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
2204 else
2205 {
2206 objects.groundBloom?.destroy();
2207 objects.groundBloom = null;
2208 }
2209 }
2210 else
2211 {
2212 objects.ground?.destroy();
2213 objects.ground = null;
2214 objects.groundBloom?.destroy();
2215 objects.groundBloom = null;
2216 objects.groundTypeId = null;
2217 objects.waterEdges = null;
2218 }
2219
2220 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2221 const isTall = forceTall === true || !!tallEntry;
2222 if (isTall && tallEntry)
2223 {
2224 const pivot = tilePivot(tileX, tileY, this.tileSize());
2225 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
2226 if (objects.block)
2227 {
2228 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
2229 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
2230 }
2231 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
2232 }
2233 else
2234 {
2235 objects.block?.destroy();
2236 objects.block = null;
2237 objects.blockBloom?.destroy();
2238 objects.blockBloom = null;
2239 }
2240 }
2241
2242 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
2243 {
2244 if (!name)
2245 {
2246 existing?.destroy();
2247 return null;
2248 }
2249 const object = this.#ensureSprite(existing, name, sortOrder);
2250 if (!object)
2251 { return null; }
2252 object.renderer.layer = RENDER_LAYER_BLOOM;
2253 this.#markUnlit(object);
2254 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
2255 return object;
2256 }
2257
2258 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
2259 {
2260 const sprite = object?.renderer?.sprite;
2261 if (!sprite)
2262 { return; }
2263 const zoom = this.zoom;
2264 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
2265 const factor = Math.max(0.1, Number(scale) || 1);
2266 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
2267 object.transform.position.x = center.x;
2268 object.transform.position.y = center.y;
2269 object.transform.size = new vector(draw.w * factor, draw.h * factor);
2270 object.layer = ySortLayer(sortY, subOrder);
2271 this.#markSortDirty();
2272 }
2273
2274 #ensureSprite (existing, name, layer)
2275 {
2276 const sprite = this.game.images[name];
2277 if (!sprite)
2278 {
2279 existing?.destroy();
2280 return null;
2281 }
2282 if (!existing || existing.renderer.sprite !== sprite)
2283 {
2284 existing?.destroy();
2285 existing = new GameObject(0, 0, sprite, layer);
2286 this.#syncLitSprite(existing, 0);
2287 this.scene.addObject(existing);
2288 this.#startIdleAnimation(existing);
2289 }
2290 return existing;
2291 }
2292
2293 #startIdleAnimation (object)
2294 {
2295 const sprite = object?.renderer?.sprite;
2296 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
2297 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
2298 }
2299
2300 #neighborClosed (snapshot, dir, dx, dy)
2301 {
2302 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2303 if (other)
2304 { return !other.open; }
2305 return !!snapshot.closedEdges?.[dir];
2306 }
2307
2308 #rebuildAllEdges ()
2309 {
2310 const seen = new Set();
2311 for (const snapshot of this.chunks.values())
2312 {
2313 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2314 seen.add(key);
2315 this.#rebuildChunkEdges(snapshot);
2316 }
2317 for (const key of [...this.edges.keys()])
2318 {
2319 if (!seen.has(key))
2320 { this.#destroyEdges(key); }
2321 }
2322 }
2323
2324 #rebuildChunkEdges (snapshot)
2325 {
2326 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2327 let bars = this.edges.get(key);
2328 if (!bars)
2329 {
2330 bars = {};
2331 this.edges.set(key, bars);
2332 }
2333
2334 const size = this.tileSize();
2335 const chunkPx = CHUNK_SIZE * size;
2336 const left = snapshot.chunkX * CHUNK_SIZE * size;
2337 const top = snapshot.chunkY * CHUNK_SIZE * size;
2338 const centerX = left + chunkPx / 2;
2339 const centerY = top + chunkPx / 2;
2340 const thickness = Math.max(2, Math.round(2 * this.zoom));
2341 const draw = snapshot.open === true;
2342
2343 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
2344 centerX, top, chunkPx, thickness, true);
2345 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
2346 centerX, top + chunkPx, chunkPx, thickness, true);
2347 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
2348 left, centerY, chunkPx, thickness, false);
2349 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
2350 left + chunkPx, centerY, chunkPx, thickness, false);
2351 }
2352
2353 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
2354 {
2355 if (!visible)
2356 {
2357 if (existing)
2358 { existing.renderer.visible = false; }
2359 return existing;
2360 }
2361
2362 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
2363 this.#markUnlit(existing);
2364 existing.renderer.visible = true;
2365 existing.transform.position.x = x;
2366 existing.transform.position.y = y;
2367 existing.transform.size = horizontal
2368 ? new vector(length, thickness)
2369 : new vector(thickness, length);
2370 existing.layer = LAYER_EDGE;
2371 this.#markSortDirty();
2372 return existing;
2373 }
2374
2375 #destroyEdges (key)
2376 {
2377 const bars = this.edges.get(key);
2378 if (!bars)
2379 { return; }
2380 bars.north?.destroy();
2381 bars.east?.destroy();
2382 bars.south?.destroy();
2383 bars.west?.destroy();
2384 this.edges.delete(key);
2385 }
2386
2387 #entityShadeAlpha (entity, now)
2388 {
2389 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
2390 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
2391 { return toAlpha; }
2392 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
2393 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
2394 return fromAlpha + (toAlpha - fromAlpha) * t;
2395 }
2396
2397 #markSortDirty ()
2398 {
2399 this.scene._sortDirty = true;
2400 }
2401
2402 #updateShade ()
2403 {
2404 const ambientDark = this.#ambientDarkness();
2405 const now = performance.now();
2406 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
2407
2408 const activeLights = [...this.dynamicLights];
2409 for (const light of this.spellLights.values())
2410 {
2411 if (light.until <= now)
2412 { continue; }
2413 activeLights.push({
2414 tileX: light.tileX,
2415 tileY: light.tileY,
2416 range: light.range,
2417 intensity: light.intensity
2418 });
2419 }
2420 for (const key of [...this.spellLights.keys()])
2421 {
2422 if (this.spellLights.get(key).until <= now)
2423 { this.spellLights.delete(key); }
2424 }
2425 const tileSize = this.tileSize();
2426 const blindLight = this.#blindVisionLight();
2427 if (blindLight)
2428 { activeLights.push(blindLight); }
2429 for (const entity of this.entities.values())
2430 {
2431 const range = entity.lightRadiusTiles ?? 0;
2432 if (range <= 0)
2433 { continue; }
2434 activeLights.push({
2435 tileX: Math.floor(entity.visualX / tileSize),
2436 tileY: Math.floor(entity.visualY / tileSize),
2437 range,
2438 intensity: 1
2439 });
2440 }
2441
2442 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
2443
2444 for (const objects of this.tiles.values())
2445 {
2446 if (objects._inViewport === false)
2447 { continue; }
2448 const intensity = this.#tileLightIntensity(objects, activeLights, lightOcclusion);
2449 objects.shadeAlpha = ambientDark * (1 - intensity);
2450 }
2451
2452 for (const baked of this.bakedChunks.values())
2453 {
2454 if (baked._inViewport === false)
2455 { continue; }
2456 this.#writeChunkLightmap(baked, activeLights, lightOcclusion);
2457 if (baked.groundObject?.renderer?.shaderUniforms)
2458 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2459 for (const object of baked.blockObjects ?? [])
2460 {
2461 if (object?.renderer?.shaderUniforms)
2462 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
2463 }
2464 }
2465
2466 const timeSec = now / 1000;
2467 for (const objects of this.tiles.values())
2468 {
2469 if (objects._inViewport === false)
2470 { continue; }
2471 if (objects.block)
2472 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
2473 if (objects.ground && isWaterGround(objects.groundTypeId))
2474 {
2475 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
2476 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
2477 }
2478 else if (objects.ground)
2479 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
2480 }
2481
2482 for (const item of this.groundItems.values())
2483 {
2484 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
2485 this.#syncGroundItemSprite(item, alpha);
2486 }
2487 }
2488
2489 #tileLightIntensity (objects, activeLights, lightOcclusion)
2490 {
2491 const baked = lightIntensity(objects.light ?? 0);
2492 const dynamic = dynamicLightAtTile(
2493 objects.tileX,
2494 objects.tileY,
2495 activeLights,
2496 lightOcclusion
2497 );
2498 return Math.max(baked, dynamic);
2499 }
2500
2501 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
2502 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
2503 {
2504 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
2505 if (tileObjects)
2506 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
2507 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2508 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2509 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2510 if (!snapshot)
2511 { return 0; }
2512 const localX = tileX - chunkX * CHUNK_SIZE;
2513 const localY = tileY - chunkY * CHUNK_SIZE;
2514 const index = localY * CHUNK_SIZE + localX;
2515 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
2516 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
2517 return Math.max(bakedLit, dynamic);
2518 }
2519
2520 /** True when ground or block on this tile occludes light rays (same rules as bake). */
2521 #tileOccludesLight (tileX, tileY)
2522 {
2523 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2524 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2525 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2526 if (!snapshot)
2527 { return false; }
2528 const localX = tileX - chunkX * CHUNK_SIZE;
2529 const localY = tileY - chunkY * CHUNK_SIZE;
2530 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
2531 { return false; }
2532 const index = localY * CHUNK_SIZE + localX;
2533 const ground = normalizeGround(snapshot.grounds?.[index]);
2534 if (!isGroundPassable(ground.typeId))
2535 { return true; }
2536 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
2537 }
2538
2539 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
2540 {
2541 const gridW = CHUNK_SIZE + 2;
2542 const gridSize = gridW * gridW;
2543 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
2544 { baked.lightIntensityGrid = new Float32Array(gridSize); }
2545 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
2546 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
2547 const grid = baked.lightIntensityGrid;
2548 const occlude = baked.lightOccludeGrid;
2549 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
2550 {
2551 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
2552 {
2553 const tileX = baked.chunkX * CHUNK_SIZE + lx;
2554 const tileY = baked.chunkY * CHUNK_SIZE + ly;
2555 const gi = (ly + 1) * gridW + (lx + 1);
2556 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
2557 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
2558 }
2559 }
2560 return { grid, occlude, gridW };
2561 }
2562
2563 #makeLightCornerSampler (grid, occlude, gridW)
2564 {
2565 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
2566 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
2567 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
2568 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
2569 {
2570 const home = sample(homeLx, homeLy);
2571 if (blocks(homeLx, homeLy))
2572 { return home; }
2573 let sum = home;
2574 let count = 1;
2575 sum += openSample(aLx, aLy);
2576 count += 1;
2577 sum += openSample(bLx, bLy);
2578 count += 1;
2579 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
2580 {
2581 sum += openSample(dLx, dLy);
2582 count += 1;
2583 }
2584 return sum / count;
2585 };
2586 return { smoothCorner };
2587 }
2588
2589 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
2590 #tileLitCorners (baked, localX, localY)
2591 {
2592 const grid = baked?.lightIntensityGrid;
2593 const occlude = baked?.lightOccludeGrid;
2594 if (!grid?.length || !occlude?.length)
2595 { return null; }
2596 const gridW = CHUNK_SIZE + 2;
2597 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
2598 return {
2599 nw: smoothCorner(
2600 localX, localY,
2601 localX - 1, localY,
2602 localX, localY - 1,
2603 localX - 1, localY - 1
2604 ),
2605 ne: smoothCorner(
2606 localX, localY,
2607 localX + 1, localY,
2608 localX, localY - 1,
2609 localX + 1, localY - 1
2610 ),
2611 sw: smoothCorner(
2612 localX, localY,
2613 localX - 1, localY,
2614 localX, localY + 1,
2615 localX - 1, localY + 1
2616 ),
2617 se: smoothCorner(
2618 localX, localY,
2619 localX + 1, localY,
2620 localX, localY + 1,
2621 localX + 1, localY + 1
2622 )
2623 };
2624 }
2625
2626 /**
2627 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
2628 * occluding tiles stay flat and contribute 0 into others so light does not bleed
2629 * through a wall to the far side. Diagonals only when both cardinals are clear.
2630 */
2631 #writeChunkLightmap (baked, activeLights, lightOcclusion)
2632 {
2633 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
2634 if (!snapshot)
2635 { return; }
2636 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2637 const pixelCount = atlasPx * atlasPx * 4;
2638 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
2639 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
2640 const pixels = baked.lightmapPixels;
2641
2642 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
2643 const simple = this.lightingMode === "simple";
2644
2645 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2646 {
2647 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2648 {
2649 const baseX = localX * SPRITE_SIZE_PX;
2650 const baseY = localY * SPRITE_SIZE_PX;
2651 if (simple)
2652 {
2653 const gridW = CHUNK_SIZE + 2;
2654 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
2655 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2656 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2657 {
2658 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2659 {
2660 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2661 pixels[offset] = value;
2662 pixels[offset + 1] = value;
2663 pixels[offset + 2] = value;
2664 pixels[offset + 3] = 255;
2665 }
2666 }
2667 continue;
2668 }
2669 const corners = this.#tileLitCorners(baked, localX, localY);
2670 const nw = corners.nw;
2671 const ne = corners.ne;
2672 const sw = corners.sw;
2673 const se = corners.se;
2674 for (let py = 0; py < SPRITE_SIZE_PX; py++)
2675 {
2676 const v = (py + 0.5) / SPRITE_SIZE_PX;
2677 const left = nw + (sw - nw) * v;
2678 const right = ne + (se - ne) * v;
2679 for (let px = 0; px < SPRITE_SIZE_PX; px++)
2680 {
2681 const u = (px + 0.5) / SPRITE_SIZE_PX;
2682 const intensity = left + (right - left) * u;
2683 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
2684 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
2685 pixels[offset] = value;
2686 pixels[offset + 1] = value;
2687 pixels[offset + 2] = value;
2688 pixels[offset + 3] = 255;
2689 }
2690 }
2691 }
2692 }
2693 const ctx = baked.lightmapCanvas.getContext("2d");
2694 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
2695 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2696 }
2697
2698 #updateSwipes (now)
2699 {
2700 this.swipes = this.swipes.filter((swipe) =>
2701 {
2702 if (swipe.lerp && swipe.started != null)
2703 {
2704 const durationMs = swipe.durationMs ?? 400;
2705 const t = Math.min(1, (now - swipe.started) / durationMs);
2706 const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());
2707 const toPivot = tilePivot(swipe.tileX, swipe.tileY, this.tileSize());
2708 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
2709 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
2710 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
2711 if (swipe.object?.transform)
2712 {
2713 swipe.object.transform.rotation = Math.atan2(
2714 toPivot.y - fromPivot.y,
2715 toPivot.x - fromPivot.x
2716 ) * (180 / Math.PI);
2717 }
2718 if (swipe.spellProjectile && swipe.baseSprite)
2719 {
2720 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
2721 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
2722 if (image && swipe.object?.renderer)
2723 { swipe.object.renderer.sprite = image; }
2724 }
2725 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
2726 if (!swipe.spellProjectile)
2727 {
2728 this.#applyPhysicalCombatFxDarkness(
2729 swipe.object,
2730 swipe.fromTileX,
2731 swipe.fromTileY,
2732 swipe.tileX,
2733 swipe.tileY,
2734 swipe.dualTint ?? null
2735 );
2736 }
2737 }
2738 else if (swipe.fromTileX != null && !swipe.spellProjectile)
2739 {
2740 this.#applyPhysicalCombatFxDarkness(
2741 swipe.object,
2742 swipe.fromTileX,
2743 swipe.fromTileY,
2744 swipe.tileX,
2745 swipe.tileY,
2746 swipe.dualTint ?? null
2747 );
2748 }
2749 if (swipe.until > now)
2750 { return true; }
2751 swipe.object?.destroy();
2752 return false;
2753 });
2754 }
2755
2756 #updateDamageNumbers (now)
2757 {
2758 const layer = this.damageNumbersEl;
2759 if (!layer)
2760 { return; }
2761 this.damageFloats = this.damageFloats.filter((entry) =>
2762 {
2763 const elapsed = now - entry.started;
2764 if (elapsed >= DAMAGE_FLOAT_MS)
2765 {
2766 entry.element?.remove();
2767 return false;
2768 }
2769 const entity = this.entities.get(entry.entityId);
2770 if (!entity)
2771 {
2772 entry.element?.remove();
2773 return false;
2774 }
2775 if (!entry.element)
2776 {
2777 entry.element = document.createElement("span");
2778 entry.element.className = "damage-number";
2779 entry.element.textContent = String(entry.damage);
2780 layer.append(entry.element);
2781 }
2782 const anchor = this.nametagAnchor(entity);
2783 if (!anchor)
2784 { return true; }
2785 const t = elapsed / DAMAGE_FLOAT_MS;
2786 entry.element.style.left = `${anchor.x}px`;
2787 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
2788 entry.element.style.opacity = String(1 - t);
2789 return true;
2790 });
2791 }
2792
2793 #updateSkillLevelFloats (now)
2794 {
2795 const layer = this.skillLevelFloatsEl;
2796 if (!layer)
2797 { return; }
2798 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
2799 {
2800 const elapsed = now - entry.started;
2801 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
2802 {
2803 entry.element?.remove();
2804 return false;
2805 }
2806 const entity = this.entities.get(entry.entityId);
2807 if (!entity)
2808 {
2809 entry.element?.remove();
2810 return false;
2811 }
2812 if (!entry.element)
2813 {
2814 const root = document.createElement("div");
2815 root.className = "skill-level-float";
2816
2817 const levelEl = document.createElement("div");
2818 levelEl.className = "skill-level-float-level";
2819 levelEl.textContent = `↑${entry.level}↑`;
2820
2821 const icon = document.createElement("img");
2822 icon.className = "skill-level-float-icon";
2823 icon.src = entry.icon;
2824 icon.alt = entry.displayName || "";
2825
2826 root.append(levelEl, icon);
2827 entry.element = root;
2828 layer.append(entry.element);
2829 }
2830 const anchor = this.nametagAnchor(entity);
2831 if (!anchor)
2832 { return true; }
2833 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
2834 entry.element.style.left = `${anchor.x}px`;
2835 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
2836 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
2837 return true;
2838 });
2839 }
2840
2841 #syncBloomLayer ()
2842 {
2843 if (!this.bloomEnabled)
2844 {
2845 this.scene.setLayers([{ name: "default" }]);
2846 return;
2847 }
2848 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
2849 this.scene.setLayers([
2850 { name: "default" },
2851 {
2852 name: RENDER_LAYER_BLOOM,
2853 composite: "add",
2854 postShaders: Shader.getBloomPostChain({
2855 threshold: settings.bloomThreshold,
2856 softKnee: settings.bloomSoftKnee,
2857 intensity: settings.bloomIntensity,
2858 blurSize: settings.bloomBlurSize,
2859 saturation: settings.bloomSaturation,
2860 colorPreserve: settings.bloomColorPreserve,
2861 dilate: settings.bloomDilate,
2862 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
2863 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
2864 })
2865 }
2866 ]);
2867 }
2868}
2869
2870export function nightFactor (hour, nightDarkness = 0.72)
2871{
2872 const peak = Math.min(1, Math.max(0, nightDarkness));
2873 if (hour >= 8 && hour <= 16)
2874 { return 0; }
2875 if (hour >= 22 || hour <= 5)
2876 { return peak; }
2877 if (hour < 8)
2878 { return lerp(peak, 0, (hour - 5) / 3); }
2879 return lerp(0, peak, (hour - 16) / 6);
2880}
2881
2882function bodySpriteName (sex)
2883{
2884 const key = sex === "female" ? "player-body-female" : "player-body-male";
2885 return spriteImageName("character", key, key);
2886}
2887
2888function lerp (a, b, t)
2889{
2890 return a + (b - a) * Math.min(1, Math.max(0, t));
2891}
2892
2893function makeLightmapCanvas (size)
2894{
2895 const canvas = document.createElement("canvas");
2896 canvas.width = size;
2897 canvas.height = size;
2898 return canvas;
2899}
2900
2901function copyCanvas (source, dest)
2902{
2903 const ctx = dest.getContext("2d");
2904 ctx.imageSmoothingEnabled = false;
2905 ctx.clearRect(0, 0, dest.width, dest.height);
2906 ctx.drawImage(source, 0, 0);
2907}
2908
2909function drawHpBar (canvas, current, max)
2910{
2911 const ctx = canvas.getContext("2d");
2912 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
2913 ctx.fillStyle = "#000000";
2914 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
2915 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
2916 const fillW = Math.round(12 * ratio);
2917 if (fillW > 0)
2918 {
2919 ctx.fillStyle = "#ff0000";
2920 ctx.fillRect(1, 1, fillW, 2);
2921 }
2922}