vmf_forge/vmf/
metadata.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
//! This module provides structures for representing metadata blocks in a VMF file, such as version info, visgroups, and view settings.

use indexmap::IndexMap;
use serde::{Deserialize, Serialize};

use crate::utils::{get_key, parse_hs_key, To01String};
use crate::{
    errors::{VmfError, VmfResult},
    VmfBlock, VmfSerializable,
};

/// Represents the version info of a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VersionInfo {
    /// The editor version.
    pub editor_version: i32,
    /// The editor build number.
    pub editor_build: i32,
    /// The map version.
    pub map_version: i32,
    /// The format version.
    pub format_version: i32,
    /// Whether the VMF is a prefab.
    pub prefab: bool,
}

impl TryFrom<VmfBlock> for VersionInfo {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let kv = &block.key_values;
        Ok(Self {
            editor_version: parse_hs_key!(kv, "editorversion", i32)?,
            editor_build: parse_hs_key!(kv, "editorbuild", i32)?,
            map_version: parse_hs_key!(kv, "mapversion", i32)?,
            format_version: parse_hs_key!(kv, "formatversion", i32)?,
            prefab: get_key!(kv, "prefab")? == "1",
        })
    }
}

impl Into<VmfBlock> for VersionInfo {
    fn into(self) -> VmfBlock {
        let mut key_values = IndexMap::new();
        key_values.insert("editorversion".to_string(), self.editor_version.to_string());
        key_values.insert("editorbuild".to_string(), self.editor_build.to_string());
        key_values.insert("mapversion".to_string(), self.map_version.to_string());
        key_values.insert("formatversion".to_string(), self.format_version.to_string());
        key_values.insert("prefab".to_string(), self.prefab.to_01_string());

        VmfBlock {
            name: "versioninfo".to_string(),
            key_values,
            blocks: Vec::new(),
        }
    }
}

impl VmfSerializable for VersionInfo {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(256);

        output.push_str(&format!("{0}versioninfo\n{0}{{\n", indent));
        output.push_str(&format!(
            "{}\t\"editorversion\" \"{}\"\n",
            indent, self.editor_version
        ));
        output.push_str(&format!(
            "{}\t\"editorbuild\" \"{}\"\n",
            indent, self.editor_build
        ));
        output.push_str(&format!(
            "{}\t\"mapversion\" \"{}\"\n",
            indent, self.map_version
        ));
        output.push_str(&format!(
            "{}\t\"formatversion\" \"{}\"\n",
            indent, self.format_version
        ));
        output.push_str(&format!(
            "{}\t\"prefab\" \"{}\"\n",
            indent,
            self.prefab.to_01_string()
        ));

        output.push_str(&format!("{}}}\n", indent));
        output
    }
}

/// Represents a collection of VisGroups in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VisGroups {
    /// The list of VisGroups.
    pub groups: Vec<VisGroup>,
}

impl TryFrom<VmfBlock> for VisGroups {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let mut groups = Vec::with_capacity(12);
        for group in block.blocks {
            groups.push(VisGroup::try_from(group)?);
        }

        Ok(Self { groups })
    }
}

impl Into<VmfBlock> for VisGroups {
    fn into(self) -> VmfBlock {
        let mut visgroups_block = VmfBlock {
            name: "visgroups".to_string(),
            key_values: IndexMap::new(),
            blocks: Vec::with_capacity(self.groups.len()),
        };

        for group in self.groups {
            visgroups_block.blocks.push(group.into())
        }

        visgroups_block
    }
}

impl VmfSerializable for VisGroups {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(128);

        output.push_str(&format!("{0}visgroups\n{0}{{\n", indent));

        if self.groups.is_empty() {
            output.push_str(&format!("{}}}\n", indent));
            return output;
        }

        for group in &self.groups {
            output.push_str(&group.to_vmf_string(indent_level));
        }

        output.push_str(&format!("\n{}}}\n", indent));
        output
    }
}

/// Represents a VisGroup in a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct VisGroup {
    /// The name of the VisGroup.
    pub name: String,
    /// The ID of the VisGroup.
    pub id: i32,
    /// The color of the VisGroup in the editor.
    pub color: String,
    /// The child VisGroups of this VisGroup, if any.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub children: Option<Vec<VisGroup>>,
}

impl TryFrom<VmfBlock> for VisGroup {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        let children = if block.blocks.is_empty() {
            None
        } else {
            Some(
                block
                    .blocks
                    .into_iter()
                    .map(VisGroup::try_from)
                    .collect::<VmfResult<Vec<_>>>()?,
            )
        };

        Ok(Self {
            name: get_key!(block.key_values, "name")?.to_owned(),
            id: parse_hs_key!(block.key_values, "visgroupid", i32)?,
            color: get_key!(block.key_values, "color")?.to_owned(),
            children,
        })
    }
}

impl Into<VmfBlock> for VisGroup {
    fn into(self) -> VmfBlock {
        // Create a block for VisGroup
        let mut visgroup_block = VmfBlock {
            name: "visgroup".to_string(),
            key_values: IndexMap::new(),
            blocks: Vec::new(),
        };

        // Adds key-value pairs for VisGroup
        visgroup_block
            .key_values
            .insert("name".to_string(), self.name);
        visgroup_block
            .key_values
            .insert("visgroupid".to_string(), self.id.to_string());
        visgroup_block
            .key_values
            .insert("color".to_string(), self.color);

        // If the `VisGroup` has a child element, adds it as nested block
        if let Some(children) = self.children {
            for child in children {
                visgroup_block.blocks.push(child.into());
            }
        }

        visgroup_block
    }
}

impl VmfSerializable for VisGroup {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(64);

        output.push_str(&format!("{0}\tvisgroup\n\t{0}{{\n", indent));
        output.push_str(&format!("{}\t\t\"name\" \"{}\"\n", indent, self.name));
        output.push_str(&format!("{}\t\t\"visgroupid\" \"{}\"\n", indent, self.id));
        output.push_str(&format!("{}\t\t\"color\" \"{}\"\n", indent, self.color));

        // If there are child elements, adds them
        if let Some(ref children) = self.children {
            for child in children {
                output.push_str(&child.to_vmf_string(indent_level + 1));
            }
        }

        output.push_str(&format!("{}\t}}\n", indent));
        output
    }
}

/// Represents the view settings of a VMF file.
#[derive(Debug, Default, Clone, Serialize, Deserialize)]
pub struct ViewSettings {
    /// Whether snapping to the grid is enabled.
    pub snap_to_grid: bool,
    /// Whether the grid is shown in the editor.
    pub show_grid: bool,
    /// Whether the logical grid is shown in the editor.
    pub show_logical_grid: bool,
    /// The grid spacing.
    pub grid_spacing: u16,
    /// Whether the 3D grid is shown in the editor.
    pub show_3d_grid: bool,
}

impl TryFrom<VmfBlock> for ViewSettings {
    type Error = VmfError;

    fn try_from(block: VmfBlock) -> VmfResult<Self> {
        Ok(Self {
            snap_to_grid: get_key!(&block.key_values, "bSnapToGrid")? == "1",
            show_grid: get_key!(&block.key_values, "bShowGrid")? == "1",
            show_logical_grid: get_key!(&block.key_values, "bShowLogicalGrid")? == "1",
            grid_spacing: get_key!(&block.key_values, "nGridSpacing")?
                .parse()
                .unwrap_or(64),
            show_3d_grid: get_key!(&block.key_values, "bShow3DGrid", "0".into()) == "1",
        })
    }
}

impl Into<VmfBlock> for ViewSettings {
    fn into(self) -> VmfBlock {
        let mut key_values = IndexMap::new();
        key_values.insert("bSnapToGrid".to_string(), self.snap_to_grid.to_01_string());
        key_values.insert("bShowGrid".to_string(), self.show_grid.to_01_string());
        key_values.insert(
            "bShowLogicalGrid".to_string(),
            self.show_logical_grid.to_01_string(),
        );
        key_values.insert("nGridSpacing".to_string(), self.grid_spacing.to_string());
        key_values.insert("bShow3DGrid".to_string(), self.show_3d_grid.to_01_string());

        VmfBlock {
            name: "viewsettings".to_string(),
            key_values,
            blocks: Vec::new(),
        }
    }
}

impl VmfSerializable for ViewSettings {
    fn to_vmf_string(&self, indent_level: usize) -> String {
        let indent = "\t".repeat(indent_level);
        let mut output = String::with_capacity(64);

        output.push_str(&format!("{0}viewsettings\n{0}{{\n", indent));
        output.push_str(&format!(
            "{}\t\"bSnapToGrid\" \"{}\"\n",
            indent,
            self.snap_to_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"bShowGrid\" \"{}\"\n",
            indent,
            self.show_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"bShowLogicalGrid\" \"{}\"\n",
            indent,
            self.show_logical_grid.to_01_string()
        ));
        output.push_str(&format!(
            "{}\t\"nGridSpacing\" \"{}\"\n",
            indent, self.grid_spacing
        ));
        output.push_str(&format!(
            "{}\t\"bShow3DGrid\" \"{}\"\n",
            indent,
            self.show_3d_grid.to_01_string()
        ));

        output.push_str(&format!("{}}}\n", indent));
        output
    }
}