1mod search;
13
14use std::cmp::Reverse;
21use std::collections::{BTreeMap, BTreeSet, VecDeque};
22
23use crate::pathfind::WALKABLE;
24use unbanished_terrain::CellType;
25
26const SECTOR: i32 = 8;
27const CACHE_LIFETIME: i64 = 120_000_000;
29const CACHE_SIZE: usize = 0x20000;
31const MAX_NODES: usize = 0x2000;
33
34fn walk(t: CellType) -> bool {
35 (1u32 << (t.0 & 0x1f)) & WALKABLE != 0
36}
37
38fn length(a: (i32, i32), b: (i32, i32)) -> i32 {
40 let (dx, dy) = (a.0 - b.0, a.1 - b.1);
41 ((dx * dx + dy * dy) as f32).sqrt() as i32
42}
43
44#[derive(Debug, Clone, Default)]
45struct Node {
46 pos: (i32, i32),
48 #[allow(dead_code)]
49 sector: i32,
50 links: Vec<i32>,
52 border: Vec<i32>,
53}
54
55#[derive(Debug, Clone, Default)]
56struct Sector {
57 x: i32,
58 y: i32,
59 nodes: Vec<i32>,
60 node_dirty: bool,
61 link_dirty: bool,
62}
63
64#[derive(Clone, Copy, Default)]
65struct Search {
66 parent: i32,
67 open: i32,
68 closed: i32,
69 g: i32,
70 key: (i32, i32),
71}
72
73#[derive(Debug, Clone)]
75struct Cache {
76 time: i64,
77 head: usize,
78 tail: usize,
79 ring: Vec<Option<((i32, i32), i32, i64)>>,
81 index: BTreeMap<(i32, i32), usize>,
82}
83
84pub struct SectorGraph {
88 n: i32,
89 w: i32,
90 h: i32,
91 nodes: Vec<Node>,
92 sectors: Vec<Sector>,
93 dirty_nodes: Vec<usize>,
94 dirty_links: Vec<usize>,
95 free: Vec<i32>,
96 pub cell_node: Vec<i32>,
99 search: Vec<Search>,
100 search_id: i32,
101 open: BTreeSet<((i32, Reverse<i32>), i32)>,
102 counter: i32,
103 cache: Cache,
104}
105
106impl SectorGraph {
107 pub fn new(size: usize, types: &[CellType]) -> SectorGraph {
111 let n = size as i32;
112 let (w, h) = (n / SECTOR, n / SECTOR);
113 let mut sectors = Vec::new();
114 for y in 0..h {
115 for x in 0..w {
116 sectors.push(Sector {
117 x,
118 y,
119 nodes: Vec::new(),
120 node_dirty: true,
121 link_dirty: true,
122 });
123 }
124 }
125 let count = sectors.len();
126 let mut g = SectorGraph {
127 n,
128 w,
129 h,
130 nodes: Vec::new(),
131 sectors,
132 dirty_nodes: (0..count).collect(),
133 dirty_links: (0..count).collect(),
134 free: Vec::new(),
135 cell_node: vec![-1; size * size],
136 search: Vec::new(),
137 search_id: 1,
138 open: BTreeSet::new(),
139 counter: 0,
140 cache: Cache {
141 time: 0,
142 head: 0,
143 tail: 0,
144 ring: vec![None; CACHE_SIZE],
145 index: BTreeMap::new(),
146 },
147 };
148 g.rebuild(types);
149 g
150 }
151
152 pub fn mark(&mut self, x: i32, y: i32) {
156 let s = ((y / SECTOR) * self.w + x / SECTOR) as usize;
157 if self.sectors[s].node_dirty {
158 return;
159 }
160 self.sectors[s].node_dirty = true;
161 self.dirty_nodes.push(s);
162 let (sx, sy) = (self.sectors[s].x, self.sectors[s].y);
163 for yy in sy - 1..=sy + 1 {
164 if yy < 0 || yy >= self.h {
165 continue;
166 }
167 for xx in sx - 1..=sx + 1 {
168 if xx < 0 || xx >= self.w {
169 continue;
170 }
171 let t = (yy * self.w + xx) as usize;
172 if !self.sectors[t].link_dirty {
173 self.sectors[t].link_dirty = true;
174 self.dirty_links.push(t);
175 }
176 }
177 }
178 }
179
180 pub fn rebuild(&mut self, types: &[CellType]) {
184 if self.dirty_nodes.is_empty() && self.dirty_links.is_empty() {
185 return;
186 }
187 for s in std::mem::take(&mut self.dirty_nodes) {
188 self.build_sector(s, types);
189 self.sectors[s].node_dirty = false;
190 }
191 for s in std::mem::take(&mut self.dirty_links) {
192 self.link_sector(s);
193 self.sectors[s].link_dirty = false;
194 }
195 self.search = vec![Search::default(); self.nodes.len()];
196 }
197
198 fn build_sector(&mut self, s: usize, types: &[CellType]) {
200 for id in std::mem::take(&mut self.sectors[s].nodes) {
202 let node = &mut self.nodes[id as usize];
203 *node = Node {
204 pos: (-1, -1),
205 sector: -1,
206 ..Default::default()
207 };
208 self.free.push(id);
209 }
210 let (x0, y0) = (self.sectors[s].x * SECTOR, self.sectors[s].y * SECTOR);
211 let labels = self.label(x0, y0, types);
212 let count = labels.iter().copied().max().unwrap_or(0);
213 for label in 1..=count {
214 let id = self.create_node(s, x0, y0, &labels, label);
215 self.sectors[s].nodes.push(id);
216 }
217 for ly in 0..SECTOR {
219 for lx in 0..SECTOR {
220 let label = labels[(ly * SECTOR + lx) as usize];
221 let cell = ((y0 + ly) * self.n + x0 + lx) as usize;
222 self.cell_node[cell] = if label >= 1 {
223 self.sectors[s].nodes[label as usize - 1]
224 } else {
225 -1
226 };
227 }
228 }
229 }
230
231 fn label(&self, x0: i32, y0: i32, types: &[CellType]) -> Vec<i32> {
234 let mut labels = vec![0i32; (SECTOR * SECTOR) as usize];
235 let at = |lx: i32, ly: i32| types[((y0 + ly) * self.n + x0 + lx) as usize];
236 let mut next = 1;
237 for ly in 0..SECTOR {
238 for lx in 0..SECTOR {
239 if !walk(at(lx, ly)) || labels[(ly * SECTOR + lx) as usize] != 0 {
240 continue;
241 }
242 let mut queue = VecDeque::from([(lx, ly)]);
243 while let Some((qx, qy)) = queue.pop_front() {
244 if labels[(qy * SECTOR + qx) as usize] != 0 || !walk(at(qx, qy)) {
245 continue;
246 }
247 let mut left = qx;
248 while left - 1 >= 0 && walk(at(left - 1, qy)) {
249 left -= 1;
250 }
251 let mut right = qx;
252 while right + 1 <= SECTOR - 1 && walk(at(right + 1, qy)) {
253 right += 1;
254 }
255 for u in left..=right {
256 labels[(qy * SECTOR + u) as usize] = next;
257 }
258 if left - 1 >= 0 {
259 left -= 1;
260 }
261 if right + 1 <= SECTOR - 1 {
262 right += 1;
263 }
264 for (ok, row) in [(qy > 0, qy - 1), (qy < SECTOR - 1, qy + 1)] {
265 if !ok {
266 continue;
267 }
268 for u in left..=right {
269 if labels[(row * SECTOR + u) as usize] == 0 && walk(at(u, row)) {
270 queue.push_back((u, row));
271 }
272 }
273 }
274 }
275 next += 1;
276 }
277 }
278 labels
279 }
280
281 fn create_node(&mut self, s: usize, x0: i32, y0: i32, labels: &[i32], label: i32) -> i32 {
283 let id = match self.free.pop() {
285 Some(id) => id,
286 None => {
287 self.nodes.push(Node::default());
288 self.nodes.len() as i32 - 1
289 }
290 };
291 let (mut sx, mut sy, mut count) = (0, 0, 0);
292 let mut border = Vec::new();
293 for ly in 0..SECTOR {
294 for lx in 0..SECTOR {
295 if labels[(ly * SECTOR + lx) as usize] != label {
296 continue;
297 }
298 let (gx, gy) = (lx + x0, ly + y0);
299 count += 1;
300 sx += gx;
301 sy += gy;
302 if lx == 0 || ly == 0 || lx == SECTOR - 1 || ly == SECTOR - 1 {
303 for dy in -1..=1 {
305 for dx in -1..=1 {
306 let (cx, cy) = (gx + dx, gy + dy);
307 if cx < 0 || cy < 0 || cx >= self.n || cy >= self.n {
308 continue;
309 }
310 let outside =
311 cx < x0 || cy < y0 || cx > x0 + SECTOR - 1 || cy > y0 + SECTOR - 1;
312 let cell = cy * self.n + cx;
313 if outside && !border.contains(&cell) {
314 border.push(cell);
315 }
316 }
317 }
318 }
319 }
320 }
321 self.nodes[id as usize] = Node {
322 pos: (sx / count, sy / count),
323 sector: s as i32,
324 links: Vec::new(),
325 border,
326 };
327 id
328 }
329
330 fn link_sector(&mut self, s: usize) {
332 for &id in &self.sectors[s].nodes.clone() {
333 let border = self.nodes[id as usize].border.clone();
334 let mut links = Vec::new();
335 for cell in border {
336 let other = self.cell_node[cell as usize];
337 if other >= 0 && !links.contains(&other) {
338 links.push(other);
339 }
340 }
341 self.nodes[id as usize].links = links;
342 }
343 }
344
345 pub fn node_near(&self, cell: i32) -> i32 {
349 let n = self.n;
350 let id = self.cell_node[cell as usize];
351 if id >= 0 {
352 return id;
353 }
354 let (x, y) = (cell % n, cell / n);
355 let node = |cx: i32, cy: i32| -> Option<i32> {
356 (cx >= 0 && cy >= 0 && cx < n && cy < n)
357 .then(|| self.cell_node[(cy * n + cx) as usize])
358 .filter(|&v| v >= 0)
359 };
360 for r in 1..=3 {
361 for t in x - r..=x + r {
362 let row = y + (t - x);
363 if row >= 0 && row < n {
364 if let Some(v) = node(x - r, row).or_else(|| node(x + r, row)) {
365 return v;
366 }
367 }
368 if t >= 0 && t < n {
369 if let Some(v) = node(t, y - r).or_else(|| node(t, y + r)) {
370 return v;
371 }
372 }
373 }
374 }
375 -1
376 }
377}
378
379#[cfg(test)]
380mod tests;