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