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