forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
pathfinding.cpp
550 lines (478 loc) · 20.6 KB
/
pathfinding.cpp
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
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
#include "pathfinding.h"
#include <cstdlib>
#include <algorithm>
#include <optional>
#include <queue>
#include <set>
#include <array>
#include <memory>
#include <utility>
#include <vector>
#include "cata_utility.h"
#include "coordinates.h"
#include "debug.h"
#include "map.h"
#include "mapdata.h"
#include "submap.h"
#include "trap.h"
#include "veh_type.h"
#include "vehicle.h"
#include "vpart_position.h"
#include "line.h"
#include "type_id.h"
#include "point.h"
enum astar_state {
ASL_NONE,
ASL_OPEN,
ASL_CLOSED
};
// Turns two indexed to a 2D array into an index to equivalent 1D array
constexpr int flat_index( const tripoint &p )
{
return ( p.x * MAPSIZE_Y ) + p.y;
}
// Flattened 2D array representing a single z-level worth of pathfinding data
struct path_data_layer {
// State is accessed way more often than all other values here
std::array< astar_state, MAPSIZE_X *MAPSIZE_Y > state;
std::array< int, MAPSIZE_X *MAPSIZE_Y > score;
std::array< int, MAPSIZE_X *MAPSIZE_Y > gscore;
std::array< tripoint, MAPSIZE_X *MAPSIZE_Y > parent;
void init( point min, point max ) {
tripoint p;
for( p.x = min.x; p.x <= max.x; p.x++ ) {
for( p.y = min.y; p.y <= max.y; p.y++ ) {
const int ind = flat_index( p );
state[ind] = ASL_NONE; // Mark as unvisited
}
}
}
};
struct pathfinder {
point min;
point max;
pathfinder( point _min, point _max ) :
min( _min ), max( _max ) {
}
std::priority_queue< std::pair<int, tripoint>, std::vector< std::pair<int, tripoint> >, pair_greater_cmp_first >
open;
std::array< std::unique_ptr< path_data_layer >, OVERMAP_LAYERS > path_data;
path_data_layer &get_layer( const int z ) {
std::unique_ptr< path_data_layer > &ptr = path_data[z + OVERMAP_DEPTH];
if( ptr != nullptr ) {
return *ptr;
}
ptr = std::make_unique<path_data_layer>();
ptr->init( min, max );
return *ptr;
}
bool empty() const {
return open.empty();
}
tripoint get_next() {
const auto pt = open.top();
open.pop();
return pt.second;
}
void add_point( const int gscore, const int score, const tripoint &from, const tripoint &to ) {
auto &layer = get_layer( to.z );
const int index = flat_index( to );
if( ( layer.state[index] == ASL_OPEN && gscore >= layer.gscore[index] ) ||
layer.state[index] == ASL_CLOSED ) {
return;
}
layer.state [index] = ASL_OPEN;
layer.gscore[index] = gscore;
layer.parent[index] = from;
layer.score [index] = score;
open.push( std::make_pair( score, to ) );
}
void close_point( const tripoint &p ) {
auto &layer = get_layer( p.z );
const int index = flat_index( p );
layer.state[index] = ASL_CLOSED;
}
void unclose_point( const tripoint &p ) {
auto &layer = get_layer( p.z );
const int index = flat_index( p );
layer.state[index] = ASL_NONE;
}
};
// Modifies `t` to be a tile with `flag` in the overmap tile that `t` was originally on
// return false if it could not find a suitable point
template<ter_bitflags flag>
bool vertical_move_destination( const map &m, tripoint &t )
{
if( !m.has_zlevels() ) {
return false;
}
real_coords rc( m.getabs( t.xy() ) );
// Align to OMT boundaries
point start = m.getlocal( rc.begin_om_pos() );
point end = start + point( SEEX * 2, SEEY * 2 );
// Exclude submaps not loaded into bubble
if( start.x < 0 ) {
start.x = 0;
}
if( start.y < 0 ) {
start.y = 0;
}
if( end.x >= MAPSIZE_X ) {
end.x = MAPSIZE_X - 1;
}
if( end.y >= MAPSIZE_Y ) {
end.y = MAPSIZE_Y - 1;
}
const auto &pf_cache = m.get_pathfinding_cache_ref( t.z );
for( int x = start.x; x < end.x; x++ ) {
for( int y = start.y; y < end.y; y++ ) {
if( pf_cache.special[x][y] & PF_UPDOWN ) {
const tripoint p( x, y, t.z );
if( m.has_flag( flag, p ) ) {
t = p;
return true;
}
}
}
}
return false;
}
template<class Set1, class Set2>
bool is_disjoint( const Set1 &set1, const Set2 &set2 )
{
if( set1.empty() || set2.empty() ) {
return true;
}
typename Set1::const_iterator it1 = set1.begin();
typename Set1::const_iterator it1_end = set1.end();
typename Set2::const_iterator it2 = set2.begin();
typename Set2::const_iterator it2_end = set2.end();
if( *set2.rbegin() < *it1 || *set1.rbegin() < *it2 ) {
return true;
}
while( it1 != it1_end && it2 != it2_end ) {
if( *it1 == *it2 ) {
return false;
}
if( *it1 < *it2 ) {
it1++;
} else {
it2++;
}
}
return true;
}
std::vector<tripoint> map::route( const tripoint &f, const tripoint &t,
const pathfinding_settings &settings,
const std::set<tripoint> &pre_closed ) const
{
/* TODO: If the origin or destination is out of bound, figure out the closest
* in-bounds point and go to that, then to the real origin/destination.
*/
std::vector<tripoint> ret;
if( f == t || !inbounds( f ) ) {
return ret;
}
if( !inbounds( t ) ) {
tripoint clipped = t;
clip_to_bounds( clipped );
return route( f, clipped, settings, pre_closed );
}
// First, check for a simple straight line on flat ground
// Except when the line contains a pre-closed tile - we need to do regular pathing then
static const auto non_normal = PF_SLOW | PF_WALL | PF_VEHICLE | PF_TRAP | PF_SHARP;
if( f.z == t.z ) {
const auto line_path = line_to( f, t );
const auto &pf_cache = get_pathfinding_cache_ref( f.z );
// Check all points for any special case (including just hard terrain)
if( !( pf_cache.special[f.x][f.y] & non_normal ) &&
std::all_of( line_path.begin(), line_path.end(), [&pf_cache]( const tripoint & p ) {
return !( pf_cache.special[p.x][p.y] & non_normal );
} ) ) {
const std::set<tripoint> sorted_line( line_path.begin(), line_path.end() );
if( is_disjoint( sorted_line, pre_closed ) ) {
return line_path;
}
}
}
// If expected path length is greater than max distance, allow only line path, like above
if( rl_dist( f, t ) > settings.max_dist ) {
return ret;
}
int max_length = settings.max_length;
int bash = settings.bash_strength;
int climb_cost = settings.climb_cost;
bool doors = settings.allow_open_doors;
bool trapavoid = settings.avoid_traps;
bool roughavoid = settings.avoid_rough_terrain;
bool sharpavoid = settings.avoid_sharp;
const int pad = 16; // Should be much bigger - low value makes pathfinders dumb!
int minx = std::min( f.x, t.x ) - pad;
int miny = std::min( f.y, t.y ) - pad;
// TODO: Make this way bigger
int minz = std::min( f.z, t.z );
int maxx = std::max( f.x, t.x ) + pad;
int maxy = std::max( f.y, t.y ) + pad;
// Same TODO: as above
int maxz = std::max( f.z, t.z );
clip_to_bounds( minx, miny, minz );
clip_to_bounds( maxx, maxy, maxz );
pathfinder pf( point( minx, miny ), point( maxx, maxy ) );
// Make NPCs not want to path through player
// But don't make player pathing stop working
for( const auto &p : pre_closed ) {
if( p.x >= minx && p.x < maxx && p.y >= miny && p.y < maxy ) {
pf.close_point( p );
}
}
// Start and end must not be closed
pf.unclose_point( f );
pf.unclose_point( t );
pf.add_point( 0, 0, f, f );
bool done = false;
do {
auto cur = pf.get_next();
const int parent_index = flat_index( cur );
auto &layer = pf.get_layer( cur.z );
auto &cur_state = layer.state[parent_index];
if( cur_state == ASL_CLOSED ) {
continue;
}
if( layer.gscore[parent_index] > max_length ) {
// Shortest path would be too long, return empty vector
return std::vector<tripoint>();
}
if( cur == t ) {
done = true;
break;
}
cur_state = ASL_CLOSED;
const auto &pf_cache = get_pathfinding_cache_ref( cur.z );
const auto cur_special = pf_cache.special[cur.x][cur.y];
int cur_part;
const vehicle *cur_veh = veh_at_internal( cur, cur_part );
// 7 3 5
// 1 . 2
// 6 4 8
constexpr std::array<int, 8> x_offset{{ -1, 1, 0, 0, 1, -1, -1, 1 }};
constexpr std::array<int, 8> y_offset{{ 0, 0, -1, 1, -1, 1, -1, 1 }};
for( size_t i = 0; i < 8; i++ ) {
const tripoint p( cur.x + x_offset[i], cur.y + y_offset[i], cur.z );
const int index = flat_index( p );
// TODO: Remove this and instead have sentinels at the edges
if( p.x < minx || p.x >= maxx || p.y < miny || p.y >= maxy ) {
continue;
}
if( layer.state[index] == ASL_CLOSED ) {
continue;
}
int part = -1;
const vehicle *veh = veh_at_internal( p, part );
if( cur_veh &&
!cur_veh->allowed_move( cur_veh->tripoint_to_mount( cur ), cur_veh->tripoint_to_mount( p ) ) ) {
//Trying to squeeze through a vehicle hole, skip this movement but don't close the tile as other paths may lead to it
continue;
}
if( veh && veh != cur_veh &&
!veh->allowed_move( veh->tripoint_to_mount( cur ), veh->tripoint_to_mount( p ) ) ) {
//Same as above but moving into rather than out of a vehicle
continue;
}
// Penalize for diagonals or the path will look "unnatural"
int newg = layer.gscore[parent_index] + ( ( cur.x != p.x && cur.y != p.y ) ? 1 : 0 );
const auto p_special = pf_cache.special[p.x][p.y];
// TODO: De-uglify, de-huge-n
if( !( p_special & non_normal ) ) {
// Boring flat dirt - the most common case above the ground
newg += 2;
} else {
if( roughavoid ) {
layer.state[index] = ASL_CLOSED; // Close all rough terrain tiles
continue;
}
const maptile &tile = maptile_at_internal( p );
const auto &terrain = tile.get_ter_t();
const auto &furniture = tile.get_furn_t();
const int cost = move_cost_internal( furniture, terrain, veh, part );
// Don't calculate bash rating unless we intend to actually use it
const int rating = ( bash == 0 || cost != 0 ) ? -1 :
bash_rating_internal( bash, furniture, terrain, false, veh, part );
if( cost == 0 && rating <= 0 && ( !doors || !terrain.open || !furniture.open ) && veh == nullptr &&
climb_cost <= 0 ) {
layer.state[index] = ASL_CLOSED; // Close it so that next time we won't try to calculate costs
continue;
}
newg += cost;
if( cost == 0 ) {
if( climb_cost > 0 && p_special & PF_CLIMBABLE ) {
// Climbing fences
newg += climb_cost;
} else if( doors && ( terrain.open || furniture.open ) &&
( !terrain.has_flag( "OPENCLOSE_INSIDE" ) || !furniture.has_flag( "OPENCLOSE_INSIDE" ) ||
!is_outside( cur ) ) ) {
// Only try to open INSIDE doors from the inside
// To open and then move onto the tile
newg += 4;
} else if( veh != nullptr ) {
const auto vpobst = vpart_position( const_cast<vehicle &>( *veh ), part ).obstacle_at_part();
part = vpobst ? vpobst->part_index() : -1;
int dummy = -1;
if( doors && veh->part_flag( part, VPFLAG_OPENABLE ) &&
( !veh->part_flag( part, "OPENCLOSE_INSIDE" ) ||
veh_at_internal( cur, dummy ) == veh ) ) {
// Handle car doors, but don't try to path through curtains
newg += 10; // One turn to open, 4 to move there
} else if( part >= 0 && bash > 0 ) {
// Car obstacle that isn't a door
// TODO: Account for armor
int hp = veh->cpart( part ).hp();
if( hp / 20 > bash ) {
// Threshold damage thing means we just can't bash this down
layer.state[index] = ASL_CLOSED;
continue;
} else if( hp / 10 > bash ) {
// Threshold damage thing means we will fail to deal damage pretty often
hp *= 2;
}
newg += 2 * hp / bash + 8 + 4;
} else if( part >= 0 ) {
if( !doors || !veh->part_flag( part, VPFLAG_OPENABLE ) ) {
// Won't be openable, don't try from other sides
layer.state[index] = ASL_CLOSED;
}
continue;
}
} else if( rating > 1 ) {
// Expected number of turns to bash it down, 1 turn to move there
// and 5 turns of penalty not to trash everything just because we can
newg += ( 20 / rating ) + 2 + 10;
} else if( rating == 1 ) {
// Desperate measures, avoid whenever possible
newg += 500;
} else {
// Unbashable and unopenable from here
if( !doors || !terrain.open || !furniture.open ) {
// Or anywhere else for that matter
layer.state[index] = ASL_CLOSED;
}
continue;
}
}
if( trapavoid && p_special & PF_TRAP ) {
const auto &ter_trp = terrain.trap.obj();
const auto &trp = ter_trp.is_benign() ? tile.get_trap_t() : ter_trp;
if( !trp.is_benign() ) {
// For now make them detect all traps
if( has_zlevels() && terrain.has_flag( TFLAG_NO_FLOOR ) ) {
// Special case - ledge in z-levels
// Warning: really expensive, needs a cache
if( valid_move( p, tripoint( p.xy(), p.z - 1 ), false, true ) ) {
tripoint below( p.xy(), p.z - 1 );
if( !has_flag( TFLAG_NO_FLOOR, below ) ) {
// Otherwise this would have been a huge fall
auto &layer = pf.get_layer( p.z - 1 );
// From cur, not p, because we won't be walking on air
pf.add_point( layer.gscore[parent_index] + 10,
layer.score[parent_index] + 10 + 2 * rl_dist( below, t ),
cur, below );
}
// Close p, because we won't be walking on it
layer.state[index] = ASL_CLOSED;
continue;
}
} else if( trapavoid ) {
// Otherwise it's walkable
newg += 500;
}
}
}
if( sharpavoid && p_special & PF_SHARP ) {
layer.state[index] = ASL_CLOSED; // Avoid sharp things
}
}
// If not visited, add as open
// If visited, add it only if we can do so with better score
if( layer.state[index] == ASL_NONE || newg < layer.gscore[index] ) {
pf.add_point( newg, newg + 2 * rl_dist( p, t ), cur, p );
}
}
if( !has_zlevels() || !( cur_special & PF_UPDOWN ) || !settings.allow_climb_stairs ) {
// The part below is only for z-level pathing
continue;
}
const maptile &parent_tile = maptile_at_internal( cur );
const auto &parent_terrain = parent_tile.get_ter_t();
if( settings.allow_climb_stairs && cur.z > minz && parent_terrain.has_flag( TFLAG_GOES_DOWN ) ) {
tripoint dest( cur.xy(), cur.z - 1 );
if( vertical_move_destination<TFLAG_GOES_UP>( *this, dest ) ) {
auto &layer = pf.get_layer( dest.z );
pf.add_point( layer.gscore[parent_index] + 2,
layer.score[parent_index] + 2 * rl_dist( dest, t ),
cur, dest );
}
}
if( settings.allow_climb_stairs && cur.z < maxz && parent_terrain.has_flag( TFLAG_GOES_UP ) ) {
tripoint dest( cur.xy(), cur.z + 1 );
if( vertical_move_destination<TFLAG_GOES_DOWN>( *this, dest ) ) {
auto &layer = pf.get_layer( dest.z );
pf.add_point( layer.gscore[parent_index] + 2,
layer.score[parent_index] + 2 * rl_dist( dest, t ),
cur, dest );
}
}
if( cur.z < maxz && parent_terrain.has_flag( TFLAG_RAMP ) &&
valid_move( cur, tripoint( cur.xy(), cur.z + 1 ), false, true ) ) {
auto &layer = pf.get_layer( cur.z + 1 );
for( size_t it = 0; it < 8; it++ ) {
const tripoint above( cur.x + x_offset[it], cur.y + y_offset[it], cur.z + 1 );
pf.add_point( layer.gscore[parent_index] + 4,
layer.score[parent_index] + 4 + 2 * rl_dist( above, t ),
cur, above );
}
}
if( cur.z < maxz && parent_terrain.has_flag( TFLAG_RAMP_UP ) &&
valid_move( cur, tripoint( cur.xy(), cur.z + 1 ), false, true, true ) ) {
auto &layer = pf.get_layer( cur.z + 1 );
for( size_t it = 0; it < 8; it++ ) {
const tripoint above( cur.x + x_offset[it], cur.y + y_offset[it], cur.z + 1 );
pf.add_point( layer.gscore[parent_index] + 4,
layer.score[parent_index] + 4 + 2 * rl_dist( above, t ),
cur, above );
}
}
if( cur.z > minz && parent_terrain.has_flag( TFLAG_RAMP_DOWN ) &&
valid_move( cur, tripoint( cur.xy(), cur.z - 1 ), false, true, true ) ) {
auto &layer = pf.get_layer( cur.z - 1 );
for( size_t it = 0; it < 8; it++ ) {
const tripoint below( cur.x + x_offset[it], cur.y + y_offset[it], cur.z - 1 );
pf.add_point( layer.gscore[parent_index] + 4,
layer.score[parent_index] + 4 + 2 * rl_dist( below, t ),
cur, below );
}
}
} while( !done && !pf.empty() );
if( done ) {
ret.reserve( rl_dist( f, t ) * 2 );
tripoint cur = t;
// Just to limit max distance, in case something weird happens
for( int fdist = max_length; fdist != 0; fdist-- ) {
const int cur_index = flat_index( cur );
const auto &layer = pf.get_layer( cur.z );
const tripoint &par = layer.parent[cur_index];
if( cur == f ) {
break;
}
ret.push_back( cur );
// Jumps are acceptable on 1 z-level changes
// This is because stairs teleport the player too
if( rl_dist( cur, par ) > 1 && std::abs( cur.z - par.z ) != 1 ) {
debugmsg( "Jump in our route! %d:%d:%d->%d:%d:%d",
cur.x, cur.y, cur.z, par.x, par.y, par.z );
return ret;
}
cur = par;
}
std::reverse( ret.begin(), ret.end() );
}
return ret;
}