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,32 +1,26 @@
#include <Cubed/app.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/log.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <Cubed/tools/system_info.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/app.hpp"
#include <imgui_impl_glfw.h>
#include "Cubed/config.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/system_info.hpp"
#include <exception>
#include <imgui_impl_glfw.h>
namespace Cubed {
App::App() {}
App::App() {
}
App::~App() {
}
void App::cursor_position_callback(GLFWwindow* window, double xpos, double ypos) {
App::~App() {}
void App::cursor_position_callback(GLFWwindow* window, double xpos,
double ypos) {
ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr");
if (io.WantCaptureMouse && app->m_window.is_mouse_enable()) {
ImGui_ImplGlfw_CursorPosCallback(window, xpos, ypos);
@@ -35,7 +29,6 @@ void App::cursor_position_callback(GLFWwindow* window, double xpos, double ypos)
if (!app->m_window.is_mouse_enable()) {
app->m_camera.update_cursor_position_camera(xpos, ypos);
}
}
void App::init() {
m_window.init();
@@ -43,21 +36,26 @@ void App::init() {
Logger::info("Window Init Success");
glfwSetWindowUserPointer(m_window.get_glfw_window(), this);
glfwSetCursorPosCallback(m_window.get_glfw_window(), cursor_position_callback);
glfwSetMouseButtonCallback(m_window.get_glfw_window(), mouse_button_callback);
glfwSetWindowFocusCallback(m_window.get_glfw_window(), window_focus_callback);
glfwSetWindowSizeCallback(m_window.get_glfw_window(), window_reshape_callback);
glfwSetCursorPosCallback(m_window.get_glfw_window(),
cursor_position_callback);
glfwSetMouseButtonCallback(m_window.get_glfw_window(),
mouse_button_callback);
glfwSetWindowFocusCallback(m_window.get_glfw_window(),
window_focus_callback);
glfwSetWindowSizeCallback(m_window.get_glfw_window(),
window_reshape_callback);
glfwSetKeyCallback(m_window.get_glfw_window(), key_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);
ChunkGenerator::init();
m_renderer.init();
Logger::info("Renderer Init Success");
m_window.update_viewport();
//MapTable::init_map();
// MapTable::init_map();
m_texture_manager.init_texture();
Logger::info("Texture Load Success");
m_world.init_world();
@@ -67,14 +65,17 @@ void App::init() {
m_dev_panel.init();
}
void App::key_callback(GLFWwindow* window, int key, int scancode, int action, int mods) {
void App::key_callback(GLFWwindow* window, int key, int scancode, int action,
int mods) {
ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr");
//ImGui_ImplGlfw_CursorEnterCallback(window, !app->m_window.is_mouse_enable());
// ImGui_ImplGlfw_CursorEnterCallback(window,
// !app->m_window.is_mouse_enable());
if (io.WantCaptureKeyboard && app->m_window.is_mouse_enable()) {
if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_ESCAPE) && action == GLFW_PRESS) {
if ((key == GLFW_KEY_LEFT_ALT || key == GLFW_KEY_ESCAPE) &&
action == GLFW_PRESS) {
app->m_window.toggle_mouse_able();
app->m_camera.reset_camera();
return;
@@ -82,39 +83,39 @@ void App::key_callback(GLFWwindow* window, int key, int scancode, int action, in
ImGui_ImplGlfw_KeyCallback(window, key, scancode, action, mods);
return;
}
switch(key) {
case GLFW_KEY_Q:
if (action == GLFW_PRESS) {
}
break;
case GLFW_KEY_ESCAPE:
if (action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
break;
case GLFW_KEY_F11:
if (action == GLFW_PRESS) {
app->m_window.toggle_fullscreen();
}
break;
case GLFW_KEY_R:
if (action == GLFW_PRESS) {
app->m_texture_manager.need_reload();
}
break;
case GLFW_KEY_LEFT_ALT:
if (action == GLFW_PRESS) {
app->m_window.toggle_mouse_able();
app->m_camera.reset_camera();
}
break;
switch (key) {
case GLFW_KEY_Q:
if (action == GLFW_PRESS) {
}
break;
case GLFW_KEY_ESCAPE:
if (action == GLFW_PRESS) {
glfwSetWindowShouldClose(window, GLFW_TRUE);
}
break;
case GLFW_KEY_F11:
if (action == GLFW_PRESS) {
app->m_window.toggle_fullscreen();
}
break;
case GLFW_KEY_R:
if (action == GLFW_PRESS) {
app->m_texture_manager.need_reload();
}
break;
case GLFW_KEY_LEFT_ALT:
if (action == GLFW_PRESS) {
app->m_window.toggle_mouse_able();
app->m_camera.reset_camera();
}
break;
}
app->m_world.get_player("TestPlayer").update_player_move_state(key, action);
}
void App::mouse_button_callback(GLFWwindow* window, int button, int action, int mods) {
void App::mouse_button_callback(GLFWwindow* window, int button, int action,
int mods) {
ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr");
@@ -123,27 +124,28 @@ void App::mouse_button_callback(GLFWwindow* window, int button, int action, int
return;
}
switch (button) {
case GLFW_MOUSE_BUTTON_LEFT:
if (action == GLFW_PRESS) {
if(app->m_window.is_mouse_enable()) {
app->m_window.toggle_mouse_able();
app->m_camera.reset_camera();
break;;
}
Input::get_input_state().mouse_state.left = true;
case GLFW_MOUSE_BUTTON_LEFT:
if (action == GLFW_PRESS) {
if (app->m_window.is_mouse_enable()) {
app->m_window.toggle_mouse_able();
app->m_camera.reset_camera();
break;
;
}
if (action == GLFW_RELEASE) {
Input::get_input_state().mouse_state.left = false;
}
break;
case GLFW_MOUSE_BUTTON_RIGHT:
if (action == GLFW_PRESS) {
Input::get_input_state().mouse_state.right = true;
}
if (action == GLFW_RELEASE) {
Input::get_input_state().mouse_state.right = false;
}
break;
Input::get_input_state().mouse_state.left = true;
}
if (action == GLFW_RELEASE) {
Input::get_input_state().mouse_state.left = false;
}
break;
case GLFW_MOUSE_BUTTON_RIGHT:
if (action == GLFW_PRESS) {
Input::get_input_state().mouse_state.right = true;
}
if (action == GLFW_RELEASE) {
Input::get_input_state().mouse_state.right = false;
}
break;
}
}
@@ -158,19 +160,20 @@ void App::window_focus_callback(GLFWwindow* window, int focused) {
if (focused) {
app->m_camera.reset_camera();
}
}
void App::window_reshape_callback(GLFWwindow* window, int new_width, int new_height) {
void App::window_reshape_callback(GLFWwindow* window, int new_width,
int new_height) {
App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr");
app->m_window.update_viewport();
}
void App::mouse_scroll_callback(GLFWwindow* window, double xoffset, double yoffset) {
void App::mouse_scroll_callback(GLFWwindow* window, double xoffset,
double yoffset) {
ImGuiIO& io = ImGui::GetIO();
App* app = static_cast<App*>(glfwGetWindowUserPointer(window));
ASSERT_MSG(app, "nullptr");
if (io.WantCaptureMouse && app->m_window.is_mouse_enable()) {
@@ -201,25 +204,23 @@ void App::char_callback(GLFWwindow* window, unsigned int c) {
}
void App::render() {
if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0)
{
ImGui_ImplGlfw_Sleep(10);
return;
}
if (glfwGetWindowAttrib(m_window.get_glfw_window(), GLFW_ICONIFIED) != 0) {
ImGui_ImplGlfw_Sleep(10);
return;
}
m_renderer.render();
glfwSwapBuffers(m_window.get_glfw_window());
}
void App::run() {
last_time = glfwGetTime();
while(!glfwWindowShouldClose(m_window.get_glfw_window())) {
while (!glfwWindowShouldClose(m_window.get_glfw_window())) {
update();
render();
render();
}
}
static Gait player_gait = Gait::WALK;
@@ -236,13 +237,16 @@ void App::update() {
glfwSetWindowTitle(m_window.get_glfw_window(), title.c_str());
frame_count = 0;
fps_time_count = 0.0f;
DebugCollector::get().report("fps", std::string{"FPS: " + std::to_string(fps)});
DebugCollector::get().report("rss", std::format("RSS: {}mb", Tools::get_current_rss() / (1024 * 1024)));
DebugCollector::get().report(
"fps", std::string{"FPS: " + std::to_string(fps)});
DebugCollector::get().report(
"rss",
std::format("RSS: {}mb", Tools::get_current_rss() / (1024 * 1024)));
}
m_texture_manager.update();
m_world.update(delta_time);
m_camera.update_move_camera();
const auto& player= m_world.get_player("TestPlayer");
const auto& player = m_world.get_player("TestPlayer");
if (player_gait != player.get_gait()) {
player_gait = player.get_gait();
float fov = static_cast<float>(Config::get().get<double>("player.fov"));
@@ -253,7 +257,6 @@ void App::update() {
m_renderer.update_fov(fov + 5.0f);
}
}
}
int App::start_cubed_application(int argc, char** argv) {
@@ -268,39 +271,22 @@ int App::start_cubed_application(int argc, char** argv) {
return 0;
} catch (std::exception& e) {
Logger::error("{}", e.what());
} catch (...) {
Logger::error("Unkown error");
}
return 1;
}
float App::delte_time() {
return delta_time;
}
float App::delte_time() { return delta_time; }
float App::get_fps() {
return fps;
}
float App::get_fps() { return fps; }
Camera& App::camera() {
return m_camera;
}
DevPanel& App::dev_panel() {
return m_dev_panel;
}
Renderer& App::renderer() {
return m_renderer;
}
TextureManager& App::texture_manager() {
return m_texture_manager;
}
Window& App::window() {
return m_window;
}
World& App::world() {
return m_world;
}
Camera& App::camera() { return m_camera; }
DevPanel& App::dev_panel() { return m_dev_panel; }
Renderer& App::renderer() { return m_renderer; }
TextureManager& App::texture_manager() { return m_texture_manager; }
Window& App::window() { return m_window; }
World& App::world() { return m_world; }
}
} // namespace Cubed

View File

@@ -1,13 +1,11 @@
#include <Cubed/camera.hpp>
#include <Cubed/gameplay/player.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include "Cubed/camera.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/cubed_assert.hpp"
namespace Cubed {
Camera::Camera() {
}
Camera::Camera() {}
void Camera::update_move_camera() {
ASSERT_MSG(m_player, "nullptr");
@@ -16,7 +14,6 @@ void Camera::update_move_camera() {
m_camera_pos = glm::vec3(pos.x, pos.y + 1.6f, pos.z);
}
void Camera::camera_init(Player* player) {
m_player = player;
update_move_camera();
@@ -24,13 +21,9 @@ void Camera::camera_init(Player* player) {
hot_reload();
}
void Camera::hot_reload() {
void Camera::hot_reload() {}
}
void Camera::reset_camera() {
m_firse_mouse = true;
}
void Camera::reset_camera() { m_firse_mouse = true; }
void Camera::update_cursor_position_camera(double xpos, double ypos) {
if (m_firse_mouse) {
@@ -49,14 +42,12 @@ void Camera::update_cursor_position_camera(double xpos, double ypos) {
m_player->update_front_vec(offset_x, offset_y);
}
const glm::mat4 Camera::get_camera_lookat() const{
const glm::mat4 Camera::get_camera_lookat() const {
ASSERT_MSG(m_player, "nullptr");
return glm::lookAt(m_camera_pos, m_camera_pos + m_player->get_front(), glm::vec3(0.0f, 1.0f, 0.0f));
return glm::lookAt(m_camera_pos, m_camera_pos + m_player->get_front(),
glm::vec3(0.0f, 1.0f, 0.0f));
}
const glm::vec3& Camera::get_camera_pos() const {
return m_camera_pos;
}
const glm::vec3& Camera::get_camera_pos() const { return m_camera_pos; }
}
} // namespace Cubed

View File

@@ -1,6 +1,7 @@
#include <Cubed/config.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include "Cubed/config.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include <filesystem>
#include <fstream>
@@ -10,22 +11,16 @@ using namespace std::string_view_literals;
namespace Cubed {
Config::Config() {
load_or_create_config();
}
Config::Config() { load_or_create_config(); }
Config::~Config() {
save_to_file();
}
Config::~Config() { save_to_file(); }
Config& Config::get() {
static Config instance;
return instance;
}
toml::table& Config::table() {
return m_tbl;
}
toml::table& Config::table() { return m_tbl; }
void Config::create_config() {
static constexpr auto SOURCE = R"(
@@ -60,26 +55,25 @@ void Config::create_config() {
std::abort();
}
Logger::info("Create New Config File Success");
}
void Config::load_or_create_config() {
fs::path config_path {CONGIF_PATH};
fs::path config_path{CONGIF_PATH};
if (!fs::is_regular_file(config_path)) {
create_config();
} else try {
m_tbl = toml::parse_file(config_path.string());
} catch (const toml::parse_error& err) {
Logger::error("Load Config Error: \"{}\"", err.what());
create_config();
}
Logger::info("Load Config File Success");
} else
try {
m_tbl = toml::parse_file(config_path.string());
} catch (const toml::parse_error& err) {
Logger::error("Load Config Error: \"{}\"", err.what());
create_config();
}
Logger::info("Load Config File Success");
}
void Config::save_to_file() {
fs::path config_path {CONGIF_PATH};
fs::path config_path{CONGIF_PATH};
std::ofstream file{config_path};
file << m_tbl;
Logger::info("Save File Success");
@@ -121,4 +115,4 @@ toml::node_view<toml::node> Config::val_view(std::string_view key) {
return view;
}
}
} // namespace Cubed

View File

@@ -1,15 +1,12 @@
#include <Cubed/debug_collector.hpp>
#include "Cubed/debug_collector.hpp"
#include <Cubed/config.hpp>
#include <Cubed/tools/system_info.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include "Cubed/config.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/system_info.hpp"
namespace Cubed {
DebugCollector::DebugCollector() {
}
DebugCollector::DebugCollector() {}
DebugCollector& DebugCollector::get() {
static DebugCollector instance;
@@ -27,70 +24,54 @@ void DebugCollector::init_text() {
Text opengl_version_text("opengl_version");
Text biome_text("biome");
Text speed_text("speed");
version_text
.position(0.0f, 100.0f)
version_text.position(0.0f, 100.0f)
.scale(0.8f)
.color(Color::WHITE)
.text("Version: " + Config::get().get<std::string>("version"));
fps_text
.position(0.0f, 50.0f)
.text("FPS: 0");
player_pos_text
.position(0.0f, 150.0f)
fps_text.position(0.0f, 50.0f).text("FPS: 0");
player_pos_text.position(0.0f, 150.0f)
.scale(0.8f)
.text("x: 0.00 y: 0.00 z: 0.00");
rendered_chunk_text
.text("Rendered Chunk: 0")
rendered_chunk_text.text("Rendered Chunk: 0")
.scale(0.8f)
.position(0.0, 200.0f);
rss_text
.text("RSS: 0mb")
.scale(0.8f)
.position(0.0f, 300.0f);
rss_text.text("RSS: 0mb").scale(0.8f).position(0.0f, 300.0f);
std::string os;
Text os_text("os");
os_text
.scale(0.8f)
.position(0.0f, 250.0f);
os_text.scale(0.8f).position(0.0f, 250.0f);
if (Tools::get_os_version(os)) {
os_text
.text("OS: " + os);
os_text.text("OS: " + os);
Logger::info("System: {}", os);
} else {
os_text
.text("OS: Unknown");
os_text.text("OS: Unknown");
}
cpu_text
.text("CPU: " + Tools::get_cpu_info())
cpu_text.text("CPU: " + Tools::get_cpu_info())
.scale(0.7f)
.position(0.0f, 350.0f);
gpu_text
.text(std::string{"GPU: "} + reinterpret_cast<const char*>(glGetString(GL_RENDERER)))
.text(std::string{"GPU: "} +
reinterpret_cast<const char*>(glGetString(GL_RENDERER)))
.scale(0.7f)
.position(0.0f, 400.0f);
opengl_version_text
.text("OpenGL: " + std::to_string(GLVersion.major) + "." + std::to_string(GLVersion.minor))
.text("OpenGL: " + std::to_string(GLVersion.major) + "." +
std::to_string(GLVersion.minor))
.scale(0.7f)
.position(0.0f, 450.0f);
biome_text
.text("Biome: ")
.scale(0.8f)
.position(0.0f, 500.0f);
speed_text
.text("Speed: 0 m/s")
.scale(0.8f)
.position(0.0f, 550.0f);
biome_text.text("Biome: ").scale(0.8f).position(0.0f, 500.0f);
speed_text.text("Speed: 0 m/s").scale(0.8f).position(0.0f, 550.0f);
m_texts.insert({version_text.uuid(), std::move(version_text)});
m_texts.insert({fps_text.uuid(), std::move(fps_text)});
m_texts.insert({player_pos_text.uuid(), std::move(player_pos_text)});
m_texts.insert({rendered_chunk_text.uuid(), std::move(rendered_chunk_text)});
m_texts.insert(
{rendered_chunk_text.uuid(), std::move(rendered_chunk_text)});
m_texts.insert({os_text.uuid(), std::move(os_text)});
m_texts.insert({rss_text.uuid(), std::move(rss_text)});
m_texts.insert({cpu_text.uuid(), std::move(cpu_text)});
m_texts.insert({gpu_text.uuid(), std::move(gpu_text)});
m_texts.insert({opengl_version_text.uuid(), std::move(opengl_version_text)});
m_texts.insert(
{opengl_version_text.uuid(), std::move(opengl_version_text)});
m_texts.insert({biome_text.uuid(), std::move(biome_text)});
m_texts.insert({speed_text.uuid(), std::move(speed_text)});
}
@@ -100,7 +81,7 @@ std::unordered_map<std::size_t, Text>& DebugCollector::all_texts() {
}
Text& DebugCollector::text(std::string_view name) {
std::size_t id = HASH::str(name);
std::size_t id = HASH::str(name);
auto it = m_texts.find(id);
ASSERT_MSG(it != m_texts.end(), "Can't Find Text");
return it->second;
@@ -111,4 +92,4 @@ void DebugCollector::report(std::string_view name, std::string_view content) {
t.text(content);
}
}
} // namespace Cubed

View File

@@ -1,8 +1,9 @@
#include <Cubed/dev_panel.hpp>
#include <Cubed/app.hpp>
#include <Cubed/gameplay/player.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/dev_panel.hpp"
#include "Cubed/app.hpp"
#include "Cubed/config.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/tools/log.hpp"
#include <imgui.h>
#include <imgui_impl_glfw.h>
@@ -42,11 +43,7 @@ static int filter_unsigned(ImGuiInputTextCallbackData* data) {
return 0;
}
DevPanel::DevPanel(App& app) :
m_app(app)
{
}
DevPanel::DevPanel(App& app) : m_app(app) {}
void DevPanel::init() {
m_player = &m_app.world().get_player("TestPlayer");
@@ -63,15 +60,14 @@ void DevPanel::render() {
continue;
}
*/
// Start the Dear ImGui frame
ImGui_ImplOpenGL3_NewFrame();
ImGui_ImplGlfw_NewFrame();
ImGui::NewFrame();
ImGui::Begin("DevPanel");
ImGui::Text("This is a DevPanel to control the game\n");
ImGui::Begin("DevPanel");
ImGui::Text("This is a DevPanel to control the game\n");
if (ImGui::BeginTabBar("Menu")) {
show_settings_tab_item();
show_world_tab_item();
@@ -79,15 +75,15 @@ void DevPanel::render() {
show_about_table_bar();
ImGui::EndTabBar();
}
ImGui::End();
ImGui::End();
ImGui::Render();
ImGui_ImplOpenGL3_RenderDrawData(ImGui::GetDrawData());
}
void DevPanel::show_about_table_bar() {
if (ImGui::BeginTabItem("about")) {
ImGui::Text("Cubed - A cube game like Minecraft, using C++ and OpenGL.");
ImGui::Text(
"Cubed - A cube game like Minecraft, using C++ and OpenGL.");
ImGui::Text("Author: zhenyan121");
ImGui::Separator();
ImGui::Text("Libraries Used");
@@ -112,52 +108,116 @@ void DevPanel::show_biome_table_bar() {
ImGui::Text("Biome");
if (ImGui::BeginTabBar("Biome")) {
if (ImGui::BeginTabItem("Plain")) {
ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq One##plain", &plain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX);
ImGui::SliderFloat("Freq Two##plain", &plain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX);
ImGui::SliderFloat("Freq Three##plain", &plain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX);
ImGui::SliderInt("Base Y##plain", &plain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##plain", &plain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::SliderFloat("MinTemp##plain", &plain_params().temp.first,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##plain", &plain_params().temp.second,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##plain", &plain_params().humid.first,
HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##plain", &plain_params().humid.second,
HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq One##plain",
&plain_params().frequencies[0], FREQ1_MIN,
FREQ1_MAX);
ImGui::SliderFloat("Freq Two##plain",
&plain_params().frequencies[1], FREQ2_MIN,
FREQ2_MAX);
ImGui::SliderFloat("Freq Three##plain",
&plain_params().frequencies[2], FREQ3_MIN,
FREQ3_MAX);
ImGui::SliderInt("Base Y##plain",
&plain_params().height_range.base_y,
HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##plain",
&plain_params().height_range.amplitude,
AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Forest")) {
ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##forest", &forest_params().humid.second, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq One##forest", &forest_params().frequencies[0], FREQ1_MIN, FREQ1_MAX);
ImGui::SliderFloat("Freq Two##forest", &forest_params().frequencies[1], FREQ2_MIN, FREQ2_MAX);
ImGui::SliderFloat("Freq Three##forest", &forest_params().frequencies[2], FREQ3_MIN, FREQ3_MAX);
ImGui::SliderInt("Base Y##forest", &forest_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##forest", &forest_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::SliderFloat("Tree Freq##forest", &forest_params().tree_frequency, TREE_FREQ_MIM, TREE_FREQ_MAX);
ImGui::SliderFloat("MinTemp##forest", &forest_params().temp.first,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##forest", &forest_params().temp.second,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##forest", &forest_params().humid.first,
HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##forest",
&forest_params().humid.second, HUMID_MIN,
HUMID_MAX);
ImGui::SliderFloat("Freq One##forest",
&forest_params().frequencies[0], FREQ1_MIN,
FREQ1_MAX);
ImGui::SliderFloat("Freq Two##forest",
&forest_params().frequencies[1], FREQ2_MIN,
FREQ2_MAX);
ImGui::SliderFloat("Freq Three##forest",
&forest_params().frequencies[2], FREQ3_MIN,
FREQ3_MAX);
ImGui::SliderInt("Base Y##forest",
&forest_params().height_range.base_y,
HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##forest",
&forest_params().height_range.amplitude,
AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::SliderFloat("Tree Freq##forest",
&forest_params().tree_frequency, TREE_FREQ_MIM,
TREE_FREQ_MAX);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Desert")) {
ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##desert", &desert_params().humid.second, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq One##desert", &desert_params().frequencies[0], FREQ1_MIN, FREQ1_MAX);
ImGui::SliderFloat("Freq Two##desert", &desert_params().frequencies[1], FREQ2_MIN, FREQ2_MAX);
ImGui::SliderFloat("Freq Three##desert", &desert_params().frequencies[2], FREQ3_MIN, FREQ3_MAX);
ImGui::SliderInt("Base Y##desert", &desert_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##desert", &desert_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::SliderFloat("MinTemp##desert", &desert_params().temp.first,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##desert", &desert_params().temp.second,
TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##desert", &desert_params().humid.first,
HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##desert",
&desert_params().humid.second, HUMID_MIN,
HUMID_MAX);
ImGui::SliderFloat("Freq One##desert",
&desert_params().frequencies[0], FREQ1_MIN,
FREQ1_MAX);
ImGui::SliderFloat("Freq Two##desert",
&desert_params().frequencies[1], FREQ2_MIN,
FREQ2_MAX);
ImGui::SliderFloat("Freq Three##desert",
&desert_params().frequencies[2], FREQ3_MIN,
FREQ3_MAX);
ImGui::SliderInt("Base Y##desert",
&desert_params().height_range.base_y,
HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##desert",
&desert_params().height_range.amplitude,
AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::EndTabItem();
}
if (ImGui::BeginTabItem("Mountain")) {
ImGui::SliderFloat("MinTemp##mountain", &mountain_params().temp.first, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MaxTemp##mountain", &mountain_params().temp.second, TEMP_MIN, TEMP_MAX);
ImGui::SliderFloat("MinHumid##mountain", &mountain_params().humid.first, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("MaxHumid##mountain", &mountain_params().humid.second, HUMID_MIN, HUMID_MAX);
ImGui::SliderFloat("Freq One##mountain", &mountain_params().frequencies[0], FREQ1_MIN, FREQ1_MAX);
ImGui::SliderFloat("Freq Two##mountain", &mountain_params().frequencies[1], FREQ2_MIN, FREQ2_MAX);
ImGui::SliderFloat("Freq Three##mountain", &mountain_params().frequencies[2], FREQ3_MIN, FREQ3_MAX);
ImGui::SliderInt("Base Y##mountain", &mountain_params().height_range.base_y, HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##mountain", &mountain_params().height_range.amplitude, AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::SliderFloat("MinTemp##mountain",
&mountain_params().temp.first, TEMP_MIN,
TEMP_MAX);
ImGui::SliderFloat("MaxTemp##mountain",
&mountain_params().temp.second, TEMP_MIN,
TEMP_MAX);
ImGui::SliderFloat("MinHumid##mountain",
&mountain_params().humid.first, HUMID_MIN,
HUMID_MAX);
ImGui::SliderFloat("MaxHumid##mountain",
&mountain_params().humid.second, HUMID_MIN,
HUMID_MAX);
ImGui::SliderFloat("Freq One##mountain",
&mountain_params().frequencies[0], FREQ1_MIN,
FREQ1_MAX);
ImGui::SliderFloat("Freq Two##mountain",
&mountain_params().frequencies[1], FREQ2_MIN,
FREQ2_MAX);
ImGui::SliderFloat("Freq Three##mountain",
&mountain_params().frequencies[2], FREQ3_MIN,
FREQ3_MAX);
ImGui::SliderInt("Base Y##mountain",
&mountain_params().height_range.base_y,
HEIGHT_BASE_MIN, HEIGHT_BASE_MAX);
ImGui::SliderInt("Amplitude##mountain",
&mountain_params().height_range.amplitude,
AMPLITUDE_MIN, AMPLITUDE_MAX);
ImGui::EndTabItem();
}
ImGui::EndTabBar();
@@ -166,7 +226,7 @@ void DevPanel::show_biome_table_bar() {
void DevPanel::show_settings_tab_item() {
if (ImGui::BeginTabItem("settings")) {
if(ImGui::SliderFloat("FOV", &m_config.fov, 1.0f, 140.0f)) {
if (ImGui::SliderFloat("FOV", &m_config.fov, 1.0f, 140.0f)) {
Config::get().set("player.fov", static_cast<double>(m_config.fov));
m_app.renderer().hot_reload();
}
@@ -176,18 +236,23 @@ void DevPanel::show_settings_tab_item() {
Config::get().set("player.fov", static_cast<double>(m_config.fov));
m_app.renderer().hot_reload();
}
if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity, 0.01f, 1.0f)) {
Config::get().set("player.mouse_sensitivity", static_cast<double>(m_config.mouse_sensitivity));
if (ImGui::SliderFloat("Sensitivity", &m_config.mouse_sensitivity,
0.01f, 1.0f)) {
Config::get().set("player.mouse_sensitivity",
static_cast<double>(m_config.mouse_sensitivity));
m_player->hot_reload();
}
ImGui::SameLine();
if (ImGui::Button("default##2")) {
m_config.mouse_sensitivity = 0.15f;
Config::get().set("player.mouse_sensitivity", static_cast<double>(m_config.mouse_sensitivity));
Config::get().set("player.mouse_sensitivity",
static_cast<double>(m_config.mouse_sensitivity));
m_player->hot_reload();
}
if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2, 128)) {
Config::get().set("world.rendering_distance", m_config.rendering_distance);
if (ImGui::SliderInt("Distance", &m_config.rendering_distance, 2,
128)) {
Config::get().set("world.rendering_distance",
m_config.rendering_distance);
m_app.world().hot_reload();
}
if (ImGui::Checkbox("Fullscreen", &m_config.fullscreen)) {
@@ -211,16 +276,17 @@ void DevPanel::show_settings_tab_item() {
} else {
m_config.aniso = 1;
}
}
if (m_config.is_enable_aniso) {
ImGui::SameLine();
if (!m_config.is_support_aniso) {
ImGui::Text("Not Support\n");
} else {
if (ImGui::SliderInt("##aniso", &m_config.aniso, 2, m_config.max_aniso)) {
if (ImGui::SliderInt("##aniso", &m_config.aniso, 2,
m_config.max_aniso)) {
m_config.is_reload = false;
int log = static_cast<int>(std::log2(m_config.aniso) + 0.5f);
int log =
static_cast<int>(std::log2(m_config.aniso) + 0.5f);
m_config.aniso = static_cast<int>(std::pow(2, log));
if (m_config.aniso < 2) {
m_config.aniso = 2;
@@ -248,28 +314,27 @@ void DevPanel::show_settings_tab_item() {
}
Config::get().set("devpanel.theme", m_theme);
}
if (ImGui::Button("save")) {
if (ImGui::Button("save")) {
Config::get().save_to_file();
}
ImGui::EndTabItem();
}
}
void DevPanel::show_world_tab_item() {
if (ImGui::BeginTabItem("world")) {
if (m_text_editing.perlin_seed) {
if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer, sizeof(perlin_noise_input_buffer),
ImGuiInputTextFlags_CallbackCharFilter |
ImGuiInputTextFlags_EnterReturnsTrue,
filter_unsigned))
{
ChunkGenerator::seed(static_cast<unsigned int>(std::strtoul(perlin_noise_input_buffer, nullptr, 10)));
if (ImGui::InputText("Perlin Noise Seed", perlin_noise_input_buffer,
sizeof(perlin_noise_input_buffer),
ImGuiInputTextFlags_CallbackCharFilter |
ImGuiInputTextFlags_EnterReturnsTrue,
filter_unsigned)) {
ChunkGenerator::seed(static_cast<unsigned int>(
std::strtoul(perlin_noise_input_buffer, nullptr, 10)));
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) {
@@ -306,7 +371,8 @@ void DevPanel::show_player_tab_item() {
return;
}
if (ImGui::BeginTabItem("player")) {
if (ImGui::Combo("GameMode", &m_player_profile.game_mode, GAME_MODES, IM_ARRAYSIZE(GAME_MODES))) {
if (ImGui::Combo("GameMode", &m_player_profile.game_mode, GAME_MODES,
IM_ARRAYSIZE(GAME_MODES))) {
if (m_player_profile.game_mode == 0) {
m_player->change_mode(GameMode::CREATIVE);
} else if (m_player_profile.game_mode == 1) {
@@ -316,7 +382,8 @@ void DevPanel::show_player_tab_item() {
}
}
if (m_player->game_mode() == GameMode::CREATIVE) {
if (ImGui::Combo("Gait", &m_player_profile.gait, GAITS, IM_ARRAYSIZE(GAITS))) {
if (ImGui::Combo("Gait", &m_player_profile.gait, GAITS,
IM_ARRAYSIZE(GAITS))) {
if (m_player_profile.gait == 0) {
m_player->gait() = Gait::WALK;
} else if (m_player_profile.gait == 1) {
@@ -329,50 +396,59 @@ void DevPanel::show_player_tab_item() {
ImGui::DragFloat3("##player_pos", m_player_profile.pos);
ImGui::SameLine();
if (ImGui::Button("TP")) {
m_player->set_player_pos({m_player_profile.pos[0], m_player_profile.pos[1], m_player_profile.pos[2]});
m_player->set_player_pos({m_player_profile.pos[0],
m_player_profile.pos[1],
m_player_profile.pos[2]});
}
ImGui::SliderFloat("Acceleration", &m_player->acceleration(), 1.0f, 200.0f);
ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f, 200.0f);
ImGui::SliderFloat("Acceleration", &m_player->acceleration(), 1.0f,
200.0f);
ImGui::SliderFloat("Deceleration", &m_player->deceleration(), 1.0f,
200.0f);
if (m_player->game_mode() == GameMode::CREATIVE) {
m_player_profile.game_mode = 0;
ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(), 1.0f, 200.0f);
ImGui::SliderFloat("MaxRunSpeed", &m_player->max_run_speed(), 1.0f, 500.0f);
ImGui::SliderFloat("MaxWalkSpeed", &m_player->max_walk_speed(),
1.0f, 200.0f);
ImGui::SliderFloat("MaxRunSpeed", &m_player->max_run_speed(), 1.0f,
500.0f);
ImGui::SliderFloat("G", &m_player->g(), 1.0f, 200.0f);
} else if (m_player->game_mode() == GameMode::SPECTATOR) {
m_player_profile.game_mode = 1;
ImGui::SliderFloat("MaxSpeed", &m_player->max_speed(), 1.0f, 500.0f);
ImGui::SliderFloat("MaxSpeed", &m_player->max_speed(), 1.0f,
500.0f);
}
if (ImGui::Button("reset")) {
m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED;
m_player->max_run_speed() = DEFAULT_MAX_RUN_SPEED;
m_player->acceleration() = DEFAULT_ACCELERATION;
m_player->deceleration() = DEFAULT_DECELERATION;
m_player->g() = DEFAULT_G;
m_player->change_mode(GameMode::CREATIVE);
m_player->gait() = Gait::WALK;
m_player_profile.game_mode = 0;
m_player_profile.gait = 0;
}
m_player->max_walk_speed() = DEFAULT_MAX_WALK_SPEED;
m_player->max_run_speed() = DEFAULT_MAX_RUN_SPEED;
m_player->acceleration() = DEFAULT_ACCELERATION;
m_player->deceleration() = DEFAULT_DECELERATION;
m_player->g() = DEFAULT_G;
m_player->change_mode(GameMode::CREATIVE);
m_player->gait() = Gait::WALK;
m_player_profile.game_mode = 0;
m_player_profile.gait = 0;
}
if (m_player->gait() == Gait::WALK) {
m_player_profile.gait = 0;
} else {
m_player_profile.gait = 1;
}
ImGui::EndTabItem();
}
}
void DevPanel::update_config_view() {
auto config = Config::get();
m_config.fov = static_cast<float>(config.val_view("player.fov").value_or(70.0));
m_config.fov =
static_cast<float>(config.val_view("player.fov").value_or(70.0));
m_config.fullscreen = config.val_view("window.fullscreen").value_or(false);
m_config.v_sync = config.val_view("window.V-Sync").value_or(true);
m_config.mouse_sensitivity = static_cast<float>(config.val_view("player.mouse_sensitivity").value_or(0.15));
m_config.mouse_sensitivity = static_cast<float>(
config.val_view("player.mouse_sensitivity").value_or(0.15));
m_config.width = config.val_view("window.width").value_or(800);
m_config.height = config.val_view("window.height").value_or(600);
m_config.rendering_distance = config.val_view("world.rendering_distance").value_or(24);
m_config.rendering_distance =
config.val_view("world.rendering_distance").value_or(24);
m_theme = config.val_view("devpanel.theme").value_or(0);
if (m_theme != 1 && m_theme != 0) {
m_theme = 0;
@@ -395,4 +471,4 @@ void DevPanel::update_player_profile() {
m_player_profile.game_mode = std::to_underlying(m_player->game_mode());
}
}
} // namespace Cubed

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

View File

@@ -1,17 +1,13 @@
#include <Cubed/input.hpp>
#include <Cubed/tools/cubed_assert.hpp>
namespace Cubed {
#include "Cubed/input.hpp"
namespace Cubed {
static InputState input_state;
namespace Input {
InputState& get_input_state() {
return input_state;
}
}
InputState& get_input_state() { return input_state; }
} // namespace Input
}
} // namespace Cubed

View File

@@ -1,11 +1,9 @@
#include <Cubed/app.hpp>
#include "Cubed/app.hpp"
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);
}

View File

@@ -1,17 +1,18 @@
#include <Cubed/map_table.hpp>
#include <Cubed/gameplay/block.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include "Cubed/map_table.hpp"
#include "Cubed/gameplay/block.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
namespace Cubed {
std::unordered_map<unsigned, std::string> MapTable::id_to_name_map;
std::unordered_map<size_t, unsigned> MapTable::name_to_id_map;
const std::string& MapTable::get_name_from_id(unsigned id) {
auto it = id_to_name_map.find(id);
ASSERT_MSG(it != id_to_name_map.end(), "Id: " + std::to_string(id) + " is not exist");
ASSERT_MSG(it != id_to_name_map.end(),
"Id: " + std::to_string(id) + " is not exist");
return it->second;
}
unsigned MapTable::get_id_from_name(const std::string& name) {
@@ -28,8 +29,6 @@ void MapTable::init_map() {
id_to_name_map[i] = BLOCK_REISTER[i];
name_to_id_map[HASH::str(BLOCK_REISTER[i])] = i;
}
}
}
} // namespace Cubed

View File

@@ -1,33 +1,28 @@
#include <Cubed/app.hpp>
#include <Cubed/camera.hpp>
#include <Cubed/config.hpp>
#include <Cubed/dev_panel.hpp>
#include <Cubed/primitive_data.hpp>
#include <Cubed/debug_collector.hpp>
#include <Cubed/gameplay/player.hpp>
#include <Cubed/gameplay/world.hpp>
#include <Cubed/texture_manager.hpp>
#include <Cubed/renderer.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include <Cubed/tools/font.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/shader_tools.hpp>
#include "Cubed/renderer.hpp"
#include "Cubed/camera.hpp"
#include "Cubed/config.hpp"
#include "Cubed/debug_collector.hpp"
#include "Cubed/dev_panel.hpp"
#include "Cubed/gameplay/player.hpp"
#include "Cubed/gameplay/world.hpp"
#include "Cubed/primitive_data.hpp"
#include "Cubed/texture_manager.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/font.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
#include <GLFW/glfw3.h>
#include <glm/gtc/type_ptr.hpp>
#include <format>
#include <glm/gtc/type_ptr.hpp>
namespace Cubed {
Renderer::Renderer(const Camera& camera, World& world, const TextureManager& texture_manager, DevPanel& dev_panel):
m_camera(camera),
m_dev_panel(dev_panel),
m_texture_manager(texture_manager),
m_world(world)
{
}
Renderer::Renderer(const Camera& camera, World& world,
const TextureManager& texture_manager, DevPanel& dev_panel)
: m_camera(camera), m_dev_panel(dev_panel),
m_texture_manager(texture_manager), m_world(world) {}
Renderer::~Renderer() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
@@ -51,13 +46,19 @@ void Renderer::init() {
exit(EXIT_FAILURE);
}
Logger::info("OpenGL Version: {}.{}", GLVersion.major, GLVersion.minor);
Logger::info("Renderer: {}", reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
Logger::info("Renderer: {}",
reinterpret_cast<const char*>(glGetString(GL_RENDERER)));
Shader world_shader{"world", "shaders/block_v_shader.glsl", "shaders/block_f_shader.glsl"};
Shader outline_shader{"outline", "shaders/outline_v_shader.glsl", "shaders/outline_f_shader.glsl"};
Shader sky_shdaer{"sky", "shaders/sky_v_shader.glsl", "shaders/sky_f_shader.glsl"};
Shader ui_shdaer{"ui", "shaders/ui_v_shader.glsl", "shaders/ui_f_shader.glsl"};
Shader text_shdaer{"text", "shaders/text_v_shader.glsl", "shaders/text_f_shader.glsl"};
Shader world_shader{"world", "shaders/block_v_shader.glsl",
"shaders/block_f_shader.glsl"};
Shader outline_shader{"outline", "shaders/outline_v_shader.glsl",
"shaders/outline_f_shader.glsl"};
Shader sky_shdaer{"sky", "shaders/sky_v_shader.glsl",
"shaders/sky_f_shader.glsl"};
Shader ui_shdaer{"ui", "shaders/ui_v_shader.glsl",
"shaders/ui_f_shader.glsl"};
Shader text_shdaer{"text", "shaders/text_v_shader.glsl",
"shaders/text_f_shader.glsl"};
m_shaders.insert({world_shader.hash(), std::move(world_shader)});
m_shaders.insert({outline_shader.hash(), std::move(outline_shader)});
@@ -70,13 +71,17 @@ void Renderer::init() {
glEnable(GL_BLEND);
glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA);
#ifdef DEBUG_MODE
#ifdef DEBUG_MODE
glEnable(GL_DEBUG_OUTPUT);
glDebugMessageCallback([](GLenum source, GLenum type, GLuint id, GLenum severity, GLsizei length, const GLchar* message, const void* user_param) {
Logger::log(Logger::Level::DEBUG, std::source_location::current(),"GL Debug: {}", reinterpret_cast<const char*>(message));
}, nullptr);
#endif
glDebugMessageCallback(
[](GLenum source, GLenum type, GLuint id, GLenum severity,
GLsizei length, const GLchar* message, const void* user_param) {
Logger::log(Logger::Level::DEBUG, std::source_location::current(),
"GL Debug: {}", reinterpret_cast<const char*>(message));
},
nullptr);
#endif
m_vao.resize(NUM_VAO);
glGenVertexArrays(NUM_VAO, m_vao.data());
@@ -88,30 +93,28 @@ void Renderer::init() {
glGenBuffers(1, &m_outline_indices_vbo);
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, m_outline_indices_vbo);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(OUTLINE_CUBE_INDICES), OUTLINE_CUBE_INDICES, GL_STATIC_DRAW);
glBufferData(GL_ELEMENT_ARRAY_BUFFER, sizeof(OUTLINE_CUBE_INDICES),
OUTLINE_CUBE_INDICES, GL_STATIC_DRAW);
glGenBuffers(1, &m_sky_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_sky_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES_POS), VERTICES_POS, GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(VERTICES_POS), VERTICES_POS,
GL_STATIC_DRAW);
glGenBuffers(1, &m_ui_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo);
for (int i = 0; i < 6; i++) {
Vertex2D vex {
SQUARE_VERTICES[i][0],
SQUARE_VERTICES[i][1],
SQUARE_TEXTURE_POS[i][0],
SQUARE_TEXTURE_POS[i][1],
0
};
Vertex2D vex{SQUARE_VERTICES[i][0], SQUARE_VERTICES[i][1],
SQUARE_TEXTURE_POS[i][0], SQUARE_TEXTURE_POS[i][1], 0};
m_ui.emplace_back(vex);
}
glBufferData(GL_ARRAY_BUFFER, m_ui.size() * sizeof(Vertex2D), m_ui.data(), GL_STATIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, m_ui.size() * sizeof(Vertex2D), m_ui.data(),
GL_STATIC_DRAW);
glGenBuffers(1, &m_text_vbo);
glBindBuffer(GL_ARRAY_BUFFER, m_text_vbo);
glBufferData(GL_ARRAY_BUFFER, sizeof(float)* 6 * 4, NULL, GL_DYNAMIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, sizeof(float) * 6 * 4, NULL, GL_DYNAMIC_DRAW);
glBindBuffer(GL_ARRAY_BUFFER, 0);
init_text();
@@ -155,14 +158,15 @@ void Renderer::render_outline() {
m_mv_loc = shader.loc("mv_matrix");
m_proj_loc = shader.loc("proj_matrix");
const auto& block_pos = m_world.get_look_block_pos("TestPlayer");
if (block_pos != std::nullopt) {
m_m_mat = glm::translate(glm::mat4(1.0f), glm::vec3(block_pos.value().pos));
m_m_mat =
glm::translate(glm::mat4(1.0f), glm::vec3(block_pos.value().pos));
m_mv_mat = m_v_mat * m_m_mat;
glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat));
glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat));
glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat));
glBindBuffer(GL_ARRAY_BUFFER, m_outline_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
@@ -174,23 +178,23 @@ void Renderer::render_outline() {
glLineWidth(4.0f);
glDrawElements(GL_LINES, 24, GL_UNSIGNED_INT, 0);
}
}
void Renderer::render_sky() {
const auto& shader = get_shader("sky");
shader.use();
m_mv_loc = shader.loc("mv_matrix");
m_proj_loc = shader.loc("proj_matrix");
m_m_mat = glm::translate(glm::mat4(1.0f), m_camera.get_camera_pos() - glm::vec3(0.5f, 0.5f, 0.5f));
m_m_mat = glm::translate(glm::mat4(1.0f), m_camera.get_camera_pos() -
glm::vec3(0.5f, 0.5f, 0.5f));
m_v_mat = m_camera.get_camera_lookat();
m_mv_mat = m_v_mat * m_m_mat;
glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat));
glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat));
glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat));
glBindBuffer(GL_ARRAY_BUFFER, m_sky_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 0, 0);
@@ -200,7 +204,6 @@ void Renderer::render_sky() {
glDrawArrays(GL_TRIANGLES, 0, 36);
glEnable(GL_DEPTH_TEST);
}
void Renderer::render_text() {
@@ -234,8 +237,10 @@ void Renderer::render_ui() {
glBindBuffer(GL_ARRAY_BUFFER, m_ui_vbo);
glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, layer));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
@@ -249,28 +254,28 @@ void Renderer::render_ui() {
glBindBuffer(GL_ARRAY_BUFFER, 0);
glEnable(GL_DEPTH_TEST);
}
void Renderer::update_fov(float fov) {
m_fov = fov;
m_p_mat = glm::perspective(glm::radians(fov), m_aspect, 0.1f, 1000.0f);
m_p_mat = glm::perspective(glm::radians(fov), m_aspect, 0.1f, 1000.0f);
}
void Renderer::update_proj_matrix(float aspect, float width, float height) {
m_aspect = aspect;
m_p_mat = glm::perspective(glm::radians(m_fov), aspect, 0.1f, 1000.0f);
m_p_mat = glm::perspective(glm::radians(m_fov), aspect, 0.1f, 1000.0f);
m_ui_proj = glm::ortho(0.0f, width, height, 0.0f, -1.0f, 1.0f);
// scale and then translate
m_ui_m_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(width / 2.0f, height / 2.0f, 0.0)) *
glm::scale(glm::mat4(1.0f), glm::vec3(50.0f, 50.0f, 1.0f));
m_ui_m_matrix =
glm::translate(glm::mat4(1.0f),
glm::vec3(width / 2.0f, height / 2.0f, 0.0)) *
glm::scale(glm::mat4(1.0f), glm::vec3(50.0f, 50.0f, 1.0f));
}
void Renderer::render_world() {
const auto& shader = get_shader("world");
shader.use();
m_mv_loc = shader.loc("mv_matrix");
m_proj_loc = shader.loc("proj_matrix");
glActiveTexture(GL_TEXTURE0);
@@ -278,9 +283,9 @@ void Renderer::render_world() {
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_manager.get_texture_array());
m_m_mat = glm::translate(glm::mat4(1.0f), glm::vec3(0.0f, 0.0f, 0.0f));
m_v_mat = m_camera.get_camera_lookat();
m_mv_mat = m_v_mat * m_m_mat;
m_mv_mat = m_v_mat * m_m_mat;
glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_mv_mat));
glUniformMatrix4fv(m_proj_loc, 1 ,GL_FALSE, glm::value_ptr(m_p_mat));
glUniformMatrix4fv(m_proj_loc, 1, GL_FALSE, glm::value_ptr(m_p_mat));
m_mvp_mat = m_p_mat * m_mv_mat;
m_world.render(m_mvp_mat);
}
@@ -291,4 +296,4 @@ void Renderer::render_dev_panel() {
glEnable(GL_DEPTH_TEST);
}
}
} // namespace Cubed

View File

@@ -1,27 +1,24 @@
#include <Cubed/shader.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/shader_tools.hpp>
#include "Cubed/shader.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
namespace Cubed {
Shader::Shader() {}
Shader::Shader() {
}
Shader::Shader(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path) {
Shader::Shader(const std::string& name, const std::string& v_shader_path,
const std::string& f_shader_path) {
m_program = Tools::create_shader_program(v_shader_path, f_shader_path);
m_name = name;
m_hash = HASH::str(name);
}
Shader::Shader(Shader&& shader) noexcept:
m_program(shader.m_program),
m_hash(shader.m_hash),
m_name(std::move(shader.m_name))
{
Shader::Shader(Shader&& shader) noexcept
: m_program(shader.m_program), m_hash(shader.m_hash),
m_name(std::move(shader.m_name)) {
shader.m_hash = 0;
shader.m_program = 0;
}
@@ -32,7 +29,7 @@ Shader::~Shader() {
}
}
Shader& Shader::operator=(Shader&& shader) noexcept{
Shader& Shader::operator=(Shader&& shader) noexcept {
m_hash = shader.m_hash;
m_name = std::move(shader.m_name);
m_program = shader.m_program;
@@ -41,7 +38,8 @@ Shader& Shader::operator=(Shader&& shader) noexcept{
return *this;
}
void Shader::create(const std::string& name, const std::string& v_shader_path, const std::string& f_shader_path) {
void Shader::create(const std::string& name, const std::string& v_shader_path,
const std::string& f_shader_path) {
if (!m_program) {
Logger::warn("Shader has already created !");
return;
@@ -72,14 +70,13 @@ GLuint Shader::loc(const std::string& loc) const {
const std::string& Shader::name() const {
if (m_name == "-1") {
Logger::warn("Shader has already created !");
}
return m_name;
}
void Shader::use() const{
void Shader::use() const {
ASSERT_MSG(m_program, "Shader don't create !");
glUseProgram(m_program);
}
}
} // namespace Cubed

View File

@@ -1,19 +1,17 @@
#include <Cubed/texture_manager.hpp>
#include <Cubed/constants.hpp>
#include <Cubed/map_table.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include "Cubed/texture_manager.hpp"
#include "Cubed/config.hpp"
#include "Cubed/constants.hpp"
#include "Cubed/map_table.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
namespace Cubed {
TextureManager::TextureManager() {}
TextureManager::TextureManager() {
}
TextureManager::~TextureManager() {
delet_texture();
}
TextureManager::~TextureManager() { delet_texture(); }
void TextureManager::delet_texture() {
glDeleteTextures(1, &m_texture_array);
@@ -21,17 +19,13 @@ void TextureManager::delet_texture() {
Logger::info("Successfully delete all texture");
}
GLuint TextureManager::get_block_status_array() const{
GLuint TextureManager::get_block_status_array() const {
return m_block_status_array;
}
GLuint TextureManager::get_texture_array() const{
return m_texture_array;
}
GLuint TextureManager::get_texture_array() const { return m_texture_array; }
GLuint TextureManager::get_ui_array() const{
return m_ui_array;
}
GLuint TextureManager::get_ui_array() const { return m_ui_array; }
void TextureManager::load_block_status(unsigned id) {
@@ -40,12 +34,8 @@ void TextureManager::load_block_status(unsigned id) {
unsigned char* image_data = nullptr;
image_data = (Tools::load_image_data(path));
glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0,
0 ,0, id,
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data
);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA,
GL_UNSIGNED_BYTE, image_data);
Tools::delete_image_data(image_data);
}
@@ -65,20 +55,15 @@ void TextureManager::load_block_texture(unsigned id) {
image_data[3] = (Tools::load_image_data(block_texture_path + "/left.png"));
image_data[4] = (Tools::load_image_data(block_texture_path + "/top.png"));
image_data[5] = (Tools::load_image_data(block_texture_path + "/base.png"));
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array);
Tools::check_opengl_error();
for (int i = 0; i < 6; i++) {
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0,
0, 0, id * 6 + i,
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data[i]
);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id * 6 + i, 16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE, image_data[i]);
Tools::check_opengl_error();
Tools::delete_image_data(image_data[i]);
}
}
void TextureManager::load_ui_texture(unsigned id) {
@@ -88,20 +73,16 @@ void TextureManager::load_ui_texture(unsigned id) {
unsigned char* image_data = nullptr;
image_data = (Tools::load_image_data(path));
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0,
0 ,0, id,
16, 16, 1,
GL_RGBA, GL_UNSIGNED_BYTE,
image_data
);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, id, 16, 16, 1, GL_RGBA,
GL_UNSIGNED_BYTE, image_data);
Tools::delete_image_data(image_data);
}
void TextureManager::init_texture() {
glGetFloatv(GL_MAX_TEXTURE_MAX_ANISOTROPY, &m_max_aniso);
if (m_max_aniso > 0.0f) {
Logger::info("Support anisotropic filtering max_aniso is {}", m_max_aniso);
Logger::info("Support anisotropic filtering max_aniso is {}",
m_max_aniso);
}
m_aniso = Config::get().get<int>("texture.aniso");
m_aniso = std::min(static_cast<int>(m_max_aniso), m_aniso);
@@ -112,12 +93,8 @@ void TextureManager::init_texture() {
Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_texture_array);
Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY,
0, GL_RGBA,
16, 16,
MAX_BLOCK_NUM * 6,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_NUM * 6, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error();
for (int i = 0; i < MAX_BLOCK_NUM; i++) {
load_block_texture(i);
@@ -127,24 +104,22 @@ void TextureManager::init_texture() {
Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
Tools::check_opengl_error();
glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
Tools::check_opengl_error();
if (m_aniso >= 1) {
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast<GLfloat>(m_aniso));
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY,
static_cast<GLfloat>(m_aniso));
}
glGenTextures(1, &m_block_status_array);
Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_block_status_array);
Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY,
0, GL_RGBA,
16, 16,
MAX_BLOCK_STATUS,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_BLOCK_STATUS, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error();
for (int i = 0; i < MAX_BLOCK_STATUS; i++) {
load_block_status(i);
@@ -154,25 +129,23 @@ void TextureManager::init_texture() {
Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
Tools::check_opengl_error();
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER,
GL_LINEAR_MIPMAP_LINEAR);
Tools::check_opengl_error();
glGenerateMipmap(GL_TEXTURE_2D_ARRAY);
Tools::check_opengl_error();
if (m_aniso >= 1) {
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY, static_cast<GLfloat>(m_aniso));
glTexParameterf(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAX_ANISOTROPY,
static_cast<GLfloat>(m_aniso));
}
glGenTextures(1, &m_ui_array);
Tools::check_opengl_error();
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array);
Tools::check_opengl_error();
glTexImage3D(GL_TEXTURE_2D_ARRAY,
0, GL_RGBA,
16, 16,
MAX_UI_NUM,
0, GL_RGBA,
GL_UNSIGNED_BYTE, nullptr);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RGBA, 16, 16, MAX_UI_NUM, 0,
GL_RGBA, GL_UNSIGNED_BYTE, nullptr);
Tools::check_opengl_error();
for (int i = 0; i < MAX_UI_NUM; i++) {
load_ui_texture(i);
@@ -180,9 +153,7 @@ void TextureManager::init_texture() {
glBindTexture(GL_TEXTURE_2D_ARRAY, m_ui_array);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
}
void TextureManager::update() {
@@ -191,19 +162,15 @@ void TextureManager::update() {
}
}
void TextureManager::need_reload() {
m_need_reload = true;
}
void TextureManager::need_reload() { m_need_reload = true; }
void TextureManager::hot_reload() {
delet_texture();
init_texture();
m_need_reload = false;
}
int TextureManager::max_aniso() const {
return static_cast<int>(m_max_aniso);
}
int TextureManager::max_aniso() const { return static_cast<int>(m_max_aniso); }
}
} // namespace Cubed

View File

@@ -1,30 +1,23 @@
#include <Cubed/tools/cubed_random.hpp>
#include <Cubed/tools/log.hpp>
#include "Cubed/tools/cubed_random.hpp"
#include "Cubed/tools/log.hpp"
namespace Cubed {
Random::Random() {
}
Random::Random() {}
bool Random::random_bool(double probability) {
std::bernoulli_distribution dist(probability);
return dist(m_engine);
}
std::mt19937& Random::engine() {
return m_engine;
}
std::mt19937& Random::engine() { return m_engine; }
unsigned Random::seed() {
return m_seed;
}
unsigned Random::seed() { return m_seed; }
void Random::init(unsigned seed) {
m_seed = seed;
m_engine.seed(seed);
}
}
} // namespace Cubed

View File

@@ -1,14 +1,14 @@
#include <Cubed/tools/font.hpp>
#include <Cubed/constants.hpp>
#include <Cubed/shader.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/tools/shader_tools.hpp>
#include "Cubed/tools/font.hpp"
#include "Cubed/constants.hpp"
#include "Cubed/shader.hpp"
#include "Cubed/tools/log.hpp"
#include "Cubed/tools/shader_tools.hpp"
namespace fs = std::filesystem;
namespace Cubed {
Font::Font() {
if (FT_Init_FreeType(&m_ft)) {
@@ -18,12 +18,12 @@ Font::Font() {
Logger::error("FREETYPE: Failed to load font");
}
FT_Set_Pixel_Sizes(m_face, 0, 48);
FT_Set_Pixel_Sizes(m_face, 0, 48);
setup_font_character();
}
Font::~Font() {
FT_Done_Face(m_face);
FT_Done_FreeType(m_ft);
glDeleteTextures(1, &m_text_texture);
@@ -31,54 +31,35 @@ Font::~Font() {
void Font::load_character(char8_t c) {
if (FT_Load_Char(m_face, c, FT_LOAD_RENDER)) {
Logger::error("FREETYTPE: Failed to load Glyph");
return;
}
const auto& width = m_face->glyph->bitmap.width;
const auto& height = m_face->glyph->bitmap.rows;
glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture);
glTexSubImage3D(
GL_TEXTURE_2D_ARRAY,
0,
0,
0,
static_cast<int>(c),
width,
height,
1,
GL_RED,
GL_UNSIGNED_BYTE,
m_face->glyph->bitmap.buffer
);
Logger::error("FREETYTPE: Failed to load Glyph");
return;
}
const auto& width = m_face->glyph->bitmap.width;
const auto& height = m_face->glyph->bitmap.rows;
glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture);
glTexSubImage3D(GL_TEXTURE_2D_ARRAY, 0, 0, 0, static_cast<int>(c), width,
height, 1, GL_RED, GL_UNSIGNED_BYTE,
m_face->glyph->bitmap.buffer);
Character character = {
glm::vec2{0.0f, 0.0f},
glm::vec2{static_cast<float>(width) / m_texture_width, static_cast<float>(height) / m_texture_height},
glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows),
glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top),
static_cast<GLuint>(m_face->glyph->advance.x)
};
Character character = {
glm::vec2{0.0f, 0.0f},
glm::vec2{static_cast<float>(width) / m_texture_width,
static_cast<float>(height) / m_texture_height},
glm::ivec2(m_face->glyph->bitmap.width, m_face->glyph->bitmap.rows),
glm::ivec2(m_face->glyph->bitmap_left, m_face->glyph->bitmap_top),
static_cast<GLuint>(m_face->glyph->advance.x)};
m_characters.insert({c, std::move(character)});
m_characters.insert({c, std::move(character)});
}
void Font::setup_font_character() {
glPixelStorei(GL_UNPACK_ALIGNMENT, 1);
glGenTextures(1, &m_text_texture);
glBindTexture(GL_TEXTURE_2D_ARRAY, m_text_texture);
glTexImage3D(
GL_TEXTURE_2D_ARRAY,
0,
GL_RED,
m_texture_width,
m_texture_height,
MAX_CHARACTER,
0,
GL_RED,
GL_UNSIGNED_BYTE,
nullptr
);
glTexImage3D(GL_TEXTURE_2D_ARRAY, 0, GL_RED, m_texture_width,
m_texture_height, MAX_CHARACTER, 0, GL_RED, GL_UNSIGNED_BYTE,
nullptr);
for (char8_t c = 0; c < 128; c++) {
load_character(c);
@@ -88,12 +69,13 @@ void Font::setup_font_character() {
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(GL_TEXTURE_2D_ARRAY, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
glBindTexture(GL_TEXTURE_2D_ARRAY, 0);
}
std::vector<Vertex2D> Font::vertices(const std::string &text, float x, float y, float scale) {
std::vector<Vertex2D> Font::vertices(const std::string& text, float x, float y,
float scale) {
static Font font;
std::vector<Vertex2D> vertices;
for (char8_t c : text) {
@@ -109,26 +91,27 @@ std::vector<Vertex2D> Font::vertices(const std::string &text, float x, float y,
float w = ch.size.x * scale;
float h = ch.size.y * scale;
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast<float>(c));
vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y, static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast<float>(c));
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y, static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y, static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y, static_cast<float>(c));
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y,
static_cast<float>(c));
vertices.emplace_back(xpos, ypos, ch.uv_min.x, ch.uv_min.y,
static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y,
static_cast<float>(c));
vertices.emplace_back(xpos, ypos + h, ch.uv_min.x, ch.uv_max.y,
static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos, ch.uv_max.x, ch.uv_min.y,
static_cast<float>(c));
vertices.emplace_back(xpos + w, ypos + h, ch.uv_max.x, ch.uv_max.y,
static_cast<float>(c));
x += (ch.advance >> 6) * scale;
}
return vertices;
}
GLuint Font::text_texture() {
return m_text_texture;
}
GLuint Font::text_texture() { return m_text_texture; }
const std::string& Font::font_path() {
return m_font_path;
}
const std::string& Font::font_path() { return m_font_path; }
}
} // namespace Cubed

View File

@@ -1,38 +1,42 @@
#include <Cubed/tools/math_tools.hpp>
#include "Cubed/tools/math_tools.hpp"
#include <glm/gtc/type_ptr.hpp>
namespace Cubed {
namespace Math {
void extract_frustum_planes(const glm::mat4& mvp_matrix, std::vector<glm::vec4>& planes) {
if (planes.size() != 6) {
planes.resize(6);
}
const float* m = glm::value_ptr(mvp_matrix);
// left plane
planes[0] = glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]);
// right plane
planes[1] = glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]);
// bottom plane
planes[2] = glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]);
// top plane
planes[3] = glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]);
// near plane
planes[4] = glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]);
// far plane
planes[5] = glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]);
for (auto& p : planes) {
p = glm::normalize(p);
}
void extract_frustum_planes(const glm::mat4& mvp_matrix,
std::vector<glm::vec4>& planes) {
if (planes.size() != 6) {
planes.resize(6);
}
const float* m = glm::value_ptr(mvp_matrix);
// left plane
planes[0] =
glm::vec4(m[3] + m[0], m[7] + m[4], m[11] + m[8], m[15] + m[12]);
// right plane
planes[1] =
glm::vec4(m[3] - m[0], m[7] - m[4], m[11] - m[8], m[15] - m[12]);
// bottom plane
planes[2] =
glm::vec4(m[3] + m[1], m[7] + m[5], m[11] + m[9], m[15] + m[13]);
// top plane
planes[3] =
glm::vec4(m[3] - m[1], m[7] - m[5], m[11] - m[9], m[15] - m[13]);
// near plane
planes[4] =
glm::vec4(m[3] + m[2], m[7] + m[6], m[11] + m[10], m[15] + m[14]);
// far plane
planes[5] =
glm::vec4(m[3] - m[2], m[7] - m[6], m[11] - m[10], m[15] - m[14]);
for (auto& p : planes) {
p = glm::normalize(p);
}
}
} // namespace Math
}
} // namespace Cubed

View File

@@ -1,15 +1,15 @@
#include <Cubed/tools/perlin_noise.hpp>
#include "Cubed/tools/perlin_noise.hpp"
#include "Cubed/config.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/cubed_random.hpp"
#include <Cubed/config.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/cubed_random.hpp>
#include <algorithm>
#include <numeric>
#include <random>
namespace Cubed {
void PerlinNoise::init(unsigned seed) {
p.resize(256);
std::iota(p.begin(), p.end(), 0);
@@ -41,27 +41,23 @@ float PerlinNoise::noise(float x, float y, float z) {
int ba = p[b] + iz;
int bb = p[b + 1] + iz;
float res = lerp (w,
lerp (v,
lerp(u, grad(p[aa], x, y, z), grad(p[ba], x - 1, y, z)),
lerp(u, grad(p[ab], x, y - 1, z), grad(p[bb], x - 1, y - 1, z))
),
float res = lerp(
w,
lerp(v, lerp(u, grad(p[aa], x, y, z), grad(p[ba], x - 1, y, z)),
lerp(u, grad(p[ab], x, y - 1, z), grad(p[bb], x - 1, y - 1, z))),
lerp(v,
lerp(u, grad(p[aa + 1], x, y, z - 1), grad(p[ba + 1], x - 1, y, z - 1)),
lerp(u, grad(p[ab + 1], x, y - 1, z - 1), grad(p[bb + 1 ], x - 1, y - 1, z - 1))
)
lerp(u, grad(p[aa + 1], x, y, z - 1),
grad(p[ba + 1], x - 1, y, z - 1)),
lerp(u, grad(p[ab + 1], x, y - 1, z - 1),
grad(p[bb + 1], x - 1, y - 1, z - 1)))
);
return (res + 1.0f) / 2.0f;
}
float PerlinNoise::fade(float t) {
return t * t * t * (t * (t * 6 - 15) + 10);
}
float PerlinNoise::fade(float t) { return t * t * t * (t * (t * 6 - 15) + 10); }
float PerlinNoise::lerp(float t, float a, float b) {
return a + t * (b - a);
}
float PerlinNoise::lerp(float t, float a, float b) { return a + t * (b - a); }
float PerlinNoise::grad(int hash, float x, float y, float z) {
int h = hash & 15;
@@ -83,4 +79,4 @@ void PerlinNoise::reload(unsigned seed) {
is_init = true;
}
}
} // namespace Cubed

View File

@@ -1,140 +1,138 @@
#include <fstream>
#include <filesystem>
#include "Cubed/tools/shader_tools.hpp"
#include <Cubed/config.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/shader_tools.hpp>
#include <Cubed/tools/log.hpp>
#include "Cubed/config.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/log.hpp"
#include <filesystem>
#include <fstream>
namespace Cubed {
namespace fs = std::filesystem;
namespace Tools {
GLuint create_shader_program(const std::string& v_shader_path, const std::string& f_shader_path) {
GLuint create_shader_program(const std::string& v_shader_path,
const std::string& f_shader_path) {
std::string v_shader_str = Tools::read_shader_source(ASSETS_PATH + v_shader_path);
std::string f_shader_str = Tools::read_shader_source(ASSETS_PATH + f_shader_path);
const char *v_shader_source = v_shader_str.c_str();
const char *f_shader_source = f_shader_str.c_str();
std::string v_shader_str =
Tools::read_shader_source(ASSETS_PATH + v_shader_path);
std::string f_shader_str =
Tools::read_shader_source(ASSETS_PATH + f_shader_path);
const char* v_shader_source = v_shader_str.c_str();
const char* f_shader_source = f_shader_str.c_str();
GLuint v_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint f_shader = glCreateShader(GL_FRAGMENT_SHADER);
GLuint v_shader = glCreateShader(GL_VERTEX_SHADER);
GLuint f_shader = glCreateShader(GL_FRAGMENT_SHADER);
GLint vc, fc;
glShaderSource(v_shader, 1, &v_shader_source, NULL);
glShaderSource(f_shader, 1, &f_shader_source, NULL);
glCompileShader(v_shader);
Tools::check_opengl_error();
glGetShaderiv(v_shader, GL_COMPILE_STATUS, &vc);
if (vc != 1) {
Logger::error("vertex compilation failed");
Tools::print_shader_log(v_shader);
ASSERT(0);
}
glCompileShader(f_shader);
Tools::check_opengl_error();
glGetShaderiv(f_shader, GL_COMPILE_STATUS, &fc);
if (fc != 1) {
Logger::error("vertex compilation failed");
Tools::print_shader_log(f_shader);
ASSERT(0);
}
GLuint vf_program = glCreateProgram();
glAttachShader(vf_program, v_shader);
glAttachShader(vf_program, f_shader);
glLinkProgram(vf_program);
GLint linked;
Tools::check_opengl_error();
glGetProgramiv(vf_program, GL_LINK_STATUS, &linked);
if (linked != 1) {
Logger::error("linking failed");
Tools::print_program_info(vf_program);
ASSERT(0);
}
glDeleteShader(v_shader);
glDeleteShader(f_shader);
return vf_program;
GLint vc, fc;
glShaderSource(v_shader, 1, &v_shader_source, NULL);
glShaderSource(f_shader, 1, &f_shader_source, NULL);
glCompileShader(v_shader);
Tools::check_opengl_error();
glGetShaderiv(v_shader, GL_COMPILE_STATUS, &vc);
if (vc != 1) {
Logger::error("vertex compilation failed");
Tools::print_shader_log(v_shader);
ASSERT(0);
}
void print_shader_log(GLuint shader) {
int len = 0;
int ch_written = 0;
char *log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetShaderInfoLog(shader, len, &ch_written, log);
Logger::info("Shader Info Log: {}", log);
free(log);
}
}
void print_program_info(int prog) {
int len = 0;
int ch_written = 0;
char *log;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetProgramInfoLog(prog, len, &ch_written, log);
Logger::info("Program Info Log: {}", log);
free(log);
}
glCompileShader(f_shader);
Tools::check_opengl_error();
glGetShaderiv(f_shader, GL_COMPILE_STATUS, &fc);
if (fc != 1) {
Logger::error("vertex compilation failed");
Tools::print_shader_log(f_shader);
ASSERT(0);
}
GLuint vf_program = glCreateProgram();
glAttachShader(vf_program, v_shader);
glAttachShader(vf_program, f_shader);
glLinkProgram(vf_program);
bool check_opengl_error() {
bool found_error = false;
int gl_err = glGetError();
while (gl_err != GL_NO_ERROR) {
Logger::error("glEorr: {}", gl_err);
found_error = true;
gl_err = glGetError();
}
return found_error;
GLint linked;
Tools::check_opengl_error();
glGetProgramiv(vf_program, GL_LINK_STATUS, &linked);
if (linked != 1) {
Logger::error("linking failed");
Tools::print_program_info(vf_program);
ASSERT(0);
}
std::string read_shader_source(const std::string& file_path) {
std::string content;
std::ifstream file_stream(file_path, std::ios::in);
if (!file_stream.is_open()) {
Logger::error("{} not exist", file_path);
}
std::string line = "";
while (!file_stream.eof()) {
getline(file_stream, line);
content.append(line + "\n");
}
file_stream.close();
return content;
}
void delete_image_data(unsigned char* data) {
SOIL_free_image_data(data);
}
unsigned char* load_image_data(const std::string& tex_image_path) {
fs::path path = ASSETS_PATH + tex_image_path;
ASSERT_MSG(fs::is_regular_file(path), path.c_str());
unsigned char* data = nullptr;
int width, height, channels;
data = SOIL_load_image(path.string().c_str(), &width, &height, &channels, SOIL_LOAD_AUTO);
ASSERT_MSG(data, "Could not load texture" + path.string());
return data;
}
glDeleteShader(v_shader);
glDeleteShader(f_shader);
return vf_program;
}
}
void print_shader_log(GLuint shader) {
int len = 0;
int ch_written = 0;
char* log;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetShaderInfoLog(shader, len, &ch_written, log);
Logger::info("Shader Info Log: {}", log);
free(log);
}
}
void print_program_info(int prog) {
int len = 0;
int ch_written = 0;
char* log;
glGetProgramiv(prog, GL_INFO_LOG_LENGTH, &len);
if (len > 0) {
log = (char*)malloc(len);
glGetProgramInfoLog(prog, len, &ch_written, log);
Logger::info("Program Info Log: {}", log);
free(log);
}
}
bool check_opengl_error() {
bool found_error = false;
int gl_err = glGetError();
while (gl_err != GL_NO_ERROR) {
Logger::error("glEorr: {}", gl_err);
found_error = true;
gl_err = glGetError();
}
return found_error;
}
std::string read_shader_source(const std::string& file_path) {
std::string content;
std::ifstream file_stream(file_path, std::ios::in);
if (!file_stream.is_open()) {
Logger::error("{} not exist", file_path);
}
std::string line = "";
while (!file_stream.eof()) {
getline(file_stream, line);
content.append(line + "\n");
}
file_stream.close();
return content;
}
void delete_image_data(unsigned char* data) { SOIL_free_image_data(data); }
unsigned char* load_image_data(const std::string& tex_image_path) {
fs::path path = ASSETS_PATH + tex_image_path;
ASSERT_MSG(fs::is_regular_file(path), path.c_str());
unsigned char* data = nullptr;
int width, height, channels;
data = SOIL_load_image(path.string().c_str(), &width, &height, &channels,
SOIL_LOAD_AUTO);
ASSERT_MSG(data, "Could not load texture" + path.string());
return data;
}
} // namespace Tools
} // namespace Cubed

View File

@@ -1,26 +1,19 @@
#include <Cubed/ui/text.hpp>
#include "Cubed/ui/text.hpp"
#include <Cubed/shader.hpp>
#include <Cubed/tools/cubed_hash.hpp>
#include <Cubed/tools/font.hpp>
#include "Cubed/shader.hpp"
#include "Cubed/tools/cubed_hash.hpp"
#include "Cubed/tools/font.hpp"
#include <glm/gtc/matrix_transform.hpp>
#include <glm/gtc/type_ptr.hpp>
namespace Cubed {
Text::Text(std::string_view name) : NAME(name), UUID(HASH::str(name)) {}
Text::Text(std::string_view name) :
NAME(name),
UUID(HASH::str(name))
{
}
Text::Text(std::string_view name, std::string_view str, glm::vec2 pos, Color color) :
NAME(name),
UUID(HASH::str(name))
{
Text::Text(std::string_view name, std::string_view str, glm::vec2 pos,
Color color)
: NAME(name), UUID(HASH::str(name)) {
m_text.assign(str);
m_pos = pos;
m_color = color_value(color);
@@ -33,17 +26,11 @@ Text::~Text() {
}
}
Text::Text(Text&& other) noexcept :
m_scale(other.m_scale),
m_pos(other.m_pos),
NAME(other.NAME),
UUID(other.UUID),
m_text(std::move(other.m_text)),
m_color(other.m_color),
m_model_matrix(other.m_model_matrix),
m_vertices(std::move(other.m_vertices)),
m_vbo(other.m_vbo)
{
Text::Text(Text&& other) noexcept
: m_scale(other.m_scale), m_pos(other.m_pos), NAME(other.NAME),
UUID(other.UUID), m_text(std::move(other.m_text)), m_color(other.m_color),
m_model_matrix(other.m_model_matrix),
m_vertices(std::move(other.m_vertices)), m_vbo(other.m_vbo) {
other.m_vbo = 0;
}
@@ -62,9 +49,7 @@ Text& Text::scale(float s) {
return *this;
}
std::size_t Text::uuid() const {
return UUID;
}
std::size_t Text::uuid() const { return UUID; }
void Text::set_loc(const Shader& shader) {
m_color_loc = shader.loc("textColor");
@@ -78,22 +63,25 @@ Text& Text::text(std::string_view str) {
}
void Text::render() {
ASSERT_MSG(m_vbo != 0,"VBO not initialized!");
ASSERT_MSG(m_vbo != 0, "VBO not initialized!");
ASSERT_MSG(!m_vertices.empty(), "Text String Not Set");
glActiveTexture(GL_TEXTURE0);
glBindTexture(GL_TEXTURE_2D_ARRAY, Font::text_texture());
ASSERT_MSG(m_color_loc, "m_color_loc is null");
m_model_matrix = glm::translate(glm::mat4(1.0f), glm::vec3(m_pos.x, m_pos.y, 0.0f)) *
glm::scale(glm::mat4(1.0f), glm::vec3(m_scale, m_scale, 1.0f));
m_model_matrix =
glm::translate(glm::mat4(1.0f), glm::vec3(m_pos.x, m_pos.y, 0.0f)) *
glm::scale(glm::mat4(1.0f), glm::vec3(m_scale, m_scale, 1.0f));
glUniform3f(m_color_loc, m_color.x, m_color.y, m_color.z);
glUniformMatrix4fv(m_mv_loc, 1, GL_FALSE, glm::value_ptr(m_model_matrix));
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glVertexAttribPointer(0, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)0);
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D), (void*)offsetof(Vertex2D, layer));
glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, s));
glVertexAttribPointer(2, 1, GL_FLOAT, GL_FALSE, sizeof(Vertex2D),
(void*)offsetof(Vertex2D, layer));
glEnableVertexAttribArray(0);
glEnableVertexAttribArray(1);
@@ -115,11 +103,10 @@ void Text::upload_to_gpu() {
}
ASSERT_MSG(m_vbo, "Vbo Is Not Gen");
glBindBuffer(GL_ARRAY_BUFFER, m_vbo);
glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex2D), m_vertices.data(), GL_DYNAMIC_DRAW);
glBufferData(GL_ARRAY_BUFFER, m_vertices.size() * sizeof(Vertex2D),
m_vertices.data(), GL_DYNAMIC_DRAW);
}
bool Text::operator==(const Text& other) const {
return UUID == other.uuid();
}
bool Text::operator==(const Text& other) const { return UUID == other.uuid(); }
}
} // namespace Cubed

View File

@@ -1,10 +1,10 @@
#include <Cubed/renderer.hpp>
#include <Cubed/input.hpp>
#include <Cubed/tools/cubed_assert.hpp>
#include <Cubed/tools/log.hpp>
#include <Cubed/window.hpp>
#include "Cubed/window.hpp"
#include <Cubed/tools/font.hpp>
#include "Cubed/config.hpp"
#include "Cubed/renderer.hpp"
#include "Cubed/tools/cubed_assert.hpp"
#include "Cubed/tools/font.hpp"
#include "Cubed/tools/log.hpp"
#include <imgui.h>
#include <imgui_impl_glfw.h>
@@ -15,11 +15,7 @@ namespace Cubed {
static int windowed_xpos = 0, windowed_ypos = 0;
static int windowed_width = 800, windowed_height = 600;
Window::Window(Renderer& renderer) :
m_renderer(renderer)
{
}
Window::Window(Renderer& renderer) : m_renderer(renderer) {}
Window::~Window() {
@@ -31,62 +27,55 @@ Window::~Window() {
glfwDestroyWindow(m_window);
m_window = nullptr;
}
glfwTerminate();
}
bool Window::is_mouse_enable() const {
return m_mouse_enable;
}
bool Window::is_mouse_enable() const { return m_mouse_enable; }
const GLFWwindow* Window::get_glfw_window() const {
return m_window;
}
const GLFWwindow* Window::get_glfw_window() const { return m_window; }
GLFWwindow* Window::get_glfw_window() {
return m_window;
}
GLFWwindow* Window::get_glfw_window() { return m_window; }
void Window::update_viewport() {
glfwGetFramebufferSize(m_window, &m_width, &m_height);
m_aspect = (float)m_width / (float)m_height;
glViewport(0, 0, m_width, m_height);
m_renderer.update_proj_matrix(m_aspect, m_width, m_height) ;
m_renderer.update_proj_matrix(m_aspect, m_width, m_height);
auto& config = Config::get();
config.set("window.width", windowed_width);
config.set("window.height", windowed_height);
}
void Window::init() {
if (!glfwInit()) {
Logger::error("glfw init fail");
exit(EXIT_FAILURE);
exit(EXIT_FAILURE);
}
glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 6);
glfwWindowHint(GLFW_RESIZABLE, GLFW_TRUE);
auto& config= Config::get();
auto& config = Config::get();
m_width = config.get<int>("window.width");
m_height = config.get<int>("window.height");
if (config.get<bool>("window.fullscreen")) {
GLFWmonitor* primary_monitor = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary_monitor);
m_window = glfwCreateWindow(mode->width, mode->height, "Cubed", primary_monitor, NULL);
m_window = glfwCreateWindow(mode->width, mode->height, "Cubed",
primary_monitor, NULL);
} else {
m_window = glfwCreateWindow(m_width, m_height, "Cubed", NULL, NULL);
}
glfwMakeContextCurrent(m_window);
if (config.get<bool>("window.V-Sync")) {
glfwSwapInterval(1);
glfwSwapInterval(1);
} else {
glfwSwapInterval(0);
glfwSwapInterval(0);
}
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
if (glfwRawMouseMotionSupported()) {
glfwSetInputMode(m_window, GLFW_RAW_MOUSE_MOTION, GLFW_TRUE);
@@ -96,17 +85,17 @@ void Window::init() {
GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowPos(m_window, static_cast<int>(mode->width / 2.0f) - 400, static_cast<int>(mode->height / 2.0f) - 300);
glfwSetWindowPos(m_window, static_cast<int>(mode->width / 2.0f) - 400,
static_cast<int>(mode->height / 2.0f) - 300);
}
void Window::hot_reload() {
auto& config= Config::get();
auto& config = Config::get();
// V-Sync
if (config.get<bool>("window.V-Sync")) {
glfwSwapInterval(1);
glfwSwapInterval(1);
} else {
glfwSwapInterval(0);
glfwSwapInterval(0);
}
// Window
windowed_width = config.get<int>("window.width");
@@ -119,27 +108,14 @@ void Window::hot_reload() {
GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowMonitor(
m_window,
primary,
0,
0,
mode->width,
mode->height,
GL_DONT_CARE
);
glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height,
GL_DONT_CARE);
} else {
GLFWmonitor* monitor = glfwGetWindowMonitor(m_window);
if (monitor != nullptr) {
glfwSetWindowMonitor(
m_window,
nullptr,
windowed_xpos,
windowed_ypos,
windowed_width,
windowed_height,
0
);
glfwSetWindowMonitor(m_window, nullptr, windowed_xpos,
windowed_ypos, windowed_width, windowed_height,
0);
} else {
Logger::error("Can't Find Monitor");
}
@@ -157,16 +133,9 @@ void Window::toggle_fullscreen() {
auto& config = Config::get();
GLFWmonitor* monitor = glfwGetWindowMonitor(m_window);
if (monitor != nullptr) {
glfwSetWindowMonitor(
m_window,
nullptr,
windowed_xpos,
windowed_ypos,
windowed_width,
windowed_height,
0
);
glfwSetWindowMonitor(m_window, nullptr, windowed_xpos, windowed_ypos,
windowed_width, windowed_height, 0);
config.set("window.fullscreen", false);
} else {
glfwGetWindowPos(m_window, &windowed_xpos, &windowed_ypos);
@@ -175,33 +144,25 @@ void Window::toggle_fullscreen() {
GLFWmonitor* primary = glfwGetPrimaryMonitor();
const GLFWvidmode* mode = glfwGetVideoMode(primary);
glfwSetWindowMonitor(
m_window,
primary,
0,
0,
mode->width,
mode->height,
GL_DONT_CARE
);
glfwSetWindowMonitor(m_window, primary, 0, 0, mode->width, mode->height,
GL_DONT_CARE);
config.set("window.fullscreen", true);
}
update_viewport();
}
void Window::toggle_mouse_able() {
//auto& io = ImGui::GetIO();
// auto& io = ImGui::GetIO();
if (m_mouse_enable) {
//io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange;
//Logger::info("ImGuiConfigFlags_NoMouseCursorChange");
//ImGui::SetMouseCursor(ImGuiMouseCursor_None);
//glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
// io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange;
// Logger::info("ImGuiConfigFlags_NoMouseCursorChange");
// ImGui::SetMouseCursor(ImGuiMouseCursor_None);
// glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_HIDDEN);
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_DISABLED);
m_mouse_enable = false;
} else {
//io.ConfigFlags &= ~ImGuiConfigFlags_NoMouseCursorChange;
//Logger::info("Disable ImGuiConfigFlags_NoMouseCursorChange");
// io.ConfigFlags &= ~ImGuiConfigFlags_NoMouseCursorChange;
// Logger::info("Disable ImGuiConfigFlags_NoMouseCursorChange");
glfwSetInputMode(m_window, GLFW_CURSOR, GLFW_CURSOR_NORMAL);
m_mouse_enable = true;
}
@@ -210,16 +171,25 @@ void Window::toggle_mouse_able() {
void Window::imgui_init() {
float dpi_scale_x, dpi_scale_y;
glfwGetWindowContentScale(m_window, &dpi_scale_x, &dpi_scale_y);
//float main_scale = ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor());
// float main_scale =
// ImGui_ImplGlfw_GetContentScaleForMonitor(glfwGetPrimaryMonitor());
float main_scale = dpi_scale_x;
Logger::info("Main Scale {}", main_scale);
// Setup Dear ImGui context
IMGUI_CHECKVERSION();
ImGui::CreateContext();
ImGuiIO& io = ImGui::GetIO();
io.ConfigFlags |= ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |= ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io.ConfigFlags |= ImGuiConfigFlags_NoMouseCursorChange; // Prevent ImGui from automatically changing the system cursor shape, allowing the game to fully control cursor appearance (e.g., hidden/disabled custom cursor).
io.ConfigFlags |=
ImGuiConfigFlags_NavEnableKeyboard; // Enable Keyboard Controls
io.ConfigFlags |=
ImGuiConfigFlags_NavEnableGamepad; // Enable Gamepad Controls
io.ConfigFlags |=
ImGuiConfigFlags_NoMouseCursorChange; // Prevent ImGui from
// automatically changing the
// system cursor shape, allowing
// the game to fully control
// cursor appearance (e.g.,
// hidden/disabled custom cursor).
auto theme = Config::get().get<int>("devpanel.theme");
if (theme == 0) {
ImGui::StyleColorsDark();
@@ -229,16 +199,19 @@ void Window::imgui_init() {
ImGui::StyleColorsDark();
Config::get().set("devpanel.theme", 0);
}
ImGuiStyle& style = ImGui::GetStyle();
style.ScaleAllSizes(main_scale); // Bake a fixed style scale. (until we have a solution for dynamic style scaling, changing this requires resetting Style + calling this again)
style.ScaleAllSizes(
main_scale); // Bake a fixed style scale. (until we have a solution for
// dynamic style scaling, changing this requires resetting
// Style + calling this again)
style.FontScaleDpi = main_scale;
style.FontSizeBase = 20.0f;
ImFont* font = io.Fonts->AddFontFromFileTTF(Font::font_path().c_str());
ASSERT_MSG(font != nullptr, "Font Load Fail");
// Setup Platform/Renderer backends
ImGui_ImplGlfw_InitForOpenGL(m_window, false);
ImGui_ImplGlfw_InitForOpenGL(m_window, false);
ImGui_ImplOpenGL3_Init();
}
}
} // namespace Cubed