Skip to main content

rpfm_lib/files/atlas/
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//! Atlas texture coordinate mapping file format support.
12//!
13//! This module handles `.atlas` files which define texture coordinate mappings for UI sprites
14//! and other 2D graphics elements in Total War games. Atlas files map logical sprite names
15//! to rectangular regions within larger texture atlas images.
16//!
17//! # File Format
18//!
19//! Atlas files use a binary format with the following structure:
20//! - Header with version and metadata
21//! - List of atlas entries mapping sprites to texture coordinates
22//! - Coordinates are stored as percentages of the atlas texture size (4096x4096)
23//!
24//! # Coordinate System
25//!
26//! Texture coordinates are stored as normalized values (0.0-1.0 range) and converted to
27//! pixel coordinates by multiplying by `IMAGE_SIZE` (4096). Each entry defines:
28//! - Top-left corner (x1, y1)
29//! - Bottom-right corner (x2, y2)
30//! - Sprite dimensions (width, height)
31//!
32//! # Table Conversion
33//!
34//! Atlas files can be converted to/from [`TableInMemory`] for easy editing as TSV files.
35//! The table format has 8 columns matching the [`AtlasEntry`] fields.
36//!
37//! [`TableInMemory`]: crate::files::table::local::TableInMemory
38//!
39//! # Usage
40//!
41//! ```ignore
42//! use rpfm_lib::files::atlas::Atlas;
43//! use rpfm_lib::files::Decodeable;
44//!
45//! // Decode an atlas file
46//! let atlas = Atlas::decode(&mut data, &None)?;
47//!
48//! // Access entries
49//! for entry in atlas.entries() {
50//!     println!("Sprite: {} at ({}, {})", entry.string1(), entry.x_1(), entry.y_1());
51//! }
52//!
53//! // Convert to table for TSV export
54//! let table = TableInMemory::from(atlas);
55//! ```
56
57use getset::*;
58use serde_derive::{Serialize, Deserialize};
59
60
61use crate::error::Result;
62use crate::binary::{ReadBytes, WriteBytes};
63use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable, table::{DecodedData, local::TableInMemory, Table}};
64use crate::schema::{Definition, Field, FieldType};
65use crate::utils::check_size_mismatch;
66
67pub use crate::files::detection::atlas::EXTENSION;
68
69/// Standard texture atlas size in pixels (4096x4096).
70///
71/// This constant is used to convert normalized texture coordinates (0.0-1.0)
72/// to pixel coordinates within the atlas image.
73const IMAGE_SIZE: u32 = 4096;
74
75/// Atlas file format version.
76const VERSION: i32 = 1;
77
78#[cfg(test)] mod atlas_test;
79
80//---------------------------------------------------------------------------//
81//                              Enum & Structs
82//---------------------------------------------------------------------------//
83
84/// Represents a texture atlas mapping file.
85///
86/// Contains metadata and a list of sprite entries that map logical names to
87/// texture coordinates within an atlas image.
88#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
89#[getset(get = "pub", get_mut = "pub", set = "pub")]
90pub struct Atlas {
91    /// File format version (currently always 1).
92    version: u32,
93
94    /// Unknown field, purpose not yet identified.
95    unknown: u32,
96
97    /// List of sprite entries defining texture coordinate mappings.
98    entries: Vec<AtlasEntry>,
99}
100
101/// Represents a single sprite entry in an atlas file.
102///
103/// Defines the mapping between a sprite name and its position/size within
104/// the atlas texture. Coordinates are in pixel space (0-4096 range).
105#[derive(PartialEq, Clone, Debug, Default, Getters, MutGetters, Setters, Serialize, Deserialize)]
106#[getset(get = "pub", get_mut = "pub", set = "pub")]
107pub struct AtlasEntry {
108    /// Primary identifier string (sprite name or reference).
109    string1: String,
110
111    /// Secondary identifier string (may be empty or contain additional metadata).
112    string2: String,
113
114    /// X coordinate of the top-left corner in pixels.
115    x_1: f32,
116
117    /// Y coordinate of the top-left corner in pixels.
118    y_1: f32,
119
120    /// X coordinate of the bottom-right corner in pixels.
121    x_2: f32,
122
123    /// Y coordinate of the bottom-right corner in pixels.
124    y_2: f32,
125
126    /// Width of the sprite in pixels.
127    width: f32,
128
129    /// Height of the sprite in pixels.
130    height: f32,
131}
132
133//---------------------------------------------------------------------------//
134//                           Implementation
135//---------------------------------------------------------------------------//
136
137impl From<TableInMemory> for Atlas {
138    fn from(value: TableInMemory) -> Self {
139        let entries = value.data()
140            .iter()
141            .map(|row| AtlasEntry {
142                string1: if let DecodedData::StringU8(data) = &row[0] { data.to_string() } else { panic!("WTF?!")},
143                string2: if let DecodedData::StringU8(data) = &row[1] { data.to_string() } else { panic!("WTF?!")},
144                x_1: if let DecodedData::F32(data) = row[2] { data } else { panic!("WTF?!")},
145                y_1: if let DecodedData::F32(data) = row[3] { data } else { panic!("WTF?!")},
146                x_2: if let DecodedData::F32(data) = row[4] { data } else { panic!("WTF?!")},
147                y_2: if let DecodedData::F32(data) = row[5] { data } else { panic!("WTF?!")},
148                width: if let DecodedData::F32(data) = row[6] { data } else { panic!("WTF?!")},
149                height: if let DecodedData::F32(data) = row[7] { data } else { panic!("WTF?!")},
150            })
151            .collect();
152
153        Self {
154            version: VERSION as u32,
155            unknown: 0,
156            entries,
157        }
158    }
159}
160
161impl From<Atlas> for TableInMemory {
162    fn from(value: Atlas) -> Self {
163        let mut table = Self::new(&Atlas::definition(), None, "");
164        let data = value.entries.iter()
165            .map(|entry| {
166                 vec![
167                    DecodedData::StringU8(entry.string1.to_owned()),
168                    DecodedData::StringU8(entry.string2.to_owned()),
169                    DecodedData::F32(entry.x_1),
170                    DecodedData::F32(entry.y_1),
171                    DecodedData::F32(entry.x_2),
172                    DecodedData::F32(entry.y_2),
173                    DecodedData::F32(entry.width),
174                    DecodedData::F32(entry.height),
175                ]
176            })
177            .collect::<Vec<_>>();
178        let _ = table.set_data(&data);
179        table
180    }
181}
182
183impl Atlas {
184
185    /// Returns the table schema definition for atlas files.
186    ///
187    /// This definition is used when converting atlas files to/from [`TableInMemory`]
188    /// for TSV export/import functionality.
189    ///
190    /// [`TableInMemory`]: crate::files::table::local::TableInMemory
191    ///
192    /// # Returns
193    ///
194    /// A [`Definition`] with 8 fields matching the [`AtlasEntry`] structure:
195    /// - `string1`, `string2`: String identifiers
196    /// - `x_1`, `y_1`, `x_2`, `y_2`: Coordinate floats
197    /// - `width`, `height`: Dimension floats
198    pub fn definition() -> Definition {
199        let mut definition = Definition::new(VERSION, None);
200        let fields = vec![
201            Field { name: "string1".to_owned(), is_key: true, default_value: Some("PLACEHOLDER".to_owned()), ..Default::default() },
202            Field { name: "string2".to_owned(), is_key: true, default_value: Some("PLACEHOLDER".to_owned()), ..Default::default() },
203            Field { name: "x_1".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
204            Field { name: "y_1".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
205            Field { name: "x_2".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
206            Field { name: "y_2".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
207            Field { name: "width".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
208            Field { name: "height".to_owned(), field_type: FieldType::F32, default_value: Some("0".to_owned()), ..Default::default() },
209        ];
210        definition.set_fields(fields);
211        definition
212    }
213}
214
215impl Decodeable for Atlas {
216
217    fn decode<R: ReadBytes>(data: &mut R, _extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
218        let version = data.read_u32()?;
219        let unknown = data.read_u32()?;
220
221        let mut entries = vec![];
222
223        for _ in 0..data.read_u32()? {
224
225            // The coordinates are stored in percentage of size.
226            entries.push(AtlasEntry {
227                string1: data.read_string_u16_0padded(512)?,
228                string2: data.read_string_u16_0padded(512)?,
229                x_1: data.read_f32()? * IMAGE_SIZE as f32,
230                y_1: data.read_f32()? * IMAGE_SIZE as f32,
231                x_2: data.read_f32()? * IMAGE_SIZE as f32,
232                y_2: data.read_f32()? * IMAGE_SIZE as f32,
233                width: data.read_f32()?,
234                height: data.read_f32()?,
235            })
236        }
237
238        // Trigger an error if there's left data on the source.
239        check_size_mismatch(data.stream_position()? as usize, data.len()? as usize)?;
240
241        Ok(Self {
242            version,
243            unknown,
244            entries
245        })
246    }
247}
248
249impl Encodeable for Atlas {
250
251    fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
252        buffer.write_u32(self.version)?;
253        buffer.write_u32(self.unknown)?;
254        buffer.write_u32(self.entries.len() as u32)?;
255
256        for entry in &self.entries {
257            buffer.write_string_u16_0padded(&entry.string1, 512, true)?;
258            buffer.write_string_u16_0padded(&entry.string2, 512, true)?;
259            buffer.write_f32(entry.x_1 / IMAGE_SIZE as f32)?;
260            buffer.write_f32(entry.y_1 / IMAGE_SIZE as f32)?;
261            buffer.write_f32(entry.x_2 / IMAGE_SIZE as f32)?;
262            buffer.write_f32(entry.y_2 / IMAGE_SIZE as f32)?;
263            buffer.write_f32(entry.width)?;
264            buffer.write_f32(entry.height)?;
265        }
266
267        Ok(())
268    }
269}