sparkle-effect-example.cpp
17.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
/*
* Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <dali-toolkit/dali-toolkit.h>
#include <dali/dali.h>
#include <algorithm>
#include <chrono> // std::chrono::system_clock
#include <map>
#include <random> // std::default_random_engine
#include <sstream>
#include "shared/utility.h"
#include "sparkle-effect.h"
using namespace Dali;
using Dali::Toolkit::ImageView;
using namespace SparkleEffect;
namespace // unnamed namespace
{
//background image for normal status
const char* const CIRCLE_BACKGROUND_IMAGE(DEMO_IMAGE_DIR "sparkle_normal_background.png");
//particle shape image
const char* const PARTICLE_IMAGE(DEMO_IMAGE_DIR "sparkle_particle.png");
float EaseOutSquare(float progress)
{
return 1.0f - (1.0f - progress) * (1.0f - progress);
}
float CustomBounce(float progress)
{
float p = 1.f - progress;
p *= p;
return 17.68f * p * p * p * progress;
}
float Mix(const Vector2& range, float a)
{
return range.x * a + range.y * (1.f - a) - 0.001f;
}
const Vector4 BACKGROUND_COLOR(0.f, 0.f, 0.05f, 1.f);
} // unnamed namespace
// This example shows a sparkle particle effect
//
class SparkleEffectExample : public ConnectionTracker
{
public:
/**
* Create the SparkleEffectExample
* @param[in] application The DALi application instance
*/
SparkleEffectExample(Application& application)
: mApplication(application),
mAnimationIndex(0u),
mShaking(false)
{
mApplication.InitSignal().Connect(this, &SparkleEffectExample::OnInit);
}
private:
/**
* Initialize the SparkleEffectExample
* @param[in] application The DALi application instance
*/
void OnInit(Application& application)
{
Window window = application.GetWindow();
window.KeyEventSignal().Connect(this, &SparkleEffectExample::OnKeyEvent);
window.SetBackgroundColor(BACKGROUND_COLOR);
mCircleBackground = ImageView::New(CIRCLE_BACKGROUND_IMAGE);
mCircleBackground.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
mCircleBackground.SetProperty(Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
window.Add(mCircleBackground);
mEffect = SparkleEffect::New();
mMeshActor = CreateMeshActor();
window.Add(mMeshActor);
mMeshActor.SetProperty(Actor::Property::POSITION, ACTOR_POSITION);
mMeshActor.SetProperty(Actor::Property::SCALE, ACTOR_SCALE);
mTapDetector = TapGestureDetector::New();
mTapDetector.Attach(mCircleBackground);
mTapDetector.DetectedSignal().Connect(this, &SparkleEffectExample::OnTap);
mPanGestureDetector = PanGestureDetector::New();
mPanGestureDetector.DetectedSignal().Connect(this, &SparkleEffectExample::OnPan);
mPanGestureDetector.Attach(mCircleBackground);
PlayWanderAnimation(35.f);
}
/**
* Create the mesh representing all the particles
*/
Actor CreateMeshActor()
{
// shuffling to assign the color in random order
unsigned int* shuffleArray = new unsigned int[NUM_PARTICLE];
for(unsigned int i = 0; i < NUM_PARTICLE; i++)
{
shuffleArray[i] = i;
}
const unsigned int seed = std::chrono::system_clock::now().time_since_epoch().count();
std::shuffle(&shuffleArray[0], &shuffleArray[NUM_PARTICLE], std::default_random_engine(seed));
// Create vertices
std::vector<Vertex> vertices;
std::vector<unsigned short> faces;
for(unsigned int i = 0; i < NUM_PARTICLE; i++)
{
float colorIndex = GetColorIndex(shuffleArray[i]);
AddParticletoMesh(vertices, faces, PATHS[i], colorIndex);
}
delete[] shuffleArray;
Property::Map vertexFormat;
vertexFormat["aTexCoord"] = Property::VECTOR2;
vertexFormat["aParticlePath0"] = Property::VECTOR2;
vertexFormat["aParticlePath1"] = Property::VECTOR2;
vertexFormat["aParticlePath2"] = Property::VECTOR2;
vertexFormat["aParticlePath3"] = Property::VECTOR2;
vertexFormat["aParticlePath4"] = Property::VECTOR2;
vertexFormat["aParticlePath5"] = Property::VECTOR2;
VertexBuffer vertexBuffer = VertexBuffer::New(vertexFormat);
vertexBuffer.SetData(&vertices[0], vertices.size());
Geometry geometry = Geometry::New();
geometry.AddVertexBuffer(vertexBuffer);
geometry.SetIndexBuffer(&faces[0], faces.size());
geometry.SetType(Geometry::TRIANGLES);
Texture particleTexture = DemoHelper::LoadTexture(PARTICLE_IMAGE);
TextureSet textureSet = TextureSet::New();
textureSet.SetTexture(0u, particleTexture);
Renderer renderer = Renderer::New(geometry, mEffect);
renderer.SetTextures(textureSet);
Actor meshActor = Actor::New();
meshActor.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
meshActor.SetProperty(Actor::Property::SIZE, Vector2(1, 1));
meshActor.SetProperty(Actor::Property::UPDATE_AREA_HINT, ACTOR_UPDATE_AREA_HINT);
meshActor.AddRenderer(renderer);
return meshActor;
}
/**
* Defines a rule to assign particle with a color according to its index
*/
float GetColorIndex(unsigned int particleIndex)
{
unsigned int thereshold = 0;
for(unsigned int i = 0; i < NUM_COLOR; i++)
{
thereshold += PARTICLE_COLORS[i].numParticle;
if(particleIndex < thereshold)
{
return i + Mix(PARTICLE_COLORS[i].AlphaRange, static_cast<float>(thereshold - particleIndex) / PARTICLE_COLORS[i].numParticle);
}
}
return NUM_COLOR - 1;
}
/**
* All a particle to the mesh by giving the moving path and color index
*
* Two triangles per particle
* 0---------3
* |\ |
* | \ |
* | \ |
* | \|
* 1---------2
*
* The information we need to pass in through attribute include:
*
* path which contains 12 integer
* ---- passed in 6 Vector2 attributes
*
* color index, particle index and textureCoor( (0,0) or (1,0) or (0,1) or (1,1) )
* ---- package these info into texCood attribute as: (+-colorIndex, +-particleIndex)
*/
void AddParticletoMesh(std::vector<Vertex>& vertices,
std::vector<unsigned short>& faces,
MovingPath& movingPath,
float colorIndex)
{
unsigned int idx = vertices.size();
// store the path into position and normal, which would be decoded inside the shader
Vector2 particlePath0(movingPath[0], movingPath[1]);
Vector2 particlePath1(movingPath[2], movingPath[3]);
Vector2 particlePath2(movingPath[4], movingPath[5]);
Vector2 particlePath3(movingPath[6], movingPath[7]);
Vector2 particlePath4(movingPath[8], movingPath[9]);
Vector2 particlePath5(movingPath[10], movingPath[11]);
float particleIdx = static_cast<float>(idx / 4 + 1); // count from 1
float colorIdx = colorIndex + 1.f; // count from 1
vertices.push_back(Vertex{Vector2(-colorIdx, -particleIdx), particlePath0, particlePath1, particlePath2, particlePath3, particlePath4, particlePath5});
vertices.push_back(Vertex{Vector2(-colorIdx, particleIdx), particlePath0, particlePath1, particlePath2, particlePath3, particlePath4, particlePath5});
vertices.push_back(Vertex{Vector2(colorIdx, particleIdx), particlePath0, particlePath1, particlePath2, particlePath3, particlePath4, particlePath5});
vertices.push_back(Vertex{Vector2(colorIdx, -particleIdx), particlePath0, particlePath1, particlePath2, particlePath3, particlePath4, particlePath5});
faces.push_back(idx);
faces.push_back(idx + 1);
faces.push_back(idx + 2);
faces.push_back(idx);
faces.push_back(idx + 2);
faces.push_back(idx + 3);
}
/*
* Main key event handler
*/
void OnKeyEvent(const KeyEvent& event)
{
if(event.GetState() == KeyEvent::DOWN)
{
if(IsKey(event, Dali::DALI_KEY_ESCAPE) || IsKey(event, Dali::DALI_KEY_BACK))
{
mApplication.Quit();
}
}
}
/**
* Callback of the TapGesture
*/
void OnTap(Actor actor, const TapGesture& tap)
{
{
PlayTapAnimation(5.f, tap.GetLocalPoint());
}
}
/**
* Callback of the PanGesture
*/
void OnPan(Actor actor, const PanGesture& gesture)
{
if(gesture.GetState() == GestureState::FINISHED)
{
switch(mAnimationIndex)
{
case 0:
{
PlayParticleFadeAnimation(0, NUM_PARTICLE, 0.f, 3.f);
break;
}
case 1:
{
PlayBreakAnimation(2.0f);
break;
}
case 2:
{
PlayShakeAnimation(0.5f, 2.5f);
break;
}
default:
{
break;
}
}
mAnimationIndex = (mAnimationIndex + 1) % 3;
}
}
/**
* Animate the particle position to make them wandering on the screen with 'seemingly' random fade in/out
* @param[in] duration The duration for the particle to move a cycle on the path. the bigger this value the slower the floating movement.
* @param[in] looping Infinite playing or not
*/
void PlayWanderAnimation(float duration, bool looping = true)
{
Animation wanderAnimation = Animation::New(duration);
wanderAnimation.AnimateTo(Property(mEffect, PERCENTAGE_UNIFORM_NAME), 1.f);
wanderAnimation.SetLooping(looping); // infinite playing
wanderAnimation.Play();
}
/**
* Accelerate the particle moving speed
* @param[in] cycle How many extra cycles to move during the animation
* @param[in] duration The duration for the animation
*/
void PlayShakeAnimation(float cycle, float duration)
{
if(mShaking)
{
return;
}
DestroyAnimation(mTapAnimationAux);
float accelaration = GetFloatUniformValue(ACCELARATION_UNIFORM_NAME);
mEffect.SetProperty(mEffect.GetPropertyIndex(ACCELARATION_UNIFORM_NAME), accelaration - int(accelaration)); // Set the value as its fractional part
Animation shakeAnimation = Animation::New(duration);
shakeAnimation.AnimateBy(Property(mEffect, ACCELARATION_UNIFORM_NAME), cycle, AlphaFunction::EASE_OUT);
shakeAnimation.FinishedSignal().Connect(this, &SparkleEffectExample::OnShakeAnimationFinished);
shakeAnimation.Play();
mShaking = true;
}
/**
* Animate the particles to appear from center and spread all over around
* @param[in] duration The duration for the animation
*/
void PlayBreakAnimation(float duration)
{
if(GetFloatUniformValue(BREAK_UNIFORM_NAME) > 0.f)
{
return;
}
// Stop the fading / tap animation before the breaking
DestroyAnimation(mFadeAnimation);
mTapIndices.x = mTapIndices.y;
mEffect.SetProperty(mEffect.GetPropertyIndex(TAP_INDICES_UNIFORM_NAME), mTapIndices);
mEffect.SetProperty(mEffect.GetPropertyIndex(ACCELARATION_UNIFORM_NAME), 0.f);
// prepare the animation by setting the uniform to the required value
mEffect.SetProperty(mEffect.GetPropertyIndex(BREAK_UNIFORM_NAME), 1.f);
mMeshActor.SetProperty(Actor::Property::SCALE, 0.01f);
mEffect.SetProperty(mEffect.GetPropertyIndex("uScale"), 0.01f);
mMeshActor.SetProperty(Actor::Property::POSITION, Vector3(0.f, 0.f, 1.f));
Animation breakAnimation = Animation::New(duration * 1.5f);
breakAnimation.AnimateTo(Property(mMeshActor, Actor::Property::SCALE), Vector3(ACTOR_SCALE, ACTOR_SCALE, ACTOR_SCALE), EaseOutSquare);
breakAnimation.AnimateTo(Property(mEffect, "uScale"), ACTOR_SCALE, EaseOutSquare);
breakAnimation.AnimateTo(Property(mMeshActor, Actor::Property::POSITION), ACTOR_POSITION, EaseOutSquare);
breakAnimation.FinishedSignal().Connect(this, &SparkleEffectExample::OnBreakAnimationFinished);
float timeUnit = duration / (NUM_PARTICLE + 1) / (NUM_PARTICLE + 1);
std::ostringstream oss;
for(unsigned int i = 0; i < NUM_PARTICLE; i++)
{
oss.str("");
oss << OPACITY_UNIFORM_NAME << i << "]";
mEffect.SetProperty(mEffect.GetPropertyIndex(oss.str()), 0.01f);
float timeSlice = timeUnit * i * i;
breakAnimation.AnimateTo(Property(mEffect, oss.str()), 1.f, AlphaFunction::EASE_IN_OUT_SINE, TimePeriod(timeSlice * 0.5f, timeSlice));
}
breakAnimation.Play();
}
/**
* Animate the particle opacity
* Particles with index between startIndex ~ startIndex+numParticle-1 fade to the target opacity one after another
* @param[in] startIndex The index of the first particle
* @param[in] numParticle The number of particle to change opacity
* @param[in] targetValue The final opacity
* @param[in] duration The duration for the animation
*/
void PlayParticleFadeAnimation(unsigned int startIndex, unsigned int numParticle, float targetValue, float duration)
{
if(GetFloatUniformValue(BREAK_UNIFORM_NAME) > 0.f)
{
return;
}
// start the opacity animation one particle after another gradually
float timeSlice = duration / (numParticle + 1);
float fadeDuration = timeSlice > 0.5f ? timeSlice : 0.5f;
Animation fadeAnimation = Animation::New(duration + fadeDuration * 2.f);
std::ostringstream oss;
for(unsigned int i = startIndex; i < numParticle; i++)
{
if(i >= NUM_PARTICLE) break; // out of bound
oss.str("");
oss << OPACITY_UNIFORM_NAME << i << "]";
fadeAnimation.AnimateTo(Property(mEffect, oss.str()), targetValue, TimePeriod(timeSlice * i, fadeDuration * 2.f));
}
fadeAnimation.Play();
mFadeAnimation = fadeAnimation;
mFadeAnimation.FinishedSignal().Connect(this, &SparkleEffectExample::OnFadeAnimationFinished);
}
/**
* Push the particles to the edge all around the circle then bounce back
* @param[in] duration The duration for the animation
* @param[in] tapPoint The position of the tap point
*/
void PlayTapAnimation(float duration, const Vector2& tapPoint)
{
if(mTapIndices.y > mTapIndices.x && mTapAnimation.GetCurrentProgress() < 0.2f)
{
return;
}
Animation animation = Animation::New(duration);
int idx = int(mTapIndices.y) % MAXIMUM_ANIMATION_COUNT;
mTapIndices.y += 1.f;
std::ostringstream oss;
oss << TAP_OFFSET_UNIFORM_NAME << idx << "]";
mEffect.SetProperty(mEffect.GetPropertyIndex(oss.str()), 0.f);
animation.AnimateTo(Property(mEffect, oss.str()), 0.75f, CustomBounce);
oss.str("");
oss << TAP_POINT_UNIFORM_NAME << idx << "]";
mEffect.SetProperty(mEffect.GetPropertyIndex(oss.str()), tapPoint / ACTOR_SCALE);
mEffect.SetProperty(mEffect.GetPropertyIndex(TAP_INDICES_UNIFORM_NAME), mTapIndices);
if(!mShaking)
{
mTapAnimationAux = Animation::New(duration * 0.2f);
mTapAnimationAux.AnimateBy(Property(mEffect, ACCELARATION_UNIFORM_NAME), 0.15f, AlphaFunction::EASE_IN_OUT);
mTapAnimationAux.Play();
}
animation.Play();
mTapAnimationIndexPair[animation] = static_cast<int>(mTapIndices.y - 1.f);
animation.FinishedSignal().Connect(this, &SparkleEffectExample::OnTapAnimationFinished);
mTapAnimation = animation;
}
/**
* Callback of the animation finished signal
*/
void OnShakeAnimationFinished(Animation& animation)
{
mShaking = false;
}
/**
* Callback of the animation finished signal
*/
void OnFadeAnimationFinished(Animation& animation)
{
mFadeAnimation.Clear();
mFadeAnimation.Reset();
}
/**
* Callback of the animation finished signal
*/
void OnBreakAnimationFinished(Animation& animation)
{
mEffect.SetProperty(mEffect.GetPropertyIndex(BREAK_UNIFORM_NAME), 0.f);
}
/**
* Callback of the animation finished signal
*/
void OnTapAnimationFinished(Animation& animation)
{
if(mTapAnimationIndexPair[animation] == static_cast<int>(mTapIndices.x))
{
mTapIndices.x += 1.f;
if(mTapIndices.x >= mTapIndices.y)
{
mTapIndices = Vector2::ZERO;
}
mEffect.SetProperty(mEffect.GetPropertyIndex(TAP_INDICES_UNIFORM_NAME), mTapIndices);
}
mTapAnimationIndexPair.erase(animation);
if(mTapAnimationIndexPair.size() < 1 && mTapIndices != Vector2::ZERO)
{
mTapIndices = Vector2::ZERO;
mEffect.SetProperty(mEffect.GetPropertyIndex(TAP_INDICES_UNIFORM_NAME), mTapIndices);
}
animation.Clear();
animation.Reset();
}
/**
* Helper retrieve a uniform value from the Sparkle effect shader
* @param[in] uniformName The uniform
* @return The float value
*/
float GetFloatUniformValue(const std::string& uniformName)
{
float value;
mEffect.GetProperty(mEffect.GetPropertyIndex(uniformName)).Get(value);
return value;
}
/**
* Terminate the given animation
*/
void DestroyAnimation(Animation& animation)
{
if(animation)
{
animation.Clear();
animation.Reset();
}
}
private:
Application& mApplication;
Shader mEffect;
ImageView mCircleBackground;
Actor mMeshActor;
PanGestureDetector mPanGestureDetector;
TapGestureDetector mTapDetector;
Animation mFadeAnimation;
Animation mTapAnimation;
Animation mTapAnimationAux;
Vector2 mTapIndices;
unsigned int mAnimationIndex;
bool mShaking;
std::map<Animation, int> mTapAnimationIndexPair;
};
int DALI_EXPORT_API main(int argc, char** argv)
{
Application application = Application::New(&argc, &argv);
SparkleEffectExample theApp(application);
application.MainLoop();
return 0;
}