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