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