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