2 * Copyright (c) 2015 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-renderer.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>
27 #include <dali-toolkit/internal/controls/renderers/renderer-factory-impl.h>
28 #include <dali-toolkit/internal/controls/renderers/renderer-factory-cache.h>
29 #include <dali-toolkit/internal/controls/renderers/control-renderer-impl.h>
30 #include <dali-toolkit/internal/controls/renderers/control-renderer-data-impl.h>
44 const char * const RENDERER_TYPE("rendererType");
45 const char * const RENDERER_TYPE_VALUE("nPatch");
47 const char * const IMAGE_URL_NAME("imageUrl");
48 const char * const BORDER_ONLY("borderOnly");
50 std::string TEXTURE_UNIFORM_NAME = "sTexture";
52 const char* VERTEX_SHADER = DALI_COMPOSE_SHADER(
53 attribute mediump vec2 aPosition;\n
54 varying mediump vec2 vTexCoord;\n
55 uniform mediump 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
62 mediump vec2 fixedFactor = vec2( uNinePatchFactorsX[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uNinePatchFactorsY[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].x );\n
63 mediump vec2 stretch = vec2( uNinePatchFactorsX[ int( ( aPosition.x ) * 0.5 ) ].y, uNinePatchFactorsY[ int( ( aPosition.y ) * 0.5 ) ].y );\n
65 mediump vec2 fixedTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].x, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].x );\n
66 mediump vec2 stretchTotal = vec2( uNinePatchFactorsX[ FACTOR_SIZE_X - 1 ].y, uNinePatchFactorsY[ FACTOR_SIZE_Y - 1 ].y );\n
68 mediump vec4 vertexPosition = vec4( ( fixedFactor + ( uSize.xy - fixedTotal ) * stretch / stretchTotal ), 0.0, 1.0 );\n
69 vertexPosition.xy -= uSize.xy * vec2( 0.5, 0.5 );\n
70 vertexPosition = uMvpMatrix * vertexPosition;\n
72 vTexCoord = ( fixedFactor + stretch ) / ( fixedTotal + stretchTotal );\n
74 gl_Position = vertexPosition;\n
78 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
79 attribute mediump vec2 aPosition;\n
80 varying mediump vec2 vTexCoord;\n
81 uniform mediump mat4 uModelMatrix;\n
82 uniform mediump mat4 uMvpMatrix;\n
83 uniform mediump vec3 uSize;\n
84 uniform mediump vec2 uFixed[ 3 ];\n
85 uniform mediump vec2 uStretchTotal;\n
89 mediump vec2 scale = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
90 mediump vec2 size = uSize.xy * scale;\n
92 mediump vec2 fixedFactor = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y + 1.0 ) * 0.5 ) ].y );\n
93 mediump vec2 stretch = floor( aPosition * 0.5 );\n
94 mediump vec2 fixedTotal = uFixed[ 2 ];\n
96 mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
97 vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
98 vertexPosition.xy = vertexPosition.xy / scale;\n
100 vertexPosition = uMvpMatrix * vertexPosition;\n
102 vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
104 gl_Position = vertexPosition;\n
108 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
109 varying mediump vec2 vTexCoord;\n
110 uniform sampler2D sTexture;\n
111 uniform lowp vec4 uColor;\n
115 gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
120 * @brief Creates the geometry formed from the vertices and indices
122 * @param[in] vertices The vertices to generate the geometry from
123 * @param[in] indices The indices to generate the geometry from
124 * @return The geometry formed from the vertices and indices
126 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned int >& indices )
128 Property::Map vertexFormat;
129 vertexFormat[ "aPosition" ] = Property::VECTOR2;
130 PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat );
131 if( vertices.Size() > 0 )
133 vertexPropertyBuffer.SetData( &vertices[ 0 ], vertices.Size() );
136 Property::Map indexFormat;
137 indexFormat[ "indices" ] = Property::INTEGER;
138 PropertyBuffer indexPropertyBuffer = PropertyBuffer::New( indexFormat );
139 if( indices.Size() > 0 )
141 indexPropertyBuffer.SetData( &indices[ 0 ], indices.Size() );
144 // Create the geometry object
145 Geometry geometry = Geometry::New();
146 geometry.AddVertexBuffer( vertexPropertyBuffer );
147 geometry.SetIndexBuffer( indexPropertyBuffer );
153 * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
155 * @param[out] indices The indices to add to
156 * @param[in] rowIdx The row index to start the quad
157 * @param[in] nextRowIdx The index to the next row
159 void AddQuadIndices( Vector< unsigned int >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
161 indices.PushBack( rowIdx );
162 indices.PushBack( nextRowIdx + 1 );
163 indices.PushBack( rowIdx + 1 );
165 indices.PushBack( rowIdx );
166 indices.PushBack( nextRowIdx );
167 indices.PushBack( nextRowIdx + 1 );
170 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
172 vertices.PushBack( Vector2( x, y ) );
175 void RegisterStretchProperties( Material& material, const char * uniformName, const NinePatchImage::StretchRanges& stretchPixels, uint16_t imageExtent)
177 uint16_t prevEnd = 0;
178 uint16_t prevFix = 0;
179 uint16_t prevStretch = 0;
181 for( NinePatchImage::StretchRanges::ConstIterator it = stretchPixels.Begin(); it != stretchPixels.End(); ++it, ++i )
183 uint16_t start = it->GetX();
184 uint16_t end = it->GetY();
186 uint16_t fix = prevFix + start - prevEnd;
187 uint16_t stretch = prevStretch + end - start;
189 std::stringstream uniform;
190 uniform << uniformName << "[" << i << "]";
191 material.RegisterProperty( uniform.str(), Vector2( fix, stretch ) );
195 prevStretch = stretch;
199 prevFix += imageExtent - prevEnd;
200 std::stringstream uniform;
201 uniform << uniformName << "[" << i << "]";
202 material.RegisterProperty( uniform.str(), Vector2( prevFix, prevStretch ) );
206 } //unnamed namespace
208 /////////////////NPatchRenderer////////////////
210 NPatchRenderer::NPatchRenderer( RendererFactoryCache& factoryCache )
211 : ControlRenderer( factoryCache ),
216 NPatchRenderer::~NPatchRenderer()
220 void NPatchRenderer::DoInitialize( Actor& actor, const Property::Map& propertyMap )
222 Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
225 //Read the borderOnly property first since InitialiseFromImage relies on mBorderOnly to be properly set
226 Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
227 if( borderOnlyValue )
229 borderOnlyValue->Get( mBorderOnly );
232 if( imageURLValue->Get( mImageUrl ) )
234 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
235 InitializeFromImage( nPatch );
239 InitializeFromBrokenImage();
240 DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
245 void NPatchRenderer::GetNaturalSize( Vector2& naturalSize ) const
249 naturalSize.x = mImage.GetWidth();
250 naturalSize.y = mImage.GetHeight();
252 else if( !mImageUrl.empty() )
254 ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
255 naturalSize.x = dimentions.GetWidth();
256 naturalSize.y = dimentions.GetHeight();
260 naturalSize = Vector2::ZERO;
264 void NPatchRenderer::SetClipRect( const Rect<int>& clipRect )
266 ControlRenderer::SetClipRect( clipRect );
267 //ToDo: renderer responds to the clipRect change
270 void NPatchRenderer::SetOffset( const Vector2& offset )
272 //ToDo: renderer applies the offset
275 Geometry NPatchRenderer::CreateGeometry()
278 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
282 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY );
285 geometry = CreateGeometry( Uint16Pair( 3, 3 ) );
286 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY, geometry );
291 geometry = mFactoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
294 geometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
295 mFactoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY, geometry );
299 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
301 Uint16Pair gridSize( 2 * mStretchPixelsX.Size() + 1, 2 * mStretchPixelsY.Size() + 1 );
302 geometry = !mBorderOnly ? CreateGeometry( gridSize ) : CreateGeometryBorder( gridSize );
308 Shader NPatchRenderer::CreateShader()
311 if( !mImpl->mCustomShader )
313 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
315 shader = mFactoryCache.GetShader( RendererFactoryCache::NINE_PATCH_SHADER );
318 shader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
319 mFactoryCache.SaveShader( RendererFactoryCache::NINE_PATCH_SHADER, shader );
322 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
324 std::stringstream vertexShader;
325 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
326 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
329 shader = Shader::New( vertexShader.str(), FRAGMENT_SHADER );
334 const char* fragmentShader = FRAGMENT_SHADER;
335 Dali::Shader::ShaderHints hints = Dali::Shader::HINT_NONE;
337 if( !mImpl->mCustomShader->mFragmentShader.empty() )
339 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
341 hints = mImpl->mCustomShader->mHints;
343 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
345 shader = Shader::New( VERTEX_SHADER_3X3, fragmentShader, hints );
347 else if( mStretchPixelsX.Size() > 0 || mStretchPixelsY.Size() > 0)
349 std::stringstream vertexShader;
350 vertexShader << "#define FACTOR_SIZE_X " << mStretchPixelsX.Size() + 2 << "\n"
351 << "#define FACTOR_SIZE_Y " << mStretchPixelsY.Size() + 2 << "\n"
354 shader = Shader::New( vertexShader.str(), fragmentShader, hints );
361 void NPatchRenderer::InitializeRenderer()
363 Geometry geometry = CreateGeometry();
364 Shader shader = CreateShader();
366 if( !geometry || !shader )
368 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() );
369 InitializeFromBrokenImage();
372 Material material = Material::New( shader );
373 mImpl->mRenderer = Renderer::New( geometry, material );
377 void NPatchRenderer::DoSetOnStage( Actor& actor )
381 if( !mImageUrl.empty() )
383 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
384 InitializeFromImage( nPatch );
388 InitializeFromImage( mImage );
392 //initialize the renderer after initializing from the image since we need to know the grid size from the image before creating the geometry
393 InitializeRenderer();
397 ApplyImageToSampler();
401 void NPatchRenderer::DoSetOffStage( Actor& actor )
403 mCroppedImage.Reset();
404 actor.RemoveRenderer( mImpl->mRenderer );
405 mImpl->mRenderer.Reset();
408 void NPatchRenderer::DoCreatePropertyMap( Property::Map& map ) const
411 map.Insert( RENDERER_TYPE, RENDERER_TYPE_VALUE );
412 if( !mImageUrl.empty() )
414 map.Insert( IMAGE_URL_NAME, mImageUrl );
418 map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
420 map.Insert( BORDER_ONLY, mBorderOnly );
423 void NPatchRenderer::ChangeRenderer( bool oldBorderOnly, size_t oldGridX, size_t oldGridY )
425 //check to see if the border style has changed
427 bool borderOnlyChanged = oldBorderOnly != mBorderOnly;
428 bool gridChanged = oldGridX != mStretchPixelsX.Size() || oldGridY != mStretchPixelsY.Size();
430 if( borderOnlyChanged || gridChanged )
432 Geometry geometry = CreateGeometry();
435 mImpl->mRenderer.SetGeometry( geometry );
439 InitializeFromBrokenImage();
445 Shader shader = CreateShader();
449 material = mImpl->mRenderer.GetMaterial();
452 material.SetShader( shader );
458 InitializeFromBrokenImage();
463 void NPatchRenderer::SetImage( const std::string& imageUrl, bool borderOnly )
465 bool oldBorderOnly = mBorderOnly;
466 size_t oldGridX = mStretchPixelsX.Size();
467 size_t oldGridY = mStretchPixelsY.Size();
469 mBorderOnly = borderOnly;
471 if( mImageUrl == imageUrl )
476 mImageUrl = imageUrl;
477 if( mImpl->mRenderer )
479 NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
480 InitializeFromImage( nPatch );
482 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
486 ApplyImageToSampler();
491 void NPatchRenderer::SetImage( NinePatchImage image, bool borderOnly )
493 bool oldBorderOnly = mBorderOnly;
494 size_t oldGridX = mStretchPixelsX.Size();
495 size_t oldGridY = mStretchPixelsY.Size();
497 mBorderOnly = borderOnly;
499 if( mImage == image )
505 if( mImpl->mRenderer )
507 InitializeFromImage( mImage );
508 ChangeRenderer( oldBorderOnly, oldGridX, oldGridY );
512 ApplyImageToSampler();
517 void NPatchRenderer::InitializeFromImage( NinePatchImage nPatch )
519 mCroppedImage = nPatch.CreateCroppedBufferImage();
522 DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
523 InitializeFromBrokenImage();
527 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
529 mStretchPixelsX = nPatch.GetStretchPixelsX();
530 mStretchPixelsY = nPatch.GetStretchPixelsY();
533 void NPatchRenderer::InitializeFromBrokenImage()
535 mCroppedImage = RendererFactory::GetBrokenRendererImage();
536 mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
538 mStretchPixelsX.Clear();
539 mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
540 mStretchPixelsY.Clear();
541 mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
544 void NPatchRenderer::ApplyImageToSampler()
546 Material material = mImpl->mRenderer.GetMaterial();
549 int index = material.GetTextureIndex( TEXTURE_UNIFORM_NAME );
552 material.SetTextureImage( index, mCroppedImage );
556 material.AddTexture( mCroppedImage, TEXTURE_UNIFORM_NAME );
559 if( mStretchPixelsX.Size() == 1 && mStretchPixelsY.Size() == 1 )
561 //special case for 9 patch
562 Uint16Pair stretchX = mStretchPixelsX[ 0 ];
563 Uint16Pair stretchY = mStretchPixelsY[ 0 ];
565 uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
566 uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
568 material.RegisterProperty( "uFixed[0]", Vector2::ZERO );
569 material.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
570 material.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
571 material.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
575 material.RegisterProperty( "uNinePatchFactorsX[0]", Vector2::ZERO );
576 material.RegisterProperty( "uNinePatchFactorsY[0]", Vector2::ZERO );
578 RegisterStretchProperties( material, "uNinePatchFactorsX", mStretchPixelsX, mImageSize.GetWidth() );
579 RegisterStretchProperties( material, "uNinePatchFactorsY", mStretchPixelsY, mImageSize.GetHeight() );
584 Geometry NPatchRenderer::CreateGeometry( Uint16Pair gridSize )
586 uint16_t gridWidth = gridSize.GetWidth();
587 uint16_t gridHeight = gridSize.GetHeight();
590 Vector< Vector2 > vertices;
591 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
593 for( int y = 0; y < gridHeight + 1; ++y )
595 for( int x = 0; x < gridWidth + 1; ++x )
597 AddVertex( vertices, x, y );
602 //TODO: compare performance with triangle strip when Geometry supports it
603 Vector< unsigned int > indices;
604 indices.Reserve( gridWidth * gridHeight * 6 );
606 unsigned int rowIdx = 0;
607 unsigned int nextRowIdx = gridWidth + 1;
608 for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
610 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
612 AddQuadIndices( indices, rowIdx, nextRowIdx );
616 return GenerateGeometry( vertices, indices );
619 Geometry NPatchRenderer::CreateGeometryBorder( Uint16Pair gridSize )
621 uint16_t gridWidth = gridSize.GetWidth();
622 uint16_t gridHeight = gridSize.GetHeight();
625 Vector< Vector2 > vertices;
626 vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
632 for( int x = 0; x < gridWidth + 1; ++x )
634 AddVertex( vertices, x, y );
638 for(; y < gridHeight - 1; ++y)
641 AddVertex( vertices, 0, y );
642 AddVertex( vertices, 1, y );
645 AddVertex( vertices, gridWidth - 1, y );
646 AddVertex( vertices, gridWidth, y );
650 for(; y < gridHeight + 1; ++y)
652 for( int x = 0; x < gridWidth + 1; ++x )
654 AddVertex( vertices, x, y );
659 //TODO: compare performance with triangle strip when Geometry supports it
660 Vector< unsigned int > indices;
661 indices.Reserve( gridWidth * gridHeight * 6 );
664 unsigned int rowIdx = 0 ;
665 unsigned int nextRowIdx = gridWidth + 1;
666 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
668 AddQuadIndices( indices, rowIdx, nextRowIdx );
673 rowIdx = gridWidth + 1;
674 nextRowIdx = ( gridWidth + 1 ) * 2;
676 unsigned increment = gridWidth - 1;
681 AddQuadIndices( indices, rowIdx, nextRowIdx );
683 rowIdx = gridWidth * 2;
684 nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
686 AddQuadIndices( indices, rowIdx, nextRowIdx );
689 rowIdx = nextRowIdx - 2;
690 nextRowIdx = rowIdx + 4;
691 for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
693 AddQuadIndices( indices, rowIdx, nextRowIdx );
698 AddQuadIndices( indices, rowIdx, nextRowIdx );
701 nextRowIdx += gridWidth - 1;
703 AddQuadIndices( indices, rowIdx, nextRowIdx );
707 rowIdx = nextRowIdx - gridWidth + 1;
708 nextRowIdx = rowIdx + gridWidth + 1;
709 for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
711 AddQuadIndices( indices, rowIdx, nextRowIdx );
714 return GenerateGeometry( vertices, indices );
717 } // namespace Internal
719 } // namespace Toolkit