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