forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
npcmove.cpp
4762 lines (4250 loc) · 164 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 "basecamp.h"
#include "bionics.h"
#include "bodypart.h"
#include "cata_algo.h"
#include "character.h"
#include "character_functions.h"
#include "character_turn.h"
#include "character_id.h"
#include "clzones.h"
#include "coordinate_conversions.h"
#include "damage.h"
#include "debug.h"
#include "dispersion.h"
#include "effect.h"
#include "enums.h"
#include "explosion.h"
#include "field.h"
#include "field_type.h"
#include "game.h"
#include "game_constants.h"
#include "gates.h"
#include "gun_mode.h"
#include "item.h"
#include "item_contents.h"
#include "item_functions.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 "messages.h"
#include "mission.h"
#include "monster.h"
#include "mtype.h"
#include "npctalk.h"
#include "options.h"
#include "overmap.h"
#include "overmap_location.h"
#include "overmapbuffer.h"
#include "player_activity.h"
#include "pldata.h"
#include "projectile.h"
#include "ranged.h"
#include "ret_val.h"
#include "rng.h"
#include "sounds.h"
#include "stomach.h"
#include "translations.h"
#include "units.h"
#include "value_ptr.h"
#include "veh_type.h"
#include "vehicle.h"
#include "visitable.h"
#include "vpart_position.h"
#include "vpart_range.h"
static const activity_id ACT_PULP( "ACT_PULP" );
static const skill_id skill_firstaid( "firstaid" );
static const bionic_id bio_ads( "bio_ads" );
static const bionic_id bio_advreactor( "bio_advreactor" );
static const bionic_id bio_faraday( "bio_faraday" );
static const bionic_id bio_furnace( "bio_furnace" );
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_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_reactor( "bio_reactor" );
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_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_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 flag_str_id flag_NO_UNWIELD( "NO_UNWIELD" );
static const itype_id itype_battery( "battery" );
static const itype_id itype_chem_ethanol( "chem_ethanol" );
static const itype_id itype_chem_methanol( "chem_methanol" );
static const itype_id itype_denat_alcohol( "denat_alcohol" );
static const itype_id itype_inhaler( "inhaler" );
static const itype_id itype_lsd( "lsd" );
static const itype_id itype_smoxygen_tank( "smoxygen_tank" );
static const itype_id itype_thorazine( "thorazine" );
static const itype_id itype_oxygen_tank( "oxygen_tank" );
static const itype_id itype_UPS( "UPS" );
static const std::string flag_SPLINT( "SPLINT" );
static constexpr float NPC_DANGER_VERY_LOW = 5.0f;
static constexpr float NPC_DANGER_MAX = 150.0f;
static constexpr float MAX_FLOAT = 5000000000.0f;
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_to_this_pos,
npc_goto_destination,
npc_avoid_friendly_fire,
npc_escape_explosion,
npc_noop,
npc_reach_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> power_cbms = { {
bio_advreactor,
bio_furnace,
bio_reactor,
}
};
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
}
};
const int avoidance_vehicles_radius = 5;
} // namespace
std::string npc_action_name( npc_action action );
void print_action( const char *prepend, npc_action action );
bool compare_sound_alert( const dangerous_sound &sound_a, const dangerous_sound &sound_b );
hp_part most_damaged_hp_part( const Character &c );
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 );
tripoint target_point = path.back();
path.pop_back();
if( path.empty() ) {
return true;
}
tripoint &last_point = path[0];
for( const tripoint &p : path ) {
Creature *inter = g->critter_at( p );
if( check_ally && inter != nullptr ) {
return false;
} else if( get_map().impassable( p ) ) {
return false;
} else if( get_map().obstructed_by_vehicle_rotation( last_point, p ) ) {
return false;
}
last_point = p;
}
return !get_map().obstructed_by_vehicle_rotation( last_point, target_point );
}
tripoint npc::good_escape_direction( bool include_pos )
{
map &here = get_map();
if( path.empty() ) {
zone_type_id retreat_zone = zone_type_id( "NPC_RETREAT" );
const tripoint &abs_pos = global_square_location();
const zone_manager &mgr = zone_manager::get_manager();
std::optional<tripoint> 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() + direction_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() + direction_XY( pt_dir ) );
} else if( cur_rating < best_rating ) {
candidates.clear();
candidates.emplace_back( pos() + direction_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 auto 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 auto &elem : active_items ) {
const auto 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_player() ) {
return std::min( character_danger( dynamic_cast<const player &>( 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;
}
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;
// Radius we can attack without moving
int max_range;
if( confident_range_cache ) {
max_range = *confident_range_cache;
} else {
invalidate_range_cache();
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 = is_walking_with() && rules.has_flag( ally_rule::follow_close ) &&
!too_close( pos(), player_character.pos(), follow_distance() );
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:
return dist <= max_range;
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();
// first, check if we're about to be consumed by fire
// TODO: Use the field cache
for( const tripoint &pt : here.points_in_radius( pos(), 6 ) ) {
if( pt == pos() || here.has_flag( TFLAG_FIRE_CONTAINER, pt ) ) {
continue;
}
if( here.get_field( pt, fd_fire ) != nullptr ) {
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
std::vector<weak_ptr_fast<Creature>> hostile_guys;
for( const npc &guy : g->all_npcs() ) {
if( &guy == this ) {
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 ) != A_NEUTRAL && sees( guy.pos() ) ) {
hostile_guys.emplace_back( g->shared_from( guy ) );
}
}
if( sees( player_character.pos() ) ) {
if( is_enemy() ) {
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() ) {
auto att = critter.attitude_to( *this );
if( att == A_FRIENDLY ) {
ai_cache.friends.emplace_back( g->shared_from( critter ) );
continue;
}
if( att != A_HOSTILE && ( critter.friendly || !is_enemy() ) ) {
continue;
}
if( !sees( critter ) ) {
continue;
}
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 && 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 : hostile_guys ) {
player *foe = dynamic_cast<player *>( guy.lock().get() );
if( foe && foe->is_npc() ) {
assessment += handle_hostile( *foe, evaluate_enemy( *foe ), "bandit", "kill_npc" );
}
}
for( const weak_ptr_fast<Creature> &guy : ai_cache.friends ) {
player *ally = dynamic_cast<player *>( guy.lock().get() );
if( !( ally && ally->is_npc() ) ) {
continue;
}
float guy_threat = evaluate_enemy( *ally );
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, "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;
}
float npc::character_danger( const Character &u ) const
{
float ret = 0.0;
bool u_gun = u.primary_weapon().is_gun();
bool my_gun = primary_weapon().is_gun();
double u_weap_val = npc_ai::wielded_value( u );
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 ? u.get_dodge() / 2 : u.get_dodge();
ret *= std::max( 0.5, u.get_speed() / 100.0 );
add_msg( m_debug, "%s danger: %1f", u.disp_name(), ret );
return ret;
}
void npc::regen_ai_cache()
{
map &here = get_map();
auto i = std::begin( ai_cache.sound_alerts );
while( i != std::end( ai_cache.sound_alerts ) ) {
if( sees( here.getlocal( i->abs_pos ) ) ) {
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.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;
ai_cache.my_weapon_value = npc_ai::wielded_value( *this );
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( auto &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_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();
adjust_power_cbms();
// NPCs under operation should just stay still
if( activity.id() == activity_id( "ACT_OPERATION" ) ) {
execute_action( npc_player_activity );
return;
}
npc_action action = npc_undecided;
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;
add_msg( m_debug, "NPC %s: target = %s, danger = %.1f, range = %d",
name, target_name, ai_cache.danger,
primary_weapon().is_gun() ? confident_shoot_range( primary_weapon(),
ranged::recoil_total( *this ) ) : primary_weapon().reach_range( *this ) );
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( m_debug, "NPC %s turning hostile because is guaranteed_hostile()", 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 ) {
action = method_of_fleeing();
} else if( 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( m_debug, "NPC %s: investigating sound at x(%d) y(%d)", name,
ai_cache.s_abs_pos.x, ai_cache.s_abs_pos.y );
}
} else {
// No present danger
deactivate_combat_cbms();
action = address_needs();
print_action( "address_needs %s", action );
if( action == npc_undecided ) {
action = address_player();
print_action( "address_player %s", action );
}
if( ai_cache.sound_alerts.empty() && ai_cache.guard_pos ) {
tripoint return_guard_pos = *ai_cache.guard_pos;
add_msg( m_debug, "NPC %s: returning to guard spot at x(%d) y(%d)", name,
return_guard_pos.x, return_guard_pos.y );
action = npc_return_to_guard_pos;
}
}
if( action == npc_undecided && is_walking_with() && goto_to_this_pos ) {
action = npc_goto_to_this_pos;
}
// 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 ) ) {
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
action = npc_pickup;
} else if( is_following() ) {
// No items, so follow the player?
action = npc_follow_player;
}
// Friendly NPCs who are followers/ doing tasks for the player should never get here.
// This will revert them to a dynamic NPC state.
if( action == npc_undecided ) {
// Do our long-term action
action = long_term_goal_action();
print_action( "long_term_goal_action %s", action );
}
}
/* Sometimes we'll be following the player at this point, but close enough that
* "following" means standing still. If that's the case, if there are any
* monsters around, we should attack them after all!
*
* If we are following a embarked player and we are in a vehicle then shoot anyway
* as we are most likely riding shotgun
*/
if( ai_cache.danger > 0 && target != nullptr &&
(
( action == npc_follow_embarked && in_vehicle ) ||
( action == npc_follow_player &&
( rl_dist( pos(), player_character.pos() ) <= follow_distance() ||
posz() != player_character.posz() ) )
) ) {
action = method_of_attack();
}
add_msg( m_debug, "%s chose action %s.", name, npc_action_name( action ) );
execute_action( action );
}
void npc::execute_action( npc_action action )
{
int oldmoves = moves;
tripoint tar = pos();
Creature *cur = current_target();
if( action == npc_flee ) {
tar = good_escape_direction( false );
} else if( cur != nullptr ) {
tar = cur->pos();
}
/*
debugmsg("%s ran execute_action() with target = %d! Action %s",
name, target, npc_action_name(action));
*/
Character &player_character = get_player_character();
map &here = get_map();
switch( action ) {
case npc_pause:
move_pause();
break;
case npc_worker_downtime:
worker_downtime();
break;
case npc_reload: {
do_reload( primary_weapon() );
}
break;
case npc_investigate_sound: {
tripoint cur_pos = pos();
update_path( here.getlocal( ai_cache.s_abs_pos ) );
move_to_next();
if( pos() == cur_pos ) {
ai_cache.stuck += 1;
}
}
break;
case npc_return_to_guard_pos: {
const tripoint local_guard_pos = here.getlocal( *ai_cache.guard_pos );
update_path( local_guard_pos );
if( pos() == local_guard_pos || path.empty() ) {
move_pause();
ai_cache.guard_pos = std::nullopt;