diff --git a/editor/src/messages/portfolio/document/node_graph/node_properties.rs b/editor/src/messages/portfolio/document/node_graph/node_properties.rs index 8a0db9b810..553776457f 100644 --- a/editor/src/messages/portfolio/document/node_graph/node_properties.rs +++ b/editor/src/messages/portfolio/document/node_graph/node_properties.rs @@ -329,6 +329,7 @@ pub(crate) fn property_from_type( Some(x) if id_is::(x) || id_is::(x) => number_or_slider(default_info, bounded(number_input, f64::NEG_INFINITY, f64::INFINITY), false), Some(x) if id_is::(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::from(u32::MAX))).into(), Some(x) if id_is::(x) => number_widget(default_info, bounded(number_input.int(), 0., f64::INFINITY)).into(), + Some(x) if id_is::(x) => number_widget(default_info, bounded(number_input.int(), f64::NEG_INFINITY, f64::INFINITY)).into(), Some(x) if id_is::(x) => bool_widget(default_info, CheckboxInput::default()).into(), Some(x) if id_is::(x) => text_widget(default_info).into(), Some(x) if id_is::(x) => vec2_widget(default_info, "X", "Y", "", None, false), @@ -1152,6 +1153,14 @@ pub fn number_widget(parameter_widgets_info: ParameterWidgetsInfo, number_props: .on_commit(commit_value) .widget_instance(), ]), + Some(&TaggedValue::I64(x)) => widgets.extend_from_slice(&[ + Separator::new(SeparatorStyle::Unrelated).widget_instance(), + number_props + .value(Some(x as f64)) + .on_update(parameter_widgets_info.update_value(move |x: &NumberInput| TaggedValue::I64(x.value.unwrap().round() as i64))) + .on_commit(commit_value) + .widget_instance(), + ]), Some(&TaggedValue::DVec2(dvec2)) => widgets.extend_from_slice(&[ Separator::new(SeparatorStyle::Unrelated).widget_instance(), number_props diff --git a/frontend/src/components/widgets/inputs/NumberInput.svelte b/frontend/src/components/widgets/inputs/NumberInput.svelte index 10091f443c..8999fb1734 100644 --- a/frontend/src/components/widgets/inputs/NumberInput.svelte +++ b/frontend/src/components/widgets/inputs/NumberInput.svelte @@ -181,18 +181,23 @@ text = displayText(sanitized, unit); } + // Rounds half away from zero, the graph's one Number to Integer rule, where `Math.round` would carry -1.5 up to -1 + function roundToInteger(value: number): number { + return Math.sign(value) * Math.round(Math.abs(value)); + } + // Called internally to update the value indirectly by informing the parent component of the new value, // so it can update the prop for this component, finally yielding the value change. function updateValue(newValue: number | undefined): number | undefined { // Check if the new value is valid, otherwise we use the old value (rounded if it's an integer) - const oldValue = value !== undefined && isInteger ? Math.round(value) : value; + const oldValue = value !== undefined && isInteger ? roundToInteger(value) : value; let newValueValidated = newValue !== undefined ? newValue : oldValue; if (newValueValidated !== undefined) { if (typeof min === "number" && !Number.isNaN(min)) newValueValidated = Math.max(newValueValidated, min); if (typeof max === "number" && !Number.isNaN(max)) newValueValidated = Math.min(newValueValidated, max); - if (isInteger) newValueValidated = Math.round(newValueValidated); + if (isInteger) newValueValidated = roundToInteger(newValueValidated); rangeSliderValue = newValueValidated; rangeSliderValueAsRendered = newValueValidated; @@ -529,7 +534,7 @@ cumulativeDragDelta += dragDelta; const combined = initialValue + cumulativeDragDelta; - const combineSnapped = snapping || isInteger ? Math.round(combined) : combined; + const combineSnapped = snapping || isInteger ? roundToInteger(combined) : combined; const newValue = updateValue(combineSnapped); @@ -577,7 +582,7 @@ } // Snap the slider value to the nearest integer if the Ctrl key is held, or the widget is set to integer mode. - const snappedValue = ctrlKeyDown || isInteger ? Math.round(roundedValue) : roundedValue; + const snappedValue = ctrlKeyDown || isInteger ? roundToInteger(roundedValue) : roundedValue; // The first "input" event upon mousedown means we transition to a "Deciding" state, allowing us to wait for the // next event to determine if the user is dragging (to slide the slider) or releasing (to edit the numerical text field). diff --git a/node-graph/graph-craft/src/document/value.rs b/node-graph/graph-craft/src/document/value.rs index 10b74c0f6a..c4bb6def67 100644 --- a/node-graph/graph-craft/src/document/value.rs +++ b/node-graph/graph-craft/src/document/value.rs @@ -523,6 +523,7 @@ tagged_value! { F64(f64), U32(u32), U64(u64), + I64(i64), Bool(bool), String(String), #[serde(alias = "IVec2", alias = "UVec2", alias = "Vec2")] @@ -605,6 +606,7 @@ impl TaggedValue { TaggedValue::String(x) => format!("\"{x}\""), TaggedValue::U32(x) => x.to_string() + "_u32", TaggedValue::U64(x) => x.to_string() + "_u64", + TaggedValue::I64(x) => x.to_string() + "_i64", TaggedValue::F32(x) => x.to_string() + "_f32", TaggedValue::F64(x) => x.to_string() + "_f64", TaggedValue::Bool(x) => x.to_string(), @@ -705,6 +707,7 @@ impl TaggedValue { () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::F32).ok()?, () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::U64).ok()?, () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::U32).ok()?, + () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::I64).ok()?, () if ty == TypeId::of::() => to_dvec2(string).map(TaggedValue::DVec2)?, () if ty == TypeId::of::() => FromStr::from_str(string).map(TaggedValue::Bool).ok()?, () if ty == TypeId::of::() => to_color(string).map(TaggedValue::Color)?, @@ -866,6 +869,7 @@ impl Display for TaggedValue { TaggedValue::String(x) => f.write_str(x), TaggedValue::U32(x) => f.write_fmt(format_args!("{x}")), TaggedValue::U64(x) => f.write_fmt(format_args!("{x}")), + TaggedValue::I64(x) => f.write_fmt(format_args!("{x}")), TaggedValue::F32(x) => f.write_fmt(format_args!("{x}")), TaggedValue::F64(x) => f.write_fmt(format_args!("{x}")), TaggedValue::Bool(x) => f.write_fmt(format_args!("{x}")), diff --git a/node-graph/libraries/core-types/src/ops.rs b/node-graph/libraries/core-types/src/ops.rs index 6ba13edeb2..3fb436b015 100644 --- a/node-graph/libraries/core-types/src/ops.rs +++ b/node-graph/libraries/core-types/src/ops.rs @@ -75,30 +75,37 @@ pub trait FromAnchorPosition { fn from_anchor_position(position: DVec2) -> Self; } -/// Implements the [`Convert`] trait for conversion between the cartesian product of Rust's primitive numeric types. +/// Implements the [`Convert`] trait between Rust's primitive numeric types. A float narrowing to an integer rounds to the +/// nearest whole number (half away from zero), the graph's one Number to Integer rule, so float noise like 5.999999 reaches +/// an integer connector as 6 rather than truncating to 5. Every other pair is a plain `as` cast. macro_rules! impl_convert { - ($from:ty, $to:ty) => { + ($from:ty => $to:ty) => { impl Convert<$to, ()> for $from { async fn convert(self, _: Footprint, _: ()) -> $to { self as $to } } }; - ($to:ty) => { - impl_convert!(f32, $to); - impl_convert!(f64, $to); - impl_convert!(i8, $to); - impl_convert!(u8, $to); - impl_convert!(u16, $to); - impl_convert!(i16, $to); - impl_convert!(i32, $to); - impl_convert!(u32, $to); - impl_convert!(i64, $to); - impl_convert!(u64, $to); - impl_convert!(i128, $to); - impl_convert!(u128, $to); - impl_convert!(isize, $to); - impl_convert!(usize, $to); + ($from:ty => round $to:ty) => { + impl Convert<$to, ()> for $from { + async fn convert(self, _: Footprint, _: ()) -> $to { + self.round() as $to + } + } + }; + (from_integers $to:ty) => { + impl_convert!(i8 => $to); + impl_convert!(u8 => $to); + impl_convert!(u16 => $to); + impl_convert!(i16 => $to); + impl_convert!(i32 => $to); + impl_convert!(u32 => $to); + impl_convert!(i64 => $to); + impl_convert!(u64 => $to); + impl_convert!(i128 => $to); + impl_convert!(u128 => $to); + impl_convert!(isize => $to); + impl_convert!(usize => $to); impl Convert for $to { async fn convert(self, _: Footprint, _: ()) -> DVec2 { @@ -106,21 +113,31 @@ macro_rules! impl_convert { } } }; + (float $to:ty) => { + impl_convert!(f32 => $to); + impl_convert!(f64 => $to); + impl_convert!(from_integers $to); + }; + (integer $to:ty) => { + impl_convert!(f32 => round $to); + impl_convert!(f64 => round $to); + impl_convert!(from_integers $to); + }; } -impl_convert!(f32); -impl_convert!(f64); -impl_convert!(i8); -impl_convert!(u8); -impl_convert!(u16); -impl_convert!(i16); -impl_convert!(i32); -impl_convert!(u32); -impl_convert!(i64); -impl_convert!(u64); -impl_convert!(i128); -impl_convert!(u128); -impl_convert!(isize); -impl_convert!(usize); +impl_convert!(float f32); +impl_convert!(float f64); +impl_convert!(integer i8); +impl_convert!(integer u8); +impl_convert!(integer u16); +impl_convert!(integer i16); +impl_convert!(integer i32); +impl_convert!(integer u32); +impl_convert!(integer i64); +impl_convert!(integer u64); +impl_convert!(integer i128); +impl_convert!(integer u128); +impl_convert!(integer isize); +impl_convert!(integer usize); /// Implements the [`Convert`] trait from `bool` into each numeric type, embedding `false` and `true` as exactly 0 and 1. /// The reverse direction is deliberately absent: a number only becomes a truth value through an explicit comparison. @@ -136,3 +153,17 @@ macro_rules! impl_convert_from_bool { }; } impl_convert_from_bool!(f32, f64, i8, u8, u16, i16, i32, u32, i64, u64, i128, u128, isize, usize); + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn a_float_narrows_to_the_nearest_integer() { + let footprint = Footprint::default(); + assert_eq!(Convert::::convert(5.999_999_f64, footprint, ()).await, 6, "float noise rounds up to the whole number it meant"); + assert_eq!(Convert::::convert(2.5_f64, footprint, ()).await, 3, "ties round away from zero"); + assert_eq!(Convert::::convert(-1.5_f64, footprint, ()).await, -2); + assert_eq!(Convert::::convert(7_i64, footprint, ()).await, 7., "an integer widens exactly"); + } +}