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