BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

worldView.js 130.9 KiB Download Raw
1import { CHUNK_SIZE, SPRITE_SIZE_PX, GAIT, DEFAULT_WORLD_SETTINGS, PIVOT_FROM_BOTTOM_PX, ENTITY_STACK_SPREAD_DIAMETER_PX } from "/shared/protocol/constants.js";
2import { dynamicLightAtTile, dynamicDarknessAtTile, lightIntensity } from "/shared/lighting/raycast.js";
3import { makeSnapshotLightOcclusion } from "/shared/lighting/tilePassable.js";
4import { bakeChunkOcclusion } from "/shared/lighting/chunkOcclusion.js";
5import { bloomCompanionName, spriteImageName } from "/shared/definitions/tileSprites.js";
6import { EQUIPMENT_SLOT, itemEquipSprite, itemSpriteName, itemDefinition } from "/shared/definitions/items.js";
7import { resolveItemTint, resolveEquipTint, resolveItemDualTint, normalizeRgb } from "/shared/render/tint.js";
8import { 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 }
1665
1666 removeSpellLight (payload)
1667 {
1668 this.spellLights.delete(`${payload.tileX},${payload.tileY}`);
1669 }
1670
1671 setSpellDark (payload)
1672 {
1673 const key = `${payload.tileX},${payload.tileY}`;
1674 this.spellDarks.set(key, {
1675 tileX: payload.tileX,
1676 tileY: payload.tileY,
1677 until: performance.now() + Math.max(0, payload.remainingMs ?? 0),
1678 range: payload.rangeTiles ?? 6,
1679 intensity: payload.intensity ?? 0.88
1680 });
1681 }
1682
1683 removeSpellDark (payload)
1684 {
1685 this.spellDarks.delete(`${payload.tileX},${payload.tileY}`);
1686 }
1687
1688 #spellProjectileImage (baseSprite, frameIndex)
1689 {
1690 const frame = Math.max(0, Math.min(2, frameIndex | 0));
1691 const stem = baseSprite.split(":").pop() ?? "spell-light";
1692 const names = [
1693 `${baseSprite}-${frame}`,
1694 `fx:projectile:${stem}-${frame}`,
1695 baseSprite,
1696 `fx:projectile:${stem}`
1697 ];
1698 for (const name of names)
1699 {
1700 if (this.game.images[name])
1701 { return this.game.images[name]; }
1702 }
1703 return null;
1704 }
1705
1706 addDynamicLight ({ worldX, worldY, radiusTiles = 3, intensity = 1, durationMs = 250 })
1707 {
1708 this.dynamicLights.push({
1709 tileX: Math.floor(worldX),
1710 tileY: Math.floor(worldY),
1711 range: radiusTiles,
1712 intensity,
1713 until: performance.now() + durationMs
1714 });
1715 }
1716
1717 updateAuthoredTile (chunkX, chunkY, localX, localY, { ground, block, light } = {})
1718 {
1719 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
1720 if (!snapshot)
1721 { return; }
1722 const index = localY * CHUNK_SIZE + localX;
1723 if (ground !== undefined)
1724 { snapshot.grounds[index] = ground; }
1725 if (block !== undefined)
1726 { snapshot.blocks[index] = block; }
1727 if (light !== undefined)
1728 { snapshot.light[index] = light; }
1729 const tileX = chunkX * CHUNK_SIZE + localX;
1730 const tileY = chunkY * CHUNK_SIZE + localY;
1731 if (block !== undefined)
1732 {
1733 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
1734 this.#drawTile(tileX, tileY);
1735 return;
1736 }
1737 this.#scheduleChunkRebuild(snapshot);
1738 if (ground !== undefined)
1739 { this.#drawTile(tileX, tileY); }
1740 }
1741
1742 /**
1743 * Editor-only mob markers for authored spawners (invisible during play).
1744 * Humanoid / town guard / CE show body + equipment overlays.
1745 * @param {number} chunkX
1746 * @param {number} chunkY
1747 * @param {Array<{ localX: number, localY: number, config?: object }>} spawners
1748 * @param {(mobTypeId: number) => string} resolveSprite
1749 */
1750 setEditorSpawners (chunkX, chunkY, spawners, resolveSprite)
1751 {
1752 const prefix = `${chunkX},${chunkY}:`;
1753 for (const [key, entry] of [...this.editorSpawners.entries()])
1754 {
1755 if (!key.startsWith(prefix))
1756 { continue; }
1757 this.#destroyEditorSpawnerEntry(entry);
1758 this.editorSpawners.delete(key);
1759 }
1760 const size = this.tileSize();
1761 for (const spawner of spawners ?? [])
1762 {
1763 const tileX = chunkX * CHUNK_SIZE + spawner.localX;
1764 const tileY = chunkY * CHUNK_SIZE + spawner.localY;
1765 const layers = layersFromSpawnerConfig(spawner.config);
1766 const bodySpriteName = layers?.[0]?.sprite
1767 ?? resolveSprite?.(spawner.config?.mobTypeId)
1768 ?? null;
1769 if (!bodySpriteName)
1770 { continue; }
1771 const key = `${prefix}${spawner.localX},${spawner.localY}`;
1772 const object = this.#ensureSprite(null, bodySpriteName, SORT_ENTITY);
1773 if (!object)
1774 { continue; }
1775 object.renderer.alpha = 0.85;
1776 const bodyTint = layers?.[0]?.tint ? normalizeRgb(layers[0].tint) : null;
1777 if (bodyTint)
1778 { this.#syncUnlitTintSprite(object, bodyTint); }
1779 else
1780 { this.#markUnlit(object); }
1781 const overlays = [];
1782 for (const layer of layers?.slice(1) ?? [])
1783 {
1784 const overlay = this.#ensureSprite(null, layer.sprite, SORT_ENTITY);
1785 if (!overlay)
1786 { continue; }
1787 overlay.renderer.alpha = 0.85;
1788 this.#applyEditorSpawnerOverlayLook(overlay, layer);
1789 overlays.push(overlay);
1790 }
1791 const pivot = tilePivot(tileX, tileY, size);
1792 this.#placePivoted(object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1793 for (let i = 0; i < overlays.length; i++)
1794 {
1795 this.#placePivoted(
1796 overlays[i],
1797 pivot.x,
1798 pivot.y,
1799 pivot.y + 0.05 + 0.001 * (i + 1),
1800 SORT_ENTITY
1801 );
1802 }
1803 this.editorSpawners.set(key, {
1804 object,
1805 overlays,
1806 tileX,
1807 tileY,
1808 spriteName: bodySpriteName
1809 });
1810 }
1811 }
1812
1813 #destroyEditorSpawnerEntry (entry)
1814 {
1815 entry?.object?.destroy();
1816 for (const overlay of entry?.overlays ?? [])
1817 { overlay?.destroy(); }
1818 }
1819
1820 #applyEditorSpawnerOverlayLook (overlay, layer)
1821 {
1822 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
1823 const dualTint = layerDef?.iconTintFromTier
1824 ? null
1825 : (layer.itemId != null
1826 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
1827 : null);
1828 const tint = layer.tint
1829 ? normalizeRgb(layer.tint)
1830 : (dualTint
1831 ? null
1832 : (layerDef?.iconTintFromTier
1833 ? resolveItemTint({ itemId: layer.itemId }, layerDef)
1834 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null)));
1835 if (dualTint)
1836 {
1837 overlay._lit = true;
1838 this.#syncDualTintLitSprite(overlay, 0, dualTint, 0, false);
1839 return;
1840 }
1841 if (tint)
1842 {
1843 this.#syncUnlitTintSprite(overlay, tint);
1844 return;
1845 }
1846 this.#markUnlit(overlay);
1847 }
1848
1849 clearEditorSpawners ()
1850 {
1851 for (const entry of this.editorSpawners.values())
1852 { this.#destroyEditorSpawnerEntry(entry); }
1853 this.editorSpawners.clear();
1854 }
1855
1856 #relayoutEditorSpawners ()
1857 {
1858 const size = this.tileSize();
1859 for (const entry of this.editorSpawners.values())
1860 {
1861 if (!entry.object)
1862 { continue; }
1863 const pivot = tilePivot(entry.tileX, entry.tileY, size);
1864 this.#placePivoted(entry.object, pivot.x, pivot.y, pivot.y + 0.05, SORT_ENTITY);
1865 const overlays = entry.overlays ?? [];
1866 for (let i = 0; i < overlays.length; i++)
1867 {
1868 this.#placePivoted(
1869 overlays[i],
1870 pivot.x,
1871 pivot.y,
1872 pivot.y + 0.05 + 0.001 * (i + 1),
1873 SORT_ENTITY
1874 );
1875 }
1876 }
1877 }
1878
1879 /**
1880 * Editor-only range overlays: spawn (inner) and wander (outer, Chebyshev squares).
1881 */
1882 setSpawnRangeHighlight (tileX, tileY, spawnRange, wanderRange = null)
1883 {
1884 const spawnRadius = Math.max(0, spawnRange | 0);
1885 const wanderRadius = Math.max(spawnRadius, wanderRange == null ? spawnRadius : (wanderRange | 0));
1886 if (this.spawnRangeHighlight
1887 && this.wanderRangeHighlight
1888 && this.spawnRangeHighlight.tileX === tileX
1889 && this.spawnRangeHighlight.tileY === tileY
1890 && this.spawnRangeHighlight.range === spawnRadius
1891 && this.wanderRangeHighlight.range === wanderRadius)
1892 {
1893 this.#relayoutSpawnRangeHighlight();
1894 return;
1895 }
1896 this.clearSpawnRangeHighlight();
1897 const wanderObject = this.#ensureSprite(null, "wander-range", LAYER_EDGE);
1898 const spawnObject = this.#ensureSprite(null, "spawn-range", LAYER_EDGE);
1899 if (wanderObject)
1900 {
1901 this.#markUnlit(wanderObject);
1902 wanderObject.renderer.alpha = 1;
1903 this.wanderRangeHighlight = { object: wanderObject, tileX, tileY, range: wanderRadius };
1904 }
1905 if (spawnObject)
1906 {
1907 this.#markUnlit(spawnObject);
1908 spawnObject.renderer.alpha = 1;
1909 this.spawnRangeHighlight = { object: spawnObject, tileX, tileY, range: spawnRadius };
1910 }
1911 this.#relayoutSpawnRangeHighlight();
1912 }
1913
1914 clearSpawnRangeHighlight ()
1915 {
1916 this.spawnRangeHighlight?.object?.destroy();
1917 this.wanderRangeHighlight?.object?.destroy();
1918 this.spawnRangeHighlight = null;
1919 this.wanderRangeHighlight = null;
1920 }
1921
1922 setSpellTargetHighlight (tileX, tileY, inRange = true)
1923 {
1924 if (
1925 this.spellTargetHighlight
1926 && this.spellTargetHighlight.mode === "tile"
1927 && this.spellTargetHighlight.tileX === tileX
1928 && this.spellTargetHighlight.tileY === tileY
1929 && this.spellTargetHighlight.inRange === inRange
1930 )
1931 {
1932 this.#relayoutSpellTargetHighlight();
1933 return;
1934 }
1935 this.clearSpellTargetHighlight();
1936 const spriteName = inRange ? "spell-target-tile" : "spell-target-invalid";
1937 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1938 if (!object)
1939 { return; }
1940 this.#markUnlit(object);
1941 object.renderer.alpha = 1;
1942 this.spellTargetHighlight = {
1943 mode: "tile",
1944 object,
1945 tileX,
1946 tileY,
1947 entityId: null,
1948 inRange,
1949 spriteName
1950 };
1951 this.#relayoutSpellTargetHighlight();
1952 }
1953
1954 /** Outline box around a living entity (mob / player) for entity-target spells. */
1955 setSpellEntityTargetHighlight (entityId, inRange = true)
1956 {
1957 const id = entityId | 0;
1958 if (
1959 this.spellTargetHighlight
1960 && this.spellTargetHighlight.mode === "entity"
1961 && this.spellTargetHighlight.entityId === id
1962 && this.spellTargetHighlight.inRange === inRange
1963 )
1964 {
1965 this.#relayoutSpellTargetHighlight();
1966 return;
1967 }
1968 this.clearSpellTargetHighlight();
1969 if (!this.entities.has(id))
1970 { return; }
1971 const spriteName = inRange ? "spell-target-entity" : "spell-target-entity-invalid";
1972 const object = this.#ensureSprite(null, spriteName, LAYER_EDGE - 1);
1973 if (!object)
1974 { return; }
1975 this.#markUnlit(object);
1976 object.renderer.alpha = 1;
1977 this.spellTargetHighlight = {
1978 mode: "entity",
1979 object,
1980 tileX: 0,
1981 tileY: 0,
1982 entityId: id,
1983 inRange,
1984 spriteName
1985 };
1986 this.#relayoutSpellTargetHighlight();
1987 }
1988
1989 clearSpellTargetHighlight ()
1990 {
1991 this.spellTargetHighlight?.object?.destroy();
1992 this.spellTargetHighlight = null;
1993 }
1994
1995 #relayoutSpellTargetHighlight ()
1996 {
1997 const highlight = this.spellTargetHighlight;
1998 if (!highlight?.object)
1999 { return; }
2000 if (highlight.mode === "entity")
2001 {
2002 const entity = this.entities.get(highlight.entityId);
2003 if (!entity?.object)
2004 {
2005 this.clearSpellTargetHighlight();
2006 return;
2007 }
2008 const pad = this.tileSize() * 0.12;
2009 const src = entity.object.transform;
2010 highlight.object.transform.position.x = src.position.x;
2011 highlight.object.transform.position.y = src.position.y;
2012 highlight.object.transform.size = new vector(src.size.x + pad, src.size.y + pad);
2013 highlight.object.layer = LAYER_EDGE - 1;
2014 highlight.tileX = entity.tileX;
2015 highlight.tileY = entity.tileY;
2016 this.#markSortDirty();
2017 return;
2018 }
2019 const size = this.tileSize();
2020 const left = highlight.tileX * size;
2021 const top = highlight.tileY * size;
2022 highlight.object.transform.position.x = left + size / 2;
2023 highlight.object.transform.position.y = top + size / 2;
2024 highlight.object.transform.size = new vector(size, size);
2025 highlight.object.layer = LAYER_EDGE - 1;
2026 this.#markSortDirty();
2027 }
2028
2029 #relayoutSpawnRangeHighlight ()
2030 {
2031 this.#layoutRangeOverlay(this.wanderRangeHighlight, LAYER_EDGE - 2);
2032 this.#layoutRangeOverlay(this.spawnRangeHighlight, LAYER_EDGE - 1);
2033 }
2034
2035 #layoutRangeOverlay (highlight, layer)
2036 {
2037 if (!highlight?.object)
2038 { return; }
2039 const size = this.tileSize();
2040 const side = (2 * highlight.range + 1) * size;
2041 const left = (highlight.tileX - highlight.range) * size;
2042 const top = (highlight.tileY - highlight.range) * size;
2043 highlight.object.transform.position.x = left + side / 2;
2044 highlight.object.transform.position.y = top + side / 2;
2045 highlight.object.transform.size = new vector(side, side);
2046 highlight.object.layer = layer;
2047 this.#markSortDirty();
2048 }
2049
2050 setTilePreview (tileX, tileY, override)
2051 {
2052 const next = { tileX, tileY, ...override };
2053 if (this.#previewEqual(this.preview, next))
2054 { return; }
2055 const previous = this.preview;
2056 this.preview = next;
2057 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2058 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2059 this.#scheduleChunkRebuild(this.chunks.get(`${chunkX},${chunkY}`));
2060 if (previous && (previous.tileX !== tileX || previous.tileY !== tileY))
2061 {
2062 const prevKey = `${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`;
2063 if (prevKey !== `${chunkX},${chunkY}`)
2064 { this.#scheduleChunkRebuild(this.chunks.get(prevKey)); }
2065 }
2066 }
2067
2068 clearTilePreview ()
2069 {
2070 if (!this.preview)
2071 { return; }
2072 const previous = this.preview;
2073 this.preview = null;
2074 const snapshot = this.chunks.get(`${Math.floor(previous.tileX / CHUNK_SIZE)},${Math.floor(previous.tileY / CHUNK_SIZE)}`);
2075 this.#scheduleChunkRebuild(snapshot);
2076 }
2077
2078 #lerpMs (gait)
2079 {
2080 const walk = this.settings.walkTilesPerSecond || 2;
2081 const seconds = gait === GAIT.run ? 1 / (walk * 2) : 1 / walk;
2082 return seconds * 1000;
2083 }
2084
2085 #centerCamera ()
2086 {
2087 if (!this.followPlayer)
2088 { return; }
2089 const local = this.entities.get(this.localEntityId);
2090 if (!local)
2091 { return; }
2092 const x = local.visualX + (local.stackOffsetX ?? 0);
2093 const y = local.visualY + (local.stackOffsetY ?? 0);
2094 this.scene.cameraPosition.x = this.scene.real_size.x / 2 - x;
2095 this.scene.cameraPosition.y = this.scene.real_size.y / 2 - y;
2096 }
2097
2098 /**
2099 * World-pixel AABB of the screen, expanded by half a tile (zoom-aware).
2100 * Tiles fully outside this rect are not drawn.
2101 */
2102 #drawBounds ()
2103 {
2104 const pad = this.tileSize() * 0.5;
2105 const camX = this.scene.cameraPosition.x;
2106 const camY = this.scene.cameraPosition.y;
2107 const w = this.scene.real_size.x;
2108 const h = this.scene.real_size.y;
2109 return {
2110 left: -camX - pad,
2111 right: -camX + w + pad,
2112 top: -camY - pad,
2113 bottom: -camY + h + pad
2114 };
2115 }
2116
2117 #rectIntersects (left, top, right, bottom, bounds)
2118 {
2119 return right >= bounds.left
2120 && left <= bounds.right
2121 && bottom >= bounds.top
2122 && top <= bounds.bottom;
2123 }
2124
2125 #setRendererVisible (object, visible)
2126 {
2127 if (object?.renderer)
2128 { object.renderer.visible = !!visible; }
2129 }
2130
2131 /** Skip drawing (and lighting work) for tiles/chunks more than ½ tile off-screen. */
2132 #cullOffscreenDrawables ()
2133 {
2134 const bounds = this.#drawBounds();
2135 const size = this.tileSize();
2136
2137 for (const baked of this.bakedChunks.values())
2138 {
2139 const left = baked.chunkX * CHUNK_SIZE * size;
2140 const top = baked.chunkY * CHUNK_SIZE * size;
2141 const chunkPx = CHUNK_SIZE * size;
2142 const chunkVisible = this.#rectIntersects(left, top, left + chunkPx, top + chunkPx, bounds);
2143 this.#setRendererVisible(baked.groundObject, chunkVisible);
2144 this.#setRendererVisible(baked.bloomObject, chunkVisible && this.bloomEnabled);
2145 baked._inViewport = chunkVisible;
2146 for (let row = 0; row < CHUNK_SIZE; row++)
2147 {
2148 const rowTop = top + row * size;
2149 const rowVisible = chunkVisible && this.#rectIntersects(
2150 left, rowTop, left + chunkPx, rowTop + size, bounds
2151 );
2152 this.#setRendererVisible(baked.blockObjects?.[row], rowVisible);
2153 }
2154 }
2155
2156 for (const objects of this.tiles.values())
2157 {
2158 const left = objects.tileX * size;
2159 const top = objects.tileY * size;
2160 const visible = this.#rectIntersects(left, top, left + size, top + size, bounds);
2161 objects._inViewport = visible;
2162 this.#setRendererVisible(objects.ground, visible);
2163 this.#setRendererVisible(objects.groundBloom, visible && this.bloomEnabled);
2164 this.#setRendererVisible(objects.block, visible);
2165 this.#setRendererVisible(objects.blockBloom, visible && this.bloomEnabled);
2166 if (objects.waterEdges)
2167 {
2168 for (const edge of Object.values(objects.waterEdges))
2169 { this.#setRendererVisible(edge, visible); }
2170 }
2171 }
2172 }
2173
2174 #upsertEntity (payload)
2175 {
2176 const size = this.tileSize();
2177 const pivot = tilePivot(payload.tileX, payload.tileY, size);
2178 let entity = this.entities.get(payload.entityId);
2179 if (!entity)
2180 {
2181 const spriteName = payload.layers?.[0]?.sprite
2182 ?? payload.sprite
2183 ?? bodySpriteName(payload.sex);
2184 const object = new GameObject(0, 0, this.game.images[spriteName], SORT_ENTITY);
2185 this.scene.addObject(object);
2186 this.#startIdleAnimation(object);
2187 entity = { object, overlays: [], bloomOverlays: [], visualX: pivot.x, visualY: pivot.y };
2188 this.entities.set(payload.entityId, entity);
2189 }
2190 entity.entityId = payload.entityId;
2191 entity.tileX = payload.tileX;
2192 entity.tileY = payload.tileY;
2193 entity.gait = payload.gait;
2194 entity.sex = payload.sex ?? entity.sex;
2195 entity.characterId = payload.characterId ?? entity.characterId ?? null;
2196 entity.accountId = payload.accountId ?? entity.accountId ?? null;
2197 entity.mobTypeId = payload.mobTypeId ?? entity.mobTypeId ?? null;
2198 if (payload.level != null)
2199 { entity.level = payload.level | 0; }
2200 entity.hostile = payload.hostile != null ? !!payload.hostile : !!entity.hostile;
2201 entity.canFight = payload.canFight != null
2202 ? !!payload.canFight
2203 : !!(entity.canFight || (payload.mobTypeId && !payload.talkable));
2204 entity.talkable = payload.talkable != null ? !!payload.talkable : !!entity.talkable;
2205 entity.hasDialogue = payload.hasDialogue != null ? !!payload.hasDialogue : !!entity.hasDialogue;
2206 entity.hasShop = payload.hasShop != null ? !!payload.hasShop : !!entity.hasShop;
2207 entity.untargetable = payload.untargetable != null ? !!payload.untargetable : !!entity.untargetable;
2208 entity.freeFlight = payload.freeFlight != null ? !!payload.freeFlight : !!entity.freeFlight;
2209 entity.lightRadiusTiles = payload.lightRadiusTiles ?? entity.lightRadiusTiles ?? 0;
2210 if (payload.visualScale != null)
2211 { entity.visualScale = Number(payload.visualScale) || 1; }
2212 else if (entity.visualScale == null)
2213 { entity.visualScale = 1; }
2214 if (payload.health != null)
2215 { entity.health = payload.health; }
2216 if (payload.maxHealth != null)
2217 { entity.maxHealth = payload.maxHealth; }
2218 if (payload.skullValue != null)
2219 { entity.skullValue = Math.max(0, payload.skullValue | 0); }
2220 else if (entity.skullValue == null)
2221 { entity.skullValue = 0; }
2222 if (payload.firstName)
2223 { entity.firstName = payload.firstName; }
2224 if (payload.lastName)
2225 { entity.lastName = payload.lastName; }
2226 entity.firstName = entity.firstName ?? "";
2227 entity.lastName = entity.lastName ?? "";
2228 if (payload.worldX != null && payload.worldY != null)
2229 {
2230 entity.worldX = payload.worldX;
2231 entity.worldY = payload.worldY;
2232 entity.visualX = payload.worldX * size;
2233 entity.visualY = payload.worldY * size;
2234 entity.targetX = entity.visualX;
2235 entity.targetY = entity.visualY;
2236 }
2237 else
2238 {
2239 entity.visualX = pivot.x;
2240 entity.visualY = pivot.y;
2241 entity.targetX = pivot.x;
2242 entity.targetY = pivot.y;
2243 }
2244 entity.fromX = entity.visualX;
2245 entity.fromY = entity.visualY;
2246 if (payload.layers)
2247 { this.#applyLayers(entity, payload.layers); }
2248 this.#syncHpBar(entity);
2249 this.#syncSkullMarker(entity);
2250 this.#placeEntity(entity, performance.now());
2251 }
2252
2253 #applyLayers (entity, layers)
2254 {
2255 entity.appearanceLayers = layers ?? [{ sprite: bodySpriteName(entity.sex) }];
2256 this.#rebuildOverlays(entity);
2257 }
2258
2259 #setGatherToolOverlay (entity, toolItemId)
2260 {
2261 entity.gatherToolItemId = toolItemId;
2262 entity.gatherToolUntil = performance.now() + GATHER_TOOL_HOLD_MS;
2263 this.#rebuildOverlays(entity);
2264 this.#placeEntity(entity, performance.now());
2265 }
2266
2267 #expireGatherToolOverlay (entity, now)
2268 {
2269 if (entity.gatherToolItemId == null)
2270 { return; }
2271 if ((entity.gatherToolUntil ?? 0) > now)
2272 { return; }
2273 entity.gatherToolItemId = null;
2274 entity.gatherToolUntil = 0;
2275 this.#rebuildOverlays(entity);
2276 }
2277
2278 /** Prefer the active gather tool's equip sprite over the worn weapon (all gather kinds). */
2279 #layersForDisplay (entity)
2280 {
2281 const layers = (entity.appearanceLayers ?? []).map((layer) => ({ ...layer }));
2282 const toolId = entity.gatherToolItemId;
2283 if (toolId == null || (entity.gatherToolUntil ?? 0) <= performance.now())
2284 { return layers; }
2285 const equip = itemEquipSprite(toolId);
2286 if (!equip || !this.game.images[equip])
2287 { return layers; }
2288 const replacement = {
2289 sprite: equip,
2290 itemId: toolId,
2291 tint: resolveEquipTint(toolId)
2292 };
2293 for (let index = layers.length - 1; index >= 1; index--)
2294 {
2295 const def = itemDefinition(layers[index].itemId);
2296 if (def?.equipment?.slot === EQUIPMENT_SLOT.weapon)
2297 {
2298 layers[index] = replacement;
2299 return layers;
2300 }
2301 }
2302 layers.push(replacement);
2303 return layers;
2304 }
2305
2306 #rebuildOverlays (entity)
2307 {
2308 const layers = this.#layersForDisplay(entity);
2309 const base = layers[0]?.sprite
2310 ?? bodySpriteName(entity.sex);
2311 if (this.game.images[base])
2312 {
2313 entity.object.renderer.sprite = this.game.images[base];
2314 this.#startIdleAnimation(entity.object);
2315 }
2316 entity.bodyTint = layers[0]?.tint ? normalizeRgb(layers[0].tint) : null;
2317 entity.bloomBody = !!layers[0]?.bloomBody;
2318 for (const overlay of entity.overlays ?? [])
2319 { overlay.destroy(); }
2320 for (const overlay of entity.bloomOverlays ?? [])
2321 { overlay.destroy(); }
2322 entity.overlays = [];
2323 entity.overlayTints = [];
2324 entity.overlayDualTints = [];
2325 entity.overlayTightFit = [];
2326 entity.bloomOverlays = [];
2327 entity.bloomOverlayTints = [];
2328 if (entity.bloomBody && this.game.images[base])
2329 {
2330 const bloomName = bloomCompanionName(base);
2331 const bloomImage = this.game.images[bloomName] ?? this.game.images[base];
2332 if (bloomImage)
2333 {
2334 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2335 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2336 this.#markUnlit(bloom);
2337 this.scene.addObject(bloom);
2338 entity.bloomOverlays.push(bloom);
2339 entity.bloomOverlayTints.push(entity.bodyTint);
2340 }
2341 }
2342 for (const layer of layers.slice(1))
2343 {
2344 const image = this.game.images[layer.sprite];
2345 if (!image)
2346 { continue; }
2347 const object = new GameObject(0, 0, image, SORT_ENTITY);
2348 this.scene.addObject(object);
2349 entity.overlays.push(object);
2350 const layerDef = layer.itemId != null ? itemDefinition(layer.itemId) : null;
2351 entity.overlayTightFit.push(!!layerDef?.tightFit);
2352 const dualTint = layer.itemId != null
2353 ? resolveItemDualTint({ itemId: layer.itemId }, layerDef)
2354 : null;
2355 entity.overlayDualTints.push(dualTint);
2356 entity.overlayTints.push(
2357 dualTint
2358 ? null
2359 : (layer.tint
2360 ? normalizeRgb(layer.tint)
2361 : (layer.itemId != null ? resolveEquipTint(layer.itemId) : null))
2362 );
2363 const bloomName = bloomCompanionName(layer.sprite);
2364 const bloomImage = this.game.images[bloomName];
2365 if (!bloomImage)
2366 { continue; }
2367 const bloom = new GameObject(0, 0, bloomImage, SORT_ENTITY);
2368 bloom.renderer.layer = RENDER_LAYER_BLOOM;
2369 this.#markUnlit(bloom);
2370 this.scene.addObject(bloom);
2371 entity.bloomOverlays.push(bloom);
2372 entity.bloomOverlayTints.push(
2373 layer.tint ? normalizeRgb(layer.tint) : null
2374 );
2375 }
2376 }
2377
2378 #placeEntity (entity, now = performance.now())
2379 {
2380 const zoom = this.zoom;
2381 const offsetX = entity.shoveOffsetX ?? 0;
2382 const offsetY = entity.shoveOffsetY ?? 0;
2383 const pivotX = entity.visualX + offsetX + (entity.stackOffsetX ?? 0);
2384 const pivotY = entity.visualY + offsetY + (entity.stackOffsetY ?? 0);
2385 let walkTilt = 0;
2386 if (entity.lerpStarted != null)
2387 {
2388 const stepMs = Math.max(1, entity.lerpMs ?? this.#lerpMs(entity.gait));
2389 const cycles = ((now - entity.lerpStarted) / stepMs) * Math.PI * 2;
2390 const tilt = entity.gait === GAIT.run ? RUN_TILT_DEG : WALK_TILT_DEG;
2391 walkTilt = Math.sin(cycles) * tilt;
2392 }
2393 const flashStrength = (entity.damageFlashUntil ?? 0) > now
2394 ? (entity.damageFlashUntil - now) / DAMAGE_FLASH_MS
2395 : 0;
2396 const flashColor = entity.damageFlashColor ?? FLASH_COLOR_DAMAGE;
2397 const tileShade = this.#entityShadeAlpha(entity, now);
2398 const wade = isWadeGroundInSeason(this.#groundTypeAt(entity.tileX, entity.tileY), this.worldSeason);
2399
2400 entity.object.transform.rotation = walkTilt;
2401 this.#syncLitSprite(entity.object, tileShade, flashStrength, wade, entity.bodyTint ?? null, flashColor);
2402 this.#placePivoted(entity.object, pivotX, pivotY, pivotY, SORT_ENTITY, entity.visualScale ?? 1);
2403 for (let index = 0; index < (entity.overlays ?? []).length; index++)
2404 {
2405 const overlay = entity.overlays[index];
2406 const overlaySortY = pivotY + 0.5 * (index + 1);
2407 overlay.transform.rotation = walkTilt;
2408 const dualTint = entity.overlayDualTints?.[index] ?? null;
2409 if (dualTint)
2410 {
2411 this.#syncDualTintLitSprite(overlay, tileShade, dualTint, flashStrength, wade, flashColor);
2412 }
2413 else if (entity.overlayTightFit?.[index])
2414 {
2415 this.#syncTightFitLitSprite(
2416 overlay,
2417 entity,
2418 tileShade,
2419 flashStrength,
2420 wade,
2421 entity.overlayTints?.[index] ?? null,
2422 flashColor
2423 );
2424 }
2425 else
2426 {
2427 this.#syncLitSprite(overlay, tileShade, flashStrength, wade, entity.overlayTints?.[index] ?? null, flashColor);
2428 }
2429 this.#placePivoted(overlay, pivotX, pivotY, overlaySortY, SORT_ENTITY, entity.visualScale ?? 1);
2430 }
2431 for (let index = 0; index < (entity.bloomOverlays ?? []).length; index++)
2432 {
2433 const overlay = entity.bloomOverlays[index];
2434 this.#setRendererVisible(overlay, this.bloomEnabled);
2435 if (!this.bloomEnabled)
2436 { continue; }
2437 /** Body bloom must share the base sprite's animation frame (e.g. elemental sprites). */
2438 if (entity.bloomBody && index === 0 && entity.object?.renderer)
2439 {
2440 overlay.renderer.cycle = null;
2441 overlay.renderer.subImage = entity.object.renderer.subImage | 0;
2442 }
2443 overlay.transform.rotation = walkTilt;
2444 const bloomTint = entity.bloomOverlayTints?.[index] ?? entity.bodyTint ?? null;
2445 if (bloomTint)
2446 { this.#syncUnlitTintSprite(overlay, bloomTint); }
2447 else
2448 { this.#syncLitSprite(overlay, tileShade, flashStrength, wade, null, flashColor); }
2449 this.#placePivoted(overlay, pivotX, pivotY, pivotY + 0.002, SORT_ENTITY, entity.visualScale ?? 1);
2450 }
2451 this.#placeHpBar(entity, pivotX, pivotY);
2452 this.#placeSkullMarker(entity, pivotX, pivotY, tileShade);
2453 }
2454
2455 #markUnlit (object)
2456 {
2457 if (!object?.renderer)
2458 { return; }
2459 object._lit = false;
2460 object.renderer.shader = null;
2461 object.renderer.shaderUniforms = null;
2462 object.renderer.secondaryMap = null;
2463 }
2464
2465 /** Bloom / unlit overlays that still need magenta channel tint (e.g. elemental sprites). */
2466 #syncUnlitTintSprite (object, tintColor)
2467 {
2468 if (!object?.renderer || !tintColor)
2469 { return; }
2470 const tint = normalizeRgb(tintColor);
2471 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2472 object.renderer.shader = getTintLitSpriteShader();
2473 object.renderer.shaderUniforms = {
2474 u_darkness: 0,
2475 u_strength: 0,
2476 u_flashColor: FLASH_COLOR_DAMAGE,
2477 u_wade: 0,
2478 u_spriteHeight: height,
2479 u_useTint: 1,
2480 u_tintColor: [tint.r, tint.g, tint.b]
2481 };
2482 object.renderer.secondaryMap = null;
2483 }
2484
2485 #syncLitSprite (object, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2486 {
2487 if (!object?.renderer || object._lit === false)
2488 { return; }
2489 object._lit = true;
2490 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2491 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2492 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2493 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2494 const tint = tintColor ? normalizeRgb(tintColor) : null;
2495 if (tint)
2496 {
2497 object.renderer.shader = getTintLitSpriteShader();
2498 object.renderer.shaderUniforms = {
2499 u_darkness: dark,
2500 u_strength: flash,
2501 u_flashColor: flashRgb,
2502 u_wade: wade ? 1 : 0,
2503 u_spriteHeight: height,
2504 u_useTint: 1,
2505 u_tintColor: [tint.r, tint.g, tint.b]
2506 };
2507 }
2508 else
2509 {
2510 object.renderer.shader = getSpriteLightingShader();
2511 object.renderer.shaderUniforms = {
2512 u_darkness: dark,
2513 u_strength: flash,
2514 u_flashColor: flashRgb,
2515 u_wade: wade ? 1 : 0,
2516 u_spriteHeight: height
2517 };
2518 }
2519 object.renderer.secondaryMap = null;
2520 }
2521
2522 #bodySecondaryMap (entity)
2523 {
2524 return entity?.object?.renderer?.sprite?.g_image ?? null;
2525 }
2526
2527 #tightFitMaskUniforms (overlay, entity)
2528 {
2529 const bodyRenderer = entity?.object?.renderer;
2530 const clothRenderer = overlay?.renderer;
2531 const bodySprite = bodyRenderer?.sprite;
2532 const clothSprite = clothRenderer?.sprite;
2533 if (!bodySprite || !clothSprite)
2534 { return null; }
2535 const clothUv = clothSprite.getUvRect?.(clothRenderer.subImage | 0)
2536 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2537 const bodyUv = bodySprite.getUvRect?.(bodyRenderer.subImage | 0)
2538 ?? { u0: 0, v0: 0, u1: 1, v1: 1 };
2539 return {
2540 u_clothSize: [clothSprite.width || SPRITE_SIZE_PX, clothSprite.height || SPRITE_SIZE_PX],
2541 u_bodySize: [bodySprite.width || SPRITE_SIZE_PX, bodySprite.height || SPRITE_SIZE_PX],
2542 u_pivotFromBottom: PIVOT_FROM_BOTTOM_PX,
2543 u_clothUvRect: [clothUv.u0, clothUv.v0, clothUv.u1, clothUv.v1],
2544 u_bodyUvRect: [bodyUv.u0, bodyUv.v0, bodyUv.u1, bodyUv.v1]
2545 };
2546 }
2547
2548 #syncTightFitLitSprite (overlay, entity, darkness, flashStrength = 0, wade = false, tintColor = null, flashColor = null)
2549 {
2550 if (!overlay?.renderer || entity?.object?.renderer == null)
2551 { return; }
2552 const bodyMap = this.#bodySecondaryMap(entity);
2553 const maskUniforms = this.#tightFitMaskUniforms(overlay, entity);
2554 const flashRgb = flashColor ?? FLASH_COLOR_DAMAGE;
2555 if (!bodyMap || !maskUniforms)
2556 {
2557 this.#syncLitSprite(overlay, darkness, flashStrength, wade, tintColor, flashRgb);
2558 return;
2559 }
2560 overlay._lit = true;
2561 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2562 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2563 const height = overlay.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2564 const tint = tintColor ? normalizeRgb(tintColor) : null;
2565 overlay.renderer.secondaryMap = bodyMap;
2566 if (tint)
2567 {
2568 overlay.renderer.shader = getTightFitTintLitSpriteShader();
2569 overlay.renderer.shaderUniforms = {
2570 u_darkness: dark,
2571 u_strength: flash,
2572 u_flashColor: flashRgb,
2573 u_wade: wade ? 1 : 0,
2574 u_spriteHeight: height,
2575 u_useTint: 1,
2576 u_tintColor: [tint.r, tint.g, tint.b],
2577 ...maskUniforms
2578 };
2579 }
2580 else
2581 {
2582 overlay.renderer.shader = getTightFitLitSpriteShader();
2583 overlay.renderer.shaderUniforms = {
2584 u_darkness: dark,
2585 u_strength: flash,
2586 u_flashColor: flashRgb,
2587 u_wade: wade ? 1 : 0,
2588 u_spriteHeight: height,
2589 ...maskUniforms
2590 };
2591 }
2592 }
2593
2594 #syncDualTintLitSprite (object, darkness, dualTint, flashStrength = 0, wade = false, flashColor = null)
2595 {
2596 if (!object?.renderer || object._lit === false || !dualTint)
2597 { return; }
2598 object._lit = true;
2599 const shaft = normalizeRgb(dualTint.shaft);
2600 const tip = normalizeRgb(dualTint.tip);
2601 const coat = dualTint.coat ? normalizeRgb(dualTint.coat) : null;
2602 const dark = Math.min(1, Math.max(0, darkness ?? 0));
2603 const flash = Math.min(1, Math.max(0, flashStrength ?? 0));
2604 const height = object.renderer.sprite?.height ?? SPRITE_SIZE_PX;
2605 object.renderer.shader = getDualTintLitSpriteShader();
2606 object.renderer.shaderUniforms = {
2607 u_darkness: dark,
2608 u_strength: flash,
2609 u_flashColor: flashColor ?? FLASH_COLOR_DAMAGE,
2610 u_wade: wade ? 1 : 0,
2611 u_spriteHeight: height,
2612 u_shaftTint: [shaft.r, shaft.g, shaft.b],
2613 u_tipTint: [tip.r, tip.g, tip.b],
2614 u_coatTint: coat ? [coat.r, coat.g, coat.b] : [0, 0, 0],
2615 u_hasCoat: coat ? 1 : 0
2616 };
2617 object.renderer.secondaryMap = null;
2618 }
2619
2620 #syncGroundItemSprite (item, darkness)
2621 {
2622 if (item?.dualTint)
2623 {
2624 this.#syncDualTintLitSprite(item.object, darkness, item.dualTint);
2625 return;
2626 }
2627 this.#syncLitSprite(item?.object, darkness, 0, false, item?.tintColor ?? null);
2628 }
2629
2630 #groundTypeAt (tileX, tileY)
2631 {
2632 const ground = this.#groundAtTile(tileX, tileY);
2633 return ground == null ? null : normalizeGround(ground).typeId;
2634 }
2635
2636 /** Ground entry at a world tile, including editor hover preview when present. */
2637 #groundAtTile (tileX, tileY)
2638 {
2639 if (this.preview && this.preview.tileX === tileX && this.preview.tileY === tileY
2640 && this.preview.ground !== undefined)
2641 { return this.preview.ground; }
2642 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2643 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2644 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
2645 if (!snapshot)
2646 { return null; }
2647 const localX = tileX - chunkX * CHUNK_SIZE;
2648 const localY = tileY - chunkY * CHUNK_SIZE;
2649 const index = localY * CHUNK_SIZE + localX;
2650 return snapshot.grounds?.[index] ?? null;
2651 }
2652
2653 #waterCoastEdges (tileX, tileY)
2654 {
2655 const season = this.worldSeason;
2656 return {
2657 n: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY - 1), season) ? 1 : 0,
2658 e: !isLiquidWaterGround(this.#groundTypeAt(tileX + 1, tileY), season) ? 1 : 0,
2659 s: !isLiquidWaterGround(this.#groundTypeAt(tileX, tileY + 1), season) ? 1 : 0,
2660 w: !isLiquidWaterGround(this.#groundTypeAt(tileX - 1, tileY), season) ? 1 : 0
2661 };
2662 }
2663
2664 #syncWaterGroundSprite (object, corners, ambientDark, edges, timeSec, fallbackLit = 1)
2665 {
2666 if (!object?.renderer)
2667 { return; }
2668 const lit = corners ?? {
2669 nw: fallbackLit,
2670 ne: fallbackLit,
2671 sw: fallbackLit,
2672 se: fallbackLit
2673 };
2674 const dark = Math.min(1, Math.max(0, ambientDark ?? 0));
2675 object._lit = true;
2676 object.renderer.shader = getWaterGroundShader();
2677 object.renderer.secondaryMap = null;
2678 object.renderer.shaderUniforms = {
2679 u_ambientDark: dark,
2680 u_litNW: lit.nw,
2681 u_litNE: lit.ne,
2682 u_litSW: lit.sw,
2683 u_litSE: lit.se,
2684 u_time: timeSec,
2685 u_edgeN: edges?.n ?? 0,
2686 u_edgeE: edges?.e ?? 0,
2687 u_edgeS: edges?.s ?? 0,
2688 u_edgeW: edges?.w ?? 0
2689 };
2690 }
2691
2692 /** Liquid water gets coast foam; frozen shallow ice uses the normal lit sprite. */
2693 #syncGroundWaterFx (objects, ambientDark, timeSec, baked = null)
2694 {
2695 if (!objects?.ground)
2696 { return; }
2697 if (!isLiquidWaterGround(objects.groundTypeId, this.worldSeason))
2698 {
2699 objects.waterEdges = null;
2700 this.#syncLitSprite(objects.ground, objects.shadeAlpha ?? 0);
2701 return;
2702 }
2703 const fallbackLit = ambientDark > 0
2704 ? 1 - (objects.shadeAlpha ?? 0) / ambientDark
2705 : 1;
2706 const chunkX = Math.floor(objects.tileX / CHUNK_SIZE);
2707 const chunkY = Math.floor(objects.tileY / CHUNK_SIZE);
2708 const chunkBaked = baked ?? this.bakedChunks.get(`${chunkX},${chunkY}`);
2709 const localX = objects.tileX - chunkX * CHUNK_SIZE;
2710 const localY = objects.tileY - chunkY * CHUNK_SIZE;
2711 let litCorners = null;
2712 if (chunkBaked)
2713 {
2714 if (this.lightingMode === "simple")
2715 {
2716 const gridW = CHUNK_SIZE + 2;
2717 const intensity = chunkBaked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? fallbackLit;
2718 litCorners = { nw: intensity, ne: intensity, sw: intensity, se: intensity };
2719 }
2720 else
2721 { litCorners = this.#tileLitCorners(chunkBaked, localX, localY); }
2722 }
2723 objects.waterEdges = this.#waterCoastEdges(objects.tileX, objects.tileY);
2724 this.#syncWaterGroundSprite(
2725 objects.ground,
2726 litCorners,
2727 ambientDark,
2728 objects.waterEdges,
2729 timeSec,
2730 fallbackLit
2731 );
2732 }
2733
2734 #ambientDarkness ()
2735 {
2736 const hour = this.nightPreview ?? this.worldHour;
2737 const calendar = nightFactor(hour, this.settings.nightDarkness);
2738 let dark = resolveDimensionDarknessFactor(this.dimensionLightingMode, calendar);
2739 if (dark == null)
2740 { dark = calendar; }
2741 if (this.localBlind)
2742 { dark = Math.min(1, dark + 0.85); }
2743 return dark;
2744 }
2745
2746 setLocalBlind (blind)
2747 {
2748 this.localBlind = !!blind;
2749 }
2750
2751 /** Soft vision bubble while blinded (client-only; stacks with ambient). */
2752 #blindVisionLight ()
2753 {
2754 if (!this.localBlind)
2755 { return null; }
2756 const local = this.entities.get(this.localEntityId);
2757 if (!local)
2758 { return null; }
2759 const tileSize = this.tileSize();
2760 return {
2761 tileX: Math.floor(local.visualX / tileSize),
2762 tileY: Math.floor(local.visualY / tileSize),
2763 range: 2.25,
2764 intensity: 1
2765 };
2766 }
2767
2768 #applyPhysicalCombatFxDarkness (object, fromTileX, fromTileY, tileX, tileY, dualTint = null)
2769 {
2770 const fromAlpha = this.tiles.get(`${fromTileX},${fromTileY}`)?.shadeAlpha ?? 0;
2771 const toAlpha = this.tiles.get(`${tileX},${tileY}`)?.shadeAlpha ?? 0;
2772 const dark = (fromAlpha + toAlpha) / 2;
2773 if (dualTint)
2774 {
2775 this.#syncDualTintLitSprite(object, dark, dualTint);
2776 return;
2777 }
2778 this.#syncLitSprite(object, dark);
2779 }
2780
2781 #dualTintFromPayload (payload)
2782 {
2783 if (!payload?.shaftTint || !payload?.tipTint)
2784 { return null; }
2785 return {
2786 shaft: payload.shaftTint,
2787 tip: payload.tipTint,
2788 ...(payload.coatTint ? { coat: payload.coatTint } : {})
2789 };
2790 }
2791
2792 #syncHpBar (entity)
2793 {
2794 const current = entity.health;
2795 const max = entity.maxHealth;
2796 const show = current != null
2797 && max != null
2798 && max > 0
2799 && current < max;
2800 if (!show)
2801 {
2802 entity.hpBar?.destroy();
2803 entity.hpBar = null;
2804 entity.hpBarCanvas = null;
2805 return;
2806 }
2807 if (!entity.hpBarCanvas)
2808 {
2809 entity.hpBarCanvas = document.createElement("canvas");
2810 entity.hpBarCanvas.width = HP_BAR_W;
2811 entity.hpBarCanvas.height = HP_BAR_H;
2812 const image = frameworkImageFromCanvas(entity.hpBarCanvas);
2813 entity.hpBar = new GameObject(0, 0, image, SORT_HP_BAR);
2814 this.#markUnlit(entity.hpBar);
2815 this.scene.addObject(entity.hpBar);
2816 }
2817 drawHpBar(entity.hpBarCanvas, current, max);
2818 invalidateCanvasTexture(this.scene, entity.hpBarCanvas);
2819 }
2820
2821 #placeHpBar (entity, pivotX, pivotY)
2822 {
2823 if (!entity.hpBar)
2824 { return; }
2825 const sprite = entity.object?.renderer?.sprite;
2826 if (!sprite)
2827 { return; }
2828 const zoom = this.zoom;
2829 const drawH = sprite.height * zoom;
2830 const centerY = pivotY - (drawH / 2 - PIVOT_FROM_BOTTOM_PX * zoom);
2831 const spriteTop = centerY - drawH / 2;
2832 const barW = HP_BAR_W * zoom;
2833 const barH = HP_BAR_H * zoom;
2834 entity.hpBar.transform.position.x = pivotX;
2835 entity.hpBar.transform.position.y = spriteTop - barH / 2;
2836 entity.hpBar.transform.size = new vector(barW, barH);
2837 entity.hpBar.layer = ySortLayer(pivotY, SORT_HP_BAR);
2838 this.#markSortDirty();
2839 }
2840
2841 #syncSkullMarker (entity)
2842 {
2843 if (!entity?.characterId)
2844 {
2845 entity.skullMarker?.destroy();
2846 entity.skullMarker = null;
2847 return;
2848 }
2849 const tint = skullTintColor(entity.skullValue | 0);
2850 if (!tint)
2851 {
2852 entity.skullMarker?.destroy();
2853 entity.skullMarker = null;
2854 return;
2855 }
2856 const image = this.game.images[SKULL_SPRITE];
2857 if (!image)
2858 { return; }
2859 if (!entity.skullMarker)
2860 {
2861 entity.skullMarker = new GameObject(0, 0, image, SORT_HP_BAR);
2862 this.scene.addObject(entity.skullMarker);
2863 }
2864 entity.skullTint = tint;
2865 entity.skullMarker.renderer.sprite = image;
2866 }
2867
2868 /**
2869 * Bottom edge of the skull sprite sits exactly on the character sprite's top edge.
2870 */
2871 #placeSkullMarker (entity, pivotX, pivotY, darkness)
2872 {
2873 this.#syncSkullMarker(entity);
2874 if (!entity.skullMarker)
2875 { return; }
2876 const body = entity.object?.renderer?.sprite;
2877 const skull = entity.skullMarker.renderer?.sprite;
2878 if (!body || !skull)
2879 { return; }
2880 const zoom = this.zoom;
2881 const scale = entity.visualScale ?? 1;
2882 const bodyH = body.height * zoom * scale;
2883 const skullH = skull.height * zoom;
2884 const skullW = skull.width * zoom;
2885 const bodyCenterY = pivotY - (bodyH / 2 - PIVOT_FROM_BOTTOM_PX * zoom * scale);
2886 const bodyTop = bodyCenterY - bodyH / 2;
2887 // GameObject position is sprite center; bottom of skull at bodyTop ⇒ center at bodyTop - skullH/2
2888 entity.skullMarker.transform.position.x = pivotX;
2889 entity.skullMarker.transform.position.y = bodyTop - skullH / 2;
2890 entity.skullMarker.transform.size = new vector(skullW, skullH);
2891 entity.skullMarker.layer = ySortLayer(pivotY, SORT_HP_BAR);
2892 this.#syncLitSprite(entity.skullMarker, darkness, 0, false, entity.skullTint);
2893 this.#markSortDirty();
2894 }
2895
2896 #rebuildChunk (snapshot, { refreshSoftNeighbors = true } = {})
2897 {
2898 this.#bakeAndPlaceChunk(snapshot);
2899 this.#relayoutChunkTiles(snapshot);
2900 if (this.softTerrain && refreshSoftNeighbors)
2901 { this.#rebuildSoftTerrainNeighborChunks(snapshot); }
2902 }
2903
2904 #relayoutChunk (snapshot)
2905 {
2906 this.#layoutBakedChunk(snapshot);
2907 this.#relayoutChunkTiles(snapshot);
2908 }
2909
2910 #relayoutChunkTiles (snapshot)
2911 {
2912 for (let localY = 0; localY < CHUNK_SIZE; localY++)
2913 {
2914 for (let localX = 0; localX < CHUNK_SIZE; localX++)
2915 {
2916 const tileX = snapshot.chunkX * CHUNK_SIZE + localX;
2917 const tileY = snapshot.chunkY * CHUNK_SIZE + localY;
2918 this.#drawTile(tileX, tileY);
2919 }
2920 }
2921 }
2922
2923 #scheduleChunkRebuild (snapshot)
2924 {
2925 if (!snapshot)
2926 { return; }
2927 this.#chunkRebuildKeys.add(`${snapshot.chunkX},${snapshot.chunkY}`);
2928 this.#cancelIdlePrefetch();
2929 this.#ensureChunkFlushScheduled();
2930 }
2931
2932 #scheduleEdgeRebuild ()
2933 {
2934 this.#edgesDirty = true;
2935 this.#cancelIdlePrefetch();
2936 this.#ensureChunkFlushScheduled();
2937 }
2938
2939 #ensureChunkFlushScheduled ()
2940 {
2941 if (this.#chunkRebuildRaf)
2942 { return; }
2943 this.#cancelIdlePrefetch();
2944 this.#chunkRebuildRaf = requestAnimationFrame(() => this.#flushChunkWork());
2945 }
2946
2947 #notePlayerTile (tileX, tileY)
2948 {
2949 const chunkX = Math.floor(tileX / CHUNK_SIZE);
2950 const chunkY = Math.floor(tileY / CHUNK_SIZE);
2951 if (this.#playerChunkX != null
2952 && (chunkX !== this.#playerChunkX || chunkY !== this.#playerChunkY))
2953 {
2954 const dx = chunkX - this.#playerChunkX;
2955 const dy = chunkY - this.#playerChunkY;
2956 if (dx !== 0)
2957 { this.#playerMoveChunkDx = Math.sign(dx); }
2958 if (dy !== 0)
2959 { this.#playerMoveChunkDy = Math.sign(dy); }
2960 }
2961 this.#playerChunkX = chunkX;
2962 this.#playerChunkY = chunkY;
2963 }
2964
2965 #playerChunkCoords ()
2966 {
2967 const local = this.entities.get(this.localEntityId);
2968 if (local)
2969 {
2970 return {
2971 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
2972 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
2973 };
2974 }
2975 if (this.#playerChunkX != null && this.#playerChunkY != null)
2976 {
2977 return { chunkX: this.#playerChunkX, chunkY: this.#playerChunkY };
2978 }
2979 return null;
2980 }
2981
2982 /** Lower score = bake sooner in urgent mode; idle mode inverts distance. */
2983 #chunkRebuildScore (key, mode = "urgent")
2984 {
2985 const [chunkX, chunkY] = key.split(",").map(Number);
2986 const player = this.#playerChunkCoords();
2987 if (!player)
2988 { return 0; }
2989 const dx = chunkX - player.chunkX;
2990 const dy = chunkY - player.chunkY;
2991 const dist = Math.abs(dx) + Math.abs(dy);
2992 let ahead = 0;
2993 if (this.#playerMoveChunkDx !== 0 || this.#playerMoveChunkDy !== 0)
2994 { ahead = dx * this.#playerMoveChunkDx + dy * this.#playerMoveChunkDy; }
2995 if (mode === "idle")
2996 {
2997 return -dist * 10 + (ahead > 0 ? -ahead * 2 : Math.max(ahead, 0));
2998 }
2999 return dist * 10 - Math.max(0, ahead) * 3;
3000 }
3001
3002 #sortedChunkRebuildKeys (mode = "urgent")
3003 {
3004 return [...this.#chunkRebuildKeys].sort((a, b) =>
3005 this.#chunkRebuildScore(a, mode) - this.#chunkRebuildScore(b, mode));
3006 }
3007
3008 #discoverUnbakedChunks ()
3009 {
3010 for (const key of this.chunks.keys())
3011 {
3012 if (!this.bakedChunks.has(key))
3013 { this.#chunkRebuildKeys.add(key); }
3014 }
3015 }
3016
3017 #hasUnbakedChunks ()
3018 {
3019 for (const key of this.chunks.keys())
3020 {
3021 if (!this.bakedChunks.has(key))
3022 { return true; }
3023 }
3024 return false;
3025 }
3026
3027 #pickIdlePrefetchSnapshot ()
3028 {
3029 let best = null;
3030 let bestScore = Infinity;
3031 for (const snapshot of this.chunks.values())
3032 {
3033 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3034 if (this.bakedChunks.has(key) || this.#chunkRebuildKeys.has(key))
3035 { continue; }
3036 const score = this.#chunkRebuildScore(key, "idle");
3037 if (score < bestScore)
3038 {
3039 bestScore = score;
3040 best = snapshot;
3041 }
3042 }
3043 return best;
3044 }
3045
3046 #cancelIdlePrefetch ()
3047 {
3048 if (this.#idlePrefetchId && typeof cancelIdleCallback === "function")
3049 { cancelIdleCallback(this.#idlePrefetchId); }
3050 this.#idlePrefetchId = 0;
3051 }
3052
3053 #scheduleIdleChunkPrefetch ()
3054 {
3055 if (this.#idlePrefetchId || this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3056 { return; }
3057 if (typeof requestIdleCallback !== "function")
3058 { return; }
3059 if (!this.#hasUnbakedChunks())
3060 { return; }
3061 this.#idlePrefetchId = requestIdleCallback(
3062 (deadline) => this.#runIdleChunkPrefetch(deadline),
3063 { timeout: 2500 }
3064 );
3065 }
3066
3067 #runIdleChunkPrefetch (deadline)
3068 {
3069 this.#idlePrefetchId = 0;
3070 if (this.#chunkRebuildRaf || this.#chunkRebuildKeys.size)
3071 { return; }
3072 this.#discoverUnbakedChunks();
3073 if (this.#chunkRebuildKeys.size)
3074 {
3075 this.#ensureChunkFlushScheduled();
3076 return;
3077 }
3078 const snapshot = this.#pickIdlePrefetchSnapshot();
3079 if (!snapshot)
3080 { return; }
3081 if (deadline.timeRemaining() <= 4 && !deadline.didTimeout)
3082 {
3083 this.#scheduleIdleChunkPrefetch();
3084 return;
3085 }
3086 this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false });
3087 if (this.#hasUnbakedChunks())
3088 { this.#scheduleIdleChunkPrefetch(); }
3089 }
3090
3091 #flushChunkWork ()
3092 {
3093 this.#chunkRebuildRaf = 0;
3094 const keys = this.#sortedChunkRebuildKeys("urgent");
3095 const batch = keys.slice(0, this.#CHUNK_REBUILD_BATCH);
3096 const rest = keys.slice(this.#CHUNK_REBUILD_BATCH);
3097 this.#chunkRebuildKeys.clear();
3098 for (const key of rest)
3099 { this.#chunkRebuildKeys.add(key); }
3100 for (const key of batch)
3101 {
3102 const snap = this.chunks.get(key);
3103 if (snap)
3104 { this.#rebuildChunk(snap, { refreshSoftNeighbors: false }); }
3105 }
3106 if (this.#chunkRebuildKeys.size)
3107 {
3108 this.#ensureChunkFlushScheduled();
3109 return;
3110 }
3111 if (this.#edgesDirty)
3112 {
3113 this.#rebuildAllEdges();
3114 this.#edgesDirty = false;
3115 }
3116 this.#scheduleIdleChunkPrefetch();
3117 }
3118
3119 #previewEqual (a, b)
3120 {
3121 if (a === b)
3122 { return true; }
3123 if (!a || !b)
3124 { return false; }
3125 return a.tileX === b.tileX
3126 && a.tileY === b.tileY
3127 && this.#previewPart(a.ground) === this.#previewPart(b.ground)
3128 && this.#previewPart(a.block) === this.#previewPart(b.block);
3129 }
3130
3131 #previewPart (value)
3132 {
3133 return value === undefined ? undefined : JSON.stringify(value);
3134 }
3135
3136 #rebuildSoftTerrainNeighborChunks (snapshot)
3137 {
3138 for (let dy = -1; dy <= 1; dy++)
3139 {
3140 for (let dx = -1; dx <= 1; dx++)
3141 {
3142 if (dx === 0 && dy === 0)
3143 { continue; }
3144 const neighbor = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3145 if (neighbor)
3146 { this.#rebuildChunk(neighbor, { refreshSoftNeighbors: false }); }
3147 }
3148 }
3149 }
3150
3151 #rebakeAllChunks ()
3152 {
3153 for (const snapshot of this.chunks.values())
3154 { this.#rebuildChunk(snapshot, { refreshSoftNeighbors: false }); }
3155 }
3156
3157 #bakeAndPlaceChunk (snapshot)
3158 {
3159 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3160 const atlases = bakeChunkAtlases({
3161 snapshot,
3162 catalog: this.catalog,
3163 images: this.game.images,
3164 preview: this.preview,
3165 season: this.worldSeason,
3166 softTerrain: this.softTerrain,
3167 resolveGround: (tileX, tileY) => this.#groundAtTile(tileX, tileY),
3168 cache: this.#atlasCache
3169 });
3170 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
3171 let baked = this.bakedChunks.get(key);
3172 this.#releaseBakedAtlasRefs(baked);
3173
3174 const groundImage = this.#atlasCache.getImage(atlases.cacheRefs?.ground);
3175 const blockImages = atlases.cacheRefs?.blockRows.map((entry) => this.#atlasCache.getImage(entry))
3176 ?? atlases.blockRows.map((canvas) => frameworkImageFromCanvas(canvas));
3177 const bloomImage = this.#atlasCache.getImage(atlases.cacheRefs?.bloom)
3178 ?? frameworkImageFromCanvas(atlases.bloom);
3179
3180 if (!baked)
3181 {
3182 const lightmapCanvas = makeLightmapCanvas(atlasPx);
3183 baked = {
3184 groundCanvas: atlases.ground,
3185 blockCanvases: atlases.blockRows,
3186 bloomCanvas: atlases.bloom,
3187 lightmapCanvas,
3188 groundImage,
3189 blockImages,
3190 bloomImage,
3191 lightmapImage: frameworkImageFromCanvas(lightmapCanvas),
3192 groundObject: null,
3193 blockObjects: [],
3194 bloomObject: null,
3195 tallBlocks: atlases.tallBlocks,
3196 animatedGrounds: atlases.animatedGrounds,
3197 lightmapPixels: null,
3198 atlasCacheRefs: atlases.cacheRefs
3199 };
3200 baked.groundObject = new GameObject(0, 0, baked.groundImage, LAYER_GROUND);
3201 this.#applyAtlasLighting(baked.groundObject, baked.lightmapImage, -1);
3202 this.scene.addObject(baked.groundObject);
3203 for (let row = 0; row < CHUNK_SIZE; row++)
3204 {
3205 const object = new GameObject(0, 0, baked.blockImages[row], SORT_BLOCK);
3206 this.#applyAtlasLighting(object, baked.lightmapImage, row);
3207 this.scene.addObject(object);
3208 baked.blockObjects.push(object);
3209 }
3210 baked.bloomObject = new GameObject(0, 0, baked.bloomImage, SORT_BLOCK);
3211 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3212 this.#markUnlit(baked.bloomObject);
3213 this.scene.addObject(baked.bloomObject);
3214 this.bakedChunks.set(key, baked);
3215 }
3216 else
3217 {
3218 if (baked.groundCanvas !== atlases.ground)
3219 {
3220 baked.groundCanvas = atlases.ground;
3221 baked.groundImage = groundImage;
3222 baked.groundObject.renderer.sprite = groundImage;
3223 }
3224 for (let row = 0; row < CHUNK_SIZE; row++)
3225 {
3226 if (baked.blockCanvases[row] !== atlases.blockRows[row])
3227 {
3228 baked.blockCanvases[row] = atlases.blockRows[row];
3229 baked.blockImages[row] = blockImages[row];
3230 baked.blockObjects[row].renderer.sprite = blockImages[row];
3231 }
3232 }
3233 if (baked.bloomCanvas !== atlases.bloom)
3234 {
3235 baked.bloomCanvas = atlases.bloom;
3236 baked.bloomImage = bloomImage;
3237 baked.bloomObject.renderer.sprite = bloomImage;
3238 }
3239 baked.tallBlocks = atlases.tallBlocks;
3240 baked.animatedGrounds = atlases.animatedGrounds;
3241 baked.atlasCacheRefs = atlases.cacheRefs;
3242 }
3243 baked.chunkX = snapshot.chunkX;
3244 baked.chunkY = snapshot.chunkY;
3245 baked.lightmapCacheKey = null;
3246 this.#invalidateNeighborLightmapCaches(snapshot.chunkX, snapshot.chunkY);
3247 this.#layoutBakedChunk(snapshot);
3248 this.#queueBakedChunkTextures(baked, snapshot.chunkX, snapshot.chunkY);
3249 }
3250
3251 #releaseBakedAtlasRefs (baked)
3252 {
3253 if (!baked?.atlasCacheRefs)
3254 { return; }
3255 this.#atlasCache.release(baked.atlasCacheRefs.ground);
3256 for (const entry of baked.atlasCacheRefs.blockRows ?? [])
3257 { this.#atlasCache.release(entry); }
3258 this.#atlasCache.release(baked.atlasCacheRefs.bloom);
3259 baked.atlasCacheRefs = null;
3260 }
3261
3262 #chunkTextureWarmPriority (chunkX, chunkY)
3263 {
3264 const local = this.entities.get(this.localEntityId);
3265 if (!local)
3266 { return 999; }
3267 const playerChunkX = Math.floor(local.tileX / CHUNK_SIZE);
3268 const playerChunkY = Math.floor(local.tileY / CHUNK_SIZE);
3269 return Math.abs(chunkX - playerChunkX) + Math.abs(chunkY - playerChunkY);
3270 }
3271
3272 #queueCanvasTextureWarm (canvas, chunkX, chunkY)
3273 {
3274 if (!canvas || this.#pendingTextureCanvasSet.has(canvas))
3275 { return; }
3276 this.#pendingTextureCanvasSet.add(canvas);
3277 this.#pendingTextureCanvases.push({
3278 canvas,
3279 priority: this.#chunkTextureWarmPriority(chunkX, chunkY)
3280 });
3281 this.#scheduleTextureWarm();
3282 }
3283
3284 #queueBakedChunkTextures (baked, chunkX, chunkY)
3285 {
3286 if (!baked)
3287 { return; }
3288 const refs = baked.atlasCacheRefs;
3289 const maybeWarm = (canvas, entry) =>
3290 {
3291 if (!canvas)
3292 { return; }
3293 if (entry && this.#atlasCache.isWarmed(canvas))
3294 { return; }
3295 this.#queueCanvasTextureWarm(canvas, chunkX, chunkY);
3296 };
3297 maybeWarm(baked.groundCanvas, refs?.ground);
3298 for (let row = 0; row < (baked.blockCanvases ?? []).length; row++)
3299 { maybeWarm(baked.blockCanvases[row], refs?.blockRows?.[row]); }
3300 maybeWarm(baked.bloomCanvas, refs?.bloom);
3301 this.#queueCanvasTextureWarm(baked.lightmapCanvas, chunkX, chunkY);
3302 }
3303
3304 #scheduleTextureWarm ()
3305 {
3306 if (this.#textureWarmRaf)
3307 { return; }
3308 this.#textureWarmRaf = requestAnimationFrame(() => this.#flushTextureWarm());
3309 }
3310
3311 #flushTextureWarm ()
3312 {
3313 this.#textureWarmRaf = 0;
3314 if (!this.#pendingTextureCanvases.length)
3315 { return; }
3316 this.#pendingTextureCanvases.sort((a, b) => a.priority - b.priority);
3317 const batch = this.#pendingTextureCanvases.splice(0, this.#TEXTURE_WARM_BATCH);
3318 for (const entry of batch)
3319 {
3320 this.#pendingTextureCanvasSet.delete(entry.canvas);
3321 setNearestFilter(this.scene, entry.canvas);
3322 this.#atlasCache.markWarmed(entry.canvas);
3323 }
3324 if (this.#pendingTextureCanvases.length)
3325 { this.#scheduleTextureWarm(); }
3326 }
3327
3328 #applyAtlasLighting (object, lightmapImage, lightRow)
3329 {
3330 if (!object?.renderer)
3331 { return; }
3332 object._lit = true;
3333 object.renderer.shader = getAtlasLightingShader();
3334 object.renderer.secondaryMap = lightmapImage;
3335 object.renderer.shaderUniforms = {
3336 u_ambientDark: 0,
3337 u_lightRow: lightRow
3338 };
3339 }
3340
3341 #layoutBakedChunk (snapshot)
3342 {
3343 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3344 const baked = this.bakedChunks.get(key);
3345 if (!baked)
3346 { return; }
3347 const size = this.tileSize();
3348 const left = snapshot.chunkX * CHUNK_SIZE * size;
3349 const top = snapshot.chunkY * CHUNK_SIZE * size;
3350 const chunkPx = CHUNK_SIZE * size;
3351 baked.groundObject.transform.position.x = left + chunkPx / 2;
3352 baked.groundObject.transform.position.y = top + chunkPx / 2;
3353 baked.groundObject.transform.size = new vector(chunkPx, chunkPx);
3354 baked.groundObject.layer = LAYER_GROUND;
3355
3356 for (let row = 0; row < CHUNK_SIZE; row++)
3357 {
3358 const object = baked.blockObjects[row];
3359 const rowY = top + row * size + size / 2;
3360 object.transform.position.x = left + chunkPx / 2;
3361 object.transform.position.y = rowY;
3362 object.transform.size = new vector(chunkPx, size);
3363 object.layer = ySortLayer(rowY, SORT_BLOCK);
3364 }
3365
3366 baked.bloomObject.transform.position.x = left + chunkPx / 2;
3367 baked.bloomObject.transform.position.y = top + chunkPx / 2;
3368 baked.bloomObject.transform.size = new vector(chunkPx, chunkPx);
3369 baked.bloomObject.layer = ySortLayer(top + chunkPx, SORT_BLOCK);
3370 baked.bloomObject.renderer.layer = RENDER_LAYER_BLOOM;
3371 this.#markSortDirty();
3372 }
3373
3374 #destroyBakedChunk (key)
3375 {
3376 const baked = this.bakedChunks.get(key);
3377 if (!baked)
3378 { return; }
3379 this.#releaseBakedAtlasRefs(baked);
3380 baked.groundObject?.destroy();
3381 for (const object of baked.blockObjects ?? [])
3382 { object.destroy(); }
3383 baked.bloomObject?.destroy();
3384 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
3385 this.bakedChunks.delete(key);
3386 }
3387
3388 #redrawPreview ()
3389 {
3390 if (!this.preview)
3391 { return; }
3392 const snapshot = this.chunks.get(`${Math.floor(this.preview.tileX / CHUNK_SIZE)},${Math.floor(this.preview.tileY / CHUNK_SIZE)}`);
3393 if (snapshot)
3394 { this.#rebuildChunk(snapshot); }
3395 }
3396
3397 #refreshWaterCoastsNear (chunkX, chunkY)
3398 {
3399 const timeSec = performance.now() / 1000;
3400 for (const objects of this.tiles.values())
3401 {
3402 if (!objects.ground || !isWaterGround(objects.groundTypeId))
3403 { continue; }
3404 if (Math.abs(objects.chunkX - chunkX) > 1 || Math.abs(objects.chunkY - chunkY) > 1)
3405 { continue; }
3406 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), timeSec);
3407 }
3408 }
3409
3410 #drawTile (tileX, tileY)
3411 {
3412 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3413 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3414 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3415 if (!snapshot)
3416 { return; }
3417 const localX = tileX - chunkX * CHUNK_SIZE;
3418 const localY = tileY - chunkY * CHUNK_SIZE;
3419 const index = localY * CHUNK_SIZE + localX;
3420 const key = `${tileX},${tileY}`;
3421 let objects = this.tiles.get(key);
3422 if (!objects)
3423 {
3424 objects = { chunkX, chunkY, tileX, tileY };
3425 this.tiles.set(key, objects);
3426 }
3427 objects.tileX = tileX;
3428 objects.tileY = tileY;
3429 objects.chunkX = chunkX;
3430 objects.chunkY = chunkY;
3431 objects.light = snapshot.light[index] ?? 0;
3432
3433 const baked = this.bakedChunks.get(`${chunkX},${chunkY}`);
3434 const animatedGround = (baked?.animatedGrounds ?? []).find((entry) => entry.tileX === tileX && entry.tileY === tileY);
3435 if (animatedGround)
3436 {
3437 objects.ground = this.#ensureSprite(objects.ground, animatedGround.sprite, LAYER_GROUND);
3438 if (objects.ground)
3439 {
3440 const size = this.tileSize();
3441 objects.ground.transform.position.x = tileX * size + size / 2;
3442 objects.ground.transform.position.y = tileY * size + size / 2;
3443 objects.ground.transform.size = new vector(size, size);
3444 objects.ground.layer = LAYER_GROUND;
3445 objects.groundTypeId = animatedGround.typeId;
3446 this.#syncGroundWaterFx(objects, this.#ambientDarkness(), performance.now() / 1000);
3447 this.#markSortDirty();
3448 }
3449 if (animatedGround.bloom)
3450 { objects.groundBloom = this.#placeBloomOverlay(objects.groundBloom, animatedGround.bloom, tilePivot(tileX, tileY, this.tileSize()), LAYER_GROUND); }
3451 else
3452 {
3453 objects.groundBloom?.destroy();
3454 objects.groundBloom = null;
3455 }
3456 }
3457 else
3458 {
3459 objects.ground?.destroy();
3460 objects.ground = null;
3461 objects.groundBloom?.destroy();
3462 objects.groundBloom = null;
3463 objects.groundTypeId = null;
3464 objects.waterEdges = null;
3465 }
3466
3467 const tileBlock = tileBlockSpriteEntry(
3468 this.catalog,
3469 this.game.images,
3470 snapshot.blocks[index],
3471 this.worldSeason
3472 );
3473 if (tileBlock)
3474 {
3475 const pivot = tilePivot(tileX, tileY, this.tileSize());
3476 objects.block = this.#ensureSprite(objects.block, tileBlock.sprite, SORT_ENTITY);
3477 if (objects.block)
3478 {
3479 this.#placePivoted(objects.block, pivot.x, pivot.y, pivot.y, SORT_ENTITY);
3480 this.#syncLitSprite(objects.block, objects.shadeAlpha ?? 0);
3481 }
3482 objects.blockBloom = this.#placeBloomOverlay(objects.blockBloom, tileBlock.bloom, pivot, SORT_ENTITY);
3483 }
3484 else
3485 {
3486 objects.block?.destroy();
3487 objects.block = null;
3488 objects.blockBloom?.destroy();
3489 objects.blockBloom = null;
3490 }
3491 }
3492
3493 #placeBloomOverlay (existing, name, pivot, sortOrder = SORT_BLOCK)
3494 {
3495 if (!name)
3496 {
3497 existing?.destroy();
3498 return null;
3499 }
3500 const object = this.#ensureSprite(existing, name, sortOrder);
3501 if (!object)
3502 { return null; }
3503 object.renderer.layer = RENDER_LAYER_BLOOM;
3504 this.#markUnlit(object);
3505 this.#placePivoted(object, pivot.x, pivot.y, pivot.y, sortOrder);
3506 return object;
3507 }
3508
3509 #placePivoted (object, pivotX, pivotY, sortY, subOrder, scale = 1)
3510 {
3511 const sprite = object?.renderer?.sprite;
3512 if (!sprite)
3513 { return; }
3514 const zoom = this.zoom;
3515 const draw = spriteDrawSize(sprite.width, sprite.height, zoom);
3516 const factor = Math.max(0.1, Number(scale) || 1);
3517 const center = spriteCenterFromPivot(pivotX, pivotY, sprite.height * factor, zoom);
3518 object.transform.position.x = center.x;
3519 object.transform.position.y = center.y;
3520 object.transform.size = new vector(draw.w * factor, draw.h * factor);
3521 object.layer = ySortLayer(sortY, subOrder);
3522 this.#markSortDirty();
3523 }
3524
3525 #ensureSprite (existing, name, layer)
3526 {
3527 const sprite = this.game.images[name];
3528 if (!sprite)
3529 {
3530 existing?.destroy();
3531 return null;
3532 }
3533 if (!existing || existing.renderer.sprite !== sprite)
3534 {
3535 existing?.destroy();
3536 existing = new GameObject(0, 0, sprite, layer);
3537 this.#syncLitSprite(existing, 0);
3538 this.scene.addObject(existing);
3539 this.#startIdleAnimation(existing);
3540 }
3541 return existing;
3542 }
3543
3544 #startIdleAnimation (object)
3545 {
3546 const sprite = object?.renderer?.sprite;
3547 if (sprite?.hasAnimationCycle?.("idle") && sprite._animationSpeed > 0)
3548 { object.renderer.setAnimation("idle", 0, sprite._animationSpeed); }
3549 }
3550
3551 #neighborClosed (snapshot, dir, dx, dy)
3552 {
3553 const other = this.chunks.get(`${snapshot.chunkX + dx},${snapshot.chunkY + dy}`);
3554 if (other)
3555 { return !other.open; }
3556 return !!snapshot.closedEdges?.[dir];
3557 }
3558
3559 #rebuildAllEdges ()
3560 {
3561 const seen = new Set();
3562 for (const snapshot of this.chunks.values())
3563 {
3564 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3565 seen.add(key);
3566 this.#rebuildChunkEdges(snapshot);
3567 }
3568 for (const key of [...this.edges.keys()])
3569 {
3570 if (!seen.has(key))
3571 { this.#destroyEdges(key); }
3572 }
3573 }
3574
3575 #rebuildChunkEdges (snapshot)
3576 {
3577 const key = `${snapshot.chunkX},${snapshot.chunkY}`;
3578 let bars = this.edges.get(key);
3579 if (!bars)
3580 {
3581 bars = {};
3582 this.edges.set(key, bars);
3583 }
3584
3585 const size = this.tileSize();
3586 const chunkPx = CHUNK_SIZE * size;
3587 const left = snapshot.chunkX * CHUNK_SIZE * size;
3588 const top = snapshot.chunkY * CHUNK_SIZE * size;
3589 const centerX = left + chunkPx / 2;
3590 const centerY = top + chunkPx / 2;
3591 const thickness = Math.max(2, Math.round(2 * this.zoom));
3592 const draw = snapshot.open === true;
3593
3594 bars.north = this.#edgeBar(bars.north, draw && this.#neighborClosed(snapshot, "north", 0, -1),
3595 centerX, top, chunkPx, thickness, true);
3596 bars.south = this.#edgeBar(bars.south, draw && this.#neighborClosed(snapshot, "south", 0, 1),
3597 centerX, top + chunkPx, chunkPx, thickness, true);
3598 bars.west = this.#edgeBar(bars.west, draw && this.#neighborClosed(snapshot, "west", -1, 0),
3599 left, centerY, chunkPx, thickness, false);
3600 bars.east = this.#edgeBar(bars.east, draw && this.#neighborClosed(snapshot, "east", 1, 0),
3601 left + chunkPx, centerY, chunkPx, thickness, false);
3602 }
3603
3604 #edgeBar (existing, visible, x, y, length, thickness, horizontal)
3605 {
3606 if (!visible)
3607 {
3608 if (existing)
3609 { existing.renderer.visible = false; }
3610 return existing;
3611 }
3612
3613 existing = this.#ensureSprite(existing, "chunk-edge", LAYER_EDGE);
3614 this.#markUnlit(existing);
3615 existing.renderer.visible = true;
3616 existing.transform.position.x = x;
3617 existing.transform.position.y = y;
3618 existing.transform.size = horizontal
3619 ? new vector(length, thickness)
3620 : new vector(thickness, length);
3621 existing.layer = LAYER_EDGE;
3622 this.#markSortDirty();
3623 return existing;
3624 }
3625
3626 #destroyEdges (key)
3627 {
3628 const bars = this.edges.get(key);
3629 if (!bars)
3630 { return; }
3631 bars.north?.destroy();
3632 bars.east?.destroy();
3633 bars.south?.destroy();
3634 bars.west?.destroy();
3635 this.edges.delete(key);
3636 }
3637
3638 #entityShadeAlpha (entity, now)
3639 {
3640 const toAlpha = this.tiles.get(`${entity.tileX},${entity.tileY}`)?.shadeAlpha ?? 0;
3641 if (entity.lerpStarted == null || entity.shadeFromTileX == null || entity.shadeFromTileY == null)
3642 { return toAlpha; }
3643 const fromAlpha = this.tiles.get(`${entity.shadeFromTileX},${entity.shadeFromTileY}`)?.shadeAlpha ?? 0;
3644 const t = Math.min(1, (now - entity.lerpStarted) / Math.max(1, entity.lerpMs ?? 1));
3645 return fromAlpha + (toAlpha - fromAlpha) * t;
3646 }
3647
3648 #markSortDirty ()
3649 {
3650 this.scene._sortDirty = true;
3651 }
3652
3653 /** Player chunk for dynamic lighting; null in editor / before spawn → no 3×3 limit. */
3654 #activeLightingCenterChunk ()
3655 {
3656 const local = this.entities.get(this.localEntityId);
3657 if (!local)
3658 { return null; }
3659 return {
3660 chunkX: Math.floor(local.tileX / CHUNK_SIZE),
3661 chunkY: Math.floor(local.tileY / CHUNK_SIZE)
3662 };
3663 }
3664
3665 #isActiveLightingChunk (chunkX, chunkY)
3666 {
3667 const center = this.#activeLightingCenterChunk();
3668 if (!center)
3669 { return true; }
3670 return Math.abs(chunkX - center.chunkX) <= 1 && Math.abs(chunkY - center.chunkY) <= 1;
3671 }
3672
3673 #isActiveLightingTile (tileX, tileY)
3674 {
3675 return this.#isActiveLightingChunk(
3676 Math.floor(tileX / CHUNK_SIZE),
3677 Math.floor(tileY / CHUNK_SIZE)
3678 );
3679 }
3680
3681 /** Dynamic light sources that originate inside the player 3×3 (never from the outer ring). */
3682 #innerDynamicLights (activeLights)
3683 {
3684 return activeLights.filter((light) => this.#isActiveLightingTile(light.tileX, light.tileY));
3685 }
3686
3687 /**
3688 * Lights to simulate for one chunk: inner chunks get all inner sources; outer ring
3689 * chunks only receive inner sources close enough to reach the chunk bounds.
3690 */
3691 #dynamicLightsForChunk (chunkX, chunkY, activeLights)
3692 {
3693 const center = this.#activeLightingCenterChunk();
3694 if (!center)
3695 { return activeLights; }
3696 const inner = this.#innerDynamicLights(activeLights);
3697 if (this.#isActiveLightingChunk(chunkX, chunkY))
3698 { return inner; }
3699 return inner.filter((light) => this.#lightAffectsChunkBounds(light, chunkX, chunkY));
3700 }
3701
3702 #dynamicLightsForTile (tileX, tileY, activeLights)
3703 {
3704 return this.#dynamicLightsForChunk(
3705 Math.floor(tileX / CHUNK_SIZE),
3706 Math.floor(tileY / CHUNK_SIZE),
3707 activeLights
3708 );
3709 }
3710
3711 #updateShade ()
3712 {
3713 const ambientDark = this.#ambientDarkness();
3714 const now = performance.now();
3715 this.dynamicLights = this.dynamicLights.filter((light) => light.until > now);
3716
3717 const activeLights = [...this.dynamicLights];
3718 for (const light of this.spellLights.values())
3719 {
3720 if (light.until <= now)
3721 { continue; }
3722 activeLights.push({
3723 tileX: light.tileX,
3724 tileY: light.tileY,
3725 range: light.range,
3726 intensity: light.intensity
3727 });
3728 }
3729 for (const key of [...this.spellLights.keys()])
3730 {
3731 if (this.spellLights.get(key).until <= now)
3732 { this.spellLights.delete(key); }
3733 }
3734 const activeDarks = [];
3735 for (const dark of this.spellDarks.values())
3736 {
3737 if (dark.until <= now)
3738 { continue; }
3739 activeDarks.push({
3740 tileX: dark.tileX,
3741 tileY: dark.tileY,
3742 range: dark.range,
3743 intensity: dark.intensity
3744 });
3745 }
3746 for (const key of [...this.spellDarks.keys()])
3747 {
3748 if (this.spellDarks.get(key).until <= now)
3749 { this.spellDarks.delete(key); }
3750 }
3751 this._activeSpellDarks = activeDarks;
3752 const tileSize = this.tileSize();
3753 const blindLight = this.#blindVisionLight();
3754 if (blindLight)
3755 { activeLights.push(blindLight); }
3756 for (const entity of this.entities.values())
3757 {
3758 const range = entity.lightRadiusTiles ?? 0;
3759 if (range <= 0)
3760 { continue; }
3761 activeLights.push({
3762 tileX: Math.floor(entity.visualX / tileSize),
3763 tileY: Math.floor(entity.visualY / tileSize),
3764 range,
3765 intensity: 1
3766 });
3767 }
3768
3769 const lightOcclusion = makeSnapshotLightOcclusion(this.chunks);
3770
3771 for (const objects of this.tiles.values())
3772 {
3773 if (objects._inViewport === false)
3774 { continue; }
3775 const lights = this.#dynamicLightsForTile(objects.tileX, objects.tileY, activeLights);
3776 const intensity = this.#tileLightIntensity(objects, lights, lightOcclusion);
3777 objects.shadeAlpha = ambientDark * (1 - intensity);
3778 }
3779
3780 for (const baked of this.bakedChunks.values())
3781 {
3782 if (baked._inViewport === false)
3783 { continue; }
3784 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3785 this.#writeChunkLightmap(baked, lights, lightOcclusion);
3786 if (baked.groundObject?.renderer?.shaderUniforms)
3787 { baked.groundObject.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3788 for (const object of baked.blockObjects ?? [])
3789 {
3790 if (object?.renderer?.shaderUniforms)
3791 { object.renderer.shaderUniforms.u_ambientDark = ambientDark; }
3792 }
3793 }
3794
3795 const timeSec = now / 1000;
3796 for (const objects of this.tiles.values())
3797 {
3798 if (objects._inViewport === false)
3799 { continue; }
3800 if (objects.block)
3801 { this.#syncLitSprite(objects.block, objects.shadeAlpha); }
3802 if (objects.ground && isWaterGround(objects.groundTypeId))
3803 {
3804 const baked = this.bakedChunks.get(`${objects.chunkX},${objects.chunkY}`);
3805 this.#syncGroundWaterFx(objects, ambientDark, timeSec, baked);
3806 }
3807 else if (objects.ground)
3808 { this.#syncLitSprite(objects.ground, objects.shadeAlpha); }
3809 }
3810
3811 for (const item of this.groundItems.values())
3812 {
3813 const alpha = this.tiles.get(`${item.tileX},${item.tileY}`)?.shadeAlpha ?? 0;
3814 this.#syncGroundItemSprite(item, alpha);
3815 }
3816 }
3817
3818 #tileLightIntensity (objects, activeLights, lightOcclusion)
3819 {
3820 const baked = lightIntensity(objects.light ?? 0);
3821 const dynamic = dynamicLightAtTile(
3822 objects.tileX,
3823 objects.tileY,
3824 activeLights,
3825 lightOcclusion
3826 );
3827 const dark = dynamicDarknessAtTile(
3828 objects.tileX,
3829 objects.tileY,
3830 this._activeSpellDarks ?? [],
3831 lightOcclusion
3832 );
3833 return Math.max(0, Math.max(baked, dynamic) - dark);
3834 }
3835
3836 /** Baked + dynamic light intensity (0–1) for any world tile, including across chunks. */
3837 #intensityAtTile (tileX, tileY, activeLights, lightOcclusion)
3838 {
3839 const tileObjects = this.tiles.get(`${tileX},${tileY}`);
3840 if (tileObjects)
3841 { return this.#tileLightIntensity(tileObjects, activeLights, lightOcclusion); }
3842 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3843 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3844 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3845 if (!snapshot)
3846 { return 0; }
3847 const localX = tileX - chunkX * CHUNK_SIZE;
3848 const localY = tileY - chunkY * CHUNK_SIZE;
3849 const index = localY * CHUNK_SIZE + localX;
3850 const bakedLit = lightIntensity(snapshot.light[index] ?? 0);
3851 const dynamic = dynamicLightAtTile(tileX, tileY, activeLights, lightOcclusion);
3852 const dark = dynamicDarknessAtTile(tileX, tileY, this._activeSpellDarks ?? [], lightOcclusion);
3853 return Math.max(0, Math.max(bakedLit, dynamic) - dark);
3854 }
3855
3856 /** True when ground or block on this tile occludes light rays (same rules as bake). */
3857 #tileOccludesLight (tileX, tileY)
3858 {
3859 const chunkX = Math.floor(tileX / CHUNK_SIZE);
3860 const chunkY = Math.floor(tileY / CHUNK_SIZE);
3861 const snapshot = this.chunks.get(`${chunkX},${chunkY}`);
3862 if (!snapshot)
3863 { return false; }
3864 const localX = tileX - chunkX * CHUNK_SIZE;
3865 const localY = tileY - chunkY * CHUNK_SIZE;
3866 if (localX < 0 || localY < 0 || localX >= CHUNK_SIZE || localY >= CHUNK_SIZE)
3867 { return false; }
3868 const index = localY * CHUNK_SIZE + localX;
3869 if (Array.isArray(snapshot.occlusion) && snapshot.occlusion.length > index)
3870 { return (snapshot.occlusion[index] | 0) >= LightOcclusion.solid; }
3871 const ground = normalizeGround(snapshot.grounds?.[index]);
3872 if (!isGroundPassable(ground.typeId))
3873 { return true; }
3874 return isBlockOccludingLight(snapshot.blocks?.[index]?.typeId ?? null);
3875 }
3876
3877 #fillChunkLightGrids (baked, activeLights, lightOcclusion)
3878 {
3879 const gridW = CHUNK_SIZE + 2;
3880 const gridSize = gridW * gridW;
3881 if (!baked.lightIntensityGrid || baked.lightIntensityGrid.length !== gridSize)
3882 { baked.lightIntensityGrid = new Float32Array(gridSize); }
3883 if (!baked.lightOccludeGrid || baked.lightOccludeGrid.length !== gridSize)
3884 { baked.lightOccludeGrid = new Uint8Array(gridSize); }
3885 const grid = baked.lightIntensityGrid;
3886 const occlude = baked.lightOccludeGrid;
3887 for (let ly = -1; ly <= CHUNK_SIZE; ly++)
3888 {
3889 for (let lx = -1; lx <= CHUNK_SIZE; lx++)
3890 {
3891 const tileX = baked.chunkX * CHUNK_SIZE + lx;
3892 const tileY = baked.chunkY * CHUNK_SIZE + ly;
3893 const gi = (ly + 1) * gridW + (lx + 1);
3894 grid[gi] = this.#intensityAtTile(tileX, tileY, activeLights, lightOcclusion);
3895 occlude[gi] = this.#tileOccludesLight(tileX, tileY) ? 1 : 0;
3896 }
3897 }
3898 return { grid, occlude, gridW };
3899 }
3900
3901 #makeLightCornerSampler (grid, occlude, gridW)
3902 {
3903 const sample = (lx, ly) => grid[(ly + 1) * gridW + (lx + 1)];
3904 const blocks = (lx, ly) => occlude[(ly + 1) * gridW + (lx + 1)] !== 0;
3905 const openSample = (lx, ly) => (blocks(lx, ly) ? 0 : sample(lx, ly));
3906 const smoothCorner = (homeLx, homeLy, aLx, aLy, bLx, bLy, dLx, dLy) =>
3907 {
3908 const home = sample(homeLx, homeLy);
3909 if (blocks(homeLx, homeLy))
3910 { return home; }
3911 let sum = home;
3912 let count = 1;
3913 sum += openSample(aLx, aLy);
3914 count += 1;
3915 sum += openSample(bLx, bLy);
3916 count += 1;
3917 if (!blocks(aLx, aLy) && !blocks(bLx, bLy))
3918 {
3919 sum += openSample(dLx, dLy);
3920 count += 1;
3921 }
3922 return sum / count;
3923 };
3924 return { smoothCorner };
3925 }
3926
3927 /** Corner lit intensities (0–1) for one tile — matches baked atlas lightmap corners. */
3928 #tileLitCorners (baked, localX, localY)
3929 {
3930 const grid = baked?.lightIntensityGrid;
3931 const occlude = baked?.lightOccludeGrid;
3932 if (!grid?.length || !occlude?.length)
3933 { return null; }
3934 const gridW = CHUNK_SIZE + 2;
3935 const { smoothCorner } = this.#makeLightCornerSampler(grid, occlude, gridW);
3936 return {
3937 nw: smoothCorner(
3938 localX, localY,
3939 localX - 1, localY,
3940 localX, localY - 1,
3941 localX - 1, localY - 1
3942 ),
3943 ne: smoothCorner(
3944 localX, localY,
3945 localX + 1, localY,
3946 localX, localY - 1,
3947 localX + 1, localY - 1
3948 ),
3949 sw: smoothCorner(
3950 localX, localY,
3951 localX - 1, localY,
3952 localX, localY + 1,
3953 localX - 1, localY + 1
3954 ),
3955 se: smoothCorner(
3956 localX, localY,
3957 localX + 1, localY,
3958 localX, localY + 1,
3959 localX + 1, localY + 1
3960 )
3961 };
3962 }
3963
3964 #hashUint8Array (values)
3965 {
3966 let hash = 2166136261;
3967 for (let i = 0; i < values.length; i++)
3968 {
3969 hash ^= values[i];
3970 hash = Math.imul(hash, 16777619);
3971 }
3972 return hash >>> 0;
3973 }
3974
3975 #lightAffectsChunkBounds (light, chunkX, chunkY)
3976 {
3977 const minX = chunkX * CHUNK_SIZE - 1;
3978 const minY = chunkY * CHUNK_SIZE - 1;
3979 const maxX = chunkX * CHUNK_SIZE + CHUNK_SIZE;
3980 const maxY = chunkY * CHUNK_SIZE + CHUNK_SIZE;
3981 const closestX = Math.max(minX, Math.min(light.tileX, maxX));
3982 const closestY = Math.max(minY, Math.min(light.tileY, maxY));
3983 return Math.hypot(light.tileX - closestX, light.tileY - closestY) <= light.range;
3984 }
3985
3986 #chunkLightmapCacheKey (baked, activeLights)
3987 {
3988 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
3989 if (!snapshot?.light)
3990 { return null; }
3991 const bakedHash = this.#hashUint8Array(snapshot.light);
3992 const lights = this.#dynamicLightsForChunk(baked.chunkX, baked.chunkY, activeLights);
3993 if (!lights.length)
3994 { return `i:${bakedHash}`; }
3995 const mode = this.lightingMode === "simple" ? "s" : "f";
3996 let lightsKey = "";
3997 for (const light of lights)
3998 {
3999 if (!this.#lightAffectsChunkBounds(light, baked.chunkX, baked.chunkY))
4000 { continue; }
4001 lightsKey += `${light.tileX},${light.tileY},${light.range},${light.intensity ?? 1};`;
4002 }
4003 return `a:${mode}:${bakedHash}:${lightsKey}`;
4004 }
4005
4006 #invalidateNeighborLightmapCaches (chunkX, chunkY)
4007 {
4008 // Halo grid is ±1 tile; outer map ring is ±2 chunks from the player.
4009 for (let dy = -2; dy <= 2; dy++)
4010 {
4011 for (let dx = -2; dx <= 2; dx++)
4012 {
4013 const baked = this.bakedChunks.get(`${chunkX + dx},${chunkY + dy}`);
4014 if (baked)
4015 { baked.lightmapCacheKey = null; }
4016 }
4017 }
4018 }
4019
4020 /**
4021 * Per-chunk lightmap for atlas ground/blocks. Open tiles blend into open neighbours;
4022 * occluding tiles stay flat and contribute 0 into others so light does not bleed
4023 * through a wall to the far side. Diagonals only when both cardinals are clear.
4024 */
4025 #writeChunkLightmap (baked, activeLights, lightOcclusion)
4026 {
4027 const snapshot = this.chunks.get(`${baked.chunkX},${baked.chunkY}`);
4028 if (!snapshot)
4029 { return; }
4030 const cacheKey = this.#chunkLightmapCacheKey(baked, activeLights);
4031 if (cacheKey && baked.lightmapCacheKey === cacheKey)
4032 { return; }
4033 const atlasPx = CHUNK_SIZE * SPRITE_SIZE_PX;
4034 const pixelCount = atlasPx * atlasPx * 4;
4035 if (!baked.lightmapPixels || baked.lightmapPixels.length !== pixelCount)
4036 { baked.lightmapPixels = new Uint8ClampedArray(pixelCount); }
4037 const pixels = baked.lightmapPixels;
4038
4039 this.#fillChunkLightGrids(baked, activeLights, lightOcclusion);
4040 const simple = this.lightingMode === "simple";
4041
4042 for (let localY = 0; localY < CHUNK_SIZE; localY++)
4043 {
4044 for (let localX = 0; localX < CHUNK_SIZE; localX++)
4045 {
4046 const baseX = localX * SPRITE_SIZE_PX;
4047 const baseY = localY * SPRITE_SIZE_PX;
4048 if (simple)
4049 {
4050 const gridW = CHUNK_SIZE + 2;
4051 const intensity = baked.lightIntensityGrid?.[(localY + 1) * gridW + (localX + 1)] ?? 0;
4052 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4053 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4054 {
4055 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4056 {
4057 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4058 pixels[offset] = value;
4059 pixels[offset + 1] = value;
4060 pixels[offset + 2] = value;
4061 pixels[offset + 3] = 255;
4062 }
4063 }
4064 continue;
4065 }
4066 const corners = this.#tileLitCorners(baked, localX, localY);
4067 const nw = corners.nw;
4068 const ne = corners.ne;
4069 const sw = corners.sw;
4070 const se = corners.se;
4071 for (let py = 0; py < SPRITE_SIZE_PX; py++)
4072 {
4073 const v = (py + 0.5) / SPRITE_SIZE_PX;
4074 const left = nw + (sw - nw) * v;
4075 const right = ne + (se - ne) * v;
4076 for (let px = 0; px < SPRITE_SIZE_PX; px++)
4077 {
4078 const u = (px + 0.5) / SPRITE_SIZE_PX;
4079 const intensity = left + (right - left) * u;
4080 const value = Math.round(Math.min(1, Math.max(0, intensity)) * 255);
4081 const offset = ((baseY + py) * atlasPx + (baseX + px)) * 4;
4082 pixels[offset] = value;
4083 pixels[offset + 1] = value;
4084 pixels[offset + 2] = value;
4085 pixels[offset + 3] = 255;
4086 }
4087 }
4088 }
4089 }
4090 const ctx = baked.lightmapCanvas.getContext("2d");
4091 ctx.putImageData(new ImageData(pixels, atlasPx, atlasPx), 0, 0);
4092 invalidateCanvasTexture(this.scene, baked.lightmapCanvas);
4093 this.#queueCanvasTextureWarm(baked.lightmapCanvas, baked.chunkX, baked.chunkY);
4094 baked.lightmapCacheKey = cacheKey;
4095 }
4096
4097 #updateSwipes (now)
4098 {
4099 this.swipes = this.swipes.filter((swipe) =>
4100 {
4101 if (swipe.lerp && swipe.started != null)
4102 {
4103 const durationMs = swipe.durationMs ?? 400;
4104 const t = Math.min(1, (now - swipe.started) / durationMs);
4105 const fromPivot = this.#projectileLaunchPoint(
4106 swipe.attackerId ?? null,
4107 swipe.fromTileX,
4108 swipe.fromTileY
4109 );
4110 const toPivot = this.#projectileEndPivot(swipe);
4111 const x = fromPivot.x + (toPivot.x - fromPivot.x) * t;
4112 const y = fromPivot.y + (toPivot.y - fromPivot.y) * t;
4113 const sortY = Math.max(fromPivot.y, toPivot.y) + 0.02;
4114 if (swipe.object?.transform)
4115 {
4116 swipe.object.transform.rotation = Math.atan2(
4117 toPivot.y - fromPivot.y,
4118 toPivot.x - fromPivot.x
4119 ) * (180 / Math.PI);
4120 }
4121 if (swipe.spellProjectile && swipe.baseSprite)
4122 {
4123 const frame = Math.floor((now - swipe.started) / SPELL_PROJECTILE_FRAME_MS) % 3;
4124 const image = this.#spellProjectileImage(swipe.baseSprite, frame);
4125 if (image && swipe.object?.renderer)
4126 { swipe.object.renderer.sprite = image; }
4127 }
4128 this.#placePivoted(swipe.object, x, y, sortY, SORT_FX);
4129 if (!swipe.spellProjectile)
4130 {
4131 this.#applyPhysicalCombatFxDarkness(
4132 swipe.object,
4133 swipe.fromTileX,
4134 swipe.fromTileY,
4135 swipe.tileX,
4136 swipe.tileY,
4137 swipe.dualTint ?? null
4138 );
4139 }
4140 }
4141 else if (swipe.fromTileX != null && !swipe.spellProjectile)
4142 {
4143 this.#applyPhysicalCombatFxDarkness(
4144 swipe.object,
4145 swipe.fromTileX,
4146 swipe.fromTileY,
4147 swipe.tileX,
4148 swipe.tileY,
4149 swipe.dualTint ?? null
4150 );
4151 }
4152 if (swipe.until > now)
4153 { return true; }
4154 const onImpact = swipe.onImpact;
4155 swipe.onImpact = null;
4156 swipe.object?.destroy();
4157 if (typeof onImpact === "function")
4158 {
4159 try
4160 { onImpact(); }
4161 catch (_)
4162 { /* presentation only */ }
4163 }
4164 return false;
4165 });
4166 }
4167
4168 #projectileEndPivot (swipe)
4169 {
4170 if (swipe.trackTarget && swipe.targetId != null)
4171 { return this.#projectileAimPoint(swipe.targetId, swipe.tileX, swipe.tileY); }
4172 return this.#projectileAimPoint(null, swipe.tileX, swipe.tileY);
4173 }
4174
4175 /**
4176 * Launch point: 4px below the top of the caster sprite (falls back to tile centre).
4177 */
4178 #projectileLaunchPoint (entityId, tileX, tileY)
4179 {
4180 const entity = entityId != null ? this.entities.get(entityId) : null;
4181 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4182 {
4183 const zoom = this.zoom;
4184 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4185 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4186 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4187 const topY = pivotY - (spriteH - PIVOT_FROM_BOTTOM_PX) * zoom;
4188 return {
4189 x: pivotX,
4190 y: topY + PROJECTILE_LAUNCH_FROM_TOP_PX * zoom
4191 };
4192 }
4193 return tilePivot(tileX, tileY, this.tileSize());
4194 }
4195
4196 /**
4197 * Aim point: sprite centre for creatures, tile centre for tile targets.
4198 */
4199 #projectileAimPoint (entityId, tileX, tileY)
4200 {
4201 const entity = entityId != null ? this.entities.get(entityId) : null;
4202 if (entity && Number.isFinite(entity.visualX) && Number.isFinite(entity.visualY))
4203 {
4204 const zoom = this.zoom;
4205 const spriteH = entity.object?.renderer?.sprite?.height ?? SPRITE_SIZE_PX;
4206 const pivotX = entity.visualX + (entity.stackOffsetX ?? 0);
4207 const pivotY = entity.visualY + (entity.stackOffsetY ?? 0);
4208 return spriteCenterFromPivot(pivotX, pivotY, spriteH, zoom);
4209 }
4210 return tilePivot(tileX, tileY, this.tileSize());
4211 }
4212
4213 #updateDamageNumbers (now)
4214 {
4215 const layer = this.damageNumbersEl;
4216 if (!layer)
4217 { return; }
4218 this.damageFloats = this.damageFloats.filter((entry) =>
4219 {
4220 const elapsed = now - entry.started;
4221 if (elapsed >= DAMAGE_FLOAT_MS)
4222 {
4223 entry.element?.remove();
4224 return false;
4225 }
4226 const entity = this.entities.get(entry.entityId);
4227 if (!entity)
4228 {
4229 entry.element?.remove();
4230 return false;
4231 }
4232 if (!entry.element)
4233 {
4234 entry.element = document.createElement("span");
4235 entry.element.className = "damage-number";
4236 entry.element.textContent = String(entry.damage);
4237 layer.append(entry.element);
4238 }
4239 const anchor = this.nametagAnchor(entity);
4240 if (!anchor)
4241 { return true; }
4242 const t = elapsed / DAMAGE_FLOAT_MS;
4243 entry.element.style.left = `${anchor.x}px`;
4244 entry.element.style.top = `${anchor.y - 6 - t * 28}px`;
4245 entry.element.style.opacity = String(1 - t);
4246 return true;
4247 });
4248 }
4249
4250 #updateSkillLevelFloats (now)
4251 {
4252 const layer = this.skillLevelFloatsEl;
4253 if (!layer)
4254 { return; }
4255 this.skillLevelFloats = this.skillLevelFloats.filter((entry) =>
4256 {
4257 const elapsed = now - entry.started;
4258 if (elapsed >= SKILL_LEVEL_FLOAT_MS)
4259 {
4260 entry.element?.remove();
4261 return false;
4262 }
4263 const entity = this.entities.get(entry.entityId);
4264 if (!entity)
4265 {
4266 entry.element?.remove();
4267 return false;
4268 }
4269 if (!entry.element)
4270 {
4271 const root = document.createElement("div");
4272 root.className = "skill-level-float";
4273
4274 const levelEl = document.createElement("div");
4275 levelEl.className = "skill-level-float-level";
4276 levelEl.textContent = `↑${entry.level}↑`;
4277
4278 const icon = document.createElement("img");
4279 icon.className = "skill-level-float-icon";
4280 icon.src = entry.icon;
4281 icon.alt = entry.displayName || "";
4282
4283 root.append(levelEl, icon);
4284 entry.element = root;
4285 layer.append(entry.element);
4286 }
4287 const anchor = this.nametagAnchor(entity);
4288 if (!anchor)
4289 { return true; }
4290 const t = elapsed / SKILL_LEVEL_FLOAT_MS;
4291 entry.element.style.left = `${anchor.x}px`;
4292 entry.element.style.top = `${anchor.y - 10 - t * 18}px`;
4293 entry.element.style.opacity = String(Math.max(0, 1 - t * 0.85));
4294 return true;
4295 });
4296 }
4297
4298 #syncBloomLayer ()
4299 {
4300 if (!this.bloomEnabled)
4301 {
4302 this.scene.setLayers([{ name: "default" }]);
4303 return;
4304 }
4305 const settings = this.settings ?? DEFAULT_WORLD_SETTINGS;
4306 this.scene.setLayers([
4307 { name: "default" },
4308 {
4309 name: RENDER_LAYER_BLOOM,
4310 composite: "add",
4311 postShaders: Shader.getBloomPostChain({
4312 threshold: settings.bloomThreshold,
4313 softKnee: settings.bloomSoftKnee,
4314 intensity: settings.bloomIntensity,
4315 blurSize: settings.bloomBlurSize,
4316 saturation: settings.bloomSaturation,
4317 colorPreserve: settings.bloomColorPreserve,
4318 dilate: settings.bloomDilate,
4319 scales: Math.max(1, Math.round(settings.bloomScales ?? 1)),
4320 halfRes: (settings.bloomHalfRes ?? 1) >= 0.5
4321 })
4322 }
4323 ]);
4324 }
4325}
4326
4327export function nightFactor (hour, nightDarkness = 0.72)
4328{
4329 const peak = Math.min(1, Math.max(0, nightDarkness));
4330 if (hour >= 8 && hour <= 16)
4331 { return 0; }
4332 if (hour >= 22 || hour <= 5)
4333 { return peak; }
4334 if (hour < 8)
4335 { return lerp(peak, 0, (hour - 5) / 3); }
4336 return lerp(0, peak, (hour - 16) / 6);
4337}
4338
4339function bodySpriteName (sex)
4340{
4341 const key = sex === "female" ? "player-body-female" : "player-body-male";
4342 return spriteImageName("character", key, key);
4343}
4344
4345function lerp (a, b, t)
4346{
4347 return a + (b - a) * Math.min(1, Math.max(0, t));
4348}
4349
4350function makeLightmapCanvas (size)
4351{
4352 const canvas = document.createElement("canvas");
4353 canvas.width = size;
4354 canvas.height = size;
4355 return canvas;
4356}
4357
4358function copyCanvas (source, dest)
4359{
4360 const ctx = dest.getContext("2d");
4361 ctx.imageSmoothingEnabled = false;
4362 ctx.clearRect(0, 0, dest.width, dest.height);
4363 ctx.drawImage(source, 0, 0);
4364}
4365
4366function drawHpBar (canvas, current, max)
4367{
4368 const ctx = canvas.getContext("2d");
4369 ctx.clearRect(0, 0, HP_BAR_W, HP_BAR_H);
4370 ctx.fillStyle = "#000000";
4371 ctx.fillRect(0, 0, HP_BAR_W, HP_BAR_H);
4372 const ratio = max > 0 ? Math.max(0, Math.min(1, current / max)) : 0;
4373 const fillW = Math.round(12 * ratio);
4374 if (fillW > 0)
4375 {
4376 ctx.fillStyle = "#ff0000";
4377 ctx.fillRect(1, 1, fillW, 2);
4378 }
4379}