osg for android (四) osgText显示文字以及显示中文的问题

       前提:很悲催的是,昨晚编译了一个晚上的osg3.2.1 for android 由于忘记将3rdParty扔到源码目录,所以虽然编译能够正常完成,但是实际中还是无法使用。今天将继续osg3.0.1,在osg论坛已经有人报告了这个问题:原因是因为GLES2并不支持标准的MipMap,并在这里给出了修改源码的文件,但是将 Glyph.cpp 这个文件覆盖源文件,再编译,出现如下的问题,这个问题比较好解决。

 C++ Code 
1
2
In member function  'virtual void osgText::GlyphTexture::apply(osg::State&) const'
error: 'requiresGenrateMipmapCall' was  not declared in  this scop

      下面给出修改好的Glyph.cpp文件

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
/* -*-c++-*- OpenSceneGraph - Copyright (C) 1998-2006 Robert Osfield 
 *
 * This library is open source and may be redistributed and/or modified under  
 * the terms of the OpenSceneGraph Public License (OSGPL) version 0.0 or 
 * (at your option) any later version.  The full license is in LICENSE file
 * included with this distribution, and on the openscenegraph.org website.
 * 
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
 * OpenSceneGraph Public License for more details.
*/


#include <osgText/Font>
#include <osgText/Text>

#include <osg/State>
#include <osg/Notify>
#include <osg/GLU>

#include <osgUtil/SmoothingVisitor>

#include <string.h>
#include <stdlib.h>

#include  "GlyphGeometry.h"

using  namespace osgText;
using  namespace std;

GlyphTexture::GlyphTexture():
    _margin( 1),
    _marginRatio( 0.02f),
    _usedY( 0),
    _partUsedX( 0),
    _partUsedY( 0)
{
    setWrap(WRAP_S, CLAMP_TO_EDGE);
    setWrap(WRAP_T, CLAMP_TO_EDGE);
}

GlyphTexture::~GlyphTexture() 
{
}

// return -1 if *this < *rhs, 0 if *this==*rhs, 1 if *this>*rhs.
int GlyphTexture::compare( const osg::StateAttribute& rhs)  const
{
     if ( this<&rhs)  return - 1;
     else  if ( this>&rhs)  return  1;
     return  0;
}


bool GlyphTexture::getSpaceForGlyph(Glyph* glyph,  int& posX,  int& posY)
{
     int maxAxis = std::max(glyph->s(), glyph->t());
     int margin = _margin + ( int)(( float)maxAxis * _marginRatio);
    
     int width = glyph->s()+ 2*margin;
     int height = glyph->t()+ 2*margin;

     // first check box (_partUsedX,_usedY) to (width,height)
     if (width <= (getTextureWidth()-_partUsedX) &&
        height <= (getTextureHeight()-_usedY))
    {
         // can fit in existing row.

         // record the position in which the texture will be stored.
        posX = _partUsedX+margin;
        posY = _usedY+margin;        

         // move used markers on.
        _partUsedX += width;
         if (_usedY+height>_partUsedY) _partUsedY = _usedY+height;

         return  true;
    }
    
     // start an new row.
     if (width <= getTextureWidth() &&
        height <= (getTextureHeight()-_partUsedY))
    {
         // can fit next row.
        _partUsedX =  0;
        _usedY = _partUsedY;

        posX = _partUsedX+margin;
        posY = _usedY+margin;        

         // move used markers on.
        _partUsedX += width;
         if (_usedY+height>_partUsedY) _partUsedY = _usedY+height;

         return  true;
    }

     // doesn't fit into glyph.
     return  false;
}

void GlyphTexture::addGlyph(Glyph* glyph,  int posX,  int posY)
{
    OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

    _glyphs.push_back(glyph);
     for( unsigned  int i= 0;i<_glyphsToSubload.size();++i)
    {
        _glyphsToSubload[i].push_back(glyph);
    }

     // set up the details of where to place glyph's image in the texture.
    glyph->setTexture( this);
    glyph->setTexturePosition(posX,posY);

    glyph->setMinTexCoord( osg::Vec2(  static_cast< float>(posX)/ static_cast< float>(getTextureWidth()),
                                       static_cast< float>(posY)/ static_cast< float>(getTextureHeight()) ) );
    glyph->setMaxTexCoord( osg::Vec2(  static_cast< float>(posX+glyph->s())/ static_cast< float>(getTextureWidth()),
                                       static_cast< float>(posY+glyph->t())/ static_cast< float>(getTextureHeight()) ) );
}

void GlyphTexture::apply(osg::State& state)  const
{
      #if defined(OSG_GLES2_AVAILABLE)
         bool requiresGenerateMipmapCall =  false;
     #endif
     // get the contextID (user defined ID of 0 upwards) for the 
     // current OpenGL context.
     const  unsigned  int contextID = state.getContextID();

     if (contextID>=_glyphsToSubload.size())
    {
        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

         // graphics context is beyond the number of glyphsToSubloads, so
         // we must now copy the glyph list across, this is a potential
         // threading issue though is multiple applies are happening the
         // same time on this object - to avoid this condition number of
         // graphics contexts should be set before create text.
         for( unsigned  int i=_glyphsToSubload.size();i<=contextID;++i)
        {
            GlyphPtrList& glyphPtrs = _glyphsToSubload[i];
             for(GlyphRefList::const_iterator itr=_glyphs.begin();
                itr!=_glyphs.end();
                ++itr)
            {
                glyphPtrs.push_back(itr->get());
            }
        }
    }


     const Extensions* extensions = getExtensions(contextID, true);
     bool generateMipMapSupported = extensions->isGenerateMipMapSupported();

     // get the texture object for the current contextID.
    TextureObject* textureObject = getTextureObject(contextID);
    
     bool newTextureObject = (textureObject ==  0);

     if (newTextureObject)
    {
        GLint maxTextureSize =  256;
        glGetIntegerv(GL_MAX_TEXTURE_SIZE, &maxTextureSize);
         if (maxTextureSize < getTextureWidth() || maxTextureSize < getTextureHeight())
        {
            OSG_WARN<< "Warning: osgText::Font texture size of ("<<getTextureWidth()<< ", "<<getTextureHeight()<< ") too large, unable to create font texture."<<std::endl;
            OSG_WARN<< "         Maximum supported by hardward by native OpenGL implementation is ("<<maxTextureSize<< ","<<maxTextureSize<< ")."<<std::endl;
            OSG_WARN<< "         Please set OSG_MAX_TEXTURE_SIZE lenvironment variable to "<<maxTextureSize<< " and re-run application."<<std::endl;
             return;
        }
        
         // being bound for the first time, need to allocate the texture

        _textureObjectBuffer[contextID] = textureObject = osg::Texture::generateTextureObject(
                 this, contextID,GL_TEXTURE_2D, 1,GL_ALPHA,getTextureWidth(), getTextureHeight(), 1, 0);

        textureObject->bind();


        applyTexParameters(GL_TEXTURE_2D,state);


        
         // need to look at generate mip map extension if mip mapping required.
         switch(_min_filter)
        {
         case NEAREST_MIPMAP_NEAREST:
         case NEAREST_MIPMAP_LINEAR:
         case LINEAR_MIPMAP_NEAREST:
         case LINEAR_MIPMAP_LINEAR:
             if (generateMipMapSupported)
            {
                 #if defined(OSG_GLES2_AVAILABLE)
                requiresGenerateMipmapCall =  true;
                 #else
                glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_TRUE);
                 #endif          
            }
             else glTexParameteri( GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, LINEAR);
             break;
         default:
             // not mip mapping so no problems.
             break;
        }
        
         unsigned  int imageDataSize = getTextureHeight()*getTextureWidth();
         unsigned  char* imageData =  new  unsigned  char[imageDataSize];
         for( unsigned  int i= 0; i<imageDataSize; ++i)
        {
            imageData[i] =  0;
        }
        

         // allocate the texture memory.
        glTexImage2D( GL_TEXTURE_2D,  0, GL_ALPHA,
                getTextureWidth(), getTextureHeight(),  0,
                GL_ALPHA,
                GL_UNSIGNED_BYTE,
                imageData );
                
         delete [] imageData;
    
    }
     else
    {
         // reuse texture by binding.
        textureObject->bind();
        
         if (getTextureParameterDirty(contextID))
        {
            applyTexParameters(GL_TEXTURE_2D,state);
        }


    }
    
     static  const GLubyte* s_renderer =  0;
     static  bool s_subloadAllGlyphsTogether =  false;
     if (!s_renderer)
    {
        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

        s_renderer = glGetString(GL_RENDERER);
        OSG_INFO<< "glGetString(GL_RENDERER)=="<<s_renderer<<std::endl;
         if (s_renderer && strstr(( const  char*)s_renderer, "IMPACT")!= 0)
        {
             // we're running on an Octane, so need to work around its
             // subloading bugs by loading all at once.
            s_subloadAllGlyphsTogether =  true;
        }
        
         if (s_renderer && 
            ((strstr(( const  char*)s_renderer, "Radeon")!= 0) || 
            (strstr(( const  char*)s_renderer, "RADEON")!= 0) ||
            (strstr(( const  char*)s_renderer, "ALL-IN-WONDER")!= 0)))
        {
             // we're running on an ATI, so need to work around its
             // subloading bugs by loading all at once.
            s_subloadAllGlyphsTogether =  true;
        }

         if (s_renderer && strstr(( const  char*)s_renderer, "Sun")!= 0)
        {
             // we're running on an solaris x server, so need to work around its
             // subloading bugs by loading all at once.
            s_subloadAllGlyphsTogether =  true;
        }

         const  char* str = getenv( "OSG_TEXT_INCREMENTAL_SUBLOADING");
         if (str)
        {
            s_subloadAllGlyphsTogether = strcmp(str, "OFF")== 0 || strcmp(str, "Off")== 0 || strcmp(str, "off")== 0;
        }
    }


     // now subload the glyphs that are outstanding for this graphics context.
    GlyphPtrList& glyphsWereSubloading = _glyphsToSubload[contextID];

     if (!glyphsWereSubloading.empty() || newTextureObject)
    {
        OpenThreads::ScopedLock<OpenThreads::Mutex> lock(_mutex);

         bool subloadAllGlyphsTogether = s_subloadAllGlyphsTogether;

         #if defined(OSG_GLES2_AVAILABLE)
         if (requiresGenerateMipmapCall) subloadAllGlyphsTogether =  true;
         #endif

         if (!subloadAllGlyphsTogether)
        {
             if (newTextureObject)
            {
                 for(GlyphRefList::const_iterator itr=_glyphs.begin();
                    itr!=_glyphs.end();
                    ++itr)
                {
                    (*itr)->subload();
                }
            }
             else  // just subload the new entries.
            {            
                 // default way of subloading as required.
                 //std::cout<<"subloading"<<std::endl;
                 for(GlyphPtrList::iterator itr=glyphsWereSubloading.begin();
                    itr!=glyphsWereSubloading.end();
                    ++itr)
                {
                    (*itr)->subload();
                }
            }
            
             // clear the list since we have now subloaded them.
            glyphsWereSubloading.clear();
            
        }
         else
        {
            OSG_INFO<< "osgText::Font loading all glyphs as a single subload."<<std::endl;

             // Octane has bugs in OGL driver which mean that subloads smaller
             // than 32x32 produce errors, and also cannot handle general alignment,
             // so to get round this copy all glyphs into a temporary image and
             // then subload the whole lot in one go.

             int tsize = getTextureHeight() * getTextureWidth();
             unsigned  char *local_data =  new  unsigned  char[tsize];
            memset( local_data, 0L, tsize);

             for(GlyphRefList::const_iterator itr=_glyphs.begin();
                itr!=_glyphs.end();
                ++itr)
            {
                 //(*itr)->subload();

                 // Rather than subloading to graphics, we'll write the values
                 // of the glyphs into some intermediate data and subload the
                 // whole thing at the end
                 forint t =  0; t < (*itr)->t(); t++ )
                {
                     forint s =  0; s < (*itr)->s(); s++ )
                    {
                         int sindex = (t*(*itr)->s()+s);
                         int dindex =  
                            ((((*itr)->getTexturePositionY()+t) * getTextureWidth()) +
                            ((*itr)->getTexturePositionX()+s));

                         const  unsigned  char *sptr = &(*itr)->data()[sindex];
                         unsigned  char *dptr       = &local_data[dindex];

                        (*dptr)   = (*sptr);
                    }
                }
            }

             // clear the list since we have now subloaded them.
            glyphsWereSubloading.clear();

             // Subload the image once
            glTexSubImage2D( GL_TEXTURE_2D,  000
                    getTextureWidth(),
                    getTextureHeight(),
                    GL_ALPHA, GL_UNSIGNED_BYTE, local_data );

             #if defined(OSG_GLES2_AVAILABLE)
             if (requiresGenerateMipmapCall) glGenerateMipmap(GL_TEXTURE_2D);
             #endif

             delete [] local_data;

        }
    }
     else
    {
//        OSG_INFO << "no need to subload "<<std::endl;
    }



//     if (generateMipMapTurnedOn)
//     {
//         glTexParameteri(GL_TEXTURE_2D, GL_GENERATE_MIPMAP_SGIS,GL_FALSE);
//     }


}

void GlyphTexture::setThreadSafeRefUnref( bool threadSafe)
{
    osg::Texture2D::setThreadSafeRefUnref(threadSafe);
}

void GlyphTexture::resizeGLObjectBuffers( unsigned  int maxSize)
{
    osg::Texture2D::resizeGLObjectBuffers(maxSize);

     unsigned  int initialSize = _glyphsToSubload.size();
    _glyphsToSubload.resize(maxSize);
    
     for( unsigned i=initialSize; i<_glyphsToSubload.size(); ++i)
    {
         for(GlyphRefList::iterator itr = _glyphs.begin();
            itr != _glyphs.end();
            ++itr)
        {
            _glyphsToSubload[i].push_back(itr->get());
        }
    }
}

osg::Image* GlyphTexture::createImage()
{
    osg::ref_ptr<osg::Image> image =  new osg::Image;
    image->allocateImage(getTextureWidth(), getTextureHeight(),  1, GL_ALPHA, GL_UNSIGNED_BYTE);
    memset(image->data(),  0, image->getTotalSizeInBytes());

     for(GlyphRefList::iterator itr = _glyphs.begin();
        itr != _glyphs.end();
        ++itr)
    {
        Glyph* glyph = itr->get();
        image->copySubImage(glyph->getTexturePositionX(), glyph->getTexturePositionY(),  0, glyph);
    }

     return image.release();
}

// all the methods in Font::Glyph have been made non inline because VisualStudio6.0 is STUPID, STUPID, STUPID PILE OF JUNK.
Glyph::Glyph(Font* font,  unsigned  int glyphCode):
    _font(font),
    _glyphCode(glyphCode),
    _width( 1.0f),
    _height( 1.0f),
    _horizontalBearing( 0.0f, 0.f),
    _horizontalAdvance( 0.f),
    _verticalBearing( 0.0f, 0.f),
    _verticalAdvance( 0.f),
    _texture( 0),
    _texturePosX( 0),
    _texturePosY( 0),
    _minTexCoord( 0.0f, 0.0f),
    _maxTexCoord( 0.0f, 0.0f)
{
    setThreadSafeRefUnref( true);
}

Glyph::~Glyph()
{
}

void Glyph::setHorizontalBearing( const osg::Vec2& bearing) {  _horizontalBearing=bearing; }
const osg::Vec2& Glyph::getHorizontalBearing()  const {  return _horizontalBearing; }

void Glyph::setHorizontalAdvance( float advance) { _horizontalAdvance=advance; }
float Glyph::getHorizontalAdvance()  const {  return _horizontalAdvance; }

void Glyph::setVerticalBearing( const osg::Vec2& bearing) {  _verticalBearing=bearing; }
const osg::Vec2& Glyph::getVerticalBearing()  const {  return _verticalBearing; }

void Glyph::setVerticalAdvance( float advance) {  _verticalAdvance=advance; }
float Glyph::getVerticalAdvance()  const {  return _verticalAdvance; }

void Glyph::setTexture(GlyphTexture* texture) { _texture = texture; }
GlyphTexture* Glyph::getTexture() {  return _texture; }
const GlyphTexture* Glyph::getTexture()  const {  return _texture; }

void Glyph::setTexturePosition( int posX, int posY) { _texturePosX = posX; _texturePosY = posY; }
int Glyph::getTexturePositionX()  const {  return _texturePosX; }
int Glyph::getTexturePositionY()  const {  return _texturePosY; }

void Glyph::setMinTexCoord( const osg::Vec2& coord) { _minTexCoord=coord; }
const osg::Vec2& Glyph::getMinTexCoord()  const {  return _minTexCoord; }

void Glyph::setMaxTexCoord( const osg::Vec2& coord) { _maxTexCoord=coord; }
const osg::Vec2& Glyph::getMaxTexCoord()  const {  return _maxTexCoord; }

void Glyph::subload()  const
{
    GLenum errorNo = glGetError();
     if (errorNo!=GL_NO_ERROR)
    {
         const GLubyte* msg = osg::gluErrorString(errorNo);
         if (msg) { OSG_WARN<< "before Glyph::subload(): detected OpenGL error: "<<msg<<std::endl; }
         else  { OSG_WARN<< "before Glyph::subload(): detected OpenGL error number: "<<errorNo<<std::endl; }
    }

     if(s() <=  0 || t() <=  0)
    {
        OSG_INFO<< "Glyph::subload(): texture sub-image width and/or height of 0, ignoring operation."<<std::endl;
         return;
    }

    glPixelStorei(GL_UNPACK_ALIGNMENT,getPacking());
    
     #if !defined(OSG_GLES1_AVAILABLE) && !defined(OSG_GLES2_AVAILABLE)
    glPixelStorei(GL_UNPACK_ROW_LENGTH,getRowLength());
     #endif

    glTexSubImage2D(GL_TEXTURE_2D, 0,
                    _texturePosX,_texturePosY,
                    s(),t(),
                    (GLenum)getPixelFormat(),
                    (GLenum)getDataType(),
                    data());
                    
    errorNo = glGetError();
     if (errorNo!=GL_NO_ERROR)
    {


         const GLubyte* msg = osg::gluErrorString(errorNo);
         if (msg) { OSG_WARN<< "after Glyph::subload() : detected OpenGL error: "<<msg<<std::endl; }
         else { OSG_WARN<< "after Glyph::subload() : detected OpenGL error number: "<<errorNo<<std::endl; }

        OSG_WARN<<  "\tglTexSubImage2D(0x"<<hex<<GL_TEXTURE_2D<<dec<< " ,"<< 0<< "\t"<<std::endl<<
                                  "\t                "<<_texturePosX<< " ,"<<_texturePosY<<std::endl<<
                                  "\t                "<<s()<< " ,"<<t()<<std::endl<<hex<<
                                  "\t                0x"<<(GLenum)getPixelFormat()<<std::endl<<
                                  "\t                0x"<<(GLenum)getDataType()<<std::endl<<
                                  "\t                0x"<<( unsigned  long)data()<< ");"<<dec<<std::endl;
    }                    
}

Glyph3D::Glyph3D(Font* font,  unsigned  int glyphCode):
    osg::Referenced( true),
    _font(font),
    _glyphCode(glyphCode),
    _width( 1.0f),
    _height( 1.0f),
    _horizontalBearing( 0, 0),
    _horizontalAdvance( 0),
    _verticalBearing( 0, 0),
    _verticalAdvance( 0)
    {}

void Glyph3D::setThreadSafeRefUnref( bool threadSafe)
{
     for(GlyphGeometries::iterator itr = _glyphGeometries.begin();
        itr != _glyphGeometries.end();
        ++itr)
    {
        (*itr)->setThreadSafeRefUnref(threadSafe);
    }
}

GlyphGeometry* Glyph3D::getGlyphGeometry( const Style* style)
{

     for(GlyphGeometries::iterator itr = _glyphGeometries.begin();
        itr != _glyphGeometries.end();
        ++itr)
    {
        GlyphGeometry* glyphGeometry = itr->get();
         if (glyphGeometry->match(style))
        {
            OSG_INFO<< "Glyph3D::getGlyphGeometry(Style* style) found matching GlyphGeometry."<<std::endl;
             return glyphGeometry;
        }
    }

    OSG_INFO<< "Glyph3D::getGlyphGeometry(Style* style) could not find matching GlyphGeometry, creating a new one."<<std::endl;

    osg::ref_ptr<GlyphGeometry> glyphGeometry =  new GlyphGeometry();
    glyphGeometry->setup( this, style);
    _glyphGeometries.push_back(glyphGeometry);

     return glyphGeometry.get();
}


GlyphGeometry::GlyphGeometry()
{
}

void GlyphGeometry::setThreadSafeRefUnref( bool threadSafe)
{
     if (_geode.valid()) _geode->setThreadSafeRefUnref(threadSafe);
}

void GlyphGeometry::setup( const Glyph3D* glyph,  const Style* style)
{
     float creaseAngle =  30.0f;
     bool smooth =  true;
    osg::ref_ptr<osg::Geometry> shellGeometry;

     if (!style)
    {
        OSG_INFO<< "GlyphGeometry::setup(const Glyph* glyph, NULL) creating default glyph geometry."<<std::endl;

         float width =  0.1f;

        _geometry = osgText::computeTextGeometry(glyph, width);
    }
     else
    {
        OSG_INFO<< "GlyphGeometry::setup(const Glyph* glyph, NULL) create glyph geometry with custom Style."<<std::endl;

         // record the style
        _style =  dynamic_cast<Style*>(style->clone(osg::CopyOp::DEEP_COPY_ALL));

         const Bevel* bevel = style ? style->getBevel() :  0;
         bool outline = style ? style->getOutlineRatio()> 0.0f :  false;
         float width = style->getThicknessRatio();

         if (bevel)
        {
             float thickness = bevel->getBevelThickness();

            osg::ref_ptr<osg::Geometry> glyphGeometry = osgText::computeGlyphGeometry(glyph, thickness, width);

            _geometry = osgText::computeTextGeometry(glyphGeometry.get(), *bevel, width);
            shellGeometry = outline ? osgText::computeShellGeometry(glyphGeometry.get(), *bevel, width) :  0;
        }
         else
        {
            _geometry = osgText::computeTextGeometry(glyph, width);
        }
    }

     if (!_geometry)
    {
        OSG_INFO<< "Warning: GlyphGeometry::setup(const Glyph* glyph, const Style* style) failed."<<std::endl;
         return;
    }

    _geode =  new osg::Geode;
    _geode->addDrawable(_geometry.get());
     if (shellGeometry.valid()) _geode->addDrawable(shellGeometry.get());

     // create the normals
     if (smooth)
    {
        osgUtil::SmoothingVisitor::smooth(*_geometry, osg::DegreesToRadians(creaseAngle));
    }

    _vertices =  dynamic_cast<osg::Vec3Array*>(_geometry->getVertexArray());
    _normals =  dynamic_cast<osg::Vec3Array*>(_geometry->getNormalArray());

     for(osg::Geometry::PrimitiveSetList::iterator itr = _geometry->getPrimitiveSetList().begin();
        itr != _geometry->getPrimitiveSetList().end();
        ++itr)
    {
        osg::PrimitiveSet* prim = itr->get();
         if (prim->getName()== "front") _frontPrimitiveSetList.push_back(prim);
         else  if (prim->getName()== "back") _backPrimitiveSetList.push_back(prim);
         else  if (prim->getName()== "wall") _wallPrimitiveSetList.push_back(prim);
    }
}

bool GlyphGeometry::match( const Style* style)  const
{
     if (_style == style)  return  true;
     if (!_style || !style)  return  false;

     return (*_style==*style);
}

         接着又是漫长的编译过程~

         现在osg for android应该能够正确显示文字了,下面给出osg创建文字代码

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
osg::ref_ptr<osg::Node> OsgMainApp::createTextNode() {
    setlocale(LC_ALL, "chs");
    std::string textConvert =  "osg for android 中文显示示例";
    osgText::Font* fontHei = osgText::readFontFile( "/sdcard/osg/simfang.ttf");
    osg::ref_ptr<osgText::Text> text =  new osgText::Text;
    text->setFont(fontHei);
    text->setText(textConvert, osgText::String::ENCODING_UTF8);
    text->setCharacterSize(40.0f);  //字体大小
    text->setPosition(osg::Vec3( 0. 00. 0, - 80.0f));
    text->setAutoRotateToScreen( true);

    osg::ref_ptr<osg::Geode> geode =  new osg::Geode;
    geode->addDrawable(
            osg::createTexturedQuadGeometry(osg::Vec3(- 150. 01. 0, - 130. 0),
                    osg::Vec3( 300. 00. 00. 0), osg::Vec3( 0. 00. 0200. 0),  1. 0,
                     1. 0)); 

    geode->addDrawable(text.get());
    osg::Drawable* geom = geode->getDrawable( 1);
    osg::Uniform* samUniform =  new osg::Uniform(osg::Uniform::SAMPLER_2D,
             "GlyphTexture");
    samUniform->set( 0);  //设置纹理单元
    osg::StateSet * ss = geom->getOrCreateStateSet();  //->getStateSet();
    ss->addUniform(samUniform);
    osg::Program * program =  new osg::Program;
    program->addShader( new osg::Shader(osg::Shader::FRAGMENT, fragShader));
    program->addShader( new osg::Shader(osg::Shader::VERTEX, vertexShader));
    ss->setAttribute(program);
     return geode;

  

          shader代码

 C++ Code 
1
2
3
4
5
6
7
8
9
10
11
12
static  const  char vertexShader[] =
         "varying vec2 texcoord1;                                \n"
         "void main(void ){                                      \n"
         "texcoord1 = gl_MultiTexCoord0.st;                      \n"
         "gl_Position = ftransform();                            \n"
         "}                                                      \n";
static  const  char fragShader[] =
         "varying mediump vec2 texcoord1;                        \n"
         "uniform sampler2D GlyphTexture;                        \n"
         "void main(void){                                       \n"
         " gl_FragColor = texture2D(GlyphTexture, texcoord1);    \n"
         "}                                                      \n";

         这个时候还不能显示中文,必须在android.mk文件加入freetype库的支持,很奇怪的是加入-losgdb_freetype,然后在OsgMainApp.h加入USE_OSGPLUGIN(freetype)这两句代码,这个时候报错:

 C++ Code 
1
2
D:/NDK/android-ndk-r10b/toolchains/arm-linux-androideabi- 4. 6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/ 4. 6/../../../../arm-linux-androideabi/bin/ld.exe: C:/Develop/osggles2/obj/local/armeabi/libosgdb_freetype.a(FreeTypeLibrary.o): in function FreeTypeLibrary::verifyCharacterMap(FT_FaceRec_*):D:/NDK/OSG/OpenSceneGraph- 3. 0. 1/src/osgPlugins/freetype/FreeTypeLibrary.cpp: 198: error: undefined reference to  'FT_Set_Charmap'
D:/NDK/android-ndk-r10b/toolchains/arm-linux-androideabi- 4. 6/prebuilt/windows-x86_64/bin/../lib/gcc/arm-linux-androideabi/ 4. 6/../../../../arm-linux-androideabi/bin/ld.exe: C:/Develop/osggles2/obj/local/armeabi/libosgdb_freetype.a(FreeTypeLibrary.o): in function FreeTypeLibrary::getFace(std::string  const&,  unsigned  int, FT_FaceRec_*&):D:/NDK/OSG/OpenSceneGraph- 3. 0. 1/src/osgPlugins/freetype/FreeTypeLibrary.cpp: 65: error: undefined reference to  'FT_New_Face'
*********

        还好在这里找到了解决的方法,非常感谢,毕竟中文显示上国外论坛也找不到解决的方法:) 在这里需要注意的一点是:添加的-lft2 \ 这句代码必须放到-losgdb_freetype \的后面,否则仍旧会出现上面的错误。接下来是很顺利的显示中文了

         

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值