Skip to content

Commit 88c059a

Browse files
authored
Add Normalize and Length nodes (#2837)
* Add vector length node * Add normalize node * Add comments * Make normalize node safer for the user
1 parent 24c6281 commit 88c059a

File tree

1 file changed

+20
-0
lines changed
  • node-graph/gmath-nodes/src

1 file changed

+20
-0
lines changed

node-graph/gmath-nodes/src/lib.rs

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -612,6 +612,20 @@ fn dot_product(_: impl Ctx, vector_a: DVec2, vector_b: DVec2) -> f64 {
612612
vector_a.dot(vector_b)
613613
}
614614

615+
/// Gets the length or magnitude of a vector.
616+
#[node_macro::node(category("Math: Vector"))]
617+
fn length(_: impl Ctx, vector: DVec2) -> f64 {
618+
vector.length()
619+
}
620+
621+
/// Scales the input vector to unit length while preserving it's direction. This is equivalent to dividing the input vector by it's own magnitude.
622+
///
623+
/// Returns zero when the input vector is zero.
624+
#[node_macro::node(category("Math: Vector"))]
625+
fn normalize(_: impl Ctx, vector: DVec2) -> DVec2 {
626+
vector.normalize_or_zero()
627+
}
628+
615629
#[cfg(test)]
616630
mod test {
617631
use super::*;
@@ -625,6 +639,12 @@ mod test {
625639
assert_eq!(dot_product((), vector_a, vector_b), 11.);
626640
}
627641

642+
#[test]
643+
pub fn length_function() {
644+
let vector = DVec2::new(3., 4.);
645+
assert_eq!(length((), vector), 5.);
646+
}
647+
628648
#[test]
629649
fn test_basic_expression() {
630650
let result = math((), 0., "2 + 2".to_string(), 0.);

0 commit comments

Comments
 (0)