chore: add clang-format and pre-commit configuration

This commit is contained in:
2026-04-28 09:22:55 +08:00
parent dc3be5a4bc
commit 611a795481
62 changed files with 2166 additions and 2134 deletions

View File

@@ -1,74 +1,60 @@
#include <Cubed/gameplay/biome.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/gameplay/biome.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/perlin_noise.hpp"
#include <cmath>
#include <unordered_map>
namespace Cubed {
static PlainParams plain {
{
Biome::PLAIN,
{0.0f, 0.5f},
{0.0f, 0.5f},
{0.003f, 0.010f, 0.020f},
{62, 8}
}
};
static PlainParams plain{{Biome::PLAIN,
{0.0f, 0.5f},
{0.0f, 0.5f},
{0.003f, 0.010f, 0.020f},
{62, 8}}};
static ForestParams forest {
{
Biome::FOREST,
{0.5f, 1.0f},
{0.5f, 1.0f},
{0.004f, 0.010f, 0.020f},
{64, 12}
},
0.1f
static ForestParams forest{{Biome::FOREST,
{0.5f, 1.0f},
{0.5f, 1.0f},
{0.004f, 0.010f, 0.020f},
{64, 12}},
0.1f
};
static DesertParams desert {
{
Biome::DESERT,
{0.5f, 1.0f},
{0.0f, 0.5f},
{0.003f, 0.010f, 0.020f},
{61, 12}
}
};
static DesertParams desert{{Biome::DESERT,
{0.5f, 1.0f},
{0.0f, 0.5f},
{0.003f, 0.010f, 0.020f},
{61, 12}}};
static MountainParams mountain {
{
Biome::MOUNTAIN,
{0.0f, 0.5f},
{0.5f, 1.0f},
{0.006f, 0.014f, 0.010f},
{70, 70}
}
};
static MountainParams mountain{{Biome::MOUNTAIN,
{0.0f, 0.5f},
{0.5f, 1.0f},
{0.006f, 0.014f, 0.010f},
{70, 70}}};
std::string get_biome_str(Biome biome) {
std::string str;
using enum Biome;
switch (biome) {
case PLAIN:
str = "Plain";
break;
case FOREST:
str = "Forest";
break;
case DESERT:
str = "Desert";
break;
case MOUNTAIN:
str = "Mountain";
break;
case NONE:
str = "Unknown";
break;
case PLAIN:
str = "Plain";
break;
case FOREST:
str = "Forest";
break;
case DESERT:
str = "Desert";
break;
case MOUNTAIN:
str = "Mountain";
break;
case NONE:
str = "Unknown";
break;
}
return str;
};
@@ -78,7 +64,7 @@ Biome get_biome_from_noise(float temp, float humid) {
float dt = t - ct;
float dh = h - ch;
float dist = std::sqrt(dt*dt + dh*dh);
return std::max(0.0f, 0.5f - dist);
return std::max(0.0f, 0.5f - dist);
};
float w_m = weight(temp, humid, 0.25f, 0.15f);
float w_p = weight(temp, humid, 0.50f, 0.40f);
@@ -93,35 +79,39 @@ Biome get_biome_from_noise(float temp, float humid) {
*/
Biome get_biome_from_noise(float temp, float humid) {
using enum Biome;
if (plain.temp.first <= temp && temp < plain.temp.second && plain.humid.first <= humid && humid < plain.humid.second) {
if (plain.temp.first <= temp && temp < plain.temp.second &&
plain.humid.first <= humid && humid < plain.humid.second) {
return PLAIN;
}
if (forest.temp.first <= temp && temp < forest.temp.second && forest.humid.first <= humid && humid < forest.humid.second) {
if (forest.temp.first <= temp && temp < forest.temp.second &&
forest.humid.first <= humid && humid < forest.humid.second) {
return FOREST;
}
if (desert.temp.first <= temp && temp < desert.temp.second && desert.humid.first <= humid && humid < desert.humid.second) {
if (desert.temp.first <= temp && temp < desert.temp.second &&
desert.humid.first <= humid && humid < desert.humid.second) {
return DESERT;
}
if (mountain.temp.first <= temp && temp <= mountain.temp.second && mountain.humid.first <= humid && humid <= mountain.humid.second) {
if (mountain.temp.first <= temp && temp <= mountain.temp.second &&
mountain.humid.first <= humid && humid <= mountain.humid.second) {
return MOUNTAIN;
}
Logger::warn("Invail Temp {} or Humid {}", temp, humid);
return PLAIN;
return PLAIN;
}
std::array<float, 3> get_noise_frequencies_for_biome(Biome biome) {
using enum Biome;
switch (biome) {
case PLAIN:
return plain.frequencies;
case FOREST:
return forest.frequencies;
case DESERT:
return desert.frequencies;
case MOUNTAIN:
return mountain.frequencies;
case NONE:
ASSERT_MSG(false, "Chunk Biome is None");
throw std::invalid_argument{"Chunk Biome is None"};
case PLAIN:
return plain.frequencies;
case FOREST:
return forest.frequencies;
case DESERT:
return desert.frequencies;
case MOUNTAIN:
return mountain.frequencies;
case NONE:
ASSERT_MSG(false, "Chunk Biome is None");
throw std::invalid_argument{"Chunk Biome is None"};
}
Logger::warn("Unknown Biome");
return {0.003f, 0.015f, 0.06f};
@@ -130,17 +120,17 @@ std::array<float, 3> get_noise_frequencies_for_biome(Biome biome) {
BiomeHeightRange get_biome_height_range(Biome biome) {
using enum Biome;
switch (biome) {
case PLAIN:
return plain.height_range;
case FOREST:
return forest.height_range;
case DESERT:
return desert.height_range;
case MOUNTAIN:
return mountain.height_range;
case NONE:
ASSERT_MSG(false, "Chunk Biome is None");
throw std::invalid_argument{"Chunk Biome is None"};
case PLAIN:
return plain.height_range;
case FOREST:
return forest.height_range;
case DESERT:
return desert.height_range;
case MOUNTAIN:
return mountain.height_range;
case NONE:
ASSERT_MSG(false, "Chunk Biome is None");
throw std::invalid_argument{"Chunk Biome is None"};
}
Logger::warn("Unknown Biome");
return {62, 4};
@@ -148,71 +138,61 @@ BiomeHeightRange get_biome_height_range(Biome biome) {
Biome safe_int_to_biome(int x) {
using enum Biome;
static const std::unordered_map<int, Biome> INT_TO_BIOME_MAP {
{0, PLAIN},
{1, FOREST},
{2, DESERT},
{3, MOUNTAIN}
};
static const std::unordered_map<int, Biome> INT_TO_BIOME_MAP{
{0, PLAIN}, {1, FOREST}, {2, DESERT}, {3, MOUNTAIN}};
auto it = INT_TO_BIOME_MAP.find(x);
ASSERT_MSG(it != INT_TO_BIOME_MAP.end(), ":Can't Find");
ASSERT_MSG(it != INT_TO_BIOME_MAP.end(), ":Can't Find");
return it->second;
}
int get_interpolated_height(float world_x, float world_z, float temp, float humid) {
int get_interpolated_height(float world_x, float world_z, float temp,
float humid) {
auto weight = [](float t, float h, float ct, float ch) -> float {
float dt = t - ct;
float dh = h - ch;
float dist = std::sqrt(dt*dt + dh*dh);
return std::max(0.0f, 0.5f - dist);
float dist = std::sqrt(dt * dt + dh * dh);
return std::max(0.0f, 0.5f - dist);
};
float w_mountain = weight(temp, humid, 0.25f, 0.15f);
float w_plain = weight(temp, humid, 0.50f, 0.40f);
float w_desert = weight(temp, humid, 0.75f, 0.15f);
float w_forest = weight(temp, humid, 0.75f, 0.75f);
float w_plain = weight(temp, humid, 0.50f, 0.40f);
float w_desert = weight(temp, humid, 0.75f, 0.15f);
float w_forest = weight(temp, humid, 0.75f, 0.75f);
// adjust transitions between chunks
float pow_n = 8.0f; // the larger n is, the purer the biome
w_mountain = std::pow(w_mountain, pow_n) * MOUNTAIN_FREQ;
w_plain = std::pow(w_plain, pow_n) * PLAIN_FREQ;
w_desert = std::pow(w_desert, pow_n) * DESERT_FREQ;
w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ;
w_plain = std::pow(w_plain, pow_n) * PLAIN_FREQ;
w_desert = std::pow(w_desert, pow_n) * DESERT_FREQ;
w_forest = std::pow(w_forest, pow_n) * FOREST_FREQ;
float total = w_mountain + w_plain + w_desert + w_forest;
w_mountain /= total; w_plain /= total; w_desert /= total; w_forest /= total;
w_mountain /= total;
w_plain /= total;
w_desert /= total;
w_forest /= total;
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);
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;
};
float h = w_mountain * sample_height(Biome::MOUNTAIN)
+ w_plain * sample_height(Biome::PLAIN)
+ w_desert * sample_height(Biome::DESERT)
+ w_forest * sample_height(Biome::FOREST);
float h = w_mountain * sample_height(Biome::MOUNTAIN) +
w_plain * sample_height(Biome::PLAIN) +
w_desert * sample_height(Biome::DESERT) +
w_forest * sample_height(Biome::FOREST);
return static_cast<int>(h);
}
PlainParams& plain_params() {
return plain;
}
ForestParams& forest_params() {
return forest;
}
DesertParams& desert_params() {
return desert;
}
MountainParams& mountain_params() {
return mountain;
}
}
PlainParams& plain_params() { return plain; }
ForestParams& forest_params() { return forest; }
DesertParams& desert_params() { return desert; }
MountainParams& mountain_params() { return mountain; }
} // namespace Cubed

View File

@@ -1,47 +1,37 @@
#include <Cubed/gameplay/chunk.hpp>
#include <Cubed/gameplay/world.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/math_tools.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/gameplay/chunk.hpp"
#include "Cubed/gameplay/world.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include <utility>
namespace Cubed {
Chunk::Chunk(World& world, ChunkPos chunk_pos) :
m_chunk_pos(chunk_pos),
m_world(world)
{
}
Chunk::Chunk(World& world, ChunkPos chunk_pos)
: m_chunk_pos(chunk_pos), m_world(world) {}
Chunk::~Chunk() {
if (m_vbo != 0) {
m_world.push_delete_vbo(m_vbo);
}
}
Chunk::Chunk(Chunk&& other) noexcept :
m_dirty(other.is_dirty()),
m_need_upload(other.m_need_upload.load()),
m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()),
m_vertex_sum(other.m_vertex_sum.load()),
m_biome(other.m_biome.load()),
m_chunk_pos(std::move(other.m_chunk_pos)),
m_world(other.m_world),
m_heightmap(std::move(other.m_heightmap)),
m_blocks(std::move(other.m_blocks)),
m_vbo(other.m_vbo),
m_vertexs_data(std::move(other.m_vertexs_data))
{
Chunk::Chunk(Chunk&& other) noexcept
: m_dirty(other.is_dirty()), m_need_upload(other.m_need_upload.load()),
m_is_on_gen_vertex_data(other.m_is_on_gen_vertex_data.load()),
m_vertex_sum(other.m_vertex_sum.load()), m_biome(other.m_biome.load()),
m_chunk_pos(std::move(other.m_chunk_pos)), m_world(other.m_world),
m_heightmap(std::move(other.m_heightmap)),
m_blocks(std::move(other.m_blocks)), m_vbo(other.m_vbo),
m_vertexs_data(std::move(other.m_vertexs_data)) {
other.m_vbo = 0;
}
Chunk& Chunk::operator=(Chunk&& other) noexcept {
//Logger::info("other Chunk pos {} {} in Chunk& Chunk::operator=(Chunk&& other) this {}", other.m_chunk_pos.x, other.m_chunk_pos.z, static_cast<const void*>(&other));
// Logger::info("other Chunk pos {} {} in Chunk& Chunk::operator=(Chunk&&
// other) this {}", other.m_chunk_pos.x, other.m_chunk_pos.z,
// static_cast<const void*>(&other));
m_vbo = other.m_vbo;
other.m_vbo = 0;
m_chunk_pos = std::move(other.m_chunk_pos);
@@ -56,26 +46,24 @@ Chunk& Chunk::operator=(Chunk&& other) noexcept {
return *this;
}
Biome Chunk::get_biome() const {
return m_biome.load();
}
Biome Chunk::get_biome() const { return m_biome.load(); }
ChunkPos Chunk::get_chunk_pos() const {
return m_chunk_pos;
}
ChunkPos Chunk::get_chunk_pos() const { return m_chunk_pos; }
const std::vector<uint8_t>& Chunk::get_chunk_blocks() const{
return m_blocks;
}
const std::vector<uint8_t>& Chunk::get_chunk_blocks() const { return m_blocks; }
HeightMapArray Chunk::get_heightmap() const {
//Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x, m_chunk_pos.z, static_cast<const void*>(this));
// Logger::info("Chunk pos {} {} in get_heightmap this {}", m_chunk_pos.x,
// m_chunk_pos.z, static_cast<const void*>(this));
return m_heightmap;
}
int Chunk::get_index(int x, int y, int z) {
ASSERT(!(x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE));
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) {
ASSERT(!(x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE));
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);
ASSERT(0);
}
@@ -86,17 +74,17 @@ int Chunk::get_index(const glm::vec3& pos) {
return Chunk::get_index(pos.x, pos.y, pos.z);
}
void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& neighbor_block) {
void Chunk::gen_vertex_data(
const std::array<const std::vector<uint8_t>*, 4>& neighbor_block) {
if (m_is_on_gen_vertex_data) {
return;
}
m_is_on_gen_vertex_data = true;
std::lock_guard lk(m_vertexs_data_mutex);
m_vertexs_data.clear();
static const glm::ivec3 DIR[6] = {
{0,0,1},{1,0,0},{0,0,-1},{-1,0,0},{0,1,0},{0,-1,0}
};
static const glm::ivec3 DIR[6] = {{0, 0, 1}, {1, 0, 0}, {0, 0, -1},
{-1, 0, 0}, {0, 1, 0}, {0, -1, 0}};
for (int x = 0; x < SIZE_X; x++) {
for (int y = 0; y < SIZE_Y; y++) {
@@ -109,51 +97,57 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
if (cur_id == 0) {
continue;
}
for (int face = 0; face < 6; face++) {
int nx = x + DIR[face].x;
int ny = y + DIR[face].y;
int nz = z + DIR[face].z;
bool neighbor_cull = false;
if (nx < 0 || nx >= SIZE_X || ny < 0 || ny >= SIZE_Y || nz < 0 || nz>= SIZE_Z) {
if (nx < 0 || nx >= SIZE_X || ny < 0 || ny >= SIZE_Y ||
nz < 0 || nz >= SIZE_Z) {
int world_nx = world_x + DIR[face].x;
int world_ny = world_y + DIR[face].y;
int world_nz = world_z + DIR[face].z;
auto [neighbor_x, neighbor_z] = World::chunk_pos(world_nx, world_nz);
auto is_cull = [&](const std::vector<uint8_t>* chunk_blocks){
if (chunk_blocks == nullptr) {
return false;
}
int x, y, z;
y = world_ny;
x = world_nx - neighbor_x * CHUCK_SIZE;
z = world_nz - neighbor_z * CHUCK_SIZE;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) {
return false;
}
int idx = Chunk::get_index(x, y, z);
// not init
if (static_cast<size_t>(idx) >= chunk_blocks->size()) {
Logger::warn("not init");
return false;
}
auto id = (*chunk_blocks)[idx];
if (is_in_transparent_map(id)) {
if (id == cur_id) {
return true;
} else {
auto [neighbor_x, neighbor_z] =
World::chunk_pos(world_nx, world_nz);
auto is_cull =
[&](const std::vector<uint8_t>* chunk_blocks) {
if (chunk_blocks == nullptr) {
return false;
}
} else {
return true;
}
};
int x, y, z;
y = world_ny;
x = world_nx - neighbor_x * CHUCK_SIZE;
z = world_nz - neighbor_z * CHUCK_SIZE;
if (x < 0 || y < 0 || z < 0 ||
x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return false;
}
int idx = Chunk::get_index(x, y, z);
// not init
if (static_cast<size_t>(idx) >=
chunk_blocks->size()) {
Logger::warn("not init");
return false;
}
auto id = (*chunk_blocks)[idx];
if (is_in_transparent_map(id)) {
if (id == cur_id) {
return true;
} else {
return false;
}
} else {
return true;
}
};
if (m_chunk_pos.x + 1 == neighbor_x) {
neighbor_cull = is_cull(neighbor_block[0]);
@@ -164,7 +158,8 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
} else if (m_chunk_pos.z - 1 == neighbor_z) {
neighbor_cull = is_cull(neighbor_block[3]);
}
//neighbor_cull = m_world.is_block(glm::ivec3(world_x, world_y, world_z) + DIR[face]);
// neighbor_cull = m_world.is_block(glm::ivec3(world_x,
// world_y, world_z) + DIR[face]);
} else {
auto id = m_blocks[get_index(nx, ny, nz)];
if (!is_in_transparent_map(id)) {
@@ -188,14 +183,13 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
VERTICES_POS[face][i][2] + (float)world_z * 1.0f,
TEX_COORDS[face][i][0],
TEX_COORDS[face][i][1],
static_cast<float>(cur_id * 6 + face)
static_cast<float>(cur_id * 6 + face)
};
m_vertexs_data.emplace_back(vex);
}
}
}
}
}
}
m_vertex_sum = m_vertexs_data.size();
@@ -203,9 +197,7 @@ void Chunk::gen_vertex_data(const std::array<const std::vector<uint8_t>*, 4>& ne
m_is_on_gen_vertex_data = false;
}
GLuint Chunk::get_vbo() const{
return m_vbo;
}
GLuint Chunk::get_vbo() const { return m_vbo; }
size_t Chunk::get_vertex_sum() const {
if (m_vertex_sum == 0) {
@@ -214,12 +206,11 @@ size_t Chunk::get_vertex_sum() const {
return m_vertex_sum.load();
}
void Chunk::gen_phase_one() {
m_generator = std::make_unique<ChunkGenerator>(*this);
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->assign_chunk_biome();
}
@@ -227,7 +218,7 @@ void Chunk::gen_phase_one() {
void Chunk::gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks) {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->resolve_biome_adjacency_conflict(adj_chunks);
}
@@ -235,15 +226,16 @@ void Chunk::gen_phase_two(const std::array<const Chunk*, 4>& adj_chunks) {
void Chunk::gen_phase_three() {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
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) {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->blend_heightmap_boundaries(neighbor_heightmap);
}
@@ -251,15 +243,16 @@ void Chunk::gen_phase_four(const std::array<std::optional<HeightMapArray>, 4>& n
void Chunk::gen_phase_five() {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->generate_terrain_blocks();
}
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) {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->blend_surface_blocks_borders(neighbor_block);
}
@@ -267,7 +260,7 @@ void Chunk::gen_phase_six(const std::array<std::optional<std::vector<uint8_t>>,
void Chunk::gen_phase_seven() {
if (!m_generator) {
Logger::error("ChunkGenerator is Nullptr");
return;
return;
}
m_generator->generate_vegetation();
mark_dirty();
@@ -278,58 +271,39 @@ void Chunk::upload_to_gpu() {
ASSERT(is_need_upload());
if (m_vbo == 0) {
glGenBuffers(1, &m_vbo);
glGenBuffers(1, &m_vbo);
}
std::lock_guard lk(m_vertexs_data_mutex);
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, m_vertexs_data.size() * sizeof(Vertex), m_vertexs_data.data(), GL_DYNAMIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, m_vertexs_data.size() * sizeof(Vertex),
m_vertexs_data.data(), GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
// after fininshed it, can use
clear_dirty();
m_need_upload = false;
}
bool Chunk::is_dirty() const{
return m_dirty.load();
}
bool Chunk::is_dirty() const { return m_dirty.load(); }
void Chunk::mark_dirty() {
m_dirty = true;
}
void Chunk::mark_dirty() { m_dirty = true; }
void Chunk::clear_dirty() {
m_dirty = false;
}
void Chunk::clear_dirty() { m_dirty = false; }
bool Chunk::is_need_upload() const {
return m_need_upload.load();
}
bool Chunk::is_need_upload() const { return m_need_upload.load(); }
void Chunk::need_upload() {
m_need_upload = true;
}
void Chunk::need_upload() { m_need_upload = true; }
void Chunk::set_chunk_block(int index ,unsigned id) {
void Chunk::set_chunk_block(int index, unsigned id) {
m_blocks[index] = id;
mark_dirty();
}
ChunkPos Chunk::chunk_pos() const{
return m_chunk_pos;
}
ChunkPos Chunk::chunk_pos() const { return m_chunk_pos; }
Biome Chunk::biome() const{
return m_biome;
}
Biome Chunk::biome() const { return m_biome; }
void Chunk::biome(Biome b) {
m_biome = b;
}
void Chunk::biome(Biome b) { m_biome = b; }
HeightMapArray& Chunk::heightmap() {
return m_heightmap;
}
std::vector<uint8_t>& Chunk::blocks() {
return m_blocks;
}
}
HeightMapArray& Chunk::heightmap() { return m_heightmap; }
std::vector<uint8_t>& Chunk::blocks() { return m_blocks; }
} // namespace Cubed

View File

@@ -1,16 +1,14 @@
#include <Cubed/gameplay/chunk_generator.hpp>
#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>
#include "Cubed/gameplay/chunk.hpp"
#include "Cubed/gameplay/tree.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/perlin_noise.hpp"
#include <numeric>
namespace Cubed {
ChunkGenerator::ChunkGenerator(Chunk& chunk) :
m_chunk(chunk)
{
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);
@@ -33,26 +31,26 @@ void ChunkGenerator::reload() {
is_seed_change = false;
}
const unsigned& ChunkGenerator::seed() {
return m_generator_seed;
}
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);
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) {
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) {
@@ -75,33 +73,36 @@ void ChunkGenerator::resolve_biome_adjacency_conflict(const std::array<const Chu
}
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);
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_heightmap[x][z] = sample_height(m_biome);
}
}
}
void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<HeightMapArray>, 4>& neighbor_heightmap) {
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)
@@ -119,8 +120,11 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
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
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;
@@ -132,7 +136,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
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 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;
@@ -144,7 +149,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
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 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;
@@ -156,7 +162,8 @@ void ChunkGenerator::blend_heightmap_boundaries(const std::array<std::optional<H
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 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;
@@ -196,7 +203,6 @@ void ChunkGenerator::generate_terrain_blocks() {
} else {
m_blocks[Chunk::get_index(x, y, z)] = 2;
}
}
if (height > 110) {
m_blocks[Chunk::get_index(x, height - 1, z)] = 3;
@@ -219,19 +225,24 @@ void ChunkGenerator::generate_terrain_blocks() {
}
}
void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional<std::vector<uint8_t>>, 4>& neighbor_block) {
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 {
// 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) {
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];
}
}
@@ -247,7 +258,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
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
if (top_y == -1)
continue; // no block? skip
// Weight map: type -> total weight
std::unordered_map<uint8_t, float> weights;
@@ -259,7 +271,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
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);
uint8_t type_neighbor =
get_top_block_from_neighbor(*neighbor_block[0], 0, z);
weights[type_neighbor] += t;
}
}
@@ -270,7 +283,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
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);
uint8_t type_neighbor = get_top_block_from_neighbor(
*neighbor_block[1], CHUCK_SIZE - 1, z);
weights[type_neighbor] += t;
}
}
@@ -281,7 +295,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
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);
uint8_t type_neighbor =
get_top_block_from_neighbor(*neighbor_block[2], x, 0);
weights[type_neighbor] += t;
}
}
@@ -292,7 +307,8 @@ void ChunkGenerator::blend_surface_blocks_borders(const std::array<std::optional
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);
uint8_t type_neighbor = get_top_block_from_neighbor(
*neighbor_block[3], x, CHUCK_SIZE - 1);
weights[type_neighbor] += t;
}
}
@@ -337,14 +353,12 @@ void ChunkGenerator::generate_vegetation() {
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});
build_tree(m_chunk,
{x, static_cast<int>(m_heightmap[x][z]), z});
}
}
}
}
}
}
} // namespace Cubed

View File

@@ -1,67 +1,50 @@
#include <Cubed/gameplay/player.hpp>
#include "Cubed/gameplay/player.hpp"
#include "Cubed/config.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/gameplay/world.hpp"
#include "Cubed/tools/log.hpp"
#include <Cubed/debug_collector.hpp>
#include <Cubed/gameplay/world.hpp>
#include <Cubed/map_table.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <GLFW/glfw3.h>
namespace Cubed {
Player::Player(World& world, const std::string& name) :
m_name(name),
m_world(world)
{
Player::Player(World& world, const std::string& name)
: m_name(name), m_world(world) {
hot_reload();
}
Player::~Player() {
}
Player::~Player() {}
AABB Player::get_aabb() const {
float half_width = m_size.x / 2.0f;
float half_depth = m_size.z / 2.0f;
glm::vec3 min{
m_player_pos.x - half_width,
m_player_pos.y,
m_player_pos.z - half_depth
};
glm::vec3 min{m_player_pos.x - half_width, m_player_pos.y,
m_player_pos.z - half_depth};
glm::vec3 max {
m_player_pos.x + half_width,
m_player_pos.y + m_size.y,
m_player_pos.z + half_depth
};
glm::vec3 max{m_player_pos.x + half_width, m_player_pos.y + m_size.y,
m_player_pos.z + half_depth};
return AABB{min, max};
}
const glm::vec3& Player::get_front() const {
return m_front;
}
const glm::vec3& Player::get_front() const { return m_front; }
const Gait& Player::get_gait() const {
return m_gait;
}
const Gait& Player::get_gait() const { return m_gait; }
const std::optional<LookBlock>& Player::get_look_block_pos() const {
return m_look_block;
}
const glm::vec3& Player::get_player_pos() const {
return m_player_pos;
}
const glm::vec3& Player::get_player_pos() const { return m_player_pos; }
const MoveState& Player::get_move_state() const {
return m_move_state;
}
const MoveState& Player::get_move_state() const { return m_move_state; }
bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3& block_pos, glm::vec3& normal, float distance) {
bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front,
glm::ivec3& block_pos, glm::vec3& normal,
float distance) {
glm::vec3 dir = glm::normalize(front);
//float step = 0.1f;
// float step = 0.1f;
glm::ivec3 cur = glm::floor(start);
int ix = cur.x;
int iy = cur.y;
@@ -72,7 +55,7 @@ bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3
int step_z = (dir.z > 0) ? 1 : ((dir.z < 0) ? -1 : 0);
static const float INF = std::numeric_limits<float>::infinity();
float t_delta_x = (dir.x != 0) ? std::fabs(1.0f / dir.x) : INF;
float t_delta_y = (dir.y != 0) ? std::fabs(1.0f / dir.y) : INF;
float t_delta_z = (dir.z != 0) ? std::fabs(1.0f / dir.z) : INF;
@@ -126,8 +109,6 @@ bool Player::ray_cast(const glm::vec3& start, const glm::vec3& front, glm::ivec3
normal = glm::vec3(0.0f, 0.0f, -step_z);
iz += step_z;
}
}
return false;
}
@@ -147,13 +128,11 @@ void Player::change_mode(GameMode mode) {
void Player::hot_reload() {
auto& config = Config::get();
m_sensitivity = static_cast<float>(config.get<double>("player.mouse_sensitivity"));
m_sensitivity =
static_cast<float>(config.get<double>("player.mouse_sensitivity"));
}
void Player::set_player_pos(const glm::vec3& pos) {
m_player_pos = pos;
}
void Player::set_player_pos(const glm::vec3& pos) { m_player_pos = pos; }
void Player::update(float delta_time) {
@@ -162,108 +141,109 @@ void Player::update(float delta_time) {
check_player_chunk_transition();
DebugCollector::get().report("player_pos",
std::format("x: {:.2f} y: {:.2f} z: {:.2f}",
m_player_pos.x, m_player_pos.y, m_player_pos.z
));
DebugCollector::get().report("speed", std::format("Speed: {:.2} m/s", m_xz_speed));
std::format("x: {:.2f} y: {:.2f} z: {:.2f}",
m_player_pos.x, m_player_pos.y,
m_player_pos.z));
DebugCollector::get().report("speed",
std::format("Speed: {:.2} m/s", m_xz_speed));
}
void Player::update_player_move_state(int key, int action) {
switch(key) {
case GLFW_KEY_W:
if (action == GLFW_PRESS) {
m_move_state.forward = true;
switch (key) {
case GLFW_KEY_W:
if (action == GLFW_PRESS) {
m_move_state.forward = true;
}
if (action == GLFW_RELEASE) {
m_move_state.forward = false;
if (m_game_mode != SPECTATOR) {
m_gait = Gait::WALK;
}
if (action == GLFW_RELEASE) {
m_move_state.forward = false;
if (m_game_mode != SPECTATOR) {
m_gait = Gait::WALK;
}
}
break;
case GLFW_KEY_S:
if (action == GLFW_PRESS) {
m_move_state.back = true;
}
if (action == GLFW_RELEASE) {
m_move_state.back = false;
}
break;
case GLFW_KEY_A:
if (action == GLFW_PRESS) {
m_move_state.left = true;
}
if (action == GLFW_RELEASE) {
m_move_state.left = false;
}
break;
case GLFW_KEY_D:
if (action == GLFW_PRESS) {
m_move_state.right = true;
}
if (action == GLFW_RELEASE) {
m_move_state.right = false;
}
break;
case GLFW_KEY_SPACE:
if (action == GLFW_PRESS) {
m_move_state.up = true;
if (space_on) {
if (m_game_mode == CREATIVE) {
is_fly = !is_fly ? true : false;
m_y_speed = 0.0f;
}
space_on = false;
space_on_time = 0.0f;
} else {
space_on = true;
}
}
if (action == GLFW_RELEASE) {
m_move_state.up = false;
}
break;
case GLFW_KEY_LEFT_SHIFT:
if (action == GLFW_PRESS) {
m_move_state.down = true;
}
if (action == GLFW_RELEASE) {
m_move_state.down = false;
}
break;
case GLFW_KEY_LEFT_CONTROL:
if (action == GLFW_PRESS) {
m_gait = Gait::RUN;
}
break;
case GLFW_KEY_F4:
if (action == GLFW_PRESS) {
}
break;
case GLFW_KEY_S:
if (action == GLFW_PRESS) {
m_move_state.back = true;
}
if (action == GLFW_RELEASE) {
m_move_state.back = false;
}
break;
case GLFW_KEY_A:
if (action == GLFW_PRESS) {
m_move_state.left = true;
}
if (action == GLFW_RELEASE) {
m_move_state.left = false;
}
break;
case GLFW_KEY_D:
if (action == GLFW_PRESS) {
m_move_state.right = true;
}
if (action == GLFW_RELEASE) {
m_move_state.right = false;
}
break;
case GLFW_KEY_SPACE:
if (action == GLFW_PRESS) {
m_move_state.up = true;
if (space_on) {
if (m_game_mode == CREATIVE) {
change_mode(SPECTATOR);
} else {
change_mode(CREATIVE);
is_fly = !is_fly ? true : false;
m_y_speed = 0.0f;
}
space_on = false;
space_on_time = 0.0f;
} else {
space_on = true;
}
break;
}
if (action == GLFW_RELEASE) {
m_move_state.up = false;
}
break;
case GLFW_KEY_LEFT_SHIFT:
if (action == GLFW_PRESS) {
m_move_state.down = true;
}
if (action == GLFW_RELEASE) {
m_move_state.down = false;
}
break;
case GLFW_KEY_LEFT_CONTROL:
if (action == GLFW_PRESS) {
m_gait = Gait::RUN;
}
break;
case GLFW_KEY_F4:
if (action == GLFW_PRESS) {
if (m_game_mode == CREATIVE) {
change_mode(SPECTATOR);
} else {
change_mode(CREATIVE);
}
}
break;
}
}
void Player::update_front_vec(float offset_x, float offset_y) {
m_yaw += offset_x * m_sensitivity;
m_pitch += offset_y * m_sensitivity;
m_yaw = std::fmod(m_yaw, 360.0);
if (m_pitch > 89.0f) m_pitch = 89.0f;
if (m_pitch < -89.0f) m_pitch = -89.0f;
m_yaw = std::fmod(m_yaw, 360.0);
if (m_pitch > 89.0f)
m_pitch = 89.0f;
if (m_pitch < -89.0f)
m_pitch = -89.0f;
m_front.x = sin(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
m_front.y = sin(glm::radians(m_pitch));
m_front.z = -cos(glm::radians(m_yaw)) * cos(glm::radians(m_pitch));
m_front = glm::normalize(m_front);
}
@@ -276,10 +256,9 @@ void Player::check_player_chunk_transition() {
if (chunk == nullptr) {
DebugCollector::get().report("biome", "Biome: Unknown");
} else {
DebugCollector::get()
.report("biome", "Biome: " + get_biome_str(chunk->get_biome()));
DebugCollector::get().report(
"biome", "Biome: " + get_biome_str(chunk->get_biome()));
}
}
}
@@ -291,15 +270,12 @@ void Player::update_direction() {
glm::vec3 move_dir = glm::vec3(0.0f);
if (m_move_state.forward) {
move_dir_front += glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z));
}
if (m_move_state.back) {
move_dir_front -= glm::normalize(glm::vec3(m_front.x, 0.0f, m_front.z));
}
if (m_move_state.left) {
move_dir_right -= glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z));
}
if (m_move_state.right) {
move_dir_right += glm::normalize(glm::vec3(m_right.x, 0.0f, m_right.z));
@@ -307,15 +283,17 @@ void Player::update_direction() {
move_dir = move_dir_front + move_dir_right;
if (glm::length(move_dir) > 0.001f) {
direction = glm::normalize(move_dir);
direction = glm::normalize(move_dir);
}
}
void Player::update_lookup_block() {
// calculate the block that is looked
// calculate the block that is looked
glm::ivec3 block_pos;
glm::vec3 block_normal;
if(ray_cast(glm::vec3(m_player_pos.x, (m_player_pos.y + 1.6f), m_player_pos.z), m_front, block_pos, block_normal)) {
if (ray_cast(
glm::vec3(m_player_pos.x, (m_player_pos.y + 1.6f), m_player_pos.z),
m_front, block_pos, block_normal)) {
m_look_block = LookBlock{block_pos, glm::floor(block_normal)};
} else {
m_look_block = std::nullopt;
@@ -325,25 +303,25 @@ void Player::update_lookup_block() {
if (Input::get_input_state().mouse_state.left) {
if (m_world.is_block(m_look_block->pos)) {
m_world.set_block(m_look_block->pos, 0);
}
Input::get_input_state().mouse_state.left = false;
}
if (Input::get_input_state().mouse_state.right) {
glm::ivec3 near_pos = m_look_block->pos + m_look_block->normal;
if (!m_world.is_block(near_pos)) {
auto x= near_pos.x;
auto x = near_pos.x;
auto y = near_pos.y;
auto z = near_pos.z;
AABB block_box = {
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)}
};
AABB block_box = {glm::vec3{static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
AABB player_box = get_aabb();
if (!player_box.intersects(block_box)) {
m_world.set_block(near_pos, 1);
}
}
Input::get_input_state().mouse_state.right = false;
}
@@ -371,9 +349,10 @@ void Player::update_move(float delta_time) {
space_on_time = 0.0f;
}
}
// calculate speed
if (m_move_state.forward || m_move_state.back || m_move_state.left || m_move_state.right || m_move_state.up) {
if (m_move_state.forward || m_move_state.back || m_move_state.left ||
m_move_state.right || m_move_state.up) {
direction = glm::vec3(0.0f, 0.0f, 0.0f);
m_xz_speed += m_acceleration * delta_time;
if (m_xz_speed > m_max_speed) {
@@ -389,11 +368,12 @@ void Player::update_move(float delta_time) {
update_direction();
move_distance = {direction.x * m_xz_speed * delta_time, 0.0f, direction.z * m_xz_speed * delta_time};
move_distance = {direction.x * m_xz_speed * delta_time, 0.0f,
direction.z * m_xz_speed * delta_time};
if (is_fly) {
if (m_move_state.up) {
m_y_speed = 7.5f;
m_y_speed = 7.5f;
}
if (m_move_state.down) {
@@ -405,14 +385,13 @@ void Player::update_move(float delta_time) {
}
} else {
if (m_move_state.up && can_up) {
m_y_speed = 7.5;
can_up = false;
m_y_speed = 7.5;
can_up = false;
}
m_y_speed += -m_g * delta_time;
}
move_distance.y = m_y_speed * delta_time;
// y
update_y_move();
@@ -425,7 +404,6 @@ void Player::update_move(float delta_time) {
Logger::warn("y is tow low");
m_player_pos += glm::vec3(1.0f, 100.0f, 1.0f);
}
}
void Player::update_x_move() {
@@ -445,10 +423,12 @@ void Player::update_x_move() {
for (int y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = {
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)}
};
AABB block_box = {glm::vec3{static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) {
m_gait = Gait::WALK;
m_player_pos.x -= move_distance.x;
@@ -477,10 +457,12 @@ void Player::update_y_move() {
for (int y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = {
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)}
};
AABB block_box = {glm::vec3{static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) {
m_player_pos.y -= move_distance.y;
m_y_speed = 0.0f;
@@ -513,10 +495,12 @@ void Player::update_z_move() {
for (int y = miny; y <= maxy; ++y) {
for (int z = minz; z <= maxz; ++z) {
if (m_world.is_block(glm::vec3{x, y, z})) {
AABB block_box = {
glm::vec3{static_cast<float>(x), static_cast<float>(y), static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1), static_cast<float>(y + 1), static_cast<float>(z + 1)}
};
AABB block_box = {glm::vec3{static_cast<float>(x),
static_cast<float>(y),
static_cast<float>(z)},
glm::vec3{static_cast<float>(x + 1),
static_cast<float>(y + 1),
static_cast<float>(z + 1)}};
if (player_box.intersects(block_box)) {
m_gait = Gait::WALK;
m_player_pos.z -= move_distance.z;
@@ -539,32 +523,16 @@ void Player::update_scroll(double yoffset) {
m_max_speed -= 1.0f;
}
}
}
}
}
float& Player::max_walk_speed() {
return m_max_walk_speed;
}
float& Player::max_run_speed() {
return m_max_run_speed;
}
float& Player::max_speed() {
return m_max_speed;
}
float& Player::acceleration() {
return m_acceleration;
}
float& Player::deceleration() {
return m_deceleration;
}
float& Player::g() {
return m_g;
}
Gait& Player::gait() {
return m_gait;
}
GameMode& Player::game_mode() {
return m_game_mode;
}
float& Player::max_walk_speed() { return m_max_walk_speed; }
float& Player::max_run_speed() { return m_max_run_speed; }
float& Player::max_speed() { return m_max_speed; }
float& Player::acceleration() { return m_acceleration; }
float& Player::deceleration() { return m_deceleration; }
float& Player::g() { return m_g; }
Gait& Player::gait() { return m_gait; }
GameMode& Player::game_mode() { return m_game_mode; }
}
} // namespace Cubed

View File

@@ -1,96 +1,50 @@
#include <Cubed/gameplay/tree.hpp>
#include "Cubed/gameplay/tree.hpp"
#include <Cubed/gameplay/chunk.hpp>
#include "Cubed/gameplay/chunk.hpp"
#include <array>
namespace Cubed {
using glm::ivec3;
static constexpr std::array<TreeStructNode, 62> TREE {{
{{0, 1, 0}, 5},
{{0, 2, 0}, 5},
{{0, 3, 0}, 5},
{{0, 4, 0}, 5},
{{0, 5, 0}, 5},
{{0, 6, 0}, 6},
{{0, 5, 1}, 6},
{{1, 5, 0}, 6},
{{0, 5, -1}, 6},
{{-1, 5, 0}, 6},
{{1, 5, 1}, 6},
{{1, 5, -1}, 6},
{{-1, 5, -1}, 6},
{{-1, 5, 1}, 6},
{{0, 4, 1}, 6},
{{1, 4, 0}, 6},
{{0, 4, -1}, 6},
{{-1, 4, 0}, 6},
{{1, 4, 1}, 6},
{{1, 4, -1}, 6},
{{-1, 4, -1}, 6},
{{-1, 4, 1}, 6},
{{0, 4, 2}, 6},
{{2, 4, 0}, 6},
{{0, 4, -2}, 6},
{{-2, 4, 0}, 6},
{{2, 4, 2}, 6},
{{2, 4, -2}, 6},
{{-2, 4, -2}, 6},
{{-2, 4, 2}, 6},
{{1, 4, 2}, 6},
{{2, 4, 1}, 6},
{{-1, 4, 2}, 6},
{{2, 4, -1}, 6},
{{1, 4, -2}, 6},
{{-2, 4, 1}, 6},
{{-1, 4, -2}, 6},
{{-2, 4, -1}, 6},
{{0, 3, 1}, 6},
{{1, 3, 0}, 6},
{{0, 3, -1}, 6},
{{-1, 3, 0}, 6},
{{1, 3, 1}, 6},
{{1, 3, -1}, 6},
{{-1, 3, -1}, 6},
{{-1, 3, 1}, 6},
{{0, 3, 2}, 6},
{{2, 3, 0}, 6},
{{0, 3, -2}, 6},
{{-2, 3, 0}, 6},
{{2, 3, 2}, 6},
{{2, 3, -2}, 6},
{{-2, 3, -2}, 6},
{{-2, 3, 2}, 6},
{{1, 3, 2}, 6},
{{2, 3, 1}, 6},
{{-1, 3, 2}, 6},
{{2, 3, -1}, 6},
{{1, 3, -2}, 6},
{{-2, 3, 1}, 6},
{{-1, 3, -2}, 6},
{{-2, 3, -1}, 6},
static constexpr std::array<TreeStructNode, 62> TREE{{
{{0, 1, 0}, 5}, {{0, 2, 0}, 5}, {{0, 3, 0}, 5}, {{0, 4, 0}, 5},
{{0, 5, 0}, 5}, {{0, 6, 0}, 6}, {{0, 5, 1}, 6}, {{1, 5, 0}, 6},
{{0, 5, -1}, 6}, {{-1, 5, 0}, 6}, {{1, 5, 1}, 6}, {{1, 5, -1}, 6},
{{-1, 5, -1}, 6}, {{-1, 5, 1}, 6}, {{0, 4, 1}, 6}, {{1, 4, 0}, 6},
{{0, 4, -1}, 6}, {{-1, 4, 0}, 6}, {{1, 4, 1}, 6}, {{1, 4, -1}, 6},
{{-1, 4, -1}, 6}, {{-1, 4, 1}, 6}, {{0, 4, 2}, 6}, {{2, 4, 0}, 6},
{{0, 4, -2}, 6}, {{-2, 4, 0}, 6}, {{2, 4, 2}, 6}, {{2, 4, -2}, 6},
{{-2, 4, -2}, 6}, {{-2, 4, 2}, 6}, {{1, 4, 2}, 6}, {{2, 4, 1}, 6},
{{-1, 4, 2}, 6}, {{2, 4, -1}, 6}, {{1, 4, -2}, 6}, {{-2, 4, 1}, 6},
{{-1, 4, -2}, 6}, {{-2, 4, -1}, 6}, {{0, 3, 1}, 6}, {{1, 3, 0}, 6},
{{0, 3, -1}, 6}, {{-1, 3, 0}, 6}, {{1, 3, 1}, 6}, {{1, 3, -1}, 6},
{{-1, 3, -1}, 6}, {{-1, 3, 1}, 6}, {{0, 3, 2}, 6}, {{2, 3, 0}, 6},
{{0, 3, -2}, 6}, {{-2, 3, 0}, 6}, {{2, 3, 2}, 6}, {{2, 3, -2}, 6},
{{-2, 3, -2}, 6}, {{-2, 3, 2}, 6}, {{1, 3, 2}, 6}, {{2, 3, 1}, 6},
{{-1, 3, 2}, 6}, {{2, 3, -1}, 6}, {{1, 3, -2}, 6}, {{-2, 3, 1}, 6},
{{-1, 3, -2}, 6}, {{-2, 3, -1}, 6},
}};
bool build_tree(Chunk& chunk, const glm::ivec3& pos) {
auto& block = chunk.get_chunk_blocks();
if (block[Chunk::get_index(pos)] != 1) {
Logger::info("Root is not Grass Block");
return false;
}
for (const auto& d : TREE) {
auto tree_node = pos + d.offset;
int x = tree_node.x;
int y = tree_node.y;
int z = tree_node.z;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) {
return false;
}
if (block[Chunk::get_index(tree_node)] != 0) {
return false;
int x = tree_node.x;
int y = tree_node.y;
int z = tree_node.z;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return false;
}
if (block[Chunk::get_index(tree_node)] != 0) {
return false;
}
}
for (const auto& d : TREE) {
@@ -100,4 +54,4 @@ bool build_tree(Chunk& chunk, const glm::ivec3& pos) {
return true;
}
}
} // namespace Cubed

View File

@@ -1,29 +1,24 @@
#include <Cubed/gameplay/world.hpp>
#include "Cubed/gameplay/world.hpp"
#include <Cubed/debug_collector.hpp>
#include <Cubed/gameplay/player.hpp>
#include <Cubed/map_table.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include <Cubed/tools/math_tools.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/config.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/math_tools.hpp"
#include <execution>
namespace Cubed {
static constexpr ChunkPos CHUNK_DIR[] {
{1, 0}, {-1, 0}, {0, 1}, {0, -1}
};
static constexpr ChunkPos CHUNK_DIR[]{{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
struct ChunkRenderData {
std::array<const std::vector<uint8_t>*, 4> neighbor_block;
Chunk* chunk;
};
World::World() {
}
World::World() {}
World::~World() {
stop_gen_thread();
@@ -37,12 +32,10 @@ World::~World() {
}
}
bool World::can_move(const AABB& player_box) const{
bool World::can_move(const AABB& player_box) const { return true; }
return true;
}
const std::optional<LookBlock>& World::get_look_block_pos(const std::string& name) const{
const std::optional<LookBlock>&
World::get_look_block_pos(const std::string& name) const {
static std::optional<LookBlock> null_look_block = std::nullopt;
auto it = m_players.find(HASH::str(name));
if (it == m_players.end()) {
@@ -52,7 +45,6 @@ const std::optional<LookBlock>& World::get_look_block_pos(const std::string& nam
}
return it->second.get_look_block_pos();
}
const Chunk* World::get_chunk(const ChunkPos& pos) const {
@@ -64,13 +56,13 @@ const Chunk* World::get_chunk(const ChunkPos& pos) const {
return &it->second;
}
Player& World::get_player(const std::string& name){
Player& World::get_player(const std::string& name) {
auto it = m_players.find(HASH::str(name));
if (it == m_players.end()) {
Logger::error("Can't find player {}", name);
ASSERT(0);
}
return it->second;
}
@@ -84,11 +76,12 @@ void World::init_world() {
ChunkPos pos{ns, nt};
m_chunks.emplace(pos, Chunk(*this, pos));
m_chunks.emplace(pos, Chunk(*this, pos));
}
}
Logger::info("Max Support Thread is {}", std::thread::hardware_concurrency());
Logger::info("Max Support Thread is {}",
std::thread::hardware_concurrency());
init_chunks();
auto t2 = std::chrono::system_clock::now();
auto d = std::chrono::duration_cast<std::chrono::milliseconds>(t2 - t1);
@@ -108,20 +101,20 @@ void World::init_chunks() {
chunk_ptrs.push_back(&chunk);
}
std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(), [](auto& chunk){
chunk->init_chunk();
std::for_each(std::execution::par, chunk_ptrs.begin(), chunk_ptrs.end(),
[](auto& chunk){ chunk->init_chunk();
});
std::atomic<int> sync{0};
sync.store(1, std::memory_order_release);
sync.load(std::memory_order_acquire);
std::vector<ChunkRenderData> pending_gen_data;
pending_gen_data.reserve(m_chunks.size());
for (auto& [pos, chunk] : m_chunks) {
ChunkRenderData data;
data.chunk = &chunk;
for (int i = 0; i < 4; i++) {
for (int i = 0; i < 4; i++) {
auto it = m_chunks.find(pos + CHUNK_DIR[i]);
if (it != m_chunks.end()) {
data.neighbor_block[i] = &(it->second.get_chunk_blocks());
@@ -131,16 +124,15 @@ void World::init_chunks() {
}
pending_gen_data.emplace_back(std::move(data));
}
std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){
if(!data.chunk) {
return ;
std::for_each(std::execution::par, pending_gen_data.begin(),
pending_gen_data.end(), [](ChunkRenderData& data){ if(!data.chunk) { return ;
}
data.chunk->gen_vertex_data(data.neighbor_block);
});
for (auto& chunk_map : m_chunks) {
auto& [chunk_pos, chunk] = chunk_map;
chunk.upload_to_gpu();
}
}
*/
@@ -159,7 +151,6 @@ void World::init_chunks() {
continue;
}
neighbor_chunks[i] = &it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
@@ -177,13 +168,12 @@ void World::init_chunks() {
continue;
}
neighbor_chunk_heightmap[i] = it->second.get_heightmap();
}
chunks.gen_phase_four(neighbor_chunk_heightmap);
}
for (auto& [pos, chunks] : m_chunks) {
chunks.gen_phase_five();
chunks.gen_phase_five();
}
std::array<std::optional<std::vector<uint8_t>>, 4> neighbor_block;
for (auto& [pos, chunks] : m_chunks) {
@@ -195,23 +185,22 @@ void World::init_chunks() {
continue;
}
neighbor_block[i] = it->second.get_chunk_blocks();
}
chunks.gen_phase_six(neighbor_block);
}
for (auto& [pos, chunks] : m_chunks) {
chunks.gen_phase_seven();
chunks.gen_phase_seven();
}
std::atomic<int> sync{0};
sync.store(1, std::memory_order_release);
sync.load(std::memory_order_acquire);
std::vector<ChunkRenderData> pending_gen_data;
pending_gen_data.reserve(m_chunks.size());
for (auto& [pos, chunk] : m_chunks) {
ChunkRenderData data;
data.chunk = &chunk;
for (int i = 0; i < 4; i++) {
for (int i = 0; i < 4; i++) {
auto it = m_chunks.find(pos + CHUNK_DIR[i]);
if (it != m_chunks.end()) {
data.neighbor_block[i] = &(it->second.get_chunk_blocks());
@@ -221,30 +210,32 @@ void World::init_chunks() {
}
pending_gen_data.emplace_back(std::move(data));
}
std::for_each(std::execution::par, pending_gen_data.begin(), pending_gen_data.end(), [](ChunkRenderData& data){
if(!data.chunk) {
return ;
}
data.chunk->gen_vertex_data(data.neighbor_block);
});
std::for_each(std::execution::par, pending_gen_data.begin(),
pending_gen_data.end(), [](ChunkRenderData& data) {
if (!data.chunk) {
return;
}
data.chunk->gen_vertex_data(data.neighbor_block);
});
for (auto& chunk_map : m_chunks) {
auto& [chunk_pos, chunk] = chunk_map;
chunk.upload_to_gpu();
}
}
void World::render(const glm::mat4& mvp_matrix) {
Math::extract_frustum_planes(mvp_matrix, m_planes);
int rendered_sum = 0;
for (const auto& snapshot : m_render_snapshots) {
if (is_aabb_in_frustum(snapshot.center, snapshot.half_extents)) {
glBindBuffer(GL_ARRAY_BUFFER, snapshot.vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex), (void*)offsetof(Vertex, layer));
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex),
(void*)offsetof(Vertex, layer));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
@@ -253,13 +244,10 @@ void World::render(const glm::mat4& mvp_matrix) {
glDrawArrays(GL_TRIANGLES, 0, snapshot.vertex_count);
glBindBuffer(GL_ARRAY_BUFFER, 0);
rendered_sum++;
}
}
DebugCollector::get().report("rendered_chunk", "Rendered Chunk: " + std::to_string(rendered_sum));
DebugCollector::get().report(
"rendered_chunk", "Rendered Chunk: " + std::to_string(rendered_sum));
}
ChunkPos World::chunk_pos(int world_x, int world_z) {
@@ -285,10 +273,10 @@ void World::gen_chunks_internal() {
compute_required_chunks(required_chunks);
ASSERT_MSG(!required_chunks.empty(), "required chunks is empty!!");
std::vector<ChunkPos> need_gen_chunks_pos;
sync_and_collect_missing_chunks(need_gen_chunks_pos, required_chunks);
Logger::info("New Gen Chunks Sum: {}", need_gen_chunks_pos.size());
if (need_gen_chunks_pos.empty()) {
m_could_gen = true;
@@ -300,12 +288,13 @@ void World::gen_chunks_internal() {
for (auto& pos : need_gen_chunks_pos) {
new_chunks.push_back({pos, Chunk(*this, pos)});
}
ConstChunkMap new_chunks_neighbor;
// affected neighbor
ChunkPtrUpdateList affected_neighbor;
build_neighbor_context_for_new_chunks(new_chunks_neighbor, affected_neighbor,new_chunks);
build_neighbor_context_for_new_chunks(new_chunks_neighbor,
affected_neighbor, new_chunks);
std::array<const std::vector<uint8_t>*, 4> neighbor_block;
// build new chunk, but the neighbor in m_chunks also need to re-build
@@ -323,7 +312,6 @@ void World::gen_chunks_internal() {
continue;
}
neighbor_chunks[i] = it->second;
}
chunks.gen_phase_two(neighbor_chunks);
}
@@ -335,7 +323,7 @@ void World::gen_chunks_internal() {
std::array<std::optional<HeightMapArray>, 4> neighbor_chunk_heightmap;
for (auto& [pos, chunks] : new_chunks) {
{
//std::lock_guard lk(m_chunks_mutex);
// std::lock_guard lk(m_chunks_mutex);
for (int i = 0; i < 4; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
@@ -355,7 +343,7 @@ void World::gen_chunks_internal() {
std::array<std::optional<std::vector<uint8_t>>, 4> neighbor_blocks_data;
for (auto& [pos, chunks] : new_chunks) {
{
//std::lock_guard lk(m_chunks_mutex);
// std::lock_guard lk(m_chunks_mutex);
for (int i = 0; i < 4; i++) {
auto neighbor_pos = pos + CHUNK_DIR[i];
auto it = new_chunks_neighbor.find(neighbor_pos);
@@ -384,7 +372,8 @@ void World::gen_chunks_internal() {
chunk.gen_vertex_data(neighbor_block);
}
m_chunk_gen_fraction = 0.7f;
build_neighbor_context_for_affected_neighbors(affected_neighbor, new_chunks_neighbor);
build_neighbor_context_for_affected_neighbors(affected_neighbor,
new_chunks_neighbor);
m_chunk_gen_fraction = 0.8f;
for (auto& [pos, chunk] : affected_neighbor) {
for (int i = 0; i < 4; i++) {
@@ -397,14 +386,13 @@ void World::gen_chunks_internal() {
}
chunk->gen_vertex_data(neighbor_block);
chunk->need_upload();
}
}
m_chunk_gen_fraction = 0.9f;
{
std::lock_guard lk(m_new_chunk_queue_mutex);
for (auto& x : new_chunks) {
m_new_chunk_queue.emplace_back(std::move(x));
}
}
m_chunk_gen_fraction = 1.0f;
}
@@ -417,11 +405,10 @@ void World::sync_player_pos(glm::vec3& player_pos) {
void World::compute_required_chunks(ChunkPosSet& required_chunks) {
glm::vec3 player_pos;
sync_player_pos(player_pos);
int x = std::floor(player_pos.x);
int z = std::floor(player_pos.z);
auto [chunk_x, chunk_z] = chunk_pos(x, z);
required_chunks.reserve(m_rendering_distance * m_rendering_distance);
int half = m_rendering_distance / 2;
@@ -432,17 +419,19 @@ void World::compute_required_chunks(ChunkPosSet& required_chunks) {
}
}
void World::sync_and_collect_missing_chunks(std::vector<ChunkPos>& need_gen_chunks_pos, const ChunkPosSet& required_chunks) {
void World::sync_and_collect_missing_chunks(
std::vector<ChunkPos>& need_gen_chunks_pos,
const ChunkPosSet& required_chunks) {
std::lock_guard lk(m_chunks_mutex);
for (auto it = m_chunks.begin(); it != m_chunks.end(); ) {
for (auto it = m_chunks.begin(); it != m_chunks.end();) {
if (required_chunks.find(it->first) == required_chunks.end()) {
it = m_chunks.erase(it);
} else {
++it;
}
}
for (auto pos: required_chunks) {
for (auto pos : required_chunks) {
auto it = m_chunks.find(pos);
if (it == m_chunks.end()) {
need_gen_chunks_pos.push_back(pos);
@@ -450,7 +439,9 @@ void World::sync_and_collect_missing_chunks(std::vector<ChunkPos>& need_gen_chun
}
}
void World::build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor,const ChunkUpdateList& new_chunks) {
void World::build_neighbor_context_for_new_chunks(
ConstChunkMap& new_chunks_neighbor, ChunkPtrUpdateList& affected_neighbor,
const ChunkUpdateList& new_chunks) {
{
std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : new_chunks) {
@@ -468,7 +459,8 @@ void World::build_neighbor_context_for_new_chunks(ConstChunkMap& new_chunks_neig
}
}
void World::build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList& affected_neighbor, ConstChunkMap& new_chunks_neighbor) {
void World::build_neighbor_context_for_affected_neighbors(
ChunkPtrUpdateList& affected_neighbor, ConstChunkMap& new_chunks_neighbor) {
std::lock_guard lk(m_chunks_mutex);
for (auto& [pos, chunk] : affected_neighbor) {
for (auto& dir : CHUNK_DIR) {
@@ -483,11 +475,11 @@ void World::build_neighbor_context_for_affected_neighbors(ChunkPtrUpdateList& af
void World::start_gen_thread() {
m_gen_running = true;
Logger::info("Gen Thread Started");
m_gen_thread = std::thread([this](){
m_gen_thread = std::thread([this]() {
while (m_gen_running) {
std::unique_lock<std::mutex> lk(m_gen_signal_mutex);
m_gen_cv.wait(lk, [this](){
m_gen_cv.wait(lk, [this]() {
return m_need_gen_chunk.load() || !m_gen_running;
});
if (!m_gen_running) {
@@ -520,12 +512,13 @@ void World::need_gen() {
std::lock_guard lk(m_gen_player_pos_mutex);
m_gen_player_pos = get_player("TestPlayer").get_player_pos();
}
m_need_gen_chunk = true;
m_gen_cv.notify_one();
}
bool World::is_aabb_in_frustum(const glm::vec3& center, const glm::vec3& half_extents) {
bool World::is_aabb_in_frustum(const glm::vec3& center,
const glm::vec3& half_extents) {
for (const auto& plane : m_planes) {
// distance
float d = glm::dot(glm::vec3(plane), center) + plane.w;
@@ -553,14 +546,14 @@ int World::get_block(const glm::ivec3& block_pos) const {
y = block_pos.y;
x = block_pos.x - chunk_x * CHUCK_SIZE;
z = block_pos.z - chunk_z * CHUCK_SIZE;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) {
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return 0;
}
return chunk_blocks[Chunk::get_index(x, y, z)];
}
bool World::is_block(const glm::ivec3& block_pos) const{
bool World::is_block(const glm::ivec3& block_pos) const {
auto [chunk_x, chunk_z] = chunk_pos(block_pos.x, block_pos.z);
std::lock_guard lk(m_chunks_mutex);
auto it = m_chunks.find(ChunkPos{chunk_x, chunk_z});
@@ -573,7 +566,8 @@ bool World::is_block(const glm::ivec3& block_pos) const{
y = block_pos.y;
x = block_pos.x - chunk_x * CHUCK_SIZE;
z = block_pos.z - chunk_z * CHUCK_SIZE;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) {
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return false;
}
auto id = chunk_blocks[Chunk::get_index(x, y, z)];
@@ -596,22 +590,22 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) {
auto it = m_chunks.find(ChunkPos{chunk_x, chunk_z});
if (it == m_chunks.end()) {
return ;
return;
}
int x, y, z;
y = world_y;
x = world_x - chunk_x * CHUCK_SIZE;
z = world_z - chunk_z * CHUCK_SIZE;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y || z >= CHUCK_SIZE) {
return ;
if (x < 0 || y < 0 || z < 0 || x >= CHUCK_SIZE || y >= WORLD_SIZE_Y ||
z >= CHUCK_SIZE) {
return;
}
it->second.set_chunk_block(Chunk::get_index(x, y, z), id);
static const glm::ivec3 NEIGHBOR_DIRS[] = {
{1, 0, 0}, {-1, 0, 0}, {0, 0, -1}, {0, 0, 1}
};
{1, 0, 0}, {-1, 0, 0}, {0, 0, -1}, {0, 0, 1}};
for (const auto& dir : NEIGHBOR_DIRS) {
glm::ivec3 neighbor = block_pos + dir;
@@ -620,17 +614,14 @@ void World::set_block(const glm::ivec3& block_pos, unsigned id) {
auto it = m_chunks.find({cx, cz});
if (it != m_chunks.end()) {
it->second.mark_dirty();
}
}
}
void World::update(float delta_time) {
for (auto& player : m_players) {
player.second.update(delta_time);
}
}
{
std::lock_guard lk(m_delete_vbo_mutex);
for (auto x : m_pending_delete_vbo) {
@@ -652,10 +643,10 @@ void World::update(float delta_time) {
}
// unified compute vertex data before rendering
{
{
std::lock_guard lk(m_chunks_mutex);
bool consumed = false;
for (auto& x : m_new_chunk) {
m_chunks.insert_or_assign(x.first, std::move(x.second));
consumed = true;
@@ -663,7 +654,7 @@ void World::update(float delta_time) {
if (consumed) {
m_could_gen = true;
}
m_render_snapshots.clear();
for (auto& [pos, chunk] : m_chunks) {
if (chunk.is_dirty()) {
@@ -684,15 +675,17 @@ void World::update(float delta_time) {
if (chunk.is_need_upload()) {
chunk.upload_to_gpu();
}
m_render_snapshots.push_back({
chunk.get_vbo(),
chunk.get_vertex_sum(),
glm::vec3(static_cast<float>(pos.x * CHUCK_SIZE) + static_cast<float>(CHUCK_SIZE / 2), static_cast<float>(WORLD_SIZE_Y/ 2), static_cast<float>(pos.z * CHUCK_SIZE) + static_cast<float>(CHUCK_SIZE / 2)),
glm::vec3(static_cast<float>(CHUCK_SIZE / 2), static_cast<float>(WORLD_SIZE_Y / 2), static_cast<float>(CHUCK_SIZE / 2))
}
);
m_render_snapshots.push_back(
{chunk.get_vbo(), chunk.get_vertex_sum(),
glm::vec3(static_cast<float>(pos.x * CHUCK_SIZE) +
static_cast<float>(CHUCK_SIZE / 2),
static_cast<float>(WORLD_SIZE_Y / 2),
static_cast<float>(pos.z * CHUCK_SIZE) +
static_cast<float>(CHUCK_SIZE / 2)),
glm::vec3(static_cast<float>(CHUCK_SIZE / 2),
static_cast<float>(WORLD_SIZE_Y / 2),
static_cast<float>(CHUCK_SIZE / 2))});
}
}
}
}
@@ -703,7 +696,7 @@ void World::push_delete_vbo(GLuint vbo) {
}
void World::hot_reload() {
auto & config = Config::get();
auto& config = Config::get();
int dist = config.get<int>("world.rendering_distance");
m_rendering_distance = dist <= MAX_DISTANCE ? dist : MAX_DISTANCE;
need_gen();
@@ -715,7 +708,7 @@ void World::rebuild_world() {
}
m_is_rebuilding = true;
stop_gen_thread();
{
std::scoped_lock lk(m_chunks_mutex, m_new_chunk_queue_mutex);
m_chunks.clear();
@@ -725,21 +718,16 @@ void World::rebuild_world() {
ChunkGenerator::reload();
start_gen_thread();
need_gen();
m_is_rebuilding = false;
}
float World::chunk_gen_fraction() const {
return m_chunk_gen_fraction.load();
}
float World::chunk_gen_fraction() const { return m_chunk_gen_fraction.load(); }
int World::rendering_distance() const {
return m_rendering_distance.load();
}
int World::rendering_distance() const { return m_rendering_distance.load(); }
void World::rendering_distance(int rendering_distance) {
m_rendering_distance = rendering_distance;
}
}
} // namespace Cubed