BlueGit

timfa questward

Files

questward / client / src / render / worldView.js

worldView.js

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