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