载入中...
搜索中...
未找到
FractureRenderer.cpp
浏览该文件的文档.
1#include <algorithm>
2#include <cmath>
3#include <glm/gtc/matrix_transform.hpp>
4#include <glm/gtc/quaternion.hpp>
5#include <glm/gtc/type_ptr.hpp>
6#include "common/Assert.h"
7#include "common/Exception.h"
8#include "graphics/Color.h"
9#include "graphics/Graphics.h"
10#include "graphics/Mesh.h"
17namespace eve::physics {
19 if (groupId < 0 || groupId > 4095 || !std::isfinite(r) || !std::isfinite(g) || !std::isfinite(b) ||
20 !std::isfinite(a) || r < 0 || r > 1 || g < 0 || g > 1 || b < 0 || b > 1 || a < 0 || a > 1)
22 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "group/color out of range", "palette"));
23 groupColors_[groupId] = {r, g, b, a};
25}
26
27void GeometryCollectionRenderer::releaseFragmentMeshes(graphics::Graphics* graphics) {
28 if (graphics)
29 for (auto& batch : fragmentBatches_)
30 if (batch.mesh) {
31 const bool released = graphics->releaseMesh(batch.mesh);
32 EV_ASSERT(released, "prepared mesh ownership changed");
33 if (released) delete batch.mesh;
34 }
35 fragmentBatches_ = {};
36 preparedGeometry_.reset();
37 poseScratch_.clear();
38 boneMatrices_.clear();
39}
41 graphics::Graphics* graphics) {
42 std::vector<int> groups;
43 for (int bone = 0; bone < animation.boneCount(); ++bone) {
44 auto pose = animation.sample(0.f, bone);
45 if (!pose) return eve::Result<void>::failure(pose.status());
46 groups.push_back(pose.value().clusterId);
47 }
48 return prepareGeometry(animation.fragmentGeometry(), graphics, groups);
49}
51 if (!instance_)
53 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "no instance to prepare", "instance"));
54 std::vector<int> groups;
55 for (int bone = 0; bone < instance_->boneCount(); ++bone) {
56 auto pose = instance_->bonePresentation(bone);
57 if (!pose) return eve::Result<void>::failure(pose.status());
58 groups.push_back(pose.value().clusterId);
59 }
60 return prepareGeometry(instance_->fragmentGeometry(), graphics, groups);
61}
62eve::Result<void> GeometryCollectionRenderer::prepareGeometry(std::shared_ptr<const FractureGeometry> geometry,
63 graphics::Graphics* graphics,
64 const std::vector<int>& groups) {
65 if (!graphics)
67 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "graphics required", "graphics"));
68 if (preparedGeometry_ == geometry && meshOwner_ == graphics) return eve::Result<void>::success();
69 if (geometry && groups.size() != geometry->fragments.size())
71 eve::DiagnosticCode::InvalidArgument, "one structural group per fragment required", "groups"));
72 std::vector<FragmentBatch> candidate;
73 std::map<std::pair<int, bool>, std::size_t> batches;
74 auto cleanup = [&] {
75 for (auto& batch : candidate)
76 if (batch.mesh) {
77 const bool released = graphics->releaseMesh(batch.mesh);
78 EV_ASSERT(released, "candidate mesh ownership changed");
79 if (released) delete batch.mesh;
80 batch.mesh = nullptr;
81 }
82 };
83 try {
84 if (geometry)
85 for (std::size_t bone = 0; bone < geometry->fragments.size(); ++bone) {
86 const auto& f = geometry->fragments[bone];
87 for (std::size_t t = 0; t < f.materials.size(); ++t) {
88 const bool interior = f.materials[t] != 0;
89 const int group = interior ? -1 : groups[bone];
90 const auto key = std::make_pair(group, interior);
91 auto found = batches.find(key);
92 if (found == batches.end()) {
93 const auto index = candidate.size();
94 candidate.emplace_back();
95 candidate.back().groupId = group;
96 candidate.back().interior = interior;
97 found = batches.emplace(key, index).first;
98 }
99 auto& batch = candidate[found->second];
100 glm::vec3 points[3];
101 for (int k = 0; k < 3; ++k) {
102 auto id = f.indices[t * 3 + static_cast<std::size_t>(k)];
103 points[k] = {f.positions[3 * id], f.positions[3 * id + 1], f.positions[3 * id + 2]};
104 }
105 const auto n = glm::normalize(glm::cross(points[1] - points[0], points[2] - points[0]));
106 for (auto p : points) {
107 batch.indices.push_back(static_cast<std::uint32_t>(batch.restPositions.size() / 3));
108 batch.bones.push_back(static_cast<std::uint32_t>(bone));
109 batch.restPositions.insert(batch.restPositions.end(), {p.x, p.y, p.z});
110 batch.restNormals.insert(batch.restNormals.end(), {n.x, n.y, n.z});
111 batch.uv.insert(batch.uv.end(), {p.x, p.z});
112 }
113 }
114 }
115 for (auto& batch : candidate) {
116 if (batch.indices.empty()) continue;
117 batch.positions = batch.restPositions;
118 batch.normals = batch.restNormals;
119 batch.mesh = graphics->newMeshFromArrays(batch.positions.data(), batch.normals.data(), batch.uv.data(),
120 static_cast<int>(batch.positions.size() / 3), batch.indices.data(),
121 static_cast<int>(batch.indices.size()));
122 if (!batch.mesh) {
123 cleanup();
125 eve::DiagnosticCode::Failed, "fragment batch allocation failed", "geometry"));
126 }
127 }
128 } catch (const std::exception& error) {
129 cleanup();
132 }
133 // Reserve CPU scratch before publishing GPU ownership so allocation failure is transactional.
134 std::vector<BonePresentation> poses;
135 std::vector<std::array<float, 16>> matrices;
136 try {
137 if (geometry) {
138 poses.reserve(geometry->fragments.size());
139 matrices.resize(geometry->fragments.size());
140 }
141 } catch (const std::exception& error) {
142 cleanup();
145 }
146 std::uint64_t token = forwardToken_;
147 std::uint64_t shadowToken = shadowToken_;
148 try {
149 if (geometry && !token)
151 [this](graphics::Graphics& target, const graphics::Camera3D::Data&, const glm::mat4&, float) {
152 if (!submitted_ || &target != meshOwner_) return;
153 submitted_ = false;
154 auto drawn = drawGeometry(target);
155 if (!drawn) throw eve::Exception("%s", drawn.status().describe().c_str());
156 });
157 if (geometry && !shadowToken)
159 [this](graphics::Graphics& target, const glm::mat4& lightVP, const graphics::Camera3D::Data&) {
160 if (!submitted_ || &target != meshOwner_) return;
161 for (const auto& batch : fragmentBatches_)
162 if (batch.mesh) target.drawMeshShadow(batch.mesh, lightVP, false);
163 });
164 } catch (const std::exception& error) {
166 if (shadowToken != shadowToken_) graphics::RenderSystem3D::removeShadowExtraDrawer(shadowToken);
167 cleanup();
169 eve::Diagnostic::error(eve::DiagnosticCode::Failed, error.what(), "forwardContributor"));
170 }
171 if (geometry && (!token || !shadowToken)) {
173 if (shadowToken != shadowToken_) graphics::RenderSystem3D::removeShadowExtraDrawer(shadowToken);
174 cleanup();
176 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "forward contributor registration failed", "geometry"));
177 }
178 forwardToken_ = token;
179 shadowToken_ = shadowToken;
180 if (meshOwner_ != graphics)
181 releaseOwnedMeshes(meshOwner_);
182 else
183 releaseFragmentMeshes(graphics);
184 meshOwner_ = graphics;
185 preparedGeometry_ = std::move(geometry);
186 fragmentBatches_ = std::move(candidate);
187 poseScratch_ = std::move(poses);
188 boneMatrices_ = std::move(matrices);
190}
195eve::Result<void> GeometryCollectionRenderer::beginAnimationSubmission(const CollapseAnimation& animation) {
196 submitted_ = false;
197 const auto geometry = animation.fragmentGeometry();
198 if (!geometry)
201 "scene submission requires embedded mesh geometry; legacy boxes use drawAnimation inside an active 3D pass",
202 "geometry"));
203 if (geometry != preparedGeometry_ || !forwardToken_ ||
204 static_cast<std::size_t>(animation.boneCount()) != boneMatrices_.size())
206 "prepareAnimation is required before scene submission",
207 "geometry"));
208 poseScratch_.clear();
210}
212 const auto animation = player.animation();
213 auto ready = beginAnimationSubmission(*animation);
214 if (!ready) return ready;
215 for (int i = 0; i < animation->boneCount(); ++i) {
216 auto pose = player.sample(i);
217 if (!pose) return eve::Result<void>::failure(pose.status());
218 poseScratch_.push_back(pose.value());
219 }
220 return finishAnimationSubmission();
221}
223 float x, float y, float z) {
224 auto ready = beginAnimationSubmission(animation);
225 if (!ready) return ready;
226 if (!std::isfinite(seconds) || !std::isfinite(x) || !std::isfinite(y) || !std::isfinite(z))
228 eve::Diagnostic::error(eve::DiagnosticCode::InvalidArgument, "submission values must be finite", "time"));
229 for (int i = 0; i < animation.boneCount(); ++i) {
230 auto pose = animation.sample(seconds, i);
231 if (!pose) return eve::Result<void>::failure(pose.status());
232 auto p = pose.value();
233 p.worldX += x;
234 p.worldY += y;
235 p.worldZ += z;
236 poseScratch_.push_back(p);
237 }
238 return finishAnimationSubmission();
239}
240eve::Result<void> GeometryCollectionRenderer::finishAnimationSubmission() {
241 auto depth = registerDepthContribution();
242 if (!depth) return depth;
243 auto updated = updateGeometry(*meshOwner_);
244 if (!updated) return updated;
245 submitted_ = true;
247}
248eve::Result<void> GeometryCollectionRenderer::updateGeometry(graphics::Graphics& graphics) {
249 if (poseScratch_.size() != boneMatrices_.size())
251 "prepared pose count mismatch", "geometry"));
252 for (std::size_t i = 0; i < poseScratch_.size(); ++i) {
253 const auto& b = poseScratch_[i];
254 const glm::quat q(b.rotW, b.rotX, b.rotY, b.rotZ);
255 const auto m =
256 glm::translate(glm::mat4(1.f), glm::vec3(b.worldX, b.worldY, b.worldZ)) * glm::mat4_cast(glm::normalize(q));
257 std::copy_n(glm::value_ptr(m), 16, boneMatrices_[i].data());
258 }
259 for (auto& batch : fragmentBatches_) {
260 if (!batch.mesh) continue;
261 for (std::size_t i = 0; i < batch.bones.size(); ++i) {
262 const auto& m = boneMatrices_[batch.bones[i]];
263 const auto offset = 3 * i;
264 const float x = batch.restPositions[offset], y = batch.restPositions[offset + 1],
265 z = batch.restPositions[offset + 2];
266 const float nx = batch.restNormals[offset], ny = batch.restNormals[offset + 1],
267 nz = batch.restNormals[offset + 2];
268 for (std::size_t axis = 0; axis < 3; ++axis) {
269 batch.positions[offset + axis] = m[axis] * x + m[4 + axis] * y + m[8 + axis] * z + m[12 + axis];
270 batch.normals[offset + axis] = m[axis] * nx + m[4 + axis] * ny + m[8 + axis] * nz;
271 }
272 }
273 if (!graphics.updateMeshVertices(batch.mesh, batch.positions.data(), batch.normals.data(), batch.uv.data(),
274 static_cast<int>(batch.positions.size() / 3), batch.indices.data(),
275 static_cast<int>(batch.indices.size())))
277 eve::Diagnostic::error(eve::DiagnosticCode::Failed, "fragment batch upload failed", "geometry"));
278 }
280}
281eve::Result<void> GeometryCollectionRenderer::drawGeometry(graphics::Graphics& graphics) {
282 graphics.setMesh3DMaterial(0.f, .85f);
283 graphics.setMesh3DShadowReceive(true);
284 for (const auto& batch : fragmentBatches_) {
285 if (!batch.mesh) continue;
286 // Group palette lookups are typed and bounded by prepared material groups.
287 graphics::Color color = batch.interior ? graphics::Color(interiorR_, interiorG_, interiorB_, interiorA_)
288 : graphics::Color(exteriorR_, exteriorG_, exteriorB_, exteriorA_);
289 if (!batch.interior) {
290 auto found = groupColors_.find(batch.groupId);
291 if (found != groupColors_.end()) {
292 const auto& c = found->second;
293 color = graphics::Color(c[0], c[1], c[2], c[3]);
294 }
295 }
296 graphics.drawMesh(batch.mesh, glm::mat4(1.f), nullptr, color);
297 }
299}
300} // namespace eve::physics
double z
double y
double m[16]
double x
LogicalId target
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
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
tensor::Graph g
Definition GpuGraph.cpp:7
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
double r
std::int32_t c
JointPoint2D axis
size_t offset
std::uint32_t bone
std::string id
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
OceanMeshSettings mesh
uint32_t groups
Definition OnnxGpgpu.cpp:39
std::string error
Definition Package.cpp:174
float f
std::array< std::uint64_t, kPixelChunkSize *kPixelChunkSize > updated
std::shared_ptr< const std::vector< glm::vec2 > > points
float t
bool found
std::string geometry
Graphics * graphics
glm::mat4 lightVP
Definition Shadow.cpp:148
AbilityActivationGroup group
std::uint32_t depth
uint32_t index
static Diagnostic error(DiagnosticCode code, std::string message, std::string path={})
Construct an error diagnostic with the standard error severity.
EVENGINE_API_FOUNDATION public API.
Definition Exception.h:13
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.
static uint64_t addShadowExtraDrawer(ShadowExtraDrawer drawer)
Adds shadow extra drawer.
static uint64_t addForwardExtraDrawer(ForwardExtraDrawer drawer)
Register 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.
Independent clock over a frozen, shared collapse animation. @ownership Owns a shared immutable snapsh...
std::shared_ptr< const CollapseAnimation > animation() const noexcept
Shared immutable clip; returned ownership survives this player's destruction.
Result< BonePresentation > sample(int bone) const
Sample at current time using the clip's interpolation and discrete-state contract.
std::shared_ptr< const FractureGeometry > fragmentGeometry() const noexcept override
Shared immutable geometry; empty for legacy box collections. @ownership Returned shared value keeps g...
int boneCount() const noexcept override
Stable positive fragment count for this sample.
eve::Result< BonePresentation > bonePresentation(int boneIndex) const override
Sample one bone's world pose and proxy extents for presentation.
eve::Result< void > submitPlayback(const CollapsePlayback &player)
Submit this player's placed poses to forward, shadow and depth passes. @ownership Copies samples duri...
eve::Result< void > prepareAnimation(const CollapseAnimation &animation, graphics::Graphics *graphics)
Upload embedded meshes once before baked playback.
eve::Result< void > submitAnimation(const CollapseAnimation &animation, float seconds, float offsetX, float offsetY, float offsetZ)
Queue one sampled mesh animation for the engine's next main forward and CSM shadow passes.
eve::Result< void > prepareInstance(graphics::Graphics *graphics)
Upload the bound live instance geometry before drawing it. @cost Same offline GPU allocation as prepa...
eve::Result< void > preparePlayback(const CollapsePlayback &player, graphics::Graphics *graphics)
Prepare meshes for a frozen player without retaining its clock. @ownership Borrows player during the ...
eve::Result< void > setGroupExteriorColor(int groupId, float r, float g, float b, float a)
Set exterior RGBA for one authored structural group (clusterId).
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
glm::vec4 Color
Render-neutral RGBA color shared by graphics-facing modules.
Definition RenderTypes.h:8
glm::vec4 color