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