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