import { CHUNK_SIZE, SPRITE_SIZE_PX } from "/shared/protocol/constants.js"; import { GROUND_DEFINITIONS, BLOCK_DEFINITIONS, GroundType, normalizeGround, normalizeBlock, isChunkAtlasBakedBlock, isLiquidWaterGround } from "/shared/definitions/tiles.js"; import { bloomImageName, spriteImageName } from "/shared/definitions/tileSprites.js"; import { resolveSeasonalVisualState, SeasonId } from "/shared/world/season.js"; import { SOFT_TERRAIN_NEIGHBOR_DIRS, softTerrainBlendWeight, softTerrainNeighborSample, mixSoftTerrainPixel } from "/shared/render/softTerrain.js"; import { WET_SAND_BAND_FRACTION, WET_SAND_NEIGHBOR_DIRS, wetSandWetness, mixWetSandPixel } from "/shared/render/wetSand.js"; import { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js"; /** * Bake immobile ≤16×16 ground/block/bloom tiles into chunk atlases. * Oversized or animated blocks/grounds are returned for individual sprites. * When `cache` is set, identical ground/row/bloom layouts reuse canvases already in GPU memory. * @param {{ * snapshot: object, * catalog: object, * images: object, * preview?: object | null, * season?: string, * softTerrain?: boolean, * wetSandBandFraction?: number, * resolveGround?: (tileX: number, tileY: number) => object | number | null, * cache?: ReturnType * }} options */ export function bakeChunkAtlases ({ snapshot, catalog, images, preview = null, season = SeasonId.summer, softTerrain = false, wetSandBandFraction = WET_SAND_BAND_FRACTION, resolveGround = null, cache = null }) { const extras = collectChunkSpriteExtras({ snapshot, catalog, images, preview, season }); const keys = computeChunkAtlasKeys({ snapshot, catalog, preview, season, softTerrain, wetSandBandFraction, resolveGround }); const bakeCtx = { snapshot, catalog, images, preview, season, softTerrain, wetSandBandFraction, resolveGround }; let groundEntry; let blockRowEntries; let bloomEntry; if (cache) { groundEntry = cache.acquireGround(keys.groundKey, () => bakeGroundCanvas(bakeCtx)); blockRowEntries = keys.blockRowKeys.map((key, row) => cache.acquireBlockRow(key, () => bakeBlockRowCanvas(bakeCtx, row))); bloomEntry = cache.acquireBloom(keys.bloomKey, () => bakeBloomCanvas(bakeCtx)); } else { groundEntry = { canvas: bakeGroundCanvas(bakeCtx) }; blockRowEntries = keys.blockRowKeys.map((_key, row) => ({ canvas: bakeBlockRowCanvas(bakeCtx, row) })); bloomEntry = { canvas: bakeBloomCanvas(bakeCtx) }; } return { ground: groundEntry.canvas, blockRows: blockRowEntries.map((entry) => entry.canvas), bloom: bloomEntry.canvas, tallBlocks: extras.tallBlocks, animatedGrounds: extras.animatedGrounds, cacheRefs: cache ? { ground: groundEntry, blockRows: blockRowEntries, bloom: bloomEntry } : null }; } export { computeChunkAtlasKeys } from "/shared/render/chunkAtlasKeys.js"; export function collectChunkSpriteExtras ({ snapshot, catalog, images, preview = null, season = SeasonId.summer }) { const tallBlocks = []; const animatedGrounds = []; const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const index = localY * CHUNK_SIZE + localX; const tileX = baseTileX + localX; const tileY = baseTileY + localY; const groundEntry = tileGroundEntry(snapshot, preview, localX, localY); const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index); const groundName = groundSpriteName(catalog, groundEntry, season); const groundMeta = groundCatalogMeta(catalog, groundEntry); if (groundName && !isBakeable(images[groundName], groundMeta)) { animatedGrounds.push({ tileX, tileY, sprite: groundName, typeId: normalizeGround(groundEntry).typeId, bloom: groundBloomName(catalog, groundEntry, season) }); } const blockName = blockSpriteName(catalog, blockEntry, season); if (!blockName) { continue; } const blockMeta = blockCatalogMeta(catalog, blockEntry); if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry)) { tallBlocks.push({ tileX, tileY, sprite: blockName, bloom: blockBloomName(catalog, blockEntry, season) }); } } } return { tallBlocks, animatedGrounds }; } /** * Per-tile block sprite when the block is not represented in the chunk atlas row. * @returns {{ sprite: string, bloom: string | null } | null} */ export function tileBlockSpriteEntry (catalog, images, blockEntry, season = SeasonId.summer) { if (!blockEntry) { return null; } const blockName = blockSpriteName(catalog, blockEntry, season); if (!blockName) { return null; } const blockMeta = blockCatalogMeta(catalog, blockEntry); const bakeable = isBakeable(images[blockName], blockMeta); if (bakeable && isChunkAtlasBakedBlock(blockEntry)) { return null; } return { sprite: blockName, bloom: blockBloomName(catalog, blockEntry, season) }; } function bakeGroundCanvas ({ snapshot, catalog, images, preview, season, softTerrain, wetSandBandFraction = WET_SAND_BAND_FRACTION, resolveGround }) { const width = CHUNK_SIZE * SPRITE_SIZE_PX; const height = CHUNK_SIZE * SPRITE_SIZE_PX; const ground = makeCanvas(width, height); const groundCtx = ground.getContext("2d", { willReadFrequently: true }); groundCtx.imageSmoothingEnabled = false; groundCtx.clearRect(0, 0, width, height); const pixelCache = new Map(); const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; const wetBand = Math.max(0, Number(wetSandBandFraction) || 0); for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const tileX = baseTileX + localX; const tileY = baseTileY + localY; const groundEntry = tileGroundEntry(snapshot, preview, localX, localY); const dx = localX * SPRITE_SIZE_PX; const dy = localY * SPRITE_SIZE_PX; const groundName = groundSpriteName(catalog, groundEntry, season); const groundMeta = groundCatalogMeta(catalog, groundEntry); if (!isBakeable(images[groundName], groundMeta)) { continue; } const wetShore = wetBand > 0 && isWetShoreGround(groundEntry); const blendable = softTerrain && isGroundBlendable(groundEntry); if (wetShore || blendable) { blitBlendedGround( groundCtx, images, catalog, groundEntry, groundName, dx, dy, tileX, tileY, season, resolveGround, pixelCache, { softTerrain: blendable, wetShore, wetSandBandFraction: wetBand } ); } else { blit(groundCtx, images[groundName], dx, dy); } } } return ground; } function bakeBlockRowCanvas ({ snapshot, catalog, images, preview, season }, row) { const width = CHUNK_SIZE * SPRITE_SIZE_PX; const canvas = makeCanvas(width, SPRITE_SIZE_PX); const ctx = canvas.getContext("2d"); ctx.imageSmoothingEnabled = false; ctx.clearRect(0, 0, width, SPRITE_SIZE_PX); const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; for (let localX = 0; localX < CHUNK_SIZE; localX++) { const index = row * CHUNK_SIZE + localX; const tileX = baseTileX + localX; const tileY = baseTileY + row; const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index); const blockName = blockSpriteName(catalog, blockEntry, season); if (!blockName) { continue; } const blockMeta = blockCatalogMeta(catalog, blockEntry); if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry)) { continue; } blit(ctx, images[blockName], localX * SPRITE_SIZE_PX, 0); } return canvas; } function bakeBloomCanvas ({ snapshot, catalog, images, preview, season }) { const width = CHUNK_SIZE * SPRITE_SIZE_PX; const bloom = makeCanvas(width, width); const bloomCtx = bloom.getContext("2d"); bloomCtx.imageSmoothingEnabled = false; bloomCtx.clearRect(0, 0, width, width); const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const index = localY * CHUNK_SIZE + localX; const tileX = baseTileX + localX; const tileY = baseTileY + localY; const dx = localX * SPRITE_SIZE_PX; const dy = localY * SPRITE_SIZE_PX; const groundEntry = tileGroundEntry(snapshot, preview, localX, localY); const blockEntry = tileBlockEntry(snapshot, preview, tileX, tileY, index); const groundBloom = groundBloomName(catalog, groundEntry, season); if (groundBloom) { blit(bloomCtx, images[groundBloom], dx, dy); } const blockName = blockSpriteName(catalog, blockEntry, season); if (!blockName) { continue; } const blockMeta = blockCatalogMeta(catalog, blockEntry); if (!isBakeable(images[blockName], blockMeta) || !isChunkAtlasBakedBlock(blockEntry)) { continue; } const blockBloom = blockBloomName(catalog, blockEntry, season); if (blockBloom) { blit(bloomCtx, images[blockBloom], dx, dy); } } } return bloom; } export function isBakeable (sprite, meta = null) { if (!sprite?.g_image) { return false; } if (sprite.width > SPRITE_SIZE_PX || sprite.height > SPRITE_SIZE_PX) { return false; } if (meta?.proceduralWaves) { return false; } const frames = Number(sprite.subImages) || Number(sprite.subImgTotal) || (meta?.frames ?? 1); const speed = sprite._animationSpeed ?? meta?.animationSpeed ?? 0; if (frames > 1) { return false; } if (speed > 0) { return false; } return true; } function tileGroundEntry (snapshot, preview, localX, localY) { const index = localY * CHUNK_SIZE + localX; const baseTileX = snapshot.chunkX * CHUNK_SIZE; const baseTileY = snapshot.chunkY * CHUNK_SIZE; const tileX = baseTileX + localX; const tileY = baseTileY + localY; let groundEntry = snapshot.grounds[index]; if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.ground !== undefined) { groundEntry = preview.ground; } return groundEntry; } function tileBlockEntry (snapshot, preview, tileX, tileY, index) { let blockEntry = snapshot.blocks[index]; if (preview && preview.tileX === tileX && preview.tileY === tileY && preview.block !== undefined) { blockEntry = preview.block; } return blockEntry; } function makeCanvas (width, height) { const canvas = document.createElement("canvas"); canvas.width = width; canvas.height = height; return canvas; } function blit (ctx, sprite, dx, dy) { if (!sprite?.g_image) { return; } const sub = sprite.getSubImage(0); ctx.drawImage( sprite.g_image, sub.sx, sub.sy, sub.sw, sub.sh, dx, dy, SPRITE_SIZE_PX, SPRITE_SIZE_PX ); } function isGroundBlendable (ground) { const entry = normalizeGround(ground); return !!GROUND_DEFINITIONS[entry.typeId]?.blendable; } function isWetShoreGround (ground) { const entry = normalizeGround(ground); return !!GROUND_DEFINITIONS[entry.typeId]?.wetShore; } function wetShoreSpriteName (catalog, ground) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId]; if (!def?.wetShore) { return null; } const wetState = `${def.key}-wet`; const states = catalog.grounds?.[def.key]?.states ?? []; if (!states.includes(wetState)) { return null; } return spriteImageName("ground", def.key, wetState); } function groundVisualKey (catalog, ground, season) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const states = catalog.grounds?.[def.key]?.states ?? []; const state = resolveSeasonalVisualState(states, entry.state, season); return `${entry.typeId}:${state ?? ""}`; } function blitBlendedGround ( ctx, images, catalog, groundEntry, groundName, dx, dy, tileX, tileY, season, resolveGround, pixelCache, { softTerrain = false, wetShore = false, wetSandBandFraction = WET_SAND_BAND_FRACTION } = {} ) { const dryPixels = spritePixels(images[groundName], pixelCache); if (!dryPixels) { blit(ctx, images[groundName], dx, dy); return; } const wetBand = Math.max(0, Number(wetSandBandFraction) || 0); const waterDirs = []; if (wetShore && wetBand > 0) { for (const { ndx, ndy } of WET_SAND_NEIGHBOR_DIRS) { const neighborGround = resolveNeighborGround( tileX + ndx, tileY + ndy, resolveGround ); if (neighborGround == null) { continue; } const typeId = normalizeGround(neighborGround).typeId; if (!isLiquidWaterGround(typeId, season)) { continue; } waterDirs.push({ ndx, ndy }); } } const wetName = wetShore && waterDirs.length ? wetShoreSpriteName(catalog, groundEntry) : null; const wetPixels = wetName ? spritePixels(images[wetName], pixelCache) : null; const selfKey = groundVisualKey(catalog, groundEntry, season); const neighborSprites = []; if (softTerrain) { for (const { ndx, ndy } of SOFT_TERRAIN_NEIGHBOR_DIRS) { const neighborGround = resolveNeighborGround( tileX + ndx, tileY + ndy, resolveGround ); if (neighborGround == null) { continue; } if (groundVisualKey(catalog, neighborGround, season) === selfKey) { continue; } // Never soft-blend land into procedural/liquid water — that pulls the noise sheet into the rim. const nbrTypeId = normalizeGround(neighborGround).typeId; const nbrDef = GROUND_DEFINITIONS[nbrTypeId]; if (nbrDef?.proceduralWaves || isLiquidWaterGround(nbrTypeId, season)) { continue; } const neighborName = groundSpriteName(catalog, neighborGround, season); const pixels = spritePixels(images[neighborName], pixelCache); if (!pixels) { continue; } neighborSprites.push({ ndx, ndy, pixels, neighborBlendable: isGroundBlendable(neighborGround) }); } } if (!waterDirs.length && !neighborSprites.length) { blit(ctx, images[groundName], dx, dy); return; } const out = ctx.createImageData(SPRITE_SIZE_PX, SPRITE_SIZE_PX); const dst = out.data; for (let py = 0; py < SPRITE_SIZE_PX; py++) { for (let px = 0; px < SPRITE_SIZE_PX; px++) { let self = readPixel(dryPixels, px, py); if (wetPixels && waterDirs.length) { const wetness = wetSandWetness(px, py, waterDirs, SPRITE_SIZE_PX, wetBand); if (wetness > 0) { self = mixWetSandPixel(self, readPixel(wetPixels, px, py), wetness); } } const contribs = []; for (const neighbor of neighborSprites) { const weight = softTerrainBlendWeight(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX, { neighborBlendable: neighbor.neighborBlendable }); if (weight <= 0) { continue; } const sample = softTerrainNeighborSample(px, py, neighbor.ndx, neighbor.ndy, SPRITE_SIZE_PX); contribs.push({ weight, color: readPixel(neighbor.pixels, sample.sx, sample.sy) }); } const mixed = mixSoftTerrainPixel(self, contribs); const i = (py * SPRITE_SIZE_PX + px) * 4; dst[i] = mixed.r; dst[i + 1] = mixed.g; dst[i + 2] = mixed.b; dst[i + 3] = mixed.a; } } ctx.putImageData(out, dx, dy); } function resolveNeighborGround (tileX, tileY, resolveGround) { if (typeof resolveGround === "function") { return resolveGround(tileX, tileY); } return null; } function spritePixels (sprite, cache) { if (!sprite?.g_image) { return null; } const key = sprite.g_image?.src ?? sprite; if (cache?.has(key)) { return cache.get(key); } const sub = sprite.getSubImage(0); const canvas = makeCanvas(SPRITE_SIZE_PX, SPRITE_SIZE_PX); const ctx = canvas.getContext("2d", { willReadFrequently: true }); ctx.imageSmoothingEnabled = false; ctx.drawImage( sprite.g_image, sub.sx, sub.sy, sub.sw, sub.sh, 0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX ); const data = ctx.getImageData(0, 0, SPRITE_SIZE_PX, SPRITE_SIZE_PX); cache?.set(key, data); return data; } function readPixel (imageData, x, y) { const i = (y * imageData.width + x) * 4; const d = imageData.data; return { r: d[i], g: d[i + 1], b: d[i + 2], a: d[i + 3] }; } function groundSpriteName (catalog, ground, season = SeasonId.summer) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const states = catalog.grounds?.[def.key]?.states ?? []; const state = resolveSeasonalVisualState(states, entry.state, season); return spriteImageName("ground", def.key, state); } function blockSpriteName (catalog, block, season = SeasonId.summer) { const entry = normalizeBlock(block); if (!entry) { return null; } const def = BLOCK_DEFINITIONS[entry.typeId]; if (!def || def.editorHidden) { return null; } const states = catalog.blocks?.[def.key]?.states ?? []; const state = resolveSeasonalVisualState(states, entry.state, season); return spriteImageName("block", def.key, state); } function groundBloomName (catalog, ground, season = SeasonId.summer) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const type = catalog.grounds?.[def.key]; const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season); if (!state || !type?.blooms?.[state]) { return null; } return bloomImageName("ground", def.key, state); } function blockBloomName (catalog, block, season = SeasonId.summer) { const entry = normalizeBlock(block); if (!entry) { return null; } const def = BLOCK_DEFINITIONS[entry.typeId]; if (!def) { return null; } const type = catalog.blocks?.[def.key]; const state = resolveSeasonalVisualState(type?.states ?? [], entry.state, season); if (!state || !type?.blooms?.[state]) { return null; } return bloomImageName("block", def.key, state); } function blockCatalogMeta (catalog, block) { const entry = normalizeBlock(block); if (!entry) { return null; } const def = BLOCK_DEFINITIONS[entry.typeId]; if (!def) { return null; } return catalog.blocks?.[def.key] ?? null; } function groundCatalogMeta (catalog, ground) { const entry = normalizeGround(ground); const def = GROUND_DEFINITIONS[entry.typeId] ?? GROUND_DEFINITIONS[GroundType.grass]; const catalogMeta = catalog.grounds?.[def.key] ?? {}; return { frames: catalogMeta.frames ?? def.frames, animationSpeed: catalogMeta.animationSpeed ?? def.animationSpeed, proceduralWaves: !!def.proceduralWaves }; }