util.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646
  1. /* -*- mode: c; tab-width: 4; c-basic-offset: 3; c-file-style: "linux" -*- */
  2. //
  3. // Copyright (c) 2009, Wei Mingzhi <whistler_wmz@users.sf.net>.
  4. // Portions Copyright (c) 2004, Pierre-Marie Baty.
  5. // Portions Copyright (c) 2009, netwan.
  6. //
  7. // All rights reserved.
  8. //
  9. // This file is part of SDLPAL.
  10. //
  11. // SDLPAL is free software: you can redistribute it and/or modify
  12. // it under the terms of the GNU General Public License as published by
  13. // the Free Software Foundation, either version 3 of the License, or
  14. // (at your option) any later version.
  15. //
  16. // This program is distributed in the hope that it will be useful,
  17. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. // GNU General Public License for more details.
  20. //
  21. // You should have received a copy of the GNU General Public License
  22. // along with this program. If not, see <http://www.gnu.org/licenses/>.
  23. //
  24. #include "util.h"
  25. #include "input.h"
  26. #include "global.h"
  27. #include "palcfg.h"
  28. #include <errno.h>
  29. #include "midi.h"
  30. #if SDL_VERSION_ATLEAST(2, 0, 0)
  31. #include "SDL_video.h"
  32. #include "SDL_messagebox.h"
  33. #endif
  34. void UTIL_MsgBox(char *string){
  35. extern SDL_Window *gpWindow;
  36. char buffer[300];
  37. SDL_MessageBoxButtonData buttons[] = { { 0, 0, "OK" } };
  38. SDL_MessageBoxData mbd = { SDL_MESSAGEBOX_WARNING, gpWindow, "Alert",buffer, 1, buttons, NULL };
  39. int btnid;
  40. sprintf(buffer, "%s\n", string);
  41. SDL_ShowMessageBox(&mbd, &btnid);
  42. }
  43. long
  44. flength(
  45. FILE *fp
  46. )
  47. {
  48. long old_pos = ftell(fp), length;
  49. if (old_pos == -1) return -1;
  50. if (fseek(fp, 0, SEEK_END) == -1) return -1;
  51. length = ftell(fp); fseek(fp, old_pos, SEEK_SET);
  52. return length;
  53. }
  54. void
  55. trim(
  56. char *str
  57. )
  58. /*++
  59. Purpose:
  60. Remove the leading and trailing spaces in a string.
  61. Parameters:
  62. str - the string to proceed.
  63. Return value:
  64. None.
  65. --*/
  66. {
  67. int pos = 0;
  68. char *dest = str;
  69. //
  70. // skip leading blanks
  71. //
  72. while (str[pos] <= ' ' && str[pos] > 0)
  73. pos++;
  74. while (str[pos])
  75. {
  76. *(dest++) = str[pos];
  77. pos++;
  78. }
  79. *(dest--) = '\0'; // store the null
  80. //
  81. // remove trailing blanks
  82. //
  83. while (dest >= str && *dest <= ' ' && *dest > 0)
  84. *(dest--) = '\0';
  85. }
  86. char *
  87. va(
  88. const char *format,
  89. ...
  90. )
  91. /*++
  92. Purpose:
  93. Does a varargs printf into a temp buffer, so we don't need to have
  94. varargs versions of all text functions.
  95. Parameters:
  96. format - the format string.
  97. Return value:
  98. Pointer to the result string.
  99. --*/
  100. {
  101. static char string[256];
  102. va_list argptr;
  103. va_start(argptr, format);
  104. vsnprintf(string, 256, format, argptr);
  105. va_end(argptr);
  106. return string;
  107. }
  108. /*
  109. * RNG code based on RACC by Pierre-Marie Baty.
  110. * http://racc.bots-united.com
  111. *
  112. * Copyright (c) 2004, Pierre-Marie Baty
  113. * All rights reserved.
  114. *
  115. * Redistribution and use in source and binary forms, with or
  116. * without modification, are permitted provided that the following
  117. * conditions are met:
  118. *
  119. * Redistributions of source code must retain the above copyright
  120. * notice, this list of conditions and the following disclaimer.
  121. *
  122. * Redistributions in binary form must reproduce the above copyright
  123. * notice, this list of conditions and the following disclaimer in
  124. * the documentation and/or other materials provided with the
  125. * distribution.
  126. *
  127. * Neither the name of the RACC nor the names of its contributors
  128. * may be used to endorse or promote products derived from this
  129. * software without specific prior written permission.
  130. *
  131. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  132. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  133. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  134. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  135. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  136. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  137. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  138. * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  139. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  140. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  141. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  142. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  143. * POSSIBILITY OF SUCH DAMAGE.
  144. */
  145. //
  146. // Our random number generator's seed.
  147. //
  148. static int glSeed = 0;
  149. static void
  150. lsrand(
  151. unsigned int iInitialSeed
  152. )
  153. /*++
  154. Purpose:
  155. This function initializes the random seed based on the initial seed value passed in the
  156. iInitialSeed parameter.
  157. Parameters:
  158. [IN] iInitialSeed - The initial random seed.
  159. Return value:
  160. None.
  161. --*/
  162. {
  163. //
  164. // fill in the initial seed of the random number generator
  165. //
  166. glSeed = 1664525L * iInitialSeed + 1013904223L;
  167. }
  168. static int
  169. lrand(
  170. void
  171. )
  172. /*++
  173. Purpose:
  174. This function is the equivalent of the rand() standard C library function, except that
  175. whereas rand() works only with short integers (i.e. not above 32767), this function is
  176. able to generate 32-bit random numbers.
  177. Parameters:
  178. None.
  179. Return value:
  180. The generated random number.
  181. --*/
  182. {
  183. if (glSeed == 0) // if the random seed isn't initialized...
  184. lsrand((unsigned int)time(NULL)); // initialize it first
  185. glSeed = 1664525L * glSeed + 1013904223L; // do some twisted math (infinite suite)
  186. return ((glSeed >> 1) + 1073741824L); // and return the result.
  187. }
  188. int
  189. RandomLong(
  190. int from,
  191. int to
  192. )
  193. /*++
  194. Purpose:
  195. This function returns a random integer number between (and including) the starting and
  196. ending values passed by parameters from and to.
  197. Parameters:
  198. from - the starting value.
  199. to - the ending value.
  200. Return value:
  201. The generated random number.
  202. --*/
  203. {
  204. if (to <= from)
  205. return from;
  206. return from + lrand() / (INT_MAX / (to - from + 1));
  207. }
  208. float
  209. RandomFloat(
  210. float from,
  211. float to
  212. )
  213. /*++
  214. Purpose:
  215. This function returns a random floating-point number between (and including) the starting
  216. and ending values passed by parameters from and to.
  217. Parameters:
  218. from - the starting value.
  219. to - the ending value.
  220. Return value:
  221. The generated random number.
  222. --*/
  223. {
  224. if (to <= from)
  225. return from;
  226. return from + (float)lrand() / (INT_MAX / (to - from));
  227. }
  228. void
  229. UTIL_Delay(
  230. unsigned int ms
  231. )
  232. {
  233. unsigned int t = SDL_GetTicks() + ms;
  234. while (PAL_PollEvent(NULL));
  235. while (!SDL_TICKS_PASSED(SDL_GetTicks(), t))
  236. {
  237. SDL_Delay(1);
  238. while (PAL_PollEvent(NULL));
  239. }
  240. #if PAL_HAS_NATIVEMIDI
  241. MIDI_CheckLoop();
  242. #endif
  243. }
  244. void
  245. TerminateOnError(
  246. const char *fmt,
  247. ...
  248. )
  249. // This function terminates the game because of an error and
  250. // prints the message string pointed to by fmt both in the
  251. // console and in a messagebox.
  252. {
  253. va_list argptr;
  254. char string[256];
  255. extern VOID PAL_Shutdown(int);
  256. // concatenate all the arguments in one string
  257. va_start(argptr, fmt);
  258. vsnprintf(string, sizeof(string), fmt, argptr);
  259. va_end(argptr);
  260. fprintf(stderr, "\nFATAL ERROR: %s\n", string);
  261. #if SDL_VERSION_ATLEAST(2, 0, 0)
  262. {
  263. extern SDL_Window *gpWindow;
  264. char buffer[300];
  265. SDL_MessageBoxButtonData buttons[2] = { { 0, 0, "Yes" },{ 0, 1, "No" } };
  266. SDL_MessageBoxData mbd = { SDL_MESSAGEBOX_ERROR, gpWindow, "FATAL ERROR", buffer, 2, buttons, NULL };
  267. int btnid;
  268. sprintf(buffer, "%sLaunch setting dialog on next start?\n", string);
  269. if (SDL_ShowMessageBox(&mbd, &btnid) == 0 && btnid == 0)
  270. {
  271. gConfig.fLaunchSetting = TRUE;
  272. PAL_SaveConfig();
  273. }
  274. PAL_Shutdown(255);
  275. }
  276. #else
  277. PAL_FATAL_OUTPUT(string);
  278. #endif
  279. #ifdef _DEBUG
  280. assert(!"TerminateOnError()"); // allows jumping to debugger
  281. #endif
  282. PAL_Shutdown(255);
  283. }
  284. void *
  285. UTIL_malloc(
  286. size_t buffer_size
  287. )
  288. {
  289. // handy wrapper for operations we always forget, like checking malloc's returned pointer.
  290. void *buffer;
  291. // first off, check if buffer size is valid
  292. if (buffer_size == 0)
  293. TerminateOnError("UTIL_malloc() called with invalid buffer size: %d\n", buffer_size);
  294. buffer = malloc(buffer_size); // allocate real memory space
  295. // last check, check if malloc call succeeded
  296. if (buffer == NULL)
  297. TerminateOnError("UTIL_malloc() failure for %d bytes (out of memory?)\n", buffer_size);
  298. return buffer; // nothing went wrong, so return buffer pointer
  299. }
  300. void *
  301. UTIL_calloc(
  302. size_t n,
  303. size_t size
  304. )
  305. {
  306. // handy wrapper for operations we always forget, like checking calloc's returned pointer.
  307. void *buffer;
  308. // first off, check if buffer size is valid
  309. if (n == 0 || size == 0)
  310. TerminateOnError ("UTIL_calloc() called with invalid parameters\n");
  311. buffer = calloc(n, size); // allocate real memory space
  312. // last check, check if malloc call succeeded
  313. if (buffer == NULL)
  314. TerminateOnError("UTIL_calloc() failure for %d bytes (out of memory?)\n", size * n);
  315. return buffer; // nothing went wrong, so return buffer pointer
  316. }
  317. FILE *
  318. UTIL_OpenRequiredFile(
  319. LPCSTR lpszFileName
  320. )
  321. /*++
  322. Purpose:
  323. Open a required file. If fails, quit the program.
  324. Parameters:
  325. [IN] lpszFileName - file name to open.
  326. Return value:
  327. Pointer to the file.
  328. --*/
  329. {
  330. return UTIL_OpenRequiredFileForMode(lpszFileName, "rb");
  331. }
  332. FILE *
  333. UTIL_OpenRequiredFileForMode(
  334. LPCSTR lpszFileName,
  335. LPCSTR szMode
  336. )
  337. /*++
  338. Purpose:
  339. Open a required file. If fails, quit the program.
  340. Parameters:
  341. [IN] lpszFileName - file name to open.
  342. [IN] szMode - file open mode.
  343. Return value:
  344. Pointer to the file.
  345. --*/
  346. {
  347. FILE *fp = UTIL_OpenFileForMode(lpszFileName, szMode);
  348. if (fp == NULL)
  349. {
  350. TerminateOnError("File open error(%d): %s!\n", errno, lpszFileName);
  351. }
  352. return fp;
  353. }
  354. FILE *
  355. UTIL_OpenFile(
  356. LPCSTR lpszFileName
  357. )
  358. /*++
  359. Purpose:
  360. Open a file. If fails, return NULL.
  361. Parameters:
  362. [IN] lpszFileName - file name to open.
  363. Return value:
  364. Pointer to the file.
  365. --*/
  366. {
  367. return UTIL_OpenFileForMode(lpszFileName, "rb");
  368. }
  369. FILE *
  370. UTIL_OpenFileForMode(
  371. LPCSTR lpszFileName,
  372. LPCSTR szMode
  373. )
  374. /*++
  375. Purpose:
  376. Open a file. If fails, return NULL.
  377. Parameters:
  378. [IN] lpszFileName - file name to open.
  379. [IN] szMode - file open mode.
  380. Return value:
  381. Pointer to the file.
  382. --*/
  383. {
  384. FILE *fp;
  385. if (UTIL_IsAbsolutePath(lpszFileName))
  386. fp = fopen(lpszFileName, szMode);
  387. else
  388. fp = fopen(va("%s%s", gConfig.pszGamePath, lpszFileName), szMode);
  389. #if !defined(PAL_FILESYSTEM_IGNORE_CASE) || !PAL_FILESYSTEM_IGNORE_CASE
  390. if (fp == NULL)
  391. {
  392. //
  393. // try to find the matching file in the directory.
  394. //
  395. struct dirent **list;
  396. int n = scandir(gConfig.pszGamePath, &list, 0, alphasort);
  397. while (n-- > 0)
  398. {
  399. if (!fp && strcasecmp(list[n]->d_name, lpszFileName) == 0)
  400. fp = fopen(va("%s%s", gConfig.pszGamePath, list[n]->d_name), szMode);
  401. free(list[n]);
  402. }
  403. free(list);
  404. }
  405. #endif
  406. return fp;
  407. }
  408. VOID
  409. UTIL_CloseFile(
  410. FILE *fp
  411. )
  412. /*++
  413. Purpose:
  414. Close a file.
  415. Parameters:
  416. [IN] fp - file handle to be closed.
  417. Return value:
  418. None.
  419. --*/
  420. {
  421. if (fp != NULL)
  422. {
  423. fclose(fp);
  424. }
  425. }
  426. #if !defined(PAL_HAS_PLATFORM_SPECIFIC_UTILS)
  427. BOOL
  428. UTIL_GetScreenSize(
  429. DWORD *pdwScreenWidth,
  430. DWORD *pdwScreenHeight
  431. )
  432. {
  433. return FALSE;
  434. }
  435. BOOL
  436. UTIL_IsAbsolutePath(
  437. LPCSTR lpszFileName
  438. )
  439. {
  440. return FALSE;
  441. }
  442. INT
  443. UTIL_Platform_Init(
  444. int argc,
  445. char* argv[]
  446. )
  447. {
  448. gConfig.fLaunchSetting = FALSE;
  449. return 0;
  450. }
  451. VOID
  452. UTIL_Platform_Quit(
  453. VOID
  454. )
  455. {
  456. }
  457. #endif
  458. #ifdef ENABLE_LOG
  459. static FILE *pLogFile = NULL;
  460. FILE *
  461. UTIL_OpenLog(
  462. VOID
  463. )
  464. {
  465. if ((pLogFile = fopen(va("%slog.txt", gConfig.pszSavePath), "a+")) == NULL)
  466. {
  467. return NULL;
  468. }
  469. return pLogFile;
  470. }
  471. VOID
  472. UTIL_CloseLog(
  473. VOID
  474. )
  475. {
  476. if (pLogFile != NULL)
  477. {
  478. fclose(pLogFile);
  479. }
  480. }
  481. VOID
  482. UTIL_WriteLog(
  483. int Priority,
  484. const char *Fmt,
  485. ...
  486. )
  487. {
  488. va_list vaa;
  489. time_t lTime;
  490. struct tm *curTime;
  491. char szDateBuf[260];
  492. time(&lTime);
  493. if ((Priority < LOG_EMERG) || (Priority >= LOG_LAST_PRIORITY))
  494. {
  495. return;
  496. }
  497. curTime = localtime(&lTime);
  498. strftime(szDateBuf, 128, "%Y-%m-%d %H:%M:%S", curTime);
  499. szDateBuf[strlen(szDateBuf) - 1] = '\0'; //remove the
  500. va_start(vaa,Fmt);
  501. fprintf(pLogFile, "[%s]", szDateBuf);
  502. vfprintf(pLogFile, Fmt, vaa);
  503. fprintf(pLogFile, "\n");
  504. fflush(pLogFile);
  505. va_end(vaa);
  506. }
  507. #endif