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