main.cpp 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054
  1. ////////////////////////////////////////////////////////////////////////////////
  2. //
  3. // Copyright 2016 RWS Inc, All Rights Reserved
  4. //
  5. // This program is free software; you can redistribute it and/or modify
  6. // it under the terms of version 2 of the GNU General Public License as published by
  7. // the Free Software Foundation
  8. //
  9. // This program is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU General Public License along
  15. // with this program; if not, write to the Free Software Foundation, Inc.,
  16. // 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
  17. //
  18. // main.cpp
  19. // Project: Nostril (aka Postal)
  20. //
  21. // This module sets up the system and RSPiX.
  22. //
  23. // History:
  24. // 11/19/96 MJR Started.
  25. //
  26. // 02/04/97 JMI Now defaults to using RSP_DOSYSTEM_SLEEP instead of
  27. // RSP_DOSYSTEM_HOGCPU for rspSetDoSystemMode().
  28. //
  29. // 02/19/97 JMI rspInitBlue was being called before
  30. // rspSetWin32Video/AudioType().
  31. //
  32. // 02/21/97 JMI Now gets specific display settings from game settings(INI).
  33. //
  34. // 02/21/97 JMI Now gets audio lag time from INI.
  35. //
  36. // 03/14/97 JMI Now, under Win32, gets value from INI indicating whether to
  37. // manage Windows' GUI components when the screen is resized.
  38. //
  39. // 03/24/97 JMI No longer exits if SetMode() fails. This allows the game
  40. // to be played on systems without sound cards.
  41. //
  42. // 04/14/97 JMI Now uses zeroinit flag to SmartHeap.
  43. //
  44. // 04/16/97 MJR Added more advanced audio init that retries for several
  45. // seconds, and then asks the user whether to abort, retry,
  46. // or ignore.
  47. //
  48. // If video mode can't be set, it now tries to figure out
  49. // the exact reason and reports it to the user.
  50. //
  51. // Fixed a stupid bug that prevented audio from ever working.
  52. //
  53. // 04/17/97 MJR Futher clarified video error messages.
  54. //
  55. // Discovered that the whole suggest-vide-mode thing is
  56. // different than I expected, so I restructured everything.
  57. //
  58. // 05/20/97 JMI Changed the #if block around the SmartHeap specific stuff
  59. // to include only Intel Processor or MAC OS.
  60. //
  61. // 06/03/97 JMI Now, in the case an audio mode cannot be obtained, we
  62. // attempt to use a message specific to the error returned
  63. // by RMix::SetMode() for the message box displayed.
  64. //
  65. // 06/16/97 JMI Now sets do system mode to highest cooperation level in
  66. // debug and lowest coop level in release.
  67. //
  68. // 07/05/97 MJR Added <smrtheap.hpp> if NOT in debug mode so we could
  69. // properly set one of its options. Not sure why this worked
  70. // without <smrtheap.hpp> on the PC, but it didn't on the mac.
  71. //
  72. // 07/06/97 MJR Added call to new rspSetWin32StaticColors() so we'll have
  73. // a common set of colors across platforms.
  74. //
  75. // 07/07/97 MJR Added RSPiX profiling stuff (in disabled form).
  76. //
  77. // 07/13/97 JMI Added MAIN_VANILLA_AUDIO_* macro overrides to MAIN_AUDIO_*
  78. // defaults. These should be used when the INI or default
  79. // audio mode fails.
  80. //
  81. // 07/26/97 JMI We were using the video type as the audio type. Whoopsee.
  82. //
  83. // 09/03/97 PPL Added the pragma to turn off far data for the mempool
  84. // initialization flag so that the smartheap library can reach it.
  85. //
  86. // 09/05/97 BRH Added #if defined(MAC) around pragmas which didn't compile
  87. // on the PC.
  88. //
  89. // 09/09/97 JMI Added check of INI flag in setting of Blue Shield Cursor
  90. // Mode on PC.
  91. //
  92. // 09/25/97 JMI Now, on the PC, when setting the video type, sets the
  93. // rspLock/Unlock behavior to be strict even when in simpler
  94. // modes that don't require that level of behavior (like GDI).
  95. //
  96. // 10/09/97 JMI Added g_pszVideoChangeDepthErrorUnderGDI_s in the event
  97. // the colordepth could not be changed and the user had
  98. // specified to use GDI (i.e., not DirectX).
  99. //
  100. // 10/21/97 JMI Put back the play movie hack. Also, added ability to turn
  101. // it off via the INI.
  102. //
  103. // 10/21/97 JMI Now disables RipCord static logo only if movie successfully
  104. // plays.
  105. //
  106. // 10/24/97 JMI Now switches the video mode back if AVI changes (this seems
  107. // to happen when we're in a DirectX mode and we launch the
  108. // AVI).
  109. //
  110. // 10/31/97 JMI Now uses MixBits entry in INI (in section Audio) to
  111. // determine what bit depth to mix samples with (defaults to
  112. // the device depth).
  113. //
  114. // 01/05/98 JMI Now the MixBits var defaults to 16.
  115. //
  116. // 01/21/98 JMI No longer plays movie regardless of OS or INI setting.
  117. //
  118. ////////////////////////////////////////////////////////////////////////////////
  119. #define MAIN_CPP
  120. #ifdef WIN32
  121. #include <direct.h>
  122. #else
  123. #include <sys/time.h>
  124. #endif
  125. #include "RSPiX.h"
  126. #include "WishPiX/Prefs/prefs.h"
  127. #include "localize.h"
  128. #include "game.h"
  129. #include "main.h"
  130. #include "menus.h"
  131. #include "title.h"
  132. #include "input.h"
  133. //#define RSP_PROFILE_ON
  134. #include "ORANGE/Debug/profile.h"
  135. #if PLATFORM_MACOSX
  136. // This redefines main() to something else, since libSDLmain-osx.a will have
  137. // the actual application entry point...that will setup some Cocoa stuff and
  138. // then call the redefined main() in this file...
  139. #include "SDL.h"
  140. #endif
  141. #if WITH_STEAMWORKS
  142. #ifdef WIN32
  143. #define WIN32_LEAN_AND_MEAN 1
  144. #include <windows.h>
  145. #endif
  146. #include "steam/steam_api.h"
  147. #include "WishPiX/Menu/menu.h"
  148. #endif
  149. ////////////////////////////////////////////////////////////////////////////////
  150. // Macros/types/etc.
  151. ////////////////////////////////////////////////////////////////////////////////
  152. // Amount of time to retry audio before telling the user it's not working
  153. #define AUDIO_RETRY_TIME 5000
  154. ////////////////////////////////////////////////////////////////////////////////
  155. // Variables/data
  156. ////////////////////////////////////////////////////////////////////////////////
  157. int wideScreenWidth;
  158. ////////////////////////////////////////////////////////////////////////////////
  159. // Function prototypes
  160. ////////////////////////////////////////////////////////////////////////////////
  161. ////////////////////////////////////////////////////////////////////////////////
  162. // Set up video for the game.
  163. ////////////////////////////////////////////////////////////////////////////////
  164. static short SetupVideo( // Returns 0 on success.
  165. short sUseCurrentDeviceDimensions, // In: 1 to use current video area.
  166. short sDeviceWidth, // In: Desired video hardware width.
  167. short sDeviceHeight) // In: Desired video hardware height.
  168. {
  169. short sResult = 0;
  170. #ifdef MOBILE
  171. wideScreenWidth = 850;
  172. #elif defined(PANDORA)
  173. wideScreenWidth = 800;
  174. #else
  175. //wideScreenWidth = 640;
  176. // Attempt to grab desired resolution from desktop
  177. short sDepth, sWidth, sHeight;
  178. rspQueryVideoModeReset();
  179. while (!rspQueryVideoMode(&sDepth, &sWidth, &sHeight));
  180. TRACE("rspQueryVideoMode result: %ix%ix%i\n", sWidth, sHeight, sDepth);
  181. // Sanity-check result
  182. if (sHeight > 480 && sWidth > 640)
  183. wideScreenWidth = 480 * sWidth / sHeight;
  184. else // fallback to specified resolution
  185. wideScreenWidth = 480 * sDeviceWidth / sDeviceHeight;
  186. #endif
  187. // If "use current settings" is specified, we get the current device settings
  188. // instead of using those specified in the prefs file.
  189. if (sUseCurrentDeviceDimensions != FALSE)
  190. rspGetVideoMode(NULL, &sDeviceWidth, &sDeviceHeight);
  191. // Try setting video mode using device size specified in prefs file
  192. sResult = rspSetVideoMode(
  193. MAIN_SCREEN_DEPTH,
  194. sDeviceWidth,
  195. sDeviceHeight,
  196. MAIN_WINDOW_WIDTH,
  197. MAIN_WINDOW_HEIGHT,
  198. MAIN_SCREEN_PAGES,
  199. MAIN_SCREEN_SCALING);
  200. if (sResult != 0)
  201. {
  202. // Create description of video mode for error messages
  203. char acVideoMode[100];
  204. sprintf(acVideoMode, "%hd by %hd Pixels", (short)MAIN_WINDOW_WIDTH, (short)MAIN_WINDOW_HEIGHT);
  205. if (MAIN_SCREEN_DEPTH <= 16)
  206. sprintf(&(acVideoMode[strlen(acVideoMode)]), ", %hd Colors", (short)pow(2.0, (double)MAIN_SCREEN_DEPTH));
  207. else if (MAIN_SCREEN_DEPTH == 24)
  208. sprintf(&(acVideoMode[strlen(acVideoMode)]), ", True Color (24 bit)");
  209. else
  210. sprintf(&(acVideoMode[strlen(acVideoMode)]), ", True Color (32 bit)");
  211. if (MAIN_SCREEN_PAGES > 1)
  212. sprintf(&(acVideoMode[strlen(acVideoMode)]), ", %hd Pages", (short)MAIN_SCREEN_PAGES);
  213. // Get current device depth (before we try changing it)
  214. short sCurrentDeviceDepth;
  215. rspGetVideoMode(&sCurrentDeviceDepth);
  216. // Find closest available device size for the settings we need. This function knows about
  217. // ALL available video modes (the same ones you get in Winows' Display Settings Dialog), so
  218. // if it can't find a matching mode, then it isn't available. However, just because it does
  219. // find a match doesn't mean we can set it, because under Win95, changing the color depth
  220. // requires a reboot (unless they have DirectX, a fancy video driver, or the QuickRes utility).
  221. sResult = rspSuggestVideoMode(
  222. MAIN_SCREEN_DEPTH,
  223. MAIN_WINDOW_WIDTH,
  224. MAIN_WINDOW_HEIGHT,
  225. MAIN_SCREEN_PAGES,
  226. MAIN_SCREEN_SCALING,
  227. &sDeviceWidth,
  228. &sDeviceHeight,
  229. NULL);
  230. if (sResult == 0)
  231. {
  232. // Try to set suggested mode
  233. sResult = rspSetVideoMode(
  234. MAIN_SCREEN_DEPTH,
  235. sDeviceWidth,
  236. sDeviceHeight,
  237. MAIN_WINDOW_WIDTH,
  238. MAIN_WINDOW_HEIGHT,
  239. MAIN_SCREEN_PAGES,
  240. MAIN_SCREEN_SCALING);
  241. if (sResult != 0)
  242. {
  243. // If current depth is different from required depth, then that is most likely the
  244. // reason for the failure.
  245. if (sCurrentDeviceDepth != MAIN_SCREEN_DEPTH)
  246. {
  247. rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
  248. g_pszCriticalErrorTitle,
  249. g_pszVideoChangeDepthError,
  250. acVideoMode);
  251. TRACE("SetupVideo(): Error returned by rspSetVideoMode() -- most likely due to attempted change in depth!\n");
  252. }
  253. else
  254. {
  255. TRACE("SetupVideo(): Error returned by rspSetVideoMode()!\n");
  256. rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
  257. g_pszCriticalErrorTitle,
  258. g_pszVideoModeError,
  259. acVideoMode);
  260. }
  261. }
  262. }
  263. else
  264. {
  265. // Since rspSuggestVideoMode() failed, we know that the requested mode is
  266. // not available. Now we just want to figure out the EXACT problem so
  267. // we can report it to the user. Since modes are returned in sorted order
  268. // by increasing depth, height, width, and pages, it makes this a bit easier.
  269. // Look for mode with the requested depth. If there isn't one, depth is the problem.
  270. rspQueryVideoModeReset();
  271. short sDeviceDepth;
  272. short sDevicePages;
  273. do {
  274. sResult = rspQueryVideoMode(
  275. &sDeviceDepth,
  276. &sDeviceWidth,
  277. &sDeviceHeight,
  278. &sDevicePages);
  279. } while ((sResult == 0) && (sDeviceDepth < MAIN_SCREEN_DEPTH));
  280. if ((sResult == 0) && (sDeviceDepth == MAIN_SCREEN_DEPTH))
  281. {
  282. // We got the depth, now find a mode with the requested resolution. If
  283. // there isn't one, then resolution at this depth is the problem.
  284. while ( (sResult == 0) &&
  285. (sDeviceDepth == MAIN_SCREEN_DEPTH) &&
  286. ((sDeviceWidth < MAIN_WINDOW_WIDTH) || (sDeviceHeight < MAIN_WINDOW_HEIGHT)) )
  287. {
  288. sResult = rspQueryVideoMode(
  289. &sDeviceDepth,
  290. &sDeviceWidth,
  291. &sDeviceHeight,
  292. &sDevicePages);
  293. }
  294. if ( (sResult == 0) &&
  295. (sDeviceDepth == MAIN_SCREEN_DEPTH) &&
  296. (sDeviceWidth >= MAIN_WINDOW_WIDTH) &&
  297. (sDeviceHeight >= MAIN_WINDOW_HEIGHT) )
  298. {
  299. // We got the depth and resolution, which only leaves pages or scaling
  300. // as possible problems. RSPiX doesn't support scaling as of 04/16/97
  301. // and probably never will, so if we eliminate that with an ASSERT(),
  302. // then we can assume that the problem is the number of pages.
  303. ASSERT(MAIN_SCREEN_SCALING == 0);
  304. sResult = -1;
  305. TRACE("SetupVideo(): No video modes available at %dx%d, %d-bit, with %d pages!\n",
  306. MAIN_WINDOW_WIDTH , MAIN_WINDOW_HEIGHT, MAIN_SCREEN_DEPTH, MAIN_SCREEN_PAGES);
  307. rspMsgBox(
  308. RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
  309. g_pszCriticalErrorTitle,
  310. g_pszVideoPagesError,
  311. acVideoMode);
  312. }
  313. else
  314. {
  315. sResult = -1;
  316. TRACE("SetupVideo(): No %hd-bit video modes go up to %hdx%hd resolution!\n",
  317. (short)MAIN_SCREEN_DEPTH, (short)MAIN_WINDOW_WIDTH, (short)MAIN_WINDOW_HEIGHT);
  318. rspMsgBox(
  319. RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
  320. g_pszCriticalErrorTitle,
  321. g_pszVideoResolutionError,
  322. acVideoMode);
  323. }
  324. }
  325. else
  326. {
  327. sResult = -1;
  328. TRACE("SetupVideo(): No %hd-bit video modes are available!\n",
  329. (short)MAIN_SCREEN_DEPTH);
  330. rspMsgBox(
  331. RSP_MB_ICN_STOP | RSP_MB_BUT_OK,
  332. g_pszCriticalErrorTitle,
  333. g_pszVideoDepthError,
  334. acVideoMode);
  335. }
  336. }
  337. }
  338. return sResult;
  339. }
  340. ////////////////////////////////////////////////////////////////////////////////
  341. // Allocates a chunk and resizes so that we may be able to have some large
  342. // blocks of contiguous memory.
  343. ////////////////////////////////////////////////////////////////////////////////
  344. static char* CreateChunk( // Returns the memory ptr that will hold the chunk
  345. // in place. Needs to be freed with free() when done
  346. // with the chunk.
  347. long lChunkSize) // In: Size of chunk to create.
  348. {
  349. char* pcOrig = (char*)malloc(lChunkSize);
  350. char* pcReAlloc = (char*)realloc(pcOrig, 1024);
  351. ASSERT(pcOrig == pcReAlloc);
  352. if (pcReAlloc)
  353. {
  354. return pcReAlloc;
  355. }
  356. else
  357. {
  358. return pcOrig;
  359. }
  360. }
  361. static void assert_types_are_sane(void)
  362. {
  363. ASSERT(sizeof (S8) == 1);
  364. ASSERT(sizeof (U8) == 1);
  365. ASSERT(sizeof (S16) == 2);
  366. ASSERT(sizeof (U16) == 2);
  367. ASSERT(sizeof (S32) == 4);
  368. ASSERT(sizeof (U32) == 4);
  369. ASSERT(sizeof (S64) == 8);
  370. ASSERT(sizeof (U64) == 8);
  371. U32 val = 0x02000001;
  372. #if SYS_ENDIAN_BIG
  373. ASSERT(*((U8*) &val) == 0x02);
  374. #else
  375. ASSERT(*((U8*) &val) == 0x01);
  376. #endif
  377. }
  378. ////////////////////////////////////////////////////////////////////////////////
  379. //
  380. // Set up the system environment and if all goes well, start the game.
  381. //
  382. ////////////////////////////////////////////////////////////////////////////////
  383. // Global versions of argc/argv...
  384. int _argc = 0;
  385. char **_argv = NULL;
  386. long playthroughMS = 0;
  387. #if WITH_STEAMWORKS
  388. bool WaitingForInitialSteamStats = true;
  389. bool EnableSteamAchievements = true;
  390. bool EnableSteamCloud = true;
  391. bool StoreSteamStatsPending = false;
  392. bool EarnedSteamAchievements[ACHIEVEMENT_MAX];
  393. uint32 SteamAppID = 0;
  394. static const char *GetAchievementName(const Achievement ach)
  395. {
  396. switch (ach)
  397. {
  398. #define ACH_CASE(name) case ACHIEVEMENT_##name: return #name
  399. ACH_CASE(KILL_FIRST_VICTIM);
  400. ACH_CASE(START_SECOND_LEVEL);
  401. ACH_CASE(DUCK_UNDER_ROCKET);
  402. ACH_CASE(RUN_5_MINUTES);
  403. ACH_CASE(PERFORM_FIRST_EXECUTION);
  404. ACH_CASE(KILL_100);
  405. ACH_CASE(KILL_1000);
  406. ACH_CASE(KILL_10000);
  407. ACH_CASE(COMPLETE_LEVEL_10);
  408. ACH_CASE(COMPLETE_GAME);
  409. ACH_CASE(FIRE_1000000_BULLETS);
  410. ACH_CASE(HIT_100000_TARGETS);
  411. ACH_CASE(TAKE_10000_HITS);
  412. ACH_CASE(KILL_EVERYTHING);
  413. ACH_CASE(KILL_ONLY_HOSTILES);
  414. ACH_CASE(USE_ONLY_M16);
  415. ACH_CASE(USE_EVERY_WEAPON);
  416. ACH_CASE(COMPLETE_LEVEL_ON_LOW_HEALTH);
  417. ACH_CASE(FIGHT_AN_OSTRICH);
  418. ACH_CASE(WATCH_ALL_CREDITS);
  419. ACH_CASE(PLAY_ON_NON_WINDOWS_PLATFORM);
  420. ACH_CASE(FIREBOMB_THE_BAND);
  421. ACH_CASE(ROCKET_TO_THE_FACE);
  422. ACH_CASE(KILL_A_NAKED_PERSON);
  423. ACH_CASE(ENABLE_CHEATS);
  424. ACH_CASE(COMMIT_SUICIDE);
  425. ACH_CASE(TOUCH_SOMEONE_WHILE_BURNING);
  426. ACH_CASE(COMPLETE_GAME_IN_X_MINUTES);
  427. ACH_CASE(COMPLETE_GAME_ON_HARDEST);
  428. #undef ACH_CASE
  429. case ACHIEVEMENT_MAX: break; // not a real achievement, keep compiler happy.
  430. }
  431. return NULL;
  432. }
  433. class SteamworksEvents
  434. {
  435. public:
  436. SteamworksEvents()
  437. : m_CallbackUserStatsReceived(this, &SteamworksEvents::OnUserStatsReceived)
  438. {}
  439. STEAM_CALLBACK(SteamworksEvents, OnUserStatsReceived, UserStatsReceived_t /* *pParam */, m_CallbackUserStatsReceived)
  440. {
  441. //printf("STEAMWORKS: OnUserStatsReceived\n");
  442. if (pParam->m_nGameID != SteamAppID)
  443. return;
  444. else if (pParam->m_eResult != k_EResultOK)
  445. return;
  446. //printf("STEAMWORKS: Accepting these stats.\n");
  447. // Update our stats and achievements.
  448. int32 val;
  449. ISteamUserStats *stats = SteamUserStats();
  450. #define UPDATESTAT(st) { \
  451. stats->GetStat(#st, &val); \
  452. /*printf("STEAMWORKS: Got stat '%s' (+%d)\n", #st, (int) val);*/ \
  453. Stat_##st += (int) val; \
  454. if (Stat_##st < 0) Stat_##st = 0x7FFFFFFF; \
  455. }
  456. UPDATESTAT(BulletsFired);
  457. UPDATESTAT(BulletsHit);
  458. UPDATESTAT(BulletsMissed);
  459. UPDATESTAT(Deaths);
  460. UPDATESTAT(Suicides);
  461. UPDATESTAT(Executions);
  462. UPDATESTAT(HitsTaken);
  463. UPDATESTAT(DamageTaken);
  464. UPDATESTAT(Burns);
  465. UPDATESTAT(TimeRunning);
  466. UPDATESTAT(KilledHostiles);
  467. UPDATESTAT(KilledCivilians);
  468. UPDATESTAT(TotalKilled);
  469. UPDATESTAT(LevelsPlayed);
  470. #undef UPDATESTAT
  471. for (int i = 0; i < ACHIEVEMENT_MAX; i++)
  472. {
  473. const char *name = GetAchievementName((Achievement) i);
  474. if (!name) break; // just in case.
  475. bool unlocked = false;
  476. if (!stats->GetAchievement(name, &unlocked))
  477. unlocked = false;
  478. //printf("STEAMWORKS: Achievement '%s': %slocked\n", name, unlocked ? "un" : "");
  479. EarnedSteamAchievements[i] = unlocked;
  480. }
  481. WaitingForInitialSteamStats = false;
  482. }
  483. };
  484. static bool touchFile(const char *fname, const int64 stamp)
  485. {
  486. #ifdef WIN32
  487. HANDLE hFile = CreateFileA(fname, GENERIC_READ | FILE_WRITE_ATTRIBUTES,
  488. FILE_SHARE_READ, NULL, OPEN_EXISTING, 0, NULL);
  489. if (hFile == INVALID_HANDLE_VALUE)
  490. return false;
  491. ULARGE_INTEGER val;
  492. val.QuadPart = (ULONGLONG) stamp;
  493. val.QuadPart += 11644473600LL; // epoch difference. Ignoring leap seconds, oh well.
  494. val.QuadPart *= 10000000LL; // convert to nanoseconds.
  495. FILETIME ft;
  496. ft.dwLowDateTime = val.LowPart;
  497. ft.dwHighDateTime = val.HighPart;
  498. const BOOL rc = SetFileTime(hFile, NULL, NULL, &ft);
  499. CloseHandle(hFile);
  500. return (rc != 0);
  501. #else
  502. timeval ft[2];
  503. ft[0].tv_sec = ft[1].tv_sec = (time_t) stamp;
  504. ft[0].tv_usec = ft[1].tv_usec = 0;
  505. return (utimes(fname, ft) == 0);
  506. #endif
  507. }
  508. static bool prepareSteamworks()
  509. {
  510. ISteamUtils *utils;
  511. if ((!SteamAPI_Init()) || ((utils = SteamUtils()) == NULL))
  512. {
  513. rspMsgBox(RSP_MB_BUT_OK | RSP_MB_ICN_STOP,
  514. "Error!", "%s", "Can't initialize Steamworks, aborting...");
  515. return false;
  516. }
  517. SteamAppID = utils->GetAppID();
  518. new SteamworksEvents;
  519. ISteamUserStats *stats = SteamUserStats();
  520. if ((!stats) || (rspCommandLine("nosteamachievements")))
  521. EnableSteamAchievements = false;
  522. if (EnableSteamAchievements)
  523. {
  524. bool nukeAchievements = rspCommandLine("nukesteamachievements") != 0;
  525. if (nukeAchievements)
  526. {
  527. if (rspMsgBox(RSP_MB_BUT_OKCANCEL | RSP_MB_ICN_QUERY, "Whoa!", "%s", "Really nuke your Steam Achievements? This can't be undone!") != RSP_MB_RET_OK)
  528. nukeAchievements = false;
  529. }
  530. if (nukeAchievements)
  531. {
  532. stats->ResetAllStats(true);
  533. stats->StoreStats();
  534. }
  535. stats->RequestCurrentStats();
  536. }
  537. ISteamRemoteStorage *cloud = SteamRemoteStorage();
  538. if ((!cloud) || (rspCommandLine("nosteamcloud")))
  539. EnableSteamCloud = false;
  540. if (EnableSteamCloud)
  541. {
  542. bool nukeCloud = rspCommandLine("nukesteamcloud") != 0;
  543. if (nukeCloud)
  544. {
  545. if (rspMsgBox(RSP_MB_BUT_OKCANCEL | RSP_MB_ICN_QUERY, "Whoa!", "%s", "Really nuke the Steam Cloud? This can't be undone!") != RSP_MB_RET_OK)
  546. nukeCloud = false;
  547. }
  548. if (nukeCloud)
  549. {
  550. const int Max = cloud->GetFileCount();
  551. for (int i = 0; i < Max; i++)
  552. {
  553. int32 fsize = 0;
  554. const char *fname = cloud->GetFileNameAndSize(i, &fsize);
  555. if (fname)
  556. cloud->FileDelete(fname);
  557. }
  558. }
  559. // no files in the cloud? Add local ones.
  560. if (cloud->GetFileCount() == 0)
  561. {
  562. const int Max = MAX_SAVE_SLOTS;
  563. for (int i = 0; i < Max; i++)
  564. {
  565. char fname[64];
  566. snprintf(fname, sizeof (fname), "savegame/%d.gme", i);
  567. FILE *io = fopen(FindCorrectFile(fname, "rb"), "rb");
  568. if (io != NULL)
  569. {
  570. char buf[1024];
  571. const size_t br = fread(buf, 1, sizeof (buf), io);
  572. fclose(io);
  573. if (br > 0)
  574. {
  575. snprintf(fname, sizeof (fname), "savegame_%d.gme", i);
  576. cloud->FileWrite(fname, buf, (int32) br);
  577. }
  578. }
  579. }
  580. }
  581. // Copy files from the Cloud back to us.
  582. const int Max = MAX_SAVE_SLOTS;
  583. for (int i = 0; i < Max; i++)
  584. {
  585. char src[64];
  586. snprintf(src, sizeof (src), "savegame_%d.gme", i);
  587. char dst[64];
  588. snprintf(dst, sizeof (dst), "steamcloud/%d.gme", i);
  589. remove(FindCorrectFile(dst, "wb"));
  590. if (!cloud->FileExists(src))
  591. continue;
  592. char buf[1024];
  593. const int32 br = cloud->FileRead(src, buf, (int32) sizeof (buf));
  594. if (br <= 0)
  595. continue;
  596. FILE *io = fopen(FindCorrectFile(dst, "wb"), "wb");
  597. if (!io)
  598. continue;
  599. const size_t bw = fwrite(buf, (size_t) br, 1, io);
  600. fclose(io);
  601. if (bw != 1)
  602. remove(FindCorrectFile(dst, "wb"));
  603. else
  604. {
  605. const int64 stamp = cloud->GetFileTimestamp(src);
  606. if (stamp > 0)
  607. touchFile(FindCorrectFile(dst, "wb"), stamp);
  608. }
  609. }
  610. }
  611. return true; // good to go.
  612. }
  613. void RequestSteamStatsStore()
  614. {
  615. if (EnableSteamAchievements)
  616. StoreSteamStatsPending = true;
  617. }
  618. void UnlockAchievement(const Achievement ach)
  619. {
  620. //if ((ach < 0) || (ach >= ACHIEVEMENT_MAX))
  621. // return;
  622. if (Flag_Achievements & FLAG_USED_CHEATS)
  623. return; // denied.
  624. else if (EarnedSteamAchievements[ach])
  625. return; // already have it.
  626. else if (!EnableSteamAchievements)
  627. return;
  628. else if (GetInputMode() == INPUT_MODE_PLAYBACK)
  629. return; // you have to actually be playing, not a demo run. :)
  630. const char *achstr = GetAchievementName(ach);
  631. if (!achstr)
  632. return;
  633. ISteamUserStats *stats = SteamUserStats();
  634. if (!stats)
  635. return;
  636. //printf("STEAMWORKS: Unlocking achievement '%s'!\n", achstr);
  637. EarnedSteamAchievements[ach] = true;
  638. stats->SetAchievement(achstr);
  639. RequestSteamStatsStore();
  640. }
  641. void RunSteamworksUpkeep()
  642. {
  643. SteamAPI_RunCallbacks();
  644. if ((StoreSteamStatsPending) && (!WaitingForInitialSteamStats))
  645. {
  646. ISteamUserStats *stats = SteamUserStats();
  647. if (stats)
  648. {
  649. //printf("STEAMWORKS: Pushing stats/achievements...\n");
  650. // since we're pushing here anyhow, might as well update counters...
  651. #define SETSTAT(st) { \
  652. /*printf("STEAMWORKS: Storing stat '%s' (%d)\n", #st, Stat_##st);*/ \
  653. stats->SetStat(#st, Stat_##st); \
  654. }
  655. SETSTAT(BulletsFired);
  656. SETSTAT(BulletsHit);
  657. SETSTAT(BulletsMissed);
  658. SETSTAT(Deaths);
  659. SETSTAT(Suicides);
  660. SETSTAT(Executions);
  661. SETSTAT(HitsTaken);
  662. SETSTAT(DamageTaken);
  663. SETSTAT(Burns);
  664. SETSTAT(TimeRunning);
  665. SETSTAT(KilledHostiles);
  666. SETSTAT(KilledCivilians);
  667. SETSTAT(TotalKilled);
  668. SETSTAT(LevelsPlayed);
  669. #undef SETSTAT
  670. if (stats->StoreStats())
  671. StoreSteamStatsPending = false;
  672. }
  673. }
  674. }
  675. #endif
  676. int main(int argc, char **argv)
  677. {
  678. short sResult = 0;
  679. _argc = argc;
  680. _argv = argv;
  681. assert_types_are_sane();
  682. rspPlatformInit();
  683. #if WITH_STEAMWORKS
  684. if (!prepareSteamworks())
  685. return 1;
  686. #endif
  687. //------------------------------------------------------------------------
  688. // Get hardware-related settings from prefs file
  689. //------------------------------------------------------------------------
  690. // Open the preference file. If this file doesn't exist then we can't
  691. // continue (we could use defaults for video, audio, etc., but we can't
  692. // guess where the assets are!) The preference file must be located in
  693. // the same directory as this application, and it is assumed that that
  694. // directory is the current directory. This will be the case unless the
  695. // user does something stupid.
  696. RPrefs prefs;
  697. if (prefs.Open(g_pszPrefFileName, "rt") == 0)
  698. {
  699. // Get video preferences
  700. short sDeviceWidth;
  701. short sDeviceHeight;
  702. short sUseCurrentDeviceDimensions;
  703. prefs.GetVal("Video", "DeviceWidth", MAIN_SCREEN_MIN_WIDTH, &sDeviceWidth);
  704. prefs.GetVal("Video", "DeviceHeight", MAIN_SCREEN_MIN_HEIGHT, &sDeviceHeight);
  705. prefs.GetVal("Video", "UseCurrentDeviceDimensions", 1, &sUseCurrentDeviceDimensions);
  706. // Get audio preferences
  707. short sAudioSamplesPerSec;
  708. short sDeviceBitsPerSample;
  709. short sBufTime;
  710. short sMixBitsPerSample;
  711. prefs.GetVal("Audio", "DeviceRate", MAIN_AUDIO_RATE, &sAudioSamplesPerSec);
  712. prefs.GetVal("Audio", "DeviceBits", MAIN_AUDIO_BITS, &sDeviceBitsPerSample);
  713. prefs.GetVal("Audio", "DeviceBufTime", MAIN_AUDIO_BUFTIME, &sBufTime);
  714. prefs.GetVal("Audio", "MixBits", 16, &sMixBitsPerSample);
  715. // Close preferences file
  716. prefs.Close();
  717. // Make sure no errors occurred
  718. if (prefs.IsError() == 0)
  719. {
  720. //---------------------------------------------------------------------------
  721. // Init blue layer
  722. //---------------------------------------------------------------------------
  723. if (rspInitBlue() == 0)
  724. {
  725. // Turn on profile (if enabled via macro)
  726. rspProfileOn();
  727. // Set profile report file name
  728. rspSetProfileOutput("profile.out");
  729. //------------------------------------------------------------------------
  730. // Set system stuff
  731. //------------------------------------------------------------------------
  732. // Set app name
  733. rspSetApplicationName(g_pszAppName);
  734. #if defined(_DEBUG)
  735. // Set mode to minimum use of CPU
  736. rspSetDoSystemMode(RSP_DOSYSTEM_SLEEP);
  737. #else
  738. // Set mode to maximum use of CPU
  739. rspSetDoSystemMode(RSP_DOSYSTEM_HOGCPU);
  740. #endif
  741. //------------------------------------------------------------------------
  742. // Setup video
  743. //------------------------------------------------------------------------
  744. sResult = SetupVideo( // Returns 0 on success.
  745. sUseCurrentDeviceDimensions, // In: 1 to use current video area.
  746. sDeviceWidth, // In: Desired video hardware width.
  747. sDeviceHeight); // In: Desired video hardware height.
  748. if (sResult == 0)
  749. {
  750. // Set Win32 static colors and lock them.
  751. rspSetWin32StaticColors(1);
  752. //---------------------------------------------------------------
  753. // Setup audio
  754. //---------------------------------------------------------------
  755. // If the INI or default mode fails b/c it is incompatible with the
  756. // hardware, we will try vanilla settings.
  757. bool bSwitchedToVanillaSettings = false;
  758. // A common reason why the audio mode can't be set is that another
  759. // process started a sound that hasn't finished playing by the time
  760. // this app starts. Therefore, it often pays to keep trying for a
  761. // few seconds to give that other sound time to finish. If it still
  762. // doesn't work after a few seconds, we ask the user what to do.
  763. // He can abort (end game), retry (for another few seconds), or ignore
  764. // (play the game without audio).
  765. bool bRetry = true;
  766. while (bRetry)
  767. {
  768. // Keep trying until it works or time runs out, whichever comes first
  769. long lTime = rspGetMilliseconds();
  770. bool bDone = false;
  771. do {
  772. // Try to set mode
  773. sResult = RMix::SetMode(
  774. sAudioSamplesPerSec,
  775. sDeviceBitsPerSample,
  776. MAIN_AUDIO_CHANNELS,
  777. sBufTime,
  778. MAIN_AUDIO_MAXBUFTIME,
  779. sMixBitsPerSample,
  780. sMixBitsPerSample);
  781. switch (sResult)
  782. {
  783. case 0:
  784. // Alrighty.
  785. bDone = true;
  786. break;
  787. case BLU_ERR_DEVICE_IN_USE:
  788. // Try again until timer expires.
  789. if ((rspGetMilliseconds() - lTime) < AUDIO_RETRY_TIME)
  790. {
  791. // Continue.
  792. }
  793. else
  794. {
  795. // Done.
  796. bDone = true;
  797. }
  798. break;
  799. case BLU_ERR_NO_DEVICE:
  800. // Not much we can do about this. Note that we'll still
  801. // need to be able to open the sample files to query info
  802. // about them (even if NO sound). This is handled by game.cpp.
  803. bDone = true;
  804. break;
  805. case BLU_ERR_NOT_SUPPORTED:
  806. // Trying more won't help. Jump out of this loop so the
  807. // user can choose what to do.
  808. bDone = true;
  809. break;
  810. }
  811. } while (bDone == false);
  812. // If it worked, clear the retry flag
  813. if (sResult == 0)
  814. {
  815. bRetry = false;
  816. }
  817. else
  818. {
  819. TRACE("main(): Audio didn't work, using msgbox to find out what to do...\n");
  820. char buf[100];
  821. sprintf(buf, "%.3f kHz, %hd Bit, %s",
  822. (float)sAudioSamplesPerSec/(float)1000,
  823. (short)sDeviceBitsPerSample,
  824. (MAIN_AUDIO_CHANNELS == 1) ? "Mono" : "Stereo");
  825. // Default to generic error.
  826. char* pszMsg;
  827. USHORT usFlags;
  828. // Try to find a better one, though, based on the return value.
  829. switch (sResult)
  830. {
  831. case BLU_ERR_DEVICE_IN_USE:
  832. pszMsg = g_pszAudioModeInUseError_s;
  833. usFlags = RSP_MB_ICN_QUERY | RSP_MB_BUT_ABORTRETRYIGNORE;
  834. break;
  835. case BLU_ERR_NO_DEVICE:
  836. pszMsg = g_pszAudioModeNoDeviceError_s;
  837. usFlags = RSP_MB_ICN_QUERY | RSP_MB_BUT_YESNO;
  838. break;
  839. case BLU_ERR_NOT_SUPPORTED:
  840. // If we haven't already tried vanilla settings . . .
  841. if (bSwitchedToVanillaSettings == false)
  842. {
  843. pszMsg = g_pszAudioModeNotSupportedError_s;
  844. usFlags = RSP_MB_ICN_QUERY | RSP_MB_BUT_ABORTRETRYIGNORE;
  845. // Fall back on our most Vanilla mode.
  846. sAudioSamplesPerSec = MAIN_VANILLA_AUDIO_RATE;
  847. sDeviceBitsPerSample = MAIN_VANILLA_AUDIO_BITS;
  848. // Should we alter sMixBitsPerSample????
  849. // Let's not -- that way they should be able to use the
  850. // assets they originally installed.
  851. // Remember.
  852. bSwitchedToVanillaSettings = true;
  853. }
  854. else
  855. {
  856. pszMsg = g_pszAudioVanillaModeNotSupportedError_s;
  857. usFlags = RSP_MB_ICN_QUERY | RSP_MB_BUT_YESNO;
  858. }
  859. break;
  860. default:
  861. pszMsg = g_pszAudioModeGeneralError_s;
  862. usFlags = RSP_MB_ICN_QUERY | RSP_MB_BUT_ABORTRETRYIGNORE;
  863. break;
  864. }
  865. short sButton = rspMsgBox(
  866. usFlags,
  867. g_pszCriticalErrorTitle,
  868. pszMsg,
  869. buf);
  870. switch (sButton)
  871. {
  872. case RSP_MB_RET_NO:
  873. case RSP_MB_RET_ABORT:
  874. // To abort, just clear the retry flag.
  875. // Keep the error, though.
  876. bRetry = false;
  877. break;
  878. case RSP_MB_RET_RETRY:
  879. // To retry, just clear the error (not really necessary, but seems like a good thing)
  880. sResult = 0;
  881. break;
  882. case RSP_MB_RET_YES:
  883. case RSP_MB_RET_IGNORE:
  884. // To ignore, just clear the error and the retry flag
  885. sResult = 0;
  886. bRetry = false;
  887. break;
  888. }
  889. }
  890. }
  891. if (sResult == 0)
  892. {
  893. //------------------------------------------------------------
  894. // Run the game
  895. //------------------------------------------------------------
  896. // Hide system cursor
  897. rspHideMouseCursor();
  898. // Run the game
  899. TheGame();
  900. // Restore system cursor
  901. rspShowMouseCursor();
  902. // Kill audio
  903. RMix::KillMode();
  904. }
  905. // Kill video
  906. rspKillVideoMode();
  907. }
  908. // Turn off profile (if enabled via macro)
  909. rspProfileOff();
  910. // Kill blue layer
  911. rspKillBlue();
  912. }
  913. else
  914. {
  915. // Can't init blue
  916. TRACE("main(): Error returned by rspInitBlue()!\n");
  917. rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszBadBlueInit);
  918. }
  919. }
  920. else
  921. {
  922. // Error reading preference file
  923. TRACE("main(): Error reading prefs file!\n");
  924. rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszPrefReadError);
  925. }
  926. }
  927. else
  928. {
  929. // Can't open preference file
  930. TRACE("main(): Couldn't open prefs file: %s !\n", g_pszPrefFileName);
  931. rspMsgBox(RSP_MB_ICN_STOP | RSP_MB_BUT_OK, g_pszCriticalErrorTitle, g_pszPrefOpenError);
  932. }
  933. return 0;
  934. }
  935. ////////////////////////////////////////////////////////////////////////////////
  936. // EOF
  937. /////////////////////////////////////////////////////////////////////////////////