Skip to main content

rpfm_lib/files/rigidmodel/vertices/
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//! Vertex format definitions and I/O for RigidModel files.
12//!
13//! # Overview
14//!
15//! Vertices define the 3D geometry of meshes. RigidModel files support multiple vertex
16//! formats optimized for different use cases, with extensive use of data compression
17//! to reduce file size.
18//!
19//! # Vertex Formats
20//!
21//! | Format    | ID | Purpose                          | Bone Support |
22//! |-----------|---.|----------------------------------|--------------|
23//! | Static    | 0  | Standard non-animated geometry   | No           |
24//! | Collision | 1  | Simplified collision meshes      | No           |
25//! | Weighted  | 3  | Skeletal animation (2 bones)     | Yes (2)      |
26//! | Cinematic | 4  | High-quality cutscenes (4 bones) | Yes (4)      |
27//! | Grass     | 5  | Vegetation/grass rendering       | No           |
28//! | Tree      | 6  | Tree rendering, with wind data   | No           |
29//! | Billboard | 7  | Tree billboards                  | No           |
30//! | Rope      | 11 | Ropes (meshes without vertices)  | No           |
31//! | Uk8       | 8  | Unknown (seen in water planes)   | Unknown      |
32//! | Uk12      | 12 | Unknown (coral shrubs; campaign vegetation in v6) | Unknown |
33//! | ClothSim  | 25 | Cloth physics simulation         | Yes          |
34//!
35//! # Compression Techniques
36//!
37//! Vertices use multiple compression methods to reduce storage:
38//!
39//! ## Half-Precision Floats (f16)
40//! - Positions and UVs stored as 16-bit floats instead of 32-bit
41//! - Reduces size by 50% with minimal precision loss
42//!
43//! ## Normalized Vectors (u8)
44//! - Normals, tangents, bitangents stored as unsigned bytes
45//! - Converted from [-1.0, 1.0] range to [0, 255] range
46//! - Formula: `u8_value = (float_value + 1.0) * 127.5`
47//!
48//! ## Percentage Encoding (Bone Weights)
49//! - Bone weights stored as u8 representing percentages
50//! - Converted from [0.0, 1.0] to [0, 255]
51//! - Formula: `u8_value = float_value * 255.0`
52//!
53//! # Format-Specific Fields
54//!
55//! Different vertex formats read/write different subsets of vertex data:
56//!
57//! - **Static**: Position, UVs, normal, tangent, bitangent
58//! - **Weighted**: Static fields + bone indices + bone weights (2 bones)
59//! - **Cinematic**: Static fields + bone indices + bone weights (4 bones)
60//! - **Collision**: Position only (minimal data)
61//! - **Grass**: Position + UVs + normal + special grass data
62//! - **ClothSim**: Similar to weighted with cloth-specific data
63//!
64//! # Material-Dependent Variations
65//!
66//! The exact fields read also depend on the material type. For example:
67//! - RsTerrain materials read minimal vertex data
68//! - DefaultMaterial reads full vertex attributes
69//! - Cloth materials include additional physics data
70
71use getset::{Getters, MutGetters, Setters};
72use nalgebra::{Vector2, Vector4};
73use serde::{Deserialize, Serialize};
74
75use crate::binary::{ReadBytes, WriteBytes};
76use crate::error::{Result, RLibError};
77
78use super::materials::MaterialType;
79
80//---------------------------------------------------------------------------//
81//                              Enum & Structs
82//---------------------------------------------------------------------------//
83
84/// Vertex format identifier determining data layout and compression.
85///
86/// Different formats optimize for different use cases. The numeric value is stored
87/// as a u16 in the file format.
88#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize, Deserialize)]
89#[repr(u16)]
90pub enum VertexFormat {
91    /// Standard static geometry without animation.
92    #[default]
93    Static = 0,
94    /// Simplified collision mesh vertices (position only).
95    Collision = 1,
96    /// Skeletal animation vertices with bone weights (2 bones per vertex).
97    Weighted = 3,
98    /// High-quality cinematic vertices (4 bones per vertex).
99    Cinematic = 4,
100    /// Grass/vegetation vertices with special rendering data.
101    Grass = 5,
102    /// Tree vertices, with a second position and wind data.
103    Tree = 6,
104    /// Tree billboard vertices (position and UVs only).
105    Billboard = 7,
106    /// Format of rope meshes, which have no vertices of their own.
107    Rope = 11,
108    /// Unknown format (observed in glb_water_planes models).
109    Uk8 = 8,
110    /// Unknown format (observed in sea_coral_shrubs_02 models).
111    Uk12 = 12,
112    /// Cloth simulation vertices with physics data.
113    ClothSim = 25,
114}
115
116/// Universal vertex structure containing all possible vertex attributes.
117///
118/// Not all fields are used by all vertex formats - the format and material type
119/// determine which fields contain valid data. Fields are stored with various
120/// compression techniques in the binary format.
121///
122/// # Field Usage by Format
123///
124/// - **Static**: position, UVs, normal, tangent, bitangent
125/// - **Weighted**: Static fields + bone_indices (2) + weights (2)
126/// - **Cinematic**: Static fields + bone_indices (4) + weights (4)
127/// - **Collision**: position only
128/// - **Grass**: position, UVs, normal, + grass-specific data
129/// - **ClothSim**: Similar to Weighted with cloth data
130///
131/// # Compression Notes
132///
133/// When reading from file:
134/// - Position is often stored as Vector4 of f16 (half-precision)
135/// - UVs stored as f16
136/// - Normals/tangents/bitangents stored as u8 normalized vectors
137/// - Bone weights stored as u8 percentages
138#[derive(Clone, Debug, Default, PartialEq, Getters, MutGetters, Setters, Serialize, Deserialize)]
139#[getset(get = "pub", get_mut = "pub", set = "pub")]
140pub struct Vertex {
141
142    /// 3D position of the vertex (x, y, z, w).
143    /// Often stored as f16 in file, expanded to f32 in memory.
144    /// Terrain blocks (RsTerrain, and up to version 6 WeightedTextureBlend and ProjectedDecalV4): w is the vertex's alpha (0 on the
145    /// edges and the skirt), not a scale.
146    /// River blocks (RsRiver, RsRiverDeprecated): w is one of the river's parameters (see `normal`).
147    position: Vector4<f32>,
148
149    /// Primary texture UV coordinates (u, v).
150    /// Often stored as f16 in file, expanded to f32 in memory.
151    texture_coordinate: Vector2<f32>,
152
153    /// Secondary texture UV coordinates (u, v) for multi-texturing.
154    /// Often stored as f16 in file, expanded to f32 in memory.
155    ///
156    /// In tree vertices these are not uvs but the LOD blend weights: the game's tree vertex shaders (rigidbranchcommon_v3,
157    /// rigidleafcommon_v3) draw `x * position + y * position2`. Full detail vertices have (0, 1).
158    texture_coordinate2: Vector2<f32>,
159
160    /// Vertex normal vector for lighting calculations (x, y, z, w).
161    /// Often stored as u8 normalized in file, expanded to f32 in memory.
162    /// River blocks (RsRiver, RsRiverDeprecated): not a normal. With `position.w` it holds the river's parameters: flow speed, width,
163    /// distance along, alpha fade and position across (RsRiver's order; RsRiverDeprecated has them in another order).
164    normal: Vector4<f32>,
165
166    /// Tangent vector for normal mapping (x, y, z, w).
167    /// Often stored as u8 normalized in file, expanded to f32 in memory.
168    tangent: Vector4<f32>,
169
170    /// Bitangent vector for normal mapping (x, y, z, w).
171    /// Often stored as u8 normalized in file, expanded to f32 in memory.
172    bitangent: Vector4<f32>,
173
174    /// Vertex color (r, g, b, a). Typically unused in modern rendering (textures used instead).
175    color: Vector4<f32>,
176
177    /// Bone indices for skeletal animation (up to 4 bones).
178    /// For Weighted format: only first 2 are used.
179    /// For Cinematic format: all 4 are used.
180    bone_indices: Vector4<u8>,
181
182    /// Bone weights for skeletal animation (up to 4 weights), as stored: u8 percentages in the file, expanded to f32 in memory.
183    /// Weighted vertices store one weight that counts: see [`Vertex::skinning_weights`] for the weights the game skins with.
184    weights: Vector4<f32>,
185
186    /// Four bytes as stored, whose meaning depends on the layout. DefaultMaterial layout: the vertex colour (BGRA; in cloth
187    /// simulation vertices the alpha is the particle's weight, 0 pinned and 255 free). TextureComboVertexWind: the wind weights.
188    /// CustomTerrain: the normal's bytes (z, y, x) and the blend weight in the alpha (0 on the plateau, 255 on the faces).
189    /// Weighted and Cinematic (version 8+), Grass, Uk12, Uk27: unknown.
190    uk_1: Vector4<u8>,
191
192    /// Second position of the vertex (x, y, z, w). Seen in bow wave vertices and in tree vertices, where it's the LOD position:
193    /// the position the vertex is drawn at, blended with `position` by the weights in `texture_coordinate2` (full detail vertices
194    /// keep `position` at the origin and are drawn entirely at this one).
195    position2: Vector4<f32>,
196
197    /// Unknown pair of values of tree vertices. Small integers stored as f16. The game's tree shaders don't read it.
198    uk_2: Vector2<f32>,
199
200    /// Tree vertices: the vertex colour (r, g, b, values up to 2) and the wind weight (a: how much the vertex sways). Stored as f16.
201    tree_colour_wind: Vector4<f32>,
202
203    /// Unknown value of bow wave vertices, 0 or 1.
204    uk_4: f32,
205}
206
207//---------------------------------------------------------------------------//
208//                            Implementation
209//---------------------------------------------------------------------------//
210
211impl TryFrom<u16> for VertexFormat {
212    type Error = RLibError;
213    fn try_from(value: u16) -> Result<Self> {
214        match value {
215            _ if value == Self::Static as u16 => Ok(Self::Static),
216            _ if value == Self::Collision as u16 => Ok(Self::Collision),
217            _ if value == Self::Weighted as u16 => Ok(Self::Weighted),
218            _ if value == Self::Cinematic as u16 => Ok(Self::Cinematic),
219            _ if value == Self::Grass as u16 => Ok(Self::Grass),
220            _ if value == Self::Tree as u16 => Ok(Self::Tree),
221            _ if value == Self::Billboard as u16 => Ok(Self::Billboard),
222            _ if value == Self::Rope as u16 => Ok(Self::Rope),
223            _ if value == Self::Uk8 as u16 => Ok(Self::Uk8),
224            _ if value == Self::Uk12 as u16 => Ok(Self::Uk12),
225            _ if value == Self::ClothSim as u16 => Ok(Self::ClothSim),
226            _ => Err(RLibError::DecodingRigidModelUnknownVertexFormat(value))
227        }
228    }
229}
230
231impl From<VertexFormat> for u16 {
232    fn from(value: VertexFormat) -> u16 {
233        value as u16
234    }
235}
236
237impl Vertex {
238
239    /// Returns the bone weights the game's vertex shaders skin this vertex with.
240    ///
241    /// A Weighted (2 bone) vertex stores one weight that counts: the shader gives the first bone `weights.x` and the second
242    /// `1 - weights.x`, never reading the second stored weight (0 in the games' own files). Every other format's weights are
243    /// returned as stored.
244    ///
245    /// # Arguments
246    ///
247    /// * `vtype` - Vertex format of the mesh the vertex belongs to.
248    pub fn skinning_weights(&self, vtype: VertexFormat) -> Vector4<f32> {
249        match vtype {
250            VertexFormat::Weighted => Vector4::new(self.weights.x, 1.0 - self.weights.x, 0.0, 0.0),
251            _ => self.weights,
252        }
253    }
254
255    /// Reads a vertex from binary data based on the vertex format and material type.
256    ///
257    /// Different combinations of vertex format and material type have different binary
258    /// layouts. This function dispatches to the appropriate reading logic based on
259    /// the format/material combination.
260    ///
261    /// # Arguments
262    ///
263    /// * `data` - Binary data source.
264    /// * `version` - RigidModel version (affects layout for some formats).
265    /// * `vtype` - Vertex format specifying the data layout.
266    /// * `mtype` - Material type (affects layout for static vertices).
267    ///
268    /// # Errors
269    ///
270    /// Returns an error if:
271    /// - The vertex format is unknown ([`RLibError::DecodingRigidModelUnknownVertexFormat`])
272    /// - The vertex format is unsupported for the material type
273    ///   ([`RLibError::DecodingRigidModelUnsupportedVertexFormatForMaterial`])
274    pub fn read<R: ReadBytes>(data: &mut R, version: u32, vtype: VertexFormat, mtype: MaterialType) -> Result<Self> {
275        let mut v = Self::default();
276        match vtype {
277            VertexFormat::Static => match static_layout(version, mtype) {
278                MaterialType::TiledDirtmap |
279                MaterialType::ShipAmbientmap |
280                MaterialType::Decal |
281                MaterialType::DecalDirtmap |
282                MaterialType::Dirtmap |
283                MaterialType::Cloth |
284                MaterialType::Unlit |
285                MaterialType::WaterDisplaceVolume |
286                MaterialType::Uk54 |
287                MaterialType::DefaultMaterial => {
288                    v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
289                    v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
290                    v.texture_coordinate2 = data.read_vector_2_f32_from_vector_2_f16()?;
291                    v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
292                    v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
293                    v.bitangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
294                    v.uk_1 = data.read_vector_4_u8()?;
295                },
296                // Terrain vertices: x, height, z and an alpha (0 on the edges and the skirt), then the normal. The alpha is no
297                // scale: the game places each vertex at its raw x, height, z.
298                MaterialType::RsTerrain => {
299                    v.position = data.read_vector_4_f32_from_vector_4_f16()?;
300                    v.normal = data.read_vector_4_f32_from_vector_4_f16()?;
301                },
302                // Up to version 6 this type is a terrain block (RS_TERRAIN_depreciated2), read as RsTerrain's.
303                MaterialType::WeightedTextureBlend if version <= 6 => {
304                    v.position = data.read_vector_4_f32_from_vector_4_f16()?;
305                    v.normal = data.read_vector_4_f32_from_vector_4_f16()?;
306                },
307                MaterialType::WeightedTextureBlend => {
308                    v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
309                    v.normal = data.read_vector_4_f32_normal_from_vector_4_f16()?;
310                },
311                // The terrain block BOB writes: x, height, z and an alpha, as RsTerrain's.
312                MaterialType::ProjectedDecalV4 => {
313                    v.position = data.read_vector_4_f32_from_vector_4_f16()?;
314                },
315                MaterialType::RsRiverDeprecated |
316                MaterialType::RsRiver => {
317                    v.position = data.read_vector_4_f32()?;
318                    v.normal = data.read_vector_4_f32()?;
319                },
320                MaterialType::ProjectedDecal |
321                MaterialType::ProjectedDecalV2 |
322                MaterialType::ProjectedDecalV3 => {
323                    v.position = data.read_vector_4_f32()?;
324                },
325                // These store no vertex data: their indices point to the vertices of another mesh.
326                MaterialType::StaticPointLight |
327                MaterialType::Uk56 |
328                MaterialType::Uk57 => {},
329                MaterialType::TextureCombo |
330                MaterialType::TextureComboVertexWind => {
331                    v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
332                    v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
333                    v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
334                    v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
335                    v.bitangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
336                    v.uk_1 = data.read_vector_4_u8()?;
337                },
338                MaterialType::Uk27 => {
339                    v.position = data.read_vector_4_f32_from_vec_3_f32()?;
340                    v.texture_coordinate = Vector2::new(data.read_f32()?, data.read_f32()?);
341                    v.texture_coordinate2 = Vector2::new(data.read_f32()?, data.read_f32()?);
342                    v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
343                    v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
344                    v.bitangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
345                    v.uk_1 = data.read_vector_4_u8()?;
346                },
347                MaterialType::DebugGeometry => {
348                    v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
349                    v.normal = data.read_vector_4_f32_normal_from_vector_4_f16()?;
350                    v.color = data.read_vector_4_f32_pct_from_vector_4_u8()?;
351                },
352                MaterialType::BowWave => {
353                    v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
354                    v.position2 = data.read_vector_4_f32_normal_from_vector_4_f16()?;
355                    v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
356                    v.uk_4 = data.read_f32()?;
357                },
358                // Up to version 6 the last 8 bytes are four f16: the uv, then two the shader passes on (0 in every file).
359                MaterialType::CustomTerrain if version <= 6 => {
360                    v.position = data.read_vector_4_f32()?;
361                    v.uk_1 = data.read_vector_4_u8()?;
362                    v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
363                    v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
364                    v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
365                    v.texture_coordinate2 = data.read_vector_2_f32_from_vector_2_f16()?;
366                },
367                MaterialType::CustomTerrain => {
368                    v.position = data.read_vector_4_f32()?;
369                    v.uk_1 = data.read_vector_4_u8()?;
370                    v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
371                    v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
372                    v.texture_coordinate = Vector2::new(data.read_f32()?, data.read_f32()?);
373                },
374                MaterialType::TerrainBlend => {
375                    v.position = data.read_vector_4_f32()?;
376                    v.normal = data.read_vector_4_f32()?;
377                },
378                MaterialType::AlphaBlend => {
379                    v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
380                    v.texture_coordinate2 = data.read_vector_2_f32_from_vector_2_f16()?;
381                }
382                _ => return Err(RLibError::DecodingRigidModelUnsupportedVertexFormatForMaterial(vtype.into(), mtype.into()))
383            },
384
385            VertexFormat::Collision => {
386                v.position = data.read_vector_4_f32_from_vec_3_f32()?;
387                v.normal = data.read_vector_4_f32_from_vec_3_f32()?;
388            }
389
390            VertexFormat::Weighted => {
391                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
392
393                let bone_indices = data.read_vector_2_u8()?;
394                v.bone_indices = Vector4::new(bone_indices.x, bone_indices.y, 0, 0);
395
396                let weights = data.read_vector_2_f32_pct_from_vector_2_u8()?;
397                v.weights = Vector4::new(weights.x, weights.y, 0.0, 0.0);
398
399                v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
400                v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
401                v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
402                v.bitangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
403
404                if version >= 8 {
405                    v.uk_1 = data.read_vector_4_u8()?;
406                }
407            }
408            VertexFormat::Cinematic => {
409                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
410
411                // w is not used in this one.
412                v.bone_indices = data.read_vector_4_u8()?;
413                v.weights = data.read_vector_4_f32_pct_from_vector_4_u8()?;
414                v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
415                v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
416                v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
417                v.bitangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
418
419                if version >= 8 {
420                    v.uk_1 = data.read_vector_4_u8()?;
421                }
422            }
423            VertexFormat::Grass => {
424                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
425                v.texture_coordinate = Vector2::new(data.read_f32()?, data.read_f32()?);
426                v.normal = data.read_vector_4_f32_normal_from_vector_4_u8()?;
427                v.tangent = data.read_vector_4_f32_normal_from_vector_4_u8()?;
428                v.uk_1 = data.read_vector_4_u8()?;
429            }
430            VertexFormat::Tree => {
431                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
432                v.position2 = data.read_vector_4_f32_normal_from_vector_4_f16()?;
433                v.normal = data.read_vector_4_f32_normal_from_vector_4_f16()?;
434                v.tangent = data.read_vector_4_f32_normal_from_vector_4_f16()?;
435                v.bitangent = data.read_vector_4_f32_normal_from_vector_4_f16()?;
436                v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
437                v.texture_coordinate2 = data.read_vector_2_f32_from_vector_2_f16()?;
438                v.uk_2 = data.read_vector_2_f32_from_vector_2_f16()?;
439                v.tree_colour_wind = data.read_vector_4_f32_from_vector_4_f16()?;
440            }
441            VertexFormat::Billboard |
442            VertexFormat::Uk8 => {
443                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
444                v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
445            }
446            VertexFormat::Uk12 if version <= 6 => {
447                v.position = data.read_vector_4_f32_from_vector_4_f16()?;
448                v.normal = data.read_vector_4_f32_from_vector_4_f16()?;
449            }
450            VertexFormat::Uk12 => {
451                v.position = data.read_vector_4_f32_normal_from_vector_4_f16()?;
452                v.texture_coordinate = data.read_vector_2_f32_from_vector_2_f16()?;
453                v.texture_coordinate2 = data.read_vector_2_f32_from_vector_2_f16()?;
454                v.uk_1 = data.read_vector_4_u8()?;
455            }
456            _ => return Err(RLibError::DecodingRigidModelUnknownVertexFormat(vtype.into()))
457        }
458
459        Ok(v)
460    }
461
462    /// Writes a vertex to binary data based on the vertex format and material type.
463    ///
464    /// Different combinations of vertex format and material type have different binary
465    /// layouts. This function dispatches to the appropriate writing logic based on
466    /// the format/material combination.
467    ///
468    /// # Arguments
469    ///
470    /// * `data` - Output buffer.
471    /// * `version` - RigidModel version (affects layout for some formats).
472    /// * `vtype` - Vertex format specifying the data layout.
473    /// * `mtype` - Material type (affects layout for static vertices).
474    ///
475    /// # Errors
476    ///
477    /// Returns an error if:
478    /// - The vertex format is unknown ([`RLibError::DecodingRigidModelUnknownVertexFormat`])
479    /// - The vertex format is unsupported for the material type
480    ///   ([`RLibError::DecodingRigidModelUnsupportedVertexFormatForMaterial`])
481    pub fn write<W: WriteBytes>(&self, data: &mut W, version: u32, vtype: VertexFormat, mtype: MaterialType) -> Result<()> {
482        match vtype {
483            VertexFormat::Static => match static_layout(version, mtype) {
484                MaterialType::TiledDirtmap |
485                MaterialType::ShipAmbientmap |
486                MaterialType::Decal |
487                MaterialType::DecalDirtmap |
488                MaterialType::Dirtmap |
489                MaterialType::Cloth |
490                MaterialType::Unlit |
491                MaterialType::WaterDisplaceVolume |
492                MaterialType::Uk54 |
493                MaterialType::DefaultMaterial => {
494                    data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
495                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
496                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate2)?;
497                    data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
498                    data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
499                    data.write_vector_4_f32_normal_as_vector_4_u8(self.bitangent)?;
500
501                    // Color? Causes difference when processing if treated as color.
502                    data.write_vector_4_u8(self.uk_1)?;
503                }
504                MaterialType::RsTerrain => {
505                    data.write_vector_4_f32_as_vector_4_f16(*self.position())?;
506                    data.write_vector_4_f32_as_vector_4_f16(*self.normal())?;
507                }
508                MaterialType::WeightedTextureBlend if version <= 6 => {
509                    data.write_vector_4_f32_as_vector_4_f16(*self.position())?;
510                    data.write_vector_4_f32_as_vector_4_f16(*self.normal())?;
511                }
512                MaterialType::WeightedTextureBlend => {
513                    data.write_vector_4_f32_normal_as_vector_4_f16(*self.position())?;
514                    data.write_vector_4_f32_normal_as_vector_4_f16(*self.normal())?;
515                }
516                MaterialType::ProjectedDecalV4 => {
517                    data.write_vector_4_f32_as_vector_4_f16(*self.position())?;
518                }
519                MaterialType::RsRiverDeprecated |
520                MaterialType::RsRiver => {
521                    data.write_vector_4_f32(*self.position())?;
522                    data.write_vector_4_f32(*self.normal())?;
523                }
524                MaterialType::ProjectedDecal |
525                MaterialType::ProjectedDecalV2 |
526                MaterialType::ProjectedDecalV3 => {
527                    data.write_vector_4_f32(*self.position())?;
528                }
529                MaterialType::StaticPointLight |
530                MaterialType::Uk56 |
531                MaterialType::Uk57 => {}
532                MaterialType::TextureCombo |
533                MaterialType::TextureComboVertexWind => {
534                    data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
535                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
536                    data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
537                    data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
538                    data.write_vector_4_f32_normal_as_vector_4_u8(self.bitangent)?;
539                    data.write_vector_4_u8(self.uk_1)?;
540                }
541                MaterialType::Uk27 => {
542                    data.write_vector_4_f32_to_vector_3_f32(self.position)?;
543                    data.write_f32(self.texture_coordinate.x)?;
544                    data.write_f32(self.texture_coordinate.y)?;
545                    data.write_f32(self.texture_coordinate2.x)?;
546                    data.write_f32(self.texture_coordinate2.y)?;
547                    data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
548                    data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
549                    data.write_vector_4_f32_normal_as_vector_4_u8(self.bitangent)?;
550                    data.write_vector_4_u8(self.uk_1)?;
551                }
552                MaterialType::DebugGeometry => {
553                    data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
554                    data.write_vector_4_f32_normal_as_vector_4_f16(self.normal)?;
555                    data.write_vector_4_f32_pct_as_vector_4_u8(self.color)?;
556                }
557                MaterialType::BowWave => {
558                    data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
559                    data.write_vector_4_f32_normal_as_vector_4_f16(self.position2)?;
560                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
561                    data.write_f32(self.uk_4)?;
562                }
563                MaterialType::CustomTerrain if version <= 6 => {
564                    data.write_vector_4_f32(self.position)?;
565                    data.write_vector_4_u8(self.uk_1)?;
566                    data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
567                    data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
568                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
569                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate2)?;
570                }
571                MaterialType::CustomTerrain => {
572                    data.write_vector_4_f32(self.position)?;
573                    data.write_vector_4_u8(self.uk_1)?;
574                    data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
575                    data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
576                    data.write_f32(self.texture_coordinate.x)?;
577                    data.write_f32(self.texture_coordinate.y)?;
578                }
579                MaterialType::TerrainBlend => {
580                    data.write_vector_4_f32(*self.position())?;
581                    data.write_vector_4_f32(*self.normal())?;
582                }
583                MaterialType::AlphaBlend => {
584                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
585                    data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate2)?;
586                }
587                _ => return Err(RLibError::DecodingRigidModelUnsupportedVertexFormatForMaterial(vtype.into(), mtype.into()))
588            },
589
590            VertexFormat::Collision => {
591                data.write_vector_4_f32_to_vector_3_f32(self.position)?;
592                data.write_vector_4_f32_to_vector_3_f32(self.normal)?;
593            }
594
595            VertexFormat::Weighted => {
596                data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
597                data.write_vector_2_u8(Vector2::new(self.bone_indices.x, self.bone_indices.y))?;
598                data.write_vector_2_f32_pct_as_vector_2_u8(Vector2::new(self.weights.x, self.weights.y))?;
599                data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
600                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
601                data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
602                data.write_vector_4_f32_normal_as_vector_4_u8(self.bitangent)?;
603
604                if version >= 8 {
605                    data.write_vector_4_u8(self.uk_1)?;
606                }
607            }
608            VertexFormat::Cinematic => {
609                data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
610                data.write_vector_4_u8(self.bone_indices)?;
611                data.write_vector_4_f32_pct_as_vector_4_u8(self.weights)?;
612                data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
613                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
614                data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
615                data.write_vector_4_f32_normal_as_vector_4_u8(self.bitangent)?;
616
617                if version >= 8 {
618                    data.write_vector_4_u8(self.uk_1)?;
619                }
620            }
621            VertexFormat::Grass => {
622                data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
623                data.write_f32(self.texture_coordinate.x)?;
624                data.write_f32(self.texture_coordinate.y)?;
625                data.write_vector_4_f32_normal_as_vector_4_u8(self.normal)?;
626                data.write_vector_4_f32_normal_as_vector_4_u8(self.tangent)?;
627                data.write_vector_4_u8(self.uk_1)?;
628            }
629            VertexFormat::Tree => {
630                data.write_vector_4_f32_normal_as_vector_4_f16(self.position)?;
631                data.write_vector_4_f32_normal_as_vector_4_f16(self.position2)?;
632                data.write_vector_4_f32_normal_as_vector_4_f16(self.normal)?;
633                data.write_vector_4_f32_normal_as_vector_4_f16(self.tangent)?;
634                data.write_vector_4_f32_normal_as_vector_4_f16(self.bitangent)?;
635                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
636                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate2)?;
637                data.write_vector_2_f32_as_vector_2_f16(self.uk_2)?;
638                data.write_vector_4_f32_as_vector_4_f16(self.tree_colour_wind)?;
639            }
640            VertexFormat::Billboard |
641            VertexFormat::Uk8 => {
642                data.write_vector_4_f32_normal_as_vector_4_f16(*self.position())?;
643                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
644            }
645            VertexFormat::Uk12 if version <= 6 => {
646                data.write_vector_4_f32_as_vector_4_f16(self.position)?;
647                data.write_vector_4_f32_as_vector_4_f16(self.normal)?;
648            }
649            VertexFormat::Uk12 => {
650                data.write_vector_4_f32_normal_as_vector_4_f16(*self.position())?;
651                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate)?;
652                data.write_vector_2_f32_as_vector_2_f16(self.texture_coordinate2)?;
653                data.write_vector_4_u8(self.uk_1)?;
654            }
655            _ => return Err(RLibError::DecodingRigidModelUnknownVertexFormat(vtype.into()))
656        }
657
658        Ok(())
659    }
660}
661/// The material whose static vertex layout a material uses.
662///
663/// Up to version 6 (Attila), TerrainBlend vertices are laid out like DefaultMaterial ones (f16 position, two f16 uvs, u8 normal, tangent,
664/// bitangent and colour): read as two f32 vectors instead, the position's w (f16 1.0) shows up in the high half of y, and x reaches
665/// thousands. Later versions keep the f32 layout.
666fn static_layout(version: u32, mtype: MaterialType) -> MaterialType {
667    match mtype {
668        MaterialType::TerrainBlend if version <= 6 => MaterialType::DefaultMaterial,
669        _ => mtype,
670    }
671}
672
673/*
674/// Util to swap the x and z coordinates of a vector.
675fn swap_xz(input: &Vector4<f32>) -> Vector4<f32> {
676    let mut i = *input;
677    i.swap_rows(0, 2);
678    i
679}*/