载入中...
搜索中...
未找到
VirtualGeometry.cpp
浏览该文件的文档.
2#include <algorithm>
3#include <array>
4#include <cmath>
5#include <cstdint>
6#include <functional>
7#include <simplesquirrel/simplesquirrel.hpp>
8#include <string>
9#include <vector>
10#include "common/Exception.h"
11#include "common/Module.h"
12#include "data/ByteData.h"
13#include "graphics/Graphics.h"
16
17// VirtualGeometry.cpp
18namespace eve::virtualgeometry {
19namespace {
20
21std::string currentGraphicsBackend() {
22 auto *gfx = eve::ModuleManager::getInstance<eve::graphics::Graphics>("Graphics");
23 if (!gfx) gfx = eve::graphics::Graphics::create();
24 if (!gfx) return {};
25 return gfx->getBackendName();
26}
27
28} // namespace
29
31
33 const std::string backend = currentGraphicsBackend();
34 return backend == "vulkan" || backend == "webgpu";
35}
36
38 const std::string backend = currentGraphicsBackend();
39 if (backend != "vulkan" && backend != "webgpu")
40 throw Exception("VirtualGeometry.newRenderer: requires vulkan or webgpu Graphics backend");
41 return new VirtualGeometryRenderer();
42}
43
44void VirtualGeometry::expose(ssq::Table &table) {
45 auto cls = table.addClass(name, VirtualGeometry::create, false);
46 expose(cls);
47
48 auto renderer = table.addClass<VirtualGeometryRenderer>(
49 "VirtualGeometryRenderer",
50 std::function<VirtualGeometryRenderer *()>([]() -> VirtualGeometryRenderer * { return nullptr; }), true);
51 renderer.addFunc("buildIcosphere", &VirtualGeometryRenderer::buildIcosphere);
52 renderer.addFunc("setViewport", &VirtualGeometryRenderer::setViewport);
53 renderer.addFunc("setCameraSimple", &VirtualGeometryRenderer::setCameraSimple);
54 renderer.addFunc("setModelYaw", &VirtualGeometryRenderer::setModelYaw);
55 renderer.addFunc("update", &VirtualGeometryRenderer::update);
57 renderer.addFunc("getViewWidth", &VirtualGeometryRenderer::getViewWidth);
58 renderer.addFunc("getViewHeight", &VirtualGeometryRenderer::getViewHeight);
59 renderer.addFunc("isReady", &VirtualGeometryRenderer::isReady);
60 renderer.addFunc("getClusterCount", &VirtualGeometryRenderer::getClusterCount);
61 renderer.addFunc("getVisibleCount", &VirtualGeometryRenderer::getVisibleCount);
62 renderer.addFunc("getTotalTriangleCount", &VirtualGeometryRenderer::getTotalTriangleCount);
63 renderer.addFunc("getLodLevel", &VirtualGeometryRenderer::getLodLevel);
64 renderer.addFunc("getMaxLodLevel", &VirtualGeometryRenderer::getMaxLodLevel);
65}
66
67void VirtualGeometry::expose(ssq::Class &cls) {
68 cls.addFunc("getName", &VirtualGeometry::getName);
69 cls.addFunc("isAvailable", &VirtualGeometry::isAvailable);
70 cls.addFunc("newRenderer", &VirtualGeometry::newRenderer);
71}
72
73} // namespace eve::virtualgeometry
74
75// VirtualGeometryRenderer.cpp
76namespace eve::virtualgeometry {
77namespace {
78
79// Minimal column-major mat4 helpers (GLM is not linked into this module).
80struct Mat4 {
81 float m[16];
82 static Mat4 identity() {
83 Mat4 r{};
84 r.m[0] = r.m[5] = r.m[10] = r.m[15] = 1.f;
85 return r;
86 }
87 static Mat4 mul(const Mat4 &a, const Mat4 &b) {
88 Mat4 r{};
89 for (int c = 0; c < 4; ++c)
90 for (int row = 0; row < 4; ++row) {
91 float sum = 0;
92 for (int k = 0; k < 4; ++k) sum += a.m[k * 4 + row] * b.m[c * 4 + k];
93 r.m[c * 4 + row] = sum;
94 }
95 return r;
96 }
97};
98
99} // namespace
100
102
104
107 bool ok = builder.build(in, builderOptions_, asset_);
108 if (!ok) return false;
109 vgReset(backend_, visibleCapacity_); // size visible/stats before upload
110 vgUpload(backend_, asset_);
111 return true;
112}
113
114bool VirtualGeometryRenderer::build(const float *positions, int vertexCount, const std::uint32_t *indices,
115 int indexCount) {
118 in.positions = positions;
119 in.indices = indices;
121 return build(in);
122}
123
124namespace {
125// Build a unit icosphere (triangulated) into CPU buffers.
126void buildIco(std::vector<float> &positions, std::vector<std::uint32_t> &indices, int subdiv) {
127 positions.clear();
128 indices.clear();
129 struct F {
130 int a, b, c;
131 };
132 auto addVtx = [&](float x, float y, float z) {
133 float l = std::sqrt(x * x + y * y + z * z);
134 positions.push_back(x / l);
135 positions.push_back(y / l);
136 positions.push_back(z / l);
137 return static_cast<int>(positions.size() / 3) - 1;
138 };
139 auto tri = [&](int a, int b, int c) {
140 indices.push_back(static_cast<std::uint32_t>(a));
141 indices.push_back(static_cast<std::uint32_t>(b));
142 indices.push_back(static_cast<std::uint32_t>(c));
143 };
144 auto mid = [&](int i0, int i1) {
145 return addVtx(0.5f * (positions[3 * i0] + positions[3 * i1]),
146 0.5f * (positions[3 * i0 + 1] + positions[3 * i1 + 1]),
147 0.5f * (positions[3 * i0 + 2] + positions[3 * i1 + 2]));
148 };
149 const float t = (1.f + std::sqrt(5.f)) * 0.5f;
150 std::vector<std::array<float, 3>> base = {{-1, t, 0}, {1, t, 0}, {-1, -t, 0}, {1, -t, 0},
151 {0, -1, t}, {0, 1, t}, {0, -1, -t}, {0, 1, -t},
152 {t, 0, -1}, {t, 0, 1}, {-t, 0, -1}, {-t, 0, 1}};
153 int idx[12];
154 for (int i = 0; i < 12; ++i) idx[i] = addVtx(base[i][0], base[i][1], base[i][2]);
155 int faces[20][3] = {{0, 11, 5}, {0, 5, 1}, {0, 1, 7}, {0, 7, 10}, {0, 10, 11}, {1, 5, 9}, {5, 11, 4},
156 {11, 10, 2}, {10, 7, 6}, {7, 1, 8}, {3, 9, 4}, {3, 4, 2}, {3, 2, 6}, {3, 6, 8},
157 {3, 8, 9}, {4, 9, 5}, {2, 4, 11}, {6, 2, 10}, {8, 6, 7}, {9, 8, 1}};
158 std::vector<F> cur;
159 for (auto &f : faces) cur.push_back({idx[f[0]], idx[f[1]], idx[f[2]]});
160 for (int d = 0; d < subdiv; ++d) {
161 std::vector<F> nf;
162 for (auto &x : cur) {
163 int ab = mid(x.a, x.b), ac = mid(x.a, x.c), bc = mid(x.b, x.c);
164 nf.push_back({x.a, ab, ac});
165 nf.push_back({ab, x.b, bc});
166 nf.push_back({ac, bc, x.c});
167 nf.push_back({ab, bc, ac});
168 }
169 cur.swap(nf);
170 }
171 for (auto &x : cur) tri(x.a, x.b, x.c);
172}
173} // namespace
174
176 std::vector<float> pos;
177 std::vector<std::uint32_t> idx;
178 buildIco(pos, idx, std::clamp(subdiv, 1, 6));
179 return build(pos.data(), static_cast<int>(pos.size() / 3), idx.data(), static_cast<int>(idx.size()));
180}
181
182void VirtualGeometryRenderer::setViewport(int width, int height, float fovYDeg, float errorPx) {
183 width_ = std::max(1, width);
184 height_ = std::max(1, height);
185 uniforms_.params[0] = static_cast<float>(width_);
186 uniforms_.params[1] = static_cast<float>(height_);
187 uniforms_.params[2] = static_cast<float>(height_) / (2.f * std::tan(fovYDeg * 3.14159265358979323846f / 360.f));
188 uniforms_.params[3] = errorPx;
189}
190
191void VirtualGeometryRenderer::setCamera(const float view[16], const float proj[16], const float model[16],
192 const float camPos[3]) {
193 // Combined view-projection: clip = P * V * model * pos. The shader uses
194 // vgU.viewProj * (vgU.model * pos), so viewProj = P * V.
195 Mat4 p;
196 for (int i = 0; i < 16; ++i) p.m[i] = proj[i];
197 Mat4 v;
198 for (int i = 0; i < 16; ++i) v.m[i] = view[i];
199 Mat4 vp = Mat4::mul(p, v);
200 for (int i = 0; i < 16; ++i) uniforms_.viewProj[i] = vp.m[i];
201 for (int i = 0; i < 16; ++i) uniforms_.model[i] = model ? model[i] : Mat4::identity().m[i];
202 uniforms_.cameraPos[0] = camPos[0];
203 uniforms_.cameraPos[1] = camPos[1];
204 uniforms_.cameraPos[2] = camPos[2];
205 uniforms_.cameraPos[3] = 0.f;
206 updateUniforms();
207}
208
209void VirtualGeometryRenderer::setCameraSimple(float camX, float camY, float camZ, float nearZ, float farZ) {
210 const float fovY = (uniforms_.params[2] > 0.f)
211 ? 2.f * std::atan(static_cast<float>(height_) / (2.f * uniforms_.params[2]))
212 : 60.f * 3.14159265358979323846f / 180.f;
213 // Identity view (looking down -Z).
214 Mat4 view = Mat4::identity();
215 view.m[12] = -camX;
216 view.m[13] = -camY;
217 view.m[14] = -camZ;
218 // Perspective projection (column-major, D3D/Vulkan clip z in [0,1]).
219 Mat4 proj{};
220 const float a = 1.f / std::tan(fovY * 0.5f);
221 const float aspect = static_cast<float>(width_) / static_cast<float>(height_);
222 proj.m[0] = a / aspect;
223 proj.m[5] = a;
224 proj.m[10] = farZ / (nearZ - farZ);
225 proj.m[11] = -1.f;
226 proj.m[14] = (nearZ * farZ) / (nearZ - farZ);
227 const float camPos[3] = {camX, camY, camZ};
228 setCamera(view.m, proj.m, nullptr, camPos);
229}
230
231void VirtualGeometryRenderer::setModelYaw(float yaw) { modelYaw_ = yaw; }
232
233void VirtualGeometryRenderer::updateUniforms() {
234 uniforms_.misc[0] = static_cast<float>(static_cast<int>(asset_.clusters.size()));
235 if (modelYaw_ != 0.f) {
236 // Build a Y-rotation model matrix (column-major) and override.
237 float c = std::cos(modelYaw_), s = std::sin(modelYaw_);
238 Mat4 r = Mat4::identity();
239 r.m[0] = c;
240 r.m[2] = s;
241 r.m[8] = -s;
242 r.m[10] = c;
243 for (int i = 0; i < 16; ++i) uniforms_.model[i] = r.m[i];
244 }
245 // Recompute per-cluster screen-space error constants (errorR * projScale).
246 for (auto &c : asset_.clusters) c.errorRScreen = c.errorR * uniforms_.params[2];
247 vgUploadUniforms(backend_, uniforms_);
248}
249
251 int clusters = static_cast<int>(asset_.clusters.size());
252 if (clusters <= 0 || !backend_.state) return 0;
253 lastVisible_ = vgUpdate(backend_, clusters, visibleCapacity_, width_, height_);
254 return lastVisible_;
255}
256
257bool VirtualGeometryRenderer::resolve(unsigned char *outRgba, int &outW, int &outH) {
258 std::vector<std::uint32_t> pix;
259 if (!vgReadPixels(backend_, pix)) return false;
260 outW = width_;
261 outH = height_;
262 const int n = outW * outH;
263 for (int i = 0; i < n; ++i) {
264 std::uint32_t packed = pix[i];
265 std::uint32_t depth = packed >> 16;
266 std::uint32_t cid = packed & 0xFFFFu;
267 if (cid == 0u && depth == 0xFFFFu) {
268 outRgba[4 * i + 0] = 4;
269 outRgba[4 * i + 1] = 6;
270 outRgba[4 * i + 2] = 12;
271 outRgba[4 * i + 3] = 255;
272 continue;
273 }
274 // Stable per-cluster color hash.
275 std::uint32_t h = cid * 2654435761u;
276 float cr = static_cast<float>((h >> 16) & 0xFFu), cg = static_cast<float>((h >> 8) & 0xFFu),
277 cb = static_cast<float>(h & 0xFFu);
278 float mx = std::max({cr, cg, cb, 1.f});
279 float depthF = static_cast<float>(depth) / 65535.f;
280 float shade = 0.35f + 0.65f * (1.f - depthF);
281 outRgba[4 * i + 0] = static_cast<unsigned char>(cr / mx * 255.f * shade);
282 outRgba[4 * i + 1] = static_cast<unsigned char>(cg / mx * 255.f * shade);
283 outRgba[4 * i + 2] = static_cast<unsigned char>(cb / mx * 255.f * shade);
284 outRgba[4 * i + 3] = 255;
285 }
286 return true;
287}
288
290 int w = 1, h = 1;
291 auto *bd = new eve::data::ByteData(static_cast<std::size_t>(width_) * height_ * 4);
292 if (!bd) return nullptr;
293 if (!resolve(static_cast<unsigned char *>(bd->getData()), w, h)) {
294 delete bd;
295 return nullptr;
296 }
297 return bd;
298}
299
300int VirtualGeometryRenderer::getClusterCount() const { return static_cast<int>(asset_.clusters.size()); }
301
303
305 if (clusterId < 0 || static_cast<std::size_t>(clusterId) >= asset_.clusters.size()) return -1;
306 return static_cast<int>(asset_.clusters[clusterId].lodLevel);
307}
308
310 int m = 0;
311 for (const auto &c : asset_.clusters) m = std::max(m, static_cast<int>(c.lodLevel));
312 return m;
313}
314
315} // namespace eve::virtualgeometry
double z
double y
double m[16]
double x
float w
Definition AnimClip.cpp:738
int mid
Definition AnimSmr.cpp:120
const std::string & s
float yaw
Definition BushMesh.cpp:37
glm::vec4 p[6]
HSQOBJECT cls
Definition ECS.cpp:39
std::string name
Definition ECS.cpp:154
std::uint32_t vertexCount
std::uint32_t indexCount
uint32_t i1
Definition Grass.cpp:61
uint32_t i0
Definition Grass.cpp:61
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::uint32_t ab
double r
std::uint32_t ac
std::vector< std::uint32_t > indices
std::vector< float > positions
float v
std::int32_t c
int h
std::uint32_t height
std::uint32_t width
std::vector< RecipeParam > params
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
#define Module_IMPL(ModuleName, newExpr)
Definition Module.h:27
std::shared_ptr< OceanRenderer > renderer
OceanRenderBackend backend
OceanSprayView view
int idx
float f
float d
float t
std::string build
glm::mat4 model
glm::mat4 proj
std::uint32_t depth
uint64_t identity
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
virtual std::string getName() const =0
Returns the name.
In-memory byte buffer implementing eve::Data (ref-counted).
Definition ByteData.h:13
CPU preprocessor that builds a Nanite-style hierarchical cluster DAG from a triangle mesh:
Definition Builder.h:23
bool build(const MeshInput &in, const Options &opt, VirtualGeometryAsset &out)
Returns false on empty/invalid input.
Definition Builder.cpp:337
A virtual-geometry renderer: preprocesses a mesh into a cluster DAG, uploads it to the GPU,...
bool buildIcosphere(int subdiv)
Convenience: procedural unit icosphere, subdiv subdivision levels.
void setViewport(int width, int height, float fovYDeg, float errorPx=1.0f)
Sets the viewport.
int update()
Run cull + raster; returns the number of visible clusters.
int getClusterCount() const
Returns the cluster count.
~VirtualGeometryRenderer()
Virtual geometry renderer.
void setModelYaw(float yaw)
Spin the virtualized model about Y by yaw radians each frame.
void setCameraSimple(float camX, float camY, float camZ, float nearZ=0.1f, float farZ=100.f)
Script-friendly: identity view (camera looking down -Z) + perspective.
void setCamera(const float view[16], const float proj[16], const float model[16], const float camPos[3])
Sets the camera.
int getMaxLodLevel() const
Returns the max lod level.
bool build(const float *positions, int vertexCount, const std::uint32_t *indices, int indexCount)
Builds .
int getVisibleCount() const
Returns the visible count.
int getTotalTriangleCount() const
Returns the total triangle count.
int getViewHeight() const
Returns the view height.
int getLodLevel(int clusterId) const
Returns the lod level.
VirtualGeometryRenderer()
Virtual geometry renderer.
int getViewWidth() const
Returns the view width.
bool resolve(unsigned char *outRgba, int &outW, int &outH)
Resolve.
eve::data::ByteData * resolveByteData()
Resolve into a heap ByteData (RGBA) for scripting/display.
Virtual-geometry module — Nanite-style virtualized geometry rendering on top of the active Graphics b...
bool isAvailable() const
True when the active Graphics backend can run virtual geometry.
VirtualGeometryRenderer * newRenderer()
Create a virtual-geometry renderer (holds GPU buffers).
Vec3 mul(Vec3 a, float scale)
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
void vgReset(VgBackend &be, int visibleCapacity)
Vg reset.
int vgUpdate(VgBackend &be, int clusterCount, int visibleCapacity, int viewW, int viewH)
Vg update.
void vgUploadUniforms(VgBackend &be, const VgUniforms &u)
Vg upload uniforms.
bool vgReadPixels(VgBackend &be, std::vector< uint32_t > &out)
Vg read pixels.
void vgCreate(VgBackend &be)
Vg create.
void vgDestroy(VgBackend &be)
Vg destroy.
void vgUpload(VgBackend &be, const VirtualGeometryAsset &asset)
Vg upload.