BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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