Last active
November 15, 2021 22:38
-
-
Save giuliano-macedo/6f8cc08de6d3ec4e6f41c50f1046e762 to your computer and use it in GitHub Desktop.
Cubic bézier function in rust (not the most performant, focused in readability)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use std::fmt; | |
#[derive(Debug, Clone, Copy)] | |
struct Point { | |
x: f64, | |
y: f64, | |
} | |
impl fmt::Display for Point { | |
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { | |
write!(f, "{}, {}", self.x, self.y) | |
} | |
} | |
impl Point { | |
fn new(x: f64, y: f64) -> Self { | |
Self { x: x, y: y } | |
} | |
} | |
#[derive(Debug)] | |
struct CubicBezier { | |
p0: Point, | |
p1: Point, | |
p2: Point, | |
p3: Point, | |
} | |
impl CubicBezier { | |
fn new(p0: Point, p1: Point, p2: Point, p3: Point) -> Self { | |
Self { | |
p0: p0, | |
p1: p1, | |
p2: p2, | |
p3: p3, | |
} | |
} | |
fn compute(&self, time: f64) -> Point { | |
let a = walk_line(self.p0, self.p1, time); | |
let b = walk_line(self.p1, self.p2, time); | |
let c = walk_line(self.p2, self.p3, time); | |
let q1 = walk_line(a, b, time); | |
let q2 = walk_line(b, c, time); | |
walk_line(q1, q2, time) | |
} | |
} | |
fn walk_line(start: Point, end: Point, time: f64) -> Point { | |
let dx = end.x - start.x; | |
let dy = end.y - start.y; | |
Point { | |
x: start.x + (time * dx), | |
y: start.y + (time * dy), | |
} | |
} | |
fn main() { | |
let bezier = CubicBezier::new( | |
Point::new(0., 0.), | |
Point::new(2., 0.), | |
Point::new(0., 2.), | |
Point::new(2., 2.), | |
); | |
let precision = 1000; | |
for i in 0..(precision + 1) { | |
let t = (i as f64) / (precision as f64); | |
println!("{}", bezier.compute(t)); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Output: