6fe86a453e1b3ceeb702b1e8a527e8011f0f5920
[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         mActor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
455       }
456
457       for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
458               endIt = meshContainer.end();
459             it != endIt; ++it )
460       {
461         MeshRecord& meshRecord = *it;
462
463         Actor actor = CreateMeshActor( meshRecord, textSize, STYLE_NORMAL );
464
465         // Whether the actor has renderers.
466         const bool hasRenderer = actor.GetRendererCount() > 0u;
467
468         // Create an effect if necessary
469         if( hasRenderer &&
470             ( style == STYLE_DROP_SHADOW ) )
471         {
472           // Change the color of the vertices.
473           for( Vector<AtlasManager::Vertex2D>::Iterator vIt =  meshRecord.mMesh.mVertices.Begin(),
474                  vEndIt = meshRecord.mMesh.mVertices.End();
475                vIt != vEndIt;
476                ++vIt )
477           {
478             AtlasManager::Vertex2D& vertex = *vIt;
479
480             vertex.mColor = shadowColor;
481           }
482
483           Actor shadowActor = CreateMeshActor( meshRecord, textSize, STYLE_DROP_SHADOW );
484 #if defined(DEBUG_ENABLED)
485           shadowActor.SetName( "Text Shadow renderable actor" );
486 #endif
487           // Offset shadow in x and y
488           shadowActor.RegisterProperty("uOffset", shadowOffset );
489           Dali::Renderer renderer( shadowActor.GetRendererAt( 0 ) );
490           int depthIndex = renderer.GetProperty<int>(Dali::Renderer::Property::DEPTH_INDEX);
491           renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, depthIndex - 1 );
492           mActor.Add( shadowActor );
493         }
494
495         if( hasRenderer )
496         {
497           mActor.Add( actor );
498         }
499       }
500     }
501 #if defined(DEBUG_ENABLED)
502     Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
503     DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
504                                                 metrics.mGlyphCount,
505                                                 metrics.mAtlasMetrics.mAtlasCount,
506                                                 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
507
508     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
509
510     for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
511     {
512       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "   Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
513                                                  i + 1, i > 8 ? "" : " ",
514                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8  " : "BGRA",
515                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
516                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
517                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
518                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
519                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
520                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
521     }
522 #endif
523   }
524
525   void RemoveText()
526   {
527     for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
528     {
529       mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
530     }
531     mTextCache.Resize( 0 );
532   }
533
534   Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize, Style style )
535   {
536     PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat );
537     quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ), meshRecord.mMesh.mVertices.Size() );
538
539     Geometry quadGeometry = Geometry::New();
540     quadGeometry.AddVertexBuffer( quadVertices );
541     quadGeometry.SetIndexBuffer( &meshRecord.mMesh.mIndices[0],  meshRecord.mMesh.mIndices.Size() );
542
543     TextureSet textureSet( mGlyphManager.GetTextures( meshRecord.mAtlasId ) );
544
545     // Choose the shader to use.
546     const bool isColorShader = ( STYLE_DROP_SHADOW != style ) && ( Pixel::BGRA8888 == mGlyphManager.GetPixelFormat( meshRecord.mAtlasId ) );
547     Shader shader;
548     if( isColorShader )
549     {
550       // The glyph is an emoji and is not a shadow.
551       if( !mShaderRgba )
552       {
553         mShaderRgba = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_RGBA );
554       }
555       shader = mShaderRgba;
556     }
557     else
558     {
559       // The glyph is text or a shadow.
560       if( !mShaderL8 )
561       {
562         mShaderL8 = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER_L8 );
563       }
564       shader = mShaderL8;
565     }
566
567     Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, shader );
568     renderer.SetTextures( textureSet );
569     renderer.SetProperty( Dali::Renderer::Property::BLEND_MODE, BlendMode::ON );
570     renderer.SetProperty( Dali::Renderer::Property::DEPTH_INDEX, DepthIndex::CONTENT + mDepth );
571
572     Actor actor = Actor::New();
573 #if defined(DEBUG_ENABLED)
574     actor.SetName( "Text renderable actor" );
575 #endif
576     actor.AddRenderer( renderer );
577     // Keep all of the origins aligned
578     actor.SetParentOrigin( ParentOrigin::TOP_LEFT );
579     actor.SetAnchorPoint( AnchorPoint::TOP_LEFT );
580     actor.SetSize( actorSize );
581     actor.RegisterProperty("uOffset", Vector2::ZERO );
582     actor.SetColorMode( USE_OWN_MULTIPLY_PARENT_COLOR );
583     return actor;
584   }
585
586   void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
587                        AtlasManager::Mesh2D& newMesh,
588                        Vector< Extent >& extents,
589                        float baseLine,
590                        bool underlineGlyph,
591                        float underlinePosition,
592                        float underlineThickness,
593                        AtlasManager::AtlasSlot& slot )
594   {
595     if ( slot.mImageId )
596     {
597       float left = newMesh.mVertices[ 0 ].mPosition.x;
598       float right = newMesh.mVertices[ 1 ].mPosition.x;
599
600       // Check to see if there's a mesh data object that references the same atlas ?
601       uint32_t index = 0;
602       for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
603               mEndIt = meshContainer.end();
604             mIt != mEndIt;
605             ++mIt, ++index )
606       {
607         if( slot.mAtlasId == mIt->mAtlasId )
608         {
609           // Append the mesh to the existing mesh and adjust any extents
610           Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
611
612           if( underlineGlyph )
613           {
614             AdjustExtents( extents,
615                            meshContainer,
616                            index,
617                            left,
618                            right,
619                            baseLine,
620                            underlinePosition,
621                            underlineThickness );
622           }
623
624           return;
625         }
626       }
627
628       // No mesh data object currently exists that references this atlas, so create a new one
629       MeshRecord meshRecord;
630       meshRecord.mAtlasId = slot.mAtlasId;
631       meshRecord.mMesh = newMesh;
632       meshContainer.push_back( meshRecord );
633
634       if( underlineGlyph )
635       {
636         // Adjust extents for this new meshrecord
637         AdjustExtents( extents,
638                        meshContainer,
639                        meshContainer.size() - 1u,
640                        left,
641                        right,
642                        baseLine,
643                        underlinePosition,
644                        underlineThickness );
645       }
646     }
647   }
648
649   void AdjustExtents( Vector< Extent >& extents,
650                       std::vector< MeshRecord>& meshRecords,
651                       uint32_t index,
652                       float left,
653                       float right,
654                       float baseLine,
655                       float underlinePosition,
656                       float underlineThickness )
657   {
658     bool foundExtent = false;
659     for ( Vector< Extent >::Iterator eIt = extents.Begin(),
660             eEndIt = extents.End();
661           eIt != eEndIt;
662           ++eIt )
663     {
664       if ( Equals( baseLine, eIt->mBaseLine ) )
665       {
666         foundExtent = true;
667         if ( left < eIt->mLeft )
668         {
669           eIt->mLeft = left;
670         }
671         if ( right > eIt->mRight  )
672         {
673           eIt->mRight = right;
674         }
675
676         if ( underlinePosition > eIt->mUnderlinePosition )
677         {
678           eIt->mUnderlinePosition = underlinePosition;
679         }
680         if ( underlineThickness > eIt->mUnderlineThickness )
681         {
682           eIt->mUnderlineThickness = underlineThickness;
683         }
684       }
685     }
686     if ( !foundExtent )
687     {
688       Extent extent;
689       extent.mLeft = left;
690       extent.mRight = right;
691       extent.mBaseLine = baseLine;
692       extent.mUnderlinePosition = underlinePosition;
693       extent.mUnderlineThickness = underlineThickness;
694       extent.mMeshRecordIndex = index;
695       extents.PushBack( extent );
696     }
697   }
698
699   void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
700   {
701     for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
702            glyphEndIt = glyphs.End();
703          glyphIt != glyphEndIt;
704          ++glyphIt )
705     {
706       const FontId fontId = (*glyphIt).fontId;
707       bool foundFont = false;
708
709       for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
710              blockEndIt = mBlockSizes.end();
711            blockIt != blockEndIt;
712            ++blockIt )
713       {
714         if( (*blockIt).mFontId == fontId )
715         {
716           foundFont = true;
717           break;
718         }
719       }
720
721       if ( !foundFont )
722       {
723         FontMetrics fontMetrics;
724         mFontClient.GetFontMetrics( fontId, fontMetrics );
725
726         MaxBlockSize maxBlockSize;
727         maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
728         maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
729         maxBlockSize.mFontId = fontId;
730
731         mBlockSizes.push_back( maxBlockSize );
732       }
733     }
734   }
735
736   void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
737                            Vector< Extent >& extents,
738                            const Vector4& underlineColor )
739   {
740     AtlasManager::Mesh2D newMesh;
741     unsigned short faceIndex = 0;
742     for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
743             eEndIt = extents.End();
744           eIt != eEndIt;
745           ++eIt )
746     {
747       AtlasManager::Vertex2D vert;
748       uint32_t index = eIt->mMeshRecordIndex;
749       Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
750
751       // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
752       float u = HALF / uv.x;
753       float v = HALF / uv.y;
754       float thickness = eIt->mUnderlineThickness;
755       float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
756       float tlx = eIt->mLeft;
757       float brx = eIt->mRight;
758
759       vert.mPosition.x = tlx;
760       vert.mPosition.y = baseLine;
761       vert.mTexCoords.x = ZERO;
762       vert.mTexCoords.y = ZERO;
763       vert.mColor = underlineColor;
764       newMesh.mVertices.PushBack( vert );
765
766       vert.mPosition.x = brx;
767       vert.mPosition.y = baseLine;
768       vert.mTexCoords.x = u;
769       vert.mColor = underlineColor;
770       newMesh.mVertices.PushBack( vert );
771
772       vert.mPosition.x = tlx;
773       vert.mPosition.y = baseLine + thickness;
774       vert.mTexCoords.x = ZERO;
775       vert.mTexCoords.y = v;
776       vert.mColor = underlineColor;
777       newMesh.mVertices.PushBack( vert );
778
779       vert.mPosition.x = brx;
780       vert.mPosition.y = baseLine + thickness;
781       vert.mTexCoords.x = u;
782       vert.mColor = underlineColor;
783       newMesh.mVertices.PushBack( vert );
784
785       // Six indices in counter clockwise winding
786       newMesh.mIndices.PushBack( faceIndex + 1u );
787       newMesh.mIndices.PushBack( faceIndex );
788       newMesh.mIndices.PushBack( faceIndex + 2u );
789       newMesh.mIndices.PushBack( faceIndex + 2u );
790       newMesh.mIndices.PushBack( faceIndex + 3u );
791       newMesh.mIndices.PushBack( faceIndex + 1u );
792       faceIndex += 4;
793
794       Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
795     }
796   }
797
798   Actor mActor;                                       ///< The actor parent which renders the text
799   AtlasGlyphManager mGlyphManager;                    ///< Glyph Manager to handle upload and caching
800   TextAbstraction::FontClient mFontClient;            ///< The font client used to supply glyph information
801   Shader mShaderL8;                                   ///< The shader for glyphs and emoji's shadows.
802   Shader mShaderRgba;                                 ///< The shader for emojis.
803   std::vector< MaxBlockSize > mBlockSizes;            ///< Maximum size needed to contain a glyph in a block within a new atlas
804   Vector< TextCacheEntry > mTextCache;                ///< Caches data from previous render
805   Property::Map mQuadVertexFormat;                    ///< Describes the vertex format for text
806   int mDepth;                                         ///< DepthIndex passed by control when connect to stage
807 };
808
809 Text::RendererPtr AtlasRenderer::New()
810 {
811   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
812
813   return Text::RendererPtr( new AtlasRenderer() );
814 }
815
816 Actor AtlasRenderer::Render( Text::ViewInterface& view,
817                              float& alignmentOffset,
818                              int depth )
819 {
820   DALI_LOG_INFO( gLogFilter, Debug::General, "Text::AtlasRenderer::Render()\n" );
821
822   UnparentAndReset( mImpl->mActor );
823
824   Length numberOfGlyphs = view.GetNumberOfGlyphs();
825
826   if( numberOfGlyphs > 0u )
827   {
828     Vector<GlyphInfo> glyphs;
829     glyphs.Resize( numberOfGlyphs );
830
831     Vector<Vector2> positions;
832     positions.Resize( numberOfGlyphs );
833
834     numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
835                                      positions.Begin(),
836                                      alignmentOffset,
837                                      0u,
838                                      numberOfGlyphs );
839
840     glyphs.Resize( numberOfGlyphs );
841     positions.Resize( numberOfGlyphs );
842
843     const Vector4* const colorsBuffer = view.GetColors();
844     const ColorIndex* const colorIndicesBuffer = view.GetColorIndices();
845     const Vector4& defaultColor = view.GetTextColor();
846
847     mImpl->AddGlyphs( view,
848                       positions,
849                       glyphs,
850                       defaultColor,
851                       colorsBuffer,
852                       colorIndicesBuffer,
853                       depth,
854                       alignmentOffset );
855
856     /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
857     /* 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. */
858     if ( !mImpl->mActor )
859     {
860       mImpl->mActor = Actor::New();
861     }
862   }
863
864   return mImpl->mActor;
865 }
866
867 AtlasRenderer::AtlasRenderer()
868 {
869   mImpl = new Impl();
870
871 }
872
873 AtlasRenderer::~AtlasRenderer()
874 {
875   mImpl->RemoveText();
876   delete mImpl;
877 }