Conversion to Apache 2.0 license
[platform/core/uifw/dali-toolkit.git] / optional / dali-toolkit / internal / controls / shadow-view / shadow-view-impl.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 "shadow-view-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <sstream>
23 #include <iomanip>
24
25 // INTERNAL INCLUDES
26 #include <dali-toolkit/internal/controls/shadow-view/shadow-view-impl.h>
27 #include <dali-toolkit/internal/filters/blur-two-pass-filter.h>
28 #include <dali/integration-api/debug.h>
29
30 // TODO:
31 // pixel format / size - set from JSON
32 // aspect ratio property needs to be able to be constrained also for cameras. (now do-able)
33 // default near clip value
34 // mChildrenRoot Add()/Remove() overloads - better solution
35
36
37 /////////////////////////////////////////////////////////
38 // IMPLEMENTATION NOTES
39
40 // As the ShadowView actor changes size, the amount of pixels we need to blur changes. Therefore we need some way of doing this. However:-
41 // OnSetSize() does not get called when ShadowView object size is modified using a Constraint.
42 // OnSizeAnimation() only gets called once per AnimateTo/By() and if an Animation has N such calls then only the final one will end up being used. Therefore we can't use
43 // OnSizeAnimation() to alter render target sizes.
44 // To get around the above problems, we use fixed sized render targets, from the last SetSize() call (which calls OnSetSize()), then we adjust the internal cameras / actors
45 // to take account of the changed ShadowView object size, projecting to the unchanged render target sizes. This is done relative to the fixed render target / actor sizes
46 // by using constraints relative to the ShadowView actor size.
47
48 namespace Dali
49 {
50
51 namespace Toolkit
52 {
53
54 namespace Internal
55 {
56
57 namespace
58 {
59
60 using namespace Dali;
61
62 BaseHandle Create()
63 {
64   return Toolkit::ShadowView::New();
65 }
66
67 TypeRegistration mType( typeid(Toolkit::ShadowView), typeid(Toolkit::Control), Create );
68
69
70 const float BLUR_STRENGTH_DEFAULT = 1.0f;
71
72 const Vector3 DEFAULT_LIGHT_POSITION(300.0f, 250.0f, 600.0f);
73 const float DEFAULT_FIELD_OF_VIEW_RADIANS = Math::PI / 4.0f; // 45 degrees
74
75 const Vector4 DEFAULT_SHADOW_COLOR = Vector4(0.2f, 0.2f, 0.2f, 0.8f);
76
77 const std::string SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME( "uLightCameraProjectionMatrix" );
78 const std::string SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME( "uLightCameraViewMatrix" );
79 const std::string SHADER_SHADOW_COLOR_PROPERTY_NAME( "uShadowColor" );
80
81 const std::string BLUR_STRENGTH_PROPERTY_NAME( "BlurStrengthProperty" );
82 const std::string SHADOW_COLOR_PROPERTY_NAME( "ShadowColorProperty" );
83
84 const char* const RENDER_SHADOW_VERTEX_SOURCE =
85   " uniform mediump mat4 uLightCameraProjectionMatrix;\n"
86   " uniform mediump mat4 uLightCameraViewMatrix;\n"
87   "\n"
88   "void main()\n"
89   "{\n"
90     "  gl_Position = uProjection * uModelView * vec4(aPosition,1.0);\n"
91     "  vec4 textureCoords = uLightCameraProjectionMatrix * uLightCameraViewMatrix * uModelMatrix  * vec4(aPosition,1.0);\n"
92     "  vTexCoord = 0.5 + 0.5 * (textureCoords.xy/textureCoords.w);\n"
93   "}\n";
94
95 const char* const RENDER_SHADOW_FRAGMENT_SOURCE =
96   "uniform lowp vec4 uShadowColor;\n"
97   "void main()\n"
98   "{\n"
99   "  lowp float alpha;\n"
100   "  alpha = texture2D(sTexture, vec2(vTexCoord.x, vTexCoord.y)).a;\n"
101   "  gl_FragColor = vec4(uShadowColor.rgb, uShadowColor.a * alpha);\n"
102   "}\n";
103
104 // TODO: Add this to dali-core constraints.h
105 /**
106  * EqualToConstraintMatrix
107  *
108  * f(current, property) = property
109  */
110 struct EqualToConstraintMatrix
111 {
112   EqualToConstraintMatrix(){}
113
114   Dali::Matrix operator()(const Dali::Matrix& current, const PropertyInput& property) {return property.GetMatrix();}
115 };
116
117 } // namespace
118
119 ShadowView::ShadowView( float downsampleWidthScale, float downsampleHeightScale )
120 : Control( CONTROL_BEHAVIOUR_NONE ),
121   mChildrenRoot(Actor::New()),
122   mCachedShadowColor(DEFAULT_SHADOW_COLOR),
123   mCachedBackgroundColor(DEFAULT_SHADOW_COLOR.r, DEFAULT_SHADOW_COLOR.g, DEFAULT_SHADOW_COLOR.b, 0.0f),
124   mBlurStrengthPropertyIndex(Property::INVALID_INDEX),
125   mShadowColorPropertyIndex(Property::INVALID_INDEX),
126   mDownsampleWidthScale(downsampleWidthScale),
127   mDownsampleHeightScale(downsampleHeightScale)
128 {
129 }
130
131 ShadowView::~ShadowView()
132 {
133 }
134
135 Toolkit::ShadowView ShadowView::New(float downsampleWidthScale, float downsampleHeightScale)
136 {
137   ShadowView* impl = new ShadowView(downsampleWidthScale, downsampleHeightScale);
138
139   Dali::Toolkit::ShadowView handle = Dali::Toolkit::ShadowView( *impl );
140
141   // Second-phase init of the implementation
142   // This can only be done after the CustomActor connection has been made...
143   impl->Initialize();
144
145   return handle;
146 }
147
148 /////////////////////////////////////////////////////////////
149 // for creating a subtree for all user added child actors.
150 // TODO: overloading Actor::Add()/Remove() not nice since breaks polymorphism. Need another method to pass ownership of added child actors to our internal actor root.
151 void ShadowView::Add(Actor child)
152 {
153   mChildrenRoot.Add(child);
154 }
155
156 void ShadowView::Remove(Actor child)
157 {
158   mChildrenRoot.Remove(child);
159 }
160
161 void ShadowView::SetShadowPlane(Actor shadowPlane)
162 {
163   mShadowPlaneBg = shadowPlane;
164
165   mShadowPlane = ImageActor::New();
166   mShadowPlane.SetParentOrigin(ParentOrigin::CENTER);
167   mShadowPlane.SetAnchorPoint(AnchorPoint::CENTER);
168
169   mShadowPlane.SetImage(mOutputImage);
170   mShadowPlane.SetShaderEffect(mShadowRenderShader);
171
172   // Rather than parent the shadow plane drawable and have constraints to move it to the same
173   // position, instead parent the shadow plane drawable on the shadow plane passed in.
174   mShadowPlaneBg.Add(mShadowPlane);
175   mShadowPlane.SetParentOrigin(ParentOrigin::CENTER);
176   mShadowPlane.SetZ(1.0f);
177
178   ConstrainCamera();
179
180   mShadowPlane.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, Source( mShadowPlaneBg, Actor::SIZE ), EqualToConstraint() ) );
181
182   mBlurRootActor.ApplyConstraint( Constraint::New<Vector3>( Actor::SIZE, Source( mShadowPlane, Actor::SIZE ), EqualToConstraint() ) );
183 }
184
185 void ShadowView::SetPointLight(Actor pointLight)
186 {
187   mPointLight = pointLight;
188
189   ConstrainCamera();
190 }
191
192 void ShadowView::SetPointLightFieldOfView(float fieldOfView)
193 {
194   mCameraActor.SetFieldOfView(fieldOfView);
195 }
196
197 void ShadowView::SetShadowColor(Vector4 color)
198 {
199   mCachedShadowColor = color;
200   mCachedBackgroundColor.r = color.r;
201   mCachedBackgroundColor.g = color.g;
202   mCachedBackgroundColor.b = color.b;
203
204   Self().SetProperty( mShadowColorPropertyIndex, mCachedShadowColor );
205   if(mRenderSceneTask)
206   {
207     mRenderSceneTask.SetClearColor( mCachedBackgroundColor );
208   }
209 }
210
211 void ShadowView::Activate()
212 {
213   DALI_ASSERT_ALWAYS( Self().OnStage() && "ShadowView should be on stage before calling Activate()\n" );
214
215   // make sure resources are allocated and start the render tasks processing
216   CreateRenderTasks();
217 }
218
219 void ShadowView::Deactivate()
220 {
221   DALI_ASSERT_ALWAYS( Self().OnStage() && "ShadowView should be on stage before calling Deactivate()\n" )
222
223   // stop render tasks processing
224   // Note: render target resources are automatically freed since we set the Image::Unused flag
225   RemoveRenderTasks();
226 }
227
228 ///////////////////////////////////////////////////////////
229 //
230 // Private methods
231 //
232
233 void ShadowView::OnInitialize()
234 {
235   // root actor to parent all user added actors. Used as source actor for shadow render task.
236   mChildrenRoot.SetPositionInheritanceMode( Dali::USE_PARENT_POSITION );
237   mChildrenRoot.ApplyConstraint(Constraint::New<Vector3>( Actor::SIZE, ParentSource( Actor::SIZE ), EqualToConstraint() ));
238
239   Vector2 stageSize = Stage::GetCurrent().GetSize();
240   mCameraActor = CameraActor::New(stageSize);
241
242   mCameraActor.SetParentOrigin( ParentOrigin::CENTER );
243
244   // Target is constrained to point at the shadow plane origin
245   mCameraActor.SetNearClippingPlane( 1.0f );
246   mCameraActor.SetType( Dali::Camera::FREE_LOOK ); // Camera orientation constrained to point at shadow plane world position
247   mCameraActor.SetRotation(Radian(Degree(180)), Vector3::YAXIS);
248   mCameraActor.SetPosition(DEFAULT_LIGHT_POSITION);
249
250   mShadowRenderShader = ShaderEffect::New( RENDER_SHADOW_VERTEX_SOURCE, RENDER_SHADOW_FRAGMENT_SOURCE,
251                                            Dali::GeometryType( GEOMETRY_TYPE_IMAGE ),
252                                            ShaderEffect::GeometryHints( ShaderEffect::HINT_GRID | ShaderEffect::HINT_BLENDING ));
253
254   // Create render targets needed for rendering from light's point of view
255   mSceneFromLightRenderTarget = FrameBufferImage::New( stageSize.width, stageSize.height, Pixel::RGBA8888 );
256
257   mOutputImage = FrameBufferImage::New( stageSize.width * 0.5f, stageSize.height * 0.5f, Pixel::RGBA8888 );
258
259   //////////////////////////////////////////////////////
260   // Connect to actor tree
261
262   Self().Add( mChildrenRoot );
263   Stage::GetCurrent().Add( mCameraActor );
264
265   mBlurFilter.SetRefreshOnDemand(false);
266   mBlurFilter.SetInputImage(mSceneFromLightRenderTarget);
267   mBlurFilter.SetOutputImage(mOutputImage);
268   mBlurFilter.SetSize(stageSize * 0.5f);
269   mBlurFilter.SetPixelFormat(Pixel::RGBA8888);
270
271   mBlurRootActor = Actor::New();
272
273   // Turn off inheritance to ensure filter renders properly
274   mBlurRootActor.SetPositionInheritanceMode(USE_PARENT_POSITION);
275   mBlurRootActor.SetInheritRotation(false);
276   mBlurRootActor.SetInheritScale(false);
277   mBlurRootActor.SetColorMode(USE_OWN_COLOR);
278
279   Self().Add(mBlurRootActor);
280
281   mBlurFilter.SetRootActor(mBlurRootActor);
282   mBlurFilter.SetBackgroundColor(Vector4::ZERO);
283
284   SetShaderConstants();
285 }
286
287 void ShadowView::OnSizeSet(const Vector3& targetSize)
288 {
289 }
290
291 void ShadowView::OnStageConnection()
292 {
293   // TODO: can't call this here, since SetImage() calls fail to connect images to stage, since parent chain not fully on stage yet
294   // Need to fix the stage connection so this callback can be used arbitrarily. At that point we  can simplify the API by removing the need for Activate() / Deactivate()
295   //Activate();
296 }
297
298 void ShadowView::OnStageDisconnection()
299 {
300   // TODO: can't call this here, since SetImage() calls fails similarly to above
301   // Need to fix the stage connection so this callback can be used arbitrarily. At that point we  can simplify the API by removing the need for Activate() / Deactivate()
302   //Deactivate();
303 }
304
305 void ShadowView::ConstrainCamera()
306 {
307   if( mPointLight && mShadowPlane )
308   {
309     // Constrain camera to look directly at center of shadow plane. (mPointLight position
310     // is under control of application, can't use transform inheritance)
311
312     Constraint cameraOrientationConstraint =
313       Constraint::New<Quaternion> ( Actor::ROTATION,
314                                     Source( mShadowPlane, Actor::WORLD_POSITION ),
315                                     Source( mPointLight,  Actor::WORLD_POSITION ),
316                                     Source( mShadowPlane, Actor::WORLD_ROTATION ),
317                                     &LookAt );
318
319     mCameraActor.ApplyConstraint( cameraOrientationConstraint );
320
321     Constraint pointLightPositionConstraint = Constraint::New<Vector3>( Actor::POSITION, Source( mPointLight, Actor::WORLD_POSITION ), EqualToConstraint() );
322
323     mCameraActor.ApplyConstraint( pointLightPositionConstraint );
324   }
325 }
326
327 void ShadowView::CreateRenderTasks()
328 {
329   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
330
331   // We want the first task to render the scene from the light
332   mRenderSceneTask = taskList.CreateTask();
333
334   mRenderSceneTask.SetCameraActor( mCameraActor );
335   mRenderSceneTask.SetSourceActor( mChildrenRoot );
336   mRenderSceneTask.SetTargetFrameBuffer( mSceneFromLightRenderTarget );
337   mRenderSceneTask.SetInputEnabled( false );
338   mRenderSceneTask.SetClearEnabled( true );
339
340   // background color for render task should be the shadow color, but with alpha 0
341   // we don't want to blend the edges of the content with a BLACK at alpha 0, but
342   // the same shadow color at alpha 0.
343   mRenderSceneTask.SetClearColor( mCachedBackgroundColor );
344
345   mBlurFilter.Enable();
346 }
347
348 void ShadowView::RemoveRenderTasks()
349 {
350   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
351
352   taskList.RemoveTask(mRenderSceneTask);
353   mRenderSceneTask.Reset();
354
355   mBlurFilter.Disable();
356 }
357
358 void ShadowView::SetShaderConstants()
359 {
360   CustomActor self = Self();
361
362   mShadowRenderShader.SetUniform( SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME, Matrix::IDENTITY );
363   mShadowRenderShader.SetUniform( SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME, Matrix::IDENTITY );
364   mShadowRenderShader.SetUniform( SHADER_SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor );
365
366   Property::Index lightCameraProjectionMatrixPropertyIndex = mShadowRenderShader.GetPropertyIndex(SHADER_LIGHT_CAMERA_PROJECTION_MATRIX_PROPERTY_NAME);
367   Property::Index lightCameraViewMatrixPropertyIndex = mShadowRenderShader.GetPropertyIndex(SHADER_LIGHT_CAMERA_VIEW_MATRIX_PROPERTY_NAME);
368
369   Constraint projectionMatrixConstraint = Constraint::New<Dali::Matrix>( lightCameraProjectionMatrixPropertyIndex, Source( mCameraActor, CameraActor::PROJECTION_MATRIX ), EqualToConstraintMatrix());
370   Constraint viewMatrixConstraint = Constraint::New<Dali::Matrix>( lightCameraViewMatrixPropertyIndex, Source( mCameraActor, CameraActor::VIEW_MATRIX ), EqualToConstraintMatrix());
371
372   mShadowRenderShader.ApplyConstraint(projectionMatrixConstraint);
373   mShadowRenderShader.ApplyConstraint(viewMatrixConstraint);
374
375   // Register a property that the user can use to control the blur in the internal object
376   mBlurStrengthPropertyIndex = self.RegisterProperty(BLUR_STRENGTH_PROPERTY_NAME, BLUR_STRENGTH_DEFAULT);
377   mBlurFilter.GetHandleForAnimateBlurStrength().ApplyConstraint( Constraint::New<float>( mBlurFilter.GetBlurStrengthPropertyIndex() ,
378                                                                            Source( self, mBlurStrengthPropertyIndex),
379                                                                            EqualToConstraint()) );
380
381   //  Register a property that the user can use to control the color of the shadow.
382   Property::Index index = mShadowRenderShader.GetPropertyIndex(SHADER_SHADOW_COLOR_PROPERTY_NAME);
383   mShadowColorPropertyIndex = self.RegisterProperty(SHADOW_COLOR_PROPERTY_NAME, mCachedShadowColor);
384
385   mShadowRenderShader.ApplyConstraint(Constraint::New<Dali::Vector4>( index, Source( self, mShadowColorPropertyIndex ), EqualToConstraint()) );
386 }
387
388 } // namespace Internal
389
390 } // namespace Toolkit
391
392 } // namespace Dali