载入中...
搜索中...
未找到
CollapseAnimation.cpp
浏览该文件的文档.
1// eve-hot-path
3#include <algorithm>
4#include <bit>
5#include <cmath>
6#include <cstdint>
7#include <filesystem>
8#include <fstream>
9#include <limits>
10#include <sstream>
11#if defined(__linux__)
12#include <fcntl.h>
13#include <unistd.h>
14#include <cerrno>
15#endif
20
21namespace eve::physics {
22using namespace collapse_detail;
23std::string CollapseAnimation::contentKey(std::string_view source) { return bakedAssetContentKey(source); }
24
25namespace {
26constexpr std::streamoff MaxFileBytes = static_cast<std::streamoff>(MaxSamples) * 56 + 16000056 + MaxRecipeBytes + 4;
27void write32(std::ostream& out, std::uint32_t v) {
28 for (unsigned i = 0; i < 4; ++i) out.put(static_cast<char>((v >> (i * 8)) & 255));
29}
30std::uint32_t read32(std::istream& in) {
31 std::uint32_t v = 0;
32 for (unsigned i = 0; i < 4; ++i) {
33 const int c = in.get();
34 if (c < 0) {
35 in.setstate(std::ios::failbit);
36 return 0;
37 }
38 v |= static_cast<std::uint32_t>(c) << (i * 8);
39 }
40 return v;
41}
42void writeFloat(std::ostream& out, float v) { write32(out, std::bit_cast<std::uint32_t>(v)); }
43float readFloat(std::istream& in) { return std::bit_cast<float>(read32(in)); }
44} // namespace
46 if (!frames_.empty())
48 "provenance must be set before capturing any frame",
49 "collapseAnimation"));
51 return Result<void>::failure(invalid("collapse requires metre-space provenance"));
52 auto encoded = recipe.encode();
53 if (!encoded) return Result<void>::failure(encoded.status());
54 recipe_ = std::make_shared<const CollapseBakeRecipe>(recipe);
55 return Result<void>::success();
56}
57std::shared_ptr<const CollapseBakeRecipe> CollapseAnimation::recipe() const noexcept { return recipe_; }
59 auto expectedBytes = expected.encode();
60 if (!expectedBytes) return Result<CollapseAnimation>::failure(expectedBytes.status());
61 auto loaded = load(path);
62 if (!loaded) return loaded;
63 if (!loaded.value().recipe_)
66 "legacy animation has no bake provenance; explicit migration or rebake required", "collapseAnimation"));
67 auto actual = loaded.value().recipe_->encode();
68 if (!actual) return Result<CollapseAnimation>::failure(actual.status());
69 if (actual.value() != expectedBytes.value())
71 DiagnosticCode::Conflict, "bake provenance does not match the expected recipe", "collapseAnimation"));
72 return loaded;
73}
74std::shared_ptr<const FractureGeometry> CollapseAnimation::fragmentGeometry() const noexcept { return geometry_; }
75float CollapseAnimation::duration() const noexcept { return frames_.empty() ? 0 : frames_.back().seconds; }
76int CollapseAnimation::boneCount() const noexcept {
77 return frames_.empty() ? 0 : static_cast<int>(frames_.front().bones.size());
78}
79int CollapseAnimation::frameCount() const noexcept { return static_cast<int>(frames_.size()); }
81 if (!std::isfinite(seconds) || bone < 0 || bone >= boneCount())
82 return Result<BonePresentation>::failure(invalid("invalid sample time or fragment"));
83 auto upper = std::upper_bound(frames_.begin(), frames_.end(), seconds,
84 [](float t, const Frame& f) { return t < f.seconds; });
85 const size_t index = static_cast<size_t>(bone);
86 if (upper == frames_.begin()) return Result<BonePresentation>::success(upper->bones[index]);
87 const auto& a = *(upper - 1);
88 if (upper == frames_.end()) return Result<BonePresentation>::success(a.bones[index]);
89 auto result = a.bones[index];
90 const auto& b = upper->bones[index];
91 const float t = (seconds - a.seconds) / (upper->seconds - a.seconds);
92 result.worldX = std::lerp(result.worldX, b.worldX, t);
93 result.worldY = std::lerp(result.worldY, b.worldY, t);
94 result.worldZ = std::lerp(result.worldZ, b.worldZ, t);
95 const float sign =
96 (result.rotX * b.rotX + result.rotY * b.rotY + result.rotZ * b.rotZ + result.rotW * b.rotW) < 0 ? -1.f : 1.f;
97 result.rotX = std::lerp(result.rotX, sign * b.rotX, t);
98 result.rotY = std::lerp(result.rotY, sign * b.rotY, t);
99 result.rotZ = std::lerp(result.rotZ, sign * b.rotZ, t);
100 result.rotW = std::lerp(result.rotW, sign * b.rotW, t);
101 const float norm = std::sqrt(result.rotX * result.rotX + result.rotY * result.rotY + result.rotZ * result.rotZ +
102 result.rotW * result.rotW);
103 result.rotX /= norm;
104 result.rotY /= norm;
105 result.rotZ /= norm;
106 result.rotW /= norm;
108}
110 if (frames_.empty() || path.empty() || path.find('\0') != std::string_view::npos)
111 return Result<void>::failure(invalid("save requires frames and a nonempty path without NUL"));
112 std::string recipeBytes;
113 if (recipe_) {
114 auto encoded = recipe_->encode();
115 if (!encoded) return Result<void>::failure(encoded.status());
116 recipeBytes = std::move(encoded).takeValue();
117 }
118 std::ostringstream out(std::ios::binary);
119 out.write("EVECOLL1", 8);
120 write32(out, recipe_ ? 4U : 3U);
121 write32(out, static_cast<std::uint32_t>(boneCount()));
122 write32(out, static_cast<std::uint32_t>(frameCount()));
123 write32(out, geometry_ ? static_cast<std::uint32_t>(geometry_->fragments.size()) : 0U);
124 if (recipe_) {
125 write32(out, static_cast<std::uint32_t>(recipeBytes.size()));
126 out.write(recipeBytes.data(), static_cast<std::streamsize>(recipeBytes.size()));
127 }
128 if (geometry_)
129 for (const auto& mesh : geometry_->fragments) {
130 write32(out, static_cast<std::uint32_t>(mesh.positions.size() / 3));
131 write32(out, static_cast<std::uint32_t>(mesh.indices.size() / 3));
132 for (float v : mesh.positions) writeFloat(out, v);
133 for (auto i : mesh.indices) write32(out, i);
134 for (auto tag : mesh.materials) write32(out, tag);
135 }
136 for (const auto& f : frames_) {
137 writeFloat(out, f.seconds);
138 for (const auto& b : f.bones) {
139 for (float v : {b.halfExtentX, b.halfExtentY, b.halfExtentZ, b.worldX, b.worldY, b.worldZ, b.rotX, b.rotY,
140 b.rotZ, b.rotW})
141 writeFloat(out, v);
142 write32(out, static_cast<std::uint32_t>(b.state));
143 write32(out, static_cast<std::uint32_t>(b.clusterId));
144 write32(out, static_cast<std::uint32_t>(b.fractureLevel));
145 }
146 }
147 if (!out) return Result<void>::failure(invalid("animation encoding failed"));
148 auto bytes = std::move(out).str();
150 if (bytes.size() > static_cast<std::size_t>(MaxFileBytes))
151 return Result<void>::failure(invalid("encoded animation exceeds file budget"));
153}
154
156 if (path.empty() || path.find('\0') != std::string_view::npos)
157 return Result<CollapseAnimation>::failure(invalid("load requires a path without NUL"));
158 std::ifstream file(std::filesystem::path(path), std::ios::binary | std::ios::ate);
159 if (!file.is_open()) {
160 std::error_code error;
161 const auto status = std::filesystem::status(std::filesystem::path(path), error);
162 const bool missing =
163 error == std::errc::no_such_file_or_directory || (!error && !std::filesystem::exists(status));
166 missing ? "animation file not found" : "animation file cannot be opened", "collapseAnimation"));
167 }
168 const auto fileBytes = file.tellg();
169 if (fileBytes < 20 || fileBytes > MaxFileBytes)
170 return Result<CollapseAnimation>::failure(invalid("invalid animation file size"));
171 file.seekg(0);
172 std::string encoded(static_cast<std::size_t>(fileBytes), '\0');
173 if (!file.read(encoded.data(), static_cast<std::streamsize>(encoded.size())) || file.peek() != EOF)
174 return Result<CollapseAnimation>::failure(invalid("animation changed or read failed"));
175 std::istringstream in(std::move(encoded), std::ios::binary);
176 const auto encodedView = in.view();
177 std::streamoff bytes = fileBytes;
178 char magic[8];
179 in.read(magic, 8);
180 const auto version = read32(in), bones = read32(in), frames = read32(in);
181 if (std::string(magic, 8) != "EVECOLL1" || (version < 1 || version > 4) || bones == 0 || frames == 0 ||
182 bones > MaxSamples / frames)
183 return Result<CollapseAnimation>::failure(invalid("unsupported schema, counts or trailing data"));
184 if (version >= 3) {
185 if (encodedView.size() < 56 ||
186 contentKey(encodedView.substr(0, encodedView.size() - 32)) != encodedView.substr(encodedView.size() - 32))
187 return Result<CollapseAnimation>::failure(invalid("animation content checksum mismatch"));
188 bytes -= 32;
189 }
191 if (version >= 2) {
192 const auto meshes = read32(in);
193 if (version == 4) {
194 const auto recipeSize = read32(in);
195 const auto position = in.tellg();
196 if (!in || recipeSize == 0 || recipeSize > MaxRecipeBytes || position < 0 || position > bytes ||
197 static_cast<std::streamoff>(recipeSize) > bytes - position)
198 return Result<CollapseAnimation>::failure(invalid("invalid bake provenance size"));
199 auto decoded =
200 CollapseBakeRecipe::decode(encodedView.substr(static_cast<std::size_t>(position), recipeSize));
201 if (!decoded) return Result<CollapseAnimation>::failure(decoded.status());
202 if (decoded.value().coordinates() != BakeCoordinates::MetresRightHandedYUp)
203 return Result<CollapseAnimation>::failure(invalid("collapse requires metre-space provenance"));
204 clip.recipe_ = std::make_shared<const CollapseBakeRecipe>(std::move(decoded).takeValue());
205 in.seekg(static_cast<std::streamoff>(recipeSize), std::ios::cur);
206 }
207 if (meshes != 0 && (meshes != bones || meshes > 4096))
208 return Result<CollapseAnimation>::failure(invalid("mesh count mismatch"));
209 if (meshes) {
211 std::size_t total = 0;
212 for (std::uint32_t m = 0; m < meshes; ++m) {
213 const auto vertices = read32(in), triangles = read32(in);
214 total += 3ULL * vertices + 4ULL * triangles;
215 if (!in || vertices < 4 || vertices > 254 || triangles == 0 || triangles > 2730 || total > 4000000)
216 return Result<CollapseAnimation>::failure(invalid("mesh budget exceeded"));
217 FractureFragment fragment;
218 fragment.positions.resize(3ULL * vertices);
219 fragment.indices.resize(3ULL * triangles);
220 fragment.materials.resize(triangles);
221 for (auto& v : fragment.positions) v = readFloat(in);
222 for (auto& i : fragment.indices) i = read32(in);
223 for (auto& tag : fragment.materials) tag = read32(in);
224 geometry.fragments.push_back(std::move(fragment));
225 }
226 auto valid = geometry.validate();
227 if (!valid) return Result<CollapseAnimation>::failure(valid.status());
228 clip.geometry_ = std::make_shared<const FractureGeometry>(std::move(geometry));
229 }
230 }
231 if (!in ||
232 bytes != in.tellg() + static_cast<std::streamoff>(static_cast<std::uint64_t>(frames) * (4ULL + 52ULL * bones)))
233 return Result<CollapseAnimation>::failure(invalid("truncated animation or trailing bytes"));
234 for (std::uint32_t f = 0; f < frames; ++f) {
235 Frame frame{readFloat(in), {}};
236 if (!std::isfinite(frame.seconds) || (f == 0 ? frame.seconds != 0 : frame.seconds <= clip.duration()))
237 return Result<CollapseAnimation>::failure(invalid("invalid frame time"));
238 if (clip.recipe_) {
239 auto timing = clip.recipe_->validateSampleTime(f, frame.seconds);
240 if (!timing) return Result<CollapseAnimation>::failure(timing.status());
241 }
242 frame.bones.reserve(bones);
243 for (std::uint32_t i = 0; i < bones; ++i) {
245 float* values[] = {&b.halfExtentX, &b.halfExtentY, &b.halfExtentZ, &b.worldX, &b.worldY,
246 &b.worldZ, &b.rotX, &b.rotY, &b.rotZ, &b.rotW};
247 for (auto* v : values) *v = readFloat(in);
248 const auto state = read32(in), cluster = read32(in), level = read32(in);
249 if (state > 2 || cluster > static_cast<std::uint32_t>(std::numeric_limits<int>::max()) ||
250 level > static_cast<std::uint32_t>(std::numeric_limits<int>::max()))
251 return Result<CollapseAnimation>::failure(invalid("invalid fragment metadata"));
252 b.state = static_cast<BoneRuntimeState>(state);
253 b.clusterId = static_cast<int>(cluster);
254 b.fractureLevel = static_cast<int>(level);
255 if (!in || !valid(b)) return Result<CollapseAnimation>::failure(invalid("invalid fragment data"));
256 if (f > 0) {
257 const auto& a = clip.frames_.front().bones[i];
258 if (a.halfExtentX != b.halfExtentX || a.halfExtentY != b.halfExtentY ||
259 a.halfExtentZ != b.halfExtentZ || a.clusterId != b.clusterId || a.fractureLevel != b.fractureLevel)
260 return Result<CollapseAnimation>::failure(invalid("inconsistent fragment topology"));
261 }
262 frame.bones.push_back(b);
263 }
264 clip.frames_.push_back(std::move(frame));
265 }
266 return Result<CollapseAnimation>::success(std::move(clip));
267}
268} // namespace eve::physics
double m[16]
wgpu::PopErrorScopeStatus status
glm::vec4 clip
float v
std::int32_t c
std::vector< Bone > bones
std::array< float, 3 > position
std::uint32_t bone
Poco::JSON::Object::Ptr result
std::uint64_t bytes
bool valid
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
std::vector< TriangleRef > triangles
int level
const std::string * tag
OceanMeshSettings mesh
ssq::Object frame
std::string error
Definition Package.cpp:174
BakeRecipe recipe
float f
std::string path
Definition PlayHost.cpp:111
std::unordered_set< std::string > loaded
Definition Plugins.cpp:24
std::set< std::string > values
std::string file
float t
std::string geometry
ScriptStructure out
std::string_view source
std::array< double, 2 > vertices[3]
uint32_t index
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
Bounded provenance builder for explicit-coordinate baked recordings. @ownership Owns names and conten...
Definition BakeRecipe.h:21
Result< std::string > encode() const
Encode complete provenance canonically, sorting dependency and RNG names. @cost Linear in bounded met...
static Result< BakeRecipe > decode(std::string_view bytes)
Parse a bounded canonical recipe record, rejecting duplicate names and trailing bytes....
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.
static std::string contentKey(std::string_view source)
Stable noncryptographic cache identity over every source byte. Compatibility facade; canonical native...
std::shared_ptr< const FractureGeometry > fragmentGeometry() const noexcept
Shared immutable embedded meshes; empty for v1/box animations. @ownership Return value extends mesh l...
static Result< CollapseAnimation > loadForRecipe(std::string_view path, const CollapseBakeRecipe &expected)
Load only if embedded provenance exactly matches the supplied expected recipe. @cost Linear file vali...
int boneCount() const noexcept
Number of fragments.
Result< void > save(std::string_view path) const
Save a new file; refuses existing paths to preserve previous bakes. @cost Linear in recorded samples,...
float duration() const noexcept
Recorded duration in seconds.
int frameCount() const noexcept
Number of recorded frames.
Result< void > beginBake(const CollapseBakeRecipe &recipe)
Freeze complete provenance before the first recorded frame. @cost Linear in bounded metadata,...
static Result< CollapseAnimation > load(std::string_view path)
Load and validate a file before publishing an owning animation. @cost Linear in file size; perform on...
std::shared_ptr< const CollapseBakeRecipe > recipe() const noexcept
Immutable recorded provenance; null means historical/unidentified recording. @ownership Shared result...
Result< float > readFloat(const Value::Object &object, std::string_view name)
Reads a required finite number representable by float.
Optional physics backend for vehicle mobility and body attach.
Definition Climbing.h:36
std::string bakedAssetContentKey(std::string_view source)
Stable noncryptographic 128-bit content digest, encoded as 32 lowercase hexadecimal bytes....
BoneRuntimeState
Runtime lifecycle for one bone inside a geometry-collection instance.
Result< void > publishBakedAsset(std::string_view path, std::string_view bytes)
Publish complete baked asset bytes atomically without replacing an existing path. @ownership Borrows ...
Presentation snapshot for one bone (world pose + proxy extents).
Owning closed convex fragment in body-local metres; outward triangle winding. Each triangle has mater...
std::vector< std::uint32_t > indices
std::vector< std::uint32_t > materials
Owning, typed mesh payload shared immutably by simulation, clip and renderer. @thread Read-only shari...