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