310e3ce4ac24d27020ea86f8c1f88c462e43705b
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / devel-api / shader-effects / motion-blur-effect.h
1 #ifndef __DALI_TOOLKIT_SHADER_EFFECT_MOTION_BLUR_H__
2 #define __DALI_TOOLKIT_SHADER_EFFECT_MOTION_BLUR_H__
3
4 /*
5  * Copyright (c) 2015 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  *
19  */
20
21 // EXTERNAL INCLUDES
22 #include <dali/public-api/shader-effects/shader-effect.h>
23
24 namespace Dali
25 {
26
27 namespace Toolkit
28 {
29
30 /**
31  * @brief Set the properties for the motion blur
32  *
33  * @param numBlurSamples Number of samples used by the shader
34  */
35 inline void SetMotionBlurProperties( Actor& actor, unsigned int numBlurSamples = 8 )
36 {
37   actor.RegisterProperty( "uBlurTexCoordScale", 0.125f );
38   actor.RegisterProperty( "uGeometryStretchFactor", 0.05f );
39   actor.RegisterProperty( "uSpeedScalingFactor", 0.5f );
40   actor.RegisterProperty( "uObjectFadeStart", Vector2( 0.25f, 0.25f ) );
41   actor.RegisterProperty( "uObjectFadeEnd", Vector2( 0.5f, 0.5f ) );
42   actor.RegisterProperty( "uAlphaScale", 0.75f );
43   actor.RegisterProperty( "uNumSamples", static_cast<float>( numBlurSamples ) );
44   actor.RegisterProperty( "uRecipNumSamples", 1.0f / static_cast<float>( numBlurSamples ) );
45   actor.RegisterProperty( "uRecipNumSamplesMinusOne", 1.0f / static_cast<float>( numBlurSamples - 1.0f ) );
46   Property::Index uModelProperty = actor.RegisterProperty( "uModelLastFrame", Matrix::IDENTITY );
47
48   Constraint constraint = Constraint::New<Matrix>( actor, uModelProperty, EqualToConstraint() );
49   constraint.AddSource( Source( actor , Actor::Property::WORLD_MATRIX ) );
50   constraint.Apply();
51 }
52
53 /**
54  * @brief Create a new MotionBlurEffect
55  *
56  * Motion blur shader works on a per object basis. Objects will
57  * blur when they move, or if the camera moves.
58  *
59  * Animatable/Constrainable uniforms:
60  *  "uBlurTexCoordScale"      - This scales the offset for texture samples along the motion velocity vector.
61  *                              A smaller value means the samples will be spaced closer, larger value further
62  *                              apart. User should use this to get the blur to look contiguous, i.e. the blur
63  *                              texels should not be too widely spread, with gaps in between. Default 0.125.
64  *  "uGeometryStretchFactor"  - This scales the amount the geometry stretches backwards along the motion velocity
65  *                              vector. A smaller value means the geometry stretches less, larger it stretches more.
66  *                              User should use this to get the blur to 'bleed' into areas outside the physical
67  *                              bounds of the actor. We need this as the blur is only applied inside the bounds of
68  *                              the actor, but you would expect motion blur trails where the actor was previously
69  *                              but is there no longer. Default 0.05.
70  *  "uSpeedScalingFactor"     - This takes the magnitude of the motion velocity vector and scales it to produce a
71  *                              value which is used to fade the blur in / out with the speed that the actor is moving.
72  *                              As the blur fades in, more of the blur is visible and less of the original actor, and
73  *                              viceversa. This value is also used to control how much to fade the actor near the
74  *                              edges, based on the speed the actor is moving. When the actor is at rest this is not applied.
75  *                              Default 0.5.
76  *  "uObjectFadeStart"        - The displacement from the centre of the actor that the actor will start to fade towards its
77  *                              edges. This is used to prevent an unsightly hard edge between the blurred actor and the scene.
78  *                              Depends on the values of the vertices in the vertex stream. When the actor is at rest this is
79  *                              not applied. Default 0.25, which is half way towards the edge for an ImageRenderer::QUAD.
80  *  "uObjectFadeEnd"          - The displacement from the centre of the actor that the actor will finish fading towards its
81  *                              edges. This is used to prevent an unsightly hard edge between the blurred actor and the scene.
82  *                              Depends on the values of the vertices in the vertex stream. When the actor is at rest this is
83  *                              not applied.Default 0.5, which is all the way towards the edge for an ImageRenderer::QUAD.
84  *  "uAlphaScale"             - Global scaler applied to the alpha of the actor. Used to make the blurred actor a bit more subtle
85  *                              (helps to hide discontinuities due to limited number of texture samples) and reveal a bit of the
86  *                              background behind it as it moves. When the actor is at rest this is not applied. Default 0.75.
87  *  "uNumSamples"             - The number of texture samples to be taken. Increasing the number of samples provides better quality
88  *                              at the cost of performance.
89  *  "uModelLastFrame"         - The model to world space transformation matrix of the actor in the previous frame.
90  *
91  * @return The newly created Property::Map with the motion blur effect
92  */
93 inline Property::Map CreateMotionBlurEffect()
94 {
95   std::string vertexSource;
96   vertexSource =
97       "precision mediump float;\n"
98
99       "attribute vec2 aPosition;\n"
100
101       "uniform mat4 uMvpMatrix;\n"
102       "uniform mat4 uModelView;\n"
103       "uniform mat4 uViewMatrix;\n"
104       "uniform mat4 uProjection;\n"
105       "uniform vec3 uSize;\n"
106
107       "uniform mat4 uModelLastFrame;\n"
108       "float timeDelta = 0.0167;\n"
109
110       "uniform float uGeometryStretchFactor;\n"
111       "uniform float uSpeedScalingFactor;\n"
112
113       // outputs
114       "varying vec2 vModelSpaceCenterToPos;\n"
115       "varying vec2 vScreenSpaceVelocityVector;\n"
116       "varying float vSpeed;\n"
117       "varying vec2 vTexCoord;\n"
118
119       "void main()\n"
120       "{\n"
121       // get view space position of vertex this frame and last frame
122       " vec4 vertexPosition = vec4(aPosition, 0.0, 1.0);\n"
123       " vertexPosition.xyz *= uSize;\n"
124
125       " vec4 viewSpaceVertex = uModelView * vertexPosition;\n"
126       " vec4 viewSpaceVertexLastFrame = (uViewMatrix * uModelLastFrame) * vertexPosition;\n"
127       " float reciprocalTimeDelta = 1.0 / timeDelta;\n"
128
129       // work out vertex's last movement in view space
130       " vec3 viewSpacePosDelta = viewSpaceVertex.xyz - viewSpaceVertexLastFrame.xyz;\n"
131
132       // get clip space position of vertex this frame and last frame
133       " vec4 clipSpaceVertex = uMvpMatrix * vertexPosition;\n"
134       " vec4 clipSpaceVertexLastFrame = uProjection * viewSpaceVertexLastFrame;\n"
135
136       // decide how much this vertex is 'trailing', i.e. at the back of the object relative to its direction of motion. We do this
137       // 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
138       " float t = 0.0;\n"
139       " float posDeltaLength = length(viewSpacePosDelta);\n"
140       " if(posDeltaLength > 0.001)\n" // avoid div by 0 if object has barely moved
141       " {\n"
142       "   vec4 viewSpaceCenterToPos = uModelView * vec4(vertexPosition.xy, 0.0, 0.0);\n"
143       "   float centerToVertexDist = length(viewSpaceCenterToPos);\n"
144       "   if(centerToVertexDist > 0.001)\n" // avoid div by 0 if object has vertex at model space origin
145       "   {\n"
146       "     vec3 viewSpacePosDeltaNormalised = viewSpacePosDelta / posDeltaLength;\n"
147       "     vec3 viewSpaceCenterToPosNormalised = viewSpaceCenterToPos.xyz / centerToVertexDist;\n"
148       "     t = (dot(viewSpacePosDeltaNormalised, viewSpaceCenterToPosNormalised) * 0.5 ) + 0.5;\n" // scale and bias from [-1..1] to [0..1]
149       "   }\n"
150       " }\n"
151       // output vertex position lerped with its last position, based on how much it is trailing,
152       // this stretches the geom back along where it has just been, giving a warping effect
153       // 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)
154       " gl_Position = mix(clipSpaceVertexLastFrame, clipSpaceVertex, t * uGeometryStretchFactor * reciprocalTimeDelta);\n"
155
156       // work out vertex's last movement in normalised device coordinates [-1..1] space, i.e. perspective divide
157       " vec2 ndcVertex = clipSpaceVertex.xy / clipSpaceVertex.w;\n"
158       " vec2 ndcVertexLastFrame = clipSpaceVertexLastFrame.xy / clipSpaceVertexLastFrame.w;\n"
159       // scale and bias so that a value of 1.0 corresponds to screen size (NDC is [-1..1] = 2)
160       " vScreenSpaceVelocityVector = ((ndcVertex - ndcVertexLastFrame) * 0.5 * reciprocalTimeDelta);\n"
161       " vScreenSpaceVelocityVector.y = -vScreenSpaceVelocityVector.y;\n" // TODO negated due to y being inverted in our coordinate system?
162       // calculate a scaling factor proportional to velocity, which we can use to tweak how things look
163       " vSpeed = length(vScreenSpaceVelocityVector) * uSpeedScalingFactor;\n"
164       " vSpeed = clamp(vSpeed, 0.0, 1.0);\n"
165
166       // 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)
167       " vModelSpaceCenterToPos = viewSpaceVertex.xy;\n"
168
169       " vec2 texCoord = aPosition + vec2(0.5);"
170       " vTexCoord = texCoord;\n"
171       "}\n";
172
173
174   std::string fragmentSource;
175   fragmentSource =
176       "precision mediump float;\n"
177
178       "uniform sampler2D sTexture;\n"
179       "uniform vec4 uColor;\n"
180
181       "uniform vec2 uObjectFadeStart;\n"
182       "uniform vec2 uObjectFadeEnd;\n"
183       "uniform float uAlphaScale;\n"
184       "uniform float uBlurTexCoordScale;\n"
185       "uniform float uNumSamples;\n"
186       "uniform float uRecipNumSamples;\n"
187       "uniform float uRecipNumSamplesMinusOne;\n"
188       // inputs
189       "varying vec2 vModelSpaceCenterToPos;\n"
190       "varying vec2 vScreenSpaceVelocityVector;\n"
191       "varying float vSpeed;\n"
192       "varying vec2 vTexCoord;\n"
193
194       "void main()\n"
195       "{\n"
196       // 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
197       // the blurred object and the unblurred background. Use smoothstep also to hide any hard edges (discontinuities) in rate of change of this alpha gradient
198       " vec2 centerToPixel = abs(vModelSpaceCenterToPos);\n"
199       " vec2 fadeToEdges = smoothstep(0.0, 1.0, 1.0 - ((centerToPixel - uObjectFadeStart) / (uObjectFadeEnd - uObjectFadeStart)));\n"
200       " float fadeToEdgesScale = fadeToEdges.x * fadeToEdges.y * uAlphaScale;\n" // apply global scaler
201       " fadeToEdgesScale = mix(1.0, fadeToEdgesScale, vSpeed);\n" // fade proportional to speed, so opaque when at rest
202
203       // scale velocity vector by user requirements
204       " vec2 velocity = vScreenSpaceVelocityVector * uBlurTexCoordScale;\n"
205
206       // standard actor texel
207       " vec4 colActor = texture2D(sTexture, vTexCoord);\n"
208
209       // blurred actor - gather texture samples from the actor texture in the direction of motion
210       " vec4 col = colActor * uRecipNumSamples;\n"
211       " for(float i = 1.0; i < uNumSamples; i += 1.0)\n"
212       " {\n"
213       "   float t = i * uRecipNumSamplesMinusOne;\n"
214       "   col += texture2D(sTexture, vTexCoord + (velocity * t)) * uRecipNumSamples;\n"
215       " }\n"
216       " gl_FragColor = mix(colActor, col, vSpeed);\n" // lerp blurred and non-blurred actor based on speed of motion
217       " gl_FragColor.a = fadeToEdgesScale;//colActor.a * fadeToEdgesScale;\n" // fade blurred actor to its edges based on speed of motion
218       " gl_FragColor *= uColor;\n"
219       "}\n";
220
221
222   Property::Map map;
223
224   Property::Map customShader;
225   customShader[ "vertexShader" ] = vertexSource;
226   customShader[ "fragmentShader" ] = fragmentSource;
227
228   customShader[ "subdivideGridX" ] = 10;
229   customShader[ "subdivideGridY" ] = 10;
230
231   // NOTE: we must turn on alpha blending for the actor (HINT_BLENDING)
232   customShader[ "hints" ] = "outputIsTransparent";
233
234   map[ "shader" ] = customShader;
235   return map;
236 }
237
238 }
239
240 }
241
242 #endif //#ifndef __DALI_TOOLKIT_SHADER_EFFECT_MOTION_BLUR_H__