pythagore_wasm/
point_2d.rs

1use wasm_bindgen::prelude::wasm_bindgen;
2use pythagore::{self as py, point};
3use crate::force_2d::Force2D;
4
5#[wasm_bindgen]
6#[derive(Copy, Clone, Debug)]
7pub struct Point2D {
8    point: py::Point2D<f64>,
9}
10
11#[wasm_bindgen]
12impl Point2D {
13    /// Creates a new point from given coordinates
14    #[wasm_bindgen(constructor)]
15    pub fn new(x: f64, y: f64) -> Point2D {
16        Point2D { point: point!(x, y) }
17    }
18
19    /// Creates a new origin point (same as `new Point2D(0, 0)`)
20    pub fn origin() -> Point2D {
21        Point2D { point: py::Point2D::origin() }
22    }
23
24    pub fn equals(&self, other: &Point2D) -> bool {
25        self.point == other.point
26    }
27
28    pub fn add_force(&self, force: &Force2D) -> Point2D {
29        (self.point + force.as_ref()).into()
30    }
31
32    pub fn sub(&self, other: &Point2D) -> Force2D {
33        (self.point - other.point).into()
34    }
35
36    pub fn sub_force(&self, force: &Force2D) -> Point2D {
37        (self.point - force.as_ref()).into()
38    }
39
40    // Properties
41    #[wasm_bindgen(getter)]
42    pub fn x(&self) -> f64 {
43        *self.point.x()
44    }
45
46    #[wasm_bindgen(setter)]
47    pub fn set_x(&mut self, x: f64) {
48        *self.point.x_mut() = x;
49    }
50
51    #[wasm_bindgen(getter)]
52    pub fn y(&self) -> f64 {
53        *self.point.y()
54    }
55
56    #[wasm_bindgen(setter)]
57    pub fn set_y(&mut self, y: f64) {
58        *self.point.y_mut() = y;
59    }
60}
61
62impl PartialEq for Point2D {
63    #[inline]
64    fn eq(&self, other: &Point2D) -> bool {
65        self.equals(other)
66    }
67}
68
69// Utils
70impl AsRef<py::Point2D<f64>> for Point2D {
71    fn as_ref(&self) -> &py::Point2D<f64> {
72        &self.point
73    }
74}
75
76impl AsMut<py::Point2D<f64>> for Point2D {
77    fn as_mut(&mut self) -> &mut py::Point2D<f64> {
78        &mut self.point
79    }
80}
81
82impl From<py::Point2D<f64>> for Point2D {
83    fn from(point: py::Point2D<f64>) -> Self {
84        Point2D { point }
85    }
86}