Debian Codegraph @

similar/main/mission.cpp

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
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 * Code to handle multiple missions
23 *
24 */
25
26 #include "dxxsconf.h"
27 #include <algorithm>
28 #include <vector>
29 #include <stdio.h>
30 #include <stdlib.h>
31 #include <string.h>
32 #include <ranges>
33 #include <ctype.h>
34 #include <limits.h>
35
36 #include "pstypes.h"
37 #include "strutil.h"
38 #include "inferno.h"
39 #include "window.h"
40 #include "mission.h"
41 #include "gamesave.h"
42 #include "piggy.h"
43 #include "console.h"
44 #include "polyobj.h"
45 #include "dxxerror.h"
46 #include "config.h"
47 #include "newmenu.h"
48 #include "text.h"
49 #include "u_mem.h"
50 #include "ignorecase.h"
51 #include "physfsx.h"
52 #include "physfs_list.h"
53 #include "event.h"
54 #if DXX_BUILD_DESCENT == 2
55 #include "movie.h"
56 #endif
57 #include "null_sentinel_iterator.h"
58
59 #include "compiler-cf_assert.h"
60 #include "compiler-poison.h"
61 #include "compiler-range_for.h"
62 #include "d_enumerate.h"
63 #include "d_underlying_value.h"
64 #include "d_zip.h"
65 #include <memory>
66
67 #define BIMD1_BRIEFING_FILE "briefing.txb"
68
69 using std::min;
70
71 #define MISSION_EXTENSION_DESCENT_I ".msn"
72 #if DXX_BUILD_DESCENT == 2
73 #define MISSION_EXTENSION_DESCENT_II ".mn2"
74 #endif
75
76 #define CON_PRIORITY_DEBUG_MISSION_LOAD CON_DEBUG
77
78 namespace dcx {
79
80 char descent_hog_basename[]{"descent.hog"};
81
82 namespace {
83
84 using mission_candidate_search_path = std::array<char, PATH_MAX>;
85
86 auto prepare_mission_list_count_dirbuf(const std::size_t immediate_directories)
87 {
88 std::array<char, sizeof("DIR:99999; ")> dirbuf;
89 /* Limit the count of directories to what can be formatted
90 * successfully without truncation. If a user has more than this
91 * many directories, an empty string will be used instead of showing
92 * the actual count.
93 */
94 if (immediate_directories && immediate_directories <= 99999)
95 std::snprintf(std::data(dirbuf), std::size(dirbuf), "DIR:%u; ", DXX_size_t_cast_unsigned_int(immediate_directories));
96 else
97 dirbuf.front() = 0;
98 return dirbuf;
99 }
100
101 }
102
103 }
104
105 namespace dsx {
106
107 char descent2_hog_basename[]{"descent2.hog"};
108 char d2demo_hog_basename[]{"d2demo.hog"};
109
110 namespace {
111
112 struct mle;
113 using mission_list_type = std::vector<mle>;
114
115 //mission list entry
116 struct mle : Mission_path
117 {
118 static constexpr std::size_t maximum_mission_name_length{75};
119 descent_hog_size builtin_hogsize; // if it's the built-in mission, used for determining the version
120 #if DXX_BUILD_DESCENT == 2
121 descent_version_type descent_version; // descent 1 or descent 2?
122 #endif
123 Mission::anarchy_only_level anarchy_only_flag; // if true, mission is anarchy only
124 mission_list_type directory;
125 ntstring<maximum_mission_name_length> mission_name;
126 mle(Mission_path &&m,
127 const descent_hog_size builtin_hogsize,
128 #if DXX_BUILD_DESCENT == 2
129 const descent_version_type descent_version,
130 #endif
131 const Mission::anarchy_only_level anarchy_only_flag,
132 const std::span<const char> mission_name
133 ) :
134 Mission_path{std::move(m)},
135 builtin_hogsize{builtin_hogsize},
136 #if DXX_BUILD_DESCENT == 2
137 descent_version{descent_version},
138 #endif
139 anarchy_only_flag{anarchy_only_flag}
140 {
141 this->mission_name.copy_if(mission_name.data(), mission_name.size());
142 }
143 mle(const char *const name, std::vector<mle> &&d);
144 };
145
146 struct mission_subdir_stats
147 {
148 std::size_t immediate_directories = 0, immediate_missions = 0, total_missions = 0;
149 static std::size_t count_missions(const mission_list_type &directory)
150 {
151 std::size_t total_missions = 0;
152 range_for (auto &&i, directory)
153 {
154 if (i.directory.empty())
155 ++ total_missions;
156 else
157 total_missions += count_missions(i.directory);
158 }
159 return total_missions;
160 }
161 void count(const mission_list_type &directory)
162 {
163 range_for (auto &&i, directory)
164 {
165 if (i.directory.empty())
166 {
167 ++ total_missions;
168 ++ immediate_missions;
169 }
170 else
171 {
172 ++ immediate_directories;
173 total_missions += count_missions(i.directory);
174 }
175 }
176 }
177 };
178
179 struct mission_name_and_version
180 {
181 #if DXX_BUILD_DESCENT == 2
182 const Mission::descent_version_type descent_version{};
183 #endif
184 const char *const name{};
185 mission_name_and_version() = default;
186 mission_name_and_version(Mission::descent_version_type, const char *);
187 };
188
189 mission_name_and_version::mission_name_and_version(Mission::descent_version_type const v, const char *const n) :
190 #if DXX_BUILD_DESCENT == 2
191 descent_version{v},
192 #endif
193 name{n}
194 {
195 #if DXX_BUILD_DESCENT == 1
196 (void)v;
197 #endif
198 }
199
200 mle::mle(const char *const name, std::vector<mle> &&d) :
201 Mission_path(name, 0), directory(std::move(d))
202 {
203 mission_subdir_stats ss;
204 ss.count(directory);
205 snprintf(mission_name.data(), mission_name.size(), "%s/ [%sMSN:L%zu;T%zu]", name, std::data(prepare_mission_list_count_dirbuf(ss.immediate_directories)), ss.immediate_missions, ss.total_missions);
206 }
207
208 static const mle *compare_mission_predicate_to_leaf(const mission_entry_predicate mission_predicate, const mle &candidate, const char *candidate_filesystem_name)
209 {
210 #if DXX_BUILD_DESCENT == 2
211 if (mission_predicate.check_version && mission_predicate.descent_version != candidate.descent_version)
212 {
213 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "mission version check requires %u, but found %u; skipping string comparison for mission \"%s\""), static_cast<unsigned>(mission_predicate.descent_version), static_cast<unsigned>(candidate.descent_version), candidate.path.data());
214 return nullptr;
215 }
216 #endif
217 if (!d_stricmp(mission_predicate.filesystem_name, candidate_filesystem_name))
218 {
219 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "found mission \"%s\"[\"%s\"] at %p"), candidate.path.data(), &*candidate.filename, &candidate);
220 return &candidate;
221 }
222 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "want mission \"%s\", no match for mission \"%s\"[\"%s\"] at %p"), mission_predicate.filesystem_name, candidate.path.data(), &*candidate.filename, &candidate);
223 return nullptr;
224 }
225
226 static const mle *compare_mission_by_guess(const mission_entry_predicate mission_predicate, const mle &candidate)
227 {
228 if (candidate.directory.empty())
229 return compare_mission_predicate_to_leaf(mission_predicate, candidate, &*candidate.filename);
230 {
231 const unsigned long size = candidate.directory.size();
232 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "want mission \"%s\", check %lu missions under \"%s\""), mission_predicate.filesystem_name, size, candidate.path.data());
233 }
234 range_for (auto &i, candidate.directory)
235 {
236 if (const auto r = compare_mission_by_guess(mission_predicate, i))
237 return r;
238 }
239 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "no matches under \"%s\""), candidate.path.data());
240 return nullptr;
241 }
242
243 static const mle *compare_mission_by_pathname(const mission_entry_predicate mission_predicate, const mle &candidate)
244 {
245 if (candidate.directory.empty())
246 return compare_mission_predicate_to_leaf(mission_predicate, candidate, candidate.path.data());
247 const auto mission_name = mission_predicate.filesystem_name;
248 const auto path_length = candidate.path.size();
249 if (!strncmp(mission_name, candidate.path.data(), path_length) && mission_name[path_length] == '/')
250 {
251 {
252 const unsigned long size = candidate.directory.size();
253 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "want mission pathname \"%s\", check %lu missions under \"%s\""), mission_predicate.filesystem_name, size, candidate.path.data());
254 }
255 range_for (auto &i, candidate.directory)
256 {
257 if (const auto r = compare_mission_by_pathname(mission_predicate, i))
258 return r;
259 }
260 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "no matches under \"%s\""), candidate.path.data());
261 }
262 else
263 con_printf(CON_PRIORITY_DEBUG_MISSION_LOAD, DXX_STRINGIZE_FL(__FILE__, __LINE__, "want mission pathname \"%s\", ignore non-matching directory \"%s\""), mission_predicate.filesystem_name, candidate.path.data());
264 return nullptr;
265 }
266
267 }
268
269 Mission_ptr Current_mission; // currently loaded mission
270
271 }
272
273 namespace {
274
275 static bool null_or_space(char c)
276 {
277 return !c || isspace(static_cast<unsigned>(c));
278 }
279
280 // Allocate the Current_mission->level_names, Current_mission->secret_level_names and Current_mission->secret_level_table arrays
281 static void allocate_levels(const unsigned count_regular_level, const unsigned count_secret_level)
282 {
283 Current_mission->level_names = std::make_unique<d_fname[]>(count_regular_level);
284 Current_mission->last_level = count_regular_level;
285 Current_mission->n_secret_levels = count_secret_level;
286 Current_mission->last_secret_level = -static_cast<signed>(count_secret_level);
287 if (count_secret_level)
288 {
289 auto secret_level_names = std::make_unique<d_fname[]>(count_secret_level);
290 auto secret_level_table = std::make_unique<uint8_t[]>(count_secret_level);
291 Current_mission->secret_level_names = std::move(secret_level_names);
292 Current_mission->secret_level_table = std::move(secret_level_table);
293 }
294 }
295
296 static void allocate_shareware_levels(const unsigned count_regular_level, const unsigned count_secret_level)
297 {
298 Current_mission->briefing_text_filename = BIMD1_BRIEFING_FILE;
299 Current_mission->ending_text_filename = BIMD1_ENDING_FILE_SHARE;
300 allocate_levels(count_regular_level, count_secret_level);
301 //build level names
302 for (const auto &&[idx, name] : enumerate(std::span(Current_mission->level_names.get(), count_regular_level), 1u))
303 {
304 cf_assert(idx <= count_regular_level);
305 snprintf(name.data(), name.size(), "level%02u.sdl", idx);
306 }
307 }
308
309 static void build_rdl_regular_level_names(const unsigned count_regular_level, std::unique_ptr<d_fname[]> &names)
310 {
311 for (auto &&[idx, name] : enumerate(std::span(names.get(), count_regular_level), 1u))
312 {
313 cf_assert(idx <= count_regular_level);
314 snprintf(name.data(), name.size(), "level%02u.rdl", idx);
315 }
316 }
317
318 static void build_rdl_secret_level_names(const unsigned count_secret_level, std::unique_ptr<d_fname[]> &names)
319 {
320 for (auto &&[idx, name] : enumerate(std::span(names.get(), count_secret_level), 1u))
321 {
322 cf_assert(idx <= count_secret_level);
323 snprintf(name.data(), name.size(), "levels%1u.rdl", idx);
324 }
325 }
326
327 //
328 // Special versions of mission routines for d1 builtins
329 //
330
331 static void load_mission_d1()
332 {
333 switch (descent_hog_size{PHYSFSX_fsize(descent_hog_basename)})
334 {
335 case descent_hog_size::pc_shareware_v14:
336 case descent_hog_size::pc_shareware_v10:
337 allocate_shareware_levels(7, 0);
338 break;
339 case descent_hog_size::mac_shareware:
340 allocate_shareware_levels(3, 0);
341 break;
342 case descent_hog_size::pc_oem_v14:
343 case descent_hog_size::pc_oem_v10:
344 {
345 constexpr unsigned last_level = 15;
346 constexpr unsigned last_secret_level = 1;
347 allocate_levels(last_level, last_secret_level);
348 //build level names
349 build_rdl_regular_level_names(last_level - 1, Current_mission->level_names);
350 {
351 auto &ln = Current_mission->level_names[last_level - 1];
352 snprintf(ln.data(), ln.size(), "saturn%02d.rdl", last_level);
353 }
354 build_rdl_secret_level_names(last_secret_level, Current_mission->secret_level_names);
355 Current_mission->secret_level_table[0] = 10;
356 Current_mission->briefing_text_filename = "briefsat.txb";
357 Current_mission->ending_text_filename = BIMD1_ENDING_FILE_OEM;
358 }
359 break;
360 default:
361 Int3();
362 [[fallthrough]];
363 case descent_hog_size::pc_retail_v15:
364 case descent_hog_size::pc_retail_v15_alt1:
365 case descent_hog_size::pc_retail_v10:
366 case descent_hog_size::mac_retail:
367 {
368 constexpr unsigned last_level = 27;
369 constexpr unsigned last_secret_level = 3;
370 allocate_levels(last_level, last_secret_level);
371
372 //build level names
373 build_rdl_regular_level_names(last_level, Current_mission->level_names);
374 build_rdl_secret_level_names(last_secret_level, Current_mission->secret_level_names);
375 Current_mission->secret_level_table[0] = 10;
376 Current_mission->secret_level_table[1] = 21;
377 Current_mission->secret_level_table[2] = 24;
378 Current_mission->briefing_text_filename = BIMD1_BRIEFING_FILE;
379 Current_mission->ending_text_filename = "endreg.txb";
380 break;
381 }
382 }
383 }
384
385 #if DXX_BUILD_DESCENT == 2
386 //
387 // Special versions of mission routines for shareware
388 //
389
390 static void load_mission_shareware()
391 {
392 Current_mission->mission_name.copy_if(SHAREWARE_MISSION_NAME);
393 Current_mission->descent_version = Mission::descent_version_type::descent2;
394 Current_mission->anarchy_only_flag = Mission::anarchy_only_level::allow_any_game;
395
396 switch (Current_mission->builtin_hogsize)
397 {
398 case descent_hog_size::d2_mac_shareware:
399 {
400 constexpr unsigned last_level = 4;
401 allocate_levels(last_level, 1);
402 }
403 // mac demo is using the regular hog and rl2 files
404 Current_mission->level_names[0] = "d2leva-1.rl2";
405 Current_mission->level_names[1] = "d2leva-2.rl2";
406 Current_mission->level_names[2] = "d2leva-3.rl2";
407 Current_mission->level_names[3] = "d2leva-4.rl2";
408 Current_mission->secret_level_names[0] = "d2leva-s.rl2";
409 break;
410 default:
411 Int3();
412 [[fallthrough]];
413 case descent_hog_size::d2_shareware:
414 {
415 constexpr unsigned last_level = 3;
416 allocate_levels(last_level, 0);
417 }
418 Current_mission->level_names[0] = "d2leva-1.sl2";
419 Current_mission->level_names[1] = "d2leva-2.sl2";
420 Current_mission->level_names[2] = "d2leva-3.sl2";
421 break;
422 }
423 }
424
425
426 //
427 // Special versions of mission routines for Diamond/S3 version
428 //
429
430 static void load_mission_oem()
431 {
432 Current_mission->mission_name.copy_if(OEM_MISSION_NAME);
433 Current_mission->descent_version = Mission::descent_version_type::descent2;
434 Current_mission->anarchy_only_flag = Mission::anarchy_only_level::allow_any_game;
435
436 {
437 constexpr unsigned last_level = 8;
438 allocate_levels(last_level, 2);
439 }
440 Current_mission->level_names[0] = "d2leva-1.rl2";
441 Current_mission->level_names[1] = "d2leva-2.rl2";
442 Current_mission->level_names[2] = "d2leva-3.rl2";
443 Current_mission->level_names[3] = "d2leva-4.rl2";
444 Current_mission->secret_level_names[0] = "d2leva-s.rl2";
445 Current_mission->level_names[4] = "d2levb-1.rl2";
446 Current_mission->level_names[5] = "d2levb-2.rl2";
447 Current_mission->level_names[6] = "d2levb-3.rl2";
448 Current_mission->level_names[7] = "d2levb-4.rl2";
449 Current_mission->secret_level_names[1] = "d2levb-s.rl2";
450 Current_mission->secret_level_table[0] = 1;
451 Current_mission->secret_level_table[1] = 5;
452 }
453 #endif
454
455 //compare a string for a token. returns true if match
456 static int istok(const char *buf,const char *tok)
457 {
458 return d_strnicmp(buf,tok,strlen(tok)) == 0;
459 }
460
461 //returns ptr to string after '=' & white space, or NULL if no '='
462 static const char *get_value(const char *buf)
463 {
464 if (auto t = strchr(buf, '='))
465 {
466 while (isspace(static_cast<unsigned>(*++t)));
467 if (*t)
468 return t;
469 }
470 return NULL; //error!
471 }
472
473 static mission_name_and_version get_any_mission_type_name_value(PHYSFSX_gets_line_t<80> &buf, PHYSFS_File *const f, const Mission::descent_version_type descent_version)
474 {
475 if (!PHYSFSX_fgets(buf,f))
476 return {};
477 if (istok(buf, "name"))
478 return {descent_version, get_value(buf)};
479 #if DXX_BUILD_DESCENT == 2
480 if (descent_version == Mission::descent_version_type::descent1)
481 /* If reading a Descent 1 `.msn` file, do not check for the
482 * extended mission types. D1X-Rebirth would ignore them, so
483 * D2X-Rebirth should also ignore them.
484 */
485 return {};
486 struct name_type_pair
487 {
488 /* std::pair cannot be used here because direct initialization
489 * from a string literal fails to compile.
490 */
491 char name[7];
492 Mission::descent_version_type descent_version;
493 };
494 static constexpr name_type_pair mission_name_type_values[] = {
495 {"xname", Mission::descent_version_type::descent2x}, // enhanced mission
496 {"zname", Mission::descent_version_type::descent2z}, // super-enhanced mission
497 {"!name", Mission::descent_version_type::descent2a}, // extensible-enhanced mission
498 };
499 for (auto &&[name, descent_version] : mission_name_type_values)
500 {
501 if (istok(buf, name))
502 return {descent_version, get_value(buf)};
503 }
504 #endif
505 return {};
506 }
507
508 static bool ml_sort_func(const mle &e0,const mle &e1)
509 {
510 const auto d0 = e0.directory.empty();
511 const auto d1 = e1.directory.empty();
512 if (d0 != d1)
513 /* If d0 is a directory and d1 is a mission, or if d0 is a
514 * mission and d1 is a directory, then apply a special case.
515 *
516 * Consider d0 to be less (and therefore ordered earlier) if d1
517 * is a mission. This moves directories to the top of the list.
518 */
519 return d1;
520 /* If both d0 and d1 are directories, or if both are missions, then
521 * apply the usual sorting rule. This makes directories sort
522 * as usual relative to each other.
523 */
524 return d_stricmp(e0.mission_name,e1.mission_name) < 0;
525 }
526
527 }
528
529 //returns 1 if file read ok, else 0
530 namespace dsx {
531
532 namespace {
533
534 static const mle *read_mission_file(mission_list_type &mission_list, std::string_view str_pathname, const descent_hog_size descent_hog_size, const mission_filter_mode mission_filter)
535 {
536 if (const auto mfile = PHYSFSX_openReadBuffered(str_pathname.data()).first)
537 {
538 const auto idx_last_slash{str_pathname.find_last_of('/')};
539 /* If no slash is found, the filename starts at the beginning of the
540 * view. If a slash is found, the filename starts at the next
541 * character after the slash.
542 */
543 const auto idx_filename{(idx_last_slash == str_pathname.npos) ? 0 : idx_last_slash + 1};
544 const auto idx_file_extension{str_pathname.find_first_of('.', {idx_filename})};
545 if (idx_file_extension == str_pathname.npos)
546 return nullptr; //missing extension
547 if (idx_file_extension >= DXX_MAX_MISSION_PATH_LENGTH)
548 return nullptr; // path too long, would be truncated in save game files
549 #if DXX_BUILD_DESCENT == 1
550 constexpr auto descent_version = Mission::descent_version_type::descent1;
551 #elif DXX_BUILD_DESCENT == 2
552 // look if it's .mn2 or .msn
553 const auto descent_version = (str_pathname[idx_file_extension + 3] == MISSION_EXTENSION_DESCENT_II[3])
554 ? Mission::descent_version_type::descent2
555 : Mission::descent_version_type::descent1;
556 #endif
557 str_pathname.remove_suffix(str_pathname.size() - idx_file_extension);
558
559 PHYSFSX_gets_line_t<80> buf;
560 const auto &&nv = get_any_mission_type_name_value(buf, mfile, descent_version);
561 const auto &p = nv.name;
562 if (!p)
563 return nullptr;
564
565 const auto semicolon = strchr(p, ';');
566 /* If a semicolon exists, point to it. Otherwise, point to the
567 * null byte terminating the buffer.
568 */
569 auto t = semicolon ? semicolon : std::next(p, strlen(p));
570 /* Iterate backward until either the beginning of the buffer or the
571 * first non-whitespace character.
572 */
573 for (; t != p && isspace(static_cast<unsigned>(*t));)
574 {
575 -- t;
576 }
577
578 auto anarchy_only_flag{Mission::anarchy_only_level::allow_any_game};
579 if (PHYSFSX_gets_line_t<64> temp; PHYSFSX_fgets(temp, mfile))
580 {
581 if (istok(temp,"type"))
582 {
583 //get mission type
584 if (const auto p = get_value(temp))
585 {
586 if (istok(p, "anarchy"))
587 {
588 if (mission_filter == mission_filter_mode::exclude_anarchy)
589 return nullptr;
590 anarchy_only_flag = Mission::anarchy_only_level::only_anarchy_games;
591 }
592 }
593 }
594 }
595 return &mission_list.emplace_back(
596 /* Cast to ptrdiff_t is safe, because
597 * `if (idx_file_extension >= DXX_MAX_MISSION_PATH_LENGTH)` is
598 * true, then execution does not reach this line. All values in
599 * [0, DXX_MAX_MISSION_PATH_LENGTH) can be represented by
600 * `std::ptrdiff_t`, so no narrowing occurs.
601 */
602 Mission_path{str_pathname, static_cast<std::ptrdiff_t>(idx_filename)},
603 descent_hog_size,
604 #if DXX_BUILD_DESCENT == 2
605 nv.descent_version,
606 #endif
607 anarchy_only_flag,
608 std::span(p, std::min<std::size_t>(mle::maximum_mission_name_length, std::distance(p, t)))
609 );
610 }
611 return nullptr;
612 }
613
614 static std::span<const char> get_d1_mission_name_from_descent_hog_size(const descent_hog_size size)
615 {
616 switch (size) {
617 case descent_hog_size::pc_shareware_v14:
618 case descent_hog_size::pc_shareware_v10:
619 case descent_hog_size::mac_shareware:
620 return D1_SHAREWARE_MISSION_NAME;
621 case descent_hog_size::pc_oem_v14:
622 case descent_hog_size::pc_oem_v10:
623 return D1_OEM_MISSION_NAME;
624 default:
625 Warning("Unknown D1 hogsize %d", underlying_value(size));
626 Int3();
627 [[fallthrough]];
628 case descent_hog_size::pc_retail_v15:
629 case descent_hog_size::pc_retail_v15_alt1:
630 case descent_hog_size::pc_retail_v10:
631 case descent_hog_size::mac_retail:
632 return D1_MISSION_NAME;
633 }
634 }
635
636 static void add_d1_builtin_mission_to_list(mission_list_type &mission_list)
637 {
638 const descent_hog_size size{PHYSFSX_fsize(descent_hog_basename)};
639 if (size == descent_hog_size{-1})
640 return;
641
642 mission_list.emplace_back(
643 Mission_path{D1_MISSION_FILENAME, 0},
644 size,
645 #if DXX_BUILD_DESCENT == 2
646 Mission::descent_version_type::descent1, /* The Descent 1 builtin campaign is always treated as a Descent 1 mission. */
647 #endif
648 Mission::anarchy_only_level::allow_any_game,
649 get_d1_mission_name_from_descent_hog_size(size)
650 );
651 }
652
653 #if DXX_BUILD_DESCENT == 2
654 template <std::size_t N1, std::size_t N2>
655 static const mle *set_hardcoded_mission(mission_list_type &mission_list, const char (&path)[N1], const char (&mission_name)[N2], const descent_hog_size descent_hog_size)
656 {
657 return &mission_list.emplace_back(
658 Mission_path{path, 0},
659 descent_hog_size,
660 Mission::descent_version_type::descent2,
661 Mission::anarchy_only_level::allow_any_game,
662 mission_name
663 );
664 }
665
666 static void add_builtin_mission_to_list(mission_list_type &mission_list, d_fname &name)
667 {
668 descent_hog_size size{PHYSFSX_fsize(descent2_hog_basename)};
669 if (size == descent_hog_size{-1})
670 size = descent_hog_size{PHYSFSX_fsize(d2demo_hog_basename)};
671
672 const mle *mission;
673 switch (size) {
674 case descent_hog_size::d2_shareware:
675 case descent_hog_size::d2_mac_shareware:
676 mission = set_hardcoded_mission(mission_list, SHAREWARE_MISSION_FILENAME, SHAREWARE_MISSION_NAME, size);
677 break;
678 case descent_hog_size::d2_oem_v11:
679 mission = set_hardcoded_mission(mission_list, OEM_MISSION_FILENAME, OEM_MISSION_NAME, size);
680 break;
681 default:
682 Warning("Unknown hogsize %d, trying %s", underlying_value(size), FULL_MISSION_FILENAME MISSION_EXTENSION_DESCENT_II);
683 Int3();
684 [[fallthrough]];
685 case descent_hog_size::d2_full:
686 case descent_hog_size::d2_full_v10:
687 case descent_hog_size::d2_mac_full:
688 if (const std::string_view full_mission_filename{{FULL_MISSION_FILENAME MISSION_EXTENSION_DESCENT_II}}; !(mission = read_mission_file(mission_list, full_mission_filename, size, mission_filter_mode::include_anarchy)))
689 Error("Could not find required mission file <%s>", FULL_MISSION_FILENAME MISSION_EXTENSION_DESCENT_II);
690 }
691 name.copy_if(mission->path.c_str(), FILENAME_LEN);
692 }
693 #endif
694
695 static void add_missions_to_list(mission_list_type &mission_list, mission_candidate_search_path &path, const mission_candidate_search_path::iterator rel_path, const mission_filter_mode mission_filter)
696 {
697 /* rel_path must point within the array `path`.
698 * rel_path must point to the null that follows a possibly empty
699 * directory prefix.
700 * If the directory prefix is not empty, it must end with a PHYSFS
701 * path separator, which is always slash, even on Windows.
702 *
703 * If any of these assertions fail, then the path transforms used to
704 * recurse into subdirectories and to open individual missions will
705 * not work correctly.
706 */
707 assert(std::distance(path.begin(), rel_path) < path.size() - 1);
708 assert(!*rel_path);
709 assert(path.begin() == rel_path || *std::prev(rel_path) == '/');
710 const std::size_t space_remaining = std::distance(rel_path, path.end());
711 *rel_path = '.';
712 *std::next(rel_path) = 0;
713 const PHYSFSX_uncounted_list s{PHYSFS_enumerateFiles(path.data())};
714 if (!s)
715 return;
716 for (const auto i : s)
717 {
718 /* Add 1 to include the terminating null. */
719 const std::size_t il = strlen(i) + 1;
720 /* Add 2 for the slash+dot in case it is a directory. */
721 if (il + 2 >= space_remaining)
722 continue; // path is too long
723
724 auto j = std::copy_n(i, il, rel_path);
725 const char *ext;
726 if (PHYSFS_isDirectory(path.data()))
727 {
728 const auto null = std::prev(j);
729 *j = 0;
730 *null = '/';
731 mission_list_type sublist;
732 add_missions_to_list(sublist, path, j, mission_filter);
733 *null = 0;
734 const auto found = sublist.size();
735 if (!found)
736 {
737 /* Ignore empty directories */
738 }
739 else if (found == 1)
740 {
741 /* If only one found, promote it up to the next level so
742 * the user does not need to navigate into a
743 * single-element directory.
744 */
745 auto &sli = sublist.front();
746 mission_list.emplace_back(std::move(sli));
747 }
748 else
749 {
750 std::sort(sublist.begin(), sublist.end(), ml_sort_func);
751 mission_list.emplace_back(path.data(), std::move(sublist));
752 }
753 }
754 else if (il > 5 &&
755 ((ext = &i[il - 5], !d_strnicmp(ext, MISSION_EXTENSION_DESCENT_I))
756 #if DXX_BUILD_DESCENT == 2
757 || !d_strnicmp(ext, MISSION_EXTENSION_DESCENT_II)
758 #endif
759 ))
760 read_mission_file(mission_list, path.data(), descent_hog_size::None, mission_filter);
761 if (mission_list.size() >= MAX_MISSIONS)
762 {
763 break;
764 }
765 *rel_path = 0; // chop off the entry
766 DXX_POISON_MEMORY(std::span(std::next(rel_path), path.end()), 0xcc);
767 }
768 }
769
770 }
771
772 }
773
774 namespace {
775
776 /* move <mission_name> to <place> on mission list, increment <place> */
777 [[nodiscard]]
778 static std::size_t promote(mission_list_type &mission_list, const char *const name, const std::size_t top_place)
779 {
780 range_for (auto &i, partial_range(mission_list, top_place, mission_list.size()))
781 if (!d_stricmp(&*i.filename, name)) {
782 //swap mission positions
783 auto &j = mission_list[top_place];
784 if (&j != &i)
785 std::swap(j, i);
786 return top_place + 1;
787 }
788 return top_place;
789 }
790
791 }
792
793 Mission::~Mission()
794 {
795 // May become more complex with the editor
796 if (!path.empty() && builtin_hogsize == descent_hog_size::None)
797 {
798 char hogpath[PATH_MAX];
799 snprintf(hogpath, sizeof(hogpath), "%s.hog", path.c_str());
800 PHYSFSX_removeRelFromSearchPath(hogpath);
801 }
802 }
803
804 //fills in the global list of missions. Returns the number of missions
805 //in the list. If anarchy_mode is set, then also add anarchy-only missions.
806
807 namespace dsx {
808
809 namespace {
810
811 static mission_list_type build_mission_list(const mission_filter_mode mission_filter)
812 {
813 //now search for levels on disk
814
815 //@@Took out this code because after this routine was called once for
816 //@@a list of single-player missions, a subsequent call for a list of
817 //@@anarchy missions would not scan again, and thus would not find the
818 //@@anarchy-only missions. If we retain the minimum level of install,
819 //@@we may want to put the code back in, having it always scan for all
820 //@@missions, and have the code that uses it sort out the ones it wants.
821 //@@ if (num_missions != -1) {
822 //@@ if (Current_mission_num != 0)
823 //@@ load_mission(0); //set built-in mission as default
824 //@@ return num_missions;
825 //@@ }
826
827 mission_list_type mission_list;
828
829 #if DXX_BUILD_DESCENT == 2
830 d_fname builtin_mission_filename;
831 add_builtin_mission_to_list(mission_list, builtin_mission_filename); //read built-in first
832 #endif
833 add_d1_builtin_mission_to_list(mission_list);
834 mission_candidate_search_path search_str{{MISSION_DIR}};
835 DXX_POISON_MEMORY(std::span(search_str).subspan<sizeof(MISSION_DIR)>(), 0xcc);
836 add_missions_to_list(mission_list, search_str, std::next(search_str.begin(), sizeof(MISSION_DIR) - 1), mission_filter);
837
838 // move original missions (in story-chronological order)
839 // to top of mission list
840 std::size_t top_place{};
841 top_place = promote(mission_list, D1_MISSION_FILENAME, top_place); // original descent 1 mission
842 #if DXX_BUILD_DESCENT == 2
843 top_place = promote(mission_list, builtin_mission_filename, top_place); // d2 or d2demo
844 top_place = promote(mission_list, "d2x", top_place); // vertigo
845 #endif
846
847 if (mission_list.size() > top_place)
848 std::sort(next(begin(mission_list), top_place), end(mission_list), ml_sort_func);
849 return mission_list;
850 }
851
852 }
853
854 #if DXX_BUILD_DESCENT == 2
855 //values for built-in mission
856
857 int load_mission_ham()
858 {
859 read_hamfile(LevelSharedRobotInfoState); // intentionally can also read from the HOG
860
861 if (Piggy_hamfile_version >= pig_hamfile_version::_3)
862 {
863 // re-read sounds in case mission has custom .sXX
864 Num_sound_files = 0;
865 read_sndfile(0);
866 piggy_read_sounds();
867 }
868
869 if (Current_mission->descent_version == Mission::descent_version_type::descent2a &&
870 Current_mission->alternate_ham_file)
871 {
872 /*
873 * If an alternate HAM is specified, map a HOG of the same name
874 * (if it exists) so that users can reference a HAM within a
875 * HOG. This is required to let users reference the D2X.HAM
876 * file provided by Descent II: Vertigo.
877 *
878 * Try both plain NAME and missions/NAME, in that order.
879 */
880 auto &altham = Current_mission->alternate_ham_file;
881 unsigned l = strlen(*altham);
882 char althog[PATH_MAX];
883 snprintf(althog, sizeof(althog), MISSION_DIR "%.*s.hog", l - 4, static_cast<const char *>(*altham));
884 char *p = althog + sizeof(MISSION_DIR) - 1;
885 const auto mount_hog = make_PHYSFSX_ComputedPathMount(p, althog, physfs_search_path::prepend);
886 bm_read_extra_robots(*altham, Mission::descent_version_type::descent2z);
887 return 1;
888 }
889 else if (Current_mission->descent_version == Mission::descent_version_type::descent2a ||
890 Current_mission->descent_version == Mission::descent_version_type::descent2z ||
891 Current_mission->descent_version == Mission::descent_version_type::descent2x)
892 {
893 char t[50];
894 snprintf(t,sizeof(t), "%s.ham", &*Current_mission->filename);
895 bm_read_extra_robots(t, Current_mission->descent_version);
896 return 1;
897 } else
898 return 0;
899 }
900 #endif
901 }
902
903 namespace {
904
905 #define tex ".tex"
906 static void set_briefing_filename(d_fname &f, const std::span<const char> v)
907 {
908 f.copy_if(v.data(), v.size());
909 f.copy_if(v.size(), tex);
910 if (!PHYSFSX_exists_ignorecase(f.data()) &&
911 !(f.copy_if(v.size() + 1, "txb"), PHYSFSX_exists_ignorecase(f.data()))) // check if this file exists ...
912 f = {};
913 }
914
915 static void set_briefing_filename(d_fname &f, const char *const v)
916 {
917 using std::next;
918 auto a = [](char c) {
919 return !c || c == '.';
920 };
921 const auto &&i{std::ranges::find_if(v, next(v, f.size() - sizeof(tex)), a)};
922 std::size_t d = std::distance(v, i);
923 set_briefing_filename(f, {v, d});
924 }
925
926 static void record_briefing(d_fname &f, const std::array<char, PATH_MAX> &buf)
927 {
928 const auto v = get_value(buf.data());
929 if (!v)
930 return;
931 const std::size_t d = std::distance(v, std::ranges::find_if(v, buf.end(), null_or_space));
932 if (d >= FILENAME_LEN)
933 return;
934 {
935 set_briefing_filename(f, {v, std::min(d, f.size() - sizeof(tex))});
936 }
937 }
938 #undef tex
939
940 }
941
942 //loads the specified mission from the mission list.
943 //build_mission_list() must have been called.
944 //Returns true if mission loaded ok, else false.
945 namespace dsx {
946
947 namespace {
948
949 static const char *load_mission(const mle *const mission)
950 {
951 Current_mission = std::make_unique<Mission>(static_cast<const Mission_path &>(*mission));
952 Current_mission->builtin_hogsize = mission->builtin_hogsize;
953 Current_mission->mission_name.copy_if(mission->mission_name);
954 #if DXX_BUILD_DESCENT == 2
955 Current_mission->descent_version = mission->descent_version;
956 #endif
957 Current_mission->anarchy_only_flag = mission->anarchy_only_flag;
958
959 // for Descent 1 missions, load descent.hog
960 #if DXX_BUILD_DESCENT == 2
961 if (EMULATING_D1)
962 #endif
963 {
964 std::array<char, PATH_MAX> pathname;
965 if (const auto r = PHYSFSX_addRelToSearchPath(descent_hog_basename, pathname, physfs_search_path::prepend); r != PHYSFS_ERR_OK)
966 #if DXX_BUILD_DESCENT == 1
967 Error("descent.hog not available!\n%s", PHYSFS_getErrorByCode(r));
968 #elif DXX_BUILD_DESCENT == 2
969 Warning("descent.hog not available!\n%s\nThis mission may be missing some files required for briefings and exit sequence.", PHYSFS_getErrorByCode(r));
970 #endif
971 if (!d_stricmp(Current_mission->path.c_str(), D1_MISSION_FILENAME))
972 {
973 load_mission_d1();
974 return nullptr;
975 }
976 }
977 #if DXX_BUILD_DESCENT == 2
978 else
979 PHYSFSX_removeRelFromSearchPath(descent_hog_basename);
980 #endif
981
982 #if DXX_BUILD_DESCENT == 2
983 if (PLAYING_BUILTIN_MISSION) {
984 switch (Current_mission->builtin_hogsize) {
985 case descent_hog_size::d2_shareware:
986 case descent_hog_size::d2_mac_shareware:
987 Current_mission->briefing_text_filename = "brief2.txb";
988 Current_mission->ending_text_filename = BIMD2_ENDING_FILE_SHARE;
989 load_mission_shareware();
990 return nullptr;
991 case descent_hog_size::d2_oem_v11:
992 Current_mission->briefing_text_filename = "brief2o.txb";
993 Current_mission->ending_text_filename = BIMD2_ENDING_FILE_OEM;
994 load_mission_oem();
995 return nullptr;
996 default:
997 Int3();
998 [[fallthrough]];
999 case descent_hog_size::d2_full:
1000 case descent_hog_size::d2_full_v10:
1001 case descent_hog_size::d2_mac_full:
1002 Current_mission->briefing_text_filename = "robot.txb";
1003 // continue on... (use d2.mn2 from hogfile)
1004 break;
1005 }
1006 }
1007 #endif
1008
1009 //read mission from file
1010
1011 auto &msn_extension =
1012 #if DXX_BUILD_DESCENT == 2
1013 (mission->descent_version != Mission::descent_version_type::descent1) ? MISSION_EXTENSION_DESCENT_II :
1014 #endif
1015 MISSION_EXTENSION_DESCENT_I;
1016 std::array<char, PATH_MAX> mission_filename;
1017 snprintf(mission_filename.data(), mission_filename.size(), "%s%s", mission->path.c_str(), msn_extension);
1018
1019 auto &&[mfile, physfserr] = PHYSFSX_openReadBuffered_updateCase(mission_filename.data());
1020 if (!mfile) {
1021 Current_mission.reset();
1022 con_printf(CON_NORMAL, DXX_STRINGIZE_FL(__FILE__, __LINE__, "error: failed to open mission \"%s\": %s"), mission_filename.data(), PHYSFS_getErrorByCode(physfserr));
1023 return "Failed to open mission file"; //error!
1024 }
1025
1026 //for non-builtin missions, load HOG
1027 #if DXX_BUILD_DESCENT == 2
1028 Current_mission->descent_version = mission->descent_version;
1029 if (!PLAYING_BUILTIN_MISSION)
1030 #endif
1031 {
1032 strcpy(&mission_filename[mission->path.size() + 1], "hog"); //change extension
1033 std::array<char, PATH_MAX> pathname;
1034 PHYSFSX_addRelToSearchPath(mission_filename.data(), pathname, physfs_search_path::prepend);
1035 set_briefing_filename(Current_mission->briefing_text_filename, &*Current_mission->filename);
1036 Current_mission->ending_text_filename = Current_mission->briefing_text_filename;
1037 }
1038
1039 for (PHYSFSX_gets_line_t<PATH_MAX> buf; PHYSFSX_fgets(buf,mfile);)
1040 {
1041 if (istok(buf,"type"))
1042 continue; //already have name, go to next line
1043 else if (istok(buf,"briefing")) {
1044 record_briefing(Current_mission->briefing_text_filename, buf.line());
1045 }
1046 else if (istok(buf,"ending")) {
1047 record_briefing(Current_mission->ending_text_filename, buf.line());
1048 }
1049 else if (istok(buf,"num_levels")) {
1050 if (const auto v{get_value(buf)})
1051 {
1052 char *ip;
1053 const auto n_levels = strtoul(v, &ip, 10);
1054 Assert(n_levels <= MAX_LEVELS_PER_MISSION);
1055 if (n_levels > MAX_LEVELS_PER_MISSION)
1056 continue;
1057 if (*ip)
1058 {
1059 while (isspace(static_cast<unsigned>(*ip)))
1060 ++ip;
1061 if (*ip && *ip != ';')
1062 continue;
1063 }
1064 auto names = std::make_unique<d_fname[]>(n_levels);
1065 uint8_t level_names_loaded{0};
1066 for (auto &i : unchecked_partial_range(names.get(), n_levels))
1067 {
1068 if (!PHYSFSX_fgets(buf, mfile))
1069 break;
1070 auto &line = buf.line();
1071 const auto &&s{std::ranges::find_if(line, null_or_space)};
1072 if (i.copy_if(line, std::distance(line.begin(), s)))
1073 {
1074 ++level_names_loaded;
1075 }
1076 else
1077 break;
1078 }
1079 Current_mission->last_level = level_names_loaded;
1080 Current_mission->level_names = std::move(names);
1081 }
1082 }
1083 else if (istok(buf,"num_secrets")) {
1084 if (const auto v{get_value(buf)})
1085 {
1086 char *ip;
1087 const auto n_levels = strtoul(v, &ip, 10);
1088 Assert(n_levels <= MAX_SECRET_LEVELS_PER_MISSION);
1089 if (n_levels > MAX_SECRET_LEVELS_PER_MISSION)
1090 continue;
1091 if (*ip)
1092 {
1093 while (isspace(static_cast<unsigned>(*ip)))
1094 ++ip;
1095 if (*ip && *ip != ';')
1096 continue;
1097 }
1098 Current_mission->n_secret_levels = n_levels;
1099 uint8_t level_names_loaded{0};
1100 auto names = std::make_unique<d_fname[]>(n_levels);
1101 auto table = std::make_unique<uint8_t[]>(n_levels);
1102 for (auto &&[name, table_cell] : zip(unchecked_partial_range(names.get(), n_levels), unchecked_partial_range(table.get(), n_levels)))
1103 {
1104 if (!PHYSFSX_fgets(buf, mfile))
1105 break;
1106 const auto &line = buf.line();
1107 const auto lb = line.begin();
1108 /* No auto: returned value must be type const char*
1109 * Modern glibc maintains const-ness of the input.
1110 * Apple libc++ and mingw32 do not.
1111 */
1112 const char *const t = strchr(lb, ',');
1113 if (!t)
1114 break;
1115 auto a = [](char c) {
1116 return isspace(static_cast<unsigned>(c));
1117 };
1118 const auto &&s{std::ranges::find_if(lb, t, a)};
1119 if (name.copy_if(line, std::distance(lb, s)))
1120 {
1121 unsigned long ls = strtoul(t + 1, &ip, 10);
1122 if (ls < 1 || ls > Current_mission->last_level)
1123 break;
1124 table_cell = ls;
1125 ++ level_names_loaded;
1126 }
1127 else
1128 break;
1129 }
1130 Current_mission->last_secret_level = -static_cast<signed>(level_names_loaded);
1131 Current_mission->secret_level_names = std::move(names);
1132 Current_mission->secret_level_table = std::move(table);
1133 }
1134 }
1135 #if DXX_BUILD_DESCENT == 2
1136 else if (Current_mission->descent_version == Mission::descent_version_type::descent2a && buf[0u] == '!') {
1137 if (istok(buf+1,"ham")) {
1138 Current_mission->alternate_ham_file = std::make_unique<d_fname>();
1139 if (const auto v{get_value(buf)})
1140 {
1141 unsigned l = strlen(v);
1142 if (l <= 4)
1143 con_printf(CON_URGENT, "Mission %s has short HAM \"%s\".", Current_mission->path.c_str(), v);
1144 else if (l >= sizeof(*Current_mission->alternate_ham_file))
1145 con_printf(CON_URGENT, "Mission %s has excessive HAM \"%s\".", Current_mission->path.c_str(), v);
1146 else {
1147 Current_mission->alternate_ham_file->copy_if(v, l + 1);
1148 con_printf(CON_VERBOSE, "Mission %s will use HAM %s.", Current_mission->path.c_str(), static_cast<const char *>(*Current_mission->alternate_ham_file));
1149 }
1150 }
1151 else
1152 con_printf(CON_URGENT, "Mission %s has no HAM.", Current_mission->path.c_str());
1153 }
1154 else {
1155 con_printf(CON_URGENT, "Mission %s uses unsupported critical directive \"%s\".", Current_mission->path.c_str(), static_cast<const char *>(buf));
1156 Current_mission->last_level = 0;
1157 break;
1158 }
1159 }
1160 #endif
1161
1162 }
1163 mfile.reset();
1164 if (Current_mission->last_level <= 0)
1165 {
1166 Current_mission.reset(); //no valid mission loaded
1167 return "Failed to parse mission file";
1168 }
1169
1170 #if DXX_BUILD_DESCENT == 2
1171 // re-read default HAM file, in case this mission brings it's own version of it
1172 free_polygon_models(LevelSharedPolygonModelState);
1173
1174 if (load_mission_ham())
1175 Current_mission->extra_robot_movie = init_extra_robot_movie(&*Current_mission->filename);
1176 #endif
1177 return nullptr;
1178 }
1179
1180 }
1181
1182 //loads the named mission if exists.
1183 //Returns nullptr if mission loaded ok, else error string.
1184 const char *load_mission_by_name (const mission_entry_predicate mission_name, const mission_name_type name_match_mode)
1185 {
1186 auto &&mission_list = build_mission_list(mission_filter_mode::include_anarchy);
1187 {
1188 range_for (auto &i, mission_list)
1189 {
1190 switch (name_match_mode)
1191 {
1192 case mission_name_type::basename:
1193 if (!d_stricmp(mission_name.filesystem_name, &*i.filename))
1194 return load_mission(&i);
1195 continue;
1196 case mission_name_type::pathname:
1197 case mission_name_type::guess:
1198 if (const auto r = compare_mission_by_pathname(mission_name, i))
1199 return load_mission(r);
1200 continue;
1201 default:
1202 return "Unhandled load mission type";
1203 }
1204 }
1205 }
1206 if (name_match_mode == mission_name_type::guess)
1207 {
1208 const auto p = strrchr(mission_name.filesystem_name, '/');
1209 const auto &guess_predicate = p
1210 ? mission_name.with_filesystem_name(p + 1)
1211 : mission_name;
1212 range_for (auto &i, mission_list)
1213 {
1214 if (const auto r = compare_mission_by_guess(guess_predicate, i))
1215 {
1216 con_printf(CON_NORMAL, "%s:%u: request for guessed mission name \"%s\" found \"%s\"", __FILE__, __LINE__, mission_name.filesystem_name, r->path.c_str());
1217 return load_mission(r);
1218 }
1219 }
1220 }
1221 return "No matching mission found in\ninstalled mission list.";
1222 }
1223
1224 }
1225
1226 namespace {
1227
1228 template <typename tag>
1229 class unique_menu_tagged_string : std::unique_ptr<char[]>
1230 {
1231 public:
1232 unique_menu_tagged_string(std::unique_ptr<char[]> p) :
1233 std::unique_ptr<char[]>(std::move(p))
1234 {
1235 }
1236 using std::unique_ptr<char[]>::get;
1237 operator menu_tagged_string<tag>() const &
1238 {
1239 return {get()};
1240 }
1241 operator menu_tagged_string<tag>() const && = delete;
1242 };
1243
1244 struct mission_menu : listbox
1245 {
1246 static constexpr char listbox_go_up[] = "<..>";
1247 using callback_type = window_event_result (*)(void);
1248 /* The top level menu stores the mission data in a member variable.
1249 * When this class is the base of toplevel_mission_menu, this
1250 * reference points to that member variable in
1251 * toplevel_mission_menu.
1252 *
1253 * Subdirectory menus do not store a copy of the mission data, and
1254 * instead store a reference to the mission data in the top level
1255 * menu. When this class is the base of subdirectory_mission_menu,
1256 * this reference points to the member variable in the
1257 * toplevel_mission_menu that created this subdirectory_mission_menu.
1258 *
1259 * The data is not reference counted, because the top level menu
1260 * always outlives the subdirectory menus.
1261 */
1262 const mission_list_type &ml;
1263 /* listbox stores an unowned pointer to the string pointers that it
1264 * uses. This member variable stores an owned pointer to the same
1265 * string pointers, so that the string pointers persist for the life
1266 * of the listbox. The strings are stored elsewhere.
1267 */
1268 const std::unique_ptr<const char *[]> listbox_strings;
1269 /* listbox stores an unowned pointer to the title string, since some
1270 * listboxes use statically allocated strings. This member variable
1271 * owns the storage for this listbox's title.
1272 */
1273 const unique_menu_tagged_string<menu_title_tag> title;
1274 const callback_type when_selected;
1275 virtual window_event_result callback_handler(const d_event &, window_event_result) override;
1276 mission_menu(const mission_list_type &rml, const std::size_t count_name_pointer_strings, std::unique_ptr<const char *[]> &&name_pointer_strings, const char *const message, callback_type when_selected, mission_menu *const parent, const int default_item, grs_canvas &canvas) :
1277 mission_menu(rml, count_name_pointer_strings, std::move(name_pointer_strings), prepare_title(message, rml), when_selected, parent, default_item, canvas)
1278 {
1279 }
1280 protected:
1281 mission_menu *parent = nullptr;
1282 mission_menu(const mission_list_type &rml, const std::size_t count_name_pointer_strings, std::unique_ptr<const char *[]> &&name_pointer_strings, unique_menu_tagged_string<menu_title_tag> title_parameter, callback_type when_selected, mission_menu *const parent, const int default_item, grs_canvas &canvas) :
1283 listbox(default_item, count_name_pointer_strings, name_pointer_strings.get(), title_parameter, canvas, 1),
1284 ml(rml), listbox_strings(std::move(name_pointer_strings)),
1285 title(std::move(title_parameter)),
1286 when_selected(when_selected), parent(parent)
1287 {
1288 }
1289 static unique_menu_tagged_string<menu_title_tag> prepare_title(const char *const message, const mission_list_type &ml)
1290 {
1291 mission_subdir_stats ss;
1292 ss.count(ml);
1293 char buf[128];
1294 const auto r = 1u + std::snprintf(buf, sizeof(buf), "%s\n[%sMSN:LOCAL %zu; TOTAL %zu]", message, std::data(prepare_mission_list_count_dirbuf(ss.immediate_directories)), ss.immediate_missions, ss.total_missions);
1295 unique_menu_tagged_string<menu_title_tag> p = std::make_unique<char[]>(r);
1296 std::memcpy(p.get(), buf, r);
1297 return p;
1298 }
1299 };
1300
1301 struct toplevel_mission_menu_storage
1302 {
1303 protected:
1304 const mission_list_type mission_list_storage;
1305 toplevel_mission_menu_storage(mission_list_type &&rml) :
1306 mission_list_storage(std::move(rml))
1307 {
1308 }
1309 };
1310
1311 struct toplevel_mission_menu : toplevel_mission_menu_storage, mission_menu
1312 {
1313 public:
1314 toplevel_mission_menu(mission_list_type &&rml, std::unique_ptr<const char *[]> &&name_pointer_strings, const char *const message, callback_type when_selected, const int default_item, grs_canvas &canvas) :
1315 toplevel_mission_menu_storage(std::move(rml)),
1316 mission_menu(mission_list_storage, mission_list_storage.size(), std::move(name_pointer_strings), message, when_selected, nullptr /* no parent for toplevel menu */, default_item, canvas)
1317 {
1318 }
1319 };
1320
1321 struct subdirectory_mission_menu : mission_menu
1322 {
1323 using mission_menu::mission_menu;
1324 };
1325
1326 constexpr char mission_menu::listbox_go_up[];
1327
1328 struct mission_menu_create_state
1329 {
1330 std::unique_ptr<const char *[]> listbox_strings;
1331 unsigned initial_selection = UINT_MAX;
1332 std::unique_ptr<mission_menu_create_state> submenu;
1333 mission_menu_create_state(const std::size_t len) :
1334 listbox_strings(std::make_unique<const char *[]>(len))
1335 {
1336 }
1337 mission_menu_create_state(mission_menu_create_state &&) = default;
1338 };
1339
1340 }
1341
1342 window_event_result mission_menu::callback_handler(const d_event &event, window_event_result)
1343 {
1344 switch (event.type)
1345 {
1346 case event_type::window_created:
1347 break;
1348 case event_type::newmenu_selected:
1349 {
1350 const auto raw_citem = static_cast<const d_select_event &>(event).citem;
1351 auto citem = raw_citem;
1352 if (parent)
1353 {
1354 if (citem == 0)
1355 {
1356 /* Clear parent pointer so that the parent window is
1357 * not implicitly closed during handling of
1358 * event_type::window_close.
1359 */
1360 parent = nullptr;
1361 return window_event_result::close;
1362 }
1363 /* Adjust for the "Go up" placeholder item */
1364 -- citem;
1365 }
1366 if (citem >= 0)
1367 {
1368 auto &mli = ml[citem];
1369 if (!mli.directory.empty())
1370 {
1371 /* Increment by 1 to allow the pseudo-entry
1372 * `listbox_go_up`.
1373 */
1374 const std::size_t count_name_pointer_strings = mli.directory.size() + 1;
1375 auto listbox_strings = std::make_unique<const char *[]>(count_name_pointer_strings);
1376 listbox_strings[0] = listbox_go_up;
1377 const auto a = [](const mle &m) -> const char * {
1378 return m.mission_name;
1379 };
1380 std::transform(mli.directory.begin(), mli.directory.end(), &listbox_strings[1], a);
1381 auto submm = window_create<subdirectory_mission_menu>(mli.directory, count_name_pointer_strings, std::move(listbox_strings), mli.path.c_str(), when_selected, this, 0, grd_curscreen->sc_canvas);
1382 (void)submm;
1383 return window_event_result::handled;
1384 }
1385 // Chose a mission
1386 else if (const auto errstr = load_mission(&mli))
1387 {
1388 nm_messagebox(menu_title{nullptr}, {TXT_OK}, "%s\n\n%s\n\n%s", TXT_MISSION_ERROR, errstr, mli.path.c_str());
1389 return window_event_result::handled; // stay in listbox so user can select another one
1390 }
1391 CGameCfg.LastMission.copy_if(listbox_strings[raw_citem]);
1392 }
1393 return (*when_selected)();
1394 }
1395 case event_type::window_close:
1396 /* If the user dismisses the listbox by pressing ESCAPE,
1397 * do not close the parent listbox.
1398 */
1399 if (listbox_get_citem(*this) != -1)
1400 if (parent)
1401 {
1402 window_close(parent);
1403 }
1404 break;
1405 default:
1406 break;
1407 }
1408
1409 return window_event_result::ignored;
1410 }
1411
1412 namespace {
1413
1414 /* Reserve an element to allow the pseudo-entry `listbox_go_up`.
1415 */
1416 constexpr std::integral_constant<std::size_t, 1> mission_subdirectory_extra_strings{};
1417
1418 static std::unique_ptr<mission_menu_create_state> prepare_mission_menu_state(const mission_list_type &mission_list, const char *const LastMission, const std::size_t extra_strings)
1419 {
1420 auto mission_name_to_select = LastMission;
1421 auto p = std::make_unique<mission_menu_create_state>(mission_list.size() + extra_strings);
1422 auto &create_state = *p.get();
1423 auto listbox_strings = create_state.listbox_strings.get();
1424 std::fill_n(listbox_strings, extra_strings, nullptr);
1425 listbox_strings += extra_strings;
1426 for (auto &&[idx, mli] : enumerate(mission_list))
1427 {
1428 const char *const mission_name = mli.mission_name;
1429 *listbox_strings++ = mission_name;
1430 if (!mission_name_to_select)
1431 /* Once the mission to select has been found, copy subsequent
1432 * mission names, but skip all the other logic. There is no need
1433 * to examine subdirectories, because that examination is only for
1434 * finding the mission to select.
1435 */
1436 continue;
1437 if (!mli.directory.empty())
1438 {
1439 /* If this entry represents a subdirectory, prepare a corresponding
1440 * inner state for it.
1441 */
1442 auto &&substate = prepare_mission_menu_state(mli.directory, mission_name_to_select, mission_subdirectory_extra_strings);
1443 if (substate->initial_selection == UINT_MAX)
1444 /* If the subdirectory did not contain the target mission, then
1445 * discard the subdirectory state. State is only needed and
1446 * maintained for the directories that must be traversed on the
1447 * path to the target mission, because only those directories
1448 * will be automatically opened in the mission choosing dialog.
1449 */
1450 continue;
1451 substate->listbox_strings[0] = mission_menu::listbox_go_up;
1452 create_state.submenu = std::move(substate);
1453 }
1454 else if (strcmp(mission_name, mission_name_to_select))
1455 continue;
1456 create_state.initial_selection = idx;
1457 mission_name_to_select = nullptr;
1458 }
1459 return p;
1460 }
1461
1462 }
1463
1464 namespace dsx {
1465
1466 void select_mission(const mission_filter_mode mission_filter, const menu_title message, window_event_result (*when_selected)(void))
1467 {
1468 auto &&mission_list = build_mission_list(mission_filter);
1469
1470 if (mission_list.empty())
1471 return;
1472 if (mission_list.size() <= 1)
1473 {
1474 load_mission(&mission_list.front());
1475 (*when_selected)();
1476 }
1477 else
1478 {
1479 auto &&create_state_ptr = prepare_mission_menu_state(mission_list, CGameCfg.LastMission, 0);
1480 auto &create_state = *create_state_ptr.get();
1481 mission_menu *parent_mission_menu;
1482 {
1483 auto mm = window_create<toplevel_mission_menu>(std::move(mission_list), std::move(create_state.listbox_strings), message, when_selected, create_state.initial_selection == UINT_MAX ? 0 : create_state.initial_selection, grd_curscreen->sc_canvas);
1484 parent_mission_menu = mm;
1485 }
1486 for (auto parent_state = &create_state; const auto substate = parent_state->submenu.get(); parent_state = substate)
1487 {
1488 const auto parent_initial_selection = parent_state->initial_selection;
1489 const auto parent_mission_list_size = parent_mission_menu->ml.size();
1490 assert(parent_initial_selection < parent_mission_list_size);
1491 if (parent_initial_selection >= parent_mission_list_size)
1492 break;
1493 const auto &substate_mission_list = parent_mission_menu->ml[parent_initial_selection];
1494 auto submm = window_create<subdirectory_mission_menu>(substate_mission_list.directory, substate_mission_list.directory.size() + mission_subdirectory_extra_strings, std::move(substate->listbox_strings), substate_mission_list.path.c_str(), when_selected, parent_mission_menu, 0, grd_curscreen->sc_canvas);
1495 parent_mission_menu = submm;
1496 }
1497 }
1498 }
1499
1500 #if DXX_USE_EDITOR
1501 namespace {
1502 static int write_mission(void)
1503 {
1504 auto &msn_extension =
1505 #if DXX_BUILD_DESCENT == 2
1506 (Current_mission->descent_version != Mission::descent_version_type::descent1) ? MISSION_EXTENSION_DESCENT_II :
1507 #endif
1508 MISSION_EXTENSION_DESCENT_I;
1509 std::array<char, PATH_MAX> mission_filename;
1510 snprintf(mission_filename.data(), mission_filename.size(), "%s%s", Current_mission->path.c_str(), msn_extension);
1511
1512 auto &&mfile = PHYSFSX_openWriteBuffered(mission_filename.data()).first;
1513 if (!mfile)
1514 {
1515 PHYSFS_mkdir(MISSION_DIR); //try making directory - in *write* path
1516 mfile = PHYSFSX_openWriteBuffered(mission_filename.data()).first;
1517 if (!mfile)
1518 return 0;
1519 }
1520
1521 const char *prefix = "";
1522 #if DXX_BUILD_DESCENT == 2
1523 switch (Current_mission->descent_version)
1524 {
1525 case Mission::descent_version_type::descent2x:
1526 prefix = "x";
1527 break;
1528
1529 case Mission::descent_version_type::descent2z:
1530 prefix = "z";
1531 break;
1532
1533 case Mission::descent_version_type::descent2a:
1534 prefix = "!";
1535 break;
1536
1537 default:
1538 break;
1539 }
1540 #endif
1541
1542 PHYSFSX_printf(mfile, "%sname = %s\n", prefix, static_cast<const char *>(Current_mission->mission_name));
1543
1544 PHYSFSX_printf(mfile, "type = %s\n", Current_mission->anarchy_only_flag == Mission::anarchy_only_level::only_anarchy_games ? "anarchy" : "normal");
1545
1546 if (Current_mission->briefing_text_filename.front())
1547 PHYSFSX_printf(mfile, "briefing = %s\n", static_cast<const char *>(Current_mission->briefing_text_filename));
1548
1549 if (Current_mission->ending_text_filename.front())
1550 PHYSFSX_printf(mfile, "ending = %s\n", static_cast<const char *>(Current_mission->ending_text_filename));
1551
1552 PHYSFSX_printf(mfile, "num_levels = %i\n", Current_mission->last_level);
1553
1554 for (const char *const i : unchecked_partial_range(Current_mission->level_names.get(), Current_mission->last_level))
1555 PHYSFSX_printf(mfile, "%s\n", i);
1556
1557 if (const auto n_secret_levels = Current_mission->n_secret_levels)
1558 {
1559 PHYSFSX_printf(mfile, "num_secrets = %i\n", n_secret_levels);
1560 for (const auto &&[name, table_cell] : zip(unchecked_partial_range(Current_mission->secret_level_names.get(), n_secret_levels), unchecked_partial_range(Current_mission->secret_level_table.get(), n_secret_levels)))
1561 PHYSFSX_printf(mfile, "%s,%i\n", static_cast<const char *>(name), table_cell);
1562 }
1563
1564 #if DXX_BUILD_DESCENT == 2
1565 if (Current_mission->alternate_ham_file)
1566 PHYSFSX_printf(mfile, "ham = %s\n", static_cast<const char *>(*Current_mission->alternate_ham_file.get()));
1567 #endif
1568
1569 return 1;
1570 }
1571 }
1572
1573 void create_new_mission(void)
1574 {
1575 Current_mission = std::make_unique<Mission>(Mission_path(MISSION_DIR "new_miss", sizeof(MISSION_DIR) - 1)); // limited to eight characters because of savegame format
1576 Current_mission->mission_name.copy_if("Untitled");
1577 Current_mission->builtin_hogsize = descent_hog_size::None;
1578 Current_mission->anarchy_only_flag = Mission::anarchy_only_level::allow_any_game;
1579
1580 Current_mission->level_names = std::make_unique<d_fname[]>(1);
1581 if (!Current_mission->level_names)
1582 {
1583 Current_mission.reset();
1584 return;
1585 }
1586
1587 Current_mission->level_names[0] = "GAMESAVE.LVL";
1588 Current_mission->last_level = 1;
1589 Current_mission->n_secret_levels = 0;
1590 Current_mission->last_secret_level = 0;
1591 Current_mission->briefing_text_filename = {};
1592 Current_mission->ending_text_filename = {};
1593 Current_mission->secret_level_table.reset();
1594 Current_mission->secret_level_names.reset();
1595
1596 #if DXX_BUILD_DESCENT == 2
1597 if (Gamesave_current_version > 3)
1598 Current_mission->descent_version = Mission::descent_version_type::descent2; // custom ham not supported in editor (yet)
1599 else
1600 Current_mission->descent_version = Mission::descent_version_type::descent1;
1601
1602 Current_mission->alternate_ham_file = nullptr;
1603 #endif
1604
1605 write_mission();
1606 }
1607 #endif
1608
1609 }