generated from tipragot/rust
Remake utils for hexagon grids #55
|
@ -55,6 +55,11 @@ pub trait Number:
|
|||
fn abs(self) -> Self {
|
||||
if self < Self::ZERO { -self } else { self }
|
||||
}
|
||||
|
||||
/// Converts `self` to an `usize`.
|
||||
fn to_usize(self) -> usize;
|
||||
|
||||
fn from_usize(value: usize) -> Self;
|
||||
}
|
||||
|
||||
macro_rules! number_impl {
|
||||
|
@ -65,7 +70,17 @@ macro_rules! number_impl {
|
|||
const ZERO: Self = [< 0 $t >];
|
||||
const ONE: Self = [< 1 $t >];
|
||||
const TWO: Self = [< 2 $t >];
|
||||
|
||||
fn to_usize(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
|
||||
fn from_usize(value: usize) -> Self {
|
||||
value as $t
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
)*}};
|
||||
}
|
||||
|
||||
|
@ -118,8 +133,8 @@ impl HexDirection {
|
|||
pub struct HexRing<T: Number> {
|
||||
current: HexPosition<T>,
|
||||
direction: HexDirection,
|
||||
radius: T,
|
||||
index: T,
|
||||
radius: usize,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl<T: Number> Iterator for HexRing<T> {
|
||||
|
@ -160,16 +175,16 @@ impl<T: Number> Iterator for HexRing<T> {
|
|||
pub struct HexSpiral<T: Number> {
|
||||
origin: HexPosition<T>,
|
||||
current: HexRing<T>,
|
||||
radius: T,
|
||||
index: T,
|
||||
radius: usize,
|
||||
index: usize,
|
||||
}
|
||||
|
||||
impl<T: Number> Iterator for HexSpiral<T> {
|
||||
type Item = HexPosition<T>;
|
||||
|
||||
fn next(&mut self) -> Option<Self::Item> {
|
||||
if self.index == T::TWO {
|
||||
self.index += T::ONE;
|
||||
if self.index == 0 {
|
||||
self.index += 1;
|
||||
return Some(self.origin);
|
||||
}
|
||||
if self.index > self.radius {
|
||||
|
@ -177,7 +192,7 @@ impl<T: Number> Iterator for HexSpiral<T> {
|
|||
}
|
||||
let mut result = self.current.next();
|
||||
if result.is_none() && self.index < self.radius {
|
||||
self.index += T::ONE;
|
||||
self.index += 1;
|
||||
self.current = self.origin.ring(self.index);
|
||||
result = self.current.next();
|
||||
}
|
||||
|
@ -198,22 +213,22 @@ impl<T: Number> HexPosition<T> {
|
|||
}
|
||||
|
||||
/// Returns the hexagonal ring of the given radius.
|
||||
pub fn ring(self, radius: T) -> HexRing<T> {
|
||||
pub fn ring(self, radius: usize) -> HexRing<T> {
|
||||
HexRing {
|
||||
current: self + HexDirection::DownLeft.to_vector() * radius,
|
||||
current: self + HexDirection::DownLeft.to_vector() * radius.from_usize(),
|
||||
direction: HexDirection::Right,
|
||||
radius,
|
||||
index: T::ZERO,
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns the hexagonal spiral of the given radius.
|
||||
pub fn spiral(self, radius: T) -> HexSpiral<T> {
|
||||
pub fn spiral(self, radius: usize) -> HexSpiral<T> {
|
||||
HexSpiral {
|
||||
origin: self,
|
||||
current: self.ring(T::ONE),
|
||||
current: self.ring(1),
|
||||
radius,
|
||||
index: T::ZERO,
|
||||
index: 0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in a new issue