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