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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
//! Virtual texture builder module
//!
//!
//!
//! This module provides functionality for creating virtual textures (GTS/GTP files)
//! from source DDS textures.
//!
//! # Example
//!
//! ```no_run
//! use maclarian::virtual_texture::builder::{VirtualTextureBuilder, SourceTexture};
//!
//! let result = VirtualTextureBuilder::new()
//!     .add_texture(
//!         SourceTexture::new("MyTexture")
//!             .with_base_map("base.dds")
//!             .with_normal_map("normal.dds")
//!     )
//!     .build("output/")?;
//! # Ok::<(), maclarian::error::Error>(())
//! ```

pub(crate) mod compression;
pub mod config;
pub(crate) mod deduplication;
pub(crate) mod geometry;
pub(crate) mod tile_processor;

pub use config::{BcFormat, SourceTexture, TileCompressionPreference, TileSetConfiguration};

use crate::error::{Error, Result};
use crate::virtual_texture::types::{GtsCodec, GtsFlatTileInfo, VTexPhase, VTexProgress};
use crate::virtual_texture::writer::{
    fourcc::build_metadata_tree,
    gtp_writer::{Chunk, GtpWriter},
    gts_writer::{
        GtsWriter, LayerInfo, LevelInfo as GtsLevelInfo, PageFileInfo, create_bc_parameter_block,
    },
};
use rayon::prelude::*;
use std::fs::File;
use std::io::BufWriter;
use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicUsize, Ordering};
use uuid::Uuid;

use self::compression::{CompressedTile, compress_tile};
use self::deduplication::build_dedup_map;
use self::geometry::calculate_geometry;
use self::tile_processor::{DdsTexture, ProcessedTile, extract_tiles_from_dds};

/// Result of building a virtual texture set
#[derive(Debug)]
pub struct BuildResult {
    /// Path to the generated GTS file
    pub gts_path: PathBuf,
    /// Paths to the generated GTP files
    pub gtp_paths: Vec<PathBuf>,
    /// Total number of tiles created
    pub tile_count: usize,
    /// Number of unique tiles (after deduplication)
    pub unique_tile_count: usize,
    /// Total size of all generated files in bytes
    pub total_size_bytes: u64,
}

/// Builder for creating virtual texture sets
pub struct VirtualTextureBuilder {
    config: TileSetConfiguration,
    textures: Vec<SourceTexture>,
    guid: [u8; 16],
    name: Option<String>,
}

impl Default for VirtualTextureBuilder {
    fn default() -> Self {
        Self::new()
    }
}

impl VirtualTextureBuilder {
    /// Create a new builder with default configuration
    #[must_use]
    pub fn new() -> Self {
        let uuid = Uuid::new_v4();
        Self {
            config: TileSetConfiguration::default(),
            textures: Vec::new(),
            guid: *uuid.as_bytes(),
            name: None,
        }
    }

    /// Create a new builder with the specified configuration
    #[must_use]
    pub fn with_config(config: TileSetConfiguration) -> Self {
        let uuid = Uuid::new_v4();
        Self {
            config,
            textures: Vec::new(),
            guid: *uuid.as_bytes(),
            name: None,
        }
    }

    /// Set the name for the output files
    #[must_use]
    pub fn name(mut self, name: impl Into<String>) -> Self {
        self.name = Some(name.into());
        self
    }

    /// Add a texture to the build
    #[must_use]
    pub fn add_texture(mut self, texture: SourceTexture) -> Self {
        self.textures.push(texture);
        self
    }

    /// Set the tile compression preference
    #[must_use]
    pub fn compression(mut self, compression: TileCompressionPreference) -> Self {
        self.config.compression = compression;
        self
    }

    /// Set the tile dimensions
    #[must_use]
    pub fn tile_size(mut self, width: u32, height: u32) -> Self {
        self.config.tile_width = width;
        self.config.tile_height = height;
        self
    }

    /// Enable or disable mip embedding
    #[must_use]
    pub fn embed_mip(mut self, enable: bool) -> Self {
        self.config.embed_mip = enable;
        self
    }

    /// Enable or disable tile deduplication
    #[must_use]
    pub fn deduplicate(mut self, enable: bool) -> Self {
        self.config.deduplicate = enable;
        self
    }

    /// Build the virtual texture set
    ///
    /// # Arguments
    /// * `output_dir` - Directory to write the GTS and GTP files to
    ///
    /// # Errors
    /// Returns an error if validation fails, textures cannot be loaded,
    /// or output files cannot be written.
    pub fn build<P: AsRef<Path>>(self, output_dir: P) -> Result<BuildResult> {
        self.build_with_progress(output_dir, |_| {})
    }

    /// Build the virtual texture set with progress reporting
    ///
    /// # Arguments
    /// * `output_dir` - Directory to write the GTS and GTP files to
    /// * `progress` - Callback function that receives progress updates
    ///
    /// # Errors
    /// Returns an error if validation fails, textures cannot be loaded,
    /// or output files cannot be written.
    pub fn build_with_progress<P, F>(self, output_dir: P, progress: F) -> Result<BuildResult>
    where
        P: AsRef<Path>,
        F: Fn(&VTexProgress) + Send + Sync,
    {
        let output_dir = output_dir.as_ref();

        // Phase: Validate
        progress(&VTexProgress::new(VTexPhase::Validating, 1, 1));
        self.validate()?;

        // Determine output name
        let name = self
            .name
            .as_ref()
            .or_else(|| self.textures.first().map(|t| &t.name))
            .cloned()
            .unwrap_or_else(|| "VirtualTexture".to_string());

        // Create output directory if needed
        std::fs::create_dir_all(output_dir)?;

        // For now, support single texture (first one)
        let texture = &self.textures[0];
        let layers_present = [
            texture.base_map.is_some(),
            texture.normal_map.is_some(),
            texture.physical_map.is_some(),
        ];

        // Phase: Calculate Geometry
        progress(&VTexProgress::new(VTexPhase::CalculatingGeometry, 1, 1));

        // Load first available layer to get dimensions
        let (first_dds, _first_layer_idx) = self.load_first_layer(texture)?;
        let tex_info = (texture.name.clone(), first_dds.width, first_dds.height);

        // Limit mip levels to what's actually in the DDS file
        let geometry = calculate_geometry(
            &[tex_info],
            layers_present,
            &self.config,
            Some(first_dds.mip_count),
        );

        // Phase: Load Tiles
        progress(&VTexProgress::new(VTexPhase::LoadingTiles, 0, 3));

        // Pre-allocate based on estimated total tiles across all layers
        let estimated_tiles: usize = geometry
            .tiles_per_layer
            .iter()
            .map(std::vec::Vec::len)
            .sum();
        let mut all_tiles: Vec<ProcessedTile> = Vec::with_capacity(estimated_tiles);
        let layer_paths = texture.layer_paths();

        // Load DDS textures for each layer
        let mut dds_textures: [Option<DdsTexture>; 3] = [None, None, None];
        for (i, path) in layer_paths.iter().enumerate() {
            if let Some(p) = path {
                progress(&VTexProgress::with_file(
                    VTexPhase::LoadingTiles,
                    i + 1,
                    3,
                    format!("Loading layer {i}"),
                ));
                dds_textures[i] = Some(DdsTexture::load(p)?);
            }
        }

        // Extract tiles from each layer
        for (layer_idx, dds_opt) in dds_textures.iter().enumerate() {
            if let Some(dds) = dds_opt {
                let coords = &geometry.tiles_per_layer[layer_idx];
                if !coords.is_empty() {
                    progress(&VTexProgress::with_file(
                        VTexPhase::LoadingTiles,
                        layer_idx + 1,
                        3,
                        format!("Extracting {} tiles from layer {}", coords.len(), layer_idx),
                    ));
                    let tiles = extract_tiles_from_dds(dds, coords, &self.config)?;
                    all_tiles.extend(tiles);
                }
            }
        }

        let total_tile_count = all_tiles.len();

        // Phase: Deduplicate (build map only - memory efficient)
        progress(&VTexProgress::new(
            VTexPhase::Deduplicating,
            1,
            total_tile_count,
        ));

        let (is_first, unique_idx) = if self.config.deduplicate {
            build_dedup_map(&all_tiles)
        } else {
            // No dedup: all tiles are unique
            let is_first: Vec<bool> = vec![true; all_tiles.len()];
            let unique_idx: Vec<usize> = (0..all_tiles.len()).collect();
            (is_first, unique_idx)
        };

        let unique_tile_count = is_first.iter().filter(|&&x| x).count();

        // Collect indices of unique tiles for parallel compression
        let unique_indices: Vec<usize> = is_first
            .iter()
            .enumerate()
            .filter_map(|(i, &first)| if first { Some(i) } else { None })
            .collect();

        // Phase: Compress (parallelized with rayon, only unique tiles)
        progress(&VTexProgress::new(
            VTexPhase::Compressing,
            0,
            unique_tile_count,
        ));

        let processed = AtomicUsize::new(0);
        let compression = self.config.compression;

        let compressed_unique: Result<Vec<CompressedTile>> = unique_indices
            .par_iter()
            .map(|&idx| {
                let current = processed.fetch_add(1, Ordering::Relaxed) + 1;
                if current % 100 == 0 {
                    progress(&VTexProgress::new(
                        VTexPhase::Compressing,
                        current,
                        unique_tile_count,
                    ));
                }
                compress_tile(&all_tiles[idx].full_data(), compression)
            })
            .collect();

        let compressed_unique = compressed_unique?;
        progress(&VTexProgress::new(
            VTexPhase::Compressing,
            unique_tile_count,
            unique_tile_count,
        ));

        // Phase: Write GTP (streaming - write chunks and track locations)
        progress(&VTexProgress::new(VTexPhase::WritingGtp, 1, 1));

        // Generate hash from GUID for filename (extractor expects Name_HASH.gtp format)
        let gtp_hash = self.guid.iter().fold(String::new(), |mut acc, b| {
            let _ = std::fmt::Write::write_fmt(&mut acc, format_args!("{b:02x}"));
            acc
        });
        let gtp_filename = format!("{name}_{gtp_hash}.gtp");
        let gtp_path = output_dir.join(&gtp_filename);

        let mut gtp_writer = GtpWriter::new(self.guid, self.config.page_size);

        // Determine compression strings from config
        let (compression1, compression2) = self.config.compression.compression_strings();

        // Write unique chunks to GTP and track their locations
        // chunk_locations[unique_idx] = (page_idx, chunk_idx)
        let mut chunk_locations: Vec<(u16, u16)> = Vec::with_capacity(unique_tile_count);

        for compressed in &compressed_unique {
            let chunk = Chunk {
                codec: GtsCodec::Bc,
                parameter_block_id: 0,
                data: compressed.data.clone(),
            };
            let (page_idx, chunk_idx) = gtp_writer.add_chunk(chunk);
            chunk_locations.push((page_idx, chunk_idx));
        }

        // Build flat_tile_infos for ALL tiles (including duplicates)
        // Each tile references the chunk location of its unique counterpart
        let mut flat_tile_infos: Vec<(GtsFlatTileInfo, usize, u32)> =
            Vec::with_capacity(total_tile_count);

        for (i, tile) in all_tiles.iter().enumerate() {
            let u_idx = unique_idx[i];
            let (page_idx, chunk_idx) = chunk_locations[u_idx];

            flat_tile_infos.push((
                GtsFlatTileInfo {
                    page_file_index: 0, // Single GTP file
                    page_index: page_idx,
                    chunk_index: chunk_idx,
                    d: 0,
                    packed_tile_id_index: 0, // Will be set when adding to GTS
                },
                tile.coord.level as usize,
                tile.packed_id,
            ));
        }

        // Write GTP file
        let gtp_file = File::create(&gtp_path)?;
        let mut gtp_buf = BufWriter::new(gtp_file);
        gtp_writer.write(&mut gtp_buf)?;
        drop(gtp_buf);

        // Phase: Write GTS
        progress(&VTexProgress::new(VTexPhase::WritingGts, 1, 1));

        let gts_path = output_dir.join(format!("{name}.gts"));

        let mut gts_writer = GtsWriter::new(
            self.guid,
            self.config.tile_width as i32,
            self.config.tile_height as i32,
            self.config.tile_border as i32,
            self.config.page_size,
        );

        // Add layers
        for (i, present) in layers_present.iter().enumerate() {
            if *present {
                // Data type: 6 = BC3, 12 = BC5, etc.
                let data_type = match i {
                    1 => 12, // Normal map uses BC5
                    _ => 6,  // Base and physical use BC3
                };
                gts_writer.add_layer(LayerInfo { data_type });
            }
        }

        // Add levels
        for level in &geometry.levels {
            gts_writer.add_level(GtsLevelInfo {
                width: level.width_tiles,
                height: level.height_tiles,
                width_pixels: level.width_pixels,
                height_pixels: level.height_pixels,
            });
        }

        // Add parameter block
        let param_block = create_bc_parameter_block(
            compression1,
            compression2,
            6, // BC3 data type
            BcFormat::Bc3.fourcc(),
            self.config.embed_mip,
        );
        gts_writer.add_parameter_block(param_block);

        // Add page file info
        gts_writer.add_page_file(PageFileInfo {
            filename: gtp_filename,
            num_pages: gtp_writer.num_pages(),
            guid: self.guid,
        });

        // Add packed tile IDs and flat tile infos (using tile_mapping for deduplication)
        // First, create entries for unique tiles
        for (mut info, level, packed_id) in flat_tile_infos {
            let packed_idx = gts_writer.add_packed_tile_id(packed_id);
            info.packed_tile_id_index = packed_idx;
            gts_writer.add_flat_tile_info(info, level);
        }

        // Build FourCC metadata
        let layer_info: Vec<(&str, &str)> = layers_present
            .iter()
            .enumerate()
            .filter(|(_, present)| **present)
            .map(|(i, _)| match i {
                0 => ("BaseMap", "BaseColor"),
                1 => ("NormalMap", "NormalMap"),
                2 => ("PhysicalMap", "PhysicalMap"),
                _ => ("Unknown", "Unknown"),
            })
            .collect();

        let fourcc_tree = build_metadata_tree(
            &texture.name,
            geometry.total_width,
            geometry.total_height,
            0, // x offset
            0, // y offset
            &layer_info,
            &self.guid,
        );
        gts_writer.set_fourcc_tree(fourcc_tree);

        // Write GTS file
        let gts_file = File::create(&gts_path)?;
        let mut gts_buf = BufWriter::new(gts_file);
        gts_writer.write(&mut gts_buf)?;
        drop(gts_buf);

        // Calculate total size
        let gts_size = std::fs::metadata(&gts_path)?.len();
        let gtp_size = std::fs::metadata(&gtp_path)?.len();
        let total_size = gts_size + gtp_size;

        progress(&VTexProgress::new(VTexPhase::Complete, 1, 1));

        Ok(BuildResult {
            gts_path,
            gtp_paths: vec![gtp_path],
            tile_count: total_tile_count,
            unique_tile_count,
            total_size_bytes: total_size,
        })
    }

    /// Load the first available layer to get texture dimensions
    fn load_first_layer(&self, texture: &SourceTexture) -> Result<(DdsTexture, usize)> {
        for (i, path) in texture.layer_paths().iter().enumerate() {
            if let Some(p) = path {
                let dds = DdsTexture::load(p)?;
                return Ok((dds, i));
            }
        }
        Err(Error::VirtualTexture(
            "No layers found in texture".to_string(),
        ))
    }

    /// Validate the builder configuration and inputs
    fn validate(&self) -> Result<()> {
        // Validate configuration
        self.config.validate().map_err(Error::VirtualTexture)?;

        // Check if there's at least one texture
        if self.textures.is_empty() {
            return Err(Error::VirtualTexture(
                "No textures added to builder".to_string(),
            ));
        }

        // Check all textures have at least one layer
        for tex in &self.textures {
            if !tex.has_any_layer() {
                return Err(Error::VirtualTexture(format!(
                    "Texture '{}' has no layers defined",
                    tex.name
                )));
            }
        }

        // Validate texture file paths exist
        for tex in &self.textures {
            for (i, path) in tex.layer_paths().iter().enumerate() {
                if let Some(p) = path {
                    if !p.exists() {
                        let layer_name = match i {
                            0 => "base_map",
                            1 => "normal_map",
                            2 => "physical_map",
                            _ => "unknown",
                        };
                        return Err(Error::VirtualTexture(format!(
                            "Texture '{}' {}: file not found: {}",
                            tex.name,
                            layer_name,
                            p.display()
                        )));
                    }
                }
            }
        }

        Ok(())
    }
}