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