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