util.c 13 KB

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