/
fonts.cpp
1635 lines (1398 loc) · 45.8 KB
/
fonts.cpp
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
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @file fonts.cpp
*
* Font resource repositories.
*
* @ingroup resource
*
* @author Copyright © 2003-2012 Jaakko Keränen <jaakko.keranen@iki.fi>
* @author Copyright © 2005-2012 Daniel Swanson <danij@dengine.net>
*
* @par License
* GPL: http://www.gnu.org/licenses/gpl.html
*
* <small>This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation; either version 2 of the License, or (at your
* option) any later version. This program is distributed in the hope that it
* will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General
* Public License for more details. You should have received a copy of the GNU
* General Public License along with this program; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA</small>
*/
#include <stdlib.h>
#include <ctype.h>
#include <string.h>
#include "de_base.h"
#include "de_console.h"
#include "de_system.h"
#include "de_filesys.h"
#include "m_misc.h"
#include "gl_texmanager.h"
#include "pathtree.h"
#include "font.h"
#include "bitmapfont.h"
#include "fonts.h"
typedef de::PathTree FontRepository;
/**
* FontRecord. Stores metadata for a unique Font in the collection.
*/
struct FontRecord
{
/// Namespace-unique identifier chosen by the owner of the collection.
int uniqueId;
/// The defined font instance (if any).
font_t* font;
};
struct FontNamespace
{
/// FontRepository contains mappings between names and unique font records.
FontRepository* repository;
/// LUT which translates namespace-unique-ids to their associated fontid_t (if any).
/// Index with uniqueId - uniqueIdBase.
int uniqueIdBase;
bool uniqueIdMapDirty;
uint uniqueIdMapSize;
fontid_t* uniqueIdMap;
};
D_CMD(ListFonts);
#if _DEBUG
D_CMD(PrintFontStats);
#endif
static int iterateDirectory(fontnamespaceid_t namespaceId,
int (*callback)(FontRepository::Node& node, void* parameters), void* parameters);
static de::Uri* emptyUri;
// LUT which translates fontid_t to PathTreeNode*. Index with fontid_t-1
static uint fontIdMapSize;
static FontRepository::Node** fontIdMap;
// Font namespace set.
static FontNamespace namespaces[FONTNAMESPACE_COUNT];
void Fonts_Register(void)
{
C_CMD("listfonts", NULL, ListFonts)
#if _DEBUG
C_CMD("fontstats", NULL, PrintFontStats)
#endif
}
static inline FontRepository* repositoryByNamespaceId(fontnamespaceid_t id)
{
DENG_ASSERT(VALID_FONTNAMESPACEID(id));
return namespaces[id - FONTNAMESPACE_FIRST].repository;
}
static fontnamespaceid_t namespaceIdForRepository(FontRepository& pt)
{
for(uint i = uint(FONTNAMESPACE_FIRST); i <= uint(FONTNAMESPACE_LAST); ++i)
{
uint idx = i - FONTNAMESPACE_FIRST;
if(namespaces[idx].repository == &pt) return fontnamespaceid_t(i);
}
// Only reachable if attempting to find the id for a Font that is not
// in the collection, or the collection has not yet been initialized.
Con_Error("Fonts::namespaceIdForRepository: Failed to determine id for directory %p.", (void*)&pt);
exit(1); // Unreachable.
}
static inline bool validFontId(fontid_t id)
{
return (id != NOFONTID && id <= fontIdMapSize);
}
static FontRepository::Node* findDirectoryNodeForBindId(fontid_t id)
{
if(!validFontId(id)) return NULL;
return fontIdMap[id-1/*1-based index*/];
}
static fontid_t findBindIdForDirectoryNode(FontRepository::Node const& node)
{
/// @todo Optimize (Low priority): Do not use a linear search.
for(uint i = 0; i < fontIdMapSize; ++i)
{
if(fontIdMap[i] == &node)
return fontid_t(i + 1); // 1-based index.
}
return NOFONTID; // Not linked.
}
static inline fontnamespaceid_t namespaceIdForDirectoryNode(FontRepository::Node const& node)
{
return namespaceIdForRepository(node.tree());
}
/// @return Newly composed Uri for @a node. Must be released with Uri_Delete()
static de::Uri composeUriForDirectoryNode(FontRepository::Node const& node)
{
Str const* namespaceName = Fonts_NamespaceName(namespaceIdForDirectoryNode(node));
return node.composeUri(FONTS_PATH_DELIMITER).setScheme(Str_Text(namespaceName));
}
/// @pre fontIdMap has been initialized and is large enough!
static void unlinkDirectoryNodeFromBindIdMap(FontRepository::Node const& node)
{
fontid_t id = findBindIdForDirectoryNode(node);
if(!validFontId(id)) return; // Not linked.
fontIdMap[id - 1/*1-based index*/] = NULL;
}
/// @pre uniqueIdMap has been initialized and is large enough!
static int linkRecordInUniqueIdMap(FontRepository::Node& node, void* parameters)
{
DENG_UNUSED(parameters);
FontRecord const* record = (FontRecord*) node.userPointer();
fontnamespaceid_t const namespaceId = namespaceIdForRepository(node.tree());
FontNamespace& fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
fn.uniqueIdMap[record->uniqueId - fn.uniqueIdBase] = findBindIdForDirectoryNode(node);
return 0; // Continue iteration.
}
/// @pre uniqueIdMap is large enough if initialized!
static int unlinkRecordInUniqueIdMap(FontRepository::Node& node, void* parameters)
{
DENG_UNUSED(parameters);
FontRecord const* record = (FontRecord*) node.userPointer();
fontnamespaceid_t const namespaceId = namespaceIdForRepository(node.tree());
FontNamespace& fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
if(fn.uniqueIdMap)
{
fn.uniqueIdMap[record->uniqueId - fn.uniqueIdBase] = NOFONTID;
}
return 0; // Continue iteration.
}
/**
* @defgroup validateFontUriFlags Validate Font Uri Flags
*/
///@{
#define VFUF_ALLOW_NAMESPACE_ANY 0x1 ///< The namespace of the uri may be of zero-length; signifying "any namespace".
#define VFUF_NO_URN 0x2 ///< Do not accept a URN.
///@}
/**
* @param uri Uri to be validated.
* @param flags @see validateFontUriFlags
* @param quiet @c true= Do not output validation remarks to the log.
*
* @return @c true if @a Uri passes validation.
*/
static bool validateUri(de::Uri const& uri, int flags, bool quiet = false)
{
LOG_AS("Fonts::validateUri");
if(Str_IsEmpty(uri.path()))
{
if(!quiet)
{
LOG_MSG("Invalid path in Font uri \"%s\".") << uri;
}
return false;
}
// If this is a URN we extract the namespace from the path.
ddstring_t const* namespaceString;
if(!Str_CompareIgnoreCase(uri.scheme(), "urn"))
{
if(flags & VFUF_NO_URN) return false;
namespaceString = uri.path();
}
else
{
namespaceString = uri.scheme();
}
fontnamespaceid_t namespaceId = Fonts_ParseNamespace(Str_Text(namespaceString));
if(!((flags & VFUF_ALLOW_NAMESPACE_ANY) && namespaceId == FN_ANY) &&
!VALID_FONTNAMESPACEID(namespaceId))
{
if(!quiet)
{
LOG_MSG("Unknown namespace in Font uri \"%s\".") << uri;
}
return false;
}
return true;
}
/**
* Given a directory and path, search the Fonts collection for a match.
*
* @param directory Namespace-specific PathTree to search in.
* @param path Path of the font to search for.
* @return Found DirectoryNode else @c NULL
*/
static FontRepository::Node* findDirectoryNodeForPath(FontRepository& directory, de::String path)
{
try
{
FontRepository::Node& node = directory.find(PCF_NO_BRANCH | PCF_MATCH_FULL, path, FONTS_PATH_DELIMITER);
return &node;
}
catch(FontRepository::NotFoundError const&)
{} // Ignore this error.
return 0;
}
/// @pre @a uri has already been validated and is well-formed.
static FontRepository::Node* findDirectoryNodeForUri(de::Uri const& uri)
{
if(!Str_CompareIgnoreCase(uri.scheme(), "urn"))
{
// This is a URN of the form; urn:namespacename:uniqueid
fontnamespaceid_t namespaceId = Fonts_ParseNamespace(Str_Text(uri.path()));
char* uid = strchr(Str_Text(uri.path()), ':');
if(uid)
{
fontid_t id = Fonts_FontForUniqueId(namespaceId, strtol(uid + 1/*skip namespace delimiter*/, 0, 0));
if(id != NOFONTID)
{
return findDirectoryNodeForBindId(id);
}
}
return NULL;
}
// This is a URI.
fontnamespaceid_t namespaceId = Fonts_ParseNamespace(Str_Text(uri.scheme()));
char const* path = Str_Text(uri.path());
if(namespaceId != FN_ANY)
{
// Caller wants a font in a specific namespace.
return findDirectoryNodeForPath(*repositoryByNamespaceId(namespaceId), path);
}
// Caller does not care which namespace.
// Check for the font in these namespaces in priority order.
static const fontnamespaceid_t order[] = {
FN_GAME, FN_SYSTEM, FN_ANY
};
FontRepository::Node* node = NULL;
int n = 0;
do
{
node = findDirectoryNodeForPath(*repositoryByNamespaceId(order[n]), path);
} while(!node && order[++n] != FN_ANY);
return node;
}
static void destroyFont(font_t* font)
{
DENG_ASSERT(font);
switch(Font_Type(font))
{
case FT_BITMAP: BitmapFont_Delete(font); return;
case FT_BITMAPCOMPOSITE: BitmapCompositeFont_Delete(font); return;
default:
Con_Error("Fonts::destroyFont: Invalid font type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
}
static void destroyBoundFont(FontRepository::Node& node)
{
FontRecord* record = (FontRecord*) node.userPointer();
if(record && record->font)
{
destroyFont(record->font); record->font = 0;
}
}
static void destroyRecord(FontRepository::Node& node)
{
LOG_AS("Fonts::destroyRecord");
FontRecord* record = (FontRecord*) node.userPointer();
if(record)
{
if(record->font)
{
#if _DEBUG
de::Uri uri = composeUriForDirectoryNode(node);
LOG_WARNING("destroyRecord: Record for \"%s\" still has Font data!") << uri;
#endif
destroyFont(record->font);
}
unlinkDirectoryNodeFromBindIdMap(node);
unlinkRecordInUniqueIdMap(node, NULL/*no parameters*/);
// Detach our user data from this node.
node.setUserPointer(0);
M_Free(record);
}
}
static void destroyFontAndRecord(FontRepository::Node& node)
{
destroyBoundFont(node);
destroyRecord(node);
}
boolean Fonts_IsInitialized(void)
{
return emptyUri != 0;
}
void Fonts_Init(void)
{
LOG_VERBOSE("Initializing Fonts collection...");
emptyUri = new de::Uri();
fontIdMap = 0;
fontIdMapSize = 0;
for(int i = 0; i < FONTNAMESPACE_COUNT; ++i)
{
FontNamespace& fn = namespaces[i];
fn.repository = new FontRepository();
fn.uniqueIdBase = 0;
fn.uniqueIdMapSize = 0;
fn.uniqueIdMap = NULL;
fn.uniqueIdMapDirty = false;
}
}
static int destroyRecordWorker(FontRepository::Node& node, void* parameters)
{
DENG_UNUSED(parameters);
destroyRecord(node);
return 0; // Continue iteration.
}
void Fonts_Shutdown(void)
{
Fonts_Clear();
for(int i = 0; i < FONTNAMESPACE_COUNT; ++i)
{
FontNamespace& fn = namespaces[i];
if(fn.repository)
{
fn.repository->iterate(PCF_NO_BRANCH, NULL, PATHTREE_NOHASH, destroyRecordWorker);
delete fn.repository; fn.repository = 0;
}
if(!fn.uniqueIdMap) continue;
M_Free(fn.uniqueIdMap); fn.uniqueIdMap = 0;
fn.uniqueIdBase = 0;
fn.uniqueIdMapSize = 0;
fn.uniqueIdMapDirty = false;
}
// Clear the bindId to PathTreeNode LUT.
if(fontIdMap)
{
M_Free(fontIdMap); fontIdMap = 0;
}
fontIdMapSize = 0;
if(emptyUri)
{
delete emptyUri; emptyUri = 0;
}
}
fontnamespaceid_t Fonts_ParseNamespace(char const* str)
{
static const struct namespace_s {
const char* name;
size_t nameLen;
fontnamespaceid_t id;
} namespaces[FONTNAMESPACE_COUNT+1] = {
// Ordered according to a best guess of occurance frequency.
{ FN_GAME_NAME, sizeof(FN_GAME_NAME) - 1, FN_GAME },
{ FN_SYSTEM_NAME, sizeof(FN_SYSTEM_NAME) - 1, FN_SYSTEM },
{ NULL, 0, FN_ANY }
};
size_t len, n;
// Special case: zero-length string means "any namespace".
if(!str || 0 == (len = strlen(str))) return FN_ANY;
// Stop comparing characters at the first occurance of ':'
char const* end = strchr(str, ':');
if(end) len = end - str;
for(n = 0; namespaces[n].name; ++n)
{
if(len < namespaces[n].nameLen) continue;
if(strnicmp(str, namespaces[n].name, len)) continue;
return namespaces[n].id;
}
return FN_INVALID; // Unknown.
}
ddstring_t const* Fonts_NamespaceName(fontnamespaceid_t id)
{
static de::Str const namespaces[1 + FONTNAMESPACE_COUNT] = {
/* No namespace name */ "",
/* FN_SYSTEM */ FN_SYSTEM_NAME,
/* FN_SYSTEM */ FN_GAME_NAME
};
if(VALID_FONTNAMESPACEID(id))
return namespaces[1 + (id - FONTNAMESPACE_FIRST)];
return namespaces[0];
}
uint Fonts_Size(void)
{
return fontIdMapSize;
}
uint Fonts_Count(fontnamespaceid_t namespaceId)
{
if(!VALID_FONTNAMESPACEID(namespaceId) || !Fonts_Size()) return 0;
FontRepository* directory = repositoryByNamespaceId(namespaceId);
if(!directory) return 0;
return directory->size();
}
void Fonts_Clear(void)
{
if(!Fonts_Size()) return;
Fonts_ClearNamespace(FN_ANY);
GL_PruneTextureVariantSpecifications();
}
void Fonts_ClearRuntime(void)
{
if(!Fonts_Size()) return;
Fonts_ClearNamespace(FN_GAME);
GL_PruneTextureVariantSpecifications();
}
void Fonts_ClearSystem(void)
{
if(!Textures_Size()) return;
Fonts_ClearNamespace(FN_SYSTEM);
GL_PruneTextureVariantSpecifications();
}
static int destroyFontAndRecordWorker(FontRepository::Node& node, void* /*parameters*/)
{
destroyFontAndRecord(node);
return 0; // Continue iteration.
}
void Fonts_ClearNamespace(fontnamespaceid_t namespaceId)
{
if(!Fonts_Size()) return;
fontnamespaceid_t from, to;
if(namespaceId == FN_ANY)
{
from = FONTNAMESPACE_FIRST;
to = FONTNAMESPACE_LAST;
}
else if(VALID_FONTNAMESPACEID(namespaceId))
{
from = to = namespaceId;
}
else
{
Con_Error("Fonts::ClearNamespace: Invalid font namespace %i.", (int) namespaceId);
exit(1); // Unreachable.
}
for(uint i = uint(from); i <= uint(to); ++i)
{
FontNamespace& fn = namespaces[i - FONTNAMESPACE_FIRST];
if(fn.repository)
{
fn.repository->iterate(PCF_NO_BRANCH, NULL, PATHTREE_NOHASH, destroyFontAndRecordWorker);
fn.repository->clear();
}
fn.uniqueIdMapDirty = true;
}
}
void Fonts_Release(font_t* font)
{
/// Stub.
switch(Font_Type(font))
{
case FT_BITMAP:
BitmapFont_DeleteGLTexture(font);
break;
case FT_BITMAPCOMPOSITE:
BitmapCompositeFont_ReleaseTextures(font);
break;
default:
Con_Error("Fonts::Release: Invalid font type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
}
static void Fonts_Prepare(font_t* font)
{
switch(Font_Type(font))
{
case FT_BITMAP: BitmapFont_Prepare(font); break;
case FT_BITMAPCOMPOSITE: BitmapCompositeFont_Prepare(font); break;
default:
Con_Error("Fonts::Prepare: Invalid font type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
}
int Fonts_Ascent(font_t* font)
{
Fonts_Prepare(font);
return Font_Ascent(font);
}
int Fonts_Descent(font_t* font)
{
Fonts_Prepare(font);
return Font_Descent(font);
}
int Fonts_Leading(font_t* font)
{
Fonts_Prepare(font);
return Font_Leading(font);
}
int Fonts_CharWidth(font_t* font, unsigned char ch)
{
Fonts_Prepare(font);
switch(Font_Type(font))
{
case FT_BITMAP: return BitmapFont_CharWidth(font, ch);
case FT_BITMAPCOMPOSITE: return BitmapCompositeFont_CharWidth(font, ch);
default:
Con_Error("Fonts::CharWidth: Invalid font type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
}
int Fonts_CharHeight(font_t* font, unsigned char ch)
{
Fonts_Prepare(font);
switch(Font_Type(font))
{
case FT_BITMAP: return BitmapFont_CharHeight(font, ch);
case FT_BITMAPCOMPOSITE: return BitmapCompositeFont_CharHeight(font, ch);
default:
Con_Error("Fonts::CharHeight: Invalid font type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
}
void Fonts_CharSize(font_t* font, Size2Raw* size, unsigned char ch)
{
if(!size) return;
size->width = Fonts_CharWidth(font, ch);
size->height = Fonts_CharHeight(font, ch);
}
font_t* Fonts_ToFont(fontid_t id)
{
LOG_AS("Fonts::toFont");
if(!validFontId(id))
{
#if _DEBUG
if(id != NOFONTID)
{
LOG_WARNING("Failed to locate font for id #%i, returning NULL.") << id;
}
#endif
return NULL;
}
FontRepository::Node* node = findDirectoryNodeForBindId(id);
if(!node) return NULL;
return ((FontRecord*) node->userPointer())->font;
}
typedef struct {
int minId, maxId;
} finduniqueidbounds_params_t;
static int findUniqueIdBounds(FontRepository::Node& node, void* parameters)
{
FontRecord const* record = (FontRecord*) node.userPointer();
finduniqueidbounds_params_t* p = (finduniqueidbounds_params_t*)parameters;
if(record->uniqueId < p->minId) p->minId = record->uniqueId;
if(record->uniqueId > p->maxId) p->maxId = record->uniqueId;
return 0; // Continue iteration.
}
static void rebuildUniqueIdMap(fontnamespaceid_t namespaceId)
{
FontNamespace fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
fontnamespaceid_t localNamespaceId = namespaceId;
finduniqueidbounds_params_t p;
DENG_ASSERT(VALID_FONTNAMESPACEID(namespaceId));
if(!fn.uniqueIdMapDirty) return;
// Determine the size of the LUT.
p.minId = DDMAXINT;
p.maxId = DDMININT;
iterateDirectory(namespaceId, findUniqueIdBounds, (void*)&p);
if(p.minId > p.maxId)
{
// None found.
fn.uniqueIdBase = 0;
fn.uniqueIdMapSize = 0;
}
else
{
fn.uniqueIdBase = p.minId;
fn.uniqueIdMapSize = p.maxId - p.minId + 1;
}
// Construct and (re)populate the LUT.
fn.uniqueIdMap = (fontid_t*)M_Realloc(fn.uniqueIdMap, sizeof *fn.uniqueIdMap * fn.uniqueIdMapSize);
if(!fn.uniqueIdMap && fn.uniqueIdMapSize)
Con_Error("Fonts::rebuildUniqueIdMap: Failed on (re)allocation of %lu bytes resizing the map.", (unsigned long) sizeof *fn.uniqueIdMap * fn.uniqueIdMapSize);
if(fn.uniqueIdMapSize)
{
memset(fn.uniqueIdMap, NOFONTID, sizeof *fn.uniqueIdMap * fn.uniqueIdMapSize);
iterateDirectory(namespaceId, linkRecordInUniqueIdMap, (void*)&localNamespaceId);
}
fn.uniqueIdMapDirty = false;
}
fontid_t Fonts_FontForUniqueId(fontnamespaceid_t namespaceId, int uniqueId)
{
if(VALID_FONTNAMESPACEID(namespaceId))
{
FontNamespace fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
rebuildUniqueIdMap(namespaceId);
if(fn.uniqueIdMap && uniqueId >= fn.uniqueIdBase &&
(unsigned)(uniqueId - fn.uniqueIdBase) <= fn.uniqueIdMapSize)
{
return fn.uniqueIdMap[uniqueId - fn.uniqueIdBase];
}
}
return NOFONTID; // Not found.
}
fontid_t Fonts_ResolveUri2(Uri const* _uri, boolean quiet)
{
LOG_AS("Fonts::resolveUri");
if(!_uri || !Fonts_Size()) return NOFONTID;
de::Uri const& uri = reinterpret_cast<de::Uri const&>(*_uri);
if(!validateUri(uri, VFUF_ALLOW_NAMESPACE_ANY, true /*quiet please*/))
{
#if _DEBUG
LOG_WARNING("Uri \"%s\" failed validation, returning NOFONTID.") << uri;
#endif
return NOFONTID;
}
// Perform the search.
FontRepository::Node* node = findDirectoryNodeForUri(uri);
if(node)
{
// If we have bound a font - it can provide the id.
FontRecord* record = (FontRecord*) node->userPointer();
DENG_ASSERT(record);
if(record->font)
{
fontid_t id = Font_PrimaryBind(record->font);
if(validFontId(id)) return id;
}
// Oh well, look it up then.
return findBindIdForDirectoryNode(*node);
}
// Not found.
if(!quiet)
{
LOG_DEBUG("\"%s\" not found, returning NOFONTID.") << uri;
}
return NOFONTID;
}
fontid_t Fonts_ResolveUri(Uri const* uri)
{
return Fonts_ResolveUri2(uri, !(verbose >= 1)/*log warnings if verbose*/);
}
fontid_t Fonts_ResolveUriCString2(char const* path, boolean quiet)
{
if(path && path[0])
{
Uri* uri = Uri_NewWithPath2(path, RC_NULL);
fontid_t id = Fonts_ResolveUri2(uri, quiet);
Uri_Delete(uri);
return id;
}
return NOFONTID;
}
fontid_t Fonts_ResolveUriCString(char const* path)
{
return Fonts_ResolveUriCString2(path, !(verbose >= 1)/*log warnings if verbose*/);
}
fontid_t Fonts_Declare(Uri const* _uri, int uniqueId)//, const Uri* resourcePath)
{
DENG_ASSERT(_uri);
LOG_AS("Fonts::declare");
de::Uri const& uri = reinterpret_cast<de::Uri const&>(*_uri);
// We require a properly formed uri (but not a urn - this is a path).
if(!validateUri(uri, VFUF_NO_URN, (verbose >= 1)))
{
LOG_WARNING("Failed creating Font \"%s\", ignoring.") << uri;
return NOFONTID;
}
// Have we already created a binding for this?
fontid_t id;
FontRecord* record;
FontRepository::Node* node = findDirectoryNodeForUri(uri);
if(node)
{
record = (FontRecord*) node->userPointer();
DENG_ASSERT(record);
id = findBindIdForDirectoryNode(*node);
}
else
{
/*
* A new binding.
*/
// Ensure the path is lowercase.
de::String path = de::String(Str_Text(uri.path())).toLower();
record = (FontRecord*) M_Malloc(sizeof *record);
if(!record) Con_Error("Fonts::Declare: Failed on allocation of %lu bytes for new FontRecord.", (unsigned long) sizeof *record);
record->font = 0;
record->uniqueId = uniqueId;
fontnamespaceid_t namespaceId = Fonts_ParseNamespace(Str_Text(uri.scheme()));
FontNamespace& fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
node = fn.repository->insert(path, FONTS_PATH_DELIMITER);
node->setUserPointer(record);
// We'll need to rebuild the unique id map too.
fn.uniqueIdMapDirty = true;
id = fontIdMapSize + 1; // 1-based identfier
// Link it into the id map.
fontIdMap = (FontRepository::Node**) M_Realloc(fontIdMap, sizeof *fontIdMap * ++fontIdMapSize);
if(!fontIdMap) Con_Error("Fonts::Declare: Failed on (re)allocation of %lu bytes enlarging bindId to PathTreeNode LUT.", (unsigned long) sizeof *fontIdMap * fontIdMapSize);
fontIdMap[id - 1] = node;
}
/**
* (Re)configure this binding.
*/
bool releaseFont = false;
// We don't care whether these identfiers are truely unique. Our only
// responsibility is to release fonts when they change.
if(record->uniqueId != uniqueId)
{
record->uniqueId = uniqueId;
releaseFont = true;
// We'll need to rebuild the id map too.
fontnamespaceid_t namespaceId = namespaceIdForRepository(node->tree());
FontNamespace& fn = namespaces[namespaceId - FONTNAMESPACE_FIRST];
fn.uniqueIdMapDirty = true;
}
if(releaseFont && record->font)
{
// The mapped resource is being replaced, so release any existing Font.
/// @todo Only release if this Font is bound to only this binding.
Fonts_Release(record->font);
}
return id;
}
static font_t* createFont(fonttype_t type, fontid_t bindId)
{
switch(type)
{
case FT_BITMAP: return BitmapFont_New(bindId);
case FT_BITMAPCOMPOSITE: return BitmapCompositeFont_New(bindId);
default:
Con_Error("Fonts::ConstructFont: Unknown font type %i.", (int)type);
exit(1); // Unreachable.
}
}
static font_t* createFontFromDef(fontid_t bindId, ded_compositefont_t* def)
{
DENG_ASSERT(def);
font_t* font = createFont(FT_BITMAPCOMPOSITE, bindId);
BitmapCompositeFont_SetDefinition(font, def);
for(int i = 0; i < def->charMapCount.num; ++i)
{
ddstring_t const* path;
if(!def->charMap[i].path) continue;
path = Uri_ResolvedConst(def->charMap[i].path);
if(path)
{
BitmapCompositeFont_CharSetPatch(font, def->charMap[i].ch, Str_Text(path));
}
}
// Lets try to prepare it right away.
BitmapCompositeFont_Prepare(font);
return font;
}
static font_t* createFontFromFile(fontid_t bindId, char const* resourcePath)
{
DENG_ASSERT(resourcePath);
font_t* font = createFont(FT_BITMAP, bindId);
BitmapFont_SetFilePath(font, resourcePath);
// Lets try and prepare it right away.
BitmapFont_Prepare(font);
return font;
}
void Fonts_RebuildFromDef(font_t* font, ded_compositefont_t* def)
{
if(Font_Type(font) != FT_BITMAPCOMPOSITE)
{
Con_Error("Fonts::RebuildFromDef: Font is of invalid type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
BitmapCompositeFont_SetDefinition(font, def);
if(!def) return;
for(int i = 0; i < def->charMapCount.num; ++i)
{
ddstring_t const* path;
if(!def->charMap[i].path) continue;
path = Uri_ResolvedConst(def->charMap[i].path);
if(path)
{
BitmapCompositeFont_CharSetPatch(font, def->charMap[i].ch, Str_Text(path));
}
}
}
font_t* Fonts_CreateFromDef(fontid_t id, ded_compositefont_t* def)
{
LOG_AS("Fonts::createFromDef");
FontRepository::Node* node = findDirectoryNodeForBindId(id);
if(!node)
{
LOG_WARNING("Failed creating Font #%u (invalid id), ignoring.") << id;
return 0;
}
if(!def)
{
LOG_WARNING("Failed creating Font #%u (def = NULL), ignoring.") << id;
return 0;
}
FontRecord* record = (FontRecord*) node->userPointer();
DENG_ASSERT(record);
if(record->font)
{
/// @todo Do not update fonts here (not enough knowledge). We should instead
/// return an invalid reference/signal and force the caller to implement the
/// necessary update logic.
font_t* font = record->font;
#if _DEBUG
de::Uri* uri = reinterpret_cast<de::Uri*>(Fonts_ComposeUri(id));
LOG_DEBUG("A Font with uri \"%s\" already exists, returning existing.") << uri;
delete uri;
#endif
Fonts_RebuildFromDef(font, def);
return font;
}
// A new font.
record->font = createFontFromDef(id, def);
if(record->font && verbose >= 1)
{
de::Uri* uri = reinterpret_cast<de::Uri*>(Fonts_ComposeUri(id));
LOG_VERBOSE("New font \"%s\"") << uri;
delete uri;
}
return record->font;
}
void Fonts_RebuildFromFile(font_t* font, char const* resourcePath)
{
if(Font_Type(font) != FT_BITMAP)
{
Con_Error("Fonts::RebuildFromFile: Font is of invalid type %i.", (int) Font_Type(font));
exit(1); // Unreachable.
}
BitmapFont_SetFilePath(font, resourcePath);
}
font_t* Fonts_CreateFromFile(fontid_t id, char const* resourcePath)
{
LOG_AS("Fonts::createFromFile");
FontRepository::Node* node = findDirectoryNodeForBindId(id);
if(!node)
{
LOG_WARNING("Failed creating Font #%u (invalid id), ignoring.") << id;
return 0;
}
if(!resourcePath || !resourcePath[0])
{
LOG_WARNING("Failed creating Font #%u (resourcePath = NULL), ignoring.") << id;
return 0;
}
FontRecord* record = (FontRecord*) node->userPointer();
DENG_ASSERT(record);