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