util.c 12 KB

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