9 點結構模塊(point.rs)

一、point.rs源碼

use super::UnknownUnit;
use crate::approxeq::ApproxEq;
use crate::approxord::{max, min};
use crate::length::Length;
use crate::num::*;
use crate::scale::Scale;
use crate::size::{Size2D, Size3D};
use crate::vector::{vec2, vec3, Vector2D, Vector3D};
use core::cmp::{Eq, PartialEq};
use core::fmt;
use core::hash::Hash;
use core::marker::PhantomData;
use core::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Neg, Sub, SubAssign};
#[cfg(feature = "mint")]
use mint;
use num_traits::real::Real;
use num_traits::{Euclid, Float, NumCast};
#[cfg(feature = "serde")]
use serde;#[cfg(feature = "bytemuck")]
use bytemuck::{Pod, Zeroable};/// A 2d Point tagged with a unit.
#[repr(C)]
pub struct Point2D<T, U> {pub x: T,pub y: T,#[doc(hidden)]pub _unit: PhantomData<U>,
}impl<T: Copy, U> Copy for Point2D<T, U> {}impl<T: Clone, U> Clone for Point2D<T, U> {fn clone(&self) -> Self {Point2D {x: self.x.clone(),y: self.y.clone(),_unit: PhantomData,}}
}//反序列化
#[cfg(feature = "serde")]
impl<'de, T, U> serde::Deserialize<'de> for Point2D<T, U>
whereT: serde::Deserialize<'de>,
{fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>whereD: serde::Deserializer<'de>,{let (x, y) = serde::Deserialize::deserialize(deserializer)?;Ok(Point2D {x,y,_unit: PhantomData,})}
}//序列化
#[cfg(feature = "serde")]
impl<T, U> serde::Serialize for Point2D<T, U>
whereT: serde::Serialize,
{fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>whereS: serde::Serializer,{(&self.x, &self.y).serialize(serializer)}
}
//模糊測試的庫特性,提供隨機數,提高測試范圍
#[cfg(feature = "arbitrary")]
impl<'a, T, U> arbitrary::Arbitrary<'a> for Point2D<T, U>
whereT: arbitrary::Arbitrary<'a>,
{fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {let (x, y) = arbitrary::Arbitrary::arbitrary(u)?;Ok(Point2D {x,y,_unit: PhantomData,})}
}#[cfg(feature = "bytemuck")]
unsafe impl<T: Zeroable, U> Zeroable for Point2D<T, U> {}#[cfg(feature = "bytemuck")]
unsafe impl<T: Pod, U: 'static> Pod for Point2D<T, U> {}impl<T, U> Eq for Point2D<T, U> where T: Eq {}impl<T, U> PartialEq for Point2D<T, U>
whereT: PartialEq,
{fn eq(&self, other: &Self) -> bool {self.x == other.x && self.y == other.y}
}impl<T, U> Hash for Point2D<T, U>
whereT: Hash,
{fn hash<H: core::hash::Hasher>(&self, h: &mut H) {self.x.hash(h);self.y.hash(h);}
}mint_vec!(Point2D[x, y] = Point2);impl<T: fmt::Debug, U> fmt::Debug for Point2D<T, U> {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {f.debug_tuple("").field(&self.x).field(&self.y).finish()}
}impl<T: Default, U> Default for Point2D<T, U> {fn default() -> Self {Point2D::new(Default::default(), Default::default())}
}impl<T, U> Point2D<T, U> {/// Constructor, setting all components to zero.#[inline]pub fn origin() -> SelfwhereT: Zero,{point2(Zero::zero(), Zero::zero())}/// The same as [`Point2D::origin`].#[inline]pub fn zero() -> SelfwhereT: Zero,{Self::origin()}/// Constructor taking scalar values directly.#[inline]pub const fn new(x: T, y: T) -> Self {Point2D {x,y,_unit: PhantomData,}}/// Constructor taking properly Lengths instead of scalar values.#[inline]pub fn from_lengths(x: Length<T, U>, y: Length<T, U>) -> Self {point2(x.0, y.0)}/// Constructor setting all components to the same value.#[inline]pub fn splat(v: T) -> SelfwhereT: Clone,{Point2D {x: v.clone(),y: v,_unit: PhantomData,}}/// Tag a unitless value with units.#[inline]pub fn from_untyped(p: Point2D<T, UnknownUnit>) -> Self {point2(p.x, p.y)}/// Apply the function `f` to each component of this point.////// # Example////// This may be used to perform unusual arithmetic which is not already offered as methods.////// ```/// use euclid::default::Point2D;////// let p = Point2D::<u32>::new(5, 15);/// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Point2D::new(0, 5));/// ```#[inline]pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Point2D<V, U> {point2(f(self.x), f(self.y))}/// Apply the function `f` to each pair of components of this point and `rhs`.////// # Example////// This may be used to perform unusual arithmetic which is not already offered as methods.////// ```/// use euclid::{default::{Point2D, Vector2D}, point2};////// let a: Point2D<u32> = point2(50, 200);/// let b: Point2D<u32> = point2(100, 100);/// assert_eq!(a.zip(b, u32::saturating_sub), Vector2D::new(0, 100));/// ```#[inline]pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector2D<V, U> {vec2(f(self.x, rhs.x), f(self.y, rhs.y))}
}impl<T: Copy, U> Point2D<T, U> {/// Create a 3d point from this one, using the specified z value.#[inline]pub fn extend(self, z: T) -> Point3D<T, U> {point3(self.x, self.y, z)}/// Cast this point into a vector.////// Equivalent to subtracting the origin from this point.#[inline]pub fn to_vector(self) -> Vector2D<T, U> {Vector2D {x: self.x,y: self.y,_unit: PhantomData,}}/// Swap x and y.////// # Example////// ```rust/// # use euclid::{Point2D, point2};/// enum Mm {}////// let point: Point2D<_, Mm> = point2(1, -8);////// assert_eq!(point.yx(), point2(-8, 1));/// ```#[inline]pub fn yx(self) -> Self {point2(self.y, self.x)}/// Drop the units, preserving only the numeric value.////// # Example////// ```rust/// # use euclid::{Point2D, point2};/// enum Mm {}////// let point: Point2D<_, Mm> = point2(1, -8);////// assert_eq!(point.x, point.to_untyped().x);/// assert_eq!(point.y, point.to_untyped().y);/// ```#[inline]pub fn to_untyped(self) -> Point2D<T, UnknownUnit> {point2(self.x, self.y)}/// Cast the unit, preserving the numeric value.////// # Example////// ```rust/// # use euclid::{Point2D, point2};/// enum Mm {}/// enum Cm {}////// let point: Point2D<_, Mm> = point2(1, -8);////// assert_eq!(point.x, point.cast_unit::<Cm>().x);/// assert_eq!(point.y, point.cast_unit::<Cm>().y);/// ```#[inline]pub fn cast_unit<V>(self) -> Point2D<T, V> {point2(self.x, self.y)}/// Cast into an array with x and y.////// # Example////// ```rust/// # use euclid::{Point2D, point2};/// enum Mm {}////// let point: Point2D<_, Mm> = point2(1, -8);////// assert_eq!(point.to_array(), [1, -8]);/// ```#[inline]pub fn to_array(self) -> [T; 2] {[self.x, self.y]}/// Cast into a tuple with x and y.////// # Example////// ```rust/// # use euclid::{Point2D, point2};/// enum Mm {}////// let point: Point2D<_, Mm> = point2(1, -8);////// assert_eq!(point.to_tuple(), (1, -8));/// ```#[inline]pub fn to_tuple(self) -> (T, T) {(self.x, self.y)}/// Convert into a 3d point with z-coordinate equals to zero.#[inline]pub fn to_3d(self) -> Point3D<T, U>whereT: Zero,{point3(self.x, self.y, Zero::zero())}/// Rounds each component to the nearest integer value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point2;/// enum Mm {}////// assert_eq!(point2::<_, Mm>(-0.1, -0.8).round(), point2::<_, Mm>(0.0, -1.0))/// ```#[inline]#[must_use]pub fn round(self) -> SelfwhereT: Round,{point2(self.x.round(), self.y.round())}/// Rounds each component to the smallest integer equal or greater than the original value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point2;/// enum Mm {}////// assert_eq!(point2::<_, Mm>(-0.1, -0.8).ceil(), point2::<_, Mm>(0.0, 0.0))/// ```#[inline]#[must_use]pub fn ceil(self) -> SelfwhereT: Ceil,{point2(self.x.ceil(), self.y.ceil())}/// Rounds each component to the biggest integer equal or lower than the original value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point2;/// enum Mm {}////// assert_eq!(point2::<_, Mm>(-0.1, -0.8).floor(), point2::<_, Mm>(-1.0, -1.0))/// ```#[inline]#[must_use]pub fn floor(self) -> SelfwhereT: Floor,{point2(self.x.floor(), self.y.floor())}/// Linearly interpolate between this point and another point.////// # Example////// ```rust/// use euclid::point2;/// use euclid::default::Point2D;////// let from: Point2D<_> = point2(0.0, 10.0);/// let to:  Point2D<_> = point2(8.0, -4.0);////// assert_eq!(from.lerp(to, -1.0), point2(-8.0,  24.0));/// assert_eq!(from.lerp(to,  0.0), point2( 0.0,  10.0));/// assert_eq!(from.lerp(to,  0.5), point2( 4.0,   3.0));/// assert_eq!(from.lerp(to,  1.0), point2( 8.0,  -4.0));/// assert_eq!(from.lerp(to,  2.0), point2(16.0, -18.0));/// ```#[inline]pub fn lerp(self, other: Self, t: T) -> SelfwhereT: One + Sub<Output = T> + Mul<Output = T> + Add<Output = T>,{let one_t = T::one() - t;point2(one_t * self.x + t * other.x, one_t * self.y + t * other.y)}
}impl<T: PartialOrd, U> Point2D<T, U> {#[inline]pub fn min(self, other: Self) -> Self {point2(min(self.x, other.x), min(self.y, other.y))}#[inline]pub fn max(self, other: Self) -> Self {point2(max(self.x, other.x), max(self.y, other.y))}/// Returns the point each component of which clamped by corresponding/// components of `start` and `end`.////// Shortcut for `self.max(start).min(end)`.#[inline]pub fn clamp(self, start: Self, end: Self) -> SelfwhereT: Copy,{self.max(start).min(end)}
}impl<T: NumCast + Copy, U> Point2D<T, U> {/// Cast from one numeric representation to another, preserving the units.////// When casting from floating point to integer coordinates, the decimals are truncated/// as one would expect from a simple cast, but this behavior does not always make sense/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.#[inline]pub fn cast<NewT: NumCast>(self) -> Point2D<NewT, U> {self.try_cast().unwrap()}/// Fallible cast from one numeric representation to another, preserving the units.////// When casting from floating point to integer coordinates, the decimals are truncated/// as one would expect from a simple cast, but this behavior does not always make sense/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.pub fn try_cast<NewT: NumCast>(self) -> Option<Point2D<NewT, U>> {match (NumCast::from(self.x), NumCast::from(self.y)) {(Some(x), Some(y)) => Some(point2(x, y)),_ => None,}}// Convenience functions for common casts/// Cast into an `f32` point.#[inline]pub fn to_f32(self) -> Point2D<f32, U> {self.cast()}/// Cast into an `f64` point.#[inline]pub fn to_f64(self) -> Point2D<f64, U> {self.cast()}/// Cast into an `usize` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_usize(self) -> Point2D<usize, U> {self.cast()}/// Cast into an `u32` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_u32(self) -> Point2D<u32, U> {self.cast()}/// Cast into an `i32` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_i32(self) -> Point2D<i32, U> {self.cast()}/// Cast into an `i64` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_i64(self) -> Point2D<i64, U> {self.cast()}
}impl<T: Float, U> Point2D<T, U> {/// Returns `true` if all members are finite.#[inline]pub fn is_finite(self) -> bool {self.x.is_finite() && self.y.is_finite()}
}impl<T: Copy + Add<T, Output = T>, U> Point2D<T, U> {#[inline]pub fn add_size(self, other: &Size2D<T, U>) -> Self {point2(self.x + other.width, self.y + other.height)}
}impl<T: Real + Sub<T, Output = T>, U> Point2D<T, U> {#[inline]pub fn distance_to(self, other: Self) -> T {(self - other).length()}
}impl<T: Neg, U> Neg for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn neg(self) -> Self::Output {point2(-self.x, -self.y)}
}impl<T: Add, U> Add<Size2D<T, U>> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn add(self, other: Size2D<T, U>) -> Self::Output {point2(self.x + other.width, self.y + other.height)}
}impl<T: AddAssign, U> AddAssign<Size2D<T, U>> for Point2D<T, U> {#[inline]fn add_assign(&mut self, other: Size2D<T, U>) {self.x += other.width;self.y += other.height;}
}impl<T: Add, U> Add<Vector2D<T, U>> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn add(self, other: Vector2D<T, U>) -> Self::Output {point2(self.x + other.x, self.y + other.y)}
}impl<T: Copy + Add<T, Output = T>, U> AddAssign<Vector2D<T, U>> for Point2D<T, U> {#[inline]fn add_assign(&mut self, other: Vector2D<T, U>) {*self = *self + other;}
}impl<T: Sub, U> Sub for Point2D<T, U> {type Output = Vector2D<T::Output, U>;#[inline]fn sub(self, other: Self) -> Self::Output {vec2(self.x - other.x, self.y - other.y)}
}impl<T: Sub, U> Sub<Size2D<T, U>> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn sub(self, other: Size2D<T, U>) -> Self::Output {point2(self.x - other.width, self.y - other.height)}
}impl<T: SubAssign, U> SubAssign<Size2D<T, U>> for Point2D<T, U> {#[inline]fn sub_assign(&mut self, other: Size2D<T, U>) {self.x -= other.width;self.y -= other.height;}
}impl<T: Sub, U> Sub<Vector2D<T, U>> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn sub(self, other: Vector2D<T, U>) -> Self::Output {point2(self.x - other.x, self.y - other.y)}
}impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector2D<T, U>> for Point2D<T, U> {#[inline]fn sub_assign(&mut self, other: Vector2D<T, U>) {*self = *self - other;}
}impl<T: Copy + Mul, U> Mul<T> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn mul(self, scale: T) -> Self::Output {point2(self.x * scale, self.y * scale)}
}impl<T: Copy + Mul<T, Output = T>, U> MulAssign<T> for Point2D<T, U> {#[inline]fn mul_assign(&mut self, scale: T) {*self = *self * scale;}
}impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Point2D<T, U1> {type Output = Point2D<T::Output, U2>;#[inline]fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {point2(self.x * scale.0, self.y * scale.0)}
}impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Point2D<T, U> {#[inline]fn mul_assign(&mut self, scale: Scale<T, U, U>) {self.x *= scale.0;self.y *= scale.0;}
}impl<T: Copy + Div, U> Div<T> for Point2D<T, U> {type Output = Point2D<T::Output, U>;#[inline]fn div(self, scale: T) -> Self::Output {point2(self.x / scale, self.y / scale)}
}impl<T: Copy + Div<T, Output = T>, U> DivAssign<T> for Point2D<T, U> {#[inline]fn div_assign(&mut self, scale: T) {*self = *self / scale;}
}impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Point2D<T, U2> {type Output = Point2D<T::Output, U1>;#[inline]fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {point2(self.x / scale.0, self.y / scale.0)}
}impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Point2D<T, U> {#[inline]fn div_assign(&mut self, scale: Scale<T, U, U>) {self.x /= scale.0;self.y /= scale.0;}
}impl<T: Zero, U> Zero for Point2D<T, U> {#[inline]fn zero() -> Self {Self::origin()}
}impl<T: Round, U> Round for Point2D<T, U> {/// See [`Point2D::round`].#[inline]fn round(self) -> Self {self.round()}
}impl<T: Ceil, U> Ceil for Point2D<T, U> {/// See [`Point2D::ceil`].#[inline]fn ceil(self) -> Self {self.ceil()}
}impl<T: Floor, U> Floor for Point2D<T, U> {/// See [`Point2D::floor`].#[inline]fn floor(self) -> Self {self.floor()}
}impl<T: ApproxEq<T>, U> ApproxEq<Point2D<T, U>> for Point2D<T, U> {#[inline]fn approx_epsilon() -> Self {point2(T::approx_epsilon(), T::approx_epsilon())}#[inline]fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {self.x.approx_eq_eps(&other.x, &eps.x) && self.y.approx_eq_eps(&other.y, &eps.y)}
}impl<T: Euclid, U> Point2D<T, U> {/// Calculates the least nonnegative remainder of `self (mod other)`.////// # Example////// ```rust/// use euclid::point2;/// use euclid::default::{Point2D, Size2D};////// let p = Point2D::new(7.0, -7.0);/// let s = Size2D::new(4.0, -4.0);////// assert_eq!(p.rem_euclid(&s), point2(3.0, 1.0));/// assert_eq!((-p).rem_euclid(&s), point2(1.0, 3.0));/// assert_eq!(p.rem_euclid(&-s), point2(3.0, 1.0));/// ```#[inline]pub fn rem_euclid(&self, other: &Size2D<T, U>) -> Self {point2(self.x.rem_euclid(&other.width),self.y.rem_euclid(&other.height),)}/// Calculates Euclidean division, the matching method for `rem_euclid`.////// # Example////// ```rust/// use euclid::point2;/// use euclid::default::{Point2D, Size2D};////// let p = Point2D::new(7.0, -7.0);/// let s = Size2D::new(4.0, -4.0);////// assert_eq!(p.div_euclid(&s), point2(1.0, 2.0));/// assert_eq!((-p).div_euclid(&s), point2(-2.0, -1.0));/// assert_eq!(p.div_euclid(&-s), point2(-1.0, -2.0));/// ```#[inline]pub fn div_euclid(&self, other: &Size2D<T, U>) -> Self {point2(self.x.div_euclid(&other.width),self.y.div_euclid(&other.height),)}
}impl<T, U> From<Point2D<T, U>> for [T; 2] {fn from(p: Point2D<T, U>) -> Self {[p.x, p.y]}
}impl<T, U> From<[T; 2]> for Point2D<T, U> {fn from([x, y]: [T; 2]) -> Self {point2(x, y)}
}impl<T, U> From<Point2D<T, U>> for (T, T) {fn from(p: Point2D<T, U>) -> Self {(p.x, p.y)}
}impl<T, U> From<(T, T)> for Point2D<T, U> {fn from(tuple: (T, T)) -> Self {point2(tuple.0, tuple.1)}
}/// A 3d Point tagged with a unit.
#[repr(C)]
pub struct Point3D<T, U> {pub x: T,pub y: T,pub z: T,#[doc(hidden)]pub _unit: PhantomData<U>,
}mint_vec!(Point3D[x, y, z] = Point3);impl<T: Copy, U> Copy for Point3D<T, U> {}impl<T: Clone, U> Clone for Point3D<T, U> {fn clone(&self) -> Self {Point3D {x: self.x.clone(),y: self.y.clone(),z: self.z.clone(),_unit: PhantomData,}}
}#[cfg(feature = "serde")]
impl<'de, T, U> serde::Deserialize<'de> for Point3D<T, U>
whereT: serde::Deserialize<'de>,
{fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>whereD: serde::Deserializer<'de>,{let (x, y, z) = serde::Deserialize::deserialize(deserializer)?;Ok(Point3D {x,y,z,_unit: PhantomData,})}
}#[cfg(feature = "serde")]
impl<T, U> serde::Serialize for Point3D<T, U>
whereT: serde::Serialize,
{fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>whereS: serde::Serializer,{(&self.x, &self.y, &self.z).serialize(serializer)}
}#[cfg(feature = "arbitrary")]
impl<'a, T, U> arbitrary::Arbitrary<'a> for Point3D<T, U>
whereT: arbitrary::Arbitrary<'a>,
{fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {let (x, y, z) = arbitrary::Arbitrary::arbitrary(u)?;Ok(Point3D {x,y,z,_unit: PhantomData,})}
}#[cfg(feature = "bytemuck")]
unsafe impl<T: Zeroable, U> Zeroable for Point3D<T, U> {}#[cfg(feature = "bytemuck")]
unsafe impl<T: Pod, U: 'static> Pod for Point3D<T, U> {}impl<T, U> Eq for Point3D<T, U> where T: Eq {}impl<T, U> PartialEq for Point3D<T, U>
whereT: PartialEq,
{fn eq(&self, other: &Self) -> bool {self.x == other.x && self.y == other.y && self.z == other.z}
}impl<T, U> Hash for Point3D<T, U>
whereT: Hash,
{fn hash<H: core::hash::Hasher>(&self, h: &mut H) {self.x.hash(h);self.y.hash(h);self.z.hash(h);}
}impl<T: fmt::Debug, U> fmt::Debug for Point3D<T, U> {fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {f.debug_tuple("").field(&self.x).field(&self.y).field(&self.z).finish()}
}impl<T: Default, U> Default for Point3D<T, U> {fn default() -> Self {Point3D::new(Default::default(), Default::default(), Default::default())}
}impl<T, U> Point3D<T, U> {/// Constructor, setting all components to zero.#[inline]pub fn origin() -> SelfwhereT: Zero,{point3(Zero::zero(), Zero::zero(), Zero::zero())}/// The same as [`Point3D::origin`].#[inline]pub fn zero() -> SelfwhereT: Zero,{Self::origin()}/// Constructor taking scalar values directly.#[inline]pub const fn new(x: T, y: T, z: T) -> Self {Point3D {x,y,z,_unit: PhantomData,}}/// Constructor taking properly Lengths instead of scalar values.#[inline]pub fn from_lengths(x: Length<T, U>, y: Length<T, U>, z: Length<T, U>) -> Self {point3(x.0, y.0, z.0)}/// Constructor setting all components to the same value.#[inline]pub fn splat(v: T) -> SelfwhereT: Clone,{Point3D {x: v.clone(),y: v.clone(),z: v,_unit: PhantomData,}}/// Tag a unitless value with units.#[inline]pub fn from_untyped(p: Point3D<T, UnknownUnit>) -> Self {point3(p.x, p.y, p.z)}/// Apply the function `f` to each component of this point.////// # Example////// This may be used to perform unusual arithmetic which is not already offered as methods.////// ```/// use euclid::default::Point3D;////// let p = Point3D::<u32>::new(5, 11, 15);/// assert_eq!(p.map(|coord| coord.saturating_sub(10)), Point3D::new(0, 1, 5));/// ```#[inline]pub fn map<V, F: FnMut(T) -> V>(self, mut f: F) -> Point3D<V, U> {point3(f(self.x), f(self.y), f(self.z))}/// Apply the function `f` to each pair of components of this point and `rhs`.////// # Example////// This may be used to perform unusual arithmetic which is not already offered as methods.////// ```/// use euclid::{default::{Point3D, Vector3D}, point2};////// let a: Point3D<u32> = Point3D::new(50, 200, 400);/// let b: Point3D<u32> = Point3D::new(100, 100, 150);/// assert_eq!(a.zip(b, u32::saturating_sub), Vector3D::new(0, 100, 250));/// ```#[inline]pub fn zip<V, F: FnMut(T, T) -> V>(self, rhs: Self, mut f: F) -> Vector3D<V, U> {vec3(f(self.x, rhs.x), f(self.y, rhs.y), f(self.z, rhs.z))}
}impl<T: Copy, U> Point3D<T, U> {/// Cast this point into a vector.////// Equivalent to subtracting the origin to this point.#[inline]pub fn to_vector(self) -> Vector3D<T, U> {Vector3D {x: self.x,y: self.y,z: self.z,_unit: PhantomData,}}/// Returns a 2d point using this point's x and y coordinates#[inline]pub fn xy(self) -> Point2D<T, U> {point2(self.x, self.y)}/// Returns a 2d point using this point's x and z coordinates#[inline]pub fn xz(self) -> Point2D<T, U> {point2(self.x, self.z)}/// Returns a 2d point using this point's x and z coordinates#[inline]pub fn yz(self) -> Point2D<T, U> {point2(self.y, self.z)}/// Cast into an array with x, y and z.////// # Example////// ```rust/// # use euclid::{Point3D, point3};/// enum Mm {}////// let point: Point3D<_, Mm> = point3(1, -8, 0);////// assert_eq!(point.to_array(), [1, -8, 0]);/// ```#[inline]pub fn to_array(self) -> [T; 3] {[self.x, self.y, self.z]}#[inline]pub fn to_array_4d(self) -> [T; 4]whereT: One,{[self.x, self.y, self.z, One::one()]}/// Cast into a tuple with x, y and z.////// # Example////// ```rust/// # use euclid::{Point3D, point3};/// enum Mm {}////// let point: Point3D<_, Mm> = point3(1, -8, 0);////// assert_eq!(point.to_tuple(), (1, -8, 0));/// ```#[inline]pub fn to_tuple(self) -> (T, T, T) {(self.x, self.y, self.z)}#[inline]pub fn to_tuple_4d(self) -> (T, T, T, T)whereT: One,{(self.x, self.y, self.z, One::one())}/// Drop the units, preserving only the numeric value.////// # Example////// ```rust/// # use euclid::{Point3D, point3};/// enum Mm {}////// let point: Point3D<_, Mm> = point3(1, -8, 0);////// assert_eq!(point.x, point.to_untyped().x);/// assert_eq!(point.y, point.to_untyped().y);/// assert_eq!(point.z, point.to_untyped().z);/// ```#[inline]pub fn to_untyped(self) -> Point3D<T, UnknownUnit> {point3(self.x, self.y, self.z)}/// Cast the unit, preserving the numeric value.////// # Example////// ```rust/// # use euclid::{Point3D, point3};/// enum Mm {}/// enum Cm {}////// let point: Point3D<_, Mm> = point3(1, -8, 0);////// assert_eq!(point.x, point.cast_unit::<Cm>().x);/// assert_eq!(point.y, point.cast_unit::<Cm>().y);/// assert_eq!(point.z, point.cast_unit::<Cm>().z);/// ```#[inline]pub fn cast_unit<V>(self) -> Point3D<T, V> {point3(self.x, self.y, self.z)}/// Convert into a 2d point.#[inline]pub fn to_2d(self) -> Point2D<T, U> {self.xy()}/// Rounds each component to the nearest integer value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point3;/// enum Mm {}////// assert_eq!(point3::<_, Mm>(-0.1, -0.8, 0.4).round(), point3::<_, Mm>(0.0, -1.0, 0.0))/// ```#[inline]#[must_use]pub fn round(self) -> SelfwhereT: Round,{point3(self.x.round(), self.y.round(), self.z.round())}/// Rounds each component to the smallest integer equal or greater than the original value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point3;/// enum Mm {}////// assert_eq!(point3::<_, Mm>(-0.1, -0.8, 0.4).ceil(), point3::<_, Mm>(0.0, 0.0, 1.0))/// ```#[inline]#[must_use]pub fn ceil(self) -> SelfwhereT: Ceil,{point3(self.x.ceil(), self.y.ceil(), self.z.ceil())}/// Rounds each component to the biggest integer equal or lower than the original value.////// This behavior is preserved for negative values (unlike the basic cast).////// ```rust/// # use euclid::point3;/// enum Mm {}////// assert_eq!(point3::<_, Mm>(-0.1, -0.8, 0.4).floor(), point3::<_, Mm>(-1.0, -1.0, 0.0))/// ```#[inline]#[must_use]pub fn floor(self) -> SelfwhereT: Floor,{point3(self.x.floor(), self.y.floor(), self.z.floor())}/// Linearly interpolate between this point and another point.////// # Example////// ```rust/// use euclid::point3;/// use euclid::default::Point3D;////// let from: Point3D<_> = point3(0.0, 10.0, -1.0);/// let to:  Point3D<_> = point3(8.0, -4.0,  0.0);////// assert_eq!(from.lerp(to, -1.0), point3(-8.0,  24.0, -2.0));/// assert_eq!(from.lerp(to,  0.0), point3( 0.0,  10.0, -1.0));/// assert_eq!(from.lerp(to,  0.5), point3( 4.0,   3.0, -0.5));/// assert_eq!(from.lerp(to,  1.0), point3( 8.0,  -4.0,  0.0));/// assert_eq!(from.lerp(to,  2.0), point3(16.0, -18.0,  1.0));/// ```#[inline]pub fn lerp(self, other: Self, t: T) -> SelfwhereT: One + Sub<Output = T> + Mul<Output = T> + Add<Output = T>,{let one_t = T::one() - t;point3(one_t * self.x + t * other.x,one_t * self.y + t * other.y,one_t * self.z + t * other.z,)}
}impl<T: PartialOrd, U> Point3D<T, U> {#[inline]pub fn min(self, other: Self) -> Self {point3(min(self.x, other.x),min(self.y, other.y),min(self.z, other.z),)}#[inline]pub fn max(self, other: Self) -> Self {point3(max(self.x, other.x),max(self.y, other.y),max(self.z, other.z),)}/// Returns the point each component of which clamped by corresponding/// components of `start` and `end`.////// Shortcut for `self.max(start).min(end)`.#[inline]pub fn clamp(self, start: Self, end: Self) -> SelfwhereT: Copy,{self.max(start).min(end)}
}impl<T: NumCast + Copy, U> Point3D<T, U> {/// Cast from one numeric representation to another, preserving the units.////// When casting from floating point to integer coordinates, the decimals are truncated/// as one would expect from a simple cast, but this behavior does not always make sense/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.#[inline]pub fn cast<NewT: NumCast>(self) -> Point3D<NewT, U> {self.try_cast().unwrap()}/// Fallible cast from one numeric representation to another, preserving the units.////// When casting from floating point to integer coordinates, the decimals are truncated/// as one would expect from a simple cast, but this behavior does not always make sense/// geometrically. Consider using `round()`, `ceil()` or `floor()` before casting.pub fn try_cast<NewT: NumCast>(self) -> Option<Point3D<NewT, U>> {match (NumCast::from(self.x),NumCast::from(self.y),NumCast::from(self.z),) {(Some(x), Some(y), Some(z)) => Some(point3(x, y, z)),_ => None,}}// Convenience functions for common casts/// Cast into an `f32` point.#[inline]pub fn to_f32(self) -> Point3D<f32, U> {self.cast()}/// Cast into an `f64` point.#[inline]pub fn to_f64(self) -> Point3D<f64, U> {self.cast()}/// Cast into an `usize` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_usize(self) -> Point3D<usize, U> {self.cast()}/// Cast into an `u32` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_u32(self) -> Point3D<u32, U> {self.cast()}/// Cast into an `i32` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_i32(self) -> Point3D<i32, U> {self.cast()}/// Cast into an `i64` point, truncating decimals if any.////// When casting from floating point points, it is worth considering whether/// to `round()`, `ceil()` or `floor()` before the cast in order to obtain/// the desired conversion behavior.#[inline]pub fn to_i64(self) -> Point3D<i64, U> {self.cast()}
}impl<T: Float, U> Point3D<T, U> {/// Returns `true` if all members are finite.#[inline]pub fn is_finite(self) -> bool {self.x.is_finite() && self.y.is_finite() && self.z.is_finite()}
}impl<T: Copy + Add<T, Output = T>, U> Point3D<T, U> {#[inline]pub fn add_size(self, other: Size3D<T, U>) -> Self {point3(self.x + other.width,self.y + other.height,self.z + other.depth,)}
}impl<T: Real + Sub<T, Output = T>, U> Point3D<T, U> {#[inline]pub fn distance_to(self, other: Self) -> T {(self - other).length()}
}impl<T: Neg, U> Neg for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn neg(self) -> Self::Output {point3(-self.x, -self.y, -self.z)}
}impl<T: Add, U> Add<Size3D<T, U>> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn add(self, other: Size3D<T, U>) -> Self::Output {point3(self.x + other.width,self.y + other.height,self.z + other.depth,)}
}impl<T: AddAssign, U> AddAssign<Size3D<T, U>> for Point3D<T, U> {#[inline]fn add_assign(&mut self, other: Size3D<T, U>) {self.x += other.width;self.y += other.height;self.z += other.depth;}
}impl<T: Add, U> Add<Vector3D<T, U>> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn add(self, other: Vector3D<T, U>) -> Self::Output {point3(self.x + other.x, self.y + other.y, self.z + other.z)}
}impl<T: Copy + Add<T, Output = T>, U> AddAssign<Vector3D<T, U>> for Point3D<T, U> {#[inline]fn add_assign(&mut self, other: Vector3D<T, U>) {*self = *self + other;}
}impl<T: Sub, U> Sub for Point3D<T, U> {type Output = Vector3D<T::Output, U>;#[inline]fn sub(self, other: Self) -> Self::Output {vec3(self.x - other.x, self.y - other.y, self.z - other.z)}
}impl<T: Sub, U> Sub<Size3D<T, U>> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn sub(self, other: Size3D<T, U>) -> Self::Output {point3(self.x - other.width,self.y - other.height,self.z - other.depth,)}
}impl<T: SubAssign, U> SubAssign<Size3D<T, U>> for Point3D<T, U> {#[inline]fn sub_assign(&mut self, other: Size3D<T, U>) {self.x -= other.width;self.y -= other.height;self.z -= other.depth;}
}impl<T: Sub, U> Sub<Vector3D<T, U>> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn sub(self, other: Vector3D<T, U>) -> Self::Output {point3(self.x - other.x, self.y - other.y, self.z - other.z)}
}impl<T: Copy + Sub<T, Output = T>, U> SubAssign<Vector3D<T, U>> for Point3D<T, U> {#[inline]fn sub_assign(&mut self, other: Vector3D<T, U>) {*self = *self - other;}
}impl<T: Copy + Mul, U> Mul<T> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn mul(self, scale: T) -> Self::Output {point3(self.x * scale, self.y * scale, self.z * scale)}
}impl<T: Copy + MulAssign, U> MulAssign<T> for Point3D<T, U> {#[inline]fn mul_assign(&mut self, scale: T) {self.x *= scale;self.y *= scale;self.z *= scale;}
}impl<T: Copy + Mul, U1, U2> Mul<Scale<T, U1, U2>> for Point3D<T, U1> {type Output = Point3D<T::Output, U2>;#[inline]fn mul(self, scale: Scale<T, U1, U2>) -> Self::Output {point3(self.x * scale.0, self.y * scale.0, self.z * scale.0)}
}impl<T: Copy + MulAssign, U> MulAssign<Scale<T, U, U>> for Point3D<T, U> {#[inline]fn mul_assign(&mut self, scale: Scale<T, U, U>) {*self *= scale.0;}
}impl<T: Copy + Div, U> Div<T> for Point3D<T, U> {type Output = Point3D<T::Output, U>;#[inline]fn div(self, scale: T) -> Self::Output {point3(self.x / scale, self.y / scale, self.z / scale)}
}impl<T: Copy + DivAssign, U> DivAssign<T> for Point3D<T, U> {#[inline]fn div_assign(&mut self, scale: T) {self.x /= scale;self.y /= scale;self.z /= scale;}
}impl<T: Copy + Div, U1, U2> Div<Scale<T, U1, U2>> for Point3D<T, U2> {type Output = Point3D<T::Output, U1>;#[inline]fn div(self, scale: Scale<T, U1, U2>) -> Self::Output {point3(self.x / scale.0, self.y / scale.0, self.z / scale.0)}
}impl<T: Copy + DivAssign, U> DivAssign<Scale<T, U, U>> for Point3D<T, U> {#[inline]fn div_assign(&mut self, scale: Scale<T, U, U>) {*self /= scale.0;}
}impl<T: Zero, U> Zero for Point3D<T, U> {#[inline]fn zero() -> Self {Self::origin()}
}impl<T: Round, U> Round for Point3D<T, U> {/// See [`Point3D::round`].#[inline]fn round(self) -> Self {self.round()}
}impl<T: Ceil, U> Ceil for Point3D<T, U> {/// See [`Point3D::ceil`].#[inline]fn ceil(self) -> Self {self.ceil()}
}impl<T: Floor, U> Floor for Point3D<T, U> {/// See [`Point3D::floor`].#[inline]fn floor(self) -> Self {self.floor()}
}impl<T: ApproxEq<T>, U> ApproxEq<Point3D<T, U>> for Point3D<T, U> {#[inline]fn approx_epsilon() -> Self {point3(T::approx_epsilon(),T::approx_epsilon(),T::approx_epsilon(),)}#[inline]fn approx_eq_eps(&self, other: &Self, eps: &Self) -> bool {self.x.approx_eq_eps(&other.x, &eps.x)&& self.y.approx_eq_eps(&other.y, &eps.y)&& self.z.approx_eq_eps(&other.z, &eps.z)}
}impl<T: Euclid, U> Point3D<T, U> {/// Calculates the least nonnegative remainder of `self (mod other)`.////// # Example////// ```rust/// use euclid::point3;/// use euclid::default::{Point3D, Size3D};////// let p = Point3D::new(7.0, -7.0, 0.0);/// let s = Size3D::new(4.0, -4.0, 12.0);////// assert_eq!(p.rem_euclid(&s), point3(3.0, 1.0, 0.0));/// assert_eq!((-p).rem_euclid(&s), point3(1.0, 3.0, 0.0));/// assert_eq!(p.rem_euclid(&-s), point3(3.0, 1.0, 0.0));/// ```#[inline]pub fn rem_euclid(&self, other: &Size3D<T, U>) -> Self {point3(self.x.rem_euclid(&other.width),self.y.rem_euclid(&other.height),self.z.rem_euclid(&other.depth),)}/// Calculates Euclidean division, the matching method for `rem_euclid`.////// # Example////// ```rust/// use euclid::point3;/// use euclid::default::{Point3D, Size3D};////// let p = Point3D::new(7.0, -7.0, 0.0);/// let s = Size3D::new(4.0, -4.0, 12.0);////// assert_eq!(p.div_euclid(&s), point3(1.0, 2.0, 0.0));/// assert_eq!((-p).div_euclid(&s), point3(-2.0, -1.0, 0.0));/// assert_eq!(p.div_euclid(&-s), point3(-1.0, -2.0, 0.0));/// ```#[inline]pub fn div_euclid(&self, other: &Size3D<T, U>) -> Self {point3(self.x.div_euclid(&other.width),self.y.div_euclid(&other.height),self.z.div_euclid(&other.depth),)}
}impl<T, U> From<Point3D<T, U>> for [T; 3] {fn from(p: Point3D<T, U>) -> Self {[p.x, p.y, p.z]}
}impl<T, U> From<[T; 3]> for Point3D<T, U> {fn from([x, y, z]: [T; 3]) -> Self {point3(x, y, z)}
}impl<T, U> From<Point3D<T, U>> for (T, T, T) {fn from(p: Point3D<T, U>) -> Self {(p.x, p.y, p.z)}
}impl<T, U> From<(T, T, T)> for Point3D<T, U> {fn from(tuple: (T, T, T)) -> Self {point3(tuple.0, tuple.1, tuple.2)}
}/// Shorthand for `Point2D::new(x, y)`.
#[inline]
pub const fn point2<T, U>(x: T, y: T) -> Point2D<T, U> {Point2D {x,y,_unit: PhantomData,}
}/// Shorthand for `Point3D::new(x, y)`.
#[inline]
pub const fn point3<T, U>(x: T, y: T, z: T) -> Point3D<T, U> {Point3D {x,y,z,_unit: PhantomData,}
}#[cfg(test)]
mod point2d {use crate::default::Point2D;use crate::point2;#[cfg(feature = "mint")]use mint;#[test]pub fn test_min() {let p1 = Point2D::new(1.0, 3.0);let p2 = Point2D::new(2.0, 2.0);let result = p1.min(p2);assert_eq!(result, Point2D::new(1.0, 2.0));}#[test]pub fn test_max() {let p1 = Point2D::new(1.0, 3.0);let p2 = Point2D::new(2.0, 2.0);let result = p1.max(p2);assert_eq!(result, Point2D::new(2.0, 3.0));}#[cfg(feature = "mint")]#[test]pub fn test_mint() {let p1 = Point2D::new(1.0, 3.0);let pm: mint::Point2<_> = p1.into();let p2 = Point2D::from(pm);assert_eq!(p1, p2);}#[test]pub fn test_conv_vector() {for i in 0..100 {// We don't care about these values as long as they are not the same.let x = i as f32 * 0.012345;let y = i as f32 * 0.987654;let p: Point2D<f32> = point2(x, y);assert_eq!(p.to_vector().to_point(), p);}}#[test]pub fn test_swizzling() {let p: Point2D<i32> = point2(1, 2);assert_eq!(p.yx(), point2(2, 1));}#[test]pub fn test_distance_to() {let p1 = Point2D::new(1.0, 2.0);let p2 = Point2D::new(2.0, 2.0);assert_eq!(p1.distance_to(p2), 1.0);let p1 = Point2D::new(1.0, 2.0);let p2 = Point2D::new(1.0, 4.0);assert_eq!(p1.distance_to(p2), 2.0);}mod ops {use crate::default::Point2D;use crate::scale::Scale;use crate::{size2, vec2, Vector2D};pub enum Mm {}pub enum Cm {}pub type Point2DMm<T> = crate::Point2D<T, Mm>;pub type Point2DCm<T> = crate::Point2D<T, Cm>;#[test]pub fn test_neg() {assert_eq!(-Point2D::new(1.0, 2.0), Point2D::new(-1.0, -2.0));assert_eq!(-Point2D::new(0.0, 0.0), Point2D::new(-0.0, -0.0));assert_eq!(-Point2D::new(-1.0, -2.0), Point2D::new(1.0, 2.0));}#[test]pub fn test_add_size() {let p1 = Point2DMm::new(1.0, 2.0);let p2 = size2(3.0, 4.0);let result = p1 + p2;assert_eq!(result, Point2DMm::new(4.0, 6.0));}#[test]pub fn test_add_assign_size() {let mut p1 = Point2DMm::new(1.0, 2.0);p1 += size2(3.0, 4.0);assert_eq!(p1, Point2DMm::new(4.0, 6.0));}#[test]pub fn test_add_vec() {let p1 = Point2DMm::new(1.0, 2.0);let p2 = vec2(3.0, 4.0);let result = p1 + p2;assert_eq!(result, Point2DMm::new(4.0, 6.0));}#[test]pub fn test_add_assign_vec() {let mut p1 = Point2DMm::new(1.0, 2.0);p1 += vec2(3.0, 4.0);assert_eq!(p1, Point2DMm::new(4.0, 6.0));}#[test]pub fn test_sub() {let p1 = Point2DMm::new(1.0, 2.0);let p2 = Point2DMm::new(3.0, 4.0);let result = p1 - p2;assert_eq!(result, Vector2D::<_, Mm>::new(-2.0, -2.0));}#[test]pub fn test_sub_size() {let p1 = Point2DMm::new(1.0, 2.0);let p2 = size2(3.0, 4.0);let result = p1 - p2;assert_eq!(result, Point2DMm::new(-2.0, -2.0));}#[test]pub fn test_sub_assign_size() {let mut p1 = Point2DMm::new(1.0, 2.0);p1 -= size2(3.0, 4.0);assert_eq!(p1, Point2DMm::new(-2.0, -2.0));}#[test]pub fn test_sub_vec() {let p1 = Point2DMm::new(1.0, 2.0);let p2 = vec2(3.0, 4.0);let result = p1 - p2;assert_eq!(result, Point2DMm::new(-2.0, -2.0));}#[test]pub fn test_sub_assign_vec() {let mut p1 = Point2DMm::new(1.0, 2.0);p1 -= vec2(3.0, 4.0);assert_eq!(p1, Point2DMm::new(-2.0, -2.0));}#[test]pub fn test_mul_scalar() {let p1: Point2D<f32> = Point2D::new(3.0, 5.0);let result = p1 * 5.0;assert_eq!(result, Point2D::new(15.0, 25.0));}#[test]pub fn test_mul_assign_scalar() {let mut p1 = Point2D::new(3.0, 5.0);p1 *= 5.0;assert_eq!(p1, Point2D::new(15.0, 25.0));}#[test]pub fn test_mul_scale() {let p1 = Point2DMm::new(1.0, 2.0);let cm_per_mm: Scale<f32, Mm, Cm> = Scale::new(0.1);let result = p1 * cm_per_mm;assert_eq!(result, Point2DCm::new(0.1, 0.2));}#[test]pub fn test_mul_assign_scale() {let mut p1 = Point2DMm::new(1.0, 2.0);let scale: Scale<f32, Mm, Mm> = Scale::new(0.1);p1 *= scale;assert_eq!(p1, Point2DMm::new(0.1, 0.2));}#[test]pub fn test_div_scalar() {let p1: Point2D<f32> = Point2D::new(15.0, 25.0);let result = p1 / 5.0;assert_eq!(result, Point2D::new(3.0, 5.0));}#[test]pub fn test_div_assign_scalar() {let mut p1: Point2D<f32> = Point2D::new(15.0, 25.0);p1 /= 5.0;assert_eq!(p1, Point2D::new(3.0, 5.0));}#[test]pub fn test_div_scale() {let p1 = Point2DCm::new(0.1, 0.2);let cm_per_mm: Scale<f32, Mm, Cm> = Scale::new(0.1);let result = p1 / cm_per_mm;assert_eq!(result, Point2DMm::new(1.0, 2.0));}#[test]pub fn test_div_assign_scale() {let mut p1 = Point2DMm::new(0.1, 0.2);let scale: Scale<f32, Mm, Mm> = Scale::new(0.1);p1 /= scale;assert_eq!(p1, Point2DMm::new(1.0, 2.0));}#[test]pub fn test_point_debug_formatting() {let n = 1.23456789;let p1 = Point2D::new(n, -n);let should_be = format!("({:.4}, {:.4})", n, -n);let got = format!("{:.4?}", p1);assert_eq!(got, should_be);}}mod euclid {use crate::default::{Point2D, Size2D};use crate::point2;#[test]pub fn test_rem_euclid() {let p = Point2D::new(7.0, -7.0);let s = Size2D::new(4.0, -4.0);assert_eq!(p.rem_euclid(&s), point2(3.0, 1.0));assert_eq!((-p).rem_euclid(&s), point2(1.0, 3.0));assert_eq!(p.rem_euclid(&-s), point2(3.0, 1.0));}#[test]pub fn test_div_euclid() {let p = Point2D::new(7.0, -7.0);let s = Size2D::new(4.0, -4.0);assert_eq!(p.div_euclid(&s), point2(1.0, 2.0));assert_eq!((-p).div_euclid(&s), point2(-2.0, -1.0));assert_eq!(p.div_euclid(&-s), point2(-1.0, -2.0));}}
}#[cfg(test)]
mod point3d {use crate::default;use crate::default::Point3D;use crate::{point2, point3};#[cfg(feature = "mint")]use mint;#[test]pub fn test_min() {let p1 = Point3D::new(1.0, 3.0, 5.0);let p2 = Point3D::new(2.0, 2.0, -1.0);let result = p1.min(p2);assert_eq!(result, Point3D::new(1.0, 2.0, -1.0));}#[test]pub fn test_max() {let p1 = Point3D::new(1.0, 3.0, 5.0);let p2 = Point3D::new(2.0, 2.0, -1.0);let result = p1.max(p2);assert_eq!(result, Point3D::new(2.0, 3.0, 5.0));}#[test]pub fn test_conv_vector() {use crate::point3;for i in 0..100 {// We don't care about these values as long as they are not the same.let x = i as f32 * 0.012345;let y = i as f32 * 0.987654;let z = x * y;let p: Point3D<f32> = point3(x, y, z);assert_eq!(p.to_vector().to_point(), p);}}#[test]pub fn test_swizzling() {let p: default::Point3D<i32> = point3(1, 2, 3);assert_eq!(p.xy(), point2(1, 2));assert_eq!(p.xz(), point2(1, 3));assert_eq!(p.yz(), point2(2, 3));}#[test]pub fn test_distance_to() {let p1 = Point3D::new(1.0, 2.0, 3.0);let p2 = Point3D::new(2.0, 2.0, 3.0);assert_eq!(p1.distance_to(p2), 1.0);let p1 = Point3D::new(1.0, 2.0, 3.0);let p2 = Point3D::new(1.0, 4.0, 3.0);assert_eq!(p1.distance_to(p2), 2.0);let p1 = Point3D::new(1.0, 2.0, 3.0);let p2 = Point3D::new(1.0, 2.0, 6.0);assert_eq!(p1.distance_to(p2), 3.0);}#[cfg(feature = "mint")]#[test]pub fn test_mint() {let p1 = Point3D::new(1.0, 3.0, 5.0);let pm: mint::Point3<_> = p1.into();let p2 = Point3D::from(pm);assert_eq!(p1, p2);}mod ops {use crate::default::Point3D;use crate::scale::Scale;use crate::{size3, vec3, Vector3D};pub enum Mm {}pub enum Cm {}pub type Point3DMm<T> = crate::Point3D<T, Mm>;pub type Point3DCm<T> = crate::Point3D<T, Cm>;#[test]pub fn test_neg() {assert_eq!(-Point3D::new(1.0, 2.0, 3.0), Point3D::new(-1.0, -2.0, -3.0));assert_eq!(-Point3D::new(0.0, 0.0, 0.0), Point3D::new(-0.0, -0.0, -0.0));assert_eq!(-Point3D::new(-1.0, -2.0, -3.0), Point3D::new(1.0, 2.0, 3.0));}#[test]pub fn test_add_size() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let p2 = size3(4.0, 5.0, 6.0);let result = p1 + p2;assert_eq!(result, Point3DMm::new(5.0, 7.0, 9.0));}#[test]pub fn test_add_assign_size() {let mut p1 = Point3DMm::new(1.0, 2.0, 3.0);p1 += size3(4.0, 5.0, 6.0);assert_eq!(p1, Point3DMm::new(5.0, 7.0, 9.0));}#[test]pub fn test_add_vec() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let p2 = vec3(4.0, 5.0, 6.0);let result = p1 + p2;assert_eq!(result, Point3DMm::new(5.0, 7.0, 9.0));}#[test]pub fn test_add_assign_vec() {let mut p1 = Point3DMm::new(1.0, 2.0, 3.0);p1 += vec3(4.0, 5.0, 6.0);assert_eq!(p1, Point3DMm::new(5.0, 7.0, 9.0));}#[test]pub fn test_sub() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let p2 = Point3DMm::new(4.0, 5.0, 6.0);let result = p1 - p2;assert_eq!(result, Vector3D::<_, Mm>::new(-3.0, -3.0, -3.0));}#[test]pub fn test_sub_size() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let p2 = size3(4.0, 5.0, 6.0);let result = p1 - p2;assert_eq!(result, Point3DMm::new(-3.0, -3.0, -3.0));}#[test]pub fn test_sub_assign_size() {let mut p1 = Point3DMm::new(1.0, 2.0, 3.0);p1 -= size3(4.0, 5.0, 6.0);assert_eq!(p1, Point3DMm::new(-3.0, -3.0, -3.0));}#[test]pub fn test_sub_vec() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let p2 = vec3(4.0, 5.0, 6.0);let result = p1 - p2;assert_eq!(result, Point3DMm::new(-3.0, -3.0, -3.0));}#[test]pub fn test_sub_assign_vec() {let mut p1 = Point3DMm::new(1.0, 2.0, 3.0);p1 -= vec3(4.0, 5.0, 6.0);assert_eq!(p1, Point3DMm::new(-3.0, -3.0, -3.0));}#[test]pub fn test_mul_scalar() {let p1: Point3D<f32> = Point3D::new(3.0, 5.0, 7.0);let result = p1 * 5.0;assert_eq!(result, Point3D::new(15.0, 25.0, 35.0));}#[test]pub fn test_mul_assign_scalar() {let mut p1: Point3D<f32> = Point3D::new(3.0, 5.0, 7.0);p1 *= 5.0;assert_eq!(p1, Point3D::new(15.0, 25.0, 35.0));}#[test]pub fn test_mul_scale() {let p1 = Point3DMm::new(1.0, 2.0, 3.0);let cm_per_mm: Scale<f32, Mm, Cm> = Scale::new(0.1);let result = p1 * cm_per_mm;assert_eq!(result, Point3DCm::new(0.1, 0.2, 0.3));}#[test]pub fn test_mul_assign_scale() {let mut p1 = Point3DMm::new(1.0, 2.0, 3.0);let scale: Scale<f32, Mm, Mm> = Scale::new(0.1);p1 *= scale;assert_eq!(p1, Point3DMm::new(0.1, 0.2, 0.3));}#[test]pub fn test_div_scalar() {let p1: Point3D<f32> = Point3D::new(15.0, 25.0, 35.0);let result = p1 / 5.0;assert_eq!(result, Point3D::new(3.0, 5.0, 7.0));}#[test]pub fn test_div_assign_scalar() {let mut p1: Point3D<f32> = Point3D::new(15.0, 25.0, 35.0);p1 /= 5.0;assert_eq!(p1, Point3D::new(3.0, 5.0, 7.0));}#[test]pub fn test_div_scale() {let p1 = Point3DCm::new(0.1, 0.2, 0.3);let cm_per_mm: Scale<f32, Mm, Cm> = Scale::new(0.1);let result = p1 / cm_per_mm;assert_eq!(result, Point3DMm::new(1.0, 2.0, 3.0));}#[test]pub fn test_div_assign_scale() {let mut p1 = Point3DMm::new(0.1, 0.2, 0.3);let scale: Scale<f32, Mm, Mm> = Scale::new(0.1);p1 /= scale;assert_eq!(p1, Point3DMm::new(1.0, 2.0, 3.0));}}mod euclid {use crate::default::{Point3D, Size3D};use crate::point3;#[test]pub fn test_rem_euclid() {let p = Point3D::new(7.0, -7.0, 0.0);let s = Size3D::new(4.0, -4.0, 12.0);assert_eq!(p.rem_euclid(&s), point3(3.0, 1.0, 0.0));assert_eq!((-p).rem_euclid(&s), point3(1.0, 3.0, 0.0));assert_eq!(p.rem_euclid(&-s), point3(3.0, 1.0, 0.0));}#[test]pub fn test_div_euclid() {let p = Point3D::new(7.0, -7.0, 0.0);let s = Size3D::new(4.0, -4.0, 12.0);assert_eq!(p.div_euclid(&s), point3(1.0, 2.0, 0.0));assert_eq!((-p).div_euclid(&s), point3(-2.0, -1.0, 0.0));assert_eq!(p.div_euclid(&-s), point3(-1.0, -2.0, 0.0));}}
}

二、Point2D結構體定義

代碼定義了一個名為 Point2D 的泛型結構體,它表示一個二維點,并且這個結構體被標記(或說是“攜帶”)了一個單位(unit)。這里的單位可能是用來表示坐標的某種度量單位或者其它信息,但具體是什么并不在這個結構體定義中明確給出,而是通過泛型參數 U 提供的。

1、源碼

#[repr(C)]
pub struct Point2D<T, U> {pub x: T,pub y: T,#[doc(hidden)]pub _unit: PhantomData<U>,
}

2、泛型參數

Point2D<T, U> 有兩個泛型參數,T 和 U。T 用于表示點的坐標類型(比如 f32、f64、i32 等),而 U 用于表示與這個點相關的單位信息。

3、字段

  • pub x: T:表示點的 X 坐標,其類型為泛型 T。
  • pub y: T:表示點的 Y 坐標,其類型也為泛型 T。
  • #[doc(hidden)] pub _unit: PhantomData< U >:這里使用了 PhantomData< U > 來攜帶單位信息 U 而不占用實際的內存空間。PhantomData 是一個在標準庫中定義的結構體,用于在泛型代碼中表示某種類型存在而不增加運行時的大小。#[doc(hidden)] 屬性意味著這個字段在生成的文檔中會被隱藏,可能是因為它對于最終用戶來說不是很有用或者是一個實現細節。

4、#[repr?] 屬性

這個屬性指定了結構體的內存布局應該與 C 語言中的結構體布局兼容。這對于與 C 語言代碼進行互操作時非常有用,因為它確保了結構體中字段的順序和內存對齊方式與 C 語言中的相同。

5、總結

Point2D<T, U> 是一個用于表示二維點的泛型結構體,它允許指定坐標的類型(T)和與該點相關的單位信息(U),而不增加任何實際的內存開銷用于存儲單位信息。

三、二維點特性實現

  1. Copy 實現:
    對于任何實現了Copy特性的T類型,Point2D<T, U>也實現了Copy。這意味著Point2D的實例可以通過值復制,而不需要顯式的克隆操作。
  2. Clone 實現:
    對于任何實現了Clone特性的T類型,Point2D<T, U>也實現了Clone。clone方法通過調用x和y的clone方法,創建了Point2D的一個新實例。
  3. 序列化和反序列化(依賴serde庫):
    當啟用serde特性時,Point2D<T, U>可以被序列化和反序列化,只要T類型支持相應的操作。這允許Point2D實例被方便地轉換為JSON等格式,或從JSON等格式恢復。

四、二維點實用方法

  1. map 方法:
  • map方法接受一個閉包f,并將Point2D的每個坐標值(x和y)作為參數傳遞給閉包,生成一個新的Point2D實例,其坐標類型為閉包返回的類型V。
  • 這允許對點的坐標進行各種轉換,比如飽和減法(saturating_sub),而不改變點的類型參數U。
  1. zip 方法:
  • zip方法接受另一個Point2D實例rhs和一個閉包f,對兩個點的對應坐標值應用閉包f,生成一個新的Vector2D實例(假設Vector2D是一個二維向量結構)。
  • 這允許對兩個點的坐標進行成對的轉換,比如計算兩個點之間的差值(如示例中的飽和減法)。
  1. extend 方法:
  • 將一個二維點擴展為一個三維點,通過指定一個z值。
  • 參數z的類型與點的x和y坐標類型相同(T)。
  • 返回Point3D<T, U>類型的新實例。
  1. to_vector 方法:
  • 將點轉換為一個向量。這在數學上等同于從原點(0,0)減去該點。
  • 返回Vector2D<T, U>類型的新實例。
  • 使用PhantomData來攜帶單位類型U,但在此方法中未直接使用U。
  1. yx 方法:
  • 交換點的x和y坐標。
  • 返回與輸入相同類型的新實例(Self類型)。
  • 示例代碼展示了如何使用這個方法。
  1. ceil 方法:
  • 對點的每個坐標值向上取整(即,取不小于原數的最小整數)。
  • 需要在T類型上實現Ceil trait(這通常意味著T是支持浮點運算的類型,如f32或f64)。
  • 返回與輸入相同類型的新實例。
  • 示例代碼展示了如何處理負數的向上取整。
  1. floor 方法:
  • 對點的每個坐標值向下取整(即,取不大于原數的最大整數)。
  • 需要在T類型上實現Floor trait(類似于Ceil)。
  • 返回與輸入相同類型的新實例。
  • 示例代碼展示了如何處理負數的向下取整。
  1. 線性插值方法 (lerp)
    線性插值方法lerp接受當前點(self)、另一個點(other)和一個參數t,然后返回這兩個點之間的一個新點,這個點位于從當前點到另一個點的直線上,具體位置由t決定。t的取值范圍是實數,通常用于動畫和漸變效果中。當t=0.0時,返回當前點;當t=1.0時,返回另一個點;當t在0到1之間時,返回兩點之間的某個點;當t超出這個范圍時,返回的是當前點和另一個點之外的點。
    代碼實現是正確的,但需要注意,當t為負值或大于1時,返回的點可能會超出原始兩點的范圍,這在某些情況下是有用的,但在其他情況下可能不是預期的行為。
    轉換為整數類型的方法
    to_i32和to_i64方法將二維點的坐標從浮點數轉換為整數(i32或i64),這里假設原始點的坐標是浮點數。這些方法簡單地將浮點數坐標截斷為整數,這可能會導致精度損失。在轉換之前,您可能希望使用round(), ceil(), 或floor()函數來決定如何處理小數部分。

  2. min 方法
    min方法的描述中似乎有些文本缺失,但從上下文中可以推斷,它應該返回一個新點,該點的每個坐標都是當前點和另一個點相應坐標中的最小值。這個方法的實現可能需要比較兩個點的x和y坐標,并返回一個新點,其x和y坐標分別是這兩個點對應坐標的最小值。

  3. is_finite 方法
    is_finite方法檢查點的x和y坐標是否都是有限的(不是NaN或無窮大)。這對于數值計算的安全性很重要,可以避免因為使用了無效數值而導致的不可預測行為。

  4. add_size 方法
    add_size方法將一個Size2D對象(表示寬度和高度)加到當前點上,返回一個新點。這個方法可能用于在圖形界面編程中調整點的位置,以適應新的大小或邊界。

  5. 距離計算 (distance_to 方法):

  • 實現了兩個Point2D實例之間的距離計算。
  • 它依賴于T類型實現了Real和Sub trait(Real不是Rust標準庫的一部分,可能來自某個數學庫,表示實數類型;Sub用于執行減法操作)。
  • 方法內部通過減去另一個點并調用.length()方法計算距離。
  1. 取反 (Neg trait實現):
  • 允許對Point2D實例進行取反操作(即坐標乘以-1)。
  • 依賴于T類型實現了Neg trait。
  1. 與Size2D相加 (Add trait實現):
  • 允許將Point2D與Size2D相加,可能用于將點的位置按照某個尺寸進行偏移。
  • 依賴于T類型實現了Add trait。
  1. 就地與Size2D相加 (AddAssign trait實現):
  • 類似于Add,但直接在原地修改Point2D實例。
  • 依賴于T類型實現了AddAssign trait。
  1. 與Vector2D相加 (Add trait的另一個實現):
  • 允許將Point2D與Vector2D相加,可能用于將點的位置按照某個向量進行移動。
  • 依賴于T類型實現了Add trait。
  1. 零值 (Zero trait實現):
  • 提供了Point2D的零值(原點)。
  • 依賴于T類型實現了Zero trait。
  1. 四舍五入 (Round trait實現):
  • 對Point2D的每個坐標進行四舍五入。
  • 依賴于T類型實現了Round trait。
  1. 向上取整 (Ceil trait實現):
  • 對Point2D的每個坐標進行向上取整。
  • 依賴于T類型實現了Ceil trait。
  1. 向下取整 (Floor trait實現):
  • 對Point2D的每個坐標進行向下取整。
  • 依賴于T類型實現了Floor trait。
  1. 近似相等 (ApproxEq trait實現):
  • 允許比較兩個Point2D實例是否在指定的誤差范圍內近似相等。
  • 依賴于T類型實現了ApproxEq trait。
  1. rem_euclid方法:
    +這個方法計算Point2D對象self相對于另一個Size2D對象other的歐幾里得余數。
  • 歐幾里得余數與普通余數不同,它總是非負的。
  • 方法接受一個&Size2D<T, U>作為參數,返回一個新的Point2D<T, U>,其中每個坐標都是self對應坐標對other對應維度的歐幾里得余數。
  1. div_euclid方法:
  • 這個方法計算Point2D對象self相對于另一個Size2D對象other的歐幾里得除法結果。
  • euclid除法返回的是商,即self每個坐標除以other對應維度的整數部分。
  • 同樣,方法接受一個&Size2D<T, U>作為參數,返回一個新的Point2D<T, U>。
  1. 實現Point2D<T, U>到[T; 2]的轉換:
  • 通過實現From<Point2D<T, U>> for [T; 2] trait,允許將Point2D轉換為包含兩個T類型元素的數組。
  • 轉換直接取Point2D的x和y坐標作為數組的兩個元素。
  1. 實現[T; 2]到Point2D<T, U>的轉換:
  • 通過實現From<[T; 2]> for Point2D<T, U> trait,允許將包含兩個T類型元素的數組轉換為Point2D。
  • 轉換將數組的前兩個元素分別作為Point2D的x和y坐標。
  1. 實現Point2D<T, U>到(T, T)的轉換:
  • 通過實現From<Point2D<T, U>> for (T, T) trait,允許將Point2D轉換為包含兩個T類型元素的元組。
  • 轉換與到數組的轉換類似,取Point2D的x和y坐標作為元組的兩個元素。
  1. 實現(T, T)到Point2D<T, U>的轉換:
  • 通過實現From<(T, T)> for Point2D<T, U> trait,允許將包含兩個T類型元素的元組轉換為Point2D。
  • 轉換將元組的兩個元素分別作為Point2D的x和y坐標。

五、Point3D結構體

比Point2D多一個z值,方法與Point2D相似。

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/894486.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/894486.shtml
英文地址,請注明出處:http://en.pswp.cn/news/894486.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

數據分析系列--[12] RapidMiner辨別分析(含數據集)

一、數據準備 二、導入數據 三、數據預處理 四、建模辨別分析 五、導入測試集進行辨別分析 一、數據準備 點擊下載數據集 二、導入數據 三、數據預處理 四、建模辨別分析 五、導入測試集進行辨別分析 Ending, congratulations, youre done.

Day33【AI思考】-函數求導過程 的優質工具和網站

文章目錄 **函數求導過程** 的優質工具和網站**一、動態圖形工具**1. **Desmos&#xff08;網頁端&#xff09;**2. **GeoGebra&#xff08;全平臺&#xff09;** **二、分步推導工具**3. **Wolfram Alpha&#xff08;網頁/App&#xff09;**4. **Symbolab&#xff08;網頁/App…

個人筆記(很沒營養,純備忘錄)

1.輸入電阻和輸出電阻指在一個可劃分為3部分的電路中&#xff0c;中間部分電路相當于前面電路的負載有輸入端電阻&#xff0c;稱輸入電阻&#xff0c;相對于后面部分等效為電源有輸出端內阻&#xff0c;稱輸出電阻 理所當然的希望輸出電阻對負載影響小&#xff0c;輸入電阻能完…

當卷積神經網絡遇上AI編譯器:TVM自動調優深度解析

從銅線到指令&#xff1a;硬件如何"消化"卷積 在深度學習的世界里&#xff0c;卷積層就像人體中的毛細血管——數量龐大且至關重要。但鮮有人知&#xff0c;一個簡單的3x3卷積在CPU上的執行路徑&#xff0c;堪比北京地鐵線路圖般復雜。 卷積的數學本質 對于輸入張…

51單片機 02 獨立按鍵

一、獨立按鍵控制LED亮滅 輕觸按鍵&#xff1a;相當于是一種電子開關&#xff0c;按下時開關接通&#xff0c;松開時開關斷開&#xff0c;實現原理是通過輕觸按鍵內部的金屬彈片受力彈動來實現接通和斷開。 #include <STC89C5xRC.H> void main() { // P20xFE;while(1){…

系統URL整合系列視頻二(界面原型)

視頻 系統URL整合系列視頻二&#xff08;界面原型&#xff09; 視頻介紹 &#xff08;全國&#xff09;大型分布式系統Web資源URL整合需求界面原型講解。當今社會各行各業對軟件系統的web資源訪問權限控制越來越嚴格&#xff0c;控制粒度也越來越細。安全級別提高的同時也增加…

vscode命令面板輸入 CMake:build不執行提示輸入

CMake&#xff1a;build或rebuild不編譯了&#xff0c;彈出:> [Add a new preset] , 提示輸入發現settings.jsons設置有問題 { "workbench.colorTheme": "Default Light", "cmake.pinnedCommands": [ "workbench.action.tasks.configu…

wax到底是什么意思

在很久很久以前&#xff0c;人類還沒有誕生文字之前&#xff0c;人類就產生了語言&#xff1b;在誕生文字之前&#xff0c;人類就已經使用了語言很久很久。 沒有文字之前&#xff0c;人們的語言其實是相對比較簡單的&#xff0c;因為人類的生產和生活水平非常低下&#xff0c;…

SSRF 漏洞利用 Redis 實戰全解析:原理、攻擊與防范

目錄 前言 SSRF 漏洞深度剖析 Redis&#xff1a;強大的內存數據庫 Redis 產生漏洞的原因 SSRF 漏洞利用 Redis 實戰步驟 準備環境 下載安裝 Redis 配置漏洞環境 啟動 Redis 攻擊機遠程連接 Redis 利用 Redis 寫 Webshell 防范措施 前言 在網絡安全領域&#xff0…

【周易哲學】生辰八字入門講解(八)

&#x1f60a;你好&#xff0c;我是小航&#xff0c;一個正在變禿、變強的文藝傾年。 &#x1f514;本文講解【周易哲學】生辰八字入門講解&#xff0c;期待與你一同探索、學習、進步&#xff0c;一起卷起來叭&#xff01; 目錄 一、六親女命六親星六親宮位相互關系 男命六親星…

CAN總線數據采集與分析

CAN總線數據采集與分析 目錄 CAN總線數據采集與分析1. 引言2. 數據采集2.1 數據采集簡介2.2 數據采集實現3. 數據分析3.1 數據分析簡介3.2 數據分析實現4. 數據可視化4.1 數據可視化簡介4.2 數據可視化實現5. 案例說明5.1 案例1:數據采集實現5.2 案例2:數據分析實現5.3 案例3…

【c++】類與對象詳解

目錄 面向過程思想和面向對象思想類的定義引入類的關鍵字類定義的兩種方式類的訪問限定符類的作用域類大小的計算封裝 this指針類的6個默認成員函數構造函數初步理解構造函數深入理解構造函數初始化列表單參數構造函數引發的隱式類型轉換 析構函數拷貝構造函數賦值運算符重載運…

大模型訓練(5):Zero Redundancy Optimizer(ZeRO零冗余優化器)

0 英文縮寫 Large Language Model&#xff08;LLM&#xff09;大型語言模型Data Parallelism&#xff08;DP&#xff09;數據并行Distributed Data Parallelism&#xff08;DDP&#xff09;分布式數據并行Zero Redundancy Optimizer&#xff08;ZeRO&#xff09;零冗余優化器 …

陸游的《詩人苦學說》:從藻繪到“功夫在詩外”(中英雙語)mastery lies beyond poetry

陸游的《詩人苦學說》&#xff1a;從藻繪到“功夫在詩外” 今天看萬維鋼的《萬萬沒想到》一書&#xff0c;看到陸游的功夫在詩外的句子&#xff0c;特意去查找這首詩的原文。故而有此文。 我國學人還往往過分強調“功夫在詩外”這句陸游的名言&#xff0c;認為提升綜合素質是一…

DeepSeek-R1 低成本訓練的根本原因是?

在人工智能領域&#xff0c;大語言模型&#xff08;LLM&#xff09;正以前所未有的速度發展&#xff0c;驅動著自然語言處理、內容生成、智能客服等眾多應用的革新。然而&#xff0c;高性能的背后往往是高昂的訓練成本&#xff0c;動輒數百萬美元的投入讓許多企業和研究機構望而…

JavaScript面向對象編程:Prototype與Class的對比詳解

JavaScript面向對象編程&#xff1a;Prototype與Class的對比詳解 JavaScript面向對象編程&#xff1a;Prototype與Class的對比詳解引言什么是JavaScript的面向對象編程&#xff1f;什么是Prototype&#xff1f;Prototype的定義Prototype的工作原理示例代碼優點缺點 什么是JavaS…

玉米苗和雜草識別分割數據集labelme格式1997張3類別

數據集格式&#xff1a;labelme格式(不包含mask文件&#xff0c;僅僅包含jpg圖片和對應的json文件) 圖片數量(jpg文件個數)&#xff1a;1997 標注數量(json文件個數)&#xff1a;1997 標注類別數&#xff1a;3 標注類別名稱:["corn","weed","Bean…

詳解CSS `clear` 屬性及其各個選項

詳解CSS clear 屬性及其各個選項 1. clear: left;示例代碼 2. clear: right;示例代碼 3. clear: both;示例代碼 4. clear: none;示例代碼 總結 在CSS布局中&#xff0c;clear 屬性是一個非常重要的工具&#xff0c;特別是在處理浮動元素時。本文將詳細解釋 clear 屬性及其各個選…

猴子吃桃問題

# 猴子吃桃問題&#xff1a;猴子第一天摘下若干個桃子&#xff0c;當即吃了一半&#xff0c;還不癮&#xff0c;有多吃了一個&#xff0c;第二天早上有將剩下的桃子吃掉一半&#xff0c;又多吃了一個。以后每天早上都吃了前一天剩的一半零一個。到第十天早上想再吃時&#xff0…

Streamlit入門

1、Streamlit是什么 Streamlit 是一個用于快速構建數據應用的開源 Python 庫&#xff0c;由 Streamlit 公司開發并維護。它極大地簡化了從數據腳本到交互式 Web 應用的轉化過程&#xff0c;讓開發者無需具備前端開發的專業知識&#xff0c;就能輕松創建出美觀、實用的交互式應…