[dali_1.9.14] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / image / image-visual.cpp
1 /*
2  * Copyright (c) 2020 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 <dali-toolkit/internal/visuals/image/image-visual.h>
20
21 // EXTERNAL HEADERS
22 #include <cstring> // for strlen()
23 #include <dali/public-api/actors/layer.h>
24 #include <dali/public-api/common/stage.h>
25 #include <dali/public-api/images/resource-image.h>
26 #include <dali/public-api/images/native-image.h>
27 #include <dali/devel-api/images/texture-set-image.h>
28 #include <dali/devel-api/adaptor-framework/image-loading.h>
29 #include <dali/devel-api/scripting/enum-helper.h>
30 #include <dali/devel-api/scripting/scripting.h>
31 #include <dali/integration-api/debug.h>
32
33 // INTERNAL HEADERS
34 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
35 #include <dali-toolkit/public-api/visuals/visual-properties.h>
36 #include <dali-toolkit/devel-api/visuals/image-visual-actions-devel.h>
37 #include <dali-toolkit/internal/visuals/texture-manager-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
40 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
41 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
42 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
43 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
44 #include <dali-toolkit/internal/visuals/visual-url.h>
45 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
46
47 namespace Dali
48 {
49
50 namespace Toolkit
51 {
52
53 namespace Internal
54 {
55
56 namespace
57 {
58
59 // fitting modes
60 DALI_ENUM_TO_STRING_TABLE_BEGIN( FITTING_MODE )
61 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SHRINK_TO_FIT )
62 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, SCALE_TO_FILL )
63 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_WIDTH )
64 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, FIT_HEIGHT )
65 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::FittingMode, DEFAULT )
66 DALI_ENUM_TO_STRING_TABLE_END( FITTING_MODE )
67
68 // sampling modes
69 DALI_ENUM_TO_STRING_TABLE_BEGIN( SAMPLING_MODE )
70 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX )
71 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NEAREST )
72 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, LINEAR )
73 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_NEAREST )
74 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, BOX_THEN_LINEAR )
75 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, NO_FILTER )
76 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::SamplingMode, DONT_CARE )
77 DALI_ENUM_TO_STRING_TABLE_END( SAMPLING_MODE )
78
79 // wrap modes
80 DALI_ENUM_TO_STRING_TABLE_BEGIN( WRAP_MODE )
81 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, DEFAULT )
82 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, CLAMP_TO_EDGE )
83 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, REPEAT )
84 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::WrapMode, MIRRORED_REPEAT )
85 DALI_ENUM_TO_STRING_TABLE_END( WRAP_MODE )
86
87 // load policies
88 DALI_ENUM_TO_STRING_TABLE_BEGIN( LOAD_POLICY )
89 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, IMMEDIATE )
90 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::LoadPolicy, ATTACHED )
91 DALI_ENUM_TO_STRING_TABLE_END( LOAD_POLICY )
92
93 // release policies
94 DALI_ENUM_TO_STRING_TABLE_BEGIN( RELEASE_POLICY )
95 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DETACHED )
96 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, DESTROYED )
97 DALI_ENUM_TO_STRING_WITH_SCOPE( Dali::Toolkit::ImageVisual::ReleasePolicy, NEVER )
98 DALI_ENUM_TO_STRING_TABLE_END( RELEASE_POLICY )
99
100 const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
101
102 const char* DEFAULT_SAMPLER_TYPENAME = "sampler2D";
103
104 const float PIXEL_ALIGN_ON = 1.0f;
105 const float PIXEL_ALIGN_OFF = 0.0f;
106
107 Geometry CreateGeometry( VisualFactoryCache& factoryCache, ImageDimensions gridSize )
108 {
109   Geometry geometry;
110
111   if( gridSize == ImageDimensions( 1, 1 ) )
112   {
113     geometry = factoryCache.GetGeometry( VisualFactoryCache::QUAD_GEOMETRY );
114   }
115   else
116   {
117     geometry = VisualFactoryCache::CreateGridGeometry( gridSize );
118   }
119
120   return geometry;
121 }
122
123 } // unnamed namespace
124
125
126 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
127                                  ImageVisualShaderFactory& shaderFactory,
128                                  const VisualUrl& imageUrl,
129                                  const Property::Map& properties,
130                                  ImageDimensions size,
131                                  FittingMode::Type fittingMode,
132                                  Dali::SamplingMode::Type samplingMode )
133 {
134   ImageVisualPtr imageVisualPtr( new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode ) );
135   imageVisualPtr->SetProperties( properties );
136   return imageVisualPtr;
137 }
138
139 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache,
140                                  ImageVisualShaderFactory& shaderFactory,
141                                  const VisualUrl& imageUrl,
142                                  ImageDimensions size,
143                                  FittingMode::Type fittingMode,
144                                  Dali::SamplingMode::Type samplingMode )
145 {
146   return new ImageVisual( factoryCache, shaderFactory, imageUrl, size, fittingMode, samplingMode );
147 }
148
149 ImageVisualPtr ImageVisual::New( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Image& image )
150 {
151   return new ImageVisual( factoryCache, shaderFactory, image );
152 }
153
154 ImageVisual::ImageVisual( VisualFactoryCache& factoryCache,
155                           ImageVisualShaderFactory& shaderFactory,
156                           const VisualUrl& imageUrl,
157                           ImageDimensions size,
158                           FittingMode::Type fittingMode,
159                           Dali::SamplingMode::Type samplingMode )
160 : Visual::Base( factoryCache, Visual::FittingMode::FILL ),
161   mImage(),
162   mPixelArea( FULL_TEXTURE_RECT ),
163   mPlacementActor(),
164   mImageUrl( imageUrl ),
165   mMaskingData( ),
166   mDesiredSize( size ),
167   mTextureId( TextureManager::INVALID_TEXTURE_ID ),
168   mTextures(),
169   mImageVisualShaderFactory( shaderFactory ),
170   mFittingMode( fittingMode ),
171   mSamplingMode( samplingMode ),
172   mWrapModeU( WrapMode::DEFAULT ),
173   mWrapModeV( WrapMode::DEFAULT ),
174   mLoadPolicy( Toolkit::ImageVisual::LoadPolicy::ATTACHED ),
175   mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DETACHED ),
176   mAtlasRect( 0.0f, 0.0f, 0.0f, 0.0f ),
177   mAtlasRectSize( 0, 0 ),
178   mAttemptAtlasing( false ),
179   mLoading( false ),
180   mOrientationCorrection( true )
181 {
182   EnablePreMultipliedAlpha( mFactoryCache.GetPreMultiplyOnLoad() );
183 }
184
185 ImageVisual::ImageVisual( VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const Image& image )
186 : Visual::Base( factoryCache, Visual::FittingMode::FILL ),
187   mImage( image ),
188   mPixelArea( FULL_TEXTURE_RECT ),
189   mPlacementActor(),
190   mImageUrl(),
191   mMaskingData( ),
192   mDesiredSize(),
193   mTextureId( TextureManager::INVALID_TEXTURE_ID ),
194   mTextures(),
195   mImageVisualShaderFactory( shaderFactory ),
196   mFittingMode( FittingMode::DEFAULT ),
197   mSamplingMode( SamplingMode::DEFAULT ),
198   mWrapModeU( WrapMode::DEFAULT ),
199   mWrapModeV( WrapMode::DEFAULT ),
200   mLoadPolicy( Toolkit::ImageVisual::LoadPolicy::ATTACHED ),
201   mReleasePolicy( Toolkit::ImageVisual::ReleasePolicy::DESTROYED ),
202   mAtlasRect( 0.0f, 0.0f, 0.0f, 0.0f ),
203   mAttemptAtlasing( false ),
204   mLoading( false ),
205   mOrientationCorrection( true )
206 {
207   // PreMultiplied alpha should be disabled when the Image is used.
208   EnablePreMultipliedAlpha( false );
209 }
210
211 ImageVisual::~ImageVisual()
212 {
213   if( Stage::IsInstalled() )
214   {
215     if( mMaskingData )
216     {
217       // TextureManager could have been deleted before the actor that contains this
218       // ImageVisual is destroyed (e.g. due to stage shutdown). Ensure the stage
219       // is still valid before accessing texture manager.
220       if( mMaskingData->mAlphaMaskId != TextureManager::INVALID_TEXTURE_ID )
221       {
222         TextureManager& textureManager = mFactoryCache.GetTextureManager();
223         textureManager.Remove( mMaskingData->mAlphaMaskId, this );
224       }
225     }
226
227     // ImageVisual destroyed so remove texture unless ReleasePolicy is set to never release
228     if( ( mTextureId != TextureManager::INVALID_TEXTURE_ID  ) && ( mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER ) )
229     {
230       RemoveTexture();
231     }
232   }
233 }
234
235 void ImageVisual::DoSetProperties( const Property::Map& propertyMap )
236 {
237   // Url is already received in constructor
238   for( Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter )
239   {
240     KeyValuePair keyValue = propertyMap.GetKeyValue( iter );
241     if( keyValue.first.type == Property::Key::INDEX )
242     {
243       DoSetProperty( keyValue.first.indexKey, keyValue.second );
244     }
245     else
246     {
247       if( keyValue.first == IMAGE_FITTING_MODE )
248       {
249         DoSetProperty( Toolkit::ImageVisual::Property::FITTING_MODE, keyValue.second );
250       }
251       else if( keyValue.first == IMAGE_SAMPLING_MODE )
252       {
253         DoSetProperty( Toolkit::ImageVisual::Property::SAMPLING_MODE, keyValue.second );
254       }
255       else if( keyValue.first == IMAGE_DESIRED_WIDTH )
256       {
257         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_WIDTH, keyValue.second );
258       }
259       else if( keyValue.first == IMAGE_DESIRED_HEIGHT )
260       {
261         DoSetProperty( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, keyValue.second );
262       }
263       else if( keyValue.first == PIXEL_AREA_UNIFORM_NAME )
264       {
265         DoSetProperty( Toolkit::ImageVisual::Property::PIXEL_AREA, keyValue.second );
266       }
267       else if( keyValue.first == IMAGE_WRAP_MODE_U )
268       {
269         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_U, keyValue.second );
270       }
271       else if( keyValue.first == IMAGE_WRAP_MODE_V )
272       {
273         DoSetProperty( Toolkit::ImageVisual::Property::WRAP_MODE_V, keyValue.second );
274       }
275       else if( keyValue.first == SYNCHRONOUS_LOADING )
276       {
277         DoSetProperty( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second );
278       }
279       else if( keyValue.first == IMAGE_ATLASING )
280       {
281         DoSetProperty( Toolkit::ImageVisual::Property::ATLASING, keyValue.second );
282       }
283       else if( keyValue.first == ALPHA_MASK_URL )
284       {
285         DoSetProperty( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, keyValue.second );
286       }
287       else if( keyValue.first == MASK_CONTENT_SCALE_NAME )
288       {
289         DoSetProperty( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, keyValue.second );
290       }
291       else if( keyValue.first == CROP_TO_MASK_NAME )
292       {
293         DoSetProperty( Toolkit::ImageVisual::Property::CROP_TO_MASK, keyValue.second );
294       }
295       else if ( keyValue.first == LOAD_POLICY_NAME )
296       {
297         DoSetProperty( Toolkit::ImageVisual::Property::LOAD_POLICY, keyValue.second );
298       }
299       else if( keyValue.first == RELEASE_POLICY_NAME )
300       {
301         DoSetProperty( Toolkit::ImageVisual::Property::RELEASE_POLICY, keyValue.second );
302       }
303       else if( keyValue.first == ORIENTATION_CORRECTION_NAME )
304       {
305         DoSetProperty( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, keyValue.second );
306       }
307     }
308   }
309   // Load image immediately if LOAD_POLICY requires it
310   if ( mLoadPolicy == Toolkit::ImageVisual::LoadPolicy::IMMEDIATE )
311   {
312     auto attemptAtlasing = AttemptAtlasing();
313     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
314                  TextureManager::ReloadPolicy::CACHED  );
315   }
316 }
317
318 void ImageVisual::DoSetProperty( Property::Index index, const Property::Value& value )
319 {
320   switch( index )
321   {
322     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
323     {
324       bool sync = false;
325       if( value.Get( sync ) )
326       {
327         if( sync )
328         {
329           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
330         }
331         else
332         {
333           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
334         }
335       }
336       else
337       {
338         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
339       }
340       break;
341     }
342
343     case Toolkit::ImageVisual::Property::DESIRED_WIDTH:
344     {
345       float desiredWidth = 0.0f;
346       if( value.Get( desiredWidth ) )
347       {
348         mDesiredSize.SetWidth( desiredWidth );
349       }
350       else
351       {
352         DALI_LOG_ERROR("ImageVisual: desiredWidth property has incorrect type\n");
353       }
354       break;
355     }
356
357     case Toolkit::ImageVisual::Property::DESIRED_HEIGHT:
358     {
359       float desiredHeight = 0.0f;
360       if( value.Get( desiredHeight ) )
361       {
362         mDesiredSize.SetHeight( desiredHeight );
363       }
364       else
365       {
366         DALI_LOG_ERROR("ImageVisual: desiredHeight property has incorrect type\n");
367       }
368       break;
369     }
370
371     case Toolkit::ImageVisual::Property::FITTING_MODE:
372     {
373       int fittingMode = 0;
374       Scripting::GetEnumerationProperty( value, FITTING_MODE_TABLE, FITTING_MODE_TABLE_COUNT, fittingMode );
375       mFittingMode = Dali::FittingMode::Type( fittingMode );
376       break;
377     }
378
379     case Toolkit::ImageVisual::Property::SAMPLING_MODE:
380     {
381       int samplingMode = 0;
382       Scripting::GetEnumerationProperty( value, SAMPLING_MODE_TABLE, SAMPLING_MODE_TABLE_COUNT, samplingMode );
383       mSamplingMode = Dali::SamplingMode::Type( samplingMode );
384       break;
385     }
386
387     case Toolkit::ImageVisual::Property::PIXEL_AREA:
388     {
389       value.Get( mPixelArea );
390       break;
391     }
392
393     case Toolkit::ImageVisual::Property::WRAP_MODE_U:
394     {
395       int wrapMode = 0;
396       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
397       mWrapModeU = Dali::WrapMode::Type( wrapMode );
398       break;
399     }
400
401     case Toolkit::ImageVisual::Property::WRAP_MODE_V:
402     {
403       int wrapMode = 0;
404       Scripting::GetEnumerationProperty( value, WRAP_MODE_TABLE, WRAP_MODE_TABLE_COUNT, wrapMode );
405       mWrapModeV = Dali::WrapMode::Type( wrapMode );
406       break;
407     }
408
409     case Toolkit::ImageVisual::Property::ATLASING:
410     {
411       value.Get( mAttemptAtlasing );
412       break;
413     }
414
415     case Toolkit::ImageVisual::Property::ALPHA_MASK_URL:
416     {
417       std::string alphaUrl = "";
418       if( value.Get( alphaUrl ) )
419       {
420         AllocateMaskData();
421         mMaskingData->mAlphaMaskUrl = alphaUrl;
422       }
423       break;
424     }
425
426     case Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE:
427     {
428       float scale = 1.0f;
429       if( value.Get( scale ) )
430       {
431         AllocateMaskData();
432         mMaskingData->mContentScaleFactor = scale;
433       }
434       break;
435     }
436
437     case Toolkit::ImageVisual::Property::CROP_TO_MASK:
438     {
439       bool crop=false;
440       if( value.Get( crop ) )
441       {
442         AllocateMaskData();
443         mMaskingData->mCropToMask = crop;
444       }
445       break;
446     }
447
448     case Toolkit::ImageVisual::Property::RELEASE_POLICY:
449     {
450       int releasePolicy = 0;
451       Scripting::GetEnumerationProperty( value, RELEASE_POLICY_TABLE, RELEASE_POLICY_TABLE_COUNT, releasePolicy );
452       mReleasePolicy = Toolkit::ImageVisual::ReleasePolicy::Type( releasePolicy );
453       break;
454     }
455
456     case Toolkit::ImageVisual::Property::LOAD_POLICY:
457     {
458       int loadPolicy = 0;
459       Scripting::GetEnumerationProperty( value, LOAD_POLICY_TABLE, LOAD_POLICY_TABLE_COUNT, loadPolicy );
460       mLoadPolicy = Toolkit::ImageVisual::LoadPolicy::Type( loadPolicy );
461       break;
462     }
463     case Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION:
464     {
465       bool orientationCorrection( mOrientationCorrection );
466       if( value.Get( orientationCorrection ) )
467       {
468         mOrientationCorrection = orientationCorrection;
469       }
470       break;
471     }
472   }
473 }
474
475 void ImageVisual::AllocateMaskData()
476 {
477   if( !mMaskingData )
478   {
479     mMaskingData.reset(new TextureManager::MaskingData());
480   }
481 }
482
483 void ImageVisual::GetNaturalSize( Vector2& naturalSize )
484 {
485   if(mImage)
486   {
487     naturalSize.x = mImage.GetWidth();
488     naturalSize.y = mImage.GetHeight();
489     return;
490   }
491   else if( mDesiredSize.GetWidth()>0 && mDesiredSize.GetHeight()>0)
492   {
493     naturalSize.x = mDesiredSize.GetWidth();
494     naturalSize.y = mDesiredSize.GetHeight();
495     return;
496   }
497   else if( mImpl->mRenderer ) // Check if we have a loaded image
498   {
499     if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
500     {
501       naturalSize.x = mAtlasRectSize.GetWidth();
502       naturalSize.y = mAtlasRectSize.GetHeight();
503       return;
504     }
505
506     auto textureSet = mImpl->mRenderer.GetTextures();
507     if( textureSet )
508     {
509       auto texture = textureSet.GetTexture(0);
510       naturalSize.x = texture.GetWidth();
511       naturalSize.y = texture.GetHeight();
512       return;
513     }
514   }
515
516   if( mMaskingData != NULL && mMaskingData->mAlphaMaskUrl.IsValid() &&
517            mMaskingData->mCropToMask )
518   {
519     ImageDimensions dimensions = Dali::GetClosestImageSize( mMaskingData->mAlphaMaskUrl.GetUrl() );
520     if( dimensions != ImageDimensions( 0, 0 ) )
521     {
522       naturalSize.x = dimensions.GetWidth();
523       naturalSize.y = dimensions.GetHeight();
524     }
525     return;
526   }
527   else if( mImageUrl.IsValid() )
528   {
529     if( mImageUrl.GetProtocolType() == VisualUrl::LOCAL )
530     {
531       ImageDimensions dimensions = Dali::GetClosestImageSize( mImageUrl.GetUrl() );
532
533       if( dimensions != ImageDimensions( 0, 0 ) )
534       {
535         naturalSize.x = dimensions.GetWidth();
536         naturalSize.y = dimensions.GetHeight();
537       }
538       else
539       {
540         Image brokenImage = mFactoryCache.GetBrokenVisualImage();
541
542         naturalSize.x = brokenImage.GetWidth();
543         naturalSize.y = brokenImage.GetWidth();
544       }
545       return;
546     }
547   }
548   naturalSize = Vector2::ZERO;
549 }
550
551 void ImageVisual::CreateRenderer( TextureSet& textureSet )
552 {
553   Geometry geometry;
554   Shader shader;
555
556   if( !mImpl->mCustomShader )
557   {
558     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
559
560     shader = mImageVisualShaderFactory.GetShader( mFactoryCache,
561                              mImpl->mFlags & Impl::IS_ATLASING_APPLIED,
562                              mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE,
563                              IsRoundedCornerRequired() );
564   }
565   else
566   {
567     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
568     if( mImpl->mCustomShader->mVertexShader.empty() && mImpl->mCustomShader->mFragmentShader.empty() )
569     {
570       // Use custom hints
571       shader = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), mImageVisualShaderFactory.GetFragmentShaderSource(), mImpl->mCustomShader->mHints );
572       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
573     }
574     else
575     {
576       shader = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
577                             mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource() : mImpl->mCustomShader->mFragmentShader,
578                             mImpl->mCustomShader->mHints );
579       if( mImpl->mCustomShader->mVertexShader.empty() )
580       {
581         shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
582       }
583     }
584   }
585
586   // Set pixel align off as default.
587   // ToDo: Pixel align causes issues such as rattling image animation.
588   // We should trun it off until issues are resolved
589   shader.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
590
591   mImpl->mRenderer = Renderer::New( geometry, shader );
592   if( textureSet )
593   {
594     mImpl->mRenderer.SetTextures( textureSet );
595   }
596   // else still waiting for texture load to finish.
597
598   //Register transform properties
599   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
600
601   EnablePreMultipliedAlpha( IsPreMultipliedAlphaEnabled() );
602 }
603
604 void ImageVisual::CreateNativeImageRenderer( NativeImage& nativeImage )
605 {
606   Geometry geometry;
607   Shader shader;
608
609   std::string fragmentShader;
610   const char* fragmentPreFix = nativeImage.GetCustomFragmentPreFix();
611   const char* customSamplerTypename = nativeImage.GetCustomSamplerTypename();
612
613   if( fragmentPreFix )
614   {
615     fragmentShader = fragmentPreFix;
616     fragmentShader += "\n";
617   }
618
619   if( mImpl->mCustomShader && !mImpl->mCustomShader->mFragmentShader.empty() )
620   {
621     fragmentShader += mImpl->mCustomShader->mFragmentShader;
622   }
623   else
624   {
625     fragmentShader += mImageVisualShaderFactory.GetFragmentShaderSource();
626   }
627
628   if( customSamplerTypename )
629   {
630     fragmentShader.replace( fragmentShader.find( DEFAULT_SAMPLER_TYPENAME ), strlen( DEFAULT_SAMPLER_TYPENAME ), customSamplerTypename );
631   }
632
633   if( !mImpl->mCustomShader )
634   {
635     geometry = CreateGeometry( mFactoryCache, ImageDimensions( 1, 1 ) );
636
637     shader  = Shader::New( mImageVisualShaderFactory.GetVertexShaderSource(), fragmentShader );
638     shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
639   }
640   else
641   {
642     geometry = CreateGeometry( mFactoryCache, mImpl->mCustomShader->mGridSize );
643     shader  = Shader::New( mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource() : mImpl->mCustomShader->mVertexShader,
644                            fragmentShader,
645                            mImpl->mCustomShader->mHints );
646     if( mImpl->mCustomShader->mVertexShader.empty() )
647     {
648       shader.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT );
649     }
650   }
651
652   mImpl->mRenderer = Renderer::New( geometry, shader );
653
654   //Register transform properties
655   mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
656 }
657
658 void ImageVisual::LoadTexture( bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection,
659                                TextureManager::ReloadPolicy forceReload )
660 {
661   TextureManager& textureManager = mFactoryCache.GetTextureManager();
662
663   ImageAtlasManagerPtr atlasManager = nullptr;
664   AtlasUploadObserver* atlasUploadObserver = nullptr;
665   auto textureObserver = this;
666
667   if( atlasing )
668   {
669     atlasManager = mFactoryCache.GetAtlasManager();
670     atlasUploadObserver = this;
671   }
672
673   auto preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader
674     ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD
675     : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
676
677   textures = textureManager.LoadTexture( mImageUrl, mDesiredSize, mFittingMode, mSamplingMode,
678                                          mMaskingData, IsSynchronousLoadingRequired(), mTextureId,
679                                          atlasRect, mAtlasRectSize, atlasing, mLoading, mWrapModeU,
680                                          mWrapModeV, textureObserver, atlasUploadObserver, atlasManager,
681                                          mOrientationCorrection, forceReload, preMultiplyOnLoad);
682
683   if( textures )
684   {
685     EnablePreMultipliedAlpha( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
686   }
687
688   if( atlasing ) // Flag needs to be set before creating renderer
689   {
690     mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
691   }
692   else
693   {
694     mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
695   }
696 }
697
698 bool ImageVisual::AttemptAtlasing()
699 {
700   return ( ! mImpl->mCustomShader && mImageUrl.GetProtocolType() == VisualUrl::LOCAL && mAttemptAtlasing );
701 }
702
703 void ImageVisual::InitializeRenderer()
704 {
705   auto attemptAtlasing = AttemptAtlasing();
706   // texture set has to be created first as we need to know if atlasing succeeded or not
707   // when selecting the shader
708
709   if( mTextureId == TextureManager::INVALID_TEXTURE_ID && ! mTextures ) // Only load the texture once
710   {
711     LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
712                  TextureManager::ReloadPolicy::CACHED );
713   }
714
715   CreateRenderer( mTextures );
716   mTextures.Reset(); // Visual should not keep a handle to the texture after this point.
717
718   if( attemptAtlasing ) // the texture is packed inside atlas
719   {
720     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
721
722     bool defaultWrapMode = mWrapModeU <= WrapMode::CLAMP_TO_EDGE && mWrapModeV <= WrapMode::CLAMP_TO_EDGE;
723
724     if( !defaultWrapMode ) // custom wrap mode
725     {
726       Vector2 wrapMode(mWrapModeU-WrapMode::CLAMP_TO_EDGE, mWrapModeV-WrapMode::CLAMP_TO_EDGE);
727       wrapMode.Clamp( Vector2::ZERO, Vector2( 2.f, 2.f ) );
728       mImpl->mRenderer.RegisterProperty( WRAP_MODE_UNIFORM_NAME, wrapMode );
729     }
730   }
731 }
732
733 void ImageVisual::InitializeRenderer( const Image& image )
734 {
735   TextureSet textures = TextureSet::New();
736
737   NativeImage nativeImage = NativeImage::DownCast( image );
738   if( nativeImage )
739   {
740     CreateNativeImageRenderer( nativeImage );
741     DALI_ASSERT_DEBUG( textures );
742     mImpl->mRenderer.SetTextures( textures );
743   }
744   else
745   {
746     // reuse existing code for regular images
747     CreateRenderer( textures ); // Textures will be retreived from Image
748   }
749   ApplyImageToSampler( image );
750 }
751
752 void ImageVisual::DoSetOnStage( Actor& actor )
753 {
754   if( mImageUrl.IsValid() )
755   {
756     InitializeRenderer();
757   }
758   else if( mImage )
759   {
760     InitializeRenderer( mImage );
761   }
762
763   if( !mImpl->mRenderer )
764   {
765     return;
766   }
767
768   mPlacementActor = actor;
769   // Search the Actor tree to find if Layer UI behaviour set.
770   Layer layer = actor.GetLayer();
771   if( layer && layer.GetBehavior() == Layer::LAYER_3D )
772   {
773      // Layer 3D set, do not align pixels
774      mImpl->mRenderer.RegisterProperty( PIXEL_ALIGNED_UNIFORM_NAME, PIXEL_ALIGN_OFF );
775   }
776
777   if( mPixelArea != FULL_TEXTURE_RECT )
778   {
779     mImpl->mRenderer.RegisterProperty( PIXEL_AREA_UNIFORM_NAME, mPixelArea );
780   }
781
782   if( mLoading == false )
783   {
784     actor.AddRenderer( mImpl->mRenderer );
785     mPlacementActor.Reset();
786
787     // Image loaded and ready to display
788     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
789   }
790 }
791
792 void ImageVisual::DoSetOffStage( Actor& actor )
793 {
794   // Visual::Base::SetOffStage only calls DoSetOffStage if mRenderer exists (is on onstage)
795
796   // Image release is dependent on the ReleasePolicy, renderer is destroyed.
797   actor.RemoveRenderer( mImpl->mRenderer);
798   if( mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED )
799   {
800     RemoveTexture(); // If INVALID_TEXTURE_ID then removal will be attempted on atlas
801     mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
802   }
803
804   if( mImageUrl.IsValid() )
805   {
806     // Legacy support for deprecated Dali::Image
807     mImage.Reset();
808   }
809   mLoading = false;
810   mImpl->mRenderer.Reset();
811   mPlacementActor.Reset();
812 }
813
814 void ImageVisual::DoCreatePropertyMap( Property::Map& map ) const
815 {
816   map.Clear();
817   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
818
819   bool sync = IsSynchronousLoadingRequired();
820   map.Insert( SYNCHRONOUS_LOADING, sync );
821   if( mImageUrl.IsValid() )
822   {
823     map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
824     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
825     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
826   }
827   else if( mImage )
828   {
829     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
830     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
831
832     ResourceImage resourceImage = ResourceImage::DownCast(mImage);
833     if( resourceImage )
834     {
835       map.Insert( Toolkit::ImageVisual::Property::URL, resourceImage.GetUrl() );
836     }
837   }
838
839   map.Insert( Toolkit::ImageVisual::Property::FITTING_MODE, mFittingMode );
840   map.Insert( Toolkit::ImageVisual::Property::SAMPLING_MODE, mSamplingMode );
841
842   map.Insert( Toolkit::ImageVisual::Property::PIXEL_AREA, mPixelArea );
843   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_U, mWrapModeU );
844   map.Insert( Toolkit::ImageVisual::Property::WRAP_MODE_V, mWrapModeV );
845
846   map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
847
848   if( mMaskingData != NULL )
849   {
850     map.Insert( Toolkit::ImageVisual::Property::ALPHA_MASK_URL, mMaskingData->mAlphaMaskUrl.GetUrl() );
851     map.Insert( Toolkit::ImageVisual::Property::MASK_CONTENT_SCALE, mMaskingData->mContentScaleFactor );
852     map.Insert( Toolkit::ImageVisual::Property::CROP_TO_MASK, mMaskingData->mCropToMask );
853   }
854
855   map.Insert( Toolkit::ImageVisual::Property::LOAD_POLICY, mLoadPolicy );
856   map.Insert( Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy );
857   map.Insert( Toolkit::ImageVisual::Property::ORIENTATION_CORRECTION, mOrientationCorrection );
858 }
859
860 void ImageVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
861 {
862   map.Clear();
863   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE );
864   if( mImageUrl.IsValid() )
865   {
866     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, mDesiredSize.GetWidth() );
867     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, mDesiredSize.GetHeight() );
868   }
869   else if( mImage )
870   {
871     map.Insert( Toolkit::ImageVisual::Property::DESIRED_WIDTH, static_cast<int>(mImage.GetWidth()) );
872     map.Insert( Toolkit::ImageVisual::Property::DESIRED_HEIGHT, static_cast<int>(mImage.GetHeight()) );
873   }
874 }
875
876 void ImageVisual::OnDoAction( const Dali::Property::Index actionName, const Dali::Property::Value& attributes )
877 {
878   // Check if action is valid for this visual type and perform action if possible
879
880   switch ( actionName )
881   {
882     case DevelImageVisual::Action::RELOAD:
883     {
884       auto attemptAtlasing = AttemptAtlasing();
885       LoadTexture( attemptAtlasing, mAtlasRect, mTextures, mOrientationCorrection,
886                    TextureManager::ReloadPolicy::FORCED );
887       break;
888     }
889   }
890 }
891
892 void ImageVisual::OnSetTransform()
893 {
894   if( mImpl->mRenderer )
895   {
896     mImpl->mTransform.RegisterUniforms( mImpl->mRenderer, Direction::LEFT_TO_RIGHT );
897   }
898 }
899
900 bool ImageVisual::IsResourceReady() const
901 {
902   return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
903            mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
904 }
905
906 void ImageVisual::ApplyImageToSampler( const Image& image )
907 {
908   if( image )
909   {
910     TextureSet textureSet = mImpl->mRenderer.GetTextures();
911     DALI_ASSERT_DEBUG( textureSet ); // texture set should always exist by this time
912
913     TextureSetImage( textureSet, 0u, image );
914     Sampler sampler = Sampler::New();
915     sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
916     textureSet.SetSampler( 0u, sampler );
917   }
918 }
919
920 // From existing atlas manager
921 void ImageVisual::UploadCompleted()
922 {
923   // Texture has been uploaded. If weak handle is holding a placement actor,
924   // it is the time to add the renderer to actor.
925   Actor actor = mPlacementActor.GetHandle();
926   if( actor )
927   {
928     mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
929     actor.AddRenderer( mImpl->mRenderer );
930     // reset the weak handle so that the renderer only get added to actor once
931     mPlacementActor.Reset();
932   }
933   // Image loaded
934   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
935   mLoading = false;
936 }
937
938 // From Texture Manager
939 void ImageVisual::UploadComplete( bool loadingSuccess, int32_t textureId, TextureSet textureSet, bool usingAtlas,
940                                   const Vector4& atlasRectangle, bool preMultiplied )
941 {
942   Toolkit::Visual::ResourceStatus resourceStatus;
943   if( mImpl->mRenderer )
944   {
945     if( usingAtlas )
946     {
947       mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, mAtlasRect );
948     }
949
950     EnablePreMultipliedAlpha( preMultiplied );
951
952     Actor actor = mPlacementActor.GetHandle();
953     if( actor )
954     {
955       actor.AddRenderer( mImpl->mRenderer );
956       // reset the weak handle so that the renderer only get added to actor once
957       mPlacementActor.Reset();
958     }
959
960     if( loadingSuccess )
961     {
962       Sampler sampler = Sampler::New();
963       sampler.SetWrapMode(  mWrapModeU, mWrapModeV  );
964       textureSet.SetSampler( 0u, sampler );
965       mImpl->mRenderer.SetTextures(textureSet);
966     }
967     else
968     {
969       Image brokenImage = mFactoryCache.GetBrokenVisualImage();
970
971       textureSet = TextureSet::New();
972       mImpl->mRenderer.SetTextures( textureSet );
973
974       ApplyImageToSampler( brokenImage );
975     }
976   }
977
978   // Storing TextureSet needed when renderer staged.
979   if( ! mImpl->mRenderer )
980   {
981     mTextures = textureSet;
982   }
983
984   // Image loaded, set status regardless of staged status.
985   if( loadingSuccess )
986   {
987     resourceStatus = Toolkit::Visual::ResourceStatus::READY;
988   }
989   else
990   {
991     resourceStatus = Toolkit::Visual::ResourceStatus::FAILED;
992   }
993   // Signal to observers ( control ) that resources are ready. Must be all resources.
994   ResourceReady( resourceStatus );
995   mLoading = false;
996 }
997
998 void ImageVisual::RemoveTexture()
999 {
1000   if( mTextureId != TextureManager::INVALID_TEXTURE_ID )
1001   {
1002     mFactoryCache.GetTextureManager().Remove( mTextureId, this );
1003     mTextureId = TextureManager::INVALID_TEXTURE_ID;
1004   }
1005   else
1006   {
1007     Vector4 atlasRect( 0.f, 0.f, 1.f, 1.f );
1008     Property::Index index = mImpl->mRenderer.GetPropertyIndex( ATLAS_RECT_UNIFORM_NAME );
1009     if( index != Property::INVALID_INDEX )
1010     {
1011       Property::Value atlasRectValue = mImpl->mRenderer.GetProperty( index );
1012       atlasRectValue.Get( atlasRect );
1013     }
1014
1015     TextureSet textureSet = mImpl->mRenderer.GetTextures();
1016     mImpl->mRenderer.Reset();
1017
1018     if( index != Property::INVALID_INDEX )
1019     {
1020       mFactoryCache.GetAtlasManager()->Remove( textureSet, atlasRect );
1021     }
1022   }
1023 }
1024
1025 } // namespace Internal
1026
1027 } // namespace Toolkit
1028
1029 } // namespace Dali