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
use crate::navmesh::HammerUnit;
pub use crate::navmesh::{
    ApproachArea, Connections, EncounterPath, LadderConnections, LadderDirection, LightIntensity,
    NavDirection, NavHidingSpot, NavQuad, Vector3, VisibleArea,
};
use crate::parser::read_quads;
pub use crate::parser::{read_areas, NavArea, ParseError};
use aabb_quadtree::{ItemId, QuadTree};
use bitbuffer::{BitReadStream, LittleEndian};
use euclid::{TypedPoint2D, TypedRect, TypedSize2D};

mod navmesh;
mod parser;

type Rect = TypedRect<f32, HammerUnit>;

/// A tree of all navigation areas
pub struct NavQuadTree(QuadTree<NavQuad, HammerUnit, [(ItemId, Rect); 4]>);

/// Parse all navigation quads from a nav file
///
/// ## Examples
///
/// ```no_run
/// use sourcenav::get_quad_tree;
///
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// let file = std::fs::read("path/to/navfile.nav")?;
/// let tree = get_quad_tree(file)?;
/// # Ok(())
/// # }
/// ```
pub fn get_quad_tree(
    data: impl Into<BitReadStream<LittleEndian>>,
) -> Result<NavQuadTree, ParseError> {
    let areas = read_quads(data.into())?;

    let (min_x, min_y, max_x, max_y) = areas.iter().fold(
        (f32::MAX, f32::MAX, f32::MIN, f32::MIN),
        |(min_x, min_y, max_x, max_y), area| {
            (
                f32::min(min_x, area.north_west.0),
                f32::min(min_y, area.north_west.1),
                f32::max(max_x, area.south_east.0),
                f32::max(max_y, area.south_east.1),
            )
        },
    );

    let mut tree = QuadTree::default(
        Rect::new(
            TypedPoint2D::new(min_x - 1.0, min_y - 1.0),
            TypedSize2D::new(max_x - min_x + 2.0, max_y - min_y + 2.0),
        ),
        areas.len(),
    );

    for area in areas {
        tree.insert(area);
    }

    Ok(NavQuadTree(tree))
}

impl NavQuadTree {
    /// Find the navigation areas at a x/y cooordinate
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// use sourcenav::get_quad_tree;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let file = std::fs::read("path/to/navfile.nav")?;
    /// let tree = get_quad_tree(file)?;
    /// let areas = tree.query(150.0, -312.0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn query(&self, x: f32, y: f32) -> impl Iterator<Item = &NavQuad> {
        let query_box = Rect::new(TypedPoint2D::new(x, y), TypedSize2D::new(1.0, 1.0));

        self.0.query(query_box).into_iter().map(|(area, ..)| area)
    }

    /// Find the z-height of a specfic x/y cooordinate
    ///
    /// Note that multiple heights might exist for a given x/y coooridnate
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// use sourcenav::get_quad_tree;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let file = std::fs::read("path/to/navfile.nav")?;
    /// let tree = get_quad_tree(file)?;
    /// let heights = tree.find_z_height(150.0, -312.0);
    /// # Ok(())
    /// # }
    /// ```
    pub fn find_z_height<'a>(&'a self, x: f32, y: f32) -> impl Iterator<Item = f32> + 'a {
        self.query(x, y).map(move |area| area.get_z_height(x, y))
    }

    /// Get the z height at a point
    ///
    /// A z-guess should be provided to resolve cases where multiple z values are possible
    pub fn find_best_height(&self, x: f32, y: f32, z_guess: f32) -> f32 {
        let found_heights = self.find_z_height(x, y);
        let best_z = f32::MIN;

        found_heights.fold(best_z, |best_z, found_z| {
            if (found_z - z_guess).abs() < (best_z - z_guess).abs() {
                found_z
            } else {
                best_z
            }
        })
    }

    /// Get all navigation areas from the nav file
    ///
    /// ## Examples
    ///
    /// ```no_run
    /// use sourcenav::get_quad_tree;
    ///
    /// # fn main() -> Result<(), Box<dyn std::error::Error>> {
    /// let file = std::fs::read("path/to/navfile.nav")?;
    /// let tree = get_quad_tree(file)?;
    /// for quad in tree.quads() {
    ///     println!("area: {:?}", quad)
    /// }
    /// # Ok(())
    /// # }
    /// ```
    pub fn quads(&self) -> impl Iterator<Item = &NavQuad> {
        self.0.iter().map(|(_, (area, _))| area)
    }
}

#[test]
fn test_tree() {
    let file = std::fs::read("data/pl_badwater.nav").unwrap();
    let tree = get_quad_tree(file).unwrap();

    // single flat plane
    let point1 = (1600.0, -1300.0);

    assert_eq!(
        vec![375.21506],
        tree.find_z_height(point1.0, point1.1).collect::<Vec<f32>>()
    );

    // 2 z levels
    let point2 = (360.0, -1200.0);

    assert_eq!(
        vec![290.2907, 108.144775],
        tree.find_z_height(point2.0, point2.1).collect::<Vec<f32>>()
    );

    // top of slope
    let point3 = (320.0, -1030.0);

    assert_eq!(
        vec![220.83125],
        tree.find_z_height(point3.0, point3.1).collect::<Vec<f32>>()
    );

    // bottom of same slope
    let point4 = (205.0, -1030.0);

    assert_eq!(
        vec![147.23126],
        tree.find_z_height(point4.0, point4.1).collect::<Vec<f32>>()
    );
}

#[cfg(doctest)]
doc_comment::doctest!("../README.md");