BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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