util.c 10 KB

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