aboutsummaryrefslogtreecommitdiff
path: root/stockton-levels/src/q3/models.rs
blob: a3de54a0cc1711651e0a40afccdc64d3be0c48e6 (plain)
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
use super::Q3BspFile;
use crate::coords::CoordSystem;
use crate::helpers::{slice_to_u32, slice_to_vec3};
use crate::traits::models::*;
use crate::types::{ParseError, Result};

const MODEL_SIZE: usize = (4 * 3 * 2) + (4 * 4);

pub fn from_data(data: &[u8], n_faces: u32, n_brushes: u32) -> Result<Box<[Model]>> {
    if data.len() % MODEL_SIZE != 0 {
        return Err(ParseError::Invalid);
    }
    let n_models = data.len() / MODEL_SIZE;

    let mut models = Vec::with_capacity(n_models);
    for n in 0..n_models {
        let raw = &data[n * MODEL_SIZE..(n + 1) * MODEL_SIZE];

        let mins = slice_to_vec3(&raw[0..12]);
        let maxs = slice_to_vec3(&raw[12..24]);

        let faces_idx = {
            let start = slice_to_u32(&raw[24..28]);
            let n = slice_to_u32(&raw[28..32]);

            if start + n > n_faces {
                return Err(ParseError::Invalid);
            }

            start..start + n
        };

        let brushes_idx = {
            let start = slice_to_u32(&raw[32..36]);
            let n = slice_to_u32(&raw[36..40]);

            if start + n > n_brushes {
                return Err(ParseError::Invalid);
            }

            start..start + n
        };

        models.push(Model {
            mins,
            maxs,
            faces_idx,
            brushes_idx,
        })
    }

    Ok(models.into_boxed_slice())
}

impl<T: CoordSystem> HasModels<T> for Q3BspFile<T> {
    type ModelsIter<'a> = std::slice::Iter<'a, Model>;

    fn models_iter(&self) -> Self::ModelsIter<'_> {
        self.models.iter()
    }

    fn get_model(&self, index: u32) -> &Model {
        &self.models[index as usize]
    }
}