载入中...
搜索中...
未找到
GeometryCollectionRenderer.cpp
浏览该文件的文档.
2
3#include "common/Assert.h"
4#include "graphics/Color.h"
5#include "graphics/Graphics.h"
6#include "graphics/Mesh.h"
10
11#include <glm/gtc/matrix_transform.hpp>
12#include <glm/gtc/quaternion.hpp>
13
14#include <algorithm>
15#include <cmath>
16#include <cstdint>
17#include <vector>
18
19namespace eve::physics {
20namespace {
21
22void appendBox(std::vector<float>& positions, std::vector<float>& normals, std::vector<float>& uv,
23 std::vector<std::uint32_t>& indices, const glm::mat4& model, float hx, float hy, float hz) {
24 struct Face {
25 glm::vec3 n;
26 glm::vec3 a, b, c, d;
27 };
28 const Face faces[] = {
29 {{0, 0, 1}, {-hx, -hy, hz}, {hx, -hy, hz}, {hx, hy, hz}, {-hx, hy, hz}},
30 {{0, 0, -1}, {hx, -hy, -hz}, {-hx, -hy, -hz}, {-hx, hy, -hz}, {hx, hy, -hz}},
31 {{0, 1, 0}, {-hx, hy, hz}, {hx, hy, hz}, {hx, hy, -hz}, {-hx, hy, -hz}},
32 {{0, -1, 0}, {-hx, -hy, -hz}, {hx, -hy, -hz}, {hx, -hy, hz}, {-hx, -hy, hz}},
33 {{1, 0, 0}, {hx, -hy, hz}, {hx, -hy, -hz}, {hx, hy, -hz}, {hx, hy, hz}},
34 {{-1, 0, 0}, {-hx, -hy, -hz}, {-hx, -hy, hz}, {-hx, hy, hz}, {-hx, hy, -hz}},
35 };
36 const float tex[8] = {0.f, 0.f, 1.f, 0.f, 1.f, 1.f, 0.f, 1.f};
37 for (const auto& face : faces) {
38 const std::uint32_t base = static_cast<std::uint32_t>(positions.size() / 3);
39 const glm::vec3 corners[4] = {face.a, face.b, face.c, face.d};
40 const glm::vec3 worldN = glm::normalize(glm::mat3(model) * face.n);
41 for (int i = 0; i < 4; ++i) {
42 const glm::vec4 world = model * glm::vec4(corners[i], 1.f);
43 positions.insert(positions.end(), {world.x, world.y, world.z});
44 normals.insert(normals.end(), {worldN.x, worldN.y, worldN.z});
45 uv.insert(uv.end(), {tex[i * 2], tex[i * 2 + 1]});
46 }
47 indices.insert(indices.end(), {base, base + 1, base + 2, base, base + 2, base + 3});
48 }
49}
50
51glm::mat4 boneModel(const BonePresentation& bone) {
52 const glm::quat rotation(bone.rotW, bone.rotX, bone.rotY, bone.rotZ);
53 glm::mat4 model = glm::translate(glm::mat4(1.f), glm::vec3(bone.worldX, bone.worldY, bone.worldZ));
54 model *= glm::mat4_cast(glm::normalize(rotation));
55 return model;
56}
57
58void clampColor(float& r, float& g, float& b, float& a) {
59 r = std::clamp(r, 0.f, 1.f);
60 g = std::clamp(g, 0.f, 1.f);
61 b = std::clamp(b, 0.f, 1.f);
62 a = std::clamp(a, 0.f, 1.f);
63}
64
65} // namespace
66
69
71 depthRegistration_.reset();
74 releaseOwnedMeshes(meshOwner_);
75}
76
78 instance_ = instance;
79 invalidateSleepBatch(meshOwner_);
80}
81
82void GeometryCollectionRenderer::setExteriorColor(float r, float g, float b, float a) {
83 exteriorR_ = r;
84 exteriorG_ = g;
85 exteriorB_ = b;
86 exteriorA_ = a;
87 clampColor(exteriorR_, exteriorG_, exteriorB_, exteriorA_);
88}
89
90void GeometryCollectionRenderer::setInteriorColor(float r, float g, float b, float a) {
91 interiorR_ = r;
92 interiorG_ = g;
93 interiorB_ = b;
94 interiorA_ = a;
95 clampColor(interiorR_, interiorG_, interiorB_, interiorA_);
96}
97
98void GeometryCollectionRenderer::setSleepColor(float r, float g, float b, float a) {
99 sleepR_ = r;
100 sleepG_ = g;
101 sleepB_ = b;
102 sleepA_ = a;
103 clampColor(sleepR_, sleepG_, sleepB_, sleepA_);
104}
105
106void GeometryCollectionRenderer::releaseOwnedMeshes(graphics::Graphics* graphics) {
107 releaseFragmentMeshes(graphics);
108 if (graphics) {
109 if (sleepBatch_) {
110 const bool released = graphics->releaseMesh(sleepBatch_);
111 EV_ASSERT(released, "sleep mesh ownership changed");
112 if (released) delete sleepBatch_;
113 }
114 if (unitBox_) {
115 const bool released = graphics->releaseMesh(unitBox_);
116 EV_ASSERT(released, "box mesh ownership changed");
117 if (released) delete unitBox_;
118 }
119 }
120 sleepBatch_ = nullptr;
121 unitBox_ = nullptr;
122 meshOwner_ = nullptr;
123 sleepBatchRevision_ = 0;
124 sleepBatchBoneCount_ = 0;
125}
126
127void GeometryCollectionRenderer::invalidateSleepBatch(graphics::Graphics* graphics) {
128 if (graphics && sleepBatch_) {
129 const bool released = graphics->releaseMesh(sleepBatch_);
130 EV_ASSERT(released, "sleep mesh ownership changed");
131 if (released) delete sleepBatch_;
132 }
133 sleepBatch_ = nullptr;
134 sleepBatchRevision_ = 0;
135 sleepBatchBoneCount_ = 0;
136}
137
138void GeometryCollectionRenderer::ensureUnitBox(graphics::Graphics& graphics) {
139 if (meshOwner_ != &graphics) {
140 releaseOwnedMeshes(meshOwner_);
141 meshOwner_ = &graphics;
142 }
143 if (unitBox_) return;
144 std::vector<float> positions;
145 std::vector<float> normals;
146 std::vector<float> uv;
147 std::vector<std::uint32_t> indices;
148 appendBox(positions, normals, uv, indices, glm::mat4(1.f), 1.f, 1.f, 1.f);
149 unitBox_ = graphics.newMeshFromArrays(positions.data(), normals.data(), uv.data(),
150 static_cast<int>(positions.size() / 3), indices.data(),
151 static_cast<int>(indices.size()));
152}
153
154eve::Result<void> GeometryCollectionRenderer::rebuildSleepBatch(graphics::Graphics& graphics) {
155 if (!instance_)
157 eve::DiagnosticCode::InvalidArgument, "geometry-collection renderer has no instance", "instance"));
158 if (meshOwner_ != &graphics) {
159 releaseOwnedMeshes(meshOwner_);
160 meshOwner_ = &graphics;
161 }
162 invalidateSleepBatch(&graphics);
163 std::vector<float> positions;
164 std::vector<float> normals;
165 std::vector<float> uv;
166 std::vector<std::uint32_t> indices;
167 int sleepCount = 0;
168 for (int i = 0; i < instance_->boneCount(); ++i) {
169 auto presentation = instance_->bonePresentation(i);
171 if (presentation.value().state != BoneRuntimeState::Sleeping) continue;
172 appendBox(positions, normals, uv, indices, boneModel(presentation.value()),
173 presentation.value().halfExtentX, presentation.value().halfExtentY,
174 presentation.value().halfExtentZ);
175 ++sleepCount;
176 }
177 sleepBatchBoneCount_ = sleepCount;
178 sleepBatchRevision_ = instance_->sleepBatchRevision();
179 if (sleepCount == 0) return eve::Result<void>::success();
180 sleepBatch_ = graphics.newMeshFromArrays(positions.data(), normals.data(), uv.data(),
181 static_cast<int>(positions.size() / 3), indices.data(),
182 static_cast<int>(indices.size()));
183 if (!sleepBatch_)
185 eve::DiagnosticCode::Failed, "geometry-collection sleep batch mesh allocation failed", "mesh"));
187}
188
190 lastActiveDrawCount_ = 0;
191 lastSleepBatchCount_ = 0;
192 if (!graphics)
194 eve::DiagnosticCode::InvalidArgument, "geometry-collection draw requires Graphics", "graphics"));
195 if (!instance_)
197 eve::DiagnosticCode::InvalidArgument, "geometry-collection renderer has no instance", "instance"));
198 if (!instance_->hasLiveWorld())
200 eve::DiagnosticCode::StaleHandle, "geometry-collection world is gone", "world"));
201
202 if (auto geometry = instance_->fragmentGeometry()) {
203 if (preparedGeometry_ != geometry || meshOwner_ != graphics)
205 "prepareInstance is required before mesh draws",
206 "geometry"));
207 poseScratch_.clear();
208 for (int i = 0; i < instance_->boneCount(); ++i) {
209 auto pose = instance_->bonePresentation(i);
210 if (!pose) return eve::Result<void>::failure(pose.status());
211 poseScratch_.push_back(pose.value());
212 ++lastActiveDrawCount_;
213 }
214 auto updated = updateGeometry(*graphics);
215 if (!updated) return updated;
216 return drawGeometry(*graphics);
217 }
218 ensureUnitBox(*graphics);
219 if (!unitBox_)
221 eve::DiagnosticCode::Failed, "geometry-collection unit box mesh allocation failed", "mesh"));
222
223 if (sleepBatchRevision_ != instance_->sleepBatchRevision() ||
224 (sleepBatch_ == nullptr && instance_->sleepBatchRevision() != 0)) {
225 auto rebuilt = rebuildSleepBatch(*graphics);
226 if (!rebuilt) return rebuilt;
227 }
228
229 for (int i = 0; i < instance_->boneCount(); ++i) {
230 auto presentation = instance_->bonePresentation(i);
232 const auto& bone = presentation.value();
233 if (bone.state == BoneRuntimeState::Sleeping) continue;
234 glm::mat4 model = boneModel(bone);
235 model = glm::scale(model, glm::vec3(bone.halfExtentX, bone.halfExtentY, bone.halfExtentZ));
236 const bool detached = bone.state == BoneRuntimeState::Detached;
237 const graphics::Color tint(detached ? interiorR_ : exteriorR_, detached ? interiorG_ : exteriorG_,
238 detached ? interiorB_ : exteriorB_, detached ? interiorA_ : exteriorA_);
239 graphics->drawMesh(unitBox_, model, nullptr, tint);
240 ++lastActiveDrawCount_;
241 }
242
243 if (sleepBatch_) {
244 graphics->drawMesh(sleepBatch_, glm::mat4(1.f), nullptr,
245 graphics::Color(sleepR_, sleepG_, sleepB_, sleepA_));
246 lastSleepBatchCount_ = sleepBatchBoneCount_;
247 }
249}
250
252 graphics::Graphics* graphics, float seconds, float offsetX,
253 float offsetY, float offsetZ) {
254 if (!graphics || animation.boneCount() == 0 || !std::isfinite(seconds) || !std::isfinite(offsetX) ||
255 !std::isfinite(offsetY) || !std::isfinite(offsetZ))
257 "invalid animation draw arguments", "animation"));
258 const auto geometry = animation.fragmentGeometry();
259 if (geometry && (preparedGeometry_ != geometry || meshOwner_ != graphics))
261 "prepareAnimation is required before mesh playback",
262 "geometry"));
263 if (!geometry) ensureUnitBox(*graphics);
264 if (!geometry && !unitBox_)
266 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "box allocation failed", "mesh"));
267 if (geometry) poseScratch_.clear();
268 for (int i = 0; i < animation.boneCount(); ++i) {
269 auto sampled = animation.sample(seconds, i);
270 if (!sampled) return eve::Result<void>::failure(sampled.status());
271 auto bone = sampled.value();
272 bone.worldX += offsetX;
273 bone.worldY += offsetY;
274 bone.worldZ += offsetZ;
275 if (geometry) {
276 poseScratch_.push_back(bone);
277 continue;
278 }
279 auto model = glm::scale(boneModel(bone), glm::vec3(bone.halfExtentX, bone.halfExtentY, bone.halfExtentZ));
280 graphics->drawMesh(unitBox_, model, nullptr, graphics::Color(exteriorR_, exteriorG_, exteriorB_, exteriorA_));
281 }
282 if (geometry) {
283 auto updated = updateGeometry(*graphics);
284 if (!updated) return updated;
285 return drawGeometry(*graphics);
286 }
288}
289} // namespace eve::physics
EVEngine assertion entry point, backed by zeroerr.
#define EV_ASSERT(cond,...)
Assert an internal engine invariant (state that must always hold).
Definition Assert.h:37
eve::EntitySpatialPose pose
float uv
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec4 tint
glm::vec3 n
Definition Grass.cpp:63
double r
std::vector< std::uint32_t > indices
std::vector< float > normals
std::vector< float > positions
std::int32_t c
std::array< float, 4 > rotation
std::uint32_t bone
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::unique_ptr< DeformMeshPresentation > presentation
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
float d
glm::mat4 model
Value::Array corners
std::string geometry
Graphics * graphics
float offsetX
float offsetY
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
Move-only operation result carrying either a value or Status.
Definition Result.h:176
static Result success(T value)
Construct a successful result owning value.
Definition Result.h:185
static Result failure(Status status)
Construct a failed result from a structured status.
Definition Result.h:196
static void removeShadowExtraDrawer(uint64_t token)
Remove one shadow callback before destroying its captured state.
static void removeForwardExtraDrawer(uint64_t token)
Unregister a main forward-pass contributor.
Owning, solver-independent baked rigid-fragment animation within Physics. @ownership Owns all samples...
Result< BonePresentation > sample(float seconds, int bone) const
Sample a fragment, clamping time to endpoints; linear translation and shortest quaternion nlerp.
std::shared_ptr< const FractureGeometry > fragmentGeometry() const noexcept
Shared immutable embedded meshes; empty for v1/box animations. @ownership Return value extends mesh l...
int boneCount() const noexcept
Number of fragments.
Runtime owner of bone state, connection strain, and PhysicsLink bindings.
std::shared_ptr< const FractureGeometry > fragmentGeometry() const noexcept override
Shared immutable geometry; empty for legacy box collections. @ownership Returned shared value keeps g...
std::uint64_t sleepBatchRevision() const noexcept
Monotonic revision bumped when any bone enters Sleeping (for batch rebuild).
int boneCount() const noexcept override
Stable positive fragment count for this sample.
bool hasLiveWorld() const noexcept
Whether the owning world handle still resolves.
eve::Result< BonePresentation > bonePresentation(int boneIndex) const override
Sample one bone's world pose and proxy extents for presentation.
void setInteriorColor(float r, float g, float b, float a)
Cut-face RGBA; also used for Detached legacy box bones.
void setExteriorColor(float r, float g, float b, float a)
Exterior-face RGBA; also used for Attached legacy box bones.
eve::Result< void > draw(graphics::Graphics *graphics)
Synchronize caches and draw all bones into the current 3D frame.
GeometryCollectionRenderer(GeometryCollectionInstance *instance) noexcept
Construct a renderer that borrows an instance.
void setSleepColor(float r, float g, float b, float a)
Sleeping-batch RGBA.
eve::Result< void > drawAnimation(const CollapseAnimation &animation, graphics::Graphics *graphics, float seconds, float offsetX, float offsetY, float offsetZ)
Draw a baked animation without a live physics instance.
void setInstance(GeometryCollectionInstance *instance)
Replace the borrowed instance; null disables drawing. @ownership Does not take ownership of instance....
~GeometryCollectionRenderer()
Geometry collection renderer.
eve::Color Color
RGBA color used by every graphics draw call. Lives inside eve::graphics so including a graphics heade...
Definition Color.h:13
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
void appendBox(MeshBuild &mesh, V3 center, V3 side, V3 up, V3 forward, float hx, float hy, float hz, RoadMaterial material)
Module-private road bake implementation helper.
Definition RoadBake.cpp:402