Add utils for hexagonal grild #50

Merged
tipragot merged 23 commits from hex-utils into main 2024-02-14 17:49:08 +00:00
Showing only changes of commit 23d839ea34 - Show all commits

View file

@ -1,28 +1,10 @@
//! This file contains utilities for working with hex coordinates.
//! All fonction related to calculations in hexagonal grid.
use std::collections::HashSet;
use std::ops;
/// Contains all "HexPosition" neighbors of "HexPosition"
pub struct GroupHexPosition(pub HashSet<HexPosition>);
impl GroupHexPosition {
/// TODO
pub fn new(hexes: HashSet<HexPosition>) -> Self {
GroupHexPosition(hexes)
}
/// Removes the origin (`HexPosition { q: 0, r: 0 }`) of a
/// "GroupHexPosition"
pub fn remove_origin(&mut self) -> &mut Self {
self.0.remove(&HexPosition { q: 0, r: 0 });
self
}
}
/// Hex position (in a hexagonal grid).
///
/// usnig this doc : https://www.redblobgames.com/grids/hexagons/
/// Hexagonal position (in a hexagonal grid).
/// We are using the axial coordinate system explained in this [documentation](https://www.redblobgames.com/grids/hexagons/#coordinates).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct HexPosition {
/// Q coordinate
@ -33,23 +15,36 @@ pub struct HexPosition {
}
impl HexPosition {
/// Returns the distance between two "HexPosition"
/// Returns the distance between two [HexPosition]
///
/// # How does it work ?
///
/// Hexagonal grid using the [cube](https://www.redblobgames.com/grids/hexagons/#coordinates) coordinate system,
/// is like a cube in 2D space.
/// The Manhattan distance between two positions is equal to: the half of the sum of abs(dx) + abs(dy) + abs(dz)
pub fn distance_to(&self, other: &HexPosition) -> f32 {
((self.q - other.q).abs()
+ (self.r - other.r).abs()
+ (self.q + self.r - other.q - other.r).abs()) as f32
/ 2.
// dx = |x1 - x2| and x = q
let dq = self.q - other.q;
// dy = |y1 - y2| and y = r
let dr = self.r - other.r;
// dz = |z1 - z2| and z = -q - r
let ds = self.q + self.r - other.q - other.r;
// Manhattan distance = (abs(dq) + abs(dr) + abs(ds)) / 2
(dq.abs() + dr.abs() + ds.abs()) as f32 / 2.
}
/// Returns all positions in a given range
pub fn range(&self, range: i32) -> GroupHexPosition {
let mut positions = HashSet::new();
/// Returns all positions in a given `range`.
pub fn range(&self, range: i32) -> HashSet<HexPosition> {
let mut result_positions = HashSet::new();
for q in (-range)..=range {
for r in (-range).max(-q - range)..=range.min(-q + range) {
positions.insert(HexPosition { q, r });
result_positions.insert(HexPosition { q, r });
}
}
GroupHexPosition(positions)
result_positions
}
}