Skip to main content

source_vmf/vmf/
file.rs

1use std::{
2    fs::{self, File},
3    io::{Read, Write},
4    path::Path,
5    str::FromStr,
6};
7
8use crate::{VmfBlock, VmfError, VmfResult, VmfSerializable, parser};
9#[cfg(feature = "serialization")]
10use serde::{Deserialize, Serialize};
11
12use super::entities::{Entities, Entity};
13use super::metadata::{VersionInfo, ViewSettings, VisGroups};
14use super::regions::{Cameras, Cordons};
15use super::world::{Solid, World};
16
17/// Represents a parsed VMF file.
18#[derive(Debug, Clone, PartialEq)]
19#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
20pub struct VmfFile {
21    /// The path to the VMF file, if known.
22    #[cfg_attr(
23        feature = "serialization",
24        serde(default, skip_serializing_if = "Option::is_none")
25    )]
26    pub path: Option<String>,
27    /// The version info of the VMF file.
28    pub versioninfo: VersionInfo,
29    /// The visgroups in the VMF file.
30    pub visgroups: VisGroups,
31    /// The view settings in the VMF file.
32    pub viewsettings: ViewSettings,
33    /// The world data in the VMF file.
34    pub world: World,
35    /// The entities in the VMF file.
36    pub entities: Entities,
37    /// The hidden entities in the VMF file.
38    pub hiddens: Entities,
39    /// The camera data in the VMF file.
40    pub cameras: Cameras,
41    /// The cordon data in the VMF file.
42    pub cordons: Cordons,
43    /// Top-level blocks this struct does not model, kept so they survive a
44    /// parse/serialize round-trip.
45    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Vec::is_empty"))]
46    pub extra_blocks: Vec<VmfBlock>,
47    /// Non-fatal warnings encountered during parsing (e.g. fallback defaults, unknown blocks).
48    #[cfg_attr(feature = "serialization", serde(default, skip_serializing_if = "Vec::is_empty"))]
49    pub warnings: Vec<String>,
50    /// Number of warnings suppressed after exceeding the warning limit.
51    #[cfg_attr(feature = "serialization", serde(default))]
52    pub suppressed_warnings: usize,
53}
54
55impl Default for VmfFile {
56    fn default() -> Self {
57        Self {
58            path: None,
59            versioninfo: Default::default(),
60            visgroups: Default::default(),
61            viewsettings: Default::default(),
62            world: Default::default(),
63            entities: Entities(Vec::with_capacity(128)),
64            hiddens: Entities(Vec::with_capacity(16)),
65            cameras: Default::default(),
66            cordons: Default::default(),
67            extra_blocks: Vec::new(),
68            warnings: Vec::new(),
69            suppressed_warnings: 0,
70        }
71    }
72}
73
74impl VmfFile {
75    /// Converts the `VmfFile` to a string in VMF format.
76    pub fn to_vmf_string(&self) -> String {
77        let mut output = String::new();
78
79        // metadatas
80        output.push_str(&self.versioninfo.to_vmf_string(0));
81        output.push_str(&self.visgroups.to_vmf_string(0));
82        output.push_str(&self.viewsettings.to_vmf_string(0));
83        output.push_str(&self.world.to_vmf_string(0));
84
85        // entities
86        for entity in &*self.entities {
87            output.push_str(&entity.to_vmf_string(0));
88        }
89
90        for entity in &*self.hiddens {
91            output.push_str("hidden\n{\n");
92            output.push_str(&entity.to_vmf_string(1));
93            output.push_str("}\n");
94        }
95
96        // regions
97        output.push_str(&self.cameras.to_vmf_string(0));
98        output.push_str(&self.cordons.to_vmf_string(0));
99
100        for block in &self.extra_blocks {
101            output.push_str(&block.serialize(0));
102        }
103
104        output
105    }
106
107    /// Parses a VMF file from a string.
108    ///
109    /// # Examples
110    ///
111    /// ```
112    /// use source_vmf::VmfFile;
113    ///
114    /// let vmf_content = r#"
115    /// versioninfo
116    /// {
117    ///     "editorversion" "400"
118    ///     "editorbuild" "8000"
119    ///     "mapversion" "1"
120    ///     "formatversion" "100"
121    ///     "prefab" "0"
122    /// }
123    /// "#;
124    ///
125    /// let vmf_file = VmfFile::parse(vmf_content);
126    /// assert!(vmf_file.is_ok());
127    /// ```
128    pub fn parse(content: &str) -> VmfResult<Self> {
129        parser::parse_vmf(content)
130    }
131
132    /// Opens and parses a VMF file from a file path.
133    ///
134    /// # Examples
135    ///
136    /// ```no_run
137    /// use source_vmf::VmfFile;
138    ///
139    /// let vmf_file = VmfFile::open("your_map.vmf");
140    /// assert!(vmf_file.is_ok());
141    /// ```
142    pub fn open(path: impl AsRef<Path>) -> VmfResult<Self> {
143        let path_str = path.as_ref().to_string_lossy().to_string();
144        let mut file = File::open(path)?;
145        let mut content = Vec::new();
146        file.read_to_end(&mut content)?;
147        let content = String::from_utf8_lossy(&content);
148
149        let mut vmf_file = VmfFile::parse(&content)?;
150        vmf_file.path = Some(path_str);
151        Ok(vmf_file)
152    }
153
154    /// Saves the `VmfFile` to a file at the specified path.
155    ///
156    /// Writes to a temporary `.part` file first and renames it into place.
157    ///
158    /// # Examples
159    ///
160    /// ```no_run
161    /// use source_vmf::VmfFile;
162    ///
163    /// let vmf_file = VmfFile::open("your_map.vmf").unwrap();
164    /// let result = vmf_file.save("new_map.vmf");
165    /// assert!(result.is_ok());
166    /// ```
167    pub fn save(&self, path: impl AsRef<Path>) -> VmfResult<()> {
168        let path = path.as_ref();
169
170        let mut name = path.file_name().unwrap_or_default().to_os_string();
171        name.push(".part");
172        let partial = path.with_file_name(name);
173
174        if let Err(e) = self.write_to(&partial) {
175            let _ = fs::remove_file(&partial);
176            return Err(e.into());
177        }
178        fs::rename(&partial, path)?;
179        Ok(())
180    }
181
182    fn write_to(&self, path: &Path) -> std::io::Result<()> {
183        let mut file = File::create(path)?;
184        file.write_all(self.to_vmf_string().as_bytes())?;
185        file.sync_all()
186    }
187
188    /// Merges the contents of another `VmfFile` into this one.
189    ///
190    /// Combines `visgroups`, `world` solids (visible and hidden), `entities`, `hiddens`,
191    /// and `cordons`. `versioninfo`, `viewsettings`, and `cameras` are retained from `self`.
192    ///
193    /// # Examples
194    ///
195    /// ```no_run
196    /// use source_vmf::prelude::*;
197    ///
198    /// let mut vmf1 = VmfFile::open("map1.vmf").unwrap();
199    /// let vmf2 = VmfFile::open("map2.vmf").unwrap();
200    ///
201    /// vmf1.merge(vmf2);
202    /// ```
203    pub fn merge(&mut self, other: Self) {
204        self.visgroups.groups.extend(other.visgroups.groups);
205        self.world.solids.extend(other.world.solids);
206        self.world.hidden.extend(other.world.hidden);
207
208        self.entities.extend(other.entities);
209        self.hiddens.extend(other.hiddens);
210
211        self.cordons.extend(other.cordons.cordons);
212    }
213
214    /// Returns an iterator over entities (including hidden ones) belonging to the specified VisGroup ID.
215    pub fn get_entities_in_visgroup(
216        &self,
217        group_id: i32,
218        include_children: bool,
219    ) -> Option<impl Iterator<Item = &Entity> + '_> {
220        let ids = self.visgroups.resolve_ids(group_id, include_children)?;
221        Some(
222            self.iter_entities()
223                .map(|(_, entity)| entity)
224                .filter(move |entity| {
225                    entity
226                        .editor
227                        .visgroup_ids
228                        .iter()
229                        .any(|ent_group_id| ids.contains(ent_group_id))
230                }),
231        )
232    }
233
234    /// Returns a mutable iterator over entities (including hidden ones) belonging to the specified VisGroup ID.
235    pub fn get_entities_in_visgroup_mut(
236        &mut self,
237        group_id: i32,
238        include_children: bool,
239    ) -> Option<impl Iterator<Item = &mut Entity> + '_> {
240        let ids = self.visgroups.resolve_ids(group_id, include_children)?;
241        Some(
242            self.entities
243                .iter_mut()
244                .chain(self.hiddens.iter_mut())
245                .filter(move |entity| {
246                    entity
247                        .editor
248                        .visgroup_ids
249                        .iter()
250                        .any(|ent_group_id| ids.contains(ent_group_id))
251                }),
252        )
253    }
254
255    /// Returns an iterator over world solids (visible and hidden) belonging to the specified VisGroup ID.
256    pub fn get_solids_in_visgroup(
257        &self,
258        group_id: i32,
259        include_children: bool,
260    ) -> Option<impl Iterator<Item = &Solid> + '_> {
261        let ids = self.visgroups.resolve_ids(group_id, include_children)?;
262        Some(
263            self.world
264                .iter_solids()
265                .filter(move |solid| {
266                    solid
267                        .editor
268                        .visgroup_ids
269                        .iter()
270                        .any(|solid_group_id| ids.contains(solid_group_id))
271                }),
272        )
273    }
274
275    /// Returns a mutable iterator over world solids (visible and hidden) belonging to the specified VisGroup ID.
276    pub fn get_solids_in_visgroup_mut(
277        &mut self,
278        group_id: i32,
279        include_children: bool,
280    ) -> Option<impl Iterator<Item = &mut Solid> + '_> {
281        let ids = self.visgroups.resolve_ids(group_id, include_children)?;
282        Some(
283            self.world
284                .iter_solids_mut()
285                .filter(move |solid| {
286                    solid
287                        .editor
288                        .visgroup_ids
289                        .iter()
290                        .any(|solid_group_id| ids.contains(solid_group_id))
291                }),
292        )
293    }
294}
295
296impl FromStr for VmfFile {
297    type Err = VmfError;
298
299    fn from_str(s: &str) -> Result<Self, Self::Err> {
300        VmfFile::parse(s)
301    }
302}