Skip to main content

rpfm_lib/files/unit_variant/
mod.rs

1//---------------------------------------------------------------------------//
2// Copyright (c) 2017-2026 Ismael Gutiérrez González. All rights reserved.
3//
4// This file is part of the Rusted PackFile Manager (RPFM) project,
5// which can be found here: https://github.com/Frodo45127/rpfm.
6//
7// This file is licensed under the MIT license, which can be found here:
8// https://github.com/Frodo45127/rpfm/blob/master/LICENSE.
9//---------------------------------------------------------------------------//
10
11//! This is a module to read/write binary UnitVariant files.
12//!
13//! UnitVariants define data about what textures and parts unit models use within a unit.
14//! They're usually xml files covered by the [`super::text`] module, but in older games
15//! (Shogun 2) they're binary files instead, and thus they need their own logic.
16//!
17//! # UnitVariant Structure
18//!
19//! ## Header
20//! ### V1
21//!
22//! | Bytes | Type     | Data                                                         |
23//! | ----- | -------- | ------------------------------------------------------------ |
24//! | 4     | StringU8 | Signature of the file.                                       |
25//! | 4     | [u32]    | Version of the file.                                         |
26//! | 4     | [u32]    | Category count.                                              |
27//! | 4     | [u32]    | Index from the start to the begining of the categories data. |
28//! | 4     | [u32]    | Index from the start to the begining of the variants data.   |
29//!
30//! ### V2
31//!
32//! | Bytes | Type     | Data                                                         |
33//! | ----- | -------- | ------------------------------------------------------------ |
34//! | 4     | StringU8 | Signature of the file.                                       |
35//! | 4     | [u32]    | Version of the file.                                         |
36//! | 4     | [u32]    | Category count.                                              |
37//! | 4     | [u32]    | Index from the start to the begining of the categories data. |
38//! | 4     | [u32]    | Index from the start to the begining of the variants data.   |
39//! | 4     | [u32]    | Unknown.                                                     |
40//!
41//! ## Data
42//!
43//! This is valid for all versions.
44//!
45//! | Bytes                | Type                                 | Data                                                   |
46//! | -------------------- | ------------------------------------ | ------------------------------------------------------ |
47//! | 528 * Category Count | [Category](#category-structure) List | List of categories in the UnitVariant.                 |
48//! | 1026 * Variant Count | [Variant](#variant-structure) List   | List of variants in the categories of the UnitVariant. |
49//!
50//! ### Category Structure
51//!
52//! This is valid for all versions.
53//!
54//! | Bytes | Type      | Data                                          |
55//! | ----- | --------- | --------------------------------------------- |
56//! | 512   | StringU16 | Category name. 00-Padded, Max 256 characters. |
57//! | 8     | [u64]     | Category Id.                                  |
58//! | 4     | [u32]     | Variant count for this category.              |
59//! | 4     | [u32]     | Variants before the ones of this category.    |
60//!
61//!  ### Variant Structure
62//!
63//! This is valid for all versions.
64//!
65//! | Bytes | Type      | Data                                                |
66//! | ----- | --------- | --------------------------------------------------- |
67//! | 512   | StringU16 | Mesh file path. 00-Padded, Max 256 characters.      |
68//! | 512   | StringU16 | Texture folder path. 00-Padded, Max 256 characters. |
69//! | 2     | [u16]     | Unknown, possibly a termination.                    |
70
71use getset::*;
72use serde_derive::{Serialize, Deserialize};
73
74use crate::error::{RLibError, Result};
75use crate::binary::{ReadBytes, WriteBytes};
76use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
77use crate::utils::check_size_mismatch;
78
79/// Signature/Magic Numbers/Whatever of an UnitVariant.
80const SIGNATURE: &str = "VRNT";
81
82const HEADER_LENGTH_V1: u32 = 20;
83const HEADER_LENGTH_V2: u32 = 24;
84
85pub use crate::files::detection::unit_variant::EXTENSION;
86
87#[cfg(test)] mod unit_variant_test;
88
89//---------------------------------------------------------------------------//
90//                              Enum & Structs
91//---------------------------------------------------------------------------//
92
93/// This holds an entire UnitVariant decoded in memory.
94#[derive(Eq, PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
95#[getset(get = "pub", get_mut = "pub", set = "pub")]
96pub struct UnitVariant {
97
98    /// Version of the UnitVariant.
99    version: u32,
100
101    /// Not sure what this is.
102    unknown_1: u32,
103
104    /// Variant categories.
105    categories: Vec<Category>,
106}
107
108/// This holds a variant category.
109#[derive(Eq, PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
110#[getset(get = "pub", get_mut = "pub", set = "pub")]
111pub struct Category {
112
113    /// Name of the category.
114    name: String,
115
116    /// Id of the category.
117    id: u64,
118
119    /// Variants of this category.
120    variants: Vec<Variant>,
121}
122
123/// This holds a `Variant` of a Category.
124#[derive(Eq, PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
125#[getset(get = "pub", get_mut = "pub", set = "pub")]
126pub struct Variant {
127
128    /// The file path (case insensitive) of the mesh file of this variant.
129    mesh_file: String,
130
131    /// The folder path (case insensitive) of the textures of this variant.
132    texture_folder: String,
133
134    /// Unknown value.
135    unknown_value: u16
136}
137
138//---------------------------------------------------------------------------//
139//                           Implementation of Text
140//---------------------------------------------------------------------------//
141
142/// Implementation of `UnitVariant`.
143impl UnitVariant {
144
145    /// This function tries to read the header of an UnitVariant from a raw data input.
146    ///
147    /// It returns, in this order: version, amount of categories, and unknown_1.
148    fn read_header<R: ReadBytes>(data: &mut R) -> Result<(u32, u32, u32)> {
149        let signature = data.read_string_u8(SIGNATURE.len())?;
150        if signature != SIGNATURE {
151            return Err(RLibError::DecodingUnitVariantNotAUnitVariant)
152        }
153
154        let version = data.read_u32()?;
155        let categories_count = data.read_u32()?;
156
157        // We don't use them, but it's good to know what they are.
158        let _categories_index = data.read_u32()?;
159        let _variants_index = data.read_u32()?;
160
161        // V2 has an extra number here. No idea what it is.
162        let unknown_1 = if version == 2 { data.read_u32()? } else { 0 };
163
164        Ok((version, categories_count, unknown_1))
165    }
166
167    /// This function returns the header binary lenght of the UnitVariant.
168    pub fn get_header_size(&self) -> u32 {
169        if self.version == 2 { HEADER_LENGTH_V2 } else { HEADER_LENGTH_V1 }
170    }
171}
172
173impl Decodeable for UnitVariant {
174
175    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
176        let (version, categories_count, unknown_1) = Self::read_header(data)?;
177
178        // Get the categories.
179        let mut categories = Vec::with_capacity(categories_count as usize);
180        for _ in 0..categories_count {
181            let name = data.read_string_u16_0padded(512)?;
182            let id = data.read_u64()?;
183            let variants_on_this_category = data.read_u32()?;
184            let _variants_before_this_category = data.read_u32()?;
185
186            let category = Category {
187                name,
188                id,
189                variants: Vec::with_capacity(variants_on_this_category as usize),
190            };
191
192            categories.push(category)
193        }
194
195        // Read the variants.
196        for category in &mut categories {
197            for _ in 0..category.variants.capacity() {
198                let mesh_file = data.read_string_u16_0padded(512)?;
199                let texture_folder = data.read_string_u16_0padded(512)?;
200                let unknown_value = data.read_u16()?;
201
202                category.variants.push(Variant {
203                    mesh_file,
204                    texture_folder,
205                    unknown_value
206                });
207            }
208        }
209
210        // Trigger an error if there's left data on the source.
211        check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
212
213        // If we've reached this, we've successfully decoded the entire UnitVariant.
214        Ok(Self {
215            version,
216            unknown_1,
217            categories
218        })
219    }
220}
221
222impl Encodeable for UnitVariant {
223
224    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
225
226        let mut encoded_variants = vec![];
227        let mut encoded_categories = vec![];
228
229        let mut variants_count = 0;
230        for category in &self.categories {
231            encoded_categories.write_string_u16_0padded(&category.name, 512, true)?;
232            encoded_categories.write_u64(category.id)?;
233            encoded_categories.write_u32(category.variants.len() as u32)?;
234            encoded_categories.write_u32(variants_count)?;
235            for variant in &category.variants {
236                encoded_variants.write_string_u16_0padded(&variant.mesh_file, 512, true)?;
237                encoded_variants.write_string_u16_0padded(&variant.texture_folder, 512, true)?;
238                encoded_variants.write_u16(variant.unknown_value)?;
239            }
240
241            variants_count += category.variants.len() as u32;
242        }
243
244        buffer.write_string_u8(SIGNATURE)?;
245        buffer.write_u32(self.version)?;
246        buffer.write_u32(self.categories.len() as u32)?;
247
248        buffer.write_u32(self.get_header_size())?;
249        buffer.write_u32(self.get_header_size() + encoded_categories.len() as u32)?;
250
251        if self.version == 2 {
252            buffer.write_u32(self.unknown_1)?;
253        }
254
255        buffer.write_all(&encoded_categories)?;
256        buffer.write_all(&encoded_variants)?;
257
258        Ok(())
259    }
260}