2 * Copyright (c) 2015 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-toolkit/internal/text/rendering/atlas/text-atlas-renderer.h>
22 #include <dali/integration-api/debug.h>
23 #include <dali/devel-api/rendering/renderer.h>
24 #include <dali/devel-api/rendering/geometry.h>
25 #include <dali/devel-api/text-abstraction/font-client.h>
28 #include <dali-toolkit/public-api/controls/control-depth-index-ranges.h>
29 #include <dali-toolkit/internal/text/glyph-run.h>
30 #include <dali-toolkit/internal/text/rendering/atlas/atlas-glyph-manager.h>
31 #include <dali-toolkit/internal/text/rendering/atlas/atlas-mesh-factory.h>
32 #include <dali-toolkit/internal/text/text-view.h>
35 using namespace Dali::Toolkit;
36 using namespace Dali::Toolkit::Text;
40 #if defined(DEBUG_ENABLED)
41 Debug::Filter* gLogFilter = Debug::Filter::New(Debug::Concise, true, "LOG_TEXT_RENDERING");
44 const float ZERO( 0.0f );
45 const float HALF( 0.5f );
46 const float ONE( 1.0f );
47 const uint32_t DEFAULT_ATLAS_WIDTH = 512u;
48 const uint32_t DEFAULT_ATLAS_HEIGHT = 512u;
51 struct AtlasRenderer::Impl
62 : mColor( Color::BLACK ),
69 AtlasManager::Mesh2D mMesh;
70 FrameBufferImage mBuffer;
74 * brief Struct used to generate the underline mesh.
75 * There is one Extent per line of text.
83 mUnderlinePosition( 0.0f ),
84 mUnderlineThickness( 0.0f ),
92 float mUnderlinePosition;
93 float mUnderlineThickness;
94 uint32_t mMeshRecordIndex;
101 mNeededBlockWidth( 0 ),
102 mNeededBlockHeight( 0 )
107 uint32_t mNeededBlockWidth;
108 uint32_t mNeededBlockHeight;
120 Text::GlyphIndex mIndex;
123 struct TextCacheEntry
133 Text::GlyphIndex mIndex;
140 mGlyphManager = AtlasGlyphManager::Get();
141 mFontClient = TextAbstraction::FontClient::Get();
143 mQuadVertexFormat[ "aPosition" ] = Property::VECTOR2;
144 mQuadVertexFormat[ "aTexCoord" ] = Property::VECTOR2;
145 mQuadIndexFormat[ "indices" ] = Property::INTEGER;
148 bool IsGlyphUnderlined( GlyphIndex index,
149 const Vector<GlyphRun>& underlineRuns )
151 for( Vector<GlyphRun>::ConstIterator it = underlineRuns.Begin(),
152 endIt = underlineRuns.End();
156 const GlyphRun& run = *it;
158 if( ( run.glyphIndex <= index ) && ( index < run.glyphIndex + run.numberOfGlyphs ) )
167 void AddGlyphs( Text::ViewInterface& view,
168 const Vector<Vector2>& positions,
169 const Vector<GlyphInfo>& glyphs,
172 AtlasManager::AtlasSlot slot;
173 std::vector< MeshRecord > meshContainer;
174 Vector< Extent > extents;
175 TextCacheEntry textCacheEntry;
178 const Vector2& actorSize( view.GetControlSize() );
179 const Vector2 halfActorSize( actorSize * 0.5f );
180 const Vector4& textColor( view.GetTextColor() );
181 const Vector2& shadowOffset( view.GetShadowOffset() );
182 const Vector4& shadowColor( view.GetShadowColor() );
183 const bool underlineEnabled( view.IsUnderlineEnabled() );
184 const Vector4& underlineColor( view.GetUnderlineColor() );
185 const float underlineHeight( view.GetUnderlineHeight() );
187 // Get the underline runs.
188 const Length numberOfUnderlineRuns = view.GetNumberOfUnderlineRuns();
189 Vector<GlyphRun> underlineRuns;
190 underlineRuns.Resize( numberOfUnderlineRuns );
191 view.GetUnderlineRuns( underlineRuns.Begin(),
193 numberOfUnderlineRuns );
195 bool thereAreUnderlinedGlyphs = false;
197 float currentUnderlinePosition = ZERO;
198 float currentUnderlineThickness = underlineHeight;
199 uint32_t currentBlockSize = 0;
200 FontId lastFontId = 0;
201 FontId lastUnderlinedFontId = 0;
202 Style style = STYLE_NORMAL;
204 if ( fabsf( shadowOffset.x ) > Math::MACHINE_EPSILON_1 || fabsf( shadowOffset.y ) > Math::MACHINE_EPSILON_1 )
206 style = STYLE_DROP_SHADOW;
209 CalculateBlocksSize( glyphs );
211 // Avoid emptying mTextCache (& removing references) until after incremented references for the new text
212 Vector< TextCacheEntry > newTextCache;
213 const GlyphInfo* const glyphsBuffer = glyphs.Begin();
214 const Vector2* const positionsBuffer = positions.Begin();
216 for( uint32_t i = 0, glyphSize = glyphs.Size(); i < glyphSize; ++i )
218 const GlyphInfo& glyph = *( glyphsBuffer + i );
220 const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined( i, underlineRuns );
221 thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
223 // No operation for white space
224 if( glyph.width && glyph.height )
226 // Are we still using the same fontId as previous
227 if( underlineGlyph && ( glyph.fontId != lastUnderlinedFontId ) )
229 // We need to fetch fresh font underline metrics
230 FontMetrics fontMetrics;
231 mFontClient.GetFontMetrics( glyph.fontId, fontMetrics );
232 currentUnderlinePosition = ceil( fabsf( fontMetrics.underlinePosition ) );
233 const float descender = ceil( fabsf( fontMetrics.descender ) );
235 if( fabsf( underlineHeight ) < Math::MACHINE_EPSILON_1000 )
237 currentUnderlineThickness = fontMetrics.underlineThickness;
239 // Ensure underline will be at least a pixel high
240 if ( currentUnderlineThickness < ONE )
242 currentUnderlineThickness = ONE;
246 currentUnderlineThickness = ceil( currentUnderlineThickness );
250 // Clamp the underline position at the font descender and check for ( as EFL describes it ) a broken font
251 if( currentUnderlinePosition > descender )
253 currentUnderlinePosition = descender;
256 if( fabsf( currentUnderlinePosition ) < Math::MACHINE_EPSILON_1000 )
258 // Move offset down by one ( EFL behavior )
259 currentUnderlinePosition = ONE;
262 lastUnderlinedFontId = glyph.fontId;
265 if( !mGlyphManager.IsCached( glyph.fontId, glyph.index, slot ) )
267 // Select correct size for new atlas if needed....?
268 if( lastFontId != glyph.fontId )
271 for( std::vector<MaxBlockSize>::const_iterator it = mBlockSizes.begin(),
272 endIt = mBlockSizes.end();
276 const MaxBlockSize& blockSize = *it;
277 if( blockSize.mFontId == glyph.fontId )
279 currentBlockSize = index;
280 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
281 DEFAULT_ATLAS_HEIGHT,
282 blockSize.mNeededBlockWidth,
283 blockSize.mNeededBlockHeight );
288 // Create a new image for the glyph
289 BufferImage bitmap = mFontClient.CreateBitmap( glyph.fontId, glyph.index );
292 MaxBlockSize& blockSize = mBlockSizes[currentBlockSize];
294 // Ensure that the next image will fit into the current block size
295 bool setSize = false;
296 if( bitmap.GetWidth() > blockSize.mNeededBlockWidth )
299 blockSize.mNeededBlockWidth = bitmap.GetWidth();
301 if( bitmap.GetHeight() > blockSize.mNeededBlockHeight )
304 blockSize.mNeededBlockHeight = bitmap.GetHeight();
309 mGlyphManager.SetNewAtlasSize( DEFAULT_ATLAS_WIDTH,
310 DEFAULT_ATLAS_HEIGHT,
311 blockSize.mNeededBlockWidth,
312 blockSize.mNeededBlockHeight );
315 // Locate a new slot for our glyph
316 mGlyphManager.Add( glyph, bitmap, slot );
321 // We have 2+ copies of the same glyph
322 mGlyphManager.AdjustReferenceCount( glyph.fontId, glyph.index, 1/*increment*/ );
325 // Move the origin (0,0) of the mesh to the center of the actor
326 const Vector2 position = *( positionsBuffer + i ) - halfActorSize;
328 // Generate mesh data for this quad, plugging in our supplied position
329 AtlasManager::Mesh2D newMesh;
330 mGlyphManager.GenerateMeshData( slot.mImageId, position, newMesh );
331 textCacheEntry.mFontId = glyph.fontId;
332 textCacheEntry.mImageId = slot.mImageId;
333 textCacheEntry.mIndex = glyph.index;
334 newTextCache.PushBack( textCacheEntry );
336 AtlasManager::Vertex2D* verticesBuffer = newMesh.mVertices.Begin();
338 // Adjust the vertices if the fixed-size font should be down-scaled
339 if( glyph.scaleFactor > 0 )
341 for( unsigned int index = 0u, size = newMesh.mVertices.Count();
345 AtlasManager::Vertex2D& vertex = *( verticesBuffer + index );
347 // Set the position of the vertex.
348 vertex.mPosition.x = position.x + ( ( vertex.mPosition.x - position.x ) * glyph.scaleFactor );
349 vertex.mPosition.y = position.y + ( ( vertex.mPosition.y - position.y ) * glyph.scaleFactor );
353 // Find an existing mesh data object to attach to ( or create a new one, if we can't find one using the same atlas)
354 StitchTextMesh( meshContainer,
358 position.y + glyph.yBearing,
360 currentUnderlinePosition,
361 currentUnderlineThickness,
363 lastFontId = glyph.fontId;
367 // Now remove references for the old text
369 mTextCache.Swap( newTextCache );
371 if( thereAreUnderlinedGlyphs )
373 // Check to see if any of the text needs an underline
374 GenerateUnderlines( meshContainer, extents, underlineColor, textColor );
377 // For each MeshData object, create a mesh actor and add to the renderable actor
378 if( !meshContainer.empty() )
380 for( std::vector< MeshRecord >::iterator it = meshContainer.begin(),
381 endIt = meshContainer.end();
384 MeshRecord& meshRecord = *it;
386 Actor actor = CreateMeshActor( meshRecord, actorSize );
388 // Create an effect if necessary
389 if( style == STYLE_DROP_SHADOW )
391 // Create a container actor to act as a common parent for text and shadow, to avoid color inheritence issues.
392 Actor containerActor = Actor::New();
393 containerActor.SetParentOrigin( ParentOrigin::CENTER );
394 containerActor.SetSize( actorSize );
396 Actor shadowActor = Actor::New();
397 #if defined(DEBUG_ENABLED)
398 shadowActor.SetName( "Text Shadow renderable actor" );
400 // Offset shadow in x and y
401 shadowActor.RegisterProperty("uOffset", shadowOffset );
402 if( actor.GetRendererCount() )
404 Dali::Renderer renderer( actor.GetRendererAt( 0 ) );
405 Geometry geometry = renderer.GetGeometry();
406 Material material = renderer.GetMaterial();
408 Dali::Renderer shadowRenderer = Dali::Renderer::New( geometry, material );
409 shadowRenderer.SetDepthIndex( renderer.GetDepthIndex() - 1 );
410 shadowActor.AddRenderer( shadowRenderer );
411 shadowActor.SetParentOrigin( ParentOrigin::CENTER );
412 shadowActor.SetSize( actorSize );
413 shadowActor.SetColor( shadowColor );
414 containerActor.Add( shadowActor );
415 containerActor.Add( actor );
416 actor = containerActor;
430 #if defined(DEBUG_ENABLED)
431 Toolkit::AtlasGlyphManager::Metrics metrics = mGlyphManager.GetMetrics();
432 DALI_LOG_INFO( gLogFilter, Debug::General, "TextAtlasRenderer::GlyphManager::GlyphCount: %i, AtlasCount: %i, TextureMemoryUse: %iK\n",
434 metrics.mAtlasMetrics.mAtlasCount,
435 metrics.mAtlasMetrics.mTextureMemoryUsed / 1024 );
437 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "%s\n", metrics.mVerboseGlyphCounts.c_str() );
439 for( uint32_t i = 0; i < metrics.mAtlasMetrics.mAtlasCount; ++i )
441 DALI_LOG_INFO( gLogFilter, Debug::Verbose, " Atlas [%i] %sPixels: %s Size: %ix%i, BlockSize: %ix%i, BlocksUsed: %i/%i\n",
442 i + 1, i > 8 ? "" : " ",
443 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mPixelFormat == Pixel::L8 ? "L8 " : "BGRA",
444 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mWidth,
445 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mHeight,
446 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockWidth,
447 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mSize.mBlockHeight,
448 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mBlocksUsed,
449 metrics.mAtlasMetrics.mAtlasMetrics[ i ].mTotalBlocks );
456 for( Vector< TextCacheEntry >::Iterator oldTextIter = mTextCache.Begin(); oldTextIter != mTextCache.End(); ++oldTextIter )
458 mGlyphManager.AdjustReferenceCount( oldTextIter->mFontId, oldTextIter->mIndex, -1/*decrement*/ );
460 mTextCache.Resize( 0 );
463 Actor CreateMeshActor( const MeshRecord& meshRecord, const Vector2& actorSize )
465 PropertyBuffer quadVertices = PropertyBuffer::New( mQuadVertexFormat, meshRecord.mMesh.mVertices.Size() );
466 PropertyBuffer quadIndices = PropertyBuffer::New( mQuadIndexFormat, meshRecord.mMesh.mIndices.Size() );
467 quadVertices.SetData( const_cast< AtlasManager::Vertex2D* >( &meshRecord.mMesh.mVertices[ 0 ] ) );
468 quadIndices.SetData( const_cast< unsigned int* >( &meshRecord.mMesh.mIndices[ 0 ] ) );
470 Geometry quadGeometry = Geometry::New();
471 quadGeometry.AddVertexBuffer( quadVertices );
472 quadGeometry.SetIndexBuffer( quadIndices );
474 Material material = mGlyphManager.GetMaterial( meshRecord.mAtlasId );
475 Dali::Renderer renderer = Dali::Renderer::New( quadGeometry, material );
476 renderer.SetDepthIndex( CONTENT_DEPTH_INDEX + mDepth );
477 Actor actor = Actor::New();
478 #if defined(DEBUG_ENABLED)
479 actor.SetName( "Text renderable actor" );
481 actor.AddRenderer( renderer );
482 actor.SetParentOrigin( ParentOrigin::CENTER ); // Keep all of the origins aligned
483 actor.SetSize( actorSize );
484 actor.SetColor( meshRecord.mColor );
485 actor.RegisterProperty("uOffset", Vector2::ZERO );
489 void StitchTextMesh( std::vector< MeshRecord >& meshContainer,
490 AtlasManager::Mesh2D& newMesh,
491 Vector< Extent >& extents,
492 const Vector4& color,
495 float underlinePosition,
496 float underlineThickness,
497 AtlasManager::AtlasSlot& slot )
501 float left = newMesh.mVertices[ 0 ].mPosition.x;
502 float right = newMesh.mVertices[ 1 ].mPosition.x;
504 // Check to see if there's a mesh data object that references the same atlas ?
506 for ( std::vector< MeshRecord >::iterator mIt = meshContainer.begin(),
507 mEndIt = meshContainer.end();
511 if( slot.mAtlasId == mIt->mAtlasId && color == mIt->mColor )
513 // Append the mesh to the existing mesh and adjust any extents
514 Toolkit::Internal::AtlasMeshFactory::AppendMesh( mIt->mMesh, newMesh );
518 AdjustExtents( extents,
525 underlineThickness );
532 // No mesh data object currently exists that references this atlas, so create a new one
533 MeshRecord meshRecord;
534 meshRecord.mAtlasId = slot.mAtlasId;
535 meshRecord.mMesh = newMesh;
536 meshRecord.mColor = color;
537 meshContainer.push_back( meshRecord );
541 // Adjust extents for this new meshrecord
542 AdjustExtents( extents,
544 meshContainer.size() - 1u,
549 underlineThickness );
554 void AdjustExtents( Vector< Extent >& extents,
555 std::vector< MeshRecord>& meshRecords,
560 float underlinePosition,
561 float underlineThickness )
563 bool foundExtent = false;
564 for ( Vector< Extent >::Iterator eIt = extents.Begin(),
565 eEndIt = extents.End();
569 if ( Equals( baseLine, eIt->mBaseLine ) )
572 if ( left < eIt->mLeft )
576 if ( right > eIt->mRight )
581 if ( underlinePosition > eIt->mUnderlinePosition )
583 eIt->mUnderlinePosition = underlinePosition;
585 if ( underlineThickness > eIt->mUnderlineThickness )
587 eIt->mUnderlineThickness = underlineThickness;
595 extent.mRight = right;
596 extent.mBaseLine = baseLine;
597 extent.mUnderlinePosition = underlinePosition;
598 extent.mUnderlineThickness = underlineThickness;
599 extent.mMeshRecordIndex = index;
600 extents.PushBack( extent );
604 void CalculateBlocksSize( const Vector<GlyphInfo>& glyphs )
606 for( Vector<GlyphInfo>::ConstIterator glyphIt = glyphs.Begin(),
607 glyphEndIt = glyphs.End();
608 glyphIt != glyphEndIt;
611 const FontId fontId = (*glyphIt).fontId;
612 bool foundFont = false;
614 for( std::vector< MaxBlockSize >::const_iterator blockIt = mBlockSizes.begin(),
615 blockEndIt = mBlockSizes.end();
616 blockIt != blockEndIt;
619 if( (*blockIt).mFontId == fontId )
628 FontMetrics fontMetrics;
629 mFontClient.GetFontMetrics( fontId, fontMetrics );
631 MaxBlockSize maxBlockSize;
632 maxBlockSize.mNeededBlockWidth = static_cast< uint32_t >( fontMetrics.height );
633 maxBlockSize.mNeededBlockHeight = maxBlockSize.mNeededBlockWidth;
634 maxBlockSize.mFontId = fontId;
636 mBlockSizes.push_back( maxBlockSize );
641 void GenerateUnderlines( std::vector< MeshRecord >& meshRecords,
642 Vector< Extent >& extents,
643 const Vector4& underlineColor,
644 const Vector4& textColor )
646 AtlasManager::Mesh2D newMesh;
647 unsigned short faceIndex = 0;
648 for ( Vector< Extent >::ConstIterator eIt = extents.Begin(),
649 eEndIt = extents.End();
653 AtlasManager::Vertex2D vert;
654 uint32_t index = eIt->mMeshRecordIndex;
655 Vector2 uv = mGlyphManager.GetAtlasSize( meshRecords[ index ].mAtlasId );
657 // Make sure we don't hit texture edge for single pixel texture ( filled pixel is in top left of every atlas )
658 float u = HALF / uv.x;
659 float v = HALF / uv.y;
660 float thickness = eIt->mUnderlineThickness;
661 float baseLine = eIt->mBaseLine + eIt->mUnderlinePosition - ( thickness * HALF );
662 float tlx = eIt->mLeft;
663 float brx = eIt->mRight;
665 vert.mPosition.x = tlx;
666 vert.mPosition.y = baseLine;
667 vert.mTexCoords.x = ZERO;
668 vert.mTexCoords.y = ZERO;
669 newMesh.mVertices.PushBack( vert );
671 vert.mPosition.x = brx;
672 vert.mPosition.y = baseLine;
673 vert.mTexCoords.x = u;
674 newMesh.mVertices.PushBack( vert );
676 vert.mPosition.x = tlx;
677 vert.mPosition.y = baseLine + thickness;
678 vert.mTexCoords.x = ZERO;
679 vert.mTexCoords.y = v;
680 newMesh.mVertices.PushBack( vert );
682 vert.mPosition.x = brx;
683 vert.mPosition.y = baseLine + thickness;
684 vert.mTexCoords.x = u;
685 newMesh.mVertices.PushBack( vert );
687 // Six indices in counter clockwise winding
688 newMesh.mIndices.PushBack( faceIndex + 1u );
689 newMesh.mIndices.PushBack( faceIndex );
690 newMesh.mIndices.PushBack( faceIndex + 2u );
691 newMesh.mIndices.PushBack( faceIndex + 2u );
692 newMesh.mIndices.PushBack( faceIndex + 3u );
693 newMesh.mIndices.PushBack( faceIndex + 1u );
696 if( underlineColor == textColor )
698 Toolkit::Internal::AtlasMeshFactory::AppendMesh( meshRecords[ index ].mMesh, newMesh );
703 record.mMesh = newMesh;
704 record.mAtlasId = meshRecords[ index ].mAtlasId;
705 record.mColor = underlineColor;
706 meshRecords.push_back( record );
711 Actor mActor; ///< The actor parent which renders the text
712 AtlasGlyphManager mGlyphManager; ///< Glyph Manager to handle upload and caching
713 TextAbstraction::FontClient mFontClient; ///> The font client used to supply glyph information
714 std::vector< MaxBlockSize > mBlockSizes; ///> Maximum size needed to contain a glyph in a block within a new atlas
715 Vector< TextCacheEntry > mTextCache; ///> Caches data from previous render
716 Property::Map mQuadVertexFormat; ///> Describes the vertex format for text
717 Property::Map mQuadIndexFormat; ///> Describes the index format for text
718 int mDepth; ///> DepthIndex passed by control when connect to stage
721 Text::RendererPtr AtlasRenderer::New()
723 DALI_LOG_INFO( gLogFilter, Debug::Verbose, "Text::AtlasRenderer::New()\n" );
725 return Text::RendererPtr( new AtlasRenderer() );
728 Actor AtlasRenderer::Render( Text::ViewInterface& view, int depth )
730 UnparentAndReset( mImpl->mActor );
732 Length numberOfGlyphs = view.GetNumberOfGlyphs();
734 if( numberOfGlyphs > 0u )
736 Vector<GlyphInfo> glyphs;
737 glyphs.Resize( numberOfGlyphs );
739 Vector<Vector2> positions;
740 positions.Resize( numberOfGlyphs );
742 numberOfGlyphs = view.GetGlyphs( glyphs.Begin(),
746 glyphs.Resize( numberOfGlyphs );
747 positions.Resize( numberOfGlyphs );
749 mImpl->AddGlyphs( view,
754 /* In the case where AddGlyphs does not create a renderable Actor for example when glyphs are all whitespace create a new Actor. */
755 /* This renderable actor is used to position the text, other "decorations" can rely on there always being an Actor regardless of it is whitespace or regular text. */
756 if ( !mImpl->mActor )
758 mImpl->mActor = Actor::New();
762 return mImpl->mActor;
765 AtlasRenderer::AtlasRenderer()
771 AtlasRenderer::~AtlasRenderer()