Fix for shadow 'leak' reported on SPIN homescreen.
[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     RemoveAllShadowRenderTasks();
362
363     if( thereAreUnderlinedGlyphs )
364     {
365       // Check to see if any of the text needs an underline
366       GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
367     }
368
369     // For each MeshData object, create a mesh actor and add to the renderable actor
370     if ( meshContainer.size() )
371     {
372       for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(); mIt != meshContainer.end(); ++mIt )
373       {
374         Actor actor = CreateMeshActor( *mIt, actorSize );
375
376         // Create an effect if necessary
377         if ( style == STYLE_DROP_SHADOW )
378         {
379           Actor shadowActor = GenerateShadow( *mIt, actorSize, shadowOffset, shadowColor );
380           shadowActor.Add( actor );
381           actor = shadowActor;
382         }
383
384         if( mActor )
385         {
386           mActor.Add( actor );
387         }
388         else
389         {
390           mActor = actor;
391         }
392       }
393     }
394 #if defined(DEBUG_ENABLED)
395     Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
396     DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
397                                                 metrics.mGlyphCount,
398                                                 metrics.mAtlasMetrics.mAtlasCount,
399                                                 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
400
401     DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
402
403     for ( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
404     {
405       DALI_LOG_INFO( gLogFilter, Debug::Verbose, "   Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
406                                                  i + 1, i > 8 ? "" : " ",
407                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8  " : "BGRA",
408                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
409                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
410                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
411                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
412                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
413                                                  metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
414     }
415 #endif
416   }
417
418   void RemoveText()
419   {
420     for ( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
421     {
422       mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
423     }
424     mTextCache.Resize( 0 );
425   }
426
427   Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
428   {
429     PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat, meshRecord.mMesh.mVertices.Size() );
430     PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat, meshRecord.mMesh.mIndices.Size() );
431     quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ) );
432     quadIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ) );
433
434     Geometry quadGeometry = Geometry::New();
435     quadGeometry.AddVertexBuffer( quadVertices );
436     quadGeometry.SetIndexBuffer( quadIndices );
437
438     Material material = mGlyphManager.GetMaterial( meshRecord.mAtlasId );
439     Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, material );
440     renderer.SetDepthIndex( CONTENT_DEPTH_INDEX + mDepth );
441     Actor actor = Actor::New();
442 #if defined(DEBUG_ENABLED)
443     actor.SetName( "Text renderable actor" );
444 #endif
445     actor.AddRenderer( renderer );
446     actor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
447     actor.SetSize( actorSize );
448     actor.SetColor( meshRecord.mColor );
449     return actor;
450   }
451
452   void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
453                        AtlasManager::Mesh2D& newMesh,
454                        Vector< Extent >& extents,
455                        const Vector4& color,
456                        float baseLine,
457                        bool underlineGlyph,
458                        float underlinePosition,
459                        float underlineThickness,
460                        AtlasManager::AtlasSlot& slot )
461   {
462     if ( slot.mImageId )
463     {
464       float left = newMesh.mVertices[ 0 ].mPosition.x;
465       float right = newMesh.mVertices[ 1 ].mPosition.x;
466
467       // Check to see if there's a mesh data object that references the same atlas ?
468       uint32_t index = 0;
469       for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
470               mEndIt = meshContainer.end();
471             mIt != mEndIt;
472             ++mIt, ++index )
473       {
474         if ( slot.mAtlasId == mIt->mAtlasId && color == mIt->mColor )
475         {
476           // Stitch the mesh to the existing mesh and adjust any extents
477           mGlyphManager.StitchMesh( mIt->mMesh, newMesh );
478
479           if( underlineGlyph )
480           {
481             AdjustExtents( extents,
482                            meshContainer,
483                            index,
484                            left,
485                            right,
486                            baseLine,
487                            underlinePosition,
488                            underlineThickness );
489           }
490
491           return;
492         }
493       }
494
495       // No mesh data object currently exists that references this atlas, so create a new one
496       MeshRecord meshRecord;
497       meshRecord.mAtlasId = slot.mAtlasId;
498       meshRecord.mMesh = newMesh;
499       meshRecord.mColor = color;
500       meshContainer.push_back( meshRecord );
501
502       if( underlineGlyph )
503       {
504         // Adjust extents for this new meshrecord
505         AdjustExtents( extents,
506                        meshContainer,
507                        meshContainer.size() - 1u,
508                        left,
509                        right,
510                        baseLine,
511                        underlinePosition,
512                        underlineThickness );
513       }
514     }
515   }
516
517   void AdjustExtents( Vector< Extent >& extents,
518                       std::vector< MeshRecord>& meshRecords,
519                       uint32_t index,
520                       float left,
521                       float right,
522                       float baseLine,
523                       float underlinePosition,
524                       float underlineThickness )
525   {
526     bool foundExtent = false;
527     for ( Vector< Extent >::Iterator eIt = extents.Begin(),
528             eEndIt = extents.End();
529           eIt != eEndIt;
530           ++eIt )
531     {
532       if ( Equals( baseLine, eIt->mBaseLine ) )
533       {
534         foundExtent = true;
535         if ( left < eIt->mLeft )
536         {
537           eIt->mLeft = left;
538         }
539         if ( right > eIt->mRight  )
540         {
541           eIt->mRight = right;
542         }
543
544         if ( underlinePosition > eIt->mUnderlinePosition )
545         {
546           eIt->mUnderlinePosition = underlinePosition;
547         }
548         if ( underlineThickness > eIt->mUnderlineThickness )
549         {
550           eIt->mUnderlineThickness = underlineThickness;
551         }
552       }
553     }
554     if ( !foundExtent )
555     {
556       Extent extent;
557       extent.mLeft = left;
558       extent.mRight = right;
559       extent.mBaseLine = baseLine;
560       extent.mUnderlinePosition = underlinePosition;
561       extent.mUnderlineThickness = underlineThickness;
562       extent.mMeshRecordIndex = index;
563       extents.PushBack( extent );
564     }
565   }
566
567   void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
568   {
569     MaxBlockSize maxBlockSize;
570     for ( uint32_t i = 0; i < glyphs.Size(); ++i )
571     {
572       FontId fontId = glyphs[ i ].fontId;
573       bool foundFont = false;
574       for ( uint32_t j = 0; j < mBlockSizes.size(); ++j )
575       {
576         if ( mBlockSizes[ j ].mFontId == fontId )
577         {
578           foundFont = true;
579         }
580       }
581       if ( !foundFont )
582       {
583         FontMetrics fontMetrics;
584         mFontClient.GetFontMetrics( fontId, fontMetrics );
585         maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
586         maxBlockSize.mNeededBlockHeight = static_cast< uint32_t >( fontMetrics.height );
587         maxBlockSize.mFontId = fontId;
588         mBlockSizes.push_back( maxBlockSize );
589       }
590     }
591   }
592
593   void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
594                            Vector< Extent >& extents,
595                            const Vector4& underlineColor,
596                            const Vector4& textColor )
597   {
598     AtlasManager::Mesh2D newMesh;
599     unsigned short faceIndex = 0;
600     for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
601             eEndIt = extents.End();
602           eIt != eEndIt;
603           ++eIt )
604     {
605       AtlasManager::Vertex2D vert;
606       uint32_t index = eIt->mMeshRecordIndex;
607       Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
608
609       // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
610       float u = HALF / uv.x;
611       float v = HALF / uv.y;
612       float thickness = eIt->mUnderlineThickness;
613       float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
614       float tlx = eIt->mLeft;
615       float brx = eIt->mRight;
616
617       vert.mPosition.x = tlx;
618       vert.mPosition.y = baseLine;
619       vert.mTexCoords.x = ZERO;
620       vert.mTexCoords.y = ZERO;
621       newMesh.mVertices.PushBack( vert );
622
623       vert.mPosition.x = brx;
624       vert.mPosition.y = baseLine;
625       vert.mTexCoords.x = u;
626       newMesh.mVertices.PushBack( vert );
627
628       vert.mPosition.x = tlx;
629       vert.mPosition.y = baseLine + thickness;
630       vert.mTexCoords.x = ZERO;
631       vert.mTexCoords.y = v;
632       newMesh.mVertices.PushBack( vert );
633
634       vert.mPosition.x = brx;
635       vert.mPosition.y = baseLine + thickness;
636       vert.mTexCoords.x = u;
637       newMesh.mVertices.PushBack( vert );
638
639       // Six indices in counter clockwise winding
640       newMesh.mIndices.PushBack( faceIndex + 1u );
641       newMesh.mIndices.PushBack( faceIndex );
642       newMesh.mIndices.PushBack( faceIndex + 2u );
643       newMesh.mIndices.PushBack( faceIndex + 2u );
644       newMesh.mIndices.PushBack( faceIndex + 3u );
645       newMesh.mIndices.PushBack( faceIndex + 1u );
646       faceIndex += 4;
647
648       if ( underlineColor == textColor )
649       {
650         mGlyphManager.StitchMesh( meshRecords[ index ].mMesh, newMesh );
651       }
652       else
653       {
654         MeshRecord record;
655         record.mMesh = newMesh;
656         record.mAtlasId = meshRecords[ index ].mAtlasId;
657         record.mColor = underlineColor;
658         meshRecords.push_back( record );
659       }
660     }
661   }
662
663   Actor GenerateShadow( MeshRecord& meshRecord,
664                         const Vector2& actorSize,
665                         const Vector2& shadowOffset,
666                         const Vector4& shadowColor )
667   {
668     // Scan vertex buffer to determine width and height of effect buffer needed
669     const Vector< AtlasManager::Vertex2D >& verts = meshRecord.mMesh.mVertices;
670     float tlx = verts[ 0 ].mPosition.x;
671     float tly = verts[ 0 ].mPosition.y;
672     float brx = ZERO;
673     float bry = ZERO;
674
675     for ( uint32_t i = 0; i < verts.Size(); ++i )
676     {
677       if ( verts[ i ].mPosition.x < tlx )
678       {
679         tlx = verts[ i ].mPosition.x;
680       }
681       if ( verts[ i ].mPosition.y < tly )
682       {
683         tly = verts[ i ].mPosition.y;
684       }
685       if ( verts[ i ].mPosition.x > brx )
686       {
687         brx = verts[ i ].mPosition.x;
688       }
689       if ( verts[ i ].mPosition.y > bry )
690       {
691         bry = verts[ i ].mPosition.y;
692       }
693     }
694
695     float width = brx - tlx;
696     float height = bry - tly;
697     float divWidth = TWO / width;
698     float divHeight = TWO / height;
699
700     // Create a buffer to render to
701     meshRecord.mBuffer = FrameBufferImage::New( width, height );
702
703     // We will render a quad into this buffer
704     unsigned int indices[ 6 ] = { 1, 0, 2, 2, 3, 1 };
705     PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat, 4u );
706     PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat, sizeof(indices)/sizeof(indices[0]) );
707
708     AtlasManager::Vertex2D vertices[ 4 ] = {
709     { Vector2( tlx + shadowOffset.x, tly + shadowOffset.y ), Vector2( ZERO, ZERO ) },
710     { Vector2( brx + shadowOffset.x, tly + shadowOffset.y ), Vector2( ONE, ZERO ) },
711     { Vector2( tlx + shadowOffset.x, bry + shadowOffset.y ), Vector2( ZERO, ONE ) },
712     { Vector2( brx + shadowOffset.x, bry + shadowOffset.y ), Vector2( ONE, ONE ) } };
713
714     quadVertices.SetData( vertices );
715     quadIndices.SetData( indices );
716
717     Geometry quadGeometry = Geometry::New();
718     quadGeometry.AddVertexBuffer( quadVertices );
719     quadGeometry.SetIndexBuffer( quadIndices );
720
721     Sampler sampler = Sampler::New( meshRecord.mBuffer, "sTexture" );
722     Material material = Material::New( mGlyphManager.GetEffectBufferShader() );
723     material.AddSampler( sampler );
724
725     Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, material );
726
727     // Set depth index to -1.0 to make sure shadow is rendered first in 3D layers
728     renderer.SetDepthIndex( -1.0f );
729     Actor actor = Actor::New();
730     actor.AddRenderer( renderer );
731     actor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
732     actor.SetSize( actorSize );
733
734     // Create a sub actor to render the source with normalized vertex positions
735     Vector< AtlasManager::Vertex2D > normVertexList;
736     for ( uint32_t i = 0; i < verts.Size(); ++i )
737     {
738       AtlasManager::Vertex2D vertex = verts[ i ];
739       vertex.mPosition.x = ( ( vertex.mPosition.x - tlx ) * divWidth ) - ONE;
740       vertex.mPosition.y = ( ( vertex.mPosition.y - tly ) * divHeight ) - ONE;
741       normVertexList.PushBack( vertex );
742     }
743
744     PropertyBuffer normVertices = PropertyBuffer::New( mQuadVertexFormat, normVertexList.Size() );
745     PropertyBuffer normIndices = PropertyBuffer::New( mQuadIndexFormat, meshRecord.mMesh.mIndices.Size() );
746     normVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &normVertexList[ 0 ] ) );
747     normIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ) );
748
749     Geometry normGeometry = Geometry::New();
750     normGeometry.AddVertexBuffer( normVertices );
751     normGeometry.SetIndexBuffer( normIndices );
752
753     Material normMaterial = Material::New( mGlyphManager.GetGlyphShadowShader() );
754     Sampler normSampler =  mGlyphManager.GetSampler( meshRecord.mAtlasId );
755     normMaterial.AddSampler( normSampler );
756     Dali::Renderer normRenderer = Dali::Renderer::New( normGeometry, normMaterial );
757     Actor subActor = Actor::New();
758     subActor.AddRenderer( normRenderer );
759     subActor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
760     subActor.SetSize( actorSize );
761     subActor.SetColor( shadowColor );
762
763     // Create a render task to render the effect
764     RenderTask shadowTask = Stage::GetCurrent().GetRenderTaskList().CreateTask();
765     shadowTask.SetTargetFrameBuffer( meshRecord.mBuffer );
766     shadowTask.SetSourceActor( subActor );
767     shadowTask.SetClearEnabled( true );
768     shadowTask.SetClearColor( Vector4::ZERO );
769     shadowTask.SetExclusive( true );
770     shadowTask.SetRefreshRate( RenderTask::REFRESH_ONCE );
771     shadowTask.FinishedSignal().Connect( this, &AtlasRenderer::Impl::RenderComplete );
772     mShadowTasks.push_back( shadowTask );
773     actor.Add( subActor );
774
775     return actor;
776   }
777
778   void RemoveShadowRenderTask( RenderTask renderTask )
779   {
780     if( renderTask )
781     {
782       renderTask.FinishedSignal().Disconnect( this, &AtlasRenderer::Impl::RenderComplete );
783
784       // Guard to prevent accessing Stage after dali-core destruction
785       if( Stage::IsInstalled() )
786       {
787         Stage::GetCurrent().GetRenderTaskList().RemoveTask( renderTask );
788       }
789       renderTask.Reset();
790     }
791   }
792
793   void RenderComplete( RenderTask& renderTask )
794   {
795     // Get the actor used for render to buffer and remove it from the parent
796     Actor renderActor = renderTask.GetSourceActor();
797     if ( renderActor )
798     {
799       Actor parent = renderActor.GetParent();
800       if ( parent )
801       {
802         parent.Remove( renderActor );
803       }
804     }
805
806     RemoveShadowRenderTask( renderTask );
807   }
808
809   void RemoveAllShadowRenderTasks()
810   {
811     for ( std::vector< RenderTask >::iterator shadowIterator = mShadowTasks.begin();
812           shadowIterator != mShadowTasks.end(); ++shadowIterator )
813     {
814       RemoveShadowRenderTask( *shadowIterator );
815     }
816   }
817
818   Actor mActor;                                       ///< The actor parent which renders the text
819   AtlasGlyphManager mGlyphManager;                    ///< Glyph Manager to handle upload and caching
820   std::vector< RenderTask > mShadowTasks;             ///< Used to render shadows
821   TextAbstraction::FontClient mFontClient;            ///> The font client used to supply glyph information
822   std::vector< MaxBlockSize > mBlockSizes;            ///> Maximum size needed to contain a glyph in a block within a new atlas
823   std::vector< uint32_t > mFace;                      ///> Face indices for a quad
824   Vector< TextCacheEntry > mTextCache;
825   Property::Map mQuadVertexFormat;
826   Property::Map mQuadIndexFormat;
827   int mDepth;
828 };
829
830 Text::RendererPtr AtlasRenderer::New()
831 {
832   DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
833
834   return Text::RendererPtr( new AtlasRenderer() );
835 }
836
837 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
838 {
839   UnparentAndReset( mImpl->mActor );
840
841   Length numberOfGlyphs = view.GetNumberOfGlyphs();
842
843   if( numberOfGlyphs > 0u )
844   {
845     Vector<GlyphInfo> glyphs;
846     glyphs.Resize( numberOfGlyphs );
847
848     Vector<Vector2> positions;
849     positions.Resize( numberOfGlyphs );
850
851     numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
852                                      positions.Begin(),
853                                      0u,
854                                      numberOfGlyphs );
855     glyphs.Resize( numberOfGlyphs );
856     positions.Resize( numberOfGlyphs );
857
858     mImpl->AddGlyphs( view,
859                       positions,
860                       glyphs,
861                       depth );
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->RemoveAllShadowRenderTasks();
876
877   mImpl->RemoveText();
878   delete mImpl;
879 }