From dae48df64ae7787d42b57de8e8e3fc37d2509ff5 Mon Sep 17 00:00:00 2001 From: CoCoSol007 Date: Thu, 15 Feb 2024 09:50:15 +0000 Subject: [PATCH] Improve utils by adding pixel conversion (#52) Reviewed-on: https://git.tipragot.fr/corentin/border-wars/pulls/52 Reviewed-by: Tipragot Co-authored-by: CoCoSol007 Co-committed-by: CoCoSol007 --- crates/border-wars/src/map/hex.rs | 31 ++++++++++++++++++++++++++++++- 1 file changed, 30 insertions(+), 1 deletion(-) diff --git a/crates/border-wars/src/map/hex.rs b/crates/border-wars/src/map/hex.rs index 1aeaa14..74db219 100644 --- a/crates/border-wars/src/map/hex.rs +++ b/crates/border-wars/src/map/hex.rs @@ -4,6 +4,7 @@ use std::collections::HashSet; use std::hash::Hash; use std::ops::{Add, AddAssign, Sub, SubAssign}; +use num::cast::AsPrimitive; use num::{FromPrimitive, Signed}; use partial_min_max::{max, min}; @@ -24,7 +25,7 @@ pub struct HexPosition { pub r: T, } -impl HexPosition { +impl> HexPosition { /// Returns the distance between two [HexPosition]s. /// /// # How it works @@ -55,6 +56,34 @@ impl HexPosition { // Manhattan distance = (abs(dq) + abs(dr) + abs(ds)) / 2 (dq + dr + ds) / (T::one() + T::one()) } + + /// Converts the current [HexPosition] into a pixel coordinate. + /// Input: The size of the hexagon in pixels (witdh, height). + /// + /// If you want to learn more about pixel coordinates conversion, + /// you can check the + /// [documentation](https://www.redblobgames.com/grids/hexagons/#hex-to-pixel). + /// + /// # Example + /// + /// ```no_run + /// use border_wars::map::hex::HexPosition; + /// + /// let position = HexPosition { q: 1, r: 0 }; + /// assert_eq!( + /// position.to_pixel_coordinates((1.0, 1.0)), + /// (3f32.sqrt(), 0.0) + /// ); + /// ``` + pub fn to_pixel_coordinates(&self, size: (f32, f32)) -> (f32, f32) { + ( + size.0 + * 3f32 + .sqrt() + .mul_add(self.q.as_(), 3f32.sqrt() / 2.0 * (self.r.as_())), + size.1 * (3.0 / 2.0 * self.r.as_()), + ) + } } impl HexPosition {