Skip to main content

dayzmake_core/
paa.rs

1//! Functions for working with PAA files.
2//!
3//! Format (as used by DayZ / Arma 3, verified against engine-loaded files):
4//!
5//! ```text
6//! u16  magic (compression: 0xff01 DXT1, 0xff02 DXT2, 0xff03 DXT3,
7//!             0xff04 DXT4, 0xff05 DXT5, 0x8888 RGBA, 0x4444 ARGB4444,
8//!             0x1555 ARGB1555, 0x8080 AI88)
9//! taggs: 8-byte signature (e.g. "GGATSFFO") + u32 data size + data,
10//!        repeated until a zero byte (which is the low byte of the
11//!        palette length following them)
12//! u16  palette size in bytes (+ palette data if non-zero)
13//! mipmaps: u16 width (bit 0x8000 = LZO compressed) + u16 height +
14//!          3-byte (little endian) data size + data, repeated until a
15//!          zero width
16//! u16 x3 zero terminator
17//! ```
18//!
19//! The mipmaps of the 16-bit formats (`0x4444`, `0x1555`, `0x8080`) are an LZSS stream of
20//! `width * height * 2` bytes followed by a 4-byte checksum, the signed sum of the output bytes.
21
22use std::io::{Error, Read, Seek, SeekFrom, Write};
23
24use byteorder::{LittleEndian, ReadBytesExt, WriteBytesExt};
25#[cfg(feature = "image")]
26use image::{DynamicImage, ImageBuffer, Rgba};
27use linked_hash_map::LinkedHashMap;
28use lzo1x;
29use texpresso::Format;
30
31use crate::error::printable;
32#[cfg(feature = "image")]
33use texpresso::{Algorithm, Params};
34
35const OFFS_TAGG: &str = "GGATSFFO"; // mipmap offsets (16 u32, zero padded)
36
37/// Largest mipmap width or height accepted when reading.
38const MAX_PAA_DIMENSION: usize = 16384;
39
40/// Most mipmaps accepted when reading (real PAAs have at most 16: 16384 down to 1 pixel is 15).
41const MAX_MIPMAPS: usize = 16;
42
43/// Most mipmap bytes accepted in total when reading, after LZO decompression. A tiny file can
44/// otherwise expand to 256 times its size.
45const MAX_PAA_TOTAL: usize = 256 << 20;
46
47/// Longest mipmap the format can store: its length field has 3 bytes.
48const MAX_MIPMAP_STORED: usize = 0x00FF_FFFF;
49
50/// Largest tagg accepted when reading.
51const MAX_TAGG_SIZE: usize = 1 << 20;
52
53/// Reads the data of a tagg without trusting its size.
54fn read_tagg_data<I: Read>(input: &mut I, name: &str) -> Result<Vec<u8>, Error> {
55    let tagg_size = input.read_u32::<LittleEndian>()? as usize;
56    if tagg_size > MAX_TAGG_SIZE {
57        return Err(error!(
58            "PAA tagg '{}' is too large: {tagg_size} bytes.",
59            printable(name)
60        ));
61    }
62    let mut data = Vec::new();
63    input.take(tagg_size as u64).read_to_end(&mut data)?;
64    if data.len() != tagg_size {
65        return Err(error!("Truncated PAA tagg '{}'.", printable(name)));
66    }
67    Ok(data)
68}
69
70/// Decompresses an LZO mipmap. The decompressed size is the format's usual compressed (block)
71/// size for the mipmap dimensions.
72fn decompress_mipmap(
73    compression: &str,
74    mip_data: &[u8],
75    w: u16,
76    h: u16,
77    budget: usize,
78) -> Result<Vec<u8>, Error> {
79    let real_w = (w & 0x7FFF) as usize;
80    let real_h = h as usize;
81    let decompressed_size = match compression {
82        "DXT1" => Format::Bc1.compressed_size(real_w, real_h),
83        "DXT2" | "DXT3" => Format::Bc2.compressed_size(real_w, real_h),
84        "DXT4" | "DXT5" => Format::Bc3.compressed_size(real_w, real_h),
85        _ => {
86            return Err(error!(
87                "LZO compression is only supported for DXT formats, not '{}'",
88                compression
89            ));
90        }
91    };
92    if decompressed_size > mip_data.len().saturating_mul(256) {
93        return Err(error!(
94            "PAA mipmap claims an implausible size: {decompressed_size} bytes from {} bytes.",
95            mip_data.len()
96        ));
97    }
98    if decompressed_size > budget {
99        return Err(error!(
100            "PAA mipmaps are too large: more than {MAX_PAA_TOTAL} bytes in total."
101        ));
102    }
103    let mut decompressed_data = vec![0; decompressed_size];
104    lzo1x::decompress(mip_data, &mut decompressed_data)
105        .map_err(|e| error!("Failed to decompress LZO-compressed mipmap: {:?}", e))?;
106    Ok(decompressed_data)
107}
108
109/// The formats whose mipmaps are an LZSS stream of 2-byte pixels followed by a checksum.
110fn is_packed16(compression: &str) -> bool {
111    matches!(compression, "ARGB4444" | "ARGB1555" | "AI88")
112}
113
114/// Checks a 16-bit format mipmap (its stored bytes: the LZSS stream and the 4 byte checksum) and
115/// returns the decoded pixel bytes, `width * height * 2`.
116fn unpack16(data: &[u8], (w, h): (u16, u16), budget: usize) -> Result<Vec<u8>, Error> {
117    let expected = usize::from(w & 0x7FFF)
118        .checked_mul(usize::from(h))
119        .and_then(|n| n.checked_mul(2))
120        .ok_or_else(|| error!("PAA mipmap is too large."))?;
121    if expected > budget {
122        return Err(error!(
123            "PAA mipmaps are too large: more than {MAX_PAA_TOTAL} bytes in total."
124        ));
125    }
126    let (pixels, used) = crate::lzss::decompress(data, expected, "PAA mipmap")?;
127    let stored = used
128        .checked_add(4)
129        .and_then(|end| data.get(used..end))
130        .and_then(|b| <[u8; 4]>::try_from(b).ok())
131        .ok_or_else(|| error!("Truncated PAA mipmap: the checksum is missing."))?;
132    let stored = i32::from_le_bytes(stored);
133    let computed = crate::lzss::checksum(&pixels);
134    if stored != computed {
135        return Err(error!(
136            "PAA mipmap checksum mismatch: stored {stored}, computed {computed}."
137        ));
138    }
139    Ok(pixels)
140}
141
142/// Reads one mipmap of `size` stored bytes (LZO compressed if bit 15 of the width is set).
143/// `budget` is what is left of the total mipmap size allowed for the file. A compressed mipmap is
144/// decompressed once to check it against the budget; the result is its stored form and the size it
145/// takes when decompressed.
146fn read_mipmap<I: Read>(
147    input: &mut I,
148    compression: &str,
149    (w, h): (u16, u16),
150    size: usize,
151    budget: usize,
152) -> Result<(Mipmap, usize), Error> {
153    // the size field is not trusted for preallocation
154    let mut mip_data = Vec::new();
155    input.take(size as u64).read_to_end(&mut mip_data)?;
156    if mip_data.len() != size {
157        return Err(error!("Truncated PAA mipmap."));
158    }
159    if is_packed16(compression) {
160        if (w & 0x8000) != 0 {
161            return Err(error!(
162                "LZO compression is only supported for DXT formats, not '{compression}'"
163            ));
164        }
165        let len = unpack16(&mip_data, (w, h), budget)?.len();
166        Ok((
167            Mipmap {
168                data: mip_data,
169                lzo: false,
170            },
171            len,
172        ))
173    } else if (w & 0x8000) != 0 {
174        let decompressed = decompress_mipmap(compression, &mip_data, w, h, budget)?.len();
175        Ok((
176            Mipmap {
177                data: mip_data,
178                lzo: true,
179            },
180            decompressed,
181        ))
182    } else if size > budget {
183        Err(error!(
184            "PAA mipmaps are too large: more than {MAX_PAA_TOTAL} bytes in total."
185        ))
186    } else {
187        let len = mip_data.len();
188        Ok((
189            Mipmap {
190                data: mip_data,
191                lzo: false,
192            },
193            len,
194        ))
195    }
196}
197
198/// The size of an uncompressed mipmap of a DXT texture, `None` for other formats.
199fn raw_mipmap_size(compression: &str, width: usize, height: usize) -> Option<usize> {
200    match compression {
201        "DXT1" => Some(Format::Bc1.compressed_size(width, height)),
202        "DXT2" | "DXT3" => Some(Format::Bc2.compressed_size(width, height)),
203        "DXT4" | "DXT5" => Some(Format::Bc3.compressed_size(width, height)),
204        _ => None,
205    }
206}
207
208/// A format a PAA can be created in.
209#[derive(Debug, Clone, Copy, PartialEq, Eq)]
210#[non_exhaustive]
211pub enum PaaFormat {
212    /// DXT1 (BC1), no or 1-bit alpha.
213    Dxt1,
214    /// DXT3 (BC2), explicit 4-bit alpha.
215    Dxt3,
216    /// DXT5 (BC3), interpolated alpha.
217    Dxt5,
218    /// Uncompressed 8-bit RGBA.
219    Rgba,
220}
221
222impl std::str::FromStr for PaaFormat {
223    type Err = Error;
224
225    /// Parses `dxt1`, `dxt3`, `dxt5` or `rgba`, ignoring case.
226    fn from_str(s: &str) -> Result<Self, Error> {
227        match s.to_lowercase().as_str() {
228            "dxt1" => Ok(PaaFormat::Dxt1),
229            "dxt3" => Ok(PaaFormat::Dxt3),
230            "dxt5" => Ok(PaaFormat::Dxt5),
231            "rgba" => Ok(PaaFormat::Rgba),
232            _ => Err(error!("Unsupported PAA compression type for creation: {s}")),
233        }
234    }
235}
236
237impl PaaFormat {
238    /// The compression name the format has in a PAA.
239    #[cfg(feature = "image")]
240    fn name(self) -> &'static str {
241        match self {
242            PaaFormat::Dxt1 => "DXT1",
243            PaaFormat::Dxt3 => "DXT3",
244            PaaFormat::Dxt5 => "DXT5",
245            PaaFormat::Rgba => "RGBA",
246        }
247    }
248}
249
250/// One mipmap: its stored bytes and whether they are an LZO stream.
251#[derive(Debug)]
252struct Mipmap {
253    data: Vec<u8>,
254    lzo: bool,
255}
256
257/// A PAA texture.
258#[derive(Debug)]
259pub struct Paa {
260    /// Tagg sections in file order (name → data).
261    taggs: LinkedHashMap<String, Vec<u8>>,
262    /// Palette data, if the texture is paletted.
263    palette: Option<Vec<u8>>,
264    /// Mipmap data, largest first.
265    mipmaps: Vec<Mipmap>,
266    /// Width of the largest mipmap.
267    width: u16,
268    /// Height of the largest mipmap.
269    height: u16,
270    /// Compression format name (e.g. "DXT5").
271    compression: String,
272}
273
274/// Expands the decoded pixels of a 16-bit format to RGBA.
275#[cfg(feature = "image")]
276fn unpack_pixels(compression: &str, pixels: &[u8]) -> Vec<u8> {
277    let mut rgba = Vec::with_capacity(pixels.len().saturating_mul(2));
278    for &[lo, hi] in pixels.as_chunks::<2>().0 {
279        let v = u16::from_le_bytes([lo, hi]);
280        // a 4 or 5 bit field (at most 31) expanded to 8 bits; the result fits a byte
281        let expand = |field: u16, max: u16| u8::try_from(field * 255 / max).unwrap_or(u8::MAX);
282        match compression {
283            // bits 12 to 15 alpha, then 4 bits each of R, G, B (as ImageToPAA writes it)
284            "ARGB4444" => rgba.extend([
285                expand((v >> 8) & 0xF, 15),
286                expand((v >> 4) & 0xF, 15),
287                expand(v & 0xF, 15),
288                expand(v >> 12, 15),
289            ]),
290            "ARGB1555" => rgba.extend([
291                expand((v >> 10) & 0x1F, 31),
292                expand((v >> 5) & 0x1F, 31),
293                expand(v & 0x1F, 31),
294                if v & 0x8000 == 0 { 0 } else { 255 },
295            ]),
296            _ => rgba.extend([lo, lo, lo, hi]),
297        }
298    }
299    rgba
300}
301
302impl Paa {
303    /// Width of the largest mipmap in pixels.
304    #[must_use]
305    pub fn width(&self) -> u16 {
306        self.width
307    }
308
309    /// Height of the largest mipmap in pixels.
310    #[must_use]
311    pub fn height(&self) -> u16 {
312        self.height
313    }
314
315    /// Compression format name as read from the file, e.g. `"DXT5"`, `"ARGB4444"`, `"ARGB1555"` or `"AI88"`.
316    #[must_use]
317    pub fn compression(&self) -> &str {
318        &self.compression
319    }
320
321    /// Number of mipmaps.
322    #[must_use]
323    pub fn mipmap_count(&self) -> usize {
324        self.mipmaps.len()
325    }
326
327    /// The data of the tagg called `name`, if the file has one.
328    ///
329    /// The mipmap offset tagg (`GGATSFFO`) is not exposed: [`Paa::write`] generates it.
330    #[must_use]
331    pub fn tagg(&self, name: &str) -> Option<&[u8]> {
332        self.taggs.get(name).map(Vec::as_slice)
333    }
334
335    /// Reads a PAA texture.
336    ///
337    /// # Errors
338    ///
339    /// Returns an error if the input is not a supported PAA file or is malformed.
340    pub fn read<I: Read + Seek>(input: &mut I) -> Result<Paa, Error> {
341        // The top-level read function. We seek to the beginning to ensure consistent state,
342        // as this might be called on a stream that has been partially read (e.g. by another
343        // part of the program trying to determine file type).
344        input.seek(SeekFrom::Start(0))?;
345
346        let magic_number = input.read_u16::<LittleEndian>()?;
347        let compression = match magic_number {
348            0xff01 => "DXT1",
349            0xff02 => "DXT2",
350            0xff03 => "DXT3",
351            0xff04 => "DXT4",
352            0xff05 => "DXT5",
353            0x8888 => "RGBA",
354            0x4444 => "ARGB4444",
355            0x1555 => "ARGB1555",
356            0x8080 => "AI88",
357            // the first two bytes of a PNG signature
358            0x5089 => {
359                let mut rest = [0u8; 6];
360                if input.read_exact(&mut rest).is_ok() && rest == *b"NG\r\n\x1a\n" {
361                    return Err(error!(
362                        "This is a PNG file, not a PAA texture; convert it with img2paa."
363                    ));
364                }
365                return Err(error!("Invalid PAA magic number: 0x{:04x}", magic_number));
366            }
367            _ => return Err(error!("Invalid PAA magic number: 0x{:04x}", magic_number)),
368        }
369        .to_string();
370
371        let mut taggs = LinkedHashMap::new();
372        let mut mipmaps = Vec::new();
373        let mut width = 0;
374        let mut height = 0;
375        let mut total = 0usize;
376
377        // Taggs. The section is terminated by a zero byte, which is not
378        // consumed: it is the low byte of the palette size that follows.
379        loop {
380            let mut next_byte = [0u8; 1];
381            if input.read(&mut next_byte)? == 0 {
382                break;
383            }
384            if next_byte[0] == 0 {
385                input.seek(SeekFrom::Current(-1))?;
386                break;
387            }
388            input.seek(SeekFrom::Current(-1))?;
389
390            let mut tagg_name_bytes = [0u8; 8];
391            input.read_exact(&mut tagg_name_bytes)?;
392            let tagg_name = String::from_utf8_lossy(&tagg_name_bytes)
393                .trim_end_matches('\0')
394                .to_string();
395
396            let data = read_tagg_data(input, &tagg_name)?;
397
398            // the writer regenerates the offset tagg; keeping it would write it twice
399            if tagg_name != OFFS_TAGG {
400                taggs.insert(tagg_name, data);
401            }
402        }
403
404        let palette_len = input.read_u16::<LittleEndian>()? as usize;
405        let palette = if palette_len > 0 {
406            let mut pal_data = vec![0; palette_len];
407            input.read_exact(&mut pal_data)?;
408            Some(pal_data)
409        } else {
410            None
411        };
412
413        // Mipmaps
414        loop {
415            let w = match input.read_u16::<LittleEndian>() {
416                Ok(0) | Err(_) => break,
417                Ok(w) => w,
418            };
419            let h = input.read_u16::<LittleEndian>()?;
420
421            let mut size_bytes = [0u8; 3];
422            input.read_exact(&mut size_bytes)?;
423            let size = (size_bytes[0] as usize)
424                | ((size_bytes[1] as usize) << 8)
425                | ((size_bytes[2] as usize) << 16);
426
427            if usize::from(w & 0x7FFF) > MAX_PAA_DIMENSION || usize::from(h) > MAX_PAA_DIMENSION {
428                return Err(error!(
429                    "PAA mipmap dimensions are too large: {} x {}.",
430                    w & 0x7FFF,
431                    h
432                ));
433            }
434
435            if width == 0 {
436                width = w & 0x7FFF;
437            }
438            if height == 0 {
439                height = h;
440            }
441
442            if mipmaps.len() >= MAX_MIPMAPS {
443                return Err(error!("PAA has more than {MAX_MIPMAPS} mipmaps."));
444            }
445            let budget = MAX_PAA_TOTAL.saturating_sub(total);
446            let mip = read_mipmap(input, &compression, (w, h), size, budget)?;
447            total += mip.1;
448            mipmaps.push(mip.0);
449        }
450
451        if mipmaps.is_empty() {
452            return Err(error!("PAA contains no mipmap data."));
453        }
454
455        Ok(Paa {
456            taggs,
457            palette,
458            mipmaps,
459            width,
460            height,
461            compression,
462        })
463    }
464
465    /// Decodes the largest mipmap into an image.
466    ///
467    /// # Errors
468    ///
469    /// Returns an error if the PAA has no image data, the format is unsupported
470    /// or the data does not fit the declared dimensions.
471    #[cfg_attr(docsrs, doc(cfg(feature = "image")))]
472    #[cfg(feature = "image")]
473    pub fn to_dynamic_image(&self) -> Result<DynamicImage, Error> {
474        let Some(first) = self.mipmaps.first() else {
475            return Err(error!("PAA has no image data"));
476        };
477        let decompressed_mipmap;
478        let main_mipmap: &[u8] = if first.lzo {
479            decompressed_mipmap = decompress_mipmap(
480                &self.compression,
481                &first.data,
482                self.width,
483                self.height,
484                MAX_PAA_TOTAL,
485            )?;
486            &decompressed_mipmap
487        } else {
488            &first.data
489        };
490        let width = usize::from(self.width);
491        let height = usize::from(self.height);
492        // the decoded RGBA image is 4 bytes per pixel; hold it to the same bound as the mipmaps
493        // (at most 8192 x 8192 pixels)
494        if width.saturating_mul(height).saturating_mul(4) > MAX_PAA_TOTAL {
495            return Err(error!(
496                "PAA is too large to decode: {width} x {height} pixels."
497            ));
498        }
499
500        if is_packed16(&self.compression) {
501            let pixels = unpack16(main_mipmap, (self.width, self.height), MAX_PAA_TOTAL)?;
502            let rgba = unpack_pixels(&self.compression, &pixels);
503            return Ok(DynamicImage::ImageRgba8(Self::rgba_image(
504                width, height, rgba,
505            )?));
506        }
507
508        let format = match self.compression.as_str() {
509            "DXT1" => Format::Bc1,
510            "DXT2" | "DXT3" => Format::Bc2,
511            "DXT4" | "DXT5" => Format::Bc3,
512            "PAL" => {
513                let palette = self
514                    .palette
515                    .as_ref()
516                    .ok_or_else(|| error!("Paletted PAA without palette data"))?;
517                let mut rgba_data = Vec::with_capacity(width * height * 4);
518                for &index in main_mipmap {
519                    let i = usize::from(index) * 4;
520                    // Palette is BGRA
521                    let Some(&[blue, green, red, alpha]) = palette.get(i..i + 4) else {
522                        return Err(error!("Palette index out of bounds"));
523                    };
524                    rgba_data.push(red);
525                    rgba_data.push(green);
526                    rgba_data.push(blue);
527                    rgba_data.push(alpha);
528                }
529                let img = Self::rgba_image(width, height, rgba_data)?;
530                return Ok(DynamicImage::ImageRgba8(img));
531            }
532            "RGBA" => {
533                if main_mipmap.len() == width * height * 4 {
534                    let img = Self::rgba_image(width, height, main_mipmap.to_vec())?;
535                    return Ok(DynamicImage::ImageRgba8(img));
536                }
537                return Err(error!("Invalid uncompressed RGBA data size"));
538            }
539            _ => {
540                return Err(error!(
541                    "Unsupported PAA compression format: {}",
542                    self.compression
543                ));
544            }
545        };
546
547        if width == 0 || height == 0 {
548            return Err(error!("PAA has no image data"));
549        }
550        // the block decoder indexes the data by the dimensions, so it must hold every block
551        if main_mipmap.len() < format.compressed_size(width, height) {
552            return Err(error!(
553                "PAA mipmap holds {} bytes, but {width} x {height} {} needs {}.",
554                main_mipmap.len(),
555                self.compression,
556                format.compressed_size(width, height)
557            ));
558        }
559        let mut decompressed = vec![0u8; width * height * 4];
560        format.decompress(main_mipmap, width, height, &mut decompressed);
561
562        let img = Self::rgba_image(width, height, decompressed)?;
563        Ok(DynamicImage::ImageRgba8(img))
564    }
565
566    /// Builds an RGBA image, checking that the data fits the dimensions.
567    ///
568    /// # Errors
569    ///
570    /// Returns an error if `data` does not hold `width * height` pixels.
571    #[cfg(feature = "image")]
572    fn rgba_image(
573        width: usize,
574        height: usize,
575        data: Vec<u8>,
576    ) -> Result<ImageBuffer<Rgba<u8>, Vec<u8>>, Error> {
577        let dims = u32::try_from(width).ok().and_then(|w| {
578            u32::try_from(height)
579                .ok()
580                .and_then(|h| ImageBuffer::<Rgba<u8>, Vec<u8>>::from_raw(w, h, data))
581        });
582        dims.ok_or_else(|| error!("Image data does not match dimensions"))
583    }
584
585    /// Encodes an image as a PAA texture, building the mipmap chain down to 4x4.
586    ///
587    /// # Errors
588    ///
589    /// Returns an error for images too large for the format.
590    #[cfg_attr(docsrs, doc(cfg(feature = "image")))]
591    #[cfg(feature = "image")]
592    pub fn from_dynamic_image(img: &DynamicImage, format: PaaFormat) -> Result<Paa, Error> {
593        let mut current = img.to_rgba8();
594        let compression = format.name().to_string();
595
596        // Build the mipmap chain down to 4x4.
597        let mut levels: Vec<ImageBuffer<Rgba<u8>, Vec<u8>>> = vec![current.clone()];
598        loop {
599            let (w, h) = current.dimensions();
600            if w <= 4 || h <= 4 {
601                break;
602            }
603            current = image::imageops::resize(
604                &current,
605                w / 2,
606                h / 2,
607                image::imageops::FilterType::Triangle,
608            );
609            levels.push(current.clone());
610        }
611
612        let params = Params {
613            algorithm: Algorithm::RangeFit,
614            weights: [1.0, 1.0, 1.0],
615            weigh_colour_by_alpha: false,
616        };
617
618        let mut mipmaps = Vec::new();
619        for level in &levels {
620            let (w, h) = level.dimensions();
621            let data = level.as_raw().clone();
622            let mipmap = match compression.as_str() {
623                "DXT1" => {
624                    let mut out = vec![0; Format::Bc1.compressed_size(w as usize, h as usize)];
625                    Format::Bc1.compress(&data, w as usize, h as usize, params, &mut out);
626                    out
627                }
628                "DXT3" => {
629                    let mut out = vec![0; Format::Bc2.compressed_size(w as usize, h as usize)];
630                    Format::Bc2.compress(&data, w as usize, h as usize, params, &mut out);
631                    out
632                }
633                "DXT5" => {
634                    let mut out = vec![0; Format::Bc3.compressed_size(w as usize, h as usize)];
635                    Format::Bc3.compress(&data, w as usize, h as usize, params, &mut out);
636                    out
637                }
638                "RGBA" => data,
639                _ => {
640                    return Err(error!(
641                        "Unsupported PAA compression type for creation: {compression}"
642                    ));
643                }
644            };
645            mipmaps.push(Mipmap {
646                data: mipmap,
647                lzo: false,
648            });
649        }
650
651        let Some(first) = levels.first() else {
652            return Err(error!("no mipmaps were built"));
653        };
654        let (width, height) = first.dimensions();
655        let to_u16 =
656            |dim: u32| u16::try_from(dim).map_err(|_| error!("image too large for PAA: {dim}px"));
657
658        let mut paa = Paa {
659            taggs: LinkedHashMap::new(),
660            palette: None,
661            mipmaps,
662            width: to_u16(width)?,
663            height: to_u16(height)?,
664            compression,
665        };
666        // LZO compress large mipmaps like the engine's own tools do.
667        paa.lzo_compress()?;
668        Ok(paa)
669    }
670
671    /// LZO-compresses the mipmaps wider than 128 pixels of a DXT texture.
672    ///
673    /// A mipmap is replaced by its compressed form only if that is shorter, so the others stay raw
674    /// (and [`Paa::write`] leaves them unmarked). Mipmaps that are already compressed, mipmaps of 128
675    /// pixels or less and textures of other formats are left unchanged; that is not an error, and
676    /// calling this twice has no further effect.
677    ///
678    /// # Errors
679    ///
680    /// Currently never fails; the result leaves room for limits on the compressed size.
681    pub fn lzo_compress(&mut self) -> Result<(), Error> {
682        let (mut width, mut height) = (usize::from(self.width), usize::from(self.height));
683        let compression = self.compression.clone();
684        for mipmap in &mut self.mipmaps {
685            let raw = raw_mipmap_size(&compression, width, height);
686            if let Some(raw) =
687                raw.filter(|&raw| width > 128 && !mipmap.lzo && mipmap.data.len() == raw)
688            {
689                // The stream already ends with the LZO end marker (11 00 00); a byte after it makes
690                // the game reject the mipmap.
691                let compressed = lzo1x::compress(&mipmap.data, lzo1x::CompressLevel::default());
692                if compressed.len() < raw {
693                    mipmap.data = compressed;
694                    mipmap.lzo = true;
695                }
696            }
697            width = (width / 2).max(1);
698            height = (height / 2).max(1);
699        }
700        Ok(())
701    }
702
703    /// Writes the PAA texture.
704    ///
705    /// # Errors
706    ///
707    /// Returns an error on I/O failure or an unsupported compression type.
708    #[expect(
709        clippy::too_many_lines,
710        reason = "one block per PAA section keeps the writer readable"
711    )]
712    pub fn write<O: Write>(&self, output: &mut O) -> Result<(), Error> {
713        let magic_number: u16 = match self.compression.as_str() {
714            "DXT1" => 0xff01,
715            "DXT2" => 0xff02,
716            "DXT3" => 0xff03,
717            "DXT4" => 0xff04,
718            "DXT5" => 0xff05,
719            "RGBA" => 0x8888,
720            // the stored LZSS bytes are written back as they were read
721            "ARGB4444" => 0x4444,
722            "ARGB1555" => 0x1555,
723            "AI88" => 0x8080,
724            _ => {
725                return Err(error!(
726                    "Cannot write PAA compression type '{}'.",
727                    self.compression
728                ));
729            }
730        };
731        for mipmap in &self.mipmaps {
732            if mipmap.data.len() > MAX_MIPMAP_STORED {
733                return Err(error!(
734                    "PAA mipmap of {} bytes is too large: at most {MAX_MIPMAP_STORED} bytes fit its 3-byte length.",
735                    mipmap.data.len()
736                ));
737            }
738        }
739        output.write_u16::<LittleEndian>(magic_number)?;
740
741        for (name, data) in &self.taggs {
742            let mut name_bytes = [0u8; 8];
743            let name = name.as_bytes();
744            if name.len() > 8 {
745                return Err(error!(
746                    "PAA tagg name '{}' is too long (max 8 bytes).",
747                    String::from_utf8_lossy(name)
748                ));
749            }
750            let (name_part, _) = name_bytes.split_at_mut(name.len());
751            name_part.copy_from_slice(name);
752            output.write_all(&name_bytes)?;
753            let size = u32::try_from(data.len())
754                .map_err(|_| error!("tagg data too large: {} bytes", data.len()))?;
755            output.write_u32::<LittleEndian>(size)?;
756            output.write_all(data)?;
757        }
758
759        // Mipmap offset tagg (GGATSFFO): 16 u32 offsets, zero padded.
760        let num_mipmaps = self.mipmaps.len().min(16);
761        let mut offset = 2u32; // magic
762        for (_, data) in &self.taggs {
763            let size = u32::try_from(data.len())
764                .map_err(|_| error!("tagg data too large: {} bytes", data.len()))?;
765            offset += 8 + 4 + size;
766        }
767        offset += 8 + 4 + 64; // offset tagg itself (padded to 16 u32)
768        offset += 2; // palette size
769        if let Some(palette) = &self.palette {
770            let size = u32::try_from(palette.len())
771                .map_err(|_| error!("palette too large: {} bytes", palette.len()))?;
772            offset += size;
773        }
774
775        let mut offsets: Vec<u32> = Vec::new();
776        let mut current_offset = offset;
777        let mut current_width = self.width;
778        let mut current_height = self.height;
779        for mipmap in self.mipmaps.iter().take(num_mipmaps) {
780            offsets.push(current_offset);
781            let size = u32::try_from(mipmap.data.len())
782                .map_err(|_| error!("mipmap too large: {} bytes", mipmap.data.len()))?;
783            current_offset += size + 2 + 2 + 3;
784            if current_width > 1 {
785                current_width /= 2;
786            }
787            if current_height > 1 {
788                current_height /= 2;
789            }
790        }
791        while offsets.len() < 16 {
792            offsets.push(0);
793        }
794
795        output.write_all(OFFS_TAGG.as_bytes())?;
796        output.write_u32::<LittleEndian>((16 * 4) as u32)?;
797        for offset in offsets {
798            output.write_u32::<LittleEndian>(offset)?;
799        }
800
801        // Palette size. The zero doubles as the tagg section terminator.
802        let palette_len = self.palette.as_ref().map_or(0, std::vec::Vec::len);
803        let palette_len = u16::try_from(palette_len)
804            .map_err(|_| error!("palette too large: {palette_len} bytes"))?;
805        output.write_u16::<LittleEndian>(palette_len)?;
806        if let Some(palette) = &self.palette {
807            output.write_all(palette)?;
808        }
809
810        // Mipmaps
811        let mut current_width = self.width;
812        let mut current_height = self.height;
813        for mipmap in &self.mipmaps {
814            let mut w = current_width;
815            if mipmap.lzo {
816                w |= 0x8000; // LZO compressed
817            }
818            output.write_u16::<LittleEndian>(w)?;
819            output.write_u16::<LittleEndian>(current_height)?;
820            let len = u32::try_from(mipmap.data.len())
821                .map_err(|_| error!("mipmap too large: {} bytes", mipmap.data.len()))?;
822            // 3-byte little endian length
823            output.write_all(&len.to_le_bytes()[..3])?;
824            output.write_all(&mipmap.data)?;
825
826            if current_width > 1 {
827                current_width /= 2;
828            }
829            if current_height > 1 {
830                current_height /= 2;
831            }
832        }
833
834        // Terminator
835        output.write_u16::<LittleEndian>(0)?;
836        output.write_u16::<LittleEndian>(0)?;
837        output.write_u16::<LittleEndian>(0)?;
838
839        Ok(())
840    }
841}