attempt to support d1 for mac mission
[btb/d2x.git] / main / game.c
1 /* $Id: game.c,v 1.16 2002-10-03 03:46:34 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.16 2002-10-03 03:46:34 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 "d_delay.h"
121 #include "hudmsg.h"
122
123 int VGA_current_mode;
124
125 #ifdef MWPROFILER
126 #include <profiler.h>
127 #endif
128
129 //#define TEST_TIMER    1               //if this is set, do checking on timer
130
131 #define SHOW_EXIT_PATH  1
132
133 #ifdef EDITOR
134 #include "editor/editor.h"
135 #endif
136
137 //#define _MARK_ON 1
138 #ifdef __WATCOMC__
139 #if __WATCOMC__ < 1000
140 #include <wsample.h>            //should come after inferno.h to get mark setting
141 #endif
142 #endif
143
144
145 extern void ReadControls(void);         // located in gamecntl.c
146 extern int Current_display_mode;
147 extern void do_final_boss_frame(void);
148
149 int     Speedtest_on = 0;
150
151 #ifndef NDEBUG
152 int     Mark_count = 0;                 // number of debugging marks set
153 int     Speedtest_start_time;
154 int     Speedtest_segnum;
155 int     Speedtest_sidenum;
156 int     Speedtest_frame_start;
157 int     Speedtest_count=0;                              //      number of times to do the debug test.
158 #endif
159
160 static fix last_timer_value=0;
161 fix ThisLevelTime=0;
162
163 #if defined(TIMER_TEST) && !defined(NDEBUG)
164 fix _timer_value,actual_last_timer_value,_last_frametime;
165 int stop_count,start_count;
166 int time_stopped,time_started;
167 #endif
168
169 #ifndef MACINTOSH
170 ubyte * Game_cockpit_copy_code = NULL;
171 #else
172 ubyte Game_cockpit_copy_code = 0;
173 ubyte Scanline_double = 1;
174 #endif
175
176 int                     VR_screen_mode                  = 0;
177
178 ubyte                   VR_screen_flags = 0;            //see values in screens.h
179 ubyte                   VR_current_page = 0;
180 fix                     VR_eye_width            = F1_0;
181 int                     VR_render_mode          = VR_NONE;
182 int                     VR_low_res                      = 3;                            // Default to low res
183 int                     VR_show_hud = 1;
184 int                     VR_sensitivity     = 1;         // 0 - 2
185
186 //NEWVR
187 int                     VR_eye_offset            = 0;
188 int                     VR_eye_switch            = 0;
189 int                     VR_eye_offset_changed = 0;
190 int                     VR_use_reg_code         = 0;
191
192 grs_canvas  *VR_offscreen_buffer        = NULL;         // The offscreen data buffer
193 grs_canvas      VR_render_buffer[2];                                    //  Two offscreen buffers for left/right eyes.
194 grs_canvas      VR_render_sub_buffer[2];                        //  Two sub buffers for left/right eyes.
195 grs_canvas      VR_screen_pages[2];                                     //  Two pages of VRAM if paging is available
196 grs_canvas      VR_editor_canvas;                                               //  The canvas that the editor writes to.
197
198 #ifdef WINDOWS
199 //@@ LPDIRECTDRAWSURFACE _lpDDSMask = NULL;
200 dd_grs_canvas *dd_VR_offscreen_buffer = NULL;
201 dd_grs_canvas dd_VR_screen_pages[2];
202 dd_grs_canvas dd_VR_render_buffer[2];
203 dd_grs_canvas dd_VR_render_sub_buffer[2];
204
205 void game_win_init_cockpit_mask(int sram);
206 #endif
207
208 //do menus work in 640x480 or 320x200?
209 //PC version sets this in main().  Mac versios is always high-res, so set to 1 here
210 int MenuHiresAvailable = 1;             //can we do highres menus?
211 int MenuHires = 1;                              //are we currently in highres menus?
212
213 int Debug_pause=0;                              //John's debugging pause system
214
215 int Cockpit_mode=CM_FULL_COCKPIT;               //set game.h for values
216
217 int Cockpit_mode_save=-1;                                       //set while in letterbox or rear view, or -1
218 int force_cockpit_redraw=0;
219
220 cvar_t r_framerate = {"r_framerate","0"};
221
222 int PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd;
223
224 //      Toggle_var points at a variable which gets !ed on ctrl-alt-T press.
225 int     Dummy_var;
226 int     *Toggle_var = &Dummy_var;
227
228 #ifdef EDITOR
229 //flag for whether initial fade-in has been done
230 char faded_in;
231 #endif
232
233 #ifndef NDEBUG                          //these only exist if debugging
234
235 int Game_double_buffer = 1;     //double buffer by default
236 fix fixed_frametime=0;          //if non-zero, set frametime to this
237
238 #endif
239
240 int Game_suspended=0;           //if non-zero, nothing moves but player
241
242 fix     RealFrameTime;
243 fix     Auto_fire_fusion_cannon_time = 0;
244 fix     Fusion_charge = 0;
245 fix     Fusion_next_sound_time = 0;
246 fix     Fusion_last_sound_time = 0;
247
248 int Debug_spew = 1;
249 int Game_turbo_mode = 0;
250
251 int Game_mode = GM_GAME_OVER;
252
253 int     Global_laser_firing_count = 0;
254 int     Global_missile_firing_count = 0;
255
256 grs_bitmap background_bitmap;
257
258 int Game_aborted;
259
260 #define BACKGROUND_NAME "statback.pcx"
261
262 //      Function prototypes for GAME.C exclusively.
263
264 void GameLoop(int RenderFlag, int ReadControlsFlag);
265 void FireLaser(void);
266 void slide_textures(void);
267 void powerup_grab_cheat_all(void);
268
269 //      Other functions
270 extern void multi_check_for_killgoal_winner();
271 extern void RestoreGameSurfaces();
272
273 // window functions
274
275 void grow_window(void);
276 void shrink_window(void);
277
278 // text functions
279
280 void fill_background();
281
282 #ifndef RELEASE
283 void show_framerate(void);
284 void ftoa(char *string, fix f);
285 #endif
286
287 extern ubyte DefiningMarkerMessage;
288 extern char Marker_input[];
289
290 //      ==============================================================================================
291
292 extern char john_head_on;
293
294 void load_background_bitmap()
295 {
296         ubyte pal[256*3];
297         int pcx_error;
298
299         if (background_bitmap.bm_data)
300                 d_free(background_bitmap.bm_data);
301
302         background_bitmap.bm_data=NULL;
303         pcx_error = pcx_read_bitmap(john_head_on?"johnhead.pcx":BACKGROUND_NAME,&background_bitmap,BM_LINEAR,pal);
304         if (pcx_error != PCX_ERROR_NONE)
305                 Error("File %s - PCX error: %s",BACKGROUND_NAME,pcx_errormsg(pcx_error));
306         gr_remap_bitmap_good( &background_bitmap, pal, -1, -1 );
307 }
308
309
310 //this is called once per game
311 void init_game()
312 {
313         atexit(close_game);             //for cleanup
314
315         init_objects();
316
317         init_special_effects();
318
319         init_ai_system();
320
321         init_gauge_canvases();
322
323         init_exploding_walls();
324
325         load_background_bitmap();
326
327         Clear_window = 2;               //      do portal only window clear.
328
329         set_detail_level_parameters(Detail_level);
330
331         build_mission_list(0);
332
333         /* Register cvars */
334         cvar_registervariable(&r_framerate);
335
336 }
337
338
339 void reset_palette_add()
340 {
341         PaletteRedAdd           = 0;
342         PaletteGreenAdd = 0;
343         PaletteBlueAdd          = 0;
344         //gr_palette_step_up( PaletteRedAdd, PaletteGreenAdd, PaletteBlueAdd );
345 }
346
347
348 #ifdef WINDOWS
349 void win_get_span_list(grs_bitmap *bm, int miny, int maxy)
350 {
351         int x,y;
352         int mode = 0;
353         ubyte *data;
354         int offset;
355         int lspan=0, rspan=0, span=0;
356 //@@FILE *fp;
357
358         data = bm->bm_data;
359 //@@    fp = fopen("cockspan.dat", "w");
360
361         for (y = 0; y < miny; y++)
362                 win_cockpit_mask[y].num = 0;
363
364         for (y = miny; y <= maxy; y++) 
365         {
366                 span = 0;
367                 //@@ fprintf(fp, "line %d: ", y);               
368                 for (x = 0; x < bm->bm_w; x++)
369                 {
370                         offset = y*bm->bm_rowsize + x;
371
372                         if (data[offset] == 255) {
373                                 switch (mode)
374                                 {
375                                         case 0:                         // Start Mode
376                                                 lspan   = x;
377                                                 win_cockpit_mask[y].span[span].xmin = x;
378                                                 mode = 1;
379                                         //@@    fprintf(fp, "<%d,", lspan);
380                                                 break;
381
382                                         case 1:                         // Transparency mode
383                                                 rspan = x;
384                                                 win_cockpit_mask[y].span[span].xmax = x;
385                                                 break;
386
387                                         case 2:                         // Switch from Draw mode to transparent
388                                                 lspan = x;
389                                                 win_cockpit_mask[y].span[span].xmin = x;
390                                         //@@    fprintf(fp, "<%d,", lspan);
391                                                 mode = 1;
392                                                 break;
393                                 }
394                         }
395                         else {
396                                 switch(mode) 
397                                 {
398                                         case 0:                         // Start mode
399                                                 mode = 2;
400                                                 break;
401                                         
402                                         case 1:                         // Switching from transparent to Draw
403                                                 rspan = x;
404                                                 mode = 2;
405                                                 win_cockpit_mask[y].span[span].xmax = x;
406                                                 span++;
407                                         //@@    fprintf(fp, "%d> ", rspan);
408                                                 break;
409
410                                         case 2:
411                                                 break;
412                                 }
413                         }
414                 }
415                 if (mode == 1) {
416                 //@@    fprintf(fp, "%d> ", rspan);
417                         win_cockpit_mask[y].span[span].xmax = rspan;
418                         span++;
419                 }
420                 win_cockpit_mask[y].num = span;
421         //@@    fprintf(fp, "\n");
422                 mode = 0;
423         }
424         win_cockpit_mask[y].num = 255;
425 }
426 #endif //WINDOWS
427         
428
429 void game_show_warning(char *s)
430 {
431
432         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
433                 stop_time();
434
435         nm_messagebox( TXT_WARNING, 1, TXT_OK, s );
436
437         if (!((Game_mode & GM_MULTI) && (Function_mode == FMODE_GAME)))
438                 start_time();
439 }
440
441
442 //these should be in gr.h
443 #define cv_w  cv_bitmap.bm_w
444 #define cv_h  cv_bitmap.bm_h
445
446 int Game_window_x = 0;
447 int Game_window_y = 0;
448 int Game_window_w = 0;
449 int Game_window_h = 0;
450 int max_window_w = 0;
451 int max_window_h = 0;
452
453 extern void newdemo_record_cockpit_change(int);
454
455 //initialize the various canvases on the game screen
456 //called every time the screen mode or cockpit changes
457 void init_cockpit()
458 {
459         int minx, maxx, miny, maxy;
460
461 #if defined(POLY_ACC)
462     pa_flush();                 // get rid of undrawn polys.
463     pa_clear_buffer(1, 0);
464 #endif
465
466         //Initialize the on-screen canvases
467
468         if (Newdemo_state==ND_STATE_RECORDING) {
469                 newdemo_record_cockpit_change(Cockpit_mode);
470         }
471
472         if ( VR_render_mode != VR_NONE )
473                 Cockpit_mode = CM_FULL_SCREEN;
474
475         if (!(VR_screen_flags & VRF_ALLOW_COCKPIT) && (Cockpit_mode==CM_FULL_COCKPIT || Cockpit_mode==CM_STATUS_BAR || Cockpit_mode==CM_REAR_VIEW) )
476                 Cockpit_mode = CM_FULL_SCREEN;
477
478         if ( Screen_mode == SCREEN_EDITOR )
479                 Cockpit_mode = CM_FULL_SCREEN;
480
481 #ifdef OGL
482         if (Cockpit_mode == CM_FULL_COCKPIT || Cockpit_mode == CM_REAR_VIEW) {
483                 hud_message(MSGC_GAME_FEEDBACK, "Cockpit not available in GL mode");
484                 Cockpit_mode = CM_FULL_SCREEN;
485         }
486 #endif
487
488         WINDOS(
489                 dd_gr_set_current_canvas(NULL),
490                 gr_set_current_canvas(NULL)
491                 );
492         gr_set_curfont( GAME_FONT );
493
494 #if !defined(MACINTOSH) && !defined(WINDOWS)
495         if (Game_cockpit_copy_code)
496                 d_free(Game_cockpit_copy_code);
497         Game_cockpit_copy_code  = NULL;
498 #else
499         if (Game_cockpit_copy_code)
500                 Game_cockpit_copy_code = 0;
501 #endif
502
503 //@@    #ifdef WINDOWS
504 //@@            if (_lpDDSMask) { DDFreeSurface(_lpDDSMask); _lpDDSMask = NULL; }
505 //@@    #endif
506
507 #ifdef WINDOWS
508         game_win_init_cockpit_mask(0);
509 #endif
510
511         switch( Cockpit_mode ) {
512         case CM_FULL_COCKPIT:
513         case CM_REAR_VIEW: {
514                 grs_bitmap *bm = &GameBitmaps[cockpit_bitmap[Cockpit_mode+(Current_display_mode?(Num_cockpits/2):0)].index];
515
516                 PIGGY_PAGE_IN(cockpit_bitmap[Cockpit_mode+(Current_display_mode?(Num_cockpits/2):0)]);
517
518 #ifdef WINDOWS
519                 dd_gr_set_current_canvas(NULL);
520                 game_win_init_cockpit_mask(1);
521                 dd_gr_set_current_canvas(dd_VR_offscreen_buffer);
522 #else
523                 gr_set_current_canvas(VR_offscreen_buffer);
524 #endif          
525
526                 WIN(DDGRLOCK(dd_grd_curcanv));
527                 gr_bitmap( 0, 0, bm );
528                 bm = &VR_offscreen_buffer->cv_bitmap;
529                 bm->bm_flags = BM_FLAG_TRANSPARENT;
530                 gr_ibitblt_find_hole_size ( bm, &minx, &miny, &maxx, &maxy );
531                 WIN(    win_get_span_list(bm, miny, maxy);
532                                 DDGRUNLOCK(dd_grd_curcanv)
533                         );
534
535 #ifndef WINDOWS
536 #ifndef __MSDOS__
537                 gr_ibitblt_create_mask( bm, minx, miny, maxx-minx+1, maxy-miny+1, VR_offscreen_buffer->cv_bitmap.bm_rowsize);
538 #else
539                 if ( Current_display_mode ) {
540 #if defined(POLY_ACC)
541                         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 );
542                         pa_clear_buffer(1, 0);      // clear offscreen to reduce white flash.
543 #else
544                         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 );
545 #endif
546                 } else
547                         Game_cockpit_copy_code  = gr_ibitblt_create_mask( bm, minx, miny, maxx-minx+1, maxy-miny+1, VR_offscreen_buffer->cv_bitmap.bm_rowsize );
548 #endif
549                 bm->bm_flags = 0;               // Clear all flags for offscreen canvas
550 #else
551                 Game_cockpit_copy_code  = (ubyte *)(1);
552                 bm->bm_flags = 0;               // Clear all flags for offscreen canvas
553 #endif
554                 game_init_render_sub_buffers( 0, 0, maxx-minx+1, maxy-miny+1 );
555                 break;
556         }
557
558         case CM_FULL_SCREEN:
559
560                 max_window_h = grd_curscreen->sc_h;
561
562                 if (Game_window_h > max_window_h || VR_screen_flags&VRF_ALLOW_COCKPIT)
563                         Game_window_h = max_window_h;
564
565                 if (Game_window_w > max_window_w || VR_screen_flags&VRF_ALLOW_COCKPIT)
566                         Game_window_w = max_window_w;
567
568                 Game_window_x = (max_window_w - Game_window_w)/2;
569                 Game_window_y = (max_window_h - Game_window_h)/2;
570
571                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w, Game_window_h );
572                 break;
573
574         case CM_STATUS_BAR:
575
576         max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(Current_display_mode?(Num_cockpits/2):0)].index].bm_h;
577
578                 if (Game_window_h > max_window_h)
579                         Game_window_h = max_window_h;
580
581                 if (Game_window_w > max_window_w)
582                         Game_window_w = max_window_w;
583
584                 Game_window_x = (max_window_w - Game_window_w)/2;
585                 Game_window_y = (max_window_h - Game_window_h)/2;
586
587                 game_init_render_sub_buffers( Game_window_x, Game_window_y, Game_window_w, Game_window_h );
588                 break;
589
590         case CM_LETTERBOX:      {
591                 int x,y,w,h;
592
593                 x = 0; w = VR_render_buffer[0].cv_bitmap.bm_w;          //VR_render_width;
594                 h = (VR_render_buffer[0].cv_bitmap.bm_h * 7) / 10;
595                 y = (VR_render_buffer[0].cv_bitmap.bm_h-h)/2;
596
597                 game_init_render_sub_buffers( x, y, w, h );
598                 break;
599                 }
600
601         }
602
603 WINDOS(
604         dd_gr_set_current_canvas(NULL),
605         gr_set_current_canvas(NULL)
606 );
607 }
608
609 //selects a given cockpit (or lack of one).  See types in game.h
610 void select_cockpit(int mode)
611 {
612         if (mode != Cockpit_mode) {             //new mode
613                 Cockpit_mode=mode;
614                 init_cockpit();
615         }
616 }
617
618 extern int last_drawn_cockpit[2];
619
620 //force cockpit redraw next time. call this if you've trashed the screen
621 void reset_cockpit()
622 {
623         force_cockpit_redraw=1;
624         last_drawn_cockpit[0] = -1;
625         last_drawn_cockpit[1] = -1;
626 }
627
628 // void HUD_clear_messages();                           //Already declared in gauges.h
629
630 //NEWVR
631 void VR_reset_params()
632 {
633         VR_eye_width = VR_SEPARATION;
634         VR_eye_offset = VR_PIXEL_SHIFT;
635         VR_eye_offset_changed = 2;
636 }
637
638 void game_init_render_sub_buffers( int x, int y, int w, int h )
639 {
640 #ifdef WINDOWS
641         dd_gr_init_sub_canvas( &dd_VR_render_sub_buffer[0], &dd_VR_render_buffer[0], x, y, w, h );
642         dd_gr_init_sub_canvas( &dd_VR_render_sub_buffer[1], &dd_VR_render_buffer[1], x, y, w, h );
643
644         dd_VR_render_sub_buffer[0].canvas.cv_bitmap.bm_x = 0;
645         dd_VR_render_sub_buffer[0].canvas.cv_bitmap.bm_y = 0;
646         dd_VR_render_sub_buffer[0].xoff = x;
647         dd_VR_render_sub_buffer[0].yoff = y;
648         dd_VR_render_sub_buffer[1].canvas.cv_bitmap.bm_x = 0;
649         dd_VR_render_sub_buffer[1].canvas.cv_bitmap.bm_y = 0;
650         dd_VR_render_sub_buffer[1].xoff = x;
651         dd_VR_render_sub_buffer[1].yoff = y;
652
653 #endif
654         if (Scanline_double) {
655                 #ifdef MACINTOSH
656                 if ( w & 0x3 )
657                         w &= ~0x3;
658                 gr_init_sub_canvas( &VR_render_sub_buffer[0], &VR_render_buffer[0], x, y, w/2, (h/2)+1);
659                 gr_init_sub_canvas( &VR_render_sub_buffer[1], &VR_render_buffer[1], x, y, w/2, (h/2)+1);
660                 #endif
661         } else {
662                 gr_init_sub_canvas( &VR_render_sub_buffer[0], &VR_render_buffer[0], x, y, w, h );
663                 gr_init_sub_canvas( &VR_render_sub_buffer[1], &VR_render_buffer[1], x, y, w, h );
664         }
665
666         #ifdef MACINTOSH
667                 #ifdef POLY_ACC
668                         if ( PAEnabled )
669                         {
670                                 TQARect newBounds;
671                                 
672                                 newBounds.left = x;
673                                 newBounds.right = x + w;
674                                 newBounds.top = y;
675                                 newBounds.bottom = y + h;
676                                 
677                                 pa_set_context(kGamePlayDrawContextID, &newBounds);             // must resize/create new context
678                         }
679                 #endif
680         #endif
681
682 #ifdef WINDOWS
683         VR_render_sub_buffer[0].cv_bitmap.bm_x = 0;
684         VR_render_sub_buffer[0].cv_bitmap.bm_y = 0;
685         VR_render_sub_buffer[1].cv_bitmap.bm_x = 0;
686         VR_render_sub_buffer[1].cv_bitmap.bm_y = 0;
687 #endif
688 }
689
690
691 #ifdef WINDOWS
692 // Sets up the canvases we will be rendering to (WIN95)
693 void game_init_render_buffers(int screen_mode, int render_w, int render_h, int render_method, int flags )
694 {
695 //      Hack for switching to higher that 640x480 modes (DDraw doesn't allow
696 //       creating surfaces greater than the current resolution
697
698         if (GRMODEINFO(rw) < render_w || GRMODEINFO(rh) < render_h) {
699                 render_w = GRMODEINFO(rw);
700                 render_h = GRMODEINFO(rh);
701         }
702
703         VR_screen_mode          = screen_mode;
704
705         VR_screen_flags =  flags;
706
707         VR_reset_params();
708         VR_render_mode  = render_method;
709
710         Game_window_w           = render_w;
711         Game_window_h           = render_h;
712
713         if (dd_VR_offscreen_buffer && dd_VR_offscreen_buffer != dd_grd_backcanv) {
714                 dd_gr_free_canvas(dd_VR_offscreen_buffer);
715         }
716
717         if ( (VR_render_mode==VR_AREA_DET) || (VR_render_mode==VR_INTERLACED ) )        {
718                 if ( render_h*2 < 200 ) {
719                         Int3();         // Not Supported yet!!!
720 //                      VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
721                 }
722                 else {
723                         Int3();         // Not Supported yet!!!
724 //                      VR_offscreen_buffer = gr_create_canvas( render_w, render_h*2 );
725                 }
726
727                 Int3();                 // Not Supported yet!!!
728 //              gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
729 //              gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, render_h, render_w, render_h );
730         }
731         else if (GRMODEINFO(paged) && !GRMODEINFO(dbuf)) {
732         //      Here we will make the VR_offscreen_buffer the 2nd page and hopefully
733         //      we can just flip it, saving a blt.  
734
735                 dd_VR_offscreen_buffer = dd_grd_backcanv;
736                 VR_offscreen_buffer = & dd_grd_backcanv->canvas;
737         }
738         else if (GRMODEINFO(dbuf)||GRMODEINFO(emul)) {
739         //      The offscreen buffer will be created.  We will just blt this
740         //      to the screen (which may be blted to the primary surface)
741                 if ( render_h < 200 ) {
742                         dd_VR_offscreen_buffer = dd_gr_create_canvas(render_w, 200);
743                         VR_offscreen_buffer = &dd_VR_offscreen_buffer->canvas;
744                 }
745                 else {
746                         dd_VR_offscreen_buffer = dd_gr_create_canvas(render_w, render_h);
747                         VR_offscreen_buffer = &dd_VR_offscreen_buffer->canvas;
748                 }
749         }
750
751         dd_gr_init_sub_canvas( &dd_VR_render_buffer[0], dd_VR_offscreen_buffer, 0, 0, render_w, render_h );
752         dd_gr_init_sub_canvas( &dd_VR_render_buffer[1], dd_VR_offscreen_buffer, 0, 0, render_w, render_h );
753         gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
754         gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, 0, render_w, render_h );
755
756         game_init_render_sub_buffers( 0, 0, render_w, render_h );
757 }
758
759 #else
760
761 // Sets up the canvases we will be rendering to (NORMAL VERSION)
762 void game_init_render_buffers(int screen_mode, int render_w, int render_h, int render_method, int flags )
763 {
764 //      if (vga_check_mode(screen_mode) != 0) 
765 //              Error("Cannot set requested video mode");
766
767         VR_screen_mode          =       screen_mode;
768
769         VR_screen_flags =  flags;
770
771 //NEWVR
772         VR_reset_params();
773         VR_render_mode  = render_method;
774
775         Game_window_w           = render_w;
776         Game_window_h           = render_h;
777
778         if (VR_offscreen_buffer) {
779                 gr_free_canvas(VR_offscreen_buffer);
780         }
781
782         if ( (VR_render_mode==VR_AREA_DET) || (VR_render_mode==VR_INTERLACED ) )        {
783                 if ( render_h*2 < 200 ) {
784                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
785                 }
786                 else {
787                         VR_offscreen_buffer = gr_create_canvas( render_w, render_h*2 );
788                 }
789
790                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
791                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, render_h, render_w, render_h );
792         }
793         else {
794                 if ( render_h < 200 ) {
795                         VR_offscreen_buffer = gr_create_canvas( render_w, 200 );
796                 }
797                 else {
798 #if defined(POLY_ACC)
799                         #ifndef MACINTOSH
800             VR_offscreen_buffer = gr_create_canvas( render_w, render_h );
801             d_free(VR_offscreen_buffer->cv_bitmap.bm_data);
802             gr_init_canvas(VR_offscreen_buffer, pa_get_buffer_address(1), BM_LINEAR15, render_w, render_h);
803                         #else
804                                 if ( PAEnabled || gConfigInfo.mAcceleration ) {
805                                         Cockpit_mode=CM_FULL_SCREEN;            // HACK HACK HACK HACK HACK!!!!
806                                         VR_offscreen_buffer = gr_create_canvas2(render_w, render_h, BM_LINEAR15);
807                                 } else
808                     VR_offscreen_buffer = gr_create_canvas( render_w, render_h );
809                         #endif
810 #else
811             VR_offscreen_buffer = gr_create_canvas( render_w, render_h );
812 #endif
813         }
814
815 #ifdef OGL
816                 VR_offscreen_buffer->cv_bitmap.bm_type = BM_OGL;
817 #endif
818
819                 gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, render_w, render_h );
820                 gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, 0, render_w, render_h );
821         }
822
823         game_init_render_sub_buffers( 0, 0, render_w, render_h );
824 }
825 #endif
826
827 //called to get the screen in a mode compatible with popup menus.
828 //if we can't have popups over the game screen, switch to menu mode.
829 void set_popup_screen(void)
830 {
831         //WIN(LoadCursorWin(MOUSE_DEFAULT_CURSOR));
832
833         if (! (VR_screen_flags & VRF_COMPATIBLE_MENUS))
834                 set_screen_mode(SCREEN_MENU);           //must switch to menu mode
835 }
836
837
838 //called to change the screen mode. Parameter sm is the new mode, one of
839 //SMODE_GAME or SMODE_EDITOR. returns mode acutally set (could be other
840 //mode if cannot init requested mode)
841 int set_screen_mode(int sm)
842 {
843 WIN(static int force_mode_change=0);
844 WIN(static int saved_window_w);
845 WIN(static int saved_window_h);
846
847 #ifdef EDITOR
848         if ( (sm==SCREEN_MENU) && (Screen_mode==SCREEN_EDITOR) )        {
849                 gr_set_current_canvas( Canv_editor );
850                 return 1;
851         }
852 #endif
853
854 #ifdef WINDOWS
855         if ( Screen_mode == sm && W95DisplayMode == VR_screen_mode) {
856                 dd_gr_set_current_canvas( &dd_VR_screen_pages[VR_current_page] );
857                 return 1;
858         }
859 #else
860         if ( Screen_mode == sm && VGA_current_mode == VR_screen_mode) {
861                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
862                 return 1;
863         }
864 #endif
865
866 #ifdef OGL
867         if ((Screen_mode == sm) && !((sm==SCREEN_GAME) && (grd_curscreen->sc_mode != VR_screen_mode) && (Screen_mode == SCREEN_GAME))) {
868              
869                 gr_set_current_canvas( &VR_screen_pages[VR_current_page] );
870                 ogl_set_screen_mode();
871                 return 1;
872         }
873 #endif
874
875 #ifdef EDITOR
876         Canv_editor = NULL;
877 #endif
878
879         Screen_mode = sm;
880
881         switch( Screen_mode )
882         {
883                 case SCREEN_MENU:
884                 #ifdef WINDOWS
885                         //mouse_set_mode(0);
886                         //ShowCursorW();
887                         if (!(VR_screen_flags & VRF_COMPATIBLE_MENUS)) {
888                         // HACK!!!  Meant to save window size when switching from
889                         // non-compat menu mode to menu mode.
890                                 saved_window_w = Game_window_w;
891                                 saved_window_h = Game_window_h; 
892                                 force_mode_change = 1;
893                         }
894                         if (W95DisplayMode != SM95_640x480x8) {
895 //@@                            piggy_bitmap_page_out_all_w();          // 2D GFX Flush cache.
896                                 DDSETDISPLAYMODE(SM95_640x480x8);
897                                 dd_gr_init_screen();
898                                 if (!gr_palette_faded_out) gr_palette_load(gr_palette);
899                         }
900
901                         dd_gr_init_sub_canvas(&dd_VR_screen_pages[0], dd_grd_screencanv,
902                                                                         0,0,
903                                                                         dd_grd_screencanv->canvas.cv_bitmap.bm_w,
904                                                                         dd_grd_screencanv->canvas.cv_bitmap.bm_h);
905                         dd_gr_init_sub_canvas(&dd_VR_screen_pages[1], dd_grd_screencanv,
906                                                                         0,0,
907                                                                         dd_grd_screencanv->canvas.cv_bitmap.bm_w,
908                                                                         dd_grd_screencanv->canvas.cv_bitmap.bm_h);
909                         MenuHires = 1;
910                         FontHires = FontHiresAvailable;
911
912                 #else
913                 {
914                         int menu_mode;
915
916                         MenuHires = MenuHiresAvailable;         //do highres if we can
917
918 #if defined(POLY_ACC)
919                                 #ifndef MACINTOSH
920                     menu_mode = MenuHires?SM(640,480):SM(320,200);
921                                 #else
922                                         menu_mode = PAEnabled?SM_640x480x15xPA:SM_640x480V;
923                                 #endif
924 #else
925             menu_mode = MenuHires?SM(640,480):SM(320,200);
926 #endif
927
928                         if (VGA_current_mode != menu_mode) {
929                                 if (gr_set_mode(menu_mode))
930                                         Error("Cannot set screen mode for menu");
931                                 if (!gr_palette_faded_out)
932                                         gr_palette_load(gr_palette);
933                         }
934
935                         gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
936                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
937
938                         FontHires = FontHiresAvailable && MenuHires;
939
940                 }
941                 #endif
942                 break;
943
944         case SCREEN_GAME:
945         #ifdef WINDOWS
946                 //mouse_set_mode(1);
947                 HideCursorW();
948                 if (force_mode_change || (W95DisplayMode != VR_screen_mode)) {
949
950                         DDSETDISPLAYMODE(VR_screen_mode);
951 //@@                    piggy_bitmap_page_out_all_w();          // 2D GFX Flush cache.
952                         dd_gr_init_screen();
953                         mprintf((0, "Reinitializing render buffers due to display mode change.\n"));
954                         game_init_render_buffers(W95DisplayMode,
955                                         GRMODEINFO(rw), GRMODEINFO(rh),
956                                         VR_render_mode, VR_screen_flags);
957
958                         reset_cockpit();
959                 }
960         #else
961                 if (VGA_current_mode != VR_screen_mode) {
962                         if (gr_set_mode(VR_screen_mode))        {
963                                 Error("Cannot set desired screen mode for game!");
964                                 //we probably should do something else here, like select a standard mode
965                         }
966                         #ifdef MACINTOSH
967                         if ( (Config_control_type == 1) && (Function_mode == FMODE_GAME) )
968                                 joydefs_calibrate();
969                         #endif
970                         reset_cockpit();
971                 }
972         #endif
973
974                 if ( VR_render_mode == VR_NONE )
975                 {
976                         max_window_w = grd_curscreen->sc_w;
977                         max_window_h = grd_curscreen->sc_h;
978
979                         if (VR_screen_flags & VRF_ALLOW_COCKPIT) {
980                                 if (Cockpit_mode == CM_STATUS_BAR)
981                         max_window_h = grd_curscreen->sc_h - GameBitmaps[cockpit_bitmap[CM_STATUS_BAR+(Current_display_mode?(Num_cockpits/2):0)].index].bm_h;
982                         }
983                         else if (Cockpit_mode != CM_LETTERBOX) 
984                                 Cockpit_mode = CM_FULL_SCREEN;
985
986               if (Game_window_h==0 || Game_window_h > max_window_h || Game_window_w==0 || Game_window_w > max_window_w) {
987                                 Game_window_w = max_window_w;
988                                 Game_window_h = max_window_h;
989               }
990
991                 }
992                 else
993                         Cockpit_mode = CM_FULL_SCREEN;
994
995                 #ifdef WINDOWS
996                 //      Super hack.   If we are switching from a 320x200 game to 640x480.
997                 //                                              and we were in a menumode when switching, we don't
998                 //                                              restore Game_window vals
999                         if (force_mode_change && (W95DisplayMode == SM95_320x200x8X)) {
1000                                 Game_window_w = saved_window_w;
1001                                 Game_window_h = saved_window_h;
1002                                 force_mode_change = 0;
1003                         }
1004                 #endif
1005
1006
1007         //      Define screen pages for game mode
1008         // If we designate through screen_flags to use paging, then do so.
1009                 WINDOS(
1010                         dd_gr_init_sub_canvas( &dd_VR_screen_pages[0], dd_grd_screencanv, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h ),
1011                         gr_init_sub_canvas( &VR_screen_pages[0], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h )
1012                 );
1013
1014                 if ( VR_screen_flags&VRF_USE_PAGING ) {
1015                 WINDOS(
1016                         dd_gr_init_sub_canvas( &dd_VR_screen_pages[1], dd_grd_backcanv, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h ),
1017                         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 )
1018                 );
1019                 }
1020                 else {
1021                 WINDOS (
1022                         dd_gr_init_sub_canvas( &dd_VR_screen_pages[1], dd_grd_screencanv, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h ),
1023                         gr_init_sub_canvas( &VR_screen_pages[1], &grd_curscreen->sc_canvas, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h )
1024                 );
1025                 }
1026
1027                 init_cockpit();
1028
1029         #ifdef WINDOWS
1030                 FontHires = FontHiresAvailable && (Current_display_mode != 0);
1031                 MenuHires = 1;
1032         #else
1033                 FontHires = FontHiresAvailable && (MenuHires = ((Current_display_mode != 0) && (Current_display_mode != 2)));
1034         #endif
1035
1036                 if ( VR_render_mode != VR_NONE )        {
1037                         // for 640x480 or higher, use hires font.
1038                         if (FontHiresAvailable && (grd_curscreen->sc_h > 400))
1039                                 FontHires = 1;
1040                         else
1041                                 FontHires = 0;
1042                 }
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 static const int max_fps = 80;
1198
1199 void calc_frame_time()
1200 {
1201         fix timer_value,last_frametime = FrameTime;
1202
1203         #if defined(TIMER_TEST) && !defined(NDEBUG)
1204         _last_frametime = last_frametime;
1205         #endif
1206
1207         timer_value = timer_get_fixed_seconds();
1208         FrameTime = timer_value - last_timer_value;
1209
1210         do {
1211             timer_value = timer_get_fixed_seconds();
1212             FrameTime = timer_value - last_timer_value;
1213             if (FrameTime < f1_0/max_fps);
1214             {
1215                 d_delay(1);
1216             }
1217         } while (FrameTime < f1_0/max_fps);
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         con_update();
2610         #ifndef NDEBUG
2611         //      Used to slow down frame rate for testing things.
2612         //      RenderFlag = 1; // DEBUG
2613         if (Debug_slowdown) {
2614                 int     h, i, j=0;
2615
2616                 for (h=0; h<Debug_slowdown; h++)
2617                         for (i=0; i<1000; i++)
2618                                 j += i;
2619         }
2620         #endif
2621
2622         #ifdef WINDOWS
2623         {
2624                 static int desc_dead_countdown=100;   /*  used if player shouldn't be playing */
2625
2626                 if (desc_id_exit_num) {                          // are we supposed to be checking
2627                         if (!(--desc_dead_countdown)) {// if so, at zero, then pull the plug
2628                                 char time_str[32], time_str2[32];
2629                         
2630                                 _ctime(&t_saved_time, time_str);
2631                                 _ctime(&t_current_time, time_str2);
2632
2633                                 Error ("EXPIRES %s.  YOUR TIME %s.\n", time_str, time_str2);
2634                                 Error ("Loading overlay -- error number: %d\n", (int)desc_id_exit_num);
2635                         }
2636                 }
2637         }
2638         #endif
2639
2640                 #ifndef RELEASE
2641                 if (FindArg("-invulnerability"))
2642                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2643                 #endif
2644
2645       
2646                 update_player_stats();
2647                 diminish_palette_towards_normal();              //      Should leave palette effect up for as long as possible by putting right before render.
2648                 do_afterburner_stuff();
2649                 do_cloak_stuff();
2650                 do_invulnerable_stuff();
2651                 remove_obsolete_stuck_objects();
2652                 init_ai_frame();
2653                 do_final_boss_frame();
2654                 // -- lightning_frame();
2655                 // -- recharge_energy_frame();
2656
2657                 if ((Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT) && (Players[Player_num].flags & PLAYER_FLAGS_HEADLIGHT_ON)) {
2658                         static int turned_off=0;
2659                         Players[Player_num].energy -= (FrameTime*3/8);
2660                         if (Players[Player_num].energy < i2f(10)) {
2661                                 if (!turned_off) {
2662                                         Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2663                                         turned_off = 1;
2664 #ifdef NETWORK
2665                                         if (Game_mode & GM_MULTI)
2666                                                 multi_send_flags(Player_num);           
2667 #endif
2668                                 }
2669                         }
2670                         else
2671                                 turned_off = 0;
2672
2673                         if (Players[Player_num].energy <= 0) {
2674                                 Players[Player_num].energy = 0;
2675                                 Players[Player_num].flags &= ~PLAYER_FLAGS_HEADLIGHT_ON;
2676 #ifdef NETWORK
2677                                 if (Game_mode & GM_MULTI)
2678                                         multi_send_flags(Player_num);           
2679 #endif
2680                         }
2681                 }
2682
2683
2684                 #ifdef EDITOR
2685                 check_create_player_path();
2686                 player_follow_path(ConsoleObject);
2687                 #endif
2688
2689                 #ifdef NETWORK
2690                 if (Game_mode & GM_MULTI)
2691         {
2692          multi_do_frame();
2693          if (Netgame.PlayTimeAllowed && ThisLevelTime>=i2f((Netgame.PlayTimeAllowed*5*60)))
2694              multi_check_for_killgoal_winner();
2695         }
2696
2697                 #endif
2698
2699                 if (RenderFlag) {
2700                         if (force_cockpit_redraw) {                     //screen need redrawing?
2701                                 init_cockpit();
2702                                 force_cockpit_redraw=0;
2703                         }
2704                         game_render_frame();
2705                         //show_extra_views();           //missile view, buddy bot, etc.
2706
2707                         #ifndef RELEASE
2708                         if (Saving_movie_frames)
2709                                 save_movie_frame();
2710                         #endif
2711
2712                 }
2713
2714
2715                 //mprintf(0,"Velocity %2.2f\n", f2fl(vm_vec_mag(&ConsoleObject->phys_info.velocity)));
2716
2717                 calc_frame_time();
2718
2719                 dead_player_frame();
2720                 if (Newdemo_state != ND_STATE_PLAYBACK)
2721                         do_controlcen_dead_frame();
2722
2723                 process_super_mines_frame();
2724                 do_seismic_stuff();
2725                 do_ambient_sounds();
2726
2727                 #ifndef NDEBUG
2728                 if (Speedtest_on)
2729                         speedtest_frame();
2730                 #endif
2731
2732                 if (ReadControlsFlag)
2733                         ReadControls();
2734                 else
2735                         memset(&Controls, 0, sizeof(Controls));
2736
2737                 GameTime += FrameTime;
2738
2739                 if (f2i(GameTime)/10 != f2i(GameTime-FrameTime)/10)
2740                         mprintf((0,"Gametime = %d secs\n",f2i(GameTime)));
2741
2742                 if (GameTime < 0 || GameTime > i2f(0x7fff - 600)) {
2743                         GameTime = FrameTime;   //wrap when goes negative, or gets within 10 minutes
2744                         mprintf((0,"GameTime reset to 0\n"));
2745                 }
2746
2747                 #ifndef NDEBUG
2748                 if (FindArg("-checktime") != 0)
2749                         if (GameTime >= i2f(600))               //wrap after 10 minutes
2750                                 GameTime = FrameTime;
2751                 #endif
2752
2753 #ifdef NETWORK
2754       if ((Game_mode & GM_MULTI) && Netgame.PlayTimeAllowed)
2755           ThisLevelTime +=FrameTime;
2756 #endif
2757
2758                 digi_sync_sounds();
2759
2760                 if (Endlevel_sequence) {
2761                         do_endlevel_frame();
2762                         powerup_grab_cheat_all();
2763                         do_special_effects();
2764                         return;                                 //skip everything else
2765                 }
2766
2767                 if (Newdemo_state != ND_STATE_PLAYBACK)
2768                         do_exploding_wall_frame();
2769                 if ((Newdemo_state != ND_STATE_PLAYBACK) || (Newdemo_vcr_state != ND_STATE_PAUSED)) {
2770                         do_special_effects();
2771                         wall_frame_process();
2772                         triggers_frame_process();
2773                 }
2774
2775
2776                 if (Control_center_destroyed)   {
2777                         if (Newdemo_state==ND_STATE_RECORDING )
2778                                 newdemo_record_control_center_destroyed();
2779                 }
2780
2781                 flash_frame();
2782
2783                 if ( Newdemo_state == ND_STATE_PLAYBACK )       {
2784                         newdemo_playback_one_frame();
2785                         if ( Newdemo_state != ND_STATE_PLAYBACK )               {
2786                                 longjmp( LeaveGame, 0 );                // Go back to menu
2787                         }
2788                 } else
2789                 { // Note the link to above!
2790
2791                         Players[Player_num].homing_object_dist = -1;            //      Assume not being tracked.  Laser_do_weapon_sequence modifies this.
2792
2793                         object_move_all();
2794                         powerup_grab_cheat_all();
2795
2796                         if (Endlevel_sequence)  //might have been started during move
2797                                 return;
2798
2799                         fuelcen_update_all();
2800
2801                         do_ai_frame_all();
2802
2803                         if (allowed_to_fire_laser())
2804                                 FireLaser();                            // Fire Laser!
2805
2806                         if (Auto_fire_fusion_cannon_time) {
2807                                 if (Primary_weapon != FUSION_INDEX)
2808                                         Auto_fire_fusion_cannon_time = 0;
2809                                 else if (GameTime + FrameTime/2 >= Auto_fire_fusion_cannon_time) {
2810                                         Auto_fire_fusion_cannon_time = 0;
2811                                         Global_laser_firing_count = 1;
2812                                 } else {
2813                                         vms_vector      rand_vec;
2814                                         fix                     bump_amount;
2815
2816                                         Global_laser_firing_count = 0;
2817
2818                                         ConsoleObject->mtype.phys_info.rotvel.x += (d_rand() - 16384)/8;
2819                                         ConsoleObject->mtype.phys_info.rotvel.z += (d_rand() - 16384)/8;
2820                                         make_random_vector(&rand_vec);
2821
2822                                         bump_amount = F1_0*4;
2823
2824                                         if (Fusion_charge > F1_0*2)
2825                                                 bump_amount = Fusion_charge*4;
2826
2827                                         bump_one_object(ConsoleObject, &rand_vec, bump_amount);
2828                                 }
2829                         }
2830
2831                         if (Global_laser_firing_count) {
2832                                 //      Don't cap here, gets capped in Laser_create_new and is based on whether in multiplayer mode, MK, 3/27/95
2833                                 // if (Fusion_charge > F1_0*2)
2834                                 //      Fusion_charge = F1_0*2;
2835                                 Global_laser_firing_count -= do_laser_firing_player();  //do_laser_firing(Players[Player_num].objnum, Primary_weapon);
2836                         }
2837
2838                         if (Global_laser_firing_count < 0)
2839                                 Global_laser_firing_count = 0;
2840                 }
2841
2842         if (Do_appearance_effect) {
2843                 create_player_appearance_effect(ConsoleObject);
2844                 Do_appearance_effect = 0;
2845 #ifdef NETWORK
2846                 if ((Game_mode & GM_MULTI) && Netgame.invul)
2847                 {
2848                         Players[Player_num].flags |= PLAYER_FLAGS_INVULNERABLE;
2849                         Players[Player_num].invulnerable_time = GameTime-i2f(27);
2850                         FakingInvul=1;
2851                 }
2852 #endif
2853                         
2854         }
2855
2856         omega_charge_frame();
2857         slide_textures();
2858         flicker_lights();
2859
2860         //!!hoard_light_pulse();                //do cool hoard light pulsing
2861
2862 }
2863
2864 //!!extern int Goal_blue_segnum,Goal_red_segnum;
2865 //!!extern int Hoard_goal_eclip;
2866 //!!
2867 //!!//do cool pulsing lights in hoard goals
2868 //!!hoard_light_pulse()
2869 //!!{
2870 //!!    if (Game_mode & GM_HOARD) {
2871 //!!            fix light;
2872 //!!            int frame;
2873 //!!
2874 //!!            frame = Effects[Hoard_goal_eclip].frame_count;
2875 //!!
2876 //!!            frame++;
2877 //!!
2878 //!!            if (frame >= Effects[Hoard_goal_eclip].vc.num_frames)
2879 //!!                    frame = 0;
2880 //!!
2881 //!!            light = abs(frame - 5) * f1_0 / 5;
2882 //!!
2883 //!!            Segment2s[Goal_red_segnum].static_light = Segment2s[Goal_blue_segnum].static_light = light;
2884 //!!    }
2885 //!!}
2886
2887
2888 ubyte   Slide_segs[MAX_SEGMENTS];
2889 int     Slide_segs_computed;
2890
2891 void compute_slide_segs(void)
2892 {
2893         int     segnum, sidenum;
2894
2895         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2896                 Slide_segs[segnum] = 0;
2897                 for (sidenum=0;sidenum<6;sidenum++) {
2898                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2899                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0)
2900                                 Slide_segs[segnum] |= 1 << sidenum;
2901                 }
2902         }
2903
2904         Slide_segs_computed = 1;
2905 }
2906
2907 //      -----------------------------------------------------------------------------
2908 void slide_textures(void)
2909 {
2910         int segnum,sidenum,i;
2911
2912         if (!Slide_segs_computed)
2913                 compute_slide_segs();
2914
2915         for (segnum=0;segnum<=Highest_segment_index;segnum++) {
2916                 if (Slide_segs[segnum]) {
2917                         for (sidenum=0;sidenum<6;sidenum++) {
2918                                 if (Slide_segs[segnum] & (1 << sidenum)) {
2919                                         int tmn = Segments[segnum].sides[sidenum].tmap_num;
2920                                         if (TmapInfo[tmn].slide_u != 0 || TmapInfo[tmn].slide_v != 0) {
2921                                                 for (i=0;i<4;i++) {
2922                                                         Segments[segnum].sides[sidenum].uvls[i].u += fixmul(FrameTime,TmapInfo[tmn].slide_u<<8);
2923                                                         Segments[segnum].sides[sidenum].uvls[i].v += fixmul(FrameTime,TmapInfo[tmn].slide_v<<8);
2924                                                         if (Segments[segnum].sides[sidenum].uvls[i].u > f2_0) {
2925                                                                 int j;
2926                                                                 for (j=0;j<4;j++)
2927                                                                         Segments[segnum].sides[sidenum].uvls[j].u -= f1_0;
2928                                                         }
2929                                                         if (Segments[segnum].sides[sidenum].uvls[i].v > f2_0) {
2930                                                                 int j;
2931                                                                 for (j=0;j<4;j++)
2932                                                                         Segments[segnum].sides[sidenum].uvls[j].v -= f1_0;
2933                                                         }
2934                                                         if (Segments[segnum].sides[sidenum].uvls[i].u < -f2_0) {
2935                                                                 int j;
2936                                                                 for (j=0;j<4;j++)
2937                                                                         Segments[segnum].sides[sidenum].uvls[j].u += f1_0;
2938                                                         }
2939                                                         if (Segments[segnum].sides[sidenum].uvls[i].v < -f2_0) {
2940                                                                 int j;
2941                                                                 for (j=0;j<4;j++)
2942                                                                         Segments[segnum].sides[sidenum].uvls[j].v += f1_0;
2943                                                         }
2944                                                 }
2945                                         }
2946                                 }
2947                         }
2948                 }
2949         }
2950 }
2951
2952 flickering_light Flickering_lights[MAX_FLICKERING_LIGHTS];
2953
2954 int Num_flickering_lights=0;
2955
2956 void flicker_lights()
2957 {
2958         int l;
2959         flickering_light *f;
2960
2961         f = Flickering_lights;
2962
2963         for (l=0;l<Num_flickering_lights;l++,f++) {
2964                 segment *segp = &Segments[f->segnum];
2965
2966                 //make sure this is actually a light
2967                 if (! (WALL_IS_DOORWAY(segp, f->sidenum) & WID_RENDER_FLAG))
2968                         continue;
2969                 if (! (TmapInfo[segp->sides[f->sidenum].tmap_num].lighting | TmapInfo[segp->sides[f->sidenum].tmap_num2 & 0x3fff].lighting))
2970                         continue;
2971
2972                 if (f->timer == 0x80000000)             //disabled
2973                         continue;
2974
2975                 if ((f->timer -= FrameTime) < 0) {
2976
2977                         while (f->timer < 0)
2978                                 f->timer += f->delay;
2979
2980                         f->mask = ((f->mask&0x80000000)?1:0) + (f->mask<<1);
2981
2982                         if (f->mask & 1)
2983                                 add_light(f->segnum,f->sidenum);
2984                         else
2985                                 subtract_light(f->segnum,f->sidenum);
2986                 }
2987         }
2988 }
2989
2990 //returns ptr to flickering light structure, or NULL if can't find
2991 flickering_light *find_flicker(int segnum,int sidenum)
2992 {
2993         int l;
2994         flickering_light *f;
2995
2996         //see if there's already an entry for this seg/side
2997
2998         f = Flickering_lights;
2999
3000         for (l=0;l<Num_flickering_lights;l++,f++)
3001                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
3002                         return f;
3003
3004         return NULL;
3005 }
3006
3007 //turn flickering off (because light has been turned off)
3008 void disable_flicker(int segnum,int sidenum)
3009 {
3010         flickering_light *f;
3011
3012         if ((f=find_flicker(segnum,sidenum)) != NULL)
3013                 f->timer = 0x80000000;
3014 }
3015
3016 //turn flickering off (because light has been turned on)
3017 void enable_flicker(int segnum,int sidenum)
3018 {
3019         flickering_light *f;
3020
3021         if ((f=find_flicker(segnum,sidenum)) != NULL)
3022                 f->timer = 0;
3023 }
3024
3025
3026 #ifdef EDITOR
3027
3028 //returns 1 if ok, 0 if error
3029 int add_flicker(int segnum,int sidenum,fix delay,ulong mask)
3030 {
3031         int l;
3032         flickering_light *f;
3033
3034         mprintf((0,"add_flicker: %d:%d %x %x\n",segnum,sidenum,delay,mask));
3035
3036         //see if there's already an entry for this seg/side
3037
3038         f = Flickering_lights;
3039
3040         for (l=0;l<Num_flickering_lights;l++,f++)
3041                 if (f->segnum == segnum && f->sidenum == sidenum)       //found it!
3042                         break;
3043
3044         if (mask==0) {          //clearing entry
3045                 if (l == Num_flickering_lights)
3046                         return 0;
3047                 else {
3048                         int i;
3049                         for (i=l;i<Num_flickering_lights-1;i++)
3050                                 Flickering_lights[i] = Flickering_lights[i+1];
3051                         Num_flickering_lights--;
3052                         return 1;
3053                 }
3054         }
3055
3056         if (l == Num_flickering_lights) {
3057                 if (Num_flickering_lights == MAX_FLICKERING_LIGHTS)
3058                         return 0;
3059                 else
3060                         Num_flickering_lights++;
3061         }
3062
3063         f->segnum = segnum;
3064         f->sidenum = sidenum;
3065         f->delay = f->timer = delay;
3066         f->mask = mask;
3067
3068         return 1;
3069 }
3070
3071 #endif
3072
3073 //      -----------------------------------------------------------------------------
3074 //      Fire Laser:  Registers a laser fire, and performs special stuff for the fusion
3075 //                                  cannon.
3076 void FireLaser()
3077 {
3078
3079         Global_laser_firing_count += Weapon_info[Primary_weapon_to_weapon_info[Primary_weapon]].fire_count * (Controls.fire_primary_state || Controls.fire_primary_down_count);
3080
3081         if ((Primary_weapon == FUSION_INDEX) && (Global_laser_firing_count)) {
3082                 if ((Players[Player_num].energy < F1_0*2) && (Auto_fire_fusion_cannon_time == 0)) {
3083                         Global_laser_firing_count = 0;
3084                 } else {
3085                         if (Fusion_charge == 0)
3086                                 Players[Player_num].energy -= F1_0*2;
3087
3088                         Fusion_charge += FrameTime;
3089                         Players[Player_num].energy -= FrameTime;
3090
3091                         if (Players[Player_num].energy <= 0) {
3092                                 Players[Player_num].energy = 0;
3093                                 Auto_fire_fusion_cannon_time = GameTime -1;     //      Fire now!
3094                         } else
3095                                 Auto_fire_fusion_cannon_time = GameTime + FrameTime/2 + 1;
3096                                                                                                 //      Fire the fusion cannon at this time in the future.
3097
3098                         if (Fusion_charge < F1_0*2)
3099                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, 0, Fusion_charge >> 11);
3100                         else
3101                                 PALETTE_FLASH_ADD(Fusion_charge >> 11, Fusion_charge >> 11, 0);
3102
3103                         if (GameTime < Fusion_last_sound_time)          //gametime has wrapped
3104                                 Fusion_next_sound_time = Fusion_last_sound_time = GameTime;
3105
3106                         if (Fusion_next_sound_time < GameTime) {
3107                                 if (Fusion_charge > F1_0*2) {
3108                                         digi_play_sample( 11, F1_0 );
3109                                         apply_damage_to_player(ConsoleObject, ConsoleObject, d_rand() * 4);
3110                                 } else {
3111                                         create_awareness_event(ConsoleObject, PA_WEAPON_ROBOT_COLLISION);
3112                                         digi_play_sample( SOUND_FUSION_WARMUP, F1_0 );
3113                                         #ifdef NETWORK
3114                                         if (Game_mode & GM_MULTI)
3115                                                 multi_send_play_sound(SOUND_FUSION_WARMUP, F1_0);
3116                                         #endif
3117                                 }
3118                                 Fusion_last_sound_time = GameTime;
3119                                 Fusion_next_sound_time = GameTime + F1_0/8 + d_rand()/4;
3120                         }
3121                 }
3122         }
3123
3124 }
3125
3126
3127 //      -------------------------------------------------------------------------------------------------------
3128 //      If player is close enough to objnum, which ought to be a powerup, pick it up!
3129 //      This could easily be made difficulty level dependent.
3130 void powerup_grab_cheat(object *player, int objnum)
3131 {
3132         fix     powerup_size;
3133         fix     player_size;
3134         fix     dist;
3135
3136         Assert(Objects[objnum].type == OBJ_POWERUP);
3137
3138         powerup_size = Objects[objnum].size;
3139         player_size = player->size;
3140
3141         dist = vm_vec_dist_quick(&Objects[objnum].pos, &player->pos);
3142
3143         if ((dist < 2*(powerup_size + player_size)) && !(Objects[objnum].flags & OF_SHOULD_BE_DEAD)) {
3144                 vms_vector      collision_point;
3145
3146                 vm_vec_avg(&collision_point, &Objects[objnum].pos, &player->pos);
3147                 collide_player_and_powerup(player, &Objects[objnum], &collision_point);
3148         }
3149 }
3150
3151 //      -------------------------------------------------------------------------------------------------------
3152 //      Make it easier to pick up powerups.
3153 //      For all powerups in this segment, pick them up at up to twice pickuppable distance based on dot product
3154 //      from player to powerup and player's forward vector.
3155 //      This has the effect of picking them up more easily left/right and up/down, but not making them disappear
3156 //      way before the player gets there.
3157 void powerup_grab_cheat_all(void)
3158 {
3159         segment *segp;
3160         int             objnum;
3161
3162         segp = &Segments[ConsoleObject->segnum];
3163         objnum = segp->objects;
3164
3165         while (objnum != -1) {
3166                 if (Objects[objnum].type == OBJ_POWERUP)
3167                         powerup_grab_cheat(ConsoleObject, objnum);
3168                 objnum = Objects[objnum].next;
3169         }
3170
3171 }
3172
3173 int     Last_level_path_created = -1;
3174
3175 #ifdef SHOW_EXIT_PATH
3176
3177 //      ------------------------------------------------------------------------------------------------------------------
3178 //      Create path for player from current segment to goal segment.
3179 //      Return true if path created, else return false.
3180 int mark_player_path_to_segment(int segnum)
3181 {
3182         int             i;
3183         object  *objp = ConsoleObject;
3184         short           player_path_length=0;
3185         int             player_hide_index=-1;
3186
3187         if (Last_level_path_created == Current_level_num) {
3188                 return 0;
3189         }
3190
3191         Last_level_path_created = Current_level_num;
3192
3193         if (create_path_points(objp, objp->segnum, segnum, Point_segs_free_ptr, &player_path_length, 100, 0, 0, -1) == -1) {
3194                 mprintf((0, "Unable to form path of length %i for myself\n", 100));
3195                 return 0;
3196         }
3197
3198         player_hide_index = Point_segs_free_ptr - Point_segs;
3199         Point_segs_free_ptr += player_path_length;
3200
3201         if (Point_segs_free_ptr - Point_segs + MAX_PATH_LENGTH*2 > MAX_POINT_SEGS) {
3202                 mprintf((1, "Can't create path.  Not enough point_segs.\n"));
3203                 ai_reset_all_paths();
3204                 return 0;
3205         }
3206
3207         for (i=1; i<player_path_length; i++) {
3208                 int                     segnum, objnum;
3209                 vms_vector      seg_center;
3210                 object          *obj;
3211
3212                 segnum = Point_segs[player_hide_index+i].segnum;
3213                 mprintf((0, "%3i ", segnum));
3214                 seg_center = Point_segs[player_hide_index+i].point;
3215
3216                 objnum = obj_create( OBJ_POWERUP, POW_ENERGY, segnum, &seg_center, &vmd_identity_matrix, Powerup_info[POW_ENERGY].size, CT_POWERUP, MT_NONE, RT_POWERUP);
3217                 if (objnum == -1) {
3218                         Int3();         //      Unable to drop energy powerup for path
3219                         return 1;
3220                 }
3221
3222                 obj = &Objects[objnum];
3223                 obj->rtype.vclip_info.vclip_num = Powerup_info[obj->id].vclip_num;
3224                 obj->rtype.vclip_info.frametime = Vclip[obj->rtype.vclip_info.vclip_num].frame_time;
3225                 obj->rtype.vclip_info.framenum = 0;
3226                 obj->lifeleft = F1_0*100 + d_rand() * 4;
3227         }
3228
3229         mprintf((0, "\n"));
3230         return 1;
3231 }
3232
3233 //      Return true if it happened, else return false.
3234 int create_special_path(void)
3235 {
3236         int     i,j;
3237
3238         //      ---------- Find exit doors ----------
3239         for (i=0; i<=Highest_segment_index; i++)
3240                 for (j=0; j<MAX_SIDES_PER_SEGMENT; j++)
3241                         if (Segments[i].children[j] == -2) {
3242                                 mprintf((0, "Exit at segment %i\n", i));
3243                                 return mark_player_path_to_segment(i);
3244                         }
3245
3246         return 0;
3247 }
3248
3249 #endif
3250
3251
3252 #ifndef RELEASE
3253 int     Max_obj_count_mike = 0;
3254
3255 //      Shows current number of used objects.
3256 void show_free_objects(void)
3257 {
3258         if (!(FrameCount & 8)) {
3259                 int     i;
3260                 int     count=0;
3261
3262                 mprintf((0, "Highest_object_index = %3i, MAX_OBJECTS = %3i, now used = ", Highest_object_index, MAX_OBJECTS));
3263
3264                 for (i=0; i<=Highest_object_index; i++)
3265                         if (Objects[i].type != OBJ_NONE)
3266                                 count++;
3267
3268                 mprintf((0, "%3i", count));
3269
3270                 if (count > Max_obj_count_mike) {
3271                         Max_obj_count_mike = count;
3272                         mprintf((0, " ***"));
3273                 }
3274
3275                 mprintf((0, "\n"));
3276         }
3277
3278 }
3279
3280 #endif
3281
3282 #ifdef WINDOWS
3283 void game_win_init_cockpit_mask(int sram)
3284 {
3285         if (dd_VR_offscreen_buffer && dd_VR_offscreen_buffer != dd_grd_backcanv) {
3286                 dd_gr_free_canvas(dd_VR_offscreen_buffer);
3287         }
3288
3289         if (GRMODEINFO(paged) && !GRMODEINFO(dbuf)) {
3290         //      Here we will make the VR_offscreen_buffer the 2nd page and hopefully
3291         //      we can just flip it, saving a blt.  
3292                 Int3();
3293         }
3294         else if (GRMODEINFO(dbuf)||GRMODEINFO(emul)) {
3295         //      The offscreen buffer will be created.  We will just blt this
3296         //      to the screen (which may be blted to the primary surface)
3297                 if ( grd_curscreen->sc_h < 200 ) {
3298                         dd_VR_offscreen_buffer = dd_gr_create_canvas(grd_curscreen->sc_w, 200);
3299                         VR_offscreen_buffer = &dd_VR_offscreen_buffer->canvas;
3300                         if (sram) {
3301                                 DDFreeSurface(dd_VR_offscreen_buffer->lpdds);
3302                                 dd_VR_offscreen_buffer->lpdds = DDCreateSysMemSurface(grd_curscreen->sc_w, 200);
3303                                 dd_VR_offscreen_buffer->sram = 1;
3304                         }
3305                 }
3306                 else {
3307                         dd_VR_offscreen_buffer = dd_gr_create_canvas(grd_curscreen->sc_w, grd_curscreen->sc_h);
3308                         VR_offscreen_buffer = &dd_VR_offscreen_buffer->canvas;
3309                         if (sram) {
3310                                 DDFreeSurface(dd_VR_offscreen_buffer->lpdds);
3311                                 dd_VR_offscreen_buffer->lpdds = DDCreateSysMemSurface(grd_curscreen->sc_w, grd_curscreen->sc_h);
3312                                 dd_VR_offscreen_buffer->sram = 1;
3313                         }
3314                 }
3315         }
3316
3317         dd_gr_init_sub_canvas( &dd_VR_render_buffer[0], dd_VR_offscreen_buffer, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
3318         dd_gr_init_sub_canvas( &dd_VR_render_buffer[1], dd_VR_offscreen_buffer, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
3319         gr_init_sub_canvas( &VR_render_buffer[0], VR_offscreen_buffer, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
3320         gr_init_sub_canvas( &VR_render_buffer[1], VR_offscreen_buffer, 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
3321
3322         game_init_render_sub_buffers( 0, 0, grd_curscreen->sc_w, grd_curscreen->sc_h );
3323 }
3324
3325 //@@void game_win_init_cockpit_mask()
3326 //@@{
3327 //@@    char title_pal[768];
3328 //@@    dd_grs_canvas ccanv;
3329 //@@    int pcx_error;
3330 //@@    LPDIRECTDRAWSURFACE dds;
3331 //@@
3332 //@@    dds = DDCreateSurface(GRMODEINFO(w), GRMODEINFO(h), 1);
3333 //@@    Assert(dds != NULL);
3334 //@@    
3335 //@@    _lpDDSMask = dds;
3336 //@@    ccanv.lpdds = dds;
3337 //@@    dd_gr_reinit_canvas(&ccanv);
3338 //@@
3339 //@@    dd_gr_set_current_canvas(&ccanv);
3340 //@@    DDGRLOCK(dd_grd_curcanv)
3341 //@@    {
3342 //@@            if (W95DisplayMode == SM95_640x480x8) {
3343 //@@                    pcx_error=pcx_read_bitmap( "MASKB.PCX", &grd_curcanv->cv_bitmap, 
3344 //@@                            grd_curcanv->cv_bitmap.bm_type, 
3345 //@@                            title_pal );
3346 //@@            }
3347 //@@            else {
3348 //@@                    pcx_error=pcx_read_bitmap( "MASK.PCX", &grd_curcanv->cv_bitmap, 
3349 //@@                            grd_curcanv->cv_bitmap.bm_type, 
3350 //@@                            title_pal );
3351 //@@            }
3352 //@@    }
3353 //@@    DDGRUNLOCK(dd_grd_curcanv);
3354 //@@
3355 //@@    Assert(pcx_error == PCX_ERROR_NONE);
3356 //@@    Game_cockpit_copy_code = (ubyte *)(0xABADC0DE);
3357 //@@}
3358
3359 #endif
3360
3361 /*
3362  * reads a flickering_light structure from a CFILE
3363  */
3364 void flickering_light_read(flickering_light *fl, CFILE *fp)
3365 {
3366         fl->segnum = cfile_read_short(fp);
3367         fl->sidenum = cfile_read_short(fp);
3368         fl->mask = cfile_read_int(fp);
3369         fl->timer = cfile_read_fix(fp);
3370         fl->delay = cfile_read_fix(fp);
3371 }