mirror of
https://github.com/MihailRis/voxelcore.git
synced 2026-11-21 01:49:44 +00:00
gpu instanced entities renderer
This commit is contained in:
parent
b985eed66a
commit
5d6446b06a
14 changed files with 492 additions and 228 deletions
|
|
@ -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 <glm/ext/matrix_transform.hpp>
|
||||
#include <glm/gtx/matrix_decompose.hpp>
|
||||
#include <glm/gtx/quaternion.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
|
||||
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<MainBatch>(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<InstanceBuffer<Instance>>();
|
||||
}
|
||||
|
||||
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::Model>& 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<Mesh<Vertex>>(
|
||||
reinterpret_cast<const Vertex*>(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::Model>& 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<DrawEntry>& 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);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -6,12 +6,17 @@
|
|||
#include <glm/glm.hpp>
|
||||
#include <unordered_map>
|
||||
|
||||
template<typename VertexStructure> class Mesh;
|
||||
#include "assets/assets_util.hpp"
|
||||
#include "graphics/core/MeshData.hpp"
|
||||
|
||||
template<typename VertexStructure>
|
||||
class Mesh;
|
||||
template<typename InstanceStructure>
|
||||
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::Model>& 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<MainBatch> 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<Vertex>> mesh;
|
||||
size_t vertexCount = 0;
|
||||
};
|
||||
|
||||
struct GpuModel {
|
||||
std::weak_ptr<model::Model> model;
|
||||
std::vector<GpuMesh> 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<Vertex>* mesh;
|
||||
glm::vec3 lightSamplePos;
|
||||
bool shading;
|
||||
Instance instance;
|
||||
};
|
||||
|
||||
std::unordered_map<const model::Model*, GpuModel> models;
|
||||
std::unordered_map<const std::string*, util::TextureRegion> textures;
|
||||
std::unordered_map<std::string, util::TextureRegion> texturesByName;
|
||||
std::vector<DrawEntry> entries;
|
||||
std::vector<DrawEntry> translucentEntries;
|
||||
std::vector<size_t> order;
|
||||
std::vector<float> distances;
|
||||
std::vector<Instance> instances;
|
||||
|
||||
std::unique_ptr<InstanceBuffer<Instance>> instanceBuffer;
|
||||
std::unique_ptr<Texture> blank;
|
||||
uint64_t frame = 0;
|
||||
|
||||
GpuModel& upload(const std::shared_ptr<model::Model>& model);
|
||||
void collectUnused();
|
||||
void resetOrder(size_t count);
|
||||
void render(std::vector<DrawEntry>& queue);
|
||||
void finishFrame();
|
||||
|
||||
const util::TextureRegion& getTexture(
|
||||
const std::string& name, const TextureNamesMap* varTextures
|
||||
);
|
||||
};
|
||||
|
|
|
|||
|
|
@ -173,6 +173,7 @@ void WorldRenderer::refreshSettings() {
|
|||
Shader* affectedShaders[] {
|
||||
&assets.require<Shader>("main"),
|
||||
&assets.require<Shader>("entity"),
|
||||
&assets.require<Shader>("model"),
|
||||
&assets.require<Shader>("clouds"),
|
||||
&assets.require<Shader>("translucent"),
|
||||
&assets.require<PostEffect>("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<Shader>("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<Shader>("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<Shader>("entity");
|
||||
auto& shader = assets.require<Shader>("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<Shader>("entity");
|
||||
auto& modelShader = assets.require<Shader>("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);
|
||||
}
|
||||
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue