ba2/fo4/
mod.rs

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
#![doc(alias = "fallout 4")]
#![doc(alias = "starfield")]

//! Fallout 4
//!
//! *"Good morning! Vault-Tec calling! ... You can't begin to know how happy I am to finally speak with you. I've been trying for days. It's a matter of utmost urgency, I assure you."*
//!
//! This format is the latest iteration, having debuted with Fallout 4. It primarily uses zlib for compression, but Starfield has introduced lz4 into the mix. Unlike previous formats, texture files are now split into chunks to enable streaming mips at a more granular level.
//!
//! # Reading
//! ```rust
//! use ba2::{
//!     fo4::{Archive, ArchiveKey, FileWriteOptions},
//!     prelude::*,
//! };
//! use std::{fs, path::Path};
//!
//! fn example() -> Option<()> {
//!     let path = Path::new(r"path/to/fallout4/Data/Fallout4 - Interface.ba2");
//!     let (archive, meta) = Archive::read(path).ok()?;
//!     let key: ArchiveKey = b"Interface/HUDMenu.swf".into();
//!     let file = archive.get(&key)?;
//!     let mut dst = fs::File::create("HUDMenu.swf").ok()?;
//!     let options: FileWriteOptions = meta.into();
//!     file.write(&mut dst, &options).ok()?;
//!     Some(())
//! }
//! ```
//!
//! # Writing
//! ```rust
//! use ba2::{
//!     fo4::{Archive, ArchiveKey, ArchiveOptions, Chunk, File},
//!     prelude::*,
//! };
//! use std::fs;
//!
//! fn example() -> Option<()> {
//!     let chunk = Chunk::from_decompressed(b"Hello world!\n");
//!     let file: File = [chunk].into_iter().collect();
//!     let key: ArchiveKey = b"hello.txt".into();
//!     let archive: Archive = [(key, file)].into_iter().collect();
//!     let mut dst = fs::File::create("example.ba2").ok()?;
//!     let options = ArchiveOptions::default();
//!     archive.write(&mut dst, &options).ok()?;
//!     Some(())
//! }
//! ```

mod archive;
mod chunk;
mod file;
mod hashing;

pub use self::{
    archive::{
        Archive, Key as ArchiveKey, Options as ArchiveOptions,
        OptionsBuilder as ArchiveOptionsBuilder,
    },
    chunk::{
        Chunk, CompressionOptions as ChunkCompressionOptions,
        CompressionOptionsBuilder as ChunkCompressionOptionsBuilder,
    },
    file::{
        CapacityError as FileCapacityError, File, Header as FileHeader,
        ReadOptions as FileReadOptions, ReadOptionsBuilder as FileReadOptionsBuilder,
        WriteOptions as FileWriteOptions, WriteOptionsBuilder as FileWriteOptionsBuilder,
        DX10 as DX10Header, GNMF as GNMFHeader,
    },
    hashing::{hash_file, hash_file_in_place, FileHash, Hash},
};

use core::num::TryFromIntError;
use directxtex::HResultError;
use std::io;

#[non_exhaustive]
#[derive(thiserror::Error, Debug)]
pub enum Error {
    #[error("can not compress the given file because it is already compressed")]
    AlreadyCompressed,

    #[error("can not decompress the given file because it is already decompressed")]
    AlreadyDecompressed,

    #[error("buffer failed to decompress to the expected size... expected {expected} bytes, but got {actual} bytes")]
    DecompressionSizeMismatch { expected: usize, actual: usize },

    #[error("error while working with a dds file")]
    DX10(#[from] HResultError),

    #[error("attempted to write in a format that does not match a file/chunk")]
    FormatMismatch,

    #[error("an operation on two integers would have overflowed and corrupted data")]
    IntegralOverflow,

    #[error("an operation on an integer would have truncated and corrupted data")]
    IntegralTruncation,

    #[error("invalid sentinel read from chunk: {0}")]
    InvalidChunkSentinel(u32),

    #[error("invalid chunk size read from file header: {0}")]
    InvalidChunkSize(u16),

    #[error("invalid format read from archive header: {0}")]
    InvalidFormat(u32),

    #[error("invalid magic read from archive header: {0}")]
    InvalidMagic(u32),

    #[error("invalid version read from archive header: {0}")]
    InvalidVersion(u32),

    #[error(transparent)]
    Io(#[from] io::Error),

    #[error(transparent)]
    LZ4(#[from] lzzzz::Error),

    #[error("support for this feature is not yet implemented")]
    NotImplemented,
}

impl From<TryFromIntError> for Error {
    fn from(_: TryFromIntError) -> Self {
        Self::IntegralTruncation
    }
}

pub type Result<T> = core::result::Result<T, Error>;

/// A list of all compression methods supported by the ba2 format.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CompressionFormat {
    /// The default compression format, compatible with all games that utilize the ba2 format.
    #[default]
    Zip,

    /// A more specialized format leveraging lz4's fast decompression to improve streaming time.
    ///
    /// Only compatible with Starfield or later.
    LZ4,
}

/// Specifies the compression level to use when compressing data.
///
/// Only compatible with [`CompressionFormat::Zip`].
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum CompressionLevel {
    /// Fallout 4.
    #[default]
    FO4,

    /// Fallout 4 on the xbox.
    ///
    /// Uses a smaller windows size, but higher a compression level to yield a higher compression ratio.
    FO4Xbox,

    /// Starfield.
    ///
    /// Uses a custom DEFLATE algorithm with zlib wrapper to obtain a good compression ratio.
    SF,
}

impl CompressionLevel {
    /// Fallout 76.
    pub const FO76: Self = Self::FO4;
}

/// Represents the file format for an archive.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum Format {
    /// A GNRL archive can contain any kind of file.
    #[default]
    GNRL,

    /// A DX10 archive can only contain .dds files (Microsoft DirectX).
    DX10,

    /// A GNMF archive can only contain .gnf files (Sony GNM).
    GNMF,
}

/// Indicates the version of an archive.
#[allow(non_camel_case_types)]
#[derive(Clone, Copy, Debug, Default, Eq, Ord, PartialEq, PartialOrd)]
pub enum Version {
    /// Initial format introduced in Fallout 4.
    #[default]
    v1 = 1,

    /// Intoduced in Starfield.
    v2 = 2,

    /// Intoduced in Starfield.
    v3 = 3,

    /// Intoduced in the Fallout 4 next-gen update.
    v7 = 7,

    /// Intoduced in the Fallout 4 next-gen update.
    v8 = 8,
}