Skip to main content

ob_game/
weapons.rs

1//! Player weapons, ammunition and the weapon animation state machine (driven by QAVs).
2
3use crate::dudes::ProjKind;
4
5pub const AMMO_TYPES: usize = 10;
6
7pub mod ammo {
8    pub const NONE: usize = 0;
9    pub const FLARES: usize = 1;
10    pub const SHELLS: usize = 2;
11    pub const BULLETS: usize = 3;
12    pub const GASOLINE: usize = 4;
13    pub const TNT: usize = 5;
14    pub const SPRAY: usize = 6;
15    pub const TESLA: usize = 7;
16    pub const SOULS: usize = 8;
17    pub const VOODOO: usize = 9;
18}
19
20pub const AMMO_MAX: [i32; AMMO_TYPES] = [0, 50, 100, 400, 200, 50, 400, 300, 100, 100];
21
22#[derive(Debug, Clone, Copy, PartialEq)]
23pub enum Fire {
24    Melee {
25        damage: i32,
26        range: f64,
27    },
28    Hitscan {
29        damage: i32,
30        pellets: i32,
31        spread: f64,
32    },
33    Projectile(ProjKind),
34    /// Several projectiles fanned out horizontally.
35    Burst {
36        kind: ProjKind,
37        count: i32,
38        spread: f64,
39    },
40    /// Thrown explosive with a fuse (seconds) and throw strength (0..1).
41    Throw {
42        fuse: f64,
43        power: f64,
44    },
45    /// Short-range flame cone.
46    Spray {
47        damage: i32,
48        range: f64,
49    },
50    /// Voodoo: damage every visible enemy.
51    Curse {
52        damage: i32,
53    },
54}
55
56#[derive(Debug, Clone, Copy)]
57pub struct FireMode {
58    pub qav: u32,
59    pub kind: Fire,
60    pub per_shot: i32,
61    /// Keep firing while the button is held.
62    pub auto: bool,
63}
64
65#[derive(Debug, Clone, Copy)]
66pub struct WeaponDef {
67    pub name: &'static str,
68    pub ammo: usize,
69    pub up: u32,
70    pub idle: u32,
71    pub down: u32,
72    pub primary: FireMode,
73    pub alt: FireMode,
74    /// Dual-wield ("guns akimbo") animation set: up, idle, fire, down.
75    pub akimbo: Option<[u32; 4]>,
76}
77
78const fn mode(qav: u32, kind: Fire, per_shot: i32, auto: bool) -> FireMode {
79    FireMode {
80        qav,
81        kind,
82        per_shot,
83        auto,
84    }
85}
86
87const MELEE: Fire = Fire::Melee {
88    damage: 12,
89    range: 160.0,
90};
91
92/// Sawed-off QAVs: idle with 0 / 1 / 2 loaded barrels, first and second barrel, both, reload.
93pub const SHOT_IDLE: [u32; 3] = [51, 52, 53];
94pub const SHOT_FIRE1: u32 = 54;
95pub const SHOT_FIRE2: u32 = 55;
96pub const SHOT_RELOAD: u32 = 57;
97/// Voodoo stab animations (picked at random).
98pub const VOODOO_STABS: [u32; 4] = [103, 104, 105, 106];
99
100/// Weapon slots 1..=10 (index 0 unused).
101pub const WEAPONS: [WeaponDef; 11] = [
102    WeaponDef {
103        name: "",
104        ammo: 0,
105        up: 0,
106        idle: 1,
107        down: 3,
108        primary: mode(2, MELEE, 0, true),
109        alt: mode(2, MELEE, 0, true),
110        akimbo: None,
111    },
112    WeaponDef {
113        name: "Pitchfork",
114        ammo: ammo::NONE,
115        up: 0,
116        idle: 1,
117        down: 3,
118        primary: mode(2, MELEE, 0, true),
119        alt: mode(2, MELEE, 0, true),
120        akimbo: None,
121    },
122    WeaponDef {
123        name: "Flare Pistol",
124        ammo: ammo::FLARES,
125        up: 41,
126        idle: 42,
127        down: 44,
128        primary: mode(43, Fire::Projectile(ProjKind::Flare), 1, false),
129        alt: mode(
130            43,
131            Fire::Burst {
132                kind: ProjKind::Flare,
133                count: 8,
134                spread: 0.35,
135            },
136            8,
137            false,
138        ),
139        akimbo: Some([45, 46, 47, 49]),
140    },
141    WeaponDef {
142        name: "Sawed-off",
143        ammo: ammo::SHELLS,
144        up: 50,
145        idle: 53,
146        down: 58,
147        primary: mode(
148            SHOT_FIRE1,
149            Fire::Hitscan {
150                damage: 5,
151                pellets: 12,
152                spread: 0.07,
153            },
154            1,
155            false,
156        ),
157        alt: mode(
158            56,
159            Fire::Hitscan {
160                damage: 5,
161                pellets: 24,
162                spread: 0.1,
163            },
164            2,
165            false,
166        ),
167        akimbo: Some([59, 60, 62, 63]),
168    },
169    WeaponDef {
170        name: "Tommy Gun",
171        ammo: ammo::BULLETS,
172        up: 64,
173        idle: 65,
174        down: 68,
175        primary: mode(
176            66,
177            Fire::Hitscan {
178                damage: 6,
179                pellets: 1,
180                spread: 0.025,
181            },
182            1,
183            true,
184        ),
185        alt: mode(
186            67,
187            Fire::Hitscan {
188                damage: 6,
189                pellets: 6,
190                spread: 0.12,
191            },
192            6,
193            true,
194        ),
195        akimbo: Some([69, 70, 71, 72]),
196    },
197    WeaponDef {
198        name: "Napalm Launcher",
199        ammo: ammo::GASOLINE,
200        up: 89,
201        idle: 90,
202        down: 92,
203        primary: mode(91, Fire::Projectile(ProjKind::Napalm), 1, false),
204        alt: mode(
205            91,
206            Fire::Burst {
207                kind: ProjKind::Napalm,
208                count: 3,
209                spread: 0.15,
210            },
211            5,
212            false,
213        ),
214        akimbo: Some([120, 121, 122, 124]),
215    },
216    WeaponDef {
217        name: "Dynamite",
218        ammo: ammo::TNT,
219        up: 16,
220        idle: 20,
221        down: 17,
222        primary: mode(23, Fire::Throw { fuse: 2.5, power: 1.0 }, 1, false),
223        alt: mode(22, Fire::Throw { fuse: 4.0, power: 0.15 }, 1, false),
224        akimbo: None,
225    },
226    WeaponDef {
227        name: "Spray Can",
228        ammo: ammo::SPRAY,
229        up: 8,
230        idle: 9,
231        down: 11,
232        primary: mode(
233            10,
234            Fire::Spray {
235                damage: 3,
236                range: 900.0,
237            },
238            1,
239            true,
240        ),
241        alt: mode(14, Fire::Throw { fuse: 1.5, power: 0.8 }, 50, false),
242        akimbo: None,
243    },
244    WeaponDef {
245        name: "Tesla Cannon",
246        ammo: ammo::TESLA,
247        up: 74,
248        idle: 75,
249        down: 81,
250        primary: mode(77, Fire::Projectile(ProjKind::Tesla), 1, true),
251        alt: mode(
252            78,
253            Fire::Burst {
254                kind: ProjKind::Tesla,
255                count: 7,
256                spread: 0.06,
257            },
258            35,
259            false,
260        ),
261        akimbo: Some([82, 83, 84, 88]),
262    },
263    WeaponDef {
264        name: "Life Leech",
265        ammo: ammo::SOULS,
266        up: 111,
267        idle: 112,
268        down: 119,
269        primary: mode(114, Fire::Projectile(ProjKind::Leech), 1, true),
270        alt: mode(
271            115,
272            Fire::Burst {
273                kind: ProjKind::Leech,
274                count: 5,
275                spread: 0.2,
276            },
277            5,
278            false,
279        ),
280        akimbo: None,
281    },
282    WeaponDef {
283        name: "Voodoo Doll",
284        ammo: ammo::VOODOO,
285        up: 100,
286        idle: 101,
287        down: 109,
288        primary: mode(
289            103,
290            Fire::Hitscan {
291                damage: 20,
292                pellets: 1,
293                spread: 0.0,
294            },
295            1,
296            false,
297        ),
298        alt: mode(107, Fire::Curse { damage: 60 }, 0, false),
299        akimbo: None,
300    },
301];
302
303#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
304pub enum WeaponState {
305    Raising,
306    Ready,
307    Firing,
308    Reloading,
309    Lowering,
310}
311
312#[derive(serde::Serialize, serde::Deserialize, Debug, Clone)]
313pub struct Arsenal {
314    pub have: [bool; 11],
315    pub ammo: [i32; AMMO_TYPES],
316    pub current: usize,
317    pub pending: usize,
318    pub state: WeaponState,
319    /// Currently playing QAV and ticks since it started.
320    pub qav: u32,
321    pub qav_time: i32,
322    pub last_frame: i32,
323    /// The running attack is the alternate fire.
324    pub alt: bool,
325    /// Loaded sawed-off barrels (0..=2).
326    pub barrels: u8,
327    /// Dual-wield power-up active.
328    pub akimbo: bool,
329    rng: u32,
330}
331
332impl Default for Arsenal {
333    fn default() -> Self {
334        let mut have = [false; 11];
335        have[1] = true;
336        Arsenal {
337            have,
338            ammo: [0; AMMO_TYPES],
339            current: 1,
340            pending: 1,
341            state: WeaponState::Raising,
342            qav: WEAPONS[1].up,
343            qav_time: 0,
344            last_frame: -1,
345            alt: false,
346            barrels: 2,
347            akimbo: false,
348            rng: 7,
349        }
350    }
351}
352
353impl Arsenal {
354    pub fn def(&self) -> &'static WeaponDef {
355        &WEAPONS[self.current]
356    }
357
358    fn dual(&self) -> Option<[u32; 4]> {
359        if self.akimbo {
360            self.def().akimbo
361        } else {
362            None
363        }
364    }
365
366    /// The fire mode of the running (or requested) attack.
367    pub fn mode(&self) -> FireMode {
368        if self.alt {
369            self.def().alt
370        } else {
371            self.def().primary
372        }
373    }
374
375    pub fn has_ammo_for(&self, w: usize, alt: bool) -> bool {
376        let d = &WEAPONS[w];
377        let m = if alt { d.alt } else { d.primary };
378        d.ammo == ammo::NONE || self.ammo[d.ammo] >= m.per_shot.max(1)
379    }
380
381    pub fn has_ammo(&self, w: usize) -> bool {
382        self.has_ammo_for(w, false)
383    }
384
385    pub fn add_ammo(&mut self, kind: usize, n: i32) -> bool {
386        if kind == 0 || kind >= AMMO_TYPES || self.ammo[kind] >= AMMO_MAX[kind] {
387            return false;
388        }
389        self.ammo[kind] = (self.ammo[kind] + n).min(AMMO_MAX[kind]);
390        true
391    }
392
393    /// Picks up a weapon; returns true if anything changed.
394    pub fn give_weapon(&mut self, w: usize, ammo_amount: i32) -> bool {
395        let new = !self.have[w];
396        self.have[w] = true;
397        let got_ammo = self.add_ammo(WEAPONS[w].ammo, ammo_amount);
398        if new && self.state != WeaponState::Firing {
399            self.select(w);
400        }
401        new || got_ammo
402    }
403
404    pub fn select(&mut self, w: usize) {
405        if w == 0 || w > 10 || !self.have[w] || w == self.current && self.state != WeaponState::Lowering {
406            return;
407        }
408        self.pending = w;
409        if self.state != WeaponState::Lowering {
410            let down = self.dual().map_or(self.def().down, |d| d[3]);
411            self.start(WeaponState::Lowering, down);
412        }
413    }
414
415    fn start(&mut self, st: WeaponState, qav: u32) {
416        self.state = st;
417        self.qav = qav;
418        self.qav_time = 0;
419        self.last_frame = -1;
420    }
421
422    fn idle_qav(&self) -> u32 {
423        if let Some(d) = self.dual() {
424            return d[1];
425        }
426        if self.current == 3 {
427            return SHOT_IDLE[self.barrels.min(2) as usize];
428        }
429        self.def().idle
430    }
431
432    fn up_qav(&self) -> u32 {
433        self.dual().map_or(self.def().up, |d| d[0])
434    }
435
436    fn fire_qav(&mut self, alt: bool) -> u32 {
437        if let Some(d) = self.dual() {
438            return d[2];
439        }
440        if self.current == 3 && !alt {
441            return if self.barrels >= 2 { SHOT_FIRE1 } else { SHOT_FIRE2 };
442        }
443        if self.current == 10 && !alt {
444            self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345);
445            return VOODOO_STABS[(self.rng >> 16) as usize % VOODOO_STABS.len()];
446        }
447        if alt {
448            self.def().alt.qav
449        } else {
450            self.def().primary.qav
451        }
452    }
453
454    /// Best weapon with ammo, used when the current one runs dry.
455    pub fn best_available(&self) -> usize {
456        for w in [4, 3, 8, 5, 2, 7, 9, 6, 1] {
457            if self.have[w] && self.has_ammo(w) {
458                return w;
459            }
460        }
461        1
462    }
463
464    fn try_fire(&mut self, alt: bool) -> bool {
465        // The sawed-off's alternate fire needs both barrels; with one loaded it fires that one.
466        let alt = alt && !(self.current == 3 && self.barrels < 2);
467        if self.has_ammo_for(self.current, alt) {
468            self.alt = alt;
469            let q = self.fire_qav(alt);
470            self.start(WeaponState::Firing, q);
471            true
472        } else if alt && self.has_ammo_for(self.current, false) {
473            self.try_fire(false)
474        } else {
475            let b = self.best_available();
476            self.select(b);
477            false
478        }
479    }
480
481    /// Advances one tick. `qav_len(id)` returns the animation length in ticks.
482    /// Returns true when an attack animation just started.
483    pub fn tick(&mut self, fire_held: bool, alt_held: bool, qav_len: impl Fn(u32) -> i32) -> bool {
484        self.qav_time += 1;
485        let done = self.qav_time >= qav_len(self.qav);
486        let mut started = false;
487        match self.state {
488            WeaponState::Raising if done => {
489                let q = self.idle_qav();
490                self.start(WeaponState::Ready, q)
491            }
492            WeaponState::Lowering if done => {
493                self.current = self.pending;
494                let q = self.up_qav();
495                self.start(WeaponState::Raising, q);
496            }
497            WeaponState::Reloading if done => {
498                self.barrels = 2;
499                let q = self.idle_qav();
500                self.start(WeaponState::Ready, q);
501            }
502            WeaponState::Firing if done => {
503                if self.current == 3 && self.barrels == 0 && self.ammo[ammo::SHELLS] > 0 && self.dual().is_none() {
504                    self.start(WeaponState::Reloading, SHOT_RELOAD);
505                } else if (fire_held || alt_held) && self.mode().auto && self.has_ammo_for(self.current, self.alt) {
506                    let alt = self.alt;
507                    started = self.try_fire(alt);
508                } else {
509                    let q = self.idle_qav();
510                    self.start(WeaponState::Ready, q);
511                }
512            }
513            WeaponState::Ready => {
514                if done {
515                    self.qav_time = 0; // loop idle
516                    self.last_frame = -1;
517                }
518                if self.current == 3 && self.barrels == 0 && self.ammo[ammo::SHELLS] > 0 {
519                    self.start(WeaponState::Reloading, SHOT_RELOAD);
520                } else if alt_held {
521                    started = self.try_fire(true);
522                } else if fire_held {
523                    started = self.try_fire(false);
524                }
525            }
526            _ => {}
527        }
528        started
529    }
530
531    /// Consumes ammo for one shot of the running attack; false if empty.
532    pub fn consume(&mut self) -> bool {
533        let d = self.def();
534        let per = self.mode().per_shot;
535        if d.ammo != ammo::NONE {
536            if self.ammo[d.ammo] < per.max(1) {
537                return false;
538            }
539            self.ammo[d.ammo] -= per;
540        }
541        if self.current == 3 {
542            self.barrels = self.barrels.saturating_sub(if self.alt { 2 } else { 1 });
543            if self.ammo[ammo::SHELLS] < self.barrels as i32 {
544                self.barrels = self.ammo[ammo::SHELLS] as u8;
545            }
546        }
547        true
548    }
549
550    /// Shots per trigger pull (dual-wielding doubles them).
551    pub fn shots(&self) -> i32 {
552        if self.dual().is_some() {
553            2
554        } else {
555            1
556        }
557    }
558}
559
560#[cfg(test)]
561mod tests {
562    use super::*;
563
564    fn ready(a: &mut Arsenal) {
565        for _ in 0..40 {
566            a.tick(false, false, |_| 10);
567        }
568    }
569
570    #[test]
571    fn raise_fire_and_switch() {
572        let mut a = Arsenal::default();
573        ready(&mut a);
574        assert_eq!(a.state, WeaponState::Ready);
575        assert!(a.tick(true, false, |_| 10), "fire starts");
576        assert_eq!(a.state, WeaponState::Firing);
577        assert!(a.give_weapon(3, 8));
578        assert_eq!(a.ammo[ammo::SHELLS], 8);
579        ready(&mut a);
580        a.select(3);
581        ready(&mut a);
582        assert_eq!(a.current, 3);
583    }
584
585    #[test]
586    fn shotgun_barrels_and_reload() {
587        let mut a = Arsenal::default();
588        a.give_weapon(3, 10);
589        ready(&mut a);
590        assert_eq!(a.current, 3);
591        assert!(a.tick(false, true, |_| 10));
592        assert_eq!(a.qav, 56, "alternate fire uses both barrels");
593        assert!(a.consume());
594        assert_eq!((a.barrels, a.ammo[ammo::SHELLS]), (0, 8));
595        for _ in 0..11 {
596            a.tick(false, false, |_| 10);
597        }
598        assert_eq!(a.state, WeaponState::Reloading);
599        ready(&mut a);
600        assert_eq!(a.barrels, 2);
601        assert!(a.tick(true, false, |_| 10));
602        assert_eq!(a.qav, SHOT_FIRE1);
603        a.consume();
604        ready(&mut a);
605        assert!(a.tick(true, false, |_| 10));
606        assert_eq!(a.qav, SHOT_FIRE2, "second barrel");
607    }
608
609    #[test]
610    fn empty_weapon_switches_away() {
611        let mut a = Arsenal::default();
612        a.have[4] = true;
613        a.current = 4;
614        a.state = WeaponState::Ready;
615        a.tick(true, false, |_| 10);
616        assert_eq!(a.state, WeaponState::Lowering);
617        assert_eq!(a.pending, 1);
618    }
619
620    #[test]
621    fn akimbo_uses_dual_animations() {
622        let mut a = Arsenal::default();
623        a.give_weapon(4, 100);
624        a.akimbo = true;
625        ready(&mut a);
626        assert_eq!(a.qav, 70);
627        a.tick(true, false, |_| 10);
628        assert_eq!(a.qav, 71);
629        assert_eq!(a.shots(), 2);
630    }
631}