Files
voxel/Chunk.cs
2025-09-03 00:37:42 +02:00

134 lines
3.9 KiB
C#

namespace Voxel
{
public class Chunk
{
public static int Size = 16;
public static int Height = 256;
public readonly int PositionX;
public readonly int PositionY;
private Dictionary<ushort, BlockData> _blockData;
private Blocks[] _blocks;
public Chunk(int positionX, int positionY)
{
PositionX = positionX;
PositionY = positionY;
_blockData = new Dictionary<ushort, BlockData>();
_blocks = new Blocks[Size * Size * Height];
Initialize();
}
public void SetBlock(int x, int y, int z, Blocks block)
{
int i = GetBlockIndex(x, y, z);
_blocks[i] = block;
}
public void SetBlockIndex(int i, Blocks block)
{
_blocks[i] = block;
}
public Blocks GetBlock(int x, int y, int z)
{
int i = GetBlockIndex(x, y, z);
return _blocks[i];
}
public BlockData GetBlockData(int x, int y, int z)
{
return new BlockData();
}
private void Initialize()
{
for (int i = 0; i < Size * Size; i++)
_blocks[i] = Blocks.Bedrock;
for (int i = Size * Size * 1; i < Size * Size * 15; i++)
_blocks[i] = Blocks.Stone;
for (int i = Size * Size * 15; i < Size * Size * 16; i++)
_blocks[i] = Blocks.Grass;
}
// todo
public (int x, int y, int z) IndexToPosition(int i)
{
int x = 0;
int y = 0;
int z = 0;
return (x, y, z);
}
private int GetBlockIndex(int x, int y, int z)
{
if (x < 0 || x > 15 || y < 0 || y > 255 || z < 0 || z > 15)
return 0;
return x + z * Size + y * Size * Size;
}
private static readonly (int dx, int dy, int dz)[] Offsets = new (int, int, int)[6]
{
( 1, 0, 0), // +X
(-1, 0, 0), // -X
( 0, 1, 0), // +Y
( 0, -1, 0), // -Y
( 0, 0, 1), // +Z
( 0, 0, -1) // -Z
};
public ChunkMesh GetChunkMesh()
{
ChunkMesh chunkMesh = new ChunkMesh(Size * Size * Height / 2);
// offsets table
for (int x = 0; x < Size; x++)
{
for (int z = 0; z < Size; z++)
{
for (int y = 0; y < Height; y++)
{
for (byte face = 0; face < 6; face++)
{
int indexBase = y * Size * Size + z * Size + x;
Blocks block = _blocks[indexBase];
if (block == Blocks.Air) continue; // ignore if air
int nx = x + Offsets[face].dx;
int ny = y + Offsets[face].dy;
int nz = z + Offsets[face].dz;
// check neighbor, ignore if at chunk edge
if (nx >= 0 && nx < Size &&
ny >= 0 && ny < Height &&
nz >= 0 && nz < Size &&
_blocks[GetBlockIndex(nx, ny, nz)] != 0)
continue;
FaceData faceData = new FaceData();
faceData.Facing = (Orientation)face;
faceData.Texture = BlockDefinitions.Blocks[block].FaceTextures[face];
faceData.X = (byte)x;
faceData.Y = (byte)y;
faceData.Z = (byte)z;
chunkMesh.Faces.Add(faceData);
}
}
}
}
return chunkMesh;
}
}
}