Skip to main content

ob_game/
game.rs

1//! Top-level game state for one level: world, player, weapons, actors and triggers.
2
3use crate::anim::{AnimLib, SEQ_REMOVE};
4use crate::dudes::{dude_info, is_dude, Attack, DudeInfo, ProjKind};
5use crate::inventory::{InvItem, Inventory, Powerups};
6use crate::items::{pickup_of, Pickup, Timed};
7use crate::player::{Input, Player};
8use crate::resources::Resources;
9use crate::triggers::{cmd, Notice, Obj, Triggers};
10use crate::weapons::{Arsenal, Fire, WeaponState};
11use crate::world::{stat, World};
12use ob_engine::collide::{self, CircleObstacle, HitCylinder, Mover, TraceTarget};
13use ob_engine::geom::{ang_to_rad, ray_segment};
14use ob_engine::map::{Map, Sprite};
15use ob_engine::render::{Camera, SpriteDraw, SPR_BLOCK, SPR_CENTER, SPR_INVISIBLE, SPR_XFLIP, SPR_YFLIP};
16use std::collections::HashMap;
17use std::io;
18
19mod ai;
20pub mod save;
21
22/// Game clock rate.
23pub const TICK_RATE: f64 = 120.0;
24/// Reach of the "use" action in xy units.
25pub const USE_RANGE: f64 = 768.0;
26/// Pseudo sprite id used for the player in traces.
27pub const PLAYER_ID: usize = usize::MAX;
28/// Breath before drowning starts.
29pub const AIR_SECONDS: f64 = 20.0;
30
31/// Projectile sprite types (OpenBlood-internal, outside Blood's editor ranges).
32const PROJ_BASE: i16 = 3000;
33
34/// Thing types with special handling.
35const TNT_BARREL: i16 = 400;
36const WALL_CRACK: i16 = 408;
37const EXPLODER: i16 = 459;
38
39/// Events surfaced to the front end (sounds, messages, level changes).
40#[derive(Debug, Clone, PartialEq)]
41pub enum GameEvent {
42    Message(String),
43    LevelExit {
44        secret: bool,
45    },
46    UseFailed,
47    SectorSound {
48        sector: usize,
49        opening: bool,
50        start: bool,
51    },
52    Switch,
53    /// Play sound `id`; `at` is a world position or `None` for the player's own sounds.
54    Sound {
55        id: i32,
56        at: Option<(f64, f64, f64)>,
57    },
58    PlayerHurt(i32),
59    PlayerDied,
60}
61
62#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq, Eq)]
63pub enum Ai {
64    /// Inert until provoked (statues) or approached (buried zombies).
65    Dormant,
66    /// Playing the rise-from-the-ground animation.
67    Rise,
68    /// Running away (innocents).
69    Flee,
70    Idle,
71    Chase,
72    Attack,
73    Recoil,
74    Dying,
75    Dead,
76}
77
78pub struct Game {
79    pub world: World,
80    pub player: Player,
81    pub triggers: Triggers,
82    pub arsenal: Arsenal,
83    pub anims: AnimLib,
84    pub clock: i32,
85    pub events: Vec<GameEvent>,
86    pub messages: Vec<String>,
87    pub kills: i32,
88    pub total_kills: i32,
89    pub damage_flash: f64,
90    pub pickup_flash: f64,
91    pub skill: i32,
92    last_sector: i32,
93    acc: f64,
94    use_down: bool,
95    rng: u32,
96    ai: Vec<Ai>,
97    attack_cd: Vec<f64>,
98    pic_for_type: HashMap<i16, i16>,
99    weapon_switch_down: bool,
100    level_messages: HashMap<u32, String>,
101    pub inventory: Inventory,
102    pub powerups: Powerups,
103    /// Seconds of breath left underwater.
104    pub air: f64,
105    inv_keys: (bool, bool, bool),
106    /// Dude was hurt (ambushers/guards start moving).
107    provoked: Vec<bool>,
108    /// Cached line-of-sight to the player.
109    sees: Vec<bool>,
110    /// Damage currently being applied comes from burning.
111    burn_kill: bool,
112    /// Sprite positions and player eye before the last tick, for drawing frames between
113    /// ticks (smooth motion at any frame rate).
114    prev_xyz: Vec<(i32, i32, i32)>,
115    prev_eye: (f64, f64, f64),
116    /// The level-start channel has been broadcast.
117    pub started: bool,
118}
119
120/// Sprite types that are editor-only markers.
121pub fn is_marker_type(t: i16) -> bool {
122    (1..=19).contains(&t)
123}
124
125/// Vertical extents of a sprite as drawn: (top z, bottom z).
126pub fn sprite_extents(res: &Resources, s: &Sprite) -> (f64, f64) {
127    let t = res.tiles.get(s.picnum as i32);
128    let h = t.height as f64 * s.yrepeat as f64 * 4.0;
129    let mut bot = s.z as f64;
130    if s.cstat & SPR_CENTER != 0 {
131        bot += h * 0.5;
132    }
133    bot -= (t.anm.yoffset as f64 + s.yoffset as f64) * s.yrepeat as f64 * 4.0;
134    (bot - h, bot)
135}
136
137impl Game {
138    pub fn load_level(res: &Resources, name: &str) -> io::Result<Game> {
139        Self::load_level_skill(res, name, 2)
140    }
141
142    pub fn load_level_skill(res: &Resources, name: &str, skill: i32) -> io::Result<Game> {
143        let bytes = res
144            .blood
145            .read_name(&format!("{}.MAP", name.to_ascii_uppercase()))
146            .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, format!("map {name} not found")))?;
147        let map = Map::parse(&bytes)?;
148        let mut world = World::from_map(&name.to_ascii_uppercase(), map);
149        let mut pic_for_type = HashMap::new();
150        for i in 0..world.sprites.len() {
151            let s = world.sprites[i].clone();
152            pic_for_type.entry(s.lotag).or_insert(s.picnum);
153            if is_marker_type(s.lotag) || matches!(s.statnum, stat::MARKER | stat::PATH_MARKER | stat::AMBIENCE) {
154                world.sprites[i].cstat |= SPR_INVISIBLE;
155            }
156            // Difficulty / game-mode filtering: launch_skill bit set = absent on that skill.
157            if let Some(x) = world.xsprite(i) {
158                let skill_bit = 1u8 << skill.clamp(0, 4);
159                if x.launch_skill & skill_bit != 0 || x.launch_single {
160                    world.delete_sprite(i);
161                    continue;
162                }
163            }
164            // Exploder markers (type 459) are never drawn; they explode when switched on.
165            if s.lotag == EXPLODER {
166                world.sprites[i].cstat |= SPR_INVISIBLE;
167            }
168        }
169        let player = Player::spawn(&world);
170        let mut triggers = Triggers::new(&world);
171        triggers.init_level(&mut world);
172        let last_sector = player.sector;
173        let n = world.sprites.len();
174        let mut g = Game {
175            world,
176            player,
177            triggers,
178            arsenal: Arsenal::default(),
179            anims: AnimLib::new(&res.blood),
180            clock: 0,
181            events: Vec::new(),
182            messages: Vec::new(),
183            kills: 0,
184            total_kills: 0,
185            damage_flash: 0.0,
186            pickup_flash: 0.0,
187            skill,
188            last_sector,
189            acc: 0.0,
190            use_down: false,
191            rng: 0x1234_5678,
192            ai: vec![Ai::Idle; n],
193            attack_cd: vec![0.0; n],
194            pic_for_type,
195            weapon_switch_down: false,
196            level_messages: res.ini.map(name).map(|m| m.messages.clone()).unwrap_or_default(),
197            inventory: Inventory::default(),
198            powerups: Powerups::default(),
199            air: AIR_SECONDS,
200            inv_keys: (false, false, false),
201            provoked: vec![false; n],
202            sees: vec![false; n],
203            burn_kill: false,
204            prev_xyz: Vec::new(),
205            prev_eye: (0.0, 0.0, 0.0),
206            started: false,
207        };
208        // The level-start broadcast is sent on the player's first input (see `tick`).
209        // Dudes start in their idle animation.
210        for i in 0..n {
211            let s = &g.world.sprites[i];
212            if s.statnum != stat::FREE && is_dude(s.lotag) {
213                if let Some(info) = dude_info(s.lotag) {
214                    g.world.rt[i].health = if g.world.rt[i].health > 0 {
215                        g.world.rt[i].health
216                    } else {
217                        info.health
218                    };
219                    g.total_kills += if s.lotag == 245 { 0 } else { 1 };
220                    // Maps store the sprite as drawn; the game keeps dude z at the feet.
221                    if s.cstat & 48 == 0 {
222                        let (top, bot) = sprite_extents(res, s);
223                        g.world.sprites[i].z = bot.round() as i32;
224                        g.world.rt[i].eye = ((bot - top) * 0.85) as i32;
225                    }
226                    g.world.rt[i].home_ang = g.world.sprites[i].ang;
227                    g.play_dude_anim(res, i, "I1");
228                    g.ai[i] = g.initial_ai(i);
229                }
230            }
231        }
232        g.fix_sprite_sectors();
233        Ok(g)
234    }
235
236    /// Some maps store pickups, dudes and blocking sprites with the sector number of a
237    /// neighbour, or (in stacked rooms) of a sector at another height. Such a sprite would
238    /// collide, light and draw with the wrong floor, or never be drawn. Reassign it to the
239    /// sector that contains its position and height (or at least its position).
240    fn fix_sprite_sectors(&mut self) {
241        const SLACK: f64 = 256.0;
242        let w = &self.world;
243        let mut moves = Vec::new();
244        for (i, s) in w.sprites.iter().enumerate() {
245            if s.statnum == stat::FREE || s.sectnum < 0 || s.cstat & 48 != 0 {
246                continue;
247            }
248            if !(pickup_of(s.lotag).is_some() || is_dude(s.lotag) || s.cstat & SPR_BLOCK != 0) {
249                continue;
250            }
251            let (x, y, z) = (s.x as f64, s.y as f64, s.z as f64);
252            let fits = |sec: usize| {
253                let (c, f) = w.zs_at(sec, x, y);
254                z >= c - SLACK && z <= f + SLACK
255            };
256            let cur = s.sectnum as usize;
257            if ob_engine::geom::inside_sector(&w.sectors, &w.walls, cur, x, y) && fits(cur) {
258                continue;
259            }
260            let containing: Vec<usize> = (0..w.sectors.len())
261                .filter(|&k| ob_engine::geom::inside_sector(&w.sectors, &w.walls, k, x, y))
262                .collect();
263            let best = containing.iter().copied().find(|&k| fits(k)).or_else(|| {
264                if ob_engine::geom::inside_sector(&w.sectors, &w.walls, cur, x, y) {
265                    None
266                } else {
267                    containing.first().copied()
268                }
269            });
270            if let Some(k) = best.filter(|&k| k != cur) {
271                moves.push((i, k));
272            }
273        }
274        for (i, k) in moves {
275            self.world.sprites[i].sectnum = k as i16;
276        }
277    }
278
279    fn rand(&mut self) -> u32 {
280        self.rng = self.rng.wrapping_mul(1_103_515_245).wrapping_add(12345);
281        (self.rng >> 8) & 0xffff
282    }
283
284    /// Uniform float in [-1, 1].
285    fn randf(&mut self) -> f64 {
286        self.rand() as f64 / 32767.5 - 1.0
287    }
288
289    fn sound(&mut self, id: i32, at: Option<(f64, f64, f64)>) {
290        if id > 0 {
291            self.events.push(GameEvent::Sound { id, at });
292        }
293    }
294
295    fn sound_group(&mut self, base: i32, at: (f64, f64, f64)) {
296        if base > 0 {
297            let v = (self.rand() % 3) as i32;
298            self.sound(base + v, Some(at));
299        }
300    }
301
302    /// Advances the simulation by real time `dt` (seconds) using fixed 120 Hz ticks.
303    pub fn update(&mut self, res: &Resources, input: &Input, dt: f64) {
304        self.acc += dt.min(0.25);
305        let step = 1.0 / TICK_RATE;
306        let mut first = true;
307        while self.acc >= step {
308            self.acc -= step;
309            let mut inp = *input;
310            if !first {
311                inp.turn = 0.0;
312                inp.look = 0.0;
313            }
314            first = false;
315            self.snapshot();
316            self.tick(res, &inp, step);
317        }
318        self.damage_flash = (self.damage_flash - dt * 2.0).max(0.0);
319        self.pickup_flash = (self.pickup_flash - dt * 6.0).max(0.0);
320    }
321
322    fn snapshot(&mut self) {
323        self.prev_xyz.clear();
324        self.prev_xyz.extend(self.world.sprites.iter().map(|s| (s.x, s.y, s.z)));
325        self.prev_eye = (self.player.x, self.player.y, self.player.view_z());
326    }
327
328    /// Fraction of a tick elapsed since the last simulated tick.
329    fn alpha(&self) -> f64 {
330        (self.acc * TICK_RATE).clamp(0.0, 1.0)
331    }
332
333    /// Position of sprite `i` blended between the last two ticks.
334    fn draw_pos(&self, i: usize) -> (f64, f64, f64) {
335        let s = &self.world.sprites[i];
336        let cur = (s.x as f64, s.y as f64, s.z as f64);
337        match self.prev_xyz.get(i) {
338            Some(&(x, y, z)) => lerp3((x as f64, y as f64, z as f64), cur, self.alpha()),
339            None => cur,
340        }
341    }
342
343    fn obstacles(&self) -> Vec<CircleObstacle> {
344        let (px, py) = (self.player.x, self.player.y);
345        self.world
346            .sprites
347            .iter()
348            .enumerate()
349            .filter(|(i, s)| {
350                s.statnum != stat::FREE
351                    && s.cstat & SPR_BLOCK != 0
352                    && s.cstat & SPR_INVISIBLE == 0
353                    && s.cstat & 48 == 0
354                    && self.ai.get(*i).is_none_or(|a| !matches!(a, Ai::Dead | Ai::Dying))
355                    && ((s.x as f64 - px).abs() < 2048.0 && (s.y as f64 - py).abs() < 2048.0)
356            })
357            .map(|(i, s)| {
358                let r = (s.clipdist as f64 * 4.0).max(16.0);
359                CircleObstacle {
360                    x: s.x as f64,
361                    y: s.y as f64,
362                    radius: r,
363                    zbot: s.z as f64 + 0x800 as f64,
364                    ztop: s.z as f64 - 0x3000 as f64,
365                    id: i,
366                }
367            })
368            .collect()
369    }
370
371    fn tick(&mut self, res: &Resources, input: &Input, dt: f64) {
372        self.clock += 1;
373        // Like the original, level-start events fire once the player first acts.
374        if !self.started {
375            let acted = input.forward != 0.0
376                || input.strafe != 0.0
377                || input.turn != 0.0
378                || input.fire
379                || input.alt_fire
380                || input.use_key
381                || input.jump;
382            if acted {
383                self.started = true;
384                self.triggers
385                    .send(&mut self.world, crate::triggers::chan::LEVEL_START, cmd::ON);
386            }
387        }
388        if self.ai.len() < self.world.sprites.len() {
389            self.ai.resize(self.world.sprites.len(), Ai::Idle);
390            self.attack_cd.resize(self.world.sprites.len(), 0.0);
391        }
392        if self.provoked.len() < self.world.sprites.len() {
393            self.provoked.resize(self.world.sprites.len(), false);
394            self.sees.resize(self.world.sprites.len(), false);
395        }
396        let obstacles = self.obstacles();
397        self.player.underwater = self
398            .world
399            .xsector(self.player.sector.max(0) as usize)
400            .is_some_and(|x| x.underwater);
401        let was_on_ground = self.player.on_ground;
402        self.player.update(&self.world, input, &obstacles, dt);
403        self.room_transition();
404        if !was_on_ground && self.player.on_ground {
405            let v = crate::player::legacy_fall_speed(self.player.fall_speed_peak);
406            self.player.fall_speed_peak = 0.0;
407            if v > 0x18000 as f64 && self.powerups.feather_fall <= 0.0 {
408                let dmg = ((v - 0x18000 as f64) / 1024.0) as i32;
409                self.damage_player(dmg.max(1), None);
410            }
411            if v > 0x6000 as f64 {
412                self.sound(701, None);
413            }
414        }
415
416        if input.use_key && !self.use_down {
417            if self.player.dead {
418                self.events.push(GameEvent::PlayerDied);
419            } else {
420                self.do_use(res);
421            }
422        }
423        self.use_down = input.use_key;
424
425        if let Some(w) = input.weapon {
426            if !self.weapon_switch_down {
427                self.arsenal.select(w as usize);
428            }
429            self.weapon_switch_down = true;
430        } else {
431            self.weapon_switch_down = false;
432        }
433        if !self.player.dead {
434            self.tick_weapon(res, input.fire, input.alt_fire);
435            self.tick_inventory(input, dt);
436        }
437
438        if self.player.sector != self.last_sector {
439            if self.last_sector >= 0 {
440                self.triggers.exit_sector(&mut self.world, self.last_sector as usize);
441            }
442            if self.player.sector >= 0 {
443                self.triggers.enter_sector(&mut self.world, self.player.sector as usize);
444            }
445            self.last_sector = self.player.sector;
446        }
447
448        self.tick_seqs(res);
449        self.tick_dudes(res, dt);
450        self.tick_projectiles(res, dt);
451        self.check_pickups_and_proximity();
452        self.sector_damage(dt);
453        if self.clock % 2 == 0 {
454            self.sector_lighting();
455        }
456        self.triggers.update(&mut self.world);
457        self.carry_player();
458        self.handle_notices(res);
459    }
460
461    /// Moves the player along with sliding / rotating sectors they stand in.
462    fn carry_player(&mut self) {
463        let carries: Vec<_> = std::mem::take(&mut self.triggers.carries);
464        for c in carries {
465            if self.player.sector as usize == c.sector && self.player.on_ground {
466                let (x, y) = c.apply(self.player.x, self.player.y);
467                self.player.x = x;
468                self.player.y = y;
469                self.player.ang = (self.player.ang + c.dang() * 2048.0 / std::f64::consts::TAU).rem_euclid(2048.0);
470                let ns = collide::find_sector_near(&self.world.sectors, &self.world.walls, x, y, self.player.sector);
471                if ns >= 0 {
472                    self.player.sector = ns;
473                }
474            }
475        }
476    }
477
478    /// Light waveform in -1..=1 (or 0..=1) for Blood's lighting wave types.
479    fn light_wave(&mut self, kind: u8, t: f64) -> f64 {
480        let f = t.rem_euclid(1.0);
481        match kind {
482            0 => 1.0,
483            1 => {
484                if f < 0.5 {
485                    1.0
486                } else {
487                    0.0
488                }
489            }
490            2 => f,
491            3 => f * f,
492            4 => 1.0 - f,
493            5 => 0.5 + 0.5 * (f * std::f64::consts::TAU).sin(),
494            6..=9 => {
495                // Flicker: random, biased toward lit.
496                let r = (self.rand() % 100) as f64 / 100.0;
497                if r < 0.15 * (kind - 5) as f64 {
498                    0.0
499                } else {
500                    1.0
501                }
502            }
503            10 => {
504                if f < 0.1 {
505                    1.0
506                } else {
507                    0.0
508                }
509            }
510            11 => (1.0 - (f * 2.0 - 1.0).abs()).powi(2),
511            _ => 1.0,
512        }
513    }
514
515    fn sector_lighting(&mut self) {
516        for s in 0..self.world.sectors.len() {
517            let Some(x) = self.world.xsector(s).cloned() else {
518                continue;
519            };
520            if !(x.shade_floor || x.shade_ceiling || x.shade_walls) || x.amplitude == 0 {
521                continue;
522            }
523            let v = if x.shade_always {
524                let t = self.clock as f64 * x.freq as f64 / (120.0 * 16.0) + x.phase as f64 / 256.0;
525                self.light_wave(x.wave, t)
526            } else if x.busy > 0 {
527                x.busy as f64 / 65536.0
528            } else {
529                0.0
530            };
531            let d = (x.amplitude as f64 * v).round() as i32;
532            let clamp = |b: i8| (b as i32 + d).clamp(-128, 127) as i8;
533            if x.shade_floor {
534                self.world.sectors[s].floor.shade = clamp(self.world.base_floor_shade[s]);
535            }
536            if x.shade_ceiling {
537                self.world.sectors[s].ceiling.shade = clamp(self.world.base_ceil_shade[s]);
538            }
539            if x.shade_walls {
540                for w in self.world.sector_walls(s) {
541                    self.world.walls[w].shade = clamp(self.world.base_wall_shade[w]);
542                }
543            }
544        }
545    }
546
547    /// Moves the player between linked rooms when their eye crosses a portal plane.
548    fn room_transition(&mut self) {
549        let p = &self.player;
550        if p.sector < 0 {
551            return;
552        }
553        let s = p.sector as usize;
554        let eye = p.z - p.eye;
555        let (c, f) = self.world.zs_at(s, p.x, p.y);
556        let link = self.world.links.get(s).copied().unwrap_or_default();
557        let target = match (link.floor, link.ceil) {
558            (Some(l), _) if eye > f => Some(l),
559            (_, Some(l)) if eye < c => Some(l),
560            _ => None,
561        };
562        let Some(l) = target else { return };
563        let (nx, ny) = (p.x + l.dx, p.y + l.dy);
564        let ns = collide::find_sector_near(&self.world.sectors, &self.world.walls, nx, ny, l.sector);
565        if ns < 0 {
566            return;
567        }
568        let p = &mut self.player;
569        p.x = nx;
570        p.y = ny;
571        p.z += l.dz;
572        p.sector = ns;
573        self.last_sector = ns;
574        let water = self.world.xsector(ns as usize).is_some_and(|x| x.underwater);
575        if water != self.player.underwater {
576            self.sound(if water { 720 } else { 721 }, None);
577        }
578    }
579
580    fn sector_damage(&mut self, _dt: f64) {
581        if self.player.sector < 0 || self.player.dead || !self.player.on_ground {
582            return;
583        }
584        let s = self.player.sector as usize;
585        let damage_floor = self.world.sectors[s].lotag == crate::triggers::sector_type::DAMAGE
586            && self.world.xsector(s).is_some_and(|x| x.state == 1);
587        if damage_floor && self.clock % 60 == 0 {
588            let d = self.world.xsector(s).map_or(5, |x| (x.data as i32).clamp(1, 50));
589            self.damage_player(d, None);
590        }
591    }
592
593    fn handle_notices(&mut self, res: &Resources) {
594        let notices: Vec<Notice> = std::mem::take(&mut self.triggers.notices);
595        for n in notices {
596            match n {
597                Notice::LevelExit { secret } => self.events.push(GameEvent::LevelExit { secret }),
598                Notice::SecretFound => self.push_message("You found a secret area!".into()),
599                Notice::Teleport { sector } => self.teleport_from(sector),
600                Notice::SectorStart(s, opening) => self.events.push(GameEvent::SectorSound {
601                    sector: s,
602                    opening,
603                    start: true,
604                }),
605                Notice::SectorStop(s, opening) => self.events.push(GameEvent::SectorSound {
606                    sector: s,
607                    opening,
608                    start: false,
609                }),
610                Notice::SwitchToggled(o, st) => {
611                    self.events.push(GameEvent::Switch);
612                    match o {
613                        Obj::Wall(w) => {
614                            if (20..=22).contains(&self.world.walls[w].lotag) {
615                                let d = if st == 1 { 1 } else { -1 };
616                                self.world.walls[w].picnum += d;
617                                self.sound(if st == 1 { 211 } else { 212 }, Some(self.wall_center(w)));
618                            }
619                        }
620                        Obj::Sprite(i) => {
621                            let t = self.world.sprites[i].lotag;
622                            if (20..=22).contains(&t) {
623                                let d = if st == 1 { 1 } else { -1 };
624                                self.world.sprites[i].picnum += d;
625                                let p = self.sprite_pos(i);
626                                self.sound(if st == 1 { 211 } else { 212 }, Some(p));
627                            }
628                            if is_dude(t) && st == 1 {
629                                // Triggered dudes (e.g. statues) come alive.
630                                self.provoked[i] = true;
631                                if self.ai[i] == Ai::Dormant && ai::is_statue(t) {
632                                    self.ai[i] = Ai::Idle;
633                                }
634                            }
635                            if t == 708 {
636                                if let Some(x) = self.world.xsprite(i) {
637                                    let id = x.data2;
638                                    let p = self.sprite_pos(i);
639                                    self.sound(id, Some(p));
640                                }
641                            }
642                            if t == 711 {
643                                if let Some(id) = self.world.xsprite(i).map(|x| x.data1) {
644                                    self.sound(id, None);
645                                }
646                            }
647                            if t == EXPLODER && st == 1 {
648                                // Scripted blasts, e.g. a wall giving way after its crack is
649                                // blown (E1M2's wagon). Size and damage are estimates.
650                                let p = self.sprite_pos(i);
651                                let sect = self.world.sprites[i].sectnum as i32;
652                                self.explode(res, p.0, p.1, p.2, sect, 1000.0, 40, false);
653                            }
654                        }
655                        Obj::Sector(_) => {}
656                    }
657                }
658                Notice::Text(n) => {
659                    if let Some(m) = self.level_messages.get(&n).cloned() {
660                        if !m.trim().is_empty() {
661                            self.push_message(m);
662                        }
663                    }
664                }
665                Notice::TotalSecrets(_) => {}
666            }
667        }
668    }
669
670    fn wall_center(&self, w: usize) -> (f64, f64, f64) {
671        let a = &self.world.walls[w];
672        let b = &self.world.walls[a.point2 as usize];
673        ((a.x + b.x) as f64 * 0.5, (a.y + b.y) as f64 * 0.5, self.player.z)
674    }
675
676    fn sprite_pos(&self, i: usize) -> (f64, f64, f64) {
677        let s = &self.world.sprites[i];
678        (s.x as f64, s.y as f64, s.z as f64)
679    }
680
681    pub fn push_message(&mut self, m: String) {
682        self.messages.push(m.clone());
683        self.events.push(GameEvent::Message(m));
684    }
685
686    fn teleport_from(&mut self, sector: usize) {
687        let Some(x) = self.world.xsector(sector) else { return };
688        let target = x.marker0 as usize;
689        if target == 0 || target >= self.world.sprites.len() || self.player.sector as usize != sector {
690            return;
691        }
692        let t = &self.world.sprites[target];
693        self.player.x = t.x as f64;
694        self.player.y = t.y as f64;
695        self.player.ang = t.ang as f64;
696        self.player.sector = t.sectnum as i32;
697        let (_, f) = self.world.zs_at(t.sectnum as usize, t.x as f64, t.y as f64);
698        self.player.z = f;
699        self.player.vx = 0.0;
700        self.player.vy = 0.0;
701        self.last_sector = self.player.sector;
702        self.sound(350, None);
703    }
704
705    // ------------------------------------------------------------------ use / keys
706
707    /// Traces a horizontal ray through open portals. Returns the first blocking wall and distance.
708    pub fn trace_wall(&self, x: f64, y: f64, z: f64, sect: i32, ang: f64, max: f64) -> Option<(usize, f64)> {
709        let a = ang_to_rad(ang);
710        let (dx, dy) = (a.cos(), a.sin());
711        let w = &self.world;
712        let mut s = sect;
713        let mut t_in = 0.0;
714        for _ in 0..64 {
715            if s < 0 {
716                return None;
717            }
718            let mut best: Option<(f64, usize)> = None;
719            for wi in w.sector_walls(s as usize) {
720                let w1 = &w.walls[wi];
721                let w2 = &w.walls[w1.point2 as usize];
722                if let Some((t, _)) = ray_segment(x, y, dx, dy, w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64) {
723                    if t > t_in + 1e-6 && best.is_none_or(|b| t < b.0) {
724                        best = Some((t, wi));
725                    }
726                }
727            }
728            let (t, wi) = best?;
729            if t > max {
730                return None;
731            }
732            let wall = &w.walls[wi];
733            if wall.nextsector < 0 {
734                return Some((wi, t));
735            }
736            let (c, f) = w.zs_at(wall.nextsector as usize, x + dx * t, y + dy * t);
737            if z < c || z > f || f - c < 1024.0 || wall.extra > 0 {
738                return Some((wi, t));
739            }
740            if let Some(xs) = w.xsector(wall.nextsector as usize) {
741                if (xs.push || xs.wallpush) && f - c < 0x2000 as f64 {
742                    return Some((wi, t));
743                }
744            }
745            s = wall.nextsector as i32;
746            t_in = t;
747        }
748        None
749    }
750
751    fn key_name(k: u8) -> &'static str {
752        ["", "Skull", "Eye", "Fire", "Dagger", "Spider", "Moon", "seventh"][k.min(7) as usize]
753    }
754
755    /// Returns false (and tells the player) when a key is required but missing.
756    fn check_key(&mut self, key: u8) -> bool {
757        if key == 0 || key > 7 || self.player.keys[key as usize - 1] {
758            return true;
759        }
760        self.push_message(format!("You need the {} key", Self::key_name(key)));
761        self.sound(206, None);
762        false
763    }
764
765    fn do_use(&mut self, res: &Resources) {
766        let p = &self.player;
767        let (x, y, z, ang, sect) = (p.x, p.y, p.view_z(), p.ang, p.sector);
768        let a = ang_to_rad(ang);
769        let (fx, fy) = (a.cos(), a.sin());
770        let wall_hit = self.trace_wall(x, y, z, sect, ang, USE_RANGE);
771        let wall_dist = wall_hit.map_or(f64::MAX, |w| w.1);
772        let mut best_spr: Option<(f64, usize)> = None;
773        for (i, s) in self.world.sprites.iter().enumerate() {
774            if s.statnum == stat::FREE || s.extra <= 0 || is_dude(s.lotag) {
775                continue;
776            }
777            let rx = s.x as f64 - x;
778            let ry = s.y as f64 - y;
779            let along = rx * fx + ry * fy;
780            let side = (-rx * fy + ry * fx).abs();
781            if along > 0.0
782                && along < USE_RANGE.min(wall_dist + 32.0)
783                && side < 160.0
784                && best_spr.is_none_or(|b| along < b.0)
785            {
786                best_spr = Some((along, i));
787            }
788        }
789        let mut done = false;
790        if let Some((_, i)) = best_spr {
791            let key = self.world.xsprite(i).map_or(0, |x| x.key);
792            if self.world.xsprite(i).is_some_and(|x| x.push || x.tx_id > 0) {
793                if !self.check_key(key) {
794                    return;
795                }
796                done = self.triggers.push_sprite(&mut self.world, i);
797            }
798        }
799        if !done {
800            if let Some((wi, _)) = wall_hit {
801                let wkey = self.world.xwall(wi).map_or(0, |x| x.key);
802                let ns = self.world.walls[wi].nextsector;
803                let skey = if ns >= 0 {
804                    self.world.xsector(ns as usize).map_or(0, |x| x.key)
805                } else {
806                    0
807                };
808                let wall_usable = self.world.xwall(wi).is_some();
809                let sector_usable = ns >= 0 && self.world.xsector(ns as usize).is_some_and(|x| x.push || x.wallpush);
810                if (wall_usable || sector_usable) && !self.check_key(wkey.max(skey)) {
811                    return;
812                }
813                done = self.triggers.push_wall(&mut self.world, wi);
814            }
815        }
816        if !done && sect >= 0 {
817            if let Some(k) = self.world.xsector(sect as usize).filter(|x| x.push).map(|x| x.key) {
818                if !self.check_key(k) {
819                    return;
820                }
821            }
822            done = self.triggers.push_sector(&mut self.world, sect as usize);
823        }
824        if !done {
825            self.events.push(GameEvent::UseFailed);
826        }
827        self.handle_notices(res);
828    }
829
830    // ------------------------------------------------------------------ animation
831
832    pub fn start_seq(&mut self, res: &Resources, i: usize, id: u32) {
833        if self.world.rt[i].seq == id as i32 {
834            return;
835        }
836        if self.anims.seq(&res.blood, id).is_none() {
837            return;
838        }
839        let rt = &mut self.world.rt[i];
840        rt.seq = id as i32;
841        rt.seq_frame = -1;
842        rt.seq_time = 0;
843        self.apply_seq_frame(res, i, 0);
844    }
845
846    fn play_dude_anim(&mut self, res: &Resources, i: usize, suffix: &str) -> bool {
847        let Some(info) = dude_info(self.world.sprites[i].lotag) else {
848            return false;
849        };
850        match self.anims.find_seq(info.seq_base, suffix) {
851            Some(id) => {
852                self.start_seq(res, i, id);
853                true
854            }
855            None => false,
856        }
857    }
858
859    fn apply_seq_frame(&mut self, res: &Resources, i: usize, frame: i32) -> bool {
860        let id = self.world.rt[i].seq;
861        let Some(seq) = self.anims.seq(&res.blood, id as u32) else {
862            return false;
863        };
864        let Some(f) = seq.frames.get(frame as usize).copied() else {
865            return false;
866        };
867        self.world.rt[i].seq_frame = frame;
868        let s = &mut self.world.sprites[i];
869        s.picnum = f.tile as i16;
870        s.shade = f.shade;
871        if f.xrepeat > 0 {
872            s.xrepeat = f.xrepeat;
873        }
874        if f.yrepeat > 0 {
875            s.yrepeat = f.yrepeat;
876        }
877        let keep_invisible_marker = is_marker_type(s.lotag);
878        if f.invisible || keep_invisible_marker {
879            s.cstat |= SPR_INVISIBLE;
880        } else {
881            s.cstat &= !SPR_INVISIBLE;
882        }
883        s.cstat = (s.cstat & !(SPR_XFLIP | SPR_YFLIP))
884            | if f.flip_x { SPR_XFLIP } else { 0 }
885            | if f.flip_y { SPR_YFLIP } else { 0 };
886        if f.transparent {
887            s.cstat |= 2;
888        } else {
889            s.cstat &= !2;
890        }
891        if f.play_sound && seq.sound_id > 0 {
892            let p = (s.x as f64, s.y as f64, s.z as f64);
893            self.sound(seq.sound_id, Some(p));
894        }
895        f.trigger
896    }
897
898    /// Advances all sprite sequences; fires callbacks on trigger frames.
899    fn tick_seqs(&mut self, res: &Resources) {
900        for i in 0..self.world.sprites.len() {
901            if self.world.sprites[i].statnum == stat::FREE || self.world.rt[i].seq < 0 {
902                continue;
903            }
904            let id = self.world.rt[i].seq as u32;
905            let Some(seq) = self.anims.seq(&res.blood, id) else {
906                continue;
907            };
908            if seq.frames.is_empty() {
909                continue;
910            }
911            let tpf = seq.ticks_per_frame.max(1);
912            self.world.rt[i].seq_time += 1;
913            if self.world.rt[i].seq_time < tpf {
914                continue;
915            }
916            self.world.rt[i].seq_time = 0;
917            let mut next = self.world.rt[i].seq_frame + 1;
918            if next as usize >= seq.frames.len() {
919                if seq.looping() {
920                    next = 0;
921                } else if seq.flags & SEQ_REMOVE != 0 && !is_dude(self.world.sprites[i].lotag) {
922                    self.world.delete_sprite(i);
923                    continue;
924                } else {
925                    // Hold on the last frame and let AI know the animation ended.
926                    self.world.rt[i].seq = -(id as i32) - 2;
927                    self.seq_finished(res, i);
928                    continue;
929                }
930            }
931            if self.apply_seq_frame(res, i, next) {
932                self.seq_callback(res, i);
933            }
934        }
935    }
936
937    fn seq_finished(&mut self, res: &Resources, i: usize) {
938        match self.ai.get(i).copied() {
939            Some(Ai::Attack) | Some(Ai::Recoil) => {
940                self.ai[i] = Ai::Chase;
941                self.play_dude_anim(res, i, "M1");
942            }
943            Some(Ai::Dying) => self.ai[i] = Ai::Dead,
944            Some(Ai::Rise) => {
945                self.ai[i] = Ai::Chase;
946                self.play_dude_anim(res, i, "M1");
947            }
948            _ => {}
949        }
950    }
951
952    fn seq_callback(&mut self, res: &Resources, i: usize) {
953        if self.ai.get(i) == Some(&Ai::Attack) {
954            self.dude_attack(res, i);
955        }
956    }
957
958    // ------------------------------------------------------------------ dudes
959
960    fn can_see_player(&self, i: usize) -> bool {
961        let s = &self.world.sprites[i];
962        // Dude z is at the feet; eye height comes from the sprite's size.
963        let eye = match self.world.rt[i].eye {
964            e if e > 0 => e as f64,
965            _ => crate::player::EYE_STAND,
966        };
967        let (sx, sy, sz) = (s.x as f64, s.y as f64, s.z as f64 - eye);
968        let (px, py, pz) = (self.player.x, self.player.y, self.player.view_z());
969        let d = (px - sx).hypot(py - sy);
970        if d < 1.0 {
971            return true;
972        }
973        if self.powerups.invisible > 0.0 && d > 1200.0 {
974            return false;
975        }
976        let h = collide::hitscan(
977            &self.world.sectors,
978            &self.world.walls,
979            &[],
980            sx,
981            sy,
982            sz,
983            s.sectnum as i32,
984            (px - sx) / d,
985            (py - sy) / d,
986            (pz - sz) / d,
987            d,
988        );
989        h.dist >= d - 8.0
990    }
991
992    fn dude_mover(info: &DudeInfo) -> Mover {
993        Mover {
994            radius: info.radius,
995            height: info.height,
996            step: 0x1800 as f64,
997        }
998    }
999
1000    fn dude_gravity(&mut self, i: usize, info: &DudeInfo, dt: f64) {
1001        let s = &self.world.sprites[i];
1002        if s.sectnum < 0 {
1003            return;
1004        }
1005        let (c, f) = self.world.zs_at(s.sectnum as usize, s.x as f64, s.y as f64);
1006        let alive = !matches!(self.ai[i], Ai::Dead | Ai::Dying);
1007        if info.flying && alive {
1008            let s = &mut self.world.sprites[i];
1009            s.z = (s.z as f64).clamp(c + info.height, f) as i32;
1010            return;
1011        }
1012        let rt = &mut self.world.rt[i];
1013        rt.vz += crate::player::GRAVITY * dt;
1014        let s = &mut self.world.sprites[i];
1015        let mut z = s.z as f64 + rt.vz * dt;
1016        if z >= f {
1017            z = f;
1018            rt.vz = 0.0;
1019        }
1020        s.z = z as i32;
1021    }
1022
1023    fn dude_attack(&mut self, res: &Resources, i: usize) {
1024        let s = self.world.sprites[i].clone();
1025        let Some(info) = dude_info(s.lotag) else { return };
1026        let (sx, sy, sz) = (s.x as f64, s.y as f64, s.z as f64 - info.height * 0.6);
1027        let (px, py, pz) = (self.player.x, self.player.y, self.player.view_z() + 0x800 as f64);
1028        let d = (px - sx).hypot(py - sy).max(1.0);
1029        let at = (sx, sy, sz);
1030        if info.attack_sound > 0 {
1031            self.sound(info.attack_sound, Some(at));
1032        }
1033        match info.attack {
1034            Attack::None => {}
1035            Attack::Melee { damage, range } => {
1036                if d < range + info.radius + crate::player::RADIUS + 32.0 && (pz - sz).abs() < 0x4000 as f64 {
1037                    self.damage_player(damage, Some(i));
1038                }
1039            }
1040            Attack::Hitscan {
1041                damage,
1042                pellets,
1043                spread,
1044                range,
1045            } => {
1046                let cyl = self.player_cylinder();
1047                for _ in 0..pellets {
1048                    let ex = self.randf() * spread * 1.5;
1049                    let ey = self.randf() * spread * 1.5;
1050                    let ez = self.randf() * spread * 16.0;
1051                    let (mut dx, mut dy) = ((px - sx) / d + ex, (py - sy) / d + ey);
1052                    let l = dx.hypot(dy);
1053                    dx /= l;
1054                    dy /= l;
1055                    let dz = (pz - sz) / d + ez;
1056                    let h = collide::hitscan(
1057                        &self.world.sectors,
1058                        &self.world.walls,
1059                        &[cyl],
1060                        sx,
1061                        sy,
1062                        sz,
1063                        s.sectnum as i32,
1064                        dx,
1065                        dy,
1066                        dz,
1067                        range,
1068                    );
1069                    match h.target {
1070                        TraceTarget::Sprite(PLAYER_ID) if self.powerups.reflect > 0.0 => {
1071                            self.damage_sprite(res, i, damage, false);
1072                        }
1073                        TraceTarget::Sprite(PLAYER_ID) => self.damage_player(damage, Some(i)),
1074                        TraceTarget::Wall(_) | TraceTarget::Floor(_) | TraceTarget::Ceiling(_)
1075                            if self.rand().is_multiple_of(3) =>
1076                        {
1077                            self.spawn_fx(44, h.x, h.y, h.z, h.sector);
1078                        }
1079                        _ => {}
1080                    }
1081                }
1082            }
1083            Attack::Projectile { kind, .. } => {
1084                let ang = (py - sy).atan2(px - sx);
1085                let dz = (pz - sz) / d;
1086                self.spawn_projectile(kind, sx, sy, sz, s.sectnum as i32, ang, dz, i as i64);
1087            }
1088        }
1089    }
1090
1091    fn player_cylinder(&self) -> HitCylinder {
1092        HitCylinder {
1093            id: PLAYER_ID,
1094            x: self.player.x,
1095            y: self.player.y,
1096            radius: crate::player::RADIUS + 16.0,
1097            ztop: self.player.z - self.player.height(),
1098            zbot: self.player.z,
1099        }
1100    }
1101
1102    /// Inventory keys, power-up timers and breathing.
1103    fn tick_inventory(&mut self, input: &Input, dt: f64) {
1104        let keys = (input.inv_prev, input.inv_next, input.inv_use);
1105        if keys.0 && !self.inv_keys.0 {
1106            self.inventory.cycle(-1);
1107        }
1108        if keys.1 && !self.inv_keys.1 {
1109            self.inventory.cycle(1);
1110        }
1111        if keys.2 && !self.inv_keys.2 {
1112            let mut hp = self.player.health;
1113            if let Some(item) = self.inventory.use_selected(&mut hp) {
1114                self.player.health = hp;
1115                let name = crate::inventory::INV_NAMES[item as usize];
1116                let msg = match item {
1117                    InvItem::DoctorBag => format!("Used {name}"),
1118                    _ if self.inventory.active[item as usize] => format!("{name} on"),
1119                    _ => format!("{name} off"),
1120                };
1121                self.push_message(msg);
1122                self.sound(if item == InvItem::DoctorBag { 780 } else { 776 }, None);
1123            }
1124        }
1125        self.inv_keys = keys;
1126        self.inventory.tick(dt);
1127        self.powerups.tick(dt);
1128        self.player.jump_scale = if self.inventory.is_active(InvItem::JumpBoots) {
1129            1.6
1130        } else {
1131            1.0
1132        };
1133        // Breathing.
1134        let suit = self.inventory.is_active(InvItem::DivingSuit);
1135        if self.player.underwater && !suit && !self.player.dead {
1136            self.air -= dt;
1137            if self.air < 0.0 && self.clock % 120 == 0 {
1138                self.damage_player(4, None);
1139                self.sound(724, None);
1140            }
1141        } else {
1142            if self.air < AIR_SECONDS * 0.5 && !self.player.underwater {
1143                self.sound(722, None);
1144            }
1145            self.air = AIR_SECONDS;
1146        }
1147    }
1148
1149    pub fn damage_player(&mut self, amount: i32, _from: Option<usize>) {
1150        if self.player.dead || amount <= 0 || self.powerups.invulnerable > 0.0 {
1151            return;
1152        }
1153        // Difficulty scales damage taken. Measured in DOSBox (E4M9 axe-zombie hits, 18 on
1154        // skill 2): 10-11, 14-15, 18, 21-22 and 26 per hit, i.e. 9/16, 13/16, 1, 19/16, 23/16.
1155        const SKILL_SCALE: [f64; 5] = [0.5625, 0.8125, 1.0, 1.1875, 1.4375];
1156        let mut dmg = ((amount as f64 * SKILL_SCALE[self.skill.clamp(0, 4) as usize]).round() as i32).max(1);
1157        for a in self.player.armor.iter_mut() {
1158            if *a > 0 && dmg > 0 {
1159                let absorbed = (dmg / 2).min(*a);
1160                *a -= absorbed;
1161                dmg -= absorbed;
1162            }
1163        }
1164        self.player.health -= dmg;
1165        self.damage_flash = (self.damage_flash + amount as f64 / 25.0).min(1.0);
1166        self.events.push(GameEvent::PlayerHurt(dmg));
1167        if self.player.health <= 0 {
1168            self.player.health = 0;
1169            self.player.dead = true;
1170            let v = (self.rand() % 3) as i32;
1171            self.sound(716 + v, None);
1172            self.push_message("You are dead. Press Use to restart.".into());
1173        } else if self.rand().is_multiple_of(2) {
1174            let v = (self.rand() % 6) as i32;
1175            self.sound(710 + v, None);
1176        }
1177    }
1178
1179    /// Damage that may set the target on fire.
1180    pub fn damage_sprite_kind(&mut self, res: &Resources, i: usize, amount: i32, explosive: bool, fire: bool) {
1181        if fire && is_dude(self.world.sprites[i].lotag) {
1182            self.world.rt[i].burn_time = self.world.rt[i].burn_time.max((4.0 * TICK_RATE) as i32);
1183        }
1184        self.damage_sprite(res, i, amount, explosive);
1185    }
1186
1187    /// Applies damage to a sprite (dudes and destructible things).
1188    pub fn damage_sprite(&mut self, res: &Resources, i: usize, amount: i32, explosive: bool) {
1189        let s = &self.world.sprites[i];
1190        if s.statnum == stat::FREE {
1191            return;
1192        }
1193        let t = s.lotag;
1194        let p = self.sprite_pos(i);
1195        if is_dude(t) {
1196            let Some(info) = dude_info(t) else { return };
1197            if matches!(self.ai[i], Ai::Dead | Ai::Dying) {
1198                return;
1199            }
1200            self.world.rt[i].health -= amount;
1201            self.spawn_fx(59, p.0, p.1, p.2 - info.height * 0.5, s.sectnum as i32);
1202            if self.world.rt[i].health <= 0 {
1203                self.kill_dude(res, i, &info, explosive || amount >= info.health);
1204            } else {
1205                self.provoke(res, i, &info);
1206                if (self.rand() % 100) as f64 / 100.0 < info.recoil_chance && self.ai[i] != Ai::Attack {
1207                    if self.play_dude_anim(res, i, "R1") {
1208                        self.ai[i] = Ai::Recoil;
1209                    }
1210                    self.sound_group(info.pain_sound, p);
1211                }
1212            }
1213            return;
1214        }
1215        // Things with health (barrels, glass, ...): destroy and fire their trigger. Wall cracks
1216        // only give way to explosions (barrels, dynamite).
1217        let breakable = if t == WALL_CRACK {
1218            explosive
1219        } else {
1220            self.world.sprites[i].cstat & 256 != 0 || self.world.rt[i].health > 0
1221        };
1222        if self.world.xsprite(i).is_some() && breakable {
1223            self.world.rt[i].health -= amount;
1224            if self.world.rt[i].health <= 0 {
1225                self.triggers
1226                    .trigger(&mut self.world, Obj::Sprite(i), cmd::SPRITE_IMPACT);
1227                let is_explosive = matches!(t, TNT_BARREL | 416..=418 | 425..=427);
1228                self.world.delete_sprite(i);
1229                if is_explosive {
1230                    self.explode(
1231                        res,
1232                        p.0,
1233                        p.1,
1234                        p.2,
1235                        self.world.sprites[i].sectnum as i32,
1236                        1200.0,
1237                        80,
1238                        false,
1239                    );
1240                }
1241            }
1242        }
1243    }
1244
1245    fn kill_dude(&mut self, res: &Resources, i: usize, info: &DudeInfo, gib: bool) {
1246        let p = self.sprite_pos(i);
1247        self.ai[i] = Ai::Dying;
1248        let s = &mut self.world.sprites[i];
1249        s.cstat &= !(SPR_BLOCK | 256);
1250        if s.lotag != 245 {
1251            self.kills += 1;
1252        }
1253        self.sound_group(info.die_sound, p);
1254        let burning = self.burn_kill || self.world.rt[i].burn_time > 0;
1255        let played = if burning {
1256            self.play_dude_anim(res, i, "D3") || self.play_dude_anim(res, i, "D1")
1257        } else if gib {
1258            self.play_dude_anim(res, i, "D2") || self.play_dude_anim(res, i, "D1")
1259        } else {
1260            self.play_dude_anim(res, i, "D1")
1261        };
1262        if !played {
1263            self.ai[i] = Ai::Dead;
1264        }
1265        // Drop item and fire the dude's own trigger.
1266        if let Some(x) = self.world.xsprite(i).cloned() {
1267            if x.drop_msg > 0 {
1268                self.spawn_item(x.drop_msg as i16, p.0, p.1, self.world.sprites[i].sectnum as i32);
1269            }
1270            if x.tx_id > 0 {
1271                self.triggers.send(&mut self.world, x.tx_id, x.command);
1272            }
1273        }
1274    }
1275
1276    fn spawn_item(&mut self, t: i16, x: f64, y: f64, sect: i32) {
1277        let Some(&pic) = self.pic_for_type.get(&t) else { return };
1278        if sect < 0 {
1279            return;
1280        }
1281        let (_, f) = self.world.zs_at(sect as usize, x, y);
1282        let s = Sprite {
1283            x: x as i32,
1284            y: y as i32,
1285            z: f as i32,
1286            picnum: pic,
1287            xrepeat: 32,
1288            yrepeat: 32,
1289            sectnum: sect as i16,
1290            statnum: stat::ITEM,
1291            lotag: t,
1292            extra: -1,
1293            ..Default::default()
1294        };
1295        let i = self.world.spawn(s);
1296        self.ensure_slots(i);
1297    }
1298
1299    fn ensure_slots(&mut self, i: usize) {
1300        if self.ai.len() <= i {
1301            self.ai.resize(i + 1, Ai::Idle);
1302            self.attack_cd.resize(i + 1, 0.0);
1303        }
1304        if self.provoked.len() <= i {
1305            self.provoked.resize(i + 1, false);
1306            self.sees.resize(i + 1, false);
1307        }
1308        self.provoked[i] = false;
1309        self.ai[i] = Ai::Idle;
1310    }
1311
1312    // ------------------------------------------------------------------ effects
1313
1314    pub fn spawn_fx(&mut self, seq: u32, x: f64, y: f64, z: f64, sect: i32) -> Option<usize> {
1315        if sect < 0 {
1316            return None;
1317        }
1318        let s = Sprite {
1319            x: x as i32,
1320            y: y as i32,
1321            z: z as i32,
1322            xrepeat: 48,
1323            yrepeat: 48,
1324            cstat: SPR_CENTER,
1325            sectnum: sect as i16,
1326            statnum: stat::FX,
1327            extra: -1,
1328            picnum: 0,
1329            ..Default::default()
1330        };
1331        let i = self.world.spawn(s);
1332        self.ensure_slots(i);
1333        self.world.rt[i].seq = -1;
1334        self.world.rt[i].ai_state = seq as i32;
1335        // Seq is started lazily in tick_projectiles (needs resources); mark pending.
1336        self.world.rt[i].ai_timer = -1;
1337        Some(i)
1338    }
1339
1340    #[allow(clippy::too_many_arguments)]
1341    fn explode(&mut self, res: &Resources, x: f64, y: f64, z: f64, sect: i32, radius: f64, damage: i32, fire: bool) {
1342        if let Some(i) = self.spawn_fx(if fire { 5 } else { 3 }, x, y, z, sect) {
1343            self.world.sprites[i].xrepeat = 64;
1344            self.world.sprites[i].yrepeat = 64;
1345        }
1346        self.sound(if fire { 307 } else { 304 }, Some((x, y, z)));
1347        // Player.
1348        let d = (self.player.x - x)
1349            .hypot(self.player.y - y)
1350            .hypot((self.player.z - 0x1800 as f64 - z) / 16.0);
1351        if d < radius {
1352            let dmg = (damage as f64 * (1.0 - d / radius)) as i32;
1353            self.damage_player(dmg, None);
1354        }
1355        // Sprites.
1356        let targets: Vec<(usize, f64)> = self
1357            .world
1358            .sprites
1359            .iter()
1360            .enumerate()
1361            .filter(|(_, s)| s.statnum != stat::FREE && (is_dude(s.lotag) || s.extra > 0))
1362            .map(|(i, s)| (i, (s.x as f64 - x).hypot(s.y as f64 - y).hypot((s.z as f64 - z) / 16.0)))
1363            .filter(|(_, d)| *d < radius)
1364            .collect();
1365        for (i, d) in targets {
1366            let dmg = (damage as f64 * (1.0 - d / radius)) as i32;
1367            if dmg > 0 {
1368                self.damage_sprite(res, i, dmg, true);
1369            }
1370        }
1371    }
1372
1373    // ------------------------------------------------------------------ projectiles
1374
1375    #[allow(clippy::too_many_arguments)]
1376    fn spawn_projectile(
1377        &mut self,
1378        kind: ProjKind,
1379        x: f64,
1380        y: f64,
1381        z: f64,
1382        sect: i32,
1383        ang: f64,
1384        dz: f64,
1385        owner: i64,
1386    ) -> Option<usize> {
1387        if sect < 0 {
1388            return None;
1389        }
1390        let (speed, seq) = match kind {
1391            ProjKind::Flare => (7000.0, 41),
1392            ProjKind::Fireball => (4500.0, 22),
1393            ProjKind::Napalm => (4500.0, 22),
1394            ProjKind::Tesla => (11250.0, 23),
1395            ProjKind::Bone => (3750.0, 24),
1396            ProjKind::Puke => (3250.0, 68),
1397            ProjKind::Tnt => (2600.0, 0),
1398            ProjKind::Leech => (7500.0, 23),
1399        };
1400        let s = Sprite {
1401            x: x as i32,
1402            y: y as i32,
1403            z: z as i32,
1404            xrepeat: 32,
1405            yrepeat: 32,
1406            cstat: SPR_CENTER,
1407            sectnum: sect as i16,
1408            statnum: stat::PROJECTILE,
1409            lotag: PROJ_BASE + kind as i16,
1410            ang: ((ang.to_degrees() / 360.0 * 2048.0).rem_euclid(2048.0)) as i16,
1411            picnum: if kind == ProjKind::Tnt {
1412                self.pic_for_type.get(&62).copied().unwrap_or(0)
1413            } else {
1414                0
1415            },
1416            extra: -1,
1417            ..Default::default()
1418        };
1419        let i = self.world.spawn(s);
1420        self.ensure_slots(i);
1421        let rt = &mut self.world.rt[i];
1422        rt.vx = ang.cos() * speed;
1423        rt.vy = ang.sin() * speed;
1424        rt.vz = dz * speed;
1425        if kind == ProjKind::Tnt {
1426            rt.vz -= 0x6000 as f64;
1427        }
1428        rt.target = owner as i32;
1429        rt.ai_timer = if kind == ProjKind::Tnt { 300 } else { 600 };
1430        rt.ai_state = seq;
1431        rt.seq = -1;
1432        Some(i)
1433    }
1434
1435    fn proj_kind(t: i16) -> Option<ProjKind> {
1436        use ProjKind::*;
1437        Some(match t - PROJ_BASE {
1438            0 => Flare,
1439            1 => Fireball,
1440            2 => Napalm,
1441            3 => Tesla,
1442            4 => Bone,
1443            5 => Puke,
1444            6 => Tnt,
1445            7 => Leech,
1446            _ => return None,
1447        })
1448    }
1449
1450    fn tick_projectiles(&mut self, res: &Resources, dt: f64) {
1451        for i in 0..self.world.sprites.len() {
1452            let st = self.world.sprites[i].statnum;
1453            if st == stat::FX {
1454                if self.world.rt[i].ai_timer == -1 {
1455                    self.world.rt[i].ai_timer = 0;
1456                    let seq = self.world.rt[i].ai_state as u32;
1457                    self.start_seq(res, i, seq);
1458                    if self.world.rt[i].seq < 0 {
1459                        self.world.delete_sprite(i);
1460                    }
1461                } else if self.world.rt[i].seq < -1 {
1462                    self.world.delete_sprite(i);
1463                }
1464                continue;
1465            }
1466            if st != stat::PROJECTILE {
1467                continue;
1468            }
1469            let Some(kind) = Self::proj_kind(self.world.sprites[i].lotag) else {
1470                continue;
1471            };
1472            if self.world.rt[i].seq == -1 && self.world.rt[i].ai_state > 0 {
1473                let seq = self.world.rt[i].ai_state as u32;
1474                self.start_seq(res, i, seq);
1475                self.world.rt[i].ai_state = 0;
1476            }
1477            self.world.rt[i].ai_timer -= 1;
1478            let s = self.world.sprites[i].clone();
1479            let (x, y, z) = (s.x as f64, s.y as f64, s.z as f64);
1480            if kind == ProjKind::Tnt {
1481                self.world.rt[i].vz += crate::player::GRAVITY * dt;
1482                if self.world.rt[i].ai_timer <= 0 {
1483                    self.world.delete_sprite(i);
1484                    self.explode(res, x, y, z, s.sectnum as i32, 1500.0, 120, false);
1485                    continue;
1486                }
1487            }
1488            if self.world.rt[i].ai_timer <= 0 {
1489                self.world.delete_sprite(i);
1490                continue;
1491            }
1492            let rt = &self.world.rt[i];
1493            let (vx, vy, vz) = (rt.vx * dt, rt.vy * dt, rt.vz * dt);
1494            let owner = rt.target;
1495            let len = vx.hypot(vy);
1496            if len < 1e-6 {
1497                continue;
1498            }
1499            let mut cyls: Vec<HitCylinder> = Vec::new();
1500            if owner != -2 {
1501                cyls.push(self.player_cylinder());
1502            }
1503            for (j, o) in self.world.sprites.iter().enumerate() {
1504                if j as i32 == owner || j == i || o.statnum == stat::FREE || !is_dude(o.lotag) {
1505                    continue;
1506                }
1507                if matches!(self.ai[j], Ai::Dead | Ai::Dying) {
1508                    continue;
1509                }
1510                if (o.x as f64 - x).abs() > len + 256.0 || (o.y as f64 - y).abs() > len + 256.0 {
1511                    continue;
1512                }
1513                let r = dude_info(o.lotag).map_or(64.0, |d| d.radius);
1514                let h = dude_info(o.lotag).map_or(0x3000 as f64, |d| d.height);
1515                cyls.push(HitCylinder {
1516                    id: j,
1517                    x: o.x as f64,
1518                    y: o.y as f64,
1519                    radius: r,
1520                    ztop: o.z as f64 - h,
1521                    zbot: o.z as f64,
1522                });
1523            }
1524            let h = collide::hitscan(
1525                &self.world.sectors,
1526                &self.world.walls,
1527                &cyls,
1528                x,
1529                y,
1530                z,
1531                s.sectnum as i32,
1532                vx / len,
1533                vy / len,
1534                vz / len,
1535                len,
1536            );
1537            if h.target == TraceTarget::Nothing {
1538                let ns = collide::find_sector_near(&self.world.sectors, &self.world.walls, h.x, h.y, s.sectnum as i32);
1539                let sp = &mut self.world.sprites[i];
1540                sp.x = h.x as i32;
1541                sp.y = h.y as i32;
1542                sp.z = h.z as i32;
1543                if ns >= 0 {
1544                    sp.sectnum = ns as i16;
1545                }
1546                continue;
1547            }
1548            if kind == ProjKind::Tnt {
1549                // Bounce and keep the fuse burning.
1550                let rt = &mut self.world.rt[i];
1551                match h.target {
1552                    TraceTarget::Floor(_) | TraceTarget::Ceiling(_) => rt.vz = -rt.vz * 0.4,
1553                    _ => {
1554                        rt.vx = -rt.vx * 0.4;
1555                        rt.vy = -rt.vy * 0.4;
1556                    }
1557                }
1558                rt.vx *= 0.8;
1559                rt.vy *= 0.8;
1560                continue;
1561            }
1562            self.world.delete_sprite(i);
1563            let (dmg, radius, fire) = match kind {
1564                ProjKind::Flare => (20, 0.0, true),
1565                ProjKind::Fireball => (25, 600.0, true),
1566                ProjKind::Napalm => (45, 900.0, true),
1567                ProjKind::Tesla => (18, 0.0, false),
1568                ProjKind::Bone => (15, 0.0, false),
1569                ProjKind::Puke => (10, 0.0, false),
1570                ProjKind::Leech => (16, 0.0, false),
1571                ProjKind::Tnt => (0, 0.0, false),
1572            };
1573            match h.target {
1574                TraceTarget::Sprite(PLAYER_ID) => self.damage_player(dmg, None),
1575                TraceTarget::Sprite(j) => self.damage_sprite(res, j, dmg, radius > 0.0),
1576                _ => {}
1577            }
1578            if radius > 0.0 {
1579                self.explode(res, h.x, h.y, h.z, h.sector, radius, dmg, fire);
1580            } else {
1581                self.spawn_fx(if fire { 54 } else { 44 }, h.x, h.y, h.z, h.sector);
1582            }
1583        }
1584    }
1585
1586    // ------------------------------------------------------------------ player weapons
1587
1588    fn tick_weapon(&mut self, res: &Resources, fire: bool, alt: bool) {
1589        self.arsenal.akimbo = self.powerups.akimbo > 0.0;
1590        let lens: HashMap<u32, i32> = [self.arsenal.qav]
1591            .iter()
1592            .filter_map(|&q| self.anims.qav(&res.blood, q).map(|a| (q, a.length())))
1593            .collect();
1594        let lib_len = |q: u32| lens.get(&q).copied().unwrap_or(30);
1595        let before = (self.arsenal.state, self.arsenal.qav);
1596        self.arsenal.tick(fire, alt, lib_len);
1597        if (self.arsenal.state, self.arsenal.qav) != before {
1598            // New animation: make sure its length is known next tick.
1599            let _ = self.anims.qav(&res.blood, self.arsenal.qav);
1600        }
1601        let Some(q) = self.anims.qav(&res.blood, self.arsenal.qav) else {
1602            return;
1603        };
1604        let frame = q.frame_at(self.arsenal.qav_time) as i32;
1605        if frame != self.arsenal.last_frame {
1606            self.arsenal.last_frame = frame;
1607            let f = &q.frames[frame as usize];
1608            if f.sound.id > 0 {
1609                self.sound(f.sound.id, None);
1610            }
1611            if f.callback > 0 && self.arsenal.state == WeaponState::Firing {
1612                self.player_shoot(res);
1613            }
1614        }
1615        // QAVs without callbacks fire on their first frame.
1616        if self.arsenal.state == WeaponState::Firing
1617            && self.arsenal.qav_time == 1
1618            && !q.frames.iter().any(|f| f.callback > 0)
1619        {
1620            self.player_shoot(res);
1621        }
1622    }
1623
1624    /// Aim vector (dx, dy, dz) for the player, with light vertical auto-aim.
1625    fn player_aim(&self) -> (f64, f64, f64) {
1626        let a = ang_to_rad(self.player.ang);
1627        let (dx, dy) = (a.cos(), a.sin());
1628        let mut dz = -self.player.horiz / 160.0 * 16.0;
1629        let (ex, ey, ez) = (self.player.x, self.player.y, self.player.view_z());
1630        let mut best: Option<f64> = None;
1631        for (i, s) in self.world.sprites.iter().enumerate() {
1632            if s.statnum == stat::FREE || !is_dude(s.lotag) || matches!(self.ai.get(i), Some(Ai::Dead | Ai::Dying)) {
1633                continue;
1634            }
1635            let rx = s.x as f64 - ex;
1636            let ry = s.y as f64 - ey;
1637            let along = rx * dx + ry * dy;
1638            if !(32.0..12000.0).contains(&along) {
1639                continue;
1640            }
1641            let side = (-rx * dy + ry * dx).abs();
1642            if side > along * 0.08 + 48.0 {
1643                continue;
1644            }
1645            if best.is_none_or(|b| along < b) {
1646                best = Some(along);
1647                let h = dude_info(s.lotag).map_or(0x2000 as f64, |d| d.height);
1648                dz = (s.z as f64 - h * 0.5 - ez) / along;
1649            }
1650        }
1651        (dx, dy, dz)
1652    }
1653
1654    fn player_shoot(&mut self, res: &Resources) {
1655        if !self.arsenal.consume() {
1656            return;
1657        }
1658        let kind = self.arsenal.mode().kind;
1659        let (dx, dy, dz) = self.player_aim();
1660        for shot in 0..self.arsenal.shots() {
1661            // Dual guns fire from the left and right hand.
1662            let side = if self.arsenal.shots() > 1 {
1663                if shot == 0 {
1664                    -24.0
1665                } else {
1666                    24.0
1667                }
1668            } else {
1669                0.0
1670            };
1671            self.fire_once(res, kind, dx, dy, dz, side);
1672        }
1673    }
1674
1675    fn fire_once(&mut self, res: &Resources, kind: Fire, dx: f64, dy: f64, dz: f64, side: f64) {
1676        let (ex, ey, ez) = (
1677            self.player.x - dy * side,
1678            self.player.y + dx * side,
1679            self.player.view_z(),
1680        );
1681        let sect = self.player.sector;
1682        let cyls = self.dude_cylinders(ex, ey);
1683        let mult = self.powerups.damage_multiplier();
1684        match kind {
1685            Fire::Melee { damage, range } | Fire::Spray { damage, range } => {
1686                let h = collide::hitscan(
1687                    &self.world.sectors,
1688                    &self.world.walls,
1689                    &cyls,
1690                    ex,
1691                    ey,
1692                    ez,
1693                    sect,
1694                    dx,
1695                    dy,
1696                    dz,
1697                    range + crate::player::RADIUS,
1698                );
1699                if let TraceTarget::Sprite(j) = h.target {
1700                    let fire = matches!(kind, Fire::Spray { .. });
1701                    self.damage_sprite_kind(res, j, damage * mult, false, fire);
1702                } else if h.target != TraceTarget::Nothing {
1703                    self.sound(500, Some((h.x, h.y, h.z)));
1704                }
1705                if matches!(kind, Fire::Spray { .. }) {
1706                    self.spawn_fx(55, ex + dx * 300.0, ey + dy * 300.0, ez + dz * 300.0, sect);
1707                }
1708                self.alert_nearby(res, 1200.0);
1709            }
1710            Fire::Hitscan {
1711                damage,
1712                pellets,
1713                spread,
1714            } => {
1715                // Pellets hitting the same target add up into one hit, so a point-blank
1716                // shotgun blast can gib like in the original.
1717                let mut hits: Vec<(usize, i32)> = Vec::new();
1718                for _ in 0..pellets {
1719                    let (mut ax, mut ay) = (dx + self.randf() * spread, dy + self.randf() * spread);
1720                    let l = ax.hypot(ay);
1721                    ax /= l;
1722                    ay /= l;
1723                    let az = dz + self.randf() * spread * 12.0;
1724                    let h = collide::hitscan(
1725                        &self.world.sectors,
1726                        &self.world.walls,
1727                        &cyls,
1728                        ex,
1729                        ey,
1730                        ez,
1731                        sect,
1732                        ax,
1733                        ay,
1734                        az,
1735                        30000.0,
1736                    );
1737                    match h.target {
1738                        TraceTarget::Sprite(j) => match hits.iter_mut().find(|h| h.0 == j) {
1739                            Some(h) => h.1 += damage * mult,
1740                            None => hits.push((j, damage * mult)),
1741                        },
1742                        TraceTarget::Wall(w) => {
1743                            let fx = 44 + self.rand() % 3;
1744                            self.spawn_fx(fx, h.x - ax * 4.0, h.y - ay * 4.0, h.z, h.sector);
1745                            // Shooting a wall can trigger it (impact-activated switches).
1746                            if self.world.xwall(w).is_some_and(|x| x.trigger_vector) {
1747                                self.triggers.trigger(&mut self.world, Obj::Wall(w), cmd::WALL_IMPACT);
1748                            }
1749                        }
1750                        TraceTarget::Floor(_) | TraceTarget::Ceiling(_) => {
1751                            let fx = 44 + self.rand() % 3;
1752                            self.spawn_fx(fx, h.x, h.y, h.z, h.sector);
1753                        }
1754                        TraceTarget::Nothing => {}
1755                    }
1756                }
1757                for (j, amount) in hits {
1758                    self.damage_sprite(res, j, amount, false);
1759                }
1760                self.alert_nearby(res, 10000.0); // gunshots carry far
1761            }
1762            Fire::Projectile(pk) => {
1763                let ang = dy.atan2(dx);
1764                self.spawn_projectile(pk, ex + dx * 64.0, ey + dy * 64.0, ez + 0x400 as f64, sect, ang, dz, -2);
1765                self.alert_nearby(res, 4000.0);
1766            }
1767            Fire::Burst {
1768                kind: pk,
1769                count,
1770                spread,
1771            } => {
1772                let base = dy.atan2(dx);
1773                for k in 0..count {
1774                    let f = if count > 1 {
1775                        k as f64 / (count - 1) as f64 - 0.5
1776                    } else {
1777                        0.0
1778                    };
1779                    let ang = base + f * spread * 2.0;
1780                    let jitter = self.randf() * 0.02;
1781                    self.spawn_projectile(
1782                        pk,
1783                        ex + dx * 64.0,
1784                        ey + dy * 64.0,
1785                        ez + 0x400 as f64,
1786                        sect,
1787                        ang,
1788                        dz + jitter,
1789                        -2,
1790                    );
1791                }
1792                self.alert_nearby(res, 5000.0);
1793            }
1794            Fire::Throw { fuse, power } => {
1795                let ang = dy.atan2(dx);
1796                if let Some(i) = self.spawn_projectile(
1797                    ProjKind::Tnt,
1798                    ex + dx * 64.0,
1799                    ey + dy * 64.0,
1800                    ez + 0x800 as f64,
1801                    sect,
1802                    ang,
1803                    dz,
1804                    -2,
1805                ) {
1806                    let rt = &mut self.world.rt[i];
1807                    let scale = 0.25 + 0.75 * power;
1808                    rt.vx *= scale;
1809                    rt.vy *= scale;
1810                    rt.vz = rt.vz * scale - 0x6000 as f64 * power;
1811                    rt.ai_timer = (fuse * TICK_RATE) as i32;
1812                }
1813            }
1814            Fire::Curse { damage } => {
1815                // Hurts every dude that can see the player.
1816                let targets: Vec<usize> = (0..self.world.sprites.len())
1817                    .filter(|&i| {
1818                        let s = &self.world.sprites[i];
1819                        s.statnum != stat::FREE
1820                            && is_dude(s.lotag)
1821                            && !matches!(self.ai[i], Ai::Dead | Ai::Dying)
1822                            && (s.x as f64 - ex).hypot(s.y as f64 - ey) < 10000.0
1823                            && self.can_see_player(i)
1824                    })
1825                    .collect();
1826                for i in targets {
1827                    self.damage_sprite(res, i, damage * mult, false);
1828                }
1829                let left = self.arsenal.ammo[crate::weapons::ammo::VOODOO];
1830                self.arsenal.ammo[crate::weapons::ammo::VOODOO] = (left - 5).max(0);
1831                self.sound(463, None);
1832            }
1833        }
1834    }
1835
1836    fn dude_cylinders(&self, x: f64, y: f64) -> Vec<HitCylinder> {
1837        self.world
1838            .sprites
1839            .iter()
1840            .enumerate()
1841            .filter(|(i, s)| {
1842                s.statnum != stat::FREE
1843                    && s.cstat & SPR_INVISIBLE == 0
1844                    && (is_dude(s.lotag) && !matches!(self.ai.get(*i), Some(Ai::Dead | Ai::Dying))
1845                        || s.cstat & 256 != 0 && s.extra > 0 && !is_dude(s.lotag))
1846                    && (s.x as f64 - x).abs() < 30000.0
1847                    && (s.y as f64 - y).abs() < 30000.0
1848            })
1849            .map(|(i, s)| {
1850                let (r, h) = dude_info(s.lotag).map_or(((s.clipdist as f64 * 4.0).max(32.0), 0x2000 as f64), |d| {
1851                    (d.radius, d.height)
1852                });
1853                HitCylinder {
1854                    id: i,
1855                    x: s.x as f64,
1856                    y: s.y as f64,
1857                    radius: r,
1858                    ztop: s.z as f64 - h,
1859                    zbot: s.z as f64 + 256.0,
1860                }
1861            })
1862            .collect()
1863    }
1864
1865    // ------------------------------------------------------------------ pickups
1866
1867    fn check_pickups_and_proximity(&mut self) {
1868        if self.player.dead {
1869            return;
1870        }
1871        let (px, py, pz) = (self.player.x, self.player.y, self.player.z);
1872        let top = pz - self.player.height() - 0x800 as f64;
1873        for i in 0..self.world.sprites.len() {
1874            let s = &self.world.sprites[i];
1875            if s.statnum == stat::FREE {
1876                continue;
1877            }
1878            let d = (s.x as f64 - px).hypot(s.y as f64 - py);
1879            if d > 768.0 {
1880                continue;
1881            }
1882            let t = s.lotag;
1883            let sz = s.z as f64;
1884            if let Some((pick, msg)) = pickup_of(t) {
1885                if s.cstat & SPR_INVISIBLE != 0
1886                    || d > 96.0 + crate::player::RADIUS
1887                    || sz < top
1888                    || sz > pz + 0x1000 as f64
1889                {
1890                    continue;
1891                }
1892                if self.apply_pickup(pick) {
1893                    self.push_message(msg.to_string());
1894                    let snd = match pick {
1895                        Pickup::Key(_) => 781,
1896                        Pickup::Health { .. } => 780,
1897                        Pickup::Armor { .. } => 779,
1898                        Pickup::Weapon { .. } => 777,
1899                        Pickup::Ammo { .. } => 782,
1900                        Pickup::Powerup(_) | Pickup::Timed(..) | Pickup::Inventory(_) => 776,
1901                    };
1902                    self.sound(snd, None);
1903                    self.pickup_flash = 1.0;
1904                    if self.world.xsprite(i).is_some() {
1905                        self.triggers
1906                            .trigger(&mut self.world, Obj::Sprite(i), cmd::SPRITE_PICKUP);
1907                    }
1908                    self.world.delete_sprite(i);
1909                }
1910                continue;
1911            }
1912            if let Some(x) = self.world.xsprite(i) {
1913                if x.proximity && !x.is_triggered && d < 256.0 && (sz - pz).abs() < 0x4000 as f64 {
1914                    if let Some(xm) = self.world.xsprite_mut(i) {
1915                        xm.is_triggered = true;
1916                    }
1917                    self.triggers
1918                        .trigger(&mut self.world, Obj::Sprite(i), cmd::SPRITE_PROXIMITY);
1919                }
1920            }
1921        }
1922    }
1923
1924    fn apply_pickup(&mut self, p: Pickup) -> bool {
1925        let pl = &mut self.player;
1926        match p {
1927            Pickup::Key(k) => {
1928                if pl.keys[k] {
1929                    return false;
1930                }
1931                pl.keys[k] = true;
1932                true
1933            }
1934            Pickup::Health { amount, max } => {
1935                if pl.health >= max {
1936                    return false;
1937                }
1938                pl.health = (pl.health + amount).min(max);
1939                true
1940            }
1941            Pickup::Armor { slot, amount } => {
1942                if pl.armor[slot] >= amount {
1943                    return false;
1944                }
1945                pl.armor[slot] = amount;
1946                true
1947            }
1948            Pickup::Weapon { slot, ammo } => self.arsenal.give_weapon(slot, ammo),
1949            Pickup::Ammo { kind, amount } => self.arsenal.add_ammo(kind, amount),
1950            Pickup::Inventory(i) => self.inventory.give(i),
1951            Pickup::Timed(k, secs) => {
1952                let p = &mut self.powerups;
1953                let t = match k {
1954                    Timed::Invisible => &mut p.invisible,
1955                    Timed::Invulnerable => &mut p.invulnerable,
1956                    Timed::Akimbo => &mut p.akimbo,
1957                    Timed::Reflect => &mut p.reflect,
1958                    Timed::FeatherFall => &mut p.feather_fall,
1959                    Timed::Rage => &mut p.rage,
1960                };
1961                *t = t.max(secs);
1962                true
1963            }
1964            Pickup::Powerup(_) => true,
1965        }
1966    }
1967
1968    // ------------------------------------------------------------------ view
1969
1970    pub fn camera(&self) -> Camera {
1971        let (x, y, z) = lerp3(
1972            self.prev_eye,
1973            (self.player.x, self.player.y, self.player.view_z()),
1974            self.alpha(),
1975        );
1976        Camera {
1977            x,
1978            y,
1979            z,
1980            ang: self.player.ang,
1981            // Blood's view centre sits 10 lines above the screen centre. The renderer's
1982            // horiz grows downward while the player's grows upward (look up = positive).
1983            horiz: 10.0 - self.player.horiz,
1984            sector: ob_engine::geom::update_sector(&self.world.sectors, &self.world.walls, x, y, self.player.sector),
1985        }
1986    }
1987
1988    /// AI state of sprite `i` (for tests and debugging).
1989    pub fn ai_state(&self, i: usize) -> Option<Ai> {
1990        self.ai.get(i).copied()
1991    }
1992
1993    /// Tile used by an item type in this level (for HUD icons).
1994    pub fn item_pic(&self, t: i16) -> Option<i32> {
1995        self.pic_for_type.get(&t).map(|&p| p as i32)
1996    }
1997
1998    /// Current weapon QAV and its elapsed ticks, for the HUD.
1999    pub fn weapon_view(&self) -> (u32, i32) {
2000        (self.arsenal.qav, self.arsenal.qav_time)
2001    }
2002
2003    /// Builds the renderer sprite list, resolving rotation frames for the camera.
2004    pub fn sprite_draws(&self, res: &Resources, cam: &Camera) -> Vec<SpriteDraw> {
2005        let mut out = Vec::with_capacity(self.world.sprites.len());
2006        for (i, s) in self.world.sprites.iter().enumerate() {
2007            if s.statnum == stat::FREE || s.cstat & SPR_INVISIBLE != 0 || s.picnum <= 0 && s.statnum != stat::DECORATION
2008            {
2009                continue;
2010            }
2011            let mut pic = res.tiles.animate(s.picnum as i32, self.clock);
2012            let mut cstat = s.cstat;
2013            let view = res.tiles.get(pic).anm.view;
2014            let voxel = if view == 6 || view == 7 {
2015                res.voxel_for_tile(pic)
2016            } else {
2017                None
2018            };
2019            // Spinning voxels rotate continuously.
2020            let ang = if view == 7 {
2021                (s.ang as f64 + self.clock as f64 * 4.0).rem_euclid(2048.0)
2022            } else {
2023                s.ang as f64
2024            };
2025            if (view == 1 || view == 2) && s.cstat & 48 == 0 {
2026                let to_cam = (cam.y - s.y as f64).atan2(cam.x - s.x as f64);
2027                let rel = (to_cam.to_degrees() / 360.0 * 2048.0 - s.ang as f64).rem_euclid(2048.0);
2028                let k = (((rel + 128.0) / 256.0).floor() as i32).rem_euclid(8);
2029                if view == 1 {
2030                    if k <= 4 {
2031                        pic += k;
2032                    } else {
2033                        pic += 8 - k;
2034                        cstat ^= SPR_XFLIP;
2035                    }
2036                } else {
2037                    pic += k;
2038                }
2039            }
2040            let (x, y, mut z) = self.draw_pos(i);
2041            // Dudes keep z at their feet; each animation frame's own offsets would otherwise
2042            // sink walking frames into the floor, so the frame's bottom edge goes to z.
2043            if s.statnum == stat::DUDE && s.cstat & 48 == 0 {
2044                let frame = Sprite {
2045                    picnum: pic as i16,
2046                    ..s.clone()
2047                };
2048                let (_, bot) = sprite_extents(res, &frame);
2049                z -= bot - s.z as f64;
2050            }
2051            out.push(SpriteDraw {
2052                x,
2053                y,
2054                z,
2055                picnum: pic,
2056                cstat,
2057                // Sprites take on their sector's (current, light-effected) shade, as in the
2058                // original: a zombie in a dark corridor is as dark as the corridor (E2M4), a
2059                // tree under the open sky is lit like the sky (E4M9).
2060                shade: s.shade as i32
2061                    + self.world.sectors.get(s.sectnum.max(0) as usize).map_or(0, |sec| {
2062                        if sec.ceiling.stat & ob_engine::render::PLANE_PARALLAX != 0 {
2063                            sec.ceiling.shade as i32
2064                        } else {
2065                            sec.floor.shade as i32
2066                        }
2067                    }),
2068                pal: s.pal,
2069                xrepeat: s.xrepeat,
2070                yrepeat: s.yrepeat,
2071                xoffset: s.xoffset,
2072                yoffset: s.yoffset,
2073                ang,
2074                sector: s.sectnum as i32,
2075                voxel,
2076                portal: 0,
2077            });
2078        }
2079        out
2080    }
2081}
2082
2083/// Blends `a` toward `b`; big jumps (teleports, respawns) are not blended.
2084fn lerp3(a: (f64, f64, f64), b: (f64, f64, f64), t: f64) -> (f64, f64, f64) {
2085    if (b.0 - a.0).abs() > 1024.0 || (b.1 - a.1).abs() > 1024.0 || (b.2 - a.2).abs() > 0x4000 as f64 {
2086        return b;
2087    }
2088    (a.0 + (b.0 - a.0) * t, a.1 + (b.1 - a.1) * t, a.2 + (b.2 - a.2) * t)
2089}