Debian Codegraph @

lib/database/src/so/nodes/SoText3.c++

raw
1 /*
2 *
3 * Copyright (C) 2000 Silicon Graphics, Inc. All Rights Reserved.
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * Further, this software is distributed without any warranty that it is
16 * free of the rightful claim of any third person regarding infringement
17 * or the like. Any license provided herein, whether implied or
18 * otherwise, applies only to this software file. Patent licenses, if
19 * any, provided herein do not apply to combinations of this program with
20 * other software, or any other product whatsoever.
21 *
22 * You should have received a copy of the GNU Lesser General Public
23 * License along with this library; if not, write to the Free Software
24 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 *
26 * Contact information: Silicon Graphics, Inc., 1600 Amphitheatre Pkwy,
27 * Mountain View, CA 94043, or:
28 *
29 * http://www.sgi.com
30 *
31 * For further information regarding this notice, see:
32 *
33 * http://oss.sgi.com/projects/GenInfo/NoticeExplan/
34 *
35 */
36
37 /*
38 * Copyright (C) 1990,91 Silicon Graphics, Inc.
39 *
40 _______________________________________________________________________
41 ______________ S I L I C O N G R A P H I C S I N C . ____________
42 |
43 | $Revision: 1.10 $
44 |
45 | Classes:
46 | SoText3
47 |
48 |
49 | Author(s) : Gavin Bell
50 |
51 ______________ S I L I C O N G R A P H I C S I N C . ____________
52 _______________________________________________________________________
53 */
54
55 #include <GL/gl.h>
56 #include <GL/glu.h>
57 #include <Inventor/SbBox.h>
58 #include <Inventor/SoPrimitiveVertex.h>
59 #include <Inventor/actions/SoCallbackAction.h>
60 #include <Inventor/actions/SoGLRenderAction.h>
61 #include <Inventor/actions/SoRayPickAction.h>
62 #include <Inventor/bundles/SoMaterialBundle.h>
63 #include <Inventor/caches/SoCache.h>
64 #include <Inventor/details/SoTextDetail.h>
65 #include <Inventor/elements/SoCacheElement.h>
66 #include <Inventor/elements/SoComplexityElement.h>
67 #include <Inventor/elements/SoComplexityTypeElement.h>
68 #include <Inventor/elements/SoCreaseAngleElement.h>
69 #include <Inventor/elements/SoFontNameElement.h>
70 #include <Inventor/elements/SoFontSizeElement.h>
71 #include <Inventor/elements/SoGLCacheContextElement.h>
72 #include <Inventor/elements/SoGLTextureCoordinateElement.h>
73 #include <Inventor/elements/SoGLTextureEnabledElement.h>
74 #include <Inventor/elements/SoMaterialBindingElement.h>
75 #include <Inventor/elements/SoModelMatrixElement.h>
76 #include <Inventor/elements/SoProfileElement.h>
77 #include <Inventor/elements/SoProfileCoordinateElement.h>
78 #include <Inventor/elements/SoProjectionMatrixElement.h>
79 #include <Inventor/elements/SoViewportRegionElement.h>
80 #include <Inventor/elements/SoViewingMatrixElement.h>
81 #include <Inventor/errors/SoDebugError.h>
82 #include <Inventor/misc/SoState.h>
83 #include <Inventor/nodes/SoProfile.h>
84 #include <Inventor/nodes/SoText3.h>
85
86 // Font library:
87 // Additional for Banyan(6.2):
88 #include <flclient.h>
89 #include <iconv.h>
90 #include <machine.h>
91
92 // First, a more convenient structure for outlines:
93 class SoFontOutline {
94
95 public:
96 // Constructor, takes a pointer to the font-library outline
97 // structure and the font's size:
98 SoFontOutline(FLoutline *outline, float fontSize);
99 // Destructor
100 ~SoFontOutline();
101
102 // Query routines:
103 int getNumOutlines() { return numOutlines; }
104 int getNumVerts(int i) { return numVerts[i]; }
105 SbVec2f &getVertex(int i, int j) { return verts[i][j]; }
106 SbVec2f getCharAdvance() { return charAdvance; }
107
108 static SoFontOutline *getNullOutline();
109
110 private:
111 // Internal constructor used by getNullOutline:
112 SoFontOutline();
113
114 // This basically mimics the FLoutline structure, with the
115 // exception that the font size is part of the outline:
116 int numOutlines;
117 int *numVerts;
118 SbVec2f **verts;
119 SbVec2f charAdvance;
120 };
121
122 //
123 // Internal class: SoOutlineFontCache
124 //
125
126 // Callback function for sides of characters-- passed the number of
127 // points going back, and points and normals on either edge of the
128 // strip. tTexCoords[0] and [1] are for the two edges, and the
129 // sTexCoords are the same for both edges.
130 typedef void SideCB(int nPoints,
131 const SbVec3f *points1, const SbVec3f *norms1,
132 const SbVec3f *points2, const SbVec3f *norms2,
133 const float *sTexCoords, const float *tTexCoords);
134
135 // This is pretty heavyweight-- it is responsible for doing all of the
136 // grunt work of figuring out the polygons making up the characters in
137 // the font.
138 class SoOutlineFontCache : public SoCache
139 {
140 public:
141 // Given a state, find an appropriate outline font.
142 static SoOutlineFontCache *getFont(SoState *, SbBool forRender);
143
144 // Checks to see if this font is valid
145 SbBool isValid(const SoState *state) const;
146
147 // Figures out if this cache is valid for rendering (the base
148 // class isValid can be used for all other actions)
149 SbBool isRenderValid(SoState *state) const;
150
151 // Returns the width of specified line number
152 float getWidth(int line);
153
154 // Returns height of font
155 float getHeight() { return fontSize; }
156
157 // Returns the 2D bounding box of a UCS character
158 void getCharBBox(const char* c, SbBox2f &result);
159 // ... and the bounding box of the font's bevel
160 void getProfileBBox(SbBox2f &result);
161
162 // Return the first/last point in the profile:
163 void getProfileBounds(float &firstZ, float &lastZ);
164
165 // Returns TRUE if there _is_ any profile
166 // (if not, act as if SIDES of text are off)
167 SbBool hasProfile() const { return (nProfileVerts > 1); }
168
169 // Returns how far to advance after drawing given character:
170 SbVec2f getCharOffset(const char* c);
171
172 // Uses the given glu tesselator to generate triangles for the
173 // given character. This is used for both rendering and
174 // generating primitives, with just different callback routines
175 // registered.
176 void generateFrontChar(const char* c, gluTESSELATOR *tobj);
177 // Ditto, for sides of characters:
178 void generateSideChar(const char* c, SideCB callbackFunc);
179
180 // Set up for GL rendering:
181 void setupToRenderFront(SoState *state);
182 void setupToRenderSide(SoState *state, SbBool willTexture);
183
184 // Returns TRUE if this font cache has a display list for the
185 // given UCS character. It will try to build a display list, if it
186 // can.
187 SbBool hasFrontDisplayList(const char* c, gluTESSELATOR *tobj);
188 SbBool hasSideDisplayList(const char* c, SideCB callbackFunc);
189
190 // Renders an entire line by using the GL callList() function.
191 void callFrontLists(int line);
192 void callSideLists(int line);
193
194 // Renders a UCS string in cases where display lists can't be buit.
195 void renderFront(int line, gluTESSELATOR *tobj);
196 void renderSide(int line, SideCB callbackFunc);
197
198 // Callback registered with GLU used to detect tesselation errors.
199 static void errorCB(GLenum whichErr);
200
201 //Convert string to UCS format, keep a copy in this cache.
202 //Use nodeid to know when to reconvert.
203 void convertToUCS(uint32_t nodeid, const SoMFString& string);
204
205 //Returns line of UCS-2 text
206 char * getUCSString(int line)
207 { return (char*)UCSStrings[line];}
208
209 int getNumUCSChars(int line)
210 { return (int)(long)UCSNumChars[line];}
211
212 GLubyte *createUniFontList(const char* fontNameList);
213
214 protected:
215
216 // Free up display lists before being deleted
217 virtual void destroy(SoState *state);
218
219 private:
220 // Constructor
221 SoOutlineFontCache(SoState *);
222 // Destructor
223 ~SoOutlineFontCache();
224
225 // Return a convnient little class representing a UCS character's
226 // outline.
227 SoFontOutline *getOutline(const char* c);
228
229 // Some helper routines for generateSide:
230 void figureSegmentNorms(SbVec2f *result, int nPoints,
231 const SbVec2f *points, float cosCreaseAngle, SbBool isClosed);
232 void figureSegmentTexCoords(float *texCoords, int nPoints,
233 const SbVec2f *points, SbBool isClosed);
234 void fillBevel(SbVec3f *result, int nPoints,
235 const SbVec2f *points, const SbVec2f &translation,
236 const SbVec2f &n1, const SbVec2f &n2);
237 void fillBevelN(SbVec3f *result, int nPoints,
238 const SbVec2f *norms, const SbVec2f &n);
239
240 // Texture coordinates in side display lists
241 int sidesHaveTexCoords;
242
243 // Number of characters in this font.
244
245 int numChars;
246
247 // Display lists for fronts, sides:
248 SoGLDisplayList *frontList;
249 SoGLDisplayList *sideList;
250
251 // Profile information:
252 float cosCreaseAngle;
253 int32_t nProfileVerts; // Number of points in profile
254 SbVec2f *profileVerts; // Profile vertices
255 float *sTexCoords; // Texture coordinates along profile
256 // (nProfileVerts of them)
257 SbVec2f *profileNorms; // Profile normals
258 // ((nProfileVerts-1)*2 of them)
259
260 // This flag will be true if there is another cache open (if
261 // building GL display lists for render caching, that means we
262 // can't also build display lists).
263 SbBool otherOpen;
264
265 // And tables telling us if a display list has been created for
266 // each character in the font (we do that lazily since it is
267 // expensive):
268 SbDict* frontDict;
269 SbDict* sideDict;
270
271 // dictionary of outlines; these are also cached and created when
272 // needed.
273 SbDict* outlineDict;
274
275 // Remember nodeId that was used to do UCS translation.
276 uint32_t currentNodeId;
277
278 static iconv_t conversionCode;
279
280 // Font size
281 float fontSize;
282
283 // Flag used to detect tesselation errors:
284 static SbBool tesselationError;
285
286 // List of font numbers for this font-list
287 GLubyte* fontNumList;
288 SbPList* fontNums;
289
290 // char* pointers of UCS-2 strings:
291 SbPList UCSStrings;
292 // size of these strings, in UCS-2 characters:
293 SbPList UCSNumChars;
294
295 // Font library context for all outline fonts
296 static FLcontext context;
297
298 // Global list of available fonts; a 'font' in this case is a
299 // unique set of font name, font size, complexity value/type, and
300 // set of profiles-- if any of these changes, the set of polygons
301 // representing the font will change, and a different font will be
302 // used.
303 static SbPList *fonts;
304 // Free up an outline (invoked by SbDict::applyToAll):
305 static void freeOutline( unsigned long, void* value);
306 };
307
308 SbBool SoOutlineFontCache::tesselationError = FALSE;
309 SbPList *SoOutlineFontCache::fonts = NULL;
310 FLcontext SoOutlineFontCache::context = NULL;
311 iconv_t SoOutlineFontCache::conversionCode = NULL;
312
313 // Static stuff is used while generating primitives:
314 SoText3 *SoText3::currentGeneratingNode = NULL;
315 SoPrimitiveVertex *SoText3::genPrimVerts[3];
316 SbVec3f SoText3::genTranslate;
317 int SoText3::genWhichVertex = -1;
318 uint32_t SoText3::genPrimType;
319 SoAction *SoText3::genAction = NULL;
320 SbBool SoText3::genBack = FALSE;
321 SbBool SoText3::genTexCoord = TRUE;
322 const SoTextureCoordinateElement *SoText3::tce = NULL;
323
324 SO_NODE_SOURCE(SoText3);
325
326 ////////////////////////////////////////////////////////////////////////
327 //
328 // Description:
329 // Constructor
330 //
331 // Use: public
332
333 SoText3::SoText3()
334 //
335 ////////////////////////////////////////////////////////////////////////
336 {
337 SO_NODE_CONSTRUCTOR(SoText3);
338
339 SO_NODE_ADD_FIELD(string, (""));
340 SO_NODE_ADD_FIELD(spacing, (1.0));
341 SO_NODE_ADD_FIELD(justification, (LEFT));
342 SO_NODE_ADD_FIELD(parts, (FRONT));
343
344 // Set up static info for enumerated type field
345 SO_NODE_DEFINE_ENUM_VALUE(Justification, LEFT);
346 SO_NODE_DEFINE_ENUM_VALUE(Justification, RIGHT);
347 SO_NODE_DEFINE_ENUM_VALUE(Justification, CENTER);
348
349 // Set up static info for enumerated type field
350 SO_NODE_DEFINE_ENUM_VALUE(Part, SIDES);
351 SO_NODE_DEFINE_ENUM_VALUE(Part, FRONT);
352 SO_NODE_DEFINE_ENUM_VALUE(Part, BACK);
353 SO_NODE_DEFINE_ENUM_VALUE(Part, ALL);
354
355 // Set up info in enumerated type field
356 SO_NODE_SET_SF_ENUM_TYPE(justification, Justification);
357 SO_NODE_SET_SF_ENUM_TYPE(parts, Part);
358
359 isBuiltIn = TRUE;
360 myFont = NULL;
361 }
362
363 ////////////////////////////////////////////////////////////////////////
364 //
365 // Description:
366 // Destructor
367 //
368 // Use: private
369
370 SoText3::~SoText3()
371 //
372 ////////////////////////////////////////////////////////////////////////
373 {
374 if (myFont != NULL) myFont->unref();
375 }
376
377 ////////////////////////////////////////////////////////////////////////
378 //
379 // Description:
380 // Figure out the bounds of a character.
381 //
382 // Use: extender
383
384 SbBox3f
385 SoText3::getCharacterBounds(SoState *state, int stringIndex, int
386 charIndex)
387 //
388 ////////////////////////////////////////////////////////////////////////
389 {
390 SbBox3f result;
391
392 if (!setupFontCache(state))
393 return result; // Empty bbox
394
395 #ifdef DEBUG
396 if (stringIndex >= string.getNum()) {
397 SoDebugError::post("SoText3::getCharacterBounds",
398 "stringIndex (%d) out of range (max %d)",
399 stringIndex, string.getNum());
400 }
401 if (charIndex >= myFont->getNumUCSChars(stringIndex)) {
402 SoDebugError::post("SoText3::getCharacterBounds",
403 "charIndex (%d) out of range (max %d)",
404 charIndex,
405 myFont->getNumUCSChars(stringIndex));
406 }
407 #endif
408
409 float frontZ, backZ;
410 myFont->getProfileBounds(frontZ, backZ);
411
412 float height = myFont->getHeight();
413
414 const char *chars = myFont->getUCSString(stringIndex);
415 float width = (myFont->getCharOffset(chars+2*charIndex))[0];
416
417 // Figure out where origin of character is:
418 SbVec2f charPosition = getStringOffset(stringIndex);
419 for (int i = 0; i < charIndex; i++) {
420 charPosition += myFont->getCharOffset(chars+2*charIndex);
421 }
422
423 // Ok, have width, height, depth and starting position of text,
424 // can create the bounds box:
425 if (parts.getValue() & (FRONT|SIDES)) {
426 result.extendBy(SbVec3f(charPosition[0],
427 charPosition[1],
428 frontZ));
429 result.extendBy(SbVec3f(charPosition[0]+width,
430 charPosition[1],
431 frontZ));
432 result.extendBy(SbVec3f(charPosition[0],
433 charPosition[1]+height,
434 frontZ));
435 result.extendBy(SbVec3f(charPosition[0]+width,
436 charPosition[1]+height,
437 frontZ));
438 }
439 if (parts.getValue() & (BACK|SIDES)) {
440 result.extendBy(SbVec3f(charPosition[0],
441 charPosition[1],
442 backZ));
443 result.extendBy(SbVec3f(charPosition[0]+width,
444 charPosition[1],
445 backZ));
446 result.extendBy(SbVec3f(charPosition[0],
447 charPosition[1]+height,
448 backZ));
449 result.extendBy(SbVec3f(charPosition[0]+width,
450 charPosition[1]+height,
451 backZ));
452 }
453 return result;
454 }
455
456 ////////////////////////////////////////////////////////////////////////
457 //
458 // Description:
459 // Performs GL rendering of a Text3.
460 //
461 // Use: extender
462
463 void
464 SoText3::GLRender(SoGLRenderAction *action)
465 //
466 ////////////////////////////////////////////////////////////////////////
467 {
468 static gluTESSELATOR *tobj = NULL;
469
470 // First see if the object is visible and should be rendered now
471 if (! shouldGLRender(action))
472 return;
473
474 SoState *state = action->getState();
475
476 if (!setupFontCache(state, TRUE))
477 return;
478
479 SoMaterialBindingElement::Binding mbe =
480 SoMaterialBindingElement::get(state);
481 SbBool materialPerPart =
482 (mbe == SoMaterialBindingElement::PER_PART_INDEXED ||
483 mbe == SoMaterialBindingElement::PER_PART);
484
485 SoMaterialBundle mb(action);
486 if (!materialPerPart) {
487 // Make sure the fist current material is sent to GL
488 mb.sendFirst();
489 }
490
491 float firstZ, lastZ;
492 myFont->getProfileBounds(firstZ, lastZ);
493
494 if (tobj == NULL) {
495 tobj = gluNewTess();
496 gluTessCallback(tobj, (GLenum)GLU_BEGIN, (void (*)())glBegin);
497 gluTessCallback(tobj, (GLenum)GLU_END, (void (*)())glEnd);
498 gluTessCallback(tobj, (GLenum)GLU_VERTEX, (void (*)())glVertex2fv);
499 gluTessCallback(tobj, (GLenum)GLU_ERROR,
500 (void (*)())SoOutlineFontCache::errorCB);
501 }
502
503 // See if texturing is enabled
504 genTexCoord = SoGLTextureEnabledElement::get(action->getState());
505
506 if ((parts.getValue() & SIDES) && (myFont->hasProfile())) {
507 if (materialPerPart) mb.send(1, FALSE);
508
509 myFont->setupToRenderSide(state, genTexCoord);
510 for (int line = 0; line < string.getNum(); line++) {
511 glPushMatrix();
512 SbVec2f p = getStringOffset(line);
513 if (p[0] != 0.0 || p[1] != 0.0)
514 glTranslatef(p[0], p[1], 0.0);
515 renderSide(action, line);
516 glPopMatrix();
517 }
518 }
519 if (parts.getValue() & BACK) {
520 if (materialPerPart) mb.send(2, FALSE);
521
522 if (lastZ != 0.0) {
523 glTranslatef(0, 0, lastZ);
524 }
525 glNormal3f(0, 0, -1);
526 glFrontFace(GL_CW);
527
528 myFont->setupToRenderFront(state);
529
530 if (genTexCoord) {
531 glPushAttrib(GL_TEXTURE_BIT);
532 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
533 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
534 GLfloat params[4];
535 params[0] = -1.0/myFont->getHeight();
536 params[1] = params[2] = params[3] = 0.0;
537 glTexGenfv(GL_S, GL_OBJECT_PLANE, params);
538 params[1] = -params[0];
539 params[0] = 0.0;
540 glTexGenfv(GL_T, GL_OBJECT_PLANE, params);
541
542 glEnable(GL_TEXTURE_GEN_S);
543 glEnable(GL_TEXTURE_GEN_T);
544 }
545
546 for (int line = 0; line < string.getNum(); line++) {
547 if (string[line].getLength() <= 0) continue;
548
549 glPushMatrix();
550 SbVec2f p = getStringOffset(line);
551 if (p[0] != 0.0 || p[1] != 0.0)
552 glTranslatef(p[0], p[1], 0.0);
553 renderFront(action, line, tobj);
554 glPopMatrix();
555 }
556
557 if (genTexCoord) {
558 glPopAttrib();
559 }
560
561 glFrontFace(GL_CCW);
562
563 if (lastZ != 0)
564 glTranslatef(0, 0, -lastZ);
565 }
566 if (parts.getValue() & FRONT) {
567 if (materialPerPart) mb.sendFirst();
568
569 if (firstZ != 0.0) {
570 glTranslatef(0, 0, firstZ);
571 }
572
573 glNormal3f(0, 0, 1);
574
575 myFont->setupToRenderFront(state);
576
577 if (genTexCoord) {
578 glPushAttrib(GL_TEXTURE_BIT);
579 glTexGeni(GL_S, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
580 glTexGeni(GL_T, GL_TEXTURE_GEN_MODE, GL_OBJECT_LINEAR);
581 GLfloat params[4];
582 params[0] = 1.0/myFont->getHeight();
583 params[1] = params[2] = params[3] = 0.0;
584 glTexGenfv(GL_S, GL_OBJECT_PLANE, params);
585 params[1] = params[0];
586 params[0] = 0.0;
587 glTexGenfv(GL_T, GL_OBJECT_PLANE, params);
588
589 glEnable(GL_TEXTURE_GEN_S);
590 glEnable(GL_TEXTURE_GEN_T);
591 }
592
593 for (int line = 0; line < string.getNum(); line++) {
594 glPushMatrix();
595 SbVec2f p = getStringOffset(line);
596 if (p[0] != 0.0 || p[1] != 0.0)
597 glTranslatef(p[0], p[1], 0.0);
598 renderFront(action, line, tobj);
599 glPopMatrix();
600 }
601
602 if (genTexCoord) {
603 glPopAttrib();
604 }
605
606 if (firstZ != 0.0) {
607 glTranslatef(0, 0, -firstZ);
608 }
609 }
610 }
611
612 ////////////////////////////////////////////////////////////////////////
613 //
614 // Description:
615 // Implements ray picking
616 //
617 // Use: extender
618
619 void
620 SoText3::rayPick(SoRayPickAction *action)
621 //
622 ////////////////////////////////////////////////////////////////////////
623 {
624 // First see if the object is pickable
625 if (! shouldRayPick(action))
626 return;
627
628 //
629 // NOTE: This could be made more efficient by testing the ray
630 // against the bounding box of each character, as follows:
631 //
632 // -- For each string {
633 // -- For each character in the string: {
634 // If the ray intersects the character's bounding box,
635 // generate primitives for that character
636 // }
637 // }
638 //
639 // This is a project for the future... ???
640
641 // For now, just use generatePrimitives() to do the work.
642 SoShape::rayPick(action);
643 }
644
645 ////////////////////////////////////////////////////////////////////////
646 //
647 // Description:
648 // Computes bounding box of text.
649 //
650 // Use: protected
651
652 void
653 SoText3::computeBBox(SoAction *action, SbBox3f &box, SbVec3f &center)
654 //
655 ////////////////////////////////////////////////////////////////////////
656 {
657 // Set the center to be the origin, which is the natural "center"
658 // of the text, regardless of justification
659 center.setValue(0.0, 0.0, 0.0);
660
661 int prts = parts.getValue();
662 if (prts == 0)
663 return;
664
665 SoState *state = action->getState();
666
667 if (!setupFontCache(state))
668 return;
669
670 // Get the bounding box of all the characters:
671 SbBox2f outlineBox;
672 getFrontBBox(outlineBox);
673
674 // If no lines and no characters, return empty bbox:
675 if (outlineBox.isEmpty()) return;
676
677 // .. and extend it based on what parts are turned on:
678 float firstZ, lastZ;
679 myFont->getProfileBounds(firstZ, lastZ);
680
681 const SbVec2f &boxMin = outlineBox.getMin();
682 const SbVec2f &boxMax = outlineBox.getMax();
683
684
685 // Front and back are straightforward:
686 if (prts & FRONT) {
687 SbVec3f min(boxMin[0], boxMin[1], firstZ);
688 SbVec3f max(boxMax[0], boxMax[1], firstZ);
689 box.extendBy(min);
690 box.extendBy(max);
691 }
692 if (prts & BACK) {
693 SbVec3f min(boxMin[0], boxMin[1], lastZ);
694 SbVec3f max(boxMax[0], boxMax[1], lastZ);
695 box.extendBy(min);
696 box.extendBy(max);
697 }
698 //
699 // Sides are trickier. We figure out the maximum offset
700 // of the profile we're using. If the offset is
701 // negative, we use its absolute value; normally, negative
702 // (indented) characters won't expand the bounding box, but if the
703 // offset is negative enough the character will inter-penetrate
704 // itself-- think of a Helvetica 'I', with a bevel of a big
705 // negative spike. The bounding box is either the bounding box of
706 // the front/back, or, if the spike is big enough, the size of the
707 // spike minus the width of the I. I'm being conservative here
708 // and just expanding the front/back bounding boxes by the maximum
709 // offset (correct for positive offsets, conservative for negative
710 // offsets).
711 //
712 if ((prts & SIDES) && myFont->hasProfile()) {
713 SbBox2f profileBox;
714 myFont->getProfileBBox(profileBox);
715
716 const SbVec2f &pBoxMin = profileBox.getMin();
717 const SbVec2f &pBoxMax = profileBox.getMax();
718
719 // If no profile, return the front/back bbox:
720 if (profileBox.isEmpty()) return;
721
722 //
723 // Expand the bounding box forward/backward in case the
724 // profile extends forwards/backwards:
725 //
726 SbVec3f min, max;
727 min.setValue(boxMin[0], boxMin[1], pBoxMin[0]);
728 max.setValue(boxMax[0], boxMax[1], pBoxMax[0]);
729 box.extendBy(min);
730 box.extendBy(max);
731
732 //
733 // And figure out the maximum profile offset, and expand
734 // out the outline's bbox:
735 //
736 # define max(a,b) (a<b ? b : a)
737 # define abs(x) (x>=0 ? x : -(x))
738 float maxOffset = max(abs(pBoxMin[1]), abs(pBoxMax[1]));
739 #undef max
740 #undef abs
741 min.setValue(boxMin[0]-maxOffset, boxMin[1]-maxOffset, firstZ);
742 max.setValue(boxMax[0]+maxOffset, boxMax[1]+maxOffset, lastZ);
743 box.extendBy(min);
744 box.extendBy(max);
745 }
746 }
747
748 ////////////////////////////////////////////////////////////////////////
749 //
750 // Description:
751 // Generates triangles representing a Text3.
752 //
753 // Use: protected
754
755 void
756 SoText3::generatePrimitives(SoAction *action)
757 //
758 ////////////////////////////////////////////////////////////////////////
759 {
760 SoState *state = action->getState();
761
762 if (!setupFontCache(state))
763 return;
764
765 currentGeneratingNode = this;
766
767 // Set up default texture coordinate mapping, if necessary:
768 SoTextureCoordinateElement::CoordType tcType =
769 SoTextureCoordinateElement::getType(state);
770 if (tcType == SoTextureCoordinateElement::EXPLICIT) {
771 genTexCoord = TRUE;
772 tce = NULL;
773 } else {
774 genTexCoord = FALSE;
775 tce = SoTextureCoordinateElement::getInstance(state);
776 }
777
778 // Set up 3 vertices we can use
779 SoPrimitiveVertex v1, v2, v3;
780 SoTextDetail detail;
781 v1.setDetail(&detail);
782 v2.setDetail(&detail);
783 v3.setDetail(&detail);
784
785 genPrimVerts[0] = &v1;
786 genPrimVerts[1] = &v2;
787 genPrimVerts[2] = &v3;
788
789 genAction = action;
790 genBack = FALSE;
791
792 SoMaterialBindingElement::Binding mbe =
793 SoMaterialBindingElement::get(state);
794 SbBool materialPerPart =
795 (mbe == SoMaterialBindingElement::PER_PART_INDEXED ||
796 mbe == SoMaterialBindingElement::PER_PART);
797 if (!materialPerPart) {
798 v1.setMaterialIndex(0);
799 v2.setMaterialIndex(0);
800 v3.setMaterialIndex(0);
801 }
802
803 float firstZ, lastZ;
804 myFont->getProfileBounds(firstZ, lastZ);
805
806 uint32_t prts = parts.getValue();
807 if ((prts & SIDES) && myFont->hasProfile()) {
808 if (materialPerPart) {
809 v1.setMaterialIndex(1);
810 v2.setMaterialIndex(1);
811 v3.setMaterialIndex(1);
812 }
813 detail.setPart(SIDES);
814
815 for (int line = 0; line < string.getNum(); line++) {
816 detail.setStringIndex(line);
817
818 SbVec2f p = getStringOffset(line);
819 genTranslate.setValue(p[0], p[1], lastZ);
820 generateSide(line);
821 }
822 }
823 if (prts & BACK) {
824 genBack = TRUE;
825 if (materialPerPart) {
826 v1.setMaterialIndex(2);
827 v2.setMaterialIndex(2);
828 v3.setMaterialIndex(2);
829 }
830 detail.setPart(BACK);
831
832 v1.setNormal(SbVec3f(0, 0, -1));
833 v2.setNormal(SbVec3f(0, 0, -1));
834 v3.setNormal(SbVec3f(0, 0, -1));
835
836 for (int line = 0; line < string.getNum(); line++) {
837 detail.setStringIndex(line);
838
839 SbVec2f p = getStringOffset(line);
840 genTranslate.setValue(p[0], p[1], lastZ);
841 generateFront(line);
842 }
843 genBack = FALSE;
844 }
845 if (prts & FRONT) {
846 if (materialPerPart) {
847 v1.setMaterialIndex(0);
848 v2.setMaterialIndex(0);
849 v3.setMaterialIndex(0);
850 }
851 detail.setPart(FRONT);
852
853 v1.setNormal(SbVec3f(0, 0, 1));
854 v2.setNormal(SbVec3f(0, 0, 1));
855 v3.setNormal(SbVec3f(0, 0, 1));
856
857 for (int line = 0; line < string.getNum(); line++) {
858 detail.setStringIndex(line);
859
860 SbVec2f p = getStringOffset(line);
861 genTranslate.setValue(p[0], p[1], firstZ);
862 generateFront(line);
863 }
864 }
865 }
866
867 ////////////////////////////////////////////////////////////////////////
868 //
869 // Description:
870 // Setup internal font cache. Called by all action methods before
871 // doing their thing. GLRender passes TRUE to do special rendering
872 // setup. Returns FALSE if there are problems and the action
873 // should bail.
874 //
875 // Use: private
876
877 SbBool
878 SoText3::setupFontCache(SoState *state, SbBool forRender)
879 //
880 ////////////////////////////////////////////////////////////////////////
881 {
882 // The state must be pushed here because myFont->isRenderValid
883 // depends on the state being the correct depth (it must be the
884 // same depth as when the font cache was built).
885 state->push();
886
887 if (myFont != NULL) {
888 SbBool isValid;
889 if (forRender)
890 isValid = myFont->isRenderValid(state);
891 else
892 isValid = myFont->isValid(state);
893
894 if (!isValid) {
895 myFont->unref(state);
896 myFont = NULL;
897 }
898 }
899 if (myFont == NULL) {
900 myFont = SoOutlineFontCache::getFont(state, forRender);
901 }
902
903 //The current text must be translated to UCS, unless this
904 //translation has already been done.
905
906 if(myFont) myFont->convertToUCS(getNodeId(), string);
907 state->pop();
908 return myFont != NULL;
909 }
910
911 ////////////////////////////////////////////////////////////////////////
912 //
913 // Description:
914 // Gets the 2D bounding box of the outlines of the letters in our
915 // string. How? Get all the outlines and extend the bbox by every
916 // point in every outline... (assuming the lines or characters
917 // don't overlap, this could be optimized by just considering the
918 // characters on the borders of the string-- although there are
919 // some gotchas, like spaces at the beginning of a line...).
920 //
921 // Use: private
922
923 void
924 SoText3::getFrontBBox(SbBox2f &result)
925 //
926 ////////////////////////////////////////////////////////////////////////
927 {
928 SbBox2f charBBox;
929
930 int line, character;
931 for (line = 0; line < string.getNum(); line++) {
932 // Starting position of string, based on justification:
933 SbVec2f charPosition = getStringOffset(line);
934
935 const char *chars = myFont->getUCSString(line);
936
937 for (character = 0; character < myFont->getNumUCSChars(line);
938 character++) {
939 myFont->getCharBBox(chars+2*character, charBBox);
940 if (!charBBox.isEmpty()) {
941 SbVec2f min = charBBox.getMin() + charPosition;
942 SbVec2f max = charBBox.getMax() + charPosition;
943 result.extendBy(min);
944 result.extendBy(max);
945 }
946
947 // And advance...
948 charPosition += myFont->getCharOffset(chars+2*character);
949 }
950 }
951 }
952
953 ////////////////////////////////////////////////////////////////////////
954 //
955 // Description:
956 // Figure out how much to offset the given line of text. The X
957 // offset depends on the justification and the width of the string
958 // in the current font. The Y offset depends on the line spacing
959 // and font height.
960 //
961 // Use: private
962
963 SbVec2f
964 SoText3::getStringOffset(int line)
965 //
966 ////////////////////////////////////////////////////////////////////////
967 {
968 SbVec2f result(0,0);
969
970 if (justification.getValue() == RIGHT) {
971 float width = myFont->getWidth(line);
972 result[0] = -width;
973 }
974 if (justification.getValue() == CENTER) {
975 float width = myFont->getWidth(line);
976 result[0] = -width/2.0;
977 }
978 result[1] = -line*myFont->getHeight()*spacing.getValue();
979
980 return result;
981 }
982
983 ////////////////////////////////////////////////////////////////////////
984 //
985 // Description:
986 // Figure out where a given character starts.
987 //
988 // Use: private
989
990 SbVec2f
991 SoText3::getCharacterOffset(int line, int whichChar)
992 //
993 ////////////////////////////////////////////////////////////////////////
994 {
995 SbVec2f result = getStringOffset(line);
996
997 const char *chars = myFont->getUCSString(line);
998
999 // Now add on all of the character advances up to char:
1000 for (int i = 0; i < whichChar; i++) {
1001 result += myFont->getCharOffset(chars+2*i);
1002 }
1003 return result;
1004 }
1005
1006 ////////////////////////////////////////////////////////////////////////
1007 //
1008 // Description:
1009 // Render the fronts of the given string. The GL transformation
1010 // matrix is munged by this routine-- surround it by
1011 // PushMatrix/PopMatrix.
1012 //
1013 // Use: private, internal
1014
1015 void
1016 SoText3::renderFront(SoGLRenderAction *, int line,
1017 gluTESSELATOR *tobj)
1018 //
1019 ////////////////////////////////////////////////////////////////////////
1020 {
1021 const char *chars = myFont->getUCSString(line);
1022
1023 // First, try to figure out if we can use glCallLists:
1024 SbBool useCallLists = TRUE;
1025
1026 for (int i = 0; i < myFont->getNumUCSChars(line); i++) {
1027 // See if the font cache already has (or can build) a display
1028 // list for this character:
1029 if (!myFont->hasFrontDisplayList(chars+2*i, tobj)) {
1030 useCallLists = FALSE;
1031 break;
1032 }
1033 }
1034 // if we have display lists for all of the characters, use
1035 // glCallLists:
1036 if (useCallLists) {
1037 myFont->callFrontLists(line);
1038 }
1039 // if we don't, draw the string character-by-character, using the
1040 // display lists we do have:
1041 else {
1042 myFont->renderFront(line, tobj);
1043 }
1044 }
1045
1046 ////////////////////////////////////////////////////////////////////////
1047 //
1048 // Description:
1049 // Render the sides of the given string. The GL transformation
1050 // matrix is munged by this routine-- surround it by
1051 // PushMatrix/PopMatrix.
1052 //
1053 // Use: private
1054
1055 void
1056 SoText3::renderSide(SoGLRenderAction *, int line)
1057 //
1058 ////////////////////////////////////////////////////////////////////////
1059 {
1060 const char *chars = myFont->getUCSString(line);
1061
1062 // First, try to figure out if we can use glCallLists:
1063 SbBool useCallLists = TRUE;
1064
1065 for (int i = 0; i < myFont->getNumUCSChars(line); i++) {
1066 // See if the font cache already has (or can build) a display
1067 // list for this character:
1068 if (!myFont->hasSideDisplayList(chars+2*i, renderSideTris)) {
1069 useCallLists = FALSE;
1070 break;
1071 }
1072 }
1073 // if we have display lists for all of the characters, use
1074 // glCallLists:
1075 if (useCallLists) {
1076 myFont->callSideLists(line);
1077 }
1078 // if we don't, draw the string character-by-character, using the
1079 // display lists we do have:
1080 else {
1081 myFont->renderSide(line, renderSideTris);
1082 }
1083 }
1084
1085 ////////////////////////////////////////////////////////////////////////
1086 //
1087 // Description:
1088 // Create text detail and fill in extra info.
1089 //
1090 // Use: protected, virtual
1091
1092 SoDetail *
1093 SoText3::createTriangleDetail(SoRayPickAction *,
1094 const SoPrimitiveVertex *v1,
1095 const SoPrimitiveVertex *,
1096 const SoPrimitiveVertex *,
1097 SoPickedPoint *)
1098 //
1099 ////////////////////////////////////////////////////////////////////////
1100 {
1101 SoTextDetail *result = new SoTextDetail;
1102 const SoTextDetail *old = (const SoTextDetail *)v1->getDetail();
1103
1104 result->setPart(old->getPart());
1105 result->setStringIndex(old->getStringIndex());
1106 result->setCharacterIndex(old->getCharacterIndex());
1107
1108 return result;
1109 }
1110
1111 ////////////////////////////////////////////////////////////////////////
1112 //
1113 // Description:
1114 // Generates primitives for the fronts of characters. Assumes that
1115 // genTranslate has been set to the starting position of the
1116 // string, and that the genPrimVerts array points to three
1117 // appropriate vertices.
1118 //
1119 // Use: private internal
1120
1121 void
1122 SoText3::generateFront(int line)
1123 //
1124 ////////////////////////////////////////////////////////////////////////
1125 {
1126 static gluTESSELATOR *tobj = NULL;
1127
1128 const char *chars = myFont->getUCSString(line);
1129
1130 if (tobj == NULL) {
1131 tobj = gluNewTess();
1132 gluTessCallback(tobj, (GLenum)GLU_BEGIN, (void (*)())SoText3::beginCB);
1133 gluTessCallback(tobj, (GLenum)GLU_END, (void (*)())SoText3::endCB);
1134 gluTessCallback(tobj, (GLenum)GLU_VERTEX, (void (*)())SoText3::vtxCB);
1135 gluTessCallback(tobj, (GLenum)GLU_ERROR,
1136 (void (*)())SoOutlineFontCache::errorCB);
1137 }
1138
1139 genWhichVertex = 0;
1140
1141 SoTextDetail *d = (SoTextDetail *)genPrimVerts[0]->getDetail();
1142
1143 for (int i = 0; i < myFont->getNumUCSChars(line); i++) {
1144 d->setCharacterIndex(i);
1145
1146 myFont->generateFrontChar(chars+2*i, tobj);
1147
1148 SbVec2f p = myFont->getCharOffset(chars+2*i);
1149 genTranslate[0] += p[0];
1150 genTranslate[1] += p[1];
1151 }
1152 }
1153
1154 ////////////////////////////////////////////////////////////////////////
1155 //
1156 // Description:
1157 // Generates sides of the characters.
1158 //
1159 // Use: private internal
1160
1161 void
1162 SoText3::generateSide(int line)
1163 //
1164 ////////////////////////////////////////////////////////////////////////
1165 {
1166 const char *chars = myFont->getUCSString(line);
1167
1168 SoTextDetail *d = (SoTextDetail *)genPrimVerts[0]->getDetail();
1169
1170 for (int i = 0; i < myFont->getNumUCSChars(line); i++) {
1171 d->setCharacterIndex(i);
1172
1173 myFont->generateSideChar(chars+2*i, generateSideTris);
1174
1175 SbVec2f p = myFont->getCharOffset(chars+2*i);
1176 genTranslate[0] += p[0];
1177 genTranslate[1] += p[1];
1178 }
1179 }
1180
1181 ////////////////////////////////////////////////////////////////////////
1182 //
1183 // Description:
1184 // Given two correctly rotated and positioned bevels, this routine
1185 // fills in the triangles in between them.
1186 //
1187 // Use: private, static
1188
1189 void
1190 SoText3::generateSideTris(int nPoints, const SbVec3f *p1, const SbVec3f *n1,
1191 const SbVec3f *p2, const SbVec3f *n2,
1192 const float *sTexCoords, const float *tTexCoords)
1193 //
1194 ////////////////////////////////////////////////////////////////////////
1195 {
1196 float vertex[3];
1197 SbVec4f texCoord(0,0,0,1);
1198
1199 const SbVec3f *p[2]; p[0] = p1; p[1] = p2;
1200 const SbVec3f *n[2]; n[0] = n1; n[1] = n2;
1201
1202 // Handy little macro to set a primitiveVertice's point, normal, and
1203 // texture coordinate:
1204 #define SET(pv,i,row,col) \
1205 {vertex[0] = p[col][i+row][0] + genTranslate[0]; \
1206 vertex[1] = p[col][i+row][1] + genTranslate[1]; \
1207 vertex[2] = p[col][i+row][2]; \
1208 genPrimVerts[pv]->setPoint(vertex);\
1209 genPrimVerts[pv]->setNormal(n[col][i*2+row]); \
1210 texCoord[0] = sTexCoords[i+row]; \
1211 texCoord[1] = tTexCoords[col]; \
1212 genPrimVerts[pv]->setTextureCoords(texCoord); \
1213 }
1214
1215 SoText3 *t3 = currentGeneratingNode;
1216
1217 for (int i = 0; i < nPoints-1; i++) {
1218 // First triangle:
1219 SET(0, i, 0, 0)
1220 SET(1, i, 1, 0)
1221 SET(2, i, 0, 1)
1222 t3->invokeTriangleCallbacks(genAction, genPrimVerts[0],
1223 genPrimVerts[1], genPrimVerts[2]);
1224
1225 // Second triangle:
1226 SET(0, i, 1, 1)
1227 SET(1, i, 0, 1)
1228 SET(2, i, 1, 0)
1229 t3->invokeTriangleCallbacks(genAction, genPrimVerts[0],
1230 genPrimVerts[1], genPrimVerts[2]);
1231 #undef SET
1232 }
1233 }
1234 ////////////////////////////////////////////////////////////////////////
1235 //
1236 // Description:
1237 // Given two correctly rotated and positioned bevels, this routine
1238 // renders triangles in between them.
1239 //
1240 // Use: private, static
1241
1242 void
1243 SoText3::renderSideTris(int nPoints, const SbVec3f *p1, const SbVec3f *n1,
1244 const SbVec3f *p2, const SbVec3f *n2,
1245 const float *sTex, const float *tTex)
1246 //
1247 ////////////////////////////////////////////////////////////////////////
1248 {
1249 // Note: the glBegin(GL_QUADS) is optimized up into the
1250 // routine that calls generateSideChar, so there is one glBegin
1251 // per character.
1252 for (int i = 0; i < nPoints-1; i++) {
1253 if (genTexCoord) glTexCoord2f(sTex[i+1], tTex[0]);
1254 glNormal3fv(n1[i*2+1].getValue());
1255 glVertex3fv(p1[i+1].getValue());
1256
1257 if (genTexCoord) glTexCoord2f(sTex[i+1], tTex[1]);
1258 glNormal3fv(n2[i*2+1].getValue());
1259 glVertex3fv(p2[i+1].getValue());
1260
1261 if (genTexCoord) glTexCoord2f(sTex[i], tTex[1]);
1262 glNormal3fv(n2[i*2].getValue());
1263 glVertex3fv(p2[i].getValue());
1264
1265 if (genTexCoord) glTexCoord2f(sTex[i], tTex[0]);
1266 glNormal3fv(n1[i*2].getValue());
1267 glVertex3fv(p1[i].getValue());
1268 }
1269 }
1270
1271 ////////////////////////////////////////////////////////////////////////
1272 //
1273 // Description:
1274 // Called by the GLU tesselator when we are beginning a triangle
1275 // strip, fan, or set of independent triangles.
1276 //
1277 // Use: static, private
1278
1279 void
1280 SoText3::beginCB(GLenum primType)
1281 //
1282 ////////////////////////////////////////////////////////////////////////
1283 {
1284 genPrimType = primType;
1285 genWhichVertex = 0;
1286 }
1287
1288 ////////////////////////////////////////////////////////////////////////
1289 //
1290 // Description:
1291 // Called by the GLU tesselator when we are done with the
1292 // strip/fan/etc.
1293 //
1294 // Use: static, private
1295
1296 void
1297 SoText3::endCB()
1298 //
1299 ////////////////////////////////////////////////////////////////////////
1300 {
1301 genWhichVertex = 0;
1302 }
1303
1304 ////////////////////////////////////////////////////////////////////////
1305 //
1306 // Description:
1307 // Called by the GLU tesselator when we are generating primitives.
1308 //
1309 // Use: static, private
1310
1311 void
1312 SoText3::vtxCB(void *v)
1313 //
1314 ////////////////////////////////////////////////////////////////////////
1315 {
1316 SbVec2f &vv = *((SbVec2f *)v);
1317 float vertex[3];
1318 vertex[0] = vv[0] + genTranslate[0];
1319 vertex[1] = vv[1] + genTranslate[1];
1320 vertex[2] = genTranslate[2];
1321
1322 SoText3 *t3 = currentGeneratingNode;
1323
1324 // Fill in one of the primitive vertices:
1325 genPrimVerts[genWhichVertex]->setPoint(vertex);
1326
1327 SbVec4f texCoord;
1328
1329 // And texture coordinates:
1330 if (genTexCoord) {
1331 float textHeight = t3->myFont->getHeight();
1332 texCoord.setValue(vertex[0]/textHeight, vertex[1]/textHeight,
1333 0.0, 1.0);
1334 // S coordinates go other way on back...
1335 if (genBack) texCoord[0] = -texCoord[0];
1336 } else {
1337 texCoord = tce->get(vertex, genPrimVerts[0]->getNormal());
1338 }
1339 genPrimVerts[genWhichVertex]->setTextureCoords(texCoord);
1340
1341 genWhichVertex = (genWhichVertex+1)%3;
1342
1343 // If we just filled in the third vertex, we can spit out a
1344 // triangle:
1345 if (genWhichVertex == 0) {
1346 // If we are doing the BACK part, reverse the triangle:
1347 if (genBack) {
1348 t3->invokeTriangleCallbacks(genAction,
1349 genPrimVerts[2],
1350 genPrimVerts[1],
1351 genPrimVerts[0]);
1352 } else {
1353 t3->invokeTriangleCallbacks(genAction,
1354 genPrimVerts[0],
1355 genPrimVerts[1],
1356 genPrimVerts[2]);
1357 }
1358 // Now, need to set-up for the next vertex.
1359 // Three cases to deal with-- independent triangles, triangle
1360 // strips, and triangle fans.
1361 switch (genPrimType) {
1362 case GL_TRIANGLES:
1363 // Don't need to do anything-- every three vertices
1364 // defines a triangle.
1365 break;
1366
1367 // Useful macro:
1368 #define SWAP(a, b) { SoPrimitiveVertex *t = a; a = b; b = t; }
1369
1370 case GL_TRIANGLE_FAN:
1371 // For triangle fans, vertex zero stays the same, but
1372 // vertex 2 becomes vertex 1, and the next vertex to come
1373 // in will replace vertex 2 (the old vertex 1).
1374 SWAP(genPrimVerts[1], genPrimVerts[2]);
1375 genWhichVertex = 2;
1376 break;
1377
1378 case GL_TRIANGLE_STRIP:
1379 // For triangle strips, vertex 1 becomes vertex 0, vertex
1380 // 2 becomes vertex 1, and the new triangle will replace
1381 // vertex 2 (the old vertex 0).
1382 SWAP(genPrimVerts[1], genPrimVerts[0]);
1383 SWAP(genPrimVerts[2], genPrimVerts[1]);
1384 genWhichVertex = 2;
1385 break;
1386 #undef SWAP
1387 }
1388 }
1389 }
1390
1391
1392 ////////////////////////////////////////////////////////////////////////
1393 //
1394 // Description:
1395 // Find an appropriate font, given a state. A bunch of elements
1396 // (fontName, fontSize, creaseAngle, complexity and profile) must
1397 // be enabled in the state...
1398 //
1399 // Use: static, internal
1400
1401 SoOutlineFontCache *
1402 SoOutlineFontCache::getFont(SoState *state, SbBool forRender)
1403 //
1404 ////////////////////////////////////////////////////////////////////////
1405 {
1406 if (fonts == NULL) {
1407 // One-time font library initialization
1408 fonts = new SbPList;
1409 context = flCreateContext(NULL, FL_FONTNAME, NULL,
1410 1.0, 1.0);
1411 if (context == NULL) {
1412 #ifdef DEBUG
1413 SoDebugError::post("SoText3::getFont",
1414 "flCreateContext returned NULL");
1415 #endif
1416 return NULL;
1417 }
1418 flMakeCurrentContext(context);
1419 flSetHint(FL_HINT_FONTTYPE, FL_FONTTYPE_OUTLINE);
1420 }
1421 else if (context == NULL) return NULL;
1422 else {
1423 if (flGetCurrentContext() != context)
1424 flMakeCurrentContext(context);
1425 }
1426
1427 SoOutlineFontCache *result = NULL;
1428 for (int i = 0; i < fonts->getLength() && result == NULL; i++) {
1429 SoOutlineFontCache *c = (SoOutlineFontCache *) (*fonts)[i];
1430 if (forRender ? c->isRenderValid(state) : c->isValid(state)) {
1431 result = c; // Loop will terminate...
1432 result->ref(); // Increment ref count
1433 }
1434 }
1435 // If none match:
1436 if (result == NULL) {
1437 result = new SoOutlineFontCache(state);
1438 result->ref();
1439
1440 }
1441 return result;
1442 }
1443 ////////////////////////////////////////////////////////////////////////
1444 //
1445 // Description:
1446 // Create a list of font numbers from a list of font names
1447 //
1448 // Use: private
1449
1450 GLubyte *
1451 SoOutlineFontCache::createUniFontList(const char* fontNameList)
1452 //
1453 ////////////////////////////////////////////////////////////////////////
1454 {
1455 char *s, *s1, *ends;
1456 FLfontNumber fn;
1457 float mat[2][2];
1458
1459 mat[0][0] = mat[1][1] = 1.0;
1460 mat[0][1] = mat[1][0] = 0.0;
1461
1462 //Make a copy of fontNameList so we don't disturb the one we are passed.
1463 //Find \n at end of namelist:
1464 char * nameCopy = new char[strlen(fontNameList)+1+1];
1465 strcpy(nameCopy, fontNameList);
1466
1467 //find the last null in nameCopy.
1468 ends = (char *)strrchr(nameCopy, '\0');
1469 strcat(nameCopy, ";"); /* put a guard in the end of string */
1470
1471 s = (char*)nameCopy;
1472 fontNums = new SbPList;
1473
1474 while (s1 = (char *)strchr(s, ';')) {
1475 *s1 = (char)NULL; /* font name is pointed to s */
1476
1477 if ((fn = flCreateFont((const GLubyte*)s, mat, 0, NULL)) == (FLfontNumber)0) {
1478 #ifdef DEBUG
1479 SoDebugError::post("SoOutlineFontCache::createUniFontList",
1480 "Cannot create font %s", s);
1481 #endif
1482 }
1483 else fontNums->append((void*)(intptr_t)fn);
1484 if(s1 == ends) break;
1485 s = (s1 + 1); /* move to next font name */
1486 }
1487
1488 if (fontNums->getLength() == 0 ) return NULL;
1489
1490 // create a comma-separated list of font numbers:
1491 char *fontList = new char[10*fontNums->getLength()];
1492 fontList[0] = '\0';
1493 for (int i = 0; i< fontNums->getLength(); i++ ){
1494 fn = (FLfontNumber)(intptr_t)(*fontNums)[i];
1495 sprintf(&fontList[strlen(fontList)], "%"PRIiPTR",", (intptr_t)fn);
1496 }
1497 fontList[strlen(fontList) - 1] = '\0'; // the last ',' is replaced with NULL
1498
1499 delete [] nameCopy;
1500
1501 return (GLubyte *)fontList;
1502
1503 }
1504 ////////////////////////////////////////////////////////////////////////
1505 //
1506 // Description:
1507 // Sees if this font is valid. If it is valid, it also makes it
1508 // current.
1509 //
1510 // Use: public
1511
1512 SbBool
1513 SoOutlineFontCache::isValid(const SoState *state) const
1514 //
1515 ////////////////////////////////////////////////////////////////////////
1516 {
1517 SbBool result = SoCache::isValid(state);
1518
1519 if (result) {
1520 if (flGetCurrentContext() != context) {
1521 flMakeCurrentContext(context);
1522 }
1523 }
1524 return result;
1525 }
1526
1527 ////////////////////////////////////////////////////////////////////////
1528 //
1529 // Description:
1530 // Figures out if this cache is valid for rendering.
1531 //
1532 // Use: internal
1533
1534 SbBool
1535 SoOutlineFontCache::isRenderValid(SoState *state) const
1536 //
1537 ////////////////////////////////////////////////////////////////////////
1538 {
1539 // Special cache case here: if we generated side display lists
1540 // without texture coordinates AND we need texture coordinates,
1541 // we'll have to regenerate and this cache is invalid:
1542 if (sideList) {
1543 if (!sidesHaveTexCoords &&
1544 SoGLTextureEnabledElement::get(state)) {
1545 return FALSE;
1546 }
1547 }
1548
1549 if (!isValid(state)) return FALSE;
1550
1551 if (frontList &&
1552 frontList->getContext() != SoGLCacheContextElement::get(state))
1553 return FALSE;
1554 if (sideList &&
1555 sideList->getContext() != SoGLCacheContextElement::get(state))
1556 return FALSE;
1557
1558 return TRUE;
1559 }
1560
1561 ////////////////////////////////////////////////////////////////////////
1562 //
1563 // Description:
1564 // Constructor. Called by getFont().
1565 //
1566 // Use: private
1567
1568 SoOutlineFontCache::SoOutlineFontCache(SoState *state) :
1569 SoCache(state)
1570 //
1571 ////////////////////////////////////////////////////////////////////////
1572 {
1573 ref();
1574
1575 frontList = sideList = NULL;
1576
1577 // Add element dependencies explicitly here; making 'this' the
1578 // CacheElement doesn't work if we are being constructed in an
1579 // action that doesn't have caches.
1580 SbName font = SoFontNameElement::get(state);
1581 addElement(state->getConstElement(
1582 SoFontNameElement::getClassStackIndex()));
1583 if (font == SoFontNameElement::getDefault()) {
1584 font = SbName("Utopia-Regular");
1585 }
1586
1587 float uems;
1588
1589 // Remember size
1590 fontSize = SoFontSizeElement::get(state);
1591 addElement(state->getConstElement(
1592 SoFontSizeElement::getClassStackIndex()));
1593
1594 // Figure out complexity...
1595 float complexity = SoComplexityElement::get(state);
1596 addElement(state->getConstElement(
1597 SoComplexityElement::getClassStackIndex()));
1598 addElement(state->getConstElement(
1599 SoComplexityTypeElement::getClassStackIndex()));
1600
1601 switch (SoComplexityTypeElement::get(state)) {
1602 case SoComplexityTypeElement::OBJECT_SPACE:
1603 {
1604 // Two ramps-- complexity of zero == 250/1000 of an em
1605 // complexity of .5 == 20/1000 of an em
1606 // complexity of 1 == 1/1000 of an em
1607 const float ZERO = 250;
1608 const float HALF = 20;
1609 const float ONE = 1;
1610 if (complexity > 0.5) uems = (2.0-complexity*2.0)*(HALF-ONE)+ONE;
1611 else uems = (1.0-complexity*2.0)*(ZERO-HALF)+HALF;
1612 }
1613 break;
1614
1615 case SoComplexityTypeElement::SCREEN_SPACE:
1616 {
1617 SbVec3f p(fontSize, fontSize, fontSize);
1618 SbVec2s rectSize;
1619
1620 SoShape::getScreenSize(state, SbBox3f(-p, p), rectSize);
1621 float maxSize =
1622 (rectSize[0] > rectSize[1] ? rectSize[0] : rectSize[1]);
1623 uems = 250.0 / (1.0 + 0.25 * maxSize * complexity *
1624 complexity);
1625
1626 // We have to manually add the dependency on the
1627 // projection, view and model matrix elements (these are
1628 // gotten in the SoShape::getScreenSize routine), and the
1629 // ViewportRegionElement:
1630 addElement(state->getConstElement(
1631 SoProjectionMatrixElement::getClassStackIndex()));
1632 addElement(state->getConstElement(
1633 SoViewingMatrixElement::getClassStackIndex()));
1634 addElement(state->getConstElement(
1635 SoModelMatrixElement::getClassStackIndex()));
1636 addElement(state->getConstElement(
1637 SoViewportRegionElement::getClassStackIndex()));
1638 }
1639 break;
1640
1641 case SoComplexityTypeElement::BOUNDING_BOX:
1642 {
1643 uems = 20;
1644 }
1645 break;
1646 }
1647 flSetHint(FL_HINT_TOLERANCE, uems);
1648
1649 fontNumList = createUniFontList(font.getString());
1650
1651 // If error creating font:
1652 if (fontNumList == NULL) {
1653 // Try Utopia-Regular, unless we just did!
1654 if (font != SbName("Utopia-Regular")) {
1655 #ifdef DEBUG
1656 SoDebugError::post("SoText3::getFont",
1657 "Couldn't find font %s, replacing with Utopia-Regular",
1658 font.getString());
1659 #endif
1660 fontNumList = createUniFontList("Utopia-Regular");
1661 }
1662 if (fontNumList == NULL) {
1663 #ifdef DEBUG
1664 SoDebugError::post("SoText3::getFont",
1665 "Couldn't find font Utopia-Regular!");
1666 #endif
1667 }
1668 }
1669
1670 numChars = 65536; //Allow for all UCS-2 possibilities.
1671 sidesHaveTexCoords = FALSE;
1672 currentNodeId = 0; //guarantee UCS translation occurs first time.
1673
1674 //sideDict and frontDict indicate if display lists exist for front,sides
1675 //outlineDict has pointer to outline.
1676 sideDict = new SbDict;
1677 frontDict = new SbDict;
1678 outlineDict = new SbDict;
1679
1680 // Get profile info:
1681 const SoNodeList &profiles = SoProfileElement::get(state);
1682 addElement(state->getConstElement(
1683 SoProfileElement::getClassStackIndex()));
1684 addElement(state->getConstElement(
1685 SoProfileCoordinateElement::getClassStackIndex()));
1686 nProfileVerts = 0;
1687 if (profiles.getLength() > 0) {
1688 SoProfile *profileNode = (SoProfile *)profiles[0];
1689 profileNode->getVertices(state, nProfileVerts, profileVerts);
1690 } else {
1691 nProfileVerts = 2;
1692 profileVerts = new SbVec2f[2];
1693 profileVerts[0].setValue(0, 0);
1694 profileVerts[1].setValue(1, 0);
1695 }
1696
1697 if (nProfileVerts > 1) {
1698 cosCreaseAngle = cos(SoCreaseAngleElement::get(state));
1699 addElement(state->getConstElement(
1700 SoCreaseAngleElement::getClassStackIndex()));
1701 int nSegments = (int) nProfileVerts - 1;
1702
1703 // Figure out normals for profiles; there are twice as many
1704 // normals as segments. The two normals for each segment endpoint
1705 // may be averaged with the normal for the next segment, depending
1706 // on whether or not the angle between the segments is greater
1707 // than the creaseAngle.
1708 profileNorms = new SbVec2f[nSegments*2];
1709 figureSegmentNorms(profileNorms, (int) nProfileVerts, profileVerts,
1710 cosCreaseAngle, FALSE);
1711 // Need to flip all the normals because of the way the profiles
1712 // are defined:
1713 int i;
1714 for (i = 0; i < nSegments*2; i++) {
1715 profileNorms[i] *= -1.0;
1716 }
1717
1718 // Figure out S texture coordinates, which run along the profile:
1719 sTexCoords = new float[nProfileVerts];
1720 figureSegmentTexCoords(sTexCoords, (int) nProfileVerts,
1721 profileVerts, FALSE);
1722 // And reverse them, so 0 is at the back of the profile:
1723 float max = sTexCoords[nProfileVerts-1];
1724 for (i = 0; i < nProfileVerts; i++) {
1725 sTexCoords[i] = max - sTexCoords[i];
1726 }
1727 } else {
1728 profileNorms = NULL;
1729 sTexCoords = NULL;
1730 }
1731
1732 fonts->append(this);
1733 }
1734
1735 ////////////////////////////////////////////////////////////////////////
1736 //
1737 // Description:
1738 // Destructor
1739 //
1740 // Use: private
1741
1742 SoOutlineFontCache::~SoOutlineFontCache()
1743 //
1744 ////////////////////////////////////////////////////////////////////////
1745 {
1746 if (fontNumList) {
1747 if (flGetCurrentContext() != context) {
1748 flMakeCurrentContext(context);
1749 }
1750
1751 // Free up cached outlines, display lists
1752
1753 if (hasProfile()) {
1754 delete[] profileVerts;
1755 delete[] sTexCoords;
1756 delete[] profileNorms;
1757 }
1758 //Must free every outline in dictionary:
1759
1760 outlineDict->applyToAll(freeOutline);
1761
1762 // Only destroy the font library font if no other font caches
1763 // are using the same font identifier:
1764 // Must go through fontlist and destroy every font that isn't used
1765 // by any other cache.
1766
1767 SbBool otherFonts = (fonts->getLength() > 1);
1768 SbDict *otherFontDict;
1769 if (otherFonts){
1770 otherFontDict = new SbDict;
1771 //Enter all the other fontnums into the dictionary:
1772 for (int i = 0; i< fonts->getLength(); i++) {
1773 SoOutlineFontCache *t = (SoOutlineFontCache *)(*fonts)[i];
1774 if ( t == this) continue;
1775 for (int j = 0; j< (t->fontNums->getLength()); j++){
1776 unsigned long key = (unsigned long)(*(t->fontNums))[j];
1777 otherFontDict->enter(key, NULL);
1778 }
1779 }
1780 }
1781 // Now destroy any fonts that don't appear in otherFontDict
1782 for (int i = 0; i < fontNums->getLength(); i++){
1783 void *value;
1784 if ( !otherFonts ||
1785 !otherFontDict->find((unsigned long)(*fontNums)[i], value)){
1786 flDestroyFont((FLfontNumber)(unsigned long)(*fontNums)[i]);
1787 }
1788 }
1789 if (otherFonts) delete otherFontDict;
1790 delete frontDict;
1791 delete sideDict;
1792 delete outlineDict;
1793
1794 if (fontNumList) delete [] fontNumList;
1795 if (fontNums) delete fontNums;
1796
1797 fonts->remove(fonts->find(this));
1798 }
1799 }
1800 ////////////////////////////////////////////////////////////////////////
1801 //
1802 // Description:
1803 // Destroy this cache. Called by unref(); frees up OpenGL display
1804 // lists.
1805 //
1806 // Use: protected, virtual
1807
1808 void
1809 SoOutlineFontCache::destroy(SoState *)
1810 //
1811 ////////////////////////////////////////////////////////////////////////
1812 {
1813 // Pass in NULL to unref because this cache may be destroyed
1814 // from an action _other_ than GLRender:
1815 if (frontList) {
1816 frontList->unref(NULL);
1817 frontList = NULL;
1818 }
1819 if (sideList) {
1820 sideList->unref(NULL);
1821 sideList = NULL;
1822 }
1823 SoCache::destroy(NULL);
1824 }
1825
1826 ////////////////////////////////////////////////////////////////////////
1827 //
1828 // Description:
1829 // Returns the width of the specified line in the cache.
1830 //
1831 // Use: private
1832
1833 float
1834 SoOutlineFontCache::getWidth(int line)
1835 //
1836 ////////////////////////////////////////////////////////////////////////
1837 {
1838 float total = 0.0;
1839 const char *chars = getUCSString(line);
1840
1841 for (int i = 0; i < getNumUCSChars(line); i++) {
1842 SoFontOutline *outline = getOutline(chars+2*i);
1843 total += outline->getCharAdvance()[0];
1844 }
1845
1846 return total;
1847 }
1848
1849 ////////////////////////////////////////////////////////////////////////
1850 //
1851 // Description:
1852 // Returns the 2D bounding box of the given character.
1853 //
1854 // Use: private
1855
1856 void
1857 SoOutlineFontCache::getCharBBox(const char* c, SbBox2f &result)
1858 //
1859 ////////////////////////////////////////////////////////////////////////
1860 {
1861 result.makeEmpty();
1862
1863 if (!fontNumList) return;
1864
1865 SoFontOutline *outline = getOutline(c);
1866
1867 for (int i = 0; i < outline->getNumOutlines(); i++) {
1868 for (int j = 0; j < outline->getNumVerts(i); j++) {
1869 result.extendBy(outline->getVertex(i,j));
1870 }
1871 }
1872 }
1873
1874 ////////////////////////////////////////////////////////////////////////
1875 //
1876 // Description:
1877 // Given a UCS character, return an outline for the character. If, for
1878 // some reason, we can't get the outline, an 'identity' or 'null'
1879 // outline is returned.
1880 //
1881 // Use: private
1882
1883 SoFontOutline *
1884 SoOutlineFontCache::getOutline(const char* c)
1885 //
1886 ////////////////////////////////////////////////////////////////////////
1887 {
1888 if (!fontNumList) {
1889 return SoFontOutline::getNullOutline();
1890 }
1891 unsigned char *uc = (unsigned char*)c;
1892 long key = (uc[0]<<8)|uc[1];
1893 void *value;
1894 if (!outlineDict->find(key, value)){
1895
1896 FLoutline *flo = flUniGetOutline(fontNumList, (GLubyte*)c);
1897 if (flo == NULL) {
1898 value = (void*)SoFontOutline::getNullOutline();
1899 } else {
1900 value = (void*) new SoFontOutline(flo, fontSize);
1901 flFreeOutline(flo);
1902 }
1903 outlineDict->enter(key, value);
1904 }
1905 return (SoFontOutline*)value;
1906 }
1907
1908 ////////////////////////////////////////////////////////////////////////
1909 //
1910 // Description:
1911 // Given a character, return the correct amount to advance after
1912 // drawing that character. Note: if we ever wanted to deal with
1913 // kerning, we'd have to fix this...
1914 //
1915 // Use: private
1916
1917 SbVec2f
1918 SoOutlineFontCache::getCharOffset(const char* c)
1919 //
1920 ////////////////////////////////////////////////////////////////////////
1921 {
1922 if (!fontNumList) return SbVec2f(0,0);
1923
1924 return getOutline(c)->getCharAdvance();
1925 }
1926
1927 ////////////////////////////////////////////////////////////////////////
1928 //
1929 // Description:
1930 // Render the fronts of the given string. The GL transformation
1931 // matrix is munged by this routine-- surround it by
1932 // PushMatrix/PopMatrix.
1933 //
1934 // Use: public, internal
1935
1936 void
1937 SoOutlineFontCache::generateFrontChar(const char* c,
1938 gluTESSELATOR *tobj)
1939 //
1940 ////////////////////////////////////////////////////////////////////////
1941 {
1942 if (!fontNumList) return;
1943
1944 GLdouble v[3];
1945
1946 tesselationError = FALSE;
1947 #ifdef GLU_VERSION_1_2
1948 gluTessBeginPolygon(tobj, NULL);
1949 gluTessBeginContour(tobj);
1950 #else
1951 gluBeginPolygon(tobj);
1952 #endif
1953
1954 // Get outline for character
1955 SoFontOutline *outline = getOutline(c);
1956 int i;
1957 for (i = 0; i < outline->getNumOutlines(); i++) {
1958
1959 // It would be nice if the font manager told us the type of
1960 // each outline...
1961 #ifdef GLU_VERSION_1_2
1962 gluTessEndContour(tobj);
1963 gluTessBeginContour(tobj);
1964 #else
1965 gluNextContour(tobj, (GLenum)GLU_UNKNOWN);
1966 #endif
1967
1968 for (int j = 0; j < outline->getNumVerts(i); j++) {
1969 SbVec2f &t = outline->getVertex(i,j);
1970 v[0] = t[0];
1971 v[1] = t[1];
1972 v[2] = 0.0;
1973
1974 // Note: The third argument MUST NOT BE a local variable,
1975 // since glu just stores the pointer and only calls us
1976 // back at the gluEndPolygon call.
1977 gluTessVertex(tobj, v, &t);
1978 }
1979 }
1980 #ifdef GLU_VERSION_1_2
1981 gluTessEndContour(tobj);
1982 gluTessEndPolygon(tobj);
1983 #else
1984 gluEndPolygon(tobj);
1985 #endif
1986
1987 // If there was an error tesselating the character, just generate
1988 // a bounding box for the character:
1989 if (tesselationError) {
1990 SbBox2f charBBox;
1991 getCharBBox(c, charBBox);
1992 if (!charBBox.isEmpty()) {
1993 SbVec2f boxVerts[4];
1994 charBBox.getBounds(boxVerts[0], boxVerts[2]);
1995 boxVerts[1].setValue(boxVerts[2][0], boxVerts[0][1]);
1996 boxVerts[3].setValue(boxVerts[0][0], boxVerts[2][1]);
1997
1998 #ifdef GLU_VERSION_1_2
1999 gluTessBeginPolygon(tobj, NULL);
2000 gluTessBeginContour(tobj);
2001 #else
2002 gluBeginPolygon(tobj);
2003 #endif
2004 for (i = 0; i < 4; i++) {
2005 v[0] = boxVerts[i][0];
2006 v[1] = boxVerts[i][1];
2007 v[2] = 0.0;
2008 gluTessVertex(tobj, v, &boxVerts[i]);
2009 }
2010 #ifdef GLU_VERSION_1_2
2011 gluTessEndContour(tobj);
2012 gluTessEndPolygon(tobj);
2013 #else
2014 gluEndPolygon(tobj);
2015 #endif
2016 }
2017 }
2018 }
2019
2020 ////////////////////////////////////////////////////////////////////////
2021 //
2022 // Description:
2023 // Sets up for GL rendering.
2024 //
2025 // Use: internal
2026
2027 void
2028 SoOutlineFontCache::setupToRenderFront(SoState *state)
2029 //
2030 ////////////////////////////////////////////////////////////////////////
2031 {
2032 otherOpen = SoCacheElement::anyOpen(state);
2033 if (!otherOpen && !frontList) {
2034 frontList = new SoGLDisplayList(state,
2035 SoGLDisplayList::DISPLAY_LIST,
2036 numChars);
2037 frontList->ref();
2038 }
2039 if (frontList) {
2040 // Set correct list base
2041 glListBase(frontList->getFirstIndex());
2042 frontList->addDependency(state);
2043 }
2044 }
2045
2046 ////////////////////////////////////////////////////////////////////////
2047 //
2048 // Description:
2049 // Sets up for GL rendering.
2050 //
2051 // Use: internal
2052
2053 void
2054 SoOutlineFontCache::setupToRenderSide(SoState *state, SbBool willTexture)
2055 //
2056 ////////////////////////////////////////////////////////////////////////
2057 {
2058 otherOpen = SoCacheElement::anyOpen(state);
2059 if (!otherOpen && !sideList) {
2060 sideList = new SoGLDisplayList(state,
2061 SoGLDisplayList::DISPLAY_LIST,
2062 numChars);
2063 sideList->ref();
2064 sidesHaveTexCoords = willTexture;
2065 }
2066 if (sideList) {
2067 // Set correct list base
2068 glListBase(sideList->getFirstIndex());
2069 sideList->addDependency(state);
2070 }
2071 }
2072
2073 ////////////////////////////////////////////////////////////////////////
2074 //
2075 // Description:
2076 // Returns TRUE if a display lists exists for given character.
2077 // Tries to build a display list, if it can.
2078 //
2079 // Use: internal
2080
2081 SbBool
2082 SoOutlineFontCache::hasFrontDisplayList(const char* c,
2083 gluTESSELATOR *tobj)
2084 //
2085 ////////////////////////////////////////////////////////////////////////
2086 {
2087 // If we have one, return TRUE
2088 unsigned char *uc = (unsigned char*)c;
2089 long key = (uc[0]<<8) | uc[1];
2090 void *value;
2091 if (frontDict->find(key, value)) return TRUE;
2092
2093 // If we don't and we can't build one, return FALSE.
2094 if (otherOpen) return FALSE;
2095
2096 // Build one:
2097 glNewList(frontList->getFirstIndex()+key, GL_COMPILE);
2098 generateFrontChar(c, tobj);
2099 SbVec2f t = getOutline(c)->getCharAdvance();
2100 glTranslatef(t[0], t[1], 0.0);
2101 glEndList();
2102
2103 frontDict->enter(key, value);
2104
2105 return TRUE;
2106 }
2107 ////////////////////////////////////////////////////////////////////////
2108 //
2109 // Description:
2110 // Returns TRUE if a display lists exists for given character.
2111 // Tries to build a display list, if it can.
2112 //
2113 // Use: internal
2114
2115 SbBool
2116 SoOutlineFontCache::hasSideDisplayList(const char* c,
2117 SideCB callbackFunc)
2118 //
2119 ////////////////////////////////////////////////////////////////////////
2120 {
2121 unsigned char *uc = (unsigned char*)c;
2122 long key = (uc[0]<<8) | uc[1];
2123 void *value;
2124 // If we have one, return TRUE
2125 if (sideDict->find(key, value)) return TRUE;
2126
2127 // If we don't and we can't build one, return FALSE.
2128 if (otherOpen) return FALSE;
2129
2130 // Build one:
2131 glNewList(sideList->getFirstIndex()+key, GL_COMPILE);
2132
2133 glBegin(GL_QUADS); // Render as independent quads:
2134 generateSideChar(c, callbackFunc);
2135 glEnd();
2136
2137 SbVec2f t = getOutline(c)->getCharAdvance();
2138 glTranslatef(t[0], t[1], 0.0);
2139 glEndList();
2140 sideDict->enter(key, value);
2141
2142 return TRUE;
2143 }
2144
2145 ////////////////////////////////////////////////////////////////////////
2146 //
2147 // Description:
2148 // Assuming that there are display lists built for all the
2149 // characters in given string, render them using the GL's CallLists
2150 // routine.
2151 //
2152 // Use: internal
2153
2154 void
2155 SoOutlineFontCache::callFrontLists(int line)
2156 //
2157 ////////////////////////////////////////////////////////////////////////
2158 {
2159 const char *str = getUCSString(line);
2160
2161 glCallLists(getNumUCSChars(line), GL_2_BYTES, (unsigned char*)str);
2162 }
2163
2164 ////////////////////////////////////////////////////////////////////////
2165 //
2166 // Description:
2167 // Assuming that there are display lists built for all the
2168 // characters in given line, render them using the GL's CallLists
2169 // routine.
2170 //
2171 // Use: internal
2172
2173 void
2174 SoOutlineFontCache::callSideLists(int line)
2175 //
2176 ////////////////////////////////////////////////////////////////////////
2177 {
2178 const char *str = getUCSString(line);
2179
2180 glCallLists(getNumUCSChars(line), GL_2_BYTES, (unsigned char*)str);
2181 }
2182
2183 ////////////////////////////////////////////////////////////////////////
2184 //
2185 // Description:
2186 // Assuming that there are not display lists built for all the
2187 // characters in given string, render the string.
2188 //
2189 // Use: internal
2190
2191 void
2192 SoOutlineFontCache::renderFront(int line,
2193 gluTESSELATOR *tobj)
2194 //
2195 ////////////////////////////////////////////////////////////////////////
2196 {
2197 const char *str = getUCSString(line);
2198 unsigned char *ustr = (unsigned char*)str;
2199
2200 void *value;
2201 for (int i = 0; i < getNumUCSChars(line); i++) {
2202 long key = ustr[2*i]<<8 | ustr[2*i+1];
2203 if (frontDict->find(key, value)) {
2204 glCallList(frontList->getFirstIndex()+key);
2205 }
2206 else {
2207 generateFrontChar(str+2*i, tobj);
2208 SbVec2f t = getOutline(str+2*i)->getCharAdvance();
2209 glTranslatef(t[0], t[1], 0.0);
2210 }
2211 }
2212 }
2213
2214 ////////////////////////////////////////////////////////////////////////
2215 //
2216 // Description:
2217 // Assuming that there are not display lists built for all the
2218 // characters in given line, render the line.
2219 //
2220 // Use: private internal
2221
2222 void
2223 SoOutlineFontCache::renderSide(int line,
2224 SideCB callbackFunc)
2225 //
2226 ////////////////////////////////////////////////////////////////////////
2227 {
2228 const char *str = getUCSString(line);
2229 unsigned char *ustr = (unsigned char*)str;
2230 void* value;
2231 for (int i = 0; i < getNumUCSChars(line); i++) {
2232 long key = (ustr[2*i]<<8)|ustr[2*i+1];
2233 if (sideDict->find(key, value)) {
2234 glCallList(sideList->getFirstIndex()+key);
2235 }
2236 else {
2237 glBegin(GL_QUADS);
2238 generateSideChar(str+2*i, callbackFunc);
2239 glEnd();
2240
2241 SbVec2f t = getOutline(str+2*i)->getCharAdvance();
2242 glTranslatef(t[0], t[1], 0.0);
2243 }
2244 }
2245 }
2246 ////////////////////////////////////////////////////////////////////////
2247 //
2248 // Description:
2249 // Convert MFString to UCS string, if necessary.
2250 //
2251 // Use: internal
2252
2253 void
2254 SoOutlineFontCache::convertToUCS(uint32_t nodeid,
2255 const SoMFString& strings)
2256 //
2257 ////////////////////////////////////////////////////////////////////////
2258 {
2259 if (nodeid == currentNodeId) return;
2260 currentNodeId = nodeid;
2261
2262 //delete previously converted UCS string
2263 int i;
2264 for (i = 0; i< UCSStrings.getLength(); i++){
2265 delete [] (char*)UCSStrings[i];
2266 }
2267 UCSStrings.truncate(0);
2268 UCSNumChars.truncate(0);
2269
2270 //make sure conversion code already set:
2271 if (conversionCode == NULL){
2272 conversionCode = iconv_open("UCS-2", "UTF-8");
2273 }
2274
2275 if ( conversionCode == (iconv_t)-1 ){
2276 #ifdef DEBUG
2277 SoDebugError::post("SoOutlineFontCache::convertToUCS",
2278 "Invalid UTF-8 to UCS-2 conversion");
2279 #endif /*DEBUG*/
2280 return;
2281 }
2282
2283 //for each line of text, allocate a sufficiently large buffer
2284 //An extra two bytes are allocated.
2285 for (i = 0; i< strings.getNum(); i++){
2286 UCSStrings[i] = new char[2*strings[i].getLength()+2];
2287
2288 char* input = (char *)strings[i].getString();
2289 size_t inbytes = strings[i].getLength();
2290 size_t outbytes = 2*inbytes+2;
2291 char* output = (char*)UCSStrings[i];
2292
2293 if ((iconv(conversionCode, &input, &inbytes, &output, &outbytes) == (size_t)-1)){
2294 #ifdef DEBUG
2295 SoDebugError::post("SoOutlineFontCache::convertToUCS",
2296 "Error converting text to UCS-2");
2297 #endif /*DEBUG*/
2298
2299 }
2300
2301 if (inbytes){
2302 #ifdef DEBUG
2303 SoDebugError::post("SoOutlineFontCache::convertToUCS",
2304 "Incomplete conversion to UCS-2");
2305 #endif /*DEBUG*/
2306 return;
2307 }
2308
2309 UCSNumChars[i] = (void*)((2*strings[i].getLength()+2 - outbytes)>>1);
2310
2311 #ifndef __APPLE__
2312 int j;
2313 for (j = 0; j < getNumUCSChars(i); j++) {
2314 char* c = (char*)UCSStrings[i]+j*2;
2315 DGL_HTON_SHORT(SHORT(c), SHORT(c));
2316 }
2317 #endif
2318 }
2319
2320 return;
2321
2322 }
2323 ////////////////////////////////////////////////////////////////////////
2324 //
2325 // Description:
2326 // Copy info from the font library into a more convenient form.
2327 //
2328 // Use: internal
2329
2330 SoFontOutline::SoFontOutline(FLoutline *outline, float fontSize)
2331 //
2332 ////////////////////////////////////////////////////////////////////////
2333 {
2334 charAdvance = SbVec2f(outline->xadvance,
2335 outline->yadvance)*fontSize;
2336 numOutlines = outline->outlinecount;
2337 if (numOutlines != 0) {
2338 numVerts = new int[numOutlines];
2339 verts = new SbVec2f*[numOutlines];
2340 for (int i = 0; i < numOutlines; i++) {
2341 numVerts[i] = outline->vertexcount[i];
2342 if (numVerts[i] != 0) {
2343 verts[i] = new SbVec2f[numVerts[i]];
2344 for (int j = 0; j < numVerts[i]; j++) {
2345 verts[i][j] = SbVec2f(outline->vertex[i][j].x,
2346 outline->vertex[i][j].y)*fontSize;
2347 }
2348 } else {
2349 verts[i] = NULL;
2350 }
2351 }
2352 } else {
2353 numVerts = NULL;
2354 verts = NULL;
2355 }
2356 }
2357
2358 ////////////////////////////////////////////////////////////////////////
2359 //
2360 // Description:
2361 // Destructor; free up outline storage
2362 //
2363 // Use: internal
2364
2365 SoFontOutline::~SoFontOutline()
2366 //
2367 ////////////////////////////////////////////////////////////////////////
2368 {
2369 for (int i = 0; i < numOutlines; i++) {
2370 if (numVerts[i] != 0)
2371 delete[] verts[i];
2372 }
2373 if (numOutlines != 0) {
2374 delete[] verts;
2375 delete[] numVerts;
2376 }
2377 }
2378
2379 ////////////////////////////////////////////////////////////////////////
2380 //
2381 // Description:
2382 // Get a do-nothing outline:
2383 //
2384 // Use: internal, static
2385
2386 SoFontOutline *
2387 SoFontOutline::getNullOutline()
2388 //
2389 ////////////////////////////////////////////////////////////////////////
2390 {
2391 return new SoFontOutline;
2392 }
2393
2394 ////////////////////////////////////////////////////////////////////////
2395 //
2396 // Description:
2397 // Internal constructor used by getNullOutline
2398 //
2399 // Use: internal, static
2400
2401 SoFontOutline::SoFontOutline()
2402 //
2403 ////////////////////////////////////////////////////////////////////////
2404 {
2405 charAdvance = SbVec2f(0,0);
2406 numOutlines = 0;
2407 numVerts = NULL;
2408 verts = NULL;
2409 }
2410
2411 ////////////////////////////////////////////////////////////////////////
2412 //
2413 // Description:
2414 // Find the first and last points in the bevel-- that is where the
2415 // front and back of the character will be.
2416 // Use:
2417 // internal
2418
2419 void
2420 SoOutlineFontCache::getProfileBounds(float &firstZ, float &lastZ)
2421 //
2422 ////////////////////////////////////////////////////////////////////////
2423 {
2424 if (hasProfile()) {
2425 firstZ = -profileVerts[0][0];
2426 lastZ = -profileVerts[nProfileVerts-1][0];
2427 } else {
2428 firstZ = lastZ = 0;
2429 }
2430 }
2431
2432 ////////////////////////////////////////////////////////////////////////
2433 //
2434 // Description:
2435 // Get the 2D bounding box of the bevel.
2436 //
2437 // Use:
2438 // internal
2439
2440 void
2441 SoOutlineFontCache::getProfileBBox(SbBox2f &profileBox)
2442 //
2443 ////////////////////////////////////////////////////////////////////////
2444 {
2445 for (int i = 0; i < nProfileVerts; i++) {
2446 profileBox.extendBy(profileVerts[i]);
2447 }
2448 }
2449
2450 ////////////////////////////////////////////////////////////////////////
2451 //
2452 // Description:
2453 // Called by generateSide. This generates the bevel triangles for
2454 // one character.
2455 //
2456 // Use: private
2457
2458 void
2459 SoOutlineFontCache::generateSideChar(const char* c, SideCB callbackFunc)
2460 //
2461 ////////////////////////////////////////////////////////////////////////
2462 {
2463 if (!hasProfile()) return;
2464
2465 // Get the outline of the character:
2466 SoFontOutline *outline = getOutline(c);
2467
2468 for (int i = 0; i < outline->getNumOutlines(); i++) {
2469 // For each outline:
2470
2471 int nOutline = outline->getNumVerts(i);
2472
2473 SbVec2f *oVerts = new SbVec2f[nOutline];
2474 // Copy in verts so figureSegmentNorms can handle them..
2475 int j;
2476 for (j = 0; j < nOutline; j++) {
2477 oVerts[j] = outline->getVertex(i, j);
2478 }
2479
2480 // First, figure out a set of normals for the outline:
2481 SbVec2f *oNorms = new SbVec2f[nOutline*2];
2482 figureSegmentNorms(oNorms, nOutline, oVerts, cosCreaseAngle, TRUE);
2483
2484 // And appropriate texture coordinates:
2485 // Figure out T texture coordinates, which run along the
2486 // outline:
2487 float *tTexCoords = new float[nOutline+1];
2488 figureSegmentTexCoords(tTexCoords, nOutline, oVerts, TRUE);
2489
2490 // Now, generate a set of triangles for each segment in the
2491 // outline. A bevel of profiles is built at each point in the
2492 // outline; each profile must be flipped perpendicular to the
2493 // outline (x coordinate becomes -z), rotated to be the
2494 // average of the normals of the two adjoining segments at
2495 // that point, and translated to that point. Triangles are
2496 // formed between consecutive bevels.
2497 // Normals are just taken from the 'pNorms' array, after being
2498 // rotated the appropriate amount.
2499
2500 SbVec3f *bevel1 = new SbVec3f[nProfileVerts];
2501 SbVec3f *bevelN1 = new SbVec3f[(nProfileVerts-1)*2];
2502 SbVec3f *bevel2 = new SbVec3f[nProfileVerts];
2503 SbVec3f *bevelN2 = new SbVec3f[(nProfileVerts-1)*2];
2504
2505 // fill out first bevel:
2506 fillBevel(bevel1, (int) nProfileVerts, profileVerts,
2507 outline->getVertex(i,0),
2508 oNorms[(nOutline-1)*2+1], oNorms[0*2]);
2509
2510 SbVec3f *s1 = bevel1;
2511 SbVec3f *s2 = bevel2;
2512
2513 for (j = 0; j < nOutline; j++) {
2514 // New normals are calculated for both ends of this
2515 // segment, since the normals may or may not be shared
2516 // with the previous segment.
2517 fillBevelN(bevelN1, (int)(nProfileVerts-1)*2, profileNorms,
2518 oNorms[j*2]);
2519
2520 int j2 = (j+1)%nOutline;
2521 // fill out second bevel:
2522 fillBevel(s2, (int) nProfileVerts, profileVerts,
2523 outline->getVertex(i,j2),
2524 oNorms[j*2+1], oNorms[j2*2]);
2525 fillBevelN(bevelN2, (int)(nProfileVerts-1)*2, profileNorms,
2526 oNorms[j*2+1]);
2527
2528 // And generate triangles between the two bevels:
2529 (*callbackFunc)((int) nProfileVerts, s1, bevelN1, s2, bevelN2,
2530 sTexCoords, &tTexCoords[j]);
2531
2532 // Swap bevel1/2 (avoids some recomputation)
2533 SbVec3f *t;
2534 t = s1; s1 = s2; s2 = t;
2535 }
2536 delete [] bevelN2;
2537 delete [] bevel2;
2538 delete [] bevelN1;
2539 delete [] bevel1;
2540 delete [] tTexCoords;
2541 delete [] oNorms;
2542 delete [] oVerts;
2543 }
2544 }
2545
2546 ////////////////////////////////////////////////////////////////////////
2547 //
2548 // Description:
2549 // Given a set of line segments, this figures out the normal at
2550 // each point in each segment. It uses the creaseAngle passed in
2551 // to decide whether or not adjacent segments share normals. The
2552 // isClosed flag is used to determine whether or not the first and
2553 // last points should be considered another segment.
2554 //
2555 //
2556 // Use: private
2557
2558 void
2559 SoOutlineFontCache::figureSegmentNorms(SbVec2f *norms, int nPoints,
2560 const SbVec2f *points, float cosCreaseAngle,
2561 SbBool isClosed)
2562 //
2563 ////////////////////////////////////////////////////////////////////////
2564 {
2565 int nSegments;
2566
2567 if (isClosed) nSegments = nPoints;
2568 else nSegments = nPoints-1;
2569
2570 // First, we'll just make all the normals perpendicular to their
2571 // segments:
2572 int i;
2573 for (i = 0; i < nSegments; i++) {
2574 SbVec2f n;
2575 // This is 2D perpendicular, assuming profile is increasing in
2576 // X (which becomes 'decreasing in Z' when we actually use
2577 // it...) (note: if a profile isn't increasing in X, the
2578 // character will be inside-out, with the front face drawn
2579 // behind the back face, etc).
2580 SbVec2f v = points[(i+1)%nPoints] - points[i];
2581 n[0] = v[1];
2582 n[1] = -v[0];
2583 n.normalize();
2584
2585 norms[i*2] = n;
2586 norms[i*2+1] = n;
2587 }
2588 // Now, figure out if the angle between any two segments is small
2589 // enough to average two of their normals.
2590 for (i = 0; i < (isClosed ? nSegments : nSegments-1); i++) {
2591 SbVec2f seg1 = points[(i+1)%nPoints] - points[i];
2592 seg1.normalize();
2593 SbVec2f seg2 = points[(i+2)%nPoints] - points[(i+1)%nPoints];
2594 seg2.normalize();
2595
2596 float dp = seg2.dot(seg1);
2597 if (dp > cosCreaseAngle) {
2598 // Average the second normal for this segment, and the
2599 // first normal for the next segment:
2600 SbVec2f average = norms[i*2+1] + norms[((i+1)%nPoints)*2];
2601 average.normalize();
2602 norms[i*2+1] = average;
2603 norms[((i+1)%nPoints)*2] = average;
2604 }
2605 }
2606 }
2607
2608 ////////////////////////////////////////////////////////////////////////
2609 //
2610 // Description:
2611 // Given a set of line segments, this figures out the texture
2612 // coordinates for each vertex. If the isClosed flag is TRUE,
2613 // an extra texture coordinate is calculated, AND the points are
2614 // traversed in reverse order.
2615 //
2616 // Use: private
2617
2618 void
2619 SoOutlineFontCache::figureSegmentTexCoords(float *texCoords, int nPoints,
2620 const SbVec2f *points, SbBool isClosed)
2621 //
2622 ////////////////////////////////////////////////////////////////////////
2623 {
2624 float total = 0.0;
2625
2626 int i;
2627
2628 if (isClosed) {
2629 for (i = nPoints; i >= 0; i--) {
2630 texCoords[i] = total / getHeight();
2631 if (i > 0) {
2632 total += (points[i%nPoints] - points[i-1]).length();
2633 }
2634 }
2635 } else {
2636 for (int i = 0; i < nPoints; i++) {
2637 texCoords[i] = total / getHeight();
2638 if (i+1 < nPoints) {
2639 total += (points[i+1] - points[i]).length();
2640 }
2641 }
2642 }
2643 }
2644
2645 ////////////////////////////////////////////////////////////////////////
2646 //
2647 // Description:
2648 // Given a set of segments that make up a profile or bevel along
2649 // which we'll extrude the front face of the text, this routine
2650 // transforms the bevel from its default orientation (in the x-y
2651 // plane) to its correct position for a particular point on the
2652 // text outline, rotated and translated into position. The
2653 // translation is the point on the outline, and the two normals
2654 // passed in are the normals for the segments adjoining that point.
2655 //
2656 // Use: private
2657
2658 void
2659 SoOutlineFontCache::fillBevel(SbVec3f *result, int nPoints,
2660 const SbVec2f *points,
2661 const SbVec2f &translation,
2662 const SbVec2f &n1, const SbVec2f &n2)
2663 //
2664 ////////////////////////////////////////////////////////////////////////
2665 {
2666 // First, figure out a rotation for this bevel:
2667 SbVec2f n = n1+n2;
2668 n.normalize();
2669
2670 // Now, for each point:
2671 for (int i = 0; i < nPoints; i++) {
2672 // This is really the 2D rotation formula,
2673 // x = x' cos(angle) - y' sin(angle)
2674 // y = x' sin(angle) + y' cos(angle)
2675 // Because of the geometry, cos(angle) is n[1] and sin(angle)
2676 // is -n[0], and x' is zero (the bevel always goes straight
2677 // back).
2678 result[i][0] = points[i][1] * n[0] + translation[0];
2679 result[i][1] = points[i][1] * n[1] + translation[1];
2680 result[i][2] = -points[i][0];
2681 }
2682 }
2683
2684 ////////////////////////////////////////////////////////////////////////
2685 //
2686 // Description:
2687 // Given a set of normals for a profile, this rotates the normals
2688 // from their default position (int the x-y plane) to the correct
2689 // orientation for a particular point on the texts outline. The
2690 // normal passed in is the normal for one end of one of the
2691 // outline's segments.
2692
2693 void
2694 SoOutlineFontCache::fillBevelN(SbVec3f *result, int nNorms,
2695 const SbVec2f *norms,
2696 const SbVec2f &n)
2697 //
2698 ////////////////////////////////////////////////////////////////////////
2699 {
2700 // Now, for each point:
2701 for (int i = 0; i < nNorms; i++) {
2702 // This is really the 2D rotation formula,
2703 // x = x' cos(angle) - y' sin(angle)
2704 // y = x' sin(angle) + y' cos(angle)
2705 // Because of the geometry, cos(angle) is n[1] and sin(angle)
2706 // is -n[0], and x' is zero (the bevel always goes straight
2707 // back).
2708 result[i][0] = norms[i][1] * n[0];
2709 result[i][1] = norms[i][1] * n[1];
2710 result[i][2] = -norms[i][0];
2711 }
2712 }
2713
2714 ////////////////////////////////////////////////////////////////////////
2715 //
2716 // Description:
2717 // Called by the GLU tesselator when there is an error
2718 //
2719 // Use: static, private
2720 //
2721 ////////////////////////////////////////////////////////////////////////
2722
2723 #ifdef DEBUG
2724 void
2725 SoOutlineFontCache::errorCB(GLenum whichErr)
2726 {
2727 SoDebugError::post("SoText3::errorCB", "%s", gluErrorString(whichErr));
2728 tesselationError = TRUE;
2729 }
2730 #else /* DEBUG */
2731 void
2732 SoOutlineFontCache::errorCB(GLenum)
2733 {
2734 tesselationError = TRUE;
2735 }
2736 #endif /* DEBUG */
2737
2738 ////////////////////////////////////////////////////////////////////////
2739 //
2740 // Description:
2741 // function used to free up outline storage
2742 //
2743 // Use: static, private
2744 //
2745 ////////////////////////////////////////////////////////////////////////
2746
2747 void SoOutlineFontCache::freeOutline(unsigned long, void* value)
2748 {
2749 delete (FLoutline*)value;
2750 }