aboutsummaryrefslogtreecommitdiff
path: root/crates/fparkan-render/src/cockpit_radar.rs
blob: e9043362238157a3ffa76fbeb5fac072be7d2494 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
//! Native cockpit radar projection and screen-pixel marks.

use crate::cockpit_course::CENTER;
use std::f64::consts::FRAC_PI_2;

pub const SWEEP_EDGES: usize = 20;

/// Clock state held by the cockpit radar panel.
#[derive(Default)]
pub struct RadarSweep {
    start_ms: Option<u32>,
}

impl RadarSweep {
    /// Returns the native design radius and whether this paint starts a new sweep.
    /// `radar_period_ms` is the positive period supplied by Control.
    pub fn sample(&mut self, now_ms: u32, radar_period_ms: f32) -> (u32, bool) {
        let duration = f64::from(radar_period_ms * 0.002);
        if let Some(start_ms) = self.start_ms {
            let elapsed = f64::from(now_ms.wrapping_sub(start_ms)) * f64::from(0.001_f32);
            if elapsed <= duration {
                let radius = (60.0 / duration * f64::from(elapsed as f32)).round_ties_even();
                return (radius as u32, false);
            }
        }
        self.start_ms = Some(now_ms);
        (0, true)
    }
}

/// The 20 native line segments, expanded to a one-pixel stroke in screen space.
/// The caller omits the degenerate outline at radius zero.
pub fn sweep_outline(radius: u32, viewport: [f32; 2]) -> [[[f32; 2]; 2]; SWEEP_EDGES] {
    let [sx, sy] = [viewport[0] / 640.0, viewport[1] / 480.0];
    let points: [[f32; 2]; SWEEP_EDGES] = std::array::from_fn(|index| {
        let angle = index as f32 * (std::f32::consts::TAU / SWEEP_EDGES as f32);
        let (sin, cos) = angle.sin_cos();
        let r = radius as f32;
        [(CENTER[0] + r * cos) * sx, (CENTER[1] + r * sin) * sy]
    });
    let normal = |[ax, ay]: [f32; 2], [bx, by]: [f32; 2]| {
        let [dx, dy] = [bx - ax, by - ay];
        let length = dx.hypot(dy);
        [dy / length, -dx / length]
    };
    std::array::from_fn(|i| {
        let point = points[i];
        let [nx, ny] = normal(points[(i + SWEEP_EDGES - 1) % SWEEP_EDGES], point);
        let [mx, my] = normal(point, points[(i + 1) % SWEEP_EDGES]);
        let scale = 0.5 / (1.0 + nx * mx + ny * my);
        let [dx, dy] = [(nx + mx) * scale, (ny + my) * scale];
        [
            [point[0] + dx, point[1] + dy],
            [point[0] - dx, point[1] - dy],
        ]
    })
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum ContactMark {
    Building,
    Unit,
    Cross,
}

/// Project a horizontal world offset into the cockpit radar's screen pixels.
#[must_use]
pub fn contact_pixel(
    [x, y]: [f32; 2],
    [forward_x, forward_y]: [f32; 2],
    range: f32,
    viewport: [f32; 2],
) -> [f32; 2] {
    let [x, y] = [x, y].map(f64::from);
    let bearing = y.atan2(x) - f64::from(forward_y).atan2(f64::from(forward_x)) + FRAC_PI_2;
    let (sin, cos) = bearing.sin_cos();
    let radius = f64::from(x.hypot(y) as f32) * f64::from(range.recip()) * 60.0;
    let [sx, sy] = [viewport[0] / 640.0, viewport[1] / 480.0].map(f64::from);
    [
        ((f64::from(CENTER[0]) + cos * radius) * sx) as f32,
        ((f64::from(CENTER[1]) - sin * radius) * sy) as f32,
    ]
}

/// Emit the filled rectangles that make up a contact and its optional outline.
pub fn mark_rectangles(
    mark: ContactMark,
    [x, y]: [f32; 2],
    [width, height]: [f32; 2],
    selected: bool,
    mut paint: impl FnMut([i32; 4]),
) {
    let design_size = match mark {
        ContactMark::Building => 5.0,
        ContactMark::Unit => 3.0,
        ContactMark::Cross => 4.0,
    };
    let round = |value: f32| value.round_ties_even() as i32;
    let w = round(width / 640.0 * design_size);
    let h = round(height / 480.0 * design_size);
    let [left, top, right, bottom] = if mark == ContactMark::Cross {
        let [cx, cy] = [round(x), round(y)];
        let [dx, dy] = [w / 2, h / 2];
        let bounds = [
            cx.saturating_sub(dx),
            cy.saturating_sub(dy),
            cx.saturating_add(dx),
            cy.saturating_add(dy),
        ];
        paint([bounds[0], cy, bounds[2], cy.saturating_add(1)]);
        paint([cx, bounds[1], cx.saturating_add(1), bounds[3]]);
        bounds
    } else {
        let left = round(x - (w / 2) as f32);
        let top = round(y - (h / 2) as f32);
        let bounds = [left, top, left.saturating_add(w), top.saturating_add(h)];
        paint(bounds);
        bounds
    };
    if selected {
        let [l, t, r, b] = [
            left.saturating_sub(2),
            top.saturating_sub(2),
            right.saturating_add(if mark == ContactMark::Cross { 2 } else { 1 }),
            bottom.saturating_add(if mark == ContactMark::Cross { 2 } else { 1 }),
        ];
        paint([l, t, r, t.saturating_add(1)]);
        paint([l, b.saturating_sub(1), r, b]);
        paint([l, t, l.saturating_add(1), b]);
        paint([r.saturating_sub(1), t, r, b]);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn sweep_restarts_only_after_the_native_strict_boundary() {
        let mut sweep = RadarSweep::default();
        assert_eq!(sweep.sample(0, 750.0), (0, true));
        assert_eq!(sweep.sample(775, 750.0), (31, false));
        assert_eq!(sweep.sample(1500, 750.0), (60, false));
        assert_eq!(sweep.sample(1501, 750.0), (0, true));
        assert_eq!(sweep.sample(1501, 750.0), (0, false));
        assert_eq!(sweep.sample(5100, 750.0), (0, true));
    }

    #[test]
    fn sweep_polygon_matches_native_800_by_600_vertices() {
        let outline = sweep_outline(31, [800.0, 600.0]);
        for (index, native) in [
            (0, [438.75, 495.0]),
            (1, [436.85345, 506.97446]),
            (5, [400.0, 533.75]),
            (13, [377.22327, 463.65067]),
        ] {
            let [outer, inner] = outline[index];
            for axis in 0..2 {
                let center = (outer[axis] + inner[axis]) * 0.5;
                assert!((center - native[axis]).abs() < 0.001);
            }
        }
    }

    #[test]
    fn cockpit_radar_rotates_with_view_and_maps_range_to_sixty_design_pixels() {
        let viewport = [800.0, 600.0];
        assert_eq!(
            contact_pixel([300.0, 0.0], [1.0, 0.0], 300.0, viewport),
            [400.0, 420.0]
        );
        assert_eq!(
            contact_pixel([0.0, -300.0], [1.0, 0.0], 300.0, viewport),
            [475.0, 495.0]
        );
        assert_eq!(
            contact_pixel([300.0, 0.0], [0.0, 1.0], 300.0, viewport),
            [475.0, 495.0]
        );
    }

    #[test]
    fn projected_contact_reproduces_native_800_by_600_draw_coordinates() {
        // Native callbacks produced these bounds for a point 110 units east and 80 north.
        let viewport = [800.0, 600.0];
        let point = contact_pixel([110.0, 80.0], [0.7673624, -0.64121366], 400.0, viewport);
        for (mark, expected) in [
            (ContactMark::Building, vec![[372, 486, 378, 492]]),
            (ContactMark::Unit, vec![[373, 487, 377, 491]]),
            (
                ContactMark::Cross,
                vec![[373, 489, 377, 490], [375, 487, 376, 491]],
            ),
        ] {
            let mut actual = Vec::new();
            mark_rectangles(mark, point, viewport, false, |rect| actual.push(rect));
            assert_eq!(actual, expected);
        }
    }
}