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