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