1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
7 // https://www.artsoft.org/
8 // ----------------------------------------------------------------------------
10 // ============================================================================
14 #include <sys/types.h>
24 #if defined(PLATFORM_UNIX)
26 #include <sys/param.h>
36 // ============================================================================
37 // some generic helper functions
38 // ============================================================================
40 // ----------------------------------------------------------------------------
42 // ----------------------------------------------------------------------------
44 #define DUPLICATE_LOGGING_TO_STDOUT TRUE
47 #if defined(PLATFORM_ANDROID)
48 static int android_log_prio = ANDROID_LOG_INFO;
49 static char *android_log_buffer = NULL;
51 static void append_to_android_log_buffer(char *format, va_list ap)
53 char text_new[MAX_OUTPUT_LINESIZE];
55 // print text to temporary string
56 vsnprintf(text_new, MAX_OUTPUT_LINESIZE, format, ap);
58 if (android_log_buffer == NULL)
60 android_log_buffer = getStringCopy(text_new);
64 char *android_log_buffer_old = android_log_buffer;
66 // append new text to existing text
67 android_log_buffer = getStringCat2(android_log_buffer, text_new);
69 checked_free(android_log_buffer_old);
73 static void vprintf_log_nonewline(char *format, va_list ap)
75 // add log output to buffer until text with newline is printed
76 append_to_android_log_buffer(format, ap);
79 static void vprintf_log(char *format, va_list ap)
81 // add log output to buffer
82 append_to_android_log_buffer(format, ap);
84 // __android_log_vprint(android_log_prio, program.program_title, format, ap);
85 __android_log_write(android_log_prio, program.program_title,
88 checked_free(android_log_buffer);
89 android_log_buffer = NULL;
94 static void vprintf_log_nonewline(char *format, va_list ap)
96 FILE *file = program.log_file;
98 #if DUPLICATE_LOGGING_TO_STDOUT
99 if (file != program.log_file_default)
104 vfprintf(program.log_file_default, format, ap2);
110 vfprintf(file, format, ap);
113 static void vprintf_log(char *format, va_list ap)
115 FILE *file = program.log_file;
116 char *newline = STRING_NEWLINE;
118 #if DUPLICATE_LOGGING_TO_STDOUT
119 if (file != program.log_file_default)
124 vfprintf(program.log_file_default, format, ap2);
125 fprintf(program.log_file_default, "%s", newline);
131 vfprintf(file, format, ap);
132 fprintf(file, "%s", newline);
136 static void printf_log_nonewline(char *format, ...)
140 va_start(ap, format);
141 vprintf_log_nonewline(format, ap);
145 static void printf_log(char *format, ...)
149 va_start(ap, format);
150 vprintf_log(format, ap);
154 static void printf_log_line(char *line_chars, int line_length)
158 for (i = 0; i < line_length; i++)
159 printf_log_nonewline("%s", line_chars);
165 // ----------------------------------------------------------------------------
166 // platform independent wrappers for printf() et al.
167 // ----------------------------------------------------------------------------
169 void fprintf_line(FILE *file, char *line_chars, int line_length)
173 for (i = 0; i < line_length; i++)
174 fprintf(file, "%s", line_chars);
179 void fprintf_line_with_prefix(FILE *file, char *prefix, char *line_chars,
182 fprintf(file, "%s", prefix);
183 fprintf_line(file, line_chars, line_length);
186 void printf_line(char *line_chars, int line_length)
188 fprintf_line(stdout, line_chars, line_length);
191 void printf_line_with_prefix(char *prefix, char *line_chars, int line_length)
193 fprintf_line_with_prefix(stdout, prefix, line_chars, line_length);
196 static void vPrint(char *format, va_list ap)
198 FILE *file = program.log_file;
200 #if DUPLICATE_LOGGING_TO_STDOUT
201 if (file != program.log_file_default)
206 vfprintf(program.log_file_default, format, ap2);
212 vfprintf(file, format, ap);
215 void Print(char *format, ...)
219 va_start(ap, format);
224 void PrintNoLog(char *format, ...)
226 FILE *file = program.log_file_default;
229 va_start(ap, format);
230 vfprintf(file, format, ap);
236 void PrintLine(char *line_chars, int line_length)
240 for (i = 0; i < line_length; i++)
246 void PrintLineWithPrefix(char *prefix, char *line_chars, int line_length)
249 PrintLine(line_chars, line_length);
253 // ----------------------------------------------------------------------------
254 // generic logging and error handling functions
255 // ----------------------------------------------------------------------------
267 static char *log_tokens[] =
277 static void printf_log_prefix(int log_level, char *mode)
279 if (log_level < 0 || log_level > LOG_FATAL)
282 char *log_token = log_tokens[log_level];
284 if (log_level == LOG_DEBUG)
285 printf_log_nonewline("[%s] [%s] ", log_token, mode);
287 printf_log_nonewline("[%s] ", log_token);
290 static void vLog(int log_level, char *mode, char *format, va_list ap)
292 if (log_level < 0 || log_level > LOG_FATAL)
295 if (log_level == LOG_DEBUG)
297 // only show debug messages when in debug mode
301 // if optional debug mode specified, limit debug output accordingly
302 if (options.debug_mode != NULL &&
303 strstr(mode, options.debug_mode) == NULL)
306 else if (log_level == LOG_WARN)
308 // only show warning messages when in verbose mode
309 if (!options.verbose)
313 #if defined(PLATFORM_ANDROID)
314 android_log_prio = (log_level == LOG_DEBUG ? ANDROID_LOG_DEBUG :
315 log_level == LOG_INFO ? ANDROID_LOG_INFO :
316 log_level == LOG_WARN ? ANDROID_LOG_WARN :
317 log_level == LOG_ERROR ? ANDROID_LOG_ERROR :
318 log_level == LOG_FATAL ? ANDROID_LOG_FATAL :
319 ANDROID_LOG_UNKNOWN);
322 static boolean last_line_was_separator = FALSE;
323 char *log_token = log_tokens[log_level];
325 if (strEqual(format, "===") ||
326 strEqual(format, "---"))
328 static char *mode_last = NULL;
329 char line_char[2] = { format[0], '\0' };
330 int line_length = 80 - strlen(log_token) - 3;
332 if (log_level == LOG_DEBUG)
333 line_length -= strlen(mode) + 3;
335 if (last_line_was_separator && strEqual(mode, mode_last))
338 printf_log_prefix(log_level, mode);
339 printf_log_line(line_char, line_length);
341 if (!strEqual(mode, mode_last))
342 setString(&mode_last, mode);
344 last_line_was_separator = TRUE;
349 last_line_was_separator = FALSE;
351 printf_log_prefix(log_level, mode);
353 vprintf_log(format, ap);
356 static void Log(int log_level, char *mode, char *format, ...)
360 va_start(ap, format);
361 vLog(log_level, mode, format, ap);
365 void DebugContinued(char *mode, char *format, ...)
367 static char message[MAX_LINE_LEN] = { 0 };
369 // initialize message (optional)
370 if (strEqual(format, ""))
377 char *message_ptr = message + strlen(message);
378 int size_left = MAX_LINE_LEN - strlen(message);
382 va_start(ap, format);
383 vsnprintf(message_ptr, size_left, format, ap);
387 if (strSuffix(format, "\n"))
389 message[strlen(message) - 1] = '\0';
391 Debug(mode, message);
397 void Debug(char *mode, char *format, ...)
401 va_start(ap, format);
402 vLog(LOG_DEBUG, mode, format, ap);
406 void Info(char *format, ...)
410 va_start(ap, format);
411 vLog(LOG_INFO, NULL, format, ap);
415 void Warn(char *format, ...)
419 va_start(ap, format);
420 vLog(LOG_WARN, NULL, format, ap);
424 void Error(char *format, ...)
428 va_start(ap, format);
429 vLog(LOG_ERROR, NULL, format, ap);
433 void Fail(char *format, ...)
437 va_start(ap, format);
438 vLog(LOG_FATAL, NULL, format, ap);
441 if (!network.is_server_thread)
443 va_start(ap, format);
444 program.exit_message_function(format, ap);
448 Log(LOG_FATAL, NULL, "aborting");
450 // network server thread: normal exit
451 if (network.is_server_thread)
454 // main process: clean up stuff
455 program.exit_function(1);
458 void FailWithHelp(char *format, ...)
462 va_start(ap, format);
463 vLog(LOG_FATAL, NULL, format, ap);
466 Log(LOG_FATAL, NULL, "try option '--help' for more information");
467 Log(LOG_FATAL, NULL, "aborting");
469 // main process: clean up stuff
470 program.exit_function(1);
474 // ----------------------------------------------------------------------------
476 // ----------------------------------------------------------------------------
478 /* int2str() returns a number converted to a string;
479 the used memory is static, but will be overwritten by later calls,
480 so if you want to save the result, copy it to a private string buffer;
481 there can be 10 local calls of int2str() without buffering the result --
482 the 11th call will then destroy the result from the first call and so on. */
484 char *int2str(int number, int size)
486 static char shift_array[10][40];
487 static int shift_counter = 0;
488 char *s = shift_array[shift_counter];
490 shift_counter = (shift_counter + 1) % 10;
497 sprintf(s, " %09d", number);
498 return &s[strlen(s) - size];
502 sprintf(s, "%d", number);
508 // something similar to "int2str()" above, but allocates its own memory
509 // and has a different interface; we cannot use "itoa()", because this
510 // seems to be already defined when cross-compiling to the win32 target
512 char *i_to_a(unsigned int i)
514 static char *a = NULL;
518 if (i > 2147483647) // yes, this is a kludge
521 a = checked_malloc(10 + 1);
529 // calculate base-2 logarithm of argument (rounded down to integer;
530 // this function returns the number of the highest bit set in argument)
532 int log_2(unsigned int x)
538 x -= (1 << e); // for rounding down (rounding up: remove this line)
545 boolean getTokenValueFromString(char *string, char **token, char **value)
547 return getTokenValueFromSetupLine(string, token, value);
551 // ----------------------------------------------------------------------------
553 // ----------------------------------------------------------------------------
555 #define UUID_BYTES 16
556 #define UUID_CHARS (UUID_BYTES * 2)
557 #define UUID_LENGTH (UUID_CHARS + 4)
559 static unsigned int uuid_random_function(int max)
561 return GetBetterRandom(max);
564 char *getUUIDExt(unsigned int (*random_function)(int max))
566 static char uuid[UUID_LENGTH + 1];
567 int data[UUID_BYTES];
571 for (i = 0; i < UUID_BYTES; i++)
572 data[i] = random_function(256);
574 data[6] = 0x40 | (data[6] & 0x0f);
575 data[8] = 0x80 | (data[8] & 0x3f);
577 for (i = 0; i < UUID_BYTES; i++)
579 sprintf(&uuid[count], "%02x", data[i]);
582 if (i == 3 || i == 5 || i == 7 || i == 9)
583 strcat(&uuid[count++], "-");
591 return getUUIDExt(uuid_random_function);
595 // ----------------------------------------------------------------------------
597 // ----------------------------------------------------------------------------
599 // maximal allowed length of a command line option
600 #define MAX_OPTION_LEN 256
602 static unsigned int getCurrentMS(void)
604 return SDL_GetTicks();
607 static unsigned int mainCounter(int mode)
609 static unsigned int base_ms = 0;
610 unsigned int current_ms;
612 // get current system milliseconds
613 current_ms = getCurrentMS();
615 // reset base timestamp in case of counter reset or wrap-around
616 if (mode == INIT_COUNTER || current_ms < base_ms)
617 base_ms = current_ms;
619 // return milliseconds since last counter reset
620 return current_ms - base_ms;
623 void InitCounter(void) // set counter back to zero
625 mainCounter(INIT_COUNTER);
628 unsigned int Counter(void) // get milliseconds since last call of InitCounter()
630 return mainCounter(READ_COUNTER);
633 static void sleep_milliseconds(unsigned int milliseconds_delay)
635 SDL_Delay(milliseconds_delay);
638 void Delay(unsigned int delay) // Sleep specified number of milliseconds
640 sleep_milliseconds(delay);
643 boolean DelayReachedExt2(unsigned int *counter_var, unsigned int delay,
644 unsigned int actual_counter)
646 if (actual_counter >= *counter_var &&
647 actual_counter < *counter_var + delay)
650 *counter_var = actual_counter;
655 boolean DelayReachedExt(DelayCounter *counter, unsigned int actual_counter)
657 return DelayReachedExt2(&counter->count, counter->value, actual_counter);
660 boolean FrameReached(DelayCounter *counter)
662 return DelayReachedExt(counter, FrameCounter);
665 boolean DelayReached(DelayCounter *counter)
667 return DelayReachedExt(counter, Counter());
670 void ResetDelayCounterExt(DelayCounter *counter, unsigned int actual_counter)
672 DelayReachedExt2(&counter->count, 0, actual_counter);
675 void ResetFrameCounter(DelayCounter *counter)
677 ResetDelayCounterExt(counter, FrameCounter);
680 void ResetDelayCounter(DelayCounter *counter)
682 ResetDelayCounterExt(counter, Counter());
685 int WaitUntilDelayReached(DelayCounter *counter)
687 unsigned int *counter_var = &counter->count;
688 unsigned int delay = counter->value;
689 unsigned int actual_counter;
694 actual_counter = Counter();
696 if (actual_counter >= *counter_var &&
697 actual_counter < *counter_var + delay)
698 sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
703 if (*counter_var != 0 &&
705 actual_counter >= *counter_var + delay)
707 int lag = actual_counter - (*counter_var + delay);
708 int delay2 = (delay + 1) / 2;
711 skip_frames = (lag + delay2) / delay;
714 *counter_var = actual_counter;
719 void SkipUntilDelayReached(DelayCounter *counter,
720 int *loop_var, int last_loop_value)
722 int skip_frames = WaitUntilDelayReached(counter);
727 Debug("internal:SkipUntilDelayReached",
728 "%d: %d ms -> SKIP %d FRAME(S) [%d ms]",
729 *loop_var, counter->value,
730 skip_frames, skip_frames * counter->value);
732 Debug("internal:SkipUntilDelayReached",
734 *loop_var, counter->value);
738 if (skip_frames == 0)
741 // when skipping frames, make sure to never skip the last frame, as
742 // this may be needed for animations to reach a defined end state;
743 // furthermore, we assume that this function is called at the end
744 // of a "for" loop, which continues by incrementing the loop variable
745 // by one before checking the loop condition again; therefore we have
746 // to check against the last loop value minus one here
750 if (*loop_var < last_loop_value) // never skip the last frame
752 *loop_var += skip_frames;
754 if (*loop_var > last_loop_value) // never skip the last frame
755 *loop_var = last_loop_value;
760 // ----------------------------------------------------------------------------
761 // random generator functions
762 // ----------------------------------------------------------------------------
764 static unsigned int init_random_number_ext(int nr, int seed)
766 if (seed == NEW_RANDOMIZE)
768 // default random seed
769 seed = (int)time(NULL); // seconds since the epoch
771 #if !defined(PLATFORM_WINDOWS)
772 // add some more randomness
773 struct timeval current_time;
775 gettimeofday(¤t_time, NULL);
777 seed += (int)current_time.tv_usec; // microseconds since the epoch
780 // add some more randomness
781 seed += (int)SDL_GetTicks(); // milliseconds since SDL init
783 // add some more randomness
784 seed += GetSimpleRandom(1000000);
787 srandom_linux_libc(nr, (unsigned int) seed);
789 return (unsigned int) seed;
792 static unsigned int prng_seed_gettimeofday(void)
794 struct timeval current_time;
796 gettimeofday(¤t_time, NULL);
798 prng_seed_bytes(¤t_time, sizeof(current_time));
803 unsigned int init_random_number(int nr, int seed)
805 return (nr == RANDOM_BETTER ? prng_seed_gettimeofday() :
806 init_random_number_ext(nr, seed));
809 static unsigned int get_random_number_ext(int nr)
811 return (nr == RANDOM_BETTER ? prng_get_uint() :
812 random_linux_libc(nr));
815 unsigned int get_random_number(int nr, int max)
817 return (max > 0 ? get_random_number_ext(nr) % max : 0);
821 // ----------------------------------------------------------------------------
822 // system info functions
823 // ----------------------------------------------------------------------------
825 #if !defined(PLATFORM_ANDROID)
826 static char *get_corrected_real_name(char *real_name)
828 char *real_name_new = checked_malloc(MAX_USERNAME_LEN + 1);
829 char *from_ptr = real_name;
830 char *to_ptr = real_name_new;
832 // copy the name string, but not more than MAX_USERNAME_LEN characters
833 while (*from_ptr && (int)(to_ptr - real_name_new) < MAX_USERNAME_LEN - 1)
835 // the name field read from "passwd" file may also contain additional
836 // user information, separated by commas, which will be removed here
837 if (*from_ptr == ',')
840 // the user's real name may contain 'german sharp s' characters,
841 // which have no equivalent in upper case letters (used by our fonts)
842 if (*from_ptr == CHAR_BYTE_SHARP_S)
849 *to_ptr++ = *from_ptr++;
854 return real_name_new;
858 #if defined(PLATFORM_UNIX)
859 static struct passwd *getPasswdEntry(void)
861 #if defined(PLATFORM_EMSCRIPTEN)
862 // currently not fully supported; force fallback to default values
865 return getpwuid(getuid());
869 char *getUnixLoginName(void)
871 struct passwd *pwd = getPasswdEntry();
873 if (pwd != NULL && strlen(pwd->pw_name) != 0)
879 char *getUnixRealName(void)
881 struct passwd *pwd = getPasswdEntry();
883 if (pwd != NULL && strlen(pwd->pw_gecos) != 0)
884 return pwd->pw_gecos;
889 char *getUnixHomeDir(void)
891 struct passwd *pwd = getPasswdEntry();
893 if (pwd != NULL && strlen(pwd->pw_dir) != 0)
900 char *getLoginName(void)
902 static char *login_name = NULL;
904 #if defined(PLATFORM_WINDOWS)
905 if (login_name == NULL)
907 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
909 login_name = checked_malloc(buffer_size);
911 if (GetUserName(login_name, &buffer_size) == 0)
912 strcpy(login_name, ANONYMOUS_NAME);
914 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
915 if (login_name == NULL)
917 char *name = getUnixLoginName();
920 login_name = getStringCopy(name);
922 login_name = ANONYMOUS_NAME;
925 login_name = ANONYMOUS_NAME;
931 char *getRealName(void)
933 static char *real_name = NULL;
935 #if defined(PLATFORM_WINDOWS)
936 if (real_name == NULL)
938 static char buffer[MAX_USERNAME_LEN + 1];
939 unsigned long buffer_size = MAX_USERNAME_LEN + 1;
941 if (GetUserName(buffer, &buffer_size) != 0)
942 real_name = get_corrected_real_name(buffer);
944 real_name = ANONYMOUS_NAME;
946 #elif defined(PLATFORM_UNIX) && !defined(PLATFORM_ANDROID)
947 if (real_name == NULL)
949 char *name = getUnixRealName();
952 real_name = get_corrected_real_name(name);
954 real_name = ANONYMOUS_NAME;
957 real_name = ANONYMOUS_NAME;
963 char *getFixedUserName(char *name)
965 // needed because player name must be a fixed length string
966 char *name_new = checked_malloc(MAX_PLAYER_NAME_LEN + 1);
968 strncpy(name_new, name, MAX_PLAYER_NAME_LEN);
969 name_new[MAX_PLAYER_NAME_LEN] = '\0';
971 if (strlen(name) > MAX_PLAYER_NAME_LEN) // name has been cut
972 if (strchr(name_new, ' '))
973 *strchr(name_new, ' ') = '\0';
978 char *getDefaultUserName(int nr)
980 static char *user_name[MAX_PLAYER_NAMES] = { NULL };
982 nr = MIN(MAX(0, nr), MAX_PLAYER_NAMES - 1);
984 if (user_name[nr] == NULL)
986 user_name[nr] = (nr == 0 ? getLoginName() : EMPTY_PLAYER_NAME);
987 user_name[nr] = getFixedUserName(user_name[nr]);
990 return user_name[nr];
993 char *getTimestampFromEpoch(time_t epoch_seconds)
995 struct tm *now = localtime(&epoch_seconds);
996 static char timestamp[20];
998 sprintf(timestamp, "%04d%02d%02d-%02d%02d%02d",
999 now->tm_year + 1900, now->tm_mon + 1, now->tm_mday,
1000 now->tm_hour, now->tm_min, now->tm_sec);
1005 char *getCurrentTimestamp(void)
1007 return getTimestampFromEpoch(time(NULL));
1010 time_t getFileTimestampEpochSeconds(char *filename)
1012 struct stat file_status;
1014 if (stat(filename, &file_status) != 0) // cannot stat file
1017 return file_status.st_mtime;
1021 // ----------------------------------------------------------------------------
1022 // path manipulation functions
1023 // ----------------------------------------------------------------------------
1025 static char *getLastPathSeparatorPtr(char *filename)
1027 char *last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_UNIX);
1029 if (last_separator == NULL) // also try DOS/Windows variant
1030 last_separator = strrchr(filename, CHAR_PATH_SEPARATOR_DOS);
1032 return last_separator;
1035 char *getBaseNamePtr(char *filename)
1037 char *last_separator = getLastPathSeparatorPtr(filename);
1039 if (last_separator != NULL)
1040 return last_separator + 1; // separator found: strip base path
1042 return filename; // no separator found: filename has no path
1045 char *getBaseName(char *filename)
1047 return getStringCopy(getBaseNamePtr(filename));
1050 char *getBaseNameNoSuffix(char *filename)
1052 char *basename = getStringCopy(getBaseNamePtr(filename));
1054 // remove trailing suffix (separated by dot or hyphen)
1055 if (basename[0] != '.' && basename[0] != '-')
1057 if (strchr(basename, '.') != NULL)
1058 *strchr(basename, '.') = '\0';
1060 if (strchr(basename, '-') != NULL)
1061 *strchr(basename, '-') = '\0';
1067 char *getBasePath(char *filename)
1069 char *basepath = getStringCopy(filename);
1070 char *last_separator = getLastPathSeparatorPtr(basepath);
1072 // if no separator was found, use current directory
1073 if (last_separator == NULL)
1077 return getStringCopy(".");
1080 // separator found: strip basename
1081 *last_separator = '\0';
1087 // ----------------------------------------------------------------------------
1088 // various string functions
1089 // ----------------------------------------------------------------------------
1091 char *getStringCat2WithSeparator(const char *s1,
1095 if (s1 == NULL || s2 == NULL || sep == NULL)
1098 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1101 sprintf(complete_string, "%s%s%s", s1, sep, s2);
1103 return complete_string;
1106 char *getStringCat3WithSeparator(const char *s1,
1111 if (s1 == NULL || s2 == NULL || s3 == NULL || sep == NULL)
1114 char *complete_string = checked_malloc(strlen(s1) + strlen(sep) +
1115 strlen(s2) + strlen(sep) +
1118 sprintf(complete_string, "%s%s%s%s%s", s1, sep, s2, sep, s3);
1120 return complete_string;
1123 char *getStringCat2(const char *s1, const char *s2)
1125 return getStringCat2WithSeparator(s1, s2, "");
1128 char *getStringCat3(const char *s1, const char *s2, const char *s3)
1130 return getStringCat3WithSeparator(s1, s2, s3, "");
1133 char *getPath2(const char *path1, const char *path2)
1135 #if defined(PLATFORM_ANDROID)
1136 // workaround for reading from assets directory -- skip "." subdirs in path
1137 if (strEqual(path1, "."))
1138 return getStringCopy(path2);
1139 else if (strEqual(path2, "."))
1140 return getStringCopy(path1);
1143 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1146 char *getPath3(const char *path1, const char *path2, const char *path3)
1148 #if defined(PLATFORM_ANDROID)
1149 // workaround for reading from assets directory -- skip "." subdirs in path
1150 if (strEqual(path1, "."))
1151 return getStringCat2WithSeparator(path2, path3, STRING_PATH_SEPARATOR);
1152 else if (strEqual(path2, "."))
1153 return getStringCat2WithSeparator(path1, path3, STRING_PATH_SEPARATOR);
1154 else if (strEqual(path3, "."))
1155 return getStringCat2WithSeparator(path1, path2, STRING_PATH_SEPARATOR);
1158 return getStringCat3WithSeparator(path1, path2, path3, STRING_PATH_SEPARATOR);
1161 static char *getPngOrPcxIfNotExists(char *filename)
1163 // switch from PNG to PCX file and vice versa, if file does not exist
1164 // (backwards compatibility with PCX files used in previous versions)
1166 if (!fileExists(filename) && strSuffix(filename, ".png"))
1167 strcpy(&filename[strlen(filename) - 3], "pcx");
1168 else if (!fileExists(filename) && strSuffix(filename, ".pcx"))
1169 strcpy(&filename[strlen(filename) - 3], "png");
1174 char *getImg2(const char *path1, const char *path2)
1176 return getPngOrPcxIfNotExists(getPath2(path1, path2));
1179 char *getImg3(const char *path1, const char *path2, const char *path3)
1181 return getPngOrPcxIfNotExists(getPath3(path1, path2, path3));
1184 char *getStringCopy(const char *s)
1191 s_copy = checked_malloc(strlen(s) + 1);
1197 char *getStringCopyN(const char *s, int n)
1200 int s_len = MAX(0, n);
1205 s_copy = checked_malloc(s_len + 1);
1206 strncpy(s_copy, s, s_len);
1207 s_copy[s_len] = '\0';
1212 char *getStringCopyNStatic(const char *s, int n)
1214 static char *s_copy = NULL;
1216 checked_free(s_copy);
1218 s_copy = getStringCopyN(s, n);
1223 char *getStringToUpper(const char *s)
1225 char *s_copy = checked_malloc(strlen(s) + 1);
1226 char *s_ptr = s_copy;
1229 *s_ptr++ = toupper(*s++);
1235 char *getStringToLower(const char *s)
1237 char *s_copy = checked_malloc(strlen(s) + 1);
1238 char *s_ptr = s_copy;
1241 *s_ptr++ = tolower(*s++);
1247 static char *getStringVPrint(char *format, va_list ap)
1249 char s[MAX_LINE_LEN];
1251 vsnprintf(s, MAX_LINE_LEN, format, ap); // may truncate output string
1253 return getStringCopy(s);
1256 char *getStringPrint(char *format, ...)
1261 va_start(ap, format);
1262 s = getStringVPrint(format, ap);
1268 void setStringPrint(char **s, char *format, ...)
1274 va_start(ap, format);
1275 *s = getStringVPrint(format, ap);
1279 void appendStringPrint(char **s_old, char *format, ...)
1284 va_start(ap, format);
1285 s_new = getStringVPrint(format, ap);
1288 char *s_combined = getStringCat2(*s_old, s_new);
1290 checked_free(*s_old);
1291 checked_free(s_new);
1293 *s_old = s_combined;
1296 void setString(char **old_value, const char *new_value)
1298 checked_free(*old_value);
1300 *old_value = getStringCopy(new_value);
1303 char **getSplitStringArray(const char *s, const char *separators, int max_tokens)
1305 const char *s_ptr, *s_last = s;
1306 byte separator_table[256] = { FALSE };
1308 char **tokens = NULL;
1313 if (separators == NULL)
1317 max_tokens = INT_MAX;
1319 // if string is empty, return empty array
1322 tokens = checked_malloc(sizeof(char *));
1328 // initialize separator table for all characters in separators string
1329 for (s_ptr = separators; *s_ptr != '\0'; s_ptr++)
1330 separator_table[*(byte *)s_ptr] = TRUE;
1332 // count number of tokens in string
1333 for (num_tokens = 1, s_ptr = s; *s_ptr != '\0'; s_ptr++)
1334 if (separator_table[*(byte *)s_ptr] && num_tokens < max_tokens)
1337 // allocate array for determined number of tokens
1338 tokens = checked_malloc((num_tokens + 1) * sizeof(char *));
1340 // copy all but last separated sub-strings to array
1341 for (num_tokens = 0, s_ptr = s; *s_ptr != '\0'; s_ptr++)
1343 if (separator_table[*(byte *)s_ptr] && num_tokens + 1 < max_tokens)
1345 tokens[num_tokens++] = getStringCopyN(s_last, s_ptr - s_last);
1350 // copy last separated sub-string to array
1351 tokens[num_tokens++] = getStringCopyN(s_last, s_ptr - s_last);
1354 tokens[num_tokens] = NULL;
1359 int getStringArrayLength(char **s_array)
1361 int num_strings = 0;
1363 if (s_array == NULL)
1366 while (s_array[num_strings] != NULL)
1372 void freeStringArray(char **s_array)
1376 if (s_array == NULL)
1379 for (i = 0; s_array[i] != NULL; i++)
1380 checked_free(s_array[i]);
1382 checked_free(s_array);
1385 char *getEscapedString(const char *s)
1387 const unsigned char *s_ptr = (unsigned char *)s;
1389 char *s_escaped_ptr;
1394 /* Each source byte needs maximally four target chars (\777) */
1395 s_escaped = checked_malloc(strlen(s) * 4 + 1);
1396 s_escaped_ptr = s_escaped;
1398 while (*s_ptr != '\0')
1403 *s_escaped_ptr++ = '\\';
1404 *s_escaped_ptr++ = 'b';
1408 *s_escaped_ptr++ = '\\';
1409 *s_escaped_ptr++ = 'f';
1413 *s_escaped_ptr++ = '\\';
1414 *s_escaped_ptr++ = 'n';
1418 *s_escaped_ptr++ = '\\';
1419 *s_escaped_ptr++ = 'r';
1423 *s_escaped_ptr++ = '\\';
1424 *s_escaped_ptr++ = 't';
1428 *s_escaped_ptr++ = '\\';
1429 *s_escaped_ptr++ = 'v';
1433 *s_escaped_ptr++ = '\\';
1434 *s_escaped_ptr++ = '\\';
1438 *s_escaped_ptr++ = '\\';
1439 *s_escaped_ptr++ = '"';
1443 if ((*s_ptr < ' ') || (*s_ptr >= 0177))
1445 *s_escaped_ptr++ = '\\';
1446 *s_escaped_ptr++ = '0' + (((*s_ptr) >> 6) & 07);
1447 *s_escaped_ptr++ = '0' + (((*s_ptr) >> 3) & 07);
1448 *s_escaped_ptr++ = '0' + ( (*s_ptr) & 07);
1452 *s_escaped_ptr++ = *s_ptr;
1460 *s_escaped_ptr = '\0';
1465 char *getUnescapedString(const char *s)
1467 const char *s_ptr = s;
1468 const char *octal_ptr;
1470 char *s_unescaped_ptr;
1475 s_unescaped = checked_malloc(strlen(s) + 1);
1476 s_unescaped_ptr = s_unescaped;
1478 while (*s_ptr != '\0')
1487 Warn("getUnescapedString: trailing \\");
1498 *s_unescaped_ptr = 0;
1501 while (s_ptr < octal_ptr + 3 && *s_ptr >= '0' && *s_ptr <= '7')
1503 *s_unescaped_ptr = (*s_unescaped_ptr * 8) + (*s_ptr - '0');
1512 *s_unescaped_ptr++ = '\b';
1516 *s_unescaped_ptr++ = '\f';
1520 *s_unescaped_ptr++ = '\n';
1524 *s_unescaped_ptr++ = '\r';
1528 *s_unescaped_ptr++ = '\t';
1532 *s_unescaped_ptr++ = '\v';
1536 /* also handles \" and \\ */
1537 *s_unescaped_ptr++ = *s_ptr;
1543 *s_unescaped_ptr++ = *s_ptr;
1550 *s_unescaped_ptr = '\0';
1555 char *chugString(char *s)
1562 for (start = (char *)s; *start && isspace(*start); start++)
1565 memmove(s, start, strlen(start) + 1);
1570 char *chompString(char *s)
1575 int len = strlen(s);
1579 if (isspace(s[len]))
1588 char *stripString(char *s)
1590 return chugString(chompString(s));
1593 boolean strEqual(const char *s1, const char *s2)
1595 return (s1 == NULL && s2 == NULL ? TRUE :
1596 s1 == NULL && s2 != NULL ? FALSE :
1597 s1 != NULL && s2 == NULL ? FALSE :
1598 strcmp(s1, s2) == 0);
1601 boolean strEqualN(const char *s1, const char *s2, int n)
1603 return (s1 == NULL && s2 == NULL ? TRUE :
1604 s1 == NULL && s2 != NULL ? FALSE :
1605 s1 != NULL && s2 == NULL ? FALSE :
1606 strncmp(s1, s2, n) == 0);
1609 boolean strEqualCase(const char *s1, const char *s2)
1611 return (s1 == NULL && s2 == NULL ? TRUE :
1612 s1 == NULL && s2 != NULL ? FALSE :
1613 s1 != NULL && s2 == NULL ? FALSE :
1614 strcasecmp(s1, s2) == 0);
1617 boolean strEqualCaseN(const char *s1, const char *s2, int n)
1619 return (s1 == NULL && s2 == NULL ? TRUE :
1620 s1 == NULL && s2 != NULL ? FALSE :
1621 s1 != NULL && s2 == NULL ? FALSE :
1622 strncasecmp(s1, s2, n) == 0);
1625 boolean strPrefix(const char *s, const char *prefix)
1627 return (s == NULL && prefix == NULL ? TRUE :
1628 s == NULL && prefix != NULL ? FALSE :
1629 s != NULL && prefix == NULL ? FALSE :
1630 strncmp(s, prefix, strlen(prefix)) == 0);
1633 boolean strSuffix(const char *s, const char *suffix)
1635 return (s == NULL && suffix == NULL ? TRUE :
1636 s == NULL && suffix != NULL ? FALSE :
1637 s != NULL && suffix == NULL ? FALSE :
1638 strlen(s) < strlen(suffix) ? FALSE :
1639 strcmp(&s[strlen(s) - strlen(suffix)], suffix) == 0);
1642 boolean strPrefixLower(const char *s, const char *prefix)
1644 char *s_lower = getStringToLower(s);
1645 boolean match = strPrefix(s_lower, prefix);
1652 boolean strSuffixLower(const char *s, const char *suffix)
1654 char *s_lower = getStringToLower(s);
1655 boolean match = strSuffix(s_lower, suffix);
1662 boolean isURL(const char *s)
1664 while (*s && *s >= 'a' && *s <= 'z')
1667 return strPrefix(s, "://");
1671 // ----------------------------------------------------------------------------
1672 // command line option handling functions
1673 // ----------------------------------------------------------------------------
1675 void GetOptions(int argc, char *argv[],
1676 void (*print_usage_function)(void),
1677 void (*print_version_function)(void))
1679 char *base_path = getProgramMainDataPath(argv[0], BASE_PATH);
1680 char **argvplus = checked_calloc((argc + 1) * sizeof(char **));
1681 char **options_left = &argvplus[1];
1683 // replace original "argv" with null-terminated array of string pointers
1685 argvplus[argc] = argv[argc];
1687 // initialize global program options
1688 options.server_host = NULL;
1689 options.server_port = 0;
1691 options.base_directory = base_path;
1693 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1694 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1695 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1696 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1697 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1698 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1700 options.execute_command = NULL;
1701 options.tape_log_filename = NULL;
1702 options.special_flags = NULL;
1703 options.debug_mode = NULL;
1704 options.player_name = NULL;
1705 options.identifier = NULL;
1706 options.level_nr = NULL;
1708 options.display_nr = 0;
1710 options.mytapes = FALSE;
1711 options.serveronly = FALSE;
1712 options.network = FALSE;
1713 options.verbose = FALSE;
1714 options.debug = FALSE;
1717 options.verbose = TRUE;
1719 #if !defined(PLATFORM_UNIX)
1720 if (*options_left == NULL) // no options given -- enable verbose mode
1721 options.verbose = TRUE;
1726 #if defined(PLATFORM_ANDROID)
1727 options.debug = TRUE;
1731 while (*options_left)
1733 char option_str[MAX_OPTION_LEN];
1734 char *option = options_left[0];
1735 char *next_option = options_left[1];
1736 char *option_arg = NULL;
1737 int option_len = strlen(option);
1739 if (option_len >= MAX_OPTION_LEN)
1740 FailWithHelp("unrecognized option '%s'", option);
1742 strcpy(option_str, option); // copy argument into buffer
1743 option = option_str;
1745 if (strEqual(option, "--")) // stop scanning arguments
1748 if (strPrefix(option, "--")) // treat '--' like '-'
1751 option_arg = strchr(option, '=');
1752 if (option_arg == NULL) // no '=' in option
1753 option_arg = next_option;
1756 *option_arg++ = '\0'; // cut argument from option
1757 if (*option_arg == '\0') // no argument after '='
1758 FailWithHelp("option '%s' has invalid argument", option_str);
1761 option_len = strlen(option);
1763 if (strEqual(option, "-"))
1765 FailWithHelp("unrecognized option '%s'", option);
1767 else if (strncmp(option, "-help", option_len) == 0)
1769 print_usage_function();
1773 else if (strncmp(option, "-basepath", option_len) == 0)
1775 if (option_arg == NULL)
1776 FailWithHelp("option '%s' requires an argument", option_str);
1778 options.base_directory = base_path = getStringCopy(option_arg);
1779 if (option_arg == next_option)
1782 // adjust paths for sub-directories in base directory accordingly
1783 options.level_directory = getPath2(base_path, LEVELS_DIRECTORY);
1784 options.graphics_directory = getPath2(base_path, GRAPHICS_DIRECTORY);
1785 options.sounds_directory = getPath2(base_path, SOUNDS_DIRECTORY);
1786 options.music_directory = getPath2(base_path, MUSIC_DIRECTORY);
1787 options.docs_directory = getPath2(base_path, DOCS_DIRECTORY);
1788 options.conf_directory = getPath2(base_path, CONF_DIRECTORY);
1790 else if (strncmp(option, "-levels", option_len) == 0)
1792 if (option_arg == NULL)
1793 FailWithHelp("option '%s' requires an argument", option_str);
1795 options.level_directory = getStringCopy(option_arg);
1796 if (option_arg == next_option)
1799 else if (strncmp(option, "-graphics", option_len) == 0)
1801 if (option_arg == NULL)
1802 FailWithHelp("option '%s' requires an argument", option_str);
1804 options.graphics_directory = getStringCopy(option_arg);
1805 if (option_arg == next_option)
1808 else if (strncmp(option, "-sounds", option_len) == 0)
1810 if (option_arg == NULL)
1811 FailWithHelp("option '%s' requires an argument", option_str);
1813 options.sounds_directory = getStringCopy(option_arg);
1814 if (option_arg == next_option)
1817 else if (strncmp(option, "-music", option_len) == 0)
1819 if (option_arg == NULL)
1820 FailWithHelp("option '%s' requires an argument", option_str);
1822 options.music_directory = getStringCopy(option_arg);
1823 if (option_arg == next_option)
1826 else if (strncmp(option, "-mytapes", option_len) == 0)
1828 options.mytapes = TRUE;
1830 else if (strncmp(option, "-network", option_len) == 0)
1832 options.network = TRUE;
1834 else if (strncmp(option, "-serveronly", option_len) == 0)
1836 options.serveronly = TRUE;
1838 else if (strncmp(option, "-debug", option_len) == 0)
1840 options.debug = TRUE;
1842 // optionally, debug output can be limited to a specific debug mode
1843 if (option_arg != next_option)
1844 options.debug_mode = getStringCopy(option_arg);
1846 else if (strncmp(option, "-player-name", option_len) == 0)
1848 if (option_arg == NULL)
1849 FailWithHelp("option '%s' requires an argument", option_str);
1851 options.player_name = getStringCopy(option_arg);
1852 if (option_arg == next_option)
1855 else if (strncmp(option, "-identifier", option_len) == 0)
1857 if (option_arg == NULL)
1858 FailWithHelp("option '%s' requires an argument", option_str);
1860 options.identifier = getStringCopy(option_arg);
1861 if (option_arg == next_option)
1864 else if (strncmp(option, "-level-nr", option_len) == 0)
1866 if (option_arg == NULL)
1867 FailWithHelp("option '%s' requires an argument", option_str);
1869 options.level_nr = getStringCopy(option_arg);
1870 if (option_arg == next_option)
1873 else if (strncmp(option, "-verbose", option_len) == 0)
1875 options.verbose = TRUE;
1877 else if (strncmp(option, "-version", option_len) == 0 ||
1878 strncmp(option, "-V", option_len) == 0)
1880 print_version_function();
1884 else if (strPrefix(option, "-D"))
1886 options.special_flags = getStringCopy(&option[2]);
1888 else if (strncmp(option, "-execute", option_len) == 0)
1890 if (option_arg == NULL)
1891 FailWithHelp("option '%s' requires an argument", option_str);
1893 options.execute_command = getStringCopy(option_arg);
1894 if (option_arg == next_option)
1897 // when doing batch processing, always enable verbose mode (warnings)
1898 options.verbose = TRUE;
1900 else if (strncmp(option, "-tape_logfile", option_len) == 0)
1902 if (option_arg == NULL)
1903 FailWithHelp("option '%s' requires an argument", option_str);
1905 options.tape_log_filename = getStringCopy(option_arg);
1906 if (option_arg == next_option)
1909 else if (strncmp(option, "-display", option_len) == 0)
1911 if (option_arg == NULL)
1912 FailWithHelp("option '%s' requires an argument", option_str);
1914 if (option_arg == next_option)
1917 int display_nr = atoi(option_arg);
1920 // dirty hack: SDL_GetNumVideoDisplays() seems broken on some systems
1921 options.display_nr = display_nr;
1923 options.display_nr =
1924 MAX(0, MIN(display_nr, SDL_GetNumVideoDisplays() - 1));
1926 if (display_nr != options.display_nr)
1927 Warn("invalid display %d -- using display %d",
1928 display_nr, options.display_nr);
1931 #if defined(PLATFORM_MAC)
1932 else if (strPrefix(option, "-psn"))
1934 // ignore process serial number when launched via GUI on Mac OS X
1937 else if (*option == '-')
1939 FailWithHelp("unrecognized option '%s'", option_str);
1941 else if (options.server_host == NULL)
1943 options.server_host = *options_left;
1945 else if (options.server_port == 0)
1947 options.server_port = atoi(*options_left);
1948 if (options.server_port < 1024)
1949 FailWithHelp("bad port number '%d'", options.server_port);
1952 FailWithHelp("too many arguments");
1959 // ----------------------------------------------------------------------------
1960 // checked memory allocation and freeing functions
1961 // ----------------------------------------------------------------------------
1963 void *checked_malloc(unsigned int size)
1970 Fail("cannot allocate %d bytes -- out of memory", size);
1975 void *checked_calloc(unsigned int size)
1979 ptr = calloc(1, size);
1982 Fail("cannot allocate %d bytes -- out of memory", size);
1987 void *checked_realloc(void *ptr, unsigned int size)
1989 ptr = realloc(ptr, size);
1992 Fail("cannot allocate %d bytes -- out of memory", size);
1997 void checked_free(void *ptr)
1999 if (ptr != NULL) // this check should be done by free() anyway
2003 void clear_mem(void *ptr, unsigned int size)
2005 #if defined(PLATFORM_WINDOWS)
2006 // for unknown reason, memset() sometimes crashes when compiled with MinGW
2007 char *cptr = (char *)ptr;
2012 memset(ptr, 0, size);
2016 void *get_memcpy(const void *m, size_t size)
2023 m_copy = checked_malloc(size);
2024 memcpy(m_copy, m, size);
2030 // ----------------------------------------------------------------------------
2031 // various helper functions
2032 // ----------------------------------------------------------------------------
2034 void swap_numbers(int *i1, int *i2)
2042 void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
2054 int get_number_of_bits(int bits)
2057 Counting bits set, Brian Kernighan's way
2059 Brian Kernighan's method goes through as many iterations as there are set
2060 bits. So if we have a 32-bit word with only the high bit set, then it will
2061 only go once through the loop.
2063 Published in 1988, the C Programming Language 2nd Ed. (by Brian W. Kernighan
2064 and Dennis M. Ritchie) mentions this in exercise 2-9.
2065 First published by Peter Wegner in CACM 3 (1960), 322.
2072 bits &= bits - 1; // clear the least significant bit set
2079 /* the "put" variants of the following file access functions check for the file
2080 pointer being != NULL and return the number of bytes they have or would have
2081 written; this allows for chunk writing functions to first determine the size
2082 of the (not yet written) chunk, write the correct chunk size and finally
2083 write the chunk itself */
2085 int getFile8BitInteger(File *file)
2087 return getByteFromFile(file);
2090 int putFile8BitInteger(FILE *file, int value)
2098 int getFile16BitInteger(File *file, int byte_order)
2100 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
2101 return ((getByteFromFile(file) << 8) |
2102 (getByteFromFile(file) << 0));
2103 else // BYTE_ORDER_LITTLE_ENDIAN
2104 return ((getByteFromFile(file) << 0) |
2105 (getByteFromFile(file) << 8));
2108 int putFile16BitInteger(FILE *file, int value, int byte_order)
2112 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
2114 fputc((value >> 8) & 0xff, file);
2115 fputc((value >> 0) & 0xff, file);
2117 else // BYTE_ORDER_LITTLE_ENDIAN
2119 fputc((value >> 0) & 0xff, file);
2120 fputc((value >> 8) & 0xff, file);
2127 int getFile32BitInteger(File *file, int byte_order)
2129 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
2130 return ((getByteFromFile(file) << 24) |
2131 (getByteFromFile(file) << 16) |
2132 (getByteFromFile(file) << 8) |
2133 (getByteFromFile(file) << 0));
2134 else // BYTE_ORDER_LITTLE_ENDIAN
2135 return ((getByteFromFile(file) << 0) |
2136 (getByteFromFile(file) << 8) |
2137 (getByteFromFile(file) << 16) |
2138 (getByteFromFile(file) << 24));
2141 int putFile32BitInteger(FILE *file, int value, int byte_order)
2145 if (byte_order == BYTE_ORDER_BIG_ENDIAN)
2147 fputc((value >> 24) & 0xff, file);
2148 fputc((value >> 16) & 0xff, file);
2149 fputc((value >> 8) & 0xff, file);
2150 fputc((value >> 0) & 0xff, file);
2152 else // BYTE_ORDER_LITTLE_ENDIAN
2154 fputc((value >> 0) & 0xff, file);
2155 fputc((value >> 8) & 0xff, file);
2156 fputc((value >> 16) & 0xff, file);
2157 fputc((value >> 24) & 0xff, file);
2164 boolean getFileChunk(File *file, char *chunk_name, int *chunk_size,
2167 const int chunk_name_length = 4;
2170 if (getStringFromFile(file, chunk_name, chunk_name_length + 1) == NULL)
2173 if (chunk_size != NULL)
2176 *chunk_size = getFile32BitInteger(file, byte_order);
2179 return (checkEndOfFile(file) ? FALSE : TRUE);
2182 int putFileChunk(FILE *file, char *chunk_name, int chunk_size,
2189 fputs(chunk_name, file);
2191 num_bytes += strlen(chunk_name);
2193 if (chunk_size >= 0)
2197 putFile32BitInteger(file, chunk_size, byte_order);
2205 int getFileVersion(File *file)
2207 int version_super = getByteFromFile(file);
2208 int version_major = getByteFromFile(file);
2209 int version_minor = getByteFromFile(file);
2210 int version_patch = getByteFromFile(file);
2212 return VERSION_IDENT(version_super, version_major, version_minor,
2216 int putFileVersion(FILE *file, int version)
2220 int version_super = VERSION_SUPER(version);
2221 int version_major = VERSION_MAJOR(version);
2222 int version_minor = VERSION_MINOR(version);
2223 int version_patch = VERSION_PATCH(version);
2225 fputc(version_super, file);
2226 fputc(version_major, file);
2227 fputc(version_minor, file);
2228 fputc(version_patch, file);
2234 void ReadBytesFromFile(File *file, byte *buffer, unsigned int bytes)
2238 for (i = 0; i < bytes && !checkEndOfFile(file); i++)
2239 buffer[i] = getByteFromFile(file);
2242 void WriteBytesToFile(FILE *file, byte *buffer, unsigned int bytes)
2246 for (i = 0; i < bytes; i++)
2247 fputc(buffer[i], file);
2250 void ReadUnusedBytesFromFile(File *file, unsigned int bytes)
2252 while (bytes-- && !checkEndOfFile(file))
2253 getByteFromFile(file);
2256 void WriteUnusedBytesToFile(FILE *file, unsigned int bytes)
2263 // ----------------------------------------------------------------------------
2264 // functions to convert between ISO-8859-1 and UTF-8
2265 // ----------------------------------------------------------------------------
2267 char *getUTF8FromLatin1(char *latin1)
2269 int max_utf8_size = 2 * strlen(latin1) + 1;
2270 char *utf8 = checked_calloc(max_utf8_size);
2271 unsigned char *src = (unsigned char *)latin1;
2272 unsigned char *dst = (unsigned char *)utf8;
2276 if (*src < 128) // pure 7-bit ASCII
2280 else if (*src >= 160) // non-ASCII characters
2282 *dst++ = 194 + (*src >= 192);
2283 *dst++ = 128 + (*src & 63);
2285 else // undefined in ISO-8859-1
2293 // only use the smallest possible string buffer size
2294 utf8 = checked_realloc(utf8, strlen(utf8) + 1);
2299 char *getLatin1FromUTF8(char *utf8)
2301 int max_latin1_size = strlen(utf8) + 1;
2302 char *latin1 = checked_calloc(max_latin1_size);
2303 unsigned char *src = (unsigned char *)utf8;
2304 unsigned char *dst = (unsigned char *)latin1;
2308 if (*src < 128) // pure 7-bit ASCII
2312 else if (src[0] == 194 &&
2313 src[1] >= 128 && src[1] < 192) // non-ASCII characters
2318 else if (src[0] == 195 &&
2319 src[1] >= 128 && src[1] < 192) // non-ASCII characters
2321 *dst++ = src[1] + 64;
2325 // all other UTF-8 characters are undefined in ISO-8859-1
2327 else if (src[0] >= 192 && src[0] < 224 &&
2328 src[1] >= 128 && src[1] < 192)
2333 else if (src[0] >= 224 && src[0] < 240 &&
2334 src[1] >= 128 && src[1] < 192 &&
2335 src[2] >= 128 && src[2] < 192)
2340 else if (src[0] >= 240 && src[0] < 248 &&
2341 src[1] >= 128 && src[1] < 192 &&
2342 src[2] >= 128 && src[2] < 192 &&
2343 src[3] >= 128 && src[3] < 192)
2348 else if (src[0] >= 248 && src[0] < 252 &&
2349 src[1] >= 128 && src[1] < 192 &&
2350 src[2] >= 128 && src[2] < 192 &&
2351 src[3] >= 128 && src[3] < 192 &&
2352 src[4] >= 128 && src[4] < 192)
2357 else if (src[0] >= 252 && src[0] < 254 &&
2358 src[1] >= 128 && src[1] < 192 &&
2359 src[2] >= 128 && src[2] < 192 &&
2360 src[3] >= 128 && src[3] < 192 &&
2361 src[4] >= 128 && src[4] < 192 &&
2362 src[5] >= 128 && src[5] < 192)
2374 // only use the smallest possible string buffer size
2375 latin1 = checked_realloc(latin1, strlen(latin1) + 1);
2380 int getTextEncoding(char *text)
2382 unsigned char *src = (unsigned char *)text;
2383 int encoding = TEXT_ENCODING_ASCII; // default: assume encoding is ASCII
2388 encoding = TEXT_ENCODING_UTF_8; // non-ASCII character: assume UTF-8
2394 else if (src[0] >= 192 && src[0] < 224 &&
2395 src[1] >= 128 && src[1] < 192)
2399 else if (src[0] >= 224 && src[0] < 240 &&
2400 src[1] >= 128 && src[1] < 192 &&
2401 src[2] >= 128 && src[2] < 192)
2405 else if (src[0] >= 240 && src[0] < 248 &&
2406 src[1] >= 128 && src[1] < 192 &&
2407 src[2] >= 128 && src[2] < 192 &&
2408 src[3] >= 128 && src[3] < 192)
2412 else if (src[0] >= 248 && src[0] < 252 &&
2413 src[1] >= 128 && src[1] < 192 &&
2414 src[2] >= 128 && src[2] < 192 &&
2415 src[3] >= 128 && src[3] < 192 &&
2416 src[4] >= 128 && src[4] < 192)
2420 else if (src[0] >= 252 && src[0] < 254 &&
2421 src[1] >= 128 && src[1] < 192 &&
2422 src[2] >= 128 && src[2] < 192 &&
2423 src[3] >= 128 && src[3] < 192 &&
2424 src[4] >= 128 && src[4] < 192 &&
2425 src[5] >= 128 && src[5] < 192)
2431 return TEXT_ENCODING_UNKNOWN; // non-UTF-8 character: unknown encoding
2439 // ----------------------------------------------------------------------------
2440 // functions for JSON handling
2441 // ----------------------------------------------------------------------------
2443 char *getEscapedJSON(char *s)
2445 int max_json_size = 2 * strlen(s) + 1;
2446 char *json = checked_calloc(max_json_size);
2447 unsigned char *src = (unsigned char *)s;
2448 unsigned char *dst = (unsigned char *)json;
2449 char *escaped[256] =
2462 if (escaped[*src] != NULL)
2464 char *esc = escaped[*src++];
2475 // only use the smallest possible string buffer size
2476 json = checked_realloc(json, strlen(json) + 1);
2482 // ----------------------------------------------------------------------------
2483 // functions to translate key identifiers between different format
2484 // ----------------------------------------------------------------------------
2486 #define TRANSLATE_KEYSYM_TO_KEYNAME 0
2487 #define TRANSLATE_KEYSYM_TO_X11KEYNAME 1
2488 #define TRANSLATE_KEYNAME_TO_KEYSYM 2
2489 #define TRANSLATE_X11KEYNAME_TO_KEYSYM 3
2491 static void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
2500 // return and escape keys
2501 { KSYM_Return, "XK_Return", "return" },
2502 { KSYM_Escape, "XK_Escape", "escape" },
2504 // normal cursor keys
2505 { KSYM_Left, "XK_Left", "cursor left" },
2506 { KSYM_Right, "XK_Right", "cursor right" },
2507 { KSYM_Up, "XK_Up", "cursor up" },
2508 { KSYM_Down, "XK_Down", "cursor down" },
2510 // keypad cursor keys
2512 { KSYM_KP_Left, "XK_KP_Left", "keypad left" },
2513 { KSYM_KP_Right, "XK_KP_Right", "keypad right" },
2514 { KSYM_KP_Up, "XK_KP_Up", "keypad up" },
2515 { KSYM_KP_Down, "XK_KP_Down", "keypad down" },
2518 // other keypad keys
2519 #ifdef KSYM_KP_Enter
2520 { KSYM_KP_Enter, "XK_KP_Enter", "keypad enter" },
2521 { KSYM_KP_Add, "XK_KP_Add", "keypad +" },
2522 { KSYM_KP_Subtract, "XK_KP_Subtract", "keypad -" },
2523 { KSYM_KP_Multiply, "XK_KP_Multiply", "keypad mltply" },
2524 { KSYM_KP_Divide, "XK_KP_Divide", "keypad /" },
2525 { KSYM_KP_Separator,"XK_KP_Separator", "keypad ," },
2529 { KSYM_Shift_L, "XK_Shift_L", "left shift" },
2530 { KSYM_Shift_R, "XK_Shift_R", "right shift" },
2531 { KSYM_Control_L, "XK_Control_L", "left control" },
2532 { KSYM_Control_R, "XK_Control_R", "right control" },
2533 { KSYM_Meta_L, "XK_Meta_L", "left meta" },
2534 { KSYM_Meta_R, "XK_Meta_R", "right meta" },
2535 { KSYM_Alt_L, "XK_Alt_L", "left alt" },
2536 { KSYM_Alt_R, "XK_Alt_R", "right alt" },
2537 { KSYM_Mode_switch, "XK_Mode_switch", "mode switch" }, // Alt-R
2538 { KSYM_Multi_key, "XK_Multi_key", "multi key" }, // Ctrl-R
2540 // some special keys
2541 { KSYM_BackSpace, "XK_BackSpace", "backspace" },
2542 { KSYM_Delete, "XK_Delete", "delete" },
2543 { KSYM_Insert, "XK_Insert", "insert" },
2544 { KSYM_Tab, "XK_Tab", "tab" },
2545 { KSYM_Home, "XK_Home", "home" },
2546 { KSYM_End, "XK_End", "end" },
2547 { KSYM_Page_Up, "XK_Page_Up", "page up" },
2548 { KSYM_Page_Down, "XK_Page_Down", "page down" },
2550 { KSYM_Select, "XK_Select", "select" },
2551 { KSYM_Menu, "XK_Menu", "menu" }, // menu key
2552 { KSYM_Back, "XK_Back", "back" }, // back key
2553 { KSYM_PlayPause, "XK_PlayPause", "play/pause" },
2554 #if defined(PLATFORM_ANDROID)
2555 { KSYM_Rewind, "XK_Rewind", "rewind" },
2556 { KSYM_FastForward, "XK_FastForward", "fast forward" },
2559 // ASCII 0x20 to 0x40 keys (except numbers)
2560 { KSYM_space, "XK_space", "space" },
2561 { KSYM_exclam, "XK_exclam", "!" },
2562 { KSYM_quotedbl, "XK_quotedbl", "\"" },
2563 { KSYM_numbersign, "XK_numbersign", "#" },
2564 { KSYM_dollar, "XK_dollar", "$" },
2565 { KSYM_percent, "XK_percent", "%" },
2566 { KSYM_ampersand, "XK_ampersand", "&" },
2567 { KSYM_apostrophe, "XK_apostrophe", "'" },
2568 { KSYM_parenleft, "XK_parenleft", "(" },
2569 { KSYM_parenright, "XK_parenright", ")" },
2570 { KSYM_asterisk, "XK_asterisk", "*" },
2571 { KSYM_plus, "XK_plus", "+" },
2572 { KSYM_comma, "XK_comma", "," },
2573 { KSYM_minus, "XK_minus", "-" },
2574 { KSYM_period, "XK_period", "." },
2575 { KSYM_slash, "XK_slash", "/" },
2576 { KSYM_colon, "XK_colon", ":" },
2577 { KSYM_semicolon, "XK_semicolon", ";" },
2578 { KSYM_less, "XK_less", "<" },
2579 { KSYM_equal, "XK_equal", "=" },
2580 { KSYM_greater, "XK_greater", ">" },
2581 { KSYM_question, "XK_question", "?" },
2582 { KSYM_at, "XK_at", "@" },
2585 { KSYM_bracketleft, "XK_bracketleft", "[" },
2586 { KSYM_backslash, "XK_backslash", "\\" },
2587 { KSYM_bracketright,"XK_bracketright", "]" },
2588 { KSYM_asciicircum, "XK_asciicircum", "^" },
2589 { KSYM_underscore, "XK_underscore", "_" },
2590 { KSYM_grave, "XK_grave", "grave" },
2591 { KSYM_quoteleft, "XK_quoteleft", "quote left" },
2592 { KSYM_braceleft, "XK_braceleft", "brace left" },
2593 { KSYM_bar, "XK_bar", "bar" },
2594 { KSYM_braceright, "XK_braceright", "brace right" },
2595 { KSYM_asciitilde, "XK_asciitilde", "~" },
2597 // special (non-ASCII) keys
2598 { KSYM_degree, "XK_degree", "degree" },
2599 { KSYM_Adiaeresis, "XK_Adiaeresis", "A umlaut" },
2600 { KSYM_Odiaeresis, "XK_Odiaeresis", "O umlaut" },
2601 { KSYM_Udiaeresis, "XK_Udiaeresis", "U umlaut" },
2602 { KSYM_adiaeresis, "XK_adiaeresis", "a umlaut" },
2603 { KSYM_odiaeresis, "XK_odiaeresis", "o umlaut" },
2604 { KSYM_udiaeresis, "XK_udiaeresis", "u umlaut" },
2605 { KSYM_ssharp, "XK_ssharp", "sharp s" },
2607 // special (non-ASCII) keys (UTF-8, for reverse mapping only)
2608 { KSYM_degree, "XK_degree", "\xc2\xb0" },
2609 { KSYM_Adiaeresis, "XK_Adiaeresis", "\xc3\x84" },
2610 { KSYM_Odiaeresis, "XK_Odiaeresis", "\xc3\x96" },
2611 { KSYM_Udiaeresis, "XK_Udiaeresis", "\xc3\x9c" },
2612 { KSYM_adiaeresis, "XK_adiaeresis", "\xc3\xa4" },
2613 { KSYM_odiaeresis, "XK_odiaeresis", "\xc3\xb6" },
2614 { KSYM_udiaeresis, "XK_udiaeresis", "\xc3\xbc" },
2615 { KSYM_ssharp, "XK_ssharp", "\xc3\x9f" },
2617 // other keys (for reverse mapping only)
2618 { KSYM_space, "XK_space", " " },
2620 // keypad keys are not in numerical order in SDL2
2621 { KSYM_KP_0, "XK_KP_0", "keypad 0" },
2622 { KSYM_KP_1, "XK_KP_1", "keypad 1" },
2623 { KSYM_KP_2, "XK_KP_2", "keypad 2" },
2624 { KSYM_KP_3, "XK_KP_3", "keypad 3" },
2625 { KSYM_KP_4, "XK_KP_4", "keypad 4" },
2626 { KSYM_KP_5, "XK_KP_5", "keypad 5" },
2627 { KSYM_KP_6, "XK_KP_6", "keypad 6" },
2628 { KSYM_KP_7, "XK_KP_7", "keypad 7" },
2629 { KSYM_KP_8, "XK_KP_8", "keypad 8" },
2630 { KSYM_KP_9, "XK_KP_9", "keypad 9" },
2632 // end-of-array identifier
2638 if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
2640 static char name_buffer[30];
2643 if (key >= KSYM_A && key <= KSYM_Z)
2644 sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
2645 else if (key >= KSYM_a && key <= KSYM_z)
2646 sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
2647 else if (key >= KSYM_0 && key <= KSYM_9)
2648 sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
2649 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2650 sprintf(name_buffer, "F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2651 else if (key == KSYM_UNDEFINED)
2652 strcpy(name_buffer, "(undefined)");
2659 if (key == translate_key[i].key)
2661 strcpy(name_buffer, translate_key[i].name);
2665 while (translate_key[++i].name);
2667 if (!translate_key[i].name)
2668 strcpy(name_buffer, "(unknown)");
2671 *name = name_buffer;
2673 else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
2675 static char name_buffer[30];
2678 if (key >= KSYM_A && key <= KSYM_Z)
2679 sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
2680 else if (key >= KSYM_a && key <= KSYM_z)
2681 sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
2682 else if (key >= KSYM_0 && key <= KSYM_9)
2683 sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
2684 else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
2685 sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
2686 else if (key == KSYM_UNDEFINED)
2687 strcpy(name_buffer, "[undefined]");
2694 if (key == translate_key[i].key)
2696 strcpy(name_buffer, translate_key[i].x11name);
2700 while (translate_key[++i].x11name);
2702 if (!translate_key[i].x11name)
2703 sprintf(name_buffer, "0x%04x", (unsigned int)key);
2706 *x11name = name_buffer;
2708 else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
2710 Key key = KSYM_UNDEFINED;
2711 char *name_ptr = *name;
2713 if (strlen(*name) == 1)
2715 char c = name_ptr[0];
2717 if (c >= 'A' && c <= 'Z')
2718 key = KSYM_A + (Key)(c - 'A');
2719 else if (c >= 'a' && c <= 'z')
2720 key = KSYM_a + (Key)(c - 'a');
2721 else if (c >= '0' && c <= '9')
2722 key = KSYM_0 + (Key)(c - '0');
2725 if (key == KSYM_UNDEFINED)
2731 if (strEqual(translate_key[i].name, *name))
2733 key = translate_key[i].key;
2737 while (translate_key[++i].x11name);
2740 if (key == KSYM_UNDEFINED)
2741 Warn("getKeyFromKeyName(): not completely implemented");
2745 else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
2747 Key key = KSYM_UNDEFINED;
2748 char *name_ptr = *x11name;
2750 if (strPrefix(name_ptr, "XK_") && strlen(name_ptr) == 4)
2752 char c = name_ptr[3];
2754 if (c >= 'A' && c <= 'Z')
2755 key = KSYM_A + (Key)(c - 'A');
2756 else if (c >= 'a' && c <= 'z')
2757 key = KSYM_a + (Key)(c - 'a');
2758 else if (c >= '0' && c <= '9')
2759 key = KSYM_0 + (Key)(c - '0');
2761 else if (strPrefix(name_ptr, "XK_F") && strlen(name_ptr) <= 6)
2763 char c1 = name_ptr[4];
2764 char c2 = name_ptr[5];
2767 if ((c1 >= '0' && c1 <= '9') &&
2768 ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
2769 d = atoi(&name_ptr[4]);
2771 if (d >= 1 && d <= KSYM_NUM_FKEYS)
2772 key = KSYM_F1 + (Key)(d - 1);
2774 else if (strPrefix(name_ptr, "XK_"))
2780 if (strEqual(name_ptr, translate_key[i].x11name))
2782 key = translate_key[i].key;
2786 while (translate_key[++i].x11name);
2788 else if (strPrefix(name_ptr, "0x"))
2790 unsigned int value = 0;
2796 char c = *name_ptr++;
2799 if (c >= '0' && c <= '9')
2801 else if (c >= 'a' && c <= 'f')
2802 d = (int)(c - 'a' + 10);
2803 else if (c >= 'A' && c <= 'F')
2804 d = (int)(c - 'A' + 10);
2812 value = value * 16 + d;
2823 char *getKeyNameFromKey(Key key)
2827 translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
2831 char *getX11KeyNameFromKey(Key key)
2835 translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
2839 Key getKeyFromKeyName(char *name)
2843 translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
2847 Key getKeyFromX11KeyName(char *x11name)
2851 translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
2855 char getCharFromKey(Key key)
2861 } translate_key_char[] =
2863 // special (non-ASCII) keys (ISO-8859-1)
2864 { KSYM_degree, CHAR_BYTE_DEGREE },
2865 { KSYM_Adiaeresis, CHAR_BYTE_UMLAUT_A },
2866 { KSYM_Odiaeresis, CHAR_BYTE_UMLAUT_O },
2867 { KSYM_Udiaeresis, CHAR_BYTE_UMLAUT_U },
2868 { KSYM_adiaeresis, CHAR_BYTE_UMLAUT_a },
2869 { KSYM_odiaeresis, CHAR_BYTE_UMLAUT_o },
2870 { KSYM_udiaeresis, CHAR_BYTE_UMLAUT_u },
2871 { KSYM_ssharp, CHAR_BYTE_SHARP_S },
2873 // end-of-array identifier
2877 char *keyname = getKeyNameFromKey(key);
2880 if (strlen(keyname) == 1)
2882 else if (strEqual(keyname, "space"))
2890 if (key == translate_key_char[i].key)
2892 c = translate_key_char[i].key_char;
2897 while (translate_key_char[++i].key_char);
2903 char getValidConfigValueChar(char c)
2905 if (c == '#' || // used to mark comments
2906 c == '\\') // used to mark continued lines
2913 // ----------------------------------------------------------------------------
2914 // functions to translate string identifiers to integer or boolean value
2915 // ----------------------------------------------------------------------------
2917 int get_integer_from_string(char *s)
2919 // check for the most common case first
2920 if (s[0] >= '0' && s[0] <= '9')
2923 char *s_lower = getStringToLower(s);
2926 if (strEqual(s_lower, "false") ||
2927 strEqual(s_lower, "no") ||
2928 strEqual(s_lower, "off"))
2930 else if (strEqual(s_lower, "true") ||
2931 strEqual(s_lower, "yes") ||
2932 strEqual(s_lower, "on"))
2942 boolean get_boolean_from_string(char *s)
2944 char *s_lower = getStringToLower(s);
2945 boolean result = FALSE;
2947 if (strEqual(s_lower, "true") ||
2948 strEqual(s_lower, "yes") ||
2949 strEqual(s_lower, "on") ||
2950 get_integer_from_string(s) == 1)
2958 int get_switch3_from_string(char *s)
2960 char *s_lower = getStringToLower(s);
2963 if (strEqual(s_lower, "true") ||
2964 strEqual(s_lower, "yes") ||
2965 strEqual(s_lower, "on") ||
2966 get_integer_from_string(s) == 1)
2968 else if (strEqual(s_lower, "auto"))
2976 int get_player_nr_from_string(char *s)
2978 static char *player_text[] =
2988 char *s_lower = getStringToLower(s);
2992 for (i = 0; player_text[i] != NULL; i++)
2993 if (strEqual(s_lower, player_text[i]))
3002 // ----------------------------------------------------------------------------
3003 // functions for generic lists
3004 // ----------------------------------------------------------------------------
3006 ListNode *newListNode(void)
3008 return checked_calloc(sizeof(ListNode));
3011 void addNodeToList(ListNode **node_first, char *key, void *content)
3013 ListNode *node_new = newListNode();
3015 node_new->key = getStringCopy(key);
3016 node_new->content = content;
3017 node_new->next = *node_first;
3020 (*node_first)->prev = node_new;
3022 *node_first = node_new;
3025 void deleteNodeFromList(ListNode **node_first, char *key,
3026 void (*destructor_function)(void *))
3028 if (node_first == NULL || *node_first == NULL)
3031 if (strEqual((*node_first)->key, key))
3033 // after first recursion, (*node_first)->prev->next == *node_first,
3034 // so *node_first would be overwritten with (*node_first)->next
3035 // => use a copy of *node_first (and later of (*node_first)->next)
3036 ListNode *node = *node_first;
3037 ListNode *node_next = node->next;
3039 checked_free(node->key);
3041 if (destructor_function)
3042 destructor_function(node->content);
3045 node->prev->next = node->next;
3048 node->next->prev = node->prev;
3052 // after removing node, set list pointer to next valid list node
3053 // (this is important if the first node of the list was deleted)
3054 *node_first = node_next;
3058 deleteNodeFromList(&(*node_first)->next, key, destructor_function);
3062 ListNode *getNodeFromKey(ListNode *node_first, char *key)
3064 if (node_first == NULL)
3067 if (strEqual(node_first->key, key))
3070 return getNodeFromKey(node_first->next, key);
3073 int getNumNodes(ListNode *node_first)
3075 return (node_first ? 1 + getNumNodes(node_first->next) : 0);
3079 static void dumpList(ListNode *node_first)
3081 ListNode *node = node_first;
3085 Debug("internal:dumpList", "['%s' (%d)]", node->key,
3086 ((struct ListNodeInfo *)node->content)->num_references);
3090 Debug("internal:dumpList", "[%d nodes]", getNumNodes(node_first));
3095 // ----------------------------------------------------------------------------
3096 // functions for file handling
3097 // ----------------------------------------------------------------------------
3099 #define MAX_BUFFER_SIZE 4096
3101 File *openFile(const char *filename, const char *mode)
3103 File *file = checked_calloc(sizeof(File));
3105 file->file = fopen(filename, mode);
3107 if (file->file != NULL)
3109 file->filename = getStringCopy(filename);
3114 #if defined(PLATFORM_ANDROID)
3115 file->asset_file = SDL_RWFromFile(filename, mode);
3117 if (file->asset_file != NULL)
3119 file->file_is_asset = TRUE;
3120 file->filename = getStringCopy(filename);
3131 int closeFile(File *file)
3138 #if defined(PLATFORM_ANDROID)
3139 if (file->asset_file)
3140 result = SDL_RWclose(file->asset_file);
3144 result = fclose(file->file);
3146 checked_free(file->filename);
3152 int checkEndOfFile(File *file)
3154 #if defined(PLATFORM_ANDROID)
3155 if (file->file_is_asset)
3156 return file->end_of_file;
3159 return feof(file->file);
3162 size_t readFile(File *file, void *buffer, size_t item_size, size_t num_items)
3164 #if defined(PLATFORM_ANDROID)
3165 if (file->file_is_asset)
3167 if (file->end_of_file)
3170 size_t num_items_read =
3171 SDL_RWread(file->asset_file, buffer, item_size, num_items);
3173 if (num_items_read < num_items)
3174 file->end_of_file = TRUE;
3176 return num_items_read;
3180 return fread(buffer, item_size, num_items, file->file);
3183 size_t writeFile(File *file, void *buffer, size_t item_size, size_t num_items)
3185 return fwrite(buffer, item_size, num_items, file->file);
3188 int seekFile(File *file, long offset, int whence)
3190 #if defined(PLATFORM_ANDROID)
3191 if (file->file_is_asset)
3193 int sdl_whence = (whence == SEEK_SET ? RW_SEEK_SET :
3194 whence == SEEK_CUR ? RW_SEEK_CUR :
3195 whence == SEEK_END ? RW_SEEK_END : 0);
3197 return (SDL_RWseek(file->asset_file, offset, sdl_whence) == -1 ? -1 : 0);
3201 return fseek(file->file, offset, whence);
3204 int getByteFromFile(File *file)
3206 #if defined(PLATFORM_ANDROID)
3207 if (file->file_is_asset)
3209 if (file->end_of_file)
3213 size_t num_bytes_read = SDL_RWread(file->asset_file, &c, 1, 1);
3215 if (num_bytes_read < 1)
3216 file->end_of_file = TRUE;
3218 return (file->end_of_file ? EOF : (int)c);
3222 return fgetc(file->file);
3225 char *getStringFromFile(File *file, char *line, int size)
3227 #if defined(PLATFORM_ANDROID)
3228 if (file->file_is_asset)
3230 if (file->end_of_file)
3233 char *line_ptr = line;
3234 int num_bytes_read = 0;
3236 while (num_bytes_read < size - 1 &&
3237 SDL_RWread(file->asset_file, line_ptr, 1, 1) == 1 &&
3238 *line_ptr++ != '\n')
3243 if (strlen(line) == 0)
3245 file->end_of_file = TRUE;
3254 return fgets(line, size, file->file);
3257 int copyFile(const char *filename_from, const char *filename_to)
3259 File *file_from, *file_to;
3261 if ((file_from = openFile(filename_from, MODE_READ)) == NULL)
3266 if ((file_to = openFile(filename_to, MODE_WRITE)) == NULL)
3268 closeFile(file_from);
3273 while (!checkEndOfFile(file_from))
3275 byte buffer[MAX_BUFFER_SIZE];
3276 size_t bytes_read = readFile(file_from, buffer, 1, MAX_BUFFER_SIZE);
3278 writeFile(file_to, buffer, 1, bytes_read);
3281 closeFile(file_from);
3287 boolean touchFile(const char *filename)
3291 if (!(file = fopen(filename, MODE_WRITE)))
3293 Warn("cannot touch file '%s'", filename);
3304 // ----------------------------------------------------------------------------
3305 // functions for directory handling
3306 // ----------------------------------------------------------------------------
3308 Directory *openDirectory(char *dir_name)
3310 Directory *dir = checked_calloc(sizeof(Directory));
3312 dir->dir = opendir(dir_name);
3314 if (dir->dir != NULL)
3316 dir->filename = getStringCopy(dir_name);
3321 #if defined(PLATFORM_ANDROID)
3322 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
3324 dir->asset_toc_file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
3326 checked_free(asset_toc_filename);
3328 if (dir->asset_toc_file != NULL)
3330 dir->directory_is_asset = TRUE;
3331 dir->filename = getStringCopy(dir_name);
3342 int closeDirectory(Directory *dir)
3349 #if defined(PLATFORM_ANDROID)
3350 if (dir->asset_toc_file)
3351 result = SDL_RWclose(dir->asset_toc_file);
3355 result = closedir(dir->dir);
3358 freeDirectoryEntry(dir->dir_entry);
3360 checked_free(dir->filename);
3366 DirectoryEntry *readDirectory(Directory *dir)
3369 freeDirectoryEntry(dir->dir_entry);
3371 dir->dir_entry = NULL;
3373 #if defined(PLATFORM_ANDROID)
3374 if (dir->directory_is_asset)
3376 char line[MAX_LINE_LEN];
3377 char *line_ptr = line;
3378 int num_bytes_read = 0;
3380 while (num_bytes_read < MAX_LINE_LEN - 1 &&
3381 SDL_RWread(dir->asset_toc_file, line_ptr, 1, 1) == 1 &&
3390 if (strlen(line) == 0)
3393 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
3395 dir->dir_entry->is_directory = FALSE;
3396 if (line[strlen(line) - 1] == '/')
3398 dir->dir_entry->is_directory = TRUE;
3400 line[strlen(line) - 1] = '\0';
3403 dir->dir_entry->basename = getStringCopy(line);
3404 dir->dir_entry->filename = getPath2(dir->filename, line);
3406 return dir->dir_entry;
3410 struct dirent *dir_entry = readdir(dir->dir);
3412 if (dir_entry == NULL)
3415 dir->dir_entry = checked_calloc(sizeof(DirectoryEntry));
3417 dir->dir_entry->basename = getStringCopy(dir_entry->d_name);
3418 dir->dir_entry->filename = getPath2(dir->filename, dir_entry->d_name);
3420 struct stat file_status;
3422 dir->dir_entry->is_directory =
3423 (stat(dir->dir_entry->filename, &file_status) == 0 &&
3424 S_ISDIR(file_status.st_mode));
3426 return dir->dir_entry;
3429 void freeDirectoryEntry(DirectoryEntry *dir_entry)
3431 if (dir_entry == NULL)
3434 checked_free(dir_entry->basename);
3435 checked_free(dir_entry->filename);
3436 checked_free(dir_entry);
3440 // ----------------------------------------------------------------------------
3441 // functions for checking files and filenames
3442 // ----------------------------------------------------------------------------
3444 boolean directoryExists(const char *dir_name)
3446 if (dir_name == NULL)
3449 struct stat file_status;
3450 boolean success = (stat(dir_name, &file_status) == 0 &&
3451 S_ISDIR(file_status.st_mode));
3453 #if defined(PLATFORM_ANDROID)
3456 // this might be an asset directory; check by trying to open toc file
3457 char *asset_toc_filename = getPath2(dir_name, ASSET_TOC_BASENAME);
3458 SDL_RWops *file = SDL_RWFromFile(asset_toc_filename, MODE_READ);
3460 checked_free(asset_toc_filename);
3462 success = (file != NULL);
3472 boolean fileExists(const char *filename)
3474 if (filename == NULL)
3477 boolean success = (access(filename, F_OK) == 0);
3479 #if defined(PLATFORM_ANDROID)
3482 // this might be an asset file; check by trying to open it
3483 SDL_RWops *file = SDL_RWFromFile(filename, MODE_READ);
3485 success = (file != NULL);
3496 static boolean fileHasPrefix(const char *basename, const char *prefix)
3498 static char *basename_lower = NULL;
3499 int basename_length, prefix_length;
3501 checked_free(basename_lower);
3503 if (basename == NULL || prefix == NULL)
3506 basename_lower = getStringToLower(basename);
3507 basename_length = strlen(basename_lower);
3508 prefix_length = strlen(prefix);
3510 if (basename_length > prefix_length + 1 &&
3511 basename_lower[prefix_length] == '.' &&
3512 strncmp(basename_lower, prefix, prefix_length) == 0)
3519 static boolean fileHasSuffix(const char *basename, const char *suffix)
3521 static char *basename_lower = NULL;
3522 int basename_length, suffix_length;
3524 checked_free(basename_lower);
3526 if (basename == NULL || suffix == NULL)
3529 basename_lower = getStringToLower(basename);
3530 basename_length = strlen(basename_lower);
3531 suffix_length = strlen(suffix);
3533 if (basename_length > suffix_length + 1 &&
3534 basename_lower[basename_length - suffix_length - 1] == '.' &&
3535 strEqual(&basename_lower[basename_length - suffix_length], suffix))
3541 static boolean FileCouldBeArtwork(char *filename)
3543 char *basename = getBaseNamePtr(filename);
3545 return (!strEqual(basename, ".") &&
3546 !strEqual(basename, "..") &&
3547 !fileHasSuffix(basename, "txt") &&
3548 !fileHasSuffix(basename, "conf") &&
3549 !directoryExists(filename));
3552 boolean FileIsGraphic(char *filename)
3554 return FileCouldBeArtwork(filename);
3557 boolean FileIsSound(char *filename)
3559 return FileCouldBeArtwork(filename);
3562 boolean FileIsMusic(char *filename)
3564 return FileCouldBeArtwork(filename);
3567 boolean FileIsArtworkType(char *filename, int type)
3569 if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(filename)) ||
3570 (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(filename)) ||
3571 (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(filename)))
3577 // ----------------------------------------------------------------------------
3578 // functions for loading artwork configuration information
3579 // ----------------------------------------------------------------------------
3581 char *get_mapped_token(char *token)
3583 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3584 static char *map_token_prefix[][2] =
3586 { "char_procent", "char_percent" },
3587 { "bd_magic_wall_filling", "bd_magic_wall.filling" },
3588 { "bd_magic_wall_emptying", "bd_magic_wall.emptying" },
3589 { "bd_butterfly_left", "bd_butterfly.left" },
3590 { "bd_butterfly_right", "bd_butterfly.right" },
3591 { "bd_butterfly_up", "bd_butterfly.up" },
3592 { "bd_butterfly_down", "bd_butterfly.down" },
3593 { "bd_firefly_left", "bd_firefly.left" },
3594 { "bd_firefly_right", "bd_firefly.right" },
3595 { "bd_firefly_up", "bd_firefly.up" },
3596 { "bd_firefly_down", "bd_firefly.down" },
3602 for (i = 0; map_token_prefix[i][0] != NULL; i++)
3604 int len_token_prefix = strlen(map_token_prefix[i][0]);
3606 if (strncmp(token, map_token_prefix[i][0], len_token_prefix) == 0)
3607 return getStringCat2(map_token_prefix[i][1], &token[len_token_prefix]);
3610 // change tokens containing ".gfx" by moving the "gfx" part to the very left
3611 char *gfx_substring = ".gfx";
3612 char *gfx_prefix = "gfx.";
3613 if (strstr(token, gfx_substring) != NULL)
3615 char *token_prefix = getStringCopy(token);
3616 char *token_gfx_pos = strstr(token_prefix, gfx_substring);
3617 char *token_suffix = &token_gfx_pos[strlen(gfx_substring)];
3620 // cut off token string at ".gfx" substring position
3621 *token_gfx_pos = '\0';
3623 // put together prefix "gfx." and token prefix and suffix without ".gfx"
3624 mapped_token = getStringCat3(gfx_prefix, token_prefix, token_suffix);
3628 return mapped_token;
3634 static char *get_special_base_token(struct ArtworkListInfo *artwork_info,
3637 // !!! make this dynamically configurable (init.c:InitArtworkConfig) !!!
3638 static struct ConfigTypeInfo prefix_list[] =
3640 { "global.anim_1" },
3641 { "global.anim_2" },
3642 { "global.anim_3" },
3643 { "global.anim_4" },
3644 { "global.anim_5" },
3645 { "global.anim_6" },
3646 { "global.anim_7" },
3647 { "global.anim_8" },
3648 { "global.anim_9" },
3649 { "global.anim_10" },
3650 { "global.anim_11" },
3651 { "global.anim_12" },
3652 { "global.anim_13" },
3653 { "global.anim_14" },
3654 { "global.anim_15" },
3655 { "global.anim_16" },
3656 { "global.anim_17" },
3657 { "global.anim_18" },
3658 { "global.anim_19" },
3659 { "global.anim_20" },
3660 { "global.anim_21" },
3661 { "global.anim_22" },
3662 { "global.anim_23" },
3663 { "global.anim_24" },
3664 { "global.anim_25" },
3665 { "global.anim_26" },
3666 { "global.anim_27" },
3667 { "global.anim_28" },
3668 { "global.anim_29" },
3669 { "global.anim_30" },
3670 { "global.anim_31" },
3671 { "global.anim_32" },
3675 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3676 boolean prefix_found = FALSE;
3680 // search for prefix to check if base token has to be created
3681 for (i = 0; prefix_list[i].token != NULL; i++)
3682 if (strPrefix(token, prefix_list[i].token))
3683 prefix_found = TRUE;
3688 // search for suffix (parameter) to determine base token length
3689 for (i = 0; suffix_list[i].token != NULL; i++)
3690 if (strSuffix(token, suffix_list[i].token))
3691 len_suffix = strlen(suffix_list[i].token);
3693 return getStringCopyN(token, strlen(token) - len_suffix);
3696 static void FreeCustomArtworkList(struct ArtworkListInfo *,
3697 struct ListNodeInfo ***, int *);
3699 struct FileInfo *getFileListFromConfigList(struct ConfigInfo *config_list,
3700 struct ConfigTypeInfo *suffix_list,
3701 char **ignore_tokens,
3702 int num_file_list_entries)
3704 SetupFileHash *ignore_tokens_hash;
3705 struct FileInfo *file_list;
3706 int num_file_list_entries_found = 0;
3707 int num_suffix_list_entries = 0;
3711 // create hash from list of tokens to be ignored (for quick access)
3712 ignore_tokens_hash = newSetupFileHash();
3713 for (i = 0; ignore_tokens[i] != NULL; i++)
3714 setHashEntry(ignore_tokens_hash, ignore_tokens[i], "");
3716 file_list = checked_calloc(num_file_list_entries * sizeof(struct FileInfo));
3718 for (i = 0; suffix_list[i].token != NULL; i++)
3719 num_suffix_list_entries++;
3721 // always start with reliable default values
3722 for (i = 0; i < num_file_list_entries; i++)
3724 file_list[i].token = NULL;
3726 file_list[i].default_filename = NULL;
3727 file_list[i].filename = NULL;
3729 if (num_suffix_list_entries > 0)
3731 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3733 file_list[i].default_parameter = checked_calloc(parameter_array_size);
3734 file_list[i].parameter = checked_calloc(parameter_array_size);
3736 for (j = 0; j < num_suffix_list_entries; j++)
3738 setString(&file_list[i].default_parameter[j], suffix_list[j].value);
3739 setString(&file_list[i].parameter[j], suffix_list[j].value);
3742 file_list[i].redefined = FALSE;
3743 file_list[i].fallback_to_default = FALSE;
3744 file_list[i].default_is_cloned = FALSE;
3750 for (i = 0; config_list[i].token != NULL; i++)
3752 int len_config_token = strlen(config_list[i].token);
3753 boolean is_file_entry = TRUE;
3755 for (j = 0; suffix_list[j].token != NULL; j++)
3757 int len_suffix = strlen(suffix_list[j].token);
3759 if (len_suffix < len_config_token &&
3760 strEqual(&config_list[i].token[len_config_token - len_suffix],
3761 suffix_list[j].token))
3763 setString(&file_list[list_pos].default_parameter[j],
3764 config_list[i].value);
3766 is_file_entry = FALSE;
3772 // the following tokens are no file definitions, but other config tokens
3773 if (getHashEntry(ignore_tokens_hash, config_list[i].token) != NULL)
3774 is_file_entry = FALSE;
3781 if (list_pos >= num_file_list_entries)
3784 file_list[list_pos].token = config_list[i].token;
3785 file_list[list_pos].default_filename = config_list[i].value;
3788 if (strSuffix(config_list[i].token, ".clone_from"))
3789 file_list[list_pos].default_is_cloned = TRUE;
3792 num_file_list_entries_found = list_pos + 1;
3793 if (num_file_list_entries_found != num_file_list_entries)
3796 Error("inconsistant config list information:");
3797 Error("- should be: %d (according to 'src/conf_xxx.h')",
3798 num_file_list_entries);
3799 Error("- found to be: %d (according to 'src/conf_xxx.c')",
3800 num_file_list_entries_found);
3805 freeSetupFileHash(ignore_tokens_hash);
3810 static boolean token_suffix_match(char *token, char *suffix, int start_pos)
3812 int len_token = strlen(token);
3813 int len_suffix = strlen(suffix);
3815 if (start_pos < 0) // compare suffix from end of string
3816 start_pos += len_token;
3818 if (start_pos < 0 || start_pos + len_suffix > len_token)
3821 if (strncmp(&token[start_pos], suffix, len_suffix) != 0)
3824 if (token[start_pos + len_suffix] == '\0')
3827 if (token[start_pos + len_suffix] == '.')
3833 #define KNOWN_TOKEN_VALUE "[KNOWN_TOKEN_VALUE]"
3835 static void read_token_parameters(SetupFileHash *setup_file_hash,
3836 struct ConfigTypeInfo *suffix_list,
3837 struct FileInfo *file_list_entry)
3839 // check for config token that is the base token without any suffixes
3840 char *filename = getHashEntry(setup_file_hash, file_list_entry->token);
3841 char *known_token_value = KNOWN_TOKEN_VALUE;
3844 if (filename != NULL)
3846 setString(&file_list_entry->filename, filename);
3848 // when file definition found, set all parameters to default values
3849 for (i = 0; suffix_list[i].token != NULL; i++)
3850 setString(&file_list_entry->parameter[i], suffix_list[i].value);
3852 file_list_entry->redefined = TRUE;
3854 // mark config file token as well known from default config
3855 setHashEntry(setup_file_hash, file_list_entry->token, known_token_value);
3858 // check for config tokens that can be build by base token and suffixes
3859 for (i = 0; suffix_list[i].token != NULL; i++)
3861 char *token = getStringCat2(file_list_entry->token, suffix_list[i].token);
3862 char *value = getHashEntry(setup_file_hash, token);
3866 setString(&file_list_entry->parameter[i], value);
3868 // mark config file token as well known from default config
3869 setHashEntry(setup_file_hash, token, known_token_value);
3876 static void add_dynamic_file_list_entry(struct FileInfo **list,
3877 int *num_list_entries,
3878 SetupFileHash *extra_file_hash,
3879 struct ConfigTypeInfo *suffix_list,
3880 int num_suffix_list_entries,
3883 struct FileInfo *new_list_entry;
3884 int parameter_array_size = num_suffix_list_entries * sizeof(char *);
3886 (*num_list_entries)++;
3887 *list = checked_realloc(*list, *num_list_entries * sizeof(struct FileInfo));
3888 new_list_entry = &(*list)[*num_list_entries - 1];
3890 new_list_entry->token = getStringCopy(token);
3891 new_list_entry->default_filename = NULL;
3892 new_list_entry->filename = NULL;
3893 new_list_entry->parameter = checked_calloc(parameter_array_size);
3895 new_list_entry->redefined = FALSE;
3896 new_list_entry->fallback_to_default = FALSE;
3897 new_list_entry->default_is_cloned = FALSE;
3899 read_token_parameters(extra_file_hash, suffix_list, new_list_entry);
3902 static void add_property_mapping(struct PropertyMapping **list,
3903 int *num_list_entries,
3904 int base_index, int ext1_index,
3905 int ext2_index, int ext3_index,
3908 struct PropertyMapping *new_list_entry;
3910 (*num_list_entries)++;
3911 *list = checked_realloc(*list,
3912 *num_list_entries * sizeof(struct PropertyMapping));
3913 new_list_entry = &(*list)[*num_list_entries - 1];
3915 new_list_entry->base_index = base_index;
3916 new_list_entry->ext1_index = ext1_index;
3917 new_list_entry->ext2_index = ext2_index;
3918 new_list_entry->ext3_index = ext3_index;
3920 new_list_entry->artwork_index = artwork_index;
3923 static void LoadArtworkConfigFromFilename(struct ArtworkListInfo *artwork_info,
3926 struct FileInfo *file_list = artwork_info->file_list;
3927 struct ConfigTypeInfo *suffix_list = artwork_info->suffix_list;
3928 char **base_prefixes = artwork_info->base_prefixes;
3929 char **ext1_suffixes = artwork_info->ext1_suffixes;
3930 char **ext2_suffixes = artwork_info->ext2_suffixes;
3931 char **ext3_suffixes = artwork_info->ext3_suffixes;
3932 char **ignore_tokens = artwork_info->ignore_tokens;
3933 int num_file_list_entries = artwork_info->num_file_list_entries;
3934 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
3935 int num_base_prefixes = artwork_info->num_base_prefixes;
3936 int num_ext1_suffixes = artwork_info->num_ext1_suffixes;
3937 int num_ext2_suffixes = artwork_info->num_ext2_suffixes;
3938 int num_ext3_suffixes = artwork_info->num_ext3_suffixes;
3939 int num_ignore_tokens = artwork_info->num_ignore_tokens;
3940 SetupFileHash *setup_file_hash, *valid_file_hash, *valid_file_hash_tmp;
3941 SetupFileHash *extra_file_hash, *empty_file_hash;
3942 char *known_token_value = KNOWN_TOKEN_VALUE;
3943 char *base_token_value = UNDEFINED_FILENAME;
3946 if (filename == NULL)
3949 if ((setup_file_hash = loadSetupFileHash(filename)) == NULL)
3952 // separate valid (defined) from empty (undefined) config token values
3953 valid_file_hash = newSetupFileHash();
3954 empty_file_hash = newSetupFileHash();
3955 BEGIN_HASH_ITERATION(setup_file_hash, itr)
3957 char *value = HASH_ITERATION_VALUE(itr);
3959 setHashEntry(*value ? valid_file_hash : empty_file_hash,
3960 HASH_ITERATION_TOKEN(itr), value);
3962 END_HASH_ITERATION(setup_file_hash, itr)
3964 // at this point, we do not need the setup file hash anymore -- free it
3965 freeSetupFileHash(setup_file_hash);
3967 // prevent changing hash while iterating over it by using a temporary copy
3968 valid_file_hash_tmp = newSetupFileHash();
3969 BEGIN_HASH_ITERATION(valid_file_hash, itr)
3971 setHashEntry(valid_file_hash_tmp,
3972 HASH_ITERATION_TOKEN(itr),
3973 HASH_ITERATION_VALUE(itr));
3975 END_HASH_ITERATION(valid_file_hash, itr)
3977 // (iterate over same temporary hash, as modifications are independent)
3979 // map deprecated to current tokens (using prefix match and replace)
3980 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
3982 char *token = HASH_ITERATION_TOKEN(itr);
3983 char *mapped_token = get_mapped_token(token);
3985 if (mapped_token != NULL)
3987 char *value = HASH_ITERATION_VALUE(itr);
3990 setHashEntry(valid_file_hash, mapped_token, value);
3992 // ignore old token (by setting it to "known" keyword)
3993 setHashEntry(valid_file_hash, token, known_token_value);
3998 END_HASH_ITERATION(valid_file_hash_tmp, itr)
4000 // add special base tokens (using prefix match and replace)
4001 BEGIN_HASH_ITERATION(valid_file_hash_tmp, itr)
4003 char *token = HASH_ITERATION_TOKEN(itr);
4004 char *base_token = get_special_base_token(artwork_info, token);
4006 if (base_token != NULL)
4008 // add base token only if it does not already exist
4009 if (getHashEntry(valid_file_hash, base_token) == NULL)
4010 setHashEntry(valid_file_hash, base_token, base_token_value);
4015 END_HASH_ITERATION(valid_file_hash_tmp, itr)
4017 // free temporary hash used for iteration
4018 freeSetupFileHash(valid_file_hash_tmp);
4020 // read parameters for all known config file tokens
4021 for (i = 0; i < num_file_list_entries; i++)
4022 read_token_parameters(valid_file_hash, suffix_list, &file_list[i]);
4024 // set all tokens that can be ignored here to "known" keyword
4025 for (i = 0; i < num_ignore_tokens; i++)
4026 setHashEntry(valid_file_hash, ignore_tokens[i], known_token_value);
4028 // copy all unknown config file tokens to extra config hash
4029 extra_file_hash = newSetupFileHash();
4030 BEGIN_HASH_ITERATION(valid_file_hash, itr)
4032 char *value = HASH_ITERATION_VALUE(itr);
4034 if (!strEqual(value, known_token_value))
4035 setHashEntry(extra_file_hash, HASH_ITERATION_TOKEN(itr), value);
4037 END_HASH_ITERATION(valid_file_hash, itr)
4039 // at this point, we do not need the valid file hash anymore -- free it
4040 freeSetupFileHash(valid_file_hash);
4042 // now try to determine valid, dynamically defined config tokens
4044 BEGIN_HASH_ITERATION(extra_file_hash, itr)
4046 struct FileInfo **dynamic_file_list =
4047 &artwork_info->dynamic_file_list;
4048 int *num_dynamic_file_list_entries =
4049 &artwork_info->num_dynamic_file_list_entries;
4050 struct PropertyMapping **property_mapping =
4051 &artwork_info->property_mapping;
4052 int *num_property_mapping_entries =
4053 &artwork_info->num_property_mapping_entries;
4054 int current_summarized_file_list_entry =
4055 artwork_info->num_file_list_entries +
4056 artwork_info->num_dynamic_file_list_entries;
4057 char *token = HASH_ITERATION_TOKEN(itr);
4058 int len_token = strlen(token);
4060 boolean base_prefix_found = FALSE;
4061 boolean parameter_suffix_found = FALSE;
4063 // skip all parameter definitions (handled by read_token_parameters())
4064 for (i = 0; i < num_suffix_list_entries && !parameter_suffix_found; i++)
4066 int len_suffix = strlen(suffix_list[i].token);
4068 if (token_suffix_match(token, suffix_list[i].token, -len_suffix))
4069 parameter_suffix_found = TRUE;
4072 if (parameter_suffix_found)
4075 // ---------- step 0: search for matching base prefix ----------
4078 for (i = 0; i < num_base_prefixes && !base_prefix_found; i++)
4080 char *base_prefix = base_prefixes[i];
4081 int len_base_prefix = strlen(base_prefix);
4082 boolean ext1_suffix_found = FALSE;
4083 boolean ext2_suffix_found = FALSE;
4084 boolean ext3_suffix_found = FALSE;
4085 boolean exact_match = FALSE;
4086 int base_index = -1;
4087 int ext1_index = -1;
4088 int ext2_index = -1;
4089 int ext3_index = -1;
4091 base_prefix_found = token_suffix_match(token, base_prefix, start_pos);
4093 if (!base_prefix_found)
4098 if (start_pos + len_base_prefix == len_token) // exact match
4102 add_dynamic_file_list_entry(dynamic_file_list,
4103 num_dynamic_file_list_entries,
4106 num_suffix_list_entries,
4108 add_property_mapping(property_mapping,
4109 num_property_mapping_entries,
4110 base_index, -1, -1, -1,
4111 current_summarized_file_list_entry);
4115 // ---------- step 1: search for matching first suffix ----------
4117 start_pos += len_base_prefix;
4118 for (j = 0; j < num_ext1_suffixes && !ext1_suffix_found; j++)
4120 char *ext1_suffix = ext1_suffixes[j];
4121 int len_ext1_suffix = strlen(ext1_suffix);
4123 ext1_suffix_found = token_suffix_match(token, ext1_suffix, start_pos);
4125 if (!ext1_suffix_found)
4130 if (start_pos + len_ext1_suffix == len_token) // exact match
4134 add_dynamic_file_list_entry(dynamic_file_list,
4135 num_dynamic_file_list_entries,
4138 num_suffix_list_entries,
4140 add_property_mapping(property_mapping,
4141 num_property_mapping_entries,
4142 base_index, ext1_index, -1, -1,
4143 current_summarized_file_list_entry);
4147 start_pos += len_ext1_suffix;
4153 // ---------- step 2: search for matching second suffix ----------
4155 for (k = 0; k < num_ext2_suffixes && !ext2_suffix_found; k++)
4157 char *ext2_suffix = ext2_suffixes[k];
4158 int len_ext2_suffix = strlen(ext2_suffix);
4160 ext2_suffix_found = token_suffix_match(token, ext2_suffix, start_pos);
4162 if (!ext2_suffix_found)
4167 if (start_pos + len_ext2_suffix == len_token) // exact match
4171 add_dynamic_file_list_entry(dynamic_file_list,
4172 num_dynamic_file_list_entries,
4175 num_suffix_list_entries,
4177 add_property_mapping(property_mapping,
4178 num_property_mapping_entries,
4179 base_index, ext1_index, ext2_index, -1,
4180 current_summarized_file_list_entry);
4184 start_pos += len_ext2_suffix;
4190 // ---------- step 3: search for matching third suffix ----------
4192 for (l = 0; l < num_ext3_suffixes && !ext3_suffix_found; l++)
4194 char *ext3_suffix = ext3_suffixes[l];
4195 int len_ext3_suffix = strlen(ext3_suffix);
4197 ext3_suffix_found = token_suffix_match(token, ext3_suffix, start_pos);
4199 if (!ext3_suffix_found)
4204 if (start_pos + len_ext3_suffix == len_token) // exact match
4208 add_dynamic_file_list_entry(dynamic_file_list,
4209 num_dynamic_file_list_entries,
4212 num_suffix_list_entries,
4214 add_property_mapping(property_mapping,
4215 num_property_mapping_entries,
4216 base_index, ext1_index, ext2_index, ext3_index,
4217 current_summarized_file_list_entry);
4223 END_HASH_ITERATION(extra_file_hash, itr)
4225 if (artwork_info->num_dynamic_file_list_entries > 0)
4227 artwork_info->dynamic_artwork_list =
4228 checked_calloc(artwork_info->num_dynamic_file_list_entries *
4229 artwork_info->sizeof_artwork_list_entry);
4232 if (options.verbose && IS_PARENT_PROCESS())
4234 SetupFileList *setup_file_list, *list;
4235 boolean dynamic_tokens_found = FALSE;
4236 boolean unknown_tokens_found = FALSE;
4237 boolean undefined_values_found = (hashtable_count(empty_file_hash) != 0);
4239 // list may be NULL for empty artwork config files
4240 setup_file_list = loadSetupFileList(filename);
4242 BEGIN_HASH_ITERATION(extra_file_hash, itr)
4244 if (strEqual(HASH_ITERATION_VALUE(itr), known_token_value))
4245 dynamic_tokens_found = TRUE;
4247 unknown_tokens_found = TRUE;
4249 END_HASH_ITERATION(extra_file_hash, itr)
4251 if (options.debug && dynamic_tokens_found)
4253 Debug("config", "---");
4254 Debug("config", "dynamic token(s) found in config file:");
4255 Debug("config", "- config file: '%s'", filename);
4257 for (list = setup_file_list; list != NULL; list = list->next)
4259 char *value = getHashEntry(extra_file_hash, list->token);
4261 if (value != NULL && strEqual(value, known_token_value))
4262 Debug("config", "- dynamic token: '%s'", list->token);
4265 Debug("config", "---");
4268 if (unknown_tokens_found)
4271 Warn("unknown token(s) found in config file:");
4272 Warn("- config file: '%s'", filename);
4274 for (list = setup_file_list; list != NULL; list = list->next)
4276 char *value = getHashEntry(extra_file_hash, list->token);
4278 if (value != NULL && !strEqual(value, known_token_value))
4279 Warn("- dynamic token: '%s'", list->token);
4285 if (undefined_values_found)
4288 Warn("undefined values found in config file:");
4289 Warn("- config file: '%s'", filename);
4291 for (list = setup_file_list; list != NULL; list = list->next)
4293 char *value = getHashEntry(empty_file_hash, list->token);
4296 Warn("- undefined value for token: '%s'", list->token);
4302 freeSetupFileList(setup_file_list);
4305 freeSetupFileHash(extra_file_hash);
4306 freeSetupFileHash(empty_file_hash);
4309 void LoadArtworkConfig(struct ArtworkListInfo *artwork_info)
4311 struct FileInfo *file_list = artwork_info->file_list;
4312 int num_file_list_entries = artwork_info->num_file_list_entries;
4313 int num_suffix_list_entries = artwork_info->num_suffix_list_entries;
4314 char *filename_base = UNDEFINED_FILENAME, *filename_local;
4317 DrawInitTextHead("Loading artwork config");
4318 DrawInitTextItem(ARTWORKINFO_FILENAME(artwork_info->type));
4320 // always start with reliable default values
4321 for (i = 0; i < num_file_list_entries; i++)
4323 setString(&file_list[i].filename, file_list[i].default_filename);
4325 for (j = 0; j < num_suffix_list_entries; j++)
4326 setString(&file_list[i].parameter[j], file_list[i].default_parameter[j]);
4328 file_list[i].redefined = FALSE;
4329 file_list[i].fallback_to_default = FALSE;
4332 // free previous dynamic artwork file array
4333 if (artwork_info->dynamic_file_list != NULL)
4335 for (i = 0; i < artwork_info->num_dynamic_file_list_entries; i++)
4337 free(artwork_info->dynamic_file_list[i].token);
4338 free(artwork_info->dynamic_file_list[i].filename);
4339 free(artwork_info->dynamic_file_list[i].parameter);
4342 free(artwork_info->dynamic_file_list);
4343 artwork_info->dynamic_file_list = NULL;
4345 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
4346 &artwork_info->num_dynamic_file_list_entries);
4349 // free previous property mapping
4350 if (artwork_info->property_mapping != NULL)
4352 free(artwork_info->property_mapping);
4354 artwork_info->property_mapping = NULL;
4355 artwork_info->num_property_mapping_entries = 0;
4358 if (!GFX_OVERRIDE_ARTWORK(artwork_info->type))
4360 // first look for special artwork configured in level series config
4361 filename_base = getCustomArtworkLevelConfigFilename(artwork_info->type);
4363 if (fileExists(filename_base))
4364 LoadArtworkConfigFromFilename(artwork_info, filename_base);
4367 filename_local = getCustomArtworkConfigFilename(artwork_info->type);
4369 if (filename_local != NULL && !strEqual(filename_base, filename_local))
4370 LoadArtworkConfigFromFilename(artwork_info, filename_local);
4373 static void deleteArtworkListEntry(struct ArtworkListInfo *artwork_info,
4374 struct ListNodeInfo **listnode)
4378 char *filename = (*listnode)->source_filename;
4380 if (--(*listnode)->num_references <= 0)
4381 deleteNodeFromList(&artwork_info->content_list, filename,
4382 artwork_info->free_artwork);
4388 static void replaceArtworkListEntry(struct ArtworkListInfo *artwork_info,
4389 struct ListNodeInfo **listnode,
4390 struct FileInfo *file_list_entry)
4400 char *basename = file_list_entry->filename;
4401 char *filename = getCustomArtworkFilename(basename, artwork_info->type);
4403 // mark all images from non-default graphics directory as "redefined"
4404 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS &&
4405 !strPrefix(filename, options.graphics_directory))
4406 file_list_entry->redefined = TRUE;
4408 if (filename == NULL)
4410 Warn("cannot find artwork file '%s'", basename);
4412 basename = file_list_entry->default_filename;
4414 // fail for cloned default artwork that has no default filename defined
4415 if (file_list_entry->default_is_cloned &&
4416 strEqual(basename, UNDEFINED_FILENAME))
4418 void (*error_func)(char *, ...) = Warn;
4420 // we can get away without sounds and music, but not without graphics
4421 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4424 error_func("token '%s' was cloned and has no default filename",
4425 file_list_entry->token);
4430 // dynamic artwork has no default filename / skip empty default artwork
4431 if (basename == NULL || strEqual(basename, UNDEFINED_FILENAME))
4434 file_list_entry->fallback_to_default = TRUE;
4436 Warn("trying default artwork file '%s'", basename);
4438 filename = getCustomArtworkFilename(basename, artwork_info->type);
4440 if (filename == NULL)
4442 void (*error_func)(char *, ...) = Warn;
4444 // we can get away without sounds and music, but not without graphics
4445 if (*listnode == NULL && artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4448 error_func("cannot find default artwork file '%s'", basename);
4454 // check if the old and the new artwork file are the same
4455 if (*listnode && strEqual((*listnode)->source_filename, filename))
4457 // The old and new artwork are the same (have the same filename and path).
4458 // This usually means that this artwork does not exist in this artwork set
4459 // and a fallback to the existing artwork is done.
4464 // delete existing artwork file entry
4465 deleteArtworkListEntry(artwork_info, listnode);
4467 // check if the new artwork file already exists in the list of artwork
4468 if ((node = getNodeFromKey(artwork_info->content_list, filename)) != NULL)
4470 *listnode = (struct ListNodeInfo *)node->content;
4471 (*listnode)->num_references++;
4476 DrawInitTextHead(init_text[artwork_info->type]);
4477 DrawInitTextItem(basename);
4479 if ((*listnode = artwork_info->load_artwork(filename)) != NULL)
4481 // add new artwork file entry to the list of artwork files
4482 (*listnode)->num_references = 1;
4483 addNodeToList(&artwork_info->content_list, (*listnode)->source_filename,
4488 void (*error_func)(char *, ...) = Warn;
4490 // we can get away without sounds and music, but not without graphics
4491 if (artwork_info->type == ARTWORK_TYPE_GRAPHICS)
4494 error_func("cannot load artwork file '%s'", basename);
4500 static void LoadCustomArtwork(struct ArtworkListInfo *artwork_info,
4501 struct ListNodeInfo **listnode,
4502 struct FileInfo *file_list_entry)
4504 if (strEqual(file_list_entry->filename, UNDEFINED_FILENAME))
4506 deleteArtworkListEntry(artwork_info, listnode);
4511 replaceArtworkListEntry(artwork_info, listnode, file_list_entry);
4514 void ReloadCustomArtworkList(struct ArtworkListInfo *artwork_info)
4516 struct FileInfo *file_list = artwork_info->file_list;
4517 struct FileInfo *dynamic_file_list = artwork_info->dynamic_file_list;
4518 int num_file_list_entries = artwork_info->num_file_list_entries;
4519 int num_dynamic_file_list_entries =
4520 artwork_info->num_dynamic_file_list_entries;
4523 print_timestamp_init("ReloadCustomArtworkList");
4525 for (i = 0; i < num_file_list_entries; i++)
4526 LoadCustomArtwork(artwork_info, &artwork_info->artwork_list[i],
4529 for (i = 0; i < num_dynamic_file_list_entries; i++)
4530 LoadCustomArtwork(artwork_info, &artwork_info->dynamic_artwork_list[i],
4531 &dynamic_file_list[i]);
4533 print_timestamp_done("ReloadCustomArtworkList");
4536 dumpList(artwork_info->content_list);
4540 static void FreeCustomArtworkList(struct ArtworkListInfo *artwork_info,
4541 struct ListNodeInfo ***list,
4542 int *num_list_entries)
4549 for (i = 0; i < *num_list_entries; i++)
4550 deleteArtworkListEntry(artwork_info, &(*list)[i]);
4554 *num_list_entries = 0;
4557 void FreeCustomArtworkLists(struct ArtworkListInfo *artwork_info)
4559 if (artwork_info == NULL)
4562 FreeCustomArtworkList(artwork_info, &artwork_info->artwork_list,
4563 &artwork_info->num_file_list_entries);
4565 FreeCustomArtworkList(artwork_info, &artwork_info->dynamic_artwork_list,
4566 &artwork_info->num_dynamic_file_list_entries);
4570 // ----------------------------------------------------------------------------
4571 // functions only needed for non-Unix (non-command-line) systems
4572 // (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")
4573 // (now also added for Windows, to create files in user data directory)
4574 // ----------------------------------------------------------------------------
4576 char *getLogBasename(char *basename)
4578 return getStringCat2(basename, ".log");
4581 char *getLogFilename(char *basename)
4583 return getPath2(getMainUserGameDataDir(), basename);
4586 void OpenLogFile(void)
4588 InitMainUserDataDirectory();
4590 if ((program.log_file = fopen(program.log_filename, MODE_WRITE)) == NULL)
4592 program.log_file = program.log_file_default; // reset to default
4594 Warn("cannot open file '%s' for writing: %s",
4595 program.log_filename, strerror(errno));
4598 // output should be unbuffered so it is not truncated in a crash
4599 setbuf(program.log_file, NULL);
4602 void CloseLogFile(void)
4604 if (program.log_file != program.log_file_default)
4605 fclose(program.log_file);
4608 void DumpLogFile(void)
4610 FILE *log_file = fopen(program.log_filename, MODE_READ);
4612 if (log_file == NULL)
4615 while (!feof(log_file))
4616 fputc(fgetc(log_file), stdout);
4621 void NotifyUserAboutErrorFile(void)
4623 #if defined(PLATFORM_WINDOWS)
4624 char *title_text = getStringCat2(program.program_title, " Error Message");
4625 char *error_text = getStringCat2("The program was aborted due to an error; "
4626 "for details, see the following error file:"
4628 program.log_filename);
4630 MessageBox(NULL, error_text, title_text, MB_OK);
4635 // ----------------------------------------------------------------------------
4636 // the following is only for debugging purpose and normally not used
4637 // ----------------------------------------------------------------------------
4641 #define DEBUG_PRINT_INIT_TIMESTAMPS TRUE
4642 #define DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH 10
4644 #define DEBUG_NUM_TIMESTAMPS 10
4645 #define DEBUG_TIME_IN_MICROSECONDS 0
4647 #if DEBUG_TIME_IN_MICROSECONDS
4648 static double Counter_Microseconds(void)
4650 static struct timeval base_time = { 0, 0 };
4651 struct timeval current_time;
4654 gettimeofday(¤t_time, NULL);
4656 // reset base time in case of wrap-around
4657 if (current_time.tv_sec < base_time.tv_sec)
4658 base_time = current_time;
4661 ((double)(current_time.tv_sec - base_time.tv_sec)) * 1000000 +
4662 ((double)(current_time.tv_usec - base_time.tv_usec));
4664 return counter; // return microseconds since last init
4668 static char *debug_print_timestamp_get_padding(int padding_size)
4670 static char *padding = NULL;
4671 int max_padding_size = 100;
4673 if (padding == NULL)
4675 padding = checked_calloc(max_padding_size + 1);
4676 memset(padding, ' ', max_padding_size);
4679 return &padding[MAX(0, max_padding_size - padding_size)];
4682 void debug_print_timestamp(int counter_nr, char *message)
4684 int indent_size = 8;
4685 int padding_size = 40;
4686 float timestamp_interval;
4689 Fail("debugging: invalid negative counter");
4690 else if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
4691 Fail("debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
4693 #if DEBUG_TIME_IN_MICROSECONDS
4694 static double counter[DEBUG_NUM_TIMESTAMPS][2];
4697 counter[counter_nr][0] = Counter_Microseconds();
4699 static int counter[DEBUG_NUM_TIMESTAMPS][2];
4702 counter[counter_nr][0] = Counter();
4705 timestamp_interval = counter[counter_nr][0] - counter[counter_nr][1];
4706 counter[counter_nr][1] = counter[counter_nr][0];
4709 Debug("time:init", "%s%s%s %.3f %s",
4710 debug_print_timestamp_get_padding(counter_nr * indent_size),
4712 debug_print_timestamp_get_padding(padding_size - strlen(message)),
4713 timestamp_interval / 1000,
4718 static void debug_print_parent_only(char *format, ...)
4720 if (!IS_PARENT_PROCESS())
4727 va_start(ap, format);
4728 vprintf(format, ap);
4738 static void print_timestamp_ext(char *message, char *mode)
4740 #if DEBUG_PRINT_INIT_TIMESTAMPS
4741 static char *debug_message = NULL;
4742 static char *last_message = NULL;
4743 static int counter_nr = 0;
4744 int max_depth = DEBUG_PRINT_INIT_TIMESTAMPS_DEPTH;
4746 checked_free(debug_message);
4747 debug_message = getStringCat3(mode, " ", message);
4749 if (strEqual(mode, "INIT"))
4751 debug_print_timestamp(counter_nr, NULL);
4753 if (counter_nr + 1 < max_depth)
4754 debug_print_timestamp(counter_nr, debug_message);
4758 debug_print_timestamp(counter_nr, NULL);
4760 else if (strEqual(mode, "DONE"))
4764 if (counter_nr + 1 < max_depth ||
4765 (counter_nr == 0 && max_depth == 1))
4767 last_message = message;
4769 if (counter_nr == 0 && max_depth == 1)
4771 checked_free(debug_message);
4772 debug_message = getStringCat3("TIME", " ", message);
4775 debug_print_timestamp(counter_nr, debug_message);
4778 else if (!strEqual(mode, "TIME") ||
4779 !strEqual(message, last_message))
4781 if (counter_nr < max_depth)
4782 debug_print_timestamp(counter_nr, debug_message);
4787 void print_timestamp_init(char *message)
4789 print_timestamp_ext(message, "INIT");
4792 void print_timestamp_time(char *message)
4794 print_timestamp_ext(message, "TIME");
4797 void print_timestamp_done(char *message)
4799 print_timestamp_ext(message, "DONE");