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