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