载入中...
搜索中...
未找到
UnityVegetationScene.cpp
浏览该文件的文档.
4
5#include <algorithm>
6#include <cmath>
7#include <map>
8#include <regex>
9#include <set>
10
11namespace eve::asset_import {
12namespace {
13constexpr std::string_view controlGuid = "504b8163e405ec24bab88beccbe43d42";
14constexpr std::string_view detailsGuid = "f3cf74665658f2249a2a56df92106e94";
15constexpr std::string_view motionGuid = "c879218671cebf84d9385947d79161cd";
16constexpr std::string_view volumeGuid = "eaf239e2056652741929c4183efd08b2";
17constexpr std::string_view elementGuid = "2d447c3f2fda29f41a5b7e81398c0ab0";
18
19struct SceneComponent {
20 std::int64_t fileId = 0;
21 std::string body;
22};
23
24std::vector<SceneComponent> components(std::string_view source, std::string_view scriptGuid) {
25 std::vector<SceneComponent> result;
26 const std::regex document(
27 R"((?:^|\n)--- !u!114 &(-?[0-9]+)[^\n]*\nMonoBehaviour:\s*\n([\s\S]*?)(?=\n--- !u!|$))");
28 const std::regex script("(?:^|\\n) m_Script: *\\{fileID: *11500000, guid: *" +
29 std::string(scriptGuid) + R"(, type: *3\})");
30 for (std::cregex_iterator it(source.data(), source.data() + source.size(), document), end; it != end; ++it) {
31 const auto body = (*it)[2].str();
32 if (!std::regex_search(body, script)) continue;
33 try {
34 result.push_back({std::stoll((*it)[1].str()), body});
35 } catch (...) {
36 return {};
37 }
38 }
39 return result;
40}
41
42std::optional<std::string> component(std::string_view source, std::string_view scriptGuid) {
43 const std::regex document(R"((?:^|\n)--- !u!114 &-?[0-9]+[^\n]*\nMonoBehaviour:\s*\n([\s\S]*?)(?=\n--- !u!|$))");
44 const std::regex script("(?:^|\\n) m_Script: *\\{fileID: *11500000, guid: *" +
45 std::string(scriptGuid) + R"(, type: *3\})");
46 for (std::cregex_iterator it(source.data(), source.data() + source.size(), document), end; it != end; ++it) {
47 auto body = (*it)[1].str();
48 if (std::regex_search(body, script)) return body;
49 }
50 return {};
51}
52
53Result<double> number(std::string_view body, std::string_view name, double fallback) {
54 std::cmatch match;
55 const std::regex field("(?:^|\\n) " + std::string(name) + R"(: *([^\r\n]+))");
56 if (!std::regex_search(body.data(), body.data() + body.size(), match, field))
57 return Result<double>::success(fallback);
58 try {
59 std::size_t end = 0;
60 const auto token = match[1].str();
61 const auto value = std::stod(token, &end);
62 if (end != token.size() || !std::isfinite(value)) throw std::invalid_argument("number");
64 } catch (...) {
65 return Result<double>::failure(Diagnostic::error(DiagnosticCode::ParseError, "TVE scene number is invalid",
66 std::string(name), {}, "asset.import"));
67 }
68}
69
70Result<Value> array(std::string_view body,
71 std::initializer_list<std::pair<std::string_view, double>> fields) {
73 for (const auto& [name, fallback] : fields) {
74 auto value = number(body, name, fallback);
75 if (!value) return Result<Value>::failure(value.status());
76 result.emplace_back(value.value());
77 }
78 return Result<Value>::success(Value(std::move(result)));
79}
80
81Result<Value> color(std::string_view body, std::string_view name, std::array<double, 4> fallback) {
82 std::cmatch match;
83 const std::regex field("(?:^|\\n) " + std::string(name) +
84 R"(: *\{r: *([^,]+), *g: *([^,]+), *b: *([^,]+), *a: *([^}]+)\})");
85 if (!std::regex_search(body.data(), body.data() + body.size(), match, field))
86 return Result<Value>::success(Value::array({fallback[0], fallback[1], fallback[2], fallback[3]}));
88 for (std::size_t index = 1; index <= 4; ++index) {
89 try {
90 std::size_t end = 0;
91 const auto token = match[index].str();
92 const auto value = std::stod(token, &end);
93 if (end != token.size() || !std::isfinite(value)) throw std::invalid_argument("color");
94 result.emplace_back(value);
95 } catch (...) {
96 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::ParseError, "TVE scene color is invalid",
97 std::string(name), {}, "asset.import"));
98 }
99 }
100 return Result<Value>::success(Value(std::move(result)));
101}
102
103std::string guid(std::string_view body, std::string_view name) {
104 std::cmatch match;
105 const std::regex field("(?:^|\\n) " + std::string(name) +
106 R"(: *\{fileID: *-?[0-9]+, guid: *([0-9a-fA-F]{32}), type: *[23]\})");
107 return std::regex_search(body.data(), body.data() + body.size(), match, field)
108 ? unity_detail::foldAscii(match[1].str())
109 : std::string{};
110}
111
112Result<Value> details(std::string_view body) {
113 auto layers = array(body, {{"layerColors", 0}, {"layerExtras", 0}, {"layerMotion", 0}});
114 auto global = array(body, {{"globalColor", 1}, {"globalAlpha", 1}, {"globalOverlay", 1}, {"globalWetness", 1}});
115 auto colorMask = array(body, {{"colorMaskMin", .4}, {"colorMaskMax", .6}});
116 auto overlayMask = array(body, {{"overlayMaskMin", .4}, {"overlayMaskMax", .6}});
117 auto perspective = array(body, {{"perspectivePush", 0}, {"perspectiveNoise", 0}, {"perspectiveAngle", 1}});
118 auto highlight = color(body, "motionHighlight", {1, 1, 1, 1});
119 auto bending = array(body, {{"bendingAmplitude", 1}, {"bendingSpeed", 6}, {"bendingScale", 2}});
120 auto flutter = array(body, {{"flutterAmplitude", .1}, {"flutterSpeed", 20}, {"flutterScale", 2}});
121 auto alpha = number(body, "alphaTreshold", .5), interaction = number(body, "interactionAmplitude", 1);
122 const bool layersOk = bool(layers), globalOk = bool(global), colorMaskOk = bool(colorMask),
123 overlayMaskOk = bool(overlayMask), perspectiveOk = bool(perspective), highlightOk = bool(highlight),
124 bendingOk = bool(bending), flutterOk = bool(flutter), alphaOk = bool(alpha),
125 interactionOk = bool(interaction);
126 if (!layersOk || !globalOk || !colorMaskOk || !overlayMaskOk || !perspectiveOk || !highlightOk || !bendingOk ||
127 !flutterOk || !alphaOk || !interactionOk)
129 Diagnostic::error(DiagnosticCode::ParseError, "TVE Global Details is malformed", {}, {}, "asset.import"));
130 auto highlightValue = std::move(highlight).takeValue();
131 highlightValue.getIf<Value::Array>()->pop_back();
133 {"layers", std::move(layers).takeValue()}, {"global", std::move(global).takeValue()},
134 {"colorMask", std::move(colorMask).takeValue()}, {"overlayMask", std::move(overlayMask).takeValue()},
135 {"alphaThreshold", alpha.value()}, {"perspective", std::move(perspective).takeValue()},
136 {"motionHighlight", std::move(highlightValue)}, {"bending", std::move(bending).takeValue()},
137 {"flutter", std::move(flutter).takeValue()}, {"interactionAmplitude", interaction.value()}}));
138}
139
140Result<Value> control(std::string_view body) {
141 auto tint = color(body, "globalColor", {.5, .5, .5, 0});
142 auto overlay = color(body, "overlayColor", {1, 1, 1, 1});
143 auto values = array(body, {{"seasonControl", 2}, {"globalAlpha", 1}, {"globalOverlay", 0},
144 {"globalWetness", 0}, {"globalEmissive", 1}, {"globalSubsurface", 1},
145 {"globalSizeFade", 1}, {"overlaySmoothness", .5}, {"overlayNormalScale", .5},
146 {"overlaySubsurface", .5}, {"overlayScale", 1}, {"wetnessContrast", .5},
147 {"wetnessNormalScale", .5}, {"noiseTextureTilling", 1},
148 {"proximityDistanceFade", 1}, {"sizeFadeDistanceBias", 1},
149 {"defaultConformHeight", 0}});
150 const bool tintOk = bool(tint), overlayOk = bool(overlay), valuesOk = bool(values);
151 if (!tintOk || !overlayOk || !valuesOk)
153 Diagnostic::error(DiagnosticCode::ParseError, "TVE Global Control is malformed", {}, {}, "asset.import"));
155 {"values", std::move(values).takeValue()}, {"globalColor", std::move(tint).takeValue()},
156 {"overlayColor", std::move(overlay).takeValue()}, {"overlayAlbedoGuid", guid(body, "overlayAlbedo")},
157 {"overlayNormalGuid", guid(body, "overlayNormal")}, {"noiseTextureGuid", guid(body, "noiseTexture3D")}}));
158}
159
160Result<Value> motion(std::string_view body) {
161 auto values = array(body, {{"windPower", .5}, {"noiseTilling", 1}, {"motionBending", 1},
162 {"motionBranch", 1}, {"motionFlutter", 1}, {"motionSpeed", 1},
163 {"useAnimatedMotionTime", 1}, {"motionFadeDistance", 100}});
164 if (!values) return Result<Value>::failure(values.status());
165 return Result<Value>::success(Value::object({{"values", std::move(values).takeValue()},
166 {"noiseTextureGuid", guid(body, "noiseTexture")}}));
167}
168
169struct SceneTransform {
170 std::int64_t parent = 0;
171 std::int64_t gameObject = 0;
172 std::array<double, 4> rotation{0, 0, 0, 1};
173 std::array<double, 3> position{0, 0, 0}, scale{1, 1, 1};
174};
175
176std::optional<std::int64_t> fileId(std::string_view body, std::string_view name) {
177 const std::string field = " " + std::string(name) + ":";
178 auto position = body.find(field);
179 while (position != std::string_view::npos && position != 0 && body[position - 1] != '\n')
180 position = body.find(field, position + field.size());
181 if (position == std::string_view::npos) return {};
182 position = body.find("fileID:", position + field.size());
183 if (position == std::string_view::npos) return {};
184 position += 7;
185 while (position < body.size() && body[position] == ' ') ++position;
186 const auto end = body.find_first_of(",}", position);
187 try {
188 std::size_t consumed = 0;
189 const auto token = std::string(body.substr(position, end - position));
190 const auto value = std::stoll(token, &consumed);
191 if (consumed != token.size()) return {};
192 return value;
193 } catch (...) {
194 return {};
195 }
196}
197
198std::optional<double> rotationComponent(std::string_view line, std::string_view name) {
199 const std::string field = std::string(name) + ":";
200 auto position = line.find(field);
201 if (position == std::string_view::npos) return {};
202 position += field.size();
203 while (position < line.size() && line[position] == ' ') ++position;
204 const auto end = line.find_first_of(",}", position);
205 try {
206 std::size_t consumed = 0;
207 const auto token = std::string(line.substr(position, end - position));
208 const auto value = std::stod(token, &consumed);
209 if (consumed != token.size() || !std::isfinite(value)) return {};
210 return value;
211 } catch (...) {
212 return {};
213 }
214}
215
216std::optional<std::array<double, 3>> vector3Field(std::string_view body, std::string_view name) {
217 const std::string field = " " + std::string(name) + ":";
218 const auto start = body.find(field);
219 if (start == std::string_view::npos) return {};
220 const auto end = body.find('\n', start);
221 const auto line = body.substr(start, end - start);
222 const auto x = rotationComponent(line, "x"), y = rotationComponent(line, "y"), z = rotationComponent(line, "z");
223 if (!x || !y || !z) return {};
224 return std::array<double, 3>{*x, *y, *z};
225}
226
227std::map<std::int64_t, SceneTransform> transforms(std::string_view source) {
228 std::map<std::int64_t, SceneTransform> result;
229 constexpr std::string_view marker = "--- !u!4 &";
230 std::size_t cursor = 0;
231 while ((cursor = source.find(marker, cursor)) != std::string_view::npos) {
232 if (cursor != 0 && source[cursor - 1] != '\n') {
233 cursor += marker.size();
234 continue;
235 }
236 const auto idBegin = cursor + marker.size();
237 const auto headerEnd = source.find('\n', idBegin);
238 if (headerEnd == std::string_view::npos) break;
239 const auto bodyBegin = headerEnd + 1;
240 if (!source.substr(bodyBegin).starts_with("Transform:")) {
241 cursor = bodyBegin;
242 continue;
243 }
244 const auto bodyContent = source.find('\n', bodyBegin);
245 if (bodyContent == std::string_view::npos) break;
246 const auto next = source.find("\n--- !u!", bodyContent + 1);
247 const auto body = source.substr(bodyContent + 1,
248 next == std::string_view::npos ? source.size() - bodyContent - 1
249 : next - bodyContent - 1);
250 SceneTransform transform;
251 try {
252 transform.gameObject = fileId(body, "m_GameObject").value_or(0);
253 transform.parent = fileId(body, "m_Father").value_or(0);
254 transform.position = vector3Field(body, "m_LocalPosition").value_or(std::array<double, 3>{0, 0, 0});
255 transform.scale = vector3Field(body, "m_LocalScale").value_or(std::array<double, 3>{1, 1, 1});
256 const auto rotationStart = body.find(" m_LocalRotation:");
257 if (rotationStart == std::string_view::npos) {
258 cursor = next == std::string_view::npos ? source.size() : next + 1;
259 continue;
260 }
261 const auto rotationEnd = body.find('\n', rotationStart);
262 const auto line = body.substr(rotationStart, rotationEnd - rotationStart);
263 const auto x = rotationComponent(line, "x"), y = rotationComponent(line, "y"),
264 z = rotationComponent(line, "z"), w = rotationComponent(line, "w");
265 if (!x || !y || !z || !w) return {};
266 transform.rotation = {*x, *y, *z, *w};
267 result.emplace(std::stoll(std::string(source.substr(idBegin, headerEnd - idBegin))), transform);
268 } catch (...) {
269 return {};
270 }
271 cursor = next == std::string_view::npos ? source.size() : next + 1;
272 }
273 return result;
274}
275
276struct WorldTransform {
277 std::array<double, 3> position{0, 0, 0}, scale{1, 1, 1};
278 std::array<double, 4> rotation{0, 0, 0, 1};
279};
280
281std::array<double, 4> multiply(std::array<double, 4> lhs, std::array<double, 4> rhs);
282
283Result<std::array<double, 4>> normalized(std::array<double, 4> value) {
284 const double length = std::sqrt(value[0] * value[0] + value[1] * value[1] + value[2] * value[2] +
285 value[3] * value[3]);
286 if (!std::isfinite(length) || length <= 1e-12)
287 return Result<std::array<double, 4>>::failure(Diagnostic::error(
288 DiagnosticCode::ParseError, "TVE element Transform rotation is invalid", {}, {}, "asset.import"));
289 for (auto& component : value) component /= length;
290 return Result<std::array<double, 4>>::success(value);
291}
292
293std::array<double, 3> rotate(std::array<double, 4> q, std::array<double, 3> v) {
294 const std::array<double, 4> p{v[0], v[1], v[2], 0};
295 const std::array<double, 4> conjugate{-q[0], -q[1], -q[2], q[3]};
296 const auto result = multiply(multiply(q, p), conjugate);
297 return {result[0], result[1], result[2]};
298}
299
300Result<WorldTransform> worldTransform(const std::map<std::int64_t, SceneTransform>& sceneTransforms,
301 std::int64_t gameObject) {
302 auto found = std::find_if(sceneTransforms.begin(), sceneTransforms.end(),
303 [&](const auto& entry) { return entry.second.gameObject == gameObject; });
304 if (found == sceneTransforms.end())
306 Diagnostic::error(DiagnosticCode::NotFound, "TVE element Transform is missing", {}, {}, "asset.import"));
307 std::vector<const SceneTransform*> chain{&found->second};
308 std::set<std::int64_t> visited{found->first};
309 auto parent = found->second.parent;
310 while (parent != 0) {
311 const auto ancestor = sceneTransforms.find(parent);
312 if (ancestor == sceneTransforms.end() || !visited.emplace(parent).second)
314 DiagnosticCode::ParseError, "TVE element Transform hierarchy is invalid", {}, {}, "asset.import"));
315 chain.push_back(&ancestor->second);
316 parent = ancestor->second.parent;
317 }
318 WorldTransform world;
319 for (auto it = chain.rbegin(); it != chain.rend(); ++it) {
320 auto localRotation = normalized((*it)->rotation);
321 if (!localRotation) return Result<WorldTransform>::failure(localRotation.status());
322 std::array<double, 3> local{(*it)->position[0] * world.scale[0], (*it)->position[1] * world.scale[1],
323 (*it)->position[2] * world.scale[2]};
324 local = rotate(world.rotation, local);
325 for (std::size_t axis = 0; axis < 3; ++axis) {
326 world.position[axis] += local[axis];
327 world.scale[axis] *= (*it)->scale[axis];
328 }
329 auto composed = normalized(multiply(world.rotation, localRotation.value()));
330 if (!composed) return Result<WorldTransform>::failure(composed.status());
331 world.rotation = std::move(composed).takeValue();
332 }
333 world.position[2] = -world.position[2];
334 world.rotation[0] = -world.rotation[0];
335 world.rotation[1] = -world.rotation[1];
337}
338
339std::optional<std::string_view> propertyBlock(std::string_view body, std::string_view name) {
340 const std::string marker = " prop: " + std::string(name);
341 auto begin = body.find(marker);
342 if (begin == std::string_view::npos) return {};
343 begin = body.rfind(" - type:", begin);
344 if (begin == std::string_view::npos) return {};
345 auto end = body.find("\n - type:", begin + 1);
346 if (end == std::string_view::npos) end = body.size();
347 return body.substr(begin, end - begin);
348}
349
350double materialNumber(std::string_view body, std::string_view name, double fallback) {
351 const auto block = propertyBlock(body, name);
352 if (!block) return fallback;
353 const auto value = number(*block, " value", fallback);
354 return value ? value.value() : fallback;
355}
356
357Value materialVector(std::string_view body, std::string_view name, std::array<double, 4> fallback) {
358 const auto block = propertyBlock(body, name);
359 if (!block) return Value::array({fallback[0], fallback[1], fallback[2], fallback[3]});
360 auto value = color(*block, " vector", fallback);
361 return value ? std::move(value).takeValue() : Value::array({fallback[0], fallback[1], fallback[2], fallback[3]});
362}
363
364std::string materialTexture(std::string_view body, std::string_view name) {
365 const auto block = propertyBlock(body, name);
366 return block ? guid(*block, " texture") : std::string{};
367}
368
369Result<Value> materialProperties(std::string_view body) {
371 std::size_t cursor = 0;
372 constexpr std::string_view marker = " - type:";
373 const std::regex namePattern(R"((?:^|\n) prop: *([A-Za-z_][A-Za-z0-9_]{0,127})\s*(?:\r?\n|$))");
374 while ((cursor = body.find(marker, cursor)) != std::string_view::npos) {
375 const auto next = body.find("\n - type:", cursor + marker.size());
376 const auto block = body.substr(cursor, next == std::string_view::npos ? body.size() - cursor : next - cursor);
377 std::cmatch name;
378 if (!std::regex_search(block.data(), block.data() + block.size(), name, namePattern))
380 DiagnosticCode::ParseError, "TVE element property name is malformed", {}, {}, "asset.import"));
381 auto type = number(block, " - type", -1), value = number(block, " value", 0);
382 auto vector = color(block, " vector", {0, 0, 0, 0});
383 if (!type || !value || !vector || std::floor(type.value()) != type.value() || type.value() < 0 ||
384 type.value() > 2)
386 "TVE element property value is malformed", name[1].str(),
387 {}, "asset.import"));
388 output.push_back(Value::object({{"name", name[1].str()}, {"type", std::int64_t(type.value())},
389 {"textureGuid", guid(block, " texture")},
390 {"vector", std::move(vector).takeValue()}, {"value", value.value()}}));
391 if (output.size() > 256)
393 DiagnosticCode::InvalidArgument, "TVE element property count exceeds 256", {}, {}, "asset.import"));
394 cursor = next == std::string_view::npos ? body.size() : next + 1;
395 }
396 return Result<Value>::success(Value(std::move(output)));
397}
398
399void collectTextureGuids(const Value& value, std::set<std::string>& output) {
400 if (const auto* object = value.getIf<Value::Object>()) {
401 for (const auto& [name, child] : *object) {
402 if (name == "textureGuid" && child.isString() && !child.asString().empty()) output.insert(child.asString());
403 collectTextureGuids(child, output);
404 }
405 } else if (const auto* array = value.getIf<Value::Array>()) {
406 for (const auto& child : *array) collectTextureGuids(child, output);
407 }
408}
409
410bool importedImageAvailable(const UnityProjectImportRequest& request, std::string_view targetGuid) {
411 for (const auto& [path, bytes] : request.files) {
412 if (!path.ends_with(".meta")) continue;
413 const std::string meta(bytes.begin(), bytes.end());
414 if (meta.find("guid: " + std::string(targetGuid)) == std::string::npos) continue;
415 const auto sourcePath = path.substr(0, path.size() - 5);
416 const auto source = request.files.find(sourcePath);
417 if (source == request.files.end()) return false;
418 const auto dot = sourcePath.find_last_of('.');
419 const auto extension = dot == std::string::npos ? std::string{} : unity_detail::foldAscii(sourcePath.substr(dot));
420 if (extension == ".png" || extension == ".tga" || extension == ".tif" || extension == ".tiff") return true;
421 if (extension != ".asset") return false;
422 const std::string text(source->second.begin(), source->second.end());
423 return text.find("\nTexture2D:") != std::string::npos;
424 }
425 return false;
426}
427
428Result<void> bindTextureAssets(Value& value, const UnityProjectImportRequest& request) {
429 if (auto* object = value.getIf<Value::Object>()) {
430 const auto guidValue = object->find("textureGuid");
431 if (guidValue != object->end() && guidValue->second.isString()) {
432 std::string asset;
433 if (!guidValue->second.asString().empty() && importedImageAvailable(request, guidValue->second.asString())) {
435 request.package.packageId.child("unity:" + guidValue->second.asString()).child("image:default"));
436 if (!reference) return Result<void>::failure(reference.status());
437 asset = reference.value().format();
438 }
439 object->emplace("textureAsset", std::move(asset));
440 }
441 for (auto& [name, child] : *object) {
442 (void)name;
443 auto bound = bindTextureAssets(child, request);
444 if (!bound) return bound;
445 }
446 } else if (auto* array = value.getIf<Value::Array>()) {
447 for (auto& child : *array) {
448 auto bound = bindTextureAssets(child, request);
449 if (!bound) return bound;
450 }
451 }
452 return Result<void>::success();
453}
454
455Result<Value> elements(std::string_view source, std::vector<ImportFinding>& findings, std::string_view path) {
456 const std::map<std::string_view, std::pair<std::string_view, int>> shaders{
457 {"1179777fe2a84944798f2df69a9616a5", {"color-effect", 0}},
458 {"ebee0293d9bb4564889bd81c801438b7", {"color-map", 0}},
459 {"da183c57da5cee64c9d1fd3e840427b6", {"color-noise", 0}},
460 {"853be43322d350648a82ec17b27de5cf", {"color-tint", 0}},
461 {"94b5d04d01c0973498bbb16cea8449ec", {"extras-alpha", 1}},
462 {"47fd4a0e901c8844a9f5ae6bcdef7ca4", {"extras-emissive", 1}},
463 {"b3820571eb3f04f4f855cc7161c165d7", {"extras-overlay", 1}},
464 {"3a8db8eb5154b6c44940a6c8616408d8", {"extras-wetness", 1}},
465 {"c2aed2f308142f94fa04326437ee0005", {"motion-advanced", 2}},
466 {"8aca4d3e46e8b7b458ec65a9bb11f144", {"motion-interaction", 2}},
467 {"c52053b6a008e1544bad0837b518fa94", {"motion-wind-power", 2}},
468 {"1e5171ac7b63ed441960da6cf37146a2", {"vertex-conform-model", 3}},
469 {"3f514efeb56cd5149a0f4c127eab8a8c", {"vertex-conform-simple", 3}},
470 {"4bcfd77507de42d40ad7ce2543a44cd8", {"vertex-conform-terrain", 3}},
471 {"387db0d42ba361645a8443beadc8bdd6", {"vertex-height-offset", 3}},
472 {"abb24a67f2ce88d498809438c1104783", {"vertex-height", 3}},
473 {"ab583b89d93bd5846883c513711e769a", {"vertex-orientation-model", 3}},
474 {"74b163185090aaf41b8df93640d24c50", {"vertex-orientation-terrain", 3}},
475 {"4776cc0409f0f4e4da64e5837bff4b0d", {"vertex-size", 3}},
476 };
477 const auto sceneTransforms = transforms(source);
479 std::size_t invalidMaterials = 0;
480 for (const auto& component : components(source, elementGuid)) {
481 const auto gameObject = fileId(component.body, "m_GameObject").value_or(0);
482 auto world = worldTransform(sceneTransforms, gameObject);
483 if (!world) return Result<Value>::failure(world.status());
484 const auto shader = guid(component.body, " shader");
485 const auto shaderDefinition = shaders.find(shader);
486 if (shaderDefinition == shaders.end()) { ++invalidMaterials; continue; }
487 const std::string kind(shaderDefinition->second.first);
488 const int channel = shaderDefinition->second.second;
489 std::array<double, 4> main{1, 1, 1, 1};
490 if (kind == "color-tint") main = {.5019608, .5019608, .5019608, 1};
491 double layerMask = 1;
492 if (propertyBlock(component.body, "_ElementLayerMask")) {
493 layerMask = materialNumber(component.body, "_ElementLayerMask", 1);
494 } else if (propertyBlock(component.body, "_ElementLayerValue")) {
495 layerMask = materialNumber(component.body, "_ElementLayerValue", 1);
496 } else {
497 const auto legacyLayer = materialNumber(component.body, "_ElementLayer", 0);
498 if (legacyLayer < 0 || legacyLayer > 8 || std::floor(legacyLayer) != legacyLayer)
500 "TVE legacy element layer is outside 0..8",
501 std::string(path), {}, "asset.import"));
502 layerMask = double(std::uint16_t(1u << std::uint32_t(legacyLayer)));
503 }
504 const auto seasonal = materialNumber(component.body, "_ElementMode", 0) >= .5;
505 Value::Array seasons;
506 for (int index = 1; index <= 4; ++index) {
507 if (kind == "color-tint")
508 seasons.push_back(materialVector(component.body, "_AdditionalColor" + std::to_string(index), main));
509 else {
510 const auto value = materialNumber(component.body, "_AdditionalValue" + std::to_string(index), 1);
511 seasons.push_back(Value::array({value, value, value, 1}));
512 }
513 }
514 const auto& transform = world.value();
515 auto enabledValue = number(component.body, "m_Enabled", 1);
516 auto visibilityValue = number(component.body, "customVisibility", -1);
517 auto propertiesValue = materialProperties(component.body);
518 if (!enabledValue || !visibilityValue || !propertiesValue)
519 return Result<Value>::failure(!enabledValue ? enabledValue.status()
520 : !visibilityValue ? visibilityValue.status()
521 : propertiesValue.status());
522 const double mainValue = materialNumber(component.body, "_MainValue", main[0]);
523 Value channelValue = materialVector(component.body, "_MainColor", main);
524 if (kind == "extras-overlay") channelValue = Value::array({1, 0, mainValue, 1});
525 else if (kind == "motion-interaction") channelValue = Value::array({1, 0, 0, mainValue});
526 else if (kind == "motion-wind-power") channelValue = Value::array({0, 0, mainValue, 1});
527 else if (kind == "vertex-size") channelValue = Value::array({0, 0, 0, mainValue});
528 output.push_back(Value::object({
529 {"sourceFileId", component.fileId}, {"shaderGuid", shader}, {"kind", kind}, {"channel", channel},
530 {"properties", std::move(propertiesValue).takeValue()},
531 {"enabled", enabledValue.value() >= .5},
532 {"visibility", std::int64_t(visibilityValue.value())},
533 {"position", Value::array({transform.position[0], transform.position[1], transform.position[2]})},
534 {"rotation", Value::array({transform.rotation[0], transform.rotation[1], transform.rotation[2], transform.rotation[3]})},
535 {"scale", Value::array({std::abs(transform.scale[0]), std::abs(transform.scale[1]), std::abs(transform.scale[2])})},
536 {"layers", std::int64_t(layerMask)}, {"intensity", materialNumber(component.body, "_ElementIntensity", 1)},
537 {"value", std::move(channelValue)},
538 {"seasonal", seasonal}, {"seasons", Value(std::move(seasons))},
539 {"textureGuid", materialTexture(component.body, "_MainTex")},
540 {"remap", Value::array({materialNumber(component.body, "_MainTexColorMinValue", 0),
541 materialNumber(component.body, "_MainTexColorMaxValue", 1),
542 materialNumber(component.body, "_MainTexAlphaMinValue", 0),
543 materialNumber(component.body, "_MainTexAlphaMaxValue", 1),
544 materialNumber(component.body, "_MainTexFallofMinValue", 0),
545 materialNumber(component.body, "_MainTexFallofMaxValue", 0)})},
546 {"blendRgb", std::int64_t(materialNumber(component.body, "_ElementBlendRGB", 0))},
547 {"blendAlpha", std::int64_t(materialNumber(component.body, "_ElementBlendA", 0))},
548 {"directionMode", std::int64_t(materialNumber(component.body, "_ElementDirectionMode", 20))},
549 {"invertDirection", materialNumber(component.body, "_ElementInvertMode",
550 materialNumber(component.body, "_InvertX", 0)) >= .5},
551 {"volumeFade", materialNumber(component.body, "_ElementVolumeFadeMode",
552 materialNumber(component.body, "_ElementFadeSupport", 0)) >= .5},
553 {"motionMode", std::int64_t(materialNumber(component.body, "_ElementMotionMode", 15))},
554 {"motionPower", materialNumber(component.body, "_MotionPower", 0)}}));
555 }
556 findings.push_back({std::string(path), "TVE.elements", ImportDisposition::Translated,
557 std::to_string(output.size()) + " executable element definitions normalized"});
558 if (invalidMaterials != 0)
559 findings.push_back({std::string(path), "TVE.elements.invalid-material", ImportDisposition::PreservedSource,
560 std::to_string(invalidMaterials) + " source elements have no executable material"});
561 return Result<Value>::success(Value(std::move(output)));
562}
563
564std::array<double, 4> multiply(std::array<double, 4> lhs, std::array<double, 4> rhs) {
565 return {lhs[3] * rhs[0] + lhs[0] * rhs[3] + lhs[1] * rhs[2] - lhs[2] * rhs[1],
566 lhs[3] * rhs[1] - lhs[0] * rhs[2] + lhs[1] * rhs[3] + lhs[2] * rhs[0],
567 lhs[3] * rhs[2] + lhs[0] * rhs[1] - lhs[1] * rhs[0] + lhs[2] * rhs[3],
568 lhs[3] * rhs[3] - lhs[0] * rhs[0] - lhs[1] * rhs[1] - lhs[2] * rhs[2]};
569}
570
571Result<Value> motionDirection(std::string_view source, std::string_view body) {
572 const auto manager = fileId(body, "m_GameObject").value_or(0);
573 const auto target = fileId(body, "mainDirection").value_or(0);
574 const auto gameObject = target == 0 ? manager : target;
575 const auto sceneTransforms = transforms(source);
576 auto found = std::find_if(sceneTransforms.begin(), sceneTransforms.end(),
577 [&](const auto& entry) { return entry.second.gameObject == gameObject; });
578 if (found == sceneTransforms.end())
580 "TVE motion direction Transform is missing", "mainDirection",
581 {}, "asset.import"));
582 auto rotation = found->second.rotation;
583 std::set<std::int64_t> visited{found->first};
584 auto parent = found->second.parent;
585 while (parent != 0) {
586 const auto ancestor = sceneTransforms.find(parent);
587 if (ancestor == sceneTransforms.end() || !visited.emplace(parent).second)
589 "TVE motion direction Transform hierarchy is invalid",
590 "mainDirection", {}, "asset.import"));
591 rotation = multiply(ancestor->second.rotation, rotation);
592 parent = ancestor->second.parent;
593 }
594 const double length = std::sqrt(rotation[0] * rotation[0] + rotation[1] * rotation[1] +
595 rotation[2] * rotation[2] + rotation[3] * rotation[3]);
596 if (!std::isfinite(length) || length <= 1e-12)
598 "TVE motion direction rotation is invalid", "mainDirection", {},
599 "asset.import"));
600 for (auto& value : rotation) value /= length;
601 const double unityX = 2.0 * (rotation[0] * rotation[2] + rotation[3] * rotation[1]);
602 const double unityZ = 1.0 - 2.0 * (rotation[0] * rotation[0] + rotation[1] * rotation[1]);
603 const double horizontal = std::hypot(unityX, unityZ);
604 if (!std::isfinite(horizontal) || horizontal <= 1e-12)
605 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::ParseError, "TVE motion direction is vertical",
606 "mainDirection", {}, "asset.import"));
607 return Result<Value>::success(Value::array({-unityX / horizontal, -unityZ / horizontal}));
608}
609
610Result<Value> volumeChannel(std::string_view body, std::string_view name) {
611 std::cmatch legacy;
612 const std::regex legacyField("(?:^|\\n) " + std::string(name) + R"(: *(-?[0-9]+)\s*(?:\r?\n|$))");
613 if (std::regex_search(body.data(), body.data() + body.size(), legacy, legacyField)) {
614 try {
615 const auto resolution = static_cast<std::int64_t>(std::stoll(legacy[1].str()));
617 Value::array({Value(std::int64_t{10}), Value(resolution), Value(resolution)}));
618 } catch (...) {
620 "TVE legacy volume resolution is invalid",
621 std::string(name), {}, "asset.import"));
622 }
623 }
624 std::cmatch match;
625 const std::regex section("(?:^|\\n) " + std::string(name) + R"(:\s*\n([\s\S]*?)(?=\n [A-Za-z_][^\n]*:|$))");
626 if (!std::regex_search(body.data(), body.data() + body.size(), match, section))
627 return Result<Value>::failure(Diagnostic::error(DiagnosticCode::ParseError, "TVE volume channel is missing",
628 std::string(name), {}, "asset.import"));
629 const auto nested = match[1].str();
630 auto read = [&](std::string_view field) -> Result<double> {
631 std::cmatch value;
632 const std::regex pattern("(?:^|\\n) " + std::string(field) + R"(: *([^\r\n]+))");
633 if (!std::regex_search(nested.data(), nested.data() + nested.size(), value, pattern))
635 Diagnostic::error(DiagnosticCode::ParseError, "TVE volume channel field is missing",
636 std::string(name) + "." + std::string(field), {}, "asset.import"));
637 try {
638 std::size_t end = 0;
639 const auto token = value[1].str();
640 const auto decoded = std::stod(token, &end);
641 if (end != token.size() || !std::isfinite(decoded)) throw std::invalid_argument("number");
642 return Result<double>::success(decoded);
643 } catch (...) {
645 Diagnostic::error(DiagnosticCode::ParseError, "TVE volume channel field is invalid",
646 std::string(name) + "." + std::string(field), {}, "asset.import"));
647 }
648 };
649 auto mode = read("renderMode"), width = read("textureWidth"), height = read("textureHeight");
650 const bool modeOk = bool(mode), widthOk = bool(width), heightOk = bool(height);
651 if (!modeOk || !widthOk || !heightOk)
652 return Result<Value>::failure(!modeOk ? mode.status() : !widthOk ? width.status() : height.status());
653 return Result<Value>::success(Value::array({mode.value(), width.value(), height.value()}));
654}
655
656Result<Value> volume(std::string_view body) {
657 auto values = array(body, {{"renderScale", 1}, {"elementsVisibility", 0}, {"elementsSorting", 0},
658 {"elementsEdgeFade", .75}});
659 auto colors = volumeChannel(body, "renderColors"), extras = volumeChannel(body, "renderExtras"),
660 motion = volumeChannel(body, "renderMotion"), vertex = volumeChannel(body, "renderVertex");
661 const bool valuesOk = bool(values), colorsOk = bool(colors), extrasOk = bool(extras), motionOk = bool(motion),
662 vertexOk = bool(vertex);
663 if (!valuesOk || !colorsOk || !extrasOk || !motionOk || !vertexOk)
664 return Result<Value>::failure(!valuesOk ? values.status()
665 : !colorsOk ? colors.status()
666 : !extrasOk ? extras.status()
667 : !motionOk ? motion.status()
668 : vertex.status());
669 return Result<Value>::success(Value::object({{"values", std::move(values).takeValue()},
670 {"colors", std::move(colors).takeValue()},
671 {"extras", std::move(extras).takeValue()},
672 {"motion", std::move(motion).takeValue()},
673 {"vertex", std::move(vertex).takeValue()}}));
674}
675} // namespace
676
678 const UnitySourceAsset& source) {
679 const auto& bytes = request.files.at(source.path);
680 const std::string text(bytes.begin(), bytes.end());
681 const auto controlBody = component(text, controlGuid), detailsBody = component(text, detailsGuid),
682 motionBody = component(text, motionGuid), volumeBody = component(text, volumeGuid);
683 if (!controlBody && !detailsBody && !motionBody && !volumeBody)
685 Diagnostic::error(DiagnosticCode::Unsupported, "Unity scene has no TVE runtime manager components",
686 source.path, {}, "asset.import"));
687 if (!controlBody || !detailsBody || !motionBody || !volumeBody)
689 "TVE scene manager component set is incomplete",
690 source.path, {}, "asset.import"));
691 std::vector<ImportFinding> elementFindings;
692 auto controlValue = control(*controlBody), detailsValue = details(*detailsBody), motionValue = motion(*motionBody),
693 volumeValue = volume(*volumeBody), elementsValue = elements(text, elementFindings, source.path);
694 const bool controlOk = bool(controlValue), detailsOk = bool(detailsValue), motionOk = bool(motionValue),
695 volumeOk = bool(volumeValue), elementsOk = bool(elementsValue);
696 if (!controlOk || !detailsOk || !motionOk || !volumeOk || !elementsOk)
698 DiagnosticCode::ParseError, "TVE scene manager data is malformed", source.path, {}, "asset.import"));
699 auto directionValue = motionDirection(text, *motionBody);
700 if (!directionValue) return Result<PreparedAssetImport>::failure(directionValue.status());
701 (*motionValue.value().getIf<Value::Object>())["direction"] = std::move(directionValue).takeValue();
702 std::set<std::string> textureGuids;
703 auto boundTextures = bindTextureAssets(elementsValue.value(), request);
704 if (!boundTextures) return Result<PreparedAssetImport>::failure(boundTextures.status());
705 collectTextureGuids(elementsValue.value(), textureGuids);
706 for (const auto name : {"overlayAlbedo", "overlayNormal", "noiseTexture3D"}) {
707 auto value = guid(*controlBody, name);
708 if (!value.empty()) textureGuids.insert(std::move(value));
709 }
710 auto motionNoise = guid(*motionBody, "noiseTexture");
711 if (!motionNoise.empty()) textureGuids.insert(std::move(motionNoise));
712 Value definition = Value::object({{"schema", "eve.vegetation-scene"}, {"schemaVersion", 1},
713 {"sourceGuid", source.guid}, {"control", std::move(controlValue).takeValue()},
714 {"details", std::move(detailsValue).takeValue()},
715 {"motion", std::move(motionValue).takeValue()},
716 {"volume", std::move(volumeValue).takeValue()},
717 {"elements", std::move(elementsValue).takeValue()}});
718 auto encoded = definition.toJson();
719 if (!encoded) return Result<PreparedAssetImport>::failure(encoded.status());
720 auto manifest = detail::baseManifest(request.package, "eve.unity-vegetation-scene/1");
721 if (!manifest) return Result<PreparedAssetImport>::failure(manifest.status());
723 out.manifest = std::move(manifest).takeValue();
724 const auto id = request.package.packageId.child("unity:" + source.guid).child("vegetation-scene:default");
725 auto ref = detail::assetRef(id);
726 if (!ref) return Result<PreparedAssetImport>::failure(ref.status());
727 for (const auto& textureGuid : textureGuids) {
728 if (!importedImageAvailable(request, textureGuid)) continue;
729 auto image = detail::assetRef(request.package.packageId.child("unity:" + textureGuid).child("image:default"));
730 if (!image) return Result<PreparedAssetImport>::failure(image.status());
731 out.manifest.dependencies.push_back({ref.value(), image.value(), asset::EvaDependencyKind::RuntimeRequired,
732 "elementTexture:" + textureGuid, {}, "eve.image/3", {}});
733 }
734 const std::string path = "assets/" + id.format() + "/asset.json";
735 const std::vector<std::uint8_t> payload(encoded.value().begin(), encoded.value().end());
736 out.manifest.assets.push_back({ref.value(), "eve.vegetation-scene", SchemaVersion(1), path,
737 detail::sha256(payload), {"vegetation", "scene", "source:unity"}});
738 out.manifest.entrypoints.emplace("default", ref.value());
739 out.entries.push_back({path, payload});
740 out.sourceMappings.push_back({"TVE.Manager", ref.value()});
741 out.findings.push_back({source.path, "TVE.sceneManager", ImportDisposition::Translated,
742 "Global Control, Details, Motion and Volume serialized as native scene state"});
743 out.findings.insert(out.findings.end(), std::make_move_iterator(elementFindings.begin()),
744 std::make_move_iterator(elementFindings.end()));
745
746 auto hierarchy = prepareUnityPrefab(request, source.path);
747 if (!hierarchy) return Result<PreparedAssetImport>::failure(hierarchy.status());
748 const auto templateAsset = std::find_if(hierarchy.value().manifest.assets.begin(),
749 hierarchy.value().manifest.assets.end(), [](const auto& asset) {
750 return asset.type == "eve.scene-template";
751 });
752 if (templateAsset == hierarchy.value().manifest.assets.end())
754 DiagnosticCode::InvariantViolation, "Unity manager scene hierarchy produced no scene template", source.path,
755 {}, "asset.import"));
756 const AssetRef templateRef = templateAsset->asset;
757 out.manifest.dependencies.push_back({templateRef, ref.value(), asset::EvaDependencyKind::RuntimeRequired,
758 "vegetationScene", {}, "eve.vegetation-scene/1", {}});
759 out.manifest.entrypoints.emplace("scene", templateRef);
760 for (auto& asset : hierarchy.value().manifest.assets) out.manifest.assets.push_back(std::move(asset));
761 for (auto& dependency : hierarchy.value().manifest.dependencies)
762 out.manifest.dependencies.push_back(std::move(dependency));
763 for (auto& entry : hierarchy.value().entries) out.entries.push_back(std::move(entry));
764 for (auto& mapping : hierarchy.value().sourceMappings) out.sourceMappings.push_back(std::move(mapping));
765 for (auto& finding : hierarchy.value().findings) out.findings.push_back(std::move(finding));
766 return Result<PreparedAssetImport>::success(std::move(out));
767}
768} // namespace eve::asset_import
769
770// Vegetation material import (previously UnityVegetationMaterial.cpp).
771#include <array>
772#include <cmath>
773#include <limits>
774#include <regex>
776#include "asset/SourcePng.h"
780
781namespace eve::asset_import {
782namespace {
783struct Invalid {};
784std::optional<std::string> match(const std::string& s, const std::string& pattern) {
785 const std::regex expression(pattern);
786 auto it = std::sregex_iterator(s.begin(), s.end(), expression);
787 if (it == std::sregex_iterator()) return {};
788 auto result = (*it)[1].str();
789 if (++it != std::sregex_iterator()) throw Invalid{};
790 return result;
791}
792double numeric(const Value& value) {
793 if (!value.isNumeric()) throw Invalid{};
794 const double n = value.isInt64() ? double(value.asInt()) : value.asDouble();
795 if (!std::isfinite(n) || std::abs(n) > std::numeric_limits<float>::max()) throw Invalid{};
796 return n;
797}
798double scalar(const std::string& text, const std::string& name, double fallback) {
799 const auto raw = match(text, "(?:^|\\n)\\s*- " + name + ": *([^\\r\\n]+)");
800 if (!raw) return fallback;
801 auto decoded = Value::fromJson(*raw);
802 if (!decoded) throw Invalid{};
803 return numeric(decoded.value());
804}
805double importerScalar(const std::string& text, const std::string& name, double fallback) {
806 const auto raw = match(text, "(?:^|\\n)[ \\t]*" + name + ": *([^\\r\\n]+)");
807 if (!raw) return fallback;
808 auto decoded = Value::fromJson(*raw);
809 if (!decoded) throw Invalid{};
810 return numeric(decoded.value());
811}
812std::array<double, 4> vector(const std::string& text, const std::string& name, std::array<double, 4> fallback) {
813 auto raw = match(text, "(?:^|\\n)\\s*- " + name + ": *(\\{[^\\r\\n]+\\})");
814 if (!raw) return fallback;
815 auto value = Value::fromJson(std::regex_replace(*raw, std::regex("([rgba]):"), "\"$1\":"));
816 if (!value || !value.value().isObject()) throw Invalid{};
817 const auto& object = *value.value().getIf<Value::Object>();
818 unsigned i = 0;
819 for (const auto key : {"r", "g", "b", "a"}) {
820 if (!object.contains(key)) throw Invalid{};
821 fallback[i++] = numeric(object.at(key));
822 }
823 return fallback;
824}
825std::optional<std::string> texture(const std::string& text, const std::string& name) {
826 auto block = match(text, "- " + name + ":([\\s\\S]*?)(?:\\n - |\\n m_|$)");
827 if (!block) return {};
828 if (match(*block, R"(m_Texture: *\{fileID: *(0)\})")) return {};
829 auto guid = match(*block, R"(m_Texture: *\{fileID: *2800000, guid: *([0-9a-fA-F]{32}), type: *[23]\})");
830 if (!guid) throw Invalid{};
831 return unity_detail::foldAscii(*guid);
832}
833Result<std::string> texturePath(const UnityProjectImportRequest& request, const std::string& guid) {
834 std::string found;
835 for (const auto& [path, bytes] : request.files)
836 if (path.ends_with(".meta")) {
837 auto id = unity_detail::metaScalar(bytes, "guid", path);
838 if (!id) return Result<std::string>::failure(id.status());
839 if (unity_detail::foldAscii(id.value()) != guid) continue;
840 if (!found.empty())
842 Diagnostic::error(DiagnosticCode::Conflict, "duplicate texture GUID", guid, {}, "asset.import"));
843 found = path.substr(0, path.size() - 5);
844 }
845 if (found.empty() || !request.files.contains(found))
847 Diagnostic::error(DiagnosticCode::NotFound, "TVE texture source is absent", guid, {}, "asset.import"));
848 return Result<std::string>::success(std::move(found));
849}
850Result<Value::Object> textureSampler(const UnityProjectImportRequest& request, const std::string& path) {
851 const bool native = path.ends_with(".asset");
852 const auto& bytes = request.files.at(native ? path : path + ".meta");
853 const std::string settings(bytes.begin(), bytes.end());
854 const auto u = importerScalar(settings, native ? "m_WrapU" : "wrapU", -1);
855 const auto v = importerScalar(settings, native ? "m_WrapV" : "wrapV", -1);
856 for (const auto wrap : {u, v}) {
857 if (wrap != -1 && wrap != 0 && wrap != 1 && wrap != 2 && wrap != 3) throw Invalid{};
858 if (wrap == 3)
860 DiagnosticCode::Unsupported, "texture MirrorOnce addressing is not supported by the canonical sampler",
861 path, {}, "asset.import"));
862 }
863 auto convert = [](double wrap) { return wrap == 1 ? 33071 : wrap == 2 ? 33648 : 10497; };
864 auto filter = importerScalar(settings, native ? "m_FilterMode" : "filterMode", -1);
865 if (filter != -1 && filter != 0 && filter != 1 && filter != 2) throw Invalid{};
866 if (filter == -1) {
867 if (native) return Result<Value::Object>::success({{"wrapS", convert(u)}, {"wrapT", convert(v)}});
868 const auto heightNormal = importerScalar(settings, "convertToNormalMap", 0);
869 if (heightNormal != 0 && heightNormal != 1) throw Invalid{};
870 filter = heightNormal == 1 ? 2 : 1;
871 }
872 const auto mipSetting = importerScalar(settings, native ? "m_MipCount" : "enableMipMap", 1);
873 if (native ? (mipSetting < 1 || mipSetting != std::floor(mipSetting)) : (mipSetting != 0 && mipSetting != 1))
874 throw Invalid{};
875 const bool mipmaps = native ? mipSetting > 1 : mipSetting == 1;
876 const int mag = filter == 0 ? 9728 : 9729;
877 const int min = !mipmaps ? mag : filter == 0 ? 9984 : filter == 2 ? 9987 : 9985;
879 {{"wrapS", convert(u)}, {"wrapT", convert(v)}, {"minFilter", min}, {"magFilter", mag}});
880}
881Result<PreparedAssetImport> ormImage(const UnityProjectImportRequest& request, const std::string& text,
882 const PersistentId& materialId, double occlusion, double smoothness) {
883 std::vector<std::uint8_t> rgba{255, 255, 255, 255};
884 std::uint32_t width = 1, height = 1;
885 auto identity = request.package;
886 identity.packageId = materialId.child("main-orm");
887 if (auto guid = texture(text, "_MainMaskTex")) {
888 auto path = texturePath(request, *guid);
889 if (!path) return Result<PreparedAssetImport>::failure(path.status());
891 {identity, path.value(), request.files.at(path.value()), ImageColorSpace::Linear, "mask", request.limits});
892 if (!imported) return imported;
893 const auto definition = imported.value().manifest.assets.front().definition;
894 for (const auto& entry : imported.value().entries)
895 if (entry.path == definition) {
896 auto cooked = asset::cookCanonicalImageRgba8(entry.bytes, request.files.at(path.value()),
898 if (!cooked) return Result<PreparedAssetImport>::failure(cooked.status());
899 auto read32 = [&](std::size_t p) {
900 const auto& b = cooked.value().bulk;
901 return std::uint32_t(b[p]) | (std::uint32_t(b[p + 1]) << 8) | (std::uint32_t(b[p + 2]) << 16) |
902 (std::uint32_t(b[p + 3]) << 24);
903 };
904 width = read32(8);
905 height = read32(12);
906 rgba.assign(cooked.value().bulk.begin() + 28, cooked.value().bulk.end());
907 }
908 }
909 for (std::size_t p = 0; p < rgba.size(); p += 4) {
910 const auto ao = 255.0 + (double(rgba[p + 1]) - 255.0) * occlusion;
911 const auto roughness = 255.0 - double(rgba[p + 3]) * smoothness;
912 const auto mask = rgba[p + 2];
913 rgba[p] = std::uint8_t(std::lround(ao));
914 rgba[p + 1] = std::uint8_t(std::lround(roughness));
915 rgba[p + 2] = 0;
916 rgba[p + 3] = mask;
917 }
919 if (!png) return Result<PreparedAssetImport>::failure(png.status());
920 return prepareImageImport(
921 {identity, "TVE main ORM", std::move(png).takeValue(), ImageColorSpace::Linear, "orm", request.limits});
922}
923enum class NormalSource { Authored, Height };
924uint32_t normalExtent(uint32_t extent, int mode) {
925 if (mode == 0 || (extent & (extent - 1)) == 0) return extent;
926 uint32_t lower = 1;
927 while (lower <= extent / 2) lower *= 2;
928 if (lower > UINT32_MAX / 2) throw Invalid{};
929 const auto upper = lower * 2;
930 return mode == 3 || (mode == 1 && extent - lower < upper - extent) ? lower : upper;
931}
932struct NormalResizeTap {
933 uint32_t index;
934 double weight;
935};
936std::vector<NormalResizeTap> normalResizeTaps(uint32_t source, uint32_t target, uint32_t coordinate, int algorithm) {
937 if (source == target) return {{coordinate, 1}};
938 const double center = algorithm == 1 && target > source ? double(coordinate) * (source - 1) / (target - 1)
939 : (coordinate + .5) * source / target - .5;
940 std::vector<NormalResizeTap> taps;
941 auto append = [&](int64_t index, double weight) {
942 taps.push_back({uint32_t(std::clamp(index, int64_t(0), int64_t(source - 1))), weight});
943 };
944 if (algorithm == 1) {
945 const auto first = int64_t(std::floor(center));
946 append(first, 1 - (center - first));
947 append(first + 1, center - first);
948 return taps;
949 }
950 const double scale = std::max(double(source) / target, 1.0);
951 const double b = target > source ? 1.0 : 1.0 / 3.0;
952 const double c = target > source ? 0.0 : 1.0 / 3.0;
953 double sum = 0;
954 for (auto index = int64_t(std::floor(center - 2 * scale)); index <= int64_t(std::ceil(center + 2 * scale));
955 ++index) {
956 const double x = std::abs((center - index) / scale);
957 const double weight =
958 x < 1 ? ((12 - 9 * b - 6 * c) * x * x * x + (-18 + 12 * b + 6 * c) * x * x + 6 - 2 * b) / 6
959 : x < 2
960 ? ((-b - 6 * c) * x * x * x + (6 * b + 30 * c) * x * x + (-12 * b - 48 * c) * x + 8 * b + 24 * c) / 6
961 : 0;
962 append(index, weight);
963 sum += weight;
964 }
965 for (auto& tap : taps) tap.weight /= sum;
966 return taps;
967}
968std::vector<double> normalResizeRgb(const std::vector<uint8_t>& bulk, uint32_t width, uint32_t height,
969 uint32_t targetWidth, uint32_t targetHeight, int algorithm) {
970 std::vector<double> rgb(size_t(targetWidth) * targetHeight * 3);
971 for (uint32_t y = 0; y < targetHeight; ++y) {
972 const auto vertical = normalResizeTaps(height, targetHeight, y, algorithm);
973 for (uint32_t x = 0; x < targetWidth; ++x) {
974 const auto horizontal = normalResizeTaps(width, targetWidth, x, algorithm);
975 std::array<double, 3> value{};
976 for (const auto& sy : vertical)
977 for (const auto& sx : horizontal)
978 for (size_t c = 0; c < 3; ++c)
979 value[c] += bulk[28 + (size_t(sy.index) * width + sx.index) * 4 + c] * sy.weight * sx.weight;
980 for (size_t c = 0; c < 3; ++c) {
981 const auto clamped = std::clamp(value[c], 0.0, 255.0);
982 // Unity's default cubic path quantizes after both axes. Convert
983 // to float before rounding to preserve its half-integer boundary.
984 rgb[(size_t(y) * targetWidth + x) * 3 + c] =
985 algorithm == 0 ? double(std::lround(float(clamped))) / 255.0 : clamped / 255.0;
986 }
987 }
988 }
989 return rgb;
990}
991Result<PreparedAssetImport> normalImage(const UnityProjectImportRequest& request, const std::string& path,
992 const PersistentId& materialId, double strength, bool sobel, bool mipmaps,
993 bool flipGreen, NormalSource source) {
994 const bool fromHeight = source == NormalSource::Height;
995 const size_t channels = fromHeight ? 1 : 2;
996 auto identity = request.package;
997 identity.packageId = materialId.child(fromHeight ? "main-height-normal" : "main-authored-normal");
999 fromHeight ? "height" : "normal", request.limits});
1000 if (!image) return image;
1001 const auto definition = image.value().manifest.assets.front().definition;
1002 for (const auto& entry : image.value().entries) {
1003 if (entry.path != definition) continue;
1004 auto cooked =
1006 if (!cooked) return Result<PreparedAssetImport>::failure(cooked.status());
1007 const auto& bulk = cooked.value().bulk;
1008 auto read32 = [&](std::size_t p) {
1009 return std::uint32_t(bulk[p]) | (std::uint32_t(bulk[p + 1]) << 8) | (std::uint32_t(bulk[p + 2]) << 16) |
1010 (std::uint32_t(bulk[p + 3]) << 24);
1011 };
1012 auto width = read32(8), height = read32(12);
1013 const auto& metaBytes = request.files.at(path + ".meta");
1014 const std::string meta(metaBytes.begin(), metaBytes.end());
1015 if (mipmaps && importerScalar(meta, "mipMapMode", 0) != 0)
1017 DiagnosticCode::Unsupported, "normal Kaiser mips are not implemented", path, {}, "asset.import"));
1018 const auto npot = importerScalar(meta, "nPOTScale", 1);
1019 if (npot < 0 || npot > 3 || npot != std::floor(npot)) throw Invalid{};
1020 const auto targetWidth = normalExtent(width, int(npot)), targetHeight = normalExtent(height, int(npot));
1021 std::vector<double> resized;
1022 int resizeAlgorithm = 0;
1023 if (targetWidth != width || targetHeight != height) {
1024 const std::regex algorithms(R"((?:^|\n)[ \t]*resizeAlgorithm: *([^\r\n]+))");
1025 std::optional<int> selected;
1026 for (auto it = std::sregex_iterator(meta.begin(), meta.end(), algorithms); it != std::sregex_iterator();
1027 ++it) {
1028 auto value = Value::fromJson((*it)[1].str());
1029 if (!value) throw Invalid{};
1030 const auto algorithm = numeric(value.value());
1031 if (algorithm != 0 && algorithm != 1) throw Invalid{};
1032 if (selected && *selected != int(algorithm))
1035 "platform-specific normal resize algorithms require target-specific image variants", path, {},
1036 "asset.import"));
1037 selected = int(algorithm);
1038 }
1039 resizeAlgorithm = selected.value_or(0);
1040 if (uint64_t(targetWidth) * targetHeight > request.limits.maximumDecodedBytes / sizeof(double) / 3)
1042 Diagnostic::error(DiagnosticCode::InvalidArgument, "resized normal RGB staging exceeds budget",
1043 path, {}, "asset.import"));
1044 resized = normalResizeRgb(bulk, width, height, targetWidth, targetHeight, resizeAlgorithm);
1045 width = targetWidth;
1046 height = targetHeight;
1047 }
1048 uint32_t w = width, h = height, levels = 0;
1049 uint64_t total = 0;
1050 do {
1051 const uint64_t bytes = uint64_t(w) * h * 4;
1053 bytes > request.limits.maximumDecodedBytes - 28 - total)
1055 DiagnosticCode::InvalidArgument, "normal mip chain exceeds budget", path, {}, "asset.import"));
1056 total += bytes;
1057 ++levels;
1058 if (!mipmaps || (w == 1 && h == 1)) break;
1059 w = std::max(w / 2, 1u);
1060 h = std::max(h / 2, 1u);
1061 } while (true);
1062 if (total > request.limits.maximumSourceBytes ||
1063 uint64_t(width) * height > request.limits.maximumDecodedBytes / sizeof(double) / channels)
1065 Diagnostic::error(DiagnosticCode::InvalidArgument, "normal source or channel staging exceeds budget",
1066 path, {}, "asset.import"));
1067 std::vector<double> heights(size_t(width) * height * channels);
1068 for (size_t i = 0; i < size_t(width) * height; ++i) {
1069 if (!resized.empty()) {
1070 if (fromHeight)
1071 heights[i] = (resized[i * 3] + resized[i * 3 + 1] + resized[i * 3 + 2]) / 3;
1072 else {
1073 heights[i * 2] = resized[i * 3];
1074 heights[i * 2 + 1] = resized[i * 3 + 1];
1075 }
1076 continue;
1077 }
1078 if (fromHeight)
1079 heights[i] = (double(bulk[28 + i * 4]) + bulk[29 + i * 4] + bulk[30 + i * 4]) / 765.0;
1080 else {
1081 heights[i * 2] = double(bulk[28 + i * 4]) / 255.0;
1082 heights[i * 2 + 1] = double(bulk[29 + i * 4]) / 255.0;
1083 }
1084 }
1085 std::vector<uint8_t> rgba;
1086 rgba.reserve(size_t(total));
1087 w = width;
1088 h = height;
1089 for (uint32_t level = 0; level < levels; ++level) {
1090 auto sample = [&](int64_t x, int64_t y) {
1091 x = (x + w) % w;
1092 y = (y + h) % h;
1093 return heights[size_t(y) * w + size_t(x)];
1094 };
1095 const double factor = .04 * (double(w) + h) * (std::pow(10.0, strength) - 1.0);
1096 for (int64_t y = 0; y < h; ++y) {
1097 for (int64_t x = 0; x < w; ++x) {
1098 if (!fromHeight) {
1099 const auto at = (size_t(y) * w + size_t(x)) * 2;
1100 const auto green = flipGreen ? 1.0 - heights[at + 1] : heights[at + 1];
1101 rgba.insert(rgba.end(), {uint8_t(std::lround(heights[at] * 255)),
1102 uint8_t(std::lround(green * 255)), 255, 255});
1103 continue;
1104 }
1105 double dx = sample(x - 1, y) - sample(x + 1, y);
1106 double dy = sample(x, y + 1) - sample(x, y - 1);
1107 if (sobel) {
1108 dx = (sample(x - 1, y - 1) - sample(x + 1, y - 1) + 2 * dx + sample(x - 1, y + 1) -
1109 sample(x + 1, y + 1)) *
1110 .25;
1111 dy = (sample(x - 1, y + 1) - sample(x - 1, y - 1) + 2 * dy + sample(x + 1, y + 1) -
1112 sample(x + 1, y - 1)) *
1113 .25;
1114 }
1115 dx *= factor;
1116 dy *= flipGreen ? -factor : factor;
1117 const double length = std::sqrt(dx * dx + dy * dy + 1.0);
1118 rgba.insert(rgba.end(), {uint8_t(std::lround((dx / length * .5 + .5) * 255)),
1119 uint8_t(std::lround((dy / length * .5 + .5) * 255)), 255, 255});
1120 }
1121 }
1122 if (level + 1 == levels) break;
1123 const uint32_t nextW = std::max(w / 2, 1u), nextH = std::max(h / 2, 1u);
1124 std::vector<double> next(size_t(nextW) * nextH * channels);
1125 for (uint32_t y = 0; y < nextH; ++y) {
1126 for (uint32_t x = 0; x < nextW; ++x) {
1127 const double sx = (x + .5) * w / nextW - .5, sy = (y + .5) * h / nextH - .5;
1128 const auto ix = uint32_t(std::floor(sx)), iy = uint32_t(std::floor(sy));
1129 const double fx = sx - ix, fy = sy - iy;
1130 const auto x1 = std::min(ix + 1, w - 1), y1 = std::min(iy + 1, h - 1);
1131 for (size_t c = 0; c < channels; ++c)
1132 next[(size_t(y) * nextW + x) * channels + c] =
1133 (heights[(size_t(iy) * w + ix) * channels + c] * (1 - fx) +
1134 heights[(size_t(iy) * w + x1) * channels + c] * fx) *
1135 (1 - fy) +
1136 (heights[(size_t(y1) * w + ix) * channels + c] * (1 - fx) +
1137 heights[(size_t(y1) * w + x1) * channels + c] * fx) *
1138 fy;
1139 }
1140 }
1141 heights = std::move(next);
1142 w = nextW;
1143 h = nextH;
1144 }
1145 auto parsed = Value::fromJson(std::string(entry.bytes.begin(), entry.bytes.end()));
1146 if (!parsed) return Result<PreparedAssetImport>::failure(parsed.status());
1147 auto& object = *parsed.value().getIf<Value::Object>();
1148 const auto oldBlob = object.at("blob").asString();
1149 const auto newBlob = definition.substr(0, definition.rfind('/') + 1) + "normal.rgba8-mips";
1150 object["encoding"] = Value("rgba8-mips");
1151 object["blob"] = Value(newBlob);
1152 object["mipCount"] = Value(int64_t(levels));
1153 object["width"] = Value(int64_t(width));
1154 object["height"] = Value(int64_t(height));
1155 object["usage"] = Value("normal");
1156 auto encoded = parsed.value().toJson();
1157 if (!encoded) return Result<PreparedAssetImport>::failure(encoded.status());
1158 auto result = std::move(image).takeValue();
1159 for (auto& output : result.entries) {
1160 if (output.path == definition)
1161 output.bytes.assign(encoded.value().begin(), encoded.value().end());
1162 else if (output.path == oldBlob) {
1163 output.path = newBlob;
1164 output.bytes = std::move(rgba);
1165 }
1166 }
1167 auto& asset = result.manifest.assets.front();
1168 asset.contentHash =
1169 detail::sha256({reinterpret_cast<const uint8_t*>(encoded.value().data()), encoded.value().size()});
1170 asset.tags = {"image", "usage:normal"};
1171 std::erase_if(result.entries, [](const auto& output) { return output.path == "reports/import.json"; });
1172 result.findings = {
1173 {path, fromHeight ? "TextureImporter.HeightNormal" : "TextureImporter.AuthoredNormal",
1175 fromHeight ? "height resampled and normals regenerated independently per mip"
1176 : "linear source RG resampled independently per mip before green flip and quantization"}};
1177 auto report = detail::finalizeImportReport(result, identity, "TVE", "12.6.0",
1178 {{"fromHeight", Value(fromHeight)},
1179 {"npotScale", Value(int64_t(npot))},
1180 {"resizeAlgorithm", Value(int64_t(resizeAlgorithm))},
1181 {"heightScale", Value(strength)},
1182 {"sobel", Value(sobel)},
1183 {"flipGreen", Value(flipGreen)},
1184 {"mipCount", Value(int64_t(levels))}});
1185 if (!report) return Result<PreparedAssetImport>::failure(report.status());
1187 }
1189 Diagnostic::error(DiagnosticCode::NotFound, "normal image definition absent", path, {}, "asset.import"));
1190}
1191} // namespace
1192
1194 const UnitySourceAsset& source) {
1195 const auto& bytes = request.files.at(source.path);
1196 const std::string text(bytes.begin(), bytes.end());
1197 try {
1198 const auto shader = match(text, R"(m_Shader: *\{fileID: *4800000, guid: *([0-9a-fA-F]{32}), type: *3\})");
1199 if (!shader ||
1200 (*shader != "7befaa6f41d00a6478d5f4af21d66518" && *shader != "a933075b367f9b24981408633f72ff34" &&
1201 *shader != "6e6307b56f9201d40ad738f21cf03495" && *shader != "d9a724745053dee46bf301b216cdd348"))
1203 DiagnosticCode::Unsupported, "shader is not an admitted TVE 12.6.0 Plant/Prop material", source.path,
1204 {}, "asset.import"));
1205 auto unit = [](double v) {
1206 if (v < 0 || v > 1) throw Invalid{};
1207 return v;
1208 };
1209 const auto mode = scalar(text, "_RenderMode", 0), cull = scalar(text, "_RenderCull", 0),
1210 clip = scalar(text, "_RenderClip", 1), coverage = scalar(text, "_RenderCoverage", 0),
1211 specular = scalar(text, "_RenderSpecular", 1);
1212 if ((mode != 0 && mode != 1) || cull < 0 || cull > 2 || cull != std::floor(cull) || (clip != 0 && clip != 1) ||
1213 (coverage != 0 && coverage != 1))
1215 DiagnosticCode::InvalidArgument, "TVE render mode, alpha clipping, or cull mode is invalid",
1216 source.path, {}, "asset.import"));
1217 auto color = vector(text, "_MainColor", {1, 1, 1, 1});
1218 auto second = vector(text, "_MainColorTwo", {1, 1, 1, 1});
1219 const auto uv = vector(text, "_MainUVs", {1, 1, 0, 0});
1220 for (unsigned c = 0; c < 4; ++c)
1221 if (color[c] < 0 || second[c] < 0 || (c == 3 && (color[c] > 1 || second[c] > 1))) throw Invalid{};
1222 // These source properties are [HDR] colors: Unity uploads their stored
1223 // values directly, including subunit RGB, even in linear color space.
1224 const auto dual = scalar(text, "_MainColorMode", 0);
1225 if (dual != 0 && dual != 1) throw Invalid{};
1226 const auto occlusion = unit(scalar(text, "_MainOcclusionValue", 0)),
1227 smoothness = unit(scalar(text, "_MainSmoothnessValue", 0));
1228 const auto albedo = unit(scalar(text, "_MainAlbedoValue", 1)),
1229 cutoff = unit(scalar(text, "_AlphaClipValue", .5));
1230 const auto minimum = unit(scalar(text, "_MainMaskMinValue", 0)),
1231 maximum = unit(scalar(text, "_MainMaskMaxValue", 0));
1232 if (float(maximum) - float(minimum) + .0001f == 0) throw Invalid{};
1233 auto manifest = detail::baseManifest(request.package, "eve.unity-tve-material/1");
1234 if (!manifest) return Result<PreparedAssetImport>::failure(manifest.status());
1236 out.manifest = std::move(manifest).takeValue();
1237 const auto id = request.package.packageId.child("unity:" + source.guid + ":2100000");
1238 auto ref = detail::assetRef(id);
1239 if (!ref) return Result<PreparedAssetImport>::failure(ref.status());
1240 Value::Object definition{{"schema", "eve.material"},
1241 {"schemaVersion", 15},
1242 {"shadingModel", "pbr"},
1243 {"surfaceMode", mode == 1 ? "transparent"
1244 : clip == 1 ? "masked"
1245 : "opaque"},
1246 {"doubleSided", cull == 0},
1247 {"cullMode", cull == 0 ? "none" : (cull == 1 ? "back" : "front")},
1248 {"alphaToCoverage", coverage == 1 && clip == 1},
1249 {"baseColor", Value::Array{color[0], color[1], color[2], color[3]}},
1250 {"metallic", 0},
1251 {"roughness", 1},
1252 {"specularFactor", unit(specular)},
1253 {"alphaCutoff", cutoff},
1254 {"albedoTextureStrength", albedo}};
1255 const auto extrasLayer = scalar(text, "_LayerExtrasValue", 0);
1256 if (extrasLayer < 0 || extrasLayer > 8 || extrasLayer != std::floor(extrasLayer)) throw Invalid{};
1257 const auto colorsLayer = scalar(text, "_LayerColorsValue", 0);
1258 if (colorsLayer < 0 || colorsLayer > 8 || colorsLayer != std::floor(colorsLayer)) throw Invalid{};
1259 const auto motionLayer = scalar(text, "_LayerMotionValue", 0);
1260 if (motionLayer < 0 || motionLayer > 8 || motionLayer != std::floor(motionLayer)) throw Invalid{};
1261 const auto vertexLayer = scalar(text, "_LayerVertexValue", 0);
1262 if (vertexLayer < 0 || vertexLayer > 8 || vertexLayer != std::floor(vertexLayer)) throw Invalid{};
1263 auto binary = [&](const char* name, double fallback) {
1264 const auto value = scalar(text, name, fallback);
1265 if (value != 0 && value != 1) throw Invalid{};
1266 return value;
1267 };
1268 definition["vegetationAlpha"] = Value::Object{{"global", unit(scalar(text, "_GlobalAlpha", 1))},
1269 {"variation", unit(scalar(text, "_AlphaVariationValue", .5))},
1270 {"detailFade", binary("_DetailFadeMode", 0) == 1},
1271 {"glancing", unit(scalar(text, "_FadeGlancingValue", 0))},
1272 {"camera", unit(scalar(text, "_FadeCameraValue", 1))},
1273 {"constant", unit(scalar(text, "_FadeConstantValue", 0))}};
1274 const auto emissiveMode = binary("_EmissiveMode", 0);
1275 if (emissiveMode == 1) {
1276 const auto emissiveColor = vector(text, "_EmissiveColor", {0, 0, 0, 0});
1277 for (size_t c = 0; c < 3; ++c)
1278 if (emissiveColor[c] < 0) throw Invalid{};
1279 const auto intensityMode = binary("_EmissiveIntensityMode", 0);
1280 const auto authoredPower = scalar(text, "_EmissiveIntensityValue", 1);
1281 const auto fallbackPower = intensityMode == 0 ? authoredPower : .125 * std::pow(2., authoredPower);
1282 const auto intensity = scalar(text, "_emissive_intensity_value", fallbackPower);
1283 if (intensity < 0 || intensity > 1000000) throw Invalid{};
1284 const auto emissionMinimum = unit(scalar(text, "_EmissiveTexMinValue", 0));
1285 const auto emissionMaximum = unit(scalar(text, "_EmissiveTexMaxValue", 1));
1286 if (float(emissionMaximum) - float(emissionMinimum) + .0001f == 0) throw Invalid{};
1287 definition["emissive"] = Value::Array{emissiveColor[0], emissiveColor[1], emissiveColor[2]};
1288 definition["emissiveStrength"] = intensity;
1289 definition["vegetationEmission"] = Value::Object{{"minimum", emissionMinimum},
1290 {"maximum", emissionMaximum},
1291 {"phase", unit(scalar(text, "_EmissivePhaseValue", 1))},
1292 {"global", unit(scalar(text, "_GlobalEmissive", 1))}};
1293 }
1294 const auto gradientOne = vector(text, "_GradientColorOne", {1, 1, 1, 1});
1295 const auto gradientTwo = vector(text, "_GradientColorTwo", {1, 1, 1, 1});
1296 for (size_t c = 0; c < 3; ++c)
1297 if (gradientOne[c] < 0 || gradientTwo[c] < 0) throw Invalid{};
1298 const auto gradientMinimum = unit(scalar(text, "_GradientMinValue", 0));
1299 const auto gradientMaximum = unit(scalar(text, "_GradientMaxValue", 1));
1300 if (float(gradientMaximum) - float(gradientMinimum) + .0001f == 0) throw Invalid{};
1301 definition["vegetationGradient"] =
1302 Value::Object{{"colorOne", Value::Array{gradientOne[0], gradientOne[1], gradientOne[2]}},
1303 {"colorTwo", Value::Array{gradientTwo[0], gradientTwo[1], gradientTwo[2]}},
1304 {"minimum", gradientMinimum},
1305 {"maximum", gradientMaximum}};
1306 definition["vegetationFields"] =
1307 Value::Object{{"colorsLayer", int64_t(colorsLayer)},
1308 {"colorsUsePivotPosition", binary("_ColorsPositionMode", 0) == 1},
1309 {"extrasLayer", int64_t(extrasLayer)},
1310 {"extrasUsePivotPosition", binary("_ExtrasPositionMode", 0) == 1},
1311 {"motionLayer", int64_t(motionLayer)},
1312 {"vertexLayer", int64_t(vertexLayer)},
1313 {"globalSize", unit(scalar(text, "_GlobalSize", 1))},
1314 {"sizeFadeStart", scalar(text, "_SizeFadeStartValue", 0)},
1315 {"sizeFadeEnd", scalar(text, "_SizeFadeEndValue", 100)}};
1316 auto nonnegative = [&](const char* name, double fallback) {
1317 const auto value = scalar(text, name, fallback);
1318 if (value < 0 || value > 1000000) throw Invalid{};
1319 return value;
1320 };
1321 definition["vegetationMotion"] =
1322 Value::Object{{"dynamicMode", unit(scalar(text, "_VertexDynamicMode", 0))},
1323 {"rigidity", unit(scalar(text, "_MotionPosition_10", .5))},
1324 {"facing", unit(scalar(text, "_MotionFacingValue", .5))},
1325 {"bending", nonnegative("_MotionAmplitude_10", .2)},
1326 {"bendingSpeed", nonnegative("_MotionSpeed_10", 2)},
1327 {"bendingScale", nonnegative("_MotionScale_10", 1)},
1328 {"bendingVariation", nonnegative("_MotionVariation_10", 0)},
1329 {"branch", nonnegative("_MotionAmplitude_20", .2)},
1330 {"rolling", nonnegative("_MotionAmplitude_22", .2)},
1331 {"branchSpeed", nonnegative("_MotionSpeed_20", 6)},
1332 {"branchScale", nonnegative("_MotionScale_20", 3)},
1333 {"branchVariation", nonnegative("_MotionVariation_20", 0)},
1334 {"flutter", nonnegative("_MotionAmplitude_32", .2)},
1335 {"flutterSpeed", nonnegative("_MotionSpeed_32", 20)},
1336 {"flutterScale", nonnegative("_MotionScale_32", 10)},
1337 {"flutterVariation", nonnegative("_MotionVariation_32", 0)},
1338 {"interaction", nonnegative("_InteractionAmplitude", 1)},
1339 {"interactionMask", unit(scalar(text, "_InteractionMaskValue", 1))},
1340 {"perspectivePush", nonnegative("_PerspectivePushValue", 0)},
1341 {"perspectiveNoise", nonnegative("_PerspectiveNoiseValue", 0)},
1342 {"perspectiveAngle", nonnegative("_PerspectiveAngleValue", 1)}};
1343 const auto occlusionColor = vector(text, "_VertexOcclusionColor", {1, 1, 1, .5019608});
1344 for (size_t c = 0; c < 3; ++c)
1345 if (occlusionColor[c] < 0) throw Invalid{};
1346 const auto colorsOcclusionMode = scalar(text, "_VertexOcclusionColorsMode", 0);
1347 if (colorsOcclusionMode != 0 && colorsOcclusionMode != 1) throw Invalid{};
1348 const auto colorsOcclusionMinimum = unit(scalar(text, "_VertexOcclusionMinValue", 0));
1349 const auto colorsOcclusionMaximum = unit(scalar(text, "_VertexOcclusionMaxValue", 1));
1350 if (float(colorsOcclusionMaximum) - float(colorsOcclusionMinimum) + .0001f == 0) throw Invalid{};
1351 const auto colorsIntensity = scalar(text, "_ColorsIntensityValue", 1);
1352 if (colorsIntensity < 0 || colorsIntensity > 2) throw Invalid{};
1353 const auto backfaceNormalMode = scalar(text, "_RenderNormals", 0);
1354 if (backfaceNormalMode < 0 || backfaceNormalMode > 2 || backfaceNormalMode != std::floor(backfaceNormalMode))
1355 throw Invalid{};
1356 definition["vegetationSurface"] = Value::Object{
1357 {"sourceFamily", "tve-12"},
1358 {"overlay", unit(scalar(text, "_GlobalOverlay", 1))},
1359 {"wetness", unit(scalar(text, "_GlobalWetness", 1))},
1360 {"overlayVariation", unit(scalar(text, "_OverlayVariationValue", .5))},
1361 {"overlayProjection", unit(scalar(text, "_OverlayProjectionValue", .5))},
1362 {"vertexOcclusionAlpha", unit(occlusionColor[3])},
1363 {"vertexOcclusionColor", Value::Array{occlusionColor[0], occlusionColor[1], occlusionColor[2]}},
1364 {"invertVertexOcclusion", scalar(text, "_VertexOcclusionOverlayMode", 0) == 1},
1365 {"colors", unit(scalar(text, "_GlobalColors", 1))},
1366 {"colorsIntensity", colorsIntensity},
1367 {"colorsMask", unit(scalar(text, "_ColorsMaskValue", 1))},
1368 {"colorsVariation", unit(scalar(text, "_ColorsVariationValue", .5))},
1369 {"vertexOcclusionMinimum", colorsOcclusionMinimum},
1370 {"vertexOcclusionMaximum", colorsOcclusionMaximum},
1371 {"invertVertexOcclusionColors", colorsOcclusionMode == 1},
1372 {"backfaceNormalMode", int64_t(backfaceNormalMode)}};
1373 const auto detailMode = scalar(text, "_DetailMode", 0);
1374 if (detailMode != 0 && detailMode != 1) throw Invalid{};
1375 if (detailMode == 1) {
1376 const auto detailUv = vector(text, "_SecondUVs", {1, 1, 0, 0});
1377 const auto detailColor = vector(text, "_SecondColor", {1, 1, 1, 1});
1378 const auto detailColorTwo = vector(text, "_SecondColorTwo", {1, 1, 1, 1});
1379 const auto uvMode = scalar(text, "_SecondUVsMode", 0);
1380 if (uvMode < 0 || uvMode > 2 || uvMode != std::floor(uvMode)) throw Invalid{};
1381 auto signedNormal = scalar(text, "_SecondNormalValue", 1);
1382 if (signedNormal < -8 || signedNormal > 8 || detailUv[0] == 0 || detailUv[1] == 0) throw Invalid{};
1383 definition["vegetationDetail"] = Value::Object{
1384 {"value", unit(scalar(text, "_DetailValue", 1))},
1385 {"uvMode", int64_t(uvMode)},
1386 {"inverseUvScale", binary("_SecondUVsScaleMode", 0) == 1},
1387 {"uvScale", Value::Array{detailUv[0], detailUv[1]}},
1388 {"uvOffset", Value::Array{detailUv[2], 1.0 - detailUv[1] - detailUv[3]}},
1389 {"color", Value::Array{detailColor[0], detailColor[1], detailColor[2], detailColor[3]}},
1390 {"colorTwo", Value::Array{detailColorTwo[0], detailColorTwo[1], detailColorTwo[2], detailColorTwo[3]}},
1391 {"colorMode", int64_t(binary("_SecondColorMode", 0))},
1392 {"albedoValue", unit(scalar(text, "_SecondAlbedoValue", 1))},
1393 {"normalValue", signedNormal},
1394 {"normalBlendValue", unit(scalar(text, "_DetailNormalValue", 1))},
1395 {"metallicValue", unit(scalar(text, "_SecondMetallicValue", 0))},
1396 {"occlusionValue", unit(scalar(text, "_SecondOcclusionValue", 1))},
1397 {"smoothnessValue", unit(scalar(text, "_SecondSmoothnessValue", 1))},
1398 {"blendMode", int64_t(binary("_DetailBlendMode", 0))},
1399 {"alphaMode", int64_t(binary("_DetailAlphaMode", 1))},
1400 {"maskMode", int64_t(binary("_DetailMaskMode", 0))},
1401 {"meshMode", int64_t(binary("_DetailMeshMode", 0))},
1402 {"blendMinimum", unit(scalar(text, "_DetailBlendMinValue", 0))},
1403 {"blendMaximum", unit(scalar(text, "_DetailBlendMaxValue", 1))},
1404 {"maskMinimum", unit(scalar(text, "_DetailMaskMinValue", 0))},
1405 {"maskMaximum", unit(scalar(text, "_DetailMaskMaxValue", 1))},
1406 {"meshMinimum", unit(scalar(text, "_DetailMeshMinValue", 0))},
1407 {"meshMaximum", unit(scalar(text, "_DetailMeshMaxValue", 1))}};
1408 }
1409 auto bindWithUv = [&](const std::string& role, const AssetRef& image, const std::array<double, 4>& transform) {
1410 definition[role] = image.format();
1411 definition[role + "Transform"] =
1412 Value::Object{{"scale", Value::Array{transform[0], transform[1]}},
1413 {"offset", Value::Array{transform[2], 1.0 - transform[1] - transform[3]}}};
1414 out.manifest.dependencies.push_back(
1415 {ref.value(), image, asset::EvaDependencyKind::RuntimeRequired, role, {}, "eve.image/3", {}});
1416 };
1417 auto bind = [&](const std::string& role, const AssetRef& image) { bindWithUv(role, image, uv); };
1418 if (auto guid = texture(text, "_MainAlbedoTex")) {
1419 auto path = texturePath(request, *guid);
1420 if (!path) return Result<PreparedAssetImport>::failure(path.status());
1421 auto image = detail::assetRef(request.package.packageId.child("unity:" + *guid).child("image:default"));
1422 if (!image) return Result<PreparedAssetImport>::failure(image.status());
1423 bind("baseColorTexture", image.value());
1424 auto sampler = textureSampler(request, path.value());
1426 definition["baseColorTextureSampler"] = std::move(sampler).takeValue();
1427 }
1428 if (emissiveMode == 1) {
1429 auto guid = texture(text, "_EmissiveTex");
1430 if (!guid) throw Invalid{};
1431 auto sourcePath = texturePath(request, *guid);
1433 auto image = detail::assetRef(request.package.packageId.child("unity:" + *guid).child("image:default"));
1434 if (!image) return Result<PreparedAssetImport>::failure(image.status());
1435 const auto emissiveUv = vector(text, "_EmissiveUVs", {1, 1, 0, 0});
1436 if (emissiveUv[0] == 0 || emissiveUv[1] == 0) throw Invalid{};
1437 bindWithUv("emissiveTexture", image.value(), emissiveUv);
1438 auto sampler = textureSampler(request, sourcePath.value());
1440 definition["emissiveTextureSampler"] = std::move(sampler).takeValue();
1441 }
1442 if (auto guid = texture(text, "_MainNormalTex")) {
1443 auto path = texturePath(request, *guid);
1444 if (!path) return Result<PreparedAssetImport>::failure(path.status());
1445 const auto& bytes = request.files.at(path.value() + ".meta");
1446 const std::string meta(bytes.begin(), bytes.end());
1447 const auto normalType = importerScalar(meta, "textureType", 0);
1448 const auto fromHeight = importerScalar(meta, "convertToNormalMap", 0);
1449 const auto flipGreen = importerScalar(meta, "flipGreenChannel", 0);
1450 if (normalType == 1 && (fromHeight == 0 || fromHeight == 1) && (flipGreen == 0 || flipGreen == 1)) {
1451 auto sampler = textureSampler(request, path.value());
1453 definition["normalTextureSampler"] = std::move(sampler).takeValue();
1454 const auto strength = scalar(text, "_MainNormalValue", 1);
1455 if (strength < -8 || strength > 8) throw Invalid{};
1456 auto image = detail::assetRef(request.package.packageId.child("unity:" + *guid).child("image:default"));
1457 if (!image) return Result<PreparedAssetImport>::failure(image.status());
1458 {
1459 const auto scale = importerScalar(meta, "heightScale", .25);
1460 const auto filter = importerScalar(meta, "normalMapFilter", 0);
1461 if (scale < 0 || scale > 1 || (filter != 0 && filter != 1)) throw Invalid{};
1462 auto generated = normalImage(request, path.value(), id, scale, filter == 1,
1463 importerScalar(meta, "enableMipMap", 1) == 1, flipGreen == 1,
1464 fromHeight == 1 ? NormalSource::Height : NormalSource::Authored);
1465 if (!generated) return generated;
1466 image = Result<AssetRef>::success(generated.value().manifest.assets.front().asset);
1467 for (auto& a : generated.value().manifest.assets) out.manifest.assets.push_back(std::move(a));
1468 for (auto& e : generated.value().entries)
1469 if (e.path.starts_with("assets/")) out.entries.push_back(std::move(e));
1470 for (auto& finding : generated.value().findings) out.findings.push_back(std::move(finding));
1471 }
1472 bind("normalTexture", image.value());
1473 definition["normalEncoding"] = "tve-rg";
1474 definition["normalScale"] = strength;
1475 out.findings.push_back(
1476 {source.path, "Material.TVE.normal", ImportDisposition::Translated,
1477 "authored or height-generated RG linked as linear data; signed strength and fixed-Z "
1478 "reconstruction run after filtering"});
1479 } else {
1480 out.findings.push_back(
1481 {source.path, "Material.TVE.normalImporter", ImportDisposition::Unsupported,
1482 "normal source retained; invalid settings or non-normal importer encoding requires conversion"});
1483 }
1484 }
1485 if (*shader == "a933075b367f9b24981408633f72ff34" || *shader == "d9a724745053dee46bf301b216cdd348") {
1486 auto tint = vector(text, "_SubsurfaceColor", {1, 1, 1, 1});
1487 for (size_t c = 0; c < 3; ++c) {
1488 if (tint[c] < 0) throw Invalid{};
1489 }
1490 const auto power = scalar(text, "_SubsurfaceScatteringValue", 2);
1491 const auto angle = scalar(text, "_SubsurfaceAngleValue", 8);
1492 if (power < 0 || power > 16 || angle < 1 || angle > 16) throw Invalid{};
1493 definition["translucency"] = Value::Object{
1494 {"color", Value::Array{tint[0], tint[1], tint[2]}},
1495 {"intensity", unit(scalar(text, "_SubsurfaceValue", 1))},
1496 {"strength", power},
1497 {"scattering", angle},
1498 {"normalDistortion", unit(scalar(text, "_SubsurfaceNormalValue", 0))},
1499 {"direct", unit(scalar(text, "_SubsurfaceDirectValue", 1))},
1500 {"ambient", unit(scalar(text, "_SubsurfaceAmbientValue", .2))},
1501 {"shadow", unit(scalar(text, "_SubsurfaceShadowValue", 1))},
1502 {"maskAmount",
1503 *shader == "a933075b367f9b24981408633f72ff34" ? unit(scalar(text, "_SubsurfaceMaskValue", 1)) : 0},
1504 {"maskMinimum", minimum},
1505 {"maskMaximum", maximum}};
1506 out.findings.push_back({source.path, "Material.TVE.translucency", ImportDisposition::Translated,
1507 "visible subsurface controls mapped to per-light translucency; field wetness is "
1508 "composed by the vegetation runtime"});
1509 }
1510 if (*shader == "a933075b367f9b24981408633f72ff34" || *shader == "7befaa6f41d00a6478d5f4af21d66518") {
1511 auto highlight = vector(text, "_MotionHighlightColor", {0, 0, 0, 0});
1512 for (size_t c = 0; c < 3; ++c) {
1513 if (highlight[c] < 0) throw Invalid{};
1514 }
1515 definition["motionHighlightColor"] = Value::Array{highlight[0], highlight[1], highlight[2]};
1516 out.findings.push_back(
1517 {source.path, "Material.TVE.motionHighlight", ImportDisposition::Translated,
1518 "Plant motion highlight RGB retained; runtime requires evaluated per-vertex highlight stream"});
1519 }
1520 if (detailMode == 1) {
1521 for (const auto& [property, role] :
1522 std::array<std::pair<const char*, const char*>, 3>{{{"_SecondAlbedoTex", "detailAlbedoTexture"},
1523 {"_SecondNormalTex", "detailNormalTexture"},
1524 {"_SecondMaskTex", "detailMaskTexture"}}}) {
1525 auto guid = texture(text, property);
1526 if (!guid) continue;
1527 auto path = texturePath(request, *guid);
1528 if (!path) return Result<PreparedAssetImport>::failure(path.status());
1529 auto image = detail::assetRef(request.package.packageId.child("unity:" + *guid).child("image:default"));
1530 if (!image) return Result<PreparedAssetImport>::failure(image.status());
1531 definition[role] = image.value().format();
1532 auto sampler = textureSampler(request, path.value());
1534 definition[std::string(role) + "Sampler"] = std::move(sampler).takeValue();
1535 out.manifest.dependencies.push_back({ref.value(),
1536 image.value(),
1538 role,
1539 {},
1540 "eve.image/3",
1541 {}});
1542 }
1543 }
1544 auto orm = ormImage(request, text, id, occlusion, smoothness);
1545 if (!orm) return orm;
1546 const auto mask = orm.value().manifest.assets.front().asset;
1547 bind("metallicRoughnessTexture", mask);
1548 bind("occlusionTexture", mask);
1549 if (auto guid = texture(text, "_MainMaskTex")) {
1550 auto path = texturePath(request, *guid);
1551 if (!path) return Result<PreparedAssetImport>::failure(path.status());
1552 auto sampler = textureSampler(request, path.value());
1554 definition["metallicRoughnessTextureSampler"] = sampler.value();
1555 definition["occlusionTextureSampler"] = std::move(sampler).takeValue();
1556 }
1557 for (auto& a : orm.value().manifest.assets) out.manifest.assets.push_back(std::move(a));
1558 for (auto& e : orm.value().entries)
1559 if (e.path.starts_with("assets/")) out.entries.push_back(std::move(e));
1560 if (dual == 1)
1561 definition["colorMask"] = Value::Object{{"secondary", Value::Array{second[0], second[1], second[2]}},
1562 {"minimum", minimum},
1563 {"maximum", maximum}};
1564 const auto path = "assets/" + id.format() + "/asset.json";
1565 auto json = Value(std::move(definition)).toJson();
1566 if (!json) return Result<PreparedAssetImport>::failure(json.status());
1567 std::vector<std::uint8_t> encoded(json.value().begin(), json.value().end());
1568 out.manifest.assets.push_back({ref.value(),
1569 "eve.material",
1570 SchemaVersion(15),
1571 path,
1572 detail::sha256(encoded),
1573 {"material", "source:unity", "vegetation"}});
1574 out.entries.push_back({path, std::move(encoded)});
1575 out.manifest.entrypoints.emplace("default", ref.value());
1576 out.sourceMappings.push_back({"2100000", ref.value()});
1577 out.findings.push_back({source.path, "Material.TVE.main", ImportDisposition::Translated,
1578 "TVE 12.6.0 primary RGB, albedo, UV transform, AO/smoothness and RGB mask converted"});
1579 out.findings.push_back({source.path, "Material.TVE.renderState", ImportDisposition::Translated,
1580 "specular, facing normal, culling and alpha-to-coverage state translated; "
1581 "Direct/Ambient/Shadow and generated noise/rim declarations are inactive in the "
1582 "inspected 12.6 shader calculations"});
1583 return Result<PreparedAssetImport>::success(std::move(out));
1584 } catch (const Invalid&) {
1586 DiagnosticCode::ParseError, "invalid TVE material saved properties", source.path, {}, "asset.import"));
1587 }
1588}
1589} // namespace eve::asset_import
double z
double y
double x
LogicalId target
Value::Object payload
Duration start
float w
Definition AnimClip.cpp:738
std::map< std::string, std::vector< Key >, std::less<> > channels
std::string selected
std::string output
double volume
AuthorityStoreHandleRef reference
Definition Authority.cpp:24
std::size_t cursor
const std::string & s
std::unordered_map< std::string, QuestRuntime > entries
int mask
float ao
Safe source-image conversion to runtime EVIMG payloads.
float uv
graphics::Texture * albedo
glm::vec4 p[6]
SQObjectPtr key
Definition ECS.cpp:155
std::string name
Definition ECS.cpp:154
std::vector< std::string > fields
Definition ECS.cpp:42
double raw
std::string pattern
float strength
float maximum[3]
float minimum[3]
const GltfImportRequest & request
vk::UniqueSampler sampler
vk::UniqueImage image
wgpu::PopErrorScopeStatus status
glm::vec4 clip
glm::vec4 tint
float u
Definition Grass.cpp:233
glm::vec3 n
Definition Grass.cpp:63
std::array< double, 10 > q
float v
std::int32_t second
std::int32_t c
std::int32_t first
int h
std::uint32_t height
std::uint32_t width
float length
JointPoint2D axis
std::function< Numbers(b3JointId)> read
const ColourScope * parent
std::string local
std::string imported
std::array< float, 4 > rotation
std::array< float, 3 > position
std::array< float, 3 > scale
std::string coverage
Poco::JSON::Object::Ptr result
std::uint64_t bytes
MeleePoint3 b
Definition MeleeHit.cpp:41
MeleePoint3 a
Definition MeleeHit.cpp:40
float roughness
int level
ScriptMotionSinkStore< ScriptMotionSink< MotionColorTraits > > colors
OceanWakeSettings settings
OceanGpuFrameToken token
glm::dvec2 center
glm::dvec3 dx
std::unordered_map< std::string, ShaderEntry > shaders
Definition OnnxGpgpu.cpp:44
Texture * texture
std::string script
Definition PlayHost.cpp:117
std::string path
Definition PlayHost.cpp:111
std::set< std::string > values
std::string body
Object::Ptr value
Shader * shader
float power
Definition RockMesh.cpp:23
double number
bool found
std::string filter
unsigned line
std::string text
ScriptStructure out
std::string_view source
size_t begin
size_t end
std::string kind
std::string string
float dy
Definition Shadow.cpp:151
std::size_t elements
TacticalUnit * unit
Heightmap global
std::string sourcePath
Json object
std::int64_t fileId
Direct Unity text-serialization adapter for TerrainData and Prefab assets.
std::vector< ImportFinding > findings
const AssetImportLimits & limits
std::size_t at
std::int64_t gameObject
double weight
uint32_t index
float highlight
uint64_t identity
Stable asset identity backed by PersistentId.
Definition ResourceRef.h:53
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
Result< std::string > toJson() const
Serialize this value as deterministic compact JSON.
Definition Value.cpp:187
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
std::vector< Value > Array
Definition Value.h:33
static Value array(Array value)
Compatibility factory for an array value.
Definition Value.cpp:128
static Value object(Object value)
Compatibility factory for an object value.
Definition Value.cpp:129
Id128 child(std::string_view role) const noexcept
Derives a deterministic child UUID for a hierarchical identity.
Definition Identity.h:191
size_t size() const
Returns the size of .
Definition Json.cpp:352
int main(int argc, char **argv)
Definition main.cpp:46
Result< std::vector< std::uint8_t > > encodeSourcePng(std::uint32_t width, std::uint32_t height, std::span< const std::uint8_t > pixels, std::uint64_t maximumBytes)
Encode top-down RGBA8 source pixels without transfer conversion.
Definition SourcePng.cpp:14
std::string sha256(std::span< const std::uint8_t > bytes)
Sha 256.
std::string extension(std::string_view name)
Extension.
EVENGINE_API_PLATFORM Result< void > finalizeImportReport(PreparedAssetImport &prepared, const ImportPackageIdentity &package, std::string_view sourceEngine, std::string_view sourceVersion, Value::Object options={})
Append the deterministic mandatory import report and bind it from provenance.
Result< asset::EvaManifest > baseManifest(const ImportPackageIdentity &package, std::string_view importer)
Base manifest.
Result< AssetRef > assetRef(PersistentId id)
Asset ref.
std::string foldAscii(std::string value)
Fold ascii.
Result< std::string > metaScalar(std::span< const std::uint8_t > bytes, std::string_view key, std::string_view path)
Read an unindented scalar from .meta; rejects duplicate keys and binary metadata.
Result< PreparedAssetImport > prepareUnityPrefab(const UnityProjectImportRequest &request, const std::string &path)
Prepare one prefab without copying or re-indexing the source collection.
Result< PreparedAssetImport > prepareUnityVegetationScene(const UnityProjectImportRequest &request, const UnitySourceAsset &source)
Convert a complete TVE manager component set from one Unity scene.
Result< PreparedAssetImport > prepareUnityVegetationMaterial(const UnityProjectImportRequest &request, const UnitySourceAsset &source)
Convert admitted TVE primary material data; remaining source features are reported explicitly.
EVENGINE_API_PLATFORM Result< PreparedAssetImport > prepareImageImport(const ImageImportRequest &request)
Decode image metadata and prepare one canonical eve.image source asset.
Result< CookedCanonicalImage > cookCanonicalImageRgba8(std::span< const std::uint8_t > definition, std::span< const std::uint8_t > encodedSource, std::uint64_t maximumDecodedBytes)
Decode image/2 base images or image/3 explicit linear RGBA8 mip chains into bounded EVIMG.
const Value * field(const Value &value, const char *key)
Borrow an optional object field.
std::variant< std::monostate, std::int64_t, double, std::string, bool > Value
Definition Database.h:27
constexpr HexDirection next(HexDirection d) noexcept
The next direction clockwise (NW wraps to NE).
Definition HexMetrics.h:76
SocketDirection rotate(SocketDirection direction, int degrees)
double dot(ForceVector a, ForceVector b)
Definition ForceMath.h:14
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...
double sample(const Heightmap &map, double u, double v)
Sample.
StrongUuid< detail::PersistentIdTag > PersistentId
Stable instance identity for persistence, networking and process boundaries.
Definition Identity.h:253
detail::StrongUint64< detail::SchemaVersionTag > SchemaVersion
Persistent data-format version; not a runtime replacement generation.
Owning, validated source archive candidate not yet published to disk/database.
In-memory Unity project slice; keys are normalized project-relative paths.
Immutable-by-convention owning source index entry; no borrowed source addresses.
Definition UnitySource.h:38
bool consumed
Definition Graphics.cpp:201
glm::vec4 color