Skip to content
Snippets Groups Projects
utils.rs 1.8 KiB
Newer Older
Louis's avatar
Louis committed
use bevy::prelude::{Component, Resource};
use num_traits::AsPrimitive;

use crate::get_ldtk_tile_scale;
use crate::ldtk::EntityInstance;
Louis's avatar
Louis committed

pub fn px_to_grid<T: AsPrimitive<i64>>(t: T) -> i64 {
	t.as_() / (get_ldtk_tile_scale() as i64)
}

pub fn grid_to_px<T: AsPrimitive<f32>>(t: T) -> f32 {
	t.as_() * get_ldtk_tile_scale()
}

Louis's avatar
Louis committed
pub fn entity_centre(level_height: i64, entity: &EntityInstance) -> (f32, f32) {
	let x = entity.px[0] - (entity.width / 2);
	let y = level_height - entity.px[1] - entity.height / 2;
Louis's avatar
Louis committed
	(x as f32, y as f32)
}

Louis's avatar
Louis committed
#[derive(Component)]
pub struct WorldLinked;

Louis's avatar
Louis committed
#[derive(Default, Resource, Clone, Debug)]
Louis's avatar
Louis committed
pub struct ActiveLevel {
	pub map: String,
	pub dirty: bool,
}

impl ActiveLevel {
	pub fn new<T: ToString>(map: T) -> Self {
		ActiveLevel {
			map: map.to_string(),
			dirty: false,
		}
	}
}
Louis's avatar
Louis committed

#[derive(Debug, Copy, Clone)]
pub struct Indexer {
Louis's avatar
Louis committed
}

impl Indexer {
	pub fn new(width: impl AsPrimitive<i64>, height: impl AsPrimitive<i64>) -> Self {
Louis's avatar
Louis committed
		Self {
			width: width.as_(),
			height: height.as_(),
		}
	}

	pub fn index(&self, x: impl AsPrimitive<i64>, y: impl AsPrimitive<i64>) -> usize {
Louis's avatar
Louis committed
		((y.as_() * self.width) + x.as_()).as_()
	}

	pub fn index_checked(
		&self,
		x: impl AsPrimitive<i64>,
		y: impl AsPrimitive<i64>,
	) -> Option<usize> {
		if self.is_valid(x, y) {
			Some(self.index(x, y))
		} else {
			None
		}
	}

	pub fn reverse(&self, index: impl AsPrimitive<i64>) -> (usize, usize) {
Louis's avatar
Louis committed
		(
			(index.as_() % self.width).max(0) as usize,
			(index.as_() / self.width).max(0) as usize,
Louis's avatar
Louis committed
		)
	}

	pub fn width(&self) -> i64 {
Louis's avatar
Louis committed
		self.width
	}
	pub fn height(&self) -> i64 {
Louis's avatar
Louis committed
		self.height
	}

	pub fn is_valid(&self, x: impl AsPrimitive<i64>, y: impl AsPrimitive<i64>) -> bool {
		let x = x.as_();
		let y = y.as_();

		x >= 0 && x < self.width && y >= 0 && y < self.height
	}
Louis's avatar
Louis committed
}