feat: add perlin noise

This commit is contained in:
2026-04-05 18:21:43 +08:00
parent 5ce0810294
commit 23affb78b5
10 changed files with 150 additions and 15 deletions

View File

@@ -1,6 +1,8 @@
#include <Cubed/gameplay/chunk.hpp>
#include <Cubed/gameplay/world.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/perlin_noise.hpp>
Chunk::Chunk(World& world, ChunkPos chunk_pos) :
m_world(world),
m_chunk_pos(chunk_pos)
@@ -18,15 +20,19 @@ const std::vector<uint8_t>& Chunk::get_chunk_blocks() const{
int Chunk::get_index(int x, int y, int z) {
return x * CHUCK_SIZE * CHUCK_SIZE + y * CHUCK_SIZE + z;
if ((x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z < 0 || (x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z >= CHUCK_SIZE * CHUCK_SIZE * WORLD_SIZE_Y) {
Logger::error("block pos x {} y {} z {} range error", x, y, z);
CUBED_ASSERT(0);
}
return (x * WORLD_SIZE_Y + y) * CHUCK_SIZE + z;
}
void Chunk::gen_vertex_data() {
m_vertexs_data.clear();
glDeleteBuffers(1, &m_vbo);
for (int x = 0; x < CHUCK_SIZE; x++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
for (int y = 0; y < CHUCK_SIZE; y++) {
for (int y = 0; y < WORLD_SIZE_Y; y++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
int world_x = x + m_chunk_pos.x * CHUCK_SIZE;
int world_z = z + m_chunk_pos.z * CHUCK_SIZE;
int world_y = y;
@@ -73,7 +79,7 @@ const std::vector<Vertex>& Chunk::get_vertex_data() const{
}
void Chunk::init_chunk() {
m_blocks.assign(CHUCK_SIZE * CHUCK_SIZE * CHUCK_SIZE, 0);
m_blocks.assign(CHUCK_SIZE * CHUCK_SIZE * WORLD_SIZE_Y, 0);
for (int x = 0; x < CHUCK_SIZE; x++) {
for (int y = 0; y < 5; y++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
@@ -81,6 +87,26 @@ void Chunk::init_chunk() {
}
}
}
for (int x = 0; x < CHUCK_SIZE; x++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
float world_x = static_cast<float>(x + m_chunk_pos.x * CHUCK_SIZE);
float world_z = static_cast<float>(z + m_chunk_pos.z * CHUCK_SIZE);
float noise =
0.5f * PerlinNoise::noise(world_x * 0.01f, world_z * 0.01f, 0.5f) +
0.25f * PerlinNoise::noise(world_x * 0.02f, world_z * 0.02f, 0.5f) +
0.125f * PerlinNoise::noise(world_x * 0.04f, world_z * 0.04f, 0.5f);
int y_max = height * noise;
for (int y = 5; y < y_max; y++) {
m_blocks[get_index(x, y, z)] = 1;
}
}
}
}