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