Merge branch 'dev' into lights-fixes

This commit is contained in:
MihailRis 2026-10-11 15:25:10 +03:00
commit 3fc5a4322d
65 changed files with 1549 additions and 715 deletions

View file

@ -1,10 +1,10 @@
project(VoxelEngineSrc)
project(VoxelCoreSrc)
file(GLOB_RECURSE headers ${CMAKE_CURRENT_SOURCE_DIR}/*.hpp)
file(GLOB_RECURSE sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp)
list(REMOVE_ITEM sources ${CMAKE_CURRENT_SOURCE_DIR}/main.cpp)
add_library(VoxelEngineSrc STATIC ${sources} ${headers})
add_library(VoxelCoreSrc STATIC ${sources} ${headers})
find_package(OpenGL REQUIRED)
find_package(GLEW REQUIRED)
@ -70,10 +70,10 @@ else()
add_library(luajit::luajit ALIAS PkgConfig::luajit)
endif()
target_include_directories(VoxelEngineSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_include_directories(VoxelCoreSrc PUBLIC ${CMAKE_CURRENT_SOURCE_DIR})
target_link_libraries(
VoxelEngineSrc
VoxelCoreSrc
PRIVATE glfw
OpenGL::GL
GLEW::GLEW
@ -91,7 +91,7 @@ target_link_libraries(
)
target_compile_options(
VoxelEngineSrc
VoxelCoreSrc
PUBLIC $<$<CXX_COMPILER_ID:MSVC>:
/utf-8
/MP
@ -129,7 +129,7 @@ target_compile_options(
>)
target_link_options(
VoxelEngineSrc
VoxelCoreSrc
PUBLIC
$<$<CXX_COMPILER_ID:GNU>:
-no-pie

View file

@ -6,7 +6,7 @@
#include <string>
inline constexpr int ENGINE_VERSION_MAJOR = 0;
inline constexpr int ENGINE_VERSION_MINOR = 32;
inline constexpr int ENGINE_VERSION_MINOR = 33;
#ifdef NDEBUG
inline constexpr bool ENGINE_DEBUG_BUILD = false;
@ -14,7 +14,7 @@ inline constexpr bool ENGINE_DEBUG_BUILD = false;
inline constexpr bool ENGINE_DEBUG_BUILD = true;
#endif // NDEBUG
inline const std::string ENGINE_VERSION_STRING = "0.32";
inline const std::string ENGINE_VERSION_STRING = "0.33";
inline constexpr uint MAX_SUBPROCESSES = 1;
inline constexpr uint MAX_SUBPROCESS_DEPTH = 2;

View file

@ -8,7 +8,7 @@ using runnable = std::function<void()>;
template<class T> using supplier = std::function<T()>;
template<class T> using consumer = std::function<void(T)>;
using KeyCallback = std::function<bool()>;
using InputCallback = std::function<bool()>;
// data sources
using wstringsupplier = std::function<std::wstring()>;

View file

@ -28,7 +28,10 @@ MenuScreen::~MenuScreen() = default;
void MenuScreen::onOpen() {
engine.getContentControl().resetContent({});
auto menu = engine.getGUI().getMenu();
auto& gui = engine.getGUI();
gui.setActiveFrame(gui::GUI::CORE_MAIN);
auto menu = gui.getMenu();
menu->reset();
}

View file

@ -113,8 +113,6 @@ static inline auto shader_deleter = [](GLuint* shader) {
delete shader;
};
inline const uint GL_LOG_LEN = 512;
// shader should be deleted after shader program linking
using glshader = std::unique_ptr<GLuint, decltype(shader_deleter)>;
@ -125,12 +123,14 @@ glshader compile_shader(GLenum type, const GLchar* source, const std::string& fi
glCompileShader(shader);
glGetShaderiv(shader, GL_COMPILE_STATUS, &success);
if (!success) {
GLchar infoLog[GL_LOG_LEN];
glGetShaderInfoLog(shader, GL_LOG_LEN, nullptr, infoLog);
GLint infoLogLength;
glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogLength);
auto infoLog = std::make_unique<GLchar[]>(infoLogLength);
glGetShaderInfoLog(shader, infoLogLength, nullptr, infoLog.get());
glDeleteShader(shader);
throw std::runtime_error(
"vertex shader compilation failed (" + file + "):\n" +
std::string(infoLog)
std::string(infoLog.get(), infoLogLength)
);
}
return glshader(new GLuint(shader), shader_deleter); //-V508
@ -172,10 +172,14 @@ static GLuint compile_program(
glGetProgramiv(program, GL_LINK_STATUS, &success);
if (!success) {
GLchar infoLog[GL_LOG_LEN];
glGetProgramInfoLog(program, GL_LOG_LEN, nullptr, infoLog);
GLint infoLogLength;
glGetProgramiv(program, GL_INFO_LOG_LENGTH, &infoLogLength);
auto infoLog = std::make_unique<GLchar[]>(infoLogLength);
glGetProgramInfoLog(program, infoLogLength, nullptr, infoLog.get());
glDeleteProgram(program);
throw std::runtime_error(
"shader program linking failed:\n" + std::string(infoLog)
"shader program linking failed:\n" +
std::string(infoLog.get(), infoLogLength)
);
}
return program;

View file

@ -22,7 +22,7 @@ static debug::Logger logger("chunks-render");
size_t ChunksRenderer::visibleChunks = 0;
static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 4;
static constexpr inline size_t MAX_CHUNKS_ENQUEUED_IN_FRAME = 64;
class RendererWorker : public util::Worker<RendererJob, RendererResult> {
BlocksRenderer renderer;
@ -197,8 +197,7 @@ void ChunksRenderer::update() {
int loadDistance = settings.chunks.loadDistance.get();
const int topN = 10;
int top = std::min<int>(meshBuildQueue.size(), topN);
int top = std::min<int>(meshBuildQueue.size(), MAX_CHUNKS_ENQUEUED_IN_FRAME);
for (int i = 0; i < top; i++) {
glm::ivec2 offset = meshBuildQueue[i];
size_t index =

View file

@ -35,8 +35,15 @@ void InlineFrame::setDocument(const std::shared_ptr<UiDocument>& document) {
root->setSize(size);
gui.postRunnable([this]() {
scripting::on_ui_open(*this->document, {});
gui.postRunnable([weak = weak_from_this(), document]() {
auto node = weak.lock();
if (node == nullptr) {
return;
}
if (static_cast<InlineFrame&>(*node).document != document) {
return;
}
scripting::on_ui_open(*document, {});
});
}

View file

@ -14,8 +14,13 @@ std::filesystem::path io::MemoryDevice::resolve(std::string_view path) {
std::unique_ptr<std::ostream> io::MemoryDevice::write(std::string_view path) {
std::string filePath = std::string(path);
auto memoryStream = std::make_unique<memory_ostream>();
memoryStream->set_sync_callback([this, filePath](std::string_view data) {
createFile(std::move(filePath), util::Buffer<char>(data.data(), data.size()));
});
return std::make_unique<finalizing_ostream>(
std::make_unique<memory_ostream>(),
std::move(memoryStream),
[this, filePath](auto ostream) {
auto& memoryStream = dynamic_cast<memory_ostream&>(*ostream);
createFile(std::move(filePath), memoryStream.release());
@ -180,6 +185,10 @@ std::unique_ptr<io::PathsGenerator> io::MemoryDevice::list(std::string_view path
}
io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) {
const auto& found = nodes.find(path);
if (found != nodes.end()) {
return found->second.get_if<Dir>();
}
io::path filePath = path;
io::path parent = filePath.parent();
auto parentDir = getDir(parent.string());
@ -195,6 +204,15 @@ io::MemoryDevice::Dir* io::MemoryDevice::createDir(std::string path) {
io::MemoryDevice::Node* io::MemoryDevice::createFile(
std::string path, util::Buffer<char>&& content
) {
const auto& found = nodes.find(path);
if (found != nodes.end()) {
auto& node = found->second;
if (!node.holds_alternative<File>()) {
return nullptr;
}
node.data = File {std::move(content)};
return &node;
}
io::path filePath = path;
io::path parent = filePath.parent();
auto dir = getDir(parent.string());

View file

@ -58,11 +58,20 @@ namespace {
}
uint32_t to_ms_dos_timestamp(const file_time_type& fileTime) {
// 1980-01-01 00:00, the earliest MS-DOS date
constexpr uint32_t DOS_EPOCH = (0 << 9 | 1 << 5 | 1) << 16;
if (fileTime == file_time_type::min()) {
return DOS_EPOCH;
}
auto timePoint = time_point_cast<system_clock::duration>(
fileTime - file_time_type::clock::now() + system_clock::now()
);
std::time_t timeT = system_clock::to_time_t(timePoint);
std::tm tm = *std::localtime(&timeT);
const std::tm* tmPtr = std::localtime(&timeT);
if (tmPtr == nullptr || tmPtr->tm_year < 80) {
return DOS_EPOCH;
}
const std::tm& tm = *tmPtr;
uint16_t date = (tm.tm_year - 80) << 9 | (tm.tm_mon + 1) << 5 | tm.tm_mday;
uint16_t time = (tm.tm_hour << 11) | (tm.tm_min << 5) | (tm.tm_sec / 2);
return (date << 16) | time;
@ -173,7 +182,12 @@ ZipFileDevice::ZipFileDevice(
entries[entry.fileName] = std::move(entry);
}
for (auto& [name, _] : entries) {
std::vector<std::string> names;
names.reserve(entries.size());
for (const auto& [name, _] : entries) {
names.push_back(name);
}
for (const auto& name : names) {
io::path path = name;
while (!(path = path.parent()).pathPart().empty()) {
@ -184,7 +198,6 @@ ZipFileDevice::ZipFileDevice(
entry.isDirectory = true;
entries[path.pathPart()] = entry;
}
break;
}
for (auto& [_, entry] : entries) {
@ -253,6 +266,9 @@ file_time_type ZipFileDevice::lastWriteTime(std::string_view path) {
}
bool ZipFileDevice::exists(std::string_view path) {
if (path.empty()) {
return true;
}
return entries.find(std::string(path)) != entries.end();
}
@ -441,7 +457,11 @@ static size_t write_zip(
void io::write_zip(const path& folder, const path& file) {
ByteBuilder central_dir;
auto out = io::write(file);
size_t entries = write_zip(folder.pathPart(), folder, *out, central_dir);
auto root = folder.pathPart();
if (!root.empty() && root.back() != '/') {
root += '/';
}
size_t entries = write_zip(root, folder, *out, central_dir);
size_t central_dir_offset = out->tellp();
out->write(reinterpret_cast<const char*>(central_dir.data()), central_dir.size());

View file

@ -3,6 +3,9 @@
#include <iostream>
#include <streambuf>
#include <cstring>
#include <climits>
#include <memory>
#include <functional>
#include <algorithm>
#include <string_view>
@ -13,81 +16,111 @@ public:
explicit memory_buffer(size_t initial_size = 64)
: buffer(std::make_unique<char[]>(initial_size)),
capacity(initial_size) {
setp(buffer.get(), buffer.get() + initial_size);
setp(buffer.get(), buffer.get() + capacity);
}
std::string_view view() const {
return std::string_view(pbase(), pptr() - pbase());
return std::string_view(pbase(), size());
}
util::Buffer<char> release() {
return {std::move(buffer), size()};
size_t n = size();
return {std::move(buffer), n};
}
size_t size() const {
return pptr() - pbase();
return std::max(length, position());
}
void set_sync_callback(std::function<void(std::string_view)> callback) {
on_sync = std::move(callback);
}
protected:
int_type overflow(int_type c) override {
if (c == traits_type::eof())
return traits_type::eof();
const size_t data_size = pptr() - pbase();
const size_t new_capacity = std::max(capacity * 2, data_size + 1);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), pbase(), data_size);
buffer = std::move(new_buffer);
capacity = new_capacity;
setp(buffer.get(), buffer.get() + new_capacity);
pbump(data_size);
reserve(position() + 1);
*pptr() = traits_type::to_char_type(c);
pbump(1);
return c;
}
std::streamsize xsputn(const char* s, std::streamsize count) override {
const std::streamsize avail = epptr() - pptr();
pos_type seekoff(
off_type off,
std::ios_base::seekdir dir,
std::ios_base::openmode which
) override {
if (!(which & std::ios_base::out)) {
return pos_type(off_type(-1));
}
length = size();
if (avail >= count) {
std::memcpy(pptr(), s, count);
pbump(count);
return count;
off_type base;
switch (dir) {
case std::ios_base::beg: base = 0; break;
case std::ios_base::cur: base = position(); break;
case std::ios_base::end: base = length; break;
default: return pos_type(off_type(-1));
}
std::streamsize written = 0;
if (avail > 0) {
std::memcpy(pptr(), s, avail);
written += avail;
s += avail;
count -= avail;
pbump(avail);
off_type target = base + off;
if (target < 0 || target > static_cast<off_type>(length)) {
return pos_type(off_type(-1));
}
set_position(target);
return pos_type(target);
}
const size_t data_size = pptr() - pbase();
const size_t required_capacity = data_size + count;
const size_t new_capacity = std::max(capacity * 2, required_capacity);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), pbase(), data_size);
std::memcpy(new_buffer.get() + data_size, s, count);
buffer = std::move(new_buffer);
capacity = new_capacity;
setp(buffer.get(), buffer.get() + new_capacity);
pbump(data_size + count);
written += count;
return written;
pos_type seekpos(pos_type pos, std::ios_base::openmode which) override {
return seekoff(off_type(pos), std::ios_base::beg, which);
}
private:
std::unique_ptr<char[]> buffer;
size_t capacity;
size_t length = 0;
size_t position() const {
return pptr() - pbase();
}
void advance(size_t n) {
while (n > 0) {
int step = static_cast<int>(std::min<size_t>(n, INT_MAX));
pbump(step);
n -= step;
}
}
void set_position(size_t pos) {
setp(buffer.get(), buffer.get() + capacity);
advance(pos);
}
void reserve(size_t required) {
if (required <= capacity) {
return;
}
size_t pos = position();
length = size();
size_t new_capacity = std::max(capacity * 2, required);
auto new_buffer = std::make_unique<char[]>(new_capacity);
std::memcpy(new_buffer.get(), buffer.get(), length);
buffer = std::move(new_buffer);
capacity = new_capacity;
set_position(pos);
}
int sync() override {
if (on_sync) {
on_sync(view());
}
return 0;
}
std::function<void(std::string_view)> on_sync;
};
class memory_ostream : public std::ostream {
@ -102,6 +135,10 @@ public:
util::Buffer<char> release() {
return buffer.release();
}
void set_sync_callback(std::function<void(std::string_view)> callback) {
buffer.set_sync_callback(std::move(callback));
}
private:
memory_buffer buffer;
};

View file

@ -305,13 +305,14 @@ static int l_read_descriptor(lua::State* L) {
int maxlen = lua::tointeger(L, 2);
auto& stream = io_descriptors::require_input(descriptor);
if (stream.eof()) {
stream.clear();
}
util::Buffer<char> buffer(maxlen);
stream.read(buffer.data(), maxlen);
std::streamsize read_len = stream.gcount();
std::streamsize read_len = stream.gcount();
if (stream.eof()) {
stream.clear(stream.rdstate() & std::ios::badbit);
}
return lua::create_bytearray(L, buffer.data(), read_len);
}

View file

@ -44,10 +44,13 @@ static int l_add_callback(lua::State* L) {
auto& input = engine->getInput();
if (pos != std::string::npos) {
std::string prefix = bindname.substr(0, pos);
auto prefix = std::string_view(bindname).substr(0, pos);
if (prefix == "key") {
auto key = input_util::keycode_from(bindname.substr(pos + 1));
handler = input.addKeyCallback(key, actual_callback);
} else if (prefix == "mouse") {
auto mouse = input_util::mousecode_from(bindname.substr(pos + 1));
handler = input.addMouseCallback(mouse, actual_callback);
}
}

View file

@ -263,7 +263,7 @@ runnable lua::create_runnable(State* L) {
};
}
KeyCallback lua::create_simple_handler(State* L) {
InputCallback lua::create_simple_handler(State* L) {
auto funcptr = create_lambda_handler(L);
return [=]() -> bool {
if (!get_from_registry(L, LAMBDAS_TABLE, *funcptr, false)) {

View file

@ -665,7 +665,7 @@ namespace lua {
}
runnable create_runnable(lua::State*);
KeyCallback create_simple_handler(lua::State*);
InputCallback create_simple_handler(lua::State*);
scripting::common_func create_lambda(lua::State*);
scripting::common_func create_lambda_nothrow(lua::State*);

View file

@ -99,14 +99,21 @@ template <typename T, T(tovalueFunc)(lua::State*, int)>
std::function<T()> create_supplier(
const scriptenv& env, const std::string& src, const std::string& file
) {
return [=]() {
return [=, errorLogged = false]() mutable {
lua::stackguard guard(lua::get_main_state());
if (auto L = process_callback(env, src, file)) {
if (lua::isfunction(L, -1)) {
lua::call_nothrow(L, 0);
if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) {
return T {};
}
try {
return tovalueFunc(L, -1);
} catch (const std::exception& err) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src) << ": "
<< err.what();
errorLogged = true;
}
}
auto str = tovalueFunc(L, -1);
lua::pop(L);
return str;
}
return T {};
};
@ -158,16 +165,33 @@ int_array_consumer scripting::create_int_array_consumer(
vec2supplier scripting::create_vec2_supplier(
const scriptenv& env, const std::string& src, const std::string& file
) {
return [=]() {
if (auto L = process_callback(env, src, file)) {
if (lua::isfunction(L, -1)) {
lua::call_nothrow(L, 0);
return [=, errorLogged = false]() mutable {
auto L = lua::get_main_state();
lua::stackguard guard(L);
int top = lua::gettop(L);
if (process_callback(env, src, file)) {
if (lua::isfunction(L, -1) && !lua::call_nothrow(L, 0)) {
return glm::vec2(0, 0);
}
if (lua::gettop(L) - top < 2) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src)
<< ": two numbers expected";
errorLogged = true;
}
return glm::vec2(0, 0);
}
try {
auto y = lua::tonumber(L, -1);
auto x = lua::tonumber(L, -2);
return glm::vec2(x, y);
} catch (const std::exception& err) {
if (!errorLogged) {
logger.error() << "supplier " << util::quote(src) << ": "
<< err.what();
errorLogged = true;
}
}
auto y = lua::tonumber(L, -1);
lua::pop(L);
auto x = lua::tonumber(L, -1);
lua::pop(L);
return glm::vec2(x, y);
}
return glm::vec2(0, 0);
};

View file

@ -328,14 +328,17 @@ void Entities::preparePhysics(float delta) {
auto view = registry->view<EntityId, Rigidbody>();
for (auto [entity, eid, rigidbody] : view.each()) {
auto bodyType = rigidbody.hitbox.type;
if (eid.destroyFlag || !rigidbody.enabled || bodyType == BodyType::STATIC) {
if (eid.destroyFlag || !rigidbody.enabled) {
continue;
}
rigidbody.hitbox.selectable = rigidbody.selectable;
rigidbody.hitbox.mass = bodyType == BodyType::DYNAMIC
? rigidbody.mass
: std::numeric_limits<float>::infinity();
rigidbody.hitbox.elasticity = rigidbody.elasticity;
rigidbody.hitbox.selectable = rigidbody.selectable;
if (bodyType == BodyType::STATIC) {
continue;
}
hitboxes.emplace_back(&rigidbody.hitbox);
if (!eid.def.solid) {
continue;
@ -477,15 +480,17 @@ void Entities::render(
const Frustum* frustum,
entityid_t fpsEntity
) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton>();
for (auto [entity, eid, transform, skeleton] : view.each()) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton, Rigidbody>();
for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) {
if (eid.uid == fpsEntity) {
continue;
}
const auto& def = eid.def;
const auto& pos = transform.pos;
const auto& size = transform.size;
if (frustum && !frustum->isBoxVisible(pos - size, pos + size)) {
const auto& halfSize = rigidbody.hitbox.getHalfSize();
// todo: more correct frustum culling
if (frustum && !frustum->isBoxVisible(pos - halfSize, pos + halfSize)) {
continue;
}

View file

@ -216,10 +216,17 @@ public:
return bindings;
}
ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) override {
ObserverHandler addKeyCallback(Keycode key, InputCallback callback) override {
return keyCallbacks[key].add(std::move(callback));
}
ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) override {
return addKeyCallback(
static_cast<Keycode>(MOUSE_KEYS_OFFSET + static_cast<int>(button)),
std::move(callback)
);
}
const std::vector<Keycode>& getPressedKeys() const override {
return pressedKeys;
}

View file

@ -288,12 +288,13 @@ public:
virtual const Bindings& getBindings() const = 0;
virtual ObserverHandler addKeyCallback(Keycode key, KeyCallback callback) = 0;
virtual ObserverHandler addKeyCallback(Keycode key, InputCallback callback) = 0;
virtual ObserverHandler addMouseCallback(Mousecode button, InputCallback callback) = 0;
virtual const std::vector<Keycode>& getPressedKeys() const = 0;
virtual const std::vector<uint>& getCodepoints() const = 0;
ObserverHandler addCallback(const std::string& name, KeyCallback callback) {
ObserverHandler addCallback(const std::string& name, InputCallback callback) {
return getBindings().require(name).onactived.add(callback);
}
};