Merge branch 'main' into dev

This commit is contained in:
MihailRis 2026-10-16 01:30:13 +03:00
commit 35e3d80f35
111 changed files with 935 additions and 664 deletions

View file

@ -14,6 +14,13 @@ if(CMAKE_SYSTEM_NAME STREQUAL "Windows")
find_package(OpenAL CONFIG REQUIRED)
else()
find_package(OpenAL REQUIRED)
if(NOT TARGET OpenAL::OpenAL)
add_library(OpenAL::OpenAL UNKNOWN IMPORTED)
set_target_properties(OpenAL::OpenAL PROPERTIES
IMPORTED_LOCATION "${OPENAL_LIBRARY}"
INTERFACE_INCLUDE_DIRECTORIES "${OPENAL_INCLUDE_DIR}"
)
endif()
endif()
find_package(ZLIB REQUIRED)
find_package(PNG REQUIRED)

View file

@ -96,6 +96,7 @@ namespace rigging {
std::unordered_map<std::string, std::string> textures;
std::vector<ModelReference> modelOverrides;
bool visible;
bool culled = false;
glm::vec4 tint {1.0f, 1.0f, 1.0f, 1.0f};
std::vector<glm::vec4> boneTints;

View file

@ -10,53 +10,69 @@ class ObjParser : BasicParser<char> {
std::vector<glm::vec2> uvs {{0, 0}};
std::vector<glm::vec3> normals {{0, 1, 0}};
// TODO: refactor
void parseFace(Mesh& mesh) {
std::vector<Vertex> vertices;
while (hasNext()) {
auto c = peekInLine();
if (c == '\n') {
break;
} else if (hasNext()) {
uint indices[3] {};
uint i = 0;
do {
char next = peekInLine();
if (is_digit(next)) {
indices[i] = parseSimpleInt(10);
if (hasNext() && peekInLine() == '/') {
pos++;
}
} else if (next == '/') {
pos++;
} else {
break;
}
} while (hasNext() && peekInLine() != '\n' && ++i < 3);
Vertex parseFaceVertex() {
auto parseIndex = [&]() -> uint {
if (!hasNext() || !is_digit(peekInLine())) {
return 0;
}
return parseSimpleInt(10);
};
vertices.push_back(Vertex {
coords[indices[0]], uvs[indices[1]], normals[indices[2]]});
uint coord = parseIndex();
uint uv = 0;
uint normal = 0;
if (hasNext() && peekInLine() == '/') {
pos++;
uv = parseIndex();
if (hasNext() && peekInLine() == '/') {
pos++;
normal = parseIndex();
}
}
if (hasNext() && peekInLine() != '\n') {
skipLine();
}
return Vertex {
coords[coord],
uvs[uv],
normals[normal]
};
}
void triangulate(const std::vector<Vertex>& vertices, std::vector<Vertex>& output) {
if (vertices.size() >= 3) {
for (size_t j = 0; j < vertices.size() - 2; j++) {
mesh.vertices.push_back(vertices[0]);
output.push_back(vertices[0]);
for (size_t i = 1; i < 3; i++) {
mesh.vertices.push_back(vertices[i + j]);
output.push_back(vertices[i + j]);
}
}
}
}
public:
ObjParser(const std::string_view file, const std::string_view src)
: BasicParser(file, src) {
void parseFace(Mesh& mesh) {
std::vector<Vertex> vertices;
while (hasNext() && peekInLine() != '\n') {
vertices.push_back(parseFaceVertex());
}
triangulate(vertices, mesh.vertices);
}
std::unique_ptr<Model> parse() {
// first iteration - collecting vertex data
glm::vec3 parseVec3() {
float x = parseNumber().asNumber();
float y = parseNumber().asNumber();
float z = parseNumber().asNumber();
return glm::vec3 {x, y, z};
}
glm::vec2 parseVec2() {
float x = parseNumber().asNumber();
float y = parseNumber().asNumber();
return glm::vec2 {x, y};
}
void collectVertexData() {
while (hasNext()) {
if (peek() == '#') {
skipLine();
@ -64,27 +80,18 @@ public:
}
auto cmd = parseName();
if (cmd == "v") {
float x = parseNumber().asNumber();
float y = parseNumber().asNumber();
float z = parseNumber().asNumber();
coords.emplace_back(x, y, z);
coords.emplace_back(parseVec3());
} else if (cmd == "vt") {
float u = parseNumber().asNumber();
float v = parseNumber().asNumber();
uvs.emplace_back(u, v);
uvs.emplace_back(parseVec2());
} else if (cmd == "vn") {
float x = parseNumber().asNumber();
float y = parseNumber().asNumber();
float z = parseNumber().asNumber();
normals.emplace_back(x, y, z);
normals.emplace_back(parseVec3());
} else {
skipLine();
}
}
// second iteration - building meshes
reset();
}
auto model = std::make_unique<Model>();
void buildMeshes(Model& model) {
std::string texture;
while (hasNext()) {
if (peek() != '#' && parseName() == "usemtl") {
@ -95,7 +102,7 @@ public:
skipLine();
}
do {
Mesh* mesh = &model->addMesh(texture);
Mesh* mesh = &model.addMesh(texture);
while (hasNext()) {
if (peek() == '#') {
skipLine();
@ -105,7 +112,7 @@ public:
if (cmd == "usemtl") {
skipWhitespace();
texture = readUntilEOL();
mesh = &model->addMesh(texture);
mesh = &model.addMesh(texture);
break;
} else if (cmd == "f") {
parseFace(*mesh);
@ -113,6 +120,19 @@ public:
skipLine();
}
} while (hasNext());
}
public:
ObjParser(const std::string_view file, const std::string_view src)
: BasicParser(file, src) {
}
std::unique_ptr<Model> parse() {
// first iteration - collecting vertex data
collectVertexData();
// second iteration - building meshes
reset();
auto model = std::make_unique<Model>();
buildMeshes(*model);
model->clean();
return model;
}

View file

@ -274,12 +274,11 @@ void LevelScreen::draw(float delta) {
const DrawContext ctx(nullptr, engine.getWindow(), batch.get());
if (!hud->isPause()) {
renderer->updateEntitiesCulling(camera);
scripting::on_entities_render(engine.getTime().getDelta());
}
renderer->renderFrame(ctx, camera, hudVisible, *postProcessing);
if (!hud->isPause()) {
scripting::on_frontend_render();
}
renderer->renderFrame(ctx, camera, hudVisible, *postProcessing);
if (hudVisible) {
hud->draw(ctx);

View file

@ -8,149 +8,65 @@ using namespace advanced_pipeline;
static debug::Logger logger("gl-gbuffer");
// TODO: REFACTOR
uint GBuffer::getSSAODownsample() const {
return 2;
}
void GBuffer::createColorBuffer() {
if (colorBuffer == 0)
glGenTextures(1, &colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGB,
width,
height,
0,
GL_RGB,
GL_UNSIGNED_BYTE,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, colorBuffer, 0
);
}
void GBuffer::createPositionsBuffer() {
if (positionsBuffer == 0)
glGenTextures(1, &positionsBuffer);
glBindTexture(GL_TEXTURE_2D, positionsBuffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA16F,
width,
height,
0,
GL_RGBA,
GL_FLOAT,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT1, GL_TEXTURE_2D, positionsBuffer, 0
);
}
void GBuffer::createNormalsBuffer() {
if (normalsBuffer == 0)
glGenTextures(1, &normalsBuffer);
glBindTexture(GL_TEXTURE_2D, normalsBuffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_RGBA16F,
width,
height,
0,
GL_RGB,
GL_FLOAT,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT2, GL_TEXTURE_2D, normalsBuffer, 0
);
}
void GBuffer::createEmissionBuffer() {
if (emissionBuffer == 0)
glGenTextures(1, &emissionBuffer);
glBindTexture(GL_TEXTURE_2D, emissionBuffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_R8,
width,
height,
0,
GL_RED,
GL_FLOAT,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT3, GL_TEXTURE_2D, emissionBuffer, 0
);
}
void GBuffer::createDepthBuffer() {
if (depthBuffer == 0)
glGenRenderbuffers(1, &depthBuffer);
glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer
);
}
void GBuffer::createSSAOBuffer() {
if (ssaoBuffer == 0) {
glGenTextures(1, &ssaoBuffer);
void GBuffer::createBuffer(Buffer& buffer, int downsample) {
if (buffer.buffer == 0) {
if (&buffer == &depthBuffer)
glGenRenderbuffers(1, &depthBuffer.buffer);
else
glGenTextures(1, &buffer.buffer);
}
if (&buffer == &depthBuffer){
glBindRenderbuffer(GL_RENDERBUFFER, depthBuffer.buffer);
glRenderbufferStorage(GL_RENDERBUFFER, GL_DEPTH_COMPONENT24, width, height);
glFramebufferRenderbuffer(
GL_FRAMEBUFFER, GL_DEPTH_ATTACHMENT, GL_RENDERBUFFER, depthBuffer.buffer
);
} else {
glBindTexture(GL_TEXTURE_2D, buffer.buffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
buffer.internalformat,
width / downsample,
height / downsample,
0,
buffer.format,
buffer.type,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
if (&buffer != &ssaoBuffer)
{
glFramebufferTexture2D(
GL_FRAMEBUFFER, buffer.attachment, GL_TEXTURE_2D, buffer.buffer, 0
);
}
}
uint ssaoDownsample = getSSAODownsample();
glBindTexture(GL_TEXTURE_2D, ssaoBuffer);
glTexImage2D(
GL_TEXTURE_2D,
0,
GL_R16F,
width / ssaoDownsample,
height / ssaoDownsample,
0,
GL_RED,
GL_FLOAT,
nullptr
);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
}
GBuffer::GBuffer(uint width, uint height) : width(width), height(height) {
GBuffer::GBuffer(uint width, uint height)
: width(width), height(height),
colorBuffer {0, GL_RGB, GL_RGB, GL_UNSIGNED_BYTE, GL_COLOR_ATTACHMENT0},
positionsBuffer {0, GL_RGBA16F, GL_RGBA, GL_FLOAT, GL_COLOR_ATTACHMENT1},
normalsBuffer {0, GL_RGBA16F, GL_RGB, GL_FLOAT, GL_COLOR_ATTACHMENT2},
emissionBuffer {0, GL_R8, GL_RED, GL_FLOAT, GL_COLOR_ATTACHMENT3},
depthBuffer {0, 0, 0, 0, 0},
ssaoBuffer {0, GL_R16F, GL_RED, GL_FLOAT, 0}
{
glGenFramebuffers(1, &fbo);
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
createColorBuffer();
createPositionsBuffer();
createNormalsBuffer();
createEmissionBuffer();
createBuffer(colorBuffer);
createBuffer(positionsBuffer);
createBuffer(normalsBuffer);
createBuffer(emissionBuffer);
GLenum attachments[4] = {
GL_COLOR_ATTACHMENT0,
@ -160,7 +76,7 @@ GBuffer::GBuffer(uint width, uint height) : width(width), height(height) {
};
glDrawBuffers(4, attachments);
createDepthBuffer();
createBuffer(depthBuffer);
int status;
if ((status = glCheckFramebufferStatus(GL_FRAMEBUFFER)) != GL_FRAMEBUFFER_COMPLETE) {
@ -170,9 +86,9 @@ GBuffer::GBuffer(uint width, uint height) : width(width), height(height) {
glGenFramebuffers(1, &ssaoFbo);
glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo);
createSSAOBuffer();
createBuffer(ssaoBuffer, getSSAODownsample());
glFramebufferTexture2D(
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoBuffer, 0
GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, ssaoBuffer.buffer, 0
);
GLenum ssaoAttachments[1] = {GL_COLOR_ATTACHMENT0};
glDrawBuffers(1, ssaoAttachments);
@ -185,12 +101,12 @@ GBuffer::GBuffer(uint width, uint height) : width(width), height(height) {
}
GBuffer::~GBuffer() {
glDeleteTextures(1, &colorBuffer);
glDeleteTextures(1, &positionsBuffer);
glDeleteTextures(1, &normalsBuffer);
glDeleteTextures(1, &emissionBuffer);
glDeleteTextures(1, &ssaoBuffer);
glDeleteRenderbuffers(1, &depthBuffer);
glDeleteTextures(1, &colorBuffer.buffer);
glDeleteTextures(1, &positionsBuffer.buffer);
glDeleteTextures(1, &normalsBuffer.buffer);
glDeleteTextures(1, &emissionBuffer.buffer);
glDeleteTextures(1, &ssaoBuffer.buffer);
glDeleteRenderbuffers(1, &depthBuffer.buffer);
glDeleteFramebuffers(1, &fbo);
glDeleteFramebuffers(1, &ssaoFbo);
}
@ -210,23 +126,23 @@ void GBuffer::unbind() const {
void GBuffer::bindBuffers() const {
glActiveTexture(GL_TEXTURE0 + TARGET_EMISSION);
glBindTexture(GL_TEXTURE_2D, emissionBuffer);
glBindTexture(GL_TEXTURE_2D, emissionBuffer.buffer);
glActiveTexture(GL_TEXTURE0 + TARGET_NORMALS);
glBindTexture(GL_TEXTURE_2D, normalsBuffer);
glBindTexture(GL_TEXTURE_2D, normalsBuffer.buffer);
glActiveTexture(GL_TEXTURE0 + TARGET_POSITIONS);
glBindTexture(GL_TEXTURE_2D, positionsBuffer);
glBindTexture(GL_TEXTURE_2D, positionsBuffer.buffer);
glActiveTexture(GL_TEXTURE0 + TARGET_COLOR);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer.buffer);
if (TARGET_COLOR != 0)
glActiveTexture(GL_TEXTURE0);
}
void GBuffer::bindSSAOBuffer() const {
glBindTexture(GL_TEXTURE_2D, ssaoBuffer);
glBindTexture(GL_TEXTURE_2D, ssaoBuffer.buffer);
}
void GBuffer::bindDepthBuffer(int drawFbo) {
@ -245,24 +161,24 @@ void GBuffer::resize(uint width, uint height) {
glBindFramebuffer(GL_FRAMEBUFFER, fbo);
createDepthBuffer();
createColorBuffer();
createPositionsBuffer();
createNormalsBuffer();
createEmissionBuffer();
createBuffer(depthBuffer);
createBuffer(colorBuffer);
createBuffer(positionsBuffer);
createBuffer(normalsBuffer);
createBuffer(emissionBuffer);
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
glBindFramebuffer(GL_FRAMEBUFFER, ssaoFbo);
createSSAOBuffer();
createBuffer(ssaoBuffer, getSSAODownsample());
glBindTexture(GL_TEXTURE_2D, 0);
glBindFramebuffer(GL_FRAMEBUFFER, 0);
}
std::unique_ptr<ImageData> GBuffer::toImage() const {
auto data = std::make_unique<ubyte[]>(width * height * 3);
glBindTexture(GL_TEXTURE_2D, colorBuffer);
glBindTexture(GL_TEXTURE_2D, colorBuffer.buffer);
glGetTexImage(GL_TEXTURE_2D, 0, GL_RGB, GL_UNSIGNED_BYTE, data.get());
glBindTexture(GL_TEXTURE_2D, 0);
return std::make_unique<ImageData>(

View file

@ -27,22 +27,25 @@ public:
uint getSSAODownsample() const;
private:
struct Buffer {
uint buffer;
const int internalformat;
const uint format;
const uint type;
const uint attachment;
};
uint width;
uint height;
uint fbo;
uint colorBuffer = 0;
uint positionsBuffer = 0;
uint normalsBuffer = 0;
uint emissionBuffer = 0;
uint depthBuffer = 0;
uint ssaoFbo = 0;
uint ssaoBuffer = 0;
Buffer colorBuffer;
Buffer positionsBuffer;
Buffer normalsBuffer;
Buffer emissionBuffer;
Buffer depthBuffer;
uint ssaoFbo;
Buffer ssaoBuffer;
void createColorBuffer();
void createPositionsBuffer();
void createNormalsBuffer();
void createEmissionBuffer();
void createDepthBuffer();
void createSSAOBuffer();
void createBuffer(Buffer& buffer, int downsample = 1);
};

View file

@ -1,4 +1,7 @@
#include "PostProcessing.hpp"
#include <GL/glew.h>
#include "Mesh.hpp"
#include "Shader.hpp"
#include "GBuffer.hpp"
@ -18,7 +21,7 @@ using namespace advanced_pipeline;
PostProcessing::PostProcessing(size_t effectSlotsCount)
: effectSlots(effectSlotsCount) {
// Fullscreen quad mesh bulding
// Fullscreen quad mesh building
PostProcessingVertex meshData[] {
{{-1.0f, -1.0f}},
{{-1.0f, 1.0f}},
@ -37,7 +40,7 @@ PostProcessing::PostProcessing(size_t effectSlotsCount)
glm::vec3 noise(
(rand() / static_cast<float>(RAND_MAX)) * 2.0 - 1.0,
(rand() / static_cast<float>(RAND_MAX)) * 2.0 - 1.0,
0.0f);
0.0f);
ssaoNoise.push_back(noise);
}
glGenTextures(1, &noiseTexture);
@ -50,7 +53,9 @@ PostProcessing::PostProcessing(size_t effectSlotsCount)
glBindTexture(GL_TEXTURE_2D, 0);
}
PostProcessing::~PostProcessing() = default;
PostProcessing::~PostProcessing() {
glDeleteTextures(1, &noiseTexture);
}
void PostProcessing::use(DrawContext& context, bool gbufferPipeline) {
const auto& vp = context.getViewport();
@ -107,8 +112,9 @@ void PostProcessing::configureEffect(
shader.uniform3f("u_cameraPos", camera.position);
shader.uniform1f("u_timer", timer);
shader.uniformMatrix("u_projection", camera.getProjection());
shader.uniformMatrix("u_view", camera.getView());
shader.uniformMatrix("u_inverseView", glm::inverse(camera.getView()));
const auto view = camera.getView();
shader.uniformMatrix("u_view", view);
shader.uniformMatrix("u_inverseView", glm::inverse(view));
}
void PostProcessing::renderDeferredShading(
@ -151,7 +157,7 @@ void PostProcessing::renderDeferredShading(
gbuffer->bindSSAOBuffer();
glActiveTexture(GL_TEXTURE0);
gbuffer->bindBuffers();
auto& effect = assets.require<PostEffect>("deferred_lighting");

View file

@ -24,8 +24,6 @@ struct PostProcessingVertex {
};
/// @brief Framebuffer with blitting with shaders.
/// @attention Current implementation does not support multiple render passes
/// for multiple effects. Will be implemented in v0.21
class PostProcessing {
public:
PostProcessing(size_t effectSlotsCount);
@ -74,12 +72,12 @@ private:
void refreshFbos(uint width, uint height);
/// @brief Main framebuffer (lasy field)
/// @brief Main framebuffer (lazy field)
std::unique_ptr<Framebuffer> fbo;
std::unique_ptr<Framebuffer> fboSecond;
/// @brief Fullscreen quad mesh as the post-processing canvas
std::unique_ptr<Mesh<PostProcessingVertex>> quadMesh;
std::vector<std::shared_ptr<PostEffect>> effectSlots;
std::unique_ptr<GBuffer> gbuffer;
uint noiseTexture;
uint noiseTexture = 0;
};

View file

@ -8,6 +8,22 @@
#include "debug/Logger.hpp"
#include "core_defs.hpp"
inline constexpr uint FACE_WEST = FACE_MX;
inline constexpr uint FACE_EAST = FACE_PX;
inline constexpr uint FACE_BOTTOM = FACE_MY;
inline constexpr uint FACE_TOP = FACE_PY;
inline constexpr uint FACE_SOUTH = FACE_MZ;
inline constexpr uint FACE_NORTH = FACE_PZ;
inline constexpr std::array<uint8_t, 6> LEGACY_CUSTOM_MODEL_TEXTURE_ORDER = {
FACE_WEST,
FACE_EAST,
FACE_BOTTOM,
FACE_TOP,
FACE_SOUTH,
FACE_NORTH,
};
static debug::Logger logger("models-generator");
static void configure_textures(
@ -49,6 +65,21 @@ static inline UVRegion get_region_for(
return texreg.region;
}
static inline void map_legacy_box_textures(
const std::vector<std::string>& modelTextures,
size_t offset,
UVRegion (&boxtexfaces)[6],
const Assets& assets
) {
for (size_t i = 0; i < 6; ++i) {
const auto legacyFace = LEGACY_CUSTOM_MODEL_TEXTURE_ORDER[i];
boxtexfaces[legacyFace] = get_region_for(modelTextures[offset + i], assets);
}
boxtexfaces[FACE_TOP].scale(glm::vec2(-1, 1));
boxtexfaces[FACE_EAST].scale(glm::vec2(-1, 1));
boxtexfaces[FACE_NORTH].scale(glm::vec2(-1, 1));
}
void ModelsGenerator::prepareModel(
Assets& assets, const Block& def, Variant& variant, uint8_t variantId
) {
@ -120,16 +151,8 @@ model::Model ModelsGenerator::fromCustom(
for (size_t i = 0; i < modelBoxes.size(); i++) {
auto& mesh = model.addMesh("blocks:");
mesh.shading = lighting;
UVRegion boxtexfaces[6] = {
get_region_for(modelTextures[i * 6 + 5], assets),
get_region_for(modelTextures[i * 6 + 4], assets),
get_region_for(modelTextures[i * 6 + 3], assets),
get_region_for(modelTextures[i * 6 + 2], assets),
get_region_for(modelTextures[i * 6 + 1], assets),
get_region_for(modelTextures[i * 6 + 0], assets)
};
boxtexfaces[2].scale(glm::vec2(-1));
boxtexfaces[5].scale(glm::vec2(-1, 1));
UVRegion boxtexfaces[6] = {};
map_legacy_box_textures(modelTextures, i * 6, boxtexfaces, assets);
bool enabled[6] {1,1,1,1,1,1};
mesh.addBox(
@ -232,17 +255,14 @@ model::Model ModelsGenerator::loadCustomBlockModel(
modelBoxes.push_back(modelbox);
if (boxarr.size() == 7) {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back(boxarr[6].asString());
}
const auto texture = boxarr[6].asString();
modelTextures.insert(modelTextures.end(), 6, texture);
} else if (boxarr.size() == 12) {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back(boxarr[j].asString());
}
} else {
for (uint j = 6; j < 12; j++) {
modelTextures.emplace_back("notfound");
}
modelTextures.insert(modelTextures.end(), 6, "notfound");
}
}
}

View file

@ -324,11 +324,24 @@ void WorldRenderer::renderInWorldLines(
auto ctx = pctx.sub(lineBatch.get());
bool culling = engine.getSettings().graphics.frustumCulling.get();
level.entities->renderDebug(
*lineBatch, culling ? frustumCulling.get() : nullptr, ctx
*lineBatch, culling ? frustumCulling.get() : nullptr, ctx,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity() : 0
);
}
}
void WorldRenderer::updateEntitiesCulling(const Camera& camera) {
bool culling = engine.getSettings().graphics.frustumCulling.get();
if (culling) {
frustumCulling->update(camera.getProjView());
}
level.entities->updateCulling(
culling ? frustumCulling.get() : nullptr,
player.currentCamera.get() == player.fpCamera.get() ? player.getEntity()
: 0
);
}
void WorldRenderer::update(const Camera& camera, float delta) {
timer += delta;
chunksRenderer->update();

View file

@ -46,6 +46,7 @@ public:
~WorldRenderer();
void update(const Camera& camera, float delta);
void updateEntitiesCulling(const Camera& camera);
void renderFrame(
const DrawContext& context,

View file

@ -1,8 +1,5 @@
#include "GUI.hpp"
#include <algorithm>
#include <utility>
#include "assets/Assets.hpp"
#include "debug/Logger.hpp"
#include "elements/Label.hpp"
@ -17,7 +14,6 @@
#include "graphics/core/Shader.hpp"
#include "graphics/core/Font.hpp"
#include "graphics/core/DrawContext.hpp"
#include "graphics/core/Shader.hpp"
#include "gui_util.hpp"
#include "window/Camera.hpp"
#include "window/Window.hpp"

View file

@ -5,6 +5,9 @@
#include "graphics/render/WorldRenderer.hpp"
#include "graphics/render/NamedSkeletons.hpp"
#include <algorithm>
#include <glm/gtc/matrix_transform.hpp>
namespace scripting {
extern WorldRenderer* renderer;
}
@ -196,6 +199,174 @@ static int l_exists(lua::State* L) {
return lua::pushboolean(L, get_skeleton(L));
}
namespace {
struct NativeTrackBone {
std::string name;
bool translate = false;
int translation[3] {};
std::vector<std::pair<int, int>> rotations;
bool scale = false;
int scaling[3] {};
};
struct NativeTrack {
std::string name;
std::vector<NativeTrackBone> bones;
int valuesCount = 0;
std::weak_ptr<const rigging::SkeletonConfig> config;
std::vector<int> indices;
};
std::vector<NativeTrack> native_tracks;
constexpr int MAX_TRACK_VALUES = 256;
}
static void read_indices(lua::State* L, int idx, const char* field, int* dst) {
if (!lua::istable(L, -1)) {
return;
}
for (int i = 0; i < 3; i++) {
lua::rawgeti(L, i + 1);
dst[i] = static_cast<int>(lua::tointeger(L, -1));
lua::pop(L);
}
}
static int l_register_track(lua::State* L) {
NativeTrack track;
track.name = lua::require_string(L, 1);
if (!lua::istable(L, 2)) {
throw std::runtime_error("layout table expected");
}
int maxValue = 0;
size_t count = lua::objlen(L, 2);
for (size_t i = 1; i <= count; i++) {
lua::rawgeti(L, static_cast<int>(i), 2);
int bone = lua::gettop(L);
NativeTrackBone entry;
lua::requirefield(L, "name", bone);
entry.name = lua::require_string(L, -1);
lua::pop(L);
if (lua::getfield(L, "t", bone)) {
entry.translate = lua::istable(L, -1);
read_indices(L, bone, "t", entry.translation);
lua::pop(L);
}
if (lua::getfield(L, "s", bone)) {
entry.scale = lua::istable(L, -1);
read_indices(L, bone, "s", entry.scaling);
lua::pop(L);
}
if (lua::getfield(L, "r", bone)) {
if (lua::istable(L, -1)) {
size_t n = lua::objlen(L, -1);
for (size_t j = 1; j + 1 <= n; j += 2) {
lua::rawgeti(L, static_cast<int>(j), -1);
int axis = static_cast<int>(lua::tointeger(L, -1));
lua::rawgeti(L, static_cast<int>(j + 1), -2);
int value = static_cast<int>(lua::tointeger(L, -1));
lua::pop(L, 2);
if (axis < 0 || axis > 2) {
throw std::runtime_error("invalid rotation axis");
}
entry.rotations.emplace_back(axis, value);
}
}
lua::pop(L);
}
for (int v : entry.translation) {
maxValue = std::max(maxValue, v);
}
for (int v : entry.scaling) {
maxValue = std::max(maxValue, v);
}
for (auto [_, v] : entry.rotations) {
maxValue = std::max(maxValue, v);
}
track.bones.push_back(std::move(entry));
lua::pop(L);
}
track.valuesCount = maxValue;
for (size_t i = 0; i < native_tracks.size(); i++) {
if (native_tracks[i].name == track.name) {
native_tracks[i] = std::move(track);
return lua::pushinteger(L, static_cast<lua::Integer>(i));
}
}
native_tracks.push_back(std::move(track));
return lua::pushinteger(L, native_tracks.size() - 1);
}
static int l_apply_track(lua::State* L) {
auto skeleton = get_skeleton(L);
if (skeleton == nullptr || skeleton->config == nullptr) {
return 0;
}
auto id = lua::tointeger(L, 2);
if (id < 0 || static_cast<size_t>(id) >= native_tracks.size()) {
throw std::runtime_error("invalid track id");
}
auto& track = native_tracks[id];
const auto& config = skeleton->config;
if (track.config.owner_before(config) || config.owner_before(track.config) ||
track.config.expired() || track.indices.size() != track.bones.size()) {
track.config = config;
track.indices.clear();
for (const auto& bone : track.bones) {
auto found = config->find(bone.name);
track.indices.push_back(found ? static_cast<int>(found->getIndex()) : -1);
}
}
float values[MAX_TRACK_VALUES + 1] {};
int top = lua::gettop(L);
int count = std::min({track.valuesCount, top - 2, MAX_TRACK_VALUES});
for (int i = 1; i <= count; i++) {
values[i] = static_cast<float>(lua::tonumber(L, i + 2));
}
static const glm::vec3 AXES[] {{1, 0, 0}, {0, 1, 0}, {0, 0, 1}};
auto value = [&values](int index, float fallback) {
return index > 0 && index <= MAX_TRACK_VALUES ? values[index] : fallback;
};
auto& matrices = skeleton->pose.matrices;
for (size_t i = 0; i < track.bones.size(); i++) {
int index = track.indices[i];
if (index < 0 || static_cast<size_t>(index) >= matrices.size()) {
continue;
}
const auto& bone = track.bones[i];
auto& matrix = matrices[index];
if (bone.translate) {
matrix = glm::translate(matrix, glm::vec3(
value(bone.translation[0], 0.0f),
value(bone.translation[1], 0.0f),
value(bone.translation[2], 0.0f)
));
}
for (const auto& [axis, v] : bone.rotations) {
matrix = glm::rotate(matrix, glm::radians(value(v, 0.0f)), AXES[axis]);
}
if (bone.scale) {
matrix = glm::scale(matrix, glm::vec3(
value(bone.scaling[0], 1.0f),
value(bone.scaling[1], 1.0f),
value(bone.scaling[2], 1.0f)
));
}
}
return 0;
}
static int l_is_culled(lua::State* L) {
if (auto skeleton = get_skeleton(L)) {
return lua::pushboolean(L, skeleton->culled);
}
return lua::pushboolean(L, false);
}
const luaL_Reg skeletonlib[] = {
{"get_model", lua::wrap<l_get_model>},
{"set_model", lua::wrap<l_set_model>},
@ -212,5 +383,8 @@ const luaL_Reg skeletonlib[] = {
{"is_interpolated", lua::wrap<l_is_interpolated>},
{"set_interpolated", lua::wrap<l_set_interpolated>},
{"exists", lua::wrap<l_exists>},
{"is_culled", lua::wrap<l_is_culled>},
{"register_track", lua::wrap<l_register_track>},
{"apply_track", lua::wrap<l_apply_track>},
{nullptr, nullptr}
};

View file

@ -70,7 +70,7 @@ static int l_get_def(lua::State* L) {
static int l_spawn(lua::State* L) {
auto level = controller->getLevel();
auto defname = lua::tostring(L, 1);
auto defname = lua::require_string(L, 1);
auto& def = content->entities.require(defname);
auto pos = lua::tovec3(L, 2);
dv::value args = nullptr;

View file

@ -211,59 +211,36 @@ static int l_tostring(lua::State* L) {
return lua::pushstring(L, ss.str());
}
#define VECLIB_BASE(n) \
{"add", lua::wrap<l_binop<n, std::plus>>}, \
{"sub", lua::wrap<l_binop<n, std::minus>>}, \
{"mul", lua::wrap<l_binop<n, std::multiplies>>}, \
{"div", lua::wrap<l_binop<n, std::divides>>}, \
{"distance", lua::wrap<l_distance<n>>}, \
{"normalize", lua::wrap<l_unaryop<n, glm::normalize>>}, \
{"length", lua::wrap<l_scalar_op<n, glm::length>>}, \
{"tostring", lua::wrap<l_tostring<n>>}, \
{"abs", lua::wrap<l_unaryop<n, glm::abs>>}, \
{"round", lua::wrap<l_unaryop<n, glm::round>>}, \
{"inverse", lua::wrap<l_inverse<n>>}, \
{"pow", lua::wrap<l_pow<n>>}, \
{"dot", lua::wrap<l_dot<n>>}, \
{"mix", lua::wrap<l_mix<n>>},
const luaL_Reg vec2lib[] = {
{"add", lua::wrap<l_binop<2, std::plus>>},
{"sub", lua::wrap<l_binop<2, std::minus>>},
{"mul", lua::wrap<l_binop<2, std::multiplies>>},
{"div", lua::wrap<l_binop<2, std::divides>>},
{"distance", lua::wrap<l_distance<2>>},
{"normalize", lua::wrap<l_unaryop<2, glm::normalize>>},
{"length", lua::wrap<l_scalar_op<2, glm::length>>},
{"tostring", lua::wrap<l_tostring<2>>},
{"abs", lua::wrap<l_unaryop<2, glm::abs>>},
{"round", lua::wrap<l_unaryop<2, glm::round>>},
{"inverse", lua::wrap<l_inverse<2>>},
{"pow", lua::wrap<l_pow<2>>},
{"dot", lua::wrap<l_dot<2>>},
VECLIB_BASE(2)
{"angle", lua::wrap<l_vec2_angle>},
{"mix", lua::wrap<l_mix<2>>},
{"rotate", lua::wrap<l_vec2_rotate>},
{nullptr, nullptr}
};
const luaL_Reg vec3lib[] = {
{"add", lua::wrap<l_binop<3, std::plus>>},
{"sub", lua::wrap<l_binop<3, std::minus>>},
{"mul", lua::wrap<l_binop<3, std::multiplies>>},
{"div", lua::wrap<l_binop<3, std::divides>>},
{"distance", lua::wrap<l_distance<3>>},
{"normalize", lua::wrap<l_unaryop<3, glm::normalize>>},
{"length", lua::wrap<l_scalar_op<3, glm::length>>},
{"tostring", lua::wrap<l_tostring<3>>},
{"abs", lua::wrap<l_unaryop<3, glm::abs>>},
{"round", lua::wrap<l_unaryop<3, glm::round>>},
{"inverse", lua::wrap<l_inverse<3>>},
{"pow", lua::wrap<l_pow<3>>},
{"dot", lua::wrap<l_dot<3>>},
VECLIB_BASE(3)
{"spherical_rand", lua::wrap<l_spherical_rand>},
{"mix", lua::wrap<l_mix<3>>},
{nullptr, nullptr}
};
const luaL_Reg vec4lib[] = {
{"add", lua::wrap<l_binop<4, std::plus>>},
{"sub", lua::wrap<l_binop<4, std::minus>>},
{"mul", lua::wrap<l_binop<4, std::multiplies>>},
{"div", lua::wrap<l_binop<4, std::divides>>},
{"distance", lua::wrap<l_distance<4>>},
{"normalize", lua::wrap<l_unaryop<4, glm::normalize>>},
{"length", lua::wrap<l_scalar_op<4, glm::length>>},
{"tostring", lua::wrap<l_tostring<4>>},
{"abs", lua::wrap<l_unaryop<4, glm::abs>>},
{"round", lua::wrap<l_unaryop<4, glm::round>>},
{"inverse", lua::wrap<l_inverse<4>>},
{"pow", lua::wrap<l_pow<4>>},
{"dot", lua::wrap<l_dot<4>>},
{"mix", lua::wrap<l_mix<4>>},
VECLIB_BASE(4)
{nullptr, nullptr}
};

View file

@ -425,7 +425,7 @@ static void debug_render_skeleton(
}
void Entities::renderDebug(
LineBatch& batch, const Frustum* frustum, const DrawContext& pctx
LineBatch& batch, const Frustum* frustum, const DrawContext& pctx, entityid_t fpsEntity
) {
{
auto ctx = pctx.sub(&batch);
@ -453,12 +453,15 @@ void Entities::renderDebug(
}
}
{
auto view = registry->view<Transform, rigging::Skeleton>();
auto view = registry->view<EntityId, Transform, rigging::Skeleton>();
auto ctx = pctx.sub(&batch);
ctx.setDepthTest(false);
ctx.setDepthMask(false);
ctx.setLineWidth(2);
for (auto [entity, transform, skeleton] : view.each()) {
for (auto [entity, eid, transform, skeleton] : view.each()) {
if (eid.uid == fpsEntity) {
continue;
}
auto config = skeleton.config;
if (config == nullptr) {
continue;
@ -509,6 +512,19 @@ void Entities::render(
}
}
void Entities::updateCulling(const Frustum* frustum, entityid_t fpsEntity) {
auto view = registry->view<EntityId, Transform, rigging::Skeleton, Rigidbody>();
for (auto [entity, eid, transform, skeleton, rigidbody] : view.each()) {
if (frustum == nullptr || eid.uid == fpsEntity) {
skeleton.culled = false;
continue;
}
const auto& pos = transform.pos;
const auto& halfSize = rigidbody.hitbox.getHalfSize();
skeleton.culled = !frustum->isBoxVisible(pos - halfSize, pos + halfSize);
}
}
bool Entities::hasBlockingInside(AABB aabb) {
constexpr float eps = 0.05f;
auto view = registry->view<EntityId, Rigidbody>();

View file

@ -58,7 +58,7 @@ public:
void update(float delta);
void renderDebug(
LineBatch& batch, const Frustum* frustum, const DrawContext& ctx
LineBatch& batch, const Frustum* frustum, const DrawContext& ctx, entityid_t fpsEntity
);
void render(
const Assets& assets,
@ -67,6 +67,8 @@ public:
entityid_t fpsEntity
);
void updateCulling(const Frustum* frustum, entityid_t fpsEntity);
entityid_t spawn(
const EntityDef& def,
glm::vec3 position,

View file

@ -322,7 +322,7 @@ void Player::deserialize(const dv::value& src) {
src.at("loading-chunks").get(loadingChunks);
setChosenSlot(src["chosen-slot"].asInteger());
eid = src["entity"].asNumber();
eid = src["entity"].asInteger();
if (src.has("inventory")) {
getInventory()->deserialize(src["inventory"]);