Debian Codegraph @

similar/main/game.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 * Game loop for Inferno
23 *
24 */
25
26 #include "dxxsconf.h"
27 #include <stdio.h>
28 #include <stdlib.h>
29 #include <string.h>
30 #include <stdarg.h>
31 #include <ranges>
32 #include <SDL.h>
33 #include <ctime>
34 #if DXX_USE_SCREENSHOT_FORMAT_PNG
35 #include <png.h>
36 #include "vers_id.h"
37 #endif
38
39 #if DXX_USE_OGL
40 #include "ogl_init.h"
41 #endif
42
43 #include "pstypes.h"
44 #include "console.h"
45 #include "gr.h"
46 #include "inferno.h"
47 #include "game.h"
48 #include "key.h"
49 #include "config.h"
50 #include "object.h"
51 #include "dxxerror.h"
52 #include "joy.h"
53 #include "pcx.h"
54 #include "timer.h"
55 #include "render.h"
56 #include "laser.h"
57 #include "screens.h"
58 #include "textures.h"
59 #include "gauges.h"
60 #include "3d.h"
61 #include "effects.h"
62 #include "menu.h"
63 #include "player.h"
64 #include "gameseg.h"
65 #include "wall.h"
66 #include "ai.h"
67 #include "fuelcen.h"
68 #include "digi.h"
69 #include "u_mem.h"
70 #include "palette.h"
71 #include "morph.h"
72 #include "lighting.h"
73 #include "newdemo.h"
74 #include "collide.h"
75 #include "weapon.h"
76 #include "sounds.h"
77 #include "args.h"
78 #include "gameseq.h"
79 #include "automap.h"
80 #include "text.h"
81 #include "powerup.h"
82 #include "fireball.h"
83 #include "newmenu.h"
84 #include "gamefont.h"
85 #include "endlevel.h"
86 #include "kconfig.h"
87 #include "mouse.h"
88 #include "switch.h"
89 #include "controls.h"
90 #include "songs.h"
91
92 #include "multi.h"
93 #include "cntrlcen.h"
94 #include "pcx.h"
95 #include "state.h"
96 #include "piggy.h"
97 #include "ai.h"
98 #include "robot.h"
99 #include "playsave.h"
100 #include "maths.h"
101 #include "hudmsg.h"
102 #if DXX_BUILD_DESCENT == 2
103 #include <climits>
104 #include "gamepal.h"
105 #include "movie.h"
106 #endif
107 #include "event.h"
108 #include "window.h"
109
110 #if DXX_USE_EDITOR
111 #include "editor/editor.h"
112 #include "editor/esegment.h"
113 #endif
114
115 #include "d_construct.h"
116 #include "d_enumerate.h"
117 #include "d_levelstate.h"
118 #include "d_range.h"
119 #include "compiler-range_for.h"
120 #include "partial_range.h"
121 #include "segiter.h"
122
123 d_time_fix ThisLevelTime;
124
125 namespace dcx {
126 namespace {
127 static fix64 last_timer_value;
128 static fix64 sync_timer_value;
129 }
130 grs_subcanvas Screen_3d_window; // The rectangle for rendering the mine to
131 int force_cockpit_redraw{0};
132 int PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd;
133
134 int Game_suspended{0}; //if non-zero, nothing moves but player
135 game_mode_flags Game_mode;
136 int Global_missile_firing_count{0};
137
138 std::optional<Difficulty_level_type> build_difficulty_level_from_untrusted(const int8_t untrusted)
139 {
140 switch (untrusted)
141 {
142 case static_cast<int8_t>(Difficulty_level_type::_0):
143 case static_cast<int8_t>(Difficulty_level_type::_1):
144 case static_cast<int8_t>(Difficulty_level_type::_2):
145 case static_cast<int8_t>(Difficulty_level_type::_3):
146 case static_cast<int8_t>(Difficulty_level_type::_4):
147 return Difficulty_level_type{untrusted};
148 default:
149 return std::nullopt;
150 }
151 }
152
153 }
154
155 // Function prototypes for GAME.C exclusively.
156
157 namespace dsx {
158
159 game_window *Game_wind;
160
161 namespace {
162
163 static window_event_result GameProcessFrame(const d_level_shared_robot_info_state &);
164 static bool FireLaser(player_info &, const control_info &Controls);
165 static void powerup_grab_cheat_all();
166
167 }
168
169 #if DXX_BUILD_DESCENT == 2
170 d_flickering_light_state Flickering_light_state;
171 namespace {
172 static void slide_textures(void);
173 static void flicker_lights(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, d_flickering_light_state &fls, fvmsegptridx &vmsegptridx);
174 }
175 #endif
176
177 // Cheats
178 game_cheats cheats;
179
180 // ==============================================================================================
181
182 //this is called once per game
183 void init_game()
184 {
185 init_objects();
186
187 init_special_effects();
188 Clear_window = 2; // do portal only window clear.
189 }
190
191 }
192
193 namespace dcx {
194
195 void reset_palette_add()
196 {
197 PaletteRedAdd = 0;
198 PaletteGreenAdd = 0;
199 PaletteBlueAdd = 0;
200 }
201
202 constexpr screen_mode initial_large_game_screen_mode{1024, 768};
203 screen_mode Game_screen_mode = initial_large_game_screen_mode;
204
205 #if DXX_USE_STEREOSCOPIC_RENDER
206 StereoFormat VR_stereo;
207 fix VR_eye_width = F1_0;
208 int VR_eye_offset{0};
209 int VR_sync_width{20};
210 grs_subcanvas VR_hud_left;
211 grs_subcanvas VR_hud_right;
212 #endif
213
214 }
215
216 namespace dsx {
217
218 #if DXX_USE_STEREOSCOPIC_RENDER
219 void init_stereo()
220 {
221 #if DXX_USE_OGL
222 // init stereo options
223 if (CGameArg.OglStereo || CGameArg.OglStereoView) {
224 if (VR_stereo == StereoFormat::None && !VR_eye_offset)
225 VR_stereo = (CGameArg.OglStereoView) ? static_cast<StereoFormat>(CGameArg.OglStereoView % (static_cast<unsigned>(StereoFormat::HighestFormat) + 1)) : StereoFormat::AboveBelow;
226 constexpr int half_width_eye_offset = -6;
227 constexpr int full_width_eye_offset = -12;
228 switch (VR_stereo)
229 {
230 case StereoFormat::None:
231 case StereoFormat::AboveBelow:
232 case StereoFormat::AboveBelowSync:
233 VR_eye_offset = full_width_eye_offset;
234 break;
235 case StereoFormat::SideBySideFullHeight:
236 case StereoFormat::SideBySideHalfHeight:
237 VR_eye_offset = half_width_eye_offset;
238 break;
239 }
240 VR_eye_width = (F1_0 * 7) / 10; // Descent 1.5 defaults
241 VR_sync_width = (20 * SHEIGHT) / 480;
242 PlayerCfg.CockpitMode[1] = cockpit_mode_t::full_screen;
243 }
244 else {
245 VR_stereo = StereoFormat::None;
246 }
247 #endif
248 }
249 #endif
250
251 //initialize the various canvases on the game screen
252 //called every time the screen mode or cockpit changes
253 void init_cockpit()
254 {
255 //Initialize the on-screen canvases
256
257 if (Screen_mode != SCREEN_GAME)
258 return;
259
260 if ( Screen_mode == SCREEN_EDITOR )
261 PlayerCfg.CockpitMode[1] = cockpit_mode_t::full_screen;
262
263 #if !DXX_USE_OGL
264 if (PlayerCfg.CockpitMode[1] != cockpit_mode_t::letterbox)
265 {
266 #if DXX_BUILD_DESCENT == 2
267 int HiresGFXAvailable = !GameArg.GfxSkipHiresGFX;
268 #endif
269 const auto full_screen_mode = HiresGFXAvailable
270 ? screen_mode /* large_game_screen_mode */{640, 480}
271 : screen_mode /* small_game_screen_mode */{320, 200};
272 if (Game_screen_mode != full_screen_mode) {
273 PlayerCfg.CockpitMode[1] = cockpit_mode_t::full_screen;
274 }
275 }
276 #endif
277
278 gr_set_default_canvas();
279 auto &canvas = *grd_curcanv;
280
281 switch( PlayerCfg.CockpitMode[1] ) {
282 case cockpit_mode_t::full_cockpit:
283 game_init_render_sub_buffers(canvas, 0, 0, SWIDTH, (SHEIGHT*2)/3);
284 break;
285
286 case cockpit_mode_t::rear_view:
287 {
288 unsigned x1{0}, y1 = 0, x2 = SWIDTH, y2 = (SHEIGHT*2)/3;
289 const auto cp_idx{
290 #if DXX_BUILD_DESCENT == 2
291 HIRESMODE
292 ? cockpit_bitmap_index::hires_rear_view
293 :
294 #endif
295 cockpit_bitmap_index::rear_view
296 };
297
298 const auto cb{cockpit_bitmap[cp_idx]};
299 PIGGY_PAGE_IN(cb);
300 auto &bm = GameBitmaps[cb];
301 gr_bitblt_find_transparent_area(bm, x1, y1, x2, y2);
302 game_init_render_sub_buffers(canvas, x1 * (static_cast<float>(SWIDTH) / bm.bm_w), y1 * (static_cast<float>(SHEIGHT) / bm.bm_h), (x2 - x1 + 1) * (static_cast<float>(SWIDTH) / bm.bm_w), (y2 - y1 + 2) * (static_cast<float>(SHEIGHT) / bm.bm_h));
303 break;
304 }
305
306 case cockpit_mode_t::full_screen:
307 {
308 unsigned w = SWIDTH;
309 unsigned h = SHEIGHT;
310 #if DXX_USE_STEREOSCOPIC_RENDER
311 switch (VR_stereo)
312 {
313 case StereoFormat::None:
314 /* Preserve width */
315 /* Preserve height */
316 break;
317 case StereoFormat::AboveBelow:
318 case StereoFormat::AboveBelowSync:
319 /* Preserve width */
320 /* Change height */
321 h /= 2;
322 break;
323 case StereoFormat::SideBySideHalfHeight:
324 /* Change width */
325 /* Change height */
326 h /= 2;
327 [[fallthrough]];
328 case StereoFormat::SideBySideFullHeight:
329 /* Change width */
330 /* Preserve height */
331 w /= 2;
332 break;
333 }
334 #endif
335 game_init_render_sub_buffers(canvas, 0, 0, w, h);
336 }
337 break;
338
339 case cockpit_mode_t::status_bar:
340 game_init_render_sub_buffers(canvas, 0, 0, SWIDTH, (HIRESMODE?(SHEIGHT*2)/2.6:(SHEIGHT*2)/2.72));
341 break;
342
343 case cockpit_mode_t::letterbox: {
344 const unsigned gsm_height = grd_curscreen->get_screen_height();
345 const unsigned w = grd_curscreen->get_screen_width();
346 const unsigned h = (gsm_height * 3) / 4; // true letterbox size (16:9)
347 const unsigned x = 0;
348 const unsigned y = (gsm_height - h) / 2;
349
350 const uint8_t color = 0;
351 auto &canvas = *grd_curcanv;
352 gr_rect(canvas, x, 0, w, gsm_height - h, color);
353 gr_rect(canvas, x, gsm_height - h, w, gsm_height, color);
354
355 game_init_render_sub_buffers(canvas, x, y, w, h);
356 break;
357 }
358 }
359
360 gr_set_default_canvas();
361 }
362
363 }
364
365 //selects a given cockpit (or lack of one). See types in game.h
366 void select_cockpit(const cockpit_mode_t mode)
367 {
368 #if DXX_USE_STEREOSCOPIC_RENDER
369 // skip switching cockpit views while stereo viewport active
370 if (VR_stereo != StereoFormat::None && mode != cockpit_mode_t::full_screen)
371 return;
372 #endif
373
374 if (mode != PlayerCfg.CockpitMode[1]) { //new mode
375 PlayerCfg.CockpitMode[1]=mode;
376 init_cockpit();
377 }
378 }
379
380 namespace dcx {
381
382 //force cockpit redraw next time. call this if you've trashed the screen
383 void reset_cockpit()
384 {
385 force_cockpit_redraw=1;
386 last_drawn_cockpit = cockpit_mode_t{UINT8_MAX};
387 }
388
389 void game_init_render_sub_buffers(grs_canvas &canvas, const int x, const int y, const int w, const int h)
390 {
391 gr_clear_canvas(canvas, 0);
392 gr_init_sub_canvas(Screen_3d_window, canvas, x, y, w, h);
393
394 #if DXX_USE_STEREOSCOPIC_RENDER
395 if (VR_stereo != StereoFormat::None)
396 {
397 // offset HUD screen rects to force out-of-screen parallax on HUD overlays
398 const int dx = (VR_eye_offset < 0) ? -VR_eye_offset : 0;
399 const int dy = VR_sync_width / 2;
400 struct {
401 uint16_t x;
402 uint16_t y;
403 uint16_t w;
404 uint16_t h;
405 } l, r;
406 switch (VR_stereo) {
407 case StereoFormat::None:
408 default:
409 return;
410 case StereoFormat::AboveBelow:
411 l.x = x + dx;
412 l.y = y;
413 l.w = r.w = w - dx;
414 l.h = r.h = h;
415 r.x = x;
416 r.y = y + h;
417 break;
418 case StereoFormat::AboveBelowSync:
419 l.x = x + dx;
420 l.y = y;
421 l.w = r.w = w - dx;
422 l.h = r.h = h - dy;
423 r.x = x;
424 r.y = y + h + dy;
425 break;
426 case StereoFormat::SideBySideFullHeight:
427 l.x = x + dx;
428 l.y = r.y = y;
429 l.w = r.w = w - dx;
430 l.h = r.h = h;
431 r.x = x + w;
432 break;
433 case StereoFormat::SideBySideHalfHeight:
434 l.x = x + dx;
435 l.y = r.y = y + (h / 2);
436 l.w = r.w = w - dx;
437 l.h = r.h = h;
438 r.x = x + w;
439 break;
440 }
441 gr_init_sub_canvas(VR_hud_left, grd_curscreen->sc_canvas, l.x, l.y, l.w, l.h);
442 gr_init_sub_canvas(VR_hud_right, grd_curscreen->sc_canvas, r.x, r.y, r.w, r.h);
443 }
444 #endif
445 }
446
447 }
448
449 namespace dsx {
450
451 //called to change the screen mode. Parameter sm is the new mode, one of
452 //SMODE_GAME or SMODE_EDITOR. returns mode acutally set (could be other
453 //mode if cannot init requested mode)
454 int set_screen_mode(int sm)
455 {
456 if ( (Screen_mode == sm) && !((sm==SCREEN_GAME) && (grd_curscreen->get_screen_mode() != Game_screen_mode)) && !(sm==SCREEN_MENU) )
457 {
458 return 1;
459 }
460
461 #if DXX_USE_EDITOR
462 Canv_editor = NULL;
463 #endif
464
465 Screen_mode = sm;
466
467 #if SDL_MAJOR_VERSION == 1
468 switch( Screen_mode )
469 {
470 case SCREEN_MENU:
471 if (grd_curscreen->get_screen_mode() != Game_screen_mode)
472 if (gr_set_mode(Game_screen_mode))
473 Error("Cannot set screen mode.");
474 break;
475
476 case SCREEN_GAME:
477 if (grd_curscreen->get_screen_mode() != Game_screen_mode)
478 if (gr_set_mode(Game_screen_mode))
479 Error("Cannot set screen mode.");
480 break;
481 #if DXX_USE_EDITOR
482 case SCREEN_EDITOR:
483 {
484 const screen_mode editor_mode{800, 600};
485 if (grd_curscreen->get_screen_mode() != editor_mode)
486 {
487 int gr_error;
488 if ((gr_error = gr_set_mode(editor_mode)) != 0) { //force into game scrren
489 Warning("Cannot init editor screen (error=%d)",gr_error);
490 return 0;
491 }
492 }
493 }
494 break;
495 #endif
496 #if DXX_BUILD_DESCENT == 2
497 case SCREEN_MOVIE:
498 {
499 const screen_mode movie_mode{MOVIE_WIDTH, MOVIE_HEIGHT};
500 if (grd_curscreen->get_screen_mode() != movie_mode)
501 {
502 if (gr_set_mode(movie_mode))
503 Error("Cannot set screen mode for game!");
504 gr_palette_load( gr_palette );
505 }
506 }
507 break;
508 #endif
509 default:
510 Error("Invalid screen mode %d",sm);
511 }
512 #endif
513 return 1;
514 }
515
516 }
517
518 namespace dcx {
519
520 namespace {
521
522 class game_world_time_paused
523 {
524 unsigned time_paused;
525 public:
526 explicit operator bool() const
527 {
528 return time_paused;
529 }
530 void increase_pause_count();
531 void decrease_pause_count();
532 };
533
534 static game_world_time_paused time_paused;
535
536 }
537
538 void game_world_time_paused::increase_pause_count()
539 {
540 if (time_paused==0) {
541 const fix64 time = timer_update();
542 last_timer_value = time - last_timer_value;
543 if (last_timer_value < 0) {
544 last_timer_value = 0;
545 }
546 }
547 time_paused++;
548 }
549
550 void game_world_time_paused::decrease_pause_count()
551 {
552 Assert(time_paused > 0);
553 --time_paused;
554 if (time_paused==0) {
555 const fix64 time = timer_update();
556 last_timer_value = time - last_timer_value;
557 }
558 }
559
560 void start_time()
561 {
562 time_paused.decrease_pause_count();
563 }
564
565 void stop_time()
566 {
567 time_paused.increase_pause_count();
568 }
569
570 pause_game_world_time::pause_game_world_time()
571 {
572 stop_time();
573 }
574
575 pause_game_world_time::~pause_game_world_time()
576 {
577 start_time();
578 }
579
580 namespace {
581
582 static void game_flush_common_inputs()
583 {
584 event_flush();
585 key_flush();
586 joy_flush();
587 mouse_flush();
588 }
589
590 }
591
592 }
593
594 namespace dsx {
595
596 void game_flush_inputs(control_info &Controls)
597 {
598 Controls = {};
599 game_flush_common_inputs();
600 }
601
602 void game_flush_respawn_inputs(control_info &Controls)
603 {
604 static_cast<control_info::fire_controls_t &>(Controls.state) = {};
605 }
606
607 }
608
609 namespace dcx {
610
611 /*
612 * timer that every sets d_tick_step true and increments d_tick_count every 1000/DESIGNATED_GAME_FPS ms.
613 */
614 void calc_d_tick()
615 {
616 static fix timer = 0;
617 auto t = timer + FrameTime;
618
619 d_tick_step = t >= DESIGNATED_GAME_FRAMETIME;
620 if (d_tick_step)
621 {
622 d_tick_count++;
623 if (d_tick_count > 1000000)
624 d_tick_count = 0;
625 t -= DESIGNATED_GAME_FRAMETIME;
626 }
627 timer = t;
628 }
629
630 void reset_time()
631 {
632 last_timer_value = timer_update();
633 }
634
635 }
636
637 void calc_frame_time()
638 {
639 fix last_frametime = FrameTime;
640
641 const auto vsync{CGameCfg.VSync};
642 const auto bound = f1_0 / (likely(vsync) ? MAXIMUM_FPS : CGameArg.SysMaxFPS);
643 const auto may_sleep = !CGameArg.SysNoNiceFPS && !vsync;
644 const auto multiplayer{Game_mode & GM_MULTI};
645 for (;;)
646 {
647 const auto timer_value = timer_update();
648 FrameTime = timer_value - last_timer_value;
649 if (FrameTime > 0 && timer_value - sync_timer_value >= bound)
650 {
651 last_timer_value = timer_value;
652
653 sync_timer_value += bound;
654 if (sync_timer_value + bound < timer_value) {
655 sync_timer_value = timer_value;
656 }
657 break;
658 }
659 if (multiplayer)
660 multi_do_frame(); // during long wait, keep packets flowing
661 if (may_sleep)
662 timer_delay_ms(1);
663 }
664
665 if ( cheats.turbo )
666 FrameTime *= 2;
667
668 if (FrameTime < 0) //if bogus frametime...
669 FrameTime = (last_frametime==0?1:last_frametime); //...then use time from last frame
670
671 GameTime64 += FrameTime;
672
673 calc_d_tick();
674 #ifdef NEWHOMER
675 calc_d_homer_tick();
676 #endif
677 }
678
679 namespace dsx {
680
681 #if DXX_USE_EDITOR
682 void move_player_2_segment(const vmsegptridx_t seg, const sidenum_t side)
683 {
684 auto &LevelSharedVertexState = LevelSharedSegmentState.get_vertex_state();
685 auto &Objects = LevelUniqueObjectState.Objects;
686 auto &Vertices = LevelSharedVertexState.get_vertices();
687 auto &vmobjptr = Objects.vmptr;
688 auto &vmobjptridx = Objects.vmptridx;
689 const auto &&console = vmobjptridx(ConsoleObject);
690 auto &vcvertptr = Vertices.vcptr;
691 console->pos = compute_segment_center(vcvertptr, seg);
692 auto vp{compute_center_point_on_side(vcvertptr, seg, side)};
693 vm_vec_sub2(vp, console->pos);
694 reconstruct_at(console->orient, vm_vector_to_matrix, vp);
695 obj_relink(vmobjptr, vmsegptr, console, seg);
696 }
697 #endif
698
699 }
700
701 namespace dcx {
702
703 namespace {
704
705 #if DXX_USE_SCREENSHOT_FORMAT_PNG
706 struct RAIIpng_struct
707 {
708 png_struct *png_ptr;
709 png_info *info_ptr = nullptr;
710 RAIIpng_struct(png_struct *const p) :
711 png_ptr(p)
712 {
713 }
714 ~RAIIpng_struct()
715 {
716 png_destroy_write_struct(&png_ptr, &info_ptr);
717 }
718 };
719
720 struct d_screenshot : RAIIpng_struct
721 {
722 using RAIIpng_struct::RAIIpng_struct;
723 /* error handling callbacks */
724 [[noreturn]]
725 static void png_error_cb(png_struct *png, const char *str);
726 static void png_warn_cb(png_struct *png, const char *str);
727 /* output callbacks */
728 static void png_write_cb(png_struct *png, uint8_t *buf, png_size_t);
729 static void png_flush_cb(png_struct *png);
730 class png_exception : std::exception
731 {
732 };
733 };
734
735 void d_screenshot::png_error_cb(png_struct *const png, const char *const str)
736 {
737 /* libpng requires that this function not return to its caller, and
738 * will abort the program if this requirement is violated. However,
739 * throwing an exception that unwinds out past libpng is permitted.
740 */
741 (void)png;
742 con_printf(CON_URGENT, "libpng error: %s", str);
743 throw png_exception();
744 }
745
746 void d_screenshot::png_warn_cb(png_struct *const png, const char *const str)
747 {
748 (void)png;
749 con_printf(CON_URGENT, "libpng warning: %s", str);
750 }
751
752 void d_screenshot::png_write_cb(png_struct *const png, uint8_t *const buf, const png_size_t size)
753 {
754 const auto file = reinterpret_cast<PHYSFS_File *>(png_get_io_ptr(png));
755 PHYSFSX_writeBytes(file, buf, size);
756 }
757
758 void d_screenshot::png_flush_cb(png_struct *const png)
759 {
760 (void)png;
761 }
762
763 void record_screenshot_time(const struct tm &tm, png_struct *const png_ptr, png_info *const info_ptr)
764 {
765 #ifdef PNG_tIME_SUPPORTED
766 png_time pt{};
767 pt.year = tm.tm_year + 1900;
768 pt.month = tm.tm_mon + 1;
769 pt.day = tm.tm_mday;
770 pt.hour = tm.tm_hour;
771 pt.minute = tm.tm_min;
772 pt.second = tm.tm_sec;
773 png_set_tIME(png_ptr, info_ptr, &pt);
774 #else
775 (void)png_ptr;
776 (void)info_ptr;
777 con_printf(CON_NORMAL, "libpng configured without support for time chunk: screenshot will lack time record.");
778 #endif
779 }
780
781 #ifdef PNG_TEXT_SUPPORTED
782 void record_screenshot_text_metadata(png_struct *const png_ptr, png_info *const info_ptr)
783 {
784 std::array<png_text, 6> text_fields{};
785 char descent_version[80];
786 char descent_build_datetime[21];
787 std::string current_mission_path;
788 ntstring<MISSION_NAME_LEN> current_mission_name;
789 char current_level_number[4];
790 char viewer_segment[sizeof("65536")];
791 unsigned idx{0};
792 char key_descent_version[] = "Rebirth.version";
793 {
794 auto &t = text_fields[idx++];
795 auto &text = descent_version;
796 t.key = key_descent_version;
797 text[sizeof(text) - 1] = 0;
798 strncpy(text, g_descent_version, sizeof(text) - 1);
799 t.text = text;
800 t.compression = PNG_TEXT_COMPRESSION_NONE;
801 }
802 char key_descent_build_datetime[] = "Rebirth.build_datetime";
803 {
804 auto &t = text_fields[idx++];
805 auto &text = descent_build_datetime;
806 t.key = key_descent_build_datetime;
807 text[sizeof(text) - 1] = 0;
808 strncpy(text, g_descent_build_datetime, sizeof(text) - 1);
809 t.text = text;
810 t.compression = PNG_TEXT_COMPRESSION_NONE;
811 }
812 char key_current_mission_path[] = "Rebirth.mission.pathname";
813 char key_current_mission_name[] = "Rebirth.mission.textname";
814 char key_viewer_segment[] = "Rebirth.viewer_segment";
815 char key_current_level_number[] = "Rebirth.current_level_number";
816 if (const auto current_mission = Current_mission.get())
817 {
818 {
819 auto &t = text_fields[idx++];
820 t.key = key_current_mission_path;
821 current_mission_path = current_mission->path;
822 t.text = current_mission_path.data();
823 t.compression = PNG_TEXT_COMPRESSION_NONE;
824 }
825 {
826 auto &t = text_fields[idx++];
827 t.key = key_current_mission_name;
828 current_mission_name = current_mission->mission_name;
829 t.text = current_mission_name.data();
830 t.compression = PNG_TEXT_COMPRESSION_NONE;
831 }
832 {
833 auto &t = text_fields[idx++];
834 t.key = key_current_level_number;
835 t.text = current_level_number;
836 t.compression = PNG_TEXT_COMPRESSION_NONE;
837 snprintf(current_level_number, sizeof(current_level_number), "%i", Current_level_num);
838 }
839 if (const auto viewer = Viewer)
840 {
841 auto &t = text_fields[idx++];
842 t.key = key_viewer_segment;
843 t.text = viewer_segment;
844 t.compression = PNG_TEXT_COMPRESSION_NONE;
845 snprintf(viewer_segment, sizeof(viewer_segment), "%hu", viewer->segnum);
846 }
847 }
848 png_set_text(png_ptr, info_ptr, text_fields.data(), idx);
849 }
850 #endif
851
852 #if DXX_USE_OGL
853 #define write_screenshot_png(F,T,B,P) write_screenshot_png(F,T,B)
854 #endif
855 unsigned write_screenshot_png(PHYSFS_File *const file, const struct tm *const tm, const grs_bitmap &bitmap, const palette_array_t &pal)
856 {
857 const unsigned bm_w = ((bitmap.bm_w + 3) & ~3);
858 const unsigned bm_h = ((bitmap.bm_h + 3) & ~3);
859 #if DXX_USE_OGL
860 const unsigned bufsize = bm_w * bm_h * 3;
861 const auto buf = std::make_unique<uint8_t[]>(bufsize);
862 const auto begin_byte_buffer = buf.get();
863 glReadPixels(0, 0, bm_w, bm_h, GL_RGB, GL_UNSIGNED_BYTE, begin_byte_buffer);
864 #else
865 const unsigned bufsize = bitmap.bm_rowsize * bm_h;
866 const auto begin_byte_buffer = bitmap.bm_mdata;
867 #endif
868 d_screenshot ss(png_create_write_struct(PNG_LIBPNG_VER_STRING, &ss, &d_screenshot::png_error_cb, &d_screenshot::png_warn_cb));
869 if (!ss.png_ptr)
870 {
871 con_puts(CON_URGENT, "Cannot save screenshot: libpng png_create_write_struct failed");
872 return 1;
873 }
874 /* Assert that Rebirth type rgb_t is layout compatible with
875 * libpng type png_color, so that the Rebirth palette_array_t
876 * can be safely reinterpret_cast to an array of png_color.
877 * Without this, it would be necessary to copy each rgb_t
878 * palette entry into a libpng png_color.
879 */
880 static_assert(sizeof(png_color) == sizeof(rgb_t), "size mismatch");
881 static_assert(offsetof(png_color, red) == offsetof(rgb_t, r), "red offsetof mismatch");
882 static_assert(offsetof(png_color, green) == offsetof(rgb_t, g), "green offsetof mismatch");
883 static_assert(offsetof(png_color, blue) == offsetof(rgb_t, b), "blue offsetof mismatch");
884 try {
885 ss.info_ptr = png_create_info_struct(ss.png_ptr);
886 if (tm)
887 record_screenshot_time(*tm, ss.png_ptr, ss.info_ptr);
888 png_set_write_fn(ss.png_ptr, file, &d_screenshot::png_write_cb, &d_screenshot::png_flush_cb);
889 #if DXX_USE_OGL
890 const auto color_type{PNG_COLOR_TYPE_RGB};
891 #else
892 png_set_PLTE(ss.png_ptr, ss.info_ptr, reinterpret_cast<const png_color *>(pal.data()), pal.size());
893 const auto color_type{PNG_COLOR_TYPE_PALETTE};
894 #endif
895 png_set_IHDR(ss.png_ptr, ss.info_ptr, bm_w, bm_h, 8 /* always 256 colors */, color_type, PNG_INTERLACE_NONE, PNG_COMPRESSION_TYPE_BASE, PNG_FILTER_TYPE_BASE);
896 #ifdef PNG_TEXT_SUPPORTED
897 record_screenshot_text_metadata(ss.png_ptr, ss.info_ptr);
898 #endif
899 png_write_info(ss.png_ptr, ss.info_ptr);
900 std::array<png_byte *, 1024> row_pointers;
901 const auto rpb = row_pointers.begin();
902 auto o = rpb;
903 const auto end_byte_buffer = begin_byte_buffer + bufsize;
904 #if DXX_USE_OGL
905 /* OpenGL glReadPixels returns an image with origin in bottom
906 * left. Write rows from end back to beginning, since PNG
907 * expects origin in top left. If rows were written in memory
908 * order, the image would be vertically flipped.
909 */
910 const uint_fast32_t stride = bm_w * 3; /* Without palette, written data is 3-byte-sized RGB tuples of color */
911 for (auto p = end_byte_buffer; p != begin_byte_buffer;)
912 #else
913 const uint_fast32_t stride = bm_w; /* With palette, written data is byte-sized indices into a color table */
914 /* SDL canvas uses an image with origin in top left. Write rows
915 * in memory order, since this matches the PNG layout.
916 */
917 for (auto p = begin_byte_buffer; p != end_byte_buffer;)
918 #endif
919 {
920 #if DXX_USE_OGL
921 p -= stride;
922 #else
923 p += stride;
924 #endif
925 *o++ = p;
926 if (o == row_pointers.end())
927 {
928 /* Internal capacity exhausted. Flush rows and rewind
929 * to the beginning of the array.
930 */
931 o = rpb;
932 png_write_rows(ss.png_ptr, o, row_pointers.size());
933 }
934 }
935 /* Flush any trailing rows */
936 if (const auto len = o - rpb)
937 png_write_rows(ss.png_ptr, rpb, len);
938 png_write_end(ss.png_ptr, ss.info_ptr);
939 return 0;
940 } catch (const d_screenshot::png_exception &) {
941 /* Destructor unwind will handle the exception. This catch is
942 * only required to prevent further propagation.
943 *
944 * Return nonzero to instruct the caller to delete the failed
945 * file.
946 */
947 return 1;
948 }
949 }
950 #endif
951
952 }
953
954 #if DXX_USE_SCREENSHOT
955 void save_screen_shot(int automap_flag)
956 {
957 #if DXX_USE_OGL
958 if (!CGameArg.DbgGlReadPixelsOk)
959 {
960 if (!automap_flag)
961 HUD_init_message_literal(HM_DEFAULT, "glReadPixels not supported on your configuration");
962 return;
963 }
964 #endif
965 #if DXX_USE_SCREENSHOT_FORMAT_PNG
966 #define DXX_SCREENSHOT_FILE_EXTENSION "png"
967 #elif DXX_USE_SCREENSHOT_FORMAT_LEGACY
968 #if DXX_USE_OGL
969 #define DXX_SCREENSHOT_FILE_EXTENSION "tga"
970 #else
971 #define DXX_SCREENSHOT_FILE_EXTENSION "pcx"
972 #endif
973 #endif
974
975 if (!PHYSFS_exists(SCRNS_DIR))
976 PHYSFS_mkdir(SCRNS_DIR); //try making directory
977
978 pause_game_world_time p;
979 unsigned tm_sec;
980 unsigned tm_min;
981 unsigned tm_hour;
982 unsigned tm_mday;
983 unsigned tm_mon;
984 unsigned tm_year;
985 const auto t = time(nullptr);
986 struct tm *tm = nullptr;
987 if (t == static_cast<time_t>(-1) || !(tm = gmtime(&t)))
988 tm_year = tm_mon = tm_mday = tm_hour = tm_min = tm_sec = 0;
989 else
990 {
991 tm_sec = tm->tm_sec;
992 tm_min = tm->tm_min;
993 tm_hour = tm->tm_hour;
994 tm_mday = tm->tm_mday;
995 tm_mon = tm->tm_mon + 1;
996 tm_year = tm->tm_year + 1900;
997 }
998 /* Colon is not legal in Windows filenames, so use - to separate
999 * hour:minute:second.
1000 */
1001 #define DXX_SCREENSHOT_TIME_FORMAT_STRING SCRNS_DIR "%04u-%02u-%02u.%02u-%02u-%02u"
1002 #define DXX_SCREENSHOT_TIME_FORMAT_VALUES tm_year, tm_mon, tm_mday, tm_hour, tm_min, tm_sec
1003 /* Reserve extra space for the trailing -NN disambiguation. This
1004 * is only used if multiple screenshots get the same time, so it is
1005 * unlikely to be seen in practice and very unlikely to be exhausted
1006 * (unless the clock is frozen or returns invalid times).
1007 */
1008 char savename[sizeof(SCRNS_DIR) + sizeof("2000-01-01.00-00-00.NN.ext")];
1009 snprintf(savename, sizeof(savename), DXX_SCREENSHOT_TIME_FORMAT_STRING "." DXX_SCREENSHOT_FILE_EXTENSION, DXX_SCREENSHOT_TIME_FORMAT_VALUES);
1010 for (unsigned savenum = 0; PHYSFS_exists(savename) && savenum != 100; ++savenum)
1011 {
1012 snprintf(savename, sizeof(savename), DXX_SCREENSHOT_TIME_FORMAT_STRING ".%02u." DXX_SCREENSHOT_FILE_EXTENSION, DXX_SCREENSHOT_TIME_FORMAT_VALUES, savenum);
1013 #undef DXX_SCREENSHOT_TIME_FORMAT_VALUES
1014 #undef DXX_SCREENSHOT_TIME_FORMAT_STRING
1015 #undef DXX_SCREENSHOT_FILE_EXTENSION
1016 }
1017 if (const auto &&[file, physfserr] = PHYSFSX_openWriteBuffered(savename); file)
1018 {
1019 if (!automap_flag)
1020 HUD_init_message(HM_DEFAULT, "%s '%s'", TXT_DUMPING_SCREEN, &savename[sizeof(SCRNS_DIR) - 1]);
1021
1022 #if DXX_USE_OGL
1023 #if !DXX_USE_OGLES
1024 glReadBuffer(GL_FRONT);
1025 #endif
1026 #if DXX_USE_SCREENSHOT_FORMAT_PNG
1027 auto write_error = write_screenshot_png(file, tm, grd_curscreen->sc_canvas.cv_bitmap, void /* unused */);
1028 #elif DXX_USE_SCREENSHOT_FORMAT_LEGACY
1029 write_bmp(file, grd_curscreen->get_screen_width(), grd_curscreen->get_screen_height());
1030 /* write_bmp never fails */
1031 std::false_type write_error;
1032 #endif
1033 #else
1034 grs_canvas &screen_canv = grd_curscreen->sc_canvas;
1035 palette_array_t pal;
1036
1037 const auto &&temp_canv = gr_create_canvas(screen_canv.cv_bitmap.bm_w, screen_canv.cv_bitmap.bm_h);
1038 gr_ubitmap(*temp_canv, screen_canv.cv_bitmap);
1039
1040 gr_palette_read(pal); //get actual palette from the hardware
1041 // Correct palette colors
1042 range_for (auto &i, pal)
1043 {
1044 i.r <<= 2;
1045 i.g <<= 2;
1046 i.b <<= 2;
1047 }
1048 #if DXX_USE_SCREENSHOT_FORMAT_PNG
1049 auto write_error = write_screenshot_png(file, tm, grd_curscreen->sc_canvas.cv_bitmap, pal);
1050 #elif DXX_USE_SCREENSHOT_FORMAT_LEGACY
1051 auto write_error = pcx_write_bitmap(file, &temp_canv->cv_bitmap, pal);
1052 #endif
1053 #endif
1054 if (write_error)
1055 PHYSFS_delete(savename);
1056 }
1057 else
1058 {
1059 const auto e = PHYSFS_getErrorByCode(physfserr);
1060 if (!automap_flag)
1061 HUD_init_message(HM_DEFAULT, "Failed to open screenshot file for writing: %s: %s", &savename[sizeof(SCRNS_DIR) - 1], e);
1062 else
1063 con_printf(CON_URGENT, "Failed to open screenshot file for writing: %s: %s", savename, e);
1064 return;
1065 }
1066 }
1067 #endif
1068
1069 //initialize flying
1070 void fly_init(object_base &obj)
1071 {
1072 obj.control_source = object::control_type::flying;
1073 obj.movement_source = object::movement_type::physics;
1074
1075 obj.mtype.phys_info.velocity = {};
1076 obj.mtype.phys_info.thrust = {};
1077 obj.mtype.phys_info.rotvel = {};
1078 obj.mtype.phys_info.rotthrust = {};
1079 }
1080
1081 }
1082
1083 namespace dsx {
1084
1085 namespace {
1086
1087 // ------------------------------------------------------------------------------------
1088 static void do_cloak_stuff()
1089 {
1090 auto &Objects = LevelUniqueObjectState.Objects;
1091 auto &vmobjptr = Objects.vmptr;
1092 for (auto &&[i, value] : enumerate(partial_range(Players, N_players)))
1093 {
1094 auto &plobj = *vmobjptr(value.objnum);
1095 auto &player_info = plobj.ctype.player_info;
1096 auto &pl_flags = player_info.powerup_flags;
1097 if (pl_flags & PLAYER_FLAGS_CLOAKED)
1098 {
1099 if (GameTime64 > player_info.cloak_time+CLOAK_TIME_MAX)
1100 {
1101 pl_flags &= ~PLAYER_FLAGS_CLOAKED;
1102 if (i == Player_num) {
1103 multi_digi_play_sample(sound_effect::SOUND_CLOAK_OFF, F1_0);
1104 #if DXX_USE_MULTIPLAYER
1105 if (!(Game_mode & GM_MULTI))
1106 continue;
1107 maybe_drop_net_powerup(powerup_type_t::POW_CLOAK, 1, 0);
1108 if ( Newdemo_state != ND_STATE_PLAYBACK )
1109 multi_send_decloak(); // For demo recording
1110 #endif
1111 }
1112 }
1113 }
1114 }
1115 }
1116
1117 // ------------------------------------------------------------------------------------
1118 static void do_invulnerable_stuff(player_info &player_info)
1119 {
1120 auto &pl_flags = player_info.powerup_flags;
1121 if (pl_flags & PLAYER_FLAGS_INVULNERABLE)
1122 {
1123 if (GameTime64 > player_info.invulnerable_time + INVULNERABLE_TIME_MAX)
1124 {
1125 pl_flags &= ~PLAYER_FLAGS_INVULNERABLE;
1126 if (auto &FakingInvul = player_info.FakingInvul)
1127 {
1128 FakingInvul = 0;
1129 return;
1130 }
1131 multi_digi_play_sample(sound_effect::SOUND_INVULNERABILITY_OFF, F1_0);
1132 if (Game_mode & GM_MULTI)
1133 {
1134 maybe_drop_net_powerup(powerup_type_t::POW_INVULNERABILITY, 1, 0);
1135 }
1136 }
1137 }
1138 }
1139
1140 }
1141
1142 #if DXX_BUILD_DESCENT == 1
1143 static inline void do_afterburner_stuff(object_array &)
1144 {
1145 }
1146 #elif DXX_BUILD_DESCENT == 2
1147 ubyte Last_afterburner_state{0};
1148 fix64 Time_flash_last_played;
1149
1150 #define AFTERBURNER_LOOP_START ((GameArg.SndDigiSampleRate == sound_sample_rate::_22k)?32027:(32027/2)) //20098
1151 #define AFTERBURNER_LOOP_END ((GameArg.SndDigiSampleRate == sound_sample_rate::_22k)?48452:(48452/2)) //25776
1152
1153 namespace {
1154 static fix Last_afterburner_charge;
1155
1156 static void do_afterburner_stuff(object_array &Objects)
1157 {
1158 auto &vmobjptr = Objects.vmptr;
1159 auto &vcobjptridx = Objects.vcptridx;
1160 static sbyte func_play = 0;
1161
1162 auto &player_info = get_local_plrobj().ctype.player_info;
1163 const auto have_afterburner = player_info.powerup_flags & PLAYER_FLAGS_AFTERBURNER;
1164 if (!have_afterburner)
1165 Afterburner_charge = 0;
1166
1167 const auto plobj = vcobjptridx(get_local_player().objnum);
1168 if (Endlevel_sequence || Player_dead_state != player_dead_state::no)
1169 {
1170 digi_kill_sound_linked_to_object(plobj);
1171 if (Game_mode & GM_MULTI && func_play)
1172 {
1173 multi_send_sound_function (0,0);
1174 func_play = 0;
1175 }
1176 }
1177
1178 if ((Controls.state.afterburner != Last_afterburner_state && Last_afterburner_charge) || (Last_afterburner_state && Last_afterburner_charge && !Afterburner_charge)) {
1179 if (Afterburner_charge && Controls.state.afterburner && have_afterburner) {
1180 digi_link_sound_to_object3(sound_effect::SOUND_AFTERBURNER_IGNITE, plobj, 1, F1_0, sound_stack::allow_stacking, vm_distance{i2f(256)}, AFTERBURNER_LOOP_START, AFTERBURNER_LOOP_END);
1181 if (Game_mode & GM_MULTI)
1182 {
1183 multi_send_sound_function (3,sound_effect::SOUND_AFTERBURNER_IGNITE);
1184 func_play = 1;
1185 }
1186 } else {
1187 digi_kill_sound_linked_to_object(plobj);
1188 digi_link_sound_to_object2(sound_effect::SOUND_AFTERBURNER_PLAY, plobj, 0, F1_0, sound_stack::allow_stacking, vm_distance{i2f(256)});
1189 if (Game_mode & GM_MULTI)
1190 {
1191 multi_send_sound_function (0,0);
1192 func_play = 0;
1193 }
1194 }
1195 }
1196
1197 //@@if (Controls.state.afterburner && Afterburner_charge)
1198 //@@ afterburner_shake();
1199
1200 Last_afterburner_state = Controls.state.afterburner;
1201 Last_afterburner_charge = Afterburner_charge;
1202 }
1203
1204 }
1205 #endif
1206
1207 // Amount to diminish guns towards normal, per second.
1208 #define DIMINISH_RATE 16 // gots to be a power of 2, else change the code in diminish_palette_towards_normal
1209
1210 //adds to rgb values for palette flash
1211 void PALETTE_FLASH_ADD(const int _dr, const int _dg, const int _db)
1212 {
1213 const int maxval{
1214 #if DXX_BUILD_DESCENT == 2
1215 Flash_effect
1216 ? 60
1217 :
1218 #endif
1219 30
1220 };
1221 const int nr{std::clamp(PaletteRedAdd + _dr, -maxval, maxval)};
1222 const int ng{std::clamp(PaletteGreenAdd + _dg, -maxval, maxval)};
1223 const int nb{std::clamp(PaletteBlueAdd + _db, -maxval, maxval)};
1224 PaletteRedAdd = nr;
1225 PaletteGreenAdd = ng;
1226 PaletteBlueAdd = nb;
1227 }
1228
1229 }
1230
1231 namespace {
1232
1233 static void diminish_palette_color_toward_zero(int& palette_color_add, const int& dec_amount)
1234 {
1235 if (palette_color_add > 0 ) {
1236 if (palette_color_add < dec_amount)
1237 palette_color_add = 0;
1238 else
1239 palette_color_add -= dec_amount;
1240 } else if (palette_color_add < 0 ) {
1241 if (palette_color_add > -dec_amount )
1242 palette_color_add = 0;
1243 else
1244 palette_color_add += dec_amount;
1245 }
1246 }
1247
1248 }
1249
1250 namespace dsx {
1251
1252 namespace {
1253
1254 // ------------------------------------------------------------------------------------
1255 // Diminish palette effects towards normal.
1256 static void diminish_palette_towards_normal(void)
1257 {
1258 int dec_amount{0};
1259 float brightness_correction = 1-(static_cast<float>(gr_palette_get_gamma())/64); // to compensate for brightness setting of the game
1260
1261 // Diminish at DIMINISH_RATE units/second.
1262 if (FrameTime < (F1_0/DIMINISH_RATE))
1263 {
1264 static fix diminish_timer = 0;
1265 diminish_timer += FrameTime;
1266 if (diminish_timer >= (F1_0/DIMINISH_RATE))
1267 {
1268 diminish_timer -= (F1_0/DIMINISH_RATE);
1269 dec_amount = 1;
1270 }
1271 }
1272 else
1273 {
1274 dec_amount = f2i(FrameTime*DIMINISH_RATE); // one second = DIMINISH_RATE counts
1275 if (dec_amount == 0)
1276 dec_amount++; // make sure we decrement by something
1277 }
1278
1279 #if DXX_BUILD_DESCENT == 2
1280 if (Flash_effect) {
1281 int force_do{0};
1282 static fix Flash_step_up_timer = 0;
1283
1284 // Part of hack system to force update of palette after exiting a menu.
1285 if (Time_flash_last_played) {
1286 force_do = 1;
1287 PaletteRedAdd ^= 1; // Very Tricky! In gr_palette_step_up, if all stepups same as last time, won't do anything!
1288 }
1289
1290 if (Time_flash_last_played + F1_0/8 < GameTime64) {
1291 Time_flash_last_played = {GameTime64};
1292 digi_play_sample( sound_effect::SOUND_CLOAK_OFF, Flash_effect/4);
1293 }
1294
1295 Flash_effect -= FrameTime;
1296 Flash_step_up_timer += FrameTime;
1297 if (Flash_effect < 0)
1298 Flash_effect = 0;
1299
1300 if (force_do || (Flash_step_up_timer >= F1_0/26)) // originally time interval based on (d_rand() > 4096)
1301 {
1302 Flash_step_up_timer -= (F1_0/26);
1303 if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1304 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1305
1306 gr_palette_step_up( PaletteRedAdd*brightness_correction, PaletteGreenAdd*brightness_correction, PaletteBlueAdd*brightness_correction );
1307
1308 return;
1309 }
1310
1311 }
1312 #endif
1313
1314 diminish_palette_color_toward_zero(PaletteRedAdd, dec_amount);
1315 diminish_palette_color_toward_zero(PaletteGreenAdd, dec_amount);
1316 diminish_palette_color_toward_zero(PaletteBlueAdd, dec_amount);
1317
1318 if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1319 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1320
1321 gr_palette_step_up( PaletteRedAdd*brightness_correction, PaletteGreenAdd*brightness_correction, PaletteBlueAdd*brightness_correction );
1322 }
1323
1324 }
1325
1326 }
1327
1328 namespace {
1329
1330 int Redsave, Bluesave, Greensave;
1331
1332 }
1333
1334 #if DXX_BUILD_DESCENT == 2
1335 static
1336 #endif
1337 void palette_save(void)
1338 {
1339 Redsave = PaletteRedAdd; Bluesave = PaletteBlueAdd; Greensave = PaletteGreenAdd;
1340 }
1341
1342 namespace dsx {
1343 void palette_restore(void)
1344 {
1345 float brightness_correction = 1-(static_cast<float>(gr_palette_get_gamma())/64);
1346
1347 PaletteRedAdd = Redsave; PaletteBlueAdd = Bluesave; PaletteGreenAdd = Greensave;
1348 gr_palette_step_up( PaletteRedAdd*brightness_correction, PaletteGreenAdd*brightness_correction, PaletteBlueAdd*brightness_correction );
1349
1350 #if DXX_BUILD_DESCENT == 2
1351 // Forces flash effect to fixup palette next frame.
1352 Time_flash_last_played = 0;
1353 #endif
1354 }
1355
1356 // --------------------------------------------------------------------------------------------------
1357 bool allowed_to_fire_laser(const player_info &player_info)
1358 {
1359 if (Player_dead_state != player_dead_state::no)
1360 {
1361 Global_missile_firing_count = 0;
1362 return 0;
1363 }
1364
1365 auto &Next_laser_fire_time = player_info.Next_laser_fire_time;
1366 // Make sure enough time has elapsed to fire laser
1367 if (Next_laser_fire_time > GameTime64)
1368 return 0;
1369
1370 return 1;
1371 }
1372
1373 int allowed_to_fire_missile(const player_info &player_info)
1374 {
1375 auto &Next_missile_fire_time = player_info.Next_missile_fire_time;
1376 // Make sure enough time has elapsed to fire missile
1377 if (Next_missile_fire_time > GameTime64)
1378 return 0;
1379
1380 return 1;
1381 }
1382
1383 #if DXX_BUILD_DESCENT == 2
1384 void full_palette_save(void)
1385 {
1386 palette_save();
1387 reset_palette_add();
1388 gr_palette_load( gr_palette );
1389 }
1390 #endif
1391
1392 namespace {
1393
1394 #if DXX_USE_SDLMIXER
1395 #define EXT_MUSIC_TEXT "Jukebox/Audio CD"
1396 #else
1397 #define EXT_MUSIC_TEXT "Audio CD"
1398 #endif
1399
1400 #if (defined(__APPLE__) || defined(macintosh))
1401 #define _DXX_HELP_MENU_SAVE_LOAD(VERB) \
1402 DXX_MENUITEM(VERB, TEXT, "Alt-F2/F3 (\x85-SHIFT-s/o)\t SAVE/LOAD GAME", HELP_AF2_3) \
1403 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F2/F3 (\x85-s/o)\t Quick Save/Load", HELP_ASF2_3)
1404 #define _DXX_HELP_MENU_PAUSE(VERB) DXX_MENUITEM(VERB, TEXT, "Pause (\x85-P)\t Pause", HELP_PAUSE)
1405
1406 #if DXX_USE_SDL_REDBOOK_AUDIO
1407 #define _DXX_HELP_MENU_AUDIO_REDBOOK(VERB) \
1408 DXX_MENUITEM(VERB, TEXT, "\x85-E\t Eject Audio CD", HELP_ASF9) \
1409
1410 #else
1411 #define _DXX_HELP_MENU_AUDIO_REDBOOK(VERB)
1412 #endif
1413
1414 #define _DXX_HELP_MENU_AUDIO(VERB) \
1415 _DXX_HELP_MENU_AUDIO_REDBOOK(VERB) \
1416 DXX_MENUITEM(VERB, TEXT, "\x85-Up/Down\t Play/Pause " EXT_MUSIC_TEXT, HELP_ASF10) \
1417 DXX_MENUITEM(VERB, TEXT, "\x85-Left/Right\t Previous/Next Song", HELP_ASF11_12)
1418 #define _DXX_HELP_MENU_HINT_CMD_KEY(VERB, PREFIX) \
1419 DXX_MENUITEM(VERB, TEXT, "", PREFIX##_SEP_HINT_CMD) \
1420 DXX_MENUITEM(VERB, TEXT, "(Use \x85-# for F#. e.g. \x85-1 for F1)", PREFIX##_HINT_CMD)
1421 #define _DXX_NETHELP_SAVELOAD_GAME(VERB) \
1422 DXX_MENUITEM(VERB, TEXT, "Alt-F2/F3 (\x85-SHIFT-s/\x85-o)\t SAVE/LOAD COOP GAME", NETHELP_SAVELOAD)
1423 #else
1424 #define _DXX_HELP_MENU_SAVE_LOAD(VERB) \
1425 DXX_MENUITEM(VERB, TEXT, "Alt-F2/F3\t SAVE/LOAD GAME", HELP_AF2_3) \
1426 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F2/F3\t Fast Save", HELP_ASF2_3)
1427 #define _DXX_HELP_MENU_PAUSE(VERB) DXX_MENUITEM(VERB, TEXT, TXT_HELP_PAUSE, HELP_PAUSE)
1428
1429 #if DXX_USE_SDL_REDBOOK_AUDIO
1430 #define _DXX_HELP_MENU_AUDIO_REDBOOK(VERB) \
1431 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F9\t Eject Audio CD", HELP_ASF9) \
1432
1433 #else
1434 #define _DXX_HELP_MENU_AUDIO_REDBOOK(VERB)
1435 #endif
1436
1437 #define _DXX_HELP_MENU_AUDIO(VERB) \
1438 _DXX_HELP_MENU_AUDIO_REDBOOK(VERB) \
1439 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F10\t Play/Pause " EXT_MUSIC_TEXT, HELP_ASF10) \
1440 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F11/F12\t Previous/Next Song", HELP_ASF11_12)
1441 #define _DXX_HELP_MENU_HINT_CMD_KEY(VERB, PREFIX)
1442 #define _DXX_NETHELP_SAVELOAD_GAME(VERB) \
1443 DXX_MENUITEM(VERB, TEXT, "Alt-F2/F3\t SAVE/LOAD COOP GAME", NETHELP_SAVELOAD)
1444 #endif
1445
1446 #if DXX_BUILD_DESCENT == 2
1447 #define _DXX_HELP_MENU_D2_DXX_F4(VERB) DXX_MENUITEM(VERB, TEXT, TXT_HELP_F4, HELP_F4)
1448 #define _DXX_HELP_MENU_D2_DXX_FEATURES(VERB) \
1449 DXX_MENUITEM(VERB, TEXT, "Shift-F1/F2\t Cycle left/right window", HELP_SF1_2) \
1450 DXX_MENUITEM(VERB, TEXT, "Shift-F4\t GuideBot menu", HELP_SF4) \
1451 DXX_MENUITEM(VERB, TEXT, "Alt-Shift-F4\t Rename GuideBot", HELP_ASF4) \
1452 DXX_MENUITEM(VERB, TEXT, "Shift-F5/F6\t Drop primary/secondary", HELP_SF5_6) \
1453 DXX_MENUITEM(VERB, TEXT, "Shift-number\t GuideBot commands", HELP_GUIDEBOT_COMMANDS)
1454 #define DSX_NETHELP_DROPFLAG(VERB) \
1455 DXX_MENUITEM(VERB, TEXT, "ALT-0\t DROP FLAG", NETHELP_DROPFLAG)
1456 #else
1457 #define _DXX_HELP_MENU_D2_DXX_F4(VERB)
1458 #define _DXX_HELP_MENU_D2_DXX_FEATURES(VERB)
1459 #define DSX_NETHELP_DROPFLAG(VERB)
1460 #endif
1461
1462 #define DXX_HELP_MENU(VERB) \
1463 DXX_MENUITEM(VERB, TEXT, TXT_HELP_ESC, HELP_ESC) \
1464 DXX_MENUITEM(VERB, TEXT, "SHIFT-ESC\t SHOW GAME LOG", HELP_LOG) \
1465 DXX_MENUITEM(VERB, TEXT, "F1\t THIS SCREEN", HELP_HELP) \
1466 DXX_MENUITEM(VERB, TEXT, TXT_HELP_F2, HELP_F2) \
1467 _DXX_HELP_MENU_SAVE_LOAD(VERB) \
1468 DXX_MENUITEM(VERB, TEXT, "F3\t SWITCH COCKPIT MODES", HELP_F3) \
1469 _DXX_HELP_MENU_D2_DXX_F4(VERB) \
1470 DXX_MENUITEM(VERB, TEXT, TXT_HELP_F5, HELP_F5) \
1471 DXX_MENUITEM(VERB, TEXT, "ALT-F7\t SWITCH HUD MODES", HELP_AF7) \
1472 _DXX_HELP_MENU_PAUSE(VERB) \
1473 DXX_MENUITEM(VERB, TEXT, TXT_HELP_PRTSCN, HELP_PRTSCN) \
1474 DXX_MENUITEM(VERB, TEXT, TXT_HELP_1TO5, HELP_1TO5) \
1475 DXX_MENUITEM(VERB, TEXT, TXT_HELP_6TO10, HELP_6TO10) \
1476 _DXX_HELP_MENU_D2_DXX_FEATURES(VERB) \
1477 _DXX_HELP_MENU_AUDIO(VERB) \
1478 _DXX_HELP_MENU_HINT_CMD_KEY(VERB, HELP) \
1479
1480 }
1481
1482 void show_help()
1483 {
1484 struct help_menu_items
1485 {
1486 enum {
1487 DXX_HELP_MENU(ENUM)
1488 };
1489 std::array<newmenu_item, DXX_HELP_MENU(COUNT)> m;
1490 help_menu_items()
1491 {
1492 DXX_HELP_MENU(ADD);
1493 }
1494 };
1495 struct help_menu : help_menu_items, passive_newmenu
1496 {
1497 help_menu(grs_canvas &src) :
1498 passive_newmenu(menu_title{nullptr}, menu_subtitle{TXT_KEYS}, menu_filename{nullptr}, tiny_mode_flag::tiny, tab_processing_flag::ignore, adjusted_citem::create(m, 0), src)
1499 {
1500 }
1501 };
1502 auto menu = window_create<help_menu>(grd_curscreen->sc_canvas);
1503 (void)menu;
1504 }
1505
1506 #undef DXX_HELP_MENU
1507
1508 #define DSX_NETHELP_MENU(VERB) \
1509 DXX_MENUITEM(VERB, TEXT, "F1\t THIS SCREEN", NETHELP_HELP) \
1510 DSX_NETHELP_DROPFLAG(VERB) \
1511 _DXX_NETHELP_SAVELOAD_GAME(VERB) \
1512 DXX_MENUITEM(VERB, TEXT, "ALT-F4\t SHOW PLAYER NAMES ON HUD", NETHELP_HUDNAMES) \
1513 DXX_MENUITEM(VERB, TEXT, "F7\t TOGGLE KILL LIST", NETHELP_TOGGLE_KILL_LIST) \
1514 DXX_MENUITEM(VERB, TEXT, "F8\t SEND MESSAGE", NETHELP_SENDMSG) \
1515 DXX_MENUITEM(VERB, TEXT, "(SHIFT-)F9 to F12\t (DEFINE)SEND MACRO", NETHELP_MACRO) \
1516 DXX_MENUITEM(VERB, TEXT, "PAUSE\t SHOW NETGAME INFORMATION", NETHELP_GAME_INFO) \
1517 DXX_MENUITEM(VERB, TEXT, "SHIFT-PAUSE\t SHOW NETGAME INFO & RULES", NETHELP_GAME_INFORULES) \
1518 _DXX_HELP_MENU_HINT_CMD_KEY(VERB, NETHELP) \
1519 DXX_MENUITEM(VERB, TEXT, "", NETHELP_SEP1) \
1520 DXX_MENUITEM(VERB, TEXT, "MULTIPLAYER MESSAGE COMMANDS:", NETHELP_COMMAND_HEADER) \
1521 DXX_MENUITEM(VERB, TEXT, "(*): TEXT\t SEND TEXT TO PLAYER/TEAM (*)", NETHELP_DIRECT_MESSAGE) \
1522 DXX_MENUITEM(VERB, TEXT, "/Handicap: (*)\t SET YOUR STARTING SHIELDS TO (*) [10-100]", NETHELP_COMMAND_HANDICAP) \
1523 DXX_MENUITEM(VERB, TEXT, "/move: (*)\t MOVE PLAYER (*) TO OTHER TEAM (Host-only)", NETHELP_COMMAND_MOVE) \
1524 DXX_MENUITEM(VERB, TEXT, "/kick: (*)\t KICK PLAYER (*) FROM GAME (Host-only)", NETHELP_COMMAND_KICK) \
1525 DXX_MENUITEM(VERB, TEXT, "/KillReactor\t BLOW UP THE MINE (Host-only)", NETHELP_COMMAND_KILL_REACTOR) \
1526
1527 enum {
1528 DSX_NETHELP_MENU(ENUM)
1529 };
1530
1531 void show_netgame_help()
1532 {
1533 struct help_menu_items
1534 {
1535 enum {
1536 DSX_NETHELP_MENU(ENUM)
1537 };
1538 std::array<newmenu_item, DSX_NETHELP_MENU(COUNT)> m;
1539 help_menu_items()
1540 {
1541 DSX_NETHELP_MENU(ADD);
1542 }
1543 };
1544 struct help_menu : help_menu_items, passive_newmenu
1545 {
1546 help_menu(grs_canvas &src) :
1547 passive_newmenu(menu_title{nullptr}, menu_subtitle{TXT_KEYS}, menu_filename{nullptr}, tiny_mode_flag::tiny, tab_processing_flag::ignore, adjusted_citem::create(m, 0), src)
1548 {
1549 }
1550 };
1551 auto menu = window_create<help_menu>(grd_curscreen->sc_canvas);
1552 (void)menu;
1553 }
1554
1555 #undef DSX_NETHELP_MENU
1556
1557 #define DXX_NEWDEMO_HELP_MENU(VERB) \
1558 DXX_MENUITEM(VERB, TEXT, "ESC\t QUIT DEMO PLAYBACK", DEMOHELP_QUIT) \
1559 DXX_MENUITEM(VERB, TEXT, "F1\t THIS SCREEN", DEMOHELP_HELP) \
1560 DXX_MENUITEM(VERB, TEXT, TXT_HELP_F2, DEMOHELP_F2) \
1561 DXX_MENUITEM(VERB, TEXT, "F3\t SWITCH COCKPIT MODES", DEMOHELP_F3) \
1562 DXX_MENUITEM(VERB, TEXT, "F4\t TOGGLE PERCENTAGE DISPLAY", DEMOHELP_F4) \
1563 DXX_MENUITEM(VERB, TEXT, "UP\t PLAY", DEMOHELP_PLAY) \
1564 DXX_MENUITEM(VERB, TEXT, "DOWN\t PAUSE", DEMOHELP_PAUSE) \
1565 DXX_MENUITEM(VERB, TEXT, "RIGHT\t ONE FRAME FORWARD", DEMOHELP_FRAME_FORWARD) \
1566 DXX_MENUITEM(VERB, TEXT, "LEFT\t ONE FRAME BACKWARD", DEMOHELP_FRAME_BACKWARD) \
1567 DXX_MENUITEM(VERB, TEXT, "SHIFT-RIGHT\t FAST FORWARD", DEMOHELP_FAST_FORWARD) \
1568 DXX_MENUITEM(VERB, TEXT, "SHIFT-LEFT\t FAST BACKWARD", DEMOHELP_FAST_BACKWARD) \
1569 DXX_MENUITEM(VERB, TEXT, "CTRL-RIGHT\t JUMP TO END", DEMOHELP_JUMP_END) \
1570 DXX_MENUITEM(VERB, TEXT, "CTRL-LEFT\t JUMP TO START", DEMOHELP_JUMP_START) \
1571 _DXX_HELP_MENU_HINT_CMD_KEY(VERB, DEMOHELP) \
1572
1573 enum {
1574 DXX_NEWDEMO_HELP_MENU(ENUM)
1575 };
1576
1577 void show_newdemo_help()
1578 {
1579 struct help_menu_items
1580 {
1581 enum {
1582 DXX_NEWDEMO_HELP_MENU(ENUM)
1583 };
1584 std::array<newmenu_item, DXX_NEWDEMO_HELP_MENU(COUNT)> m;
1585 help_menu_items()
1586 {
1587 DXX_NEWDEMO_HELP_MENU(ADD);
1588 }
1589 };
1590 struct help_menu : help_menu_items, passive_newmenu
1591 {
1592 help_menu(grs_canvas &src) :
1593 passive_newmenu(menu_title{nullptr}, menu_subtitle{"DEMO PLAYBACK CONTROLS"}, menu_filename{nullptr}, tiny_mode_flag::tiny, tab_processing_flag::ignore, adjusted_citem::create(m, 0), src)
1594 {
1595 }
1596 };
1597 auto menu = window_create<help_menu>(grd_curscreen->sc_canvas);
1598 (void)menu;
1599 }
1600
1601 }
1602
1603 namespace {
1604
1605 #undef DXX_NEWDEMO_HELP_MENU
1606
1607 #define LEAVE_TIME 0x4000 //how long until we decide key is down (Used to be 0x4000)
1608
1609 enum class leave_type : uint_fast8_t
1610 {
1611 none,
1612 maybe_on_release,
1613 wait_for_release,
1614 on_press,
1615 };
1616
1617 static leave_type leave_mode;
1618
1619 static void end_rear_view()
1620 {
1621 Rear_view = 0;
1622 if (PlayerCfg.CockpitMode[1] == cockpit_mode_t::rear_view)
1623 select_cockpit(PlayerCfg.CockpitMode[0]);
1624 if (Newdemo_state == ND_STATE_RECORDING)
1625 newdemo_record_restore_rearview();
1626 }
1627
1628 static void check_end_rear_view()
1629 {
1630 leave_mode = leave_type::none;
1631 if (Rear_view)
1632 end_rear_view();
1633 }
1634
1635 }
1636
1637 namespace dsx {
1638
1639 //deal with rear view - switch it on, or off, or whatever
1640 void check_rear_view(control_info &Controls)
1641 {
1642 static fix64 entry_time;
1643
1644 if (Newdemo_state == ND_STATE_PLAYBACK)
1645 return;
1646
1647 const auto rear_view = Controls.state.rear_view;
1648 switch (leave_mode)
1649 {
1650 case leave_type::none:
1651 if (!rear_view)
1652 return;
1653 if (Rear_view)
1654 end_rear_view();
1655 else
1656 {
1657 Rear_view = 1;
1658 leave_mode = leave_type::maybe_on_release; //means wait for another key
1659 entry_time = timer_query();
1660 if (PlayerCfg.CockpitMode[1] == cockpit_mode_t::full_cockpit)
1661 select_cockpit(cockpit_mode_t::rear_view);
1662 if (Newdemo_state == ND_STATE_RECORDING)
1663 newdemo_record_rearview();
1664 }
1665 return;
1666 case leave_type::maybe_on_release:
1667 if (rear_view)
1668 {
1669 if (timer_query() - entry_time > LEAVE_TIME)
1670 leave_mode = leave_type::wait_for_release;
1671 }
1672 else
1673 leave_mode = leave_type::on_press;
1674 return;
1675 case leave_type::wait_for_release:
1676 if (!rear_view)
1677 check_end_rear_view();
1678 return;
1679 case leave_type::on_press:
1680 if (rear_view)
1681 {
1682 Controls.state.rear_view = 0;
1683 check_end_rear_view();
1684 }
1685 return;
1686 default:
1687 break;
1688 }
1689 }
1690
1691 }
1692
1693 void reset_rear_view(void)
1694 {
1695 if (Rear_view) {
1696 if (Newdemo_state == ND_STATE_RECORDING)
1697 newdemo_record_restore_rearview();
1698 }
1699
1700 Rear_view = 0;
1701 select_cockpit(PlayerCfg.CockpitMode[0]);
1702 }
1703
1704 int8_t cheats_enabled()
1705 {
1706 return cheats.enabled;
1707 }
1708
1709 //turns off all cheats & resets cheater flag
1710 void game_disable_cheats()
1711 {
1712 #if DXX_BUILD_DESCENT == 2
1713 if (cheats.homingfire)
1714 weapons_homing_all_reset();
1715 #endif
1716
1717 cheats = {};
1718 }
1719
1720 // game_setup()
1721 // ----------------------------------------------------------------------------
1722
1723 namespace dsx {
1724
1725 game_window *game_setup()
1726 {
1727
1728 PlayerCfg.CockpitMode[1] = PlayerCfg.CockpitMode[0];
1729 last_drawn_cockpit = cockpit_mode_t{UINT8_MAX}; // Force cockpit to redraw next time a frame renders.
1730 Endlevel_sequence = 0;
1731
1732 auto game_wind = window_create<game_window>(grd_curscreen->sc_canvas, 0, 0, SWIDTH, SHEIGHT);
1733 reset_palette_add();
1734 #if DXX_USE_STEREOSCOPIC_RENDER
1735 init_stereo();
1736 #endif
1737 init_cockpit();
1738 init_gauges();
1739 netplayerinfo_on = 0;
1740
1741 #if DXX_USE_EDITOR
1742 if (!Cursegp)
1743 {
1744 Cursegp = imsegptridx(segment_first);
1745 Curside = sidenum_t::WLEFT;
1746 }
1747 #endif
1748
1749 Viewer = ConsoleObject;
1750 fly_init(*ConsoleObject);
1751 Game_suspended = 0;
1752 reset_time();
1753 FrameTime = 0; //make first frame zero
1754
1755 fix_object_segs();
1756 if (CGameArg.SysAutoRecordDemo && Newdemo_state == ND_STATE_NORMAL)
1757 newdemo_start_recording();
1758 return game_wind;
1759 }
1760
1761 // Event handler for the game
1762 window_event_result game_window::event_handler(const d_event &event)
1763 {
1764 auto result = window_event_result::ignored;
1765
1766 switch (event.type)
1767 {
1768 case event_type::window_activated:
1769 set_screen_mode(SCREEN_GAME);
1770
1771 event_toggle_focus(1);
1772 key_toggle_repeat(0);
1773 game_flush_inputs(Controls);
1774
1775 if (time_paused)
1776 start_time();
1777
1778 if (!((Game_mode & GM_MULTI) && (Newdemo_state != ND_STATE_PLAYBACK)))
1779 digi_resume_digi_sounds();
1780
1781 if (!((Game_mode & GM_MULTI) && (Newdemo_state != ND_STATE_PLAYBACK)))
1782 palette_restore();
1783
1784 reset_cockpit();
1785 break;
1786
1787 case event_type::window_deactivated:
1788 if (!(((Game_mode & GM_MULTI) && (Newdemo_state != ND_STATE_PLAYBACK)) && (!Endlevel_sequence)) )
1789 stop_time();
1790
1791 if (!((Game_mode & GM_MULTI) && (Newdemo_state != ND_STATE_PLAYBACK)))
1792 digi_pause_digi_sounds();
1793
1794 if (!((Game_mode & GM_MULTI) && (Newdemo_state != ND_STATE_PLAYBACK)))
1795 full_palette_save();
1796
1797 event_toggle_focus(0);
1798 key_toggle_repeat(1);
1799 break;
1800
1801 #if DXX_MAX_BUTTONS_PER_JOYSTICK
1802 case event_type::joystick_button_up:
1803 case event_type::joystick_button_down:
1804 #endif
1805 #if DXX_MAX_AXES_PER_JOYSTICK
1806 case event_type::joystick_moved:
1807 #endif
1808 case event_type::mouse_button_up:
1809 case event_type::mouse_button_down:
1810 case event_type::mouse_moved:
1811 case event_type::key_command:
1812 case event_type::key_release:
1813 case event_type::idle:
1814 return ReadControls(LevelSharedRobotInfoState, event, Controls);
1815
1816 case event_type::window_draw:
1817 if (!time_paused)
1818 {
1819 calc_frame_time();
1820 result = GameProcessFrame(LevelSharedRobotInfoState);
1821 }
1822
1823 if (!Automap_active) // efficiency hack
1824 {
1825 if (force_cockpit_redraw) { //screen need redrawing?
1826 init_cockpit();
1827 force_cockpit_redraw=0;
1828 }
1829 game_render_frame(LevelSharedRobotInfoState.Robot_info, Controls);
1830 }
1831 break;
1832
1833 case event_type::window_close:
1834 digi_stop_digi_sounds();
1835
1836 if ( (Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED) )
1837 newdemo_stop_recording();
1838
1839 multi_leave_game();
1840
1841 if ( Newdemo_state == ND_STATE_PLAYBACK )
1842 newdemo_stop_playback();
1843
1844 songs_play_song(song_number::title, 1);
1845
1846 game_disable_cheats();
1847 Game_mode = {};
1848 #if DXX_USE_EDITOR
1849 if (!EditorWindow) // have to do it this way because of the necessary longjmp. Yuck.
1850 #endif
1851 show_menus();
1852 event_toggle_focus(0);
1853 key_toggle_repeat(1);
1854 Game_wind = nullptr;
1855 return window_event_result::ignored;
1856
1857 case event_type::loop_begin_loop:
1858 kconfig_begin_loop(Controls);
1859 break;
1860 case event_type::loop_end_loop:
1861 kconfig_end_loop(Controls, FrameTime);
1862 break;
1863
1864 default:
1865 break;
1866 }
1867
1868 return result;
1869 }
1870
1871 // Initialise game, actually runs in main event loop
1872 void game()
1873 {
1874 hide_menus();
1875 Game_wind = game_setup();
1876 }
1877
1878 }
1879
1880 //called at the end of the program
1881 void close_game()
1882 {
1883 close_gauges();
1884 restore_effect_bitmap_icons();
1885 }
1886
1887 #if DXX_BUILD_DESCENT == 2
1888 namespace dsx {
1889 object *Missile_viewer=NULL;
1890 object_signature_t Missile_viewer_sig;
1891
1892 enumerated_array<game_marker_index, 2, gauge_inset_window_view> Marker_viewer_num{
1893 {{
1894 game_marker_index::None,
1895 game_marker_index::None,
1896 }}
1897 };
1898 enumerated_array<unsigned, 2, gauge_inset_window_view> Coop_view_player{
1899 {{
1900 UINT_MAX,
1901 UINT_MAX
1902 }}
1903 };
1904
1905 //returns ptr to escort robot, or NULL
1906 imobjptridx_t find_escort(fvmobjptridx &vmobjptridx, const d_robot_info_array &Robot_info)
1907 {
1908 range_for (const auto &&o, vmobjptridx)
1909 {
1910 if (o->type == OBJ_ROBOT && Robot_info[get_robot_id(o)].companion)
1911 return imobjptridx_t(o);
1912 }
1913 return object_none;
1914 }
1915
1916 namespace {
1917 //if water or fire level, make occasional sound
1918 static void do_ambient_sounds(const sound_ambient_flags s2_flags)
1919 {
1920 sound_effect sound;
1921 switch (s2_flags)
1922 {
1923 case sound_ambient_flags::water_and_lava:
1924 if (d_rand() & 1) //both, pick one
1925 {
1926 case sound_ambient_flags::water:
1927 sound = sound_effect::SOUND_AMBIENT_WATER;
1928 break;
1929 }
1930 [[fallthrough]];
1931 case sound_ambient_flags::lava:
1932 sound = sound_effect::SOUND_AMBIENT_LAVA;
1933 break;
1934 default:
1935 return;
1936 }
1937 if (((d_rand() << 3) < FrameTime)) { //play the sound
1938 fix volume = d_rand() + f1_0/2;
1939 digi_play_sample(sound,volume);
1940 }
1941 }
1942 }
1943 }
1944 #endif
1945
1946 void game_leave_menus(void)
1947 {
1948 if (!Game_wind)
1949 return;
1950 for (;;) // go through all windows and actually close them if they want to
1951 {
1952 const auto wind = window_get_front();
1953 if (!wind)
1954 break;
1955 if (wind == Game_wind)
1956 break;
1957 if (!window_close(wind))
1958 break;
1959 }
1960 }
1961
1962 namespace dsx {
1963
1964 namespace {
1965
1966 window_event_result GameProcessFrame(const d_level_shared_robot_info_state &LevelSharedRobotInfoState)
1967 {
1968 auto &LevelUniqueControlCenterState = LevelUniqueObjectState.ControlCenterState;
1969 auto &Objects = LevelUniqueObjectState.Objects;
1970 auto &vmobjptr = Objects.vmptr;
1971 auto &plrobj = get_local_plrobj();
1972 auto &player_info = plrobj.ctype.player_info;
1973 auto &local_player_shields_ref = plrobj.shields;
1974 fix player_shields = local_player_shields_ref;
1975 const auto player_was_dead{Player_dead_state};
1976 auto result = window_event_result::ignored;
1977
1978 state_poll_autosave_game(GameUniqueState, LevelUniqueObjectState);
1979 update_player_stats();
1980 diminish_palette_towards_normal(); // Should leave palette effect up for as long as possible by putting right before render.
1981 do_afterburner_stuff(Objects);
1982 do_cloak_stuff();
1983 do_invulnerable_stuff(player_info);
1984 #if DXX_BUILD_DESCENT == 2
1985 init_ai_frame(player_info.powerup_flags, Controls);
1986 result = do_final_boss_frame();
1987
1988 auto &pl_flags = player_info.powerup_flags;
1989 if (pl_flags & PLAYER_FLAGS_HEADLIGHT_ON)
1990 {
1991 static int turned_off=0;
1992 auto &energy = player_info.energy;
1993 energy -= (FrameTime*3/8);
1994 if (energy < i2f(10)) {
1995 if (!turned_off) {
1996 pl_flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
1997 turned_off = 1;
1998 if (Game_mode & GM_MULTI)
1999 multi_send_flags(Player_num);
2000 }
2001 }
2002 else
2003 turned_off = 0;
2004
2005 if (energy <= 0)
2006 {
2007 energy = 0;
2008 pl_flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2009 if (Game_mode & GM_MULTI)
2010 multi_send_flags(Player_num);
2011 }
2012 }
2013 #endif
2014
2015 #if DXX_USE_EDITOR
2016 check_create_player_path();
2017 player_follow_path(vmobjptr(ConsoleObject));
2018 #endif
2019
2020 #if DXX_USE_MULTIPLAYER
2021 if (Game_mode & GM_MULTI)
2022 {
2023 result = std::max(multi_do_frame(), result);
2024 if (Netgame.PlayTimeAllowed.count())
2025 {
2026 if (ThisLevelTime >= Netgame.PlayTimeAllowed)
2027 multi_check_for_killgoal_winner(LevelSharedRobotInfoState.Robot_info);
2028 ThisLevelTime += d_time_fix(FrameTime);
2029 }
2030 }
2031 #endif
2032
2033 result = std::max(dead_player_frame(LevelSharedRobotInfoState.Robot_info), result);
2034 if (Newdemo_state != ND_STATE_PLAYBACK)
2035 result = std::max(do_controlcen_dead_frame(), result);
2036 if (result == window_event_result::close)
2037 return result; // skip everything else - don't set Player_dead_state again
2038
2039 #if DXX_BUILD_DESCENT == 2
2040 process_super_mines_frame();
2041 do_seismic_stuff();
2042 do_ambient_sounds(vcsegptr(ConsoleObject->segnum)->s2_flags);
2043 #endif
2044
2045 digi_sync_sounds();
2046
2047 if (Endlevel_sequence) {
2048 result = std::max(do_endlevel_frame(LevelSharedRobotInfoState), result);
2049 powerup_grab_cheat_all();
2050 do_special_effects();
2051 return result; //skip everything else
2052 }
2053
2054 if ((Newdemo_state != ND_STATE_PLAYBACK) || (Newdemo_vcr_state != ND_STATE_PAUSED)) {
2055 do_special_effects();
2056 wall_frame_process(LevelSharedRobotInfoState.Robot_info);
2057 }
2058
2059 if (LevelUniqueControlCenterState.Control_center_destroyed)
2060 {
2061 if (Newdemo_state==ND_STATE_RECORDING )
2062 newdemo_record_control_center_destroyed();
2063 }
2064
2065 flash_frame();
2066
2067 if ( Newdemo_state == ND_STATE_PLAYBACK )
2068 {
2069 result = std::max(newdemo_playback_one_frame(), result);
2070 if ( Newdemo_state != ND_STATE_PLAYBACK )
2071 {
2072 Assert(result == window_event_result::close);
2073 return window_event_result::close; // Go back to menu
2074 }
2075 }
2076 else
2077 { // Note the link to above!
2078 #ifndef NEWHOMER
2079 player_info.homing_object_dist = -1; // Assume not being tracked. Laser_do_weapon_sequence modifies this.
2080 #endif
2081 result = std::max(game_move_all_objects(LevelSharedRobotInfoState), result);
2082 powerup_grab_cheat_all();
2083
2084 if (Endlevel_sequence) //might have been started during move
2085 return result;
2086
2087 fuelcen_update_all(LevelSharedRobotInfoState.Robot_info);
2088 do_ai_frame_all(LevelSharedRobotInfoState.Robot_info);
2089
2090 auto laser_firing_count = FireLaser(player_info, Controls);
2091 if (auto &Auto_fire_fusion_cannon_time = player_info.Auto_fire_fusion_cannon_time)
2092 {
2093 if (player_info.Primary_weapon != primary_weapon_index_t::FUSION_INDEX)
2094 Auto_fire_fusion_cannon_time = 0;
2095 else if ((laser_firing_count = (GameTime64 + FrameTime/2 >= Auto_fire_fusion_cannon_time)))
2096 {
2097 Auto_fire_fusion_cannon_time = 0;
2098 } else if (d_tick_step) {
2099 const auto rx = (d_rand() - 16384) / 8;
2100 const auto rz = (d_rand() - 16384) / 8;
2101 const auto &&console = vmobjptr(ConsoleObject);
2102 auto &rotvel = console->mtype.phys_info.rotvel;
2103 rotvel.x += rx;
2104 rotvel.z += rz;
2105
2106 const auto bump_amount = player_info.Fusion_charge > F1_0*2 ? player_info.Fusion_charge * 4 : F1_0 * 4;
2107 bump_one_object(console, make_random_vector(), bump_amount);
2108 }
2109 }
2110
2111 if (laser_firing_count)
2112 do_laser_firing_player(plrobj);
2113 delayed_autoselect(player_info, Controls);
2114 }
2115
2116 if (Do_appearance_effect) {
2117 Do_appearance_effect = 0;
2118 create_player_appearance_effect(Vclip, *ConsoleObject);
2119 }
2120
2121 #if DXX_BUILD_DESCENT == 2
2122 omega_charge_frame(player_info);
2123 slide_textures();
2124 auto &LevelSharedDestructibleLightState = LevelSharedSegmentState.DestructibleLights;
2125 flicker_lights(LevelSharedDestructibleLightState, Flickering_light_state, vmsegptridx);
2126
2127 //if the player is taking damage, give up guided missile control
2128 if (local_player_shields_ref != player_shields)
2129 {
2130 const auto player_num{Player_num};
2131 if (const auto &&gimobj = LevelUniqueObjectState.Guided_missile.get_player_active_guided_missile(vmobjptr, player_num))
2132 release_local_guided_missile(LevelUniqueObjectState, player_num, *gimobj);
2133 }
2134 #endif
2135
2136 // Check if we have to close in-game menus for multiplayer
2137 if ((Game_mode & GM_MULTI) && get_local_player().connected == player_connection_status::playing)
2138 {
2139 if (Endlevel_sequence || Player_dead_state != player_was_dead || local_player_shields_ref < player_shields || (LevelUniqueControlCenterState.Control_center_destroyed && LevelUniqueControlCenterState.Countdown_seconds_left < 10))
2140 game_leave_menus();
2141 }
2142
2143 return result;
2144 }
2145
2146 }
2147
2148 #if DXX_BUILD_DESCENT == 2
2149 void compute_slide_segs()
2150 {
2151 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
2152 for (const csmusegment suseg : vmsegptr)
2153 {
2154 sidemask_t slide_textures{};
2155 for (const auto sidenum : MAX_SIDES_PER_SEGMENT)
2156 {
2157 const auto &uside = suseg.u.sides[sidenum];
2158 const auto &ti = TmapInfo[get_texture_index(uside.tmap_num)];
2159 if (!(ti.slide_u || ti.slide_v))
2160 continue;
2161 const auto &sside = suseg.s.sides[sidenum];
2162 if (IS_CHILD(suseg.s.children[sidenum]) && sside.wall_num == wall_none)
2163 /* If a wall exists, it could be visible at start or
2164 * become visible later, so always enable sliding for
2165 * walls.
2166 */
2167 continue;
2168 slide_textures |= build_sidemask(sidenum);
2169 }
2170 suseg.u.slide_textures = slide_textures;
2171 }
2172 }
2173
2174 namespace {
2175
2176 template <fix uvl::*p>
2177 static void update_uv(std::array<uvl, 4> &uvls, uvl &i, fix a)
2178 {
2179 if (!a)
2180 return;
2181 const auto ip = (i.*p += a);
2182 if (ip > f2_0)
2183 range_for (auto &j, uvls)
2184 j.*p -= f1_0;
2185 else if (ip < -f2_0)
2186 range_for (auto &j, uvls)
2187 j.*p += f1_0;
2188 }
2189
2190 // -----------------------------------------------------------------------------
2191 static void slide_textures(void)
2192 {
2193 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
2194 for (unique_segment &useg : vmsegptr)
2195 {
2196 if (const auto slide_seg = useg.slide_textures; slide_seg != sidemask_t{})
2197 {
2198 for (const auto sidenum : MAX_SIDES_PER_SEGMENT)
2199 {
2200 if (slide_seg & build_sidemask(sidenum))
2201 {
2202 auto &side = useg.sides[sidenum];
2203 const auto &ti = TmapInfo[get_texture_index(side.tmap_num)];
2204 const auto tiu = ti.slide_u;
2205 const auto tiv = ti.slide_v;
2206 if (tiu || tiv)
2207 {
2208 const auto frametime{FrameTime};
2209 const auto ua = fixmul(frametime, tiu << 8);
2210 const auto va = fixmul(frametime, tiv << 8);
2211 auto &uvls = side.uvls;
2212 range_for (auto &i, uvls)
2213 {
2214 update_uv<&uvl::u>(uvls, i, ua);
2215 update_uv<&uvl::v>(uvls, i, va);
2216 }
2217 }
2218 }
2219 }
2220 }
2221 }
2222 }
2223
2224 constexpr std::integral_constant<fix, INT32_MIN> flicker_timer_disabled{};
2225
2226 static void flicker_lights(const d_level_shared_destructible_light_state &LevelSharedDestructibleLightState, d_flickering_light_state &fls, fvmsegptridx &vmsegptridx)
2227 {
2228 auto &TmapInfo = LevelUniqueTmapInfoState.TmapInfo;
2229 auto &Walls = LevelUniqueWallSubsystemState.Walls;
2230 auto &vcwallptr = Walls.vcptr;
2231 range_for (auto &f, partial_range(fls.Flickering_lights, fls.Num_flickering_lights))
2232 {
2233 if (f.timer == flicker_timer_disabled) //disabled
2234 continue;
2235 const auto &&segp = vmsegptridx(f.segnum);
2236 const auto sidenum{f.sidenum};
2237 {
2238 auto &side = segp->unique_segment::sides[sidenum];
2239 if (!(TmapInfo[get_texture_index(side.tmap_num)].lighting || TmapInfo[get_texture_index(side.tmap_num2)].lighting))
2240 continue;
2241 }
2242
2243 //make sure this is actually a light
2244 if (! (WALL_IS_DOORWAY(GameBitmaps, Textures, vcwallptr, segp, sidenum) & WALL_IS_DOORWAY_FLAG::render))
2245 continue;
2246
2247 if ((f.timer -= FrameTime) < 0)
2248 {
2249 while (f.timer < 0)
2250 f.timer += f.delay;
2251 f.mask = ((f.mask & 0x80000000) ? 1 : 0) + (f.mask << 1);
2252 if (f.mask & 1)
2253 add_light(LevelSharedDestructibleLightState, segp, sidenum);
2254 else
2255 subtract_light(LevelSharedDestructibleLightState, segp, sidenum);
2256 }
2257 }
2258 }
2259
2260 //returns ptr to flickering light structure, or NULL if can't find
2261 static std::pair<d_flickering_light_state::Flickering_light_array_t::iterator, d_flickering_light_state::Flickering_light_array_t::iterator> find_flicker(d_flickering_light_state &fls, const vmsegidx_t segnum, const sidenum_t sidenum)
2262 {
2263 //see if there's already an entry for this seg/side
2264 const auto &&pr = partial_range(fls.Flickering_lights, fls.Num_flickering_lights);
2265 const auto &&predicate = [segnum, sidenum](const flickering_light &f) {
2266 return f.segnum == segnum && f.sidenum == sidenum; //found it!
2267 };
2268 const auto &&pe = pr.end();
2269 return {std::ranges::find_if(pr.begin(), pe, predicate), pe};
2270 }
2271
2272 static void update_flicker(d_flickering_light_state &fls, const vmsegidx_t segnum, const sidenum_t sidenum, const fix timer)
2273 {
2274 const auto &&i = find_flicker(fls, segnum, sidenum);
2275 if (i.first != i.second)
2276 i.first->timer = timer;
2277 }
2278
2279 }
2280
2281 //turn flickering off (because light has been turned off)
2282 void disable_flicker(d_flickering_light_state &fls, const vmsegidx_t segnum, const sidenum_t sidenum)
2283 {
2284 update_flicker(fls, segnum, sidenum, flicker_timer_disabled);
2285 }
2286
2287 //turn flickering off (because light has been turned on)
2288 void enable_flicker(d_flickering_light_state &fls, const vmsegidx_t segnum, const sidenum_t sidenum)
2289 {
2290 update_flicker(fls, segnum, sidenum, 0);
2291 }
2292 #endif
2293
2294 namespace {
2295
2296 // -----------------------------------------------------------------------------
2297 // Fire Laser: Registers a laser fire, and performs special stuff for the fusion
2298 // cannon.
2299 bool FireLaser(player_info &player_info, const control_info &Controls)
2300 {
2301 auto &Objects = LevelUniqueObjectState.Objects;
2302 auto &vmobjptr = Objects.vmptr;
2303 auto &vmobjptridx = Objects.vmptridx;
2304 if (!Controls.state.fire_primary)
2305 return false;
2306 if (!allowed_to_fire_laser(player_info))
2307 return false;
2308 auto &Primary_weapon = player_info.Primary_weapon;
2309 if (!Weapon_info[Primary_weapon_to_weapon_info[Primary_weapon]].fire_count)
2310 /* Retail data sets fire_count=1 for all primary weapons */
2311 return false;
2312
2313 if (Primary_weapon == primary_weapon_index_t::FUSION_INDEX)
2314 {
2315 auto &energy = player_info.energy;
2316 auto &Auto_fire_fusion_cannon_time = player_info.Auto_fire_fusion_cannon_time;
2317 if (energy < F1_0 * 2 && Auto_fire_fusion_cannon_time == 0)
2318 {
2319 return false;
2320 } else {
2321 static fix64 Fusion_next_sound_time = 0;
2322
2323 if (player_info.Fusion_charge == 0)
2324 energy -= F1_0*2;
2325
2326 const auto Fusion_charge = (player_info.Fusion_charge += FrameTime);
2327 energy -= FrameTime;
2328
2329 if (energy <= 0)
2330 {
2331 energy = 0;
2332 Auto_fire_fusion_cannon_time = GameTime64 -1; // Fire now!
2333 } else
2334 Auto_fire_fusion_cannon_time = GameTime64 + FrameTime/2 + 1; // Fire the fusion cannon at this time in the future.
2335
2336 {
2337 int dg, db;
2338 const int dr = Fusion_charge >> 11;
2339 if (Fusion_charge < F1_0*2)
2340 dg = 0, db = dr;
2341 else
2342 dg = dr, db = 0;
2343 PALETTE_FLASH_ADD(dr, dg, db);
2344 }
2345
2346 if (Fusion_next_sound_time > GameTime64 + F1_0/8 + D_RAND_MAX/4) // GameTime64 is smaller than max delay - player in new level?
2347 Fusion_next_sound_time = GameTime64 - 1;
2348
2349 if (Fusion_next_sound_time < GameTime64) {
2350 if (Fusion_charge > F1_0*2) {
2351 digi_play_sample(sound_effect::SOUND_BADASS_EXPLOSION, F1_0 );
2352 #if DXX_BUILD_DESCENT == 1
2353 if(Game_mode & GM_MULTI)
2354 multi_send_play_sound(sound_effect::SOUND_BADASS_EXPLOSION, F1_0, sound_stack::allow_stacking);
2355 #endif
2356 const auto cobjp = vmobjptridx(ConsoleObject);
2357 apply_damage_to_player(cobjp, cobjp, d_rand() * 4, apply_damage_player::always);
2358 } else {
2359 create_awareness_event(vmobjptr(ConsoleObject), player_awareness_type_t::PA_WEAPON_ROBOT_COLLISION, LevelUniqueRobotAwarenessState);
2360 multi_digi_play_sample(sound_effect::SOUND_FUSION_WARMUP, F1_0);
2361 }
2362 Fusion_next_sound_time = GameTime64 + F1_0/8 + d_rand()/4;
2363 }
2364 }
2365 }
2366 return true;
2367 }
2368
2369
2370 // -------------------------------------------------------------------------------------------------------
2371 // If player is close enough to objnum, which ought to be a powerup, pick it up!
2372 // This could easily be made difficulty level dependent.
2373 static void powerup_grab_cheat(object &player, const vmobjptridx_t powerup)
2374 {
2375 fix powerup_size;
2376 fix player_size;
2377
2378 Assert(powerup->type == OBJ_POWERUP);
2379
2380 powerup_size = powerup->size;
2381 player_size = player.size;
2382
2383 const auto dist = vm_vec_dist_quick(powerup->pos, player.pos);
2384
2385 if ((dist < 2*(powerup_size + player_size)) && !(powerup->flags & OF_SHOULD_BE_DEAD)) {
2386 collide_live_local_player_and_powerup(powerup);
2387 }
2388 }
2389
2390 // -------------------------------------------------------------------------------------------------------
2391 // Make it easier to pick up powerups.
2392 // For all powerups in this segment, pick them up at up to twice pickuppable distance based on dot product
2393 // from player to powerup and player's forward vector.
2394 // This has the effect of picking them up more easily left/right and up/down, but not making them disappear
2395 // way before the player gets there.
2396 void powerup_grab_cheat_all(void)
2397 {
2398 auto &Objects = LevelUniqueObjectState.Objects;
2399 auto &vmobjptr = Objects.vmptr;
2400 auto &vmobjptridx = Objects.vmptridx;
2401 if (Endlevel_sequence)
2402 return;
2403 if (Player_dead_state != player_dead_state::no)
2404 return;
2405 const auto &&console = vmobjptr(ConsoleObject);
2406 range_for (const auto objnum, objects_in(vmsegptr(console->segnum), vmobjptridx, vmsegptr))
2407 if (objnum->type == OBJ_POWERUP)
2408 powerup_grab_cheat(console, objnum);
2409 }
2410
2411 }
2412
2413 }
2414
2415 #ifdef SHOW_EXIT_PATH
2416 namespace dsx {
2417 namespace {
2418
2419 // ------------------------------------------------------------------------------------------------------------------
2420 // Create path for player from current segment to goal segment.
2421 // Return true if path created, else return false.
2422 static int mark_player_path_to_segment(const d_vclip_array &Vclip, fvmobjptridx &vmobjptridx, fvmsegptridx &vmsegptridx, segnum_t segnum)
2423 {
2424 int player_hide_index=-1;
2425
2426 if (LevelUniqueObjectState.Level_path_created)
2427 return 0;
2428 LevelUniqueObjectState.Level_path_created = 1;
2429
2430 auto objp = vmobjptridx(ConsoleObject);
2431 const auto &&cr = create_path_points(objp, create_path_unused_robot_info, objp->segnum, segnum, Point_segs_free_ptr, 100, create_path_random_flag::nonrandom, create_path_safety_flag::unsafe, segment_none);
2432 const unsigned player_path_length = cr.second;
2433 if (cr.first == create_path_result::early)
2434 return 0;
2435
2436 player_hide_index = Point_segs_free_ptr - Point_segs;
2437 Point_segs_free_ptr += player_path_length;
2438
2439 if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
2440 ai_reset_all_paths();
2441 return 0;
2442 }
2443
2444 for (int i=1; i<player_path_length; i++) {
2445 vms_vector seg_center;
2446
2447 seg_center = Point_segs[player_hide_index+i].point;
2448
2449 const auto &&obj = obj_create(LevelUniqueObjectState, LevelSharedSegmentState, LevelUniqueSegmentState, OBJ_POWERUP, underlying_value(powerup_type_t::POW_ENERGY), vmsegptridx(Point_segs[player_hide_index+i].segnum), seg_center, &vmd_identity_matrix, Powerup_info[powerup_type_t::POW_ENERGY].size, object::control_type::powerup, object::movement_type::None, render_type::RT_POWERUP);
2450 if (obj == object_none) {
2451 Int3(); // Unable to drop energy powerup for path
2452 return 1;
2453 }
2454
2455 obj->rtype.vclip_info.vclip_num = Powerup_info[get_powerup_id(obj)].vclip_num;
2456 obj->rtype.vclip_info.frametime = Vclip[obj->rtype.vclip_info.vclip_num].frame_time;
2457 obj->rtype.vclip_info.framenum = 0;
2458 obj->lifeleft = F1_0*100 + d_rand() * 4;
2459 }
2460
2461 return 1;
2462 }
2463
2464 }
2465
2466 // Return true if it happened, else return false.
2467 int create_special_path(void)
2468 {
2469 auto &Objects = LevelUniqueObjectState.Objects;
2470 auto &vmobjptridx = Objects.vmptridx;
2471 // ---------- Find exit doors ----------
2472 range_for (const auto &&segp, vcsegptridx)
2473 {
2474 for (const auto child_segnum : segp->shared_segment::children)
2475 if (child_segnum == segment_exit)
2476 {
2477 return mark_player_path_to_segment(Vclip, vmobjptridx, vmsegptridx, segp);
2478 }
2479 }
2480
2481 return 0;
2482 }
2483
2484 }
2485 #endif
2486
2487
2488 #if DXX_BUILD_DESCENT == 2
2489 namespace dsx {
2490 /*
2491 * reads a flickering_light structure from a PHYSFS_File
2492 */
2493 void flickering_light_read(flickering_light &fl, const NamedPHYSFS_File fp)
2494 {
2495 fl.segnum = read_untrusted_segnum_le16(fp);
2496 const auto sidenum{build_sidenum_from_untrusted(PHYSFSX_readSLE16(fp))};
2497 fl.mask = PHYSFSX_readInt(fp);
2498 fl.timer = PHYSFSX_readFix(fp);
2499 fl.delay = PHYSFSX_readFix(fp);
2500 if (!sidenum)
2501 {
2502 fl = {};
2503 return;
2504 }
2505 fl.sidenum = sidenum.value();
2506 }
2507
2508 void flickering_light_write(const flickering_light &fl, PHYSFS_File *fp)
2509 {
2510 PHYSFS_writeSLE16(fp, fl.segnum);
2511 PHYSFS_writeSLE16(fp, underlying_value(fl.sidenum));
2512 PHYSFS_writeULE32(fp, fl.mask);
2513 PHYSFSX_writeFix(fp, fl.timer);
2514 PHYSFSX_writeFix(fp, fl.delay);
2515 }
2516 }
2517 #endif