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