BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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