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/visual-factory/devel-visual-properties.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>
48 const char * const BORDER_ONLY("borderOnly");
50 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
51 attribute mediump vec2 aPosition;\n
52 varying mediump vec2 vTexCoord;\n
53 uniform mediump mat4 uMvpMatrix;\n
54 uniform mediump vec3 uSize;\n
55 uniform mediump vec2 uNinePatchFactorsX[ FACTOR_SIZE_X ];\n
56 uniform mediump vec2 uNinePatchFactorsY[ FACTOR_SIZE_Y ];\n
59 //Visual size and offset
60 uniform mediump vec2 offset;\n
61 uniform mediump vec2 size;\n
62 uniform mediump vec4 offsetSizeMode;\n
63 uniform mediump vec2 origin;\n
64 uniform mediump vec2 anchorPoint;\n
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
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
75 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
76 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
78 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( visualSize.xy - fixedTotal ) * stretch / stretchTotal ) + anchorPoint*visualSize + (visualOffset + origin)*uSize.xy, 0.0, 1.0 );\n
79 vertexPosition.xy -= visualSize.xy * vec2( 0.5, 0.5 );\n
81 vertexPosition = uMvpMatrix * vertexPosition;\n
83 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
85 gl_Position = vertexPosition;\n
89 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
90 attribute mediump vec2 aPosition;\n
91 varying mediump vec2 vTexCoord;\n
92 uniform mediump mat4 uModelMatrix;\n
93 uniform mediump mat4 uMvpMatrix;\n
94 uniform mediump vec3 uSize;\n
95 uniform mediump vec2 uFixed[ 3 ];\n
96 uniform mediump vec2 uStretchTotal;\n
99 //Visual size and offset
100 uniform mediump vec2 offset;\n
101 uniform mediump vec2 size;\n
102 uniform mediump vec4 offsetSizeMode;\n
103 uniform mediump vec2 origin;\n
104 uniform mediump vec2 anchorPoint;\n
108 vec2 visualSize = mix(uSize.xy*size, size, offsetSizeMode.zw );\n
109 vec2 visualOffset = mix( offset, offset/uSize.xy, offsetSizeMode.xy);\n
111 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
112 mediump vec2 size = visualSize.xy * scale;\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
118 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );
119 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
120 vertexPosition.xy = vertexPosition.xy / scale + anchorPoint*size + (visualOffset + origin)*uSize.xy;\
122 vertexPosition = uMvpMatrix * vertexPosition;\n
124 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
126 gl_Position = vertexPosition;\n
130 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
131 varying mediump vec2 vTexCoord;\n
132 uniform sampler2D sTexture;\n
133 uniform lowp vec4 uColor;\n
137 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
142 * @brief Creates the geometry formed from the vertices and indices
144 * @param[in] vertices The vertices to generate the geometry from
145 * @param[in] indices The indices to generate the geometry from
146 * @return The geometry formed from the vertices and indices
148 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned short >& indices )
150 Property::Map vertexFormat;
151 vertexFormat[ "aPosition" ] = Property::VECTOR2;
152 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
153 if( vertices.Size() > 0 )
155 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
158 // Create the geometry object
159 Geometry geometry = Geometry::New();
160 geometry.AddVertexBuffer( vertexPropertyBuffer );
161 if( indices.Size() > 0 )
163 geometry.SetIndexBuffer( &indices[ 0 ], indices.Size() );
171 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
173 * @param[out] indices The indices to add to
174 * @param[in] rowIdx The row index to start the quad
175 * @param[in] nextRowIdx The index to the next row
177 void AddQuadIndices( Vector< unsigned short >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
179 indices.PushBack( rowIdx );
180 indices.PushBack( nextRowIdx + 1 );
181 indices.PushBack( rowIdx + 1 );
183 indices.PushBack( rowIdx );
184 indices.PushBack( nextRowIdx );
185 indices.PushBack( nextRowIdx + 1 );
188 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
190 vertices.PushBack( Vector2( x, y ) );
193 void RegisterStretchProperties( Renderer& renderer, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
195 uint16_t prevEnd = 0;
196 uint16_t prevFix = 0;
197 uint16_t prevStretch = 0;
199 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
201 uint16_t start = it->GetX();
202 uint16_t end = it->GetY();
204 uint16_t fix = prevFix + start - prevEnd;
205 uint16_t stretch = prevStretch + end - start;
207 std::stringstream uniform;
208 uniform << uniformName << "[" << i << "]";
209 renderer.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
213 prevStretch = stretch;
217 prevFix += imageExtent - prevEnd;
218 std::stringstream uniform;
219 uniform << uniformName << "[" << i << "]";
220 renderer.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
224 } //unnamed namespace
226 /////////////////NPatchVisual////////////////
228 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache )
230 return new NPatchVisual( factoryCache );
233 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, const std::string& imageUrl, bool borderOnly )
235 NPatchVisual* nPatchVisual = new NPatchVisual( factoryCache, borderOnly );
236 nPatchVisual->mImageUrl = imageUrl;
238 NinePatchImage image = NinePatchImage::New( imageUrl );
239 nPatchVisual->InitializeFromImage( image );
244 NPatchVisualPtr NPatchVisual::New( VisualFactoryCache& factoryCache, NinePatchImage image, bool borderOnly )
246 NPatchVisual* nPatchVisual = new NPatchVisual( factoryCache, borderOnly );
247 nPatchVisual->mImage = image;
249 nPatchVisual->InitializeFromImage( image );
254 NPatchVisual::NPatchVisual( VisualFactoryCache& factoryCache, bool borderOnly )
255 : Visual::Base( factoryCache ),
262 mBorderOnly( borderOnly )
266 NPatchVisual::~NPatchVisual()
270 void NPatchVisual::DoSetProperties( const Property::Map& propertyMap )
272 Property::Value* imageURLValue = propertyMap.Find( Toolkit::ImageVisual::Property::URL, IMAGE_URL_NAME );
275 //Read the borderOnly property first since InitialiseFromImage relies on mBorderOnly to be properly set
276 Property::Value* borderOnlyValue = propertyMap.Find( Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY );
277 if( borderOnlyValue )
279 borderOnlyValue->Get( mBorderOnly );
282 if( imageURLValue->Get( mImageUrl ) )
284 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
285 InitializeFromImage( nPatch );
289 InitializeFromBrokenImage();
290 DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
295 void NPatchVisual::GetNaturalSize( Vector2& naturalSize ) const
299 naturalSize.x = mImage.GetWidth();
300 naturalSize.y = mImage.GetHeight();
302 else if( !mImageUrl.empty() )
304 ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
305 naturalSize.x = dimentions.GetWidth();
306 naturalSize.y = dimentions.GetHeight();
310 naturalSize = Vector2::ZERO;
314 Geometry NPatchVisual::CreateGeometry()
317 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
321 geometry = mFactoryCache.GetGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY );
324 geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
325 mFactoryCache.SaveGeometry( VisualFactoryCache::NINE_PATCH_GEOMETRY, geometry );
330 geometry = mFactoryCache.GetGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
333 geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
334 mFactoryCache.SaveGeometry( VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
338 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
340 Uint16Pair gridSize( 2 * mStretchPixelsX.Size() + 1, 2 * mStretchPixelsY.Size() + 1 );
341 geometry = !mBorderOnly ? CreateGeometry( gridSize ) : CreateGeometryBorder( gridSize );
347 Shader NPatchVisual::CreateShader()
350 if( !mImpl->mCustomShader )
352 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
354 shader = mFactoryCache.GetShader( VisualFactoryCache::NINE_PATCH_SHADER );
357 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
358 mFactoryCache.SaveShader( VisualFactoryCache::NINE_PATCH_SHADER, shader );
361 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
363 std::stringstream vertexShader;
364 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
365 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
368 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
373 const char* fragmentShader = FRAGMENT_SHADER;
374 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
376 if( !mImpl->mCustomShader->mFragmentShader.empty() )
378 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
380 hints = mImpl->mCustomShader->mHints;
382 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
384 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
386 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
388 std::stringstream vertexShader;
389 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
390 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
393 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
400 void NPatchVisual::InitializeRenderer()
402 Geometry geometry = CreateGeometry();
403 Shader shader = CreateShader();
405 if( !geometry || !shader )
407 DALI_LOG_ERROR("The 9 patch image '%s' doesn't have any valid stretch borders and so is not a valid 9 patch image\n", mImageUrl.c_str() );
408 InitializeFromBrokenImage();
411 TextureSet textureSet = TextureSet::New();
412 mImpl->mRenderer = Renderer::New( geometry, shader );
413 mImpl->mRenderer.SetTextures( textureSet );
415 //Register transform properties
416 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
420 void NPatchVisual::DoSetOnStage( Actor& actor )
424 if( !mImageUrl.empty() )
426 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
427 InitializeFromImage( nPatch );
431 InitializeFromImage( mImage );
435 //initialize the renderer after initializing from the image since we need to know the grid size from the image before creating the geometry
436 InitializeRenderer();
440 ApplyImageToSampler();
443 actor.AddRenderer( mImpl->mRenderer );
446 void NPatchVisual::DoSetOffStage( Actor& actor )
448 mCroppedImage.Reset();
449 actor.RemoveRenderer( mImpl->mRenderer );
450 mImpl->mRenderer.Reset();
453 void NPatchVisual::DoCreatePropertyMap( Property::Map& map ) const
456 map.Insert( Toolkit::VisualProperty::TYPE, Toolkit::Visual::IMAGE );
457 if( !mImageUrl.empty() )
459 map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl );
463 map.Insert( Toolkit::ImageVisual::Property::URL, mImage.GetUrl() );
465 map.Insert( Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly );
468 void NPatchVisual::DoSetProperty( Dali::Property::Index index, const Dali::Property::Value& propertyValue )
473 Dali::Property::Value NPatchVisual::DoGetProperty( Dali::Property::Index index )
476 return Dali::Property::Value();
479 void NPatchVisual::OnSetTransform()
481 if( mImpl->mRenderer )
483 mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
488 void NPatchVisual::ChangeRenderer( bool oldBorderOnly, size_t oldGridX, size_t oldGridY )
490 //check to see if the border style has changed
492 bool borderOnlyChanged = oldBorderOnly != mBorderOnly;
493 bool gridChanged = oldGridX != mStretchPixelsX.Size() || oldGridY != mStretchPixelsY.Size();
495 if( borderOnlyChanged || gridChanged )
497 Geometry geometry = CreateGeometry();
500 mImpl->mRenderer.SetGeometry( geometry );
504 InitializeFromBrokenImage();
510 Shader shader = CreateShader();
511 TextureSet textureSet;
514 textureSet = mImpl->mRenderer.GetTextures();
517 InitializeFromBrokenImage();
519 mImpl->mRenderer.SetShader( shader );
524 void NPatchVisual::InitializeFromImage( NinePatchImage nPatch )
526 mCroppedImage = nPatch.CreateCroppedBufferImage();
529 DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
530 InitializeFromBrokenImage();
534 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
536 mStretchPixelsX = nPatch.GetStretchPixelsX();
537 mStretchPixelsY = nPatch.GetStretchPixelsY();
540 void NPatchVisual::InitializeFromBrokenImage()
542 mCroppedImage = VisualFactoryCache::GetBrokenVisualImage();
543 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
545 mStretchPixelsX.Clear();
546 mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
547 mStretchPixelsY.Clear();
548 mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
551 void NPatchVisual::ApplyImageToSampler()
553 TextureSet textureSet = mImpl->mRenderer.GetTextures();
556 TextureSetImage( textureSet, 0u, mCroppedImage );
558 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
560 //special case for 9 patch
561 Uint16Pair stretchX = mStretchPixelsX[ 0 ];
562 Uint16Pair stretchY = mStretchPixelsY[ 0 ];
564 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
565 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
567 mImpl->mRenderer.RegisterProperty( "uFixed[0]", Vector2::ZERO );
568 mImpl->mRenderer.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
569 mImpl->mRenderer.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
570 mImpl->mRenderer.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
574 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
575 mImpl->mRenderer.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
577 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsX", mStretchPixelsX, mImageSize.GetWidth() );
578 RegisterStretchProperties( mImpl->mRenderer, "uNinePatchFactorsY", mStretchPixelsY, mImageSize.GetHeight() );
583 Geometry NPatchVisual::CreateGeometry( Uint16Pair gridSize )
585 uint16_t gridWidth = gridSize.GetWidth();
586 uint16_t gridHeight = gridSize.GetHeight();
589 Vector< Vector2 > vertices;
590 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
592 for( int y = 0; y < gridHeight + 1; ++y )
594 for( int x = 0; x < gridWidth + 1; ++x )
596 AddVertex( vertices, x, y );
601 //TODO: compare performance with triangle strip when Geometry supports it
602 Vector< unsigned short > indices;
603 indices.Reserve( gridWidth * gridHeight * 6 );
605 unsigned int rowIdx = 0;
606 unsigned int nextRowIdx = gridWidth + 1;
607 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
609 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
611 AddQuadIndices( indices, rowIdx, nextRowIdx );
615 return GenerateGeometry( vertices, indices );
618 Geometry NPatchVisual::CreateGeometryBorder( Uint16Pair gridSize )
620 uint16_t gridWidth = gridSize.GetWidth();
621 uint16_t gridHeight = gridSize.GetHeight();
624 Vector< Vector2 > vertices;
625 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
631 for( int x = 0; x < gridWidth + 1; ++x )
633 AddVertex( vertices, x, y );
637 for(; y < gridHeight - 1; ++y)
640 AddVertex( vertices, 0, y );
641 AddVertex( vertices, 1, y );
644 AddVertex( vertices, gridWidth - 1, y );
645 AddVertex( vertices, gridWidth, y );
649 for(; y < gridHeight + 1; ++y)
651 for( int x = 0; x < gridWidth + 1; ++x )
653 AddVertex( vertices, x, y );
658 //TODO: compare performance with triangle strip when Geometry supports it
659 Vector< unsigned short > indices;
660 indices.Reserve( gridWidth * gridHeight * 6 );
663 unsigned int rowIdx = 0 ;
664 unsigned int nextRowIdx = gridWidth + 1;
665 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
667 AddQuadIndices( indices, rowIdx, nextRowIdx );
672 rowIdx = gridWidth + 1;
673 nextRowIdx = ( gridWidth + 1 ) * 2;
675 unsigned increment = gridWidth - 1;
680 AddQuadIndices( indices, rowIdx, nextRowIdx );
682 rowIdx = gridWidth * 2;
683 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
685 AddQuadIndices( indices, rowIdx, nextRowIdx );
688 rowIdx = nextRowIdx - 2;
689 nextRowIdx = rowIdx + 4;
690 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
692 AddQuadIndices( indices, rowIdx, nextRowIdx );
697 AddQuadIndices( indices, rowIdx, nextRowIdx );
700 nextRowIdx += gridWidth - 1;
702 AddQuadIndices( indices, rowIdx, nextRowIdx );
706 rowIdx = nextRowIdx - gridWidth + 1;
707 nextRowIdx = rowIdx + gridWidth + 1;
708 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
710 AddQuadIndices( indices, rowIdx, nextRowIdx );
713 return GenerateGeometry( vertices, indices );
716 } // namespace Internal
718 } // namespace Toolkit