nalgebra/geometry/
point_construction.rs

1#[cfg(feature = "arbitrary")]
2use quickcheck::{Arbitrary, Gen};
3
4use num::{Bounded, One, Zero};
5#[cfg(feature = "rand-no-std")]
6use rand::{
7    distributions::{Distribution, Standard},
8    Rng,
9};
10
11use crate::base::allocator::Allocator;
12use crate::base::dimension::{DimNameAdd, DimNameSum, U1};
13use crate::base::{DefaultAllocator, Scalar};
14use crate::{
15    Const, DimName, OPoint, OVector, Point1, Point2, Point3, Point4, Point5, Point6, Vector1,
16    Vector2, Vector3, Vector4, Vector5, Vector6,
17};
18use simba::scalar::{ClosedDivAssign, SupersetOf};
19
20use crate::geometry::Point;
21
22impl<T: Scalar + Zero, D: DimName> Default for OPoint<T, D>
23where
24    DefaultAllocator: Allocator<D>,
25{
26    fn default() -> Self {
27        Self::origin()
28    }
29}
30
31/// # Other construction methods
32impl<T: Scalar, D: DimName> OPoint<T, D>
33where
34    DefaultAllocator: Allocator<D>,
35{
36    /// Creates a new point with all coordinates equal to zero.
37    ///
38    /// # Example
39    ///
40    /// ```
41    /// # use nalgebra::{Point2, Point3};
42    /// // This works in any dimension.
43    /// // The explicit crate::<f32> type annotation may not always be needed,
44    /// // depending on the context of type inference.
45    /// let pt = Point2::<f32>::origin();
46    /// assert!(pt.x == 0.0 && pt.y == 0.0);
47    ///
48    /// let pt = Point3::<f32>::origin();
49    /// assert!(pt.x == 0.0 && pt.y == 0.0 && pt.z == 0.0);
50    /// ```
51    #[inline]
52    pub fn origin() -> Self
53    where
54        T: Zero,
55    {
56        Self::from(OVector::from_element(T::zero()))
57    }
58
59    /// Creates a new point from a slice.
60    ///
61    /// # Example
62    ///
63    /// ```
64    /// # use nalgebra::{Point2, Point3};
65    /// let data = [ 1.0, 2.0, 3.0 ];
66    ///
67    /// let pt = Point2::from_slice(&data[..2]);
68    /// assert_eq!(pt, Point2::new(1.0, 2.0));
69    ///
70    /// let pt = Point3::from_slice(&data);
71    /// assert_eq!(pt, Point3::new(1.0, 2.0, 3.0));
72    /// ```
73    #[inline]
74    pub fn from_slice(components: &[T]) -> Self {
75        Self::from(OVector::from_row_slice(components))
76    }
77
78    /// Creates a new point from its homogeneous vector representation.
79    ///
80    /// In practice, this builds a D-dimensional points with the same first D component as `v`
81    /// divided by the last component of `v`. Returns `None` if this divisor is zero.
82    ///
83    /// # Example
84    ///
85    /// ```
86    /// # use nalgebra::{Point2, Point3, Vector3, Vector4};
87    ///
88    /// let coords = Vector4::new(1.0, 2.0, 3.0, 1.0);
89    /// let pt = Point3::from_homogeneous(coords);
90    /// assert_eq!(pt, Some(Point3::new(1.0, 2.0, 3.0)));
91    ///
92    /// // All component of the result will be divided by the
93    /// // last component of the vector, here 2.0.
94    /// let coords = Vector4::new(1.0, 2.0, 3.0, 2.0);
95    /// let pt = Point3::from_homogeneous(coords);
96    /// assert_eq!(pt, Some(Point3::new(0.5, 1.0, 1.5)));
97    ///
98    /// // Fails because the last component is zero.
99    /// let coords = Vector4::new(1.0, 2.0, 3.0, 0.0);
100    /// let pt = Point3::from_homogeneous(coords);
101    /// assert!(pt.is_none());
102    ///
103    /// // Works also in other dimensions.
104    /// let coords = Vector3::new(1.0, 2.0, 1.0);
105    /// let pt = Point2::from_homogeneous(coords);
106    /// assert_eq!(pt, Some(Point2::new(1.0, 2.0)));
107    /// ```
108    #[inline]
109    pub fn from_homogeneous(v: OVector<T, DimNameSum<D, U1>>) -> Option<Self>
110    where
111        T: Scalar + Zero + One + ClosedDivAssign,
112        D: DimNameAdd<U1>,
113        DefaultAllocator: Allocator<DimNameSum<D, U1>>,
114    {
115        if !v[D::dim()].is_zero() {
116            let coords = v.generic_view((0, 0), (D::name(), Const::<1>)) / v[D::dim()].clone();
117            Some(Self::from(coords))
118        } else {
119            None
120        }
121    }
122
123    /// Cast the components of `self` to another type.
124    ///
125    /// # Example
126    /// ```
127    /// # use nalgebra::Point2;
128    /// let pt = Point2::new(1.0f64, 2.0);
129    /// let pt2 = pt.cast::<f32>();
130    /// assert_eq!(pt2, Point2::new(1.0f32, 2.0));
131    /// ```
132    pub fn cast<To: Scalar>(self) -> OPoint<To, D>
133    where
134        OPoint<To, D>: SupersetOf<Self>,
135        DefaultAllocator: Allocator<D>,
136    {
137        crate::convert(self)
138    }
139}
140
141/*
142 *
143 * Traits that build points.
144 *
145 */
146impl<T: Scalar + Bounded, D: DimName> Bounded for OPoint<T, D>
147where
148    DefaultAllocator: Allocator<D>,
149{
150    #[inline]
151    fn max_value() -> Self {
152        Self::from(OVector::max_value())
153    }
154
155    #[inline]
156    fn min_value() -> Self {
157        Self::from(OVector::min_value())
158    }
159}
160
161#[cfg(feature = "rand-no-std")]
162impl<T: Scalar, D: DimName> Distribution<OPoint<T, D>> for Standard
163where
164    Standard: Distribution<T>,
165    DefaultAllocator: Allocator<D>,
166{
167    /// Generate a `Point` where each coordinate is an independent variate from `[0, 1)`.
168    #[inline]
169    fn sample<'a, G: Rng + ?Sized>(&self, rng: &mut G) -> OPoint<T, D> {
170        OPoint::from(rng.gen::<OVector<T, D>>())
171    }
172}
173
174#[cfg(feature = "arbitrary")]
175impl<T: Scalar + Arbitrary + Send, D: DimName> Arbitrary for OPoint<T, D>
176where
177    <DefaultAllocator as Allocator<D>>::Buffer<T>: Send,
178    DefaultAllocator: Allocator<D>,
179{
180    #[inline]
181    fn arbitrary(g: &mut Gen) -> Self {
182        Self::from(OVector::arbitrary(g))
183    }
184}
185
186/*
187 *
188 * Small points construction from components.
189 *
190 */
191// NOTE: the impl for Point1 is not with the others so that we
192// can add a section with the impl block comment.
193/// # Construction from individual components
194impl<T: Scalar> Point1<T> {
195    /// Initializes this point from its components.
196    ///
197    /// # Example
198    ///
199    /// ```
200    /// # use nalgebra::Point1;
201    /// let p = Point1::new(1.0);
202    /// assert_eq!(p.x, 1.0);
203    /// ```
204    #[inline]
205    pub const fn new(x: T) -> Self {
206        Point {
207            coords: Vector1::new(x),
208        }
209    }
210}
211macro_rules! componentwise_constructors_impl(
212    ($($doc: expr; $Point: ident, $Vector: ident, $($args: ident:$irow: expr),*);* $(;)*) => {$(
213        impl<T: Scalar> $Point<T> {
214            #[doc = "Initializes this point from its components."]
215            #[doc = "# Example\n```"]
216            #[doc = $doc]
217            #[doc = "```"]
218            #[inline]
219            pub const fn new($($args: T),*) -> Self {
220                Point { coords: $Vector::new($($args),*) }
221            }
222        }
223    )*}
224);
225
226componentwise_constructors_impl!(
227    "# use nalgebra::Point2;\nlet p = Point2::new(1.0, 2.0);\nassert!(p.x == 1.0 && p.y == 2.0);";
228    Point2, Vector2, x:0, y:1;
229    "# use nalgebra::Point3;\nlet p = Point3::new(1.0, 2.0, 3.0);\nassert!(p.x == 1.0 && p.y == 2.0 && p.z == 3.0);";
230    Point3, Vector3, x:0, y:1, z:2;
231    "# use nalgebra::Point4;\nlet p = Point4::new(1.0, 2.0, 3.0, 4.0);\nassert!(p.x == 1.0 && p.y == 2.0 && p.z == 3.0 && p.w == 4.0);";
232    Point4, Vector4, x:0, y:1, z:2, w:3;
233    "# use nalgebra::Point5;\nlet p = Point5::new(1.0, 2.0, 3.0, 4.0, 5.0);\nassert!(p.x == 1.0 && p.y == 2.0 && p.z == 3.0 && p.w == 4.0 && p.a == 5.0);";
234    Point5, Vector5, x:0, y:1, z:2, w:3, a:4;
235    "# use nalgebra::Point6;\nlet p = Point6::new(1.0, 2.0, 3.0, 4.0, 5.0, 6.0);\nassert!(p.x == 1.0 && p.y == 2.0 && p.z == 3.0 && p.w == 4.0 && p.a == 5.0 && p.b == 6.0);";
236    Point6, Vector6, x:0, y:1, z:2, w:3, a:4, b:5;
237);