Skip to content
Snippets Groups Projects
utils.rs 1.71 KiB
Newer Older
Louis's avatar
Louis committed
use bevy::prelude::{Component, Resource};
use ldtk_rust::EntityInstance;
use num_traits::AsPrimitive;
use serde::de::DeserializeOwned;
use serde::Serialize;

use crate::get_ldtk_tile_scale;

pub trait SerdeClone {
	fn serde_clone(&self) -> Self;
}

impl<T> SerdeClone for T
where
	T: Serialize + DeserializeOwned,
{
	fn serde_clone(&self) -> Self {
		serde_json::from_value(serde_json::to_value(self).unwrap()).unwrap()
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;

#[derive(Default, Resource, Clone)]
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 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
	}
}