载入中...
搜索中...
未找到
GltfDecode.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <bit>
5#include <cmath>
6#include <utility>
8
10const Value* member(const Value::Object& object, std::string_view name) {
11 const auto found = object.find(std::string(name));
12 return found == object.end() ? nullptr : &found->second;
13}
14
15Result<std::uint64_t> unsignedValue(const Value* value, std::string path, bool required, std::uint64_t fallback) {
16 if (!value && !required) return Result<std::uint64_t>::success(fallback);
17 if (!value || !value->isInt64() || value->asInt() < 0)
19 "glTF field must be a non-negative integer",
20 std::move(path), {}, "asset.import"));
21 return Result<std::uint64_t>::success(static_cast<std::uint64_t>(value->asInt()));
22}
23
24std::uint32_t little32(std::span<const std::uint8_t> bytes, std::size_t offset) {
25 return std::uint32_t(bytes[offset]) | (std::uint32_t(bytes[offset + 1]) << 8) |
26 (std::uint32_t(bytes[offset + 2]) << 16) | (std::uint32_t(bytes[offset + 3]) << 24);
27}
28
29void put32(std::vector<std::uint8_t>& bytes, std::uint32_t value) {
30 for (unsigned shift = 0; shift != 32; shift += 8) bytes.push_back(static_cast<std::uint8_t>(value >> shift));
31}
32
33void putFloat(std::vector<std::uint8_t>& bytes, float value) { put32(bytes, std::bit_cast<std::uint32_t>(value)); }
34
35
37 if (request.documentBytes.empty() || request.documentBytes.size() > request.limits.maximumSourceBytes)
39 DiagnosticCode::InvalidArgument, "glTF document size is outside limits", {}, {}, "asset.import"));
40 std::string json;
41 std::vector<std::uint8_t> binary;
42 const auto bytes = std::span<const std::uint8_t>(request.documentBytes);
43 if (bytes.size() >= 12 && little32(bytes, 0) == 0x46546c67) {
44 if (little32(bytes, 4) != 2 || little32(bytes, 8) != bytes.size() || bytes.size() < 20)
46 Diagnostic::error(DiagnosticCode::ParseError, "GLB header is invalid", {}, {}, "asset.import"));
47 std::size_t cursor = 12;
48 const std::uint32_t jsonSize = little32(bytes, cursor);
49 const std::uint32_t jsonType = little32(bytes, cursor + 4);
50 cursor += 8;
51 if (jsonType != 0x4e4f534a || jsonSize > bytes.size() - cursor)
53 Diagnostic::error(DiagnosticCode::ParseError, "GLB JSON chunk is invalid", {}, {}, "asset.import"));
54 json.assign(reinterpret_cast<const char*>(bytes.data() + cursor), jsonSize);
55 while (!json.empty() && (json.back() == ' ' || json.back() == '\0')) json.pop_back();
56 cursor += jsonSize;
57 if (cursor < bytes.size()) {
58 if (bytes.size() - cursor < 8)
60 DiagnosticCode::ParseError, "GLB trailing chunk is truncated", {}, {}, "asset.import"));
61 const std::uint32_t binarySize = little32(bytes, cursor);
62 const std::uint32_t binaryType = little32(bytes, cursor + 4);
63 cursor += 8;
64 if (binaryType != 0x004e4942 || binarySize > bytes.size() - cursor || cursor + binarySize != bytes.size())
66 Diagnostic::error(DiagnosticCode::ParseError, "GLB BIN chunk is invalid", {}, {}, "asset.import"));
67 binary.assign(bytes.begin() + cursor, bytes.end());
68 }
69 } else {
70 json.assign(request.documentBytes.begin(), request.documentBytes.end());
71 }
72 auto parsed = Value::fromJson(json);
73 if (!parsed) return Result<Document>::failure(parsed.status());
74 return Result<Document>::success({std::move(parsed).takeValue(), std::move(binary)});
75}
76
77bool safeUri(std::string_view uri, const AssetImportLimits& limits) {
78 if (uri.empty() || uri.size() > limits.maximumStringBytes || uri.front() == '/' ||
79 uri.find('\\') != std::string_view::npos || uri.starts_with("data:") || uri.find(':') != std::string_view::npos)
80 return false;
81 std::size_t start = 0;
82 for (std::size_t index = 0; index <= uri.size(); ++index) {
83 if (index != uri.size() && uri[index] != '/') continue;
84 const auto segment = uri.substr(start, index - start);
85 if (segment.empty() || segment == "." || segment == "..") return false;
86 start = index + 1;
87 }
88 return true;
89}
90
93 const Value* buffersValue = member(root, "buffers");
94 const auto* buffers = buffersValue ? buffersValue->getIf<Value::Array>() : nullptr;
95 if (!buffers || buffers->empty())
97 DiagnosticCode::ParseError, "glTF buffers are required", "$.buffers", {}, "asset.import"));
98 std::vector<std::span<const std::uint8_t>> result;
99 result.reserve(buffers->size());
100 std::uint64_t totalBytes = 0;
101 for (std::size_t index = 0; index < buffers->size(); ++index) {
102 const auto* object = (*buffers)[index].getIf<Value::Object>();
103 if (!object)
105 Diagnostic::error(DiagnosticCode::ParseError, "glTF buffer must be an object", {}, {}, "asset.import"));
106 auto declared =
107 unsignedValue(member(*object, "byteLength"), "$.buffers[" + std::to_string(index) + "].byteLength");
108 if (!declared) return Result<std::vector<std::span<const std::uint8_t>>>::failure(declared.status());
109 std::span<const std::uint8_t> data;
110 const Value* uriValue = member(*object, "uri");
111 if (uriValue) {
112 if (!uriValue->isString() || !safeUri(uriValue->asString(), request.limits))
114 Diagnostic::error(DiagnosticCode::Unsupported, "external glTF buffer URI is unsafe or unsupported",
115 {}, {}, "asset.import"));
116 const auto found = request.externalResources.find(uriValue->asString());
117 if (found == request.externalResources.end())
119 Diagnostic::error(DiagnosticCode::NotFound, "external glTF buffer was not supplied",
120 uriValue->asString(), {}, "asset.import"));
121 data = found->second;
122 } else {
123 if (index != 0 || document.binaryChunk.empty())
125 Diagnostic::error(DiagnosticCode::ParseError, "buffer without URI requires the first GLB BIN chunk",
126 {}, {}, "asset.import"));
127 data = document.binaryChunk;
128 }
129 if (declared.value() > data.size())
131 DiagnosticCode::ParseError, "glTF buffer is shorter than byteLength", {}, {}, "asset.import"));
132 if (declared.value() > request.limits.maximumSourceBytes ||
133 totalBytes > request.limits.maximumSourceBytes - declared.value())
135 DiagnosticCode::InvalidArgument, "glTF buffer budget is exceeded", {}, {}, "asset.import"));
136 totalBytes += declared.value();
137 result.push_back(data.first(static_cast<std::size_t>(declared.value())));
138 }
139 return Result<std::vector<std::span<const std::uint8_t>>>::success(std::move(result));
140}
141
142
143std::uint32_t componentSize(std::uint32_t type) {
144 if (type == 5120 || type == 5121) return 1;
145 if (type == 5122 || type == 5123) return 2;
146 if (type == 5125 || type == 5126) return 4;
147 return 0;
148}
149
150Result<Accessor> accessorAt(const Value::Object& root, const std::vector<std::span<const std::uint8_t>>& buffers,
151 std::uint64_t accessorIndex, const AssetImportLimits& limits) {
152 const auto* accessors = member(root, "accessors") ? member(root, "accessors")->getIf<Value::Array>() : nullptr;
153 const auto* views = member(root, "bufferViews") ? member(root, "bufferViews")->getIf<Value::Array>() : nullptr;
154 if (!accessors || !views || accessorIndex >= accessors->size())
156 Diagnostic::error(DiagnosticCode::ParseError, "glTF accessor index is invalid", {}, {}, "asset.import"));
157 const auto* object = (*accessors)[accessorIndex].getIf<Value::Object>();
158 if (!object || member(*object, "sparse"))
160 DiagnosticCode::Unsupported, "sparse or malformed glTF accessor is unsupported", {}, {}, "asset.import"));
161 auto viewIndex = unsignedValue(member(*object, "bufferView"), "accessor.bufferView");
162 auto count = unsignedValue(member(*object, "count"), "accessor.count");
163 auto component = unsignedValue(member(*object, "componentType"), "accessor.componentType");
164 auto accessorOffset = unsignedValue(member(*object, "byteOffset"), "accessor.byteOffset", false, 0);
165 if (!viewIndex || !count || !component || !accessorOffset)
167 Diagnostic::error(DiagnosticCode::ParseError, "glTF accessor fields are invalid", {}, {}, "asset.import"));
168 if (viewIndex.value() >= views->size() || count.value() == 0 ||
169 count.value() > std::max(limits.maximumVerticesPerPrimitive, limits.maximumIndicesPerPrimitive))
171 Diagnostic::error(DiagnosticCode::InvalidArgument, "glTF accessor exceeds limits", {}, {}, "asset.import"));
172 const Value* typeValue = member(*object, "type");
173 if (!typeValue || !typeValue->isString())
175 Diagnostic::error(DiagnosticCode::ParseError, "glTF accessor type is missing", {}, {}, "asset.import"));
176 std::uint32_t components = 0;
177 if (typeValue->asString() == "SCALAR")
178 components = 1;
179 else if (typeValue->asString() == "VEC2")
180 components = 2;
181 else if (typeValue->asString() == "VEC3")
182 components = 3;
183 else if (typeValue->asString() == "VEC4")
184 components = 4;
185 else if (typeValue->asString() == "MAT4")
186 components = 16;
187 else
189 DiagnosticCode::Unsupported, "glTF accessor shape is unsupported", {}, {}, "asset.import"));
190 const auto* view = (*views)[viewIndex.value()].getIf<Value::Object>();
191 if (!view)
193 Diagnostic::error(DiagnosticCode::ParseError, "glTF bufferView is malformed", {}, {}, "asset.import"));
194 auto bufferIndex = unsignedValue(member(*view, "buffer"), "bufferView.buffer");
195 auto viewOffset = unsignedValue(member(*view, "byteOffset"), "bufferView.byteOffset", false, 0);
196 auto viewLength = unsignedValue(member(*view, "byteLength"), "bufferView.byteLength");
197 auto byteStride = unsignedValue(member(*view, "byteStride"), "bufferView.byteStride", false, 0);
198 if (!bufferIndex || !viewOffset || !viewLength || !byteStride || bufferIndex.value() >= buffers.size())
200 DiagnosticCode::ParseError, "glTF bufferView fields are invalid", {}, {}, "asset.import"));
201 const std::uint32_t elementSize = componentSize(static_cast<std::uint32_t>(component.value())) * components;
202 const std::uint64_t stride = byteStride.value() == 0 ? elementSize : byteStride.value();
203 if (elementSize == 0 || stride < elementSize || stride > 252 ||
204 viewOffset.value() > buffers[bufferIndex.value()].size() ||
205 viewLength.value() > buffers[bufferIndex.value()].size() - viewOffset.value() ||
206 accessorOffset.value() > viewLength.value())
208 Diagnostic::error(DiagnosticCode::ParseError, "glTF accessor layout is invalid", {}, {}, "asset.import"));
209 const std::uint64_t required = (count.value() - 1) * stride + elementSize;
210 if (required > viewLength.value() - accessorOffset.value())
212 Diagnostic::error(DiagnosticCode::ParseError, "glTF accessor range is truncated", {}, {}, "asset.import"));
213 const auto* normalized = member(*object, "normalized");
214 if (normalized && !normalized->isBool())
216 DiagnosticCode::ParseError, "glTF normalized flag must be boolean", {}, {}, "asset.import"));
218 {buffers[bufferIndex.value()], static_cast<std::size_t>(viewOffset.value() + accessorOffset.value()),
219 static_cast<std::size_t>(stride), static_cast<std::uint32_t>(count.value()),
220 static_cast<std::uint32_t>(component.value()), components, normalized && normalized->asBool()});
221}
222
223Result<float> readFloat(const Accessor& accessor, std::uint32_t element, std::uint32_t component) {
224 if (accessor.componentType != 5126 || accessor.normalized || element >= accessor.count ||
225 component >= accessor.components)
227 DiagnosticCode::Unsupported, "mesh attribute must use FLOAT components", {}, {}, "asset.import"));
228 const std::size_t offset = accessor.offset + std::size_t(element) * accessor.stride + component * 4;
229 const float value = std::bit_cast<float>(little32(accessor.buffer, offset));
230 if (!std::isfinite(value))
232 DiagnosticCode::ParseError, "mesh attribute contains non-finite values", {}, {}, "asset.import"));
234}
235
236Result<std::uint32_t> readIndex(const Accessor& accessor, std::uint32_t element) {
237 if (accessor.components != 1)
239 Diagnostic::error(DiagnosticCode::ParseError, "index accessor must be SCALAR", {}, {}, "asset.import"));
240 const std::size_t offset = accessor.offset + std::size_t(element) * accessor.stride;
241 if (accessor.componentType == 5121) return Result<std::uint32_t>::success(accessor.buffer[offset]);
242 if (accessor.componentType == 5123)
243 return Result<std::uint32_t>::success(std::uint32_t(accessor.buffer[offset]) |
244 (std::uint32_t(accessor.buffer[offset + 1]) << 8));
245 if (accessor.componentType == 5125) return Result<std::uint32_t>::success(little32(accessor.buffer, offset));
247 Diagnostic::error(DiagnosticCode::Unsupported, "indices must use UNSIGNED_BYTE, UNSIGNED_SHORT or UNSIGNED_INT",
248 {}, {}, "asset.import"));
249}
250
251} // namespace eve::asset_import::gltf
Duration start
int root
Definition AnimSmr.cpp:119
std::size_t cursor
std::string name
Definition ECS.cpp:154
const GltfImportRequest & request
size_t offset
bool required
Poco::JSON::Object::Ptr result
std::uint64_t bytes
OceanSprayView view
std::string path
Definition PlayHost.cpp:111
std::string uri
Object::Ptr value
bool found
std::string element
int count
float(ui::Theme::* member)[4]
const AssetImportLimits & limits
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
The canonical owning dynamic value used by data-facing protocols.
Definition Value.h:31
const std::string & asString() const
Return the string payload; the caller must have checked the kind.
Definition Value.cpp:207
static Result< Value > fromJson(std::string_view json)
Parse one strict JSON value into an owning Value.
Definition Value.cpp:177
std::map< std::string, Value > Object
Definition Value.h:34
bool isString() const noexcept
Return true when this value is a string.
Definition Value.h:106
std::vector< Value > Array
Definition Value.h:33
const T * getIf() const noexcept
Return a typed pointer, or nullptr when the kind differs.
Definition Value.h:209
Value * find(const std::string &key) noexcept
Return an object member, or nullptr when absent.
Definition Value.cpp:244
Result< Accessor > accessorAt(const Value::Object &root, const std::vector< std::span< const std::uint8_t > > &buffers, std::uint64_t accessorIndex, const AssetImportLimits &limits)
Validate an accessor retaining only buffer spans borrowed for this import.
Result< float > readFloat(const Accessor &accessor, std::uint32_t element, std::uint32_t component)
Read one bounded finite FLOAT component.
void put32(std::vector< std::uint8_t > &bytes, std::uint32_t value)
Append little-endian uint32 to owned storage.
Result< std::vector< std::span< const std::uint8_t > > > resolveBuffers(const Value::Object &root, const Document &document, const GltfImportRequest &request)
Resolve immutable spans borrowed from document/request; both must outlive their use.
Result< std::uint64_t > unsignedValue(const Value *value, std::string path, bool required, std::uint64_t fallback)
Validate an optional integer field. @ownership Borrowed nullable field owned by the input document....
std::uint32_t little32(std::span< const std::uint8_t > bytes, std::size_t offset)
Read a uint32 after the caller has bounded the byte range.
Result< Document > parseDocument(const GltfImportRequest &request)
Parse a bounded document into an owning result.
Result< std::uint32_t > readIndex(const Accessor &accessor, std::uint32_t element)
Read one bounded unsigned scalar index.
std::uint32_t componentSize(std::uint32_t type)
Return encoded component byte size, or zero for an unknown type.
bool safeUri(std::string_view uri, const AssetImportLimits &limits)
void putFloat(std::vector< std::uint8_t > &bytes, float value)
Append IEEE FLOAT to owned storage.
Parser and allocation budgets applied to untrusted importer inputs.
Untrusted .gltf/.glb input plus explicitly supplied external URI bytes.
Borrowed validated accessor; its source document/resources must outlive synchronous reads.
Definition GltfDecode.h:13
std::span< const std::uint8_t > buffer
Definition GltfDecode.h:14
Owning parsed document; keep alive while resolved buffer spans are used.
Definition GltfDecode.h:8
std::vector< std::uint8_t > binaryChunk
Definition GltfDecode.h:10