Respect driven grayscale weights and signed Levels ranges

This commit is contained in:
chasse20 committed 2026-11-18 12:10:53 -05:00
1 parent f6eaae57dc
commit daefcbb5f0
17 files changed
+218 -46

No files matched your search

+10 -4
View File
@@ -56,7 +56,7 @@ pub(super) const FILTERS: &[FilterMap] = &[
sbs: "grayscaleconversion",
def: "grayscale_conversion",
inputs: &[("input1", "input")],
params: &[("alphamult", "flatten_alpha"), ("mattelevel", "matte")],
params: &[("alphamult", "flatten_alpha"), ("mattelevel", "matte"), ("channelsweights", "weights")],
},
FilterMap { sbs: "hsl", def: "hsl", inputs: &[("input1", "input")], params: &[("hue", "hue"), ("saturation", "saturation"), ("luminosity", "lightness")] },
FilterMap { sbs: "bitmap", def: "bitmap", inputs: &[], params: &[("colorswitch", "color_mode"), ("colorspace", "colour_space")] },
@@ -64,7 +64,14 @@ pub(super) const FILTERS: &[FilterMap] = &[
sbs: "levels",
def: "levels",
inputs: &[("input1", "input")],
params: &[("levelinlow", "in_low"), ("levelinmid", "in_mid"), ("levelinhigh", "in_high"), ("leveloutlow", "out_low"), ("levelouthigh", "out_high")],
params: &[
("levelinlow", "in_low"),
("levelinmid", "in_mid"),
("levelinhigh", "in_high"),
("leveloutlow", "out_low"),
("levelouthigh", "out_high"),
("clampinterm", "clamp_intermediate"),
],
},
FilterMap {
sbs: "normal",
@@ -126,8 +133,7 @@ pub(super) const FILTERS: &[FilterMap] = &[
},
];
pub(super) const BASE_PARAMS: &[&str] = &["outputsize", "format", "randomseed", "tiling", "pixelsize", "pixelratio", "quality"];
pub(super) const HANDLED_PARAMS: &[(&str, &str)] =
&[("bitmap", "bitmapresourcepath"), ("grayscaleconversion", "channelsweights"), ("transformation", "matrix22"), ("curve", "exposecurve")];
pub(super) const HANDLED_PARAMS: &[(&str, &str)] = &[("bitmap", "bitmapresourcepath"), ("transformation", "matrix22"), ("curve", "exposecurve")];
pub(super) fn filter_by_sbs_name(name: &str) -> Option<&'static FilterMap> {
FILTERS.iter().find(|f| f.sbs == name)
-4
View File
@@ -29,10 +29,6 @@ pub(super) fn special_filter_params_xml<'a>(
.unwrap_or_default(),
_ => String::new(),
},
"grayscaleconversion" => {
let weight = |channel: &str| value_of(channel).and_then(Value::as_f32).unwrap_or(0.0);
param_xml("channelsweights", &Value::Float4([weight("red"), weight("green"), weight("blue"), weight("alpha")])).unwrap_or_default()
}
_ => String::new(),
}
}
+3 -10
View File
@@ -51,16 +51,10 @@ pub(super) fn read(node: &mut Node, implementation: XmlNode<'_, '_>) {
}
}
pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) -> String {
pub(super) fn write(value: &Value, writer: &mut SbsWriter) -> String {
let name = match value {
Value::Curve(_) => "curveluminance",
Value::Gradient(_) => {
if color_mode {
"gradientrgba"
} else {
"gradientluminance"
}
}
Value::Gradient(_) => "gradientrgba",
_ => return String::new(),
};
@@ -91,8 +85,7 @@ pub(super) fn write(value: &Value, color_mode: bool, writer: &mut SbsWriter) ->
}
Value::Gradient(gradient) => {
for key in &gradient.keys {
let color = if color_mode { Value::Color(key.color) } else { Value::Float(craft_texture::luminance(key.color)) };
cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(2.0 * key.midpoint - 1.0)), ("value", color)]);
cell(vec![("position", Value::Float(key.pos)), ("midpoint", Value::Float(2.0 * key.midpoint - 1.0)), ("value", Value::Float4(key.color))]);
}
}
_ => {}
+10 -5
View File
@@ -678,6 +678,16 @@ impl<'text> SbsReader<'text, '_> {
}
if let Some(&(_, mc_name)) = filter.params.iter().find(|(sbs, _)| *sbs == param_name) {
if filter.sbs == "grayscaleconversion" && mc_name == "weights" {
if let Some(weights) = value {
for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() {
node.params.insert(channel.into(), Value::Float(weights.float(i)));
}
} else {
self.set_param(node, mc_name, &Value::Float4([0.0; 4]), 0, *param, graph_name);
}
continue;
}
let Some(param_def) = def.param(mc_name) else { continue };
self.set_param(node, mc_name, &param_def.default, param_def.options.len(), *param, graph_name);
@@ -690,11 +700,6 @@ impl<'text> SbsReader<'text, '_> {
node.params.insert("resource".into(), Value::Text(name));
}
}
("grayscaleconversion", "channelsweights", Some(weights)) => {
for (i, channel) in ["red", "green", "blue", "alpha"].into_iter().enumerate() {
node.params.insert(channel.into(), Value::Float(weights.float(i)));
}
}
_ if HANDLED_PARAMS.contains(&(filter.sbs, param_name)) => {}
_ => self.warnings.add(format!("`{}`: SBS parameter `{param_name}` is not supported yet and was ignored", filter.def)),
}
+5 -2
View File
@@ -327,7 +327,10 @@ impl SbsWriter {
def => match (filter_by_def(def), find(def)) {
(Some(filter), Some(catalog_def)) => {
let _ = write!(out, "<compFilter><filter v=\"{}\"/><parameters>{base}", filter.sbs);
let value_of = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default));
let stored = |id: &str| node.params.get(id).or_else(|| catalog_def.param(id).map(|p| &p.default));
let weights = (filter.sbs == "grayscaleconversion")
.then(|| Value::Float4(["red", "green", "blue", "alpha"].map(|id| stored(id).and_then(Value::as_f32).unwrap_or(0.0))));
let value_of = |id: &str| stored(id).or_else(|| if id == "weights" { weights.as_ref() } else { None });
for (sbs_name, mc_name) in filter.params {
let Some(value) = value_of(mc_name) else { continue };
@@ -367,7 +370,7 @@ impl SbsWriter {
out.push_str("</parameters>");
for parameter in ["curve", "gradient"] {
if let Some(value) = value_of(parameter) {
out.push_str(&super::parameter_array::write(value, value_of("color_mode").and_then(Value::as_bool).unwrap_or(true), self));
out.push_str(&super::parameter_array::write(value, self));
}
}
if let Some(Value::PatternGraph(graph)) = value_of("pattern") {
+3
View File
@@ -51,6 +51,9 @@ fn native_gradient_default_midpoints_are_linear_and_components_are_preserved() {
assert!((gradient.eval(0.5)[3] - if color { 0.4 } else { 1.0 }).abs() < 1e-6);
let saved = write_sbs(&read.pkg).unwrap();
let xml = std::str::from_utf8(&saved).unwrap();
assert!(xml.contains(r#"<name v="gradientrgba"/>"#));
assert_eq!(xml.matches("<constantValueFloat4 ").count(), 2);
read = read_sbs(&saved, "saved.sbs", &|_| None).unwrap();
}
}
@@ -1,5 +1,42 @@
use materialcraft_formats::sbs::{read_sbs, write_sbs};
#[test]
fn grayscale_channel_weights_round_trip_as_one_function() {
use materialcraft_core::Value;
let xml = br#"<package><content><graph><identifier v="Weights"/><compNodes><compNode><uid v="1"/>
<compImplementation><compFilter><filter v="grayscaleconversion"/><parameters>
<parameter><name v="channelsweights"/><paramValue><dynamicValue><rootnode v="17"/><paramNodes>
<paramNode><uid v="17"/><function v="const_float4"/><type v="2048"/><funcDatas><funcData><name v="const_float4"/>
<constantValue><constantValueFloat4 v="0.125 0.25 0.5 0.125"/></constantValue></funcData></funcDatas></paramNode>
</paramNodes></dynamicValue></paramValue></parameter></parameters></compFilter></compImplementation>
</compNode></compNodes></graph></content></package>"#;
let mut read = read_sbs(xml, "weights.sbs", &|_| None).unwrap();
for _ in 0..2 {
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
let node = &read.pkg.graphs[0].nodes[0];
assert_eq!(node.functions.len(), 1);
assert_eq!(node.functions["weights"].nodes[0].value, Some(Value::Float4([0.125, 0.25, 0.5, 0.125])));
let saved = write_sbs(&read.pkg).unwrap();
assert_eq!(std::str::from_utf8(&saved).unwrap().matches(r#"<name v="channelsweights"/>"#).count(), 1);
read = read_sbs(&saved, "saved.sbs", &|_| None).unwrap();
}
}
#[test]
fn levels_preserves_the_unclamped_input_range_on_save() {
let xml = br#"<package><content><graph><identifier v="Range"/><compNodes><compNode><uid v="1"/>
<compImplementation><compFilter><filter v="levels"/><parameters><parameter><name v="clampinterm"/>
<paramValue><constantValueBool v="0"/></paramValue></parameter></parameters></compFilter></compImplementation>
</compNode></compNodes></graph></content></package>"#;
let mut read = read_sbs(xml, "range.sbs", &|_| None).unwrap();
for _ in 0..2 {
assert!(read.warnings.is_empty(), "{:?}", read.warnings);
assert_eq!(read.pkg.graphs[0].nodes[0].params["clamp_intermediate"].as_bool(), Some(false));
let saved = write_sbs(&read.pkg).unwrap();
read = read_sbs(&saved, "saved.sbs", &|_| None).unwrap();
}
}
#[test]
fn fx_map_render_and_tiling_regions_keep_native_names_and_functions() {
use materialcraft_core::Value;
+22 -10
View File
@@ -1,6 +1,6 @@
use super::ATOMIC;
use crate::{CookContext, CookResult, NodeDefinition, node, texture_sampler};
use craft_texture::{Image, Kind, Limits, luminance};
use craft_texture::{Image, Kind, Limits};
use materialcraft_core::{Gradient, OutputFormat};
pub(super) fn definition() -> NodeDefinition {
@@ -17,18 +17,17 @@ pub(super) fn definition() -> NodeDefinition {
fn gradient_map(context: &CookContext) -> CookResult {
let input = context.gray_or(0, 0.0);
let table = lookup_table(context.gradient("gradient"), context.i("interpolation") == 1, context.format)?;
let width = table.width() as f32;
let gray = !context.b("color_mode");
let kind = if gray { Kind::Gray } else { Kind::Color };
let table = lookup_table(context.gradient("gradient"), context.i("interpolation") == 1, context.format, gray)?;
let width = table.width() as f32;
Ok(vec![input.map(kind, |p| {
let u = (p[0].clamp(0.0, 1.0) * (width - 1.0) + 0.5) / width;
let color = texture_sampler::sample(&table, [u, 0.5], [false; 2], OutputFormat::F32, None);
if gray && (color[0] != color[1] || color[1] != color[2]) { [luminance(color); 4] } else { color }
texture_sampler::sample(&table, [u, 0.5], [false; 2], OutputFormat::F32, None)
})])
}
fn lookup_table(mut gradient: Gradient, smooth: bool, format: OutputFormat) -> Result<Image, String> {
fn lookup_table(mut gradient: Gradient, smooth: bool, format: OutputFormat, gray: bool) -> Result<Image, String> {
let levels = match format {
OutputFormat::U8 => Some(255.0),
OutputFormat::Inherit | OutputFormat::U16 => Some(65535.0),
@@ -41,10 +40,15 @@ fn lookup_table(mut gradient: Gradient, smooth: bool, format: OutputFormat) -> R
gradient = Gradient::default();
}
gradient.sort();
// The first authored stop owns both sides of a shared position.
gradient.keys.dedup_by(|later, earlier| later.pos == earlier.pos);
for key in &mut gradient.keys {
let position = key.pos.clamp(0.0, 1.0);
key.pos = if levels.is_some() { (position * 65535.0).round() / 257.0 } else { position * last_index };
if levels.is_some() {
if gray {
let [r, g, b, _] = key.color;
key.color = [(r + g + b) / 3.0; 4];
} else if levels.is_some() {
// Integer ramp stops store byte colors even when the output uses 16 bits.
key.color = key.color.map(|v| (v.clamp(0.0, 1.0) * 255.0).round() / 255.0);
}
@@ -56,8 +60,12 @@ fn lookup_table(mut gradient: Gradient, smooth: bool, format: OutputFormat) -> R
}
for pair in gradient.keys.windows(2) {
let [left, right] = pair else { continue };
// Different authored stops can collapse to one position in an integer table.
if right.pos <= left.pos {
continue;
}
let first = left.pos.ceil() as usize;
let end = right.pos.ceil() as usize;
let end = if gray { right.pos.floor() as usize + 1 } else { right.pos.ceil() as usize };
let Some(segment) = entries.get_mut(first..end).filter(|s| !s.is_empty()) else { continue };
let step = (right.pos - left.pos).recip();
let mut t = (first as f32 - left.pos) * step;
@@ -66,8 +74,12 @@ fn lookup_table(mut gradient: Gradient, smooth: bool, format: OutputFormat) -> R
let bias = 2.0 * left.midpoint - 1.0;
for entry in segment {
let u = t * (1.0 - bias * (1.0 - t));
let weight = u * u * (3.0 - 2.0 * u);
*entry = std::array::from_fn(|c| left.color[c] + delta[c] * weight);
*entry = if gray {
[left.color[0] + (delta[0] * u) * (u * (3.0 - 2.0 * u)); 4]
} else {
let weight = u * u * (3.0 - 2.0 * u);
std::array::from_fn(|c| left.color[c] + delta[c] * weight)
};
// Each addition rounds at the table's working precision.
t += step;
}
@@ -19,14 +19,17 @@ pub(super) fn definition() -> NodeDefinition {
fn grayscale_conversion(context: &CookContext) -> CookResult {
let image = context.any_or(0, Kind::Color, [0.0, 0.0, 0.0, 1.0]).to_color();
let weights = [context.f("red"), context.f("green"), context.f("blue"), context.f("alpha")];
let weights = context
.value("weights")
.and_then(materialcraft_core::Value::as_vec4)
.unwrap_or_else(|| [context.f("red"), context.f("green"), context.f("blue"), context.f("alpha")]);
let flatten = context.b("flatten_alpha");
let matte = context.f("matte");
Ok(vec![image.map(Kind::Gray, |pixel| {
// Preserve the fused, ordered dot product through float image storage
let mut value = pixel[3].mul_add(weights[3], pixel[2].mul_add(weights[2], pixel[1].mul_add(weights[1], pixel[0] * weights[0])));
let mut value = pixel.into_iter().zip(weights).fold(0.0, |sum, (channel, weight)| channel.mul_add(weight, sum));
if flatten {
value = value * pixel[3] + matte * (1.0 - pixel[3]);
value = (matte - value).mul_add(1.0 - pixel[3], value);
}
[value, 0.0, 0.0, 0.0]
})])
+10 -5
View File
@@ -12,6 +12,7 @@ pub(super) fn definition() -> NodeDefinition {
.float4("in_high", "Level in high", [1.0; 4], 0.0, 1.0)
.float4("out_low", "Level out low", [0.0; 4], 0.0, 1.0)
.float4("out_high", "Level out high", [1.0; 4], 0.0, 1.0)
.boolean("clamp_intermediate", "Clamp intermediate values", true)
.any_out()
.cook(levels)
}
@@ -23,24 +24,28 @@ fn levels(context: &CookContext) -> CookResult {
let high = context.v4("in_high");
let output_low = context.v4("out_low");
let output_high = context.v4("out_high");
let clamp = context.b("clamp_intermediate");
Ok(vec![image.map(image.kind(), |pixel| {
std::array::from_fn(|channel| levels_fn(pixel[channel], low[channel], mid[channel], high[channel], output_low[channel], output_high[channel]))
})])
Ok(vec![image.map(image.kind(), |pixel| std::array::from_fn(|c| remap(pixel[c], low[c], mid[c], high[c], output_low[c], output_high[c], clamp)))])
}
pub fn levels_fn(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32) -> f32 {
remap(v, in_low, in_mid, in_high, out_low, out_high, true)
}
fn remap(v: f32, in_low: f32, in_mid: f32, in_high: f32, out_low: f32, out_high: f32, clamp: bool) -> f32 {
let span = in_high - in_low;
let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { ((v - in_low) / span).clamp(0.0, 1.0) };
let t = if span.abs() < 1e-6 { if v >= in_high { 1.0 } else { 0.0 } } else { (v - in_low) / span };
// NaN (from an input or a hostile parameter) would otherwise spread through the graph
let t = if t.is_finite() { t } else { 0.0 };
let t = if clamp { t.clamp(0.0, 1.0) } else { t };
let mid = if in_mid.is_finite() { in_mid.clamp(0.0, 1.0) } else { 0.5 };
// The midpoint slider controls reciprocal gamma below neutral and gamma above it
// Treating it as an input value that maps to 0.5 changes authored levels curves
let g = if mid <= 0.5 { 1.0 / (9.0 - 16.0 * mid) } else { 16.0 * mid - 7.0 };
out_low + t.powf(g) * (out_high - out_low)
out_low + crate::function::signed_pixel_power(t, g) * (out_high - out_low)
}
#[cfg(test)]
@@ -56,6 +56,10 @@ pub(super) fn ln(value: f32) -> f32 {
log2(value) * std::f32::consts::LN_2
}
pub(crate) fn signed_pixel_power(value: f32, exponent: f32) -> f32 {
exp2(log2(value.abs()) * exponent).copysign(value)
}
pub(super) fn exp(value: f32) -> f32 {
if value < -88.0 || value.is_nan() {
return 0.0;
+1
View File
@@ -41,6 +41,7 @@ pub mod value_type;
mod vector;
mod warnings;
pub(crate) use binary_exponential::signed_pixel_power;
pub use catalog::{FUNCTIONS, default_value, definition};
pub use compile::compile;
pub use evaluation_context::EvaluationContext;
+12
View File
@@ -17,6 +17,13 @@ fn clamp_finite(v: f32, lo: f32, hi: f32, fallback: f32) -> f32 {
}
pub fn clamp_params(definition: &NodeDefinition, params: &mut BTreeMap<String, Value>) {
if definition.id == "grayscale_conversion"
&& let Some(Value::Float4(weights)) = params.get_mut("weights")
{
for (weight, fallback) in weights.iter_mut().zip([1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0]) {
*weight = clamp_finite(*weight, -HARD_SPAN, 1.0 + HARD_SPAN, fallback);
}
}
for parameter in &definition.params {
let Some(value) = params.get_mut(parameter.id) else { continue };
if let Value::Enum(index) = value {
@@ -80,6 +87,11 @@ pub fn resolve_params(def: &NodeDefinition, overrides: &BTreeMap<String, Value>)
m.insert(k.clone(), v.clone());
}
}
if def.id == "grayscale_conversion"
&& let Some(Value::Float4(weights)) = overrides.get("weights")
{
m.insert("weights".into(), Value::Float4(*weights));
}
clamp_params(def, &mut m);
m
}
+12
View File
@@ -35,6 +35,18 @@ impl ParameterDescriptor {
}
pub fn for_node(package: &Package, node: &Node, parameter: &str) -> Option<Self> {
if node.def == "grayscale_conversion" && parameter == "weights" {
// A single function can drive the four channel controls together.
return Some(Self {
id: parameter.into(),
label: "RGBA weights".into(),
default: Value::Float4([1.0 / 3.0, 1.0 / 3.0, 1.0 / 3.0, 0.0]),
min: 0.0,
max: 1.0,
options: Vec::new(),
supports_function: true,
});
}
if node.def == "graph_instance" {
let source = node
.instance
@@ -24,6 +24,56 @@ fn cook(id: &str, inputs: &[Option<Image>], values: &[(&str, Value)], size: [u32
(definition.cook)(&context).unwrap().remove(0)
}
#[test]
fn grayscale_uses_all_driven_weights_and_flattens_signed_alpha() {
let px = [0xbfd95555, 0xbf9aaaab, 0xbf380000, 0xbe6aaaab].map(f32::from_bits);
let inp = Image::generate(2, 1, Kind::Color, |x, _| if x == 0 { [-0.0; 4] } else { px });
let weights = ("weights", Value::Float4([0.125, 0.25, 0.5, 0.125]));
let gray = cook("grayscale_conversion", &[Some(inp.clone())], std::slice::from_ref(&weights), [2, 1], false);
assert_eq!(gray.get_gray(0, 0, false).to_bits(), 0);
let params = [weights, ("flatten_alpha", Value::Bool(true)), ("matte", Value::Float(0.3125))];
let flattened = cook("grayscale_conversion", &[Some(inp)], &params, [2, 1], false);
assert_eq!(flattened.get_gray(1, 0, false).to_bits(), 0x3f174555);
}
#[test]
fn levels_applies_signed_gamma_before_mapping_the_output_range() {
let input = Image::generate(2, 1, Kind::Color, |x, _| if x == 0 { [-0.5; 4] } else { [3.0; 4] });
let params = [("clamp_intermediate", Value::Bool(false)), ("in_mid", Value::Float4([0.25, 0.375, 0.625, 0.75]))];
let output = cook("levels", &[Some(input)], &params, [2, 1], false);
assert_eq!(output.get(0, 0, false).map(f32::to_bits), [0xbf5edc67, 0xbf4b2ff5, 0xbe000003, 0xbd000003]);
assert_eq!(output.get(1, 0, false).map(f32::to_bits), [0x3f9f741c, 0x3fb89ba3, 0x41d80001, 0x4372fffe]);
}
#[test]
fn gradient_keeps_the_first_stop_at_a_shared_position() {
let input = Image::gray(1, 1, |_, _| 640.0 / 1023.0);
let keys = vec![
GradientKey::new(0.125, [0.375, 0.75, 0.875, 0.6875]),
GradientKey::new(0.5, [0.875, 0.0625, 0.3125, 0.25]),
GradientKey::new(0.5, [0.1875, 0.75, 0.25, 0.8125]),
GradientKey::new(0.75, [0.25, 0.5625, 0.75, 0.375]),
];
let output = cook("gradient_map", &[Some(input)], &[("gradient", Value::Gradient(Gradient { keys }))], [1, 1], false);
assert_eq!(output.get(0, 0, false).map(f32::to_bits), [0x3f0f9be7, 0x3ea0a028, 0x3f084612, 0x3ea0280a]);
}
#[test]
fn grayscale_gradient_averages_stops_before_interpolating() {
let input = Image::gray(1, 1, |_, _| 640.0 / 1023.0);
let keys = vec![
GradientKey::new(0.0625, [0.1875, 0.25, 0.4375, 0.8125]),
GradientKey::new(0.34375, [0.59375, 0.9375, 0.3125, 0.5625]),
GradientKey::new(0.890625, [0.8125, 0.125, 0.75, 0.375]),
];
for (mode, bits) in [(0, 0x3f167617), (1, 0x3f165bd5)] {
let params = [("gradient", Value::Gradient(Gradient { keys: keys.clone() })), ("interpolation", Value::Enum(mode)), ("color_mode", Value::Bool(false))];
let output = cook("gradient_map", &[Some(input.clone())], &params, [1, 1], false);
assert_eq!(output.kind(), Kind::Gray);
assert_eq!(output.get_gray(0, 0, false).to_bits(), bits);
}
}
#[test]
fn gradient_filter_preserves_linear_and_biased_smooth_segments() {
let input = Image::gray(1, 1, |_, _| f32::from_bits(0x3e414c15));
+30
View File
@@ -253,6 +253,36 @@ 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).
### Signed Levels, driven grayscale weights and grayscale gradients
The **grayscale HDR range viewer** matches **167,424/167,424 pixels across 18 cases**, maximum error zero. This includes all 35,328 pixels of the nine signed range inputs described under [gradient interpolation](#gradient-interpolation-color-blend-and-chrominance). At 64² the input to the inverted Levels filter was already exact. An independent pixel expression that takes the absolute value, evaluates 2 raised to its base-two logarithm, restores the sign and subtracts from one matched its entire 4,096-pixel intermediate. Direct subtraction matched 2,503/4,096, maximum 9.53674316e−7. Levels now honors the intermediate clamp on load, cook and save and uses the signed power curve.
The **color to mask** root matches all 132,096 pixels of its original four cases, four 64² format cases and independent 32² case. In nine further cases **36,075/36,096** match. The only differences are 21 pixels in the 64² F32 output, maximum 1.19209290e−7. Capturing every connected primitive locates all 21 at the final Levels filter. Its incoming images and every earlier filter match, including the grayscale weights driven by a function.
For the nine mask cases, form each original float channel c at integer (x,y) as ((x×(13+4c)+y×(29+2c)+xy×(3+c)+17c) mod 257)/256. In the left half replace RGB by .5×RGB−.25+target. Set column zero to the target RGB and columns one and two to alpha zero and one. Each 64² case uses seed 91 and the same field. The signed case additionally maps RGB to 3×RGB−1. All other rows use F32.
| Input and output dimensions | Seed | Target RGB | Keying type | Flatten alpha | Range / softness |
|---|---:|---|---:|---|---|
| 16² | 17 | (.25,.5,.75) | 0 | off | .25 / .125 |
| 64², U8, U16, F16 and F32 | 91 | (.375,.625,.8125) | 1 | on | .375 / .1875 |
| 128² | 73 | (.3125,.6875,.25) | 1 | off | .5 / .25 |
| 32×16 input, 32² output | 39 | (.125,.75,.375) | 0 | on | .5625 / .25 |
| 32² | 137 | (.375,.625,.8125) | 0 | off | .0625 / .03125 |
| 32², signed | 159 | (.3125,.4375,.6875) | 1 | on | .5 / .375 |
The isolated **grayscale conversion** matches **122,880/122,880 pixels across 30 cases**, including the sign of zero and all four output formats. At 64² let channel c be (((13x+31y+7xy+47c) mod 1024)−384)/96. Replace the first 16 pixels of row zero by −2, −1, −.5, −.25, −.125, −.0625, −0, +0, .125, .25, .5, .75, 1, 1.5, 2 and 3 in all lanes. Use weights (.125,.25,.5,.125) as a literal four-vector, a constant-returning function and a function reading an exposed four-vector. Run all three with flattening off and on, matte .3125, seed 131 and each output format. In F32 repeat the exposed vector at seeds 199–201 with (1,0,0,0), (0,.625,.125,.25), and (.299,.587,.114,0). The four fused multiply-adds start from positive zero. Flattening is a fused interpolation from the weighted pixel toward the matte by one minus alpha.
For **Levels**, use the same signed four-channel field, size and seed. Test the omitted clamp, explicit false and explicit true. With the input range [0,1], neutral, inverted output endpoints and per-channel midpoints (.25,.375,.625,.75) give **147,456/147,456** pixels across 36 cases, maximum zero. A second pair of probes maps [.125,.75] to [.1875,.8125] and reverses both ranges, with neutral midpoints. These 24 cases match 24,576/24,576 U8 and 24,576/24,576 U16, 23,925/24,576 F16 (maximum .00390625) and 19,527/24,576 F32 (maximum 1.43051147e−6).
Grayscale gradient output reads the same four-channel stops as color output. Saving a scalar-key document writes the equivalent native four-channel array. Grayscale interpolation first averages RGB at each stop. For a smooth grayscale segment, multiply the color difference by u and multiply the result by u×(3−2u) before adding the left stop. A repeated position uses its first stop on both sides. The following measurements use the three indexed input ramps and seed 103 from [gradient interpolation](#gradient-interpolation-color-blend-and-chrominance). Grayscale covers the unit ramp, the three-stop ramp with distinct RGB and the same three-stop ramp with R replicated into G and B. Each uses linear and smooth interpolation. The duplicate-position color ramp uses positions (.125,.5,.5,.75), signed biases (.5,.25,−.25,0) and colors (.375,.75,.875,.6875), (.875,.0625,.3125,.25), (.1875,.75,.25,.8125), (.25,.5625,.75,.375).
| Controls | U8 exact / total | U16 exact / total | F16 exact / total | F32 exact / total |
|---|---:|---:|---:|---:|
| Six grayscale ramps | 405,239/405,504 | 336,699/405,504 | 405,504/405,504 | 405,504/405,504 |
| Two duplicate-position color ramps | 135,168/135,168 | 125,227/135,168 | 135,168/135,168 | 135,168/135,168 |
Every floating-point maximum in the gradient table is zero. Each unsigned mismatch is one stored level. The four-stop irregular-position F32 control from the previous batch remains open.
### Gradient interpolation, color blend and chrominance
The **color blend** and **chrominance extract** roots each match **171,264/171,264 pixels in 18 cases**, maximum error zero. The original four cases account for 114,688 pixels per root. The four 64² output formats at seed 42 and the independent 32² F32 case account for 17,408. Repeat the nine [original color input cases](#color-burn-and-color-dodge) for a further 39,168. Color blend uses the same foreground, background and mask with opacity .375 in the 16², 128² and signed cases and .8125 elsewhere. Chrominance takes only the original foreground. Before the fix the independent color blend matched 1,021/1,024 pixels, maximum .00676953793. Seven of its grayscale-to-color gradient pixels differed by up to 23 byte levels. The incoming scalar image matched in full.
+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 **214 Parity**, **27 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 **215 Parity**, **26 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)
[Grayscale sampler measurements](parity-fixes.md#grayscale-sampling-of-color-inputs) · [Value sampling across 240 typed comparisons](parity-fixes.md#value-processor-texture-filtering)
@@ -138,7 +138,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
| [color_space_conversion.sbs/srgb_to_linear_srgb](../assets/sbs/color_space_conversion.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [color_space_conversion.sbs/srgb_to_linear_srgb_grayscale](../assets/sbs/color_space_conversion.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [color_temperature_adjustment.sbs/color_temperature_adjustment](../assets/sbs/color_temperature_adjustment.sbs) | 1 | No | [Parity · 18 cases, 171,264 exact RGBA pixels](parity-fixes.md#color-temperature-range-reductions-sky-parameters-and-polygon-paths) |
| [color_to_mask.sbs/color_to_mask](../assets/sbs/color_to_mask.sbs) | 1 | Yes | [In progress · function-valued grayscale weights differ](parity-fixes.md#gradient-interpolation-color-blend-and-chrominance) |
| [color_to_mask.sbs/color_to_mask](../assets/sbs/color_to_mask.sbs) | 1 | Yes | [In progress · 21 of 168,192 pixels differ at final Levels](parity-fixes.md#signed-levels-driven-grayscale-weights-and-grayscale-gradients) |
| [color_to_mask_v2.sbs/color_to_mask](../assets/sbs/color_to_mask_v2.sbs) | 2 | No | [Too hard: 1 pixel remains](parity-fixes.md#remaining-differences) |
| [composite.sbs/composite/background/uniform_color_float3](../assets/sbs/composite.sbs) | 0 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [composite.sbs/composite/blends/blend_content](../assets/sbs/composite.sbs) | 3 | Yes | [Too hard: pixel differences](parity-fixes.md#remaining-differences) |
@@ -229,7 +229,7 @@ The first pass covered all **546 roots**, with **166 Parity** and **380 Too hard
| [hbao_2.sbs/hbao_subsample](../assets/sbs/hbao_2.sbs) | 2 | Yes | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |
| [hdr_exposure_preview.sbs/hdr_exposure_preview](../assets/sbs/hdr_exposure_preview.sbs) | 1 | No | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [hdr_merge.sbs/average_luminance_merge](../assets/sbs/hdr_merge.sbs) | 1 | Yes | [Parity · 15 cases, 165,120 exact pixels](parity-fixes.md#luminosity-axial-gradients-color-lookup-and-luminance-merge) |
| [hdr_range_viewer.sbs/hdr_range_viewer_grayscale](../assets/sbs/hdr_range_viewer.sbs) | 1 | No | [In progress · signed input exposes intermediate Levels clamping](parity-fixes.md#gradient-interpolation-color-blend-and-chrominance) |
| [hdr_range_viewer.sbs/hdr_range_viewer_grayscale](../assets/sbs/hdr_range_viewer.sbs) | 1 | No | [Parity · 18 cases, 167,424 exact pixels](parity-fixes.md#signed-levels-driven-grayscale-weights-and-grayscale-gradients) |
| [height_blend.sbs/height_blend](../assets/sbs/height_blend.sbs) | 3 | No | [Too hard: remaining pixel differences](parity-fixes.md#remaining-differences) |
| [height_extrude.sbs/impl/acceleration_struct_impl](../assets/sbs/height_extrude.sbs) | 1 | Yes | [Parity: 4 cases](parity-fixes.md#verified-cases) |
| [height_to_normal_world_units.sbs/height_to_normal_world_units](../assets/sbs/height_to_normal_world_units.sbs) | 1 | Yes | [Parity · eight cases in four formats](parity-fixes.md#height-to-normal-in-world-units) |