2 * Copyright (c) 2018 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.
21 #include <cstdint> // uint32_t, uint16_t etc
23 #include <dali/public-api/rendering/renderer.h>
24 #include <dali/public-api/rendering/texture.h>
25 #include <dali/public-api/rendering/texture-set.h>
26 #include <dali/public-api/rendering/frame-buffer.h>
27 #include <dali/public-api/math/random.h>
30 #include "shared/utility.h" // DemoHelper::LoadTexture
34 namespace // unnamed namespace for constants
37 const char * const BACKGROUND_IMAGE( DEMO_IMAGE_DIR "background-2.jpg" );
39 // number of metaballs
40 constexpr uint32_t METABALL_NUMBER = 6;
43 * Vertex shader code for metaball
45 const char* const METABALL_VERTEX_SHADER = DALI_COMPOSE_SHADER (
46 attribute mediump vec2 aPosition;\n
47 attribute mediump vec2 aTexture;\n
48 uniform mediump mat4 uMvpMatrix;\n
49 uniform mediump vec3 uSize;\n
50 uniform lowp vec4 uColor;\n
51 varying mediump vec2 vTexCoord;\n
55 vTexCoord = aTexture;\n
56 mediump vec4 vertexPosition = vec4(aPosition.x, aPosition.y, 0.0, 1.0);\n
57 gl_Position = uMvpMatrix * vertexPosition;\n
62 * Fragment shader code for metaball
64 const char* const METABALL_FRAG_SHADER = DALI_COMPOSE_SHADER (
65 precision mediump float;\n
66 varying vec2 vTexCoord;\n
67 uniform vec2 uPositionMetaball;\n
68 uniform vec2 uPositionVar;\n
69 uniform vec2 uGravityVector;\n
70 uniform float uRadius;\n
71 uniform float uRadiusVar;\n
74 vec2 adjustedCoords = vTexCoord * 2.0 - 1.0;\n
75 vec2 finalMetaballPosition = uPositionMetaball + uGravityVector + uPositionVar;\n
77 float finalRadius = uRadius + uRadiusVar;\n
78 vec2 distanceVec = adjustedCoords - finalMetaballPosition;\n
79 float result = dot(distanceVec, distanceVec);\n
80 float color = inversesqrt(result) * finalRadius;\n
82 gl_FragColor = vec4(color,color,color,1.0);\n
87 * Fragment shader code for metaball and background composition with refraction effect
89 const char* const REFRACTION_FRAG_SHADER = DALI_COMPOSE_SHADER (
90 precision highp float;\n
91 varying vec2 vTexCoord;\n
92 uniform sampler2D sTexture;\n
93 uniform sampler2D sEffect;\n
94 uniform vec2 uPositionMetaball;\n
98 vec3 normal = vec3(0.0,0.0,1.0);\n
99 vec2 fakePos = vec2(0.0,0.0);\n
100 vec3 color = vec3(1.0, 1.0, 1.0);
103 vec4 metaColor = texture2D(sEffect, vTexCoord);\n
105 vec2 adjustedCoords = vTexCoord.xy * vec2(2.0) - vec2(1.0);\n
106 fakePos = adjustedCoords.xy - vec2(uPositionMetaball.x, -uPositionMetaball.y);
107 float len = length(fakePos) + 0.01;\n
108 vec3 colorPos = vec3(0,0,1);
110 if (metaColor.r > 0.85)\n
112 zoomCoords = ((vTexCoord - 0.5) * 0.9);\n
113 zoomCoords = zoomCoords + 0.5;\n
115 float interpNormal = mix(0.7, 1.0, (metaColor.r - 0.85) * 4.);\n
116 normal.xyz = vec3(fakePos.x * (1.0 - interpNormal) / len, fakePos.y * (1.0 - interpNormal) / len, interpNormal);\n
117 normal.xyz = normalize(normal.xyz);\n
118 color = vec3(0.65, 1.0, 0);\n
119 colorPos = vec3(fakePos.x,fakePos.y,0);
121 else if (metaColor.r > 0.75)\n
123 float interpolation = mix(0.9, 1.15, (0.85 - metaColor.r) * 10.0);\n
124 zoomCoords = ((vTexCoord - 0.5) * interpolation);\n
125 zoomCoords = zoomCoords + 0.5;\n
127 float interpNormal = mix(0.7, 0.0, (0.85 - metaColor.r) * 10.0);\n
128 normal.xyz = vec3(fakePos.x * (1.0 - interpNormal) / len, fakePos.y * (1.0 - interpNormal) / len, interpNormal);\n
129 normal.xyz = normalize(normal.xyz);\n
130 color = vec3(0.65, 1.0, 0);\n
131 colorPos = vec3(fakePos.x,fakePos.y,0);
135 zoomCoords = vTexCoord;\n
136 normal = vec3(0,0,0);\n
140 vec3 lightPosition = vec3(-750.0,-1000.0,2000.0);\n
141 vec3 vertex = vec3(adjustedCoords.x,adjustedCoords.y,0.0);\n
143 vec3 vecToLight = normalize( lightPosition - vertex );\n
145 float lightDiffuse = dot( vecToLight, normal );\n
146 lightDiffuse = max(0.0,lightDiffuse);\n
147 lightDiffuse = lightDiffuse * 0.5 + 0.5;
149 vec3 vertexToEye = vec3(0,0,1) - vertex;\n
150 vertexToEye = normalize(vertexToEye);
151 vec3 lightReflect = normalize(reflect(-vecToLight, normal));\n
152 float specularFactor = max(0.0,dot(vertexToEye, lightReflect));\n
153 specularFactor = pow(specularFactor, 32.0) * 0.7;
155 vec4 texColor = texture2D(sTexture, zoomCoords);\n
156 gl_FragColor.rgb = texColor.rgb * ambient + color.rgb * texColor.rgb * lightDiffuse + vec3(specularFactor);\n
157 gl_FragColor.a = 1.0;
162 * Metadata for each ball
172 Property::Index positionIndex;
173 Property::Index positionVarIndex;
176 } // unnamed namespace
179 * Demo using Metaballs
181 * When the metaball is clicked it explodes to smaller balls
183 class MetaballExplosionController : public ConnectionTracker
191 MetaballExplosionController( Application& application );
196 virtual ~MetaballExplosionController();
199 * Creates the metaballs and initializes the scene
201 void Create( Application& app );
204 * Touch event handler to center metaballs at touch position
205 * and start explosion animation on release
207 bool OnTouch( Actor actor, const TouchData& touch );
210 * Key event handler to quit application on escape or back key
212 void OnKeyEvent(const KeyEvent& event);
216 Application& mApplication;
219 Texture mBackgroundTexture;
220 FrameBuffer mMetaballFBO;
223 MetaballInfo mMetaballs[METABALL_NUMBER];
225 Property::Index mPositionIndex;
226 Actor mCompositionActor;
229 Vector2 mCurrentTouchPosition;
230 Vector2 mMetaballPosVariation;
231 Vector2 mMetaballPosVariationFrom;
232 Vector2 mMetaballPosVariationTo;
233 Vector2 mMetaballCenter;
236 Animation mPositionVarAnimation[METABALL_NUMBER];
238 uint32_t mDispersion;
239 Animation mDispersionAnimation[METABALL_NUMBER];
241 Timer mTimerDispersion;
243 float mTimeMultiplier;
245 // Private helper functions
248 * Create a mesh data with the geometry for the metaball rendering
249 * @param aspectMappedTexture whether texture coords should be mapped based on aspect ratio
251 Geometry CreateGeometry( bool aspectMappedTexture = true );
254 * Create a actors and renderers for the metaballs
256 void CreateMetaballActors();
259 * Create the render task and FBO to render the metaballs into a texture
261 void CreateMetaballImage();
264 * Create the the final composition
266 void CreateComposition();
269 * Function to create animations for the small variations of position inside the metaball
271 void CreateAnimations();
274 * Function to reset metaball state
276 void ResetMetaballs( bool resetAnims );
279 * Function to create disperse each of the ball that compose the metaball when exploding
281 void DisperseBallAnimation( uint32_t ball );
284 * Function to make metaballs come back to reset position
286 void LaunchResetMetaballPosition( Animation& source );
289 * Function to set things at the end of the animation
291 void EndDisperseAnimation( Animation& source );
294 * Function to init dispersion of the metaballs one by one using a timer
295 * (so not all the balls begin moving at the same time)
297 bool OnTimerDispersionTick();
300 * Function to set the actual position of the metaballs when the user clicks the screen
302 void SetPositionToMetaballs( const Vector2& metaballCenter );
309 MetaballExplosionController::MetaballExplosionController( Application& application )
310 : mApplication( application ),
312 mBackgroundTexture(),
318 mCurrentTouchPosition(),
319 mMetaballPosVariation(),
320 mMetaballPosVariationFrom(),
321 mMetaballPosVariationTo(),
323 mPositionVarAnimation(),
325 mDispersionAnimation(),
327 mTimeMultiplier( 1.0f )
329 // Connect to the Application's Init signal
330 mApplication.InitSignal().Connect( this, &MetaballExplosionController::Create );
333 MetaballExplosionController::~MetaballExplosionController()
335 // Nothing to do here;
338 void MetaballExplosionController::Create( Application& app )
340 Stage stage = Stage::GetCurrent();
342 stage.KeyEventSignal().Connect( this, &MetaballExplosionController::OnKeyEvent );
344 mScreenSize = stage.GetSize();
346 mTimeMultiplier = 1.0f;
348 stage.SetBackgroundColor(Color::BLACK);
350 // Load background texture
351 mBackgroundTexture = DemoHelper::LoadTexture( BACKGROUND_IMAGE );
353 srand( static_cast<uint32_t>( time(0) ) );
355 //Create internal data
356 CreateMetaballActors();
357 CreateMetaballImage();
363 mTimerDispersion = Timer::New( 150 );
364 mTimerDispersion.TickSignal().Connect( this, &MetaballExplosionController::OnTimerDispersionTick );
366 // Connect the callback to the touch signal on the mesh actor
367 stage.GetRootLayer().TouchSignal().Connect( this, &MetaballExplosionController::OnTouch );
370 Geometry MetaballExplosionController::CreateGeometry( bool aspectMappedTexture )
372 const float aspect = mScreenSize.y / mScreenSize.x;
374 // Create vertices and specify their color
375 const float xsize = mScreenSize.x * 0.5;
377 // Create the meshdata for the metaballs
378 struct VertexPosition { Vector2 position; };
379 struct VertexTexture { Vector2 texture; };
381 VertexPosition vertices[] =
383 { Vector2( -xsize, -xsize * aspect ) },
384 { Vector2( xsize, -xsize * aspect ) },
385 { Vector2( -xsize, xsize * aspect ) },
386 { Vector2( xsize, xsize * aspect ) }
389 const float textureAspect = (aspectMappedTexture) ? aspect : 1.0f;
390 VertexTexture textures[] =
392 { Vector2( 0.0f, 0.0f ) },
393 { Vector2( 1.0f, 0.0f ) },
394 { Vector2( 0.0f, 1.0f * textureAspect ) },
395 { Vector2( 1.0f, 1.0f * textureAspect ) }
398 uint32_t numberOfVertices = sizeof(vertices)/sizeof(VertexPosition);
401 Property::Map positionVertexFormat;
402 positionVertexFormat["aPosition"] = Property::VECTOR2;
403 PropertyBuffer positionVertices = PropertyBuffer::New( positionVertexFormat );
404 positionVertices.SetData( vertices, numberOfVertices );
407 Property::Map textureVertexFormat;
408 textureVertexFormat["aTexture"] = Property::VECTOR2;
409 PropertyBuffer textureVertices = PropertyBuffer::New( textureVertexFormat );
410 textureVertices.SetData( textures, numberOfVertices );
413 const uint16_t indices[] = { 0, 3, 1, 0, 2, 3 };
415 // Create the geometry object
416 Geometry texturedQuadGeometry = Geometry::New();
417 texturedQuadGeometry.AddVertexBuffer( positionVertices );
418 texturedQuadGeometry.AddVertexBuffer( textureVertices );
420 texturedQuadGeometry.SetIndexBuffer ( &indices[0], sizeof( indices )/ sizeof( indices[0] ) );
422 return texturedQuadGeometry;
425 void MetaballExplosionController::CreateMetaballActors()
427 // Create the shader for the metaballs, tell DALi that shader modifies geometry so we dont need to set a meaningless size
428 Shader shader = Shader::New( METABALL_VERTEX_SHADER, METABALL_FRAG_SHADER, Shader::Hint::MODIFIES_GEOMETRY );
430 Geometry metaballGeom = CreateGeometry();
431 // Reuse same renderer for each actor
432 Renderer renderer = Renderer::New( metaballGeom, shader );
433 renderer.SetProperty( Renderer::Property::BLEND_MODE, BlendMode::ON );
434 renderer.SetProperty( Renderer::Property::BLEND_FACTOR_SRC_RGB, BlendFactor::ONE );
435 renderer.SetProperty( Renderer::Property::BLEND_FACTOR_DEST_RGB, BlendFactor::ONE );
436 renderer.SetProperty( Renderer::Property::BLEND_FACTOR_SRC_ALPHA, BlendFactor::ONE );
437 renderer.SetProperty( Renderer::Property::BLEND_FACTOR_DEST_ALPHA, BlendFactor::ONE );
439 //Initialization of each of the metaballs
440 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
442 mMetaballs[i].position = Vector2(0.0f, 0.0f);
443 mMetaballs[i].radius = mMetaballs[i].initRadius = Random::Range(0.05f,0.07f);
445 mMetaballs[i].actor = Actor::New( );
446 mMetaballs[i].actor.SetName( "Metaball" );
447 mMetaballs[i].actor.SetScale( 1.0f );
448 mMetaballs[i].actor.SetParentOrigin( ParentOrigin::CENTER );
449 mMetaballs[i].actor.AddRenderer( renderer );
451 mMetaballs[i].positionIndex = mMetaballs[i].actor.RegisterProperty( "uPositionMetaball", mMetaballs[i].position );
453 mMetaballs[i].positionVarIndex = mMetaballs[i].actor.RegisterProperty( "uPositionVar", Vector2(0.f,0.f) );
455 mMetaballs[i].actor.RegisterProperty( "uGravityVector", Vector2(Random::Range(-0.2,0.2),Random::Range(-0.2,0.2)) );
456 mMetaballs[i].actor.RegisterProperty( "uRadius", mMetaballs[i].radius );
457 mMetaballs[i].actor.RegisterProperty( "uRadiusVar", 0.f );
461 mMetaballRoot = Actor::New();
462 mMetaballRoot.SetParentOrigin( ParentOrigin::CENTER );
463 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
465 mMetaballRoot.Add( mMetaballs[i].actor );
470 void MetaballExplosionController::CreateMetaballImage()
472 // Create an FBO and a render task to create to render the metaballs with a fragment shader
473 Stage stage = Stage::GetCurrent();
475 mMetaballFBO = FrameBuffer::New( mScreenSize.x, mScreenSize.y );
477 stage.Add(mMetaballRoot);
479 // Create the render task used to render the metaballs
480 RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
481 RenderTask task = taskList.CreateTask();
482 task.SetRefreshRate( RenderTask::REFRESH_ALWAYS );
483 task.SetSourceActor( mMetaballRoot );
484 task.SetExclusive( true );
485 task.SetClearColor( Color::BLACK );
486 task.SetClearEnabled( true );
487 task.SetFrameBuffer( mMetaballFBO );
490 void MetaballExplosionController::CreateComposition()
493 Shader shader = Shader::New( METABALL_VERTEX_SHADER, REFRACTION_FRAG_SHADER );
495 // Create new texture set
496 auto textureSet = TextureSet::New();
497 textureSet.SetTexture( 0u, mBackgroundTexture );
498 textureSet.SetTexture( 1u, mMetaballFBO.GetColorTexture() );
501 Geometry metaballGeom = CreateGeometry( false );
503 Renderer mRenderer = Renderer::New( metaballGeom, shader );
504 mRenderer.SetTextures( textureSet );
507 mCompositionActor = Actor::New( );
508 mCompositionActor.SetParentOrigin(ParentOrigin::CENTER);
509 mCompositionActor.SetPosition(Vector3(0.0f, 0.0f, 0.0f));
510 mCompositionActor.SetSize(mScreenSize.x, mScreenSize.y);
511 mCompositionActor.AddRenderer( mRenderer );
513 Vector2 metaballCenter(0.0,0);
514 metaballCenter.x = metaballCenter.x * 0.5;
515 metaballCenter.y = metaballCenter.y * 0.5;
516 mPositionIndex = mCompositionActor.RegisterProperty( "uPositionMetaball", metaballCenter );
518 SetPositionToMetaballs( metaballCenter );
520 mCompositionActor.SetSize(mScreenSize.x, mScreenSize.y);
522 Stage stage = Stage::GetCurrent();
523 stage.Add( mCompositionActor );
526 void MetaballExplosionController::CreateAnimations()
530 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
532 KeyFrames keySinCosVariation = KeyFrames::New();
533 Vector2 sinCosVariation( 0,0 );
535 direction.x = Random::Range( -100.f,100.f );
536 direction.y = Random::Range( -100.f,100.f );
538 direction.Normalize();
541 for( uint32_t j = 0; j < 360; j++ )
543 sinCosVariation.x = sinf( j * Math::PI/180.f ) * direction.x;
544 sinCosVariation.y = cosf( j * Math::PI/180.f ) * direction.y;
546 keySinCosVariation.Add( key, sinCosVariation );
549 mPositionVarAnimation[i] = Animation::New( 3.f );
550 mPositionVarAnimation[i].AnimateBetween( Property( mMetaballs[i].actor, mMetaballs[i].positionVarIndex ), keySinCosVariation );
551 mPositionVarAnimation[i].SetLooping( true );
552 mPositionVarAnimation[i].Play();
556 void MetaballExplosionController::ResetMetaballs( bool resetAnims )
558 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
560 if( mDispersionAnimation[i] )
562 mDispersionAnimation[i].Clear();
565 mMetaballs[i].position = Vector2( 0.0f, 0.0f );
566 mMetaballs[i].actor.SetProperty( mMetaballs[i].positionIndex, mMetaballs[i].position );
568 mTimerDispersion.Stop();
571 mCompositionActor.SetProperty( mPositionIndex, Vector2(0,0) );
574 void MetaballExplosionController::DisperseBallAnimation( uint32_t ball )
577 position.x = Random::Range(-1.5f,1.5f);
578 position.y = Random::Range(-1.5f,1.5f);
580 mDispersionAnimation[ball] = Animation::New(2.0f * mTimeMultiplier);
581 mDispersionAnimation[ball].AnimateTo( Property(mMetaballs[ball].actor, mMetaballs[ball].positionIndex), position);
582 mDispersionAnimation[ball].Play();
584 if( ball == METABALL_NUMBER - 1 )
586 mDispersionAnimation[ball].FinishedSignal().Connect( this, &MetaballExplosionController::LaunchResetMetaballPosition );
590 void MetaballExplosionController::LaunchResetMetaballPosition( Animation& source )
592 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
594 mDispersionAnimation[i] = Animation::New( 1.5f + i * 0.25f * mTimeMultiplier );
595 mDispersionAnimation[i].AnimateTo(Property( mMetaballs[i].actor, mMetaballs[i].positionIndex), Vector2(0,0) );
596 mDispersionAnimation[i].Play();
598 if( i == METABALL_NUMBER - 1 )
600 mDispersionAnimation[i].FinishedSignal().Connect( this, &MetaballExplosionController::EndDisperseAnimation );
605 void MetaballExplosionController::EndDisperseAnimation( Animation& source )
607 mCompositionActor.SetProperty( mPositionIndex, Vector2(0,0) );
610 bool MetaballExplosionController::OnTimerDispersionTick()
612 if( mDispersion < METABALL_NUMBER )
614 DisperseBallAnimation( mDispersion );
620 void MetaballExplosionController::SetPositionToMetaballs( const Vector2& metaballCenter )
622 //We set the position for the metaballs based on click position
623 for( uint32_t i = 0; i < METABALL_NUMBER; i++ )
625 mMetaballs[i].position = metaballCenter;
626 mMetaballs[i].actor.SetProperty( mMetaballs[i].positionIndex, mMetaballs[i].position );
629 mCompositionActor.SetProperty( mPositionIndex, metaballCenter );
632 bool MetaballExplosionController::OnTouch( Actor actor, const TouchData& touch )
634 float aspectR = mScreenSize.y / mScreenSize.x;
636 switch( touch.GetState( 0 ) )
638 case PointState::DOWN:
640 ResetMetaballs(true);
642 const Vector2 screen = touch.GetScreenPosition( 0 );
643 Vector2 metaballCenter = Vector2( (screen.x / mScreenSize.x) - 0.5f, (aspectR * (mScreenSize.y - screen.y) / mScreenSize.y) - 0.5f ) * 2.0f;
644 SetPositionToMetaballs(metaballCenter);
648 case PointState::MOTION:
650 const Vector2 screen = touch.GetScreenPosition( 0 );
651 Vector2 metaballCenter = Vector2( (screen.x / mScreenSize.x) - 0.5f, (aspectR * (mScreenSize.y - screen.y) / mScreenSize.y) - 0.5f ) * 2.0f;
652 SetPositionToMetaballs(metaballCenter);
656 case PointState::LEAVE:
657 case PointState::INTERRUPTED:
659 mTimerDispersion.Start();
668 void MetaballExplosionController::OnKeyEvent(const KeyEvent& event)
670 if(event.state == KeyEvent::Down)
672 if( IsKey( event, Dali::DALI_KEY_ESCAPE) || IsKey( event, Dali::DALI_KEY_BACK) )
682 int32_t DALI_EXPORT_API main( int argc, char **argv )
684 Application application = Application::New( &argc, &argv );
686 MetaballExplosionController test( application );
688 application.MainLoop();