Debian Codegraph @

lib/database/src/so/nodes/SoText2.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.6 $
44 |
45 | Classes:
46 | SoText2
47 |
48 | Author(s) : Gavin Bell
49 |
50 ______________ S I L I C O N G R A P H I C S I N C . ____________
51 _______________________________________________________________________
52 */
53
54 #include <GL/gl.h>
55 #include <Inventor/SbBox.h>
56 #include <Inventor/SoPickedPoint.h>
57 #include <Inventor/actions/SoCallbackAction.h>
58 #include <Inventor/actions/SoGLRenderAction.h>
59 #include <Inventor/actions/SoRayPickAction.h>
60 #include <Inventor/bundles/SoMaterialBundle.h>
61 #include <Inventor/caches/SoCache.h>
62 #include <Inventor/details/SoTextDetail.h>
63 #include <Inventor/elements/SoCacheElement.h>
64 #include <Inventor/elements/SoFontNameElement.h>
65 #include <Inventor/elements/SoFontSizeElement.h>
66 #include <Inventor/elements/SoGLCacheContextElement.h>
67 #include <Inventor/elements/SoGLTextureEnabledElement.h>
68 #include <Inventor/elements/SoLazyElement.h>
69 #include <Inventor/elements/SoMaterialBindingElement.h>
70 #include <Inventor/elements/SoModelMatrixElement.h>
71 #include <Inventor/elements/SoProjectionMatrixElement.h>
72 #include <Inventor/elements/SoViewingMatrixElement.h>
73 #include <Inventor/elements/SoViewportRegionElement.h>
74 #include <Inventor/errors/SoDebugError.h>
75 #include <Inventor/misc/SoState.h>
76 #include <Inventor/nodes/SoText2.h>
77
78 // 6.2 requires flclient.h, iconv.h for UTF->UCS conversion
79 #include <flclient.h>
80 #include <cmath>
81 #include <iconv.h>
82 #include <machine.h>
83
84
85 // An internal class that makes life easier:
86
87 // This very specialized cache class is used to cache bitmaps and GL
88 // display lists containing bitmaps. It is strange because it doesn't
89 // use the normal list of elements used to determine validity, etc,
90 // and knows exactly which elements it depends on.
91
92 class SoBitmapFontCache : public SoCache
93 {
94 public:
95 // Return a font (either a new one or an old one) that is valid
96 // for the given state.
97 static SoBitmapFontCache * getFont(SoState *state, SbBool forRender);
98
99 // Checks to see if this font is valid
100 SbBool isValid(const SoState *state) const;
101
102 // Use this when rendering to decide if this cache is valid (it
103 // checks the GL cache context in addition to other elements)
104 SbBool isRenderValid(SoState *state) const;
105
106 // Set up for GL rendering:
107 void setupToRender(SoState *state);
108
109 // Returns the amount the current raster position will be advanced
110 // after drawing the given unicode character.
111 SbVec3f getCharOffset(char* c);
112
113 // Get the pixel-space bounding box of a given unicode character.
114 void getCharBbox(char* c, SbBox3f &box);
115
116 // Gets the width (in pixels) of specified UCS-2 string
117 float getWidth(int line);
118
119 // Gets the height of the font, in pixels
120 float getHeight();
121
122 // Draws the current UCS-2 string
123 void drawString(int line);
124
125 // Draws the given unicode character (using GL)
126 void drawCharacter(const char* c);
127
128 //Convert string to UCS-2 format, keep a copy in this cache.
129 //Use nodeid to know when to reconvert.
130 SbBool convertToUCS(uint32_t nodeid, const SoMFString& string);
131
132 //Returns line of UCS-2 text
133 char * getUCSString(int line)
134 { return (char*)UCSStrings[line];}
135
136 int getNumUCSChars(int line)
137 { return (int)(long)UCSNumChars[line];}
138
139 protected:
140 // Free up display lists before being deleted
141 virtual void destroy(SoState *state);
142
143 private:
144 // Constructor.
145 SoBitmapFontCache(SoState *state);
146
147 // Destructor
148 virtual ~SoBitmapFontCache();
149
150 // Returns TRUE if this font cache has a display list for the
151 // given unicode UCS-2 character. It will try to build a display list, if it
152 // can.
153 SbBool hasDisplayList(const char* c);
154
155 // Renders an entire UCS-2 string by using the GL callList() function.
156 void callLists(const char *string, int length);
157
158 const FLbitmap *getBitmap(unsigned char* c);
159
160 // Static list of all fonts. OPTIMIZATION: If there turn out to
161 // be applications that use lots of fonts, we could change this
162 // list into a dictionary keyed off the font name.
163 static SbPList *fonts;
164
165 int numChars; // Number of characters in this font
166
167
168
169 SoGLDisplayList *list;
170
171 // Dictionary to point to unicode-character display lists;
172 // Keyed by unicode value
173 SbDict *displayListDict;
174
175 // Dictionary to point to bitmap; keyed by unicode value.
176 SbDict *bitmapDict;
177
178 // This flag will be true if there is another cache open (if
179 // building GL display lists for render caching, that means we
180 // can't also build display lists).
181 SbBool otherOpen;
182
183 // This indicates the nodeId of the last created cache, so we can
184 // know when a new UCS-2 translation is required
185 uint32_t currentNodeId;
186
187 // And some font library stuff:
188 static FLcontext flContext;
189
190 // instead of font number, we use a comma-separated list of font numbers.
191 GLubyte* createUniFontList(const char* fontNameList, float fontsize);
192 GLubyte* fontNumList;
193 SbPList* fontNums;
194
195 // char* pointers of UCS-2 strings:
196 SbPList UCSStrings;
197 // size of these strings, in UCS-2 characters:
198 SbPList UCSNumChars;
199
200 static iconv_t conversionCode; // Used for UCS conversion
201 //Routine to release storage of an FLBitmap
202 static void freeBitmap(unsigned long, void* value);
203
204 };
205
206
207
208 SO_NODE_SOURCE(SoText2);
209
210 ////////////////////////////////////////////////////////////////////////
211 //
212 // Description:
213 // Constructor
214 //
215 // Use: public
216
217 SoText2::SoText2()
218 //
219 ////////////////////////////////////////////////////////////////////////
220 {
221 SO_NODE_CONSTRUCTOR(SoText2);
222
223 SO_NODE_ADD_FIELD(string, (""));
224 SO_NODE_ADD_FIELD(spacing, (1.));
225 SO_NODE_ADD_FIELD(justification, (LEFT));
226
227 // Set up static info for enumerated type field
228 SO_NODE_DEFINE_ENUM_VALUE(Justification, LEFT);
229 SO_NODE_DEFINE_ENUM_VALUE(Justification, RIGHT);
230 SO_NODE_DEFINE_ENUM_VALUE(Justification, CENTER);
231
232 // Set up info in enumerated type field
233 SO_NODE_SET_SF_ENUM_TYPE(justification, Justification);
234
235 isBuiltIn = TRUE;
236 myFont = NULL;
237
238
239 }
240
241 ////////////////////////////////////////////////////////////////////////
242 //
243 // Description:
244 // Destructor
245 //
246 // Use: private
247
248 SoText2::~SoText2()
249 //
250 ////////////////////////////////////////////////////////////////////////
251 {
252 if (myFont != NULL) myFont->unref();
253 }
254
255 ////////////////////////////////////////////////////////////////////////
256 //
257 // Description:
258 // Static helper routine; given a vector in object space, a
259 // transformation matrix to screen (normalized-device coordinate)
260 // space, and a viewportRegion, returns the 2D pixel coordinates of
261 // the vector (relative to the origin of the viewport). This
262 // actually returns a 3D vector; the z value is just the NDC z value.
263 //
264 // Use: internal, static
265
266 static SbVec3f
267 fromObjectSpace(const SbVec3f &vector, const SbMatrix &matrix,
268 const SbViewportRegion &vpr)
269 //
270 ////////////////////////////////////////////////////////////////////////
271 {
272 // First, transform to NDC (-1 to 1 in viewport)
273 SbVec3f ndc;
274 matrix.multVecMatrix(vector, ndc);
275
276 // And do the viewport transformation:
277 SbVec2s vpSize = vpr.getViewportSizePixels();
278 SbVec3f result;
279 result[0] = (ndc[0]+1.0)*vpSize[0]/2.0;
280 result[1] = (ndc[1]+1.0)*vpSize[1]/2.0;
281 // Leave the z coordinate alone
282 result[2] = ndc[2];
283
284 return result;
285 }
286
287 ////////////////////////////////////////////////////////////////////////
288 //
289 // Description:
290 // Static helper routine; given 2D pixel coordinates, a
291 // transformation matrix to object space, and a viewportRegion,
292 // return the object-space point (assuming the 2D pixel is at z
293 // coordinate 0).
294 //
295 // Use: internal, static
296
297 static SbVec3f
298 toObjectSpace(const SbVec3f &pixel, const SbMatrix &matrix,
299 const SbViewportRegion &vpr)
300 //
301 ////////////////////////////////////////////////////////////////////////
302 {
303 // Viewport transformation, to normalized device coordinates:
304 SbVec2s vpSize = vpr.getViewportSizePixels();
305 SbVec3f ndc;
306 ndc[0] = pixel[0]*2.0/vpSize[0] - 1.0;
307 ndc[1] = pixel[1]*2.0/vpSize[1] - 1.0;
308 ndc[2] = pixel[2];
309
310 SbVec3f result;
311 matrix.multVecMatrix(ndc, result);
312
313 return result;
314 }
315
316 ////////////////////////////////////////////////////////////////////////
317 //
318 // Description:
319 // render the text with the current font
320 //
321 // Use: protected
322
323 void
324 SoText2::GLRender(SoGLRenderAction *action)
325 //
326 ////////////////////////////////////////////////////////////////////////
327 {
328 if (!shouldGLRender(action)) return;
329
330 SoState *state = action->getState();
331
332 state->push();
333
334 // Get a font cache we can pull stuff out of
335 if (myFont != NULL) {
336 if (!myFont->isRenderValid(state)) {
337 myFont->unref(state);
338 myFont = NULL;
339 }
340 }
341 if (myFont == NULL) {
342 myFont = SoBitmapFontCache::getFont(state, TRUE);
343 if (myFont == NULL) {
344 state->pop();
345 return;
346 }
347 }
348
349 //The current text must be translated to UCS, unless this
350 //translation has already been done.
351 if (myFont) myFont->convertToUCS(getNodeId(), string);
352
353 // Turn off lighting
354 SoLazyElement::setLightModel(state,
355 SoLazyElement::BASE_COLOR);
356 // Turn off texturing
357 SoGLTextureEnabledElement::set(state, FALSE);
358
359 myFont->setupToRender(state);
360
361 // Send first color
362 SoMaterialBundle mb(action);
363 mb.sendFirst();
364
365 // Special-case left-justified, single-line text, which we know
366 // starts at (0,0,0) in object space, so we can help caching by
367 // avoiding getting the projection/view/model matrices:
368 if (string.getNum() == 1 && justification.getValue() == LEFT) {
369 glRasterPos3f(0,0,0);
370
371 myFont->drawString(0);
372 }
373 // General case:
374 else {
375 SbMatrix objToScreen;
376 objToScreen = SoProjectionMatrixElement::get(state);
377 objToScreen =
378 objToScreen.multLeft(SoViewingMatrixElement::get(state));
379 objToScreen =
380 objToScreen.multLeft(SoModelMatrixElement::get(state));
381
382 SbMatrix screenToObj = objToScreen.inverse();
383
384 SbViewportRegion vpr = SoViewportRegionElement::get(state);
385
386 // The origin of the text on the screen is the object-space point
387 // 0,0,0:
388 SbVec3f screenOrigin =
389 fromObjectSpace(SbVec3f(0,0,0), objToScreen, vpr);
390
391 for (int line = 0; line < string.getNum(); line++) {
392
393 // Starting position of string, based on justification:
394 SbVec3f charPosition = getPixelStringOffset(line) +
395 screenOrigin;
396
397 // Transform the screen-space starting position into object
398 // space, and feed that back to the glRasterPos command (which
399 // will turn around and transform it back into screen-space,
400 // but oh well).
401 SbVec3f lineOrigin = toObjectSpace(charPosition, screenToObj,
402 vpr);
403 glRasterPos3fv(&lineOrigin[0]);
404
405 myFont->drawString(line);
406 }
407 // Don't auto-cache above, since dependent on camera:
408 SoGLCacheContextElement::shouldAutoCache(state,
409 SoGLCacheContextElement::DONT_AUTO_CACHE);
410 }
411 state->pop();
412 }
413
414 ////////////////////////////////////////////////////////////////////////
415 //
416 // Description:
417 // Implements ray picking
418 //
419 // Use: protected
420
421 void
422 SoText2::rayPick(SoRayPickAction *action)
423 //
424 ////////////////////////////////////////////////////////////////////////
425 {
426 // First see if the object is pickable
427 if (! shouldRayPick(action))
428 return;
429
430 SoState *state = action->getState();
431
432 state->push();
433
434 // Get a font cache we can pull stuff out of
435 if (myFont != NULL) {
436 if (!myFont->isValid(state)) {
437 myFont->unref();
438 myFont = NULL;
439 }
440 }
441 if (myFont == NULL) {
442 myFont = SoBitmapFontCache::getFont(state, FALSE);
443 if (myFont == NULL) {
444 state->pop();
445 return;
446 }
447 }
448
449 //The current text must be translated to UCS, unless this
450 //translation has already been done.
451 if (myFont) myFont->convertToUCS(getNodeId(), string);
452
453 // Tell the action about our current object space
454 action->setObjectSpace();
455
456 SbMatrix objToScreen;
457 objToScreen = SoProjectionMatrixElement::get(state);
458 objToScreen =
459 objToScreen.multLeft(SoViewingMatrixElement::get(state));
460 objToScreen =
461 objToScreen.multLeft(SoModelMatrixElement::get(state));
462
463 SbMatrix screenToObj = objToScreen.inverse();
464
465 SbViewportRegion vpr = SoViewportRegionElement::get(state);
466 // font size in pixels
467 float fontSize = SoFontSizeElement::get(state) *
468 vpr.getPixelsPerPoint();
469
470 // The origin of the text on the screen is the object-space point
471 // 0,0,0:
472 SbVec3f screenOrigin =
473 fromObjectSpace(SbVec3f(0,0,0), objToScreen, vpr);
474
475 for (int line = 0; line < string.getNum(); line++) {
476
477 int len = myFont->getNumUCSChars(line);
478
479 char* str = myFont->getUCSString(line);
480
481 // Intersect against each line of text's bounding box:
482 SbBox3f lineBbox, charBbox;
483
484 // Starting position of string, based on justification:
485 SbVec3f charPosition = getPixelStringOffset(line) +
486 screenOrigin;
487
488 SbVec3f p0, p1, p2, p3;
489 int chr;
490 for (chr = 0; chr < len; chr++) {
491 myFont->getCharBbox(str + 2*chr, charBbox);
492
493 if (!charBbox.isEmpty()) {
494
495 SbVec3f charMin = charBbox.getMin() + charPosition;
496 SbVec3f charMax = charBbox.getMax() + charPosition;
497
498 // Extend the line's bounding box by this character's
499 // bounding box (both boxes are in screen-space):
500 lineBbox.extendBy(charMin);
501 lineBbox.extendBy(charMax);
502
503 // Advance to next character...
504 charPosition += myFont->getCharOffset(str + 2*chr);
505 }
506 }
507 // And transform line's box into object space:
508 SbVec3f min = lineBbox.getMin();
509 SbVec3f max = lineBbox.getMax();
510
511 SbVec3f t;
512 t.setValue(min[0], min[1], screenOrigin[2]);
513 p0 = toObjectSpace(t, screenToObj, vpr);
514 t.setValue(max[0], min[1], screenOrigin[2]);
515 p1 = toObjectSpace(t, screenToObj, vpr);
516 t.setValue(min[0], max[1], screenOrigin[2]);
517 p2 = toObjectSpace(t, screenToObj, vpr);
518 t.setValue(max[0], max[1], screenOrigin[2]);
519 p3 = toObjectSpace(t, screenToObj, vpr);
520
521 // intersect the two triangles:
522 SbVec3f point;
523 // Info we get back from the pick that we don't need:
524 SbVec3f junk1; SbBool junk2;
525 if (action->intersect(p0, p1, p2, point, junk1, junk2) ||
526 action->intersect(p2, p1, p3, point, junk1, junk2)) {
527
528 SoPickedPoint *pp = action->addIntersection(point);
529 if (pp) {
530 SoTextDetail *detail = new SoTextDetail();
531 detail->setStringIndex(line);
532
533 // Figure out which character was hit:
534 // Transform picked point into screen space:
535 SbVec3f screenPoint =
536 fromObjectSpace(pp->getObjectPoint(), objToScreen,
537 vpr);
538 // Figure out which character that corresponds to, by
539 // adding on the x-offset of each character until we
540 // go past the picked point:
541 charPosition = getPixelStringOffset(line) +
542 screenOrigin;
543 for (chr = 0; chr < len; chr++) {
544 charPosition +=
545 myFont->getCharOffset(str + 2*chr);
546 // Assuming left-to-right drawing of characters:
547 if (charPosition[0] >= screenPoint[0]) break;
548 }
549
550 detail->setCharacterIndex(chr);
551
552 pp->setDetail(detail, this);
553 pp->setMaterialIndex(0);
554
555 // We'll define normal to be object-space 0,0,1:
556 pp->setObjectNormal(SbVec3f(0,0,1));
557 // And texture coordinates to be zero:
558 pp->setObjectTextureCoords(SbVec4f(0,0,0,0));
559 }
560 }
561 }
562 state->pop();
563 }
564
565 ////////////////////////////////////////////////////////////////////////
566 //
567 // Description:
568 // Generates primitives - no-op.
569 //
570 // Use: protected
571
572 void
573 SoText2::generatePrimitives(SoAction *)
574 //
575 ////////////////////////////////////////////////////////////////////////
576 {
577 }
578
579 ////////////////////////////////////////////////////////////////////////
580 //
581 // Description:
582 // Computes bounding box of text. Since 2D text is screen-aligned,
583 // we need to look at the current view volume and viewport region.
584 //
585 // Use: protected
586
587 void
588 SoText2::computeBBox(SoAction *action, SbBox3f &box, SbVec3f &center)
589 //
590 ////////////////////////////////////////////////////////////////////////
591 {
592 SoState *state = action->getState();
593
594 state->push();
595
596 // Get a font cache we can pull stuff out of
597 if (myFont != NULL) {
598 if (!myFont->isValid(state)) {
599 myFont->unref();
600 myFont = NULL;
601 }
602 }
603 if (myFont == NULL) {
604 myFont = SoBitmapFontCache::getFont(state, FALSE);
605 if (myFont == NULL) {
606 state->pop();
607 return;
608 }
609 }
610
611 //The current text must be translated to UCS, unless this
612 //translation has already been done.
613 if (myFont) myFont->convertToUCS(getNodeId(), string);
614
615 SbMatrix objToScreen;
616 objToScreen = SoProjectionMatrixElement::get(state);
617 objToScreen =
618 objToScreen.multLeft(SoViewingMatrixElement::get(state));
619 objToScreen =
620 objToScreen.multLeft(SoModelMatrixElement::get(state));
621
622 SbMatrix screenToObj = objToScreen.inverse();
623
624 SbViewportRegion vpr = SoViewportRegionElement::get(state);
625
626 // font size in pixels
627 float fontSize = SoFontSizeElement::get(state) *
628 vpr.getPixelsPerPoint();
629
630 // The origin of the text on the screen is the object-space point
631 // 0,0,0:
632 SbVec3f screenOrigin =
633 fromObjectSpace(SbVec3f(0,0,0), objToScreen, vpr);
634
635 // Figure out the screen-space bounding box of the characters:
636 SbBox3f screenBbox, charBbox;
637
638 for (int line = 0; line < string.getNum(); line++) {
639
640 int len = myFont->getNumUCSChars(line);
641 char* str = myFont->getUCSString(line);
642
643 // Starting position of string, based on justification:
644 SbVec3f charPosition = getPixelStringOffset(line) +
645 screenOrigin;
646
647 for (int chr = 0; chr < len; chr++) {
648 myFont->getCharBbox(str+2*chr, charBbox);
649 if (!charBbox.isEmpty()) {
650 SbVec3f min = charBbox.getMin() + charPosition;
651 SbVec3f max = charBbox.getMax() + charPosition;
652 screenBbox.extendBy(min);
653 screenBbox.extendBy(max);
654 }
655
656 // And advance...
657 charPosition += myFont->getCharOffset(str+2*chr);
658 }
659 }
660 // Ok, screenBbox now contains the pixel-space extent of the
661 // characters. We'll transform the bounds of that box back into
662 // object space and extend the object-space bounding box:
663
664 if (!screenBbox.isEmpty()) {
665 // Do each of the 4 corners of the screen-space box:
666 const SbVec3f &min = screenBbox.getMin();
667 const SbVec3f &max = screenBbox.getMax();
668 SbVec3f objectPoint, temp;
669
670 temp.setValue(min[0], min[1], screenOrigin[2]);
671 objectPoint = toObjectSpace(temp, screenToObj, vpr);
672 box.extendBy(objectPoint);
673
674 temp.setValue(max[0], max[1], screenOrigin[2]);
675 objectPoint = toObjectSpace(temp, screenToObj, vpr);
676 box.extendBy(objectPoint);
677
678 temp.setValue(min[0], max[1], screenOrigin[2]);
679 objectPoint = toObjectSpace(temp, screenToObj, vpr);
680 box.extendBy(objectPoint);
681
682 temp.setValue(max[0], min[1], screenOrigin[2]);
683 objectPoint = toObjectSpace(temp, screenToObj, vpr);
684 box.extendBy(objectPoint);
685
686 // Set the center to be the origin, which is the natural "center"
687 // of the text, regardless of justification
688 center.setValue(0.0, 0.0, 0.0);
689 }
690
691 state->pop();
692 }
693
694 ////////////////////////////////////////////////////////////////////////
695 //
696 // Description:
697 // Returns the number of pixels the current text string is offset from the
698 // text origin. Uses latest UCS-string in myFont.
699 //
700 // Use: private
701
702 SbVec3f
703 SoText2::getPixelStringOffset(int line)
704 //
705 ////////////////////////////////////////////////////////////////////////
706 {
707 SbVec3f result(0,0,0);
708
709 if (justification.getValue() == RIGHT) {
710 float width = myFont->getWidth(line);
711 result[0] = -width;
712 }
713 if (justification.getValue() == CENTER) {
714 float width = myFont->getWidth(line);
715 result[0] = -width/2.0;
716 }
717 result[1] = -line*myFont->getHeight()*spacing.getValue()*2;
718
719 return result;
720 }
721 //////////////////////////////////////////////////////////////////////////////
722 ///////////////////// SoBitmapFontCache //////////////////////////////////
723 //////////////////////////////////////////////////////////////////////////////
724 // Static variables for SoBitmapFontCache
725 SbPList *SoBitmapFontCache::fonts = NULL;
726 FLcontext SoBitmapFontCache::flContext;
727
728 //The conversion code (from UTF-8 to UCS-2) is static, set only once.
729 iconv_t SoBitmapFontCache::conversionCode = NULL;
730
731
732 ////////////////////////////////////////////////////////////////////////
733 //
734 // Description:
735 // Convert MFString to UCS string, if necessary.
736 //
737 // Use: internal
738
739 SbBool
740 SoBitmapFontCache::convertToUCS(uint32_t nodeid,
741 const SoMFString& strings)
742 //
743 ////////////////////////////////////////////////////////////////////////
744 {
745 if (nodeid == currentNodeId) return TRUE;
746 currentNodeId = nodeid;
747
748 //delete previously converted UCS string
749 int i;
750 for (i = 0; i< UCSStrings.getLength(); i++){
751 delete [] (char*)UCSStrings[i];
752 }
753 UCSStrings.truncate(0);
754 UCSNumChars.truncate(0);
755
756 //make sure conversion code already set:
757 if (conversionCode == NULL){
758 conversionCode = iconv_open("UCS-2", "UTF-8");
759 }
760
761 if ( conversionCode == (iconv_t)-1 ){
762 #ifdef DEBUG
763 SoDebugError::post("SoBitmapFontCache::convertToUCS",
764 "Invalid UTF-8 to UCS-2 conversion");
765 #endif /*DEBUG*/
766 return FALSE;
767 }
768
769 //for each line of text, allocate a sufficiently large buffer:
770 //An extra two bytes allocated, since glCallLists likes to trample it.
771 for (i = 0; i< strings.getNum(); i++){
772 UCSStrings[i] = new char[2*strings[i].getLength()+2];
773
774 char* input = (char *)strings[i].getString();
775 size_t inbytes = strings[i].getLength();
776 size_t outbytes = 2*inbytes+2;
777 char* output = (char*)UCSStrings[i];
778
779 if ((iconv(conversionCode, &input, &inbytes, &output, &outbytes) == (size_t)-1)){
780 #ifdef DEBUG
781 SoDebugError::post("SoBitmapFontCache::convertToUCS",
782 "Error converting text to UCS-2");
783 #endif /*DEBUG*/
784
785 }
786
787 if (inbytes){
788 #ifdef DEBUG
789 SoDebugError::post("SoBitmapFontCache::convertToUCS",
790 "Incomplete conversion to UCS-2");
791 #endif /*DEBUG*/
792 return FALSE;
793 }
794
795 UCSNumChars[i] = (void*)((2*strings[i].getLength()+2 - outbytes)>>1);
796
797 #ifndef __APPLE__
798 int j;
799 for (j = 0; j < getNumUCSChars(i); j++) {
800 char* c = (char*)UCSStrings[i]+j*2;
801 DGL_HTON_SHORT(SHORT(c), SHORT(c));
802 }
803 #endif
804 }
805
806 return TRUE;
807
808 }
809
810 ////////////////////////////////////////////////////////////////////////
811 //
812 // Description:
813 // Get a font cache suitable for using with the given state.
814 //
815 // Use: static, internal, public
816
817 SoBitmapFontCache *
818 SoBitmapFontCache::getFont(SoState *state, SbBool forRender)
819 //
820 ////////////////////////////////////////////////////////////////////////
821 {
822 if (fonts == NULL) {
823 // One-time font library initialization
824 fonts = new SbPList;
825 flContext = flCreateContext(NULL, FL_FONTNAME, NULL,
826 1.0, 1.0);
827 if (flContext == NULL) {
828 #ifdef DEBUG
829 SoDebugError::post("SoText2::getFont",
830 "flCreateContext returned NULL");
831 #endif
832 return NULL;
833 }
834 if (flGetCurrentContext() != flContext)
835 flMakeCurrentContext(flContext);
836 flSetHint(FL_HINT_MINOUTLINESIZE, 24.0);
837 }
838 else if (flContext == NULL) return NULL;
839 else {
840 if (flGetCurrentContext() != flContext)
841 flMakeCurrentContext(flContext);
842 }
843
844 SoBitmapFontCache *result = NULL;
845 for (int i = 0; i < fonts->getLength() && result == NULL; i++) {
846 SoBitmapFontCache *fc = (SoBitmapFontCache *)(*fonts)[i];
847 if (!fc->fontNumList) continue;
848 if (forRender ? fc->isRenderValid(state) : fc->isValid(state)) {
849 result = fc;
850 result->ref();
851
852 }
853 }
854 if (result == NULL) {
855 result = new SoBitmapFontCache(state);
856 result->ref();
857 }
858 return result;
859 }
860 ////////////////////////////////////////////////////////////////////////
861 //
862 // Description:
863 // Create a list of font numbers from a list of font names
864 //
865 // Use: private
866 GLubyte *
867 SoBitmapFontCache::createUniFontList(const char* fontNameList, float size)
868 //
869 ////////////////////////////////////////////////////////////////////////
870 {
871 char *s, *s1, *ends;
872 FLfontNumber fn;
873 float mat[2][2];
874
875 mat[0][0] = mat[1][1] = size;
876 mat[0][1] = mat[1][0] = 0.0;
877
878 //Make a copy of fontNameList so we don't disturb the one we are passed.
879 //Find \n at end of namelist:
880 char * nameCopy = new char[strlen(fontNameList)+1+1];
881 strcpy(nameCopy, fontNameList);
882
883 //find the last null in nameCopy.
884 ends = (char *)strrchr(nameCopy, '\0');
885 strcat(nameCopy, ";"); /* put a guard in the end of string */
886
887
888 s = (char*)nameCopy;
889 fontNums = new SbPList;
890
891 while (s1 = (char *)strchr(s, ';')) {
892 *s1 = (char)NULL; /* font name is pointed to s */
893
894 if ((fn = flCreateFont((const GLubyte*)s, mat, 0, NULL)) == (FLfontNumber)0) {
895 #ifdef DEBUG
896 SoDebugError::post("SoBitmapFontCache::createUniFontList",
897 "Cannot create font %s", s);
898 #endif
899 }
900 else {
901 fontNums->append((void*)(intptr_t)fn);
902 }
903 if(s1 == ends) break;
904 s = (s1 + 1); /* move to next font name */
905 }
906
907 if (fontNums->getLength() == 0 ) return NULL;
908
909 // create a comma-separated list of font numbers:
910 char *fontList = new char[10*fontNums->getLength()];
911 fontList[0] = '\0';
912 for (int i = 0; i< fontNums->getLength(); i++ ){
913 fn = (FLfontNumber)(intptr_t)(*fontNums)[i];
914 sprintf(&fontList[strlen(fontList)], "%"PRIiPTR",", (intptr_t)fn);
915 }
916 fontList[strlen(fontList) - 1] = '\0'; // the last ',' is replaced with NULL
917
918 delete [] nameCopy;
919
920 return (GLubyte *)fontList;
921
922 }
923
924 ////////////////////////////////////////////////////////////////////////
925 //
926 // Description:
927 // Sees if this font is valid. If it is valid, it also makes it
928 // current.
929 //
930 // Use: public
931
932 SbBool
933 SoBitmapFontCache::isValid(const SoState *state) const
934 //
935 ////////////////////////////////////////////////////////////////////////
936 {
937 SbBool result = SoCache::isValid(state);
938
939 if (result) {
940 if (flGetCurrentContext() != flContext) {
941 flMakeCurrentContext(flContext);
942 }
943 }
944 return result;
945 }
946
947 ////////////////////////////////////////////////////////////////////////
948 //
949 // Description:
950 // Construct a bitmap font cache, given the state and a dummy
951 // (empty) list of overridden elements (needed only to pass to the
952 // SoCache constructor).
953 //
954 // Use: internal, private
955
956 SoBitmapFontCache::SoBitmapFontCache(SoState *state) : SoCache(state)
957 //
958 ////////////////////////////////////////////////////////////////////////
959 {
960 ref();
961
962 list = NULL;
963
964 // Grab all the stuff we'll need to determine our validity from
965 // the state.
966 SbName fontName = SoFontNameElement::get(state);
967 addElement(state->getConstElement(
968 SoFontNameElement::getClassStackIndex()));
969 if (fontName == SoFontNameElement::getDefault()) {
970 fontName = SbName("Utopia-Regular");
971 }
972 const SbViewportRegion &vpr = SoViewportRegionElement::get(state);
973 addElement(state->getConstElement(
974 SoViewportRegionElement::getClassStackIndex()));
975 float fontSize = SoFontSizeElement::get(state) * vpr.getPixelsPerPoint();
976 addElement(state->getConstElement(
977 SoFontSizeElement::getClassStackIndex()));
978
979 // Initialize font list
980 fontNumList = createUniFontList(fontName.getString(), fontSize);
981
982
983 if (fontNumList == NULL) {
984 // Try Utopia-Regular, unless we just did!
985 if (fontName != SbName("Utopia-Regular")) {
986 #ifdef DEBUG
987 SoDebugError::post("SoText2::getFont",
988 "Couldn't find font %s, replacing with Utopia-Regular",
989 fontName.getString());
990 #endif
991 fontNumList = createUniFontList("Utopia-Regular", fontSize);
992
993 }
994 if (fontNumList == NULL) {
995 #ifdef DEBUG
996 SoDebugError::post("SoText3::getFont",
997 "Couldn't find font Utopia-Regular!");
998 #endif
999 numChars = 0;
1000 }
1001 }
1002
1003
1004 numChars = 65536; // ??? Just do UCS-2
1005 currentNodeId = 0;
1006 displayListDict = new SbDict;
1007 bitmapDict = new SbDict;
1008
1009 fonts->append(this);
1010 }
1011
1012 ////////////////////////////////////////////////////////////////////////
1013 //
1014 // Description:
1015 // Destructor. Clean up-- GL stuff, font library stuff, and
1016 // internally generated stuff.
1017 //
1018 // Use: internal, private
1019
1020 SoBitmapFontCache::~SoBitmapFontCache()
1021 //
1022 ////////////////////////////////////////////////////////////////////////
1023 {
1024 if (fontNumList) {
1025 if (flGetCurrentContext() != flContext) {
1026 flMakeCurrentContext(flContext);
1027 }
1028
1029 //Must free every bitmap in dictionary:
1030 //this will just apply flFreeBitmap(entry->value)
1031
1032 bitmapDict->applyToAll(freeBitmap);
1033
1034 // Only destroy the font library font if no other font caches
1035 // are using the same font identifier:
1036 // Must go through fontlist and destroy every font that isn't used
1037 // by any other cache.
1038
1039 SbBool otherFonts = (fonts->getLength() > 1);
1040 SbDict *otherFontDict;
1041 if (otherFonts){
1042 otherFontDict = new SbDict;
1043 //Enter all the other fontnums into the dictionary:
1044 for (int i = 0; i< fonts->getLength(); i++) {
1045 SoBitmapFontCache *t = (SoBitmapFontCache *)(*fonts)[i];
1046 if ( t == this) continue;
1047 for (int j = 0; j< (t->fontNums->getLength()); j++){
1048 unsigned long key = (unsigned long)(*(t->fontNums))[j];
1049 otherFontDict->enter(key, NULL);
1050 }
1051 }
1052 }
1053 // Now destroy any fonts that don't appear in otherFontDict
1054 for (int i = 0; i < fontNums->getLength(); i++){
1055 void *value;
1056 if ( !otherFonts ||
1057 !otherFontDict->find((unsigned long)(*fontNums)[i], value)){
1058 flDestroyFont((FLfontNumber)(intptr_t)(*fontNums)[i]);
1059 }
1060 }
1061 if (otherFonts) delete otherFontDict;
1062 delete displayListDict;
1063 delete bitmapDict;
1064
1065 if (fontNumList) delete [] fontNumList;
1066 if (fontNums) delete fontNums;
1067
1068 fonts->remove(fonts->find(this));
1069 }
1070 }
1071
1072 ////////////////////////////////////////////////////////////////////////
1073 //
1074 // Description:
1075 // Destroy this cache. Called by unref(); frees up OpenGL display
1076 // lists.
1077 //
1078 // Use: protected, virtual
1079
1080 void
1081 SoBitmapFontCache::destroy(SoState *)
1082 //
1083 ////////////////////////////////////////////////////////////////////////
1084 {
1085 // Pass in NULL to unref because this cache may be destroyed
1086 // from an action _other_ than GLRender:
1087 if (list) {
1088 list->unref(NULL);
1089 list = NULL;
1090 }
1091 SoCache::destroy(NULL);
1092 }
1093
1094 ////////////////////////////////////////////////////////////////////////
1095 //
1096 // Description:
1097 // Returns TRUE if this cache is valid
1098 //
1099 // Use: internal, public
1100
1101 SbBool
1102 SoBitmapFontCache::isRenderValid(SoState *state) const
1103 //
1104 ////////////////////////////////////////////////////////////////////////
1105 {
1106 if (!list) return isValid(state);
1107 else
1108 return (list->getContext() == SoGLCacheContextElement::get(state)
1109 && isValid(state));
1110 }
1111
1112 ////////////////////////////////////////////////////////////////////////
1113 //
1114 // Description:
1115 // Sets up for GL rendering.
1116 //
1117 // Use: internal
1118
1119 void
1120 SoBitmapFontCache::setupToRender(SoState *state)
1121 //
1122 ////////////////////////////////////////////////////////////////////////
1123 {
1124 otherOpen = SoCacheElement::anyOpen(state);
1125
1126 if (!otherOpen && !list) {
1127 list = new SoGLDisplayList(state,
1128 SoGLDisplayList::DISPLAY_LIST,
1129 numChars);
1130 list->ref();
1131 }
1132 if (list) {
1133 // Set correct list base
1134 glListBase(list->getFirstIndex());
1135 list->addDependency(state);
1136 }
1137 }
1138
1139 ////////////////////////////////////////////////////////////////////////
1140 //
1141 // Description:
1142 // Returns TRUE if a display lists exists for given character.
1143 // Tries to build a display list, if it can.
1144 //
1145 // Use: internal
1146
1147 SbBool
1148 SoBitmapFontCache::hasDisplayList(const char* c)
1149 //
1150 ////////////////////////////////////////////////////////////////////////
1151 {
1152 unsigned char *uc = (unsigned char*)c;
1153 unsigned long key = (uc[0]<<8)|uc[1];
1154 // If we have one, return TRUE
1155 void *value = NULL;
1156 if (displayListDict->find(key, value)) return TRUE;
1157
1158 // If we don't and we can't build one, return FALSE.
1159 if (otherOpen) return FALSE;
1160
1161 // Build one:
1162 glNewList(list->getFirstIndex()+key, GL_COMPILE);
1163 drawCharacter(c);
1164 glEndList();
1165
1166 displayListDict->enter(key, value);
1167
1168 return TRUE;
1169 }
1170
1171 ////////////////////////////////////////////////////////////////////////
1172 //
1173 // Description:
1174 // Assuming that there are display lists built for all the
1175 // UCS-2 characters in given string, render them.
1176 // string should have already been converted from UTF8 form.
1177 //
1178 // Use: internal
1179
1180 void
1181 SoBitmapFontCache::callLists(const char *string, int len)
1182 //
1183 ////////////////////////////////////////////////////////////////////////
1184 {
1185
1186 glCallLists(len, GL_2_BYTES, (unsigned char*)string);
1187 }
1188
1189 ////////////////////////////////////////////////////////////////////////
1190 //
1191 // Description:
1192 // Returns the pixel-space bounding box of given UCS-2 character.
1193 //
1194 // Use: internal, public
1195
1196 void
1197 SoBitmapFontCache::getCharBbox(char* c, SbBox3f &box)
1198 //
1199 ////////////////////////////////////////////////////////////////////////
1200 {
1201 box.makeEmpty();
1202
1203 const FLbitmap *bmap = getBitmap((unsigned char*)c);
1204 if (bmap == NULL) return;
1205
1206 box.extendBy(SbVec3f(-bmap->xorig, -bmap->yorig, 0));
1207 box.extendBy(SbVec3f(bmap->width - bmap->xorig,
1208 bmap->height - bmap->yorig, 0));
1209 }
1210
1211 ////////////////////////////////////////////////////////////////////////
1212 //
1213 // Description:
1214 // Returns the amount the current raster position will be advanced
1215 // after drawing the given UCS-2 character.
1216 //
1217 // Use: internal, public
1218
1219 SbVec3f
1220 SoBitmapFontCache::getCharOffset(char* c)
1221 //
1222 ////////////////////////////////////////////////////////////////////////
1223 {
1224 const FLbitmap *bmap = getBitmap((unsigned char*)c);
1225 if (bmap != NULL)
1226 return SbVec3f(bmap->xmove, bmap->ymove, 0);
1227 else return SbVec3f(0,0,0);
1228 }
1229
1230 ////////////////////////////////////////////////////////////////////////
1231 //
1232 // Description:
1233 // Returns the width of specified UCS2 string.
1234 //
1235 // Use: internal, public
1236
1237 float
1238 SoBitmapFontCache::getWidth(int line)
1239 //
1240 ////////////////////////////////////////////////////////////////////////
1241 {
1242 float result = 0.0;
1243
1244 char *str = getUCSString(line);
1245 for (int i = 0; i < getNumUCSChars(line); i++) {
1246 const FLbitmap *bmap = getBitmap((unsigned char*)(str+2*i));
1247 if (bmap != NULL)
1248 result += bmap->xmove;
1249 }
1250 return result;
1251 }
1252
1253 ////////////////////////////////////////////////////////////////////////
1254 //
1255 // Description:
1256 // Returns the height of given string.
1257 //
1258 // Use: internal, public
1259
1260 float
1261 SoBitmapFontCache::getHeight()
1262 //
1263 ////////////////////////////////////////////////////////////////////////
1264 {
1265 //take height from UCS-2 code for "M"
1266 const FLbitmap *bmap = getBitmap((unsigned char*)"\000M");
1267 if (bmap != NULL)
1268 return bmap->height - bmap->yorig;
1269 else return 0;
1270 }
1271
1272 ////////////////////////////////////////////////////////////////////////
1273 //
1274 // Description:
1275 // Draws a bitmap, using UCS-2 character
1276 //
1277 // Use: internal public
1278
1279 void
1280 SoBitmapFontCache::drawCharacter(const char* c)
1281 //
1282 ////////////////////////////////////////////////////////////////////////
1283 {
1284 unsigned char *uc = (unsigned char*)c;
1285 const FLbitmap *bmap = getBitmap(uc);
1286
1287 if (bmap != NULL)
1288 glBitmap(bmap->width, bmap->height, bmap->xorig, bmap->yorig,
1289 bmap->xmove, bmap->ymove, bmap->bitmap);
1290 #ifdef DEBUG
1291 else SoDebugError::post("SoBitmapFontCache::drawCharacter",
1292 "no bitmap for character %d ", uc[0]*256+uc[1]);
1293 #endif
1294 }
1295
1296 ////////////////////////////////////////////////////////////////////////
1297 //
1298 // Description:
1299 // Draws a whole string. Tries to build display lists, if it can.
1300 // Assumes string is in UCS-2 format.
1301 //
1302 // Use: internal public
1303
1304 void
1305 SoBitmapFontCache::drawString(int line)
1306 //
1307 ////////////////////////////////////////////////////////////////////////
1308 {
1309 SbBool useCallLists = TRUE;
1310
1311 char *str = getUCSString(line);
1312 unsigned char *ustr = (unsigned char*)str;
1313
1314 // If there aren't any other caches open, build display lists for
1315 // the characters we can:
1316 for (int i = 0; i < getNumUCSChars(line); i++) {
1317 // See if the font cache already has (or can build) a display
1318 // list for this character:
1319 if (!hasDisplayList(str + 2*i)) {
1320 useCallLists = FALSE;
1321 break;
1322 }
1323 }
1324
1325 // if we have display lists for all of the characters, use
1326 // glCallLists:
1327 if (useCallLists) {
1328 callLists(str, getNumUCSChars(line));
1329 } else {
1330 // if we don't, draw the string character-by-character, using the
1331 // display lists we do have:
1332 for (int i = 0; i < getNumUCSChars(line); i++) {
1333 if (!hasDisplayList(str + 2*i)) {
1334 drawCharacter(str + 2*i);
1335 }
1336 else glCallList(list->getFirstIndex()+
1337 ((ustr[2*i]<<8) | ustr[2*i+1]));
1338 }
1339 }
1340 }
1341
1342 ////////////////////////////////////////////////////////////////////////
1343 //
1344 // Description:
1345 // Returns a bitmap.
1346 //
1347 // Use: private
1348
1349 const FLbitmap *
1350 SoBitmapFontCache::getBitmap(unsigned char* c)
1351 //
1352 ////////////////////////////////////////////////////////////////////////
1353 {
1354 if (!fontNumList) return NULL;
1355
1356 unsigned long key = (unsigned long)(c[0]<<8 | c[1]);
1357 void* value;
1358 if(!bitmapDict->find(key, value)){
1359 value = (void*)flUniGetBitmap(fontNumList, c);
1360
1361 #ifdef DEBUG
1362 if(value == NULL){
1363 SoDebugError::post("SoBitmapFontCache::getBitmap",
1364 "Invalid Unicode bitmap for character %d", key);
1365 }
1366 #endif /*DEBUG*/
1367
1368 bitmapDict->enter(key, value);
1369 }
1370
1371 return (FLbitmap*)value;
1372 }
1373
1374 ////////////////////////////////////////////////////////////////////////
1375 //
1376 // Description:
1377 // free up a bitmap.
1378 //
1379 // Use: static, private
1380 void
1381 SoBitmapFontCache::freeBitmap(unsigned long, void* value)
1382 ////////////////////////////////////////////////////////////////////////
1383 {
1384 flFreeBitmap((FLbitmap*)value);
1385 }
1386
1387 /////////////////////////////////////////////////////////////////////////