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