Skip to main content

source_vmf/vmf/
index.rs

1//! Entity addressing and targetname index for fast lookups
2
3use std::collections::HashMap;
4
5use super::entities::Entity;
6use super::file::VmfFile;
7
8/// Addresses an entity in a [`VmfFile`] across visible and hidden entities.
9///
10/// Valid only while entities are not inserted, removed, or reordered.
11#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
12pub struct EntId {
13    /// Whether the entity is in [`VmfFile::hiddens`].
14    pub hidden: bool,
15    pub idx: u32,
16}
17
18impl VmfFile {
19    /// Returns a reference to the entity at `id`, or `None` if the index is out of bounds.
20    pub fn entity(&self, id: EntId) -> Option<&Entity> {
21        let list = if id.hidden {
22            &self.hiddens
23        } else {
24            &self.entities
25        };
26        list.get(id.idx as usize)
27    }
28
29    /// Returns a mutable reference to the entity at `id`, or `None` if the index is out of bounds.
30    pub fn entity_mut(&mut self, id: EntId) -> Option<&mut Entity> {
31        let list = if id.hidden {
32            &mut self.hiddens
33        } else {
34            &mut self.entities
35        };
36        list.get_mut(id.idx as usize)
37    }
38
39    /// Iterates over all entities in the file, including hidden ones.
40    pub fn iter_entities(&self) -> impl Iterator<Item = (EntId, &Entity)> {
41        let visible = self.entities.iter().enumerate().map(|(i, ent)| {
42            (
43                EntId {
44                    hidden: false,
45                    idx: i as u32,
46                },
47                ent,
48            )
49        });
50        let hidden = self.hiddens.iter().enumerate().map(|(i, ent)| {
51            (
52                EntId {
53                    hidden: true,
54                    idx: i as u32,
55                },
56                ent,
57            )
58        });
59        visible.chain(hidden)
60    }
61
62    /// Mutably iterates over all entities in the file, including hidden ones.
63    pub fn iter_entities_mut(&mut self) -> impl Iterator<Item = (EntId, &mut Entity)> {
64        let visible = self.entities.iter_mut().enumerate().map(|(i, ent)| {
65            (
66                EntId {
67                    hidden: false,
68                    idx: i as u32,
69                },
70                ent,
71            )
72        });
73        let hidden = self.hiddens.iter_mut().enumerate().map(|(i, ent)| {
74            (
75                EntId {
76                    hidden: true,
77                    idx: i as u32,
78                },
79                ent,
80            )
81        });
82        visible.chain(hidden)
83    }
84}
85
86/// Targetname index mapping entity names to their identifiers.
87///
88/// Names are not unique in a VMF, so lookups return slices of [`EntId`].
89#[derive(Debug, Default, Clone)]
90pub struct EntityIndex {
91    names: HashMap<Box<str>, Vec<EntId>>,
92}
93
94impl EntityIndex {
95    /// Builds an index from the given [`VmfFile`].
96    pub fn build(vmf: &VmfFile) -> Self {
97        let mut names: HashMap<Box<str>, Vec<EntId>> = HashMap::new();
98        for (id, ent) in vmf.iter_entities() {
99            if let Some(name) = ent.targetname() {
100                names.entry(name.into()).or_default().push(id);
101            }
102        }
103        Self { names }
104    }
105
106    /// Returns entity IDs matching the given targetname exactly.
107    pub fn by_name(&self, name: &str) -> &[EntId] {
108        self.names.get(name).map_or(&[], |ids| ids.as_slice())
109    }
110
111    /// Returns entity IDs whose targetname starts with `prefix`.
112    pub fn by_prefix<'a>(&'a self, prefix: &'a str) -> impl Iterator<Item = EntId> + 'a {
113        self.names
114            .iter()
115            .filter(move |(name, _)| name.starts_with(prefix))
116            .flat_map(|(_, ids)| ids.iter().copied())
117    }
118}