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