Skip to content

Commit

Permalink
Support rotation/ in draw_tiles
Browse files Browse the repository at this point in the history
This change adds support for `tiled`'s flipping flags when rendering a tilemap

- Adds new api in Map `.spr_flip`, which renders a tile including the
  tile's [flipping parameters](https://doc.mapeditor.org/en/stable/reference/global-tile-ids/#mapping-a-gid-to-a-local-tile-id)
- Uses that api in .draw_tiles
  • Loading branch information
Adjective-Object committed Sep 27, 2024
1 parent 44cad5d commit d2702a5
Showing 1 changed file with 42 additions and 1 deletion.
43 changes: 42 additions & 1 deletion tiled/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ use std::collections::HashMap;
mod error;
mod tiled;

use core::f32::consts::PI;
pub use error::Error;
pub use tiled::{Property, PropertyVal};

Expand Down Expand Up @@ -47,6 +48,7 @@ pub struct Tile {
/// Whether the tile is vertically flipped
pub flip_y: bool,
/// Whether the tile is anti-diagonally flipped
/// (equivalent to a 90 degree clockwise rotation followed by a horizontal flip)
pub flip_d: bool,
}

Expand Down Expand Up @@ -95,8 +97,28 @@ pub struct Map {
pub raw_tiled_map: tiled::Map,
}

pub struct TileFlippedParams {
flip_x: bool,
flip_y: bool,
flip_d: bool,
}

impl Default for TileFlippedParams {
fn default() -> Self {
TileFlippedParams {
flip_x: false,
flip_y: false,
flip_d: false,
}
}
}

impl Map {
pub fn spr(&self, tileset: &str, sprite: u32, dest: Rect) {
self.spr_flip(tileset, sprite, dest, TileFlippedParams::default())
}

pub fn spr_flip(&self, tileset: &str, sprite: u32, dest: Rect, flip: TileFlippedParams) {
if self.tilesets.contains_key(tileset) == false {
panic!(
"No such tileset: {}, tilesets available: {:?}",
Expand All @@ -107,6 +129,13 @@ impl Map {
let tileset = &self.tilesets[tileset];
let spr_rect = tileset.sprite_rect(sprite);

let rotation = if flip.flip_d {
// diagonal flip
-PI / 2.0
} else {
0.0
};

draw_texture_ex(
&tileset.texture,
dest.x,
Expand All @@ -120,6 +149,9 @@ impl Map {
spr_rect.w + 2.0,
spr_rect.h + 2.0,
)),
flip_x: flip.flip_x,
flip_y: flip.flip_y ^ flip.flip_d,
rotation: rotation,
..Default::default()
},
);
Expand Down Expand Up @@ -186,7 +218,16 @@ impl Map {

for (tileset, tileset_layer) in &separated_by_ts {
for (tile, rect) in tileset_layer {
self.spr(tileset, tile.id, *rect);
self.spr_flip(
tileset,
tile.id,
*rect,
TileFlippedParams {
flip_x: tile.flip_x,
flip_y: tile.flip_y,
flip_d: tile.flip_d,
},
);
}
}
}
Expand Down

0 comments on commit d2702a5

Please sign in to comment.