util.c 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  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. #ifdef PAL_HAS_NATIVEMIDI
  27. #include "midi.h"
  28. #endif
  29. #if SDL_VERSION_ATLEAST(2, 0, 0)
  30. #include "SDL_video.h"
  31. #include "SDL_messagebox.h"
  32. #endif
  33. void
  34. trim(
  35. char *str
  36. )
  37. /*++
  38. Purpose:
  39. Remove the leading and trailing spaces in a string.
  40. Parameters:
  41. str - the string to proceed.
  42. Return value:
  43. None.
  44. --*/
  45. {
  46. int pos = 0;
  47. char *dest = str;
  48. //
  49. // skip leading blanks
  50. //
  51. while (str[pos] <= ' ' && str[pos] > 0)
  52. pos++;
  53. while (str[pos])
  54. {
  55. *(dest++) = str[pos];
  56. pos++;
  57. }
  58. *(dest--) = '\0'; // store the null
  59. //
  60. // remove trailing blanks
  61. //
  62. while (dest >= str && *dest <= ' ' && *dest > 0)
  63. *(dest--) = '\0';
  64. }
  65. char *
  66. va(
  67. const char *format,
  68. ...
  69. )
  70. /*++
  71. Purpose:
  72. Does a varargs printf into a temp buffer, so we don't need to have
  73. varargs versions of all text functions.
  74. Parameters:
  75. format - the format string.
  76. Return value:
  77. Pointer to the result string.
  78. --*/
  79. {
  80. static char string[256];
  81. va_list argptr;
  82. va_start(argptr, format);
  83. vsnprintf(string, 256, format, argptr);
  84. va_end(argptr);
  85. return string;
  86. }
  87. /*
  88. * RNG code based on RACC by Pierre-Marie Baty.
  89. * http://racc.bots-united.com
  90. *
  91. * Copyright (c) 2004, Pierre-Marie Baty
  92. * All rights reserved.
  93. *
  94. * Redistribution and use in source and binary forms, with or
  95. * without modification, are permitted provided that the following
  96. * conditions are met:
  97. *
  98. * Redistributions of source code must retain the above copyright
  99. * notice, this list of conditions and the following disclaimer.
  100. *
  101. * Redistributions in binary form must reproduce the above copyright
  102. * notice, this list of conditions and the following disclaimer in
  103. * the documentation and/or other materials provided with the
  104. * distribution.
  105. *
  106. * Neither the name of the RACC nor the names of its contributors
  107. * may be used to endorse or promote products derived from this
  108. * software without specific prior written permission.
  109. *
  110. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND
  111. * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
  112. * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
  113. * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  114. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS
  115. * BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
  116. * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED
  117. * TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  118. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  119. * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  120. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  121. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  122. * POSSIBILITY OF SUCH DAMAGE.
  123. */
  124. //
  125. // Our random number generator's seed.
  126. //
  127. static int glSeed = 0;
  128. static void
  129. lsrand(
  130. unsigned int iInitialSeed
  131. )
  132. /*++
  133. Purpose:
  134. This function initializes the random seed based on the initial seed value passed in the
  135. iInitialSeed parameter.
  136. Parameters:
  137. [IN] iInitialSeed - The initial random seed.
  138. Return value:
  139. None.
  140. --*/
  141. {
  142. //
  143. // fill in the initial seed of the random number generator
  144. //
  145. glSeed = 1664525L * iInitialSeed + 1013904223L;
  146. }
  147. static int
  148. lrand(
  149. void
  150. )
  151. /*++
  152. Purpose:
  153. This function is the equivalent of the rand() standard C library function, except that
  154. whereas rand() works only with short integers (i.e. not above 32767), this function is
  155. able to generate 32-bit random numbers.
  156. Parameters:
  157. None.
  158. Return value:
  159. The generated random number.
  160. --*/
  161. {
  162. if (glSeed == 0) // if the random seed isn't initialized...
  163. lsrand((unsigned int)time(NULL)); // initialize it first
  164. glSeed = 1664525L * glSeed + 1013904223L; // do some twisted math (infinite suite)
  165. return ((glSeed >> 1) + 1073741824L); // and return the result.
  166. }
  167. int
  168. RandomLong(
  169. int from,
  170. int to
  171. )
  172. /*++
  173. Purpose:
  174. This function returns a random integer number between (and including) the starting and
  175. ending values passed by parameters from and to.
  176. Parameters:
  177. from - the starting value.
  178. to - the ending value.
  179. Return value:
  180. The generated random number.
  181. --*/
  182. {
  183. if (to <= from)
  184. return from;
  185. return from + lrand() / (INT_MAX / (to - from + 1));
  186. }
  187. float
  188. RandomFloat(
  189. float from,
  190. float to
  191. )
  192. /*++
  193. Purpose:
  194. This function returns a random floating-point number between (and including) the starting
  195. and ending values passed by parameters from and to.
  196. Parameters:
  197. from - the starting value.
  198. to - the ending value.
  199. Return value:
  200. The generated random number.
  201. --*/
  202. {
  203. if (to <= from)
  204. return from;
  205. return from + (float)lrand() / (INT_MAX / (to - from));
  206. }
  207. void
  208. UTIL_Delay(
  209. unsigned int ms
  210. )
  211. {
  212. unsigned int t = SDL_GetTicks() + ms;
  213. while (PAL_PollEvent(NULL));
  214. while (SDL_GetTicks() < t)
  215. {
  216. SDL_Delay(1);
  217. while (PAL_PollEvent(NULL));
  218. }
  219. #ifdef PAL_HAS_NATIVEMIDI
  220. MIDI_CheckLoop();
  221. #endif
  222. }
  223. void
  224. TerminateOnError(
  225. const char *fmt,
  226. ...
  227. )
  228. // This function terminates the game because of an error and
  229. // prints the message string pointed to by fmt both in the
  230. // console and in a messagebox.
  231. {
  232. va_list argptr;
  233. char string[256];
  234. extern VOID PAL_Shutdown(VOID);
  235. // concatenate all the arguments in one string
  236. va_start(argptr, fmt);
  237. vsnprintf(string, sizeof(string), fmt, argptr);
  238. va_end(argptr);
  239. fprintf(stderr, "\nFATAL ERROR: %s\n", string);
  240. #if SDL_VERSION_ATLEAST(2, 0, 0)
  241. {
  242. extern SDL_Window *gpWindow;
  243. SDL_ShowSimpleMessageBox(0, "FATAL ERROR", string, gpWindow);
  244. }
  245. #else
  246. #ifdef _WIN32
  247. MessageBoxA(0, string, "FATAL ERROR", MB_ICONERROR);
  248. #endif
  249. #ifdef __linux__
  250. system(va("beep; xmessage -center \"FATAL ERROR: %s\"", string));
  251. #endif
  252. #if defined(__SYMBIAN32__)
  253. UTIL_WriteLog(LOG_DEBUG,"[0x%08x][%s][%s] - %s",(long)TerminateOnError,"TerminateOnError",__FILE__, string);
  254. SDL_Delay(3000);
  255. #endif
  256. #endif
  257. #ifdef _DEBUG
  258. assert(!"TerminateOnError()"); // allows jumping to debugger
  259. #endif
  260. PAL_Shutdown();
  261. #if defined (NDS)
  262. while (1);
  263. #else
  264. exit(255);
  265. #endif
  266. }
  267. void *
  268. UTIL_malloc(
  269. size_t buffer_size
  270. )
  271. {
  272. // handy wrapper for operations we always forget, like checking malloc's returned pointer.
  273. void *buffer;
  274. // first off, check if buffer size is valid
  275. if (buffer_size == 0)
  276. TerminateOnError("UTIL_malloc() called with invalid buffer size: %d\n", buffer_size);
  277. buffer = malloc(buffer_size); // allocate real memory space
  278. // last check, check if malloc call succeeded
  279. if (buffer == NULL)
  280. TerminateOnError("UTIL_malloc() failure for %d bytes (out of memory?)\n", buffer_size);
  281. return buffer; // nothing went wrong, so return buffer pointer
  282. }
  283. void *
  284. UTIL_calloc(
  285. size_t n,
  286. size_t size
  287. )
  288. {
  289. // handy wrapper for operations we always forget, like checking calloc's returned pointer.
  290. void *buffer;
  291. // first off, check if buffer size is valid
  292. if (n == 0 || size == 0)
  293. TerminateOnError ("UTIL_calloc() called with invalid parameters\n");
  294. buffer = calloc(n, size); // allocate real memory space
  295. // last check, check if malloc call succeeded
  296. if (buffer == NULL)
  297. TerminateOnError("UTIL_calloc() failure for %d bytes (out of memory?)\n", size * n);
  298. return buffer; // nothing went wrong, so return buffer pointer
  299. }
  300. FILE *
  301. UTIL_OpenRequiredFile(
  302. LPCSTR lpszFileName
  303. )
  304. /*++
  305. Purpose:
  306. Open a required file. If fails, quit the program.
  307. Parameters:
  308. [IN] lpszFileName - file name to open.
  309. Return value:
  310. Pointer to the file.
  311. --*/
  312. {
  313. FILE *fp;
  314. fp = fopen(va("%s%s", PAL_PREFIX, lpszFileName), "rb");
  315. #ifndef _WIN32
  316. if (fp == NULL)
  317. {
  318. //
  319. // try converting the filename to upper-case.
  320. //
  321. char *pBuf = strdup(lpszFileName);
  322. char *p = pBuf;
  323. while (*p)
  324. {
  325. if (*p >= 'a' && *p <= 'z')
  326. {
  327. *p -= 'a' - 'A';
  328. }
  329. p++;
  330. }
  331. fp = fopen(va("%s%s", PAL_PREFIX, pBuf), "rb");
  332. free(pBuf);
  333. }
  334. #endif
  335. if (fp == NULL)
  336. {
  337. TerminateOnError("File not found: %s!\n", lpszFileName);
  338. }
  339. return fp;
  340. }
  341. FILE *
  342. UTIL_OpenFile(
  343. LPCSTR lpszFileName
  344. )
  345. /*++
  346. Purpose:
  347. Open a file. If fails, return NULL.
  348. Parameters:
  349. [IN] lpszFileName - file name to open.
  350. Return value:
  351. Pointer to the file.
  352. --*/
  353. {
  354. FILE *fp;
  355. fp = fopen(va("%s%s", PAL_PREFIX, lpszFileName), "rb");
  356. #ifndef _WIN32
  357. if (fp == NULL)
  358. {
  359. //
  360. // try converting the filename to upper-case.
  361. //
  362. char *pBuf = strdup(lpszFileName);
  363. char *p = pBuf;
  364. while (*p)
  365. {
  366. if (*p >= 'a' && *p <= 'z')
  367. {
  368. *p -= 'a' - 'A';
  369. }
  370. p++;
  371. }
  372. fp = fopen(va("%s%s", PAL_PREFIX, pBuf), "rb");
  373. free(pBuf);
  374. }
  375. #endif
  376. return fp;
  377. }
  378. VOID
  379. UTIL_CloseFile(
  380. FILE *fp
  381. )
  382. /*++
  383. Purpose:
  384. Close a file.
  385. Parameters:
  386. [IN] fp - file handle to be closed.
  387. Return value:
  388. None.
  389. --*/
  390. {
  391. if (fp != NULL)
  392. {
  393. fclose(fp);
  394. }
  395. }
  396. #ifdef ENABLE_LOG
  397. static FILE *pLogFile = NULL;
  398. FILE *
  399. UTIL_OpenLog(
  400. VOID
  401. )
  402. {
  403. if ((pLogFile = fopen(_PATH_LOG, "a+")) == NULL)
  404. {
  405. return NULL;
  406. }
  407. return pLogFile;
  408. }
  409. VOID
  410. UTIL_CloseLog(
  411. VOID
  412. )
  413. {
  414. if (pLogFile != NULL)
  415. {
  416. fclose(pLogFile);
  417. }
  418. }
  419. VOID
  420. UTIL_WriteLog(
  421. int Priority,
  422. const char *Fmt,
  423. ...
  424. )
  425. {
  426. va_list vaa;
  427. time_t lTime;
  428. struct tm *curTime;
  429. char szDateBuf[260];
  430. time(&lTime);
  431. if ((Priority < LOG_EMERG) || (Priority >= LOG_LAST_PRIORITY))
  432. {
  433. return;
  434. }
  435. curTime = localtime(&lTime);
  436. strftime(szDateBuf, 128, "%Y-%m-%d %H:%M:%S", curTime);
  437. szDateBuf[strlen(szDateBuf) - 1] = '\0'; //remove the
  438. va_start(vaa,Fmt);
  439. fprintf(pLogFile, "[%s]", szDateBuf);
  440. vfprintf(pLogFile, Fmt, vaa);
  441. fprintf(pLogFile, "\n");
  442. fflush(pLogFile);
  443. va_end(vaa);
  444. }
  445. #endif