BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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