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 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214
|
/*=========================================================================
Program: Visualization Toolkit
Module: vtkFreeTypeTools.cxx
Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
All rights reserved.
See Copyright.txt or http://www.kitware.com/Copyright.htm for details.
This software is distributed WITHOUT ANY WARRANTY; without even
the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
PURPOSE. See the above copyright notice for more information.
=========================================================================*/
#include "vtkFreeTypeTools.h"
#include "vtkTextProperty.h"
#include "vtkObjectFactory.h"
#include "vtkMath.h"
#include "vtkImageData.h"
#include "vtkSmartPointer.h"
#include "vtkStdString.h"
#include "vtkUnicodeString.h"
// FTGL
#include "vtkftglConfig.h"
#include "FTLibrary.h"
// The embedded fonts
#include "fonts/vtkEmbeddedFonts.h"
#ifdef FTGL_USE_NAMESPACE
using namespace ftgl;
#endif
#include <stdint.h>
// Print debug info
#define VTK_FTFC_DEBUG 0
#define VTK_FTFC_DEBUG_CD 0
//----------------------------------------------------------------------------
vtkInstantiatorNewMacro(vtkFreeTypeTools);
//----------------------------------------------------------------------------
// The singleton, and the singleton cleanup
vtkFreeTypeTools* vtkFreeTypeTools::Instance = NULL;
vtkFreeTypeToolsCleanup vtkFreeTypeTools::Cleanup;
//----------------------------------------------------------------------------
// The embedded fonts
// Create a lookup table between the text mapper attributes
// and the font buffers.
struct EmbeddedFontStruct
{
size_t length;
unsigned char *ptr;
};
//----------------------------------------------------------------------------
// This callback will be called by the FTGLibrary singleton cleanup destructor
// if it happens to be destroyed before our singleton (this order is not
// deterministic). It will destroy our singleton, if needed.
void vtkFreeTypeToolsCleanupCallback ()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeToolsCleanupCallback\n");
#endif
vtkFreeTypeTools::SetInstance(NULL);
}
//----------------------------------------------------------------------------
// Create the singleton cleanup
// Register our singleton cleanup callback against the FTLibrary so that
// it might be called before the FTLibrary singleton is destroyed.
vtkFreeTypeToolsCleanup::vtkFreeTypeToolsCleanup()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeToolsCleanup::vtkFreeTypeToolsCleanup\n");
#endif
FTLibraryCleanup::AddDependency(&vtkFreeTypeToolsCleanupCallback);
}
//----------------------------------------------------------------------------
// Delete the singleton cleanup
// The callback called here might have been called by the FTLibrary singleton
// cleanup first (depending on the destruction order), but in case ours is
// destroyed first, let's call it too.
vtkFreeTypeToolsCleanup::~vtkFreeTypeToolsCleanup()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeToolsCleanup::~vtkFreeTypeToolsCleanup\n");
#endif
vtkFreeTypeToolsCleanupCallback();
}
//----------------------------------------------------------------------------
vtkFreeTypeTools* vtkFreeTypeTools::GetInstance()
{
if (!vtkFreeTypeTools::Instance)
{
vtkFreeTypeTools::Instance = static_cast<vtkFreeTypeTools *>(
vtkObjectFactory::CreateInstance("vtkFreeTypeTools"));
if (!vtkFreeTypeTools::Instance)
{
vtkFreeTypeTools::Instance = new vtkFreeTypeTools;
}
}
return vtkFreeTypeTools::Instance;
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::SetInstance(vtkFreeTypeTools* instance)
{
if (vtkFreeTypeTools::Instance == instance)
{
return;
}
if (vtkFreeTypeTools::Instance)
{
vtkFreeTypeTools::Instance->Delete();
}
vtkFreeTypeTools::Instance = instance;
// User will call ->Delete() after setting instance
if (instance)
{
instance->Register(NULL);
}
}
//----------------------------------------------------------------------------
vtkFreeTypeTools::vtkFreeTypeTools()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::vtkFreeTypeTools\n");
#endif
this->MaximumNumberOfFaces = 30; // combinations of family+bold+italic
this->MaximumNumberOfSizes = this->MaximumNumberOfFaces * 20; // sizes
this->MaximumNumberOfBytes = 300000UL * this->MaximumNumberOfSizes;
this->CacheManager = NULL;
this->ImageCache = NULL;
this->CMapCache = NULL;
this->ScaleToPowerTwo = false;
}
//----------------------------------------------------------------------------
vtkFreeTypeTools::~vtkFreeTypeTools()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::~vtkFreeTypeTools\n");
#endif
this->ReleaseCacheManager();
}
//----------------------------------------------------------------------------
FT_Library* vtkFreeTypeTools::GetLibrary()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::GetLibrary\n");
#endif
FTLibrary * ftgl_lib = FTLibrary::GetInstance();
if (ftgl_lib)
{
return ftgl_lib->GetLibrary();
}
return NULL;
}
//----------------------------------------------------------------------------
FTC_Manager* vtkFreeTypeTools::GetCacheManager()
{
if (!this->CacheManager)
{
this->InitializeCacheManager();
}
return this->CacheManager;
}
//----------------------------------------------------------------------------
FTC_ImageCache* vtkFreeTypeTools::GetImageCache()
{
if (!this->ImageCache)
{
this->InitializeCacheManager();
}
return this->ImageCache;
}
//----------------------------------------------------------------------------
FTC_CMapCache* vtkFreeTypeTools::GetCMapCache()
{
if (!this->CMapCache)
{
this->InitializeCacheManager();
}
return this->CMapCache;
}
//----------------------------------------------------------------------------
FT_CALLBACK_DEF(FT_Error)
vtkFreeTypeToolsFaceRequester(FTC_FaceID face_id,
FT_Library lib,
FT_Pointer request_data,
FT_Face* face)
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeToolsFaceRequester()\n");
#endif
FT_UNUSED(request_data);
// Get a pointer to the current vtkFreeTypeTools object
vtkFreeTypeTools *self =
reinterpret_cast<vtkFreeTypeTools*>(request_data);
// Map the ID to a text property
vtkSmartPointer<vtkTextProperty> tprop =
vtkSmartPointer<vtkTextProperty>::New();
self->MapIdToTextProperty(reinterpret_cast<intptr_t>(face_id), tprop);
// Fonts, organized by [Family][Bold][Italic]
static EmbeddedFontStruct EmbeddedFonts[3][2][2] =
{
{
{
{ // VTK_ARIAL: Bold [ ] Italic [ ]
face_arial_buffer_length, face_arial_buffer
},
{ // VTK_ARIAL: Bold [ ] Italic [x]
face_arial_italic_buffer_length, face_arial_italic_buffer
}
},
{
{ // VTK_ARIAL: Bold [x] Italic [ ]
face_arial_bold_buffer_length, face_arial_bold_buffer
},
{ // VTK_ARIAL: Bold [x] Italic [x]
face_arial_bold_italic_buffer_length, face_arial_bold_italic_buffer
}
}
},
{
{
{ // VTK_COURIER: Bold [ ] Italic [ ]
face_courier_buffer_length, face_courier_buffer
},
{ // VTK_COURIER: Bold [ ] Italic [x]
face_courier_italic_buffer_length, face_courier_italic_buffer
}
},
{
{ // VTK_COURIER: Bold [x] Italic [ ]
face_courier_bold_buffer_length, face_courier_bold_buffer
},
{ // VTK_COURIER: Bold [x] Italic [x]
face_courier_bold_italic_buffer_length,
face_courier_bold_italic_buffer
}
}
},
{
{
{ // VTK_TIMES: Bold [ ] Italic [ ]
face_times_buffer_length, face_times_buffer
},
{ // VTK_TIMES: Bold [ ] Italic [x]
face_times_italic_buffer_length, face_times_italic_buffer
}
},
{
{ // VTK_TIMES: Bold [x] Italic [ ]
face_times_bold_buffer_length, face_times_bold_buffer
},
{ // VTK_TIMES: Bold [x] Italic [x]
face_times_bold_italic_buffer_length, face_times_bold_italic_buffer
}
}
}
};
FT_Long length = EmbeddedFonts
[tprop->GetFontFamily()][tprop->GetBold()][tprop->GetItalic()].length;
FT_Byte *ptr = EmbeddedFonts
[tprop->GetFontFamily()][tprop->GetBold()][tprop->GetItalic()].ptr;
// Create a new face from the embedded fonts if possible
FT_Error error = 1;
// If the font face is of type unknown, attempt to load it from disk
if (tprop->GetFontFamily() != VTK_UNKNOWN_FONT)
{
error = FT_New_Memory_Face(lib, ptr, length, 0, face);
}
else
{
vtkStdString filePath = "/usr/share/fonts/TTF/DejaVuSans.ttf";
cout << "Loading a font from disk!!! " << filePath << endl;
error = FT_New_Face(lib, filePath.c_str(), 0, face);
}
if (error)
{
vtkErrorWithObjectMacro(
tprop.GetPointer(),
<< "Unable to create font !" << " (family: " << tprop->GetFontFamily()
<< ", bold: " << tprop->GetBold() << ", italic: " << tprop->GetItalic()
<< ", length: " << length << ")");
}
else
{
#if VTK_FTFC_DEBUG
cout << "Requested: " << *face
<< " (F: " << tprop->GetFontFamily()
<< ", B: " << tprop->GetBold()
<< ", I: " << tprop->GetItalic()
<< ", O: " << tprop->GetOrientation() << ")" << endl;
#endif
if ( tprop->GetOrientation() != 0.0 )
{
// FreeType documentation says that the transform should not be set
// but we cache faces also by transform, so that there is a unique
// (face, orientation) cache entry
FT_Matrix matrix;
float angle = vtkMath::RadiansFromDegrees( tprop->GetOrientation() );
matrix.xx = (FT_Fixed)( cos(angle) * 0x10000L);
matrix.xy = (FT_Fixed)(-sin(angle) * 0x10000L);
matrix.yx = (FT_Fixed)( sin(angle) * 0x10000L);
matrix.yy = (FT_Fixed)( cos(angle) * 0x10000L);
FT_Set_Transform(*face, &matrix, NULL);
}
}
return error;
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::InitializeCacheManager()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::InitializeCacheManager()\n");
#endif
this->ReleaseCacheManager();
FT_Error error;
// Create the cache manager itself
this->CacheManager = new FTC_Manager;
error = FTC_Manager_New(*this->GetLibrary(),
this->MaximumNumberOfFaces,
this->MaximumNumberOfSizes,
this->MaximumNumberOfBytes,
vtkFreeTypeToolsFaceRequester,
static_cast<FT_Pointer>(this),
this->CacheManager);
if (error)
{
vtkErrorMacro(<< "Failed allocating a new FreeType Cache Manager");
}
// The image cache
this->ImageCache = new FTC_ImageCache;
error = FTC_ImageCache_New(*this->CacheManager, this->ImageCache);
if (error)
{
vtkErrorMacro(<< "Failed allocating a new FreeType Image Cache");
}
// The charmap cache
this->CMapCache = new FTC_CMapCache;
error = FTC_CMapCache_New(*this->CacheManager, this->CMapCache);
if (error)
{
vtkErrorMacro(<< "Failed allocating a new FreeType CMap Cache");
}
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::ReleaseCacheManager()
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::ReleaseCacheManager()\n");
#endif
if (this->CacheManager)
{
FTC_Manager_Done(*this->CacheManager);
delete this->CacheManager;
this->CacheManager = NULL;
}
if (this->ImageCache)
{
delete this->ImageCache;
this->ImageCache = NULL;
}
if (this->CMapCache)
{
delete this->CMapCache;
this->CMapCache = NULL;
}
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::IsBoundingBoxValid(int bbox[4])
{
return (!bbox ||
bbox[0] == VTK_INT_MAX || bbox[1] == VTK_INT_MIN ||
bbox[2] == VTK_INT_MAX || bbox[3] == VTK_INT_MIN) ? false : true;
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetBoundingBox(vtkTextProperty *tprop,
const vtkStdString& str,
int bbox[4])
{
// We need the tprop and bbox
if (!tprop || !bbox)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL or zero");
return false;
}
// No string to render, bail out now
if (str.empty())
{
return false;
}
return this->CalculateBoundingBox(tprop, str, bbox);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetBoundingBox(vtkTextProperty *tprop,
const vtkUnicodeString& str,
int bbox[4])
{
// We need the tprop and bbox
if (!tprop || !bbox)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL or zero");
return false;
}
// No string to render, bail out now
if (str.empty())
{
return false;
}
return this->CalculateBoundingBox(tprop, str, bbox);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::RenderString(vtkTextProperty *tprop,
const vtkStdString& str,
vtkImageData *data)
{
// Check parameters
if (!tprop || !data)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL or zero");
return false;
}
if (data->GetNumberOfScalarComponents() > 4)
{
vtkErrorMacro("The image data must have a maximum of four components");
return false;
}
if (str.empty())
{
return false;
}
// Prepare the ImageData to receive the text
int x = 0;
int y = 0;
this->PrepareImageData(data, tprop, str, &x, &y);
// Execute text
return this->PopulateImageData(tprop, str, x, y, data);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::RenderString(vtkTextProperty *tprop,
const vtkUnicodeString& str,
vtkImageData *data)
{
// Check parameters
if (!tprop || !data)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL or zero");
return false;
}
if (data->GetNumberOfScalarComponents() > 4)
{
vtkErrorMacro("The image data must have a maximum of four components");
return false;
}
if (str.empty())
{
return false;
}
// Prepare the ImageData to receive the text
int x = 0;
int y = 0;
this->PrepareImageData(data, tprop, str, &x, &y);
// Execute text
return this->PopulateImageData(tprop, str, x, y, data);
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::MapTextPropertyToId(vtkTextProperty *tprop,
unsigned long *id)
{
if (!tprop || !id)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL");
return;
}
// Set the first bit to avoid id = 0
// (the id will be mapped to a pointer, FTC_FaceID, so let's avoid NULL)
*id = 1;
int bits = 1;
// The font family is in 4 bits (= 5 bits so far)
// (2 would be enough right now, but who knows, it might grow)
// Avoid unknown as this can cause segfaluts - this should be fixed...
int family = tprop->GetFontFamily() == VTK_UNKNOWN_FONT ? VTK_ARIAL :
tprop->GetFontFamily();
int fam = (family - tprop->GetFontFamilyMinValue()) << bits;
bits += 4;
// Bold is in 1 bit (= 6 bits so far)
int bold = (tprop->GetBold() ? 1 : 0) << bits;
++bits;
// Italic is in 1 bit (= 7 bits so far)
int italic = (tprop->GetItalic() ? 1 : 0) << bits;
++bits;
// Orientation (in degrees)
// We need 9 bits for 0 to 360. What do we need for more precisions:
// - 1/10th degree: 12 bits (11.8)
int angle = (vtkMath::Round(tprop->GetOrientation() * 10.0) % 3600) << bits;
// We really should not use more than 32 bits
// Now final id
*id |= fam | bold | italic | angle;
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::MapIdToTextProperty(unsigned long id,
vtkTextProperty *tprop)
{
if (!tprop)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL");
return;
}
// The first was set to avoid id = 0
int bits = 1;
// The font family is in 4 bits
// (2 would be enough right now, but who knows, it might grow)
int fam = id >> bits;
bits += 4;
tprop->SetFontFamily((fam & ((1 << 4) - 1))+ tprop->GetFontFamilyMinValue());
// Bold is in 1 bit
int bold = id >> bits;
bits++;
tprop->SetBold(bold & 0x1);
// Italic is in 1 bit
int italic = id >> bits;
bits++;
tprop->SetItalic(italic & 0x1);
// Orientation (in degrees)
// We need 9 bits for 0 to 360. What do we need for more precisions:
// - 1/10th degree: 12 bits (11.8)
int angle = id >> bits;
tprop->SetOrientation((angle & ((1 << 12) - 1)) / 10.0);
// We really should not use more than 32 bits
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetSize(unsigned long tprop_cache_id,
int font_size,
FT_Size *size)
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::GetSize()\n");
#endif
if (!size || font_size <= 0)
{
vtkErrorMacro(<< "Wrong parameters, size is NULL or invalid font size");
return 0;
}
FTC_Manager *manager = this->GetCacheManager();
if (!manager)
{
vtkErrorMacro(<< "Failed querying the cache manager !");
return 0;
}
// Map the id of a text property in the cache to a FTC_FaceID
FTC_FaceID face_id = reinterpret_cast<FTC_FaceID>(tprop_cache_id);
FTC_ScalerRec scaler_rec;
scaler_rec.face_id = face_id;
scaler_rec.width = font_size;
scaler_rec.height = font_size;
scaler_rec.pixel = 1;
FT_Error error = FTC_Manager_LookupSize(*manager, &scaler_rec, size);
if (error)
{
vtkErrorMacro(<< "Failed looking up a FreeType Size");
}
return error ? false : true;
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetSize(vtkTextProperty *tprop,
FT_Size *size)
{
if (!tprop)
{
vtkErrorMacro(<< "Wrong parameters, text property is NULL");
return 0;
}
// Map the text property to a unique id that will be used as face id
unsigned long tprop_cache_id;
this->MapTextPropertyToId(tprop, &tprop_cache_id);
return this->GetSize(tprop_cache_id, tprop->GetFontSize(), size);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetFace(unsigned long tprop_cache_id,
FT_Face *face)
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::GetFace()\n");
#endif
if (!face)
{
vtkErrorMacro(<< "Wrong parameters, face is NULL");
return false;
}
FTC_Manager *manager = this->GetCacheManager();
if (!manager)
{
vtkErrorMacro(<< "Failed querying the cache manager !");
return false;
}
// Map the id of a text property in the cache to a FTC_FaceID
FTC_FaceID face_id = reinterpret_cast<FTC_FaceID>(tprop_cache_id);
FT_Error error = FTC_Manager_LookupFace(*manager, face_id, face);
if (error)
{
vtkErrorMacro(<< "Failed looking up a FreeType Face");
}
return error ? false : true;
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetFace(vtkTextProperty *tprop,
FT_Face *face)
{
if (!tprop)
{
vtkErrorMacro(<< "Wrong parameters, face is NULL");
return 0;
}
// Map the text property to a unique id that will be used as face id
unsigned long tprop_cache_id;
this->MapTextPropertyToId(tprop, &tprop_cache_id);
return this->GetFace(tprop_cache_id, face);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetGlyphIndex(unsigned long tprop_cache_id,
FT_UInt32 c,
FT_UInt *gindex)
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::GetGlyphIndex()\n");
#endif
if (!gindex)
{
vtkErrorMacro(<< "Wrong parameters, gindex is NULL");
return 0;
}
FTC_CMapCache *cmap_cache = this->GetCMapCache();
if (!cmap_cache)
{
vtkErrorMacro(<< "Failed querying the charmap cache manager !");
return 0;
}
// Map the id of a text property in the cache to a FTC_FaceID
FTC_FaceID face_id = reinterpret_cast<FTC_FaceID>(tprop_cache_id);
// Lookup the glyph index
*gindex = FTC_CMapCache_Lookup(*cmap_cache, face_id, 0, c);
return *gindex ? true : false;
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetGlyphIndex(vtkTextProperty *tprop,
FT_UInt32 c,
FT_UInt *gindex)
{
if (!tprop)
{
vtkErrorMacro(<< "Wrong parameters, text property is NULL");
return 0;
}
// Map the text property to a unique id that will be used as face id
unsigned long tprop_cache_id;
this->MapTextPropertyToId(tprop, &tprop_cache_id);
return this->GetGlyphIndex(tprop_cache_id, c, gindex);
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetGlyph(unsigned long tprop_cache_id,
int font_size,
FT_UInt gindex,
FT_Glyph *glyph,
int request)
{
#if VTK_FTFC_DEBUG_CD
printf("vtkFreeTypeTools::GetGlyph()\n");
#endif
if (!glyph)
{
vtkErrorMacro(<< "Wrong parameters, one of them is NULL");
return false;
}
FTC_ImageCache *image_cache = this->GetImageCache();
if (!image_cache)
{
vtkErrorMacro(<< "Failed querying the image cache manager !");
return false;
}
// Map the id of a text property in the cache to a FTC_FaceID
FTC_FaceID face_id = reinterpret_cast<FTC_FaceID>(tprop_cache_id);
// Which font are we looking for
FTC_ImageTypeRec image_type_rec;
image_type_rec.face_id = face_id;
image_type_rec.width = font_size;
image_type_rec.height = font_size;
image_type_rec.flags = FT_LOAD_DEFAULT;
if (request == GLYPH_REQUEST_BITMAP)
{
image_type_rec.flags |= FT_LOAD_RENDER;
}
else if (request == GLYPH_REQUEST_OUTLINE)
{
image_type_rec.flags |= FT_LOAD_NO_BITMAP;
}
// Lookup the glyph
FT_Error error = FTC_ImageCache_Lookup(
*image_cache, &image_type_rec, gindex, glyph, NULL);
return error ? false : true;
}
//----------------------------------------------------------------------------
bool vtkFreeTypeTools::GetGlyph(vtkTextProperty *tprop,
FT_UInt32 c,
FT_Glyph *glyph,
int request)
{
if (!tprop)
{
vtkErrorMacro(<< "Wrong parameters, text property is NULL");
return 0;
}
// Map the text property to a unique id that will be used as face id
unsigned long tprop_cache_id;
this->MapTextPropertyToId(tprop, &tprop_cache_id);
// Get the character/glyph index
FT_UInt gindex;
if (!this->GetGlyphIndex(tprop_cache_id, c, &gindex))
{
vtkErrorMacro(<< "Failed querying a glyph index");
return false;
}
// Get the glyph
return this->GetGlyph(
tprop_cache_id, tprop->GetFontSize(), gindex, glyph, request);
}
//----------------------------------------------------------------------------
void vtkFreeTypeTools::PrintSelf(ostream& os, vtkIndent indent)
{
this->Superclass::PrintSelf(os,indent);
os << indent << "MaximumNumberOfFaces: "
<< this->MaximumNumberOfFaces << endl;
os << indent << "MaximumNumberOfSizes: "
<< this->MaximumNumberOfSizes << endl;
os << indent << "MaximumNumberOfBytes: "
<< this->MaximumNumberOfBytes << endl;
os << indent << "Scale to nearest power of 2 for image sizes: "
<< this->ScaleToPowerTwo << endl;
}
//----------------------------------------------------------------------------
template <typename T>
bool vtkFreeTypeTools::CalculateBoundingBox(vtkTextProperty *tprop,
const T& str,
int bbox[4])
{
// Initialize bbox to some large values
bbox[0] = bbox[2] = VTK_INT_MAX;
bbox[1] = bbox[3] = VTK_INT_MIN;
// Map the text property to a unique id that will be used as face id, get the
// font face and establish whether kerning information is available.
unsigned long tprop_cache_id;
FT_Face face;
bool face_has_kerning = false;
if (!this->GetFace(tprop, tprop_cache_id, face, face_has_kerning))
{
return false;
}
int tprop_font_size = tprop->GetFontSize();
FT_BitmapGlyph bitmap_glyph;
FT_Bitmap *bitmap;
FT_UInt gindex, previous_gindex = 0;
FT_Vector kerning_delta;
int x = 0, y = 0;
// Render char by char
for (typename T::const_iterator it = str.begin(); it != str.end(); ++it)
{
bitmap = this->GetBitmap(*it, tprop_cache_id, tprop_font_size, gindex,
bitmap_glyph);
if (!bitmap)
{
// Glyph not found in the face. FIXME: do something more elegant here.
// We should render an empty rectangle to adhere to the specs...
continue;
}
if (bitmap->width && bitmap->rows)
{
// Starting position given the bearings. Move the pen to the upper-left
// extent of this character.
// Substract 1 to the bearing Y, because this is the vertical distance
// from the glyph origin (0,0) to the topmost pixel of the glyph bitmap
// (more precisely, to the pixel just above the bitmap). This distance is
// expressed in integer pixels, and is positive for upwards y.
int pen_x = x + bitmap_glyph->left;
int pen_y = y + bitmap_glyph->top - 1;
// Add the kerning
if (face_has_kerning && previous_gindex && gindex)
{
FT_Get_Kerning(
face, previous_gindex, gindex, ft_kerning_default, &kerning_delta);
pen_x += kerning_delta.x >> 6;
pen_y += kerning_delta.y >> 6;
}
previous_gindex = gindex;
// Update bounding box
if (pen_x < bbox[0])
{
bbox[0] = pen_x;
}
if (pen_y > bbox[3])
{
bbox[3] = pen_y;
}
// now move the pen to the lower-right corner of this character and
// update the bounding box if appropriate
pen_x += bitmap->width;
pen_y -= bitmap->rows;
if (pen_x > bbox[1])
{
bbox[1] = pen_x;
}
if (pen_y < bbox[2])
{
bbox[2] = pen_y;
}
}
// Advance to next char
x += (bitmap_glyph->root.advance.x + 0x8000) >> 16;
y += (bitmap_glyph->root.advance.y + 0x8000) >> 16;
}
return true;
}
template <typename T>
void vtkFreeTypeTools::PrepareImageData(vtkImageData *data,
vtkTextProperty *tprop,
const T& str,
int *x, int *y)
{
int text_bbox[4];
if (!this->GetBoundingBox(tprop, str, text_bbox))
{
vtkErrorMacro(<<"Could not get a valid bounding box.");
return;
}
if (!this->IsBoundingBoxValid(text_bbox))
{
vtkErrorMacro(<<"no text in input");
return;
}
// The bounding box was the area that is going to be filled with pixels
// given a text origin of (0, 0). Now get the real size we need, i.e.
// the full extent from the origin to the bounding box.
int text_size[2];
text_size[0] = (text_bbox[1] - text_bbox[0] + 1);// + abs(text_bbox[0]);
text_size[1] = (text_bbox[3] - text_bbox[2] + 1);// + abs(text_bbox[2]);
// If the RGBA image data is too small, resize it to the next power of 2
// WARNING: at this point, since this image is going to be a texture
// we should limit its size or query the hardware
data->SetScalarTypeToUnsignedChar();
data->SetNumberOfScalarComponents(4);
data->SetSpacing(1.0, 1.0, 1.0);
// If the current image data is too small to render the text,
// or more than twice as big (too hungry), then resize
int img_dims[3], new_img_dims[3];
data->GetDimensions(img_dims);
if (img_dims[0] < text_size[0] || img_dims[1] < text_size[1] ||
text_size[0] * 2 < img_dims[0] || text_size[1] * 2 < img_dims[0])
{
// Scale to the next highest power of 2 if required.
if (this->ScaleToPowerTwo)
{
new_img_dims[0] =
1 << static_cast<int>(ceil(log(static_cast<double>(text_size[0]+1)) /
log(2.0)));
new_img_dims[1] =
1 << static_cast<int>(ceil(log(static_cast<double>(text_size[1]+1)) /
log(2.0)));
}
else
{
new_img_dims[0] = text_size[0]+1;
new_img_dims[1] = text_size[1]+1;
}
new_img_dims[2] = 1;
if (new_img_dims[0] != img_dims[0] ||
new_img_dims[1] != img_dims[1] ||
new_img_dims[2] != img_dims[2])
{
data->SetDimensions(new_img_dims);
data->AllocateScalars();
data->UpdateInformation();
data->SetUpdateExtent(data->GetWholeExtent());
data->PropagateUpdateExtent();
data->SetOrigin(text_size[0] + 1, text_size[1] + 1, 0.0);
data->SetSpacing(text_size[0] / double(new_img_dims[0] - 1),
text_size[1] / double(new_img_dims[1] - 1),
0.0);
}
}
// Render inside the image data
*x = (text_bbox[0] < 0 ? -text_bbox[0] : 0);
*y = (text_bbox[2] < 0 ? -text_bbox[2] : 0);
memset(data->GetScalarPointer(), 0,
(data->GetNumberOfPoints() *
data->GetNumberOfScalarComponents()));
}
//----------------------------------------------------------------------------
template <typename T>
bool vtkFreeTypeTools::PopulateImageData(vtkTextProperty *tprop,
const T& str,
int x, int y,
vtkImageData *data)
{
// Map the text property to a unique id that will be used as face id, get the
// font face and establish whether kerning information is available.
unsigned long tprop_cache_id;
FT_Face face;
bool face_has_kerning = false;
if (!this->GetFace(tprop, tprop_cache_id, face, face_has_kerning))
{
return false;
}
// Text property size and opacity
int tprop_font_size = tprop->GetFontSize();
float tprop_opacity = tprop->GetOpacity();
// Image params (increments, range)
vtkIdType data_inc_x, data_inc_y, data_inc_z;
data->GetIncrements(data_inc_x, data_inc_y, data_inc_z);
double data_min, data_max;
if (data->GetScalarType() == VTK_DOUBLE || data->GetScalarType() == VTK_FLOAT)
{
data_min = 0.0;
data_max = 1.0;
}
else
{
data_min = data->GetScalarTypeMin();
data_max = data->GetScalarTypeMax();
}
double data_range = data_max - data_min;
// Calculate the text color to set in the tight loop.
double color[3];
tprop->GetColor(color);
unsigned char text_color[] = {
static_cast<unsigned char>(data_min + data_range * color[0]),
static_cast<unsigned char>(data_min + data_range * color[1]),
static_cast<unsigned char>(data_min + data_range * color[2]) };
FT_BitmapGlyph bitmap_glyph;
FT_Bitmap *bitmap;
FT_UInt gindex, previous_gindex = 0;
FT_Vector kerning_delta;
// Render char by char
for (typename T::const_iterator it = str.begin(); it != str.end(); ++it)
{
bitmap = this->GetBitmap(*it, tprop_cache_id, tprop_font_size, gindex,
bitmap_glyph);
if (!bitmap)
{
// Glyph not found in the face.
continue;
}
if (bitmap->width && bitmap->rows)
{
// Starting position given the bearings.
// Substract 1 to the bearing Y, because this is the vertical distance
// from the glyph origin (0,0) to the topmost pixel of the glyph bitmap
// (more precisely, to the pixel just above the bitmap). This distance is
// expressed in integer pixels, and is positive for upwards y.
int pen_x = x + bitmap_glyph->left;
int pen_y = y + bitmap_glyph->top - 1;
// Add the kerning
if (face_has_kerning && previous_gindex && gindex)
{
FT_Get_Kerning(
face, previous_gindex, gindex, ft_kerning_default, &kerning_delta);
pen_x += kerning_delta.x >> 6;
pen_y += kerning_delta.y >> 6;
}
previous_gindex = gindex;
// Render the current face.
unsigned char *data_ptr =
static_cast<unsigned char *>(data->GetScalarPointer(pen_x, pen_y, 0));
if(!data_ptr)
{
return false;
}
int data_pitch = (-data->GetDimensions()[0] - bitmap->width) * data_inc_x;
unsigned char *glyph_ptr_row = bitmap->buffer;
unsigned char *glyph_ptr;
float t_alpha, data_alpha, t_1_m_alpha;
for (int j = 0; j < bitmap->rows; ++j)
{
glyph_ptr = glyph_ptr_row;
for (int i = 0; i < bitmap->width; ++i)
{
t_alpha = tprop_opacity * (*glyph_ptr / 255.0);
t_1_m_alpha = 1.0 - t_alpha;
data_alpha = (data_ptr[3] - data_min) / data_range;
*data_ptr = text_color[0];
++data_ptr;
*data_ptr = text_color[1];
++data_ptr;
*data_ptr = text_color[2];
++data_ptr;
*data_ptr = static_cast<unsigned char>(
data_min + data_range * (t_alpha + data_alpha * t_1_m_alpha));
++data_ptr;
++glyph_ptr;
}
glyph_ptr_row += bitmap->pitch;
data_ptr += data_pitch;
}
}
// Advance to next char
x += (bitmap_glyph->root.advance.x + 0x8000) >> 16;
y += (bitmap_glyph->root.advance.y + 0x8000) >> 16;
}
return true;
}
inline bool vtkFreeTypeTools::GetFace(vtkTextProperty *prop,
unsigned long &prop_cache_id,
FT_Face &face, bool &face_has_kerning)
{
this->MapTextPropertyToId(prop, &prop_cache_id);
if (!this->GetFace(prop_cache_id, &face))
{
vtkErrorMacro(<< "Failed retrieving the face");
return false;
}
face_has_kerning = (FT_HAS_KERNING(face) != 0);
return true;
}
inline FT_Bitmap* vtkFreeTypeTools::GetBitmap(FT_UInt32 c,
unsigned long prop_cache_id,
int prop_font_size,
FT_UInt &gindex,
FT_BitmapGlyph &bitmap_glyph)
{
// Get the glyph index
if (!this->GetGlyphIndex(prop_cache_id, c, &gindex))
{
return 0;
}
FT_Glyph glyph;
// Get the glyph as a bitmap
if (!this->GetGlyph(prop_cache_id,
prop_font_size,
gindex,
&glyph,
vtkFreeTypeTools::GLYPH_REQUEST_BITMAP) ||
glyph->format != ft_glyph_format_bitmap)
{
return 0;
}
bitmap_glyph = reinterpret_cast<FT_BitmapGlyph>(glyph);
FT_Bitmap *bitmap = &bitmap_glyph->bitmap;
if (bitmap->pixel_mode != ft_pixel_mode_grays)
{
return 0;
}
return bitmap;
}
|