BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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