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