From 7dba1b22e320c09a959d714561e61b03b5602d22 Mon Sep 17 00:00:00 2001 From: crumblingstatue Date: Sun, 2 Apr 2023 12:10:11 +0200 Subject: [PATCH] Fix world pos to tile pos calculation for negative values --- src/game.rs | 6 +++--- src/math.rs | 26 ++++++++++++++++++++++---- src/world.rs | 2 +- 3 files changed, 26 insertions(+), 8 deletions(-) diff --git a/src/game.rs b/src/game.rs index 1cd2380..0549bb5 100644 --- a/src/game.rs +++ b/src/game.rs @@ -2,7 +2,7 @@ use sfml::graphics::{Rect, RenderTarget, RenderWindow, Sprite, Transformable}; use crate::{ graphics::{ScreenPos, NATIVE_RESOLUTION}, - math::WorldPos, + math::{wp_to_tp, WorldPos, WorldPosScalar}, res::Res, world::{TilePos, World}, }; @@ -28,8 +28,8 @@ fn for_each_tile(camera_offset: WorldPos, mut f: impl FnMut(TilePos, ScreenPos)) for x in (-32..NATIVE_RESOLUTION.w + 32).step_by(32) { f( TilePos { - x: (camera_offset.x + x as i32) / 32, - y: (camera_offset.y + y as i32) / 32, + x: wp_to_tp(camera_offset.x + x as WorldPosScalar), + y: wp_to_tp(camera_offset.y + y as WorldPosScalar), }, ScreenPos { x: (x as i32 - camera_offset.x % 32) as i16, diff --git a/src/math.rs b/src/math.rs index 58a8849..c3a1c3c 100644 --- a/src/math.rs +++ b/src/math.rs @@ -1,4 +1,4 @@ -use crate::world::TilePos; +use crate::world::{TilePos, TilePosScalar}; pub type WorldPosScalar = i32; @@ -8,13 +8,31 @@ pub struct WorldPos { pub y: WorldPosScalar, } +pub const TILE_SIZE: u8 = 32; + impl WorldPos { pub fn tile_pos(&self) -> TilePos { TilePos { - x: self.x / TILE_SIZE as i32, - y: self.y / TILE_SIZE as i32, + x: wp_to_tp(self.x), + y: wp_to_tp(self.y), } } } -pub const TILE_SIZE: u8 = 32; +pub fn wp_to_tp(wp: WorldPosScalar) -> TilePosScalar { + if wp.is_negative() { + (wp + 1) / TILE_SIZE as TilePosScalar - 1 + } else { + wp / TILE_SIZE as TilePosScalar + } +} + +#[test] +fn test_wp_to_tp() { + assert_eq!(wp_to_tp(0), 0); + assert_eq!(wp_to_tp(1), 0); + assert_eq!(wp_to_tp(33), 1); + assert_eq!(wp_to_tp(-1), -1); + assert_eq!(wp_to_tp(-32), -1); + assert_eq!(wp_to_tp(-33), -2); +} diff --git a/src/world.rs b/src/world.rs index 157f447..b387a4e 100644 --- a/src/world.rs +++ b/src/world.rs @@ -140,7 +140,7 @@ fn test_to_chunk_and_local() { } // Need to support at least 4 million tiles long -type TilePosScalar = i32; +pub type TilePosScalar = i32; const CHUNK_EXTENT: u16 = 128; const CHUNK_N_TILES: usize = CHUNK_EXTENT as usize * CHUNK_EXTENT as usize;