2 * Copyright (c) 2020 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 <dali-toolkit/dali-toolkit.h>
22 #include "renderer-stencil-shaders.h"
23 #include "shared/view.h"
24 #include "shared/utility.h"
33 // Application constants:
34 const char * const APPLICATION_TITLE( "Renderer Stencil API Demo" );
35 const char * const BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-gradient.jpg" );
38 const char * const CUBE_TEXTURE( DEMO_IMAGE_DIR "people-medium-1.jpg" );
39 const char * const FLOOR_TEXTURE( DEMO_IMAGE_DIR "wood.png" );
41 // Scale dimensions: These values are relative to the stage size. EG. width = 0.32f * stageSize.
42 const float CUBE_WIDTH_SCALE( 0.32f ); ///< The width (and height + depth) of the main and reflection cubes.
43 const Vector2 FLOOR_DIMENSION_SCALE( 0.67f, 0.017f ); ///< The width and height of the floor object.
45 // Configurable animation characteristics:
46 const float ANIMATION_ROTATION_DURATION( 10.0f ); ///< Time in seconds to rotate the scene 360 degrees around Y.
47 const float ANIMATION_BOUNCE_TOTAL_TIME( 1.6f ); ///< Time in seconds to perform 1 full bounce animation cycle.
48 const float ANIMATION_BOUNCE_DEFORMATION_TIME( 0.4f ); ///< Time in seconds that the cube deformation animation will occur for (on contact with the floor).
49 const float ANIMATION_BOUNCE_DEFORMATION_PERCENT( 20.0f ); ///< Percentage (of the cube's size) to deform the cube by (on contact with floor).
50 const float ANIMATION_BOUNCE_HEIGHT_PERCENT( 40.0f ); ///< Percentage (of the cube's size) to bounce up in to the air by.
52 // Base colors for the objects:
53 const Vector4 TEXT_COLOR( 1.0f, 1.0f, 1.0f, 1.0f ); ///< White.
54 const Vector4 CUBE_COLOR( 1.0f, 1.0f, 1.0f, 1.0f ); ///< White.
55 const Vector4 FLOOR_COLOR( 1.0f, 1.0f, 1.0f, 1.0f ); ///< White.
56 const Vector4 REFLECTION_COLOR( 0.6f, 0.6f, 0.6f, 0.6f ); ///< Note that alpha is not 1.0f, to make the blend more photo-realistic.
58 // We need to control the draw order as we are controlling both the stencil and depth buffer per renderer.
59 const int DEPTH_INDEX_GRANULARITY( 10000 ); ///< This value is the gap in depth-index in-between each renderer.
61 } // Anonymous namespace
64 * @brief This example shows how to manipulate stencil and depth buffer properties within the Renderer API.
66 class RendererStencilExample : public ConnectionTracker
72 * @param[in] application The DALi application object
74 RendererStencilExample( Application& application )
75 : mApplication( application )
77 // Connect to the Application's Init signal.
78 mApplication.InitSignal().Connect( this, &RendererStencilExample::Create );
82 * @brief Destructor (non-virtual).
84 ~RendererStencilExample()
91 * @brief Enum to facilitate more readable use of the cube array.
95 MAIN_CUBE, ///< The main cube that bounces above the floor object.
96 REFLECTION_CUBE ///< The reflected cube object.
100 * @brief Struct to store the position, normal and texture coordinates of a single vertex.
102 struct TexturedVertex
106 Vector2 textureCoord;
110 * @brief This is the main scene setup method for this demo.
111 * This is called via the Init signal which is received once (only) during the Application lifetime.
112 * @param[in] application The DALi application object
114 void Create( Application& application )
116 Stage stage = Stage::GetCurrent();
118 // Use a gradient visual to render the background gradient.
119 Toolkit::Control background = Dali::Toolkit::Control::New();
120 background.SetProperty( Actor::Property::ANCHOR_POINT, Dali::AnchorPoint::CENTER );
121 background.SetProperty( Actor::Property::PARENT_ORIGIN, Dali::ParentOrigin::CENTER );
122 background.SetResizePolicy( Dali::ResizePolicy::FILL_TO_PARENT, Dali::Dimension::ALL_DIMENSIONS );
124 // Set up the background gradient.
125 Property::Array stopOffsets;
126 stopOffsets.PushBack( 0.0f );
127 stopOffsets.PushBack( 1.0f );
128 Property::Array stopColors;
129 stopColors.PushBack( Vector4( 0.17f, 0.24f, 0.35f, 1.0f ) ); // Dark, medium saturated blue ( top of screen)
130 stopColors.PushBack( Vector4( 0.45f, 0.70f, 0.80f, 1.0f ) ); // Medium bright, pastel blue (bottom of screen)
131 const float percentageStageHeight = stage.GetSize().height * 0.7f;
133 background.SetProperty( Toolkit::Control::Property::BACKGROUND, Dali::Property::Map()
134 .Add( Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::GRADIENT )
135 .Add( Toolkit::GradientVisual::Property::STOP_OFFSET, stopOffsets )
136 .Add( Toolkit::GradientVisual::Property::STOP_COLOR, stopColors )
137 .Add( Toolkit::GradientVisual::Property::START_POSITION, Vector2( 0.0f, -percentageStageHeight ) )
138 .Add( Toolkit::GradientVisual::Property::END_POSITION, Vector2( 0.0f, percentageStageHeight ) )
139 .Add( Toolkit::GradientVisual::Property::UNITS, Toolkit::GradientVisual::Units::USER_SPACE ) );
141 stage.Add( background );
143 // Create a TextLabel for the application title.
144 Toolkit::TextLabel label = Toolkit::TextLabel::New( APPLICATION_TITLE );
145 label.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
146 // Set the parent origin to a small percentage below the top (so the demo will scale for different resolutions).
147 label.SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.03f, 0.5f ) );
148 label.SetProperty( Toolkit::TextLabel::Property::HORIZONTAL_ALIGNMENT, "CENTER" );
149 label.SetProperty( Toolkit::TextLabel::Property::VERTICAL_ALIGNMENT, "CENTER" );
150 label.SetProperty( Toolkit::TextLabel::Property::TEXT_COLOR, TEXT_COLOR );
153 // Layer to hold the 3D scene.
154 Layer layer = Layer::New();
155 layer.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
156 // Set the parent origin to a small percentage below the center (so the demo will scale for different resolutions).
157 layer.SetProperty( Actor::Property::PARENT_ORIGIN, Vector3( 0.5f, 0.58f, 0.5f ) );
158 layer.SetProperty( Layer::Property::BEHAVIOR, Layer::LAYER_UI );
159 layer.SetProperty( Layer::Property::DEPTH_TEST, true );
163 // Make the demo scalable with different resolutions by basing
164 // the cube size on a percentage of the stage size.
165 float scaleSize( std::min( stage.GetSize().width, stage.GetSize().height ) );
166 float cubeWidth( scaleSize * CUBE_WIDTH_SCALE );
167 Vector3 cubeSize( cubeWidth, cubeWidth, cubeWidth );
168 // Create the geometry for the cube, and the texture.
169 Geometry cubeGeometry = CreateCubeVertices( Vector3::ONE, false );
170 TextureSet cubeTextureSet = CreateTextureSet( CUBE_TEXTURE );
171 // Create the cube object and add it.
172 // Note: The cube is anchored around its base for animation purposes, so the position can be zero.
173 mCubes[ MAIN_CUBE ] = CreateMainCubeObject( cubeGeometry, cubeSize, cubeTextureSet );
174 layer.Add( mCubes[ MAIN_CUBE ] );
177 float floorWidth( scaleSize * FLOOR_DIMENSION_SCALE.x );
178 Vector3 floorSize( floorWidth, scaleSize * FLOOR_DIMENSION_SCALE.y, floorWidth );
179 // Create the floor object using the cube geometry with a new size, and add it.
180 Actor floorObject( CreateFloorObject( cubeGeometry, floorSize ) );
181 layer.Add( floorObject );
184 Vector3 planeSize( floorWidth, floorWidth, 0.0f );
185 // Create the stencil plane object, and add it.
186 Actor stencilPlaneObject( CreateStencilPlaneObject( planeSize ) );
187 layer.Add( stencilPlaneObject );
190 // Create the reflection cube object and add it.
191 // Note: The cube is anchored around its base for animation purposes, so the position can be zero.
192 mCubes[ REFLECTION_CUBE ] = CreateReflectionCubeObject( cubeSize, cubeTextureSet );
193 layer.Add( mCubes[ REFLECTION_CUBE ] );
195 // Rotate the layer so we can see some of the top of the cube for a more 3D effect.
196 layer.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -24.0f ), Degree( 0.0f ), Degree( 0.0f ) ) );
198 // Set up the rotation on the Y axis.
199 mRotationAnimation = Animation::New( ANIMATION_ROTATION_DURATION );
200 float fullRotation = 360.0f;
201 mRotationAnimation.AnimateBy( Property( mCubes[ MAIN_CUBE ], Actor::Property::ORIENTATION ),
202 Quaternion( Degree( 0.0f ), Degree( fullRotation ), Degree( 0.0f ) ) );
203 mRotationAnimation.AnimateBy( Property( floorObject, Actor::Property::ORIENTATION ),
204 Quaternion( Degree( 0.0f ), Degree( fullRotation ), Degree( 0.0f ) ) );
205 // Note the stencil is pre-rotated by 90 degrees on X, so we rotate relatively on its Z axis for an equivalent Y rotation.
206 mRotationAnimation.AnimateBy( Property( stencilPlaneObject, Actor::Property::ORIENTATION ),
207 Quaternion( Degree( 0.0f ), Degree( 0.0f ), Degree( fullRotation ) ) );
208 mRotationAnimation.AnimateBy( Property( mCubes[ REFLECTION_CUBE ], Actor::Property::ORIENTATION ),
209 Quaternion( Degree( 0.0f ), Degree( fullRotation ), Degree( 0.0f ) ) );
210 mRotationAnimation.SetLooping( true );
212 // Set up the cube bouncing animation.
213 float totalTime = ANIMATION_BOUNCE_TOTAL_TIME;
214 float deformationTime = ANIMATION_BOUNCE_DEFORMATION_TIME;
215 // Percentage based amounts allows the bounce and deformation to scale for different resolution screens.
216 float deformationAmount = ANIMATION_BOUNCE_DEFORMATION_PERCENT / 100.0f;
217 float heightChange = ( cubeSize.y * ANIMATION_BOUNCE_HEIGHT_PERCENT ) / 100.0f;
219 // Animation pre-calculations:
220 float halfTime = totalTime / 2.0f;
221 float halfDeformationTime = deformationTime / 2.0f;
223 // First position the cubes at the top of the animation cycle.
224 mCubes[ MAIN_CUBE ].SetProperty( Actor::Property::POSITION_Y, -heightChange );
225 mCubes[ REFLECTION_CUBE ].SetProperty( Actor::Property::POSITION_Y, heightChange );
227 mBounceAnimation = Animation::New( totalTime );
229 // The animations for the main and reflected cubes are almost identical, so we combine the code to do both.
230 for( int cube = 0; cube < 2; ++cube )
232 // If iterating on the reflection cube, adjust the heightChange variable so the below code can be reused.
235 heightChange = -heightChange;
238 // 1st TimePeriod: Start moving down with increasing speed, until it is time to distort the cube due to impact.
239 mBounceAnimation.AnimateBy( Property( mCubes[ cube ], Actor::Property::POSITION_Y ), heightChange, AlphaFunction::EASE_IN_SQUARE, TimePeriod( 0.0f, halfTime - halfDeformationTime ) );
241 // 2nd TimePeriod: The cube is touching the floor, start deforming it - then un-deform it again.
242 mBounceAnimation.AnimateBy( Property( mCubes[ cube ], Actor::Property::SCALE_X ), deformationAmount, AlphaFunction::BOUNCE, TimePeriod( halfTime - halfDeformationTime, deformationTime ) );
243 mBounceAnimation.AnimateBy( Property( mCubes[ cube ], Actor::Property::SCALE_Z ), deformationAmount, AlphaFunction::BOUNCE, TimePeriod( halfTime - halfDeformationTime, deformationTime ) );
244 mBounceAnimation.AnimateBy( Property( mCubes[ cube ], Actor::Property::SCALE_Y ), -deformationAmount, AlphaFunction::BOUNCE, TimePeriod( halfTime - halfDeformationTime, deformationTime ) );
246 // 3rd TimePeriod: Start moving up with decreasing speed, until at the apex of the animation.
247 mBounceAnimation.AnimateBy( Property( mCubes[ cube ], Actor::Property::POSITION_Y ), -heightChange, AlphaFunction::EASE_OUT_SQUARE, TimePeriod( halfTime + halfDeformationTime, halfTime - halfDeformationTime ) );
250 mBounceAnimation.SetLooping( true );
252 // Start the animations.
253 mRotationAnimation.Play();
254 mBounceAnimation.Play();
256 // Respond to a click anywhere on the stage
257 stage.GetRootLayer().TouchSignal().Connect( this, &RendererStencilExample::OnTouch );
258 // Connect signals to allow Back and Escape to exit.
259 stage.KeyEventSignal().Connect( this, &RendererStencilExample::OnKeyEvent );
264 // Methods to setup each component of the 3D scene:
267 * @brief Creates the Main cube object.
268 * This creates the renderer from existing geometry (as the cubes geometry is shared).
269 * The texture is set and all relevant renderer properties are set-up.
270 * @param[in] geometry Pre-calculated cube geometry
271 * @param[in] size The desired cube size
272 * @param[in] textureSet A pre-existing TextureSet with a texture set up, to be applied to the cube
273 * @return An actor set-up containing the main cube object
275 Actor CreateMainCubeObject( Geometry& geometry, Vector3 size, TextureSet& textureSet )
277 Toolkit::Control container = Toolkit::Control::New();
278 container.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::BOTTOM_CENTER );
279 container.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::BOTTOM_CENTER );
280 container.SetProperty( Actor::Property::SIZE, Vector2( size ) );
281 container.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
283 // Create a renderer from the geometry and add the texture.
284 Renderer renderer = CreateRenderer( geometry, size, true, CUBE_COLOR );
285 renderer.SetTextures( textureSet );
287 // Setup the renderer properties:
288 // We are writing to the color buffer & culling back faces (no stencil is used for the main cube).
289 renderer.SetProperty( Renderer::Property::RENDER_MODE, RenderMode::COLOR );
290 renderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK );
292 // We do need to write to the depth buffer as other objects need to appear underneath this cube.
293 renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::ON );
294 // We do not need to test the depth buffer as we are culling the back faces.
295 renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::OFF );
297 // This object must be rendered 1st.
298 renderer.SetProperty( Renderer::Property::DEPTH_INDEX, 0 * DEPTH_INDEX_GRANULARITY );
300 container.AddRenderer( renderer );
305 * @brief Creates the Floor object.
306 * This creates the renderer from existing geometry (as the cube geometry can be re-used).
307 * The texture is created and set and all relevant renderer properties are set-up.
308 * @param[in] geometry Pre-calculated cube geometry
309 * @param[in] size The desired floor size
310 * @return An actor set-up containing the floor object
312 Actor CreateFloorObject( Geometry& geometry, Vector3 size )
314 Toolkit::Control container = Toolkit::Control::New();
315 container.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
316 container.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
317 container.SetProperty( Actor::Property::SIZE, Vector2( size ) );
318 container.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
320 // Create a renderer from the geometry and add the texture.
321 TextureSet planeTextureSet = CreateTextureSet( FLOOR_TEXTURE );
322 Renderer renderer = CreateRenderer( geometry, size, true, FLOOR_COLOR );
323 renderer.SetTextures( planeTextureSet );
325 // Setup the renderer properties:
326 // We are writing to the color buffer & culling back faces as we are NOT doing depth write (no stencil is used for the floor).
327 renderer.SetProperty( Renderer::Property::RENDER_MODE, RenderMode::COLOR );
328 renderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK );
330 // We do not write to the depth buffer as its not needed.
331 renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::OFF );
332 // We do need to test the depth buffer as we need the floor to be underneath the cube.
333 renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
335 // This object must be rendered 2nd.
336 renderer.SetProperty( Renderer::Property::DEPTH_INDEX, 1 * DEPTH_INDEX_GRANULARITY );
338 container.AddRenderer( renderer );
343 * @brief Creates the Stencil-Plane object.
344 * This is places on the floor object to allow the reflection to be drawn on to the floor.
345 * This creates the geometry and renderer.
346 * All relevant renderer properties are set-up.
347 * @param[in] size The desired plane size
348 * @return An actor set-up containing the stencil-plane object
350 Actor CreateStencilPlaneObject( Vector3 size )
352 Toolkit::Control container = Toolkit::Control::New();
353 container.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER );
354 container.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER );
355 container.SetProperty( Actor::Property::SIZE, Vector2( size ) );
356 container.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
358 // We rotate the plane as the geometry is created flat in X & Y. We want it to span X & Z axis.
359 container.SetProperty( Actor::Property::ORIENTATION, Quaternion( Degree( -90.0f ), Degree( 0.0f ), Degree( 0.0f ) ) );
361 // Create geometry for a flat plane.
362 Geometry planeGeometry = CreatePlaneVertices( Vector2::ONE );
363 // Create a renderer from the geometry.
364 Renderer renderer = CreateRenderer( planeGeometry, size, false, Vector4::ONE );
366 // Setup the renderer properties:
367 // The stencil plane is only for stencilling.
368 renderer.SetProperty( Renderer::Property::RENDER_MODE, RenderMode::STENCIL );
370 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION, StencilFunction::ALWAYS );
371 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION_REFERENCE, 1 );
372 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION_MASK, 0xFF );
373 renderer.SetProperty( Renderer::Property::STENCIL_OPERATION_ON_FAIL, StencilOperation::KEEP );
374 renderer.SetProperty( Renderer::Property::STENCIL_OPERATION_ON_Z_FAIL, StencilOperation::KEEP );
375 renderer.SetProperty( Renderer::Property::STENCIL_OPERATION_ON_Z_PASS, StencilOperation::REPLACE );
376 renderer.SetProperty( Renderer::Property::STENCIL_MASK, 0xFF );
378 // We don't want to write to the depth buffer, as this would block the reflection being drawn.
379 renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::OFF );
380 // We test the depth buffer as we want the stencil to only exist underneath the cube.
381 renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
383 // This object must be rendered 3rd.
384 renderer.SetProperty( Renderer::Property::DEPTH_INDEX, 2 * DEPTH_INDEX_GRANULARITY );
386 container.AddRenderer( renderer );
391 * @brief Creates the Reflection cube object.
392 * This creates new geometry (as the texture UVs are different to the main cube).
393 * The renderer is then created.
394 * The texture is set and all relevant renderer properties are set-up.
395 * @param[in] size The desired cube size
396 * @param[in] textureSet A pre-existing TextureSet with a texture set up, to be applied to the cube
397 * @return An actor set-up containing the reflection cube object
399 Actor CreateReflectionCubeObject( Vector3 size, TextureSet& textureSet )
401 Toolkit::Control container = Toolkit::Control::New();
402 container.SetProperty( Actor::Property::ANCHOR_POINT, AnchorPoint::TOP_CENTER );
403 container.SetProperty( Actor::Property::PARENT_ORIGIN, ParentOrigin::TOP_CENTER );
404 container.SetProperty( Actor::Property::SIZE, Vector2( size ) );
405 container.SetResizePolicy( ResizePolicy::FIXED, Dimension::ALL_DIMENSIONS );
407 // Create the cube geometry of unity size.
408 // The "true" specifies we want the texture UVs flipped vertically as this is the reflection cube.
409 Geometry reflectedCubeGeometry = CreateCubeVertices( Vector3::ONE, true );
410 // Create a renderer from the geometry and add the texture.
411 Renderer renderer = CreateRenderer( reflectedCubeGeometry, size, true, REFLECTION_COLOR );
412 renderer.SetTextures( textureSet );
414 // Setup the renderer properties:
415 // Write to color buffer so reflection is visible.
416 // Also enable the stencil buffer, as we will be testing against it to only draw to areas within the stencil.
417 renderer.SetProperty( Renderer::Property::RENDER_MODE, RenderMode::COLOR_STENCIL );
418 // We cull to skip drawing the back faces.
419 renderer.SetProperty( Renderer::Property::FACE_CULLING_MODE, FaceCullingMode::BACK );
421 // We use blending to blend the reflection with the floor texture.
422 renderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
423 renderer.SetProperty( Renderer::Property::BLEND_EQUATION_RGB, BlendEquation::ADD );
424 renderer.SetProperty( Renderer::Property::BLEND_EQUATION_ALPHA, BlendEquation::ADD );
425 renderer.SetProperty( Renderer::Property::BLEND_FACTOR_DEST_RGB, BlendFactor::ONE );
427 // Enable stencil. Here we only draw to areas within the stencil.
428 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION, StencilFunction::EQUAL );
429 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION_REFERENCE, 1 );
430 renderer.SetProperty( Renderer::Property::STENCIL_FUNCTION_MASK, 0xff );
431 // Don't write to the stencil.
432 renderer.SetProperty( Renderer::Property::STENCIL_MASK, 0x00 );
434 // We don't need to write to the depth buffer, as we are culling.
435 renderer.SetProperty( Renderer::Property::DEPTH_WRITE_MODE, DepthWriteMode::OFF );
436 // We need to test the depth buffer as we need the reflection to be underneath the cube.
437 renderer.SetProperty( Renderer::Property::DEPTH_TEST_MODE, DepthTestMode::ON );
439 // This object must be rendered last.
440 renderer.SetProperty( Renderer::Property::DEPTH_INDEX, 3 * DEPTH_INDEX_GRANULARITY );
442 container.AddRenderer( renderer );
449 * @brief Creates a geometry object from vertices and indices.
450 * @param[in] vertices The object vertices
451 * @param[in] indices The object indices
452 * @return A geometry object
454 Geometry CreateTexturedGeometry( Vector<TexturedVertex>& vertices, Vector<unsigned short>& indices )
457 Property::Map vertexFormat;
458 vertexFormat[POSITION] = Property::VECTOR3;
459 vertexFormat[NORMAL] = Property::VECTOR3;
460 vertexFormat[TEXTURE] = Property::VECTOR2;
462 PropertyBuffer surfaceVertices = PropertyBuffer::New( vertexFormat );
463 surfaceVertices.SetData( &vertices[0u], vertices.Size() );
465 Geometry geometry = Geometry::New();
466 geometry.AddVertexBuffer( surfaceVertices );
468 // Indices for triangle formulation
469 geometry.SetIndexBuffer( &indices[0u], indices.Size() );
474 * @brief Creates a renderer from a geometry object.
475 * @param[in] geometry The geometry to use
476 * @param[in] dimensions The dimensions (will be passed in to the shader)
477 * @param[in] textured Set to true to use the texture versions of the shaders
478 * @param[in] color The base color for the renderer
479 * @return A renderer object
481 Renderer CreateRenderer( Geometry geometry, Vector3 dimensions, bool textured, Vector4 color )
483 Stage stage = Stage::GetCurrent();
488 shader = Shader::New( VERTEX_SHADER_TEXTURED, FRAGMENT_SHADER_TEXTURED );
492 shader = Shader::New( VERTEX_SHADER, FRAGMENT_SHADER );
495 // Here we modify the light position based on half the stage size as a pre-calculation step.
496 // This avoids the work having to be done in the shader.
497 shader.RegisterProperty( LIGHT_POSITION_UNIFORM_NAME, Vector3( -stage.GetSize().width / 2.0f, -stage.GetSize().width / 2.0f, 1000.0f ) );
498 shader.RegisterProperty( COLOR_UNIFORM_NAME, color );
499 shader.RegisterProperty( OBJECT_DIMENSIONS_UNIFORM_NAME, dimensions );
501 return Renderer::New( geometry, shader );
505 * @brief Helper method to create a TextureSet from an image URL.
506 * @param[in] url An image URL
507 * @return A TextureSet object
509 TextureSet CreateTextureSet( const char* url )
511 TextureSet textureSet = TextureSet::New();
515 Texture texture = DemoHelper::LoadTexture( url );
518 textureSet.SetTexture( 0u, texture );
525 // Geometry Creation:
528 * @brief Creates a geometry object for a flat plane.
529 * The plane is oriented in X & Y axis (Z is 0).
530 * @param[in] dimensions The desired plane dimensions
531 * @return A Geometry object
533 Geometry CreatePlaneVertices( Vector2 dimensions )
535 Vector<TexturedVertex> vertices;
536 Vector<unsigned short> indices;
537 vertices.Resize( 4u );
538 indices.Resize( 6u );
540 float scaledX = 0.5f * dimensions.x;
541 float scaledY = 0.5f * dimensions.y;
543 vertices[0].position = Vector3( -scaledX, -scaledY, 0.0f );
544 vertices[0].textureCoord = Vector2( 0.0, 0.0f );
545 vertices[1].position = Vector3( scaledX, -scaledY, 0.0f );
546 vertices[1].textureCoord = Vector2( 1.0, 0.0f );
547 vertices[2].position = Vector3( scaledX, scaledY, 0.0f );
548 vertices[2].textureCoord = Vector2( 1.0, 1.0f );
549 vertices[3].position = Vector3( -scaledX, scaledY, 0.0f );
550 vertices[3].textureCoord = Vector2( 0.0, 1.0f );
552 // All vertices have the same normal.
553 for( int i = 0; i < 4; ++i )
555 vertices[i].normal = Vector3( 0.0f, 0.0f, -1.0f );
565 // Use the helper method to create the geometry object.
566 return CreateTexturedGeometry( vertices, indices );
570 * @brief Creates a geometry object for a cube (or cuboid).
571 * @param[in] dimensions The desired cube dimensions
572 * @param[in] reflectVerticalUVs Set to True to force the UVs to be vertically flipped
573 * @return A Geometry object
575 Geometry CreateCubeVertices( Vector3 dimensions, bool reflectVerticalUVs )
577 Vector<TexturedVertex> vertices;
578 Vector<unsigned short> indices;
579 int vertexIndex = 0u; // Tracks progress through vertices.
580 float scaledX = 0.5f * dimensions.x;
581 float scaledY = 0.5f * dimensions.y;
582 float scaledZ = 0.5f * dimensions.z;
583 float verticalTextureCoord = reflectVerticalUVs ? 0.0f : 1.0f;
585 vertices.Resize( 4u * 6u ); // 4 vertices x 6 faces
587 Vector<Vector3> positions; // Stores vertex positions, which are shared between vertexes at the same position but with a different normal.
588 positions.Resize( 8u );
589 Vector<Vector3> normals; // Stores normals, which are shared between vertexes of the same face.
590 normals.Resize( 6u );
592 positions[0] = Vector3( -scaledX, scaledY, -scaledZ );
593 positions[1] = Vector3( scaledX, scaledY, -scaledZ );
594 positions[2] = Vector3( scaledX, scaledY, scaledZ );
595 positions[3] = Vector3( -scaledX, scaledY, scaledZ );
596 positions[4] = Vector3( -scaledX, -scaledY, -scaledZ );
597 positions[5] = Vector3( scaledX, -scaledY, -scaledZ );
598 positions[6] = Vector3( scaledX, -scaledY, scaledZ );
599 positions[7] = Vector3( -scaledX, -scaledY, scaledZ );
601 normals[0] = Vector3( 0, 1, 0 );
602 normals[1] = Vector3( 0, 0, -1 );
603 normals[2] = Vector3( 1, 0, 0 );
604 normals[3] = Vector3( 0, 0, 1 );
605 normals[4] = Vector3( -1, 0, 0 );
606 normals[5] = Vector3( 0, -1, 0 );
608 // Top face, upward normals.
609 for( int i = 0; i < 4; ++i, ++vertexIndex )
611 vertices[vertexIndex].position = positions[i];
612 vertices[vertexIndex].normal = normals[0];
613 // The below logic forms the correct U/V pairs for a quad when "i" goes from 0 to 3.
614 vertices[vertexIndex].textureCoord = Vector2( ( i == 1 || i == 2 ) ? 1.0f : 0.0f, ( i == 2 || i == 3 ) ? 1.0f : 0.0f );
617 // Top face, outward normals.
618 for( int i = 0; i < 4; ++i, vertexIndex += 2 )
620 vertices[vertexIndex].position = positions[i];
621 vertices[vertexIndex].normal = normals[i + 1];
625 // End, so loop around.
626 vertices[vertexIndex + 1].position = positions[0];
630 vertices[vertexIndex + 1].position = positions[i + 1];
632 vertices[vertexIndex + 1].normal = normals[i + 1];
634 vertices[vertexIndex].textureCoord = Vector2( 0.0f, verticalTextureCoord );
635 vertices[vertexIndex+1].textureCoord = Vector2( 1.0f, verticalTextureCoord );
638 // Flip the vertical texture coord for the UV values of the bottom points.
639 verticalTextureCoord = 1.0f - verticalTextureCoord;
641 // Bottom face, outward normals.
642 for( int i = 0; i < 4; ++i, vertexIndex += 2 )
644 vertices[vertexIndex].position = positions[i + 4];
645 vertices[vertexIndex].normal = normals[i + 1];
649 // End, so loop around.
650 vertices[vertexIndex + 1].position = positions[4];
654 vertices[vertexIndex + 1].position = positions[i + 5];
656 vertices[vertexIndex + 1].normal = normals[i + 1];
658 vertices[vertexIndex].textureCoord = Vector2( 0.0f, verticalTextureCoord );
659 vertices[vertexIndex+1].textureCoord = Vector2( 1.0f, verticalTextureCoord );
662 // Bottom face, downward normals.
663 for( int i = 0; i < 4; ++i, ++vertexIndex )
665 // Reverse positions for bottom face to keep triangles clockwise (for culling).
666 vertices[vertexIndex].position = positions[ 7 - i ];
667 vertices[vertexIndex].normal = normals[5];
668 // The below logic forms the correct U/V pairs for a quad when "i" goes from 0 to 3.
669 vertices[vertexIndex].textureCoord = Vector2( ( i == 1 || i == 2 ) ? 1.0f : 0.0f, ( i == 2 || i == 3 ) ? 1.0f : 0.0f );
672 // Create cube indices.
673 int triangleIndex = 0u; //Track progress through indices.
674 indices.Resize( 3u * 12u ); // 3 points x 12 triangles.
677 indices[triangleIndex] = 0;
678 indices[triangleIndex + 1] = 1;
679 indices[triangleIndex + 2] = 2;
680 indices[triangleIndex + 3] = 2;
681 indices[triangleIndex + 4] = 3;
682 indices[triangleIndex + 5] = 0;
685 int topFaceStart = 4u;
686 int bottomFaceStart = topFaceStart + 8u;
689 for( int i = 0; i < 8; i += 2, triangleIndex += 6 )
691 indices[triangleIndex ] = i + topFaceStart;
692 indices[triangleIndex + 1] = i + bottomFaceStart + 1;
693 indices[triangleIndex + 2] = i + topFaceStart + 1;
694 indices[triangleIndex + 3] = i + topFaceStart;
695 indices[triangleIndex + 4] = i + bottomFaceStart;
696 indices[triangleIndex + 5] = i + bottomFaceStart + 1;
700 indices[triangleIndex] = 20;
701 indices[triangleIndex + 1] = 21;
702 indices[triangleIndex + 2] = 22;
703 indices[triangleIndex + 3] = 22;
704 indices[triangleIndex + 4] = 23;
705 indices[triangleIndex + 5] = 20;
707 // Use the helper method to create the geometry object.
708 return CreateTexturedGeometry( vertices, indices );
714 * @brief OnTouch signal handler.
715 * @param[in] actor The actor that has been touched
716 * @param[in] touch The touch information
717 * @return True if the event has been handled
719 bool OnTouch( Actor actor, const TouchData& touch )
721 // Quit the application.
727 * @brief OnKeyEvent signal handler.
728 * @param[in] event The key event information
730 void OnKeyEvent( const KeyEvent& event )
732 if( event.state == KeyEvent::Down )
734 if ( IsKey( event, Dali::DALI_KEY_ESCAPE ) || IsKey( event, Dali::DALI_KEY_BACK ) )
745 Application& mApplication; ///< The DALi application object
746 Toolkit::Control mView; ///< The view used to show the background
748 Animation mRotationAnimation; ///< The animation to spin the cube & floor
749 Animation mBounceAnimation; ///< The animation to bounce the cube
750 Actor mCubes[2]; ///< The cube object containers
753 int DALI_EXPORT_API main( int argc, char **argv )
755 Application application = Application::New( &argc, &argv );
756 RendererStencilExample example( application );
757 application.MainLoop();