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