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