native-gui-core 1.0.0

Core abstraction, widget model, and layout engine for Native GUI
Documentation
//! Software fallback cube shared by the Win32, GTK, and Web
//! `draw_demo_cube` painters.
//!
//! The projection treats larger `z` as farther from the camera
//! (`depth = z + 4`). Faces are returned already painter-sorted far to
//! near so the closest faces, including the top, end up on top.

/// One painter-sorted face of the fallback demo cube.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct DemoCubeFace {
    /// Projected corner positions in canvas pixels, clockwise or
    /// counter-clockwise as stored in the model (screen Y grows down).
    pub points: [[f64; 2]; 4],
    /// Fill colour as `(r, g, b)`.
    pub color: (u8, u8, u8),
}

/// Average transformed `z` of this face (larger is farther).
impl DemoCubeFace {
    /// Identity accessor kept so call sites can name the colour clearly.
    pub fn rgb(self) -> (u8, u8, u8) {
        self.color
    }
}

/// Colour of the +Y (top) face.
pub const DEMO_CUBE_TOP: (u8, u8, u8) = (184, 112, 245);
/// Colour of the -Y (bottom) face.
pub const DEMO_CUBE_BOTTOM: (u8, u8, u8) = (250, 138, 77);

/// Projects the six-face demo cube into a `width` × `height` canvas and
/// returns the faces in far-to-near order for a painter's algorithm.
pub fn project_demo_cube(width: f64, height: f64) -> Vec<DemoCubeFace> {
    let width = width.max(1.0);
    let height = height.max(1.0);

    let vertices = [
        [-1.0, -1.0, -1.0],
        [1.0, -1.0, -1.0],
        [1.0, 1.0, -1.0],
        [-1.0, 1.0, -1.0],
        [-1.0, -1.0, 1.0],
        [1.0, -1.0, 1.0],
        [1.0, 1.0, 1.0],
        [-1.0, 1.0, 1.0],
    ];

    // Cross-platform fixture pose used by the software painters and the
    // Metal comparison shader (yaw 0.65, pitch -0.45).
    let yaw = 0.65_f64;
    let pitch = -0.45_f64;
    let (sy, cy) = yaw.sin_cos();
    let (sx, cx) = pitch.sin_cos();

    let transformed: Vec<[f64; 3]> = vertices
        .iter()
        .map(|v| {
            let x1 = v[0] * cy + v[2] * sy;
            let z1 = -v[0] * sy + v[2] * cy;
            let y2 = v[1] * cx - z1 * sx;
            let z2 = v[1] * sx + z1 * cx;
            [x1, y2, z2]
        })
        .collect();

    let projected: Vec<[f64; 2]> = transformed
        .iter()
        .map(|v| {
            // Larger z is farther: scale shrinks as z grows.
            let depth = v[2] + 4.0;
            let scale = (width.min(height) * 0.28) / depth;
            [width * 0.5 + v[0] * scale, height * 0.52 - v[1] * scale]
        })
        .collect();

    let mut faces = vec![
        ([4usize, 5, 6, 7], (235u8, 72u8, 87u8)),
        ([0usize, 1, 2, 3], (64u8, 184u8, 245u8)),
        ([0usize, 3, 7, 4], (77u8, 217u8, 133u8)),
        ([1usize, 2, 6, 5], (250u8, 181u8, 64u8)),
        ([3usize, 2, 6, 7], DEMO_CUBE_TOP),
        ([0usize, 1, 5, 4], DEMO_CUBE_BOTTOM),
    ];

    // Far (larger z) first, near last, so the closest faces paint on top.
    // Sorting the other way drew the floor and far walls over the exterior
    // and made the cube read as an open box.
    faces.sort_by(|(a, _), (b, _)| {
        let az = a.iter().map(|index| transformed[*index][2]).sum::<f64>() / 4.0;
        let bz = b.iter().map(|index| transformed[*index][2]).sum::<f64>() / 4.0;
        bz.partial_cmp(&az).unwrap_or(std::cmp::Ordering::Equal)
    });

    faces
        .into_iter()
        .map(|(face, color)| DemoCubeFace {
            points: [
                projected[face[0]],
                projected[face[1]],
                projected[face[2]],
                projected[face[3]],
            ],
            color,
        })
        .collect()
}

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

    fn edge_length(a: [f64; 2], b: [f64; 2]) -> f64 {
        let dx = a[0] - b[0];
        let dy = a[1] - b[1];
        (dx * dx + dy * dy).sqrt()
    }

    #[test]
    fn demo_cube_shows_the_top_face_and_hides_the_floor() {
        let faces = project_demo_cube(400.0, 400.0);
        assert_eq!(faces.len(), 6);
        // The three faces drawn last are the visible exterior of a convex cube.
        let visible = &faces[faces.len() - 3..];
        assert!(
            visible.iter().any(|face| face.color == DEMO_CUBE_TOP),
            "camera is above the cube, so the top face must be visible: {visible:?}"
        );
        assert!(
            visible.iter().all(|face| face.color != DEMO_CUBE_BOTTOM),
            "the floor must stay behind the top face: {visible:?}"
        );
    }

    #[test]
    fn demo_cube_near_corner_edge_is_the_longest() {
        let faces = project_demo_cube(400.0, 400.0);
        let visible = &faces[faces.len() - 3..];

        // The near corner is the unique vertex shared by all three visible faces.
        fn key(p: [f64; 2]) -> (i64, i64) {
            ((p[0] * 100.0).round() as i64, (p[1] * 100.0).round() as i64)
        }
        let mut counts = std::collections::HashMap::new();
        for face in visible {
            for point in face.points {
                *counts.entry(key(point)).or_insert(0) += 1;
            }
        }
        let near = counts
            .iter()
            .find(|(_, count)| **count == 3)
            .map(|(point, _)| *point)
            .expect("three visible faces of a cube meet at one near corner");
        let mut near_edges = Vec::new();
        let mut all_edges = Vec::new();
        for face in visible {
            for i in 0..4 {
                let a = face.points[i];
                let b = face.points[(i + 1) % 4];
                let len = edge_length(a, b);
                all_edges.push(len);
                if key(a) == near || key(b) == near {
                    near_edges.push(len);
                }
            }
        }
        let longest_near = near_edges.iter().copied().fold(0.0_f64, f64::max);
        let longest_all = all_edges.iter().copied().fold(0.0_f64, f64::max);
        assert!(
            (longest_near - longest_all).abs() < 1e-6,
            "the near corner's longest edge ({longest_near}) must be the longest visible edge ({longest_all})"
        );
        // And that edge must be longer than the far edges of the same corner fan.
        let shortest_near = near_edges.iter().copied().fold(f64::INFINITY, f64::min);
        assert!(
            longest_near > shortest_near + 1.0,
            "perspective should make the near edge longer than the far ones ({longest_near} vs {shortest_near})"
        );
    }
}