1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527
#![warn(missing_docs)] #![cfg_attr(feature = "simd", feature(doc_cfg))] /*! This crate provides traits for doing 2D vector geometry operations using standard types # Scalars Simple vector math is implemented for vectors with the following scalar types: * `u8`-`u128` * `usize` * `i8`-`i128` * `isize` * `f32` * `f64` * Any type that implements [`Scalar`](trait.Scalar.html) `f32` and `f64` implement [`FloatingScalar`](trait.FloatingScalar.html), which gives some additional operations only applicable to floating-point numbers. Each scalar type has an associated module that has type definitions for standard geometric types using that scalar. For example, instead of writing ``` # use vector2math::*; let square = <[f32; 4]>::square([0.0; 2], 1.0); ``` You can instead write ``` # use vector2math::*; let square = f32::Rect::square([0.0; 2], 1.0); ``` # Vectors Vectors can be of the following forms: * `[T; 2]` * `(T, T)` * Any type that implements [`Vector2`](trait.Vector2.html) Many 2D Vector operations are supported. ``` use vector2math::*; let a = [2, 6]; let b = [4, -1]; assert_eq!(2, a.x()); assert_eq!(-1, b.y()); assert_eq!([-2, -6], a.neg()); assert_eq!([6, 5], a.add(b)); assert_eq!([-2, 7], a.sub(b)); assert_eq!([12, -3], b.mul(3)); assert_eq!([8, -6], b.mul2(a)); assert_eq!([1, 3], a.div(2)); assert_eq!([0, -6], a.div2(b)); assert_eq!(2, a.dot(b)); ``` Vectors that implement [`FloatingVector2`](trait.FloatingVector2.html) have additional operations: ``` use vector2math::*; assert_eq!(5.0, [3.0, 4.0].mag()); assert_eq!(10.0, [-1.0, -2.0].dist([5.0, 6.0])); let rotation_calculation = [1.0, 0.0].rotate_about(f64::TAU / 8.0, [0.0; 2]); let rotation_solution = [2f64.powf(0.5) / 2.0; 2]; assert!(rotation_calculation.sub(rotation_solution).mag() < std::f64::EPSILON); ``` # Rectangles Many types can be used to define axis-aligned rectangles: * `[[T; 2]; 2]` * `[(T, T); 2]` * `((T, T), (T, T))` * `([T; 2], [T; 2])` * `[T; 4]` * `(T, T, T, T)` * Any type that implements [`Pair`](trait.Pair.html) where the associated [`Item`](trait.Pair.html#associatedtype.Item) type implements [`Vector2`](trait.Vector2.html). ``` use vector2math::*; let rect = [1i32, 2, 4, 6]; assert_eq!([1, 2], rect.top_left()); assert_eq!([4, 6], rect.size()); assert_eq!([3, 5], rect.center()); assert_eq!(20, rect.perimeter()); assert_eq!(24, rect.area()); assert!(rect.contains([3, 5])); assert_eq!([1, 2, 2, 6], rect.move_right_bound(-2)); let corners = rect.corners(); assert_eq!(corners[0], [1, 2]); assert_eq!(corners[1], [5, 2]); assert_eq!(corners[2], [5, 8]); assert_eq!(corners[3], [1, 8]); ``` # Circles A few types can be used to define circles: * `([T; 2], T)` * `((T, T), T)` * Any pair of types where the first implements [`FloatingVector2`](trait.FloatingVector2.html) and the second is the vector's [`Scalar`](trait.Vector2.html#associatedtype.Scalar) type. ``` use vector2math::*; use std::f64; let circle = ([2.0, 3.0], 4.0); assert!((circle.circumference() - 25.132_741_228_718_345).abs() < f64::EPSILON); assert!((circle.area() - 50.265_482_457_436_69).abs() < f64::EPSILON); assert!(circle.contains([0.0, 1.0])); assert!(!circle.contains([5.0, 6.0])); ``` # Mapping Vector, rectangle, and circle types can be easily mapped to different types: ``` use vector2math::*; let arrayf32: [f32; 2] = [1.0, 2.0]; let arrayf64: [f64; 2] = arrayf32.map(); let pairf64: (f64, f64) = arrayf64.map(); let arrayi16: [i16; 2] = pairf64.map_with(|f| f as i16); assert_eq!(arrayf32, arrayi16.map_f32()); let weird_rect = [(0.0, 1.0), (2.0, 5.0)]; let normal_rectf32: [f32; 4] = weird_rect.map(); let normal_rectf64: [f64; 4] = normal_rectf32.map(); let normal_rectu8: [u8; 4] = normal_rectf32.map_with(|f| f as u8); assert_eq!([0, 1, 2, 5], normal_rectu8); let pair_circlef32 = ((0.0, 1.0), 2.0); let array_circlef32 = ([0.0, 1.0], 2.0); assert_eq!(((0.0, 1.0), 2.0), array_circlef32.map::<((f64, f64), f64)>()); ``` # Transforms The [`Transform`](trait.Transform.html) trait is used to define 2D vector transforms. This crate implements [`Transform`](trait.Transform.html) for all types that implement [`Pair`](trait.Pair.html) where the [`Pair`](trait.Pair.html)'s [`Item`](trait.Pair.html#associatedtype.Item) implments [`Trio`](trait.Trio.html) where the [`Trio`](trait.Trio.html)'s [`Item`](trait.Trio.html#associatedtype.Item) implements [`FloatingScalar`](trait.FloatingScalar.html). This type range includes everything from `[[f32; 3]; 2]` to `(f64, f64, f64, f64, f64, f64)`. [`Transform`](trait.Transform.html)s can be chained and applied to vectors. ``` use vector2math::*; let dis = [1.0; 2]; let rot = f32::TAU / 4.0; let sc = [2.0; 2]; let transform = f32::Trans::new().translate(dis).rotate(rot).scale(sc); let v = [3.0, 5.0]; let v1 = v.transform(transform); let v2 = v.add(dis).rotate(rot).mul2(sc); assert_eq!(v1, v2); ``` # Implementing traits Implementing these traits for your own types is simple. Just make sure that your type is [`Copy`](https://doc.rust-lang.org/nightly/core/marker/trait.Copy.html). ``` use vector2math::*; #[derive(Clone, Copy)] struct MyVector { x: f64, y: f64, } impl Vector2 for MyVector { type Scalar = f64; fn new(x: f64, y: f64) -> Self { MyVector { x, y } } fn x(self) -> f64 { self.x } fn y(self) -> f64 { self.y } } #[derive(Clone, Copy)] struct MyRectangle { top_left: MyVector, size: MyVector, } impl Rectangle for MyRectangle { type Scalar = f64; type Vector = MyVector; fn new(top_left: MyVector, size: MyVector) -> Self { MyRectangle { top_left, size } } fn top_left(self) -> MyVector { self.top_left } fn size(self) -> MyVector { self.size } } let rect: MyRectangle = [1, 2, 3, 4].map(); assert_eq!(12.0, rect.area()); assert_eq!(6.0, rect.bottom()); ``` */ macro_rules! mods { ($($m:ident),*) => { $(mod $m; pub use $m::*;)* }; } #[cfg(feature = "simd")] #[cfg_attr(feature = "simd", doc(cfg(feature = "simd")))] pub mod simd; mods!(circle, group, rectangle, scalar, transform); macro_rules! int_mod { ($T:ident) => { /// Standard geometric types for a scalar type pub mod $T { /// A dimension type pub type Dim = $T; /// A standard 2D vector type pub type Vec2 = [Dim; 2]; /// A standard rectangle type pub type Rect = [Dim; 4]; } }; } int_mod!(u8); int_mod!(u16); int_mod!(u32); int_mod!(u64); int_mod!(u128); int_mod!(usize); int_mod!(i8); int_mod!(i16); int_mod!(i32); int_mod!(i64); int_mod!(i128); int_mod!(isize); macro_rules! float_mod { ($T:ident) => { /// Standard geometric types for a scalar type pub mod $T { /// A dimension type pub type Dim = $T; /// A standard 2D vector type pub type Vec2 = [Dim; 2]; /// A standard rectangle type pub type Rect = [Dim; 4]; /// A standard circle type pub type Circ = (Vec2, Dim); /// A standard transform type pub type Trans = [Dim; 6]; } }; } float_mod!(f32); float_mod!(f64); use std::ops::Neg; /// Trait for manipulating 2D vectors pub trait Vector2: Copy { /// The scalar type type Scalar: Scalar; /// Get the x component fn x(self) -> Self::Scalar; /// Get the y component fn y(self) -> Self::Scalar; /// Create a new vector from an x and y component fn new(x: Self::Scalar, y: Self::Scalar) -> Self; /// Set the x component fn set_x(&mut self, x: Self::Scalar) { *self = Vector2::new(x, self.y()) } /// Set the y component fn set_y(&mut self, y: Self::Scalar) { *self = Vector2::new(self.x(), y) } /// Get this vector with a different x component fn with_x(self, x: Self::Scalar) -> Self { Self::new(x, self.y()) } /// Get this vector with a different y component fn with_y(self, y: Self::Scalar) -> Self { Self::new(self.x(), y) } /// Create a new square vector fn square(s: Self::Scalar) -> Self { Self::new(s, s) } /// Map this vector to a vector of another type fn map<V>(self) -> V where V: Vector2, V::Scalar: From<Self::Scalar>, { V::new(V::Scalar::from(self.x()), V::Scalar::from(self.y())) } /// Map this vector to a `[f32;2]` /// /// This is an alias for Vector2::map::<[f32;2]>() that is more concise fn map_f32(self) -> [f32; 2] where f32: From<Self::Scalar>, { self.map() } /// Map this vector to a `[f64;2]` /// /// This is an alias for Vector2::map::<[f64;2]>() that is more concise fn map_f64(self) -> [f64; 2] where f64: From<Self::Scalar>, { self.map() } /// Map this vector to a vector of another type using a function fn map_with<V, F>(self, mut f: F) -> V where V: Vector2, F: FnMut(Self::Scalar) -> V::Scalar, { V::new(f(self.x()), f(self.y())) } /// Negate the vector fn neg(self) -> Self where Self::Scalar: Neg<Output = Self::Scalar>, { Self::square(Self::Scalar::ZERO).sub(self) } /// Add this vector to another fn add(self, other: Self) -> Self { Self::new(self.x() + other.x(), self.y() + other.y()) } /// Subtract another vector from this one fn sub(self, other: Self) -> Self { Self::new(self.x() - other.x(), self.y() - other.y()) } /// Multiply this vector by a scalar fn mul(self, by: Self::Scalar) -> Self { self.mul2(Self::square(by)) } /// Multiply this vector component-wise by another fn mul2(self, other: Self) -> Self { Self::new(self.x() * other.x(), self.y() * other.y()) } /// Divide this vector by a scalar fn div(self, by: Self::Scalar) -> Self { self.div2(Self::square(by)) } /// Divide this vector component-wise by another fn div2(self, other: Self) -> Self { Self::new(self.x() / other.x(), self.y() / other.y()) } /// Add another vector into this one fn add_assign(&mut self, other: Self) { *self = self.add(other); } /// Subtract another vector into this one fn sub_assign(&mut self, other: Self) { *self = self.sub(other); } /// Multiply a scalar into this vector fn mul_assign(&mut self, by: Self::Scalar) { *self = self.mul(by); } /// Multiply another vector component-wise into this one fn mul2_assign(&mut self, other: Self) { *self = self.mul2(other); } /// Divide a scalar into this vector fn div_assign(&mut self, by: Self::Scalar) { *self = self.div(by); } /// Divide another vector component-wise into this one fn div2_assign(&mut self, other: Self) { *self = self.div2(other); } /// Get the value of the dimension with the higher magnitude fn max_dim(self) -> Self::Scalar { if self.x().abs() > self.y().abs() { self.x() } else { self.y() } } /// Get the value of the dimension with the lower magnitude fn min_dim(self) -> Self::Scalar { if self.x().abs() < self.y().abs() { self.x() } else { self.y() } } /// Get the dot product of this vector and another fn dot<V>(self, other: V) -> Self::Scalar where V: Vector2<Scalar = Self::Scalar>, { self.x() * other.x() + self.y() * other.y() } } impl<P> Vector2 for P where P: Pair + Copy, P::Item: Scalar, { type Scalar = P::Item; fn x(self) -> P::Item { self.to_pair().0 } fn y(self) -> P::Item { self.to_pair().1 } fn new(x: P::Item, y: P::Item) -> Self { Self::from_items(x, y) } } /// Trait for manipulating floating-point 2D vectors pub trait FloatingVector2: Vector2 where Self::Scalar: FloatingScalar, { /// Get the distance between this vector and another fn dist(self, to: Self) -> Self::Scalar { let cdiff = self.sub(to); (cdiff.x().pow(Self::Scalar::TWO) + cdiff.y().pow(Self::Scalar::TWO)) .pow(Self::Scalar::ONE / Self::Scalar::TWO) } /// Get the vector's magnitude fn mag(self) -> Self::Scalar { (self.x().pow(Self::Scalar::TWO) + self.y().pow(Self::Scalar::TWO)) .pow(Self::Scalar::ONE / Self::Scalar::TWO) } /// Get the unit vector fn unit(self) -> Self { let mag = self.mag(); if mag < Self::Scalar::EPSILON { Self::new(Self::Scalar::ZERO, Self::Scalar::ZERO) } else { self.div(mag) } } /// Rotate the vector some number of radians about the origin fn rotate(self, radians: Self::Scalar) -> Self { self.rotate_about(radians, Self::square(Self::Scalar::ZERO)) } /// Rotate the vector some number of radians about a pivot fn rotate_about(self, radians: Self::Scalar, pivot: Self) -> Self { let sin = radians.sin(); let cos = radians.cos(); let origin_point = self.sub(pivot); let rotated_point = Self::new( origin_point.x() * cos - origin_point.y() * sin, origin_point.x() * sin + origin_point.y() * cos, ); rotated_point.add(pivot) } /// Linear interpolate the vector with another fn lerp(self, other: Self, t: Self::Scalar) -> Self { Self::square(Self::Scalar::ONE - t) .mul2(self) .sub(Self::square(t).mul2(other)) } /// Get the arctangent of the vector, which corresponds to /// the angle it represents bounded between -π to π fn atan(self) -> Self::Scalar { self.y().atan2(self.x()) } /// Apply a transform to the vector fn transform<T>(self, transform: T) -> Self where T: Transform<Scalar = Self::Scalar>, { transform.apply(self) } } impl<T> FloatingVector2 for T where T: Vector2, T::Scalar: FloatingScalar, { } #[cfg(test)] #[test] fn margins() { let rect = [0, 0, 8, 8]; assert!(rect.contains([1, 1])); assert!(!rect.inner_margin(2).contains([1, 1])); } #[cfg(test)] #[test] fn transforms() { let v = [1.0, 3.0]; let rot = 1.0; let pivot = [5.0; 2]; let transform = f32::Trans::new().rotate_about(rot, pivot); let v1 = v.rotate_about(rot, pivot); let v2 = v.transform(transform); dbg!(v1.dist(v2) / f32::EPSILON); assert!(v1.dist(v2).is_near_zero(10.0)); }