rpfm_lib/files/matched_combat/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 module contains the implementation of the Matched Combat file format for Total War games.
12//!
13//! Matched combat files define synchronized combat animations between units, specifying which
14//! animation files to use, what conditions must be met, and how units transition during the
15//! animation sequence. These files control cinematic melee combat interactions where units
16//! perform matched animations together (e.g., sword duels, executions, grapples).
17//!
18//! # File Format
19//!
20//! Matched combat files (`.bin`) contain entries that define combat animation sequences.
21//! Each entry specifies:
22//!
23//! - Animation participants (multiple units involved in the sequence)
24//! - Entity-specific animation files and metadata
25//! - Selection weights for animation variety
26//! - Filters to determine when animations can be used (unit types, equipment, etc.)
27//! - State transitions (alive to dead, alive to alive, etc.)
28//! - Team assignments for participants
29//!
30//! # Versions
31//!
32//! The format has multiple versions with game-specific variations:
33//!
34//! - Version 1 (Three Kingdoms): Basic matched combat system
35//! - Version 1 (Warhammer 3): Extended with mount animations
36//! - Version 3: Further expanded format
37//!
38//! # File Locations
39//!
40//! Matched combat files are typically found in:
41//! - `animations/matched_combat/*.bin`
42//! - `animations/database/matched/*.bin`
43//! - `animations/database/trigger/*.bin`
44//!
45//! # Usage Example
46//!
47//! ```rust,ignore
48//! use rpfm_lib::files::{Decodeable, matched_combat::*};
49//!
50//! // Decode a matched combat file
51//! let mut data = std::io::Cursor::new(file_data);
52//! let extra_data = Some(DecodeableExtraData {
53//! game_info: Some(game_info),
54//! ..Default::default()
55//! });
56//! let matched = MatchedCombat::decode(&mut data, &extra_data)?;
57//!
58//! // Access combat entries
59//! for entry in matched.entries() {
60//! println!("Combat ID: {}", entry.id());
61//! for participant in entry.participants() {
62//! println!("Team: {}", participant.team());
63//! }
64//! }
65//! ```
66
67use getset::{Getters, Setters};
68use serde_derive::{Serialize, Deserialize};
69
70use crate::binary::{ReadBytes, WriteBytes};
71use crate::error::{RLibError, Result};
72use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
73use crate::games::supported_games::{KEY_THREE_KINGDOMS, KEY_WARHAMMER_3};
74use crate::utils::check_size_mismatch;
75
76pub use crate::files::detection::matched_combat::{BASE_PATHS, EXTENSION};
77
78mod versions;
79
80#[cfg(test)] mod matched_combat_test;
81
82//---------------------------------------------------------------------------//
83// Enum & Structs
84//---------------------------------------------------------------------------//
85
86/// Represents a matched combat file decoded in memory.
87///
88/// Contains the format version and a list of combat animation entries.
89#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
90#[getset(get = "pub", set = "pub")]
91pub struct MatchedCombat {
92 /// File format version (1 or 3).
93 version: u32,
94
95 /// List of matched combat animation entries.
96 entries: Vec<MatchedEntry>,
97}
98
99/// A single matched combat animation entry.
100///
101/// Defines a synchronized combat sequence involving one or more participants,
102/// each with their own animations and state transitions.
103#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
104#[getset(get = "pub", set = "pub")]
105pub struct MatchedEntry {
106 /// Unique identifier for this matched combat entry.
107 id: String,
108
109 /// List of participants involved in this combat sequence.
110 ///
111 /// Typically 2 participants for duels, but can be more for group animations.
112 participants: Vec<Participant>,
113}
114
115/// A participant in a matched combat animation sequence.
116///
117/// Represents one unit/entity involved in the combat, including which animations
118/// it should play, what conditions must be met, and how its state changes.
119#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
120#[getset(get = "pub", set = "pub")]
121pub struct Participant {
122 /// Team identifier for this participant (e.g., 0 for attacker, 1 for defender).
123 team: u32,
124
125 /// Bundles of animation entities with selection weights.
126 ///
127 /// Multiple bundles allow for animation variety - the game randomly selects
128 /// one bundle based on weights.
129 entity_info: Vec<EntityBundle>,
130
131 /// State transition for this participant (e.g., alive to dead).
132 state: State,
133
134 /// Unknown field from Three Kingdoms files.
135 uk1: u32,
136
137 /// Unknown field from Three Kingdoms files.
138 uk2: u32,
139
140 /// Unknown field from Warhammer 3 files.
141 uk3: u32,
142
143 /// Unknown field from Warhammer 3 files.
144 uk4: u32,
145}
146
147/// A bundle of animation entities that can be selected together.
148///
149/// Allows the game to randomly choose between different animation variations
150/// based on selection weights, providing visual variety in combat.
151#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
152#[getset(get = "pub", set = "pub")]
153pub struct EntityBundle {
154 /// Animation entities in this bundle.
155 entities: Vec<Entity>,
156
157 /// Weight for random selection of this bundle (higher = more likely to be chosen).
158 selection_weight: f32,
159}
160
161/// An entity's animation data for matched combat.
162///
163/// Specifies the animation files, metadata, timing, equipment visibility,
164/// and conditions (filters) for when this animation can be used.
165#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
166#[getset(get = "pub", set = "pub")]
167pub struct Entity {
168 /// Path to the animation file for this entity.
169 animation_filename: String,
170
171 /// Paths to metadata files containing additional animation data.
172 metadata_filenames: Vec<String>,
173
174 /// Time in seconds for blending into this animation from the previous state.
175 blend_in_time: f32,
176
177 /// Equipment display flags controlling weapon/shield visibility during animation.
178 equipment_display: u32,
179
180 /// Filters that must match for this animation to be eligible for selection.
181 ///
182 /// Filters check conditions like unit type, equipment, size, etc.
183 filters: Vec<Filter>,
184
185 /// Unknown field.
186 uk: u32,
187
188 /// Animation filename for the mount (only in Warhammer 3 files).
189 ///
190 /// Used when the participant is mounted on a creature or horse.
191 mount_filename: String,
192}
193
194/// A filter condition for determining when an animation can be used.
195///
196/// Filters check properties of the participating units (e.g., unit type, equipment,
197/// size class) to ensure animations only play when appropriate.
198#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
199#[getset(get = "pub", set = "pub")]
200pub struct Filter {
201 /// If true, check for equality; if false, check for inequality.
202 equals: bool,
203
204 /// If true, combine with previous filter using OR; if false, use AND.
205 or: bool,
206
207 /// Type of filter (e.g., unit type, equipment slot, size class).
208 filter_type: u32,
209
210 /// Value to compare against (interpretation depends on filter_type).
211 value: String,
212}
213
214/// State transition for a participant during the matched combat sequence.
215///
216/// Defines how the participant's state changes from the start to the end of the animation
217/// (e.g., alive to dead for an execution animation, alive to alive for a non-lethal clash).
218#[derive(PartialEq, Clone, Debug, Default, Getters, Setters, Serialize, Deserialize)]
219#[getset(get = "pub", set = "pub")]
220pub struct State {
221 /// State at the beginning of the animation.
222 start: StateParticipant,
223
224 /// State at the end of the animation.
225 end: StateParticipant,
226}
227
228/// Possible states for a participant in a matched combat animation.
229///
230/// Indicates whether the participant is alive, dead, or in some other state
231/// at the beginning or end of the animation sequence.
232#[derive(PartialEq, Clone, Copy, Debug, Default, Serialize, Deserialize)]
233#[repr(u32)]
234pub enum StateParticipant {
235 /// Participant is alive and active.
236 #[default] Alive,
237
238 /// Participant is dead or dying.
239 Dead = 1,
240
241 /// Unknown state variant.
242 NoIdea1 = 2,
243
244 /// Unknown state variant.
245 NoIdea2 = 3,
246
247 /// Unknown state variant.
248 NoIdea3 = 4,
249
250 /// Unknown state variant.
251 NoIdea4 = 5,
252
253 /// Unknown state variant.
254 NoIdea5 = 6,
255}
256
257//---------------------------------------------------------------------------//
258// Implementation of MatchedCombat
259//---------------------------------------------------------------------------//
260
261impl Decodeable for MatchedCombat {
262
263 fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
264 let extra_data = extra_data.as_ref().ok_or(RLibError::DecodingMissingExtraData)?;
265 let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
266
267 let mut matched = Self::default();
268 matched.version = data.read_u32()?;
269
270 match matched.version {
271 1 => match game_info.key() {
272 KEY_WARHAMMER_3 => matched.read_v1_wh3(data)?,
273 KEY_THREE_KINGDOMS => matched.read_v1_3k(data)?,
274 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(matched.version as usize))?,
275 }
276 3 => matched.read_v3(data)?,
277 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(matched.version as usize))?,
278 }
279
280 // If we are not in the last byte, it means we didn't parse the entire file, which means this file is corrupt.
281 check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
282
283 Ok(matched)
284 }
285}
286
287impl Encodeable for MatchedCombat {
288
289 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()> {
290 let extra_data = extra_data.as_ref().ok_or(RLibError::EncodingMissingExtraData)?;
291 let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
292
293 buffer.write_u32(self.version)?;
294
295 match self.version {
296 1 => match game_info.key() {
297 KEY_WARHAMMER_3 => self.write_v1_wh3(buffer)?,
298 KEY_THREE_KINGDOMS => self.write_v1_3k(buffer)?,
299 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(self.version as usize))?,
300 }
301 3 => self.write_v3(buffer)?,
302 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(self.version as usize))?,
303 };
304
305 Ok(())
306 }
307}
308
309impl TryFrom<u32> for StateParticipant {
310 type Error = RLibError;
311
312 fn try_from(value: u32) -> std::result::Result<Self, Self::Error> {
313 match value {
314 _ if value == Self::Alive as u32 => Ok(Self::Alive),
315 _ if value == Self::Dead as u32 => Ok(Self::Dead),
316 _ if value == Self::NoIdea1 as u32 => Ok(Self::NoIdea1),
317 _ if value == Self::NoIdea2 as u32 => Ok(Self::NoIdea2),
318 _ if value == Self::NoIdea3 as u32 => Ok(Self::NoIdea3),
319 _ if value == Self::NoIdea4 as u32 => Ok(Self::NoIdea4),
320 _ if value == Self::NoIdea5 as u32 => Ok(Self::NoIdea5),
321 _ => Err(RLibError::InvalidStateParticipantValue(value)),
322 }
323 }
324}