Normalize integer Levels endpoints and preserve scalar channel alpha

This commit is contained in:
chasse20 committed 2026-11-18 12:54:05 -05:00
1 parent 313bf96d40
commit 83516a4bfa
12 files changed
+154 -62

No files matched your search

+1 -1
View File
@@ -132,7 +132,7 @@ pub(crate) fn cook_node(
}
let seed = base.seed;
let mut parameters = match resolve_parameters(package, node, definition, &mut variables, seed, base.size) {
let mut parameters = match resolve_parameters(package, node, definition, &mut variables, base) {
Ok(parameters) => parameters,
Err(error) => return fail(error, 0),
};
+9 -10
View File
@@ -1,4 +1,5 @@
use materialcraft_core::{Node, Package, Value, ValueType};
use crate::{ResolvedBaseParameters, parameter_function::ChannelMode};
use materialcraft_core::{Node, OutputFormat, Package, Value, ValueType};
use materialcraft_nodes::{NodeDefinition, ParameterDescriptor, clamp_params, resolve_params};
use std::collections::BTreeMap;
@@ -7,8 +8,7 @@ pub(crate) fn resolve_parameters(
node: &Node,
definition: Option<&NodeDefinition>,
variables: &mut std::borrow::Cow<'_, BTreeMap<String, Value>>,
seed: u32,
size: [u32; 2],
base: ResolvedBaseParameters,
) -> Result<BTreeMap<String, Value>, String> {
let mut parameters = match definition {
Some(definition) if node.def != "graph_instance" => resolve_params(definition, &node.params),
@@ -38,14 +38,13 @@ pub(crate) fn resolve_parameters(
for (parameter, function) in &node.functions {
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 allow_scalar = materialcraft_nodes::accepts_scalar_function(&node.def, parameter);
let value = crate::parameter_function::evaluate(function, expected, variables.to_mut(), seed, size, allow_scalar)
.map_err(|error| format!("function of `{parameter}`: {error}"))?;
let value = match (current, value) {
(Value::Float4(_), Value::Float(value)) if allow_scalar => Value::Float4([value; 4]),
(Value::Color(_), Value::Float(value)) if allow_scalar => Value::Float4([value, value, value, 1.0]),
(_, value) => value,
let channels = match (node.def.as_str(), parameter.as_str(), base.format) {
("levels", "in_low" | "in_high" | "out_low" | "out_high", OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit) => ChannelMode::Normalized,
("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)
.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);
}
+14 -18
View File
@@ -2,20 +2,24 @@ use materialcraft_core::{FunctionGraph, Value, ValueType};
use materialcraft_nodes::function::{EvaluationContext, EvaluationState, compile};
use std::collections::BTreeMap;
#[derive(Clone, Copy)]
pub(crate) enum ChannelMode {
Opaque,
Broadcast,
Normalized,
}
pub(crate) fn evaluate(
function: &FunctionGraph,
expected: ValueType,
variables: &mut BTreeMap<String, Value>,
seed: u32,
size: [u32; 2],
allow_scalar: bool,
channels: ChannelMode,
) -> Result<Value, String> {
let program = compile(function, seed)?;
let scalar_channel = allow_scalar && expected == ValueType::Float4 && program.output_type() == ValueType::Float as u32;
// A color parameter also takes a gray level or an opaque RGB triple
let widened = expected == ValueType::Float4 && [ValueType::Float as u32, ValueType::Float3 as u32].contains(&program.output_type());
if program.output_type() != expected as u32 && !scalar_channel && !widened {
if program.output_type() != expected as u32 && !widened {
return Err(format!("output must be {}", expected.label()));
}
@@ -29,21 +33,13 @@ pub(crate) fn evaluate(
variables,
};
let mut state = EvaluationState::default();
let value = program.evaluate(&context, &mut state)?;
let finite = match &value {
Value::Float(value) => value.is_finite(),
Value::Float2(values) => values.iter().all(|value| value.is_finite()),
Value::Float3(values) => values.iter().all(|value| value.is_finite()),
Value::Float4(values) | Value::Color(values) => values.iter().all(|value| value.is_finite()),
_ => true,
let value = match channels {
ChannelMode::Normalized => program.evaluate_normalized_color(&context, &mut state)?,
_ => program.evaluate(&context, &mut state)?,
};
if !finite {
return Err("function returned a non-finite value".into());
}
let value = match value {
Value::Float(level) if !scalar_channel && widened => Value::Float4([level, level, level, 1.0]),
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]),
Value::Float3([red, green, blue]) if widened => Value::Float4([red, green, blue, 1.0]),
value => value,
};
+9 -2
View File
@@ -97,8 +97,15 @@ pub(crate) fn evaluate(
resolved.size
};
let value = crate::parameter_function::evaluate(function, parameter.value_type(), variables.to_mut(), resolved.seed, size, false)
.map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?;
let value = crate::parameter_function::evaluate(
function,
parameter.value_type(),
variables.to_mut(),
resolved.seed,
size,
crate::parameter_function::ChannelMode::Opaque,
)
.map_err(|error| format!("function of `{}`: {error}", parameter.identifier()))?;
parameter.set_value(&mut evaluated, &value)?;
parameter.set_inheritance(&mut evaluated, parameter.inheritance(base));
resolved = ResolvedBaseParameters::resolve(&evaluated, input, parent);
+27
View File
@@ -924,3 +924,30 @@ fn a_color_parameter_function_may_return_a_gray_level_or_an_rgb_triple() {
assert_eq!(result.parameters.get("color").and_then(Value::as_vec4), Some(expected));
}
}
#[test]
fn levels_widens_scalar_endpoints_to_opaque_gray_and_normalizes_integer_controls() {
use materialcraft_core::{FunctionGraph, OutputFormat};
for (format, numerator, denominator, expected) in [
(OutputFormat::F32, 1.0, 0.125, [8.0, 8.0, 8.0, 1.0]),
(OutputFormat::U8, 1.0, 0.0, [1.0; 4]),
(OutputFormat::U16, 1.0, -0.0, [0.0, 0.0, 0.0, 1.0]),
(OutputFormat::U16, 0.0, 0.0, [0.0, 0.0, 0.0, 1.0]),
] {
let mut function = FunctionGraph::default();
let a = function.add_constant(Value::Float(numerator));
let b = function.add_constant(Value::Float(denominator));
function.output = Some(function.add("div", &[a, b], None));
let mut graph = Graph::new("Channel control");
let levels = graph.add_node("levels", [0.0; 2]);
let node = graph.node_mut(levels).unwrap();
node.base.format = format;
node.functions.insert("in_high".into(), function);
let mut package = Package::new("Channel control");
package.graphs.push(graph);
let cooked = cook(&package, 0, &Options::new(&no_res), &Mutex::new(Cache::default()));
assert_eq!(cooked.nodes[&levels].error, None);
assert_eq!(cooked.nodes[&levels].parameters["in_high"], Value::Float4(expected));
}
}
+12 -4
View File
@@ -1,6 +1,7 @@
use super::ATOMIC;
use crate::{CookContext, CookResult, NodeDefinition, node};
use craft_texture::Kind;
use materialcraft_core::OutputFormat;
pub(super) fn definition() -> NodeDefinition {
node("levels", "Levels", ATOMIC)
@@ -19,11 +20,18 @@ pub(super) fn definition() -> NodeDefinition {
fn levels(context: &CookContext) -> CookResult {
let image = context.any_or(0, Kind::Gray, [0.0; 4]);
let low = context.v4("in_low");
let endpoint = |name| {
let values = context.v4(name);
match context.format {
OutputFormat::U8 | OutputFormat::U16 | OutputFormat::Inherit => values.map(|v| v.clamp(0.0, 1.0)),
OutputFormat::F16 | OutputFormat::F32 => values,
}
};
let low = endpoint("in_low");
let mid = context.v4("in_mid");
let high = context.v4("in_high");
let output_low = context.v4("out_low");
let output_high = context.v4("out_high");
let high = endpoint("in_high");
let output_low = endpoint("out_low");
let output_high = endpoint("out_high");
let clamp = context.b("clamp_intermediate");
let ranges: [_; 4] = std::array::from_fn(|c| ChannelRange::new(low[c], mid[c], high[c], output_low[c], output_high[c]));
+22 -8
View File
@@ -34,19 +34,33 @@ impl Program {
/// Pattern parameters share a random stream within each traversal visit.
pub(crate) fn evaluate_with_random(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState, random: &mut u32) -> Result<Value, String> {
let value = self.run_with_random(context, state, random)?;
// Callers may clamp undefined intermediates; completed functions must be finite
if value.as_vec4().is_some_and(|components| components.iter().any(|value| !value.is_finite())) {
return Err("function produced a non-finite output".into());
}
Ok(value)
}
/// Evaluate an integer texture's channel control at its normalized storage boundary.
pub fn evaluate_normalized_color(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState) -> Result<Value, String> {
let mut random = self.random_seed(context);
let channels = match self.run_with_random(context, state, &mut random)? {
Value::Float(v) => [v, v, v, 1.0],
Value::Float3([r, g, b]) => [r, g, b, 1.0],
Value::Float4(rgba) | Value::Color(rgba) => rgba,
_ => return Err("channel control requires a gray level, RGB or RGBA".into()),
};
Ok(Value::Float4(channels.map(|v| if v.is_nan() { 0.0 } else { v.clamp(0.0, 1.0) })))
}
fn run_with_random(&self, context: &EvaluationContext<'_>, state: &mut EvaluationState, random: &mut u32) -> Result<Value, String> {
state.variables.clone_from(context.variables);
state.random = *random;
let mut remaining = MAX_EVALUATION_STEPS;
let result = self.run(context, state, &mut remaining);
*random = state.random;
let value = result?;
// Callers may clamp undefined intermediates; completed functions must be finite
if value.as_vec4().is_some_and(|components| components.iter().any(|value| !value.is_finite())) {
return Err("function produced a non-finite output".into());
}
Ok(value)
result
}
fn random_seed(&self, context: &EvaluationContext<'_>) -> u32 {
+4 -3
View File
@@ -5,7 +5,7 @@ use std::collections::BTreeMap;
/// How many slider spans the hard limit extends past each end of a parameter's range
const HARD_SPAN: f32 = 16.0;
/// Native channel controls also accept a single grayscale value, broadcast by the evaluator.
/// Native channel controls also accept a single grayscale function result.
/// Other vector parameters keep their exact function output type.
pub fn accepts_scalar_function(definition: &str, parameter: &str) -> bool {
matches!((definition, parameter), ("levels", "in_low" | "in_mid" | "in_high" | "out_low" | "out_high") | ("fx_map", "background"))
@@ -48,8 +48,9 @@ pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap<String, V
continue;
}
// An unconstrained Input Value accepts any number; reject only nonnumeric values
let ranged = parameter.min < parameter.max;
// Levels endpoints have fixed evaluation cost and float images can span the entire finite range.
let levels_endpoint = definition.id == "levels" && matches!(parameter.id, "in_low" | "in_high" | "out_low" | "out_high");
let ranged = parameter.min < parameter.max && !levels_endpoint;
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) };
+6 -2
View File
@@ -19,9 +19,13 @@ fn resolve_params_clamps_to_hard_limits() {
assert_eq!(p["opacity"], Value::Float(-16.0));
let p = resolve_params(def, &over("opacity", Value::Float(f32::NAN)));
assert_eq!(p["opacity"], def.param("opacity").unwrap().default);
}
#[test]
fn levels_preserves_finite_float_endpoints_beyond_the_slider() {
let levels = find("levels").unwrap();
let p = resolve_params(levels, &over("in_low", Value::Float4([1e9, -1e9, 0.0, 1.0])));
assert_eq!(p["in_low"], Value::Float4([17.0, -16.0, 0.0, 1.0]));
let p = resolve_params(levels, &over("in_low", Value::Float4([1024.0, -1e12, 0.0, f32::NAN])));
assert_eq!(p["in_low"], Value::Float4([1024.0, -1e12, 0.0, 0.0]));
}
#[test]
+23 -12
View File
@@ -4,23 +4,16 @@ use materialcraft_nodes::{CookContext, find, resolve_params};
use std::collections::BTreeMap;
fn cook(id: &str, inputs: &[Option<Image>], values: &[(&str, Value)], size: [u32; 2], tile: bool) -> Image {
cook_format(id, inputs, values, size, tile, OutputFormat::F32)
}
fn cook_format(id: &str, inputs: &[Option<Image>], values: &[(&str, Value)], size: [u32; 2], tile: bool, format: OutputFormat) -> Image {
let definition = find(id).unwrap();
let values = values.iter().map(|(key, value)| ((*key).into(), value.clone())).collect();
let params = resolve_params(definition, &values);
let resource = |_: &str| None;
let vars = BTreeMap::new();
let context = CookContext {
input_formats: &[],
w: size[0],
h: size[1],
seed: 0,
format: OutputFormat::F32,
tile,
inputs,
params: &params,
resource: &resource,
vars: &vars,
};
let context = CookContext { input_formats: &[], w: size[0], h: size[1], seed: 0, format, tile, inputs, params: &params, resource: &resource, vars: &vars };
(definition.cook)(&context).unwrap().remove(0)
}
@@ -45,6 +38,24 @@ fn levels_applies_signed_gamma_before_mapping_the_output_range() {
assert_eq!(output.get(1, 0, false).map(f32::to_bits), [0x3f9f741c, 0x3fb89ba3, 0x41d80001, 0x4372fffe]);
}
#[test]
fn integer_levels_bounds_the_four_endpoints_before_applying_gamma() {
let params = [
("in_low", Value::Float4([-1.75, -0.625, -0.125, -0.5])),
("in_mid", Value::Float4([0.469, 0.44, 0.51, 0.25])),
("in_high", Value::Float4([2.375, 2.75, 1.5, 2.875])),
("out_low", Value::Float4([-0.5, -1.0, 0.25, 0.125])),
("out_high", Value::Float4([1.875, 2.25, 1.375, 0.875])),
("clamp_intermediate", Value::Bool(false)),
];
let input = [Some(Image::filled(1, 1, Kind::Color, [0.125; 4]))];
for (format, max, expected) in [(OutputFormat::U8, 255.0, [64, 88, 81, 158]), (OutputFormat::U16, 65535.0, [16323, 22684, 20789, 40620])] {
let image = cook_format("levels", &input, &params, [1, 1], false, format);
let stored = materialcraft_nodes::output_precision::apply(image, format);
assert_eq!(stored.get(0, 0, false).map(|v| (v * max).round() as u16), expected);
}
}
#[test]
fn levels_scales_narrow_and_coincident_ranges_independently() {
let pixel = [0xbfd95555, 0xbf9aaaab, 0xbf380000, 0xbe6aaaab].map(f32::from_bits);
+25
View File
@@ -253,6 +253,31 @@ Literal-only pixel graphs at 16², seed 23, give 512/768 exact pixels for each l
The shared-lookup ridged root still matches 5,160/16,384 at changed roughness in F32, maximum 1.78813934e−7. Its one-octave .7 control still matches 1,847/4,096, maximum 2.38418579e−7. For positive normal x on the signed field, the reference's general power agrees with exp(y×ln(x)) on all 32,614 pixels. On .7 with exponent 1 it returns `3f333334`. Further work on general power and natural exponential is tracked with the [octave controls](#ridged-noise-octave-isolation).
### Integer Levels endpoints and channel mixing
**Integer Levels.** The 60 signed controls and the 24 mixed, narrow and signed-range controls from the [Levels endpoint table](#levels-endpoints-camera-tangents-and-uniform-exponentials) now match **344,064/344,064 RGBA pixels**, maximum zero. For an integer destination, bound each input and output endpoint to [0,1] before computing the curve. The intermediate-clamp switch still controls the position on the curve. For F16 and F32, retain finite endpoints outside the slider range.
In 32 additional comparisons, replace one endpoint at a time by the literal RGBA tuple (1024, −1024, 10¹², −10¹²). Use the other default endpoints and midpoint, the 64² signed field, seed 131, both intermediate-clamp settings and all four formats. All **131,072/131,072 pixels** match, maximum zero. At the uniform input .125, the signed-endpoint row in the previous table stores (64,88,81,158) in RGBA8 and (16323,22684,20789,40620) in RGBA16.
**Driven controls.** Attach the scalar function numerator/denominator to input high, input low or output high. Use numerators zero and one and exposed denominators 1, +0, −0, 1/1024, −1/1024, 10⁻¹², −10⁻¹² and −1 in that order. Apply the otherwise default Levels filter to the [64² signed field](#signed-levels-driven-grayscale-weights-and-grayscale-gradients) with seeds 607 through 614. A scalar becomes (value,value,value,1). At the integer boundary positive infinity becomes one, and negative infinity and NaN become zero. The 96 integer cases match **393,216/393,216 pixels**. The 72 finite-result float cases match **294,912/294,912**, maximum zero. The 24 float cases with a zero denominator still report a nonfinite parameter error.
A separate upper-endpoint tuple (2¹²⁵,2¹²⁷,−F32_MAX,F32_MAX), with both clamp settings, matches 8,192/8,192 in each integer format. F16 matches 6,411/8,192 with maximum numerical error zero and different zero signs. F32 matches 3,883/8,192 with maximum 3.91219466e−38. Subnormal range scaling remains open.
**Channel mixer.** The default 128² and 256² renders and seed 42 now cook and match all **98,304/98,304 RGBA16 pixels**. The changed 128² case matches 16,380/16,384, maximum four levels. The 64² changed monochrome case in all four formats and the independent 32² F32 case match **17,408/17,408**, maximum zero. The historical changed case uses red (50,25,10,5), green (−10,100,10,0), blue (20,0,50,25) and monochrome enabled. The input fields are original.
Nine further channel mixes use the [original small, full, large, rectangular and signed fields](#signed-levels-driven-grayscale-weights-and-grayscale-gradients). The four numbers in each channel control are percentages. All comparisons count RGBA pixels with all four stored channels equal.
| Input, output, seed | Red / green / blue | Exact pixels | Maximum error |
|---|---|---:|---:|
| Small, 16² F32, 41 | (100,0,0,0) / (0,100,0,0) / (0,0,100,0) | 256/256 | 0 |
| Full, 64² U8 / U16 / F16 / F32, 73 | (60,30,10,0) / (−10,130,−20,0) / (20,15,55,10) | 561 / 513 / 515 / 513 of 4,096 | 58 / 14,864 / .22705078125 / .226810098 |
| Large, 128² F32, 99 | (.1,0,99.9,0) / (0,99,.1,1) / (0,.125,100,0) | 16,383/16,384 | .00006103515625 |
| Rectangular, 32² F32, 211 | (29.9,58.7,11.4,0) / (0,100,0,0) / (0,0,100,0), monochrome on | 1,024/1,024 | 0 |
| Signed, 32² F32, 317 | (−15,75,40,−5) / (70,−6,23,13) / (110,−15,−20,25) | 534/1,024 | .307743947 |
| Full, 64² F32, 137 | Repeat the seed 73 controls | 513/4,096 | .226810098 |
Reading the intermediate images identifies an additive grayscale blend with opacity 1.3 as the first large difference in the 64² F32 mix. Its two LUM16 inputs match. The first texel has background 0 and foreground 13,281. The reference stores 13,281 and MaterialCraft stores 17,265. A second additive blend with opacity .55 differs at only two of 4,096 texels, maximum one level. The root remains in progress.
### Levels endpoints, camera tangents and uniform exponentials
**Color to mask** matches **168,192/168,192 pixels in 18 cases**, maximum error zero. Keeping all upstream images fixed on the 64² float color field isolated the last 21 differing pixels at the final Levels filter. Multiply the centered input by the reciprocal input span and perform the output scaling and addition as a single fused operation. The 32×16 source, mixed alpha, signed input, altered keying modes and seeds are included in the [mask case definitions](#signed-levels-driven-grayscale-weights-and-grayscale-gradients). The grayscale HDR range viewer also retains its 18 exact cases.
+2 -2
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 **216 Parity**, **25 In progress** and **305 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 **216 Parity**, **26 In progress** and **304 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)
@@ -117,7 +117,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
| [cartesian_polar_transformation.sbs/polar_to_cartesian](../assets/sbs/cartesian_polar_transformation.sbs) | 1 | No | [Too hard: sampling/rounding](parity-fixes.md#remaining-differences) |
| [cartesian_polar_transformation.sbs/polar_to_cartesian_grayscale](../assets/sbs/cartesian_polar_transformation.sbs) | 1 | No | [Too hard: sampling/rounding](parity-fixes.md#remaining-differences) |
| [cells_1.sbs/cells_1](../assets/sbs/cells_1.sbs) | 0 | Yes | [Too hard: noise field](parity-fixes.md#remaining-differences) |
| [channel_mixer.sbs/channel_mixer](../assets/sbs/channel_mixer.sbs) | 1 | No | [Too hard: function parameter output](parity-fixes.md#remaining-differences) |
| [channel_mixer.sbs/channel_mixer](../assets/sbs/channel_mixer.sbs) | 1 | No | [In progress · defaults exact, first residual in additive blending](parity-fixes.md#integer-levels-endpoints-and-channel-mixing) |
| [checker_1.sbs/checker_1](../assets/sbs/checker_1.sbs) | 0 | Yes | [Parity · eight cases, four formats](parity-fixes.md#transform-edges-and-floating-point-filtering) |
| [checker_2.sbs/checker_2](../assets/sbs/checker_2.sbs) | 0 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [chrominance_extract.sbs/chrominance_extract](../assets/sbs/chrominance_extract.sbs) | 1 | No | [Parity · 18 cases, 171,264 exact pixels](parity-fixes.md#gradient-interpolation-color-blend-and-chrominance) |