fixed bug where player actions were incorrectly mapped in single player mode (also...
[rocksndiamonds.git] / src / libgame / text.c
1 // ============================================================================
2 // Artsoft Retro-Game Library
3 // ----------------------------------------------------------------------------
4 // (c) 1995-2014 by Artsoft Entertainment
5 //                  Holger Schemel
6 //                  info@artsoft.org
7 //                  http://www.artsoft.org/
8 // ----------------------------------------------------------------------------
9 // text.c
10 // ============================================================================
11
12 #include <stdio.h>
13 #include <stdarg.h>
14
15 #include "text.h"
16 #include "misc.h"
17
18
19 /* ========================================================================= */
20 /* font functions                                                            */
21 /* ========================================================================= */
22
23 void InitFontInfo(struct FontBitmapInfo *font_bitmap_info, int num_fonts,
24                   int (*select_font_function)(int),
25                   int (*get_font_from_token_function)(char *))
26 {
27   gfx.num_fonts = num_fonts;
28   gfx.font_bitmap_info = font_bitmap_info;
29   gfx.select_font_function = select_font_function;
30   gfx.get_font_from_token_function = get_font_from_token_function;
31 }
32
33 void FreeFontInfo(struct FontBitmapInfo *font_bitmap_info)
34 {
35   if (font_bitmap_info == NULL)
36     return;
37
38   free(font_bitmap_info);
39 }
40
41 struct FontBitmapInfo *getFontBitmapInfo(int font_nr)
42 {
43   int font_bitmap_id = gfx.select_font_function(font_nr);
44
45   return &gfx.font_bitmap_info[font_bitmap_id];
46 }
47
48 int getFontWidth(int font_nr)
49 {
50   int font_bitmap_id = gfx.select_font_function(font_nr);
51
52   return gfx.font_bitmap_info[font_bitmap_id].width;
53 }
54
55 int getFontHeight(int font_nr)
56 {
57   int font_bitmap_id = gfx.select_font_function(font_nr);
58
59   return gfx.font_bitmap_info[font_bitmap_id].height;
60 }
61
62 int getTextWidth(char *text, int font_nr)
63 {
64   return (text != NULL ? strlen(text) * getFontWidth(font_nr) : 0);
65 }
66
67 static int getFontCharPosition(int font_nr, char c)
68 {
69   int font_bitmap_id = gfx.select_font_function(font_nr);
70   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
71   boolean default_font = (font->num_chars == DEFAULT_NUM_CHARS_PER_FONT);
72   int font_pos = (unsigned char)c - 32;
73
74   /* map some special characters to their ascii values in default font */
75   if (default_font)
76     font_pos = MAP_FONT_ASCII(c) - 32;
77
78   /* this allows dynamic special characters together with special font */
79   if (font_pos < 0 || font_pos >= font->num_chars)
80     font_pos = 0;
81
82   return font_pos;
83 }
84
85 void getFontCharSource(int font_nr, char c, Bitmap **bitmap, int *x, int *y)
86 {
87   int font_bitmap_id = gfx.select_font_function(font_nr);
88   struct FontBitmapInfo *font = &gfx.font_bitmap_info[font_bitmap_id];
89   int font_pos = getFontCharPosition(font_nr, c);
90
91   *bitmap = font->bitmap;
92   *x = font->src_x + (font_pos % font->num_chars_per_line) * font->width;
93   *y = font->src_y + (font_pos / font->num_chars_per_line) * font->height;
94 }
95
96
97 /* ========================================================================= */
98 /* text string helper functions                                              */
99 /* ========================================================================= */
100
101 int maxWordLengthInString(char *text)
102 {
103   char *text_ptr;
104   int word_len = 0, max_word_len = 0;
105
106   for (text_ptr = text; *text_ptr; text_ptr++)
107   {
108     word_len = (*text_ptr != ' ' ? word_len + 1 : 0);
109
110     max_word_len = MAX(word_len, max_word_len);
111   }
112
113   return max_word_len;
114 }
115
116
117 /* ========================================================================= */
118 /* simple text drawing functions                                             */
119 /* ========================================================================= */
120
121 void DrawInitText(char *text, int ypos, int font_nr)
122 {
123   LimitScreenUpdates(TRUE);
124
125   UPDATE_BUSY_STATE();
126
127   if (window != NULL &&
128       gfx.draw_init_text &&
129       gfx.num_fonts > 0 &&
130       gfx.font_bitmap_info[font_nr].bitmap != NULL)
131   {
132     int x = (video.width - getTextWidth(text, font_nr)) / 2;
133     int y = ypos;
134     int width = video.width;
135     int height = getFontHeight(font_nr);
136
137     ClearRectangle(drawto, 0, y, width, height);
138     DrawTextExt(drawto, x, y, text, font_nr, BLIT_OPAQUE);
139
140     BlitBitmap(drawto, window, 0, 0, video.width, video.height, 0, 0);
141   }
142 }
143
144 void DrawTextF(int x, int y, int font_nr, char *format, ...)
145 {
146   char buffer[MAX_OUTPUT_LINESIZE + 1];
147   va_list ap;
148
149   va_start(ap, format);
150   vsprintf(buffer, format, ap);
151   va_end(ap);
152
153   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
154     Error(ERR_EXIT, "string too long in DrawTextF() -- aborting");
155
156   DrawText(gfx.sx + x, gfx.sy + y, buffer, font_nr);
157 }
158
159 void DrawTextFCentered(int y, int font_nr, char *format, ...)
160 {
161   char buffer[MAX_OUTPUT_LINESIZE + 1];
162   va_list ap;
163
164   va_start(ap, format);
165   vsprintf(buffer, format, ap);
166   va_end(ap);
167
168   if (strlen(buffer) > MAX_OUTPUT_LINESIZE)
169     Error(ERR_EXIT, "string too long in DrawTextFCentered() -- aborting");
170
171   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(buffer, font_nr)) / 2,
172            gfx.sy + y, buffer, font_nr);
173 }
174
175 void DrawTextS(int x, int y, int font_nr, char *text)
176 {
177   DrawText(gfx.sx + x, gfx.sy + y, text, font_nr);
178 }
179
180 void DrawTextSCentered(int y, int font_nr, char *text)
181 {
182   DrawText(gfx.sx + (gfx.sxsize - getTextWidth(text, font_nr)) / 2,
183            gfx.sy + y, text, font_nr);
184 }
185
186 void DrawTextSAligned(int x, int y, char *text, int font_nr, int align)
187 {
188   DrawText(gfx.sx + ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
189            gfx.sx + y, text, font_nr);
190 }
191
192 void DrawTextAligned(int x, int y, char *text, int font_nr, int align)
193 {
194   DrawText(ALIGNED_XPOS(x, getTextWidth(text, font_nr), align),
195            y, text, font_nr);
196 }
197
198 void DrawText(int x, int y, char *text, int font_nr)
199 {
200   int mask_mode = BLIT_OPAQUE;
201
202   if (DrawingOnBackground(x, y))
203     mask_mode = BLIT_ON_BACKGROUND;
204
205   DrawTextExt(drawto, x, y, text, font_nr, mask_mode);
206
207   if (IN_GFX_FIELD_FULL(x, y))
208     redraw_mask |= REDRAW_FIELD;
209   else if (IN_GFX_DOOR_1(x, y))
210     redraw_mask |= REDRAW_DOOR_1;
211   else if (IN_GFX_DOOR_2(x, y))
212     redraw_mask |= REDRAW_DOOR_2;
213   else if (IN_GFX_DOOR_3(x, y))
214     redraw_mask |= REDRAW_DOOR_3;
215   else
216     redraw_mask |= REDRAW_ALL;
217 }
218
219 void DrawTextExt(DrawBuffer *dst_bitmap, int dst_x, int dst_y, char *text,
220                  int font_nr, int mask_mode)
221 {
222   struct FontBitmapInfo *font = getFontBitmapInfo(font_nr);
223   int font_width = getFontWidth(font_nr);
224   int font_height = getFontHeight(font_nr);
225   Bitmap *src_bitmap;
226   int src_x, src_y;
227   char *text_ptr = text;
228
229   if (font->bitmap == NULL)
230     return;
231
232   /* skip text to be printed outside the window (left/right will be clipped) */
233   if (dst_y < 0 || dst_y + font_height > video.height)
234     return;
235
236   /* add offset for drawing font characters */
237   dst_x += font->draw_xoffset;
238   dst_y += font->draw_yoffset;
239
240   while (*text_ptr)
241   {
242     char c = *text_ptr++;
243
244     if (c == '\n')
245       c = ' ';          /* print space instead of newline */
246
247     getFontCharSource(font_nr, c, &src_bitmap, &src_x, &src_y);
248
249     /* clip text at the left side of the window */
250     if (dst_x < 0)
251     {
252       dst_x += font_width;
253
254       continue;
255     }
256
257     /* clip text at the right side of the window */
258     if (dst_x + font_width > video.width)
259       break;
260
261     if (mask_mode == BLIT_INVERSE)      /* special mode for text gadgets */
262     {
263       /* first step: draw solid colored rectangle (use "cursor" character) */
264       if (strlen(text) == 1)    /* only one char inverted => draw cursor */
265       {
266         Bitmap *cursor_bitmap;
267         int cursor_x, cursor_y;
268
269         getFontCharSource(font_nr, FONT_ASCII_CURSOR, &cursor_bitmap,
270                           &cursor_x, &cursor_y);
271
272         BlitBitmap(cursor_bitmap, dst_bitmap, cursor_x, cursor_y,
273                    font_width, font_height, dst_x, dst_y);
274       }
275
276       /* second step: draw masked inverted character */
277       SDLCopyInverseMasked(src_bitmap, dst_bitmap, src_x, src_y,
278                            font_width, font_height, dst_x, dst_y);
279     }
280     else if (mask_mode == BLIT_MASKED || mask_mode == BLIT_ON_BACKGROUND)
281     {
282       if (mask_mode == BLIT_ON_BACKGROUND)
283       {
284         /* clear font character background */
285         ClearRectangleOnBackground(dst_bitmap, dst_x, dst_y,
286                                    font_width, font_height);
287       }
288
289       BlitBitmapMasked(src_bitmap, dst_bitmap, src_x, src_y,
290                        font_width, font_height, dst_x, dst_y);
291     }
292     else        /* normal, non-masked font blitting */
293     {
294       BlitBitmap(src_bitmap, dst_bitmap, src_x, src_y,
295                  font_width, font_height, dst_x, dst_y);
296     }
297
298     dst_x += font_width;
299   }
300 }
301
302
303 /* ========================================================================= */
304 /* text buffer drawing functions                                             */
305 /* ========================================================================= */
306
307 #define MAX_LINES_FROM_FILE             1024
308
309 char *GetTextBufferFromFile(char *filename, int max_lines)
310 {
311   File *file;
312   char *buffer;
313   int num_lines = 0;
314
315   if (filename == NULL)
316     return NULL;
317
318   if (!(file = openFile(filename, MODE_READ)))
319     return NULL;
320
321   buffer = checked_calloc(1);   /* start with valid, but empty text buffer */
322
323   while (!checkEndOfFile(file) && num_lines < max_lines)
324   {
325     char line[MAX_LINE_LEN];
326
327     /* read next line of input file */
328     if (!getStringFromFile(file, line, MAX_LINE_LEN))
329       break;
330
331     buffer = checked_realloc(buffer, strlen(buffer) + strlen(line) + 1);
332
333     strcat(buffer, line);
334
335     num_lines++;
336   }
337
338   closeFile(file);
339
340   return buffer;
341 }
342
343 static boolean RenderLineToBuffer(char **src_buffer_ptr, char *dst_buffer,
344                                   int *dst_buffer_len, int line_length,
345                                   boolean last_line_was_empty)
346 {
347   char *text_ptr = *src_buffer_ptr;
348   char *buffer = dst_buffer;
349   int buffer_len = *dst_buffer_len;
350   boolean buffer_filled = FALSE;
351
352   while (*text_ptr)
353   {
354     char *word_ptr;
355     int word_len;
356
357     /* skip leading whitespaces */
358     while (*text_ptr == ' ' || *text_ptr == '\t')
359       text_ptr++;
360
361     word_ptr = text_ptr;
362     word_len = 0;
363
364     /* look for end of next word */
365     while (*word_ptr != ' ' && *word_ptr != '\t' && *word_ptr != '\0')
366     {
367       word_ptr++;
368       word_len++;
369     }
370
371     if (word_len == 0)
372     {
373       continue;
374     }
375     else if (*text_ptr == '\n')         /* special case: force empty line */
376     {
377       if (buffer_len == 0)
378         text_ptr++;
379
380       /* prevent printing of multiple empty lines */
381       if (buffer_len > 0 || !last_line_was_empty)
382         buffer_filled = TRUE;
383     }
384     else if (word_len < line_length - buffer_len)
385     {
386       /* word fits into text buffer -- add word */
387
388       if (buffer_len > 0)
389         buffer[buffer_len++] = ' ';
390
391       strncpy(&buffer[buffer_len], text_ptr, word_len);
392       buffer_len += word_len;
393       buffer[buffer_len] = '\0';
394       text_ptr += word_len;
395     }
396     else if (buffer_len > 0)
397     {
398       /* not enough space left for word in text buffer -- print buffer */
399
400       buffer_filled = TRUE;
401     }
402     else
403     {
404       /* word does not fit at all into empty text buffer -- cut word */
405
406       strncpy(buffer, text_ptr, line_length);
407       buffer[line_length] = '\0';
408       text_ptr += line_length;
409       buffer_filled = TRUE;
410     }
411
412     if (buffer_filled)
413       break;
414   }
415
416   *src_buffer_ptr = text_ptr;
417   *dst_buffer_len = buffer_len;
418
419   return buffer_filled;
420 }
421
422 static boolean getCheckedTokenValueFromString(char *string, char **token,
423                                               char **value)
424 {
425   char *ptr;
426
427   if (!getTokenValueFromString(string, token, value))
428     return FALSE;
429
430   if (**token != '.')                   /* token should begin with dot */
431     return FALSE;
432
433   for (ptr = *token; *ptr; ptr++)       /* token should contain no whitespace */
434     if (*ptr == ' ' || *ptr == '\t')
435       return FALSE;
436
437   for (ptr = *value; *ptr; ptr++)       /* value should contain no whitespace */
438     if (*ptr == ' ' || *ptr == '\t')
439       return FALSE;
440
441   return TRUE;
442 }
443
444 static void DrawTextBuffer_Flush(int x, int y, char *buffer, int font_nr,
445                                  int line_length, int cut_length,
446                                  int line_spacing, int mask_mode,
447                                  boolean centered, int current_line)
448 {
449   int buffer_len = strlen(buffer);
450   int font_width = getFontWidth(font_nr);
451   int font_height = getFontHeight(font_nr);
452   int offset_chars = (centered ? (line_length - buffer_len) / 2 : 0);
453   int offset_xsize =
454     (centered ? font_width * (line_length - buffer_len) / 2 : 0);
455   int final_cut_length = MAX(0, cut_length - offset_chars);
456   int xx = x + offset_xsize;
457   int yy = y + current_line * (font_height + line_spacing);
458
459   buffer[final_cut_length] = '\0';
460
461   if (mask_mode != -1)
462     DrawTextExt(drawto, xx, yy, buffer, font_nr, mask_mode);
463   else
464     DrawText(xx, yy, buffer, font_nr);
465 }
466
467 int DrawTextBuffer(int x, int y, char *text_buffer, int font_nr,
468                    int line_length, int cut_length, int max_lines,
469                    int line_spacing, int mask_mode, boolean autowrap,
470                    boolean centered, boolean parse_comments)
471 {
472   char buffer[line_length + 1];
473   int buffer_len;
474   int current_line = 0;
475
476   if (text_buffer == NULL || *text_buffer == '\0')
477     return 0;
478
479   if (current_line >= max_lines)
480     return 0;
481
482   if (cut_length == -1)
483     cut_length = line_length;
484
485   buffer[0] = '\0';
486   buffer_len = 0;
487
488   while (*text_buffer && current_line < max_lines)
489   {
490     char line[MAX_LINE_LEN + 1];
491     char *line_ptr;
492     boolean last_line_was_empty = TRUE;
493     int num_line_chars = MAX_LINE_LEN;
494     int i;
495
496     /* copy next line from text buffer to line buffer (nearly fgets() style) */
497     for (i = 0; i < num_line_chars && *text_buffer; i++)
498       if ((line[i] = *text_buffer++) == '\n')
499         break;
500     line[i] = '\0';
501
502     /* prevent 'num_line_chars' sized lines to cause additional empty line */
503     if (i == num_line_chars && *text_buffer == '\n')
504       text_buffer++;
505
506     /* skip comments (lines directly beginning with '#') */
507     if (line[0] == '#' && parse_comments)
508     {
509       char *token, *value;
510
511       /* try to read generic token/value pair definition after comment sign */
512       if (getCheckedTokenValueFromString(line + 1, &token, &value))
513       {
514         /* if found, flush the current buffer, if non-empty */
515         if (buffer_len > 0 && current_line < max_lines)
516         {
517           DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
518                                line_spacing, mask_mode, centered, current_line);
519
520           current_line++;
521
522           buffer[0] = '\0';
523           buffer_len = 0;
524         }
525
526         if (strEqual(token, ".font"))
527           font_nr = gfx.get_font_from_token_function(value);
528         else if (strEqual(token, ".autowrap"))
529           autowrap = get_boolean_from_string(value);
530         else if (strEqual(token, ".centered"))
531           centered = get_boolean_from_string(value);
532         else if (strEqual(token, ".parse_comments"))
533           parse_comments = get_boolean_from_string(value);
534       }
535
536       continue;
537     }
538
539     /* cut trailing newline and carriage return from input line */
540     for (line_ptr = line; *line_ptr; line_ptr++)
541     {
542       if (*line_ptr == '\n' || *line_ptr == '\r')
543       {
544         *line_ptr = '\0';
545         break;
546       }
547     }
548
549     if (strlen(line) == 0)              /* special case: force empty line */
550       strcpy(line, "\n");
551
552     line_ptr = line;
553
554     while (*line_ptr && current_line < max_lines)
555     {
556       boolean buffer_filled;
557
558       if (autowrap)
559       {
560         buffer_filled = RenderLineToBuffer(&line_ptr, buffer, &buffer_len,
561                                            line_length, last_line_was_empty);
562       }
563       else
564       {
565         if (strlen(line_ptr) <= line_length)
566         {
567           buffer_len = strlen(line_ptr);
568           strcpy(buffer, line_ptr);
569         }
570         else
571         {
572           buffer_len = line_length;
573           strncpy(buffer, line_ptr, line_length);
574         }
575
576         buffer[buffer_len] = '\0';
577         line_ptr += buffer_len;
578
579         buffer_filled = TRUE;
580       }
581
582       if (buffer_filled)
583       {
584         DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
585                              line_spacing, mask_mode, centered, current_line);
586         current_line++;
587
588         last_line_was_empty = (buffer_len == 0);
589
590         buffer[0] = '\0';
591         buffer_len = 0;
592       }
593     }
594   }
595
596   if (buffer_len > 0 && current_line < max_lines)
597   {
598     DrawTextBuffer_Flush(x, y, buffer, font_nr, line_length, cut_length,
599                          line_spacing, mask_mode, centered, current_line);
600     current_line++;
601   }
602
603   return current_line;
604 }
605
606 int DrawTextBufferVA(int x, int y, char *format, va_list ap, int font_nr,
607                      int line_length, int cut_length, int max_lines,
608                      int line_spacing, int mask_mode, boolean autowrap,
609                      boolean centered, boolean parse_comments)
610 {
611   char text_buffer[MAX_OUTPUT_LINESIZE];
612   int text_length = vsnprintf(text_buffer, MAX_OUTPUT_LINESIZE, format, ap);
613
614   if (text_length >= MAX_OUTPUT_LINESIZE)
615     Error(ERR_WARN, "string too long in DrawTextBufferVA() -- truncated");
616
617   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
618                                          line_length, cut_length, max_lines,
619                                          line_spacing, mask_mode, autowrap,
620                                          centered, parse_comments);
621   return num_lines_printed;
622 }
623
624 int DrawTextFile(int x, int y, char *filename, int font_nr,
625                  int line_length, int cut_length, int max_lines,
626                  int line_spacing, int mask_mode, boolean autowrap,
627                  boolean centered, boolean parse_comments)
628 {
629   char *text_buffer = GetTextBufferFromFile(filename, MAX_LINES_FROM_FILE);
630   int num_lines_printed = DrawTextBuffer(x, y, text_buffer, font_nr,
631                                          line_length, cut_length, max_lines,
632                                          line_spacing, mask_mode, autowrap,
633                                          centered, parse_comments);
634   checked_free(text_buffer);
635
636   return num_lines_printed;
637 }