Rendering optimisation with AddOn
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / npatch / npatch-visual.cpp
1 /*
2  * Copyright (c) 2020 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 "npatch-visual.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/object/handle-devel.h>
23 #include <dali/devel-api/rendering/renderer-devel.h>
24 #include <dali/devel-api/adaptor-framework/image-loading.h>
25 #include <dali/integration-api/debug.h>
26
27 // INTERNAL INCLUDES
28 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
29 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
30 #include <dali-toolkit/public-api/visuals/visual-properties.h>
31 #include <dali-toolkit/internal/visuals/npatch-loader.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
33 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
34 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
35 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
36 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
37 #include <dali-toolkit/internal/visuals/rendering-addon.h>
38
39 namespace Dali
40 {
41
42 namespace Toolkit
43 {
44
45 namespace Internal
46 {
47
48 namespace
49 {
50 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
51   attribute mediump vec2 aPosition;\n
52   varying mediump vec2 vTexCoord;\n
53   varying mediump vec2 vMaskTexCoord;\n
54   uniform highp   mat4 uMvpMatrix;\n
55   uniform mediump vec3 uSize;\n
56   uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
57   uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
58   \n
59
60   // Visual size and offset
61   uniform mediump vec2 offset;\n
62   uniform mediump vec2 size;\n
63   uniform mediump vec4 offsetSizeMode;\n
64   uniform mediump vec2 origin;\n
65   uniform mediump vec2 anchorPoint;\n
66   uniform mediump vec2 extraSize;\n
67
68   void main()\n
69   {\n
70     mediump vec2 fixedFactor  = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
71     mediump vec2 stretch      = vec2( uNinePatchFactorsX[ int( ( aPosition.x       ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y       ) * 0.5 ) ].y );\n
72     \n
73     mediump vec2 fixedTotal   = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
74     mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
75     \n
76     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
77     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
78     \n
79     mediump vec4 gridPosition = vec4( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal, 0.0, 1.0 );\n
80     mediump vec4 vertexPosition = gridPosition;\n
81     vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
82     vertexPosition.xy += anchorPoint*visualSize + (visualOffset + origin)*uSize.xy;\n
83     vertexPosition = uMvpMatrix * vertexPosition;\n
84     \n
85     vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
86     vMaskTexCoord = gridPosition.xy / visualSize;\n
87     \n
88     gl_Position = vertexPosition;\n
89   }\n
90 );
91
92 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
93     attribute mediump vec2 aPosition;\n
94     varying mediump vec2 vTexCoord;\n
95     varying mediump vec2 vMaskTexCoord;\n
96     uniform highp   mat4 uMvpMatrix;\n
97     uniform mediump vec3 uSize;\n
98     uniform mediump vec2 uFixed[ 3 ];\n
99     uniform mediump vec2 uStretchTotal;\n
100     \n
101     //Visual size and offset
102     uniform mediump vec2 offset;\n
103     uniform mediump vec2 size;\n
104     uniform mediump vec4 offsetSizeMode;\n
105     uniform mediump vec2 origin;\n
106     uniform mediump vec2 anchorPoint;\n
107     uniform mediump vec2 extraSize;\n
108     \n
109     void main()\n
110     {\n
111       vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
112       vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
113       \n
114       mediump vec2 size         = visualSize.xy;\n
115       \n
116       mediump vec2 fixedFactor  = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y  + 1.0 ) * 0.5 ) ].y );\n
117       mediump vec2 stretch      = floor( aPosition * 0.5 );\n
118       mediump vec2 fixedTotal   = uFixed[ 2 ];\n
119       \n
120       mediump vec4 gridPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
121       mediump vec4 vertexPosition = gridPosition;\n
122       vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
123       vertexPosition.xy += anchorPoint*size + (visualOffset + origin)*uSize.xy;\n
124       \n
125       vertexPosition = uMvpMatrix * vertexPosition;\n
126       \n
127       vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
128       \n
129       vMaskTexCoord = gridPosition.xy / size;\n
130       gl_Position = vertexPosition;\n
131     }\n
132 );
133
134 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
135   varying mediump vec2 vTexCoord;\n
136   uniform sampler2D sTexture;\n
137   uniform lowp vec4 uColor;\n
138   uniform lowp vec3 mixColor;\n
139   uniform lowp float preMultipliedAlpha;\n
140   \n
141   void main()\n
142   {\n
143     gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * vec4( mixColor, 1.0 );\n
144   }\n
145 );
146
147 const char* FRAGMENT_MASK_SHADER = DALI_COMPOSE_SHADER(
148   varying mediump vec2 vTexCoord;\n
149   varying mediump vec2 vMaskTexCoord;\n
150   uniform sampler2D sTexture;\n
151   uniform sampler2D sMask;\n
152   uniform lowp vec4 uColor;\n
153   uniform lowp vec3 mixColor;\n
154   uniform lowp float preMultipliedAlpha;\n
155   uniform mediump float auxiliaryImageAlpha;\n
156   \n
157   void main()\n
158   {\n
159       // Where mask image is transparent, all of background image must show through.
160       // where mask image is opaque, only mask should be shown
161       // where mask is translucent, less of background should be shown.
162       // auxiliaryImageAlpha controls how much of mask is visible
163
164       mediump vec4 color = texture2D( sTexture, vTexCoord );\n
165       mediump vec4 mask  = texture2D( sMask, vMaskTexCoord );\n
166
167       mediump vec3 mixedColor = color.rgb * mix( 1.0-mask.a, 1.0, 1.0-auxiliaryImageAlpha)
168                                 + mask.rgb*mask.a * auxiliaryImageAlpha;\n
169       gl_FragColor = vec4(mixedColor,1.0) * uColor * vec4( mixColor, 1.0 );\n
170   }\n
171 );
172
173 /**
174  * @brief Creates the geometry formed from the vertices and indices
175  *
176  * @param[in]  vertices             The vertices to generate the geometry from
177  * @param[in]  indices              The indices to generate the geometry from
178  * @return The geometry formed from the vertices and indices
179  */
180 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
181 {
182   Property::Map vertexFormat;
183   vertexFormat[ "aPosition" ] = Property::VECTOR2;
184   PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
185   if( vertices.Size() > 0 )
186   {
187     vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
188   }
189
190   // Create the geometry object
191   Geometry geometry = Geometry::New();
192   geometry.AddVertexBuffer( vertexPropertyBuffer );
193   if( indices.Size() > 0 )
194   {
195     geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
196   }
197
198
199   return geometry;
200 }
201
202 /**
203  * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
204  *
205  * @param[out] indices     The indices to add to
206  * @param[in]  rowIdx      The row index to start the quad
207  * @param[in]  nextRowIdx  The index to the next row
208  */
209 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
210 {
211   indices.PushBack( rowIdx );
212   indices.PushBack( nextRowIdx + 1 );
213   indices.PushBack( rowIdx + 1 );
214
215   indices.PushBack( rowIdx );
216   indices.PushBack( nextRowIdx );
217   indices.PushBack( nextRowIdx + 1 );
218 }
219
220 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
221 {
222   vertices.PushBack( Vector2( x, y ) );
223 }
224
225 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NPatchUtility::StretchRanges& stretchPixels, uint16_t imageExtent)
226 {
227   uint16_t prevEnd = 0;
228   uint16_t prevFix = 0;
229   uint16_t prevStretch = 0;
230   unsigned int i = 1;
231   for( NPatchUtility::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
232   {
233     uint16_t start = it->GetX();
234     uint16_t end = it->GetY();
235
236     uint16_t fix = prevFix + start - prevEnd;
237     uint16_t stretch = prevStretch + end - start;
238
239     std::stringstream uniform;
240     uniform << uniformName << "[" << i << "]";
241     renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
242
243     prevEnd = end;
244     prevFix = fix;
245     prevStretch = stretch;
246   }
247
248   {
249     prevFix += imageExtent - prevEnd;
250     std::stringstream uniform;
251     uniform << uniformName << "[" << i << "]";
252     renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
253   }
254 }
255
256 } //unnamed namespace
257
258 /////////////////NPatchVisual////////////////
259
260 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl, const Property::Map& properties )
261 {
262   NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
263   nPatchVisual->mImageUrl = imageUrl;
264   nPatchVisual->SetProperties( properties );
265
266   return nPatchVisual;
267 }
268
269 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl )
270 {
271   NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
272   nPatchVisual->mImageUrl = imageUrl;
273
274   return nPatchVisual;
275 }
276
277 void NPatchVisual::LoadImages()
278 {
279   TextureManager& textureManager = mFactoryCache.GetTextureManager();
280   bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
281
282   if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocalResource() )
283   {
284     bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
285     mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
286
287     const NPatchLoader::Data* data;
288     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
289     {
290       EnablePreMultipliedAlpha( preMultiplyOnLoad );
291     }
292   }
293
294   if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
295   {
296     // Load the auxiliary image
297     auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
298     mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
299                                                             SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
300                                                             this, true, preMultiplyOnLoading );
301   }
302 }
303
304 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
305 {
306   naturalSize.x = 0u;
307   naturalSize.y = 0u;
308
309   // load now if not already loaded
310   const NPatchLoader::Data* data;
311   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
312   {
313     naturalSize.x = data->croppedWidth;
314     naturalSize.y = data->croppedHeight;
315   }
316   else
317   {
318     if( mImageUrl.IsValid() )
319     {
320       ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
321       if( dimensions != ImageDimensions( 0, 0 ) )
322       {
323         naturalSize.x = dimensions.GetWidth();
324         naturalSize.y = dimensions.GetHeight();
325       }
326     }
327   }
328
329   if( mAuxiliaryPixelBuffer )
330   {
331     naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) );
332     naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) );
333   }
334 }
335
336 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
337 {
338   // URL is already passed in via constructor
339
340   Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
341   if( borderOnlyValue )
342   {
343     borderOnlyValue->Get( mBorderOnly );
344   }
345
346   Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER );
347   if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
348   {
349     // Not a rect so try vector4
350     Vector4 border;
351     if( borderValue->Get( border ) )
352     {
353       mBorder.left = static_cast< int >( border.x );
354       mBorder.right = static_cast< int >( border.y );
355       mBorder.bottom = static_cast< int >( border.z );
356       mBorder.top = static_cast< int >( border.w );
357     }
358   }
359
360   Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME );
361   if( auxImage )
362   {
363     std::string url;
364     if( auxImage->Get( url ) )
365     {
366       mAuxiliaryUrl = url;
367     }
368   }
369
370   Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME );
371   if( auxImageAlpha )
372   {
373     auxImageAlpha->Get( mAuxiliaryImageAlpha );
374   }
375
376   Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
377   if( synchronousLoading )
378   {
379     bool sync = false;
380     synchronousLoading->Get( sync );
381     if( sync )
382     {
383       mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
384     }
385     else
386     {
387       mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
388     }
389   }
390 }
391
392 void NPatchVisual::DoSetOnStage( Actor& actor )
393 {
394   // load when first go on stage
395   LoadImages();
396
397   const NPatchLoader::Data* data;
398   if( mLoader.GetNPatchData( mId, data ) )
399   {
400     Geometry geometry = CreateGeometry();
401     Shader shader = CreateShader();
402
403     mImpl->mRenderer = Renderer::New( geometry, shader );
404
405     mPlacementActor = actor;
406     if( data->loadCompleted )
407     {
408       if( RenderingAddOn::Get().IsValid() )
409       {
410         RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->renderingMap );
411       }
412
413       ApplyTextureAndUniforms();
414       actor.AddRenderer( mImpl->mRenderer );
415       mPlacementActor.Reset();
416
417       // npatch loaded and ready to display
418       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
419     }
420   }
421 }
422
423 void NPatchVisual::DoSetOffStage( Actor& actor )
424 {
425   actor.RemoveRenderer( mImpl->mRenderer );
426   mImpl->mRenderer.Reset();
427   mPlacementActor.Reset();
428 }
429
430 void NPatchVisual::OnSetTransform()
431 {
432   if( mImpl->mRenderer )
433   {
434     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
435   }
436 }
437
438 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
439 {
440   map.Clear();
441   bool sync = IsSynchronousLoadingRequired();
442   map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
443   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
444   map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
445   map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
446   map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder );
447
448   if( mAuxiliaryUrl.IsValid() )
449   {
450     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
451     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
452   }
453 }
454
455 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
456 {
457   if( mAuxiliaryUrl.IsValid() )
458   {
459     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
460     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
461   }
462 }
463
464 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
465 : Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH ),
466   mPlacementActor(),
467   mLoader( factoryCache.GetNPatchLoader() ),
468   mImageUrl(),
469   mAuxiliaryUrl(),
470   mId( NPatchLoader::UNINITIALIZED_ID ),
471   mBorderOnly( false ),
472   mBorder(),
473   mAuxiliaryImageAlpha( 0.0f )
474 {
475   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
476 }
477
478 NPatchVisual::~NPatchVisual()
479 {
480 }
481
482 Geometry NPatchVisual::CreateGeometry()
483 {
484   Geometry geometry;
485   const NPatchLoader::Data* data;
486   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
487   {
488     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
489     {
490       if( DALI_UNLIKELY( mBorderOnly ) )
491       {
492         geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
493       }
494       else
495       {
496         if( data->renderingMap )
497         {
498           uint32_t elementCount[2];
499           geometry = RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, Uint16Pair(3, 3), elementCount );
500         }
501         else
502         {
503           geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
504         }
505       }
506     }
507     else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
508     {
509       Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1,  2 * data->stretchPixelsY.Size() + 1 );
510       if( !data->renderingMap )
511       {
512         geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
513       }
514       else
515       {
516         uint32_t elementCount[2];
517         geometry = !mBorderOnly ?
518                    RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, gridSize, elementCount ) : CreateBorderGeometry(gridSize );
519       }
520     }
521   }
522   else
523   {
524     // no N patch data so use default geometry
525     geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
526   }
527   return geometry;
528 }
529
530 Shader NPatchVisual::CreateShader()
531 {
532   Shader shader;
533   const NPatchLoader::Data* data;
534   // 0 is either no data (load failed?) or no stretch regions on image
535   // for both cases we use the default shader
536   NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
537   NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
538
539   auto fragmentShader = mAuxiliaryPixelBuffer ? FRAGMENT_MASK_SHADER
540                                               : FRAGMENT_SHADER;
541   auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
542                                           : VisualFactoryCache::NINE_PATCH_SHADER;
543
544   // ask loader for the regions
545   if( mLoader.GetNPatchData( mId, data ) )
546   {
547     xStretchCount = data->stretchPixelsX.Count();
548     yStretchCount = data->stretchPixelsY.Count();
549   }
550
551   if( DALI_LIKELY( !mImpl->mCustomShader ) )
552   {
553     if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
554                      ( xStretchCount == 0 && yStretchCount == 0 ) ) )
555     {
556       shader = mFactoryCache.GetShader( shaderType );
557       if( DALI_UNLIKELY( !shader ) )
558       {
559         shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader );
560         // Only cache vanilla 9 patch shaders
561         mFactoryCache.SaveShader( shaderType, shader );
562       }
563     }
564     else if( xStretchCount > 0 || yStretchCount > 0)
565     {
566       std::stringstream vertexShader;
567       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
568                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
569                    << VERTEX_SHADER;
570
571       shader = Shader::New( vertexShader.str(), fragmentShader );
572     }
573   }
574   else
575   {
576     Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
577
578     if( !mImpl->mCustomShader->mFragmentShader.empty() )
579     {
580       fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
581     }
582     hints = mImpl->mCustomShader->mHints;
583
584     /* Apply Custom Vertex Shader only if image is 9-patch */
585     if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
586         ( xStretchCount == 0 && yStretchCount == 0 ) )
587     {
588       const char* vertexShader = VERTEX_SHADER_3X3;
589
590       if( !mImpl->mCustomShader->mVertexShader.empty() )
591       {
592         vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
593       }
594       shader = Shader::New( vertexShader, fragmentShader, hints );
595     }
596     else if( xStretchCount > 0 || yStretchCount > 0)
597     {
598       std::stringstream vertexShader;
599       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
600                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
601                    << VERTEX_SHADER;
602
603       shader = Shader::New( vertexShader.str(), fragmentShader, hints );
604     }
605   }
606
607   return shader;
608 }
609
610 void NPatchVisual::ApplyTextureAndUniforms()
611 {
612   const NPatchLoader::Data* data;
613   TextureSet textureSet;
614
615   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
616   {
617     textureSet = data->textureSet;
618
619     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
620     {
621       //special case for 9 patch
622       Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
623       Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
624
625       uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0;
626       uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0;
627
628       mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
629       mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
630       mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
631       mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
632     }
633     else
634     {
635       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
636       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
637
638       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
639       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
640     }
641   }
642   else
643   {
644     DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
645     textureSet = TextureSet::New();
646
647     Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
648     textureSet.SetTexture( 0u, croppedImage );
649     mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
650     mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
651     mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
652     mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
653   }
654
655   if( mAuxiliaryPixelBuffer )
656   {
657     // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
658     // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
659     // on GL interpolation alone.
660     if( mAuxiliaryPixelBuffer.GetWidth() < data->croppedWidth &&
661         mAuxiliaryPixelBuffer.GetHeight() < data->croppedHeight )
662     {
663       mAuxiliaryPixelBuffer.Resize( data->croppedWidth, data->croppedHeight );
664     }
665
666     // Note, this resets mAuxiliaryPixelBuffer handle
667     auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer );
668
669     auto texture = Texture::New( TextureType::TEXTURE_2D,
670                                  auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(),
671                                  auxiliaryPixelData.GetHeight() );
672     texture.Upload( auxiliaryPixelData );
673     textureSet.SetTexture( 1, texture );
674     DevelHandle::RegisterProperty( mImpl->mRenderer, DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
675                                    AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
676   }
677   mImpl->mRenderer.SetTextures( textureSet );
678
679   // Register transform properties
680   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
681 }
682
683 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
684 {
685   Geometry geometry = mFactoryCache.GetGeometry( subType );
686   if( !geometry )
687   {
688     if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
689     {
690       geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
691     }
692     else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
693     {
694       geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
695     }
696     mFactoryCache.SaveGeometry( subType, geometry );
697   }
698   return geometry;
699 }
700
701 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
702 {
703   uint16_t gridWidth = gridSize.GetWidth();
704   uint16_t gridHeight = gridSize.GetHeight();
705
706   // Create vertices
707   Vector< Vector2 > vertices;
708   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
709
710   for( int y = 0; y < gridHeight + 1; ++y )
711   {
712     for( int x = 0; x < gridWidth + 1; ++x )
713     {
714       AddVertex( vertices, x, y );
715     }
716   }
717
718   // Create indices
719   Vector< unsigned short > indices;
720   indices.Reserve( gridWidth * gridHeight * 6 );
721
722   unsigned int rowIdx     = 0;
723   unsigned int nextRowIdx = gridWidth + 1;
724   for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
725   {
726     for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
727     {
728       AddQuadIndices( indices, rowIdx, nextRowIdx );
729     }
730   }
731
732   return GenerateGeometry( vertices, indices );
733 }
734
735 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
736 {
737   uint16_t gridWidth = gridSize.GetWidth();
738   uint16_t gridHeight = gridSize.GetHeight();
739
740   // Create vertices
741   Vector< Vector2 > vertices;
742   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
743
744   //top
745   int y = 0;
746   for(; y < 2; ++y)
747   {
748     for( int x = 0; x < gridWidth + 1; ++x )
749     {
750       AddVertex( vertices, x, y );
751     }
752   }
753
754   for(; y < gridHeight - 1; ++y)
755   {
756     //left
757     AddVertex( vertices, 0, y );
758     AddVertex( vertices, 1, y );
759
760     //right
761     AddVertex( vertices, gridWidth - 1, y );
762     AddVertex( vertices, gridWidth, y );
763   }
764
765   //bottom
766   for(; y < gridHeight + 1; ++y)
767   {
768     for( int x = 0; x < gridWidth + 1; ++x )
769     {
770       AddVertex( vertices, x, y );
771     }
772   }
773
774   // Create indices
775   Vector< unsigned short > indices;
776   indices.Reserve( gridWidth * gridHeight * 6 );
777
778   //top
779   unsigned int rowIdx     = 0 ;
780   unsigned int nextRowIdx = gridWidth + 1;
781   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
782   {
783     AddQuadIndices( indices, rowIdx, nextRowIdx );
784   }
785
786   if(gridHeight > 2)
787   {
788     rowIdx     = gridWidth + 1;
789     nextRowIdx = ( gridWidth + 1 ) * 2;
790
791     unsigned increment = gridWidth - 1;
792     if(gridHeight > 3)
793     {
794       increment = 2;
795       //second row left
796       AddQuadIndices( indices, rowIdx, nextRowIdx );
797
798       rowIdx     = gridWidth * 2;
799       nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
800       //second row right
801       AddQuadIndices( indices, rowIdx, nextRowIdx );
802
803       //left and right
804       rowIdx     = nextRowIdx - 2;
805       nextRowIdx = rowIdx + 4;
806       for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
807       {
808         AddQuadIndices( indices, rowIdx, nextRowIdx );
809       }
810     }
811
812     //second row left
813     AddQuadIndices( indices, rowIdx, nextRowIdx );
814
815     rowIdx     += increment;
816     nextRowIdx += gridWidth - 1;
817     //second row right
818     AddQuadIndices( indices, rowIdx, nextRowIdx );
819   }
820
821   //bottom
822   rowIdx     = nextRowIdx - gridWidth + 1;
823   nextRowIdx = rowIdx + gridWidth + 1;
824   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
825   {
826     AddQuadIndices( indices, rowIdx, nextRowIdx );
827   }
828
829   return GenerateGeometry( vertices, indices );
830 }
831
832 void NPatchVisual::SetResource()
833 {
834   const NPatchLoader::Data* data;
835   if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
836   {
837     Geometry geometry = CreateGeometry();
838     Shader shader = CreateShader();
839
840     mImpl->mRenderer.SetGeometry( geometry );
841     mImpl->mRenderer.SetShader( shader );
842
843     Actor actor = mPlacementActor.GetHandle();
844     if( actor )
845     {
846       ApplyTextureAndUniforms();
847       actor.AddRenderer( mImpl->mRenderer );
848       mPlacementActor.Reset();
849
850       // npatch loaded and ready to display
851       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
852     }
853   }
854 }
855
856 void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
857 {
858   if( url.GetUrl() == mAuxiliaryUrl.GetUrl() )
859   {
860     mAuxiliaryPixelBuffer = pixelBuffer;
861     const NPatchLoader::Data* data;
862     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
863     {
864       SetResource();
865     }
866   }
867   else
868   {
869     if( loadSuccess )
870     {
871       mLoader.SetNPatchData( mId, pixelBuffer );
872       EnablePreMultipliedAlpha( preMultiplied );
873     }
874
875     if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
876     {
877       SetResource();
878     }
879   }
880 }
881
882 } // namespace Internal
883
884 } // namespace Toolkit
885
886 } // namespace Dali