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