Moved Core Rendering API from devel-api to public-api
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / text / rendering / atlas / text-atlas-renderer.cpp
1 /*
2  * Copyright (c) 2016 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include <dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/rendering/geometry.h>
23 #include <dali/public-api/rendering/renderer.h>
24 #include <dali/devel-api/text-abstraction/font-client.h>
25 #include <dali/integration-api/debug.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
29 #include <dali-toolkit/internal/text/glyph-run.h>
30 #include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
31 #include <dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.h>
32 #include <dali-toolkit/internal/text/text-view.h>
33
34 using namespace Dali;
35 using namespace Dali::Toolkit;
36 using namespace Dali::Toolkit::Text;
37
38 namespace
39 {
40 #if defined(DEBUG_ENABLED)
41   Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, true, "LOG_TEXT_RENDERING");
42 #endif
43
44 const float ZERO( 0.0f );
45 const float HALF( 0.5f );
46 const float ONE( 1.0f );
47 const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
48 const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
49 }
50
51 struct AtlasRenderer::Impl
52 {
53   enum Style
54   {
55     STYLE_NORMAL,
56     STYLE_DROP_SHADOW
57   };
58
59   struct MeshRecord
60   {
61     MeshRecord()
62     : mAtlasId( 0u )
63     {
64     }
65
66     uint32_t mAtlasId;
67     AtlasManager::Mesh2D mMesh;
68     FrameBufferImage mBuffer;
69   };
70
71   /**
72    * brief Struct used to generate the underline mesh.
73    * There is one Extent per line of text.
74    */
75   struct Extent
76   {
77     Extent()
78     : mBaseLine( 0.0f ),
79       mLeft( 0.0f ),
80       mRight( 0.0f ),
81       mUnderlinePosition( 0.0f ),
82       mUnderlineThickness( 0.0f ),
83       mMeshRecordIndex( 0u )
84     {
85     }
86
87     float mBaseLine;
88     float mLeft;
89     float mRight;
90     float mUnderlinePosition;
91     float mUnderlineThickness;
92     uint32_t mMeshRecordIndex;
93   };
94
95   struct MaxBlockSize
96   {
97     MaxBlockSize()
98     : mFontId( 0 ),
99       mNeededBlockWidth( 0 ),
100       mNeededBlockHeight( 0 )
101     {
102     }
103
104     FontId mFontId;
105     uint32_t mNeededBlockWidth;
106     uint32_t mNeededBlockHeight;
107   };
108
109   struct CheckEntry
110   {
111     CheckEntry()
112     : mFontId( 0 ),
113       mIndex( 0 )
114     {
115     }
116
117     FontId mFontId;
118     Text::GlyphIndex mIndex;
119   };
120
121   struct TextCacheEntry
122   {
123     TextCacheEntry()
124     : mFontId( 0 ),
125       mIndex( 0 ),
126       mImageId( 0 )
127     {
128     }
129
130     FontId mFontId;
131     Text::GlyphIndex mIndex;
132     uint32_t mImageId;
133   };
134
135   Impl()
136   : mDepth( 0 )
137   {
138     mGlyphManager = AtlasGlyphManager::Get();
139     mFontClient = TextAbstraction::FontClient::Get();
140
141     mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
142     mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
143     mQuadVertexFormat[ "aColor" ] = Property::VECTOR4;
144   }
145
146   bool IsGlyphUnderlined( GlyphIndex index,
147                           const Vector<GlyphRun>& underlineRuns )
148   {
149     for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
150            endIt = underlineRuns.End();
151            it != endIt;
152          ++it )
153     {
154       const GlyphRun& run = *it;
155
156       if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
157       {
158         return true;
159       }
160     }
161
162     return false;
163   }
164
165   void AddGlyphs( Text::ViewInterface& view,
166                   const Vector<Vector2>& positions,
167                   const Vector<GlyphInfo>& glyphs,
168                   const Vector4& defaultColor,
169                   const Vector4* const colorsBuffer,
170                   const ColorIndex* const colorIndicesBuffer,
171                   int depth )
172   {
173     AtlasManager::AtlasSlot slot;
174     std::vector< MeshRecord > meshContainer;
175     Vector< Extent > extents;
176     TextCacheEntry textCacheEntry;
177     mDepth = depth;
178
179     const Vector2& actorSize( view.GetControlSize() );
180     const Vector2& textSize( view.GetLayoutSize() );
181     const Vector2 halfTextSize( textSize * 0.5f );
182     const Vector2& shadowOffset( view.GetShadowOffset() );
183     const Vector4& shadowColor( view.GetShadowColor() );
184     const bool underlineEnabled( view.IsUnderlineEnabled() );
185     const Vector4& underlineColor( view.GetUnderlineColor() );
186     const float underlineHeight( view.GetUnderlineHeight() );
187
188     const bool useDefaultColor = ( NULL == colorsBuffer );
189
190     // Get the underline runs.
191     const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
192     Vector<GlyphRun> underlineRuns;
193     underlineRuns.Resize( numberOfUnderlineRuns );
194     view.GetUnderlineRuns( underlineRuns.Begin(),
195                            0u,
196                            numberOfUnderlineRuns );
197
198     bool thereAreUnderlinedGlyphs = false;
199
200     float currentUnderlinePosition = ZERO;
201     float currentUnderlineThickness = underlineHeight;
202     uint32_t currentBlockSize = 0;
203     FontId lastFontId = 0;
204     FontId lastUnderlinedFontId = 0;
205     Style style = STYLE_NORMAL;
206
207     if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
208     {
209       style = STYLE_DROP_SHADOW;
210     }
211
212     CalculateBlocksSize( glyphs );
213
214     // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
215     Vector< TextCacheEntry > newTextCache;
216     const GlyphInfo* const glyphsBuffer = glyphs.Begin();
217     const Vector2* const positionsBuffer = positions.Begin();
218
219     for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
220     {
221       const GlyphInfo& glyph = *( glyphsBuffer + i );
222
223       const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
224       thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
225
226       // No operation for white space
227       if( glyph.width && glyph.height )
228       {
229         // Are we still using the same fontId as previous
230         if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
231         {
232           // We need to fetch fresh font underline metrics
233           FontMetrics fontMetrics;
234           mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
235           currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
236           const float descender = ceil( fabsf( fontMetrics.descender ) );
237
238           if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
239           {
240             currentUnderlineThickness = fontMetrics.underlineThickness;
241
242             // Ensure underline will be at least a pixel high
243             if ( currentUnderlineThickness < ONE )
244             {
245               currentUnderlineThickness = ONE;
246             }
247             else
248             {
249               currentUnderlineThickness = ceil( currentUnderlineThickness );
250             }
251           }
252
253           // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
254           if( currentUnderlinePosition > descender )
255           {
256             currentUnderlinePosition = descender;
257           }
258
259           if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
260           {
261             // Move offset down by one ( EFL behavior )
262             currentUnderlinePosition = ONE;
263           }
264
265           lastUnderlinedFontId = glyph.fontId;
266         } // underline
267
268         if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
269         {
270           // Select correct size for new atlas if needed....?
271           if( lastFontId != glyph.fontId )
272           {
273             uint32_t index = 0u;
274             for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
275                    endIt = mBlockSizes.end();
276                  it != endIt;
277                  ++it, ++index )
278             {
279               const MaxBlockSize& blockSize = *it;
280               if( blockSize.mFontId == glyph.fontId )
281               {
282                 currentBlockSize = index;
283                 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
284                                                DEFAULT_ATLAS_HEIGHT,
285                                                blockSize.mNeededBlockWidth,
286                                                blockSize.mNeededBlockHeight );
287               }
288             }
289           }
290
291           // Create a new image for the glyph
292           PixelData bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
293           if( bitmap )
294           {
295             MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
296
297             // Ensure that the next image will fit into the current block size
298             bool setSize = false;
299             if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
300             {
301               setSize = true;
302               blockSize.mNeededBlockWidth = bitmap.GetWidth();
303             }
304             if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
305             {
306               setSize = true;
307               blockSize.mNeededBlockHeight = bitmap.GetHeight();
308             }
309
310             if( setSize )
311             {
312               mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
313                                              DEFAULT_ATLAS_HEIGHT,
314                                              blockSize.mNeededBlockWidth,
315                                              blockSize.mNeededBlockHeight );
316             }
317
318             // Locate a new slot for our glyph
319             mGlyphManager.Add( glyph, bitmap, slot );
320           }
321         }
322         else
323         {
324           // We have 2+ copies of the same glyph
325           mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
326         }
327
328         // Move the origin (0,0) of the mesh to the center of the actor
329         const Vector2 position = *( positionsBuffer + i ) - halfTextSize;
330
331         // Generate mesh data for this quad, plugging in our supplied position
332         AtlasManager::Mesh2D newMesh;
333         mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
334         textCacheEntry.mFontId = glyph.fontId;
335         textCacheEntry.mImageId = slot.mImageId;
336         textCacheEntry.mIndex = glyph.index;
337         newTextCache.PushBack( textCacheEntry );
338
339         AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
340
341         // Adjust the vertices if the fixed-size font should be down-scaled
342         if( glyph.scaleFactor > 0 )
343         {
344           for( unsigned int index = 0u, size = newMesh.mVertices.Count();
345                index < size;
346                ++index )
347           {
348             AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
349
350             // Set the position of the vertex.
351             vertex.mPosition.x = position.x + ( ( vertex.mPosition.x - position.x ) * glyph.scaleFactor );
352             vertex.mPosition.y = position.y + ( ( vertex.mPosition.y - position.y ) * glyph.scaleFactor );
353           }
354         }
355
356         // Get the color of the character.
357         const ColorIndex colorIndex = useDefaultColor ? 0u : *( colorIndicesBuffer + i );
358         const Vector4& color = ( useDefaultColor || ( 0u == colorIndex ) ) ? defaultColor : *( colorsBuffer + colorIndex - 1u );
359
360         for( unsigned int index = 0u, size = newMesh.mVertices.Count();
361              index < size;
362              ++index )
363         {
364           AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
365
366           // Set the color of the vertex.
367           vertex.mColor = color;
368         }
369
370         // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
371         StitchTextMesh( meshContainer,
372                         newMesh,
373                         extents,
374                         position.y + glyph.yBearing,
375                         underlineGlyph,
376                         currentUnderlinePosition,
377                         currentUnderlineThickness,
378                         slot );
379         lastFontId = glyph.fontId;
380       }
381     } // glyphs
382
383     // Now remove references for the old text
384     RemoveText();
385     mTextCache.Swap( newTextCache );
386
387     if( thereAreUnderlinedGlyphs )
388     {
389       // Check to see if any of the text needs an underline
390       GenerateUnderlines( meshContainer, extents, underlineColor );
391     }
392
393     // For each MeshData object, create a mesh actor and add to the renderable actor
394     if( !meshContainer.empty() )
395     {
396       for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
397               endIt = meshContainer.end();
398             it != endIt; ++it )
399       {
400         MeshRecord& meshRecord = *it;
401
402         Actor actor = CreateMeshActor( meshRecord, textSize );
403
404         // Create an effect if necessary
405         if( style == STYLE_DROP_SHADOW )
406         {
407           // Change the color of the vertices.
408           for( Vector<AtlasManager::Vertex2D>::Iterator vIt =  meshRecord.mMesh.mVertices.Begin(),
409                  vEndIt = meshRecord.mMesh.mVertices.End();
410                vIt != vEndIt;
411                ++vIt )
412           {
413             AtlasManager::Vertex2D& vertex = *vIt;
414
415             vertex.mColor = shadowColor;
416           }
417
418           // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
419           Actor containerActor = Actor::New();
420           containerActor.SetParentOrigin( ParentOrigin::CENTER );
421           containerActor.SetSize( actorSize );
422
423           Actor shadowActor = CreateMeshActor( meshRecord, textSize );
424 #if defined(DEBUG_ENABLED)
425           shadowActor.SetName( "Text Shadow renderable actor" );
426 #endif
427           // Offset shadow in x and y
428           shadowActor.RegisterProperty("uOffset", shadowOffset );
429           if( actor.GetRendererCount() )
430           {
431             Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
432             int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
433             renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
434             containerActor.Add( shadowActor );
435             containerActor.Add( actor );
436 #if defined(DEBUG_ENABLED)
437             containerActor.SetName("TextContainer");
438 #endif
439             actor = containerActor;
440           }
441         }
442
443         if( mActor )
444         {
445           mActor.Add( actor );
446         }
447         else
448         {
449           mActor = actor;
450         }
451       }
452     }
453 #if defined(DEBUG_ENABLED)
454     Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
455     DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
456                                                 metrics.mGlyphCount,
457                                                 metrics.mAtlasMetrics.mAtlasCount,
458                                                 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
459
460     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
461
462     for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
463     {
464       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "   Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
465                                                  i + 1, i > 8 ? "" : " ",
466                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8  " : "BGRA",
467                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
468                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
469                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
470                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
471                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
472                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
473     }
474 #endif
475   }
476
477   void RemoveText()
478   {
479     for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
480     {
481       mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
482     }
483     mTextCache.Resize( 0 );
484   }
485
486   Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
487   {
488     PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat );
489     quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
490
491     Geometry quadGeometry = Geometry::New();
492     quadGeometry.AddVertexBuffer( quadVertices );
493     quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0],  meshRecord.mMesh.mIndices.Size() );
494
495     TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
496     Shader shader( mGlyphManager.GetShader( meshRecord.mAtlasId ) );
497     Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
498     renderer.SetTextures( textureSet );
499     renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON );
500     renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
501     Actor actor = Actor::New();
502 #if defined(DEBUG_ENABLED)
503     actor.SetName( "Text renderable actor" );
504 #endif
505     actor.AddRenderer( renderer );
506
507     // Keep all of the origins aligned
508     actor.SetParentOrigin( ParentOrigin::TOP_LEFT );
509     actor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
510     actor.SetSize( actorSize );
511     actor.RegisterProperty("uOffset", Vector2::ZERO );
512     return actor;
513   }
514
515   void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
516                        AtlasManager::Mesh2D& newMesh,
517                        Vector< Extent >& extents,
518                        float baseLine,
519                        bool underlineGlyph,
520                        float underlinePosition,
521                        float underlineThickness,
522                        AtlasManager::AtlasSlot& slot )
523   {
524     if ( slot.mImageId )
525     {
526       float left = newMesh.mVertices[ 0 ].mPosition.x;
527       float right = newMesh.mVertices[ 1 ].mPosition.x;
528
529       // Check to see if there's a mesh data object that references the same atlas ?
530       uint32_t index = 0;
531       for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
532               mEndIt = meshContainer.end();
533             mIt != mEndIt;
534             ++mIt, ++index )
535       {
536         if( slot.mAtlasId == mIt->mAtlasId )
537         {
538           // Append the mesh to the existing mesh and adjust any extents
539           Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
540
541           if( underlineGlyph )
542           {
543             AdjustExtents( extents,
544                            meshContainer,
545                            index,
546                            left,
547                            right,
548                            baseLine,
549                            underlinePosition,
550                            underlineThickness );
551           }
552
553           return;
554         }
555       }
556
557       // No mesh data object currently exists that references this atlas, so create a new one
558       MeshRecord meshRecord;
559       meshRecord.mAtlasId = slot.mAtlasId;
560       meshRecord.mMesh = newMesh;
561       meshContainer.push_back( meshRecord );
562
563       if( underlineGlyph )
564       {
565         // Adjust extents for this new meshrecord
566         AdjustExtents( extents,
567                        meshContainer,
568                        meshContainer.size() - 1u,
569                        left,
570                        right,
571                        baseLine,
572                        underlinePosition,
573                        underlineThickness );
574       }
575     }
576   }
577
578   void AdjustExtents( Vector< Extent >& extents,
579                       std::vector< MeshRecord>& meshRecords,
580                       uint32_t index,
581                       float left,
582                       float right,
583                       float baseLine,
584                       float underlinePosition,
585                       float underlineThickness )
586   {
587     bool foundExtent = false;
588     for ( Vector< Extent >::Iterator eIt = extents.Begin(),
589             eEndIt = extents.End();
590           eIt != eEndIt;
591           ++eIt )
592     {
593       if ( Equals( baseLine, eIt->mBaseLine ) )
594       {
595         foundExtent = true;
596         if ( left < eIt->mLeft )
597         {
598           eIt->mLeft = left;
599         }
600         if ( right > eIt->mRight  )
601         {
602           eIt->mRight = right;
603         }
604
605         if ( underlinePosition > eIt->mUnderlinePosition )
606         {
607           eIt->mUnderlinePosition = underlinePosition;
608         }
609         if ( underlineThickness > eIt->mUnderlineThickness )
610         {
611           eIt->mUnderlineThickness = underlineThickness;
612         }
613       }
614     }
615     if ( !foundExtent )
616     {
617       Extent extent;
618       extent.mLeft = left;
619       extent.mRight = right;
620       extent.mBaseLine = baseLine;
621       extent.mUnderlinePosition = underlinePosition;
622       extent.mUnderlineThickness = underlineThickness;
623       extent.mMeshRecordIndex = index;
624       extents.PushBack( extent );
625     }
626   }
627
628   void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
629   {
630     for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
631            glyphEndIt = glyphs.End();
632          glyphIt != glyphEndIt;
633          ++glyphIt )
634     {
635       const FontId fontId = (*glyphIt).fontId;
636       bool foundFont = false;
637
638       for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
639              blockEndIt = mBlockSizes.end();
640            blockIt != blockEndIt;
641            ++blockIt )
642       {
643         if( (*blockIt).mFontId == fontId )
644         {
645           foundFont = true;
646           break;
647         }
648       }
649
650       if ( !foundFont )
651       {
652         FontMetrics fontMetrics;
653         mFontClient.GetFontMetrics( fontId, fontMetrics );
654
655         MaxBlockSize maxBlockSize;
656         maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
657         maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
658         maxBlockSize.mFontId = fontId;
659
660         mBlockSizes.push_back( maxBlockSize );
661       }
662     }
663   }
664
665   void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
666                            Vector< Extent >& extents,
667                            const Vector4& underlineColor )
668   {
669     AtlasManager::Mesh2D newMesh;
670     unsigned short faceIndex = 0;
671     for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
672             eEndIt = extents.End();
673           eIt != eEndIt;
674           ++eIt )
675     {
676       AtlasManager::Vertex2D vert;
677       uint32_t index = eIt->mMeshRecordIndex;
678       Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
679
680       // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
681       float u = HALF / uv.x;
682       float v = HALF / uv.y;
683       float thickness = eIt->mUnderlineThickness;
684       float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
685       float tlx = eIt->mLeft;
686       float brx = eIt->mRight;
687
688       vert.mPosition.x = tlx;
689       vert.mPosition.y = baseLine;
690       vert.mTexCoords.x = ZERO;
691       vert.mTexCoords.y = ZERO;
692       vert.mColor = underlineColor;
693       newMesh.mVertices.PushBack( vert );
694
695       vert.mPosition.x = brx;
696       vert.mPosition.y = baseLine;
697       vert.mTexCoords.x = u;
698       vert.mColor = underlineColor;
699       newMesh.mVertices.PushBack( vert );
700
701       vert.mPosition.x = tlx;
702       vert.mPosition.y = baseLine + thickness;
703       vert.mTexCoords.x = ZERO;
704       vert.mTexCoords.y = v;
705       vert.mColor = underlineColor;
706       newMesh.mVertices.PushBack( vert );
707
708       vert.mPosition.x = brx;
709       vert.mPosition.y = baseLine + thickness;
710       vert.mTexCoords.x = u;
711       vert.mColor = underlineColor;
712       newMesh.mVertices.PushBack( vert );
713
714       // Six indices in counter clockwise winding
715       newMesh.mIndices.PushBack( faceIndex + 1u );
716       newMesh.mIndices.PushBack( faceIndex );
717       newMesh.mIndices.PushBack( faceIndex + 2u );
718       newMesh.mIndices.PushBack( faceIndex + 2u );
719       newMesh.mIndices.PushBack( faceIndex + 3u );
720       newMesh.mIndices.PushBack( faceIndex + 1u );
721       faceIndex += 4;
722
723       Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
724     }
725   }
726
727   Actor mActor;                                       ///< The actor parent which renders the text
728   AtlasGlyphManager mGlyphManager;                    ///< Glyph Manager to handle upload and caching
729   TextAbstraction::FontClient mFontClient;            ///> The font client used to supply glyph information
730   std::vector< MaxBlockSize > mBlockSizes;            ///> Maximum size needed to contain a glyph in a block within a new atlas
731   Vector< TextCacheEntry > mTextCache;                ///> Caches data from previous render
732   Property::Map mQuadVertexFormat;                    ///> Describes the vertex format for text
733   int mDepth;                                         ///> DepthIndex passed by control when connect to stage
734 };
735
736 Text::RendererPtr AtlasRenderer::New()
737 {
738   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
739
740   return Text::RendererPtr( new AtlasRenderer() );
741 }
742
743 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
744 {
745   DALI_LOG_INFO( gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n" );
746
747   UnparentAndReset( mImpl->mActor );
748
749   Length numberOfGlyphs = view.GetNumberOfGlyphs();
750
751   if( numberOfGlyphs > 0u )
752   {
753     Vector<GlyphInfo> glyphs;
754     glyphs.Resize( numberOfGlyphs );
755
756     Vector<Vector2> positions;
757     positions.Resize( numberOfGlyphs );
758
759     numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
760                                      positions.Begin(),
761                                      0u,
762                                      numberOfGlyphs );
763
764     glyphs.Resize( numberOfGlyphs );
765     positions.Resize( numberOfGlyphs );
766
767     const Vector4* const colorsBuffer = view.GetColors();
768     const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
769     const Vector4& defaultColor = view.GetTextColor();
770
771     mImpl->AddGlyphs( view,
772                       positions,
773                       glyphs,
774                       defaultColor,
775                       colorsBuffer,
776                       colorIndicesBuffer,
777                       depth );
778
779     /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
780     /* This renderable actor is used to position the text, other "decorations" can rely on there always being an Actor regardless of it is whitespace or regular text. */
781     if ( !mImpl->mActor )
782     {
783       mImpl->mActor = Actor::New();
784     }
785   }
786
787   return mImpl->mActor;
788 }
789
790 AtlasRenderer::AtlasRenderer()
791 {
792   mImpl = new Impl();
793
794 }
795
796 AtlasRenderer::~AtlasRenderer()
797 {
798   mImpl->RemoveText();
799   delete mImpl;
800 }