14#include <unordered_map>
20Result<ProceduralDecalRecipe> recipeFailure(std::string
message) {
25Result<ProceduralDecalBake> bakeFailure(std::string
message) {
31 const std::string needle = std::string(
name) +
"=\"";
33 if (
begin == std::string_view::npos)
return std::nullopt;
34 const auto valueBegin =
begin + needle.size();
35 const auto valueEnd =
element.find(
'"', valueBegin);
36 if (valueEnd == std::string_view::npos)
return std::nullopt;
37 return element.substr(valueBegin, valueEnd - valueBegin);
40std::optional<float>
number(std::string_view
text) {
41 if (
text.empty())
return std::nullopt;
42 if (
text.find_first_of(
" \t\n\r\f\v") != std::string_view::npos)
return std::nullopt;
43 const std::string copy(
text);
46 const float value = std::strtof(copy.c_str(), &
end);
47 if (
end != copy.c_str() + copy.size() || errno == ERANGE || !std::isfinite(
value))
return std::nullopt;
53 const auto parsed = std::from_chars(
text.data(),
text.data() +
text.size(),
value);
54 if (parsed.ec != std::errc{} || parsed.ptr !=
text.data() +
text.size())
return std::nullopt;
58std::optional<std::array<float, 3>> color3(std::string_view
text) {
59 std::array<float, 3>
color{};
60 for (std::size_t channel = 0; channel <
color.size(); ++channel) {
61 const auto comma =
text.find(
',');
62 const auto token = comma == std::string_view::npos ?
text :
text.substr(0, comma);
64 if (!
value)
return std::nullopt;
66 if (channel + 1 <
color.size()) {
67 if (comma == std::string_view::npos)
return std::nullopt;
68 text.remove_prefix(comma + 1);
69 }
else if (comma != std::string_view::npos) {
82 return families[std::size_t(magnitude % std::size(families))];
85float clamp01(
float value) {
return std::clamp(
value, 0.f, 1.f); }
88 const float t = clamp01((
value - edge0) / (edge1 - edge0));
89 return t *
t * (3.f - 2.f *
t);
100float random01(std::uint32_t
x, std::uint32_t
y, std::uint32_t
seed) {
101 return float(
hash(
x * 0x9e3779b9u ^
y * 0x85ebca6bu ^
seed)) / float(std::numeric_limits<std::uint32_t>::max());
104float valueNoise(
float x,
float y, std::uint32_t
seed) {
105 const int ix =
static_cast<int>(std::floor(
x));
106 const int iy =
static_cast<int>(std::floor(
y));
107 const float fx =
x - float(ix);
108 const float fy =
y - float(iy);
109 const float sx = fx * fx * (3.f - 2.f * fx);
110 const float sy = fy * fy * (3.f - 2.f * fy);
112 return random01(
static_cast<std::uint32_t
>(
px),
static_cast<std::uint32_t
>(
py),
seed);
115 const float b = std::lerp(
sample(ix, iy + 1),
sample(ix + 1, iy + 1),
sx);
116 return std::lerp(
a,
b,
sy);
119float fractal(
float x,
float y, std::uint32_t
seed) {
122 for (
int octave = 0; octave < 4; ++octave) {
128 return value / 1.03125f;
132 std::uint32_t
seed) {
133 const float x = (
u - 0.5f) *
scale;
134 const float y = (
v - 0.5f) *
scale;
135 const float radius = std::sqrt(
x *
x +
y *
y);
136 const float noise = fractal(
x + 17.1f,
y - 9.7f,
seed);
137 const int family = sourcePatternId >= 0 ? sourcePatternId % 12 :
static_cast<int>(
pattern);
140 const float cells = valueNoise(
x * 2.1f,
y * 2.1f,
seed + 71u);
141 return clamp01((
cells - 0.42f) * 2.8f) * clamp01(1.15f -
radius * 0.55f);
144 const float ridge = 1.f - std::abs(noise * 2.f - 1.f);
145 return clamp01((ridge - 0.76f) * 5.2f) * clamp01(1.2f -
radius * 0.45f);
148 const float streak = fractal(
x * 0.45f,
y * 3.8f,
seed + 191u);
149 return clamp01((streak - 0.38f) * 2.1f) * clamp01(1.1f - std::abs(
x) * 0.22f);
152 const float warpedRadius =
radius * (0.78f + 0.42f * noise);
153 return 1.f -
smoothStep(0.62f, 1.05f, warpedRadius);
155 case 4:
return clamp01((noise - 0.28f) * 1.45f) * clamp01(1.25f -
radius * 0.38f);
157 const float islands = fractal(
x * 1.45f + noise * 0.55f,
y * 1.45f - noise * 0.35f,
159 return clamp01((islands - 0.46f) * 2.65f) * clamp01(1.14f -
radius * 0.48f);
162 const float scratches = fractal((
x +
y) * 4.8f, (
y -
x) * 0.38f,
seed + 313u);
163 return clamp01((scratches - 0.56f) * 3.2f) * clamp01(1.18f -
radius * 0.42f);
166 const float blobs = valueNoise(
x * 1.35f,
y * 1.35f,
seed + 419u);
167 const float drops = valueNoise(
x * 4.7f,
y * 4.7f,
seed + 431u);
168 return clamp01((std::max(blobs, drops * 0.82f) - 0.48f) * 2.7f) *
169 clamp01(1.15f -
radius * 0.46f);
172 const float cells = valueNoise(
x * 2.6f,
y * 2.6f,
seed + 557u);
173 const float edge = 1.f - std::abs(
cells * 2.f - 1.f);
174 return clamp01((
edge - 0.68f) * 4.1f) * clamp01(1.2f -
radius * 0.44f);
177 const float smear = fractal(
x * 2.8f + noise,
y * 0.42f,
seed + 631u);
178 return clamp01((smear - 0.4f) * 2.25f) * clamp01(1.1f -
radius * 0.48f);
181 const float drops = valueNoise(
x * 5.3f,
y * 5.3f,
seed + 743u);
182 return clamp01((drops - 0.63f) * 4.4f) * clamp01(1.16f -
radius * 0.4f);
185 const float coarse = fractal(
x * 0.72f,
y * 0.72f,
seed + 829u);
186 const float fine = fractal(
x * 3.1f,
y * 3.1f,
seed + 853u);
187 return clamp01((coarse * 0.7f + fine * 0.3f - 0.38f) * 2.f) *
188 clamp01(1.22f -
radius * 0.4f);
194std::vector<float> layerMask(
const ProceduralDecalRecipe&
recipe,
const ProceduralDecalLayer&
layer) {
195 const std::size_t
count = std::size_t(
recipe.width) * std::size_t(
recipe.height);
198 const float c = std::cos(
layer.rotation);
199 const float s = std::sin(
layer.rotation);
200 for (
int y = 0;
y <
recipe.height; ++
y) {
202 const float u = (float(
x) + 0.5f) /
float(
recipe.width) - 0.5f;
203 const float v = (float(
y) + 0.5f) /
float(
recipe.height) - 0.5f;
204 const float ru =
c *
u -
s *
v + 0.5f;
205 const float rv =
s *
u +
c *
v + 0.5f;
213 const int radius = std::clamp(
static_cast<int>(std::round(
layer.blur * 12.f)), 0, 12);
215 std::vector<float> horizontal(
count, 0.f);
217 for (
int y = 0;
y <
recipe.height; ++
y) {
221 sum +=
mask[std::size_t(
y) * std::size_t(
recipe.width) +
222 std::size_t(std::clamp(
x +
dx, 0,
recipe.width - 1))];
223 horizontal[std::size_t(
y) * std::size_t(
recipe.width) + std::size_t(
x)] = sum / float(
radius * 2 + 1);
226 for (
int y = 0;
y <
recipe.height; ++
y) {
230 sum += horizontal[std::size_t(std::clamp(
y +
dy, 0,
recipe.height - 1)) * std::size_t(
recipe.width) +
232 result[std::size_t(
y) * std::size_t(
recipe.width) + std::size_t(
x)] = sum / float(
radius * 2 + 1);
238std::uint8_t byte(
float value) {
return static_cast<std::uint8_t
>(std::round(clamp01(
value) * 255.f)); }
240std::array<float, 3> rotateHue(
const std::array<float, 3>&
color,
float angle) {
241 const float c = std::cos(
angle);
242 const float s = std::sin(
angle);
244 clamp01(
color[0] * (0.299f + 0.701f *
c + 0.168f *
s) +
245 color[1] * (0.587f - 0.587f *
c + 0.330f *
s) +
246 color[2] * (0.114f - 0.114f *
c - 0.497f *
s)),
247 clamp01(
color[0] * (0.299f - 0.299f *
c - 0.328f *
s) +
248 color[1] * (0.587f + 0.413f *
c + 0.035f *
s) +
249 color[2] * (0.114f - 0.114f *
c + 0.292f *
s)),
250 clamp01(
color[0] * (0.299f - 0.300f *
c + 1.250f *
s) +
251 color[1] * (0.587f - 0.588f *
c - 1.050f *
s) +
252 color[2] * (0.114f + 0.886f *
c - 0.203f *
s)),
256bool finiteLayer(
const ProceduralDecalLayer&
layer) {
262 return std::all_of(std::begin(
values), std::end(
values), [](
float value) {
return std::isfinite(
value); });
265bool validLayer(
const ProceduralDecalLayer&
layer) {
269 return finiteLayer(
layer) && inRange(
layer.amount, 0.f, 1.f) &&
270 inRange(
layer.scale, 0.001f, 4096.f) && std::abs(
layer.rotation) <= 1000000.f &&
271 inRange(
layer.blur, 0.f, 1.f) && inRange(
layer.contrast, 0.f, 64.f) &&
272 std::all_of(
layer.color.begin(),
layer.color.end(),
273 [&](
float value) { return inRange(value, 0.f, 1.f); }) &&
274 inRange(
layer.colorVariation, 0.f, 1.f) && inRange(
layer.hueVariation, 0.f, 1.f) &&
275 inRange(
layer.roughness, 0.f, 1.f) && inRange(
layer.roughnessVariation, 0.f, 1.f) &&
276 inRange(
layer.metallic, 0.f, 1.f) && inRange(
layer.emissive, 0.f, 1.f) &&
277 inRange(
layer.normalStrength, 0.f, 64.f) && inRange(
layer.normalSoftness, 0.005f, 1.f) &&
278 inRange(
layer.normalTrim, 0.f, 1.f) && inRange(
layer.normalThickness, 0.1f, 16.f) &&
279 layer.normalStyle >= 0 &&
layer.normalStyle <= 16 && inRange(
layer.height, 0.f, 1.f);
284 ProceduralDecalLayer
value;
299 recipe.layerB.amount = 0.45f;
300 recipe.layerB.scale = 9.f;
301 recipe.layerB.blur = 0.04f;
302 if (
name ==
"blood-wet") {
305 }
else if (
name ==
"blood-dried") {
308 }
else if (
name ==
"damage") {
310 recipe.layerA.normalStrength = 5.f;
312 }
else if (
name ==
"dirt") {
315 }
else if (
name ==
"rust") {
318 }
else if (
name ==
"puddle") {
320 recipe.layerB.enabled =
false;
321 }
else if (
name ==
"paint") {
324 }
else if (
name ==
"moss" ||
name ==
"mold" ||
name ==
"lichen") {
325 const std::array<float, 3> base =
326 name ==
"mold" ? std::array<float, 3>{0.08f, 0.11f, 0.075f} : std::array<float, 3>{0.12f, 0.25f, 0.06f};
330 return recipeFailure(
"Unknown procedural decal preset: " + std::string(
name));
333 recipe.layerB.seed ^=
seed * 1664525u + 1013904223u;
338 constexpr std::size_t maxPresetBytes = 1024u * 1024u;
339 if (xml.empty())
return recipeFailure(
"Substance preset document is empty");
340 if (xml.size() > maxPresetBytes)
return recipeFailure(
"Substance preset document exceeds the 1 MiB limit");
341 if (xml.find(
"<sbspresets") == std::string_view::npos || xml.find(
"<sbspreset") == std::string_view::npos)
342 return recipeFailure(
"Input is not a Substance preset document");
344 std::unordered_map<std::string, std::string>
inputs;
346 while ((
cursor = xml.find(
"<presetinput",
cursor)) != std::string_view::npos) {
348 if (
end == std::string_view::npos)
return recipeFailure(
"Unterminated presetinput element");
352 if (!
id || !
value)
return recipeFailure(
"presetinput requires identifier and value attributes");
353 inputs.insert_or_assign(std::string(*
id), std::string(*
value));
356 if (
inputs.empty())
return recipeFailure(
"Substance preset contains no inputs");
359 bool malformedKnownInput =
false;
360 const auto readFloat = [&](std::string_view
name) -> std::optional<float> {
364 malformedKnownInput = malformedKnownInput || !
value.has_value();
367 const auto readInt = [&](std::string_view
name) -> std::optional<int> {
371 malformedKnownInput = malformedKnownInput || !
value.has_value();
375 const std::string
key(prefix);
377 if (
const auto value = readInt(
key +
"pattern")) {
381 if (
const auto value = readFloat(
key +
"tweak"))
target.scale = 1.f + clamp01(*
value) * 11.f;
382 if (
const auto value = readFloat(
key +
"tile"))
target.scale *= std::clamp(*
value, 0.25f, 8.f);
384 if (
const auto value = readFloat(
key +
"blur"))
target.blur = std::max(0.f, *
value) * 0.15f;
385 if (
const auto value = readFloat(
key +
"contrast"))
target.contrast = 0.5f + std::max(0.f, *
value) * 2.f;
386 const auto colorIt =
inputs.find(
key +
"color");
387 if (colorIt !=
inputs.end()) {
388 auto value = color3(colorIt->second);
389 if (!
value)
return false;
392 if (
const auto value = readFloat(
key +
"color_value_variation"))
394 if (
const auto value = readFloat(
key +
"color_hue_variation"))
target.hueVariation = clamp01(*
value);
396 if (
const auto value = readFloat(
key +
"rough_variation"))
400 if (
const auto value = readFloat(
key +
"normal"))
target.normalStrength = std::abs(*
value);
401 if (
const auto value = readFloat(
key +
"normal_softness"))
402 target.normalSoftness = std::clamp(*
value, 0.005f, 1.f);
403 if (
const auto value = readFloat(
key +
"normal_trim"))
target.normalTrim = clamp01(*
value);
404 if (
const auto value = readFloat(
key +
"normal_thickness"))
405 target.normalThickness = std::clamp(*
value, 0.1f, 16.f);
412 if (
const auto seed = readInt(
"$randomseed"))
recipe.seed =
static_cast<std::uint32_t
>(*seed);
413 const auto outputSize =
inputs.find(
"$outputsize");
414 if (outputSize !=
inputs.end()) {
415 const auto comma = outputSize->second.find(
',');
416 if (comma == std::string::npos)
return recipeFailure(
"$outputsize must contain width,height exponents");
417 const auto x = integer(std::string_view(outputSize->second).substr(0, comma));
418 const auto y = integer(std::string_view(outputSize->second).substr(comma + 1));
419 if (!
x || !
y || *
x < 0 || *y < 0 || *x > 12 || *
y > 12)
420 return recipeFailure(
"$outputsize exponents must be in [0, 12]");
424 if (!applyLayer(
"a_",
recipe.layerA) || !applyLayer(
"b_",
recipe.layerB))
425 return recipeFailure(
"Substance preset contains an invalid color value");
426 if (
const auto value = readFloat(
"ab_height_masking"))
427 recipe.layerHeightBlend = clamp01((*
value + 1.f) * 0.5f);
428 if (
const auto value = readFloat(
"ab_balance"))
recipe.layerBalance = clamp01(*
value);
429 if (
const auto value = readInt(
"ab_blendmode"))
recipe.layerBlendMode = *
value;
430 if (malformedKnownInput)
431 return recipeFailure(
"Substance preset contains a malformed recognized numeric value");
439 return bakeFailure(
"Unsupported procedural decal recipe schema version");
441 return bakeFailure(
"Procedural decal dimensions must be in [1, 4096]");
442 if (!validLayer(
recipe.layerA) || !validLayer(
recipe.layerB) ||
443 !std::isfinite(
recipe.layerHeightBlend) ||
recipe.layerHeightBlend < 0.f ||
444 recipe.layerHeightBlend > 1.f || !std::isfinite(
recipe.layerBalance) ||
445 recipe.layerBalance < 0.f ||
recipe.layerBalance > 1.f ||
recipe.layerBlendMode < 0 ||
446 recipe.layerBlendMode > 2 || !std::isfinite(
recipe.opacity) ||
recipe.opacity < 0.f ||
448 return bakeFailure(
"Procedural decal recipe contains values outside supported ranges");
460 std::vector<float> normalHeight(
pixels, 0.f);
463 const float a = maskA[
index] * (2.f * (1.f -
recipe.layerBalance));
464 const float b = maskB[
index] * (2.f *
recipe.layerBalance);
465 const float bWeight =
466 b * clamp01(0.5f + (
recipe.layerB.height -
recipe.layerA.height) *
recipe.layerHeightBlend);
467 const float combined =
recipe.layerBlendMode == 2 ? std::max(
a, bWeight) :
a + bWeight * (1.f -
a);
468 const float alpha = clamp01(combined) *
recipe.opacity;
469 const float mixB = alpha > 1e-6f ? bWeight / std::max(
a + bWeight, 1e-6f) : 0.f;
470 const float variation =
471 random01(
static_cast<std::uint32_t
>(
index % std::size_t(
recipe.width)),
472 static_cast<std::uint32_t
>(
index / std::size_t(
recipe.width)),
recipe.seed + 991u) *
475 const float hueNoise = random01(
static_cast<std::uint32_t
>(
index % std::size_t(
recipe.width)),
476 static_cast<std::uint32_t
>(
index / std::size_t(
recipe.width)),
477 recipe.seed + 1877u) * 2.f - 1.f;
478 const auto colorA = rotateHue(
recipe.layerA.color, hueNoise *
recipe.layerA.hueVariation * 3.14159265f);
479 const auto colorB = rotateHue(
recipe.layerB.color, hueNoise *
recipe.layerB.hueVariation * 3.14159265f);
480 for (
int channel = 0; channel < 3; ++channel) {
481 const float color = std::lerp(colorA[channel], colorB[channel], mixB);
482 const float colorVar = std::lerp(
recipe.layerA.colorVariation,
recipe.layerB.colorVariation, mixB);
483 bake.
albedo[
index * 4u + std::size_t(channel)] = byte(
color * (1.f + variation * colorVar));
487 std::lerp(
recipe.layerA.roughness,
recipe.layerB.roughness, mixB) +
488 variation * std::lerp(
recipe.layerA.roughnessVariation,
recipe.layerB.roughnessVariation, mixB);
494 const float edge0 = std::min(
layer.normalTrim * 0.9f, 0.95f);
495 float shaped = smoothStep(edge0, std::min(1.f, edge0 +
layer.normalSoftness), clamp01(
mask));
496 if (
layer.normalStyle > 0)
497 shaped = std::pow(shaped, 0.65f + 0.1f *
float(
layer.normalStyle % 5));
498 const float thickness = 0.5f + std::log2(1.f +
layer.normalThickness) * 0.75f;
501 normalHeight[
index] = clamp01(normalLayer(
a,
recipe.layerA) + normalLayer(bWeight,
recipe.layerB));
505 for (
int y = 0;
y <
recipe.height; ++
y) {
507 const auto at = [&](
int px,
int py) {
508 return normalHeight[std::size_t(std::clamp(
py, 0,
recipe.height - 1)) * std::size_t(
recipe.width) +
509 std::size_t(std::clamp(
px, 0,
recipe.width - 1))];
511 const std::size_t
index = std::size_t(
y) * std::size_t(
recipe.width) + std::size_t(
x);
512 const float layerMix = maskB[
index] / std::max(maskA[
index] + maskB[
index], 1e-6f);
513 const float strength = std::lerp(
recipe.layerA.normalStrength,
recipe.layerB.normalStrength, layerMix);
516 const float invLength = 1.f / std::sqrt(
nx *
nx +
ny *
ny + 1.f);
519 const float nz = invLength;
Stable, structured diagnostics shared by engine modules.
std::array< float, 3 > scale
std::array< PixelCell, kPixelChunkSize *kPixelChunkSize > cells
std::set< std::string > values
Share string attribute map operations through the Windows Foundation DLL.
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.
static Result success(T value)
Construct a successful result owning value.
static Result failure(Status status)
Construct a failed result from a structured status.
float smoothStep(float value) noexcept
Smooth step.
Result< ProceduralDecalBake > bakeProceduralDecal(const ProceduralDecalRecipe &recipe)
Bake a two-layer decal recipe into renderer-ready texture bytes.
Result< ProceduralDecalRecipe > proceduralDecalPreset(std::string_view name, std::uint32_t seed)
Build a deterministic preset recipe.
DecalPattern
Built-in procedural masks used by a procedural decal layer.
Result< ProceduralDecalRecipe > importProceduralDecalSbsprs(std::string_view xml)
Import one Substance .sbsprs preset into the native version-two recipe.
double sample(const Heightmap &map, double u, double v)
Sample.
int64_t integer(const RuntimeTensor &v, size_t i=0)
Integer.
Owning, renderer-neutral output of one decal bake.
std::vector< std::uint8_t > albedo
std::vector< std::uint8_t > params
std::vector< std::uint8_t > normal
One independently art-directed layer of a procedural decal recipe.
Versioned two-layer authoring recipe analogous to Procedural Decal's Standard graph and material-inst...
static constexpr std::uint32_t kSchemaVersion