BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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