util.c 10 KB

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