Skip to main content

rpfm_lib/files/cs2_parsed/
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//! CS2 Parsed file format support.
12//!
13//! CS2 Parsed files (`.cs2.parsed`) define gameplay logic and interaction data for 3D
14//! building models in Total War games. These files contain information about unit
15//! placement, pathfinding, collision, defense positions, and various building-specific
16//! behaviors.
17//!
18//! # File Format
19//!
20//! CS2 Parsed files are binary files containing:
21//! - Version header
22//! - UI flag position for minimap display
23//! - Building pieces with destruction states
24//! - Gameplay logic: platforms, pipes, gates, EF lines, etc.
25//! - Legacy collision data (moved to separate `.cs2.collision` files in newer games)
26//! - Projectile emitters (moved to map data in newer games)
27//!
28//! # Supported Versions
29//!
30//! - **Version 0**: Legacy format (Empire/Napoleon)
31//! - **Version 8**: Legacy format
32//! - **Version 9**: Legacy format
33//! - **Version 10**: Legacy format
34//! - **Version 11**: Legacy format
35//! - **Version 12**: Legacy format
36//! - **Version 13**: Legacy format
37//! - **Version 18**: Older format (Three Kingdoms)
38//! - **Version 20**: Older format (Troy/Warhammer II)
39//! - **Version 21**: Current format (Warhammer III)
40//!
41//! # Key Components
42//!
43//! ## Platforms
44//! Define walkable surfaces where units can stand and fight.
45//!
46//! ## Pipes
47//! Define paths for unit movement between platforms (stairs, ladders, doors, etc.).
48//!
49//! ## EF Lines (Entity Formation Lines)
50//! Define positions where units form up for specific actions (firing lines, boarding
51//! positions, officer spawn points, etc.).
52//!
53//! ## Gates
54//! Define entrance/exit collision for wall gates.
55//!
56//! ## Docking Lines
57//! Define where siege equipment can attach to walls.
58//!
59//! # Usage
60//!
61//! ```rust,ignore
62//! use rpfm_lib::files::cs2_parsed::Cs2Parsed;
63//! use rpfm_lib::files::Decodeable;
64//!
65//! // Decode from binary data
66//! let parsed = Cs2Parsed::decode(&mut data, &None)?;
67//!
68//! // Access building pieces
69//! for piece in parsed.pieces() {
70//!     println!("Piece: {}", piece.name());
71//!
72//!     // Access destructs (damage states)
73//!     for destruct in piece.destructs() {
74//!         println!("  Destruct: {} ({} platforms, {} pipes)",
75//!             destruct.name(),
76//!             destruct.platforms().len(),
77//!             destruct.pipes().len()
78//!         );
79//!     }
80//! }
81//! ```
82//!
83//! # File Location
84//!
85//! These files are typically found at:
86//! - `rigidmodels/buildings/*/*.cs2.parsed`
87
88use getset::*;
89use serde_derive::{Serialize, Deserialize};
90
91use crate::error::{Result, RLibError};
92use crate::binary::{ReadBytes, WriteBytes};
93use crate::files::{cs2_collision::Collision3d, DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
94use crate::files::bmd::common::*;
95use crate::games::GameInfo;
96use crate::utils::check_size_mismatch;
97
98/// File extension for CS2 Parsed files.
99pub const EXTENSION: &str = ".cs2.parsed";
100
101#[cfg(test)] mod cs2_parsed_test;
102
103mod versions;
104
105//---------------------------------------------------------------------------//
106//                              Enum & Structs
107//---------------------------------------------------------------------------//
108
109/// Represents a CS2 Parsed file decoded in memory.
110///
111/// Contains all gameplay logic data for a building model, including unit placement,
112/// pathfinding, collision, and various building-specific behaviors.
113///
114/// # Fields
115///
116/// * `version` - File format version (0, 8-13, 18, 20, or 21)
117/// * `ui_flag` - Flag position shown on minimap
118/// * `bounding_box` - Overall bounds (not present in v20 onwards)
119/// * `int_1` - Unknown field
120/// * `pieces` - List of building pieces with destruction states
121///
122/// # Examples
123///
124/// ```rust,ignore
125/// let parsed = Cs2Parsed::decode(&mut data, &None)?;
126/// println!("Version: {}", parsed.version());
127/// println!("Pieces: {}", parsed.pieces().len());
128/// ```
129#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
130#[getset(get = "pub", get_mut = "pub", set = "pub")]
131pub struct Cs2Parsed {
132    /// File format version number.
133    version: u32,
134
135    /// Flag position for minimap display.
136    ui_flag: UiFlag,
137
138    /// Overall bounding box (not present in v20 onwards).
139    bounding_box: Cube,
140
141    /// Unknown field.
142    int_1: i32,
143
144    /// List of building pieces.
145    pieces: Vec<Piece>,
146}
147
148/// A piece of a building model with multiple destruction states.
149///
150/// Buildings are composed of multiple pieces, each with one or more destruction
151/// states (destructs). As a building takes damage, it transitions between these states.
152///
153/// # Fields
154///
155/// * `name` - Name identifier for this piece
156/// * `node_name` - Scene node name for attachment
157/// * `node_transform` - Transformation matrix for positioning
158/// * `int_3` - Unknown field
159/// * `int_4` - Unknown field (only in v21)
160/// * `destructs` - List of destruction states for this piece
161/// * `f_6` - Unknown field
162///
163/// # Examples
164///
165/// ```rust,ignore
166/// for piece in parsed.pieces() {
167///     println!("Piece: {} ({} destructs)", piece.name(), piece.destructs().len());
168/// }
169/// ```
170#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
171#[getset(get = "pub", get_mut = "pub", set = "pub")]
172pub struct Piece {
173    /// Name identifier for this piece.
174    name: String,
175
176    /// Scene node name for attachment.
177    node_name: String,
178
179    /// Transformation matrix for positioning.
180    node_transform: Transform4x4,
181
182    /// Unknown field.
183    int_3: i32,
184
185    /// Unknown field (only in v21).
186    int_4: i32,
187
188    /// List of destruction states for this piece.
189    destructs: Vec<Destruct>,
190
191    /// Unknown field.
192    f_6: f32,
193}
194
195/// A destruction state of a building piece.
196///
197/// Each piece can have multiple destructs representing different damage states.
198/// Destructs contain all the gameplay logic for that damage state: platforms,
199/// pipes, gates, EF lines, collision, etc.
200///
201/// # Fields
202///
203/// * `name` - Name identifier for this destruction state
204/// * `index` - Index of this destruct
205/// * `collision_3d` - Collision mesh (legacy, moved to `.cs2.collision` in newer games)
206/// * `collision_outlines` - 2D collision outlines
207/// * `windows` - Number of window positions
208/// * `doors` - Number of door positions
209/// * `gates` - Gate collision data for wall gates
210/// * `pipes` - Unit movement paths (stairs, ladders, doors, etc.)
211/// * `footprints` - Footprint rings of the level, beside its collision outlines (x and z)
212/// * `platforms` - Walkable surfaces for units
213/// * `uk_2` - Unknown field
214/// * `bounding_box` - Bounding box for this destruct
215/// * `cannon_emitters` - Projectile emitter count for cannons (legacy)
216/// * `arrow_emitters` - Projectile emitters for arrows (legacy)
217/// * `docking_points` - Number of docking points
218/// * `soft_collisions` - Soft collision data
219/// * `uk_7` - Unknown field (v18 and later)
220/// * `vfx_emitters` - VFX the destruct always plays (v13 and before)
221/// * `file_refs` - Attached model references (e.g., torches)
222/// * `ef_lines` - Entity Formation lines for unit positioning
223/// * `docking_lines` - Lines where siege equipment can attach
224/// * `f_1` - Unknown field
225/// * `action_vfx` - VFX for actions
226/// * `action_vfx_attachments` - VFX attachment points
227/// * `action_vfx_triangles` - Per `action_vfx` entry, the hull triangles it belongs to
228/// * `bin_data_2` - Unknown binary data (present in some Three Kingdoms gates)
229///
230/// # Examples
231///
232/// ```rust,ignore
233/// for destruct in piece.destructs() {
234///     println!("Destruct '{}': {} platforms, {} pipes",
235///         destruct.name(),
236///         destruct.platforms().len(),
237///         destruct.pipes().len()
238///     );
239/// }
240/// ```
241#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
242#[getset(get = "pub", get_mut = "pub", set = "pub")]
243pub struct Destruct {
244    /// Name identifier for this destruction state.
245    name: String,
246
247    /// Index of this destruct.
248    index: u32,
249
250    /// Collision mesh (legacy, moved to separate `.cs2.collision` files in newer games).
251    collision_3d: Collision3d,
252
253    /// 2D collision outlines.
254    collision_outlines: Vec<CollisionOutline>,
255
256    /// Number of window positions.
257    windows: i32,
258
259    /// Number of door positions.
260    doors: i32,
261
262    /// Gate collision data for wall gates.
263    gates: Vec<Gate>,
264
265    /// Unit movement paths between platforms.
266    pipes: Vec<Pipe>,
267
268    /// Footprint rings of the level, beside its collision outlines: the ground it covers (x and z). Drawn as an orange line in Terry.
269    footprints: Vec<Vec<FootprintCorner>>,
270
271    /// Walkable platform surfaces.
272    platforms: Vec<Platform>,
273
274    /// Unknown field.
275    uk_2: i32,
276
277    /// Bounding box for this destruct.
278    bounding_box: Cube,
279
280    /// Projectile emitter count for cannons (legacy, moved to map in newer games).
281    cannon_emitters: i32,
282
283    /// Projectile emitters for arrows (legacy, moved to map in newer games).
284    arrow_emitters: Vec<ProjectileEmitter>,
285
286    /// Number of docking points.
287    docking_points: i32,
288
289    /// Soft collision data.
290    soft_collisions: Vec<SoftCollisions>,
291
292    /// Unknown field (v18 and later; not checked whether it is the count of `vfx_emitters` there too).
293    uk_7: i32,
294
295    /// VFX the destruct always plays (v13 and before). In Attila, the name of the effect is the key without its first three and its last
296    /// `_` tokens: `piece01_destruct01_emitter_action_vfx_torch_fire_small_01` plays `action_vfx_torch_fire_small`. No file shipped with
297    /// the game has any, but they play in game.
298    vfx_emitters: Vec<Vfx>,
299
300    /// Attached model references (e.g., torches).
301    file_refs: Vec<FileRef>,
302
303    /// Entity Formation lines for unit positioning.
304    ef_lines: Vec<EFLine>,
305
306    /// Lines where siege equipment can attach.
307    docking_lines: Vec<DockingLine>,
308
309    /// Unknown field.
310    f_1: f32,
311
312    /// VFX for actions.
313    action_vfx: Vec<Vfx>,
314
315    /// VFX attachment points.
316    action_vfx_attachments: Vec<Vfx>,
317
318    /// Lists of indices into the level's `collision_3d` triangles, as many lists as `action_vfx` entries, together covering every
319    /// hull triangle once: probably which effect a hit on that part of the hull plays (the pairing by index is not checked in game).
320    action_vfx_triangles: Vec<Vec<i16>>,
321
322    /// Unknown binary data (present in some Three Kingdoms gates).
323    bin_data_2: Vec<Vec<i16>>,
324}
325
326/// UI flag position shown on the minimap.
327///
328/// Defines where the building's flag icon appears on the tactical map.
329///
330/// # Fields
331///
332/// * `name` - Name identifier for the flag
333/// * `transform` - Transformation matrix for flag position and orientation
334#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
335#[getset(get = "pub", get_mut = "pub", set = "pub")]
336pub struct UiFlag {
337    /// Name identifier for the flag.
338    name: String,
339
340    /// Transformation matrix for flag position.
341    transform: Transform4x4,
342}
343
344/// Gate collision data for wall gates.
345///
346/// Defines the collision geometry for gates where units enter and exit cities.
347/// Contains two collision meshes, possibly for open and closed states.
348///
349/// # Fields
350///
351/// * `collision_1` - First collision mesh
352/// * `collision_2` - Second collision mesh
353/// * `uk_1` - Unknown field
354/// * `uk_2` - Unknown field
355#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
356#[getset(get = "pub", get_mut = "pub", set = "pub")]
357pub struct Gate {
358    /// First collision mesh.
359    collision_1: Collision3d,
360
361    /// Second collision mesh.
362    collision_2: Collision3d,
363
364    /// Unknown field.
365    uk_1: u32,
366
367    /// Unknown field.
368    uk_2: u32,
369}
370
371/// A 3D collision outline.
372///
373/// Defines a named 3D outline used for collision detection.
374///
375/// # Fields
376///
377/// * `name` - Name identifier for this collision outline
378/// * `vertices` - 3D polyline defining the outline
379/// * `uk_1` - Unknown field
380#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
381#[getset(get = "pub", get_mut = "pub", set = "pub")]
382pub struct CollisionOutline {
383    /// Name identifier for this collision outline.
384    name: String,
385
386    /// 3D polyline vertices.
387    vertices: Outline3d,
388
389    /// Unknown field.
390    uk_1: u32,
391}
392
393/// Soft collision data.
394///
395/// Defines soft collision zones with transforms and positions.
396///
397/// # Fields
398///
399/// * `name` - Name identifier
400/// * `transform` - Transformation matrix
401/// * `uk_1` - Unknown field
402/// * `point_1` - 2D point position
403#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
404#[getset(get = "pub", get_mut = "pub", set = "pub")]
405pub struct SoftCollisions {
406    /// Name identifier.
407    name: String,
408
409    /// Transformation matrix.
410    transform: Transform4x4,
411
412    /// Unknown field.
413    uk_1: i16,
414
415    /// 2D point position.
416    point_1: Point2d,
417}
418
419/// Projectile emitter position for building-based ranged attacks.
420///
421/// Defines where projectiles (arrows/cannonballs) are fired from on a building.
422/// Legacy feature used in Thrones of Britannia and older games. Newer games
423/// moved this logic to the map itself.
424///
425/// # Fields
426///
427/// * `name` - Name identifier for this emitter
428/// * `transform` - Transformation matrix for emitter position and orientation
429#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
430#[getset(get = "pub", get_mut = "pub", set = "pub")]
431pub struct ProjectileEmitter {
432    /// Name identifier for this emitter.
433    name: String,
434
435    /// Transformation matrix for position and orientation.
436    transform: Transform4x4,
437}
438
439/// Reference to an attached building model.
440///
441/// Used to attach additional models to buildings (e.g., torches on Attila's walls,
442/// decorative elements).
443///
444/// # Fields
445///
446/// * `key` - Path to the model file to attach
447/// * `name` - Name identifier for this attachment
448/// * `transform` - Transformation matrix for attachment position
449/// * `uk_1` - Unknown field (possibly unique ID within the file)
450#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
451#[getset(get = "pub", get_mut = "pub", set = "pub")]
452pub struct FileRef {
453    /// Path to the model file to attach.
454    key: String,
455
456    /// Name identifier for this attachment.
457    name: String,
458
459    /// Transformation matrix for attachment position.
460    transform: Transform4x4,
461
462    /// Unknown field (possibly unique ID within the file).
463    uk_1: i16,
464}
465
466/// A corner of a footprint ring.
467///
468/// # Fields
469///
470/// * `vertex` - Position of the corner (x and z)
471/// * `vertex_type` - Type of the corner (2 on every corner of `bridge_wood_complete`'s rings)
472#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
473#[getset(get = "pub", get_mut = "pub", set = "pub")]
474pub struct FootprintCorner {
475    /// 2D vertex position.
476    vertex: Point2d,
477
478    /// Type identifier for this vertex.
479    vertex_type: u32,
480}
481
482/// A walkable platform surface where units can stand and fight.
483///
484/// Platforms define the areas where units can be placed within a building.
485/// Different flags control how the pathfinder treats the platform.
486///
487/// # Fields
488///
489/// * `normal` - Surface normal vector
490/// * `vertices` - 3D outline defining the platform boundary
491/// * `flag_1` - Unknown behavior flag
492/// * `flag_2` - Treats platform as ground if true (units can walk freely)
493/// * `flag_3` - Unknown flag (set in siege tower ramp platforms)
494///
495/// # Examples
496///
497/// ```rust,ignore
498/// for platform in destruct.platforms() {
499///     if *platform.flag_2() {
500///         println!("Platform '{}' is treated as ground", /* no name field */);
501///     }
502/// }
503/// ```
504#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
505#[getset(get = "pub", get_mut = "pub", set = "pub")]
506pub struct Platform {
507    /// Surface normal vector.
508    normal: Point3d,
509
510    /// 3D polyline defining platform boundary.
511    vertices: Outline3d,
512
513    /// Unknown behavior flag.
514    flag_1: bool,
515
516    /// Treats platform as ground if true (units can walk freely).
517    flag_2: bool,
518
519    /// Unknown flag (set in siege tower ramp platforms).
520    flag_3: bool,
521}
522
523/// A path for unit movement between platforms.
524///
525/// Pipes define how units move between different platform levels (stairs, ladders,
526/// doors, teleports, etc.). On ships, pipe vertices must align with deck vertices.
527///
528/// # Fields
529///
530/// * `name` - Name identifier for this pipe
531/// * `line` - 3D polyline defining the movement path
532/// * `line_type` - Type of pipe (stairs, ladder, door, etc.)
533///
534/// # Examples
535///
536/// ```rust,ignore
537/// for pipe in destruct.pipes() {
538///     println!("Pipe '{}': {:?}", pipe.name(), pipe.line_type());
539/// }
540/// ```
541#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
542#[getset(get = "pub", get_mut = "pub", set = "pub")]
543pub struct Pipe {
544    /// Name identifier for this pipe.
545    name: String,
546
547    /// 3D polyline defining the movement path.
548    line: Outline3d,
549
550    /// Type of pipe (stairs, ladder, door, etc.).
551    line_type: PipeType,
552}
553
554/// Entity Formation line for unit positioning and actions.
555///
556/// EF Lines define where units should form up for specific actions like firing,
557/// boarding, defending, or spawning. Different types serve different purposes.
558/// See `EFLineType` for available types and their uses.
559///
560/// # Fields
561///
562/// * `name` - Name identifier for this line
563/// * `action` - Type of action/formation for this line
564/// * `start` - Starting point of the line
565/// * `end` - Ending point of the line
566/// * `direction` - Direction vector for unit orientation
567/// * `parent_index` - Parent index for hierarchical relationships
568///
569/// # Examples
570///
571/// ```rust,ignore
572/// for ef_line in destruct.ef_lines() {
573///     println!("EF Line '{}': {:?}", ef_line.name(), ef_line.action());
574/// }
575/// ```
576#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
577#[getset(get = "pub", get_mut = "pub", set = "pub")]
578pub struct EFLine {
579    /// Name identifier for this line.
580    name: String,
581
582    /// Type of action/formation for this line.
583    action: EFLineType,
584
585    /// Starting point of the line.
586    start: Point3d,
587
588    /// Ending point of the line.
589    end: Point3d,
590
591    /// Direction vector for unit orientation.
592    direction: Point3d,
593
594    /// Parent index for hierarchical relationships.
595    parent_index: u32,
596}
597
598/// Line where siege equipment can attach to walls.
599///
600/// Docking lines are required on walls for siege towers and ladders to attach.
601/// Without these, siege equipment cannot dock to the wall.
602///
603/// # Fields
604///
605/// * `key` - Key identifier for this docking line
606/// * `start` - Starting point of the line
607/// * `end` - Ending point of the line
608/// * `direction` - Direction vector for docking orientation
609#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
610#[getset(get = "pub", get_mut = "pub", set = "pub")]
611pub struct DockingLine {
612    /// Key identifier for this docking line.
613    key: String,
614
615    /// Starting point of the line.
616    start: Point2d,
617
618    /// Ending point of the line.
619    end: Point2d,
620
621    /// Direction vector for docking orientation.
622    direction: Point2d,
623}
624
625/// Visual effects attachment point.
626///
627/// Defines where VFX (particle effects, animations, etc.) are attached to the building.
628///
629/// # Fields
630///
631/// * `key` - Path to the VFX resource
632/// * `matrix_1` - Transformation matrix for VFX position and orientation
633#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
634#[getset(get = "pub", get_mut = "pub", set = "pub")]
635pub struct Vfx {
636    /// Path to the VFX resource.
637    key: String,
638
639    /// Transformation matrix for VFX position and orientation.
640    matrix_1: Transform4x4,
641}
642
643/// Type of pipe for unit movement.
644///
645/// Defines the movement behavior for a pipe. Different types handle different
646/// movement scenarios like stairs, ladders, doors, teleportation, etc.
647///
648/// # Variants by Use Case
649///
650/// ## Naval Movement (Ships)
651/// - [`ShipStaircase`](Self::ShipStaircase) - Movement through ship staircases
652/// - [`ShipWalk`](Self::ShipWalk) - Walking movement on ships (unconfirmed)
653/// - [`ShipLadder`](Self::ShipLadder) - Climbing ship ladders
654///
655/// ## Wall Climbing
656/// - [`SiegeLadder1`](Self::SiegeLadder1) - Wall ladders in Empire/Napoleon
657/// - [`SiegeLadder2`](Self::SiegeLadder2) - Wall ladders in Warhammer games
658/// - [`Rope`](Self::Rope) - Rope climbing in Three Kingdoms
659///
660/// ## Siege Equipment
661/// - [`LadderLeft`](Self::LadderLeft) - Left ladder in siege towers
662/// - [`LadderRight`](Self::LadderRight) - Right ladder in siege towers
663/// - [`JumpRamp`](Self::JumpRamp) - Jumping from siege tower ramps
664///
665/// ## Doors and Entry
666/// - [`DoorNoTeleport`](Self::DoorNoTeleport) - Door threshold for garrisonable buildings
667/// - [`WallDoorTeleport`](Self::WallDoorTeleport) - Teleport between ends (Warhammer walls)
668/// - [`GroundTeleport`](Self::GroundTeleport) - Barricade teleportation (Warhammer III)
669///
670/// ## Other
671/// - [`Stairs`](Self::Stairs) - Interior wall stairs (Three Kingdoms)
672/// - [`Jump`](Self::Jump) - Jumping onto walls
673/// - [`UnknownSambucaPipe`](Self::UnknownSambucaPipe) - Sambuca-related (Thrones of Britannia)
674#[derive(Default, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
675#[repr(i32)]
676pub enum PipeType {
677    /// Ship staircase movement.
678    #[default]
679    ShipStaircase = 1,
680    /// Ship walking movement (unconfirmed).
681    ShipWalk = 2,
682    /// Ship ladder climbing.
683    ShipLadder = 3,
684    /// Wall climbing ladders (Empire/Napoleon).
685    SiegeLadder1 = 8,
686    /// Interior wall stairs (Three Kingdoms).
687    Stairs = 9,
688    /// Rope wall climbing (Three Kingdoms).
689    Rope = 10,
690    /// Sambuca pipe (Thrones of Britannia).
691    UnknownSambucaPipe = 11,
692    /// Door entry threshold for garrisonable buildings.
693    DoorNoTeleport = 13,
694    /// Jumping onto walls (PT_JUMP).
695    Jump = 14,
696    /// Teleportation between pipe ends (Warhammer walls, PT_WALL_DOOR).
697    WallDoorTeleport = 30,
698    /// Jumping from siege tower ramps to walls (PT_JUMP_RAMP).
699    JumpRamp = 32,
700    /// Left ladder in siege towers.
701    LadderLeft = 33,
702    /// Right ladder in siege towers.
703    LadderRight = 34,
704    /// Wall climbing ladders (Warhammer).
705    SiegeLadder2 = 35,
706    /// Barricade teleportation (Warhammer III).
707    GroundTeleport = 38,
708}
709
710/// Type of Entity Formation line.
711///
712/// Defines the purpose of an EF line - where units should position themselves
713/// for specific actions like firing, boarding, defending, or spawning.
714///
715/// # Variants by Use Case
716///
717/// ## Wall Defense
718/// - [`LowWall`](Self::LowWall) - Mid-size walls, first row in Warhammer
719/// - [`HighWall`](Self::HighWall) - Full-size walls
720/// - [`Overflow`](Self::Overflow) - Rows behind the second, waiting positions
721/// - [`CrenelLeftOuter`](Self::CrenelLeftOuter) - Crenellation positions (likely)
722/// - [`CrenelLeftInner`](Self::CrenelLeftInner) - Crenellation positions (likely)
723/// - [`CrenelRightInner`](Self::CrenelRightInner) - Crenellation positions (likely)
724/// - [`CrenelRightOuter`](Self::CrenelRightOuter) - Crenellation positions (likely)
725///
726/// ## Building Defense
727/// - [`Window`](Self::Window) - Window firing positions
728/// - [`EntranceDefense`](Self::EntranceDefense) - Melee defense at building entrances
729///
730/// ## Naval - Spawn Points
731/// - [`Marines`](Self::Marines) - Marine spawn locations and gun placements
732/// - [`Seamen`](Self::Seamen) - Seamen spawn locations
733/// - [`Captain`](Self::Captain) - Captain spawn point
734/// - [`Officer1`](Self::Officer1) - First officer spawn point
735/// - [`Officer2`](Self::Officer2) - Second officer spawn point
736/// - [`Officer3`](Self::Officer3) - Third officer spawn point
737///
738/// ## Naval - Combat Positions
739/// - [`NavalFiringPositionStand`](Self::NavalFiringPositionStand) - Standing firing positions
740/// - [`NavalFiringPositionCrouch`](Self::NavalFiringPositionCrouch) - Crouching firing positions
741/// - [`NavalFiringPositionStand360`](Self::NavalFiringPositionStand360) - 360° standing fire
742/// - [`NavalPerimeterPosition`](Self::NavalPerimeterPosition) - Perimeter positions (unknown)
743///
744/// ## Naval - Boarding and Disembark
745/// - [`Boarding`](Self::Boarding) - Boarding rope launch/entry points (required for boarding)
746/// - [`DisembarkLeft`](Self::DisembarkLeft) - Left-side disembarkation point
747/// - [`DisembarkRight`](Self::DisembarkRight) - Right-side disembarkation point
748///
749/// ## Equipment and Other
750/// - [`EnginePlacement`](Self::EnginePlacement) - Engine placement (unknown)
751/// - [`SecondaryEnginePlacement`](Self::SecondaryEnginePlacement) - Secondary engine (unknown)
752/// - [`GunnersOverflow`](Self::GunnersOverflow) - Gunner overflow (unknown)
753/// - [`Tree`](Self::Tree) - Unknown purpose
754///
755/// ## Invalid/Reserved
756/// - [`NumPurposes`](Self::NumPurposes) - Probably invalid
757/// - [`InvalidPurposes`](Self::InvalidPurposes) - Probably invalid
758#[derive(Default, PartialEq, Copy, Clone, Debug, Serialize, Deserialize)]
759#[repr(i32)]
760pub enum EFLineType {
761    /// Mid-size walls, first row in Warhammer walls.
762    #[default]
763    LowWall = 0,
764    /// Full-size walls.
765    HighWall = 1,
766    /// Window firing positions in garrisonable buildings.
767    Window = 2,
768    /// Rows behind the second one, waiting positions.
769    Overflow = 3,
770    /// Naval: Marine spawn locations and gun placements.
771    Marines = 4,
772    /// Naval: Seamen spawn locations.
773    Seamen = 5,
774    /// Naval: Gunner overflow (unknown).
775    GunnersOverflow = 6,
776    /// Naval: Captain spawn point.
777    Captain = 7,
778    /// Naval: First officer spawn point.
779    Officer1 = 8,
780    /// Naval: Boarding rope launch/entry points (required for boarding).
781    Boarding = 9,
782    /// Naval: Standing firing positions.
783    NavalFiringPositionStand = 10,
784    /// Naval: Crouching firing positions.
785    NavalFiringPositionCrouch = 11,
786    /// Naval: 360° standing firing positions.
787    NavalFiringPositionStand360 = 12,
788    /// Naval: Perimeter positions (unknown).
789    NavalPerimeterPosition = 13,
790    /// Unknown purpose.
791    Tree = 14,
792    /// Melee defense at building entrances.
793    EntranceDefense = 15,
794    /// Naval: Second officer spawn point.
795    Officer2 = 16,
796    /// Naval: Third officer spawn point.
797    Officer3 = 17,
798    /// Crenellation positions (likely).
799    CrenelLeftOuter = 18,
800    /// Crenellation positions (likely).
801    CrenelLeftInner = 19,
802    /// Crenellation positions (likely).
803    CrenelRightInner = 20,
804    /// Crenellation positions (likely).
805    CrenelRightOuter = 21,
806    /// Engine placement (unknown).
807    EnginePlacement = 22,
808    /// Secondary engine placement (unknown).
809    SecondaryEnginePlacement = 23,
810    /// Naval: Left-side disembarkation point.
811    DisembarkLeft = 24,
812    /// Naval: Right-side disembarkation point.
813    DisembarkRight = 25,
814    /// Probably invalid.
815    NumPurposes = 26,
816    /// Probably invalid.
817    InvalidPurposes = 27,
818}
819
820//---------------------------------------------------------------------------//
821//                           Implementation of Cs2Parsed
822//---------------------------------------------------------------------------//
823
824impl Decodeable for Cs2Parsed {
825
826    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
827        let mut decoded = Self::default();
828        decoded.version = data.read_u32()?;
829
830        match decoded.version {
831            21 => decoded.read_v21(data)?,
832            20 => decoded.read_v20(data)?,
833            18 => decoded.read_v18(data)?,
834            13 => decoded.read_v13(data)?,
835            12 => decoded.read_v12(data)?,
836            11 => decoded.read_v11(data)?,
837            10 => decoded.read_v10(data)?,
838            9 => decoded.read_v9(data)?,
839            8 => decoded.read_v8(data)?,
840            0 => decoded.read_v0(data)?,
841             _ => return Err(RLibError::DecodingUnsupportedVersion(decoded.version as usize)),
842        }
843
844        // Trigger an error if there's left data on the source.
845        check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
846
847        Ok(decoded)
848    }
849}
850
851impl Encodeable for Cs2Parsed {
852
853    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
854        buffer.write_u32(self.version)?;
855
856        match self.version {
857            21 => self.write_v21(buffer)?,
858            20 => self.write_v20(buffer)?,
859            18 => self.write_v18(buffer)?,
860            13 => self.write_v13(buffer)?,
861            12 => self.write_v12(buffer)?,
862            11 => self.write_v11(buffer)?,
863            10 => self.write_v10(buffer)?,
864            9 => self.write_v9(buffer)?,
865            8 => self.write_v8(buffer)?,
866            0 => self.write_v0(buffer)?,
867            _ => unimplemented!()
868        }
869
870        Ok(())
871    }
872}
873
874impl TryFrom<i32> for EFLineType {
875    type Error = RLibError;
876
877    fn try_from(value: i32) -> Result<Self, Self::Error> {
878        match value {
879            _ if value == Self::LowWall as i32 => Ok(Self::LowWall),
880            _ if value == Self::HighWall as i32 => Ok(Self::HighWall),
881            _ if value == Self::Window as i32 => Ok(Self::Window),
882            _ if value == Self::Overflow as i32 => Ok(Self::Overflow),
883            _ if value == Self::Marines as i32 => Ok(Self::Marines),
884            _ if value == Self::Seamen as i32 => Ok(Self::Seamen),
885            _ if value == Self::GunnersOverflow as i32 => Ok(Self::GunnersOverflow),
886            _ if value == Self::Captain as i32 => Ok(Self::Captain),
887            _ if value == Self::Officer1 as i32 => Ok(Self::Officer1),
888            _ if value == Self::Boarding as i32 => Ok(Self::Boarding),
889            _ if value == Self::NavalFiringPositionStand as i32 => Ok(Self::NavalFiringPositionStand),
890            _ if value == Self::NavalFiringPositionCrouch as i32 => Ok(Self::NavalFiringPositionCrouch),
891            _ if value == Self::NavalFiringPositionStand360 as i32 => Ok(Self::NavalFiringPositionStand360),
892            _ if value == Self::NavalPerimeterPosition as i32 => Ok(Self::NavalPerimeterPosition),
893            _ if value == Self::Tree as i32 => Ok(Self::Tree),
894            _ if value == Self::EntranceDefense as i32 => Ok(Self::EntranceDefense),
895            _ if value == Self::Officer2 as i32 => Ok(Self::Officer2),
896            _ if value == Self::Officer3 as i32 => Ok(Self::Officer3),
897            _ if value == Self::CrenelLeftOuter as i32 => Ok(Self::CrenelLeftOuter),
898            _ if value == Self::CrenelLeftInner as i32 => Ok(Self::CrenelLeftInner),
899            _ if value == Self::CrenelRightInner as i32 => Ok(Self::CrenelRightInner),
900            _ if value == Self::CrenelRightOuter as i32 => Ok(Self::CrenelRightOuter),
901            _ if value == Self::EnginePlacement as i32 => Ok(Self::EnginePlacement),
902            _ if value == Self::SecondaryEnginePlacement as i32 => Ok(Self::SecondaryEnginePlacement),
903            _ if value == Self::DisembarkLeft as i32 => Ok(Self::DisembarkLeft),
904            _ if value == Self::DisembarkRight as i32 => Ok(Self::DisembarkRight),
905            _ if value == Self::NumPurposes as i32 => Ok(Self::NumPurposes),
906            _ if value == Self::InvalidPurposes as i32 => Ok(Self::InvalidPurposes),
907            _ => Err(RLibError::UnknownEFLineType(value.to_string())),
908        }
909    }
910}
911
912impl From<EFLineType> for i32 {
913    fn from(value: EFLineType) -> Self {
914        value as i32
915    }
916}
917
918impl TryFrom<i32> for PipeType {
919    type Error = RLibError;
920
921    fn try_from(value: i32) -> Result<Self, Self::Error> {
922        match value {
923            _ if value == Self::ShipStaircase as i32 => Ok(Self::ShipStaircase),
924            _ if value == Self::ShipWalk as i32 => Ok(Self::ShipWalk),
925            _ if value == Self::ShipLadder as i32 => Ok(Self::ShipLadder),
926            _ if value == Self::SiegeLadder1 as i32 => Ok(Self::SiegeLadder1),
927            _ if value == Self::Stairs as i32 => Ok(Self::Stairs),
928            _ if value == Self::Rope as i32 => Ok(Self::Rope),
929            _ if value == Self::UnknownSambucaPipe as i32 => Ok(Self::UnknownSambucaPipe),
930            _ if value == Self::DoorNoTeleport as i32 => Ok(Self::DoorNoTeleport),
931            _ if value == Self::Jump as i32 => Ok(Self::Jump),
932            _ if value == Self::WallDoorTeleport as i32 => Ok(Self::WallDoorTeleport),
933            _ if value == Self::JumpRamp as i32 => Ok(Self::JumpRamp),
934            _ if value == Self::LadderLeft as i32 => Ok(Self::LadderLeft),
935            _ if value == Self::LadderRight as i32 => Ok(Self::LadderRight),
936            _ if value == Self::SiegeLadder2 as i32 => Ok(Self::SiegeLadder2),
937            _ if value == Self::GroundTeleport as i32 => Ok(Self::GroundTeleport),
938            _ => Err(RLibError::UnknownPipeType(value.to_string())),
939        }
940    }
941}
942
943impl From<PipeType> for i32 {
944    fn from(value: PipeType) -> Self {
945        value as i32
946    }
947}
948
949impl Cs2Parsed {
950
951    /// Migrates this CS2 Parsed file to be compatible with a specific game.
952    ///
953    /// Converts the file version to the maximum version supported by the target game.
954    /// Games generally support all previous format versions, so migration only occurs
955    /// if the current file version is newer than the game's maximum supported version.
956    ///
957    /// # Arguments
958    ///
959    /// * `game` - Target game information containing maximum supported version
960    ///
961    /// # Returns
962    ///
963    /// * `Ok(())` - Migration successful or not needed
964    /// * `Err(RLibError::GameDoesntSupportCs2Migration)` - Game doesn't support CS2 files
965    ///
966    /// # Examples
967    ///
968    /// ```rust,ignore
969    /// let mut parsed = Cs2Parsed::decode(&mut data, &None)?;
970    /// parsed.migrate_game(&game_info)?;
971    /// // File is now compatible with the target game
972    /// ```
973    pub fn migrate_game(&mut self, game: &GameInfo) -> Result<()> {
974
975        if *game.max_cs2_parsed_version() == 0 {
976            return Err(RLibError::GameDoesntSupportCs2Migration)
977        }
978
979        // Games (at least until thrones) seem to support all previous formats.
980        // So we only perform a migration if the format of the file is newer than the latest supported one by the game.
981        if self.version > *game.max_cs2_parsed_version() {
982            self.version = *game.max_cs2_parsed_version();
983        }
984
985        Ok(())
986    }
987}