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