Merge "DALi Version 2.1.20" into devel/master
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / texture-manager / texture-manager-impl.cpp
1 /*
2  * Copyright (c) 2022 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 "texture-manager-impl.h"
20
21 // EXTERNAL HEADERS
22 #include <dali/devel-api/adaptor-framework/environment-variable.h>
23 #include <dali/devel-api/adaptor-framework/image-loading.h>
24 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
25 #include <dali/integration-api/debug.h>
26 #include <dali/public-api/rendering/geometry.h>
27
28 // INTERNAL HEADERS
29 #include <dali-toolkit/internal/texture-manager/texture-async-loading-helper.h>
30 #include <dali-toolkit/internal/texture-manager/texture-cache-manager.h>
31 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
32 #include <dali-toolkit/internal/visuals/rendering-addon.h>
33
34 namespace
35 {
36 constexpr auto INITIAL_HASH_NUMBER                     = size_t{0u};
37 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS  = size_t{4u};
38 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
39
40 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV  = "DALI_TEXTURE_LOCAL_THREADS";
41 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
42
43 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
44 {
45   using Dali::EnvironmentVariable::GetEnvironmentVariable;
46   auto           numberString          = GetEnvironmentVariable(environmentVariable);
47   auto           numberOfThreads       = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
48   constexpr auto MAX_NUMBER_OF_THREADS = 100u;
49   DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
50   return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
51 }
52
53 size_t GetNumberOfLocalLoaderThreads()
54 {
55   return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
56 }
57
58 size_t GetNumberOfRemoteLoaderThreads()
59 {
60   return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
61 }
62
63 } // namespace
64
65 namespace Dali
66 {
67 namespace Toolkit
68 {
69 namespace Internal
70 {
71 #ifdef DEBUG_ENABLED
72 // Define logfilter Internal namespace level so other files (e.g. texture-cache-manager.cpp) can also use this filter.
73 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
74
75 // clang-format off
76 #define GET_LOAD_STATE_STRING(loadState) \
77   loadState == TextureManagerType::LoadState::NOT_STARTED      ? "NOT_STARTED"      : \
78   loadState == TextureManagerType::LoadState::LOADING          ? "LOADING"          : \
79   loadState == TextureManagerType::LoadState::LOAD_FINISHED    ? "LOAD_FINISHED"    : \
80   loadState == TextureManagerType::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
81   loadState == TextureManagerType::LoadState::MASK_APPLYING    ? "MASK_APPLYING"    : \
82   loadState == TextureManagerType::LoadState::MASK_APPLIED     ? "MASK_APPLIED"     : \
83   loadState == TextureManagerType::LoadState::UPLOADED         ? "UPLOADED"         : \
84   loadState == TextureManagerType::LoadState::CANCELLED        ? "CANCELLED"        : \
85   loadState == TextureManagerType::LoadState::LOAD_FAILED      ? "LOAD_FAILED"      : \
86                                                                  "Unknown"
87 // clang-format on
88 #endif
89
90 namespace
91 {
92 const uint32_t DEFAULT_ATLAS_SIZE(1024u);               ///< This size can fit 8 by 8 images of average size 128 * 128
93 const Vector4  FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
94
95 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
96 {
97   if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
98   {
99     if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
100     {
101       pixelBuffer.MultiplyColorByAlpha();
102     }
103   }
104   else
105   {
106     preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
107   }
108 }
109
110 } // Anonymous namespace
111
112 TextureManager::MaskingData::MaskingData()
113 : mAlphaMaskUrl(),
114   mAlphaMaskId(INVALID_TEXTURE_ID),
115   mContentScaleFactor(1.0f),
116   mCropToMask(true)
117 {
118 }
119
120 TextureManager::TextureManager()
121 : mTextureCacheManager(),
122   mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]() { return TextureAsyncLoadingHelper(*this); }),
123   mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]() { return TextureAsyncLoadingHelper(*this); }),
124   mLifecycleObservers(),
125   mLoadQueue(),
126   mQueueLoadFlag(false)
127 {
128   // Initialize the AddOn
129   RenderingAddOn::Get();
130 }
131
132 TextureManager::~TextureManager()
133 {
134   for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
135   {
136     (*iter)->TextureManagerDestroyed();
137   }
138 }
139
140 TextureSet TextureManager::LoadAnimatedImageTexture(Dali::AnimatedImageLoading      animatedImageLoading,
141                                                     const uint32_t&                 frameIndex,
142                                                     TextureManager::TextureId&      textureId,
143                                                     const Dali::SamplingMode::Type& samplingMode,
144                                                     const Dali::WrapMode::Type&     wrapModeU,
145                                                     const Dali::WrapMode::Type&     wrapModeV,
146                                                     const bool&                     synchronousLoading,
147                                                     const bool&                     useCache,
148                                                     TextureUploadObserver*          textureObserver)
149 {
150   TextureSet textureSet;
151
152   if(synchronousLoading)
153   {
154     Devel::PixelBuffer pixelBuffer;
155     if(animatedImageLoading)
156     {
157       pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
158     }
159     if(!pixelBuffer)
160     {
161       DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
162     }
163     else
164     {
165       PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
166       if(!textureSet)
167       {
168         Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelData.GetPixelFormat(), pixelData.GetWidth(), pixelData.GetHeight());
169         texture.Upload(pixelData);
170         textureSet = TextureSet::New();
171         textureSet.SetTexture(0u, texture);
172       }
173     }
174   }
175   else
176   {
177     auto preMultiply                    = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
178     textureId                           = RequestLoadInternal(animatedImageLoading.GetUrl(), INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::BOX_THEN_LINEAR, UseAtlas::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex, false, useCache);
179     TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
180     if(loadState == TextureManager::LoadState::UPLOADED)
181     {
182       // LoadComplete has already been called - keep the same texture set
183       textureSet = GetTextureSet(textureId);
184     }
185   }
186
187   if(textureSet)
188   {
189     Sampler sampler = Sampler::New();
190     sampler.SetWrapMode(wrapModeU, wrapModeV);
191     textureSet.SetSampler(0u, sampler);
192   }
193
194   return textureSet;
195 }
196
197 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
198   const VisualUrl&                url,
199   const Dali::ImageDimensions&    desiredSize,
200   const Dali::FittingMode::Type&  fittingMode,
201   const Dali::SamplingMode::Type& samplingMode,
202   const bool&                     synchronousLoading,
203   TextureUploadObserver*          textureObserver,
204   const bool&                     orientationCorrection,
205   TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
206 {
207   Devel::PixelBuffer pixelBuffer;
208   if(synchronousLoading)
209   {
210     if(url.IsValid())
211     {
212       if(url.IsBufferResource())
213       {
214         const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url.GetUrl());
215         if(encodedImageBuffer)
216         {
217           pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
218         }
219       }
220       else
221       {
222         pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
223       }
224       if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
225       {
226         PreMultiply(pixelBuffer, preMultiplyOnLoad);
227       }
228     }
229   }
230   else
231   {
232     RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, UseAtlas::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, false, false);
233   }
234
235   return pixelBuffer;
236 }
237
238 TextureSet TextureManager::LoadTexture(
239   const VisualUrl&                    url,
240   const Dali::ImageDimensions&        desiredSize,
241   const Dali::FittingMode::Type&      fittingMode,
242   const Dali::SamplingMode::Type&     samplingMode,
243   MaskingDataPointer&                 maskInfo,
244   const bool&                         synchronousLoading,
245   TextureManager::TextureId&          textureId,
246   Vector4&                            textureRect,
247   Dali::ImageDimensions&              textureRectSize,
248   bool&                               atlasingStatus,
249   bool&                               loadingStatus,
250   const Dali::WrapMode::Type&         wrapModeU,
251   const Dali::WrapMode::Type&         wrapModeV,
252   TextureUploadObserver*              textureObserver,
253   AtlasUploadObserver*                atlasObserver,
254   ImageAtlasManagerPtr                imageAtlasManager,
255   const bool&                         orientationCorrection,
256   const TextureManager::ReloadPolicy& reloadPolicy,
257   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad)
258 {
259   TextureSet textureSet;
260
261   loadingStatus = false;
262   textureRect   = FULL_ATLAS_RECT;
263
264   if(VisualUrl::TEXTURE == url.GetProtocolType())
265   {
266     std::string location = url.GetLocation();
267     if(location.size() > 0u)
268     {
269       TextureId id = std::stoi(location);
270       textureSet   = mTextureCacheManager.GetExternalTextureSet(id);
271       if(textureSet)
272       {
273         preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
274         textureId         = id;
275         return textureSet;
276       }
277     }
278   }
279   else
280   {
281     // For Atlas
282     if(synchronousLoading && atlasingStatus && imageAtlasManager->CheckAtlasAvailable(url, desiredSize))
283     {
284       Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
285
286       if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
287       {
288         Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
289         if(maskPixelBuffer)
290         {
291           pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
292         }
293       }
294
295       PixelData data;
296       if(pixelBuffer)
297       {
298         PreMultiply(pixelBuffer, preMultiplyOnLoad);
299         data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
300
301         if(data)
302         {
303           textureSet = imageAtlasManager->Add(textureRect, data);
304           if(textureSet)
305           {
306             textureRectSize.SetWidth(data.GetWidth());
307             textureRectSize.SetHeight(data.GetHeight());
308           }
309         }
310         else
311         {
312           DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
313         }
314       }
315       if(!textureSet)
316       {
317         atlasingStatus = false;
318       }
319     }
320
321     if(!textureSet)
322     {
323       loadingStatus = true;
324       // Atlas manager can chage desired size when it is set by 0,0.
325       // We should store into textureRectSize only if atlasing successed.
326       // So copy inputed desiredSize, and replace value into textureRectSize only if atlasing success.
327       Dali::ImageDimensions atlasDesiredSize = desiredSize;
328       if(atlasingStatus)
329       {
330         textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), atlasDesiredSize, fittingMode, true, atlasObserver);
331       }
332       if(!textureSet) // big image, no atlasing or atlasing failed
333       {
334         atlasingStatus = false;
335         if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
336         {
337           textureId = RequestLoad(
338             url,
339             desiredSize,
340             fittingMode,
341             samplingMode,
342             UseAtlas::NO_ATLAS,
343             textureObserver,
344             orientationCorrection,
345             reloadPolicy,
346             preMultiplyOnLoad,
347             synchronousLoading);
348         }
349         else
350         {
351           maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
352           textureId              = RequestLoad(
353             url,
354             maskInfo->mAlphaMaskId,
355             maskInfo->mContentScaleFactor,
356             desiredSize,
357             fittingMode,
358             samplingMode,
359             UseAtlas::NO_ATLAS,
360             maskInfo->mCropToMask,
361             textureObserver,
362             orientationCorrection,
363             reloadPolicy,
364             preMultiplyOnLoad,
365             synchronousLoading);
366         }
367
368         TextureManager::LoadState loadState = mTextureCacheManager.GetTextureStateInternal(textureId);
369         if(loadState == TextureManager::LoadState::UPLOADED)
370         {
371           // LoadComplete has already been called - keep the same texture set
372           textureSet = mTextureCacheManager.GetTextureSet(textureId);
373         }
374
375         // If we are loading the texture, or waiting for the ready signal handler to complete, inform
376         // caller that they need to wait.
377         loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
378                          loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
379                          loadState == TextureManager::LoadState::MASK_APPLYING ||
380                          loadState == TextureManager::LoadState::MASK_APPLIED ||
381                          loadState == TextureManager::LoadState::NOT_STARTED ||
382                          mQueueLoadFlag);
383       }
384       else
385       {
386         textureRectSize = atlasDesiredSize;
387       }
388     }
389   }
390
391   if(!atlasingStatus && textureSet)
392   {
393     Sampler sampler = Sampler::New();
394     sampler.SetWrapMode(wrapModeU, wrapModeV);
395     textureSet.SetSampler(0u, sampler);
396   }
397
398   if(synchronousLoading)
399   {
400     loadingStatus = false;
401   }
402
403   return textureSet;
404 }
405
406 TextureManager::TextureId TextureManager::RequestLoad(
407   const VisualUrl&                    url,
408   const ImageDimensions&              desiredSize,
409   const Dali::FittingMode::Type&      fittingMode,
410   const Dali::SamplingMode::Type&     samplingMode,
411   const UseAtlas&                     useAtlas,
412   TextureUploadObserver*              observer,
413   const bool&                         orientationCorrection,
414   const TextureManager::ReloadPolicy& reloadPolicy,
415   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
416   const bool&                         synchronousLoading)
417 {
418   return RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas, false, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
419 }
420
421 TextureManager::TextureId TextureManager::RequestLoad(
422   const VisualUrl&                    url,
423   const TextureManager::TextureId&    maskTextureId,
424   const float&                        contentScale,
425   const Dali::ImageDimensions&        desiredSize,
426   const Dali::FittingMode::Type&      fittingMode,
427   const Dali::SamplingMode::Type&     samplingMode,
428   const TextureManager::UseAtlas&     useAtlas,
429   const bool&                         cropToMask,
430   TextureUploadObserver*              observer,
431   const bool&                         orientationCorrection,
432   const TextureManager::ReloadPolicy& reloadPolicy,
433   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
434   const bool&                         synchronousLoading)
435 {
436   return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
437 }
438
439 TextureManager::TextureId TextureManager::RequestMaskLoad(
440   const VisualUrl& maskUrl,
441   const bool&      synchronousLoading)
442 {
443   // Use the normal load procedure to get the alpha mask.
444   auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
445   return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, UseAtlas::NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u, synchronousLoading, true);
446 }
447
448 TextureManager::TextureId TextureManager::RequestLoadInternal(
449   const VisualUrl&                    url,
450   const TextureManager::TextureId&    maskTextureId,
451   const float&                        contentScale,
452   const Dali::ImageDimensions&        desiredSize,
453   const Dali::FittingMode::Type&      fittingMode,
454   const Dali::SamplingMode::Type&     samplingMode,
455   const TextureManager::UseAtlas&     useAtlas,
456   const bool&                         cropToMask,
457   const TextureManager::StorageType&  storageType,
458   TextureUploadObserver*              observer,
459   const bool&                         orientationCorrection,
460   const TextureManager::ReloadPolicy& reloadPolicy,
461   TextureManager::MultiplyOnLoad&     preMultiplyOnLoad,
462   Dali::AnimatedImageLoading          animatedImageLoading,
463   const std::uint32_t&                frameIndex,
464   const bool&                         synchronousLoading,
465   const bool&                         useCache)
466 {
467   TextureHash       textureHash = INITIAL_HASH_NUMBER;
468   TextureCacheIndex cacheIndex  = INVALID_CACHE_INDEX;
469   if(storageType != StorageType::RETURN_PIXEL_BUFFER && useCache)
470   {
471     textureHash = mTextureCacheManager.GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, cropToMask);
472
473     // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
474     cacheIndex = mTextureCacheManager.FindCachedTexture(textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, preMultiplyOnLoad, (animatedImageLoading) ? true : false, cropToMask);
475   }
476
477   TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
478   // Check if the requested Texture exists in the cache.
479   if(cacheIndex != INVALID_CACHE_INDEX)
480   {
481     if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
482     {
483       // Mark this texture being used by another client resource. Forced reload would replace the current texture
484       // without the need for incrementing the reference count.
485       ++(mTextureCacheManager[cacheIndex].referenceCount);
486     }
487     textureId = mTextureCacheManager[cacheIndex].textureId;
488
489     // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
490     preMultiplyOnLoad = mTextureCacheManager[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
491
492     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
493   }
494
495   if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
496   {
497     if(VisualUrl::BUFFER == url.GetProtocolType())
498     {
499       std::string location = url.GetLocation();
500       if(location.size() > 0u)
501       {
502         TextureId                 targetId           = std::stoi(location);
503         const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(targetId);
504         if(encodedImageBuffer)
505         {
506           textureId = targetId;
507
508           // Increase EncodedImageBuffer reference during it contains mTextureInfoContainer.
509           // TODO! We should change action when reload policy is FORCE.
510           // Eunki Hong will fix it after refactoring patch merged.
511           mTextureCacheManager.UseExternalResource(url.GetUrl());
512         }
513       }
514     }
515
516     if(textureId == INVALID_TEXTURE_ID)
517     {
518       textureId = mTextureCacheManager.GenerateUniqueTextureId();
519     }
520
521     bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
522
523     // Cache new texutre, and get cacheIndex.
524     cacheIndex = mTextureCacheManager.AppendCache(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
525
526     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
527   }
528
529   // The below code path is common whether we are using the cache or not.
530   // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
531   // or a new TextureInfo just created.
532   TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
533   textureInfo.maskTextureId         = maskTextureId;
534   textureInfo.storageType           = storageType;
535   textureInfo.orientationCorrection = orientationCorrection;
536
537   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
538
539   // Force reloading of texture by setting loadState unless already loading or cancelled.
540   if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
541      TextureManager::LoadState::LOADING != textureInfo.loadState &&
542      TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
543      TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
544      TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
545      TextureManager::LoadState::CANCELLED != textureInfo.loadState)
546   {
547     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n", url.GetUrl().c_str(), observer, cacheIndex, textureId);
548
549     textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
550   }
551
552   if(!synchronousLoading)
553   {
554     // Check if we should add the observer.
555     // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
556     switch(textureInfo.loadState)
557     {
558       case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
559       case TextureManager::LoadState::NOT_STARTED:
560       {
561         LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
562         break;
563       }
564       case TextureManager::LoadState::LOADING:
565       case TextureManager::LoadState::WAITING_FOR_MASK:
566       case TextureManager::LoadState::MASK_APPLYING:
567       case TextureManager::LoadState::MASK_APPLIED:
568       {
569         ObserveTexture(textureInfo, observer);
570         break;
571       }
572       case TextureManager::LoadState::UPLOADED:
573       {
574         if(observer)
575         {
576           LoadOrQueueTexture(textureInfo, observer);
577         }
578         break;
579       }
580       case TextureManager::LoadState::CANCELLED:
581       {
582         // A cancelled texture hasn't finished loading yet. Treat as a loading texture
583         // (it's ref count has already been incremented, above)
584         textureInfo.loadState = TextureManager::LoadState::LOADING;
585         ObserveTexture(textureInfo, observer);
586         break;
587       }
588       case TextureManager::LoadState::LOAD_FINISHED:
589       {
590         // Loading has already completed.
591         if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
592         {
593           LoadOrQueueTexture(textureInfo, observer);
594         }
595         break;
596       }
597     }
598   }
599   else
600   {
601     // If the image is already finished to load, use cached texture.
602     // We don't need to consider Observer because this is synchronous loading.
603     if(!(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
604          textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED))
605     {
606       Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
607
608       if(!pixelBuffer)
609       {
610         // If pixelBuffer loading is failed in synchronously, call Remove() method.
611         Remove(textureId, nullptr);
612         return INVALID_TEXTURE_ID;
613       }
614
615       if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
616       {
617         textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
618         textureInfo.loadState   = LoadState::LOAD_FINISHED;
619       }
620       else // For the image loading.
621       {
622         if(maskTextureId != INVALID_TEXTURE_ID)
623         {
624           TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
625           if(maskCacheIndex != INVALID_CACHE_INDEX)
626           {
627             Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
628             if(maskPixelBuffer)
629             {
630               pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
631             }
632             else
633             {
634               DALI_LOG_ERROR("Mask image cached invalid pixel buffer!\n");
635             }
636           }
637           else
638           {
639             DALI_LOG_ERROR("Mask image is not stored in cache.\n");
640           }
641         }
642         PreMultiply(pixelBuffer, preMultiplyOnLoad);
643
644         // Upload texture
645         UploadTexture(pixelBuffer, textureInfo);
646       }
647     }
648   }
649   return textureId;
650 }
651
652 void TextureManager::Remove(const TextureManager::TextureId& textureId, TextureUploadObserver* observer)
653 {
654   // Remove textureId in CacheManager.
655   mTextureCacheManager.RemoveCache(textureId);
656
657   if(observer)
658   {
659     // Remove element from the LoadQueue
660     for(auto&& element : mLoadQueue)
661     {
662       if(element.mObserver == observer)
663       {
664         // Do not erase the item. We will clear it later in ProcessQueuedTextures().
665         element.mObserver = nullptr;
666         break;
667       }
668     }
669   }
670 }
671
672 Devel::PixelBuffer TextureManager::LoadImageSynchronously(
673   const VisualUrl&                url,
674   const Dali::ImageDimensions&    desiredSize,
675   const Dali::FittingMode::Type&  fittingMode,
676   const Dali::SamplingMode::Type& samplingMode,
677   const bool&                     orientationCorrection)
678 {
679   Devel::PixelBuffer pixelBuffer;
680   if(url.IsBufferResource())
681   {
682     const EncodedImageBuffer& encodedImageBuffer = mTextureCacheManager.GetEncodedImageBuffer(url.GetUrl());
683     if(encodedImageBuffer)
684     {
685       pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
686     }
687   }
688   else
689   {
690     pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
691   }
692   return pixelBuffer;
693 }
694
695 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
696 {
697   // make sure an observer doesn't observe the same object twice
698   // otherwise it will get multiple calls to ObjectDestroyed()
699   DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
700   mLifecycleObservers.PushBack(&observer);
701 }
702
703 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
704 {
705   // Find the observer...
706   auto endIter = mLifecycleObservers.End();
707   for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
708   {
709     if((*iter) == &observer)
710     {
711       mLifecycleObservers.Erase(iter);
712       break;
713     }
714   }
715   DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
716 }
717
718 void TextureManager::LoadOrQueueTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
719 {
720   switch(textureInfo.loadState)
721   {
722     case LoadState::NOT_STARTED:
723     case LoadState::LOAD_FAILED:
724     {
725       if(mQueueLoadFlag)
726       {
727         QueueLoadTexture(textureInfo, observer);
728       }
729       else
730       {
731         LoadTexture(textureInfo, observer);
732       }
733       break;
734     }
735     case LoadState::UPLOADED:
736     {
737       if(mQueueLoadFlag)
738       {
739         QueueLoadTexture(textureInfo, observer);
740       }
741       else
742       {
743         // The Texture has already loaded. The other observers have already been notified.
744         // We need to send a "late" loaded notification for this observer.
745         EmitLoadComplete(observer, textureInfo, true);
746       }
747       break;
748     }
749     case LoadState::LOADING:
750     case LoadState::CANCELLED:
751     case LoadState::LOAD_FINISHED:
752     case LoadState::WAITING_FOR_MASK:
753     case LoadState::MASK_APPLYING:
754     case LoadState::MASK_APPLIED:
755     {
756       break;
757     }
758   }
759 }
760
761 void TextureManager::QueueLoadTexture(const TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
762 {
763   const auto& textureId = textureInfo.textureId;
764   mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
765
766   observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
767 }
768
769 void TextureManager::LoadTexture(TextureManager::TextureInfo& textureInfo, TextureUploadObserver* observer)
770 {
771   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
772
773   textureInfo.loadState = LoadState::LOADING;
774   if(!textureInfo.loadSynchronously)
775   {
776     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
777     auto  loadingHelperIt   = loadersContainer.GetNext();
778     auto  premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
779     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
780     if(textureInfo.animatedImageLoading)
781     {
782       loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
783     }
784     else
785     {
786       loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
787     }
788   }
789   ObserveTexture(textureInfo, observer);
790 }
791
792 void TextureManager::ProcessQueuedTextures()
793 {
794   for(auto&& element : mLoadQueue)
795   {
796     if(!element.mObserver)
797     {
798       continue;
799     }
800
801     TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(element.mTextureId);
802     if(cacheIndex != INVALID_CACHE_INDEX)
803     {
804       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
805       if((textureInfo.loadState == LoadState::UPLOADED) || (textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER))
806       {
807         EmitLoadComplete(element.mObserver, textureInfo, true);
808       }
809       else
810       {
811         LoadTexture(textureInfo, element.mObserver);
812       }
813     }
814   }
815   mLoadQueue.Clear();
816 }
817
818 void TextureManager::ObserveTexture(TextureManager::TextureInfo& textureInfo,
819                                     TextureUploadObserver*       observer)
820 {
821   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
822
823   if(observer)
824   {
825     textureInfo.observerList.PushBack(observer);
826     observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
827   }
828 }
829
830 void TextureManager::AsyncLoadComplete(const TextureManager::TextureId& textureId, Devel::PixelBuffer pixelBuffer)
831 {
832   DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( textureId:%d )\n", textureId);
833   TextureCacheIndex cacheIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
834   if(cacheIndex != INVALID_CACHE_INDEX)
835   {
836     TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
837
838     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "  textureId:%d Url:%s CacheIndex:%d LoadState: %s\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, GET_LOAD_STATE_STRING(textureInfo.loadState));
839
840     if(textureInfo.loadState != LoadState::CANCELLED)
841     {
842       // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
843       PostLoad(textureInfo, pixelBuffer);
844     }
845     else
846     {
847       Remove(textureInfo.textureId, nullptr);
848     }
849   }
850 }
851
852 void TextureManager::PostLoad(TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
853 {
854   // Was the load successful?
855   if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
856   {
857     // No atlas support for now
858     textureInfo.useAtlas      = UseAtlas::NO_ATLAS;
859     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
860
861     if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
862     {
863       // If there is a mask texture ID associated with this texture, then apply the mask
864       // if it's already loaded. If it hasn't, and the mask is still loading,
865       // wait for the mask to finish loading.
866       // note, If the texture is already uploaded synchronously during loading,
867       // we don't need to apply mask.
868       if(textureInfo.loadState != LoadState::UPLOADED &&
869          textureInfo.maskTextureId != INVALID_TEXTURE_ID)
870       {
871         if(textureInfo.loadState == LoadState::MASK_APPLYING)
872         {
873           textureInfo.loadState = LoadState::MASK_APPLIED;
874           UploadTexture(pixelBuffer, textureInfo);
875           NotifyObservers(textureInfo, true);
876         }
877         else
878         {
879           LoadState maskLoadState = mTextureCacheManager.GetTextureStateInternal(textureInfo.maskTextureId);
880           textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
881           if(maskLoadState == LoadState::LOADING)
882           {
883             textureInfo.loadState = LoadState::WAITING_FOR_MASK;
884           }
885           else if(maskLoadState == LoadState::LOAD_FINISHED)
886           {
887             // Send New Task to Thread
888             ApplyMask(textureInfo, textureInfo.maskTextureId);
889           }
890           else // maskLoadState == LoadState::LOAD_FAILED
891           {
892             // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
893             DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
894             UploadTexture(pixelBuffer, textureInfo);
895             NotifyObservers(textureInfo, true);
896           }
897         }
898       }
899       else
900       {
901         UploadTexture(pixelBuffer, textureInfo);
902         NotifyObservers(textureInfo, true);
903       }
904     }
905     else
906     {
907       textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
908       textureInfo.loadState   = LoadState::LOAD_FINISHED;
909
910       if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
911       {
912         NotifyObservers(textureInfo, true);
913       }
914       else
915       {
916         // Check if there was another texture waiting for this load to complete
917         // (e.g. if this was an image mask, and its load is on a different thread)
918         CheckForWaitingTexture(textureInfo);
919       }
920     }
921   }
922   else
923   {
924     textureInfo.loadState = LoadState::LOAD_FAILED;
925     if(textureInfo.storageType != StorageType::KEEP_PIXEL_BUFFER)
926     {
927       NotifyObservers(textureInfo, false);
928     }
929     else // if(textureInfo.storageType == StorageType::KEEP_PIXEL_BUFFER) // image mask case
930     {
931       // Check if there was another texture waiting for this load to complete
932       // (e.g. if this was an image mask, and its load is on a different thread)
933       CheckForWaitingTexture(textureInfo);
934     }
935   }
936 }
937
938 void TextureManager::CheckForWaitingTexture(TextureManager::TextureInfo& maskTextureInfo)
939 {
940   // Search the cache, checking if any texture has this texture id as a
941   // maskTextureId:
942   const TextureCacheIndex size = static_cast<TextureCacheIndex>(mTextureCacheManager.size());
943
944   const bool maskLoadSuccess = maskTextureInfo.loadState == LoadState::LOAD_FINISHED ? true : false;
945
946   for(TextureCacheIndex cacheIndex = 0; cacheIndex < size; ++cacheIndex)
947   {
948     if(mTextureCacheManager[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
949        mTextureCacheManager[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
950     {
951       TextureInfo& textureInfo(mTextureCacheManager[cacheIndex]);
952
953       if(maskLoadSuccess)
954       {
955         // Send New Task to Thread
956         ApplyMask(textureInfo, maskTextureInfo.textureId);
957       }
958       else
959       {
960         // Url texture load success, But alpha mask texture load failed. Run as normal image upload.
961         DALI_LOG_ERROR("Alpha mask image loading failed! Image will not be masked\n");
962         UploadTexture(textureInfo.pixelBuffer, textureInfo);
963         NotifyObservers(textureInfo, true);
964       }
965     }
966   }
967 }
968
969 void TextureManager::ApplyMask(TextureManager::TextureInfo& textureInfo, const TextureManager::TextureId& maskTextureId)
970 {
971   TextureCacheIndex maskCacheIndex = mTextureCacheManager.GetCacheIndexFromId(maskTextureId);
972   if(maskCacheIndex != INVALID_CACHE_INDEX)
973   {
974     Devel::PixelBuffer maskPixelBuffer = mTextureCacheManager[maskCacheIndex].pixelBuffer;
975     Devel::PixelBuffer pixelBuffer     = textureInfo.pixelBuffer;
976     textureInfo.pixelBuffer.Reset();
977
978     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
979
980     textureInfo.loadState   = LoadState::MASK_APPLYING;
981     auto& loadersContainer  = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
982     auto  loadingHelperIt   = loadersContainer.GetNext();
983     auto  premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
984     DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
985     loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
986   }
987 }
988
989 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureManager::TextureInfo& textureInfo)
990 {
991   if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != UseAtlas::USE_ATLAS)
992   {
993     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "  TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
994
995     // Check if this pixelBuffer is premultiplied
996     textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
997
998     auto& renderingAddOn = RenderingAddOn::Get();
999     if(renderingAddOn.IsValid())
1000     {
1001       renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1002     }
1003
1004     Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1005
1006     PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1007     texture.Upload(pixelData);
1008     if(!textureInfo.textureSet)
1009     {
1010       textureInfo.textureSet = TextureSet::New();
1011     }
1012     textureInfo.textureSet.SetTexture(0u, texture);
1013   }
1014
1015   // Update the load state.
1016   // Note: This is regardless of success as we care about whether a
1017   // load attempt is in progress or not.  If unsuccessful, a broken
1018   // image is still loaded.
1019   textureInfo.loadState = LoadState::UPLOADED;
1020 }
1021
1022 void TextureManager::NotifyObservers(TextureManager::TextureInfo& textureInfo, const bool& success)
1023 {
1024   TextureId textureId = textureInfo.textureId;
1025
1026   // If there is an observer: Notify the load is complete, whether successful or not,
1027   // and erase it from the list
1028   TextureInfo* info = &textureInfo;
1029
1030   if(info->animatedImageLoading)
1031   {
1032     // If loading failed, we don't need to get frameCount and frameInterval.
1033     if(success)
1034     {
1035       info->frameCount    = info->animatedImageLoading.GetImageCount();
1036       info->frameInterval = info->animatedImageLoading.GetFrameInterval(info->frameIndex);
1037     }
1038     info->animatedImageLoading.Reset();
1039   }
1040
1041   mQueueLoadFlag = true;
1042
1043   while(info->observerList.Count())
1044   {
1045     TextureUploadObserver* observer = info->observerList[0];
1046
1047     // During LoadComplete() a Control ResourceReady() signal is emitted.
1048     // During that signal the app may add remove /add Textures (e.g. via
1049     // ImageViews).
1050     // It is possible for observers to be removed from the observer list,
1051     // and it is also possible for the mTextureInfoContainer to be modified,
1052     // invalidating the reference to the textureInfo struct.
1053     // Texture load requests for the same URL are deferred until the end of this
1054     // method.
1055     DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::NotifyObservers() textureId:%d url:%s loadState:%s\n", textureId, textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState));
1056
1057     // It is possible for the observer to be deleted.
1058     // Disconnect and remove the observer first.
1059     observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1060
1061     info->observerList.Erase(info->observerList.Begin());
1062
1063     EmitLoadComplete(observer, *info, success);
1064
1065     // Get the textureInfo from the container again as it may have been invalidated.
1066     TextureCacheIndex textureInfoIndex = mTextureCacheManager.GetCacheIndexFromId(textureId);
1067     if(textureInfoIndex == INVALID_CACHE_INDEX)
1068     {
1069       break; // texture has been removed - can stop.
1070     }
1071     info = &mTextureCacheManager[textureInfoIndex];
1072   }
1073
1074   mQueueLoadFlag = false;
1075   ProcessQueuedTextures();
1076
1077   if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1078   {
1079     Remove(info->textureId, nullptr);
1080   }
1081 }
1082
1083 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1084 {
1085   const TextureCacheIndex count = static_cast<TextureCacheIndex>(mTextureCacheManager.size());
1086   for(TextureCacheIndex i = 0; i < count; ++i)
1087   {
1088     TextureInfo& textureInfo(mTextureCacheManager[i]);
1089     for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1090         j != textureInfo.observerList.End();)
1091     {
1092       if(*j == observer)
1093       {
1094         j = textureInfo.observerList.Erase(j);
1095       }
1096       else
1097       {
1098         ++j;
1099       }
1100     }
1101   }
1102
1103   // Remove element from the LoadQueue
1104   for(auto&& element : mLoadQueue)
1105   {
1106     if(element.mObserver == observer)
1107     {
1108       element.mObserver = nullptr;
1109     }
1110   }
1111 }
1112
1113 Dali::Geometry TextureManager::GetRenderGeometry(const TextureManager::TextureId& textureId, std::uint32_t& frontElements, std::uint32_t& backElements)
1114 {
1115   return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1116 }
1117
1118 void TextureManager::EmitLoadComplete(TextureUploadObserver* observer, TextureManager::TextureInfo& textureInfo, const bool& success)
1119 {
1120   if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1121   {
1122     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1123   }
1124   else if(textureInfo.isAnimatedImageFormat)
1125   {
1126     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::ANIMATED_IMAGE_TEXTURE, textureInfo.textureId, textureInfo.frameCount, textureInfo.frameInterval));
1127   }
1128   else
1129   {
1130     observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, (textureInfo.useAtlas == UseAtlas::USE_ATLAS) ? true : false, textureInfo.atlasRect, textureInfo.preMultiplied));
1131   }
1132 }
1133
1134 } // namespace Internal
1135
1136 } // namespace Toolkit
1137
1138 } // namespace Dali