From 6fc78f924c4222efeed0b6848c7184f4fdb8b431 Mon Sep 17 00:00:00 2001 From: dani Date: Mon, 3 Jul 2023 14:41:34 +0000 Subject: [PATCH] haaacky pixel->coord conversion --- examples/assets/hex2.gif | Bin 925 -> 1001 bytes examples/test.rs | 10 ++++++++-- src/hexmap.rs | 37 +++++++++++++++++++++++++++++++++---- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/examples/assets/hex2.gif b/examples/assets/hex2.gif index eedd75634f38bddbbe7b319de6b501fa277a4c1b..22691251d894aa335bdf1b6349e9e8cf3a64a1f7 100644 GIT binary patch delta 179 zcmV;k08Ia#2k8d~M@dFFIbl4p2SEdWJOCO100NkVFQLn=2csCY+DoGb$@#TO*l2~w zhd$;+wu8x~D9pO!DyLy>-&>dS?0T(VP$wc5CC6D(={q%@1|Adx0Ztv+>oT@=TD_NQ zSWGTz&yI1rv}UW^Z?n8neMjTxuD+6W2ZHbi7$*_@06R83P!0e9 delta 102 zcmV-s0Ga>k2b~88M@dFFIbj~L2SEc>9sn8u00K;eFQLn=2V-({#XGCMFl)*g-Uo6c z*_bGat)JwwNc@VleBKO@>wE9B`AWQDYG$-_l7UuIH4Fh!p`xy8y { window_state.scramble_palette(); } + Event::MouseClick(MouseButton::Right, _) => { + self.map + .set(self.map.pixel_to_coord(window_state.mouse_pos()), 1); + } _ => {} } } diff --git a/src/hexmap.rs b/src/hexmap.rs index 66982f4..2cd23ad 100644 --- a/src/hexmap.rs +++ b/src/hexmap.rs @@ -1,4 +1,5 @@ use crate::{Image, Tileset, Vec2}; +use num::complex::ComplexFloat; use std::rc::Rc; //odd-q vertical layout https://www.redblobgames.com/grids/hexagons @@ -6,15 +7,18 @@ pub struct HexMap { size: Vec2, data: Vec, tileset: Rc, + pix_tile_off: Vec2, } impl HexMap { //pub static - pub fn new(size: Vec2, tileset: Rc) -> Self { + //pix_tile_off: x offset per tile, up/down alternating y offset on x axis + pub fn new(size: Vec2, tileset: Rc, pix_tile_off: Vec2) -> Self { HexMap { size, data: vec![0; size.size()], tileset, + pix_tile_off, } } @@ -23,6 +27,32 @@ impl HexMap { self.data[self.coord_to_idx(coord)] } + pub fn pixel_to_coord(&self, pixel: Vec2) -> Vec2 { + let tilesize = self.tileset.tile_size(); + let xrepeat = pixel.x % self.pix_tile_off.x; + let mut x = pixel.x / self.pix_tile_off.x; + let py = if x % 2 == 0 { + pixel.y + } else { + pixel.y - self.pix_tile_off.y + }; + let yrepeat = py % tilesize.y; + let mut y = py / tilesize.y; + let outside = self.tileset.get(0).get_pixel(Vec2 { + x: xrepeat, + y: yrepeat, + }) == 0; + if outside { + x -= 1; + if yrepeat > tilesize.y / 2 { + y += 1; + } + y -= x % 2; + } + let slice = xrepeat / (tilesize.x / 4); + Vec2 { x, y } + } + pub fn set(&mut self, coord: Vec2, val: i32) { let idx = self.coord_to_idx(coord); self.data[idx] = val; @@ -39,9 +69,8 @@ impl HexMap { coord: Vec2, offset: Vec2, ) { - let x = coord.x * (self.tileset.tile_size().x as f64 * 3.0 / 4.0).ceil() as i32; - let y = - coord.y * self.tileset.tile_size().y + (coord.x % 2) * (self.tileset.tile_size().y / 2); + let x = coord.x * self.pix_tile_off.x; + let y = coord.y * self.tileset.tile_size().y + (coord.x % 2) * self.pix_tile_off.y; target.draw_image( Vec2 { x, y } + offset, self.tileset.get(self.data[self.coord_to_idx(coord)]),