rnd-20060726-6-src
[rocksndiamonds.git] / src / libgame / system.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 * 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 "image.h"
25 #include "sound.h"
26 #include "setup.h"
27 #include "joystick.h"
28 #include "misc.h"
29
30
31 /* ========================================================================= */
32 /* exported variables                                                        */
33 /* ========================================================================= */
34
35 struct ProgramInfo      program;
36 struct OptionInfo       options;
37 struct VideoSystemInfo  video;
38 struct AudioSystemInfo  audio;
39 struct GfxInfo          gfx;
40 struct ArtworkInfo      artwork;
41 struct JoystickInfo     joystick;
42 struct SetupInfo        setup;
43
44 LevelDirTree           *leveldir_first_all = NULL;
45 LevelDirTree           *leveldir_first = NULL;
46 LevelDirTree           *leveldir_current = NULL;
47 int                     level_nr;
48
49 Display                *display = NULL;
50 Visual                 *visual = NULL;
51 int                     screen = 0;
52 Colormap                cmap = None;
53
54 DrawWindow             *window = NULL;
55 DrawBuffer             *backbuffer = NULL;
56 DrawBuffer             *drawto = NULL;
57
58 int                     button_status = MB_NOT_PRESSED;
59 boolean                 motion_status = FALSE;
60
61 int                     redraw_mask = REDRAW_NONE;
62 int                     redraw_tiles = 0;
63
64 int                     FrameCounter = 0;
65
66
67 /* ========================================================================= */
68 /* init/close functions                                                      */
69 /* ========================================================================= */
70
71 void InitProgramInfo(char *argv0,
72                      char *userdata_directory, char *program_title,
73                      char *window_title, char *icon_title,
74                      char *x11_icon_filename, char *x11_iconmask_filename,
75                      char *msdos_cursor_filename,
76                      char *cookie_prefix, char *filename_prefix,
77                      int program_version)
78 {
79   program.command_basepath = getBasePath(argv0);
80   program.command_basename = getBaseName(argv0);
81
82   program.userdata_directory = userdata_directory;
83   program.program_title = program_title;
84   program.window_title = window_title;
85   program.icon_title = icon_title;
86   program.x11_icon_filename = x11_icon_filename;
87   program.x11_iconmask_filename = x11_iconmask_filename;
88   program.msdos_cursor_filename = msdos_cursor_filename;
89
90   program.cookie_prefix = cookie_prefix;
91   program.filename_prefix = filename_prefix;
92
93   program.version_major = VERSION_MAJOR(program_version);
94   program.version_minor = VERSION_MINOR(program_version);
95   program.version_patch = VERSION_PATCH(program_version);
96
97   program.error_filename = getErrorFilename(ERROR_BASENAME);
98 }
99
100 void InitExitFunction(void (*exit_function)(int))
101 {
102   program.exit_function = exit_function;
103
104   /* set signal handlers to custom exit function */
105   signal(SIGINT, exit_function);
106   signal(SIGTERM, exit_function);
107
108 #if defined(TARGET_SDL)
109   /* set exit function to automatically cleanup SDL stuff after exit() */
110   atexit(SDL_Quit);
111 #endif
112 }
113
114 void InitPlatformDependentStuff(void)
115 {
116 #if defined(PLATFORM_MSDOS)
117   _fmode = O_BINARY;
118 #endif
119
120 #if defined(PLATFORM_WIN32) || defined(PLATFORM_MSDOS)
121   initErrorFile();
122 #endif
123
124 #if defined(TARGET_SDL)
125   if (SDL_Init(SDL_INIT_EVENTTHREAD | SDL_INIT_NOPARACHUTE) < 0)
126     Error(ERR_EXIT, "SDL_Init() failed: %s", SDL_GetError());
127
128   SDLNet_Init();
129 #endif
130 }
131
132 void ClosePlatformDependentStuff(void)
133 {
134 #if defined(PLATFORM_MSDOS)
135   dumpErrorFile();
136 #endif
137 }
138
139 void InitGfxFieldInfo(int sx, int sy, int sxsize, int sysize,
140                       int real_sx, int real_sy,
141                       int full_sxsize, int full_sysize,
142                       Bitmap *field_save_buffer)
143 {
144   gfx.sx = sx;
145   gfx.sy = sy;
146   gfx.sxsize = sxsize;
147   gfx.sysize = sysize;
148   gfx.real_sx = real_sx;
149   gfx.real_sy = real_sy;
150   gfx.full_sxsize = full_sxsize;
151   gfx.full_sysize = full_sysize;
152
153   gfx.field_save_buffer = field_save_buffer;
154
155   gfx.background_bitmap = NULL;
156   gfx.background_bitmap_mask = REDRAW_NONE;
157
158   SetDrawDeactivationMask(REDRAW_NONE);         /* do not deactivate drawing */
159   SetDrawBackgroundMask(REDRAW_NONE);           /* deactivate masked drawing */
160 }
161
162 void InitGfxDoor1Info(int dx, int dy, int dxsize, int dysize)
163 {
164   gfx.dx = dx;
165   gfx.dy = dy;
166   gfx.dxsize = dxsize;
167   gfx.dysize = dysize;
168 }
169
170 void InitGfxDoor2Info(int vx, int vy, int vxsize, int vysize)
171 {
172   gfx.vx = vx;
173   gfx.vy = vy;
174   gfx.vxsize = vxsize;
175   gfx.vysize = vysize;
176 }
177
178 void InitGfxScrollbufferInfo(int scrollbuffer_width, int scrollbuffer_height)
179 {
180   /* currently only used by MSDOS code to alloc VRAM buffer, if available */
181   gfx.scrollbuffer_width = scrollbuffer_width;
182   gfx.scrollbuffer_height = scrollbuffer_height;
183 }
184
185 void SetDrawDeactivationMask(int draw_deactivation_mask)
186 {
187   gfx.draw_deactivation_mask = draw_deactivation_mask;
188 }
189
190 void SetDrawBackgroundMask(int draw_background_mask)
191 {
192   gfx.draw_background_mask = draw_background_mask;
193 }
194
195 static void DrawBitmapFromTile(Bitmap *bitmap, Bitmap *tile,
196                                int dest_x, int dest_y, int width, int height)
197 {
198   int bitmap_xsize = width;
199   int bitmap_ysize = height;
200   int tile_xsize = tile->width;
201   int tile_ysize = tile->height;
202   int tile_xsteps = (bitmap_xsize + tile_xsize - 1) / tile_xsize;
203   int tile_ysteps = (bitmap_ysize + tile_ysize - 1) / tile_ysize;
204   int x, y;
205
206   for (y = 0; y < tile_ysteps; y++)
207   {
208     for (x = 0; x < tile_xsteps; x++)
209     {
210       int draw_x = dest_x + x * tile_xsize;
211       int draw_y = dest_y + y * tile_ysize;
212       int draw_xsize = MIN(tile_xsize, bitmap_xsize - x * tile_xsize);
213       int draw_ysize = MIN(tile_ysize, bitmap_ysize - y * tile_ysize);
214
215       BlitBitmap(tile, bitmap, 0, 0, draw_xsize, draw_ysize, draw_x, draw_y);
216     }
217   }
218 }
219
220 void SetBackgroundBitmap(Bitmap *background_bitmap_tile, int mask)
221 {
222   if (background_bitmap_tile != NULL)
223     gfx.background_bitmap_mask |= mask;
224   else
225     gfx.background_bitmap_mask &= ~mask;
226
227   if (gfx.background_bitmap == NULL)
228     gfx.background_bitmap = CreateBitmap(video.width, video.height,
229                                          DEFAULT_DEPTH);
230
231   if (background_bitmap_tile == NULL)   /* empty background requested */
232     return;
233
234   if (mask == REDRAW_FIELD)
235     DrawBitmapFromTile(gfx.background_bitmap, background_bitmap_tile,
236                        gfx.real_sx, gfx.real_sy,
237                        gfx.full_sxsize, gfx.full_sysize);
238   else if (mask == REDRAW_DOOR_1)
239   {
240     DrawBitmapFromTile(gfx.background_bitmap, background_bitmap_tile,
241                        gfx.dx, gfx.dy,
242                        gfx.dxsize, gfx.dysize);
243   }
244 }
245
246 void SetMainBackgroundBitmap(Bitmap *background_bitmap_tile)
247 {
248   SetBackgroundBitmap(background_bitmap_tile, REDRAW_FIELD);
249 }
250
251 void SetDoorBackgroundBitmap(Bitmap *background_bitmap_tile)
252 {
253   SetBackgroundBitmap(background_bitmap_tile, REDRAW_DOOR_1);
254 }
255
256
257 /* ========================================================================= */
258 /* video functions                                                           */
259 /* ========================================================================= */
260
261 inline static int GetRealDepth(int depth)
262 {
263   return (depth == DEFAULT_DEPTH ? video.default_depth : depth);
264 }
265
266 inline static void sysFillRectangle(Bitmap *bitmap, int x, int y,
267                                int width, int height, Pixel color)
268 {
269 #if defined(TARGET_SDL)
270   SDLFillRectangle(bitmap, x, y, width, height, color);
271 #else
272   X11FillRectangle(bitmap, x, y, width, height, color);
273 #endif
274 }
275
276 inline static void sysCopyArea(Bitmap *src_bitmap, Bitmap *dst_bitmap,
277                                int src_x, int src_y, int width, int height,
278                                int dst_x, int dst_y, int mask_mode)
279 {
280 #if defined(TARGET_SDL)
281   SDLCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
282               dst_x, dst_y, mask_mode);
283 #else
284   X11CopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
285               dst_x, dst_y, mask_mode);
286 #endif
287 }
288
289 void InitVideoDisplay(void)
290 {
291 #if defined(TARGET_SDL)
292   SDLInitVideoDisplay();
293 #else
294   X11InitVideoDisplay();
295 #endif
296 }
297
298 void CloseVideoDisplay(void)
299 {
300   KeyboardAutoRepeatOn();
301
302 #if defined(TARGET_SDL)
303   SDL_QuitSubSystem(SDL_INIT_VIDEO);
304 #else
305   if (display)
306     XCloseDisplay(display);
307 #endif
308 }
309
310 void InitVideoBuffer(DrawBuffer **backbuffer, DrawWindow **window,
311                      int width, int height, int depth, boolean fullscreen)
312 {
313   video.width = width;
314   video.height = height;
315   video.depth = GetRealDepth(depth);
316   video.fullscreen_available = FULLSCREEN_STATUS;
317   video.fullscreen_enabled = FALSE;
318
319 #if defined(TARGET_SDL)
320   SDLInitVideoBuffer(backbuffer, window, fullscreen);
321 #else
322   X11InitVideoBuffer(backbuffer, window);
323 #endif
324 }
325
326 Bitmap *CreateBitmapStruct(void)
327 {
328 #if defined(TARGET_SDL)
329   return checked_calloc(sizeof(struct SDLSurfaceInfo));
330 #else
331   return checked_calloc(sizeof(struct X11DrawableInfo));
332 #endif
333 }
334
335 Bitmap *CreateBitmap(int width, int height, int depth)
336 {
337   Bitmap *new_bitmap = CreateBitmapStruct();
338   int real_depth = GetRealDepth(depth);
339
340 #if defined(TARGET_SDL)
341   SDLCreateBitmapContent(new_bitmap, width, height, real_depth);
342 #else
343   X11CreateBitmapContent(new_bitmap, width, height, real_depth);
344 #endif
345
346   new_bitmap->width = width;
347   new_bitmap->height = height;
348
349   return new_bitmap;
350 }
351
352 inline static void FreeBitmapPointers(Bitmap *bitmap)
353 {
354   if (bitmap == NULL)
355     return;
356
357 #if defined(TARGET_SDL)
358   SDLFreeBitmapPointers(bitmap);
359 #else
360   X11FreeBitmapPointers(bitmap);
361 #endif
362
363   checked_free(bitmap->source_filename);
364   bitmap->source_filename = NULL;
365 }
366
367 inline static void TransferBitmapPointers(Bitmap *src_bitmap,
368                                           Bitmap *dst_bitmap)
369 {
370   if (src_bitmap == NULL || dst_bitmap == NULL)
371     return;
372
373   FreeBitmapPointers(dst_bitmap);
374
375   *dst_bitmap = *src_bitmap;
376 }
377
378 void FreeBitmap(Bitmap *bitmap)
379 {
380   if (bitmap == NULL)
381     return;
382
383   FreeBitmapPointers(bitmap);
384
385   free(bitmap);
386 }
387
388 void CloseWindow(DrawWindow *window)
389 {
390 #if defined(TARGET_X11)
391   if (window->drawable)
392   {
393     XUnmapWindow(display, window->drawable);
394     XDestroyWindow(display, window->drawable);
395   }
396   if (window->gc)
397     XFreeGC(display, window->gc);
398 #endif
399 }
400
401 inline static boolean CheckDrawingArea(int x, int y, int width, int height,
402                                        int draw_mask)
403 {
404   if (draw_mask == REDRAW_NONE)
405     return FALSE;
406
407   if (draw_mask & REDRAW_ALL)
408     return TRUE;
409
410   if ((draw_mask & REDRAW_FIELD) && x < gfx.real_sx + gfx.full_sxsize)
411     return TRUE;
412
413   if ((draw_mask & REDRAW_DOOR_1) && x >= gfx.dx && y < gfx.dy + gfx.dysize)
414     return TRUE;
415
416   if ((draw_mask & REDRAW_DOOR_2) && x >= gfx.dx && y >= gfx.vy)
417     return TRUE;
418
419   return FALSE;
420 }
421
422 boolean DrawingDeactivated(int x, int y, int width, int height)
423 {
424   return CheckDrawingArea(x, y, width, height, gfx.draw_deactivation_mask);
425 }
426
427 boolean DrawingOnBackground(int x, int y)
428 {
429   return (CheckDrawingArea(x, y, 1, 1, gfx.background_bitmap_mask) &&
430           CheckDrawingArea(x, y, 1, 1, gfx.draw_background_mask));
431 }
432
433 void BlitBitmap(Bitmap *src_bitmap, Bitmap *dst_bitmap,
434                 int src_x, int src_y, int width, int height,
435                 int dst_x, int dst_y)
436 {
437   if (DrawingDeactivated(dst_x, dst_y, width, height))
438     return;
439
440   sysCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
441               dst_x, dst_y, BLIT_OPAQUE);
442 }
443
444 void FadeScreen(Bitmap *bitmap_cross, int fade_mode, int fade_delay,
445                 int post_delay)
446 {
447 #if defined(TARGET_SDL)
448   SDLFadeScreen(bitmap_cross, fade_mode, fade_delay, post_delay);
449 #else
450   X11FadeScreen(bitmap_cross, fade_mode, fade_delay, post_delay);
451 #endif
452 }
453
454 void FillRectangle(Bitmap *bitmap, int x, int y, int width, int height,
455                    Pixel color)
456 {
457   if (DrawingDeactivated(x, y, width, height))
458     return;
459
460   sysFillRectangle(bitmap, x, y, width, height, color);
461 }
462
463 void ClearRectangle(Bitmap *bitmap, int x, int y, int width, int height)
464 {
465   FillRectangle(bitmap, x, y, width, height, BLACK_PIXEL);
466 }
467
468 void ClearRectangleOnBackground(Bitmap *bitmap, int x, int y,
469                                 int width, int height)
470 {
471   if (DrawingOnBackground(x, y))
472     BlitBitmap(gfx.background_bitmap, bitmap, x, y, width, height, x, y);
473   else
474     ClearRectangle(bitmap, x, y, width, height);
475 }
476
477 void SetClipMask(Bitmap *bitmap, GC clip_gc, Pixmap clip_pixmap)
478 {
479 #if defined(TARGET_X11)
480   if (clip_gc)
481   {
482     bitmap->clip_gc = clip_gc;
483     XSetClipMask(display, bitmap->clip_gc, clip_pixmap);
484   }
485 #endif
486 }
487
488 void SetClipOrigin(Bitmap *bitmap, GC clip_gc, int clip_x, int clip_y)
489 {
490 #if defined(TARGET_X11)
491   if (clip_gc)
492   {
493     bitmap->clip_gc = clip_gc;
494     XSetClipOrigin(display, bitmap->clip_gc, clip_x, clip_y);
495   }
496 #endif
497 }
498
499 void BlitBitmapMasked(Bitmap *src_bitmap, Bitmap *dst_bitmap,
500                       int src_x, int src_y, int width, int height,
501                       int dst_x, int dst_y)
502 {
503   if (DrawingDeactivated(dst_x, dst_y, width, height))
504     return;
505
506   sysCopyArea(src_bitmap, dst_bitmap, src_x, src_y, width, height,
507               dst_x, dst_y, BLIT_MASKED);
508 }
509
510 void BlitBitmapOnBackground(Bitmap *src_bitmap, Bitmap *dst_bitmap,
511                             int src_x, int src_y, int width, int height,
512                             int dst_x, int dst_y)
513 {
514   if (DrawingOnBackground(dst_x, dst_y))
515   {
516     /* draw background */
517     BlitBitmap(gfx.background_bitmap, dst_bitmap, dst_x, dst_y, width, height,
518                dst_x, dst_y);
519
520     /* draw foreground */
521     SetClipOrigin(src_bitmap, src_bitmap->stored_clip_gc,
522                   dst_x - src_x, dst_y - src_y);
523     BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y, width, height,
524                      dst_x, dst_y);
525   }
526   else
527     BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y, width, height,
528                dst_x, dst_y);
529 }
530
531 void DrawSimpleBlackLine(Bitmap *bitmap, int from_x, int from_y,
532                          int to_x, int to_y)
533 {
534 #if defined(TARGET_SDL)
535   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, BLACK_PIXEL);
536 #else
537   X11DrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, BLACK_PIXEL);
538 #endif
539 }
540
541 void DrawSimpleWhiteLine(Bitmap *bitmap, int from_x, int from_y,
542                          int to_x, int to_y)
543 {
544 #if defined(TARGET_SDL)
545   SDLDrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, WHITE_PIXEL);
546 #else
547   X11DrawSimpleLine(bitmap, from_x, from_y, to_x, to_y, WHITE_PIXEL);
548 #endif
549 }
550
551 #if !defined(TARGET_X11_NATIVE)
552 void DrawLine(Bitmap *bitmap, int from_x, int from_y,
553               int to_x, int to_y, Pixel pixel, int line_width)
554 {
555   int x, y;
556
557   for (x = 0; x < line_width; x++)
558   {
559     for (y = 0; y < line_width; y++)
560     {
561       int dx = x - line_width / 2;
562       int dy = y - line_width / 2;
563
564       if ((x == 0 && y == 0) ||
565           (x == 0 && y == line_width - 1) ||
566           (x == line_width - 1 && y == 0) ||
567           (x == line_width - 1 && y == line_width - 1))
568         continue;
569
570 #if defined(TARGET_SDL)
571       SDLDrawLine(bitmap,
572                   from_x + dx, from_y + dy, to_x + dx, to_y + dy, pixel);
573 #elif defined(TARGET_ALLEGRO)
574       AllegroDrawLine(bitmap->drawable, from_x + dx, from_y + dy,
575                       to_x + dx, to_y + dy, pixel);
576 #endif
577     }
578   }
579 }
580 #endif
581
582 void DrawLines(Bitmap *bitmap, struct XY *points, int num_points, Pixel pixel)
583 {
584 #if !defined(TARGET_X11_NATIVE)
585   int line_width = 4;
586   int i;
587
588   for (i = 0; i < num_points - 1; i++)
589     DrawLine(bitmap, points[i].x, points[i].y,
590              points[i + 1].x, points[i + 1].y, pixel, line_width);
591
592   /*
593   SDLDrawLines(bitmap->surface, points, num_points, pixel);
594   */
595 #else
596   XSetForeground(display, bitmap->line_gc[1], pixel);
597   XDrawLines(display, bitmap->drawable, bitmap->line_gc[1],
598              (XPoint *)points, num_points, CoordModeOrigin);
599 #endif
600 }
601
602 Pixel GetPixel(Bitmap *bitmap, int x, int y)
603 {
604   if (x < 0 || x >= bitmap->width ||
605       y < 0 || y >= bitmap->height)
606     return BLACK_PIXEL;
607
608 #if defined(TARGET_SDL)
609   return SDLGetPixel(bitmap, x, y);
610 #elif defined(TARGET_ALLEGRO)
611   return AllegroGetPixel(bitmap->drawable, x, y);
612 #else
613   return X11GetPixel(bitmap, x, y);
614 #endif
615 }
616
617 Pixel GetPixelFromRGB(Bitmap *bitmap, unsigned int color_r,
618                       unsigned int color_g, unsigned int color_b)
619 {
620 #if defined(TARGET_SDL)
621   return SDL_MapRGB(bitmap->surface->format, color_r, color_g, color_b);
622 #elif defined(TARGET_ALLEGRO)
623   return AllegroAllocColorCell(color_r << 8, color_g << 8, color_b << 8);
624 #else
625   return X11GetPixelFromRGB(color_r, color_g, color_b);
626 #endif
627 }
628
629 Pixel GetPixelFromRGBcompact(Bitmap *bitmap, unsigned int color)
630 {
631   unsigned int color_r = (color >> 16) & 0xff;
632   unsigned int color_g = (color >>  8) & 0xff;
633   unsigned int color_b = (color >>  0) & 0xff;
634
635   return GetPixelFromRGB(bitmap, color_r, color_g, color_b);
636 }
637
638 /* execute all pending screen drawing operations */
639 void FlushDisplay(void)
640 {
641 #ifndef TARGET_SDL
642   XFlush(display);
643 #endif
644 }
645
646 /* execute and wait for all pending screen drawing operations */
647 void SyncDisplay(void)
648 {
649 #ifndef TARGET_SDL
650   XSync(display, FALSE);
651 #endif
652 }
653
654 void KeyboardAutoRepeatOn(void)
655 {
656 #if defined(TARGET_SDL)
657   SDL_EnableKeyRepeat(SDL_DEFAULT_REPEAT_DELAY / 2,
658                       SDL_DEFAULT_REPEAT_INTERVAL / 2);
659   SDL_EnableUNICODE(1);
660 #else
661   if (display)
662     XAutoRepeatOn(display);
663 #endif
664 }
665
666 void KeyboardAutoRepeatOff(void)
667 {
668 #if defined(TARGET_SDL)
669   SDL_EnableKeyRepeat(0, SDL_DEFAULT_REPEAT_INTERVAL);
670   SDL_EnableUNICODE(0);
671 #else
672   if (display)
673     XAutoRepeatOff(display);
674 #endif
675 }
676
677 boolean PointerInWindow(DrawWindow *window)
678 {
679 #if defined(TARGET_SDL)
680   return TRUE;
681 #else
682   Window root, child;
683   int root_x, root_y;
684   unsigned int mask;
685   int win_x, win_y;
686
687   /* if XQueryPointer() returns False, the pointer
688      is not on the same screen as the specified window */
689   return XQueryPointer(display, window->drawable, &root, &child,
690                        &root_x, &root_y, &win_x, &win_y, &mask);
691 #endif
692 }
693
694 boolean SetVideoMode(boolean fullscreen)
695 {
696 #if defined(TARGET_SDL)
697   return SDLSetVideoMode(&backbuffer, fullscreen);
698 #else
699   boolean success = TRUE;
700
701   if (fullscreen && video.fullscreen_available)
702   {
703     Error(ERR_WARN, "fullscreen not available in X11 version");
704
705     /* display error message only once */
706     video.fullscreen_available = FALSE;
707
708     success = FALSE;
709   }
710
711   return success;
712 #endif
713 }
714
715 boolean ChangeVideoModeIfNeeded(boolean fullscreen)
716 {
717 #if defined(TARGET_SDL)
718   if ((fullscreen && !video.fullscreen_enabled && video.fullscreen_available)||
719       (!fullscreen && video.fullscreen_enabled))
720     fullscreen = SetVideoMode(fullscreen);
721 #endif
722
723   return fullscreen;
724 }
725
726 Bitmap *LoadImage(char *filename)
727 {
728   Bitmap *new_bitmap;
729
730 #if defined(TARGET_SDL)
731   new_bitmap = SDLLoadImage(filename);
732 #else
733   new_bitmap = X11LoadImage(filename);
734 #endif
735
736   if (new_bitmap)
737     new_bitmap->source_filename = getStringCopy(filename);
738
739   return new_bitmap;
740 }
741
742 Bitmap *LoadCustomImage(char *basename)
743 {
744   char *filename = getCustomImageFilename(basename);
745   Bitmap *new_bitmap;
746
747   if (filename == NULL)
748     Error(ERR_EXIT, "LoadCustomImage(): cannot find file '%s'", basename);
749
750   if ((new_bitmap = LoadImage(filename)) == NULL)
751     Error(ERR_EXIT, "LoadImage() failed: %s", GetError());
752
753   return new_bitmap;
754 }
755
756 void ReloadCustomImage(Bitmap *bitmap, char *basename)
757 {
758   char *filename = getCustomImageFilename(basename);
759   Bitmap *new_bitmap;
760
761   if (filename == NULL)         /* (should never happen) */
762   {
763     Error(ERR_WARN, "ReloadCustomImage(): cannot find file '%s'", basename);
764     return;
765   }
766
767   if (strEqual(filename, bitmap->source_filename))
768   {
769     /* The old and new image are the same (have the same filename and path).
770        This usually means that this image does not exist in this graphic set
771        and a fallback to the existing image is done. */
772
773     return;
774   }
775
776   if ((new_bitmap = LoadImage(filename)) == NULL)
777   {
778     Error(ERR_WARN, "LoadImage() failed: %s", GetError());
779     return;
780   }
781
782   if (bitmap->width != new_bitmap->width ||
783       bitmap->height != new_bitmap->height)
784   {
785     Error(ERR_WARN, "ReloadCustomImage: new image '%s' has wrong dimensions",
786           filename);
787     FreeBitmap(new_bitmap);
788     return;
789   }
790
791   TransferBitmapPointers(new_bitmap, bitmap);
792   free(new_bitmap);
793 }
794
795 Bitmap *ZoomBitmap(Bitmap *src_bitmap, int zoom_width, int zoom_height)
796 {
797   Bitmap *dst_bitmap = CreateBitmap(zoom_width, zoom_height, DEFAULT_DEPTH);
798
799 #if defined(TARGET_SDL)
800   SDLZoomBitmap(src_bitmap, dst_bitmap);
801 #else
802   X11ZoomBitmap(src_bitmap, dst_bitmap);
803 #endif
804
805   return dst_bitmap;
806 }
807
808 static void CreateScaledBitmaps(Bitmap *old_bitmap, int zoom_factor,
809                                 boolean create_small_bitmaps)
810 {
811   Bitmap swap_bitmap;
812   Bitmap *new_bitmap, *tmp_bitmap_1, *tmp_bitmap_2, *tmp_bitmap_8;
813   int width_1, height_1, width_2, height_2, width_8, height_8;
814   int new_width, new_height;
815
816   /* calculate new image dimensions for normal sized image */
817   width_1  = old_bitmap->width  * zoom_factor;
818   height_1 = old_bitmap->height * zoom_factor;
819
820   /* get image with normal size (this might require scaling up) */
821   if (zoom_factor != 1)
822     tmp_bitmap_1 = ZoomBitmap(old_bitmap, width_1, height_1);
823   else
824     tmp_bitmap_1 = old_bitmap;
825
826   /* this is only needed to make compilers happy */
827   tmp_bitmap_2 = tmp_bitmap_8 = NULL;
828
829   if (create_small_bitmaps)
830   {
831     /* calculate new image dimensions for small images */
832     width_2  = width_1  / 2;
833     height_2 = height_1 / 2;
834     width_8  = width_1  / 8;
835     height_8 = height_1 / 8;
836
837     /* get image with 1/2 of normal size (for use in the level editor) */
838     if (zoom_factor != 2)
839       tmp_bitmap_2 = ZoomBitmap(tmp_bitmap_1, width_1 / 2, height_1 / 2);
840     else
841       tmp_bitmap_2 = old_bitmap;
842
843     /* get image with 1/8 of normal size (for use on the preview screen) */
844     if (zoom_factor != 8)
845       tmp_bitmap_8 = ZoomBitmap(tmp_bitmap_1, width_1 / 8, height_1 / 8);
846     else
847       tmp_bitmap_8 = old_bitmap;
848   }
849
850   /* if image was scaled up, create new clipmask for normal size image */
851   if (zoom_factor != 1)
852   {
853 #if defined(TARGET_X11)
854     if (old_bitmap->clip_mask)
855       XFreePixmap(display, old_bitmap->clip_mask);
856
857     old_bitmap->clip_mask =
858       Pixmap_to_Mask(tmp_bitmap_1->drawable, width_1, height_1);
859
860     XSetClipMask(display, old_bitmap->stored_clip_gc, old_bitmap->clip_mask);
861 #else
862     SDL_Surface *tmp_surface_1 = tmp_bitmap_1->surface;
863
864     if (old_bitmap->surface_masked)
865       SDL_FreeSurface(old_bitmap->surface_masked);
866
867     SDL_SetColorKey(tmp_surface_1, SDL_SRCCOLORKEY,
868                     SDL_MapRGB(tmp_surface_1->format, 0x00, 0x00, 0x00));
869     if ((old_bitmap->surface_masked = SDL_DisplayFormat(tmp_surface_1)) ==NULL)
870       Error(ERR_EXIT, "SDL_DisplayFormat() failed");
871     SDL_SetColorKey(tmp_surface_1, 0, 0);       /* reset transparent pixel */
872 #endif
873   }
874
875   if (create_small_bitmaps)
876   {
877     new_width  = width_1;
878     new_height = height_1 + (height_1 + 1) / 2;     /* prevent odd height */
879
880     new_bitmap = CreateBitmap(new_width, new_height, DEFAULT_DEPTH);
881
882     BlitBitmap(tmp_bitmap_1, new_bitmap, 0, 0, width_1, height_1, 0, 0);
883     BlitBitmap(tmp_bitmap_2, new_bitmap, 0, 0, width_1 / 2, height_1 / 2,
884                0, height_1);
885     BlitBitmap(tmp_bitmap_8, new_bitmap, 0, 0, width_1 / 8, height_1 / 8,
886                3 * width_1 / 4, height_1);
887   }
888   else
889   {
890     new_width  = width_1;
891     new_height = height_1;
892
893     new_bitmap = tmp_bitmap_1;  /* directly use tmp_bitmap_1 as new bitmap */
894   }
895
896   if (create_small_bitmaps)
897   {
898     /* if no small bitmaps created, tmp_bitmap_1 is used as new bitmap now */
899     if (zoom_factor != 1)
900       FreeBitmap(tmp_bitmap_1);
901
902     if (zoom_factor != 2)
903       FreeBitmap(tmp_bitmap_2);
904
905     if (zoom_factor != 8)
906       FreeBitmap(tmp_bitmap_8);
907   }
908
909   /* replace image with extended image (containing normal, 1/2 and 1/8 size) */
910 #if defined(TARGET_SDL)
911   swap_bitmap.surface = old_bitmap->surface;
912   old_bitmap->surface = new_bitmap->surface;
913   new_bitmap->surface = swap_bitmap.surface;
914 #else
915   swap_bitmap.drawable = old_bitmap->drawable;
916   old_bitmap->drawable = new_bitmap->drawable;
917   new_bitmap->drawable = swap_bitmap.drawable;
918 #endif
919
920   old_bitmap->width  = new_bitmap->width;
921   old_bitmap->height = new_bitmap->height;
922
923   FreeBitmap(new_bitmap);       /* this actually frees the _old_ bitmap now */
924 }
925
926 void CreateBitmapWithSmallBitmaps(Bitmap *old_bitmap, int zoom_factor)
927 {
928   CreateScaledBitmaps(old_bitmap, zoom_factor, TRUE);
929 }
930
931 void ScaleBitmap(Bitmap *old_bitmap, int zoom_factor)
932 {
933   CreateScaledBitmaps(old_bitmap, zoom_factor, FALSE);
934 }
935
936
937 /* ------------------------------------------------------------------------- */
938 /* mouse pointer functions                                                   */
939 /* ------------------------------------------------------------------------- */
940
941 #if !defined(PLATFORM_MSDOS)
942 /* XPM */
943 static const char *cursor_image_playfield[] =
944 {
945   /* width height num_colors chars_per_pixel */
946   "    16    16        3            1",
947
948   /* colors */
949   "X c #000000",
950   ". c #ffffff",
951   "  c None",
952
953 #if 1
954   /* some people complained about a "white dot" on the screen and thought it
955      was a graphical error... OK, let's just remove the whole pointer :-) */
956
957   /* pixels */
958   "                ",
959   "                ",
960   "                ",
961   "                ",
962   "                ",
963   "                ",
964   "                ",
965   "                ",
966   "                ",
967   "                ",
968   "                ",
969   "                ",
970   "                ",
971   "                ",
972   "                ",
973   "                ",
974
975   /* hot spot */
976   "0,0"
977
978 #else
979
980   /* pixels */
981   " X              ",
982   "X.X             ",
983   " X              ",
984   "                ",
985   "                ",
986   "                ",
987   "                ",
988   "                ",
989   "                ",
990   "                ",
991   "                ",
992   "                ",
993   "                ",
994   "                ",
995   "                ",
996   "                ",
997
998   /* hot spot */
999   "1,1"
1000 #endif
1001 };
1002
1003 #if defined(TARGET_SDL)
1004 static const int cursor_bit_order = BIT_ORDER_MSB;
1005 #elif defined(TARGET_X11_NATIVE)
1006 static const int cursor_bit_order = BIT_ORDER_LSB;
1007 #endif
1008
1009 static struct MouseCursorInfo *get_cursor_from_image(const char **image)
1010 {
1011   struct MouseCursorInfo *cursor;
1012   boolean bit_order_msb = (cursor_bit_order == BIT_ORDER_MSB);
1013   int header_lines = 4;
1014   int x, y, i;
1015
1016   cursor = checked_calloc(sizeof(struct MouseCursorInfo));
1017
1018   sscanf(image[0], " %d %d ", &cursor->width, &cursor->height);
1019
1020   i = -1;
1021   for (y = 0; y < cursor->width; y++)
1022   {
1023     for (x = 0; x < cursor->height; x++)
1024     {
1025       int bit_nr = x % 8;
1026       int bit_mask = 0x01 << (bit_order_msb ? 7 - bit_nr : bit_nr );
1027
1028       if (bit_nr == 0)
1029       {
1030         i++;
1031         cursor->data[i] = cursor->mask[i] = 0;
1032       }
1033
1034       switch (image[header_lines + y][x])
1035       {
1036         case 'X':
1037           cursor->data[i] |= bit_mask;
1038           cursor->mask[i] |= bit_mask;
1039           break;
1040
1041         case '.':
1042           cursor->mask[i] |= bit_mask;
1043           break;
1044
1045         case ' ':
1046           break;
1047       }
1048     }
1049   }
1050
1051   sscanf(image[header_lines + y], "%d,%d", &cursor->hot_x, &cursor->hot_y);
1052
1053   return cursor;
1054 }
1055 #endif  /* !PLATFORM_MSDOS */
1056
1057 void SetMouseCursor(int mode)
1058 {
1059 #if !defined(PLATFORM_MSDOS)
1060   static struct MouseCursorInfo *cursor_playfield = NULL;
1061
1062   if (cursor_playfield == NULL)
1063     cursor_playfield = get_cursor_from_image(cursor_image_playfield);
1064
1065 #if defined(TARGET_SDL)
1066   SDLSetMouseCursor(mode == CURSOR_PLAYFIELD ? cursor_playfield : NULL);
1067 #elif defined(TARGET_X11_NATIVE)
1068   X11SetMouseCursor(mode == CURSOR_PLAYFIELD ? cursor_playfield : NULL);
1069 #endif
1070 #endif
1071 }
1072
1073
1074 /* ========================================================================= */
1075 /* audio functions                                                           */
1076 /* ========================================================================= */
1077
1078 void OpenAudio(void)
1079 {
1080   /* always start with reliable default values */
1081   audio.sound_available = FALSE;
1082   audio.music_available = FALSE;
1083   audio.loops_available = FALSE;
1084
1085   audio.sound_enabled = FALSE;
1086   audio.sound_deactivated = FALSE;
1087
1088   audio.mixer_pipe[0] = audio.mixer_pipe[1] = 0;
1089   audio.mixer_pid = 0;
1090   audio.device_name = NULL;
1091   audio.device_fd = -1;
1092
1093   audio.num_channels = 0;
1094   audio.music_channel = 0;
1095   audio.first_sound_channel = 0;
1096
1097 #if defined(TARGET_SDL)
1098   SDLOpenAudio();
1099 #elif defined(PLATFORM_UNIX)
1100   UnixOpenAudio();
1101 #elif defined(PLATFORM_MSDOS)
1102   MSDOSOpenAudio();
1103 #endif
1104 }
1105
1106 void CloseAudio(void)
1107 {
1108 #if defined(TARGET_SDL)
1109   SDLCloseAudio();
1110 #elif defined(PLATFORM_UNIX)
1111   UnixCloseAudio();
1112 #elif defined(PLATFORM_MSDOS)
1113   MSDOSCloseAudio();
1114 #endif
1115
1116   audio.sound_enabled = FALSE;
1117 }
1118
1119 void SetAudioMode(boolean enabled)
1120 {
1121   if (!audio.sound_available)
1122     return;
1123
1124   audio.sound_enabled = enabled;
1125 }
1126
1127
1128 /* ========================================================================= */
1129 /* event functions                                                           */
1130 /* ========================================================================= */
1131
1132 void InitEventFilter(EventFilter filter_function)
1133 {
1134 #if defined(TARGET_SDL)
1135   /* set event filter to filter out certain events */
1136   SDL_SetEventFilter(filter_function);
1137 #endif
1138 }
1139
1140 boolean PendingEvent(void)
1141 {
1142 #if defined(TARGET_SDL)
1143   return (SDL_PollEvent(NULL) ? TRUE : FALSE);
1144 #else
1145   return (XPending(display) ? TRUE : FALSE);
1146 #endif
1147 }
1148
1149 void NextEvent(Event *event)
1150 {
1151 #if defined(TARGET_SDL)
1152   SDLNextEvent(event);
1153 #else
1154   XNextEvent(display, event);
1155 #endif
1156 }
1157
1158 void PeekEvent(Event *event)
1159 {
1160 #if defined(TARGET_SDL)
1161   SDL_PeepEvents(event, 1, SDL_PEEKEVENT, SDL_ALLEVENTS);
1162 #else
1163   XPeekEvent(display, event);
1164 #endif
1165 }
1166
1167 Key GetEventKey(KeyEvent *event, boolean with_modifiers)
1168 {
1169 #if defined(TARGET_SDL)
1170
1171 #if 0
1172   printf("unicode == '%d', sym == '%d', mod == '0x%04x'\n",
1173          (int)event->keysym.unicode,
1174          (int)event->keysym.sym,
1175          (int)SDL_GetModState());
1176 #endif
1177
1178   if (with_modifiers &&
1179       event->keysym.unicode > 0x0000 &&
1180       event->keysym.unicode < 0x2000)
1181     return event->keysym.unicode;
1182   else
1183     return event->keysym.sym;
1184
1185 #else
1186
1187 #if 0
1188   printf("with modifiers == '0x%04x', without modifiers == '0x%04x'\n",
1189          (int)XLookupKeysym(event, event->state),
1190          (int)XLookupKeysym(event, 0));
1191 #endif
1192
1193   if (with_modifiers)
1194     return XLookupKeysym(event, event->state);
1195   else
1196     return XLookupKeysym(event, 0);
1197 #endif
1198 }
1199
1200 KeyMod HandleKeyModState(Key key, int key_status)
1201 {
1202   static KeyMod current_modifiers = KMOD_None;
1203
1204 #if !defined(TARGET_SDL)
1205   if (key != KSYM_UNDEFINED)    /* new key => check for modifier key change */
1206   {
1207     KeyMod new_modifier = KMOD_None;
1208
1209     switch(key)
1210     {
1211       case KSYM_Shift_L:
1212         new_modifier = KMOD_Shift_L;
1213         break;
1214       case KSYM_Shift_R:
1215         new_modifier = KMOD_Shift_R;
1216         break;
1217       case KSYM_Control_L:
1218         new_modifier = KMOD_Control_L;
1219         break;
1220       case KSYM_Control_R:
1221         new_modifier = KMOD_Control_R;
1222         break;
1223       case KSYM_Meta_L:
1224         new_modifier = KMOD_Meta_L;
1225         break;
1226       case KSYM_Meta_R:
1227         new_modifier = KMOD_Meta_R;
1228         break;
1229       case KSYM_Alt_L:
1230         new_modifier = KMOD_Alt_L;
1231         break;
1232       case KSYM_Alt_R:
1233         new_modifier = KMOD_Alt_R;
1234         break;
1235       default:
1236         break;
1237     }
1238
1239     if (key_status == KEY_PRESSED)
1240       current_modifiers |= new_modifier;
1241     else
1242       current_modifiers &= ~new_modifier;
1243   }
1244 #endif
1245
1246   return current_modifiers;
1247 }
1248
1249 KeyMod GetKeyModState()
1250 {
1251 #if defined(TARGET_SDL)
1252   return (KeyMod)SDL_GetModState();
1253 #else
1254   return HandleKeyModState(KSYM_UNDEFINED, 0);
1255 #endif
1256 }
1257
1258 boolean CheckCloseWindowEvent(ClientMessageEvent *event)
1259 {
1260   if (event->type != EVENT_CLIENTMESSAGE)
1261     return FALSE;
1262
1263 #if defined(TARGET_SDL)
1264   return TRUE;          /* the only possible message here is SDL_QUIT */
1265 #elif defined(PLATFORM_UNIX)
1266   if ((event->window == window->drawable) &&
1267       (event->data.l[0] == XInternAtom(display, "WM_DELETE_WINDOW", FALSE)))
1268     return TRUE;
1269 #endif
1270
1271   return FALSE;
1272 }
1273
1274
1275 /* ========================================================================= */
1276 /* joystick functions                                                        */
1277 /* ========================================================================= */
1278
1279 void InitJoysticks()
1280 {
1281   int i;
1282
1283 #if defined(NO_JOYSTICK)
1284   return;       /* joysticks generally deactivated by compile-time directive */
1285 #endif
1286
1287   /* always start with reliable default values */
1288   joystick.status = JOYSTICK_NOT_AVAILABLE;
1289   for (i = 0; i < MAX_PLAYERS; i++)
1290     joystick.fd[i] = -1;                /* joystick device closed */
1291
1292 #if defined(TARGET_SDL)
1293   SDLInitJoysticks();
1294 #elif defined(PLATFORM_UNIX)
1295   UnixInitJoysticks();
1296 #elif defined(PLATFORM_MSDOS)
1297   MSDOSInitJoysticks();
1298 #endif
1299
1300 #if 0
1301   for (i = 0; i < MAX_PLAYERS; i++)
1302     printf("::: Joystick for player %d: %d\n", i, joystick.fd[i]);
1303 #endif
1304 }
1305
1306 boolean ReadJoystick(int nr, int *x, int *y, boolean *b1, boolean *b2)
1307 {
1308 #if defined(TARGET_SDL)
1309   return SDLReadJoystick(nr, x, y, b1, b2);
1310 #elif defined(PLATFORM_UNIX)
1311   return UnixReadJoystick(nr, x, y, b1, b2);
1312 #elif defined(PLATFORM_MSDOS)
1313   return MSDOSReadJoystick(nr, x, y, b1, b2);
1314 #endif
1315 }