NPatch rendering optimization
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / npatch / npatch-visual.cpp
1 /*
2  * Copyright (c) 2020 Samsung Electronics Co., Ltd.
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  *
16  */
17
18 // CLASS HEADER
19 #include "npatch-visual.h"
20
21 // EXTERNAL INCLUDES
22 #include <dali/devel-api/rendering/renderer-devel.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/integration-api/debug.h>
25
26 // INTERNAL INCLUDES
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
29 #include <dali-toolkit/public-api/visuals/visual-properties.h>
30 #include <dali-toolkit/internal/visuals/npatch-loader.h>
31 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
33 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
34 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
36 #include <dali-toolkit/internal/visuals/rendering-addon.h>
37
38 namespace Dali
39 {
40
41 namespace Toolkit
42 {
43
44 namespace Internal
45 {
46
47 namespace
48 {
49 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
50   attribute mediump vec2 aPosition;\n
51   varying mediump vec2 vTexCoord;\n
52   varying mediump vec2 vMaskTexCoord;\n
53   uniform highp   mat4 uMvpMatrix;\n
54   uniform mediump vec3 uSize;\n
55   uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
56   uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
57   \n
58
59   // Visual size and offset
60   uniform mediump vec2 offset;\n
61   uniform mediump vec2 size;\n
62   uniform mediump vec4 offsetSizeMode;\n
63   uniform mediump vec2 origin;\n
64   uniform mediump vec2 anchorPoint;\n
65   uniform mediump vec2 extraSize;\n
66
67   void main()\n
68   {\n
69     mediump vec2 fixedFactor  = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
70     mediump vec2 stretch      = vec2( uNinePatchFactorsX[ int( ( aPosition.x       ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y       ) * 0.5 ) ].y );\n
71     \n
72     mediump vec2 fixedTotal   = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
73     mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
74     \n
75     vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\n
76     vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
77     \n
78     mediump vec4 gridPosition = vec4( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal, 0.0, 1.0 );\n
79     mediump vec4 vertexPosition = gridPosition;\n
80     vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
81     vertexPosition.xy += anchorPoint*visualSize + (visualOffset + origin)*uSize.xy;\n
82     vertexPosition = uMvpMatrix * vertexPosition;\n
83     \n
84     vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
85     vMaskTexCoord = gridPosition.xy / visualSize;\n
86     \n
87     gl_Position = vertexPosition;\n
88   }\n
89 );
90
91 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
92     attribute mediump vec2 aPosition;\n
93     varying mediump vec2 vTexCoord;\n
94     varying mediump vec2 vMaskTexCoord;\n
95     uniform highp   mat4 uMvpMatrix;\n
96     uniform mediump vec3 uSize;\n
97     uniform mediump vec2 uFixed[ 3 ];\n
98     uniform mediump vec2 uStretchTotal;\n
99     \n
100     //Visual size and offset
101     uniform mediump vec2 offset;\n
102     uniform mediump vec2 size;\n
103     uniform mediump vec4 offsetSizeMode;\n
104     uniform mediump vec2 origin;\n
105     uniform mediump vec2 anchorPoint;\n
106     uniform mediump vec2 extraSize;\n
107     \n
108     void main()\n
109     {\n
110       vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw ) + extraSize;\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   VertexBuffer vertexBuffer = VertexBuffer::New( vertexFormat );
184   if( vertices.Size() > 0 )
185   {
186     vertexBuffer.SetData( &vertices[ 0 ], vertices.Size() );
187   }
188
189   // Create the geometry object
190   Geometry geometry = Geometry::New();
191   geometry.AddVertexBuffer( vertexBuffer );
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 NPatchUtility::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( NPatchUtility::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 void NPatchVisual::LoadImages()
277 {
278   TextureManager& textureManager = mFactoryCache.GetTextureManager();
279   bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
280
281   if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocalResource() )
282   {
283     bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
284     mId = mLoader.Load( textureManager, this, mImageUrl.GetUrl(), mBorder, preMultiplyOnLoad, synchronousLoading );
285
286     const NPatchLoader::Data* data;
287     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
288     {
289       EnablePreMultipliedAlpha( preMultiplyOnLoad );
290     }
291   }
292
293   if( !mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && mAuxiliaryUrl.IsLocalResource() )
294   {
295     // Load the auxiliary image
296     auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
297     mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer( mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT,
298                                                             SamplingMode::BOX_THEN_LINEAR, synchronousLoading,
299                                                             this, true, preMultiplyOnLoading );
300   }
301 }
302
303 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
304 {
305   naturalSize.x = 0u;
306   naturalSize.y = 0u;
307
308   // load now if not already loaded
309   const NPatchLoader::Data* data;
310   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
311   {
312     naturalSize.x = data->croppedWidth;
313     naturalSize.y = data->croppedHeight;
314   }
315   else
316   {
317     if( mImageUrl.IsValid() )
318     {
319       ImageDimensions dimensions = Dali::GetOriginalImageSize( mImageUrl.GetUrl() );
320       if( dimensions != ImageDimensions( 0, 0 ) )
321       {
322         naturalSize.x = dimensions.GetWidth();
323         naturalSize.y = dimensions.GetHeight();
324       }
325     }
326   }
327
328   if( mAuxiliaryPixelBuffer )
329   {
330     naturalSize.x = std::max( naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()) );
331     naturalSize.y = std::max( naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()) );
332   }
333 }
334
335 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
336 {
337   // URL is already passed in via constructor
338
339   Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
340   if( borderOnlyValue )
341   {
342     borderOnlyValue->Get( mBorderOnly );
343   }
344
345   Property::Value* borderValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER, BORDER );
346   if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
347   {
348     // Not a rect so try vector4
349     Vector4 border;
350     if( borderValue->Get( border ) )
351     {
352       mBorder.left = static_cast< int >( border.x );
353       mBorder.right = static_cast< int >( border.y );
354       mBorder.bottom = static_cast< int >( border.z );
355       mBorder.top = static_cast< int >( border.w );
356     }
357   }
358
359   Property::Value* auxImage = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME );
360   if( auxImage )
361   {
362     std::string url;
363     if( auxImage->Get( url ) )
364     {
365       mAuxiliaryUrl = url;
366     }
367   }
368
369   Property::Value* auxImageAlpha = propertyMap.Find( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME );
370   if( auxImageAlpha )
371   {
372     auxImageAlpha->Get( mAuxiliaryImageAlpha );
373   }
374
375   Property::Value* synchronousLoading = propertyMap.Find( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING );
376   if( synchronousLoading )
377   {
378     bool sync = false;
379     synchronousLoading->Get( sync );
380     if( sync )
381     {
382       mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
383     }
384     else
385     {
386       mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
387     }
388   }
389 }
390
391 void NPatchVisual::DoSetOnScene( Actor& actor )
392 {
393   // load when first go on stage
394   LoadImages();
395
396   const NPatchLoader::Data* data;
397   if( mLoader.GetNPatchData( mId, data ) )
398   {
399     Geometry geometry = CreateGeometry();
400     Shader shader = CreateShader();
401
402     mImpl->mRenderer = Renderer::New( geometry, shader );
403
404     mPlacementActor = actor;
405     if( data->loadCompleted )
406     {
407       if( RenderingAddOn::Get().IsValid() )
408       {
409         RenderingAddOn::Get().SubmitRenderTask( mImpl->mRenderer, data->renderingMap );
410       }
411
412       ApplyTextureAndUniforms();
413       actor.AddRenderer( mImpl->mRenderer );
414       mPlacementActor.Reset();
415
416       // npatch loaded and ready to display
417       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
418     }
419   }
420 }
421
422 void NPatchVisual::DoSetOffScene( Actor& actor )
423 {
424   actor.RemoveRenderer( mImpl->mRenderer );
425   mImpl->mRenderer.Reset();
426   mPlacementActor.Reset();
427 }
428
429 void NPatchVisual::OnSetTransform()
430 {
431   if( mImpl->mRenderer )
432   {
433     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
434   }
435 }
436
437 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
438 {
439   map.Clear();
440   bool sync = IsSynchronousLoadingRequired();
441   map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync );
442   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH );
443   map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
444   map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
445   map.Insert( Toolkit::ImageVisual::Property::BORDER, mBorder );
446
447   if( mAuxiliaryUrl.IsValid() )
448   {
449     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
450     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
451   }
452 }
453
454 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
455 {
456   if( mAuxiliaryUrl.IsValid() )
457   {
458     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl() );
459     map.Insert( Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha );
460   }
461 }
462
463 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
464 : Visual::Base( factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH ),
465   mPlacementActor(),
466   mLoader( factoryCache.GetNPatchLoader() ),
467   mImageUrl(),
468   mAuxiliaryUrl(),
469   mId( NPatchLoader::UNINITIALIZED_ID ),
470   mBorderOnly( false ),
471   mBorder(),
472   mAuxiliaryImageAlpha( 0.0f )
473 {
474   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
475 }
476
477 NPatchVisual::~NPatchVisual()
478 {
479 }
480
481 Geometry NPatchVisual::CreateGeometry()
482 {
483   Geometry geometry;
484   const NPatchLoader::Data* data;
485   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
486   {
487     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
488     {
489       if( DALI_UNLIKELY( mBorderOnly ) )
490       {
491         geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
492       }
493       else
494       {
495         if( data->renderingMap )
496         {
497           uint32_t elementCount[2];
498           geometry = RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, Uint16Pair(3, 3), elementCount );
499           if( mImpl->mRenderer )
500           {
501             RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->renderingMap);
502           }
503         }
504         else
505         {
506           geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
507         }
508       }
509     }
510     else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
511     {
512       Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1,  2 * data->stretchPixelsY.Size() + 1 );
513       if( !data->renderingMap )
514       {
515         geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
516       }
517       else
518       {
519         uint32_t elementCount[2];
520         geometry = !mBorderOnly ?
521                    RenderingAddOn::Get().CreateGeometryGrid(data->renderingMap, gridSize, elementCount ) : CreateBorderGeometry(gridSize );
522         if( mImpl->mRenderer )
523         {
524           RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->renderingMap);
525         }
526       }
527     }
528   }
529   else
530   {
531     // no N patch data so use default geometry
532     geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
533   }
534   return geometry;
535 }
536
537 Shader NPatchVisual::CreateShader()
538 {
539   Shader shader;
540   const NPatchLoader::Data* data;
541   // 0 is either no data (load failed?) or no stretch regions on image
542   // for both cases we use the default shader
543   NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
544   NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
545
546   auto fragmentShader = mAuxiliaryPixelBuffer ? FRAGMENT_MASK_SHADER
547                                               : FRAGMENT_SHADER;
548   auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
549                                           : VisualFactoryCache::NINE_PATCH_SHADER;
550
551   // ask loader for the regions
552   if( mLoader.GetNPatchData( mId, data ) )
553   {
554     xStretchCount = data->stretchPixelsX.Count();
555     yStretchCount = data->stretchPixelsY.Count();
556   }
557
558   if( DALI_LIKELY( !mImpl->mCustomShader ) )
559   {
560     if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
561                      ( xStretchCount == 0 && yStretchCount == 0 ) ) )
562     {
563       shader = mFactoryCache.GetShader( shaderType );
564       if( DALI_UNLIKELY( !shader ) )
565       {
566         shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader );
567         // Only cache vanilla 9 patch shaders
568         mFactoryCache.SaveShader( shaderType, shader );
569       }
570     }
571     else if( xStretchCount > 0 || yStretchCount > 0)
572     {
573       std::stringstream vertexShader;
574       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
575                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
576                    << VERTEX_SHADER;
577
578       shader = Shader::New( vertexShader.str(), fragmentShader );
579     }
580   }
581   else
582   {
583     Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
584
585     if( !mImpl->mCustomShader->mFragmentShader.empty() )
586     {
587       fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
588     }
589     hints = mImpl->mCustomShader->mHints;
590
591     /* Apply Custom Vertex Shader only if image is 9-patch */
592     if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
593         ( xStretchCount == 0 && yStretchCount == 0 ) )
594     {
595       const char* vertexShader = VERTEX_SHADER_3X3;
596
597       if( !mImpl->mCustomShader->mVertexShader.empty() )
598       {
599         vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
600       }
601       shader = Shader::New( vertexShader, fragmentShader, hints );
602     }
603     else if( xStretchCount > 0 || yStretchCount > 0)
604     {
605       std::stringstream vertexShader;
606       vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
607                    << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
608                    << VERTEX_SHADER;
609
610       shader = Shader::New( vertexShader.str(), fragmentShader, hints );
611     }
612   }
613
614   return shader;
615 }
616
617 void NPatchVisual::ApplyTextureAndUniforms()
618 {
619   const NPatchLoader::Data* data;
620   TextureSet textureSet;
621
622   if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
623   {
624     textureSet = data->textureSet;
625
626     if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
627     {
628       //special case for 9 patch
629       Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
630       Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
631
632       uint16_t stretchWidth = ( stretchX.GetY() >= stretchX.GetX() ) ? stretchX.GetY() - stretchX.GetX() : 0;
633       uint16_t stretchHeight = ( stretchY.GetY() >= stretchY.GetX() ) ? stretchY.GetY() - stretchY.GetX() : 0;
634
635       mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
636       mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
637       mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
638       mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
639     }
640     else
641     {
642       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
643       mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
644
645       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
646       RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
647     }
648   }
649   else
650   {
651     DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
652     textureSet = TextureSet::New();
653
654     Texture croppedImage = mFactoryCache.GetBrokenVisualImage();
655     textureSet.SetTexture( 0u, croppedImage );
656     mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
657     mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
658     mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
659     mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
660   }
661
662   if( mAuxiliaryPixelBuffer )
663   {
664     // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
665     // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
666     // on GL interpolation alone.
667     if( mAuxiliaryPixelBuffer.GetWidth() < data->croppedWidth &&
668         mAuxiliaryPixelBuffer.GetHeight() < data->croppedHeight )
669     {
670       mAuxiliaryPixelBuffer.Resize( data->croppedWidth, data->croppedHeight );
671     }
672
673     // Note, this resets mAuxiliaryPixelBuffer handle
674     auto auxiliaryPixelData = Devel::PixelBuffer::Convert( mAuxiliaryPixelBuffer );
675
676     auto texture = Texture::New( TextureType::TEXTURE_2D,
677                                  auxiliaryPixelData.GetPixelFormat(), auxiliaryPixelData.GetWidth(),
678                                  auxiliaryPixelData.GetHeight() );
679     texture.Upload( auxiliaryPixelData );
680     textureSet.SetTexture( 1, texture );
681     mImpl->mRenderer.RegisterProperty( DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
682                                        AUXILIARY_IMAGE_ALPHA_NAME, mAuxiliaryImageAlpha );
683   }
684   mImpl->mRenderer.SetTextures( textureSet );
685
686   // Register transform properties
687   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
688 }
689
690 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
691 {
692   Geometry geometry = mFactoryCache.GetGeometry( subType );
693   if( !geometry )
694   {
695     if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
696     {
697       geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
698     }
699     else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
700     {
701       geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
702     }
703     mFactoryCache.SaveGeometry( subType, geometry );
704   }
705   return geometry;
706 }
707
708 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
709 {
710   uint16_t gridWidth = gridSize.GetWidth();
711   uint16_t gridHeight = gridSize.GetHeight();
712
713   // Create vertices
714   Vector< Vector2 > vertices;
715   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
716
717   for( int y = 0; y < gridHeight + 1; ++y )
718   {
719     for( int x = 0; x < gridWidth + 1; ++x )
720     {
721       AddVertex( vertices, x, y );
722     }
723   }
724
725   // Create indices
726   Vector< unsigned short > indices;
727   indices.Reserve( gridWidth * gridHeight * 6 );
728
729   unsigned int rowIdx     = 0;
730   unsigned int nextRowIdx = gridWidth + 1;
731   for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
732   {
733     for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
734     {
735       AddQuadIndices( indices, rowIdx, nextRowIdx );
736     }
737   }
738
739   return GenerateGeometry( vertices, indices );
740 }
741
742 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
743 {
744   uint16_t gridWidth = gridSize.GetWidth();
745   uint16_t gridHeight = gridSize.GetHeight();
746
747   // Create vertices
748   Vector< Vector2 > vertices;
749   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
750
751   //top
752   int y = 0;
753   for(; y < 2; ++y)
754   {
755     for( int x = 0; x < gridWidth + 1; ++x )
756     {
757       AddVertex( vertices, x, y );
758     }
759   }
760
761   for(; y < gridHeight - 1; ++y)
762   {
763     //left
764     AddVertex( vertices, 0, y );
765     AddVertex( vertices, 1, y );
766
767     //right
768     AddVertex( vertices, gridWidth - 1, y );
769     AddVertex( vertices, gridWidth, y );
770   }
771
772   //bottom
773   for(; y < gridHeight + 1; ++y)
774   {
775     for( int x = 0; x < gridWidth + 1; ++x )
776     {
777       AddVertex( vertices, x, y );
778     }
779   }
780
781   // Create indices
782   Vector< unsigned short > indices;
783   indices.Reserve( gridWidth * gridHeight * 6 );
784
785   //top
786   unsigned int rowIdx     = 0 ;
787   unsigned int nextRowIdx = gridWidth + 1;
788   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
789   {
790     AddQuadIndices( indices, rowIdx, nextRowIdx );
791   }
792
793   if(gridHeight > 2)
794   {
795     rowIdx     = gridWidth + 1;
796     nextRowIdx = ( gridWidth + 1 ) * 2;
797
798     unsigned increment = gridWidth - 1;
799     if(gridHeight > 3)
800     {
801       increment = 2;
802       //second row left
803       AddQuadIndices( indices, rowIdx, nextRowIdx );
804
805       rowIdx     = gridWidth * 2;
806       nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
807       //second row right
808       AddQuadIndices( indices, rowIdx, nextRowIdx );
809
810       //left and right
811       rowIdx     = nextRowIdx - 2;
812       nextRowIdx = rowIdx + 4;
813       for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
814       {
815         AddQuadIndices( indices, rowIdx, nextRowIdx );
816       }
817     }
818
819     //second row left
820     AddQuadIndices( indices, rowIdx, nextRowIdx );
821
822     rowIdx     += increment;
823     nextRowIdx += gridWidth - 1;
824     //second row right
825     AddQuadIndices( indices, rowIdx, nextRowIdx );
826   }
827
828   //bottom
829   rowIdx     = nextRowIdx - gridWidth + 1;
830   nextRowIdx = rowIdx + gridWidth + 1;
831   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
832   {
833     AddQuadIndices( indices, rowIdx, nextRowIdx );
834   }
835
836   return GenerateGeometry( vertices, indices );
837 }
838
839 void NPatchVisual::SetResource()
840 {
841   const NPatchLoader::Data* data;
842   if( mImpl->mRenderer && mLoader.GetNPatchData( mId, data ) )
843   {
844     Geometry geometry = CreateGeometry();
845     Shader shader = CreateShader();
846
847     mImpl->mRenderer.SetGeometry( geometry );
848     mImpl->mRenderer.SetShader( shader );
849
850     Actor actor = mPlacementActor.GetHandle();
851     if( actor )
852     {
853       ApplyTextureAndUniforms();
854       actor.AddRenderer( mImpl->mRenderer );
855       mPlacementActor.Reset();
856
857       // npatch loaded and ready to display
858       ResourceReady( Toolkit::Visual::ResourceStatus::READY );
859     }
860   }
861 }
862
863 void NPatchVisual::LoadComplete( bool loadSuccess, Devel::PixelBuffer pixelBuffer, const VisualUrl& url, bool preMultiplied )
864 {
865   if( url.GetUrl() == mAuxiliaryUrl.GetUrl() )
866   {
867     mAuxiliaryPixelBuffer = pixelBuffer;
868     const NPatchLoader::Data* data;
869     if( mLoader.GetNPatchData( mId, data ) && data->loadCompleted )
870     {
871       SetResource();
872     }
873   }
874   else
875   {
876     if( loadSuccess )
877     {
878       mLoader.SetNPatchData( mId, pixelBuffer );
879       EnablePreMultipliedAlpha( preMultiplied );
880     }
881
882     if( mAuxiliaryPixelBuffer || !mAuxiliaryUrl.IsValid() )
883     {
884       SetResource();
885     }
886   }
887 }
888
889 } // namespace Internal
890
891 } // namespace Toolkit
892
893 } // namespace Dali