Merge remote-tracking branch 'origin/tizen' into new_text
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / public-api / shader-effects / motion-stretch-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 // CLASS HEADER
19 #include <dali-toolkit/public-api/shader-effects/motion-stretch-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 struct MatrixFromPropertiesConstraint
35 {
36   MatrixFromPropertiesConstraint()
37   {
38   }
39
40   Matrix operator()( const Matrix& current,
41                      const PropertyInput& propertyPosition,
42                      const PropertyInput& propertyOrientation,
43                      const PropertyInput& propertyScale )
44   {
45     Matrix mat4( false );
46     mat4.SetTransformComponents( propertyScale.GetVector3(),
47                                  propertyOrientation.GetQuaternion(),
48                                  propertyPosition.GetVector3() );
49
50     return mat4;
51   }
52 };
53
54 const std::string MOTION_STRETCH_GEOMETRY_STRETCH_SCALING_FACTOR_PROPERTY_NAME( "uGeometryStretchFactor" );
55 const std::string MOTION_STRETCH_SPEED_SCALING_FACTOR_PROPERTY_NAME( "uSpeedScalingFactor" );
56 const std::string MOTION_STRETCH_OBJECT_FADE_START_PROPERTY_NAME( "uObjectFadeStart" );
57 const std::string MOTION_STRETCH_OBJECT_FADE_END_PROPERTY_NAME( "uObjectFadeEnd" );
58 const std::string MOTION_STRETCH_ALPHA_SCALE_PROPERTY_NAME( "uAlphaScale" );
59 const std::string MOTION_STRETCH_MODELVIEW_LASTFRAME( "uModelLastFrame" );  ///< Matrix
60
61 ////////////////////////////////////////////////////
62 //
63 // Motion stretch shader / actor tweaking parameters
64 //
65
66 // half width and half height respectively of actor, corresponding to values in vertex attribute stream
67 // Note that these values work for normal image actor (verts +/- 0.5) but a grid or a nine square seemsi
68 // to have verts in pixel space (e.g. 256,256). Need to fix this somehow,
69 // either in Dali or by passing uniforms which we can use to 'normalise' the verts in the vertex shader
70 const Vector2 MOTION_STRETCH_ACTOR_VERTEX( 0.5f, 0.5f );
71
72 const float MOTION_STRETCH_GEOM_STRETCH_SCALING_FACTOR = 0.5f; // scaling factor for how much to stretch actor geom as it moves
73 const float MOTION_STRETCH_SPEED_SCALING_FACTOR = 0.5f;        // scales the speed, producing a number affecting how much the actor stretches & fades at the edges
74
75 const Vector2 MOTION_STRETCH_OBJECT_FADE_END( MOTION_STRETCH_ACTOR_VERTEX );             // displacement from center at which actor fully fades to zero alpha
76 const Vector2 MOTION_STRETCH_OBJECT_FADE_START( MOTION_STRETCH_OBJECT_FADE_END * 0.5f ); // displacement from center at which actor start to fade from full alpha
77
78 const float MOTION_STRETCH_ALPHA_SCALE = 0.75f; // global scaler applied to actor alpha as it is stretched + moving
79
80 } // namespace
81
82
83 MotionStretchEffect::MotionStretchEffect()
84 {
85 }
86
87 // Call the Parent copy constructor to add reference to the implementation for this object
88 MotionStretchEffect::MotionStretchEffect( ShaderEffect handle )
89 :ShaderEffect( handle )
90 {
91 }
92
93 MotionStretchEffect::~MotionStretchEffect()
94 {
95 }
96
97 MotionStretchEffect MotionStretchEffect::Apply( RenderableActor renderable )
98 {
99   MotionStretchEffect newEffect = New();
100   renderable.SetShaderEffect( newEffect );
101
102   Dali::Property::Index uModelProperty = newEffect.GetPropertyIndex( MOTION_STRETCH_MODELVIEW_LASTFRAME );
103
104   Constraint constraint = Constraint::New<Matrix>( newEffect, uModelProperty, EqualToConstraint() );
105   constraint.AddSource( Source( renderable, Actor::Property::WORLD_MATRIX ) );
106
107   // and set up constraint.
108   constraint.Apply();
109   return newEffect;
110 }
111
112 MotionStretchEffect MotionStretchEffect::New()
113 {
114   // Dali vertexSource prefix for reference:
115   // precision highp float;
116   // attribute vec3  aPosition;
117   // attribute vec2  aTexCoord;
118   // uniform   mat4  uMvpMatrix;
119   // uniform   mat4  uModelView;
120   // uniform   mat3  uNormalMatrix;
121   // uniform   mat4  uProjection;
122   // uniform   vec4  uColor;
123   // varying   vec2  vTexCoord;
124   std::string vertexSource;
125   vertexSource =
126     "precision mediump float;\n"
127     "uniform mat4  uModelLastFrame;\n"
128     "uniform float uTimeDelta;\n"
129
130     "uniform float uGeometryStretchFactor;\n"
131     "uniform float uSpeedScalingFactor;\n"
132
133     // outputs
134     "varying vec2 vModelSpaceCenterToPos;\n"
135     "varying vec2 vScreenSpaceVelocityVector;\n"
136     "varying float vSpeed;\n"
137
138     "void main()\n"
139     "{\n"
140     // get view space position of vertex this frame and last frame
141     " vec4 vertex = vec4(aPosition, 1.0);\n"
142     " vec4 viewSpaceVertex = uModelView * vertex;\n"
143     " vec4 viewSpaceVertexLastFrame = uViewMatrix * uModelLastFrame * vertex;\n"
144
145     // work out vertex's last movement in view space
146     " vec3 viewSpacePosDelta = viewSpaceVertex.xyz - viewSpaceVertexLastFrame.xyz;\n"
147     " float reciprocalTimeDelta = 1.0 / ((uTimeDelta > 0.0) ? uTimeDelta : 0.01);\n"
148
149     // get clip space position of vertex this frame and last frame
150     " vec4 clipSpaceVertex = uMvpMatrix * vertex;\n"
151     " vec4 clipSpaceVertexLastFrame = uProjection * viewSpaceVertexLastFrame;\n"
152
153     // decide how much this vertex is 'trailing', i.e. at the back of the object relative to its direction of motion. We do this
154     // 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
155     " float t = 0.0;\n"
156     " float posDeltaLength = length(viewSpacePosDelta);\n"
157     " if(posDeltaLength > 0.001)\n" // avoid div by 0 if object has barely moved
158     " {\n"
159     "   vec4 viewSpaceCenterToPos = uModelView * vec4(aPosition, 0.0);\n"
160     "   float centerToVertexDist = length(viewSpaceCenterToPos);\n"
161     "   if(centerToVertexDist > 0.001)\n" // avoid div by 0 if object has vertex at model space origin
162     "   {\n"
163     "     vec3 viewSpacePosDeltaNormalised = viewSpacePosDelta / posDeltaLength;\n"
164     "     vec3 viewSpaceCenterToPosNormalised = viewSpaceCenterToPos.xyz / centerToVertexDist;\n"
165     "     t = (dot(viewSpacePosDeltaNormalised, viewSpaceCenterToPosNormalised) * 0.5 ) + 0.5;\n" // scale and bias from [-1..1] to [0..1]
166     "   }\n"
167     " }\n"
168     // output vertex position lerped with its last position, based on how much it is trailing,
169     // this stretches the geom back along where it has just been, giving a warping effect
170     // We raise t to a power in order that non-trailing vertices are effected much more than trailing ones
171     // 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)
172     " gl_Position = mix(clipSpaceVertexLastFrame, clipSpaceVertex, t * t * t * uGeometryStretchFactor * reciprocalTimeDelta);\n"
173
174     // work out vertex's last movement in normalised device coordinates [-1..1] space, i.e. perspective divide
175     " vec2 ndcVertex = clipSpaceVertex.xy / clipSpaceVertex.w;\n"
176     " vec2 ndcVertexLastFrame = clipSpaceVertexLastFrame.xy / clipSpaceVertexLastFrame.w;\n"
177     // scale and bias so that a value of 1.0 corresponds to screen size (NDC is [-1..1] = 2)
178     " vScreenSpaceVelocityVector = ((ndcVertex - ndcVertexLastFrame) * 0.5 * reciprocalTimeDelta);\n"
179     " vScreenSpaceVelocityVector.y = -vScreenSpaceVelocityVector.y;\n" // TODO negated due to y being inverted in our coordinate system?
180     // calculate a scaling factor proportional to velocity, which we can use to tweak how things look
181     " vSpeed = length(vScreenSpaceVelocityVector) * uSpeedScalingFactor;\n"
182     " vSpeed = clamp(vSpeed, 0.0, 1.0);\n"
183
184     // 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)
185     " vModelSpaceCenterToPos = aPosition.xy;\n"
186
187     " vTexCoord = aTexCoord;\n"
188     "}\n";
189
190
191   // Dali fragmentSource prefix for reference:
192   // precision highp     float;
193   // uniform   sampler2D sTexture;
194   // uniform   sampler2D sEffect;
195   // uniform   vec4      uColor;
196   // varying   vec2      vTexCoord;
197   std::string fragmentSource;
198   fragmentSource =
199     "precision mediump float;\n"
200
201     "uniform vec2 uObjectFadeStart;\n"
202     "uniform vec2 uObjectFadeEnd;\n"
203     "uniform float uAlphaScale;\n"
204
205     // inputs
206     "varying vec2 vModelSpaceCenterToPos;\n"
207     "varying vec2 vScreenSpaceVelocityVector;\n"
208     "varying float vSpeed;\n"
209
210     "void main()\n"
211     "{\n"
212     // 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
213     // the stretched object and the background. Use smoothstep also to hide any hard edges (discontinuities) in rate of change of this alpha gradient
214     " vec2 centerToPixel = abs( vModelSpaceCenterToPos );\n"
215     " vec2 fadeToEdges = smoothstep(0.0, 1.0, 1.0 - ((centerToPixel - uObjectFadeStart) / (uObjectFadeEnd - uObjectFadeStart)));\n"
216     " float fadeToEdgesScale = fadeToEdges.x * fadeToEdges.y * uAlphaScale;\n" // apply global scaler
217     " fadeToEdgesScale = mix(1.0, fadeToEdgesScale, vSpeed);\n" // fade proportional to speed, so opaque when at rest
218
219     // standard actor texel
220     " vec4 colActor = texture2D(sTexture, vTexCoord);\n"
221     " gl_FragColor = colActor;\n"
222     " gl_FragColor.a *= fadeToEdgesScale;\n" // fade actor to its edges based on speed of motion
223     " gl_FragColor *= uColor;\n"
224     "}";
225
226   // NOTE: we must turn on alpha blending for the actor (HINT_BLENDING)
227   ShaderEffect shader = ShaderEffect::New(
228     vertexSource, fragmentSource, GeometryType( GEOMETRY_TYPE_IMAGE ),
229     ShaderEffect::GeometryHints( ShaderEffect::HINT_BLENDING | ShaderEffect::HINT_GRID ) );
230
231
232
233   MotionStretchEffect handle( shader );
234
235
236   //////////////////////////////////////
237   // Register uniform properties
238   //
239   //
240
241   // factors that scale the look, defaults
242   handle.SetUniform( MOTION_STRETCH_GEOMETRY_STRETCH_SCALING_FACTOR_PROPERTY_NAME, MOTION_STRETCH_GEOM_STRETCH_SCALING_FACTOR );
243   handle.SetUniform( MOTION_STRETCH_SPEED_SCALING_FACTOR_PROPERTY_NAME, MOTION_STRETCH_SPEED_SCALING_FACTOR );
244   handle.SetUniform( MOTION_STRETCH_OBJECT_FADE_START_PROPERTY_NAME, MOTION_STRETCH_OBJECT_FADE_START );
245   handle.SetUniform( MOTION_STRETCH_OBJECT_FADE_END_PROPERTY_NAME, MOTION_STRETCH_OBJECT_FADE_END );
246   handle.SetUniform( MOTION_STRETCH_ALPHA_SCALE_PROPERTY_NAME, MOTION_STRETCH_ALPHA_SCALE );
247   handle.SetUniform( MOTION_STRETCH_MODELVIEW_LASTFRAME, Matrix::IDENTITY );
248
249   return handle;
250 }
251
252 void MotionStretchEffect::SetGeometryStretchFactor( float scalingFactor )
253 {
254   SetUniform( MOTION_STRETCH_GEOMETRY_STRETCH_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
255 }
256
257 void MotionStretchEffect::SetSpeedScalingFactor( float scalingFactor )
258 {
259   SetUniform( MOTION_STRETCH_SPEED_SCALING_FACTOR_PROPERTY_NAME, scalingFactor );
260 }
261
262 void MotionStretchEffect::SetObjectFadeStart( Vector2 displacement )
263 {
264   SetUniform( MOTION_STRETCH_OBJECT_FADE_START_PROPERTY_NAME, displacement );
265 }
266
267 void MotionStretchEffect::SetObjectFadeEnd( Vector2 displacement )
268 {
269   SetUniform( MOTION_STRETCH_OBJECT_FADE_END_PROPERTY_NAME, displacement );
270 }
271
272 void MotionStretchEffect::SetAlphaScale( float alphaScale )
273 {
274   SetUniform( MOTION_STRETCH_ALPHA_SCALE_PROPERTY_NAME, alphaScale );
275 }
276
277 const std::string& MotionStretchEffect::GetGeometryStretchFactorPropertyName() const
278 {
279   return MOTION_STRETCH_GEOMETRY_STRETCH_SCALING_FACTOR_PROPERTY_NAME;
280 }
281
282 const std::string& MotionStretchEffect::GetSpeedScalingFactorPropertyName() const
283 {
284   return MOTION_STRETCH_SPEED_SCALING_FACTOR_PROPERTY_NAME;
285 }
286
287 const std::string& MotionStretchEffect::GetObjectFadeStartPropertyName() const
288 {
289   return MOTION_STRETCH_OBJECT_FADE_START_PROPERTY_NAME;
290 }
291
292 const std::string& MotionStretchEffect::GetObjectFadeEndPropertyName() const
293 {
294   return MOTION_STRETCH_OBJECT_FADE_END_PROPERTY_NAME;
295 }
296
297 const std::string& MotionStretchEffect::GetAlphaScalePropertyName() const
298 {
299   return MOTION_STRETCH_ALPHA_SCALE_PROPERTY_NAME;
300 }
301
302 }
303
304 }