Debian Codegraph @

engine/video/font.cpp

raw
1 // ____ _ __
2 // / __ )____ _____ | | / /___ ___________
3 // / __ / __ \/ ___/ | | /| / / __ `/ ___/ ___/
4 // / /_/ / /_/ (__ ) | |/ |/ / /_/ / / (__ )
5 // /_____/\____/____/ |__/|__/\__,_/_/ /____/
6 //
7 // A futuristic real-time strategy game.
8 // This file is part of Bos Wars.
9 //
10 /**@name font.cpp - The color fonts. */
11 //
12 // (c) Copyright 1998-2008 by Lutz Sammer, Jimmy Salmon, Nehal Mistry
13 //
14 // This program is free software; you can redistribute it and/or modify
15 // it under the terms of the GNU General Public License as published by
16 // the Free Software Foundation; only version 2 of the License.
17 //
18 // This program is distributed in the hope that it will be useful,
19 // but WITHOUT ANY WARRANTY; without even the implied warranty of
20 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 // GNU General Public License for more details.
22 //
23 // You should have received a copy of the GNU General Public License
24 // along with this program; if not, write to the Free Software
25 // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA
26 // 02111-1307, USA.
27 //
28
29 //@{
30
31 /*----------------------------------------------------------------------------
32 -- Includes
33 ----------------------------------------------------------------------------*/
34
35 #include <stdio.h>
36 #include <stdlib.h>
37 #include <string.h>
38
39 #include "stratagus.h"
40
41 #include <string>
42 #include <vector>
43 #include <map>
44 #include <memory>
45
46 #include "video.h"
47 #include "font.h"
48 #include "script.h"
49
50 #include "intern_video.h"
51
52 /*----------------------------------------------------------------------------
53 -- Types
54 ----------------------------------------------------------------------------*/
55
56 namespace {
57 /**
58 ** A smart pointer that maintains CGraphic::Refs.
59 **
60 ** There is no CGraphicPtr(CGraphic *) constructor, because
61 ** that would too easily lead to bugs. Instead, you can set
62 ** the G member directly.
63 **
64 ** @todo Publish CGraphicPtr to Lua, instead of CGraphic itself.
65 ** That should make it easier to ensure that CGraphic::Refs
66 ** remains positive as long as references exist in Lua.
67 */
68 struct CGraphicPtr {
69 CGraphic *G;
70
71 CGraphicPtr(): G(NULL)
72 {
73 }
74
75 ~CGraphicPtr()
76 {
77 CGraphic::Free(this->G);
78 }
79
80 CGraphicPtr(const CGraphicPtr &other): G(other.G)
81 {
82 if (this->G) {
83 this->G->Refs++;
84 }
85 }
86
87 CGraphicPtr &operator =(const CGraphicPtr &other)
88 {
89 if (other.G != this->G) {
90 CGraphic::Free(this->G);
91 this->G = other.G;
92 if (this->G) {
93 this->G->Refs++;
94 }
95 }
96 return *this;
97 }
98
99 operator CGraphic *() const
100 {
101 return this->G;
102 }
103
104 CGraphic *operator ->() const
105 {
106 return this->G;
107 }
108
109 CGraphic *Detach()
110 {
111 CGraphic *ret = this->G;
112 this->G = NULL;
113 return ret;
114 }
115 };
116
117 /**
118 ** Swaps the pointers of two CGraphicPtr objects.
119 */
120 void swap(CGraphicPtr &a, CGraphicPtr &b)
121 {
122 std::swap(a.G, b.G);
123 }
124 }
125
126 /**
127 ** Two fonts that use the same textures: a markup font that recognizes
128 ** markup in strings drawn with it, and a plain-text font that
129 ** doesn't.
130 */
131 class CFontFamily {
132 friend class CFont;
133
134 public:
135 explicit CFontFamily(const std::string &ident);
136 ~CFontFamily();
137
138 void MeasureWidths();
139 void MakeFontColorGraphics();
140 CGraphic *FontColorGraphic(CFontColor *);
141 void FreeFontColorGraphics();
142
143 /**
144 ** A font that does not recognize any markup in strings.
145 **
146 ** This should be used in text-input fields and text boxes
147 ** because GUIChan lets the user type directly into those
148 ** and does not know how to escape markup.
149 */
150 CFont PlainTextFont;
151
152 /**
153 ** A font that recognizes markup in strings.
154 */
155 CFont MarkupFont;
156
157 /**
158 ** How many Unicode characters the font supports.
159 ** The first of them is always U+0020 SPACE.
160 ** Each character corresponds to a glyph in the graphic.
161 ** (This implementation does not support combining characters.)
162 */
163 int GlyphCount;
164
165 /**
166 ** The width of each Unicode character that the font supports.
167 ** CharWidth[0] is the width of U+0020 SPACE,
168 ** CharWidth[1] is the width of U+0021 EXCLAMATION MARK,
169 ** and so on. This array has GlyphCount elements.
170 */
171 char *CharWidth;
172
173 /// Graphic object used to draw
174 CGraphicPtr G;
175
176 private:
177 /// Ident of the font.
178 const std::string Ident;
179
180 /**
181 ** Textures for each CFontColor. Used for OpenGL only.
182 */
183 typedef std::map<CFontColor *, CGraphic *> FontColorGraphicsType;
184 FontColorGraphicsType FontColorGraphics;
185
186 private: // undefined
187 CFontFamily(const CFontFamily &);
188 CFontFamily &operator =(const CFontFamily &);
189 };
190
191 /*----------------------------------------------------------------------------
192 -- Variables
193 ----------------------------------------------------------------------------*/
194
195 typedef std::map<std::string, CFontFamily *> FontFamiliesType;
196 static FontFamiliesType FontFamilies; /// Map of ident to font family.
197
198 static std::vector<CFontColor *> AllFontColors; /// Vector of all font colors.
199 static std::map<std::string, CFontColor *> FontColors; /// Map of ident to font color.
200
201 static CFontColor *FontColor; /// Current font color
202
203 static CFontColor *LastTextColor; /// Last text color
204 static CFontColor *DefaultTextColor; /// Default text color
205 static CFontColor *ReverseTextColor; /// Reverse text color
206 static std::string DefaultNormalColorIndex; /// Default normal color index
207 static std::string DefaultReverseColorIndex; /// Default reverse color index
208
209 // FIXME: remove these
210 CFont *SmallFont; /// Small font used in stats
211 CFont *GameFont; /// Normal font used in game
212 CFont *LargeFont; /// Large font used in menus
213
214
215 /*----------------------------------------------------------------------------
216 -- Guichan Functions
217 ----------------------------------------------------------------------------*/
218
219 int CFont::Height() const
220 {
221 return this->Family->G->Height;
222 }
223
224 bool CFont::IsLoaded() const
225 {
226 return this->Family->G && this->Family->G->IsLoaded();
227 }
228
229 void CFont::drawString(gcn::Graphics *graphics, const std::string &txt,
230 int x, int y)
231 {
232 const gcn::ClipRectangle &r = graphics->getCurrentClipArea();
233 int right = std::min(r.x + r.width - 1, Video.Width - 1);
234 int bottom = std::min(r.y + r.height - 1, Video.Height - 1);
235
236 if (r.x > right || r.y > bottom) {
237 return;
238 }
239
240 PushClipping();
241 SetClipping(r.x, r.y, right, bottom);
242 VideoDrawTextClip(x + r.xOffset, y + r.yOffset, this, txt);
243 PopClipping();
244 }
245
246 /*----------------------------------------------------------------------------
247 -- Functions
248 ----------------------------------------------------------------------------*/
249
250 /**
251 ** CFontFamily constructor.
252 **
253 ** This does not set CFontFamily::G. That must be done separately.
254 */
255 CFontFamily::CFontFamily(const std::string &ident)
256 : Ident(ident)
257 {
258 this->PlainTextFont.Family = this;
259 this->MarkupFont.Family = this;
260 this->GlyphCount = 0;
261 this->CharWidth = NULL;
262 }
263
264 /**
265 ** CFontFamily destructor.
266 */
267 CFontFamily::~CFontFamily()
268 {
269 this->FreeFontColorGraphics();
270 delete[] this->CharWidth;
271 }
272
273 /**
274 ** CFont constructor.
275 **
276 ** All the hard work is done in CFont::New instead.
277 */
278 CFont::CFont(): Family(NULL)
279 {
280 }
281
282 /**
283 ** CFont destructor.
284 **
285 ** Because CFont nowadays has just a CFontFamily pointer
286 ** and exists only as part of the CFontFamily,
287 ** there is nothing to do here.
288 */
289 CFont::~CFont()
290 {
291 }
292
293 /**
294 ** Gets the plain-text font in the same font family.
295 **
296 ** The plain-text font does not recognize markup in strings
297 ** and is therefore suitable for widgets to which the user
298 ** can directly type text.
299 **
300 ** @return The plain-text font in the same font family
301 ** as this font.
302 */
303 CFont *CFont::PlainText()
304 {
305 return &this->Family->PlainTextFont;
306 }
307
308 /**
309 ** Checks whether this font is a plain-text font.
310 **
311 ** @return true if this font is a plain-text font;
312 ** false if this font recognizes markup in strings.
313 */
314 bool CFont::IsPlainText() const
315 {
316 return this == &this->Family->PlainTextFont;
317 }
318
319 /**
320 ** Draw character with current color.
321 **
322 ** @param g Pointer to object
323 ** @param gx X offset into object
324 ** @param gy Y offset into object
325 ** @param w width to display
326 ** @param h height to display
327 ** @param x X screen position
328 ** @param y Y screen position
329 */
330 static void VideoDrawChar(const CGraphic *g,
331 int gx, int gy, int w, int h, int x, int y)
332 {
333 if (!UseOpenGL) {
334 SDL_Rect srect = {
335 static_cast<Sint16>(gx),
336 static_cast<Sint16>(gy),
337 static_cast<Uint16>(w),
338 static_cast<Uint16>(h)
339 };
340 SDL_Rect drect = {
341 static_cast<Sint16>(x),
342 static_cast<Sint16>(y),
343 0, // SDL_BlitSurface ignores the width and height.
344 0
345 };
346
347 SDL_SetColors(g->Surface, FontColor->Colors, 0, MaxFontColors);
348 SDL_BlitSurface(g->Surface, &srect, TheScreen, &drect);
349 } else {
350 g->DrawSub(gx, gy, w, h, x, y);
351 }
352 }
353
354 /**
355 ** Set the default text colors.
356 **
357 ** @param normal Normal text color.
358 ** @param reverse Reverse text color.
359 */
360 void SetDefaultTextColors(const std::string &normal, const std::string &reverse)
361 {
362 DefaultNormalColorIndex = normal;
363 DefaultReverseColorIndex = reverse;
364 LastTextColor = DefaultTextColor = FontColor = CFontColor::Get(normal);
365 ReverseTextColor = CFontColor::Get(reverse);
366 }
367
368 /**
369 ** Get the default text colors.
370 **
371 ** @param normalp Normal text color pointer.
372 ** @param reversep Reverse text color pointer.
373 */
374 void GetDefaultTextColors(std::string &normalp, std::string &reversep)
375 {
376 normalp = DefaultNormalColorIndex;
377 reversep = DefaultReverseColorIndex;
378 }
379
380 /**
381 ** Get the next utf8 character from a string
382 */
383 static bool GetUTF8(const std::string &text, size_t &pos, int &utf8)
384 {
385 // end of string
386 if (pos >= text.size()) {
387 return false;
388 }
389
390 int count;
391 char c = text[pos++];
392
393 // ascii
394 if (!(c & 0x80)) {
395 utf8 = c;
396 return true;
397 }
398
399 if ((c & 0xE0) == 0xC0) {
400 utf8 = (c & 0x1F);
401 count = 1;
402 } else if ((c & 0xF0) == 0xE0) {
403 utf8 = (c & 0x0F);
404 count = 2;
405 } else if ((c & 0xF8) == 0xF0) {
406 utf8 = (c & 0x07);
407 count = 3;
408 } else if ((c & 0xFC) == 0xF8) {
409 utf8 = (c & 0x03);
410 count = 4;
411 } else if (( c & 0xFE) == 0xFC) {
412 utf8 = (c & 0x01);
413 count = 5;
414 } else {
415 DebugPrint("Invalid utf8\n");
416 return false;
417 }
418
419 while (count--) {
420 c = text[pos++];
421 if ((c & 0xC0) != 0x80) {
422 DebugPrint("Invalid utf8\n");
423 return false;
424 }
425 utf8 <<= 6;
426 utf8 |= (c & 0x3F);
427 }
428
429 return true;
430 }
431
432 /**
433 ** Returns the pixel width of text.
434 **
435 ** @param text Text to calculate the width of.
436 **
437 ** @return The width in pixels of the text.
438 */
439 int CFont::Width(const std::string &text) const
440 {
441 int width = 0;
442 bool isformat = false;
443 int utf8;
444 size_t pos = 0;
445
446 bool isPlainText = this->IsPlainText();
447
448 while (GetUTF8(text, pos, utf8)) {
449 if (utf8 == '~' && !isPlainText) {
450 if (pos >= text.size()) { // bad formatted string
451 break;
452 }
453 if (text[pos] == '<' || text[pos] == '>') {
454 isformat = false;
455 ++pos;
456 continue;
457 }
458 if (text[pos] == '!') {
459 ++pos;
460 continue;
461 }
462 if (text[pos] != '~') { // ~~ -> ~
463 isformat = !isformat;
464 continue;
465 }
466 }
467 if (!isformat) {
468 int glyph = utf8 - 32;
469 if (glyph < 0 || glyph >= this->Family->GlyphCount) {
470 glyph = 0;
471 }
472 width += this->Family->CharWidth[glyph] + 1;
473 }
474 }
475 return width;
476 }
477
478 extern int convertKey(const char *key);
479
480 /**
481 ** Get the hot key from a string
482 */
483 int GetHotKey(const std::string &text)
484 {
485 int hotkey = 0;
486 int utf8;
487 size_t pos = 0;
488
489 while (GetUTF8(text, pos, utf8)) {
490 if (utf8 == '~') {
491 if (pos >= text.size()) {
492 break;
493 }
494 if (text[pos] == '<') {
495 ++pos;
496 size_t endpos = pos;
497 while (endpos < text.size()) {
498 if (text[endpos] == '~') {
499 break;
500 }
501 ++endpos;
502 }
503 std::string key = text.substr(pos, endpos - pos);
504 hotkey = convertKey(key.c_str());
505 break;
506 }
507 if (text[pos] == '!') {
508 ++pos;
509 if (pos >= text.size()) {
510 break;
511 }
512 GetUTF8(text, pos, utf8);
513 hotkey = utf8;
514 break;
515 }
516 }
517 }
518
519 return hotkey;
520 }
521
522 /**
523 ** Draw character with current color clipped into 8 bit framebuffer.
524 **
525 ** @param g Pointer to object
526 ** @param gx X offset into object
527 ** @param gy Y offset into object
528 ** @param w width to display
529 ** @param h height to display
530 ** @param x X screen position
531 ** @param y Y screen position
532 */
533 static void VideoDrawCharClip(const CGraphic *g, int gx, int gy, int w, int h,
534 int x, int y)
535 {
536 int ox;
537 int oy;
538 int ex;
539 CLIP_RECTANGLE_OFS(x, y, w, h, ox, oy, ex);
540 VideoDrawChar(g, gx + ox, gy + oy, w, h, x, y);
541 ex = ex; // make the compiler to shut up.
542 }
543
544 /**
545 ** Draw text with font at x,y clipped/unclipped.
546 **
547 ** ~ is special prefix.
548 ** ~~ is the ~ character self.
549 ** ~! print next character reverse.
550 ** ~< start reverse.
551 ** ~> switch back to last used color.
552 **
553 ** @param x X screen position
554 ** @param y Y screen position
555 ** @param font Font number
556 ** @param text Text to be displayed.
557 ** @param clip Flag to clip the text.
558 **
559 ** @return The length of the printed text.
560 */
561 static int DoDrawText(int x, int y, CFontFamily *fontFamily,
562 bool isPlainText, const std::string &text, bool clip)
563 {
564 int w;
565 int width;
566 CFontColor *rev;
567 char *color;
568 const char *p;
569 void (*DrawChar)(const CGraphic *, int, int, int, int, int, int);
570 int ipr;
571 int c;
572 CGraphic *g;
573 int utf8;
574 size_t pos;
575
576 if (clip) {
577 DrawChar = VideoDrawCharClip;
578 } else {
579 DrawChar = VideoDrawChar;
580 }
581
582 if (!UseOpenGL) {
583 g = fontFamily->G;
584 } else {
585 g = fontFamily->FontColorGraphic(FontColor);
586 }
587
588 rev = NULL;
589 width = 0;
590 pos = 0;
591 while (GetUTF8(text, pos, utf8)) {
592 if (utf8 == '~' && !isPlainText) {
593 switch (text[pos]) {
594 case '\0': // wrong formatted string.
595 DebugPrint("oops, format your ~\n");
596 return width;
597 case '~':
598 ++pos;
599 break;
600 case '!':
601 rev = FontColor;
602 FontColor = ReverseTextColor;
603 if (UseOpenGL) {
604 g = fontFamily->FontColorGraphic(FontColor);
605 }
606 ++pos;
607 continue;
608 case '<':
609 LastTextColor = FontColor;
610 FontColor = ReverseTextColor;
611 if (UseOpenGL) {
612 g = fontFamily->FontColorGraphic(FontColor);
613 }
614 ++pos;
615 continue;
616 case '>':
617 rev = LastTextColor; // swap last and current color
618 LastTextColor = FontColor;
619 FontColor = rev;
620 if (UseOpenGL) {
621 g = fontFamily->FontColorGraphic(FontColor);
622 }
623 ++pos;
624 continue;
625
626 default:
627 p = text.c_str() + pos;
628 while (*p && *p !='~') {
629 ++p;
630 }
631 if (!*p) {
632 DebugPrint("oops, format your ~\n");
633 return width;
634 }
635 color = new char[p - (text.c_str() + pos) + 1];
636 memcpy(color, text.c_str() + pos, p - (text.c_str() + pos));
637 color[p - (text.c_str() + pos)] = '\0';
638 pos = p - text.c_str() + 1;
639 LastTextColor = FontColor;
640 CFontColor *fc = CFontColor::Get(color);
641 if (fc) {
642 FontColor = fc;
643 if (UseOpenGL) {
644 g = fontFamily->FontColorGraphic(fc);
645 }
646 }
647 delete[] color;
648 continue;
649 }
650 }
651
652 c = utf8 - 32;
653 Assert(c >= 0);
654
655 ipr = fontFamily->G->GraphicWidth / fontFamily->G->Width;
656 if (c >= 0 && c < ipr * fontFamily->G->GraphicHeight / fontFamily->G->Height) {
657 w = fontFamily->CharWidth[c];
658 DrawChar(g, (c % ipr) * fontFamily->G->Width, (c / ipr) * fontFamily->G->Height,
659 w, fontFamily->G->Height, x + width, y);
660 } else {
661 w = fontFamily->CharWidth[0];
662 DrawChar(g, 0, 0, w, fontFamily->G->Height, x + width, y);
663 }
664 width += w + 1;
665 if (rev) {
666 FontColor = rev;
667 if (UseOpenGL) {
668 g = fontFamily->FontColorGraphic(FontColor);
669 }
670 rev = NULL;
671 }
672 }
673
674 return width;
675 }
676
677 /**
678 ** Draw text with font at x,y unclipped.
679 **
680 ** @see DoDrawText
681 **
682 ** @param x X screen position
683 ** @param y Y screen position
684 ** @param font Font number
685 ** @param text Text to be displayed.
686 **
687 ** @return The length of the printed text.
688 */
689 int VideoDrawText(int x, int y, CFont *font, const std::string &text)
690 {
691 return DoDrawText(x, y, font->FontFamily(), font->IsPlainText(),
692 text, false);
693 }
694
695 /**
696 ** Draw text with font at x,y clipped.
697 **
698 ** @see DoDrawText.
699 **
700 ** @param x X screen position
701 ** @param y Y screen position
702 ** @param font Font number
703 ** @param text Text to be displayed.
704 **
705 ** @return The length of the printed text.
706 */
707 int VideoDrawTextClip(int x, int y, CFont *font, const std::string &text)
708 {
709 return DoDrawText(x, y, font->FontFamily(), font->IsPlainText(),
710 text, true);
711 }
712
713 /**
714 ** Draw reverse text with font at x,y unclipped.
715 **
716 ** @see DoDrawText for full description.
717 **
718 ** @param x X screen position
719 ** @param y Y screen position
720 ** @param font Font number
721 ** @param text Text to be displayed.
722 **
723 ** @return The length of the printed text.
724 */
725 int VideoDrawReverseText(int x, int y, CFont *font, const std::string &text)
726 {
727 int width;
728
729 FontColor = ReverseTextColor;
730 width = VideoDrawText(x, y, font, text);
731 FontColor = DefaultTextColor;
732
733 return width;
734 }
735
736 /**
737 ** Draw reverse text with font at x,y clipped.
738 **
739 ** @see DoDrawText for full description.
740 **
741 ** @param x X screen position
742 ** @param y Y screen position
743 ** @param font Font number
744 ** @param text Text to be displayed.
745 **
746 ** @return The length of the printed text.
747 */
748 int VideoDrawReverseTextClip(int x, int y, CFont *font, const std::string &text)
749 {
750 int width;
751
752 FontColor = ReverseTextColor;
753 width = VideoDrawTextClip(x, y, font, text);
754 FontColor = DefaultTextColor;
755
756 return width;
757 }
758
759 /**
760 ** Draw text with font at x,y centered.
761 **
762 ** @see DoDrawText for full description.
763 **
764 ** @param x X screen position
765 ** @param y Y screen position
766 ** @param font Font number
767 ** @param text Text to be displayed.
768 **
769 ** @return The length of the printed text.
770 */
771 int VideoDrawTextCentered(int x, int y, CFont *font, const std::string &text)
772 {
773 int dx;
774
775 dx = font->Width(text);
776 VideoDrawText(x - dx / 2, y, font, text);
777
778 return dx / 2;
779 }
780
781 /**
782 ** Format a number using commas
783 **
784 ** @param number Number to be formatted
785 ** @param buf Buffer to save the formatted number to
786 */
787 static void FormatNumber(int number, char *buf)
788 {
789 char bufs[sizeof(int) * 10 + 2];
790 int sl;
791 int s;
792 int d;
793
794 sl = s = d = 0;
795 sprintf_s(bufs, sizeof(bufs), "%d", number);
796 sl = strlen(bufs);
797 do {
798 if (s > 0 && s < sl && (s - (sl % 3)) % 3 == 0) {
799 buf[d++] = ',';
800 }
801 buf[d++] = bufs[s++];
802 } while (s <= sl);
803 }
804
805 /**
806 ** Draw number with font at x,y unclipped.
807 **
808 ** @param x X screen position
809 ** @param y Y screen position
810 ** @param font Font number
811 ** @param number Number to be displayed.
812 **
813 ** @return The length of the printed text.
814 */
815 int VideoDrawNumber(int x, int y, CFont *font, int number)
816 {
817 char buf[sizeof(int) * 10 + 2];
818
819 FormatNumber(number, buf);
820 return VideoDrawText(x, y, font, buf);
821 }
822
823 /**
824 ** Draw number with font at x,y clipped.
825 **
826 ** @param x X screen position
827 ** @param y Y screen position
828 ** @param font Font number
829 ** @param number Number to be displayed.
830 **
831 ** @return The length of the printed text.
832 */
833 int VideoDrawNumberClip(int x, int y, CFont *font, int number)
834 {
835 char buf[sizeof(int) * 10 + 2];
836
837 FormatNumber(number, buf);
838 return VideoDrawTextClip(x, y, font, buf);
839 }
840
841 /**
842 ** Draw reverse number with font at x,y unclipped.
843 **
844 ** @param x X screen position
845 ** @param y Y screen position
846 ** @param font Font number
847 ** @param number Number to be displayed.
848 **
849 ** @return The length of the printed text.
850 */
851 int VideoDrawReverseNumber(int x, int y, CFont *font, int number)
852 {
853 char buf[sizeof(int) * 10 + 2];
854
855 FormatNumber(number, buf);
856 return VideoDrawReverseText(x, y, font, buf);
857 }
858
859 /**
860 ** Draw reverse number with font at x,y clipped.
861 **
862 ** @param x X screen position
863 ** @param y Y screen position
864 ** @param font Font number
865 ** @param number Number to be displayed.
866 **
867 ** @return The length of the printed text.
868 */
869 int VideoDrawReverseNumberClip(int x, int y, CFont *font, int number)
870 {
871 char buf[sizeof(int) * 10 + 2];
872
873 FormatNumber(number, buf);
874 return VideoDrawReverseTextClip(x, y, font, buf);
875 }
876
877 /**
878 ** Calculate the width of each character
879 */
880 void CFontFamily::MeasureWidths()
881 {
882 const unsigned char *sp;
883 const unsigned char *lp;
884 const unsigned char *gp;
885 Uint32 ckey;
886 int ipr; // images per row
887
888 GlyphCount = G->GraphicWidth / G->Width * G->GraphicHeight / G->Height;
889 delete[] CharWidth;
890 CharWidth = new char[GlyphCount];
891 memset(CharWidth, 0, GlyphCount);
892 CharWidth[0] = G->Width / 2; // a reasonable value for SPACE
893 ckey = G->Surface->format->colorkey;
894 ipr = G->Surface->w / G->Width;
895
896 SDL_LockSurface(G->Surface);
897 for (int y = 1; y < GlyphCount; ++y) {
898 sp = (const unsigned char *)G->Surface->pixels +
899 (y / ipr) * G->Surface->pitch * G->Height +
900 (y % ipr) * G->Width - 1;
901 gp = sp + G->Surface->pitch * G->Height;
902 // Bail out if no letters left
903 if (gp >= ((const unsigned char *)G->Surface->pixels +
904 G->Surface->pitch * G->GraphicHeight)) {
905 break;
906 }
907 while (sp < gp) {
908 lp = sp + G->Width;
909 for (; sp < lp; --lp) {
910 if (*lp != ckey && *lp != 7) {
911 if (lp - sp > CharWidth[y]) { // max width
912 CharWidth[y] = lp - sp;
913 }
914 }
915 }
916 sp += G->Surface->pitch;
917 }
918
919 }
920 SDL_UnlockSurface(G->Surface);
921 }
922
923 /**
924 ** Make or retrieve a variant of the graphic, colorized for the
925 ** specified CFontColor. This function is used for OpenGL only.
926 **
927 ** @param fc Which color you want. This function saves the address
928 ** of the CFontColor object and uses that for checking whether a
929 ** suitably colorized variant already exists.
930 **
931 ** @return The colorized graphic. The caller must not free it.
932 */
933 CGraphic *CFontFamily::FontColorGraphic(CFontColor *fc)
934 {
935 // Only OpenGL needs color-specific textures.
936 Assert(UseOpenGL);
937
938 FontColorGraphicsType::iterator found
939 = this->FontColorGraphics.find(fc);
940 if (found != this->FontColorGraphics.end()) {
941 // already loaded
942 return found->second;
943 }
944
945 // The CGraphic we'll create will not have its own Surface;
946 // instead, it shares the Surface of this->G. To prevent
947 // CGraphic::Free from freeing the shared surface, we reset
948 // newg->Surface to NULL immediately after MakeTexture.
949 // We must do that even if MakeTexture throws std::bad_alloc.
950 // Use a destructor rather than try...catch, for better
951 // backtraces on uncaught exceptions.
952 struct CSurfaceSharingGraphicPtr: CGraphicPtr
953 {
954 ~CSurfaceSharingGraphicPtr()
955 {
956 if (this->G) {
957 this->G->Surface = NULL;
958 }
959 }
960 };
961
962 CSurfaceSharingGraphicPtr newg;
963 newg.G = new CGraphic;
964 newg->Width = this->G->Width;
965 newg->Height = this->G->Height;
966 newg->NumFrames = this->G->NumFrames;
967 newg->GraphicWidth = this->G->GraphicWidth;
968 newg->GraphicHeight = this->G->GraphicHeight;
969
970 SDL_Surface *s = this->G->Surface;
971 SDL_LockSurface(s);
972 for (int j = 0; j < MaxFontColors; ++j) {
973 s->format->palette->colors[j] = fc->Colors[j];
974 }
975 SDL_UnlockSurface(s);
976
977 newg->Surface = s;
978 MakeTexture(newg);
979 newg->Surface = NULL;
980
981 this->FontColorGraphics.insert(
982 FontColorGraphicsType::value_type(fc, newg));
983 return newg.Detach();
984 }
985
986 /**
987 ** Makes colorized variants of the graphic for all known CFontColor
988 ** objects. This function is used for OpenGL only.
989 */
990 void CFontFamily::MakeFontColorGraphics()
991 {
992 // Only OpenGL needs color-specific textures.
993 Assert(UseOpenGL);
994
995 for (int i = 0; i < (int)AllFontColors.size(); ++i) {
996 CFontColor *fc = AllFontColors[i];
997 this->FontColorGraphic(fc);
998 }
999 }
1000
1001 /**
1002 ** Frees all colorized variants of the graphic. This function is
1003 ** needed for OpenGL only, but is safe to call without OpenGL too.
1004 */
1005 void CFontFamily::FreeFontColorGraphics()
1006 {
1007 // Clear the map regardless of whether the CFontColor
1008 // objects still exist.
1009 for (FontColorGraphicsType::iterator iter
1010 = this->FontColorGraphics.begin();
1011 iter != this->FontColorGraphics.end();
1012 ++iter) {
1013 CGraphic::Free(iter->second);
1014 }
1015 this->FontColorGraphics.clear();
1016 }
1017
1018 /**
1019 ** Load all fonts.
1020 */
1021 void LoadFonts()
1022 {
1023 for (FontFamiliesType::iterator iter = FontFamilies.begin();
1024 iter != FontFamilies.end(); ++iter) {
1025 CFontFamily *fontFamily = iter->second;
1026 CGraphic *g = fontFamily->G;
1027 if (g) {
1028 ShowLoadProgress("Fonts %s", g->File.c_str());
1029 g->Load();
1030 fontFamily->MeasureWidths();
1031 if (UseOpenGL) {
1032 fontFamily->MakeFontColorGraphics();
1033 }
1034 }
1035 }
1036
1037 // TODO: remove this
1038 SmallFont = CFont::Get("small");
1039 GameFont = CFont::Get("game");
1040 LargeFont = CFont::Get("large");
1041 }
1042
1043 /**
1044 ** Free OpenGL fonts
1045 */
1046 void FreeOpenGLFonts()
1047 {
1048 for (FontFamiliesType::iterator iter = FontFamilies.begin();
1049 iter != FontFamilies.end(); ++iter) {
1050 CFontFamily *fontFamily = iter->second;
1051 fontFamily->FreeFontColorGraphics();
1052 }
1053 }
1054
1055 /**
1056 ** Reload OpenGL fonts
1057 */
1058 void ReloadFonts()
1059 {
1060 for (FontFamiliesType::iterator iter = FontFamilies.begin();
1061 iter != FontFamilies.end(); ++iter) {
1062 CFontFamily *fontFamily = iter->second;
1063 fontFamily->FreeFontColorGraphics();
1064 if (fontFamily->G) {
1065 fontFamily->MakeFontColorGraphics();
1066 }
1067 }
1068 }
1069
1070 /**
1071 ** Create a new font
1072 **
1073 ** @param ident Font identifier
1074 ** @param g Graphic (always consumes a reference)
1075 **
1076 ** @return New font
1077 */
1078 CFont *CFont::New(const std::string &ident, CGraphic *g)
1079 {
1080 // Make sure we'll call CGraphic::Free(g) on any exception.
1081 CGraphicPtr gptr;
1082 gptr.G = g;
1083
1084 FontFamiliesType::iterator found = FontFamilies.find(ident);
1085 if (found != FontFamilies.end()) {
1086 CFontFamily *fontFamily = found->second;
1087 if (fontFamily->G != g) {
1088 fontFamily->FreeFontColorGraphics();
1089 }
1090 swap(fontFamily->G, gptr);
1091 return &fontFamily->MarkupFont;
1092 } else {
1093 CFontFamily *fontFamily = new CFontFamily(ident);
1094 swap(fontFamily->G, gptr);
1095 FontFamilies.insert(
1096 FontFamiliesType::value_type(ident, fontFamily));
1097 return &fontFamily->MarkupFont;
1098 }
1099 }
1100
1101 /**
1102 ** Get a font
1103 **
1104 ** @param ident Font identifier
1105 **
1106 ** @return The font
1107 */
1108 CFont *CFont::Get(const std::string &ident)
1109 {
1110 FontFamiliesType::iterator found = FontFamilies.find(ident);
1111 if (found != FontFamilies.end()) {
1112 return &found->second->MarkupFont;
1113 } else {
1114 DebugPrint("font not found: %s" _C_ ident.c_str());
1115 return NULL;
1116 }
1117 }
1118
1119 /**
1120 ** CFontColor constructor
1121 */
1122 CFontColor::CFontColor(const std::string &ident)
1123 {
1124 Ident = ident;
1125 memset(Colors, 0, sizeof(Colors));
1126 }
1127
1128 /**
1129 ** CFontColor destructor
1130 */
1131 CFontColor::~CFontColor()
1132 {
1133 }
1134
1135 /**
1136 ** Create a new font color
1137 **
1138 ** @param ident Font color identifier
1139 **
1140 ** @return New font color
1141 */
1142 CFontColor *CFontColor::New(const std::string &ident)
1143 {
1144 CFontColor *fc = FontColors[ident];
1145 if (fc) {
1146 return fc;
1147 } else {
1148 fc = new CFontColor(ident);
1149 FontColors[ident] = fc;
1150 AllFontColors.push_back(fc);
1151 return fc;
1152 }
1153 }
1154
1155 /**
1156 ** Get a font color
1157 **
1158 ** @param ident Font color identifier
1159 **
1160 ** @return The font color
1161 */
1162 CFontColor *CFontColor::Get(const std::string &ident)
1163 {
1164 CFontColor *fc = FontColors[ident];
1165 if (!fc) {
1166 DebugPrint("font color not found: %s" _C_ ident.c_str());
1167 }
1168 return fc;
1169 }
1170
1171 /**
1172 ** Clean up the font module.
1173 */
1174 void CleanFonts()
1175 {
1176 while (FontFamilies.begin() != FontFamilies.end()) {
1177 delete FontFamilies.begin()->second;
1178 FontFamilies.erase(FontFamilies.begin());
1179 }
1180
1181 for (int i = 0; i < (int)AllFontColors.size(); ++i) {
1182 delete AllFontColors[i];
1183 }
1184 AllFontColors.clear();
1185 FontColors.clear();
1186
1187 SmallFont = NULL;
1188 GameFont = NULL;
1189 LargeFont = NULL;
1190 }
1191
1192 //@}