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