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