fix: reimplement view culling (5def8fb1)

This commit is contained in:
trafficlunar 2024-12-17 20:43:22 +00:00
parent ec1afe39e4
commit 0321afa65f
2 changed files with 39 additions and 18 deletions

View file

@ -25,28 +25,11 @@ function Blocks({ blocks, setBlocks, textures, image, imageDimensions, coords, s
const tilemapRef = useRef<CompositeTilemap>();
const findClosestBlock = (r: number, g: number, b: number, a: number) => {
let closestBlock = "";
let closestDistance = Infinity;
Object.entries(blocksData).forEach(([block, rgba]) => {
const distance = Math.sqrt(Math.pow(r - rgba[0], 2) + Math.pow(g - rgba[1], 2) + Math.pow(b - rgba[2], 2) + Math.pow(a - rgba[3], 3));
if (distance < closestDistance) {
closestDistance = distance;
closestBlock = block;
}
});
return closestBlock;
};
const tileBlocks = () => {
if (!tilemapRef.current) return;
const tilemap = tilemapRef.current;
tilemap.clear();
console.log(tilemap.texturesPerTilemap);
blocks.forEach((block) => {
tilemap.tile(textures[block.name] ?? missingTexture, block.x * 16, block.y * 16);
});
@ -81,6 +64,21 @@ function Blocks({ blocks, setBlocks, textures, image, imageDimensions, coords, s
tilemapRef.current.scale.set(scale, scale);
}, [coords, scale]);
const findClosestBlock = (r: number, g: number, b: number, a: number) => {
let closestBlock = "";
let closestDistance = Infinity;
Object.entries(blocksData).forEach(([block, rgba]) => {
const distance = Math.sqrt(Math.pow(r - rgba[0], 2) + Math.pow(g - rgba[1], 2) + Math.pow(b - rgba[2], 2) + Math.pow(a - rgba[3], 3));
if (distance < closestDistance) {
closestDistance = distance;
closestBlock = block;
}
});
return closestBlock;
};
useEffect(() => {
if (!image) return;

View file

@ -65,6 +65,29 @@ function Canvas() {
};
}, [blocks]);
const visibleArea = useMemo(() => {
const blockSize = 16 * scale;
const visibleWidthBlocks = Math.ceil(stageSize.width / blockSize);
const visibleHeightBlocks = Math.ceil(stageSize.height / blockSize);
const startX = Math.floor(-coords.x / blockSize);
const startY = Math.floor(-coords.y / blockSize);
return {
startX,
startY,
endX: startX + visibleWidthBlocks + 1,
endY: startY + visibleHeightBlocks + 1,
};
}, [coords, scale, stageSize]);
const visibleBlocks = useMemo(() => {
return blocks.filter(
(block) => block.x >= visibleArea.startX && block.x < visibleArea.endX && block.y >= visibleArea.startY && block.y < visibleArea.endY
);
}, [blocks, visibleArea]);
const zoomToMousePosition = useCallback(
(newScale: number) => {
setCoords({
@ -242,7 +265,7 @@ function Canvas() {
onClick={onClick}
>
<Blocks
blocks={blocks}
blocks={visibleBlocks}
setBlocks={setBlocks}
textures={textures}
image={image}