BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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