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