File: font.cpp

package info (click to toggle)
freespace2 24.2.0%2Brepack-1
  • links: PTS, VCS
  • area: non-free
  • in suites: forky, sid
  • size: 43,716 kB
  • sloc: cpp: 595,001; ansic: 21,741; python: 1,174; sh: 457; makefile: 248; xml: 181
file content (772 lines) | stat: -rw-r--r-- 18,310 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
/*
 * Copyright (C) Volition, Inc. 1999.  All rights reserved.
 *
 * All source code herein is the property of Volition, Inc. You may not sell 
 * or otherwise commercially exploit the source or things you created based on the 
 * source.
 *
*/ 

#include <cstdio>
#include <cstdarg>
#include <string>
#include <sstream>
#include <climits>

#include "graphics/software/font_internal.h"
#include "graphics/software/FontManager.h"
#include "graphics/software/FSFont.h"
#include "graphics/software/VFNTFont.h"
#include "graphics/software/NVGFont.h"

#include "graphics/2d.h"

#include "mod_table/mod_table.h"

#include "def_files/def_files.h"
#include "bmpman/bmpman.h"
#include "cfile/cfile.h"
#include "localization/localize.h"
#include "parse/parselo.h"
#include "tracing/Monitor.h"

namespace
{
	namespace fo = font;
	using namespace font;

	bool font_initialized = false;

	constexpr ubyte DEFAULT_SPECIAL_CHAR_INDEX = 0;

	// max allowed special char index; i.e. 7 special chars in retail fonts 1 & 3
	const int MAX_SPECIAL_CHAR_IDX = UCHAR_MAX - 6;


	bool parse_type(FontType &type, SCP_string &fileName)
	{
		int num = optional_string_either("$TrueType:", "$Font:");
		if (num == 0)
		{
			type = NVG_FONT;
		}
		else if (num == 1)
		{
			type = VFNT_FONT;
		}
		else
		{
			type = UNKNOWN_FONT;
		}


		if (type != UNKNOWN_FONT)
		{
			stuff_string(fileName, F_NAME);
			return true;
		}
		else
		{
			return false;
		}
	}

	void parse_nvg_font(const SCP_string& fontFilename)
	{
		float size = 8.0f;
		SCP_string fontStr;
		bool hasName = false;

		if (optional_string("+Name:"))
		{
			stuff_string(fontStr, F_NAME);

			hasName = true;
		}

		if (optional_string("+Size:"))
		{
			stuff_float(&size);

			if (size <= 0.0f)
			{
				error_display(0, "+Size has to be bigger than 0 for font \"%s\".", fontFilename.c_str());
				size = 8;
			}
		}

		// Build name from existing values if no name is specified
		if (!hasName)
		{
			SCP_stringstream ss;

			ss << fontFilename << "-";

			ss << size;

			fontStr = ss.str();
		}

		if (FontManager::getFont(fontStr) != NULL)
		{
			if (hasName)
			{
				error_display(0, "Font with name \"%s\" is already present! Font names have to be unique!", fontStr.c_str());
				return;
			}
			else
			{
				error_display(0, "Found font with same default name (\"%s\"). This is most likely a duplicate.", fontStr.c_str());
				return;
			}
		}

		NVGFont *nvgFont = FontManager::loadNVGFont(fontFilename, size);

		if (nvgFont == NULL)
		{
			error_display(0, "Couldn't load font \"%s\".", fontFilename.c_str());
			return;
		}

		if (optional_string("+Top offset:"))
		{
			float temp;

			stuff_float(&temp);

			nvgFont->setTopOffset(temp);
		}

		if (optional_string("+Bottom offset:"))
		{
			float temp;

			stuff_float(&temp);

			nvgFont->setBottomOffset(temp);
		}
		
		if (optional_string("+Tab width:"))
		{
			float temp;
			stuff_float(&temp);

			if (temp < 0.0f)
			{
				error_display(0, "Invalid tab spacing %f. Has to be greater or equal to zero.", temp);
			}
			else
			{
				nvgFont->setTabWidth(temp);
			}
		}

		if (optional_string("+Letter spacing:"))
		{
			float temp;
			stuff_float(&temp);

			if (temp < 0.0f)
			{
				error_display(0, "Invalid letter spacing %f! Has to be greater or equal to zero.", temp);
			}
			else
			{
				nvgFont->setLetterSpacing(temp);
			}
		}

		if (!Unicode_text_mode) {
			int special_char_index = DEFAULT_SPECIAL_CHAR_INDEX;
			// Special characters only exist in non-Unicode mode
			if (optional_string("+Special Character Font:"))
			{
				SCP_string fontName;
				stuff_string(fontName, F_NAME);

				fo::font* fontData = FontManager::loadFontOld(fontName.c_str());

				if (fontData == NULL)
				{
					error_display(0, "Failed to load font \"%s\" for special characters of font \"%s\"!", fontName.c_str(), fontFilename.c_str());
				}
				else
				{
					nvgFont->setSpecialCharacterFont(fontData);
				}

				if (optional_string("+Special Character Index:")) {
					stuff_int(&special_char_index);
					if (special_char_index < 0 || special_char_index >= MAX_SPECIAL_CHAR_IDX) {
						Warning(LOCATION, "Special character index (%d) for font (%s) is invalid, must be 0 - %u. Defaulting to 0.",
							special_char_index, fontName.c_str(), MAX_SPECIAL_CHAR_IDX);
						special_char_index = DEFAULT_SPECIAL_CHAR_INDEX;
					}
				}
				else {
					auto old_entry = FontManager::getFontByFilename(fontName);
					
					if (old_entry != nullptr) {
						int old_index = FontManager::getFontIndex(old_entry);
						special_char_index = Lcl_languages[0].special_char_indexes[old_index];
					} else {

						Warning(LOCATION,
							"A \"+Special Character Index:\" was not specified after the \"+Special Character Font:\" entry for the %s font. And a previous entry with a \"+Special Character Index:\" was not found."
							"\n\n This entry must be specified directly or indirectly to avoid this warning.  Defaulting to 0.",
							fontStr.c_str());
					}
				}

			}
			else
			{
				fo::font* fontData = FontManager::loadFontOld("font01.vf");

				if (fontData == nullptr) {
					error_display(0,
								  "Failed to load default font \"%s\" for special characters of font \"%s\"! "
									  "This font is required for rendering special characters, if another font is not defined, and will cause an error later.",
								  "font01.vf",
								  fontFilename.c_str());
				} else {
					nvgFont->setSpecialCharacterFont(fontData);
				}
			}

			auto font_id = FontManager::getFontIndex(nvgFont);

			// add the index specified to all languages
			for (auto & Lcl_language : Lcl_languages) {

				// if there wasn't already something specified for this font.
				if (font_id >= (int)Lcl_language.special_char_indexes.size()) {
					
					// if there were absolutely no special characters defined, put the default value as the language default.
					if (Lcl_language.special_char_indexes.empty() == 0) {
						Lcl_language.special_char_indexes.push_back(DEFAULT_SPECIAL_CHAR_INDEX);
					}

					// if somehow a lot of indexes were missing, add the language default to fill in the gaps until ...
					while (font_id > (int)Lcl_language.special_char_indexes.size()) {
							Lcl_language.special_char_indexes.push_back(Lcl_language.special_char_indexes[0]);
					}

					// we're at just the right place in the vector to add the index we just read from the table.
					Lcl_language.special_char_indexes.push_back((ubyte)special_char_index);

				} // replace if there was something already specified, except if nothing was specified in the table
				else if (special_char_index != DEFAULT_SPECIAL_CHAR_INDEX) {
					Lcl_language.special_char_indexes[font_id] = (ubyte)special_char_index;
				}
			}
		}

		nvgFont->setName(fontStr);
		nvgFont->setFilename(fontFilename);

		// Make sure that the height is not invalid
		nvgFont->computeFontMetrics();
	}

	void parse_vfnt_font(const SCP_string& fontFilename)
	{
		VFNTFont *font = FontManager::loadVFNTFont(fontFilename);

		if (font == NULL)
		{
			error_display(0, "Couldn't load font\"%s\".", fontFilename.c_str());
			return;
		}

		SCP_string fontName;

		if (optional_string("+Name:"))
		{
			stuff_string(fontName, F_NAME);
		}
		else
		{
			fontName.assign(fontFilename);
		}

		font->setName(fontName);
		font->setFilename(fontFilename);

		auto font_id = FontManager::getFontIndex(font);

		int user_defined_default_special_char_index = (int)DEFAULT_SPECIAL_CHAR_INDEX;
		// 'default' special char index for all languages using this font
		if (optional_string("+Default Special Character Index:")) {
			stuff_int(&user_defined_default_special_char_index);

			if (user_defined_default_special_char_index < 0 || user_defined_default_special_char_index >= MAX_SPECIAL_CHAR_IDX) {
				Warning(LOCATION, "Default special character index (%d) for font (%s), must be 0 - %u.  Defaulting to 0.", user_defined_default_special_char_index,
					  fontName.c_str(), MAX_SPECIAL_CHAR_IDX);
			}

		}

		// add the index specified to all the languages 
		for (auto & Lcl_language : Lcl_languages) {

			// if there wasn't already something specified for this font.
			if (font_id >= (int)Lcl_language.special_char_indexes.size()) {

				// if the default for the language was not already specified, set that default to the general default
				if (Lcl_language.special_char_indexes.empty()) {
					Lcl_language.special_char_indexes.push_back(DEFAULT_SPECIAL_CHAR_INDEX);
				}

				// if a lot of indexes were missing, add some defaults to fill in the gaps until ...
				while (font_id > (int)Lcl_language.special_char_indexes.size()) {
					// take into account retail special character settings for font index 2 (size is 1 indexed)
					if (Lcl_language.special_char_indexes.size() == FONT3 - 1) {
						Lcl_language.special_char_indexes.push_back(176);
					}
					else {
						Lcl_language.special_char_indexes.push_back(Lcl_language.special_char_indexes[0]);
					}
				}
				// we're at just the right place in the vector to add the index we just read from the table.
				Lcl_language.special_char_indexes.push_back((ubyte)DEFAULT_SPECIAL_CHAR_INDEX);
			} // if there was something already specified that's being replaced.
			else if (user_defined_default_special_char_index != DEFAULT_SPECIAL_CHAR_INDEX) {
				Lcl_language.special_char_indexes[font_id] = (ubyte)user_defined_default_special_char_index;
			}
		}

		while (optional_string("+Language:")) {
			char lang_name[LCL_LANG_NAME_LEN + 1];
			int special_char_index, lang_idx = -1;

			stuff_string(lang_name, F_NAME, LCL_LANG_NAME_LEN + 1);

			// find language and set the index, or if not found move to the next one
			lang_idx = lcl_find_lang_index_by_name(lang_name);

			if (lang_idx == -1) {
				Warning(LOCATION, "Ignoring invalid language (%s) specified by font (%s); not built-in or in strings.tbl",
						lang_name, fontName.c_str());
				skip_to_start_of_string_either("+Language:", "$Font:", "#End");
				continue;
			}

			if (optional_string("+Special Character Index:")) {
				stuff_int(&special_char_index);

				if (special_char_index < 0 || special_char_index >= MAX_SPECIAL_CHAR_IDX) {
					Error(LOCATION, "Special character index (%d) for font (%s), language (%s) is invalid, must be 0 - %u",
						  special_char_index, fontName.c_str(), lang_name, MAX_SPECIAL_CHAR_IDX);
				}

				Lcl_languages[lang_idx].special_char_indexes[font_id] = (ubyte)special_char_index;
			}
		}

		if (optional_string("+Top offset:"))
		{
			float temp;

			stuff_float(&temp);

			font->setTopOffset(temp);
		}

		if (optional_string("+Bottom offset:"))
		{
			float temp;

			stuff_float(&temp);

			font->setBottomOffset(temp);
		}
		// Make sure that the height is not invalid
		font->computeFontMetrics();
	}

	void font_parse_setup(const char *fileName)
	{
		bool noTable = false;
		if (!strcmp(fileName, "fonts.tbl"))
		{
			if (!cf_exists_full(fileName, CF_TYPE_TABLES))
			{
				noTable = true;
			}
		}

		if (noTable)
		{
			read_file_text_from_default(defaults_get_file("fonts.tbl"));
		}
		else
		{
			read_file_text(fileName, CF_TYPE_TABLES);
		}

		reset_parse();

		// start parsing
		required_string("#Fonts");
	}

	void parse_font_tbl(const char *fileName)
	{
		try
		{
			font_parse_setup(fileName);

			FontType type;
			SCP_string fontName;

			while (parse_type(type, fontName))
			{
				switch (type)
				{
				case VFNT_FONT:
					if (Unicode_text_mode) {
						WarningEx(LOCATION, "Bitmap fonts are not supported in Unicode text mode! Font %s will be ignored.", fontName.c_str());
						skip_to_start_of_string_one_of({"$TrueType:", "$Font:", "#End"});
					} else {
						parse_vfnt_font(fontName);
					}
					break;
				case NVG_FONT:
					parse_nvg_font(fontName);
					break;
				default:
					error_display(0, "Unknown font type %d! Get a coder!", (int)type);
					break;
				}
			}

			// done parsing
			required_string("#End");
		}
		catch (const parse::ParseException& e)
		{
			mprintf(("TABLES: Unable to parse '%s'!  Error message = %s.\n", fileName, e.what()));
		}
	}

	void parse_fonts_tbl()
	{
		//Parse main TBL first
		parse_font_tbl("fonts.tbl");

		//Then other ones
		parse_modular_table("*-fnt.tbm", parse_font_tbl);

		// double check
		if (FontManager::numberOfFonts() < 3) {
			Error(LOCATION, "At least three fonts have to be loaded but only %d valid entries were found!", FontManager::numberOfFonts());
		}
	}
}

namespace font
{
	void init()
	{
		if (font_initialized) {
			// Already initialized
			return;
		}

		FontManager::init();

		parse_fonts_tbl();

		set_font(0);

		font_initialized = true;
	}

	void close()
	{
		if (!font_initialized) {
			return;
		}

		FontManager::close();

		font_initialized = false;
	}

	int force_fit_string(char *str, int max_str, int max_width)
	{
		int w;

		gr_get_string_size(&w, NULL, str);
		if (w > max_width) {
			if ((int)strlen(str) > max_str - 3) {
				Assert(max_str >= 3);
				str[max_str - 3] = 0;
			}

			strcpy(str + strlen(str) - 1, "...");
			gr_get_string_size(&w, NULL, str);
			while (w > max_width) {
				Assert(strlen(str) >= 4);  // if this is hit, a bad max_width was passed in and the calling function needs fixing.
				strcpy(str + strlen(str) - 4, "...");
				gr_get_string_size(&w, NULL, str);
			}
		}

		return w;
	}

	void stuff_first(SCP_string &firstFont)
	{
		try
		{
			font_parse_setup("fonts.tbl");

			FontType type;
			parse_type(type, firstFont);
		}
		catch (const parse::ParseException& e)
		{
			Error(LOCATION, "Failed to setup font parsing. This may be caused by an empty fonts.tbl file.\nError message: %s", e.what());
			firstFont = "";
		}
	}

	int parse_font()
	{
		int font_idx;

		SCP_string input;
		stuff_string(input, F_NAME);
		SCP_stringstream ss(input);

		int fontNum;
		ss >> fontNum;

		if (ss.fail())
		{
			fontNum = FontManager::getFontIndex(input);

			if (fontNum < 0)
			{
				error_display(0, "Invalid font name \"%s\"!", input.c_str());
				font_idx = -1;
			}
			else
			{
				font_idx = fontNum;
			}
		}
		else
		{
			if (fontNum < 0 || fontNum >= FontManager::numberOfFonts())
			{
				error_display(0, "Invalid font number %d! must be greater or equal to zero and smaller than %d.", fontNum, FontManager::numberOfFonts());
				font_idx = -1;
			}
			else
			{
				font_idx = fontNum;
			}
		}

		return font_idx;
	}

	FSFont *get_current_font()
	{
		return FontManager::getCurrentFont();
	}

	FSFont *get_font(const SCP_string& name)
	{
		return FontManager::getFont(name);
	}

	FSFont *get_font_by_filename(const SCP_string& name)
	{
		return FontManager::getFontByFilename(name);
	}

	

	/**
	* @brief	Gets the width of an character.
	*
	* Returns the width of the specified charachter also taking account of kerning.
	*
	* @param fnt				The font data
	* @param c1				The character that should be checked.
	* @param c2				The character which follows this character. Used to compute the kerning
	* @param [out]	width   	If non-null, the width.
	* @param [out]	spaceing	If non-null, the spaceing.
	*
	* @return	The character width.
	*/
	int get_char_width_old(fo::font* fnt, ubyte c1, ubyte c2, int *width, int* spacing)
	{
		int i, letter;

		letter = c1 - fnt->first_ascii;

		//not in font, draw as space
		if (letter < 0 || letter >= fnt->num_chars)
		{
			*width = 0;
			*spacing = fnt->w;
			return -1;
		}

		*width = fnt->char_data[letter].byte_width;
		*spacing = fnt->char_data[letter].spacing;

		i = fnt->char_data[letter].kerning_entry;
		if (i > -1)
		{
			if (!(c2 == 0 || c2 == '\n'))
			{
				int letter2;

				letter2 = c2 - fnt->first_ascii;

				if ((letter2 >= 0) && (letter2 < fnt->num_chars) && (i < fnt->num_kern_pairs))
				{
					font_kernpair *k = &fnt->kern_data[i];
					while ((i < fnt->num_kern_pairs) && (k->c1 == (char)letter) && (k->c2 < (char)letter2))
					{
						i++;
						k++;
					}

					if ((i < fnt->num_kern_pairs) && (k->c2 == (char)letter2))
					{
						*spacing += k->offset;
					}
				}
			}
		}

		return letter;
	}
}

int gr_get_font_height()
{
	if (FontManager::isReady())
	{
		return fl2i(FontManager::getCurrentFont()->getHeight());
	}
	else
	{
		return 16;
	}
}

int gr_get_dynamic_font_lines(int number_default_lines) {
	// the default font height (font01) is 9, thus the *10 --wookieejedi
	return fl2i((number_default_lines * 10) / (gr_get_font_height() + 1));
}

void gr_get_string_size(int *w1, int *h1, const char *text, size_t len)
{
	if (!FontManager::isReady())
	{
		if (w1)
			*w1 = 16;

		if (h1)
			*h1 = 16;

		return;
	}

	float w = 0.0f;
	float h = 0.0f;

	FontManager::getCurrentFont()->getStringSize(text, len, -1, &w, &h);

	if (w1)
	{
		*w1 = fl2i(ceil(w));
	}
	if (h1)
	{
		*h1 = fl2i(ceil(h));
	}
}

MONITOR(FontChars)

#ifdef _WIN32

void gr_string_win(int x, int y, char *s)
{
	using namespace font;

	int old_bitmap = gr_screen.current_bitmap;
	set_font(FONT1);
	gr_string(x, y, s);
	gr_screen.current_bitmap = old_bitmap;
}

#endif   // ifdef _WIN32

char grx_printf_text[2048];

void gr_printf(int x, int y, const char * format, ...)
{
	va_list args;

	if (!FontManager::isReady()) return;

	va_start(args, format);
	vsnprintf(grx_printf_text, sizeof(grx_printf_text) - 1, format, args);
	va_end(args);
	grx_printf_text[sizeof(grx_printf_text) - 1] = '\0';

	gr_string(x, y, grx_printf_text);
}

void gr_printf_menu(int x, int y, const char * format, ...)
{
	va_list args;

	if (!FontManager::isReady()) return;

	va_start(args, format);
	vsnprintf(grx_printf_text, sizeof(grx_printf_text) - 1, format, args);
	va_end(args);
	grx_printf_text[sizeof(grx_printf_text) - 1] = '\0';

	gr_string(x, y, grx_printf_text, GR_RESIZE_MENU);
}

void gr_printf_menu_zoomed(int x, int y, const char * format, ...)
{
	va_list args;

	if (!FontManager::isReady()) return;

	va_start(args, format);
	vsnprintf(grx_printf_text, sizeof(grx_printf_text) - 1, format, args);
	va_end(args);
	grx_printf_text[sizeof(grx_printf_text) - 1] = '\0';

	gr_string(x, y, grx_printf_text, GR_RESIZE_MENU_ZOOMED);
}

void gr_printf_no_resize(int x, int y, const char * format, ...)
{
	va_list args;

	if (!FontManager::isReady()) return;

	va_start(args, format);
	vsnprintf(grx_printf_text, sizeof(grx_printf_text) - 1, format, args);
	va_end(args);
	grx_printf_text[sizeof(grx_printf_text) - 1] = '\0';

	gr_string(x, y, grx_printf_text, GR_RESIZE_NONE);
}