/** Authored block lights (torches, furnaces, …) for dynamic lighting / combat. */ import { CHUNK_SIZE } from "../protocol/constants.js"; import { BLOCK_DEFINITIONS, blockLightRange } from "../definitions/tiles.js"; let cachedMaxRange = null; /** Max `lightRangeTiles` across block defs (cached). */ export function maxBlockLightRangeTiles () { if (cachedMaxRange != null) { return cachedMaxRange; } let max = 0; for (const def of Object.values(BLOCK_DEFINITIONS)) { max = Math.max(max, def.lightRangeTiles ?? 0); } cachedMaxRange = max; return max; } /** * Collect block light sources from one chunk's blocks array (row-major, CHUNK_SIZE²). * @returns {Array<{ tileX: number, tileY: number, range: number }>} */ export function collectBlockLightSources (chunkX, chunkY, blocks) { const sources = []; if (!Array.isArray(blocks) || blocks.length < CHUNK_SIZE * CHUNK_SIZE) { return sources; } for (let localY = 0; localY < CHUNK_SIZE; localY++) { for (let localX = 0; localX < CHUNK_SIZE; localX++) { const block = blocks[localY * CHUNK_SIZE + localX]; const range = blockLightRange(block?.typeId ?? null); if (range > 0) { sources.push({ tileX: chunkX * CHUNK_SIZE + localX, tileY: chunkY * CHUNK_SIZE + localY, range }); } } } return sources; } /** * Block lights in chunks that can reach (tileX, tileY). * @param {(chunkX: number, chunkY: number) => { blocks?: any[] }|null|undefined} loadChunk */ export function blockLightSourcesNearTile (loadChunk, tileX, tileY, maxRange = maxBlockLightRangeTiles()) { const range = Math.max(0, maxRange | 0); const halo = Math.ceil(range / CHUNK_SIZE) + 1; const centerX = Math.floor(tileX / CHUNK_SIZE); const centerY = Math.floor(tileY / CHUNK_SIZE); const sources = []; for (let dy = -halo; dy <= halo; dy++) { for (let dx = -halo; dx <= halo; dx++) { const chunkX = centerX + dx; const chunkY = centerY + dy; const data = loadChunk(chunkX, chunkY); if (!data?.blocks) { continue; } sources.push(...collectBlockLightSources(chunkX, chunkY, data.blocks)); } } return sources; }