hex2d_dpcext/algo.rs
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 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355
/// Breadth First Search
pub mod bfs {
use hex2d::Coordinate;
use hex2d;
use std::hash;
use std::collections::VecDeque;
use std::collections::HashMap;
use std::collections::hash_map::Entry::{Occupied,Vacant};
struct Visited<I = i32>
where I : hex2d::Integer
{
prev : Coordinate<I>,
dist : u32,
}
/// Breadth First Search
///
/// Use BFS to find closest (in walk steps) Coordinates that satisfy `is_dest` and can be
/// reached with a walk through coordinates for which `can_pass` returns true.
pub struct Traverser<FCanPass, FIsDest, I = i32> where
I : hex2d::Integer,
I : hash::Hash,
FCanPass : Fn(Coordinate<I>) -> bool,
FIsDest : Fn(Coordinate<I>) -> bool
{
visited : HashMap<Coordinate<I>, Visited<I>>,
to_traverse : VecDeque<Coordinate<I>>,
can_pass : FCanPass,
is_dest : FIsDest,
start : Coordinate<I>,
}
impl<FCanPass, FIsDest, I> Traverser<FCanPass, FIsDest, I> where
I : hex2d::Integer,
I : hash::Hash,
FCanPass : Fn(Coordinate<I>) -> bool,
FIsDest : Fn(Coordinate<I>) -> bool
{
/// Create a Traverser instance with initial conditions
pub fn new(can_pass : FCanPass, is_dest : FIsDest, start: Coordinate<I>) -> Traverser<FCanPass, FIsDest, I> {
let mut to_traverse = VecDeque::new();
to_traverse.push_back(start);
let mut visited = HashMap::new();
visited.insert(start, Visited{prev: start, dist: 0});
Traverser {
visited: visited,
to_traverse: to_traverse,
can_pass: can_pass,
is_dest: is_dest,
start: start,
}
}
/// Find next closest coordinate.
///
/// Can be called multiple times, each time returning next coordinate
pub fn find(&mut self) -> Option<Coordinate<I>> {
loop {
let pos = match self.to_traverse.pop_front() {
None => return None,
Some(coord) => coord,
};
// Traverse before returning, so `find` can be call subsequently
// for more than just first answer
if (self.can_pass)(pos) {
let &Visited{dist, ..} = self.visited.get(&pos).expect("BFS: Should have been visited already");
let dist = dist + 1;
for &npos in pos.neighbors().iter() {
match self.visited.entry(npos) {
Occupied(_) => { /* already visited */ }
Vacant(entry) => {
entry.insert(Visited{prev: pos, dist: dist});
self.to_traverse.push_back(npos);
}
}
}
}
if (self.is_dest)(pos) {
return Some(pos);
}
}
}
/// Return neighbor Coordinate to `pos` that is one step closer to
/// `start` from initial conditions.
///
/// Useful for finding whole path to a Coordinate returned by `find`.
///
/// Returns `None` for Coordinates that were not yet visited.
/// Returns `start` for `start` (from initial conditions)
pub fn backtrace(&self, pos : Coordinate<I>) -> Option<Coordinate<I>> {
self.visited.get(&pos).map(|entry| entry.prev)
}
/// Perform a recursive `backtrace` walk to find a neighbor of `start` that leads to the
/// Coordinate returned by `find()`.
///
/// Returns `None` for Coordinates that were not yet visited.
/// Returns `start` for `start` (from initial conditions)
pub fn backtrace_last(&self, mut pos : Coordinate<I>) -> Option<Coordinate<I>> {
loop {
pos = match self.visited.get(&pos) {
None => return None,
Some(entry) => {
if entry.prev == self.start {
return Some(pos);
} else {
entry.prev
}
}
}
}
}
}
}
/// Very tricky, but (hopefully) good enough, recursive LoS algorithm
pub mod los {
use hex2d;
use hex2d::Angle::{Left,Right};
use hex2d::Direction;
use hex2d::Coordinate;
fn los_rec<FOpaqueness, FVisible, I>(
opaqueness : &FOpaqueness,
visible : &mut FVisible,
light: I,
pos : Coordinate<I>,
start_dir : Direction,
main_dir : Direction,
dir : Option<Direction>,
pdir : Option<Direction>,
) where
I : hex2d::Integer,
FOpaqueness : Fn(Coordinate<I>) -> I,
FVisible : FnMut(Coordinate<I>, I)
{
let mut light = light;
let opaq = opaqueness(pos);
if opaq >= light {
return;
} else {
light = light - opaq;
}
visible(pos, light);
let neighbors = match (dir, pdir) {
(Some(dir), Some(pdir)) => {
if dir == pdir {
vec!(dir)
} else {
vec!(dir, pdir)
}
},
(Some(dir), None) => {
if main_dir == dir {
vec!(dir, dir + Left, dir + Right)
} else {
vec!(dir, main_dir)
}
},
_ => {
vec!(main_dir, main_dir + Left, main_dir + Right)
}
};
for &d in neighbors.iter() {
let npos = pos + d;
match dir {
Some(_) => los_rec::<FOpaqueness, FVisible, I>(opaqueness, visible, light, npos, start_dir, d, Some(d), dir),
None => los_rec::<FOpaqueness, FVisible, I>(opaqueness, visible, light, npos, start_dir, main_dir, Some(d), dir),
}
}
}
/// Starting from `pos` in direction `dir`, call `visible` for each visible Coordinate.
///
/// Use `light` as starting range of the LoS. For each visible Coordinate, the value returned
/// by `opaqueness` will be subtracted from `light` to check if the LoS should finish due to
/// "lack of visibility". `opaqueness` should typically return 1 for fully transparent
/// Coordinates, and anything bigger than initial `light` for fully opaque Coordinates.
pub fn los<FOpaqueness, FVisible, I>(
opaqueness : &FOpaqueness,
visible : &mut FVisible,
light: I,
pos : Coordinate<I>,
dirs : &[Direction],
) where
I : hex2d::Integer,
FOpaqueness : Fn(Coordinate<I>) -> I,
FVisible : FnMut(Coordinate<I>, I)
{
for dir in dirs.iter() {
los_rec::<FOpaqueness, FVisible, I>(opaqueness, visible, light, pos, *dir, *dir, None, None);
}
}
}
/// Combination of tricky Los with straight line checking
pub mod los2 {
use hex2d;
use hex2d::Angle::{Left, Right, Forward};
use hex2d::Direction;
use hex2d::Coordinate;
use num::{FromPrimitive};
use std::collections::HashSet;
use std::hash;
use std::ops::{Add};
use std::cmp;
fn los_check_line<FOpaqueness, I>(
opaqueness : &FOpaqueness,
light: I,
start : Coordinate<I>,
pos : Coordinate<I>,
) -> (bool, I)
where
I : hex2d::Integer,
I : hash::Hash+Eq,
for <'a> &'a I: Add<&'a I, Output = I>,
FOpaqueness : Fn(Coordinate<I>) -> I,
{
let mut opaq_sum1 : I = FromPrimitive::from_i8(0).unwrap();
let mut last1 = start;
let mut opaq_sum2 : I = FromPrimitive::from_i8(0).unwrap();
let mut last2 = start;
for &(c1, c2) in start.line_to_with_edge_detection(pos).iter() {
if opaq_sum1 < light {
let opaq1 = opaqueness(c1);
opaq_sum1 = opaq_sum1 + opaq1;
last1 = c1;
}
if opaq_sum2 < light {
let opaq2 = opaqueness(c2);
opaq_sum2 = opaq_sum2 + opaq2;
last2 = c2;
}
};
match (last1 == pos, last2 == pos) {
(true, true) => (true, light - cmp::min(opaq_sum1, opaq_sum2)),
(true, false) => (true, light - opaq_sum1),
(false, true) => (true, light - opaq_sum2),
(false, false) => (false, light - light),
}
}
fn los_rec<FOpaqueness, FVisible, I>(
opaqueness : &FOpaqueness,
visible : &mut FVisible,
light: I,
start : Coordinate<I>,
pos : Coordinate<I>,
dir : Direction,
visited : &mut HashSet<Coordinate<I>>,
) where
I : hex2d::Integer,
I : hash::Hash+Eq,
for <'a> &'a I: Add<&'a I, Output = I>,
FOpaqueness : Fn(Coordinate<I>) -> I,
FVisible : FnMut(Coordinate<I>, I)
{
if visited.contains(&pos) {
return;
} else {
visited.insert(pos);
}
let (directly_visible, v_light) = los_check_line(
opaqueness,
light,
start,
pos);
if directly_visible {
visible(pos, v_light);
} else {
let dir_to = start.direction_to_cw(pos).unwrap_or(dir);
let neighbors = vec!(Left, Right);
for npos in neighbors.iter()
.map(|&rd| dir_to + rd)
.map(|dir| pos + dir) {
let (side_visible, v_light) = los_check_line(
opaqueness,
light,
start,
npos,);
if side_visible {
visible(pos, v_light);
}
}
return;
}
let neighbors = vec!(Forward, Left, Right);
for &a in neighbors.iter() {
let npos = pos + (dir + a);
los_rec::<FOpaqueness, FVisible, I>(
opaqueness, visible, light, start, npos, dir, visited
);
}
}
/// Starting from `pos` in direction `dir`, call `visible` for each visible Coordinate.
///
/// Use `light` as starting range of the LoS. For each visible Coordinate, the value returned
/// by `opaqueness` will be subtracted from `light` to check if the LoS should finish due to
/// "lack of visibility". `opaqueness` should typically return 1 for fully transparent
/// Coordinates, and anything bigger than initial `light` for fully opaque Coordinates.
pub fn los<FOpaqueness, FVisible, I>(
opaqueness : &FOpaqueness,
visible : &mut FVisible,
light: I,
pos : Coordinate<I>,
dirs : &[Direction],
) where
I : hex2d::Integer,
I : hash::Hash,
for <'a> &'a I: Add<&'a I, Output = I>,
FOpaqueness : Fn(Coordinate<I>) -> I,
FVisible : FnMut(Coordinate<I>, I)
{
for dir in dirs.iter() {
let mut visited = HashSet::new();
los_rec::<FOpaqueness, FVisible, I>(
opaqueness, visible, light, pos, pos, *dir, &mut visited
);
}
}
}