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