feat: add ChunkGenerator

This commit is contained in:
2026-04-26 14:10:09 +08:00
parent a3eb19e58f
commit c5a78185ba
15 changed files with 523 additions and 336 deletions

View File

@@ -95,6 +95,7 @@ add_executable(${PROJECT_NAME}
src/dev_panel.cpp src/dev_panel.cpp
src/gameplay/biome.cpp src/gameplay/biome.cpp
src/gameplay/chunk.cpp src/gameplay/chunk.cpp
src/gameplay/chunk_generator.cpp
src/gameplay/player.cpp src/gameplay/player.cpp
src/gameplay/tree.cpp src/gameplay/tree.cpp
src/gameplay/world.cpp src/gameplay/world.cpp

View File

@@ -20,6 +20,7 @@ enum class Biome {
NONE NONE
}; };
struct BiomeHeightRange { struct BiomeHeightRange {
int base_y; int base_y;
int amplitude; int amplitude;
@@ -31,6 +32,13 @@ struct BiomeNonAdjacent {
Biome replace; Biome replace;
}; };
static inline const std::vector<BiomeNonAdjacent> NON_ADJACENT {{
{Biome::PLAIN, {Biome::NONE}, Biome::PLAIN},
{Biome::FOREST, {Biome::DESERT}, Biome::PLAIN},
{Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN},
{Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN}
}};
struct BaseBiomeParams { struct BaseBiomeParams {
Biome biome; Biome biome;
std::pair<float, float> temp; std::pair<float, float> temp;

View File

@@ -6,6 +6,7 @@
#include <Cubed/config.hpp> #include <Cubed/config.hpp>
#include <Cubed/primitive_data.hpp> #include <Cubed/primitive_data.hpp>
#include <Cubed/gameplay/biome.hpp> #include <Cubed/gameplay/biome.hpp>
#include <Cubed/gameplay/chunk_generator.hpp>
#include <Cubed/gameplay/chunk_pos.hpp> #include <Cubed/gameplay/chunk_pos.hpp>
#include <Cubed/gameplay/block.hpp> #include <Cubed/gameplay/block.hpp>
@@ -20,21 +21,16 @@ private:
static constexpr int SIZE_Y = WORLD_SIZE_Y; static constexpr int SIZE_Y = WORLD_SIZE_Y;
static constexpr int SIZE_Z = CHUCK_SIZE; static constexpr int SIZE_Z = CHUCK_SIZE;
static inline const std::vector<BiomeNonAdjacent> NON_ADJACENT {{
{Biome::PLAIN, {Biome::NONE}, Biome::PLAIN},
{Biome::FOREST, {Biome::DESERT}, Biome::PLAIN},
{Biome::DESERT, {Biome::MOUNTAIN, Biome::FOREST}, Biome::PLAIN},
{Biome::MOUNTAIN, {Biome::DESERT}, Biome::PLAIN}
}
};
using HeightMapArray = std::array<std::array<float, SIZE_Z>, SIZE_X>; using HeightMapArray = std::array<std::array<float, SIZE_Z>, SIZE_X>;
std::atomic<bool> m_dirty {false}; std::atomic<bool> m_dirty {false};
std::atomic<bool> m_need_upload{true}; std::atomic<bool> m_need_upload{true};
std::atomic<bool> m_is_on_gen_vertex_data {false}; std::atomic<bool> m_is_on_gen_vertex_data {false};
std::atomic<size_t> m_vertex_sum = 0; std::atomic<size_t> m_vertex_sum = 0;
std::atomic<Biome> m_biome = Biome::PLAIN;
std::mutex m_vertexs_data_mutex; std::mutex m_vertexs_data_mutex;
std::atomic<Biome> m_biome = Biome::PLAIN; std::unique_ptr<ChunkGenerator> m_generator;
ChunkPos m_chunk_pos; ChunkPos m_chunk_pos;
World& m_world; World& m_world;
HeightMapArray m_heightmap; HeightMapArray m_heightmap;
@@ -57,25 +53,25 @@ public:
Chunk& operator=(Chunk&&) noexcept; Chunk& operator=(Chunk&&) noexcept;
Biome get_biome() const; Biome get_biome() const;
ChunkPos get_chunk_pos() const;
const std::vector<uint8_t>& get_chunk_blocks() const; const std::vector<uint8_t>& get_chunk_blocks() const;
HeightMapArray get_heightmap() const; HeightMapArray get_heightmap() const;
static int get_index(int x, int y, int z); static int get_index(int x, int y, int z);
static int get_index(const glm::vec3& pos); static int get_index(const glm::vec3& pos);
// Init Chunk // Init Chunk
// Generate Biome // Determine biome from temperature and humidity noise
void gen_phase_one(); void gen_phase_one();
// Adjust Biome // Resolve biome adjacency conflicts with neighbor chunks
void gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks); void gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks);
// Generate Heightmap // Generate heightmap using biome-specific noise
void gen_phase_three(); void gen_phase_three();
// Adjust Height // Blend heightmap with neighbors for smooth transitions
void gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap); void gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap);
// Generate Block // Generate terrain blocks from heightmap and biome
void gen_phase_five(); void gen_phase_five();
// Adjust Block; // Blend surface blocks at chunk borders with neighbors
void gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block); void gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block);
// Generate Structure // Generate biome-specific vegetation/structures
void gen_phase_seven(); void gen_phase_seven();
//void gen_vertex_data(); //void gen_vertex_data();
// 0 : (1, 0) // 0 : (1, 0)
@@ -96,6 +92,11 @@ public:
void set_chunk_block(int index, unsigned id); void set_chunk_block(int index, unsigned id);
ChunkPos chunk_pos() const;
Biome biome() const;
void biome(Biome b);
HeightMapArray& heightmap();
std::vector<uint8_t>& blocks();
}; };

View File

@@ -0,0 +1,50 @@
#pragma once
#include <Cubed/constants.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <atomic>
#include <optional>
namespace Cubed {
class Chunk;
class ChunkGenerator {
static constexpr int SIZE_X = CHUCK_SIZE;
static constexpr int SIZE_Y = WORLD_SIZE_Y;
static constexpr int SIZE_Z = CHUCK_SIZE;
using HeightMapArray = std::array<std::array<float, CHUCK_SIZE>, CHUCK_SIZE>;
public:
ChunkGenerator(Chunk& chunk);
static void init();
static void reload();
static const unsigned& seed();
static void seed(unsigned s);
// Generate Biome
void assign_chunk_biome();
// Adjust Biome
void resolve_biome_adjacency_conflict(const std::array<const Chunk*, 4>& adj_chunks);
// Generate Heightmap
void generate_heightmap();
// Adjust Height
void blend_heightmap_boundaries(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap);
// Generate Block
void generate_terrain_blocks();
// Adjust Block;
void blend_surface_blocks_borders(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block);
// Generate Structure
void generate_vegetation();
private:
static inline std::atomic<bool> is_init {false};
static inline unsigned m_generator_seed {0};
static inline std::atomic<bool> is_seed_change {false};
Chunk& m_chunk;
Random m_random;
};
}

View File

@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <string_view> #include <string_view>
#include <cstdint>
namespace Cubed { namespace Cubed {
@@ -8,7 +8,26 @@ namespace HASH {
inline std::size_t str(std::string_view value) { inline std::size_t str(std::string_view value) {
return std::hash<std::string_view>{}(value); return std::hash<std::string_view>{}(value);
} }
inline uint32_t mix_hash(int32_t a, int32_t b, uint32_t fixed_seed) {
uint32_t h = fixed_seed;
h ^= (uint32_t)a * 0xcc9e2d51u;
h = (h << 15) | (h >> 17); // rotl 15
h *= 0x1b873593u;
h ^= (uint32_t)b * 0xcc9e2d51u;
h = (h << 15) | (h >> 17); // rotl 15
h *= 0x1b873593u;
// Finalizationavalanche
h ^= h >> 16;
h *= 0x85ebca6bu;
h ^= h >> 13;
h *= 0xc2b2ae35u;
h ^= h >> 16;
return h;
}
} }
} }

View File

@@ -4,16 +4,15 @@ namespace Cubed {
class Random { class Random {
public: public:
static unsigned get_base_seed(); Random();
static unsigned get_thread_seed();
static Random& get();
bool random_bool(double probability); bool random_bool(double probability);
std::mt19937& engine(); std::mt19937& engine();
unsigned seed(); unsigned seed();
void init(unsigned seed);
private: private:
Random();
unsigned int m_seed = 0; unsigned int m_seed = 0;
std::mt19937 m_engine; std::mt19937 m_engine;
}; };

View File

@@ -7,16 +7,12 @@ namespace Cubed {
class PerlinNoise { class PerlinNoise {
public: public:
static void init(); static void init(unsigned seed);
static float noise(float x, float y, float z); static float noise(float x, float y, float z);
static void reload(); static void reload(unsigned seed);
static const unsigned& seed();
static void seed(unsigned seed);
private: private:
static inline std::atomic<bool> is_init = false; static inline std::atomic<bool> is_init = false;
static inline std::vector<int> p; static inline std::vector<int> p;
static inline unsigned m_seed = 0;
static inline bool is_seed_change = false;
static float fade(float t); static float fade(float t);
static float lerp(float t, float a, float b); static float lerp(float t, float a, float b);
static float grad(int hash, float x, float y, float z); static float grad(int hash, float x, float y, float z);

View File

@@ -52,7 +52,7 @@ void App::init() {
glfwSetScrollCallback(m_window.get_glfw_window(), mouse_scroll_callback); glfwSetScrollCallback(m_window.get_glfw_window(), mouse_scroll_callback);
glfwSetCursorEnterCallback(m_window.get_glfw_window(), cursor_enter_callback); glfwSetCursorEnterCallback(m_window.get_glfw_window(), cursor_enter_callback);
glfwSetCharCallback(m_window.get_glfw_window(), char_callback); glfwSetCharCallback(m_window.get_glfw_window(), char_callback);
PerlinNoise::init(); ChunkGenerator::init();
m_renderer.init(); m_renderer.init();
Logger::info("Renderer Init Success"); Logger::info("Renderer Init Success");

View File

@@ -212,12 +212,15 @@ void DevPanel::show_world_tab_item() {
ImGuiInputTextFlags_EnterReturnsTrue, ImGuiInputTextFlags_EnterReturnsTrue,
filter_unsigned)) filter_unsigned))
{ {
PerlinNoise::seed(static_cast<unsigned int>(std::strtoul(perlin_noise_input_buffer, nullptr, 10))); ChunkGenerator::seed(static_cast<unsigned int>(std::strtoul(perlin_noise_input_buffer, nullptr, 10)));
m_text_editing.perlin_seed = false; m_text_editing.perlin_seed = false;
m_player->set_player_pos({0.0f, 255.0f, 0.0f});
m_app.world().rebuild_world();
} }
} }
if (!m_text_editing.perlin_seed) { if (!m_text_editing.perlin_seed) {
ImGui::Text("Perlin Noise Seed: %u", PerlinNoise::seed()); ImGui::Text("ChunkGenerator Seed: %u", ChunkGenerator::seed());
if (ImGui::IsItemClicked()) { if (ImGui::IsItemClicked()) {
m_text_editing.perlin_seed = true; m_text_editing.perlin_seed = true;
} }

View File

@@ -1,5 +1,4 @@
#include <Cubed/gameplay/chunk.hpp> #include <Cubed/gameplay/chunk.hpp>
#include <Cubed/gameplay/tree.hpp>
#include <Cubed/gameplay/world.hpp> #include <Cubed/gameplay/world.hpp>
#include <Cubed/tools/cubed_assert.hpp> #include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_random.hpp> #include <Cubed/tools/cubed_random.hpp>
@@ -7,7 +6,6 @@
#include <Cubed/tools/math_tools.hpp> #include <Cubed/tools/math_tools.hpp>
#include <Cubed/tools/perlin_noise.hpp> #include <Cubed/tools/perlin_noise.hpp>
#include <numeric>
#include <utility> #include <utility>
namespace Cubed { namespace Cubed {
@@ -62,6 +60,10 @@ Biome Chunk::get_biome() const {
return m_biome.load(); return m_biome.load();
} }
ChunkPos Chunk::get_chunk_pos() const {
return m_chunk_pos;
}
const std::vector<uint8_t>& Chunk::get_chunk_blocks() const{ const std::vector<uint8_t>& Chunk::get_chunk_blocks() const{
return m_blocks; return m_blocks;
} }
@@ -214,290 +216,62 @@ size_t Chunk::get_vertex_sum() const {
void Chunk::gen_phase_one() { void Chunk::gen_phase_one() {
float x = static_cast<float>(m_chunk_pos.x); m_generator = std::make_unique<ChunkGenerator>(*this);
float z = static_cast<float>(m_chunk_pos.z); if (!m_generator) {
float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f, z * BIOME_NOISE_FREQUENCY); Logger::error("ChunkGenerator is Nullptr");
float humid = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 1.0f, z * BIOME_NOISE_FREQUENCY); return;
m_biome = get_biome_from_noise(temp, humid); }
m_generator->assign_chunk_biome();
} }
void Chunk::gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks) { void Chunk::gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks) {
for (auto& chunk : adj_chunks) { if (!m_generator) {
if (chunk == nullptr) { Logger::error("ChunkGenerator is Nullptr");
continue;
}
Biome biome = chunk->get_biome();
for (const auto& non : NON_ADJACENT) {
if (m_biome != non.first) {
continue;
}
for (auto b : non.second) {
if (b == biome) {
m_biome = non.replace;
return; return;
} }
} m_generator->resolve_biome_adjacency_conflict(adj_chunks);
}
}
} }
void Chunk::gen_phase_three() { void Chunk::gen_phase_three() {
for (int x = 0; x < CHUCK_SIZE; x++) { if (!m_generator) {
for (int z = 0; z < CHUCK_SIZE; z++) { Logger::error("ChunkGenerator is Nullptr");
return;
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);
auto sample_height = [&](Biome b) -> float {
auto range = get_biome_height_range(b);
auto [f1, f2, f3] = get_noise_frequencies_for_biome(b);
float n =
1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) +
0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) +
0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3);
n /= 1.75f;
return range.base_y + n * range.amplitude;
};
m_heightmap[x][z] = sample_height(m_biome);
}
} }
m_generator->generate_heightmap();
} }
void Chunk::gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) { void Chunk::gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) {
// Width of interpolation influence (in number of cells) if (!m_generator) {
constexpr int BLEND_RADIUS = 12; Logger::error("ChunkGenerator is Nullptr");
return;
for (int x = 0; x < SIZE_X; x++) {
for (int z = 0; z < SIZE_Z; z++) {
float h = static_cast<float>(m_heightmap[x][z]);
float total_weight = 1.0f;
float blended = h;
// --- Right neighbor neighbor[0]: (1, 0) ---
// Blend when x is close to SIZE_X-1
if (neighbor_heightmap[0] != std::nullopt) {
int dist = (SIZE_X - 1) - x; // distance from right border
if (dist < BLEND_RADIUS) {
// Neighbor's boundary row is its x=0 column
float neighbor_h = static_cast<float>((*neighbor_heightmap[0])[0][z]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; // larger weight when closer
// Use smoothstep for a more natural transition
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Left neighbor neighbor[1]: (-1, 0) ---
if (neighbor_heightmap[1] != std::nullopt) {
int dist = x; // distance from left border
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[1])[SIZE_X - 1][z]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Front neighbor neighbor[2]: (0, 1) ---
if (neighbor_heightmap[2] != std::nullopt) {
int dist = (SIZE_Z - 1) - z;
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[2])[x][0]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Back neighbor neighbor[3]: (0, -1) ---
if (neighbor_heightmap[3] != std::nullopt) {
int dist = z;
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[3])[x][SIZE_Z - 1]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
m_heightmap[x][z] = static_cast<int>(blended / total_weight);
}
} }
m_generator->blend_heightmap_boundaries(neighbor_heightmap);
} }
void Chunk::gen_phase_five() { void Chunk::gen_phase_five() {
// bottom if (!m_generator) {
m_blocks.assign(CHUCK_SIZE * CHUCK_SIZE * WORLD_SIZE_Y, 0); Logger::error("ChunkGenerator is Nullptr");
for (int x = 0; x < CHUCK_SIZE; x++) { return;
for (int y = 0; y < 5; y++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
m_blocks[get_index(x, y, z)] = 3;
} }
} m_generator->generate_terrain_blocks();
}
for (int x = 0; x < CHUCK_SIZE; x++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
int height = static_cast<int>(m_heightmap[x][z]);
for (int y = 5; y < height - 5; y++) {
m_blocks[get_index(x, y, z)] = 3;
}
if (m_biome == Biome::MOUNTAIN) {
for (int y = height - 5; y <= height - 1; y++) {
if (y > 110) {
m_blocks[get_index(x, y, z)] = 3;
} else {
m_blocks[get_index(x, y, z)] = 2;
}
}
if (height > 110) {
m_blocks[get_index(x, height - 1, z)] = 3;
} else {
m_blocks[get_index(x, height - 1, z)] = 1;
}
} else if (m_biome == Biome::DESERT) {
for (int y = height - 5; y <= height; y++) {
m_blocks[get_index(x, y, z)] = 4;
}
} else {
for (int y = height - 5; y <= height - 1; y++) {
m_blocks[get_index(x, y, z)] = 2;
}
for (int y = height; y <= height; y++) {
m_blocks[get_index(x, y, z)] = 1;
}
}
}
}
} }
void Chunk::gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) { void Chunk::gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) {
constexpr int BLEND_RADIUS = 12; if (!m_generator) {
constexpr int WORLD_HEIGHT = WORLD_SIZE_Y; Logger::error("ChunkGenerator is Nullptr");
return;
// Helper lambda: get top block type from a neighbor's block data at (nx, nz)
auto get_top_block_from_neighbor = [&](const std::vector<uint8_t>& blocks, int nx, int nz) -> uint8_t {
// Search from topmost y downwards for the first non-zero block
for (int y = WORLD_HEIGHT - 1; y >= 0; --y) {
int idx = get_index(nx, y, nz); // linear index: y * area + z * size + x
if (idx >= 0 && idx < static_cast<int>(blocks.size()) && blocks[idx] != 0) {
return blocks[idx];
}
}
return 0; // fallback, should not happen for valid chunks
};
// For each column (x, z)
for (int x = 0; x < CHUCK_SIZE; ++x) {
for (int z = 0; z < CHUCK_SIZE; ++z) {
// Get the current top block type of this column from m_blocks
uint8_t type_self = 0;
int top_y = -1;
top_y = m_heightmap[x][z];
type_self = m_blocks[get_index(x, top_y, z)];
if (top_y == -1) continue; // no block? skip
// Weight map: type -> total weight
std::unordered_map<uint8_t, float> weights;
weights[type_self] = 1.0f; // self weight
// --- Right neighbor (index 0) ---
if (neighbor_block[0] && x >= CHUCK_SIZE - BLEND_RADIUS) {
int dist = (CHUCK_SIZE - 1) - x;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); // smoothstep
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[0], 0, z);
weights[type_neighbor] += t;
}
}
// --- Left neighbor (index 1) ---
if (neighbor_block[1] && x < BLEND_RADIUS) {
int dist = x;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[1], CHUCK_SIZE - 1, z);
weights[type_neighbor] += t;
}
}
// --- Front neighbor (index 2) ---
if (neighbor_block[2] && z >= CHUCK_SIZE - BLEND_RADIUS) {
int dist = (CHUCK_SIZE - 1) - z;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[2], x, 0);
weights[type_neighbor] += t;
}
}
// --- Back neighbor (index 3) ---
if (neighbor_block[3] && z < BLEND_RADIUS) {
int dist = z;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[3], x, CHUCK_SIZE - 1);
weights[type_neighbor] += t;
}
}
// Find type with maximum total weight
uint8_t final_type = type_self;
float max_weight = weights[type_self];
for (const auto& [type, w] : weights) {
if (w > max_weight) {
max_weight = w;
final_type = type;
}
}
// Update the top block if the type changed
if (final_type != type_self) {
m_blocks[get_index(x, top_y, z)] = final_type;
unsigned fill_type = 2;
if (final_type == 1) {
fill_type = 2;
} else if (final_type == 4) {
fill_type = 4;
}
for (int y = top_y - 5; y < top_y; y++) {
m_blocks[get_index(x, y, z)] = fill_type;
}
}
}
} }
m_generator->blend_surface_blocks_borders(neighbor_block);
} }
void Chunk::gen_phase_seven() { void Chunk::gen_phase_seven() {
if (m_biome == Biome::FOREST) { if (!m_generator) {
std::array<int, SIZE_X> x_arr; Logger::error("ChunkGenerator is Nullptr");
std::iota(x_arr.begin(), x_arr.end(), 0); return;
std::shuffle(x_arr.begin(), x_arr.end(), Cubed::Random::get().engine());
std::array<int, SIZE_Z> z_arr;
std::iota(z_arr.begin(), z_arr.end(), 0);
std::shuffle(z_arr.begin(), z_arr.end(), Cubed::Random::get().engine());
for (auto x : x_arr) {
for (auto z : z_arr) {
if (Cubed::Random::get().random_bool(forest_params().tree_frequency)) {
build_tree(*this, {x, static_cast<int>(m_heightmap[x][z]), z});
} }
m_generator->generate_vegetation();
}
}
}
mark_dirty(); mark_dirty();
m_generator = nullptr;
} }
void Chunk::upload_to_gpu() { void Chunk::upload_to_gpu() {
@@ -540,4 +314,22 @@ void Chunk::set_chunk_block(int index ,unsigned id) {
mark_dirty(); mark_dirty();
} }
ChunkPos Chunk::chunk_pos() const{
return m_chunk_pos;
}
Biome Chunk::biome() const{
return m_biome;
}
void Chunk::biome(Biome b) {
m_biome = b;
}
HeightMapArray& Chunk::heightmap() {
return m_heightmap;
}
std::vector<uint8_t>& Chunk::blocks() {
return m_blocks;
}
} }

View File

@@ -0,0 +1,347 @@
#include <Cubed/gameplay/chunk_generator.hpp>
#include <Cubed/gameplay/chunk.hpp>
#include <Cubed/gameplay/tree.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include <Cubed/tools/perlin_noise.hpp>
namespace Cubed {
ChunkGenerator::ChunkGenerator(Chunk& chunk) :
m_chunk(chunk)
{
ASSERT_MSG(is_init, "ChunksGenerator is not init");
ChunkPos pos = m_chunk.get_chunk_pos();
unsigned seed = HASH::mix_hash(pos.x, pos.z, m_generator_seed);
m_random.init(seed);
}
void ChunkGenerator::init() {
std::random_device d;
m_generator_seed = d();
Logger::info("Chunk Generator Seed {}", m_generator_seed);
PerlinNoise::init(m_generator_seed);
is_init = true;
}
void ChunkGenerator::reload() {
if (!is_seed_change) {
return;
}
PerlinNoise::reload(m_generator_seed);
is_seed_change = false;
}
const unsigned& ChunkGenerator::seed() {
return m_generator_seed;
}
void ChunkGenerator::seed(unsigned s) {
is_seed_change = true;
m_generator_seed = s;
}
void ChunkGenerator::assign_chunk_biome() {
auto m_chunk_pos = m_chunk.chunk_pos();
float x = static_cast<float>(m_chunk_pos.x);
float z = static_cast<float>(m_chunk_pos.z);
float temp = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 0.0f, z * BIOME_NOISE_FREQUENCY);
float humid = PerlinNoise::noise(x * BIOME_NOISE_FREQUENCY, 1.0f, z * BIOME_NOISE_FREQUENCY);
auto biome = get_biome_from_noise(temp, humid);
m_chunk.biome(biome);
}
void ChunkGenerator::resolve_biome_adjacency_conflict(const std::array<const Chunk*, 4>& adj_chunks) {
auto m_biome = m_chunk.biome();
for (auto& chunk : adj_chunks) {
if (chunk == nullptr) {
continue;
}
Biome biome = chunk->get_biome();
for (const auto& non : NON_ADJACENT) {
if (m_biome != non.first) {
continue;
}
for (auto b : non.second) {
if (b == biome) {
m_biome = non.replace;
return;
}
}
}
}
}
void ChunkGenerator::generate_heightmap() {
auto m_chunk_pos = m_chunk.chunk_pos();
auto& m_heightmap = m_chunk.heightmap();
auto m_biome = m_chunk.biome();
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);
auto sample_height = [&](Biome b) -> float {
auto range = get_biome_height_range(b);
auto [f1, f2, f3] = get_noise_frequencies_for_biome(b);
float n =
1.00f * PerlinNoise::noise(world_x * f1, 0.5f, world_z * f1) +
0.50f * PerlinNoise::noise(world_x * f2, 0.5f, world_z * f2) +
0.25f * PerlinNoise::noise(world_x * f3, 0.5f, world_z * f3);
n /= 1.75f;
return range.base_y + n * range.amplitude;
};
m_heightmap[x][z] = sample_height(m_biome);
}
}
}
void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) {
auto& m_heightmap = m_chunk.heightmap();
// Width of interpolation influence (in number of cells)
constexpr int BLEND_RADIUS = 12;
for (int x = 0; x < SIZE_X; x++) {
for (int z = 0; z < SIZE_Z; z++) {
float h = static_cast<float>(m_heightmap[x][z]);
float total_weight = 1.0f;
float blended = h;
// --- Right neighbor neighbor[0]: (1, 0) ---
// Blend when x is close to SIZE_X-1
if (neighbor_heightmap[0] != std::nullopt) {
int dist = (SIZE_X - 1) - x; // distance from right border
if (dist < BLEND_RADIUS) {
// Neighbor's boundary row is its x=0 column
float neighbor_h = static_cast<float>((*neighbor_heightmap[0])[0][z]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS; // larger weight when closer
// Use smoothstep for a more natural transition
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Left neighbor neighbor[1]: (-1, 0) ---
if (neighbor_heightmap[1] != std::nullopt) {
int dist = x; // distance from left border
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[1])[SIZE_X - 1][z]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Front neighbor neighbor[2]: (0, 1) ---
if (neighbor_heightmap[2] != std::nullopt) {
int dist = (SIZE_Z - 1) - z;
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[2])[x][0]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
// --- Back neighbor neighbor[3]: (0, -1) ---
if (neighbor_heightmap[3] != std::nullopt) {
int dist = z;
if (dist < BLEND_RADIUS) {
float neighbor_h = static_cast<float>((*neighbor_heightmap[3])[x][SIZE_Z - 1]);
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
blended += t * neighbor_h;
total_weight += t;
}
}
m_heightmap[x][z] = static_cast<int>(blended / total_weight);
}
}
}
void ChunkGenerator::generate_terrain_blocks() {
auto& m_blocks = m_chunk.blocks();
auto& m_heightmap = m_chunk.heightmap();
auto m_biome = m_chunk.biome();
// bottom
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++) {
m_blocks[Chunk::get_index(x, y, z)] = 3;
}
}
}
for (int x = 0; x < CHUCK_SIZE; x++) {
for (int z = 0; z < CHUCK_SIZE; z++) {
int height = static_cast<int>(m_heightmap[x][z]);
for (int y = 5; y < height - 5; y++) {
m_blocks[Chunk::get_index(x, y, z)] = 3;
}
if (m_biome == Biome::MOUNTAIN) {
for (int y = height - 5; y <= height - 1; y++) {
if (y > 110) {
m_blocks[Chunk::get_index(x, y, z)] = 3;
} else {
m_blocks[Chunk::get_index(x, y, z)] = 2;
}
}
if (height > 110) {
m_blocks[Chunk::get_index(x, height - 1, z)] = 3;
} else {
m_blocks[Chunk::get_index(x, height - 1, z)] = 1;
}
} else if (m_biome == Biome::DESERT) {
for (int y = height - 5; y <= height; y++) {
m_blocks[Chunk::get_index(x, y, z)] = 4;
}
} else {
for (int y = height - 5; y <= height - 1; y++) {
m_blocks[Chunk::get_index(x, y, z)] = 2;
}
for (int y = height; y <= height; y++) {
m_blocks[Chunk::get_index(x, y, z)] = 1;
}
}
}
}
}
void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) {
auto& m_blocks = m_chunk.blocks();
auto& m_heightmap = m_chunk.heightmap();
constexpr int BLEND_RADIUS = 12;
constexpr int WORLD_HEIGHT = WORLD_SIZE_Y;
// Helper lambda: get top block type from a neighbor's block data at (nx, nz)
auto get_top_block_from_neighbor = [&](const std::vector<uint8_t>& blocks, int nx, int nz) -> uint8_t {
// Search from topmost y downwards for the first non-zero block
for (int y = WORLD_HEIGHT - 1; y >= 0; --y) {
int idx = Chunk::get_index(nx, y, nz); // linear index: y * area + z * size + x
if (idx >= 0 && idx < static_cast<int>(blocks.size()) && blocks[idx] != 0) {
return blocks[idx];
}
}
return 0; // fallback, should not happen for valid chunks
};
// For each column (x, z)
for (int x = 0; x < CHUCK_SIZE; ++x) {
for (int z = 0; z < CHUCK_SIZE; ++z) {
// Get the current top block type of this column from m_blocks
uint8_t type_self = 0;
int top_y = -1;
top_y = m_heightmap[x][z];
type_self = m_blocks[Chunk::get_index(x, top_y, z)];
if (top_y == -1) continue; // no block? skip
// Weight map: type -> total weight
std::unordered_map<uint8_t, float> weights;
weights[type_self] = 1.0f; // self weight
// --- Right neighbor (index 0) ---
if (neighbor_block[0] && x >= CHUCK_SIZE - BLEND_RADIUS) {
int dist = (CHUCK_SIZE - 1) - x;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t); // smoothstep
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[0], 0, z);
weights[type_neighbor] += t;
}
}
// --- Left neighbor (index 1) ---
if (neighbor_block[1] && x < BLEND_RADIUS) {
int dist = x;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[1], CHUCK_SIZE - 1, z);
weights[type_neighbor] += t;
}
}
// --- Front neighbor (index 2) ---
if (neighbor_block[2] && z >= CHUCK_SIZE - BLEND_RADIUS) {
int dist = (CHUCK_SIZE - 1) - z;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[2], x, 0);
weights[type_neighbor] += t;
}
}
// --- Back neighbor (index 3) ---
if (neighbor_block[3] && z < BLEND_RADIUS) {
int dist = z;
float t = 1.0f - static_cast<float>(dist) / BLEND_RADIUS;
t = t * t * (3.0f - 2.0f * t);
if (t > 0.0f) {
uint8_t type_neighbor = get_top_block_from_neighbor(*neighbor_block[3], x, CHUCK_SIZE - 1);
weights[type_neighbor] += t;
}
}
// Find type with maximum total weight
uint8_t final_type = type_self;
float max_weight = weights[type_self];
for (const auto& [type, w] : weights) {
if (w > max_weight) {
max_weight = w;
final_type = type;
}
}
// Update the top block if the type changed
if (final_type != type_self) {
m_blocks[Chunk::get_index(x, top_y, z)] = final_type;
unsigned fill_type = 2;
if (final_type == 1) {
fill_type = 2;
} else if (final_type == 4) {
fill_type = 4;
}
for (int y = top_y - 5; y < top_y; y++) {
m_blocks[Chunk::get_index(x, y, z)] = fill_type;
}
}
}
}
}
void ChunkGenerator::generate_vegetation() {
auto m_biome = m_chunk.biome();
auto& m_heightmap = m_chunk.heightmap();
if (m_biome == Biome::FOREST) {
std::array<int, SIZE_X> x_arr;
std::iota(x_arr.begin(), x_arr.end(), 0);
std::shuffle(x_arr.begin(), x_arr.end(), m_random.engine());
std::array<int, SIZE_Z> z_arr;
std::iota(z_arr.begin(), z_arr.end(), 0);
std::shuffle(z_arr.begin(), z_arr.end(), m_random.engine());
for (auto x : x_arr) {
for (auto z : z_arr) {
if (m_random.random_bool(forest_params().tree_frequency)) {
build_tree(m_chunk, {x, static_cast<int>(m_heightmap[x][z]), z});
}
}
}
}
}
}

View File

@@ -722,7 +722,7 @@ void World::rebuild_world() {
m_new_chunk_queue.clear(); m_new_chunk_queue.clear();
} }
m_could_gen = true; m_could_gen = true;
PerlinNoise::reload(); ChunkGenerator::reload();
start_gen_thread(); start_gen_thread();
need_gen(); need_gen();

View File

@@ -1,6 +1,10 @@
#include <Cubed/app.hpp> #include <Cubed/app.hpp>
int main(int argc, char** argv) { int main(int argc, char** argv) {
static_assert(sizeof(int) == sizeof(int32_t));
static_assert(sizeof(unsigned int) == sizeof(uint32_t));
return Cubed::App::start_cubed_application(argc, argv); return Cubed::App::start_cubed_application(argc, argv);
} }

View File

@@ -2,33 +2,11 @@
#include <Cubed/tools/log.hpp> #include <Cubed/tools/log.hpp>
#include <atomic>
namespace Cubed { namespace Cubed {
unsigned Random::get_base_seed() {
static unsigned base = [] {
std::random_device rd;
return rd();
}();
return base;
}
unsigned Random::get_thread_seed() {
static std::atomic<unsigned> counter{0};
thread_local static unsigned seed = get_base_seed() + counter.fetch_add(1);
return seed;
}
Random::Random() { Random::Random() {
m_seed = get_thread_seed();
Logger::info("Seed: {}", m_seed);
m_engine.seed(m_seed);
}
Random& Random::get() {
thread_local Random instance;
return instance;
} }
bool Random::random_bool(double probability) { bool Random::random_bool(double probability) {
@@ -44,6 +22,9 @@ unsigned Random::seed() {
return m_seed; return m_seed;
} }
void Random::init(unsigned seed) {
m_seed = seed;
m_engine.seed(seed);
}
} }

View File

@@ -10,16 +10,14 @@
namespace Cubed { namespace Cubed {
void PerlinNoise::init() { void PerlinNoise::init(unsigned seed) {
p.resize(256); p.resize(256);
std::iota(p.begin(), p.end(), 0); std::iota(p.begin(), p.end(), 0);
auto seed = std::random_device{}();
Logger::info("Init Perlin Noise With Seed {}", seed); Logger::info("Init Perlin Noise With Seed {}", seed);
std::shuffle(p.begin(), p.end(), std::mt19937(seed)); std::shuffle(p.begin(), p.end(), std::mt19937(seed));
p.insert(p.end(), p.begin(), p.end()); p.insert(p.end(), p.begin(), p.end());
is_init = true; is_init = true;
m_seed = seed;
} }
float PerlinNoise::noise(float x, float y, float z) { float PerlinNoise::noise(float x, float y, float z) {
@@ -74,27 +72,15 @@ float PerlinNoise::grad(int hash, float x, float y, float z) {
return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v); return ((h & 1) == 0 ? u : -u) + ((h & 2) == 0 ? v : -v);
} }
void PerlinNoise::reload() { void PerlinNoise::reload(unsigned seed) {
if (!is_seed_change) {
Logger::warn("Seed Not Change");
return;
}
is_init = false; is_init = false;
p.resize(256); p.resize(256);
std::iota(p.begin(), p.end(), 0); std::iota(p.begin(), p.end(), 0);
Logger::info("Reload Perlin Noise With Seed {}", m_seed); Logger::info("Reload Perlin Noise With Seed {}", seed);
std::shuffle(p.begin(), p.end(), std::mt19937(m_seed)); std::shuffle(p.begin(), p.end(), std::mt19937(seed));
p.insert(p.end(), p.begin(), p.end()); p.insert(p.end(), p.begin(), p.end());
is_init = true; is_init = true;
is_seed_change = false;
} }
const unsigned& PerlinNoise::seed() {
return m_seed;
}
void PerlinNoise::seed(unsigned seed) {
m_seed = seed;
is_seed_change = true;
}
} }