1use crate::parse_ctx::{FromBlock, ParseCtx, impl_try_from_block};
4use crate::{Extras, VmfBlock, VmfSerializable};
5use derive_more::{Deref, DerefMut, IntoIterator};
6use indexmap::IndexMap;
7#[cfg(feature = "serialization")]
8use serde::{Deserialize, Serialize};
9
10use super::common::Editor;
11use super::world::Solid;
12use std::mem;
13
14impl_try_from_block!(Entity);
15
16pub use super::connection::{Connection, InstanceIo, Special, Target};
19
20#[derive(Debug, Default, Clone, PartialEq)]
22#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
23pub struct Entity {
24 pub key_values: IndexMap<String, String>,
26 #[cfg_attr(
28 feature = "serialization",
29 serde(default, skip_serializing_if = "Option::is_none")
30 )]
31 pub connections: Option<Vec<Connection>>,
32 #[cfg_attr(
34 feature = "serialization",
35 serde(default, skip_serializing_if = "Option::is_none")
36 )]
37 pub solids: Option<Vec<Solid>>,
38 pub editor: Editor,
40 #[cfg_attr(feature = "serialization", serde(default, skip_serializing))]
44 pub is_hidden: bool,
45 #[cfg_attr(
47 feature = "serialization",
48 serde(default, skip_serializing_if = "Extras::is_empty")
49 )]
50 pub extra: Extras,
51}
52
53impl Entity {
54 pub fn new(classname: impl Into<String>, id: u64) -> Self {
71 let mut key_values = IndexMap::with_capacity(12);
72 key_values.insert("classname".to_string(), classname.into());
73 key_values.insert("id".to_string(), id.to_string());
74 Entity {
75 key_values,
76 connections: None,
77 solids: None,
78 editor: Editor::default(),
79 is_hidden: false,
80 extra: Extras::default(),
81 }
82 }
83
84 pub fn set(&mut self, key: String, value: String) {
92 self.key_values.insert(key, value);
93 }
94
95 pub fn remove_key(&mut self, key: &str) -> Option<String> {
105 self.key_values.shift_remove(key)
106 }
107
108 pub fn swap_remove_key(&mut self, key: &str) -> Option<String> {
119 self.key_values.swap_remove(key)
120 }
121
122 pub fn get(&self, key: &str) -> Option<&String> {
132 self.key_values.get(key)
133 }
134
135 pub fn get_mut(&mut self, key: &str) -> Option<&mut String> {
145 self.key_values.get_mut(key)
146 }
147
148 pub fn classname(&self) -> Option<&str> {
154 self.key_values.get("classname").map(|s| s.as_str())
155 }
156
157 pub fn targetname(&self) -> Option<&str> {
163 self.key_values.get("targetname").map(|s| s.as_str())
164 }
165
166 pub fn id(&self) -> u64 {
168 self.key_values
169 .get("id")
170 .and_then(|s| s.parse::<u64>().ok())
171 .unwrap_or(0)
172 }
173
174 pub fn model(&self) -> Option<&str> {
180 self.key_values.get("model").map(|s| s.as_str())
181 }
182
183 pub fn add_connection(
203 &mut self,
204 output: impl Into<String>,
205 target_entity: impl Into<String>,
206 input: impl Into<String>,
207 parms: impl Into<String>,
208 delay: f32,
209 fire_limit: i32,
210 ) {
211 let connection = Connection {
212 output: output.into(),
213 target: target_entity.into(),
214 input: input.into(),
215 params: parms.into(),
216 delay,
217 fire_limit,
218 };
219
220 if let Some(connections) = &mut self.connections {
221 connections.push(connection);
222 } else {
223 self.connections = Some(vec![connection]);
224 }
225 }
226
227 pub fn clear_connections(&mut self) {
229 self.connections = None;
230 }
231
232 pub fn has_connection(&self, output: &str, input: &str) -> bool {
241 if let Some(connections) = &self.connections {
242 connections
243 .iter()
244 .any(|c| c.output == output && c.input == input)
245 } else {
246 false
247 }
248 }
249}
250
251impl FromBlock for Entity {
252 fn from_block(mut block: VmfBlock, ctx: &mut ParseCtx) -> Self {
253 let blocks = std::mem::take(&mut block.blocks);
254
255 let mut ent = Self {
256 key_values: block.key_values,
257 ..Default::default()
258 };
259 let mut solids = Vec::with_capacity(blocks.len());
260
261 for mut inner_block in blocks {
262 let name = inner_block.name.clone();
263 if name.eq_ignore_ascii_case("editor") {
264 ctx.enter("editor");
265 ent.editor = Editor::from_block(inner_block, ctx);
266 ctx.leave();
267 } else if name.eq_ignore_ascii_case("connections") {
268 ent.connections = process_connections(inner_block.key_values);
269 } else if name.eq_ignore_ascii_case("solid") {
270 ctx.enter_indexed("solid", solids.len());
271 solids.push(Solid::from_block(inner_block, ctx));
272 ctx.leave();
273 } else if name.eq_ignore_ascii_case("hidden") {
274 for hidden_block in mem::take(&mut inner_block.blocks) {
276 ctx.enter_indexed("hidden", solids.len());
277 solids.push(Solid::from_block(hidden_block, ctx));
278 ctx.leave();
279 }
280 } else {
281 ctx.warn(format!("unexpected block '{}', kept as-is", name));
282 ent.extra.blocks.push(inner_block);
283 }
284 }
285
286 if !solids.is_empty() {
287 ent.solids = Some(solids);
288 }
289
290 ent
291 }
292}
293
294impl From<Entity> for VmfBlock {
295 fn from(val: Entity) -> Self {
296 let mut blocks = Vec::with_capacity(3);
297
298 if let Some(connections) = &val.connections {
299 if !connections.is_empty() {
300 blocks.push(VmfBlock {
301 name: "connections".to_string(),
302 key_values: Connection::to_key_values(connections),
303 blocks: Vec::new(),
304 });
305 }
306 }
307 if let Some(solids) = val.solids {
308 blocks.extend(solids.into_iter().map(VmfBlock::from));
309 }
310 blocks.push(val.editor.into());
311 blocks.extend(val.extra.blocks);
312
313 let mut key_values = val.key_values;
314 key_values.extend(val.extra.key_values);
315
316 VmfBlock {
317 name: "entity".to_string(),
318 key_values,
319 blocks,
320 }
321 }
322}
323
324impl VmfSerializable for Entity {
325 fn to_vmf_string(&self, indent_level: usize) -> String {
326 let indent = "\t".repeat(indent_level);
327 let mut output = String::with_capacity(256);
328
329 output.push_str(&format!("{0}entity\n{0}{{\n", indent));
331
332 for (key, value) in &self.key_values {
334 crate::write_key_value(&mut output, &format!("{indent}\t"), key, value);
335 }
336
337 if let Some(connections) = &self.connections {
339 output.push_str(&format!("{0}\tconnections\n{0}\t{{\n", indent));
340 for connection in connections {
341 output.push_str(&format!(
342 "{}\t\t\"{}\" \"{}\"\n",
343 indent,
344 connection.output,
345 connection.to_value_string()
346 ));
347 }
348 output.push_str(&format!("{}\t}}\n", indent));
349 }
350
351 if let Some(solids) = &self.solids {
353 for solid in solids {
354 output.push_str(&solid.to_vmf_string(indent_level + 1));
355 }
356 }
357
358 output.push_str(&self.editor.to_vmf_string(indent_level + 1));
360 self.extra.write_blocks(&mut output, indent_level + 1);
361
362 output.push_str(&format!("{}}}\n", indent));
363
364 output
365 }
366}
367
368#[derive(Debug, Default, Clone, Deref, DerefMut, IntoIterator, PartialEq)]
370#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
371pub struct Entities(pub Vec<Entity>);
372
373impl Entities {
374 pub fn find_by_keyvalue<'a>(
381 &'a self,
382 key: &'a str,
383 value: &'a str,
384 ) -> impl Iterator<Item = &'a Entity> + 'a {
385 self.iter()
386 .filter(move |ent| ent.key_values.get(key).is_some_and(|v| v == value))
387 }
388
389 pub fn find_by_keyvalue_mut<'a>(
396 &'a mut self,
397 key: &'a str,
398 value: &'a str,
399 ) -> impl Iterator<Item = &'a mut Entity> + 'a {
400 self.iter_mut()
401 .filter(move |ent| ent.key_values.get(key).is_some_and(|v| v == value))
402 }
403
404 pub fn find_by_classname<'a>(
410 &'a self,
411 classname: &'a str,
412 ) -> impl Iterator<Item = &'a Entity> + 'a {
413 self.find_by_keyvalue("classname", classname)
414 }
415
416 pub fn find_by_name<'a>(&'a self, name: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
422 self.find_by_keyvalue("targetname", name)
423 }
424
425 pub fn find_by_classname_mut<'a>(
431 &'a mut self,
432 classname: &'a str,
433 ) -> impl Iterator<Item = &'a mut Entity> + 'a {
434 self.find_by_keyvalue_mut("classname", classname)
435 }
436
437 pub fn find_by_name_mut<'a>(
443 &'a mut self,
444 name: &'a str,
445 ) -> impl Iterator<Item = &'a mut Entity> + 'a {
446 self.find_by_keyvalue_mut("targetname", name)
447 }
448
449 pub fn find_by_model<'a>(&'a self, model: &'a str) -> impl Iterator<Item = &'a Entity> + 'a {
455 self.find_by_keyvalue("model", model)
456 }
457
458 pub fn find_by_model_mut<'a>(
464 &'a mut self,
465 model: &'a str,
466 ) -> impl Iterator<Item = &'a mut Entity> + 'a {
467 self.find_by_keyvalue_mut("model", model)
468 }
469
470 pub fn remove_entity(&mut self, entity_id: i32) -> Option<Entity> {
481 self.iter()
482 .position(|e| e.key_values.get("id") == Some(&entity_id.to_string()))
483 .map(|index| self.remove(index))
484 }
485
486 pub fn remove_by_keyvalue(&mut self, key: &str, value: &str) {
493 self.retain(|ent| ent.key_values.get(key).map(|v| v != value).unwrap_or(true));
494 }
495}
496
497fn process_connections(map: IndexMap<String, String>) -> Option<Vec<Connection>> {
498 Connection::from_key_values(&map)
499}