BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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