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