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