pathfinding/map/
map_manager.rs1use crate::astar::AStar;
2use crate::errors::my_errors::{MyError, RetResult};
3use lazy_static::lazy_static;
4use std::collections::HashMap;
5use std::sync::{Arc};
6use tokio::sync::RwLock;
7use chrono::Utc;
8
9use crate::map::map::Map;
10use crate::map::map::MapType;
11use crate::map::IndexType;
12
13pub struct MapManager {
14 map_collections: HashMap<i64, MapType>,
15}
16
17impl MapManager {
18 pub fn get_instance() -> Arc<RwLock<MapManager>> {
19 Arc::clone(&MAP_MANAGER)
20 }
21
22 fn new() -> Arc<RwLock<MapManager>> {
23 Arc::new(RwLock::new(MapManager {
24 map_collections: HashMap::new(),
25 }))
26 }
27 pub async fn new_astar(&mut self) -> i64 {
28 let map_id = Utc::now().timestamp_millis();
29 self.map_collections.insert(map_id, AStar::new());
30 map_id
31 }
32
33 pub async fn remove_map(&mut self, map_id: &i64) {
34 self.map_collections.remove(map_id);
35 }
36
37 pub async fn load(&self, map_id: &i64, points: Vec<Vec<i32>>) -> RetResult<()> {
38 let res = self.map_collections.get(map_id);
39 match res {
40 None => Err(MyError::MapNotExist(map_id.clone()).into()),
41 Some(m) => m.clone().write().await.load(points),}
46 }
47
48 pub async fn load_from_file(&self, map_id: &i64, file: String) -> RetResult<()> {
49 if let Some(m) = self.map_collections.get(&map_id) {
50 return Ok(m.clone().write().await.load_from_file(file).await?)
51 }
56
57 Err(MyError::MapNotExist(map_id.clone()).into())
58 }
59
60 pub async fn load_from_string(&self, map_id: &i64, file: String) -> RetResult<()> {
61 if let Some(m) = self.map_collections.get(&map_id) {
62 return Ok(m.clone().write().await.load_from_string(file).await?)
63 }
68
69 Err(MyError::MapNotExist(map_id.clone()).into())
70 }
71
72 pub async fn set_walkable(
73 &self,
74 map_id: &i64,
75 point: (IndexType, IndexType),
76 walkable: i32,
77 ) -> RetResult<()> {
78 let res = self.map_collections.get(map_id);
79 match res {
80 None => Err(MyError::MapNotExist(map_id.clone()).into()),
81 Some(m) => Ok(m.clone().write().await.set_walkable(point, walkable)),
82 }
87 }
88
89 pub async fn find_path(
90 &self,
91 map_id: &i64,
92 start: (IndexType, IndexType),
93 end: (IndexType, IndexType),
94 ) -> RetResult<Vec<(IndexType, IndexType)>> {
95 let res = self.map_collections.get(map_id);
96 match res {
97 None => Err(MyError::MapNotExist(map_id.clone()).into()),
98 Some(m) => Ok(m.clone().read().await.find_path(start, end)),
99 }
104 }
105}
106
107lazy_static! {
108 static ref MAP_MANAGER: Arc<RwLock<MapManager>> = MapManager::new();
109
110 }