BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 108.3 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";
5import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
6import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
7import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js";
8import { normalizeGround, isWadeGroundInSeason, isWaterGround, isLiquidWaterGround, isGroundPassable, isBlockOccludingLight, LightOcclusion } from "/shared/definitions/tiles.js";
9import { spriteCenterFromPivot, spriteDrawSize, tilePivot, ySortLayer } from "/shared/render/pivot.js";
10import { bakeChunkAtlases } from "./chunkBake.js";
11import
12{
13 frameworkImageFromCanvas,
14 invalidateCanvasTexture
15} from "./canvasSprite.js";
16import { setNearestFilter } from "./sprites.js";
17import { SeasonId, seasonIdAt } from "/shared/world/season.js";
18import
19{
20 OVERWORLD_ID,
21 normalizeDimensionId,
22 normalizeLightingMode,
23 normalizeSeasonMode,
24 resolveDimensionDarknessFactor,
25 resolveDimensionSeasonId
26} from "/shared/world/dimensions.js";
27import { SPELL_PROJECTILE_FRAME_MS } from "/shared/spells/constants.js";
28
29const LAYER_GROUND = 0;
30const LAYER_EDGE = 900000;
31const SORT_BLOCK = 2;
32const SORT_ENTITY = 3;
33const SORT_HP_BAR = 4;
34const SORT_FX = 5;
35const RENDER_LAYER_BLOOM = "bloom";
36
37const HP_BAR_W = 14;
38const HP_BAR_H = 4;
39const WALK_TILT_DEG = 6;
40const RUN_TILT_DEG = 8;
41const SHOVE_TILE_FRACTION = 0.25;
42const SHOVE_MS = 280;
43/** Soft reflow when stack circle targets change (join/leave a shared tile). */
44const STACK_SPREAD_LERP_MS = 280;
45/** Hold gather-tool equip overlay slightly past swing interval so it stays visible between swings. */
46const GATHER_TOOL_HOLD_MS = 1100;
47const DAMAGE_FLASH_MS = 180;
48const DAMAGE_FLOAT_MS = 900;
49const SKILL_LEVEL_FLOAT_MS = 2800;
50
51const SPRITE_LIGHTING_FRAG = [
52 "precision mediump float;",
53 "varying vec2 v_texCoord;",
54 "uniform sampler2D u_texture;",
55 "uniform float u_darkness;",
56 "uniform float u_strength;",
57 "uniform float u_wade;",
58 "uniform float u_spriteHeight;",
59 "void main() {",
60 " vec4 color = texture2D(u_texture, v_texCoord);",
61 " if (color.a <= 0.0) { discard; }",
62 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
63 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
64 " vec3 rgb = color.rgb;",
65 " if (u_wade > 0.5 && fromBottom < 5.0) {",
66 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
67 " }",
68 " rgb = mix(rgb, vec3(0.0), u_darkness);",
69 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
70 " gl_FragColor = vec4(rgb, color.a);",
71 "}"
72].join("\n");
73
74const WATER_GROUND_FRAG = [
75 "precision mediump float;",
76 "varying vec2 v_texCoord;",
77 "uniform sampler2D u_texture;",
78 "uniform float u_ambientDark;",
79 "uniform float u_litNW;",
80 "uniform float u_litNE;",
81 "uniform float u_litSW;",
82 "uniform float u_litSE;",
83 "uniform float u_time;",
84 "uniform float u_edgeN;",
85 "uniform float u_edgeE;",
86 "uniform float u_edgeS;",
87 "uniform float u_edgeW;",
88 "void main() {",
89 " vec4 color = texture2D(u_texture, v_texCoord);",
90 " if (color.a <= 0.0) { discard; }",
91 " vec3 rgb = color.rgb;",
92 " float foam = 0.0;",
93 " float pulse = 0.55 + 0.45 * sin(u_time * 3.2 + v_texCoord.x * 18.0 + v_texCoord.y * 10.0);",
94 " if (u_edgeN > 0.5 && v_texCoord.y < 0.22) {",
95 " foam = max(foam, (1.0 - v_texCoord.y / 0.22) * pulse);",
96 " }",
97 " if (u_edgeS > 0.5 && v_texCoord.y > 0.78) {",
98 " foam = max(foam, ((v_texCoord.y - 0.78) / 0.22) * pulse);",
99 " }",
100 " if (u_edgeW > 0.5 && v_texCoord.x < 0.22) {",
101 " foam = max(foam, (1.0 - v_texCoord.x / 0.22) * pulse);",
102 " }",
103 " if (u_edgeE > 0.5 && v_texCoord.x > 0.78) {",
104 " foam = max(foam, ((v_texCoord.x - 0.78) / 0.22) * pulse);",
105 " }",
106 " rgb = mix(rgb, vec3(0.78, 0.92, 1.0), clamp(foam, 0.0, 0.85));",
107 " float litTop = mix(u_litNW, u_litNE, v_texCoord.x);",
108 " float litBottom = mix(u_litSW, u_litSE, v_texCoord.x);",
109 " float lit = mix(litTop, litBottom, v_texCoord.y);",
110 " float darkness = u_ambientDark * (1.0 - lit);",
111 " rgb = mix(rgb, vec3(0.0), darkness);",
112 " gl_FragColor = vec4(rgb, color.a);",
113 "}"
114].join("\n");
115
116/** Magenta-tint (R==B, G < R) then lit effects; darkness always after tint. */
117const TINT_LIT_SPRITE_FRAG = [
118 "precision mediump float;",
119 "varying vec2 v_texCoord;",
120 "uniform sampler2D u_texture;",
121 "uniform float u_darkness;",
122 "uniform float u_strength;",
123 "uniform float u_wade;",
124 "uniform float u_spriteHeight;",
125 "uniform float u_useTint;",
126 "uniform vec3 u_tintColor;",
127 "void main() {",
128 " vec4 color = texture2D(u_texture, v_texCoord);",
129 " if (color.a <= 0.0) { discard; }",
130 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
131 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
132 " vec3 rgb = color.rgb;",
133 " if (u_useTint > 0.5) {",
134 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
135 " float L = color.r;",
136 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
137 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
138 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
139 " }",
140 " }",
141 " if (u_wade > 0.5 && fromBottom < 5.0) {",
142 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
143 " }",
144 " rgb = mix(rgb, vec3(0.0), u_darkness);",
145 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
146 " gl_FragColor = vec4(rgb, color.a);",
147 "}"
148].join("\n");
149
150/** Dual-channel tint: red = shaft/wood, blue = tip/string, white unchanged; then darkness. */
151const DUAL_TINT_LIT_SPRITE_FRAG = [
152 "precision mediump float;",
153 "varying vec2 v_texCoord;",
154 "uniform sampler2D u_texture;",
155 "uniform float u_darkness;",
156 "uniform float u_strength;",
157 "uniform float u_wade;",
158 "uniform float u_spriteHeight;",
159 "uniform vec3 u_shaftTint;",
160 "uniform vec3 u_tipTint;",
161 "void main() {",
162 " vec4 color = texture2D(u_texture, v_texCoord);",
163 " if (color.a <= 0.0) { discard; }",
164 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
165 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
166 " vec3 rgb = color.rgb;",
167 " float tipMask = clamp((color.b - max(color.r, color.g)) * 1.75, 0.0, 1.0);",
168 " if (tipMask > 0.0) {",
169 " float L = color.b;",
170 " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;",
171 " float tipLuma = dot(u_tipTint, vec3(0.2126, 0.7152, 0.0722));",
172 " vec3 tipCol = mix(u_tipTint, vec3(tipLuma), gBlend) * L;",
173 " rgb = mix(rgb, tipCol, tipMask);",
174 " }",
175 " float shaftMask = clamp((color.r - max(color.g, color.b)) * 1.75, 0.0, 1.0);",
176 " if (shaftMask > 0.0) {",
177 " float L = color.r;",
178 " float gBlend = L > 0.0 ? clamp(color.g / L, 0.0, 1.0) : 0.0;",
179 " float shaftLuma = dot(u_shaftTint, vec3(0.2126, 0.7152, 0.0722));",
180 " vec3 shaftCol = mix(u_shaftTint, vec3(shaftLuma), gBlend) * L;",
181 " rgb = mix(rgb, shaftCol, shaftMask);",
182 " }",
183 " if (u_wade > 0.5 && fromBottom < 5.0) {",
184 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
185 " }",
186 " rgb = mix(rgb, vec3(0.0), u_darkness);",
187 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
188 " gl_FragColor = vec4(rgb, color.a);",
189 "}"
190].join("\n");
191
192/** Magenta-tint equip overlay that clips alpha to the worn body silhouette. */
193/**
194 * Tight-fit: clip clothing alpha to the body silhouette in *pivot space*
195 * (sizes may differ: shirt 20×24 vs body 16×24). Sample body UV remapped from
196 * clothing frame coords; 1px dilate fills armpit/crotch gaps in the body art.
197 */
198const TIGHT_FIT_BODY_MASK_GLSL = [
199 "uniform vec2 u_clothSize;",
200 "uniform vec2 u_bodySize;",
201 "uniform float u_pivotFromBottom;",
202 "uniform vec4 u_clothUvRect;",
203 "uniform vec4 u_bodyUvRect;",
204 "float tightFitBodyAlpha() {",
205 " vec2 clothSpan = max(u_clothUvRect.zw - u_clothUvRect.xy, vec2(1e-5));",
206 " vec2 nu = (v_texCoord - u_clothUvRect.xy) / clothSpan;",
207 " float ox = (nu.x - 0.5) * u_clothSize.x;",
208 " float oy = nu.y * u_clothSize.y - (u_clothSize.y - u_pivotFromBottom);",
209 " vec2 bodySize = max(u_bodySize, vec2(1.0));",
210 " vec2 bodyNu = vec2(0.5 + ox / bodySize.x, ((u_bodySize.y - u_pivotFromBottom) + oy) / bodySize.y);",
211 " vec2 bodySpan = max(u_bodyUvRect.zw - u_bodyUvRect.xy, vec2(1e-5));",
212 " vec2 texel = 1.0 / bodySize;",
213 " float bodyA = 0.0;",
214 " for (int dy = -1; dy <= 1; dy++) {",
215 " for (int dx = -1; dx <= 1; dx++) {",
216 " vec2 sampleNu = bodyNu + vec2(float(dx), float(dy)) * texel;",
217 " if (sampleNu.x < 0.0 || sampleNu.x > 1.0 || sampleNu.y < 0.0 || sampleNu.y > 1.0) { continue; }",
218 " vec2 sampleUv = u_bodyUvRect.xy + sampleNu * bodySpan;",
219 " bodyA = max(bodyA, texture2D(u_secondary, sampleUv).a);",
220 " }",
221 " }",
222 " return bodyA;",
223 "}"
224].join("\n");
225
226const TIGHT_FIT_TINT_LIT_SPRITE_FRAG = [
227 "precision mediump float;",
228 "varying vec2 v_texCoord;",
229 "uniform sampler2D u_texture;",
230 "uniform sampler2D u_secondary;",
231 "uniform float u_darkness;",
232 "uniform float u_strength;",
233 "uniform float u_wade;",
234 "uniform float u_spriteHeight;",
235 "uniform float u_useTint;",
236 "uniform vec3 u_tintColor;",
237 TIGHT_FIT_BODY_MASK_GLSL,
238 "void main() {",
239 " vec4 color = texture2D(u_texture, v_texCoord);",
240 " if (color.a <= 0.0) { discard; }",
241 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
242 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
243 " vec3 rgb = color.rgb;",
244 " if (u_useTint > 0.5) {",
245 " if (abs(color.r - color.b) * 255.0 <= 2.01 && color.g < color.r) {",
246 " float L = color.r;",
247 " float gBlend = color.r > 0.0 ? clamp(color.g / color.r, 0.0, 1.0) : 0.0;",
248 " float tintLuma = dot(u_tintColor, vec3(0.2126, 0.7152, 0.0722));",
249 " rgb = mix(u_tintColor, vec3(tintLuma), gBlend) * L;",
250 " }",
251 " }",
252 " if (u_wade > 0.5 && fromBottom < 5.0) {",
253 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
254 " }",
255 " rgb = mix(rgb, vec3(0.0), u_darkness);",
256 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
257 " float alpha = min(tightFitBodyAlpha(), color.a);",
258 " if (alpha <= 0.0) { discard; }",
259 " gl_FragColor = vec4(rgb, alpha);",
260 "}"
261].join("\n");
262
263/** Body-clipped equip overlay without dye recolour. */
264const TIGHT_FIT_LIT_SPRITE_FRAG = [
265 "precision mediump float;",
266 "varying vec2 v_texCoord;",
267 "uniform sampler2D u_texture;",
268 "uniform sampler2D u_secondary;",
269 "uniform float u_darkness;",
270 "uniform float u_strength;",
271 "uniform float u_wade;",
272 "uniform float u_spriteHeight;",
273 TIGHT_FIT_BODY_MASK_GLSL,
274 "void main() {",
275 " vec4 color = texture2D(u_texture, v_texCoord);",
276 " if (color.a <= 0.0) { discard; }",
277 " float fromBottom = (1.0 - v_texCoord.y) * max(u_spriteHeight, 1.0);",
278 " if (u_wade > 0.5 && fromBottom < 4.0) { discard; }",
279 " vec3 rgb = color.rgb;",
280 " if (u_wade > 0.5 && fromBottom < 5.0) {",
281 " rgb = mix(rgb, vec3(0.55, 0.82, 0.98), 0.55);",
282 " }",
283 " rgb = mix(rgb, vec3(0.0), u_darkness);",
284 " rgb = mix(rgb, vec3(1.0, 0.12, 0.12), u_strength);",
285 " float alpha = min(tightFitBodyAlpha(), color.a);",
286 " if (alpha <= 0.0) { discard; }",
287 " gl_FragColor = vec4(rgb, alpha);",
288 "}"
289].join("\n");
290
291const ATLAS_LIGHTING_FRAG = [
292 "precision mediump float;",
293 "varying vec2 v_texCoord;",
294 "uniform sampler2D u_texture;",
295 "uniform sampler2D u_secondary;",
296 "uniform float u_ambientDark;",
297 "uniform float u_lightRow;",
298 "void main() {",
299 " vec4 color = texture2D(u_texture, v_texCoord);",
300 " if (color.a <= 0.0) { discard; }",
301 " vec2 lightUV = v_texCoord;",
302 " if (u_lightRow >= 0.0) {",
303 " lightUV.y = (u_lightRow + v_texCoord.y) / 16.0;",
304 " }",
305 " float lit = texture2D(u_secondary, lightUV).r;",
306 " float darkness = u_ambientDark * (1.0 - lit);",
307 " vec3 rgb = mix(color.rgb, vec3(0.0), darkness);",
308 " gl_FragColor = vec4(rgb, color.a);",
309 "}"
310].join("\n");
311
312let spriteLightingShader = null;
313let atlasLightingShader = null;
314let waterGroundShader = null;
315let tintLitSpriteShader = null;
316let dualTintLitSpriteShader = null;
317let tightFitTintLitSpriteShader = null;
318let tightFitLitSpriteShader = null;
319
320function getSpriteLightingShader ()
321{
322 if (!spriteLightingShader)
323 { spriteLightingShader = Shader.fragment(SPRITE_LIGHTING_FRAG); }
324 return spriteLightingShader;
325}
326
327function getAtlasLightingShader ()
328{
329 if (!atlasLightingShader)
330 { atlasLightingShader = Shader.fragment(ATLAS_LIGHTING_FRAG); }
331 return atlasLightingShader;
332}
333
334function getWaterGroundShader ()
335{
336 if (!waterGroundShader)
337 { waterGroundShader = Shader.fragment(WATER_GROUND_FRAG); }
338 return waterGroundShader;
339}
340
341function getTintLitSpriteShader ()
342{
343 if (!tintLitSpriteShader)
344 { tintLitSpriteShader = Shader.fragment(TINT_LIT_SPRITE_FRAG); }
345 return tintLitSpriteShader;
346}
347
348function getDualTintLitSpriteShader ()
349{
350 if (!dualTintLitSpriteShader)
351 { dualTintLitSpriteShader = Shader.fragment(DUAL_TINT_LIT_SPRITE_FRAG); }
352 return dualTintLitSpriteShader;
353}
354
355function getTightFitTintLitSpriteShader ()
356{
357 if (!tightFitTintLitSpriteShader)
358 { tightFitTintLitSpriteShader = Shader.fragment(TIGHT_FIT_TINT_LIT_SPRITE_FRAG); }
359 return tightFitTintLitSpriteShader;
360}
361
362function getTightFitLitSpriteShader ()
363{
364 if (!tightFitLitSpriteShader)
365 { tightFitLitSpriteShader = Shader.fragment(TIGHT_FIT_LIT_SPRITE_FRAG); }
366 return tightFitLitSpriteShader;
367}
368
369export class WorldView
370{
371 #chunkRebuildKeys = new Set();
372 #chunkRebuildRaf = 0;
373 #edgesDirty = false;
374 #CHUNK_REBUILD_BATCH = 2;
375 #pendingTextureCanvases = [];
376 #pendingTextureCanvasSet = new Set();
377 #textureWarmRaf = 0;
378 #TEXTURE_WARM_BATCH = 2;
379
380 constructor(game, scene, catalog = { grounds: {}, blocks: {} })
381 {
382 this.game = game;
383 this.scene = scene;
384 this.catalog = catalog;
385 this.preview = null;
386 this.zoom = 2;
387 this.chunks = new Map();
388 this.bakedChunks = new Map();
389 this.tiles = new Map();
390 this.entities = new Map();
391 this.groundItems = new Map();
392 this.edges = new Map();
393 this.localEntityId = null;
394 this.localBlind = false;
395 /** @type {string} */
396 this.dimensionId = OVERWORLD_ID;
397 /** @type {string} */
398 this.dimensionLightingMode = "dayNight";
399 /** @type {string} */
400 this.dimensionSeasonMode = "auto";
401 /** Calendar season from worldStatus when dimension season is auto. */
402 this.calendarSeason = seasonIdAt();
403 /** @type {"soft"|"simple"} */
404 this.lightingMode = "soft";
405 /** @type {boolean} */
406 this.bloomEnabled = true;
407 /** Soft edge blend for blendable grounds (grass, dirt, …). */
408 this.softTerrain = false;
409 this.settings = { ...DEFAULT_WORLD_SETTINGS };
410 this.worldHour = 12;
411 /** Calendar season for seasonal ground/block visuals (`spring` / `summer` / `fall` / `winter`). */
412 this.worldSeason = seasonIdAt();
413 this.nightPreview = null;
414 this.followPlayer = true;
415 this.dynamicLights = [];
416 this.swipes = [];
417 this.damageFloats = [];
418 this.damageNumbersEl = document.getElementById("damage-numbers");
419 this.skillLevelFloats = [];
420 this.skillLevelFloatsEl = document.getElementById("skill-level-floats");
421 /** @type {Map<string, { object: object, tileX: number, tileY: number, spriteName: string }>} */
422 this.editorSpawners = new Map();
423 this.spawnRangeHighlight = null;
424 this.wanderRangeHighlight = null;
425 this.spellTargetHighlight = null;
426 this.#syncBloomLayer();
427 }
428
429 setSettings (settings)
430 {
431 this.settings = { ...DEFAULT_WORLD_SETTINGS, ...settings };
432 this.#syncBloomLayer();
433 }
434
435 /**
436 * Client graphics prefs (lighting Soft/Simple, bloom On/Off, soft terrain).
437 * @param {{ lighting?: string, bloom?: string, softTerrain?: string }} prefs
438 */
439 setGraphicsPrefs (prefs)
440 {
441 if (prefs?.lighting === "simple" || prefs?.lighting === "soft")
442 { this.lightingMode = prefs.lighting; }
443 if (prefs?.bloom === "off" || prefs?.bloom === "on")
444 {
445 const enabled = prefs.bloom !== "off";
446 if (enabled !== this.bloomEnabled)
447 {
448 this.bloomEnabled = enabled;
449 this.#syncBloomLayer();
450 }
451 else
452 { this.bloomEnabled = enabled; }
453 }
454 if (prefs?.softTerrain === "on" || prefs?.softTerrain === "off")
455 {
456 const enabled = prefs.softTerrain === "on";
457 if (enabled !== this.softTerrain)
458 {
459 this.softTerrain = enabled;
460 this.#rebakeAllChunks();
461 }
462 }
463 }
464
465 /** Apply server (or local) calendar season; rebakes chunks when it changes. */
466 setWorldSeason (season)
467 {
468 const calendar = season === SeasonId.spring
469 || season === SeasonId.fall
470 || season === SeasonId.winter
471 || season === SeasonId.summer
472 ? season
473 : seasonIdAt();
474 this.calendarSeason = calendar;
475 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
476 const next = forced ?? calendar;
477 if (next === this.worldSeason)
478 { return; }
479 this.worldSeason = next;
480 this.#rebakeAllChunks();
481 }
482
483 setDimensionId (dimensionId)
484 {
485 this.dimensionId = normalizeDimensionId(dimensionId);
486 }
487
488 setDimensionModes (lightingMode, seasonMode)
489 {
490 this.dimensionLightingMode = normalizeLightingMode(lightingMode);
491 this.dimensionSeasonMode = normalizeSeasonMode(seasonMode);
492 const forced = resolveDimensionSeasonId(this.dimensionSeasonMode);
493 const next = forced ?? this.calendarSeason ?? seasonIdAt();
494 if (next !== this.worldSeason)
495 {
496 this.worldSeason = next;
497 this.#rebakeAllChunks();
498 }
499 }
500
501 clearAllChunks ()
502 {
503 for (const key of [...this.chunks.keys()])
504 {
505 const [chunkX, chunkY] = key.split(",").map(Number);
506 this.removeChunk(chunkX, chunkY);
507 }
508 for (const [id] of [...this.entities.entries()])
509 {
510 if (id === this.localEntityId)
511 { continue; }
512 this.despawnEntity(id);
513 }
514 for (const [id] of [...this.groundItems.entries()])
515 { this.despawnGroundItem(id); }
516 }
517
518 /** Full client wipe when leaving the world (menu / disconnect). Includes the local player. */
519 clearPlaySession ()
520 {
521 this.localEntityId = null;
522 for (const key of [...this.chunks.keys()])
523 {
524 const [chunkX, chunkY] = key.split(",").map(Number);
525 this.removeChunk(chunkX, chunkY);
526 }
527 for (const [id] of [...this.entities.entries()])
528 { this.despawnEntity(id); }
529 for (const [id] of [...this.groundItems.entries()])
530 { this.despawnGroundItem(id); }
531 }
532
533 applySnapshot (snapshot)
534 {
535 const snapDim = normalizeDimensionId(snapshot.dimensionId ?? OVERWORLD_ID);
536 if (normalizeDimensionId(this.dimensionId) !== snapDim)
537 { return; }
538 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
539 if (!Array.isArray(snapshot.occlusion) || snapshot.occlusion.length < CHUNK_SIZE * CHUNK_SIZE)
540 {
541 snapshot.occlusion = bakeChunkOcclusion(snapshot);
542 }
543 this.chunks.set(key, snapshot);
544 this.#scheduleChunkRebuild(snapshot);
545 this.#redrawPreview();
546 this.#refreshWaterCoastsNear(snapshot.chunkX, snapshot.chunkY);
547 if (snapshot.staticOnly)
548 {
549 this.#stripChunkDynamic(snapshot.chunkX, snapshot.chunkY);
550 this.#scheduleEdgeRebuild();
551 return;
552 }
553 for (const entity of snapshot.entities ?? [])
554 { this.#upsertEntity(entity); }
555 for (const [id, item] of [...this.groundItems.entries()])
556 {
557 if (Math.floor(item.tileX / CHUNK_SIZE) === snapshot.chunkX && Math.floor(item.tileY / CHUNK_SIZE) === snapshot.chunkY)
558 { this.despawnGroundItem(id); }
559 }
560 for (const item of snapshot.groundItems ?? [])
561 { this.upsertGroundItem(item); }
562 this.#scheduleEdgeRebuild();
563 }
564
565 setLocalEntity (entityId, tileX, tileY, gait, sex, firstName = "", lastName = "", characterId = null, layers = null, health = null, maxHealth = null)
566 {
567 this.localEntityId = entityId;
568 this.#upsertEntity({
569 entityId,
570 characterId,
571 tileX,
572 tileY,
573 gait,
574 sex,
575 firstName,
576 lastName,
577 layers: layers ?? undefined,
578 ...(health != null ? { health } : {}),
579 ...(maxHealth != null ? { maxHealth } : {})
580 });
581 }
582
583 #stripChunkDynamic (chunkX, chunkY)
584 {
585 for (const [id, item] of [...this.groundItems.entries()])
586 {
587 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
588 { this.despawnGroundItem(id); }
589 }
590 for (const [id, entity] of [...this.entities.entries()])
591 {
592 if (id === this.localEntityId)
593 { continue; }
594 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
595 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
596 { this.despawnEntity(id); }
597 }
598 }
599
600 removeChunk (chunkX, chunkY)
601 {
602 const key = `${chunkX},${chunkY}`;
603 this.chunks.delete(key);
604 this.#destroyBakedChunk(key);
605 this.#destroyEdges(key);
606 const prefix = `${chunkX},${chunkY}:`;
607 for (const [spawnerKey, entry] of [...this.editorSpawners.entries()])
608 {
609 if (!spawnerKey.startsWith(prefix))
610 { continue; }
611 entry.object?.destroy();
612 this.editorSpawners.delete(spawnerKey);
613 }
614 for (const [tileKey, objects] of [...this.tiles.entries()])
615 {
616 if (objects.chunkX === chunkX && objects.chunkY === chunkY)
617 {
618 objects.ground?.destroy();
619 objects.groundBloom?.destroy();
620 objects.block?.destroy();
621 objects.blockBloom?.destroy();
622 this.tiles.delete(tileKey);
623 }
624 }
625 for (const [id, item] of [...this.groundItems.entries()])
626 {
627 if (Math.floor(item.tileX / CHUNK_SIZE) === chunkX && Math.floor(item.tileY / CHUNK_SIZE) === chunkY)
628 { this.despawnGroundItem(id); }
629 }
630 // Server sends unsubscribeChunk when a chunk leaves the static 5×5 ring.
631 // Entity replication is limited to the inner 3×3; static-only chunks strip dynamics via staticOnly snapshots.
632 for (const [id, entity] of [...this.entities.entries()])
633 {
634 if (id === this.localEntityId)
635 { continue; }
636 if (Math.floor(entity.tileX / CHUNK_SIZE) === chunkX
637 && Math.floor(entity.tileY / CHUNK_SIZE) === chunkY)
638 { this.despawnEntity(id); }
639 }
640 this.#rebuildAllEdges();
641 }
642
643 setChunkOpen (chunkX, chunkY, open)
644 {
645 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
646 if (!snapshot)
647 { return; }
648 snapshot.open = !!open;
649 this.#rebuildAllEdges();
650 }
651
652 spawnEntity (payload)
653 {
654 this.#upsertEntity(payload);
655 }
656
657 moveEntity (payload)
658 {
659 const existing = this.entities.get(payload.entityId);
660 if (!existing)
661 {
662 this.#upsertEntity(payload);
663 return;
664 }
665 const size = this.tileSize();
666 existing.fromX = existing.visualX;
667 existing.fromY = existing.visualY;
668 existing.shadeFromTileX = existing.tileX;
669 existing.shadeFromTileY = existing.tileY;
670 existing.tileX = payload.tileX;
671 existing.tileY = payload.tileY;
672 existing.gait = payload.gait;
673 existing.freeFlight = !!payload.freeFlight || existing.freeFlight;
674 if (payload.worldX != null && payload.worldY != null)
675 {
676 existing.worldX = payload.worldX;
677 existing.worldY = payload.worldY;
678 existing.targetX = payload.worldX * size;
679 existing.targetY = payload.worldY * size;
680 }
681 else
682 {
683 const pivot = tilePivot(payload.tileX, payload.tileY, size);
684 existing.targetX = pivot.x;
685 existing.targetY = pivot.y;
686 }
687 existing.lerpStarted = performance.now();
688 existing.lerpMs = payload.lerpMs ?? this.#lerpMs(payload.gait);
689 }
690
691 despawnEntity (entityId)
692 {
693 const existing = this.entities.get(entityId);
694 if (!existing)
695 { return; }
696 existing.object?.destroy();
697 existing.hpBar?.destroy();
698 for (const overlay of existing.overlays ?? [])
699 { overlay.destroy(); }
700 for (const overlay of existing.bloomOverlays ?? [])
701 { overlay.destroy(); }
702 this.entities.delete(entityId);
703 }
704
705 updateEntityHealth (entityId, health, maxHealth)
706 {
707 const entity = this.entities.get(entityId);
708 if (!entity)
709 { return; }
710 entity.health = health;
711 entity.maxHealth = maxHealth;
712 this.#syncHpBar(entity);
713 }
714
715 flashDamage (entityId)
716 {
717 const entity = this.entities.get(entityId);
718 if (!entity)
719 { return; }
720 entity.damageFlashUntil = performance.now() + DAMAGE_FLASH_MS;
721 }
722
723 spawnDamageNumber (entityId, damage)
724 {
725 const amount = damage | 0;
726 if (amount <= 0)
727 { return; }
728 this.damageFloats.push({
729 entityId,
730 damage: amount,
731 started: performance.now()
732 });
733 }
734
735 /**
736 * Queue combat-hit presentation until a matching in-flight projectile lands.
737 * Returns true when deferred; caller should apply immediately when false.
738 */
739 deferCombatHit (message, apply)
740 {
741 if (typeof apply !== "function" || message?.targetId == null)
742 { return false; }
743 const attackerId = message.attackerId ?? null;
744 const targetId = message.targetId;
745 const swipe = this.swipes.find((entry) =>
746 entry.lerp
747 && entry.onImpact == null
748 && entry.targetId === targetId
749 && (attackerId == null || entry.attackerId === attackerId)
750 && (entry.until ?? 0) > performance.now());
751 if (!swipe)
752 { return false; }
753 swipe.onImpact = apply;
754 swipe.trackTarget = true;
755 return true;
756 }
757
758 /** Stop tracking a living target (misses fly to a fixed tile). */
759 markProjectileMiss (message)
760 {
761 const attackerId = message?.attackerId ?? null;
762 const targetId = message?.targetId ?? null;
763 for (const swipe of this.swipes)
764 {
765 if (!swipe.lerp || swipe.onImpact != null)
766 { continue; }
767 if (targetId != null && swipe.targetId !== targetId)
768 { continue; }
769 if (attackerId != null && swipe.attackerId !== attackerId)
770 { continue; }
771 swipe.trackTarget = false;
772 if (message.tileX != null)
773 { swipe.tileX = message.tileX; }
774 if (message.tileY != null)
775 { swipe.tileY = message.tileY; }
776 }
777 }
778
779 spawnSkillLevelUp (entityId, payload)
780 {
781 const level = payload?.level | 0;
782 if (level <= 0 || !payload?.icon)
783 { return; }
784 this.skillLevelFloats.push({
785 entityId,
786 level,
787 icon: payload.icon,
788 displayName: payload.displayName ?? payload.skillId ?? "",
789 started: performance.now()
790 });
791 }
792
793 setAppearance (payload)
794 {
795 const existing = this.entities.get(payload.entityId);
796 if (!existing)
797 { return; }
798 existing.lightRadiusTiles = payload.lightRadiusTiles ?? 0;
799 if (payload.visualScale != null)
800 { existing.visualScale = Number(payload.visualScale) || 1; }
801 this.#applyLayers(existing, payload.layers ?? [{ sprite: payload.sprite }]);
802 this.#placeEntity(existing);
803 }
804
805 /**
806 * Render the live entity (body + overlays, same tint/tight-fit shaders as the
807 * world, unlit) into an offscreen FBO, crop the top square, and return a
808 * pixel-scaled canvas for UI (e.g. dialogue speaker icons).
809 * @param {number} entityId
810 * @param {{ size?: number }} [options]
811 * @returns {HTMLCanvasElement | null}
812 */
813 captureEntityPortrait (entityId, { size = 64 } = {})
814 {
815 const entity = this.entities.get(entityId);
816 const body = entity?.object?.renderer?.sprite;
817 const glCtx = this.scene?.glContext;
818 const gl = glCtx?.gl;
819 if (!entity || !body || !gl)
820 { return null; }
821
822 const frameW = Math.max(1, body.width | 0 || SPRITE_SIZE_PX);
823 const frameH = Math.max(1, body.height | 0 || SPRITE_SIZE_PX);
824 if (!this.#ensurePortraitTarget(gl, frameW, frameH))
825 { return null; }
826
827 const prevFb = gl.getParameter(gl.FRAMEBUFFER_BINDING);
828 const prevViewport = gl.getParameter(gl.VIEWPORT);
829 const prevW = glCtx._lastWidth;
830 const prevH = glCtx._lastHeight;
831 const prevBlend = gl.isEnabled(gl.BLEND);
832
833 try
834 {
835 // drawSprite projects with _lastWidth/_lastHeight — match the FBO.
836 glCtx._lastWidth = frameW;
837 glCtx._lastHeight = frameH;
838 gl.bindFramebuffer(gl.FRAMEBUFFER, this._portrait.fb);
839 gl.viewport(0, 0, frameW, frameH);
840 gl.enable(gl.BLEND);
841 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
842 gl.clearColor(0, 0, 0, 0);
843 gl.clear(gl.COLOR_BUFFER_BIT);
844
845 const pivotX = frameW * 0.5;
846 const pivotY = frameH - PIVOT_FROM_BOTTOM_PX;
847 this._portraitBodyMap = body.g_image ?? null;
848 this._portraitTightFitEntity = entity;
849 this.#drawPortraitLayer(glCtx, entity.object, pivotX, pivotY, null, false);
850
851 const overlays = entity.overlays ?? [];
852 const tints = entity.overlayTints ?? [];
853 const dualTints = entity.overlayDualTints ?? [];
854 const tight = entity.overlayTightFit ?? [];
855 for (let index = 0; index < overlays.length; index++)
856 {
857 this.#drawPortraitLayer(
858 glCtx,
859 overlays[index],
860 pivotX,
861 pivotY,
862 tints[index] ?? null,
863 !!tight[index],
864 dualTints[index] ?? null
865 );
866 }
867 this._portraitBodyMap = null;
868 this._portraitTightFitEntity = null;
869
870 const pixels = this._portrait.pixels;
871 gl.readPixels(0, 0, frameW, frameH, gl.RGBA, gl.UNSIGNED_BYTE, pixels);
872 }
873 finally
874 {
875 glCtx._lastWidth = prevW;
876 glCtx._lastHeight = prevH;
877 gl.bindFramebuffer(gl.FRAMEBUFFER, prevFb);
878 gl.viewport(prevViewport[0], prevViewport[1], prevViewport[2], prevViewport[3]);
879 if (!prevBlend)
880 { gl.disable(gl.BLEND); }
881 gl.blendFunc(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA);
882 }
883
884 return this.#portraitPixelsToCanvas(frameW, frameH, size);
885 }
886
887 #ensurePortraitTarget (gl, width, height)
888 {
889 const prev = this._portrait;
890 if (prev && prev.w === width && prev.h === height && prev.fb && prev.tex)
891 { return true; }
892 if (prev?.fb)
893 { gl.deleteFramebuffer(prev.fb); }
894 if (prev?.tex)
895 { gl.deleteTexture(prev.tex); }
896
897 const tex = gl.createTexture();
898 gl.bindTexture(gl.TEXTURE_2D, tex);
899 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
900 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
901 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
902 gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
903 gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, width, height, 0, gl.RGBA, gl.UNSIGNED_BYTE, null);
904
905 const fb = gl.createFramebuffer();
906 gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
907 gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, tex, 0);
908 const status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
909 gl.bindFramebuffer(gl.FRAMEBUFFER, null);
910 if (status !== gl.FRAMEBUFFER_COMPLETE)
911 {
912 gl.deleteFramebuffer(fb);
913 gl.deleteTexture(tex);
914 this._portrait = null;
915 return false;
916 }
917 this._portrait = {
918 fb,
919 tex,
920 w: width,
921 h: height,
922 pixels: new Uint8Array(width * height * 4),
923 scratch: document.createElement("canvas")
924 };
925 return true;
926 }
927
928 #drawPortraitLayer (glCtx, object, pivotX, pivotY, tintColor, tightFit, dualTint = null)
929 {
930 const sprite = object?.renderer?.sprite;
931 if (!sprite?.g_image)
932 { return; }
933 const subImage = object.renderer.subImage | 0;
934 const height = sprite.height || SPRITE_SIZE_PX;
935 const draw = spriteDrawSize(sprite.width, sprite.height, 1);
936 const center = spriteCenterFromPivot(pivotX, pivotY, height, 1);
937 const tint = tintColor ? normalizeRgb(tintColor) : null;
938 let shader = glCtx.defaultShader;
939 let uniforms = null;
940 let secondaryHtml = null;
941
942 const bodyHtml = this._portraitBodyMap;
943 const portraitEntity = this._portraitTightFitEntity;
944 const maskUniforms = tightFit && portraitEntity
945 ? this.#tightFitMaskUniforms(object, portraitEntity)
946 : null;
947 if (dualTint)
948 {
949 const shaft = normalizeRgb(dualTint.shaft);
950 const tip = normalizeRgb(dualTint.tip);
951 shader = getDualTintLitSpriteShader();
952 uniforms = {
953 u_darkness: 0,
954 u_strength: 0,
955 u_wade: 0,
956 u_spriteHeight: height,
957 u_shaftTint: [shaft.r, shaft.g, shaft.b],
958 u_tipTint: [tip.r, tip.g, tip.b]
959 };
960 }
961 else if (tightFit && bodyHtml && maskUniforms)
962 {
963 secondaryHtml = bodyHtml;
964 if (tint)
965 {
966 shader = getTightFitTintLitSpriteShader();
967 uniforms = {
968 u_darkness: 0,
969 u_strength: 0,
970 u_wade: 0,
971 u_spriteHeight: height,
972 u_useTint: 1,
973 u_tintColor: [tint.r, tint.g, tint.b],
974 ...maskUniforms
975 };
976 }
977 else
978 {
979 shader = getTightFitLitSpriteShader();
980 uniforms = {
981 u_darkness: 0,
982 u_strength: 0,
983 u_wade: 0,
984 u_spriteHeight: height,
985 ...maskUniforms
986 };
987 }
988 }
989 else if (tint)
990 {
991 shader = getTintLitSpriteShader();
992 uniforms = {
993 u_darkness: 0,
994 u_strength: 0,
995 u_wade: 0,
996 u_spriteHeight: height,
997 u_useTint: 1,
998 u_tintColor: [tint.r, tint.g, tint.b]
999 };
1000 }
1001 else
1002 {
1003 shader = getSpriteLightingShader();
1004 uniforms = {
1005 u_darkness: 0,
1006 u_strength: 0,
1007 u_wade: 0,
1008 u_spriteHeight: height
1009 };
1010 }
1011
1012 glCtx.drawSprite({
1013 texture: glCtx.getTexture(sprite.g_image),
1014 x: center.x,
1015 y: center.y,
1016 w: draw.w,
1017 h: draw.h,
1018 rotationDeg: 0,
1019 mirrorX: false,
1020 mirrorY: false,
1021 alpha: 1,
1022 uvRect: sprite.getUvRect(subImage),
1023 shader,
1024 uniforms,
1025 textures: secondaryHtml ? { u_secondary: glCtx.getTexture(secondaryHtml) } : null,
1026 lights: null
1027 });
1028 }
1029
1030 #portraitPixelsToCanvas (frameW, frameH, size)
1031 {
1032 const pixels = this._portrait?.pixels;
1033 if (!pixels)
1034 { return null; }
1035 const scratch = this._portrait.scratch;
1036 scratch.width = frameW;
1037 scratch.height = frameH;
1038 const sctx = scratch.getContext("2d");
1039 const imageData = sctx.createImageData(frameW, frameH);
1040 // WebGL y=0 is bottom — flip to top-down image order.
1041 for (let y = 0; y < frameH; y++)
1042 {
1043 const src = (frameH - 1 - y) * frameW * 4;
1044 const dst = y * frameW * 4;
1045 imageData.data.set(pixels.subarray(src, src + frameW * 4), dst);
1046 }
1047 sctx.putImageData(imageData, 0, 0);
1048
1049 const crop = Math.min(frameW, frameH);
1050 const out = document.createElement("canvas");
1051 out.width = size;
1052 out.height = size;
1053 const octx = out.getContext("2d");
1054 octx.imageSmoothingEnabled = false;
1055 octx.clearRect(0, 0, size, size);
1056 octx.drawImage(scratch, 0, 0, crop, crop, 0, 0, size, size);
1057 return out;
1058 }
1059
1060 upsertGroundItem (payload)
1061 {
1062 const size = this.tileSize();
1063 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1064 const potion = payload.instance?.kind === "potion" ? payload.instance : null;
1065 const spriteName = potion
1066 ? spriteImageName("item", "potion", `potion-${Math.max(1, Math.min(5, potion.fillLevel | 0 || 4))}`)
1067 : (payload.sprite ?? itemSpriteName(payload.itemId, payload.instance));
1068 let item = this.groundItems.get(payload.groundItemId);
1069 if (!item)
1070 {
1071 const object = new GameObject(0, 0, this.game.images[spriteName] ?? this.game.images[itemSpriteName(null)], SORT_BLOCK);
1072 this.scene.addObject(object);
1073 item = { object };
1074 this.groundItems.set(payload.groundItemId, item);
1075 }
1076 else if (item.object && this.game.images[spriteName])
1077 { item.object.image = this.game.images[spriteName]; }
1078 item.groundItemId = payload.groundItemId;
1079 item.tileX = payload.tileX;
1080 item.tileY = payload.tileY;
1081 item.itemId = payload.itemId;
1082 item.quantity = payload.quantity;
1083 item.displayName = payload.displayName;
1084 item.sprite = spriteName;
1085 item.instance = payload.instance ?? null;
1086 const stack = { itemId: payload.itemId, instance: payload.instance ?? null };
1087 item.dualTint = resolveItemDualTint(stack, itemDefinition(payload.itemId));
1088 item.tintColor = item.dualTint ? null : resolveItemTint(stack, itemDefinition(payload.itemId));
1089 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1090 this.#syncGroundItemSprite(item, this.tiles.get(`${payload.tileX},${payload.tileY}`)?.shadeAlpha ?? 0);
1091 }
1092
1093 despawnGroundItem (groundItemId)
1094 {
1095 const item = this.groundItems.get(groundItemId);
1096 if (!item)
1097 { return; }
1098 item.object?.destroy();
1099 this.groundItems.delete(groundItemId);
1100 }
1101
1102 groundItemAtTile (tileX, tileY)
1103 {
1104 return this.groundItemsAtTile(tileX, tileY)[0] ?? null;
1105 }
1106
1107 groundItemsAtTile (tileX, tileY)
1108 {
1109 const items = [];
1110 for (const item of this.groundItems.values())
1111 {
1112 if (item.tileX === tileX && item.tileY === tileY)
1113 { items.push(item); }
1114 }
1115 return items;
1116 }
1117
1118 entitiesAtTile (tileX, tileY)
1119 {
1120 const matches = [];
1121 for (const entity of this.entities.values())
1122 {
1123 if (entity.tileX === tileX && entity.tileY === tileY)
1124 { matches.push(entity); }
1125 }
1126 matches.sort((a, b) => (b.object?.layer ?? 0) - (a.object?.layer ?? 0));
1127 return matches;
1128 }
1129
1130 setZoom (zoom, limits = { min: 2, max: 4 })
1131 {
1132 const min = limits.min ?? 1;
1133 const max = limits.max ?? 4;
1134 this.zoom = Math.min(max, Math.max(min, zoom));
1135 for (const snapshot of this.chunks.values())
1136 { this.#relayoutChunk(snapshot); }
1137 const size = this.tileSize();
1138 for (const entity of this.entities.values())
1139 {
1140 entity.visualX = tilePivot(entity.tileX, entity.tileY, size).x;
1141 entity.visualY = tilePivot(entity.tileX, entity.tileY, size).y;
1142 entity.fromX = entity.visualX;
1143 entity.fromY = entity.visualY;
1144 entity.targetX = entity.visualX;
1145 entity.targetY = entity.visualY;
1146 entity.lerpStarted = null;
1147 this.#placeEntity(entity);
1148 }
1149 for (const item of this.groundItems.values())
1150 {
1151 const pivot = tilePivot(item.tileX, item.tileY, size);
1152 this.#placePivoted(item.object, pivot.x, pivot.y, pivot.y - 0.01, SORT_BLOCK);
1153 }
1154 this.#rebuildAllEdges();
1155 this.#relayoutEditorSpawners();
1156 this.#relayoutSpawnRangeHighlight();
1157 this.#relayoutSpellTargetHighlight();
1158 }
1159
1160 tileSize ()
1161 {
1162 return SPRITE_SIZE_PX * this.zoom;
1163 }
1164
1165 screenToTile (mouseX, mouseY)
1166 {
1167 const size = this.tileSize();
1168 const worldX = mouseX - this.scene.cameraPosition.x;
1169 const worldY = mouseY - this.scene.cameraPosition.y;
1170 return {
1171 tileX: Math.floor(worldX / size),
1172 tileY: Math.floor(worldY / size)
1173 };
1174 }
1175
1176 entityAtScreen (mouseX, mouseY)
1177 {
1178 let best = null;
1179 let bestLayer = -Infinity;
1180 for (const entity of this.entities.values())
1181 {
1182 const box = this.#entityScreenBox(entity);
1183 if (!box)
1184 { continue; }
1185 if (mouseX >= box.left && mouseX < box.right && mouseY >= box.top && mouseY < box.bottom)
1186 {
1187 const layer = entity.object?.layer ?? 0;
1188 if (layer >= bestLayer)
1189 {
1190 best = entity;
1191 bestLayer = layer;
1192 }
1193 }
1194 }
1195 return best;
1196 }
1197
1198 nametagAnchor (entity)
1199 {
1200 const box = this.#entityScreenBox(entity);
1201 if (!box)
1202 { return null; }
1203 return { x: (box.left + box.right) / 2, y: box.top };
1204 }
1205
1206 #entityScreenBox (entity)
1207 {
1208 const object = entity?.object;
1209 if (!object)
1210 { return null; }
1211 const size = object.transform.size;
1212 const x = object.transform.position.x + this.scene.cameraPosition.x;
1213 const y = object.transform.position.y + this.scene.cameraPosition.y;
1214 return {
1215 left: x - size.x / 2,
1216 right: x + size.x / 2,
1217 top: y - size.y / 2,
1218 bottom: y + size.y / 2
1219 };
1220 }
1221
1222 update (deltaTime)
1223 {
1224 const now = performance.now();
1225 const size = this.tileSize();
1226 this.#refreshStackTargets();
1227 for (const entity of this.entities.values())
1228 {
1229 const target = entity.targetX != null && entity.targetY != null
1230 ? { x: entity.targetX, y: entity.targetY }
1231 : tilePivot(entity.tileX, entity.tileY, size);
1232 if (entity.lerpStarted != null)
1233 {
1234 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs));
1235 entity.visualX = entity.fromX + (target.x - entity.fromX) * t;
1236 entity.visualY = entity.fromY + (target.y - entity.fromY) * t;
1237 if (t >= 1)
1238 { entity.lerpStarted = null; }
1239 }
1240 else
1241 {
1242 entity.visualX = target.x;
1243 entity.visualY = target.y;
1244 }
1245 this.#updateStackOffset(entity, now);
1246 this.#updateShove(entity, now, size);
1247 this.#expireGatherToolOverlay(entity, now);
1248 this.#placeEntity(entity, now);
1249 }
1250
1251 this.#updateSwipes(now);
1252 this.#updateDamageNumbers(now);
1253 this.#updateSkillLevelFloats(now);
1254 this.#centerCamera();
1255 this.#cullOffscreenDrawables();
1256 this.#updateShade(deltaTime);
1257 }
1258
1259 /**
1260 * Desired circle offsets for stacked entities (applied via {@link #updateStackOffset}).
1261 * Stable assignment by entityId; free-flight entities stay unshifted.
1262 */
1263 #refreshStackTargets ()
1264 {
1265 const byTile = new Map();
1266 for (const entity of this.entities.values())
1267 {
1268 if (entity.freeFlight)
1269 {
1270 entity.stackTargetX = 0;
1271 entity.stackTargetY = 0;
1272 continue;
1273 }
1274 const key = `${entity.tileX},${entity.tileY}`;
1275 let list = byTile.get(key);
1276 if (!list)
1277 {
1278 list = [];
1279 byTile.set(key, list);
1280 }
1281 list.push(entity);
1282 }
1283 const radius = (ENTITY_STACK_SPREAD_DIAMETER_PX * this.zoom) / 2;
1284 for (const list of byTile.values())
1285 {
1286 if (list.length <= 1)
1287 {
1288 for (const entity of list)
1289 {
1290 entity.stackTargetX = 0;
1291 entity.stackTargetY = 0;
1292 }
1293 continue;
1294 }
1295 list.sort((a, b) => String(a.entityId).localeCompare(String(b.entityId)));
1296 const n = list.length;
1297 for (let i = 0; i < n; i++)
1298 {
1299 const angle = -Math.PI / 2 + (Math.PI * 2 * i) / n;
1300 list[i].stackTargetX = Math.cos(angle) * radius;
1301 list[i].stackTargetY = Math.sin(angle) * radius;
1302 }
1303 }
1304 }
1305
1306 #updateStackOffset (entity, now)
1307 {
1308 const tx = entity.stackTargetX ?? 0;
1309 const ty = entity.stackTargetY ?? 0;
1310 const cx = entity.stackOffsetX ?? 0;
1311 const cy = entity.stackOffsetY ?? 0;
1312 if (entity.stackLerpToX !== tx || entity.stackLerpToY !== ty)
1313 {
1314 entity.stackFromX = cx;
1315 entity.stackFromY = cy;
1316 entity.stackLerpToX = tx;
1317 entity.stackLerpToY = ty;
1318 entity.stackLerpStarted = now;
1319 }
1320 if (entity.stackLerpStarted == null)
1321 {
1322 entity.stackOffsetX = tx;
1323 entity.stackOffsetY = ty;
1324 return;
1325 }
1326 const t = Math.min(1, (now - entity.stackLerpStarted) / STACK_SPREAD_LERP_MS);
1327 entity.stackOffsetX = entity.stackFromX + (tx - entity.stackFromX) * t;
1328 entity.stackOffsetY = entity.stackFromY + (ty - entity.stackFromY) * t;
1329 if (t >= 1)
1330 {
1331 entity.stackOffsetX = tx;
1332 entity.stackOffsetY = ty;
1333 entity.stackLerpStarted = null;
1334 }
1335 }
1336
1337 #updateShove (entity, now, tileSize)
1338 {
1339 if (!entity.shove)
1340 {
1341 entity.shoveOffsetX = 0;
1342 entity.shoveOffsetY = 0;
1343 return;
1344 }
1345 const elapsed = now - entity.shove.started;
1346 const t = Math.min(1, elapsed / entity.shove.durationMs);
1347 const maxDist = tileSize * SHOVE_TILE_FRACTION;
1348 const dx = entity.shove.targetVisualX - entity.shove.startVisualX;
1349 const dy = entity.shove.targetVisualY - entity.shove.startVisualY;
1350 const dist = Math.hypot(dx, dy) || 1;
1351 const ux = dx / dist;
1352 const uy = dy / dist;
1353 let phase;
1354 if (t < 0.45)
1355 { phase = t / 0.45; }
1356 else
1357 { phase = 1 - (t - 0.45) / 0.55; }
1358 entity.shoveOffsetX = ux * maxDist * phase;
1359 entity.shoveOffsetY = uy * maxDist * phase;
1360 if (t >= 1)
1361 { entity.shove = null; }
1362 }
1363
1364 spawnCombatSwing (payload)
1365 {
1366 const attacker = this.entities.get(payload.attackerId);
1367 const target = this.entities.get(payload.targetId);
1368 if (!attacker || !target)
1369 { return; }
1370 const ax = attacker.visualX + (attacker.stackOffsetX ?? 0);
1371 const ay = attacker.visualY + (attacker.stackOffsetY ?? 0);
1372 const tx = target.visualX + (target.stackOffsetX ?? 0);
1373 const ty = target.visualY + (target.stackOffsetY ?? 0);
1374 this.#applyShove(attacker, tx, ty);
1375 const midX = (ax + tx) / 2;
1376 const midY = (ay + ty) / 2;
1377 const sortY = Math.max(ay, ty) + 0.02;
1378 const angle = Math.atan2(ty - ay, tx - ax) * (180 / Math.PI);
1379 const spriteName = "fx:melee-swipe:melee-swipe";
1380 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_FX);
1381 if (object.transform)
1382 { object.transform.rotation = angle; }
1383 this.scene.addObject(object);
1384 this.#placePivoted(object, midX, midY, sortY, SORT_FX);
1385 this.#applyPhysicalCombatFxDarkness(object, payload.fromTileX, payload.fromTileY, payload.tileX, payload.tileY);
1386 this.swipes.push({
1387 object,
1388 until: performance.now() + 500,
1389 fromTileX: payload.fromTileX,
1390 fromTileY: payload.fromTileY,
1391 tileX: payload.tileX,
1392 tileY: payload.tileY
1393 });
1394 }
1395
1396 /** Mining / gathering lunge toward a tile — shove only, no swipe FX. */
1397 spawnGatherSwing (payload)
1398 {
1399 const attacker = this.entities.get(payload.attackerId);
1400 if (!attacker)
1401 { return; }
1402 const pivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1403 this.#applyShove(attacker, pivot.x, pivot.y);
1404 if (payload.toolItemId != null)
1405 { this.#setGatherToolOverlay(attacker, payload.toolItemId); }
1406 }
1407
1408 #applyShove (entity, targetVisualX, targetVisualY)
1409 {
1410 entity.shove = {
1411 startVisualX: entity.visualX,
1412 startVisualY: entity.visualY,
1413 targetVisualX,
1414 targetVisualY,
1415 started: performance.now(),
1416 durationMs: SHOVE_MS
1417 };
1418 }
1419
1420 /** Physical combat FX (melee swipes, ranged projectiles). Magic spells stay unshaded. */
1421 spawnPhysicalProjectileFx (payload)
1422 {
1423 const spriteName = payload.sprite ?? "fx:projectile:arrow";
1424 const image = this.game.images[spriteName];
1425 if (!image)
1426 { return; }
1427 const dualTint = this.#dualTintFromPayload(payload);
1428 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1429 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1430 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1431 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1432 const object = new GameObject(0, 0, image, SORT_FX);
1433 if (object.transform)
1434 { object.transform.rotation = angle; }
1435 this.scene.addObject(object);
1436 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1437 this.#applyPhysicalCombatFxDarkness(
1438 object,
1439 payload.fromTileX,
1440 payload.fromTileY,
1441 payload.tileX,
1442 payload.tileY,
1443 dualTint
1444 );
1445 const started = performance.now();
1446 const durationMs = payload.durationMs ?? 400;
1447 const trackTarget = payload.trackTarget !== false && payload.targetId != null;
1448 this.swipes.push({
1449 object,
1450 until: started + durationMs,
1451 started,
1452 durationMs,
1453 lerp: true,
1454 dualTint,
1455 fromTileX: payload.fromTileX,
1456 fromTileY: payload.fromTileY,
1457 tileX: payload.tileX,
1458 tileY: payload.tileY,
1459 attackerId: payload.attackerId ?? null,
1460 targetId: payload.targetId ?? null,
1461 trackTarget,
1462 onImpact: null
1463 });
1464 }
1465
1466 /** Bloom-layer spell projectiles — unlit, animated, 2s travel. */
1467 spawnSpellProjectileFx (payload)
1468 {
1469 const baseSprite = payload.sprite ?? "fx:projectile:spell-light";
1470 const image = this.#spellProjectileImage(baseSprite, 0);
1471 if (!image)
1472 { return; }
1473 const fromPivot = tilePivot(payload.fromTileX, payload.fromTileY, this.tileSize());
1474 const toPivot = tilePivot(payload.tileX, payload.tileY, this.tileSize());
1475 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
1476 const angle = Math.atan2(toPivot.y - fromPivot.y, toPivot.x - fromPivot.x) * (180 / Math.PI);
1477 const object = new GameObject(0, 0, image, SORT_FX);
1478 object.renderer.layer = RENDER_LAYER_BLOOM;
1479 this.#markUnlit(object);
1480 if (object.transform)
1481 { object.transform.rotation = angle; }
1482 this.scene.addObject(object);
1483 this.#placePivoted(object, fromPivot.x, fromPivot.y, sortY, SORT_FX);
1484 const started = performance.now();
1485 const durationMs = payload.durationMs ?? 2000;
1486 this.swipes.push({
1487 object,
1488 until: started + durationMs,
1489 started,
1490 durationMs,
1491 lerp: true,
1492 spellProjectile: true,
1493 baseSprite,
1494 fromTileX: payload.fromTileX,
1495 fromTileY: payload.fromTileY,
1496 tileX: payload.tileX,
1497 tileY: payload.tileY,
1498 attackerId: payload.casterId ?? null,
1499 targetId: payload.targetId ?? null,
1500 trackTarget: payload.targetId != null,
1501 onImpact: null
1502 });
1503 }
1504
1505 spawnSpellFizzleFx (_payload)
1506 {
1507 // Visual-only fizzle; no dynamic light (too expensive for lightmap rebakes).
1508 }
1509
1510 #spellProjectileImage (baseSprite, frameIndex)
1511 {
1512 const frame = Math.max(0, Math.min(2, frameIndex | 0));
1513 const stem = baseSprite.split(":").pop() ?? "spell-light";
1514 const names = [
1515 `${baseSprite}-${frame}`,
1516 `fx:projectile:${stem}-${frame}`,
1517 baseSprite,
1518 `fx:projectile:${stem}`
1519 ];
1520 for (const name of names)
1521 {
1522 if (this.game.images[name])
1523 { return this.game.images[name]; }
1524 }
1525 return null;
1526 }
1527
1528 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1529 {
1530 this.dynamicLights.push({
1531 tileX: Math.floor(worldX),
1532 tileY: Math.floor(worldY),
1533 range: radiusTiles,
1534 intensity,
1535 until: performance.now() + durationMs
1536 });
1537 }
1538
1539 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1540 {
1541 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1542 if (!snapshot)
1543 { return; }
1544 const index = localY * CHUNK_SIZE + localX;
1545 if (ground !== undefined)
1546 { snapshot.grounds[index] = ground; }
1547 if (block !== undefined)
1548 { snapshot.blocks[index] = block; }
1549 if (light !== undefined)
1550 { snapshot.light[index] = light; }
1551 this.#scheduleChunkRebuild(snapshot);
1552 }
1553
1554 /**
1555 * Editor-only mob markers for authored spawners (invisible during play).
1556 * @param {number} chunkX
1557 * @param {number} chunkY
1558 * @param {Array<{ localX: number, localY: number, config?: { mobTypeId?: string } }>} spawners
1559 * @param {(mobTypeId: string) => string} resolveSprite
1560 */
1561 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1562 {
1563 const prefix = `${chunkX},${chunkY}:`;
1564 for (const [key, entry] of [...this.editorSpawners.entries()])
1565 {
1566 if (!key.startsWith(prefix))
1567 { continue; }
1568 entry.object?.destroy();
1569 this.editorSpawners.delete(key);
1570 }
1571 for (const spawner of spawners ?? [])
1572 {
1573 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1574 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1575 const spriteName = resolveSprite?.(spawner.config?.mobTypeId) ?? null;
1576 if (!spriteName)
1577 { continue; }
1578 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1579 const object = this.#ensureSprite(null, spriteName, SORT_ENTITY);
1580 if (!object)
1581 { continue; }
1582 object.renderer.alpha = 0.85;
1583 const pivot = tilePivot(tileX, tileY, this.tileSize());
1584 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1585 this.#markUnlit(object);
1586 this.editorSpawners.set(key, { object, tileX, tileY, spriteName });
1587 }
1588 }
1589
1590 clearEditorSpawners ()
1591 {
1592 for (const entry of this.editorSpawners.values())
1593 { entry.object?.destroy(); }
1594 this.editorSpawners.clear();
1595 }
1596
1597 #relayoutEditorSpawners ()
1598 {
1599 const size = this.tileSize();
1600 for (const entry of this.editorSpawners.values())
1601 {
1602 if (!entry.object)
1603 { continue; }
1604 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1605 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1606 }
1607 }
1608
1609 /**
1610 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
1611 */
1612 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
1613 {
1614 const spawnRadius = Math.max(0, spawnRange | 0);
1615 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
1616 if (this.spawnRangeHighlight
1617 && this.wanderRangeHighlight
1618 && this.spawnRangeHighlight.tileX === tileX
1619 && this.spawnRangeHighlight.tileY === tileY
1620 && this.spawnRangeHighlight.range === spawnRadius
1621 && this.wanderRangeHighlight.range === wanderRadius)
1622 {
1623 this.#relayoutSpawnRangeHighlight();
1624 return;
1625 }
1626 this.clearSpawnRangeHighlight();
1627 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
1628 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
1629 if (wanderObject)
1630 {
1631 this.#markUnlit(wanderObject);
1632 wanderObject.renderer.alpha = 1;
1633 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1634 }
1635 if (spawnObject)
1636 {
1637 this.#markUnlit(spawnObject);
1638 spawnObject.renderer.alpha = 1;
1639 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1640 }
1641 this.#relayoutSpawnRangeHighlight();
1642 }
1643
1644 clearSpawnRangeHighlight ()
1645 {
1646 this.spawnRangeHighlight?.object?.destroy();
1647 this.wanderRangeHighlight?.object?.destroy();
1648 this.spawnRangeHighlight = null;
1649 this.wanderRangeHighlight = null;
1650 }
1651
1652 setSpellTargetHighlight (tileX, tileY, inRange = true)
1653 {
1654 if (
1655 this.spellTargetHighlight
1656 && this.spellTargetHighlight.tileX === tileX
1657 && this.spellTargetHighlight.tileY === tileY
1658 && this.spellTargetHighlight.inRange === inRange
1659 )
1660 {
1661 this.#relayoutSpellTargetHighlight();
1662 return;
1663 }
1664 this.clearSpellTargetHighlight();
1665 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1666 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1667 if (!object)
1668 { return; }
1669 this.#markUnlit(object);
1670 object.renderer.alpha = 1;
1671 this.spellTargetHighlight = { object, tileX, tileY, inRange, spriteName };
1672 this.#relayoutSpellTargetHighlight();
1673 }
1674
1675 clearSpellTargetHighlight ()
1676 {
1677 this.spellTargetHighlight?.object?.destroy();
1678 this.spellTargetHighlight = null;
1679 }
1680
1681 #relayoutSpellTargetHighlight ()
1682 {
1683 const highlight = this.spellTargetHighlight;
1684 if (!highlight?.object)
1685 { return; }
1686 const size = this.tileSize();
1687 const left = highlight.tileX * size;
1688 const top = highlight.tileY * size;
1689 highlight.object.transform.position.x = left + size / 2;
1690 highlight.object.transform.position.y = top + size / 2;
1691 highlight.object.transform.size = new vector(size, size);
1692 highlight.object.layer = LAYER_EDGE - 1;
1693 this.#markSortDirty();
1694 }
1695
1696 #relayoutSpawnRangeHighlight ()
1697 {
1698 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
1699 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
1700 }
1701
1702 #layoutRangeOverlay (highlight, layer)
1703 {
1704 if (!highlight?.object)
1705 { return; }
1706 const size = this.tileSize();
1707 const side = (2 * highlight.range + 1) * size;
1708 const left = (highlight.tileX - highlight.range) * size;
1709 const top = (highlight.tileY - highlight.range) * size;
1710 highlight.object.transform.position.x = left + side / 2;
1711 highlight.object.transform.position.y = top + side / 2;
1712 highlight.object.transform.size = new vector(side, side);
1713 highlight.object.layer = layer;
1714 this.#markSortDirty();
1715 }
1716
1717 setTilePreview (tileX, tileY, override)
1718 {
1719 const next = { tileX, tileY, ...override };
1720 if (this.#previewEqual(this.preview, next))
1721 { return; }
1722 const previous = this.preview;
1723 this.preview = next;
1724 const chunkX = Math.floor(tileX / CHUNK_SIZE);
1725 const chunkY = Math.floor(tileY / CHUNK_SIZE);
1726 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
1727 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
1728 {
1729 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
1730 if (prevKey !== `${chunkX},${chunkY}`)
1731 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
1732 }
1733 }
1734
1735 clearTilePreview ()
1736 {
1737 if (!this.preview)
1738 { return; }
1739 const previous = this.preview;
1740 this.preview = null;
1741 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
1742 this.#scheduleChunkRebuild(snapshot);
1743 }
1744
1745 #lerpMs (gait)
1746 {
1747 const walk = this.settings.walkTilesPerSecond || 2;
1748 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
1749 return seconds * 1000;
1750 }
1751
1752 #centerCamera ()
1753 {
1754 if (!this.followPlayer)
1755 { return; }
1756 const local = this.entities.get(this.localEntityId);
1757 if (!local)
1758 { return; }
1759 const x = local.visualX + (local.stackOffsetX ?? 0);
1760 const y = local.visualY + (local.stackOffsetY ?? 0);
1761 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
1762 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
1763 }
1764
1765 /**
1766 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
1767 * Tiles fully outside this rect are not drawn.
1768 */
1769 #drawBounds ()
1770 {
1771 const pad = this.tileSize() * 0.5;
1772 const camX = this.scene.cameraPosition.x;
1773 const camY = this.scene.cameraPosition.y;
1774 const w = this.scene.real_size.x;
1775 const h = this.scene.real_size.y;
1776 return {
1777 left: -camX - pad,
1778 right: -camX + w + pad,
1779 top: -camY - pad,
1780 bottom: -camY + h + pad
1781 };
1782 }
1783
1784 #rectIntersects (left, top, right, bottom, bounds)
1785 {
1786 return right >= bounds.left
1787 && left <= bounds.right
1788 && bottom >= bounds.top
1789 && top <= bounds.bottom;
1790 }
1791
1792 #setRendererVisible (object, visible)
1793 {
1794 if (object?.renderer)
1795 { object.renderer.visible = !!visible; }
1796 }
1797
1798 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
1799 #cullOffscreenDrawables ()
1800 {
1801 const bounds = this.#drawBounds();
1802 const size = this.tileSize();
1803
1804 for (const baked of this.bakedChunks.values())
1805 {
1806 const left = baked.chunkX * CHUNK_SIZE * size;
1807 const top = baked.chunkY * CHUNK_SIZE * size;
1808 const chunkPx = CHUNK_SIZE * size;
1809 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
1810 this.#setRendererVisible(baked.groundObject, chunkVisible);
1811 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
1812 baked._inViewport = chunkVisible;
1813 for (let row = 0; row < CHUNK_SIZE; row++)
1814 {
1815 const rowTop = top + row * size;
1816 const rowVisible = chunkVisible && this.#rectIntersects(
1817 left, rowTop, left + chunkPx, rowTop + size, bounds
1818 );
1819 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
1820 }
1821 }
1822
1823 for (const objects of this.tiles.values())
1824 {
1825 const left = objects.tileX * size;
1826 const top = objects.tileY * size;
1827 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
1828 objects._inViewport = visible;
1829 this.#setRendererVisible(objects.ground, visible);
1830 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
1831 this.#setRendererVisible(objects.block, visible);
1832 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
1833 if (objects.waterEdges)
1834 {
1835 for (const edge of Object.values(objects.waterEdges))
1836 { this.#setRendererVisible(edge, visible); }
1837 }
1838 }
1839 }
1840
1841 #upsertEntity (payload)
1842 {
1843 const size = this.tileSize();
1844 const pivot = tilePivot(payload.tileX, payload.tileY, size);
1845 let entity = this.entities.get(payload.entityId);
1846 if (!entity)
1847 {
1848 const spriteName = payload.layers?.[0]?.sprite
1849 ?? payload.sprite
1850 ?? bodySpriteName(payload.sex);
1851 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
1852 this.scene.addObject(object);
1853 this.#startIdleAnimation(object);
1854 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
1855 this.entities.set(payload.entityId, entity);
1856 }
1857 entity.entityId = payload.entityId;
1858 entity.tileX = payload.tileX;
1859 entity.tileY = payload.tileY;
1860 entity.gait = payload.gait;
1861 entity.sex = payload.sex ?? entity.sex;
1862 entity.characterId = payload.characterId ?? entity.characterId ?? null;
1863 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
1864 if (payload.level != null)
1865 { entity.level = payload.level | 0; }
1866 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
1867 entity.canFight = payload.canFight != null
1868 ? !!payload.canFight
1869 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
1870 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
1871 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
1872 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
1873 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
1874 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
1875 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
1876 if (payload.visualScale != null)
1877 { entity.visualScale = Number(payload.visualScale) || 1; }
1878 else if (entity.visualScale == null)
1879 { entity.visualScale = 1; }
1880 if (payload.health != null)
1881 { entity.health = payload.health; }
1882 if (payload.maxHealth != null)
1883 { entity.maxHealth = payload.maxHealth; }
1884 if (payload.firstName)
1885 { entity.firstName = payload.firstName; }
1886 if (payload.lastName)
1887 { entity.lastName = payload.lastName; }
1888 entity.firstName = entity.firstName ?? "";
1889 entity.lastName = entity.lastName ?? "";
1890 if (payload.worldX != null && payload.worldY != null)
1891 {
1892 entity.worldX = payload.worldX;
1893 entity.worldY = payload.worldY;
1894 entity.visualX = payload.worldX * size;
1895 entity.visualY = payload.worldY * size;
1896 entity.targetX = entity.visualX;
1897 entity.targetY = entity.visualY;
1898 }
1899 else
1900 {
1901 entity.visualX = pivot.x;
1902 entity.visualY = pivot.y;
1903 entity.targetX = pivot.x;
1904 entity.targetY = pivot.y;
1905 }
1906 entity.fromX = entity.visualX;
1907 entity.fromY = entity.visualY;
1908 if (payload.layers)
1909 { this.#applyLayers(entity, payload.layers); }
1910 this.#syncHpBar(entity);
1911 this.#placeEntity(entity, performance.now());
1912 }
1913
1914 #applyLayers (entity, layers)
1915 {
1916 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
1917 this.#rebuildOverlays(entity);
1918 }
1919
1920 #setGatherToolOverlay (entity, toolItemId)
1921 {
1922 entity.gatherToolItemId = toolItemId;
1923 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
1924 this.#rebuildOverlays(entity);
1925 this.#placeEntity(entity, performance.now());
1926 }
1927
1928 #expireGatherToolOverlay (entity, now)
1929 {
1930 if (entity.gatherToolItemId == null)
1931 { return; }
1932 if ((entity.gatherToolUntil ?? 0) > now)
1933 { return; }
1934 entity.gatherToolItemId = null;
1935 entity.gatherToolUntil = 0;
1936 this.#rebuildOverlays(entity);
1937 }
1938
1939 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
1940 #layersForDisplay (entity)
1941 {
1942 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
1943 const toolId = entity.gatherToolItemId;
1944 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
1945 { return layers; }
1946 const equip = itemEquipSprite(toolId);
1947 if (!equip || !this.game.images[equip])
1948 { return layers; }
1949 const replacement = {
1950 sprite: equip,
1951 itemId: toolId,
1952 tint: resolveEquipTint(toolId)
1953 };
1954 for (let index = layers.length - 1; index >= 1; index--)
1955 {
1956 const def = itemDefinition(layers[index].itemId);
1957 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
1958 {
1959 layers[index] = replacement;
1960 return layers;
1961 }
1962 }
1963 layers.push(replacement);
1964 return layers;
1965 }
1966
1967 #rebuildOverlays (entity)
1968 {
1969 const layers = this.#layersForDisplay(entity);
1970 const base = layers[0]?.sprite
1971 ?? bodySpriteName(entity.sex);
1972 if (this.game.images[base])
1973 {
1974 entity.object.renderer.sprite = this.game.images[base];
1975 this.#startIdleAnimation(entity.object);
1976 }
1977 for (const overlay of entity.overlays ?? [])
1978 { overlay.destroy(); }
1979 for (const overlay of entity.bloomOverlays ?? [])
1980 { overlay.destroy(); }
1981 entity.overlays = [];
1982 entity.overlayTints = [];
1983 entity.overlayDualTints = [];
1984 entity.overlayTightFit = [];
1985 entity.bloomOverlays = [];
1986 for (const layer of layers.slice(1))
1987 {
1988 const image = this.game.images[layer.sprite];
1989 if (!image)
1990 { continue; }
1991 const object = new GameObject(0, 0, image, SORT_ENTITY);
1992 this.scene.addObject(object);
1993 entity.overlays.push(object);
1994 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1995 entity.overlayTightFit.push(!!layerDef?.tightFit);
1996 const dualTint = layer.itemId != null
1997 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
1998 : null;
1999 entity.overlayDualTints.push(dualTint);
2000 entity.overlayTints.push(
2001 dualTint
2002 ? null
2003 : (layer.tint
2004 ? normalizeRgb(layer.tint)
2005 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2006 );
2007 const bloomName = bloomCompanionName(layer.sprite);
2008 const bloomImage = this.game.images[bloomName];
2009 if (!bloomImage)
2010 { continue; }
2011 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2012 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2013 this.#markUnlit(bloom);
2014 this.scene.addObject(bloom);
2015 entity.bloomOverlays.push(bloom);
2016 }
2017 }
2018
2019 #placeEntity (entity, now = performance.now())
2020 {
2021 const zoom = this.zoom;
2022 const offsetX = entity.shoveOffsetX ?? 0;
2023 const offsetY = entity.shoveOffsetY ?? 0;
2024 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2025 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2026 let walkTilt = 0;
2027 if (entity.lerpStarted != null)
2028 {
2029 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2030 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2031 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2032 walkTilt = Math.sin(cycles) * tilt;
2033 }
2034 const flashStrength = (entity.damageFlashUntil ?? 0) > now
2035 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2036 : 0;
2037 const tileShade = this.#entityShadeAlpha(entity, now);
2038 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2039
2040 entity.object.transform.rotation = walkTilt;
2041 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade);
2042 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
2043 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2044 {
2045 const overlay = entity.overlays[index];
2046 const overlaySortY = pivotY + 0.5 * (index + 1);
2047 overlay.transform.rotation = walkTilt;
2048 const dualTint = entity.overlayDualTints?.[index] ?? null;
2049 if (dualTint)
2050 {
2051 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade);
2052 }
2053 else if (entity.overlayTightFit?.[index])
2054 {
2055 this.#syncTightFitLitSprite(
2056 overlay,
2057 entity,
2058 tileShade,
2059 flashStrength,
2060 wade,
2061 entity.overlayTints?.[index] ?? null
2062 );
2063 }
2064 else
2065 {
2066 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null);
2067 }
2068 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
2069 }
2070 for (const overlay of entity.bloomOverlays ?? [])
2071 {
2072 this.#setRendererVisible(overlay, this.bloomEnabled);
2073 if (!this.bloomEnabled)
2074 { continue; }
2075 overlay.transform.rotation = walkTilt;
2076 this.#syncLitSprite(overlay, tileShade, flashStrength, wade);
2077 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2078 }
2079 this.#placeHpBar(entity, pivotX, pivotY);
2080 }
2081
2082 #markUnlit (object)
2083 {
2084 if (!object?.renderer)
2085 { return; }
2086 object._lit = false;
2087 object.renderer.shader = null;
2088 object.renderer.shaderUniforms = null;
2089 object.renderer.secondaryMap = null;
2090 }
2091
2092 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null)
2093 {
2094 if (!object?.renderer || object._lit === false)
2095 { return; }
2096 object._lit = true;
2097 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2098 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2099 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2100 const tint = tintColor ? normalizeRgb(tintColor) : null;
2101 if (tint)
2102 {
2103 object.renderer.shader = getTintLitSpriteShader();
2104 object.renderer.shaderUniforms = {
2105 u_darkness: dark,
2106 u_strength: flash,
2107 u_wade: wade ? 1 : 0,
2108 u_spriteHeight: height,
2109 u_useTint: 1,
2110 u_tintColor: [tint.r, tint.g, tint.b]
2111 };
2112 }
2113 else
2114 {
2115 object.renderer.shader = getSpriteLightingShader();
2116 object.renderer.shaderUniforms = {
2117 u_darkness: dark,
2118 u_strength: flash,
2119 u_wade: wade ? 1 : 0,
2120 u_spriteHeight: height
2121 };
2122 }
2123 object.renderer.secondaryMap = null;
2124 }
2125
2126 #bodySecondaryMap (entity)
2127 {
2128 return entity?.object?.renderer?.sprite?.g_image ?? null;
2129 }
2130
2131 #tightFitMaskUniforms (overlay, entity)
2132 {
2133 const bodyRenderer = entity?.object?.renderer;
2134 const clothRenderer = overlay?.renderer;
2135 const bodySprite = bodyRenderer?.sprite;
2136 const clothSprite = clothRenderer?.sprite;
2137 if (!bodySprite || !clothSprite)
2138 { return null; }
2139 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2140 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2141 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2142 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2143 return {
2144 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2145 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2146 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2147 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2148 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2149 };
2150 }
2151
2152 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null)
2153 {
2154 if (!overlay?.renderer || entity?.object?.renderer == null)
2155 { return; }
2156 const bodyMap = this.#bodySecondaryMap(entity);
2157 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2158 if (!bodyMap || !maskUniforms)
2159 {
2160 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor);
2161 return;
2162 }
2163 overlay._lit = true;
2164 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2165 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2166 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2167 const tint = tintColor ? normalizeRgb(tintColor) : null;
2168 overlay.renderer.secondaryMap = bodyMap;
2169 if (tint)
2170 {
2171 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2172 overlay.renderer.shaderUniforms = {
2173 u_darkness: dark,
2174 u_strength: flash,
2175 u_wade: wade ? 1 : 0,
2176 u_spriteHeight: height,
2177 u_useTint: 1,
2178 u_tintColor: [tint.r, tint.g, tint.b],
2179 ...maskUniforms
2180 };
2181 }
2182 else
2183 {
2184 overlay.renderer.shader = getTightFitLitSpriteShader();
2185 overlay.renderer.shaderUniforms = {
2186 u_darkness: dark,
2187 u_strength: flash,
2188 u_wade: wade ? 1 : 0,
2189 u_spriteHeight: height,
2190 ...maskUniforms
2191 };
2192 }
2193 }
2194
2195 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false)
2196 {
2197 if (!object?.renderer || object._lit === false || !dualTint)
2198 { return; }
2199 object._lit = true;
2200 const shaft = normalizeRgb(dualTint.shaft);
2201 const tip = normalizeRgb(dualTint.tip);
2202 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2203 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2204 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2205 object.renderer.shader = getDualTintLitSpriteShader();
2206 object.renderer.shaderUniforms = {
2207 u_darkness: dark,
2208 u_strength: flash,
2209 u_wade: wade ? 1 : 0,
2210 u_spriteHeight: height,
2211 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2212 u_tipTint: [tip.r, tip.g, tip.b]
2213 };
2214 object.renderer.secondaryMap = null;
2215 }
2216
2217 #syncGroundItemSprite (item, darkness)
2218 {
2219 if (item?.dualTint)
2220 {
2221 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2222 return;
2223 }
2224 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2225 }
2226
2227 #groundTypeAt (tileX, tileY)
2228 {
2229 const ground = this.#groundAtTile(tileX, tileY);
2230 return ground == null ? null : normalizeGround(ground).typeId;
2231 }
2232
2233 /** Ground entry at a world tile, including editor hover preview when present. */
2234 #groundAtTile (tileX, tileY)
2235 {
2236 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2237 && this.preview.ground !== undefined)
2238 { return this.preview.ground; }
2239 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2240 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2241 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2242 if (!snapshot)
2243 { return null; }
2244 const localX = tileX - chunkX * CHUNK_SIZE;
2245 const localY = tileY - chunkY * CHUNK_SIZE;
2246 const index = localY * CHUNK_SIZE + localX;
2247 return snapshot.grounds?.[index] ?? null;
2248 }
2249
2250 #waterCoastEdges (tileX, tileY)
2251 {
2252 const season = this.worldSeason;
2253 return {
2254 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2255 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2256 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2257 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2258 };
2259 }
2260
2261 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2262 {
2263 if (!object?.renderer)
2264 { return; }
2265 const lit = corners ?? {
2266 nw: fallbackLit,
2267 ne: fallbackLit,
2268 sw: fallbackLit,
2269 se: fallbackLit
2270 };
2271 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2272 object._lit = true;
2273 object.renderer.shader = getWaterGroundShader();
2274 object.renderer.secondaryMap = null;
2275 object.renderer.shaderUniforms = {
2276 u_ambientDark: dark,
2277 u_litNW: lit.nw,
2278 u_litNE: lit.ne,
2279 u_litSW: lit.sw,
2280 u_litSE: lit.se,
2281 u_time: timeSec,
2282 u_edgeN: edges?.n ?? 0,
2283 u_edgeE: edges?.e ?? 0,
2284 u_edgeS: edges?.s ?? 0,
2285 u_edgeW: edges?.w ?? 0
2286 };
2287 }
2288
2289 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2290 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2291 {
2292 if (!objects?.ground)
2293 { return; }
2294 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2295 {
2296 objects.waterEdges = null;
2297 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2298 return;
2299 }
2300 const fallbackLit = ambientDark > 0
2301 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
2302 : 1;
2303 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2304 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2305 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2306 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2307 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2308 let litCorners = null;
2309 if (chunkBaked)
2310 {
2311 if (this.lightingMode === "simple")
2312 {
2313 const gridW = CHUNK_SIZE + 2;
2314 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2315 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2316 }
2317 else
2318 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2319 }
2320 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2321 this.#syncWaterGroundSprite(
2322 objects.ground,
2323 litCorners,
2324 ambientDark,
2325 objects.waterEdges,
2326 timeSec,
2327 fallbackLit
2328 );
2329 }
2330
2331 #ambientDarkness ()
2332 {
2333 const hour = this.nightPreview ?? this.worldHour;
2334 const calendar = nightFactor(hour, this.settings.nightDarkness);
2335 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2336 if (dark == null)
2337 { dark = calendar; }
2338 if (this.localBlind)
2339 { dark = Math.min(1, dark + 0.85); }
2340 return dark;
2341 }
2342
2343 setLocalBlind (blind)
2344 {
2345 this.localBlind = !!blind;
2346 }
2347
2348 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2349 #blindVisionLight ()
2350 {
2351 if (!this.localBlind)
2352 { return null; }
2353 const local = this.entities.get(this.localEntityId);
2354 if (!local)
2355 { return null; }
2356 const tileSize = this.tileSize();
2357 return {
2358 tileX: Math.floor(local.visualX / tileSize),
2359 tileY: Math.floor(local.visualY / tileSize),
2360 range: 2.25,
2361 intensity: 1
2362 };
2363 }
2364
2365 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2366 {
2367 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2368 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2369 const dark = (fromAlpha + toAlpha) / 2;
2370 if (dualTint)
2371 {
2372 this.#syncDualTintLitSprite(object, dark, dualTint);
2373 return;
2374 }
2375 this.#syncLitSprite(object, dark);
2376 }
2377
2378 #dualTintFromPayload (payload)
2379 {
2380 if (!payload?.shaftTint || !payload?.tipTint)
2381 { return null; }
2382 return { shaft: payload.shaftTint, tip: payload.tipTint };
2383 }
2384
2385 #syncHpBar (entity)
2386 {
2387 const current = entity.health;
2388 const max = entity.maxHealth;
2389 const show = current != null
2390 && max != null
2391 && max > 0
2392 && current < max;
2393 if (!show)
2394 {
2395 entity.hpBar?.destroy();
2396 entity.hpBar = null;
2397 entity.hpBarCanvas = null;
2398 return;
2399 }
2400 if (!entity.hpBarCanvas)
2401 {
2402 entity.hpBarCanvas = document.createElement("canvas");
2403 entity.hpBarCanvas.width = HP_BAR_W;
2404 entity.hpBarCanvas.height = HP_BAR_H;
2405 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2406 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2407 this.#markUnlit(entity.hpBar);
2408 this.scene.addObject(entity.hpBar);
2409 }
2410 drawHpBar(entity.hpBarCanvas, current, max);
2411 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
2412 }
2413
2414 #placeHpBar (entity, pivotX, pivotY)
2415 {
2416 if (!entity.hpBar)
2417 { return; }
2418 const sprite = entity.object?.renderer?.sprite;
2419 if (!sprite)
2420 { return; }
2421 const zoom = this.zoom;
2422 const drawH = sprite.height * zoom;
2423 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
2424 const spriteTop = centerY - drawH / 2;
2425 const barW = HP_BAR_W * zoom;
2426 const barH = HP_BAR_H * zoom;
2427 entity.hpBar.transform.position.x = pivotX;
2428 entity.hpBar.transform.position.y = spriteTop - barH / 2;
2429 entity.hpBar.transform.size = new vector(barW, barH);
2430 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
2431 this.#markSortDirty();
2432 }
2433
2434 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2435 {
2436 this.#bakeAndPlaceChunk(snapshot);
2437 this.#relayoutChunkTiles(snapshot);
2438 if (this.softTerrain && refreshSoftNeighbors)
2439 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2440 }
2441
2442 #relayoutChunk (snapshot)
2443 {
2444 this.#layoutBakedChunk(snapshot);
2445 this.#relayoutChunkTiles(snapshot);
2446 }
2447
2448 #relayoutChunkTiles (snapshot)
2449 {
2450 const baked = this.bakedChunks.get(`${snapshot.chunkX},${snapshot.chunkY}`);
2451 const tall = new Set(
2452 (baked?.tallBlocks ?? []).map((entry) => `${entry.tileX},${entry.tileY}`)
2453 );
2454 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2455 {
2456 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2457 {
2458 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
2459 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
2460 this.#drawTile(tileX, tileY, tall.has(`${tileX},${tileY}`));
2461 }
2462 }
2463 }
2464
2465 #scheduleChunkRebuild (snapshot)
2466 {
2467 if (!snapshot)
2468 { return; }
2469 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2470 this.#ensureChunkFlushScheduled();
2471 }
2472
2473 #scheduleEdgeRebuild ()
2474 {
2475 this.#edgesDirty = true;
2476 this.#ensureChunkFlushScheduled();
2477 }
2478
2479 #ensureChunkFlushScheduled ()
2480 {
2481 if (this.#chunkRebuildRaf)
2482 { return; }
2483 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
2484 }
2485
2486 #flushChunkWork ()
2487 {
2488 this.#chunkRebuildRaf = 0;
2489 const keys = [...this.#chunkRebuildKeys];
2490 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
2491 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
2492 this.#chunkRebuildKeys.clear();
2493 for (const key of rest)
2494 { this.#chunkRebuildKeys.add(key); }
2495 for (const key of batch)
2496 {
2497 const snap = this.chunks.get(key);
2498 if (snap)
2499 { this.#rebuildChunk(snap); }
2500 }
2501 if (this.#chunkRebuildKeys.size)
2502 {
2503 this.#ensureChunkFlushScheduled();
2504 return;
2505 }
2506 if (this.#edgesDirty)
2507 {
2508 this.#rebuildAllEdges();
2509 this.#edgesDirty = false;
2510 }
2511 }
2512
2513 #previewEqual (a, b)
2514 {
2515 if (a === b)
2516 { return true; }
2517 if (!a || !b)
2518 { return false; }
2519 return a.tileX === b.tileX
2520 && a.tileY === b.tileY
2521 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
2522 && this.#previewPart(a.block) === this.#previewPart(b.block);
2523 }
2524
2525 #previewPart (value)
2526 {
2527 return value === undefined ? undefined : JSON.stringify(value);
2528 }
2529
2530 #rebuildSoftTerrainNeighborChunks (snapshot)
2531 {
2532 for (let dy = -1; dy <= 1; dy++)
2533 {
2534 for (let dx = -1; dx <= 1; dx++)
2535 {
2536 if (dx === 0 && dy === 0)
2537 { continue; }
2538 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2539 if (neighbor)
2540 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
2541 }
2542 }
2543 }
2544
2545 #rebakeAllChunks ()
2546 {
2547 for (const snapshot of this.chunks.values())
2548 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
2549 }
2550
2551 #bakeAndPlaceChunk (snapshot)
2552 {
2553 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2554 const atlases = bakeChunkAtlases({
2555 snapshot,
2556 catalog: this.catalog,
2557 images: this.game.images,
2558 preview: this.preview,
2559 season: this.worldSeason,
2560 softTerrain: this.softTerrain,
2561 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY)
2562 });
2563 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
2564 let baked = this.bakedChunks.get(key);
2565 if (!baked)
2566 {
2567 const lightmapCanvas = makeLightmapCanvas(atlasPx);
2568 baked = {
2569 groundCanvas: atlases.ground,
2570 blockCanvases: atlases.blockRows,
2571 bloomCanvas: atlases.bloom,
2572 lightmapCanvas,
2573 groundImage: frameworkImageFromCanvas(atlases.ground),
2574 blockImages: atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas)),
2575 bloomImage: frameworkImageFromCanvas(atlases.bloom),
2576 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
2577 groundObject: null,
2578 blockObjects: [],
2579 bloomObject: null,
2580 tallBlocks: atlases.tallBlocks,
2581 animatedGrounds: atlases.animatedGrounds,
2582 lightmapPixels: null
2583 };
2584 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
2585 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
2586 this.scene.addObject(baked.groundObject);
2587 for (let row = 0; row < CHUNK_SIZE; row++)
2588 {
2589 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
2590 this.#applyAtlasLighting(object, baked.lightmapImage, row);
2591 this.scene.addObject(object);
2592 baked.blockObjects.push(object);
2593 }
2594 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
2595 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2596 this.#markUnlit(baked.bloomObject);
2597 this.scene.addObject(baked.bloomObject);
2598 this.bakedChunks.set(key, baked);
2599 }
2600 else
2601 {
2602 copyCanvas(atlases.ground, baked.groundCanvas);
2603 for (let row = 0; row < CHUNK_SIZE; row++)
2604 { copyCanvas(atlases.blockRows[row], baked.blockCanvases[row]); }
2605 copyCanvas(atlases.bloom, baked.bloomCanvas);
2606 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2607 for (const canvas of baked.blockCanvases)
2608 { invalidateCanvasTexture(this.scene, canvas); }
2609 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2610 baked.tallBlocks = atlases.tallBlocks;
2611 baked.animatedGrounds = atlases.animatedGrounds;
2612 }
2613 baked.chunkX = snapshot.chunkX;
2614 baked.chunkY = snapshot.chunkY;
2615 baked.lightmapCacheKey = null;
2616 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
2617 this.#layoutBakedChunk(snapshot);
2618 this.#queueBakedChunkTextures(baked);
2619 }
2620
2621 #queueBakedChunkTextures (baked)
2622 {
2623 if (!baked)
2624 { return; }
2625 const canvases = [
2626 baked.groundCanvas,
2627 ...(baked.blockCanvases ?? []),
2628 baked.bloomCanvas,
2629 baked.lightmapCanvas
2630 ];
2631 for (const canvas of canvases)
2632 {
2633 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
2634 { continue; }
2635 this.#pendingTextureCanvasSet.add(canvas);
2636 this.#pendingTextureCanvases.push(canvas);
2637 }
2638 this.#scheduleTextureWarm();
2639 }
2640
2641 #scheduleTextureWarm ()
2642 {
2643 if (this.#textureWarmRaf)
2644 { return; }
2645 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
2646 }
2647
2648 #flushTextureWarm ()
2649 {
2650 this.#textureWarmRaf = 0;
2651 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
2652 for (const canvas of batch)
2653 {
2654 this.#pendingTextureCanvasSet.delete(canvas);
2655 setNearestFilter(this.scene, canvas);
2656 }
2657 if (this.#pendingTextureCanvases.length)
2658 { this.#scheduleTextureWarm(); }
2659 }
2660
2661 #applyAtlasLighting (object, lightmapImage, lightRow)
2662 {
2663 if (!object?.renderer)
2664 { return; }
2665 object._lit = true;
2666 object.renderer.shader = getAtlasLightingShader();
2667 object.renderer.secondaryMap = lightmapImage;
2668 object.renderer.shaderUniforms = {
2669 u_ambientDark: 0,
2670 u_lightRow: lightRow
2671 };
2672 }
2673
2674 #layoutBakedChunk (snapshot)
2675 {
2676 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2677 const baked = this.bakedChunks.get(key);
2678 if (!baked)
2679 { return; }
2680 const size = this.tileSize();
2681 const left = snapshot.chunkX * CHUNK_SIZE * size;
2682 const top = snapshot.chunkY * CHUNK_SIZE * size;
2683 const chunkPx = CHUNK_SIZE * size;
2684 baked.groundObject.transform.position.x = left + chunkPx / 2;
2685 baked.groundObject.transform.position.y = top + chunkPx / 2;
2686 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
2687 baked.groundObject.layer = LAYER_GROUND;
2688
2689 for (let row = 0; row < CHUNK_SIZE; row++)
2690 {
2691 const object = baked.blockObjects[row];
2692 const rowY = top + row * size + size / 2;
2693 object.transform.position.x = left + chunkPx / 2;
2694 object.transform.position.y = rowY;
2695 object.transform.size = new vector(chunkPx, size);
2696 object.layer = ySortLayer(rowY, SORT_BLOCK);
2697 }
2698
2699 baked.bloomObject.transform.position.x = left + chunkPx / 2;
2700 baked.bloomObject.transform.position.y = top + chunkPx / 2;
2701 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
2702 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
2703 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
2704 this.#markSortDirty();
2705 }
2706
2707 #destroyBakedChunk (key)
2708 {
2709 const baked = this.bakedChunks.get(key);
2710 if (!baked)
2711 { return; }
2712 baked.groundObject?.destroy();
2713 for (const object of baked.blockObjects ?? [])
2714 { object.destroy(); }
2715 baked.bloomObject?.destroy();
2716 invalidateCanvasTexture(this.scene, baked.groundCanvas);
2717 for (const canvas of baked.blockCanvases ?? [])
2718 { invalidateCanvasTexture(this.scene, canvas); }
2719 invalidateCanvasTexture(this.scene, baked.bloomCanvas);
2720 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
2721 this.bakedChunks.delete(key);
2722 }
2723
2724 #redrawPreview ()
2725 {
2726 if (!this.preview)
2727 { return; }
2728 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
2729 if (snapshot)
2730 { this.#rebuildChunk(snapshot); }
2731 }
2732
2733 #refreshWaterCoastsNear (chunkX, chunkY)
2734 {
2735 const timeSec = performance.now() / 1000;
2736 for (const objects of this.tiles.values())
2737 {
2738 if (!objects.ground || !isWaterGround(objects.groundTypeId))
2739 { continue; }
2740 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
2741 { continue; }
2742 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
2743 }
2744 }
2745
2746 #drawTile (tileX, tileY, forceTall = null)
2747 {
2748 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2749 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2750 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2751 if (!snapshot)
2752 { return; }
2753 const localX = tileX - chunkX * CHUNK_SIZE;
2754 const localY = tileY - chunkY * CHUNK_SIZE;
2755 const index = localY * CHUNK_SIZE + localX;
2756 const key = `${tileX},${tileY}`;
2757 let objects = this.tiles.get(key);
2758 if (!objects)
2759 {
2760 objects = { chunkX, chunkY, tileX, tileY };
2761 this.tiles.set(key, objects);
2762 }
2763 objects.tileX = tileX;
2764 objects.tileY = tileY;
2765 objects.chunkX = chunkX;
2766 objects.chunkY = chunkY;
2767 objects.light = snapshot.light[index] ?? 0;
2768
2769 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
2770 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2771 if (animatedGround)
2772 {
2773 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
2774 if (objects.ground)
2775 {
2776 const size = this.tileSize();
2777 objects.ground.transform.position.x = tileX * size + size / 2;
2778 objects.ground.transform.position.y = tileY * size + size / 2;
2779 objects.ground.transform.size = new vector(size, size);
2780 objects.ground.layer = LAYER_GROUND;
2781 objects.groundTypeId = animatedGround.typeId;
2782 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
2783 this.#markSortDirty();
2784 }
2785 if (animatedGround.bloom)
2786 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
2787 else
2788 {
2789 objects.groundBloom?.destroy();
2790 objects.groundBloom = null;
2791 }
2792 }
2793 else
2794 {
2795 objects.ground?.destroy();
2796 objects.ground = null;
2797 objects.groundBloom?.destroy();
2798 objects.groundBloom = null;
2799 objects.groundTypeId = null;
2800 objects.waterEdges = null;
2801 }
2802
2803 const tallEntry = (baked?.tallBlocks ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
2804 const isTall = forceTall === true || !!tallEntry;
2805 if (isTall && tallEntry)
2806 {
2807 const pivot = tilePivot(tileX, tileY, this.tileSize());
2808 objects.block = this.#ensureSprite(objects.block, tallEntry.sprite, SORT_ENTITY);
2809 if (objects.block)
2810 {
2811 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
2812 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
2813 }
2814 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tallEntry.bloom, pivot, SORT_ENTITY);
2815 }
2816 else
2817 {
2818 objects.block?.destroy();
2819 objects.block = null;
2820 objects.blockBloom?.destroy();
2821 objects.blockBloom = null;
2822 }
2823 }
2824
2825 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
2826 {
2827 if (!name)
2828 {
2829 existing?.destroy();
2830 return null;
2831 }
2832 const object = this.#ensureSprite(existing, name, sortOrder);
2833 if (!object)
2834 { return null; }
2835 object.renderer.layer = RENDER_LAYER_BLOOM;
2836 this.#markUnlit(object);
2837 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
2838 return object;
2839 }
2840
2841 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
2842 {
2843 const sprite = object?.renderer?.sprite;
2844 if (!sprite)
2845 { return; }
2846 const zoom = this.zoom;
2847 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
2848 const factor = Math.max(0.1, Number(scale) || 1);
2849 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
2850 object.transform.position.x = center.x;
2851 object.transform.position.y = center.y;
2852 object.transform.size = new vector(draw.w * factor, draw.h * factor);
2853 object.layer = ySortLayer(sortY, subOrder);
2854 this.#markSortDirty();
2855 }
2856
2857 #ensureSprite (existing, name, layer)
2858 {
2859 const sprite = this.game.images[name];
2860 if (!sprite)
2861 {
2862 existing?.destroy();
2863 return null;
2864 }
2865 if (!existing || existing.renderer.sprite !== sprite)
2866 {
2867 existing?.destroy();
2868 existing = new GameObject(0, 0, sprite, layer);
2869 this.#syncLitSprite(existing, 0);
2870 this.scene.addObject(existing);
2871 this.#startIdleAnimation(existing);
2872 }
2873 return existing;
2874 }
2875
2876 #startIdleAnimation (object)
2877 {
2878 const sprite = object?.renderer?.sprite;
2879 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
2880 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
2881 }
2882
2883 #neighborClosed (snapshot, dir, dx, dy)
2884 {
2885 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
2886 if (other)
2887 { return !other.open; }
2888 return !!snapshot.closedEdges?.[dir];
2889 }
2890
2891 #rebuildAllEdges ()
2892 {
2893 const seen = new Set();
2894 for (const snapshot of this.chunks.values())
2895 {
2896 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2897 seen.add(key);
2898 this.#rebuildChunkEdges(snapshot);
2899 }
2900 for (const key of [...this.edges.keys()])
2901 {
2902 if (!seen.has(key))
2903 { this.#destroyEdges(key); }
2904 }
2905 }
2906
2907 #rebuildChunkEdges (snapshot)
2908 {
2909 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
2910 let bars = this.edges.get(key);
2911 if (!bars)
2912 {
2913 bars = {};
2914 this.edges.set(key, bars);
2915 }
2916
2917 const size = this.tileSize();
2918 const chunkPx = CHUNK_SIZE * size;
2919 const left = snapshot.chunkX * CHUNK_SIZE * size;
2920 const top = snapshot.chunkY * CHUNK_SIZE * size;
2921 const centerX = left + chunkPx / 2;
2922 const centerY = top + chunkPx / 2;
2923 const thickness = Math.max(2, Math.round(2 * this.zoom));
2924 const draw = snapshot.open === true;
2925
2926 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
2927 centerX, top, chunkPx, thickness, true);
2928 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
2929 centerX, top + chunkPx, chunkPx, thickness, true);
2930 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
2931 left, centerY, chunkPx, thickness, false);
2932 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
2933 left + chunkPx, centerY, chunkPx, thickness, false);
2934 }
2935
2936 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
2937 {
2938 if (!visible)
2939 {
2940 if (existing)
2941 { existing.renderer.visible = false; }
2942 return existing;
2943 }
2944
2945 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
2946 this.#markUnlit(existing);
2947 existing.renderer.visible = true;
2948 existing.transform.position.x = x;
2949 existing.transform.position.y = y;
2950 existing.transform.size = horizontal
2951 ? new vector(length, thickness)
2952 : new vector(thickness, length);
2953 existing.layer = LAYER_EDGE;
2954 this.#markSortDirty();
2955 return existing;
2956 }
2957
2958 #destroyEdges (key)
2959 {
2960 const bars = this.edges.get(key);
2961 if (!bars)
2962 { return; }
2963 bars.north?.destroy();
2964 bars.east?.destroy();
2965 bars.south?.destroy();
2966 bars.west?.destroy();
2967 this.edges.delete(key);
2968 }
2969
2970 #entityShadeAlpha (entity, now)
2971 {
2972 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
2973 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
2974 { return toAlpha; }
2975 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
2976 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
2977 return fromAlpha + (toAlpha - fromAlpha) * t;
2978 }
2979
2980 #markSortDirty ()
2981 {
2982 this.scene._sortDirty = true;
2983 }
2984
2985 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
2986 #activeLightingCenterChunk ()
2987 {
2988 const local = this.entities.get(this.localEntityId);
2989 if (!local)
2990 { return null; }
2991 return {
2992 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
2993 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
2994 };
2995 }
2996
2997 #isActiveLightingChunk (chunkX, chunkY)
2998 {
2999 const center = this.#activeLightingCenterChunk();
3000 if (!center)
3001 { return true; }
3002 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
3003 }
3004
3005 #isActiveLightingTile (tileX, tileY)
3006 {
3007 return this.#isActiveLightingChunk(
3008 Math.floor(tileX / CHUNK_SIZE),
3009 Math.floor(tileY / CHUNK_SIZE)
3010 );
3011 }
3012
3013 #updateShade ()
3014 {
3015 const ambientDark = this.#ambientDarkness();
3016 const now = performance.now();
3017 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3018
3019 const activeLights = [...this.dynamicLights];
3020 const tileSize = this.tileSize();
3021 const blindLight = this.#blindVisionLight();
3022 if (blindLight)
3023 { activeLights.push(blindLight); }
3024 for (const entity of this.entities.values())
3025 {
3026 const range = entity.lightRadiusTiles ?? 0;
3027 if (range <= 0)
3028 { continue; }
3029 activeLights.push({
3030 tileX: Math.floor(entity.visualX / tileSize),
3031 tileY: Math.floor(entity.visualY / tileSize),
3032 range,
3033 intensity: 1
3034 });
3035 }
3036
3037 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
3038
3039 for (const objects of this.tiles.values())
3040 {
3041 if (objects._inViewport === false)
3042 { continue; }
3043 const lights = this.#isActiveLightingTile(objects.tileX, objects.tileY) ? activeLights : [];
3044 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3045 objects.shadeAlpha = ambientDark * (1 - intensity);
3046 }
3047
3048 for (const baked of this.bakedChunks.values())
3049 {
3050 if (baked._inViewport === false)
3051 { continue; }
3052 const lights = this.#isActiveLightingChunk(baked.chunkX, baked.chunkY) ? activeLights : [];
3053 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3054 if (baked.groundObject?.renderer?.shaderUniforms)
3055 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3056 for (const object of baked.blockObjects ?? [])
3057 {
3058 if (object?.renderer?.shaderUniforms)
3059 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3060 }
3061 }
3062
3063 const timeSec = now / 1000;
3064 for (const objects of this.tiles.values())
3065 {
3066 if (objects._inViewport === false)
3067 { continue; }
3068 if (objects.block)
3069 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
3070 if (objects.ground && isWaterGround(objects.groundTypeId))
3071 {
3072 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
3073 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
3074 }
3075 else if (objects.ground)
3076 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
3077 }
3078
3079 for (const item of this.groundItems.values())
3080 {
3081 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
3082 this.#syncGroundItemSprite(item, alpha);
3083 }
3084 }
3085
3086 #tileLightIntensity (objects, activeLights, lightOcclusion)
3087 {
3088 const baked = lightIntensity(objects.light ?? 0);
3089 const dynamic = dynamicLightAtTile(
3090 objects.tileX,
3091 objects.tileY,
3092 activeLights,
3093 lightOcclusion
3094 );
3095 return Math.max(baked, dynamic);
3096 }
3097
3098 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
3099 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
3100 {
3101 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
3102 if (tileObjects)
3103 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
3104 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3105 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3106 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3107 if (!snapshot)
3108 { return 0; }
3109 const localX = tileX - chunkX * CHUNK_SIZE;
3110 const localY = tileY - chunkY * CHUNK_SIZE;
3111 const index = localY * CHUNK_SIZE + localX;
3112 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
3113 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
3114 return Math.max(bakedLit, dynamic);
3115 }
3116
3117 /** True when ground or block on this tile occludes light rays (same rules as bake). */
3118 #tileOccludesLight (tileX, tileY)
3119 {
3120 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3121 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3122 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3123 if (!snapshot)
3124 { return false; }
3125 const localX = tileX - chunkX * CHUNK_SIZE;
3126 const localY = tileY - chunkY * CHUNK_SIZE;
3127 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
3128 { return false; }
3129 const index = localY * CHUNK_SIZE + localX;
3130 if (Array.isArray(snapshot.occlusion) && snapshot.occlusion.length > index)
3131 { return (snapshot.occlusion[index] | 0) >= LightOcclusion.solid; }
3132 const ground = normalizeGround(snapshot.grounds?.[index]);
3133 if (!isGroundPassable(ground.typeId))
3134 { return true; }
3135 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
3136 }
3137
3138 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
3139 {
3140 const gridW = CHUNK_SIZE + 2;
3141 const gridSize = gridW * gridW;
3142 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
3143 { baked.lightIntensityGrid = new Float32Array(gridSize); }
3144 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
3145 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
3146 const grid = baked.lightIntensityGrid;
3147 const occlude = baked.lightOccludeGrid;
3148 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
3149 {
3150 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
3151 {
3152 const tileX = baked.chunkX * CHUNK_SIZE + lx;
3153 const tileY = baked.chunkY * CHUNK_SIZE + ly;
3154 const gi = (ly + 1) * gridW + (lx + 1);
3155 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
3156 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
3157 }
3158 }
3159 return { grid, occlude, gridW };
3160 }
3161
3162 #makeLightCornerSampler (grid, occlude, gridW)
3163 {
3164 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
3165 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
3166 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
3167 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
3168 {
3169 const home = sample(homeLx, homeLy);
3170 if (blocks(homeLx, homeLy))
3171 { return home; }
3172 let sum = home;
3173 let count = 1;
3174 sum += openSample(aLx, aLy);
3175 count += 1;
3176 sum += openSample(bLx, bLy);
3177 count += 1;
3178 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
3179 {
3180 sum += openSample(dLx, dLy);
3181 count += 1;
3182 }
3183 return sum / count;
3184 };
3185 return { smoothCorner };
3186 }
3187
3188 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
3189 #tileLitCorners (baked, localX, localY)
3190 {
3191 const grid = baked?.lightIntensityGrid;
3192 const occlude = baked?.lightOccludeGrid;
3193 if (!grid?.length || !occlude?.length)
3194 { return null; }
3195 const gridW = CHUNK_SIZE + 2;
3196 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
3197 return {
3198 nw: smoothCorner(
3199 localX, localY,
3200 localX - 1, localY,
3201 localX, localY - 1,
3202 localX - 1, localY - 1
3203 ),
3204 ne: smoothCorner(
3205 localX, localY,
3206 localX + 1, localY,
3207 localX, localY - 1,
3208 localX + 1, localY - 1
3209 ),
3210 sw: smoothCorner(
3211 localX, localY,
3212 localX - 1, localY,
3213 localX, localY + 1,
3214 localX - 1, localY + 1
3215 ),
3216 se: smoothCorner(
3217 localX, localY,
3218 localX + 1, localY,
3219 localX, localY + 1,
3220 localX + 1, localY + 1
3221 )
3222 };
3223 }
3224
3225 #hashUint8Array (values)
3226 {
3227 let hash = 2166136261;
3228 for (let i = 0; i < values.length; i++)
3229 {
3230 hash ^= values[i];
3231 hash = Math.imul(hash, 16777619);
3232 }
3233 return hash >>> 0;
3234 }
3235
3236 #lightAffectsChunkBounds (light, chunkX, chunkY)
3237 {
3238 const minX = chunkX * CHUNK_SIZE - 1;
3239 const minY = chunkY * CHUNK_SIZE - 1;
3240 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
3241 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
3242 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
3243 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
3244 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
3245 }
3246
3247 #chunkLightmapCacheKey (baked, activeLights)
3248 {
3249 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3250 if (!snapshot?.light)
3251 { return null; }
3252 const bakedHash = this.#hashUint8Array(snapshot.light);
3253 if (!this.#isActiveLightingChunk(baked.chunkX, baked.chunkY))
3254 { return `i:${bakedHash}`; }
3255 const mode = this.lightingMode === "simple" ? "s" : "f";
3256 let lightsKey = "";
3257 for (const light of activeLights)
3258 {
3259 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
3260 { continue; }
3261 lightsKey += `${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
3262 }
3263 return `a:${mode}:${bakedHash}:${lightsKey}`;
3264 }
3265
3266 #invalidateNeighborLightmapCaches (chunkX, chunkY)
3267 {
3268 for (let dy = -1; dy <= 1; dy++)
3269 {
3270 for (let dx = -1; dx <= 1; dx++)
3271 {
3272 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
3273 if (baked)
3274 { baked.lightmapCacheKey = null; }
3275 }
3276 }
3277 }
3278
3279 /**
3280 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
3281 * occluding tiles stay flat and contribute 0 into others so light does not bleed
3282 * through a wall to the far side. Diagonals only when both cardinals are clear.
3283 */
3284 #writeChunkLightmap (baked, activeLights, lightOcclusion)
3285 {
3286 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3287 if (!snapshot)
3288 { return; }
3289 const cacheKey = this.#chunkLightmapCacheKey(baked, activeLights);
3290 if (cacheKey && baked.lightmapCacheKey === cacheKey)
3291 { return; }
3292 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3293 const pixelCount = atlasPx * atlasPx * 4;
3294 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
3295 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
3296 const pixels = baked.lightmapPixels;
3297
3298 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
3299 const simple = this.lightingMode === "simple";
3300
3301 for (let localY = 0; localY < CHUNK_SIZE; localY++)
3302 {
3303 for (let localX = 0; localX < CHUNK_SIZE; localX++)
3304 {
3305 const baseX = localX * SPRITE_SIZE_PX;
3306 const baseY = localY * SPRITE_SIZE_PX;
3307 if (simple)
3308 {
3309 const gridW = CHUNK_SIZE + 2;
3310 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
3311 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3312 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3313 {
3314 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3315 {
3316 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3317 pixels[offset] = value;
3318 pixels[offset + 1] = value;
3319 pixels[offset + 2] = value;
3320 pixels[offset + 3] = 255;
3321 }
3322 }
3323 continue;
3324 }
3325 const corners = this.#tileLitCorners(baked, localX, localY);
3326 const nw = corners.nw;
3327 const ne = corners.ne;
3328 const sw = corners.sw;
3329 const se = corners.se;
3330 for (let py = 0; py < SPRITE_SIZE_PX; py++)
3331 {
3332 const v = (py + 0.5) / SPRITE_SIZE_PX;
3333 const left = nw + (sw - nw) * v;
3334 const right = ne + (se - ne) * v;
3335 for (let px = 0; px < SPRITE_SIZE_PX; px++)
3336 {
3337 const u = (px + 0.5) / SPRITE_SIZE_PX;
3338 const intensity = left + (right - left) * u;
3339 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
3340 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
3341 pixels[offset] = value;
3342 pixels[offset + 1] = value;
3343 pixels[offset + 2] = value;
3344 pixels[offset + 3] = 255;
3345 }
3346 }
3347 }
3348 }
3349 const ctx = baked.lightmapCanvas.getContext("2d");
3350 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
3351 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3352 baked.lightmapCacheKey = cacheKey;
3353 }
3354
3355 #updateSwipes (now)
3356 {
3357 this.swipes = this.swipes.filter((swipe) =>
3358 {
3359 if (swipe.lerp && swipe.started != null)
3360 {
3361 const durationMs = swipe.durationMs ?? 400;
3362 const t = Math.min(1, (now - swipe.started) / durationMs);
3363 const fromPivot = tilePivot(swipe.fromTileX, swipe.fromTileY, this.tileSize());
3364 const toPivot = this.#projectileEndPivot(swipe);
3365 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
3366 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
3367 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
3368 if (swipe.object?.transform)
3369 {
3370 swipe.object.transform.rotation = Math.atan2(
3371 toPivot.y - fromPivot.y,
3372 toPivot.x - fromPivot.x
3373 ) * (180 / Math.PI);
3374 }
3375 if (swipe.spellProjectile && swipe.baseSprite)
3376 {
3377 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
3378 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
3379 if (image && swipe.object?.renderer)
3380 { swipe.object.renderer.sprite = image; }
3381 }
3382 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
3383 if (!swipe.spellProjectile)
3384 {
3385 this.#applyPhysicalCombatFxDarkness(
3386 swipe.object,
3387 swipe.fromTileX,
3388 swipe.fromTileY,
3389 swipe.tileX,
3390 swipe.tileY,
3391 swipe.dualTint ?? null
3392 );
3393 }
3394 }
3395 else if (swipe.fromTileX != null && !swipe.spellProjectile)
3396 {
3397 this.#applyPhysicalCombatFxDarkness(
3398 swipe.object,
3399 swipe.fromTileX,
3400 swipe.fromTileY,
3401 swipe.tileX,
3402 swipe.tileY,
3403 swipe.dualTint ?? null
3404 );
3405 }
3406 if (swipe.until > now)
3407 { return true; }
3408 const onImpact = swipe.onImpact;
3409 swipe.onImpact = null;
3410 swipe.object?.destroy();
3411 if (typeof onImpact === "function")
3412 {
3413 try
3414 { onImpact(); }
3415 catch (_)
3416 { /* presentation only */ }
3417 }
3418 return false;
3419 });
3420 }
3421
3422 #projectileEndPivot (swipe)
3423 {
3424 if (swipe.trackTarget && swipe.targetId != null)
3425 {
3426 const target = this.entities.get(swipe.targetId);
3427 if (target && Number.isFinite(target.visualX) && Number.isFinite(target.visualY))
3428 {
3429 return { x: target.visualX, y: target.visualY };
3430 }
3431 }
3432 return tilePivot(swipe.tileX, swipe.tileY, this.tileSize());
3433 }
3434
3435 #updateDamageNumbers (now)
3436 {
3437 const layer = this.damageNumbersEl;
3438 if (!layer)
3439 { return; }
3440 this.damageFloats = this.damageFloats.filter((entry) =>
3441 {
3442 const elapsed = now - entry.started;
3443 if (elapsed >= DAMAGE_FLOAT_MS)
3444 {
3445 entry.element?.remove();
3446 return false;
3447 }
3448 const entity = this.entities.get(entry.entityId);
3449 if (!entity)
3450 {
3451 entry.element?.remove();
3452 return false;
3453 }
3454 if (!entry.element)
3455 {
3456 entry.element = document.createElement("span");
3457 entry.element.className = "damage-number";
3458 entry.element.textContent = String(entry.damage);
3459 layer.append(entry.element);
3460 }
3461 const anchor = this.nametagAnchor(entity);
3462 if (!anchor)
3463 { return true; }
3464 const t = elapsed / DAMAGE_FLOAT_MS;
3465 entry.element.style.left = `${anchor.x}px`;
3466 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
3467 entry.element.style.opacity = String(1 - t);
3468 return true;
3469 });
3470 }
3471
3472 #updateSkillLevelFloats (now)
3473 {
3474 const layer = this.skillLevelFloatsEl;
3475 if (!layer)
3476 { return; }
3477 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
3478 {
3479 const elapsed = now - entry.started;
3480 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
3481 {
3482 entry.element?.remove();
3483 return false;
3484 }
3485 const entity = this.entities.get(entry.entityId);
3486 if (!entity)
3487 {
3488 entry.element?.remove();
3489 return false;
3490 }
3491 if (!entry.element)
3492 {
3493 const root = document.createElement("div");
3494 root.className = "skill-level-float";
3495
3496 const levelEl = document.createElement("div");
3497 levelEl.className = "skill-level-float-level";
3498 levelEl.textContent = `↑${entry.level}↑`;
3499
3500 const icon = document.createElement("img");
3501 icon.className = "skill-level-float-icon";
3502 icon.src = entry.icon;
3503 icon.alt = entry.displayName || "";
3504
3505 root.append(levelEl, icon);
3506 entry.element = root;
3507 layer.append(entry.element);
3508 }
3509 const anchor = this.nametagAnchor(entity);
3510 if (!anchor)
3511 { return true; }
3512 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
3513 entry.element.style.left = `${anchor.x}px`;
3514 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
3515 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
3516 return true;
3517 });
3518 }
3519
3520 #syncBloomLayer ()
3521 {
3522 if (!this.bloomEnabled)
3523 {
3524 this.scene.setLayers([{ name: "default" }]);
3525 return;
3526 }
3527 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
3528 this.scene.setLayers([
3529 { name: "default" },
3530 {
3531 name: RENDER_LAYER_BLOOM,
3532 composite: "add",
3533 postShaders: Shader.getBloomPostChain({
3534 threshold: settings.bloomThreshold,
3535 softKnee: settings.bloomSoftKnee,
3536 intensity: settings.bloomIntensity,
3537 blurSize: settings.bloomBlurSize,
3538 saturation: settings.bloomSaturation,
3539 colorPreserve: settings.bloomColorPreserve,
3540 dilate: settings.bloomDilate,
3541 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
3542 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
3543 })
3544 }
3545 ]);
3546 }
3547}
3548
3549export function nightFactor (hour, nightDarkness = 0.72)
3550{
3551 const peak = Math.min(1, Math.max(0, nightDarkness));
3552 if (hour >= 8 && hour <= 16)
3553 { return 0; }
3554 if (hour >= 22 || hour <= 5)
3555 { return peak; }
3556 if (hour < 8)
3557 { return lerp(peak, 0, (hour - 5) / 3); }
3558 return lerp(0, peak, (hour - 16) / 6);
3559}
3560
3561function bodySpriteName (sex)
3562{
3563 const key = sex === "female" ? "player-body-female" : "player-body-male";
3564 return spriteImageName("character", key, key);
3565}
3566
3567function lerp (a, b, t)
3568{
3569 return a + (b - a) * Math.min(1, Math.max(0, t));
3570}
3571
3572function makeLightmapCanvas (size)
3573{
3574 const canvas = document.createElement("canvas");
3575 canvas.width = size;
3576 canvas.height = size;
3577 return canvas;
3578}
3579
3580function copyCanvas (source, dest)
3581{
3582 const ctx = dest.getContext("2d");
3583 ctx.imageSmoothingEnabled = false;
3584 ctx.clearRect(0, 0, dest.width, dest.height);
3585 ctx.drawImage(source, 0, 0);
3586}
3587
3588function drawHpBar (canvas, current, max)
3589{
3590 const ctx = canvas.getContext("2d");
3591 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
3592 ctx.fillStyle = "#000000";
3593 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
3594 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
3595 const fillW = Math.round(12 * ratio);
3596 if (fillW > 0)
3597 {
3598 ctx.fillStyle = "#ff0000";
3599 ctx.fillRect(1, 1, fillW, 2);
3600 }
3601}