Merge "Added more test cases for ScrollView" into tizen
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / devel-api / shader-effects / motion-blur-effect.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 <dali-toolkit/devel-api/shader-effects/motion-blur-effect.h>
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/animation/constraint.h>
23 #include <dali/public-api/animation/constraints.h>
24
25 namespace Dali
26 {
27
28 namespace Toolkit
29 {
30
31 namespace
32 {
33
34 const std::string MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME( "uBlurTexCoordScale" );
35 const std::string MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME( "uGeometryStretchFactor" );
36 const std::string MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME( "uSpeedScalingFactor" );
37 const std::string MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME( "uObjectFadeStart" );
38 const std::string MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME( "uObjectFadeEnd" );
39 const std::string MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME( "uAlphaScale" );
40 const std::string MOTION_BLUR_NUM_SAMPLES_NAME( "uNumSamples" );
41 const std::string MOTION_BLUR_RECIP_NUM_SAMPLES_NAME( "uRecipNumSamples" );
42 const std::string MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME( "uRecipNumSamplesMinusOne" );
43 const std::string MOTION_BLUR_MODEL_LASTFRAME( "uModelLastFrame" );  ///< Matrix
44
45 ////////////////////////////////////////////////////
46 //
47 // Motion blur shader / actor tweaking parameters
48 //
49
50 const unsigned int MOTION_BLUR_NUM_SAMPLES = 8;
51
52 // half width and half height respectively of actor, corresponding to values in vertex attribute stream
53 // TODO: Note that these values work for normal image actor (verts +/- 0.5) but a grid or a nine square seems to have verts in pixel space (e.g. 256,256). Need to fix this somehow,
54 // either in Dali or by passing uniforms which we can use to 'normalise' the verts in the vertex shader
55 const Vector2 MOTION_BLUR_ACTOR_VERTEX( 0.5f, 0.5f );
56
57 const float MOTION_BLUR_TEXCOORD_SCALE = 0.125f;             // stretch texture reads along velocity vector, larger number means reads spaced further apart
58 const float MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR = 0.05f; // scaling factor for how much to stretch actor geom as it moves
59 const float MOTION_BLUR_SPEED_SCALING_FACTOR = 0.5f;         // scales the speed, producing a number affecting how much the actor blurs & fades at the edges
60
61 const Vector2 MOTION_BLUR_OBJECT_FADE_END( MOTION_BLUR_ACTOR_VERTEX );             // distance from center at which actor fully fades to zero alpha
62 const Vector2 MOTION_BLUR_OBJECT_FADE_START( MOTION_BLUR_OBJECT_FADE_END * 0.5f ); // distance from center at which actor start to fade from full alpha
63
64 const float MOTION_BLUR_ALPHA_SCALE = 0.75f; // global scaler applied to actor alpha as it is blurred + moving
65
66 } // namespace
67
68
69 MotionBlurEffect::MotionBlurEffect()
70 {
71 }
72
73 //Call the Parent copy constructor to add reference to the implementation for this object
74 MotionBlurEffect::MotionBlurEffect( ShaderEffect handle )
75 :ShaderEffect( handle )
76 {
77 }
78
79 MotionBlurEffect::~MotionBlurEffect()
80 {
81 }
82
83 MotionBlurEffect MotionBlurEffect::Apply( RenderableActor renderable )
84 {
85   MotionBlurEffect newEffect = New( MOTION_BLUR_NUM_SAMPLES );
86   renderable.SetShaderEffect( newEffect );
87
88   Dali::Property::Index uModelProperty = newEffect.GetPropertyIndex( MOTION_BLUR_MODEL_LASTFRAME );
89
90   Constraint constraint = Constraint::New<Matrix>( newEffect, uModelProperty, EqualToConstraint() );
91   constraint.AddSource( Source( renderable, Actor::Property::WORLD_MATRIX ) );
92
93   // and set up constraint.
94   constraint.Apply();
95   return newEffect;
96 }
97
98 MotionBlurEffect MotionBlurEffect::New()
99 {
100   return New( MOTION_BLUR_NUM_SAMPLES );
101 }
102
103 MotionBlurEffect MotionBlurEffect::New( unsigned int numBlurSamples )
104 {
105   // Dali vertexSource prefix for reference:
106   // precision highp float;
107   // attribute vec3  aPosition;
108   // attribute vec2  aTexCoord;
109   // uniform   mat4  uMvpMatrix;
110   // uniform   mat4  uModelView;
111   // uniform   mat3  uNormalMatrix;
112   // uniform   mat4  uProjection;
113   // uniform   vec4  uColor;
114   // varying   vec2  vTexCoord;
115   std::string vertexSource;
116   vertexSource =
117     "precision mediump float;\n"
118     "uniform mat4 uModelLastFrame;\n"
119     "uniform float uTimeDelta;\n"
120
121     "uniform float uGeometryStretchFactor;\n"
122     "uniform float uSpeedScalingFactor;\n"
123
124     // outputs
125     "varying vec2 vModelSpaceCenterToPos;\n"
126     "varying vec2 vScreenSpaceVelocityVector;\n"
127     "varying float vSpeed;\n"
128
129     "void main()\n"
130     "{\n"
131     // get view space position of vertex this frame and last frame
132     " vec4 vertex = vec4(aPosition, 1.0);\n"
133     " vec4 viewSpaceVertex = uModelView * vertex;\n"
134     " vec4 viewSpaceVertexLastFrame = (uViewMatrix * uModelLastFrame) * vertex;\n"
135     " float reciprocalTimeDelta = 1.0 / ((uTimeDelta > 0.0) ? uTimeDelta : 0.01);\n"
136
137     // work out vertex's last movement in view space
138     " vec3 viewSpacePosDelta = viewSpaceVertex.xyz - viewSpaceVertexLastFrame.xyz;\n"
139
140     // get clip space position of vertex this frame and last frame
141     " vec4 clipSpaceVertex = uMvpMatrix * vertex;\n"
142     " vec4 clipSpaceVertexLastFrame = uProjection * viewSpaceVertexLastFrame;\n"
143
144     // decide how much this vertex is 'trailing', i.e. at the back of the object relative to its direction of motion. We do this
145     // by assuming the objects model space origin is at its center and taking the dot product of the vector from center to vertex with the motion direction
146     " float t = 0.0;\n"
147     " float posDeltaLength = length(viewSpacePosDelta);\n"
148     " if(posDeltaLength > 0.001)\n" // avoid div by 0 if object has barely moved
149     " {\n"
150     "   vec4 viewSpaceCenterToPos = uModelView * vec4(aPosition, 0.0);\n"
151     "   float centerToVertexDist = length(viewSpaceCenterToPos);\n"
152     "   if(centerToVertexDist > 0.001)\n" // avoid div by 0 if object has vertex at model space origin
153     "   {\n"
154     "     vec3 viewSpacePosDeltaNormalised = viewSpacePosDelta / posDeltaLength;\n"
155     "     vec3 viewSpaceCenterToPosNormalised = viewSpaceCenterToPos.xyz / centerToVertexDist;\n"
156     "     t = (dot(viewSpacePosDeltaNormalised, viewSpaceCenterToPosNormalised) * 0.5 ) + 0.5;\n" // scale and bias from [-1..1] to [0..1]
157     "   }\n"
158     " }\n"
159     // output vertex position lerped with its last position, based on how much it is trailing,
160     // this stretches the geom back along where it has just been, giving a warping effect
161     // Note: we must take account of time delta to convert position delta into a velocity, so changes are smooth (take into account frame time correctly)
162     " gl_Position = mix(clipSpaceVertexLastFrame, clipSpaceVertex, t * uGeometryStretchFactor * reciprocalTimeDelta);\n"
163
164     // work out vertex's last movement in normalised device coordinates [-1..1] space, i.e. perspective divide
165     " vec2 ndcVertex = clipSpaceVertex.xy / clipSpaceVertex.w;\n"
166     " vec2 ndcVertexLastFrame = clipSpaceVertexLastFrame.xy / clipSpaceVertexLastFrame.w;\n"
167     // scale and bias so that a value of 1.0 corresponds to screen size (NDC is [-1..1] = 2)
168     " vScreenSpaceVelocityVector = ((ndcVertex - ndcVertexLastFrame) * 0.5 * reciprocalTimeDelta);\n"
169     " vScreenSpaceVelocityVector.y = -vScreenSpaceVelocityVector.y;\n" // TODO negated due to y being inverted in our coordinate system?
170     // calculate a scaling factor proportional to velocity, which we can use to tweak how things look
171     " vSpeed = length(vScreenSpaceVelocityVector) * uSpeedScalingFactor;\n"
172     " vSpeed = clamp(vSpeed, 0.0, 1.0);\n"
173
174     // provide fragment shader with vector from center of object to pixel (assumes the objects model space origin is at its center and verts have same z)
175     " vModelSpaceCenterToPos = aPosition.xy;\n"
176
177     " vTexCoord = aTexCoord;\n"
178     "}\n";
179
180
181   // Dali fragmentSource prefix for reference:
182   // precision highp     float;
183   // uniform   sampler2D sTexture;
184   // uniform   sampler2D sEffect;
185   // uniform   vec4      uColor;
186   // varying   vec2      vTexCoord;
187   std::string fragmentSource;
188   fragmentSource =
189     "precision mediump float;\n"
190     "uniform vec2 uObjectFadeStart;\n"
191     "uniform vec2 uObjectFadeEnd;\n"
192     "uniform float uAlphaScale;\n"
193     "uniform float uBlurTexCoordScale;\n"
194     "uniform float uNumSamples;\n"
195     "uniform float uRecipNumSamples;\n"
196     "uniform float uRecipNumSamplesMinusOne;\n"
197     // inputs
198     "varying vec2 vModelSpaceCenterToPos;\n"
199     "varying vec2 vScreenSpaceVelocityVector;\n"
200     "varying float vSpeed;\n"
201
202     "void main()\n"
203     "{\n"
204     // calculate an alpha value that will fade the object towards its extremities, we need this to avoid an unsightly hard edge between color values of
205     // the blurred object and the unblurred background. Use smoothstep also to hide any hard edges (discontinuities) in rate of change of this alpha gradient
206     " vec2 centerToPixel = abs(vModelSpaceCenterToPos);\n"
207     " vec2 fadeToEdges = smoothstep(0.0, 1.0, 1.0 - ((centerToPixel - uObjectFadeStart) / (uObjectFadeEnd - uObjectFadeStart)));\n"
208     " float fadeToEdgesScale = fadeToEdges.x * fadeToEdges.y * uAlphaScale;\n" // apply global scaler
209     " fadeToEdgesScale = mix(1.0, fadeToEdgesScale, vSpeed);\n" // fade proportional to speed, so opaque when at rest
210
211     // scale velocity vector by user requirements
212     " vec2 velocity = vScreenSpaceVelocityVector * uBlurTexCoordScale;\n"
213
214     // standard actor texel
215     " vec4 colActor = texture2D(sTexture, vTexCoord);\n"
216
217     // blurred actor - gather texture samples from the actor texture in the direction of motion
218     " vec4 col = colActor * uRecipNumSamples;\n"
219     " for(float i = 1.0; i < uNumSamples; i += 1.0)\n"
220     " {\n"
221     "   float t = i * uRecipNumSamplesMinusOne;\n"
222     "   col += texture2D(sTexture, vTexCoord + (velocity * t)) * uRecipNumSamples;\n"
223     " }\n"
224     " gl_FragColor = mix(colActor, col, vSpeed);\n" // lerp blurred and non-blurred actor based on speed of motion
225     " gl_FragColor.a = colActor.a * fadeToEdgesScale;\n" // fade blurred actor to its edges based on speed of motion
226     " gl_FragColor *= uColor;\n"
227     "}\n";
228
229   // NOTE: we must turn on alpha blending for the actor (HINT_BLENDING)
230   ShaderEffect shader = ShaderEffect::New( vertexSource, fragmentSource,
231                                            GEOMETRY_TYPE_IMAGE,
232                                            ShaderEffect::GeometryHints( ShaderEffect::HINT_BLENDING | ShaderEffect::HINT_GRID) );
233
234   MotionBlurEffect handle( shader );
235
236
237   //////////////////////////////////////
238   // Register uniform properties
239   //
240   //
241
242   // factors that scale the look, defaults
243   handle.SetUniform( MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME, MOTION_BLUR_TEXCOORD_SCALE );
244   handle.SetUniform( MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME, MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR );
245   handle.SetUniform( MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME, MOTION_BLUR_SPEED_SCALING_FACTOR );
246   handle.SetUniform( MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME, MOTION_BLUR_OBJECT_FADE_START );
247   handle.SetUniform( MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME, MOTION_BLUR_OBJECT_FADE_END );
248   handle.SetUniform( MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME, MOTION_BLUR_ALPHA_SCALE );
249   handle.SetUniform( MOTION_BLUR_NUM_SAMPLES_NAME, static_cast<float>( MOTION_BLUR_NUM_SAMPLES ) );
250   handle.SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_NAME, 1.0f / static_cast<float>( MOTION_BLUR_NUM_SAMPLES ) );
251   handle.SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME, 1.0f / static_cast<float>( MOTION_BLUR_NUM_SAMPLES - 1.0f ) );
252   handle.SetUniform( MOTION_BLUR_MODEL_LASTFRAME, Matrix::IDENTITY );
253
254   return handle;
255 }
256
257 MotionBlurEffect MotionBlurEffect::DownCast( ShaderEffect shaderEffect )
258 {
259   MotionBlurEffect handle = shaderEffect;
260   return handle;
261 }
262
263 void MotionBlurEffect::SetNumSamples( int numSamples )
264 {
265   SetUniform( MOTION_BLUR_NUM_SAMPLES_NAME, static_cast<float>( numSamples ) );
266   SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_NAME, 1.0f / static_cast<float>( numSamples ) );
267   SetUniform( MOTION_BLUR_RECIP_NUM_SAMPLES_MINUS_ONE_NAME, 1.0f / static_cast<float>( numSamples - 1.0f ) );
268 }
269
270 void MotionBlurEffect::SetTexcoordScale( float texcoordScale )
271 {
272   SetUniform( MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME, texcoordScale );
273 }
274
275 void MotionBlurEffect::SetGeometryStretchFactor( float scalingFactor )
276 {
277   SetUniform( MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
278 }
279
280 void MotionBlurEffect::SetSpeedScalingFactor( float scalingFactor )
281 {
282   SetUniform( MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
283 }
284
285 void MotionBlurEffect::SetObjectFadeStart( Vector2 displacement )
286 {
287   SetUniform( MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME, displacement );
288 }
289
290 void MotionBlurEffect::SetObjectFadeEnd( Vector2 displacement )
291 {
292   SetUniform( MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME, displacement );
293 }
294
295 void MotionBlurEffect::SetAlphaScale( float alphaScale )
296 {
297   SetUniform( MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME, alphaScale );
298 }
299
300 const std::string& MotionBlurEffect::GetTexcoordScalePropertyName() const
301 {
302   return MOTION_BLUR_TEXCOORD_SCALE_PROPERTY_NAME;
303 }
304
305 const std::string& MotionBlurEffect::GetGeometryStretchFactorPropertyName() const
306 {
307   return MOTION_BLUR_GEOM_STRETCH_SCALING_FACTOR_PROPERTY_NAME;
308 }
309
310 const std::string& MotionBlurEffect::GetSpeedScalingFactorPropertyName() const
311 {
312   return MOTION_BLUR_SPEED_SCALING_FACTOR_PROPERTY_NAME;
313 }
314
315 const std::string& MotionBlurEffect::GetObjectFadeStartPropertyName() const
316 {
317   return MOTION_BLUR_OBJECT_FADE_START_PROPERTY_NAME;
318 }
319
320 const std::string& MotionBlurEffect::GetObjectFadeEndPropertyName() const
321 {
322   return MOTION_BLUR_OBJECT_FADE_END_PROPERTY_NAME;
323 }
324
325 const std::string& MotionBlurEffect::GetAlphaScalePropertyName() const
326 {
327   return MOTION_BLUR_ALPHA_SCALE_PROPERTY_NAME;
328 }
329
330 }
331
332 }