voxel-test/src/world/chunk.zig

90 lines
2.3 KiB
Zig
Raw Normal View History

2024-09-09 18:05:14 +01:00
const std = @import("std");
const raylib = @cImport({
2024-09-09 18:07:36 +01:00
@cInclude("raylib.h");
2024-09-09 18:05:14 +01:00
});
const A7r = std.mem.Allocator;
pub const Chunk = struct {
tiles: []i32,
a7r: A7r,
pub fn init(a7r: A7r) !Chunk {
return Chunk{
.a7r = a7r,
.tiles = try a7r.alloc(i32, 32 * 32 * 32),
};
}
pub fn deinit(self: Chunk) void {
self.a7r.free(self.tiles);
}
pub fn getTile(self: Chunk, x: u5, y: u5, z: u5) i32 {
return self.tiles[@as(u15, x) << 10 | @as(u15, y) << 5 | @as(u15, z)];
}
pub fn setTile(self: Chunk, x: u5, y: u5, z: u5, tile: i32) void {
self.tiles[@as(u15, x) << 10 | @as(u15, y) << 5 | @as(u15, z)] = tile;
}
pub fn createMesh(_: Chunk) raylib.Mesh {
const triangle_count: u32 = 1;
const arr_size: c_uint = triangle_count * 3 * @sizeOf(f32);
const vertices: [*]f32 = @ptrCast(@alignCast(raylib.MemAlloc(arr_size * 3)));
const texcoords: [*]f32 = @ptrCast(@alignCast(raylib.MemAlloc(arr_size * 2)));
const normals: [*]f32 = @ptrCast(@alignCast(raylib.MemAlloc(arr_size * 3)));
vertices[0] = 0.0;
vertices[1] = 0.0;
vertices[2] = 0.0;
normals[0] = 0.0;
normals[1] = 1.0;
normals[2] = 0.0;
texcoords[0] = 0.0;
texcoords[1] = 0.0;
vertices[3] = 1.0;
vertices[4] = 0.0;
vertices[5] = 2.0;
normals[3] = 0.0;
normals[4] = 1.0;
normals[5] = 0.0;
texcoords[2] = 0.5;
texcoords[3] = 1.0;
vertices[6] = 2.0;
vertices[7] = 0.0;
vertices[8] = 0.0;
normals[6] = 0.0;
normals[7] = 1.0;
normals[8] = 0.0;
texcoords[4] = 1.0;
texcoords[5] = 0.0;
var mesh = raylib.Mesh{
.triangleCount = triangle_count,
.vertexCount = triangle_count * 3,
.vertices = vertices,
.texcoords = texcoords,
.texcoords2 = null,
.normals = normals,
.tangents = null,
.colors = null,
.indices = null,
.animVertices = null,
.animNormals = null,
.boneIds = null,
.boneWeights = null,
.vaoId = 0,
.vboId = null,
};
raylib.UploadMesh(@ptrCast(&mesh), false);
return mesh;
}
};