mirror of
https://github.com/storytold/materialcraft.git
synced 2026-11-28 17:19:17 +01:00
Match grayscale Uniform precision to the width and source of its color
This commit is contained in:
1 parent
6f88884d93
commit
b54f750f29
7 files changed
+195
-8
No files matched your search
@@ -10,6 +10,15 @@ pub(crate) struct ResolvedParameters {
|
||||
pub dynamic_blend_opacity: bool,
|
||||
}
|
||||
|
||||
// The color cook needs the operand's original width and whether its channels were folded.
|
||||
fn uniform_color_operand(value: &Value, literal: bool) -> Option<Value> {
|
||||
match value {
|
||||
Value::Float(_) | Value::Float3(_) => Some(value.clone()),
|
||||
Value::Float4(rgba) | Value::Color(rgba) => Some(if literal { Value::Color(*rgba) } else { Value::Float4(*rgba) }),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_parameters(
|
||||
package: &Package,
|
||||
node: &Node,
|
||||
@@ -37,7 +46,11 @@ pub(crate) fn resolve_parameters(
|
||||
|
||||
let mut dynamic = std::collections::BTreeSet::new();
|
||||
let mut dynamic_blend_opacity = false;
|
||||
let mut uniform_color = None;
|
||||
for (parameter, exposed) in &node.bindings {
|
||||
if node.def == "uniform" && parameter == "color" {
|
||||
uniform_color = variables.get(exposed).and_then(|value| uniform_color_operand(value, false));
|
||||
}
|
||||
if node.def == "graph_instance" && !literal_inputs.contains(exposed) {
|
||||
dynamic.insert(parameter);
|
||||
}
|
||||
@@ -56,6 +69,7 @@ pub(crate) fn resolve_parameters(
|
||||
let current = parameters.get(parameter).ok_or_else(|| format!("unknown function parameter `{parameter}`"))?;
|
||||
let expected = ValueType::of(current).ok_or_else(|| format!("parameter `{parameter}` cannot have a function"))?;
|
||||
let channels = match (node.def.as_str(), parameter.as_str(), base.format) {
|
||||
("uniform", "color", _) => ChannelMode::UniformColor,
|
||||
("levels", name, format) if accepts_scalar_function("levels", name) => {
|
||||
ChannelMode::Levels { normalized: name != "in_mid" && matches!(format, OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit) }
|
||||
}
|
||||
@@ -71,6 +85,10 @@ pub(crate) fn resolve_parameters(
|
||||
crate::parameter_function::evaluate(&program, expected, variables.to_mut(), base.size, channels, Some(current))
|
||||
})
|
||||
.map_err(|error| format!("function of `{parameter}`: {error}"))?;
|
||||
if matches!(channels, ChannelMode::UniformColor) {
|
||||
uniform_color = uniform_color_operand(&value, literal);
|
||||
continue;
|
||||
}
|
||||
if matches!(channels, ChannelMode::GrayPatternOpacity) {
|
||||
// Keep the result in floating point until blending. JSON and slider limits lose signed infinities.
|
||||
gray_pattern_opacity = Some(value);
|
||||
@@ -91,6 +109,9 @@ pub(crate) fn resolve_parameters(
|
||||
parameters.insert(parameter.clone(), value);
|
||||
}
|
||||
|
||||
if let Some(color) = uniform_color {
|
||||
parameters.insert("color".into(), color);
|
||||
}
|
||||
// Catalog limits keep values from files and functions within safe cook bounds
|
||||
if let Some(definition) = definition
|
||||
&& node.def != "graph_instance"
|
||||
@@ -111,6 +132,14 @@ pub(crate) fn resolve_parameters(
|
||||
|
||||
pub(crate) fn inspection_parameters(node: &Node, parameters: &mut BTreeMap<String, Value>) {
|
||||
parameters.retain(|name, value| {
|
||||
if node.def == "uniform" && name == "color" {
|
||||
match value {
|
||||
Value::Float(level) => *value = Value::Color([*level, *level, *level, 1.0]),
|
||||
Value::Float3([r, g, b]) => *value = Value::Color([*r, *g, *b, 1.0]),
|
||||
Value::Float4(rgba) => *value = Value::Color(*rgba),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Value::Float(level) = value
|
||||
&& node.def == "levels"
|
||||
&& accepts_scalar_function("levels", name)
|
||||
@@ -127,6 +156,106 @@ mod tests {
|
||||
use materialcraft_core::{FunctionGraph, Graph, Package, Value, ValueType};
|
||||
use std::sync::Mutex;
|
||||
|
||||
#[test]
|
||||
fn uniform_gray_preserves_the_precision_of_its_color_source() {
|
||||
use materialcraft_core::OutputFormat;
|
||||
|
||||
let mut graph = Graph::new("Uniform precision");
|
||||
graph.size = [2; 2];
|
||||
graph.format = OutputFormat::F32;
|
||||
let uniform = graph.add_node("uniform", [0.0; 2]);
|
||||
graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false));
|
||||
let mut package = Package::new("Uniform precision");
|
||||
package.graphs.push(graph);
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let mut options = Options::new(&|_| None);
|
||||
let scalar = Value::Float(f32::from_bits(0x3ed5_1632));
|
||||
let rgba = Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375]);
|
||||
for (value, bound, expected) in [
|
||||
(rgba.clone(), false, 0x332a_aaab),
|
||||
(rgba.clone(), true, 0x3300_0000),
|
||||
(scalar, true, 0x3ed5_1632),
|
||||
(Value::Float3([0.125, 0.3125, 0.6875]), true, 0),
|
||||
(Value::Float4([-65536.0, 65536.0, 0.001953125, 0.5]), false, 0x3a2a_aaab),
|
||||
(rgba, false, 0x332a_aaab),
|
||||
] {
|
||||
let function = if bound {
|
||||
let get = FunctionGraph::input("ink", ValueType::of(&value).unwrap());
|
||||
options.overrides.insert("ink".into(), value);
|
||||
get
|
||||
} else {
|
||||
FunctionGraph::constant(value)
|
||||
};
|
||||
package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
|
||||
let cooked = cook(&package, 0, &options, &cache);
|
||||
assert_eq!(cooked.nodes[&uniform].error, None);
|
||||
assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grayscale_uniform_distinguishes_image_size_from_an_exposed_color_read() {
|
||||
use materialcraft_core::OutputFormat;
|
||||
|
||||
let mut graph = Graph::new("Uniform sources");
|
||||
graph.size = [2; 2];
|
||||
graph.format = OutputFormat::F32;
|
||||
let uniform = graph.add_node("uniform", [0.0; 2]);
|
||||
graph.node_mut(uniform).unwrap().params.insert("color_mode".into(), Value::Bool(false));
|
||||
let mut package = Package::new("Uniform sources");
|
||||
package.graphs.push(graph);
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let mut options = Options::new(&|_| None);
|
||||
options.overrides.insert("ink".into(), Value::Float4([0.25; 4]));
|
||||
|
||||
for (variable, ty, expected) in [
|
||||
("$size", ValueType::Float2, 0x332a_aaab),
|
||||
("$pixelratio", ValueType::Integer, 0x332a_aaab),
|
||||
("$uvtile", ValueType::Integer2, 0x332a_aaab),
|
||||
("$physicalsize", ValueType::Float3, 0x332a_aaab),
|
||||
("unbound_color", ValueType::Float, 0x332a_aaab),
|
||||
("$time", ValueType::Float, 0x3300_0000),
|
||||
("$normalformat", ValueType::Integer, 0x3300_0000),
|
||||
("ink", ValueType::Float4, 0x3300_0000),
|
||||
] {
|
||||
let mut function = FunctionGraph::input(variable, ty);
|
||||
let read = function.output.unwrap();
|
||||
let rgba = function.add_constant(Value::Float4([1.0, f32::EPSILON, -1.0, 0.59375]));
|
||||
function.output = Some(function.add("sequence", &[read, rgba], None));
|
||||
package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
|
||||
let cooked = cook(&package, 0, &options, &cache);
|
||||
assert_eq!(cooked.nodes[&uniform].error, None);
|
||||
assert_eq!(cooked.image(uniform, 0).unwrap().get_gray(0, 0, false).to_bits(), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uniform_color_keeps_hdr_channels_and_distinguishes_an_explicit_alpha() {
|
||||
use materialcraft_core::OutputFormat;
|
||||
|
||||
let mut graph = Graph::new("Uniform channels");
|
||||
graph.size = [2; 2];
|
||||
graph.format = OutputFormat::F32;
|
||||
let uniform = graph.add_node("uniform", [0.0; 2]);
|
||||
let mut package = Package::new("Uniform channels");
|
||||
package.graphs.push(graph);
|
||||
let cache = Mutex::new(Cache::default());
|
||||
let mut options = Options::new(&|_| None);
|
||||
let rgb = [-65536.0, 65536.0, 0.001953125];
|
||||
options.overrides.insert("ink".into(), Value::Float3(rgb));
|
||||
let direct = FunctionGraph::input("ink", ValueType::Float3);
|
||||
let mut with_alpha = direct.clone();
|
||||
let color = with_alpha.output.unwrap();
|
||||
let alpha = with_alpha.add_constant(Value::Float(0.59375));
|
||||
with_alpha.output = Some(with_alpha.add("vector4", &[color, alpha], None));
|
||||
for (function, expected) in [(direct, [0.0, 0.0, 0.0, 1.0]), (with_alpha, [rgb[0], rgb[1], rgb[2], 0.59375])] {
|
||||
package.graphs[0].node_mut(uniform).unwrap().functions.insert("color".into(), function);
|
||||
let cooked = cook(&package, 0, &options, &cache);
|
||||
assert_eq!(cooked.nodes[&uniform].error, None);
|
||||
assert_eq!(cooked.image(uniform, 0).unwrap().get(0, 0, false), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn gray_levels_keep_scalar_endpoints_distinct_from_equal_rgb_controls() {
|
||||
use craft_texture::Image;
|
||||
|
||||
@@ -6,6 +6,7 @@ use std::collections::BTreeMap;
|
||||
pub(crate) enum ChannelMode {
|
||||
Opaque,
|
||||
Broadcast,
|
||||
UniformColor,
|
||||
GrayPatternOpacity,
|
||||
Levels { normalized: bool },
|
||||
}
|
||||
@@ -26,7 +27,7 @@ pub(crate) fn evaluate(
|
||||
if let Some(value) = fallback
|
||||
&& program.input_identifier().is_some_and(|name| !name.starts_with('$') && !variables.contains_key(name))
|
||||
{
|
||||
return Ok((value.clone(), false));
|
||||
return Ok((value.clone(), matches!(channels, ChannelMode::UniformColor)));
|
||||
}
|
||||
|
||||
let context = EvaluationContext {
|
||||
@@ -47,6 +48,7 @@ pub(crate) fn evaluate(
|
||||
// A scalar level is already luminance. Its RGB expansion would introduce a second rounding.
|
||||
let scalar_level = matches!(channels, ChannelMode::Levels { .. }) && program.output_type() == ValueType::Float as u32;
|
||||
let value = match value {
|
||||
value if matches!(channels, ChannelMode::UniformColor) => value,
|
||||
Value::Float(level) | Value::Float4([level, _, _, _]) if scalar_level => Value::Float(level),
|
||||
Value::Float(level) if widened && matches!(channels, ChannelMode::Broadcast) => Value::Float4([level; 4]),
|
||||
Value::Float(level) if widened => Value::Float4([level, level, level, 1.0]),
|
||||
@@ -54,7 +56,10 @@ pub(crate) fn evaluate(
|
||||
value => value,
|
||||
};
|
||||
|
||||
let fixed = match channels {
|
||||
ChannelMode::UniformColor => program.uses_fixed_uniform_color(variables),
|
||||
_ => program.output_is_literal(),
|
||||
};
|
||||
variables.extend(state.assignments().clone());
|
||||
|
||||
Ok((value, program.output_is_literal()))
|
||||
Ok((value, fixed))
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
use super::ATOMIC;
|
||||
use crate::{CookContext, CookResult, NodeDefinition, node};
|
||||
use craft_texture::{Image, Kind};
|
||||
use materialcraft_core::Value;
|
||||
|
||||
pub(super) fn definition() -> NodeDefinition {
|
||||
node("uniform", "Uniform color", ATOMIC)
|
||||
@@ -14,10 +15,18 @@ pub(super) fn definition() -> NodeDefinition {
|
||||
}
|
||||
|
||||
fn uniform(context: &CookContext) -> CookResult {
|
||||
let color = context.v4("color");
|
||||
let source = context.value("color");
|
||||
// A three-component function needs an explicit alpha to supply this property.
|
||||
let color = if matches!(source, Some(Value::Float3(_))) { [0.0, 0.0, 0.0, 1.0] } else { context.v4("color") };
|
||||
|
||||
Ok(vec![if !context.b("color_mode") {
|
||||
Image::filled(context.w, context.h, Kind::Gray, [(color[0] + color[1] + color[2]) / 3.0; 4])
|
||||
let gray = match source {
|
||||
Some(Value::Float(level)) => *level,
|
||||
// Runtime RGBA rounds each channel's contribution before accumulating the three.
|
||||
Some(Value::Float4([r, g, b, _])) => r * (1.0 / 3.0) + g * (1.0 / 3.0) + b * (1.0 / 3.0),
|
||||
_ => (color[0] + color[1] + color[2]) / 3.0,
|
||||
};
|
||||
Image::filled(context.w, context.h, Kind::Gray, [gray; 4])
|
||||
} else {
|
||||
Image::filled(context.w, context.h, Kind::Color, color)
|
||||
}])
|
||||
|
||||
@@ -32,6 +32,25 @@ impl Program {
|
||||
self.instructions.get(self.output).is_some_and(|instruction| instruction.literal)
|
||||
}
|
||||
|
||||
/// A grayscale Uniform folds its channel mean when its property has only fixed operands.
|
||||
pub fn uses_fixed_uniform_color(&self, variables: &std::collections::BTreeMap<String, Value>) -> bool {
|
||||
self.instructions.iter().all(|op| {
|
||||
op.literal
|
||||
|| op.depends_only_on_operands()
|
||||
|| op.definition.id == "isdefined"
|
||||
|| match (&op.value, op.definition.id) {
|
||||
(Some(Value::Text(name)), getter) if getter.starts_with("get_") && !name.starts_with('$') => !variables.contains_key(name),
|
||||
(Some(Value::Text(name)), "get_float2") => matches!(name.as_str(), "$size" | "$sizelog2"),
|
||||
(Some(Value::Text(name)), "get_integer1") => {
|
||||
matches!(name.as_str(), "$tiling" | "$pixelratio") || super::SystemVariable::named(name).is_none()
|
||||
}
|
||||
(Some(Value::Text(name)), "get_integer2") => name == "$uvtile",
|
||||
(Some(Value::Text(name)), "get_float3") => name == "$physicalsize",
|
||||
_ => false,
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
/// Whether the property reads a bound graph parameter, even if its final value is constant.
|
||||
pub fn reads_graph_parameter(&self, variables: &std::collections::BTreeMap<String, Value>) -> bool {
|
||||
self.instructions.iter().any(|op| {
|
||||
|
||||
@@ -41,9 +41,10 @@ pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap<String, V
|
||||
continue;
|
||||
}
|
||||
|
||||
// These colors supply image samples, including signed HDR values.
|
||||
let image_color = matches!((definition.id, parameter.id), ("fx_map", "background") | ("uniform", "color"));
|
||||
if let Value::Color(components) = value {
|
||||
// A pattern background supplies image samples, including signed HDR values.
|
||||
let (lo, hi) = if (definition.id, parameter.id) == ("fx_map", "background") { (f32::MIN, f32::MAX) } else { (-HARD_SPAN, 1.0 + HARD_SPAN) };
|
||||
let (lo, hi) = if image_color { (f32::MIN, f32::MAX) } else { (-HARD_SPAN, 1.0 + HARD_SPAN) };
|
||||
for component in components {
|
||||
*component = clamp_finite(*component, lo, hi, 0.0);
|
||||
}
|
||||
@@ -59,7 +60,7 @@ pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap<String, V
|
||||
// The pattern renderer bounds copy count and pixel work using the resolved region.
|
||||
| ("fx_map", "roughness" | "opacity" | "tiling_region")
|
||||
);
|
||||
let ranged = parameter.min < parameter.max && !unbounded;
|
||||
let ranged = parameter.min < parameter.max && !unbounded && (definition.id, parameter.id) != ("uniform", "color");
|
||||
let span = parameter.max - parameter.min;
|
||||
let (lo, hi) = if ranged { (parameter.min - HARD_SPAN * span, parameter.max + HARD_SPAN * span) } else { (f32::MIN, f32::MAX) };
|
||||
|
||||
|
||||
@@ -1636,6 +1636,28 @@ Twenty-three pairs have identical coefficients at all five extents, and one diff
|
||||
|
||||
The 480 original branch renders matched **351,169/491,520** whole RGB pixels across applications, maximum 1.78813934e-07. Save the three graphs in MaterialCraft, reopen them in both applications and repeat the first and last extents at both sizes. All sixteen named outputs reproduced their own originals in each application. Across applications, the 192 reopened renders matched **142,599/196,608**, maximum 1.78813934e-07. Both HQ blur roots remain in progress.
|
||||
|
||||
### Uniform channel width and grayscale rounding in node properties
|
||||
|
||||
Grayscale Uniform preserves a scalar input directly. A fixed four-component color sums red, green and blue in that order, then divides by three. A runtime four-component color multiplies each of those channels by F32(1/3) first, then adds the three rounded contributions from left to right. Alpha does not enter the mean. A three-component function result yields zero in grayscale and opaque black in RGBA. Packing the same RGB with an explicit alpha restores its color. Graph inspection keeps the original RGB parameter available.
|
||||
|
||||
Use (1,2⁻²³,−1,.59375) to distinguish the two means. The fixed F32 result has bits `332aaaab` and the exposed result has bits `33000000`. A fixed signed tuple (−65536,65536,2⁻⁹,.5) yields `3a2aaaab`. Feed the scalar with bits `3ed51632` to either channel mode. In grayscale, it retains that word. The controls also cover three primaries, equal-channel levels, signed colors and permutations of nearly canceling channels.
|
||||
|
||||
For the first dependency series, compare a literal, a folded sum with zero, a bound RGBA color, the same color plus a zero vector, and a sequence that reads the bound color before returning the literal. Also read image size before the literal, take alpha from the bound input, select between the bound and fixed colors, return a scalar channel, or return a scalar after reading size. Use the signed tuple above, (1.75,−.875,−.25,.5), (.1,.1,.1,.25), three copies of `3ed51632` with alpha .875, the HDR cancellation tuple, and (−.4,1.875,.1375,−.5). At tuple j use seed 116491 + 17j, width 16 for even j and 8 for odd j, and height 8 when j is divisible by three and 4 otherwise. Compare F32 at all six and all four formats at j = 0, 2 and 4.
|
||||
|
||||
For the last two series, return the signed cancellation tuple after reading the source, or make its green component (1 + source) × 2⁻²³. Render grayscale and RGBA at 8 × 4, 16 × 8, 32 × 16 and 64 × 16. Use seeds 31, 12071, 68047 and 471817 and exposed scalar values .03125, .25, .875 and 1. Size uses the first width divided by 16, and log size uses the first exponent divided by four. Compare fixed arithmetic after size, log size, tiling, pixel ratio, UV tile, physical size, an unbound integer seed, an invented reserved integer and absent user inputs. Definedness tests on time, the exposed input, a missing input and pixel ratio also use the fixed mean. Reading time, normal format or an exposed value, performing a random draw, and writing a named value use the runtime mean. Both the direct and sequence forms are measured.
|
||||
|
||||
| Raw image comparison | Renders | Exact before / compared | Maximum before by storage (U8 / U16 / F16 / F32) | Exact after / compared | Maximum after |
|
||||
|---|---:|---:|---|---:|---:|
|
||||
| Fixed and exposed colors | 192 | 27,456/27,648 | 0 / 0 / 0 / 2.98023224e-08 | 27,648/27,648 | 0 |
|
||||
| Permutations, equal channels and cancellation | 116 | 1,088/7,424 | — / — / — / 0.895311117 | 7,424/7,424 | 0 |
|
||||
| Scalar, RGB and RGBA endpoints | 246 | 4,992/7,872 | 255 / 65535 / 1.3125 / 1.3125 | 7,872/7,872 | 0 |
|
||||
| Packing, selecting and binding channels | 329 | 5,984/10,528 | — / 45055 / — / 65520 | 10,528/10,528 | 0 |
|
||||
| Folded, bound and sequenced colors | 300 | 19,840/23,040 | 85 / 21845 / 65488 / 65520 | 23,040/23,040 | 0 |
|
||||
| Image size, seed, time, random draws and assignments | 160 | 54,272/67,840 | — / — / — / 1.98682173e-08 | 67,840/67,840 | 0 |
|
||||
| Other system variables, missing inputs and definedness | 160 | 64,448/67,840 | — / — / — / 9.93410865e-09 | 67,840/67,840 | 0 |
|
||||
|
||||
Across the seven series, **212,192/212,192** raw pixels matched across 1,503 renders. Save twelve of the system-variable and source graphs and reopen them in both applications. All 20,352/20,352 pixels matched in 48 F32 renders. The earlier 16 saved graphs cover widths, direct links, folded and bound parameters and extreme colors. All 5,568/5,568 pixels matched across 78 reopens. Both applications reproduced their own original buffers. The three regressions failed on the earlier evaluation paths and passed after correction. The 413 release node and evaluation tests, strict Clippy, formatting, layering and all ten WebAssembly checks passed using the committed resource set. In a separate control with the pattern random-order changes disabled, the grayscale and color tile generators and both random tiling roots matched the earlier totals of 757,504/757,504, 621,344/765,184, 291,084/316,672, 498,989/619,776, respectively.
|
||||
|
||||
## 2026-11-20 root comparisons
|
||||
|
||||
### Hue, saturation, lightness and Replace Color
|
||||
|
||||
@@ -49,6 +49,8 @@ Odd-sized grayscale bitmap resources match 116,736/116,736 pixels directly and 9
|
||||
|
||||
Linear RGBA bitmap resources match 108,544/108,544 pixels on two procedural fields. [Exact counts by format and saved-package results](parity-fixes.md#stored-levels-of-linear-color-bitmap-resources)
|
||||
|
||||
Uniform source and channel-width controls matched 212,192/212,192 pixels across 1,503 renders. The material and blending roots also retained their [rectangular comparisons](parity-fixes.md#rectangular-inputs-and-reopened-outputs-on-seven-roots). [Measurements and saved packages](parity-fixes.md#uniform-channel-width-and-grayscale-rounding-in-node-properties)
|
||||
|
||||
Node-property integer reads and Blend property controls matched 330,080/330,080 pixels across 203 renders, including 40 previously failed cooks. [Measurements and saved packages](parity-fixes.md#unbound-integer-variables-in-node-properties)
|
||||
|
||||
Automatic samples of an embedded bitmap changed on repeated reference renders in three of five dimension pairs. The U16 Bitmap buffers and explicit bilinear samples were stable. [Raw readbacks in both render orders](parity-fixes.md#first-and-repeated-automatic-samples-of-an-embedded-bitmap)
|
||||
|
||||
Reference in new issue
Block a user