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