BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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