neurodoom 0.6.7

Deterministic no_std Doom engine with semantic and depth perception buffers for AI
Documentation
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
//! Classic Doom game rules — the built-in `GameRules` implementation.
//!
//! Uses the `game_data` tables (mobjinfo, states) for entity behavior,
//! Doom's physics for movement/collision, and sector specials for doors/lifts.
//! This is the "battery included" experience for single-player Doom.

use crate::combat;
use crate::game_data::{ActionId, EntityType, MobjFlag, StateNum};
use crate::types::Card;
use crate::types::{AmmoType, WeaponType};
use crate::map::MapData;
use crate::math::*;
use crate::rules::{GameRules, PlayerAction, TouchResult, WorldAction};
use crate::types::Button;
use crate::world::{Entity, EntityId, PeerId, World};

/// Behavior categories for classic Doom entities.
#[derive(Clone, Copy, PartialEq, Eq, Hash, Debug)]
pub enum ClassicBehavior {
    /// Player-controlled entity.
    Player,
    /// Monster with AI (A_Chase, A_Look, etc).
    Monster,
    /// Pickup item (health, ammo, weapons, keys).
    Item,
    /// Projectile (rocket, plasma, etc).
    Projectile,
    /// No autonomous behavior (decoration, corpse).
    Inert,
    /// Externally controlled (network puppet).
    Puppet,
}

/// Classic Doom rules using game_data state machines.
pub struct ClassicDoomRules;

/// Classic-Doom-specific behavior callbacks, used internally by
/// `ClassicDoomRules::tick`. These are inherent methods (not trait
/// methods) because the engine doesn't call them — only this rules
/// implementation does. Custom `GameRules` impls don't need to provide
/// them at all, and can organize their internals however they like.
impl ClassicDoomRules {
    /// Classify an entity into its behavior category.
    pub fn behavior_for(entity: &Entity) -> ClassicBehavior {
        if entity.entity_type == EntityType(0) {
            return ClassicBehavior::Player;
        }
        if entity.flags.contains(MobjFlag::Shootable) && entity.flags.contains(MobjFlag::CountKill) {
            return ClassicBehavior::Monster;
        }
        if entity.flags.contains(MobjFlag::Special) {
            return ClassicBehavior::Item;
        }
        if entity.flags.contains(MobjFlag::Missile) {
            return ClassicBehavior::Projectile;
        }
        ClassicBehavior::Inert
    }

    /// Advance an entity's state machine for one tick.
    pub fn think(behavior: ClassicBehavior, entity: &mut Entity) -> ActionId {
        match behavior {
            ClassicBehavior::Player | ClassicBehavior::Puppet => ActionId::NONE,
            ClassicBehavior::Monster
            | ClassicBehavior::Projectile
            | ClassicBehavior::Item
            | ClassicBehavior::Inert => combat::advance_state(entity),
        }
    }

    /// Classify a touch between `entity` and `other`.
    pub fn on_touch(behavior: ClassicBehavior, entity: &Entity, other: &Entity) -> TouchResult {
        match behavior {
            ClassicBehavior::Item => {
                if other.entity_type == EntityType(0) {
                    TouchResult::PickedUp
                } else {
                    TouchResult::Nothing
                }
            }
            _ => {
                if entity.flags.contains(MobjFlag::Solid) {
                    TouchResult::Blocked
                } else {
                    TouchResult::Nothing
                }
            }
        }
    }

    /// Apply damage to an entity outside the normal combat path (e.g.
    /// external damage sources). Returns actual damage dealt.
    pub fn on_damage(entity: &mut Entity, damage: i32) -> i32 {
        if !entity.flags.contains(MobjFlag::Shootable) {
            return 0;
        }
        entity.health -= damage;
        if entity.health <= 0 {
            if let Some(info) = entity.entity_type.info() {
                entity.flags.remove(MobjFlag::Shootable | MobjFlag::Solid);
                combat::set_entity_state(entity, info.deathstate);
            }
        } else if let Some(info) = entity.entity_type.info()
            && !info.painstate.is_null()
        {
            combat::set_entity_state(entity, info.painstate);
        }
        damage
    }
}

impl GameRules for ClassicDoomRules {
    fn tick(
        &self,
        world: &mut World,
        map: &MapData,
        player_actions: &[(PeerId, PlayerAction)],
        _world_actions: &[WorldAction],
    ) {
        // Apply player inputs
        for (peer, action) in player_actions {
            if let Some(pid) = world.controlled_by(*peer) {
                // Dead players don't receive input — their entity continues
                // through the death animation via tick_entities below.
                let alive = world.get(pid).is_some_and(|e| e.health > 0);
                if !alive {
                    continue;
                }

                combat::apply_player_input(world, map, pid, action);

                // Use button — activate doors/switches/exits (debounced)
                let use_pressed = action.buttons.contains(Button::Use);
                let was_down = world.player_state(pid).is_none_or(|ps| ps.use_down);
                if use_pressed && !was_down {
                    combat::use_lines(world, map, pid);
                }
                if let Some(ps) = world.player_state_mut(pid) {
                    ps.use_down = use_pressed;
                }

                // Check for secret sector
                combat::check_player_sector(world, map, pid);

                // Update weapon bob from player momentum
                combat::update_weapon_bob(world, pid);

                // Advance weapon psprite state machine
                advance_weapon(world, map, pid, action);
            }
        }

        // Check for pickups (players touching items)
        check_pickups(world);

        // Run entity behaviors and physics
        combat::tick_entities(world, map, dispatch_action);

        world.tick += 1;
    }

    fn validate_player_action(
        &self,
        _world: &World,
        _player: PeerId,
        action: &PlayerAction,
    ) -> bool {
        // Basic validation: movement values in range
        action.forward_move.abs() <= 25 && action.side_move.abs() <= 20
    }

    fn validate_world_action(&self, _world: &World, _action: &WorldAction) -> bool {
        true
    }
}

// --- Doom-specific helpers ---

/// Check for and process item pickups — players touching Special entities.
fn check_pickups(world: &mut World) {
    use crate::types::{doomednum as dn, AmmoType, ArmorType, Card, WeaponType};

    // Snapshot player positions from controller map
    let player_ids: alloc::vec::Vec<EntityId> = world.controlled_entities().collect();
    let mut players = alloc::vec::Vec::with_capacity(player_ids.len());
    for &pid in &player_ids {
        if let Some(e) = world.get(pid) {
            players.push((e.id, e.x, e.y, e.radius));
        }
    }

    // Find items touched by a player: (item_id, item_entity_type, player_id)
    const MAX_PICKUPS: usize = 16;
    let mut touches = [(EntityId(0), EntityType(0), EntityId(0)); MAX_PICKUPS];
    let mut n_touches = 0;

    for e in world.iter() {
        if !e.flags.contains(MobjFlag::Special) { continue; }
        for &(pid, px, py, pradius) in &players {
            let dx = (e.x - px).abs();
            let dy = (e.y - py).abs();
            let touch_dist = pradius + e.radius;
            if dx < touch_dist
                && dy < touch_dist
                && let Some(slot) = touches.get_mut(n_touches)
            {
                *slot = (e.id, e.entity_type, pid);
                n_touches = n_touches.saturating_add(1);
                break;
            }
        }
    }

    for &(item_id, item_type, player_id) in touches.iter().take(n_touches) {
        let Some(info) = item_type.info() else { continue };
        let dnum = info.doomednum;

        // Check if pickup can be applied (some are conditional on current state)
        let picked_up = match dnum {
            // Health
            dn::HEALTH_BONUS => world.get_mut(player_id).is_some_and(|e| {
                e.health = (e.health + 1).min(200);
                true
            }),
            dn::STIMPACK => match world.get(player_id) {
                Some(e) if e.health < 100 => world.get_mut(player_id).is_some_and(|e| {
                    e.health = (e.health + 10).min(100);
                    true
                }),
                _ => false,
            },
            dn::MEDIKIT => match world.get(player_id) {
                Some(e) if e.health < 100 => world.get_mut(player_id).is_some_and(|e| {
                    e.health = (e.health + 25).min(100);
                    true
                }),
                _ => false,
            },
            dn::SOUL_SPHERE => world.get_mut(player_id).is_some_and(|e| {
                e.health = (e.health + 100).min(200);
                true
            }),

            // Armor
            dn::ARMOR_BONUS => {
                if let Some(ps) = world.player_state_mut(player_id) {
                    ps.armor_points = (ps.armor_points + 1).min(200);
                    if ps.armor_type == ArmorType::None { ps.armor_type = ArmorType::Green; }
                    true
                } else { false }
            }
            dn::GREEN_ARMOR => {
                if let Some(ps) = world.player_state_mut(player_id) {
                    if ps.armor_points >= 100 { false }
                    else { ps.armor_type = ArmorType::Green; ps.armor_points = 100; true }
                } else { false }
            }
            dn::BLUE_ARMOR => {
                if let Some(ps) = world.player_state_mut(player_id) {
                    if ps.armor_points >= 200 { false }
                    else { ps.armor_type = ArmorType::Blue; ps.armor_points = 200; true }
                } else { false }
            }

            // Ammo
            dn::CLIP => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Bullets, 10)),
            dn::BOX_OF_AMMO => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Bullets, 50)),
            dn::SHELLS => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Shells, 4)),
            dn::SHELL_BOX => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Shells, 20)),
            dn::ROCKET => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Rockets, 1)),
            dn::ROCKET_BOX => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Rockets, 5)),
            dn::CELL => world.player_state_mut(player_id).is_some_and(|ps| ps.give_ammo(AmmoType::Cells, 20)),

            // Weapons (give weapon + starting ammo)
            dn::SHOTGUN => give_weapon(world, player_id, WeaponType::Shotgun, AmmoType::Shells, 8),
            dn::CHAINGUN => give_weapon(world, player_id, WeaponType::Chaingun, AmmoType::Bullets, 20),
            dn::ROCKET_LAUNCHER => give_weapon(world, player_id, WeaponType::RocketLauncher, AmmoType::Rockets, 2),
            dn::PLASMA_RIFLE => give_weapon(world, player_id, WeaponType::PlasmaRifle, AmmoType::Cells, 40),
            dn::BFG => give_weapon(world, player_id, WeaponType::Bfg, AmmoType::Cells, 40),
            dn::BACKPACK => {
                if let Some(ps) = world.player_state_mut(player_id) {
                    ps.double_max_ammo();
                    ps.give_ammo(AmmoType::Bullets, 10);
                    ps.give_ammo(AmmoType::Shells, 4);
                    ps.give_ammo(AmmoType::Rockets, 1);
                    ps.give_ammo(AmmoType::Cells, 20);
                    true
                } else { false }
            }

            // Keys (always picked up if player exists)
            dn::BLUE_CARD => grant_card(world, player_id, Card::BlueCard),
            dn::YELLOW_CARD => grant_card(world, player_id, Card::YellowCard),
            dn::RED_CARD => grant_card(world, player_id, Card::RedCard),
            dn::BLUE_SKULL => grant_card(world, player_id, Card::BlueSkull),
            dn::YELLOW_SKULL => grant_card(world, player_id, Card::YellowSkull),
            dn::RED_SKULL => grant_card(world, player_id, Card::RedSkull),

            // Unknown item — pick up anyway
            _ => true,
        };

        if picked_up {
            world.remove(item_id);
        }
    }
}

/// Grant `weapon` + `amount` starting ammo to `player`. Returns true if
/// the player exists (the item should be consumed).
fn give_weapon(
    world: &mut World,
    player: EntityId,
    weapon: WeaponType,
    ammo: AmmoType,
    amount: i32,
) -> bool {
    if let Some(ps) = world.player_state_mut(player) {
        ps.give_ammo(ammo, amount);
        ps.grant_weapon(weapon);
        true
    } else {
        false
    }
}

/// Grant a keycard/skull to `player`. Always "picked up" (returns true)
/// even if the card slot is already set — matches Doom pickup semantics.
fn grant_card(world: &mut World, player: EntityId, card: Card) -> bool {
    if let Some(ps) = world.player_state_mut(player) {
        ps.grant_card(card);
    }
    true
}

/// Dispatch an action function by ID.
fn dispatch_action(action_id: ActionId, world: &mut World, map: &MapData, id: EntityId) {
    match action_id {
        ActionId::A_LOOK => combat::a_look(world, map, id),
        ActionId::A_CHASE => combat::a_chase(world, map, id),
        ActionId::A_FACE_TARGET => combat::a_face_target(world, id),
        ActionId::A_FALL => a_fall(world, id),
        ActionId::A_POS_ATTACK => a_pos_attack(world, map, id),
        ActionId::A_SPOS_ATTACK => a_spos_attack(world, map, id),
        ActionId::A_TROOP_ATTACK => a_troop_attack(world, id),
        ActionId::A_SARG_ATTACK => a_sarg_attack(world, id),
        ActionId::A_SKULL_ATTACK => a_skull_attack(world, id),
        ActionId::A_EXPLODE => a_explode(world, id),
        ActionId::A_BFG_SPRAY => a_bfg_spray(world, map, id),
        ActionId::A_PAIN | ActionId::A_SCREAM | ActionId::NONE => {}
        _ => {} // unimplemented actions are no-ops
    }
}


/// A_Fall: clear SOLID and SHOOTABLE on death.
fn a_fall(world: &mut World, id: EntityId) {
    if let Some(e) = world.get_mut(id) {
        e.flags.remove(MobjFlag::Solid | MobjFlag::Shootable);
    }
}

/// A_PosAttack: Zombieman hitscan. Doom order: P_Random spread (2 calls),
/// then damage (1 call). Getting the order right matters because the PRNG
/// table is globally shared — any reversal desyncs every downstream
/// random draw in the same tic.
fn a_pos_attack(world: &mut World, map: &MapData, id: EntityId) {
    combat::a_face_target(world, id);
    let spread = (world.p_random() - world.p_random()) << 20;
    let damage = (world.p_random() % 5 + 1) * 3;
    monster_hitscan(world, map, id, damage, spread);
}

/// A_SPosAttack: Shotgun guy — 3 pellets, each (1..=5)*3 = 3-15 damage.
/// Per-pellet Doom order: spread (2 calls), then damage (1 call).
fn a_spos_attack(world: &mut World, map: &MapData, id: EntityId) {
    combat::a_face_target(world, id);
    for _ in 0..3 {
        let spread = (world.p_random() - world.p_random()) << 20;
        let damage = (world.p_random() % 5 + 1) * 3;
        monster_hitscan(world, map, id, damage, spread);
    }
}

/// A_TroopAttack: Imp melee or fireball. Doom uses `(P_Random()%8 + 1)*3`
/// for the melee damage — a random call, not the entity ID.
fn a_troop_attack(world: &mut World, id: EntityId) {
    let Some(entity) = world.get(id) else { return };
    let Some(target_id) = entity.target else { return };
    combat::a_face_target(world, id);
    if combat::check_melee_range(world, id, target_id) {
        let damage = (world.p_random() % 8 + 1) * 3;
        combat::apply_damage_to(world, target_id, damage, Some(id));
    } else {
        combat::spawn_projectile(world, id, target_id, crate::game_data::MT_TROOPSHOT);
    }
}

/// A_SargAttack: Demon melee bite. Doom: `(P_Random()%10 + 1)*4`.
fn a_sarg_attack(world: &mut World, id: EntityId) {
    let Some(entity) = world.get(id) else { return };
    let Some(target_id) = entity.target else { return };
    combat::a_face_target(world, id);
    if combat::check_melee_range(world, id, target_id) {
        let damage = (world.p_random() % 10 + 1) * 4;
        combat::apply_damage_to(world, target_id, damage, Some(id));
    }
}

/// A_SkullAttack: Lost Soul charge.
fn a_skull_attack(world: &mut World, id: EntityId) {
    let Some(entity) = world.get(id) else { return };
    let Some(target_id) = entity.target else { return };
    combat::a_face_target(world, id);

    let Some(target) = world.get(target_id) else { return };
    let Some(entity) = world.get(id) else { return };
    let dx = target.x - entity.x;
    let dy = target.y - entity.y;
    let dist = ((dx.abs() as i64 + dy.abs() as i64) >> FRACBITS).max(1) as i32;
    let speed = 20 * FRACUNIT;
    let momx = fixed_div(fixed_mul(dx >> FRACBITS, speed), dist);
    let momy = fixed_div(fixed_mul(dy >> FRACBITS, speed), dist);

    if let Some(e) = world.get_mut(id) {
        e.momx = momx;
        e.momy = momy;
    }
}

/// A_Explode: radius damage (barrels, rockets). 128 damage at center, falls off.
fn a_explode(world: &mut World, id: EntityId) {
    combat::radius_damage(world, id, 128 * FRACUNIT, 128);
}

/// A_BFGSpray: the green "tracer" attack fired by the BFG ball's death
/// state. Doom fans 40 rays over 90° centered on the ball's travel
/// direction. For each ray that finds a shootable target within ~1024
/// units, damage is rolled as the sum of fifteen `(P_Random() & 7) + 1`
/// draws (range 15..=120), and that damage is attributed to the ball's
/// original shooter (stored in `mo->target`).
fn a_bfg_spray(world: &mut World, map: &MapData, id: EntityId) {
    // Snapshot the ball's angle and its originator (the shooter).
    let (ball_angle, source_id) = match world.get(id) {
        Some(e) => (e.angle, e.target),
        None => return,
    };
    let Some(source_id) = source_id else { return };

    // The shooter's eye-level ray origin.
    let (sx, sy, sz) = match world.get(source_id) {
        Some(s) => (s.x, s.y, s.z + s.height - (s.height >> 2)),
        None => return,
    };

    const STEPS: u32 = 40;
    const BFG_RANGE: Fixed = 16 * 64 * FRACUNIT; // 1024 map units
    const STEP_ANGLE: u32 = ANG90 / STEPS;
    let fan_start = ball_angle.wrapping_sub(ANG90 / 2);

    for i in 0..STEPS {
        let ray_angle = fan_start.wrapping_add(STEP_ANGLE.wrapping_mul(i));

        // Pick nearest shootable in that ray direction, with LOS.
        let tolerance = ANG90 / 18;
        let mut best_dist = i64::MAX;
        let mut best_id = None;
        for e in world.iter() {
            if e.id == source_id || e.id == id || !e.flags.contains(MobjFlag::Shootable) {
                continue;
            }
            let dx = e.x - sx;
            let dy = e.y - sy;
            let dist = dx.abs() as i64 + dy.abs() as i64;
            if dist <= 0 || dist > BFG_RANGE as i64 {
                continue;
            }
            let to_angle = crate::map::point_to_angle(dx, dy);
            let diff = to_angle.wrapping_sub(ray_angle);
            let within = diff <= tolerance || diff >= 0u32.wrapping_sub(tolerance);
            if !within {
                continue;
            }
            if dist < best_dist
                && crate::physics::check_sight(map, sx, sy, sz, e.x, e.y, e.z, e.height)
            {
                best_dist = dist;
                best_id = Some(e.id);
            }
        }

        let Some(hit_id) = best_id else { continue };
        let mut damage = 0;
        for _ in 0..15 {
            damage += (world.p_random() & 7) + 1;
        }
        combat::apply_damage_to(world, hit_id, damage, Some(source_id));
    }
}

/// Monster hitscan: damage the target directly.
/// Monster hitscan. Computes the shooter's intended aim (entity angle +
/// random spread) and checks whether that aim cone actually covers the
/// target. Miss rate scales with range and spread — matches Doom's
/// `P_LineAttack` well enough that zombies at range aren't perfect
/// snipers (previously our version always hit, which slaughtered the
/// recorded player in seconds).
fn monster_hitscan(world: &mut World, map: &MapData, id: EntityId, damage: i32, spread: i32) {
    let (sx, sy, sz, s_height, aim_angle) = {
        let Some(entity) = world.get(id) else { return };
        (
            entity.x,
            entity.y,
            entity.z,
            entity.height,
            entity.angle.wrapping_add(spread as u32),
        )
    };
    let Some(target_id) = world.get(id).and_then(|e| e.target) else { return };
    let (tx, ty, tz, th) = {
        let Some(t) = world.get(target_id) else { return };
        (t.x, t.y, t.z, t.height)
    };

    // Is the target inside the aim cone?
    let to_angle = crate::map::point_to_angle(tx - sx, ty - sy);
    let tolerance = crate::math::ANG90 / 18; // ~5°
    let diff = to_angle.wrapping_sub(aim_angle);
    let within = diff <= tolerance || diff >= 0u32.wrapping_sub(tolerance);
    if !within {
        return; // shot passed wide of the target
    }

    // Line of sight — wall or obstacle between us?
    let eye_z = sz + s_height - (s_height >> 2);
    if !crate::physics::check_sight(map, sx, sy, eye_z, tx, ty, tz, th) {
        return;
    }

    combat::apply_damage_to(world, target_id, damage, Some(id));
}

// --- Weapon psprite ---

/// Advance the weapon psprite state machine and handle actions.
fn advance_weapon(world: &mut World, map: &MapData, pid: EntityId, action: &PlayerAction) {
    // Advance tics
    let action_id = {
        let Some(ps) = world.player_state_mut(pid) else { return };
        if ps.psp_tics != -1 {
            ps.psp_tics -= 1;
            if ps.psp_tics <= 0 {
                // Transition to next state
                let cur = ps.psp_state;
                let Some(st) = cur.get() else { return };
                let next = st.next_state;
                let Some(nst) = next.get() else { return };
                ps.psp_state = next;
                ps.psp_tics = nst.tics;
                nst.action
            } else {
                ActionId::NONE
            }
        } else {
            ActionId::NONE
        }
    };

    // Dispatch weapon action, chaining through state changes
    let mut cur_action = action_id;
    let mut chain = 0;
    while cur_action != ActionId::NONE && chain < 8 {
        let state_before = world.player_state(pid).map(|ps| ps.psp_state);
        psp_dispatch(cur_action, world, map, pid, action);
        let state_after = world.player_state(pid).map(|ps| ps.psp_state);
        cur_action = if state_after != state_before {
            state_after
                .and_then(|s| s.get())
                .map_or(ActionId::NONE, |st| st.action)
        } else {
            ActionId::NONE
        };
        chain += 1;
    }

    // Advance flash psprite
    if let Some(ps) = world.player_state_mut(pid)
        && !ps.flash_state.is_null() && ps.flash_tics > 0
    {
        ps.flash_tics -= 1;
        if ps.flash_tics <= 0 {
            let cur = ps.flash_state;
            if let Some(st) = cur.get() {
                let next = st.next_state;
                if next.is_null() || next == crate::game_data::StateNum(1) {
                    // S_LIGHTDONE or S_NULL — flash finished
                    ps.flash_state = crate::game_data::StateNum::NULL;
                } else if let Some(nst) = next.get() {
                    ps.flash_state = next;
                    ps.flash_tics = nst.tics;
                }
            }
        }
    }

    // Apply bob when in ready state (check current state's action for A_WeaponReady)
    let tick = world.tick;
    let Some(ps) = world.player_state(pid) else { return };
    let cur_state = ps.psp_state;
    if let Some(st) = cur_state.get()
        && st.action == ActionId::A_WEAPON_READY
    {
        let bob = ps.bob;
        let angle = ((128u32.wrapping_mul(tick)) as usize) & FINEMASK;
        let sx = FRACUNIT + fixed_mul(bob, finecosine(angle));
        let sy = combat::WEAPONTOP + fixed_mul(bob, finesine(angle & (FINEANGLES / 2 - 1)));
        if let Some(ps) = world.player_state_mut(pid) {
            ps.psp_sx = sx;
            ps.psp_sy = sy;
        }
    }
}

/// Weapon state table: (ready, down, up, fire1, flash) for each WeaponType.
fn weapon_states(weapon: WeaponType) -> (StateNum, StateNum, StateNum, StateNum, StateNum) {
    use crate::game_data::*;
    match weapon {
        WeaponType::Fist      => (S_PUNCH,   StateNum(3),  StateNum(4),  StateNum(5),  StateNum::NULL),
        WeaponType::Pistol    => (S_PISTOL,  StateNum(11), StateNum(12), StateNum(13), S_PISTOLFLASH),
        WeaponType::Shotgun   => (S_SGUN,    StateNum(19), StateNum(20), StateNum(21), StateNum(30)),
        WeaponType::Chaingun  => (StateNum(49), StateNum(50), StateNum(51), StateNum(52), StateNum(55)),
        WeaponType::RocketLauncher => (StateNum(57), StateNum(58), StateNum(59), StateNum(60), StateNum(63)),
        WeaponType::PlasmaRifle => (StateNum(74), StateNum(75), StateNum(76), StateNum(77), StateNum(79)),
        WeaponType::Bfg       => (StateNum(81), StateNum(82), StateNum(83), StateNum(84), StateNum(88)),
        WeaponType::Chainsaw  => (StateNum(67), StateNum(69), StateNum(70), StateNum(71), StateNum::NULL),
        WeaponType::SuperShotgun => (S_SGUN, StateNum(19), StateNum(20), StateNum(21), StateNum(30)), // fallback
    }
}

/// Dispatch a weapon psprite action.
fn psp_dispatch(
    action_id: ActionId,
    world: &mut World,
    map: &MapData,
    pid: EntityId,
    action: &PlayerAction,
) {
    match action_id {
        ActionId::A_WEAPON_READY => {
            // Check for weapon change
            let want = action.weapon_select;
            let new_weapon = match want {
                1 => Some(WeaponType::Fist),
                2 => Some(WeaponType::Pistol),
                3 => Some(WeaponType::Shotgun),
                4 => Some(WeaponType::Chaingun),
                5 => Some(WeaponType::RocketLauncher),
                6 => Some(WeaponType::PlasmaRifle),
                7 => Some(WeaponType::Bfg),
                8 => Some(WeaponType::Chainsaw),
                _ => None,
            };
            if let Some(new_weapon) = new_weapon {
                let owns = world.player_state(pid).is_some_and(|ps| {
                    ps.weapon_owned
                        .get(new_weapon as usize)
                        .copied()
                        .unwrap_or(false)
                });
                let cur = world.player_state(pid).map(|ps| ps.ready_weapon);
                if owns && cur != Some(new_weapon) {
                    if let Some(ps) = world.player_state_mut(pid) {
                        ps.pending_weapon = new_weapon;
                    }
                    // Start lowering current weapon
                    let cur_weapon = world.player_state(pid).map_or(WeaponType::Pistol, |ps| ps.ready_weapon);
                    let (_, down, _, _, _) = weapon_states(cur_weapon);
                    combat::psp_set_state(world, pid, down);
                    return;
                }
            }
            // Check for fire
            if action.buttons.contains(Button::Attack) {
                psp_fire_weapon(world, pid);
            }
        }
        ActionId::A_PUNCH => {
            // Doom A_Punch: damage, then a +/- spread draw. We don't use
            // the spread yet (our melee_attack is a straight cone), but
            // the P_Random calls are consumed to keep the index aligned
            // with the reference PRNG sequence.
            let damage = (world.p_random() % 10 + 1) * 2;
            let _spread = (world.p_random() - world.p_random()) << 18;
            combat::melee_attack(world, pid, damage, 64 * FRACUNIT);
        }
        ActionId::A_SAW => {
            // Same shape as A_Punch for RNG consumption.
            let damage = (world.p_random() % 10 + 1) * 2;
            let _spread = (world.p_random() - world.p_random()) << 18;
            combat::melee_attack(world, pid, damage, 64 * FRACUNIT + 16 * FRACUNIT);
        }
        ActionId::A_FIRE_PISTOL => {
            if !combat::use_ammo(world, pid, AmmoType::Bullets, 1) { return; }
            let damage = 5 * (world.p_random() % 3 + 1);
            let refire = world.player_state(pid).map_or(0, |ps| ps.refire_count);
            let spread = if refire > 0 { (world.p_random() - world.p_random()) << 18 } else { 0 };
            combat::hitscan_attack(world, map, pid, damage, spread, crate::game_data::MT_PUFF);
            psp_set_flash(world, pid);
        }
        ActionId::A_FIRE_SHOTGUN => {
            if !combat::use_ammo(world, pid, AmmoType::Shells, 1) { return; }
            for _ in 0..7 {
                let damage = 5 * (world.p_random() % 3 + 1);
                let spread = (world.p_random() - world.p_random()) << 18;
                combat::hitscan_attack(world, map, pid, damage, spread, crate::game_data::MT_PUFF);
            }
            psp_set_flash(world, pid);
        }
        ActionId::A_FIRE_CGUN => {
            if !combat::use_ammo(world, pid, AmmoType::Bullets, 1) { return; }
            let damage = 5 * (world.p_random() % 3 + 1);
            let refire = world.player_state(pid).map_or(0, |ps| ps.refire_count);
            let spread = if refire > 0 { (world.p_random() - world.p_random()) << 18 } else { 0 };
            combat::hitscan_attack(world, map, pid, damage, spread, crate::game_data::MT_PUFF);
            psp_set_flash(world, pid);
        }
        ActionId::A_FIRE_MISSILE => {
            if !combat::use_ammo(world, pid, AmmoType::Rockets, 1) { return; }
            combat::fire_player_projectile(world, pid, crate::game_data::MT_ROCKET);
            psp_set_flash(world, pid);
        }
        ActionId::A_FIRE_PLASMA => {
            if !combat::use_ammo(world, pid, AmmoType::Cells, 1) { return; }
            combat::fire_player_projectile(world, pid, crate::game_data::MT_PLASMA);
            psp_set_flash(world, pid);
        }
        ActionId::A_BFG_SOUND => {
            // BFG charge sound — no-op (no sound system). The real BFG
            // spray fires from the ball entity's death state, handled
            // in dispatch_action → a_bfg_spray.
        }
        ActionId::A_CHECK_RELOAD => {
            // Post-rocket-fire check — no-op (ammo system not enforced yet)
        }
        ActionId::A_REFIRE => {
            if action.buttons.contains(Button::Attack) {
                if let Some(ps) = world.player_state_mut(pid) {
                    ps.refire_count += 1;
                }
                psp_fire_weapon(world, pid);
            } else if let Some(ps) = world.player_state_mut(pid) {
                ps.refire_count = 0;
            }
        }
        ActionId::A_LOWER => {
            if let Some(ps) = world.player_state_mut(pid) {
                ps.psp_sy += combat::RAISESPEED;
                if ps.psp_sy >= combat::WEAPONBOTTOM {
                    // Switch to pending weapon
                    let new_weapon = ps.pending_weapon;
                    ps.ready_weapon = new_weapon;
                    let (_, _, up, _, _) = weapon_states(new_weapon);
                    ps.psp_state = up;
                    if let Some(st) = up.get() {
                        ps.psp_tics = st.tics;
                    }
                }
            }
        }
        ActionId::A_RAISE => {
            if let Some(ps) = world.player_state_mut(pid) {
                ps.psp_sy -= combat::RAISESPEED;
                if ps.psp_sy <= combat::WEAPONTOP {
                    ps.psp_sy = combat::WEAPONTOP;
                    let weapon = ps.ready_weapon;
                    let (ready, _, _, _, _) = weapon_states(weapon);
                    ps.psp_state = ready;
                    if let Some(st) = ready.get() {
                        ps.psp_tics = st.tics;
                    }
                }
            }
        }
        ActionId::A_LIGHT0 | ActionId::A_LIGHT1 | ActionId::A_LIGHT2 => {}
        ActionId::NONE => {}
        _ => {}
    }
}

/// Transition weapon to fire state (resolves fire state from Doom weapon table).
fn psp_fire_weapon(world: &mut World, pid: EntityId) {
    let weapon = world.player_state(pid).map_or(WeaponType::Pistol, |ps| ps.ready_weapon);
    let (_, _, _, fire, _) = weapon_states(weapon);
    combat::psp_set_state(world, pid, fire);
}

/// Set the muzzle flash for the current weapon.
fn psp_set_flash(world: &mut World, pid: EntityId) {
    let weapon = world.player_state(pid).map_or(WeaponType::Pistol, |ps| ps.ready_weapon);
    let (_, _, _, _, flash) = weapon_states(weapon);
    if !flash.is_null()
        && let Some(ps) = world.player_state_mut(pid)
    {
        ps.flash_state = flash;
        if let Some(st) = flash.get() {
            ps.flash_tics = st.tics;
        }
    }
}