/
archive.rs
1233 lines (1086 loc) · 38.6 KB
/
archive.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
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
use crate::{
containers::Bytes,
derive,
fo4::{
self, Chunk, CompressionFormat, DX10Header, Error, File, FileHash, FileHeader, Format,
GNMFHeader, Hash, Result, Version,
},
io::{Endian, Sink, Source},
protocols::WString,
};
use bstr::BString;
use std::io::Write;
mod constants {
use crate::cc;
pub(crate) const MAGIC: u32 = cc::make_four(b"BTDX");
pub(crate) const GNRL: u32 = cc::make_four(b"GNRL");
pub(crate) const DX10: u32 = cc::make_four(b"DX10");
pub(crate) const GNMF: u32 = cc::make_four(b"GNMF");
pub(crate) const HEADER_SIZE_V1: usize = 0x18;
pub(crate) const HEADER_SIZE_V2: usize = 0x20;
pub(crate) const HEADER_SIZE_V3: usize = 0x24;
pub(crate) const FILE_HEADER_SIZE_GNRL: u16 = 0x10;
pub(crate) const FILE_HEADER_SIZE_DX10: u16 = 0x18;
pub(crate) const FILE_HEADER_SIZE_GNMF: u16 = 0x30;
pub(crate) const CHUNK_SIZE_GNRL: usize = 0x14;
pub(crate) const CHUNK_SIZE_DX10: usize = 0x18;
pub(crate) const CHUNK_SIZE_GNMF: usize = 0x18;
pub(crate) const CHUNK_SENTINEL: u32 = 0xBAAD_F00D;
}
struct Offsets {
file_data: usize,
strings: usize,
}
impl Offsets {
#[must_use]
pub fn new(archive: &Archive, options: Options) -> Self {
let chunks_offset = match options.version {
Version::v1 => constants::HEADER_SIZE_V1,
Version::v2 => constants::HEADER_SIZE_V2,
Version::v3 => constants::HEADER_SIZE_V3,
};
let file_data_offset = {
let (file_header_size, chunk_size) = match options.format {
Format::GNRL => (constants::FILE_HEADER_SIZE_GNRL, constants::CHUNK_SIZE_GNRL),
Format::DX10 => (constants::FILE_HEADER_SIZE_DX10, constants::CHUNK_SIZE_DX10),
Format::GNMF => (constants::FILE_HEADER_SIZE_GNMF, constants::CHUNK_SIZE_GNMF),
};
let chunks_count: usize = archive.values().map(File::len).sum();
chunks_offset
+ (archive.len() * usize::from(file_header_size))
+ (chunks_count * chunk_size)
};
let strings_offset = {
let data_size: usize = archive.values().flat_map(File::iter).map(Chunk::len).sum();
file_data_offset + data_size
};
Self {
file_data: file_data_offset,
strings: strings_offset,
}
}
}
struct Header {
version: Version,
format: Format,
file_count: u32,
string_table_offset: u64,
compression_format: CompressionFormat,
}
/// See also [`ArchiveOptions`](Options).
#[derive(Clone, Copy, Debug, Default)]
#[repr(transparent)]
pub struct OptionsBuilder(Options);
impl OptionsBuilder {
#[must_use]
pub fn build(self) -> Options {
self.0
}
#[must_use]
pub fn compression_format(mut self, compression_format: CompressionFormat) -> Self {
self.0.compression_format = compression_format;
self
}
#[must_use]
pub fn format(mut self, format: Format) -> Self {
self.0.format = format;
self
}
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn strings(mut self, strings: bool) -> Self {
self.0.strings = strings;
self
}
#[must_use]
pub fn version(mut self, version: Version) -> Self {
self.0.version = version;
self
}
}
/// Info about the contents of the given archive.
///
/// ```rust
/// use ba2::fo4::{ArchiveOptions, CompressionFormat, Format, Version};
///
/// // Write an archive for FO4/FO76, GNRL format
/// let _ = ArchiveOptions::builder()
/// .format(Format::GNRL)
/// .version(Version::v1)
/// .compression_format(CompressionFormat::Zip)
/// .build();
///
/// // Write an archive for FO4/FO76, DX10 format
/// let _ = ArchiveOptions::builder()
/// .format(Format::DX10)
/// .version(Version::v1)
/// .compression_format(CompressionFormat::Zip)
/// .build();
///
/// // Write an archive for SF, GNRL format
/// let _ = ArchiveOptions::builder()
/// .format(Format::GNRL)
/// .version(Version::v2)
/// .compression_format(CompressionFormat::Zip)
/// .build();
///
/// // Write an archive for SF, DX10 format
/// let _ = ArchiveOptions::builder()
/// .format(Format::DX10)
/// .version(Version::v3)
/// .compression_format(CompressionFormat::LZ4)
/// .build();
/// ```
#[derive(Clone, Copy, Debug, Default)]
pub struct Options {
format: Format,
version: Version,
compression_format: CompressionFormat,
strings: bool,
}
impl Options {
#[must_use]
pub fn builder() -> OptionsBuilder {
OptionsBuilder::new()
}
#[must_use]
pub fn compression_format(&self) -> CompressionFormat {
self.compression_format
}
#[must_use]
pub fn format(&self) -> Format {
self.format
}
#[must_use]
pub fn strings(&self) -> bool {
self.strings
}
#[must_use]
pub fn version(&self) -> Version {
self.version
}
}
derive::key!(Key: FileHash);
impl<'bytes> Key<'bytes> {
#[must_use]
fn hash_in_place(name: &mut BString) -> FileHash {
fo4::hash_file_in_place(name)
}
}
type ReadResult<T> = (T, Options);
derive::archive! {
/// Represents the FO4 revision of the ba2 format.
Archive => ReadResult
Map: (Key: FileHash) => File
}
impl<'bytes> Archive<'bytes> {
pub fn write<Out>(&self, stream: &mut Out, options: &Options) -> Result<()>
where
Out: ?Sized + Write,
{
let mut sink = Sink::new(stream);
let (header, mut offsets) = self.make_header(*options)?;
Self::write_header(&mut sink, &header)?;
for (key, file) in self {
Self::write_file(&mut sink, &header, &mut offsets, key.hash(), file)?;
}
for file in self.values() {
for chunk in file {
sink.write_bytes(chunk.as_bytes())?;
}
}
if options.strings {
for key in self.keys() {
sink.write_protocol::<WString>(key.name(), Endian::Little)?;
}
}
Ok(())
}
fn make_header(&self, options: Options) -> Result<(Header, Offsets)> {
let offsets = Offsets::new(self, options);
Ok((
Header {
version: options.version,
format: options.format,
file_count: self.len().try_into()?,
string_table_offset: if options.strings {
offsets.strings as u64
} else {
0
},
compression_format: options.compression_format,
},
offsets,
))
}
fn write_chunk<Out>(
sink: &mut Sink<Out>,
header: &Header,
offsets: &mut Offsets,
chunk: &Chunk<'bytes>,
) -> Result<()>
where
Out: ?Sized + Write,
{
let data_offset: u64 = offsets.file_data.try_into()?;
offsets.file_data += chunk.len();
let (compressed_size, decompressed_size): (u32, u32) =
if let Some(decompressed_len) = chunk.decompressed_len() {
(chunk.len().try_into()?, decompressed_len.try_into()?)
} else {
(0, chunk.len().try_into()?)
};
sink.write(
&(data_offset, compressed_size, decompressed_size),
Endian::Little,
)?;
match (header.format, &chunk.mips) {
(Format::GNRL, None) => (),
(Format::DX10 | Format::GNMF, Some(mips)) => {
sink.write(&(*mips.start(), *mips.end()), Endian::Little)?;
}
_ => {
return Err(Error::FormatMismatch);
}
}
sink.write(&constants::CHUNK_SENTINEL, Endian::Little)?;
Ok(())
}
fn write_file<Out>(
sink: &mut Sink<Out>,
header: &Header,
offsets: &mut Offsets,
hash: &FileHash,
file: &File<'bytes>,
) -> Result<()>
where
Out: ?Sized + Write,
{
Self::write_hash(sink, hash)?;
let chunk_count: u8 = file.len().try_into()?;
let chunk_size = match header.format {
Format::GNRL => constants::FILE_HEADER_SIZE_GNRL,
Format::DX10 => constants::FILE_HEADER_SIZE_DX10,
Format::GNMF => constants::FILE_HEADER_SIZE_GNMF,
};
sink.write(&(0u8, chunk_count, chunk_size), Endian::Little)?;
match (header.format, &file.header) {
(Format::GNRL, FileHeader::GNRL) => (),
(Format::DX10, FileHeader::DX10(x)) => {
sink.write(
&(
x.height,
x.width,
x.mip_count,
x.format,
x.flags,
x.tile_mode,
),
Endian::Little,
)?;
}
(Format::GNMF, FileHeader::GNMF(x)) => {
sink.write(&x.metadata, Endian::Little)?;
}
(_, _) => {
return Err(Error::FormatMismatch);
}
}
for chunk in file {
Self::write_chunk(sink, header, offsets, chunk)?;
}
Ok(())
}
fn write_hash<Out>(sink: &mut Sink<Out>, hash: &Hash) -> Result<()>
where
Out: ?Sized + Write,
{
sink.write(&(hash.file, hash.extension, hash.directory), Endian::Little)?;
Ok(())
}
fn write_header<Out>(sink: &mut Sink<Out>, header: &Header) -> Result<()>
where
Out: ?Sized + Write,
{
let format = match header.format {
Format::GNRL => constants::GNRL,
Format::DX10 => constants::DX10,
Format::GNMF => constants::GNMF,
};
sink.write(
&(
constants::MAGIC,
header.version as u32,
format,
header.file_count,
header.string_table_offset,
),
Endian::Little,
)?;
if header.version >= Version::v2 {
sink.write(&1u64, Endian::Little)?;
}
if header.version >= Version::v3 {
let format: u32 = match header.compression_format {
CompressionFormat::Zip => 0,
CompressionFormat::LZ4 => 3,
};
sink.write(&format, Endian::Little)?;
}
Ok(())
}
fn do_read<In>(source: &mut In) -> Result<ReadResult<Self>>
where
In: ?Sized + Source<'bytes>,
{
let header = Self::read_header(source)?;
let mut map = Map::default();
let mut strings: usize = header.string_table_offset.try_into()?;
for _ in 0..header.file_count {
let (key, value) = Self::read_file(source, &header, &mut strings)?;
map.insert(key, value);
}
Ok((
Self { map },
Options {
format: header.format,
version: header.version,
compression_format: header.compression_format,
strings: header.string_table_offset != 0,
},
))
}
fn read_chunk<In>(source: &mut In, header: &Header) -> Result<Chunk<'bytes>>
where
In: ?Sized + Source<'bytes>,
{
let (data_offset, compressed_size, decompressed_size): (u64, u32, u32) =
source.read(Endian::Little)?;
let mips = match header.format {
Format::GNRL => None,
Format::DX10 | Format::GNMF => {
let (mip_first, mip_last) = source.read(Endian::Little)?;
Some(mip_first..=mip_last)
}
};
let sentinel = source.read(Endian::Little)?;
if sentinel != constants::CHUNK_SENTINEL {
return Err(Error::InvalidChunkSentinel(sentinel));
}
let bytes = source.save_restore_position(|source| -> Result<Bytes<'bytes>> {
source.seek_absolute(data_offset.try_into()?)?;
let len = if compressed_size == 0 {
decompressed_size
} else {
compressed_size
};
let bytes = source.read_bytes(len as usize)?;
Ok(bytes)
})??;
let decompressed_len = (compressed_size != 0).then_some(decompressed_size as usize);
let bytes = bytes.into_compressable(decompressed_len);
Ok(Chunk { bytes, mips })
}
fn read_file<In>(
source: &mut In,
header: &Header,
strings: &mut usize,
) -> Result<(Key<'bytes>, File<'bytes>)>
where
In: ?Sized + Source<'bytes>,
{
let name = if *strings == 0 {
Bytes::default()
} else {
source.save_restore_position(|source| -> Result<Bytes<'bytes>> {
source.seek_absolute(*strings)?;
let name = source.read_protocol::<WString>(Endian::Little)?;
*strings = source.stream_position();
Ok(name)
})??
};
let hash = Self::read_hash(source)?;
let (_, chunk_count, chunk_size): (u8, u8, u16) = source.read(Endian::Little)?;
if !matches!(
(header.format, chunk_size),
(Format::GNRL, constants::FILE_HEADER_SIZE_GNRL)
| (Format::DX10, constants::FILE_HEADER_SIZE_DX10)
) {
return Err(Error::InvalidChunkSize(chunk_size));
}
let file_header = match header.format {
Format::GNRL => FileHeader::GNRL,
Format::DX10 => {
let (height, width, mip_count, format, flags, tile_mode) =
source.read(Endian::Little)?;
DX10Header {
height,
width,
mip_count,
format,
flags,
tile_mode,
}
.into()
}
Format::GNMF => {
let metadata = source.read(Endian::Little)?;
GNMFHeader { metadata }.into()
}
};
let mut chunks = Vec::with_capacity(chunk_count.into());
for _ in 0..chunk_count {
let chunk = Self::read_chunk(source, header)?;
chunks.push(chunk);
}
Ok((
Key {
hash: hash.into(),
name,
},
File {
chunks,
header: file_header,
},
))
}
fn read_hash<In>(source: &mut In) -> Result<Hash>
where
In: ?Sized + Source<'bytes>,
{
let (file, extension, directory) = source.read(Endian::Little)?;
Ok(Hash {
file,
extension,
directory,
})
}
fn read_header<In>(source: &mut In) -> Result<Header>
where
In: ?Sized + Source<'bytes>,
{
let (magic, version, contents_format, file_count, string_table_offset) =
source.read(Endian::Little)?;
if magic != constants::MAGIC {
return Err(Error::InvalidMagic(magic));
}
let format = match contents_format {
constants::GNRL => Format::GNRL,
constants::DX10 => Format::DX10,
constants::GNMF => Format::GNMF,
_ => return Err(Error::InvalidFormat(contents_format)),
};
let version = match version {
1 => Version::v1,
2 => Version::v2,
3 => Version::v3,
_ => return Err(Error::InvalidVersion(version)),
};
if version >= Version::v2 {
source.read::<u64>(Endian::Little)?;
}
let compression_format = if version >= Version::v3 {
let format: u32 = source.read(Endian::Little)?;
if format == 3 {
CompressionFormat::LZ4
} else {
CompressionFormat::Zip
}
} else {
CompressionFormat::Zip
};
Ok(Header {
version,
format,
file_count,
string_table_offset,
compression_format,
})
}
}
#[cfg(test)]
mod tests {
use crate::{
cc,
fo4::{
Archive, ArchiveKey, ArchiveOptions, CompressionFormat, Error, File, FileHeader,
FileReadOptions, Format, Version,
},
prelude::*,
Borrowed, CompressionResult,
};
use anyhow::Context as _;
use bstr::ByteSlice as _;
use core::mem;
use directxtex::DXGI_FORMAT;
use memmap2::Mmap;
use std::{
ffi::OsString,
fs,
io::{self, Read as _},
path::{Path, PathBuf},
str::FromStr as _,
};
use walkdir::WalkDir;
#[test]
fn default_state() {
let archive = Archive::default();
assert!(archive.is_empty());
assert_eq!(archive.len(), 0);
}
#[test]
fn chunking_strategy() -> anyhow::Result<()> {
let file = {
let options = FileReadOptions::builder()
.format(Format::DX10)
.compression_result(CompressionResult::Compressed)
.build();
File::read(Path::new("data/fo4_chunk_test/test.dds"), &options)
.context("failed to read file")?
};
let FileHeader::DX10(header) = &file.header else {
anyhow::bail!("file was not dx10");
};
assert_eq!(header.mip_count, 11);
assert_eq!(
header.format,
DXGI_FORMAT::DXGI_FORMAT_BC1_UNORM.bits() as u8
);
assert_eq!(file.len(), 3);
let mut index = 0;
let mut next_chunk = || {
let chunk = &file[index];
index += 1;
let Some(mips) = &chunk.mips else {
anyhow::bail!("chunk was missing mips");
};
Ok((chunk, mips))
};
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.decompressed_len(), Some(0x8_0000));
assert_eq!(*mips, 0..=0);
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.decompressed_len(), Some(0x2_0000));
assert_eq!(*mips, 1..=1);
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.decompressed_len(), Some(0xAAB8));
assert_eq!(*mips, 2..=10);
Ok(())
}
#[test]
fn archives_with_compression() -> anyhow::Result<()> {
let root_path = Path::new("data/fo4_compression_test");
for archive_name in ["normal.ba2", "xbox.ba2"] {
let (archive, options) = Archive::read(root_path.join(archive_name).as_path())
.context("failed to read archive")?;
assert_eq!(options.format(), Format::GNRL);
assert_eq!(options.compression_format(), CompressionFormat::Zip);
let root_path = root_path.join("data");
for file_path in WalkDir::new(&root_path) {
if let Ok(file_path) = file_path {
let metadata = file_path.metadata().with_context(|| {
format!(
"failed to get metadata for file path: {:?}",
file_path.path()
)
})?;
if metadata.is_file() {
let key = file_path
.path()
.strip_prefix(&root_path)
.with_context(|| {
format!(
"failed to strip prefix ({root_path:?}) from path ({file_path:?})"
)
})?
.as_os_str();
let file = archive
.get(&ArchiveKey::from(key.as_encoded_bytes()))
.with_context(|| format!("failed to get file with key: {key:?}"))?;
assert_eq!(file.len(), 1);
let chunk = &file[0];
assert!(chunk.is_compressed());
let chunk = chunk.decompress(&Default::default()).with_context(|| {
format!("failed to decompress chunk for file: {file_path:?}")
})?;
assert!(chunk.is_decompressed());
assert_eq!(chunk.len() as u64, metadata.len());
let mut original_data = Vec::new();
fs::File::open(file_path.path())
.with_context(|| format!("failed to open file: {file_path:?}"))?
.read_to_end(&mut original_data)
.with_context(|| format!("failed to read from file: {file_path:?}"))?;
assert_eq!(chunk.len(), original_data.len());
assert_eq!(chunk.as_bytes(), &original_data);
}
}
}
}
Ok(())
}
#[test]
fn files_with_cubemaps() -> anyhow::Result<()> {
let file = {
let options = FileReadOptions::builder()
.format(Format::DX10)
.compression_result(CompressionResult::Compressed)
.build();
File::read(Path::new("data/fo4_cubemap_test/blacksky_e.dds"), &options)
.context("failed to read file")?
};
let FileHeader::DX10(header) = &file.header else {
anyhow::bail!("file was not dx10");
};
assert_eq!(header.mip_count, 10);
assert_eq!(header.flags, 1);
assert_eq!(header.tile_mode, 8);
assert_eq!(file.len(), 1);
let chunk = &file[0];
let Some(mips) = &chunk.mips else {
anyhow::bail!("chunk was missing mips");
};
assert_eq!(*mips, 0..=9);
assert_eq!(chunk.decompressed_len(), Some(0x20_00A0));
Ok(())
}
#[test]
fn read_write_texture_archives() -> anyhow::Result<()> {
let path = Path::new("data/fo4_dds_test/in.ba2");
let original = {
let fd =
fs::File::open(path).with_context(|| format!("failed to open file: {path:?}"))?;
unsafe { Mmap::map(&fd) }
.with_context(|| format!("failed to memory map file: {path:?}"))?
};
let (archive, options) = Archive::read(Borrowed(&original[..]))
.with_context(|| format!("failed to read archive: {path:?}"))?;
assert_eq!(options.compression_format, CompressionFormat::Zip);
assert_eq!(options.format, Format::DX10);
assert_eq!(options.strings, true);
assert_eq!(options.version, Version::v1);
assert_eq!(archive.len(), 1);
let file = archive
.get(&ArchiveKey::from("Fence006_1K_Roughness.dds"))
.context("failed to get file from archive")?;
let FileHeader::DX10(header) = &file.header else {
anyhow::bail!("file header was not dx10");
};
assert_eq!(file.len(), 3);
assert_eq!(header.height, 1024);
assert_eq!(header.width, 1024);
assert_eq!(header.mip_count, 11);
assert_eq!(header.format, 98);
assert_eq!(header.flags, 0);
assert_eq!(header.tile_mode, 8);
let mut idx = 0;
let mut next_chunk = || {
let chunk = &file[idx];
idx += 1;
let Some(mips) = &chunk.mips else {
anyhow::bail!("chunk extra was missing mips");
};
Ok((chunk, mips))
};
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.len(), 0x100_000);
assert_eq!(*mips.start(), 0);
assert_eq!(*mips.end(), 0);
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.len(), 0x40_000);
assert_eq!(*mips.start(), 1);
assert_eq!(*mips.end(), 1);
let (chunk, mips) = next_chunk()?;
assert_eq!(chunk.len(), 0x15_570);
assert_eq!(*mips.start(), 2);
assert_eq!(*mips.end(), 10);
let copy = {
let mut v = Vec::new();
archive
.write(&mut v, &options)
.with_context(|| format!("failed to write archive: {path:?}"))?;
v
};
assert_eq!(original.len(), copy.len());
assert_eq!(&original[..], copy);
Ok(())
}
#[allow(non_camel_case_types, non_snake_case)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DDS_PIXELFORMAT {
dwSize: u32,
dwFlags: u32,
dwFourCC: u32,
dwRGBBitCount: u32,
dwRBitMask: u32,
dwGBitMask: u32,
dwBBitMask: u32,
dwABitMask: u32,
}
#[allow(non_camel_case_types, non_snake_case)]
#[derive(Clone, Copy, Debug)]
struct DDS_HEADER {
dwSize: u32,
dwFlags: u32,
dwHeight: u32,
dwWidth: u32,
dwPitchOrLinearSize: u32,
dwDepth: u32,
dwMipMapCount: u32,
#[allow(unused)]
dwReserved1: [u32; 11],
ddspf: DDS_PIXELFORMAT,
dwCaps: u32,
dwCaps2: u32,
dwCaps3: u32,
dwCaps4: u32,
#[allow(unused)]
dwReserved2: u32,
}
impl Eq for DDS_HEADER {}
impl PartialEq for DDS_HEADER {
fn eq(&self, other: &Self) -> bool {
macro_rules! compare {
($name:ident) => {
self.$name == other.$name
};
}
compare!(dwSize)
&& compare!(dwFlags)
&& compare!(dwHeight)
&& compare!(dwWidth)
&& compare!(dwPitchOrLinearSize)
&& compare!(dwDepth)
&& compare!(dwMipMapCount)
&& compare!(ddspf)
&& compare!(dwCaps)
&& compare!(dwCaps2)
&& compare!(dwCaps3)
&& compare!(dwCaps4)
}
}
#[allow(non_camel_case_types, non_snake_case)]
#[derive(Clone, Copy, Debug)]
struct DDS_HEADER_DXT10 {
dxgiFormat: DXGI_FORMAT,
resourceDimension: u32,
miscFlag: u32,
arraySize: u32,
#[allow(unused)]
miscFlags2: u32,
}
impl Eq for DDS_HEADER_DXT10 {}
impl PartialEq for DDS_HEADER_DXT10 {
fn eq(&self, other: &Self) -> bool {
macro_rules! compare {
($name:ident) => {
self.$name == other.$name
};
}
compare!(dxgiFormat)
&& compare!(resourceDimension)
&& compare!(miscFlag)
&& compare!(arraySize)
}
}
#[allow(non_snake_case)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DDS9Header {
dwMagic: u32,
header: DDS_HEADER,
}
#[allow(non_snake_case)]
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
struct DDS10Header {
header9: DDS9Header,
header10: DDS_HEADER_DXT10,
}
#[test]
fn pack_unpack_texture_archives() -> anyhow::Result<()> {
let root = Path::new("data/fo4_dds_test");
let original = {
let fd = fs::File::open(root.join("in.ba2")).context("failed to open archive")?;
unsafe { Mmap::map(&fd) }.context("failed to map archive")?
};
let (archive, options) =
Archive::read(Borrowed(&original[..])).context("failed to read archive")?;
assert_eq!(options.format(), Format::DX10);
assert_eq!(options.compression_format(), CompressionFormat::Zip);
{
let file_name = "Fence006_1K_Roughness.dds";
let original = {
let fd = fs::File::open(root.join(file_name)).context("failed to open file")?;
unsafe { Mmap::map(&fd) }.context("failed to map file")?
};
let file = {
let from_archive = archive
.get(&ArchiveKey::from(file_name))
.context("failed to get file from archive")?;
assert!(!from_archive.is_empty());
for chunk in from_archive {
assert!(chunk.is_decompressed());
}
let options = FileReadOptions::builder().format(Format::DX10).build();
let from_disk =
File::read(Borrowed(&original), &options).context("failed to read file")?;
assert_eq!(from_disk.header, from_archive.header);
assert_eq!(from_disk.len(), from_archive.len());
for (disk, archived) in from_disk.iter().zip(from_archive) {
assert_eq!(disk.mips, archived.mips);
assert_eq!(disk.as_bytes(), archived.as_bytes());
}
from_archive
};
let copy = {
let mut v = Vec::new();
file.write(&mut v, &Default::default())
.context("failed to write file")?;
v
};
assert_eq!(original.len(), copy.len());
let header_size = mem::size_of::<DDS10Header>();
let get_header = |bytes: &[u8]| unsafe {
bytes[..header_size]
.as_ptr()
.cast::<DDS10Header>()
.read_unaligned()
};
let original_header = get_header(&original[..]);
let copy_header = get_header(©);
assert_eq!(original_header, copy_header);
assert_eq!(&original[header_size..], ©[header_size..]);
}
let copy = {
let mut v = Vec::new();
archive
.write(&mut v, &options)
.context("failed to write archive")?;
v
};
assert_eq!(original.len(), copy.len());
assert_eq!(&original[..], ©);
Ok(())
}
#[test]
fn dx9() -> anyhow::Result<()> {
let root = Path::new("data/fo4_dx9_test");
let file_names = ["dx9.dds", "blacksky_e.dds", "bleakfallscube_e.dds"];
for file_name in file_names {
let original = {
let fd = fs::File::open(root.join(file_name))
.with_context(|| format!("failed to open file: {file_name}"))?;
unsafe { Mmap::map(&fd) }
.with_context(|| format!("failed to map file: {file_name}"))?
};
let copy = {
let options = FileReadOptions::builder().format(Format::DX10).build();
let file = File::read(Borrowed(&original[..]), &options)
.with_context(|| format!("failed to read file: {file_name}"))?;
let mut v = Vec::new();
file.write(&mut v, &Default::default())