]> icculus.org git repositories - taylor/freespace2.git/blob - src/freespace2/freespace.cpp
New graphics stubbing arrangement
[taylor/freespace2.git] / src / freespace2 / freespace.cpp
1 /*
2  * $Logfile: /Freespace2/code/Freespace2/FreeSpace.cpp $
3  * $Revision$
4  * $Date$
5  * $Author$
6  *
7  * Freespace main body
8  *
9  * $Log$
10  * Revision 1.5  2002/05/28 04:07:28  theoddone33
11  * New graphics stubbing arrangement
12  *
13  * Revision 1.4  2002/05/27 22:46:52  theoddone33
14  * Remove more undefined symbols
15  *
16  * Revision 1.3  2002/05/26 23:31:18  relnev
17  * added a few files that needed to be compiled
18  *
19  * freespace.cpp: now compiles
20  *
21  * Revision 1.2  2002/05/07 03:16:44  theoddone33
22  * The Great Newline Fix
23  *
24  * Revision 1.1.1.1  2002/05/03 03:28:09  root
25  * Initial import.
26  *
27  * 
28  * 201   6/16/00 3:15p Jefff
29  * sim of the year dvd version changes, a few german soty localization
30  * fixes
31  * 
32  * 200   11/03/99 11:06a Jefff
33  * 1.2 checksums
34  * 
35  * 199   10/26/99 5:07p Jamest
36  * fixed jeffs dumb debug code
37  * 
38  * 198   10/25/99 5:53p Jefff
39  * call control_config_common_init() on startup
40  * 
41  * 197   10/14/99 10:18a Daveb
42  * Fixed incorrect CD checking problem on standalone server.
43  * 
44  * 196   10/13/99 9:22a Daveb
45  * Fixed Fred jumpnode placing bug. Fixed 1024 glide tiled texture problem
46  * related to movies. Fixed launcher spawning from PXO screen.
47  * 
48  * 195   10/06/99 11:05a Jefff
49  * new oem upsell 3 hotspot coords
50  * 
51  * 194   10/06/99 10:31a Jefff
52  * OEM updates
53  * 
54  * 193   10/01/99 9:10a Daveb
55  * V 1.1 PATCH
56  * 
57  * 192   9/15/99 4:57a Dave
58  * Updated ships.tbl checksum
59  * 
60  * 191   9/15/99 3:58a Dave
61  * Removed framerate warning at all times.
62  * 
63  * 190   9/15/99 3:16a Dave
64  * Remove mt-011.fs2 from the builtin mission list.
65  * 
66  * 189   9/15/99 1:45a Dave
67  * Don't init joystick on standalone. Fixed campaign mode on standalone.
68  * Fixed no-score-report problem in TvT
69  * 
70  * 188   9/14/99 6:08a Dave
71  * Updated (final) single, multi, and campaign list.
72  * 
73  * 187   9/14/99 3:26a Dave
74  * Fixed laser fogging problem in nebula (D3D)> Fixed multiplayer
75  * respawn-too-early problem. Made a few crash points safe.
76  * 
77  * 186   9/13/99 4:52p Dave
78  * RESPAWN FIX
79  * 
80  * 185   9/12/99 8:09p Dave
81  * Fixed problem where skip-training button would cause mission messages
82  * not to get paged out for the current mission.
83  * 
84  * 184   9/10/99 11:53a Dave
85  * Shutdown graphics before sound to eliminate apparent lockups when
86  * Directsound decides to be lame. Fix TOPMOST problem with D3D windows.
87  * 
88  * 183   9/09/99 11:40p Dave
89  * Handle an Assert() in beam code. Added supernova sounds. Play the right
90  * 2 end movies properly, based upon what the player did in the mission.
91  * 
92  * 182   9/08/99 10:29p Dave
93  * Make beam sound pausing and unpausing much safer.
94  * 
95  * 181   9/08/99 10:01p Dave
96  * Make sure game won't run in a drive's root directory. Make sure
97  * standalone routes suqad war messages properly to the host.
98  * 
99  * 180   9/08/99 3:22p Dave
100  * Updated builtin mission list.
101  * 
102  * 179   9/08/99 12:01p Jefff
103  * fixed Game_builtin_mission_list typo on Training-2.fs2
104  * 
105  * 178   9/08/99 9:48a Andsager
106  * Add force feedback for engine wash.
107  * 
108  * 177   9/07/99 4:01p Dave
109  * Fixed up a string.tbl paroblem (self destruct message). Make sure IPX
110  * does everything properly (setting up address when binding). Remove
111  * black rectangle background from UI_INPUTBOX.
112  * 
113  * 176   9/13/99 2:40a Dave
114  * Comment in full 80 minute CD check for RELEASE_REAL builds.
115  * 
116  * 175   9/06/99 6:38p Dave
117  * Improved CD detection code.
118  * 
119  * 174   9/06/99 1:30a Dave
120  * Intermediate checkin. Started on enforcing CD-in-drive to play the
121  * game.
122  * 
123  * 173   9/06/99 1:16a Dave
124  * Make sure the user sees the intro movie.
125  * 
126  * 172   9/04/99 8:00p Dave
127  * Fixed up 1024 and 32 bit movie support.
128  * 
129  * 171   9/03/99 1:32a Dave
130  * CD checking by act. Added support to play 2 cutscenes in a row
131  * seamlessly. Fixed super low level cfile bug related to files in the
132  * root directory of a CD. Added cheat code to set campaign mission # in
133  * main hall.
134  * 
135  * 170   9/01/99 10:49p Dave
136  * Added nice SquadWar checkbox to the client join wait screen.
137  * 
138  * 169   9/01/99 10:14a Dave
139  * Pirate bob.
140  * 
141  * 168   8/29/99 4:51p Dave
142  * Fixed damaged checkin.
143  * 
144  * 167   8/29/99 4:18p Andsager
145  * New "burst" limit for friendly damage.  Also credit more damage done
146  * against large friendly ships.
147  * 
148  * 166   8/27/99 6:38p Alanl
149  * crush the blasted repeating messages bug
150  * 
151  * 164   8/26/99 9:09p Dave
152  * Force framerate check in everything but a RELEASE_REAL build.
153  * 
154  * 163   8/26/99 9:45a Dave
155  * First pass at easter eggs and cheats.
156  * 
157  * 162   8/24/99 8:55p Dave
158  * Make sure nondimming pixels work properly in tech menu.
159  * 
160  * 161   8/24/99 1:49a Dave
161  * Fixed client-side afterburner stuttering. Added checkbox for no version
162  * checking on PXO join. Made button info passing more friendly between
163  * client and server.
164  * 
165  * 160   8/22/99 5:53p Dave
166  * Scoring fixes. Added self destruct key. Put callsigns in the logfile
167  * instead of ship designations for multiplayer players.
168  * 
169  * 159   8/22/99 1:19p Dave
170  * Fixed up http proxy code. Cleaned up scoring code. Reverse the order in
171  * which d3d cards are detected.
172  * 
173  * 158   8/20/99 2:09p Dave
174  * PXO banner cycling.
175  * 
176  * 157   8/19/99 10:59a Dave
177  * Packet loss detection.
178  * 
179  * 156   8/19/99 10:12a Alanl
180  * preload mission-specific messages on machines greater than 48MB
181  * 
182  * 155   8/16/99 4:04p Dave
183  * Big honking checkin.
184  * 
185  * 154   8/11/99 5:54p Dave
186  * Fixed collision problem. Fixed standalone ghost problem.
187  * 
188  * 153   8/10/99 7:59p Jefff
189  * XSTR'ed some stuff
190  * 
191  * 152   8/10/99 6:54p Dave
192  * Mad optimizations. Added paging to the nebula effect.
193  * 
194  * 151   8/10/99 3:44p Jefff
195  * loads Intelligence information on startup
196  * 
197  * 150   8/09/99 3:47p Dave
198  * Fixed incorrect nebula regeneration. Default HUD to low-contrast in
199  * non-nebula missions.
200  * 
201  * 149   8/09/99 2:21p Andsager
202  * Fix patching from multiplayer direct to launcher update tab.
203  * 
204  * 148   8/09/99 10:36a Dave
205  * Version info for game.
206  * 
207  * 147   8/06/99 9:46p Dave
208  * Hopefully final changes for the demo.
209  * 
210  * 146   8/06/99 3:34p Andsager
211  * Make title version info "(D)" -> "D"  show up nicely
212  * 
213  * 145   8/06/99 2:59p Adamp
214  * Fixed NT launcher/update problem.
215  * 
216  * 144   8/06/99 1:52p Dave
217  * Bumped up MAX_BITMAPS for the demo.
218  * 
219  * 143   8/06/99 12:17p Andsager
220  * Demo: down to just 1 demo dog
221  * 
222  * 142   8/05/99 9:39p Dave
223  * Yet another new checksum.
224  * 
225  * 141   8/05/99 6:19p Dave
226  * New demo checksums.
227  * 
228  * 140   8/05/99 5:31p Andsager
229  * Up demo version 1.01
230  * 
231  * 139   8/05/99 4:22p Andsager
232  * No time limit on upsell screens.  Reverse order of display of upsell
233  * bitmaps.
234  * 
235  * 138   8/05/99 4:17p Dave
236  * Tweaks to client interpolation.
237  * 
238  * 137   8/05/99 3:52p Danw
239  * 
240  * 136   8/05/99 3:01p Danw
241  * 
242  * 135   8/05/99 2:43a Anoop
243  * removed duplicate definition.
244  * 
245  * 134   8/05/99 2:13a Dave
246  * Fixed build error.
247  * 
248  * 133   8/05/99 2:05a Dave
249  * Whee.
250  * 
251  * 132   8/05/99 1:22a Andsager
252  * fix upsell bug.
253  * 
254  * 131   8/04/99 9:51p Andsager
255  * Add title screen to demo
256  * 
257  * 130   8/04/99 6:47p Jefff
258  * fixed link error resulting from #ifdefs
259  * 
260  * 129   8/04/99 6:26p Dave
261  * Updated ship tbl checksum.
262  * 
263  * 128   8/04/99 5:40p Andsager
264  * Add multiple demo dogs
265  * 
266  * 127   8/04/99 5:36p Andsager
267  * Show upsell screens at end of demo campaign before returning to main
268  * hall.
269  * 
270  * 126   8/04/99 11:42a Danw
271  * tone down EAX reverb
272  * 
273  * 125   8/04/99 11:23a Dave
274  * Updated demo checksums.
275  * 
276  * 124   8/03/99 11:02p Dave
277  * Maybe fixed sync problems in multiplayer.
278  * 
279  * 123   8/03/99 6:21p Jefff
280  * minor text change
281  * 
282  * 122   8/03/99 3:44p Andsager
283  * Launch laucher if trying to run FS without first having configured
284  * system.
285  * 
286  * 121   8/03/99 12:45p Dave
287  * Update checksums.
288  * 
289  * 120   8/02/99 9:13p Dave
290  * Added popup tips.
291  * 
292  * 119   7/30/99 10:31p Dave
293  * Added comm menu to the configurable hud files.
294  * 
295  * 118   7/30/99 5:17p Andsager
296  * first fs2demo checksums
297  * 
298  * 117   7/29/99 3:09p Anoop
299  * 
300  * 116   7/29/99 12:05a Dave
301  * Nebula speed optimizations.
302  * 
303  * 115   7/27/99 8:59a Andsager
304  * Make major, minor version consistent for all builds.  Only show major
305  * and minor for launcher update window.
306  * 
307  * 114   7/26/99 5:50p Dave
308  * Revised ingame join. Better? We'll see....
309  * 
310  * 113   7/26/99 5:27p Andsager
311  * Add training mission as builtin to demo build
312  * 
313  * 112   7/24/99 1:54p Dave
314  * Hud text flash gauge. Reworked dead popup to use 4 buttons in red-alert
315  * missions.
316  * 
317  * 111   7/22/99 4:00p Dave
318  * Fixed beam weapon muzzle glow rendering. Externalized hud shield info.
319  * 
320  * 110   7/21/99 8:10p Dave
321  * First run of supernova effect.
322  * 
323  * 109   7/20/99 1:49p Dave
324  * Peter Drake build. Fixed some release build warnings.
325  * 
326  * 108   7/19/99 2:26p Andsager
327  * set demo multiplayer missions
328  * 
329  * 107   7/18/99 5:19p Dave
330  * Jump node icon. Fixed debris fogging. Framerate warning stuff.
331  * 
332  * 106   7/16/99 1:50p Dave
333  * 8 bit aabitmaps. yay.
334  * 
335  * 105   7/15/99 3:07p Dave
336  * 32 bit detection support. Mouse coord commandline.
337  * 
338  * 104   7/15/99 2:13p Dave
339  * Added 32 bit detection.
340  * 
341  * 103   7/15/99 9:20a Andsager
342  * FS2_DEMO initial checkin
343  * 
344  * 102   7/14/99 11:02a Dave
345  * Skill level default back to easy. Blech.
346  * 
347  * 101   7/09/99 5:54p Dave
348  * Seperated cruiser types into individual types. Added tons of new
349  * briefing icons. Campaign screen.
350  * 
351  * 100   7/08/99 4:43p Andsager
352  * New check for sparky_hi and print if not found.
353  * 
354  * 99    7/08/99 10:53a Dave
355  * New multiplayer interpolation scheme. Not 100% done yet, but still
356  * better than the old way.
357  * 
358  * 98    7/06/99 4:24p Dave
359  * Mid-level checkin. Starting on some potentially cool multiplayer
360  * smoothness crap.
361  * 
362  * 97    7/06/99 3:35p Andsager
363  * Allow movie to play before red alert mission.
364  * 
365  * 96    7/03/99 5:50p Dave
366  * Make rotated bitmaps draw properly in padlock views.
367  * 
368  * 95    7/02/99 9:55p Dave
369  * Player engine wash sound.
370  * 
371  * 94    7/02/99 4:30p Dave
372  * Much more sophisticated lightning support.
373  * 
374  * 93    6/29/99 7:52p Dave
375  * Put in exception handling in FS2.
376  * 
377  * 92    6/22/99 9:37p Dave
378  * Put in pof spewing.
379  * 
380  * 91    6/16/99 4:06p Dave
381  * New pilot info popup. Added new draw-bitmap-as-poly function.
382  * 
383  * 90    6/15/99 1:56p Andsager
384  * For release builds, allow start up in high res only with
385  * sparky_hi._fs2.vp
386  * 
387  * 89    6/15/99 9:34a Dave
388  * Fixed key checking in single threaded version of the stamp notification
389  * screen. 
390  * 
391  * 88    6/09/99 2:55p Andsager
392  * Allow multiple asteroid subtypes (of large, medium, small) and follow
393  * family.
394  * 
395  * 87    6/08/99 1:14a Dave
396  * Multi colored hud test.
397  * 
398  * 86    6/04/99 9:52a Dave
399  * Fixed some rendering problems.
400  * 
401  * 85    6/03/99 10:15p Dave
402  * Put in temporary main hall screen.
403  * 
404  * 84    6/02/99 6:18p Dave
405  * Fixed TNT lockup problems! Wheeeee!
406  * 
407  * 83    6/01/99 3:52p Dave
408  * View footage screen. Fixed xstrings to not display the & symbol. Popup,
409  * dead popup, pxo find player popup, pxo private room popup.
410  * 
411  * 82    5/26/99 1:28p Jasenw
412  * changed coords for loading ani
413  * 
414  * 81    5/26/99 11:46a Dave
415  * Added ship-blasting lighting and made the randomization of lighting
416  * much more customizable.
417  * 
418  * 80    5/24/99 5:45p Dave
419  * Added detail levels to the nebula, with a decent speedup. Split nebula
420  * lightning into its own section.
421  * 
422  * 
423  */
424
425 #ifndef PLAT_UNIX
426 #include <windows.h>
427 #include <process.h>
428 #include <direct.h>
429 #include <io.h>
430 #else
431 #endif
432
433 #include <stdio.h>
434 #include <stdlib.h>
435 #include <time.h>
436
437 #include "pstypes.h"
438 #include "systemvars.h"
439 #include "key.h"
440 #include "vecmat.h"
441 #include "2d.h"
442 #include "3d.h"
443 #include "starfield.h"
444 #include "lighting.h"
445 #include "weapon.h"
446 #include "ship.h"
447 #include "palman.h"
448 #include "osapi.h"
449 #include "fireballs.h"
450 #include "debris.h"
451 #include "timer.h"
452 #include "fix.h"
453 #include "floating.h"
454 #include "gamesequence.h"
455 #include "radar.h"
456 #include "optionsmenu.h"
457 #include "playermenu.h"
458 #include "trainingmenu.h"
459 #include "techmenu.h"
460 #include "ai.h"
461 #include "hud.h"
462 #include "hudmessage.h"
463 #include "psnet.h"
464 #include "missiongoals.h"
465 #include "missionparse.h"
466 #include "bmpman.h"
467 #include "joy.h"
468 #include "joy_ff.h"
469 #include "multi.h"
470 #include "multiutil.h"
471 #include "multimsgs.h"
472 #include "multiui.h"
473 #include "cfile.h"
474 #include "player.h"
475 #include "freespace.h"
476 #include "managepilot.h"
477 #include "sound.h"
478 #include "contexthelp.h"
479 #include "mouse.h"
480 #include "joy.h"
481 #include "missionbrief.h"
482 #include "missiondebrief.h"
483 #include "ui.h"
484 #include "missionshipchoice.h"
485 #include "model.h"
486 #include "hudconfig.h"
487 #include "controlsconfig.h"
488 #include "missionmessage.h"
489 #include "missiontraining.h"
490 #include "hudets.h"
491 #include "hudtarget.h"
492 #include "gamesnd.h"
493 #include "rbaudio.h"
494 #include "winmidi.h"
495 #include "eventmusic.h"
496 #include "animplay.h"
497 #include "missionweaponchoice.h"
498 #include "missionlog.h"
499 #include "audiostr.h"
500 #include "hudlock.h"
501 #include "missioncampaign.h"
502 #include "credits.h"
503 #include "missionhotkey.h"
504 #include "objectsnd.h"
505 #include "cmeasure.h"
506 #include "ai.h"
507 #include "linklist.h"
508 #include "shockwave.h"
509 #include "afterburner.h"
510 #include "scoring.h"
511 #include "stats.h"
512 #include "cmdline.h"
513 #include "timer.h"
514 #include "stand_gui.h"
515 #include "pcxutils.h"
516 #include "hudtargetbox.h"
517 #include "multi_xfer.h"
518 #include "hudescort.h"
519 #include "multiutil.h"
520 #include "sexp.h"
521 #include "medals.h"
522 #include "multiteamselect.h"
523 #include "ds3d.h"
524 #include "shipfx.h"
525 #include "readyroom.h"
526 #include "mainhallmenu.h"
527 #include "multilag.h"
528 #include "trails.h"
529 #include "particle.h"
530 #include "popup.h"
531 #include "multi_ingame.h"
532 #include "snazzyui.h"
533 #include "asteroid.h"
534 #include "popupdead.h"
535 #include "multi_voice.h"
536 #include "missioncmdbrief.h"
537 #include "redalert.h"
538 #include "gameplayhelp.h"
539 #include "multilag.h"
540 #include "staticrand.h"
541 #include "multi_pmsg.h"
542 #include "levelpaging.h"
543 #include "observer.h"
544 #include "multi_pause.h"
545 #include "multi_endgame.h"
546 #include "cutscenes.h"
547 #include "multi_respawn.h"
548 // #include "movie.h"
549 #include "multi_obj.h"
550 #include "multi_log.h"
551 #include "emp.h"
552 #include "localize.h"
553 #include "osregistry.h"
554 #include "barracks.h"
555 #include "missionpause.h"
556 #include "font.h"
557 #include "alphacolors.h"
558 #include "objcollide.h"
559 #include "flak.h"
560 #include "neb.h"
561 #include "neblightning.h"
562 #include "shipcontrails.h"
563 #include "awacs.h"
564 #include "beam.h"
565 #include "multi_dogfight.h"
566 #include "multi_rate.h"
567 #include "muzzleflash.h"
568 #include "encrypt.h"
569 #include "demo.h"
570 #include "version.h"
571 #include "mainhalltemp.h"
572 #include "exceptionhandler.h"
573 #ifndef PLAT_UNIX
574 #include "glide.h"
575 #endif
576 #include "supernova.h"
577 #include "hudshield.h"
578 // #include "names.h"
579 #include "shiphit.h"
580 #include "missionloopbrief.h"
581
582 #ifdef NDEBUG
583 #ifdef FRED
584 #error macro FRED is defined when trying to build release Fred.  Please undefine FRED macro in build settings
585 #endif
586 #endif
587
588 //      Revision history.
589 //      Full version:
590 //    1.00.04   5/26/98 MWA -- going final (12 pm)
591 //    1.00.03   5/26/98 MWA -- going final (3 am)
592 //    1.00.02   5/25/98 MWA -- going final
593 //    1.00.01   5/25/98 MWA -- going final
594 //              0.90            5/21/98 MWA -- getting ready for final.
595 //              0.10            4/9/98.  Set by MK.
596 //
597 //      Demo version: (obsolete since DEMO codebase split from tree)
598 //              0.03            4/10/98 AL.     Interplay rev
599 //              0.02            4/8/98  MK.     Increased when this system was modified.
600 //              0.01            4/7/98? AL.     First release to Interplay QA.
601 //
602 //      OEM version:
603 //              1.00            5/28/98 AL.     First release to Interplay QA.
604
605 void game_level_init(int seed = -1);
606 void game_post_level_init();
607 void game_do_frame();
608 void game_update_missiontime(); // called from game_do_frame() and navmap_do_frame()
609 void game_reset_time();
610 void game_show_framerate();                     // draws framerate in lower right corner
611
612 int Game_no_clear = 0;
613
614 int Pofview_running = 0;
615 int Nebedit_running = 0;
616
617 typedef struct big_expl_flash {
618         float max_flash_intensity;      // max intensity
619         float cur_flash_intensity;      // cur intensity
620         int     flash_start;            // start time
621 } big_expl_flash;
622
623 #define FRAME_FILTER 16
624
625 #define DEFAULT_SKILL_LEVEL     1
626 int     Game_skill_level = DEFAULT_SKILL_LEVEL;
627
628 #define VIEWER_ZOOM_DEFAULT 0.75f                       //      Default viewer zoom, 0.625 as per multi-lateral agreement on 3/24/97
629 float Viewer_zoom = VIEWER_ZOOM_DEFAULT;
630
631 #define EXE_FNAME                       ("fs2.exe")
632 #define LAUNCHER_FNAME  ("freespace2.exe")
633
634 // JAS: Code for warphole camera.
635 // Needs to be cleaned up.
636 vector Camera_pos = { 0.0f, 0.0f, 0.0f };
637 vector Camera_velocity = { 0.0f, 0.0f, 0.0f };
638 vector Camera_desired_velocity = { 0.0f, 0.0f, 0.0f };
639 matrix Camera_orient = IDENTITY_MATRIX;
640 float Camera_damping = 1.0f;
641 float Camera_time = 0.0f;
642 float Warpout_time = 0.0f;
643 int Warpout_forced = 0;         // Set if this is a forced warpout that cannot be cancelled.
644 int Warpout_sound = -1;
645 void camera_move();
646 int Use_joy_mouse = 0;
647 int Use_palette_flash = 1;
648 #ifndef NDEBUG
649 int Use_fullscreen_at_startup = 0;
650 #endif
651 int Show_area_effect = 0;
652 object  *Last_view_target = NULL;
653
654 int dogfight_blown = 0;
655
656 int     frame_int = -1;
657 float frametimes[FRAME_FILTER];
658 float frametotal = 0.0f;
659 float flFrametime;
660
661 #ifdef RELEASE_REAL
662         int     Show_framerate = 0;
663 #else 
664         int     Show_framerate = 1;
665 #endif
666
667 int     Framerate_cap = 120;
668 int     Show_mem = 0;
669 int     Show_cpu = 0;
670 int     Show_target_debug_info = 0;
671 int     Show_target_weapons = 0;
672 int     Game_font = -1;
673 static int Show_player_pos = 0;         // debug console command to show player world pos on HUD
674
675 int Debug_octant = -1;
676
677 fix Game_time_compression = F1_0;
678
679 // if the ships.tbl the player has is valid
680 int Game_ships_tbl_valid = 0;
681
682 // if the weapons.tbl the player has is valid
683 int Game_weapons_tbl_valid = 0;
684
685 #ifndef NDEBUG
686 int Test_begin = 0;
687 extern int      Player_attacking_enabled;
688 int Show_net_stats;
689 #endif
690
691 int Pre_player_entry;
692
693 int     Fred_running = 0;
694 char Game_current_mission_filename[MAX_FILENAME_LEN];
695 int game_single_step = 0;
696 int last_single_step=0;
697
698 extern int MSG_WINDOW_X_START;  // used to position mission_time and shields output
699 extern int MSG_WINDOW_Y_START;
700 extern int MSG_WINDOW_HEIGHT;
701
702 int game_zbuffer = 1;
703 //static int Game_music_paused;
704 static int Game_paused;
705
706 int Game_level_seed;
707
708 #define EXPIRE_BAD_CHECKSUM                     1
709 #define EXPIRE_BAD_TIME                                 2
710
711 extern void ssm_init();
712 extern void ssm_level_init();
713 extern void ssm_process();
714
715 // static variable to contain the time this version was built
716 // commented out for now until
717 // I figure out how to get the username into the file
718 //LOCAL char freespace_build_time[] = "Compiled on:"__DATE__" "__TIME__" by "__USER__;
719
720 // defines and variables used for dumping frame for making trailers.
721 #ifndef NDEBUG
722 int Debug_dump_frames = 0;                      // Set to 0 to not dump frames, else equal hz to dump. (15 or 30 probably)
723 int Debug_dump_trigger = 0;
724 int Debug_dump_frame_count;
725 int Debug_dump_frame_num = 0;
726 #define DUMP_BUFFER_NUM_FRAMES  1                       // store every 15 frames
727 #endif
728
729 // amount of time to wait after the player has died before we display the death died popup
730 #define PLAYER_DIED_POPUP_WAIT          2500
731 int Player_died_popup_wait = -1;
732 int Player_multi_died_check = -1;
733
734 // builtin mission list stuff
735 #ifdef FS2_DEMO
736         int Game_builtin_mission_count = 6;
737         fs_builtin_mission Game_builtin_mission_list[MAX_BUILTIN_MISSIONS] = {
738                 { "SPDemo-01.fs2",                              (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     ""              },
739                 { "SPDemo-02.fs2",                              (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     ""              },
740                 { "DemoTrain.fs2",                              (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     ""              },
741                 { "Demo.fc2",                                           (FSB_FROM_VOLITION | FSB_CAMPAIGN_FILE),                                        ""              },
742                 { "MPDemo-01.fs2",                              (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
743                 { "Demo-DOG-01.fs2",                            (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
744         };
745 #elif defined(PD_BUILD)
746         int Game_builtin_mission_count = 4;
747         fs_builtin_mission Game_builtin_mission_list[MAX_BUILTIN_MISSIONS] = {
748                 { "sm1-01.fs2",                                 (FSB_FROM_VOLITION),                                                                                            ""              },
749                 { "sm1-05.fs2",                                 (FSB_FROM_VOLITION),                                                                                            ""              },              
750                 { "sm1-01",                                                     (FSB_FROM_VOLITION),                                                                                            ""              },
751                 { "sm1-05",                                                     (FSB_FROM_VOLITION),                                                                                            ""              },              
752         };
753 #elif defined(MULTIPLAYER_BETA)
754         int Game_builtin_mission_count = 17;
755         fs_builtin_mission Game_builtin_mission_list[MAX_BUILTIN_MISSIONS] = {
756                 // multiplayer beta
757                 { "md-01.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
758                 { "md-02.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
759                 { "md-03.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
760                 { "md-04.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
761                 { "md-05.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
762                 { "md-06.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
763                 { "md-07.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
764                 { "mt-02.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
765                 { "mt-03.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
766                 { "m-03.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
767                 { "m-04.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
768                 { "m-05.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""              },
769                 { "templar-01.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""              },
770                 { "templar-02.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""              },
771                 { "templar-03a.fs2",                            (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""              },
772                 { "templar-04a.fs2",                            (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""              },
773                 { "templar.fc2",                                        (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN_FILE),    ""              },      
774         };
775 #elif defined(OEM_BUILD)
776         int Game_builtin_mission_count = 17;
777         fs_builtin_mission Game_builtin_mission_list[MAX_BUILTIN_MISSIONS] = {
778                 // oem version - act 1 only
779                 { "freespace2oem.fc2",                  (FSB_FROM_VOLITION | FSB_CAMPAIGN_FILE),                                        "" },
780                         
781                 // act 1
782                 { "sm1-01.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
783                 { "sm1-02.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
784                 { "sm1-03.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
785                 { "sm1-04.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
786                 { "sm1-05.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
787                 { "sm1-06.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
788                 { "sm1-07.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
789                 { "sm1-08.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
790                 { "sm1-09.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
791                 { "sm1-10.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
792                 { "training-1.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
793                 { "training-2.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
794                 { "training-3.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
795                 { "tsm-104.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
796                 { "tsm-105.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       },
797                 { "tsm-106.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_1       }
798         };
799 #else 
800         int Game_builtin_mission_count = 92;
801         fs_builtin_mission Game_builtin_mission_list[MAX_BUILTIN_MISSIONS] = {
802                 // single player campaign
803                 { "freespace2.fc2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN_FILE),                                        "" },
804                         
805                 // act 1
806                 { "sm1-01.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
807                 { "sm1-02.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
808                 { "sm1-03.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
809                 { "sm1-04.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
810                 { "sm1-05.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
811                 { "sm1-06.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
812                 { "sm1-07.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
813                 { "sm1-08.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
814                 { "sm1-09.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
815                 { "sm1-10.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
816                 { "loop1-1.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
817                 { "loop1-2.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
818                 { "loop1-3.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
819                 { "training-1.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
820                 { "training-2.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
821                 { "training-3.fs2",                             (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
822                 { "tsm-104.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
823                 { "tsm-105.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
824                 { "tsm-106.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_2       },
825
826                 // act 2
827                 { "sm2-01.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
828                 { "sm2-02.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
829                 { "sm2-03.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
830                 { "sm2-04.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
831                 { "sm2-05.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
832                 { "sm2-06.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
833                 { "sm2-07.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
834                 { "sm2-08.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
835                 { "sm2-09.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
836                 { "sm2-10.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
837
838                 // act 3
839                 { "sm3-01.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
840                 { "sm3-02.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
841                 { "sm3-03.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
842                 { "sm3-04.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
843                 { "sm3-05.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
844                 { "sm3-06.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
845                 { "sm3-07.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
846                 { "sm3-08.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
847                 { "sm3-09.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
848                 { "sm3-10.fs2",                                 (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
849                 { "loop2-1.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },              
850                 { "loop2-2.fs2",                                        (FSB_FROM_VOLITION | FSB_CAMPAIGN),                                                     FS_CDROM_VOLUME_3       },
851
852                 // multiplayer missions
853
854                 // gauntlet
855                 { "g-shi.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
856                 { "g-ter.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
857                 { "g-vas.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
858
859                 // coop
860                 { "m-01.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
861                 { "m-02.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
862                 { "m-03.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
863                 { "m-04.fs2",                                           (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
864
865                 // dogfight
866                 { "mdh-01.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
867                 { "mdh-02.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
868                 { "mdh-03.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
869                 { "mdh-04.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
870                 { "mdh-05.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
871                 { "mdh-06.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
872                 { "mdh-07.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
873                 { "mdh-08.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
874                 { "mdh-09.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
875                 { "mdl-01.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
876                 { "mdl-02.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
877                 { "mdl-03.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
878                 { "mdl-04.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
879                 { "mdl-05.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
880                 { "mdl-06.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
881                 { "mdl-07.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
882                 { "mdl-08.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
883                 { "mdl-09.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
884                 { "mdm-01.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
885                 { "mdm-02.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
886                 { "mdm-03.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
887                 { "mdm-04.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
888                 { "mdm-05.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
889                 { "mdm-06.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
890                 { "mdm-07.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
891                 { "mdm-08.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
892                 { "mdm-09.fs2",                                 (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },              
893                 { "osdog.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
894
895                 // TvT          
896                 { "mt-01.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
897                 { "mt-02.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
898                 { "mt-03.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
899                 { "mt-04.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
900                 { "mt-05.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
901                 { "mt-06.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
902                 { "mt-07.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
903                 { "mt-08.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
904                 { "mt-09.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },
905                 { "mt-10.fs2",                                          (FSB_FROM_VOLITION | FSB_MULTI),                                                                ""                                              },                              
906
907                 // campaign
908                 { "templar.fc2",                                (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN_FILE),                                    "" },
909                 { "templar-01.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""                                              },                              
910                 { "templar-02.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""                                              },                              
911                 { "templar-03.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""                                              },                              
912                 { "templar-04.fs2",                             (FSB_FROM_VOLITION | FSB_MULTI | FSB_CAMPAIGN),                 ""                                              },                              
913         };
914 #endif
915
916
917 // Internal function prototypes
918 void game_maybe_draw_mouse(float frametime);
919 void init_animating_pointer();
920 void load_animating_pointer(char *filename, int dx, int dy);
921 void unload_animating_pointer();
922 void game_do_training_checks();
923 void game_shutdown(void);
924 void game_show_event_debug(float frametime);
925 void game_event_debug_init();
926 void game_frame();
927 void demo_upsell_show_screens();
928 void game_start_subspace_ambient_sound();
929 void game_stop_subspace_ambient_sound();
930 void verify_ships_tbl();
931 void verify_weapons_tbl();
932 void display_title_screen();
933
934 // loading background filenames
935 static char *Game_loading_bground_fname[GR_NUM_RESOLUTIONS] = {
936         "LoadingBG",            // GR_640
937         "2_LoadingBG"           // GR_1024
938 };
939
940
941 static char *Game_loading_ani_fname[GR_NUM_RESOLUTIONS] = {
942         "Loading.ani",          // GR_640
943         "2_Loading.ani"         // GR_1024
944 };
945
946 #if defined(FS2_DEMO)
947 static char *Game_demo_title_screen_fname[GR_NUM_RESOLUTIONS] = {
948         "PreLoad",
949         "2_PreLoad"
950 };
951 #elif defined(OEM_BUILD)
952 static char *Game_demo_title_screen_fname[GR_NUM_RESOLUTIONS] = {
953         "OEMPreLoad",
954         "2_OEMPreLoad"
955 };
956 #endif
957
958 // cdrom stuff
959 char Game_CDROM_dir[MAX_PATH_LEN];
960 int init_cdrom();
961
962 // How much RAM is on this machine. Set in WinMain
963 uint Freespace_total_ram = 0;
964
965 // game flash stuff
966 float Game_flash_red = 0.0f;
967 float Game_flash_green = 0.0f;
968 float Game_flash_blue = 0.0f;
969 float Sun_spot = 0.0f;
970 big_expl_flash Big_expl_flash = {0.0f, 0.0f, 0};
971
972 // game shudder stuff (in ms)
973 int Game_shudder_time = -1;
974 int Game_shudder_total = 0;
975 float Game_shudder_intensity = 0.0f;                    // should be between 0.0 and 100.0
976
977 // EAX stuff
978 sound_env Game_sound_env;
979 //sound_env Game_default_sound_env = {SND_ENV_AUDITORIUM, 0.25f, 0.35f, 3.0f};
980 sound_env Game_default_sound_env = {SND_ENV_GENERIC, 0.2F,0.2F,1.0F};
981
982 int Game_sound_env_update_timestamp;
983
984 // WARPIN CRAP BEGIN --------------------------------------------------------------------------------------------
985
986
987 // WARPIN CRAP END --------------------------------------------------------------------------------------------
988
989 fs_builtin_mission *game_find_builtin_mission(char *filename)
990 {
991         int idx;
992
993         // look through all existing builtin missions
994         for(idx=0; idx<Game_builtin_mission_count; idx++){
995                 if(!stricmp(Game_builtin_mission_list[idx].filename, filename)){
996                         return &Game_builtin_mission_list[idx];
997                 }
998         }
999
1000         // didn't find it
1001         return NULL;
1002 }
1003
1004 int game_get_default_skill_level()
1005 {
1006         return DEFAULT_SKILL_LEVEL;
1007 }
1008
1009 // Resets the flash
1010 void game_flash_reset()
1011 {
1012         Game_flash_red = 0.0f;
1013         Game_flash_green = 0.0f;
1014         Game_flash_blue = 0.0f;
1015         Sun_spot = 0.0f;
1016         Big_expl_flash.max_flash_intensity = 0.0f;
1017         Big_expl_flash.cur_flash_intensity = 0.0f;
1018         Big_expl_flash.flash_start = 0;
1019 }
1020
1021 float Gf_critical = -1.0f;                                      // framerate we should be above on the average for this mission
1022 float Gf_critical_time = 0.0f;                  // how much time we've been at the critical framerate
1023
1024 void game_framerate_check_init()
1025 {
1026         // zero critical time
1027         Gf_critical_time = 0.0f;
1028                 
1029         // nebula missions
1030         if(The_mission.flags & MISSION_FLAG_FULLNEB){
1031                 // if this is a glide card
1032                 if(gr_screen.mode == GR_GLIDE){
1033 #ifndef PLAT_UNIX               
1034                         extern GrHwConfiguration hwconfig;
1035
1036                         // voodoo 2/3
1037                         if(hwconfig.SSTs[0].sstBoard.VoodooConfig.fbRam >= 4){
1038                                 Gf_critical = 15.0f;
1039                         }
1040                         // voodoo 1
1041                         else {
1042                                 Gf_critical = 10.0f;
1043                         }
1044 #else
1045                         STUB_FUNCTION;
1046                         
1047                         Gf_critical = 15.0f;
1048 #endif                                          
1049                 }
1050                 // d3d. only care about good cards here I guess (TNT)
1051                 else {
1052                         Gf_critical = 15.0f;                    
1053                 }
1054         } else {
1055                 // if this is a glide card
1056                 if(gr_screen.mode == GR_GLIDE){
1057 #ifndef PLAT_UNIX               
1058                         extern GrHwConfiguration hwconfig;
1059
1060                         // voodoo 2/3
1061                         if(hwconfig.SSTs[0].sstBoard.VoodooConfig.fbRam >= 4){
1062                                 Gf_critical = 25.0f;
1063                         }
1064                         // voodoo 1
1065                         else {
1066                                 Gf_critical = 20.0f;
1067                         }
1068 #else
1069                         STUB_FUNCTION;
1070                         
1071                         Gf_critical = 25.0f;
1072 #endif                                          
1073                 }
1074                 // d3d. only care about good cards here I guess (TNT)
1075                 else {
1076                         Gf_critical = 25.0f;
1077                 }
1078         }
1079 }
1080
1081 extern float Framerate;
1082 void game_framerate_check()
1083 {
1084         int y_start = 100;
1085         
1086         // if the current framerate is above the critical level, add frametime
1087         if(Framerate >= Gf_critical){
1088                 Gf_critical_time += flFrametime;
1089         }       
1090
1091         if(!Show_framerate){
1092                 return;
1093         }
1094
1095         // display if we're above the critical framerate
1096         if(Framerate < Gf_critical){
1097                 gr_set_color_fast(&Color_bright_red);
1098                 gr_string(200, y_start, "Framerate warning");
1099
1100                 y_start += 10;
1101         }
1102
1103         // display our current pct of good frametime
1104         if(f2fl(Missiontime) >= 0.0f){
1105                 float pct = (Gf_critical_time / f2fl(Missiontime)) * 100.0f;
1106
1107                 if(pct >= 85.0f){
1108                         gr_set_color_fast(&Color_bright_green);
1109                 } else {
1110                         gr_set_color_fast(&Color_bright_red);
1111                 }
1112
1113                 gr_printf(200, y_start, "%d%%", (int)pct);
1114
1115                 y_start += 10;
1116         }
1117 }
1118
1119
1120 // Adds a flash effect.  These can be positive or negative.
1121 // The range will get capped at around -1 to 1, so stick 
1122 // with a range like that.
1123 void game_flash( float r, float g, float b )
1124 {
1125         Game_flash_red += r;
1126         Game_flash_green += g;
1127         Game_flash_blue += b;
1128
1129         if ( Game_flash_red < -1.0f )   {
1130                 Game_flash_red = -1.0f;
1131         } else if ( Game_flash_red > 1.0f )     {
1132                 Game_flash_red = 1.0f;
1133         }
1134
1135         if ( Game_flash_green < -1.0f ) {
1136                 Game_flash_green = -1.0f;
1137         } else if ( Game_flash_green > 1.0f )   {
1138                 Game_flash_green = 1.0f;
1139         }
1140
1141         if ( Game_flash_blue < -1.0f )  {
1142                 Game_flash_blue = -1.0f;
1143         } else if ( Game_flash_blue > 1.0f )    {
1144                 Game_flash_blue = 1.0f;
1145         }
1146
1147 }
1148
1149 // Adds a flash for Big Ship explosions
1150 // cap range from 0 to 1
1151 void big_explosion_flash(float flash)
1152 {
1153         Big_expl_flash.flash_start = timestamp(1);
1154
1155         if (flash > 1.0f) {
1156                 flash = 1.0f;
1157         } else if (flash < 0.0f) {
1158                 flash = 0.0f;
1159         }
1160
1161         Big_expl_flash.max_flash_intensity = flash;
1162         Big_expl_flash.cur_flash_intensity = 0.0f;
1163 }
1164
1165 //      Amount to diminish palette towards normal, per second.
1166 #define DIMINISH_RATE   0.75f
1167 #define SUN_DIMINISH_RATE       6.00f
1168
1169 int Sun_drew = 0;
1170
1171 float sn_glare_scale = 1.7f;
1172 DCF(sn_glare, "")
1173 {
1174         dc_get_arg(ARG_FLOAT);
1175         sn_glare_scale = Dc_arg_float;
1176 }
1177
1178 float Supernova_last_glare = 0.0f;
1179 void game_sunspot_process(float frametime)
1180 {
1181         int n_lights, idx;
1182         int sn_stage;
1183         float Sun_spot_goal = 0.0f;
1184
1185         // supernova
1186         sn_stage = supernova_active();
1187         if(sn_stage){           
1188                 // sunspot differently based on supernova stage
1189                 switch(sn_stage){
1190                 // approaching. player still in control
1191                 case 1:                 
1192                         float pct;
1193                         pct = (1.0f - (supernova_time_left() / SUPERNOVA_CUT_TIME));
1194
1195                         vector light_dir;                               
1196                         light_get_global_dir(&light_dir, 0);
1197                         float dot;
1198                         dot = vm_vec_dot( &light_dir, &Eye_matrix.fvec );
1199                         
1200                         if(dot >= 0.0f){
1201                                 // scale it some more
1202                                 dot = dot * (0.5f + (pct * 0.5f));
1203                                 dot += 0.05f;                                   
1204
1205                                 Sun_spot_goal += (dot * sn_glare_scale);
1206                         }
1207
1208                         // draw the sun glow
1209                         if ( !shipfx_eye_in_shadow( &Eye_position, Viewer_obj, 0 ) )    {
1210                                 // draw the glow for this sun
1211                                 stars_draw_sun_glow(0); 
1212                         }
1213
1214                         Supernova_last_glare = Sun_spot_goal;
1215                         break;
1216
1217                 // camera cut. player not in control. note : at this point camera starts out facing the sun. so we can go nice and bright
1218                 case 2:                                         
1219                 case 3:
1220                         Sun_spot_goal = 0.9f;
1221                         Sun_spot_goal += (1.0f - (supernova_time_left() / SUPERNOVA_CUT_TIME)) * 0.1f;
1222
1223                         if(Sun_spot_goal > 1.0f){
1224                                 Sun_spot_goal = 1.0f;
1225                         }
1226
1227                         Sun_spot_goal *= sn_glare_scale;
1228                         Supernova_last_glare = Sun_spot_goal;
1229                         break;          
1230
1231                 // fade to white. display dead popup
1232                 case 4:
1233                 case 5:
1234                         Supernova_last_glare += (2.0f * flFrametime);
1235                         if(Supernova_last_glare > 2.0f){
1236                                 Supernova_last_glare = 2.0f;
1237                         }
1238
1239                         Sun_spot_goal = Supernova_last_glare;
1240                         break;
1241                 }
1242         
1243                 Sun_drew = 0;                           
1244         } else {
1245                 if ( Sun_drew ) {
1246                         // check sunspots for all suns
1247                         n_lights = light_get_global_count();
1248
1249                         // check
1250                         for(idx=0; idx<n_lights; idx++){
1251                                 //(vector *eye_pos, matrix *eye_orient)
1252                                 if ( !shipfx_eye_in_shadow( &Eye_position, Viewer_obj, idx ) )  {
1253
1254                                         vector light_dir;                               
1255                                         light_get_global_dir(&light_dir, idx);
1256
1257                                         float dot = vm_vec_dot( &light_dir, &Eye_matrix.fvec )*0.5f+0.5f;
1258
1259                                         Sun_spot_goal += (float)pow(dot,85.0f);
1260
1261                                         // draw the glow for this sun
1262                                         stars_draw_sun_glow(idx);                               
1263                                 } else {
1264                                         Sun_spot_goal = 0.0f;
1265                                 }
1266                         }
1267
1268                         Sun_drew = 0;
1269                 } else {
1270                         Sun_spot_goal = 0.0f;
1271                 }
1272         }
1273
1274         float dec_amount = frametime*SUN_DIMINISH_RATE;
1275
1276         if ( Sun_spot < Sun_spot_goal ) {
1277                 Sun_spot += dec_amount;
1278                 if ( Sun_spot > Sun_spot_goal ) {
1279                         Sun_spot = Sun_spot_goal;
1280                 }
1281         } else if ( Sun_spot > Sun_spot_goal )  {
1282                 Sun_spot -= dec_amount;
1283                 if ( Sun_spot < Sun_spot_goal ) {
1284                         Sun_spot = Sun_spot_goal;
1285                 }
1286         }
1287 }
1288
1289
1290 // Call once a frame to diminish the
1291 // flash effect to 0.
1292 void game_flash_diminish(float frametime)
1293 {
1294         float dec_amount = frametime*DIMINISH_RATE;
1295
1296         if ( Game_flash_red > 0.0f ) {
1297                 Game_flash_red -= dec_amount;           
1298                 if ( Game_flash_red < 0.0f )
1299                         Game_flash_red = 0.0f;
1300         } else {
1301                 Game_flash_red += dec_amount;           
1302                 if ( Game_flash_red > 0.0f )
1303                         Game_flash_red = 0.0f;
1304         } 
1305
1306         if ( Game_flash_green > 0.0f ) {
1307                 Game_flash_green -= dec_amount;         
1308                 if ( Game_flash_green < 0.0f )
1309                         Game_flash_green = 0.0f;
1310         } else {
1311                 Game_flash_green += dec_amount;         
1312                 if ( Game_flash_green > 0.0f )
1313                         Game_flash_green = 0.0f;
1314         } 
1315
1316         if ( Game_flash_blue > 0.0f ) {
1317                 Game_flash_blue -= dec_amount;          
1318                 if ( Game_flash_blue < 0.0f )
1319                         Game_flash_blue = 0.0f;
1320         } else {
1321                 Game_flash_blue += dec_amount;          
1322                 if ( Game_flash_blue > 0.0f )
1323                         Game_flash_blue = 0.0f;
1324         } 
1325
1326         // update big_explosion_cur_flash
1327 #define TIME_UP         1500
1328 #define TIME_DOWN       2500
1329         int duration = TIME_UP + TIME_DOWN;
1330         int time = timestamp_until(Big_expl_flash.flash_start);
1331         if (time > -duration) {
1332                 time = -time;
1333                 if (time < TIME_UP) {
1334                         Big_expl_flash.cur_flash_intensity = Big_expl_flash.max_flash_intensity * time / (float) TIME_UP;
1335                 } else {
1336                         time -= TIME_UP;
1337                         Big_expl_flash.cur_flash_intensity = Big_expl_flash.max_flash_intensity * ((float) TIME_DOWN - time) / (float) TIME_DOWN;
1338                 }
1339         }
1340         
1341         if ( Use_palette_flash )        {
1342                 int r,g,b;
1343 //              static int or=0, og=0, ob=0;
1344
1345                 // Change the 200 to change the color range of colors.
1346                 r = fl2i( Game_flash_red*128.0f );  
1347                 g = fl2i( Game_flash_green*128.0f );   
1348                 b = fl2i( Game_flash_blue*128.0f );  
1349
1350                 if ( Sun_spot > 0.0f )  {
1351                         r += fl2i(Sun_spot*128.0f);
1352                         g += fl2i(Sun_spot*128.0f);
1353                         b += fl2i(Sun_spot*128.0f);
1354                 }
1355
1356                 if ( Big_expl_flash.cur_flash_intensity  > 0.0f ) {
1357                         r += fl2i(Big_expl_flash.cur_flash_intensity*128.0f);
1358                         g += fl2i(Big_expl_flash.cur_flash_intensity*128.0f);
1359                         b += fl2i(Big_expl_flash.cur_flash_intensity*128.0f);
1360                 }
1361
1362                 if ( r < 0 ) r = 0; else if ( r > 255 ) r = 255;
1363                 if ( g < 0 ) g = 0; else if ( g > 255 ) g = 255;
1364                 if ( b < 0 ) b = 0; else if ( b > 255 ) b = 255;
1365
1366                 if ( (r!=0) || (g!=0) || (b!=0) ) {
1367                         gr_flash( r, g, b );
1368
1369                         //mprintf(( "Flash! %d,%d,%d\n", r, g, b ));
1370
1371 //                      or = r;
1372 //                      og = g;
1373 //                      ob = b;
1374                 }
1375         }
1376         
1377 }
1378
1379
1380 void game_level_close()
1381 {
1382         // De-Initialize the game subsystems
1383         message_mission_shutdown();
1384         event_music_level_close();
1385         game_stop_looped_sounds();
1386         snd_stop_all();
1387         obj_snd_level_close();                                  // uninit object-linked persistant sounds
1388         gamesnd_unload_gameplay_sounds();       // unload gameplay sounds from memory
1389         anim_level_close();                                             // stop and clean up any anim instances
1390         shockwave_level_close();
1391         fireball_level_close(); 
1392         shield_hit_close();
1393         mission_event_shutdown();
1394         asteroid_level_close();
1395         model_cache_reset();                                            // Reset/free all the model caching stuff
1396         flak_level_close();                                             // unload flak stuff
1397         neb2_level_close();                                             // shutdown gaseous nebula stuff
1398         ct_level_close();
1399         beam_level_close();
1400         mflash_level_close();
1401
1402         audiostream_unpause_all();
1403         Game_paused = 0;
1404 }
1405
1406
1407 // intializes game stuff and loads the mission.  Returns 0 on failure, 1 on success
1408 // input: seed =>       DEFAULT PARAMETER (value -1).  Only set by demo playback code.
1409 void game_level_init(int seed)
1410 {
1411         // seed the random number generator
1412         if ( seed == -1 ) {
1413                 // if no seed was passed, seed the generator either from the time value, or from the
1414                 // netgame security flags -- ensures that all players in multiplayer game will have the
1415                 // same randon number sequence (with static rand functions)
1416                 if ( Game_mode & GM_NORMAL ) {
1417                         Game_level_seed = time(NULL);
1418                 } else {
1419                         Game_level_seed = Netgame.security;
1420                 }
1421         } else {
1422                 // mwa 9/17/98 -- maybe this assert isn't needed????
1423                 Assert( !(Game_mode & GM_MULTIPLAYER) );
1424                 Game_level_seed = seed;
1425         }
1426         srand( Game_level_seed );
1427
1428         // semirand function needs to get re-initted every time in multiplayer
1429         if ( Game_mode & GM_MULTIPLAYER ){
1430                 init_semirand();
1431         }
1432
1433         Framecount = 0;
1434
1435         Key_normal_game = (Game_mode & GM_NORMAL);
1436         Cheats_enabled = 0;
1437
1438         Game_shudder_time = -1;
1439
1440         // Initialize the game subsystems
1441 //      timestamp_reset();                      // Must be inited before everything else
1442         if(!Is_standalone){
1443                 game_reset_time();                      // resets time, and resets saved time too
1444         }
1445         obj_init();                                             // Must be inited before the other systems
1446         model_free_all();                               // Free all existing models
1447         mission_brief_common_init();            // Free all existing briefing/debriefing text
1448         weapon_level_init();
1449         ai_level_init();                                //      Call this before ship_init() because it reads ai.tbl.
1450         ship_level_init();
1451         player_level_init();    
1452         shipfx_flash_init();                    // Init the ship gun flash system.
1453         game_flash_reset();                     // Reset the flash effect
1454         particle_init();                                // Reset the particle system
1455         fireball_init();
1456         debris_init();
1457         cmeasure_init();
1458         shield_hit_init();                              //      Initialize system for showing shield hits
1459         radar_mission_init();
1460         mission_init_goals();
1461         mission_log_init();
1462         messages_init();
1463         obj_snd_level_init();                                   // init object-linked persistant sounds
1464         anim_level_init();
1465         shockwave_level_init();
1466         afterburner_level_init();
1467         scoring_level_init( &Player->stats );
1468         key_level_init();
1469         asteroid_level_init();
1470         control_config_clear_used_status();
1471         collide_ship_ship_sounds_init();
1472         Missiontime = 0;
1473         Pre_player_entry = 1;                   //      Means the player has not yet entered.
1474         Entry_delay_time = 0;                   //      Could get overwritten in mission read.
1475         fireball_preload();                             //      page in warphole bitmaps
1476         observer_init();
1477         flak_level_init();                              // initialize flak - bitmaps, etc
1478         ct_level_init();                                        // initialize ships contrails, etc
1479         awacs_level_init();                             // initialize AWACS
1480         beam_level_init();                              // initialize beam weapons
1481         mflash_level_init();
1482         ssm_level_init();       
1483         supernova_level_init();
1484
1485         // multiplayer dogfight hack
1486         dogfight_blown = 0;
1487
1488         shipfx_engine_wash_level_init();
1489
1490         nebl_level_init();
1491
1492         Last_view_target = NULL;
1493         Game_paused = 0;
1494
1495         Game_no_clear = 0;
1496
1497         // campaign wasn't ended
1498         Campaign_ended_in_mission = 0;
1499 }
1500
1501 // called when a mission is over -- does server specific stuff.
1502 void freespace_stop_mission()
1503 {       
1504         game_level_close();
1505         Game_mode &= ~GM_IN_MISSION;
1506 }
1507
1508 // called at frame interval to process networking stuff
1509 void game_do_networking()
1510 {
1511         Assert( Net_player != NULL );
1512         if (!(Game_mode & GM_MULTIPLAYER)){
1513                 return;
1514         }
1515
1516         // see if this player should be reading/writing data.  Bit is set when at join
1517         // screen onward until quits back to main menu.
1518         if ( !(Net_player->flags & NETINFO_FLAG_DO_NETWORKING) ){
1519                 return;
1520         }
1521
1522         if(gameseq_get_state()!=GS_STATE_MULTI_PAUSED){
1523                 multi_do_frame();
1524         } else {
1525                 multi_pause_do_frame();
1526         }       
1527 }
1528
1529
1530 // Loads the best palette for this level, based
1531 // on nebula color and hud color.  You could just call palette_load_table with
1532 // the appropriate filename, but who wants to do that.
1533 void game_load_palette()
1534 {
1535         char palette_filename[1024];
1536
1537         // We only use 3 hud colors right now
1538         // Assert( HUD_config.color >= 0 );
1539         // Assert( HUD_config.color <= 2 );
1540
1541         Assert( Mission_palette >= 0 );
1542         Assert( Mission_palette <= 98 );
1543
1544         // if ( The_mission.flags & MISSION_FLAG_SUBSPACE )     {
1545                 strcpy( palette_filename, NOX("gamepalette-subspace") );
1546         // } else {
1547                 // sprintf( palette_filename, NOX("gamepalette%d-%02d"), HUD_config.color+1, Mission_palette+1 );
1548         // }
1549
1550         mprintf(( "Loading palette %s\n", palette_filename ));
1551
1552         // palette_load_table(palette_filename);
1553 }
1554
1555 void game_post_level_init()
1556 {
1557         // Stuff which gets called after mission is loaded.  Because player isn't created until
1558         // after mission loads, some things must get initted after the level loads
1559
1560         model_level_post_init();
1561
1562         HUD_init();
1563         hud_setup_escort_list();
1564         mission_hotkey_set_defaults();  // set up the default hotkeys (from mission file)
1565
1566         stars_level_init();     
1567         neb2_level_init();              
1568
1569 #ifndef NDEBUG
1570         game_event_debug_init();
1571 #endif
1572
1573         training_mission_init();
1574         asteroid_create_all();
1575         
1576         game_framerate_check_init();
1577 }
1578
1579
1580 // An estimate as to how high the count passed to game_loading_callback will go.
1581 // This is just a guess, it seems to always be about the same.   The count is
1582 // proportional to the code being executed, not the time, so this works good
1583 // for a bar, assuming the code does about the same thing each time you
1584 // load a level.   You can find this value by looking at the return value
1585 // of game_busy_callback(NULL), which I conveniently print out to the
1586 // debug output window with the '=== ENDING LOAD ==' stuff.   
1587 //#define COUNT_ESTIMATE 3706
1588 #define COUNT_ESTIMATE 1111
1589
1590 int Game_loading_callback_inited = 0;
1591
1592 int Game_loading_background = -1;
1593 anim * Game_loading_ani = NULL;
1594 anim_instance   *Game_loading_ani_instance;
1595 int Game_loading_frame=-1;
1596
1597 static int Game_loading_ani_coords[GR_NUM_RESOLUTIONS][2] = {
1598         {
1599                 63, 316  // GR_640
1600         },
1601         {
1602                 101, 505        // GR_1024
1603         }
1604 };
1605
1606 // This gets called 10x per second and count is the number of times 
1607 // game_busy() has been called since the current callback function
1608 // was set.
1609 void game_loading_callback(int count)
1610 {       
1611         game_do_networking();
1612
1613         Assert( Game_loading_callback_inited==1 );
1614         Assert( Game_loading_ani != NULL );
1615
1616         int framenum = ((Game_loading_ani->total_frames*count) / COUNT_ESTIMATE)+1;
1617         if ( framenum > Game_loading_ani->total_frames-1 )      {
1618                 framenum = Game_loading_ani->total_frames-1;
1619         } else if ( framenum < 0 )      {
1620                 framenum = 0;
1621         }
1622
1623         int cbitmap = -1;
1624         while ( Game_loading_frame < framenum ) {
1625                 Game_loading_frame++;
1626                 cbitmap = anim_get_next_frame(Game_loading_ani_instance);
1627         }
1628
1629
1630         if ( cbitmap > -1 )     {
1631                 if ( Game_loading_background > -1 )     {
1632                         gr_set_bitmap( Game_loading_background );
1633                         gr_bitmap(0,0);
1634                 }
1635
1636                 //mprintf(( "Showing frame %d/%d [ Bitmap=%d ]\n", Game_loading_frame ,  Game_loading_ani->total_frames, cbitmap ));
1637                 gr_set_bitmap( cbitmap );
1638                 gr_bitmap(Game_loading_ani_coords[gr_screen.res][0],Game_loading_ani_coords[gr_screen.res][1]);
1639
1640                 bm_release(cbitmap);
1641         
1642                 gr_flip();
1643         }
1644 }
1645
1646 void game_loading_callback_init()
1647 {
1648         Assert( Game_loading_callback_inited==0 );
1649
1650         Game_loading_background = bm_load(Game_loading_bground_fname[gr_screen.res]);
1651         //common_set_interface_palette("InterfacePalette");  // set the interface palette
1652
1653
1654         Game_loading_ani = anim_load( Game_loading_ani_fname[gr_screen.res]);
1655         Assert( Game_loading_ani != NULL );
1656         Game_loading_ani_instance = init_anim_instance(Game_loading_ani, 16);
1657         Assert( Game_loading_ani_instance != NULL );
1658         Game_loading_frame = -1;
1659
1660         Game_loading_callback_inited = 1;
1661         Mouse_hidden = 1;
1662         game_busy_callback( game_loading_callback, (COUNT_ESTIMATE/Game_loading_ani->total_frames)+1 ); 
1663
1664
1665 }
1666
1667 void game_loading_callback_close()
1668 {
1669         Assert( Game_loading_callback_inited==1 );
1670
1671         // Make sure bar shows all the way over.
1672         game_loading_callback(COUNT_ESTIMATE);
1673         
1674         int real_count = game_busy_callback( NULL );
1675         Mouse_hidden = 0;
1676
1677         Game_loading_callback_inited = 0;
1678         
1679 #ifndef NDEBUG
1680         mprintf(( "=================== ENDING LOAD ================\n" ));
1681         mprintf(( "Real count = %d,  Estimated count = %d\n", real_count, COUNT_ESTIMATE ));
1682         mprintf(( "================================================\n" ));
1683 #else
1684         // to remove warnings in release build
1685         real_count = 0;
1686 #endif
1687
1688         free_anim_instance(Game_loading_ani_instance);
1689         Game_loading_ani_instance = NULL;
1690         anim_free(Game_loading_ani);
1691         Game_loading_ani = NULL;
1692
1693         bm_release( Game_loading_background );
1694         common_free_interface_palette();                // restore game palette
1695         Game_loading_background = -1;
1696
1697         gr_set_font( FONT1 );
1698 }
1699
1700 // Update the sound environment (ie change EAX settings based on proximity to large ships)
1701 //
1702 void game_maybe_update_sound_environment()
1703 {
1704         // do nothing for now
1705 }
1706
1707 // Assign the sound environment for the game, based on the current mission
1708 //
1709 void game_assign_sound_environment()
1710 {
1711         /*
1712         if (The_mission.flags & MISSION_FLAG_SUBSPACE) {
1713                 Game_sound_env.id = SND_ENV_DRUGGED;
1714                 Game_sound_env.volume = 0.800f;
1715                 Game_sound_env.damping = 1.188f;
1716                 Game_sound_env.decay = 6.392f;
1717 #ifndef FS2_DEMO
1718         } else if (Num_asteroids > 30) {
1719                 Game_sound_env.id = SND_ENV_AUDITORIUM;
1720                 Game_sound_env.volume = 0.603f;
1721                 Game_sound_env.damping = 0.5f;
1722                 Game_sound_env.decay = 4.279f;
1723 #endif
1724         } else {
1725                 Game_sound_env = Game_default_sound_env;
1726         }
1727         */
1728
1729         Game_sound_env = Game_default_sound_env;
1730         Game_sound_env_update_timestamp = timestamp(1);
1731 }
1732
1733 // function which gets called before actually entering the mission.  It is broken down into a funciton
1734 // since it will get called in one place from a single player game and from another place for
1735 // a multiplayer game
1736 void freespace_mission_load_stuff()
1737 {
1738         // called if we're not on a freespace dedicated (non rendering, no pilot) server
1739         // IE : we _don't_ want to load any sounds or bitmap/texture info on this machine.
1740         if(!(Game_mode & GM_STANDALONE_SERVER)){        
1741         
1742                 mprintf(( "=================== STARTING LEVEL DATA LOAD ==================\n" ));
1743
1744                 game_loading_callback_init();
1745                 
1746                 event_music_level_init();       // preloads the first 2 seconds for each event music track
1747                 game_busy();
1748
1749                 gamesnd_unload_interface_sounds();              // unload interface sounds from memory
1750                 game_busy();
1751
1752                 gamesnd_preload_common_sounds();                        // load in sounds that are expected to play
1753                 game_busy();
1754
1755                 ship_assign_sound_all();        // assign engine sounds to ships
1756                 game_assign_sound_environment();         // assign the sound environment for this mission
1757                 game_busy();
1758
1759                 // call function in missionparse.cpp to fixup player/ai stuff.
1760                 mission_parse_fixup_players();
1761                 game_busy();
1762
1763                 // Load in all the bitmaps for this level
1764                 level_page_in();
1765
1766                 game_busy();
1767
1768                 game_loading_callback_close();  
1769         } 
1770         // the only thing we need to call on the standalone for now.
1771         else {
1772                 // call function in missionparse.cpp to fixup player/ai stuff.
1773                 mission_parse_fixup_players();
1774
1775                 // Load in all the bitmaps for this level
1776                 level_page_in();
1777         }
1778 }
1779
1780 uint load_gl_init;
1781 uint load_mission_load;
1782 uint load_post_level_init;
1783 uint load_mission_stuff;
1784
1785 // tells the server to load the mission and initialize structures
1786 int game_start_mission()
1787 {       
1788         mprintf(( "=================== STARTING LEVEL LOAD ==================\n" ));
1789         
1790         load_gl_init = time(NULL);
1791         game_level_init();
1792         load_gl_init = time(NULL) - load_gl_init;
1793         
1794         if (Game_mode & GM_MULTIPLAYER) {
1795                 Player->flags |= PLAYER_FLAGS_IS_MULTI;
1796
1797                 // clear multiplayer stats
1798                 init_multiplayer_stats();
1799         }
1800
1801         load_mission_load = time(NULL);
1802         if (mission_load()) {
1803                 if ( !(Game_mode & GM_MULTIPLAYER) ) {
1804                         popup(PF_BODY_BIG, 1, POPUP_OK, XSTR( "Attempt to load the mission failed", 169));
1805                         gameseq_post_event(GS_EVENT_MAIN_MENU);
1806                 } else {
1807                         multi_quit_game(PROMPT_NONE, MULTI_END_NOTIFY_NONE, MULTI_END_ERROR_LOAD_FAIL);
1808                 }
1809
1810                 return 0;
1811         }
1812         load_mission_load = time(NULL) - load_mission_load;
1813
1814         // If this is a red alert mission in campaign mode, bash wingman status
1815         if ( (Game_mode & GM_CAMPAIGN_MODE) && red_alert_mission() ) {
1816                 red_alert_bash_wingman_status();
1817         }
1818
1819         // the standalone server in multiplayer doesn't do any rendering, so we will not even bother loading the palette
1820         if ( !(Game_mode & GM_STANDALONE_SERVER) ) {
1821                 mprintf(( "=================== LOADING GAME PALETTE ================\n" ));
1822                 // game_load_palette();
1823         }
1824
1825         load_post_level_init = time(NULL);
1826         game_post_level_init();
1827         load_post_level_init = time(NULL) - load_post_level_init;
1828
1829         #ifndef NDEBUG
1830         {
1831                 void Do_model_timings_test();
1832                 Do_model_timings_test();        
1833         }
1834         #endif
1835
1836         load_mission_stuff = time(NULL);
1837         freespace_mission_load_stuff();
1838         load_mission_stuff = time(NULL) - load_mission_stuff;
1839
1840         return 1;
1841 }
1842
1843 int Interface_framerate = 0;
1844 #ifndef NDEBUG
1845
1846 DCF_BOOL( mouse_control, Use_mouse_to_fly )
1847 DCF_BOOL( show_framerate, Show_framerate )
1848 DCF_BOOL( show_target_debug_info, Show_target_debug_info )
1849 DCF_BOOL( show_target_weapons, Show_target_weapons )
1850 DCF_BOOL( lead_target_cheat, Players[Player_num].lead_target_cheat )
1851 DCF_BOOL( sound, Sound_enabled )
1852 DCF_BOOL( zbuffer, game_zbuffer )
1853 DCF_BOOL( shield_system, New_shield_system )
1854 DCF_BOOL( show_shield_mesh, Show_shield_mesh)
1855 DCF_BOOL( player_attacking, Player_attacking_enabled )
1856 DCF_BOOL( show_waypoints, Show_waypoints )
1857 DCF_BOOL( show_area_effect, Show_area_effect )
1858 DCF_BOOL( show_net_stats, Show_net_stats )
1859 DCF_BOOL( log, Log_debug_output_to_file )
1860 DCF_BOOL( training_msg_method, Training_msg_method )
1861 DCF_BOOL( show_player_pos, Show_player_pos )
1862 DCF_BOOL(i_framerate, Interface_framerate )
1863
1864 DCF(show_mem,"Toggles showing mem usage")
1865 {
1866         if ( Dc_command )       {       
1867                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1868                 if ( Dc_arg_type & ARG_TRUE )   Show_mem = 1;   
1869                 else if ( Dc_arg_type & ARG_FALSE ) Show_mem = 0;       
1870                 else if ( Dc_arg_type & ARG_NONE ) Show_mem ^= 1;       
1871
1872                 if ( Show_mem ) {
1873                         Show_cpu = 0;
1874                 }
1875         }       
1876         if ( Dc_help )  dc_printf( "Usage: Show_mem\nSets show_mem to true or false.  If nothing passed, then toggles it.\n" ); 
1877         if ( Dc_status )        {
1878                 dc_printf( "Show_mem is %s\n", (Show_mem?"TRUE":"FALSE") );     
1879                 dc_printf( "Show_cpu is %s\n", (Show_cpu?"TRUE":"FALSE") );     
1880         }
1881 }
1882
1883 DCF(show_cpu,"Toggles showing cpu usage")
1884 {
1885         if ( Dc_command )       {       
1886                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1887                 if ( Dc_arg_type & ARG_TRUE )   Show_cpu = 1;   
1888                 else if ( Dc_arg_type & ARG_FALSE ) Show_cpu = 0;       
1889                 else if ( Dc_arg_type & ARG_NONE ) Show_cpu ^= 1;       
1890
1891                 if ( Show_cpu ) {
1892                         Show_mem = 0;
1893                 }
1894         }       
1895         if ( Dc_help )  dc_printf( "Usage: Show_cpu\nSets show_cpu to true or false.  If nothing passed, then toggles it.\n" ); 
1896         if ( Dc_status )        {
1897                 dc_printf( "Show_mem is %s\n", (Show_mem?"TRUE":"FALSE") );     
1898                 dc_printf( "Show_cpu is %s\n", (Show_cpu?"TRUE":"FALSE") );     
1899
1900         }
1901 }
1902
1903 #else
1904
1905         // AL 4-8-98: always allow players to display their framerate
1906
1907         #ifdef FS2_DEMO
1908                 DCF_BOOL( show_framerate, Show_framerate )
1909         #endif
1910
1911 #endif  // NDEBUG
1912
1913                         int Game_init_seed;
1914
1915 DCF(use_joy_mouse,"Makes joystick move mouse cursor")
1916 {
1917         if ( Dc_command )       {       
1918                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1919                 if ( Dc_arg_type & ARG_TRUE )   Use_joy_mouse = 1;      
1920                 else if ( Dc_arg_type & ARG_FALSE ) Use_joy_mouse = 0;  
1921                 else if ( Dc_arg_type & ARG_NONE ) Use_joy_mouse ^= 1;  
1922         }       
1923         if ( Dc_help )  dc_printf( "Usage: use_joy_mouse [bool]\nSets use_joy_mouse to true or false.  If nothing passed, then toggles it.\n" );        
1924         if ( Dc_status )        dc_printf( "use_joy_mouse is %s\n", (Use_joy_mouse?"TRUE":"FALSE") );   
1925
1926         os_config_write_uint( NULL, NOX("JoystickMovesCursor"), Use_joy_mouse );
1927 }
1928
1929 DCF(palette_flash,"Toggles palette flash effect on/off")
1930 {
1931         if ( Dc_command )       {       
1932                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1933                 if ( Dc_arg_type & ARG_TRUE )   Use_palette_flash = 1;  
1934                 else if ( Dc_arg_type & ARG_FALSE ) Use_palette_flash = 0;      
1935                 else if ( Dc_arg_type & ARG_NONE ) Use_palette_flash ^= 1;      
1936         }       
1937         if ( Dc_help )  dc_printf( "Usage: palette_flash [bool]\nSets palette_flash to true or false.  If nothing passed, then toggles it.\n" );        
1938         if ( Dc_status )        dc_printf( "palette_flash is %s\n", (Use_palette_flash?"TRUE":"FALSE") );       
1939 }
1940
1941 int Use_low_mem = 0;
1942
1943 DCF(low_mem,"Uses low memory settings regardless of RAM")
1944 {
1945         if ( Dc_command )       {       
1946                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1947                 if ( Dc_arg_type & ARG_TRUE )   Use_low_mem = 1;        
1948                 else if ( Dc_arg_type & ARG_FALSE ) Use_low_mem = 0;    
1949                 else if ( Dc_arg_type & ARG_NONE ) Use_low_mem ^= 1;    
1950         }       
1951         if ( Dc_help )  dc_printf( "Usage: low_mem [bool]\nSets low_mem to true or false.  If nothing passed, then toggles it.\n" );    
1952         if ( Dc_status )        dc_printf( "low_mem is %s\n", (Use_low_mem?"TRUE":"FALSE") );   
1953
1954         os_config_write_uint( NULL, NOX("LowMem"), Use_low_mem );
1955 }
1956
1957
1958 #ifndef NDEBUG
1959
1960 DCF(force_fullscreen, "Forces game to startup in fullscreen mode")
1961 {
1962         if ( Dc_command )       {       
1963                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
1964                 if ( Dc_arg_type & ARG_TRUE )   Use_fullscreen_at_startup = 1;  
1965                 else if ( Dc_arg_type & ARG_FALSE ) Use_fullscreen_at_startup = 0;      
1966                 else if ( Dc_arg_type & ARG_NONE ) Use_fullscreen_at_startup ^= 1;      
1967         }       
1968         if ( Dc_help )  dc_printf( "Usage: force_fullscreen [bool]\nSets force_fullscreen to true or false.  If nothing passed, then toggles it.\n" );  
1969         if ( Dc_status )        dc_printf( "force_fullscreen is %s\n", (Use_fullscreen_at_startup?"TRUE":"FALSE") );    
1970         os_config_write_uint( NULL, NOX("ForceFullscreen"), Use_fullscreen_at_startup );
1971 }
1972 #endif
1973
1974 int     Framerate_delay = 0;
1975
1976 float Freespace_gamma = 1.0f;
1977
1978 DCF(gamma,"Sets Gamma factor")
1979 {
1980         if ( Dc_command )       {
1981                 dc_get_arg(ARG_FLOAT|ARG_NONE);
1982                 if ( Dc_arg_type & ARG_FLOAT )  {
1983                         Freespace_gamma = Dc_arg_float;
1984                 } else {
1985                         dc_printf( "Gamma reset to 1.0f\n" );
1986                         Freespace_gamma = 1.0f;
1987                 }
1988                 if ( Freespace_gamma < 0.1f )   {
1989                         Freespace_gamma = 0.1f;
1990                 } else if ( Freespace_gamma > 5.0f )    {
1991                         Freespace_gamma = 5.0f;
1992                 }
1993                 gr_set_gamma(Freespace_gamma);
1994
1995                 char tmp_gamma_string[32];
1996                 sprintf( tmp_gamma_string, NOX("%.2f"), Freespace_gamma );
1997                 os_config_write_string( NULL, NOX("Gamma"), tmp_gamma_string );
1998         }
1999
2000         if ( Dc_help )  {
2001                 dc_printf( "Usage: gamma <float>\n" );
2002                 dc_printf( "Sets gamma in range 1-3, no argument resets to default 1.2\n" );
2003                 Dc_status = 0;  // don't print status if help is printed.  Too messy.
2004         }
2005
2006         if ( Dc_status )        {
2007                 dc_printf( "Gamma = %.2f\n", Freespace_gamma );
2008         }
2009 }
2010
2011 void game_init()
2012 {
2013         char *ptr;
2014         int depth = 16;
2015
2016         Game_current_mission_filename[0] = 0;
2017
2018         // seed the random number generator
2019         Game_init_seed = time(NULL);
2020         srand( Game_init_seed );
2021
2022         Framerate_delay = 0;
2023
2024         #ifndef NDEBUG
2025         load_filter_info();
2026         #endif
2027
2028         extern void bm_init();
2029         bm_init();
2030
2031         // encrypt stuff
2032         encrypt_init();
2033
2034         // Initialize the timer before the os
2035         timer_init();
2036
2037         int s1, e1;
2038         // int s2, e2;
2039
2040         char whee[1024];
2041 #ifndef PLAT_UNIX       
2042         GetCurrentDirectory(1024, whee);
2043 #else
2044         strcpy(whee, ".");
2045         strcpy(whee,".\\.");
2046         STUB_FUNCTION;
2047 #endif
2048         strcat(whee, "\\");
2049         strcat(whee, EXE_FNAME);
2050
2051         //Initialize the libraries
2052         s1 = timer_get_milliseconds();
2053         if(cfile_init(whee, Game_CDROM_dir)){                   // initialize before calling any cfopen stuff!!!
2054                 exit(1);
2055         }               
2056         e1 = timer_get_milliseconds();
2057
2058         // time a bunch of cfopens      
2059         /*
2060         s2 = timer_get_milliseconds();  
2061         CFILE *whee;
2062         for(int idx=0; idx<10000; idx++){
2063                 whee = cfopen("capital01.pof", "rb", CFILE_NORMAL, CF_TYPE_MODELS);
2064                 if(whee != NULL){
2065                         cfclose(whee);
2066                 }
2067                 whee = NULL;
2068                 //cf_exist("capital01.pof", CF_TYPE_MODELS);
2069         }
2070         e2 = timer_get_milliseconds();  
2071         */
2072
2073         if (Is_standalone) {
2074                 std_init_standalone();
2075         } else {                
2076                 os_init( Osreg_class_name, Osreg_app_name );
2077                 os_set_title(Osreg_title);
2078         }
2079
2080         // initialize localization module. Make sure this is down AFTER initialzing OS.
2081 //      int t1 = timer_get_milliseconds();
2082         lcl_init();     
2083         lcl_xstr_init();
2084 //      mprintf(("LCL_INIT() TOOK %d MS\n", timer_get_milliseconds()-t1));
2085
2086         // verify that he has a valid ships.tbl (will Game_ships_tbl_valid if so)
2087         verify_ships_tbl();
2088
2089         // verify that he has a valid weapons.tbl
2090         verify_weapons_tbl();
2091
2092         // Output version numbers to registry for auto patching purposes
2093         os_config_write_uint(NOX("Version"), NOX("Major"), FS_VERSION_MAJOR);
2094         os_config_write_uint(NOX("Version"), NOX("Minor"), FS_VERSION_MINOR);
2095         os_config_write_uint(NOX("Version"), NOX("Build"), FS_VERSION_BUILD);
2096
2097         Use_joy_mouse = 0;              //os_config_read_uint( NULL, NOX("JoystickMovesCursor"), 1 );
2098         //Use_palette_flash = os_config_read_uint( NULL, NOX("PaletteFlash"), 0 );
2099         Use_low_mem = os_config_read_uint( NULL, NOX("LowMem"), 0 );
2100
2101 #ifndef NDEBUG
2102         Use_fullscreen_at_startup = os_config_read_uint( NULL, NOX("ForceFullscreen"), 1 );
2103 #endif
2104
2105 #ifndef FS2_DEMO
2106         Asteroids_enabled = 1;          
2107 #endif
2108
2109 /////////////////////////////
2110 // SOUND INIT START
2111 /////////////////////////////
2112
2113         int use_a3d = 0;
2114         int use_eax = 0;
2115
2116         ptr = os_config_read_string(NULL, NOX("Soundcard"), NULL);
2117         mprintf(("soundcard = %s\n", ptr ? ptr : "<nothing>"));
2118         if (ptr) {
2119                 if (!stricmp(ptr, NOX("no sound"))) {
2120                         Cmdline_freespace_no_sound = 1;
2121
2122                 } else if (!stricmp(ptr, NOX("Aureal A3D"))) {
2123                         use_a3d = 1;
2124                 } else if (!stricmp(ptr, NOX("EAX"))) {
2125                         use_eax = 1;
2126                 }
2127         }
2128
2129         if (!Is_standalone) {
2130                 snd_init(use_a3d, use_eax);
2131         }
2132 /////////////////////////////
2133 // SOUND INIT END
2134 /////////////////////////////
2135         
2136         ptr = os_config_read_string(NULL, NOX("Videocard"), NULL);
2137         if (ptr == NULL) {
2138 #ifndef PLAT_UNIX       
2139                 MessageBox((HWND)os_get_window(), XSTR("Please configure your system in the Launcher before running FS2.\n\n The Launcher will now be started!", 1446), XSTR("Attention!", 1447), MB_OK);
2140
2141                 // fire up the UpdateLauncher executable
2142                 STARTUPINFO si;
2143                 PROCESS_INFORMATION pi;
2144
2145                 memset( &si, 0, sizeof(STARTUPINFO) );
2146                 si.cb = sizeof(si);
2147
2148                 BOOL ret = CreateProcess(       LAUNCHER_FNAME, // pointer to name of executable module 
2149                                                                         NULL,                                                   // pointer to command line string
2150                                                                         NULL,                                                   // pointer to process security attributes 
2151                                                                         NULL,                                                   // pointer to thread security attributes 
2152                                                                         FALSE,                                                  // handle inheritance flag 
2153                                                                         CREATE_DEFAULT_ERROR_MODE,              // creation flags 
2154                                                                         NULL,                                                   // pointer to new environment block 
2155                                                                         NULL,   // pointer to current directory name 
2156                                                                         &si,    // pointer to STARTUPINFO 
2157                                                                         &pi     // pointer to PROCESS_INFORMATION  
2158                                                                 );                      
2159
2160                 // If the Launcher could not be started up, let the user know
2161                 if (!ret) {
2162                         MessageBox((HWND)os_get_window(), XSTR("The Launcher could not be restarted.", 1450), XSTR("Error", 1451), MB_OK);
2163                 }
2164 #else
2165                 STUB_FUNCTION;
2166 #endif          
2167                 exit(1);
2168         }
2169
2170         if(!Is_standalone){
2171                 if(!stricmp(ptr, "Aucune accélération 3D") || !stricmp(ptr, "Keine 3D-Beschleunigerkarte") || !stricmp(ptr, "No 3D acceleration")){
2172 #ifndef PLAT_UNIX               
2173                         MessageBox((HWND)os_get_window(), XSTR("Warning, Freespace 2 requires Glide or Direct3D hardware accleration. You will not be able to run Freespace 2 without it.", 1448), XSTR("Warning", 1449), MB_OK);
2174 #else
2175                         STUB_FUNCTION;
2176 #endif                                          
2177                         exit(1);
2178                 }
2179         }
2180
2181         // check for hi res pack file 
2182         int has_sparky_hi = 0;
2183
2184         // check if sparky_hi exists -- access mode 0 means does file exist
2185         char dir[128];
2186         _getcwd(dir, 128);
2187         if ( _access("sparky_hi_fs2.vp", 0) == 0) {
2188                 has_sparky_hi = 1;
2189         } else {
2190                 mprintf(("No sparky_hi_fs2.vp in directory %s\n", dir));
2191         }
2192
2193         // see if we've got 32 bit in the string
2194         if(strstr(ptr, "32 bit")){
2195                 depth = 32;
2196         }
2197
2198         int trying_d3d = 0;
2199         
2200         if (!Is_standalone && ptr && (strstr(ptr, NOX("3DFX Glide")))) {
2201 #ifdef E3_BUILD
2202                 // always 640 for E3
2203                 gr_init(GR_640, GR_GLIDE);
2204 #else
2205                 // regular or hi-res ?
2206 #ifdef NDEBUG
2207                 if(has_sparky_hi && strstr(ptr, NOX("(1024x768)"))){
2208 #else
2209                 if(strstr(ptr, NOX("(1024x768)"))){
2210 #endif
2211                         gr_init(GR_1024, GR_GLIDE);
2212                 } else {                        
2213                         gr_init(GR_640, GR_GLIDE);
2214                 }
2215 #endif
2216         } else if (!Is_standalone && ptr && (strstr(ptr, NOX("Direct 3D -") ))) {
2217 #ifdef E3_BUILD         
2218                 // always 640 for E3
2219                 trying_d3d = 1;
2220                 gr_init(GR_640, GR_DIRECT3D, depth);            
2221 #else
2222                 // regular or hi-res ?
2223 #ifdef NDEBUG
2224                 if(has_sparky_hi && strstr(ptr, NOX("(1024x768)"))){
2225 #else
2226                 if(strstr(ptr, NOX("(1024x768)"))){
2227 #endif
2228                         // Direct 3D
2229                         trying_d3d = 1;
2230                         gr_init(GR_1024, GR_DIRECT3D, depth);
2231                 } else {
2232                         // Direct 3D
2233                         trying_d3d = 1;
2234                         gr_init(GR_640, GR_DIRECT3D, depth);
2235                 }
2236 #endif
2237         } else {
2238                 // Software
2239                 #ifndef NDEBUG
2240                         if ( Use_fullscreen_at_startup && !Is_standalone)       {               
2241                                 gr_init(GR_640, GR_DIRECTDRAW);
2242                         } else {
2243                                 gr_init(GR_640, GR_SOFTWARE);
2244                         }
2245                 #else
2246                         if ( !Is_standalone ) {
2247                                 gr_init(GR_640, GR_DIRECTDRAW);
2248                         } else {
2249                                 gr_init(GR_640, GR_SOFTWARE);
2250                         }
2251                 #endif
2252         }
2253
2254         // tried d3d ?
2255         extern int Gr_inited;
2256         if(trying_d3d && !Gr_inited){
2257                 extern char Device_init_error[512];
2258 #ifndef PLAT_UNIX               
2259                 MessageBox( NULL, Device_init_error, "Error intializing Direct3D", MB_OK|MB_TASKMODAL|MB_SETFOREGROUND );
2260 #lse
2261                 STUB_FUNCTION;
2262 #endif          
2263                 exit(1);
2264                 return;
2265         }
2266
2267         // Set the gamma
2268         ptr = os_config_read_string(NULL,NOX("Gamma"),NOX("1.80"));
2269         Freespace_gamma = (float)atof(ptr);
2270         if ( Freespace_gamma < 0.1f )   {
2271                 Freespace_gamma = 0.1f;
2272         } else if ( Freespace_gamma > 5.0f )    {
2273                 Freespace_gamma = 5.0f;
2274         }
2275         char tmp_gamma_string[32];
2276         sprintf( tmp_gamma_string, NOX("%.2f"), Freespace_gamma );
2277         os_config_write_string( NULL, NOX("Gamma"), tmp_gamma_string );
2278
2279         gr_set_gamma(Freespace_gamma);
2280
2281 #if defined(FS2_DEMO) || defined(OEM_BUILD)
2282         // add title screen
2283         if(!Is_standalone){
2284                 display_title_screen();
2285         }
2286 #endif
2287         
2288         // attempt to load up master tracker registry info (login and password)
2289         Multi_tracker_id = -1;          
2290
2291         // pxo login and password
2292         ptr = os_config_read_string(NOX("PXO"),NOX("Login"),NULL);
2293         if(ptr == NULL){
2294                 nprintf(("Network","Error reading in PXO login data\n"));
2295                 strcpy(Multi_tracker_login,"");
2296         } else {                
2297                 strcpy(Multi_tracker_login,ptr);
2298         }
2299         ptr = os_config_read_string(NOX("PXO"),NOX("Password"),NULL);
2300         if(ptr == NULL){                
2301                 nprintf(("Network","Error reading PXO password\n"));
2302                 strcpy(Multi_tracker_passwd,"");
2303         } else {                
2304                 strcpy(Multi_tracker_passwd,ptr);
2305         }       
2306
2307         // pxo squad name and password
2308         ptr = os_config_read_string(NOX("PXO"),NOX("SquadName"),NULL);
2309         if(ptr == NULL){
2310                 nprintf(("Network","Error reading in PXO squad name\n"));
2311                 strcpy(Multi_tracker_squad_name, "");
2312         } else {                
2313                 strcpy(Multi_tracker_squad_name, ptr);
2314         }
2315
2316         // If less than 48MB of RAM, use low memory model.
2317         if ( (Freespace_total_ram < 48*1024*1024) || Use_low_mem )      {
2318                 mprintf(( "Using normal memory settings...\n" ));
2319                 bm_set_low_mem(1);              // Use every other frame of bitmaps
2320         } else {
2321                 mprintf(( "Using high memory settings...\n" ));
2322                 bm_set_low_mem(0);              // Use all frames of bitmaps
2323         }
2324
2325         // load non-darkening pixel defs
2326         palman_load_pixels();
2327
2328         // hud shield icon stuff
2329         hud_shield_game_init();
2330
2331         control_config_common_init();                           // sets up localization stuff in the control config
2332         parse_rank_tbl();
2333         parse_medal_tbl();
2334         cutscene_init();
2335         key_init();
2336         mouse_init();
2337         gamesnd_parse_soundstbl();
2338         radar_init();
2339         gameseq_init();
2340         multi_init();   
2341
2342         // standalone's don't use hte joystick and it seems to sometimes cause them to not get shutdown properly
2343         if(!Is_standalone){
2344                 joy_init();
2345         }
2346
2347         player_controls_init();
2348         model_init();   
2349
2350         //if(!Is_standalone){
2351                 event_music_init();
2352         //}     
2353
2354         obj_init();     
2355         mflash_game_init();     
2356         weapon_init();  
2357         ai_init();              
2358         ship_init();                                            // read in ships.tbl    
2359         player_init();  
2360         mission_campaign_init();                // load in the default campaign 
2361         anim_init();
2362 //      navmap_init();                                          // init the navigation map system
2363         context_help_init();                    
2364         techroom_intel_init();                  // parse species.tbl, load intel info   
2365         // initialize psnet
2366         psnet_init( Multi_options_g.protocol, Multi_options_g.port );                                           // initialize the networking code               
2367         init_animating_pointer();       
2368         asteroid_init();
2369         mission_brief_common_init();    // Mark all the briefing structures as empty.           
2370         gr_font_init();                                 // loads up all fonts           
2371
2372         neb2_init();                                            // fullneb stuff
2373         nebl_init();
2374         stars_init();
2375         ssm_init();     
2376         player_tips_init();                             // helpful tips
2377         beam_init();
2378         
2379         // load the list of pilot pic filenames (for barracks and pilot select popup quick reference)
2380         pilot_load_pic_list();  
2381         pilot_load_squad_pic_list();
2382
2383         load_animating_pointer(NOX("cursor"), 0, 0);    
2384
2385         // initialize alpha colors
2386         alpha_colors_init();    
2387
2388         Viewer_mode = 0;
2389 //      Game_music_paused = 0;
2390         Game_paused = 0;
2391
2392 #ifndef PLAT_UNIX
2393         timeBeginPeriod(1);     
2394 #endif
2395
2396         nprintf(("General", "Ships.tbl is : %s\n", Game_ships_tbl_valid ? "VALID" : "INVALID!!!!"));
2397         nprintf(("General", "Weapons.tbl is : %s\n", Game_weapons_tbl_valid ? "VALID" : "INVALID!!!!"));
2398
2399         mprintf(("cfile_init() took %d\n", e1 - s1));
2400         // mprintf(("1000 cfopens() took %d\n", e2 - s2));      
2401 }
2402
2403 char transfer_text[128];
2404
2405 float   Start_time = 0.0f;
2406
2407 float Framerate = 0.0f;
2408
2409 float Timing_total = 0.0f;
2410 float Timing_render2 = 0.0f;
2411 float Timing_render3 = 0.0f;
2412 float Timing_flip = 0.0f;
2413 float Timing_clear = 0.0f;
2414
2415 MONITOR(NumPolysDrawn);
2416 MONITOR(NumPolys);
2417 MONITOR(NumVerts);
2418 MONITOR(BmpUsed);
2419 MONITOR(BmpNew);
2420
2421 void game_get_framerate()
2422 {       
2423         char text[128] = "";
2424
2425         if ( frame_int == -1 )  {
2426                 int i;
2427                 for (i=0; i<FRAME_FILTER; i++ ) {
2428                         frametimes[i] = 0.0f;
2429                 }
2430                 frametotal = 0.0f;
2431                 frame_int = 0;
2432         }
2433         frametotal -= frametimes[frame_int];
2434         frametotal += flFrametime;
2435         frametimes[frame_int] = flFrametime;
2436         frame_int = (frame_int + 1 ) % FRAME_FILTER;
2437
2438         if ( frametotal != 0.0 )        {
2439                 if ( Framecount >= FRAME_FILTER )
2440                         Framerate = FRAME_FILTER / frametotal;
2441                 else
2442                         Framerate = Framecount / frametotal;
2443                 sprintf( text, NOX("FPS: %.1f"), Framerate );
2444         } else {
2445                 sprintf( text, NOX("FPS: ?") );
2446         }
2447         Framecount++;
2448
2449         if (Show_framerate)     {
2450                 gr_set_color_fast(&HUD_color_debug);
2451                 gr_string( 570, 2, text );
2452         }
2453 }
2454
2455 void game_show_framerate()
2456 {       
2457         float   cur_time;
2458
2459         cur_time = f2fl(timer_get_approx_seconds());
2460         if (cur_time - Start_time > 30.0f) {
2461                 mprintf(("%i frames executed in %7.3f seconds, %7.3f frames per second.\n", Framecount, cur_time - Start_time, Framecount/(cur_time - Start_time)));
2462                 Start_time += 1000.0f;
2463         }
2464
2465         //mprintf(( "%s\n", text ));
2466
2467 #ifndef NDEBUG
2468         if ( Debug_dump_frames )
2469                 return;
2470 #endif  
2471
2472         // possibly show control checking info
2473         control_check_indicate();
2474
2475 //      int bitmaps_used_this_frame, bitmaps_new_this_frame;
2476 //      bm_get_frame_usage(&bitmaps_used_this_frame,&bitmaps_new_this_frame);
2477 //      MONITOR_INC(BmpUsed, bitmaps_used_this_frame);
2478 // MONITOR_INC(BmpNew, bitmaps_new_this_frame);
2479
2480 #ifndef NDEBUG
2481         if ( Show_cpu == 1 ) {
2482                 
2483                 int sx,sy,dy;
2484                 sx = 530;
2485                 sy = 15;
2486                 dy = gr_get_font_height() + 1;
2487
2488                 gr_set_color_fast(&HUD_color_debug);
2489
2490                 {
2491 #ifndef PLAT_UNIX
2492                         extern int D3D_textures_in;
2493                         extern int D3D_textures_in_frame;
2494                         extern int Glide_textures_in;
2495                         extern int Glide_textures_in_frame;
2496                         extern int Glide_explosion_vram;
2497                         gr_printf( sx, sy, NOX("VRAM: %d KB\n"), (D3D_textures_in+Glide_textures_in)/1024 );
2498                         sy += dy;
2499                         gr_printf( sx, sy, NOX("VRAM: +%d KB\n"), (Glide_textures_in_frame+D3D_textures_in_frame)/1024 );
2500                         sy += dy;
2501                         gr_printf( sx, sy, NOX("EXP VRAM: %dKB\n"), (Glide_explosion_vram)/1024 );
2502                         sy += dy;
2503 #else
2504                         STUB_FUNCTION;
2505 #endif
2506                 }
2507 //              gr_printf( sx, sy, "BPP: %d", gr_screen.bits_per_pixel );
2508 //              sy += dy;
2509                 gr_printf( sx, sy, NOX("DMA: %s"), transfer_text );
2510                 sy += dy;
2511                 gr_printf( sx, sy, NOX("POLYP: %d"), modelstats_num_polys );
2512                 sy += dy;
2513                 gr_printf( sx, sy, NOX("POLYD: %d"), modelstats_num_polys_drawn );
2514                 sy += dy;
2515                 gr_printf( sx, sy, NOX("VERTS: %d"), modelstats_num_verts );
2516                 sy += dy;
2517
2518                 {
2519
2520                         extern int Num_pairs;           // Number of object pairs that were checked.
2521                         gr_printf( sx, sy, NOX("PAIRS: %d"), Num_pairs );
2522                         sy += dy;
2523
2524                         extern int Num_pairs_checked;   // What percent of object pairs were checked.
2525                         gr_printf( sx, sy, NOX("FVI: %d"), Num_pairs_checked );
2526                         sy += dy;
2527                         Num_pairs_checked = 0;
2528
2529                 }
2530
2531                 gr_printf( sx, sy, NOX("Snds: %d"), snd_num_playing() );
2532                 sy += dy;
2533
2534                 if ( Timing_total > 0.01f )     {
2535                         gr_printf(  sx, sy, NOX("CLEAR: %.0f%%"), Timing_clear*100.0f/Timing_total );
2536                         sy += dy;
2537                         gr_printf( sx, sy, NOX("REND2D: %.0f%%"), Timing_render2*100.0f/Timing_total );
2538                         sy += dy;
2539                         gr_printf( sx, sy, NOX("REND3D: %.0f%%"), Timing_render3*100.0f/Timing_total );
2540                         sy += dy;
2541                         gr_printf( sx, sy, NOX("FLIP: %.0f%%"), Timing_flip*100.0f/Timing_total );
2542                         sy += dy;
2543                         gr_printf( sx, sy, NOX("GAME: %.0f%%"), (Timing_total-(Timing_render2+Timing_render3+Timing_flip+Timing_clear))*100.0f/Timing_total );
2544                         sy += dy;
2545                 }
2546         }
2547                 
2548         if ( Show_mem  ) {
2549                 
2550                 int sx,sy,dy;
2551                 sx = 530;
2552                 sy = 15;
2553                 dy = gr_get_font_height() + 1;
2554
2555                 gr_set_color_fast(&HUD_color_debug);
2556
2557                 {
2558                         extern int TotalRam;
2559                         gr_printf( sx, sy, NOX("DYN: %d KB\n"), TotalRam/1024 );
2560                         sy += dy;
2561                 }       
2562
2563                 {
2564                         extern int Model_ram;
2565                         gr_printf( sx, sy, NOX("POF: %d KB\n"), Model_ram/1024 );
2566                         sy += dy;
2567                 }       
2568
2569                 gr_printf( sx, sy, NOX("BMP: %d KB\n"), bm_texture_ram/1024 );
2570                 sy += dy;
2571                 gr_printf( sx, sy, NOX("S-SRAM: %d KB\n"), Snd_sram/1024 );             // mem used to store game sound
2572                 sy += dy;
2573                 gr_printf( sx, sy, NOX("S-HRAM: %d KB\n"), Snd_hram/1024 );             // mem used to store game sound
2574                 sy += dy;
2575                 {
2576 #ifndef PLAT_UNIX
2577                         extern int D3D_textures_in;
2578                         extern int Glide_textures_in;
2579                         extern int Glide_textures_in_frame;
2580                         extern int Glide_explosion_vram;
2581                         gr_printf( sx, sy, NOX("VRAM: %d KB\n"), (D3D_textures_in+Glide_textures_in)/1024 );
2582                         sy += dy;
2583                         gr_printf( sx, sy, NOX("VRAM: +%d KB\n"), (Glide_textures_in_frame)/1024 );
2584                         sy += dy;
2585                         gr_printf( sx, sy, NOX("EXP VRAM: %dKB\n"), (Glide_explosion_vram)/1024 );
2586                         sy += dy;
2587 #else
2588                         STUB_FUNCTION;
2589 #endif
2590                 }
2591         }
2592
2593
2594         if ( Show_player_pos ) {
2595                 int sx, sy;
2596                 sx = 320;
2597                 sy = 100;
2598                 gr_printf(sx, sy, NOX("Player Pos: (%d,%d,%d)"), fl2i(Player_obj->pos.x), fl2i(Player_obj->pos.y), fl2i(Player_obj->pos.z));
2599         }
2600
2601         MONITOR_INC(NumPolys, modelstats_num_polys);
2602         MONITOR_INC(NumPolysDrawn, modelstats_num_polys_drawn );
2603         MONITOR_INC(NumVerts, modelstats_num_verts );
2604
2605         modelstats_num_polys = 0;
2606         modelstats_num_polys_drawn = 0;
2607         modelstats_num_verts = 0;
2608         modelstats_num_sortnorms = 0;
2609 #endif
2610 }
2611
2612 void game_show_standalone_framerate()
2613 {
2614         float frame_rate=30.0f;
2615         if ( frame_int == -1 )  {
2616                 int i;
2617                 for (i=0; i<FRAME_FILTER; i++ ) {
2618                         frametimes[i] = 0.0f;
2619                 }
2620                 frametotal = 0.0f;
2621                 frame_int = 0;
2622         }
2623         frametotal -= frametimes[frame_int];
2624         frametotal += flFrametime;
2625         frametimes[frame_int] = flFrametime;
2626         frame_int = (frame_int + 1 ) % FRAME_FILTER;
2627
2628         if ( frametotal != 0.0 )        {
2629                 if ( Framecount >= FRAME_FILTER ){
2630                         frame_rate = FRAME_FILTER / frametotal;
2631                 } else {
2632                         frame_rate = Framecount / frametotal;
2633                 }
2634         }
2635         std_set_standalone_fps(frame_rate);
2636         Framecount++;
2637 }
2638
2639 // function to show the time remaining in a mission.  Used only when the end-mission sexpression is used
2640 void game_show_time_left()
2641 {
2642         int diff;
2643
2644         // mission_end_time is a global from missionparse.cpp that contains the mission time at which the
2645         // mission should end (in fixed seconds).  There is code in missionparse.cpp which actually handles
2646         // checking how much time is left
2647
2648         if ( Mission_end_time == -1 ){
2649                 return;
2650         }
2651
2652         diff = f2i(Mission_end_time - Missiontime);
2653         // be sure to bash to 0.  diff could be negative on frame that we quit mission
2654         if ( diff < 0 ){
2655                 diff = 0;
2656         }
2657
2658         hud_set_default_color();
2659         gr_printf( 5, 40, XSTR( "Mission time remaining: %d seconds", 179), diff );
2660 }
2661
2662 //========================================================================================
2663 //=================== NEW DEBUG CONSOLE COMMANDS TO REPLACE OLD DEBUG PAUSE MENU =========
2664 //========================================================================================
2665
2666 #ifndef NDEBUG
2667
2668 DCF(ai_pause,"Pauses ai")
2669 {
2670         if ( Dc_command )       {       
2671                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
2672                 if ( Dc_arg_type & ARG_TRUE )   ai_paused = 1;  
2673                 else if ( Dc_arg_type & ARG_FALSE ) ai_paused = 0;      
2674                 else if ( Dc_arg_type & ARG_NONE ) ai_paused = !ai_paused;      
2675
2676                 if (ai_paused)  {       
2677                         obj_init_all_ships_physics();
2678                 }
2679         }       
2680         if ( Dc_help )  dc_printf( "Usage: ai_paused [bool]\nSets ai_paused to true or false.  If nothing passed, then toggles it.\n" );        
2681         if ( Dc_status )        dc_printf( "ai_paused is %s\n", (ai_paused?"TRUE":"FALSE") );   
2682 }
2683
2684 DCF(single_step,"Single steps the game")
2685 {
2686         if ( Dc_command )       {       
2687                 dc_get_arg(ARG_TRUE|ARG_FALSE|ARG_NONE);                
2688                 if ( Dc_arg_type & ARG_TRUE )   game_single_step = 1;   
2689                 else if ( Dc_arg_type & ARG_FALSE ) game_single_step = 0;       
2690                 else if ( Dc_arg_type & ARG_NONE ) game_single_step = !game_single_step;        
2691
2692                 last_single_step = 0;   // Make so single step waits a frame before stepping
2693
2694         }       
2695         if ( Dc_help )  dc_printf( "Usage: single_step [bool]\nSets single_step to true or false.  If nothing passed, then toggles it.\n" );    
2696         if ( Dc_status )        dc_printf( "single_step is %s\n", (game_single_step?"TRUE":"FALSE") );  
2697 }
2698
2699 DCF_BOOL(physics_pause, physics_paused)
2700 DCF_BOOL(ai_rendering, Ai_render_debug_flag)
2701 DCF_BOOL(ai_firing, Ai_firing_enabled )
2702
2703 // Create some simple aliases to these commands...
2704 debug_command dc_s("s","shortcut for single_step",dcf_single_step);
2705 debug_command dc_p("p","shortcut for physics_pause", dcf_physics_pause );
2706 debug_command dc_r("r","shortcut for ai_rendering", dcf_ai_rendering );
2707 debug_command dc_f("f","shortcut for ai_firing", dcf_ai_firing);
2708 debug_command dc_a("a","shortcut for ai_pause", dcf_ai_pause);
2709 #endif
2710
2711 //========================================================================================
2712 //========================================================================================
2713
2714
2715 void game_training_pause_do()
2716 {
2717         int key;
2718
2719         key = game_check_key();
2720         if (key > 0){
2721                 gameseq_post_event(GS_EVENT_PREVIOUS_STATE);
2722         }
2723
2724         gr_flip();
2725 }
2726
2727
2728 void game_increase_skill_level()
2729 {
2730         Game_skill_level++;
2731         if (Game_skill_level >= NUM_SKILL_LEVELS){
2732                 Game_skill_level = 0;
2733         }
2734 }
2735
2736 int     Player_died_time;
2737
2738 int View_percent = 100;
2739
2740
2741 DCF(view, "Sets the percent of the 3d view to render.")
2742 {
2743         if ( Dc_command ) {
2744                 dc_get_arg(ARG_INT);
2745                 if ( (Dc_arg_int >= 5 ) || (Dc_arg_int <= 100) ) {
2746                         View_percent = Dc_arg_int;
2747                 } else {
2748                         dc_printf( "Illegal value for view. (Must be from 5-100) \n\n");
2749                         Dc_help = 1;
2750                 }
2751         }
2752
2753         if ( Dc_help ) {
2754                 dc_printf("Usage: view [n]\nwhere n is percent of view to show (5-100).\n");
2755         }
2756         
2757         if ( Dc_status ) {
2758                 dc_printf("View is set to %d%%\n", View_percent );
2759         }
2760 }
2761
2762
2763 // Set the clip region for the 3d rendering window
2764 void game_set_view_clip()
2765 {
2766         if ((Game_mode & GM_DEAD) || (supernova_active() >= 2)) {
2767                 // Set the clip region for the letterbox "dead view"
2768                 int yborder = gr_screen.max_h/4;
2769
2770                 //      Numeric constants encouraged by J "pig farmer" S, who shall remain semi-anonymous.
2771                 // J.S. I've changed my ways!! See the new "no constants" code!!!
2772                 gr_set_clip(0, yborder, gr_screen.max_w, gr_screen.max_h - yborder*2 ); 
2773         } else {
2774                 // Set the clip region for normal view
2775                 if ( View_percent >= 100 )      {
2776                         gr_reset_clip();
2777                 } else {
2778                         int xborder, yborder;
2779
2780                         if ( View_percent < 5 ) {
2781                                 View_percent = 5;
2782                         }
2783
2784                         float fp = i2fl(View_percent)/100.0f;
2785                         int fi = fl2i(fl_sqrt(fp)*100.0f);
2786                         if ( fi > 100 ) fi=100;
2787                         
2788                         xborder = ( gr_screen.max_w*(100-fi) )/200;
2789                         yborder = ( gr_screen.max_h*(100-fi) )/200;
2790
2791                         gr_set_clip(xborder, yborder, gr_screen.max_w-xborder*2,gr_screen.max_h-yborder*2 );
2792                 }
2793         }
2794 }
2795
2796
2797 void show_debug_stuff()
2798 {
2799         int     i;
2800         int     laser_count = 0, missile_count = 0;
2801
2802         for (i=0; i<MAX_OBJECTS; i++) {
2803                 if (Objects[i].type == OBJ_WEAPON){
2804                         if (Weapon_info[Weapons[Objects[i].instance].weapon_info_index].subtype == WP_LASER){
2805                                 laser_count++;
2806                         } else if (Weapon_info[Weapons[Objects[i].instance].weapon_info_index].subtype == WP_MISSILE){
2807                                 missile_count++;
2808                         }
2809                 }
2810         }
2811
2812         nprintf(("Mike", "Frame: %i Lasers: %4i, Missiles: %4i\n", Framecount, laser_count, missile_count));
2813 }
2814
2815 extern int Tool_enabled;
2816 int tst = 0;
2817 int tst_time = 0;
2818 int tst_big = 0;
2819 vector tst_pos;
2820 int tst_bitmap = -1;
2821 float tst_x, tst_y;
2822 float tst_offset, tst_offset_total;
2823 int tst_mode;
2824 int tst_stamp;
2825 void game_tst_frame_pre()
2826 {
2827         // start tst
2828         if(tst == 3){
2829                 tst = 0;
2830
2831                 // screen position
2832                 vertex v;
2833                 g3_rotate_vertex(&v, &tst_pos);
2834                 g3_project_vertex(&v);  
2835         
2836                 // offscreen
2837                 if(!((v.sx >= 0) && (v.sx <= gr_screen.max_w) && (v.sy >= 0) && (v.sy <= gr_screen.max_h))){
2838                         return;
2839                 }       
2840
2841                 // big ship? always tst
2842                 if(tst_big){
2843                         // within 3000 meters
2844                         if( vm_vec_dist_quick(&tst_pos, &Eye_position) <= 3000.0f){
2845                                 tst = 2;                                
2846                         }
2847                 } else {                        
2848                         // within 300 meters
2849                         if( (vm_vec_dist_quick(&tst_pos, &Eye_position) <= 300.0f) && ((tst_time == 0) || ((time(NULL) - tst_time) >= 10)) ){
2850                                 tst = 2;                                
2851                         } 
2852                 }                       
2853         }
2854
2855 }
2856 void game_tst_frame()
2857 {
2858         int left = 0;
2859
2860         if(!Tool_enabled){
2861                 return;
2862         }
2863         
2864         // setup tst
2865         if(tst == 2){           
2866                 tst_time = time(NULL);
2867
2868                 // load the tst bitmap          
2869                 switch((int)frand_range(0.0f, 3.0)){
2870                 case 0:                 
2871                         tst_bitmap = bm_load("ig_jim");
2872                         left = 1;
2873                         mprintf(("TST 0\n"));
2874                         break;
2875
2876                 case 1:
2877                         tst_bitmap = bm_load("ig_kan");
2878                         left = 0;
2879                         mprintf(("TST 1\n"));
2880                         break;
2881
2882                 case 2:
2883                         tst_bitmap = bm_load("ig_jim");
2884                         left = 1;
2885                         mprintf(("TST 2\n"));
2886                         break;
2887                         
2888                 default:                        
2889                         tst_bitmap = bm_load("ig_kan");
2890                         left = 0;
2891                         mprintf(("TST 3\n"));
2892                         break;
2893                 }
2894
2895                 if(tst_bitmap < 0){
2896                         tst = 0;
2897                         return;
2898                 }               
2899
2900                 // get the tst bitmap dimensions
2901                 int w, h;
2902                 bm_get_info(tst_bitmap, &w, &h);
2903
2904                 // tst y
2905                 tst_y = frand_range(0.0f, (float)gr_screen.max_h - h);
2906
2907                 snd_play(&Snds[SND_VASUDAN_BUP]);
2908
2909                 // tst x and direction
2910                 tst_mode = 0;
2911                 if(left){
2912                         tst_x = (float)-w;
2913                         tst_offset_total = (float)w;
2914                         tst_offset = (float)w;
2915                 } else {
2916                         tst_x = (float)gr_screen.max_w;
2917                         tst_offset_total = (float)-w;
2918                         tst_offset = (float)w;
2919                 }
2920
2921                 tst = 1;
2922         }
2923
2924         // run tst
2925         if(tst == 1){
2926                 float diff = (tst_offset_total / 0.5f) * flFrametime;
2927
2928                 // move the bitmap
2929                 if(tst_mode == 0){
2930                         tst_x += diff;
2931                         
2932                         tst_offset -= fl_abs(diff);
2933                 } else if(tst_mode == 2){
2934                         tst_x -= diff;
2935                         
2936                         tst_offset -= fl_abs(diff);
2937                 }
2938
2939                 // draw the bitmap
2940                 gr_set_bitmap(tst_bitmap);
2941                 gr_bitmap((int)tst_x, (int)tst_y);
2942
2943                 if(tst_mode == 1){
2944                         if(timestamp_elapsed_safe(tst_stamp, 1100)){
2945                                 tst_mode = 2;
2946                         }
2947                 } else {
2948                         // if we passed the switch point
2949                         if(tst_offset <= 0.0f){
2950                                 // switch modes
2951                                 switch(tst_mode){
2952                                 case 0:
2953                                         tst_mode = 1;
2954                                         tst_stamp = timestamp(1000);
2955                                         tst_offset = fl_abs(tst_offset_total);
2956                                         break;                          
2957
2958                                 case 2:                         
2959                                         tst = 0;
2960                                         return;
2961                                 }
2962                         }                               
2963                 }
2964         }
2965 }
2966 void game_tst_mark(object *objp, ship *shipp)
2967 {
2968         ship_info *sip; 
2969
2970         if(!Tool_enabled){
2971                 return;
2972         }
2973
2974         // bogus
2975         if((objp == NULL) || (shipp == NULL) || (shipp->ship_info_index < 0) || (shipp->ship_info_index >= Num_ship_types)){
2976                 return;
2977         }
2978         sip = &Ship_info[shipp->ship_info_index];
2979
2980         // already tst
2981         if(tst){
2982                 return;
2983         }
2984
2985         tst_pos = objp->pos;
2986         if(sip->flags & (SIF_BIG_SHIP | SIF_HUGE_SHIP)){
2987                 tst_big = 1;
2988         }
2989         tst = 3;
2990 }
2991
2992 extern void render_shields();
2993
2994 void player_repair_frame(float frametime)
2995 {
2996         if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)){
2997                 int idx;
2998                 for(idx=0;idx<MAX_PLAYERS;idx++){
2999                         net_player *np;
3000
3001                         np = &Net_players[idx];
3002
3003                         if(MULTI_CONNECTED(Net_players[idx]) && (Net_player != NULL) && (Net_player->player_id != Net_players[idx].player_id) && (Net_players[idx].player != NULL) && (Net_players[idx].player->objnum >= 0) && (Net_players[idx].player->objnum < MAX_OBJECTS)){
3004
3005                                 // don't rearm/repair if the player is dead or dying/departing
3006                                 if ( !NETPLAYER_IS_DEAD(np) && !(Ships[Objects[np->player->objnum].instance].flags & (SF_DYING|SF_DEPARTING)) ) {
3007                                         ai_do_repair_frame(&Objects[Net_players[idx].player->objnum],&Ai_info[Ships[Objects[Net_players[idx].player->objnum].instance].ai_index],frametime);
3008                                 }
3009                         }
3010                 }
3011         }       
3012         if ( (Player_obj != NULL) && (Player_obj->type == OBJ_SHIP) && !(Game_mode & GM_STANDALONE_SERVER) && (Player_ship != NULL) && !(Player_ship->flags & SF_DYING) ) {
3013                 ai_do_repair_frame(Player_obj, &Ai_info[Ships[Player_obj->instance].ai_index], frametime);
3014         }
3015 }
3016
3017
3018 #ifndef NDEBUG
3019 #define NUM_FRAMES_TEST         300
3020 #define NUM_MIXED_SOUNDS        16
3021 void do_timing_test(float flFrametime)
3022 {
3023         static int framecount = 0;
3024         static int test_running = 0;
3025         static float test_time = 0.0f;
3026
3027         static int snds[NUM_MIXED_SOUNDS];
3028         int i;
3029
3030         if ( test_running ) {
3031                 framecount++;
3032                 test_time += flFrametime;
3033                 if ( framecount >= NUM_FRAMES_TEST ) {
3034                         test_running = 0;
3035                         nprintf(("General", "%d frames took %.3f seconds\n", NUM_FRAMES_TEST, test_time));
3036                         for ( i = 0; i < NUM_MIXED_SOUNDS; i++ )
3037                                 snd_stop(snds[i]);
3038                 }
3039         }
3040
3041         if ( Test_begin == 1 ) {
3042                 framecount = 0;
3043                 test_running = 1;
3044                 test_time = 0.0f;
3045                 Test_begin = 0;
3046
3047                 for ( i = 0; i < NUM_MIXED_SOUNDS; i++ )
3048                         snds[i] = -1;
3049
3050                 // start looping digital sounds
3051                 for ( i = 0; i < NUM_MIXED_SOUNDS; i++ )
3052                         snds[i] = snd_play_looping( &Snds[i], 0.0f, -1, -1);
3053         }
3054         
3055
3056 }
3057 #endif
3058
3059 DCF(dcf_fov, "Change the field of view")
3060 {
3061         if ( Dc_command )       {
3062                 dc_get_arg(ARG_FLOAT|ARG_NONE);
3063                 if ( Dc_arg_type & ARG_NONE )   {
3064                         Viewer_zoom = VIEWER_ZOOM_DEFAULT;
3065                         dc_printf( "Zoom factor reset\n" );
3066                 }
3067                 if ( Dc_arg_type & ARG_FLOAT )  {
3068                         if (Dc_arg_float < 0.25f) {
3069                                 Viewer_zoom = 0.25f;
3070                                 dc_printf("Zoom factor pinned at 0.25.\n");
3071                         } else if (Dc_arg_float > 1.25f) {
3072                                 Viewer_zoom = 1.25f;
3073                                 dc_printf("Zoom factor pinned at 1.25.\n");
3074                         } else {
3075                                 Viewer_zoom = Dc_arg_float;
3076                         }
3077                 }
3078         }
3079
3080         if ( Dc_help )  
3081                 dc_printf( "Usage: fov [factor]\nFactor is the zoom factor btwn .25 and 1.25\nNo parameter resets it to default.\n" );
3082
3083         if ( Dc_status )                                
3084                 dc_printf("Zoom factor set to %6.3f (original = 0.5, John = 0.75)", Viewer_zoom);
3085 }
3086
3087
3088 DCF(framerate_cap, "Sets the framerate cap")
3089 {
3090         if ( Dc_command ) {
3091                 dc_get_arg(ARG_INT);
3092                 if ( (Dc_arg_int >= 1 ) || (Dc_arg_int <= 120) ) {
3093                         Framerate_cap = Dc_arg_int;
3094                 } else {
3095                         dc_printf( "Illegal value for framerate cap. (Must be from 1-120) \n\n");
3096                         Dc_help = 1;
3097                 }
3098         }
3099
3100         if ( Dc_help ) {
3101                 dc_printf("Usage: framerate_cap [n]\nwhere n is the frames per second to cap framerate at.\n");
3102                 dc_printf("If n is 0 or omitted, then the framerate cap is removed\n");
3103                 dc_printf("[n] must be from 1 to 120.\n");
3104         }
3105         
3106         if ( Dc_status ) {
3107                 if ( Framerate_cap )
3108                         dc_printf("Framerate cap is set to %d fps\n", Framerate_cap );
3109                 else
3110                         dc_printf("There is no framerate cap currently active.\n");
3111         }
3112 }
3113
3114 #define MIN_DIST_TO_DEAD_CAMERA         50.0f
3115 int Show_viewing_from_self = 0;
3116
3117 void say_view_target()
3118 {
3119         object  *view_target;
3120
3121         if ((Viewer_mode & VM_OTHER_SHIP) && (Player_ai->target_objnum != -1))
3122                 view_target = &Objects[Player_ai->target_objnum];
3123         else
3124                 view_target = Player_obj;
3125
3126         if (Game_mode & GM_DEAD) {
3127                 if (Player_ai->target_objnum != -1)
3128                         view_target = &Objects[Player_ai->target_objnum];
3129         }
3130
3131         if (!(Game_mode & GM_DEAD_DIED) && ((Game_mode & (GM_DEAD_BLEW_UP)) || ((Last_view_target != NULL) && (Last_view_target != view_target)))) {
3132                 if (view_target != Player_obj){
3133
3134                         char *view_target_name = NULL;
3135                         switch(Objects[Player_ai->target_objnum].type) {
3136                         case OBJ_SHIP:
3137                                 view_target_name = Ships[Objects[Player_ai->target_objnum].instance].ship_name;
3138                                 break;
3139                         case OBJ_WEAPON:
3140                                 view_target_name = Weapon_info[Weapons[Objects[Player_ai->target_objnum].instance].weapon_info_index].name;
3141                                 Viewer_mode &= ~VM_OTHER_SHIP;
3142                                 break;
3143                         case OBJ_JUMP_NODE: {
3144                                 char    jump_node_name[128];
3145                                 strcpy(jump_node_name, XSTR( "jump node", 184));
3146                                 view_target_name = jump_node_name;
3147                                 Viewer_mode &= ~VM_OTHER_SHIP;
3148                                 break;
3149                                 }
3150
3151                         default:
3152                                 Int3();
3153                                 break;
3154                         }
3155
3156                         if ( view_target_name ) {
3157                                 HUD_fixed_printf(0.0f, XSTR( "Viewing %s%s\n", 185), (Viewer_mode & VM_OTHER_SHIP) ? XSTR( "from ", 186) : "", view_target_name);
3158                                 Show_viewing_from_self = 1;
3159                         }
3160                 } else {
3161                         if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_OBSERVER) && (Player_obj->type == OBJ_OBSERVER)){
3162                                 HUD_fixed_printf(2.0f,XSTR( "Viewing from observer\n", 187));
3163                                 Show_viewing_from_self = 1;
3164                         } else {
3165                                 if (Show_viewing_from_self)
3166                                         HUD_fixed_printf(2.0f, XSTR( "Viewing from self\n", 188));
3167                         }
3168                 }
3169         }
3170
3171         Last_view_target = view_target;
3172 }
3173
3174
3175 float Game_hit_x = 0.0f;
3176 float Game_hit_y = 0.0f;
3177
3178 // Reset at the beginning of each frame
3179 void game_whack_reset()
3180 {
3181         Game_hit_x = 0.0f;
3182         Game_hit_y = 0.0f;
3183 }
3184
3185 // Apply a 2d whack to the player
3186 void game_whack_apply( float x, float y )
3187 {
3188         // Do some force feedback
3189         joy_ff_play_dir_effect(x * 80.0f, y * 80.0f);
3190
3191         // Move the eye 
3192         Game_hit_x += x;
3193         Game_hit_y += y;
3194
3195 //      mprintf(( "WHACK = %.1f, %.1f\n", Game_hit_x, Game_hit_y ));
3196 }
3197
3198 // call to apply a "shudder"
3199 void game_shudder_apply(int time, float intensity)
3200 {
3201         Game_shudder_time = timestamp(time);
3202         Game_shudder_total = time;
3203         Game_shudder_intensity = intensity;
3204 }
3205
3206 #define FF_SCALE        10000
3207 void apply_hud_shake(matrix *eye_orient)
3208 {
3209         if (Viewer_obj == Player_obj) {
3210                 physics_info    *pi = &Player_obj->phys_info;
3211
3212                 angles  tangles;
3213
3214                 tangles.p = 0.0f;
3215                 tangles.h = 0.0f;
3216                 tangles.b = 0.0f;
3217
3218                 //      Make eye shake due to afterburner
3219                 if ( !timestamp_elapsed(pi->afterburner_decay) ) {                      
3220                         int             dtime;
3221
3222                         dtime = timestamp_until(pi->afterburner_decay);
3223                         
3224                         int r1 = myrand();
3225                         int r2 = myrand();
3226                         tangles.p += 0.07f * (float) (r1-RAND_MAX/2)/RAND_MAX * (0.5f - fl_abs(0.5f - (float) dtime/ABURN_DECAY_TIME));
3227                         tangles.h += 0.07f * (float) (r2-RAND_MAX/2)/RAND_MAX * (0.5f - fl_abs(0.5f - (float) dtime/ABURN_DECAY_TIME));
3228                 }
3229
3230                 // Make eye shake due to engine wash
3231                 extern int Wash_on;
3232                 if (Player_obj->type == OBJ_SHIP && (Ships[Player_obj->instance].wash_intensity > 0) && Wash_on ) {
3233                         int r1 = myrand();
3234                         int r2 = myrand();
3235                         tangles.p += 0.07f * Ships[Player_obj->instance].wash_intensity * (float) (r1-RAND_MAX/2)/RAND_MAX;
3236                         tangles.h += 0.07f * Ships[Player_obj->instance].wash_intensity * (float) (r2-RAND_MAX/2)/RAND_MAX;
3237
3238                         // get the   intensity
3239                         float intensity = FF_SCALE * Ships[Player_obj->instance].wash_intensity;
3240
3241                         // vector rand_vec
3242                         vector rand_vec;
3243                         vm_vec_rand_vec_quick(&rand_vec);
3244
3245                         // play the effect
3246                         joy_ff_play_dir_effect(intensity*rand_vec.x, intensity*rand_vec.y);
3247                 }
3248
3249         
3250                 // make hud shake due to shuddering
3251                 if(Game_shudder_time != -1){
3252                         // if the timestamp has elapsed
3253                         if(timestamp_elapsed(Game_shudder_time)){
3254                                 Game_shudder_time = -1;
3255                         } 
3256                         // otherwise apply some shudder
3257                         else {
3258                                 int dtime;
3259
3260                                 dtime = timestamp_until(Game_shudder_time);
3261                         
3262                                 int r1 = myrand();
3263                                 int r2 = myrand();
3264                                 tangles.p += (Game_shudder_intensity / 200.0f) * (float) (r1-RAND_MAX/2)/RAND_MAX * (0.5f - fl_abs(0.5f - (float) dtime/(float)Game_shudder_total));
3265                                 tangles.h += (Game_shudder_intensity / 200.0f) * (float) (r2-RAND_MAX/2)/RAND_MAX * (0.5f - fl_abs(0.5f - (float) dtime/(float)Game_shudder_total));
3266                         }
3267                 }
3268
3269                 matrix  tm, tm2;
3270                 vm_angles_2_matrix(&tm, &tangles);
3271                 Assert(vm_vec_mag(&tm.fvec) > 0.0f);
3272                 Assert(vm_vec_mag(&tm.rvec) > 0.0f);
3273                 Assert(vm_vec_mag(&tm.uvec) > 0.0f);
3274                 vm_matrix_x_matrix(&tm2, eye_orient, &tm);
3275                 *eye_orient = tm2;
3276         }
3277 }
3278
3279 extern void compute_slew_matrix(matrix *orient, angles *a);     // TODO: move code to proper place and extern in header file
3280
3281 //      Player's velocity just before he blew up.  Used to keep camera target moving.
3282 vector  Dead_player_last_vel = {1.0f, 1.0f, 1.0f};
3283
3284 //      Set eye_pos and eye_orient based on view mode.
3285 void game_render_frame_setup(vector *eye_pos, matrix *eye_orient)
3286 {
3287         vector  eye_dir;
3288
3289         static int last_Viewer_mode = 0;
3290         static int last_Game_mode = 0;
3291         static int last_Viewer_objnum = -1;
3292
3293         // This code is supposed to detect camera "cuts"... like going between
3294         // different views.
3295
3296         // determine if we need to regenerate the nebula
3297         if(     (!(last_Viewer_mode & VM_EXTERNAL) && (Viewer_mode & VM_EXTERNAL)) ||                                                   // internal to external 
3298                         ((last_Viewer_mode & VM_EXTERNAL) && !(Viewer_mode & VM_EXTERNAL)) ||                                                   // external to internal
3299                         (!(last_Viewer_mode & VM_DEAD_VIEW) && (Viewer_mode & VM_DEAD_VIEW)) ||                                                 // non dead-view to dead-view
3300                         ((last_Viewer_mode & VM_DEAD_VIEW) && !(Viewer_mode & VM_DEAD_VIEW)) ||                                                 // dead-view to non dead-view
3301                         (!(last_Viewer_mode & VM_WARP_CHASE) && (Viewer_mode & VM_WARP_CHASE)) ||                                               // non warp-chase to warp-chase
3302                         ((last_Viewer_mode & VM_WARP_CHASE) && !(Viewer_mode & VM_WARP_CHASE)) ||                                               // warp-chase to non warp-chase
3303                         (!(last_Viewer_mode & VM_OTHER_SHIP) && (Viewer_mode & VM_OTHER_SHIP)) ||                                               // non other-ship to other-ship
3304                         ((last_Viewer_mode & VM_OTHER_SHIP) && !(Viewer_mode & VM_OTHER_SHIP)) ||                                               // other-ship to non-other ship
3305                         ((Viewer_mode & VM_OTHER_SHIP) && (last_Viewer_objnum != Player_ai->target_objnum))             // other ship mode, but targets changes
3306                         ) {
3307
3308                 // regenerate the nebula
3309                 neb2_eye_changed();
3310         }               
3311
3312         if ( (last_Viewer_mode != Viewer_mode) || (last_Game_mode != Game_mode) )       {
3313                 //mprintf(( "************** Camera cut! ************\n" ));
3314                 last_Viewer_mode = Viewer_mode;
3315                 last_Game_mode = Game_mode;
3316
3317                 // Camera moved.  Tell stars & debris to not do blurring.
3318                 stars_camera_cut();             
3319         }
3320
3321         say_view_target();
3322
3323         if ( Viewer_mode & VM_PADLOCK_ANY ) {
3324                 player_display_packlock_view();
3325         }
3326         
3327         game_set_view_clip();
3328
3329         if (Game_mode & GM_DEAD) {
3330                 vector  vec_to_deader, view_pos;
3331                 float           dist;
3332
3333                 Viewer_mode |= VM_DEAD_VIEW;
3334
3335                 if (Player_ai->target_objnum != -1) {
3336                         int view_from_player = 1;
3337
3338                         if (Viewer_mode & VM_OTHER_SHIP) {
3339                                 //      View from target.
3340                                 Viewer_obj = &Objects[Player_ai->target_objnum];
3341
3342                                 last_Viewer_objnum = Player_ai->target_objnum;
3343
3344                                 if ( Viewer_obj->type == OBJ_SHIP ) {
3345                                         ship_get_eye( eye_pos, eye_orient, Viewer_obj );
3346                                         view_from_player = 0;
3347                                 }
3348                         } else {
3349                                 last_Viewer_objnum = -1;
3350                         }
3351
3352                         if ( view_from_player ) {
3353                                 //      View target from player ship.
3354                                 Viewer_obj = NULL;
3355                                 *eye_pos = Player_obj->pos;
3356                                 vm_vec_normalized_dir(&eye_dir, &Objects[Player_ai->target_objnum].pos, eye_pos);
3357                                 vm_vector_2_matrix(eye_orient, &eye_dir, NULL, NULL);
3358                         }
3359                 } else {
3360                         dist = vm_vec_normalized_dir(&vec_to_deader, &Player_obj->pos, &Dead_camera_pos);
3361                         
3362                         if (dist < MIN_DIST_TO_DEAD_CAMERA)
3363                                 dist += flFrametime * 16.0f;
3364
3365                         vm_vec_scale(&vec_to_deader, -dist);
3366                         vm_vec_add(&Dead_camera_pos, &Player_obj->pos, &vec_to_deader);
3367                         
3368                         view_pos = Player_obj->pos;
3369
3370                         if (!(Game_mode & GM_DEAD_BLEW_UP)) {
3371                                 Viewer_mode &= ~(VM_EXTERNAL | VM_CHASE);
3372                                 vm_vec_scale_add2(&Dead_camera_pos, &Original_vec_to_deader, 25.0f * flFrametime);
3373                                 Dead_player_last_vel = Player_obj->phys_info.vel;
3374                                 //nprintf(("AI", "Player death roll vel = %7.3f %7.3f %7.3f\n", Player_obj->phys_info.vel.x, Player_obj->phys_info.vel.y, Player_obj->phys_info.vel.z));
3375                         } else if (Player_ai->target_objnum != -1) {
3376                                 view_pos = Objects[Player_ai->target_objnum].pos;
3377                         } else {
3378                                 //      Make camera follow explosion, but gradually slow down.
3379                                 vm_vec_scale_add2(&Player_obj->pos, &Dead_player_last_vel, flFrametime);
3380                                 view_pos = Player_obj->pos;
3381                                 vm_vec_scale(&Dead_player_last_vel, 0.99f);
3382                                 vm_vec_scale_add2(&Dead_camera_pos, &Original_vec_to_deader, min(25.0f, vm_vec_mag_quick(&Dead_player_last_vel)) * flFrametime);
3383                         }
3384
3385                         *eye_pos = Dead_camera_pos;
3386
3387                         vm_vec_normalized_dir(&eye_dir, &Player_obj->pos, eye_pos);
3388
3389                         vm_vector_2_matrix(eye_orient, &eye_dir, NULL, NULL);
3390                         Viewer_obj = NULL;
3391                 }
3392         } 
3393
3394         // if supernova shockwave
3395         if(supernova_camera_cut()){
3396                 // no viewer obj
3397                 Viewer_obj = NULL;
3398
3399                 // call it dead view
3400                 Viewer_mode |= VM_DEAD_VIEW;
3401
3402                 // set eye pos and orient
3403                 supernova_set_view(eye_pos, eye_orient);
3404         } else {        
3405                 //      If already blown up, these other modes can override.
3406                 if (!(Game_mode & (GM_DEAD | GM_DEAD_BLEW_UP))) {
3407                         Viewer_mode &= ~VM_DEAD_VIEW;
3408
3409                         Viewer_obj = Player_obj;
3410  
3411                         if (Viewer_mode & VM_OTHER_SHIP) {
3412                                 if (Player_ai->target_objnum != -1){
3413                                         Viewer_obj = &Objects[Player_ai->target_objnum];
3414                                         last_Viewer_objnum = Player_ai->target_objnum;
3415                                 } else {
3416                                         Viewer_mode &= ~VM_OTHER_SHIP;
3417                                         last_Viewer_objnum = -1;
3418                                 }
3419                         } else {
3420                                 last_Viewer_objnum = -1;
3421                         }
3422
3423                         if (Viewer_mode & VM_EXTERNAL) {
3424                                 matrix  tm, tm2;
3425
3426                                 vm_angles_2_matrix(&tm2, &Viewer_external_info.angles);
3427                                 vm_matrix_x_matrix(&tm, &Viewer_obj->orient, &tm2);
3428
3429                                 vm_vec_scale_add(eye_pos, &Viewer_obj->pos, &tm.fvec, 2.0f * Viewer_obj->radius + Viewer_external_info.distance);
3430
3431                                 vm_vec_sub(&eye_dir, &Viewer_obj->pos, eye_pos);
3432                                 vm_vec_normalize(&eye_dir);
3433                                 vm_vector_2_matrix(eye_orient, &eye_dir, &Viewer_obj->orient.uvec, NULL);
3434                                 Viewer_obj = NULL;
3435
3436                                 //      Modify the orientation based on head orientation.
3437                                 compute_slew_matrix(eye_orient, &Viewer_slew_angles);
3438
3439                         } else if ( Viewer_mode & VM_CHASE ) {
3440                                 vector  move_dir;
3441
3442                                 if ( Viewer_obj->phys_info.speed < 0.1 )
3443                                         move_dir = Viewer_obj->orient.fvec;
3444                                 else {
3445                                         move_dir = Viewer_obj->phys_info.vel;
3446                                         vm_vec_normalize(&move_dir);
3447                                 }
3448
3449                                 vm_vec_scale_add(eye_pos, &Viewer_obj->pos, &move_dir, -3.0f * Viewer_obj->radius - Viewer_chase_info.distance);
3450                                 vm_vec_scale_add2(eye_pos, &Viewer_obj->orient.uvec, 0.75f * Viewer_obj->radius);
3451                                 vm_vec_sub(&eye_dir, &Viewer_obj->pos, eye_pos);
3452                                 vm_vec_normalize(&eye_dir);
3453
3454                                 // JAS: I added the following code because if you slew up using
3455                                 // Descent-style physics, eye_dir and Viewer_obj->orient.uvec are
3456                                 // equal, which causes a zero-length vector in the vm_vector_2_matrix
3457                                 // call because the up and the forward vector are the same.   I fixed
3458                                 // it by adding in a fraction of the right vector all the time to the
3459                                 // up vector.
3460                                 vector tmp_up = Viewer_obj->orient.uvec;
3461                                 vm_vec_scale_add2( &tmp_up, &Viewer_obj->orient.rvec, 0.00001f );
3462
3463                                 vm_vector_2_matrix(eye_orient, &eye_dir, &tmp_up, NULL);
3464                                 Viewer_obj = NULL;
3465
3466                                 //      Modify the orientation based on head orientation.
3467                                 compute_slew_matrix(eye_orient, &Viewer_slew_angles);
3468                         } else if ( Viewer_mode & VM_WARP_CHASE ) {
3469                                         *eye_pos = Camera_pos;
3470
3471                                         ship * shipp = &Ships[Player_obj->instance];
3472
3473                                         vm_vec_sub(&eye_dir, &shipp->warp_effect_pos, eye_pos);
3474                                         vm_vec_normalize(&eye_dir);
3475                                         vm_vector_2_matrix(eye_orient, &eye_dir, &Player_obj->orient.uvec, NULL);
3476                                         Viewer_obj = NULL;
3477                         } else {
3478                                 // get an eye position based upon the correct type of object
3479                                 switch(Viewer_obj->type){
3480                                 case OBJ_SHIP:
3481                                         // make a call to get the eye point for the player object
3482                                         ship_get_eye( eye_pos, eye_orient, Viewer_obj );
3483                                         break;
3484                                 case OBJ_OBSERVER:
3485                                         // make a call to get the eye point for the player object
3486                                         observer_get_eye( eye_pos, eye_orient, Viewer_obj );                            
3487                                         break;
3488                                 default :
3489                                         Int3();
3490                                 }
3491
3492                                 #ifdef JOHNS_DEBUG_CODE
3493                                 john_debug_stuff(&eye_pos, &eye_orient);
3494                                 #endif
3495                         }
3496                 }
3497         }
3498
3499         apply_hud_shake(eye_orient);
3500
3501         // setup neb2 rendering
3502         neb2_render_setup(eye_pos, eye_orient);
3503 }
3504
3505 #ifndef NDEBUG
3506 extern void ai_debug_render_stuff();
3507 #endif
3508
3509 int Game_subspace_effect = 0;
3510 DCF_BOOL( subspace, Game_subspace_effect );
3511
3512 // Does everything needed to render a frame
3513 void game_render_frame( vector * eye_pos, matrix * eye_orient )
3514 {
3515         int dont_offset;
3516
3517         g3_start_frame(game_zbuffer);
3518         g3_set_view_matrix( eye_pos, eye_orient, Viewer_zoom );
3519
3520         // maybe offset the HUD (jitter stuff)
3521         dont_offset = ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_OBSERVER));
3522         HUD_set_offsets(Viewer_obj, !dont_offset);
3523         
3524         // for multiplayer clients, call code in Shield.cpp to set up the Shield_hit array.  Have to
3525         // do this becaues of the disjointed nature of this system (in terms of setup and execution).
3526         // must be done before ships are rendered
3527         if ( MULTIPLAYER_CLIENT ) {
3528                 shield_point_multi_setup();
3529         }
3530
3531         if ( Game_subspace_effect )     {
3532                 stars_draw(0,0,0,1);
3533         } else {
3534                 stars_draw(1,1,1,0);
3535         }
3536
3537         obj_render_all(obj_render);
3538         beam_render_all();                                              // render all beam weapons
3539         particle_render_all();                                  // render particles after everything else.
3540         trail_render_all();                                             // render missilie trails after everything else.        
3541         mflash_render_all();                                            // render all muzzle flashes    
3542
3543         //      Why do we not show the shield effect in these modes?  Seems ok.
3544         //if (!(Viewer_mode & (VM_EXTERNAL | VM_SLEWED | VM_CHASE | VM_DEAD_VIEW))) {
3545         render_shields();
3546         //}
3547
3548         // render nebula lightning
3549         nebl_render_all();
3550
3551         // render local player nebula
3552         neb2_render_player();   
3553
3554 #ifndef NDEBUG
3555         ai_debug_render_stuff();
3556 #endif
3557
3558 #ifndef RELEASE_REAL
3559         // game_framerate_check();
3560 #endif
3561
3562 #ifndef NDEBUG
3563         extern void snd_spew_debug_info();
3564         snd_spew_debug_info();
3565 #endif
3566
3567         //================ END OF 3D RENDERING STUFF ====================
3568
3569         hud_show_radar();
3570
3571         if( (Game_detail_flags & DETAIL_FLAG_HUD) && !(Game_mode & GM_MULTIPLAYER) || ( (Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_OBSERVER) ) ) {
3572                 hud_maybe_clear_head_area();
3573                 anim_render_all(0, flFrametime);
3574         }
3575
3576         extern int Multi_display_netinfo;
3577         if(Multi_display_netinfo){
3578                 extern void multi_display_netinfo();
3579                 multi_display_netinfo();
3580         }       
3581
3582         game_tst_frame_pre();
3583
3584 #ifndef NDEBUG
3585         do_timing_test(flFrametime);
3586 #endif
3587
3588 #ifndef NDEBUG
3589         extern int OO_update_index;     
3590         multi_rate_display(OO_update_index, 375, 0);
3591 #endif
3592
3593 #ifndef NDEBUG
3594         // test
3595         extern void oo_display();
3596         oo_display();                   
3597 #endif
3598         
3599         g3_end_frame();
3600 }
3601
3602 //#define JOHNS_DEBUG_CODE      1
3603
3604 #ifdef JOHNS_DEBUG_CODE
3605 void john_debug_stuff(vector *eye_pos, matrix *eye_orient)
3606 {
3607         //if ( keyd_pressed[KEY_LSHIFT] )               
3608         {
3609                 ship_subsys *tsys = Players[Player_num].targeted_subobject;
3610                 if ( tsys )     {
3611                         model_subsystem *turret = tsys->system_info;
3612
3613                         if (turret->type == SUBSYSTEM_TURRET )  {
3614                                 vector fvec, uvec;
3615                                 object * tobj = &Objects[Players[Player_num].targeted_subobject_parent];
3616
3617                                 ship_model_start(tobj);
3618
3619                                 model_find_world_point(eye_pos, &turret->turret_firing_point[0], turret->model_num, turret->turret_gun_sobj, &tobj->orient, &tobj->pos );
3620                                 model_find_world_dir(&fvec, &turret->turret_matrix.fvec, turret->model_num, turret->turret_gun_sobj, &tobj->orient, NULL );
3621                                 model_find_world_dir(&uvec, &turret->turret_matrix.uvec, turret->model_num, turret->turret_gun_sobj, &tobj->orient, NULL );
3622                                 
3623                                 vm_vector_2_matrix( eye_orient, &fvec, &uvec, NULL );
3624
3625                                 ship_model_stop(tobj);
3626
3627                                 Viewer_obj = NULL;
3628                         }
3629                 }
3630
3631         }
3632 }
3633 #endif
3634
3635 // following function for dumping frames for purposes of building trailers.
3636 #ifndef NDEBUG
3637
3638 // function to toggle state of dumping every frame into PCX when playing the game
3639 DCF(dump_frames, "Starts/stop frame dumping at 15 hz")
3640 {
3641         if ( Dc_command )       {
3642
3643                 if ( Debug_dump_frames == 0 )   {
3644                         // Turn it on
3645                         Debug_dump_frames = 15;
3646                         Debug_dump_trigger = 0;
3647                         gr_dump_frame_start( Debug_dump_frame_num, DUMP_BUFFER_NUM_FRAMES );
3648                         dc_printf( "Frame dumping at 15 hz is now ON\n" );
3649                 } else {
3650                         // Turn it off
3651                         Debug_dump_frames = 0;
3652                         Debug_dump_trigger = 0;
3653                         gr_dump_frame_stop();
3654                         dc_printf( "Frame dumping is now OFF\n" );
3655                 }
3656                 
3657         }
3658 }
3659
3660 DCF(dump_frames_trigger, "Starts/stop frame dumping at 15 hz")
3661 {
3662         if ( Dc_command )       {
3663
3664                 if ( Debug_dump_frames == 0 )   {
3665                         // Turn it on
3666                         Debug_dump_frames = 15;
3667                         Debug_dump_trigger = 1;
3668                         gr_dump_frame_start( Debug_dump_frame_num, DUMP_BUFFER_NUM_FRAMES );
3669                         dc_printf( "Frame dumping at 15 hz is now ON\n" );
3670                 } else {
3671                         // Turn it off
3672                         Debug_dump_frames = 0;
3673                         Debug_dump_trigger = 0;
3674                         gr_dump_frame_stop();
3675                         dc_printf( "Frame dumping is now OFF\n" );
3676                 }
3677                 
3678         }
3679 }
3680
3681 DCF(dump_frames30, "Starts/stop frame dumping at 30 hz")
3682 {
3683         if ( Dc_command )       {
3684
3685                 if ( Debug_dump_frames == 0 )   {
3686                         // Turn it on
3687                         Debug_dump_frames = 30;
3688                         Debug_dump_trigger = 0;
3689                         gr_dump_frame_start( Debug_dump_frame_num, DUMP_BUFFER_NUM_FRAMES );
3690                         dc_printf( "Frame dumping at 30 hz is now ON\n" );
3691                 } else {
3692                         // Turn it off
3693                         Debug_dump_frames = 0;
3694                         Debug_dump_trigger = 0;
3695                         gr_dump_frame_stop();
3696                         dc_printf( "Frame dumping is now OFF\n" );
3697                 }
3698                 
3699         }
3700 }
3701
3702 DCF(dump_frames30_trigger, "Starts/stop frame dumping at 30 hz")
3703 {
3704         if ( Dc_command )       {
3705
3706                 if ( Debug_dump_frames == 0 )   {
3707                         // Turn it on
3708                         Debug_dump_frames = 30;
3709                         Debug_dump_trigger = 1;
3710                         gr_dump_frame_start( Debug_dump_frame_num, DUMP_BUFFER_NUM_FRAMES );
3711                         dc_printf( "Triggered frame dumping at 30 hz is now ON\n" );
3712                 } else {
3713                         // Turn it off
3714                         Debug_dump_frames = 0;
3715                         Debug_dump_trigger = 0;
3716                         gr_dump_frame_stop();
3717                         dc_printf( "Triggered frame dumping is now OFF\n" );
3718                 }
3719                 
3720         }
3721 }
3722
3723 void game_maybe_dump_frame()
3724 {
3725         if ( !Debug_dump_frames ){
3726                 return;
3727         }
3728
3729         if( Debug_dump_trigger && !keyd_pressed[KEY_Q] ){
3730                 return;
3731         }
3732
3733         game_stop_time();
3734
3735         gr_dump_frame();
3736         Debug_dump_frame_num++;
3737
3738         game_start_time();
3739 }
3740 #endif
3741
3742 extern int Player_dead_state;
3743
3744 //      Flip the page and time how long it took.
3745 void game_flip_page_and_time_it()
3746 {       
3747         fix t1, t2,d;
3748         int t;
3749         t1 = timer_get_fixed_seconds();
3750         gr_flip();
3751         t2 = timer_get_fixed_seconds();
3752         d = t2 - t1;
3753         t = (gr_screen.max_w*gr_screen.max_h*gr_screen.bytes_per_pixel)/1024;
3754         sprintf( transfer_text, NOX("%d MB/s"), fixmuldiv(t,65,d) );
3755 }
3756
3757 void game_simulation_frame()
3758 {
3759         // blow ships up in multiplayer dogfight
3760         if((Game_mode & GM_MULTIPLAYER) && (Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && (Netgame.type_flags & NG_TYPE_DOGFIGHT) && (f2fl(Missiontime) >= 2.0f) && !dogfight_blown){
3761                 // blow up all non-player ships
3762                 ship_obj *moveup = GET_FIRST(&Ship_obj_list);
3763                 ship *shipp;
3764                 ship_info *sip;
3765                 while((moveup != END_OF_LIST(&Ship_obj_list)) && (moveup != NULL)){
3766                         // bogus
3767                         if((moveup->objnum < 0) || (moveup->objnum >= MAX_OBJECTS) || (Objects[moveup->objnum].type != OBJ_SHIP) || (Objects[moveup->objnum].instance < 0) || (Objects[moveup->objnum].instance >= MAX_SHIPS) || (Ships[Objects[moveup->objnum].instance].ship_info_index < 0) || (Ships[Objects[moveup->objnum].instance].ship_info_index >= Num_ship_types)){
3768                                 moveup = GET_NEXT(moveup);
3769                                 continue;
3770                         }
3771                         shipp = &Ships[Objects[moveup->objnum].instance];
3772                         sip = &Ship_info[shipp->ship_info_index];
3773
3774                         // only blow up small ships                     
3775                         if((sip->flags & SIF_SMALL_SHIP) && (multi_find_player_by_object(&Objects[moveup->objnum]) < 0) ){                                                      
3776                                 // function to simply explode a ship where it is currently at
3777                                 ship_self_destruct( &Objects[moveup->objnum] );                                 
3778                         }
3779
3780                         moveup = GET_NEXT(moveup);
3781                 }
3782
3783                 dogfight_blown = 1;
3784         }
3785
3786         // process AWACS stuff - do this first thing
3787         awacs_process();
3788
3789         // single player, set Player hits_this_frame to 0
3790         if ( !(Game_mode & GM_MULTIPLAYER) && Player ) {
3791                 Player->damage_this_burst -= (flFrametime * MAX_BURST_DAMAGE  / (0.001f * BURST_DURATION));
3792                 Player->damage_this_burst = max(Player->damage_this_burst, 0.0f);
3793         }
3794
3795         // supernova
3796         supernova_process();
3797         if(supernova_active() >= 5){
3798                 return;
3799         }
3800
3801         // fire targeting lasers now so that 
3802         // 1 - created this frame
3803         // 2 - collide this frame
3804         // 3 - render this frame
3805         // 4 - ignored and deleted next frame
3806         // the basic idea being that because it con be confusing to deal with them on a multi-frame basis, they are only valid for
3807         // frame
3808         ship_process_targeting_lasers();        
3809
3810         // do this here so that it works for multiplayer
3811         if ( Viewer_obj ) {
3812                 // get viewer direction
3813                 int viewer_direction = PHYSICS_VIEWER_REAR;
3814
3815                 if(Viewer_mode == 0){
3816                         viewer_direction = PHYSICS_VIEWER_FRONT;
3817                 }
3818                 if(Viewer_mode & VM_PADLOCK_UP){
3819                         viewer_direction = PHYSICS_VIEWER_UP;
3820                 }
3821                 else if(Viewer_mode & VM_PADLOCK_REAR){
3822                         viewer_direction = PHYSICS_VIEWER_REAR;
3823                 } 
3824                 else if(Viewer_mode & VM_PADLOCK_LEFT){
3825                         viewer_direction = PHYSICS_VIEWER_LEFT;
3826                 } 
3827                 else if(Viewer_mode & VM_PADLOCK_RIGHT){
3828                         viewer_direction = PHYSICS_VIEWER_RIGHT;
3829                 }
3830
3831                 physics_set_viewer( &Viewer_obj->phys_info, viewer_direction );
3832         } else {
3833                 physics_set_viewer( NULL, PHYSICS_VIEWER_FRONT );
3834         }
3835
3836 #define VM_PADLOCK_UP                                   (1 << 7)
3837 #define VM_PADLOCK_REAR                         (1 << 8)
3838 #define VM_PADLOCK_LEFT                         (1 << 9)
3839 #define VM_PADLOCK_RIGHT                                (1 << 10)
3840                 
3841         // evaluate mission departures and arrivals before we process all objects.
3842         if ( !(Game_mode & GM_MULTIPLAYER) || ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER) && !multi_endgame_ending()) ) {
3843
3844                 // we don't want to evaluate mission stuff when any ingame joiner in multiplayer is receiving
3845                 // ships/wing packets.
3846                 if ( !((Game_mode & GM_MULTIPLAYER) && (Netgame.flags & NG_FLAG_INGAME_JOINING_CRITICAL)) && !(Game_mode & GM_DEMO_PLAYBACK)){
3847                         mission_parse_eval_stuff();
3848                 }
3849
3850                 // if we're an observer, move ourselves seperately from the standard physics
3851                 if((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_OBSERVER)){
3852                         obj_observer_move(flFrametime);
3853                 }
3854                 
3855                 // move all the objects now
3856                 obj_move_all(flFrametime);
3857
3858                 // check for cargo reveal (this has an internal timestamp, so only runs every N ms)
3859                 // AL: 3-15-98: It was decided to not let AI ships inspect cargo
3860                 //      ship_check_cargo_all();
3861                 if(!(Game_mode & GM_DEMO_PLAYBACK)){
3862                         mission_eval_goals();
3863                 }
3864         }
3865
3866         // always check training objectives, even in multiplayer missions. we need to do this so that the directives gauge works properly on clients
3867         if(!(Game_mode & GM_DEMO_PLAYBACK)){
3868                 training_check_objectives();
3869         }
3870         
3871         // do all interpolation now
3872         if ( (Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER) && !multi_endgame_ending() && !(Netgame.flags & NG_FLAG_SERVER_LOST)) {
3873                 // client side processing of warping in effect stages
3874                 multi_do_client_warp(flFrametime);     
3875         
3876                 // client side movement of an observer
3877                 if((Net_player->flags & NETINFO_FLAG_OBSERVER) || (Player_obj->type == OBJ_OBSERVER)){
3878                         obj_observer_move(flFrametime);   
3879                 }
3880
3881                 // move all objects - does interpolation now as well
3882                 obj_move_all(flFrametime);
3883         }
3884
3885         // only process the message queue when the player is "in" the game
3886         if ( !Pre_player_entry ){
3887                 message_queue_process();                                // process any messages send to the player
3888         }
3889
3890         if(!(Game_mode & GM_DEMO_PLAYBACK)){
3891                 message_maybe_distort();                                // maybe distort incoming message if comms damaged
3892                 player_repair_frame(flFrametime);       //      AI objects get repaired in ai_process, called from move code...deal with player.
3893                 player_process_pending_praise();                // maybe send off a delayed praise message to the player
3894                 player_maybe_play_all_alone_msg();      // mabye tell the player he is all alone        
3895         }
3896
3897         if(!(Game_mode & GM_STANDALONE_SERVER)){                
3898                 // process some stuff every frame (before frame is rendered)
3899                 emp_process_local();
3900
3901                 hud_update_frame();                                             // update hud systems
3902
3903                 if (!physics_paused)    {
3904                         // Move particle system
3905                         particle_move_all(flFrametime); 
3906
3907                         // Move missile trails
3908                         trail_move_all(flFrametime);            
3909
3910                         // process muzzle flashes
3911                         mflash_process_all();
3912
3913                         // Flash the gun flashes
3914                         shipfx_flash_do_frame(flFrametime);                     
3915
3916                         shockwave_move_all(flFrametime);        // update all the shockwaves
3917                 }
3918
3919                 // subspace missile strikes
3920                 ssm_process();
3921
3922                 obj_snd_do_frame();                                             // update the object-linked persistant sounds
3923                 game_maybe_update_sound_environment();
3924                 snd_update_listener(&View_position, &Player_obj->phys_info.vel, &Player_obj->orient);
3925
3926 // AL: debug code used for testing ambient subspace sound (ie when enabling subspace through debug console)
3927 #ifndef NDEBUG
3928                 if ( Game_subspace_effect ) {
3929                         game_start_subspace_ambient_sound();
3930                 }
3931 #endif
3932         }               
3933 }
3934
3935 // Maybe render and process the dead-popup
3936 void game_maybe_do_dead_popup(float frametime)
3937 {
3938         if ( popupdead_is_active() ) {
3939                 int leave_popup=1;
3940                 int choice = popupdead_do_frame(frametime);
3941
3942                 if ( Game_mode & GM_NORMAL ) {
3943                         switch(choice) {
3944                         case 0:
3945                                 // CD CHECK                             
3946                                 if(game_do_cd_mission_check(Game_current_mission_filename)){
3947                                         gameseq_post_event(GS_EVENT_ENTER_GAME);
3948                                 } else {
3949                                         gameseq_post_event(GS_EVENT_MAIN_MENU);
3950                                 }                                       
3951                                 break;
3952
3953                         case 1:
3954                                 gameseq_post_event(GS_EVENT_END_GAME);
3955                                 break;
3956
3957                         case 2:
3958                                 // CD CHECK
3959                                 if(game_do_cd_mission_check(Game_current_mission_filename)){
3960                                         gameseq_post_event(GS_EVENT_START_GAME);                                        
3961                                 } else {
3962                                         gameseq_post_event(GS_EVENT_MAIN_MENU);
3963                                 }                                       
3964                                 break;
3965
3966                         // this should only happen during a red alert mission
3967                         case 3:                         
3968                                 // bogus?
3969                                 Assert(The_mission.red_alert);
3970                                 if(!The_mission.red_alert){
3971                                         // CD CHECK
3972                                         if(game_do_cd_mission_check(Game_current_mission_filename)){
3973                                                 gameseq_post_event(GS_EVENT_START_GAME);
3974                                         } else {
3975                                                 gameseq_post_event(GS_EVENT_MAIN_MENU);
3976                                         }
3977                                         break;
3978                                 }
3979                                 
3980                                 // choose the previous mission
3981                                 mission_campaign_previous_mission();
3982                                 // CD CHECK
3983                                 if(game_do_cd_mission_check(Game_current_mission_filename)){
3984                                         gameseq_post_event(GS_EVENT_START_GAME);
3985                                 } else {
3986                                         gameseq_post_event(GS_EVENT_MAIN_MENU);
3987                                 }                               
3988                                 break;
3989
3990                         default:
3991                                 leave_popup=0;
3992                                 break;
3993                         }
3994                 } else {
3995                         switch( choice ) {
3996
3997                         case POPUPDEAD_DO_MAIN_HALL:
3998                                 multi_quit_game(PROMPT_NONE,-1);
3999                                 break;
4000
4001                         case POPUPDEAD_DO_RESPAWN:                              
4002                                 multi_respawn_normal();
4003                                 event_music_player_respawn();
4004                                 break;
4005
4006                         case POPUPDEAD_DO_OBSERVER:
4007                                 multi_respawn_observer();
4008                                 event_music_player_respawn_as_observer();
4009                                 break;
4010
4011                         default:
4012                                 leave_popup = 0;
4013                                 break;
4014                         }
4015                 }
4016
4017                 if ( leave_popup ) {
4018                         popupdead_close();
4019                 }
4020         }
4021 }
4022
4023 // returns true if player is actually in a game_play stats
4024 int game_actually_playing()
4025 {
4026         int state;
4027
4028         state = gameseq_get_state();
4029         if ( (state != GS_STATE_GAME_PLAY) && (state != GS_STATE_DEATH_DIED) && (state != GS_STATE_DEATH_BLEW_UP) )
4030                 return 0;
4031         else
4032                 return 1;
4033 }
4034
4035 // Draw the 2D HUD gauges
4036 void game_render_hud_2d()
4037 {
4038         if ( !(Game_detail_flags & DETAIL_FLAG_HUD) ) {
4039                 return;
4040         }
4041         
4042         HUD_render_2d(flFrametime);
4043         gr_reset_clip();
4044 }
4045
4046 // Draw the 3D-dependant HUD gauges
4047 void game_render_hud_3d(vector *eye_pos, matrix *eye_orient)
4048 {
4049         g3_start_frame(0);              // 0 = turn zbuffering off
4050         g3_set_view_matrix( eye_pos, eye_orient, Viewer_zoom );
4051
4052         if ( (Game_detail_flags & DETAIL_FLAG_HUD) && (supernova_active() < 3)/* && !(Game_mode & GM_MULTIPLAYER) || ( (Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_OBSERVER) )*/ ) {
4053                 HUD_render_3d(flFrametime);
4054         }
4055
4056         // Do the sunspot
4057         game_sunspot_process(flFrametime);
4058
4059         // Diminish the palette effect
4060         game_flash_diminish(flFrametime);
4061
4062         g3_end_frame();
4063 }
4064
4065
4066 void game_frame()
4067 {
4068         int actually_playing;
4069         fix total_time1, total_time2;
4070         fix render2_time1=0, render2_time2=0;
4071         fix render3_time1=0, render3_time2=0;
4072         fix flip_time1=0, flip_time2=0;
4073         fix clear_time1=0, clear_time2=0;
4074         
4075         vector eye_pos;
4076         matrix eye_orient;
4077
4078 #ifndef NDEBUG
4079         if (Framerate_delay) {
4080                 int     start_time = timer_get_milliseconds();
4081                 while (timer_get_milliseconds() < start_time + Framerate_delay)
4082                         ;
4083         }
4084 #endif
4085
4086 #ifdef DEMO_SYSTEM
4087         demo_do_frame_start();
4088         if(Demo_error){
4089                 mprintf(("Error (%d) while processing demo!\n", Demo_error));
4090                 demo_close();
4091         }
4092 #endif
4093         
4094         // start timing frame
4095         timing_frame_start();
4096
4097         total_time1 = timer_get_fixed_seconds();
4098
4099         // var to hold which state we are in
4100         actually_playing = game_actually_playing();
4101         
4102         if ((!(Game_mode & GM_MULTIPLAYER)) || ((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_OBSERVER))) {
4103                 if (!(Game_mode & GM_STANDALONE_SERVER)){
4104                         Assert( OBJ_INDEX(Player_obj) >= 0 );
4105                 }
4106         }
4107
4108         if (Missiontime > Entry_delay_time){
4109                 Pre_player_entry = 0;
4110         } else {
4111                 ; //nprintf(("AI", "Framecount = %i, time = %7.3f\n", Framecount, f2fl(Missiontime)));
4112         }
4113
4114         //      Note: These are done even before the player enters, else buffers can overflow.
4115         if (! (Game_mode & GM_STANDALONE_SERVER)){
4116                 radar_frame_init();
4117         }
4118
4119         shield_frame_init();
4120
4121         if ( Player->control_mode != PCM_NORMAL )
4122                 camera_move();
4123
4124         if ( !Pre_player_entry && actually_playing ) {                          
4125                 if (! (Game_mode & GM_STANDALONE_SERVER) ) {
4126
4127                         if( (!popup_running_state()) && (!popupdead_is_active()) ){
4128                                 game_process_keys();
4129
4130                                 // don't read flying controls if we're playing a demo back
4131                                 if(!(Game_mode & GM_DEMO_PLAYBACK)){
4132                                         read_player_controls( Player_obj, flFrametime);
4133                                 }
4134                         }
4135                         
4136                         // if we're not the master, we may have to send the server-critical ship status button_info bits
4137                         if ((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER) && !(Net_player->flags & NETINFO_FLAG_OBSERVER)){
4138                                 multi_maybe_send_ship_status();
4139                         }
4140                 }
4141         }
4142
4143         // Reset the whack stuff
4144         game_whack_reset();
4145
4146         // These two lines must be outside of Pre_player_entry code,
4147         // otherwise too many lights are added.
4148         light_reset();
4149
4150         if ((Game_mode & GM_MULTIPLAYER) && (Netgame.game_state == NETGAME_STATE_SERVER_TRANSFER)){
4151                 return;
4152         }
4153         
4154         game_simulation_frame();        
4155
4156         // if not actually in a game play state, then return.  This condition could only be true in 
4157         // a multiplayer game.
4158         if ( !actually_playing ) {
4159                 Assert( Game_mode & GM_MULTIPLAYER );
4160                 return;
4161         }
4162
4163         if (!Pre_player_entry) {
4164                 if (! (Game_mode & GM_STANDALONE_SERVER)) {
4165                         clear_time1 = timer_get_fixed_seconds();
4166                         // clear the screen to black
4167                         gr_reset_clip();
4168                         if ( (Game_detail_flags & DETAIL_FLAG_CLEAR) ) {
4169                                 gr_clear();
4170                         }
4171
4172                         clear_time2 = timer_get_fixed_seconds();
4173                         render3_time1 = timer_get_fixed_seconds();
4174                         game_render_frame_setup(&eye_pos, &eye_orient);
4175                         game_render_frame( &eye_pos, &eye_orient );
4176
4177                         // save the eye position and orientation
4178                         if ( Game_mode & GM_MULTIPLAYER ) {
4179                                 Net_player->s_info.eye_pos = eye_pos;
4180                                 Net_player->s_info.eye_orient = eye_orient;
4181                         }
4182
4183                         hud_show_target_model();
4184
4185                         // check to see if we should display the death died popup
4186                         if(Game_mode & GM_DEAD_BLEW_UP){                                
4187                                 if(Game_mode & GM_MULTIPLAYER){
4188                                         // catch the situation where we're supposed to be warping out on this transition
4189                                         if(Net_player->flags & NETINFO_FLAG_WARPING_OUT){
4190                                                 gameseq_post_event(GS_EVENT_DEBRIEF);
4191                                         } else if((Player_died_popup_wait != -1) && (timestamp_elapsed(Player_died_popup_wait))){
4192                                                 Player_died_popup_wait = -1;
4193                                                 popupdead_start();
4194                                         }
4195                                 } else {
4196                                         if((Player_died_popup_wait != -1) && (timestamp_elapsed(Player_died_popup_wait))){
4197                                                 Player_died_popup_wait = -1;
4198                                                 popupdead_start();
4199                                         }
4200                                 }
4201                         }
4202
4203                         // hack - sometimes this seems to slip by in multiplayer. this should guarantee that we catch it
4204                         if((Game_mode & GM_MULTIPLAYER) && (Player_multi_died_check != -1) && (Game_mode & GM_DEAD_BLEW_UP) ){
4205                                 if(fl_abs(time(NULL) - Player_multi_died_check) > 4){
4206                                         if(!popupdead_is_active()){
4207                                                 popupdead_start();
4208                                         }
4209
4210                                         Player_multi_died_check = -1;
4211                                 }
4212                         }
4213         
4214                         render3_time2 = timer_get_fixed_seconds();
4215                         render2_time1 = timer_get_fixed_seconds();
4216
4217                         gr_reset_clip();
4218                         game_get_framerate();
4219                         game_show_framerate();          
4220
4221                         game_show_time_left();
4222
4223                         // Draw the 2D HUD gauges
4224                         if(supernova_active() < 3){
4225                                 game_render_hud_2d();
4226                         }
4227
4228                         game_set_view_clip();
4229
4230                         // Draw 3D HUD gauges                   
4231                         game_render_hud_3d(&eye_pos, &eye_orient);                                                                      
4232
4233                         game_tst_frame();
4234
4235                         render2_time2 = timer_get_fixed_seconds();
4236
4237                         // maybe render and process the dead popup
4238                         game_maybe_do_dead_popup(flFrametime);
4239
4240                         // start timing frame
4241                         timing_frame_stop();
4242                         // timing_display(30, 10);                      
4243
4244                         // If a regular popup is active, don't flip (popup code flips)
4245                         if( !popup_running_state() ){
4246                                 flip_time1 = timer_get_fixed_seconds();
4247                                 game_flip_page_and_time_it();
4248                                 flip_time2 = timer_get_fixed_seconds();
4249                         }
4250
4251 #ifndef NDEBUG
4252                         game_maybe_dump_frame();                        // used to dump pcx files for building trailers
4253 #endif          
4254                 } else {
4255                         game_show_standalone_framerate();
4256                 }
4257         }
4258
4259         game_do_training_checks();
4260         asteroid_frame();
4261
4262         // process lightning (nebula only)
4263         nebl_process();
4264
4265         total_time2 = timer_get_fixed_seconds();
4266
4267         // Got some timing numbers
4268         Timing_total = f2fl( total_time2 - total_time1 ) * 1000.0f;
4269         Timing_clear = f2fl( clear_time2 - clear_time1 ) * 1000.0f;
4270         Timing_render2 = f2fl( render2_time2- render2_time1 ) * 1000.0f;
4271         Timing_render3 = f2fl( render3_time2- render3_time1 ) * 1000.0f;
4272         Timing_flip = f2fl( flip_time2 - flip_time1 ) * 1000.0f;
4273
4274 #ifdef DEMO_SYSTEM
4275         demo_do_frame_end();
4276         if(Demo_error){
4277                 mprintf(("Error (%d) while processing demo!\n", Demo_error));
4278                 demo_close();
4279         }
4280 #endif
4281 }
4282
4283 #define MAX_FRAMETIME   (F1_0/4)                // Frametime gets saturated at this.  Changed by MK on 11/1/97.
4284                                                                                                 //      Some bug was causing Frametime to always get saturated at 2.0 seconds after the player
4285                                                                                                 //      died.  This resulted in screwed up death sequences.
4286
4287 fix Last_time = 0;                                              // The absolute time of game at end of last frame (beginning of this frame)
4288 fix Last_delta_time = 0;                                // While game is paused, this keeps track of how much elapsed in the frame before paused.
4289 static int timer_paused=0;
4290 static int stop_count,start_count;
4291 static int time_stopped,time_started;
4292 int saved_timestamp_ticker = -1;
4293
4294 void game_reset_time()
4295 {
4296         if((Game_mode & GM_MULTIPLAYER) && (Netgame.game_state == NETGAME_STATE_SERVER_TRANSFER)){
4297                 return ;
4298         }
4299         
4300         //      Last_time = timer_get_fixed_seconds();
4301         game_start_time();
4302         timestamp_reset();
4303         game_stop_time();
4304 }
4305
4306 void game_stop_time()
4307 {
4308         if (timer_paused==0) {
4309                 fix time;
4310                 time = timer_get_fixed_seconds();
4311                 // Save how much time progressed so far in the frame so we can
4312                 // use it when we unpause.
4313                 Last_delta_time = time - Last_time;             
4314
4315                 //mprintf(("Last_time in game_stop_time = %7.3f\n", f2fl(Last_delta_time)));
4316                 if (Last_delta_time < 0) {
4317                         #if defined(TIMER_TEST) && !defined(NDEBUG)
4318                         Int3();         //get Matt!!!!
4319                         #endif
4320                         Last_delta_time = 0;
4321                 }
4322                 #if defined(TIMER_TEST) && !defined(NDEBUG)
4323                 time_stopped = time;
4324                 #endif
4325
4326                 // Stop the timer_tick stuff...
4327                 // Normally, you should never access 'timestamp_ticker', consider this a low-level routine
4328                 saved_timestamp_ticker = timestamp_ticker;
4329         }
4330         timer_paused++;
4331
4332         #if defined(TIMER_TEST) && !defined(NDEBUG)
4333         stop_count++;
4334         #endif
4335 }
4336
4337 void game_start_time()
4338 {
4339         timer_paused--;
4340         Assert(timer_paused >= 0);
4341         if (timer_paused==0) {
4342                 fix time;
4343                 time = timer_get_fixed_seconds();
4344                 #if defined(TIMER_TEST) && !defined(NDEBUG)
4345                 if (Last_time < 0)
4346                         Int3();         //get Matt!!!!
4347                 }
4348                 #endif
4349                 // Take current time, and set it backwards to account for time  
4350                 // that the frame already executed, so that timer_get_fixed_seconds() - Last_time
4351                 // will be correct when it goes to calculate the frametime next
4352                 // frame.
4353                 Last_time = time - Last_delta_time;             
4354                 #if defined(TIMER_TEST) && !defined(NDEBUG)
4355                 time_started = time;
4356                 #endif
4357
4358                 // Restore the timer_tick stuff...
4359                 // Normally, you should never access 'timestamp_ticker', consider this a low-level routine
4360                 Assert( saved_timestamp_ticker > -1 );          // Called out of order, get JAS
4361                 timestamp_ticker = saved_timestamp_ticker;
4362                 saved_timestamp_ticker = -1;
4363         }
4364
4365         #if defined(TIMER_TEST) && !defined(NDEBUG)
4366         start_count++;
4367         #endif
4368 }
4369
4370
4371 void game_set_frametime(int state)
4372 {
4373         fix thistime;
4374         float frame_cap_diff;
4375
4376         thistime = timer_get_fixed_seconds();
4377
4378         if ( Last_time == 0 )   
4379                 Frametime = F1_0 / 30;
4380         else
4381                 Frametime = thistime - Last_time;
4382
4383 //      Frametime = F1_0 / 30;
4384
4385         fix     debug_frametime = Frametime;    //      Just used to display frametime.
4386
4387         //      If player hasn't entered mission yet, make frame take 1/4 second.
4388         if ((Pre_player_entry) && (state == GS_STATE_GAME_PLAY))
4389                 Frametime = F1_0/4;
4390 #ifndef NDEBUG
4391         else if ((Debug_dump_frames) && (state == GS_STATE_GAME_PLAY)) {                                // note link to above if!!!!!
4392         
4393                 fix frame_speed = F1_0 / Debug_dump_frames;
4394
4395                 if (Frametime > frame_speed ){
4396                         nprintf(("warning","slow frame: %x\n",Frametime));
4397                 } else {                        
4398                         do {
4399                                 thistime = timer_get_fixed_seconds();
4400                                 Frametime = thistime - Last_time;
4401                         } while (Frametime < frame_speed );                     
4402                 }
4403                 Frametime = frame_speed;
4404         }
4405 #endif
4406
4407         Assert( Framerate_cap > 0 );
4408
4409         // Cap the framerate so it doesn't get too high.
4410         {
4411                 fix cap;
4412
4413                 cap = F1_0/Framerate_cap;
4414                 if (Frametime < cap) {
4415                         thistime = cap - Frametime;
4416                         //mprintf(("Sleeping for %6.3f seconds.\n", f2fl(thistime)));
4417                         Sleep( DWORD(f2fl(thistime) * 1000.0f) );
4418                         Frametime = cap;
4419                         thistime = timer_get_fixed_seconds();
4420                 }
4421         }
4422
4423         if((Game_mode & GM_STANDALONE_SERVER) && 
4424                 (f2fl(Frametime) < ((float)1.0/(float)Multi_options_g.std_framecap))){
4425
4426                 frame_cap_diff = ((float)1.0/(float)Multi_options_g.std_framecap) - f2fl(Frametime);            
4427                 Sleep((DWORD)(frame_cap_diff*1000));                            
4428                 
4429                 thistime += fl2f((frame_cap_diff));             
4430
4431                 Frametime = thistime - Last_time;
4432    }
4433
4434         // If framerate is too low, cap it.
4435         if (Frametime > MAX_FRAMETIME)  {
4436 #ifndef NDEBUG
4437                 mprintf(("Frame %2i too long!!: frametime = %.3f (%.3f)\n", Framecount, f2fl(Frametime), f2fl(debug_frametime)));
4438 #else 
4439                 // to remove warnings in release build
4440                 debug_frametime = fl2f(flFrametime);
4441 #endif
4442                 Frametime = MAX_FRAMETIME;
4443         }
4444
4445         Frametime = fixmul(Frametime, Game_time_compression);
4446
4447         Last_time = thistime;
4448         //mprintf(("Frame %i, Last_time = %7.3f\n", Framecount, f2fl(Last_time)));
4449
4450         flFrametime = f2fl(Frametime);
4451         //if(!(Game_mode & GM_PLAYING_DEMO)){
4452         timestamp_inc(flFrametime);
4453
4454 /*      if ((Framecount > 0) && (Framecount < 10)) {
4455                 mprintf(("Frame %2i: frametime = %.3f (%.3f)\n", Framecount, f2fl(Frametime), f2fl(debug_frametime)));
4456         }
4457 */
4458 }
4459
4460 // This is called from game_do_frame(), and from navmap_do_frame() 
4461 void game_update_missiontime()
4462 {
4463         // TODO JAS: Put in if and move this into game_set_frametime, 
4464         // fix navmap to call game_stop/start_time
4465         //if ( !timer_paused )  
4466                 Missiontime += Frametime;
4467 }
4468
4469 void game_do_frame()
4470 {       
4471         game_set_frametime(GS_STATE_GAME_PLAY);
4472         game_update_missiontime();
4473
4474         if (Game_mode & GM_STANDALONE_SERVER) {
4475                 std_multi_set_standalone_missiontime(f2fl(Missiontime));
4476         }
4477
4478         if ( game_single_step && (last_single_step == game_single_step) ) {
4479                 os_set_title( NOX("SINGLE STEP MODE (Pause exits, any other key steps)") );
4480                 while( key_checkch() == 0 )
4481                         os_sleep(10);
4482                 os_set_title( XSTR( "FreeSpace", 171) );
4483                 Last_time = timer_get_fixed_seconds();
4484         }
4485
4486         last_single_step = game_single_step;
4487
4488         if ((gameseq_get_state() == GS_STATE_GAME_PLAY) && Use_mouse_to_fly){
4489                 Keep_mouse_centered = 1;  // force mouse to center of our window (so we don't hit movement limits)
4490         }
4491         game_frame();
4492
4493         Keep_mouse_centered = 0;
4494         monitor_update();                       // Update monitor variables
4495 }
4496
4497 void multi_maybe_do_frame()
4498 {
4499         if ( (Game_mode & GM_MULTIPLAYER) && (Game_mode & GM_IN_MISSION) && !Multi_pause_status){
4500                 game_do_frame(); 
4501         }
4502 }
4503
4504 int Joymouse_button_status = 0;
4505
4506 // Flush all input devices
4507 void game_flush()
4508 {
4509         key_flush();
4510         mouse_flush();
4511         joy_flush();
4512         snazzy_flush();
4513
4514         Joymouse_button_status = 0;
4515
4516         //mprintf(("Game flush!\n" ));
4517 }
4518
4519 // function for multiplayer only which calls game_do_state_common() when running the
4520 // debug console
4521 void game_do_dc_networking()
4522 {
4523         Assert( Game_mode & GM_MULTIPLAYER );
4524
4525         game_do_state_common( gameseq_get_state() );
4526 }
4527
4528 // Call this whenever in a loop, or when you need to check for a keystroke.
4529 int game_check_key()
4530 {
4531         int k;
4532
4533         k = game_poll();
4534
4535         // convert keypad enter to normal enter
4536         if ((k & KEY_MASK) == KEY_PADENTER)
4537                 k = (k & ~KEY_MASK) | KEY_ENTER;
4538
4539         return k;
4540 }
4541
4542 #ifdef FS2_DEMO
4543
4544 #define DEMO_TRAILER_TIMEOUT_MS         45000                   // 45 seconds of no input, play trailer
4545 static int Demo_show_trailer_timestamp = 0;
4546
4547 void demo_reset_trailer_timer()
4548 {
4549         Demo_show_trailer_timestamp = timer_get_milliseconds();
4550 }
4551
4552 void demo_maybe_show_trailer(int k)
4553 {
4554         /*
4555         // if key pressed, reset demo trailer timer
4556         if ( k > 0 ) {
4557                 demo_reset_trailer_timer();
4558                 return;
4559         }
4560
4561         // if mouse moved, reset demo trailer timer
4562         int dx = 0, dy = 0;
4563
4564         mouse_get_delta(&dx, &dy);
4565         if ( (dx > 0) || (dy > 0) ) {
4566                 demo_reset_trailer_timer();
4567                 return;
4568         }
4569
4570         // if joystick has moved, reset demo trailer timer
4571         dx = 0;
4572         dy = 0;
4573         joy_get_delta(&dx, &dy);
4574         if ( (dx > 0) || (dy > 0) ) {
4575                 demo_reset_trailer_timer();
4576                 return;
4577         }
4578
4579         // NOTE: reseting the trailer timer on mouse/joystick presses is handled in
4580         //       the low-level code.  Ugly, I know... but was the simplest and most
4581         //       robust solution.
4582                 
4583         // if 30 seconds since last demo trailer time reset, launch movie
4584         if ( os_foreground() ) {
4585                 int now = timer_get_milliseconds();
4586                 if ( (now - Demo_show_trailer_timestamp) > DEMO_TRAILER_TIMEOUT_MS ) {
4587 //              if ( (now - Demo_show_trailer_timestamp) > 10000 ) {
4588                         // play movie here
4589                         movie_play( NOX("fstrailer2.mve") );
4590                         demo_reset_trailer_timer();
4591                 }
4592         }
4593         */
4594 }
4595
4596 #endif
4597
4598 // same as game_check_key(), except this is used while actually in the game.  Since there
4599 // generally are differences between game control keys and general UI keys, makes sense to
4600 // have seperate functions for each case.  If you are not checking a game control while in a
4601 // mission, you should probably be using game_check_key() instead.
4602 int game_poll()
4603 {
4604         int k, state;
4605
4606         if (!os_foreground()) {         
4607                 game_stop_time();
4608                 os_sleep(100);
4609                 game_start_time();
4610
4611                 // If we're in a single player game, pause it.
4612                 if (!(Game_mode & GM_MULTIPLAYER)){
4613                         if ( (gameseq_get_state() == GS_STATE_GAME_PLAY) && (!popup_active()) && (!popupdead_is_active()) )     {
4614                                 game_process_pause_key();
4615                         }
4616                 }
4617         }
4618
4619    k = key_inkey();
4620
4621 #ifdef FS2_DEMO
4622         demo_maybe_show_trailer(k);
4623 #endif
4624
4625         // Move the mouse cursor with the joystick.
4626         if (os_foreground() && (!Mouse_hidden) && (Use_joy_mouse) )     {
4627                 // Move the mouse cursor with the joystick
4628                 int mx, my, dx, dy;
4629                 int jx, jy, jz, jr;
4630
4631                 joy_get_pos( &jx, &jy, &jz, &jr );
4632
4633                 dx = fl2i(f2fl(jx)*flFrametime*500.0f);
4634                 dy = fl2i(f2fl(jy)*flFrametime*500.0f);
4635
4636                 if ( dx || dy ) {
4637                         mouse_get_real_pos( &mx, &my );
4638                         mouse_set_pos( mx+dx, my+dy );
4639                 }
4640
4641                 int j, m;
4642                 j = joy_down(0);
4643                 m = mouse_down(MOUSE_LEFT_BUTTON);
4644
4645                 if ( j != Joymouse_button_status )      {
4646                         //mprintf(( "Joy went from %d to %d, mouse is %d\n", Joymouse_button_status, j, m ));
4647                         Joymouse_button_status = j;
4648                         if ( j && (!m) )        {
4649                                 mouse_mark_button( MOUSE_LEFT_BUTTON, 1 );
4650                         } else if ( (!j) && (m) )       {
4651                                 mouse_mark_button( MOUSE_LEFT_BUTTON, 0 );
4652                         }
4653                 }
4654         }
4655
4656         // if we should be ignoring keys because of some multiplayer situations
4657         if((Game_mode & GM_MULTIPLAYER) && multi_ignore_controls(k)){
4658                 return 0;
4659         }
4660
4661         // If a popup is running, don't process all the Fn keys
4662         if( popup_active() ) {
4663                 return k;
4664         }
4665
4666         state = gameseq_get_state();
4667
4668 //      if ( k ) nprintf(( "General", "Key = %x\n", k ));
4669
4670         switch (k) {
4671                 case KEY_DEBUGGED + KEY_BACKSP:
4672                         Int3();
4673                         break;
4674
4675                 case KEY_F1:
4676                         launch_context_help();
4677                         k = 0;
4678                         break;
4679
4680                 case KEY_F2:
4681 //                      if (state != GS_STATE_INITIAL_PLAYER_SELECT) {
4682
4683                         // don't allow f2 while warping out in multiplayer      
4684                         if((Game_mode & GM_MULTIPLAYER) && (Net_player != NULL) && (Net_player->flags & NETINFO_FLAG_WARPING_OUT)){
4685                                 break;
4686                         }
4687
4688                         switch (state) {
4689                                 case GS_STATE_INITIAL_PLAYER_SELECT:
4690                                 case GS_STATE_OPTIONS_MENU:
4691                                 case GS_STATE_HUD_CONFIG:
4692                                 case GS_STATE_CONTROL_CONFIG:
4693                                 case GS_STATE_DEATH_DIED:
4694                                 case GS_STATE_DEATH_BLEW_UP:            
4695                                 case GS_STATE_VIEW_MEDALS:
4696                                         break;
4697
4698                                 default:
4699                                         gameseq_post_event(GS_EVENT_OPTIONS_MENU);
4700                                         k = 0;
4701                                         break;
4702                         }
4703
4704                         break;
4705
4706                         // hotkey selection screen -- only valid from briefing and beyond.
4707                 case KEY_F3:    
4708                         #ifndef FS2_DEMO
4709                                 if ( (state == GS_STATE_TEAM_SELECT) || (state == GS_STATE_BRIEFING) || (state == GS_STATE_SHIP_SELECT) || (state == GS_STATE_WEAPON_SELECT) || (state == GS_STATE_GAME_PLAY) || (state == GS_STATE_GAME_PAUSED) ) {
4710                                         gameseq_post_event( GS_EVENT_HOTKEY_SCREEN );
4711                                         k = 0;
4712                                 }
4713                         #endif
4714                         break;
4715
4716                 case KEY_DEBUGGED + KEY_F3:
4717                         gameseq_post_event( GS_EVENT_TOGGLE_FULLSCREEN );
4718                         break;
4719
4720                 case KEY_DEBUGGED + KEY_F4:
4721                         gameseq_post_event( GS_EVENT_TOGGLE_GLIDE );
4722                         break;
4723                 
4724                 case KEY_F4:
4725                         if(Game_mode & GM_MULTIPLAYER){
4726                                 if((state == GS_STATE_GAME_PLAY) || (state == GS_STATE_MULTI_PAUSED)){
4727                                         gameseq_post_event( GS_EVENT_MISSION_LOG_SCROLLBACK );
4728                                         k = 0;
4729                                 } 
4730                         } else {
4731                                 if ((state == GS_STATE_GAME_PLAY) || (state == GS_STATE_DEATH_DIED) || (state == GS_STATE_DEATH_BLEW_UP) || (state == GS_STATE_GAME_PAUSED) ) {
4732                                         gameseq_post_event( GS_EVENT_MISSION_LOG_SCROLLBACK );
4733                                         k = 0;
4734                                 }
4735                         }
4736                         break;
4737
4738                 case KEY_ESC | KEY_SHIFTED:
4739                         // make sure to quit properly out of multiplayer
4740                         if(Game_mode & GM_MULTIPLAYER){
4741                                 multi_quit_game(PROMPT_NONE);
4742                         }
4743
4744                         gameseq_post_event( GS_EVENT_QUIT_GAME );
4745                         k = 0;
4746
4747                         break;
4748
4749                 case KEY_DEBUGGED + KEY_P:                      
4750                         break;                  
4751
4752                 case KEY_PRINT_SCRN: 
4753                         {
4754                                 static int counter = 0;
4755                                 char tmp_name[127];
4756
4757                                 game_stop_time();
4758
4759                                 sprintf( tmp_name, NOX("screen%02d"), counter );
4760                                 counter++;
4761                                 mprintf(( "Dumping screen to '%s'\n", tmp_name ));
4762                                 gr_print_screen(tmp_name);
4763
4764                                 game_start_time();
4765                         }
4766
4767                         k = 0;
4768                         break;
4769
4770                 case KEY_SHIFTED | KEY_ENTER: {
4771
4772 #if !defined(NDEBUG)
4773
4774                         if ( Game_mode & GM_NORMAL ){
4775                                 game_stop_time();
4776                         }
4777
4778                         // if we're in multiplayer mode, do some special networking
4779                         if(Game_mode & GM_MULTIPLAYER){
4780                                 debug_console(game_do_dc_networking);
4781                         } else {                                
4782                                 debug_console();
4783                         }
4784
4785                         game_flush();
4786
4787                         if ( Game_mode & GM_NORMAL )
4788                                 game_start_time();
4789
4790 #endif
4791
4792                         break;
4793                 }
4794         }
4795
4796         return k;
4797 }
4798
4799 void os_close()
4800 {
4801         gameseq_post_event(GS_EVENT_QUIT_GAME);
4802 }
4803
4804 void apply_physics( float damping, float desired_vel, float initial_vel, float t, float * new_vel, float * delta_pos );
4805
4806
4807 void camera_set_position( vector *pos )
4808 {
4809         Camera_pos = *pos;
4810 }
4811
4812 void camera_set_orient( matrix *orient )
4813 {
4814         Camera_orient = *orient;
4815 }
4816
4817 void camera_set_velocity( vector *vel, int instantaneous )
4818 {
4819         Camera_desired_velocity.x = 0.0f;
4820         Camera_desired_velocity.y = 0.0f;
4821         Camera_desired_velocity.z = 0.0f;
4822
4823         vm_vec_scale_add2( &Camera_desired_velocity, &Camera_orient.rvec, vel->x );
4824         vm_vec_scale_add2( &Camera_desired_velocity, &Camera_orient.uvec, vel->y );
4825         vm_vec_scale_add2( &Camera_desired_velocity, &Camera_orient.fvec, vel->z );
4826
4827         if ( instantaneous )    {
4828                 Camera_velocity = Camera_desired_velocity;
4829         }
4830
4831 }
4832
4833 //
4834 void camera_move()
4835 {
4836         vector new_vel, delta_pos;
4837
4838         apply_physics( Camera_damping, Camera_desired_velocity.x, Camera_velocity.x, flFrametime, &new_vel.x, &delta_pos.x );
4839         apply_physics( Camera_damping, Camera_desired_velocity.y, Camera_velocity.y, flFrametime, &new_vel.y, &delta_pos.y );
4840         apply_physics( Camera_damping, Camera_desired_velocity.z, Camera_velocity.z, flFrametime, &new_vel.z, &delta_pos.z );
4841
4842         Camera_velocity = new_vel;
4843
4844 //      mprintf(( "Camera velocity = %.1f,%.1f, %.1f\n", Camera_velocity.x, Camera_velocity.y, Camera_velocity.z ));
4845
4846         vm_vec_add2( &Camera_pos, &delta_pos );
4847
4848         float ot = Camera_time+0.0f;
4849
4850         Camera_time += flFrametime;
4851
4852         if ( (ot < 0.667f) && ( Camera_time >= 0.667f ) )       {
4853                 vector tmp;
4854                 
4855                 tmp.z = 4.739f;         // always go this fast forward.
4856
4857                 // pick x and y velocities so they are always on a 
4858                 // circle with a 25 m radius.
4859
4860                 float tmp_angle = frand()*PI2;
4861         
4862                 tmp.x = 22.0f * (float)sin(tmp_angle);
4863                 tmp.y = -22.0f * (float)cos(tmp_angle);
4864
4865                 //mprintf(( "Angle = %.1f, vx=%.1f, vy=%.1f\n", tmp_angle, tmp.x, tmp.y ));
4866
4867                 //mprintf(( "Changing velocity!\n" ));
4868                 camera_set_velocity( &tmp, 0 );
4869         }
4870
4871         if ( (ot < 3.0f ) && ( Camera_time >= 3.0f ) )  {
4872                 vector tmp = { 0.0f, 0.0f, 0.0f };
4873                 camera_set_velocity( &tmp, 0 );
4874         }
4875         
4876 }
4877
4878 void end_demo_campaign_do()
4879 {
4880 #if defined(FS2_DEMO)
4881         // show upsell screens
4882         demo_upsell_show_screens();
4883 #elif defined(OEM_BUILD)
4884         // show oem upsell screens
4885         oem_upsell_show_screens();
4886 #endif
4887
4888         // drop into main hall
4889         gameseq_post_event( GS_EVENT_MAIN_MENU );
4890 }
4891
4892 // All code to process events.   This is the only place
4893 // that you should change the state of the game.
4894 void game_process_event( int current_state, int event )
4895 {
4896         mprintf(("Got event %s in state %s\n", GS_event_text[event], GS_state_text[current_state]));
4897
4898         switch (event) {
4899                 case GS_EVENT_SIMULATOR_ROOM:
4900                         gameseq_set_state(GS_STATE_SIMULATOR_ROOM);
4901                         break;
4902
4903                 case GS_EVENT_MAIN_MENU:
4904                         gameseq_set_state(GS_STATE_MAIN_MENU);          
4905                         break;
4906
4907                 case GS_EVENT_OPTIONS_MENU:
4908                         gameseq_push_state( GS_STATE_OPTIONS_MENU );
4909                         break;
4910
4911                 case GS_EVENT_BARRACKS_MENU:
4912                         gameseq_set_state(GS_STATE_BARRACKS_MENU);              
4913                         break;
4914
4915                 case GS_EVENT_TECH_MENU:
4916                         gameseq_set_state(GS_STATE_TECH_MENU);          
4917                         break;
4918
4919                 case GS_EVENT_TRAINING_MENU:
4920                         gameseq_set_state(GS_STATE_TRAINING_MENU);              
4921                         break;
4922
4923                 case GS_EVENT_START_GAME:
4924                         Select_default_ship = 0;                        
4925                         Player_multi_died_check = -1;
4926                         gameseq_set_state(GS_STATE_CMD_BRIEF);
4927                         break;
4928
4929                 case GS_EVENT_START_BRIEFING:
4930                         gameseq_set_state(GS_STATE_BRIEFING);           
4931                         break;
4932
4933                 case GS_EVENT_DEBRIEF:
4934                         // did we end the campaign in the main freespace 2 single player campaign?
4935                         if(Campaign_ended_in_mission && (Game_mode & GM_CAMPAIGN_MODE) && !stricmp(Campaign.filename, "freespace2")) {
4936                                 gameseq_post_event(GS_EVENT_END_CAMPAIGN);
4937                         } else {
4938                                 gameseq_set_state(GS_STATE_DEBRIEF);            
4939                         }
4940
4941                         Player_multi_died_check = -1;
4942                         break;
4943
4944                 case GS_EVENT_SHIP_SELECTION:
4945                         gameseq_set_state( GS_STATE_SHIP_SELECT );
4946                         break;
4947
4948                 case GS_EVENT_WEAPON_SELECTION:
4949                         gameseq_set_state( GS_STATE_WEAPON_SELECT );
4950                         break;
4951
4952                 case GS_EVENT_ENTER_GAME:               
4953 #ifdef DEMO_SYSTEM
4954                         // maybe start recording a demo
4955                         if(Demo_make){
4956                                 demo_start_record("test.fsd");
4957                         }
4958 #endif
4959
4960                         if (Game_mode & GM_MULTIPLAYER) {
4961                                 // if we're respawning, make sure we change the view mode so that the hud shows up
4962                                 if (current_state == GS_STATE_DEATH_BLEW_UP) {
4963                                         Viewer_mode = 0;
4964                                 }
4965
4966                                 gameseq_set_state(GS_STATE_GAME_PLAY);
4967                         } else {
4968                                 gameseq_set_state(GS_STATE_GAME_PLAY, 1);
4969                         }
4970
4971                         Player_multi_died_check = -1;
4972
4973                         // clear multiplayer button info                        
4974                         extern button_info Multi_ship_status_bi;
4975                         memset(&Multi_ship_status_bi, 0, sizeof(button_info));
4976
4977                         Start_time = f2fl(timer_get_approx_seconds());
4978                         //Framecount = 0;
4979                         mprintf(("Entering game at time = %7.3f\n", Start_time));
4980                         break;
4981
4982
4983                 case GS_EVENT_START_GAME_QUICK:
4984                         Select_default_ship = 1;
4985                         gameseq_post_event(GS_EVENT_ENTER_GAME);
4986                         break;
4987
4988
4989                 case GS_EVENT_END_GAME:
4990                         if ( (current_state == GS_STATE_GAME_PLAY) || (current_state == GS_STATE_DEATH_DIED) ||
4991                                 (current_state == GS_STATE_DEATH_BLEW_UP) ||    (current_state == GS_STATE_DEBRIEF) || (current_state == GS_STATE_MULTI_DOGFIGHT_DEBRIEF)) {
4992                                         gameseq_set_state(GS_STATE_MAIN_MENU);
4993
4994                         } else
4995                                 Int3();
4996
4997                         Player_multi_died_check = -1;
4998                         break;
4999
5000                 case GS_EVENT_QUIT_GAME:
5001                         main_hall_stop_music();
5002                         main_hall_stop_ambient();
5003                         gameseq_set_state(GS_STATE_QUIT_GAME);
5004
5005                         Player_multi_died_check = -1;
5006                         break;
5007
5008                 case GS_EVENT_GAMEPLAY_HELP:
5009                         gameseq_push_state( GS_STATE_GAMEPLAY_HELP );
5010                         break;
5011
5012                 case GS_EVENT_PAUSE_GAME:
5013                         gameseq_push_state(GS_STATE_GAME_PAUSED);
5014                         break;
5015
5016                 case GS_EVENT_DEBUG_PAUSE_GAME:
5017                         gameseq_push_state(GS_STATE_DEBUG_PAUSED);
5018                         break;
5019
5020                 case GS_EVENT_TRAINING_PAUSE:
5021                         gameseq_push_state(GS_STATE_TRAINING_PAUSED);
5022                         break;
5023
5024                 case GS_EVENT_PREVIOUS_STATE:
5025                         gameseq_pop_state();
5026                         break;
5027
5028                 case GS_EVENT_TOGGLE_FULLSCREEN:
5029                         #ifndef HARDWARE_ONLY
5030                                 #ifndef NDEBUG
5031                                 if ( gr_screen.mode == GR_SOFTWARE )    {
5032                                         gr_init( GR_640, GR_DIRECTDRAW );
5033                                 } else if ( gr_screen.mode == GR_DIRECTDRAW )   {
5034                                         gr_init( GR_640, GR_SOFTWARE );
5035                                 }
5036                                 #endif
5037                         #endif
5038                         break;
5039
5040                 case GS_EVENT_TOGGLE_GLIDE:
5041                         #ifndef NDEBUG
5042                         if ( gr_screen.mode != GR_GLIDE )       {
5043                                 gr_init( GR_640, GR_GLIDE );
5044                         } else {
5045                                 gr_init( GR_640, GR_SOFTWARE );
5046                         }
5047                         #endif
5048                         break;                                          
5049  
5050                 case GS_EVENT_LOAD_MISSION_MENU:
5051                         gameseq_set_state(GS_STATE_LOAD_MISSION_MENU);
5052                         break;
5053
5054                 case GS_EVENT_MISSION_LOG_SCROLLBACK:
5055                         gameseq_push_state( GS_STATE_MISSION_LOG_SCROLLBACK );
5056                         break;
5057
5058                 case GS_EVENT_HUD_CONFIG:
5059                         gameseq_push_state( GS_STATE_HUD_CONFIG );
5060                         break;
5061
5062                 case GS_EVENT_CONTROL_CONFIG:
5063                         gameseq_push_state( GS_STATE_CONTROL_CONFIG );
5064                         break;  
5065
5066                 case GS_EVENT_DEATH_DIED:
5067                         gameseq_set_state( GS_STATE_DEATH_DIED );
5068                         break;
5069
5070                 case GS_EVENT_DEATH_BLEW_UP:
5071                         if (  current_state == GS_STATE_DEATH_DIED )    {
5072                                 gameseq_set_state( GS_STATE_DEATH_BLEW_UP );
5073                                 event_music_player_death();
5074
5075                                 // multiplayer clients set their extra check here
5076                                 if(Game_mode & GM_MULTIPLAYER){
5077                                         // set the multi died absolute last chance check                                        
5078                                         Player_multi_died_check = time(NULL);
5079                                 }                                       
5080                         } else {
5081                                 mprintf(( "Ignoring GS_EVENT_DEATH_BLEW_UP because we're in state %d\n", current_state ));
5082                         }
5083                         break;
5084
5085                 case GS_EVENT_NEW_CAMPAIGN:
5086                         if (!mission_load_up_campaign()){
5087                                 readyroom_continue_campaign();
5088                         }
5089
5090                         Player_multi_died_check = -1;
5091                         break;
5092
5093                 case GS_EVENT_CAMPAIGN_CHEAT:
5094                         if (!mission_load_up_campaign()){
5095                                 /*
5096                                 // bash campaign value
5097                                 extern char Main_hall_campaign_cheat[512];
5098                                 int idx;
5099                                 
5100                                 // look for the mission
5101                                 for(idx=0; idx<Campaign.num_missions; idx++){
5102                                         if(!stricmp(Campaign.missions[idx].name, Main_hall_campaign_cheat)){
5103                                                 Campaign.next_mission = idx;
5104                                                 Campaign.prev_mission = idx - 1;
5105                                                 break;
5106                                         }
5107                                 }
5108                                 */
5109
5110                                 // continue
5111                                 readyroom_continue_campaign();
5112                         }
5113
5114                         Player_multi_died_check = -1;
5115                         break;
5116
5117                 case GS_EVENT_CAMPAIGN_ROOM:
5118                         gameseq_set_state(GS_STATE_CAMPAIGN_ROOM);
5119                         break;
5120
5121                 case GS_EVENT_CMD_BRIEF:
5122                         gameseq_set_state(GS_STATE_CMD_BRIEF);
5123                         break;
5124
5125                 case GS_EVENT_RED_ALERT:
5126                         gameseq_set_state(GS_STATE_RED_ALERT);
5127                         break;
5128
5129                 case GS_EVENT_CREDITS:
5130                         gameseq_set_state( GS_STATE_CREDITS );
5131                         break;
5132
5133                 case GS_EVENT_VIEW_MEDALS:
5134                         gameseq_push_state( GS_STATE_VIEW_MEDALS );
5135                         break;
5136
5137                 case GS_EVENT_SHOW_GOALS:
5138                         gameseq_push_state( GS_STATE_SHOW_GOALS );      // use push_state() since we might get to this screen through a variety of states
5139                         break;
5140
5141                 case GS_EVENT_HOTKEY_SCREEN:
5142                         gameseq_push_state( GS_STATE_HOTKEY_SCREEN );   // use push_state() since we might get to this screen through a variety of states
5143                         break;
5144                 
5145         // multiplayer stuff follow these comments
5146
5147                 case GS_EVENT_MULTI_JOIN_GAME:
5148                         gameseq_set_state( GS_STATE_MULTI_JOIN_GAME );
5149                         break;
5150
5151                 case GS_EVENT_MULTI_HOST_SETUP:
5152                         gameseq_set_state( GS_STATE_MULTI_HOST_SETUP );
5153                         break;
5154
5155                 case GS_EVENT_MULTI_CLIENT_SETUP:
5156                         gameseq_set_state( GS_STATE_MULTI_CLIENT_SETUP );
5157                         break;
5158
5159                 case GS_EVENT_GOTO_VIEW_CUTSCENES_SCREEN:
5160                         gameseq_set_state(GS_STATE_VIEW_CUTSCENES);
5161                         break;
5162
5163                 case GS_EVENT_MULTI_STD_WAIT:
5164                         gameseq_set_state( GS_STATE_MULTI_STD_WAIT );
5165                         break;
5166
5167                 case GS_EVENT_STANDALONE_MAIN:
5168                         gameseq_set_state( GS_STATE_STANDALONE_MAIN );
5169                         break;   
5170
5171                 case GS_EVENT_MULTI_PAUSE:
5172                         gameseq_push_state( GS_STATE_MULTI_PAUSED );
5173                         break;                  
5174
5175                 case GS_EVENT_INGAME_PRE_JOIN:
5176                         gameseq_set_state( GS_STATE_INGAME_PRE_JOIN );
5177                         break;
5178                 
5179                 case GS_EVENT_EVENT_DEBUG:
5180                         gameseq_push_state(GS_STATE_EVENT_DEBUG);
5181                         break;
5182
5183                 // Start a warpout where player automatically goes 70 no matter what
5184                 // and can't cancel out of it.
5185                 case GS_EVENT_PLAYER_WARPOUT_START_FORCED:
5186                         Warpout_forced = 1;                                                     // If non-zero, bash the player to speed and go through effect
5187
5188                         // Same code as in GS_EVENT_PLAYER_WARPOUT_START only ignores current mode
5189                         Player->saved_viewer_mode = Viewer_mode;
5190                         Player->control_mode = PCM_WARPOUT_STAGE1;
5191                         Warpout_sound = snd_play(&Snds[SND_PLAYER_WARP_OUT]);
5192                         Warpout_time = 0.0f;                    // Start timer!
5193                         break;
5194
5195                 case GS_EVENT_PLAYER_WARPOUT_START:
5196                         if ( Player->control_mode != PCM_NORMAL )       {
5197                                 mprintf(( "Player isn't in normal mode; cannot warp out.\n" ));
5198                         } else {
5199                                 Player->saved_viewer_mode = Viewer_mode;
5200                                 Player->control_mode = PCM_WARPOUT_STAGE1;
5201                                 Warpout_sound = snd_play(&Snds[SND_PLAYER_WARP_OUT]);
5202                                 Warpout_time = 0.0f;                    // Start timer!
5203                                 Warpout_forced = 0;                             // If non-zero, bash the player to speed and go through effect
5204                         }
5205                         break;
5206
5207                 case GS_EVENT_PLAYER_WARPOUT_STOP:
5208                         if ( Player->control_mode != PCM_NORMAL )       {
5209                                 if ( !Warpout_forced )  {               // cannot cancel forced warpout
5210                                         Player->control_mode = PCM_NORMAL;
5211                                         Viewer_mode = Player->saved_viewer_mode;
5212                                         hud_subspace_notify_abort();
5213                                         mprintf(( "Player put back to normal mode.\n" ));
5214                                         if ( Warpout_sound > -1 )       {
5215                                                 snd_stop( Warpout_sound );
5216                                                 Warpout_sound = -1;
5217                                         }
5218                                 }
5219                         }
5220                         break;
5221
5222                 case GS_EVENT_PLAYER_WARPOUT_DONE_STAGE1:               // player ship got up to speed
5223                         if ( Player->control_mode != PCM_WARPOUT_STAGE1 )       {
5224                                 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_STOP );
5225                                 mprintf(( "Player put back to normal mode, because of invalid sequence in stage1.\n" ));
5226                         } else {
5227                                 mprintf(( "Hit target speed.  Starting warp effect and moving to stage 2!\n" ));
5228                                 shipfx_warpout_start( Player_obj );
5229                                 Player->control_mode = PCM_WARPOUT_STAGE2;
5230                                 Player->saved_viewer_mode = Viewer_mode;
5231                                 Viewer_mode |= VM_WARP_CHASE;
5232                                 
5233                                 vector tmp = Player_obj->pos;
5234                                 matrix tmp_m;
5235                                 ship_get_eye( &tmp, &tmp_m, Player_obj );
5236                                 vm_vec_scale_add2( &tmp, &Player_obj->orient.rvec, 0.0f );
5237                                 vm_vec_scale_add2( &tmp, &Player_obj->orient.uvec, 0.952f );
5238                                 vm_vec_scale_add2( &tmp, &Player_obj->orient.fvec, -1.782f );
5239                                 Camera_time = 0.0f;
5240                                 camera_set_position( &tmp );
5241                                 camera_set_orient( &Player_obj->orient );
5242                                 vector tmp_vel = { 0.0f, 5.1919f, 14.7f };
5243
5244                                 //mprintf(( "Rad = %.1f\n", Player_obj->radius ));
5245                                 camera_set_velocity( &tmp_vel, 1);
5246                         }
5247                         break;
5248
5249                 case GS_EVENT_PLAYER_WARPOUT_DONE_STAGE2:               // player ship got into the warp effect
5250                         if ( Player->control_mode != PCM_WARPOUT_STAGE2 )       {
5251                                 gameseq_post_event( GS_EVENT_PLAYER_WARPOUT_STOP );
5252                                 mprintf(( "Player put back to normal mode, because of invalid sequence in stage2.\n" ));
5253                         } else {
5254                                 mprintf(( "Hit warp effect.  Moving to stage 3!\n" ));
5255                                 Player->control_mode = PCM_WARPOUT_STAGE3;
5256                         }
5257                         break;
5258
5259                 case GS_EVENT_PLAYER_WARPOUT_DONE:      // player ship got through the warp effect
5260                         mprintf(( "Player warped out.  Going to debriefing!\n" ));
5261                         Player->control_mode = PCM_NORMAL;
5262                         Viewer_mode = Player->saved_viewer_mode;
5263                         Warpout_sound = -1;
5264
5265                         // we have a special debriefing screen for multiplayer furballs
5266                         if((Game_mode & GM_MULTIPLAYER) && (The_mission.game_type & MISSION_TYPE_MULTI_DOGFIGHT)){
5267                                 gameseq_post_event(GS_EVENT_MULTI_DOGFIGHT_DEBRIEF);
5268                         }
5269                         // do the normal debriefing for all other situations
5270                         else {
5271                                 gameseq_post_event(GS_EVENT_DEBRIEF);
5272                         }
5273                         break;
5274
5275                 case GS_EVENT_STANDALONE_POSTGAME:
5276                         gameseq_set_state(GS_STATE_STANDALONE_POSTGAME);
5277                         break;
5278
5279                 case GS_EVENT_INITIAL_PLAYER_SELECT:
5280                         gameseq_set_state(GS_STATE_INITIAL_PLAYER_SELECT);
5281                         break;
5282
5283                 case GS_EVENT_GAME_INIT:
5284         #if defined(FS2_DEMO) || defined(OEM_BUILD)
5285                         gameseq_set_state(GS_STATE_INITIAL_PLAYER_SELECT);
5286         #else                   
5287                         // see if the command line option has been set to use the last pilot, and act acoordingly
5288                         if( player_select_get_last_pilot() ) {                                                          
5289                                 // always enter the main menu -- do the automatic network startup stuff elsewhere
5290                                 // so that we still have valid checks for networking modes, etc.
5291                                 gameseq_set_state(GS_STATE_MAIN_MENU);
5292                         } else {
5293                                 gameseq_set_state(GS_STATE_INITIAL_PLAYER_SELECT);
5294                         }
5295         #endif
5296                         break;
5297
5298                 case GS_EVENT_MULTI_MISSION_SYNC:
5299                         gameseq_set_state(GS_STATE_MULTI_MISSION_SYNC);
5300                         break;          
5301
5302                 case GS_EVENT_MULTI_START_GAME:
5303                         gameseq_set_state(GS_STATE_MULTI_START_GAME);
5304                         break;
5305
5306                 case GS_EVENT_MULTI_HOST_OPTIONS:
5307                         gameseq_set_state(GS_STATE_MULTI_HOST_OPTIONS);
5308                         break;
5309
5310                 case GS_EVENT_MULTI_DOGFIGHT_DEBRIEF:
5311                         gameseq_set_state(GS_STATE_MULTI_DOGFIGHT_DEBRIEF);
5312                         break;
5313
5314                 case GS_EVENT_TEAM_SELECT:
5315                         gameseq_set_state(GS_STATE_TEAM_SELECT);
5316                         break;
5317
5318                 case GS_EVENT_END_CAMPAIGN:                     
5319                         gameseq_set_state(GS_STATE_END_OF_CAMPAIGN);
5320                         break;          
5321
5322                 case GS_EVENT_END_DEMO:
5323                         gameseq_set_state(GS_STATE_END_DEMO);
5324                         break;
5325
5326                 case GS_EVENT_LOOP_BRIEF:
5327                         gameseq_set_state(GS_STATE_LOOP_BRIEF);
5328                         break;
5329
5330                 default:
5331                         Int3();
5332                         break;
5333         }
5334 }
5335
5336 // Called when a state is being left.
5337 // The current state is still at old_state, but as soon as
5338 // this function leaves, then the current state will become
5339 // new state.     You should never try to change the state
5340 // in here... if you think you need to, you probably really
5341 // need to post an event, not change the state.
5342 void game_leave_state( int old_state, int new_state )
5343 {
5344         int end_mission = 1;
5345
5346         switch (new_state) {
5347                 case GS_STATE_GAME_PAUSED:
5348                 case GS_STATE_DEBUG_PAUSED:
5349                 case GS_STATE_OPTIONS_MENU:
5350                 case GS_STATE_CONTROL_CONFIG:           
5351                 case GS_STATE_MISSION_LOG_SCROLLBACK:
5352                 case GS_STATE_DEATH_DIED:
5353                 case GS_STATE_SHOW_GOALS:
5354                 case GS_STATE_HOTKEY_SCREEN:            
5355                 case GS_STATE_MULTI_PAUSED:
5356                 case GS_STATE_TRAINING_PAUSED:
5357                 case GS_STATE_EVENT_DEBUG:                              
5358                 case GS_STATE_GAMEPLAY_HELP:
5359                         end_mission = 0;  // these events shouldn't end a mission
5360                         break;
5361         }
5362
5363         switch (old_state) {
5364                 case GS_STATE_BRIEFING:
5365                         brief_stop_voices();
5366                         if ( (new_state != GS_STATE_OPTIONS_MENU) && (new_state != GS_STATE_WEAPON_SELECT)
5367                                   && (new_state != GS_STATE_SHIP_SELECT) && (new_state != GS_STATE_HOTKEY_SCREEN)
5368                                   && (new_state != GS_STATE_TEAM_SELECT) ){
5369                                 common_select_close();
5370                                 if ( new_state == GS_STATE_MAIN_MENU ) {
5371                                         freespace_stop_mission();       
5372                                 }
5373                         }
5374                         
5375                         // COMMAND LINE OPTION
5376                         if (Cmdline_multi_stream_chat_to_file){
5377                                 cfwrite_string(NOX("-------------------------------------------\n"),Multi_chat_stream);
5378                                 cfclose(Multi_chat_stream);
5379                         }
5380                         break;
5381
5382                 case GS_STATE_DEBRIEF:
5383                         if ( (new_state != GS_STATE_VIEW_MEDALS) && (new_state != GS_STATE_OPTIONS_MENU) ) {
5384                                 debrief_close();                                
5385                         }
5386                         break;
5387
5388                 case GS_STATE_MULTI_DOGFIGHT_DEBRIEF:
5389                         multi_df_debrief_close();
5390                         break;
5391
5392                 case GS_STATE_LOAD_MISSION_MENU:
5393                         mission_load_menu_close();
5394                         break;
5395
5396                 case GS_STATE_SIMULATOR_ROOM:
5397                         sim_room_close();
5398                         break;
5399
5400                 case GS_STATE_CAMPAIGN_ROOM:
5401                         campaign_room_close();
5402                         break;
5403
5404                 case GS_STATE_CMD_BRIEF:
5405                         if (new_state == GS_STATE_OPTIONS_MENU) {
5406                                 cmd_brief_hold();
5407
5408                         } else {
5409                                 cmd_brief_close();
5410                                 if (new_state == GS_STATE_MAIN_MENU)
5411                                         freespace_stop_mission();       
5412                         }
5413
5414                         break;
5415
5416                 case GS_STATE_RED_ALERT:
5417                         red_alert_close();
5418                         break;
5419
5420                 case GS_STATE_SHIP_SELECT:
5421                         if ( new_state != GS_STATE_OPTIONS_MENU && new_state != GS_STATE_WEAPON_SELECT &&
5422                                   new_state != GS_STATE_HOTKEY_SCREEN &&
5423                                   new_state != GS_STATE_BRIEFING && new_state != GS_STATE_TEAM_SELECT) {
5424                                 common_select_close();
5425                                 if ( new_state == GS_STATE_MAIN_MENU ) {
5426                                         freespace_stop_mission();       
5427                                 }
5428                         }
5429                         break;
5430
5431                 case GS_STATE_WEAPON_SELECT:
5432                         if ( new_state != GS_STATE_OPTIONS_MENU && new_state != GS_STATE_SHIP_SELECT &&
5433                                   new_state != GS_STATE_HOTKEY_SCREEN &&
5434                                   new_state != GS_STATE_BRIEFING && new_state != GS_STATE_TEAM_SELECT) {
5435                                 common_select_close();
5436                                 if ( new_state == GS_STATE_MAIN_MENU ) {
5437                                         freespace_stop_mission();       
5438                                 }
5439                         }
5440                         break;
5441
5442                 case GS_STATE_TEAM_SELECT:
5443                         if ( new_state != GS_STATE_OPTIONS_MENU && new_state != GS_STATE_SHIP_SELECT &&
5444                                   new_state != GS_STATE_HOTKEY_SCREEN &&
5445                                   new_state != GS_STATE_BRIEFING && new_state != GS_STATE_WEAPON_SELECT) {
5446                                 common_select_close();
5447                                 if ( new_state == GS_STATE_MAIN_MENU ) {
5448                                         freespace_stop_mission();       
5449                                 }
5450                         }                                       
5451                         break;
5452
5453                 case GS_STATE_MAIN_MENU:
5454 #if defined(PRESS_TOUR_BUILD) || defined(PD_BUILD)
5455                         mht_close();
5456 #else
5457                         main_hall_close();
5458 #endif
5459                         break;
5460
5461                 case GS_STATE_OPTIONS_MENU:
5462                         //game_start_time();
5463                         if(new_state == GS_STATE_MULTI_JOIN_GAME){
5464                                 multi_join_clear_game_list();
5465                         }
5466                         options_menu_close();
5467                         break;
5468
5469                 case GS_STATE_BARRACKS_MENU:
5470                         if(new_state != GS_STATE_VIEW_MEDALS){
5471                                 barracks_close();
5472                         }
5473                         break;
5474
5475                 case GS_STATE_MISSION_LOG_SCROLLBACK:
5476                         hud_scrollback_close();
5477                         break;
5478
5479                 case GS_STATE_TRAINING_MENU:
5480                         training_menu_close();
5481                         break;
5482
5483                 case GS_STATE_GAME_PLAY:
5484                         if ( !(Game_mode & GM_STANDALONE_SERVER) ) {
5485                                 player_save_target_and_weapon_link_prefs();
5486                                 game_stop_looped_sounds();
5487                         }
5488
5489                         sound_env_disable();
5490                         joy_ff_stop_effects();
5491
5492                         // stop game time under certain conditions
5493                         if ( end_mission || (Game_mode & GM_NORMAL) || ((Game_mode & GM_MULTIPLAYER) && (new_state == GS_STATE_MULTI_PAUSED)) ){
5494                                 game_stop_time();
5495                         }
5496
5497                         if (end_mission) {
5498                         // shut down any recording or playing demos
5499 #ifdef DEMO_SYSTEM
5500                                 demo_close();
5501 #endif
5502
5503                                 // when in multiplayer and going back to the main menu, send a leave game packet
5504                                 // right away (before calling stop mission).  stop_mission was taking to long to
5505                                 // close mission down and I want people to get notified ASAP.
5506                                 if ( (Game_mode & GM_MULTIPLAYER) && (new_state == GS_STATE_MAIN_MENU) ){
5507                                         multi_quit_game(PROMPT_NONE);
5508                                 }
5509
5510                                 freespace_stop_mission();                       
5511                                 Game_time_compression = F1_0;
5512                         }
5513                         break;
5514
5515                 case GS_STATE_TECH_MENU:
5516                         techroom_close();
5517                         break;
5518
5519                 case GS_STATE_TRAINING_PAUSED:
5520                         Training_num_lines = 0;
5521                         // fall through to GS_STATE_GAME_PAUSED
5522
5523                 case GS_STATE_GAME_PAUSED:
5524                         game_start_time();
5525                         if ( end_mission ) {
5526                                 pause_close(0);
5527                         }
5528                         break;
5529
5530                 case GS_STATE_DEBUG_PAUSED:
5531                         #ifndef NDEBUG
5532                                 game_start_time();
5533                                 pause_debug_close();
5534                         #endif
5535                         break;
5536
5537                 case GS_STATE_HUD_CONFIG:
5538                         hud_config_close();
5539                         break;
5540
5541                 // join/start a game
5542                 case GS_STATE_MULTI_JOIN_GAME:
5543                         if(new_state != GS_STATE_OPTIONS_MENU){
5544                                 multi_join_game_close();
5545                         }
5546                         break;
5547
5548                 case GS_STATE_MULTI_HOST_SETUP:
5549                 case GS_STATE_MULTI_CLIENT_SETUP:
5550                         // if this is just the host going into the options screen, don't do anything
5551                         if((new_state == GS_STATE_MULTI_HOST_OPTIONS) || (new_state == GS_STATE_OPTIONS_MENU)){
5552                                 break;
5553                         }
5554
5555                         // close down the proper state
5556                         if(old_state == GS_STATE_MULTI_HOST_SETUP){
5557                                 multi_create_game_close();
5558                         } else {
5559                                 multi_game_client_setup_close();
5560                         }
5561
5562                         // COMMAND LINE OPTION
5563                         if (Cmdline_multi_stream_chat_to_file){
5564                                 if( (new_state != GS_STATE_TEAM_SELECT) && (Multi_chat_stream!=NULL) ) {
5565                                         cfwrite_string(NOX("-------------------------------------------\n"),Multi_chat_stream);
5566                                         cfclose(Multi_chat_stream);
5567                                 }
5568                         }                       
5569                         break;
5570
5571                 case GS_STATE_CONTROL_CONFIG:
5572                         control_config_close();
5573                         break;
5574
5575                 case GS_STATE_DEATH_DIED:
5576                         Game_mode &= ~GM_DEAD_DIED;
5577                         
5578                         // early end while respawning or blowing up in a multiplayer game
5579                         if((Game_mode & GM_MULTIPLAYER) && ((new_state == GS_STATE_DEBRIEF) || (new_state == GS_STATE_MULTI_DOGFIGHT_DEBRIEF)) ){
5580                                 game_stop_time();
5581                                 freespace_stop_mission();
5582                         }
5583                         break;
5584
5585                 case GS_STATE_DEATH_BLEW_UP:
5586                         Game_mode &= ~GM_DEAD_BLEW_UP;
5587
5588                         // for single player, we might reload mission, etc.  For multiplayer, look at my new state
5589                         // to determine if I should do anything.
5590                         if ( !(Game_mode & GM_MULTIPLAYER) ) {
5591                                 if ( end_mission ){
5592                                         freespace_stop_mission();
5593                                 }
5594                         } else {
5595                                 // if we are not respawing as an observer or as a player, our new state will not
5596                                 // be gameplay state.
5597                                 if ( (new_state != GS_STATE_GAME_PLAY) && (new_state != GS_STATE_MULTI_PAUSED) ) {
5598                                         game_stop_time();                                                                       // hasn't been called yet!!
5599                                         freespace_stop_mission();
5600                                 }
5601                         }
5602                         break;
5603
5604
5605                 case GS_STATE_CREDITS:
5606                         credits_close();
5607                         break;
5608
5609                 case GS_STATE_VIEW_MEDALS:
5610                         medal_main_close();
5611                         break;
5612
5613                 case GS_STATE_SHOW_GOALS:
5614                         mission_show_goals_close();
5615                         break;
5616
5617                 case GS_STATE_HOTKEY_SCREEN:
5618                         if ( new_state != GS_STATE_OPTIONS_MENU ) {
5619                                 mission_hotkey_close();
5620                         }
5621                         break;
5622
5623                 case GS_STATE_MULTI_MISSION_SYNC:
5624                         // if we're moving into the options menu, don't do anything
5625                         if(new_state == GS_STATE_OPTIONS_MENU){
5626                                 break;
5627                         }
5628
5629                         Assert( Game_mode & GM_MULTIPLAYER );
5630                         multi_sync_close();
5631                         if ( new_state == GS_STATE_GAME_PLAY ){
5632                                 // palette_restore_palette();
5633
5634                                 // change a couple of flags to indicate our state!!!
5635                                 Net_player->state = NETPLAYER_STATE_IN_MISSION;
5636                                 send_netplayer_update_packet();
5637
5638                                 // set the game mode
5639                                 Game_mode |= GM_IN_MISSION;
5640                         }                       
5641                         break;          
5642    
5643                 case GS_STATE_VIEW_CUTSCENES:
5644                         cutscenes_screen_close();
5645                         break;
5646
5647                 case GS_STATE_MULTI_STD_WAIT:
5648                         multi_standalone_wait_close();
5649                         break;
5650
5651                 case GS_STATE_STANDALONE_MAIN:                  
5652                         standalone_main_close();
5653                         if(new_state == GS_STATE_MULTI_STD_WAIT){               
5654                                 init_multiplayer_stats();                                                                               
5655                         }                       
5656                         break;
5657
5658                 case GS_STATE_MULTI_PAUSED:
5659                         // if ( end_mission ){
5660                                 pause_close(1);
5661                         // }
5662                         break;                  
5663
5664                 case GS_STATE_INGAME_PRE_JOIN:
5665                         multi_ingame_select_close();
5666                         break;
5667
5668                 case GS_STATE_STANDALONE_POSTGAME:
5669                         multi_standalone_postgame_close();
5670                         break;
5671
5672                 case GS_STATE_INITIAL_PLAYER_SELECT:                    
5673                         player_select_close();                  
5674                         break;          
5675
5676                 case GS_STATE_MULTI_START_GAME:
5677                         multi_start_game_close();
5678                         break;
5679
5680                 case GS_STATE_MULTI_HOST_OPTIONS:
5681                         multi_host_options_close();
5682                         break;                          
5683
5684                 case GS_STATE_END_OF_CAMPAIGN:
5685                         mission_campaign_end_close();
5686                         break;
5687
5688                 case GS_STATE_LOOP_BRIEF:
5689                         loop_brief_close();
5690                         break;
5691         }
5692 }
5693
5694 // Called when a state is being entered.
5695 // The current state is set to the state we're entering at
5696 // this point, and old_state is set to the state we're coming
5697 // from.    You should never try to change the state
5698 // in here... if you think you need to, you probably really
5699 // need to post an event, not change the state.
5700
5701 void game_enter_state( int old_state, int new_state )
5702 {
5703         switch (new_state) {
5704                 case GS_STATE_MAIN_MENU:                                
5705                         // in multiplayer mode, be sure that we are not doing networking anymore.
5706                         if ( Game_mode & GM_MULTIPLAYER ) {
5707                                 Assert( Net_player != NULL );
5708                                 Net_player->flags &= ~NETINFO_FLAG_DO_NETWORKING;
5709                         }
5710
5711                         Game_time_compression = F1_0;
5712         
5713                         // determine which ship this guy is currently based on
5714 #if defined(PRESS_TOUR_BUILD) || defined(PD_BUILD)
5715                         mht_init();
5716 #else
5717                         if (Player->on_bastion) {
5718                                 main_hall_init(1);
5719                         } else {
5720                                 main_hall_init(0);
5721                         }
5722 #endif
5723                         break;
5724
5725                 case GS_STATE_BRIEFING:
5726                         main_hall_stop_music();
5727                         main_hall_stop_ambient();
5728                         
5729                         if (Game_mode & GM_NORMAL) {
5730                                 // AL: Don't call freespace_start_mission() if re-entering from ship or weapon select
5731                                 // MWA: or from options or hotkey screens
5732                                 // JH: or if the command brief state already did this
5733                                 if ( (old_state != GS_STATE_OPTIONS_MENU) && (old_state != GS_STATE_HOTKEY_SCREEN)
5734                                         && (old_state != GS_STATE_SHIP_SELECT) && (old_state != GS_STATE_WEAPON_SELECT)
5735                                         && (old_state != GS_STATE_CMD_BRIEF) ) {
5736                                         if ( !game_start_mission() )                    // this should put us into a new state on failure!
5737                                                 break;
5738                                 }
5739                         }
5740                         // maybe play a movie before the briefing.  don't play if entering briefing screen from ship or weapon select.
5741                         if ( (old_state == GS_STATE_DEBRIEF) || (old_state == GS_STATE_SIMULATOR_ROOM) || (old_state == GS_STATE_MAIN_MENU))
5742                                 mission_campaign_maybe_play_movie(CAMPAIGN_MOVIE_PRE_MISSION);
5743
5744                         Game_time_compression = F1_0;
5745
5746                         if ( red_alert_mission() ) {
5747                                 gameseq_post_event(GS_EVENT_RED_ALERT);
5748                         } else {
5749                                 brief_init();
5750                         }
5751
5752                         break;
5753
5754                 case GS_STATE_DEBRIEF:
5755                         game_stop_looped_sounds();
5756                         mission_goal_fail_incomplete();                         // fail all incomplete goals before entering debriefing
5757                         if ( (old_state != GS_STATE_VIEW_MEDALS) && (old_state != GS_STATE_OPTIONS_MENU) ){
5758                                 debrief_init();
5759                         }
5760                         break;
5761
5762                 case GS_STATE_MULTI_DOGFIGHT_DEBRIEF:
5763                         multi_df_debrief_init();
5764                         break;
5765
5766                 case GS_STATE_LOAD_MISSION_MENU:
5767                         mission_load_menu_init();
5768                         break;
5769
5770                 case GS_STATE_SIMULATOR_ROOM:
5771                         sim_room_init();
5772                         break;
5773
5774                 case GS_STATE_CAMPAIGN_ROOM:
5775                         campaign_room_init();
5776                         break;
5777
5778                 case GS_STATE_RED_ALERT:
5779                         mission_campaign_maybe_play_movie(CAMPAIGN_MOVIE_PRE_MISSION);
5780                         red_alert_init();
5781                         break;
5782
5783                 case GS_STATE_CMD_BRIEF: {
5784                         int team_num = 0;  // team number used as index for which cmd brief to use.
5785
5786                         if (old_state == GS_STATE_OPTIONS_MENU) {
5787                                 cmd_brief_unhold();
5788
5789                         } else {
5790                                 main_hall_stop_music();
5791                                 main_hall_stop_ambient();
5792
5793                                 if (Game_mode & GM_NORMAL) {
5794                                         // AL: Don't call freespace_start_mission() if re-entering from ship or weapon select
5795                                         // MWA: or from options or hotkey screens
5796                                         // JH: or if the command brief state already did this
5797                                         if ( (old_state != GS_STATE_OPTIONS_MENU) && (old_state != GS_STATE_HOTKEY_SCREEN)
5798                                                 && (old_state != GS_STATE_SHIP_SELECT) && (old_state != GS_STATE_WEAPON_SELECT) ) {
5799                                                 if ( !game_start_mission() )                    // this should put us into a new state on failure!
5800                                                         break;
5801                                         }
5802                                 }
5803
5804                                 // maybe play a movie before the briefing.  don't play if entering briefing screen from ship or weapon select.
5805                                 if ( (old_state == GS_STATE_DEBRIEF) || (old_state == GS_STATE_SIMULATOR_ROOM) || (old_state == GS_STATE_MAIN_MENU))
5806                                         mission_campaign_maybe_play_movie(CAMPAIGN_MOVIE_PRE_MISSION);
5807
5808                                 cmd_brief_init(team_num);
5809                         }
5810
5811                         break;
5812                 }
5813
5814                 case GS_STATE_SHIP_SELECT:
5815                         ship_select_init();
5816                         break;
5817
5818                 case GS_STATE_WEAPON_SELECT:
5819                         weapon_select_init();
5820                         break;
5821
5822                 case GS_STATE_TEAM_SELECT:              
5823                         multi_ts_init();
5824                         break;
5825
5826                 case GS_STATE_GAME_PAUSED:
5827                         game_stop_time();
5828                         pause_init(0);
5829                         break;
5830
5831                 case GS_STATE_DEBUG_PAUSED:
5832         //              game_stop_time();
5833         //              os_set_title("FreeSpace - PAUSED");
5834         //              break;
5835         //
5836                 case GS_STATE_TRAINING_PAUSED:
5837                         #ifndef NDEBUG
5838                                 game_stop_time();
5839                                 pause_debug_init();
5840                         #endif
5841                         break;
5842
5843                 case GS_STATE_OPTIONS_MENU:
5844                         //game_stop_time();
5845                         options_menu_init();
5846                         break;
5847  
5848                 case GS_STATE_GAME_PLAY:
5849                         // coming from the gameplay state or the main menu, we might need to load the mission
5850                         if ( (Game_mode & GM_NORMAL) && ((old_state == GS_STATE_MAIN_MENU) || (old_state == GS_STATE_GAME_PLAY) || (old_state == GS_STATE_DEATH_BLEW_UP)) ) {
5851                                 if ( !game_start_mission() )            // this should put us into a new state.
5852                                         // Failed!!!
5853                                         break;
5854                         }
5855
5856                         // if we are coming from the briefing, ship select, weapons loadout, or main menu (in the
5857                         // case of quick start), then do bitmap loads, etc  Don't do any of the loading stuff
5858                         // if we are in multiplayer -- this stuff is all handled in the multi-wait section
5859                         if ( !(Game_mode & GM_MULTIPLAYER) && (old_state == GS_STATE_BRIEFING) || (old_state == GS_STATE_SHIP_SELECT) ||
5860                                 (old_state == GS_STATE_WEAPON_SELECT) || (old_state == GS_STATE_MAIN_MENU) || (old_state == GS_STATE_MULTI_STD_WAIT)    || (old_state == GS_STATE_SIMULATOR_ROOM) ) {
5861                                         // JAS: Used to do all paging here.
5862
5863                                         #ifndef NDEBUG
5864                                         //XSTR:OFF
5865                                                 HUD_printf("Skill level is set to ** %s **", Skill_level_names(Game_skill_level));
5866                                         //XSTR:ON
5867                                         #endif
5868
5869                                         main_hall_stop_music();
5870                                         main_hall_stop_ambient();
5871                                         event_music_first_pattern();    // start the first pattern
5872                         }
5873
5874                         // special code that restores player ship selection and weapons loadout when doing a quick start
5875                         if ( !(Game_mode & GM_MULTIPLAYER) && (old_state == GS_STATE_MAIN_MENU) || (old_state == GS_STATE_DEATH_BLEW_UP)  || (old_state == GS_STATE_GAME_PLAY) ) {
5876                                 if ( !stricmp(Player_loadout.filename, Game_current_mission_filename) ) {
5877                                         wss_direct_restore_loadout();
5878                                 }
5879                         }
5880
5881                         // single-player, quick-start after just died... we need to set weapon linking and kick off the event music
5882                         if (!(Game_mode & GM_MULTIPLAYER) && (old_state == GS_STATE_DEATH_BLEW_UP) ) {
5883                                 event_music_first_pattern();    // start the first pattern
5884                         }
5885
5886                         if ( !(Game_mode & GM_STANDALONE_SERVER) && (old_state != GS_STATE_GAME_PAUSED) && (old_state != GS_STATE_MULTI_PAUSED) ) {
5887                                 event_music_first_pattern();    // start the first pattern
5888                         }                       
5889                         player_restore_target_and_weapon_link_prefs();
5890
5891                         Game_mode |= GM_IN_MISSION;
5892
5893 #ifndef NDEBUG
5894                         // required to truely make mouse deltas zeroed in debug mouse code
5895 void mouse_force_pos(int x, int y);
5896                         mouse_force_pos(gr_screen.max_w / 2, gr_screen.max_h / 2);
5897 #endif
5898
5899                         game_flush();
5900
5901                         // only start time if in single player, or coming from multi wait state
5902                         if (
5903                                         (
5904                                                 (Game_mode & GM_NORMAL) && 
5905                                                 (old_state != GS_STATE_VIEW_CUTSCENES)
5906                                         ) || (
5907                                                 (Game_mode & GM_MULTIPLAYER) && (
5908                                                         (old_state == GS_STATE_MULTI_PAUSED) ||
5909                                                         (old_state == GS_STATE_MULTI_MISSION_SYNC)
5910                                                 )
5911                                         )
5912                                 )
5913                                         game_start_time();
5914
5915                         // when coming from the multi paused state, reset the timestamps
5916                         if ( (Game_mode & GM_MULTIPLAYER) && (old_state == GS_STATE_MULTI_PAUSED) ){
5917                                 multi_reset_timestamps();
5918                         }
5919
5920                         if ((Game_mode & GM_MULTIPLAYER) && (old_state != GS_STATE_DEATH_BLEW_UP) ) {
5921                                 // initialize all object update details
5922                                 multi_oo_gameplay_init();
5923                         }
5924         
5925                         // under certain circumstances, the server should reset the object update rate limiting stuff
5926                         if( ((Game_mode & GM_MULTIPLAYER) && (Net_player->flags & NETINFO_FLAG_AM_MASTER)) &&
5927                                  (old_state == GS_STATE_MULTI_PAUSED) || (old_state == GS_STATE_MULTI_MISSION_SYNC) ){
5928                                 
5929                                 // reinitialize the rate limiting system for all clients
5930                                 multi_oo_rate_init_all();
5931                         }
5932
5933                         // multiplayer clients should always re-initialize their control info rate limiting system                      
5934                         if((Game_mode & GM_MULTIPLAYER) && !(Net_player->flags & NETINFO_FLAG_AM_MASTER)){
5935                                 multi_oo_rate_init_all();
5936                         }
5937                         
5938                         // reset ping times
5939                         if(Game_mode & GM_MULTIPLAYER){
5940                                 multi_ping_reset_players();
5941                         }
5942
5943                         Game_subspace_effect = 0;
5944                         if (The_mission.flags & MISSION_FLAG_SUBSPACE) {
5945                                 Game_subspace_effect = 1;
5946                                 if( !(Game_mode & GM_STANDALONE_SERVER) ){      
5947                                         game_start_subspace_ambient_sound();
5948                                 }
5949                         }
5950
5951                         sound_env_set(&Game_sound_env);
5952                         joy_ff_mission_init(Ship_info[Player_ship->ship_info_index].rotation_time);
5953
5954                         // clear multiplayer button info                        i
5955                         extern button_info Multi_ship_status_bi;
5956                         memset(&Multi_ship_status_bi, 0, sizeof(button_info));
5957                         break;
5958
5959                 case GS_STATE_HUD_CONFIG:
5960                         hud_config_init();
5961                         break;
5962
5963                 case GS_STATE_MULTI_JOIN_GAME:
5964                         multi_join_clear_game_list();
5965
5966                         if (old_state != GS_STATE_OPTIONS_MENU) {
5967                                 multi_join_game_init();
5968                         }
5969
5970                         break;
5971
5972                 case GS_STATE_MULTI_HOST_SETUP:         
5973                         // don't reinitialize if we're coming back from the host options screen
5974                         if ((old_state != GS_STATE_MULTI_HOST_OPTIONS) && (old_state != GS_STATE_OPTIONS_MENU)) {
5975                                 multi_create_game_init();
5976                         }
5977
5978                         break;
5979
5980                 case GS_STATE_MULTI_CLIENT_SETUP:               
5981                         if (old_state != GS_STATE_OPTIONS_MENU) {
5982                                 multi_game_client_setup_init();
5983                         }
5984
5985                         break;
5986
5987                 case GS_STATE_CONTROL_CONFIG:
5988                         control_config_init();
5989                         break;
5990
5991                 case GS_STATE_TECH_MENU:
5992                         techroom_init();
5993                         break;
5994
5995                 case GS_STATE_BARRACKS_MENU:
5996                         if(old_state != GS_STATE_VIEW_MEDALS){
5997                                 barracks_init();
5998                         }
5999                         break;
6000
6001                 case GS_STATE_MISSION_LOG_SCROLLBACK:
6002                         hud_scrollback_init();
6003                         break;
6004
6005                 case GS_STATE_DEATH_DIED:
6006                         Player_died_time = timestamp(10);
6007
6008                         if(!(Game_mode & GM_MULTIPLAYER)){
6009                                 player_show_death_message();
6010                         }
6011                         Game_mode |= GM_DEAD_DIED;
6012                         break;
6013
6014                 case GS_STATE_DEATH_BLEW_UP:
6015                         if ( !popupdead_is_active() ) {
6016                                 Player_ai->target_objnum = -1;
6017                         }
6018
6019                         // stop any local EMP effect
6020                         emp_stop_local();
6021
6022                         Players[Player_num].flags &= ~PLAYER_FLAGS_AUTO_TARGETING;      //      Prevent immediate switch to a hostile ship.
6023                         Game_mode |= GM_DEAD_BLEW_UP;           
6024                         Show_viewing_from_self = 0;
6025
6026                         // timestamp how long we should wait before displaying the died popup
6027                         if ( !popupdead_is_active() ) {
6028                                 Player_died_popup_wait = timestamp(PLAYER_DIED_POPUP_WAIT);
6029                         }
6030                         break;
6031
6032                 case GS_STATE_GAMEPLAY_HELP:
6033                         gameplay_help_init();
6034                         break;
6035
6036                 case GS_STATE_CREDITS:
6037                         main_hall_stop_music();
6038                         main_hall_stop_ambient();
6039                         credits_init();
6040                         break;
6041
6042                 case GS_STATE_VIEW_MEDALS:
6043                         medal_main_init(Player);
6044                         break;
6045
6046                 case GS_STATE_SHOW_GOALS:
6047                         mission_show_goals_init();
6048                         break;
6049
6050                 case GS_STATE_HOTKEY_SCREEN:
6051                         mission_hotkey_init();
6052                         break;
6053
6054                 case GS_STATE_MULTI_MISSION_SYNC:
6055                         // if we're coming from the options screen, don't do any
6056                         if(old_state == GS_STATE_OPTIONS_MENU){
6057                                 break;
6058                         }
6059
6060                         switch(Multi_sync_mode){
6061                         case MULTI_SYNC_PRE_BRIEFING:
6062                                 // if moving from game forming to the team select state                                         
6063                                 multi_sync_init();                      
6064                                 break;
6065                         case MULTI_SYNC_POST_BRIEFING:
6066                                 // if moving from briefing into the mission itself                      
6067                                 multi_sync_init();
6068                         
6069                                 // tell everyone that we're now loading data
6070                                 Net_player->state = NETPLAYER_STATE_DATA_LOAD;
6071                                 send_netplayer_update_packet();
6072
6073                                 // JAS: Used to do all paging here!!!!
6074                                                                 
6075                                 Net_player->state = NETPLAYER_STATE_WAITING;                    
6076                                 send_netplayer_update_packet();                         
6077                                 Missiontime = 0;
6078                                 Game_time_compression = F1_0;
6079                                 break;
6080                         case MULTI_SYNC_INGAME:
6081                                 multi_sync_init();
6082                                 break;
6083                         }
6084                         break;          
6085    
6086                 case GS_STATE_VIEW_CUTSCENES:
6087                         cutscenes_screen_init();
6088                         break;
6089
6090                 case GS_STATE_MULTI_STD_WAIT:
6091                         multi_standalone_wait_init();
6092                         break;
6093
6094                 case GS_STATE_STANDALONE_MAIN:
6095                         // don't initialize if we're coming from one of these 2 states unless there are no 
6096                         // players left (reset situation)
6097                         if((old_state != GS_STATE_STANDALONE_POSTGAME) || multi_endgame_ending()){
6098                                 standalone_main_init();
6099                         }
6100                         break;  
6101
6102                 case GS_STATE_MULTI_PAUSED:
6103                         pause_init(1);
6104                         break;
6105                 
6106                 case GS_STATE_INGAME_PRE_JOIN:
6107                         multi_ingame_select_init();
6108                         break;
6109
6110                 case GS_STATE_STANDALONE_POSTGAME:
6111                         multi_standalone_postgame_init();
6112                         break;
6113
6114                 case GS_STATE_INITIAL_PLAYER_SELECT:
6115                         player_select_init();
6116                         break;          
6117
6118                 case GS_STATE_MULTI_START_GAME:
6119                         multi_start_game_init();
6120                         break;
6121
6122                 case GS_STATE_MULTI_HOST_OPTIONS:
6123                         multi_host_options_init();
6124                         break;          
6125
6126                 case GS_STATE_END_OF_CAMPAIGN:
6127                         mission_campaign_end_init();
6128                         break;          
6129
6130                 case GS_STATE_LOOP_BRIEF:
6131                         loop_brief_init();
6132                         break;
6133
6134         } // end switch
6135 }
6136
6137 // do stuff that may need to be done regardless of state
6138 void game_do_state_common(int state,int no_networking)
6139 {
6140         game_maybe_draw_mouse(flFrametime);             // determine if to draw the mouse this frame
6141         snd_do_frame();                                                         // update sound system
6142         event_music_do_frame();                                         // music needs to play across many states
6143
6144         multi_log_process();    
6145
6146         if (no_networking) {
6147                 return;
6148         }
6149
6150         // maybe do a multiplayer frame based on game mode and state type       
6151         if (Game_mode & GM_MULTIPLAYER) {
6152                 switch (state) {
6153                         case GS_STATE_OPTIONS_MENU:
6154                         case GS_STATE_GAMEPLAY_HELP:
6155                         case GS_STATE_HOTKEY_SCREEN:
6156                         case GS_STATE_HUD_CONFIG:
6157                         case GS_STATE_CONTROL_CONFIG:
6158                         case GS_STATE_MISSION_LOG_SCROLLBACK:
6159                         case GS_STATE_SHOW_GOALS:
6160                         case GS_STATE_VIEW_CUTSCENES:
6161                         case GS_STATE_EVENT_DEBUG:
6162                                 multi_maybe_do_frame();
6163                                 break;
6164                 }
6165                 
6166                 game_do_networking();
6167         }
6168 }
6169
6170 // Called once a frame.
6171 // You should never try to change the state
6172 // in here... if you think you need to, you probably really
6173 // need to post an event, not change the state.
6174 int Game_do_state_should_skip = 0;
6175 void game_do_state(int state)
6176 {
6177         // always lets the do_state_common() function determine if the state should be skipped
6178         Game_do_state_should_skip = 0;
6179         
6180         // legal to set the should skip state anywhere in this function
6181         game_do_state_common(state);    // do stuff that may need to be done regardless of state
6182
6183         if(Game_do_state_should_skip){
6184                 return;
6185         }
6186         
6187         switch (state) {
6188                 case GS_STATE_MAIN_MENU:
6189                         game_set_frametime(GS_STATE_MAIN_MENU);
6190 #if defined(PRESS_TOUR_BUILD) || defined(PD_BUILD)
6191                         mht_do();
6192 #else
6193                         main_hall_do(flFrametime);
6194 #endif
6195                         break;
6196
6197                 case GS_STATE_OPTIONS_MENU:
6198                         game_set_frametime(GS_STATE_OPTIONS_MENU);
6199                         options_menu_do_frame(flFrametime);
6200                         break;
6201
6202                 case GS_STATE_BARRACKS_MENU:
6203                         game_set_frametime(GS_STATE_BARRACKS_MENU);
6204                         barracks_do_frame(flFrametime);
6205                         break;
6206
6207                 case GS_STATE_TRAINING_MENU:
6208                         game_set_frametime(GS_STATE_TRAINING_MENU);
6209                         training_menu_do_frame(flFrametime);
6210                         break;
6211
6212                 case GS_STATE_TECH_MENU:
6213                         game_set_frametime(GS_STATE_TECH_MENU);
6214                         techroom_do_frame(flFrametime);
6215                         break;
6216
6217                 case GS_STATE_GAMEPLAY_HELP:
6218                         game_set_frametime(GS_STATE_GAMEPLAY_HELP);
6219                         gameplay_help_do_frame(flFrametime);
6220                         break;
6221
6222                 case GS_STATE_GAME_PLAY:        // do stuff that should be done during gameplay
6223                         game_do_frame();
6224                         break;
6225
6226                 case GS_STATE_GAME_PAUSED:
6227                         pause_do(0);
6228                         break;
6229
6230                 case GS_STATE_DEBUG_PAUSED:
6231                         #ifndef NDEBUG
6232                                 game_set_frametime(GS_STATE_DEBUG_PAUSED);
6233                                 pause_debug_do();
6234                         #endif
6235                         break;
6236
6237                 case GS_STATE_TRAINING_PAUSED:
6238                         game_training_pause_do();
6239                         break;
6240
6241                 case GS_STATE_LOAD_MISSION_MENU:
6242                         game_set_frametime(GS_STATE_LOAD_MISSION_MENU);
6243                         mission_load_menu_do();
6244                         break;
6245                 
6246                 case GS_STATE_BRIEFING:
6247                         game_set_frametime(GS_STATE_BRIEFING);
6248                         brief_do_frame(flFrametime);
6249                         break;
6250
6251                 case GS_STATE_DEBRIEF:
6252                         game_set_frametime(GS_STATE_DEBRIEF);
6253                         debrief_do_frame(flFrametime);
6254                         break;
6255
6256                 case GS_STATE_MULTI_DOGFIGHT_DEBRIEF:
6257                         game_set_frametime(GS_STATE_MULTI_DOGFIGHT_DEBRIEF);
6258                         multi_df_debrief_do();
6259                         break;
6260
6261                 case GS_STATE_SHIP_SELECT:
6262                         game_set_frametime(GS_STATE_SHIP_SELECT);
6263                         ship_select_do(flFrametime);
6264                         break;
6265
6266                 case GS_STATE_WEAPON_SELECT:
6267                         game_set_frametime(GS_STATE_WEAPON_SELECT);
6268                         weapon_select_do(flFrametime);
6269                         break;
6270
6271                 case GS_STATE_MISSION_LOG_SCROLLBACK:
6272                         game_set_frametime(GS_STATE_MISSION_LOG_SCROLLBACK);
6273                         hud_scrollback_do_frame(flFrametime);
6274                         break;
6275
6276                 case GS_STATE_HUD_CONFIG:
6277                         game_set_frametime(GS_STATE_HUD_CONFIG);
6278                         hud_config_do_frame(flFrametime);
6279                         break;
6280
6281                 case GS_STATE_MULTI_JOIN_GAME:
6282                         game_set_frametime(GS_STATE_MULTI_JOIN_GAME);
6283                         multi_join_game_do_frame();
6284                         break;
6285
6286                 case GS_STATE_MULTI_HOST_SETUP:
6287                         game_set_frametime(GS_STATE_MULTI_HOST_SETUP);
6288                         multi_create_game_do();
6289                         break;
6290
6291                 case GS_STATE_MULTI_CLIENT_SETUP:
6292                         game_set_frametime(GS_STATE_MULTI_CLIENT_SETUP);
6293                         multi_game_client_setup_do_frame();
6294                         break;
6295
6296                 case GS_STATE_CONTROL_CONFIG:
6297                         game_set_frametime(GS_STATE_CONTROL_CONFIG);
6298                         control_config_do_frame(flFrametime);
6299                         break;  
6300
6301                 case GS_STATE_DEATH_DIED:
6302                         game_do_frame();                        
6303                         break;
6304
6305                 case GS_STATE_DEATH_BLEW_UP:
6306                         game_do_frame();
6307                         break;
6308
6309                 case GS_STATE_SIMULATOR_ROOM:
6310                         game_set_frametime(GS_STATE_SIMULATOR_ROOM);
6311                         sim_room_do_frame(flFrametime);
6312                         break;
6313
6314                 case GS_STATE_CAMPAIGN_ROOM:
6315                         game_set_frametime(GS_STATE_CAMPAIGN_ROOM);
6316                         campaign_room_do_frame(flFrametime);
6317                         break;
6318
6319                 case GS_STATE_RED_ALERT:
6320                         game_set_frametime(GS_STATE_RED_ALERT);
6321                         red_alert_do_frame(flFrametime);
6322                         break;
6323
6324                 case GS_STATE_CMD_BRIEF:
6325                         game_set_frametime(GS_STATE_CMD_BRIEF);
6326                         cmd_brief_do_frame(flFrametime);
6327                         break;
6328
6329                 case GS_STATE_CREDITS:
6330                         game_set_frametime(GS_STATE_CREDITS);
6331                         credits_do_frame(flFrametime);
6332                         break;
6333
6334                 case GS_STATE_VIEW_MEDALS:
6335                         game_set_frametime(GS_STATE_VIEW_MEDALS);
6336                         medal_main_do();
6337                         break;
6338
6339                 case GS_STATE_SHOW_GOALS:
6340                         game_set_frametime(GS_STATE_SHOW_GOALS);
6341                         mission_show_goals_do_frame(flFrametime);
6342                         break;
6343
6344                 case GS_STATE_HOTKEY_SCREEN:
6345                         game_set_frametime(GS_STATE_HOTKEY_SCREEN);
6346                         mission_hotkey_do_frame(flFrametime);
6347                         break;  
6348    
6349                 case GS_STATE_VIEW_CUTSCENES:
6350                         game_set_frametime(GS_STATE_VIEW_CUTSCENES);
6351                         cutscenes_screen_do_frame();
6352                         break;
6353
6354                 case GS_STATE_MULTI_STD_WAIT:
6355                         game_set_frametime(GS_STATE_STANDALONE_MAIN);
6356                         multi_standalone_wait_do();
6357                         break;
6358
6359                 case GS_STATE_STANDALONE_MAIN:
6360                         game_set_frametime(GS_STATE_STANDALONE_MAIN);
6361                         standalone_main_do();
6362                         break;  
6363
6364                 case GS_STATE_MULTI_PAUSED:
6365                         game_set_frametime(GS_STATE_MULTI_PAUSED);
6366                         pause_do(1);
6367                         break;
6368
6369                 case GS_STATE_TEAM_SELECT:
6370                         game_set_frametime(GS_STATE_TEAM_SELECT);
6371                         multi_ts_do();
6372                         break;
6373
6374                 case GS_STATE_INGAME_PRE_JOIN:
6375                         game_set_frametime(GS_STATE_INGAME_PRE_JOIN);
6376                         multi_ingame_select_do();
6377                         break;
6378
6379                 case GS_STATE_EVENT_DEBUG:
6380         #ifndef NDEBUG
6381                         game_set_frametime(GS_STATE_EVENT_DEBUG);
6382                         game_show_event_debug(flFrametime);
6383         #endif
6384                         break;
6385
6386                 case GS_STATE_STANDALONE_POSTGAME:
6387                         game_set_frametime(GS_STATE_STANDALONE_POSTGAME);
6388                         multi_standalone_postgame_do();
6389                         break;
6390
6391                 case GS_STATE_INITIAL_PLAYER_SELECT:
6392                         game_set_frametime(GS_STATE_INITIAL_PLAYER_SELECT);
6393                         player_select_do();
6394                         break;
6395
6396                 case GS_STATE_MULTI_MISSION_SYNC:
6397                         game_set_frametime(GS_STATE_MULTI_MISSION_SYNC);
6398                         multi_sync_do();
6399                         break;          
6400
6401                 case GS_STATE_MULTI_START_GAME:
6402                         game_set_frametime(GS_STATE_MULTI_START_GAME);
6403                         multi_start_game_do();
6404                         break;
6405                 
6406                 case GS_STATE_MULTI_HOST_OPTIONS:
6407                         game_set_frametime(GS_STATE_MULTI_HOST_OPTIONS);
6408                         multi_host_options_do();
6409                         break;          
6410
6411                 case GS_STATE_END_OF_CAMPAIGN:
6412                         mission_campaign_end_do();
6413                         break;          
6414
6415                 case GS_STATE_END_DEMO:
6416                         game_set_frametime(GS_STATE_END_DEMO);
6417                         end_demo_campaign_do();
6418                         break;
6419
6420                 case GS_STATE_LOOP_BRIEF:
6421                         game_set_frametime(GS_STATE_LOOP_BRIEF);
6422                         loop_brief_do();
6423                         break;
6424
6425    } // end switch(gs_current_state)
6426 }
6427
6428
6429 // return 0 if there is enough RAM to run FreeSpace, otherwise return -1
6430 int game_do_ram_check(int ram_in_bytes)
6431 {
6432         if ( ram_in_bytes < 30*1024*1024 )      {
6433                 int allowed_to_run = 1;
6434                 if ( ram_in_bytes < 25*1024*1024 ) {
6435                         allowed_to_run = 0;
6436                 }
6437
6438                 char tmp[1024];
6439                 int Freespace_total_ram_MB;
6440                 Freespace_total_ram_MB = fl2i(ram_in_bytes/(1024*1024));
6441
6442                 if ( allowed_to_run ) {
6443
6444                         sprintf( tmp, XSTR( "FreeSpace has detected that you only have %dMB of free memory.\n\nFreeSpace requires at least 32MB of memory to run.  If you think you have more than %dMB of physical memory, ensure that you aren't running SmartDrive (SMARTDRV.EXE).  Any memory allocated to SmartDrive is not usable by applications\n\nPress 'OK' to continue running with less than the minimum required memory\n", 193), Freespace_total_ram_MB, Freespace_total_ram_MB);
6445
6446                         int msgbox_rval;
6447 #ifndef PLAT_UNIX                       
6448                         msgbox_rval = MessageBox( NULL, tmp, XSTR( "Not Enough RAM", 194), MB_OKCANCEL );
6449                         if ( msgbox_rval == IDCANCEL ) {
6450                                 return -1;
6451                         }
6452 #else
6453                         STUB_FUNCTION;
6454 #endif                  
6455                 } else {
6456                         sprintf( tmp, XSTR( "FreeSpace has detected that you only have %dMB of free memory.\n\nFreeSpace requires at least 32MB of memory to run.  If you think you have more than %dMB of physical memory, ensure that you aren't running SmartDrive (SMARTDRV.EXE).  Any memory allocated to SmartDrive is not usable by applications\n", 195), Freespace_total_ram_MB, Freespace_total_ram_MB);
6457 #ifndef PLAT_UNIX
6458                         MessageBox( NULL, tmp, XSTR( "Not Enough RAM", 194), MB_OK );
6459 #else
6460                         STUB_FUNCTION;
6461 #endif                  
6462                         return -1;
6463                 }
6464         }
6465
6466         return 0;
6467 }
6468
6469 // Check if there is a freespace.exe in the /update directory (relative to where fs.exe is installed).
6470 // If so, copy it over and remove the update directory.
6471 void game_maybe_update_launcher(char *exe_dir)
6472 {
6473 #ifndef PLAT_UNIX
6474         char src_filename[MAX_PATH];
6475         char dest_filename[MAX_PATH];
6476
6477         strcpy(src_filename, exe_dir);
6478         strcat(src_filename, NOX("\\update\\freespace.exe"));
6479
6480         strcpy(dest_filename, exe_dir);
6481         strcat(dest_filename, NOX("\\freespace.exe"));
6482
6483         // see if src_filename exists
6484         FILE *fp;
6485         fp = fopen(src_filename, "rb");
6486         if ( !fp ) {
6487                 return;
6488         }
6489         fclose(fp);
6490
6491         SetFileAttributes(dest_filename, FILE_ATTRIBUTE_NORMAL);
6492
6493         // copy updated freespace.exe to freespace exe dir
6494         if ( CopyFile(src_filename, dest_filename, 0) == 0 ) {
6495                 MessageBox( NULL, XSTR("Unable to copy freespace.exe from update directory to installed directory.  You should copy freespace.exe from the update directory (located in your FreeSpace install directory) to your install directory", 988), NULL, MB_OK|MB_TASKMODAL|MB_SETFOREGROUND );
6496                 return;
6497         }
6498
6499         // delete the file in the update directory
6500         DeleteFile(src_filename);
6501
6502         // safe to assume directory is empty, since freespace.exe should only be the file ever in the update dir
6503         char update_dir[MAX_PATH];
6504         strcpy(update_dir, exe_dir);
6505         strcat(update_dir, NOX("\\update"));
6506         RemoveDirectory(update_dir);
6507 #else
6508         STUB_FUNCTION;
6509 #endif  
6510 }
6511
6512 void game_spew_pof_info_sub(int model_num, polymodel *pm, int sm, CFILE *out, int *out_total, int *out_destroyed_total)
6513 {
6514         int i;
6515         int sub_total = 0;
6516         int sub_total_destroyed = 0;
6517         int total = 0;
6518         char str[255] = "";             
6519         
6520         // get the total for all his children
6521         for (i=pm->submodel[sm].first_child; i>-1; i = pm->submodel[i].next_sibling )   {
6522                 game_spew_pof_info_sub(model_num, pm, i, out, &sub_total, &sub_total_destroyed);
6523         }       
6524
6525         // find the # of faces for this _individual_ object     
6526         total = submodel_get_num_polys(model_num, sm);
6527         if(strstr(pm->submodel[sm].name, "-destroyed")){
6528                 sub_total_destroyed = total;
6529         }
6530         
6531         // write out total
6532         sprintf(str, "Submodel %s total : %d faces\n", pm->submodel[sm].name, total);
6533         cfputs(str, out);               
6534
6535         *out_total += total + sub_total;
6536         *out_destroyed_total += sub_total_destroyed;
6537 }
6538
6539 #define BAIL()                  do { int idx; for(idx=0; idx<num_files; idx++){ if(pof_list[idx] != NULL){free(pof_list[idx]); pof_list[idx] = NULL;}} return;} while(0);
6540 void game_spew_pof_info()
6541 {
6542         char *pof_list[1000];
6543         int num_files;  
6544         CFILE *out;
6545         int idx, model_num, i, j;
6546         polymodel *pm;
6547         int total, root_total, model_total, destroyed_total, counted;
6548         char str[255] = "";
6549
6550         // get file list
6551         num_files = cf_get_file_list(1000, pof_list, CF_TYPE_MODELS, "*.pof");
6552
6553         // spew info on all the pofs
6554         if(!num_files){
6555                 return;
6556         }
6557
6558         // go
6559         out = cfopen("pofspew.txt", "wt", CFILE_NORMAL, CF_TYPE_DATA);
6560         if(out == NULL){
6561                 BAIL();
6562         }       
6563         counted = 0;    
6564         for(idx=0; idx<num_files; idx++, counted++){
6565                 sprintf(str, "%s.pof", pof_list[idx]);
6566                 model_num = model_load(str, 0, NULL);
6567                 if(model_num >= 0){
6568                         pm = model_get(model_num);
6569
6570                         // if we have a real model
6571                         if(pm != NULL){                         
6572                                 cfputs(str, out);
6573                                 cfputs("\n", out);
6574                                 
6575                                 // go through and print all raw submodels
6576                                 cfputs("RAW\n", out);
6577                                 total = 0;
6578                                 model_total = 0;                                
6579                                 for (i=0; i<pm->n_models; i++)  {                                       
6580                                         total = submodel_get_num_polys(model_num, i);                                   
6581                                         
6582                                         model_total += total;
6583                                         sprintf(str, "Submodel %s total : %d faces\n", pm->submodel[i].name, total);
6584                                         cfputs(str, out);
6585                                 }                               
6586                                 sprintf(str, "Model total %d\n", model_total);                          
6587                                 cfputs(str, out);                               
6588
6589                                 // now go through and do it by LOD
6590                                 cfputs("BY LOD\n\n", out);                              
6591                                 for(i=0; i<pm->n_detail_levels; i++){
6592                                         sprintf(str, "LOD %d\n", i);
6593                                         cfputs(str, out);
6594
6595                                         // submodels
6596                                         root_total = submodel_get_num_polys(model_num, pm->detail[i] );
6597                                         total = 0;
6598                                         destroyed_total = 0;
6599                                         for (j=pm->submodel[pm->detail[i]].first_child; j>-1; j = pm->submodel[j].next_sibling )        {
6600                                                 game_spew_pof_info_sub(model_num, pm, j, out, &total, &destroyed_total);
6601                                         }
6602
6603                                         sprintf(str, "Submodel %s total : %d faces\n", pm->submodel[pm->detail[i]].name, root_total);
6604                                         cfputs(str, out);
6605
6606                                         sprintf(str, "TOTAL: %d\n", total + root_total);                                        
6607                                         cfputs(str, out);
6608                                         sprintf(str, "TOTAL not counting destroyed faces %d\n", (total + root_total) - destroyed_total);
6609                                         cfputs(str, out);
6610                                         sprintf(str, "TOTAL destroyed faces %d\n\n", destroyed_total);
6611                                         cfputs(str, out);
6612                                 }                               
6613                                 cfputs("------------------------------------------------------------------------\n\n", out);                            
6614                         }
6615                 }
6616
6617                 if(counted >= MAX_POLYGON_MODELS - 5){
6618                         model_free_all();
6619                         counted = 0;
6620                 }
6621         }
6622
6623         cfclose(out);
6624         model_free_all();
6625         BAIL();
6626 }
6627
6628 DCF(pofspew, "")
6629 {
6630         game_spew_pof_info();
6631 }
6632
6633 int PASCAL WinMainSub(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
6634 {
6635         int state;              
6636
6637 #ifndef PLAT_UNIX
6638         // Don't let more than one instance of Freespace run.
6639         HWND hwnd = FindWindow( NOX( "FreeSpaceClass" ), NULL );
6640         if ( hwnd )     {
6641                 SetForegroundWindow(hwnd);
6642                 return 0;
6643         }
6644 #endif
6645
6646         // Find out how much RAM is on this machine
6647 #ifndef PLAT_UNIX
6648         MEMORYSTATUS ms;
6649         ms.dwLength = sizeof(MEMORYSTATUS);
6650         GlobalMemoryStatus(&ms);
6651         Freespace_total_ram = ms.dwTotalPhys;
6652
6653         if ( game_do_ram_check(Freespace_total_ram) == -1 ) {
6654                 return 0;
6655         }
6656
6657         if ( ms.dwTotalVirtual < 1024 ) {
6658                 MessageBox( NULL, XSTR( "FreeSpace requires virtual memory to run.\r\n", 196), XSTR( "No Virtual Memory", 197), MB_OK );
6659                 return 0;
6660         }
6661
6662         if (!vm_init(24*1024*1024)) {
6663                 MessageBox( NULL, XSTR( "Not enough memory to run Freespace.\r\nTry closing down some other applications.\r\n", 198), XSTR( "Not Enough Memory", 199), MB_OK );
6664                 return 0;
6665         }
6666                 
6667         char *tmp_mem = (char *) malloc(16 * 1024 * 1024);
6668         if (!tmp_mem) {
6669                 MessageBox(NULL, XSTR( "Not enough memory to run Freespace.\r\nTry closing down some other applications.\r\n", 198), XSTR( "Not Enough Memory", 199), MB_OK);
6670                 return 0;
6671         }
6672
6673         free(tmp_mem);
6674         tmp_mem = NULL;
6675 #else
6676         STUB_FUNCTION;
6677 #endif
6678         
6679 /* this code doesn't work, and we will hit an error about being unable to load the direct draw
6680         dll before we get here anyway if it's not installed (unless we load it manually, which doesn't
6681         seem worth bothering with.
6682
6683         LONG lResult;
6684
6685         lResult = RegOpenKeyEx(
6686                 HKEY_LOCAL_MACHINE,                                     // Where it is
6687                 "Software\\Microsoft\\DirectX", // name of key
6688                 NULL,                                                                           // DWORD reserved
6689                 KEY_QUERY_VALUE,                                                // Allows all changes
6690                 &hKey                                                                           // Location to store key
6691         );
6692
6693         if (lResult == ERROR_SUCCESS) {
6694                 char version[32];
6695                 DWORD dwType, dwLen;
6696
6697                 dwLen = 32;
6698                 lResult = RegQueryValueEx(
6699                         hKey,                                                                   // Handle to key
6700                         "Version",                                                      // The values name
6701                         NULL,                                                                   // DWORD reserved
6702                         &dwType,                                                                // What kind it is
6703                         (ubyte *) version,                              // value to set
6704                         &dwLen                                                          // How many bytes to set
6705                 );
6706
6707                 if (lResult == ERROR_SUCCESS) {
6708                         dx_version = atoi(strstr(version, ".") + 1);
6709
6710                 } else {
6711                         int val;
6712                         DWORD dwType, dwLen;
6713
6714                         dwLen = 4;
6715                         lResult = RegQueryValueEx(
6716                                 hKey,                                                                   // Handle to key
6717                                 "InstalledVersion",                             // The values name
6718                                 NULL,                                                                   // DWORD reserved
6719                                 &dwType,                                                                // What kind it is
6720                                 (ubyte *) &val,                                 // value to set
6721                                 &dwLen                                                          // How many bytes to set
6722                         );
6723
6724                         if (lResult == ERROR_SUCCESS) {
6725                                 dx_version = val;
6726                         }
6727                 }
6728
6729                 RegCloseKey(hKey);
6730         }
6731
6732         if (dx_version < 3) {
6733                 MessageBox(NULL, "DirectX 3.0 or higher is required and wasn't detected.  You can get the\n"
6734                         "latest version of DirectX at:\n\n"
6735                         "http://www.microsoft.com/msdownload/directx/dxf/enduser5.0/default.htm", "DirectX required", MB_OK);
6736
6737                 MessageBox(NULL, "DirectX 3.0 or higher is required and wasn't detected.  You can install\n"
6738                         "DirectX 5.2 by pressing the 'Install DirectX' button on the FreeSpace Launcher", "DirectX required", MB_OK);
6739
6740                 return 0;
6741         }
6742 */
6743         //=====================================================
6744         // Make sure we're running in the right directory.
6745 #ifndef PLAT_UNIX
6746         char exe_dir[1024];
6747
6748         if ( GetModuleFileName( hInst, exe_dir, 1023 ) > 0 )    {
6749                 char *p = exe_dir + strlen(exe_dir);
6750
6751                 // chop off the filename
6752                 while( (p>exe_dir) && (*p!='\\') && (*p!='/') && (*p!=':') )    {
6753                         p--;
6754                 }
6755                 *p = 0;
6756
6757                 // Set directory
6758                 if ( strlen(exe_dir) > 0 )      {
6759                         SetCurrentDirectory(exe_dir);
6760                 }
6761
6762                 // check for updated freespace.exe
6763                 game_maybe_update_launcher(exe_dir);
6764         }
6765 #else
6766         STUB_FUNCTION;
6767 #endif
6768         
6769         #ifndef NDEBUG                          
6770         {
6771                 extern void windebug_memwatch_init();
6772                 windebug_memwatch_init();
6773         }
6774         #endif
6775         
6776         parse_cmdline(szCmdLine);       
6777
6778 #ifdef STANDALONE_ONLY_BUILD
6779         Is_standalone = 1;
6780         nprintf(("Network", "Standalone running"));
6781 #else
6782         if (Is_standalone){
6783                 nprintf(("Network", "Standalone running"));
6784         }
6785 #endif
6786
6787         init_cdrom();
6788         game_init();
6789         game_stop_time();
6790
6791         // maybe spew pof stuff
6792         if(Cmdline_spew_pof_info){
6793                 game_spew_pof_info();
6794                 game_shutdown();
6795                 return 1;
6796         }
6797
6798         // non-demo, non-standalone, play the intro movie
6799         if(!Is_standalone){
6800 #ifndef DEMO
6801 #ifdef RELEASE_REAL
6802                 char *plist[5];
6803                 if( (cf_get_file_list(2, plist, CF_TYPE_MULTI_PLAYERS, NOX("*.plr"))    <= 0) && (cf_get_file_list(2, plist, CF_TYPE_SINGLE_PLAYERS, NOX("*.plr"))      <= 0) ){
6804                         // prompt for cd 2
6805 #if defined(OEM_BUILD)
6806                         game_do_cd_check_specific(FS_CDROM_VOLUME_1, 1);
6807 #else
6808                         game_do_cd_check_specific(FS_CDROM_VOLUME_2, 2);
6809 #endif // defined(OEM_BUILD)
6810                 }
6811 #endif
6812         }
6813
6814         if ( !Is_standalone ) {
6815
6816                 // release -- movies always play
6817                 #if defined(NDEBUG)
6818
6819                 // in RELEASE_REAL builds make the user stick in CD2 if there are no pilots on disk so that we guarantee he plays the movie
6820                 // no soup for you!
6821                 // movie_play( NOX("intro.mve"), 0 );
6822
6823                 // debug version, movie will only play with -showmovies
6824                 #elif !defined(NDEBUG)
6825                 
6826                 // no soup for you!
6827                 // movie_play( NOX("intro.mve"), 0);
6828 /*
6829 #ifndef NDEBUG
6830                 if ( Cmdline_show_movies )
6831                         movie_play( NOX("intro.mve"), 0 );
6832 #endif
6833 */
6834                 #endif
6835         }
6836
6837 #endif  
6838
6839         if (Is_standalone){
6840                 gameseq_post_event(GS_EVENT_STANDALONE_MAIN);
6841         } else {
6842                 gameseq_post_event(GS_EVENT_GAME_INIT);         // start the game rolling -- check for default pilot, or go to the pilot select screen
6843         }
6844
6845         while (1) {
6846                 // only important for non THREADED mode
6847                 os_poll();
6848
6849                 state = gameseq_process_events();
6850                 if ( state == GS_STATE_QUIT_GAME ){
6851                         break;
6852                 }
6853         } 
6854
6855 #ifdef FS2_DEMO
6856         if(!Is_standalone){
6857                 demo_upsell_show_screens();
6858         }
6859 #elif defined(OEM_BUILD)
6860         // show upsell screens on exit
6861         oem_upsell_show_screens();
6862 #endif
6863
6864         game_shutdown();
6865         return 1;
6866 }
6867
6868 int PASCAL WinMain(HINSTANCE hInst, HINSTANCE hPrev, LPSTR szCmdLine, int nCmdShow)
6869 {
6870         int result = -1;
6871 #ifndef PLAT_UNIX
6872         __try
6873         {
6874                 result = WinMainSub(hInst, hPrev, szCmdLine, nCmdShow);
6875         }
6876         __except(RecordExceptionInfo(GetExceptionInformation(), "Freespace 2 Main Thread"))
6877         {
6878                 // Do nothing here - RecordExceptionInfo() has already done
6879                 // everything that is needed. Actually this code won't even
6880                 // get called unless you return EXCEPTION_EXECUTE_HANDLER from
6881                 // the __except clause.
6882         }
6883         return result;
6884 #else
6885         STUB_FUNCTION;
6886         
6887         fprintf(stderr, "WinMain: exceptions shall fall through\n");
6888         result = WinMainSub(hInst, hPrev, szCmdLine, nCmdShow);
6889 #endif  
6890 }
6891
6892 // launcher the fslauncher program on exit
6893 void game_launch_launcher_on_exit()
6894 {
6895 #ifndef PLAT_UNIX
6896         STARTUPINFO si;
6897         PROCESS_INFORMATION pi;
6898         char cmd_line[2048];
6899         char original_path[1024] = "";
6900         
6901         memset( &si, 0, sizeof(STARTUPINFO) );
6902         si.cb = sizeof(si);
6903
6904         // directory
6905         _getcwd(original_path, 1023);
6906
6907         // set up command line
6908         strcpy(cmd_line, original_path);
6909         strcat(cmd_line, "\\");
6910         strcat(cmd_line, LAUNCHER_FNAME);
6911         strcat(cmd_line, " -straight_to_update");               
6912
6913         BOOL ret = CreateProcess(       NULL,                                                                   // pointer to name of executable module 
6914                                                                                 cmd_line,                                                       // pointer to command line string
6915                                                                                 NULL,                                                                   // pointer to process security attributes 
6916                                                                                 NULL,                                                                   // pointer to thread security attributes 
6917                                                                                 FALSE,                                                          // handle inheritance flag 
6918                                                                                 CREATE_DEFAULT_ERROR_MODE,              // creation flags 
6919                                                                                 NULL,                                                                   // pointer to new environment block 
6920                                                                                 NULL,                                                                   // pointer to current directory name 
6921                                                                                 &si,                                                                    // pointer to STARTUPINFO 
6922                                                                                 &pi                                                                     // pointer to PROCESS_INFORMATION  
6923                                                                                 );                      
6924         // to eliminate build warnings
6925         ret;
6926 #else
6927         STUB_FUNCTION;
6928 #endif          
6929 }
6930
6931
6932 // game_shutdown()
6933 //
6934 // This function is called when FreeSpace terminates normally.  
6935 //
6936 void game_shutdown(void)
6937 {
6938 #ifndef PLAT_UNIX
6939         timeEndPeriod(1);
6940 #endif
6941
6942         // don't ever flip a page on the standalone!
6943         if(!(Game_mode & GM_STANDALONE_SERVER)){
6944                 gr_reset_clip();
6945                 gr_clear();
6946                 gr_flip();
6947         }
6948
6949    // if the player has left the "player select" screen and quit the game without actually choosing
6950         // a player, Player will be NULL, in which case we shouldn't write the player file out!
6951         if (!(Game_mode & GM_STANDALONE_SERVER) && (Player!=NULL) && !Is_standalone){
6952                 write_pilot_file();
6953         }
6954
6955         // load up common multiplayer icons
6956         multi_unload_common_icons();
6957         
6958         shockwave_close();                      // release any memory used by shockwave system  
6959         fireball_close();                               // free fireball system
6960         ship_close();                                   // free any memory that was allocated for the ships
6961         hud_free_scrollback_list();// free space allocated to store hud messages in hud scrollback
6962         unload_animating_pointer();// frees the frames used for the animating mouse pointer
6963         bm_unload_all();                                // free bitmaps
6964         mission_campaign_close();       // close out the campaign stuff
6965         multi_voice_close();                    // close down multiplayer voice (including freeing buffers, etc)
6966         multi_log_close();
6967 #ifdef MULTI_USE_LAG
6968         multi_lag_close();
6969 #endif
6970
6971         // the menu close functions will unload the bitmaps if they were displayed during the game
6972 #if !defined(PRESS_TOUR_BUILD) && !defined(PD_BUILD)
6973         main_hall_close();
6974 #endif
6975         training_menu_close();
6976         gr_close();
6977
6978         extern void joy_close();
6979         joy_close();
6980
6981         audiostream_close();
6982         snd_close();
6983         event_music_close();
6984         psnet_close();
6985         os_cleanup();
6986
6987         // HACKITY HACK HACK
6988         // if this flag is set, we should be firing up the launcher when exiting freespace
6989         extern int Multi_update_fireup_launcher_on_exit;
6990         if(Multi_update_fireup_launcher_on_exit){
6991                 game_launch_launcher_on_exit();
6992         }
6993 }
6994
6995 // game_stop_looped_sounds()
6996 //
6997 // This function will call the appropriate stop looped sound functions for those
6998 // modules which use looping sounds.  It is not enough just to stop a looping sound
6999 // at the DirectSound level, the game is keeping track of looping sounds, and this
7000 // function is used to inform the game that looping sounds are being halted.
7001 //
7002 void game_stop_looped_sounds()
7003 {
7004         hud_stop_looped_locking_sounds();
7005         hud_stop_looped_engine_sounds();
7006         afterburner_stop_sounds();
7007         player_stop_looped_sounds();
7008         obj_snd_stop_all();             // stop all object-linked persistant sounds
7009         game_stop_subspace_ambient_sound();
7010         snd_stop(Radar_static_looping);
7011         Radar_static_looping = -1;
7012         snd_stop(Target_static_looping);
7013         shipfx_stop_engine_wash_sound();
7014         Target_static_looping = -1;
7015 }
7016
7017 //////////////////////////////////////////////////////////////////////////
7018 //
7019 // Code for supporting an animating mouse pointer
7020 //
7021 //
7022 //////////////////////////////////////////////////////////////////////////
7023
7024 typedef struct animating_obj
7025 {
7026         int     first_frame;
7027         int     num_frames;
7028         int     current_frame;
7029         float time;
7030         float elapsed_time;
7031 } animating_obj;
7032
7033 static animating_obj Animating_mouse;
7034
7035 // ----------------------------------------------------------------------------
7036 // init_animating_pointer()
7037 //
7038 // Called by load_animating_pointer() to ensure the Animating_mouse struct
7039 // gets properly initialized
7040 //
7041 void init_animating_pointer()
7042 {
7043         Animating_mouse.first_frame     = -1;
7044         Animating_mouse.num_frames              = 0;
7045         Animating_mouse.current_frame   = -1;
7046         Animating_mouse.time                            = 0.0f;
7047         Animating_mouse.elapsed_time    = 0.0f;
7048 }
7049
7050 // ----------------------------------------------------------------------------
7051 // load_animating_pointer()
7052 //
7053 // Called at game init to load in the frames for the animating mouse pointer
7054 //
7055 // input:       filename        =>      filename of animation file that holds the animation
7056 // 
7057 void load_animating_pointer(char *filename, int dx, int dy)
7058 {
7059         int                             fps;
7060         animating_obj *am;
7061
7062         init_animating_pointer();
7063
7064         am = &Animating_mouse;
7065         am->first_frame = bm_load_animation(filename, &am->num_frames, &fps);
7066         if ( am->first_frame == -1 ) 
7067                 Error(LOCATION, "Could not load animation %s for the mouse pointer\n", filename);
7068         am->current_frame = 0;
7069         am->time = am->num_frames / i2fl(fps);
7070 }
7071
7072 // ----------------------------------------------------------------------------
7073 // unload_animating_pointer()
7074 //
7075 // Called at game shutdown to free the memory used to store the animation frames
7076 //
7077 void unload_animating_pointer()
7078 {
7079         int                             i;
7080         animating_obj   *am;
7081
7082         am = &Animating_mouse;
7083         for ( i = 0; i < am->num_frames; i++ ) {
7084                 Assert( (am->first_frame+i) >= 0 );
7085                 bm_release(am->first_frame + i);
7086         }
7087
7088         am->first_frame = -1;
7089         am->num_frames          = 0;
7090         am->current_frame = -1;
7091 }
7092
7093 // draw the correct frame of the game mouse... called from game_maybe_draw_mouse()
7094 void game_render_mouse(float frametime)
7095 {
7096         int                             mx, my;
7097         animating_obj   *am;
7098
7099         // if animating cursor exists, play the next frame
7100         am = &Animating_mouse;
7101         if ( am->first_frame != -1 ) {
7102                 mouse_get_pos(&mx, &my);
7103                 am->elapsed_time += frametime;
7104                 am->current_frame = fl2i( ( am->elapsed_time / am->time ) * (am->num_frames-1) );
7105                 if ( am->current_frame >= am->num_frames ) {
7106                         am->current_frame = 0;
7107                         am->elapsed_time = 0.0f;
7108                 }
7109                 gr_set_cursor_bitmap(am->first_frame + am->current_frame);
7110         }
7111 }
7112
7113 // ----------------------------------------------------------------------------
7114 // game_maybe_draw_mouse()
7115 //
7116 // determines whether to draw the mouse pointer at all, and what frame of
7117 // animation to use if the mouse is animating
7118 //
7119 // Sets mouse.cpp globals Mouse_hidden and Mouse_moved based on the state of the game.
7120 //
7121 // input:       frametime => elapsed frame time in seconds since last call
7122 //
7123 void game_maybe_draw_mouse(float frametime)
7124 {
7125         int game_state;
7126
7127         game_state = gameseq_get_state();
7128
7129         switch ( game_state ) {
7130                 case GS_STATE_GAME_PAUSED:
7131                 // case GS_STATE_MULTI_PAUSED:
7132                 case GS_STATE_GAME_PLAY:
7133                 case GS_STATE_DEATH_DIED:
7134                 case GS_STATE_DEATH_BLEW_UP:
7135                         if ( popup_active() || popupdead_is_active() ) {
7136                                 Mouse_hidden = 0;
7137                         } else {
7138                                 Mouse_hidden = 1;       
7139                         }
7140                         break;
7141
7142                 default:
7143                         Mouse_hidden = 0;
7144                         break;
7145         }       // end switch
7146
7147         if ( !Mouse_hidden ) 
7148                 game_render_mouse(frametime);
7149
7150 }
7151
7152 void game_do_training_checks()
7153 {
7154         int i, s;
7155         float d;
7156         waypoint_list *wplp;
7157
7158         if (Training_context & TRAINING_CONTEXT_SPEED) {
7159                 s = (int) Player_obj->phys_info.fspeed;
7160                 if ((s >= Training_context_speed_min) && (s <= Training_context_speed_max)) {
7161                         if (!Training_context_speed_set) {
7162                                 Training_context_speed_set = 1;
7163                                 Training_context_speed_timestamp = timestamp();
7164                         }
7165
7166                 } else
7167                         Training_context_speed_set = 0;
7168         }
7169
7170         if (Training_context & TRAINING_CONTEXT_FLY_PATH) {
7171                 wplp = &Waypoint_lists[Training_context_path];
7172                 if (wplp->count > Training_context_goal_waypoint) {
7173                         i = Training_context_goal_waypoint;
7174                         do {
7175                                 d = vm_vec_dist(&wplp->waypoints[i], &Player_obj->pos);
7176                                 if (d <= Training_context_distance) {
7177                                         Training_context_at_waypoint = i;
7178                                         if (Training_context_goal_waypoint == i) {
7179                                                 Training_context_goal_waypoint++;
7180                                                 snd_play(&Snds[SND_CARGO_REVEAL], 0.0f);
7181                                         }
7182
7183                                         break;
7184                                 }
7185
7186                                 i++;
7187                                 if (i == wplp->count)
7188                                         i = 0;
7189
7190                         } while (i != Training_context_goal_waypoint);
7191                 }
7192         }
7193
7194         if ((Players_target == UNINITIALIZED) || (Player_ai->target_objnum != Players_target) || (Player_ai->targeted_subsys != Players_targeted_subsys)) {
7195                 Players_target = Player_ai->target_objnum;
7196                 Players_targeted_subsys = Player_ai->targeted_subsys;
7197                 Players_target_timestamp = timestamp();
7198         }
7199 }
7200
7201 /////////// Following is for event debug view screen
7202
7203 #ifndef NDEBUG
7204
7205 #define EVENT_DEBUG_MAX 5000
7206 #define EVENT_DEBUG_EVENT 0x8000
7207
7208 int Event_debug_index[EVENT_DEBUG_MAX];
7209 int ED_count;
7210
7211 void game_add_event_debug_index(int n, int indent)
7212 {
7213         if (ED_count < EVENT_DEBUG_MAX)
7214                 Event_debug_index[ED_count++] = n | (indent << 16);
7215 }
7216
7217 void game_add_event_debug_sexp(int n, int indent)
7218 {
7219         if (n < 0)
7220                 return;
7221
7222         if (Sexp_nodes[n].first >= 0) {
7223                 game_add_event_debug_sexp(Sexp_nodes[n].first, indent);
7224                 game_add_event_debug_sexp(Sexp_nodes[n].rest, indent);
7225                 return;
7226         }
7227
7228         game_add_event_debug_index(n, indent);
7229         if (Sexp_nodes[n].subtype == SEXP_ATOM_OPERATOR)
7230                 game_add_event_debug_sexp(Sexp_nodes[n].rest, indent + 1);
7231         else
7232                 game_add_event_debug_sexp(Sexp_nodes[n].rest, indent);
7233 }
7234
7235 void game_event_debug_init()
7236 {
7237         int e;
7238
7239         ED_count = 0;
7240         for (e=0; e<Num_mission_events; e++) {
7241                 game_add_event_debug_index(e | EVENT_DEBUG_EVENT, 0);
7242                 game_add_event_debug_sexp(Mission_events[e].formula, 1);
7243         }
7244 }
7245
7246 void game_show_event_debug(float frametime) 
7247 {
7248         char buf[256];
7249         int i, k, z;
7250         int font_height, font_width;    
7251         int y_index, y_max;
7252         static int scroll_offset = 0;
7253         
7254         k = game_check_key();
7255         if (k)
7256                 switch (k) {
7257                         case KEY_UP:
7258                         case KEY_PAD8:
7259                                 scroll_offset--;
7260                                 if (scroll_offset < 0)
7261                                         scroll_offset = 0;
7262                                 break;
7263
7264                         case KEY_DOWN:
7265                         case KEY_PAD2:
7266                                 scroll_offset++;
7267                                 break;
7268
7269                         case KEY_PAGEUP:
7270                                 scroll_offset -= 20;
7271                                 if (scroll_offset < 0)
7272                                         scroll_offset = 0;
7273                                 break;
7274
7275                         case KEY_PAGEDOWN:
7276                                 scroll_offset += 20;    // not font-independent, hard-coded since I counted the lines!
7277                                 break;
7278
7279                         default:
7280                                 gameseq_post_event(GS_EVENT_PREVIOUS_STATE);
7281                                 key_flush();
7282                                 break;
7283                 } // end switch
7284
7285         gr_clear();
7286         gr_set_color_fast(&Color_bright);
7287         gr_set_font(FONT1);
7288         gr_printf(0x8000, 5, NOX("EVENT DEBUG VIEW"));
7289
7290         gr_set_color_fast(&Color_normal);
7291         gr_set_font(FONT1);
7292         gr_get_string_size(&font_width, &font_height, NOX("test"));
7293         y_max = gr_screen.max_h - font_height - 5;
7294         y_index = 45;
7295
7296         k = scroll_offset;
7297         while (k < ED_count) {
7298                 if (y_index > y_max)
7299                         break;
7300
7301                 z = Event_debug_index[k];
7302                 if (z & EVENT_DEBUG_EVENT) {
7303                         z &= 0x7fff;
7304                         sprintf(buf, NOX("%s%s (%s) %s%d %d"), (Mission_events[z].flags & MEF_CURRENT) ? NOX("* ") : "",
7305                                 Mission_events[z].name, Mission_events[z].result ? NOX("True") : NOX("False"),
7306                                 (Mission_events[z].chain_delay < 0) ? "" : NOX("x "),
7307                                 Mission_events[z].repeat_count, Mission_events[z].interval);
7308
7309                 } else {
7310                         i = (z >> 16) * 3;
7311                         buf[i] = 0;
7312                         while (i--)
7313                                 buf[i] = ' ';
7314
7315                         strcat(buf, Sexp_nodes[z & 0x7fff].text);
7316                         switch (Sexp_nodes[z & 0x7fff].value) {
7317                                 case SEXP_TRUE:
7318                                         strcat(buf, NOX(" (True)"));
7319                                         break;
7320
7321                                 case SEXP_FALSE:
7322                                         strcat(buf, NOX(" (False)"));
7323                                         break;
7324
7325                                 case SEXP_KNOWN_TRUE:
7326                                         strcat(buf, NOX(" (Always true)"));
7327                                         break;
7328
7329                                 case SEXP_KNOWN_FALSE:
7330                                         strcat(buf, NOX(" (Always false)"));
7331                                         break;
7332
7333                                 case SEXP_CANT_EVAL:
7334                                         strcat(buf, NOX(" (Can't eval)"));
7335                                         break;
7336
7337                                 case SEXP_NAN:
7338                                 case SEXP_NAN_FOREVER:
7339                                         strcat(buf, NOX(" (Not a number)"));
7340                                         break;
7341                         }
7342                 }
7343
7344                 gr_printf(10, y_index, buf);
7345                 y_index += font_height;
7346                 k++;
7347         }
7348
7349         gr_flip();
7350 }
7351
7352 #endif // NDEBUG
7353
7354 #ifndef NDEBUG
7355 FILE * Time_fp;
7356 FILE * Texture_fp;
7357
7358 extern int Tmap_npixels;
7359
7360 int Tmap_num_too_big = 0;
7361 int Num_models_needing_splitting = 0;
7362
7363 void Time_model( int modelnum )
7364 {
7365 //      mprintf(( "Timing ship '%s'\n", si->name ));
7366
7367         vector eye_pos, model_pos;
7368         matrix eye_orient, model_orient;
7369
7370         polymodel *pm = model_get( modelnum );
7371
7372         int l = strlen(pm->filename);
7373         while( (l>0) )  {
7374                 if ( (l == '/') || (l=='\\') || (l==':'))       {
7375                         l++;
7376                         break;
7377                 }
7378                 l--;
7379         }
7380         char *pof_file = &pm->filename[l];
7381
7382         int model_needs_splitting = 0;
7383
7384         //fprintf( Texture_fp, "Model: %s\n", pof_file );
7385         int i;
7386         for (i=0; i<pm->n_textures; i++ )       {
7387                 char filename[1024];
7388                 ubyte pal[768];
7389
7390                 int bmp_num = pm->original_textures[i];
7391                 if ( bmp_num > -1 )     {
7392                         bm_get_palette(pm->original_textures[i], pal, filename );               
7393                         int w,h;
7394                         bm_get_info( pm->original_textures[i],&w, &h );
7395
7396
7397                         if ( (w > 512) || (h > 512) )   {
7398                                 fprintf( Texture_fp, "%s\t%s\t%d\t%d\n", pof_file, filename, w, h );
7399                                 Tmap_num_too_big++;
7400                                 model_needs_splitting++;
7401                         }
7402                 } else {
7403                         //fprintf( Texture_fp, "\tTexture %d is bogus\n", i );
7404                 }
7405         }
7406
7407         if ( model_needs_splitting )    {
7408                 Num_models_needing_splitting++;
7409         }
7410         eye_orient = model_orient = vmd_identity_matrix;
7411         eye_pos = model_pos = vmd_zero_vector;
7412
7413         eye_pos.z = -pm->rad*2.0f;
7414
7415         vector eye_to_model;
7416
7417         vm_vec_sub( &eye_to_model, &model_pos, &eye_pos );
7418         vm_vector_2_matrix( &eye_orient, &eye_to_model, NULL, NULL );
7419
7420         fix t1 = timer_get_fixed_seconds();
7421
7422         angles ta;
7423         ta.p = ta.b = ta.h = 0.0f; 
7424         int framecount = 0;
7425
7426         Tmap_npixels = 0;
7427
7428         int bitmaps_used_this_frame, bitmaps_new_this_frame;
7429                 
7430         bm_get_frame_usage(&bitmaps_used_this_frame,&bitmaps_new_this_frame);
7431
7432         modelstats_num_polys = modelstats_num_verts = 0;
7433
7434         while( ta.h < PI2 )     {
7435
7436                 matrix m1;
7437                 vm_angles_2_matrix(&m1, &ta );
7438                 vm_matrix_x_matrix( &model_orient, &vmd_identity_matrix, &m1 );
7439
7440                 gr_reset_clip();
7441 //              gr_clear();
7442
7443                 g3_start_frame(1);
7444
7445                 g3_set_view_matrix( &eye_pos, &eye_orient, Viewer_zoom );       
7446
7447                 model_clear_instance( modelnum );
7448                 model_set_detail_level(0);              // use highest detail level
7449                 model_render( modelnum, &model_orient, &model_pos, MR_LOCK_DETAIL);     //|MR_NO_POLYS );
7450
7451                 g3_end_frame();
7452 //              gr_flip();
7453
7454                 framecount++;
7455                 ta.h += 0.1f;
7456
7457                 int k = key_inkey();
7458                 if ( k == KEY_ESC ) {
7459                         exit(1);
7460                 }
7461         }
7462
7463         fix t2 = timer_get_fixed_seconds();
7464
7465         bm_get_frame_usage(&bitmaps_used_this_frame,&bitmaps_new_this_frame);
7466         //bitmaps_used_this_frame /= framecount;
7467
7468         modelstats_num_polys /= framecount;
7469         modelstats_num_verts /= framecount;
7470
7471         Tmap_npixels /=framecount;
7472
7473
7474         mprintf(( "'%s' is %.2f FPS\n", pof_file, i2fl(framecount)/f2fl(t2-t1) ));
7475         fprintf( Time_fp, "\"%s\"\t%.0f\t%d\t%d\t%d\t%d\n", pof_file, i2fl(framecount)/f2fl(t2-t1), bitmaps_used_this_frame, modelstats_num_polys, modelstats_num_verts, Tmap_npixels );
7476 //      fprintf( Time_fp, "%.0f\t%d\t%d\t%d\t%d\n", i2fl(framecount)/f2fl(t2-t1), bitmaps_used_this_frame, modelstats_num_polys, modelstats_num_verts, Tmap_npixels );
7477
7478                 
7479 //      key_getch();
7480 }
7481
7482 int Time_models = 0;
7483 DCF_BOOL( time_models, Time_models );
7484
7485 void Do_model_timings_test()
7486 {
7487         
7488
7489         if ( !Time_models ) return;
7490
7491         mprintf(( "Timing models!\n" ));
7492
7493         int i;
7494
7495         ubyte model_used[MAX_POLYGON_MODELS];
7496         int model_id[MAX_POLYGON_MODELS];
7497         for (i=0; i<MAX_POLYGON_MODELS; i++ )   {
7498                 model_used[i] = 0;
7499         }
7500         
7501         // Load them all
7502         for (i=0; i<Num_ship_types; i++ )       {
7503                 Ship_info[i].modelnum = model_load( Ship_info[i].pof_file, NULL, NULL );
7504
7505                 model_used[Ship_info[i].modelnum%MAX_POLYGON_MODELS]++;
7506                 model_id[Ship_info[i].modelnum%MAX_POLYGON_MODELS] = Ship_info[i].modelnum;
7507         }
7508
7509         Texture_fp = fopen( NOX("ShipTextures.txt"), "wt" );
7510         if ( !Texture_fp ) return;
7511
7512         Time_fp = fopen( NOX("ShipTimings.txt"), "wt" );
7513         if ( !Time_fp ) return;
7514
7515         fprintf( Time_fp, "Name\tFPS\tTRAM\tPolys\tVerts\tPixels\n" );
7516 //      fprintf( Time_fp, "FPS\tTRAM\tPolys\tVerts\tPixels\n" );
7517         
7518         for (i=0; i<MAX_POLYGON_MODELS; i++ )   {
7519                 if ( model_used[i] )    {
7520                         Time_model( model_id[i] );
7521                 }
7522         }
7523         
7524         fprintf( Texture_fp, "Number too big: %d\n", Tmap_num_too_big );
7525         fprintf( Texture_fp, "Number of models needing splitting: %d\n", Num_models_needing_splitting );
7526         
7527         fclose(Time_fp);
7528         fclose(Texture_fp);
7529
7530         exit(1);
7531 }
7532 #endif
7533
7534 // Call this function when you want to inform the player that a feature is not
7535 // enabled in the DEMO version of FreSpace
7536 void game_feature_not_in_demo_popup()
7537 {
7538         popup(PF_USE_AFFIRMATIVE_ICON|PF_BODY_BIG, 1, POPUP_OK, XSTR( "Sorry, this feature is available only in the retail version", 200));
7539 }
7540
7541 // format the specified time (fixed point) into a nice string
7542 void game_format_time(fix m_time,char *time_str)
7543 {
7544         float mtime;
7545         int hours,minutes,seconds;
7546         char tmp[10];
7547
7548         mtime = f2fl(m_time);           
7549
7550         // get the hours, minutes and seconds   
7551         hours = (int)(mtime / 3600.0f);
7552         if(hours > 0){
7553                 mtime -= (3600.0f * (float)hours);
7554         }
7555         seconds = (int)mtime%60;
7556         minutes = (int)mtime/60;                        
7557
7558         // print the hour if necessary
7559         if(hours > 0){          
7560                 sprintf(time_str,XSTR( "%d:", 201),hours);
7561                 // if there are less than 10 minutes, print a leading 0
7562                 if(minutes < 10){
7563                         strcpy(tmp,NOX("0"));
7564                         strcat(time_str,tmp);
7565                 }               
7566         }       
7567         
7568         // print the minutes
7569         if(hours){
7570                 sprintf(tmp,XSTR( "%d:", 201),minutes);
7571                 strcat(time_str,tmp);
7572         } else {
7573                 sprintf(time_str,XSTR( "%d:", 201),minutes);
7574         }
7575
7576         // print the seconds
7577         if(seconds < 10){
7578                 strcpy(tmp,NOX("0"));
7579                 strcat(time_str,tmp);
7580         } 
7581         sprintf(tmp,"%d",seconds);
7582         strcat(time_str,tmp);
7583 }
7584
7585 //      Stuff version string in *str.
7586 void get_version_string(char *str)
7587 {
7588 //XSTR:OFF
7589 if ( FS_VERSION_BUILD == 0 ) {
7590         sprintf(str,"v%d.%02d",FS_VERSION_MAJOR, FS_VERSION_MINOR);
7591 } else {
7592         sprintf(str,"v%d.%02d.%02d",FS_VERSION_MAJOR, FS_VERSION_MINOR, FS_VERSION_BUILD );
7593 }
7594
7595 #if defined (FS2_DEMO)
7596         strcat(str, " D");
7597 #elif defined (OEM_BUILD)
7598         strcat(str, " (OEM)");
7599 #endif
7600 //XSTR:ON
7601         /*
7602         HMODULE hMod;
7603         DWORD bogus_handle;
7604         char myname[_MAX_PATH];
7605         int namelen, major, minor, build, waste;
7606         unsigned int buf_size;
7607         DWORD version_size;
7608         char *infop;
7609         VOID *bufp;
7610         BOOL result;
7611
7612         // Find my EXE file name
7613         hMod = GetModuleHandle(NULL);
7614         namelen = GetModuleFileName( hMod, myname, _MAX_PATH );
7615
7616         version_size = GetFileVersionInfoSize(myname, &bogus_handle );
7617         infop = (char *)malloc(version_size);
7618         result = GetFileVersionInfo( myname, 0, version_size, (LPVOID)infop );
7619
7620         // get the product version
7621         result = VerQueryValue((LPVOID)infop, TEXT("\\StringFileInfo\\040904b0\\ProductVersion"), &bufp, &buf_size );
7622         sscanf( (char *)bufp, "%d, %d, %d, %d", &major, &minor, &build, &waste );
7623 #ifdef DEMO
7624         sprintf(str,"Dv%d.%02d",major, minor);
7625 #else
7626         sprintf(str,"v%d.%02d",major, minor);
7627 #endif
7628         */
7629 }
7630
7631 void get_version_string_short(char *str)
7632 {
7633         sprintf(str,"v%d.%02d",FS_VERSION_MAJOR, FS_VERSION_MINOR);
7634 }
7635
7636 // ----------------------------------------------------------------
7637 //
7638 // OEM UPSELL SCREENS BEGIN
7639 //
7640 // ----------------------------------------------------------------
7641 #if defined(OEM_BUILD)
7642
7643 #define NUM_OEM_UPSELL_SCREENS                          3
7644 #define OEM_UPSELL_SCREEN_DELAY                         10000
7645
7646 static int Oem_upsell_bitmaps_loaded = 0;
7647 static int Oem_upsell_bitmaps[GR_NUM_RESOLUTIONS][NUM_OEM_UPSELL_SCREENS];
7648 static int Oem_upsell_screen_number = 0;
7649 static int Oem_upsell_show_next_bitmap_time;
7650
7651 //XSTR:OFF
7652 static char *Oem_upsell_bitmap_filenames[GR_NUM_RESOLUTIONS][NUM_OEM_UPSELL_SCREENS] = 
7653 {
7654         {       "OEMUpSell02",
7655                 "OEMUpSell01",
7656                 "OEMUpSell03",
7657         },
7658         {       "2_OEMUpSell02",
7659                 "2_OEMUpSell01",
7660                 "2_OEMUpSell03",
7661         },
7662 };
7663 //XSTR:ON
7664
7665 static int Oem_normal_cursor = -1;
7666 static int Oem_web_cursor = -1;
7667 //#define OEM_UPSELL_URL                "http://www.interplay-store.com/"
7668 #define OEM_UPSELL_URL          "http://www.interplay.com/cgi-bin/oemlinks.pl/pid=483421&cid=18384"
7669
7670 void oem_upsell_next_screen()
7671 {
7672         Oem_upsell_screen_number++;
7673         if ( Oem_upsell_screen_number == (NUM_OEM_UPSELL_SCREENS-1) ) {
7674                 // extra long delay, mouse shown on last upsell
7675                 Oem_upsell_show_next_bitmap_time = timer_get_milliseconds() + OEM_UPSELL_SCREEN_DELAY*2;
7676                 Mouse_hidden = 0;
7677
7678         } else {
7679                 Oem_upsell_show_next_bitmap_time = timer_get_milliseconds() + OEM_UPSELL_SCREEN_DELAY;
7680         }
7681 }
7682
7683 void oem_upsell_load_bitmaps()
7684 {
7685         int i;
7686
7687         for ( i = 0; i < NUM_OEM_UPSELL_SCREENS; i++ ) {
7688                 Oem_upsell_bitmaps[gr_screen.res][i] = bm_load(Oem_upsell_bitmap_filenames[gr_screen.res][i]);
7689         }
7690 }
7691
7692 void oem_upsell_unload_bitmaps()
7693 {
7694         int i;
7695
7696         for ( i = 0; i < NUM_OEM_UPSELL_SCREENS; i++ ) {
7697                 if(Oem_upsell_bitmaps[gr_screen.res][i] >= 0){
7698                         bm_unload(Oem_upsell_bitmaps[gr_screen.res][i]);
7699                 }
7700         }
7701
7702         // unloaded
7703         Oem_upsell_bitmaps_loaded = 0;
7704 }
7705
7706 // clickable hotspot on 3rd OEM upsell screen
7707 static int Oem_upsell3_button_coords[GR_NUM_RESOLUTIONS][4] = {
7708         {       // GR_640
7709                 28, 350, 287, 96                                        // x, y, w, h
7710         },
7711         {       // GR_1024
7712                 45, 561, 460, 152                                       // x, y, w, h
7713         }
7714 };
7715
7716 void oem_upsell_show_screens()
7717 {
7718         int current_time, k;
7719         int done = 0;
7720
7721         if ( !Oem_upsell_bitmaps_loaded ) {
7722                 oem_upsell_load_bitmaps();
7723                 Oem_upsell_bitmaps_loaded = 1;
7724         }
7725
7726         // may use upsell screens more than once
7727         Oem_upsell_show_next_bitmap_time = timer_get_milliseconds() + OEM_UPSELL_SCREEN_DELAY;
7728         Oem_upsell_screen_number = 0;
7729         
7730         key_flush();
7731         Mouse_hidden = 1;
7732
7733         // set up cursors
7734         int nframes;                                            // used to pass, not really needed (should be 1)
7735         Oem_normal_cursor = gr_get_cursor_bitmap();
7736         Oem_web_cursor = bm_load_animation("cursorweb", &nframes);
7737         Assert(Oem_web_cursor >= 0);
7738         if (Oem_web_cursor < 0) {
7739                 Oem_web_cursor = Oem_normal_cursor;
7740         }
7741
7742         while(!done) {
7743
7744                 //oem_reset_trailer_timer();
7745
7746                 current_time = timer_get_milliseconds();
7747
7748                 os_poll();
7749                 k = key_inkey();
7750
7751                 // advance screen on keypress or timeout
7752                 if (( k > 0 ) || (mouse_up_count(MOUSE_LEFT_BUTTON) > 0) || (current_time > Oem_upsell_show_next_bitmap_time)) {
7753                         oem_upsell_next_screen();
7754                 }
7755
7756                 // check if we are done
7757                 if ( Oem_upsell_screen_number >= NUM_OEM_UPSELL_SCREENS ) {
7758                         Oem_upsell_screen_number--;
7759                         done = 1;
7760                 } else {
7761                         if ( Oem_upsell_bitmaps[gr_screen.res][Oem_upsell_screen_number] < 0 ) {
7762                                 done = 1;
7763                         }
7764                 }
7765
7766                 // show me the upsell
7767                 if ( Oem_upsell_bitmaps[gr_screen.res][Oem_upsell_screen_number] >= 0 ) {               
7768                         gr_set_bitmap(Oem_upsell_bitmaps[gr_screen.res][Oem_upsell_screen_number]);
7769                         gr_bitmap(0,0);
7770                 }
7771
7772                 // if this is the 3rd upsell, make it clickable, d00d
7773                 if ( Oem_upsell_screen_number == NUM_OEM_UPSELL_SCREENS-1 ) {
7774                         int mx, my;
7775                         int button_state = mouse_get_pos(&mx, &my);
7776                         if ( (mx >= Oem_upsell3_button_coords[gr_screen.res][0]) && (mx <= Oem_upsell3_button_coords[gr_screen.res][0] + Oem_upsell3_button_coords[gr_screen.res][2])
7777                                 && (my >= Oem_upsell3_button_coords[gr_screen.res][1]) && (my <= Oem_upsell3_button_coords[gr_screen.res][1] + Oem_upsell3_button_coords[gr_screen.res][3]) )
7778                         {
7779                                 // switch cursors
7780                                 gr_set_cursor_bitmap(Oem_web_cursor); //, GR_CURSOR_LOCK);
7781
7782                                 // check for clicks
7783                                 if (button_state & MOUSE_LEFT_BUTTON) {
7784                                         // launch URL
7785                                         multi_pxo_url(OEM_UPSELL_URL);
7786                                         done = 1;
7787                                 } 
7788                         } else {
7789                                 // switch cursor back to normal one
7790                                 gr_set_cursor_bitmap(Oem_normal_cursor); //, GR_CURSOR_UNLOCK);
7791                         }
7792                 }
7793
7794                 if ( done ) {
7795                         if (gameseq_get_state() != GS_STATE_END_DEMO) {
7796                                 gr_fade_out(0);
7797                                 Sleep(300);
7798                         }
7799                 }
7800
7801                 gr_flip();
7802         }
7803
7804         // unload bitmap
7805         oem_upsell_unload_bitmaps();
7806
7807         // switch cursor back to normal one
7808         gr_set_cursor_bitmap(Oem_normal_cursor); //, GR_CURSOR_UNLOCK);
7809
7810 }
7811
7812 #endif // defined(OEM_BUILD)
7813 // ----------------------------------------------------------------
7814 //
7815 // OEM UPSELL SCREENS END
7816 //
7817 // ----------------------------------------------------------------
7818
7819
7820
7821 // ----------------------------------------------------------------
7822 //
7823 // DEMO UPSELL SCREENS BEGIN
7824 //
7825 // ----------------------------------------------------------------
7826
7827 #ifdef FS2_DEMO
7828
7829 //#define NUM_DEMO_UPSELL_SCREENS                               4
7830
7831 #define NUM_DEMO_UPSELL_SCREENS                         2
7832 #define DEMO_UPSELL_SCREEN_DELAY                                3000
7833
7834 static int Demo_upsell_bitmaps_loaded = 0;
7835 static int Demo_upsell_bitmaps[GR_NUM_RESOLUTIONS][NUM_DEMO_UPSELL_SCREENS];
7836 static int Demo_upsell_screen_number = 0;
7837 static int Demo_upsell_show_next_bitmap_time;
7838
7839 //XSTR:OFF
7840 static char *Demo_upsell_bitmap_filenames[GR_NUM_RESOLUTIONS][NUM_DEMO_UPSELL_SCREENS] = 
7841 {
7842         {       "UpSell02",
7843                 "UpSell01",
7844         },
7845         {       "2_UpSell02",
7846                 "2_UpSell01",
7847         },
7848         // "DemoUpsell3",
7849         // "DemoUpsell4",
7850 };
7851 //XSTR:ON
7852
7853 void demo_upsell_next_screen()
7854 {
7855         Demo_upsell_screen_number++;
7856         if ( Demo_upsell_screen_number == (NUM_DEMO_UPSELL_SCREENS-1) ) {
7857                 Demo_upsell_show_next_bitmap_time = timer_get_milliseconds() + DEMO_UPSELL_SCREEN_DELAY*4;
7858         } else {
7859                 Demo_upsell_show_next_bitmap_time = timer_get_milliseconds() + DEMO_UPSELL_SCREEN_DELAY;
7860         }
7861
7862         /*
7863         if ( Demo_upsell_screen_number < NUM_DEMO_UPSELL_SCREENS ) {
7864                 if ( Demo_upsell_bitmap_filenames[gr_screen.res][Demo_upsell_screen_number] >= 0 ) {
7865 #ifndef HARDWARE_ONLY
7866                         palette_use_bm_palette(Demo_upsell_bitmaps[gr_screen.res][Demo_upsell_screen_number]);
7867 #endif
7868                 }
7869         }
7870         */
7871 }
7872
7873 void demo_upsell_load_bitmaps()
7874 {
7875         int i;
7876
7877         for ( i = 0; i < NUM_DEMO_UPSELL_SCREENS; i++ ) {
7878                 Demo_upsell_bitmaps[gr_screen.res][i] = bm_load(Demo_upsell_bitmap_filenames[gr_screen.res][i]);
7879         }
7880 }
7881
7882 void demo_upsell_unload_bitmaps()
7883 {
7884         int i;
7885
7886         for ( i = 0; i < NUM_DEMO_UPSELL_SCREENS; i++ ) {
7887                 if(Demo_upsell_bitmaps[gr_screen.res][i] >= 0){
7888                         bm_unload(Demo_upsell_bitmaps[gr_screen.res][i]);
7889                 }
7890         }
7891
7892         // unloaded
7893         Demo_upsell_bitmaps_loaded = 0;
7894 }
7895
7896 void demo_upsell_show_screens()
7897 {
7898         int current_time, k;
7899         int done = 0;
7900
7901         if ( !Demo_upsell_bitmaps_loaded ) {
7902                 demo_upsell_load_bitmaps();
7903                 Demo_upsell_bitmaps_loaded = 1;
7904         }
7905
7906         // may use upsell screens more than once
7907         Demo_upsell_show_next_bitmap_time = timer_get_milliseconds() + DEMO_UPSELL_SCREEN_DELAY;
7908         Demo_upsell_screen_number = 0;
7909         
7910         key_flush();
7911         Mouse_hidden = 1;
7912
7913         while(!done) {
7914
7915                 demo_reset_trailer_timer();
7916
7917                 current_time = timer_get_milliseconds();
7918
7919 // #ifndef THREADED
7920                 os_poll();
7921 // #endif
7922                 k = key_inkey();
7923
7924                 // don't time out, wait for keypress
7925                 /*
7926                 if ( current_time > Demo_upsell_show_next_bitmap_time ) {
7927                         demo_upsell_next_screen();
7928                         k = 0;
7929                 }*/
7930
7931                 if ( k > 0 ) {
7932                         demo_upsell_next_screen();
7933                 }
7934
7935                 if ( Demo_upsell_screen_number >= NUM_DEMO_UPSELL_SCREENS ) {
7936                         Demo_upsell_screen_number--;
7937                         done = 1;
7938                 } else {
7939                         if ( Demo_upsell_bitmaps[gr_screen.res][Demo_upsell_screen_number] < 0 ) {
7940                                 done = 1;
7941                         }
7942                 }
7943
7944                 if ( Demo_upsell_bitmaps[gr_screen.res][Demo_upsell_screen_number] >= 0 ) {             
7945                         gr_set_bitmap(Demo_upsell_bitmaps[gr_screen.res][Demo_upsell_screen_number]);
7946                         gr_bitmap(0,0);
7947                 }
7948
7949                 if ( done ) {
7950                         if (gameseq_get_state() != GS_STATE_END_DEMO) {
7951                                 gr_fade_out(0);
7952                                 Sleep(300);
7953                         }
7954                 }
7955
7956                 gr_flip();
7957         }
7958
7959         // unload bitmap
7960         demo_upsell_unload_bitmaps();
7961 }
7962
7963 #endif // DEMO
7964
7965 // ----------------------------------------------------------------
7966 //
7967 // DEMO UPSELL SCREENS END
7968 //
7969 // ----------------------------------------------------------------
7970
7971
7972 // ----------------------------------------------------------------
7973 //
7974 // Subspace Ambient Sound START
7975 //
7976 // ----------------------------------------------------------------
7977
7978 static int Subspace_ambient_left_channel = -1;
7979 static int Subspace_ambient_right_channel = -1;
7980
7981 // 
7982 void game_start_subspace_ambient_sound()
7983 {
7984         if ( Subspace_ambient_left_channel < 0 ) {
7985                 Subspace_ambient_left_channel = snd_play_looping(&Snds[SND_SUBSPACE_LEFT_CHANNEL], -1.0f);
7986         }
7987
7988         if ( Subspace_ambient_right_channel < 0 ) {
7989                 Subspace_ambient_right_channel = snd_play_looping(&Snds[SND_SUBSPACE_RIGHT_CHANNEL], 1.0f);
7990         }
7991 }
7992
7993 void game_stop_subspace_ambient_sound()
7994 {
7995         if ( Subspace_ambient_left_channel >= 0 ) {
7996                 snd_stop(Subspace_ambient_left_channel);
7997                 Subspace_ambient_left_channel = -1;
7998         }
7999
8000         if ( Subspace_ambient_right_channel >= 0 ) {
8001                 snd_stop(Subspace_ambient_right_channel);
8002                 Subspace_ambient_right_channel = -1;
8003         }
8004 }
8005
8006 // ----------------------------------------------------------------
8007 //
8008 // Subspace Ambient Sound END
8009 //
8010 // ----------------------------------------------------------------
8011
8012 // ----------------------------------------------------------------
8013 //
8014 // CDROM detection code START
8015 //
8016 // ----------------------------------------------------------------
8017
8018 #define CD_SIZE_72_MINUTE_MAX                   (697000000)
8019
8020 uint game_get_cd_used_space(char *path)
8021 {
8022 #ifndef PLAT_UNIX
8023         uint total = 0;
8024         char use_path[512] = "";
8025         char sub_path[512] = "";
8026         WIN32_FIND_DATA find;
8027         HANDLE find_handle;
8028
8029         // recurse through all files and directories
8030         strcpy(use_path, path);
8031         strcat(use_path, "*.*");
8032         find_handle = FindFirstFile(use_path, &find);
8033
8034         // bogus
8035         if(find_handle == INVALID_HANDLE_VALUE){
8036                 return 0;
8037         }       
8038
8039         // whee
8040         do {
8041                 // subdirectory. make sure to ignore . and ..
8042                 if((find.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) && stricmp(find.cFileName, ".") && stricmp(find.cFileName, "..")){
8043                         // subsearch
8044                         strcpy(sub_path, path);
8045                         strcat(sub_path, find.cFileName);
8046                         strcat(sub_path, "\\");
8047                         total += game_get_cd_used_space(sub_path);      
8048                 } else {
8049                         total += (uint)find.nFileSizeLow;
8050                 }                               
8051         } while(FindNextFile(find_handle, &find));      
8052
8053         // close
8054         FindClose(find_handle);
8055
8056         // total
8057         return total;
8058 #else
8059         STUB_FUNCTION;
8060         
8061         return 0;
8062 #endif  
8063 }
8064
8065
8066 // if volume_name is non-null, the CD name must match that
8067 int find_freespace_cd(char *volume_name)
8068 {
8069 #ifndef PLAT_UNIX
8070         char oldpath[MAX_PATH];
8071         char volume[256];
8072         int i;
8073         int cdrom_drive=-1;
8074         int volume_match = 0;
8075         _finddata_t find;
8076         int find_handle;
8077
8078         GetCurrentDirectory(MAX_PATH, oldpath);
8079
8080         for (i = 0; i < 26; i++) 
8081         {
8082 //XSTR:OFF
8083                 char path[]="d:\\";
8084 //XSTR:ON
8085
8086                 path[0] = (char)('A'+i);
8087                 if (GetDriveType(path) == DRIVE_CDROM) {
8088                         cdrom_drive = -3;
8089                         if ( GetVolumeInformation(path, volume, 256, NULL, NULL, NULL, NULL, 0) == TRUE ) {
8090                                 nprintf(("CD", "CD volume: %s\n", volume));
8091                         
8092                                 // check for any CD volume
8093                                 int volume1_present = 0;
8094                                 int volume2_present = 0;
8095                                 int volume3_present = 0;                
8096
8097                                 char full_check[512] = "";
8098
8099                                 // look for setup.exe
8100                                 strcpy(full_check, path);
8101                                 strcat(full_check, "setup.exe");                                
8102                                 find_handle = _findfirst(full_check, &find);
8103                                 if(find_handle != -1){
8104                                         volume1_present = 1;                            
8105                                         _findclose(find_handle);                                
8106                                 }
8107
8108                                 // look for intro.mve
8109                                 strcpy(full_check, path);
8110                                 strcat(full_check, "intro.mve");                                
8111                                 find_handle = _findfirst(full_check, &find);
8112                                 if(find_handle != -1){
8113                                         volume2_present = 1;
8114                                         _findclose(find_handle);                                                
8115                                 }                               
8116
8117                                 // look for endpart1.mve
8118                                 strcpy(full_check, path);
8119                                 strcat(full_check, "endpart1.mve");                             
8120                                 find_handle = _findfirst(full_check, &find);
8121                                 if(find_handle != -1){
8122                                         volume3_present = 1;
8123                                         _findclose(find_handle);                                
8124                                 }                               
8125                         
8126                                 // see if we have the specific CD we're looking for
8127                                 if ( volume_name ) {
8128                                         // volume 1
8129                                         if ( !stricmp(volume_name, FS_CDROM_VOLUME_1) && volume1_present) {
8130                                                 volume_match = 1;
8131                                         }
8132                                         // volume 2
8133                                         if ( !stricmp(volume_name, FS_CDROM_VOLUME_2) && volume2_present) {
8134                                                 volume_match = 1;
8135                                         }
8136                                         // volume 3
8137                                         if ( !stricmp(volume_name, FS_CDROM_VOLUME_3) && volume3_present) {
8138                                                 volume_match = 1;
8139                                         }
8140                                 } else {                                                                                
8141                                         if ( volume1_present || volume2_present || volume3_present ) {
8142                                                 volume_match = 1;
8143                                         }
8144                                 }
8145                                 
8146                                 // here's where we make sure that CD's 2 and 3 are not just ripped - check to make sure its capacity is > 697,000,000 bytes                             
8147                                 if ( volume_match ){
8148 #ifdef RELEASE_REAL                                     
8149                                         // we don't care about CD1 though. let it be whatever size it wants, since the game will demand CD's 2 and 3 at the proper time
8150                                         if(volume2_present || volume3_present) {
8151                                                 // first step - check to make sure its a cdrom
8152                                                 if(GetDriveType(path) != DRIVE_CDROM){                                                  
8153                                                         break;
8154                                                 }
8155
8156 #if !defined(OEM_BUILD)
8157                                                 // oem not on 80 min cds, so dont check tha size
8158                                                 // check its size
8159                                                 uint used_space = game_get_cd_used_space(path);                                                                                 
8160                                                 if(used_space < CD_SIZE_72_MINUTE_MAX){                                                 
8161                                                         break;
8162                                                 }
8163 #endif // !defined(OEM_BUILD)
8164                                         }                                       
8165
8166                                         cdrom_drive = i;
8167                                         break;
8168 #else
8169                                         cdrom_drive = i;
8170                                         break;
8171 #endif // RELEASE_REAL
8172                                 }
8173                         }
8174                 }
8175         }       
8176
8177         SetCurrentDirectory(oldpath);
8178         return cdrom_drive;
8179 #else
8180         STUB_FUNCTION;
8181         
8182         return 0;
8183 #endif  
8184 }
8185
8186 int set_cdrom_path(int drive_num)
8187 {
8188         int rval;
8189
8190         if (drive_num < 0) {                    //no CD
8191 //              #ifndef NDEBUG
8192 //              strcpy(CDROM_dir,"j:\\FreeSpaceCD\\");                          //set directory
8193 //              rval = 1;
8194 //              #else
8195                 strcpy(Game_CDROM_dir,"");                              //set directory
8196                 rval = 0;
8197 //              #endif
8198         } else {
8199                 sprintf(Game_CDROM_dir,NOX("%c:\\"), 'a' + drive_num );                 //set directory
8200                 rval = 1;
8201         }
8202
8203         return rval;
8204 }
8205
8206 int init_cdrom()
8207 {
8208         int i, rval;
8209
8210         //scan for CD, etc.
8211
8212         rval = 1;
8213
8214         #ifndef DEMO
8215         i = find_freespace_cd();
8216
8217         rval = set_cdrom_path(i);
8218
8219         /*
8220         if ( rval ) {
8221                 nprintf(("CD", "Using %s for FreeSpace CD\n", CDROM_dir));
8222         } else {
8223                 nprintf(("CD", "FreeSpace CD not found\n"));
8224         }
8225         */
8226         #endif
8227
8228         return rval;
8229 }
8230
8231 int Last_cd_label_found = 0;
8232 char Last_cd_label[256];
8233
8234 int game_cd_changed()
8235 {
8236 #ifndef PLAT_UNIX
8237         char label[256];
8238         int found;
8239         int changed = 0;
8240         
8241         if ( strlen(Game_CDROM_dir) == 0 ) {
8242                 init_cdrom();
8243         }
8244
8245         found = GetVolumeInformation(Game_CDROM_dir, label, 256, NULL, NULL, NULL, NULL, 0);
8246
8247         if ( found != Last_cd_label_found )     {
8248                 Last_cd_label_found = found;
8249                 if ( found )    {
8250                         mprintf(( "CD '%s' was inserted\n", label ));
8251                         changed = 1;
8252                 } else {
8253                         mprintf(( "CD '%s' was removed\n", Last_cd_label ));
8254                         changed = 1;
8255                 }
8256         } else {
8257                 if ( Last_cd_label_found )      {
8258                         if ( !stricmp( Last_cd_label, label ))  {
8259                                 //mprintf(( "CD didn't change\n" ));
8260                         } else {
8261                                 mprintf(( "CD was changed from '%s' to '%s'\n", Last_cd_label, label ));
8262                                 changed = 1;
8263                         }
8264                 } else {
8265                         // none found before, none found now.
8266                         //mprintf(( "still no CD...\n" ));
8267                 }
8268         }
8269         
8270         Last_cd_label_found = found;
8271         if ( found )    {
8272                 strcpy( Last_cd_label, label );
8273         } else {
8274                 strcpy( Last_cd_label, "" );
8275         }
8276
8277         return changed;
8278 #else
8279         STUB_FUNCTION;
8280 #endif          
8281 }
8282
8283 // check if _any_ FreeSpace2 CDs are in the drive
8284 // return: 1    => CD now in drive
8285 //                        0     =>      Could not find CD, they refuse to put it in the drive
8286 int game_do_cd_check(char *volume_name)
8287 {       
8288 #if !defined(GAME_CD_CHECK)
8289         return 1;
8290 #else
8291         int cd_present = 0;
8292         int cd_drive_num;
8293
8294         int num_attempts = 0;
8295         int refresh_files = 0;
8296         while(1) {
8297                 int path_set_ok, popup_rval;
8298
8299                 cd_drive_num = find_freespace_cd(volume_name);
8300                 path_set_ok = set_cdrom_path(cd_drive_num);
8301                 if ( path_set_ok ) {
8302                         cd_present = 1;
8303                         if ( refresh_files ) {
8304                                 cfile_refresh();
8305                                 refresh_files = 0;
8306                         }
8307                         break;
8308                 }
8309
8310                 // standalone mode
8311                 if(Is_standalone){
8312                         cd_present = 0;
8313                         break;
8314                 } else {
8315                         // no CD found, so prompt user
8316                         popup_rval = popup(PF_BODY_BIG, 1, POPUP_OK, XSTR( "FreeSpace 2 CD not found\n\nInsert a FreeSpace 2 CD to continue", 202));
8317                         refresh_files = 1;
8318                         if ( popup_rval != 1 ) {
8319                                 cd_present = 0;
8320                                 break;
8321                         }
8322
8323                         if ( num_attempts++ > 5 ) {
8324                                 cd_present = 0;
8325                                 break;
8326                         }
8327                 }
8328         }
8329
8330         return cd_present;
8331 #endif
8332 }
8333
8334 // check if _any_ FreeSpace2 CDs are in the drive
8335 // return: 1    => CD now in drive
8336 //                        0     =>      Could not find CD, they refuse to put it in the drive
8337 int game_do_cd_check_specific(char *volume_name, int cdnum)
8338 {       
8339         int cd_present = 0;
8340         int cd_drive_num;
8341
8342         int num_attempts = 0;
8343         int refresh_files = 0;
8344         while(1) {
8345                 int path_set_ok, popup_rval;
8346
8347                 cd_drive_num = find_freespace_cd(volume_name);
8348                 path_set_ok = set_cdrom_path(cd_drive_num);
8349                 if ( path_set_ok ) {
8350                         cd_present = 1;
8351                         if ( refresh_files ) {
8352                                 cfile_refresh();
8353                                 refresh_files = 0;
8354                         }
8355                         break;
8356                 }
8357
8358                 if(Is_standalone){
8359                         cd_present = 0;
8360                         break;
8361                 } else {
8362                         // no CD found, so prompt user
8363 #if defined(DVD_MESSAGE_HACK)
8364                         popup_rval = popup(PF_BODY_BIG, 1, POPUP_OK, XSTR("Please insert DVD", 1468));
8365 #else
8366                         popup_rval = popup(PF_BODY_BIG, 1, POPUP_OK, XSTR("Please insert CD %d", 1468), cdnum);
8367 #endif
8368                         refresh_files = 1;
8369                         if ( popup_rval != 1 ) {
8370                                 cd_present = 0;
8371                                 break;
8372                         }
8373
8374                         if ( num_attempts++ > 5 ) {
8375                                 cd_present = 0;
8376                                 break;
8377                         }
8378                 }
8379         }
8380
8381         return cd_present;
8382 }
8383
8384 // only need to do this in RELEASE_REAL
8385 int game_do_cd_mission_check(char *filename)
8386 {       
8387 #ifdef RELEASE_REAL
8388         int cd_num;
8389         int cd_present = 0;
8390         int cd_drive_num;
8391         fs_builtin_mission *m = game_find_builtin_mission(filename);
8392
8393         // check for changed CD
8394         if(game_cd_changed()){
8395                 cfile_refresh();
8396         }
8397
8398         // multiplayer
8399         if((Game_mode & GM_MULTIPLAYER) || Is_standalone){
8400                 return 1;
8401         }
8402
8403         // not builtin, so do a general check (any FS2 CD will do)
8404         if(m == NULL){
8405                 return game_do_cd_check();
8406         }
8407
8408         // does not have any CD requirement, do a general check
8409         if(strlen(m->cd_volume) <= 0){
8410                 return game_do_cd_check();
8411         }
8412
8413         // get the volume
8414         if(!stricmp(m->cd_volume, FS_CDROM_VOLUME_1)){
8415                 cd_num = 1;
8416         } else if(!stricmp(m->cd_volume, FS_CDROM_VOLUME_2)){
8417                 cd_num = 2;
8418         } else if(!stricmp(m->cd_volume, FS_CDROM_VOLUME_3)){
8419                 cd_num = 3; 
8420         } else {
8421                 return game_do_cd_check();
8422         }
8423
8424         // did we find the cd?
8425         if(find_freespace_cd(m->cd_volume) >= 0){
8426                 return 1;
8427         }
8428
8429         // make sure the volume exists
8430         int num_attempts = 0;
8431         int refresh_files = 0;
8432         while(1){
8433                 int path_set_ok, popup_rval;
8434
8435                 cd_drive_num = find_freespace_cd(m->cd_volume);
8436                 path_set_ok = set_cdrom_path(cd_drive_num);
8437                 if ( path_set_ok ) {
8438                         cd_present = 1;
8439                         if ( refresh_files ) {
8440                                 cfile_refresh();
8441                                 refresh_files = 0;
8442                         }
8443                         break;
8444                 }
8445
8446                 // no CD found, so prompt user
8447 #if defined(DVD_MESSAGE_HACK)
8448                 popup_rval = popup(PF_BODY_BIG, 1, POPUP_OK, XSTR("Please insert DVD", 1468));
8449 #else
8450                 popup_rval = popup(PF_BODY_BIG, 1, POPUP_OK, XSTR("Please insert CD %d", 1468), cd_num);
8451 #endif
8452
8453                 refresh_files = 1;
8454                 if ( popup_rval != 1 ) {
8455                         cd_present = 0;
8456                         break;
8457                 }
8458
8459                 if ( num_attempts++ > 5 ) {
8460                         cd_present = 0;
8461                         break;
8462                 }
8463         }       
8464
8465         return cd_present;
8466 #else
8467         return 1;
8468 #endif
8469 }
8470
8471 // ----------------------------------------------------------------
8472 //
8473 // CDROM detection code END
8474 //
8475 // ----------------------------------------------------------------
8476
8477 // ----------------------------------------------------------------
8478 // SHIPS TBL VERIFICATION STUFF
8479 //
8480
8481 // checksums, just keep a list of all valid ones, if it matches any of them, keep it
8482 #define NUM_SHIPS_TBL_CHECKSUMS         1
8483 /*
8484 int Game_ships_tbl_checksums[NUM_SHIPS_TBL_CHECKSUMS] = {
8485         -463907578,                                             // US - beta 1
8486         1696074201,                                             // FS2 demo
8487 };
8488 */
8489 int Game_ships_tbl_checksums[NUM_SHIPS_TBL_CHECKSUMS] = {
8490 //      -1022810006,                                    // 1.0 FULL
8491         -1254285366                                             // 1.2 FULL (German)
8492 };
8493
8494 void verify_ships_tbl()
8495 {       
8496         /*
8497 #ifdef NDEBUG
8498         Game_ships_tbl_valid = 1;
8499 #else
8500         */
8501         uint file_checksum;             
8502         int idx;
8503
8504         // detect if the packfile exists
8505         CFILE *detect = cfopen("ships.tbl", "rb");
8506         Game_ships_tbl_valid = 0;        
8507         
8508         // not mission-disk
8509         if(!detect){
8510                 Game_ships_tbl_valid = 0;
8511                 return;
8512         }       
8513
8514         // get the long checksum of the file
8515         file_checksum = 0;
8516         cfseek(detect, 0, SEEK_SET);    
8517         cf_chksum_long(detect, &file_checksum);
8518         cfclose(detect);
8519         detect = NULL;  
8520
8521         // now compare the checksum/filesize against known #'s
8522         for(idx=0; idx<NUM_SHIPS_TBL_CHECKSUMS; idx++){
8523                 if(Game_ships_tbl_checksums[idx] == (int)file_checksum){
8524                         Game_ships_tbl_valid = 1;
8525                         return;
8526                 }
8527         }
8528 // #endif
8529 }
8530
8531 DCF(shipspew, "display the checksum for the current ships.tbl")
8532 {
8533         uint file_checksum;
8534         CFILE *detect = cfopen("ships.tbl", "rb");
8535         // get the long checksum of the file
8536         file_checksum = 0;
8537         cfseek(detect, 0, SEEK_SET);    
8538         cf_chksum_long(detect, &file_checksum);
8539         cfclose(detect);
8540
8541         dc_printf("%d", file_checksum);
8542 }
8543
8544 // ----------------------------------------------------------------
8545 // WEAPONS TBL VERIFICATION STUFF
8546 //
8547
8548 // checksums, just keep a list of all valid ones, if it matches any of them, keep it
8549 #define NUM_WEAPONS_TBL_CHECKSUMS               1
8550 /*
8551 int Game_weapons_tbl_checksums[NUM_WEAPONS_TBL_CHECKSUMS] = {
8552         141718090,                              // US - beta 1
8553         -266420030,                             // demo 1
8554 };
8555 */
8556 int Game_weapons_tbl_checksums[NUM_WEAPONS_TBL_CHECKSUMS] = {
8557 //      399297860,                              // 1.0 FULL     
8558         -553984927                              // 1.2 FULL (german)
8559 };
8560
8561 void verify_weapons_tbl()
8562 {       
8563         /*
8564 #ifdef NDEBUG
8565         Game_weapons_tbl_valid = 1;
8566 #else
8567         */
8568         uint file_checksum;             
8569         int idx;
8570
8571         // detect if the packfile exists
8572         CFILE *detect = cfopen("weapons.tbl", "rb");
8573         Game_weapons_tbl_valid = 0;      
8574         
8575         // not mission-disk
8576         if(!detect){
8577                 Game_weapons_tbl_valid = 0;
8578                 return;
8579         }       
8580
8581         // get the long checksum of the file
8582         file_checksum = 0;
8583         cfseek(detect, 0, SEEK_SET);    
8584         cf_chksum_long(detect, &file_checksum);
8585         cfclose(detect);
8586         detect = NULL;  
8587
8588         // now compare the checksum/filesize against known #'s
8589         for(idx=0; idx<NUM_WEAPONS_TBL_CHECKSUMS; idx++){
8590                 if(Game_weapons_tbl_checksums[idx] == (int)file_checksum){
8591                         Game_weapons_tbl_valid = 1;
8592                         return;
8593                 }
8594         }
8595 // #endif
8596 }
8597
8598 DCF(wepspew, "display the checksum for the current weapons.tbl")
8599 {
8600         uint file_checksum;
8601         CFILE *detect = cfopen("weapons.tbl", "rb");
8602         // get the long checksum of the file
8603         file_checksum = 0;
8604         cfseek(detect, 0, SEEK_SET);    
8605         cf_chksum_long(detect, &file_checksum);
8606         cfclose(detect);
8607
8608         dc_printf("%d", file_checksum);
8609 }
8610
8611 // if the game is running using hacked data
8612 int game_hacked_data()
8613 {
8614         // hacked!
8615         if(!Game_weapons_tbl_valid || !Game_ships_tbl_valid){
8616                 return 1;
8617         }
8618
8619         // not hacked
8620         return 0;
8621 }
8622
8623 void display_title_screen()
8624 {
8625 #if defined(FS2_DEMO) || defined(OEM_BUILD)
8626         ///int title_bitmap;
8627
8628         // load bitmap
8629         int title_bitmap = bm_load(Game_demo_title_screen_fname[gr_screen.res]);
8630         if (title_bitmap == -1) {
8631                 return;
8632         }
8633
8634         // d3d  
8635         if((gr_screen.mode == GR_DIRECT3D) && (Gr_bitmap_poly)){
8636                 extern void d3d_start_frame();
8637                 d3d_start_frame();
8638         }
8639
8640         // set
8641         gr_set_bitmap(title_bitmap);
8642
8643         // draw
8644         gr_bitmap(0, 0);
8645
8646         // d3d  
8647         if((gr_screen.mode == GR_DIRECT3D) && (Gr_bitmap_poly)){
8648                 extern void d3d_stop_frame();
8649                 d3d_stop_frame();
8650         }
8651
8652         // flip
8653         gr_flip();
8654
8655         bm_unload(title_bitmap);
8656 #endif  // FS2_DEMO || OEM_BUILD
8657 }
8658
8659 // return true if the game is running with "low memory", which is less than 48MB
8660 bool game_using_low_mem()
8661 {
8662         if (Use_low_mem == 0) {
8663                 return false;
8664         } else {
8665                 return true;
8666         }
8667 }
8668