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