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