1 /*************************************************************************/
2 /*  font.cpp                                                             */
3 /*************************************************************************/
4 /*                       This file is part of:                           */
5 /*                           GODOT ENGINE                                */
6 /*                      https://godotengine.org                          */
7 /*************************************************************************/
8 /* Copyright (c) 2007-2019 Juan Linietsky, Ariel Manzur.                 */
9 /* Copyright (c) 2014-2019 Godot Engine contributors (cf. AUTHORS.md)    */
10 /*                                                                       */
11 /* Permission is hereby granted, free of charge, to any person obtaining */
12 /* a copy of this software and associated documentation files (the       */
13 /* "Software"), to deal in the Software without restriction, including   */
14 /* without limitation the rights to use, copy, modify, merge, publish,   */
15 /* distribute, sublicense, and/or sell copies of the Software, and to    */
16 /* permit persons to whom the Software is furnished to do so, subject to */
17 /* the following conditions:                                             */
18 /*                                                                       */
19 /* The above copyright notice and this permission notice shall be        */
20 /* included in all copies or substantial portions of the Software.       */
21 /*                                                                       */
22 /* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,       */
23 /* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF    */
24 /* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.*/
25 /* IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY  */
26 /* CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,  */
27 /* TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE     */
28 /* SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.                */
29 /*************************************************************************/
30 #include "font.h"
31 
32 #include "core/io/resource_loader.h"
33 #include "core/os/file_access.h"
34 
draw_halign(RID p_canvas_item,const Point2 & p_pos,HAlign p_align,float p_width,const String & p_text,const Color & p_modulate) const35 void Font::draw_halign(RID p_canvas_item, const Point2 &p_pos, HAlign p_align, float p_width, const String &p_text, const Color &p_modulate) const {
36 
37 	float length = get_string_size(p_text).width;
38 	if (length >= p_width) {
39 		draw(p_canvas_item, p_pos, p_text, p_modulate, p_width);
40 		return;
41 	}
42 
43 	float ofs;
44 	switch (p_align) {
45 		case HALIGN_LEFT: {
46 			ofs = 0;
47 		} break;
48 		case HALIGN_CENTER: {
49 			ofs = Math::floor((p_width - length) / 2.0);
50 		} break;
51 		case HALIGN_RIGHT: {
52 			ofs = p_width - length;
53 		} break;
54 	}
55 	draw(p_canvas_item, p_pos + Point2(ofs, 0), p_text, p_modulate, p_width);
56 }
57 
draw(RID p_canvas_item,const Point2 & p_pos,const String & p_text,const Color & p_modulate,int p_clip_w) const58 void Font::draw(RID p_canvas_item, const Point2 &p_pos, const String &p_text, const Color &p_modulate, int p_clip_w) const {
59 
60 	Vector2 ofs;
61 
62 	for (int i = 0; i < p_text.length(); i++) {
63 
64 		int width = get_char_size(p_text[i]).width;
65 
66 		if (p_clip_w >= 0 && (ofs.x + width) > p_clip_w)
67 			break; //clip
68 
69 		ofs.x += draw_char(p_canvas_item, p_pos + ofs, p_text[i], p_text[i + 1], p_modulate);
70 	}
71 }
72 
update_changes()73 void Font::update_changes() {
74 
75 	emit_changed();
76 }
77 
_bind_methods()78 void Font::_bind_methods() {
79 
80 	ObjectTypeDB::bind_method(_MD("draw", "canvas_item", "pos", "string", "modulate", "clip_w"), &Font::draw, DEFVAL(Color(1, 1, 1)), DEFVAL(-1));
81 	ObjectTypeDB::bind_method(_MD("get_ascent"), &Font::get_ascent);
82 	ObjectTypeDB::bind_method(_MD("get_descent"), &Font::get_descent);
83 	ObjectTypeDB::bind_method(_MD("get_height"), &Font::get_height);
84 	ObjectTypeDB::bind_method(_MD("is_distance_field_hint"), &Font::is_distance_field_hint);
85 	ObjectTypeDB::bind_method(_MD("get_string_size", "string"), &Font::get_string_size);
86 	ObjectTypeDB::bind_method(_MD("draw_char", "canvas_item", "pos", "char", "next", "modulate"), &Font::draw_char, DEFVAL(-1), DEFVAL(Color(1, 1, 1)));
87 	ObjectTypeDB::bind_method(_MD("update_changes"), &Font::update_changes);
88 }
89 
Font()90 Font::Font() {
91 }
92 
93 /////////////////////////////////////////////////////////////////
94 
_set_chars(const DVector<int> & p_chars)95 void BitmapFont::_set_chars(const DVector<int> &p_chars) {
96 
97 	int len = p_chars.size();
98 	//char 1 charsize 1 texture, 4 rect, 2 align, advance 1
99 	ERR_FAIL_COND(len % 9);
100 	if (!len)
101 		return; //none to do
102 	int chars = len / 9;
103 
104 	DVector<int>::Read r = p_chars.read();
105 	for (int i = 0; i < chars; i++) {
106 
107 		const int *data = &r[i * 9];
108 		add_char(data[0], data[1], Rect2(data[2], data[3], data[4], data[5]), Size2(data[6], data[7]), data[8]);
109 	}
110 }
111 
_get_chars() const112 DVector<int> BitmapFont::_get_chars() const {
113 
114 	DVector<int> chars;
115 
116 	const CharType *key = NULL;
117 
118 	while ((key = char_map.next(key))) {
119 
120 		const Character *c = char_map.getptr(*key);
121 		chars.push_back(*key);
122 		chars.push_back(c->texture_idx);
123 		chars.push_back(c->rect.pos.x);
124 		chars.push_back(c->rect.pos.y);
125 
126 		chars.push_back(c->rect.size.x);
127 		chars.push_back(c->rect.size.y);
128 		chars.push_back(c->h_align);
129 		chars.push_back(c->v_align);
130 		chars.push_back(c->advance);
131 	}
132 
133 	return chars;
134 }
135 
_set_kernings(const DVector<int> & p_kernings)136 void BitmapFont::_set_kernings(const DVector<int> &p_kernings) {
137 
138 	int len = p_kernings.size();
139 	ERR_FAIL_COND(len % 3);
140 	if (!len)
141 		return;
142 	DVector<int>::Read r = p_kernings.read();
143 
144 	for (int i = 0; i < len / 3; i++) {
145 
146 		const int *data = &r[i * 3];
147 		add_kerning_pair(data[0], data[1], data[2]);
148 	}
149 }
150 
_get_kernings() const151 DVector<int> BitmapFont::_get_kernings() const {
152 
153 	DVector<int> kernings;
154 
155 	for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
156 
157 		kernings.push_back(E->key().A);
158 		kernings.push_back(E->key().B);
159 		kernings.push_back(E->get());
160 	}
161 
162 	return kernings;
163 }
164 
_set_textures(const Vector<Variant> & p_textures)165 void BitmapFont::_set_textures(const Vector<Variant> &p_textures) {
166 
167 	for (int i = 0; i < p_textures.size(); i++) {
168 		Ref<Texture> tex = p_textures[i];
169 		ERR_CONTINUE(!tex.is_valid());
170 		add_texture(tex);
171 	}
172 }
173 
_get_textures() const174 Vector<Variant> BitmapFont::_get_textures() const {
175 
176 	Vector<Variant> rtextures;
177 	for (int i = 0; i < textures.size(); i++)
178 		rtextures.push_back(textures[i].get_ref_ptr());
179 	return rtextures;
180 }
181 
create_from_fnt(const String & p_string)182 Error BitmapFont::create_from_fnt(const String &p_string) {
183 	//fnt format used by angelcode bmfont
184 	//http://www.angelcode.com/products/bmfont/
185 
186 	FileAccess *f = FileAccess::open(p_string, FileAccess::READ);
187 
188 	if (!f) {
189 		ERR_EXPLAIN("Can't open font: " + p_string);
190 		ERR_FAIL_V(ERR_FILE_NOT_FOUND);
191 	}
192 
193 	clear();
194 
195 	while (true) {
196 
197 		String line = f->get_line();
198 
199 		int delimiter = line.find(" ");
200 		String type = line.substr(0, delimiter);
201 		int pos = delimiter + 1;
202 		Map<String, String> keys;
203 
204 		while (pos < line.size() && line[pos] == ' ')
205 			pos++;
206 
207 		while (pos < line.size()) {
208 
209 			int eq = line.find("=", pos);
210 			if (eq == -1)
211 				break;
212 			String key = line.substr(pos, eq - pos);
213 			int end = -1;
214 			String value;
215 			if (line[eq + 1] == '"') {
216 				end = line.find("\"", eq + 2);
217 				if (end == -1)
218 					break;
219 				value = line.substr(eq + 2, end - 1 - eq - 1);
220 				pos = end + 1;
221 			} else {
222 				end = line.find(" ", eq + 1);
223 				if (end == -1)
224 					end = line.size();
225 
226 				value = line.substr(eq + 1, end - eq);
227 
228 				pos = end;
229 			}
230 
231 			while (pos < line.size() && line[pos] == ' ')
232 				pos++;
233 
234 			keys[key] = value;
235 		}
236 
237 		if (type == "info") {
238 
239 			if (keys.has("face"))
240 				set_name(keys["face"]);
241 			//if (keys.has("size"))
242 			//	font->set_height(keys["size"].to_int());
243 
244 		} else if (type == "common") {
245 
246 			if (keys.has("lineHeight"))
247 				set_height(keys["lineHeight"].to_int());
248 			if (keys.has("base"))
249 				set_ascent(keys["base"].to_int());
250 
251 		} else if (type == "page") {
252 
253 			if (keys.has("file")) {
254 
255 				String file = keys["file"];
256 				file = p_string.get_base_dir() + "/" + file;
257 				Ref<Texture> tex = ResourceLoader::load(file);
258 				if (tex.is_null()) {
259 					ERR_PRINT("Can't load font texture!");
260 				} else {
261 					add_texture(tex);
262 				}
263 			}
264 		} else if (type == "char") {
265 
266 			CharType idx = 0;
267 			if (keys.has("id"))
268 				idx = keys["id"].to_int();
269 
270 			Rect2 rect;
271 
272 			if (keys.has("x"))
273 				rect.pos.x = keys["x"].to_int();
274 			if (keys.has("y"))
275 				rect.pos.y = keys["y"].to_int();
276 			if (keys.has("width"))
277 				rect.size.width = keys["width"].to_int();
278 			if (keys.has("height"))
279 				rect.size.height = keys["height"].to_int();
280 
281 			Point2 ofs;
282 
283 			if (keys.has("xoffset"))
284 				ofs.x = keys["xoffset"].to_int();
285 			if (keys.has("yoffset"))
286 				ofs.y = keys["yoffset"].to_int();
287 
288 			int texture = 0;
289 			if (keys.has("page"))
290 				texture = keys["page"].to_int();
291 			int advance = -1;
292 			if (keys.has("xadvance"))
293 				advance = keys["xadvance"].to_int();
294 
295 			add_char(idx, texture, rect, ofs, advance);
296 
297 		} else if (type == "kerning") {
298 
299 			CharType first = 0, second = 0;
300 			int k = 0;
301 
302 			if (keys.has("first"))
303 				first = keys["first"].to_int();
304 			if (keys.has("second"))
305 				second = keys["second"].to_int();
306 			if (keys.has("amount"))
307 				k = keys["amount"].to_int();
308 
309 			add_kerning_pair(first, second, -k);
310 		}
311 
312 		if (f->eof_reached())
313 			break;
314 	}
315 
316 	memdelete(f);
317 
318 	return OK;
319 }
320 
set_height(float p_height)321 void BitmapFont::set_height(float p_height) {
322 
323 	height = p_height;
324 }
get_height() const325 float BitmapFont::get_height() const {
326 
327 	return height;
328 }
329 
set_ascent(float p_ascent)330 void BitmapFont::set_ascent(float p_ascent) {
331 
332 	ascent = p_ascent;
333 }
get_ascent() const334 float BitmapFont::get_ascent() const {
335 
336 	return ascent;
337 }
get_descent() const338 float BitmapFont::get_descent() const {
339 
340 	return height - ascent;
341 }
342 
add_texture(const Ref<Texture> & p_texture)343 void BitmapFont::add_texture(const Ref<Texture> &p_texture) {
344 
345 	ERR_FAIL_COND(p_texture.is_null());
346 	textures.push_back(p_texture);
347 }
348 
get_texture_count() const349 int BitmapFont::get_texture_count() const {
350 
351 	return textures.size();
352 };
353 
get_texture(int p_idx) const354 Ref<Texture> BitmapFont::get_texture(int p_idx) const {
355 
356 	ERR_FAIL_INDEX_V(p_idx, textures.size(), Ref<Texture>());
357 	return textures[p_idx];
358 };
359 
get_character_count() const360 int BitmapFont::get_character_count() const {
361 
362 	return char_map.size();
363 };
364 
get_char_keys() const365 Vector<CharType> BitmapFont::get_char_keys() const {
366 
367 	Vector<CharType> chars;
368 	chars.resize(char_map.size());
369 	const CharType *ct = NULL;
370 	int count = 0;
371 	while ((ct = char_map.next(ct))) {
372 
373 		chars[count++] = *ct;
374 	};
375 
376 	return chars;
377 };
378 
get_character(CharType p_char) const379 BitmapFont::Character BitmapFont::get_character(CharType p_char) const {
380 
381 	if (!char_map.has(p_char)) {
382 		ERR_FAIL_V(Character());
383 	};
384 
385 	return char_map[p_char];
386 };
387 
add_char(CharType p_char,int p_texture_idx,const Rect2 & p_rect,const Size2 & p_align,float p_advance)388 void BitmapFont::add_char(CharType p_char, int p_texture_idx, const Rect2 &p_rect, const Size2 &p_align, float p_advance) {
389 
390 	if (p_advance < 0)
391 		p_advance = p_rect.size.width;
392 
393 	Character c;
394 	c.rect = p_rect;
395 	c.texture_idx = p_texture_idx;
396 	c.v_align = p_align.y;
397 	c.advance = p_advance;
398 	c.h_align = p_align.x;
399 
400 	char_map[p_char] = c;
401 }
402 
add_kerning_pair(CharType p_A,CharType p_B,int p_kerning)403 void BitmapFont::add_kerning_pair(CharType p_A, CharType p_B, int p_kerning) {
404 
405 	KerningPairKey kpk;
406 	kpk.A = p_A;
407 	kpk.B = p_B;
408 
409 	if (p_kerning == 0 && kerning_map.has(kpk)) {
410 
411 		kerning_map.erase(kpk);
412 	} else {
413 
414 		kerning_map[kpk] = p_kerning;
415 	}
416 }
417 
get_kerning_pair_keys() const418 Vector<BitmapFont::KerningPairKey> BitmapFont::get_kerning_pair_keys() const {
419 
420 	Vector<BitmapFont::KerningPairKey> ret;
421 	ret.resize(kerning_map.size());
422 	int i = 0;
423 
424 	for (Map<KerningPairKey, int>::Element *E = kerning_map.front(); E; E = E->next()) {
425 		ret[i++] = E->key();
426 	}
427 
428 	return ret;
429 }
430 
get_kerning_pair(CharType p_A,CharType p_B) const431 int BitmapFont::get_kerning_pair(CharType p_A, CharType p_B) const {
432 
433 	KerningPairKey kpk;
434 	kpk.A = p_A;
435 	kpk.B = p_B;
436 
437 	const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
438 	if (E)
439 		return E->get();
440 
441 	return 0;
442 }
443 
set_distance_field_hint(bool p_distance_field)444 void BitmapFont::set_distance_field_hint(bool p_distance_field) {
445 
446 	distance_field_hint = p_distance_field;
447 	emit_changed();
448 }
449 
is_distance_field_hint() const450 bool BitmapFont::is_distance_field_hint() const {
451 
452 	return distance_field_hint;
453 }
454 
clear()455 void BitmapFont::clear() {
456 
457 	height = 1;
458 	ascent = 0;
459 	char_map.clear();
460 	textures.clear();
461 	kerning_map.clear();
462 	distance_field_hint = false;
463 }
464 
get_string_size(const String & p_string) const465 Size2 Font::get_string_size(const String &p_string) const {
466 
467 	float w = 0;
468 
469 	int l = p_string.length();
470 	if (l == 0)
471 		return Size2(0, get_height());
472 	const CharType *sptr = &p_string[0];
473 
474 	for (int i = 0; i < l; i++) {
475 
476 		w += get_char_size(sptr[i], sptr[i + 1]).width;
477 	}
478 
479 	return Size2(w, get_height());
480 }
set_fallback(const Ref<BitmapFont> & p_fallback)481 void BitmapFont::set_fallback(const Ref<BitmapFont> &p_fallback) {
482 
483 	fallback = p_fallback;
484 }
485 
get_fallback() const486 Ref<BitmapFont> BitmapFont::get_fallback() const {
487 
488 	return fallback;
489 }
490 
draw_char(RID p_canvas_item,const Point2 & p_pos,CharType p_char,CharType p_next,const Color & p_modulate) const491 float BitmapFont::draw_char(RID p_canvas_item, const Point2 &p_pos, CharType p_char, CharType p_next, const Color &p_modulate) const {
492 
493 	const Character *c = char_map.getptr(p_char);
494 
495 	if (!c) {
496 		if (fallback.is_valid())
497 			return fallback->draw_char(p_canvas_item, p_pos, p_char, p_next, p_modulate);
498 		return 0;
499 	}
500 
501 	Point2 cpos = p_pos;
502 	cpos.x += c->h_align;
503 	cpos.y -= ascent;
504 	cpos.y += c->v_align;
505 	ERR_FAIL_COND_V(c->texture_idx < -1 || c->texture_idx >= textures.size(), 0);
506 	if (c->texture_idx != -1)
507 		VisualServer::get_singleton()->canvas_item_add_texture_rect_region(p_canvas_item, Rect2(cpos, c->rect.size), textures[c->texture_idx]->get_rid(), c->rect, p_modulate);
508 
509 	return get_char_size(p_char, p_next).width;
510 }
511 
get_char_size(CharType p_char,CharType p_next) const512 Size2 BitmapFont::get_char_size(CharType p_char, CharType p_next) const {
513 
514 	const Character *c = char_map.getptr(p_char);
515 
516 	if (!c) {
517 		if (fallback.is_valid())
518 			return fallback->get_char_size(p_char, p_next);
519 		return Size2();
520 	}
521 
522 	Size2 ret(c->advance, c->rect.size.y);
523 
524 	if (p_next) {
525 
526 		KerningPairKey kpk;
527 		kpk.A = p_char;
528 		kpk.B = p_next;
529 
530 		const Map<KerningPairKey, int>::Element *E = kerning_map.find(kpk);
531 		if (E) {
532 
533 			ret.width -= E->get();
534 		}
535 	}
536 
537 	return ret;
538 }
539 
_bind_methods()540 void BitmapFont::_bind_methods() {
541 
542 	ObjectTypeDB::bind_method(_MD("create_from_fnt", "path"), &BitmapFont::create_from_fnt);
543 	ObjectTypeDB::bind_method(_MD("set_height", "px"), &BitmapFont::set_height);
544 
545 	ObjectTypeDB::bind_method(_MD("set_ascent", "px"), &BitmapFont::set_ascent);
546 
547 	ObjectTypeDB::bind_method(_MD("add_kerning_pair", "char_a", "char_b", "kerning"), &BitmapFont::add_kerning_pair);
548 	ObjectTypeDB::bind_method(_MD("get_kerning_pair", "char_a", "char_b"), &BitmapFont::get_kerning_pair);
549 
550 	ObjectTypeDB::bind_method(_MD("add_texture", "texture:Texture"), &BitmapFont::add_texture);
551 	ObjectTypeDB::bind_method(_MD("add_char", "character", "texture", "rect", "align", "advance"), &BitmapFont::add_char, DEFVAL(Point2()), DEFVAL(-1));
552 
553 	ObjectTypeDB::bind_method(_MD("get_texture_count"), &BitmapFont::get_texture_count);
554 	ObjectTypeDB::bind_method(_MD("get_texture:Texture", "idx"), &BitmapFont::get_texture);
555 
556 	ObjectTypeDB::bind_method(_MD("get_char_size", "char", "next"), &BitmapFont::get_char_size, DEFVAL(0));
557 
558 	ObjectTypeDB::bind_method(_MD("set_distance_field_hint", "enable"), &BitmapFont::set_distance_field_hint);
559 
560 	ObjectTypeDB::bind_method(_MD("clear"), &BitmapFont::clear);
561 
562 	ObjectTypeDB::bind_method(_MD("_set_chars"), &BitmapFont::_set_chars);
563 	ObjectTypeDB::bind_method(_MD("_get_chars"), &BitmapFont::_get_chars);
564 
565 	ObjectTypeDB::bind_method(_MD("_set_kernings"), &BitmapFont::_set_kernings);
566 	ObjectTypeDB::bind_method(_MD("_get_kernings"), &BitmapFont::_get_kernings);
567 
568 	ObjectTypeDB::bind_method(_MD("_set_textures"), &BitmapFont::_set_textures);
569 	ObjectTypeDB::bind_method(_MD("_get_textures"), &BitmapFont::_get_textures);
570 
571 	ObjectTypeDB::bind_method(_MD("set_fallback", "fallback"), &BitmapFont::set_fallback);
572 	ObjectTypeDB::bind_method(_MD("get_fallback"), &BitmapFont::get_fallback);
573 
574 	ADD_PROPERTY(PropertyInfo(Variant::ARRAY, "textures", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), _SCS("_set_textures"), _SCS("_get_textures"));
575 	ADD_PROPERTY(PropertyInfo(Variant::INT_ARRAY, "chars", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), _SCS("_set_chars"), _SCS("_get_chars"));
576 	ADD_PROPERTY(PropertyInfo(Variant::INT_ARRAY, "kernings", PROPERTY_HINT_NONE, "", PROPERTY_USAGE_NOEDITOR), _SCS("_set_kernings"), _SCS("_get_kernings"));
577 
578 	ADD_PROPERTY(PropertyInfo(Variant::REAL, "height", PROPERTY_HINT_RANGE, "-1024,1024,1"), _SCS("set_height"), _SCS("get_height"));
579 	ADD_PROPERTY(PropertyInfo(Variant::REAL, "ascent", PROPERTY_HINT_RANGE, "-1024,1024,1"), _SCS("set_ascent"), _SCS("get_ascent"));
580 	ADD_PROPERTY(PropertyInfo(Variant::BOOL, "distance_field"), _SCS("set_distance_field_hint"), _SCS("is_distance_field_hint"));
581 	ADD_PROPERTY(PropertyInfo(Variant::OBJECT, "fallback", PROPERTY_HINT_RESOURCE_TYPE, "BitmapFont"), _SCS("set_fallback"), _SCS("get_fallback"));
582 }
583 
BitmapFont()584 BitmapFont::BitmapFont() {
585 
586 	clear();
587 }
588 
~BitmapFont()589 BitmapFont::~BitmapFont() {
590 
591 	clear();
592 }
593