Render control background without creating extra actor
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / renderers / npatch / npatch-renderer.cpp
1 /*
2  * Copyright (c) 2015 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-renderer.h"
20
21 // EXTERNAL INCLUDES
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
26 // INTERNAL IINCLUDES
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>
31
32
33 namespace Dali
34 {
35
36 namespace Toolkit
37 {
38
39 namespace Internal
40 {
41
42 namespace
43 {
44 const char * const RENDERER_TYPE("renderer-type");
45 const char * const RENDERER_TYPE_VALUE("n-patch-renderer");
46
47 const char * const IMAGE_URL_NAME("image-url");
48 const char * const BORDER_ONLY("border-only");
49
50 std::string TEXTURE_UNIFORM_NAME = "sTexture";
51
52 const char* VERTEX_SHADER_3X3 = DALI_COMPOSE_SHADER(
53     attribute mediump vec2 aPosition;\n
54     varying mediump vec2 vTexCoord;\n
55     uniform mediump mat4 uModelMatrix;\n
56     uniform mediump mat4 uMvpMatrix;\n
57     uniform mediump vec3 uSize;\n
58     uniform mediump vec2 uFixed[ 3 ];\n
59     uniform mediump vec2 uStretchTotal;\n
60     \n
61     void main()\n
62     {\n
63       mediump vec2 scale        = vec2( length( uModelMatrix[ 0 ].xyz ), length( uModelMatrix[ 1 ].xyz ) );\n
64       mediump vec2 size         = uSize.xy * scale;\n
65       \n
66       mediump vec2 fixedFactor  = vec2( uFixed[ int( ( aPosition.x + 1.0 ) * 0.5 ) ].x, uFixed[ int( ( aPosition.y  + 1.0 ) * 0.5 ) ].y );\n
67       mediump vec2 stretch      = floor( aPosition * 0.5 );\n
68       mediump vec2 fixedTotal   = uFixed[ 2 ];\n
69       \n
70       mediump vec4 vertexPosition = vec4( fixedFactor + ( size - fixedTotal ) * stretch, 0.0, 1.0 );\n
71       vertexPosition.xy -= size * vec2( 0.5, 0.5 );\n
72       vertexPosition.xy =  vertexPosition.xy / scale;\n
73       \n
74       vertexPosition = uMvpMatrix * vertexPosition;\n
75       \n
76       vTexCoord = ( fixedFactor + stretch * uStretchTotal ) / ( fixedTotal + uStretchTotal );\n
77       \n
78       gl_Position = vertexPosition;\n
79     }\n
80 );
81
82 const char* FRAGMENT_SHADER = DALI_COMPOSE_SHADER(
83   varying mediump vec2 vTexCoord;\n
84   uniform sampler2D sTexture;\n
85   uniform lowp vec4 uColor;\n
86   \n
87   void main()\n
88   {\n
89     gl_FragColor = texture2D( sTexture, vTexCoord ) * uColor;\n
90   }\n
91 );
92
93 /**
94  * @brief Creates the geometry formed from the vertices and indices
95  *
96  * @param[in]  vertices             The vertices to generate the geometry from
97  * @param[in]  indices              The indices to generate the geometry from
98  * @return The geometry formed from the vertices and indices
99  */
100 Geometry GenerateGeometry( const Vector< Vector2 >& vertices, const Vector< unsigned int >& indices )
101 {
102   Property::Map vertexFormat;
103   vertexFormat[ "aPosition" ] = Property::VECTOR2;
104   PropertyBuffer vertexPropertyBuffer = PropertyBuffer::New( vertexFormat, vertices.Size() );
105   if( vertices.Size() > 0 )
106   {
107     vertexPropertyBuffer.SetData( &vertices[ 0 ] );
108   }
109
110   Property::Map indexFormat;
111   indexFormat[ "indices" ] = Property::INTEGER;
112   PropertyBuffer indexPropertyBuffer = PropertyBuffer::New( indexFormat, indices.Size() );
113   if( indices.Size() > 0 )
114   {
115     indexPropertyBuffer.SetData( &indices[ 0 ] );
116   }
117
118   // Create the geometry object
119   Geometry geometry = Geometry::New();
120   geometry.AddVertexBuffer( vertexPropertyBuffer );
121   geometry.SetIndexBuffer( indexPropertyBuffer );
122
123   return geometry;
124 }
125
126 /**
127  * @brief Adds the indices to form a quad composed off two triangles where the indices are organised in a grid
128  *
129  * @param[out] indices     The indices to add to
130  * @param[in]  rowIdx      The row index to start the quad
131  * @param[in]  nextRowIdx  The index to the next row
132  */
133 void AddQuadIndices( Vector< unsigned int >& indices, unsigned int rowIdx, unsigned int nextRowIdx )
134 {
135   indices.PushBack( rowIdx );
136   indices.PushBack( nextRowIdx + 1 );
137   indices.PushBack( rowIdx + 1 );
138
139   indices.PushBack( rowIdx );
140   indices.PushBack( nextRowIdx );
141   indices.PushBack( nextRowIdx + 1 );
142 }
143
144 void AddVertex( Vector< Vector2 >& vertices, unsigned int x, unsigned int y )
145 {
146   vertices.PushBack( Vector2( x, y ) );
147 }
148
149 } //unnamed namespace
150
151 /////////////////NPatchRenderer////////////////
152
153 NPatchRenderer::NPatchRenderer()
154 : ControlRenderer(),
155   mBorderOnly( false )
156 {
157 }
158
159 NPatchRenderer::~NPatchRenderer()
160 {
161 }
162
163 void NPatchRenderer::Initialize( RendererFactoryCache& factoryCache, const Property::Map& propertyMap )
164 {
165   Initialize(factoryCache);
166
167   Property::Value* imageURLValue = propertyMap.Find( IMAGE_URL_NAME );
168   if( imageURLValue )
169   {
170     //Read the border-only property first since InitialiseFromImage relies on mBorderOnly to be properly set
171     Property::Value* borderOnlyValue = propertyMap.Find( BORDER_ONLY );
172     if( borderOnlyValue )
173     {
174       borderOnlyValue->Get( mBorderOnly );
175     }
176
177     if( imageURLValue->Get( mImageUrl ) )
178     {
179       NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
180       InitialiseFromImage( nPatch );
181     }
182     else
183     {
184       CreateErrorImage();
185       DALI_LOG_ERROR( "The property '%s' is not a string\n", IMAGE_URL_NAME );
186     }
187   }
188 }
189
190 void NPatchRenderer::GetNaturalSize( Vector2& naturalSize ) const
191 {
192   if( mImage )
193   {
194     naturalSize.x = mImage.GetWidth();
195     naturalSize.y = mImage.GetHeight();
196     return;
197   }
198   else if( !mImageUrl.empty() )
199   {
200     ImageDimensions dimentions = ResourceImage::GetImageSize( mImageUrl );
201     naturalSize.x = dimentions.GetWidth();
202     naturalSize.y = dimentions.GetHeight();
203     return;
204   }
205
206   naturalSize = Vector2::ZERO;
207 }
208
209 void NPatchRenderer::SetClipRect( const Rect<int>& clipRect )
210 {
211   ControlRenderer::SetClipRect( clipRect );
212   //ToDo: renderer responds to the clipRect change
213 }
214
215 void NPatchRenderer::SetOffset( const Vector2& offset )
216 {
217   //ToDo: renderer applies the offset
218 }
219
220 void NPatchRenderer::DoSetOnStage( Actor& actor )
221 {
222   if( !mCroppedImage )
223   {
224     if( !mImageUrl.empty() )
225     {
226       NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
227       InitialiseFromImage( nPatch );
228     }
229     else if( mImage )
230     {
231       InitialiseFromImage( mImage );
232     }
233   }
234
235   if( mCroppedImage )
236   {
237     ApplyImageToSampler();
238   }
239 }
240
241 void NPatchRenderer::DoSetOffStage( Actor& actor )
242 {
243   mCroppedImage.Reset();
244 }
245
246 void NPatchRenderer::CreatePropertyMap( Property::Map& map ) const
247 {
248   map.Clear();
249   map.Insert( RENDERER_TYPE, RENDERER_TYPE_VALUE );
250   if( !mImageUrl.empty() )
251   {
252     map.Insert( IMAGE_URL_NAME, mImageUrl );
253   }
254   else if( mImage )
255   {
256     map.Insert( IMAGE_URL_NAME, mImage.GetUrl() );
257   }
258   map.Insert( BORDER_ONLY, mBorderOnly );
259 }
260
261 void NPatchRenderer::Initialize( RendererFactoryCache& factoryCache )
262 {
263   mNinePatchGeometry = factoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY );
264   if( !(mNinePatchGeometry) )
265   {
266     mNinePatchGeometry = CreateGeometry( Uint16Pair( 3, 3 ) );
267     factoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_GEOMETRY, mNinePatchGeometry );
268   }
269
270   mNinePatchBorderGeometry = factoryCache.GetGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY );
271   if( !(mNinePatchBorderGeometry) )
272   {
273     mNinePatchBorderGeometry = CreateGeometryBorder( Uint16Pair( 3, 3 ) );
274     factoryCache.SaveGeometry( RendererFactoryCache::NINE_PATCH_BORDER_GEOMETRY, mNinePatchBorderGeometry );
275   }
276
277   mNinePatchShader = factoryCache.GetShader( RendererFactoryCache::NINE_PATCH_SHADER );
278   if( !mNinePatchShader )
279   {
280     mNinePatchShader = Shader::New( VERTEX_SHADER_3X3, FRAGMENT_SHADER );
281     factoryCache.SaveShader( RendererFactoryCache::NINE_PATCH_SHADER, mNinePatchShader );
282   }
283
284   mImpl->mGeometry = mNinePatchGeometry;
285   mImpl->mShader = mNinePatchShader;
286
287   mImageUrl.clear();
288 }
289
290 void NPatchRenderer::SetImage( const std::string& imageUrl, bool borderOnly )
291 {
292   mBorderOnly = borderOnly;
293   mImage.Reset();
294   if( mImageUrl == imageUrl )
295   {
296     return;
297   }
298
299   mImageUrl = imageUrl;
300   NinePatchImage nPatch = NinePatchImage::New( mImageUrl );
301   InitialiseFromImage( nPatch );
302
303   if( mCroppedImage && mImpl->mIsOnStage )
304   {
305     ApplyImageToSampler();
306   }
307 }
308
309 void NPatchRenderer::SetImage( NinePatchImage image, bool borderOnly )
310 {
311   mBorderOnly = borderOnly;
312   mImageUrl.empty();
313   if( mImage == image )
314   {
315     return;
316   }
317
318   mImage = image;
319   InitialiseFromImage( mImage );
320
321   if( mCroppedImage && mImpl->mIsOnStage )
322   {
323     ApplyImageToSampler();
324   }
325 }
326
327 void NPatchRenderer::InitialiseFromImage( NinePatchImage nPatch )
328 {
329   mCroppedImage = nPatch.CreateCroppedBufferImage();
330   if( !mCroppedImage )
331   {
332     DALI_LOG_ERROR("'%s' specify a valid 9 patch image\n", mImageUrl.c_str() );
333     CreateErrorImage();
334     return;
335   }
336
337   mImageSize = ImageDimensions( mCroppedImage.GetWidth(), mCroppedImage.GetHeight() );
338
339   mStretchPixelsX = nPatch.GetStretchPixelsX();
340   mStretchPixelsY = nPatch.GetStretchPixelsY();
341
342   if( mStretchPixelsX.Size() > 0 && mStretchPixelsY.Size() > 0 )
343   {
344     //only 9 patch supported for now
345     mImpl->mGeometry = !mBorderOnly ? mNinePatchGeometry : mNinePatchBorderGeometry;
346     mImpl->mShader = mNinePatchShader;
347   }
348 }
349
350 void NPatchRenderer::CreateErrorImage()
351 {
352   mImageSize = ImageDimensions( 1, 1 );
353
354   BufferImage bufferImage = BufferImage::New( mImageSize.GetWidth(), mImageSize.GetHeight(), Pixel::RGBA8888 );
355   mCroppedImage = bufferImage;
356   PixelBuffer* pixbuf = bufferImage.GetBuffer();
357
358   for( size_t i = 0; i < mImageSize.GetWidth() * mImageSize.GetHeight() * 4u; )
359   {
360     pixbuf[ i++ ] = 0;
361     pixbuf[ i++ ] = 0;
362     pixbuf[ i++ ] = 0;
363     pixbuf[ i++ ] = 255;
364   }
365
366   mStretchPixelsX.Clear();
367   mStretchPixelsX.PushBack( Uint16Pair( 0, mImageSize.GetWidth() ) );
368   mStretchPixelsY.Clear();
369   mStretchPixelsY.PushBack( Uint16Pair( 0, mImageSize.GetHeight() ) );
370
371   mImpl->mGeometry = mNinePatchGeometry;
372   mImpl->mShader = mNinePatchShader;
373 }
374
375 void NPatchRenderer::ApplyImageToSampler()
376 {
377   Material material = mImpl->mRenderer.GetMaterial();
378   if( material )
379   {
380     Sampler sampler;
381     for( std::size_t i = 0; i < material.GetNumberOfSamplers(); ++i )
382     {
383       sampler = material.GetSamplerAt( i );
384       if( sampler.GetUniformName() == TEXTURE_UNIFORM_NAME )
385       {
386         sampler.SetImage( mCroppedImage );
387         break;
388       }
389     }
390     if( !sampler )
391     {
392       sampler = Sampler::New( mCroppedImage, TEXTURE_UNIFORM_NAME );
393       material.AddSampler( sampler );
394     }
395
396     if( mStretchPixelsX.Size() > 0 && mStretchPixelsY.Size() > 0 )
397     {
398       //only 9 patch supported for now
399       Uint16Pair stretchX = mStretchPixelsX[ 0 ];
400       Uint16Pair stretchY = mStretchPixelsY[ 0 ];
401
402       uint16_t stretchWidth = stretchX.GetY() - stretchX.GetX();
403       uint16_t stretchHeight = stretchY.GetY() - stretchY.GetX();
404
405       sampler.RegisterProperty( "uFixed[0]", Vector2::ZERO );
406       sampler.RegisterProperty( "uFixed[1]", Vector2( stretchX.GetX(), stretchY.GetX()) );
407       sampler.RegisterProperty( "uFixed[2]", Vector2( mImageSize.GetWidth() - stretchWidth, mImageSize.GetHeight() - stretchHeight ) );
408       sampler.RegisterProperty( "uStretchTotal", Vector2( stretchWidth, stretchHeight ) );
409     }
410   }
411 }
412
413 Geometry NPatchRenderer::CreateGeometry( Uint16Pair gridSize )
414 {
415   uint16_t gridWidth = gridSize.GetWidth();
416   uint16_t gridHeight = gridSize.GetHeight();
417
418   // Create vertices
419   Vector< Vector2 > vertices;
420   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
421
422   for( int y = 0; y < gridHeight + 1; ++y )
423   {
424     for( int x = 0; x < gridWidth + 1; ++x )
425     {
426       AddVertex( vertices, x, y );
427     }
428   }
429
430   // Create indices
431   //TODO: compare performance with triangle strip when Geometry supports it
432   Vector< unsigned int > indices;
433   indices.Reserve( gridWidth * gridHeight * 6 );
434
435   unsigned int rowIdx     = 0;
436   unsigned int nextRowIdx = gridWidth + 1;
437   for( int y = 0; y < gridHeight; ++y, ++nextRowIdx, ++rowIdx )
438   {
439     for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
440     {
441       AddQuadIndices( indices, rowIdx, nextRowIdx );
442     }
443   }
444
445   return GenerateGeometry( vertices, indices );
446 }
447
448 Geometry NPatchRenderer::CreateGeometryBorder( Uint16Pair gridSize )
449 {
450   uint16_t gridWidth = gridSize.GetWidth();
451   uint16_t gridHeight = gridSize.GetHeight();
452
453   // Create vertices
454   Vector< Vector2 > vertices;
455   vertices.Reserve( ( gridWidth + 1 ) * ( gridHeight + 1 ) );
456
457   //top
458   int y = 0;
459   for(; y < 2; ++y)
460   {
461     for( int x = 0; x < gridWidth + 1; ++x )
462     {
463       AddVertex( vertices, x, y );
464     }
465   }
466
467   for(; y < gridHeight - 1; ++y)
468   {
469     //left
470     AddVertex( vertices, 0, y );
471     AddVertex( vertices, 1, y );
472
473     //right
474     AddVertex( vertices, gridWidth - 1, y );
475     AddVertex( vertices, gridWidth, y );
476   }
477
478   //bottom
479   for(; y < gridHeight + 1; ++y)
480   {
481     for( int x = 0; x < gridWidth + 1; ++x )
482     {
483       AddVertex( vertices, x, y );
484     }
485   }
486
487   // Create indices
488   //TODO: compare performance with triangle strip when Geometry supports it
489   Vector< unsigned int > indices;
490   indices.Reserve( gridWidth * gridHeight * 6 );
491
492   //top
493   unsigned int rowIdx     = 0 ;
494   unsigned int nextRowIdx = gridWidth + 1;
495   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
496   {
497     AddQuadIndices( indices, rowIdx, nextRowIdx );
498   }
499
500   if(gridHeight > 2)
501   {
502     rowIdx     = gridWidth + 1;
503     nextRowIdx = ( gridWidth + 1 ) * 2;
504
505     unsigned increment = gridWidth - 1;
506     if(gridHeight > 3)
507     {
508       increment = 2;
509       //second row left
510       AddQuadIndices( indices, rowIdx, nextRowIdx );
511
512       rowIdx     = gridWidth * 2;
513       nextRowIdx = ( gridWidth + 1 ) * 2 + 2;
514       //second row right
515       AddQuadIndices( indices, rowIdx, nextRowIdx );
516
517       //left and right
518       rowIdx     = nextRowIdx - 2;
519       nextRowIdx = rowIdx + 4;
520       for(int y = 2; y < 2*(gridHeight - 3); ++y, rowIdx += 2, nextRowIdx += 2)
521       {
522         AddQuadIndices( indices, rowIdx, nextRowIdx );
523       }
524     }
525
526     //second row left
527     AddQuadIndices( indices, rowIdx, nextRowIdx );
528
529     rowIdx     += increment;
530     nextRowIdx += gridWidth - 1;
531     //second row right
532     AddQuadIndices( indices, rowIdx, nextRowIdx );
533   }
534
535   //bottom
536   rowIdx     = nextRowIdx - gridWidth + 1;
537   nextRowIdx = rowIdx + gridWidth + 1;
538   for( int x = 0; x < gridWidth; ++x, ++nextRowIdx, ++rowIdx )
539   {
540     AddQuadIndices( indices, rowIdx, nextRowIdx );
541   }
542
543   return GenerateGeometry( vertices, indices );
544 }
545
546 } // namespace Internal
547
548 } // namespace Toolkit
549
550 } // namespace Dali