maclarian 0.1.3

Larian file format library for Baldur's Gate 3 - PAK, LSF, LSX, GR2, DDS, and more
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
//! Types for GTS/GTP virtual texture files
//!
//! GTS (Game Texture Set) files contain metadata about virtual textures.
//! GTP (Game Texture Page) files contain the actual tile data.
//!
//!

#![allow(clippy::cast_possible_truncation, clippy::doc_markdown)]

// ============================================================================
// Progress Types (mirrors PAK progress pattern)
// ============================================================================

/// Progress callback type for virtual texture operations
pub type VTexProgressCallback<'a> = &'a (dyn Fn(&VTexProgress) + Sync + Send);

/// Progress information during virtual texture operations
#[derive(Debug, Clone)]
pub struct VTexProgress {
    /// Current operation phase
    pub phase: VTexPhase,
    /// Current item number (1-indexed for consistency with PAK)
    pub current: usize,
    /// Total number of items
    pub total: usize,
    /// Current file or item being processed (if applicable)
    pub current_file: Option<String>,
}

impl VTexProgress {
    /// Create a new progress update
    #[must_use]
    pub fn new(phase: VTexPhase, current: usize, total: usize) -> Self {
        Self {
            phase,
            current,
            total,
            current_file: None,
        }
    }

    /// Create a progress update with a file/item name
    #[must_use]
    pub fn with_file(
        phase: VTexPhase,
        current: usize,
        total: usize,
        file: impl Into<String>,
    ) -> Self {
        Self {
            phase,
            current,
            total,
            current_file: Some(file.into()),
        }
    }

    /// Get the progress percentage (0.0 - 1.0)
    #[must_use]
    pub fn percentage(&self) -> f32 {
        if self.total == 0 {
            1.0
        } else {
            self.current as f32 / self.total as f32
        }
    }
}

/// Phase of virtual texture operation
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VTexPhase {
    // === Extraction phases ===
    /// Reading GTS metadata file
    ReadingMetadata,
    /// Extracting tiles from GTP files
    ExtractingTiles,
    /// Writing DDS output files
    WritingFiles,

    // === Build phases ===
    /// Validating configuration and inputs
    Validating,
    /// Calculating texture geometry and tile layout
    CalculatingGeometry,
    /// Loading and extracting tiles from source DDS
    LoadingTiles,
    /// Deduplicating identical tiles
    Deduplicating,
    /// Compressing tile data
    Compressing,
    /// Writing GTP page files
    WritingGtp,
    /// Writing GTS metadata file
    WritingGts,

    // === Common ===
    /// Operation complete
    Complete,
}

impl VTexPhase {
    /// Get a human-readable description of this phase
    #[must_use]
    pub fn as_str(self) -> &'static str {
        match self {
            // Extraction
            Self::ReadingMetadata => "Reading metadata",
            Self::ExtractingTiles => "Extracting tiles",
            Self::WritingFiles => "Writing files",
            // Build
            Self::Validating => "Validating configuration",
            Self::CalculatingGeometry => "Calculating geometry",
            Self::LoadingTiles => "Loading tiles",
            Self::Deduplicating => "Deduplicating tiles",
            Self::Compressing => "Compressing tiles",
            Self::WritingGtp => "Writing page files",
            Self::WritingGts => "Writing metadata",
            // Common
            Self::Complete => "Complete",
        }
    }
}

// ============================================================================
// GTS/GTP File Types
// ============================================================================

/// GTS codec types
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum GtsCodec {
    /// Uniform color codec.
    Uniform = 0,
    /// YCoCg 4:2:0 color codec.
    Color420 = 1,
    /// Normal map codec.
    Normal = 2,
    /// Raw color data.
    RawColor = 3,
    /// Binary data codec.
    Binary = 4,
    /// Codec 1.5 YCoCg 4:2:0.
    Codec15Color420 = 5,
    /// Codec 1.5 normal map.
    Codec15Normal = 6,
    /// Raw normal data.
    RawNormal = 7,
    /// Half-precision float codec.
    Half = 8,
    /// Block compression codec (BC1-BC7).
    Bc = 9,
    /// Multi-channel codec.
    MultiChannel = 10,
    /// ASTC compression codec.
    Astc = 11,
}

impl GtsCodec {
    /// Converts a u32 value to a `GtsCodec`, if valid.
    #[must_use]
    pub fn from_u32(value: u32) -> Option<Self> {
        match value {
            0 => Some(Self::Uniform),
            1 => Some(Self::Color420),
            2 => Some(Self::Normal),
            3 => Some(Self::RawColor),
            4 => Some(Self::Binary),
            5 => Some(Self::Codec15Color420),
            6 => Some(Self::Codec15Normal),
            7 => Some(Self::RawNormal),
            8 => Some(Self::Half),
            9 => Some(Self::Bc),
            10 => Some(Self::MultiChannel),
            11 => Some(Self::Astc),
            _ => None,
        }
    }
}

/// GTS data types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub(crate) enum GtsDataType {
    R8G8B8Srgb = 0,
    R8G8B8A8Srgb = 1,
    X8Y8Z0Tangent = 2,
    R8G8B8Linear = 3,
    R8G8B8A8Linear = 4,
    X8 = 5,
    X8Y8 = 6,
    X8Y8Z8 = 7,
    X8Y8Z8W8 = 8,
    X16 = 9,
    X16Y16 = 10,
    X16Y16Z16 = 11,
    X16Y16Z16W16 = 12,
    X32 = 13,
    X32Float = 14,
    X32Y32 = 15,
    X32Y32Float = 16,
    X32Y32Z32 = 17,
    X32Y32Z32Float = 18,
    R32G32B32 = 19,
    R32G32B32Float = 20,
    X32Y32Z32W32 = 21,
    X32Y32Z32W32Float = 22,
    R32G32B32A32 = 23,
    R32G32B32A32Float = 24,
    R16G16B16Float = 25,
    R16G16B16A16Float = 26,
}

impl GtsDataType {
    #[must_use]
    pub fn from_u32(value: u32) -> Option<Self> {
        match value {
            0 => Some(Self::R8G8B8Srgb),
            1 => Some(Self::R8G8B8A8Srgb),
            2 => Some(Self::X8Y8Z0Tangent),
            3 => Some(Self::R8G8B8Linear),
            4 => Some(Self::R8G8B8A8Linear),
            5 => Some(Self::X8),
            6 => Some(Self::X8Y8),
            7 => Some(Self::X8Y8Z8),
            8 => Some(Self::X8Y8Z8W8),
            9 => Some(Self::X16),
            10 => Some(Self::X16Y16),
            11 => Some(Self::X16Y16Z16),
            12 => Some(Self::X16Y16Z16W16),
            13 => Some(Self::X32),
            14 => Some(Self::X32Float),
            15 => Some(Self::X32Y32),
            16 => Some(Self::X32Y32Float),
            17 => Some(Self::X32Y32Z32),
            18 => Some(Self::X32Y32Z32Float),
            19 => Some(Self::R32G32B32),
            20 => Some(Self::R32G32B32Float),
            21 => Some(Self::X32Y32Z32W32),
            22 => Some(Self::X32Y32Z32W32Float),
            23 => Some(Self::R32G32B32A32),
            24 => Some(Self::R32G32B32A32Float),
            25 => Some(Self::R16G16B16Float),
            26 => Some(Self::R16G16B16A16Float),
            _ => None,
        }
    }
}

/// Tile compression method
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TileCompression {
    /// No compression (raw data).
    Raw,
    /// LZ4 compression (legacy, read-only support).
    Lz4,
    /// `FastLZ` compression (default for BG3).
    FastLZ,
}

/// GTS file header (156 bytes)
///
/// Many fields are parsed for binary format completeness but not currently used.
/// Fields like `i2`, `i6`, `i7`, `m-s`, `xjj-xmm` are reserved/unknown in BG3 files.
/// Fields like `layers_offset`, `fourcc_list_*`, `thumbnails_offset` contain valid
/// data that could support future features (layer info, metadata, thumbnails).
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct GtsHeader {
    pub magic: u32,
    pub version: u32,
    pub unused: u32,
    pub guid: [u8; 16],
    pub num_layers: u32,
    pub layers_offset: u64,
    pub num_levels: u32,
    pub levels_offset: u64,
    pub tile_width: i32,
    pub tile_height: i32,
    pub tile_border: i32,
    pub i2: u32,
    pub num_flat_tile_infos: u32,
    pub flat_tile_info_offset: u64,
    pub i6: u32,
    pub i7: u32,
    pub num_packed_tile_ids: u32,
    pub packed_tile_ids_offset: u64,
    pub m: u32,
    pub n: u32,
    pub o: u32,
    pub p: u32,
    pub q: u32,
    pub r: u32,
    pub s: u32,
    pub page_size: u32,
    pub num_page_files: u32,
    pub page_file_metadata_offset: u64,
    pub fourcc_list_size: u32,
    pub fourcc_list_offset: u64,
    pub parameter_block_headers_count: u32,
    pub parameter_block_headers_offset: u64,
    pub thumbnails_offset: u64,
    pub xjj: u32,
    pub xkk: u32,
    pub xll: u32,
    pub xmm: u32,
}

impl GtsHeader {
    pub const MAGIC: u32 = 0x4750_5247; // 'GRPG'
}

/// BC codec parameter block (56 bytes)
#[derive(Debug, Clone)]
pub(crate) struct GtsBCParameterBlock {
    pub version: u16,
    pub compression1: [u8; 16],
    pub compression2: [u8; 16],
    pub b: u32,
    pub c1: u8,
    pub c2: u8,
    pub bc_field3: u8,
    pub data_type: u8,
    pub d: u16,
    pub fourcc: u32,
    pub e1: u8,
    pub save_mip: u8,
    pub e3: u8,
    pub e4: u8,
    pub f: u32,
}

impl GtsBCParameterBlock {
    /// Get compression name 1 as string
    #[must_use]
    pub fn compression_name1(&self) -> String {
        let end = self.compression1.iter().position(|&b| b == 0).unwrap_or(16);
        String::from_utf8_lossy(&self.compression1[..end]).to_string()
    }

    /// Get compression name 2 as string
    #[must_use]
    pub fn compression_name2(&self) -> String {
        let end = self.compression2.iter().position(|&b| b == 0).unwrap_or(16);
        String::from_utf8_lossy(&self.compression2[..end]).to_string()
    }

    /// Determine the tile compression method
    #[must_use]
    pub fn get_compression_method(&self) -> TileCompression {
        let name1 = self.compression_name1();
        let name2 = self.compression_name2();

        if (name1 == "fastlz" || name1 == "lz77") && name2 == "fastlz0.1.0" {
            TileCompression::FastLZ
        } else if name1 == "lz4" && name2 == "lz40.1.0" {
            TileCompression::Lz4
        } else {
            TileCompression::Raw
        }
    }
}

/// Uniform codec parameter block (16 bytes)
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct GtsUniformParameterBlock {
    pub version: u16,
    pub a_unused: u16,
    pub width: u32,
    pub height: u32,
    pub data_type: GtsDataType,
}

/// Parameter block data
#[derive(Debug, Clone)]
pub(crate) enum GtsParameterBlock {
    BC(GtsBCParameterBlock),
    #[allow(dead_code)]
    Uniform(GtsUniformParameterBlock),
    Unknown,
}

/// Level info from GTS file
///
/// Parsed for format completeness. Currently tile lookup uses packed tile IDs
/// directly rather than level offsets.
#[derive(Debug, Clone)]
#[allow(dead_code)]
pub(crate) struct GtsLevelInfo {
    /// Width in tiles
    pub width_tiles: u32,
    /// Height in tiles
    pub height_tiles: u32,
    /// Offset to flat tile indices for this level
    pub flat_tile_offset: u64,
    /// Actual width in pixels (extended field, may be 0 for original BG3 files)
    pub width_pixels: u32,
    /// Actual height in pixels (extended field, may be 0 for original BG3 files)
    pub height_pixels: u32,
}

/// Page file metadata
#[derive(Debug, Clone)]
pub(crate) struct GtsPageFileInfo {
    pub filename: String,
    pub num_pages: u32,
}

/// Flat tile info (12 bytes)
#[derive(Debug, Clone)]
pub(crate) struct GtsFlatTileInfo {
    pub page_file_index: u16,
    pub page_index: u16,
    pub chunk_index: u16,
    pub d: u16,
    pub packed_tile_id_index: u32,
}

/// Packed tile ID (decoded from 32-bit value)
#[derive(Debug, Clone)]
pub(crate) struct GtsPackedTileId {
    pub layer: u8,
    pub level: u8,
    pub x: u16,
    pub y: u16,
}

impl GtsPackedTileId {
    #[must_use]
    pub fn from_u32(value: u32) -> Self {
        Self {
            layer: (value & 0xF) as u8,
            level: ((value >> 4) & 0xF) as u8,
            y: ((value >> 8) & 0xFFF) as u16,
            x: (value >> 20) as u16,
        }
    }
}

/// GTP file header (24 bytes)
#[derive(Debug, Clone)]
pub(crate) struct GtpHeader {
    pub magic: u32,
    pub version: u32,
    pub guid: [u8; 16],
}

impl GtpHeader {
    pub const MAGIC: u32 = 0x5041_5247; // 'GRAP' (reads as 'PARG' in little endian)
}

/// GTP chunk header (12 bytes)
#[derive(Debug, Clone)]
pub(crate) struct GtpChunkHeader {
    pub codec: GtsCodec,
    pub parameter_block_id: u32,
    pub size: u32,
}

/// Tile location info for combining
#[derive(Debug, Clone)]
pub(crate) struct TileLocation {
    pub page: u16,
    pub chunk: u16,
    pub x: u16,
    pub y: u16,
}

/// Layer type for virtual textures
///
/// BG3 virtual textures have 3 layers:
/// - Layer 0: BaseMap (color/albedo)
/// - Layer 1: NormalMap (surface normals)
/// - Layer 2: PhysicalMap (roughness/metallic/etc)
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum VirtualTextureLayer {
    /// Color/albedo layer.
    BaseMap = 0,
    /// Surface normal layer.
    NormalMap = 1,
    /// Physical properties layer (roughness/metallic).
    PhysicalMap = 2,
}

impl VirtualTextureLayer {
    /// Converts a layer index to a `VirtualTextureLayer`, if valid.
    #[must_use]
    pub fn from_index(index: u8) -> Option<Self> {
        match index {
            0 => Some(Self::BaseMap),
            1 => Some(Self::NormalMap),
            2 => Some(Self::PhysicalMap),
            _ => None,
        }
    }

    /// Returns the layer type as a string.
    #[must_use]
    pub fn as_str(&self) -> &'static str {
        match self {
            Self::BaseMap => "BaseMap",
            Self::NormalMap => "NormalMap",
            Self::PhysicalMap => "PhysicalMap",
        }
    }
}

/// Output from virtual texture extraction
#[derive(Debug)]
pub struct VirtualTextureOutput {
    /// The texture layer type.
    pub layer: VirtualTextureLayer,
    /// Texture width in pixels.
    pub width: u32,
    /// Texture height in pixels.
    pub height: u32,
    /// Raw RGBA pixel data.
    pub data: Vec<u8>,
}