BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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