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