载入中...
搜索中...
未找到
LDrawImporter.cpp
浏览该文件的文档.
2
3#include <algorithm>
4#include <charconv>
5#include <cmath>
6#include <locale>
7#include <set>
8#include <sstream>
9
10namespace eve::asset_import {
11namespace {
12using Point = std::array<double, 3>;
13using Matrix = std::array<double, 12>;
14constexpr Matrix identity{1, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0};
15
16std::string trim(std::string text) {
17 const auto first = text.find_first_not_of(" \t\r");
18 if (first == std::string::npos) return {};
19 return text.substr(first, text.find_last_not_of(" \t\r") - first + 1);
20}
21std::string pathKey(std::string text) {
22 std::replace(text.begin(), text.end(), '\\', '/');
23 if (text.empty() || text.front() == '/' || text.find(':') != std::string::npos) return {};
24 std::string out;
25 std::istringstream stream(text);
26 std::string component;
27 while (std::getline(stream, component, '/')) {
28 if (component == ".." || component.empty()) return {};
29 if (component == ".") continue;
30 for (char& c : component)
31 if (c >= 'A' && c <= 'Z') c = char(c - 'A' + 'a');
32 if (!out.empty()) out += '/';
33 out += component;
34 }
35 return out;
36}
37Point transform(const Matrix& m, const Point& p) {
38 return {m[0] * p[0] + m[1] * p[1] + m[2] * p[2] + m[9], m[3] * p[0] + m[4] * p[1] + m[5] * p[2] + m[10],
39 m[6] * p[0] + m[7] * p[1] + m[8] * p[2] + m[11]};
40}
41Matrix compose(const Matrix& parent, const Matrix& child) {
42 Matrix out{};
43 for (std::size_t row = 0; row < 3; ++row)
44 for (std::size_t column = 0; column < 3; ++column)
45 for (std::size_t k = 0; k < 3; ++k) out[row * 3 + column] += parent[row * 3 + k] * child[k * 3 + column];
46 const auto translation = transform(parent, {child[9], child[10], child[11]});
47 for (std::size_t i = 0; i < 3; ++i) out[9 + i] = translation[i];
48 return out;
49}
50std::optional<unsigned> integer(std::string_view text) {
51 unsigned value = 0;
52 int base = 10;
53 if (text.starts_with("0x") || text.starts_with("0X")) {
54 text.remove_prefix(2);
55 base = 16;
56 }
57 const auto parsed = std::from_chars(text.data(), text.data() + text.size(), value, base);
58 if (text.empty() || parsed.ec != std::errc{} || parsed.ptr != text.data() + text.size()) return {};
59 return value;
60}
61double linear(unsigned byte) {
62 const double value = double(byte) / 255;
63 return value <= 0.04045 ? value / 12.92 : std::pow((value + 0.055) / 1.055, 2.4);
64}
65std::array<double, 4> rgba(unsigned rgb, double alpha = 1) {
66 return {linear((rgb >> 16) & 255), linear((rgb >> 8) & 255), linear(rgb & 255), alpha};
67}
68struct Colour {
69 std::array<double, 4> value;
70 std::string key;
71};
72struct ColourScope {
73 const ColourScope* parent = nullptr;
74 std::map<unsigned, Colour> definitions;
75};
76
77class Decoder {
78public:
79 explicit Decoder(const LDrawImportRequest& request) : request_(request) {
80 constexpr unsigned rgb[] = {0x05131d, 0x0055bf, 0x237841, 0x008f9b, 0xc91a09, 0xc870a0, 0x583927, 0x9ba19d,
81 0x6d6e5c, 0xb4d2e3, 0x4b9f4a, 0x55a5af, 0xf2705e, 0xfc97ac, 0xf2cd37, 0xffffff};
82 for (unsigned i = 0; i < 16; ++i) palette_[i] = {rgba(rgb[i]), "colour-" + std::to_string(i)};
83 }
84 Result<PreparedAssetImport> run() {
85 auto indexed = index();
86 if (!indexed) return Result<PreparedAssetImport>::failure(indexed.status());
87 std::string root = pathKey(request_.sourceName);
88 if (const auto found = firstSections_.find(root); found != firstSections_.end()) root = found->second;
89 auto expanded = expand(root, identity, palette_.at(7), false, 0, nullptr);
90 if (!expanded) return Result<PreparedAssetImport>::failure(expanded.status());
91 if (edgeLines_)
92 findings_.push_back(
93 {request_.sourceName, "LDraw.edgeLines", ImportDisposition::Unsupported,
94 std::to_string(edgeLines_) + " line/conditional-line records are retained in source, not rendered"});
95 findings_.push_back({request_.sourceName, "LDraw.geometry", ImportDisposition::Baked,
96 "part transforms baked; 1 LDU = 0.4 mm; colours mapped to linear PBR base colour; "
97 "connectivity not inferred"});
98 return structured_detail::packageModel(request_.package, request_.sourceName, "ldraw", std::move(parts_),
99 usedSources_, std::move(findings_), request_.limits);
100 }
101
102private:
103 const LDrawImportRequest& request_;
104 std::map<std::string, std::vector<std::string>> documents_;
105 std::map<std::string, std::string> firstSections_;
106 std::map<std::string, std::string> owners_;
107 std::map<std::string, std::vector<std::uint8_t>> usedSources_;
108 std::map<unsigned, Colour> palette_;
109 std::map<std::string, structured_detail::MeshPart> parts_;
110 std::set<std::string> active_;
111 std::vector<ImportFinding> findings_;
112 std::uint64_t expandedLines_ = 0, edgeLines_ = 0, vertices_ = 0;
113
114 Result<void> fail(std::string message, std::string path, DiagnosticCode code = DiagnosticCode::ParseError) const {
116 Diagnostic::error(code, std::move(message), std::move(path), {}, "asset.import.ldraw"));
117 }
118 Result<void> index() {
119 std::uint64_t total = 0, lines = 0;
120 if (request_.files.size() > request_.limits.maximumAssets || request_.maximumDepth == 0 ||
121 request_.maximumDepth > 256 || request_.maximumExpandedLines == 0)
122 return fail("invalid LDraw source/depth budget", request_.sourceName, DiagnosticCode::InvalidArgument);
123 for (const auto& [name, bytes] : request_.files) {
124 if (bytes.size() > request_.limits.maximumSourceBytes - total)
125 return fail("source byte budget exceeded", name, DiagnosticCode::InvalidArgument);
126 total += bytes.size();
127 const auto owner = pathKey(name);
128 if (owner.empty() || owner.size() > request_.limits.maximumStringBytes || owners_.contains(owner))
129 return fail("invalid or duplicate case-insensitive source name", name);
130 if (std::find(bytes.begin(), bytes.end(), 0) != bytes.end()) return fail("NUL in LDraw source", name);
131 std::string current = owner;
132 std::istringstream stream(std::string(bytes.begin(), bytes.end()));
133 std::string line;
134 bool section = false, closed = false;
135 owners_[owner] = name;
136 while (std::getline(stream, line)) {
137 if (++lines > request_.maximumExpandedLines || line.size() > request_.limits.maximumStringBytes)
138 return fail("source line budget exceeded", name, DiagnosticCode::InvalidArgument);
139 line = trim(std::move(line));
140 if (line.starts_with("\xEF\xBB\xBF")) line.erase(0, 3);
141 if (line.starts_with("0 FILE ")) {
142 current = pathKey(trim(line.substr(7)));
143 if (!section) documents_.erase(owner); // Header comments are not a second MPD document.
144 if (current.empty() || documents_.contains(current))
145 return fail("duplicate/invalid MPD FILE name", name);
146 if (!section) firstSections_[owner] = current;
147 section = true;
148 closed = false;
149 documents_[current] = {};
150 owners_[current] = name;
151 } else if (line == "0 NOFILE") {
152 if (!section) return fail("NOFILE without FILE", name);
153 closed = true;
154 } else if (!closed) {
155 documents_[current].push_back(line);
156 }
157 if (owner == "ldconfig.ldr" && line.starts_with("0 !COLOUR ")) {
158 auto color = readColour(line, name, palette_, {});
159 if (!color) return color;
160 usedSources_.try_emplace(name, bytes);
161 }
162 }
163 if (documents_.size() > request_.limits.maximumAssets) return fail("MPD section budget exceeded", name);
164 }
165 return Result<void>::success();
166 }
167 Result<void> readColour(const std::string& line, const std::string& name, std::map<unsigned, Colour>& definitions,
168 const std::string& suffix) {
169 std::istringstream stream(line);
170 std::string token, codeText, valueText, edgeText, alphaText = "255";
171 while (stream >> token) {
172 for (char& c : token)
173 if (c >= 'a' && c <= 'z') c = char(c - 'a' + 'A');
174 if (token == "CODE")
175 stream >> codeText;
176 else if (token == "VALUE")
177 stream >> valueText;
178 else if (token == "EDGE")
179 stream >> edgeText;
180 else if (token == "ALPHA")
181 stream >> alphaText;
182 }
183 auto code = integer(codeText), alpha = integer(alphaText);
184 if (!code || *code == 16 || *code == 24 || !alpha || *alpha > 255 || edgeText.empty())
185 return fail("invalid !COLOUR definition", name);
186 auto rgb = integer(valueText.starts_with('#') ? "0x" + valueText.substr(1) : valueText);
187 auto edge = integer(edgeText.starts_with('#') ? "0x" + edgeText.substr(1) : edgeText);
188 if (!rgb || *rgb > 0xffffffu || !edge ||
189 !(valueText.starts_with('#') || valueText.starts_with("0x") || valueText.starts_with("0X")))
190 return fail("invalid !COLOUR RGB/edge", name);
191 if (definitions.size() >= request_.limits.maximumAssets && !definitions.contains(*code))
192 return fail("colour definition budget exceeded", name);
193 definitions[*code] = {rgba(*rgb, double(*alpha) / 255), "colour-" + std::to_string(*code) + suffix};
194 if (line.find(" MATERIAL ") != std::string::npos || line.find(" CHROME") != std::string::npos ||
195 line.find(" METAL") != std::string::npos || line.find(" PEARLESCENT") != std::string::npos ||
196 line.find(" RUBBER") != std::string::npos || line.find("LUMINANCE") != std::string::npos)
197 findings_.push_back({name, "LDraw.colourFinish", ImportDisposition::Unsupported,
198 "special finish/luminance retained in source; base colour and alpha translated"});
199 return Result<void>::success();
200 }
201 std::string resolve(const std::string& parent, const std::string& filename) const {
202 const auto key = pathKey(filename);
203 if (key.empty()) return {};
204 const auto slash = parent.find_last_of('/');
205 const auto relative = slash == std::string::npos ? key : parent.substr(0, slash + 1) + key;
206 for (const auto& candidate : {relative, key, "parts/" + key, "p/" + key, "models/" + key}) {
207 if (const auto first = firstSections_.find(candidate); first != firstSections_.end()) return first->second;
208 if (documents_.contains(candidate)) {
209 return candidate;
210 }
211 }
212 return {};
213 }
214 Result<Colour> colour(unsigned code, const Colour& inherited, const ColourScope& scope) const {
215 if (code == 16) return Result<Colour>::success(inherited);
216 if ((code & 0xff000000u) == 0x02000000u)
217 return Result<Colour>::success({rgba(code & 0xffffffu), "colour-" + std::to_string(code)});
218 for (auto* current = &scope; current; current = current->parent)
219 if (const auto found = current->definitions.find(code); found != current->definitions.end())
220 return Result<Colour>::success(found->second);
221 if (const auto found = palette_.find(code); found != palette_.end())
222 return Result<Colour>::success(found->second);
224 DiagnosticCode::Unsupported, "unknown face colour: supply LDConfig.ldr; colour 24 is edge-only", {}, {},
225 "asset.import.ldraw"));
226 }
227 Result<void> expand(const std::string& name, const Matrix& matrix, const Colour& inheritedColor, bool invert,
228 unsigned depth, const ColourScope* parentScope) {
229 if (depth >= request_.maximumDepth || active_.contains(name)) return fail("cyclic/deep LDraw reference", name);
230 const auto document = documents_.find(name);
231 if (document == documents_.end()) return fail("missing LDraw part", name, DiagnosticCode::NotFound);
232 active_.insert(name);
233 const auto& owner = owners_.at(name);
234 usedSources_.try_emplace(owner, request_.files.at(owner));
235 ColourScope scope{parentScope, {}};
236 bool clockwise = false, invertNext = false;
237 for (std::size_t lineNumber = 0; lineNumber < document->second.size(); ++lineNumber) {
238 if (++expandedLines_ > request_.maximumExpandedLines) return fail("expanded line budget exceeded", name);
239 const auto& line = document->second[lineNumber];
240 const auto location = name + ":" + std::to_string(lineNumber + 1);
241 if (line.empty()) continue;
242 std::istringstream stream(line);
243 stream.imbue(std::locale::classic());
244 unsigned type = 0;
245 if (!(stream >> type) || type > 5) return fail("invalid LDraw line type", location);
246 if (type == 0) {
247 if (line.starts_with("0 !COLOUR ") && name != "ldconfig.ldr") {
248 auto defined = readColour(line, location, scope.definitions, "@" + location);
249 if (!defined) return defined;
250 }
251 if (line.starts_with("0 !TEXMAP") || line.starts_with("0 !DATA") || line.starts_with("0 !:"))
252 return fail("textured/embedded geometry extensions are unsupported", location,
254 if (line.starts_with("0 BFC ")) {
255 const auto command = trim(line.substr(6));
256 if (command == "INVERTNEXT")
257 invertNext = true;
258 else if (command == "CW" || command == "CERTIFY CW" || command == "CLIP CW")
259 clockwise = true;
260 else if (command == "CCW" || command == "CERTIFY CCW" || command == "CLIP CCW" ||
261 command == "CERTIFY")
262 clockwise = false;
263 else if (command != "NOCERTIFY" && command != "NOCLIP" && command != "CLIP")
264 return fail("unknown BFC command", location, DiagnosticCode::Unsupported);
265 }
266 continue;
267 }
268 std::string colorText;
269 stream >> colorText;
270 const auto decodedColor = integer(colorText);
271 if (!decodedColor) return fail("invalid LDraw colour", location);
272 if (type == 1) {
273 auto resolvedColour = colour(*decodedColor, inheritedColor, scope);
274 if (!resolvedColour) return Result<void>::failure(resolvedColour.status());
275 Matrix local{};
276 for (std::size_t i = 9; i < 12; ++i)
277 if (!(stream >> local[i]) || !std::isfinite(local[i]))
278 return fail("invalid part translation", location);
279 for (std::size_t i = 0; i < 9; ++i)
280 if (!(stream >> local[i]) || !std::isfinite(local[i])) return fail("invalid part matrix", location);
281 std::string filename;
282 std::getline(stream, filename);
283 const auto reference = resolve(name, trim(std::move(filename)));
284 if (reference.empty())
285 return fail("missing/invalid LDraw reference", location, DiagnosticCode::NotFound);
286 const double det = local[0] * (local[4] * local[8] - local[5] * local[7]) -
287 local[1] * (local[3] * local[8] - local[5] * local[6]) +
288 local[2] * (local[3] * local[7] - local[4] * local[6]);
289 if (!std::isfinite(det) || det == 0) return fail("singular part transform", location);
290 auto child = expand(reference, compose(matrix, local), resolvedColour.value(), invert != invertNext,
291 depth + 1, &scope);
292 if (!child) return child;
293 invertNext = false;
294 continue;
295 }
296 if (invertNext) return fail("INVERTNEXT must precede a reference", location);
297 std::array<Point, 4> points{};
298 const unsigned count = type == 2 ? 2 : type == 3 ? 3 : 4;
299 for (unsigned i = 0; i < count; ++i)
300 for (double& value : points[i])
301 if (!(stream >> value) || !std::isfinite(value)) return fail("invalid LDraw coordinate", location);
302 std::string extra;
303 if (stream >> extra) return fail("extra LDraw geometry tokens", location);
304 if (type == 2 || type == 5) {
305 ++edgeLines_;
306 continue;
307 }
308 auto resolvedColour = colour(*decodedColor, inheritedColor, scope);
309 if (!resolvedColour) return Result<void>::failure(resolvedColour.status());
310 const auto& key = resolvedColour.value().key;
311 if (!parts_.contains(key) && parts_.size() * 2 + 3 > request_.limits.maximumAssets)
312 return fail("colour part budget exceeded", location);
313 auto& part = parts_[key];
314 part.color = resolvedColour.value().value;
315 for (unsigned i = 0; i < count; ++i) {
316 const auto p = transform(matrix, points[i]);
317 points[i] = {p[0] * 0.0004, -p[1] * 0.0004, -p[2] * 0.0004};
318 }
319 auto triangle = [&](unsigned a, unsigned b, unsigned c) -> Result<void> {
320 if ((vertices_ + 3) * 28 + 24 > request_.limits.maximumDecodedBytes)
321 return fail("total mesh byte budget exceeded", location);
323 part.mesh, {points[a], points[clockwise != invert ? c : b], points[clockwise != invert ? b : c]},
324 request_.limits);
325 if (added) vertices_ += 3;
326 return added;
327 };
328 auto added = triangle(0, 1, 2);
329 if (!added) return added;
330 if (type == 4) {
331 auto second = triangle(0, 2, 3);
332 if (!second) return second;
333 }
334 }
335 if (invertNext) return fail("dangling INVERTNEXT", name);
336 active_.erase(name);
337 return Result<void>::success();
338 }
339};
340} // namespace
341
343} // namespace eve::asset_import
double m[16]
int root
Definition AnimSmr.cpp:119
Vec3 relative
Definition AnimSmr.cpp:164
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
int triangle
Definition FluidSdf.cpp:554
float linear
std::string message
DiagnosticCode code
const GltfImportRequest & request
std::int32_t second
std::int32_t c
std::int32_t first
JobScope scope
const ColourScope * parent
std::map< unsigned, Colour > definitions
std::string local
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
OceanGpuFrameToken token
std::shared_ptr< OceanGpuSpectrum > owner
std::weak_ptr< Run > run
Definition OnnxGpgpu.cpp:25
std::string path
Definition PlayHost.cpp:111
std::shared_ptr< const std::vector< glm::vec2 > > points
Object::Ptr value
bool found
glm::dmat4 matrix
unsigned line
std::string text
ScriptStructure out
unsigned column
double current
int count
std::vector< std::string_view > lines
std::uint32_t depth
uint32_t index
uint64_t identity
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
Result< void > appendTriangle(asset::CanonicalMeshData &mesh, const std::array< std::array< double, 3 >, 3 > &triangle, const AssetImportLimits &limits)
Result< PreparedAssetImport > packageModel(const ImportPackageIdentity &identity, std::string_view sourceName, std::string_view format, std::map< std::string, MeshPart > parts, const std::map< std::string, std::vector< std::uint8_t > > &sources, std::vector< ImportFinding > findings, const AssetImportLimits &limits)
Result< PreparedAssetImport > prepareLDrawImport(const LDrawImportRequest &request)
Prepare LDR/DAT/MPD triangles, referenced parts and colour-separated static prefab.
Result< T > fail(std::string message, DiagnosticCode code=DiagnosticCode::InvalidArgument)
ShapeState * child(const JPH::Body &body, const JPH::SubShapeID &id)
Resolves a native child record for a synchronous callback or query. @ownership Borrowed from the worl...
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
WidgetDesc row(std::vector< WidgetDesc > children, std::string id)
Horizontal elastic layout row.
Definition Widget.cpp:870
DiagnosticCode
Stable machine-readable diagnostic codes.
Definition Diagnostic.h:47
Owning LDraw source set. Names are relative, case-insensitive LDraw paths. Supply the document and re...
glm::vec4 color