BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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