2 * Copyright (c) 2014 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "page-turn-effect-impl.h"
23 #include <dali/public-api/animation/active-constraint.h>
24 #include <dali/public-api/animation/constraint.h>
25 #include <dali/public-api/common/stage.h>
38 #define MAKE_STRING(A)#A
40 const std::string CURRENT_CENTER_PROPERTY_NAME("uCurrentCenter");
41 const std::string ORIGINAL_CENTER_PROPERTY_NAME("uOriginalCenter");
42 const std::string PAGE_SIZE_PROPERTY_NAME("uPageSize");
43 const std::string IS_TURNING_BACK_PROPERTY_NAME("uIsTurningBack");
44 const std::string SHADOW_WIDTH_PROPERTY_NAME("uShadowWidth");
45 const std::string SPINE_SHADOW_PARAMETER_PROPERTY_NAME("uSpineShadowParameter");
47 // fake shadow is used to enhance the effect, with its default maximum width to be pageSize * 0.15
48 const float DEFAULT_SHADOW_WIDTH(0.15f);
50 // the major&minor radius (in pixels) to form an ellipse shape
51 // the top-left quarter of this ellipse is used to calculate spine normal for simulating shadow
52 const Vector2 DEFAULT_SPINE_SHADOW_PARAMETER(50.0f, 20.0f);
54 // when the vanishing point is very far away(pageHeight*THRESHOLD), make it infinitely, in this case, the page bent horizontally
55 const float THRESHOLD(20.0);
57 struct CommonParametersConstraint
59 Matrix operator()( const Matrix& current,
60 const PropertyInput& originalCenterProperty,
61 const PropertyInput& currentCenterProperty,
62 const PropertyInput& pageSizeProperty)
64 const Vector2& originalCenter = originalCenterProperty.GetVector2();
65 Vector2 currentCenter = currentCenterProperty.GetVector2();
66 const Vector2& pageSize = pageSizeProperty.GetVector2();
68 // calculate the curve direction and the vanishing point
69 // here, the vanishing point is the intersection of spine with the line passing through original center and vertical to curve direction
70 Vector2 curveDirection( currentCenter - originalCenter );
71 curveDirection.Normalize();
72 if( fabs(curveDirection.y) < 0.01f) // eliminate the possibility of division by zero in the next step
74 curveDirection.y = 0.01f;
76 float vanishingPointY = originalCenter.y + curveDirection.x * originalCenter.x / curveDirection.y;
78 float curveEndY, cosTheta ,sinTheta ,translateX, translateY;
79 // when the vanishing point is very far away, make it infinitely, in this case, the page bent horizontally
80 if( fabs(vanishingPointY-pageSize.y*0.5f) >= pageSize.y*THRESHOLD )
82 curveDirection = Vector2(-1.f,0.f);
83 currentCenter.y = originalCenter.y;
85 curveEndY = originalCenter.y;
88 translateX = currentCenter.x - originalCenter.x;
89 translateY = vanishingPointY;
93 curveEndY = currentCenter.y - curveDirection.y * (currentCenter.x/curveDirection.x) ;
94 Vector2 v1( currentCenter.x, currentCenter.y - vanishingPointY );
96 Vector2 v2( originalCenter.x, originalCenter.y - vanishingPointY );
98 cosTheta = v1.x*v2.x + v1.y*v2.y;
99 sinTheta = ( vanishingPointY > pageSize.y*0.5f ) ? sqrt(1.0-cosTheta*cosTheta) : -sqrt(1.0-cosTheta*cosTheta);
100 translateX = currentCenter.x - cosTheta*originalCenter.x - sinTheta*( originalCenter.y-vanishingPointY );
101 translateY = currentCenter.y + sinTheta*originalCenter.x - cosTheta*( originalCenter.y-vanishingPointY );
104 float originalLength = fabs(originalCenter.x/curveDirection.x);
105 float currentLength = fabs(currentCenter.x/curveDirection.x);
106 float curveHeight = 0.45f*sqrt(originalLength*originalLength - currentLength*currentLength);
108 Matrix commonParameters( false );
109 float* parameterArray = commonParameters.AsFloat();
110 parameterArray[0] = cosTheta;
111 parameterArray[1] = -sinTheta;
112 parameterArray[2] = originalCenter.x;
113 parameterArray[3] = originalCenter.y;
114 parameterArray[4] = sinTheta;
115 parameterArray[5] = cosTheta;
116 parameterArray[6] = currentCenter.x;
117 parameterArray[7] = currentCenter.y;
118 parameterArray[8] = translateX;
119 parameterArray[9] = translateY;
120 parameterArray[10] = vanishingPointY;
121 parameterArray[11] = curveEndY;
122 parameterArray[12] = curveDirection.x;
123 parameterArray[13] = curveDirection.y;
124 parameterArray[14] = curveHeight;
125 parameterArray[15] = currentLength;
127 return commonParameters;
133 PageTurnEffect::PageTurnEffect()
134 : mOriginalCenterPropertyIndex(Property::INVALID_INDEX),
135 mCurrentCenterPropertyIndex(Property::INVALID_INDEX)
139 PageTurnEffect::~PageTurnEffect()
143 Toolkit::PageTurnEffect PageTurnEffect::CreateShaderEffect( bool enableBlending )
145 std::string vertexShader = MAKE_STRING(
147 * The common parameters for all the vertices, calculate in CPU then pass into the shader as uniforms
149 * first part of the page, (outside the the line passing through original center and vertical to curve direction)
150 * no Z change, only 2D rotation and translation
151 * ([0][0],[0][1],[1][0],[1][1]) mat2 rotateMatrix
152 * ([2][0],[2][1]) vec2 translationVector
154 * ([0][2],[0][3]) vec2 originalCenter: Typically the press down position of the Pan Gesture
155 * ([1][2],[1][3]) vec2 currentCenter: Typically the current position of the Pan Gesture
156 * ([3][0],[3][1]) vec2 curveDirection: The normalized vector pointing from original center to current center
157 * ([2][2]) float vanishingPointY: The Y coordinate of the intersection of the spine
158 * and the line which goes through the original center and is vertical to the curveDirection
159 * ([2][3]) float curveEndY: The Y coordinate of intersection of the spine and the line through both original and current center
160 * ([3][2]) float curveHeight: The height of the interpolated hermite curve.
161 * ([3][3]) float currentLength: The length from the current center to the curveEnd.
163 precision mediump float;\n
164 uniform mat4 uCommonParameters;\n
166 uniform vec2 uPageSize;\n
167 uniform float uIsTurningBack;\n
168 uniform float uShadowWidth;\n
169 varying vec3 vNormal;\n
170 varying vec4 vPosition;\n
171 varying float vEdgeShadow;\n
175 vec4 position = vec4( aPosition.xy, 0.0, 1.0);\n
176 vec2 currentCenter = vec2( uCommonParameters[1][2], uCommonParameters[1][3]);\n
177 vec2 originalCenter = vec2( uCommonParameters[0][2], uCommonParameters[0][3]);\n
178 vec3 normal = vec3(0.0,0.0,1.0);\n
180 if(currentCenter.x < originalCenter.x)\n
182 // change the coordinate origin from the center of the page to its top-left
183 position.xy += uPageSize * 0.5;\n
184 vec2 curveDirection = vec2( uCommonParameters[3]);\n
185 vec3 vanishingPoint = vec3(0.0, uCommonParameters[2][2], 0.0);\n
186 // first part of the page, (outside the the line passing through original center and vertical to curve direction)
187 //no Z change, only 2D rotation and translation
188 if( dot(curveDirection, position.xy - originalCenter) < 0.0 )
190 position.y -= vanishingPoint.y;\n
191 position.xy = mat2(uCommonParameters)*position.xy + vec2( uCommonParameters[2]);\n
193 // second part of the page, bent as a ruled surface
196 // calculate on the flat plane, between
197 // the first line passing through current vertex and vanishing point
198 // the second line passing through original center and current center
199 vec2 curveEnd = vec2( 0.0, uCommonParameters[2][3] );\n
200 vec2 curFlatDirection = vec2(0.0,1.0);\n
201 float lengthFromCurve = position.y - originalCenter.y;\n
202 float lengthOnCurve = position.x;\n
203 if(currentCenter.y != originalCenter.y)\n
205 curFlatDirection = normalize(position.xy - vanishingPoint.xy);\n
206 lengthFromCurve = (curveEnd.x*curveDirection.y-curveEnd.y*curveDirection.x-position.x*curveDirection.y+position.y*curveDirection.x)
207 / (curFlatDirection.x*curveDirection.y-curFlatDirection.y*curveDirection.x);\n
208 lengthOnCurve = length(position.xy+lengthFromCurve*curFlatDirection-curveEnd);\n
211 // define the control points of hermite curve, composed with two segments
212 // calulation is carried out on the 2D plane which is passing through both current and original center and vertical to the image plane
213 float currentLength = uCommonParameters[3][3];\n
214 float originalLength = abs(originalCenter.x/curveDirection.x);\n
215 float height = uCommonParameters[3][2];\n
216 float percentage = currentLength/originalLength;\n
217 //vec2 SegmentOneControlPoint0 = vec2(0.0, 0.0);
218 vec2 SegmentOneControlPoint1 = vec2((0.65*percentage - 0.15)*originalLength, (0.8 + 0.2 * percentage)*height); \n
219 vec2 SegmentTwoControlPoint0 = SegmentOneControlPoint1;\n
220 vec2 SegmentTwoControlPoint1 = vec2(currentLength, 0.0); \n
221 vec2 SegmentOneTangentVector0 = SegmentOneControlPoint1;\n
222 vec2 SegmentOneTangentVector1 = vec2(0.5*originalLength,0.0);\n
223 vec2 SegmentTwoTangentVector0 = SegmentOneTangentVector1;\n
224 vec2 SegmentTwoTangentVector1 = SegmentOneTangentVector1;\n
226 // calulate the corresponding curve point position and its tangent vector
227 // it is a linear mapping onto nonlinear curves, might cause some unwanted deformation
228 // but as there are no analytical method to calculate the curve length on arbitrary segment
229 // no efficient way to solve this nonlinear mapping, Numerical approximation would cost too much computation in shader
232 float t0 = lengthOnCurve / originalLength;\n
238 curvePoint2D = (-2.0*t_3+3.0*t_2)*SegmentOneControlPoint1
239 + (t_3-2.0*t_2+t)*SegmentOneTangentVector0 + (t_3-t_2)*SegmentOneTangentVector1;\n
240 tangent = (-6.0*t_2+6.0*t)*SegmentOneControlPoint1
241 + (3.0*t_2-4.0*t+1.0)*SegmentOneTangentVector0 + (3.0*t_2-2.0*t)*SegmentOneTangentVector1;\n
245 float t = 2.0*t0-1.0;\n
248 curvePoint2D = (2.0*t_3-3.0*t_2+1.0)*SegmentTwoControlPoint0 + (-2.0*t_3+3.0*t_2)*SegmentTwoControlPoint1
249 + (t_3-2.0*t_2+t)*SegmentTwoTangentVector0 + (t_3-t_2)*SegmentTwoTangentVector1;\n
250 tangent = (6.0*t_2-6.0*t)*SegmentTwoControlPoint0 + (-6.0*t_2+6.0*t)*SegmentTwoControlPoint1
251 + (3.0*t_2-4.0*t+1.0)*SegmentTwoTangentVector0 + (3.0*t_2-2.0*t)*SegmentTwoTangentVector1;\n
252 // a trick to eliminate some optical illusion caused by the gradient matter of normal in per-fragment shading
253 // which is caused by linear interpolation of normal vs. nonlinear lighting
254 // will notice some artifact in the areas with dramatically normal changes, so compress the normal differences here
255 tangent.y *= min(1.0, length(position.xyz - vanishingPoint) / uPageSize.y ); \n
257 vec3 curvePoint = vec3(curveEnd - curvePoint2D.x*curveDirection,max(0.0,curvePoint2D.y));\n
258 vec3 tangentVector = vec3(-tangent.x*curveDirection,tangent.y);\n
260 // locate the new vertex position on the line passing through both vanishing point and the calculated curve point position
261 vec3 curLiftDirection = vec3(0.0,-1.0,0.0);\n
262 if(currentCenter.y != originalCenter.y)\n
264 curLiftDirection = normalize(curvePoint - vanishingPoint);\n
265 tangentVector *= (curveDirection.y > 0.0) ? -1.0 : 1.0;\n
266 // an heuristic adjustment here, to compensate the linear parameter mapping onto the nonlinear curve
267 float Y0 = position.y - curveDirection.y * (position.x/curveDirection.x); \n
270 if(abs(Y0-vanishingPoint.y) > abs(curveEnd.y-vanishingPoint.y)) \n
272 proportion = abs(curveEnd.y - Y0) / (abs(curveEnd.y-Y0)+abs(curveEnd.y - vanishingPoint.y)); \n
273 refLength = proportion*length(originalCenter-vanishingPoint.xy) / (proportion-1.0); \n
277 proportion = abs(curveEnd.y - Y0) / abs(curveEnd.y - vanishingPoint.y);\n
278 refLength = proportion*length(originalCenter-vanishingPoint.xy); \n
280 float Y1 = currentCenter.y - (normalize(currentCenter-vanishingPoint.xy)).y * refLength; \n
281 position.y = mix(Y0, Y1, t0); \n
283 position.xz = curvePoint.xz - lengthFromCurve*curLiftDirection.xz;\n
284 // calculate the normal vector, will be used for lighting
285 normal = cross(curLiftDirection, normalize(tangentVector));\n
286 // the signature of Z is decided by the page turning direction:
287 // from left to right(negative); from right to left (positive)
288 position.z *= -uIsTurningBack;\n
289 normal.xy *= -uIsTurningBack;\n
291 // change the coordinate origin from the top-left of the page to its center
292 position.xy -= uPageSize * 0.5; \n
294 position.z += aPosition.z;\n
295 gl_Position = uMvpMatrix * position;\n
296 // varying parameters for fragment shader
297 vTexCoord = aTexCoord;
298 vNormal = uNormalMatrix*normal;\n
299 vPosition = uModelView * position;\n
302 std::string vertexShaderWithFakedShadow = MAKE_STRING(
303 // display shadow, the fake shadow value is calculated according to the height and the distance from page edge
304 vTexCoord.x = (aTexCoord.x-sTextureRect.s) /( 1.0 - uShadowWidth ) + sTextureRect.s;\n
305 vTexCoord.y = ( aTexCoord.y-sTextureRect.t-0.5*uShadowWidth*(sTextureRect.q-sTextureRect.t) )/( 1.0 - uShadowWidth ) + sTextureRect.t;\n
306 float heightCoef = (1.0 + position.z*uIsTurningBack*3.0 / uPageSize.x) * 0.6;
307 vEdgeShadow = clamp(0.9 - heightCoef, 0.0, 0.9 ); \n
308 if( vTexCoord.y >= sTextureRect.q || vTexCoord.y <= sTextureRect.t || vTexCoord.x >= sTextureRect.p )\n
310 float inversedShadowWidth = (1.0-uShadowWidth) / uShadowWidth ;\n
311 float alpha1 = (vTexCoord.x-sTextureRect.p) * inversedShadowWidth / (sTextureRect.p - sTextureRect.s);\n
312 inversedShadowWidth = 2.0 * inversedShadowWidth / (sTextureRect.q - sTextureRect.t); \n
313 float alpha2 = (vTexCoord.y-sTextureRect.q) * inversedShadowWidth;\n
314 float alpha3 = (sTextureRect.t-vTexCoord.y) * inversedShadowWidth;\n
316 if(alpha1 > 0.0 && alpha2 > 0.0) alpha = sqrt(alpha2*alpha2+alpha1*alpha1)/sqrt(1.0 + max(alpha1,alpha2)*max(alpha1,alpha2));\n //bottom-right corner
317 else if(alpha1 > 0.0 && alpha3 > 0.0) alpha = sqrt(alpha3*alpha3+alpha1*alpha1)/sqrt(1.0+max(alpha1,alpha3)*max(alpha1,alpha3));\n //top-right corner
318 else alpha = max(alpha1,max(alpha2,alpha3)); \n
319 alpha = 0.9 - alpha*0.9;\n
320 vEdgeShadow = clamp(alpha - heightCoef, 0.0, 0.9 ); \n
324 std::string vertexShaderEnd("}");
326 std::string fragmentShaderPartOne = MAKE_STRING(
327 precision mediump float;\n
328 uniform vec2 uPageSize;\n
329 uniform vec2 uSpineShadowParameter;\n
330 varying vec3 vNormal;\n
331 varying vec4 vPosition;\n
332 varying float vEdgeShadow;\n
336 // need to re-normalize the interpolated normal
337 vec3 normal = normalize(vNormal);\n
339 float spineShadowCoef = 1.0; \n
342 std::string fragmentShaderWithFakedShadow = MAKE_STRING(
343 if( vTexCoord.y > sTextureRect.q || vTexCoord.y < sTextureRect.t || vTexCoord.x > sTextureRect.p )\n
344 texel = vec4(0.0,0.0,0.0,vEdgeShadow);
348 std::string fragmentShaderPartTwo = MAKE_STRING(
350 // display page content
351 // display back image of the page, flip the texture
352 if( dot(vPosition.xyz, normal) > 0.0 ) texel = texture2D( sTexture, vec2( sTextureRect.p+sTextureRect.s-vTexCoord.x, vTexCoord.y ) );\n
353 // display front image of the page
354 else texel = texture2D( sTexture, vTexCoord );\n
355 // display book spine, a stripe of shadowed texture
356 float pixelPos = (vTexCoord.x-sTextureRect.s)*uPageSize.x; \n
357 if(pixelPos < uSpineShadowParameter.x) \n
359 float x = pixelPos - uSpineShadowParameter.x;\n
360 float y = sqrt( uSpineShadowParameter.x*uSpineShadowParameter.x - x*x);\n
361 spineShadowCoef = normalize( vec2( uSpineShadowParameter.y*x/uSpineShadowParameter.x, y ) ).y;\n
364 // calculate the lighting
365 // set the ambient color as vec3(0.4);
366 float lightColor = abs( normal.z ) * 0.6 + 0.4;\n
367 gl_FragColor = vec4( ( spineShadowCoef* lightColor)* texel.rgb , texel.a ) * uColor;\n
371 // Create the implementation, temporarily owned on stack,
372 Dali::ShaderEffect shaderEffectCustom;
373 std::ostringstream vertexShaderStringStream;
374 std::ostringstream fragmentShaderStringStream;
377 vertexShaderStringStream<< vertexShader << vertexShaderWithFakedShadow << vertexShaderEnd;
378 fragmentShaderStringStream<< fragmentShaderPartOne << fragmentShaderWithFakedShadow << fragmentShaderPartTwo;
379 shaderEffectCustom = Dali::ShaderEffect::New( vertexShaderStringStream.str(), fragmentShaderStringStream.str(), GeometryType( GEOMETRY_TYPE_IMAGE ),
380 ShaderEffect::GeometryHints( ShaderEffect::HINT_GRID | ShaderEffect::HINT_DEPTH_BUFFER | ShaderEffect::HINT_BLENDING) );
384 vertexShaderStringStream<< vertexShader << vertexShaderEnd;
385 fragmentShaderStringStream<< fragmentShaderPartOne << fragmentShaderPartTwo;
386 shaderEffectCustom = Dali::ShaderEffect::New( vertexShaderStringStream.str(), fragmentShaderStringStream.str(), GeometryType( GEOMETRY_TYPE_IMAGE ),
387 ShaderEffect::GeometryHints( ShaderEffect::HINT_GRID | ShaderEffect::HINT_DEPTH_BUFFER ) );
390 PageTurnEffect* shaderImpl = new PageTurnEffect();
391 Dali::Toolkit::PageTurnEffect handle = Toolkit::PageTurnEffect( shaderEffectCustom, shaderImpl );
393 shaderImpl->Initialize( handle );
395 Vector2 defaultPageSize = Dali::Stage::GetCurrent().GetSize();
396 Matrix zeroMatrix(true);
397 handle.SetUniform( "uCommonParameters", zeroMatrix );
398 handle.SetUniform( PAGE_SIZE_PROPERTY_NAME, defaultPageSize/(1.f-DEFAULT_SHADOW_WIDTH) );
399 handle.SetUniform( SHADOW_WIDTH_PROPERTY_NAME, DEFAULT_SHADOW_WIDTH );
400 handle.SetUniform( SPINE_SHADOW_PARAMETER_PROPERTY_NAME, DEFAULT_SPINE_SHADOW_PARAMETER );
402 shaderImpl->mOriginalCenterPropertyIndex = handle.RegisterProperty( ORIGINAL_CENTER_PROPERTY_NAME, Vector2( defaultPageSize[0], defaultPageSize[1]*0.5f ) );
403 shaderImpl->mCurrentCenterPropertyIndex = handle.RegisterProperty( CURRENT_CENTER_PROPERTY_NAME, Vector2( defaultPageSize[0], defaultPageSize[1]*0.5f ) );
404 shaderImpl->mInternalConstraint = Constraint::New<Matrix>( handle.GetPropertyIndex( "uCommonParameters" ),
405 LocalSource( shaderImpl->mOriginalCenterPropertyIndex ),
406 LocalSource( shaderImpl->mCurrentCenterPropertyIndex ),
407 LocalSource( handle.GetPropertyIndex( PAGE_SIZE_PROPERTY_NAME ) ),
408 CommonParametersConstraint() );
409 handle.ApplyConstraint( shaderImpl->mInternalConstraint );
411 // setting isTurningBack to -1.0f here means turning page forward
412 handle.SetUniform( IS_TURNING_BACK_PROPERTY_NAME, -1.0f );
417 void PageTurnEffect::SetPageSize(const Vector2& pageSize)
419 mShaderEffect.SetUniform(PAGE_SIZE_PROPERTY_NAME, pageSize);
422 void PageTurnEffect::SetOriginalCenter(const Vector2& originalCenter)
424 mShaderEffect.SetProperty( mOriginalCenterPropertyIndex, originalCenter );
427 void PageTurnEffect::SetCurrentCenter(const Vector2& currentCenter)
429 mShaderEffect.SetProperty( mCurrentCenterPropertyIndex, currentCenter );
432 void PageTurnEffect::SetIsTurningBack(bool isTurningBack)
434 float direction = isTurningBack ? 1.0f : -1.0f;
435 mShaderEffect.SetUniform(IS_TURNING_BACK_PROPERTY_NAME, direction);
438 void PageTurnEffect::SetShadowWidth(float shadowWidth)
440 mShaderEffect.SetUniform( SHADOW_WIDTH_PROPERTY_NAME, shadowWidth );
443 void PageTurnEffect::SetSpineShadowParameter(const Vector2& spineShadowParameter)
445 mShaderEffect.SetUniform( SPINE_SHADOW_PARAMETER_PROPERTY_NAME, spineShadowParameter);
448 void PageTurnEffect::ApplyInternalConstraint()
450 mShaderEffect.ApplyConstraint( mInternalConstraint );
453 const std::string& PageTurnEffect::GetPageSizePropertyName() const
455 return PAGE_SIZE_PROPERTY_NAME;
458 const std::string& PageTurnEffect::GetOriginalCenterPropertyName() const
460 return ORIGINAL_CENTER_PROPERTY_NAME;
463 const std::string& PageTurnEffect::GetCurrentCenterPropertyName() const
465 return CURRENT_CENTER_PROPERTY_NAME;
468 void PageTurnEffect::Initialize( Dali::ShaderEffect shaderEffect )
470 // Save a reference to the shader handle
471 mShaderEffect = shaderEffect;
474 } // namespace Internal
476 } // namespace Toolkit