rpfm_lib/files/image/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//! Image file handling with DDS conversion support.
12//!
13//! This module provides the [`Image`] type for working with image files in Total War PackFiles.
14//! It stores raw image data and provides automatic conversion of DDS textures to PNG format
15//! for easier viewing and editing.
16//!
17//! # Supported Formats
18//!
19//! The following image formats are recognized:
20//! - **JPEG** (`.jpg`, `.jpeg`) - Standard photo compression
21//! - **PNG** (`.png`) - Lossless compressed images with alpha
22//! - **TGA** (`.tga`) - Targa images (common in game assets)
23//! - **DDS** (`.dds`) - DirectDraw Surface textures (Total War's primary format)
24//! - **GIF** (`.gif`) - Animated or simple images
25//!
26//! # DDS Conversion
27//!
28//! DDS files are automatically converted to PNG format when decoded to enable easier
29//! viewing in standard image viewers and editors. The original DDS data is preserved
30//! for re-encoding.
31//!
32//! The conversion process handles various DDS formats:
33//! - Standard DDS formats supported by the `image` crate
34//! - BC3_UNORM compressed textures via re-compression
35//! - RGBA_U8 color formats
36//!
37//! # Example
38//!
39//! ```ignore
40//! use rpfm_lib::files::{Decodeable, image::Image, DecodeableExtraData};
41//! use std::io::Cursor;
42//!
43//! // Read a DDS texture
44//! let dds_data = std::fs::read("texture.dds").unwrap();
45//! let mut reader = Cursor::new(dds_data);
46//! let mut extra = DecodeableExtraData::default();
47//! extra.set_is_dds(true);
48//! let image = Image::decode(&mut reader, &Some(extra)).unwrap();
49//!
50//! // Access converted PNG data for viewing
51//! if let Some(png_data) = image.converted_data() {
52//! // Display in image viewer
53//! }
54//! ```
55
56use dds::{ColorFormat, Decoder, ImageViewMut};
57use getset::*;
58use image::{ImageFormat, ImageReader, RgbaImage};
59use serde_derive::{Serialize, Deserialize};
60
61use std::io::Cursor;
62
63use crate::binary::{ReadBytes, WriteBytes};
64use crate::error::{Result, RLibError};
65use crate::files::{DecodeableExtraData, Decodeable, EncodeableExtraData, Encodeable};
66
67pub use crate::files::detection::image::EXTENSIONS;
68
69#[cfg(test)] mod image_test;
70
71//---------------------------------------------------------------------------//
72// Enum & Structs
73//---------------------------------------------------------------------------//
74
75/// In-memory representation of an image file.
76///
77/// Stores the raw image data in its original format, plus optionally converted PNG data
78/// for DDS textures. The original data is preserved to allow lossless re-encoding.
79///
80/// # Fields
81///
82/// * `data` - Raw binary data in the original image format
83/// * `converted_data` - For DDS files, PNG-converted data for viewing (optional)
84///
85/// # Getters
86///
87/// Fields have public getters via the `getset` crate:
88/// - `data()` - Get reference to original image data
89/// - `converted_data()` - Get reference to converted PNG data (DDS only)
90///
91/// # DDS Handling
92///
93/// When a DDS file is decoded:
94/// 1. `data` contains the original DDS bytes
95/// 2. `converted_data` contains PNG-converted bytes for display
96/// 3. Encoding writes back the original DDS data from `data`
97///
98/// For non-DDS formats:
99/// 1. `data` contains the image bytes
100/// 2. `converted_data` is `None`
101///
102/// # Example
103///
104/// ```ignore
105/// use rpfm_lib::files::{Decodeable, Encodeable, image::Image};
106/// use std::io::Cursor;
107///
108/// # let png_bytes = vec![137, 80, 78, 71]; // PNG header
109/// let mut reader = Cursor::new(png_bytes);
110/// let image = Image::decode(&mut reader, &None).unwrap();
111///
112/// // Access original data
113/// let original = image.data();
114/// ```
115#[derive(Default, PartialEq, Eq, Clone, Debug, Getters, Serialize, Deserialize)]
116#[getset(get = "pub")]
117pub struct Image {
118 /// Original raw image data in native format.
119 data: Vec<u8>,
120
121 /// PNG-converted data for DDS textures (for viewing/editing).
122 converted_data: Option<Vec<u8>>,
123}
124
125//---------------------------------------------------------------------------//
126// Implementation of Image
127//---------------------------------------------------------------------------//
128
129impl Decodeable for Image {
130
131 fn decode<R: ReadBytes>(data: &mut R, extra_data: &Option<DecodeableExtraData>) -> Result<Self> {
132 let len = data.len()?;
133 let data = data.read_slice(len as usize, false)?;
134 let mut converted_data = None;
135
136 if let Some(extra_data) = extra_data {
137
138 // For dds files, we try to convert them to png instead.
139 if extra_data.is_dds {
140
141 match ImageReader::new(Cursor::new(&data))
142 .with_guessed_format()?
143 .decode() {
144 Ok(image) => {
145 let mut cdata = vec![];
146 image.write_to(&mut Cursor::new(&mut cdata), ImageFormat::Png)?;
147 converted_data = Some(cdata);
148 }
149
150 // If it fails, use the dds crate to decode the raw pixel data and convert directly to PNG.
151 Err(_) => {
152
153 // Decode the data from the file into a single dds texture.
154 let mut decoder = Decoder::new(Cursor::new(&data))?;
155 let size = decoder.main_size();
156 let mut dds_data = vec![0_u8; size.pixels() as usize * 4];
157
158 // This can return None if the format is wrong.
159 if let Some(view) = ImageViewMut::new(&mut dds_data, size, ColorFormat::RGBA_U8) {
160 decoder.read_surface(view)?;
161
162 // Convert the raw RGBA buffer directly to PNG.
163 if let Some(rgba_image) = RgbaImage::from_raw(size.width, size.height, dds_data) {
164 let mut cdata = vec![];
165 rgba_image.write_to(&mut Cursor::new(&mut cdata), ImageFormat::Png)?;
166 converted_data = Some(cdata);
167 } else {
168 return Err(RLibError::DecodingDDSColourFormatUnsupported)
169 }
170 } else {
171 return Err(RLibError::DecodingDDSColourFormatUnsupported)
172 }
173 },
174 }
175 }
176 }
177
178 Ok(Self {
179 data,
180 converted_data,
181 })
182 }
183}
184
185impl Encodeable for Image {
186
187 fn encode<W: WriteBytes>(&mut self, buffer: &mut W, _extra_data: &Option<EncodeableExtraData>) -> Result<()> {
188 buffer.write_all(&self.data).map_err(From::from)
189 }
190}
191
192/// Decodes a mipmap of a DDS texture to RGBA pixels.
193///
194/// # Arguments
195///
196/// * `data` - The DDS file.
197/// * `mipmap` - Level to decode, 0 being the largest. Levels past the last one decode the last one.
198///
199/// # Returns
200///
201/// The pixels of the mipmap.
202///
203/// # Errors
204///
205/// Returns an error if the data is not a DDS texture, or its format can't be decoded.
206pub fn decode_dds_rgba(data: &[u8], mipmap: u32) -> Result<RgbaImage> {
207 let mut decoder = Decoder::new(Cursor::new(data))?;
208 let mipmaps = decoder.layout().texture().map_or(1, |texture| u32::from(texture.mipmaps()));
209
210 for _ in 0..mipmap.min(mipmaps.saturating_sub(1)) {
211 decoder.skip_surface()?;
212 }
213
214 let size = decoder.surface_info().ok_or(RLibError::DecodingDDSColourFormatUnsupported)?.size();
215 let mut pixels = vec![0_u8; size.pixels() as usize * 4];
216 let view = ImageViewMut::new(&mut pixels, size, ColorFormat::RGBA_U8).ok_or(RLibError::DecodingDDSColourFormatUnsupported)?;
217 decoder.read_surface(view)?;
218
219 RgbaImage::from_raw(size.width, size.height, pixels).ok_or(RLibError::DecodingDDSColourFormatUnsupported)
220}