1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
use super::path_segment::{PathSegment, PathSegment::*};
use crate::{
	generics::{a_star_search, Cost, Path},
	neighbors::Neighborhood,
	Point,
};

/// A Path that may not be fully calculated yet.
///
/// This struct represents a Path that was generated by the PathCache. Since
/// [`config.cache_paths`](super::PathCacheConfig::cache_paths) may be set to false, there might by
/// segments of this Path that are not yet calculated. In those cases, since the cost function is
/// required to resolve those sections, it is necessary to call
/// [`safe_next()`](AbstractPath::safe_next) or [`resolve()`](AbstractPath::resolve).
/// Otherwise it is possible to treat this as an Iterator<Point>.
///
/// **Warning: Calling `next()` on an AbstractPath with unknown segments will panic as soon as those
/// segments are reached.**
///
/// **Warning: Keeping an AbstractPath after changing the Grid, or using a different cost function,
/// leads to undefined behavior and panics.**
///
/// **You have been warned**
#[derive(Debug, Clone)]
pub struct AbstractPath<N: Neighborhood> {
	neighborhood: N,
	total_cost: Cost,
	total_length: usize,
	path: Vec<PathSegment>,
	end: Point,
	current_index: (usize, usize),
}

#[allow(dead_code)]
impl<N: Neighborhood> AbstractPath<N> {
	/// Returns the total cost of this Path.
	/// This value is always known and requires no further calculations.
	pub fn cost(&self) -> Cost {
		self.total_cost
	}

	/// Returns the total length of this Path.
	/// This value is always known and requires no further calculations.
	pub fn length(&self) -> usize {
		self.total_length
	}

	/// A variant of [`Iterator::next()`](#impl-Iterator) that can resolve unknown segments
	/// of the Path. Use this method instead of `next()` when
	/// [`config.cache_paths`](super::PathCacheConfig::cache_paths) is set to false.
	pub fn safe_next(&mut self, get_cost: impl Fn(Point) -> isize) -> Option<Point> {
		if self.current_index.0 >= self.path.len() {
			return None;
		}
		let mut current = &self.path[self.current_index.0];
		if let Unknown { start, end, .. } = *current {
			let path = a_star_search(
				|p| {
					self.neighborhood
						.get_all_neighbors(p)
						.map(|n| (n, get_cost(n) as usize))
				},
				|p| get_cost(p) >= 0,
				start,
				end,
				|p| self.neighborhood.heuristic(p, end),
			)
			.unwrap_or_else(|| {
				panic!(
					"Impossible Path marked as Possible: {:?} -> {:?}",
					start, end
				)
			});

			self.path[self.current_index.0] = Known(path);
			current = &self.path[self.current_index.0];

			self.current_index.1 = 1; // paths include start and end, but we are already at start
		}

		if let Known(path) = current {
			let ret = path[self.current_index.1];
			self.current_index.1 += 1;
			if self.current_index.1 >= path.len() {
				self.current_index.0 += 1;
				self.current_index.1 = 0;
			}
			Some(ret)
		} else {
			panic!("how.");
		}
	}

	/// Resolves all unknown sections of the Path.
	///
	/// if [`config.cache_paths`](super::PathCacheConfig::cache_paths) is set to true,
	/// then calling this method is similar to calling `path.collect::<Vec<Point>>()`.
	///
	/// The return value is a [`Path`] from the [`generics`](crate::generics) module, which is
	/// essentially a Vec<Point>, but with a `cost` member, since this path is consumed by
	/// `resolve`
	pub fn resolve(mut self, get_cost: impl Fn(Point) -> isize) -> Path<Point> {
		let mut result = Vec::with_capacity(self.total_length);

		while let Some(pos) = self.safe_next(&get_cost) {
			result.push(pos);
		}

		Path::new(result, self.total_cost)
	}

	pub(crate) fn new(neighborhood: N, start: Point) -> AbstractPath<N> {
		AbstractPath {
			neighborhood: neighborhood,
			total_cost: 0,
			total_length: 0,
			path: vec![],
			end: start,
			current_index: (0, 1),
		}
	}

	pub(crate) fn from_known_path(neighborhood: N, path: Path<Point>) -> AbstractPath<N> {
		let end = path[path.len() - 1];
		AbstractPath {
			neighborhood: neighborhood,
			total_cost: path.cost(),
			total_length: path.len(),
			path: vec![Known(path)],
			end,
			current_index: (0, 1),
		}
	}

	pub(crate) fn from_node(neighborhood: N, node: Point) -> AbstractPath<N> {
		AbstractPath {
			neighborhood: neighborhood,
			total_cost: 0,
			total_length: 0,
			path: vec![],
			end: node,
			current_index: (0, 1),
		}
	}

	pub(crate) fn add_path_segment(&mut self, path: PathSegment) -> &mut Self {
		assert!(self.end == path.start(), "Added disconnected PathSegment");
		self.total_cost += path.cost();
		self.total_length += path.len();
		self.end = path.end();
		self.path.push(path);
		self
	}

	pub(crate) fn add_path(&mut self, path: Path<Point>) -> &mut Self {
		self.total_cost += path.cost();
		self.total_length += path.len();
		self.end = path[path.len() - 1];
		self.path.push(Known(path));
		self
	}

	pub(crate) fn add_node(&mut self, node: Point, cost: Cost, len: usize) -> &mut Self {
		self.path.push(Unknown {
			start: self.end,
			end: node,
			cost,
			len,
		});
		self.total_cost += cost;
		self.total_length += len;
		self.end = node;
		self
	}
}

impl<N: Neighborhood> Iterator for AbstractPath<N> {
	type Item = Point;
	/// See [`Iterator::next`]
	///
	/// ## Panics
	/// Panics if a segment of the Path is not known because [`config.cache_paths`](super::PathCacheConfig::cache_paths)
	/// is set to false. Use [`safe_next`](AbstractPath::safe_next) in those cases.
	fn next(&mut self) -> Option<Point> {
		if self.current_index.0 >= self.path.len() {
			return None;
		}
		let current = &self.path[self.current_index.0];
		if let Unknown { .. } = *current {
			panic!(
				"Tried calling next() on a Path that is not fully known. Use safe_next instead."
			);
		}

		if let Known(path) = current {
			let ret = path[self.current_index.1];
			self.current_index.1 += 1;
			if self.current_index.1 >= path.len() {
				self.current_index.0 += 1;
				self.current_index.1 = 1;
			}
			Some(ret)
		} else {
			panic!("how.");
		}
	}
}