diff --git a/res/preload.json b/res/preload.json index ae9056b7f..6b0093f36 100644 --- a/res/preload.json +++ b/res/preload.json @@ -5,6 +5,7 @@ "main", "lines", "entity", + "model", "translucent", "translucent_composite", "background", diff --git a/res/shaders/entity.glslf b/res/shaders/entity.glslf index baaaea09e..701d481fb 100644 --- a/res/shaders/entity.glslf +++ b/res/shaders/entity.glslf @@ -1,71 +1 @@ -layout (location = 0) out vec4 f_color; -layout (location = 1) out vec4 f_position; -layout (location = 2) out vec4 f_normal; -layout (location = 3) out vec4 f_emission; - -uniform vec3 u_sunDir; - -#include -#include - -in vec4 a_color; - -uniform sampler2D u_texture0; -uniform float u_alphaThreshold; -uniform bool u_opaque; -uniform bool u_forward; -uniform bool u_forwardLight; -uniform bool u_alphaClip; - -const float BAYER_MATRIX[64] = float[]( - 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, - 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, - 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, - 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, - 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, - 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, - 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, - 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0 -); - -float calc_bayer(vec2 pos){ - ivec2 p = ivec2(mod(pos, 8.0)); - return BAYER_MATRIX[p.y * 8 + p.x] / 64.0; -} - -void main() { - vec4 texColor = texture(u_texture0, a_texCoord); - float alpha = a_color.a * texColor.a; - if (u_opaque) { - float bayer = calc_bayer(gl_FragCoord.xy); - if (alpha - bayer < 0.01) { - discard; - } - alpha = 1.0; - } else { - if (alpha < u_alphaThreshold) { - discard; - } - } - f_color = a_color * texColor; - -#ifdef ADVANCED_RENDER - if (u_forward) { - if (u_forwardLight) { - f_color.rgb *= calc_deferred_light( - a_modelpos, a_realnormal, length(a_position), a_emission, 1.0 - ); - } - vec3 fogColor = texture(u_skybox, a_dir).rgb; - f_color.rgb = mix(f_color.rgb, fogColor, a_fog); - } -#else - vec3 fogColor = texture(u_skybox, a_dir).rgb; - f_color.rgb = mix(f_color.rgb, fogColor, a_fog); -#endif - - f_color.a = u_opaque ? 1.0 : alpha; - f_position = vec4(a_position, 1.0); - f_normal = vec4(a_normal, 1.0); - f_emission = vec4(vec3(a_emission), 1.0); -} +#include diff --git a/res/shaders/lib/entity_fragment.glsl b/res/shaders/lib/entity_fragment.glsl new file mode 100644 index 000000000..736d8fe5d --- /dev/null +++ b/res/shaders/lib/entity_fragment.glsl @@ -0,0 +1,71 @@ +layout (location = 0) out vec4 f_color; +layout (location = 1) out vec4 f_position; +layout (location = 2) out vec4 f_normal; +layout (location = 3) out vec4 f_emission; + +uniform vec3 u_sunDir; + +#include +#include + +in vec4 a_color; + +uniform sampler2D u_texture0; +uniform float u_alphaThreshold; +uniform bool u_opaque; +uniform bool u_forward; +uniform bool u_forwardLight; +uniform bool u_alphaClip; + +const float BAYER_MATRIX[64] = float[]( + 0.0, 32.0, 8.0, 40.0, 2.0, 34.0, 10.0, 42.0, + 48.0, 16.0, 56.0, 24.0, 50.0, 18.0, 58.0, 26.0, + 12.0, 44.0, 4.0, 36.0, 14.0, 46.0, 6.0, 38.0, + 60.0, 28.0, 52.0, 20.0, 62.0, 30.0, 54.0, 22.0, + 3.0, 35.0, 11.0, 43.0, 1.0, 33.0, 9.0, 41.0, + 51.0, 19.0, 59.0, 27.0, 49.0, 17.0, 57.0, 25.0, + 15.0, 47.0, 7.0, 39.0, 13.0, 45.0, 5.0, 37.0, + 63.0, 31.0, 55.0, 23.0, 61.0, 29.0, 53.0, 21.0 +); + +float calc_bayer(vec2 pos){ + ivec2 p = ivec2(mod(pos, 8.0)); + return BAYER_MATRIX[p.y * 8 + p.x] / 64.0; +} + +void main() { + vec4 texColor = texture(u_texture0, a_texCoord); + float alpha = a_color.a * texColor.a; + if (u_opaque) { + float bayer = calc_bayer(gl_FragCoord.xy); + if (alpha - bayer < 0.01) { + discard; + } + alpha = 1.0; + } else { + if (alpha < u_alphaThreshold) { + discard; + } + } + f_color = a_color * texColor; + +#ifdef ADVANCED_RENDER + if (u_forward) { + if (u_forwardLight) { + f_color.rgb *= calc_deferred_light( + a_modelpos, a_realnormal, length(a_position), a_emission, 1.0 + ); + } + vec3 fogColor = texture(u_skybox, a_dir).rgb; + f_color.rgb = mix(f_color.rgb, fogColor, a_fog); + } +#else + vec3 fogColor = texture(u_skybox, a_dir).rgb; + f_color.rgb = mix(f_color.rgb, fogColor, a_fog); +#endif + + f_color.a = u_opaque ? 1.0 : alpha; + f_position = vec4(a_position, 1.0); + f_normal = vec4(a_normal, 1.0); + f_emission = vec4(vec3(a_emission), 1.0); +} diff --git a/res/shaders/model.glslf b/res/shaders/model.glslf new file mode 100644 index 000000000..701d481fb --- /dev/null +++ b/res/shaders/model.glslf @@ -0,0 +1 @@ +#include diff --git a/res/shaders/model.glslv b/res/shaders/model.glslv new file mode 100644 index 000000000..20202cf1a --- /dev/null +++ b/res/shaders/model.glslv @@ -0,0 +1,58 @@ +#include + +layout (location = 0) in vec3 v_position; +layout (location = 1) in vec2 v_texCoord; +layout (location = 2) in vec3 v_normal; +layout (location = 3) in mat4 i_model; +layout (location = 7) in vec4 i_tint; +layout (location = 8) in vec4 i_light; +layout (location = 9) in vec4 i_uvRegion; +layout (location = 10) in vec4 i_params; + +#include +#include +#include +#include + +out vec4 a_color; + +uniform float u_dayTime; + +const vec3 SUN_VECTOR = vec3(0.411934, 0.863868, -0.279161); + +void main() { + a_modelpos = i_model * vec4(v_position, 1.0); + vec3 pos3d = a_modelpos.xyz - u_cameraPos; + + vec3 normal = mat3(i_model) * v_normal; + float normalLength = length(normal); + normal = normalLength > 1e-6 ? normal / normalLength : v_normal; + + bool shading = i_params.x > 0.5; + vec4 light = i_light; + if (shading) { + light *= 0.8 + dot(normal, SUN_VECTOR) * 0.2; + } + + a_realnormal = normal; + a_normal = calc_screen_normal(a_realnormal); + + a_color = vec4(calc_torch_light( + light.rgb, a_realnormal, a_modelpos.xyz, u_torchlightColor, u_gamma + ), 1.0); + a_texCoord = v_texCoord * i_uvRegion.zw + i_uvRegion.xy; + + a_dir = a_modelpos.xyz - u_cameraPos; + vec3 skyLightColor = pick_sky_color(u_skybox, u_dayTime, u_minSkyLight); + a_color.rgb = max(a_color.rgb, skyLightColor.rgb * light.a) * i_tint.rgb; + a_color.a = u_opacity * i_tint.a; + + mat4 viewmodel = u_view * u_model; + a_distance = length(viewmodel * vec4(pos3d, 0.0)); + a_fog = calc_fog(length(viewmodel * vec4(pos3d * FOG_POS_SCALE, 0.0)) / 256.0); + a_emission = shading ? 0.0 : 1.0; + + vec4 viewmodelpos = u_view * a_modelpos; + a_position = viewmodelpos.xyz; + gl_Position = u_proj * viewmodelpos; +} diff --git a/src/animation/rigging.cpp b/src/animation/rigging.cpp index f59d8ce53..18cfa770e 100644 --- a/src/animation/rigging.cpp +++ b/src/animation/rigging.cpp @@ -197,13 +197,13 @@ void SkeletonConfig::render( continue; } node->model.refresh(assets); - auto model = node->model.model.lock().get(); // TODO: cache model pointer during frame + auto model = node->model.model.lock(); // TODO: cache model pointer during frame auto& modelOverride = skeleton.modelOverrides.at(i); if (modelOverride.updateFlag) { modelOverride.refresh(assets); } if (auto foundOverride = modelOverride.model.lock()) { - model = foundOverride.get(); + model = std::move(foundOverride); } if (model == nullptr) { if (!node->model.name.empty()) { diff --git a/src/graphics/core/InstanceBuffer.hpp b/src/graphics/core/InstanceBuffer.hpp new file mode 100644 index 000000000..4513a353e --- /dev/null +++ b/src/graphics/core/InstanceBuffer.hpp @@ -0,0 +1,20 @@ +#pragma once + +#include + +#include "MeshData.hpp" + +template +class InstanceBuffer { + unsigned int vbo; + size_t capacity; +public: + InstanceBuffer(); + ~InstanceBuffer(); + + void reload(const InstanceStructure* instances, size_t count); + + void bind(int location, size_t first) const; +}; + +#include "graphics/core/InstanceBuffer.inl" diff --git a/src/graphics/core/InstanceBuffer.inl b/src/graphics/core/InstanceBuffer.inl new file mode 100644 index 000000000..67110705c --- /dev/null +++ b/src/graphics/core/InstanceBuffer.inl @@ -0,0 +1,55 @@ +#pragma once + +#include + +#include "gl_util.hpp" + +template +InstanceBuffer::InstanceBuffer() : vbo(0), capacity(0) { + static_assert( + calc_size(InstanceStructure::ATTRIBUTES) == sizeof(InstanceStructure) + ); + glGenBuffers(1, &vbo); +} + +template +InstanceBuffer::~InstanceBuffer() { + glDeleteBuffers(1, &vbo); +} + +template +void InstanceBuffer::reload( + const InstanceStructure* instances, size_t count +) { + size_t size = count * sizeof(InstanceStructure); + if (size > capacity) { + capacity = std::max(size, capacity * 2); + } + glBindBuffer(GL_ARRAY_BUFFER, vbo); + glBufferData(GL_ARRAY_BUFFER, capacity, nullptr, GL_STREAM_DRAW); + glBufferSubData(GL_ARRAY_BUFFER, 0, size, instances); + glBindBuffer(GL_ARRAY_BUFFER, 0); +} + +template +void InstanceBuffer::bind(int location, size_t first) const { + const auto& attrs = InstanceStructure::ATTRIBUTES; + + glBindBuffer(GL_ARRAY_BUFFER, vbo); + size_t offset = first * sizeof(InstanceStructure); + for (int i = 0; attrs[i].count; i++) { + const VertexAttribute& attr = attrs[i]; + glVertexAttribPointer( + location + i, + attr.count, + gl::to_glenum(attr.type), + attr.normalized, + sizeof(InstanceStructure), + (GLvoid*)offset + ); + glVertexAttribDivisor(location + i, 1); + glEnableVertexAttribArray(location + i); + offset += attr.size(); + } + glBindBuffer(GL_ARRAY_BUFFER, 0); +} diff --git a/src/graphics/core/Mesh.hpp b/src/graphics/core/Mesh.hpp index 2ff15cc2a..92b967fae 100644 --- a/src/graphics/core/Mesh.hpp +++ b/src/graphics/core/Mesh.hpp @@ -3,6 +3,7 @@ #include #include "MeshData.hpp" +#include "InstanceBuffer.hpp" struct MeshStats { @@ -64,6 +65,13 @@ public: /// @brief Draw mesh as triangles void draw() const; + + template + void drawInstanced( + const InstanceBuffer& instances, + size_t first, + size_t count + ) const; private: }; diff --git a/src/graphics/core/Mesh.inl b/src/graphics/core/Mesh.inl index 4c6424dd1..7452acc7e 100644 --- a/src/graphics/core/Mesh.inl +++ b/src/graphics/core/Mesh.inl @@ -3,14 +3,6 @@ #include "MeshData.hpp" #include "gl_util.hpp" -inline constexpr size_t calc_size(const VertexAttribute attrs[]) { - size_t vertexSize = 0; - for (int i = 0; attrs[i].count; i++) { - vertexSize += attrs[i].size(); - } - return vertexSize; -} - template inline std::vector convert_to_ibd(const MeshData& data) { std::vector indices; @@ -144,3 +136,21 @@ template void Mesh::draw() const { draw(GL_TRIANGLES); } + +template +template +void Mesh::drawInstanced( + const InstanceBuffer& instances, + size_t first, + size_t count +) const { + if (vertexCount == 0 || count == 0) { + return; + } + MeshStats::drawCalls++; + + glBindVertexArray(vao); + instances.bind(count_attributes(VertexStructure::ATTRIBUTES), first); + glDrawArraysInstanced(GL_TRIANGLES, 0, vertexCount, count); + glBindVertexArray(0); +} diff --git a/src/graphics/core/MeshData.hpp b/src/graphics/core/MeshData.hpp index e9a0630c5..c26f53fd2 100644 --- a/src/graphics/core/MeshData.hpp +++ b/src/graphics/core/MeshData.hpp @@ -37,6 +37,22 @@ struct VertexAttribute { } }; +inline constexpr size_t calc_size(const VertexAttribute attrs[]) { + size_t vertexSize = 0; + for (int i = 0; attrs[i].count; i++) { + vertexSize += attrs[i].size(); + } + return vertexSize; +} + +inline constexpr int count_attributes(const VertexAttribute attrs[]) { + int count = 0; + while (attrs[count].count) { + count++; + } + return count; +} + /// @brief Raw mesh data structure template struct MeshData { diff --git a/src/graphics/render/ModelBatch.cpp b/src/graphics/render/ModelBatch.cpp index ba9b84425..958f2bc0d 100644 --- a/src/graphics/render/ModelBatch.cpp +++ b/src/graphics/render/ModelBatch.cpp @@ -2,47 +2,18 @@ #include "assets/assets_util.hpp" #include "graphics/commons/Model.hpp" -#include "graphics/core/Mesh.hpp" -#include "graphics/core/Atlas.hpp" #include "graphics/core/Texture.hpp" +#include "graphics/core/ImageData.hpp" +#include "graphics/core/Mesh.hpp" #include "assets/Assets.hpp" #include "voxels/Chunks.hpp" -#include "lighting/Lightmap.hpp" #include "settings.hpp" #include "MainBatch.hpp" -#define GLM_ENABLE_EXPERIMENTAL -#include -#include -#include - #include -inline constexpr glm::vec3 X(1, 0, 0); -inline constexpr glm::vec3 Y(0, 1, 0); -inline constexpr glm::vec3 Z(0, 0, 1); - -struct DecomposedMat4 { - glm::vec3 scale; - glm::mat3 rotation; - glm::vec3 translation; - glm::vec3 skew; - glm::vec4 perspective; -}; - -static glm::mat4 extract_rotation(glm::mat4 matrix) { - DecomposedMat4 decomposed = {}; - glm::quat rotation; - glm::decompose( - matrix, - decomposed.scale, - rotation, - decomposed.translation, - decomposed.skew, - decomposed.perspective - ); - return glm::toMat3(rotation); -} +inline constexpr uint64_t COLLECT_EVERY = 600; +inline constexpr uint64_t UNUSED_FRAMES = 1200; ModelBatch::ModelBatch( size_t capacity, @@ -50,135 +21,204 @@ ModelBatch::ModelBatch( const Chunks& chunks, const EngineSettings& settings ) - : assets(assets), - chunks(chunks), - settings(settings), - batch(std::make_unique(capacity)) {} + : assets(assets), chunks(chunks), settings(settings) { + entries.reserve(capacity / 36); + + const ubyte pixels[] = {255, 255, 255, 255}; + ImageData image(ImageFormat::RGBA8888, 1, 1, pixels); + blank = Texture::from(&image); + + instanceBuffer = std::make_unique>(); +} ModelBatch::~ModelBatch() = default; -void ModelBatch::draw( - const model::Mesh& mesh, - const glm::mat4& matrix, - const glm::mat3& rotation, - const glm::vec4& tint, - const TextureNamesMap* varTextures, - bool backlight +ModelBatch::GpuModel& ModelBatch::upload( + const std::shared_ptr& model ) { - setTexture(mesh.texture, varTextures); - size_t vcount = mesh.vertices.size(); - const auto& vertexData = mesh.vertices.data(); - - glm::vec4 lights(1, 1, 1, 0); - if (mesh.shading) { - glm::vec3 gpos = matrix * glm::vec4(0.0f, 0.0f, 0.0f, 1.0f); - gpos += lightsOffset + localLightsOffset; - lights = MainBatch::sampleLight(gpos, chunks, backlight); + auto& gpuModel = models[model.get()]; + bool valid = gpuModel.model.lock() == model && + gpuModel.meshes.size() == model->meshes.size(); + for (size_t i = 0; valid && i < gpuModel.meshes.size(); i++) { + valid = gpuModel.meshes[i].vertexCount == + model->meshes[i].vertices.size(); } - for (size_t i = 0; i < vcount / 3; i++) { - batch->prepare(3); - for (size_t j = 0; j < 3; j++) { - const auto vert = vertexData[i * 3 + j]; - float d = 1.0f; - auto norm = rotation * vert.normal; - if (mesh.shading) { - d = glm::dot(norm, SUN_VECTOR); - d = 0.8f + d * 0.2f; - } - batch->vertex( - matrix * glm::vec4(vert.coord, 1.0f), - vert.uv, - lights * d, - tint, - norm, - mesh.shading ? 0.0f : 1.0f - ); + static_assert(sizeof(Vertex) == sizeof(model::Vertex)); + if (!valid) { + gpuModel.meshes.clear(); + gpuModel.model = model; + for (const auto& mesh : model->meshes) { + gpuModel.meshes.push_back(GpuMesh { + std::make_unique>( + reinterpret_cast(mesh.vertices.data()), + mesh.vertices.size() + ), + mesh.vertices.size()}); } } + gpuModel.lastUsed = frame; + return gpuModel; +} + +void ModelBatch::collectUnused() { + for (auto it = models.begin(); it != models.end();) { + if (frame - it->second.lastUsed > UNUSED_FRAMES || + it->second.model.expired()) { + it = models.erase(it); + } else { + ++it; + } + } +} + +const util::TextureRegion& ModelBatch::getTexture( + const std::string& name, const TextureNamesMap* varTextures +) { + static const util::TextureRegion NONE {nullptr, UVRegion(0, 0, 1, 1)}; + if (varTextures && !name.empty() && name.at(0) == '$') { + const auto& found = varTextures->find(name); + if (found == varTextures->end()) { + return NONE; + } + return getTexture(found->second, varTextures); + } + const auto& found = textures.find(&name); + if (found != textures.end()) { + return found->second; + } + auto byName = texturesByName.find(name); + if (byName == texturesByName.end()) { + byName = texturesByName.emplace( + name, util::get_texture_region(assets, name, "blocks:notfound") + ).first; + } + return textures[&name] = byName->second; } void ModelBatch::draw( const glm::mat4& matrix, const glm::vec4& tint, const glm::vec3& lightSampleOffset, - const model::Model* model, + const std::shared_ptr& model, const TextureNamesMap* varTextures, bool translucent ) { auto& queue = translucent || tint.a < 1.0f ? translucentEntries : entries; - for (const auto& mesh : model->meshes) { + const auto& gpuModel = upload(model); + glm::vec3 lightSamplePos = + glm::vec3(matrix[3]) + lightsOffset + lightSampleOffset; + for (size_t i = 0; i < model->meshes.size(); i++) { + const auto& mesh = model->meshes[i]; + if (mesh.vertices.empty()) { + continue; + } + const auto& region = getTexture(mesh.texture, varTextures); + const auto& uv = region.region; queue.push_back(DrawEntry { - matrix, - extract_rotation(matrix), - tint, - lightSampleOffset, - &mesh, - varTextures}); + region.texture ? region.texture : blank.get(), + gpuModel.meshes[i].mesh.get(), + lightSamplePos, + mesh.shading, + Instance { + matrix, + tint, + glm::vec4(1, 1, 1, 0), + glm::vec4(uv.u1, uv.v1, uv.getWidth(), uv.getHeight()), + glm::vec4(mesh.shading ? 1.0f : 0.0f, 0, 0, 0)}}); + } +} + +void ModelBatch::resetOrder(size_t count) { + order.resize(count); + for (size_t i = 0; i < count; i++) { + order[i] = i; } } void ModelBatch::render(std::vector& queue) { - bool backlight = settings.graphics.backlight.get(); - for (auto& entry : queue) { - localLightsOffset = entry.lightSampleOffset; - draw( - *entry.mesh, - entry.matrix, - entry.rotation, - entry.tint, - entry.varTextures, - backlight - ); - localLightsOffset = {}; + if (queue.empty()) { + return; + } + bool backlight = settings.graphics.backlight.get(); + + instances.resize(queue.size()); + for (size_t i = 0; i < order.size(); i++) { + auto& entry = queue[order[i]]; + if (entry.shading) { + entry.instance.light = + MainBatch::sampleLight(entry.lightSamplePos, chunks, backlight); + } + instances[i] = entry.instance; + } + + instanceBuffer->reload(instances.data(), instances.size()); + + const Texture* boundTexture = nullptr; + size_t start = 0; + for (size_t i = 1; i <= order.size(); i++) { + if (i < order.size()) { + const auto& prev = queue[order[i - 1]]; + const auto& next = queue[order[i]]; + if (prev.texture == next.texture && prev.mesh == next.mesh) { + continue; + } + } + const auto& entry = queue[order[start]]; + if (entry.texture != boundTexture) { + boundTexture = entry.texture; + boundTexture->bind(); + } + entry.mesh->drawInstanced(*instanceBuffer, start, i - start); + start = i; } - batch->flush(); queue.clear(); } +void ModelBatch::finishFrame() { + frame++; + textures.clear(); + texturesByName.clear(); + if (frame % COLLECT_EVERY == 0) { + collectUnused(); + } +} + void ModelBatch::render() { renderOpaque(); + resetOrder(translucentEntries.size()); render(translucentEntries); + finishFrame(); } void ModelBatch::renderOpaque() { - std::sort(entries.begin(), entries.end(), - [](const DrawEntry& a, const DrawEntry& b) { - return a.mesh->texture < b.mesh->texture; + resetOrder(entries.size()); + std::sort(order.begin(), order.end(), [this](size_t a, size_t b) { + const auto& ea = entries[a]; + const auto& eb = entries[b]; + if (ea.texture != eb.texture) { + return ea.texture < eb.texture; } - ); + return ea.mesh < eb.mesh; + }); render(entries); } void ModelBatch::renderTranslucent(const glm::vec3& cameraPosition) { - auto distance2 = [&cameraPosition](const DrawEntry& entry) { - glm::vec3 delta = glm::vec3(entry.matrix[3]) - cameraPosition; - return glm::dot(delta, delta); - }; - std::stable_sort( - translucentEntries.begin(), - translucentEntries.end(), - [&distance2](const DrawEntry& a, const DrawEntry& b) { - return distance2(a) > distance2(b); - } - ); + distances.resize(translucentEntries.size()); + for (size_t i = 0; i < translucentEntries.size(); i++) { + glm::vec3 delta = + glm::vec3(translucentEntries[i].instance.matrix[3]) - cameraPosition; + distances[i] = glm::dot(delta, delta); + } + resetOrder(translucentEntries.size()); + std::stable_sort(order.begin(), order.end(), [this](size_t a, size_t b) { + return distances[a] > distances[b]; + }); render(translucentEntries); + finishFrame(); } void ModelBatch::setLightsOffset(const glm::vec3& offset) { lightsOffset = offset; } - -void ModelBatch::setTexture(const std::string& name, - const TextureNamesMap* varTextures) { - if (varTextures && !name.empty() && name.at(0) == '$') { - const auto& found = varTextures->find(name); - if (found == varTextures->end()) { - return batch->setTexture(nullptr); - } else { - return setTexture(found->second, varTextures); - } - } - auto region = util::get_texture_region(assets, name, "blocks:notfound"); - batch->setTexture(region.texture, region.region); -} diff --git a/src/graphics/render/ModelBatch.hpp b/src/graphics/render/ModelBatch.hpp index 88b998e1d..d75131c43 100644 --- a/src/graphics/render/ModelBatch.hpp +++ b/src/graphics/render/ModelBatch.hpp @@ -6,12 +6,17 @@ #include #include -template class Mesh; +#include "assets/assets_util.hpp" +#include "graphics/core/MeshData.hpp" + +template +class Mesh; +template +class InstanceBuffer; class Texture; class Chunks; class Assets; struct EngineSettings; -class MainBatch; namespace model { struct Mesh; @@ -34,7 +39,7 @@ public: const glm::mat4& matrix, const glm::vec4& tint, const glm::vec3& lightSampleOffset, - const model::Model* model, + const std::shared_ptr& model, const TextureNamesMap* varTextures, bool translucent = false ); @@ -52,34 +57,77 @@ private: const EngineSettings& settings; glm::vec3 lightsOffset {}; - glm::vec3 localLightsOffset {}; - static inline glm::vec3 SUN_VECTOR {0.411934f, 0.863868f, -0.279161f}; + struct Vertex { + glm::vec3 coord; + glm::vec2 uv; + glm::vec3 normal; - std::unique_ptr batch; + static constexpr VertexAttribute ATTRIBUTES[] = { + {VertexAttribute::Type::FLOAT, false, 3}, + {VertexAttribute::Type::FLOAT, false, 2}, + {VertexAttribute::Type::FLOAT, false, 3}, + {{}, 0}}; + }; - void draw( - const model::Mesh& mesh, - const glm::mat4& matrix, - const glm::mat3& rotation, - const glm::vec4& tint, - const TextureNamesMap* varTextures, - bool backlight - ); + struct Instance { + glm::mat4 matrix; + glm::vec4 tint; + glm::vec4 light; + glm::vec4 uvRegion; + glm::vec4 params; - void setTexture(const std::string& name, - const TextureNamesMap* varTextures); + static constexpr VertexAttribute ATTRIBUTES[] = { + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {VertexAttribute::Type::FLOAT, false, 4}, + {{}, 0}}; + }; + + struct GpuMesh { + std::unique_ptr> mesh; + size_t vertexCount = 0; + }; + + struct GpuModel { + std::weak_ptr model; + std::vector meshes; + uint64_t lastUsed = 0; + }; struct DrawEntry { - glm::mat4 matrix; - glm::mat3 rotation; - glm::vec4 tint; - glm::vec3 lightSampleOffset; - const model::Mesh* mesh; - const TextureNamesMap* varTextures; + const Texture* texture; + const Mesh* mesh; + glm::vec3 lightSamplePos; + bool shading; + Instance instance; }; + + std::unordered_map models; + std::unordered_map textures; + std::unordered_map texturesByName; std::vector entries; std::vector translucentEntries; + std::vector order; + std::vector distances; + std::vector instances; + std::unique_ptr> instanceBuffer; + std::unique_ptr blank; + uint64_t frame = 0; + + GpuModel& upload(const std::shared_ptr& model); + void collectUnused(); + void resetOrder(size_t count); void render(std::vector& queue); + void finishFrame(); + + const util::TextureRegion& getTexture( + const std::string& name, const TextureNamesMap* varTextures + ); }; diff --git a/src/graphics/render/WorldRenderer.cpp b/src/graphics/render/WorldRenderer.cpp index 1087f4318..3882e6477 100644 --- a/src/graphics/render/WorldRenderer.cpp +++ b/src/graphics/render/WorldRenderer.cpp @@ -173,6 +173,7 @@ void WorldRenderer::refreshSettings() { Shader* affectedShaders[] { &assets.require("main"), &assets.require("entity"), + &assets.require("model"), &assets.require("clouds"), &assets.require("translucent"), &assets.require("deferred_lighting").getShader(), @@ -273,6 +274,10 @@ void WorldRenderer::renderOpaque( } setup_entity_pass(entityShader, {0.5f, true, false, false, 1.0f}); + + auto& modelShader = assets.require("model"); + setupWorldShader(modelShader, camera, settings, fogFactor); + setup_entity_pass(modelShader, {0.5f, true, false, false, 1.0f}); level.entities->render( assets, *modelBatch, @@ -281,6 +286,7 @@ void WorldRenderer::renderOpaque( : 0 ); modelBatch->renderOpaque(); + entityShader.use(); particles->render(camera); auto& mainShader = assets.require("main"); @@ -576,7 +582,7 @@ void WorldRenderer::renderTranslucency( auto lctx = ctx.sub(); lctx.setFramebuffer(&translucentLayers->getLayer(translucent::ENTITIES)); lctx.setCullFace(true); - auto& shader = assets.require("entity"); + auto& shader = assets.require("model"); setupWorldShader(shader, camera, settings, fogFactor); setup_entity_pass(shader, {0.002f, false, true, true, 1.0f}); modelBatch->renderTranslucent(camera.position); @@ -608,7 +614,7 @@ void WorldRenderer::renderDebugLines(const DrawContext& ctx, Camera& camera) { } void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) { - auto& entityShader = assets.require("entity"); + auto& modelShader = assets.require("model"); DrawContext ctx = pctx.sub(); ctx.setDepthTest(true); @@ -623,8 +629,8 @@ void WorldRenderer::renderHandsPass(const DrawContext& pctx, Camera& camera) { hudcam.setFov(0.9f); hudcam.position = {}; - setupWorldShader(entityShader, hudcam, engine.getSettings(), 0.0f); - setup_entity_pass(entityShader, {0.15f, false, false, false, 1.0f}); + setupWorldShader(modelShader, hudcam, engine.getSettings(), 0.0f); + setup_entity_pass(modelShader, {0.15f, false, false, false, 1.0f}); hands->render(camera); }