Skip to main content

ob_engine/
render.rs

1//! Resolution-independent software renderer for Build-style worlds.
2//!
3//! Each screen column casts one ray through the sector/portal graph. Walls, sloped
4//! floors/ceilings and parallax skies are drawn front to back into a column-major
5//! buffer with a per-pixel depth (perpendicular distance in xy units). Sprites and
6//! masked walls are drawn afterwards, back to front, with a depth test. Columns are
7//! independent, so both passes run in parallel on all CPU cores.
8
9use crate::art::TileSet;
10use crate::geom::{ang_to_rad, plane_eq, ray_segment, PlaneEq};
11use crate::map::{Sector, Wall};
12use crate::palette::NUM_SHADES;
13use rayon::prelude::*;
14use std::sync::atomic::{AtomicU8, Ordering};
15
16pub const TRANSPARENT: u8 = 255;
17
18// wall cstat
19pub const WALL_BLOCK: u16 = 1;
20pub const WALL_BOTTOM_SWAP: u16 = 2;
21pub const WALL_ALIGN_BOTTOM: u16 = 4;
22pub const WALL_XFLIP: u16 = 8;
23pub const WALL_MASKED: u16 = 16;
24pub const WALL_ONEWAY: u16 = 32;
25pub const WALL_TRANS: u16 = 128;
26pub const WALL_YFLIP: u16 = 256;
27pub const WALL_TRANS_REV: u16 = 512;
28
29// sprite cstat
30pub const SPR_BLOCK: u16 = 1;
31pub const SPR_TRANS: u16 = 2;
32pub const SPR_XFLIP: u16 = 4;
33pub const SPR_YFLIP: u16 = 8;
34pub const SPR_ALIGN_MASK: u16 = 48;
35pub const SPR_WALL: u16 = 16;
36pub const SPR_FLOOR: u16 = 32;
37pub const SPR_ONESIDED: u16 = 64;
38pub const SPR_CENTER: u16 = 128;
39pub const SPR_TRANS_REV: u16 = 512;
40pub const SPR_INVISIBLE: u16 = 32768;
41
42// plane stat
43pub const PLANE_PARALLAX: u16 = 1;
44pub const PLANE_SWAPXY: u16 = 4;
45pub const PLANE_SMOOSH: u16 = 8;
46pub const PLANE_XFLIP: u16 = 16;
47pub const PLANE_YFLIP: u16 = 32;
48pub const PLANE_RELATIVE: u16 = 64;
49
50#[derive(Debug, Clone, Copy, Default)]
51pub struct Camera {
52    pub x: f64,
53    pub y: f64,
54    pub z: f64,
55    /// Build angle units (2048 per turn).
56    pub ang: f64,
57    /// Vertical look offset in 200-line units (0 = level, positive = look down).
58    pub horiz: f64,
59    pub sector: i32,
60}
61
62/// A sprite prepared by the game for drawing (picnum already animated/rotated if desired).
63#[derive(Debug, Clone, Copy, Default)]
64pub struct SpriteDraw {
65    pub x: f64,
66    pub y: f64,
67    pub z: f64,
68    pub picnum: i32,
69    pub cstat: u16,
70    pub shade: i32,
71    pub pal: u8,
72    pub xrepeat: u8,
73    pub yrepeat: u8,
74    pub xoffset: i8,
75    pub yoffset: i8,
76    pub ang: f64,
77    pub sector: i32,
78    /// Voxel model index into [`Scene::voxels`] (drawn instead of the tile).
79    pub voxel: Option<u32>,
80    /// Non-zero for sprites seen through a room-over-room portal: only drawn on pixels
81    /// that show that portal (see [`portal_id`]).
82    pub portal: u32,
83}
84
85/// Id of the see-through plane of sector `s` (floor or ceiling) in the portal mask.
86pub fn portal_id(s: usize, floor: bool) -> u32 {
87    1 + s as u32 * 2 + floor as u32
88}
89
90/// Room-over-room link: looking through a floor/ceiling continues in `sector`, offset by
91/// (dx, dy, dz) (Blood's stack / link markers).
92#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, PartialEq)]
93pub struct RorLink {
94    pub sector: i32,
95    pub dx: f64,
96    pub dy: f64,
97    pub dz: f64,
98}
99
100#[derive(serde::Serialize, serde::Deserialize, Debug, Clone, Copy, Default, PartialEq)]
101pub struct Ror {
102    pub floor: Option<RorLink>,
103    pub ceil: Option<RorLink>,
104}
105
106/// True-colour shade tables, one per palookup (`pal`), each `64 * 256` entries.
107pub struct ShadeLuts {
108    pub tables: Vec<Option<Vec<u32>>>,
109}
110
111impl ShadeLuts {
112    #[inline]
113    pub fn get(&self, pal: u8) -> &[u32] {
114        match &self.tables[pal as usize] {
115            Some(t) => t,
116            None => self.tables[0].as_deref().expect("palookup 0 missing"),
117        }
118    }
119}
120
121pub struct Scene<'a> {
122    pub sectors: &'a [Sector],
123    pub walls: &'a [Wall],
124    pub sprites: &'a [SpriteDraw],
125    pub tiles: &'a TileSet,
126    pub luts: &'a ShadeLuts,
127    pub sky_offsets: &'a [i16],
128    pub sky_bits: i32,
129    /// Global visibility (map header value; larger = darker with distance).
130    pub visibility: i32,
131    /// Game clock in 120 Hz ticks, used for tile animation.
132    pub clock: i32,
133    /// Voxel models by id.
134    pub voxels: &'a [Option<crate::voxel::Voxel>],
135    /// See-through floor/ceiling links per sector (may be empty).
136    pub ror: &'a [Ror],
137}
138
139#[derive(Clone, Copy)]
140struct MaskSeg {
141    t: f32,
142    wall: u32,
143    s: f32,
144    ytop: f32,
145    ybot: f32,
146    sect: u32,
147    next: u32,
148}
149
150#[derive(Clone, Copy)]
151enum SprKind {
152    Face {
153        sx0: f32,
154        sx1: f32,
155        depth: f32,
156    },
157    Wall {
158        ax: f64,
159        ay: f64,
160        bx: f64,
161        by: f64,
162        sx0: f32,
163        sx1: f32,
164    },
165    Floor {
166        sx0: f32,
167        sx1: f32,
168        /// Screen rows the sprite can cover (from its projected corners).
169        ry0: f32,
170        ry1: f32,
171        cos: f64,
172        sin: f64,
173        hw: f64,
174        hh: f64,
175    },
176    Voxel {
177        id: u32,
178        sx0: f32,
179        sx1: f32,
180        y0: f32,
181        y1: f32,
182        /// Nearest depth any part of the model can have (pixels already covered by
183        /// something nearer skip the ray cast).
184        tmin: f32,
185        /// Width axis and facing axis (unit vectors), xy units per voxel, z units per voxel.
186        w: (f64, f64),
187        f: (f64, f64),
188        unit: f64,
189        zunit: f64,
190    },
191}
192
193#[derive(Clone, Copy)]
194struct SprProj {
195    idx: usize,
196    depth: f32,
197    kind: SprKind,
198    ztop: f64,
199    zbot: f64,
200    pic: i32,
201}
202
203struct View {
204    w: usize,
205    h: usize,
206    fl: f64,
207    fly: f64,
208    horizon: f64,
209    cos: f64,
210    sin: f64,
211    /// Per screen row: vertical ray slope `k` (z units per unit of depth) and `1 / k`.
212    /// A flat plane's depth on a row is `height / k`, so it costs a multiply, not a divide.
213    row_k: Vec<f64>,
214    row_inv_k: Vec<f64>,
215}
216
217impl View {
218    #[inline]
219    fn dir(&self, x: usize) -> (f64, f64) {
220        let u = (x as f64 + 0.5 - self.w as f64 * 0.5) / self.fl;
221        (self.cos - self.sin * u, self.sin + self.cos * u)
222    }
223    #[inline]
224    fn proj_y(&self, z: f64, camz: f64, t: f64) -> f64 {
225        self.horizon + (z - camz) / 16.0 / t * self.fly
226    }
227}
228
229pub struct Renderer {
230    pub width: usize,
231    pub height: usize,
232    /// Row-major output, 0x00RRGGBB.
233    pub frame: Vec<u32>,
234    col_pix: Vec<u32>,
235    col_depth: Vec<f32>,
236    /// Per pixel: id of the portal it was drawn through (0 = none).
237    col_mask: Vec<u32>,
238    masked: Vec<Vec<MaskSeg>>,
239    visited: Vec<AtomicU8>,
240    /// Horizontal sky texels per full turn multiplier (tuning knob).
241    pub sky_scale: f64,
242    /// Vertical stretch emulating the 320x200 pixel aspect (1.2 in the original).
243    pub y_stretch: f64,
244    /// Milliseconds spent in the last frame: walls/planes, portal sprites + projection,
245    /// masked walls + sprites, output copy.
246    pub phase_ms: [f64; 4],
247    /// Also produce the row-major [`Renderer::frame`]. Callers that scale the column-major
248    /// image themselves ([`Renderer::columns`]) turn this off to skip a full-frame copy.
249    pub keep_rows: bool,
250    /// Portal ids seen in each column during the wall pass.
251    col_portals: Vec<Vec<u32>>,
252    pub stats_sectors: usize,
253    /// Projected sprites by kind (face, wall, floor, voxel) and masked wall segments.
254    pub stats_kinds: [usize; 5],
255}
256
257/// Distance (xy units) times visibility per shade step.
258const VIS_DIVISOR: f64 = 5.0 * 65536.0;
259
260/// Visibility of sector `si`: the map's global value scaled by the sector's own, stored as a
261/// signed byte offset (0 = use the global value).
262fn sector_vis(scene: &Scene, si: i32) -> f64 {
263    let vis = scene.visibility as f64;
264    match usize::try_from(si).ok().and_then(|i| scene.sectors.get(i)) {
265        Some(sec) if sec.visibility != 0 => vis * ((sec.visibility as u32 + 16) & 255) as f64 / 16.0,
266        _ => vis,
267    }
268}
269
270#[inline]
271fn shade_index(shade: i32) -> usize {
272    shade.clamp(0, NUM_SHADES as i32 - 1) as usize * 256
273}
274
275/// Euclidean `v mod n`, using a mask when `n` is a power of two (almost every Build
276/// texture): an integer division per pixel was a large part of the wall/floor cost.
277#[inline(always)]
278fn wrap(v: i64, n: i64) -> i64 {
279    if n & (n - 1) == 0 {
280        v & (n - 1)
281    } else {
282        v.rem_euclid(n)
283    }
284}
285
286#[inline]
287fn blend(dst: u32, src: u32, rev: bool) -> u32 {
288    // Approximation of Build's 1/3 - 2/3 translucency.
289    let (a, b) = if rev { (src, dst) } else { (dst, src) };
290    let mix = |sh: u32| -> u32 {
291        let x = (a >> sh) & 0xff;
292        let y = (b >> sh) & 0xff;
293        ((x * 2 + y) / 3) << sh
294    };
295    mix(16) | mix(8) | mix(0)
296}
297
298impl Renderer {
299    pub fn new(width: usize, height: usize) -> Self {
300        let mut r = Renderer {
301            width: 0,
302            height: 0,
303            frame: Vec::new(),
304            col_pix: Vec::new(),
305            col_depth: Vec::new(),
306            col_mask: Vec::new(),
307            masked: Vec::new(),
308            visited: Vec::new(),
309            sky_scale: 1.0,
310            // Vertical/horizontal focal ratio; 1.0 matched the original best (see EYE_STAND).
311            y_stretch: 1.0,
312            phase_ms: [0.0; 4],
313            keep_rows: true,
314            col_portals: Vec::new(),
315            stats_sectors: 0,
316            stats_kinds: [0; 5],
317        };
318        r.resize(width, height);
319        r
320    }
321
322    pub fn resize(&mut self, width: usize, height: usize) {
323        let width = width.max(1);
324        let height = height.max(1);
325        if width == self.width && height == self.height {
326            return;
327        }
328        self.width = width;
329        self.height = height;
330        self.frame = vec![0; width * height];
331        self.col_pix = vec![0; width * height];
332        self.col_depth = vec![f32::INFINITY; width * height];
333        self.col_mask = vec![0; width * height];
334        self.masked = (0..width).map(|_| Vec::new()).collect();
335        self.col_portals = (0..width).map(|_| Vec::new()).collect();
336    }
337
338    /// The last frame in column-major order: (pixels, width, height), `pixels[x * h + y]`.
339    pub fn columns(&self) -> (&[u32], usize, usize) {
340        (&self.col_pix, self.width, self.height)
341    }
342
343    fn view(&self, cam: &Camera) -> View {
344        let w = self.width;
345        let h = self.height;
346        // Hor+ field of view: a 4:3 region of the screen maps to 90 degrees.
347        let fl = h as f64 * 2.0 / 3.0;
348        let a = ang_to_rad(cam.ang);
349        let fly = fl * self.y_stretch;
350        let horizon = h as f64 * 0.5 - cam.horiz * h as f64 / 200.0;
351        let row_k: Vec<f64> = (0..h).map(|y| (y as f64 + 0.5 - horizon) / fly * 16.0).collect();
352        let row_inv_k = row_k
353            .iter()
354            .map(|&k| if k.abs() < 1e-12 { 0.0 } else { 1.0 / k })
355            .collect();
356        View {
357            w,
358            h,
359            fl,
360            fly,
361            horizon,
362            cos: a.cos(),
363            sin: a.sin(),
364            row_k,
365            row_inv_k,
366        }
367    }
368
369    /// Distance in xy units for a depth value (used for fog/visibility shading).
370    #[inline]
371    fn vis_shade(vis: f64, t: f64) -> i32 {
372        // Fitted to DOSBox captures of nine map starts (mean block-brightness error 7.4 ->
373        // 4.3 on a 0-255 scale): distance darkens about 3.2x faster than the old 1/2^20.
374        (t * vis / VIS_DIVISOR) as i32
375    }
376
377    pub fn render(&mut self, scene: &Scene, cam: &Camera) {
378        let view = self.view(cam);
379        let h = self.height;
380        if self.visited.len() != scene.sectors.len() {
381            self.visited = (0..scene.sectors.len()).map(|_| AtomicU8::new(0)).collect();
382        } else {
383            for v in &self.visited {
384                v.store(0, Ordering::Relaxed);
385            }
386        }
387        let sky_scale = self.sky_scale;
388        let visited = &self.visited;
389
390        // Pass 1: opaque world.
391        let t0 = std::time::Instant::now();
392        self.col_pix
393            .par_chunks_mut(h)
394            .zip(self.col_depth.par_chunks_mut(h))
395            .zip(self.col_mask.par_chunks_mut(h))
396            .zip(self.masked.par_iter_mut())
397            .zip(self.col_portals.par_iter_mut())
398            .enumerate()
399            .for_each(|(x, ((((pix, depth), mask), masked), portals))| {
400                masked.clear();
401                // The mask only holds marks where this column showed a portal last frame;
402                // everywhere else it is already clear (clearing the whole screen every frame
403                // was a large share of the memory traffic at high resolutions).
404                if !portals.is_empty() {
405                    mask.fill(0);
406                    portals.clear();
407                }
408                cast_column(
409                    x, scene, cam, &view, sky_scale, pix, depth, mask, portals, masked, visited,
410                );
411            });
412
413        let t1 = std::time::Instant::now();
414        // Sprites in rooms seen through floor/ceiling portals, moved into the viewer's frame.
415        let mut portal_sprites: Vec<SpriteDraw> = Vec::new();
416        let mut seen: Vec<u32> = Vec::new();
417        for ids in &self.col_portals {
418            for &m in ids {
419                if !seen.contains(&m) {
420                    seen.push(m);
421                }
422            }
423        }
424        seen.sort_unstable();
425        for id in seen {
426            let si = ((id - 1) / 2) as usize;
427            let floor = (id - 1) % 2 == 1;
428            let Some(r) = scene.ror.get(si) else { continue };
429            let Some(l) = (if floor { r.floor } else { r.ceil }) else {
430                continue;
431            };
432            let room = linked_room(scene, l.sector, 96);
433            for sp in scene
434                .sprites
435                .iter()
436                .filter(|sp| sp.portal == 0 && sp.sector >= 0 && room.contains(&(sp.sector as usize)))
437            {
438                portal_sprites.push(SpriteDraw {
439                    x: sp.x - l.dx,
440                    y: sp.y - l.dy,
441                    z: sp.z - l.dz,
442                    portal: id,
443                    ..*sp
444                });
445            }
446        }
447        let combined: Vec<SpriteDraw>;
448        let scene_with_portals;
449        let scene = if portal_sprites.is_empty() {
450            scene
451        } else {
452            combined = scene.sprites.iter().copied().chain(portal_sprites).collect();
453            scene_with_portals = Scene {
454                sprites: &combined,
455                ..*scene
456            };
457            &scene_with_portals
458        };
459
460        self.stats_sectors = self.visited.iter().filter(|v| v.load(Ordering::Relaxed) != 0).count();
461
462        // Project visible sprites.
463        let mut sprites: Vec<SprProj> = scene
464            .sprites
465            .iter()
466            .enumerate()
467            .filter(|(_, s)| {
468                s.cstat & SPR_INVISIBLE == 0
469                    && s.sector >= 0
470                    && (s.portal != 0
471                        || (s.sector as usize) < self.visited.len()
472                            && self.visited[s.sector as usize].load(Ordering::Relaxed) != 0)
473            })
474            .filter_map(|(i, s)| project_sprite(i, s, scene, cam, &view))
475            .collect();
476        sprites.sort_by(|a, b| b.depth.partial_cmp(&a.depth).unwrap_or(std::cmp::Ordering::Equal));
477        let mut kinds = [0usize; 5];
478        for sp in &sprites {
479            kinds[match sp.kind {
480                SprKind::Face { .. } => 0,
481                SprKind::Wall { .. } => 1,
482                SprKind::Floor { .. } => 2,
483                SprKind::Voxel { .. } => 3,
484            }] += 1;
485        }
486        kinds[4] = self.masked.iter().map(|m| m.len()).sum();
487        self.stats_kinds = kinds;
488
489        // Pass 2: masked walls and sprites, back to front.
490        let t2 = std::time::Instant::now();
491        self.col_pix
492            .par_chunks_mut(h)
493            .zip(self.col_depth.par_chunks(h))
494            .zip(self.col_mask.par_chunks(h))
495            .zip(self.masked.par_iter_mut())
496            .enumerate()
497            .for_each(|(x, (((pix, depth), mask), masked))| {
498                masked.sort_by(|a, b| b.t.partial_cmp(&a.t).unwrap_or(std::cmp::Ordering::Equal));
499                let mut mi = 0;
500                for sp in &sprites {
501                    while mi < masked.len() && masked[mi].t > sp.depth {
502                        draw_masked(x, &masked[mi], scene, cam, &view, pix, depth);
503                        mi += 1;
504                    }
505                    draw_sprite_column(x, sp, scene, cam, &view, pix, depth, mask);
506                }
507                while mi < masked.len() {
508                    draw_masked(x, &masked[mi], scene, cam, &view, pix, depth);
509                    mi += 1;
510                }
511            });
512
513        // Transpose column-major into row-major output.
514        let t3 = std::time::Instant::now();
515        if !self.keep_rows {
516            self.phase_ms = [
517                (t1 - t0).as_secs_f64() * 1e3,
518                (t2 - t1).as_secs_f64() * 1e3,
519                (t3 - t2).as_secs_f64() * 1e3,
520                0.0,
521            ];
522            return;
523        }
524        let w = self.width;
525        let col = &self.col_pix;
526        // In bands of rows so each column is read as a short contiguous run (a plain
527        // per-pixel strided read was a quarter of the frame time at 8K).
528        const BAND: usize = 32;
529        self.frame
530            .par_chunks_mut(w * BAND)
531            .enumerate()
532            .for_each(|(band, rows)| {
533                let y0 = band * BAND;
534                let n = rows.len() / w;
535                for x in 0..w {
536                    let src = &col[x * h + y0..x * h + y0 + n];
537                    for (k, &p) in src.iter().enumerate() {
538                        rows[k * w + x] = p;
539                    }
540                }
541            });
542        let t4 = std::time::Instant::now();
543        let ms = |a: std::time::Instant, b: std::time::Instant| (b - a).as_secs_f64() * 1e3;
544        self.phase_ms = [ms(t0, t1), ms(t1, t2), ms(t2, t3), ms(t3, t4)];
545    }
546
547    /// Depth (perpendicular distance) at screen pixel, for hit tests and debugging.
548    pub fn depth_at(&self, x: usize, y: usize) -> f32 {
549        self.col_depth[x * self.height + y]
550    }
551}
552
553struct PlaneCtx<'a> {
554    eq: PlaneEq,
555    plane: &'a crate::map::Plane,
556    sector: &'a Sector,
557    walls: &'a [Wall],
558    link: Option<RorLink>,
559}
560
561#[allow(clippy::too_many_arguments)]
562fn cast_column(
563    x: usize,
564    scene: &Scene,
565    cam: &Camera,
566    view: &View,
567    sky_scale: f64,
568    pix: &mut [u32],
569    depth: &mut [f32],
570    mask: &mut [u32],
571    portals: &mut Vec<u32>,
572    masked: &mut Vec<MaskSeg>,
573    visited: &[AtomicU8],
574) {
575    let h = view.h;
576    // Marks rows drawn by a see-through plane with that portal's id.
577    // Marks rows drawn by a see-through plane with that portal's id, and records the id.
578    let mark = |mask: &mut [u32], portals: &mut Vec<u32>, y0: f64, y1: f64, id: u32| {
579        let r0 = y0.max(0.0).ceil() as usize;
580        let r1 = (y1.min(h as f64).ceil() as isize).max(0) as usize;
581        if r0 >= r1 {
582            return;
583        }
584        for m in mask.iter_mut().take(r1).skip(r0) {
585            *m = id;
586        }
587        if !portals.contains(&id) {
588            portals.push(id);
589        }
590    };
591    let (dx, dy) = view.dir(x);
592    let mut sect = cam.sector;
593    let mut ytop = 0.0f64;
594    let mut ybot = h as f64;
595    let mut t_enter = 0.0f64;
596    let mut filled_to_top = 0usize; // rows < this are final
597    let _ = &mut filled_to_top;
598    let sectors = scene.sectors;
599    let walls = scene.walls;
600    for _ in 0..1024 {
601        if sect < 0 || sect as usize >= sectors.len() {
602            break;
603        }
604        let si = sect as usize;
605        visited[si].store(1, Ordering::Relaxed);
606        let sec = &sectors[si];
607        let vis_s = sector_vis(scene, si as i32);
608
609        // Find exit wall: nearest crossing beyond the entry distance.
610        let mut best: Option<(f64, f64, usize)> = None;
611        let start = sec.wallptr as usize;
612        let end = start + sec.wallnum as usize;
613        for wi in start..end.min(walls.len()) {
614            let w1 = &walls[wi];
615            let w2 = &walls[w1.point2 as usize];
616            if let Some((t, s)) = ray_segment(cam.x, cam.y, dx, dy, w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64)
617            {
618                if t > t_enter + 1e-7 && best.is_none_or(|b| t < b.0) {
619                    best = Some((t, s, wi));
620                }
621            }
622        }
623
624        let ceq = plane_eq(sec, walls, &sec.ceiling);
625        let feq = plane_eq(sec, walls, &sec.floor);
626        let ror = scene.ror.get(si).copied().unwrap_or_default();
627        let cctx = PlaneCtx {
628            eq: ceq,
629            plane: &sec.ceiling,
630            sector: sec,
631            walls,
632            link: ror.ceil,
633        };
634        let fctx = PlaneCtx {
635            eq: feq,
636            plane: &sec.floor,
637            sector: sec,
638            walls,
639            link: ror.floor,
640        };
641
642        let Some((t, s, wi)) = best else {
643            // Open-ended (degenerate) sector: fill the rest with planes.
644            let mid = view.horizon.clamp(ytop, ybot);
645            draw_plane(
646                &cctx, scene, cam, view, sky_scale, dx, dy, x, ytop, mid, vis_s, pix, depth,
647            );
648            draw_plane(
649                &fctx, scene, cam, view, sky_scale, dx, dy, x, mid, ybot, vis_s, pix, depth,
650            );
651            if cctx.link.is_some() {
652                mark(mask, portals, ytop, mid, portal_id(si, false));
653            }
654            if fctx.link.is_some() {
655                mark(mask, portals, mid, ybot, portal_id(si, true));
656            }
657            break;
658        };
659        let t = t.max(1e-3);
660        let hx = cam.x + dx * t;
661        let hy = cam.y + dy * t;
662        let cz = ceq.z_at(hx, hy);
663        let fz = feq.z_at(hx, hy);
664        let yc = view.proj_y(cz, cam.z, t);
665        let yf = view.proj_y(fz, cam.z, t);
666
667        draw_plane(
668            &cctx,
669            scene,
670            cam,
671            view,
672            sky_scale,
673            dx,
674            dy,
675            x,
676            ytop,
677            yc.min(ybot),
678            vis_s,
679            pix,
680            depth,
681        );
682        draw_plane(
683            &fctx,
684            scene,
685            cam,
686            view,
687            sky_scale,
688            dx,
689            dy,
690            x,
691            yf.max(ytop),
692            ybot,
693            vis_s,
694            pix,
695            depth,
696        );
697        if cctx.link.is_some() {
698            mark(mask, portals, ytop, yc.min(ybot), portal_id(si, false));
699        }
700        if fctx.link.is_some() {
701            mark(mask, portals, yf.max(ytop), ybot, portal_id(si, true));
702        }
703
704        let wall = &walls[wi];
705        let ns = wall.nextsector;
706        let wlen = {
707            let w2 = &walls[wall.point2 as usize];
708            ((w2.x - wall.x) as f64).hypot((w2.y - wall.y) as f64)
709        };
710        let _ = wlen;
711        if ns < 0 || ns as usize >= sectors.len() {
712            let zref = if wall.cstat & WALL_ALIGN_BOTTOM != 0 {
713                sec.floor.z
714            } else {
715                sec.ceiling.z
716            } as f64;
717            draw_wall_span(
718                wall,
719                wall.picnum,
720                wall.xpanning,
721                wall.ypanning,
722                s,
723                t,
724                zref,
725                ytop.max(yc),
726                ybot.min(yf),
727                scene,
728                cam,
729                view,
730                vis_s,
731                pix,
732                depth,
733            );
734            break;
735        }
736        let nsec = &sectors[ns as usize];
737        let nceq = plane_eq(nsec, walls, &nsec.ceiling);
738        let nfeq = plane_eq(nsec, walls, &nsec.floor);
739        let ncz = nceq.z_at(hx, hy);
740        let nfz = nfeq.z_at(hx, hy);
741        let ync = view.proj_y(ncz, cam.z, t);
742        let ynf = view.proj_y(nfz, cam.z, t);
743        let both_sky_c = sec.ceiling.stat & PLANE_PARALLAX != 0 && nsec.ceiling.stat & PLANE_PARALLAX != 0;
744        let both_sky_f = sec.floor.stat & PLANE_PARALLAX != 0 && nsec.floor.stat & PLANE_PARALLAX != 0;
745
746        // Upper wall.
747        if !both_sky_c && ync > yc {
748            let zref = if wall.cstat & WALL_ALIGN_BOTTOM != 0 {
749                sec.ceiling.z
750            } else {
751                nsec.ceiling.z
752            } as f64;
753            draw_wall_span(
754                wall,
755                wall.picnum,
756                wall.xpanning,
757                wall.ypanning,
758                s,
759                t,
760                zref,
761                ytop.max(yc),
762                ybot.min(ync),
763                scene,
764                cam,
765                view,
766                vis_s,
767                pix,
768                depth,
769            );
770        }
771        // Lower wall.
772        if !both_sky_f && ynf < yf {
773            let (pic, xp, yp, src) = if wall.cstat & WALL_BOTTOM_SWAP != 0 && wall.nextwall >= 0 {
774                let nw = &walls[wall.nextwall as usize];
775                (nw.picnum, nw.xpanning, nw.ypanning, nw)
776            } else {
777                (wall.picnum, wall.xpanning, wall.ypanning, wall)
778            };
779            let zref = if src.cstat & WALL_ALIGN_BOTTOM != 0 {
780                sec.ceiling.z
781            } else {
782                nsec.floor.z
783            } as f64;
784            draw_wall_span(
785                wall,
786                pic,
787                xp,
788                yp,
789                s,
790                t,
791                zref,
792                ytop.max(ynf),
793                ybot.min(yf),
794                scene,
795                cam,
796                view,
797                vis_s,
798                pix,
799                depth,
800            );
801        }
802
803        if !both_sky_c {
804            ytop = ytop.max(yc).max(ync);
805        }
806        if !both_sky_f {
807            ybot = ybot.min(yf).min(ynf);
808        }
809        if wall.cstat & WALL_MASKED != 0 && ytop < ybot {
810            masked.push(MaskSeg {
811                t: t as f32,
812                wall: wi as u32,
813                s: s as f32,
814                ytop: ytop as f32,
815                ybot: ybot as f32,
816                sect: si as u32,
817                next: ns as u32,
818            });
819        }
820        if ytop >= ybot {
821            break;
822        }
823        t_enter = t;
824        sect = ns as i32;
825    }
826}
827
828#[allow(clippy::too_many_arguments)]
829fn draw_plane(
830    p: &PlaneCtx,
831    scene: &Scene,
832    cam: &Camera,
833    view: &View,
834    sky_scale: f64,
835    dx: f64,
836    dy: f64,
837    x: usize,
838    y0: f64,
839    y1: f64,
840    vis: f64,
841    pix: &mut [u32],
842    depth: &mut [f32],
843) {
844    let h = view.h as f64;
845    let r0 = y0.max(0.0).ceil() as usize;
846    let r1 = (y1.min(h).ceil() as isize).max(0) as usize;
847    if r0 >= r1 {
848        return;
849    }
850    let pic = scene.tiles.animate(p.plane.picnum as i32, scene.clock);
851    let a = p.eq.z_at(cam.x, cam.y);
852    let b = p.eq.bx * dx + p.eq.by * dy;
853    let lut = scene.luts.get(p.plane.pal);
854
855    if let Some(l) = p.link {
856        // Look through the plane into the linked room. Every pixel of this column travels
857        // along the same 2D line, so the sectors it crosses are found once per column.
858        let mut tmin = f64::INFINITY;
859        for y in r0..r1 {
860            let k = (y as f64 + 0.5 - view.horizon) / view.fly * 16.0;
861            let den = k - b;
862            let t = if den.abs() > 1e-12 { (a - cam.z) / den } else { -1.0 };
863            if t > 0.0 {
864                tmin = tmin.min(t);
865            }
866        }
867        let (ox, oy, oz) = (cam.x + l.dx, cam.y + l.dy, cam.z + l.dz);
868        let mut segs = ColTrace::new(scene, l.sector, ox, oy, dx, dy, tmin);
869        for y in r0..r1 {
870            let k = (y as f64 + 0.5 - view.horizon) / view.fly * 16.0;
871            let den = k - b;
872            let t = if den.abs() > 1e-12 { (a - cam.z) / den } else { -1.0 };
873            if t.is_nan() || t <= 0.0 {
874                pix[y] = 0;
875                depth[y] = f32::INFINITY;
876                continue;
877            }
878            let (c, tt) = trace_column(scene, &mut segs, ox, oy, oz, dx, dy, k, t);
879            pix[y] = c;
880            depth[y] = tt as f32;
881        }
882        return;
883    }
884
885    if p.plane.stat & PLANE_PARALLAX != 0 {
886        draw_sky(
887            p, pic, scene, cam, view, sky_scale, dx, dy, x, r0, r1, a, b, lut, pix, depth,
888        );
889        return;
890    }
891
892    let tile = scene.tiles.get(pic);
893    let shade = p.plane.shade as i32;
894    if tile.is_empty() {
895        for y in r0..r1 {
896            pix[y] = 0;
897            depth[y] = f32::INFINITY;
898        }
899        return;
900    }
901    let tw = tile.width as i64;
902    let th = tile.height as i64;
903    let stat = p.plane.stat;
904    let texel = if stat & PLANE_SMOOSH != 0 { 8.0 } else { 16.0 };
905
906    // Relative alignment: rotate into the first wall's frame.
907    let (ox, oy, ux, uy) = if stat & PLANE_RELATIVE != 0 && p.sector.wallnum >= 2 {
908        let w1 = &p.walls[p.sector.wallptr as usize];
909        let w2 = &p.walls[w1.point2 as usize];
910        let ex = (w2.x - w1.x) as f64;
911        let ey = (w2.y - w1.y) as f64;
912        let l = ex.hypot(ey).max(1e-9);
913        (w1.x as f64, w1.y as f64, ex / l, ey / l)
914    } else {
915        (0.0, 0.0, 1.0, 0.0)
916    };
917    let xpan = p.plane.xpan as f64 * tw as f64 / 256.0;
918    let ypan = p.plane.ypan as f64 * th as f64 / 256.0;
919    // Orientation flags folded into one linear map (u, v) = M (px, py), in texels.
920    let (mut m00, mut m01, mut m10, mut m11) = if stat & PLANE_RELATIVE != 0 {
921        (ux, uy, -uy, ux)
922    } else {
923        (1.0, 0.0, 0.0, 1.0)
924    };
925    if stat & PLANE_SWAPXY != 0 {
926        std::mem::swap(&mut m00, &mut m10);
927        std::mem::swap(&mut m01, &mut m11);
928    }
929    if stat & PLANE_XFLIP != 0 {
930        m00 = -m00;
931        m01 = -m01;
932    }
933    if stat & PLANE_YFLIP != 0 {
934        m10 = -m10;
935        m11 = -m11;
936    }
937    let inv_texel = 1.0 / texel;
938    let (m00, m01, m10, m11) = (m00 * inv_texel, m01 * inv_texel, m10 * inv_texel, m11 * inv_texel);
939    let k_scale = 16.0 / view.fly;
940    let height = a - cam.z;
941
942    let flat = b == 0.0;
943    for y in r0..r1 {
944        let k = if flat {
945            view.row_k[y]
946        } else {
947            (y as f64 + 0.5 - view.horizon) * k_scale
948        };
949        let den = k - b;
950        if den.abs() < 1e-12 {
951            pix[y] = 0;
952            depth[y] = f32::INFINITY;
953            continue;
954        }
955        let mut t = if flat { height * view.row_inv_k[y] } else { height / den };
956        if t.is_nan() || t <= 0.0 {
957            t = 1e9;
958        }
959        let px = cam.x + dx * t - ox;
960        let py = cam.y + dy * t - oy;
961        let tu = wrap((px * m00 + py * m01 + xpan).floor() as i64, tw);
962        let tv = wrap((px * m10 + py * m11 + ypan).floor() as i64, th);
963        let c = tile.pixels[(tu * th + tv) as usize];
964        let sh = shade + Renderer::vis_shade(vis, t);
965        pix[y] = lut[shade_index(sh) + c as usize];
966        depth[y] = t as f32;
967    }
968}
969
970/// Sectors reachable from `start` through open walls (bounded), i.e. one "room".
971fn linked_room(scene: &Scene, start: i32, limit: usize) -> Vec<usize> {
972    let mut out = Vec::new();
973    if start < 0 || start as usize >= scene.sectors.len() {
974        return out;
975    }
976    out.push(start as usize);
977    let mut i = 0;
978    while i < out.len() && out.len() < limit {
979        let sec = &scene.sectors[out[i]];
980        for wi in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
981            let ns = scene.walls[wi].nextsector;
982            if ns >= 0 && !out.contains(&(ns as usize)) {
983                out.push(ns as usize);
984            }
985        }
986        i += 1;
987    }
988    out
989}
990
991/// Texture colour of a floor or ceiling at world point (px, py), `t` units away.
992fn sample_plane(scene: &Scene, si: usize, floor: bool, px: f64, py: f64, t: f64) -> u32 {
993    let sec = &scene.sectors[si];
994    let plane = if floor { &sec.floor } else { &sec.ceiling };
995    let lut = scene.luts.get(plane.pal);
996    let pic = scene.tiles.animate(plane.picnum as i32, scene.clock);
997    let tile = scene.tiles.get(pic);
998    let sh = shade_index(plane.shade as i32 + Renderer::vis_shade(sector_vis(scene, si as i32), t));
999    if tile.is_empty() {
1000        return lut[sh];
1001    }
1002    let (tw, th) = (tile.width as i64, tile.height as i64);
1003    let stat = plane.stat;
1004    let texel = if stat & PLANE_SMOOSH != 0 { 8.0 } else { 16.0 };
1005    let (mut u, mut v) = if stat & PLANE_RELATIVE != 0 && sec.wallnum >= 2 {
1006        let w1 = &scene.walls[sec.wallptr as usize];
1007        let w2 = &scene.walls[w1.point2 as usize];
1008        let (ex, ey) = ((w2.x - w1.x) as f64, (w2.y - w1.y) as f64);
1009        let l = ex.hypot(ey).max(1e-9);
1010        let (ux, uy) = (ex / l, ey / l);
1011        let (rx, ry) = (px - w1.x as f64, py - w1.y as f64);
1012        (rx * ux + ry * uy, -rx * uy + ry * ux)
1013    } else {
1014        (px, py)
1015    };
1016    if stat & PLANE_SWAPXY != 0 {
1017        std::mem::swap(&mut u, &mut v);
1018    }
1019    if stat & PLANE_XFLIP != 0 {
1020        u = -u;
1021    }
1022    if stat & PLANE_YFLIP != 0 {
1023        v = -v;
1024    }
1025    let tu = ((u / texel + plane.xpan as f64 * tw as f64 / 256.0).floor() as i64).rem_euclid(tw);
1026    let tv = ((v / texel + plane.ypan as f64 * th as f64 / 256.0).floor() as i64).rem_euclid(th);
1027    lut[sh + tile.pixels[(tu * th + tv) as usize] as usize]
1028}
1029
1030/// Texture colour of a wall at position `s` (0..1 along it) and height `z`.
1031#[allow(clippy::too_many_arguments)]
1032fn sample_wall(
1033    scene: &Scene,
1034    si: usize,
1035    wall: &Wall,
1036    picnum: i16,
1037    xpan: u8,
1038    ypan: u8,
1039    s: f64,
1040    z: f64,
1041    zref: f64,
1042    t: f64,
1043) -> u32 {
1044    let lut = scene.luts.get(wall.pal);
1045    let tile = scene.tiles.get(scene.tiles.animate(picnum as i32, scene.clock));
1046    let sh = shade_index(wall.shade as i32 + Renderer::vis_shade(sector_vis(scene, si as i32), t));
1047    if tile.is_empty() {
1048        return lut[sh];
1049    }
1050    let (tw, th) = (tile.width as i64, tile.height as i64);
1051    let mut tx = ((s * wall.xrepeat as f64 * 8.0).floor() as i64 + xpan as i64).rem_euclid(tw);
1052    if wall.cstat & WALL_XFLIP != 0 {
1053        tx = tw - 1 - tx;
1054    }
1055    let mut v = ((z - zref) * wall.yrepeat as f64 / 1024.0 + ypan as f64 * th as f64 / 256.0).floor() as i64;
1056    if wall.cstat & WALL_YFLIP != 0 {
1057        v = -v - 1;
1058    }
1059    lut[sh + tile.pixels[(tx * th + v.rem_euclid(th)) as usize] as usize]
1060}
1061
1062/// Traces one pixel's ray through sectors starting at (ox, oy, oz) in sector `s`.
1063/// `dz` is z units per xy unit; `t_base` is the distance already travelled.
1064#[allow(clippy::too_many_arguments)]
1065/// One stretch of a column's 2D ray inside a sector (global ray parameter `t`).
1066struct ColSeg {
1067    sector: usize,
1068    t1: f64,
1069    ceil: PlaneEq,
1070    floor: PlaneEq,
1071    /// Wall hit at `t1` (index, position along it) and, for a portal, the next sector's
1072    /// ceiling/floor heights at the hit point.
1073    wall: Option<WallHit>,
1074}
1075
1076/// (wall index, position along the wall, next sector's (ceiling, floor) z for a portal).
1077type WallHit = (usize, f64, Option<(f64, f64)>);
1078
1079/// Sectors crossed by a column's ray `(ox, oy) + t (dx, dy)`, found lazily: only as far
1080/// along as some pixel of the column actually reaches.
1081struct ColTrace {
1082    segs: Vec<ColSeg>,
1083    /// Next sector to enter and the ray parameter where it starts (-1 = finished).
1084    next: i32,
1085    t_in: f64,
1086    ox: f64,
1087    oy: f64,
1088    dx: f64,
1089    dy: f64,
1090}
1091
1092impl ColTrace {
1093    fn new(scene: &Scene, start: i32, ox: f64, oy: f64, dx: f64, dy: f64, t_start: f64) -> ColTrace {
1094        let (sectors, walls) = (scene.sectors, scene.walls);
1095        let mut s = -1;
1096        if t_start.is_finite() {
1097            let (sx, sy) = (ox + dx * t_start, oy + dy * t_start);
1098            s = start;
1099            if s < 0 || s as usize >= sectors.len() || !crate::geom::inside_sector(sectors, walls, s as usize, sx, sy) {
1100                s = crate::geom::update_sector(sectors, walls, sx, sy, s);
1101            }
1102        }
1103        ColTrace {
1104            segs: Vec::with_capacity(8),
1105            next: s,
1106            t_in: t_start,
1107            ox,
1108            oy,
1109            dx,
1110            dy,
1111        }
1112    }
1113
1114    /// Segment `i`, computing it (and any before it) if needed.
1115    fn get(&mut self, scene: &Scene, i: usize) -> Option<&ColSeg> {
1116        let (sectors, walls) = (scene.sectors, scene.walls);
1117        while self.segs.len() <= i {
1118            if self.next < 0 || self.segs.len() >= 64 {
1119                return None;
1120            }
1121            let si = self.next as usize;
1122            let sec = &sectors[si];
1123            let (ox, oy, dx, dy) = (self.ox, self.oy, self.dx, self.dy);
1124            let mut best: Option<(f64, f64, usize)> = None;
1125            for wi in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
1126                let w1 = &walls[wi];
1127                let w2 = &walls[w1.point2 as usize];
1128                if let Some((t, u)) = ray_segment(ox, oy, dx, dy, w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64) {
1129                    if t > self.t_in + 1e-7 && best.is_none_or(|b| t < b.0) {
1130                        best = Some((t, u, wi));
1131                    }
1132                }
1133            }
1134            let ceil = plane_eq(sec, walls, &sec.ceiling);
1135            let floor = plane_eq(sec, walls, &sec.floor);
1136            let Some((t, u, wi)) = best else {
1137                self.segs.push(ColSeg {
1138                    sector: si,
1139                    t1: 1e9,
1140                    ceil,
1141                    floor,
1142                    wall: None,
1143                });
1144                self.next = -1;
1145                continue;
1146            };
1147            let w = &walls[wi];
1148            let next = (w.nextsector >= 0)
1149                .then(|| crate::geom::zs_of_slope(sectors, walls, w.nextsector as usize, ox + dx * t, oy + dy * t));
1150            self.segs.push(ColSeg {
1151                sector: si,
1152                t1: t,
1153                ceil,
1154                floor,
1155                wall: Some((wi, u, next)),
1156            });
1157            self.next = w.nextsector as i32;
1158            self.t_in = t;
1159        }
1160        self.segs.get(i)
1161    }
1162}
1163
1164/// Colour and depth for one pixel's ray `(ox, oy, oz) + t (dx, dy, dz)` entering the linked
1165/// room at `t_entry`, using the column's precomputed sector list. Same result as
1166/// [`trace_pixel`], which still handles portals nested inside the linked room.
1167#[allow(clippy::too_many_arguments)]
1168fn trace_column(
1169    scene: &Scene,
1170    segs: &mut ColTrace,
1171    ox: f64,
1172    oy: f64,
1173    oz: f64,
1174    dx: f64,
1175    dy: f64,
1176    dz: f64,
1177    t_entry: f64,
1178) -> (u32, f64) {
1179    let (sectors, walls) = (scene.sectors, scene.walls);
1180    let mut t_in = t_entry;
1181    let mut idx = 0;
1182    while let Some(g) = segs.get(scene, idx) {
1183        idx += 1;
1184        if g.t1 <= t_entry + 1e-7 {
1185            continue;
1186        }
1187        let si = g.sector;
1188        let sec = &sectors[si];
1189        let ror = scene.ror.get(si).copied().unwrap_or_default();
1190        for (floor, eq) in [(false, &g.ceil), (true, &g.floor)] {
1191            // Plane height along the ray: a + b t.
1192            let a = eq.z_at(ox, oy);
1193            let b = eq.bx * dx + eq.by * dy;
1194            let den = dz - b;
1195            if den.abs() < 1e-12 || (floor && den < 0.0) || (!floor && den > 0.0) {
1196                continue;
1197            }
1198            let t = (a - oz) / den;
1199            if t < t_in - 1e-6 || t > g.t1 {
1200                continue;
1201            }
1202            let (hx, hy, hz) = (ox + dx * t, oy + dy * t, oz + dz * t);
1203            let link = if floor { ror.floor } else { ror.ceil };
1204            if let Some(l2) = link {
1205                return trace_pixel(scene, l2.sector, hx + l2.dx, hy + l2.dy, hz + l2.dz, dx, dy, dz, t, 2);
1206            }
1207            return (sample_plane(scene, si, floor, hx, hy, t), t);
1208        }
1209        let Some((wi, u, next)) = g.wall else {
1210            return (0, f64::INFINITY);
1211        };
1212        let w = &walls[wi];
1213        let t = g.t1;
1214        let hz = oz + dz * t;
1215        match next {
1216            None => {
1217                let zref = if w.cstat & WALL_ALIGN_BOTTOM != 0 {
1218                    sec.floor.z
1219                } else {
1220                    sec.ceiling.z
1221                } as f64;
1222                return (
1223                    sample_wall(scene, si, w, w.picnum, w.xpanning, w.ypanning, u, hz, zref, t),
1224                    t,
1225                );
1226            }
1227            Some((c, f)) => {
1228                let ns = w.nextsector as usize;
1229                if hz < c {
1230                    let zref = if w.cstat & WALL_ALIGN_BOTTOM != 0 {
1231                        sec.ceiling.z
1232                    } else {
1233                        sectors[ns].ceiling.z
1234                    } as f64;
1235                    return (
1236                        sample_wall(scene, si, w, w.picnum, w.xpanning, w.ypanning, u, hz, zref, t),
1237                        t,
1238                    );
1239                }
1240                if hz > f {
1241                    let src = if w.cstat & WALL_BOTTOM_SWAP != 0 && w.nextwall >= 0 {
1242                        &walls[w.nextwall as usize]
1243                    } else {
1244                        w
1245                    };
1246                    let zref = if src.cstat & WALL_ALIGN_BOTTOM != 0 {
1247                        sec.ceiling.z
1248                    } else {
1249                        sectors[ns].floor.z
1250                    } as f64;
1251                    return (
1252                        sample_wall(scene, si, w, src.picnum, src.xpanning, src.ypanning, u, hz, zref, t),
1253                        t,
1254                    );
1255                }
1256            }
1257        }
1258        t_in = t;
1259    }
1260    (0, f64::INFINITY)
1261}
1262
1263#[allow(clippy::too_many_arguments)]
1264fn trace_pixel(
1265    scene: &Scene,
1266    mut s: i32,
1267    ox: f64,
1268    oy: f64,
1269    oz: f64,
1270    dx: f64,
1271    dy: f64,
1272    dz: f64,
1273    t_base: f64,
1274    depth: u32,
1275) -> (u32, f64) {
1276    let (sectors, walls) = (scene.sectors, scene.walls);
1277    if s < 0 || s as usize >= sectors.len() || !crate::geom::inside_sector(sectors, walls, s as usize, ox, oy) {
1278        s = crate::geom::update_sector(sectors, walls, ox, oy, s);
1279    }
1280    let mut t_in = 0.0f64;
1281    for _ in 0..64 {
1282        if s < 0 {
1283            return (0, f64::INFINITY);
1284        }
1285        let si = s as usize;
1286        let sec = &sectors[si];
1287        let mut best: Option<(f64, f64, usize)> = None;
1288        for wi in sec.wallptr as usize..(sec.wallptr + sec.wallnum) as usize {
1289            let w1 = &walls[wi];
1290            let w2 = &walls[w1.point2 as usize];
1291            if let Some((t, u)) = ray_segment(ox, oy, dx, dy, w1.x as f64, w1.y as f64, w2.x as f64, w2.y as f64) {
1292                if t > t_in + 1e-7 && best.is_none_or(|b| t < b.0) {
1293                    best = Some((t, u, wi));
1294                }
1295            }
1296        }
1297        let t_out = best.map_or(1e9, |b| b.0);
1298        let ror = scene.ror.get(si).copied().unwrap_or_default();
1299        for (floor, plane) in [(false, &sec.ceiling), (true, &sec.floor)] {
1300            let eq = plane_eq(sec, walls, plane);
1301            let a = eq.z_at(ox, oy);
1302            let b = eq.bx * dx + eq.by * dy;
1303            let den = dz - b;
1304            if den.abs() < 1e-12 || (floor && den < 0.0) || (!floor && den > 0.0) {
1305                continue;
1306            }
1307            let t = (a - oz) / den;
1308            if t < t_in - 1e-6 || t > t_out {
1309                continue;
1310            }
1311            let (hx, hy, hz) = (ox + dx * t, oy + dy * t, oz + dz * t);
1312            let link = if floor { ror.floor } else { ror.ceil };
1313            if let (Some(l), true) = (link, depth > 0) {
1314                return trace_pixel(
1315                    scene,
1316                    l.sector,
1317                    hx + l.dx,
1318                    hy + l.dy,
1319                    hz + l.dz,
1320                    dx,
1321                    dy,
1322                    dz,
1323                    t_base + t,
1324                    depth - 1,
1325                );
1326            }
1327            return (sample_plane(scene, si, floor, hx, hy, t_base + t), t_base + t);
1328        }
1329        let Some((t, u, wi)) = best else {
1330            return (0, f64::INFINITY);
1331        };
1332        let w = &walls[wi];
1333        let hz = oz + dz * t;
1334        let tt = t_base + t;
1335        if w.nextsector < 0 {
1336            let zref = if w.cstat & WALL_ALIGN_BOTTOM != 0 {
1337                sec.floor.z
1338            } else {
1339                sec.ceiling.z
1340            } as f64;
1341            return (
1342                sample_wall(scene, si, w, w.picnum, w.xpanning, w.ypanning, u, hz, zref, tt),
1343                tt,
1344            );
1345        }
1346        let ns = w.nextsector as usize;
1347        let (c, f) = crate::geom::zs_of_slope(sectors, walls, ns, ox + dx * t, oy + dy * t);
1348        if hz < c {
1349            let zref = if w.cstat & WALL_ALIGN_BOTTOM != 0 {
1350                sec.ceiling.z
1351            } else {
1352                sectors[ns].ceiling.z
1353            } as f64;
1354            return (
1355                sample_wall(scene, si, w, w.picnum, w.xpanning, w.ypanning, u, hz, zref, tt),
1356                tt,
1357            );
1358        }
1359        if hz > f {
1360            let src = if w.cstat & WALL_BOTTOM_SWAP != 0 && w.nextwall >= 0 {
1361                &walls[w.nextwall as usize]
1362            } else {
1363                w
1364            };
1365            let zref = if src.cstat & WALL_ALIGN_BOTTOM != 0 {
1366                sec.ceiling.z
1367            } else {
1368                sectors[ns].floor.z
1369            } as f64;
1370            return (
1371                sample_wall(scene, si, w, src.picnum, src.xpanning, src.ypanning, u, hz, zref, tt),
1372                tt,
1373            );
1374        }
1375        s = ns as i32;
1376        t_in = t;
1377    }
1378    (0, f64::INFINITY)
1379}
1380
1381#[allow(clippy::too_many_arguments)]
1382fn draw_sky(
1383    p: &PlaneCtx,
1384    pic: i32,
1385    scene: &Scene,
1386    cam: &Camera,
1387    view: &View,
1388    sky_scale: f64,
1389    dx: f64,
1390    dy: f64,
1391    _x: usize,
1392    r0: usize,
1393    r1: usize,
1394    a: f64,
1395    b: f64,
1396    lut: &[u32],
1397    pix: &mut [u32],
1398    depth: &mut [f32],
1399) {
1400    let bits = scene.sky_bits.clamp(0, 10);
1401    let segs = 1i64 << bits;
1402    // Angle of this ray, 0..1 turn.
1403    let ang = dy.atan2(dx) / std::f64::consts::TAU;
1404    let base = scene.tiles.get(pic);
1405    let tw = base.width.max(1) as f64;
1406    let total = tw * segs as f64 * sky_scale;
1407    let texx = (ang.rem_euclid(1.0) * total).floor() as i64;
1408    let seg = (texx / tw as i64).rem_euclid(segs) as usize;
1409    let off = scene.sky_offsets.get(seg).copied().unwrap_or(0) as i32;
1410    let tile = scene.tiles.get(pic + off);
1411    let shade = p.plane.shade as i32;
1412    let sh = shade_index(shade);
1413    let _ = cam;
1414    if tile.is_empty() {
1415        for y in r0..r1 {
1416            pix[y] = lut[sh];
1417            depth[y] = f32::INFINITY;
1418        }
1419        return;
1420    }
1421    let th = tile.height as f64;
1422    let col = tile.column((texx.rem_euclid(tile.width as i64)) as usize);
1423    // Sky is a cylinder at infinity: one texel per original screen line, horizon near
1424    // the lower part of the sky tile.
1425    let px_per_texel = view.h as f64 / 200.0 * view.fly / (view.h as f64 * 0.8);
1426    let texel_per_px = 1.0 / px_per_texel;
1427    let k_scale = 16.0 / view.fly;
1428    let lut = &lut[sh..sh + 256];
1429    for y in r0..r1 {
1430        let dy = y as f64 + 0.5 - view.horizon;
1431        let v = dy * texel_per_px + th * 0.5;
1432        let tv = (v.floor() as i64).clamp(0, th as i64 - 1) as usize;
1433        pix[y] = lut[col[tv] as usize];
1434        let t = if b == 0.0 {
1435            if view.row_k[y].abs() > 1e-12 {
1436                (a - cam.z) * view.row_inv_k[y]
1437            } else {
1438                -1.0
1439            }
1440        } else {
1441            let den = dy * k_scale - b;
1442            if den.abs() > 1e-12 {
1443                (a - cam.z) / den
1444            } else {
1445                -1.0
1446            }
1447        };
1448        depth[y] = if t > 0.0 { t as f32 } else { f32::INFINITY };
1449    }
1450}
1451
1452#[allow(clippy::too_many_arguments)]
1453fn draw_wall_span(
1454    wall: &Wall,
1455    picnum: i16,
1456    xpan: u8,
1457    ypan: u8,
1458    s: f64,
1459    t: f64,
1460    zref: f64,
1461    y0: f64,
1462    y1: f64,
1463    scene: &Scene,
1464    cam: &Camera,
1465    view: &View,
1466    vis: f64,
1467    pix: &mut [u32],
1468    depth: &mut [f32],
1469) {
1470    let h = view.h as f64;
1471    let r0 = y0.max(0.0).ceil() as usize;
1472    let r1 = (y1.min(h).ceil() as isize).max(0) as usize;
1473    if r0 >= r1 {
1474        return;
1475    }
1476    let pic = scene.tiles.animate(picnum as i32, scene.clock);
1477    let tile = scene.tiles.get(pic);
1478    let lut = scene.luts.get(wall.pal);
1479    let sh = shade_index(wall.shade as i32 + Renderer::vis_shade(vis, t));
1480    if tile.is_empty() {
1481        for y in r0..r1 {
1482            pix[y] = lut[sh];
1483            depth[y] = t as f32;
1484        }
1485        return;
1486    }
1487    let tw = tile.width as i64;
1488    let th = tile.height as i64;
1489    let mut tx = ((s * wall.xrepeat as f64 * 8.0).floor() as i64 + xpan as i64).rem_euclid(tw);
1490    if wall.cstat & WALL_XFLIP != 0 {
1491        tx = tw - 1 - tx;
1492    }
1493    let col = tile.column(tx as usize);
1494    let yrep = wall.yrepeat as f64 / 1024.0;
1495    let pan = ypan as f64 * th as f64 / 256.0;
1496    let dz_per_row = 16.0 * t / view.fly;
1497    let yflip = wall.cstat & WALL_YFLIP != 0;
1498    let tf = t as f32;
1499    // Texture row stepped in 32.32 fixed point: one add per pixel.
1500    const ONE: f64 = 4294967296.0;
1501    let z0 = cam.z + (r0 as f64 + 0.5 - view.horizon) * dz_per_row;
1502    let mut vf = (((z0 - zref) * yrep + pan) * ONE) as i64;
1503    let step = (dz_per_row * yrep * ONE) as i64;
1504    let lut = &lut[sh..sh + 256];
1505    for y in r0..r1 {
1506        let mut v = vf >> 32;
1507        if yflip {
1508            v = -v - 1;
1509        }
1510        let c = col[wrap(v, th) as usize];
1511        pix[y] = lut[c as usize];
1512        depth[y] = tf;
1513        vf += step;
1514    }
1515}
1516
1517fn draw_masked(x: usize, m: &MaskSeg, scene: &Scene, cam: &Camera, view: &View, pix: &mut [u32], depth: &[f32]) {
1518    let _ = x;
1519    let wall = &scene.walls[m.wall as usize];
1520    let sec = &scene.sectors[m.sect as usize];
1521    let nsec = &scene.sectors[m.next as usize];
1522    let pic = scene.tiles.animate(wall.overpicnum as i32, scene.clock);
1523    let tile = scene.tiles.get(pic);
1524    if tile.is_empty() {
1525        return;
1526    }
1527    let h = view.h as f64;
1528    let r0 = (m.ytop as f64).max(0.0).ceil() as usize;
1529    let r1 = ((m.ybot as f64).min(h).ceil() as isize).max(0) as usize;
1530    let t = m.t as f64;
1531    let vis = sector_vis(scene, m.sect as i32);
1532    let lut = scene.luts.get(wall.pal);
1533    let sh = shade_index(wall.shade as i32 + Renderer::vis_shade(vis, t));
1534    let tw = tile.width as i64;
1535    let th = tile.height as i64;
1536    let mut tx = ((m.s as f64 * wall.xrepeat as f64 * 8.0).floor() as i64 + wall.xpanning as i64).rem_euclid(tw);
1537    if wall.cstat & WALL_XFLIP != 0 {
1538        tx = tw - 1 - tx;
1539    }
1540    let col = tile.column(tx as usize);
1541    let zref = if wall.cstat & WALL_ALIGN_BOTTOM != 0 {
1542        sec.floor.z.min(nsec.floor.z)
1543    } else {
1544        sec.ceiling.z.max(nsec.ceiling.z)
1545    } as f64;
1546    let yrep = wall.yrepeat as f64 / 1024.0;
1547    let pan = wall.ypanning as f64 * th as f64 / 256.0;
1548    let dz_per_row = 16.0 * t / view.fly;
1549    let trans = wall.cstat & WALL_TRANS != 0;
1550    let rev = wall.cstat & WALL_TRANS_REV != 0;
1551    let yflip = wall.cstat & WALL_YFLIP != 0;
1552    let lut = &lut[sh..sh + 256];
1553    // Texture row stepped in 32.32 fixed point, as for solid walls.
1554    const ONE: f64 = 4294967296.0;
1555    let z0 = cam.z + (r0 as f64 + 0.5 - view.horizon) * dz_per_row;
1556    let mut vf = (((z0 - zref) * yrep + pan) * ONE) as i64;
1557    let step = (dz_per_row * yrep * ONE) as i64;
1558    for y in r0..r1 {
1559        if m.t < depth[y] {
1560            let mut v = vf >> 32;
1561            if yflip {
1562                v = -v - 1;
1563            }
1564            let c = col[wrap(v, th) as usize];
1565            if c != TRANSPARENT {
1566                let rgb = lut[c as usize];
1567                pix[y] = if trans { blend(pix[y], rgb, rev) } else { rgb };
1568            }
1569        }
1570        vf += step;
1571    }
1572}
1573
1574/// Sprite world extents: (half width in xy, height in z, left offset texels).
1575fn sprite_dims(s: &SpriteDraw, tw: f64, th: f64, anm_x: i8, anm_y: i8) -> (f64, f64, f64, f64) {
1576    let xs = s.xrepeat as f64 / 4.0;
1577    let zs = s.yrepeat as f64 * 4.0;
1578    let xoff = anm_x as f64 + s.xoffset as f64;
1579    let yoff = anm_y as f64 + s.yoffset as f64;
1580    let height = th * zs;
1581    let mut zbot = s.z;
1582    if s.cstat & SPR_CENTER != 0 {
1583        zbot += height * 0.5;
1584    }
1585    zbot -= yoff * zs;
1586    // left edge offset in xy units relative to the sprite origin
1587    let left = -(tw * 0.5 + xoff) * xs;
1588    (left, tw * xs, zbot - height, zbot)
1589}
1590
1591fn project_voxel(
1592    idx: usize,
1593    s: &SpriteDraw,
1594    id: u32,
1595    v: &crate::voxel::Voxel,
1596    cam: &Camera,
1597    view: &View,
1598) -> Option<SprProj> {
1599    let a = ang_to_rad(s.ang);
1600    // KVX x runs along the sprite's facing, y across it (the flat tile's horizontal axis).
1601    let w = (a.cos(), a.sin());
1602    let f = (-a.sin(), a.cos());
1603    // One voxel is one sprite texel at the same repeat, and the model stands on the sprite's
1604    // z even when the sprite is flagged as centred. Both fitted to DOSBox captures of voxel
1605    // crates at the E4M9 and E2M4 starts (22x14 px and 13x8 px in the original; a quarter
1606    // texel per voxel drew them 6 px wide, half sunk into the floor).
1607    let unit = s.xrepeat as f64 / 4.0;
1608    let zunit = s.yrepeat as f64 * 4.0;
1609    if unit <= 0.0 || zunit <= 0.0 {
1610        return None;
1611    }
1612    let height = v.zs as f64 * zunit;
1613    let zbot = s.z;
1614    let ztop = zbot - height;
1615    // Project the model's bounding box.
1616    let half_w = view.w as f64 * 0.5;
1617    let (mut x0, mut x1, mut y0, mut y1) = (f64::INFINITY, f64::NEG_INFINITY, f64::INFINITY, f64::NEG_INFINITY);
1618    let mut behind = false;
1619    let mut depth = f64::INFINITY;
1620    for cx in [0.0, v.xs as f64] {
1621        for cy in [0.0, v.ys as f64] {
1622            let (mx, my) = ((cx - v.pivot.0) * unit, (cy - v.pivot.1) * unit);
1623            let wx = s.x + w.0 * mx + f.0 * my;
1624            let wy = s.y + w.1 * mx + f.1 * my;
1625            let (rx, ry) = (wx - cam.x, wy - cam.y);
1626            let fw = rx * view.cos + ry * view.sin;
1627            let sd = -rx * view.sin + ry * view.cos;
1628            if fw < 1.0 {
1629                behind = true;
1630                continue;
1631            }
1632            depth = depth.min(fw);
1633            let sx = half_w + sd / fw * view.fl;
1634            x0 = x0.min(sx);
1635            x1 = x1.max(sx);
1636            for z in [ztop, zbot] {
1637                let sy = view.proj_y(z, cam.z, fw);
1638                y0 = y0.min(sy);
1639                y1 = y1.max(sy);
1640            }
1641        }
1642    }
1643    // Entirely behind the camera: nothing to draw (this used to cover the whole screen and
1644    // cast a ray for every pixel).
1645    if !x0.is_finite() {
1646        return None;
1647    }
1648    if behind {
1649        // Straddles the camera plane: can reach any part of the screen.
1650        x0 = 0.0;
1651        x1 = view.w as f64;
1652        y0 = 0.0;
1653        y1 = view.h as f64;
1654        depth = 1.0;
1655    }
1656    Some(SprProj {
1657        idx,
1658        depth: (s.x - cam.x).hypot(s.y - cam.y).max(depth.min(1e9)) as f32,
1659        kind: SprKind::Voxel {
1660            id,
1661            sx0: x0 as f32,
1662            sx1: x1 as f32,
1663            y0: y0 as f32,
1664            y1: y1 as f32,
1665            tmin: depth.min(1e9) as f32,
1666            w,
1667            f,
1668            unit,
1669            zunit,
1670        },
1671        ztop,
1672        zbot,
1673        pic: s.picnum,
1674    })
1675}
1676
1677fn project_sprite(idx: usize, s: &SpriteDraw, scene: &Scene, cam: &Camera, view: &View) -> Option<SprProj> {
1678    if let Some(id) = s.voxel {
1679        if let Some(Some(v)) = scene.voxels.get(id as usize) {
1680            return project_voxel(idx, s, id, v, cam, view);
1681        }
1682    }
1683    let pic = scene.tiles.animate(s.picnum, scene.clock);
1684    let tile = scene.tiles.get(pic);
1685    if tile.is_empty() || s.xrepeat == 0 || s.yrepeat == 0 {
1686        return None;
1687    }
1688    let tw = tile.width as f64;
1689    let th = tile.height as f64;
1690    let (left, width, ztop, zbot) = sprite_dims(s, tw, th, tile.anm.xoffset, tile.anm.yoffset);
1691    let rx = s.x - cam.x;
1692    let ry = s.y - cam.y;
1693    let fwd = rx * view.cos + ry * view.sin;
1694    let side = -rx * view.sin + ry * view.cos;
1695    let half_w = view.w as f64 * 0.5;
1696    match s.cstat & SPR_ALIGN_MASK {
1697        SPR_WALL => {
1698            let a = ang_to_rad(s.ang);
1699            // Wall sprites extend perpendicular to their facing angle.
1700            let (px, py) = (a.sin(), -a.cos());
1701            let ax = s.x + px * left;
1702            let ay = s.y + py * left;
1703            let bx = ax + px * width;
1704            let by = ay + py * width;
1705            if s.cstat & SPR_ONESIDED != 0 {
1706                // Visible only from the front side (facing direction).
1707                let nx = a.cos();
1708                let ny = a.sin();
1709                if (cam.x - s.x) * nx + (cam.y - s.y) * ny < 0.0 {
1710                    return None;
1711                }
1712            }
1713            let pa = |x: f64, y: f64| -> Option<f64> {
1714                let rx = x - cam.x;
1715                let ry = y - cam.y;
1716                let f = rx * view.cos + ry * view.sin;
1717                let sd = -rx * view.sin + ry * view.cos;
1718                (f > 0.5).then(|| half_w + sd / f * view.fl)
1719            };
1720            let (sx0, sx1) = match (pa(ax, ay), pa(bx, by)) {
1721                (Some(p), Some(q)) => (p.min(q), p.max(q)),
1722                (Some(p), None) | (None, Some(p)) => {
1723                    let _ = p;
1724                    (0.0, view.w as f64)
1725                }
1726                (None, None) => return None,
1727            };
1728            Some(SprProj {
1729                idx,
1730                depth: fwd.max(1.0) as f32,
1731                kind: SprKind::Wall {
1732                    ax,
1733                    ay,
1734                    bx,
1735                    by,
1736                    sx0: sx0 as f32,
1737                    sx1: sx1 as f32,
1738                },
1739                ztop,
1740                zbot,
1741                pic,
1742            })
1743        }
1744        SPR_FLOOR => {
1745            let a = ang_to_rad(s.ang);
1746            let hw = width * 0.5;
1747            let hh = th * s.yrepeat as f64 / 4.0 * 0.5;
1748            // Bounding columns from the projected corners.
1749            let (c, sn) = (a.cos(), a.sin());
1750            let mut minx = f64::INFINITY;
1751            let mut maxx = f64::NEG_INFINITY;
1752            let (mut miny, mut maxy) = (f64::INFINITY, f64::NEG_INFINITY);
1753            let dz = s.z - cam.z;
1754            let mut any_behind = false;
1755            for (u, v) in [(-hw, -hh), (hw, -hh), (hw, hh), (-hw, hh)] {
1756                let wx = s.x + u * c - v * sn;
1757                let wy = s.y + u * sn + v * c;
1758                let rx = wx - cam.x;
1759                let ry = wy - cam.y;
1760                let f = rx * view.cos + ry * view.sin;
1761                let sd = -rx * view.sin + ry * view.cos;
1762                if f <= 1.0 {
1763                    any_behind = true;
1764                    continue;
1765                }
1766                let sx = half_w + sd / f * view.fl;
1767                minx = minx.min(sx);
1768                maxx = maxx.max(sx);
1769                let sy = view.horizon + dz / 16.0 / f * view.fly;
1770                miny = miny.min(sy);
1771                maxy = maxy.max(sy);
1772            }
1773            if any_behind {
1774                minx = 0.0;
1775                maxx = view.w as f64;
1776                // Part of it is behind the camera: it reaches the screen edge on its side.
1777                if dz > 0.0 {
1778                    maxy = view.h as f64;
1779                    miny = miny.min(view.h as f64);
1780                } else {
1781                    miny = 0.0;
1782                    maxy = maxy.max(0.0);
1783                }
1784            }
1785            if !minx.is_finite() {
1786                return None;
1787            }
1788            Some(SprProj {
1789                idx,
1790                depth: fwd.max(1.0) as f32,
1791                kind: SprKind::Floor {
1792                    sx0: minx as f32,
1793                    sx1: maxx as f32,
1794                    ry0: (miny - 1.0) as f32,
1795                    ry1: (maxy + 1.0) as f32,
1796                    cos: c,
1797                    sin: sn,
1798                    hw,
1799                    hh,
1800                },
1801                ztop: s.z,
1802                zbot: s.z,
1803                pic,
1804            })
1805        }
1806        _ => {
1807            if fwd < 4.0 {
1808                return None;
1809            }
1810            let sx_center = half_w + side / fwd * view.fl;
1811            let scale = view.fl / fwd;
1812            let sx0 = sx_center + left * scale;
1813            let sx1 = sx0 + width * scale;
1814            Some(SprProj {
1815                idx,
1816                depth: fwd as f32,
1817                kind: SprKind::Face {
1818                    sx0: sx0 as f32,
1819                    sx1: sx1 as f32,
1820                    depth: fwd as f32,
1821                },
1822                ztop,
1823                zbot,
1824                pic,
1825            })
1826        }
1827    }
1828}
1829
1830#[allow(clippy::too_many_arguments)]
1831fn draw_sprite_column(
1832    x: usize,
1833    sp: &SprProj,
1834    scene: &Scene,
1835    cam: &Camera,
1836    view: &View,
1837    pix: &mut [u32],
1838    depth: &[f32],
1839    mask: &[u32],
1840) {
1841    let s = &scene.sprites[sp.idx];
1842    // Portal sprites only appear where their portal is visible.
1843    let portal = s.portal;
1844    let shown = |y: usize| portal == 0 || mask[y] == portal;
1845    let tile = scene.tiles.get(sp.pic);
1846    let tw = tile.width as i64;
1847    let th = tile.height as i64;
1848    let xc = x as f32 + 0.5;
1849    let lut = scene.luts.get(s.pal);
1850    let vis = sector_vis(scene, s.sector);
1851    let trans = s.cstat & SPR_TRANS != 0;
1852    let rev = s.cstat & SPR_TRANS_REV != 0;
1853    let xflip = s.cstat & SPR_XFLIP != 0;
1854    let yflip = s.cstat & SPR_YFLIP != 0;
1855    let h = view.h as f64;
1856
1857    let column = |t: f64, u: f64, pix: &mut [u32]| {
1858        // u in [0,1) across the sprite
1859        let mut tx = (u * tw as f64).floor() as i64;
1860        if !(0..tw).contains(&tx) {
1861            return;
1862        }
1863        if xflip {
1864            tx = tw - 1 - tx;
1865        }
1866        let col = tile.column(tx as usize);
1867        let y0 = view.proj_y(sp.ztop, cam.z, t);
1868        let y1 = view.proj_y(sp.zbot, cam.z, t);
1869        let r0 = y0.max(0.0).ceil() as usize;
1870        let r1 = (y1.min(h).ceil() as isize).max(0) as usize;
1871        if r0 >= r1 {
1872            return;
1873        }
1874        let sh = shade_index(s.shade + Renderer::vis_shade(vis, t));
1875        let inv = th as f64 / (y1 - y0);
1876        let tf = t as f32;
1877        let lut = &lut[sh..sh + 256];
1878        // Texture row stepped in 32.32 fixed point, clamped to the tile.
1879        const ONE: f64 = 4294967296.0;
1880        let mut vf = (((r0 as f64 + 0.5 - y0) * inv) * ONE) as i64;
1881        let step = (inv * ONE) as i64;
1882        let last = th - 1;
1883        let row = |vf: i64| {
1884            let ty = (vf >> 32).clamp(0, last);
1885            (if yflip { last - ty } else { ty }) as usize
1886        };
1887        if portal == 0 && !trans {
1888            // Common case: opaque sprite, no portal mask.
1889            for y in r0..r1 {
1890                if tf < depth[y] {
1891                    let c = col[row(vf)];
1892                    if c != TRANSPARENT {
1893                        pix[y] = lut[c as usize];
1894                    }
1895                }
1896                vf += step;
1897            }
1898            return;
1899        }
1900        for y in r0..r1 {
1901            if tf < depth[y] && shown(y) {
1902                let c = col[row(vf)];
1903                if c != TRANSPARENT {
1904                    let rgb = lut[c as usize];
1905                    pix[y] = if trans { blend(pix[y], rgb, rev) } else { rgb };
1906                }
1907            }
1908            vf += step;
1909        }
1910    };
1911
1912    match sp.kind {
1913        SprKind::Face { sx0, sx1, depth: d } => {
1914            if xc < sx0 || xc >= sx1 {
1915                return;
1916            }
1917            let u = ((xc - sx0) / (sx1 - sx0)) as f64;
1918            column(d as f64, u, pix);
1919        }
1920        SprKind::Wall {
1921            ax,
1922            ay,
1923            bx,
1924            by,
1925            sx0,
1926            sx1,
1927        } => {
1928            if xc < sx0 - 1.0 || xc > sx1 + 1.0 {
1929                return;
1930            }
1931            let (dx, dy) = view.dir(x);
1932            if let Some((t, u)) = ray_segment(cam.x, cam.y, dx, dy, ax, ay, bx, by) {
1933                if t > 0.5 {
1934                    column(t, u.min(0.999_999), pix);
1935                }
1936            }
1937        }
1938        SprKind::Voxel {
1939            id,
1940            sx0,
1941            sx1,
1942            y0,
1943            y1,
1944            tmin,
1945            w,
1946            f,
1947            unit,
1948            zunit,
1949        } => {
1950            if xc < sx0 - 1.0 || xc > sx1 + 1.0 {
1951                return;
1952            }
1953            let Some(Some(v)) = scene.voxels.get(id as usize) else {
1954                return;
1955            };
1956            let (dx, dy) = view.dir(x);
1957            // Ray origin and direction in model space.
1958            let (lx, ly) = (cam.x - s.x, cam.y - s.y);
1959            let ox = (lx * w.0 + ly * w.1) / unit + v.pivot.0;
1960            let oy = (lx * f.0 + ly * f.1) / unit + v.pivot.1;
1961            let oz = (cam.z - sp.ztop) / zunit;
1962            let ddx = (dx * w.0 + dy * w.1) / unit;
1963            let ddy = (dx * f.0 + dy * f.1) / unit;
1964            let r0 = (y0 as f64).max(0.0).floor() as usize;
1965            let r1 = ((y1 as f64).ceil() as isize).clamp(0, view.h as isize) as usize;
1966            for y in r0..r1 {
1967                if depth[y] <= tmin || !shown(y) {
1968                    continue; // hidden behind something nearer than the whole model
1969                }
1970                let dzz = (y as f64 + 0.5 - view.horizon) / view.fly * 16.0;
1971                let Some((t, c)) = v.cast([ox, oy, oz], [ddx, ddy, dzz / zunit]) else {
1972                    continue;
1973                };
1974                if t <= 0.0 || t as f32 >= depth[y] || !shown(y) {
1975                    continue;
1976                }
1977                let sh = shade_index(s.shade + Renderer::vis_shade(vis, t));
1978                let rgb = lut[sh + c as usize];
1979                pix[y] = if trans { blend(pix[y], rgb, rev) } else { rgb };
1980            }
1981        }
1982        SprKind::Floor {
1983            sx0,
1984            sx1,
1985            ry0,
1986            ry1,
1987            cos,
1988            sin,
1989            hw,
1990            hh,
1991        } => {
1992            if xc < sx0 - 1.0 || xc > sx1 + 1.0 {
1993                return;
1994            }
1995            let (dx, dy) = view.dir(x);
1996            let dz = sp.zbot - cam.z;
1997            if dz.abs() < 1.0 {
1998                return;
1999            }
2000            let sh_base = s.shade;
2001            let (r0, r1) = if dz > 0.0 {
2002                (view.horizon.max(0.0).ceil() as usize, view.h)
2003            } else {
2004                (0, (view.horizon.min(h).ceil() as isize).max(0) as usize)
2005            };
2006            // Only the rows its corners project to (a decal far away is a thin strip).
2007            let r0 = r0.max(ry0.max(0.0) as usize);
2008            let r1 = r1.min((ry1.max(0.0) as usize).min(view.h));
2009            for y in r0..r1 {
2010                let k = (y as f64 + 0.5 - view.horizon) / view.fly * 16.0;
2011                if k.abs() < 1e-12 {
2012                    continue;
2013                }
2014                let t = dz / k;
2015                if t <= 0.0 || t as f32 >= depth[y] || !shown(y) {
2016                    continue;
2017                }
2018                let wx = cam.x + dx * t - s.x;
2019                let wy = cam.y + dy * t - s.y;
2020                let lu = wx * cos + wy * sin;
2021                let lv = -wx * sin + wy * cos;
2022                if lu.abs() >= hw || lv.abs() >= hh {
2023                    continue;
2024                }
2025                let mut tx = (((lu + hw) / (2.0 * hw)) * tw as f64) as i64;
2026                let mut ty = (((lv + hh) / (2.0 * hh)) * th as f64) as i64;
2027                tx = tx.clamp(0, tw - 1);
2028                ty = ty.clamp(0, th - 1);
2029                if xflip {
2030                    tx = tw - 1 - tx;
2031                }
2032                if yflip {
2033                    ty = th - 1 - ty;
2034                }
2035                let c = tile.pixels[(tx * th + ty) as usize];
2036                if c == TRANSPARENT {
2037                    continue;
2038                }
2039                let sh = shade_index(sh_base + Renderer::vis_shade(vis, t));
2040                let rgb = lut[sh + c as usize];
2041                pix[y] = if trans { blend(pix[y], rgb, rev) } else { rgb };
2042            }
2043        }
2044    }
2045}
2046
2047#[cfg(test)]
2048mod tests {
2049    use super::*;
2050    use crate::art::{Tile, TileSet};
2051    use crate::map::{Sector, Wall};
2052
2053    fn room() -> (Vec<Sector>, Vec<Wall>) {
2054        let pts = [(-1024, -1024), (1024, -1024), (1024, 1024), (-1024, 1024)];
2055        let walls: Vec<Wall> = pts
2056            .iter()
2057            .enumerate()
2058            .map(|(i, &(x, y))| Wall {
2059                x,
2060                y,
2061                point2: ((i + 1) % 4) as i16,
2062                nextwall: -1,
2063                nextsector: -1,
2064                picnum: 1,
2065                xrepeat: 8,
2066                yrepeat: 8,
2067                ..Default::default()
2068            })
2069            .collect();
2070        let mut s = Sector {
2071            wallptr: 0,
2072            wallnum: 4,
2073            ..Default::default()
2074        };
2075        s.ceiling.z = -16384;
2076        s.floor.z = 0;
2077        s.ceiling.picnum = 2;
2078        s.floor.picnum = 3;
2079        (vec![s], walls)
2080    }
2081
2082    fn tiles() -> TileSet {
2083        let mut t = TileSet::default();
2084        for (i, c) in [(1usize, 10u8), (2, 20), (3, 30)] {
2085            t.tiles[i] = Tile {
2086                width: 8,
2087                height: 8,
2088                anm: Default::default(),
2089                pixels: vec![c; 64],
2090            };
2091        }
2092        t
2093    }
2094
2095    fn luts() -> ShadeLuts {
2096        // Encode the palette index directly as the colour so tests can inspect it.
2097        let mut t = vec![0u32; 64 * 256];
2098        for s in 0..64 {
2099            for c in 0..256 {
2100                t[s * 256 + c] = c as u32;
2101            }
2102        }
2103        let mut tables = vec![None; 256];
2104        tables[0] = Some(t);
2105        ShadeLuts { tables }
2106    }
2107
2108    #[test]
2109    fn renders_wall_floor_ceiling() {
2110        let (sectors, walls) = room();
2111        let tiles = tiles();
2112        let luts = luts();
2113        let scene = Scene {
2114            sectors: &sectors,
2115            walls: &walls,
2116            sprites: &[],
2117            tiles: &tiles,
2118            luts: &luts,
2119            sky_offsets: &[0],
2120            sky_bits: 0,
2121            visibility: 0,
2122            clock: 0,
2123            voxels: &[],
2124            ror: &[],
2125        };
2126        let cam = Camera {
2127            x: 0.0,
2128            y: 0.0,
2129            z: -8192.0,
2130            ang: 0.0,
2131            horiz: 0.0,
2132            sector: 0,
2133        };
2134        let mut r = Renderer::new(64, 48);
2135        r.render(&scene, &cam);
2136        let at = |x: usize, y: usize| r.frame[y * 64 + x];
2137        assert_eq!(at(32, 0), 20, "ceiling at top");
2138        assert_eq!(at(32, 47), 30, "floor at bottom");
2139        assert_eq!(at(32, 24), 10, "wall in the middle");
2140        // Wall is 1024 units ahead.
2141        assert!((r.depth_at(32, 24) - 1024.0).abs() < 1.0);
2142    }
2143
2144    #[test]
2145    fn sprite_occludes_wall() {
2146        let (sectors, walls) = room();
2147        let mut tiles = tiles();
2148        tiles.tiles[4] = Tile {
2149            width: 16,
2150            height: 16,
2151            anm: Default::default(),
2152            pixels: vec![40; 256],
2153        };
2154        let luts = luts();
2155        let spr = [SpriteDraw {
2156            x: 512.0,
2157            y: 0.0,
2158            z: 0.0,
2159            picnum: 4,
2160            xrepeat: 64,
2161            yrepeat: 64,
2162            sector: 0,
2163            ..Default::default()
2164        }];
2165        let scene = Scene {
2166            sectors: &sectors,
2167            walls: &walls,
2168            sprites: &spr,
2169            tiles: &tiles,
2170            luts: &luts,
2171            sky_offsets: &[0],
2172            sky_bits: 0,
2173            visibility: 0,
2174            clock: 0,
2175            voxels: &[],
2176            ror: &[],
2177        };
2178        let cam = Camera {
2179            x: 0.0,
2180            y: 0.0,
2181            z: -2048.0,
2182            ang: 0.0,
2183            horiz: 0.0,
2184            sector: 0,
2185        };
2186        let mut r = Renderer::new(64, 48);
2187        r.render(&scene, &cam);
2188        assert_eq!(r.frame[30 * 64 + 32], 40);
2189    }
2190}