use std::{sync::atomic::AtomicU32, collections::HashMap, net::SocketAddr}; use nalgebra::Vector2; use starkingdoms_protocol::planet::PlanetType; use crate::{planet::Planet, SCALE, manager::{ClientHandlerMessage, Player}}; pub type EntityId = u32; pub type Entities = HashMap; static mut ENTITY_ID_COUNT: AtomicU32 = AtomicU32::new(0); pub fn get_entity_id() -> EntityId { let last_entity_id = unsafe { &ENTITY_ID_COUNT }; let id = last_entity_id.fetch_add(1, std::sync::atomic::Ordering::AcqRel); if id > 2_147_483_600 { panic!("No remaining entity ids") }; id } #[derive(Default)] pub struct EntityHandler { pub entities: Entities, } impl EntityHandler { pub fn new() -> EntityHandler { EntityHandler { entities: Entities::new() } } pub fn get_planets(&self) -> Vec { let mut ids = Vec::new(); for entity in self.entities.values() { if let Entity::Planet(planet) = entity { ids.push(planet.clone()); } } ids } pub fn get_planet(&self, planet_type: PlanetType) -> Option { let mut planets = self.get_planets(); for i in 0..planets.len() { if planets[i].planet_type == planet_type { planets.remove(i); } } if planets.is_empty() { return None; } Some(planets[0].clone()) } pub fn get_players(&self) -> Vec<(SocketAddr, Player)> { let mut players = Vec::new(); for entity in self.entities.values() { if let Entity::Player(player) = entity { players.push((player.addr, player.clone())); } } players } pub fn get_player_id(&self, addr: SocketAddr) -> Option { for (id, entity) in self.entities.iter() { if let Entity::Player(player) = entity { if player.addr == addr { return Some(*id); } } } None } pub fn get_player(&self, addr: SocketAddr) -> Option { let mut players = self.get_players(); for i in 0..players.len() { if players[i].0 != addr { players.remove(i); } } if players.is_empty() { return None; } Some(players[0].clone().1) } pub fn gravity(&self, position: (f64, f64), mass: f64) -> (f64, f64) { let mut direction = Vector2::zeros(); let planets = self.get_planets(); for planet in planets { let planet_grav = planet.gravity(position, mass); direction.x += planet_grav.0; direction.y += planet_grav.1; } (direction.x, direction.y) } pub fn to_protocol(&self) -> ClientHandlerMessage { let mut planets = vec![]; for planet in self.get_planets() { // TODO: Adjust codegen to use f64 planets.push(starkingdoms_protocol::planet::Planet { planet_type: planet.planet_type.into(), x: (planet.position.0 * SCALE) as f32, y: (planet.position.1 * SCALE) as f32, radius: planet.radius as f32, // DO NOT * SCALE special_fields: Default::default(), }); } ClientHandlerMessage::PlanetData { planets } } } #[derive(Clone)] pub enum Entity { Player(Player), Planet(Planet), }