2 * Copyright (c) 2016 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "npatch-visual.h"
22 #include <dali/integration-api/platform-abstraction.h>
23 #include <dali/public-api/images/buffer-image.h>
24 #include <dali/public-api/images/resource-image.h>
25 #include <dali/devel-api/images/texture-set-image.h>
28 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
29 #include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
30 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
31 #include <dali-toolkit/internal/visuals/npatch-loader.h>
32 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
33 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
34 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
35 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
36 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
50 const char * const BORDER_ONLY( "borderOnly" );
51 const char * const BORDER( "border" );
53 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
54 attribute mediump vec2 aPosition;\n
55 varying mediump vec2 vTexCoord;\n
56 uniform mediump mat4 uMvpMatrix;\n
57 uniform mediump vec3 uSize;\n
58 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
59 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
62 //Visual size and offset
63 uniform mediump vec2 offset;\n
64 uniform mediump vec2 size;\n
65 uniform mediump vec4 offsetSizeMode;\n
66 uniform mediump vec2 origin;\n
67 uniform mediump vec2 anchorPoint;\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
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
78 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
79 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
81 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal ) + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
82 vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
84 vertexPosition = uMvpMatrix * vertexPosition;\n
86 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
88 gl_Position = vertexPosition;\n
92 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
93 attribute mediump vec2 aPosition;\n
94 varying mediump vec2 vTexCoord;\n
95 uniform mediump mat4 uModelMatrix;\n
96 uniform mediump mat4 uMvpMatrix;\n
97 uniform mediump vec3 uSize;\n
98 uniform mediump vec2 uFixed[ 3 ];\n
99 uniform mediump vec2 uStretchTotal;\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
111 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
112 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
114 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
115 mediump vec2 size = visualSize.xy;\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
121 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );
122 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
123 vertexPosition.xy = vertexPosition.xy + anchorPoint*size + (visualOffset + origin)*uSize.xy;\
125 vertexPosition = uMvpMatrix * vertexPosition;\n
127 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
129 gl_Position = vertexPosition;\n
133 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
134 varying mediump vec2 vTexCoord;\n
135 uniform sampler2D sTexture;\n
136 uniform lowp vec4 uColor;\n
137 uniform lowp vec3 mixColor;\n
138 uniform lowp float opacity;\n
139 uniform lowp float preMultipliedAlpha;\n
140 lowp vec4 visualMixColor()\n
142 return vec4( mixColor * mix( 1.0, opacity, preMultipliedAlpha ), opacity );\n
146 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor * visualMixColor();\n
151 * @brief Creates the geometry formed from the vertices and indices
153 * @param[in] vertices The vertices to generate the geometry from
154 * @param[in] indices The indices to generate the geometry from
155 * @return The geometry formed from the vertices and indices
157 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
159 Property::Map vertexFormat;
160 vertexFormat[ "aPosition" ] = Property::VECTOR2;
161 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
162 if( vertices.Size() > 0 )
164 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
167 // Create the geometry object
168 Geometry geometry = Geometry::New();
169 geometry.AddVertexBuffer( vertexPropertyBuffer );
170 if( indices.Size() > 0 )
172 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
180 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
182 * @param[out] indices The indices to add to
183 * @param[in] rowIdx The row index to start the quad
184 * @param[in] nextRowIdx The index to the next row
186 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
188 indices.PushBack( rowIdx );
189 indices.PushBack( nextRowIdx + 1 );
190 indices.PushBack( rowIdx + 1 );
192 indices.PushBack( rowIdx );
193 indices.PushBack( nextRowIdx );
194 indices.PushBack( nextRowIdx + 1 );
197 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
199 vertices.PushBack( Vector2( x, y ) );
202 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
204 uint16_t prevEnd = 0;
205 uint16_t prevFix = 0;
206 uint16_t prevStretch = 0;
208 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
210 uint16_t start = it->GetX();
211 uint16_t end = it->GetY();
213 uint16_t fix = prevFix + start - prevEnd;
214 uint16_t stretch = prevStretch + end - start;
216 std::stringstream uniform;
217 uniform << uniformName << "[" << i << "]";
218 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
222 prevStretch = stretch;
226 prevFix += imageExtent - prevEnd;
227 std::stringstream uniform;
228 uniform << uniformName << "[" << i << "]";
229 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
233 } //unnamed namespace
235 /////////////////NPatchVisual////////////////
237 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl, const Property::Map& properties )
239 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
240 nPatchVisual->mImageUrl = imageUrl;
241 nPatchVisual->SetProperties( properties );
246 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const VisualUrl& imageUrl )
248 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
249 nPatchVisual->mImageUrl = imageUrl;
254 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, NinePatchImage image )
256 NPatchVisualPtr nPatchVisual( new NPatchVisual( factoryCache ) );
257 VisualUrl visualUrl( image.GetUrl() );
258 nPatchVisual->mImageUrl = visualUrl;
262 void NPatchVisual::GetNaturalSize( Vector2& naturalSize )
267 // load now if not already loaded
268 if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocal() )
270 mId = mLoader.Load( mImageUrl.GetUrl(), mBorder );
272 const NPatchLoader::Data* data;
273 if( mLoader.GetNPatchData( mId, data ) )
275 naturalSize.x = data->croppedWidth;
276 naturalSize.y = data->croppedHeight;
280 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
282 // URL is already passed in via constructor
284 Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
285 if( borderOnlyValue )
287 borderOnlyValue->Get( mBorderOnly );
290 Property::Value* borderValue = propertyMap.Find( Toolkit::DevelImageVisual::Property::BORDER, BORDER );
291 if( borderValue && ! borderValue->Get( mBorder ) ) // If value exists and is rect, just set mBorder
293 // Not a rect so try vector4
295 if( borderValue->Get( border ) )
297 mBorder.left = static_cast< int >( border.x );
298 mBorder.right = static_cast< int >( border.y );
299 mBorder.bottom = static_cast< int >( border.z );
300 mBorder.top = static_cast< int >( border.w );
305 void NPatchVisual::DoSetOnStage( Actor& actor )
307 // load when first go on stage
308 if( NPatchLoader::UNINITIALIZED_ID == mId && mImageUrl.IsLocal() )
310 mId = mLoader.Load( mImageUrl.GetUrl(), mBorder );
313 Geometry geometry = CreateGeometry();
314 Shader shader = CreateShader();
315 mImpl->mRenderer = Renderer::New( geometry, shader );
317 ApplyTextureAndUniforms();
319 actor.AddRenderer( mImpl->mRenderer );
322 void NPatchVisual::DoSetOffStage( Actor& actor )
324 actor.RemoveRenderer( mImpl->mRenderer );
325 mImpl->mRenderer.Reset();
328 void NPatchVisual::OnSetTransform()
330 if( mImpl->mRenderer )
332 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
336 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
339 map.Insert( Toolkit::DevelVisual::Property::TYPE, Toolkit::DevelVisual::N_PATCH );
340 map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
341 map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
342 map.Insert( Toolkit::DevelImageVisual::Property::BORDER, mBorder );
345 void NPatchVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
350 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache )
351 : Visual::Base( factoryCache ),
352 mLoader( factoryCache.GetNPatchLoader() ),
354 mId( NPatchLoader::UNINITIALIZED_ID ),
355 mBorderOnly( false ),
360 NPatchVisual::~NPatchVisual()
364 Geometry NPatchVisual::CreateGeometry()
367 const NPatchLoader::Data* data;
368 if( mLoader.GetNPatchData( mId, data ) )
370 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
372 if( DALI_UNLIKELY( mBorderOnly ) )
374 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
378 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
381 else if( data->stretchPixelsX.Size() > 0 || data->stretchPixelsY.Size() > 0)
383 Uint16Pair gridSize( 2 * data->stretchPixelsX.Size() + 1, 2 * data->stretchPixelsY.Size() + 1 );
384 geometry = !mBorderOnly ? CreateGridGeometry( gridSize ) : CreateBorderGeometry( gridSize );
389 // no N patch data so use default geometry
390 geometry = GetNinePatchGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
395 Shader NPatchVisual::CreateShader()
398 const NPatchLoader::Data* data;
399 // 0 is either no data (load failed?) or no stretch regions on image
400 // for both cases we use the default shader
401 NinePatchImage::StretchRanges::SizeType xStretchCount = 0;
402 NinePatchImage::StretchRanges::SizeType yStretchCount = 0;
404 // ask loader for the regions
405 if( mLoader.GetNPatchData( mId, data ) )
407 xStretchCount = data->stretchPixelsX.Count();
408 yStretchCount = data->stretchPixelsY.Count();
411 if( DALI_LIKELY( !mImpl->mCustomShader ) )
413 if( DALI_LIKELY( ( xStretchCount == 1 && yStretchCount == 1 ) ||
414 ( xStretchCount == 0 && yStretchCount == 0 ) ) )
416 shader = mFactoryCache.GetShader( VisualFactoryCache::NINE_PATCH_SHADER );
417 if( DALI_UNLIKELY( !shader ) )
419 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
420 mFactoryCache.SaveShader( VisualFactoryCache::NINE_PATCH_SHADER, shader );
423 else if( xStretchCount > 0 || yStretchCount > 0)
425 std::stringstream vertexShader;
426 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
427 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
430 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
435 const char* fragmentShader = FRAGMENT_SHADER;
436 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
438 if( !mImpl->mCustomShader->mFragmentShader.empty() )
440 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
442 hints = mImpl->mCustomShader->mHints;
444 if( ( xStretchCount == 1 && yStretchCount == 1 ) ||
445 ( xStretchCount == 0 && yStretchCount == 0 ) )
447 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
449 else if( xStretchCount > 0 || yStretchCount > 0)
451 std::stringstream vertexShader;
452 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
453 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
456 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
463 void NPatchVisual::ApplyTextureAndUniforms()
465 const NPatchLoader::Data* data;
466 if( mLoader.GetNPatchData( mId, data ) )
468 TextureSet textures( data->textureSet );
469 mImpl->mRenderer.SetTextures( textures );
470 if( data->stretchPixelsX.Size() == 1 && data->stretchPixelsY.Size() == 1 )
472 //special case for 9 patch
473 Uint16Pair stretchX = data->stretchPixelsX[ 0 ];
474 Uint16Pair stretchY = data->stretchPixelsY[ 0 ];
476 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
477 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
479 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
480 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
481 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( data->croppedWidth - stretchWidth, data->croppedHeight - stretchHeight ) );
482 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
486 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
487 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
489 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", data->stretchPixelsX, data->croppedWidth );
490 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", data->stretchPixelsY, data->croppedHeight );
495 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str() );
496 TextureSet textureSet = TextureSet::New();
497 mImpl->mRenderer.SetTextures( textureSet );
498 Image croppedImage = VisualFactoryCache::GetBrokenVisualImage();
499 TextureSetImage( textureSet, 0u, croppedImage );
500 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
501 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2::ZERO );
502 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2::ZERO );
503 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( croppedImage.GetWidth(), croppedImage.GetHeight() ) );
506 //Register transform properties
507 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
510 Geometry NPatchVisual::GetNinePatchGeometry( VisualFactoryCache::GeometryType subType )
512 Geometry geometry = mFactoryCache.GetGeometry( subType );
515 if( DALI_LIKELY( VisualFactoryCache::NINE_PATCH_GEOMETRY == subType ) )
517 geometry = CreateGridGeometry( Uint16Pair( 3, 3 ) );
519 else if( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType )
521 geometry = CreateBorderGeometry( Uint16Pair( 3, 3 ) );
523 mFactoryCache.SaveGeometry( subType, geometry );
528 Geometry NPatchVisual::CreateGridGeometry( Uint16Pair gridSize )
530 uint16_t gridWidth = gridSize.GetWidth();
531 uint16_t gridHeight = gridSize.GetHeight();
534 Vector< Vector2 > vertices;
535 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
537 for( int y = 0; y < gridHeight + 1; ++y )
539 for( int x = 0; x < gridWidth + 1; ++x )
541 AddVertex( vertices, x, y );
546 Vector< unsigned short > indices;
547 indices.Reserve( gridWidth * gridHeight * 6 );
549 unsigned int rowIdx = 0;
550 unsigned int nextRowIdx = gridWidth + 1;
551 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
553 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
555 AddQuadIndices( indices, rowIdx, nextRowIdx );
559 return GenerateGeometry( vertices, indices );
562 Geometry NPatchVisual::CreateBorderGeometry( Uint16Pair gridSize )
564 uint16_t gridWidth = gridSize.GetWidth();
565 uint16_t gridHeight = gridSize.GetHeight();
568 Vector< Vector2 > vertices;
569 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
575 for( int x = 0; x < gridWidth + 1; ++x )
577 AddVertex( vertices, x, y );
581 for(; y < gridHeight - 1; ++y)
584 AddVertex( vertices, 0, y );
585 AddVertex( vertices, 1, y );
588 AddVertex( vertices, gridWidth - 1, y );
589 AddVertex( vertices, gridWidth, y );
593 for(; y < gridHeight + 1; ++y)
595 for( int x = 0; x < gridWidth + 1; ++x )
597 AddVertex( vertices, x, y );
602 Vector< unsigned short > indices;
603 indices.Reserve( gridWidth * gridHeight * 6 );
606 unsigned int rowIdx = 0 ;
607 unsigned int nextRowIdx = gridWidth + 1;
608 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
610 AddQuadIndices( indices, rowIdx, nextRowIdx );
615 rowIdx = gridWidth + 1;
616 nextRowIdx = ( gridWidth + 1 ) * 2;
618 unsigned increment = gridWidth - 1;
623 AddQuadIndices( indices, rowIdx, nextRowIdx );
625 rowIdx = gridWidth * 2;
626 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
628 AddQuadIndices( indices, rowIdx, nextRowIdx );
631 rowIdx = nextRowIdx - 2;
632 nextRowIdx = rowIdx + 4;
633 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
635 AddQuadIndices( indices, rowIdx, nextRowIdx );
640 AddQuadIndices( indices, rowIdx, nextRowIdx );
643 nextRowIdx += gridWidth - 1;
645 AddQuadIndices( indices, rowIdx, nextRowIdx );
649 rowIdx = nextRowIdx - gridWidth + 1;
650 nextRowIdx = rowIdx + gridWidth + 1;
651 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
653 AddQuadIndices( indices, rowIdx, nextRowIdx );
656 return GenerateGeometry( vertices, indices );
659 } // namespace Internal
661 } // namespace Toolkit