Commit 84869ec7da984493b3cd268b9e56b80e7c78ac82

dtremenak 2008-05-23T00:46:08

* Provide a helper class for walking potentially-multibyte unicode strings. * Provide support for multibyte encodings (UTF-8, UTF-16) in FTFont and derived classes, and in FTSimpleLayout. * Put a few UTF-8 strings in non-latin codeplanes in FTGLDemo (toggle at compile-time) for testing. * FTSimpleLayout should be tested extensively before release. I would be surprised if I didn't break at least one unusual use case.

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
diff --git a/TODO b/TODO
index 11da3a1..20ae13b 100644
--- a/TODO
+++ b/TODO
@@ -9,8 +9,6 @@ TODO
 
 * Use the Freetype Cache mechanism. FTC_xxx
 
-* Handle non western scripts.
-
 * Multiple Masters
 
 * String Cache or string chunks
diff --git a/demo/FTGLDemo.cpp b/demo/FTGLDemo.cpp
index b70c958..8872027 100644
--- a/demo/FTGLDemo.cpp
+++ b/demo/FTGLDemo.cpp
@@ -177,11 +177,22 @@ void setUpFonts(const char* file)
     }
 
     infoFont->FaceSize(18);
-
-    strcpy(myString, "OpenGL is a powerful software interface for graphics "
+#if 1
+	strcpy(myString, "OpenGL is a powerful software interface for graphics "
            "hardware that allows graphics programmers to produce high-quality "
            "color images of 3D objects.\nabc def ghij klm nop qrs tuv wxyz "
            "ABC DEF GHIJ KLM NOP QRS TUV WXYZ 01 23 45 67 89");
+#elif 0
+	strcpy(myString, "OpenGL (Open Graphics Library — открытая графическая "
+		"библиотека) — спецификация, определяющая независимый от языка "
+		"программирования кросс-платформенный программный интерфейс для написания "
+		"приложений, использующих двумерную и трехмерную компьютерную графику.");
+#else
+	strcpy(myString, "OpenGL™ 是行业领域中最为广泛接纳的 2D/3D 图形 API, "
+		"其自诞生至今已催生了各种计算机平台及设备上的数千优秀应用程序。OpenGL™ 是独立于视窗操作系统或其它操作系统的"
+		",亦是网络透明的。在包含CAD、内容创作、能源、娱乐、游戏开发、制造业、制药业及虚拟现实等行业领域中, OpenGL™ "
+		"帮助程序员实现在 PC、工作站、超级计算机等硬件设备上的高性能、极具冲击力的高视觉表现力图形处理软件的开发。");
+#endif
 }
 
 
diff --git a/msvc/vc8/ftgl_static.vcproj b/msvc/vc8/ftgl_static.vcproj
index 21362d4..d88f354 100644
--- a/msvc/vc8/ftgl_static.vcproj
+++ b/msvc/vc8/ftgl_static.vcproj
@@ -159,10 +159,6 @@
 				>
 			</File>
 			<File
-				RelativePath="..\..\src\FTCharToGlyphIndexMap.h"
-				>
-			</File>
-			<File
 				RelativePath="..\..\src\FTContour.cpp"
 				>
 			</File>
@@ -297,6 +293,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\FTCharToGlyphIndexMap.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\FTContour.h"
 				>
 			</File>
@@ -325,6 +325,10 @@
 				>
 			</File>
 			<File
+				RelativePath="..\..\src\FTUnicode.h"
+				>
+			</File>
+			<File
 				RelativePath="..\..\src\FTVector.h"
 				>
 			</File>
diff --git a/src/FTFont/FTFont.cpp b/src/FTFont/FTFont.cpp
index 8ba2147..380b770 100644
--- a/src/FTFont/FTFont.cpp
+++ b/src/FTFont/FTFont.cpp
@@ -26,6 +26,7 @@
 #include "config.h"
 
 #include "FTInternals.h"
+#include "FTUnicode.h"
 
 #include "FTFontImpl.h"
 
@@ -369,26 +370,34 @@ inline FTBBox FTFontImpl::BBoxI(const T* string, const int len,
     /* Only compute the bounds if string is non-empty. */
     if(string && ('\0' != string[0]))
     {
-        if(CheckGlyph(string[0]))
+        // for multibyte - we can't rely on sizeof(T) == character
+        FTUnicodeStringItr<T> ustr(string);
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
         {
-            totalBBox = glyphList->BBox(string[0]);
+            totalBBox = glyphList->BBox(thisChar);
             totalBBox += position;
 
-            position += glyphList->Advance(string[0], string[1]);
+            position += glyphList->Advance(thisChar, nextChar);
         }
 
         /* Expand totalBox by each glyph in string */
-        for(int i = 1; (len < 0 && string[i]) || (len >= 0 && i < len); i++)
+        for(int i = 1; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
         {
-            if(CheckGlyph(string[i]))
+            unsigned int thisChar = *ustr++;
+            unsigned int nextChar = *ustr;
+
+            if(CheckGlyph(thisChar))
             {
                 position += spacing;
 
-                FTBBox tempBBox = glyphList->BBox(string[i]);
+                FTBBox tempBBox = glyphList->BBox(thisChar);
                 tempBBox += position;
                 totalBBox |= tempBBox;
 
-                position += glyphList->Advance(string[i], string[i + 1]);
+                position += glyphList->Advance(thisChar, nextChar);
             }
         }
     }
@@ -416,15 +425,19 @@ template <typename T>
 inline FTPoint FTFontImpl::AdvanceI(const T* string, const int len,
                                     FTPoint position, FTPoint spacing)
 {
-    for(int i = 0; (len < 0 && string[i]) || (len >= 0 && i < len); i++)
+    FTUnicodeStringItr<T> ustr(string);
+
+    for(int i = 0; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
     {
-        if(CheckGlyph(string[i]))
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
         {
-            position += glyphList->Advance((unsigned int)string[i],
-                                           (unsigned int)string[i + 1]);
+            position += glyphList->Advance(thisChar, nextChar);
         }
 
-        if(string[i + 1])
+        if(nextChar)
         {
             position += spacing;
         }
@@ -455,21 +468,26 @@ inline FTPoint FTFontImpl::RenderI(const T* string, const int len,
                                    FTPoint position, FTPoint spacing,
                                    int renderMode)
 {
-    for(int i = 0; (len < 0 && string[i]) || (len >= 0 && i < len); i++)
+     // for multibyte - we can't rely on sizeof(T) == character
+    FTUnicodeStringItr<T> ustr(string);
+
+    for(int i = 0; (len < 0 && *ustr) || (len >= 0 && i < len); i++)
     {
-        if(CheckGlyph(string[i]))
+        unsigned int thisChar = *ustr++;
+        unsigned int nextChar = *ustr;
+
+        if(CheckGlyph(thisChar))
         {
-            position += glyphList->Render((unsigned int)string[i],
-                                          (unsigned int)string[i + 1],
+            position += glyphList->Render(thisChar, nextChar,
                                           position, renderMode);
         }
 
-        if(string[i + 1])
+        if(nextChar)
         {
             position += spacing;
         }
     }
-
+    
     return position;
 }
 
diff --git a/src/FTLayout/FTSimpleLayout.cpp b/src/FTLayout/FTSimpleLayout.cpp
index 1823250..9b090f7 100644
--- a/src/FTLayout/FTSimpleLayout.cpp
+++ b/src/FTLayout/FTSimpleLayout.cpp
@@ -28,6 +28,7 @@
 #include <ctype.h>
 
 #include "FTInternals.h"
+#include "FTUnicode.h"
 
 #include "FTGlyphContainer.h"
 #include "FTSimpleLayoutImpl.h"
@@ -191,13 +192,15 @@ inline void FTSimpleLayoutImpl::WrapTextI(const T *buf, const int len,
                                           FTPoint position, int renderMode,
                                           FTBBox *bounds)
 {
-    int breakIdx = 0;          // index of the last break character
-    int lineStart = 0;         // character index of the line start
+    FTUnicodeStringItr<T> breakItr(buf);          // points to the last break character
+    FTUnicodeStringItr<T> lineStart(buf);         // points to the line start
     float nextStart = 0.0;     // total width of the current line
     float breakWidth = 0.0;    // width of the line up to the last word break
     float currentWidth = 0.0;  // width of all characters on the current line
     float prevWidth;           // width of all characters but the current glyph
     float wordLength = 0.0;    // length of the block since the last break char
+    int charCount = 0;         // number of characters so far on the line
+    int breakCharCount = 0;    // number of characters before the breakItr
     float glyphWidth, advance;
     FTBBox glyphBounds;
 
@@ -211,55 +214,57 @@ inline void FTSimpleLayoutImpl::WrapTextI(const T *buf, const int len,
     }
 
     // Scan the input for all characters that need output
-    for(int i = 0; buf[i]; i++)
+    FTUnicodeStringItr<T> prevItr(buf);
+    for (FTUnicodeStringItr<T> itr(buf); *itr; prevItr = itr++, charCount++)
     {
         // Find the width of the current glyph
-        glyphBounds = currentFont->BBox(buf + i, 1);
+        glyphBounds = currentFont->BBox(itr.getBufferFromHere(), 1);
         glyphWidth = glyphBounds.Upper().Xf() - glyphBounds.Lower().Xf();
 
-        advance = currentFont->Advance(buf + i, 1).Xf();
+        advance = currentFont->Advance(itr.getBufferFromHere(), 1).Xf();
         prevWidth = currentWidth;
         // Compute the width of all glyphs up to the end of buf[i]
         currentWidth = nextStart + glyphWidth;
         // Compute the position of the next glyph
         nextStart += advance;
 
-        // See if buf[i] is a space, a break or a regular character
-        if((currentWidth > lineLength) || (buf[i] == '\n'))
+        // See if the current character is a space, a break or a regular character
+        if((currentWidth > lineLength) || (*itr == '\n'))
         {
             // A non whitespace character has exceeded the line length.  Or a
             // newline character has forced a line break.  Output the last
             // line and start a new line after the break character.
             // If we have not yet found a break, break on the last character
-            if(!breakIdx || (buf[i] == '\n'))
+            if(breakItr == lineStart || (*itr == '\n'))
             {
                 // Break on the previous character
-                breakIdx = i - 1;
+                breakItr = prevItr;
+                breakCharCount = charCount - 1;
                 breakWidth = prevWidth;
                 // None of the previous words will be carried to the next line
                 wordLength = 0;
                 // If the current character is a newline discard its advance
-                if(buf[i] == '\n') advance = 0;
+                if(*itr == '\n') advance = 0;
             }
 
             float remainingWidth = lineLength - breakWidth;
 
             // Render the current substring
+            FTUnicodeStringItr<T> breakChar = breakItr;
+            // move past the break character and don't count it on the next line either
+            ++breakChar; --charCount;
             // If the break character is a newline do not render it
-            if(buf[breakIdx + 1] == '\n')
+            if(*breakChar == '\n')
             {
-                breakIdx++;
-                OutputWrapped(buf + lineStart, breakIdx - lineStart - 1,
-                              position, renderMode, remainingWidth, bounds);
-            }
-            else
-            {
-                OutputWrapped(buf + lineStart, breakIdx - lineStart,
-                              position, renderMode, remainingWidth, bounds);
+                ++breakChar; --charCount;
             }
 
+            OutputWrapped(lineStart.getBufferFromHere(), breakCharCount,
+                          //breakItr.getBufferFromHere() - lineStart.getBufferFromHere(),
+                          position, renderMode, remainingWidth, bounds);
+
             // Store the start of the next line
-            lineStart = breakIdx + 1;
+            lineStart = breakChar;
             // TODO: Is Height() the right value here?
             pen -= FTPoint(0, currentFont->LineHeight() * lineSpacing);
             // The current width is the width since the last break
@@ -267,16 +272,18 @@ inline void FTSimpleLayoutImpl::WrapTextI(const T *buf, const int len,
             wordLength += advance;
             currentWidth = wordLength + advance;
             // Reset the safe break for the next line
-            breakIdx = 0;
+            breakItr = lineStart;
+            charCount -= breakCharCount;
         }
-        else if(isspace(buf[i]))
+        else if(iswspace(*itr))
         {
             // This is the last word break position
             wordLength = 0;
-            breakIdx = i;
+            breakItr = itr;
+            breakCharCount = charCount;
 
             // Check to see if this is the first whitespace character in a run
-            if(!i || !isspace(buf[i - 1]))
+            if(buf == itr.getBufferFromHere() || !iswspace(*prevItr))
             {
                 // Record the width of the start of the block
                 breakWidth = currentWidth;
@@ -294,13 +301,13 @@ inline void FTSimpleLayoutImpl::WrapTextI(const T *buf, const int len,
     if(alignment == FTGL::ALIGN_JUSTIFY)
     {
         alignment = FTGL::ALIGN_LEFT;
-        OutputWrapped(buf + lineStart, -1, position, renderMode,
+        OutputWrapped(lineStart.getBufferFromHere(), -1, position, renderMode,
                       remainingWidth, bounds);
         alignment = FTGL::ALIGN_JUSTIFY;
     }
     else
     {
-        OutputWrapped(buf + lineStart, -1, position, renderMode,
+        OutputWrapped(lineStart.getBufferFromHere(), -1, position, renderMode,
                       remainingWidth, bounds);
     }
 }
@@ -403,11 +410,12 @@ inline void FTSimpleLayoutImpl::RenderSpaceI(const T *string, const int len,
         int numSpaces = 0;
 
         // Count the number of space blocks in the input
-        for(int i = 0; ((len < 0) && string[i])
-                              || ((len >= 0) && (i <= len)); i++)
+        FTUnicodeStringItr<T> prevItr(string), itr(string);
+        for(int i = 0; ((len < 0) && *itr) || ((len >= 0) && (i <= len));
+            ++i, prevItr = itr++)
         {
             // If this is the end of a space block, increment the counter
-            if((i > 0) && !isspace(string[i]) && isspace(string[i - 1]))
+            if((i > 0) && !iswspace(*itr) && iswspace(*prevItr))
             {
                 numSpaces++;
             }
@@ -417,17 +425,18 @@ inline void FTSimpleLayoutImpl::RenderSpaceI(const T *string, const int len,
     }
 
     // Output all characters of the string
-    for(int i = 0; ((len < 0) && string[i])
-                          || ((len >= 0) && (i <= len)); i++)
+    FTUnicodeStringItr<T> prevItr(string), itr(string);
+    for(int i = 0; ((len < 0) && *itr) || ((len >= 0) && (i <= len));
+        ++i, prevItr = itr++)
     {
         // If this is the end of a space block, distribute the extra space
         // inside it
-        if((i > 0) && !isspace(string[i]) && isspace(string[i - 1]))
+        if((i > 0) && !iswspace(*itr) && iswspace(*prevItr))
         {
             pen += FTPoint(space, 0);
         }
 
-        pen = currentFont->Render(string + i, 1, pen, FTPoint(), renderMode);
+        pen = currentFont->Render(itr.getBufferFromHere(), 1, pen, FTPoint(), renderMode);
     }
 }
 
diff --git a/src/FTUnicode.h b/src/FTUnicode.h
new file mode 100644
index 0000000..fc02252
--- /dev/null
+++ b/src/FTUnicode.h
@@ -0,0 +1,230 @@
+/*
+ * FTGL - OpenGL font library
+ *
+ * Copyright (c) 2001-2004 Henry Maddocks <ftgl@opengl.geek.nz>
+ *
+ * Permission is hereby granted, free of charge, to any person obtaining
+ * a copy of this software and associated documentation files (the
+ * "Software"), to deal in the Software without restriction, including
+ * without limitation the rights to use, copy, modify, merge, publish,
+ * distribute, sublicense, and/or sell copies of the Software, and to
+ * permit persons to whom the Software is furnished to do so, subject to
+ * the following conditions:
+ *
+ * The above copyright notice and this permission notice shall be
+ * included in all copies or substantial portions of the Software.
+ *
+ * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
+ * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
+ * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
+ * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
+ * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
+ * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
+ */
+
+#ifndef    __FTUnicode__
+#define    __FTUnicode__
+
+/**
+ * Provides a way to easily walk multibyte unicode strings in the various
+ * Unicode encodings (UTF-8, UTF-16, UTF-32, UCS-2, and UCS-4).  Encodings
+ * with elements larger than one byte must already be in the correct endian
+ * order for the current architecture.
+ */
+template <typename T>
+class FTUnicodeStringItr
+{
+public:
+	/**
+	 * Constructor.  Also reads the first character and stores it.
+	 *
+	 * @param string  The buffer to iterate.  No copy is made.
+	 */
+    FTUnicodeStringItr(const T* string) : curPos(string), nextPos(string)
+    {
+        (*this)++;
+    };
+
+	/**
+	 * Pre-increment operator.  Reads the next unicode character and sets 
+	 * the state appropriately.
+     * Note - not protected against overruns.
+	 */
+    FTUnicodeStringItr& operator++()
+    {
+        curPos = nextPos;
+        // unicode handling
+        switch (sizeof(T))
+        {
+            case 1: // UTF-8
+                // get this character
+                readUTF8(); break;
+            case 2: // UTF-16
+                readUTF16(); break;
+            case 4: // UTF-32
+                // fall through
+            default: // error condition really, but give it a shot anyway
+                curChar = *nextPos++;
+        }
+        return *this;
+    }
+
+	/**
+	 * Post-increment operator.  Reads the next character and sets
+	 * the state appropriately.
+	 * Note - not protected against overruns.
+	 */
+    FTUnicodeStringItr operator++(int)
+    {
+        FTUnicodeStringItr temp = *this;
+        ++*this;
+        return temp;
+    }
+
+	/**
+	 * Equality operator.  Two FTUnicodeStringItrs are considered equal
+	 * if they have the same current buffer and buffer position.
+	 */
+    bool operator==(const FTUnicodeStringItr& right) const
+    {
+        if (curPos == right.getBufferFromHere())
+            return true;
+        return false;
+    }
+
+	/**
+	 * Dereference operator.
+	 *
+	 * @return  The unicode codepoint of the character currently pointed
+	 * to by the FTUnicodeStringItr.
+	 */
+    unsigned int operator*() const
+    {
+        return curChar;
+    }
+
+	/**
+	 * Buffer-fetching getter.  You can use this to retreive the buffer starting
+	 * at the currently-iterated character for functions which require a unicode 
+	 * string as input.
+	 */
+    const T* getBufferFromHere() const { return curPos; }
+
+private:
+	/**
+	 * Helper function for reading a single UTF8 character from the string.
+	 * Updates internal state appropriately.
+	 */
+    void readUTF8();
+
+	/**
+	 * Helper function for reading a single UTF16 character from the string.
+	 * Updates internal state appropriately.
+	 */
+    void readUTF16();
+
+	/**
+	 * The buffer position of the first element in the current character.
+	 */
+    const T* curPos;
+
+	/**
+	 * The character stored at the current buffer position (prefetched on
+	 * increment, so there's no penalty for dereferencing more than once).
+	 */
+    unsigned int curChar;
+
+	/**
+	 * The buffer position of the first element in the next character.
+	 */
+    const T* nextPos;
+
+	// unicode magic numbers
+    static const char utf8bytes[256];
+    static const unsigned long offsetsFromUTF8[6];
+    static const unsigned long highSurrogateStart;
+    static const unsigned long highSurrogateEnd;
+    static const unsigned long lowSurrogateStart;
+    static const unsigned long lowSurrogateEnd;
+    static const unsigned long highSurrogateShift;
+    static const unsigned long lowSurrogateBase;
+};
+
+/* The first character in a UTF8 sequence indicates how many bytes
+ * to read (among other things) */
+template <typename T>
+const char FTUnicodeStringItr<T>::utf8bytes[256] = {
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,
+  2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2, 2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,2,
+  3,3,3,3,3,3,3,3,3,3,3,3,3,3,3,3, 4,4,4,4,4,4,4,4,5,5,5,5,6,6,6,6
+};
+
+/* Magic values subtracted from a buffer value during UTF8 conversion.
+ * This table contains as many values as there might be trailing bytes
+ * in a UTF-8 sequence. */
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::offsetsFromUTF8[6] = { 0x00000000UL, 0x00003080UL, 0x000E2080UL,
+  0x03C82080UL, 0xFA082080UL, 0x82082080UL };
+
+// get a UTF8 character; leave the tracking pointer at the start of the 
+// next character
+// not protected against invalid UTF8
+template <typename T>
+inline void FTUnicodeStringItr<T>::readUTF8()
+{
+    unsigned int ch = 0;
+    unsigned int extraBytesToRead = utf8bytes[(unsigned char)(*nextPos)];
+    // falls through
+    switch (extraBytesToRead)
+    {
+          case 6: ch += *nextPos++; ch <<= 6; /* remember, illegal UTF-8 */
+          case 5: ch += *nextPos++; ch <<= 6; /* remember, illegal UTF-8 */
+          case 4: ch += *nextPos++; ch <<= 6;
+          case 3: ch += *nextPos++; ch <<= 6;
+          case 2: ch += *nextPos++; ch <<= 6;
+          case 1: ch += *nextPos++;
+    }
+    ch -= offsetsFromUTF8[extraBytesToRead-1];
+    curChar = ch;
+}
+
+// Magic numbers for UTF-16 conversions
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateStart = 0xD800;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateEnd = 0xDBFF;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateStart = 0xDC00;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateEnd = 0xDFFF;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::highSurrogateShift = 10;
+template <typename T>
+const unsigned long FTUnicodeStringItr<T>::lowSurrogateBase = 0x0010000UL;
+
+template <typename T>
+inline void FTUnicodeStringItr<T>::readUTF16()
+{
+    unsigned int ch = *nextPos++;
+    // if we have the first half of the surrogate pair
+    if (ch >= highSurrogateStart && ch <= highSurrogateEnd)
+    {
+        unsigned int ch2 = *curPos;
+        // complete the surrogate pair
+        if (ch2 >= lowSurrogateStart && ch2 <= lowSurrogateEnd)
+        {
+            ch = ((ch - highSurrogateStart) << highSurrogateShift)
+                + (ch2 - lowSurrogateStart) + lowSurrogateBase;
+            ++nextPos;
+        }
+    }
+    curChar = ch;
+}
+
+#endif
diff --git a/src/Makefile.am b/src/Makefile.am
index 47dea29..b0c0430 100644
--- a/src/Makefile.am
+++ b/src/Makefile.am
@@ -22,6 +22,7 @@ libftgl_la_SOURCES = \
     FTVector.h \
     FTVectoriser.cpp \
     FTVectoriser.h \
+    FTUnicode.h \
     $(ftglyph_sources) \
     $(ftfont_sources) \
     $(ftlayout_sources) \