rnd-20020323-2-src
[rocksndiamonds.git] / src / libgame / system.c
1 /***********************************************************
2 * Artsoft Retro-Game Library                               *
3 *----------------------------------------------------------*
4 * (c) 1994-2001 Artsoft Entertainment                      *
5 *               Holger Schemel                             *
6 *               Detmolder Strasse 189                      *
7 *               33604 Bielefeld                            *
8 *               Germany                                    *
9 *               e-mail: info@artsoft.org                   *
10 *----------------------------------------------------------*
11 * system.c                                                 *
12 ***********************************************************/
13
14 #include <string.h>
15 #include <signal.h>
16
17 #include "platform.h"
18
19 #if defined(PLATFORM_MSDOS)
20 #include <fcntl.h>
21 #endif
22
23 #include "system.h"
24 #include "sound.h"
25 #include "setup.h"
26 #include "misc.h"
27
28
29 /* ========================================================================= */
30 /* exported variables                                                        */
31 /* ========================================================================= */
32
33 struct ProgramInfo      program;
34 struct OptionInfo       options;
35 struct VideoSystemInfo  video;
36 struct AudioSystemInfo  audio;
37 struct GfxInfo          gfx;
38 struct JoystickInfo     joystick;
39 struct SetupInfo        setup;
40
41 struct LevelDirInfo    *leveldir_first = NULL;
42 struct LevelDirInfo    *leveldir_current = NULL;
43 int                     level_nr;
44
45 Display                *display = NULL;
46 Visual                 *visual = NULL;
47 int                     screen = 0;
48 Colormap                cmap = None;
49
50 DrawWindow             *window = NULL;
51 DrawBuffer             *backbuffer = NULL;
52 DrawBuffer             *drawto = NULL;
53
54 int                     button_status = MB_NOT_PRESSED;
55 boolean                 motion_status = FALSE;
56
57 int                     redraw_mask = REDRAW_NONE;
58 int                     redraw_tiles = 0;
59
60 int                     FrameCounter = 0;
61
62
63 /* ========================================================================= */
64 /* init/close functions                                                      */
65 /* ========================================================================= */
66
67 void InitCommandName(char *argv0)
68 {
69   program.command_basename =
70     (strrchr(argv0, '/') ? strrchr(argv0, '/') + 1 : argv0);
71 }
72
73 void InitExitFunction(void (*exit_function)(int))
74 {
75   program.exit_function = exit_function;
76
77   /* set signal handlers to custom exit function */
78   signal(SIGINT, exit_function);
79   signal(SIGTERM, exit_function);
80
81 #if defined(TARGET_SDL)
82   /* set exit function to automatically cleanup SDL stuff after exit() */
83   atexit(SDL_Quit);
84 #endif
85 }
86
87 void InitPlatformDependantStuff(void)
88 {
89 #if defined(PLATFORM_MSDOS)
90   _fmode = O_BINARY;
91 #endif
92
93 #if !defined(PLATFORM_UNIX)
94   program.userdata_directory = "userdata";
95   initErrorFile();
96 #endif
97
98 #if defined(TARGET_SDL)
99   if (SDL_Init(SDL_INIT_EVENTTHREAD | SDL_INIT_NOPARACHUTE) < 0)
100     Error(ERR_EXIT, "SDL_Init() failed: %s", SDL_GetError());
101 #endif
102 }
103
104 void ClosePlatformDependantStuff(void)
105 {
106 #if !defined(PLATFORM_UNIX)
107   dumpErrorFile();
108 #endif
109 }
110
111 void InitProgramInfo(char *unix_userdata_directory, char *program_title,
112                      char *window_title, char *icon_title,
113                      char *x11_icon_basename, char *x11_iconmask_basename,
114                      char *msdos_pointer_basename)
115 {
116   char *x11_icon_filename =
117     getPath2(options.graphics_directory, x11_icon_basename);
118   char *x11_iconmask_filename =
119     getPath2(options.graphics_directory, x11_iconmask_basename);
120   char *msdos_pointer_filename =
121     getPath2(options.graphics_directory, msdos_pointer_basename);
122
123 #if defined(PLATFORM_UNIX)
124   program.userdata_directory = unix_userdata_directory;
125 #else
126   program.userdata_directory = "userdata";
127 #endif
128
129   program.program_title = program_title;
130   program.window_title = window_title;
131   program.icon_title = icon_title;
132   program.x11_icon_filename = x11_icon_filename;
133   program.x11_iconmask_filename = x11_iconmask_filename;
134   program.msdos_pointer_filename = msdos_pointer_filename;
135 }
136
137 void InitGfxFieldInfo(int sx, int sy, int sxsize, int sysize,
138                       int real_sx, int real_sy,
139                       int full_sxsize, int full_sysize)
140 {
141   gfx.sx = sx;
142   gfx.sy = sy;
143   gfx.sxsize = sxsize;
144   gfx.sysize = sysize;
145   gfx.real_sx = real_sx;
146   gfx.real_sy = real_sy;
147   gfx.full_sxsize = full_sxsize;
148   gfx.full_sysize = full_sysize;
149 }
150
151 void InitGfxDoor1Info(int dx, int dy, int dxsize, int dysize)
152 {
153   gfx.dx = dx;
154   gfx.dy = dy;
155   gfx.dxsize = dxsize;
156   gfx.dysize = dysize;
157 }
158
159 void InitGfxDoor2Info(int vx, int vy, int vxsize, int vysize)
160 {
161   gfx.vx = vx;
162   gfx.vy = vy;
163   gfx.vxsize = vxsize;
164   gfx.vysize = vysize;
165 }
166
167 void InitGfxScrollbufferInfo(int scrollbuffer_width, int scrollbuffer_height)
168 {
169   /* currently only used by MSDOS code to alloc VRAM buffer, if available */
170   gfx.scrollbuffer_width = scrollbuffer_width;
171   gfx.scrollbuffer_height = scrollbuffer_height;
172 }
173
174
175 /* ========================================================================= */
176 /* video functions                                                           */
177 /* ========================================================================= */
178
179 inline static int GetRealDepth(int depth)
180 {
181   return (depth == DEFAULT_DEPTH ? video.default_depth : depth);
182 }
183
184 inline void InitVideoDisplay(void)
185 {
186 #if defined(TARGET_SDL)
187   SDLInitVideoDisplay();
188 #else
189   X11InitVideoDisplay();
190 #endif
191 }
192
193 inline void CloseVideoDisplay(void)
194 {
195   KeyboardAutoRepeatOn();
196
197 #if defined(TARGET_SDL)
198   SDL_QuitSubSystem(SDL_INIT_VIDEO);
199 #else
200   if (display)
201     XCloseDisplay(display);
202 #endif
203 }
204
205 inline void InitVideoBuffer(DrawBuffer **backbuffer, DrawWindow **window,
206                             int width, int height, int depth,
207                             boolean fullscreen)
208 {
209   video.width = width;
210   video.height = height;
211   video.depth = GetRealDepth(depth);
212   video.fullscreen_available = FULLSCREEN_STATUS;
213   video.fullscreen_enabled = FALSE;
214
215 #ifdef TARGET_SDL
216   SDLInitVideoBuffer(backbuffer, window, fullscreen);
217 #else
218   X11InitVideoBuffer(backbuffer, window);
219 #endif
220 }
221
222 inline Bitmap *CreateBitmapStruct(void)
223 {
224 #ifdef TARGET_SDL
225   return checked_calloc(sizeof(struct SDLSurfaceInfo));
226 #else
227   return checked_calloc(sizeof(struct X11DrawableInfo));
228 #endif
229 }
230
231 inline Bitmap *CreateBitmap(int width, int height, int depth)
232 {
233   Bitmap *new_bitmap = CreateBitmapStruct();
234   int real_depth = GetRealDepth(depth);
235
236 #ifdef TARGET_SDL
237   SDL_Surface *surface_tmp, *surface_native;
238
239   if ((surface_tmp = SDL_CreateRGBSurface(SURFACE_FLAGS, width, height,
240                                           real_depth, 0, 0, 0, 0))
241       == NULL)
242     Error(ERR_EXIT, "SDL_CreateRGBSurface() failed: %s", SDL_GetError());
243
244   if ((surface_native = SDL_DisplayFormat(surface_tmp)) == NULL)
245     Error(ERR_EXIT, "SDL_DisplayFormat() failed: %s", SDL_GetError());
246
247   SDL_FreeSurface(surface_tmp);
248
249   new_bitmap->surface = surface_native;
250 #else
251   Pixmap pixmap;
252
253   if ((pixmap = XCreatePixmap(display, window->drawable,
254                               width, height, real_depth))
255       == None)
256     Error(ERR_EXIT, "cannot create pixmap");
257
258   new_bitmap->drawable = pixmap;
259
260   if (window == NULL)
261     Error(ERR_EXIT, "Window GC needed for Bitmap -- create Window first");
262
263   new_bitmap->gc = window->gc;
264
265   new_bitmap->line_gc[0] = window->line_gc[0];
266   new_bitmap->line_gc[1] = window->line_gc[1];
267 #endif
268
269   return new_bitmap;
270 }
271
272 inline void FreeBitmap(Bitmap *bitmap)
273 {
274   if (bitmap == NULL)
275     return;
276
277 #ifdef TARGET_SDL
278   if (bitmap->surface)
279     SDL_FreeSurface(bitmap->surface);
280   if (bitmap->surface_masked)
281     SDL_FreeSurface(bitmap->surface_masked);
282 #else
283   if (bitmap->drawable)
284     XFreePixmap(display, bitmap->drawable);
285   if (bitmap->clip_mask)
286     XFreePixmap(display, bitmap->clip_mask);
287   if (bitmap->stored_clip_gc)
288     XFreeGC(display, bitmap->stored_clip_gc);
289 #endif
290
291   free(bitmap);
292 }
293
294 inline void CloseWindow(DrawWindow *window)
295 {
296 #ifdef TARGET_X11
297   if (window->drawable)
298   {
299     XUnmapWindow(display, window->drawable);
300     XDestroyWindow(display, window->drawable);
301   }
302   if (window->gc)
303     XFreeGC(display, window->gc);
304 #endif
305 }
306
307 inline void BlitBitmap(Bitmap *src_bitmap, Bitmap *dst_bitmap,
308                        int src_x, int src_y,
309                        int width, int height,
310                        int dst_x, int dst_y)
311 {
312 #ifdef TARGET_SDL
313   SDLCopyArea(src_bitmap, dst_bitmap,
314               src_x, src_y, width, height, dst_x, dst_y, SDLCOPYAREA_OPAQUE);
315 #else
316   XCopyArea(display, src_bitmap->drawable, dst_bitmap->drawable,
317             dst_bitmap->gc, src_x, src_y, width, height, dst_x, dst_y);
318 #endif
319 }
320
321 inline void ClearRectangle(Bitmap *bitmap, int x, int y, int width, int height)
322 {
323 #ifdef TARGET_SDL
324   SDLFillRectangle(bitmap, x, y, width, height, 0x000000);
325 #else
326   XFillRectangle(display, bitmap->drawable, bitmap->gc, x, y, width, height);
327 #endif
328 }
329
330 #if 0
331 #ifndef TARGET_SDL
332 static GC last_clip_gc = 0;     /* needed for XCopyArea() through clip mask */
333 #endif
334 #endif
335
336 inline void SetClipMask(Bitmap *bitmap, GC clip_gc, Pixmap clip_pixmap)
337 {
338 #ifdef TARGET_X11
339   if (clip_gc)
340   {
341     bitmap->clip_gc = clip_gc;
342     XSetClipMask(display, bitmap->clip_gc, clip_pixmap);
343   }
344 #if 0
345   last_clip_gc = clip_gc;
346 #endif
347 #endif
348 }
349
350 inline void SetClipOrigin(Bitmap *bitmap, GC clip_gc, int clip_x, int clip_y)
351 {
352 #ifdef TARGET_X11
353   if (clip_gc)
354   {
355     bitmap->clip_gc = clip_gc;
356     XSetClipOrigin(display, bitmap->clip_gc, clip_x, clip_y);
357   }
358 #if 0
359   last_clip_gc = clip_gc;
360 #endif
361 #endif
362 }
363
364 inline void BlitBitmapMasked(Bitmap *src_bitmap, Bitmap *dst_bitmap,
365                              int src_x, int src_y,
366                              int width, int height,
367                              int dst_x, int dst_y)
368 {
369 #ifdef TARGET_SDL
370   SDLCopyArea(src_bitmap, dst_bitmap,
371               src_x, src_y, width, height, dst_x, dst_y, SDLCOPYAREA_MASKED);
372 #else
373   XCopyArea(display, src_bitmap->drawable, dst_bitmap->drawable,
374             src_bitmap->clip_gc, src_x, src_y, width, height, dst_x, dst_y);
375 #endif
376 }
377
378 inline void DrawSimpleWhiteLine(Bitmap *bitmap, int from_x, int from_y,
379                                 int to_x, int to_y)
380 {
381 #ifdef TARGET_SDL
382   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, 0xffffff);
383 #else
384   XSetForeground(display, bitmap->gc, WhitePixel(display, screen));
385   XDrawLine(display, bitmap->drawable, bitmap->gc, from_x, from_y, to_x, to_y);
386   XSetForeground(display, bitmap->gc, BlackPixel(display, screen));
387 #endif
388 }
389
390 #if !defined(TARGET_X11_NATIVE)
391 inline void DrawLine(Bitmap *bitmap, int from_x, int from_y,
392                      int to_x, int to_y, Pixel pixel, int line_width)
393 {
394   int x, y;
395
396   for (x=0; x<line_width; x++)
397   {
398     for (y=0; y<line_width; y++)
399     {
400       int dx = x - line_width / 2;
401       int dy = y - line_width / 2;
402
403       if ((x == 0 && y == 0) ||
404           (x == 0 && y == line_width - 1) ||
405           (x == line_width - 1 && y == 0) ||
406           (x == line_width - 1 && y == line_width - 1))
407         continue;
408
409 #if defined(TARGET_SDL)
410       SDLDrawLine(bitmap,
411                   from_x + dx, from_y + dy, to_x + dx, to_y + dy, pixel);
412 #elif defined(TARGET_ALLEGRO)
413       AllegroDrawLine(bitmap->drawable, from_x + dx, from_y + dy,
414                       to_x + dx, to_y + dy, pixel);
415 #endif
416     }
417   }
418 }
419 #endif
420
421 inline void DrawLines(Bitmap *bitmap, struct XY *points, int num_points,
422                       Pixel pixel)
423 {
424 #if !defined(TARGET_X11_NATIVE)
425   int line_width = 4;
426   int i;
427
428   for (i=0; i<num_points - 1; i++)
429     DrawLine(bitmap, points[i].x, points[i].y,
430              points[i + 1].x, points[i + 1].y, pixel, line_width);
431
432   /*
433   SDLDrawLines(bitmap->surface, points, num_points, pixel);
434   */
435 #else
436   XSetForeground(display, bitmap->line_gc[1], pixel);
437   XDrawLines(display, bitmap->drawable, bitmap->line_gc[1],
438              (XPoint *)points, num_points, CoordModeOrigin);
439   /*
440   XSetForeground(display, gc, BlackPixel(display, screen));
441   */
442 #endif
443 }
444
445 inline Pixel GetPixel(Bitmap *bitmap, int x, int y)
446 {
447 #if defined(TARGET_SDL)
448   return SDLGetPixel(bitmap, x, y);
449 #elif defined(TARGET_ALLEGRO)
450   return AllegroGetPixel(bitmap->drawable, x, y);
451 #else
452   unsigned long pixel_value;
453   XImage *pixel_image;
454
455   pixel_image = XGetImage(display, bitmap->drawable, x, y, 1, 1,
456                           AllPlanes, ZPixmap);
457   pixel_value = XGetPixel(pixel_image, 0, 0);
458
459   XDestroyImage(pixel_image);
460
461   return pixel_value;
462 #endif
463 }
464
465 inline Pixel GetPixelFromRGB(Bitmap *bitmap, unsigned int color_r,
466                              unsigned int color_g, unsigned int color_b)
467 {
468   Pixel pixel;
469
470 #if defined(TARGET_SDL)
471   pixel = SDL_MapRGB(bitmap->surface->format, color_r, color_g, color_b);
472 #elif defined(TARGET_ALLEGRO)
473   pixel = AllegroAllocColorCell(color_r << 8, color_g << 8, color_b << 8);
474 #elif defined(TARGET_X11_NATIVE)
475   XColor xcolor;
476
477   xcolor.flags = DoRed | DoGreen | DoBlue;
478   xcolor.red = (color_r << 8);
479   xcolor.green = (color_g << 8);
480   xcolor.blue = (color_b << 8);
481   XAllocColor(display, cmap, &xcolor);
482   pixel = xcolor.pixel;
483 #endif
484
485   return pixel;
486 }
487
488 inline Pixel GetPixelFromRGBcompact(Bitmap *bitmap, unsigned int color)
489 {
490   unsigned int color_r = (color >> 16) & 0xff;
491   unsigned int color_g = (color >>  8) & 0xff;
492   unsigned int color_b = (color >>  0) & 0xff;
493
494   return GetPixelFromRGB(bitmap, color_r, color_g, color_b);
495 }
496
497 /* execute all pending screen drawing operations */
498 inline void FlushDisplay(void)
499 {
500 #ifndef TARGET_SDL
501   XFlush(display);
502 #endif
503 }
504
505 /* execute and wait for all pending screen drawing operations */
506 inline void SyncDisplay(void)
507 {
508 #ifndef TARGET_SDL
509   XSync(display, FALSE);
510 #endif
511 }
512
513 inline void KeyboardAutoRepeatOn(void)
514 {
515 #ifdef TARGET_SDL
516   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY / 2,
517                       SDL_DEFAULT_REPEAT_INTERVAL / 2);
518   SDL_EnableUNICODE(1);
519 #else
520   if (display)
521     XAutoRepeatOn(display);
522 #endif
523 }
524
525 inline void KeyboardAutoRepeatOff(void)
526 {
527 #ifdef TARGET_SDL
528   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
529   SDL_EnableUNICODE(0);
530 #else
531   if (display)
532     XAutoRepeatOff(display);
533 #endif
534 }
535
536 inline boolean PointerInWindow(DrawWindow *window)
537 {
538 #ifdef TARGET_SDL
539   return TRUE;
540 #else
541   Window root, child;
542   int root_x, root_y;
543   unsigned int mask;
544   int win_x, win_y;
545
546   /* if XQueryPointer() returns False, the pointer
547      is not on the same screen as the specified window */
548   return XQueryPointer(display, window->drawable, &root, &child,
549                        &root_x, &root_y, &win_x, &win_y, &mask);
550 #endif
551 }
552
553 inline boolean SetVideoMode(boolean fullscreen)
554 {
555 #ifdef TARGET_SDL
556   return SDLSetVideoMode(&backbuffer, fullscreen);
557 #else
558   boolean success = TRUE;
559
560   if (fullscreen && video.fullscreen_available)
561   {
562     Error(ERR_WARN, "fullscreen not available in X11 version");
563
564     /* display error message only once */
565     video.fullscreen_available = FALSE;
566
567     success = FALSE;
568   }
569
570   return success;
571 #endif
572 }
573
574 inline boolean ChangeVideoModeIfNeeded(boolean fullscreen)
575 {
576 #ifdef TARGET_SDL
577   if ((fullscreen && !video.fullscreen_enabled && video.fullscreen_available)||
578       (!fullscreen && video.fullscreen_enabled))
579     fullscreen = SetVideoMode(fullscreen);
580 #endif
581
582   return fullscreen;
583 }
584
585 Bitmap *LoadImage(char *basename)
586 {
587   Bitmap *new_bitmap;
588   char *filename = getPath2(options.graphics_directory, basename);
589
590 #if defined(TARGET_SDL)
591   new_bitmap = SDLLoadImage(filename);
592 #else
593   new_bitmap = X11LoadImage(filename);
594 #endif
595
596   free(filename);
597
598   return new_bitmap;
599 }
600
601
602 /* ========================================================================= */
603 /* audio functions                                                           */
604 /* ========================================================================= */
605
606 inline void OpenAudio(void)
607 {
608   /* always start with reliable default values */
609   audio.sound_available = FALSE;
610   audio.music_available = FALSE;
611   audio.loops_available = FALSE;
612   audio.mods_available = FALSE;
613   audio.sound_enabled = FALSE;
614
615   audio.soundserver_pipe[0] = audio.soundserver_pipe[1] = 0;
616   audio.soundserver_pid = 0;
617   audio.device_name = NULL;
618   audio.device_fd = 0;
619
620   audio.channels = 0;
621   audio.music_channel = 0;
622   audio.music_nr = 0;
623
624 #if defined(TARGET_SDL)
625   SDLOpenAudio();
626 #elif defined(PLATFORM_MSDOS)
627   MSDOSOpenAudio();
628 #elif defined(PLATFORM_UNIX)
629   UnixOpenAudio();
630 #endif
631 }
632
633 inline void CloseAudio(void)
634 {
635 #if defined(TARGET_SDL)
636   SDLCloseAudio();
637 #elif defined(PLATFORM_MSDOS)
638   MSDOSCloseAudio();
639 #elif defined(PLATFORM_UNIX)
640   UnixCloseAudio();
641 #endif
642
643   audio.sound_enabled = FALSE;
644 }
645
646 inline void SetAudioMode(boolean enabled)
647 {
648   if (!audio.sound_available)
649     return;
650
651   audio.sound_enabled = enabled;
652 }
653
654
655 /* ========================================================================= */
656 /* event functions                                                           */
657 /* ========================================================================= */
658
659 inline void InitEventFilter(EventFilter filter_function)
660 {
661 #ifdef TARGET_SDL
662   /* set event filter to filter out certain events */
663   SDL_SetEventFilter(filter_function);
664 #endif
665 }
666
667 inline boolean PendingEvent(void)
668 {
669 #ifdef TARGET_SDL
670   return (SDL_PollEvent(NULL) ? TRUE : FALSE);
671 #else
672   return (XPending(display) ? TRUE : FALSE);
673 #endif
674 }
675
676 inline void NextEvent(Event *event)
677 {
678 #ifdef TARGET_SDL
679   SDLNextEvent(event);
680 #else
681   XNextEvent(display, event);
682 #endif
683 }
684
685 inline Key GetEventKey(KeyEvent *event, boolean with_modifiers)
686 {
687 #ifdef TARGET_SDL
688 #if 0
689   printf("unicode == '%d', sym == '%d', mod == '0x%04x'\n",
690          (int)event->keysym.unicode,
691          (int)event->keysym.sym,
692          (int)SDL_GetModState());
693 #endif
694
695   if (with_modifiers && event->keysym.unicode != 0)
696     return event->keysym.unicode;
697   else
698     return event->keysym.sym;
699 #else
700 #if 0
701   printf("with modifiers == '0x%04x', without modifiers == '0x%04x'\n",
702          (int)XLookupKeysym(event, event->state),
703          (int)XLookupKeysym(event, 0));
704 #endif
705
706   if (with_modifiers)
707     return XLookupKeysym(event, event->state);
708   else
709     return XLookupKeysym(event, 0);
710 #endif
711 }
712
713 inline boolean CheckCloseWindowEvent(ClientMessageEvent *event)
714 {
715   if (event->type != EVENT_CLIENTMESSAGE)
716     return FALSE;
717
718 #if defined(TARGET_SDL)
719   return TRUE;          /* the only possible message here is SDL_QUIT */
720 #elif defined(PLATFORM_UNIX)
721   if ((event->window == window->drawable) &&
722       (event->data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", FALSE)))
723     return TRUE;
724 #endif
725
726   return FALSE;
727 }
728
729
730 inline void dummy(void)
731 {
732 #ifdef TARGET_SDL
733 #else
734 #endif
735 }