]> icculus.org git repositories - btb/d2x.git/blob - main/game.c
explicit casts
[btb/d2x.git] / main / game.c
1 /*
2 THE COMPUTER CODE CONTAINED HEREIN IS THE SOLE PROPERTY OF PARALLAX
3 SOFTWARE CORPORATION ("PARALLAX").  PARALLAX, IN DISTRIBUTING THE CODE TO
4 END-USERS, AND SUBJECT TO ALL OF THE TERMS AND CONDITIONS HEREIN, GRANTS A
5 ROYALTY-FREE, PERPETUAL LICENSE TO SUCH END-USERS FOR USE BY SUCH END-USERS
6 IN USING, DISPLAYING,  AND CREATING DERIVATIVE WORKS THEREOF, SO LONG AS
7 SUCH USE, DISPLAY OR CREATION IS FOR NON-COMMERCIAL, ROYALTY OR REVENUE
8 FREE PURPOSES.  IN NO EVENT SHALL THE END-USER USE THE COMPUTER CODE
9 CONTAINED HEREIN FOR REVENUE-BEARING PURPOSES.  THE END-USER UNDERSTANDS
10 AND AGREES TO THE TERMS HEREIN AND ACCEPTS THE SAME BY USE OF THIS FILE.
11 COPYRIGHT 1993-1999 PARALLAX SOFTWARE CORPORATION.  ALL RIGHTS RESERVED.
12 */
13
14 /*
15  *
16  * Game loop for Inferno
17  *
18  */
19
20 #ifdef HAVE_CONFIG_H
21 #include <conf.h>
22 #endif
23
24 #include <stdio.h>
25 #include <stdlib.h>
26 #include <string.h>
27 #include <stdarg.h>
28 #include <ctype.h>
29 #include <time.h>
30 #include <math.h>
31
32 #ifdef MACINTOSH
33 #include <Files.h>
34 #include <StandardFile.h>
35 #include <Quickdraw.h>
36 #include <Script.h>
37 #include <Strings.h>
38 #endif
39
40 #ifdef OGL
41 #include "ogl_init.h"
42 #endif
43
44 #include "pstypes.h"
45 #include "console.h"
46 #include "gr.h"
47 #include "inferno.h"
48 #include "game.h"
49 #include "key.h"
50 #include "object.h"
51 #include "physics.h"
52 #include "error.h"
53 #include "joy.h"
54 #include "mono.h"
55 #include "iff.h"
56 #include "pcx.h"
57 #include "timer.h"
58 #include "render.h"
59 #include "laser.h"
60 #include "screens.h"
61 #include "textures.h"
62 #include "slew.h"
63 #include "gauges.h"
64 #include "texmap.h"
65 #include "3d.h"
66 #include "effects.h"
67 #include "menu.h"
68 #include "gameseg.h"
69 #include "wall.h"
70 #include "ai.h"
71 #include "fuelcen.h"
72 #include "digi.h"
73 #include "ibitblt.h"
74 #include "u_mem.h"
75 #include "palette.h"
76 #include "morph.h"
77 #include "lighting.h"
78 #include "newdemo.h"
79 #include "collide.h"
80 #include "weapon.h"
81 #include "sounds.h"
82 #include "args.h"
83 #include "gameseq.h"
84 #include "automap.h"
85 #include "text.h"
86 #include "powerup.h"
87 #include "fireball.h"
88 #include "newmenu.h"
89 #ifdef NETWORK
90 #include "network.h"
91 #endif
92 #include "gamefont.h"
93 #include "endlevel.h"
94 #include "joydefs.h"
95 #include "kconfig.h"
96 #include "mouse.h"
97 #include "switch.h"
98 #include "controls.h"
99 #include "songs.h"
100 #include "gamepal.h"
101
102 #include "multi.h"
103 #include "desc_id.h"
104 #include "cntrlcen.h"
105 #include "pcx.h"
106 #include "state.h"
107 #include "piggy.h"
108 #include "multibot.h"
109 #include "ai.h"
110 #include "robot.h"
111 #include "fix.h"
112 #include "hudmsg.h"
113
114 int VGA_current_mode;
115
116 #ifdef MWPROFILER
117 #include <profiler.h>
118 #endif
119
120 //#define TEST_TIMER    1               //if this is set, do checking on timer
121
122 #define SHOW_EXIT_PATH  1
123
124 #ifdef EDITOR
125 #include "editor/editor.h"
126 #endif
127
128 //#define _MARK_ON 1
129 #ifdef __WATCOMC__
130 #if __WATCOMC__ < 1000
131 #include <wsample.h>            //should come after inferno.h to get mark setting
132 #endif
133 #endif
134
135
136 extern void ReadControls(void);         // located in gamecntl.c
137 extern void do_final_boss_frame(void);
138
139 int     Speedtest_on = 0;
140
141 #ifndef NDEBUG
142 int     Mark_count = 0;                 // number of debugging marks set
143 int     Speedtest_start_time;
144 int     Speedtest_segnum;
145 int     Speedtest_sidenum;
146 int     Speedtest_frame_start;
147 int     Speedtest_count=0;                              //      number of times to do the debug test.
148 #endif
149
150 static fix last_timer_value=0;
151 fix ThisLevelTime=0;
152
153 #if defined(TIMER_TEST) && !defined(NDEBUG)
154 fix _timer_value,actual_last_timer_value,_last_frametime;
155 int stop_count,start_count;
156 int time_stopped,time_started;
157 #endif
158
159 int                     VR_screen_mode                  = 0;
160
161 ubyte                   VR_screen_flags = 0;            //see values in screens.h
162 ubyte                   VR_current_page = 0;
163 fix                     VR_eye_width            = F1_0;
164 int                     VR_render_mode          = VR_NONE;
165 int                     VR_low_res                      = 3;                            // Default to low res
166 int                     VR_show_hud = 1;
167 int                     VR_sensitivity     = 1;         // 0 - 2
168
169 //NEWVR
170 int                     VR_eye_offset            = 0;
171 int                     VR_eye_switch            = 0;
172 int                     VR_eye_offset_changed = 0;
173 int                     VR_use_reg_code         = 0;
174
175 grs_canvas  *VR_offscreen_buffer        = NULL;         // The offscreen data buffer
176 grs_canvas      VR_render_buffer[2];                                    //  Two offscreen buffers for left/right eyes.
177 grs_canvas      VR_render_sub_buffer[2];                        //  Two sub buffers for left/right eyes.
178 grs_canvas      VR_screen_pages[2];                                     //  Two pages of VRAM if paging is available
179 grs_canvas      VR_editor_canvas;                                               //  The canvas that the editor writes to.
180
181 //do menus work in 640x480 or 320x200?
182 //PC version sets this in main().  Mac versios is always high-res, so set to 1 here
183 int MenuHiresAvailable = 1;             //can we do highres menus?
184 int MenuHires = 1;                              //are we currently in highres menus?
185
186 int Debug_pause=0;                              //John's debugging pause system
187
188 cvar_t Cockpit_mode = { "CockpitMode", "0", 1 }; // CM_FULL_COCKPIT, see game.h for values
189
190 int Cockpit_mode_save=-1;                                       //set while in letterbox or rear view, or -1
191 int force_cockpit_redraw=0;
192
193 fix oldfov;
194 cvar_t r_framerate = {"show_fps", "0"};
195 cvar_t cg_fov = {"fov", "30"};
196
197 int PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd;
198
199 //      Toggle_var points at a variable which gets !ed on ctrl-alt-T press.
200 int     Dummy_var;
201 int     *Toggle_var = &Dummy_var;
202
203 #ifdef EDITOR
204 //flag for whether initial fade-in has been done
205 char faded_in;
206 #endif
207
208 #ifndef NDEBUG                          //these only exist if debugging
209
210 int Game_double_buffer = 1;     //double buffer by default
211 fix fixed_frametime=0;          //if non-zero, set frametime to this
212
213 #endif
214
215 int Game_suspended=0;           //if non-zero, nothing moves but player
216
217 fix     RealFrameTime;
218 fix     Auto_fire_fusion_cannon_time = 0;
219 fix     Fusion_charge = 0;
220 fix     Fusion_next_sound_time = 0;
221 fix     Fusion_last_sound_time = 0;
222
223 int Debug_spew = 1;
224 int Game_turbo_mode = 0;
225
226 int Game_mode = GM_GAME_OVER;
227
228 int     Global_laser_firing_count = 0;
229 int     Global_missile_firing_count = 0;
230
231 grs_bitmap background_bitmap;
232
233 int Game_aborted;
234
235 #define BACKGROUND_NAME "statback.pcx"
236
237 //      Function prototypes for GAME.C exclusively.
238
239 void GameLoop(int RenderFlag, int ReadControlsFlag);
240 void FireLaser(void);
241 void slide_textures(void);
242 void powerup_grab_cheat_all(void);
243
244 //      Other functions
245 extern void multi_check_for_killgoal_winner();
246 extern void RestoreGameSurfaces();
247
248 // window functions
249
250 void grow_window(void);
251 void shrink_window(void);
252
253 // text functions
254
255 void fill_background();
256
257 #ifndef RELEASE
258 void show_framerate(void);
259 void ftoa(char *string, fix f);
260 #endif
261
262 extern ubyte DefiningMarkerMessage;
263 extern char Marker_input[];
264
265 //      ==============================================================================================
266
267 extern char john_head_on;
268
269 void load_background_bitmap()
270 {
271         ubyte pal[256*3];
272         int pcx_error;
273
274         if (background_bitmap.bm_data)
275                 d_free(background_bitmap.bm_data);
276
277         background_bitmap.bm_data=NULL;
278         pcx_error = pcx_read_bitmap(john_head_on?"johnhead.pcx":BACKGROUND_NAME,&background_bitmap,BM_LINEAR,pal);
279         if (pcx_error != PCX_ERROR_NONE)
280                 Error("File %s - PCX error: %s",BACKGROUND_NAME,pcx_errormsg(pcx_error));
281         gr_remap_bitmap_good( &background_bitmap, pal, -1, -1 );
282 }
283
284
285 /* load player */
286 void game_cmd_player(int argc, char **argv)
287 {
288         if (argc < 2 || !stricmp(argv[1], "-h")) {
289                 con_printf(CON_NORMAL, "%s <name>\n", argv[0]);
290                 con_printf(CON_NORMAL, "    use the player/pilot file <name>\n");
291                 return;
292         }
293
294         strncpy(Players[Player_num].callsign, argv[1], CALLSIGN_LEN);
295
296         WriteConfigFile();              // Update lastplr
297 }
298
299
300 /* load mission */
301 void game_cmd_map(int argc, char **argv)
302 {
303         int level_num = 1;
304
305         if (argc < 2 || !stricmp(argv[1], "-h")) {
306                 con_printf(CON_NORMAL, "%s <name> [num]\n", argv[0]);
307                 con_printf(CON_NORMAL, "    start level <num> of mission <name> (defaults to level 1)\n");
308                 return;
309         }
310
311         if (!strlen(Players[Player_num].callsign)) {
312                 con_printf(CON_CRITICAL, "map: no player selected, not starting level\n");
313                 return;
314         }
315
316         load_mission_by_name(argv[1]);
317
318         if (argc > 2)
319                 level_num = atoi(argv[2]);
320
321         if (level_num == 0)
322                 level_num = 1;
323         if (level_num > Last_level)
324                 level_num = Last_level;
325         if (level_num < Last_secret_level)
326                 level_num = Last_secret_level;
327
328         StartNewGame(level_num);
329 }
330
331
332 /* send network message */
333 void game_cmd_say(int argc, char **argv)
334 {
335 #ifdef NETWORK
336         int ret, i;
337 #endif
338
339         if (argc < 2 || !stricmp(argv[1], "-h")) {
340                 con_printf(CON_NORMAL, "%s <text>\n", argv[0]);
341                 con_printf(CON_NORMAL, "    send the message <text> to the network\n");
342                 return;
343         }
344
345 #ifdef NETWORK
346         Network_message[0] = 0;
347
348         ret = snprintf(Network_message, MAX_MESSAGE_LEN, "%s", argv[1]);
349         if (ret >= MAX_MESSAGE_LEN) {
350                 con_printf(CON_CRITICAL, "say: message too long (max %d characters)\n", MAX_MESSAGE_LEN);
351                 return;
352         }
353
354         for (i = 2; i < argc; i++) {
355                 ret = snprintf(Network_message, MAX_MESSAGE_LEN, "%s %s", Network_message, argv[i]);
356                 if (ret >= MAX_MESSAGE_LEN) {
357                         con_printf(CON_CRITICAL, "say: message too long (max %d characters)\n", MAX_MESSAGE_LEN);
358                         return;
359                 }
360         }
361
362         multi_send_message_end();
363 #endif
364 }
365
366
367 /* increase window size */
368 void game_cmd_sizeup(int argc, char **argv)
369 {
370         if (argc > 1) {
371                 con_printf(CON_NORMAL, "%s\n", argv[0]);
372                 con_printf(CON_NORMAL, "    increase the game window size\n");
373                 return;
374         }
375
376         grow_window();
377 }
378
379
380 /* decrease window size */
381 void game_cmd_sizedown(int argc, char **argv)
382 {
383         if (argc > 1) {
384                 con_printf(CON_NORMAL, "%s\n", argv[0]);
385                 con_printf(CON_NORMAL, "    decrease the game window size\n");
386                 return;
387         }
388
389         shrink_window();
390 }
391
392
393 //this is called once per game
394 void init_game()
395 {
396         atexit(close_game);             //for cleanup
397
398         init_objects();
399
400         init_special_effects();
401
402         init_ai_system();
403
404         init_exploding_walls();
405
406         load_background_bitmap();
407
408         Clear_window = 2;               //      do portal only window clear.
409
410         set_detail_level_parameters(Detail_level);
411
412         /* Register cvars */
413         cvar_registervariable(&r_framerate);
414         cvar_registervariable(&cg_fov);
415         cvar_registervariable(&Player_highest_level);
416
417         /* Register cmds */
418         cmd_addcommand("player", game_cmd_player);
419         cmd_addcommand("map", game_cmd_map);
420         cmd_addcommand("say", game_cmd_say);
421         cmd_addcommand("sizeup", game_cmd_sizeup);
422         cmd_addcommand("sizedown", game_cmd_sizedown);
423 }
424
425
426 void reset_palette_add()
427 {
428         PaletteRedAdd           = 0;
429         PaletteGreenAdd = 0;
430         PaletteBlueAdd          = 0;
431         //gr_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
432 }
433
434
435 void game_show_warning(char *s)
436 {
437
438         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
439                 stop_time();
440
441         nm_messagebox( TXT_WARNING, 1, TXT_OK, s );
442
443         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
444                 start_time();
445 }
446
447
448 //these should be in gr.h
449 #define cv_w  cv_bitmap.bm_w
450 #define cv_h  cv_bitmap.bm_h
451
452 //added 3/24/99 by Owen Evans for screen res changing
453 uint32_t Game_screen_mode = 0;
454 //end added - OE
455 int Game_window_x = 0;
456 int Game_window_y = 0;
457 cvar_t Game_window_w = { "GameWidth", "0", 1 };
458 cvar_t Game_window_h = { "GameHeight", "0", 1 };
459 int max_window_w = 0;
460 int max_window_h = 0;
461
462 extern void newdemo_record_cockpit_change(int);
463
464 //initialize the various canvases on the game screen
465 //called every time the screen mode or cockpit changes
466 void init_cockpit()
467 {
468 //      int minx, maxx, miny, maxy;
469
470         //Initialize the on-screen canvases
471
472         if (Newdemo_state==ND_STATE_RECORDING) {
473                 newdemo_record_cockpit_change(Cockpit_mode.intval);
474         }
475
476         if ( VR_render_mode != VR_NONE )
477                 cvar_setint(&Cockpit_mode, CM_FULL_SCREEN);
478
479         if (!(VR_screen_flags & VRF_ALLOW_COCKPIT) &&
480                 (Cockpit_mode.intval == CM_FULL_COCKPIT ||
481                  Cockpit_mode.intval == CM_STATUS_BAR ||
482                  Cockpit_mode.intval == CM_REAR_VIEW) )
483                 cvar_setint(&Cockpit_mode, CM_FULL_SCREEN);
484
485         if ( Screen_mode == SCREEN_EDITOR )
486                 cvar_setint(&Cockpit_mode, CM_FULL_SCREEN);
487
488         gr_set_current_canvas(NULL);
489         gr_set_curfont( GAME_FONT );
490
491         switch( Cockpit_mode.intval ) {
492         case CM_FULL_COCKPIT:
493         case CM_REAR_VIEW: {
494 #if 0
495                 grs_bitmap *bm = &GameBitmaps[cockpit_bitmap[Cockpit_mode.intval+(SM_HIRES?(Num_cockpits/2):0)].index];
496
497                 PIGGY_PAGE_IN(cockpit_bitmap[Cockpit_mode.intval+(SM_HIRES?(Num_cockpits/2):0)]);
498
499                 gr_set_current_canvas(VR_offscreen_buffer);
500
501                 gr_bitmap( 0, 0, bm );
502                 bm = &VR_offscreen_buffer->cv_bitmap;
503                 bm->bm_flags = BM_FLAG_TRANSPARENT;
504                 gr_ibitblt_find_hole_size ( bm, &minx, &miny, &maxx, &maxy );
505 #endif
506
507                 if (Cockpit_mode.intval == CM_FULL_COCKPIT)
508                         game_init_render_sub_buffers(0, 0, grd_curscreen->sc_w, (grd_curscreen->sc_h*2)/3);
509                 else if (Cockpit_mode.intval == CM_REAR_VIEW)
510                         game_init_render_sub_buffers((16*grd_curscreen->sc_w)/640, (89*grd_curscreen->sc_h)/480, (604*grd_curscreen->sc_w)/640, (209*grd_curscreen->sc_h)/480);
511                 break;
512         }
513
514         case CM_FULL_SCREEN:
515
516                 max_window_h = grd_curscreen->sc_h;
517
518                 if (Game_window_h.intval > max_window_h || VR_screen_flags&VRF_ALLOW_COCKPIT)
519                         cvar_setint(&Game_window_h, max_window_h);
520
521                 if (Game_window_w.intval > max_window_w || VR_screen_flags&VRF_ALLOW_COCKPIT)
522                         cvar_setint(&Game_window_w, max_window_w);
523
524                 Game_window_x = (max_window_w - Game_window_w.intval) / 2;
525                 Game_window_y = (max_window_h - Game_window_h.intval) / 2;
526
527                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w.intval, Game_window_h.intval );
528                 break;
529
530         case CM_STATUS_BAR:
531
532                 max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(SM_HIRES?(Num_cockpits/2):0)].index].bm_h;
533
534                 if (Game_window_h.intval > max_window_h)
535                         cvar_setint(&Game_window_h, max_window_h);
536
537                 if (Game_window_w.intval > max_window_w)
538                         cvar_setint(&Game_window_w, max_window_w);
539
540                 Game_window_x = (max_window_w - Game_window_w.intval) / 2;
541                 Game_window_y = (max_window_h - Game_window_h.intval) / 2;
542
543                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w.intval, Game_window_h.intval );
544                 break;
545
546         case CM_LETTERBOX:      {
547                 int x,y,w,h;
548
549                 x = 0; w = VR_render_buffer[0].cv_bitmap.bm_w;          //VR_render_width;
550                 h = (VR_render_buffer[0].cv_bitmap.bm_h * 7) / 10;
551                 y = (VR_render_buffer[0].cv_bitmap.bm_h-h)/2;
552
553                 game_init_render_sub_buffers( x, y, w, h );
554                 break;
555                 }
556
557         }
558
559         gr_set_current_canvas(NULL);
560 }
561
562 //selects a given cockpit (or lack of one).  See types in game.h
563 void select_cockpit(int mode)
564 {
565         if (mode != Cockpit_mode.intval) { //new mode
566                 cvar_setint(&Cockpit_mode, mode);
567                 init_cockpit();
568         }
569 }
570
571 extern int last_drawn_cockpit[2];
572
573 //force cockpit redraw next time. call this if you've trashed the screen
574 void reset_cockpit()
575 {
576         force_cockpit_redraw=1;
577         last_drawn_cockpit[0] = -1;
578         last_drawn_cockpit[1] = -1;
579 }
580
581 // void HUD_clear_messages();                           //Already declared in gauges.h
582
583 //NEWVR
584 void VR_reset_params()
585 {
586         VR_eye_width = VR_SEPARATION;
587         VR_eye_offset = VR_PIXEL_SHIFT;
588         VR_eye_offset_changed = 2;
589 }
590
591 void game_init_render_sub_buffers( int x, int y, int w, int h )
592 {
593         gr_init_sub_canvas( &VR_render_sub_buffer[0], &VR_render_buffer[0], x, y, w, h );
594         gr_init_sub_canvas( &VR_render_sub_buffer[1], &VR_render_buffer[1], x, y, w, h );
595 }
596
597
598 // Sets up the canvases we will be rendering to (NORMAL VERSION)
599 void game_init_render_buffers(int screen_mode, int render_w, int render_h, int render_method, int flags )
600 {
601 //      if (vga_check_mode(screen_mode) != 0)
602 //              Error("Cannot set requested video mode");
603
604         VR_screen_mode          =       screen_mode;
605
606         VR_screen_flags =  flags;
607
608 //NEWVR
609         VR_reset_params();
610         VR_render_mode  = render_method;
611
612         cvar_setint(&Game_window_w, render_w);
613         cvar_setint(&Game_window_h, render_h);
614
615         if (VR_offscreen_buffer) {
616                 gr_free_canvas(VR_offscreen_buffer);
617         }
618
619         if ( (VR_render_mode==VR_AREA_DET) || (VR_render_mode==VR_INTERLACED ) )        {
620                 if ( render_h*2 < 200 ) {
621                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
622                 }
623                 else {
624                         VR_offscreen_buffer = gr_create_canvas( render_w, render_h*2 );
625                 }
626
627                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
628                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, render_h, render_w, render_h );
629         }
630         else {
631                 if ( render_h < 200 ) {
632                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
633                 }
634                 else {
635             VR_offscreen_buffer = gr_create_canvas( render_w, render_h );
636         }
637
638 #ifdef OGL
639                 VR_offscreen_buffer->cv_bitmap.bm_type = BM_OGL;
640 #endif
641
642                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
643                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, 0, render_w, render_h );
644         }
645
646         game_init_render_sub_buffers( 0, 0, render_w, render_h );
647 }
648
649 //called to get the screen in a mode compatible with popup menus.
650 //if we can't have popups over the game screen, switch to menu mode.
651 void set_popup_screen(void)
652 {
653         mouse_set_mode(0);
654         newmenu_show_cursor();
655         //WIN(LoadCursorWin(MOUSE_DEFAULT_CURSOR));
656
657 #ifndef OGL // always have to switch to menu mode
658         if (! (VR_screen_flags & VRF_COMPATIBLE_MENUS))
659 #endif
660         {
661                 set_screen_mode(SCREEN_MENU);           //must switch to menu mode
662         }
663 }
664
665
666 //called to change the screen mode. Parameter sm is the new mode, one of
667 //SMODE_GAME or SMODE_EDITOR. returns mode acutally set (could be other
668 //mode if cannot init requested mode)
669 int set_screen_mode(int sm)
670 {
671 #if 0 //def EDITOR
672         if ( (sm==SCREEN_MENU) && (Screen_mode==SCREEN_EDITOR) )        {
673                 gr_set_current_canvas( Canv_editor );
674                 return 1;
675         }
676 #endif
677
678         if ( Screen_mode == sm && VGA_current_mode == VR_screen_mode) {
679                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
680                 return 1;
681         }
682
683 #ifdef OGL
684         if ((Screen_mode == sm) && !((sm==SCREEN_GAME) && (grd_curscreen->sc_mode != VR_screen_mode) && (Screen_mode == SCREEN_GAME))) {
685                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
686                 ogl_set_screen_mode();
687                 return 1;
688         }
689 #endif
690
691 #ifdef EDITOR
692         Canv_editor = NULL;
693 #endif
694
695         Screen_mode = sm;
696
697         switch( Screen_mode )
698         {
699                 case SCREEN_MENU:
700                 {
701                         int menu_mode;
702
703                         MenuHires = MenuHiresAvailable;         //do highres if we can
704
705             menu_mode = MenuHires?SM(640,480):SM(320,200);
706
707                         if (VGA_current_mode != menu_mode) {
708                                 if (gr_set_mode(menu_mode))
709                                         Error("Cannot set screen mode for menu");
710                                 if (!gr_palette_faded_out)
711                                         gr_palette_load(gr_palette);
712                         }
713
714                         gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
715                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
716
717                         FontHires = FontHiresAvailable && MenuHires;
718
719                 }
720                 mouse_set_mode(0);
721                 newmenu_show_cursor();
722
723                 break;
724
725         case SCREEN_GAME:
726                 if (VGA_current_mode != VR_screen_mode) {
727                         if (gr_set_mode(VR_screen_mode))        {
728                                 Error("Cannot set desired screen mode for game!");
729                                 //we probably should do something else here, like select a standard mode
730                         }
731                         #ifdef MACINTOSH
732                         if ( Config_control_joystick.intval && (Function_mode == FMODE_GAME) )
733                                 joydefs_calibrate();
734                         #endif
735                         reset_cockpit();
736                 }
737
738                 if ( VR_render_mode == VR_NONE )
739                 {
740                         max_window_w = grd_curscreen->sc_w;
741                         max_window_h = grd_curscreen->sc_h;
742
743                         if (VR_screen_flags & VRF_ALLOW_COCKPIT) {
744                                 if (Cockpit_mode.intval == CM_STATUS_BAR)
745                                         max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(SM_HIRES?(Num_cockpits/2):0)].index].bm_h;
746                         }
747                         else if (Cockpit_mode.intval != CM_LETTERBOX)
748                                 cvar_setint(&Cockpit_mode, CM_FULL_SCREEN);
749
750                         if (Game_window_h.intval == 0 || Game_window_h.intval > max_window_h ||
751                                 Game_window_w.intval == 0 || Game_window_w.intval > max_window_w) {
752                                 cvar_setint(&Game_window_w, max_window_w);
753                                 cvar_setint(&Game_window_h, max_window_h);
754                         }
755
756                 }
757                 else
758                         cvar_setint(&Cockpit_mode, CM_FULL_SCREEN);
759
760         //      Define screen pages for game mode
761         // If we designate through screen_flags to use paging, then do so.
762                 gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
763
764                 if ( VR_screen_flags&VRF_USE_PAGING )
765                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, grd_curscreen->sc_h, grd_curscreen->sc_w, grd_curscreen->sc_h );
766                 else
767                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
768
769                 init_cockpit();
770
771                 FontHires = FontHiresAvailable && (MenuHires = SM_HIRES2);
772
773                 if ( VR_render_mode != VR_NONE )        {
774                         // for 640x480 or higher, use hires font.
775                         if (FontHiresAvailable && (grd_curscreen->sc_h > 400))
776                                 FontHires = 1;
777                         else
778                                 FontHires = 0;
779                 }
780
781                 CON_InitGFX(grd_curscreen->sc_w, grd_curscreen->sc_h / 2);
782
783                 mouse_set_mode(1);
784                 newmenu_hide_cursor();
785
786                 break;
787         #ifdef EDITOR
788         case SCREEN_EDITOR:
789                 if (grd_curscreen->sc_mode != SM(800,600))      {
790                         int gr_error;
791                         if ((gr_error=gr_set_mode(SM(800,600)))!=0) { //force into game scrren
792                                 Warning("Cannot init editor screen (error=%d)",gr_error);
793                                 return 0;
794                         }
795                 }
796                 gr_palette_load( gr_palette );
797
798                 gr_init_sub_canvas( &VR_editor_canvas, &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
799                 Canv_editor = &VR_editor_canvas;
800                 gr_init_sub_canvas( &VR_screen_pages[0], Canv_editor, 0, 0, Canv_editor->cv_w, Canv_editor->cv_h );
801                 gr_init_sub_canvas( &VR_screen_pages[1], Canv_editor, 0, 0, Canv_editor->cv_w, Canv_editor->cv_h );
802                 gr_set_current_canvas( Canv_editor );
803                 init_editor_screen();   //setup other editor stuff
804                 break;
805         #endif
806         default:
807                 Error("Invalid screen mode %d",sm);
808         }
809
810         VR_current_page = 0;
811
812                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
813
814         if ( VR_screen_flags&VRF_USE_PAGING )
815                 gr_show_canvas( &VR_screen_pages[VR_current_page] );
816 #ifdef OGL
817         ogl_set_screen_mode();
818 #endif
819
820         return 1;
821 }
822
823 int gr_toggle_fullscreen_game(void){
824 #ifdef GR_SUPPORTS_FULLSCREEN_TOGGLE
825         int i;
826         hud_message(MSGC_GAME_FEEDBACK, "toggling fullscreen mode %s",(i=gr_toggle_fullscreen())?"on":"off" );
827         //added 2000/06/19 Matthew Mueller - hack to fix "infinite toggle" problem
828         //it seems to be that the screen mode change takes long enough that the key has already sent repeat codes, or that its unpress event gets dropped, etc.  This is a somewhat ugly fix, but it works.
829 //      generic_key_handler(KEY_PADENTER,0);
830 //      generic_key_handler(KEY_ENTER, 0);
831         key_flush();
832         //end addition -MM
833         return i;
834 #else
835         hud_message(MSGC_GAME_FEEDBACK, "fullscreen toggle not supported by this target");
836         return -1;
837 #endif
838 }
839
840 int arch_toggle_fullscreen_menu(void);
841
842 int gr_toggle_fullscreen_menu(void){
843 #ifdef GR_SUPPORTS_FULLSCREEN_MENU_TOGGLE
844         int i;
845         i=arch_toggle_fullscreen_menu();
846
847 //      generic_key_handler(KEY_PADENTER,0);
848 //      generic_key_handler(KEY_ENTER, 0);
849         key_flush();
850
851         return i;
852 #else
853         return -1;
854 #endif
855 }
856
857 static int timer_paused=0;
858
859 void stop_time()
860 {
861         if (timer_paused==0) {
862                 fix time;
863                 time = timer_get_fixed_seconds();
864                 last_timer_value = time - last_timer_value;
865                 if (last_timer_value < 0) {
866                         #if defined(TIMER_TEST) && !defined(NDEBUG)
867                         Int3();         //get Matt!!!!
868                         #endif
869                         last_timer_value = 0;
870                 }
871                 #if defined(TIMER_TEST) && !defined(NDEBUG)
872                 time_stopped = time;
873                 #endif
874         }
875         timer_paused++;
876
877         #if defined(TIMER_TEST) && !defined(NDEBUG)
878         stop_count++;
879         #endif
880 }
881
882 void start_time()
883 {
884         timer_paused--;
885         Assert(timer_paused >= 0);
886         if (timer_paused==0) {
887                 fix time;
888                 time = timer_get_fixed_seconds();
889                 #if defined(TIMER_TEST) && !defined(NDEBUG)
890                 if (last_timer_value < 0)
891                         Int3();         //get Matt!!!!
892                 #endif
893                 last_timer_value = time - last_timer_value;
894                 #if defined(TIMER_TEST) && !defined(NDEBUG)
895                 time_started = time;
896                 #endif
897         }
898
899         #if defined(TIMER_TEST) && !defined(NDEBUG)
900         start_count++;
901         #endif
902 }
903
904 MAC(extern ubyte joydefs_calibrating;)
905
906 void game_flush_inputs()
907 {
908         int dx, dy, dz;
909         key_flush();
910         joy_flush();
911         mouse_flush();
912         #ifdef MACINTOSH
913         if ( (Function_mode != FMODE_MENU) && !joydefs_calibrating )            // only reset mouse when not in menu or not calibrating
914         #endif
915         mouse_get_delta( &dx, &dy, &dz ); // Read mouse
916         cmd_queue_flush();
917         memset(&Controls,0,sizeof(control_info));
918 }
919
920 void reset_time()
921 {
922         last_timer_value = timer_get_fixed_seconds();
923
924 }
925
926 #ifndef RELEASE
927 extern int Saving_movie_frames;
928 int Movie_fixed_frametime;
929 #else
930 #define Saving_movie_frames     0
931 #define Movie_fixed_frametime   0
932 #endif
933
934 //added on 8/18/98 by Victor Rachels to add maximum framerate
935 int maxfps = MAX_FPS;
936 //end this section
937
938 void calc_frame_time()
939 {
940         fix timer_value,last_frametime = FrameTime;
941
942         #if defined(TIMER_TEST) && !defined(NDEBUG)
943         _last_frametime = last_frametime;
944         #endif
945
946         timer_value = timer_get_fixed_seconds();
947         FrameTime = timer_value - last_timer_value;
948
949         while (FrameTime < f1_0 / maxfps)
950         {
951                 timer_delay(f1_0 / maxfps - FrameTime);
952                 timer_value = timer_get_fixed_seconds();
953                 FrameTime = timer_value - last_timer_value;
954         }
955
956         #if defined(TIMER_TEST) && !defined(NDEBUG)
957         _timer_value = timer_value;
958         #endif
959
960         #ifndef NDEBUG
961         if (!(((FrameTime > 0) && (FrameTime <= F1_0)) || (Function_mode == FMODE_EDITOR) || (Newdemo_state == ND_STATE_PLAYBACK))) {
962                 mprintf((1,"Bad FrameTime - value = %x\n",FrameTime));
963                 if (FrameTime == 0)
964                         Int3(); //      Call Mike or Matt or John!  Your interrupts are probably trashed!
965 //              if ( !dpmi_virtual_memory )
966 //                      Int3();         //Get MATT if hit this!
967         }
968         #endif
969
970         #if defined(TIMER_TEST) && !defined(NDEBUG)
971         actual_last_timer_value = last_timer_value;
972         #endif
973
974         if ( Game_turbo_mode )
975                 FrameTime *= 2;
976
977         // Limit frametime to be between 5 and 150 fps.
978         RealFrameTime = FrameTime;
979         if ( FrameTime < F1_0/150 ) FrameTime = F1_0/150;
980         if ( FrameTime > F1_0/5 ) FrameTime = F1_0/5;
981
982         last_timer_value = timer_value;
983
984         if (FrameTime < 0)                                              //if bogus frametime...
985                 FrameTime = last_frametime;             //...then use time from last frame
986
987         #ifndef NDEBUG
988         if (fixed_frametime) FrameTime = fixed_frametime;
989         #endif
990
991         #ifndef NDEBUG
992         // Pause here!!!
993         if ( Debug_pause )      {
994                 int c;
995                 c = 0;
996                 while( c==0 )
997                         c = key_peekkey();
998
999                 if ( c == KEY_P )       {
1000                         Debug_pause = 0;
1001                         c = key_inkey();
1002                 }
1003                 last_timer_value = timer_get_fixed_seconds();
1004         }
1005         #endif
1006
1007         #if Arcade_mode
1008                 FrameTime /= 2;
1009         #endif
1010
1011         #if defined(TIMER_TEST) && !defined(NDEBUG)
1012         stop_count = start_count = 0;
1013         #endif
1014
1015         //      Set value to determine whether homing missile can see target.
1016         //      The lower frametime is, the more likely that it can see its target.
1017         if (FrameTime <= F1_0/64)
1018                 Min_trackable_dot = MIN_TRACKABLE_DOT;  // -- 3*(F1_0 - MIN_TRACKABLE_DOT)/4 + MIN_TRACKABLE_DOT;
1019         else if (FrameTime < F1_0/32)
1020                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - 2*FrameTime;  // -- fixmul(F1_0 - MIN_TRACKABLE_DOT, F1_0-4*FrameTime) + MIN_TRACKABLE_DOT;
1021         else if (FrameTime < F1_0/4)
1022                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - F1_0/16 - FrameTime;  // -- fixmul(F1_0 - MIN_TRACKABLE_DOT, F1_0-4*FrameTime) + MIN_TRACKABLE_DOT;
1023         else
1024                 Min_trackable_dot = MIN_TRACKABLE_DOT + F1_0/64 - F1_0/8;
1025
1026 }
1027
1028 //--unused-- int Auto_flythrough=0;  //if set, start flythough automatically
1029
1030 void move_player_2_segment(segment *seg,int side)
1031 {
1032         vms_vector vp;
1033
1034         compute_segment_center(&ConsoleObject->pos,seg);
1035         compute_center_point_on_side(&vp,seg,side);
1036         vm_vec_sub2(&vp,&ConsoleObject->pos);
1037         vm_vector_2_matrix(&ConsoleObject->orient,&vp,NULL,NULL);
1038
1039         obj_relink( OBJECT_NUMBER(ConsoleObject), SEG_PTR_2_NUM(seg) );
1040
1041 }
1042
1043 #ifdef NETWORK
1044 void game_draw_time_left()
1045 {
1046         char temp_string[30];
1047         fix timevar;
1048         int i;
1049
1050         gr_set_curfont( GAME_FONT );    //GAME_FONT
1051         gr_set_fontcolor(gr_getcolor(0,63,0), -1 );
1052
1053         timevar=i2f (Netgame.PlayTimeAllowed*5*60);
1054         i=f2i(timevar-ThisLevelTime);
1055         i++;
1056
1057         sprintf( temp_string, "Time left: %d secs", i );
1058
1059         if (i>=0)
1060          gr_string(0, 32, temp_string );
1061 }
1062 #endif
1063
1064
1065 extern int Game_pause;
1066
1067 void do_photos();
1068 void level_with_floor();
1069
1070 void modex_clear_box(int x,int y,int w,int h)
1071 {
1072         grs_canvas *temp_canv,*save_canv;
1073
1074         save_canv = grd_curcanv;
1075         temp_canv = gr_create_canvas(w,h);
1076         gr_set_current_canvas(temp_canv);
1077         gr_clear_canvas(BM_XRGB(0,0,0));
1078         gr_set_current_canvas(save_canv);
1079         gr_bitmapm(x,y,&temp_canv->cv_bitmap);
1080         gr_free_canvas(temp_canv);
1081
1082 }
1083
1084 extern void modex_printf(int x,int y,char *s,grs_font *font,int color);
1085
1086 // mac routine to drop contents of screen to a pict file using copybits
1087 // save a PICT to a file
1088 #ifdef MACINTOSH
1089
1090 void SavePictScreen(int multiplayer)
1091 {
1092         OSErr err;
1093         int parid, i, count;
1094         char *pfilename, filename[50], buf[512], cwd[FILENAME_MAX];
1095         short fd;
1096         FSSpec spec;
1097         PicHandle pict_handle;
1098         static int multi_count = 0;
1099         StandardFileReply sf_reply;
1100         
1101 // dump the contents of the GameWindow into a picture using copybits
1102
1103         pict_handle = OpenPicture(&GameWindow->portRect);
1104         if (pict_handle == NULL)
1105                 return;
1106                 
1107         CopyBits(&GameWindow->portBits, &GameWindow->portBits, &GameWindow->portRect, &GameWindow->portRect, srcBic, NULL);
1108         ClosePicture();
1109
1110 // get the cwd to restore with chdir when done -- this keeps the mac world sane
1111         if (!getcwd(cwd, FILENAME_MAX))
1112                 Int3();
1113 // create the fsspec
1114
1115         sprintf(filename, "screen%d", multi_count++);
1116         pfilename = c2pstr(filename);
1117         if (!multiplayer) {
1118                 show_cursor();
1119                 StandardPutFile("\pSave PICT as:", pfilename, &sf_reply);
1120                 if (!sf_reply.sfGood)
1121                         goto end;
1122                 memcpy( &spec, &(sf_reply.sfFile), sizeof(FSSpec) );
1123                 if (sf_reply.sfReplacing)
1124                         FSpDelete(&spec);
1125                 err = FSpCreate( &spec, 'ttxt', 'PICT', smSystemScript );
1126                 if (err)
1127                         goto end;
1128         } else {
1129 //              parid = GetAppDirId();
1130                 err = FSMakeFSSpec(0, 0, pfilename, &spec);
1131                 if (err == nsvErr)
1132                         goto end;
1133                 if (err != fnfErr)
1134                         FSpDelete(&spec);
1135                 err = FSpCreate(&spec, 'ttxt', 'PICT', smSystemScript);
1136                 if (err != 0)
1137                         goto end;
1138         }
1139
1140 // write the PICT file
1141         if ( FSpOpenDF(&spec, fsRdWrPerm, &fd) )
1142                 goto end;
1143         memset(buf, 0, sizeof(buf));
1144         count = 512;
1145         if ( FSWrite(fd, &count, buf) )
1146                 goto end;
1147         count = GetHandleSize((Handle)pict_handle);
1148         HLock((Handle)pict_handle);
1149         if ( FSWrite(fd, &count, *pict_handle) ) {
1150                 FSClose(fd);
1151                 FSpDelete(&spec);
1152         }
1153
1154 end:
1155         HUnlock((Handle)pict_handle);
1156         DisposeHandle((Handle)pict_handle);
1157         FSClose(fd);
1158         hide_cursor();
1159         chdir(cwd);
1160 }
1161
1162 #endif
1163
1164 //automap_flag is now unused, since we just check if the screen we're
1165 //writing to is modex
1166 //if called from automap, current canvas is set to visible screen
1167 #ifndef OGL
1168 void save_screen_shot(int automap_flag)
1169 {
1170 #if !defined(MACINTOSH)
1171         fix t1;
1172         char message[100];
1173         grs_canvas *screen_canv=&grd_curscreen->sc_canvas;
1174         grs_font *save_font;
1175         static int savenum=0;
1176         static int stereo_savenum=0;
1177         grs_canvas *temp_canv,*temp_canv2,*save_canv;
1178         char savename[FILENAME_LEN],savename2[FILENAME_LEN];
1179         ubyte pal[768];
1180         int w,h,aw,x,y;
1181         int modex_flag;
1182         int stereo=0;
1183
1184         temp_canv2=NULL;
1185
1186 //      // Can't do screen shots in VR modes.
1187 //      if ( VR_render_mode != VR_NONE )
1188 //              return;
1189
1190         stop_time();
1191
1192         save_canv = grd_curcanv;
1193
1194         if ( VR_render_mode != VR_NONE && !automap_flag && Function_mode==FMODE_GAME && Screen_mode==SCREEN_GAME)
1195                 stereo = 1;
1196
1197         if ( stereo ) {
1198                 temp_canv = gr_create_canvas(VR_render_buffer[0].cv_bitmap.bm_w,VR_render_buffer[0].cv_bitmap.bm_h);
1199                 gr_set_current_canvas(temp_canv);
1200                 gr_ubitmap(0,0,&VR_render_buffer[0].cv_bitmap);
1201
1202                 temp_canv2 = gr_create_canvas(VR_render_buffer[1].cv_bitmap.bm_w,VR_render_buffer[1].cv_bitmap.bm_h);
1203                 gr_set_current_canvas(temp_canv2);
1204                 gr_ubitmap(0,0,&VR_render_buffer[1].cv_bitmap);
1205         }
1206         else {
1207                 temp_canv = gr_create_canvas(screen_canv->cv_bitmap.bm_w,screen_canv->cv_bitmap.bm_h);
1208                 gr_set_current_canvas(temp_canv);
1209                 gr_ubitmap(0,0,&screen_canv->cv_bitmap);
1210         }
1211
1212         gr_set_current_canvas(save_canv);
1213
1214         if ( savenum > 99 ) savenum = 0;
1215         if ( stereo_savenum > 99 ) stereo_savenum = 0;
1216
1217         if ( stereo ) {
1218                 sprintf(savename,"left%02d.pcx",stereo_savenum);
1219                 sprintf(savename2,"right%02d.pcx",stereo_savenum);
1220                 if (VR_eye_switch) {char t[FILENAME_LEN]; strcpy(t,savename); strcpy(savename,savename2); strcpy(savename2,t);}
1221                 stereo_savenum++;
1222                 sprintf( message, "%s '%s' & '%s'", TXT_DUMPING_SCREEN, savename, savename2 );
1223         }
1224         else {
1225                 sprintf(savename,"screen%02d.pcx",savenum++);
1226                 sprintf( message, "%s '%s'", TXT_DUMPING_SCREEN, savename );
1227         }
1228
1229         if (!automap_flag)              //if from automap, curcanv is already visible canv
1230                 gr_set_current_canvas(NULL);
1231         modex_flag = (grd_curcanv->cv_bitmap.bm_type==BM_MODEX);
1232         if (!automap_flag && modex_flag)
1233                 gr_set_current_canvas(&VR_screen_pages[VR_current_page]);
1234
1235         save_font = grd_curcanv->cv_font;
1236         gr_set_curfont(GAME_FONT);
1237         gr_set_fontcolor(gr_find_closest_color_current(0,31,0),-1);
1238         gr_get_string_size(message,&w,&h,&aw);
1239
1240         if (modex_flag)
1241                 h *= 2;
1242
1243         //I changed how these coords were calculated for the high-res automap. -MT
1244         //x = (VR_screen_pages[VR_current_page].cv_w-w)/2;
1245         //y = (VR_screen_pages[VR_current_page].cv_h-h)/2;
1246         x = (grd_curcanv->cv_w-w)/2;
1247         y = (grd_curcanv->cv_h-h)/2;
1248
1249         if (modex_flag) {
1250                 modex_clear_box(x-2,y-2,w+4,h+4);
1251                 modex_printf(x, y, message,GAME_FONT,gr_find_closest_color_current(0,31,0));
1252         } else {
1253                 gr_setcolor(gr_find_closest_color_current(0,0,0));
1254                 gr_rect(x-2,y-2,x+w+2,y+h+2);
1255                 gr_printf(x,y,message);
1256                 gr_set_curfont(save_font);
1257         }
1258         t1 = timer_get_fixed_seconds() + F1_0;
1259
1260         gr_palette_read(pal);           //get actual palette from the hardware
1261         pcx_write_bitmap(savename,&temp_canv->cv_bitmap,pal);
1262         if ( stereo )
1263                 pcx_write_bitmap(savename2,&temp_canv2->cv_bitmap,pal);
1264
1265         while ( timer_get_fixed_seconds() < t1 );               // Wait so that messag stays up at least 1 second.
1266
1267         gr_set_current_canvas(screen_canv);
1268
1269         if (grd_curcanv->cv_bitmap.bm_type!=BM_MODEX && !stereo)
1270                 gr_ubitmap(0,0,&temp_canv->cv_bitmap);
1271
1272         gr_free_canvas(temp_canv);
1273         if ( stereo )
1274                 gr_free_canvas(temp_canv2);
1275
1276         gr_set_current_canvas(save_canv);
1277         key_flush();
1278         start_time();
1279         
1280 #else
1281
1282         grs_canvas *screen_canv = &grd_curscreen->sc_canvas;
1283         grs_canvas *temp_canv, *save_canv;
1284         
1285         // Can't do screen shots in VR modes.
1286         if ( VR_render_mode != VR_NONE )
1287                 return;
1288
1289         stop_time();
1290
1291         save_canv = grd_curcanv;        
1292         temp_canv = gr_create_canvas( screen_canv->cv_bitmap.bm_w, screen_canv->cv_bitmap.bm_h );
1293         if (!temp_canv)
1294                 goto shot_done;
1295         gr_set_current_canvas( temp_canv );
1296         gr_ubitmap( 0, 0, &screen_canv->cv_bitmap );
1297         gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
1298
1299         show_cursor();
1300         key_close();
1301         if (Game_mode & GM_MULTI)
1302                 SavePictScreen(1);
1303         else
1304                 SavePictScreen(0);
1305         key_init();
1306         hide_cursor();
1307
1308         gr_set_current_canvas(screen_canv);
1309         
1310 //      if (!automap_flag)
1311                 gr_ubitmap( 0, 0, &temp_canv->cv_bitmap);
1312
1313         gr_free_canvas(temp_canv);
1314 shot_done:
1315         gr_set_current_canvas(save_canv);
1316         key_flush();
1317         start_time();
1318         #endif
1319 }
1320
1321 #endif
1322
1323 //initialize flying
1324 void fly_init(object *obj)
1325 {
1326         obj->control_type = CT_FLYING;
1327         obj->movement_type = MT_PHYSICS;
1328
1329         vm_vec_zero(&obj->mtype.phys_info.velocity);
1330         vm_vec_zero(&obj->mtype.phys_info.thrust);
1331         vm_vec_zero(&obj->mtype.phys_info.rotvel);
1332         vm_vec_zero(&obj->mtype.phys_info.rotthrust);
1333 }
1334
1335 //void morph_test(), morph_step();
1336
1337
1338 //      ------------------------------------------------------------------------------------
1339
1340 void test_anim_states();
1341
1342 #include "fvi.h"
1343
1344 //put up the help message
1345 void do_show_help()
1346 {
1347         show_help();
1348 }
1349
1350
1351 extern int been_in_editor;
1352
1353 //      ------------------------------------------------------------------------------------
1354 void do_cloak_stuff(void)
1355 {
1356         int i;
1357         for (i = 0; i < N_players; i++)
1358                 if (Players[i].flags & PLAYER_FLAGS_CLOAKED) {
1359                         // mprintf(0, "Cloak time left: %7.3f\n", f2fl(CLOAK_TIME_MAX - (GameTime - Players[Player_num].cloak_time)));
1360                         if (GameTime - Players[i].cloak_time > CLOAK_TIME_MAX) {
1361                                 Players[i].flags &= ~PLAYER_FLAGS_CLOAKED;
1362                                 if (i == Player_num) {
1363                                         digi_play_sample( SOUND_CLOAK_OFF, F1_0);
1364                                         #ifdef NETWORK
1365                                         if (Game_mode & GM_MULTI)
1366                                                 multi_send_play_sound(SOUND_CLOAK_OFF, F1_0);
1367                                         maybe_drop_net_powerup(POW_CLOAK);
1368                                         multi_send_decloak(); // For demo recording
1369                                         #endif
1370 //                                      mprintf((0, " --- You have been DE-CLOAKED! ---\n"));
1371                                 }
1372                         }
1373                 }
1374 }
1375
1376 int FakingInvul=0;
1377
1378 //      ------------------------------------------------------------------------------------
1379 void do_invulnerable_stuff(void)
1380 {
1381         if (Players[Player_num].flags & PLAYER_FLAGS_INVULNERABLE) {
1382                 if (GameTime - Players[Player_num].invulnerable_time > INVULNERABLE_TIME_MAX) {
1383                         Players[Player_num].flags ^= PLAYER_FLAGS_INVULNERABLE;
1384                         if (FakingInvul==0)
1385                         {
1386                                 digi_play_sample( SOUND_INVULNERABILITY_OFF, F1_0);
1387                                 #ifdef NETWORK
1388                                 if (Game_mode & GM_MULTI)
1389                                 {
1390                                         multi_send_play_sound(SOUND_INVULNERABILITY_OFF, F1_0);
1391                                         maybe_drop_net_powerup(POW_INVULNERABILITY);
1392                                 }
1393                                 #endif
1394                                 mprintf((0, " --- You have been DE-INVULNERABLEIZED! ---\n"));
1395                         }
1396                         FakingInvul=0;
1397                 }
1398         }
1399 }
1400
1401 ubyte   Last_afterburner_state = 0;
1402 fix Last_afterburner_charge = 0;
1403
1404 #define AFTERBURNER_LOOP_START  ((digi_sample_rate==SAMPLE_RATE_22K)?32027:(32027/2))           //20098
1405 #define AFTERBURNER_LOOP_END            ((digi_sample_rate==SAMPLE_RATE_22K)?48452:(48452/2))           //25776
1406
1407 int     Ab_scale = 4;
1408
1409 //@@//  ------------------------------------------------------------------------------------
1410 //@@void afterburner_shake(void)
1411 //@@{
1412 //@@    int     rx, rz;
1413 //@@
1414 //@@    rx = (Ab_scale * fixmul(d_rand() - 16384, F1_0/8 + (((GameTime + 0x4000)*4) & 0x3fff)))/16;
1415 //@@    rz = (Ab_scale * fixmul(d_rand() - 16384, F1_0/2 + ((GameTime*4) & 0xffff)))/16;
1416 //@@
1417 //@@    // -- mprintf((0, "AB: %8x %8x\n", rx, rz));
1418 //@@    ConsoleObject->mtype.phys_info.rotvel.x += rx;
1419 //@@    ConsoleObject->mtype.phys_info.rotvel.z += rz;
1420 //@@
1421 //@@}
1422
1423 //      ------------------------------------------------------------------------------------
1424 #ifdef NETWORK
1425 extern void multi_send_sound_function (char,char);
1426 #endif
1427
1428 void do_afterburner_stuff(void)
1429 {
1430    if (!(Players[Player_num].flags & PLAYER_FLAGS_AFTERBURNER))
1431                 Afterburner_charge=0;
1432
1433         if (Endlevel_sequence || Player_is_dead)
1434                 {
1435                  digi_kill_sound_linked_to_object( Players[Player_num].objnum);
1436 #ifdef NETWORK
1437                  multi_send_sound_function (0,0);
1438 #endif
1439                 }
1440
1441         if ((Controls.state[afterburner] != Last_afterburner_state && Last_afterburner_charge) || (Last_afterburner_state && Last_afterburner_charge && !Afterburner_charge)) {
1442
1443                 if (Afterburner_charge && Controls.state[afterburner] && (Players[Player_num].flags & PLAYER_FLAGS_AFTERBURNER)) {
1444                         digi_link_sound_to_object3( SOUND_AFTERBURNER_IGNITE, Players[Player_num].objnum, 1, F1_0, i2f(256), AFTERBURNER_LOOP_START, AFTERBURNER_LOOP_END );
1445 #ifdef NETWORK
1446                         if (Game_mode & GM_MULTI)
1447                                 multi_send_sound_function (3,SOUND_AFTERBURNER_IGNITE);
1448 #endif
1449                 } else {
1450                         digi_kill_sound_linked_to_object( Players[Player_num].objnum);
1451                         digi_link_sound_to_object2( SOUND_AFTERBURNER_PLAY, Players[Player_num].objnum, 0, F1_0, i2f(256));
1452 #ifdef NETWORK
1453                         if (Game_mode & GM_MULTI)
1454                                 multi_send_sound_function (0,0);
1455 #endif
1456                         mprintf((0,"Killing afterburner sound\n"));
1457                 }
1458         }
1459
1460         //@@if (Controls.state[afterburner] && Afterburner_charge)
1461         //@@    afterburner_shake();
1462
1463         Last_afterburner_state = Controls.state[afterburner];
1464         Last_afterburner_charge = Afterburner_charge;
1465 }
1466
1467 // -- //        ------------------------------------------------------------------------------------
1468 // -- //        if energy < F1_0/2, recharge up to F1_0/2
1469 // -- void recharge_energy_frame(void)
1470 // -- {
1471 // --   if (Players[Player_num].energy < Weapon_info[0].energy_usage) {
1472 // --           Players[Player_num].energy += FrameTime/4;
1473 // --
1474 // --           if (Players[Player_num].energy > Weapon_info[0].energy_usage)
1475 // --                   Players[Player_num].energy = Weapon_info[0].energy_usage;
1476 // --   }
1477 // -- }
1478
1479 //      Amount to diminish guns towards normal, per second.
1480 #define DIMINISH_RATE   16              //      gots to be a power of 2, else change the code in diminish_palette_towards_normal
1481
1482 extern fix Flash_effect;
1483
1484  //adds to rgb values for palette flash
1485 void PALETTE_FLASH_ADD(int _dr,int _dg,int _db)
1486 {
1487         int     maxval;
1488
1489         PaletteRedAdd += _dr;
1490         PaletteGreenAdd += _dg;
1491         PaletteBlueAdd += _db;
1492
1493         // -- mprintf((0, "Palette add: %3i %3i %3i\n", PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd));
1494
1495         if (Flash_effect)
1496                 maxval = 60;
1497         else
1498                 maxval = MAX_PALETTE_ADD;
1499
1500         if (PaletteRedAdd > maxval)
1501                 PaletteRedAdd = maxval;
1502
1503         if (PaletteGreenAdd > maxval)
1504                 PaletteGreenAdd = maxval;
1505
1506         if (PaletteBlueAdd > maxval)
1507                 PaletteBlueAdd = maxval;
1508
1509         if (PaletteRedAdd < -maxval)
1510                 PaletteRedAdd = -maxval;
1511
1512         if (PaletteGreenAdd < -maxval)
1513                 PaletteGreenAdd = -maxval;
1514
1515         if (PaletteBlueAdd < -maxval)
1516                 PaletteBlueAdd = -maxval;
1517 }
1518
1519 fix     Time_flash_last_played;
1520
1521
1522 void game_palette_step_up( int r, int g, int b );
1523 //      ------------------------------------------------------------------------------------
1524 //      Diminish palette effects towards normal.
1525 void diminish_palette_towards_normal(void)
1526 {
1527         int     dec_amount = 0;
1528
1529         //      Diminish at DIMINISH_RATE units/second.
1530         //      For frame rates > DIMINISH_RATE Hz, use randomness to achieve this.
1531         if (FrameTime < F1_0/DIMINISH_RATE) {
1532                 if (d_rand() < FrameTime*DIMINISH_RATE/2)       //      Note: d_rand() is in 0..32767, and 8 Hz means decrement every frame
1533                         dec_amount = 1;
1534         } else {
1535                 dec_amount = f2i(FrameTime*DIMINISH_RATE);              // one second = DIMINISH_RATE counts
1536                 if (dec_amount == 0)
1537                         dec_amount++;                                           // make sure we decrement by something
1538         }
1539
1540         if (Flash_effect) {
1541                 int     force_do = 0;
1542
1543                 //      Part of hack system to force update of palette after exiting a menu.
1544                 if (Time_flash_last_played) {
1545                         force_do = 1;
1546                         PaletteRedAdd ^= 1;     //      Very Tricky!  In gr_palette_step_up, if all stepups same as last time, won't do anything!
1547                 }
1548
1549                 if ((Time_flash_last_played + F1_0/8 < GameTime) || (Time_flash_last_played > GameTime)) {
1550                         digi_play_sample( SOUND_CLOAK_OFF, Flash_effect/4);
1551                         Time_flash_last_played = GameTime;
1552                 }
1553
1554                 Flash_effect -= FrameTime;
1555                 if (Flash_effect < 0)
1556                         Flash_effect = 0;
1557
1558                 if (force_do || (d_rand() > 4096 )) {
1559         if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1560                 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1561
1562                         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1563
1564                         return;
1565                 }
1566
1567         }
1568
1569         if (PaletteRedAdd > 0 ) { PaletteRedAdd -= dec_amount; if (PaletteRedAdd < 0 ) PaletteRedAdd = 0; }
1570         if (PaletteRedAdd < 0 ) { PaletteRedAdd += dec_amount; if (PaletteRedAdd > 0 ) PaletteRedAdd = 0; }
1571
1572         if (PaletteGreenAdd > 0 ) { PaletteGreenAdd -= dec_amount; if (PaletteGreenAdd < 0 ) PaletteGreenAdd = 0; }
1573         if (PaletteGreenAdd < 0 ) { PaletteGreenAdd += dec_amount; if (PaletteGreenAdd > 0 ) PaletteGreenAdd = 0; }
1574
1575         if (PaletteBlueAdd > 0 ) { PaletteBlueAdd -= dec_amount; if (PaletteBlueAdd < 0 ) PaletteBlueAdd = 0; }
1576         if (PaletteBlueAdd < 0 ) { PaletteBlueAdd += dec_amount; if (PaletteBlueAdd > 0 ) PaletteBlueAdd = 0; }
1577
1578         if ( (Newdemo_state==ND_STATE_RECORDING) && (PaletteRedAdd || PaletteGreenAdd || PaletteBlueAdd) )
1579                 newdemo_record_palette_effect(PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1580
1581         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1582
1583         //mprintf(0, "%2i %2i %2i\n", PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd);
1584 }
1585
1586 int     Redsave, Bluesave, Greensave;
1587
1588 void palette_save(void)
1589 {
1590         Redsave = PaletteRedAdd; Bluesave = PaletteBlueAdd; Greensave = PaletteGreenAdd;
1591 }
1592
1593 extern void gr_palette_step_up_vr( int r, int g, int b, int white, int black );
1594
1595 void game_palette_step_up( int r, int g, int b )
1596 {
1597         if ( VR_use_reg_code )  {
1598 //              gr_palette_step_up_vr( r, g, b, VR_WHITE_INDEX, VR_BLACK_INDEX );
1599         } else {
1600                 gr_palette_step_up( r, g, b );
1601         }
1602 }
1603
1604 void palette_restore(void)
1605 {
1606         PaletteRedAdd = Redsave; PaletteBlueAdd = Bluesave; PaletteGreenAdd = Greensave;
1607         game_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
1608
1609         //      Forces flash effect to fixup palette next frame.
1610         Time_flash_last_played = 0;
1611 }
1612
1613 extern void dead_player_frame(void);
1614
1615
1616 //      --------------------------------------------------------------------------------------------------
1617 int allowed_to_fire_laser(void)
1618 {
1619         if (Player_is_dead) {
1620                 Global_missile_firing_count = 0;
1621                 return 0;
1622         }
1623
1624         //      Make sure enough time has elapsed to fire laser, but if it looks like it will
1625         //      be a long while before laser can be fired, then there must be some mistake!
1626         if (Next_laser_fire_time > GameTime)
1627                 if (Next_laser_fire_time < GameTime + 2*F1_0)
1628                         return 0;
1629
1630         return 1;
1631 }
1632
1633 fix     Next_flare_fire_time = 0;
1634 #define FLARE_BIG_DELAY (F1_0*2)
1635
1636 int allowed_to_fire_flare(void)
1637 {
1638         if (Next_flare_fire_time > GameTime)
1639                 if (Next_flare_fire_time < GameTime + FLARE_BIG_DELAY)  //      In case time is bogus, never wait > 1 second.
1640                         return 0;
1641
1642         if (Players[Player_num].energy >= Weapon_info[FLARE_ID].energy_usage)
1643                 Next_flare_fire_time = GameTime + F1_0/4;
1644         else
1645                 Next_flare_fire_time = GameTime + FLARE_BIG_DELAY;
1646
1647         return 1;
1648 }
1649
1650 int allowed_to_fire_missile(void)
1651 {
1652 // mprintf(0, "Next fire = %7.3f, Cur time = %7.3f\n", f2fl(Next_missile_fire_time), f2fl(GameTime));
1653         //      Make sure enough time has elapsed to fire missile, but if it looks like it will
1654         //      be a long while before missile can be fired, then there must be some mistake!
1655         if (Next_missile_fire_time > GameTime)
1656                 if (Next_missile_fire_time < GameTime + 5*F1_0)
1657                         return 0;
1658
1659         return 1;
1660 }
1661
1662 void full_palette_save(void)
1663 {
1664         palette_save();
1665         apply_modified_palette();
1666         reset_palette_add();
1667         gr_palette_load( gr_palette );
1668 }
1669
1670 extern int Death_sequence_aborted;
1671 extern int newmenu_dotiny2( char * title, char * subtitle, int nitems, newmenu_item * item, void (*subfunction)(int nitems,newmenu_item * items, int * last_key, int citem) );
1672
1673 void show_help()
1674 {
1675         int nitems = 0;
1676         newmenu_item m[25];
1677 #ifdef MACINTOSH
1678         char pixel_double_help[64];
1679 #endif
1680 #ifdef __APPLE__
1681         char command_help[64], save_help[64], restore_help[64];
1682 #endif
1683
1684         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ESC;
1685 #ifndef __APPLE__
1686         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ALT_F2;
1687         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_ALT_F3;
1688 #else
1689         sprintf(save_help, "OPT-F2 (%c-s)\t Save Game", 133);
1690         sprintf(restore_help, "OPT-F3 (%c-o)\t Load Game", 133);
1691         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = save_help;
1692         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = restore_help;
1693 #endif
1694         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F2;
1695         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F3;
1696         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F4;
1697         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_F5;
1698         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "F6\t Fast Save";
1699 #ifndef __APPLE__
1700         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_PAUSE;
1701 #else
1702         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Pause (F15)\t  Pause";
1703 #endif
1704         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_MINUSPLUS;
1705 #ifndef __APPLE__
1706         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_PRTSCN;
1707 #else
1708         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "printscrn (F13)\t  save screen shot";
1709 #endif
1710         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_1TO5;
1711         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = TXT_HELP_6TO10;
1712         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F1\t  Cycle left window";
1713         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F2\t  Cycle right window";
1714         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F4\t  GuideBot menu";
1715 #ifndef __APPLE__
1716         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Alt-Shift-F4\t  Rename GuideBot";
1717 #else
1718         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Opt-Shift-F4\t  Rename GuideBot";
1719 #endif
1720         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F5\t  Drop primary";
1721         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F6\t  Drop secondary";
1722         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-F7\t  Calibrate joystick";
1723         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "Shift-number\t  GuideBot commands";
1724 #ifdef MACINTOSH
1725         sprintf(pixel_double_help, "%c-D\t  Toggle Pixel Double Mode", 133);
1726         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = pixel_double_help;
1727 #endif
1728 #ifdef __APPLE__
1729         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = "";
1730         sprintf(command_help, "(Use %c-# for F#. i.e. %c-1 for F1)", 133, 133);
1731         m[nitems].type = NM_TYPE_TEXT; m[nitems++].text = command_help;
1732 #endif
1733
1734         full_palette_save();
1735
1736         newmenu_dotiny2( NULL, TXT_KEYS, nitems, m, NULL );
1737
1738         palette_restore();
1739 }
1740
1741 //temp function until Matt cleans up game sequencing
1742 extern void temp_reset_stuff_on_level();
1743
1744 fix Rear_view_leave_time = 0x1000;   // how long until we decide key is down (Used to be 0x4000)
1745
1746 //deal with rear view - switch it on, or off, or whatever
1747 void check_rear_view()
1748 {
1749         static int leave_mode;
1750         static fix entry_time;
1751
1752         if ( Controls.count[rear_view] ) { // key/button has gone down
1753
1754                 if (Rear_view) {
1755                         Rear_view = 0;
1756                         if (Cockpit_mode.intval == CM_REAR_VIEW) {
1757                                 select_cockpit(Cockpit_mode_save);
1758                                 Cockpit_mode_save = -1;
1759                         }
1760                         if (Newdemo_state == ND_STATE_RECORDING)
1761                                 newdemo_record_restore_rearview();
1762                 }
1763                 else {
1764                         Rear_view = 1;
1765                         if (Rear_view_leave_time <= 0)
1766                         {
1767                                 leave_mode = 1; // set leave mode on here otherwise we will always have to hold for at least 1 frame to get leave_mode on
1768                         }
1769                         else
1770                         {
1771                                 leave_mode = 0; // means wait for another key
1772                                 entry_time = timer_get_fixed_seconds();
1773                         }
1774                         if (Cockpit_mode.intval == CM_FULL_COCKPIT) {
1775                                 Cockpit_mode_save = Cockpit_mode.intval;
1776                                 select_cockpit(CM_REAR_VIEW);
1777                         }
1778                         if (Newdemo_state == ND_STATE_RECORDING)
1779                                 newdemo_record_rearview();
1780                 }
1781         }
1782         else
1783                 if (Controls.state[rear_view]) {
1784
1785                         if (leave_mode == 0 && (timer_get_fixed_seconds() - entry_time) > Rear_view_leave_time)
1786                                 leave_mode = 1;
1787                 }
1788                 else {
1789
1790                         //@@if (leave_mode==1 && Cockpit_mode.intval == CM_REAR_VIEW) {
1791
1792                         if (leave_mode==1 && Rear_view) {
1793                                 Rear_view = 0;
1794                                 if (Cockpit_mode.intval == CM_REAR_VIEW) {
1795                                         select_cockpit(Cockpit_mode_save);
1796                                         Cockpit_mode_save = -1;
1797                                 }
1798                                 if (Newdemo_state == ND_STATE_RECORDING)
1799                                         newdemo_record_restore_rearview();
1800                         }
1801                 }
1802 }
1803
1804 void reset_rear_view(void)
1805 {
1806         if (Rear_view) {
1807                 if (Newdemo_state == ND_STATE_RECORDING)
1808                         newdemo_record_restore_rearview();
1809         }
1810
1811         Rear_view = 0;
1812
1813         if (!(Cockpit_mode.intval == CM_FULL_COCKPIT || Cockpit_mode.intval == CM_STATUS_BAR || Cockpit_mode.intval == CM_FULL_SCREEN)) {
1814                 if (!(Cockpit_mode_save == CM_FULL_COCKPIT || Cockpit_mode_save == CM_STATUS_BAR || Cockpit_mode_save == CM_FULL_SCREEN))
1815                         Cockpit_mode_save = CM_FULL_COCKPIT;
1816                 select_cockpit(Cockpit_mode_save);
1817                 Cockpit_mode_save       = -1;
1818         }
1819
1820 }
1821
1822 int Automap_flag;
1823 int Config_menu_flag;
1824
1825 jmp_buf LeaveGame;
1826
1827 int gr_renderstats = 0;
1828 // need to define "cheat" for renderstats
1829 int gr_badtexture = 0;
1830 // need to define "cheat" for badtexture
1831
1832 int Cheats_enabled=0;
1833
1834 extern int Laser_rapid_fire;
1835 extern void do_lunacy_on(), do_lunacy_off();
1836
1837 extern int Physics_cheat_flag,Robots_kill_robots_cheat;
1838 extern char BounceCheat,HomingCheat,OldHomingState[20];
1839 extern char AcidCheatOn,old_IntMethod, Monster_mode;
1840 extern int Buddy_dude_cheat;
1841
1842 //turns off active cheats
1843 void turn_cheats_off()
1844 {
1845         int i;
1846
1847         if (HomingCheat)
1848                 for (i=0;i<20;i++)
1849                         Weapon_info[i].homing_flag=OldHomingState[i];
1850
1851         if (AcidCheatOn)
1852         {
1853                 AcidCheatOn=0;
1854                 Interpolation_method=old_IntMethod;
1855         }
1856
1857         Buddy_dude_cheat = 0;
1858         BounceCheat=0;
1859    HomingCheat=0;
1860         do_lunacy_off();
1861         Laser_rapid_fire = 0;
1862         Physics_cheat_flag = 0;
1863         Monster_mode = 0;
1864         Robots_kill_robots_cheat=0;
1865         Robot_firing_enabled = 1;
1866 }
1867
1868 //turns off all cheats & resets cheater flag    
1869 void game_disable_cheats()
1870 {
1871         turn_cheats_off();
1872         Cheats_enabled=0;
1873 }
1874
1875
1876 //      game_setup()
1877 // ----------------------------------------------------------------------------
1878
1879 void game_setup(void)
1880 {
1881         //@@int demo_playing=0;
1882         //@@int multi_game=0;
1883
1884         do_lunacy_on();         //      Copy values for insane into copy buffer in ai.c
1885         do_lunacy_off();                //      Restore true insane mode.
1886
1887         Game_aborted = 0;
1888         last_drawn_cockpit[0] = -1;                             // Force cockpit to redraw next time a frame renders.
1889         last_drawn_cockpit[1] = -1;                             // Force cockpit to redraw next time a frame renders.
1890         Endlevel_sequence = 0;
1891
1892         //@@if ( Newdemo_state == ND_STATE_PLAYBACK )
1893         //@@    demo_playing = 1;
1894         //@@if ( Game_mode & GM_MULTI )
1895         //@@    multi_game = 1;
1896
1897         set_screen_mode(SCREEN_GAME);
1898         reset_palette_add();
1899
1900         set_warn_func(game_show_warning);
1901
1902         init_cockpit();
1903         init_gauges();
1904         //digi_init_sounds();
1905
1906         //keyd_repeat = 0;                // Don't allow repeat in game
1907         keyd_repeat = 1;                // Do allow repeat in game
1908
1909 #ifdef __MSDOS__
1910         //_MARK_("start of game");
1911 #endif
1912
1913         #ifdef EDITOR
1914                 if (Segments[ConsoleObject->segnum].segnum == -1)      //segment no longer exists
1915                         obj_relink( OBJECT_NUMBER(ConsoleObject), SEG_PTR_2_NUM(Cursegp) );
1916
1917                 if (!check_obj_seg(ConsoleObject))
1918                         move_player_2_segment(Cursegp,Curside);
1919         #endif
1920
1921         Viewer = ConsoleObject;
1922         fly_init(ConsoleObject);
1923
1924         Game_suspended = 0;
1925
1926         reset_time();
1927         FrameTime = 0;                  //make first frame zero
1928
1929         #ifdef EDITOR
1930         if (Current_level_num == 0) {                   //not a real level
1931                 init_player_stats_game();
1932                 init_ai_objects();
1933         }
1934         #endif
1935
1936         fix_object_segs();
1937
1938         game_flush_inputs();
1939
1940 }
1941
1942
1943 #ifdef NETWORK
1944 extern char IWasKicked;
1945 #endif
1946
1947
1948 //      ------------------------------------------------------------------------------------
1949 //this function is the game.  called when game mode selected.  runs until
1950 //editor mode or exit selected
1951 void game()
1952 {
1953         game_setup();                                                           // Replaces what was here earlier.
1954                                                                                                         // Good for Windows Sake.
1955
1956 #ifdef MWPROFILE
1957         ProfilerSetStatus(1);
1958 #endif
1959
1960         if ( setjmp(LeaveGame)==0 )     {
1961                 while (1) {
1962                         int player_shields;
1963
1964                         // GAME LOOP!
1965                         Automap_flag = 0;
1966                         Config_menu_flag = 0;
1967
1968                         if ( ConsoleObject != &Objects[Players[Player_num].objnum] )
1969                           {
1970                             mprintf ((0,"Player_num=%d objnum=%d",Player_num,Players[Player_num].objnum));
1971                             //Assert( ConsoleObject == &Objects[Players[Player_num].objnum] );
1972                           }
1973
1974                         player_shields = Players[Player_num].shields;
1975
1976                         ExtGameStatus=GAMESTAT_RUNNING;
1977                         GameLoop( 1, 1 );               // Do game loop with rendering and reading controls.
1978
1979                         if (oldfov != cg_fov.value)
1980                         {
1981                                 oldfov = cg_fov.value;
1982                                 if (cg_fov.value < F1_0)
1983                                         cvar_setint(&cg_fov, 1);
1984                                 if (cg_fov.value > 170 * F1_0)
1985                                         cvar_setint(&cg_fov, 170);
1986                                 Render_zoom = cg_fov.value * M_PI / 180; // convert to radians
1987                                 con_printf(CON_VERBOSE, "FOV set to %f (0x%08x)\n", f2fl(cg_fov.value), Render_zoom);
1988                         }
1989
1990                         //if the player is taking damage, give up guided missile control
1991                         if (Players[Player_num].shields != player_shields)
1992                                 release_guided_missile(Player_num);
1993
1994                         //see if redbook song needs to be restarted
1995                         songs_check_redbook_repeat();   // Handle RedBook Audio Repeating.
1996
1997                         if (Config_menu_flag)   {
1998                                 if (!(Game_mode&GM_MULTI)) {palette_save(); reset_palette_add();        apply_modified_palette(); gr_palette_load( gr_palette ); }
1999                                 do_options_menu();
2000                                 if (!(Game_mode&GM_MULTI)) palette_restore();
2001                         }
2002
2003                         if (Automap_flag) {
2004                                 int save_w = Game_window_w.intval, save_h = Game_window_h.intval;
2005                                 do_automap(0);
2006                                 Screen_mode=-1; set_screen_mode(SCREEN_GAME);
2007                                 cvar_setint(&Game_window_w, save_w);
2008                                 cvar_setint(&Game_window_h, save_h);
2009                                 init_cockpit();
2010                                 last_drawn_cockpit[0] = -1;
2011                                 last_drawn_cockpit[1] = -1;
2012                         }
2013
2014                         if ( (Function_mode != FMODE_GAME) && Auto_demo && (Newdemo_state != ND_STATE_NORMAL) ) {
2015                                 int choice, fmode;
2016                                 fmode = Function_mode;
2017                                 Function_mode = FMODE_GAME;
2018                                 palette_save();
2019                                 apply_modified_palette();
2020                                 reset_palette_add();
2021                                 gr_palette_load( gr_palette );
2022                                 choice=nm_messagebox( NULL, 2, TXT_YES, TXT_NO, TXT_ABORT_AUTODEMO );
2023                                 palette_restore();
2024                                 Function_mode = fmode;
2025                                 if (choice==0)  {
2026                                         Auto_demo = 0;
2027                                         newdemo_stop_playback();
2028                                         Function_mode = FMODE_MENU;
2029                                 } else {
2030                                         Function_mode = FMODE_GAME;
2031                                 }
2032                         }
2033
2034                         if ( (Function_mode != FMODE_GAME ) && (Newdemo_state != ND_STATE_PLAYBACK ) && (Function_mode!=FMODE_EDITOR)
2035 #ifdef NETWORK
2036                                         && !IWasKicked
2037 #endif
2038                            )            {
2039                                 int choice, fmode;
2040                                 fmode = Function_mode;
2041                                 Function_mode = FMODE_GAME;
2042                                 palette_save();
2043                                 apply_modified_palette();
2044                                 reset_palette_add();
2045                                 gr_palette_load( gr_palette );
2046                                 ExtGameStatus=GAMESTAT_ABORT_GAME;
2047                                 choice=nm_messagebox( NULL, 2, TXT_YES, TXT_NO, TXT_ABORT_GAME );
2048                                 palette_restore();
2049                                 Function_mode = fmode;
2050                                 if (choice != 0)
2051                                         Function_mode = FMODE_GAME;
2052                         }
2053
2054 #ifdef NETWORK
2055                         IWasKicked=0;
2056 #endif
2057                         if (Function_mode != FMODE_GAME)
2058                                 longjmp(LeaveGame,0);
2059
2060                         #ifdef APPLE_DEMO
2061                         if ( (keyd_time_when_last_pressed + (F1_0 * 60)) < timer_get_fixed_seconds() )          // idle in game for 1 minutes means exit
2062                                 longjmp(LeaveGame,0);
2063                         #endif
2064
2065                         if (VR_screen_flags & VRF_COMPATIBLE_MENUS) {
2066                                 mouse_set_mode(1);
2067                                 newmenu_hide_cursor();
2068                         }
2069                 }
2070         }
2071
2072 #ifdef MWPROFILE
2073         ProfilerSetStatus(0);
2074 #endif
2075
2076         digi_stop_all();
2077
2078         if ( (Newdemo_state == ND_STATE_RECORDING) || (Newdemo_state == ND_STATE_PAUSED) )
2079                 newdemo_stop_recording();
2080
2081         #ifdef NETWORK
2082         multi_leave_game();
2083         #endif
2084
2085         if ( Newdemo_state == ND_STATE_PLAYBACK )
2086                 newdemo_stop_playback();
2087
2088    if (Cockpit_mode_save!=-1)
2089          {
2090                 cvar_setint(&Cockpit_mode, Cockpit_mode_save);
2091                 Cockpit_mode_save=-1;           
2092          }
2093
2094         if (Function_mode != FMODE_EDITOR)
2095                 gr_palette_fade_out(gr_palette,32,0);                   // Fade out before going to menu
2096
2097 //@@    if ( (!demo_playing) && (!multi_game) && (Function_mode != FMODE_EDITOR))       {
2098 //@@            scores_maybe_add_player(Game_aborted);
2099 //@@    }
2100
2101 #ifdef __MSDOS__
2102         //_MARK_("end of game");
2103 #endif
2104
2105         clear_warn_func(game_show_warning);     //don't use this func anymore
2106
2107         game_disable_cheats();
2108
2109         #ifdef APPLE_DEMO
2110         Function_mode = FMODE_EXIT;             // get out of game in Apple OEM version
2111         #endif
2112 }
2113
2114 //called at the end of the program
2115 void close_game()
2116 {
2117         if (VR_offscreen_buffer)        {
2118                 gr_free_canvas(VR_offscreen_buffer);
2119                 VR_offscreen_buffer = NULL;
2120         }
2121
2122         close_gauge_canvases();
2123
2124         restore_effect_bitmap_icons();
2125
2126         if (background_bitmap.bm_data)
2127                 d_free(background_bitmap.bm_data);
2128
2129         clear_warn_func(game_show_warning);     //don't use this func anymore
2130 }
2131
2132 grs_canvas * get_current_game_screen()
2133 {
2134         return &VR_screen_pages[VR_current_page];
2135 }
2136
2137
2138 extern void kconfig_center_headset();
2139
2140
2141 #ifndef NDEBUG
2142 void    speedtest_frame(void);
2143 int     Debug_slowdown=0;
2144 #endif
2145
2146 #ifdef EDITOR
2147 extern void player_follow_path(object *objp);
2148 extern void check_create_player_path(void);
2149
2150 #endif
2151
2152 extern  int     Do_appearance_effect;
2153
2154 object *Missile_viewer=NULL;
2155
2156 cvar_t Missile_view_enabled = { "MissileView", "1", 1 };
2157
2158 int Marker_viewer_num[2]={-1,-1};
2159 int Coop_view_player[2]={-1,-1};
2160 cvar_t Cockpit_3d_view[2] = {
2161         { "CockpitViewLeft", "0", 1 },
2162         { "CockpitViewRight", "0", 1 },
2163 };
2164
2165 //returns ptr to escort robot, or NULL
2166 object *find_escort()
2167 {
2168         int i;
2169
2170         for (i=0; i<=Highest_object_index; i++)
2171                 if (Objects[i].type == OBJ_ROBOT)
2172                         if (Robot_info[Objects[i].id].companion)
2173                                 return &Objects[i];
2174
2175         return NULL;
2176 }
2177
2178 extern void process_super_mines_frame(void);
2179 extern void do_seismic_stuff(void);
2180
2181 #ifndef RELEASE
2182 int Saving_movie_frames=0;
2183 int __Movie_frame_num=0;
2184
2185 #define MAX_MOVIE_BUFFER_FRAMES 250
2186 #define MOVIE_FRAME_SIZE        (320 * 200)
2187
2188 ubyte *Movie_frame_buffer;
2189 int Movie_frame_counter;
2190 ubyte Movie_pal[768];
2191 char movie_path[50] = ".\\";
2192
2193 grs_bitmap Movie_bm;
2194
2195 void flush_movie_buffer()
2196 {
2197         char savename[128];
2198         int f;
2199
2200         stop_time();
2201
2202         mprintf((0,"Flushing movie buffer..."));
2203
2204         Movie_bm.bm_data = Movie_frame_buffer;
2205
2206         for (f=0;f<Movie_frame_counter;f++) {
2207                 sprintf(savename, "%sfrm%04d.pcx",movie_path,__Movie_frame_num);
2208                 __Movie_frame_num++;
2209                 pcx_write_bitmap(savename,&Movie_bm,Movie_pal);
2210                 Movie_bm.bm_data += MOVIE_FRAME_SIZE;
2211
2212                 if (f % 5 == 0)
2213                         mprintf((0,"%3d/%3d\10\10\10\10\10\10\10",f,Movie_frame_counter));
2214         }
2215
2216         Movie_frame_counter=0;
2217
2218         mprintf((0,"done   \n"));
2219
2220         start_time();
2221 }
2222
2223 void toggle_movie_saving()
2224 {
2225         int exit;
2226
2227         Saving_movie_frames = !Saving_movie_frames;
2228
2229         if (Saving_movie_frames) {
2230                 newmenu_item m[1];
2231
2232                 m[0].type=NM_TYPE_INPUT; m[0].text_len = 50; m[0].text = movie_path;
2233                 exit = newmenu_do( NULL, "Directory for movie frames?" , 1, &(m[0]), NULL );
2234
2235                 if (exit==-1) {
2236                         Saving_movie_frames = 0;
2237                         return;
2238                 }
2239
2240                 while (isspace(movie_path[strlen(movie_path)-1]))
2241                         movie_path[strlen(movie_path)-1] = 0;
2242                 if (movie_path[strlen(movie_path)-1]!='\\' && movie_path[strlen(movie_path)-1]!=':')
2243                         strcat(movie_path,"\\");
2244
2245
2246                 if (!Movie_frame_buffer) {
2247                         Movie_frame_buffer = d_malloc(MAX_MOVIE_BUFFER_FRAMES * MOVIE_FRAME_SIZE);
2248                         if (!Movie_frame_buffer) {
2249                                 Int3();
2250                                 Saving_movie_frames=0;
2251                         }
2252
2253                         Movie_frame_counter=0;
2254
2255                         Movie_bm.bm_x = Movie_bm.bm_y = 0;
2256                         Movie_bm.bm_w = 320;
2257                         Movie_bm.bm_h = 200;
2258                         Movie_bm.bm_type = BM_LINEAR;
2259                         Movie_bm.bm_flags = 0;
2260                         Movie_bm.bm_rowsize = 320;
2261                         Movie_bm.bm_handle = 0;
2262
2263                         gr_palette_read(Movie_pal);             //get actual palette from the hardware
2264
2265                         if (Newdemo_state == ND_STATE_PLAYBACK)
2266                                 Newdemo_do_interpolate = 0;
2267                 }
2268         }
2269         else {
2270                 flush_movie_buffer();
2271
2272                 if (Newdemo_state == ND_STATE_PLAYBACK)
2273                         Newdemo_do_interpolate = 1;
2274         }
2275
2276 }
2277
2278 void save_movie_frame()
2279 {
2280         memcpy(Movie_frame_buffer+Movie_frame_counter*MOVIE_FRAME_SIZE,grd_curscreen->sc_canvas.cv_bitmap.bm_data,MOVIE_FRAME_SIZE);
2281
2282         Movie_frame_counter++;
2283
2284         if (Movie_frame_counter == MAX_MOVIE_BUFFER_FRAMES)
2285                 flush_movie_buffer();
2286
2287 }
2288
2289 #endif
2290
2291 extern int Level_shake_duration;
2292
2293 //if water or fire level, make occasional sound
2294 void do_ambient_sounds()
2295 {
2296         int has_water,has_lava;
2297         int sound;
2298
2299         has_lava = (Segment2s[ConsoleObject->segnum].s2_flags & S2F_AMBIENT_LAVA);
2300         has_water = (Segment2s[ConsoleObject->segnum].s2_flags & S2F_AMBIENT_WATER);
2301
2302         if (has_lava) {                                                 //has lava
2303                 sound = SOUND_AMBIENT_LAVA;
2304                 if (has_water && (d_rand() & 1))        //both, pick one
2305                         sound = SOUND_AMBIENT_WATER;
2306         }
2307         else if (has_water)                                             //just water
2308                 sound = SOUND_AMBIENT_WATER;
2309         else
2310                 return;
2311
2312         if (((d_rand() << 3) < FrameTime)) {                                            //play the sound
2313                 fix volume = d_rand() + f1_0/2;
2314                 digi_play_sample(sound,volume);
2315         }
2316 }
2317
2318 // -- extern void lightning_frame(void);
2319
2320 void game_render_frame();
2321 extern void omega_charge_frame(void);
2322
2323 extern time_t t_current_time, t_saved_time;
2324
2325 void flicker_lights();
2326
2327 void GameLoop(int RenderFlag, int ReadControlsFlag )
2328 {
2329         #ifndef NDEBUG
2330         //      Used to slow down frame rate for testing things.
2331         //      RenderFlag = 1; // DEBUG
2332         if (Debug_slowdown) {
2333                 int     h, i, j=0;
2334
2335                 for (h=0; h<Debug_slowdown; h++)
2336                         for (i=0; i<1000; i++)
2337                                 j += i;
2338         }
2339         #endif
2340
2341                 #ifndef RELEASE
2342                 if (FindArg("-invulnerability"))
2343                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2344                 #endif
2345
2346
2347                 update_player_stats();
2348                 diminish_palette_towards_normal();              //      Should leave palette effect up for as long as possible by putting right before render.
2349                 do_afterburner_stuff();
2350                 do_cloak_stuff();
2351                 do_invulnerable_stuff();
2352                 remove_obsolete_stuck_objects();
2353                 init_ai_frame();
2354                 do_final_boss_frame();
2355                 // -- lightning_frame();
2356                 // -- recharge_energy_frame();
2357
2358                 if ((Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT) && (Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT_ON)) {
2359                         static int turned_off=0;
2360                         Players[Player_num].energy -= (FrameTime*3/8);
2361                         if (Players[Player_num].energy < i2f(10)) {
2362                                 if (!turned_off) {
2363                                         Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2364                                         turned_off = 1;
2365 #ifdef NETWORK
2366                                         if (Game_mode & GM_MULTI)
2367                                                 multi_send_flags(Player_num);           
2368 #endif
2369                                 }
2370                         }
2371                         else
2372                                 turned_off = 0;
2373
2374                         if (Players[Player_num].energy <= 0) {
2375                                 Players[Player_num].energy = 0;
2376                                 Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2377 #ifdef NETWORK
2378                                 if (Game_mode & GM_MULTI)
2379                                         multi_send_flags(Player_num);           
2380 #endif
2381                         }
2382                 }
2383
2384
2385                 #ifdef EDITOR
2386                 check_create_player_path();
2387                 player_follow_path(ConsoleObject);
2388                 #endif
2389
2390                 #ifdef NETWORK
2391                 if (Game_mode & GM_MULTI)
2392         {
2393          multi_do_frame();
2394          if (Netgame.PlayTimeAllowed && ThisLevelTime>=i2f((Netgame.PlayTimeAllowed*5*60)))
2395              multi_check_for_killgoal_winner();
2396         }
2397
2398                 #endif
2399
2400                 if (RenderFlag) {
2401                         if (force_cockpit_redraw) {                     //screen need redrawing?
2402                                 init_cockpit();
2403                                 force_cockpit_redraw=0;
2404                         }
2405                         game_render_frame();
2406                         //show_extra_views();           //missile view, buddy bot, etc.
2407
2408                         #ifndef RELEASE
2409                         if (Saving_movie_frames)
2410                                 save_movie_frame();
2411                         #endif
2412
2413                 }
2414
2415
2416                 //mprintf(0,"Velocity %2.2f\n", f2fl(vm_vec_mag(&ConsoleObject->phys_info.velocity)));
2417
2418                 calc_frame_time();
2419
2420                 dead_player_frame();
2421                 if (Newdemo_state != ND_STATE_PLAYBACK)
2422                         do_controlcen_dead_frame();
2423
2424                 process_super_mines_frame();
2425                 do_seismic_stuff();
2426                 do_ambient_sounds();
2427
2428                 #ifndef NDEBUG
2429                 if (Speedtest_on)
2430                         speedtest_frame();
2431                 #endif
2432
2433                 if (ReadControlsFlag)
2434                         ReadControls();
2435                 else
2436                         memset(&Controls, 0, sizeof(Controls));
2437
2438                 GameTime += FrameTime;
2439
2440                 if (f2i(GameTime)/10 != f2i(GameTime-FrameTime)/10)
2441                         mprintf((0,"Gametime = %d secs\n",f2i(GameTime)));
2442
2443                 if (GameTime < 0 || GameTime > i2f(0x7fff - 600)) {
2444                         GameTime = FrameTime;   //wrap when goes negative, or gets within 10 minutes
2445                         mprintf((0,"GameTime reset to 0\n"));
2446                 }
2447
2448                 #ifndef NDEBUG
2449                 if (FindArg("-checktime") != 0)
2450                         if (GameTime >= i2f(600))               //wrap after 10 minutes
2451                                 GameTime = FrameTime;
2452                 #endif
2453
2454 #ifdef NETWORK
2455       if ((Game_mode & GM_MULTI) && Netgame.PlayTimeAllowed)
2456           ThisLevelTime +=FrameTime;
2457 #endif
2458
2459                 digi_sync_sounds();
2460
2461                 if (Endlevel_sequence) {
2462                         do_endlevel_frame();
2463                         powerup_grab_cheat_all();
2464                         do_special_effects();
2465                         return;                                 //skip everything else
2466                 }
2467
2468                 if (Newdemo_state != ND_STATE_PLAYBACK)
2469                         do_exploding_wall_frame();
2470                 if ((Newdemo_state != ND_STATE_PLAYBACK) || (Newdemo_vcr_state != ND_STATE_PAUSED)) {
2471                         do_special_effects();
2472                         wall_frame_process();
2473                         triggers_frame_process();
2474                 }
2475
2476
2477                 if (Control_center_destroyed)   {
2478                         if (Newdemo_state==ND_STATE_RECORDING )
2479                                 newdemo_record_control_center_destroyed();
2480                 }
2481
2482                 flash_frame();
2483
2484                 if ( Newdemo_state == ND_STATE_PLAYBACK )       {
2485                         newdemo_playback_one_frame();
2486                         if ( Newdemo_state != ND_STATE_PLAYBACK )               {
2487                                 longjmp( LeaveGame, 0 );                // Go back to menu
2488                         }
2489                 } else
2490                 { // Note the link to above!
2491
2492                         Players[Player_num].homing_object_dist = -1;            //      Assume not being tracked.  Laser_do_weapon_sequence modifies this.
2493
2494                         object_move_all();
2495                         powerup_grab_cheat_all();
2496
2497                         if (Endlevel_sequence)  //might have been started during move
2498                                 return;
2499
2500                         fuelcen_update_all();
2501
2502                         do_ai_frame_all();
2503
2504                         if (allowed_to_fire_laser())
2505                                 FireLaser();                            // Fire Laser!
2506
2507                         if (Auto_fire_fusion_cannon_time) {
2508                                 if (Primary_weapon != FUSION_INDEX)
2509                                         Auto_fire_fusion_cannon_time = 0;
2510                                 else if (GameTime + FrameTime/2 >= Auto_fire_fusion_cannon_time) {
2511                                         Auto_fire_fusion_cannon_time = 0;
2512                                         Global_laser_firing_count = 1;
2513                                 } else {
2514                                         vms_vector      rand_vec;
2515                                         fix                     bump_amount;
2516
2517                                         Global_laser_firing_count = 0;
2518
2519                                         ConsoleObject->mtype.phys_info.rotvel.x += (d_rand() - 16384)/8;
2520                                         ConsoleObject->mtype.phys_info.rotvel.z += (d_rand() - 16384)/8;
2521                                         make_random_vector(&rand_vec);
2522
2523                                         bump_amount = F1_0*4;
2524
2525                                         if (Fusion_charge > F1_0*2)
2526                                                 bump_amount = Fusion_charge*4;
2527
2528                                         bump_one_object(ConsoleObject, &rand_vec, bump_amount);
2529                                 }
2530                         }
2531
2532                         if (Global_laser_firing_count) {
2533                                 //      Don't cap here, gets capped in Laser_create_new and is based on whether in multiplayer mode, MK, 3/27/95
2534                                 // if (Fusion_charge > F1_0*2)
2535                                 //      Fusion_charge = F1_0*2;
2536                                 Global_laser_firing_count -= do_laser_firing_player();  //do_laser_firing(Players[Player_num].objnum, Primary_weapon);
2537                         }
2538
2539                         if (Global_laser_firing_count < 0)
2540                                 Global_laser_firing_count = 0;
2541                 }
2542
2543         if (Do_appearance_effect) {
2544                 create_player_appearance_effect(ConsoleObject);
2545                 Do_appearance_effect = 0;
2546 #ifdef NETWORK
2547                 if ((Game_mode & GM_MULTI) && Netgame.invul)
2548                 {
2549                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2550                         Players[Player_num].invulnerable_time = GameTime-i2f(27);
2551                         FakingInvul=1;
2552                 }
2553 #endif
2554                         
2555         }
2556
2557         omega_charge_frame();
2558         slide_textures();
2559         flicker_lights();
2560
2561         //!!hoard_light_pulse();                //do cool hoard light pulsing
2562
2563 }
2564
2565 //!!extern int Goal_blue_segnum,Goal_red_segnum;
2566 //!!extern int Hoard_goal_eclip;
2567 //!!
2568 //!!//do cool pulsing lights in hoard goals
2569 //!!hoard_light_pulse()
2570 //!!{
2571 //!!    if (Game_mode & GM_HOARD) {
2572 //!!            fix light;
2573 //!!            int frame;
2574 //!!
2575 //!!            frame = Effects[Hoard_goal_eclip].frame_count;
2576 //!!
2577 //!!            frame++;
2578 //!!
2579 //!!            if (frame >= Effects[Hoard_goal_eclip].vc.num_frames)
2580 //!!                    frame = 0;
2581 //!!
2582 //!!            light = abs(frame - 5) * f1_0 / 5;
2583 //!!
2584 //!!            Segment2s[Goal_red_segnum].static_light = Segment2s[Goal_blue_segnum].static_light = light;
2585 //!!    }
2586 //!!}
2587
2588
2589 ubyte   Slide_segs[MAX_SEGMENTS];
2590 int     Slide_segs_computed;
2591
2592 void compute_slide_segs(void)
2593 {
2594         int     segnum, sidenum;
2595
2596         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2597                 Slide_segs[segnum] = 0;
2598                 for (sidenum=0;sidenum<6;sidenum++) {
2599                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2600                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0)
2601                                 Slide_segs[segnum] |= 1 << sidenum;
2602                 }
2603         }
2604
2605         Slide_segs_computed = 1;
2606 }
2607
2608 //      -----------------------------------------------------------------------------
2609 void slide_textures(void)
2610 {
2611         int segnum,sidenum,i;
2612
2613         if (!Slide_segs_computed)
2614                 compute_slide_segs();
2615
2616         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2617                 if (Slide_segs[segnum]) {
2618                         for (sidenum=0;sidenum<6;sidenum++) {
2619                                 if (Slide_segs[segnum] & (1 << sidenum)) {
2620                                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2621                                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0) {
2622                                                 for (i=0;i<4;i++) {
2623                                                         Segments[segnum].sides[sidenum].uvls[i].u += fixmul(FrameTime,TmapInfo[tmn].slide_u<<8);
2624                                                         Segments[segnum].sides[sidenum].uvls[i].v += fixmul(FrameTime,TmapInfo[tmn].slide_v<<8);
2625                                                         if (Segments[segnum].sides[sidenum].uvls[i].u > f2_0) {
2626                                                                 int j;
2627                                                                 for (j=0;j<4;j++)
2628                                                                         Segments[segnum].sides[sidenum].uvls[j].u -= f1_0;
2629                                                         }
2630                                                         if (Segments[segnum].sides[sidenum].uvls[i].v > f2_0) {
2631                                                                 int j;
2632                                                                 for (j=0;j<4;j++)
2633                                                                         Segments[segnum].sides[sidenum].uvls[j].v -= f1_0;
2634                                                         }
2635                                                         if (Segments[segnum].sides[sidenum].uvls[i].u < -f2_0) {
2636                                                                 int j;
2637                                                                 for (j=0;j<4;j++)
2638                                                                         Segments[segnum].sides[sidenum].uvls[j].u += f1_0;
2639                                                         }
2640                                                         if (Segments[segnum].sides[sidenum].uvls[i].v < -f2_0) {
2641                                                                 int j;
2642                                                                 for (j=0;j<4;j++)
2643                                                                         Segments[segnum].sides[sidenum].uvls[j].v += f1_0;
2644                                                         }
2645                                                 }
2646                                         }
2647                                 }
2648                         }
2649                 }
2650         }
2651 }
2652
2653 flickering_light Flickering_lights[MAX_FLICKERING_LIGHTS];
2654
2655 int Num_flickering_lights=0;
2656
2657 void flicker_lights()
2658 {
2659         int l;
2660         flickering_light *f;
2661
2662         f = Flickering_lights;
2663
2664         for (l=0;l<Num_flickering_lights;l++,f++) {
2665                 segment *segp = &Segments[f->segnum];
2666
2667                 //make sure this is actually a light
2668                 if (! (WALL_IS_DOORWAY(segp, f->sidenum) & WID_RENDER_FLAG))
2669                         continue;
2670                 if (! (TmapInfo[segp->sides[f->sidenum].tmap_num].lighting | TmapInfo[segp->sides[f->sidenum].tmap_num2 & 0x3fff].lighting))
2671                         continue;
2672
2673                 if (f->timer == 0x80000000)             //disabled
2674                         continue;
2675
2676                 if ((f->timer -= FrameTime) < 0) {
2677
2678                         while (f->timer < 0)
2679                                 f->timer += f->delay;
2680
2681                         f->mask = ((f->mask&0x80000000)?1:0) + (f->mask<<1);
2682
2683                         if (f->mask & 1)
2684                                 add_light(f->segnum,f->sidenum);
2685                         else
2686                                 subtract_light(f->segnum,f->sidenum);
2687                 }
2688         }
2689 }
2690
2691 //returns ptr to flickering light structure, or NULL if can't find
2692 flickering_light *find_flicker(int segnum,int sidenum)
2693 {
2694         int l;
2695         flickering_light *f;
2696
2697         //see if there's already an entry for this seg/side
2698
2699         f = Flickering_lights;
2700
2701         for (l=0;l<Num_flickering_lights;l++,f++)
2702                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
2703                         return f;
2704
2705         return NULL;
2706 }
2707
2708 //turn flickering off (because light has been turned off)
2709 void disable_flicker(int segnum,int sidenum)
2710 {
2711         flickering_light *f;
2712
2713         if ((f=find_flicker(segnum,sidenum)) != NULL)
2714                 f->timer = 0x80000000;
2715 }
2716
2717 //turn flickering off (because light has been turned on)
2718 void enable_flicker(int segnum,int sidenum)
2719 {
2720         flickering_light *f;
2721
2722         if ((f=find_flicker(segnum,sidenum)) != NULL)
2723                 f->timer = 0;
2724 }
2725
2726
2727 #ifdef EDITOR
2728
2729 //returns 1 if ok, 0 if error
2730 int add_flicker(int segnum, int sidenum, fix delay, unsigned long mask)
2731 {
2732         int l;
2733         flickering_light *f;
2734
2735         mprintf((0,"add_flicker: %d:%d %x %x\n",segnum,sidenum,delay,mask));
2736
2737         //see if there's already an entry for this seg/side
2738
2739         f = Flickering_lights;
2740
2741         for (l=0;l<Num_flickering_lights;l++,f++)
2742                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
2743                         break;
2744
2745         if (mask==0) {          //clearing entry
2746                 if (l == Num_flickering_lights)
2747                         return 0;
2748                 else {
2749                         int i;
2750                         for (i=l;i<Num_flickering_lights-1;i++)
2751                                 Flickering_lights[i] = Flickering_lights[i+1];
2752                         Num_flickering_lights--;
2753                         return 1;
2754                 }
2755         }
2756
2757         if (l == Num_flickering_lights) {
2758                 if (Num_flickering_lights == MAX_FLICKERING_LIGHTS)
2759                         return 0;
2760                 else
2761                         Num_flickering_lights++;
2762         }
2763
2764         f->segnum = segnum;
2765         f->sidenum = sidenum;
2766         f->delay = f->timer = delay;
2767         f->mask = mask;
2768
2769         return 1;
2770 }
2771
2772 #endif
2773
2774 //      -----------------------------------------------------------------------------
2775 //      Fire Laser:  Registers a laser fire, and performs special stuff for the fusion
2776 //                                  cannon.
2777 void FireLaser()
2778 {
2779
2780         Global_laser_firing_count = Weapon_info[Primary_weapon_to_weapon_info[Primary_weapon]].fire_count * (Controls.state[fire_primary] || Controls.count[fire_primary]);
2781
2782         if ((Primary_weapon == FUSION_INDEX) && (Global_laser_firing_count)) {
2783                 if ((Players[Player_num].energy < F1_0*2) && (Auto_fire_fusion_cannon_time == 0)) {
2784                         Global_laser_firing_count = 0;
2785                 } else {
2786                         if (Fusion_charge == 0)
2787                                 Players[Player_num].energy -= F1_0*2;
2788
2789                         Fusion_charge += FrameTime;
2790                         Players[Player_num].energy -= FrameTime;
2791
2792                         if (Players[Player_num].energy <= 0) {
2793                                 Players[Player_num].energy = 0;
2794                                 Auto_fire_fusion_cannon_time = GameTime -1;     //      Fire now!
2795                         } else
2796                                 Auto_fire_fusion_cannon_time = GameTime + FrameTime/2 + 1;
2797                                                                                                 //      Fire the fusion cannon at this time in the future.
2798
2799                         if (Fusion_charge < F1_0*2)
2800                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, 0, Fusion_charge >> 11);
2801                         else
2802                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, Fusion_charge >> 11, 0);
2803
2804                         if (GameTime < Fusion_last_sound_time)          //gametime has wrapped
2805                                 Fusion_next_sound_time = Fusion_last_sound_time = GameTime;
2806
2807                         if (Fusion_next_sound_time < GameTime) {
2808                                 if (Fusion_charge > F1_0*2) {
2809                                         digi_play_sample( 11, F1_0 );
2810                                         apply_damage_to_player(ConsoleObject, ConsoleObject, d_rand() * 4);
2811                                 } else {
2812                                         create_awareness_event(ConsoleObject, PA_WEAPON_ROBOT_COLLISION);
2813                                         digi_play_sample( SOUND_FUSION_WARMUP, F1_0 );
2814                                         #ifdef NETWORK
2815                                         if (Game_mode & GM_MULTI)
2816                                                 multi_send_play_sound(SOUND_FUSION_WARMUP, F1_0);
2817                                         #endif
2818                                 }
2819                                 Fusion_last_sound_time = GameTime;
2820                                 Fusion_next_sound_time = GameTime + F1_0/8 + d_rand()/4;
2821                         }
2822                 }
2823         }
2824
2825 }
2826
2827
2828 //      -------------------------------------------------------------------------------------------------------
2829 //      If player is close enough to objnum, which ought to be a powerup, pick it up!
2830 //      This could easily be made difficulty level dependent.
2831 void powerup_grab_cheat(object *player, int objnum)
2832 {
2833         fix     powerup_size;
2834         fix     player_size;
2835         fix     dist;
2836
2837         Assert(Objects[objnum].type == OBJ_POWERUP);
2838
2839         powerup_size = Objects[objnum].size;
2840         player_size = player->size;
2841
2842         dist = vm_vec_dist_quick(&Objects[objnum].pos, &player->pos);
2843
2844         if ((dist < 2*(powerup_size + player_size)) && !(Objects[objnum].flags & OF_SHOULD_BE_DEAD)) {
2845                 vms_vector      collision_point;
2846
2847                 vm_vec_avg(&collision_point, &Objects[objnum].pos, &player->pos);
2848                 collide_player_and_powerup(player, &Objects[objnum], &collision_point);
2849         }
2850 }
2851
2852 //      -------------------------------------------------------------------------------------------------------
2853 //      Make it easier to pick up powerups.
2854 //      For all powerups in this segment, pick them up at up to twice pickuppable distance based on dot product
2855 //      from player to powerup and player's forward vector.
2856 //      This has the effect of picking them up more easily left/right and up/down, but not making them disappear
2857 //      way before the player gets there.
2858 void powerup_grab_cheat_all(void)
2859 {
2860         segment *segp;
2861         int             objnum;
2862
2863         segp = &Segments[ConsoleObject->segnum];
2864         objnum = segp->objects;
2865
2866         while (objnum != -1) {
2867                 if (Objects[objnum].type == OBJ_POWERUP)
2868                         powerup_grab_cheat(ConsoleObject, objnum);
2869                 objnum = Objects[objnum].next;
2870         }
2871
2872 }
2873
2874 int     Last_level_path_created = -1;
2875
2876 #ifdef SHOW_EXIT_PATH
2877
2878 //      ------------------------------------------------------------------------------------------------------------------
2879 //      Create path for player from current segment to goal segment.
2880 //      Return true if path created, else return false.
2881 int mark_player_path_to_segment(int segnum)
2882 {
2883         int             i;
2884         object  *objp = ConsoleObject;
2885         short           player_path_length=0;
2886         int             player_hide_index=-1;
2887
2888         if (Last_level_path_created == Current_level_num) {
2889                 return 0;
2890         }
2891
2892         Last_level_path_created = Current_level_num;
2893
2894         if (create_path_points(objp, objp->segnum, segnum, Point_segs_free_ptr, &player_path_length, 100, 0, 0, -1) == -1) {
2895                 mprintf((0, "Unable to form path of length %i for myself\n", 100));
2896                 return 0;
2897         }
2898
2899         player_hide_index = (int)(Point_segs_free_ptr - Point_segs);
2900         Point_segs_free_ptr += player_path_length;
2901
2902         if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
2903                 mprintf((1, "Can't create path.  Not enough point_segs.\n"));
2904                 ai_reset_all_paths();
2905                 return 0;
2906         }
2907
2908         for (i=1; i<player_path_length; i++) {
2909                 int                     segnum, objnum;
2910                 vms_vector      seg_center;
2911                 object          *obj;
2912
2913                 segnum = Point_segs[player_hide_index+i].segnum;
2914                 mprintf((0, "%3i ", segnum));
2915                 seg_center = Point_segs[player_hide_index+i].point;
2916
2917                 objnum = obj_create( OBJ_POWERUP, POW_ENERGY, segnum, &seg_center, &vmd_identity_matrix, Powerup_info[POW_ENERGY].size, CT_POWERUP, MT_NONE, RT_POWERUP);
2918                 if (objnum == -1) {
2919                         Int3();         //      Unable to drop energy powerup for path
2920                         return 1;
2921                 }
2922
2923                 obj = &Objects[objnum];
2924                 obj->rtype.vclip_info.vclip_num = Powerup_info[obj->id].vclip_num;
2925                 obj->rtype.vclip_info.frametime = Vclip[obj->rtype.vclip_info.vclip_num].frame_time;
2926                 obj->rtype.vclip_info.framenum = 0;
2927                 obj->lifeleft = F1_0*100 + d_rand() * 4;
2928         }
2929
2930         mprintf((0, "\n"));
2931         return 1;
2932 }
2933
2934 //      Return true if it happened, else return false.
2935 int create_special_path(void)
2936 {
2937         int     i,j;
2938
2939         //      ---------- Find exit doors ----------
2940         for (i=0; i<=Highest_segment_index; i++)
2941                 for (j=0; j<MAX_SIDES_PER_SEGMENT; j++)
2942                         if (Segments[i].children[j] == -2) {
2943                                 mprintf((0, "Exit at segment %i\n", i));
2944                                 return mark_player_path_to_segment(i);
2945                         }
2946
2947         return 0;
2948 }
2949
2950 #endif
2951
2952
2953 #ifndef RELEASE
2954 int     Max_obj_count_mike = 0;
2955
2956 //      Shows current number of used objects.
2957 void show_free_objects(void)
2958 {
2959         if (!(FrameCount & 8)) {
2960                 int     i;
2961                 int     count=0;
2962
2963                 mprintf((0, "Highest_object_index = %3i, MAX_OBJECTS = %3i, now used = ", Highest_object_index, MAX_OBJECTS));
2964
2965                 for (i=0; i<=Highest_object_index; i++)
2966                         if (Objects[i].type != OBJ_NONE)
2967                                 count++;
2968
2969                 mprintf((0, "%3i", count));
2970
2971                 if (count > Max_obj_count_mike) {
2972                         Max_obj_count_mike = count;
2973                         mprintf((0, " ***"));
2974                 }
2975
2976                 mprintf((0, "\n"));
2977         }
2978
2979 }
2980
2981 #endif
2982
2983 /*
2984  * reads a flickering_light structure from a CFILE
2985  */
2986 void flickering_light_read(flickering_light *fl, CFILE *fp)
2987 {
2988         fl->segnum = cfile_read_short(fp);
2989         fl->sidenum = cfile_read_short(fp);
2990         fl->mask = cfile_read_int(fp);
2991         fl->timer = cfile_read_fix(fp);
2992         fl->delay = cfile_read_fix(fp);
2993 }
2994
2995 void flickering_light_write(flickering_light *fl, PHYSFS_file *fp)
2996 {
2997         PHYSFS_writeSLE16(fp, fl->segnum);
2998         PHYSFS_writeSLE16(fp, fl->sidenum);
2999         PHYSFS_writeULE32(fp, (uint32_t)fl->mask);
3000         PHYSFSX_writeFix(fp, fl->timer);
3001         PHYSFSX_writeFix(fp, fl->delay);
3002 }