BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 42.9 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 { makeSnapshotPassable } from "/shared/lighting/tilePassable.js";
4import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
5import { itemSpriteName } from "/shared/definitions/items.js";
6import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
7import { bakeChunkAtlases } from "./chunkBake.js";
8import {
9 frameworkImageFromCanvas,
10 invalidateCanvasTexture
11} from "./canvasSprite.js";
12import { applyNearestToAllTextures, setNearestFilter } from "./sprites.js";
13
14const LAYER_GROUND = 0;
15const LAYER_EDGE = 900000;
16const SORT_BLOCK = 2;
17const SORT_ENTITY = 3;
18const SORT_HP_BAR = 4;
19const SORT_FX = 5;
20const RENDER_LAYER_BLOOM = "bloom";
21
22const HP_BAR_W = 14;
23const HP_BAR_H = 4;
24const WALK_TILT_DEG = 6;
25const RUN_TILT_DEG = 8;
26const SHOVE_TILE_FRACTION = 0.25;
27const SHOVE_MS = 280;
28const DAMAGE_FLASH_MS = 180;
29const DAMAGE_FLOAT_MS = 900;
30
31const SPRITE_LIGHTING_FRAG = [
32 "precision mediump float;",
33 "varying vec2 v_texCoord;",
34 "uniform sampler2D u_texture;",
35 "uniform float u_darkness;",
36 "uniform float u_strength;",
37 "void main() {",
38 " vec4 color = texture2D(u_texture, v_texCoord);",
39 " if (color.a <= 0.0) { discard; }",
40 " vec3 rgb = mix(color.rgb, vec3(0.0), u_darkness);",
41 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
42 " gl_FragColor = vec4(rgb, color.a);",
43 "}"
44].join("\n");
45
46const ATLAS_LIGHTING_FRAG = [
47 "precision mediump float;",
48 "varying vec2 v_texCoord;",
49 "uniform sampler2D u_texture;",
50 "uniform sampler2D u_secondary;",
51 "uniform float u_ambientDark;",
52 "uniform float u_lightRow;",
53 "void main() {",
54 " vec4 color = texture2D(u_texture, v_texCoord);",
55 " if (color.a <= 0.0) { discard; }",
56 " vec2 lightUV = v_texCoord;",
57 " if (u_lightRow >= 0.0) {",
58 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
59 " }",
60 " float lit = texture2D(u_secondary, lightUV).r;",
61 " float darkness = u_ambientDark * (1.0 - lit);",
62 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
63 " gl_FragColor = vec4(rgb, color.a);",
64 "}"
65].join("\n");
66
67let spriteLightingShader = null;
68let atlasLightingShader = null;
69
70function getSpriteLightingShader ()
71{
72 if (!spriteLightingShader)
73 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
74 return spriteLightingShader;
75}
76
77function getAtlasLightingShader ()
78{
79 if (!atlasLightingShader)
80 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
81 return atlasLightingShader;
82}
83
84export class WorldView
85{
86 constructor (game, scene, catalog = { grounds: {}, blocks: {} })
87 {
88 this.game = game;
89 this.scene = scene;
90 this.catalog = catalog;
91 this.preview = null;
92 this.zoom = 2;
93 this.chunks = new Map();
94 this.bakedChunks = new Map();
95 this.tiles = new Map();
96 this.entities = new Map();
97 this.groundItems = new Map();
98 this.edges = new Map();
99 this.localEntityId = null;
100 this.settings = { ...DEFAULT_WORLD_SETTINGS };
101 this.worldHour = 12;
102 this.nightPreview = null;
103 this.followPlayer = true;
104 this.dynamicLights = [];
105 this.swipes = [];
106 this.damageFloats = [];
107 this.damageNumbersEl = document.getElementById("damage-numbers");
108 this.#syncBloomLayer();
109 }
110
111 setSettings (settings)
112 {
113 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
114 this.#syncBloomLayer();
115 }
116
117 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null)
118 {
119 this.localEntityId = entityId;
120 this.#upsertEntity({
121 entityId,
122 characterId,
123 tileX,
124 tileY,
125 gait,
126 sex,
127 firstName,
128 lastName,
129 layers: layers ?? undefined
130 });
131 }
132
133 applySnapshot (snapshot)
134 {
135 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
136 this.chunks.set(key, snapshot);
137 this.#rebuildChunk(snapshot);
138 this.#redrawPreview();
139 for (const entity of snapshot.entities ?? [])
140 { this.#upsertEntity(entity); }
141 const chunkPrefix = `${snapshot.chunkX},${snapshot.chunkY}`;
142 for (const [id, item] of [...this.groundItems.entries()])
143 {
144 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
145 { this.despawnGroundItem(id); }
146 }
147 for (const item of snapshot.groundItems ?? [])
148 { this.upsertGroundItem(item); }
149 this.#rebuildAllEdges();
150 }
151
152 removeChunk (chunkX, chunkY)
153 {
154 const key = `${chunkX},${chunkY}`;
155 this.chunks.delete(key);
156 this.#destroyBakedChunk(key);
157 this.#destroyEdges(key);
158 for (const [tileKey, objects] of [...this.tiles.entries()])
159 {
160 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
161 {
162 objects.ground?.destroy();
163 objects.groundBloom?.destroy();
164 objects.block?.destroy();
165 objects.blockBloom?.destroy();
166 this.tiles.delete(tileKey);
167 }
168 }
169 for (const [id, item] of [...this.groundItems.entries()])
170 {
171 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
172 { this.despawnGroundItem(id); }
173 }
174 this.#rebuildAllEdges();
175 }
176
177 setChunkOpen (chunkX, chunkY, open)
178 {
179 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
180 if (!snapshot)
181 { return; }
182 snapshot.open = !!open;
183 this.#rebuildAllEdges();
184 }
185
186 spawnEntity (payload)
187 {
188 this.#upsertEntity(payload);
189 }
190
191 moveEntity (payload)
192 {
193 const existing = this.entities.get(payload.entityId);
194 if (!existing)
195 {
196 this.#upsertEntity(payload);
197 return;
198 }
199 const size = this.tileSize();
200 existing.fromX = existing.visualX;
201 existing.fromY = existing.visualY;
202 existing.shadeFromTileX = existing.tileX;
203 existing.shadeFromTileY = existing.tileY;
204 existing.tileX = payload.tileX;
205 existing.tileY = payload.tileY;
206 existing.gait = payload.gait;
207 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
208 if (payload.worldX != null && payload.worldY != null)
209 {
210 existing.worldX = payload.worldX;
211 existing.worldY = payload.worldY;
212 existing.targetX = payload.worldX * size;
213 existing.targetY = payload.worldY * size;
214 }
215 else
216 {
217 const pivot = tilePivot(payload.tileX, payload.tileY, size);
218 existing.targetX = pivot.x;
219 existing.targetY = pivot.y;
220 }
221 existing.lerpStarted = performance.now();
222 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
223 }
224
225 despawnEntity (entityId)
226 {
227 const existing = this.entities.get(entityId);
228 if (!existing)
229 { return; }
230 existing.object?.destroy();
231 existing.hpBar?.destroy();
232 for (const overlay of existing.overlays ?? [])
233 { overlay.destroy(); }
234 for (const overlay of existing.bloomOverlays ?? [])
235 { overlay.destroy(); }
236 this.entities.delete(entityId);
237 }
238
239 updateEntityHealth (entityId, health, maxHealth)
240 {
241 const entity = this.entities.get(entityId);
242 if (!entity)
243 { return; }
244 entity.health = health;
245 entity.maxHealth = maxHealth;
246 this.#syncHpBar(entity);
247 }
248
249 flashDamage (entityId)
250 {
251 const entity = this.entities.get(entityId);
252 if (!entity)
253 { return; }
254 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
255 }
256
257 spawnDamageNumber (entityId, damage)
258 {
259 const amount = damage | 0;
260 if (amount <= 0)
261 { return; }
262 this.damageFloats.push({
263 entityId,
264 damage: amount,
265 started: performance.now()
266 });
267 }
268
269 setAppearance (payload)
270 {
271 const existing = this.entities.get(payload.entityId);
272 if (!existing)
273 { return; }
274 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
275 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
276 this.#placeEntity(existing);
277 }
278
279 upsertGroundItem (payload)
280 {
281 const size = this.tileSize();
282 const pivot = tilePivot(payload.tileX, payload.tileY, size);
283 let item = this.groundItems.get(payload.groundItemId);
284 if (!item)
285 {
286 const object = new GameObject(0, 0, this.game.images[payload.sprite] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
287 this.scene.addObject(object);
288 item = { object };
289 this.groundItems.set(payload.groundItemId, item);
290 }
291 item.groundItemId = payload.groundItemId;
292 item.tileX = payload.tileX;
293 item.tileY = payload.tileY;
294 item.itemId = payload.itemId;
295 item.quantity = payload.quantity;
296 item.displayName = payload.displayName;
297 item.sprite = payload.sprite;
298 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
299 this.#syncLitSprite(item.object, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
300 }
301
302 despawnGroundItem (groundItemId)
303 {
304 const item = this.groundItems.get(groundItemId);
305 if (!item)
306 { return; }
307 item.object?.destroy();
308 this.groundItems.delete(groundItemId);
309 }
310
311 groundItemAtTile (tileX, tileY)
312 {
313 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
314 }
315
316 groundItemsAtTile (tileX, tileY)
317 {
318 const items = [];
319 for (const item of this.groundItems.values())
320 {
321 if (item.tileX === tileX && item.tileY === tileY)
322 { items.push(item); }
323 }
324 return items;
325 }
326
327 entitiesAtTile (tileX, tileY)
328 {
329 const matches = [];
330 for (const entity of this.entities.values())
331 {
332 if (entity.tileX === tileX && entity.tileY === tileY)
333 { matches.push(entity); }
334 }
335 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
336 return matches;
337 }
338
339 setZoom (zoom, limits = { min: 1, max: 4 })
340 {
341 const min = limits.min ?? 1;
342 const max = limits.max ?? 4;
343 this.zoom = Math.min(max, Math.max(min, zoom));
344 for (const snapshot of this.chunks.values())
345 {
346 this.#layoutBakedChunk(snapshot);
347 this.#rebuildChunk(snapshot);
348 }
349 const size = this.tileSize();
350 for (const entity of this.entities.values())
351 {
352 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
353 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
354 entity.fromX = entity.visualX;
355 entity.fromY = entity.visualY;
356 entity.targetX = entity.visualX;
357 entity.targetY = entity.visualY;
358 entity.lerpStarted = null;
359 this.#placeEntity(entity);
360 }
361 for (const item of this.groundItems.values())
362 {
363 const pivot = tilePivot(item.tileX, item.tileY, size);
364 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
365 }
366 this.#rebuildAllEdges();
367 this.#redrawPreview();
368 applyNearestToAllTextures(this.scene, this.game.images);
369 }
370
371 tileSize ()
372 {
373 return SPRITE_SIZE_PX * this.zoom;
374 }
375
376 screenToTile (mouseX, mouseY)
377 {
378 const size = this.tileSize();
379 const worldX = mouseX - this.scene.cameraPosition.x;
380 const worldY = mouseY - this.scene.cameraPosition.y;
381 return {
382 tileX: Math.floor(worldX / size),
383 tileY: Math.floor(worldY / size)
384 };
385 }
386
387 entityAtScreen (mouseX, mouseY)
388 {
389 let best = null;
390 let bestLayer = -Infinity;
391 for (const entity of this.entities.values())
392 {
393 const box = this.#entityScreenBox(entity);
394 if (!box)
395 { continue; }
396 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
397 {
398 const layer = entity.object?.layer ?? 0;
399 if (layer >= bestLayer)
400 {
401 best = entity;
402 bestLayer = layer;
403 }
404 }
405 }
406 return best;
407 }
408
409 nametagAnchor (entity)
410 {
411 const box = this.#entityScreenBox(entity);
412 if (!box)
413 { return null; }
414 return { x: (box.left + box.right) / 2, y: box.top };
415 }
416
417 #entityScreenBox (entity)
418 {
419 const object = entity?.object;
420 if (!object)
421 { return null; }
422 const size = object.transform.size;
423 const x = object.transform.position.x + this.scene.cameraPosition.x;
424 const y = object.transform.position.y + this.scene.cameraPosition.y;
425 return {
426 left: x - size.x / 2,
427 right: x + size.x / 2,
428 top: y - size.y / 2,
429 bottom: y + size.y / 2
430 };
431 }
432
433 update (deltaTime)
434 {
435 const now = performance.now();
436 const size = this.tileSize();
437 for (const entity of this.entities.values())
438 {
439 const target = entity.targetX != null && entity.targetY != null
440 ? { x: entity.targetX, y: entity.targetY }
441 : tilePivot(entity.tileX, entity.tileY, size);
442 if (entity.lerpStarted != null)
443 {
444 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
445 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
446 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
447 if (t >= 1)
448 { entity.lerpStarted = null; }
449 }
450 else
451 {
452 entity.visualX = target.x;
453 entity.visualY = target.y;
454 }
455 this.#updateShove(entity, now, size);
456 this.#placeEntity(entity, now);
457 }
458
459 this.#updateSwipes(now);
460 this.#updateDamageNumbers(now);
461 this.#centerCamera();
462 this.#updateShade(deltaTime);
463 }
464
465 #updateShove (entity, now, tileSize)
466 {
467 if (!entity.shove)
468 {
469 entity.shoveOffsetX = 0;
470 entity.shoveOffsetY = 0;
471 return;
472 }
473 const elapsed = now - entity.shove.started;
474 const t = Math.min(1, elapsed / entity.shove.durationMs);
475 const maxDist = tileSize * SHOVE_TILE_FRACTION;
476 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
477 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
478 const dist = Math.hypot(dx, dy) || 1;
479 const ux = dx / dist;
480 const uy = dy / dist;
481 let phase;
482 if (t < 0.45)
483 { phase = t / 0.45; }
484 else
485 { phase = 1 - (t - 0.45) / 0.55; }
486 entity.shoveOffsetX = ux * maxDist * phase;
487 entity.shoveOffsetY = uy * maxDist * phase;
488 if (t >= 1)
489 { entity.shove = null; }
490 }
491
492 spawnCombatSwing (payload)
493 {
494 const attacker = this.entities.get(payload.attackerId);
495 const target = this.entities.get(payload.targetId);
496 if (!attacker || !target)
497 { return; }
498 attacker.shove = {
499 startVisualX: attacker.visualX,
500 startVisualY: attacker.visualY,
501 targetVisualX: target.visualX,
502 targetVisualY: target.visualY,
503 started: performance.now(),
504 durationMs: SHOVE_MS
505 };
506 const midX = (attacker.visualX + target.visualX) / 2;
507 const midY = (attacker.visualY + target.visualY) / 2;
508 const sortY = Math.max(attacker.visualY, target.visualY) + 0.02;
509 const angle = Math.atan2(target.visualY - attacker.visualY, target.visualX - attacker.visualX) * (180 / Math.PI);
510 const spriteName = "fx:melee-swipe:melee-swipe";
511 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
512 if (object.transform)
513 { object.transform.rotation = angle; }
514 this.scene.addObject(object);
515 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
516 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
517 this.swipes.push({
518 object,
519 until: performance.now() + 500,
520 fromTileX: payload.fromTileX,
521 fromTileY: payload.fromTileY,
522 tileX: payload.tileX,
523 tileY: payload.tileY
524 });
525 }
526
527 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
528 spawnPhysicalProjectileFx (payload)
529 {
530 const spriteName = payload.sprite ?? "fx:projectile:projectile";
531 const image = this.game.images[spriteName];
532 if (!image)
533 { return; }
534 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
535 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
536 const midX = (fromPivot.x + toPivot.x) / 2;
537 const midY = (fromPivot.y + toPivot.y) / 2;
538 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
539 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
540 const object = new GameObject(0, 0, image, SORT_FX);
541 if (object.transform)
542 { object.transform.rotation = angle; }
543 this.scene.addObject(object);
544 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
545 this.#applyPhysicalCombatFxDarkness(
546 object,
547 payload.fromTileX,
548 payload.fromTileY,
549 payload.tileX,
550 payload.tileY
551 );
552 this.swipes.push({
553 object,
554 until: performance.now() + (payload.durationMs ?? 500),
555 fromTileX: payload.fromTileX,
556 fromTileY: payload.fromTileY,
557 tileX: payload.tileX,
558 tileY: payload.tileY
559 });
560 }
561
562 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
563 {
564 this.dynamicLights.push({
565 tileX: Math.floor(worldX),
566 tileY: Math.floor(worldY),
567 range: radiusTiles,
568 intensity,
569 until: performance.now() + durationMs
570 });
571 }
572
573 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
574 {
575 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
576 if (!snapshot)
577 { return; }
578 const index = localY * CHUNK_SIZE + localX;
579 if (ground !== undefined)
580 { snapshot.grounds[index] = ground; }
581 if (block !== undefined)
582 { snapshot.blocks[index] = block; }
583 if (light !== undefined)
584 { snapshot.light[index] = light; }
585 this.#rebuildChunk(snapshot);
586 }
587
588 setTilePreview (tileX, tileY, override)
589 {
590 const previous = this.preview;
591 this.preview = { tileX, tileY, ...override };
592 const chunkX = Math.floor(tileX / CHUNK_SIZE);
593 const chunkY = Math.floor(tileY / CHUNK_SIZE);
594 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
595 if (snapshot)
596 { this.#rebuildChunk(snapshot); }
597 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
598 {
599 const prevSnapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
600 if (prevSnapshot && prevSnapshot !== snapshot)
601 { this.#rebuildChunk(prevSnapshot); }
602 }
603 }
604
605 clearTilePreview ()
606 {
607 const previous = this.preview;
608 this.preview = null;
609 if (previous)
610 {
611 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
612 if (snapshot)
613 { this.#rebuildChunk(snapshot); }
614 }
615 }
616
617 #lerpMs (gait)
618 {
619 const walk = this.settings.walkTilesPerSecond || 2;
620 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
621 return seconds * 1000;
622 }
623
624 #centerCamera ()
625 {
626 if (!this.followPlayer)
627 { return; }
628 const local = this.entities.get(this.localEntityId);
629 if (!local)
630 { return; }
631 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - local.visualX;
632 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - local.visualY;
633 }
634
635 #upsertEntity (payload)
636 {
637 const size = this.tileSize();
638 const pivot = tilePivot(payload.tileX, payload.tileY, size);
639 let entity = this.entities.get(payload.entityId);
640 if (!entity)
641 {
642 const spriteName = payload.layers?.[0]?.sprite
643 ?? payload.sprite
644 ?? bodySpriteName(payload.sex);
645 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
646 this.scene.addObject(object);
647 this.#startIdleAnimation(object);
648 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
649 this.entities.set(payload.entityId, entity);
650 }
651 entity.entityId = payload.entityId;
652 entity.tileX = payload.tileX;
653 entity.tileY = payload.tileY;
654 entity.gait = payload.gait;
655 entity.sex = payload.sex ?? entity.sex;
656 entity.characterId = payload.characterId ?? entity.characterId ?? null;
657 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
658 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
659 entity.canFight = payload.canFight != null
660 ? !!payload.canFight
661 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
662 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
663 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
664 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
665 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
666 if (payload.health != null)
667 { entity.health = payload.health; }
668 if (payload.maxHealth != null)
669 { entity.maxHealth = payload.maxHealth; }
670 if (payload.firstName)
671 { entity.firstName = payload.firstName; }
672 if (payload.lastName)
673 { entity.lastName = payload.lastName; }
674 entity.firstName = entity.firstName ?? "";
675 entity.lastName = entity.lastName ?? "";
676 if (payload.worldX != null && payload.worldY != null)
677 {
678 entity.worldX = payload.worldX;
679 entity.worldY = payload.worldY;
680 entity.visualX = payload.worldX * size;
681 entity.visualY = payload.worldY * size;
682 entity.targetX = entity.visualX;
683 entity.targetY = entity.visualY;
684 }
685 else
686 {
687 entity.visualX = pivot.x;
688 entity.visualY = pivot.y;
689 entity.targetX = pivot.x;
690 entity.targetY = pivot.y;
691 }
692 entity.fromX = entity.visualX;
693 entity.fromY = entity.visualY;
694 if (payload.layers)
695 { this.#applyLayers(entity, payload.layers); }
696 this.#syncHpBar(entity);
697 this.#placeEntity(entity, performance.now());
698 }
699
700 #applyLayers (entity, layers)
701 {
702 const base = layers[0]?.sprite
703 ?? bodySpriteName(entity.sex);
704 if (this.game.images[base])
705 {
706 entity.object.renderer.sprite = this.game.images[base];
707 this.#startIdleAnimation(entity.object);
708 }
709 for (const overlay of entity.overlays ?? [])
710 { overlay.destroy(); }
711 for (const overlay of entity.bloomOverlays ?? [])
712 { overlay.destroy(); }
713 entity.overlays = [];
714 entity.bloomOverlays = [];
715 for (const layer of layers.slice(1))
716 {
717 const image = this.game.images[layer.sprite];
718 if (!image)
719 { continue; }
720 const object = new GameObject(0, 0, image, SORT_ENTITY);
721 this.scene.addObject(object);
722 entity.overlays.push(object);
723 const bloomName = bloomCompanionName(layer.sprite);
724 const bloomImage = this.game.images[bloomName];
725 if (!bloomImage)
726 { continue; }
727 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
728 bloom.renderer.layer = RENDER_LAYER_BLOOM;
729 this.#markUnlit(bloom);
730 this.scene.addObject(bloom);
731 entity.bloomOverlays.push(bloom);
732 }
733 }
734
735 #placeEntity (entity, now = performance.now())
736 {
737 const zoom = this.zoom;
738 const offsetX = entity.shoveOffsetX ?? 0;
739 const offsetY = entity.shoveOffsetY ?? 0;
740 const pivotX = entity.visualX + offsetX;
741 const pivotY = entity.visualY + offsetY;
742 let walkTilt = 0;
743 if (entity.lerpStarted != null)
744 {
745 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
746 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
747 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
748 walkTilt = Math.sin(cycles) * tilt;
749 }
750 const flashStrength = (entity.damageFlashUntil ?? 0) > now
751 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
752 : 0;
753 const tileShade = this.#entityShadeAlpha(entity, now);
754
755 entity.object.transform.rotation = walkTilt;
756 this.#syncLitSprite(entity.object, tileShade, flashStrength);
757 this.#placePivoted(entity.object, pivotX, pivotY, entity.visualY, SORT_ENTITY);
758 for (let index = 0; index < (entity.overlays ?? []).length; index++)
759 {
760 const overlay = entity.overlays[index];
761 const overlaySortY = entity.visualY + 0.5 * (index + 1);
762 overlay.transform.rotation = walkTilt;
763 this.#syncLitSprite(overlay, tileShade, flashStrength);
764 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY);
765 }
766 for (const overlay of entity.bloomOverlays ?? [])
767 {
768 overlay.transform.rotation = walkTilt;
769 this.#placePivoted(overlay, pivotX, pivotY, entity.visualY + 0.002, SORT_ENTITY);
770 }
771 this.#placeHpBar(entity, pivotX, pivotY);
772 }
773
774 #markUnlit (object)
775 {
776 if (!object?.renderer)
777 { return; }
778 object._lit = false;
779 object.renderer.shader = null;
780 object.renderer.shaderUniforms = null;
781 object.renderer.secondaryMap = null;
782 }
783
784 #syncLitSprite (object, darkness, flashStrength = 0)
785 {
786 if (!object?.renderer || object._lit === false)
787 { return; }
788 object._lit = true;
789 const dark = Math.min(1, Math.max(0, darkness ?? 0));
790 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
791 object.renderer.shader = getSpriteLightingShader();
792 object.renderer.shaderUniforms = { u_darkness: dark, u_strength: flash };
793 object.renderer.secondaryMap = null;
794 }
795
796 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY)
797 {
798 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
799 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
800 this.#syncLitSprite(object, (fromAlpha + toAlpha) / 2);
801 }
802
803 #syncHpBar (entity)
804 {
805 const current = entity.health;
806 const max = entity.maxHealth;
807 const show = entity.mobTypeId != null
808 && current != null
809 && max != null
810 && max > 0
811 && current < max;
812 if (!show)
813 {
814 entity.hpBar?.destroy();
815 entity.hpBar = null;
816 entity.hpBarCanvas = null;
817 return;
818 }
819 if (!entity.hpBarCanvas)
820 {
821 entity.hpBarCanvas = document.createElement("canvas");
822 entity.hpBarCanvas.width = HP_BAR_W;
823 entity.hpBarCanvas.height = HP_BAR_H;
824 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
825 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
826 this.#markUnlit(entity.hpBar);
827 this.scene.addObject(entity.hpBar);
828 }
829 drawHpBar(entity.hpBarCanvas, current, max);
830 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
831 }
832
833 #placeHpBar (entity, pivotX, pivotY)
834 {
835 if (!entity.hpBar)
836 { return; }
837 const sprite = entity.object?.renderer?.sprite;
838 if (!sprite)
839 { return; }
840 const zoom = this.zoom;
841 const drawH = sprite.height * zoom;
842 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
843 const spriteTop = centerY - drawH / 2;
844 const barW = HP_BAR_W * zoom;
845 const barH = HP_BAR_H * zoom;
846 entity.hpBar.transform.position.x = pivotX;
847 entity.hpBar.transform.position.y = spriteTop - barH / 2;
848 entity.hpBar.transform.size = new vector(barW, barH);
849 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
850 this.#markSortDirty();
851 }
852
853 #rebuildChunk (snapshot)
854 {
855 this.#bakeAndPlaceChunk(snapshot);
856 const tall = new Set(
857 (this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`)?.tallBlocks ?? [])
858 .map((entry) => `${entry.tileX},${entry.tileY}`)
859 );
860 for (let localY = 0; localY < CHUNK_SIZE; localY++)
861 {
862 for (let localX = 0; localX < CHUNK_SIZE; localX++)
863 {
864 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
865 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
866 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
867 }
868 }
869 }
870
871 #bakeAndPlaceChunk (snapshot)
872 {
873 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
874 const atlases = bakeChunkAtlases({
875 snapshot,
876 catalog: this.catalog,
877 images: this.game.images,
878 preview: this.preview
879 });
880 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
881 let baked = this.bakedChunks.get(key);
882 if (!baked)
883 {
884 const lightmapCanvas = makeLightmapCanvas(atlasPx);
885 baked = {
886 groundCanvas: atlases.ground,
887 blockCanvases: atlases.blockRows,
888 bloomCanvas: atlases.bloom,
889 lightmapCanvas,
890 groundImage: frameworkImageFromCanvas(atlases.ground),
891 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
892 bloomImage: frameworkImageFromCanvas(atlases.bloom),
893 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
894 groundObject: null,
895 blockObjects: [],
896 bloomObject: null,
897 tallBlocks: atlases.tallBlocks,
898 lightmapPixels: null
899 };
900 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
901 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
902 this.scene.addObject(baked.groundObject);
903 for (let row = 0; row < CHUNK_SIZE; row++)
904 {
905 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
906 this.#applyAtlasLighting(object, baked.lightmapImage, row);
907 this.scene.addObject(object);
908 baked.blockObjects.push(object);
909 }
910 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
911 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
912 this.#markUnlit(baked.bloomObject);
913 this.scene.addObject(baked.bloomObject);
914 this.bakedChunks.set(key, baked);
915 }
916 else
917 {
918 copyCanvas(atlases.ground, baked.groundCanvas);
919 for (let row = 0; row < CHUNK_SIZE; row++)
920 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
921 copyCanvas(atlases.bloom, baked.bloomCanvas);
922 invalidateCanvasTexture(this.scene, baked.groundCanvas);
923 for (const canvas of baked.blockCanvases)
924 { invalidateCanvasTexture(this.scene, canvas); }
925 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
926 baked.tallBlocks = atlases.tallBlocks;
927 }
928 baked.chunkX = snapshot.chunkX;
929 baked.chunkY = snapshot.chunkY;
930 this.#layoutBakedChunk(snapshot);
931 }
932
933 #applyAtlasLighting (object, lightmapImage, lightRow)
934 {
935 if (!object?.renderer)
936 { return; }
937 object._lit = true;
938 object.renderer.shader = getAtlasLightingShader();
939 object.renderer.secondaryMap = lightmapImage;
940 object.renderer.shaderUniforms = {
941 u_ambientDark: 0,
942 u_lightRow: lightRow
943 };
944 }
945
946 #layoutBakedChunk (snapshot)
947 {
948 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
949 const baked = this.bakedChunks.get(key);
950 if (!baked)
951 { return; }
952 const size = this.tileSize();
953 const left = snapshot.chunkX * CHUNK_SIZE * size;
954 const top = snapshot.chunkY * CHUNK_SIZE * size;
955 const chunkPx = CHUNK_SIZE * size;
956 baked.groundObject.transform.position.x = left + chunkPx / 2;
957 baked.groundObject.transform.position.y = top + chunkPx / 2;
958 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
959 baked.groundObject.layer = LAYER_GROUND;
960
961 for (let row = 0; row < CHUNK_SIZE; row++)
962 {
963 const object = baked.blockObjects[row];
964 const rowY = top + row * size + size / 2;
965 object.transform.position.x = left + chunkPx / 2;
966 object.transform.position.y = rowY;
967 object.transform.size = new vector(chunkPx, size);
968 object.layer = ySortLayer(rowY, SORT_BLOCK);
969 }
970
971 baked.bloomObject.transform.position.x = left + chunkPx / 2;
972 baked.bloomObject.transform.position.y = top + chunkPx / 2;
973 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
974 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
975 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
976 this.#markSortDirty();
977 setNearestFilter(this.scene, baked.groundCanvas);
978 for (const canvas of baked.blockCanvases)
979 { setNearestFilter(this.scene, canvas); }
980 setNearestFilter(this.scene, baked.bloomCanvas);
981 setNearestFilter(this.scene, baked.lightmapCanvas);
982 }
983
984 #destroyBakedChunk (key)
985 {
986 const baked = this.bakedChunks.get(key);
987 if (!baked)
988 { return; }
989 baked.groundObject?.destroy();
990 for (const object of baked.blockObjects ?? [])
991 { object.destroy(); }
992 baked.bloomObject?.destroy();
993 invalidateCanvasTexture(this.scene, baked.groundCanvas);
994 for (const canvas of baked.blockCanvases ?? [])
995 { invalidateCanvasTexture(this.scene, canvas); }
996 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
997 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
998 this.bakedChunks.delete(key);
999 }
1000
1001 #redrawPreview ()
1002 {
1003 if (!this.preview)
1004 { return; }
1005 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
1006 if (snapshot)
1007 { this.#rebuildChunk(snapshot); }
1008 }
1009
1010 #drawTile (tileX, tileY, forceTall = null)
1011 {
1012 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1013 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1014 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1015 if (!snapshot)
1016 { return; }
1017 const localX = tileX - chunkX * CHUNK_SIZE;
1018 const localY = tileY - chunkY * CHUNK_SIZE;
1019 const index = localY * CHUNK_SIZE + localX;
1020 const key = `${tileX},${tileY}`;
1021 let objects = this.tiles.get(key);
1022 if (!objects)
1023 {
1024 objects = { chunkX, chunkY, tileX, tileY };
1025 this.tiles.set(key, objects);
1026 }
1027 objects.tileX = tileX;
1028 objects.tileY = tileY;
1029 objects.chunkX = chunkX;
1030 objects.chunkY = chunkY;
1031 objects.light = snapshot.light[index] ?? 0;
1032
1033 if (objects.ground)
1034 {
1035 objects.ground.destroy();
1036 objects.ground = null;
1037 }
1038 if (objects.groundBloom)
1039 {
1040 objects.groundBloom.destroy();
1041 objects.groundBloom = null;
1042 }
1043
1044 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
1045 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
1046 const isTall = forceTall === true || !!tallEntry;
1047 if (isTall && tallEntry)
1048 {
1049 const pivot = tilePivot(tileX, tileY, this.tileSize());
1050 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
1051 if (objects.block)
1052 {
1053 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
1054 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
1055 }
1056 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
1057 }
1058 else
1059 {
1060 objects.block?.destroy();
1061 objects.block = null;
1062 objects.blockBloom?.destroy();
1063 objects.blockBloom = null;
1064 }
1065 }
1066
1067 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
1068 {
1069 if (!name)
1070 {
1071 existing?.destroy();
1072 return null;
1073 }
1074 const object = this.#ensureSprite(existing, name, sortOrder);
1075 if (!object)
1076 { return null; }
1077 object.renderer.layer = RENDER_LAYER_BLOOM;
1078 this.#markUnlit(object);
1079 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
1080 return object;
1081 }
1082
1083 #placePivoted (object, pivotX, pivotY, sortY, subOrder)
1084 {
1085 const sprite = object?.renderer?.sprite;
1086 if (!sprite)
1087 { return; }
1088 const zoom = this.zoom;
1089 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
1090 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height, zoom);
1091 object.transform.position.x = center.x;
1092 object.transform.position.y = center.y;
1093 object.transform.size = new vector(draw.w, draw.h);
1094 object.layer = ySortLayer(sortY, subOrder);
1095 this.#markSortDirty();
1096 }
1097
1098 #ensureSprite (existing, name, layer)
1099 {
1100 const sprite = this.game.images[name];
1101 if (!sprite)
1102 {
1103 existing?.destroy();
1104 return null;
1105 }
1106 if (!existing || existing.renderer.sprite !== sprite)
1107 {
1108 existing?.destroy();
1109 existing = new GameObject(0, 0, sprite, layer);
1110 this.#syncLitSprite(existing, 0);
1111 this.scene.addObject(existing);
1112 this.#startIdleAnimation(existing);
1113 }
1114 return existing;
1115 }
1116
1117 #startIdleAnimation (object)
1118 {
1119 const sprite = object?.renderer?.sprite;
1120 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
1121 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
1122 }
1123
1124 #neighborClosed (snapshot, dir, dx, dy)
1125 {
1126 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
1127 if (other)
1128 { return !other.open; }
1129 return !!snapshot.closedEdges?.[dir];
1130 }
1131
1132 #rebuildAllEdges ()
1133 {
1134 const seen = new Set();
1135 for (const snapshot of this.chunks.values())
1136 {
1137 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1138 seen.add(key);
1139 this.#rebuildChunkEdges(snapshot);
1140 }
1141 for (const key of [...this.edges.keys()])
1142 {
1143 if (!seen.has(key))
1144 { this.#destroyEdges(key); }
1145 }
1146 }
1147
1148 #rebuildChunkEdges (snapshot)
1149 {
1150 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
1151 let bars = this.edges.get(key);
1152 if (!bars)
1153 {
1154 bars = {};
1155 this.edges.set(key, bars);
1156 }
1157
1158 const size = this.tileSize();
1159 const chunkPx = CHUNK_SIZE * size;
1160 const left = snapshot.chunkX * CHUNK_SIZE * size;
1161 const top = snapshot.chunkY * CHUNK_SIZE * size;
1162 const centerX = left + chunkPx / 2;
1163 const centerY = top + chunkPx / 2;
1164 const thickness = Math.max(2, Math.round(2 * this.zoom));
1165 const draw = snapshot.open === true;
1166
1167 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
1168 centerX, top, chunkPx, thickness, true);
1169 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
1170 centerX, top + chunkPx, chunkPx, thickness, true);
1171 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
1172 left, centerY, chunkPx, thickness, false);
1173 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
1174 left + chunkPx, centerY, chunkPx, thickness, false);
1175 }
1176
1177 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
1178 {
1179 if (!visible)
1180 {
1181 if (existing)
1182 { existing.renderer.visible = false; }
1183 return existing;
1184 }
1185
1186 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
1187 this.#markUnlit(existing);
1188 existing.renderer.visible = true;
1189 existing.transform.position.x = x;
1190 existing.transform.position.y = y;
1191 existing.transform.size = horizontal
1192 ? new vector(length, thickness)
1193 : new vector(thickness, length);
1194 existing.layer = LAYER_EDGE;
1195 this.#markSortDirty();
1196 return existing;
1197 }
1198
1199 #destroyEdges (key)
1200 {
1201 const bars = this.edges.get(key);
1202 if (!bars)
1203 { return; }
1204 bars.north?.destroy();
1205 bars.east?.destroy();
1206 bars.south?.destroy();
1207 bars.west?.destroy();
1208 this.edges.delete(key);
1209 }
1210
1211 #entityShadeAlpha (entity, now)
1212 {
1213 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
1214 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
1215 { return toAlpha; }
1216 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
1217 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
1218 return fromAlpha + (toAlpha - fromAlpha) * t;
1219 }
1220
1221 #markSortDirty ()
1222 {
1223 this.scene._sortDirty = true;
1224 }
1225
1226 #updateShade ()
1227 {
1228 const hour = this.nightPreview ?? this.worldHour;
1229 const ambientDark = nightFactor(hour, this.settings.nightDarkness);
1230 const now = performance.now();
1231 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
1232
1233 const activeLights = [...this.dynamicLights];
1234 const tileSize = this.tileSize();
1235 for (const entity of this.entities.values())
1236 {
1237 const range = entity.lightRadiusTiles ?? 0;
1238 if (range <= 0)
1239 { continue; }
1240 activeLights.push({
1241 tileX: Math.floor(entity.visualX / tileSize),
1242 tileY: Math.floor(entity.visualY / tileSize),
1243 range,
1244 intensity: 1
1245 });
1246 }
1247
1248 const isPassable = makeSnapshotPassable(this.chunks);
1249
1250 for (const objects of this.tiles.values())
1251 {
1252 const intensity = this.#tileLightIntensity(objects, activeLights, isPassable);
1253 objects.shadeAlpha = ambientDark * (1 - intensity);
1254 if (objects.block)
1255 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
1256 }
1257
1258 for (const baked of this.bakedChunks.values())
1259 {
1260 this.#writeChunkLightmap(baked, activeLights, isPassable);
1261 if (baked.groundObject?.renderer?.shaderUniforms)
1262 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1263 for (const object of baked.blockObjects ?? [])
1264 {
1265 if (object?.renderer?.shaderUniforms)
1266 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
1267 }
1268 }
1269
1270 for (const item of this.groundItems.values())
1271 {
1272 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
1273 this.#syncLitSprite(item.object, alpha);
1274 }
1275 }
1276
1277 #tileLightIntensity (objects, activeLights, isPassable)
1278 {
1279 const baked = lightIntensity(objects.light ?? 0);
1280 const dynamic = dynamicLightAtTile(
1281 objects.tileX,
1282 objects.tileY,
1283 activeLights,
1284 isPassable
1285 );
1286 return Math.max(baked, dynamic);
1287 }
1288
1289 #writeChunkLightmap (baked, activeLights, isPassable)
1290 {
1291 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
1292 if (!snapshot)
1293 { return; }
1294 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
1295 const pixelCount = atlasPx * atlasPx * 4;
1296 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
1297 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
1298 const pixels = baked.lightmapPixels;
1299 for (let localY = 0; localY < CHUNK_SIZE; localY++)
1300 {
1301 for (let localX = 0; localX < CHUNK_SIZE; localX++)
1302 {
1303 const tileX = baked.chunkX * CHUNK_SIZE + localX;
1304 const tileY = baked.chunkY * CHUNK_SIZE + localY;
1305 const index = localY * CHUNK_SIZE + localX;
1306 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
1307 let intensity;
1308 if (tileObjects)
1309 {
1310 intensity = this.#tileLightIntensity(tileObjects, activeLights, isPassable);
1311 }
1312 else
1313 {
1314 const baked = lightIntensity(snapshot.light[index] ?? 0);
1315 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, isPassable);
1316 intensity = Math.max(baked, dynamic);
1317 }
1318 const value = Math.round(Math.min(1, intensity) * 255);
1319 const baseX = localX * SPRITE_SIZE_PX;
1320 const baseY = localY * SPRITE_SIZE_PX;
1321 for (let py = 0; py < SPRITE_SIZE_PX; py++)
1322 {
1323 for (let px = 0; px < SPRITE_SIZE_PX; px++)
1324 {
1325 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
1326 pixels[offset] = value;
1327 pixels[offset + 1] = value;
1328 pixels[offset + 2] = value;
1329 pixels[offset + 3] = 255;
1330 }
1331 }
1332 }
1333 }
1334 const ctx = baked.lightmapCanvas.getContext("2d");
1335 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
1336 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
1337 }
1338
1339 #updateSwipes (now)
1340 {
1341 this.swipes = this.swipes.filter((swipe) =>
1342 {
1343 if (swipe.until > now)
1344 {
1345 if (swipe.fromTileX != null)
1346 {
1347 this.#applyPhysicalCombatFxDarkness(
1348 swipe.object,
1349 swipe.fromTileX,
1350 swipe.fromTileY,
1351 swipe.tileX,
1352 swipe.tileY
1353 );
1354 }
1355 return true;
1356 }
1357 swipe.object?.destroy();
1358 return false;
1359 });
1360 }
1361
1362 #updateDamageNumbers (now)
1363 {
1364 const layer = this.damageNumbersEl;
1365 if (!layer)
1366 { return; }
1367 this.damageFloats = this.damageFloats.filter((entry) =>
1368 {
1369 const elapsed = now - entry.started;
1370 if (elapsed >= DAMAGE_FLOAT_MS)
1371 {
1372 entry.element?.remove();
1373 return false;
1374 }
1375 const entity = this.entities.get(entry.entityId);
1376 if (!entity)
1377 {
1378 entry.element?.remove();
1379 return false;
1380 }
1381 if (!entry.element)
1382 {
1383 entry.element = document.createElement("span");
1384 entry.element.className = "damage-number";
1385 entry.element.textContent = String(entry.damage);
1386 layer.append(entry.element);
1387 }
1388 const anchor = this.nametagAnchor(entity);
1389 if (!anchor)
1390 { return true; }
1391 const t = elapsed / DAMAGE_FLOAT_MS;
1392 entry.element.style.left = `${anchor.x}px`;
1393 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
1394 entry.element.style.opacity = String(1 - t);
1395 return true;
1396 });
1397 }
1398
1399 #syncBloomLayer ()
1400 {
1401 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
1402 this.scene.setLayers([
1403 { name: "default" },
1404 {
1405 name: RENDER_LAYER_BLOOM,
1406 composite: "add",
1407 postShaders: Shader.getBloomPostChain({
1408 threshold: settings.bloomThreshold,
1409 softKnee: settings.bloomSoftKnee,
1410 intensity: settings.bloomIntensity,
1411 blurSize: settings.bloomBlurSize,
1412 saturation: settings.bloomSaturation,
1413 colorPreserve: settings.bloomColorPreserve,
1414 dilate: settings.bloomDilate,
1415 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
1416 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
1417 })
1418 }
1419 ]);
1420 }
1421}
1422
1423export function nightFactor (hour, nightDarkness = 0.72)
1424{
1425 const peak = Math.min(1, Math.max(0, nightDarkness));
1426 if (hour >= 8 && hour <= 16)
1427 { return 0; }
1428 if (hour >= 22 || hour <= 5)
1429 { return peak; }
1430 if (hour < 8)
1431 { return lerp(peak, 0, (hour - 5) / 3); }
1432 return lerp(0, peak, (hour - 16) / 6);
1433}
1434
1435function bodySpriteName (sex)
1436{
1437 const key = sex === "female" ? "player-body-female" : "player-body-male";
1438 return spriteImageName("character", key, key);
1439}
1440
1441function lerp (a, b, t)
1442{
1443 return a + (b - a) * Math.min(1, Math.max(0, t));
1444}
1445
1446function makeLightmapCanvas (size)
1447{
1448 const canvas = document.createElement("canvas");
1449 canvas.width = size;
1450 canvas.height = size;
1451 return canvas;
1452}
1453
1454function copyCanvas (source, dest)
1455{
1456 const ctx = dest.getContext("2d");
1457 ctx.imageSmoothingEnabled = false;
1458 ctx.clearRect(0, 0, dest.width, dest.height);
1459 ctx.drawImage(source, 0, 0);
1460}
1461
1462function drawHpBar (canvas, current, max)
1463{
1464 const ctx = canvas.getContext("2d");
1465 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
1466 ctx.fillStyle = "#000000";
1467 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
1468 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
1469 const fillW = Math.round(12 * ratio);
1470 if (fillW > 0)
1471 {
1472 ctx.fillStyle = "#ff0000";
1473 ctx.fillRect(1, 1, fillW, 2);
1474 }
1475}