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