delatin/
lib.rs

1/*!
2Simple and fast [**TIN**](https://en.wikipedia.org/wiki/Triangulated_irregular_network) generation library.
3Uses [Delaunay triangulation](https://en.wikipedia.org/wiki/Delaunay_triangulation).
4
5# Example
6
7```rust
8use delatin::{triangulate, Error};
9
10let heights = vec![100.1, 123.4, 111.5, 121.4];
11let width = 2;
12let height = 2;
13let max_error = Error(1.0);
14// points `Vec<(usize, usize)>`: A vector containing all the vertices of the triangulated mesh. Each point corresponds to heights vector index.
15// triangles `Vec<(usize, usize, usize)>`: A vector containing all the triangles of the mesh, each defined by indices into the `points`.
16let (points, triangles) = triangulate(&heights, width, height, max_error)?;
17```
18*/
19
20use std::fmt;
21
22pub use error::TriangulationError;
23use triangulation::Triangulation;
24
25mod error;
26mod priority_queue;
27mod triangulation;
28mod utils;
29
30// TODO: consider NewTypes
31type Point = (usize, usize);
32type Triangle = (usize, usize, usize);
33type Height = f64;
34
35/// Error for the triangulation process.
36#[derive(Debug, Clone, Copy, PartialOrd, PartialEq, Default)]
37pub struct Error(pub f64);
38
39impl fmt::Display for Error {
40    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
41        write!(f, "{}", self.0)
42    }
43}
44
45/// Runs the triangulation process until the maximum error is below the specified threshold.
46///
47/// # Arguments
48///
49/// * `height_data` - Height values of the grid.
50/// * `dimesions` - Tuple width and height of the grid.
51/// * `max_error` - The maximum allowable error for the triangulation process.
52///
53/// # Returns
54///
55/// Tuple containing:
56/// - points `Vec<(usize, usize)>`: A vector containing all the vertices of the triangulated mesh.
57/// - triangles `Vec<(usize, usize, usize)>`: A vector containing all the triangles of the mesh, each defined by indices into the `points`.
58///
59/// # Errors
60///
61/// - `InvalidDataLengthError` - If the length of the height data does not match the width and height of the grid.
62/// - `MaxErrorRetrievalError` - If the maximum error is not found in the priority queue.
63/// - `EmptyQueueError` - If the priority queue is empty during triangulation.
64///
65pub fn triangulate(
66    height_data: &[f64],
67    dimesions: (usize, usize),
68    max_error: Error,
69) -> Result<(Vec<Point>, Vec<Triangle>), TriangulationError> {
70    let width = dimesions.0;
71    let height = dimesions.1;
72    (height_data.len() == width * height)
73        .then_some(())
74        .ok_or(TriangulationError::InvalidDataLengthError)?;
75
76    let mut delatin = Triangulation::new(height_data, width, height);
77
78    delatin.run(max_error)
79}