Moved ControlImpl to Internal namespace & renamed to Control
[platform/core/uifw/dali-toolkit.git] / optional / dali-toolkit / internal / controls / magnifier / magnifier-impl.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/internal/controls/magnifier/magnifier-impl.h>
18
19 using namespace Dali;
20
21 namespace // unnamed namespace
22 {
23
24 const char* DEFAULT_FRAME_IMAGE_PATH = DALI_IMAGE_DIR "magnifier-image-frame.png";
25
26 const float IMAGE_BORDER_INDENT = 14.0f;            ///< Indent of border in pixels.
27
28 /**
29  * ImageBorderSizeConstraint
30  */
31 struct ImageBorderSizeConstraint
32 {
33   ImageBorderSizeConstraint()
34   : mSizeOffset(Vector3(IMAGE_BORDER_INDENT - 1, IMAGE_BORDER_INDENT - 1, 0.0f) * 2.0f)
35   {
36   }
37
38   Vector3 operator()(const Vector3&    current,
39                      const PropertyInput& referenceSizeProperty)
40   {
41     const Vector3& referenceSize = referenceSizeProperty.GetVector3();
42
43     return referenceSize + mSizeOffset;
44   }
45
46   Vector3 mSizeOffset;                        ///< The amount to offset the size from referenceSize
47 };
48
49 struct CameraActorPositionConstraint
50 {
51   CameraActorPositionConstraint(const Vector2& stageSize, float defaultCameraDistance = 0.0f)
52   : mStageSize(stageSize),
53     mDefaultCameraDistance(defaultCameraDistance)
54   {
55   }
56
57   Vector3 operator()(const Vector3& current,
58                      const PropertyInput& sourcePositionProperty)
59   {
60     const Vector3& sourcePosition = sourcePositionProperty.GetVector3();
61
62     return Vector3( sourcePosition.x + mStageSize.x * 0.5f,
63                     sourcePosition.y + mStageSize.y * 0.5f,
64                     sourcePosition.z + mDefaultCameraDistance);
65   }
66
67   Vector2 mStageSize;
68   float mDefaultCameraDistance;
69
70 };
71
72 struct RenderTaskViewportPositionConstraint
73 {
74   RenderTaskViewportPositionConstraint(const Vector2& stageSize)
75   : mStageSize(stageSize)
76   {
77   }
78
79   Vector2 operator()(const Vector2& current,
80                      const PropertyInput& positionProperty,
81                      const PropertyInput& magnifierSizeProperty,
82                      const PropertyInput& magnifierScaleProperty)
83   {
84     Vector2 position(positionProperty.GetVector3()); // World position?
85
86     //position -= mStageSize * 0.5f;
87
88     // should be updated when:
89     // Magnifier's world position/size/scale/parentorigin/anchorpoint changes.
90     // or Magnifier camera's world position changes.
91     Vector3 size = magnifierSizeProperty.GetVector3() * magnifierScaleProperty.GetVector3();
92
93     // Reposition, and resize viewport to reflect the world bounds of this Magnifier actor.
94     position.x += (mStageSize.width - size.width) * 0.5f;
95     position.y += (mStageSize.height - size.height) * 0.5f;
96
97     return position;
98   }
99
100   Vector2 mStageSize;
101 };
102
103 struct RenderTaskViewportSizeConstraint
104 {
105   RenderTaskViewportSizeConstraint()
106   {
107   }
108
109   Vector2 operator()(const Vector2& current,
110                      const PropertyInput& magnifierSizeProperty,
111                      const PropertyInput& magnifierScaleProperty)
112   {
113     return Vector2(magnifierSizeProperty.GetVector3() * magnifierScaleProperty.GetVector3());
114   }
115 };
116
117 /**
118  * Returns relative border (0.0f...1.0f x 0.0f...1.0f)
119  * from an absolute pixel specified border.
120  * @param[in] absolute A border using absolute pixel coordinates
121  * @param[in] width The width of the texture
122  * @param[in] height The height of the texture.
123  * @return A border relative to the size of the Image texture dimensions.
124  */
125 Vector4 GetRelativeBorder(Vector4 absolute, float width, float height)
126 {
127   return Vector4( absolute.x / width,
128                   absolute.y / height,
129                   absolute.z / width,
130                   absolute.w / height);
131 }
132
133 }
134
135 namespace Dali
136 {
137
138 namespace Toolkit
139 {
140
141 namespace Internal
142 {
143
144 ///////////////////////////////////////////////////////////////////////////////////////////////////
145 // Magnifier
146 ///////////////////////////////////////////////////////////////////////////////////////////////////
147
148 Dali::Toolkit::Magnifier Magnifier::New()
149 {
150   // Create the implementation
151   MagnifierPtr magnifier(new Magnifier());
152
153   // Pass ownership to CustomActor via derived handle
154   Dali::Toolkit::Magnifier handle(*magnifier);
155
156   // Second-phase init of the implementation
157   // This can only be done after the CustomActor connection has been made...
158   magnifier->Initialize();
159
160   return handle;
161 }
162
163 Magnifier::Magnifier()
164 : Control(true),
165   mPropertySourcePosition(Property::INVALID_INDEX),
166   mActorSize(Vector3::ZERO),
167   mMagnificationFactor(1.0f)
168 {
169 }
170
171 void Magnifier::SetSourceActor(Actor actor)
172 {
173   mTask.SetSourceActor( actor );
174 }
175
176 void Magnifier::SetSourcePosition(const Vector3& position)
177 {
178   Self().SetProperty(mPropertySourcePosition, position);
179 }
180
181 void Magnifier::Initialize()
182 {
183   Actor self = Self();
184   mPropertySourcePosition = self.RegisterProperty( Toolkit::Magnifier::SOURCE_POSITION_PROPERTY_NAME, Vector3::ZERO );
185   Vector2 stageSize(Stage::GetCurrent().GetSize());
186
187   Layer dummyLayer = Layer::New();
188   Stage().GetCurrent().Add(dummyLayer);
189   dummyLayer.SetParentOrigin(ParentOrigin::CENTER);
190
191   // NOTE:
192   // sourceActor is a dummy delegate actor that takes the source property position,
193   // and generates a WORLD_POSITION, which is 1 frame behind the source property.
194   // This way the constraints for determining the camera position (source) and those
195   // for determining viewport position use the same 1 frame old values.
196   // A simple i) CameraPos = f(B), ii) B = f(A) set of constraints wont suffice as
197   // although CameraPos will use B, which is A's previous value. The constraint will
198   // not realise that B is still dirty as far as constraint (i) is concerned.
199   // Perhaps this is a bug in the way the constraint system factors into what is dirty
200   // and what is not.
201   mSourceActor = Actor::New();
202   dummyLayer.Add(mSourceActor);
203   mSourceActor.SetParentOrigin(ParentOrigin::CENTER);
204   Constraint constraint = Constraint::New<Vector3>( Actor::POSITION,
205                                                     Source( self, mPropertySourcePosition ),
206                                                     EqualToConstraint() );
207   mSourceActor.ApplyConstraint(constraint);
208
209   // create the render task this will render content on top of everything
210   // based on camera source position.
211   InitializeRenderTask();
212
213   // set up some constraints to:
214   // i) reposition (dest) frame actor based on magnifier actor's world position (this is 1 frame delayed)
215   // ii) reposition and resize (dest) the render task's viewport based on magnifier actor's world position (1 frame delayed) & size.
216   // iii) reposition (source) camera actor based on magnifier source actor's world position (this is 1 frame delayed)
217
218   // Apply constraint to camera's position
219   // Position our camera at the same distance from its target as the default camera is.
220   // The camera position doesn't affect how we render, just what we render (due to near and far clip planes)
221   // NOTE: We can't interrogate the default camera's position as it is not known initially (takes 1 frame
222   // for value to update).
223   // But we can determine the initial position using the same formula:
224   // distance = stage.height * 0.5 / tan(FOV * 0.5)
225
226   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
227   RenderTask renderTask = taskList.GetTask(0u);
228   float fov = renderTask.GetCameraActor().GetFieldOfView();
229   mDefaultCameraDistance = (stageSize.height * 0.5f) / tanf(fov * 0.5f);
230
231   // Use a 1 frame delayed source position to determine the camera actor's position.
232   // This is necessary as the viewport is determined by the Magnifier's Actor's World position (which is computed
233   // at the end of the update cycle i.e. after constraints have been applied.)
234   //Property::Index propertySourcePositionDelayed = mCameraActor.RegisterProperty("delayed-source-position", Vector3::ZERO);
235
236   constraint = Constraint::New<Vector3>( Actor::POSITION,
237                                                     Source( mSourceActor, Actor::WORLD_POSITION ),
238                                                     CameraActorPositionConstraint(stageSize, mDefaultCameraDistance) );
239   mCameraActor.ApplyConstraint(constraint);
240
241   // Apply constraint to render-task viewport position
242   constraint = Constraint::New<Vector2>( RenderTask::VIEWPORT_POSITION,
243                                          Source( self, Actor::WORLD_POSITION ),//mPropertySourcePosition ),
244                                          Source( self, Actor::SIZE ),
245                                          Source( self, Actor::WORLD_SCALE),
246                                          RenderTaskViewportPositionConstraint(stageSize) );
247   mTask.ApplyConstraint(constraint);
248
249   // Apply constraint to render-task viewport position
250   constraint = Constraint::New<Vector2>( RenderTask::VIEWPORT_SIZE,
251                                          Source( self, Actor::SIZE ),
252                                          Source( self, Actor::WORLD_SCALE),
253                                          RenderTaskViewportSizeConstraint() );
254   mTask.ApplyConstraint(constraint);
255 }
256
257 Magnifier::~Magnifier()
258 {
259
260 }
261
262 void Magnifier::InitializeRenderTask()
263 {
264   Stage stage = Stage::GetCurrent();
265
266   RenderTaskList taskList = stage.GetRenderTaskList();
267
268   mTask = taskList.CreateTask();
269   mTask.SetInputEnabled(false);
270   mTask.SetClearColor(Vector4(0.5f, 0.5f, 0.5f, 1.0f));
271   mTask.SetClearEnabled(true);
272
273   mCameraActor = CameraActor::New();
274   mCameraActor.SetType(Camera::FREE_LOOK);
275   mCameraActor.SetRotation(Quaternion(M_PI, Vector3::YAXIS)); // Look at stage
276
277   stage.Add(mCameraActor);
278   mTask.SetCameraActor( mCameraActor );
279
280   SetFrameVisibility(true);
281 }
282
283 bool Magnifier::GetFrameVisibility() const
284 {
285   return mFrameLayer;
286 }
287
288 void Magnifier::SetFrameVisibility(bool visible)
289 {
290   if(visible && !mFrameLayer)
291   {
292     Actor self(Self());
293
294     Layer mFrameLayer = Layer::New();
295     mFrameLayer.SetParentOrigin( ParentOrigin::CENTER );
296     Stage::GetCurrent().Add(mFrameLayer);
297
298     Image image = Image::New( DEFAULT_FRAME_IMAGE_PATH );
299     ImageActor frame = ImageActor::New( image );
300     frame.SetDrawMode(DrawMode::OVERLAY);
301     frame.SetStyle( ImageActor::STYLE_NINE_PATCH );
302
303     frame.SetNinePatchBorder( Vector4::ONE * IMAGE_BORDER_INDENT );
304     mFrameLayer.Add(frame);
305
306     // Apply position constraint to the frame
307     Constraint constraint = Constraint::New<Vector3>( Actor::POSITION,
308                                                       Source( self, Actor::WORLD_POSITION ),
309                                                       EqualToConstraint() );
310     frame.ApplyConstraint(constraint);
311
312     // Apply scale constraint to the frame
313     constraint = Constraint::New<Vector3>( Actor::SCALE,
314                                            Source( self, Actor::SCALE ),
315                                            EqualToConstraint() );
316     frame.ApplyConstraint(constraint);
317
318     Source(self, Actor::SCALE),
319
320     // Apply size constraint to the the frame
321     constraint = Constraint::New<Vector3>(Actor::SIZE,
322                                           Source(self, Actor::SIZE),
323                                           ImageBorderSizeConstraint());
324     frame.ApplyConstraint(constraint);
325   }
326   else if(!visible && mFrameLayer)
327   {
328     Stage::GetCurrent().Remove(mFrameLayer);
329     mFrameLayer.Reset();
330   }
331 }
332
333 void Magnifier::OnControlSizeSet(const Vector3& targetSize)
334 {
335   // TODO: Once Camera/CameraActor properties function as proper animatable properties
336   // this code can disappear.
337   // whenever the size of the magnifier changes, the field of view needs to change
338   // to compensate for the new size of the viewport. this cannot be done within
339   // a constraint yet as Camera/CameraActor properties are not animatable/constrainable.
340   mActorSize = targetSize;
341   Update();
342 }
343
344 float Magnifier::GetMagnificationFactor() const
345 {
346   return mMagnificationFactor;
347 }
348
349 void Magnifier::SetMagnificationFactor(float value)
350 {
351   mMagnificationFactor = value;
352   Update();
353 }
354
355 void Magnifier::Update()
356 {
357   // TODO: Make Camera settings (fieldofview/aspectratio) as animatable constraints.
358
359   // should be updated when:
360   // Magnifier's world size/scale changes.
361   Actor self(Self());
362   Vector3 worldSize = mActorSize * self.GetCurrentWorldScale();
363
364   // Adjust field of view to scale content
365
366   // size.height / 2
367   // |------/
368   // |d    /
369   // |i   /
370   // |s  /
371   // |t /
372   // |./
373   // |/ <--- fov/2 radians.
374   //
375   const float fov = atanf( 0.5f * worldSize.height / mDefaultCameraDistance / mMagnificationFactor) * 2.0f;
376   mCameraActor.SetFieldOfView( fov );
377
378   // Adjust aspect ratio to compensate for rectangular viewports.
379   mCameraActor.SetAspectRatio( worldSize.width / worldSize.height );
380 }
381
382 } // namespace Internal
383
384 } // namespace Toolkit
385
386 } // namespace Dali