Skip to main content

source_vmf/
lib.rs

1//! A library for parsing and manipulating Valve Map Format (VMF) files.
2//!
3//! This library provides functionality to parse VMF files used in Source Engine games
4//! into Rust data structures, modify the data, and serialize it back into a VMF file.
5//!
6//! # Example
7//!
8//! ```
9//! use source_vmf::prelude::*;
10//! use std::fs::File;
11//!
12//! fn main() -> Result<(), VmfError> {
13//!     let vmf_file = VmfFile::open("vmf_examples/your_map.vmf")?;
14//!
15//!     println!("Map Version: {}", vmf_file.versioninfo.map_version);
16//!
17//!     Ok(())
18//! }
19//! ```
20
21use indexmap::IndexMap;
22#[cfg(feature = "serialization")]
23use serde::{Deserialize, Serialize};
24
25pub mod parse_ctx;
26pub mod parser;
27pub mod system;
28pub mod transform;
29pub(crate) mod utils;
30pub mod vmf;
31
32pub mod errors;
33pub mod prelude;
34
35pub use errors::{VmfError, VmfResult};
36pub use parse_ctx::{FromBlock, ParseCtx};
37
38/// A trait for types that can be serialized into a VMF string representation.
39pub trait VmfSerializable {
40    /// Serializes the object into a VMF string.
41    ///
42    /// # Arguments
43    ///
44    /// * `indent_level` - The indentation level to use for formatting.
45    ///
46    /// # Returns
47    ///
48    /// A string representation of the object in VMF format.
49    fn to_vmf_string(&self, indent_level: usize) -> String;
50}
51
52pub use system::{Flattened, Instance, VmfSystem};
53pub use transform::Transform;
54pub use vmf::{EntId, EntityIndex, VmfFile};
55
56/// Preserves unrecognized keys and nested blocks during parsing for lossless round-tripping.
57#[derive(Debug, Default, Clone, PartialEq, Eq)]
58#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
59pub struct Extras {
60    /// Keys that are not mapped to typed struct fields.
61    pub key_values: IndexMap<String, String>,
62    /// Nested blocks that are not mapped to typed struct fields.
63    pub blocks: Vec<VmfBlock>,
64}
65
66/// Internal delimiter used to store multiple values of repeated keys in a single map entry.
67pub const REPEATED_KEY_SEP: char = '\r';
68
69/// Writes key-value pairs, expanding values joined by [`REPEATED_KEY_SEP`] back into separate lines.
70pub fn write_key_value(output: &mut String, indent: &str, key: &str, value: &str) {
71    for part in value.split(REPEATED_KEY_SEP) {
72        output.push_str(indent);
73        output.push('"');
74        output.push_str(key);
75        output.push_str("\" \"");
76        output.push_str(part);
77        output.push_str("\"\n");
78    }
79}
80
81/// Joins multiple values for a repeated key into a single string using [`REPEATED_KEY_SEP`].
82pub fn join_repeated_key(values: impl IntoIterator<Item = impl std::fmt::Display>) -> String {
83    let mut joined = String::new();
84    for value in values {
85        if !joined.is_empty() {
86            joined.push(REPEATED_KEY_SEP);
87        }
88        joined.push_str(&value.to_string());
89    }
90    joined
91}
92
93impl Extras {
94    pub fn is_empty(&self) -> bool {
95        self.key_values.is_empty() && self.blocks.is_empty()
96    }
97
98    /// Serializes unrecognized key-value pairs at the specified indentation level.
99    pub fn write_key_values(&self, output: &mut String, indent_level: usize) {
100        let indent = "\t".repeat(indent_level);
101        for (key, value) in &self.key_values {
102            write_key_value(output, &indent, key, value);
103        }
104    }
105
106    /// Serializes unrecognized blocks at the specified indentation level.
107    pub fn write_blocks(&self, output: &mut String, indent_level: usize) {
108        for block in &self.blocks {
109            output.push_str(&block.serialize(indent_level));
110        }
111    }
112}
113
114/// Represents a block in a VMF file, which can contain key-value pairs and other blocks.
115#[derive(Debug, Default, Clone, PartialEq, Eq)]
116#[cfg_attr(feature = "serialization", derive(Serialize, Deserialize))]
117pub struct VmfBlock {
118    /// The name of the block.
119    pub name: String,
120    /// The key-value pairs in the block.
121    pub key_values: IndexMap<String, String>, // what if Cow?!
122    /// The child blocks contained within this block.
123    pub blocks: Vec<VmfBlock>,
124}
125
126impl VmfBlock {
127    /// Serializes the `VmfBlock` into a string with the specified indentation level.
128    ///
129    /// # Arguments
130    ///
131    /// * `indent_level` - The indentation level to use for formatting.
132    ///
133    /// # Returns
134    ///
135    /// A string representation of the `VmfBlock` in VMF format.
136    pub fn serialize(&self, indent_level: usize) -> String {
137        let indent = "\t".repeat(indent_level);
138        let mut output = String::new();
139
140        // Opens the block with its name
141        output.push_str(&format!("{}{}\n", indent, self.name));
142        output.push_str(&format!("{}{{\n", indent));
143
144        // Adds all key-value pairs with the required indent
145        for (key, value) in &self.key_values {
146            write_key_value(&mut output, &format!("{indent}\t"), key, value);
147        }
148
149        // Adds nested blocks with an increased indentation level
150        for block in &self.blocks {
151            output.push_str(&block.serialize(indent_level + 1));
152        }
153
154        // Closes the block
155        output.push_str(&format!("{}}}\n", indent));
156
157        output
158    }
159}