mirror of
https://github.com/GraphiteEditor/Graphite.git
synced 2026-09-19 10:58:04 +08:00
Update #[min/max] node macro attributes to #[soft/hard]_[min/max] and make them clamp their input data (#2464)
* Fix min and max macro not enforcing limits when data flows * Use trait based clamping * Remove min/max from testing * cargo fmt * Resolve into min, and hard_min * cargo fmt * fix traits * cargo fmt * fix tests * rename as soft_x * Add validation code * Clean up (not compiling because of DVec2 clamping) * Avoid needing to add trait bounds to node definitions * Code review --------- Co-authored-by: Dennis Kobert <dennis@kobert.dev> Co-authored-by: Keavon Chambers <keavon@keavon.com>
This commit is contained in:
62
node-graph/gcore/src/misc.rs
Normal file
62
node-graph/gcore/src/misc.rs
Normal file
@@ -0,0 +1,62 @@
|
||||
// TODO(TrueDoctor): Replace this with the more idiomatic approach instead of using `trait Clampable`.
|
||||
|
||||
/// A trait for types that can be clamped within a min/max range defined by f64.
|
||||
pub trait Clampable: Sized {
|
||||
/// Clamps the value to be no less than `min`.
|
||||
fn clamp_hard_min(self, min: f64) -> Self;
|
||||
/// Clamps the value to be no more than `max`.
|
||||
fn clamp_hard_max(self, max: f64) -> Self;
|
||||
}
|
||||
|
||||
// Implement for common numeric types
|
||||
macro_rules! impl_clampable_float {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Clampable for $ty {
|
||||
#[inline(always)]
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
self.max(min as $ty)
|
||||
}
|
||||
#[inline(always)]
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
self.min(max as $ty)
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
impl_clampable_float!(f32, f64);
|
||||
|
||||
macro_rules! impl_clampable_int {
|
||||
($($ty:ty),*) => {
|
||||
$(
|
||||
impl Clampable for $ty {
|
||||
#[inline(always)]
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
// Using try_from to handle potential range issues safely, though min should ideally be valid.
|
||||
// Consider using a different approach if f64 precision vs integer range is a concern.
|
||||
<$ty>::try_from(min.ceil() as i64).ok().map_or(self, |min_val| self.max(min_val))
|
||||
}
|
||||
#[inline(always)]
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
<$ty>::try_from(max.floor() as i64).ok().map_or(self, |max_val| self.min(max_val))
|
||||
}
|
||||
}
|
||||
)*
|
||||
};
|
||||
}
|
||||
// Add relevant integer types (adjust as needed)
|
||||
impl_clampable_int!(u32, u64, i32, i64);
|
||||
|
||||
// Implement for DVec2 (component-wise clamping)
|
||||
use glam::DVec2;
|
||||
impl Clampable for DVec2 {
|
||||
#[inline(always)]
|
||||
fn clamp_hard_min(self, min: f64) -> Self {
|
||||
self.max(DVec2::splat(min))
|
||||
}
|
||||
#[inline(always)]
|
||||
fn clamp_hard_max(self, max: f64) -> Self {
|
||||
self.min(DVec2::splat(max))
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user