BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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