forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
npcmove.cpp
4769 lines (4260 loc) · 165 KB
/
npcmove.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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#include "npc.h" // IWYU pragma: associated
#include <algorithm>
#include <cfloat>
#include <climits>
#include <cmath>
#include <cstdlib>
#include <iterator>
#include <memory>
#include <numeric>
#include <ostream>
#include <tuple>
#include "active_item_cache.h"
#include "activity_handlers.h"
#include "avatar.h"
#include "basecamp.h"
#include "bionics.h"
#include "bodypart.h"
#include "cata_algo.h"
#include "character.h"
#include "character_id.h"
#include "clzones.h"
#include "colony.h"
#include "coordinates.h"
#include "creature.h"
#include "creature_tracker.h"
#include "damage.h"
#include "debug.h"
#include "dialogue_chatbin.h"
#include "dispersion.h"
#include "effect.h"
#include "enums.h"
#include "explosion.h"
#include "field.h"
#include "field_type.h"
#include "flag.h"
#include "flat_set.h"
#include "game.h"
#include "game_constants.h"
#include "gates.h"
#include "gun_mode.h"
#include "item.h"
#include "item_factory.h"
#include "itype.h"
#include "iuse.h"
#include "iuse_actor.h"
#include "line.h"
#include "map.h"
#include "map_iterator.h"
#include "mapdata.h"
#include "material.h"
#include "messages.h"
#include "mission.h"
#include "monster.h"
#include "mtype.h"
#include "npc_attack.h"
#include "npctalk.h"
#include "omdata.h"
#include "options.h"
#include "overmap.h"
#include "overmap_location.h"
#include "overmapbuffer.h"
#include "player_activity.h"
#include "projectile.h"
#include "ranged.h"
#include "ret_val.h"
#include "rng.h"
#include "sounds.h"
#include "stomach.h"
#include "talker.h"
#include "translations.h"
#include "units.h"
#include "value_ptr.h"
#include "veh_type.h"
#include "vehicle.h"
#include "viewer.h"
#include "visitable.h"
#include "vpart_position.h"
#include "vpart_range.h"
static const activity_id ACT_FIRSTAID( "ACT_FIRSTAID" );
static const activity_id ACT_MOVE_LOOT( "ACT_MOVE_LOOT" );
static const activity_id ACT_OPERATION( "ACT_OPERATION" );
static const activity_id ACT_PULP( "ACT_PULP" );
static const activity_id ACT_SPELLCASTING( "ACT_SPELLCASTING" );
static const activity_id ACT_TIDY_UP( "ACT_TIDY_UP" );
static const bionic_id bio_ads( "bio_ads" );
static const bionic_id bio_blade( "bio_blade" );
static const bionic_id bio_chain_lightning( "bio_chain_lightning" );
static const bionic_id bio_claws( "bio_claws" );
static const bionic_id bio_faraday( "bio_faraday" );
static const bionic_id bio_heat_absorb( "bio_heat_absorb" );
static const bionic_id bio_heatsink( "bio_heatsink" );
static const bionic_id bio_hydraulics( "bio_hydraulics" );
static const bionic_id bio_laser( "bio_laser" );
static const bionic_id bio_leukocyte( "bio_leukocyte" );
static const bionic_id bio_nanobots( "bio_nanobots" );
static const bionic_id bio_ods( "bio_ods" );
static const bionic_id bio_painkiller( "bio_painkiller" );
static const bionic_id bio_plutfilter( "bio_plutfilter" );
static const bionic_id bio_radscrubber( "bio_radscrubber" );
static const bionic_id bio_shock( "bio_shock" );
static const bionic_id bio_soporific( "bio_soporific" );
static const efftype_id effect_asthma( "asthma" );
static const efftype_id effect_bandaged( "bandaged" );
static const efftype_id effect_bite( "bite" );
static const efftype_id effect_bleed( "bleed" );
static const efftype_id effect_bouldering( "bouldering" );
static const efftype_id effect_catch_up( "catch_up" );
static const efftype_id effect_disinfected( "disinfected" );
static const efftype_id effect_hallu( "hallu" );
static const efftype_id effect_hit_by_player( "hit_by_player" );
static const efftype_id effect_hypovolemia( "hypovolemia" );
static const efftype_id effect_infected( "infected" );
static const efftype_id effect_lying_down( "lying_down" );
static const efftype_id effect_no_sight( "no_sight" );
static const efftype_id effect_npc_fire_bad( "npc_fire_bad" );
static const efftype_id effect_npc_flee_player( "npc_flee_player" );
static const efftype_id effect_npc_player_still_looking( "npc_player_still_looking" );
static const efftype_id effect_npc_run_away( "npc_run_away" );
static const efftype_id effect_onfire( "onfire" );
static const efftype_id effect_stunned( "stunned" );
static const itype_id itype_inhaler( "inhaler" );
static const itype_id itype_lsd( "lsd" );
static const itype_id itype_oxygen_tank( "oxygen_tank" );
static const itype_id itype_smoxygen_tank( "smoxygen_tank" );
static const itype_id itype_thorazine( "thorazine" );
static const material_id material_alcohol( "alcohol" );
static const material_id material_battery( "battery" );
static const npc_class_id NC_EVAC_SHOPKEEP( "NC_EVAC_SHOPKEEP" );
static const skill_id skill_firstaid( "firstaid" );
static const zone_type_id zone_type_NO_NPC_PICKUP( "NO_NPC_PICKUP" );
static const zone_type_id zone_type_NPC_RETREAT( "NPC_RETREAT" );
static constexpr float NPC_DANGER_VERY_LOW = 5.0f;
static constexpr float NPC_DANGER_MAX = 150.0f;
static constexpr float MAX_FLOAT = 5000000000.0f;
// TODO: These would be much better using common code or constants from character.cpp,
// which handles the player formatting of thirst/hunger levels. Right now we
// have magic numbers all over the place. ;(
static constexpr int NPC_THIRST_CONSUME = 40; // "Thirsty"
static constexpr int NPC_THIRST_COMPLAIN = 80; // "Very thirsty"
static constexpr int NPC_HUNGER_CONSUME = 80; // 50% of what's needed to refuse training.
static constexpr int NPC_HUNGER_COMPLAIN = 160; // The level at which we refuse to do some tasks.
enum npc_action : int {
npc_undecided = 0,
npc_pause,
npc_reload, npc_sleep,
npc_pickup,
npc_heal, npc_use_painkiller, npc_drop_items,
npc_flee, npc_melee, npc_shoot,
npc_look_for_player, npc_heal_player, npc_follow_player, npc_follow_embarked,
npc_talk_to_player, npc_mug_player,
npc_goto_destination,
npc_avoid_friendly_fire,
npc_escape_explosion,
npc_noop,
npc_reach_attack,
npc_do_attack,
npc_aim,
npc_investigate_sound,
npc_return_to_guard_pos,
npc_player_activity,
npc_worker_downtime,
num_npc_actions
};
namespace
{
const std::vector<bionic_id> defense_cbms = { {
bio_ads,
bio_faraday,
bio_heat_absorb,
bio_heatsink,
bio_ods,
bio_shock
}
};
const std::vector<bionic_id> health_cbms = { {
bio_leukocyte,
bio_plutfilter
}
};
// lightning, laser, blade, claws in order of use priority
const std::vector<bionic_id> weapon_cbms = { {
bio_chain_lightning,
bio_laser,
bio_blade,
bio_claws
}
};
const int avoidance_vehicles_radius = 5;
bool good_for_pickup( const item &it, npc &who )
{
bool good = false;
const bool whitelisting = who.has_item_whitelist();
auto weight_allowed = who.weight_capacity() - who.weight_carried();
int min_value = who.minimum_item_value();
item &weap = who.get_wielded_item() ? *who.get_wielded_item() : null_item_reference();
if( ( !it.made_of_from_type( phase_id::LIQUID ) ) &&
( ( !whitelisting && who.value( it ) > min_value ) || who.item_whitelisted( it ) ) &&
( it.weight() <= weight_allowed ) &&
( who.can_stash( it ) ||
who.weapon_value( it ) > who.weapon_value( weap ) ) ) {
good = true;
}
return good;
}
} // namespace
static std::string npc_action_name( npc_action action );
static void print_action( const char *prepend, npc_action action );
static bool compare_sound_alert( const dangerous_sound &sound_a, const dangerous_sound &sound_b );
bool compare_sound_alert( const dangerous_sound &sound_a, const dangerous_sound &sound_b )
{
if( sound_a.type != sound_b.type ) {
return sound_a.type < sound_b.type;
}
return sound_a.volume < sound_b.volume;
}
static bool clear_shot_reach( const tripoint &from, const tripoint &to, bool check_ally = true )
{
std::vector<tripoint> path = line_to( from, to );
path.pop_back();
creature_tracker &creatures = get_creature_tracker();
for( const tripoint &p : path ) {
Creature *inter = creatures.creature_at( p );
if( check_ally && inter != nullptr ) {
return false;
}
if( get_map().impassable( p ) ) {
return false;
}
}
return true;
}
tripoint npc::good_escape_direction( bool include_pos )
{
map &here = get_map();
if( path.empty() ) {
zone_type_id retreat_zone = zone_type_NPC_RETREAT;
const tripoint_abs_ms abs_pos = get_location();
const zone_manager &mgr = zone_manager::get_manager();
cata::optional<tripoint_abs_ms> retreat_target =
mgr.get_nearest( retreat_zone, abs_pos, 60, fac_id );
if( retreat_target && *retreat_target != abs_pos ) {
update_path( here.getlocal( *retreat_target ) );
if( !path.empty() ) {
return path[0];
}
}
}
std::vector<tripoint> candidates;
const auto rate_pt = [&]( const tripoint & pt, const float threat_val ) {
if( !can_move_to( pt, !rules.has_flag( ally_rule::allow_bash ) ) ) {
return MAX_FLOAT;
}
float rating = threat_val;
for( const auto &e : here.field_at( pt ) ) {
if( is_dangerous_field( e.second ) ) {
// TODO: Rate fire higher than smoke
rating += e.second.get_field_intensity();
}
}
return rating;
};
float best_rating = include_pos ? rate_pt( pos(), 0.0f ) : FLT_MAX;
candidates.emplace_back( pos() );
std::map<direction, float> adj_map;
for( direction pt_dir : npc_threat_dir ) {
const tripoint pt = pos() + displace_XY( pt_dir );
float cur_rating = rate_pt( pt, ai_cache.threat_map[ pt_dir ] );
adj_map[pt_dir] = cur_rating;
if( cur_rating == best_rating ) {
candidates.emplace_back( pos() + displace_XY( pt_dir ) );
} else if( cur_rating < best_rating ) {
candidates.clear();
candidates.emplace_back( pos() + displace_XY( pt_dir ) );
best_rating = cur_rating;
}
}
return random_entry( candidates );
}
bool npc::sees_dangerous_field( const tripoint &p ) const
{
return is_dangerous_fields( get_map().field_at( p ) );
}
bool npc::could_move_onto( const tripoint &p ) const
{
map &here = get_map();
if( !here.passable( p ) ) {
return false;
}
if( !sees_dangerous_field( p ) ) {
return true;
}
const field fields_here = here.field_at( pos() );
for( const auto &e : here.field_at( p ) ) {
if( !is_dangerous_field( e.second ) ) {
continue;
}
const auto *entry_here = fields_here.find_field( e.first );
if( entry_here == nullptr || entry_here->get_field_intensity() < e.second.get_field_intensity() ) {
return false;
}
}
return true;
}
std::vector<sphere> npc::find_dangerous_explosives() const
{
std::vector<sphere> result;
const auto active_items = get_map().get_active_items_in_radius( pos(), MAX_VIEW_DISTANCE,
special_item_type::explosive );
for( const item_location &elem : active_items ) {
const use_function *use = elem->type->get_use( "explosion" );
if( !use ) {
continue;
}
const explosion_iuse *actor = dynamic_cast<const explosion_iuse *>( use->get_actor_ptr() );
const int safe_range = actor->explosion.safe_range();
if( rl_dist( pos(), elem.position() ) >= safe_range ) {
continue; // Far enough.
}
const int turns_to_evacuate = 2 * safe_range / speed_rating();
if( elem->charges > turns_to_evacuate ) {
continue; // Consider only imminent dangers.
}
result.emplace_back( elem.position(), safe_range );
}
return result;
}
float npc::evaluate_enemy( const Creature &target ) const
{
if( target.is_monster() ) {
const monster &mon = dynamic_cast<const monster &>( target );
float diff = static_cast<float>( mon.type->difficulty );
return std::min( diff, NPC_DANGER_MAX );
} else if( target.is_npc() || target.is_avatar() ) {
return std::min( character_danger( dynamic_cast<const Character &>( target ) ),
NPC_DANGER_MAX );
} else {
return 0.0f;
}
}
static bool too_close( const tripoint &critter_pos, const tripoint &ally_pos, const int def_radius )
{
return rl_dist( critter_pos, ally_pos ) <= def_radius;
}
cata::optional<int> npc_short_term_cache::closest_enemy_to_friendly_distance() const
{
int distance = INT_MAX;
for( const weak_ptr_fast<Creature> &buddy : friends ) {
if( buddy.expired() ) {
continue;
}
for( const weak_ptr_fast<Creature> &enemy : hostile_guys ) {
if( enemy.expired() ) {
continue;
}
distance = std::min( distance, rl_dist( buddy.lock()->pos(), enemy.lock()->pos() ) );
}
}
if( distance == INT_MAX ) {
return cata::nullopt;
}
return distance;
}
void npc::assess_danger()
{
float assessment = 0.0f;
float highest_priority = 1.0f;
int def_radius = rules.has_flag( ally_rule::follow_close ) ? follow_distance() : 6;
if( !confident_range_cache ) {
invalidate_range_cache();
}
// Radius we can attack without moving
int max_range = *confident_range_cache;
Character &player_character = get_player_character();
const bool self_defense_only = rules.engagement == combat_engagement::NO_MOVE ||
rules.engagement == combat_engagement::NONE;
const bool no_fighting = rules.has_flag( ally_rule::forbid_engage );
const bool must_retreat = rules.has_flag( ally_rule::follow_close ) &&
!too_close( pos(), player_character.pos(), follow_distance() ) &&
!is_guarding();
if( is_player_ally() ) {
if( rules.engagement == combat_engagement::FREE_FIRE ) {
def_radius = std::max( 6, max_range );
} else if( self_defense_only ) {
def_radius = max_range;
} else if( no_fighting ) {
def_radius = 1;
}
}
const auto ok_by_rules = [max_range, def_radius, this, &player_character]( const Creature & c,
int dist, int scaled_dist ) {
// If we're forbidden to attack, no need to check engagement rules
if( rules.has_flag( ally_rule::forbid_engage ) ) {
return false;
}
switch( rules.engagement ) {
case combat_engagement::NONE:
return false;
case combat_engagement::CLOSE:
// Either close to player or close enough that we can reach it and close to us
return ( dist <= max_range && scaled_dist <= def_radius * 0.5 ) ||
too_close( c.pos(), player_character.pos(), def_radius );
case combat_engagement::WEAK:
return c.get_hp() <= average_damage_dealt();
case combat_engagement::HIT:
return c.has_effect( effect_hit_by_player );
case combat_engagement::NO_MOVE:
case combat_engagement::FREE_FIRE:
return dist <= max_range;
case combat_engagement::ALL:
return true;
}
return true;
};
std::map<direction, float> cur_threat_map;
// start with a decayed version of last turn's map
for( direction threat_dir : npc_threat_dir ) {
cur_threat_map[ threat_dir ] = 0.25f * ai_cache.threat_map[ threat_dir ];
}
map &here = get_map();
// cache string_id -> int_id conversion before hot loop
const field_type_id fd_fire = ::fd_fire;
// first, check if we're about to be consumed by fire
// `map::get_field` uses `field_cache`, so in general case (no fire) it provides an early exit
for( const tripoint &pt : here.points_in_radius( pos(), 6 ) ) {
if( pt == pos() || !here.get_field( pt, fd_fire ) ||
here.has_flag( ter_furn_flag::TFLAG_FIRE_CONTAINER, pt ) ) {
continue;
}
int dist = rl_dist( pos(), pt );
cur_threat_map[direction_from( pos(), pt )] += 2.0f * ( NPC_DANGER_MAX - dist );
if( dist < 3 && !has_effect( effect_npc_fire_bad ) ) {
warn_about( "fire_bad", 1_minutes );
add_effect( effect_npc_fire_bad, 5_turns );
path.clear();
}
}
// find our Character friends and enemies
const bool clairvoyant = clairvoyance();
for( const npc &guy : g->all_npcs() ) {
if( &guy == this ) {
continue;
}
if( !clairvoyant && !here.has_potential_los( pos(), guy.pos() ) ) {
continue;
}
if( has_faction_relationship( guy, npc_factions::watch_your_back ) ) {
ai_cache.friends.emplace_back( g->shared_from( guy ) );
} else if( attitude_to( guy ) != Attitude::NEUTRAL && sees( guy.pos() ) ) {
ai_cache.hostile_guys.emplace_back( g->shared_from( guy ) );
}
}
if( sees( player_character.pos() ) ) {
if( is_enemy() ) {
ai_cache.hostile_guys.emplace_back( g->shared_from( player_character ) );
} else if( is_friendly( player_character ) ) {
ai_cache.friends.emplace_back( g->shared_from( player_character ) );
}
}
for( const monster &critter : g->all_monsters() ) {
if( !clairvoyant && !here.has_potential_los( pos(), critter.pos() ) ) {
continue;
}
Creature::Attitude att = critter.attitude_to( *this );
if( att == Attitude::FRIENDLY ) {
ai_cache.friends.emplace_back( g->shared_from( critter ) );
continue;
}
if( att != Attitude::HOSTILE && ( critter.friendly || !is_enemy() ) ) {
ai_cache.neutral_guys.emplace_back( g->shared_from( critter ) );
continue;
}
if( !sees( critter ) ) {
continue;
}
ai_cache.hostile_guys.emplace_back( g->shared_from( critter ) );
float critter_threat = evaluate_enemy( critter );
// warn and consider the odds for distant enemies
int dist = rl_dist( pos(), critter.pos() );
if( is_enemy() || !critter.friendly ) {
assessment += critter_threat;
if( critter_threat > ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
warn_about( "monster", 10_minutes, critter.type->nname(), dist, critter.pos() );
}
}
if( must_retreat || no_fighting ) {
continue;
}
// ignore targets behind glass even if we can see them
if( !clear_shot_reach( pos(), critter.pos(), false ) ) {
continue;
}
float scaled_distance = std::max( 1.0f, dist / critter.speed_rating() );
float hp_percent = 1.0f - static_cast<float>( critter.get_hp() ) / critter.get_hp_max();
float critter_danger = std::max( critter_threat * ( hp_percent * 0.5f + 0.5f ),
NPC_DANGER_VERY_LOW );
ai_cache.total_danger += critter_danger / scaled_distance;
// don't ignore monsters that are too close or too close to an ally if we can move
bool is_too_close = dist <= def_radius;
for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
if( is_too_close || self_defense_only ) {
break;
}
// HACK: Bit of a dirty hack - sometimes shared_from, returns nullptr or bad weak_ptr for
// friendly NPC when the NPC is riding a creature - I don't know why.
// so this skips the bad weak_ptrs, but this doesn't functionally change the AI Priority
// because the horse the NPC is riding is still in the ai_cache.friends vector,
// so either one would count as a friendly for this purpose.
if( guy.lock() ) {
is_too_close |= too_close( critter.pos(), guy.lock()->pos(), def_radius );
}
}
// ignore distant monsters that our rules prevent us from attacking
if( !is_too_close && is_player_ally() && !ok_by_rules( critter, dist, scaled_distance ) ) {
continue;
}
// prioritize the biggest, nearest threats, or the biggest threats that are threatening
// us or an ally
// critter danger is always at least NPC_DANGER_VERY_LOW
float priority = std::max( critter_danger - 2.0f * ( scaled_distance - 1.0f ),
is_too_close ? critter_danger : 0.0f );
cur_threat_map[direction_from( pos(), critter.pos() )] += priority;
if( priority > highest_priority ) {
highest_priority = priority;
ai_cache.target = g->shared_from( critter );
ai_cache.danger = critter_danger;
}
}
if( assessment == 0.0 && ai_cache.hostile_guys.empty() ) {
ai_cache.danger_assessment = assessment;
return;
}
const auto handle_hostile = [&]( const Character & foe, float foe_threat,
const std::string & bogey, const std::string & warning ) {
int dist = rl_dist( pos(), foe.pos() );
if( foe_threat > ( 8.0f + personality.bravery + rng( 0, 5 ) ) ) {
warn_about( "monster", 10_minutes, bogey, dist, foe.pos() );
}
int scaled_distance = std::max( 1, ( 100 * dist ) / foe.get_speed() );
ai_cache.total_danger += foe_threat / scaled_distance;
if( must_retreat || no_fighting ) {
return 0.0f;
}
// ignore targets behind glass even if we can see them
if( !clear_shot_reach( pos(), foe.pos(), false ) ) {
return 0.0f;
}
bool is_too_close = dist <= def_radius;
for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
if( self_defense_only ) {
break;
}
is_too_close |= too_close( foe.pos(), guy.lock()->pos(), def_radius );
if( is_too_close ) {
break;
}
}
if( !is_player_ally() || is_too_close || ok_by_rules( foe, dist, scaled_distance ) ) {
float priority = std::max( foe_threat - 2.0f * ( scaled_distance - 1 ),
is_too_close ? std::max( foe_threat, NPC_DANGER_VERY_LOW ) :
0.0f );
cur_threat_map[direction_from( pos(), foe.pos() )] += priority;
if( priority > highest_priority ) {
warn_about( warning, 1_minutes );
highest_priority = priority;
ai_cache.danger = foe_threat;
ai_cache.target = g->shared_from( foe );
}
}
return foe_threat;
};
for( const weak_ptr_fast<Creature> &guy : ai_cache.hostile_guys ) {
Character *foe = dynamic_cast<Character *>( guy.lock().get() );
if( foe && foe->is_npc() ) {
assessment += handle_hostile( *foe, evaluate_enemy( *foe ), translate_marker( "bandit" ),
"kill_npc" );
}
}
for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
if( !( guy.lock() && guy.lock()->is_npc() ) ) {
continue;
}
float guy_threat = evaluate_enemy( *guy.lock() );
float min_danger = assessment >= NPC_DANGER_VERY_LOW ? NPC_DANGER_VERY_LOW : -10.0f;
assessment = std::max( min_danger, assessment - guy_threat * 0.5f );
}
if( sees( player_character.pos() ) ) {
// Mod for the player
// cap player difficulty at 150
float player_diff = evaluate_enemy( player_character );
if( is_enemy() ) {
assessment += handle_hostile( player_character, player_diff, translate_marker( "maniac" ),
"kill_player" );
} else if( is_friendly( player_character ) ) {
float min_danger = assessment >= NPC_DANGER_VERY_LOW ? NPC_DANGER_VERY_LOW : -10.0f;
assessment = std::max( min_danger, assessment - player_diff * 0.5f );
ai_cache.friends.emplace_back( g->shared_from( player_character ) );
}
}
assessment *= 0.1f;
if( !has_effect( effect_npc_run_away ) && !has_effect( effect_npc_fire_bad ) ) {
float my_diff = evaluate_enemy( *this );
if( ( my_diff * 0.5f + personality.bravery + rng( 0, 10 ) ) < assessment ) {
time_duration run_away_for = 5_turns + 1_turns * rng( 0, 5 );
warn_about( "run_away", run_away_for );
add_effect( effect_npc_run_away, run_away_for );
path.clear();
}
}
// update the threat cache
for( size_t i = 0; i < 8; i++ ) {
direction threat_dir = npc_threat_dir[i];
direction dir_right = npc_threat_dir[( i + 1 ) % 8];
direction dir_left = npc_threat_dir[( i + 7 ) % 8 ];
ai_cache.threat_map[threat_dir] = cur_threat_map[threat_dir] + 0.1f *
( cur_threat_map[dir_right] + cur_threat_map[dir_left] );
}
if( assessment <= 2.0f ) {
assessment = -10.0f + 5.0f * assessment; // Low danger if no monsters around
}
ai_cache.danger_assessment = assessment;
}
bool npc::is_safe() const
{
return ai_cache.total_danger <= 0;
}
float npc::character_danger( const Character &uc ) const
{
// TODO: Remove this when possible
float ret = 0.0f;
bool u_gun = uc.get_wielded_item() && uc.get_wielded_item()->is_gun();
bool my_gun = get_wielded_item() && get_wielded_item()->is_gun();
const item &u_weap = uc.get_wielded_item() ? *uc.get_wielded_item() : null_item_reference();
double u_weap_val = uc.weapon_value( u_weap );
const double &my_weap_val = ai_cache.my_weapon_value;
if( u_gun && !my_gun ) {
u_weap_val *= 1.5f;
}
ret += u_weap_val;
ret += hp_percentage() * get_hp_max( bodypart_id( "torso" ) ) / 100.0 / my_weap_val;
ret += my_gun ? uc.get_dodge() / 2 : uc.get_dodge();
ret *= std::max( 0.5, uc.get_speed() / 100.0 );
add_msg_debug( debugmode::DF_NPC, "%s danger: %1f", uc.disp_name(), ret );
return ret;
}
void npc::regen_ai_cache()
{
map &here = get_map();
auto i = std::begin( ai_cache.sound_alerts );
creature_tracker &creatures = get_creature_tracker();
while( i != std::end( ai_cache.sound_alerts ) ) {
if( sees( here.getlocal( i->abs_pos ) ) ) {
// if they were responding to a call for guards because of thievery
npc *const sound_source = creatures.creature_at<npc>( here.getlocal( i->abs_pos ) );
if( sound_source ) {
if( my_fac == sound_source->my_fac && sound_source->known_stolen_item ) {
sound_source->known_stolen_item = nullptr;
set_attitude( NPCATT_RECOVER_GOODS );
}
}
i = ai_cache.sound_alerts.erase( i );
if( ai_cache.sound_alerts.size() == 1 ) {
path.clear();
}
} else {
++i;
}
}
float old_assessment = ai_cache.danger_assessment;
ai_cache.friends.clear();
ai_cache.hostile_guys.clear();
ai_cache.neutral_guys.clear();
ai_cache.target = shared_ptr_fast<Creature>();
ai_cache.ally = shared_ptr_fast<Creature>();
ai_cache.can_heal.clear_all();
ai_cache.danger = 0.0f;
ai_cache.total_danger = 0.0f;
item &weapon = get_wielded_item() ? *get_wielded_item() : null_item_reference();
ai_cache.my_weapon_value = weapon_value( weapon );
ai_cache.dangerous_explosives = find_dangerous_explosives();
assess_danger();
if( old_assessment > NPC_DANGER_VERY_LOW && ai_cache.danger_assessment <= 0 ) {
warn_about( "relax", 30_minutes );
} else if( old_assessment <= 0.0f && ai_cache.danger_assessment > NPC_DANGER_VERY_LOW ) {
warn_about( "general_danger" );
}
// Non-allied NPCs with a completed mission should move to the player
if( !is_player_ally() && !is_stationary( true ) ) {
Character &player_character = get_player_character();
for( ::mission *miss : chatbin.missions_assigned ) {
if( miss->is_complete( getID() ) ) {
// unless the player found an item and already told the NPC he wanted to keep it
const mission_goal &mgoal = miss->get_type().goal;
if( ( mgoal == MGOAL_FIND_ITEM || mgoal == MGOAL_FIND_ANY_ITEM ||
mgoal == MGOAL_FIND_ITEM_GROUP ) &&
has_effect( effect_npc_player_still_looking ) ) {
continue;
}
if( global_omt_location() != player_character.global_omt_location() ) {
goal = player_character.global_omt_location();
}
set_attitude( NPCATT_TALK );
break;
}
}
}
}
void npc::move()
{
// don't just return from this function without doing something
// that will eventually subtract moves, or change the NPC to a different type of action.
// because this will result in an infinite loop
if( attitude == NPCATT_FLEE ) {
set_attitude( NPCATT_FLEE_TEMP ); // Only run for so many hours
} else if( attitude == NPCATT_FLEE_TEMP && !has_effect( effect_npc_flee_player ) ) {
set_attitude( NPCATT_NULL );
}
regen_ai_cache();
// NPCs under operation should just stay still
if( activity.id() == ACT_OPERATION || activity.id() == ACT_SPELLCASTING ) {
execute_action( npc_player_activity );
return;
}
npc_action action = npc_undecided;
const item_location weapon = get_wielded_item();
static const std::string no_target_str = "none";
const Creature *target = current_target();
const std::string &target_name = target != nullptr ? target->disp_name() : no_target_str;
if( !confident_range_cache ) {
invalidate_range_cache();
}
add_msg_debug( debugmode::DF_NPC, "NPC %s: target = %s, danger = %.1f, range = %d",
get_name(), target_name, ai_cache.danger, *confident_range_cache );
Character &player_character = get_player_character();
//faction opinion determines if it should consider you hostile
if( !is_enemy() && guaranteed_hostile() && sees( player_character ) ) {
if( is_player_ally() ) {
mutiny();
}
add_msg_debug( debugmode::DF_NPC, "NPC %s turning hostile because is guaranteed_hostile()",
get_name() );
if( op_of_u.fear > 10 + personality.aggression + personality.bravery ) {
set_attitude( NPCATT_FLEE_TEMP ); // We don't want to take u on!
} else {
set_attitude( NPCATT_KILL ); // Yeah, we think we could take you!
}
}
/* This bypasses the logic to determine the npc action, but this all needs to be rewritten
* anyway.
* NPC won't avoid dangerous terrain while accompanying the player inside a vehicle to keep
* them from inadvertently getting themselves run over and/or cause vehicle related errors.
* NPCs flee from uncontained fires within 3 tiles
*/
if( !in_vehicle && ( sees_dangerous_field( pos() ) || has_effect( effect_npc_fire_bad ) ) ) {
if( sees_dangerous_field( pos() ) ) {
path.clear();
}
const tripoint escape_dir = good_escape_direction( sees_dangerous_field( pos() ) );
if( escape_dir != pos() ) {
move_to( escape_dir );
return;
}
}
// TODO: Place player-aiding actions here, with a weight
/* NPCs are fairly suicidal so at this point we will do a quick check to see if
* something nasty is going to happen.
*/
if( is_enemy() && vehicle_danger( avoidance_vehicles_radius ) > 0 ) {
// TODO: Think about how this actually needs to work, for now assume flee from player
ai_cache.target = g->shared_from( player_character );
}
map &here = get_map();
if( !ai_cache.dangerous_explosives.empty() ) {
action = npc_escape_explosion;
} else if( ( target == &player_character && attitude == NPCATT_FLEE_TEMP ) ||
has_effect( effect_npc_run_away ) ) {
action = method_of_fleeing();
} else if( has_effect( effect_asthma ) && ( has_charges( itype_inhaler, 1 ) ||
has_charges( itype_oxygen_tank, 1 ) ||
has_charges( itype_smoxygen_tank, 1 ) ) ) {
action = npc_heal;
} else if( target != nullptr && ai_cache.danger > 0 ) {
action = method_of_attack();
} else if( !ai_cache.sound_alerts.empty() && !is_walking_with() ) {
tripoint cur_s_abs_pos = ai_cache.s_abs_pos;
if( !ai_cache.guard_pos ) {
ai_cache.guard_pos = here.getabs( pos() );
}
if( ai_cache.sound_alerts.size() > 1 ) {
std::sort( ai_cache.sound_alerts.begin(), ai_cache.sound_alerts.end(),
compare_sound_alert );
if( ai_cache.sound_alerts.size() > 10 ) {
ai_cache.sound_alerts.resize( 10 );
}
}
action = npc_investigate_sound;
if( ai_cache.sound_alerts.front().abs_pos != cur_s_abs_pos ) {
ai_cache.stuck = 0;
ai_cache.s_abs_pos = ai_cache.sound_alerts.front().abs_pos;
} else if( ai_cache.stuck > 10 ) {
ai_cache.stuck = 0;
if( ai_cache.sound_alerts.size() == 1 ) {
ai_cache.sound_alerts.clear();
action = npc_return_to_guard_pos;
} else {
ai_cache.s_abs_pos = ai_cache.sound_alerts.at( 1 ).abs_pos;
}
}
if( action == npc_investigate_sound ) {
add_msg_debug( debugmode::DF_NPC, "NPC %s: investigating sound at x(%d) y(%d)", get_name(),
ai_cache.s_abs_pos.x, ai_cache.s_abs_pos.y );
}
} else if( ai_cache.sound_alerts.empty() && ai_cache.guard_pos ) {
tripoint return_guard_pos = *ai_cache.guard_pos;
add_msg_debug( debugmode::DF_NPC, "NPC %s: returning to guard spot at x(%d) y(%d)", get_name(),
return_guard_pos.x, return_guard_pos.y );
action = npc_return_to_guard_pos;
} else {
// No present danger
cleanup_on_no_danger();
action = address_needs();
print_action( "address_needs %s", action );
if( action == npc_undecided ) {
action = address_player();
print_action( "address_player %s", action );
}
}
// check if in vehicle before doing any other follow activities
if( action == npc_undecided && is_walking_with() && player_character.in_vehicle &&
!in_vehicle ) {
action = npc_follow_embarked;
}
if( action == npc_undecided && is_walking_with() && rules.has_flag( ally_rule::follow_close ) &&
rl_dist( pos(), player_character.pos() ) > follow_distance() ) {
action = npc_follow_player;
}
if( action == npc_undecided && attitude == NPCATT_ACTIVITY ) {
if( has_stashed_activity() ) {
if( !check_outbounds_activity( get_stashed_activity(), true ) ) {
assign_stashed_activity();
} else {
// wait a turn, because next turn, the object of our activity
// may have been loaded in.
set_moves( 0 );
}
return;
}
std::vector<tripoint> activity_route = get_auto_move_route();
if( !activity_route.empty() && !has_destination_activity() ) {
tripoint final_destination;
if( destination_point ) {
final_destination = here.getlocal( *destination_point );
} else {
final_destination = activity_route.back();
}
update_path( final_destination );
if( !path.empty() ) {
move_to_next();
return;
}
}
if( has_destination_activity() ) {
start_destination_activity();
action = npc_player_activity;
} else if( has_player_activity() ) {
action = npc_player_activity;
}
}
if( action == npc_undecided ) {
// an interrupted activity can cause this situation. stops allied NPCs zooming off
// like random NPCs
if( attitude == NPCATT_ACTIVITY && !activity ) {
revert_after_activity();
if( is_ally( player_character ) && !assigned_camp ) {
attitude = NPCATT_FOLLOW;
mission = NPC_MISSION_NULL;
}
}
if( assigned_camp && attitude != NPCATT_ACTIVITY ) {
if( has_job() && calendar::once_every( 10_minutes ) && find_job_to_perform() ) {
action = npc_player_activity;
} else {
action = npc_worker_downtime;
goal = global_omt_location();
}
}
if( is_stationary( true ) && !assigned_camp ) {
// if we're in a vehicle, stay in the vehicle
if( in_vehicle ) {
action = npc_pause;
goal = global_omt_location();
} else {
action = goal == global_omt_location() ? npc_pause : npc_goto_destination;
}
} else if( has_new_items && scan_new_items() ) {
return;
} else if( !fetching_item ) {
find_item();
print_action( "find_item %s", action );
} else if( assigned_camp ) {
// this should be covered above, but justincase to stop them zooming away.
action = npc_pause;
}
// check if in vehicle before rushing off to fetch things
if( is_walking_with() && player_character.in_vehicle ) {
action = npc_follow_embarked;
} else if( fetching_item ) {
// Set to true if find_item() found something