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