e16e2efc1b16f8568c2acede36a3e328fadef247
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / devel-api / shader-effects / motion-stretch-effect.h
1 #ifndef __DALI_TOOLKIT_SHADER_EFFECT_MOTION_STRETCH_H__
2 #define __DALI_TOOLKIT_SHADER_EFFECT_MOTION_STRETCH_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/actors/image-actor.h>
23 #include <dali/public-api/shader-effects/shader-effect.h>
24
25 namespace Dali
26 {
27
28 namespace Toolkit
29 {
30
31 /**
32  * @brief Creates a new MotionStretchEffect
33  *
34  * Motion stretch shader works on a per object basis. Objects will stretch in the direction of motion when they move, or if the camera moves. Can be applied
35  * to ImageActor or TextActor only.
36  *
37  * Usage example:-
38  *
39  * // Create shader used for doing motion stretch\n
40  * ShaderEffect MotionStretchEffect = CreateMotionStretchEffect();
41  *
42  * // set actor shader to the stretch one\n
43  * Actor actor = Actor::New( ... );\n
44  * actor.SetShaderEffect( MotionStretchEffect );
45  *
46  * // Constrain "uModelLastFrame" to be the same as the actor's world matrix\n
47  * Dali::Property::Index uModelProperty = MotionBlurEffect.GetPropertyIndex( "uModelLastFrame" );
48  * Constraint constraint = Constraint::New<Matrix>( MotionBlurEffect, uModelProperty, EqualToConstraint() );\n
49  * constraint.AddSource( Source( actor , Actor::Property::WORLD_MATRIX ) );\n
50  * constraint.Apply();\n
51  *
52  * Animatable/Constrainable uniforms:
53  *  "uGeometryStretchFactor"  - This scales the amount the geometry stretches along the motion velocity vector.
54  *                              A smaller value means the geometry stretches less, larger it stretches more. Default 0.5.
55  *  "uSpeedScalingFactor"     - This value is used to control how much to fade the actor near the edges, based on the
56  *                              speed the actor is moving. When the actor is at rest this is not applied. Default 0.5.
57  *  "uObjectFadeStart"        - The displacement from the centre of the actor that the actor will start to fade towards
58  *                              its edges. This is used to prevent an unsightly hard edge between the stretched actor and
59  *                              the scene. Depends on the values of the vertices in the vertex stream. When the actor is at
60  *                              rest this is not applied. Default Vector2(0.25, 0.25), which is half way towards the edge for
61  *                              an ImageRenderer::QUAD.
62  *  "uObjectFadeEnd"          - The displacement from the centre of the actor that the actor will finish fading towards its edges.
63  *                              This is used to prevent an unsightly hard edge between the stretched actor and the scene. Depends
64  *                              on the values of the vertices in the vertex stream. When the actor is at rest this is not applied.
65  *                              Default 0.5, which is all the way towards the edge for an ImageRenderer::QUAD.
66  *  "uAlphaScale"             - Global scaler applied to the alpha of the actor. Used to make the stretched actor a bit more subtle
67  *                              and reveal a bit of the background behind it as it moves. When the actor is at rest this is not
68  *                              applied. Default 0.75.
69  *  "uModelLastFrame"         - The model to world space transformation matrix of the actor in the previous frame.
70  *
71  * @return A handle to a newly allocated ShaderEffect
72  */
73 inline ShaderEffect CreateMotionStretchEffect()
74 {
75   // Dali vertexSource prefix for reference:
76   // precision highp float;
77   // attribute vec3  aPosition;
78   // attribute vec2  aTexCoord;
79   // uniform   mat4  uMvpMatrix;
80   // uniform   mat4  uModelView;
81   // uniform   mat3  uNormalMatrix;
82   // uniform   mat4  uProjection;
83   // uniform   vec4  uColor;
84   // varying   vec2  vTexCoord;
85   std::string vertexSource;
86   vertexSource =
87       "precision mediump float;\n"
88       "uniform mat4  uModelLastFrame;\n"
89       "uniform float uTimeDelta;\n"
90
91       "uniform float uGeometryStretchFactor;\n"
92       "uniform float uSpeedScalingFactor;\n"
93
94       // outputs
95       "varying vec2 vModelSpaceCenterToPos;\n"
96       "varying vec2 vScreenSpaceVelocityVector;\n"
97       "varying float vSpeed;\n"
98
99       "void main()\n"
100       "{\n"
101       // get view space position of vertex this frame and last frame
102       " vec4 vertex = vec4(aPosition, 1.0);\n"
103       " vec4 viewSpaceVertex = uModelView * vertex;\n"
104       " vec4 viewSpaceVertexLastFrame = uViewMatrix * uModelLastFrame * vertex;\n"
105
106       // work out vertex's last movement in view space
107       " vec3 viewSpacePosDelta = viewSpaceVertex.xyz - viewSpaceVertexLastFrame.xyz;\n"
108       " float reciprocalTimeDelta = 1.0 / ((uTimeDelta > 0.0) ? uTimeDelta : 0.01);\n"
109
110       // get clip space position of vertex this frame and last frame
111       " vec4 clipSpaceVertex = uMvpMatrix * vertex;\n"
112       " vec4 clipSpaceVertexLastFrame = uProjection * viewSpaceVertexLastFrame;\n"
113
114       // decide how much this vertex is 'trailing', i.e. at the back of the object relative to its direction of motion. We do this
115       // 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
116       " float t = 0.0;\n"
117       " float posDeltaLength = length(viewSpacePosDelta);\n"
118       " if(posDeltaLength > 0.001)\n" // avoid div by 0 if object has barely moved
119       " {\n"
120       "   vec4 viewSpaceCenterToPos = uModelView * vec4(aPosition, 0.0);\n"
121       "   float centerToVertexDist = length(viewSpaceCenterToPos);\n"
122       "   if(centerToVertexDist > 0.001)\n" // avoid div by 0 if object has vertex at model space origin
123       "   {\n"
124       "     vec3 viewSpacePosDeltaNormalised = viewSpacePosDelta / posDeltaLength;\n"
125       "     vec3 viewSpaceCenterToPosNormalised = viewSpaceCenterToPos.xyz / centerToVertexDist;\n"
126       "     t = (dot(viewSpacePosDeltaNormalised, viewSpaceCenterToPosNormalised) * 0.5 ) + 0.5;\n" // scale and bias from [-1..1] to [0..1]
127       "   }\n"
128       " }\n"
129       // output vertex position lerped with its last position, based on how much it is trailing,
130       // this stretches the geom back along where it has just been, giving a warping effect
131       // We raise t to a power in order that non-trailing vertices are effected much more than trailing ones
132       // 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)
133       " gl_Position = mix(clipSpaceVertexLastFrame, clipSpaceVertex, t * t * t * uGeometryStretchFactor * reciprocalTimeDelta);\n"
134
135       // work out vertex's last movement in normalised device coordinates [-1..1] space, i.e. perspective divide
136       " vec2 ndcVertex = clipSpaceVertex.xy / clipSpaceVertex.w;\n"
137       " vec2 ndcVertexLastFrame = clipSpaceVertexLastFrame.xy / clipSpaceVertexLastFrame.w;\n"
138       // scale and bias so that a value of 1.0 corresponds to screen size (NDC is [-1..1] = 2)
139       " vScreenSpaceVelocityVector = ((ndcVertex - ndcVertexLastFrame) * 0.5 * reciprocalTimeDelta);\n"
140       " vScreenSpaceVelocityVector.y = -vScreenSpaceVelocityVector.y;\n" // TODO negated due to y being inverted in our coordinate system?
141       // calculate a scaling factor proportional to velocity, which we can use to tweak how things look
142       " vSpeed = length(vScreenSpaceVelocityVector) * uSpeedScalingFactor;\n"
143       " vSpeed = clamp(vSpeed, 0.0, 1.0);\n"
144
145       // 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)
146       " vModelSpaceCenterToPos = aPosition.xy;\n"
147
148       " vTexCoord = aTexCoord;\n"
149       "}\n";
150
151
152   // Dali fragmentSource prefix for reference:
153   // precision highp     float;
154   // uniform   sampler2D sTexture;
155   // uniform   sampler2D sEffect;
156   // uniform   vec4      uColor;
157   // varying   vec2      vTexCoord;
158   std::string fragmentSource;
159   fragmentSource =
160       "precision mediump float;\n"
161
162       "uniform vec2 uObjectFadeStart;\n"
163       "uniform vec2 uObjectFadeEnd;\n"
164       "uniform float uAlphaScale;\n"
165
166       // inputs
167       "varying vec2 vModelSpaceCenterToPos;\n"
168       "varying vec2 vScreenSpaceVelocityVector;\n"
169       "varying float vSpeed;\n"
170
171       "void main()\n"
172       "{\n"
173       // 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
174       // the stretched object and the background. Use smoothstep also to hide any hard edges (discontinuities) in rate of change of this alpha gradient
175       " vec2 centerToPixel = abs( vModelSpaceCenterToPos );\n"
176       " vec2 fadeToEdges = smoothstep(0.0, 1.0, 1.0 - ((centerToPixel - uObjectFadeStart) / (uObjectFadeEnd - uObjectFadeStart)));\n"
177       " float fadeToEdgesScale = fadeToEdges.x * fadeToEdges.y * uAlphaScale;\n" // apply global scaler
178       " fadeToEdgesScale = mix(1.0, fadeToEdgesScale, vSpeed);\n" // fade proportional to speed, so opaque when at rest
179
180       // standard actor texel
181       " vec4 colActor = texture2D(sTexture, vTexCoord);\n"
182       " gl_FragColor = colActor;\n"
183       " gl_FragColor.a *= fadeToEdgesScale;\n" // fade actor to its edges based on speed of motion
184       " gl_FragColor *= uColor;\n"
185       "}";
186
187   // NOTE: we must turn on alpha blending for the actor (HINT_BLENDING)
188   ShaderEffect shaderEffect = ShaderEffect::New(
189       vertexSource, fragmentSource,
190       ShaderEffect::GeometryHints( ShaderEffect::HINT_BLENDING | ShaderEffect::HINT_GRID ) );
191
192
193   //////////////////////////////////////
194   // Register uniform properties
195   //
196   //
197   shaderEffect.SetUniform( "uGeometryStretchFactor",  0.5f );
198   shaderEffect.SetUniform( "uSpeedScalingFactor",     0.5f );
199   shaderEffect.SetUniform( "uObjectFadeStart",        Vector2( 0.25f, 0.25f ) );
200   shaderEffect.SetUniform( "uObjectFadeEnd",          Vector2( 0.5f, 0.5f ) );
201   shaderEffect.SetUniform( "uAlphaScale",             0.75f );
202   shaderEffect.SetUniform( "uModelLastFrame",         Matrix::IDENTITY );
203
204   return shaderEffect;
205 }
206
207 }
208
209 }
210
211 #endif //#ifndef __DALI_TOOLKIT_SHADER_EFFECT_MOTION_STRETCH_H__