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