1use std::path::{Path, PathBuf};
5
6use crate::transform::Transform;
7use crate::vmf::entities::Entity;
8use crate::vmf::world::World;
9use crate::{EntId, VmfFile, VmfResult};
10
11#[derive(Debug, Clone, Copy, PartialEq)]
13pub struct Instance {
14 pub file: usize,
16 pub parent: Option<(usize, EntId)>,
19 pub transform: Transform,
21}
22
23#[derive(Debug)]
43pub struct VmfSystem {
44 pub files: Vec<VmfFile>,
47 pub instances: Vec<Instance>,
49 pub search_dirs: Vec<PathBuf>,
51 pub warnings: Vec<String>,
53}
54
55#[derive(Debug, Clone)]
57pub struct Flattened {
58 pub vmf: VmfFile,
59 pub sources: Vec<(usize, EntId)>,
61}
62
63impl VmfSystem {
64 pub fn open(path: impl AsRef<Path>) -> VmfResult<Self> {
66 Self::open_with(path, Vec::new())
67 }
68
69 pub fn open_with(path: impl AsRef<Path>, search_dirs: Vec<PathBuf>) -> VmfResult<Self> {
71 let root = VmfFile::open(path.as_ref().canonicalize()?)?;
72 let mut system = Self {
73 files: vec![root],
74 instances: Vec::new(),
75 search_dirs,
76 warnings: Vec::new(),
77 };
78 system.relink();
79 Ok(system)
80 }
81
82 pub fn relink(&mut self) {
86 self.warnings.clear();
87 self.instances.clear();
88 self.instances.push(Instance {
89 file: 0,
90 parent: None,
91 transform: Transform::IDENTITY,
92 });
93
94 let mut current = 0;
96 while current < self.instances.len() {
97 let vmf = &self.files[self.instances[current].file];
98 let placer = vmf.path.clone().unwrap_or_default();
99 let dir = Path::new(&placer).parent().map(Path::to_path_buf);
100 let links: Vec<(u32, String, Transform)> = vmf
101 .entities
102 .iter()
103 .enumerate()
104 .filter(|(_, ent)| is_class(ent, "func_instance"))
105 .filter_map(|(idx, ent)| {
106 Some((
107 idx as u32,
108 ent.get("file")?.clone(),
109 Transform::from_entity(ent),
110 ))
111 })
112 .collect();
113
114 for (idx, name, local) in links {
115 let Some(file) = self.load(&name, dir.as_deref(), &placer) else {
116 continue;
117 };
118 if self.chain(current).any(|i| self.instances[i].file == file) {
119 self.warnings
120 .push(format!("{placer}: instance '{name}' includes itself"));
121 continue;
122 }
123 let transform = self.instances[current].transform * local;
124 self.instances.push(Instance {
125 file,
126 parent: Some((current, EntId { hidden: false, idx })),
127 transform,
128 });
129 }
130 current += 1;
131 }
132 }
133
134 pub fn chain(&self, instance: usize) -> impl Iterator<Item = usize> {
136 std::iter::successors(Some(instance), |&i| {
137 self.instances[i].parent.map(|(parent, _)| parent)
138 })
139 }
140
141 pub fn iter_entities(&self) -> impl Iterator<Item = (usize, EntId, &Entity)> {
144 self.files
145 .iter()
146 .enumerate()
147 .flat_map(|(file, vmf)| vmf.iter_entities().map(move |(id, ent)| (file, id, ent)))
148 }
149
150 pub fn iter_entities_mut(&mut self) -> impl Iterator<Item = (usize, EntId, &mut Entity)> {
152 self.files.iter_mut().enumerate().flat_map(|(file, vmf)| {
153 vmf.iter_entities_mut()
154 .map(move |(id, ent)| (file, id, ent))
155 })
156 }
157
158 pub fn flatten(&self) -> Flattened {
164 let root = &self.files[0];
165
166 let mut vmf = VmfFile {
168 path: None,
170 versioninfo: root.versioninfo.clone(),
171 visgroups: root.visgroups.clone(),
172 viewsettings: root.viewsettings.clone(),
173 world: World {
174 key_values: root.world.key_values.clone(),
175 groups: root.world.groups.clone(),
176 extra: root.world.extra.clone(),
177 ..Default::default()
178 },
179 cameras: root.cameras.clone(),
180 cordons: root.cordons.clone(),
181 extra_blocks: root.extra_blocks.clone(),
182 ..Default::default()
183 };
184
185 let mut sources = Vec::new();
186 for (index, inst) in self.instances.iter().enumerate() {
187 let file = &self.files[inst.file];
188
189 for solid in &file.world.solids {
190 let mut solid = solid.clone();
191 inst.transform.apply_solid(&mut solid);
192 vmf.world.solids.push(solid);
193 }
194
195 for (idx, ent) in file.entities.iter().enumerate() {
196 if is_class(ent, "func_instance") || is_class(ent, "func_instance_parms") {
197 continue;
198 }
199 let mut ent = ent.clone();
200 inst.transform.apply_entity(&mut ent);
201 vmf.entities.push(ent);
202 sources.push((index, EntId { hidden: false, idx: idx as u32 }));
203 }
204 }
205
206 Flattened { vmf, sources }
207 }
208
209 pub fn save(&self) -> VmfResult<()> {
211 for vmf in &self.files {
212 if let Some(path) = &vmf.path {
213 vmf.save(path)?;
214 }
215 }
216
217 Ok(())
218 }
219
220 fn load(&mut self, name: &str, dir: Option<&Path>, placer: &str) -> Option<usize> {
222 if name.trim().is_empty() {
223 return None;
224 }
225
226 let Some(path) = resolve(name, dir, &self.search_dirs) else {
227 self.warnings
228 .push(format!("{placer}: instance '{name}' not found"));
229 return None;
230 };
231 let loaded = self
232 .files
233 .iter()
234 .position(|vmf| vmf.path.as_deref().map(Path::new) == Some(path.as_path()));
235
236 if loaded.is_some() {
237 return loaded;
238 }
239
240 match VmfFile::open(&path) {
241 Ok(vmf) => {
242 self.files.push(vmf);
243 Some(self.files.len() - 1)
244 }
245 Err(err) => {
246 self.warnings
247 .push(format!("{placer}: instance '{}': {err}", path.display()));
248 None
249 }
250 }
251 }
252}
253
254fn is_class(ent: &Entity, class: &str) -> bool {
255 ent.classname()
256 .is_some_and(|name| name.eq_ignore_ascii_case(class))
257}
258
259fn resolve(name: &str, dir: Option<&Path>, search_dirs: &[PathBuf]) -> Option<PathBuf> {
263 let mut relative = PathBuf::from(name.trim().replace('\\', "/"));
264 relative.set_extension("vmf");
265 let maps = dir.and_then(|dir| {
266 dir.ancestors()
267 .filter(|dir| {
268 dir.file_name()
269 .is_some_and(|name| name.eq_ignore_ascii_case("maps"))
270 })
271 .last()
272 });
273 dir.into_iter()
274 .chain(maps)
275 .chain(search_dirs.iter().map(PathBuf::as_path))
276 .map(|base| base.join(&relative))
277 .find(|candidate| candidate.is_file())?
278 .canonicalize()
279 .ok()
280}