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