Debian Codegraph @

similar/main/piggy.cpp

raw
1 /*
2 * Portions of this file are copyright Rebirth contributors and licensed as
3 * described in COPYING.txt.
4 * Portions of this file are copyright Parallax Software and licensed
5 * according to the Parallax license below.
6 * See COPYING.txt for license details.
7
8 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
9 SOFTWARE CORPORATION ("PARALLAX"). PARALLAX, IN DISTRIBUTING THE CODE TO
10 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
11 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
12 IN USING, DISPLAYING, AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
13 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
14 FREE PURPOSES. IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
15 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES. THE END-USER UNDERSTANDS
16 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
17 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION. ALL RIGHTS RESERVED.
18 */
19
20 /*
21 *
22 * Functions for managing the pig files.
23 *
24 */
25
26 #include <stdio.h>
27 #include <string.h>
28 #include <ranges>
29
30 #include "pstypes.h"
31 #include "strutil.h"
32 #include "inferno.h"
33 #include "gr.h"
34 #include "u_mem.h"
35 #include "iff.h"
36 #include "dxxerror.h"
37 #include "sounds.h"
38 #include "digi.h"
39 #include "bm.h"
40 #include "hash.h"
41 #include "common/2d/bitmap.h"
42 #include "args.h"
43 #include "palette.h"
44 #include "gamepal.h"
45 #include "physfsx.h"
46 #include "rle.h"
47 #include "piggy.h"
48 #include "gamemine.h"
49 #include "textures.h"
50 #include "texmerge.h"
51 #include "paging.h"
52 #include "game.h"
53 #include "text.h"
54 #include "vclip.h"
55 #include "makesig.h"
56 #include "console.h"
57 #include "compiler-cf_assert.h"
58 #include "compiler-range_for.h"
59 #include "d_construct.h"
60 #include "d_range.h"
61 #include "d_zip.h"
62 #include "partial_range.h"
63 #include <memory>
64
65 #if DXX_BUILD_DESCENT == 1
66 #include "custom.h"
67 #include "snddecom.h"
68 #define DEFAULT_PIGFILE_REGISTERED "descent.pig"
69
70 #elif DXX_BUILD_DESCENT == 2
71 #define DEFAULT_PIGFILE_REGISTERED "groupa.pig"
72 #define DEFAULT_PIGFILE_SHAREWARE "d2demo.pig"
73 #define DEFAULT_HAMFILE_REGISTERED "descent2.ham"
74 #define DEFAULT_HAMFILE_SHAREWARE "d2demo.ham"
75
76 #define D1_PALETTE "palette.256"
77
78 #define DEFAULT_SNDFILE ((Piggy_hamfile_version < pig_hamfile_version::_3) ? DEFAULT_HAMFILE_SHAREWARE : (GameArg.SndDigiSampleRate == sound_sample_rate::_22k) ? "descent2.s22" : "descent2.s11")
79
80 enum class pigfile_size : uint32_t
81 {
82 mac_alien1_pigsize = 5013035,
83 mac_alien2_pigsize = 4909916,
84 mac_fire_pigsize = 4969035,
85 mac_groupa_pigsize = 4929684, // also used for mac shareware
86 mac_ice_pigsize = 4923425,
87 mac_water_pigsize = 4832403,
88 };
89
90 namespace dsx {
91
92 #if DXX_USE_EDITOR
93 unsigned Num_aliases;
94 std::array<alias, MAX_ALIASES> alias_list;
95 #endif
96
97 pig_hamfile_version Piggy_hamfile_version;
98 uint8_t Pigfile_initialized;
99
100 char descent_pig_basename[]{D1_PIGFILE};
101
102 }
103 #endif
104
105 namespace {
106
107 static std::unique_ptr<ubyte[]> BitmapBits;
108 static std::unique_ptr<ubyte[]> SoundBits;
109
110 struct SoundFile
111 {
112 std::array<char, 15> name;
113 };
114 }
115
116 #if DXX_BUILD_DESCENT == 2
117 namespace {
118 #endif
119 hashtable AllBitmapsNames;
120 hashtable AllDigiSndNames;
121 enumerated_array<pig_bitmap_offset, MAX_BITMAP_FILES, bitmap_index> GameBitmapOffset;
122 #if DXX_BUILD_DESCENT == 2
123 static std::unique_ptr<uint8_t[]> Bitmap_replacement_data;
124 static std::array<char, FILENAME_LEN> Current_pigfile;
125 }
126 #endif
127
128 unsigned Num_bitmap_files;
129
130 namespace dsx {
131 #if DXX_BUILD_DESCENT == 1
132 bool MacPig; // using the Macintosh pigfile?
133 bool PCSharePig; // using PC Shareware pigfile?
134 #endif
135 std::array<digi_sound, MAX_SOUND_FILES> GameSounds;
136 GameBitmaps_array GameBitmaps;
137 }
138
139 #if DXX_BUILD_DESCENT == 1
140 #define DBM_FLAG_LARGE 128 // Flags added onto the flags struct in b
141
142 static char default_pigfile_registered[]{DEFAULT_PIGFILE_REGISTERED};
143 static
144 #endif
145 enumerated_array<BitmapFile, MAX_BITMAP_FILES, bitmap_index> AllBitmaps;
146 namespace {
147 static std::array<SoundFile, MAX_SOUND_FILES> AllSounds;
148
149 #define DBM_FLAG_ABM 64 // animated bitmap
150
151 static int Piggy_bitmap_cache_size;
152 static int Piggy_bitmap_cache_next;
153 static uint8_t *Piggy_bitmap_cache_data;
154 static enumerated_array<uint8_t, MAX_BITMAP_FILES, bitmap_index> GameBitmapFlags;
155 static enumerated_array<bitmap_index, MAX_BITMAP_FILES, bitmap_index> GameBitmapXlat;
156 static RAIINamedPHYSFS_File Piggy_fp;
157 }
158
159 #if DXX_BUILD_DESCENT == 1
160 #define PIGGY_BUFFER_SIZE (2048*1024)
161 #elif DXX_BUILD_DESCENT == 2
162 #define PIGFILE_ID MAKE_SIG('G','I','P','P') //PPIG
163 #define PIGFILE_VERSION 2
164 #define PIGGY_BUFFER_SIZE (2400*1024)
165 #endif
166 #define PIGGY_SMALL_BUFFER_SIZE (1400*1024) // size of buffer when CGameArg.SysLowMem is set
167
168 ubyte bogus_bitmap_initialized{0};
169 std::array<uint8_t, 64 * 64> bogus_data;
170
171 #if DXX_BUILD_DESCENT == 1
172 grs_bitmap bogus_bitmap;
173 namespace {
174 static std::array<int, MAX_SOUND_FILES> SoundCompressed;
175 }
176 #elif DXX_BUILD_DESCENT == 2
177 #define BM_FLAGS_TO_COPY (BM_FLAG_TRANSPARENT | BM_FLAG_SUPER_TRANSPARENT \
178 | BM_FLAG_NO_LIGHTING | BM_FLAG_RLE | BM_FLAG_RLE_BIG)
179 #endif
180
181 #define DBM_NUM_FRAMES 63
182
183 namespace {
184
185 struct DiskBitmapHeader
186 {
187 char name[8];
188 ubyte dflags; // bits 0-5 anim frame num, bit 6 abm flag
189 ubyte width; // low 8 bits here, 4 more bits in wh_extra
190 ubyte height; // low 8 bits here, 4 more bits in wh_extra
191 #if DXX_BUILD_DESCENT == 2
192 ubyte wh_extra; // bits 0-3 width, bits 4-7 height
193 #endif
194 ubyte flags;
195 ubyte avg_color;
196 int offset;
197 } __pack__;
198 #if DXX_BUILD_DESCENT == 1
199 static_assert(sizeof(DiskBitmapHeader) == 0x11, "sizeof(DiskBitmapHeader) must be 0x11");
200 #elif DXX_BUILD_DESCENT == 2
201 static_assert(sizeof(DiskBitmapHeader) == 0x12, "sizeof(DiskBitmapHeader) must be 0x12");
202
203 #define DISKBITMAPHEADER_D1_SIZE 17 // no wh_extra
204 #endif
205
206 struct DiskSoundHeader
207 {
208 char name[8];
209 int length;
210 int data_length;
211 int offset;
212 } __pack__;
213
214 }
215
216 namespace dsx {
217 namespace {
218 static void piggy_bitmap_page_out_all();
219 #if DXX_BUILD_DESCENT == 2
220
221 /* the inverse of the d2 Textures array, but for the descent 1 pigfile.
222 * "Textures" looks up a d2 bitmap index given a d2 tmap_num.
223 * "d1_tmap_nums" looks up a d1 tmap_num given a d1 bitmap. "-1" means "None".
224 */
225 using d1_tmap_nums_t = std::array<short, 1630>; // 1621 in descent.pig Mac registered
226 static std::unique_ptr<d1_tmap_nums_t> d1_tmap_nums;
227
228 static void free_d1_tmap_nums()
229 {
230 d1_tmap_nums.reset();
231 }
232 #if DXX_USE_EDITOR
233 static int piggy_is_substitutable_bitmap(std::span<const char, 13> name, std::array<char, 32> &subst_name);
234 static void piggy_write_pigfile(std::span<const char, FILENAME_LEN> filename);
235 static void write_int(int i,PHYSFS_File *file);
236 #endif
237 #endif
238 }
239 }
240
241 namespace dcx {
242
243 namespace {
244
245 struct BitmapNameFromHeader
246 {
247 BitmapFile storage;
248 std::span<const char> name;
249 BitmapNameFromHeader(const DiskBitmapHeader &);
250 };
251
252 BitmapNameFromHeader::BitmapNameFromHeader(const DiskBitmapHeader &bmh) :
253 name{
254 (bmh.dflags & DBM_FLAG_ABM)
255 ? (storage = {}, std::span<const char>(storage.name).first(snprintf(storage.name.data(), storage.name.size(), "%.8s#%d", bmh.name, bmh.dflags & DBM_NUM_FRAMES)))
256 : std::span(bmh.name)
257 }
258 {
259 }
260
261 static int piggy_is_needed(const int soundnum)
262 {
263 if (!CGameArg.SysLowMem)
264 return 1;
265 constexpr std::size_t upper_bound = Sounds.size();
266 for (const auto i : AltSounds)
267 {
268 if (i < upper_bound && Sounds[i] == soundnum)
269 return 1;
270 }
271 return 0;
272 }
273
274 /*
275 * reads a DiskSoundHeader structure from a PHYSFS_File
276 */
277 static DiskSoundHeader DiskSoundHeader_read(const NamedPHYSFS_File fp)
278 {
279 DiskSoundHeader dsh{};
280 PHYSFSX_readBytes(fp, dsh.name, 8);
281 dsh.length = PHYSFSX_readInt(fp);
282 dsh.data_length = PHYSFSX_readInt(fp);
283 dsh.offset = PHYSFSX_readInt(fp);
284 return dsh;
285 }
286
287 }
288
289 }
290
291 /*
292 * reads a DiskBitmapHeader structure from a PHYSFS_File
293 */
294 namespace dsx {
295
296 namespace {
297
298 static DiskBitmapHeader DiskBitmapHeader_read(const NamedPHYSFS_File fp)
299 {
300 DiskBitmapHeader dbh{};
301 PHYSFSX_readBytes(fp, dbh.name, 8);
302 dbh.dflags = PHYSFSX_readByte(fp);
303 dbh.width = PHYSFSX_readByte(fp);
304 dbh.height = PHYSFSX_readByte(fp);
305 #if DXX_BUILD_DESCENT == 2
306 dbh.wh_extra = PHYSFSX_readByte(fp);
307 #endif
308 dbh.flags = PHYSFSX_readByte(fp);
309 dbh.avg_color = PHYSFSX_readByte(fp);
310 dbh.offset = PHYSFSX_readInt(fp);
311 return dbh;
312 }
313
314 #if DXX_BUILD_DESCENT == 2
315 /*
316 * reads a descent 1 DiskBitmapHeader structure from a PHYSFS_File
317 */
318 static DiskBitmapHeader DiskBitmapHeader_d1_read(const NamedPHYSFS_File fp)
319 {
320 DiskBitmapHeader dbh{};
321 PHYSFSX_readBytes(fp, dbh.name, 8);
322 dbh.dflags = PHYSFSX_readByte(fp);
323 dbh.width = PHYSFSX_readByte(fp);
324 dbh.height = PHYSFSX_readByte(fp);
325 dbh.flags = PHYSFSX_readByte(fp);
326 dbh.avg_color = PHYSFSX_readByte(fp);
327 dbh.offset = PHYSFSX_readInt(fp);
328 return dbh;
329 }
330 #endif
331
332 }
333
334 bitmap_index piggy_register_bitmap(grs_bitmap &bmp, const std::span<const char> name, const int in_file)
335 {
336 assert(Num_bitmap_files < AllBitmaps.size());
337 const bitmap_index temp{static_cast<uint16_t>(Num_bitmap_files)};
338
339 if (!in_file) {
340 #if DXX_BUILD_DESCENT == 2
341 #if DXX_USE_EDITOR
342 if ( GameArg.EdiMacData )
343 swap_0_255(bmp);
344 #endif
345 #endif
346 if (CGameArg.DbgNoCompressPigBitmap)
347 gr_bitmap_rle_compress(bmp);
348 }
349
350 auto &abn = AllBitmaps[temp].name;
351 std::memcpy(abn.data(), name.data(), std::min(abn.size() - 1, name.size()));
352 abn.back() = 0;
353 hashtable_insert(&AllBitmapsNames, AllBitmaps[temp].name.data(), Num_bitmap_files);
354 #if DXX_BUILD_DESCENT == 1
355 GameBitmaps[temp] = bmp;
356 #endif
357 if ( !in_file ) {
358 GameBitmapOffset[temp] = pig_bitmap_offset::None;
359 GameBitmapFlags[temp] = bmp.get_flags();
360 }
361 Num_bitmap_files++;
362
363 return temp;
364 }
365
366 int piggy_register_sound(digi_sound &snd, const std::span<const char> name)
367 {
368 int i;
369
370 Assert( Num_sound_files < MAX_SOUND_FILES );
371
372 auto &asn = AllSounds[Num_sound_files].name;
373 std::memcpy(asn.data(), name.data(), std::min(asn.size() - 1, name.size()));
374 asn.back() = 0;
375 hashtable_insert(&AllDigiSndNames, asn.data(), Num_sound_files);
376 auto &gs = GameSounds[Num_sound_files];
377 gs = std::move(snd);
378 #if DXX_BUILD_DESCENT == 1
379 //added/moved on 11/13/99 by Victor Rachels to ready for changing freq
380 //#ifdef ALLEGRO
381 GameSounds[Num_sound_files].freq = snd.freq;
382
383 #endif
384 i = Num_sound_files;
385 Num_sound_files++;
386 return i;
387 }
388
389 bitmap_index piggy_find_bitmap(const std::span<const char> entry_name)
390 {
391 auto name = entry_name;
392 #if DXX_BUILD_DESCENT == 2 && DXX_USE_EDITOR
393 size_t namelen;
394 const auto t = strchr(name.data(), '#');
395 if (t != nullptr)
396 namelen = t - name.data();
397 else
398 namelen = strlen(name.data());
399
400 std::array<char, FILENAME_LEN> temp;
401 range_for (auto &i, partial_const_range(alias_list, Num_aliases))
402 if (i.alias_name[namelen] == 0 && d_strnicmp(name.data(), i.alias_name.data(), namelen) == 0)
403 {
404 if (t) { //extra stuff for ABMs
405 const auto path = d_splitpath(i.file_name.data());
406 snprintf(temp.data(), temp.size(), "%.*s%s\n", DXX_ptrdiff_cast_int(path.base_end - path.base_start), path.base_start, t);
407 name = temp;
408 }
409 else
410 name = i.file_name;
411 break;
412 }
413 #endif
414
415 const auto i = hashtable_search(&AllBitmapsNames, name.data());
416 Assert( i != 0 );
417 if ( i < 0 )
418 return bitmap_index{};
419 return bitmap_index{static_cast<uint16_t>(i)};
420 }
421
422 }
423
424 int piggy_find_sound(const std::span<const char> name)
425 {
426 const auto i = hashtable_search(&AllDigiSndNames, name.data());
427 if ( i < 0 )
428 return 255;
429 return i;
430 }
431
432 namespace dsx {
433
434 namespace {
435
436 static void piggy_close_file()
437 {
438 if (Piggy_fp)
439 {
440 Piggy_fp.reset();
441 #if DXX_BUILD_DESCENT == 2
442 Current_pigfile[0] = 0;
443 #endif
444 }
445 }
446 }
447
448 #if DXX_BUILD_DESCENT == 1
449 properties_init_result properties_init(d_level_shared_robot_info_state &LevelSharedRobotInfoState)
450 {
451 int sbytes{0};
452 int N_sounds;
453 int size;
454 GameSounds = {};
455
456 static_assert(GameBitmapXlat.size() == GameBitmaps.size(), "size mismatch");
457 for (const uint16_t i : xrange(std::size(GameBitmaps)))
458 {
459 const bitmap_index bi{i};
460 GameBitmapXlat[bi] = bi;
461 GameBitmaps[bi].set_flags(BM_FLAG_PAGED_OUT);
462 }
463
464 if ( !bogus_bitmap_initialized ) {
465 ubyte c;
466 bogus_bitmap_initialized = 1;
467 c = gr_find_closest_color( 0, 0, 63 );
468 bogus_data.fill(c);
469 c = gr_find_closest_color( 63, 0, 0 );
470 // Make a big red X !
471 range_for (const unsigned i, xrange(64u))
472 {
473 bogus_data[i*64+i] = c;
474 bogus_data[i*64+(63-i)] = c;
475 }
476 gr_init_bitmap(bogus_bitmap, bm_mode::linear, 0, 0, 64, 64, 64, bogus_data.data());
477 piggy_register_bitmap(bogus_bitmap, "bogus", 1);
478 #ifdef ALLEGRO
479 bogus_sound.len = 64*64;
480 #else
481 bogus_sound.length = 64*64;
482 #endif
483 bogus_sound.data = digi_sound::allocated_data{bogus_data.data(), game_sound_offset{INT_MAX}};
484 //added on 11/13/99 by Victor Rachels to ready for changing freq
485 bogus_sound.freq = 11025;
486 //end this section addition - VR
487 GameBitmapOffset[(bitmap_index{0})] = pig_bitmap_offset::None;
488 }
489
490 Piggy_fp = PHYSFSX_openReadBuffered_updateCase(default_pigfile_registered).first;
491 if (!Piggy_fp)
492 {
493 if (!PHYSFS_exists("BITMAPS.TBL") && !PHYSFS_exists("BITMAPS.BIN"))
494 Error("Cannot find " DEFAULT_PIGFILE_REGISTERED " or BITMAPS.TBL");
495 return properties_init_result::use_gamedata_read_tbl; // need to run gamedata_read_tbl
496 }
497
498 unsigned Pigdata_start;
499 switch (descent1_pig_size{PHYSFS_fileLength(Piggy_fp)}) {
500 case descent1_pig_size::d1_share_big_pigsize:
501 case descent1_pig_size::d1_share_10_pigsize:
502 case descent1_pig_size::d1_share_pigsize:
503 PCSharePig = true;
504 Pigdata_start = 0;
505 break;
506 case descent1_pig_size::d1_10_big_pigsize:
507 case descent1_pig_size::d1_10_pigsize:
508 Pigdata_start = 0;
509 break;
510 default:
511 Warning_puts("Unknown size for " DEFAULT_PIGFILE_REGISTERED);
512 Int3();
513 [[fallthrough]];
514 case descent1_pig_size::d1_mac_pigsize:
515 case descent1_pig_size::d1_mac_share_pigsize:
516 MacPig = true;
517 [[fallthrough]];
518 case descent1_pig_size::d1_pigsize:
519 case descent1_pig_size::d1_oem_pigsize:
520 Pigdata_start = PHYSFSX_readInt(Piggy_fp );
521 break;
522 }
523
524 HiresGFXAvailable = MacPig; // for now at least
525
526 properties_init_result retval;
527 static char bitmaps_bin_basename[]{"bitmaps.bin"};
528
529 if (PCSharePig)
530 retval = properties_init_result::shareware; // run gamedata_read_tbl in shareware mode
531 else if (GameArg.EdiNoBm || (!PHYSFS_exists("BITMAPS.TBL") && !PHYSFSX_exists_ignorecase(bitmaps_bin_basename)))
532 {
533 properties_read_cmp(LevelSharedRobotInfoState, Vclip, Piggy_fp); // Note connection to above if!!!
534 range_for (auto &i, GameBitmapXlat)
535 {
536 const auto bi = GameBitmapXlat.valid_index(PHYSFSX_readSLE16(Piggy_fp));
537 i = bi ? *bi : bitmap_index::None;
538 if (PHYSFS_eof(Piggy_fp))
539 break;
540 }
541 retval = properties_init_result::skip_gamedata_read_tbl; // don't run gamedata_read_tbl
542 }
543 else
544 retval = properties_init_result::use_gamedata_read_tbl; // run gamedata_read_tbl
545
546 PHYSFS_seek(Piggy_fp, Pigdata_start);
547 size = PHYSFS_fileLength(Piggy_fp) - Pigdata_start;
548
549 const unsigned N_bitmaps = PHYSFSX_readInt(Piggy_fp);
550 size -= sizeof(int);
551 N_sounds = PHYSFSX_readInt(Piggy_fp);
552 size -= sizeof(int);
553
554 const unsigned header_size = (N_bitmaps * sizeof(DiskBitmapHeader)) + (N_sounds * sizeof(DiskSoundHeader));
555
556 for (const unsigned i : xrange(N_bitmaps))
557 {
558 const auto bmh = DiskBitmapHeader_read(Piggy_fp);
559 const bitmap_index bi{static_cast<uint16_t>(i + 1)};
560 GameBitmapFlags[bi] = bmh.flags & (BM_FLAG_TRANSPARENT | BM_FLAG_SUPER_TRANSPARENT | BM_FLAG_NO_LIGHTING | BM_FLAG_RLE);
561
562 GameBitmapOffset[bi] = static_cast<pig_bitmap_offset>(bmh.offset + header_size + (sizeof(int)*2) + Pigdata_start);
563 Assert( (i+1) == Num_bitmap_files );
564
565 //size -= sizeof(DiskBitmapHeader);
566 const BitmapNameFromHeader bitmap_name(bmh);
567 const auto &temp_name = bitmap_name.name;
568
569 grs_bitmap temp_bitmap{};
570 const auto iwidth = (bmh.dflags & DBM_FLAG_LARGE) ? bmh.width + 256 : bmh.width;
571 gr_init_bitmap(temp_bitmap, bm_mode::linear, 0, 0,
572 iwidth, bmh.height,
573 iwidth, Piggy_bitmap_cache_data);
574 temp_bitmap.add_flags(BM_FLAG_PAGED_OUT);
575 #if !DXX_USE_OGL
576 temp_bitmap.avg_color = bmh.avg_color;
577 #endif
578
579 if (MacPig)
580 {
581 // HACK HACK HACK!!!!!
582 if (!d_strnicmp(bmh.name, "cockpit") || !d_strnicmp(bmh.name, "status") || !d_strnicmp(bmh.name, "rearview")) {
583 temp_bitmap.bm_w = temp_bitmap.bm_rowsize = 640;
584 if (auto &f = GameBitmapFlags[bi]; f & BM_FLAG_RLE)
585 f |= BM_FLAG_RLE_BIG;
586 }
587 if (!d_strnicmp(bmh.name, "cockpit") || !d_strnicmp(bmh.name, "rearview"))
588 temp_bitmap.bm_h = 480;
589 }
590
591 piggy_register_bitmap(temp_bitmap, temp_name, 1);
592 }
593
594 if (!MacPig)
595 {
596 for (unsigned i = 0; i < N_sounds; ++i)
597 {
598 const auto sndh = DiskSoundHeader_read(Piggy_fp);
599
600 //size -= sizeof(DiskSoundHeader);
601 digi_sound temp_sound;
602 temp_sound.length = sndh.length;
603
604 //added on 11/13/99 by Victor Rachels to ready for changing freq
605 temp_sound.freq = 11025;
606 //end this section addition - VR
607 const game_sound_offset sound_offset{static_cast<int>(sndh.offset + header_size + (sizeof(int)*2)+Pigdata_start)};
608 temp_sound.data = digi_sound::allocated_data{nullptr, sound_offset};
609 if (PCSharePig)
610 SoundCompressed[Num_sound_files] = sndh.data_length;
611 piggy_register_sound(temp_sound, std::span(sndh.name).first<8>());
612 sbytes += sndh.length;
613 }
614
615 SoundBits = std::make_unique<ubyte[]>(sbytes + 16);
616 }
617
618 #if 1 //def EDITOR
619 Piggy_bitmap_cache_size = size - header_size - sbytes + 16;
620 Assert( Piggy_bitmap_cache_size > 0 );
621 #else
622 Piggy_bitmap_cache_size = PIGGY_BUFFER_SIZE;
623 if (CGameArg.SysLowMem)
624 Piggy_bitmap_cache_size = PIGGY_SMALL_BUFFER_SIZE;
625 #endif
626 BitmapBits = std::make_unique<ubyte[]>(Piggy_bitmap_cache_size);
627 Piggy_bitmap_cache_data = BitmapBits.get();
628 Piggy_bitmap_cache_next = 0;
629
630 return retval;
631 }
632 #elif DXX_BUILD_DESCENT == 2
633
634 //initialize a pigfile, reading headers
635 //returns the size of all the bitmap data
636 void piggy_init_pigfile(const std::span<const char> filename)
637 {
638 int i;
639 int header_size, N_bitmaps;
640 #if DXX_USE_EDITOR
641 int data_size;
642 #endif
643
644 piggy_close_file(); //close old pig if still open
645
646 auto &&[fp, physfserr] = PHYSFSX_openReadBuffered(filename.data());
647 #if !DXX_USE_EDITOR
648 auto effective_filename = filename.data();
649 #endif
650 //try pigfile for shareware
651 if (!fp)
652 {
653 auto &&[fp2, physfserr2] = PHYSFSX_openReadBuffered(DEFAULT_PIGFILE_SHAREWARE);
654 if (!fp2)
655 {
656 #if DXX_USE_EDITOR
657 static_cast<void>(physfserr);
658 static_cast<void>(physfserr2);
659 return; //if editor, ok to not have pig, because we'll build one
660 #else
661 Error("Failed to open required files <%s>, <" DEFAULT_PIGFILE_SHAREWARE ">: \"%s\", \"%s\"", filename.data(), PHYSFS_getErrorByCode(physfserr), PHYSFS_getErrorByCode(physfserr2));
662 #endif
663 }
664 fp = std::move(fp2);
665 #if !DXX_USE_EDITOR
666 effective_filename = DEFAULT_PIGFILE_SHAREWARE;
667 #endif
668 }
669 Piggy_fp = std::move(fp);
670 if (Piggy_fp) { //make sure pig is valid type file & is up-to-date
671 int pig_id,pig_version;
672
673 pig_id = PHYSFSX_readInt(Piggy_fp);
674 pig_version = PHYSFSX_readInt(Piggy_fp);
675 if (pig_id != PIGFILE_ID || pig_version != PIGFILE_VERSION) {
676 Piggy_fp.reset(); //out of date pig
677 //..so pretend it's not here
678 #if DXX_USE_EDITOR
679 return; //if editor, ok to not have pig, because we'll build one
680 #else
681 Error("Cannot load PIG file: expected (id=%.8lx version=%.8x), found (id=%.8x version=%.8x) in \"%s\"", PIGFILE_ID, PIGFILE_VERSION, pig_id, pig_version, effective_filename);
682 #endif
683 }
684 }
685
686 std::copy_n(filename.data(), std::min(filename.size(), std::size(Current_pigfile) - 1), Current_pigfile.begin());
687
688 N_bitmaps = PHYSFSX_readInt(Piggy_fp);
689
690 header_size = N_bitmaps * sizeof(DiskBitmapHeader);
691
692 const unsigned data_start = header_size + PHYSFS_tell(Piggy_fp);
693 #if DXX_USE_EDITOR
694 data_size = PHYSFS_fileLength(Piggy_fp) - data_start;
695 #endif
696 Num_bitmap_files = 1;
697
698 for (i=0; i<N_bitmaps; i++ )
699 {
700 int width;
701 const bitmap_index bi{static_cast<uint16_t>(i + 1)};
702 grs_bitmap *const bm = &GameBitmaps[bi];
703
704 const auto bmh = DiskBitmapHeader_read(Piggy_fp);
705 const BitmapNameFromHeader bitmap_name(bmh);
706 const auto &temp_name = bitmap_name.name;
707 width = bmh.width + (static_cast<short>(bmh.wh_extra & 0x0f) << 8);
708 gr_init_bitmap(*bm, bm_mode::linear, 0, 0, width, bmh.height + (static_cast<short>(bmh.wh_extra & 0xf0) << 4), width, NULL);
709 bm->set_flags(BM_FLAG_PAGED_OUT);
710 #if !DXX_USE_OGL
711 bm->avg_color = bmh.avg_color;
712 #endif
713
714 GameBitmapFlags[bi] = bmh.flags & BM_FLAGS_TO_COPY;
715 GameBitmapOffset[bi] = pig_bitmap_offset{bmh.offset + data_start};
716 Assert( (i+1) == Num_bitmap_files );
717 piggy_register_bitmap(*bm, temp_name, 1);
718 }
719
720 #if DXX_USE_EDITOR
721 Piggy_bitmap_cache_size = data_size + (data_size/10); //extra mem for new bitmaps
722 Assert( Piggy_bitmap_cache_size > 0 );
723 #else
724 Piggy_bitmap_cache_size = PIGGY_BUFFER_SIZE;
725 if (CGameArg.SysLowMem)
726 Piggy_bitmap_cache_size = PIGGY_SMALL_BUFFER_SIZE;
727 #endif
728 BitmapBits = std::make_unique<ubyte[]>(Piggy_bitmap_cache_size);
729 Piggy_bitmap_cache_data = BitmapBits.get();
730 Piggy_bitmap_cache_next = 0;
731
732 Pigfile_initialized=1;
733 }
734
735 //reads in a new pigfile (for new palette)
736 //returns the size of all the bitmap data
737 void piggy_new_pigfile(const std::span<char, FILENAME_LEN> pigname)
738 {
739 int header_size, N_bitmaps;
740 #if DXX_USE_EDITOR
741 int must_rewrite_pig{0};
742 #endif
743
744 d_strlwr(pigname.data());
745
746 if (strcmp(Current_pigfile.data(), pigname.data()) == 0 // correct pig already loaded
747 && !Bitmap_replacement_data) // no need to reload: no bitmaps were altered
748 return;
749
750 if (!Pigfile_initialized) { //have we ever opened a pigfile?
751 piggy_init_pigfile(pigname); //..no, so do initialization stuff
752 return;
753 }
754 else
755 piggy_close_file(); //close old pig if still open
756
757 Piggy_bitmap_cache_next = 0; //free up cache
758
759 std::copy_n(pigname.data(), std::min(pigname.size(), std::size(Current_pigfile) - 1), Current_pigfile.begin());
760
761 auto &&[fp, physfserr] = PHYSFSX_openReadBuffered(pigname.data());
762 #if !DXX_USE_EDITOR
763 const char *effective_filename = pigname.data();
764 #endif
765 //try pigfile for shareware
766 if (!fp)
767 {
768 if (auto &&[fp2, physfserr2] = PHYSFSX_openReadBuffered(DEFAULT_PIGFILE_SHAREWARE); fp2)
769 fp = std::move(fp2);
770 else
771 {
772 if constexpr (DXX_USE_EDITOR)
773 {
774 static_cast<void>(physfserr);
775 static_cast<void>(physfserr2);
776 }
777 else
778 Error("Failed to open required files <%s>, <" DEFAULT_PIGFILE_SHAREWARE ">: \"%s\", \"%s\"", pigname.data(), PHYSFS_getErrorByCode(physfserr), PHYSFS_getErrorByCode(physfserr2));
779 /* In an editor build, a pig can be built. In a non-editor build,
780 * Error was fatal.
781 */
782 return;
783 }
784 #if !DXX_USE_EDITOR
785 effective_filename = DEFAULT_PIGFILE_SHAREWARE;
786 #endif
787 }
788 Piggy_fp = std::move(fp);
789 if (Piggy_fp) { //make sure pig is valid type file & is up-to-date
790 int pig_id,pig_version;
791
792 pig_id = PHYSFSX_readInt(Piggy_fp);
793 pig_version = PHYSFSX_readInt(Piggy_fp);
794 if (pig_id != PIGFILE_ID || pig_version != PIGFILE_VERSION) {
795 Piggy_fp.reset(); //out of date pig
796 //..so pretend it's not here
797 #if DXX_USE_EDITOR
798 return; //if editor, ok to not have pig, because we'll build one
799 #else
800 Error("Cannot load PIG file: expected (id=%.8lx version=%.8x), found (id=%.8x version=%.8x) in \"%s\"", PIGFILE_ID, PIGFILE_VERSION, pig_id, pig_version, effective_filename);
801 #endif
802 }
803 N_bitmaps = PHYSFSX_readInt(Piggy_fp);
804
805 header_size = N_bitmaps * sizeof(DiskBitmapHeader);
806
807 const unsigned data_start = header_size + PHYSFS_tell(Piggy_fp);
808
809 for (unsigned i = 1; i <= N_bitmaps; ++i)
810 {
811 const bitmap_index bi{static_cast<uint16_t>(i)};
812 grs_bitmap *const bm = &GameBitmaps[bi];
813 int width;
814
815 const auto bmh = DiskBitmapHeader_read(Piggy_fp);
816 const BitmapNameFromHeader bitmap_name(bmh);
817 const auto &temp_name = bitmap_name.name;
818 auto &abn = AllBitmaps[bi];
819 #if DXX_USE_EDITOR
820 //Make sure name matches
821 if (strcmp(temp_name.data(), abn.name.data()))
822 {
823 //Int3(); //this pig is out of date. Delete it
824 must_rewrite_pig=1;
825 }
826 #endif
827 abn = {};
828 std::copy(temp_name.begin(), temp_name.end(), abn.name.begin());
829
830 width = bmh.width + (static_cast<short>(bmh.wh_extra & 0x0f) << 8);
831 gr_set_bitmap_data(*bm, NULL); // free ogl texture
832 gr_init_bitmap(*bm, bm_mode::linear, 0, 0, width, bmh.height + (static_cast<short>(bmh.wh_extra & 0xf0) << 4), width, NULL);
833 bm->set_flags(BM_FLAG_PAGED_OUT);
834 #if !DXX_USE_OGL
835 bm->avg_color = bmh.avg_color;
836 #endif
837
838 GameBitmapFlags[bi] = bmh.flags & BM_FLAGS_TO_COPY;
839 GameBitmapOffset[bi] = pig_bitmap_offset{bmh.offset + data_start};
840 }
841 }
842 else
843 N_bitmaps = 0; //no pigfile, so no bitmaps
844
845 #if !DXX_USE_EDITOR
846
847 Assert(N_bitmaps == Num_bitmap_files-1);
848
849 #else
850
851 if (must_rewrite_pig || (N_bitmaps < Num_bitmap_files-1)) {
852 int size;
853
854 //re-read the bitmaps that aren't in this pig
855
856 for (unsigned i = N_bitmaps + 1; i < Num_bitmap_files; ++i)
857 {
858 const bitmap_index bi{static_cast<uint16_t>(i)};
859 auto &abn = AllBitmaps[bi].name;
860 if (const auto p = strchr(abn.data(), '#'))
861 { // this is an ABM == animated bitmap
862 char abmname[FILENAME_LEN];
863 unsigned fnum;
864 snprintf(abmname, sizeof(abmname), "%.*s.abm", static_cast<int>(std::min<std::ptrdiff_t>(p - abn.data(), 8)), abn.data());
865
866 auto read_result = iff_read_animbrush(abmname);
867 auto &bm = read_result.bm;
868 auto &newpal = read_result.palette;
869 const auto nframes = read_result.n_bitmaps;
870 if (const auto iff_error{read_result.status}; iff_error != iff_status_code::no_error)
871 {
872 Error("File %s - IFF error: %s",abmname,iff_errormsg(iff_error));
873 }
874 for (fnum=0;fnum<nframes; fnum++) {
875 int SuperX;
876
877 //SuperX = (GameBitmaps[i+fnum].bm_flags&BM_FLAG_SUPER_TRANSPARENT)?254:-1;
878 const bitmap_index bfi{static_cast<uint16_t>(i + fnum)};
879 SuperX = (GameBitmapFlags[bfi] & BM_FLAG_SUPER_TRANSPARENT) ? 254 : -1;
880 //above makes assumption that supertransparent color is 254
881
882 gr_remap_bitmap_good(*bm[fnum].get(), newpal, iff_has_transparency ? iff_transparent_color : -1, SuperX);
883
884 #if !DXX_USE_OGL
885 bm[fnum]->avg_color = compute_average_pixel(bm[fnum].get());
886 #endif
887
888 if ( GameArg.EdiMacData )
889 swap_0_255(*bm[fnum].get());
890
891 if (CGameArg.DbgNoCompressPigBitmap)
892 gr_bitmap_rle_compress(*bm[fnum].get());
893
894 if (bm[fnum]->get_flag_mask(BM_FLAG_RLE))
895 size = *reinterpret_cast<const int *>(bm[fnum]->bm_data);
896 else
897 size = bm[fnum]->bm_w * bm[fnum]->bm_h;
898
899 memcpy( &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next],bm[fnum]->bm_data,size);
900 d_free(bm[fnum]->bm_mdata);
901 bm[fnum]->bm_mdata = &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next];
902 Piggy_bitmap_cache_next += size;
903
904 GameBitmaps[bfi] = std::move(*bm[fnum]);
905 }
906
907 i += nframes-1; //filled in multiple bitmaps
908 }
909 else { //this is a BBM
910
911 grs_bitmap n;
912 palette_array_t newpal;
913 char bbmname[FILENAME_LEN];
914 int SuperX;
915
916 snprintf(bbmname, sizeof(bbmname), "%.8s.bbm", abn.data());
917 if (const auto iff_error{iff_read_bitmap(bbmname, n, &newpal)}; iff_error != iff_status_code::no_error)
918 {
919 Error("File %s - IFF error: %s",bbmname,iff_errormsg(iff_error));
920 }
921
922 SuperX = (GameBitmapFlags[bi] & BM_FLAG_SUPER_TRANSPARENT) ? 254 : -1;
923 //above makes assumption that supertransparent color is 254
924
925 gr_remap_bitmap_good(n, newpal, iff_has_transparency ? iff_transparent_color : -1, SuperX);
926
927 #if !DXX_USE_OGL
928 n.avg_color = compute_average_pixel(&n);
929 #endif
930
931 if ( GameArg.EdiMacData )
932 swap_0_255(n);
933
934 if (CGameArg.DbgNoCompressPigBitmap)
935 gr_bitmap_rle_compress(n);
936
937 if (n.get_flag_mask(BM_FLAG_RLE))
938 size = *reinterpret_cast<const int *>(n.bm_data);
939 else
940 size = n.bm_w * n.bm_h;
941
942 memcpy( &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next],n.bm_data,size);
943 d_free(n.bm_mdata);
944 n.bm_mdata = &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next];
945 Piggy_bitmap_cache_next += size;
946 GameBitmaps[bi] = std::move(n);
947 }
948 }
949
950 //@@Dont' do these things which are done when writing
951 //@@for (i=0; i < Num_bitmap_files; i++ ) {
952 //@@ bitmap_index bi;
953 //@@ bi.index = i;
954 //@@ PIGGY_PAGE_IN( bi );
955 //@@}
956 //@@
957 //@@piggy_close_file();
958
959 piggy_write_pigfile(pigname);
960
961 Current_pigfile[0] = 0; //say no pig, to force reload
962
963 piggy_new_pigfile(pigname); //read in just-generated pig
964
965
966 }
967 #endif //ifdef EDITOR
968 }
969
970 #define HAMFILE_ID MAKE_SIG('!','M','A','H') //HAM!
971 #define HAMFILE_VERSION 3
972 //version 1 -> 2: save marker_model_num
973 //version 2 -> 3: removed sound files
974
975 #define SNDFILE_ID MAKE_SIG('D','N','S','D') //DSND
976 #define SNDFILE_VERSION 1
977
978 int read_hamfile(d_level_shared_robot_info_state &LevelSharedRobotInfoState)
979 {
980 int ham_id;
981 int sound_offset{0};
982 int shareware{0};
983
984 auto ham_fp = PHYSFSX_openReadBuffered(DEFAULT_HAMFILE_REGISTERED).first;
985
986 if (!ham_fp)
987 {
988 ham_fp = PHYSFSX_openReadBuffered(DEFAULT_HAMFILE_SHAREWARE).first;
989 if (ham_fp)
990 {
991 shareware = 1;
992 GameArg.SndDigiSampleRate = sound_sample_rate::_11k;
993 if (CGameArg.SndDisableSdlMixer)
994 {
995 digi_close();
996 digi_init();
997 }
998 }
999 }
1000
1001 if (!ham_fp) {
1002 return 0;
1003 }
1004
1005 //make sure ham is valid type file & is up-to-date
1006 ham_id = PHYSFSX_readInt(ham_fp);
1007 /* All code checks only that Piggy_hamfile_version is `< 3` or `! ( < 3 )`,
1008 * so clamp any version higher than 3 to just 3.
1009 */
1010 Piggy_hamfile_version = static_cast<pig_hamfile_version>(std::clamp(PHYSFSX_readInt(ham_fp), 0, 3));
1011 if (ham_id != HAMFILE_ID)
1012 Error("Failed to load ham file " DEFAULT_HAMFILE_REGISTERED ": expected ham_id=%.8lx, found ham_id=%.8x version=%.8x\n", HAMFILE_ID, ham_id, underlying_value(Piggy_hamfile_version));
1013
1014 if (Piggy_hamfile_version < pig_hamfile_version::_3) // hamfile contains sound info, probably PC demo
1015 {
1016 sound_offset = PHYSFSX_readInt(ham_fp);
1017
1018 if (shareware) // deal with interactive PC demo
1019 {
1020 GameArg.GfxSkipHiresGFX = 1;
1021 //CGameArg.SysLowMem = 1;
1022 }
1023 }
1024
1025 #if 1 //ndef EDITOR
1026 {
1027 bm_read_all(LevelSharedRobotInfoState, Vclip, ham_fp);
1028 range_for (auto &i, GameBitmapXlat)
1029 {
1030 const auto bi = GameBitmapXlat.valid_index(PHYSFSX_readSLE16(ham_fp));
1031 i = bi ? *bi : bitmap_index::None;
1032 if (PHYSFS_eof(ham_fp))
1033 break;
1034 }
1035 }
1036 #endif
1037
1038 if (Piggy_hamfile_version < pig_hamfile_version::_3) {
1039 int N_sounds;
1040 int sound_start;
1041 int header_size;
1042 int i;
1043 int sbytes{0};
1044 static int justonce = 1;
1045
1046 if (!justonce)
1047 {
1048 return 1;
1049 }
1050 justonce = 0;
1051
1052 PHYSFS_seek(ham_fp, sound_offset);
1053 N_sounds = PHYSFSX_readInt(ham_fp);
1054
1055 sound_start = PHYSFS_tell(ham_fp);
1056
1057 header_size = N_sounds * sizeof(DiskSoundHeader);
1058
1059 //Read sounds
1060
1061 for (i=0; i<N_sounds; i++ ) {
1062 const auto sndh = DiskSoundHeader_read(ham_fp);
1063 digi_sound temp_sound;
1064 temp_sound.length = sndh.length;
1065 const game_sound_offset sound_offset{sndh.offset + header_size + sound_start};
1066 temp_sound.data = digi_sound::allocated_data{nullptr, sound_offset};
1067 piggy_register_sound(temp_sound, std::span(sndh.name).first<8>());
1068 if (piggy_is_needed(i))
1069 sbytes += sndh.length;
1070 }
1071 SoundBits = std::make_unique<ubyte[]>(sbytes + 16);
1072 }
1073 return 1;
1074 }
1075
1076 void read_sndfile(const int required)
1077 {
1078 int snd_id,snd_version;
1079 int N_sounds;
1080 int sound_start;
1081 int header_size;
1082 int i;
1083 int sbytes{0};
1084
1085 const auto filename{DEFAULT_SNDFILE};
1086 auto &&[snd_fp, physfserr] = PHYSFSX_openReadBuffered(filename);
1087 if (!snd_fp)
1088 {
1089 if (required)
1090 Error("Cannot open sound file: %s: %s", filename, PHYSFS_getErrorByCode(physfserr));
1091 return;
1092 }
1093
1094 //make sure soundfile is valid type file & is up-to-date
1095 snd_id = PHYSFSX_readInt(snd_fp);
1096 snd_version = PHYSFSX_readInt(snd_fp);
1097 if (snd_id != SNDFILE_ID || snd_version != SNDFILE_VERSION) {
1098 if (required)
1099 Error("Cannot load sound file: expected (id=%.8lx version=%.8x), found (id=%.8x version=%.8x) in \"%s\"", SNDFILE_ID, SNDFILE_VERSION, snd_id, snd_version, filename);
1100 return;
1101 }
1102
1103 N_sounds = PHYSFSX_readInt(snd_fp);
1104
1105 sound_start = PHYSFS_tell(snd_fp);
1106 header_size = N_sounds*sizeof(DiskSoundHeader);
1107
1108 //Read sounds
1109
1110 for (i=0; i<N_sounds; i++ ) {
1111 const auto sndh = DiskSoundHeader_read(snd_fp);
1112 digi_sound temp_sound;
1113 temp_sound.length = sndh.length;
1114 const game_sound_offset sound_offset{sndh.offset + header_size + sound_start};
1115 temp_sound.data = digi_sound::allocated_data{nullptr, sound_offset};
1116 piggy_register_sound(temp_sound, std::span(sndh.name).first<8>());
1117 if (piggy_is_needed(i))
1118 sbytes += sndh.length;
1119 }
1120 SoundBits = std::make_unique<ubyte[]>(sbytes + 16);
1121 }
1122
1123 properties_init_result properties_init(d_level_shared_robot_info_state &LevelSharedRobotInfoState)
1124 {
1125 int ham_ok{0},snd_ok=0;
1126 GameSounds = {};
1127 for (const uint16_t i : xrange(std::size(GameBitmapXlat)))
1128 {
1129 const bitmap_index bi{i};
1130 GameBitmapXlat[bi] = bi;
1131 }
1132
1133 if ( !bogus_bitmap_initialized ) {
1134 ubyte c;
1135
1136 bogus_bitmap_initialized = 1;
1137 c = gr_find_closest_color( 0, 0, 63 );
1138 bogus_data.fill(c);
1139 c = gr_find_closest_color( 63, 0, 0 );
1140 // Make a big red X !
1141 range_for (const unsigned i, xrange(64u))
1142 {
1143 bogus_data[i*64+i] = c;
1144 bogus_data[i*64+(63-i)] = c;
1145 }
1146 const bitmap_index bi{static_cast<uint16_t>(Num_bitmap_files)};
1147 gr_init_bitmap(GameBitmaps[bi], bm_mode::linear, 0, 0, 64, 64, 64, bogus_data.data());
1148 piggy_register_bitmap(GameBitmaps[bi], "bogus", 1);
1149 bogus_sound.length = 64*64;
1150 bogus_sound.data = digi_sound::allocated_data{bogus_data.data(), game_sound_offset{INT_MAX}};
1151 GameBitmapOffset[(bitmap_index{0})] = pig_bitmap_offset::None;
1152 }
1153
1154 snd_ok = ham_ok = read_hamfile(LevelSharedRobotInfoState);
1155
1156 if (Piggy_hamfile_version >= pig_hamfile_version::_3)
1157 {
1158 read_sndfile(1);
1159 }
1160
1161 return (ham_ok && snd_ok) ? properties_init_result::success : properties_init_result::failure; //read ok
1162 }
1163 #endif
1164
1165 #if DXX_BUILD_DESCENT == 1
1166 void piggy_read_sounds(int pc_shareware)
1167 {
1168 uint8_t * ptr;
1169 int i;
1170
1171 if (MacPig)
1172 {
1173 // Read Mac sounds converted to RAW format (too messy to read them directly from the resource fork code-wise)
1174 char soundfile[32] = "Sounds/sounds.array";
1175 // hack for Mac Demo
1176 if (auto array = PHYSFSX_openReadBuffered(soundfile).first)
1177 {
1178 /* Sounds.size() is the D2-compatible size, but this
1179 * statement must read a D1 length, so use MAX_SOUNDS.
1180 */
1181 if (PHYSFSX_readBytes(array, Sounds, MAX_SOUNDS) != MAX_SOUNDS) // make the 'Sounds' index array match with the sounds we're about to read in
1182 {
1183 con_printf(CON_URGENT,"Warning: Can't read Sounds/sounds.array: %s", PHYSFS_getLastError());
1184 return;
1185 }
1186 }
1187 else if (descent1_pig_size{PHYSFSX_fsize(default_pigfile_registered)} == descent1_pig_size::d1_mac_share_pigsize)
1188 {
1189 con_printf(CON_URGENT,"Warning: Missing Sounds/sounds.array for Mac data files");
1190 return;
1191 }
1192
1193 for (i = 0; i < MAX_SOUND_FILES; i++)
1194 {
1195 snprintf(soundfile, sizeof(soundfile), "SND%04d.raw", i);
1196 if (ds_load(0, soundfile) == 255)
1197 break;
1198 }
1199
1200 return;
1201 }
1202
1203 ptr = SoundBits.get();
1204
1205 std::vector<uint8_t> lastbuf;
1206 for (i=0; i<Num_sound_files; i++ )
1207 {
1208 auto &snd = GameSounds[i];
1209 auto &d = snd.data.get_deleter();
1210 if (!d.must_free_buffer())
1211 {
1212 if ( piggy_is_needed(i) )
1213 {
1214 const auto current_sound_offset{d.offset};
1215 const auto sound_offset = underlying_value(current_sound_offset);
1216 PHYSFS_seek(Piggy_fp, sound_offset);
1217
1218 // Read in the sound data!!!
1219 snd.data = digi_sound::allocated_data{ptr, current_sound_offset};
1220 ptr += snd.length;
1221 //Arne's decompress for shareware on all soundcards - [email protected]
1222 if (pc_shareware)
1223 {
1224 const auto compressed_length = SoundCompressed[i];
1225 lastbuf.resize(compressed_length);
1226 PHYSFSX_readBytes(Piggy_fp, lastbuf.data(), compressed_length);
1227 sound_decompress(lastbuf.data(), compressed_length, snd.data.get());
1228 }
1229 else
1230 PHYSFSX_readBytes(Piggy_fp, snd.data.get(), snd.length);
1231 }
1232 }
1233 }
1234 }
1235 #elif DXX_BUILD_DESCENT == 2
1236 void piggy_read_sounds(void)
1237 {
1238 uint8_t * ptr;
1239 int i;
1240
1241 ptr = SoundBits.get();
1242 auto fp = PHYSFSX_openReadBuffered(DEFAULT_SNDFILE).first;
1243 if (!fp)
1244 return;
1245
1246 for (i=0; i<Num_sound_files; i++ ) {
1247 auto &snd = GameSounds[i];
1248 auto &d = snd.data.get_deleter();
1249 if (!d.must_free_buffer())
1250 {
1251 if ( piggy_is_needed(i) ) {
1252 const auto current_sound_offset = snd.data.get_deleter().offset;
1253 const auto sound_offset = underlying_value(current_sound_offset);
1254 PHYSFS_seek(fp, sound_offset);
1255
1256 // Read in the sound data!!!
1257 snd.data = digi_sound::allocated_data{ptr, current_sound_offset};
1258 ptr += snd.length;
1259 PHYSFSX_readBytes(fp, snd.data.get(), snd.length);
1260 }
1261 else
1262 snd.data.reset();
1263 }
1264 }
1265 }
1266 #endif
1267
1268 void piggy_bitmap_page_in(GameBitmaps_array &GameBitmaps, const bitmap_index entry_bitmap_index)
1269 {
1270 const auto i = underlying_value(entry_bitmap_index);
1271 Assert( i < MAX_BITMAP_FILES );
1272 Assert( i < Num_bitmap_files );
1273 Assert( Piggy_bitmap_cache_size > 0 );
1274
1275 if ( i < 1 ) return;
1276 if ( i >= MAX_BITMAP_FILES ) return;
1277 if ( i >= Num_bitmap_files ) return;
1278
1279 if (GameBitmapOffset[entry_bitmap_index] == pig_bitmap_offset::None)
1280 return; // A read-from-disk bitmap!!!
1281
1282 const auto xlat_bitmap_index = CGameArg.SysLowMem ? GameBitmapXlat[entry_bitmap_index] : entry_bitmap_index; // Xlat for low-memory settings!
1283 grs_bitmap *const bmp = &GameBitmaps[xlat_bitmap_index];
1284
1285 if (bmp->get_flag_mask(BM_FLAG_PAGED_OUT))
1286 {
1287 pause_game_world_time p;
1288
1289 ReDoIt:
1290 PHYSFS_seek(Piggy_fp, static_cast<unsigned>(GameBitmapOffset[xlat_bitmap_index]));
1291
1292 gr_set_bitmap_flags(*bmp, GameBitmapFlags[xlat_bitmap_index]);
1293 #if DXX_BUILD_DESCENT == 1
1294 gr_set_bitmap_data (*bmp, &Piggy_bitmap_cache_data [Piggy_bitmap_cache_next]);
1295 #endif
1296
1297 if (bmp->get_flag_mask(BM_FLAG_RLE))
1298 {
1299 int zsize = PHYSFSX_readInt(Piggy_fp);
1300 #if DXX_BUILD_DESCENT == 1
1301
1302 // GET JOHN NOW IF YOU GET THIS ASSERT!!!
1303 Assert( Piggy_bitmap_cache_next+zsize < Piggy_bitmap_cache_size );
1304 if ( Piggy_bitmap_cache_next+zsize >= Piggy_bitmap_cache_size ) {
1305 piggy_bitmap_page_out_all();
1306 goto ReDoIt;
1307 }
1308 memcpy( &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next], &zsize, sizeof(int) );
1309 Piggy_bitmap_cache_next += sizeof(int);
1310 PHYSFSX_readBytes(Piggy_fp, &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next], zsize - 4);
1311 if (MacPig)
1312 {
1313 rle_swap_0_255(*bmp);
1314 memcpy(&zsize, bmp->bm_data, 4);
1315 }
1316 Piggy_bitmap_cache_next += zsize-4;
1317 #elif DXX_BUILD_DESCENT == 2
1318 const pigfile_size pigsize{static_cast<uint32_t>(PHYSFS_fileLength(Piggy_fp))};
1319
1320 // GET JOHN NOW IF YOU GET THIS ASSERT!!!
1321 //Assert( Piggy_bitmap_cache_next+zsize < Piggy_bitmap_cache_size );
1322 if ( Piggy_bitmap_cache_next+zsize >= Piggy_bitmap_cache_size ) {
1323 Int3();
1324 piggy_bitmap_page_out_all();
1325 goto ReDoIt;
1326 }
1327 PHYSFSX_readBytes(Piggy_fp, &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next + 4], zsize - 4);
1328 PUT_INTEL_INT(&Piggy_bitmap_cache_data[Piggy_bitmap_cache_next], zsize);
1329 gr_set_bitmap_data(*bmp, &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next]);
1330
1331 #ifndef MACDATA
1332 switch (pigsize) {
1333 default:
1334 if (!GameArg.EdiMacData)
1335 break;
1336 [[fallthrough]];
1337 case pigfile_size::mac_alien1_pigsize:
1338 case pigfile_size::mac_alien2_pigsize:
1339 case pigfile_size::mac_fire_pigsize:
1340 case pigfile_size::mac_groupa_pigsize:
1341 case pigfile_size::mac_ice_pigsize:
1342 case pigfile_size::mac_water_pigsize:
1343 rle_swap_0_255(*bmp);
1344 memcpy(&zsize, bmp->bm_data, 4);
1345 break;
1346 }
1347 #endif
1348
1349 Piggy_bitmap_cache_next += zsize;
1350 if ( Piggy_bitmap_cache_next+zsize >= Piggy_bitmap_cache_size ) {
1351 Int3();
1352 piggy_bitmap_page_out_all();
1353 goto ReDoIt;
1354 }
1355 #endif
1356
1357 } else {
1358 // GET JOHN NOW IF YOU GET THIS ASSERT!!!
1359 Assert( Piggy_bitmap_cache_next+(bmp->bm_h*bmp->bm_w) < Piggy_bitmap_cache_size );
1360 if ( Piggy_bitmap_cache_next+(bmp->bm_h*bmp->bm_w) >= Piggy_bitmap_cache_size ) {
1361 piggy_bitmap_page_out_all();
1362 goto ReDoIt;
1363 }
1364 PHYSFSX_readBytes(Piggy_fp, &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next], bmp->bm_h * bmp->bm_w);
1365 #if DXX_BUILD_DESCENT == 1
1366 Piggy_bitmap_cache_next+=bmp->bm_h*bmp->bm_w;
1367 if (MacPig)
1368 swap_0_255(*bmp);
1369 #elif DXX_BUILD_DESCENT == 2
1370 const pigfile_size pigsize{static_cast<uint32_t>(PHYSFS_fileLength(Piggy_fp))};
1371 gr_set_bitmap_data(*bmp, &Piggy_bitmap_cache_data[Piggy_bitmap_cache_next]);
1372 Piggy_bitmap_cache_next+=bmp->bm_h*bmp->bm_w;
1373
1374 #ifndef MACDATA
1375 switch (pigsize) {
1376 default:
1377 if (!GameArg.EdiMacData)
1378 break;
1379 [[fallthrough]];
1380 case pigfile_size::mac_alien1_pigsize:
1381 case pigfile_size::mac_alien2_pigsize:
1382 case pigfile_size::mac_fire_pigsize:
1383 case pigfile_size::mac_groupa_pigsize:
1384 case pigfile_size::mac_ice_pigsize:
1385 case pigfile_size::mac_water_pigsize:
1386 swap_0_255(*bmp);
1387 break;
1388 }
1389 #endif
1390 #endif
1391 }
1392
1393 //@@if ( bmp->bm_selector ) {
1394 //@@#if !defined(WINDOWS) && !defined(MACINTOSH)
1395 //@@ if (!dpmi_modify_selector_base( bmp->bm_selector, bmp->bm_data ))
1396 //@@ Error( "Error modifying selector base in piggy.c\n" );
1397 //@@#endif
1398 //@@}
1399
1400 compute_average_rgb(bmp, bmp->avg_color_rgb);
1401
1402 }
1403
1404 if (CGameArg.SysLowMem)
1405 {
1406 if (entry_bitmap_index != xlat_bitmap_index)
1407 GameBitmaps[entry_bitmap_index] = GameBitmaps[xlat_bitmap_index];
1408 }
1409
1410 //@@Removed from John's code:
1411 //@@#ifndef WINDOWS
1412 //@@ if ( bmp->bm_selector ) {
1413 //@@ if (!dpmi_modify_selector_base( bmp->bm_selector, bmp->bm_data ))
1414 //@@ Error( "Error modifying selector base in piggy.c\n" );
1415 //@@ }
1416 //@@#endif
1417 }
1418
1419 namespace {
1420
1421 void piggy_bitmap_page_out_all()
1422 {
1423 Piggy_bitmap_cache_next = 0;
1424
1425 texmerge_flush();
1426 rle_cache_flush();
1427
1428 for (auto &&[gbo, gb] : zip(partial_range(GameBitmapOffset, Num_bitmap_files), GameBitmaps))
1429 {
1430 if (gbo != pig_bitmap_offset::None)
1431 { // Don't page out bitmaps read from disk!!!
1432 gb.set_flags(BM_FLAG_PAGED_OUT);
1433 gr_set_bitmap_data(gb, nullptr);
1434 }
1435 }
1436 }
1437
1438 }
1439
1440 void piggy_load_level_data()
1441 {
1442 piggy_bitmap_page_out_all();
1443 paging_touch_all(Vclip);
1444 }
1445
1446 namespace {
1447 #if DXX_BUILD_DESCENT == 2
1448 #if DXX_USE_EDITOR
1449
1450 static void piggy_write_pigfile(const std::span<const char, FILENAME_LEN> filename)
1451 {
1452 int bitmap_data_start, data_offset;
1453 DiskBitmapHeader bmh;
1454 int org_offset;
1455 for (const unsigned n = Num_bitmap_files; const uint16_t i : xrange(n))
1456 {
1457 const bitmap_index bi{i};
1458 PIGGY_PAGE_IN( bi );
1459 }
1460
1461 piggy_close_file();
1462
1463 auto pig_fp = PHYSFSX_openWriteBuffered(filename.data()).first; //open PIG file
1464 if (!pig_fp)
1465 return;
1466
1467 write_int(PIGFILE_ID,pig_fp);
1468 write_int(PIGFILE_VERSION,pig_fp);
1469
1470 Num_bitmap_files--;
1471 PHYSFSX_writeBytes(pig_fp, &Num_bitmap_files, sizeof(int));
1472 Num_bitmap_files++;
1473
1474 bitmap_data_start = PHYSFS_tell(pig_fp);
1475 bitmap_data_start += (Num_bitmap_files - 1) * sizeof(DiskBitmapHeader);
1476 data_offset = bitmap_data_start;
1477
1478 std::array<char, FILENAME_LEN> tname;
1479 if (!change_filename_extension(tname, filename.data(), "lst"))
1480 return;
1481 auto fp1 = PHYSFSX_openWriteBuffered(tname.data()).first;
1482 if (!change_filename_extension(tname, filename.data(), "all"))
1483 return;
1484 auto fp2 = PHYSFSX_openWriteBuffered(tname.data()).first;
1485
1486 for (unsigned i = 1; i < Num_bitmap_files; ++i)
1487 {
1488 grs_bitmap *bmp;
1489
1490 const bitmap_index bi{static_cast<uint16_t>(i)};
1491 const std::span name = AllBitmaps[bi].name;
1492 {
1493 char *p1;
1494 if (const auto p = strchr(name.data(), '#')) { // this is an ABM == animated bitmap
1495 int n;
1496 p1 = p; p1++;
1497 n = atoi(p1);
1498 *p = 0;
1499 if (fp2 && n==0)
1500 PHYSFSX_printf(fp2, "%s.abm\n", name.data());
1501 memcpy(bmh.name, name.data(), 8);
1502 Assert( n <= DBM_NUM_FRAMES );
1503 bmh.dflags = DBM_FLAG_ABM + n;
1504 *p = '#';
1505 } else {
1506 if (fp2)
1507 PHYSFSX_printf(fp2, "%s.bbm\n", name.data());
1508 memcpy(bmh.name, name.data(), 8);
1509 bmh.dflags = 0;
1510 }
1511 }
1512 bmp = &GameBitmaps[bi];
1513
1514 assert(!bmp->get_flag_mask(BM_FLAG_PAGED_OUT));
1515
1516 if (fp1)
1517 PHYSFSX_printf(fp1, "BMP: %s, size %d bytes", name.data(), bmp->bm_rowsize * bmp->bm_h);
1518 org_offset = PHYSFS_tell(pig_fp);
1519 bmh.offset = data_offset - bitmap_data_start;
1520 PHYSFS_seek(pig_fp, data_offset);
1521
1522 if (bmp->get_flag_mask(BM_FLAG_RLE))
1523 {
1524 const auto size = reinterpret_cast<const int *>(bmp->bm_data);
1525 PHYSFSX_writeBytes(pig_fp, bmp->bm_data, *size);
1526 data_offset += *size;
1527 if (fp1)
1528 PHYSFSX_printf( fp1, ", and is already compressed to %d bytes.\n", *size );
1529 } else {
1530 PHYSFSX_writeBytes(pig_fp, bmp->bm_data, bmp->bm_rowsize * bmp->bm_h);
1531 data_offset += bmp->bm_rowsize * bmp->bm_h;
1532 if (fp1)
1533 PHYSFSX_puts_literal( fp1, ".\n" );
1534 }
1535 PHYSFS_seek(pig_fp, org_offset);
1536 auto &gbi = GameBitmaps[bi];
1537 assert(gbi.bm_w < 4096);
1538 bmh.width = (gbi.bm_w & 0xff);
1539 bmh.wh_extra = ((gbi.bm_w >> 8) & 0x0f);
1540 assert(gbi.bm_h < 4096);
1541 bmh.height = gbi.bm_h;
1542 bmh.wh_extra |= ((gbi.bm_h >> 4) & 0xf0);
1543 bmh.flags = gbi.get_flags();
1544 if (std::array<char, 32> subst_name; piggy_is_substitutable_bitmap(name, subst_name))
1545 {
1546 const auto other_bitmap = piggy_find_bitmap(subst_name);
1547 GameBitmapXlat[bi] = other_bitmap;
1548 bmh.flags |= BM_FLAG_PAGED_OUT;
1549 } else {
1550 bmh.flags &= ~BM_FLAG_PAGED_OUT;
1551 }
1552 bmh.avg_color = compute_average_pixel(&GameBitmaps[bi]);
1553 PHYSFSX_writeBytes(pig_fp, &bmh, sizeof(DiskBitmapHeader)); // Mark as a bitmap
1554 }
1555 PHYSFSX_printf( fp1, " Dumped %d assorted bitmaps.\n", Num_bitmap_files );
1556 }
1557
1558 static void write_int(int i, PHYSFS_File *file)
1559 {
1560 if (PHYSFSX_writeBytes(file, &i, sizeof(i)) != sizeof(i))
1561 Error("Error writing int in " __FILE__);
1562
1563 }
1564 #endif
1565
1566 /*
1567 * Functions for loading replacement textures
1568 * 1) From .pog files
1569 * 2) From descent.pig (for loading d1 levels)
1570 */
1571 static void free_bitmap_replacements()
1572 {
1573 Bitmap_replacement_data.reset();
1574 }
1575 #endif
1576 }
1577
1578 void piggy_close()
1579 {
1580 #if DXX_BUILD_DESCENT == 1
1581 custom_close();
1582 #endif
1583 piggy_close_file();
1584 BitmapBits.reset();
1585 SoundBits.reset();
1586 for (auto &gs : partial_range(GameSounds, Num_sound_files))
1587 gs.data.reset();
1588 #if DXX_BUILD_DESCENT == 2
1589 free_bitmap_replacements();
1590 free_d1_tmap_nums();
1591 #endif
1592 }
1593
1594 #if DXX_BUILD_DESCENT == 2
1595 namespace {
1596
1597 #if DXX_USE_EDITOR
1598 static const BitmapFile *piggy_does_bitmap_exist_slow(const char *const name)
1599 {
1600 range_for (auto &i, partial_const_range(AllBitmaps, Num_bitmap_files))
1601 {
1602 if (!strcmp(i.name.data(), name))
1603 return &i;
1604 }
1605 return nullptr;
1606 }
1607
1608 constexpr char gauge_bitmap_names[][9] = {
1609 "gauge01",
1610 "gauge02",
1611 "gauge06",
1612 "targ01",
1613 "targ02",
1614 "targ03",
1615 "targ04",
1616 "targ05",
1617 "targ06",
1618 "gauge18",
1619 #if DXX_BUILD_DESCENT == 1
1620 "targ01pc",
1621 "targ02pc",
1622 "targ03pc",
1623 "gaug18pc"
1624 #elif DXX_BUILD_DESCENT == 2
1625 "gauge01b",
1626 "gauge02b",
1627 "gauge06b",
1628 "targ01b",
1629 "targ02b",
1630 "targ03b",
1631 "targ04b",
1632 "targ05b",
1633 "targ06b",
1634 "gauge18b",
1635 "gauss1",
1636 "helix1",
1637 "phoenix1"
1638 #endif
1639 };
1640
1641 static const char (*piggy_is_gauge_bitmap(const char *const base_name))[9]
1642 {
1643 range_for (auto &i, gauge_bitmap_names)
1644 {
1645 if (!d_stricmp(base_name, i))
1646 return &i;
1647 }
1648 return nullptr;
1649 }
1650
1651 static int piggy_is_substitutable_bitmap(std::span<const char, 13> name, std::array<char, 32> &subst_name)
1652 {
1653 std::copy(name.begin(), name.end(), subst_name.begin());
1654 if (const auto p = strchr(subst_name.data(), '#'))
1655 {
1656 const int frame = atoi(&p[1]);
1657 *p = 0;
1658 auto base_name = subst_name;
1659 if (!piggy_is_gauge_bitmap(base_name.data()))
1660 {
1661 snprintf(subst_name.data(), subst_name.size(), "%.13s#%d", base_name.data(), frame + 1);
1662 if (piggy_does_bitmap_exist_slow(subst_name.data()))
1663 {
1664 if ( frame & 1 ) {
1665 snprintf(subst_name.data(), subst_name.size(), "%.13s#%d", base_name.data(), frame - 1);
1666 return 1;
1667 }
1668 }
1669 }
1670 std::copy(name.begin(), name.end(), subst_name.begin());
1671 }
1672 return 0;
1673 }
1674 #endif
1675
1676 /* returns nonzero if d1_tmap_num references a texture which isn't available in d2. */
1677 int d1_tmap_num_unique(uint16_t d1_tmap_num)
1678 {
1679 switch (d1_tmap_num) {
1680 case 0: case 2: case 4: case 5: case 6: case 7: case 9:
1681 case 10: case 11: case 12: case 17: case 18:
1682 case 20: case 21: case 25: case 28:
1683 case 38: case 39: case 41: case 44: case 49:
1684 case 50: case 55: case 57: case 88:
1685 case 132: case 141: case 147:
1686 case 154: case 155: case 158: case 159:
1687 case 160: case 161: case 167: case 168: case 169:
1688 case 170: case 171: case 174: case 175: case 185:
1689 case 193: case 194: case 195: case 198: case 199:
1690 case 200: case 202: case 210: case 211:
1691 case 220: case 226: case 227: case 228: case 229: case 230:
1692 case 240: case 241: case 242: case 243: case 246:
1693 case 250: case 251: case 252: case 253: case 257: case 258: case 259:
1694 case 260: case 263: case 266: case 283: case 298:
1695 case 315: case 317: case 319: case 320: case 321:
1696 case 330: case 331: case 332: case 333: case 349:
1697 case 351: case 352: case 353: case 354:
1698 case 355: case 357: case 358: case 359:
1699 case 362: case 370: return 1;
1700 default: return 0;
1701 }
1702 }
1703
1704 }
1705
1706 void load_bitmap_replacements(const std::span<const char, FILENAME_LEN> level_name)
1707 {
1708 //first, free up data allocated for old bitmaps
1709 free_bitmap_replacements();
1710
1711 std::array<char, FILENAME_LEN> ifile_name;
1712 if (!change_filename_extension(ifile_name, level_name.data(), "POG"))
1713 return;
1714 if (auto ifile = PHYSFSX_openReadBuffered(ifile_name.data()).first)
1715 {
1716 int id,version;
1717 unsigned n_bitmaps;
1718 int bitmap_data_size;
1719
1720 id = PHYSFSX_readInt(ifile);
1721 version = PHYSFSX_readInt(ifile);
1722
1723 if (id != MAKE_SIG('G','O','P','D') || version != 1) {
1724 return;
1725 }
1726
1727 n_bitmaps = PHYSFSX_readInt(ifile);
1728
1729 const auto indices = std::make_unique<uint16_t[]>(n_bitmaps);
1730 range_for (auto &i, unchecked_partial_range(indices.get(), n_bitmaps))
1731 i = PHYSFSX_readSLE16(ifile);
1732
1733 bitmap_data_size = PHYSFS_fileLength(ifile) - PHYSFS_tell(ifile) - sizeof(DiskBitmapHeader) * n_bitmaps;
1734 Bitmap_replacement_data = std::make_unique<ubyte[]>(bitmap_data_size);
1735
1736 range_for (const auto i, unchecked_partial_range(indices.get(), n_bitmaps))
1737 {
1738 const bitmap_index bi{i};
1739 grs_bitmap *const bm = &GameBitmaps[bi];
1740 int width;
1741
1742 const auto bmh = DiskBitmapHeader_read(ifile);
1743
1744 width = bmh.width + (static_cast<short>(bmh.wh_extra & 0x0f) << 8);
1745 gr_set_bitmap_data(*bm, NULL); // free ogl texture
1746 gr_init_bitmap(*bm, bm_mode::linear, 0, 0, width, bmh.height + (static_cast<short>(bmh.wh_extra & 0xf0) << 4), width, NULL);
1747 #if !DXX_USE_OGL
1748 bm->avg_color = bmh.avg_color;
1749 #endif
1750 bm->bm_data = reinterpret_cast<uint8_t *>(static_cast<uintptr_t>(bmh.offset));
1751
1752 gr_set_bitmap_flags(*bm, bmh.flags & BM_FLAGS_TO_COPY);
1753 GameBitmapOffset[bi] = pig_bitmap_offset::None; // don't try to read bitmap from current pigfile
1754 }
1755
1756 PHYSFSX_readBytes(ifile, Bitmap_replacement_data, bitmap_data_size);
1757
1758 range_for (const auto i, unchecked_partial_range(indices.get(), n_bitmaps))
1759 {
1760 const bitmap_index bi{i};
1761 grs_bitmap *const bm = &GameBitmaps[bi];
1762 gr_set_bitmap_data(*bm, &Bitmap_replacement_data[reinterpret_cast<uintptr_t>(bm->bm_data)]);
1763 }
1764 last_palette_loaded_pig[0]= 0; //force pig re-load
1765 texmerge_flush(); //for re-merging with new textures
1766 }
1767 }
1768
1769 namespace {
1770
1771 /* `std::optional` is almost suitable here, but `std::optional` provides no way
1772 * to mark the object as having a value and not implicitly perform
1773 * value-initialization of the contained object. There is no need to
1774 * value-initialize the arrays first, so use a custom type that allows that to
1775 * be skipped.
1776 */
1777 struct d1_colormap_data
1778 {
1779 palette_array_t d1_palette;
1780 std::array<color_palette_index, 256> colormap;
1781 bool engaged{};
1782 };
1783
1784 /* calculate table to translate d1 bitmaps to current palette,
1785 * On error, return a d1_colormap_data with engaged==false and other members
1786 * default-initialized. Since these members have no constructor and no
1787 * initializer, default-initialization degenerates to "no initialization" and
1788 * they retain whatever value happened to be in memory, so they must not be
1789 * accessed.
1790 *
1791 * On success, return a d1_colormap_data with engaged==true and other members
1792 * initialized.
1793 */
1794 [[nodiscard]]
1795 static d1_colormap_data build_d1_colormap_from_palette_file()
1796 {
1797 d1_colormap_data r;
1798 constexpr std::size_t expected_bytes_read{sizeof(r.d1_palette[0]) * r.d1_palette.size()};
1799 if (const auto &&[file, physfserr] = PHYSFSX_openReadBuffered(D1_PALETTE); !file)
1800 Warning("Failed to load Descent 1 color palette: failed to open \"" D1_PALETTE "\": \"%s\".", PHYSFS_getErrorByCode(physfserr));
1801 else if (const auto size{PHYSFS_fileLength(file)}; size != 9472)
1802 Warning("Failed to load Descent 1 color palette: failed to read \"" D1_PALETTE "\": expected length 9472, found length %li", static_cast<long>(size));
1803 else if (const auto actual_bytes_read{PHYSFSX_readBytes(file, r.d1_palette, expected_bytes_read)}; actual_bytes_read != expected_bytes_read)
1804 Warning("Failed to load Descent 1 color palette: failed to read \"" D1_PALETTE "\": expected to read %" DXX_PRI_size_type " bytes, actual read length %li", expected_bytes_read, static_cast<long>(actual_bytes_read));
1805 else
1806 {
1807 reconstruct_at(r.colormap, build_colormap_good, r.d1_palette);
1808 // don't change transparencies:
1809 r.colormap[254] = color_palette_index{254};
1810 r.colormap[255] = TRANSPARENCY_COLOR;
1811 r.engaged = true;
1812 }
1813 return r;
1814 }
1815
1816 #define JUST_IN_CASE 132 /* is enough for d1 pc registered */
1817 static std::span<uint8_t> bitmap_read_d1(grs_bitmap *bitmap, /* read into this bitmap */
1818 const NamedPHYSFS_File d1_Piggy_fp, /* read from this file */
1819 int bitmap_data_start, /* specific to file */
1820 const DiskBitmapHeader *const bmh, /* header info for bitmap */
1821 std::span<uint8_t> next_bitmap, /* where to write it (if points to nullptr, use malloc) */
1822 const d1_colormap_data &d1_colormap /* what palette and colormap the bitmap has */
1823 )
1824 {
1825 uint8_t *data;
1826 int width;
1827
1828 width = bmh->width + (static_cast<short>(bmh->wh_extra & 0x0f) << 8);
1829 gr_set_bitmap_data(*bitmap, NULL); // free ogl texture
1830 gr_init_bitmap(*bitmap, bm_mode::linear, 0, 0, width, bmh->height + (static_cast<short>(bmh->wh_extra & 0xf0) << 4), width, NULL);
1831 #if !DXX_USE_OGL
1832 bitmap->avg_color = bmh->avg_color;
1833 #endif
1834 gr_set_bitmap_flags(*bitmap, bmh->flags & BM_FLAGS_TO_COPY);
1835
1836 PHYSFS_seek(d1_Piggy_fp, bitmap_data_start + bmh->offset);
1837 const auto is_rle{bmh->flags & BM_FLAG_RLE};
1838 const uint32_t zsize{
1839 is_rle
1840 ? PHYSFSX_readULE32(d1_Piggy_fp)
1841 : (bitmap->bm_h * bitmap->bm_w)
1842 };
1843
1844 if (next_bitmap.data())
1845 {
1846 /* Advise `std::span` how much space will be written, so that a debug
1847 * version can trap here if that would exceed the available buffer. If
1848 * `std::span` does not trap, and there is insufficient space, return
1849 * without reading the bitmap. This is an improvement over the
1850 * previous implementation, which would write off the end of the buffer
1851 * and cause heap corruption.
1852 *
1853 * This trap and return should be unreachable, assuming an official
1854 * palette file and official bitmaps. This error path _can_ be
1855 * triggered by corrupt input data. Fixing that is left as an exercise
1856 * to the reader, since no one has filed a bug report about the
1857 * heap corruption bug, even though the bug appears to date to when the
1858 * D1-textures-in-D2 feature was added in 2003 with commit
1859 * 168cf918a43dce2b1cd697fbb45bea7468efbfd6 ("fix loading of d1 texture
1860 * replacements for non-animated textures"), though equivalent logic
1861 * may have been present even earlier. Therefore, it seems no one
1862 * needs this to succeed, so converting it from corruption to a
1863 * trap+return is sufficient for now.
1864 */
1865 data = next_bitmap.first(zsize).data();
1866 if (next_bitmap.size() < zsize)
1867 return next_bitmap;
1868 } else {
1869 MALLOC(data, ubyte, zsize + JUST_IN_CASE);
1870 if (!data) return next_bitmap;
1871 }
1872
1873 /* If a 32-bit unsigned little endian was read from the data file above for
1874 * the initialization of `zsize`, then store it into the buffer and read
1875 * from the file into the location following that stored 32-bit value.
1876 *
1877 * If no value was read above, then begin reading at the head of the buffer.
1878 *
1879 * This effectively emulates a "peek" to initialize `zsize` above, without
1880 * requiring a separate seek here.
1881 */
1882 PHYSFSX_readBytes(d1_Piggy_fp, (is_rle ? (PUT_INTEL_INT(data, zsize), data + sizeof(uint32_t)) : data), zsize);
1883 gr_set_bitmap_data(*bitmap, data);
1884 switch (descent1_pig_size{PHYSFS_fileLength(d1_Piggy_fp)})
1885 {
1886 default:
1887 break;
1888 case descent1_pig_size::d1_mac_pigsize:
1889 case descent1_pig_size::d1_mac_share_pigsize:
1890 if (bmh->flags & BM_FLAG_RLE)
1891 rle_swap_0_255(*bitmap);
1892 else
1893 swap_0_255(*bitmap);
1894 }
1895 if (bmh->flags & BM_FLAG_RLE)
1896 {
1897 if (d1_colormap.engaged)
1898 rle_remap(*bitmap, d1_colormap.colormap);
1899 /* Otherwise, skip the remapping. The colors will be wrong, but the
1900 * size will not change, so the bitmap will still reliably fit in the
1901 * allocated space.
1902 */
1903 }
1904 else
1905 {
1906 if (d1_colormap.engaged)
1907 gr_remap_bitmap_good(*bitmap, d1_colormap.d1_palette, TRANSPARENCY_COLOR, -1);
1908 }
1909 uint32_t advance_next_bitmap{zsize};
1910 if (bmh->flags & BM_FLAG_RLE) { // size of bitmap could have changed!
1911 int new_size;
1912 memcpy(&new_size, bitmap->bm_data, 4);
1913 advance_next_bitmap = new_size;
1914 if (!next_bitmap.data()) {
1915 Assert( zsize + JUST_IN_CASE >= new_size );
1916 bitmap->bm_mdata = reinterpret_cast<uint8_t *>(d_realloc(bitmap->bm_mdata, new_size));
1917 Assert(bitmap->bm_data);
1918 }
1919 }
1920 return next_bitmap.data() ? next_bitmap.subspan(advance_next_bitmap) : next_bitmap;
1921 }
1922
1923 #define D1_MAX_TEXTURES 800
1924
1925 static void bm_read_d1_tmap_nums(const NamedPHYSFS_File d1pig)
1926 {
1927 int i;
1928
1929 PHYSFS_seek(d1pig, 8);
1930 d1_tmap_nums = std::make_unique<d1_tmap_nums_t>();
1931 auto &t = *d1_tmap_nums.get();
1932 t.fill(-1);
1933 for (i = 0; i < D1_MAX_TEXTURES; i++) {
1934 const uint16_t d1_index = PHYSFSX_readSLE16(d1pig);
1935 if (d1_index >= std::size(t))
1936 break;
1937 t[d1_index] = i;
1938 if (PHYSFS_eof(d1pig))
1939 break;
1940 }
1941 }
1942
1943 // this function is at the same position in the d1 shareware piggy loading
1944 // algorithm as bm_load_sub in main/bmread.c
1945 static int get_d1_bm_index(char *filename, const NamedPHYSFS_File d1_pig)
1946 {
1947 int i, N_bitmaps;
1948 if (const auto p{strchr(filename, '.')})
1949 *p = '\0'; // remove extension
1950 PHYSFS_seek(d1_pig, 0);
1951 N_bitmaps = PHYSFSX_readInt(d1_pig);
1952 PHYSFS_seek(d1_pig, 8);
1953 for (i = 1; i <= N_bitmaps; i++) {
1954 const auto bmh{DiskBitmapHeader_d1_read(d1_pig)};
1955 if (!d_strnicmp(bmh.name, filename, 8))
1956 return i;
1957 }
1958 return -1;
1959 }
1960
1961 // imitate the algorithm of gamedata_read_tbl in main/bmread.c
1962 static void read_d1_tmap_nums_from_hog(const NamedPHYSFS_File d1_pig)
1963 {
1964 #define LINEBUF_SIZE 600
1965 int reading_textures{0};
1966 short texture_count{0};
1967 int bitmaps_tbl_is_binary{0};
1968
1969 auto &&[bitmaps, physfserr] = PHYSFSX_openReadBuffered("bitmaps.tbl");
1970 if (!bitmaps) {
1971 auto &&[bitmapbin, physfserr2] = PHYSFSX_openReadBuffered ("bitmaps.bin");
1972 if (!bitmapbin)
1973 {
1974 Warning("Failed to open \"bitmaps.tbl\", \"bitmaps.bin\": \"%s\", \"%s\". Descent 1 textures will not be read.", PHYSFS_getErrorByCode(physfserr), PHYSFS_getErrorByCode(physfserr2));
1975 return;
1976 }
1977 bitmaps = std::move(bitmapbin);
1978 bitmaps_tbl_is_binary = 1;
1979 }
1980
1981 d1_tmap_nums = std::make_unique<d1_tmap_nums_t>();
1982 auto &t = *d1_tmap_nums.get();
1983 t.fill(-1);
1984
1985 for (PHYSFSX_gets_line_t<LINEBUF_SIZE> inputline; PHYSFSX_fgets (inputline, bitmaps);)
1986 {
1987 char *arg;
1988
1989 if (bitmaps_tbl_is_binary)
1990 decode_text_line((inputline));
1991 else
1992 for (std::size_t i; inputline[(i=strlen(inputline))-2]=='\\';)
1993 {
1994 if (!PHYSFSX_fgets(inputline, bitmaps, i - 2)) // strip comments
1995 break;
1996 }
1997 REMOVE_EOL(inputline);
1998 if (strchr(inputline, ';')!=NULL) REMOVE_COMMENTS(inputline);
1999 if (strlen(inputline) == LINEBUF_SIZE-1) {
2000 Warning_puts("Possible line truncation in BITMAPS.TBL");
2001 return;
2002 }
2003 arg = strtok( inputline, space_tab );
2004 if (arg && arg[0] == '@') {
2005 arg++;
2006 //Registered_only = 1;
2007 }
2008
2009 while (arg != NULL) {
2010 if (*arg == '$')
2011 reading_textures = 0; // default
2012 if (!strcmp(arg, "$TEXTURES")) // BM_TEXTURES
2013 reading_textures = 1;
2014 else if (! d_stricmp(arg, "$ECLIP") // BM_ECLIP
2015 || ! d_stricmp(arg, "$WCLIP")) // BM_WCLIP
2016 texture_count++;
2017 else // not a special token, must be a bitmap!
2018 if (reading_textures) {
2019 while (*arg == '\t' || *arg == ' ')
2020 arg++;//remove unwanted blanks
2021 if (*arg == '\0')
2022 break;
2023 if (d1_tmap_num_unique(texture_count)) {
2024 const uint32_t d1_index = get_d1_bm_index(arg, d1_pig);
2025 if (d1_index < std::size(t))
2026 {
2027 t[d1_index] = texture_count;
2028 //int d2_index = d2_index_for_d1_index(d1_index);
2029 }
2030 }
2031 Assert (texture_count < D1_MAX_TEXTURES);
2032 texture_count++;
2033 }
2034
2035 arg = strtok (NULL, equal_space);
2036 }
2037 }
2038 }
2039
2040 /* If the given d1_index is the index of a bitmap we have to load
2041 * (because it is unique to descent 1), then returns the d2_index that
2042 * the given d1_index replaces.
2043 * Returns bitmap_index::None if the given d1_index is not unique to descent 1.
2044 */
2045 static bitmap_index d2_index_for_d1_index(short d1_index)
2046 {
2047 if (!d1_tmap_nums)
2048 return bitmap_index::None;
2049 auto &t = *d1_tmap_nums.get();
2050 assert(d1_index < std::size(t));
2051 if (d1_index >= std::size(t))
2052 return bitmap_index::None;
2053 const auto i = t[d1_index];
2054 if (i == -1 || !d1_tmap_num_unique(i))
2055 return bitmap_index::None;
2056 return Textures[convert_d1_tmap_num(i)];
2057 }
2058
2059 }
2060
2061 void load_d1_bitmap_replacements()
2062 {
2063 int pig_data_start, bitmap_header_start, bitmap_data_start;
2064 int N_bitmaps;
2065 short d1_index;
2066 char *p;
2067
2068 auto &&[d1_Piggy_fp, physfserr] = PHYSFSX_openReadBuffered(descent_pig_basename);
2069 #define D1_PIG_LOAD_FAILED "Failed loading " D1_PIGFILE
2070 if (!d1_Piggy_fp) {
2071 Warning("Failed to open " D1_PIGFILE ": %s", PHYSFS_getErrorByCode(physfserr));
2072 return;
2073 }
2074
2075 //first, free up data allocated for old bitmaps
2076 free_bitmap_replacements();
2077
2078 switch (descent1_pig_size{PHYSFS_fileLength(d1_Piggy_fp)})
2079 {
2080 case descent1_pig_size::d1_share_big_pigsize:
2081 case descent1_pig_size::d1_share_10_pigsize:
2082 case descent1_pig_size::d1_share_pigsize:
2083 case descent1_pig_size::d1_10_big_pigsize:
2084 case descent1_pig_size::d1_10_pigsize:
2085 pig_data_start = 0;
2086 // OK, now we need to read d1_tmap_nums by emulating d1's gamedata_read_tbl()
2087 read_d1_tmap_nums_from_hog(d1_Piggy_fp);
2088 break;
2089 default:
2090 Warning_puts("Unknown size for " D1_PIGFILE);
2091 Int3();
2092 [[fallthrough]];
2093 case descent1_pig_size::d1_pigsize:
2094 case descent1_pig_size::d1_oem_pigsize:
2095 case descent1_pig_size::d1_mac_pigsize:
2096 case descent1_pig_size::d1_mac_share_pigsize:
2097 pig_data_start = PHYSFSX_readInt(d1_Piggy_fp );
2098 bm_read_d1_tmap_nums(d1_Piggy_fp); //was: bm_read_all_d1(fp);
2099 //for (i = 0; i < 1800; i++) GameBitmapXlat[i] = PHYSFSX_readSLE16(d1_Piggy_fp);
2100 break;
2101 }
2102
2103 PHYSFS_seek(d1_Piggy_fp, pig_data_start);
2104 N_bitmaps = PHYSFSX_readInt(d1_Piggy_fp);
2105 {
2106 int N_sounds = PHYSFSX_readInt(d1_Piggy_fp);
2107 int header_size = N_bitmaps * DISKBITMAPHEADER_D1_SIZE
2108 + N_sounds * sizeof(DiskSoundHeader);
2109 bitmap_header_start = pig_data_start + 2 * sizeof(int);
2110 bitmap_data_start = bitmap_header_start + header_size;
2111 }
2112
2113 /* This size is sufficient for all official releases of Descent 1 bitmaps,
2114 * when decoded using the standard palette.
2115 *
2116 * Custom bitmap files, or custom palette files, may exhaust this space,
2117 * causing `bitmap_read_d1` to fail to read all bitmaps.
2118 */
2119 static constexpr std::size_t D1_BITMAPS_SIZE{300000};
2120 Bitmap_replacement_data = std::make_unique<ubyte[]>(D1_BITMAPS_SIZE);
2121 if (!Bitmap_replacement_data) {
2122 Warning_puts(D1_PIG_LOAD_FAILED);
2123 return;
2124 }
2125
2126 const auto d1_colormap{build_d1_colormap_from_palette_file()};
2127
2128 std::span<uint8_t> next_bitmap{Bitmap_replacement_data.get(), D1_BITMAPS_SIZE};
2129 for (d1_index = 1; d1_index <= N_bitmaps; d1_index++ ) {
2130 const auto d2_index = d2_index_for_d1_index(d1_index);
2131 // only change bitmaps which are unique to d1
2132 if (d2_index != bitmap_index::None)
2133 {
2134 PHYSFS_seek(d1_Piggy_fp, bitmap_header_start + (d1_index - 1) * DISKBITMAPHEADER_D1_SIZE);
2135 const auto bmh{DiskBitmapHeader_d1_read(d1_Piggy_fp)};
2136
2137 next_bitmap = bitmap_read_d1(&GameBitmaps[d2_index], d1_Piggy_fp, bitmap_data_start, &bmh, next_bitmap, d1_colormap);
2138 GameBitmapOffset[d2_index] = pig_bitmap_offset::None; // don't try to read bitmap from current d2 pigfile
2139 GameBitmapFlags[d2_index] = bmh.flags;
2140
2141 auto &abname = AllBitmaps[d2_index].name;
2142 if ((p = strchr(abname.data(), '#')) /* d2 BM is animated */
2143 && !(bmh.dflags & DBM_FLAG_ABM) ) { /* d1 bitmap is not animated */
2144 int len = p - abname.data();
2145 const auto num_bitmap_files{Num_bitmap_files};
2146 for (const uint16_t i : xrange(num_bitmap_files))
2147 {
2148 const bitmap_index bi{i};
2149 if (bi != d2_index && ! memcmp(abname.data(), AllBitmaps[bi].name.data(), len))
2150 {
2151 gr_set_bitmap_data(GameBitmaps[bi], nullptr); // free ogl texture
2152 GameBitmaps[bi] = GameBitmaps[d2_index];
2153 GameBitmapOffset[bi] = pig_bitmap_offset::None;
2154 GameBitmapFlags[bi] = bmh.flags;
2155 }
2156 }
2157 }
2158 }
2159 }
2160 last_palette_loaded_pig[0]= 0; //force pig re-load
2161
2162 texmerge_flush(); //for re-merging with new textures
2163 }
2164
2165 /*
2166 * Find and load the named bitmap from descent.pig
2167 * similar to read_extra_bitmap_iff
2168 */
2169 grs_bitmap *read_extra_bitmap_d1_pig(const std::span<const char> name, grs_bitmap &n)
2170 {
2171 {
2172 int pig_data_start, bitmap_header_start, bitmap_data_start;
2173 int N_bitmaps;
2174 auto &&[d1_Piggy_fp, physfserr] = PHYSFSX_openReadBuffered(descent_pig_basename);
2175 if (!d1_Piggy_fp)
2176 {
2177 Warning("Failed to open " D1_PIGFILE ": %s", PHYSFS_getErrorByCode(physfserr));
2178 return nullptr;
2179 }
2180
2181 switch (descent1_pig_size{PHYSFS_fileLength(d1_Piggy_fp)})
2182 {
2183 case descent1_pig_size::d1_share_big_pigsize:
2184 case descent1_pig_size::d1_share_10_pigsize:
2185 case descent1_pig_size::d1_share_pigsize:
2186 case descent1_pig_size::d1_10_big_pigsize:
2187 case descent1_pig_size::d1_10_pigsize:
2188 pig_data_start = 0;
2189 break;
2190 default:
2191 Warning_puts("Unknown size for " D1_PIGFILE);
2192 Int3();
2193 [[fallthrough]];
2194 case descent1_pig_size::d1_pigsize:
2195 case descent1_pig_size::d1_oem_pigsize:
2196 case descent1_pig_size::d1_mac_pigsize:
2197 case descent1_pig_size::d1_mac_share_pigsize:
2198 pig_data_start = PHYSFSX_readInt(d1_Piggy_fp );
2199
2200 break;
2201 }
2202
2203 PHYSFS_seek(d1_Piggy_fp, pig_data_start);
2204 N_bitmaps = PHYSFSX_readInt(d1_Piggy_fp);
2205 {
2206 int N_sounds = PHYSFSX_readInt(d1_Piggy_fp);
2207 int header_size = N_bitmaps * DISKBITMAPHEADER_D1_SIZE
2208 + N_sounds * sizeof(DiskSoundHeader);
2209 bitmap_header_start = pig_data_start + 2 * sizeof(int);
2210 bitmap_data_start = bitmap_header_start + header_size;
2211 }
2212
2213 const auto d1_colormap{build_d1_colormap_from_palette_file()};
2214
2215 for (unsigned i = 1;; ++i)
2216 {
2217 if (i > N_bitmaps)
2218 {
2219 con_printf(CON_DEBUG, "Failed to find bitmap: %s", name.data());
2220 return nullptr;
2221 }
2222 const auto bmh{DiskBitmapHeader_d1_read(d1_Piggy_fp)};
2223 if (!d_strnicmp(bmh.name, name.data(), std::min<std::size_t>(8u, name.size())))
2224 {
2225 bitmap_read_d1(&n, d1_Piggy_fp, bitmap_data_start, &bmh, std::span<uint8_t>{}, d1_colormap);
2226 break;
2227 }
2228 }
2229 }
2230
2231 #if !DXX_USE_OGL
2232 n.avg_color = 0; //compute_average_pixel(n);
2233 #endif
2234 return &n;
2235 }
2236 #endif
2237
2238 /*
2239 * reads a bitmap_index structure from a PHYSFS_File
2240 */
2241 void bitmap_index_read(const NamedPHYSFS_File fp, bitmap_index &bi)
2242 {
2243 const auto i = GameBitmaps.valid_index(PHYSFSX_readSLE16(fp));
2244 bi = i ? *i : bitmap_index::None;
2245 }
2246
2247 /*
2248 * reads n bitmap_index structs from a PHYSFS_File
2249 */
2250 void bitmap_index_read_n(const NamedPHYSFS_File fp, const std::ranges::subrange<bitmap_index *> r)
2251 {
2252 for (auto &bi : r)
2253 {
2254 const auto i = GameBitmaps.valid_index(PHYSFSX_readSLE16(fp));
2255 bi = i ? *i : bitmap_index::None;
2256 }
2257 }
2258
2259 }