forked from cataclysmbnteam/Cataclysm-BN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ranged.cpp
3955 lines (3495 loc) · 152 KB
/
ranged.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 "ranged.h"
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <iterator>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "activity_actor_definitions.h"
#include "avatar.h"
#include "ballistics.h"
#include "bodypart.h"
#include "calendar.h"
#include "cata_utility.h"
#include "catacharset.h"
#include "character.h"
#include "character_functions.h"
#include "color.h"
#include "creature.h"
#include "cursesdef.h"
#include "damage.h"
#include "debug.h"
#include "dispersion.h"
#include "enums.h"
#include "event.h"
#include "event_bus.h"
#include "game.h"
#include "game_constants.h"
#include "gun_mode.h"
#include "input.h"
#include "item.h"
#include "item_functions.h"
#include "item_location.h"
#include "itype.h"
#include "line.h"
#include "magic.h"
#include "map.h"
#include "material.h"
#include "math_defines.h"
#include "messages.h"
#include "monster.h"
#include "morale_types.h"
#include "mtype.h"
#include "npc.h"
#include "options.h"
#include "output.h"
#include "panels.h"
#include "player.h"
#include "player_activity.h"
#include "point.h"
#include "projectile.h"
#include "rng.h"
#include "skill.h"
#include "sounds.h"
#include "string_formatter.h"
#include "string_id.h"
#include "translations.h"
#include "trap.h"
#include "type_id.h"
#include "ui_manager.h"
#include "units.h"
#include "units_angle.h"
#include "units_utility.h"
#include "value_ptr.h"
#include "vehicle.h"
#include "vpart_position.h"
struct ammo_effect;
using ammo_effect_str_id = string_id<ammo_effect>;
static const ammo_effect_str_id ammo_effect_ACT_ON_RANGED_HIT( "ACT_ON_RANGED_HIT" );
static const ammo_effect_str_id ammo_effect_BLACKPOWDER( "BLACKPOWDER" );
static const ammo_effect_str_id ammo_effect_BOUNCE( "BOUNCE" );
static const ammo_effect_str_id ammo_effect_BURST( "BURST" );
static const ammo_effect_str_id ammo_effect_CUSTOM_EXPLOSION( "CUSTOM_EXPLOSION" );
static const ammo_effect_str_id ammo_effect_EMP( "EMP" );
static const ammo_effect_str_id ammo_effect_EXPLOSIVE( "EXPLOSIVE" );
static const ammo_effect_str_id ammo_effect_HEAVY_HIT( "HEAVY_HIT" );
static const ammo_effect_str_id ammo_effect_IGNITE( "IGNITE" );
static const ammo_effect_str_id ammo_effect_LASER( "LASER" );
static const ammo_effect_str_id ammo_effect_LIGHTNING( "LIGHTNING" );
static const ammo_effect_str_id ammo_effect_NO_CRIT( "NO_CRIT" );
static const ammo_effect_str_id ammo_effect_NO_EMBED( "NO_EMBED" );
static const ammo_effect_str_id ammo_effect_NO_ITEM_DAMAGE( "NO_ITEM_DAMAGE" );
static const ammo_effect_str_id ammo_effect_NON_FOULING( "NON-FOULING" );
static const ammo_effect_str_id ammo_effect_PLASMA( "PLASMA" );
static const ammo_effect_str_id ammo_effect_RECYCLED( "RECYCLED" );
static const ammo_effect_str_id ammo_effect_SHATTER_SELF( "SHATTER_SELF" );
static const ammo_effect_str_id ammo_effect_SHOT( "SHOT" );
static const ammo_effect_str_id ammo_effect_TANGLE( "TANGLE" );
static const ammo_effect_str_id ammo_effect_WHIP( "WHIP" );
static const ammo_effect_str_id ammo_effect_WIDE( "WIDE" );
static const efftype_id effect_downed( "downed" );
static const efftype_id effect_hit_by_player( "hit_by_player" );
static const efftype_id effect_on_roof( "on_roof" );
static const itype_id itype_12mm( "12mm" );
static const itype_id itype_40x46mm( "40x46mm" );
static const itype_id itype_40x53mm( "40x53mm" );
static const itype_id itype_66mm( "66mm" );
static const itype_id itype_84x246mm( "84x246mm" );
static const itype_id itype_adv_UPS_off( "adv_UPS_off" );
static const itype_id itype_arrow( "arrow" );
static const itype_id itype_bolt( "bolt" );
static const itype_id itype_brass_catcher( "brass_catcher" );
static const itype_id itype_flammable( "flammable" );
static const itype_id itype_m235( "m235" );
static const itype_id itype_metal_rail( "metal_rail" );
static const itype_id itype_UPS( "UPS" );
static const itype_id itype_UPS_off( "UPS_off" );
static const trap_str_id tr_practice_target( "tr_practice_target" );
static const fault_id fault_gun_blackpowder( "fault_gun_blackpowder" );
static const fault_id fault_gun_chamber_spent( "fault_gun_chamber_spent" );
static const fault_id fault_gun_dirt( "fault_gun_dirt" );
static const fault_id fault_gun_unlubricated( "fault_gun_unlubricated" );
static const skill_id skill_archery( "archery" );
static const skill_id skill_dodge( "dodge" );
static const skill_id skill_driving( "driving" );
static const skill_id skill_gun( "gun" );
static const skill_id skill_launcher( "launcher" );
static const skill_id skill_pistol( "pistol" );
static const skill_id skill_rifle( "rifle" );
static const skill_id skill_shotgun( "shotgun" );
static const skill_id skill_smg( "smg" );
static const skill_id skill_throw( "throw" );
static const bionic_id bio_railgun( "bio_railgun" );
static const bionic_id bio_targeting( "bio_targeting" );
static const bionic_id bio_ups( "bio_ups" );
static const std::string flag_CONSUMABLE( "CONSUMABLE" );
static const std::string flag_DISABLE_SIGHTS( "DISABLE_SIGHTS" );
static const std::string flag_FIRE_TWOHAND( "FIRE_TWOHAND" );
static const std::string flag_MOUNTABLE( "MOUNTABLE" );
static const std::string flag_MOUNTED_GUN( "MOUNTED_GUN" );
static const std::string flag_NEVER_JAMS( "NEVER_JAMS" );
static const std::string flag_NON_FOULING( "NON-FOULING" );
static const std::string flag_PRIMITIVE_RANGED_WEAPON( "PRIMITIVE_RANGED_WEAPON" );
static const std::string flag_PYROMANIAC_WEAPON( "PYROMANIAC_WEAPON" );
static const std::string flag_RELOAD_AND_SHOOT( "RELOAD_AND_SHOOT" );
static const std::string flag_RESTRICT_HANDS( "RESTRICT_HANDS" );
static const std::string flag_STR_DRAW( "STR_DRAW" );
static const std::string flag_UNDERWATER_GUN( "UNDERWATER_GUN" );
static const std::string flag_VEHICLE( "VEHICLE" );
static const trait_id trait_PYROMANIA( "PYROMANIA" );
static const trait_id trait_NORANGEDCRIT( "NO_RANGED_CRIT" );
// Maximum duration of aim-and-fire loop, in turns
static constexpr int AIF_DURATION_LIMIT = 10;
static projectile make_gun_projectile( const item &gun );
static void cycle_action( item &weap, const tripoint &pos );
bool can_use_bipod( const map &m, const tripoint &pos );
dispersion_sources calculate_dispersion( const map &m, const Character &who, const item &gun,
int at_recoil, bool burst );
class target_ui
{
public:
/* None of the public members (except range) should be modified during execution */
enum class TargetMode : int {
Fire,
Throw,
ThrowBlind,
Turrets,
TurretManual,
Reach,
Spell,
Shape
};
// Avatar
avatar *you;
// Interface mode
TargetMode mode = TargetMode::Fire;
// Weapon being fired/thrown
item *relevant = nullptr;
// Cached selection range from player's position
int range = 0;
// Turret being manually fired
turret_data *turret = nullptr;
// Turrets being fired (via vehicle controls)
const std::vector<vehicle_part *> *vturrets = nullptr;
// Vehicle that turrets belong to
vehicle *veh = nullptr;
// Spell being cast
spell *casting = nullptr;
// Spell cannot fail
bool no_fail = false;
// Spell does not require mana
bool no_mana = false;
// Relevant activity
aim_activity_actor *activity = nullptr;
// Generator of AoE shapes
std::optional<shape_factory> shape_gen;
// Initialize UI and run the event loop
target_handler::trajectory run();
private:
enum class ExitCode : int {
Abort,
Fire,
Timeout,
Reload
};
enum class Status : int {
Good, // All UI elements are enabled
BadTarget, // Bad 'dst' selected; forbid aiming/firing
OutOfAmmo, // Selected gun mode is out of ammo; forbid moving cursor,aiming and firing
OutOfRange // Selected target is out of range of current gun mode; forbid aiming/firing
};
// Ui status (affects which UI controls are temporarily disabled)
Status status = Status::Good;
// Cached current ammo to display
const itype *ammo = nullptr;
// Current trajectory
std::vector<tripoint> traj;
// Aiming source (player's position)
tripoint src;
// Aiming destination (cursor position)
// Use set_cursor_pos() to modify
tripoint dst;
// Creature currently under cursor. nullptr if aiming at empty tile,
// yourself or a creature you cannot see
Creature *dst_critter = nullptr;
// List of visible hostile targets
std::vector<Creature *> targets;
// 'true' if map has z levels and 3D fov is on
bool allow_zlevel_shift = false;
// Snap camera to cursor. Can be permanently toggled in settings
// or temporarily in this window
bool snap_to_target = false;
// If true, LEVEL_UP, LEVEL_DOWN and directional keys
// responsible for moving cursor will shift view instead.
bool shifting_view = false;
// Compact layout
bool compact = false;
// Tiny layout - when extremely short on space
bool tiny = false;
// Narrow layout - to keep in theme with
// "compact" and "labels-narrow" sidebar styles.
bool narrow = false;
// Window
catacurses::window w_target;
// Input context
input_context ctxt;
/* These members are relevant for TargetMode::Fire */
// Weapon sight dispersion
int sight_dispersion = 0;
// List of available weapon aim types
std::vector<ranged::aim_type> aim_types;
// Currently selected aim mode
std::vector<ranged::aim_type>::iterator aim_mode;
// 'Recoil' value the player will reach if they
// start aiming at cursor position. Equals player's
// 'recoil' while they are actively spending moves to aim,
// but increases the further away the new aim point will be
// relative to the current one.
double predicted_recoil = 0;
// For AOE spells, list of tiles affected by the spell
// relevant for TargetMode::Spell
std::set<tripoint> spell_aoe;
// For shaped attacks, we want both points and coverage
std::map<tripoint, double> shape_coverage;
// Represents a turret and a straight line from that turret to target
struct turret_with_lof {
vehicle_part *turret;
std::vector<tripoint> line;
};
// List of vehicle turrets in range (out of those listed in 'vturrets')
std::vector<turret_with_lof> turrets_in_range;
// If true, draws turret lines
// relevant for TargetMode::Turrets
bool draw_turret_lines = false;
// Create window and set up input context
void init_window_and_input();
// Handle input related to cursor movement.
// Returns 'true' if action was recognized and processed.
// 'skip_redraw' is set to 'true' if there is no need to redraw the UI.
bool handle_cursor_movement( const std::string &action, bool &skip_redraw );
// Set cursor position. If new position is out of range,
// selects closest position in range.
// Returns 'false' if cursor position did not change
bool set_cursor_pos( const tripoint &new_pos );
// Called when range/ammo changes (or may have changed)
void on_range_ammo_changed();
// Updates 'targets' for current range
void update_target_list();
// Choose where to position the cursor when opening the ui
tripoint choose_initial_target();
/**
* Try to re-acquire target for aim-and-fire.
* @param critter whether were aiming at a critter, or a tile
* @param new_dst where to move aim cursor (if e.g. critter moved)
* @returns true on success
*/
bool try_reacquire_target( bool critter, tripoint &new_dst );
// Update 'status' variable
void update_status();
// Calculates distance from 'src'. For consistency, prefer using this over rl_dist.
int dist_fn( const tripoint &p );
// Set creature (or tile) under cursor as player's last target
void set_last_target();
// Prompts player to confirm attack on neutral NPC
// Returns 'true' if attack should proceed
bool confirm_non_enemy_target();
// Prompts player to re-confirm an ongoing attack if
// a non-hostile NPC / friendly creatures enters line of fire.
// Returns 'true' if attack should proceed
bool prompt_friendlies_in_lof();
// List friendly creatures currently occupying line of fire.
std::vector<weak_ptr_fast<Creature>> list_friendlies_in_lof();
// Toggle snap-to-target
void toggle_snap_to_target();
// Cycle targets. 'direction' is either 1 or -1
void cycle_targets( int direction );
// Set new view offset. Updates map cache if necessary
void set_view_offset( const tripoint &new_offset );
// Updates 'turrets_in_range'
void update_turrets_in_range();
// Recalculate 'recoil' penalty. This should be called if
// avatar's 'recoil' value has been modified
// Relevant for TargetMode::Fire
void recalc_aim_turning_penalty();
// Apply penalty to avatar's 'recoil' value based on
// how much they moved their aim point.
// Relevant for TargetMode::Fire
void apply_aim_turning_penalty();
// Switch firing mode.
void action_switch_mode();
// Ensure we're using ranged gun mode.
void ensure_ranged_gun_mode();
// Update range & ammo from current gun mode
void update_ammo_range_from_gun_mode();
// Switch ammo. Returns 'false' if requires a reloading UI.
bool action_switch_ammo();
// Aim for 10 turns. Returns 'false' if ran out of moves
bool action_aim();
// Aim and shoot. Returns 'false' if ran out of moves
bool action_aim_and_shoot( const std::string &action );
// Draw UI-specific terrain overlays
void draw_terrain_overlay();
// Draw aiming window
void draw_ui_window();
// Generate ui window title
std::string uitext_title();
// Generate flavor text for 'Fire!' key
std::string uitext_fire();
void draw_window_title();
void draw_help_notice();
// Draw list of available controls at the bottom of the window.
// text_y - first free line counting from the top
void draw_controls_list( int text_y );
void panel_cursor_info( int &text_y );
void panel_gun_info( int &text_y );
void panel_recoil( int &text_y );
void panel_spell_info( int &text_y );
void panel_target_info( int &text_y, bool fill_with_blank_if_no_target );
void panel_fire_mode_aim( int &text_y );
void panel_turret_list( int &text_y );
// On-selected-as-target checks that act as if they are on-hit checks.
// `harmful` is `false` if using a non-damaging spell
void on_target_accepted( bool harmful );
};
target_handler::trajectory target_handler::mode_fire( avatar &you, aim_activity_actor &activity )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Fire;
ui.activity = &activity;
ui.relevant = activity.get_weapon();
return ui.run();
}
target_handler::trajectory target_handler::mode_throw( avatar &you, item &relevant,
bool blind_throwing )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = blind_throwing ? target_ui::TargetMode::ThrowBlind : target_ui::TargetMode::Throw;
ui.relevant = &relevant;
ui.range = you.throw_range( relevant );
restore_on_out_of_scope<tripoint> view_offset_prev( you.view_offset );
return ui.run();
}
target_handler::trajectory target_handler::mode_reach( avatar &you, item &weapon )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Reach;
ui.relevant = &weapon;
ui.range = weapon.reach_range( you );
restore_on_out_of_scope<tripoint> view_offset_prev( you.view_offset );
return ui.run();
}
target_handler::trajectory target_handler::mode_turret_manual( avatar &you, turret_data &turret )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::TurretManual;
ui.turret = &turret;
ui.relevant = &*turret.base();
restore_on_out_of_scope<tripoint> view_offset_prev( you.view_offset );
return ui.run();
}
target_handler::trajectory target_handler::mode_turrets( avatar &you, vehicle &veh,
const std::vector<vehicle_part *> &turrets )
{
// Find radius of a circle centered at u encompassing all points turrets can aim at
// FIXME: this calculation is fine for square distances, but results in an underestimation
// when used with real circles
int range_total = 0;
for( vehicle_part *t : turrets ) {
int range = veh.turret_query( *t ).range();
tripoint pos = veh.global_part_pos3( *t );
int res = 0;
res = std::max( res, rl_dist( you.pos(), pos + point( range, 0 ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( -range, 0 ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( 0, range ) ) );
res = std::max( res, rl_dist( you.pos(), pos + point( 0, -range ) ) );
range_total = std::max( range_total, res );
}
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Turrets;
ui.veh = &veh;
ui.vturrets = &turrets;
ui.range = range_total;
restore_on_out_of_scope<tripoint> view_offset_prev( you.view_offset );
return ui.run();
}
target_handler::trajectory target_handler::mode_spell( avatar &you, spell &casting, bool no_fail,
bool no_mana )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Spell;
ui.casting = &casting;
ui.range = casting.range();
ui.no_fail = no_fail;
ui.no_mana = no_mana;
restore_on_out_of_scope<tripoint> view_offset_prev( you.view_offset );
return ui.run();
}
target_handler::trajectory target_handler::mode_shaped( avatar &you, shape_factory &shape_fac,
aim_activity_actor &activity )
{
target_ui ui = target_ui();
ui.you = &you;
ui.mode = target_ui::TargetMode::Shape;
ui.shape_gen = shape_fac;
ui.range = shape_fac.get_range();
ui.activity = &activity;
ui.relevant = activity.get_weapon();
return ui.run();
}
static double occupied_tile_fraction( m_size target_size )
{
switch( target_size ) {
case MS_TINY:
return 0.1;
case MS_SMALL:
return 0.25;
case MS_MEDIUM:
return 0.5;
case MS_LARGE:
return 0.75;
case MS_HUGE:
return 1.0;
default:
break;
}
return 0.5;
}
double Creature::ranged_target_size() const
{
if( has_flag( MF_HARDTOSHOOT ) ) {
switch( get_size() ) {
case MS_TINY:
case MS_SMALL:
return occupied_tile_fraction( MS_TINY );
case MS_MEDIUM:
return occupied_tile_fraction( MS_SMALL );
case MS_LARGE:
return occupied_tile_fraction( MS_MEDIUM );
case MS_HUGE:
return occupied_tile_fraction( MS_LARGE );
default:
break;
}
}
return occupied_tile_fraction( get_size() );
}
int range_with_even_chance_of_good_hit( int dispersion )
{
int even_chance_range = 0;
while( static_cast<unsigned>( even_chance_range ) <
Creature::dispersion_for_even_chance_of_good_hit.size() &&
dispersion < Creature::dispersion_for_even_chance_of_good_hit[ even_chance_range ] ) {
even_chance_range++;
}
return even_chance_range;
}
int ranged::gun_engagement_moves( const Character &who, const item &gun, int target, int start )
{
int mv = 0;
double penalty = start;
while( penalty > target ) {
double adj = ranged::aim_per_move( who, gun, penalty );
if( adj <= 0 ) {
break;
}
penalty -= adj;
mv++;
}
return mv;
}
bool ranged::handle_gun_damage( Character &shooter, item &it )
{
// Below item (maximum dirt possible) should be greater than or equal to dirt range in item_group.cpp. Also keep in mind that monster drops can have specific ranges and these should be below the max!
const double dirt_max_dbl = 10000;
if( !it.is_gun() ) {
debugmsg( "Tried to handle_gun_damage of a non-gun %s", it.tname() );
return false;
}
int dirt = it.get_var( "dirt", 0 );
int dirtadder = 0;
double dirt_dbl = static_cast<double>( dirt );
if( it.faults.count( fault_gun_chamber_spent ) ) {
return false;
}
const auto &curammo_effects = it.ammo_effects();
const islot_gun &firing = *it.type->gun;
// misfire chance based on dirt accumulation. Formula is designed to make chance of jam highly unlikely at low dirt levels, but levels increase geometrically as the dirt level reaches max (10,000). The number used is just a figure I found reasonable after plugging the number into excel and changing it until the probability made sense at high, medium, and low levels of dirt.
if( !it.has_flag( flag_NEVER_JAMS ) &&
x_in_y( dirt_dbl * dirt_dbl * dirt_dbl,
1000000000000.0 ) ) {
shooter.add_msg_player_or_npc(
_( "Your %s misfires with a muffled click!" ),
_( "<npcname>'s %s misfires with a muffled click!" ),
it.tname() );
// at high dirt levels the chance to misfire gets to significant levels. 10,000 is max and 7800 is quite high so above that the player gets some relief in the form of exchanging time for some dirt reduction. Basically jiggling the parts loose to remove some dirt and get a few more shots out.
if( dirt_dbl >
7800 ) {
shooter.add_msg_player_or_npc(
_( "Perhaps taking the ammo out of your %s and reloading will help." ),
_( "Perhaps taking the ammo out of <npcname>'s %s and reloading will help." ),
it.tname() );
}
return false;
}
// Here we check if we're underwater and whether we should misfire.
// As a result this causes no damage to the firearm, note that some guns are waterproof
// and so are immune to this effect, note also that WATERPROOF_GUN status does not
// mean the gun will actually be accurate underwater.
int effective_durability = firing.durability;
if( shooter.is_underwater() && !it.has_flag( "WATERPROOF_GUN" ) &&
one_in( effective_durability ) ) {
shooter.add_msg_player_or_npc( _( "Your %s misfires with a wet click!" ),
_( "<npcname>'s %s misfires with a wet click!" ),
it.tname() );
return false;
// Here we check for a chance for the weapon to suffer a mechanical malfunction.
// Note that some weapons never jam up 'NEVER_JAMS' and thus are immune to this
// effect as current guns have a durability between 5 and 9 this results in
// a chance of mechanical failure between 1/(64*3) and 1/(1024*3) on any given shot.
// the malfunction can't cause damage
} else if( one_in( ( 2 << effective_durability ) * 3 ) && !it.has_flag( flag_NEVER_JAMS ) ) {
shooter.add_msg_player_or_npc( _( "Your %s malfunctions!" ),
_( "<npcname>'s %s malfunctions!" ),
it.tname() );
return false;
// Here we check for a chance for the weapon to suffer a misfire due to
// using player-made 'RECYCLED' bullets. Note that not all forms of
// player-made ammunition have this effect.
} else if( curammo_effects.count( ammo_effect_RECYCLED ) && one_in( 256 ) ) {
shooter.add_msg_player_or_npc( _( "Your %s misfires with a muffled click!" ),
_( "<npcname>'s %s misfires with a muffled click!" ),
it.tname() );
return false;
// Here we check for a chance for attached mods to get damaged if they are flagged as 'CONSUMABLE'.
// This is mostly for crappy handmade expedient stuff or things that rarely receive damage during normal usage.
// Default chance is 1/10000 unless set via json, damage is proportional to caliber(see below).
// Can be toned down with 'consume_divisor.'
} else if( it.has_flag( flag_CONSUMABLE ) && !curammo_effects.count( ammo_effect_LASER ) &&
!curammo_effects.count( ammo_effect_PLASMA ) && !curammo_effects.count( ammo_effect_EMP ) ) {
int uncork = ( ( 10 * it.ammo_data()->ammo->loudness )
+ ( it.ammo_data()->ammo->recoil / 2 ) ) / 100;
uncork = std::pow( uncork, 3 ) * 6.5;
for( auto mod : it.gunmods() ) {
if( mod->has_flag( flag_CONSUMABLE ) ) {
int dmgamt = uncork / mod->type->gunmod->consume_divisor;
int modconsume = mod->type->gunmod->consume_chance;
int initstate = it.damage();
// fuzz damage if it's small
if( dmgamt < 1000 ) {
dmgamt = rng( dmgamt, dmgamt + 200 );
// ignore damage if inconsequential.
}
if( dmgamt < 800 ) {
dmgamt = 0;
}
if( one_in( modconsume ) ) {
if( mod->mod_damage( dmgamt ) ) {
shooter.add_msg_player_or_npc( m_bad, _( "Your attached %s is destroyed by your shot!" ),
_( "<npcname>'s attached %s is destroyed by their shot!" ),
mod->tname() );
shooter.i_rem( mod );
} else if( it.damage() > initstate ) {
shooter.add_msg_player_or_npc( m_bad, _( "Your attached %s is damaged by your shot!" ),
_( "<npcname>'s %s is damaged by their shot!" ),
mod->tname() );
}
}
}
}
}
if( it.has_fault( fault_gun_unlubricated ) &&
x_in_y( dirt_dbl, dirt_max_dbl ) ) {
shooter.add_msg_player_or_npc( m_bad, _( "Your %s emits a grimace-inducing screech!" ),
_( "<npcname>'s %s emits a grimace-inducing screech!" ),
it.tname() );
it.inc_damage();
}
if( ( ( !curammo_effects.count( ammo_effect_NON_FOULING ) && !it.has_flag( flag_NON_FOULING ) ) ||
( it.has_fault( fault_gun_unlubricated ) ) ) &&
!it.has_flag( flag_PRIMITIVE_RANGED_WEAPON ) ) {
if( curammo_effects.count( ammo_effect_BLACKPOWDER ) ||
it.has_fault( fault_gun_unlubricated ) ) {
if( ( ( it.ammo_data()->ammo->recoil < firing.min_cycle_recoil ) ||
( it.has_fault( fault_gun_unlubricated ) && one_in( 16 ) ) ) &&
it.faults_potential().count( fault_gun_chamber_spent ) ) {
shooter.add_msg_player_or_npc( m_bad, _( "Your %s fails to cycle!" ),
_( "<npcname>'s %s fails to cycle!" ),
it.tname() );
it.faults.insert( fault_gun_chamber_spent );
// Don't return false in this case; this shot happens, follow-up ones won't.
}
}
// These are the dirtying/fouling mechanics
if( !curammo_effects.count( ammo_effect_NON_FOULING ) && !it.has_flag( flag_NON_FOULING ) ) {
if( dirt < static_cast<int>( dirt_max_dbl ) ) {
dirtadder = curammo_effects.count( ammo_effect_BLACKPOWDER ) * ( 200 -
( firing.blackpowder_tolerance *
2 ) );
// dirtadder is the dirt-increasing number for shots fired with gunpowder-based ammo. Usually dirt level increases by 1, unless it's blackpowder, in which case it increases by a higher number, but there is a reduction for blackpowder resistance of a weapon.
if( dirtadder < 0 ) {
dirtadder = 0;
}
// in addition to increasing dirt level faster, regular gunpowder fouling is also capped at 7,150, not 10,000. So firing with regular gunpowder can never make the gun quite as bad as firing it with black gunpowder. At 7,150 the chance to jam is significantly lower (though still significant) than it is at 10,000, the absolute cap.
if( curammo_effects.count( ammo_effect_BLACKPOWDER ) ||
dirt < 7150 ) {
it.set_var( "dirt", std::min( static_cast<int>( dirt_max_dbl ), dirt + dirtadder + 1 ) );
}
}
dirt = it.get_var( "dirt", 0 );
dirt_dbl = static_cast<double>( dirt );
if( dirt > 0 && !it.faults.count( fault_gun_blackpowder ) ) {
it.faults.insert( fault_gun_dirt );
}
if( dirt > 0 && curammo_effects.count( ammo_effect_BLACKPOWDER ) ) {
it.faults.erase( fault_gun_dirt );
it.faults.insert( fault_gun_blackpowder );
}
// end fouling mechanics
}
}
// chance to damage gun due to high levels of dirt. Very unlikely, especially at lower levels and impossible below 5,000. Lower than the chance of a jam at the same levels. 555555... is an arbitrary number that I came up with after playing with the formula in excel. It makes sense at low, medium, and high levels of dirt.
if( dirt_dbl > 5000 &&
x_in_y( dirt_dbl * dirt_dbl * dirt_dbl,
5555555555555 ) ) {
shooter.add_msg_player_or_npc( m_bad, _( "Your %s is damaged by the high pressure!" ),
_( "<npcname>'s %s is damaged by the high pressure!" ),
it.tname() );
// Don't increment until after the message
it.inc_damage();
}
return true;
}
void npc::pretend_fire( npc *source, int shots, item &gun )
{
int curshot = 0;
avatar &you = get_avatar();
if( you.sees( *source ) && one_in( 50 ) ) {
add_msg( m_info, _( "%s shoots something." ), source->disp_name() );
}
while( curshot != shots ) {
if( gun.ammo_consume( gun.ammo_required(), pos() ) != gun.ammo_required() ) {
debugmsg( "Unexpected shortage of ammo whilst firing %s", gun.tname().c_str() );
break;
}
item *weapon = &gun;
const auto data = weapon->gun_noise( shots > 1 );
if( you.sees( *source ) ) {
add_msg( m_warning, _( "You hear %s." ), data.sound );
}
curshot++;
moves -= 100;
}
}
bool can_use_bipod( const map &m, const tripoint &pos )
{
// usage of any attached bipod is dependent upon terrain
if( m.has_flag_ter_or_furn( "MOUNTABLE", pos ) ) {
return true;
}
if( const optional_vpart_position vp = m.veh_at( pos ) ) {
return vp->vehicle().has_part( pos, "MOUNTABLE" );
}
return false;
}
dispersion_sources calculate_dispersion( const map &m, const Character &who, const item &gun,
int at_recoil, bool burst )
{
bool bipod = can_use_bipod( m, who.pos() );
int gun_recoil = gun.gun_recoil( bipod );
int eff_recoil = at_recoil + ( burst ? ranged::burst_penalty( who, gun, gun_recoil ) : 0 );
dispersion_sources dispersion( ranged::get_weapon_dispersion( who, gun ) );
dispersion.add_range( eff_recoil );
return dispersion;
}
int ranged::fire_gun( Character &who, const tripoint &target, int shots )
{
return fire_gun( who, target, shots, who.primary_weapon(), item_location() );
}
int ranged::fire_gun( Character &who, const tripoint &target, int max_shots, item &gun,
item_location ammo )
{
int attack_moves = time_to_attack( who, gun, ammo );
if( !gun.is_gun() ) {
debugmsg( "%s tried to fire non-gun (%s).", who.name, gun.tname() );
return 0;
}
if( gun.ammo_required() > 0 && !gun.ammo_remaining() && !ammo ) {
debugmsg( "%s's gun %s is empty and has no ammo for reloading.", who.name, gun.tname() );
return 0;
}
bool is_mech_weapon = false;
if( who.is_mounted() && who.mounted_creature->has_flag( MF_RIDEABLE_MECH ) ) {
is_mech_weapon = true;
}
int shots = max_shots;
// Number of shots to fire is limited by the amount of remaining ammo
if( gun.ammo_required() ) {
const int ammo_left = ammo ? ammo.get_item()->count() : gun.ammo_remaining();
shots = std::min( shots, ammo_left / gun.ammo_required() );
}
// cap our maximum burst size by the amount of UPS power left
if( !gun.has_flag( flag_VEHICLE ) && gun.get_gun_ups_drain() > 0 ) {
shots = std::min( shots, static_cast<int>( who.charges_of( itype_UPS ) /
gun.get_gun_ups_drain() ) );
}
if( shots <= 0 ) {
debugmsg( "Attempted to fire zero or negative shots using %s", gun.tname() );
}
std::optional<shape_factory> shape;
if( gun.ammo_current() && gun.ammo_current()->ammo ) {
shape = gun.ammo_current()->ammo->shape;
}
map &here = get_map();
// Shaped attacks don't allow aiming, so they don't suffer from lack of aim either
int character_recoil = shape ? recoil_vehicle( who ) : recoil_total( who );
// Penalty is (intentionally) based off mode shots, not ammo-limited.
dispersion_sources dispersion = calculate_dispersion( here, who, gun, character_recoil,
max_shots > 1 );
bool aoe_attack = gun.gun_skill() == skill_launcher || shape;
tripoint aim = target;
int curshot = 0;
int hits = 0; // total shots on target
while( curshot != shots ) {
if( !!ammo && !gun.ammo_remaining() ) {
gun.reload( get_avatar(), std::move( ammo ), 1 );
}
if( gun.faults.count( fault_gun_chamber_spent ) && curshot == 0 ) {
who.moves -= 50;
gun.faults.erase( fault_gun_chamber_spent );
who.add_msg_if_player( _( "You cycle your %s manually." ), gun.tname() );
}
if( !ranged::handle_gun_damage( who, gun ) ) {
break;
}
// If this is a vehicle mounted turret, which vehicle is it mounted on?
const vehicle *in_veh = who.has_effect( effect_on_roof )
? veh_pointer_or_null( here.veh_at( who.pos() ) )
: nullptr;
projectile projectile = make_gun_projectile( gun );
// Damage reduction from insufficient strength, if using a STR_DRAW weapon.
projectile.impact.mult_damage( ranged::str_draw_damage_modifier( gun, who ) );
if( who.has_trait( trait_NORANGEDCRIT ) ) {
projectile.add_effect( ammo_effect_NO_CRIT );
}
if( !shape ) {
auto shot = projectile_attack( projectile, who.pos(), aim, dispersion, &who, in_veh );
if( shot.missed_by <= .1 ) {
// TODO: check head existence for headshot
g->events().send<event_type::character_gets_headshot>( who.getID() );
}
if( shot.hit_critter ) {
hits++;
}
} else {
// 30 degree cap, like for projectiles
double angle_offset_arcmin = std::min( dispersion.roll(), 1800.0 ) * ( one_in( 2 ) ? 1 : -1 );
double angle_offset = units::to_radians( units::from_arcmin( angle_offset_arcmin ) );
double dx = aim.x - who.posx();
double dy = aim.y - who.posy();
double new_angle = atan2( dy, dx ) + angle_offset;
// Always using trig here, rotations in maximum metric are weird
double length = trig_dist( who.pos(), aim );
rl_vec3d vec_pos( who.pos() );
rl_vec3d new_aim = vec_pos + rl_vec3d( length, 0, 0 ).rotated( new_angle );
ranged::execute_shaped_attack( *shape->create( vec_pos, new_aim ), projectile, who );
}
curshot++;
ranged::make_gun_sound_effect( who, shots > 1, gun );
cycle_action( gun, who.pos() );
if( who.has_trait( trait_PYROMANIA ) &&
!who.has_morale( MORALE_PYROMANIA_STARTFIRE ) &&
gun.has_flag( flag_PYROMANIAC_WEAPON ) ) {
who.add_msg_if_player( m_good, _( "You feel a surge of euphoria as flames roar out of the %s!" ),
gun.tname() );
who.add_morale( MORALE_PYROMANIA_STARTFIRE, 15, 15, 8_hours, 6_hours );
who.rem_morale( MORALE_PYROMANIA_NOFIRE );
}
if( gun.ammo_consume( gun.ammo_required(), who.pos() ) != gun.ammo_required() ) {
debugmsg( "Unexpected shortage of ammo whilst firing %s", gun.tname() );
break;
}
if( !gun.has_flag( flag_VEHICLE ) ) {
who.use_charges( itype_UPS, gun.get_gun_ups_drain() );
}
if( aoe_attack ) {
continue; // skip retargeting for launchers
}
}
if( gun.has_flag( flag_RELOAD_AND_SHOOT ) ) {
// Reset aim for bows and other reload-and-shoot weapons.
who.recoil = MAX_RECOIL;
} else {
// Now actually apply recoil for the future shots
// But only for one shot, because bursts kinda suck
int gun_recoil = gun.gun_recoil( can_use_bipod( here, who.pos() ) );
// If user is currently able to fire a mounted gun freely, penalize recoil based on size class.
if( gun.has_flag( flag_MOUNTED_GUN ) && !can_use_bipod( here, who.pos() ) ) {
if( who.get_size() == MS_HUGE ) {
gun_recoil = gun_recoil * 2;
} else {
gun_recoil = gun_recoil * 3;
}
}
who.recoil += gun_recoil;
if( is_mech_weapon ) {
// mechs can handle recoil far better. they are built around their main gun.
who.recoil = who.recoil / 2;
}
who.recoil = std::min( MAX_RECOIL, who.recoil );
}
// Use different amounts of time depending on the type of gun and our skill
who.moves -= attack_moves;
// Practice the base gun skill proportionally to number of hits, but always by one.
who.as_player()->practice( skill_gun, ( hits + 1 ) * 5 );
// launchers train weapon skill for both hits and misses.
int practice_units = aoe_attack ? curshot : hits;
who.as_player()->practice( gun.gun_skill(), ( practice_units + 1 ) * 5 );
return curshot;
}
namespace ranged
{
int throw_cost( const Character &c, const item &to_throw )
{
// Very similar to player::attack_cost
// TODO: Extract into a function?
// Differences:
// Dex is more (2x) important for throwing speed
// At 10 skill, the cost is down to 0.75%, not 0.66%
const int base_move_cost = to_throw.attack_cost() / 2;