BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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