NPatch rendering optimization
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / npatch / npatch-visual.cpp
old mode 100755 (executable)
new mode 100644 (file)
index 971c73d..b954c8c
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2018 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2020 Samsung Electronics Co., Ltd.
  *
  * Licensed under the Apache License, Version 2.0 (the "License");
  * you may not use this file except in compliance with the License.
 #include "npatch-visual.h"
 
 // EXTERNAL INCLUDES
-#include <dali/public-api/images/buffer-image.h>
-#include <dali/public-api/images/resource-image.h>
-#include <dali/devel-api/object/handle-devel.h>
-#include <dali/devel-api/images/texture-set-image.h>
+#include <dali/devel-api/rendering/renderer-devel.h>
 #include <dali/devel-api/adaptor-framework/image-loading.h>
 #include <dali/integration-api/debug.h>
 
@@ -36,6 +33,7 @@
 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
+#include <dali-toolkit/internal/visuals/rendering-addon.h>
 
 namespace Dali
 {
@@ -48,16 +46,11 @@ namespace Internal
 
 namespace
 {
-const char * const BORDER_ONLY( "borderOnly" );
-const char * const BORDER( "border" );
-const char * const AUXILIARY_IMAGE_NAME( "auxiliaryImage" );
-const char * const AUXILIARY_IMAGE_ALPHA_NAME( "auxiliaryImageAlpha" );
-
 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
   attribute mediump vec2 aPosition;\n
   varying mediump vec2 vTexCoord;\n
   varying mediump vec2 vMaskTexCoord;\n
-  uniform mediump mat4 uMvpMatrix;\n
+  uniform highp   mat4 uMvpMatrix;\n
   uniform mediump vec3 uSize;\n
   uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
   uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
@@ -69,6 +62,7 @@ const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
   uniform mediump vec4 offsetSizeMode;\n
   uniform mediump vec2 origin;\n
   uniform mediump vec2 anchorPoint;\n
+  uniform mediump vec2 extraSize;\n
 
   void main()\n
   {\n
@@ -78,7 +72,7 @@ const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
     mediump vec2 fixedTotal   = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
     mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
     \n
-    vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
+    vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
     \n
     mediump vec4 gridPosition = vec4( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal, 0.0, 1.0 );\n
@@ -98,8 +92,7 @@ const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
     attribute mediump vec2 aPosition;\n
     varying mediump vec2 vTexCoord;\n
     varying mediump vec2 vMaskTexCoord;\n
-    uniform mediump mat4 uModelMatrix;\n
-    uniform mediump mat4 uMvpMatrix;\n
+    uniform highp   mat4 uMvpMatrix;\n
     uniform mediump vec3 uSize;\n
     uniform mediump vec2 uFixed[ 3 ];\n
     uniform mediump vec2 uStretchTotal;\n
@@ -110,10 +103,11 @@ const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
     uniform mediump vec4 offsetSizeMode;\n
     uniform mediump vec2 origin;\n
     uniform mediump vec2 anchorPoint;\n
+    uniform mediump vec2 extraSize;\n
     \n
     void main()\n
     {\n
-      vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
+      vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
       vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
       \n
       mediump vec2 size         = visualSize.xy;\n
@@ -186,15 +180,15 @@ Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsi
 {
   Property::Map vertexFormat;
   vertexFormat[ "aPosition" ] = Property::VECTOR2;
-  PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
+  VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
   if( vertices.Size() > 0 )
   {
-    vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
+    vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
   }
 
   // Create the geometry object
   Geometry geometry = Geometry::New();
-  geometry.AddVertexBuffer( vertexPropertyBuffer );
+  geometry.AddVertexBuffer( vertexBuffer );
   if( indices.Size() > 0 )
   {
     geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
@@ -227,13 +221,13 @@ void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
   vertices.PushBack( Vector2( x, y ) );
 }
 
-void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
+void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent)
 {
   uint16_t prevEnd = 0;
   uint16_t prevFix = 0;
   uint16_t prevStretch = 0;
   unsigned int i = 1;
-  for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
+  for( NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
   {
     uint16_t start = it->GetX();
     uint16_t end = it->GetY();
@@ -279,26 +273,30 @@ NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const Visua
   return nPatchVisual;
 }
 
-NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, NinePatchImage image )
-{
-  NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
-  VisualUrl visualUrl( image.GetUrl() );
-  nPatchVisual->mImageUrl = visualUrl;
-  return nPatchVisual;
-}
-
 void NPatchVisual::LoadImages()
 {
+  TextureManager& textureManager = mFactoryCache.GetTextureManager();
+  bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
+
   if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocalResource() )
   {
-    mId = mLoader.Load( mImageUrl.GetUrl(), mBorder );
+    bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
+    mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
+
+    const NPatchLoader::Data* data;
+    if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
+    {
+      EnablePreMultipliedAlpha( preMultiplyOnLoad );
+    }
   }
 
-  if( ! mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
+  if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
   {
-    // Load the auxiliary image synchronously
-    mAuxiliaryPixelBuffer = Dali::LoadImageFromFile( mAuxiliaryUrl.GetUrl(), ImageDimensions(),
-                                                     FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, true );
+    // Load the auxiliary image
+    auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
+    mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
+                                                            SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
+                                                            this, true, preMultiplyOnLoading );
   }
 }
 
@@ -308,14 +306,24 @@ void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
   naturalSize.y = 0u;
 
   // load now if not already loaded
-  LoadImages();
-
   const NPatchLoader::Data* data;
-  if( mLoader.GetNPatchData( mId, data ) )
+  if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
   {
     naturalSize.x = data->croppedWidth;
     naturalSize.y = data->croppedHeight;
   }
+  else
+  {
+    if( mImageUrl.IsValid() )
+    {
+      ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
+      if( dimensions != ImageDimensions( 0, 0 ) )
+      {
+        naturalSize.x = dimensions.GetWidth();
+        naturalSize.y = dimensions.GetHeight();
+      }
+    }
+  }
 
   if( mAuxiliaryPixelBuffer )
   {
@@ -363,29 +371,59 @@ void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
   {
     auxImageAlpha->Get( mAuxiliaryImageAlpha );
   }
+
+  Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
+  if( synchronousLoading )
+  {
+    bool sync = false;
+    synchronousLoading->Get( sync );
+    if( sync )
+    {
+      mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
+    }
+    else
+    {
+      mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
+    }
+  }
 }
 
-void NPatchVisual::DoSetOnStage( Actor& actor )
+void NPatchVisual::DoSetOnScene( Actor& actor )
 {
   // load when first go on stage
   LoadImages();
 
-  Geometry geometry = CreateGeometry();
-  Shader shader = CreateShader();
-  mImpl->mRenderer = Renderer::New( geometry, shader );
+  const NPatchLoader::Data* data;
+  if( mLoader.GetNPatchData( mId, data ) )
+  {
+    Geometry geometry = CreateGeometry();
+    Shader shader = CreateShader();
+
+    mImpl->mRenderer = Renderer::New( geometry, shader );
 
-  ApplyTextureAndUniforms();
+    mPlacementActor = actor;
+    if( data->loadCompleted )
+    {
+      if( RenderingAddOn::Get().IsValid() )
+      {
+        RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->renderingMap );
+      }
 
-  actor.AddRenderer( mImpl->mRenderer );
+      ApplyTextureAndUniforms();
+      actor.AddRenderer( mImpl->mRenderer );
+      mPlacementActor.Reset();
 
-  // npatch loaded and ready to display
-  ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+      // npatch loaded and ready to display
+      ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+    }
+  }
 }
 
-void NPatchVisual::DoSetOffStage( Actor& actor )
+void NPatchVisual::DoSetOffScene( Actor& actor )
 {
   actor.RemoveRenderer( mImpl->mRenderer );
   mImpl->mRenderer.Reset();
+  mPlacementActor.Reset();
 }
 
 void NPatchVisual::OnSetTransform()
@@ -399,6 +437,8 @@ void NPatchVisual::OnSetTransform()
 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
 {
   map.Clear();
+  bool sync = IsSynchronousLoadingRequired();
+  map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
   map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
   map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
@@ -421,7 +461,8 @@ void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
 }
 
 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
-: Visual::Base( factoryCache, Visual::FittingMode::FILL ),
+: Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH ),
+  mPlacementActor(),
   mLoader( factoryCache.GetNPatchLoader() ),
   mImageUrl(),
   mAuxiliaryUrl(),
@@ -430,6 +471,7 @@ NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
   mBorder(),
   mAuxiliaryImageAlpha( 0.0f )
 {
+  EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
 }
 
 NPatchVisual::~NPatchVisual()
@@ -440,7 +482,7 @@ Geometry NPatchVisual::CreateGeometry()
 {
   Geometry geometry;
   const NPatchLoader::Data* data;
-  if( mLoader.GetNPatchData( mId, data ) )
+  if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
   {
     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
     {
@@ -450,13 +492,38 @@ Geometry NPatchVisual::CreateGeometry()
       }
       else
       {
-        geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
+        if( data->renderingMap )
+        {
+          uint32_t elementCount[2];
+          geometry = RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, Uint16Pair(3, 3), elementCount );
+          if( mImpl->mRenderer )
+          {
+            RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->renderingMap);
+          }
+        }
+        else
+        {
+          geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
+        }
       }
     }
     else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
     {
       Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1,  2 * data->stretchPixelsY.Size() + 1 );
-      geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
+      if( !data->renderingMap )
+      {
+        geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
+      }
+      else
+      {
+        uint32_t elementCount[2];
+        geometry = !mBorderOnly ?
+                   RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, gridSize, elementCount ) : CreateBorderGeometry(gridSize );
+        if( mImpl->mRenderer )
+        {
+          RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->renderingMap);
+        }
+      }
     }
   }
   else
@@ -473,8 +540,8 @@ Shader NPatchVisual::CreateShader()
   const NPatchLoader::Data* data;
   // 0 is either no data (load failed?) or no stretch regions on image
   // for both cases we use the default shader
-  NinePatchImage::StretchRanges::SizeType xStretchCount = 0;
-  NinePatchImage::StretchRanges::SizeType yStretchCount = 0;
+  NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
+  NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
 
   auto fragmentShader = mAuxiliaryPixelBuffer ? FRAGMENT_MASK_SHADER
                                               : FRAGMENT_SHADER;
@@ -552,7 +619,7 @@ void NPatchVisual::ApplyTextureAndUniforms()
   const NPatchLoader::Data* data;
   TextureSet textureSet;
 
-  if( mLoader.GetNPatchData( mId, data ) )
+  if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
   {
     textureSet = data->textureSet;
 
@@ -584,8 +651,8 @@ void NPatchVisual::ApplyTextureAndUniforms()
     DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
     textureSet = TextureSet::New();
 
-    Image croppedImage = VisualFactoryCache::GetBrokenVisualImage();
-    TextureSetImage( textureSet, 0u, croppedImage );
+    Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
+    textureSet.SetTexture( 0u, croppedImage );
     mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
     mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
     mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
@@ -611,8 +678,8 @@ void NPatchVisual::ApplyTextureAndUniforms()
                                  auxiliaryPixelData.GetHeight() );
     texture.Upload( auxiliaryPixelData );
     textureSet.SetTexture( 1, texture );
-    DevelHandle::RegisterProperty( mImpl->mRenderer, DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
-                                   AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
+    mImpl->mRenderer.RegisterProperty( DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
+                                       AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
   }
   mImpl->mRenderer.SetTextures( textureSet );
 
@@ -769,6 +836,56 @@ Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
   return GenerateGeometry( vertices, indices );
 }
 
+void NPatchVisual::SetResource()
+{
+  const NPatchLoader::Data* data;
+  if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
+  {
+    Geometry geometry = CreateGeometry();
+    Shader shader = CreateShader();
+
+    mImpl->mRenderer.SetGeometry( geometry );
+    mImpl->mRenderer.SetShader( shader );
+
+    Actor actor = mPlacementActor.GetHandle();
+    if( actor )
+    {
+      ApplyTextureAndUniforms();
+      actor.AddRenderer( mImpl->mRenderer );
+      mPlacementActor.Reset();
+
+      // npatch loaded and ready to display
+      ResourceReady( Toolkit::Visual::ResourceStatus::READY );
+    }
+  }
+}
+
+void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
+{
+  if( url.GetUrl() == mAuxiliaryUrl.GetUrl() )
+  {
+    mAuxiliaryPixelBuffer = pixelBuffer;
+    const NPatchLoader::Data* data;
+    if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
+    {
+      SetResource();
+    }
+  }
+  else
+  {
+    if( loadSuccess )
+    {
+      mLoader.SetNPatchData( mId, pixelBuffer );
+      EnablePreMultipliedAlpha( preMultiplied );
+    }
+
+    if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
+    {
+      SetResource();
+    }
+  }
+}
+
 } // namespace Internal
 
 } // namespace Toolkit