Stop Overriding Actor::Add() & Actor::Remove()
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / controls / gaussian-blur-view / gaussian-blur-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 "gaussian-blur-view-impl.h"
20
21 // EXTERNAL INCLUDES
22 #include <sstream>
23 #include <iomanip>
24 #include <dali/public-api/animation/constraint.h>
25 #include <dali/public-api/animation/constraints.h>
26 #include <dali/public-api/common/stage.h>
27 #include <dali/public-api/object/property-map.h>
28 #include <dali/public-api/object/type-registry.h>
29 #include <dali/devel-api/object/type-registry-helper.h>
30 #include <dali/public-api/render-tasks/render-task-list.h>
31 #include <dali/integration-api/debug.h>
32
33 // INTERNAL INCLUDES
34 #include <dali-toolkit/public-api/controls/gaussian-blur-view/gaussian-blur-view.h>
35
36 // TODO:
37 // pixel format / size - set from JSON
38 // aspect ratio property needs to be able to be constrained also for cameras, not possible currently. Therefore changing aspect ratio of GaussianBlurView won't currently work
39 // default near clip value
40 // Manager object - re-use render targets if there are multiple GaussianBlurViews created
41
42
43 /////////////////////////////////////////////////////////
44 // IMPLEMENTATION NOTES
45
46 // As the GaussianBlurView actor changes size, the amount of pixels we need to blur changes. Therefore we need some way of doing this. However:-
47 // OnSetSize() does not get called when GaussianBlurView object size is modified using a Constraint.
48 // 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
49 // OnSizeAnimation() to alter render target sizes.
50 // 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
51 // to take account of the changed GaussianBlurView object size, projecting to the unchanged render target sizes. This is done relative to the fixed render target / actor sizes
52 // by using constraints relative to the GaussianBlurView actor size.
53
54
55 // 2 modes:
56 // 1st mode, this control has a tree of actors (use Add() to add children) that are rendered and blurred.
57 // mRenderChildrenTask renders children to FB mRenderTargetForRenderingChildren
58 // mHorizBlurTask renders mImageActorHorizBlur Actor showing FB mRenderTargetForRenderingChildren into FB mRenderTarget2
59 // mVertBlurTask renders mImageActorVertBlur Actor showing FB mRenderTarget2 into FB mRenderTarget1
60 // mCompositeTask renders mImageActorComposite Actor showing FB mRenderTarget1 into FB mRenderTargetForRenderingChildren
61 //
62 // 2nd mode, an image is blurred and rendered to a supplied target framebuffer
63 // mHorizBlurTask renders mImageActorHorizBlur Actor showing mUserInputImage into FB mRenderTarget2
64 // mVertBlurTask renders mImageActorVertBlur Actor showing mRenderTarget2 into FB mUserOutputRenderTarget
65 //
66 // Only this 2nd mode handles ActivateOnce
67
68 namespace Dali
69 {
70
71 namespace Toolkit
72 {
73
74 namespace Internal
75 {
76
77 namespace
78 {
79
80 using namespace Dali;
81
82 BaseHandle Create()
83 {
84   return Toolkit::GaussianBlurView::New();
85 }
86
87 DALI_TYPE_REGISTRATION_BEGIN( Toolkit::GaussianBlurView, Toolkit::Control, Create )
88 DALI_TYPE_REGISTRATION_END()
89
90 const unsigned int GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES = 5;
91 const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH = 1.5f;
92 const Pixel::Format GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT = Pixel::RGBA8888;
93 const float GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH = 1.0f;                                       // default, fully blurred
94 const char* const GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME = "GaussianBlurStrengthPropertyName";
95 const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE = 0.5f;
96 const float GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE = 0.5f;
97
98 const float ARBITRARY_FIELD_OF_VIEW = Math::PI / 4.0f;
99
100 const char* const GAUSSIAN_BLUR_FRAGMENT_SOURCE =
101     "varying mediump vec2 vTexCoord;\n"
102     "uniform sampler2D sTexture;\n"
103     "uniform lowp vec4 uColor;\n"
104     "uniform mediump vec2 uSampleOffsets[NUM_SAMPLES];\n"
105     "uniform mediump float uSampleWeights[NUM_SAMPLES];\n"
106
107     "void main()\n"
108     "{\n"
109     "   mediump vec4 col = texture2D(sTexture, vTexCoord + uSampleOffsets[0]) * uSampleWeights[0];\n"
110     "   for (int i=1; i<NUM_SAMPLES; ++i)\n"
111     "   {\n"
112     "     col += texture2D(sTexture, vTexCoord + uSampleOffsets[i]) * uSampleWeights[i];\n"
113     "   }\n"
114     "   gl_FragColor = col;\n"
115     "}\n";
116
117 } // namespace
118
119
120 GaussianBlurView::GaussianBlurView()
121   : Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION ) )
122   , mNumSamples(GAUSSIAN_BLUR_VIEW_DEFAULT_NUM_SAMPLES)
123   , mBlurBellCurveWidth( 0.001f )
124   , mPixelFormat(GAUSSIAN_BLUR_VIEW_DEFAULT_RENDER_TARGET_PIXEL_FORMAT)
125   , mDownsampleWidthScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_WIDTH_SCALE)
126   , mDownsampleHeightScale(GAUSSIAN_BLUR_VIEW_DEFAULT_DOWNSAMPLE_HEIGHT_SCALE)
127   , mDownsampledWidth( 0.0f )
128   , mDownsampledHeight( 0.0f )
129   , mBlurUserImage( false )
130   , mRenderOnce( false )
131   , mBackgroundColor( Color::BLACK )
132   , mTargetSize(Vector2::ZERO)
133   , mLastSize(Vector2::ZERO)
134   , mChildrenRoot(Actor::New())
135   , mInternalRoot(Actor::New())
136   , mBlurStrengthPropertyIndex(Property::INVALID_INDEX)
137   , mActivated( false )
138 {
139   SetBlurBellCurveWidth(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_BELL_CURVE_WIDTH);
140 }
141
142 GaussianBlurView::GaussianBlurView( const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
143                                     const float downsampleWidthScale, const float downsampleHeightScale,
144                                     bool blurUserImage)
145   : Control( ControlBehaviour( DISABLE_SIZE_NEGOTIATION ) )
146   , mNumSamples(numSamples)
147   , mBlurBellCurveWidth( 0.001f )
148   , mPixelFormat(renderTargetPixelFormat)
149   , mDownsampleWidthScale(downsampleWidthScale)
150   , mDownsampleHeightScale(downsampleHeightScale)
151   , mDownsampledWidth( 0.0f )
152   , mDownsampledHeight( 0.0f )
153   , mBlurUserImage( blurUserImage )
154   , mRenderOnce( false )
155   , mBackgroundColor( Color::BLACK )
156   , mTargetSize(Vector2::ZERO)
157   , mLastSize(Vector2::ZERO)
158   , mChildrenRoot(Actor::New())
159   , mInternalRoot(Actor::New())
160   , mBlurStrengthPropertyIndex(Property::INVALID_INDEX)
161   , mActivated( false )
162 {
163   SetBlurBellCurveWidth(blurBellCurveWidth);
164 }
165
166 GaussianBlurView::~GaussianBlurView()
167 {
168 }
169
170
171 Toolkit::GaussianBlurView GaussianBlurView::New()
172 {
173   GaussianBlurView* impl = new GaussianBlurView();
174
175   Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
176
177   // Second-phase init of the implementation
178   // This can only be done after the CustomActor connection has been made...
179   impl->Initialize();
180
181   return handle;
182 }
183
184 Toolkit::GaussianBlurView GaussianBlurView::New(const unsigned int numSamples, const float blurBellCurveWidth, const Pixel::Format renderTargetPixelFormat,
185                                                 const float downsampleWidthScale, const float downsampleHeightScale,
186                                                 bool blurUserImage)
187 {
188   GaussianBlurView* impl = new GaussianBlurView( numSamples, blurBellCurveWidth, renderTargetPixelFormat,
189                                                  downsampleWidthScale, downsampleHeightScale,
190                                                  blurUserImage);
191
192   Dali::Toolkit::GaussianBlurView handle = Dali::Toolkit::GaussianBlurView( *impl );
193
194   // Second-phase init of the implementation
195   // This can only be done after the CustomActor connection has been made...
196   impl->Initialize();
197
198   return handle;
199 }
200
201 /////////////////////////////////////////////////////////////
202 // for creating a subtree for all user added child actors, so that we can have them exclusive to the mRenderChildrenTask and our other actors exclusive to our other tasks
203 // DEPRECATED: overloading Actor::Add()/Remove() not nice since breaks polymorphism. Need another method to pass ownership of added child actors to our internal actor root.
204 void GaussianBlurView::Add(Actor child)
205 {
206   mChildrenRoot.Add(child);
207 }
208
209 void GaussianBlurView::Remove(Actor child)
210 {
211   mChildrenRoot.Remove(child);
212 }
213
214 void GaussianBlurView::SetUserImageAndOutputRenderTarget(Image inputImage, FrameBufferImage outputRenderTarget)
215 {
216   // can only do this if the GaussianBlurView object was created with this parameter set
217   DALI_ASSERT_ALWAYS(mBlurUserImage);
218
219   mUserInputImage = inputImage;
220   mImageActorHorizBlur.SetImage( mUserInputImage );
221
222   mUserOutputRenderTarget = outputRenderTarget;
223 }
224
225 FrameBufferImage GaussianBlurView::GetBlurredRenderTarget() const
226 {
227   if(!mUserOutputRenderTarget)
228   {
229     return mRenderTargetForRenderingChildren;
230   }
231
232   return mUserOutputRenderTarget;
233 }
234
235 void GaussianBlurView::SetBackgroundColor( const Vector4& color )
236 {
237   mBackgroundColor = color;
238 }
239
240 Vector4 GaussianBlurView::GetBackgroundColor() const
241 {
242   return mBackgroundColor;
243 }
244
245 ///////////////////////////////////////////////////////////
246 //
247 // Private methods
248 //
249
250 void GaussianBlurView::OnInitialize()
251 {
252   // root actor to parent all user added actors, needed to allow us to set that subtree as exclusive for our child render task
253   mChildrenRoot.SetParentOrigin(ParentOrigin::CENTER);
254   mInternalRoot.SetParentOrigin(ParentOrigin::CENTER);
255
256   //////////////////////////////////////////////////////
257   // Create shaders
258
259   std::ostringstream horizFragmentShaderStringStream;
260   horizFragmentShaderStringStream << "#define NUM_SAMPLES " << mNumSamples << "\n";
261   horizFragmentShaderStringStream << GAUSSIAN_BLUR_FRAGMENT_SOURCE;
262   Property::Map customShader;
263   customShader[ "fragmentShader" ] = horizFragmentShaderStringStream.str();
264   Property::Map rendererMap;
265   rendererMap.Insert( "rendererType", "image" );
266   rendererMap.Insert( "shader", customShader );
267
268   //////////////////////////////////////////////////////
269   // Create actors
270
271   // Create an ImageActor for performing a horizontal blur on the texture
272   mImageActorHorizBlur = Toolkit::ImageView::New();
273   mImageActorHorizBlur.SetParentOrigin(ParentOrigin::CENTER);
274   mImageActorHorizBlur.SetProperty( Toolkit::ImageView::Property::IMAGE, rendererMap );
275
276   // Create an ImageActor for performing a vertical blur on the texture
277   mImageActorVertBlur = Toolkit::ImageView::New();
278   mImageActorVertBlur.SetParentOrigin(ParentOrigin::CENTER);
279   mImageActorVertBlur.SetProperty( Toolkit::ImageView::Property::IMAGE, rendererMap );
280
281   // Register a property that the user can control to fade the blur in / out via the GaussianBlurView object
282   Actor self = Self();
283   mBlurStrengthPropertyIndex = self.RegisterProperty(GAUSSIAN_BLUR_VIEW_STRENGTH_PROPERTY_NAME, GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH);
284
285   // Create an ImageActor for compositing the blur and the original child actors render
286   if(!mBlurUserImage)
287   {
288     mImageActorComposite = Toolkit::ImageView::New();
289     mImageActorComposite.SetParentOrigin(ParentOrigin::CENTER);
290     mImageActorComposite.SetOpacity(GAUSSIAN_BLUR_VIEW_DEFAULT_BLUR_STRENGTH); // ensure alpha is enabled for this object and set default value
291
292     Constraint blurStrengthConstraint = Constraint::New<float>( mImageActorComposite, Actor::Property::COLOR_ALPHA, EqualToConstraint());
293     blurStrengthConstraint.AddSource( Source( self, mBlurStrengthPropertyIndex) );
294     blurStrengthConstraint.Apply();
295
296     // Create an ImageActor for holding final result, i.e. the blurred image. This will get rendered to screen later, via default / user render task
297     mTargetActor = Toolkit::ImageView::New();
298     mTargetActor.SetParentOrigin(ParentOrigin::CENTER);
299
300     //////////////////////////////////////////////////////
301     // Create cameras for the renders corresponding to the view size
302     mRenderFullSizeCamera = CameraActor::New();
303     mRenderFullSizeCamera.SetInvertYAxis( true );
304     mRenderFullSizeCamera.SetParentOrigin(ParentOrigin::CENTER);
305
306
307     //////////////////////////////////////////////////////
308     // Connect to actor tree
309     mInternalRoot.Add( mImageActorComposite );
310     mInternalRoot.Add( mTargetActor );
311     mInternalRoot.Add( mRenderFullSizeCamera );
312   }
313
314
315   //////////////////////////////////////////////////////
316   // Create camera for the renders corresponding to the (potentially downsampled) render targets' size
317   mRenderDownsampledCamera = CameraActor::New();
318   mRenderDownsampledCamera.SetInvertYAxis( true );
319   mRenderDownsampledCamera.SetParentOrigin(ParentOrigin::CENTER);
320
321
322   //////////////////////////////////////////////////////
323   // Connect to actor tree
324   Self().Add( mChildrenRoot );
325   Self().Add( mInternalRoot );
326   mInternalRoot.Add( mImageActorHorizBlur );
327   mInternalRoot.Add( mImageActorVertBlur );
328   mInternalRoot.Add( mRenderDownsampledCamera );
329 }
330
331
332 void GaussianBlurView::OnSizeSet(const Vector3& targetSize)
333 {
334   mTargetSize = Vector2(targetSize);
335
336   mChildrenRoot.SetSize(targetSize);
337
338   if( !mBlurUserImage )
339   {
340     mImageActorComposite.SetSize(targetSize);
341     mTargetActor.SetSize(targetSize);
342
343     // Children render camera must move when GaussianBlurView object is resized. This is since we cannot change render target size - so we need to remap the child actors' rendering
344     // accordingly so they still exactly fill the render target. Note that this means the effective resolution of the child render changes as the GaussianBlurView object changes
345     // size, this is the trade off for not being able to modify render target size
346     // Change camera z position based on GaussianBlurView actor height
347     float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
348     mRenderFullSizeCamera.SetZ(mTargetSize.height * cameraPosConstraintScale);
349   }
350
351
352   // if we have already activated the blur, need to update render target sizes now to reflect the new size of this actor
353   if(mActivated)
354   {
355     Deactivate();
356     Activate();
357   }
358 }
359
360 void GaussianBlurView::OnControlChildAdd( Actor& child )
361 {
362   if( child != mChildrenRoot && child != mInternalRoot)
363   {
364     mChildrenRoot.Add( child );
365   }
366 }
367
368 void GaussianBlurView::OnControlChildRemove( Actor& child )
369 {
370   mChildrenRoot.Remove( child );
371 }
372
373 void GaussianBlurView::AllocateResources()
374 {
375   // size of render targets etc is based on the size of this actor, ignoring z
376   if(mTargetSize != mLastSize)
377   {
378     mLastSize = mTargetSize;
379
380     // get size of downsampled render targets
381     mDownsampledWidth = mTargetSize.width * mDownsampleWidthScale;
382     mDownsampledHeight = mTargetSize.height * mDownsampleHeightScale;
383
384     // Create and place a camera for the renders corresponding to the (potentially downsampled) render targets' size
385     mRenderDownsampledCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
386     // TODO: how do we pick a reasonable value for near clip? Needs to relate to normal camera the user renders with, but we don't have a handle on it
387     mRenderDownsampledCamera.SetNearClippingPlane(1.0f);
388     mRenderDownsampledCamera.SetAspectRatio(mDownsampledWidth / mDownsampledHeight);
389     mRenderDownsampledCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
390
391     mRenderDownsampledCamera.SetPosition(0.0f, 0.0f, ((mDownsampledHeight * 0.5f) / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f)));
392
393     // setup for normal operation
394     if(!mBlurUserImage)
395     {
396       // Create and place a camera for the children render, corresponding to its render target size
397       mRenderFullSizeCamera.SetFieldOfView(ARBITRARY_FIELD_OF_VIEW);
398       // TODO: how do we pick a reasonable value for near clip? Needs to relate to normal camera the user renders with, but we don't have a handle on it
399       mRenderFullSizeCamera.SetNearClippingPlane(1.0f);
400       mRenderFullSizeCamera.SetAspectRatio(mTargetSize.width / mTargetSize.height);
401       mRenderFullSizeCamera.SetType(Dali::Camera::FREE_LOOK); // camera orientation based solely on actor
402
403       float cameraPosConstraintScale = 0.5f / tanf(ARBITRARY_FIELD_OF_VIEW * 0.5f);
404       mRenderFullSizeCamera.SetPosition(0.0f, 0.0f, mTargetSize.height * cameraPosConstraintScale);
405
406       // create offscreen buffer of new size to render our child actors to
407       mRenderTargetForRenderingChildren = FrameBufferImage::New( mTargetSize.width, mTargetSize.height, mPixelFormat );
408
409       // Set ImageActor for performing a horizontal blur on the texture
410       mImageActorHorizBlur.SetImage( mRenderTargetForRenderingChildren );
411
412       // Create offscreen buffer for vert blur pass
413       mRenderTarget1 = FrameBufferImage::New( mDownsampledWidth, mDownsampledHeight, mPixelFormat );
414
415       // use the completed blur in the first buffer and composite with the original child actors render
416       mImageActorComposite.SetImage( mRenderTarget1 );
417
418       // set up target actor for rendering result, i.e. the blurred image
419       mTargetActor.SetImage(mRenderTargetForRenderingChildren);
420     }
421
422     // Create offscreen buffer for horiz blur pass
423     mRenderTarget2 = FrameBufferImage::New( mDownsampledWidth, mDownsampledHeight, mPixelFormat );
424
425     // size needs to match render target
426     mImageActorHorizBlur.SetSize(mDownsampledWidth, mDownsampledHeight);
427
428     // size needs to match render target
429     mImageActorVertBlur.SetImage( mRenderTarget2 );
430     mImageActorVertBlur.SetSize(mDownsampledWidth, mDownsampledHeight);
431
432     // set gaussian blur up for new sized render targets
433     SetShaderConstants();
434   }
435 }
436
437 void GaussianBlurView::CreateRenderTasks()
438 {
439   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
440
441   if(!mBlurUserImage)
442   {
443     // create render task to render our child actors to offscreen buffer
444     mRenderChildrenTask = taskList.CreateTask();
445     mRenderChildrenTask.SetSourceActor( mChildrenRoot );
446     mRenderChildrenTask.SetExclusive(true);
447     mRenderChildrenTask.SetInputEnabled( false );
448     mRenderChildrenTask.SetClearEnabled( true );
449     mRenderChildrenTask.SetClearColor( mBackgroundColor );
450
451     mRenderChildrenTask.SetCameraActor(mRenderFullSizeCamera);
452     mRenderChildrenTask.SetTargetFrameBuffer( mRenderTargetForRenderingChildren );
453   }
454
455   // perform a horizontal blur targeting the second buffer
456   mHorizBlurTask = taskList.CreateTask();
457   mHorizBlurTask.SetSourceActor( mImageActorHorizBlur );
458   mHorizBlurTask.SetExclusive(true);
459   mHorizBlurTask.SetInputEnabled( false );
460   mHorizBlurTask.SetClearEnabled( true );
461   mHorizBlurTask.SetClearColor( mBackgroundColor );
462   mHorizBlurTask.SetCameraActor(mRenderDownsampledCamera);
463   mHorizBlurTask.SetTargetFrameBuffer( mRenderTarget2 );
464   if( mRenderOnce && mBlurUserImage )
465   {
466     mHorizBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
467   }
468
469   // use the second buffer and perform a horizontal blur targeting the first buffer
470   mVertBlurTask = taskList.CreateTask();
471   mVertBlurTask.SetSourceActor( mImageActorVertBlur );
472   mVertBlurTask.SetExclusive(true);
473   mVertBlurTask.SetInputEnabled( false );
474   mVertBlurTask.SetClearEnabled( true );
475   mVertBlurTask.SetClearColor( mBackgroundColor );
476   mVertBlurTask.SetCameraActor(mRenderDownsampledCamera);
477   if(mUserOutputRenderTarget)
478   {
479     mVertBlurTask.SetTargetFrameBuffer( mUserOutputRenderTarget );
480   }
481   else
482   {
483     mVertBlurTask.SetTargetFrameBuffer( mRenderTarget1 );
484   }
485   if( mRenderOnce && mBlurUserImage )
486   {
487     mVertBlurTask.SetRefreshRate(RenderTask::REFRESH_ONCE);
488     mVertBlurTask.FinishedSignal().Connect( this, &GaussianBlurView::OnRenderTaskFinished );
489   }
490
491   // use the completed blur in the first buffer and composite with the original child actors render
492   if(!mBlurUserImage)
493   {
494     mCompositeTask = taskList.CreateTask();
495     mCompositeTask.SetSourceActor( mImageActorComposite );
496     mCompositeTask.SetExclusive(true);
497     mCompositeTask.SetInputEnabled( false );
498
499     mCompositeTask.SetCameraActor(mRenderFullSizeCamera);
500     mCompositeTask.SetTargetFrameBuffer( mRenderTargetForRenderingChildren );
501   }
502 }
503
504 void GaussianBlurView::RemoveRenderTasks()
505 {
506   RenderTaskList taskList = Stage::GetCurrent().GetRenderTaskList();
507
508   taskList.RemoveTask(mRenderChildrenTask);
509   taskList.RemoveTask(mHorizBlurTask);
510   taskList.RemoveTask(mVertBlurTask);
511   taskList.RemoveTask(mCompositeTask);
512 }
513
514 void GaussianBlurView::Activate()
515 {
516   // make sure resources are allocated and start the render tasks processing
517   AllocateResources();
518   CreateRenderTasks();
519   mActivated = true;
520 }
521
522 void GaussianBlurView::ActivateOnce()
523 {
524   DALI_ASSERT_ALWAYS(mBlurUserImage); // Only works with blurring image mode.
525   mRenderOnce = true;
526   Activate();
527 }
528
529 void GaussianBlurView::Deactivate()
530 {
531   // stop render tasks processing
532   // Note: render target resources are automatically freed since we set the Image::Unused flag
533   RemoveRenderTasks();
534   mRenderTargetForRenderingChildren.Reset();
535   mRenderTarget1.Reset();
536   mRenderTarget2.Reset();
537   mRenderOnce = false;
538   mActivated = false;
539 }
540
541 void GaussianBlurView::SetBlurBellCurveWidth(float blurBellCurveWidth)
542 {
543   // a value of zero leads to undefined Gaussian weights, do not allow user to do this
544   mBlurBellCurveWidth = std::max( blurBellCurveWidth, 0.001f );
545 }
546
547 float GaussianBlurView::CalcGaussianWeight(float x)
548 {
549   return (1.0f / sqrt(2.0f * Math::PI * mBlurBellCurveWidth)) * exp(-(x * x) / (2.0f * mBlurBellCurveWidth * mBlurBellCurveWidth));
550 }
551
552 void GaussianBlurView::SetShaderConstants()
553 {
554   Vector2 *uvOffsets;
555   float ofs;
556   float *weights;
557   float w, totalWeights;
558   unsigned int i;
559
560   uvOffsets = new Vector2[mNumSamples + 1];
561   weights = new float[mNumSamples + 1];
562
563   totalWeights = weights[0] = CalcGaussianWeight(0);
564   uvOffsets[0].x = 0.0f;
565   uvOffsets[0].y = 0.0f;
566
567   for(i=0; i<mNumSamples >> 1; i++)
568   {
569     w = CalcGaussianWeight((float)(i + 1));
570     weights[(i << 1) + 1] = w;
571     weights[(i << 1) + 2] = w;
572     totalWeights += w * 2.0f;
573
574     // offset texture lookup to between texels, that way the bilinear filter in the texture hardware will average two samples with one lookup
575     ofs = ((float)(i << 1)) + 1.5f;
576
577     // get offsets from units of pixels into uv coordinates in [0..1]
578     float ofsX = ofs / mDownsampledWidth;
579     float ofsY = ofs / mDownsampledHeight;
580     uvOffsets[(i << 1) + 1].x = ofsX;
581     uvOffsets[(i << 1) + 1].y = ofsY;
582
583     uvOffsets[(i << 1) + 2].x = -ofsX;
584     uvOffsets[(i << 1) + 2].y = -ofsY;
585   }
586
587   for(i=0; i<mNumSamples; i++)
588   {
589     weights[i] /= totalWeights;
590   }
591
592   // set shader constants
593   Vector2 xAxis(1.0f, 0.0f);
594   Vector2 yAxis(0.0f, 1.0f);
595   for (i = 0; i < mNumSamples; ++i )
596   {
597     mImageActorHorizBlur.RegisterProperty( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * xAxis );
598     mImageActorHorizBlur.RegisterProperty( GetSampleWeightsPropertyName( i ), weights[ i ] );
599
600     mImageActorVertBlur.RegisterProperty( GetSampleOffsetsPropertyName( i ), uvOffsets[ i ] * yAxis );
601     mImageActorVertBlur.RegisterProperty( GetSampleWeightsPropertyName( i ), weights[ i ] );
602   }
603
604   delete[] uvOffsets;
605   delete[] weights;
606 }
607
608 std::string GaussianBlurView::GetSampleOffsetsPropertyName( unsigned int index ) const
609 {
610   DALI_ASSERT_ALWAYS( index < mNumSamples );
611
612   std::ostringstream oss;
613   oss << "uSampleOffsets[" << index << "]";
614   return oss.str();
615 }
616
617 std::string GaussianBlurView::GetSampleWeightsPropertyName( unsigned int index ) const
618 {
619   DALI_ASSERT_ALWAYS( index < mNumSamples );
620
621   std::ostringstream oss;
622   oss << "uSampleWeights[" << index << "]";
623   return oss.str();
624 }
625
626 Dali::Toolkit::GaussianBlurView::GaussianBlurViewSignal& GaussianBlurView::FinishedSignal()
627 {
628   return mFinishedSignal;
629 }
630
631 void GaussianBlurView::OnRenderTaskFinished(Dali::RenderTask& renderTask)
632 {
633   Toolkit::GaussianBlurView handle( GetOwner() );
634   mFinishedSignal.Emit( handle );
635 }
636
637 } // namespace Internal
638 } // namespace Toolkit
639 } // namespace Dali