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