File: truetype.cpp

package info (click to toggle)
povray 1%3A3.7.0.10-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 147,232 kB
  • sloc: cpp: 845,011; ansic: 122,118; sh: 34,204; pascal: 6,420; asm: 3,355; ada: 1,681; makefile: 1,389; cs: 879; awk: 590; perl: 245; xml: 95
file content (3174 lines) | stat: -rw-r--r-- 85,076 bytes parent folder | download | duplicates (6)
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
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
/*******************************************************************************
 * truetype.cpp
 *
 * This module implements rendering of TrueType fonts.
 * This file was written by Alexander Enzmann.  He wrote the code for
 * rendering glyphs and generously provided us these enhancements.
 *
 * ---------------------------------------------------------------------------
 * Persistence of Vision Ray Tracer ('POV-Ray') version 3.7.
 * Copyright 1991-2013 Persistence of Vision Raytracer Pty. Ltd.
 *
 * POV-Ray is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Affero General Public License as
 * published by the Free Software Foundation, either version 3 of the
 * License, or (at your option) any later version.
 *
 * POV-Ray 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 Affero General Public License for more details.
 *
 * You should have received a copy of the GNU Affero General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 * ---------------------------------------------------------------------------
 * POV-Ray is based on the popular DKB raytracer version 2.12.
 * DKBTrace was originally written by David K. Buck.
 * DKBTrace Ver 2.0-2.12 were written by David K. Buck & Aaron A. Collins.
 * ---------------------------------------------------------------------------
 * $File: //depot/public/povray/3.x/source/backend/shape/truetype.cpp $
 * $Revision: #1 $
 * $Change: 6069 $
 * $DateTime: 2013/11/06 11:59:40 $
 * $Author: chrisc $
 *******************************************************************************/

// frame.h must always be the first POV file included (pulls in platform config)
#include "backend/frame.h"
#include "backend/povray.h"
#include "backend/math/vector.h"
#include "backend/bounding/bbox.h"
#include "backend/math/matrices.h"
#include "backend/scene/objects.h"
#include "backend/shape/truetype.h"
#include "backend/shape/csg.h"                /* [ARE 11/94] */
#include "backend/scene/threaddata.h"
#include "backend/support/fileutil.h"

// this must be the last file included
#include "base/povdebug.h"

namespace pov
{

/*****************************************************************************
* Local preprocessor defines
******************************************************************************/

/* uncomment this to debug ttf. DEBUG1 gives less output than DEBUG2
#define TTF_DEBUG2 1
#define TTF_DEBUG 1
#define TTF_DEBUG3 1
*/

const DBL TTF_Tolerance = 1.0e-6;    /* -4 worked, -8 failed */

const int MAX_ITERATIONS = 50;
const DBL COEFF_LIMIT = 1.0e-20;

/* For decoding glyph coordinate bit flags */
const int ONCURVE            = 0x01;
const int XSHORT             = 0x02;
const int YSHORT             = 0x04;
const int REPEAT_FLAGS       = 0x08;  /* repeat flag n times */
const int SHORT_X_IS_POS     = 0x10;  /* the short vector is positive */
const int NEXT_X_IS_ZERO     = 0x10;  /* the relative x coordinate is zero */
const int SHORT_Y_IS_POS     = 0x20;  /* the short vector is positive */
const int NEXT_Y_IS_ZERO     = 0x20;  /* the relative y coordinate is zero */

/* For decoding multi-component glyph bit flags */
const int ARG_1_AND_2_ARE_WORDS    = 0x0001;
const int ARGS_ARE_XY_VALUES       = 0x0002;
const int ROUND_XY_TO_GRID         = 0x0004;
const int WE_HAVE_A_SCALE          = 0x0008;
/*      RESERVED                 = 0x0010 */
const int MORE_COMPONENTS          = 0x0020;
const int WE_HAVE_AN_X_AND_Y_SCALE = 0x0040;
const int WE_HAVE_A_TWO_BY_TWO     = 0x0080;
const int WE_HAVE_INSTRUCTIONS     = 0x0100;
const int USE_MY_METRICS           = 0x0200;

/* For decoding kern coverage bit flags */
const int KERN_HORIZONTAL    = 0x01;
const int KERN_MINIMUM       = 0x02;
const int KERN_CROSS_STREAM  = 0x04;
const int KERN_OVERRIDE      = 0x08;

/* Some marcos to make error detection easier, as well as clarify code */
#define READSHORT(fp) readSHORT(fp, __LINE__, __FILE__)
#define READLONG(fp) readLONG(fp, __LINE__, __FILE__)
#define READUSHORT(fp) readUSHORT(fp, __LINE__, __FILE__)
#define READULONG(fp) readULONG(fp, __LINE__, __FILE__)
#define READFIXED(fp) readLONG(fp, __LINE__, __FILE__)
#define READFWORD(fp) readSHORT(fp, __LINE__, __FILE__)
#define READUFWORD(fp) readUSHORT(fp, __LINE__, __FILE__)

/*****************************************************************************
* Local typedefs
******************************************************************************/

/* Type definitions to match the TTF spec, makes code clearer */
typedef char CHAR;
typedef unsigned char BYTE;
typedef short SHORT;
typedef unsigned short USHORT;
typedef int LONG;
typedef unsigned int ULONG;
typedef short FWord;
typedef unsigned short uFWord;

#if !defined(TARGET_OS_MAC)
typedef int Fixed;
#endif

typedef struct
{
	Fixed version;                /* 0x10000 (1.0) */
	USHORT numTables;             /* number of tables */
	USHORT searchRange;           /* (max2 <= numTables)*16 */
	USHORT entrySelector;         /* log2 (max2 <= numTables) */
	USHORT rangeShift;            /* numTables*16-searchRange */
} sfnt_OffsetTable;

typedef struct
{
	BYTE tag[4];
	ULONG checkSum;
	ULONG offset;
	ULONG length;
} sfnt_TableDirectory;

typedef sfnt_TableDirectory *sfnt_TableDirectoryPtr;

typedef struct
{
	ULONG bc;
	ULONG ad;
} longDateTime;

typedef struct
{
	Fixed version;                /* for this table, set to 1.0 */
	Fixed fontRevision;           /* For Font Manufacturer */
	ULONG checkSumAdjustment;
	ULONG magicNumber;            /* signature, must be 0x5F0F3CF5 == MAGIC */
	USHORT flags;
	USHORT unitsPerEm;            /* How many in Font Units per EM */

	longDateTime created;
	longDateTime modified;

	FWord xMin;                   /* Font wide bounding box in ideal space */
	FWord yMin;                   /* Baselines and metrics are NOT worked */
	FWord xMax;                   /* into these numbers) */
	FWord yMax;

	USHORT macStyle;              /* macintosh style word */
	USHORT lowestRecPPEM;         /* lowest recommended pixels per Em */

	SHORT fontDirectionHint;
	SHORT indexToLocFormat;       /* 0 - short offsets, 1 - long offsets */
	SHORT glyphDataFormat;
} sfnt_FontHeader;

typedef struct
{
	USHORT platformID;
	USHORT specificID;
	ULONG offset;
} sfnt_platformEntry;

typedef sfnt_platformEntry *sfnt_platformEntryPtr;

typedef struct
{
	USHORT format;
	USHORT length;
	USHORT version;
} sfnt_mappingTable;

typedef struct
{
	Fixed version;

	FWord Ascender;
	FWord Descender;
	FWord LineGap;

	uFWord advanceWidthMax;
	FWord minLeftSideBearing;
	FWord minRightSideBearing;
	FWord xMaxExtent;
	SHORT caretSlopeRise;
	SHORT caretSlopeRun;

	SHORT reserved1;
	SHORT reserved2;
	SHORT reserved3;
	SHORT reserved4;
	SHORT reserved5;

	SHORT metricDataFormat;
	USHORT numberOfHMetrics;      /* number of hMetrics in the hmtx table */
} sfnt_HorizHeader;

typedef struct
{
	SHORT numContours;
	SHORT xMin;
	SHORT yMin;
	SHORT xMax;
	SHORT yMax;
} GlyphHeader;

typedef struct
{
	GlyphHeader header;
	USHORT numPoints;
	USHORT *endPoints;
	BYTE *flags;
	DBL *x, *y;
	USHORT myMetrics;
} GlyphOutline;

typedef struct
{
	BYTE inside_flag;             /* 1 if this an inside contour, 0 if outside */
	USHORT count;                 /* Number of points in the contour */
	BYTE *flags;                  /* On/off curve flags */
	DBL *x, *y;                   /* Coordinates of control vertices */
} Contour;


/* Contour information for a single glyph */
typedef struct GlyphStruct
{
	GlyphHeader header;           /* Count and sizing information about this
	                               * glyph */
	USHORT glyph_index;           /* Internal glyph index for this character */
	Contour *contours;            /* Array of outline contours */
	USHORT unitsPerEm;            /* Max units character */
	GlyphPtr next;                /* Next cached glyph */
	USHORT c;                     /* Character code */
	USHORT myMetrics;             /* Which glyph index this is for metrics */
} Glyph;

typedef struct KernData_struct
{
	USHORT left, right;           /* Glyph index of left/right to kern */
	FWord value;                  /* Delta in FUnits to apply in between */
} KernData;

/*
 * [esp] There's already a "KernTable" on the Mac... renamed to TTKernTable for
 * now in memorium to its author.
 */

typedef struct KernStruct
{
	USHORT coverage;              /* Coverage bit field of this subtable */
	USHORT nPairs;                /* # of kerning pairs in this table */
	KernData *kern_pairs;         /* Array of kerning values */
} TTKernTable;

typedef struct KernTableStruct
{
	USHORT nTables;               /* # of subtables in the kerning table */
	TTKernTable *tables;
} KernTables;

typedef struct longHorMertric
{
	uFWord advanceWidth;          /* Total width of a glyph in FUnits */
	FWord lsb;                    /* FUnits to the left of the glyph */
} longHorMetric;

/* Useful general data about this font */
struct FontFileInfo;

struct FontFileInfo
{
	UCS2 *filename;
	IStream *fp;
	USHORT platformID[4];             /* Character encoding search order */
	USHORT specificID[4];
	ULONG cmap_table_offset;          /* File locations for these tables */
	ULONG glyf_table_offset;
	USHORT numGlyphs;                 /* How many symbols in this file */
	USHORT unitsPerEm;                /* The "resoultion" of this font */
	SHORT indexToLocFormat;           /* 0 - short format, 1 - long format */
	ULONG *loca_table;                /* Mapping from characters to glyphs */
	GlyphPtr glyphs;                  /* Cached info for this font */
	KernTables kerning_tables;        /* Kerning info for this font */
	USHORT numberOfHMetrics;          /* The number of explicit spacings */
	longHorMetric *hmtx_table;        /* Horizontal spacing info */
	ULONG glyphIDoffset;              /* Offset for Type 4 encoding tables */
	USHORT segCount, searchRange,     /* Counts for Type 4 encoding tables */
	       entrySelector, rangeShift;
	USHORT *startCount, *endCount,    /* Type 4 (MS) encoding tables */
	       *idDelta, *idRangeOffset;
	FontFileInfo *next;  /* Next font */
};

/*****************************************************************************
* Local variables
******************************************************************************/

const BYTE tag_CharToIndexMap[] = "cmap"; /* 0x636d6170; */
const BYTE tag_FontHeader[]     = "head"; /* 0x68656164; */
const BYTE tag_GlyphData[]      = "glyf"; /* 0x676c7966; */
const BYTE tag_IndexToLoc[]     = "loca"; /* 0x6c6f6361; */
const BYTE tag_Kerning[]        = "kern"; /* 0x6b65726e; */
const BYTE tag_MaxProfile[]     = "maxp"; /* 0x6d617870; */
const BYTE tag_HorizHeader[]    = "hhea"; /* 0x68686561; */
const BYTE tag_HorizMetric[]    = "hmtx"; /* 0x686d7478; */
const BYTE tag_TTCFontFile[]    = "ttcf"; /* */

/*****************************************************************************
* Static functions
******************************************************************************/

/* Byte order independent I/O routines (probably already in other routines) */
SHORT readSHORT(IStream *infile, int line, const char *file);
USHORT readUSHORT(IStream *infile, int line, const char *file);
LONG readLONG(IStream *infile, int line, const char *file);
ULONG readULONG(IStream *infile, int line, const char *file);
int compare_tag4(BYTE *ttf_tag, BYTE *known_tag);

/* Internal TTF input routines */
FontFileInfo *ProcessFontFile(const char *fontfilename, const int font_id, Parser *parser, shared_ptr<SceneData>& sceneData);
FontFileInfo *OpenFontFile(const char *filename, const int font_id, Parser *parser, shared_ptr<SceneData>& sceneData);
void ProcessHeadTable(FontFileInfo *ffile, int head_table_offset);
void ProcessLocaTable(FontFileInfo *ffile, int loca_table_offset);
void ProcessMaxpTable(FontFileInfo *ffile, int maxp_table_offset);
void ProcessKernTable(FontFileInfo *ffile, int kern_table_offset);
void ProcessHheaTable(FontFileInfo *ffile, int hhea_table_offset);
void ProcessHmtxTable(FontFileInfo *ffile, int hmtx_table_offset);
GlyphPtr ProcessCharacter(FontFileInfo *ffile, unsigned int search_char, unsigned int *glyph_index);
USHORT ProcessCharMap(FontFileInfo *ffile, unsigned int search_char);
USHORT ProcessFormat0Glyph(FontFileInfo *ffile, unsigned int search_char);
USHORT ProcessFormat4Glyph(FontFileInfo *ffile, unsigned int search_char);
USHORT ProcessFormat6Glyph(FontFileInfo *ffile, unsigned int search_char);
GlyphPtr ExtractGlyphInfo(FontFileInfo *ffile, unsigned int glyph_index, unsigned int c);
GlyphOutline *ExtractGlyphOutline(FontFileInfo *ffile, unsigned int glyph_index, unsigned int c);
GlyphPtr ConvertOutlineToGlyph(FontFileInfo *ffile, const GlyphOutline *ttglyph);

/*
 * The following work as macros if sizeof(short) == 16 bits and
 * sizeof(long) == 32 bits, but tend to break otherwise.  Making these
 * into error functions also allows file error checking.  Do not attempt to
 * "optimize" these functions - some architectures require them the way
 * that they are written.
 */
SHORT readSHORT(IStream *infile, int line, const char *file)
{
	int i0, i1 = 0; /* To quiet warnings */

	if ((i0 = infile->Read_Byte ()) == EOF || (i1  = infile->Read_Byte ()) == EOF)
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
	}

	if (i0 & 0x80) /* Subtract 1 after value is negated to avoid overflow [AED] */
		return -(((255 - i0) << 8) | (255 - i1)) - 1;
	else
		return (i0 << 8) | i1;
}

USHORT readUSHORT(IStream *infile, int line, const char *file)
{
	int i0, i1 = 0; /* To quiet warnings */

	if ((i0  = infile->Read_Byte ()) == EOF || (i1  = infile->Read_Byte ()) == EOF)
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
	}

	return (USHORT)((((USHORT)i0) << 8) | ((USHORT)i1));
}

LONG readLONG(IStream *infile, int line, const char *file)
{
	LONG i0, i1 = 0, i2 = 0, i3 = 0; /* To quiet warnings */

	if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF ||
	    (i2 = infile->Read_Byte ()) == EOF || (i3 = infile->Read_Byte ()) == EOF)
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
	}

	if (i0 & 0x80) /* Subtract 1 after value is negated to avoid overflow [AED] */
		return -(((255 - i0) << 24) | ((255 - i1) << 16) |
		         ((255 - i2) << 8)  |  (255 - i3)) - 1;
	else
		return (i0 << 24) | (i1 << 16) | (i2 << 8) | i3;
}

ULONG readULONG(IStream *infile, int line, const char *file)
{
	int i0, i1 = 0, i2 = 0, i3 = 0;  /* To quiet warnings */

	if ((i0 = infile->Read_Byte ()) == EOF || (i1 = infile->Read_Byte ()) == EOF ||
	    (i2 = infile->Read_Byte ()) == EOF || (i3 = infile->Read_Byte ()) == EOF)
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
	}

	return (ULONG) ((((ULONG) i0) << 24) | (((ULONG) i1) << 16) |
	                (((ULONG) i2) << 8)  |  ((ULONG) i3));
}

static int compare_tag4(const BYTE *ttf_tag, const BYTE *known_tag)
{
	return (ttf_tag[0] == known_tag[0] && ttf_tag[1] == known_tag[1] &&
	        ttf_tag[2] == known_tag[2] && ttf_tag[3] == known_tag[3]);
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessNewTTF
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   Alexander Ennzmann
*   
* DESCRIPTION
*
*   Takes an input string and a font filename, and creates a POV-Ray CSG
*   object for each letter in the string.
*
* CHANGES
*
*   Allow usage of built-in fonts via an additional parameter
*   (triggered when filename is null) - Oct 2012 [JG]
*
******************************************************************************/
void TrueType::ProcessNewTTF(CSG *Object, const char *filename, const int font_id, const UCS2 *text_string, DBL depth, const VECTOR offset, Parser *parser, shared_ptr<SceneData>& sceneData)
{
	FontFileInfo *ffile;
	VECTOR local_offset, total_offset;
	TrueType *ttf;
	DBL funit_size;
	TTKernTable *table;
	USHORT coverage;
	unsigned int search_char;
	unsigned int glyph_index, last_index = 0;
	FWord kern_value_x, kern_value_min_x;
	FWord kern_value_y, kern_value_min_y;
	int i, j, k;
	TRANSFORM Trans;

	/* Get general font info */
	ffile = ProcessFontFile(filename, font_id, parser, sceneData);

	if((sceneData->languageVersion < 350) && (sceneData->stringEncoding == 0))
	{
// TODO MESSAGE		PossibleError("Text may not be displayed as expected.\n"
//		              "Please refer to the user manual regarding changes\n"
//		              "in POV-Ray 3.5 and later.");
	}

	/* Get info about each character in the string */
	Make_Vector(total_offset, 0.0, 0.0, 0.0);

	for (i = 0; text_string[i] != 0; i++)
	{
		/*
		 * We need to make sure (for now) that this is only the lower 8 bits,
		 * so we don't have all the high bits set if converted from a signed
		 * char to an unsigned short.
		 */
		search_char = (unsigned int)(text_string[i]);

#ifdef TTF_DEBUG
		Debug_Info("\nChar: '%c' (0x%X), Offset[%d]: <%g,%g,%g>\n", (char)search_char,
			search_char, i, total_offset[X], total_offset[Y], total_offset[Z]);
#endif

		/* Make a new child for each character */
		ttf = new TrueType();

		/* Set the depth information for the character */
		ttf->depth = depth;

		/*
		 * Get pointers to the contour information for each character
		 * in the text string.
		 */
		ttf->glyph = ProcessCharacter(ffile, search_char, &glyph_index);
		funit_size = 1.0 / (DBL)(ffile->unitsPerEm);

		/*
		 * Spacing based on the horizontal metric table, the kerning table,
		 * and (possibly) the previous glyph.
		 */
		if (i == 0) /* Ignore spacing on the left for the first character only */
		{
			/* Shift the glyph to start at the origin */
			total_offset[X] = -ttf->glyph->header.xMin * funit_size;

			Compute_Translation_Transform(&Trans, total_offset);

			ttf->Translate(total_offset, &Trans);

			/* Shift next glyph by the width of this one excluding the left offset*/
			total_offset[X] = (ffile->hmtx_table[ttf->glyph->myMetrics].advanceWidth -
			                   ffile->hmtx_table[ttf->glyph->myMetrics].lsb) * funit_size;

#ifdef TTF_DEBUG
			Debug_Info("aw(%d): %g\n", i,
			                   (ffile->hmtx_table[ttf->glyph->myMetrics].advanceWidth -
			                    ffile->hmtx_table[ttf->glyph->myMetrics].lsb)*funit_size);
#endif
		}
		else /* Kern all of the other characters */
		{
			kern_value_x = kern_value_y = 0;
			kern_value_min_x = kern_value_min_y = -ffile->unitsPerEm;
			Make_Vector(local_offset, 0.0, 0.0, 0.0);

			for (j = 0; j < ffile->kerning_tables.nTables; j++)
			{
				table = ffile->kerning_tables.tables;
				coverage = table->coverage;

				/*
				 * Don't use vertical kerning until such a time when we support
				 * characters moving in the vertical direction...
				 */
				if (!(coverage & KERN_HORIZONTAL))
					continue;

				/*
				 * If we were keen, we could do a binary search for this
				 * character combination, since the pairs are sorted in 
				 * order as if the left and right index values were a 32 bit 
				 * unsigned int (mostly - at least they are sorted on the
				 * left glyph).  Something to do when everything else works...
				 */
				for (k = 0; k < table[j].nPairs; k++)
				{
					if (table[j].kern_pairs[k].left == last_index &&
					    table[j].kern_pairs[k].right == ttf->glyph->myMetrics)
					{
#ifdef TTF_DEBUG2
						Debug_Info("Found a kerning for <%d, %d> = %d\n",
						           last_index, glyph_index, table[j].kern_pairs[k].value);
#endif

						/*
						 * By default, Windows & OS/2 assume at most a single table with
						 * !KERN_MINIMUM, !KERN_CROSS_STREAM, KERN_OVERRIDE.
						 */
						if (coverage & KERN_MINIMUM)
						{
#ifdef TTF_DEBUG2
							Debug_Info(" KERN_MINIMUM\n");
#endif
							if (coverage & KERN_CROSS_STREAM)
								kern_value_min_y = table[j].kern_pairs[k].value;
							else
								kern_value_min_x = table[j].kern_pairs[k].value;
						}
						else
						{
							if (coverage & KERN_CROSS_STREAM)
							{
#ifdef TTF_DEBUG2
								Debug_Info(" KERN_CROSS_STREAM\n");
#endif
								if (table[j].kern_pairs[k].value == (FWord)0x8000)
								{
									kern_value_y = 0;
								}
								else
								{
									if (coverage & KERN_OVERRIDE)
										kern_value_y = table[j].kern_pairs[k].value;
									else
										kern_value_y += table[j].kern_pairs[k].value;
								}
							}
							else
							{
#ifdef TTF_DEBUG2
								Debug_Info(" KERN_VALUE\n");
#endif
								if (coverage & KERN_OVERRIDE)
									kern_value_x = table[j].kern_pairs[k].value;
								else
									kern_value_x += table[j].kern_pairs[k].value;
							}
						}
						break;
					}
					/* Abort now if we have passed all potential matches */
					else if (table[j].kern_pairs[k].left > last_index)
					{
						break;
					}
				}
			}
			kern_value_x = (kern_value_x > kern_value_min_x ?
			                kern_value_x : kern_value_min_x);
			kern_value_y = (kern_value_y > kern_value_min_y ?
			                kern_value_y : kern_value_min_y);

			/*
			 * Offset this character so that the left edge of the glyph is at
			 * the previous offset + the lsb + any kerning amount.
			 */
			local_offset[X] = total_offset[X] +
			                  (DBL)(ffile->hmtx_table[ttf->glyph->myMetrics].lsb -
			                        ttf->glyph->header.xMin + kern_value_x) * funit_size;
			local_offset[Y] = total_offset[Y] + (DBL)kern_value_y * funit_size;

			/* Translate this glyph to its final position in the string */
			Compute_Translation_Transform(&Trans, local_offset);

			ttf->Translate(local_offset, &Trans);

			/* Shift next glyph by the width of this one + any kerning amount */
			total_offset[X] += (ffile->hmtx_table[ttf->glyph->myMetrics].advanceWidth +kern_value_x) * funit_size;

#ifdef TTF_DEBUG
			Debug_Info("kern(%d): <%d, %d> (%g,%g)\n", i, last_index, glyph_index,
			           (DBL)kern_value_x*funit_size, (DBL)kern_value_y * funit_size);
			Debug_Info("lsb(%d): %g\n", i,
			           (DBL)ffile->hmtx_table[glyph->myMetrics].lsb * funit_size);
			Debug_Info("aw(%d): %g\n", i,
			           (DBL)ffile->hmtx_table[glyph->myMetrics].advanceWidth *
			           funit_size);
#endif
		}

		/*
		 * Add to the offset of the next character the minimum spacing specified.
		 */
		VAddEq(total_offset, offset);

		/* Link this glyph with the others in the union */
		Object->Type |= (ttf->Type & CHILDREN_FLAGS);
		ttf->Type |= IS_CHILD_OBJECT;
		Object->children.push_back(ttf);

		last_index = glyph_index;
	}

#ifdef TTF_DEBUG
	if (filename)
	{
		Debug_Info("TTF parsing of \"%s\" from %s complete\n", text_string, filename);
	}
	else
	{
		Debug_Info("TTF parsing of \"%s\" from builtin %d complete\n", text_string, font_id);
	}
#endif

	/* Close the font file descriptor */
	if(ffile->fp!=NULL)
	{
		delete ffile->fp;
		ffile->fp = NULL;
	}
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessFontFile
*
* INPUT
*
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   Alexander Ennzmann
*   
* DESCRIPTION
*
* Read the header information about the specific font.  Parse the tables
* as we come across them.
*
* CHANGES
*
*   Added tests for reading manditory tables/validity checks - Jan 1996 [AED]
*   Reordered table parsing to avoid lots of file seeking - Jan 1996 [AED]
*
*   Added builtin fonts when fontfilename is nullptr - Oct 2012 [JG]
*
******************************************************************************/
FontFileInfo *ProcessFontFile(const char *fontfilename, const int font_id, Parser *parser, shared_ptr<SceneData>& sceneData)
{
	unsigned i;
	int head_table_offset = 0;
	int loca_table_offset = 0;
	int maxp_table_offset = 0;
	int kern_table_offset = 0;
	int hhea_table_offset = 0;
	int hmtx_table_offset = 0;
	BYTE temp_tag[4];
	sfnt_OffsetTable OffsetTable;
	sfnt_TableDirectory Table;
	FontFileInfo *ffile;

	/* Open the font file */

	ffile = OpenFontFile(fontfilename, font_id, parser, sceneData);

	/* We have already read all the header info, no need to do it again */

	if (ffile->cmap_table_offset != 0)
	{
		return (ffile);
	}

	/*
	 * Read the initial directory header on the TTF.  The numTables variable
	 * tells us how many tables are present in this file.
	 */
	if (!ffile->fp->read((char *)(&temp_tag), sizeof(BYTE) * 4))
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file table tag");
	}
	if (compare_tag4(temp_tag, tag_TTCFontFile))
	{
		READFIXED(ffile->fp); // header version - ignored [trf]
		READULONG(ffile->fp); // directory count - ignored [trf]
		// go to first font data block listed in the directory table entry [trf]
		ffile->fp->seekg(READULONG(ffile->fp), SEEK_SET);
	}
	else
	{
		// if it is no TTC style file, it is a regular TTF style file
		ffile->fp->seekg(0, SEEK_SET);
	}

	OffsetTable.version = READFIXED(ffile->fp);
	OffsetTable.numTables = READUSHORT(ffile->fp);
	OffsetTable.searchRange = READUSHORT(ffile->fp);
	OffsetTable.entrySelector = READUSHORT(ffile->fp);
	OffsetTable.rangeShift = READUSHORT(ffile->fp);

#ifdef TTF_DEBUG
	Debug_Info("OffsetTable:\n");
	Debug_Info("version=%d\n", OffsetTable.version);
	Debug_Info("numTables=%u\n", OffsetTable.numTables);
	Debug_Info("searchRange=%u\n", OffsetTable.searchRange);
	Debug_Info("entrySelector=%u\n", OffsetTable.entrySelector);
	Debug_Info("rangeShift=%u\n", OffsetTable.rangeShift);
#endif

	/*
	 * I don't know why we limit this to 40 tables, since the spec says there
	 * can be any number, but that's how it was when I got it.  Added a warning
	 * just in case it ever happens in real life. [AED]
	 */
	if (OffsetTable.numTables > 40)
	{
// TODO MESSAGE    Warning(0, "More than 40 (%d) TTF Tables in %s - some info may be lost!",
//            OffsetTable.numTables, ffile->filename);
	}

	/* Process general font information and save it. */

	for (i = 0; i < OffsetTable.numTables && i < 40; i++)
	{
		if (!ffile->fp->read((char *)(&Table.tag), sizeof(BYTE) * 4))
		{
			throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file table tag");
		}
		Table.checkSum = READULONG(ffile->fp);
		Table.offset   = READULONG(ffile->fp);
		Table.length   = READULONG(ffile->fp);

#ifdef TTF_DEBUG
		Debug_Info("\nTable %d:\n",i);
		Debug_Info("tag=%c%c%c%c\n", Table.tag[0], Table.tag[1],
		                             Table.tag[2], Table.tag[3]);
		Debug_Info("checkSum=%u\n", Table.checkSum);
		Debug_Info("offset=%u\n", Table.offset);
		Debug_Info("length=%u\n", Table.length);
#endif

		if (compare_tag4(Table.tag, tag_CharToIndexMap))
			ffile->cmap_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_GlyphData))
			ffile->glyf_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_FontHeader))
			head_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_IndexToLoc))
			loca_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_MaxProfile))
			maxp_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_Kerning))
			kern_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_HorizHeader))
			hhea_table_offset = Table.offset;
		else if (compare_tag4(Table.tag, tag_HorizMetric))
			hmtx_table_offset = Table.offset;
	}

	if (ffile->cmap_table_offset == 0 || ffile->glyf_table_offset == 0 ||
	    head_table_offset == 0 || loca_table_offset == 0 ||
	    hhea_table_offset == 0 || hmtx_table_offset == 0 ||
	    maxp_table_offset == 0)
	{
// TODO MESSAGE    throw POV_EXCEPTION(kFileDataErr, "Invalid TrueType font headers in %s", ffile->filename);
	}

	ProcessHeadTable(ffile, head_table_offset);  /* Need indexToLocFormat */
	if ((ffile->indexToLocFormat != 0 && ffile->indexToLocFormat != 1) ||
	    (ffile->unitsPerEm < 16 || ffile->unitsPerEm > 16384))
;// TODO MESSAGE    Error("Invalid TrueType font data in %s", ffile->filename);

	ProcessMaxpTable(ffile, maxp_table_offset);  /* Need numGlyphs */
	if (ffile->numGlyphs <= 0)
;// TODO MESSAGE    Error("Invalid TrueType font data in %s", ffile->filename);

	ProcessLocaTable(ffile, loca_table_offset);  /* Now we can do loca_table */

	ProcessHheaTable(ffile, hhea_table_offset);  /* Need numberOfHMetrics */
	if (ffile->numberOfHMetrics <= 0)
;// TODO MESSAGE    Error("Invalid TrueType font data in %s", ffile->filename);

	ProcessHmtxTable(ffile, hmtx_table_offset);  /* Now we can read HMetrics */

	if (kern_table_offset != 0)
		ProcessKernTable(ffile, kern_table_offset);

	/* Return the information about this font */

	return ffile;
}

/*****************************************************************************
*
* FUNCTION
*
*   OpenFontFile
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   Alexander Ennzmann
*   
* DESCRIPTION
*
*   -
*
* CHANGES
*
*   Added support for builtin fonts - Oct 2012 [JG]
*
******************************************************************************/
FontFileInfo *OpenFontFile(const char *asciifn, const int font_id, Parser *parser, shared_ptr<SceneData>& sceneData)
{
	/* int i; */ /* tw, mtg */
	FontFileInfo *fontlist = NULL;
	UCS2String b, ign;
	if (asciifn)
	{
		UCS2String filename(ASCIItoUCS2String(asciifn));

		/* First look to see if we have already opened this font */

		for(fontlist = sceneData->TTFonts; fontlist != NULL; fontlist = fontlist->next)
			if(!parser->UCS2_strcmp(filename.c_str(), fontlist->filename))
				break;

	}
	if(fontlist != NULL)
	{
		if(fontlist->fp == NULL)
		{
			/* We have a match, use the previous information */
			fontlist->fp = Locate_File(parser, sceneData, fontlist->filename,POV_File_Font_TTF,ign,true);
			if(fontlist->fp == NULL)
			{
				throw POV_EXCEPTION(kCannotOpenFileErr, "Cannot open font file.");
			}
		}
		else
		{
			#ifdef TTF_DEBUG
			Debug_Info("Using cached font info for %s\n", fontlist->filename);
			#endif
		}
	}
	else
	{
		/*
		 * We haven't looked at this font before, let's allocate a holder for the
		 * information and set some defaults
		 */

		fontlist = (FontFileInfo *)POV_CALLOC(1, sizeof(FontFileInfo), "FontFileInfo");

		if (asciifn)
		{
			UCS2String filename(ASCIItoUCS2String(asciifn));

			if((fontlist->fp = Locate_File(parser, sceneData, filename,POV_File_Font_TTF,b,true)) == NULL)
			{
				throw POV_EXCEPTION(kCannotOpenFileErr, "Cannot open font file.");
			}
		}
		else
		{
			fontlist->fp = Internal_Font_File(font_id,b);
		}

		fontlist->filename = parser->UCS2_strdup(b.c_str());

		/*
		 * For Microsoft encodings 3, 1 is for Unicode
		 *                         3, 0 is for Non-Unicode (ie symbols)
		 * For Macintosh encodings 1, 0 is for Roman character set
		 * For Unicode encodings   0, 3 is for Unicode
		 */
		switch(sceneData->stringEncoding)
		{
			case 0: // ASCII
				// first choice
				fontlist->platformID[0] = 1;
				fontlist->specificID[0] = 0;
				// second choice
				fontlist->platformID[1] = 3;
				fontlist->specificID[1] = 1;
				// third choice
				fontlist->platformID[2] = 0;
				fontlist->specificID[2] = 3;
				// fourth choice
				fontlist->platformID[3] = 3;
				fontlist->specificID[3] = 0;
				break;
			case 1: // UTF8
			case 2: // System Specific
				// first choice
				fontlist->platformID[0] = 0;
				fontlist->specificID[0] = 3;
				// second choice
				fontlist->platformID[1] = 3;
				fontlist->specificID[1] = 1;
				// third choice
				fontlist->platformID[2] = 1;
				fontlist->specificID[2] = 0;
				// fourth choice
				fontlist->platformID[3] = 3;
				fontlist->specificID[3] = 0;
				break;
		}
		fontlist->next = sceneData->TTFonts;
		sceneData->TTFonts = fontlist;
	}

	return fontlist;
}

void FreeFontInfo(FontFileInfo *ffi)
{
	int i;
	FontFileInfo *oldfont, *tempfont;
	GlyphPtr glyphs, tempglyph;

	for (oldfont = ffi; oldfont != NULL;)
	{
		if (oldfont->fp != NULL)
			delete oldfont->fp;

		if (oldfont->filename != NULL)
			POV_FREE(oldfont->filename);

		if (oldfont->loca_table != NULL)
			POV_FREE(oldfont->loca_table);

		if (oldfont->hmtx_table != NULL)
			POV_FREE(oldfont->hmtx_table);

		if (oldfont->kerning_tables.nTables != 0)
		{
			for (i = 0; i < oldfont->kerning_tables.nTables; i++)
			{
				if (oldfont->kerning_tables.tables[i].kern_pairs)
					POV_FREE(oldfont->kerning_tables.tables[i].kern_pairs);
			}

			POV_FREE(oldfont->kerning_tables.tables);
		}

		for (glyphs = oldfont->glyphs; glyphs != NULL;)
		{
			for (i = 0; i < glyphs->header.numContours; i++)
			{
				POV_FREE(glyphs->contours[i].flags);
				POV_FREE(glyphs->contours[i].x);
				POV_FREE(glyphs->contours[i].y);
			}

			if (glyphs->contours != NULL)
				POV_FREE(glyphs->contours);

			tempglyph = glyphs;
			glyphs = glyphs->next;
			POV_FREE(tempglyph);
		}

		if (oldfont->segCount != 0)
		{
			POV_FREE(oldfont->endCount);
			POV_FREE(oldfont->startCount);
			POV_FREE(oldfont->idDelta);
			POV_FREE(oldfont->idRangeOffset);
		}

		tempfont = oldfont;
		oldfont = oldfont->next;
		POV_FREE(tempfont);
	}
}

/* Process the font header table */
void ProcessHeadTable(FontFileInfo *ffile, int head_table_offset)
{
	sfnt_FontHeader fontHeader;

	/* Read head table */
	ffile->fp->seekg(head_table_offset) ;

	fontHeader.version = READFIXED(ffile->fp);
	fontHeader.fontRevision = READFIXED(ffile->fp);
	fontHeader.checkSumAdjustment = READULONG(ffile->fp);
	fontHeader.magicNumber = READULONG(ffile->fp);   /* should be 0x5F0F3CF5 */
	fontHeader.flags = READUSHORT(ffile->fp);
	fontHeader.unitsPerEm = READUSHORT(ffile->fp);
	fontHeader.created.bc = READULONG(ffile->fp);
	fontHeader.created.ad = READULONG(ffile->fp);
	fontHeader.modified.bc = READULONG(ffile->fp);
	fontHeader.modified.ad = READULONG(ffile->fp);
	fontHeader.xMin = READFWORD(ffile->fp);
	fontHeader.yMin = READFWORD(ffile->fp);
	fontHeader.xMax = READFWORD(ffile->fp);
	fontHeader.yMax = READFWORD(ffile->fp);
	fontHeader.macStyle = READUSHORT(ffile->fp);
	fontHeader.lowestRecPPEM = READUSHORT(ffile->fp);
	fontHeader.fontDirectionHint = READSHORT(ffile->fp);
	fontHeader.indexToLocFormat = READSHORT(ffile->fp);
	fontHeader.glyphDataFormat = READSHORT(ffile->fp);

#ifdef TTF_DEBUG
	Debug_Info("\nfontHeader:\n");
	Debug_Info("version: %d\n",fontHeader.version);
	Debug_Info("fontRevision: %d\n",fontHeader.fontRevision);
	Debug_Info("checkSumAdjustment: %u\n",fontHeader.checkSumAdjustment);
	Debug_Info("magicNumber: 0x%8X\n",fontHeader.magicNumber);
	Debug_Info("flags: %u\n",fontHeader.flags);
	Debug_Info("unitsPerEm: %u\n",fontHeader.unitsPerEm);
	Debug_Info("created.bc: %u\n",fontHeader.created.bc);
	Debug_Info("created.ad: %u\n",fontHeader.created.ad);
	Debug_Info("modified.bc: %u\n",fontHeader.modified.bc);
	Debug_Info("modified.ad: %u\n",fontHeader.modified.ad);
	Debug_Info("xMin: %d\n",fontHeader.xMin);
	Debug_Info("yMin: %d\n",fontHeader.yMin);
	Debug_Info("xMax: %d\n",fontHeader.xMax);
	Debug_Info("yMax: %d\n",fontHeader.yMax);
	Debug_Info("macStyle: %u\n",fontHeader.macStyle);
	Debug_Info("lowestRecPPEM: %u\n",fontHeader.lowestRecPPEM);
	Debug_Info("fontDirectionHint: %d\n",fontHeader.fontDirectionHint);
	Debug_Info("indexToLocFormat: %d\n",fontHeader.indexToLocFormat);
	Debug_Info("glyphDataFormat: %d\n",fontHeader.glyphDataFormat);
#endif

	if (fontHeader.magicNumber != 0x5F0F3CF5)
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font.");
	}

	ffile->indexToLocFormat = fontHeader.indexToLocFormat;
	ffile->unitsPerEm = fontHeader.unitsPerEm;
}

/* Determine the relative offsets of glyphs */
void ProcessLocaTable(FontFileInfo *ffile, int loca_table_offset)
{
	int i;

	/* Move to location of table in file */
	ffile->fp->seekg(loca_table_offset) ;

	ffile->loca_table = (ULONG *)POV_MALLOC((ffile->numGlyphs+1) * sizeof(ULONG), "ttf");

#ifdef TTF_DEBUG
	Debug_Info("\nlocation table:\n");
	Debug_Info("version: %s\n",(ffile->indexToLocFormat?"long":"short"));
#endif

	/* Now read and save the location table */

	if (ffile->indexToLocFormat == 0)                  /* short version */
	{
		for (i = 0; i < ffile->numGlyphs; i++)
		{
			ffile->loca_table[i] = ((ULONG)READUSHORT(ffile->fp)) << 1;
#ifdef TTF_DEBUG2
			Debug_Info("loca_table[%d] @ %u\n", i, ffile->loca_table[i]);
#endif
		}
	}
	else                                               /* long version */
	{
		for (i = 0; i < ffile->numGlyphs; i++)
		{
			ffile->loca_table[i] = READULONG(ffile->fp);
#ifdef TTF_DEBUG2
			Debug_Info("loca_table[%d] @ %u\n", i, ffile->loca_table[i]);
#endif
		}
	}
}


/*
 * This routine determines the total number of glyphs in a TrueType file.
 * Necessary so that we can allocate the proper amount of storage for the glyph
 * location table.
 */
void ProcessMaxpTable(FontFileInfo *ffile, int maxp_table_offset)
{
	/* seekg to the maxp table, skipping the 4 byte version number */
	ffile->fp->seekg(maxp_table_offset + 4) ;

	ffile->numGlyphs = READUSHORT(ffile->fp);

#ifdef TTF_DEBUG
	Debug_Info("\nmaximum profile table:\n");
	Debug_Info("numGlyphs: %u\n", ffile->numGlyphs);
#endif
}


/* Read the kerning information for a glyph */
void ProcessKernTable(FontFileInfo *ffile, int kern_table_offset)
{
	int i, j;
	USHORT temp16;
	USHORT length;
	KernTables *kern_table;

	kern_table = &ffile->kerning_tables;

	/* Move to the beginning of the kerning table, skipping the 2 byte version */
	ffile->fp->seekg(kern_table_offset + 2) ;

	/* Read in the number of kerning tables */

	kern_table->nTables = READUSHORT(ffile->fp);
	kern_table->tables = NULL;      /*<==[esp] added (in case nTables is zero)*/

#ifdef TTF_DEBUG
	Debug_Info("\nKerning table:\n", kern_table_offset);
	Debug_Info("Offset: %d\n", kern_table_offset);
	Debug_Info("Number of tables: %u\n",kern_table->nTables);
#endif

	/* Don't do any more work if there isn't kerning info */

	if (kern_table->nTables == 0)
		return;

	kern_table->tables = (TTKernTable *)POV_MALLOC(kern_table->nTables * sizeof(TTKernTable),
	                                "ProcessKernTable");

	for (i = 0; i < kern_table->nTables; i++)
	{
		/* Read in a subtable */

		temp16 = READUSHORT(ffile->fp);                      /* Subtable version */
		length = READUSHORT(ffile->fp);                       /* Subtable length */
		kern_table->tables[i].coverage = READUSHORT(ffile->fp); /* Coverage bits */

#ifdef TTF_DEBUG
		Debug_Info("Coverage table[%d] (0x%X):", i, kern_table->tables[i].coverage);
		Debug_Info("  type %u", (kern_table->tables[i].coverage >> 8));
		Debug_Info(" %s", (kern_table->tables[i].coverage & KERN_HORIZONTAL ?
		                     "Horizontal" : "Vertical" ));
		Debug_Info(" %s values", (kern_table->tables[i].coverage & KERN_MINIMUM ?
		                     "Minimum" : "Kerning" ));
		Debug_Info("%s", (kern_table->tables[i].coverage & KERN_CROSS_STREAM ?
		                     " Cross-stream" : "" ));
		Debug_Info("%s\n", (kern_table->tables[i].coverage & KERN_OVERRIDE ?
		                     " Override" : "" ));
#endif

		kern_table->tables[i].kern_pairs = NULL;   /*<==[esp] added*/
		kern_table->tables[i].nPairs = 0;          /*<==[esp] added*/

		if ((kern_table->tables[i].coverage >> 8) == 0)
		{
			/* Can only handle format 0 kerning subtables */
			kern_table->tables[i].nPairs = READUSHORT(ffile->fp);

#ifdef TTF_DEBUG
			Debug_Info("entries in table[%d]: %d\n", i, kern_table->tables[i].nPairs);
#endif

			temp16 = READUSHORT(ffile->fp);     /* searchRange */
			temp16 = READUSHORT(ffile->fp);     /* entrySelector */
			temp16 = READUSHORT(ffile->fp);     /* rangeShift */

			kern_table->tables[i].kern_pairs =
			(KernData *)POV_MALLOC(kern_table->tables[i].nPairs * sizeof(KernData), "Kern Pairs");

			for (j = 0; j < kern_table->tables[i].nPairs; j++)
			{
				/* Read in a kerning pair */
				kern_table->tables[i].kern_pairs[j].left = READUSHORT(ffile->fp);
				kern_table->tables[i].kern_pairs[j].right = READUSHORT(ffile->fp);
				kern_table->tables[i].kern_pairs[j].value = READFWORD(ffile->fp);

#ifdef TTF_DEBUG2
				Debug_Info("Kern pair: <%d,%d> = %d\n",
				           (int)kern_table->tables[i].kern_pairs[j].left,
				           (int)kern_table->tables[i].kern_pairs[j].right,
				           (int)kern_table->tables[i].kern_pairs[j].value);
#endif
			}
		}
		else
		{
#ifdef TTF_DEBUG2
			Warning(0, "Cannot handle format %u kerning data",
			        (kern_table->tables[i].coverage >> 8));
#endif
			/*
			 * seekg to the end of this table, excluding the length of the version,
			 * length, and coverage USHORTs, which we have already read.
			 */
			ffile->fp->seekg((int)(length - 6), POV_SEEK_CUR) ;
			kern_table->tables[i].nPairs = 0;
		}
	}
}

/*
 * This routine determines the total number of horizontal metrics.
 */
void ProcessHheaTable(FontFileInfo *ffile, int hhea_table_offset)
{
#ifdef TTF_DEBUG
	sfnt_HorizHeader horizHeader;

	/* seekg to the hhea table */
	ffile->fp->seekg(hhea_table_offset);

	horizHeader.version = READFIXED(ffile->fp);
	horizHeader.Ascender = READFWORD(ffile->fp);
	horizHeader.Descender = READFWORD(ffile->fp);
	horizHeader.LineGap = READFWORD(ffile->fp);
	horizHeader.advanceWidthMax = READUFWORD(ffile->fp);
	horizHeader.minLeftSideBearing = READFWORD(ffile->fp);
	horizHeader.minRightSideBearing = READFWORD(ffile->fp);
	horizHeader.xMaxExtent = READFWORD(ffile->fp);
	horizHeader.caretSlopeRise = READSHORT(ffile->fp);
	horizHeader.caretSlopeRun = READSHORT(ffile->fp);
	horizHeader.reserved1 = READSHORT(ffile->fp);
	horizHeader.reserved2 = READSHORT(ffile->fp);
	horizHeader.reserved3 = READSHORT(ffile->fp);
	horizHeader.reserved4 = READSHORT(ffile->fp);
	horizHeader.reserved5 = READSHORT(ffile->fp);
	horizHeader.metricDataFormat = READSHORT(ffile->fp);
#else

	/* seekg to the hhea table, skipping all that stuff we don't need */
	ffile->fp->seekg (hhea_table_offset + 34) ;

#endif

	ffile->numberOfHMetrics = READUSHORT(ffile->fp);

#ifdef TTF_DEBUG
	Debug_Info("\nhorizontal header table:\n");
	Debug_Info("Ascender: %d\n",horizHeader.Ascender);
	Debug_Info("Descender: %d\n",horizHeader.Descender);
	Debug_Info("LineGap: %d\n",horizHeader.LineGap);
	Debug_Info("advanceWidthMax: %d\n",horizHeader.advanceWidthMax);
	Debug_Info("minLeftSideBearing: %d\n",horizHeader.minLeftSideBearing);
	Debug_Info("minRightSideBearing: %d\n",horizHeader.minRightSideBearing);
	Debug_Info("xMaxExtent: %d\n",horizHeader.xMaxExtent);
	Debug_Info("caretSlopeRise: %d\n",horizHeader.caretSlopeRise);
	Debug_Info("caretSlopeRun: %d\n",horizHeader.caretSlopeRun);
	Debug_Info("metricDataFormat: %d\n",horizHeader.metricDataFormat);
	Debug_Info("numberOfHMetrics: %d\n",ffile->numberOfHMetrics);
#endif
}

void ProcessHmtxTable (FontFileInfo *ffile, int hmtx_table_offset)
{
	int i;
	longHorMetric *metric;
	uFWord lastAW = 0;     /* Just to quiet warnings. */

	ffile->fp->seekg (hmtx_table_offset) ;

	ffile->hmtx_table = (longHorMetric *)POV_MALLOC(ffile->numGlyphs*sizeof(longHorMetric), "ttf");

	/*
	 * Read in the total glyph width, and the left side offset.  There is
	 * guaranteed to be at least one longHorMetric entry in this table to
	 * set the advanceWidth for the subsequent lsb entries.
	 */
	for (i=0, metric=ffile->hmtx_table; i < ffile->numberOfHMetrics; i++,metric++)
	{
		lastAW = metric->advanceWidth = READUFWORD(ffile->fp);
		metric->lsb = READFWORD(ffile->fp);
	}

	/* Read in the remaining left offsets */
	for (; i < ffile->numGlyphs; i++, metric++)
	{
		metric->advanceWidth = lastAW;
		metric->lsb = READFWORD(ffile->fp);
	}
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessCharacter
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
*   Finds the glyph description for the current character.
*
* CHANGES
*
*   -
*
******************************************************************************/

GlyphPtr ProcessCharacter(FontFileInfo *ffile, unsigned int search_char, unsigned int *glyph_index)
{
	GlyphPtr glyph;

	/* See if we have already processed this glyph */
	for (glyph = ffile->glyphs; glyph != NULL; glyph = glyph->next)
	{
		if (glyph->c == search_char)
		{
			/* Found it, no need to do any more work */
#ifdef TTF_DEBUG
			Debug_Info("Cached glyph: %c/%u\n",(char)search_char,glyph->glyph_index);
#endif
			*glyph_index = glyph->glyph_index;
			return glyph;
		}
	}

	*glyph_index = ProcessCharMap(ffile, search_char);

	if (*glyph_index == 0)
;// TODO MESSAGE    Warning(0, "Character %d (0x%X) not found in %s", (BYTE)search_char,
//            search_char, ffile->filename);

	/* See if we have already processed this glyph (using the glyph index) */
	for (glyph = ffile->glyphs; glyph != NULL; glyph = glyph->next)
	{
		if (glyph->glyph_index == *glyph_index)
		{
			/* Found it, no need to do any more work */
#ifdef TTF_DEBUG
			Debug_Info("Cached glyph: %c/%u\n",(char)search_char,glyph->glyph_index);
#endif
			*glyph_index = glyph->glyph_index;
			return glyph;
		}
	}

	glyph = ExtractGlyphInfo(ffile, *glyph_index, search_char);

	/* Add this glyph to the ones we already know about */

	glyph->next = ffile->glyphs;
	ffile->glyphs = glyph;

	/* Glyph is all built */

	return glyph;
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessCharMap
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
*   Find the character mapping for 'search_char'.  We should really know
*   which character set we are using (ie ISO 8859-1, Mac, Unicode, etc).
*   Search char should really be a USHORT to handle double byte systems.
*
* CHANGES
*
*   961120  esp  Added check to allow Macintosh encodings to pass
*
******************************************************************************/
USHORT ProcessCharMap(FontFileInfo *ffile, unsigned int search_char)
{
	int initial_table_offset;
	int old_table_offset;
	int entry_offset;
	sfnt_platformEntry cmapEntry;
	sfnt_mappingTable encodingTable;
	int i, j, table_count;

	/* Move to the start of the character map, skipping the 2 byte version */
	ffile->fp->seekg (ffile->cmap_table_offset + 2) ;

	table_count = READUSHORT(ffile->fp);

	#ifdef TTF_DEBUG
	Debug_Info("table_count=%d\n", table_count);
	#endif

	/*
	 * Search the tables until we find the glyph index for the search character.
	 * Just return the first one we find...
	 */

	initial_table_offset = ffile->fp->tellg (); /* Save the initial position */

	for(j = 0; j <= 3; j++)
	{
		ffile->fp->seekg(initial_table_offset); /* Always start new search at the initial position */

		for (i = 0; i < table_count; i++)
		{
			cmapEntry.platformID = READUSHORT(ffile->fp);
			cmapEntry.specificID = READUSHORT(ffile->fp);
			cmapEntry.offset     = READULONG(ffile->fp);

			#ifdef TTF_DEBUG
			Debug_Info("cmapEntry: platformID=%d\n", cmapEntry.platformID);
			Debug_Info("cmapEntry: specificID=%d\n", cmapEntry.specificID);
			Debug_Info("cmapEntry: offset=%d\n", cmapEntry.offset);
			#endif

			/*
			 * Check if this is the encoding table we want to use.
			 * The search is done according to user preference.
			 */
			if ( ffile->platformID[j] != cmapEntry.platformID ) /* [JAC 01/99] */
			{
				continue;
			}

			entry_offset = cmapEntry.offset;

			old_table_offset = ffile->fp->tellg (); /* Save the current position */

			ffile->fp->seekg (ffile->cmap_table_offset + entry_offset) ;

			encodingTable.format = READUSHORT(ffile->fp);
			encodingTable.length = READUSHORT(ffile->fp);
			encodingTable.version = READUSHORT(ffile->fp);

			#ifdef TTF_DEBUG
			Debug_Info("Encoding table, format: %u, length: %u, version: %u\n",
			           encodingTable.format, encodingTable.length, encodingTable.version);
			#endif

			if (encodingTable.format == 0)
			{
				/*
				 * Translation is simple - add 'entry_char' to the start of the
				 * table and grab what's there.
				 */
				#ifdef TTF_DEBUG
				Debug_Info("Apple standard index mapping\n");
				#endif

				return(ProcessFormat0Glyph(ffile, search_char));
			}
			#if 0  /* Want to get the rest of these working first */
			else if (encodingTable.format == 2)
			{
				/* Used for multi-byte character encoding (Chinese, Japanese, etc) */
				#ifdef TTF_DEBUG
				Debug_Info("High-byte index mapping\n");
				#endif

				return(ProcessFormat2Glyph(ffile, search_char));
			}
			#endif
			else if (encodingTable.format == 4)
			{
				/* Microsoft UGL encoding */
				#ifdef TTF_DEBUG
				Debug_Info("Microsoft standard index mapping\n");
				#endif

				return(ProcessFormat4Glyph(ffile, search_char));
			}
			else if (encodingTable.format == 6)
			{
				#ifdef TTF_DEBUG
				Debug_Info("Trimmed table mapping\n");
				#endif

				return(ProcessFormat6Glyph(ffile, search_char));
			}
			#ifdef TTF_DEBUG
			else
				Debug_Info("Unsupported TrueType font index mapping format: %u\n",
				           encodingTable.format);
			#endif

			/* Go to the next table entry if we didn't find a match */
			ffile->fp->seekg (old_table_offset) ;
		}
	}

	/*
	 * No character mapping was found - very odd, we should really have had the
	 * character in at least one table.  Perhaps getting here means we didn't
	 * have any character mapping tables.  '0' means no mapping.
	 */

	return 0;
}


/*****************************************************************************
*
* FUNCTION
*
*   ProcessFormat0Glyph
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
* This handles the Apple standard index mapping for glyphs.
* The file pointer must be pointing immediately after the version entry in the
* encoding table for the next two functions to work.
*
* CHANGES
*
*   -
*
******************************************************************************/
USHORT ProcessFormat0Glyph(FontFileInfo *ffile, unsigned int search_char)
{
	BYTE temp_index;

	ffile->fp->seekg ((int)search_char, POV_SEEK_CUR) ;

	if (!ffile->fp->read ((char *)(&temp_index), 1)) /* Each index is 1 byte */
	{
		throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
	}

	return (USHORT)(temp_index);
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessFormat4Glyph
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
* This handles the Microsoft standard index mapping for glyph tables
*
* CHANGES
*
*   Mar 26, 1996: Cache segment info rather than read each time.  [AED]
*
******************************************************************************/
USHORT ProcessFormat4Glyph(FontFileInfo *ffile, unsigned int search_char)
{
	int i;
	unsigned int glyph_index = 0;  /* Set the glyph index to "not present" */

	/*
	 * If this is the first time we are here, read all of the segment headers,
	 * and save them for later calls to this function, rather than seeking and
	 * mallocing for each character
	 */
	if (ffile->segCount == 0)
	{
		USHORT temp16;

		ffile->segCount = READUSHORT(ffile->fp) >> 1;
		ffile->searchRange = READUSHORT(ffile->fp);
		ffile->entrySelector = READUSHORT(ffile->fp);
		ffile->rangeShift = READUSHORT(ffile->fp);

		/* Now allocate and read in the segment arrays */

		ffile->endCount = (USHORT *)POV_MALLOC(ffile->segCount * sizeof(USHORT), "ttf");
		ffile->startCount = (USHORT *)POV_MALLOC(ffile->segCount * sizeof(USHORT), "ttf");
		ffile->idDelta = (USHORT *)POV_MALLOC(ffile->segCount * sizeof(USHORT), "ttf");
		ffile->idRangeOffset = (USHORT *)POV_MALLOC(ffile->segCount * sizeof(USHORT), "ttf");

		for (i = 0; i < ffile->segCount; i++)
		{
			ffile->endCount[i] = READUSHORT(ffile->fp);
		}

		temp16 = READUSHORT(ffile->fp);  /* Skip over 'reservedPad' */

		for (i = 0; i < ffile->segCount; i++)
		{
			ffile->startCount[i] = READUSHORT(ffile->fp);
		}

		for (i = 0; i < ffile->segCount; i++)
		{
			ffile->idDelta[i] = READUSHORT(ffile->fp);
		}

		/* location of start of idRangeOffset */
		ffile->glyphIDoffset = ffile->fp->tellg () ;

		for (i = 0; i < ffile->segCount; i++)
		{
			ffile->idRangeOffset[i] = READUSHORT(ffile->fp);
		}
	}

	/* Search the segments for our character */

glyph_search:
	for (i = 0; i < ffile->segCount; i++)
	{
		if (search_char <= ffile->endCount[i])
		{
			if (search_char >= ffile->startCount[i])
			{
				/* Found correct range for this character */

				if (ffile->idRangeOffset[i] == 0)
				{
					glyph_index = search_char + ffile->idDelta[i];
				}
				else
				{
					/*
					 * Alternate encoding of glyph indices, relies on a quite unusual way
					 * of storing the offsets.  We need the *2s because we are talking
					 * about addresses of shorts and not bytes.
					 *
					 * (glyphIDoffset + i*2 + idRangeOffset[i]) == &idRangeOffset[i]
					 */
					ffile->fp->seekg (ffile->glyphIDoffset + 2*i + ffile->idRangeOffset[i]+
					                 2*(search_char - ffile->startCount[i]));

					glyph_index = READUSHORT(ffile->fp);

					if (glyph_index != 0)
						glyph_index = glyph_index + ffile->idDelta[i];
				}
			}
			break;
		}
	}

	/*
	 * If we haven't found the character yet, and this is the first time to
	 * search the tables, try looking in the Unicode user space, since this
	 * is the location Microsoft recommends for symbol characters like those
	 * in wingdings and dingbats.
	 */
	if (glyph_index == 0 && search_char < 0x100)
	{
		search_char += 0xF000;
#ifdef TTF_DEBUG
		Debug_Info("Looking for glyph in Unicode user space (0x%X)\n", search_char);
#endif
		goto glyph_search;
	}

	/* Deallocate the memory we used for the segment arrays */

	return glyph_index;
}

/*****************************************************************************
*
* FUNCTION
*
*   ProcessFormat6Glyph
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
*  This handles the trimmed table mapping for glyphs.
*
* CHANGES
*
*   -
*
******************************************************************************/
USHORT ProcessFormat6Glyph(FontFileInfo *ffile, unsigned int search_char)
{
	USHORT firstCode, entryCount;
	USHORT glyph_index;

	firstCode = READUSHORT(ffile->fp);
	entryCount = READUSHORT(ffile->fp);

	if (search_char >= firstCode && search_char < firstCode + entryCount)
	{
		ffile->fp->seekg (((int)(search_char - firstCode))*2, POV_SEEK_CUR) ;
		glyph_index = READUSHORT(ffile->fp);
	}
	else
		glyph_index = 0;

	return glyph_index;
}


/*****************************************************************************
*
* FUNCTION
*
*   ExtractGlyphInfo
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
*   Change TTF outline information for the glyph(s) into a useful format
*
* CHANGES
*
*   -
*
******************************************************************************/
GlyphPtr ExtractGlyphInfo(FontFileInfo *ffile, unsigned int glyph_index, unsigned int c)
{
	GlyphOutline *ttglyph;
	GlyphPtr glyph;

	ttglyph = ExtractGlyphOutline(ffile, glyph_index, c);

	/*
	 * Convert the glyph outline information from TrueType layout into a more
	 * easily processed format
	 */

	glyph = ConvertOutlineToGlyph(ffile, ttglyph);
	glyph->c = c;
	glyph->glyph_index = glyph_index;
	glyph->myMetrics = ttglyph->myMetrics;

	/* Free up outline information */

	if (ttglyph)
	{
		if (ttglyph->y) POV_FREE(ttglyph->y);
		if (ttglyph->x) POV_FREE(ttglyph->x);
		if (ttglyph->endPoints) POV_FREE(ttglyph->endPoints);
		if (ttglyph->flags) POV_FREE(ttglyph->flags);

		POV_FREE(ttglyph);
	}

#ifdef TTF_DEBUG3
	int i, j;

	Debug_Info("// Character '%c'\n", (char)c);

	for(i = 0; i < (int)glyph->header.numContours; i++)
	{
		Debug_Info("BYTE gGlypthFlags_%c_%d[] = \n", (char)c, i);
		Debug_Info("{");
		for(j = 0; j <= (int)glyph->contours[i].count; j++)
		{
			if((j % 10) == 0)
				Debug_Info("\n\t");
			Debug_Info("0x%x, ", (unsigned int)glyph->contours[i].flags[j]);
		}
		Debug_Info("\n};\n\n");

		Debug_Info("DBL gGlypthX_%c_%d[] = \n", (char)c, i);
		Debug_Info("{");
		for(j = 0; j <= (int)glyph->contours[i].count; j++)
		{
			if((j % 10) == 0)
				Debug_Info("\n\t");
			Debug_Info("%f, ", (DBL)glyph->contours[i].x[j]);
		}
		Debug_Info("\n};\n\n");

		Debug_Info("DBL gGlypthY_%c_%d[] = \n", (char)c, i);
		Debug_Info("{");
		for(j = 0; j <= (int)glyph->contours[i].count; j++)
		{
			if((j % 10) == 0)
				Debug_Info("\n\t");
			Debug_Info("%f, ", (DBL)glyph->contours[i].y[j]);
		}
		Debug_Info("\n};\n\n");
	}

	Debug_Info("Contour gGlypthContour_%c[] = \n", (char)c);
	Debug_Info("{\n");
	for(i = 0; i < glyph->header.numContours; i++)
	{
		Debug_Info("\t{\n");
		Debug_Info("\t\t%u, // inside_flag \n", (unsigned int)glyph->contours[i].inside_flag);
		Debug_Info("\t\t%u, // count \n", (unsigned int)glyph->contours[i].count);
		Debug_Info("\t\tgGlypthFlags_%c_%d, // flags[]\n", (char)c, i);
		Debug_Info("\t\tgGlypthX_%c_%d, // x[]\n", (char)c, i);
		Debug_Info("\t\tgGlypthY_%c_%d // y[]\n", (char)c, i);
		Debug_Info("\t},\n");
	}
	Debug_Info("\n};\n\n");

	Debug_Info("Glyph gGlypth_%c = \n", (char)c);
	Debug_Info("{\n");
	Debug_Info("\t{ // header\n");
	Debug_Info("\t\t%u, // header.numContours \n", (unsigned int)glyph->header.numContours);
	Debug_Info("\t\t%f, // header.xMin\n", (DBL)glyph->header.xMin);
	Debug_Info("\t\t%f, // header.yMin\n", (DBL)glyph->header.yMin);
	Debug_Info("\t\t%f, // header.xMax\n", (DBL)glyph->header.xMax);
	Debug_Info("\t\t%f // header.yMax\n", (DBL)glyph->header.yMax);
	Debug_Info("\t},\n");
	Debug_Info("\t%u, // glyph_index\n", (unsigned int)glyph->glyph_index);
	Debug_Info("\tgGlypthContour_%c, // contours[]\n", (char)c);
	Debug_Info("\t%u, // unitsPerEm\n", (unsigned int)glyph->unitsPerEm);
	Debug_Info("\tNULL, // next\n");
	Debug_Info("\t%u, // c\n", (unsigned int)glyph->c);
	Debug_Info("\t%u // myMetrics\n", (unsigned int)glyph->myMetrics);

	Debug_Info("};\n\n");
#endif

	return glyph;
}



/*****************************************************************************
*
* FUNCTION
*
*   ExtractGlyphOutline
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
*   Read the contour information for a specific glyph.  This has to be a
*   separate routine from ExtractGlyphInfo because we call it recurisvely
*   for multiple component glyphs.
*
* CHANGES
*
*   -
*
******************************************************************************/
GlyphOutline *ExtractGlyphOutline(FontFileInfo *ffile, unsigned int glyph_index, unsigned int c)
{
	int i;
	USHORT n;
	SHORT nc;
	GlyphOutline *ttglyph;

	ttglyph = (GlyphOutline *)POV_CALLOC(1, sizeof(GlyphOutline), "ttf");
	ttglyph->myMetrics = glyph_index;

	/* Have to treat space characters differently */
	if (c != ' ')
	{
		ffile->fp->seekg (ffile->glyf_table_offset+ffile->loca_table[glyph_index]);

		ttglyph->header.numContours = READSHORT(ffile->fp);
		ttglyph->header.xMin = READFWORD(ffile->fp);   /* These may be  */
		ttglyph->header.yMin = READFWORD(ffile->fp);   /* unreliable in */
		ttglyph->header.xMax = READFWORD(ffile->fp);   /* some fonts.   */
		ttglyph->header.yMax = READFWORD(ffile->fp);
	}

#ifdef TTF_DEBUG
	Debug_Info("ttglyph->header:\n");
	Debug_Info("glyph_index=%d\n", glyph_index);
	Debug_Info("loca_table[%d]=%d\n",glyph_index,ffile->loca_table[glyph_index]);
	Debug_Info("numContours=%d\n", (int)ttglyph->header.numContours);
#endif

	nc = ttglyph->header.numContours;

	/*
	 * A positive number of contours means a regular glyph, with possibly
	 * several separate line segments making up the outline.
	 */
	if (nc > 0)
	{
		FWord coord;
		BYTE flag, repeat_count;
		USHORT temp16;

		/* Grab the contour endpoints */

		ttglyph->endPoints = (USHORT *)POV_MALLOC(nc * sizeof(USHORT), "ttf");

		for (i = 0; i < nc; i++)
		{
			ttglyph->endPoints[i] = READUSHORT(ffile->fp);
#ifdef TTF_DEBUG
			Debug_Info("endPoints[%d]=%d\n", i, ttglyph->endPoints[i]);
#endif
		}

		/* Skip over the instructions */
		temp16 = READUSHORT(ffile->fp);
		ffile->fp->seekg (temp16, POV_SEEK_CUR);
#ifdef TTF_DEBUG
		Debug_Info("skipping instruction bytes: %d\n", temp16);
#endif

		/* Determine the number of points making up this glyph */

		n = ttglyph->numPoints = ttglyph->endPoints[nc - 1] + 1;
#ifdef TTF_DEBUG
		Debug_Info("numPoints=%d\n", ttglyph->numPoints);
#endif

		/* Read the flags */

		ttglyph->flags = (BYTE *)POV_MALLOC(n * sizeof(BYTE), "ttf");

		for (i = 0; i < ttglyph->numPoints; i++)
		{
			if (!ffile->fp->read((char *)(&ttglyph->flags[i]), sizeof(BYTE)))
			{
				throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
			}

			if (ttglyph->flags[i] & REPEAT_FLAGS)
			{
				if (!ffile->fp->read((char *)(&repeat_count), sizeof(BYTE)))
				{
					throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
				}
				for (; repeat_count > 0; repeat_count--, i++)
				{
#ifdef TTF_DEBUG
					if (i>=n)
					{
						Debug_Info("readflags ERROR: i >= n (%d > %d)\n", i, n);
					}
#endif
					if (i<n)      /* hack around a bug that is trying to write too many flags */
						ttglyph->flags[i + 1] = ttglyph->flags[i];
				}
			}
		}
#ifdef  TTF_DEBUG
		Debug_Info("flags:");
		for (i=0; i<n; i++)
			Debug_Info(" %02x", ttglyph->flags[i]);
		Debug_Info("\n");
#endif
		/* Read the coordinate vectors */

		ttglyph->x = (DBL *)POV_MALLOC(n * sizeof(DBL), "ttf");
		ttglyph->y = (DBL *)POV_MALLOC(n * sizeof(DBL), "ttf");

		coord = 0;

		for (i = 0; i < ttglyph->numPoints; i++)
		{
			/* Read each x coordinate */

			flag = ttglyph->flags[i];

			if (flag & XSHORT)
			{
				BYTE temp8;

				if (!ffile->fp->read((char *)(&temp8), 1))
				{
					throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
				}

				if (flag & SHORT_X_IS_POS)
					coord += temp8;
				else
					coord -= temp8;
			}
			else if (!(flag & NEXT_X_IS_ZERO))
			{
				coord += READSHORT(ffile->fp);
			}

			/* Find our own maximum and minimum x coordinates */
			if (coord > ttglyph->header.xMax)
				ttglyph->header.xMax = coord;
			if (coord < ttglyph->header.xMin)
				ttglyph->header.xMin = coord;

			ttglyph->x[i] = (DBL)coord / (DBL)ffile->unitsPerEm;
		}

		coord = 0;

		for (i = 0; i < ttglyph->numPoints; i++)
		{
			/* Read each y coordinate */

			flag = ttglyph->flags[i];

			if (flag & YSHORT)
			{
				BYTE temp8;

				if (!ffile->fp->read((char *)(&temp8), 1))
				{
					throw POV_EXCEPTION(kFileDataErr, "Cannot read TrueType font file.");
				}

				if (flag & SHORT_Y_IS_POS)
					coord += temp8;
				else
					coord -= temp8;
			}
			else if (!(flag & NEXT_Y_IS_ZERO))
			{
				coord += READSHORT(ffile->fp);
			}

			/* Find out our own maximum and minimum y coordinates */
			if (coord > ttglyph->header.yMax)
				ttglyph->header.yMax = coord;
			if (coord < ttglyph->header.yMin)
				ttglyph->header.yMin = coord;

			ttglyph->y[i] = (DBL)coord / (DBL)ffile->unitsPerEm;
		}
	}
	/*
	 * A negative number for numContours means that this glyph is
	 * made up of several separate glyphs.
	 */
	else if (nc < 0)
	{
		USHORT flags;

		ttglyph->header.numContours = 0;
		ttglyph->numPoints = 0;

		do
		{
			GlyphOutline *sub_ttglyph;
			unsigned int sub_glyph_index;
			int   current_pos;
			SHORT arg1, arg2;
			DBL xoff = 0, yoff = 0;
			DBL xscale = 1, yscale = 1;
			DBL scale01 = 0, scale10 = 0;
			USHORT n2;
			SHORT nc2;

			flags = READUSHORT(ffile->fp);
			sub_glyph_index = READUSHORT(ffile->fp);

#ifdef TTF_DEBUG
			Debug_Info("sub_glyph %d: ", sub_glyph_index);
#endif

			if (flags & ARG_1_AND_2_ARE_WORDS)
			{
#ifdef TTF_DEBUG
				Debug_Info("ARG_1_AND_2_ARE_WORDS ");
#endif
				arg1 = READSHORT(ffile->fp);
				arg2 = READSHORT(ffile->fp);
			}
			else
			{
				arg1 = READUSHORT(ffile->fp);
				arg2 = arg1 & 0xFF;
				arg1 = (arg1 >> 8) & 0xFF;
			}

#ifdef TTF_DEBUG
			if (flags & ROUND_XY_TO_GRID)
			{
				Debug_Info("ROUND_XY_TO_GRID ");
			}

			if (flags & MORE_COMPONENTS)
			{
				Debug_Info("MORE_COMPONENTS ");
			}
#endif

			if (flags & WE_HAVE_A_SCALE)
			{
				xscale = yscale = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
				Debug_Info("WE_HAVE_A_SCALE ");
				Debug_Info("xscale = %lf\t", xscale);
				Debug_Info("scale01 = %lf\n", scale01);
				Debug_Info("scale10 = %lf\t", scale10);
				Debug_Info("yscale = %lf\n", yscale);
#endif
			}
			else if (flags & WE_HAVE_AN_X_AND_Y_SCALE)
			{
				xscale = (DBL)READSHORT(ffile->fp)/0x4000;
				yscale = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
				Debug_Info("WE_HAVE_AN_X_AND_Y_SCALE ");
				Debug_Info("xscale = %lf\t", xscale);
				Debug_Info("scale01 = %lf\n", scale01);
				Debug_Info("scale10 = %lf\t", scale10);
				Debug_Info("yscale = %lf\n", yscale);
#endif
			}
			else if (flags & WE_HAVE_A_TWO_BY_TWO)
			{
				xscale  = (DBL)READSHORT(ffile->fp)/0x4000;
				scale01 = (DBL)READSHORT(ffile->fp)/0x4000;
				scale10 = (DBL)READSHORT(ffile->fp)/0x4000;
				yscale  = (DBL)READSHORT(ffile->fp)/0x4000;
#ifdef TTF_DEBUG
				Debug_Info("WE_HAVE_A_TWO_BY_TWO ");
				Debug_Info("xscale = %lf\t", xscale);
				Debug_Info("scale01 = %lf\n", scale01);
				Debug_Info("scale10 = %lf\t", scale10);
				Debug_Info("yscale = %lf\n", yscale);
#endif
			}

			if (flags & ARGS_ARE_XY_VALUES)
			{
				xoff = (DBL)arg1 / ffile->unitsPerEm;
				yoff = (DBL)arg2 / ffile->unitsPerEm;

#ifdef TTF_DEBUG
				Debug_Info("ARGS_ARE_XY_VALUES ");
				Debug_Info("\narg1 = %d  xoff = %lf\t", arg1, xoff);
				Debug_Info("arg2 = %d  yoff = %lf\n", arg2, yoff);
#endif
			}
			else  /* until I understand how this method works... */
			{
// TODO MESSAGE        Warning(0, "Cannot handle part of glyph %d (0x%X).", c, c);
				continue;
			}

			if (flags & USE_MY_METRICS)
			{
#ifdef TTF_DEBUG
				Debug_Info("USE_MY_METRICS ");
#endif
				ttglyph->myMetrics = sub_glyph_index;
			}

			current_pos = ffile->fp->tellg () ;
			sub_ttglyph = ExtractGlyphOutline(ffile, sub_glyph_index, c);
			ffile->fp->seekg (current_pos) ;

			if ((nc2 = sub_ttglyph->header.numContours) == 0)
				continue;

			nc = ttglyph->header.numContours;
			n = ttglyph->numPoints;
			n2 = sub_ttglyph->numPoints;

			ttglyph->endPoints = (USHORT *)POV_REALLOC(ttglyph->endPoints,
			                                 (nc + nc2) * sizeof(USHORT), "ttf");
			ttglyph->flags = (BYTE *)POV_REALLOC(ttglyph->flags, (n+n2)*sizeof(BYTE), "ttf");
			ttglyph->x = (DBL *)POV_REALLOC(ttglyph->x, (n + n2) * sizeof(DBL), "ttf");
			ttglyph->y = (DBL *)POV_REALLOC(ttglyph->y, (n + n2) * sizeof(DBL), "ttf");

			/* Add the sub glyph info to the end of the current glyph */

			ttglyph->header.numContours += nc2;
			ttglyph->numPoints += n2;

			for (i = 0; i < nc2; i++)
			{
				ttglyph->endPoints[i + nc] = sub_ttglyph->endPoints[i] + n;
#ifdef TTF_DEBUG
				Debug_Info("endPoints[%d]=%d\n", i + nc, ttglyph->endPoints[i + nc]);
#endif
			}

			for (i = 0; i < n2; i++)
			{
#ifdef TTF_DEBUG
				Debug_Info("x[%d]=%lf\t", i, sub_ttglyph->x[i]);
				Debug_Info("y[%d]=%lf\n", i, sub_ttglyph->y[i]);
#endif
				ttglyph->flags[i + n] = sub_ttglyph->flags[i];
				ttglyph->x[i + n] = xscale * sub_ttglyph->x[i] +
				                    scale01 * sub_ttglyph->y[i] + xoff;
				ttglyph->y[i + n] = scale10 * sub_ttglyph->x[i] +
				                    yscale * sub_ttglyph->y[i] + yoff;

#ifdef TTF_DEBUG
				Debug_Info("x[%d]=%lf\t", i+n, ttglyph->x[i+n]);
				Debug_Info("y[%d]=%lf\n", i+n, ttglyph->y[i+n]);
#endif

				if (ttglyph->x[i + n] < ttglyph->header.xMin)
					ttglyph->header.xMin = ttglyph->x[i + n];

				if (ttglyph->x[i + n] > ttglyph->header.xMax)
					ttglyph->header.xMax = ttglyph->x[i + n];

				if (ttglyph->y[i + n] < ttglyph->header.yMin)
					ttglyph->header.yMin = ttglyph->y[i + n];

				if (ttglyph->y[i + n] > ttglyph->header.yMax)
					ttglyph->header.yMax = ttglyph->y[i + n];
			}

			/* Free up the sub glyph outline information */

			if (sub_ttglyph->y) POV_FREE(sub_ttglyph->y);
			if (sub_ttglyph->x) POV_FREE(sub_ttglyph->x);
			if (sub_ttglyph->endPoints) POV_FREE(sub_ttglyph->endPoints);
			if (sub_ttglyph->flags) POV_FREE(sub_ttglyph->flags);

			POV_FREE(sub_ttglyph);
		} while (flags & MORE_COMPONENTS);
	}

#ifdef TTF_DEBUG
		Debug_Info("xMin=%d\n",ttglyph->header.xMin);
		Debug_Info("yMin=%d\n",ttglyph->header.yMin);
		Debug_Info("xMax=%d\n",ttglyph->header.xMax);
		Debug_Info("yMax=%d\n",ttglyph->header.yMax);
#endif

	return ttglyph;
}



/*****************************************************************************
*
* FUNCTION
*
*   ConvertOutlineToGlyph
*
* INPUT
*   
* OUTPUT
*   
* RETURNS
*   
* AUTHOR
*
*   POV-Ray Team
*   
* DESCRIPTION
*
* Transform a glyph from TrueType storage format to something a little easier
* to manage.
*
* CHANGES
*
*   -
*
******************************************************************************/
GlyphPtr ConvertOutlineToGlyph(FontFileInfo *ffile, const GlyphOutline *ttglyph)
{
	GlyphPtr glyph;
	DBL *temp_x, *temp_y;
	BYTE *temp_f;
	USHORT i, j, last_j;

	/* Create storage for this glyph */

	glyph = (Glyph *)POV_MALLOC(sizeof(Glyph), "ttf");
	if (ttglyph->header.numContours > 0)
	{
		glyph->contours = (Contour *)POV_MALLOC(ttglyph->header.numContours * sizeof(Contour), "ttf");
	}
	else
	{
		glyph->contours = NULL;
	}

	/* Copy sizing information about this glyph */

	POV_MEMCPY(&glyph->header, &ttglyph->header, sizeof(GlyphHeader));

	/* Keep track of the size for this glyph */

	glyph->unitsPerEm = ffile->unitsPerEm;

	/* Now copy the vertex information into the contours */

	for (i = 0, last_j = 0; i < (USHORT) ttglyph->header.numContours; i++)
	{
		/* Figure out number of points in contour */

		j = ttglyph->endPoints[i] - last_j + 1;

		/* Copy the coordinate information into the glyph */

		temp_x = (DBL *)POV_MALLOC((j + 1) * sizeof(DBL), "ttf");
		temp_y = (DBL *)POV_MALLOC((j + 1) * sizeof(DBL), "ttf");

		temp_f = (BYTE *)POV_MALLOC((j + 1) * sizeof(BYTE), "ttf");
		POV_MEMCPY(temp_x, &ttglyph->x[last_j], j * sizeof(DBL));
		POV_MEMCPY(temp_y, &ttglyph->y[last_j], j * sizeof(DBL));

		POV_MEMCPY(temp_f, &ttglyph->flags[last_j], j * sizeof(BYTE));
		temp_x[j] = ttglyph->x[last_j];
		temp_y[j] = ttglyph->y[last_j];
		temp_f[j] = ttglyph->flags[last_j];

		/* Figure out if this is an inside or outside contour */

		glyph->contours[i].inside_flag = 0;

		/* Plug in the reset of the contour components into the glyph */

		glyph->contours[i].count = j;
		glyph->contours[i].x = temp_x;
		glyph->contours[i].y = temp_y;
		glyph->contours[i].flags = temp_f;

		/*
		 * Set last_j to point to the beginning of the next contour's coordinate
		 * information
		 */

		last_j = ttglyph->endPoints[i] + 1;
	}

	/* Show statistics about this glyph */

#ifdef TTF_DEBUG
	Debug_Info("Number of contours: %u\n", glyph->header.numContours);
	Debug_Info("X extent: [%f, %f]\n",
		(DBL)glyph->header.xMin / (DBL)ffile->unitsPerEm,
		(DBL)glyph->header.xMax / (DBL)ffile->unitsPerEm);

	Debug_Info("Y extent: [%f, %f]\n",
		(DBL)glyph->header.yMin / (DBL)ffile->unitsPerEm,
		(DBL)glyph->header.yMax / (DBL)ffile->unitsPerEm);

	Debug_Info("Converted coord list(%d):\n", (int)glyph->header.numContours);

	for (i=0;i<(USHORT)glyph->header.numContours;i++)
	{
		for (j=0;j<=glyph->contours[i].count;j++)
			Debug_Info("  %c[%f, %f]\n",
				(glyph->contours[i].flags[j] & ONCURVE ? '*' : ' '),
				glyph->contours[i].x[j], glyph->contours[i].y[j]);
		Debug_Info("\n");
	}
#endif

	return glyph;
}

/* Test to see if "point" is inside the splined polygon "points". */
bool TrueType::Inside_Glyph(double x, double y, const GlyphStruct* glyph) const
{
	int i, j, k, n, n1, crossings;
	int qi, ri, qj, rj;
	Contour *contour;
	double xt[3], yt[3], roots[2];
	DBL *xv, *yv;
	double x0, x1, x2, t;
	double y0, y1, y2;
	double m, b, xc;
	BYTE *fv;

	crossings = 0;

	n = glyph->header.numContours;

	contour = glyph->contours;

	for (i = 0; i < n; i++)
	{
		xv = contour[i].x;
		yv = contour[i].y;
		fv = contour[i].flags;
		x0 = xv[0];
		y0 = yv[0];
		n1 = contour[i].count;

		for (j = 1; j <= n1; j++)
		{
			x1 = xv[j];
			y1 = yv[j];

			if (fv[j] & ONCURVE)
			{
				/* Straight line - first set up for the next */
				/* Now do the crossing test */

				qi = ri = qj = rj = 0;

				if (y0 == y1)
					goto end_line_test;

				/* if (fabs((y - y0) / (y1 - y0)) < EPSILON) goto end_line_test; */

				if (y0 < y)
					qi = 1;

				if (y1 < y)
					qj = 1;

				if (qi == qj)
					goto end_line_test;

				if (x0 > x)
					ri = 1;

				if (x1 > x)
					rj = 1;

				if (ri & rj)
				{
					crossings++;
					goto end_line_test;
				}

				if ((ri | rj) == 0)
					goto end_line_test;

				m = (y1 - y0) / (x1 - x0);
				b = (y1 - y) - m * (x1 - x);

				if ((b / m) < EPSILON)
				{
					crossings++;
				}

			end_line_test:
				x0 = x1;
				y0 = y1;
			}
			else
			{
				if (j == n1)
				{
					x2 = xv[0];
					y2 = yv[0];
				}
				else
				{
					x2 = xv[j + 1];
					y2 = yv[j + 1];

					if (!(fv[j + 1] & ONCURVE))
					{
						/*
						 * Parabola with far end floating - readjust the far end so that it
						 * is on the curve.
						 */

						x2 = 0.5 * (x1 + x2);
						y2 = 0.5 * (y1 + y2);
					}
				}

				/* only test crossing when y is in the range */
				/* this should also help saving some computations */
				if (((y0 < y) && (y1 < y) && (y2 < y)) ||
				    ((y0 > y) && (y1 > y) && (y2 > y)))
					goto end_curve_test;

				yt[0] = y0 - 2.0 * y1 + y2;
				yt[1] = 2.0 * (y1 - y0);
				yt[2] = y0 - y;

				k = solve_quad(yt, roots, 0.0, 1.0);

				for (ri = 0; ri < k;) {
					if (roots[ri] <= EPSILON) {
						/* if y actually is not in range, discard the root */
						if (((y <= y0) && (y < y1)) || ((y >= y0) && (y > y1))) {
							k--;
							if (k > ri)
								roots[ri] = roots[ri+1];
							continue;
						}
					}
					else if (roots[ri] >= (1.0 - EPSILON)) {
						/* if y actually is not in range, discard the root */
						if (((y < y2) && (y < y1)) || ((y > y2) && (y > y1))) {
							k--;
							if (k > ri)
								roots[ri] = roots[ri+1];
							continue;
						}
					}

					ri++;
				}

				if (k > 0)
				{
					xt[0] = x0 - 2.0 * x1 + x2;
					xt[1] = 2.0 * (x1 - x0);
					xt[2] = x0;

					t = roots[0];

					xc = (xt[0] * t + xt[1]) * t + xt[2];

					if (xc > x)
						crossings++;

					if (k > 1)
					{
						t = roots[1];
						xc = (xt[0] * t + xt[1]) * t + xt[2];

						if (xc > x)
							crossings++;
					}
				}

end_curve_test:

				x0 = x2;

				y0 = y2;
			}
		}
	}

	return ((crossings & 1) != 0);
}


int TrueType::solve_quad(double *x, double *y, double mindist, DBL maxdist) const
{
	double d, t, a, b, c, q;

	a = x[0];
	b = -x[1];
	c = x[2];

	if (fabs(a) < COEFF_LIMIT)
	{
		if (fabs(b) < COEFF_LIMIT)
			return 0;

		q = c / b;

		if (q >= mindist && q <= maxdist)
		{
			y[0] = q;
			return 1;
		}
		else
			return 0;
	}

	d = b * b - 4.0 * a * c;

	if (d < EPSILON)
		return 0;

	d = sqrt(d);
	t = 2.0 * a;
	q = (b + d) / t;

	if (q >= mindist && q <= maxdist)
	{
		y[0] = q;
		q = (b - d) / t;

		if (q >= mindist && q <= maxdist)
		{
			y[1] = q;
			return 2;
		}

		return 1;
	}

	q = (b - d) / t;

	if (q >= mindist && q <= maxdist)
	{
		y[0] = q;
		return 1;
	}

	return 0;
}

/*
 * Returns the distance to z = 0 in t0, and the distance to z = 1 in t1.
 * These distances are to the the bottom and top surfaces of the glyph.
 * The distances are set to -1 if there is no hit.
 */
void TrueType::GetZeroOneHits(const GlyphStruct* glyph, const VECTOR P, const VECTOR D, DBL glyph_depth, double *t0, double *t1) const
{
	double x0, y0, t;

	*t0 = -1.0;
	*t1 = -1.0;

	/* Are we parallel to the x-y plane? */

	if (fabs(D[Z]) < EPSILON)
		return;

	/* Solve: P[Y] + t * D[Y] = 0 */

	t = -P[Z] / D[Z];

	x0 = P[X] + t * D[X];
	y0 = P[Y] + t * D[Y];

	if (Inside_Glyph(x0, y0, glyph))
		*t0 = t;

	/* Solve: P[Y] + t * D[Y] = glyph_depth */

	t += (glyph_depth / D[Z]);

	x0 = P[X] + t * D[X];
	y0 = P[Y] + t * D[Y];

	if (Inside_Glyph(x0, y0, glyph))
		*t1 = t;
}

/*
 * Solving for a linear sweep of a non-linear curve can be performed by
 * projecting the ray onto the x-y plane, giving a parametric equation for the
 * ray as:
 * 
 * x = x0 + x1 t, y = y0 + y1 t
 * 
 * Eliminating t from the above gives the implicit equation:
 * 
 * y1 x - x1 y - (x0 y1 - y0 x1) = 0.
 * 
 * Substituting a parametric equation for x and y gives:
 * 
 * y1 x(s) - x1 y(s) - (x0 y1 - y0 x1) = 0.
 * 
 * which can be written as
 * 
 * a x(s) + b y(s) + c = 0,
 * 
 * where a = y1, b = -x1, c = (y0 x1 - x0 y1).
 * 
 * For piecewise quadratics, the parametric equations will have the forms:
 * 
 * x(s) = (1-s)^2 P0(x) + 2 s (1 - s) P1(x) + s^2 P2(x) y(s) = (1-s)^2 P0(y) + 2 s
 * (1 - s) P1(y) + s^2 P2(y)
 * 
 * where P0 is the first defining vertex of the spline, P1 is the second, P2 is
 * the third.  Using the substitutions:
 * 
 * xt2 = x0 - 2 x1 + x2, xt1 = 2 * (x1 - x0), xt0 = x0; yt2 = y0 - 2 y1 + y2, yt1
 * = 2 * (y1 - y0), yt0 = y0;
 * 
 * the equations can be written as:
 * 
 * x(s) = xt2 s^2 + xt1 s + xt0, y(s) = yt2 s^2 + yt1 s + yt0.
 * 
 * Substituting and multiplying out gives the following equation in s:
 * 
 * s^2 * (a*xt2 + b*yt2) + s   * (a*xt1 + b*yt1) + c + a*xt0 + b*yt0
 * 
 * This is then solved using the quadratic formula.  Any solutions of s that are
 * between 0 and 1 (inclusive) are valid solutions.
 */
bool TrueType::GlyphIntersect(const VECTOR P, const VECTOR D, const GlyphStruct* glyph, DBL glyph_depth, const Ray& ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
	Contour *contour;
	int i, j, k, l, n, m;
	bool Flag = false;
	VECTOR N, IPoint;
	DBL Depth;
	double x0, x1, y0, y1, x2, y2, t, t0, t1, z;
	double xt0, xt1, xt2, yt0, yt1, yt2;
	double a, b, c, d0, d1, C[3], S[2];
	DBL *xv, *yv;
	BYTE *fv;
	int dirflag = 0;

	/*
	 * First thing to do is to get any hits at z = 0 and z = 1 (which are the
	 * bottom and top surfaces of the glyph.
	 */

	GetZeroOneHits(glyph, P, D, glyph_depth, &t0, &t1);

	if (t0 > 0.0)
	{
		Depth = t0 /* / len */;
		VScale(IPoint, ray.Direction, Depth);
		VAddEq(IPoint, ray.Origin);

		if (Depth > TTF_Tolerance && (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread)))
		{
			Make_Vector(N, 0.0, 0.0, -1.0);
			MTransNormal(N, N, Trans);
			VNormalize(N, N);
			Depth_Stack->push(Intersection(Depth, IPoint, N, this));
			Flag = true;
		}
	}

	if (t1 > 0.0)
	{
		Depth = t1 /* / len */;
		VScale(IPoint, ray.Direction, Depth);
		VAddEq(IPoint, ray.Origin);

		if (Depth > TTF_Tolerance && (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread)))
		{
			Make_Vector(N, 0.0, 0.0, 1.0);
			MTransNormal(N, N, Trans);
			VNormalize(N, N);
			Depth_Stack->push(Intersection(Depth, IPoint, N, this));
			Flag = true;
		}
	}

	/* Simple test to see if we can just toss this ray */

	if (fabs(D[X]) < EPSILON)
	{
		if (fabs(D[Y]) < EPSILON)
		{
			/*
			 * This means the ray is moving parallel to the walls of the sweep
			 * surface
			 */
			return Flag;
		}
		else
		{
			dirflag = 0;
		}
	}
	else
	{
		dirflag = 1;
	}

	/*
	 * Now walk through the glyph, looking for places where the ray hits the
	 * walls
	 */

	a = D[Y];
	b = -D[X];
	c = (P[Y] * D[X] - P[X] * D[Y]);

	n = glyph->header.numContours;

	for (i = 0, contour = glyph->contours; i < n; i++, contour++)
	{
		xv = contour->x;
		yv = contour->y;
		fv = contour->flags;
		x0 = xv[0];
		y0 = yv[0];
		m = contour->count;

		for (j = 1; j <= m; j++)
		{
			x1 = xv[j];
			y1 = yv[j];

			if (fv[j] & ONCURVE)
			{
				/* Straight line */
				d0 = (x1 - x0);
				d1 = (y1 - y0);

				t0 = d1 * D[X] - d0 * D[Y];

				if (fabs(t0) < EPSILON)
					/* No possible intersection */
					goto end_line_test;

				t = (D[X] * (P[Y] - y0) - D[Y] * (P[X] - x0)) / t0;

				if (t < 0.0 || t > 1.0)
					goto end_line_test;

				if (dirflag)
					t = ((x0 + t * d0) - P[X]) / D[X];
				else
					t = ((y0 + t * d1) - P[Y]) / D[Y];

				z = P[Z] + t * D[Z];

				Depth = t /* / len */;

				if (z >= 0 && z <= glyph_depth && Depth > TTF_Tolerance)
				{
					VScale(IPoint, ray.Direction, Depth);
					VAddEq(IPoint, ray.Origin);

					if (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread))
					{
						Make_Vector(N, d1, -d0, 0.0);
						MTransNormal(N, N, Trans);
						VNormalize(N, N);
						Depth_Stack->push(Intersection(Depth, IPoint, N, this));
						Flag = true;
					}
				}
			end_line_test:
				x0 = x1;
				y0 = y1;
			}
			else
			{
				if (j == m)
				{
					x2 = xv[0];
					y2 = yv[0];
				}
				else
				{
					x2 = xv[j + 1];
					y2 = yv[j + 1];

					if (!(fv[j + 1] & ONCURVE))
					{

						/*
						 * Parabola with far end DBLing - readjust the far end so that it
						 * is on the curve.  (In the correct place too.)
						 */

						x2 = 0.5 * (x1 + x2);
						y2 = 0.5 * (y1 + y2);
					}
				}

				/* Make the interpolating quadrics */

				xt2 = x0 - 2.0 * x1 + x2;
				xt1 = 2.0 * (x1 - x0);
				xt0 = x0;
				yt2 = y0 - 2.0 * y1 + y2;
				yt1 = 2.0 * (y1 - y0);
				yt0 = y0;

				C[0] = a * xt2 + b * yt2;
				C[1] = a * xt1 + b * yt1;
				C[2] = a * xt0 + b * yt0 + c;

				k = solve_quad(C, S, 0.0, 1.0);

				for (l = 0; l < k; l++)
				{
					if (dirflag)
						t = ((S[l] * S[l] * xt2 + S[l] * xt1 + xt0) - P[X]) / D[X];
					else
						t = ((S[l] * S[l] * yt2 + S[l] * yt1 + yt0) - P[Y]) / D[Y];

					/*
					 * If the intersection with this wall is between 0 and glyph_depth
					 * along the z-axis, then it is a valid hit.
					 */

					z = P[Z] + t * D[Z];

					Depth = t /* / len */;

					if (z >= 0 && z <= glyph_depth && Depth > TTF_Tolerance)
					{
						VScale(IPoint, ray.Direction, Depth);
						VAddEq(IPoint, ray.Origin);

						if (Clip.empty() || Point_In_Clip(IPoint, Clip, Thread))
						{
							Make_Vector(N, 2.0 * yt2 * S[l] + yt1, -2.0 * xt2 * S[l] - xt1, 0.0);
							MTransNormal(N, N, Trans);
							VNormalize(N, N);
							Depth_Stack->push(Intersection(Depth, IPoint, N, this));
							Flag = true;
						}
					}
				}

				x0 = x2;
				y0 = y2;
			}
		}
	}

	return Flag;
}

bool TrueType::All_Intersections(const Ray& ray, IStack& Depth_Stack, TraceThreadData *Thread)
{
	VECTOR P, D;

	Thread->Stats()[Ray_TTF_Tests]++;

	/* Transform the point into the glyph's space */

	MInvTransPoint(P, ray.Origin, Trans);
	MInvTransDirection(D, ray.Direction, Trans);

	/* Tweak the ray to try to avoid pathalogical intersections */
/* 	DBL len;

	D[0] *= 1.0000013147;
	D[1] *= 1.0000022741;
	D[2] *= 1.0000017011;

	VLength(len, D);
	VInverseScaleEq(D, len);*/

	if (GlyphIntersect(P, D, glyph, depth, ray, Depth_Stack, Thread)) /* tw */
	{
		Thread->Stats()[Ray_TTF_Tests_Succeeded]++;
		return true;
	}

	return false;
}

bool TrueType::Inside(const VECTOR IPoint, TraceThreadData *Thread) const
{
	VECTOR New_Point;

	/* Transform the point into font space */

	MInvTransPoint(New_Point, IPoint, Trans);

	if (New_Point[Z] >= 0.0 && New_Point[Z] <= depth &&
	    Inside_Glyph(New_Point[X], New_Point[Y], glyph))
		return (!Test_Flag(this, INVERTED_FLAG));
	else
		return (Test_Flag(this, INVERTED_FLAG));
}

void TrueType::Normal(VECTOR Result, Intersection *Inter, TraceThreadData *Thread) const
{
	/* Use precomputed normal. [ARE 11/94] */

	Assign_Vector(Result, Inter->INormal);
}

ObjectPtr TrueType::Copy()
{
	TrueType *New = new TrueType();
	Destroy_Transform(New->Trans);
	*New = *this;
	New->Trans = Copy_Transform(Trans);
	New->glyph = glyph; // TODO - How can this work correctly? [trf]
	return (New);
}

void TrueType::Translate(const VECTOR /*Vector*/, const TRANSFORM *tr)
{
	Transform(tr);
}

void TrueType::Rotate(const VECTOR /*Vector*/, const TRANSFORM *tr)
{
	Transform(tr);
}

void TrueType::Scale(const VECTOR /*Vector*/, const TRANSFORM *tr)
{
	Transform(tr);
}

void TrueType::Invert()
{
	Invert_Flag(this, INVERTED_FLAG);
}

void TrueType::Transform(const TRANSFORM *tr)
{
	Compose_Transforms(Trans, tr);

	/* Calculate the bounds */

	Compute_BBox();
}

TrueType::TrueType() : ObjectBase(TTF_OBJECT)
{
	/* Initialize TTF specific information */

	Trans = Create_Transform();

	glyph = NULL;
	depth = 1.0;

	/* Default bounds */
	Make_BBox(BBox, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0);
}

TrueType::~TrueType()
{
	Destroy_Transform(Trans);
}



/*****************************************************************************
*
* FUNCTION
*
*   Compute_TTF_BBox
*
* INPUT
*
*   ttf - ttf
*
* OUTPUT
*
*   ttf
*
* RETURNS
*
* AUTHOR
*
*   Dieter Bayer, August 1994
*
* DESCRIPTION
*
*   Calculate the bounding box of a true type font.
*
* CHANGES
*
*   -
*
******************************************************************************/
void TrueType::Compute_BBox()
{
	DBL funit_size, xMin, yMin, zMin, xMax, yMax, zMax;

	funit_size = 1.0 / (DBL)(glyph->unitsPerEm);

	xMin = (DBL)glyph->header.xMin * funit_size;
	yMin = (DBL)glyph->header.yMin * funit_size;
	zMin = -TTF_Tolerance;

	xMax = (DBL)glyph->header.xMax * funit_size;
	yMax = (DBL)glyph->header.yMax * funit_size;
	zMax = depth + TTF_Tolerance;

	Make_BBox(BBox, xMin, yMin, zMin, xMax - xMin, yMax - yMin, zMax - zMin);

#ifdef TTF_DEBUG
	Debug_Info("Bounds: <%g,%g,%g> -> <%g,%g,%g>\n",
	           ttf->BBox.Lower_Left[0],
	           ttf->BBox.Lower_Left[1],
	           ttf->BBox.Lower_Left[2],
	           ttf->BBox.Lengths[0],
	           ttf->BBox.Lengths[1],
	           ttf->BBox.Lengths[2]);
#endif

	/* Apply the transformation to the bounding box */

	Recompute_BBox(&BBox, Trans);
}

}