rpfm_lib/files/anim_fragment_battle/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//! Animation fragment battle file format support.
12//!
13//! This module handles animation fragment files (`.bin`/`.frg`) which define battle animations
14//! for units in Total War games. These files replaced the older text-based animation tables
15//! with a more efficient binary format.
16//!
17//! # File Format
18//!
19//! Animation fragments use game-specific binary formats with different versions:
20//! - **Version 2 (Warhammer 2)**: Basic animation metadata with file references
21//! - **Version 2 (Three Kingdoms)**: Enhanced with mount/unmount tables and locomotion graphs
22//! - **Version 4 (Warhammer 3)**: Advanced format with animation references and cavalry tech flags
23//!
24//! # File Extensions
25//!
26//! - `.bin` - Modern binary animation fragment files (Warhammer 2+)
27//! - `.frg` - Legacy fragment file extension (older games)
28//!
29//! # File Organization
30//!
31//! Animation fragments are stored in:
32//! ```text
33//! animations/{skeleton_name}/battle/{animation_type}.bin
34//! ```
35//!
36//! # Supported Games
37//!
38//! Full support for:
39//! - Total War: Warhammer II (version 2)
40//! - Total War: Three Kingdoms (version 2, enhanced)
41//! - A Total War Saga: Troy (version 2)
42//! - Total War: Warhammer III (version 4)
43//! - Total War: Pharaoh / Pharaoh Dynasties (version 2)
44//!
45//! Older games (pre-Warhammer 2) are not supported.
46//!
47//! # Animation Entry Structure
48//!
49//! Each entry contains:
50//! - Animation ID and metadata (blend time, selection weight)
51//! - Weapon bone flags (for weapon attachment points)
52//! - File references to animation data and metadata
53//! - Optional single-frame variant flag
54//!
55//! # Table Conversion
56//!
57//! Animation fragments can be converted to/from [`TableInMemory`]
58//! for editing as TSV files.
59//!
60//! [`TableInMemory`]: crate::files::table::local::TableInMemory
61//!
62//! # Usage
63//!
64//! ```ignore
65//! use rpfm_lib::files::anim_fragment_battle::AnimFragmentBattle;
66//! use rpfm_lib::files::Decodeable;
67//!
68//! // Decode an animation fragment
69//! let fragment = AnimFragmentBattle::decode(&mut data, &Some(extra_data))?;
70//!
71//! // Access entries
72//! for entry in fragment.entries() {
73//! println!("Animation {}: blend={}, weight={}",
74//! entry.animation_id(),
75//! entry.blend_in_time(),
76//! entry.selection_weight()
77//! );
78//! }
79//!
80//! // Convert to table for TSV export
81//! let table = fragment.to_table()?;
82//! ```
83
84use bitflags::bitflags;
85use getset::*;
86use serde_derive::{Serialize, Deserialize};
87
88use std::collections::HashMap;
89use std::io::Cursor;
90
91use crate::binary::{ReadBytes, WriteBytes};
92use crate::error::{RLibError, Result};
93use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable, table::{DecodedData, local::TableInMemory, Table}};
94use crate::games::supported_games::{KEY_PHARAOH, KEY_PHARAOH_DYNASTIES, KEY_THREE_KINGDOMS, KEY_TROY, KEY_WARHAMMER_2};
95use crate::schema::*;
96use crate::utils::check_size_mismatch;
97
98pub use crate::files::detection::anim_fragment_battle::{BASE_PATH, MID_PATH, EXTENSION_NEW, EXTENSION_OLD};
99
100mod versions;
101
102#[cfg(test)] mod anim_fragment_battle_test;
103
104//---------------------------------------------------------------------------//
105// Enum & Structs
106//---------------------------------------------------------------------------//
107
108/// Represents a battle animation fragment file.
109///
110/// Contains animation entries and metadata for a specific skeleton type.
111/// The structure varies by game version, with newer games supporting more features.
112///
113/// # Version Differences
114///
115/// - **Version 2 (Warhammer 2/Troy/Pharaoh)**: Basic structure with min/max IDs
116/// - **Version 2 (Three Kingdoms)**: Adds mount tables and locomotion graph support
117/// - **Version 4 (Warhammer 3)**: Enhanced with subversion and cavalry tech flags
118#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
119#[getset(get = "pub", get_mut = "pub", set = "pub")]
120pub struct AnimFragmentBattle {
121 // Common fields across all versions
122
123 /// File format version (2 or 4).
124 version: u32,
125
126 /// List of animation entries in this fragment.
127 entries: Vec<Entry>,
128
129 /// Name of the skeleton this animation fragment applies to.
130 skeleton_name: String,
131
132 // Warhammer 3 specific (version 4)
133
134 /// Format subversion (version 4 only).
135 subversion: u32,
136
137 // Warhammer 3 / Three Kingdoms specific
138
139 /// Name of the animation table.
140 table_name: String,
141
142 /// Name of the mount animation table.
143 mount_table_name: String,
144
145 /// Name of the unmount animation table.
146 unmount_table_name: String,
147
148 /// Locomotion graph identifier.
149 locomotion_graph: String,
150
151 /// Whether this uses simple flight mechanics.
152 is_simple_flight: bool,
153
154 /// Whether this uses new cavalry technology.
155 is_new_cavalry_tech: bool,
156
157 // Warhammer 2 specific (version 2)
158
159 /// Minimum animation ID in this fragment (version 2 only).
160 min_id: u32,
161
162 /// Maximum animation ID in this fragment (version 2 only).
163 max_id: u32,
164}
165
166/// Represents a single animation entry within a fragment.
167///
168/// Contains all metadata and file references for one animation. The structure
169/// varies between version 2 and version 4 formats.
170///
171/// # Version Differences
172///
173/// - **Version 2**: Uses direct filename and metadata strings
174/// - **Version 4**: Uses `anim_refs` for multiple animation file references
175#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
176#[getset(get = "pub", get_mut = "pub", set = "pub")]
177pub struct Entry {
178 // Common fields across all versions
179
180 /// Unique animation identifier.
181 animation_id: u32,
182
183 /// Blend-in time in seconds for smooth transitions.
184 blend_in_time: f32,
185
186 /// Selection weight for animation variation selection (higher = more likely).
187 selection_weight: f32,
188
189 /// Weapon attachment bone flags.
190 weapon_bone: WeaponBone,
191
192 // Warhammer 3 specific (version 4)
193
194 /// Animation file references (version 4 only).
195 ///
196 /// Contains paths to animation data, metadata, and sound files.
197 anim_refs: Vec<AnimRef>,
198
199 // Warhammer 2 specific (version 2)
200
201 /// Slot identifier (version 2 only).
202 slot_id: u32,
203
204 /// Animation filename (version 2 only).
205 filename: String,
206
207 /// Metadata file path (version 2 only).
208 metadata: String,
209
210 /// Sound metadata file path (version 2 only).
211 metadata_sound: String,
212
213 /// Skeleton type identifier (version 2 only).
214 skeleton_type: String,
215
216 /// Unknown field (purpose not identified, version 2 only).
217 uk_3: u32,
218
219 /// Unknown field (purpose not identified, version 2 only).
220 uk_4: String,
221
222 // Common to version 2 and 4
223
224 /// Whether this is a single-frame animation variant.
225 single_frame_variant: bool,
226}
227
228/// Animation file reference (version 4 only).
229///
230/// Contains paths to the three files that make up an animation:
231/// - Animation data file (skeletal animation)
232/// - Metadata file (timing, events, etc.)
233/// - Sound file (audio cues and effects)
234#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
235#[getset(get = "pub", get_mut = "pub", set = "pub")]
236pub struct AnimRef {
237 /// Path to the animation data file.
238 file_path: String,
239
240 /// Path to the animation metadata file.
241 meta_file_path: String,
242
243 /// Path to the sound file.
244 snd_file_path: String,
245}
246
247bitflags! {
248 /// Weapon attachment bone flags.
249 ///
250 /// Defines which bones (attachment points) on the skeleton are used for
251 /// weapon positioning during this animation. Multiple bones can be active
252 /// simultaneously (e.g., for dual-wielding).
253 ///
254 /// # Bone Mapping
255 ///
256 /// Each bit corresponds to a specific weapon attachment point:
257 /// - `WEAPON_BONE_1`: Primary weapon hand (typically right hand)
258 /// - `WEAPON_BONE_2`: Secondary weapon hand (typically left hand)
259 /// - `WEAPON_BONE_3`: Back-mounted weapon (holstered)
260 /// - `WEAPON_BONE_4`: Additional attachment point
261 /// - `WEAPON_BONE_5`: Additional attachment point
262 /// - `WEAPON_BONE_6`: Additional attachment point
263 ///
264 /// The exact bone mapping depends on the skeleton definition.
265 #[derive(PartialEq, Clone, Copy, Debug, Default, Serialize, Deserialize)]
266 pub struct WeaponBone: u32 {
267 /// Primary weapon bone (bit 0).
268 const WEAPON_BONE_1 = 0b0000_0000_0000_0001;
269
270 /// Secondary weapon bone (bit 1).
271 const WEAPON_BONE_2 = 0b0000_0000_0000_0010;
272
273 /// Tertiary weapon bone (bit 2).
274 const WEAPON_BONE_3 = 0b0000_0000_0000_0100;
275
276 /// Fourth weapon bone (bit 3).
277 const WEAPON_BONE_4 = 0b0000_0000_0000_1000;
278
279 /// Fifth weapon bone (bit 4).
280 const WEAPON_BONE_5 = 0b0000_0000_0001_0000;
281
282 /// Sixth weapon bone (bit 5).
283 const WEAPON_BONE_6 = 0b0000_0000_0010_0000;
284 }
285}
286
287//---------------------------------------------------------------------------//
288// Implementation of AnimFragment
289//---------------------------------------------------------------------------//
290
291impl AnimFragmentBattle {
292
293 /// Returns table schema definitions for animation fragments.
294 ///
295 /// Provides two [`Definition`]s:
296 /// 1. Main entry definition with all animation entry fields
297 /// 2. Animation reference sub-definition (for version 4 `anim_refs` field)
298 ///
299 /// These definitions are used when converting animation fragments to/from
300 /// [`TableInMemory`] for TSV export/import.
301 ///
302 /// [`TableInMemory`]: crate::files::table::local::TableInMemory
303 ///
304 /// # Returns
305 ///
306 /// A tuple of `(entry_definition, anim_ref_definition)`.
307 pub fn definitions() -> (Definition, Definition) {
308 let anim_refs_definition = Definition::new_with_fields(0, &[
309 Field { name: "file_path".to_string(), field_type: FieldType::StringU8, ..Default::default() },
310 Field { name: "meta_file_path".to_string(), field_type: FieldType::StringU8, ..Default::default() },
311 Field { name: "snd_file_path".to_string(), field_type: FieldType::StringU8, ..Default::default() },
312 ], &[], None);
313
314 let definition = Definition::new_with_fields(0, &[
315 Field { name: "animation_id".to_string(), field_type: FieldType::I32, is_key: true, ..Default::default() },
316 Field { name: "blend_in_time".to_string(), field_type: FieldType::F32, ..Default::default() },
317 Field { name: "selection_weight".to_string(), field_type: FieldType::F32, ..Default::default() },
318 Field { name: "weapon_bone".to_string(), field_type: FieldType::I32, is_bitwise: 6, ..Default::default() },
319 Field { name: "anim_refs".to_string(), field_type: FieldType::SequenceU32(Box::new(anim_refs_definition.clone())), ..Default::default() },
320 Field { name: "slot_id".to_string(), field_type: FieldType::I32, is_key: true, ..Default::default() },
321 Field { name: "filename".to_string(), field_type: FieldType::StringU8, ..Default::default() },
322 Field { name: "metadata".to_string(), field_type: FieldType::StringU8, ..Default::default() },
323 Field { name: "metadata_sound".to_string(), field_type: FieldType::StringU8, ..Default::default() },
324 Field { name: "skeleton_type".to_string(), field_type: FieldType::StringU8, ..Default::default() },
325 Field { name: "uk_3".to_string(), field_type: FieldType::I32, ..Default::default() },
326 Field { name: "uk_4".to_string(), field_type: FieldType::StringU8, ..Default::default() },
327 Field { name: "single_frame_variant".to_string(), field_type: FieldType::Boolean, ..Default::default() },
328 ], &[], None);
329
330 (definition, anim_refs_definition)
331 }
332
333 /// Converts a table to a list of animation entries.
334 ///
335 /// Parses a [`TableInMemory`] (typically loaded from TSV)
336 /// and extracts animation entry data.
337 ///
338 /// [`TableInMemory`]: crate::files::table::local::TableInMemory
339 ///
340 /// # Parameters
341 ///
342 /// - `table`: The table containing animation entry data
343 ///
344 /// # Returns
345 ///
346 /// A vector of [`Entry`] structs parsed from the table rows.
347 ///
348 /// # Errors
349 ///
350 /// Returns an error if the table structure doesn't match the expected schema
351 /// or if data conversion fails.
352 pub fn from_table(table: &TableInMemory) -> Result<Vec<Entry>> {
353 let mut entries = vec![];
354
355 let definition = table.definition();
356 let fields_processed = definition.fields_processed();
357
358 for row in table.data().iter() {
359 let mut entry = Entry::default();
360
361 if let DecodedData::I32(data) = row[0] {
362 entry.set_animation_id(data as u32);
363 }
364
365 if let DecodedData::F32(data) = row[1] {
366 entry.set_blend_in_time(data);
367 }
368
369 if let DecodedData::F32(data) = row[2] {
370 entry.set_selection_weight(data);
371 }
372
373 if let DecodedData::Boolean(data_1) = row[3] {
374 if let DecodedData::Boolean(data_2) = row[4] {
375 if let DecodedData::Boolean(data_3) = row[5] {
376 if let DecodedData::Boolean(data_4) = row[6] {
377 if let DecodedData::Boolean(data_5) = row[7] {
378 if let DecodedData::Boolean(data_6) = row[8] {
379 let mut bits = WeaponBone::empty();
380
381 if data_1 { bits |= WeaponBone::WEAPON_BONE_1; }
382 if data_2 { bits |= WeaponBone::WEAPON_BONE_2; }
383 if data_3 { bits |= WeaponBone::WEAPON_BONE_3; }
384 if data_4 { bits |= WeaponBone::WEAPON_BONE_4; }
385 if data_5 { bits |= WeaponBone::WEAPON_BONE_5; }
386 if data_6 { bits |= WeaponBone::WEAPON_BONE_6; }
387
388 entry.set_weapon_bone(bits);
389 }
390 }
391 }
392 }
393 }
394 }
395
396 if let DecodedData::SequenceU32(ref data) = row[9] {
397 if let FieldType::SequenceU32(ref definition) = fields_processed[9].field_type() {
398 let mut data = Cursor::new(data);
399 let data = TableInMemory::decode(&mut data, definition, &HashMap::new(), None, false, fields_processed[9].name())?;
400 let mut entries = vec![];
401
402 for row in data.data().iter() {
403 let mut entry = AnimRef::default();
404
405 if let DecodedData::StringU8(ref data) = row[0] {
406 entry.set_file_path(data.to_string());
407 }
408
409 if let DecodedData::StringU8(ref data) = row[1] {
410 entry.set_meta_file_path(data.to_string());
411 }
412
413 if let DecodedData::StringU8(ref data) = row[2] {
414 entry.set_snd_file_path(data.to_string());
415 }
416
417 entries.push(entry);
418 }
419
420 entry.set_anim_refs(entries);
421 }
422 }
423
424 if let DecodedData::I32(data) = row[10] {
425 entry.set_slot_id(data as u32);
426 }
427
428 if let DecodedData::StringU8(ref data) = row[11] {
429 entry.set_filename(data.to_string());
430 }
431
432 if let DecodedData::StringU8(ref data) = row[12] {
433 entry.set_metadata(data.to_string());
434 }
435
436 if let DecodedData::StringU8(ref data) = row[13] {
437 entry.set_metadata_sound(data.to_string());
438 }
439
440 if let DecodedData::StringU8(ref data) = row[14] {
441 entry.set_skeleton_type(data.to_string());
442 }
443
444 if let DecodedData::I32(data) = row[15] {
445 entry.set_uk_3(data as u32);
446 }
447
448 if let DecodedData::StringU8(ref data) = row[16] {
449 entry.set_uk_4(data.to_string());
450 }
451
452 if let DecodedData::Boolean(data) = row[17] {
453 entry.set_single_frame_variant(data);
454 }
455
456 entries.push(entry);
457 }
458
459 Ok(entries)
460 }
461
462 /// Converts this animation fragment to a table.
463 ///
464 /// Creates a [`TableInMemory`] from the animation entries, which can then be
465 /// exported as TSV for editing.
466 ///
467 /// [`TableInMemory`]: crate::files::table::local::TableInMemory
468 ///
469 /// # Returns
470 ///
471 /// A table containing all animation entries with the appropriate schema.
472 ///
473 /// # Errors
474 ///
475 /// Returns an error if table construction or data conversion fails.
476 pub fn to_table(&self) -> Result<TableInMemory> {
477 let (definition, anim_refs_definition) = Self::definitions();
478 let mut table = TableInMemory::new(&definition, None, "");
479
480 let data = self.entries()
481 .iter()
482 .map(|entry| {
483 let mut row = Vec::with_capacity(19);
484 row.push(DecodedData::I32(*entry.animation_id() as i32));
485 row.push(DecodedData::F32(*entry.blend_in_time()));
486 row.push(DecodedData::F32(*entry.selection_weight()));
487 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_1)));
488 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_2)));
489 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_3)));
490 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_4)));
491 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_5)));
492 row.push(DecodedData::Boolean(entry.weapon_bone().contains(WeaponBone::WEAPON_BONE_6)));
493
494 let mut anim_refs_subtable = TableInMemory::new(&anim_refs_definition, None, "anim_refs");
495 let mut anim_ref_rows = Vec::with_capacity(entry.anim_refs().len());
496 for anim_ref in entry.anim_refs() {
497 let anim_ref_row = vec![
498 DecodedData::StringU8(anim_ref.file_path().to_string()),
499 DecodedData::StringU8(anim_ref.meta_file_path().to_string()),
500 DecodedData::StringU8(anim_ref.snd_file_path().to_string()),
501 ];
502 anim_ref_rows.push(anim_ref_row)
503 }
504 anim_refs_subtable.set_data(&anim_ref_rows).unwrap();
505 let mut writer = vec![];
506 writer.write_u32(anim_ref_rows.len() as u32).unwrap();
507 let _ = anim_refs_subtable.encode(&mut writer);
508
509 row.push(DecodedData::SequenceU32(writer));
510
511 row.push(DecodedData::I32(*entry.slot_id() as i32));
512 row.push(DecodedData::StringU8(entry.filename().to_string()));
513 row.push(DecodedData::StringU8(entry.metadata().to_string()));
514 row.push(DecodedData::StringU8(entry.metadata_sound().to_string()));
515 row.push(DecodedData::StringU8(entry.skeleton_type().to_string()));
516 row.push(DecodedData::I32(*entry.uk_3() as i32));
517 row.push(DecodedData::StringU8(entry.uk_4().to_string()));
518 row.push(DecodedData::Boolean(*entry.single_frame_variant()));
519
520 row
521 }).collect::<Vec<_>>();
522
523 table.set_data(&data)?;
524 Ok(table)
525 }
526}
527
528impl Decodeable for AnimFragmentBattle {
529
530 fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
531 let extra_data = extra_data.as_ref().ok_or(RLibError::DecodingMissingExtraData)?;
532 let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
533
534 let version = data.read_u32()?;
535
536 let mut fragment = Self::default();
537 fragment.version = version;
538
539 match version {
540 2 => match game_info.key() {
541 KEY_WARHAMMER_2 | KEY_TROY | KEY_PHARAOH | KEY_PHARAOH_DYNASTIES => fragment.read_v2_wh2(data)?,
542 KEY_THREE_KINGDOMS => fragment.read_v2_3k(data)?,
543 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(fragment.version as usize))?,
544 },
545 4 => fragment.read_v4(data)?,
546 _ => Err(RLibError::DecodingAnimFragmentUnsupportedVersion(version as usize))?,
547 }
548
549 // If we are not in the last byte, it means we didn't parse the entire file, which means this file is corrupt.
550 check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
551
552 Ok(fragment)
553 }
554}
555
556impl Encodeable for AnimFragmentBattle {
557
558 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, extra_data: &Option<EncodeableExtraData>) -> Result<()> {
559 let extra_data = extra_data.as_ref().ok_or(RLibError::DecodingMissingExtraData)?;
560 let game_info = extra_data.game_info.ok_or_else(|| RLibError::DecodingMissingExtraDataField("game_info".to_owned()))?;
561
562 buffer.write_u32(self.version)?;
563
564 match self.version {
565 2 => match game_info.key() {
566 KEY_WARHAMMER_2 | KEY_TROY | KEY_PHARAOH | KEY_PHARAOH_DYNASTIES => self.write_v2_wh2(buffer)?,
567 KEY_THREE_KINGDOMS => self.write_v2_3k(buffer)?,
568 _ => Err(RLibError::DecodingMatchedCombatUnsupportedVersion(self.version as usize))?,
569 },
570 4 => self.write_v4(buffer)?,
571 _ => Err(RLibError::DecodingAnimFragmentUnsupportedVersion(self.version as usize))?,
572 };
573
574 Ok(())
575 }
576}