BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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