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