rnd-20020810-2-src
[rocksndiamonds.git] / src / libgame / misc.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2002 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * misc.c                                                   *
12 ***********************************************************/
13
14 #include <time.h>
15 #include <sys/time.h>
16 #include <sys/types.h>
17 #include <stdarg.h>
18 #include <ctype.h>
19 #include <string.h>
20 #include <unistd.h>
21
22 #include "platform.h"
23
24 #if !defined(PLATFORM_WIN32)
25 #include <pwd.h>
26 #include <sys/param.h>
27 #endif
28
29 #include "misc.h"
30 #include "setup.h"
31 #include "random.h"
32
33
34 #if defined(PLATFORM_MSDOS)
35 volatile unsigned long counter = 0;
36
37 void increment_counter()
38 {
39   counter++;
40 }
41
42 END_OF_FUNCTION(increment_counter);
43 #endif
44
45
46 /* maximal allowed length of a command line option */
47 #define MAX_OPTION_LEN          256
48
49 #ifdef TARGET_SDL
50 static unsigned long mainCounter(int mode)
51 {
52   static unsigned long base_ms = 0;
53   unsigned long current_ms;
54   unsigned long counter_ms;
55
56   current_ms = SDL_GetTicks();
57
58   /* reset base time in case of counter initializing or wrap-around */
59   if (mode == INIT_COUNTER || current_ms < base_ms)
60     base_ms = current_ms;
61
62   counter_ms = current_ms - base_ms;
63
64   return counter_ms;            /* return milliseconds since last init */
65 }
66
67 #else /* !TARGET_SDL */
68
69 #if defined(PLATFORM_UNIX)
70 static unsigned long mainCounter(int mode)
71 {
72   static struct timeval base_time = { 0, 0 };
73   struct timeval current_time;
74   unsigned long counter_ms;
75
76   gettimeofday(&current_time, NULL);
77
78   /* reset base time in case of counter initializing or wrap-around */
79   if (mode == INIT_COUNTER || current_time.tv_sec < base_time.tv_sec)
80     base_time = current_time;
81
82   counter_ms = (current_time.tv_sec  - base_time.tv_sec)  * 1000
83              + (current_time.tv_usec - base_time.tv_usec) / 1000;
84
85   return counter_ms;            /* return milliseconds since last init */
86 }
87 #endif /* PLATFORM_UNIX */
88 #endif /* !TARGET_SDL */
89
90 void InitCounter()              /* set counter back to zero */
91 {
92 #if !defined(PLATFORM_MSDOS)
93   mainCounter(INIT_COUNTER);
94 #else
95   LOCK_VARIABLE(counter);
96   LOCK_FUNCTION(increment_counter);
97   install_int_ex(increment_counter, BPS_TO_TIMER(100));
98 #endif
99 }
100
101 unsigned long Counter() /* get milliseconds since last call of InitCounter() */
102 {
103 #if !defined(PLATFORM_MSDOS)
104   return mainCounter(READ_COUNTER);
105 #else
106   return (counter * 10);
107 #endif
108 }
109
110 static void sleep_milliseconds(unsigned long milliseconds_delay)
111 {
112   boolean do_busy_waiting = (milliseconds_delay < 5 ? TRUE : FALSE);
113
114 #if 0
115 #if defined(PLATFORM_MSDOS)
116   /* don't use select() to perform waiting operations under DOS
117      environment; always use a busy loop for waiting instead */
118   do_busy_waiting = TRUE;
119 #endif
120 #endif
121
122   if (do_busy_waiting)
123   {
124     /* we want to wait only a few ms -- if we assume that we have a
125        kernel timer resolution of 10 ms, we would wait far to long;
126        therefore it's better to do a short interval of busy waiting
127        to get our sleeping time more accurate */
128
129     unsigned long base_counter = Counter(), actual_counter = Counter();
130
131     while (actual_counter < base_counter + milliseconds_delay &&
132            actual_counter >= base_counter)
133       actual_counter = Counter();
134   }
135   else
136   {
137 #if defined(TARGET_SDL)
138     SDL_Delay(milliseconds_delay);
139 #elif defined(TARGET_ALLEGRO)
140     rest(milliseconds_delay);
141 #else
142     struct timeval delay;
143
144     delay.tv_sec  = milliseconds_delay / 1000;
145     delay.tv_usec = 1000 * (milliseconds_delay % 1000);
146
147     if (select(0, NULL, NULL, NULL, &delay) != 0)
148       Error(ERR_WARN, "sleep_milliseconds(): select() failed");
149 #endif
150   }
151 }
152
153 void Delay(unsigned long delay) /* Sleep specified number of milliseconds */
154 {
155   sleep_milliseconds(delay);
156 }
157
158 boolean FrameReached(unsigned long *frame_counter_var,
159                      unsigned long frame_delay)
160 {
161   unsigned long actual_frame_counter = FrameCounter;
162
163   if (actual_frame_counter < *frame_counter_var + frame_delay &&
164       actual_frame_counter >= *frame_counter_var)
165     return FALSE;
166
167   *frame_counter_var = actual_frame_counter;
168
169   return TRUE;
170 }
171
172 boolean DelayReached(unsigned long *counter_var,
173                      unsigned long delay)
174 {
175   unsigned long actual_counter = Counter();
176
177   if (actual_counter < *counter_var + delay &&
178       actual_counter >= *counter_var)
179     return FALSE;
180
181   *counter_var = actual_counter;
182
183   return TRUE;
184 }
185
186 void WaitUntilDelayReached(unsigned long *counter_var, unsigned long delay)
187 {
188   unsigned long actual_counter;
189
190   while(1)
191   {
192     actual_counter = Counter();
193
194     if (actual_counter < *counter_var + delay &&
195         actual_counter >= *counter_var)
196       sleep_milliseconds((*counter_var + delay - actual_counter) / 2);
197     else
198       break;
199   }
200
201   *counter_var = actual_counter;
202 }
203
204 /* int2str() returns a number converted to a string;
205    the used memory is static, but will be overwritten by later calls,
206    so if you want to save the result, copy it to a private string buffer;
207    there can be 10 local calls of int2str() without buffering the result --
208    the 11th call will then destroy the result from the first call and so on.
209 */
210
211 char *int2str(int number, int size)
212 {
213   static char shift_array[10][40];
214   static int shift_counter = 0;
215   char *s = shift_array[shift_counter];
216
217   shift_counter = (shift_counter + 1) % 10;
218
219   if (size > 20)
220     size = 20;
221
222   if (size)
223   {
224     sprintf(s, "                    %09d", number);
225     return &s[strlen(s) - size];
226   }
227   else
228   {
229     sprintf(s, "%d", number);
230     return s;
231   }
232 }
233
234 unsigned int SimpleRND(unsigned int max)
235 {
236 #if defined(TARGET_SDL)
237   static unsigned long root = 654321;
238   unsigned long current_ms;
239
240   current_ms = SDL_GetTicks();
241   root = root * 4253261 + current_ms;
242   return (root % max);
243 #else
244   static unsigned long root = 654321;
245   struct timeval current_time;
246
247   gettimeofday(&current_time, NULL);
248   root = root * 4253261 + current_time.tv_sec + current_time.tv_usec;
249   return (root % max);
250 #endif
251 }
252
253 #ifdef DEBUG
254 static unsigned int last_RND_value = 0;
255
256 unsigned int last_RND()
257 {
258   return last_RND_value;
259 }
260 #endif
261
262 unsigned int RND(unsigned int max)
263 {
264 #ifdef DEBUG
265   return (last_RND_value = random_linux_libc() % max);
266 #else
267   return (random_linux_libc() % max);
268 #endif
269 }
270
271 unsigned int InitRND(long seed)
272 {
273 #if defined(TARGET_SDL)
274   unsigned long current_ms;
275
276   if (seed == NEW_RANDOMIZE)
277   {
278     current_ms = SDL_GetTicks();
279     srandom_linux_libc((unsigned int) current_ms);
280     return (unsigned int) current_ms;
281   }
282   else
283   {
284     srandom_linux_libc((unsigned int) seed);
285     return (unsigned int) seed;
286   }
287 #else
288   struct timeval current_time;
289
290   if (seed == NEW_RANDOMIZE)
291   {
292     gettimeofday(&current_time, NULL);
293     srandom_linux_libc((unsigned int) current_time.tv_usec);
294     return (unsigned int) current_time.tv_usec;
295   }
296   else
297   {
298     srandom_linux_libc((unsigned int) seed);
299     return (unsigned int) seed;
300   }
301 #endif
302 }
303
304 char *getLoginName()
305 {
306 #if defined(PLATFORM_WIN32)
307   return ANONYMOUS_NAME;
308 #else
309   static char *login_name = NULL;
310
311   if (login_name == NULL)
312   {
313     struct passwd *pwd;
314
315     if ((pwd = getpwuid(getuid())) == NULL)
316       login_name = ANONYMOUS_NAME;
317     else
318       login_name = getStringCopy(pwd->pw_name);
319   }
320
321   return login_name;
322 #endif
323 }
324
325 char *getRealName()
326 {
327 #if defined(PLATFORM_UNIX)
328   struct passwd *pwd;
329
330   if ((pwd = getpwuid(getuid())) == NULL || strlen(pwd->pw_gecos) == 0)
331     return ANONYMOUS_NAME;
332   else
333   {
334     static char real_name[1024];
335     char *from_ptr = pwd->pw_gecos, *to_ptr = real_name;
336
337     if (strchr(pwd->pw_gecos, 'ß') == NULL)
338       return pwd->pw_gecos;
339
340     /* the user's real name contains a 'ß' character (german sharp s),
341        which has no equivalent in upper case letters (which our fonts use) */
342     while (*from_ptr != '\0' && (long)(to_ptr - real_name) < 1024 - 2)
343     {
344       if (*from_ptr != 'ß')
345         *to_ptr++ = *from_ptr++;
346       else
347       {
348         from_ptr++;
349         *to_ptr++ = 's';
350         *to_ptr++ = 's';
351       }
352     }
353     *to_ptr = '\0';
354
355     return real_name;
356   }
357 #else /* !PLATFORM_UNIX */
358   return ANONYMOUS_NAME;
359 #endif
360 }
361
362 char *getHomeDir()
363 {
364 #if defined(PLATFORM_UNIX)
365   static char *home_dir = NULL;
366
367   if (home_dir == NULL)
368   {
369     if ((home_dir = getenv("HOME")) == NULL)
370     {
371       struct passwd *pwd;
372
373       if ((pwd = getpwuid(getuid())) == NULL)
374         home_dir = ".";
375       else
376         home_dir = getStringCopy(pwd->pw_dir);
377     }
378   }
379
380   return home_dir;
381 #else
382   return ".";
383 #endif
384 }
385
386 char *getPath2(char *path1, char *path2)
387 {
388   char *complete_path = checked_malloc(strlen(path1) + 1 +
389                                        strlen(path2) + 1);
390
391   sprintf(complete_path, "%s/%s", path1, path2);
392   return complete_path;
393 }
394
395 char *getPath3(char *path1, char *path2, char *path3)
396 {
397   char *complete_path = checked_malloc(strlen(path1) + 1 +
398                                        strlen(path2) + 1 +
399                                        strlen(path3) + 1);
400
401   sprintf(complete_path, "%s/%s/%s", path1, path2, path3);
402   return complete_path;
403 }
404
405 char *getStringCopy(char *s)
406 {
407   char *s_copy;
408
409   if (s == NULL)
410     return NULL;
411
412   s_copy = checked_malloc(strlen(s) + 1);
413
414   strcpy(s_copy, s);
415   return s_copy;
416 }
417
418 char *getStringToLower(char *s)
419 {
420   char *s_copy = checked_malloc(strlen(s) + 1);
421   char *s_ptr = s_copy;
422
423   while (*s)
424     *s_ptr++ = tolower(*s++);
425   *s_ptr = '\0';
426
427   return s_copy;
428 }
429
430 void GetOptions(char *argv[])
431 {
432   char **options_left = &argv[1];
433
434   /* initialize global program options */
435   options.display_name = NULL;
436   options.server_host = NULL;
437   options.server_port = 0;
438   options.ro_base_directory = RO_BASE_PATH;
439   options.rw_base_directory = RW_BASE_PATH;
440   options.level_directory = RO_BASE_PATH "/" LEVELS_DIRECTORY;
441   options.graphics_directory = RO_BASE_PATH "/" GRAPHICS_DIRECTORY;
442   options.sounds_directory = RO_BASE_PATH "/" SOUNDS_DIRECTORY;
443   options.music_directory = RO_BASE_PATH "/" MUSIC_DIRECTORY;
444   options.serveronly = FALSE;
445   options.network = FALSE;
446   options.verbose = FALSE;
447   options.debug = FALSE;
448   options.debug_command = NULL;
449
450   while (*options_left)
451   {
452     char option_str[MAX_OPTION_LEN];
453     char *option = options_left[0];
454     char *next_option = options_left[1];
455     char *option_arg = NULL;
456     int option_len = strlen(option);
457
458     if (option_len >= MAX_OPTION_LEN)
459       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
460
461     strcpy(option_str, option);                 /* copy argument into buffer */
462     option = option_str;
463
464     if (strcmp(option, "--") == 0)              /* stop scanning arguments */
465       break;
466
467     if (strncmp(option, "--", 2) == 0)          /* treat '--' like '-' */
468       option++;
469
470     option_arg = strchr(option, '=');
471     if (option_arg == NULL)                     /* no '=' in option */
472       option_arg = next_option;
473     else
474     {
475       *option_arg++ = '\0';                     /* cut argument from option */
476       if (*option_arg == '\0')                  /* no argument after '=' */
477         Error(ERR_EXIT_HELP, "option '%s' has invalid argument", option_str);
478     }
479
480     option_len = strlen(option);
481
482     if (strcmp(option, "-") == 0)
483       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option);
484     else if (strncmp(option, "-help", option_len) == 0)
485     {
486       printf("Usage: %s [options] [<server host> [<server port>]]\n"
487              "Options:\n"
488              "  -d, --display <host>[:<scr>]  X server display\n"
489              "  -b, --basepath <directory>    alternative base directory\n"
490              "  -l, --level <directory>       alternative level directory\n"
491              "  -g, --graphics <directory>    alternative graphics directory\n"
492              "  -s, --sounds <directory>      alternative sounds directory\n"
493              "  -m, --music <directory>       alternative music directory\n"
494              "  -n, --network                 network multiplayer game\n"
495              "      --serveronly              only start network server\n"
496              "  -v, --verbose                 verbose mode\n"
497              "      --debug                   display debugging information\n",
498              program.command_basename);
499
500       if (options.debug)
501         printf("      --debug-command <command> execute special command\n");
502
503       exit(0);
504     }
505     else if (strncmp(option, "-display", option_len) == 0)
506     {
507       if (option_arg == NULL)
508         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
509
510       options.display_name = option_arg;
511       if (option_arg == next_option)
512         options_left++;
513     }
514     else if (strncmp(option, "-basepath", option_len) == 0)
515     {
516       if (option_arg == NULL)
517         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
518
519       /* this should be extended to separate options for ro and rw data */
520       options.ro_base_directory = option_arg;
521       options.rw_base_directory = option_arg;
522       if (option_arg == next_option)
523         options_left++;
524
525       /* adjust path for level directory accordingly */
526       options.level_directory =
527         getPath2(options.ro_base_directory, LEVELS_DIRECTORY);
528     }
529     else if (strncmp(option, "-levels", option_len) == 0)
530     {
531       if (option_arg == NULL)
532         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
533
534       options.level_directory = option_arg;
535       if (option_arg == next_option)
536         options_left++;
537     }
538     else if (strncmp(option, "-graphics", option_len) == 0)
539     {
540       if (option_arg == NULL)
541         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
542
543       options.graphics_directory = option_arg;
544       if (option_arg == next_option)
545         options_left++;
546     }
547     else if (strncmp(option, "-sounds", option_len) == 0)
548     {
549       if (option_arg == NULL)
550         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
551
552       options.sounds_directory = option_arg;
553       if (option_arg == next_option)
554         options_left++;
555     }
556     else if (strncmp(option, "-music", option_len) == 0)
557     {
558       if (option_arg == NULL)
559         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
560
561       options.music_directory = option_arg;
562       if (option_arg == next_option)
563         options_left++;
564     }
565     else if (strncmp(option, "-network", option_len) == 0)
566     {
567       options.network = TRUE;
568     }
569     else if (strncmp(option, "-serveronly", option_len) == 0)
570     {
571       options.serveronly = TRUE;
572     }
573     else if (strncmp(option, "-verbose", option_len) == 0)
574     {
575       options.verbose = TRUE;
576     }
577     else if (strncmp(option, "-debug", option_len) == 0)
578     {
579       options.debug = TRUE;
580     }
581     else if (strncmp(option, "-debug-command", option_len) == 0)
582     {
583       if (option_arg == NULL)
584         Error(ERR_EXIT_HELP, "option '%s' requires an argument", option_str);
585
586       options.debug_command = option_arg;
587       if (option_arg == next_option)
588         options_left++;
589     }
590     else if (*option == '-')
591     {
592       Error(ERR_EXIT_HELP, "unrecognized option '%s'", option_str);
593     }
594     else if (options.server_host == NULL)
595     {
596       options.server_host = *options_left;
597     }
598     else if (options.server_port == 0)
599     {
600       options.server_port = atoi(*options_left);
601       if (options.server_port < 1024)
602         Error(ERR_EXIT_HELP, "bad port number '%d'", options.server_port);
603     }
604     else
605       Error(ERR_EXIT_HELP, "too many arguments");
606
607     options_left++;
608   }
609 }
610
611 /* used by SetError() and GetError() to store internal error messages */
612 static char internal_error[1024];       /* this is bad */
613
614 void SetError(char *format, ...)
615 {
616   va_list ap;
617
618   va_start(ap, format);
619   vsprintf(internal_error, format, ap);
620   va_end(ap);
621 }
622
623 char *GetError()
624 {
625   return internal_error;
626 }
627
628 void Error(int mode, char *format, ...)
629 {
630   char *process_name = "";
631   FILE *error = stderr;
632   char *newline = "\n";
633
634   /* display warnings only when running in verbose mode */
635   if (mode & ERR_WARN && !options.verbose)
636     return;
637
638 #if defined(PLATFORM_MSDOS)
639   newline = "\r\n";
640
641   if ((error = openErrorFile()) == NULL)
642   {
643     printf("Cannot write to error output file!%s", newline);
644     program.exit_function(1);
645   }
646 #endif
647
648   if (mode & ERR_SOUND_SERVER)
649     process_name = " sound server";
650   else if (mode & ERR_NETWORK_SERVER)
651     process_name = " network server";
652   else if (mode & ERR_NETWORK_CLIENT)
653     process_name = " network client **";
654
655   if (format)
656   {
657     va_list ap;
658
659     fprintf(error, "%s%s: ", program.command_basename, process_name);
660
661     if (mode & ERR_WARN)
662       fprintf(error, "warning: ");
663
664     va_start(ap, format);
665     vfprintf(error, format, ap);
666     va_end(ap);
667   
668     fprintf(error, "%s", newline);
669   }
670   
671   if (mode & ERR_HELP)
672     fprintf(error, "%s: Try option '--help' for more information.%s",
673             program.command_basename, newline);
674
675   if (mode & ERR_EXIT)
676     fprintf(error, "%s%s: aborting%s",
677             program.command_basename, process_name, newline);
678
679   if (error != stderr)
680     fclose(error);
681
682   if (mode & ERR_EXIT)
683   {
684     if (mode & ERR_FROM_SERVER)
685       exit(1);                          /* child process: normal exit */
686     else
687       program.exit_function(1);         /* main process: clean up stuff */
688   }
689 }
690
691 void *checked_malloc(unsigned long size)
692 {
693   void *ptr;
694
695   ptr = malloc(size);
696
697   if (ptr == NULL)
698     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
699
700   return ptr;
701 }
702
703 void *checked_calloc(unsigned long size)
704 {
705   void *ptr;
706
707   ptr = calloc(1, size);
708
709   if (ptr == NULL)
710     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
711
712   return ptr;
713 }
714
715 void *checked_realloc(void *ptr, unsigned long size)
716 {
717   ptr = realloc(ptr, size);
718
719   if (ptr == NULL)
720     Error(ERR_EXIT, "cannot allocate %d bytes -- out of memory", size);
721
722   return ptr;
723 }
724
725 inline void swap_numbers(int *i1, int *i2)
726 {
727   int help = *i1;
728
729   *i1 = *i2;
730   *i2 = help;
731 }
732
733 inline void swap_number_pairs(int *x1, int *y1, int *x2, int *y2)
734 {
735   int help_x = *x1;
736   int help_y = *y1;
737
738   *x1 = *x2;
739   *x2 = help_x;
740
741   *y1 = *y2;
742   *y2 = help_y;
743 }
744
745 short getFile16BitInteger(FILE *file, int byte_order)
746 {
747   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
748     return ((fgetc(file) <<  8) |
749             (fgetc(file) <<  0));
750   else           /* BYTE_ORDER_LITTLE_ENDIAN */
751     return ((fgetc(file) <<  0) |
752             (fgetc(file) <<  8));
753 }
754
755 void putFile16BitInteger(FILE *file, short value, int byte_order)
756 {
757   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
758   {
759     fputc((value >>  8) & 0xff, file);
760     fputc((value >>  0) & 0xff, file);
761   }
762   else           /* BYTE_ORDER_LITTLE_ENDIAN */
763   {
764     fputc((value >>  0) & 0xff, file);
765     fputc((value >>  8) & 0xff, file);
766   }
767 }
768
769 int getFile32BitInteger(FILE *file, int byte_order)
770 {
771   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
772     return ((fgetc(file) << 24) |
773             (fgetc(file) << 16) |
774             (fgetc(file) <<  8) |
775             (fgetc(file) <<  0));
776   else           /* BYTE_ORDER_LITTLE_ENDIAN */
777     return ((fgetc(file) <<  0) |
778             (fgetc(file) <<  8) |
779             (fgetc(file) << 16) |
780             (fgetc(file) << 24));
781 }
782
783 void putFile32BitInteger(FILE *file, int value, int byte_order)
784 {
785   if (byte_order == BYTE_ORDER_BIG_ENDIAN)
786   {
787     fputc((value >> 24) & 0xff, file);
788     fputc((value >> 16) & 0xff, file);
789     fputc((value >>  8) & 0xff, file);
790     fputc((value >>  0) & 0xff, file);
791   }
792   else           /* BYTE_ORDER_LITTLE_ENDIAN */
793   {
794     fputc((value >>  0) & 0xff, file);
795     fputc((value >>  8) & 0xff, file);
796     fputc((value >> 16) & 0xff, file);
797     fputc((value >> 24) & 0xff, file);
798   }
799 }
800
801 boolean getFileChunk(FILE *file, char *chunk_name, int *chunk_size,
802                      int byte_order)
803 {
804   const int chunk_name_length = 4;
805
806   /* read chunk name */
807   fgets(chunk_name, chunk_name_length + 1, file);
808
809   if (chunk_size != NULL)
810   {
811     /* read chunk size */
812     *chunk_size = getFile32BitInteger(file, byte_order);
813   }
814
815   return (feof(file) || ferror(file) ? FALSE : TRUE);
816 }
817
818 void putFileChunk(FILE *file, char *chunk_name, int chunk_size,
819                   int byte_order)
820 {
821   /* write chunk name */
822   fputs(chunk_name, file);
823
824   if (chunk_size >= 0)
825   {
826     /* write chunk size */
827     putFile32BitInteger(file, chunk_size, byte_order);
828   }
829 }
830
831 int getFileVersion(FILE *file)
832 {
833   int version_major, version_minor, version_patch;
834
835   version_major = fgetc(file);
836   version_minor = fgetc(file);
837   version_patch = fgetc(file);
838   fgetc(file);          /* not used */
839
840   return VERSION_IDENT(version_major, version_minor, version_patch);
841 }
842
843 void putFileVersion(FILE *file, int version)
844 {
845   int version_major = VERSION_MAJOR(version);
846   int version_minor = VERSION_MINOR(version);
847   int version_patch = VERSION_PATCH(version);
848
849   fputc(version_major, file);
850   fputc(version_minor, file);
851   fputc(version_patch, file);
852   fputc(0, file);       /* not used */
853 }
854
855 void ReadUnusedBytesFromFile(FILE *file, unsigned long bytes)
856 {
857   while (bytes-- && !feof(file))
858     fgetc(file);
859 }
860
861 void WriteUnusedBytesToFile(FILE *file, unsigned long bytes)
862 {
863   while (bytes--)
864     fputc(0, file);
865 }
866
867
868 /* ------------------------------------------------------------------------- */
869 /* functions to translate key identifiers between different format           */
870 /* ------------------------------------------------------------------------- */
871
872 #define TRANSLATE_KEYSYM_TO_KEYNAME     0
873 #define TRANSLATE_KEYSYM_TO_X11KEYNAME  1
874 #define TRANSLATE_KEYNAME_TO_KEYSYM     2
875 #define TRANSLATE_X11KEYNAME_TO_KEYSYM  3
876
877 void translate_keyname(Key *keysym, char **x11name, char **name, int mode)
878 {
879   static struct
880   {
881     Key key;
882     char *x11name;
883     char *name;
884   } translate_key[] =
885   {
886     /* normal cursor keys */
887     { KSYM_Left,        "XK_Left",              "cursor left" },
888     { KSYM_Right,       "XK_Right",             "cursor right" },
889     { KSYM_Up,          "XK_Up",                "cursor up" },
890     { KSYM_Down,        "XK_Down",              "cursor down" },
891
892     /* keypad cursor keys */
893 #ifdef KSYM_KP_Left
894     { KSYM_KP_Left,     "XK_KP_Left",           "keypad left" },
895     { KSYM_KP_Right,    "XK_KP_Right",          "keypad right" },
896     { KSYM_KP_Up,       "XK_KP_Up",             "keypad up" },
897     { KSYM_KP_Down,     "XK_KP_Down",           "keypad down" },
898 #endif
899
900     /* other keypad keys */
901 #ifdef KSYM_KP_Enter
902     { KSYM_KP_Enter,    "XK_KP_Enter",          "keypad enter" },
903     { KSYM_KP_Add,      "XK_KP_Add",            "keypad +" },
904     { KSYM_KP_Subtract, "XK_KP_Subtract",       "keypad -" },
905     { KSYM_KP_Multiply, "XK_KP_Multiply",       "keypad mltply" },
906     { KSYM_KP_Divide,   "XK_KP_Divide",         "keypad /" },
907     { KSYM_KP_Separator,"XK_KP_Separator",      "keypad ," },
908 #endif
909
910     /* modifier keys */
911     { KSYM_Shift_L,     "XK_Shift_L",           "left shift" },
912     { KSYM_Shift_R,     "XK_Shift_R",           "right shift" },
913     { KSYM_Control_L,   "XK_Control_L",         "left control" },
914     { KSYM_Control_R,   "XK_Control_R",         "right control" },
915     { KSYM_Meta_L,      "XK_Meta_L",            "left meta" },
916     { KSYM_Meta_R,      "XK_Meta_R",            "right meta" },
917     { KSYM_Alt_L,       "XK_Alt_L",             "left alt" },
918     { KSYM_Alt_R,       "XK_Alt_R",             "right alt" },
919     { KSYM_Super_L,     "XK_Super_L",           "left super" },  /* Win-L */
920     { KSYM_Super_R,     "XK_Super_R",           "right super" }, /* Win-R */
921     { KSYM_Mode_switch, "XK_Mode_switch",       "mode switch" }, /* Alt-R */
922     { KSYM_Multi_key,   "XK_Multi_key",         "multi key" },   /* Ctrl-R */
923
924     /* some special keys */
925     { KSYM_BackSpace,   "XK_BackSpace",         "backspace" },
926     { KSYM_Delete,      "XK_Delete",            "delete" },
927     { KSYM_Insert,      "XK_Insert",            "insert" },
928     { KSYM_Tab,         "XK_Tab",               "tab" },
929     { KSYM_Home,        "XK_Home",              "home" },
930     { KSYM_End,         "XK_End",               "end" },
931     { KSYM_Page_Up,     "XK_Page_Up",           "page up" },
932     { KSYM_Page_Down,   "XK_Page_Down",         "page down" },
933     { KSYM_Menu,        "XK_Menu",              "menu" },        /* Win-Menu */
934
935     /* ASCII 0x20 to 0x40 keys (except numbers) */
936     { KSYM_space,       "XK_space",             "space" },
937     { KSYM_exclam,      "XK_exclam",            "!" },
938     { KSYM_quotedbl,    "XK_quotedbl",          "\"" },
939     { KSYM_numbersign,  "XK_numbersign",        "#" },
940     { KSYM_dollar,      "XK_dollar",            "$" },
941     { KSYM_percent,     "XK_percent",           "%" },
942     { KSYM_ampersand,   "XK_ampersand",         "&" },
943     { KSYM_apostrophe,  "XK_apostrophe",        "'" },
944     { KSYM_parenleft,   "XK_parenleft",         "(" },
945     { KSYM_parenright,  "XK_parenright",        ")" },
946     { KSYM_asterisk,    "XK_asterisk",          "*" },
947     { KSYM_plus,        "XK_plus",              "+" },
948     { KSYM_comma,       "XK_comma",             "," },
949     { KSYM_minus,       "XK_minus",             "-" },
950     { KSYM_period,      "XK_period",            "." },
951     { KSYM_slash,       "XK_slash",             "/" },
952     { KSYM_colon,       "XK_colon",             ":" },
953     { KSYM_semicolon,   "XK_semicolon",         ";" },
954     { KSYM_less,        "XK_less",              "<" },
955     { KSYM_equal,       "XK_equal",             "=" },
956     { KSYM_greater,     "XK_greater",           ">" },
957     { KSYM_question,    "XK_question",          "?" },
958     { KSYM_at,          "XK_at",                "@" },
959
960     /* more ASCII keys */
961     { KSYM_bracketleft, "XK_bracketleft",       "[" },
962     { KSYM_backslash,   "XK_backslash",         "backslash" },
963     { KSYM_bracketright,"XK_bracketright",      "]" },
964     { KSYM_asciicircum, "XK_asciicircum",       "circumflex" },
965     { KSYM_underscore,  "XK_underscore",        "_" },
966     { KSYM_grave,       "XK_grave",             "grave" },
967     { KSYM_quoteleft,   "XK_quoteleft",         "quote left" },
968     { KSYM_braceleft,   "XK_braceleft",         "brace left" },
969     { KSYM_bar,         "XK_bar",               "bar" },
970     { KSYM_braceright,  "XK_braceright",        "brace right" },
971     { KSYM_asciitilde,  "XK_asciitilde",        "ascii tilde" },
972
973     /* special (non-ASCII) keys */
974     { KSYM_Adiaeresis,  "XK_Adiaeresis",        "Ä" },
975     { KSYM_Odiaeresis,  "XK_Odiaeresis",        "Ö" },
976     { KSYM_Udiaeresis,  "XK_Udiaeresis",        "Ãœ" },
977     { KSYM_adiaeresis,  "XK_adiaeresis",        "ä" },
978     { KSYM_odiaeresis,  "XK_odiaeresis",        "ö" },
979     { KSYM_udiaeresis,  "XK_udiaeresis",        "ü" },
980     { KSYM_ssharp,      "XK_ssharp",            "sharp s" },
981
982     /* end-of-array identifier */
983     { 0,                NULL,                   NULL }
984   };
985
986   int i;
987
988   if (mode == TRANSLATE_KEYSYM_TO_KEYNAME)
989   {
990     static char name_buffer[30];
991     Key key = *keysym;
992
993     if (key >= KSYM_A && key <= KSYM_Z)
994       sprintf(name_buffer, "%c", 'A' + (char)(key - KSYM_A));
995     else if (key >= KSYM_a && key <= KSYM_z)
996       sprintf(name_buffer, "%c", 'a' + (char)(key - KSYM_a));
997     else if (key >= KSYM_0 && key <= KSYM_9)
998       sprintf(name_buffer, "%c", '0' + (char)(key - KSYM_0));
999     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1000       sprintf(name_buffer, "keypad %c", '0' + (char)(key - KSYM_KP_0));
1001     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1002       sprintf(name_buffer, "function F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1003     else if (key == KSYM_UNDEFINED)
1004       strcpy(name_buffer, "(undefined)");
1005     else
1006     {
1007       i = 0;
1008
1009       do
1010       {
1011         if (key == translate_key[i].key)
1012         {
1013           strcpy(name_buffer, translate_key[i].name);
1014           break;
1015         }
1016       }
1017       while (translate_key[++i].name);
1018
1019       if (!translate_key[i].name)
1020         strcpy(name_buffer, "(unknown)");
1021     }
1022
1023     *name = name_buffer;
1024   }
1025   else if (mode == TRANSLATE_KEYSYM_TO_X11KEYNAME)
1026   {
1027     static char name_buffer[30];
1028     Key key = *keysym;
1029
1030     if (key >= KSYM_A && key <= KSYM_Z)
1031       sprintf(name_buffer, "XK_%c", 'A' + (char)(key - KSYM_A));
1032     else if (key >= KSYM_a && key <= KSYM_z)
1033       sprintf(name_buffer, "XK_%c", 'a' + (char)(key - KSYM_a));
1034     else if (key >= KSYM_0 && key <= KSYM_9)
1035       sprintf(name_buffer, "XK_%c", '0' + (char)(key - KSYM_0));
1036     else if (key >= KSYM_KP_0 && key <= KSYM_KP_9)
1037       sprintf(name_buffer, "XK_KP_%c", '0' + (char)(key - KSYM_KP_0));
1038     else if (key >= KSYM_FKEY_FIRST && key <= KSYM_FKEY_LAST)
1039       sprintf(name_buffer, "XK_F%d", (int)(key - KSYM_FKEY_FIRST + 1));
1040     else if (key == KSYM_UNDEFINED)
1041       strcpy(name_buffer, "[undefined]");
1042     else
1043     {
1044       i = 0;
1045
1046       do
1047       {
1048         if (key == translate_key[i].key)
1049         {
1050           strcpy(name_buffer, translate_key[i].x11name);
1051           break;
1052         }
1053       }
1054       while (translate_key[++i].x11name);
1055
1056       if (!translate_key[i].x11name)
1057         sprintf(name_buffer, "0x%04lx", (unsigned long)key);
1058     }
1059
1060     *x11name = name_buffer;
1061   }
1062   else if (mode == TRANSLATE_KEYNAME_TO_KEYSYM)
1063   {
1064     Key key = KSYM_UNDEFINED;
1065
1066     i = 0;
1067     do
1068     {
1069       if (strcmp(translate_key[i].name, *name) == 0)
1070       {
1071         key = translate_key[i].key;
1072         break;
1073       }
1074     }
1075     while (translate_key[++i].x11name);
1076
1077     if (key == KSYM_UNDEFINED)
1078       Error(ERR_WARN, "getKeyFromKeyName(): not completely implemented");
1079
1080     *keysym = key;
1081   }
1082   else if (mode == TRANSLATE_X11KEYNAME_TO_KEYSYM)
1083   {
1084     Key key = KSYM_UNDEFINED;
1085     char *name_ptr = *x11name;
1086
1087     if (strncmp(name_ptr, "XK_", 3) == 0 && strlen(name_ptr) == 4)
1088     {
1089       char c = name_ptr[3];
1090
1091       if (c >= 'A' && c <= 'Z')
1092         key = KSYM_A + (Key)(c - 'A');
1093       else if (c >= 'a' && c <= 'z')
1094         key = KSYM_a + (Key)(c - 'a');
1095       else if (c >= '0' && c <= '9')
1096         key = KSYM_0 + (Key)(c - '0');
1097     }
1098     else if (strncmp(name_ptr, "XK_KP_", 6) == 0 && strlen(name_ptr) == 7)
1099     {
1100       char c = name_ptr[6];
1101
1102       if (c >= '0' && c <= '9')
1103         key = KSYM_0 + (Key)(c - '0');
1104     }
1105     else if (strncmp(name_ptr, "XK_F", 4) == 0 && strlen(name_ptr) <= 6)
1106     {
1107       char c1 = name_ptr[4];
1108       char c2 = name_ptr[5];
1109       int d = 0;
1110
1111       if ((c1 >= '0' && c1 <= '9') &&
1112           ((c2 >= '0' && c1 <= '9') || c2 == '\0'))
1113         d = atoi(&name_ptr[4]);
1114
1115       if (d >= 1 && d <= KSYM_NUM_FKEYS)
1116         key = KSYM_F1 + (Key)(d - 1);
1117     }
1118     else if (strncmp(name_ptr, "XK_", 3) == 0)
1119     {
1120       i = 0;
1121
1122       do
1123       {
1124         if (strcmp(name_ptr, translate_key[i].x11name) == 0)
1125         {
1126           key = translate_key[i].key;
1127           break;
1128         }
1129       }
1130       while (translate_key[++i].x11name);
1131     }
1132     else if (strncmp(name_ptr, "0x", 2) == 0)
1133     {
1134       unsigned long value = 0;
1135
1136       name_ptr += 2;
1137
1138       while (name_ptr)
1139       {
1140         char c = *name_ptr++;
1141         int d = -1;
1142
1143         if (c >= '0' && c <= '9')
1144           d = (int)(c - '0');
1145         else if (c >= 'a' && c <= 'f')
1146           d = (int)(c - 'a' + 10);
1147         else if (c >= 'A' && c <= 'F')
1148           d = (int)(c - 'A' + 10);
1149
1150         if (d == -1)
1151         {
1152           value = -1;
1153           break;
1154         }
1155
1156         value = value * 16 + d;
1157       }
1158
1159       if (value != -1)
1160         key = (Key)value;
1161     }
1162
1163     *keysym = key;
1164   }
1165 }
1166
1167 char *getKeyNameFromKey(Key key)
1168 {
1169   char *name;
1170
1171   translate_keyname(&key, NULL, &name, TRANSLATE_KEYSYM_TO_KEYNAME);
1172   return name;
1173 }
1174
1175 char *getX11KeyNameFromKey(Key key)
1176 {
1177   char *x11name;
1178
1179   translate_keyname(&key, &x11name, NULL, TRANSLATE_KEYSYM_TO_X11KEYNAME);
1180   return x11name;
1181 }
1182
1183 Key getKeyFromKeyName(char *name)
1184 {
1185   Key key;
1186
1187   translate_keyname(&key, NULL, &name, TRANSLATE_KEYNAME_TO_KEYSYM);
1188   return key;
1189 }
1190
1191 Key getKeyFromX11KeyName(char *x11name)
1192 {
1193   Key key;
1194
1195   translate_keyname(&key, &x11name, NULL, TRANSLATE_X11KEYNAME_TO_KEYSYM);
1196   return key;
1197 }
1198
1199 char getCharFromKey(Key key)
1200 {
1201   char *keyname = getKeyNameFromKey(key);
1202   char letter = 0;
1203
1204   if (strlen(keyname) == 1)
1205     letter = keyname[0];
1206   else if (strcmp(keyname, "space") == 0)
1207     letter = ' ';
1208   else if (strcmp(keyname, "circumflex") == 0)
1209     letter = '^';
1210
1211   return letter;
1212 }
1213
1214
1215 /* ========================================================================= */
1216 /* functions for checking filenames                                          */
1217 /* ========================================================================= */
1218
1219 boolean FileIsGraphic(char *filename)
1220 {
1221   if (strlen(filename) > 4 &&
1222       strcmp(&filename[strlen(filename) - 4], ".pcx") == 0)
1223     return TRUE;
1224
1225   return FALSE;
1226 }
1227
1228 boolean FileIsSound(char *basename)
1229 {
1230   if (strlen(basename) > 4 &&
1231       strcmp(&basename[strlen(basename) - 4], ".wav") == 0)
1232     return TRUE;
1233
1234   return FALSE;
1235 }
1236
1237 boolean FileIsMusic(char *basename)
1238 {
1239   /* "music" can be a WAV (loop) file or (if compiled with SDL) a MOD file */
1240
1241   if (FileIsSound(basename))
1242     return TRUE;
1243
1244 #if defined(TARGET_SDL)
1245   if (strlen(basename) > 4 &&
1246       (strcmp(&basename[strlen(basename) - 4], ".mod") == 0 ||
1247        strcmp(&basename[strlen(basename) - 4], ".MOD") == 0 ||
1248        strncmp(basename, "mod.", 4) == 0 ||
1249        strncmp(basename, "MOD.", 4) == 0))
1250     return TRUE;
1251 #endif
1252
1253   return FALSE;
1254 }
1255
1256 boolean FileIsArtworkType(char *basename, int type)
1257 {
1258   if ((type == TREE_TYPE_GRAPHICS_DIR && FileIsGraphic(basename)) ||
1259       (type == TREE_TYPE_SOUNDS_DIR && FileIsSound(basename)) ||
1260       (type == TREE_TYPE_MUSIC_DIR && FileIsMusic(basename)))
1261     return TRUE;
1262
1263   return FALSE;
1264 }
1265
1266
1267 /* ========================================================================= */
1268 /* functions only needed for non-Unix (non-command-line) systems             */
1269 /* (MS-DOS only; SDL/Windows creates files "stdout.txt" and "stderr.txt")    */
1270 /* ========================================================================= */
1271
1272 #if defined(PLATFORM_MSDOS)
1273
1274 #define ERROR_FILENAME          "stderr.txt"
1275
1276 void initErrorFile()
1277 {
1278   unlink(ERROR_FILENAME);
1279 }
1280
1281 FILE *openErrorFile()
1282 {
1283   return fopen(ERROR_FILENAME, MODE_APPEND);
1284 }
1285
1286 void dumpErrorFile()
1287 {
1288   FILE *error_file = fopen(ERROR_FILENAME, MODE_READ);
1289
1290   if (error_file != NULL)
1291   {
1292     while (!feof(error_file))
1293       fputc(fgetc(error_file), stderr);
1294
1295     fclose(error_file);
1296   }
1297 }
1298 #endif
1299
1300
1301 /* ========================================================================= */
1302 /* the following is only for debugging purpose and normally not used         */
1303 /* ========================================================================= */
1304
1305 #define DEBUG_NUM_TIMESTAMPS    3
1306
1307 void debug_print_timestamp(int counter_nr, char *message)
1308 {
1309   static long counter[DEBUG_NUM_TIMESTAMPS][2];
1310
1311   if (counter_nr >= DEBUG_NUM_TIMESTAMPS)
1312     Error(ERR_EXIT, "debugging: increase DEBUG_NUM_TIMESTAMPS in misc.c");
1313
1314   counter[counter_nr][0] = Counter();
1315
1316   if (message)
1317     printf("%s %.2f seconds\n", message,
1318            (float)(counter[counter_nr][0] - counter[counter_nr][1]) / 1000);
1319
1320   counter[counter_nr][1] = Counter();
1321 }