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