Preserve half blend precision across output size expressions

This commit is contained in:
chasse20 committed 2026-11-18 21:21:15 -05:00
1 parent 14be8d0588
commit d98d3fc921
10 files changed
+147 -16

No files matched your search

+7 -2
View File
@@ -117,8 +117,13 @@ pub(crate) fn cook_instance(
.ok_or_else(|| format!("the source output `{}` is missing", port.id))?;
let output = result.outputs.first().ok_or_else(|| format!("the source output `{}` is empty", port.id))?;
let source_base = result.base;
let port_base =
crate::ResolvedBaseParameters { size: source_base.size, size_underflow: source_base.size_underflow, format: source_base.format, ..base };
let port_base = crate::ResolvedBaseParameters {
size: source_base.size,
size_underflow: source_base.size_underflow,
dynamic_size: source_base.dynamic_size,
format: source_base.format,
..base
};
Ok((output.clone(), port_base))
})
.collect()
+26 -1
View File
@@ -164,7 +164,20 @@ pub(crate) fn cook_node(
let key = hash_of(&(
&node.def,
serde_json::to_string(&parameters).unwrap_or_default(),
(w, h, seed, tile, node.disabled, base.size, base.size_underflow, base.format, base.tiling, base.pixel_ratio, base.pixel_size.map(f32::to_bits)),
(
w,
h,
seed,
tile,
node.disabled,
base.size,
base.size_underflow,
base.dynamic_size,
base.format,
base.tiling,
base.pixel_ratio,
base.pixel_size.map(f32::to_bits),
),
&input_keys,
resource_hash,
subgraph_hash,
@@ -213,6 +226,18 @@ pub(crate) fn cook_node(
values
})
} else if let Some(definition) = definition {
if node.def == "blend" && base.format == OutputFormat::F16 {
// Even matching dimensions require half storage when one normalized input has a runtime size.
for ((image, format), port) in inputs.iter_mut().zip(&input_formats).zip(input_ports) {
if matches!(format, OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit)
&& let Some(image) = image
&& (image.width(), image.height()) == (w, h)
&& prepared.source_base(node.id, &port.id, cooked).is_some_and(|source| source.dynamic_size != base.dynamic_size)
{
*image = crate::output_precision::apply(image.clone(), OutputFormat::F16);
}
}
}
let context = CookContext {
input_formats: &input_formats,
format: base.format,
+1 -1
View File
@@ -43,7 +43,7 @@ pub(crate) fn resolve_parameters(
("fx_map", "background", _) if matches!(current, Value::Float4(_)) => ChannelMode::Broadcast,
_ => ChannelMode::Opaque,
};
let value = crate::parameter_function::evaluate(function, expected, variables.to_mut(), base.seed, base.size, channels)
let (value, _) = crate::parameter_function::evaluate(function, expected, variables.to_mut(), base.seed, base.size, channels)
.map_err(|error| format!("function of `{parameter}`: {error}"))?;
let value = current.coerce_json(&serde_json::to_value(value).unwrap_or_default()).ok_or_else(|| format!("invalid function value for `{parameter}`"))?;
parameters.insert(parameter.clone(), value);
+2 -2
View File
@@ -16,7 +16,7 @@ pub(crate) fn evaluate(
seed: u32,
size: [u32; 2],
channels: ChannelMode,
) -> Result<Value, String> {
) -> Result<(Value, bool), String> {
let program = compile(function, seed)?;
let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type());
if program.output_type() != expected as u32 && !widened {
@@ -46,5 +46,5 @@ pub(crate) fn evaluate(
variables.extend(state.assignments().clone());
Ok(value)
Ok((value, program.output_is_literal()))
}
+8 -5
View File
@@ -36,21 +36,24 @@ impl<'a> PreparedGraph<'a> {
.0
.iter()
.filter(|port| port.kind != materialcraft_nodes::PortKind::Value && primary.is_none_or(|primary| port.id == primary))
.find_map(|port| {
let connection = self.index.input_of(id, &port.id)?;
let port_index = self.ports(connection.from).1.iter().position(|output| output.id == connection.from_port)?;
cooked.nodes.get(&connection.from)?.output_base(port_index)
})?;
.find_map(|port| self.source_base(id, &port.id, cooked))?;
// Only bypassed generators take their image dimensions from the input
if !node.disabled && definition.is_some_and(|definition| definition.generator) {
base.size = self.parent_base.size;
base.size_underflow = self.parent_base.size_underflow;
base.dynamic_size = self.parent_base.dynamic_size;
}
Some(base)
}
pub fn source_base(&self, id: NodeId, port: &str, cooked: &crate::Cooked) -> Option<crate::ResolvedBaseParameters> {
let edge = self.index.input_of(id, port)?;
let index = self.ports(edge.from).1.iter().position(|output| output.id == edge.from_port)?;
cooked.nodes.get(&edge.from)?.output_base(index)
}
pub fn ports(&self, id: NodeId) -> (&[Port], &[Port]) {
self.ports.get(&id).map_or((&[], &[]), |(inputs, outputs)| (inputs.as_slice(), outputs.as_slice()))
}
+13 -2
View File
@@ -5,6 +5,9 @@ use std::collections::BTreeMap;
#[serde(rename_all = "camelCase")]
pub struct ResolvedBaseParameters {
pub size: [u32; 2],
/// The texture dimensions depend on a runtime size expression in this path.
#[serde(skip)]
pub dynamic_size: bool,
/// Negative requested exponents on axes whose allocated texture is one texel.
#[serde(skip)]
pub size_underflow: [i32; 2],
@@ -20,6 +23,7 @@ impl ResolvedBaseParameters {
let parent = options.parent_base;
Self {
size: parent.map_or_else(|| graph.size_px(), |base| graph.output_size_px(base.size)),
dynamic_size: graph.absolute_output_size.is_none() && parent.is_some_and(|base| base.dynamic_size),
size_underflow: parent.filter(|_| graph.absolute_output_size.is_none()).map_or([0; 2], |base| base.size_underflow),
seed: parent.map_or(graph.seed as u32, |base| base.seed),
format: parent.map_or(graph.format, |base| base.format),
@@ -31,7 +35,8 @@ impl ResolvedBaseParameters {
pub(crate) fn resolve(base: &BaseParameters, input: Option<Self>, parent: Self) -> Self {
let dimensions = |base: Self| (base.size, base.size_underflow);
let (size_base, underflow) = BaseParameter::OutputSize.inheritance(base).resolve(([1; 2], [0; 2]), input.map(dimensions), dimensions(parent));
let size_mode = BaseParameter::OutputSize.inheritance(base);
let (size_base, underflow) = size_mode.resolve(([1; 2], [0; 2]), input.map(dimensions), dimensions(parent));
let shift: [i32; 2] = std::array::from_fn(|axis| underflow[axis].saturating_add(base.size[axis].clamp(-12, 13)));
// Internal images may be one texel; the editor minimum would break size functions
@@ -46,6 +51,7 @@ impl ResolvedBaseParameters {
Self {
size,
size_underflow,
dynamic_size: size_mode.resolve(false, input.map(|base| base.dynamic_size), parent.dynamic_size),
seed: inherited_seed.wrapping_add(base.seed as u32),
format: BaseParameter::Format.inheritance(base).resolve(base.format, input.map(|base| base.format), parent.format),
tiling: base.tiling_mode.resolve(base.tiling, input.map(|base| base.tiling), parent.tiling),
@@ -98,6 +104,7 @@ pub(crate) fn evaluate(
pixel_ratio_mode: base.pixel_ratio_mode,
};
let mut values = BTreeMap::new();
let mut computed_size = false;
let mut resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
// Size and seed establish the context used by the remaining parameter functions
@@ -119,7 +126,7 @@ pub(crate) fn evaluate(
resolved.size
};
let value = crate::parameter_function::evaluate(
let (value, literal) = crate::parameter_function::evaluate(
function,
parameter.value_type(),
variables.to_mut(),
@@ -128,6 +135,9 @@ pub(crate) fn evaluate(
crate::parameter_function::ChannelMode::Opaque,
)
.map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?;
if parameter == BaseParameter::OutputSize {
computed_size = !literal;
}
parameter.set_value(&mut evaluated, &value)?;
parameter.set_inheritance(&mut evaluated, parameter.inheritance(base));
resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
@@ -136,5 +146,6 @@ pub(crate) fn evaluate(
values.insert(parameter, parameter.value(&evaluated));
}
resolved.dynamic_size |= computed_size;
Ok((resolved, values))
}
+56
View File
@@ -410,6 +410,62 @@ fn bound_image_resizing_filters_rgb_before_grayscale_conversion() {
assert_eq!(image.get(2, 0, false)[0], level * (1.0 / 3.0));
}
#[test]
fn half_blends_store_integer_inputs_on_different_size_paths() {
use materialcraft_core::{BaseParameter, FunctionGraph, OutputFormat, SizeMode};
let mut graph = Graph::new("Blend sizing");
graph.size = [1, 0];
graph.format = OutputFormat::U8;
let [foreground, background] = ["foreground", "background"].map(|identifier| {
let id = graph.add_node("input_grayscale", [0.0; 2]);
let node = graph.node_mut(id).unwrap();
node.params.insert("identifier".into(), Value::Text(identifier.into()));
node.base.size_mode = SizeMode::RelativeToParent;
id
});
let bridge = graph.add_node("dot", [0.0; 2]);
let blend = graph.add_node("blend", [0.0; 2]);
let node = graph.node_mut(blend).unwrap();
node.base.format = OutputFormat::F16;
node.params.insert("opacity".into(), Value::Float(0.4));
graph.connect(foreground, "output", bridge, "input").unwrap();
graph.connect(bridge, "output", blend, "foreground").unwrap();
graph.connect(background, "output", blend, "background").unwrap();
let mut package = Package::new("Blend sizing");
package.graphs.push(graph);
let literal = FunctionGraph::constant(Value::Int2([0, 0]));
let mut runtime = FunctionGraph::default();
let dimensions = runtime.add("get_float2", &[], Some(Value::Text("$size".into())));
let zero = runtime.add_constant(Value::Int2([0, 0]));
runtime.output = Some(runtime.add("sequence", &[dimensions, zero], None));
let mut options = Options::new(&no_res);
for (name, levels) in [("foreground", [71.0, 55.0]), ("background", [155.0, 1.0])] {
options.inputs.insert(name.into(), Image::gray(2, 1, |x, _| levels[x as usize] / 255.0));
}
let cache = Mutex::new(Cache::default());
for (front, back, inherit, expected) in [
(false, false, false, [0x3ef3c000, 0x3db58000]),
(true, false, false, [0x3ef3a000, 0x3db56000]),
(false, true, false, [0x3ef38000, 0x3db58000]),
(true, true, false, [0x3ef38000, 0x3db56000]),
(false, true, true, [0x3ef3a000, 0x3db56000]),
(true, true, true, [0x3ef3c000, 0x3db58000]),
] {
let graph = &mut package.graphs[0];
for (id, dynamic) in [(foreground, front), (background, back)] {
graph.node_mut(id).unwrap().base.functions.insert(BaseParameter::OutputSize, if dynamic { runtime.clone() } else { literal.clone() });
}
graph.node_mut(blend).unwrap().base.size_mode = if inherit { SizeMode::RelativeToInput } else { SizeMode::RelativeToParent };
let result = cook(&package, 0, &options, &cache);
assert!(result.nodes.values().all(|node| node.error.is_none()));
let pixels = result.image(blend, 0).unwrap();
assert_eq!([0, 1].map(|x| pixels.get_gray(x, 0, false).to_bits()), expected);
assert!(cook(&package, 0, &options, &cache).nodes[&blend].cached);
}
}
#[test]
fn bound_image_resizing_reads_the_upstream_float_format_inside_instances() {
use materialcraft_core::{OutputFormat, SizeMode};
+5
View File
@@ -15,6 +15,11 @@ impl Program {
self.instructions.get(self.output).map_or(0, |instruction| instruction.type_code)
}
/// Whether the result depends only on literals and pure operations.
pub fn output_is_literal(&self) -> bool {
self.instructions.get(self.output).is_some_and(|instruction| instruction.literal)
}
pub fn node_type(&self, id: u32) -> Option<u32> {
self.instructions.iter().find(|instruction| instruction.id == id).map(|instruction| instruction.type_code)
}
+26
View File
@@ -209,6 +209,32 @@ Feed an original 128² image to a Pixel Processor and read input zero with the g
For RGBA8 use ((17x+31y) mod 256, floor(255x/127), 255−floor(255y/127), (7x+13y) mod 256). For the floating formats use the signed four-channel input under [3D linear gradient](#3d-linear-gradient). For RGBA16 encode round((channel+4)×65535/8) from that field. The eight grayscale-bridge controls also match all pixels. Their U8 input is (61x+137y+7xy) mod 256. Their U16 input is q=(2029x+4889y+193xy) mod 65536. For floating storage, supply a linear RGB image with the same float32 value q/8191−3.25 in each channel and alpha one, and select a grayscale bridge. The single stored channel is sampled directly. The sixteen comparisons match **262,144/262,144 pixels**, maximum error zero. A separate luminance-only float EXR was readable in the reference app and the current MaterialCraft decoder returned an error for that file.
### Half-precision Crop area and input sizes
| Root | Renders | Exact stored pixels / compared | Maximum error |
|---|---:|---:|---:|
| Color Crop, both outputs | 48 | 377,344/377,344 | 0 |
| Grayscale Crop, both outputs | 48 | 377,344/377,344 | 0 |
Each root produced 256,000 exact U8 pixels, 26,624 U16, 30,720 F16 and 64,000 F32. The four archived renders each expose two image outputs. The remaining runs change storage at the producing node of Output or Area. The formerly mismatching enabled Area renders at 64² now match all 4,096 pixels each. The [earlier Crop controls](#crop-output-and-area) give the source fields, transforms and first exact counts.
For the additional twelve renders per port, use original bytes Hⱼ=((37+13j)x+(29−5j)y+(7+2j)xy+53j) mod 256. Use j=0…3 for RGBA and j=0 for gray. Run native defaults at 16²/seed 47 in F32. Enable Show Crop Area for the remaining cases. At 32²/139 use Input Size (32,64), matrix (.75,−.125,.375,1.25), offset (−.1875,.3125) and filter 0. At 64²/277 use (64,64), (.625,.25,−.375,1.125), (.125,−.25) and filter 1. Run both in all four output formats. At 32²/419 use 16×32 input, Input Size (16,32), identity, offset (.09375,.1875), filter 0 in F16 and F32. Repeat the first changed F16 case at seed 619. These inputs contribute 47,616 exact pixels per root.
With F16 blend output and equal physical extents, normalized integer inputs pass through half storage when the source and blend differ in whether their effective output size depends on a runtime expression. A plain size, a literal Int2 or an expression made solely of constants each use the static path. A getter or assignment sequenced before the same Int2 can change the rounding. A blend inheriting the background size also inherits that dependency. A pass-through node preserves it. The cook cache includes the distinction.
For a two-pixel reproduction, blend foreground bytes (71,55) over background (155,1) at opacity .4. Use a static (0,0) relative size or a sequence that reads the runtime size then returns (0,0). The half output expanded to F32 has bits 3ef3c000 and 3db58000 with both inputs static. Making just the foreground size dynamic changes them to 3ef3a000 and 3db56000. The regression varies both sources and blend inheritance with a shared cache.
| Standalone blend controls | Renders | Exact stored pixels / compared | Largest stored error¹ |
|---|---:|---:|---:|
| Output size read or assignment | 64 | 262,144/262,144 | 0 |
| Size inheritance through two image sources | 96 | 391,540/393,216 | 1 |
| Eleven expressions with byte, word or half inputs | 132 | 540,672/540,672 | 0 |
| Independent foreground, background and opacity sizes | 36 | 147,456/147,456 | 0 |
| Eleven expressions with full-float inputs | 44 | 180,224/180,224 | 0 |
| Different physical extents and equal-size controls | 96 | 293,493/393,216 | 5501 |
¹ Integer errors use stored levels. Floating errors use absolute component differences. For the separate source-depth controls, use a 64² linear field Hⱼ=(((19+16j)x+(13+28j)y+(7+6j)xy+43j) mod 1021)/1019−.03125 for foreground j=0 and background j=1. Change the stored precision, size inheritance and expression independently. Compare all four output formats. The 96 size-inheritance renders match all 98,304 F16 pixels. In that set, 1,674 F32 pixels differ by at most 1.19209290e−7 and two U16 pixels differ by one level. The physical-size controls also exercise 16, 32 and 128 texel inputs to a 64² blend. Those filter results have their own measurements above.
### Crop output and area
The color and grayscale Crop roots each match **229,376/229,376** pixels across both outputs in the four original cases. Use the default graph at 128² and 256² with seed zero, repeat 128² with seed 42, then disable Show Crop Area, set Input Size to (128,128), Matrix to (1.2,.25,−.125,.8), Offset to (.1,−.15), and Filtering to 1 at 128². The inputs are the original foreground or grayscale ramp from the first pass. At 64² seed 42, retaining the 128² original input, these altered settings match a further 32,768/32,768 pixels per root across the two outputs and all four storage formats. Every maximum is zero.
+3 -3
View File
@@ -35,7 +35,7 @@ A graph may accept input pins and still be a root under the dependency criterion
Statuses: **Not checked**, **In progress**, **Parity** (exact pixels or typed values for the linked measured cases), or **Too hard** (reason recorded). Function calls do not count as regular graph dependencies.
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **305 Parity**, **44 In progress** and **197 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons)
The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard**. The current inventory has **307 Parity**, **42 In progress** and **197 Too hard**. The November 17 and 18 comparisons include raw counts, output formats and remaining differences. [November 17 measurements](parity-fixes.md#2026-11-17-root-comparisons) · [November 18 measurements](parity-fixes.md#2026-11-18-root-comparisons)
[Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering)
@@ -166,8 +166,8 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
| [contrast_luminosity.sbs/contrast_luminosity](../assets/sbs/contrast_luminosity.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [contrast_luminosity.sbs/contrast_luminosity_grayscale](../assets/sbs/contrast_luminosity.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [creased.sbs/creased](../assets/sbs/creased.sbs) | 0 | Yes | [Too hard: noise field](parity-fixes.md#remaining-differences) |
| [crop.sbs/crop](../assets/sbs/crop.sbs) | 1 | No | [In progress · output exact, color area differs in half precision](parity-fixes.md#crop-output-and-area) |
| [crop.sbs/crop_grayscale](../assets/sbs/crop.sbs) | 1 | No | [In progress · output exact, grayscale area differs in half precision](parity-fixes.md#crop-output-and-area) |
| [crop.sbs/crop](../assets/sbs/crop.sbs) | 1 | No | [Parity · 48 renders, all 377,344 pixels across both outputs exact](parity-fixes.md#half-precision-crop-area-and-input-sizes) |
| [crop.sbs/crop_grayscale](../assets/sbs/crop.sbs) | 1 | No | [Parity · 48 renders, all 377,344 pixels across both outputs exact](parity-fixes.md#half-precision-crop-area-and-input-sizes) |
| [crystal_1.sbs/crystal_1](../assets/sbs/crystal_1.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |
| [crystal_2.sbs/crystal_2](../assets/sbs/crystal_2.sbs) | 0 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |
| [curvature.sbs/curvature](../assets/sbs/curvature.sbs) | 1 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |