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