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