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