2 * Copyright (c) 2021 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include <dali-toolkit/internal/visuals/texture-manager-impl.h>
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/devel-api/common/hash.h>
26 #include <dali/integration-api/debug.h>
27 #include <dali/public-api/math/vector4.h>
28 #include <dali/public-api/rendering/geometry.h>
33 #include <dali-toolkit/internal/image-loader/async-image-loader-impl.h>
34 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
36 #include <dali-toolkit/internal/visuals/rendering-addon.h>
37 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
41 constexpr auto INITIAL_CACHE_NUMBER = size_t{0u};
42 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
43 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
45 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
46 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
48 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
50 using Dali::EnvironmentVariable::GetEnvironmentVariable;
51 auto numberString = GetEnvironmentVariable(environmentVariable);
52 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
53 constexpr auto MAX_NUMBER_OF_THREADS = 100u;
54 DALI_ASSERT_DEBUG(numberOfThreads < MAX_NUMBER_OF_THREADS);
55 return (numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS) ? numberOfThreads : defaultValue;
58 size_t GetNumberOfLocalLoaderThreads()
60 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
63 size_t GetNumberOfRemoteLoaderThreads()
65 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
79 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_TEXTURE_MANAGER");
81 #define GET_LOAD_STATE_STRING(loadState) \
82 loadState == TextureManager::LoadState::NOT_STARTED ? "NOT_STARTED" : loadState == TextureManager::LoadState::LOADING ? "LOADING" \
83 : loadState == TextureManager::LoadState::LOAD_FINISHED ? "LOAD_FINISHED" \
84 : loadState == TextureManager::LoadState::WAITING_FOR_MASK ? "WAITING_FOR_MASK" \
85 : loadState == TextureManager::LoadState::MASK_APPLYING ? "MASK_APPLYING" \
86 : loadState == TextureManager::LoadState::MASK_APPLIED ? "MASK_APPLIED" \
87 : loadState == TextureManager::LoadState::UPLOADED ? "UPLOADED" \
88 : loadState == TextureManager::LoadState::CANCELLED ? "CANCELLED" \
89 : loadState == TextureManager::LoadState::LOAD_FAILED ? "LOAD_FAILED" \
94 const uint32_t DEFAULT_ATLAS_SIZE(1024u); ///< This size can fit 8 by 8 images of average size 128 * 128
95 const Vector4 FULL_ATLAS_RECT(0.0f, 0.0f, 1.0f, 1.0f); ///< UV Rectangle that covers the full Texture
96 const int INVALID_INDEX(-1); ///< Invalid index used to represent a non-existant TextureInfo struct
97 const int INVALID_CACHE_INDEX(-1); ///< Invalid Cache index
99 void PreMultiply(Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
101 if(Pixel::HasAlpha(pixelBuffer.GetPixelFormat()))
103 if(preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
105 pixelBuffer.MultiplyColorByAlpha();
110 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
114 } // Anonymous namespace
116 TextureManager::MaskingData::MaskingData()
118 mAlphaMaskId(INVALID_TEXTURE_ID),
119 mContentScaleFactor(1.0f),
124 TextureManager::TextureManager()
125 : mAsyncLocalLoaders(GetNumberOfLocalLoaderThreads(), [&]()
126 { return AsyncLoadingHelper(*this); }),
127 mAsyncRemoteLoaders(GetNumberOfRemoteLoaderThreads(), [&]()
128 { return AsyncLoadingHelper(*this); }),
130 mLifecycleObservers(),
132 mCurrentTextureId(0),
133 mQueueLoadFlag(false)
135 // Initialize the AddOn
136 RenderingAddOn::Get();
139 TextureManager::~TextureManager()
141 for(auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
143 (*iter)->TextureManagerDestroyed();
147 TextureSet TextureManager::LoadAnimatedImageTexture(
148 Dali::AnimatedImageLoading animatedImageLoading, uint32_t frameIndex, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureManager::TextureId& textureId, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver)
150 TextureSet textureSet;
152 if(synchronousLoading)
154 Devel::PixelBuffer pixelBuffer;
155 if(animatedImageLoading)
157 pixelBuffer = animatedImageLoading.LoadFrame(frameIndex);
161 DALI_LOG_ERROR("TextureManager::LoadAnimatedImageTexture: Synchronous loading is failed\n");
165 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
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);
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, TextureManager::NO_ATLAS, false, StorageType::UPLOAD_TO_TEXTURE, textureObserver, true, TextureManager::ReloadPolicy::CACHED, preMultiply, animatedImageLoading, frameIndex, false);
179 TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
180 if(loadState == TextureManager::LoadState::UPLOADED)
182 // LoadComplete has already been called - keep the same texture set
183 textureSet = GetTextureSet(textureId);
189 Sampler sampler = Sampler::New();
190 sampler.SetWrapMode(wrapModeU, wrapModeV);
191 textureSet.SetSampler(0u, sampler);
197 Devel::PixelBuffer TextureManager::LoadPixelBuffer(
198 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, bool synchronousLoading, TextureUploadObserver* textureObserver, bool orientationCorrection, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
200 Devel::PixelBuffer pixelBuffer;
201 if(synchronousLoading)
205 if(url.IsBufferResource())
207 const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
208 if(encodedImageBuffer)
210 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
215 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
217 if(pixelBuffer && preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD)
219 PreMultiply(pixelBuffer, preMultiplyOnLoad);
225 RequestLoadInternal(url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, false, StorageType::RETURN_PIXEL_BUFFER, textureObserver, orientationCorrection, TextureManager::ReloadPolicy::FORCED, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, false);
231 TextureSet TextureManager::LoadTexture(
232 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode, Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo, bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect, Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver, AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection, TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
234 TextureSet textureSet;
236 loadingStatus = false;
237 textureRect = FULL_ATLAS_RECT;
239 if(VisualUrl::TEXTURE == url.GetProtocolType())
241 std::string location = url.GetLocation();
242 if(location.size() > 0u)
244 TextureId id = std::stoi(location);
245 for(auto&& elem : mExternalTextures)
247 if(elem.textureId == id)
249 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
250 textureId = elem.textureId;
251 return elem.textureSet;
259 if(synchronousLoading && atlasingStatus && imageAtlasManager->CheckAtlasAvailable(url, desiredSize))
261 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);
263 if(maskInfo && maskInfo->mAlphaMaskUrl.IsValid())
265 Devel::PixelBuffer maskPixelBuffer = LoadImageSynchronously(maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true);
268 pixelBuffer.ApplyMask(maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask);
275 PreMultiply(pixelBuffer, preMultiplyOnLoad);
276 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
280 textureSet = imageAtlasManager->Add(textureRect, data);
283 textureRectSize.SetWidth(data.GetWidth());
284 textureRectSize.SetHeight(data.GetHeight());
289 DALI_LOG_ERROR("TextureManager::LoadTexture: Synchronous Texture loading with atlasing is failed.\n");
294 atlasingStatus = false;
300 loadingStatus = true;
303 textureSet = imageAtlasManager->Add(textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
305 if(!textureSet) // big image, no atlasing or atlasing failed
307 atlasingStatus = false;
308 if(!maskInfo || !maskInfo->mAlphaMaskUrl.IsValid())
310 textureId = RequestLoad(url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS, textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad, synchronousLoading);
314 maskInfo->mAlphaMaskId = RequestMaskLoad(maskInfo->mAlphaMaskUrl, synchronousLoading);
315 textureId = RequestLoad(url,
316 maskInfo->mAlphaMaskId,
317 maskInfo->mContentScaleFactor,
321 TextureManager::NO_ATLAS,
322 maskInfo->mCropToMask,
324 orientationCorrection,
330 TextureManager::LoadState loadState = GetTextureStateInternal(textureId);
331 if(loadState == TextureManager::LoadState::UPLOADED)
333 // LoadComplete has already been called - keep the same texture set
334 textureSet = GetTextureSet(textureId);
337 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
338 // caller that they need to wait.
339 loadingStatus = (loadState == TextureManager::LoadState::LOADING ||
340 loadState == TextureManager::LoadState::WAITING_FOR_MASK ||
341 loadState == TextureManager::LoadState::MASK_APPLYING ||
342 loadState == TextureManager::LoadState::MASK_APPLIED ||
343 loadState == TextureManager::LoadState::NOT_STARTED ||
348 textureRectSize = desiredSize;
353 if(!atlasingStatus && textureSet)
355 Sampler sampler = Sampler::New();
356 sampler.SetWrapMode(wrapModeU, wrapModeV);
357 textureSet.SetSampler(0u, sampler);
360 if(synchronousLoading)
362 loadingStatus = false;
368 TextureManager::TextureId TextureManager::RequestLoad(
369 const VisualUrl& url,
370 const ImageDimensions desiredSize,
371 FittingMode::Type fittingMode,
372 Dali::SamplingMode::Type samplingMode,
373 const UseAtlas useAtlas,
374 TextureUploadObserver* observer,
375 bool orientationCorrection,
376 TextureManager::ReloadPolicy reloadPolicy,
377 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
378 bool synchronousLoading)
380 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);
383 TextureManager::TextureId TextureManager::RequestLoad(
384 const VisualUrl& url,
385 TextureId maskTextureId,
387 const ImageDimensions desiredSize,
388 FittingMode::Type fittingMode,
389 Dali::SamplingMode::Type samplingMode,
390 const UseAtlas useAtlas,
392 TextureUploadObserver* observer,
393 bool orientationCorrection,
394 TextureManager::ReloadPolicy reloadPolicy,
395 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
396 bool synchronousLoading)
398 return RequestLoadInternal(url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas, cropToMask, StorageType::UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy, preMultiplyOnLoad, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
401 TextureManager::TextureId TextureManager::RequestMaskLoad(const VisualUrl& maskUrl, bool synchronousLoading)
403 // Use the normal load procedure to get the alpha mask.
404 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
405 return RequestLoadInternal(maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, NO_ATLAS, false, StorageType::KEEP_PIXEL_BUFFER, NULL, true, TextureManager::ReloadPolicy::CACHED, preMultiply, Dali::AnimatedImageLoading(), 0u, synchronousLoading);
408 TextureManager::TextureId TextureManager::RequestLoadInternal(
409 const VisualUrl& url,
410 TextureId maskTextureId,
412 const ImageDimensions desiredSize,
413 FittingMode::Type fittingMode,
414 Dali::SamplingMode::Type samplingMode,
417 StorageType storageType,
418 TextureUploadObserver* observer,
419 bool orientationCorrection,
420 TextureManager::ReloadPolicy reloadPolicy,
421 TextureManager::MultiplyOnLoad& preMultiplyOnLoad,
422 Dali::AnimatedImageLoading animatedImageLoading,
424 bool synchronousLoading)
426 // First check if the requested Texture is cached.
427 bool isAnimatedImage = (animatedImageLoading) ? true : false;
429 TextureHash textureHash = INITIAL_CACHE_NUMBER;
430 int cacheIndex = INVALID_CACHE_INDEX;
431 if(storageType != StorageType::RETURN_PIXEL_BUFFER && !isAnimatedImage)
433 textureHash = GenerateHash(url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId);
435 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
436 cacheIndex = FindCachedTexture(textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas, maskTextureId, preMultiplyOnLoad);
439 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
440 // Check if the requested Texture exists in the cache.
441 if(cacheIndex != INVALID_CACHE_INDEX)
443 if(TextureManager::ReloadPolicy::CACHED == reloadPolicy)
445 // Mark this texture being used by another client resource. Forced reload would replace the current texture
446 // without the need for incrementing the reference count.
447 ++(mTextureInfoContainer[cacheIndex].referenceCount);
449 textureId = mTextureInfoContainer[cacheIndex].textureId;
451 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
452 preMultiplyOnLoad = mTextureInfoContainer[cacheIndex].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
454 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);
457 if(textureId == INVALID_TEXTURE_ID) // There was no caching, or caching not required
459 if(VisualUrl::BUFFER == url.GetProtocolType())
461 std::string location = url.GetLocation();
462 if(location.size() > 0u)
464 TextureId targetId = std::stoi(location);
465 const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(targetId);
466 if(encodedImageBuffer)
468 textureId = targetId;
470 // Increase EncodedImageBuffer reference during it contains mTextureInfoContainer.
471 UseExternalResource(url.GetUrl());
476 if(textureId == INVALID_TEXTURE_ID)
478 textureId = GenerateUniqueTextureId();
481 bool preMultiply = (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD);
482 mTextureInfoContainer.push_back(TextureInfo(textureId, maskTextureId, url, desiredSize, contentScale, fittingMode, samplingMode, false, cropToMask, useAtlas, textureHash, orientationCorrection, preMultiply, animatedImageLoading, frameIndex));
483 cacheIndex = mTextureInfoContainer.size() - 1u;
485 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);
488 // The below code path is common whether we are using the cache or not.
489 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
490 // or a new TextureInfo just created.
491 TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
492 textureInfo.maskTextureId = maskTextureId;
493 textureInfo.storageType = storageType;
494 textureInfo.orientationCorrection = orientationCorrection;
496 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n", GET_LOAD_STATE_STRING(textureInfo.loadState));
498 // Force reloading of texture by setting loadState unless already loading or cancelled.
499 if(TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
500 TextureManager::LoadState::LOADING != textureInfo.loadState &&
501 TextureManager::LoadState::WAITING_FOR_MASK != textureInfo.loadState &&
502 TextureManager::LoadState::MASK_APPLYING != textureInfo.loadState &&
503 TextureManager::LoadState::MASK_APPLIED != textureInfo.loadState &&
504 TextureManager::LoadState::CANCELLED != textureInfo.loadState)
506 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);
508 textureInfo.loadState = TextureManager::LoadState::NOT_STARTED;
511 if(!synchronousLoading)
513 // Check if we should add the observer.
514 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
515 switch(textureInfo.loadState)
517 case TextureManager::LoadState::LOAD_FAILED: // Failed notifies observer which then stops observing.
518 case TextureManager::LoadState::NOT_STARTED:
520 LoadOrQueueTexture(textureInfo, observer); // If called inside NotifyObservers, queues until afterwards
523 case TextureManager::LoadState::LOADING:
524 case TextureManager::LoadState::WAITING_FOR_MASK:
525 case TextureManager::LoadState::MASK_APPLYING:
526 case TextureManager::LoadState::MASK_APPLIED:
528 ObserveTexture(textureInfo, observer);
531 case TextureManager::LoadState::UPLOADED:
535 LoadOrQueueTexture(textureInfo, observer);
539 case TextureManager::LoadState::CANCELLED:
541 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
542 // (it's ref count has already been incremented, above)
543 textureInfo.loadState = TextureManager::LoadState::LOADING;
544 ObserveTexture(textureInfo, observer);
547 case TextureManager::LoadState::LOAD_FINISHED:
549 // Loading has already completed.
550 if(observer && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
552 LoadOrQueueTexture(textureInfo, observer);
560 // If the image is already finished to load, use cached texture.
561 // We don't need to consider Observer becaouse this is synchronous loading.
562 if(textureInfo.loadState == TextureManager::LoadState::UPLOADED ||
563 textureInfo.loadState == TextureManager::LoadState::LOAD_FINISHED)
569 Devel::PixelBuffer pixelBuffer = LoadImageSynchronously(url, desiredSize, fittingMode, samplingMode, orientationCorrection);;
573 // If pixelBuffer loading is failed in synchronously, call Remove() method.
574 Remove(textureId, nullptr);
575 return INVALID_TEXTURE_ID;
578 if(storageType == StorageType::KEEP_PIXEL_BUFFER) // For the mask image loading.
580 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
581 textureInfo.loadState = LoadState::LOAD_FINISHED;
583 else // For the image loading.
585 if(maskTextureId != INVALID_TEXTURE_ID)
587 int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
588 if(maskCacheIndex != INVALID_CACHE_INDEX)
590 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
593 pixelBuffer.ApplyMask(maskPixelBuffer, contentScale, cropToMask);
598 DALI_LOG_ERROR("Mask image is not stored in cache.\n");
601 PreMultiply(pixelBuffer, preMultiplyOnLoad);
604 UploadTexture(pixelBuffer, textureInfo);
609 // Return the TextureId for which this Texture can now be referenced by externally.
613 void TextureManager::Remove(const TextureManager::TextureId textureId, TextureUploadObserver* observer)
615 int textureInfoIndex = GetCacheIndexFromId(textureId);
617 if(textureInfoIndex != INVALID_INDEX)
619 TextureInfo& textureInfo(mTextureInfoContainer[textureInfoIndex]);
621 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s reference count = %d\n", textureId, textureInfo.url.GetUrl().c_str(), textureInfoIndex, GET_LOAD_STATE_STRING(textureInfo.loadState), textureInfo.referenceCount);
623 // Decrement the reference count and check if this is the last user of this Texture.
624 if(--textureInfo.referenceCount <= 0)
626 // This is the last remove for this Texture.
627 textureInfo.referenceCount = 0;
628 bool removeTextureInfo = false;
630 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
631 if(textureInfo.loadState == LoadState::UPLOADED)
633 if(textureInfo.atlas)
635 textureInfo.atlas.Remove(textureInfo.atlasRect);
637 removeTextureInfo = true;
639 else if(textureInfo.loadState == LoadState::LOADING)
641 // We mark the textureInfo for removal.
642 // Once the load has completed, this method will be called again.
643 textureInfo.loadState = LoadState::CANCELLED;
647 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
648 removeTextureInfo = true;
651 // If the state allows us to remove the TextureInfo data, we do so.
652 if(removeTextureInfo)
654 // If url location is BUFFER, decrease reference count of EncodedImageBuffer.
655 if(textureInfo.url.IsBufferResource())
657 RemoveExternalEncodedImageBuffer(textureInfo.url.GetUrl());
659 // Permanently remove the textureInfo struct.
660 mTextureInfoContainer.erase(mTextureInfoContainer.begin() + textureInfoIndex);
666 // Remove element from the LoadQueue
667 for(auto&& element : mLoadQueue)
669 if(element.mObserver == observer)
671 // Do not erase the item. We will clear it later in ProcessQueuedTextures().
672 element.mObserver = nullptr;
680 VisualUrl TextureManager::GetVisualUrl(TextureId textureId)
682 VisualUrl visualUrl("");
683 int cacheIndex = GetCacheIndexFromId(textureId);
685 if(cacheIndex != INVALID_CACHE_INDEX)
687 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n", cacheIndex, textureId);
689 TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
690 visualUrl = cachedTextureInfo.url;
695 TextureManager::LoadState TextureManager::GetTextureState(TextureId textureId)
697 LoadState loadState = TextureManager::LoadState::NOT_STARTED;
699 int cacheIndex = GetCacheIndexFromId(textureId);
700 if(cacheIndex != INVALID_CACHE_INDEX)
702 TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
703 loadState = cachedTextureInfo.loadState;
707 for(auto&& elem : mExternalTextures)
709 if(elem.textureId == textureId)
711 loadState = LoadState::UPLOADED;
719 TextureManager::LoadState TextureManager::GetTextureStateInternal(TextureId textureId)
721 LoadState loadState = TextureManager::LoadState::NOT_STARTED;
723 int cacheIndex = GetCacheIndexFromId(textureId);
724 if(cacheIndex != INVALID_CACHE_INDEX)
726 TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
727 loadState = cachedTextureInfo.loadState;
733 Devel::PixelBuffer TextureManager::LoadImageSynchronously(const VisualUrl& url,
734 const ImageDimensions desiredSize,
735 FittingMode::Type fittingMode,
736 Dali::SamplingMode::Type samplingMode,
737 bool orientationCorrection)
739 Devel::PixelBuffer pixelBuffer;
740 if(url.IsBufferResource())
742 const EncodedImageBuffer& encodedImageBuffer = GetEncodedImageBuffer(url.GetUrl());
743 if(encodedImageBuffer)
745 pixelBuffer = LoadImageFromBuffer(encodedImageBuffer.GetRawBuffer(), desiredSize, fittingMode, samplingMode, orientationCorrection);
750 pixelBuffer = LoadImageFromFile(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
755 TextureSet TextureManager::GetTextureSet(TextureId textureId)
757 TextureSet textureSet; // empty handle
759 int cacheIndex = GetCacheIndexFromId(textureId);
760 if(cacheIndex != INVALID_CACHE_INDEX)
762 TextureInfo& cachedTextureInfo(mTextureInfoContainer[cacheIndex]);
763 textureSet = cachedTextureInfo.textureSet;
767 for(auto&& elem : mExternalTextures)
769 if(elem.textureId == textureId)
771 textureSet = elem.textureSet;
779 EncodedImageBuffer TextureManager::GetEncodedImageBuffer(TextureId textureId)
781 EncodedImageBuffer encodedImageBuffer; // empty handle
782 for(auto&& elem : mEncodedBufferTextures)
784 if(elem.textureId == textureId)
786 encodedImageBuffer = elem.encodedImageBuffer;
790 return encodedImageBuffer;
793 EncodedImageBuffer TextureManager::GetEncodedImageBuffer(const std::string& url)
795 EncodedImageBuffer encodedImageBuffer; // empty handle
796 if(url.size() > 0 && VisualUrl::BUFFER == VisualUrl::GetProtocolType(url))
798 std::string location = VisualUrl::GetLocation(url);
799 if(location.size() > 0u)
801 TextureId targetId = std::stoi(location);
802 return GetEncodedImageBuffer(targetId);
805 return encodedImageBuffer;
808 std::string TextureManager::AddExternalTexture(TextureSet& textureSet)
810 TextureManager::ExternalTextureInfo info;
811 info.textureId = GenerateUniqueTextureId();
812 info.textureSet = textureSet;
813 mExternalTextures.emplace_back(info);
815 return VisualUrl::CreateTextureUrl(std::to_string(info.textureId));
818 std::string TextureManager::AddExternalEncodedImageBuffer(const EncodedImageBuffer& encodedImageBuffer)
821 for(auto&& elem : mEncodedBufferTextures)
823 if(elem.encodedImageBuffer == encodedImageBuffer)
825 // If same buffer added, increase reference count and return.
826 elem.referenceCount++;
827 return VisualUrl::CreateBufferUrl(std::to_string(elem.textureId));
830 TextureManager::EncodedBufferTextureInfo info(GenerateUniqueTextureId(), encodedImageBuffer);
831 mEncodedBufferTextures.emplace_back(info);
832 return VisualUrl::CreateBufferUrl(std::to_string(info.textureId));
835 TextureSet TextureManager::RemoveExternalTexture(const std::string& url)
839 if(VisualUrl::TEXTURE == VisualUrl::GetProtocolType(url))
841 // get the location from the Url
842 std::string location = VisualUrl::GetLocation(url);
843 if(location.size() > 0u)
845 TextureId id = std::stoi(location);
846 const auto end = mExternalTextures.end();
847 for(auto iter = mExternalTextures.begin(); iter != end; ++iter)
849 if(iter->textureId == id)
851 auto textureSet = iter->textureSet;
852 if(--(iter->referenceCount) <= 0)
854 mExternalTextures.erase(iter);
865 EncodedImageBuffer TextureManager::RemoveExternalEncodedImageBuffer(const std::string& url)
869 if(VisualUrl::BUFFER == VisualUrl::GetProtocolType(url))
871 // get the location from the Url
872 std::string location = VisualUrl::GetLocation(url);
873 if(location.size() > 0u)
875 TextureId id = std::stoi(location);
876 const auto end = mEncodedBufferTextures.end();
877 for(auto iter = mEncodedBufferTextures.begin(); iter != end; ++iter)
879 if(iter->textureId == id)
881 auto encodedImageBuffer = iter->encodedImageBuffer;
882 if(--(iter->referenceCount) <= 0)
884 mEncodedBufferTextures.erase(iter);
886 return encodedImageBuffer;
892 return EncodedImageBuffer();
895 void TextureManager::UseExternalResource(const VisualUrl& url)
897 if(VisualUrl::TEXTURE == url.GetProtocolType())
899 std::string location = url.GetLocation();
900 if(location.size() > 0u)
902 TextureId id = std::stoi(location);
903 for(auto&& elem : mExternalTextures)
905 if(elem.textureId == id)
907 elem.referenceCount++;
913 else if(VisualUrl::BUFFER == url.GetProtocolType())
915 std::string location = url.GetLocation();
916 if(location.size() > 0u)
918 TextureId id = std::stoi(location);
919 for(auto&& elem : mEncodedBufferTextures)
921 if(elem.textureId == id)
923 elem.referenceCount++;
931 void TextureManager::AddObserver(TextureManager::LifecycleObserver& observer)
933 // make sure an observer doesn't observe the same object twice
934 // otherwise it will get multiple calls to ObjectDestroyed()
935 DALI_ASSERT_DEBUG(mLifecycleObservers.End() == std::find(mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
936 mLifecycleObservers.PushBack(&observer);
939 void TextureManager::RemoveObserver(TextureManager::LifecycleObserver& observer)
941 // Find the observer...
942 auto endIter = mLifecycleObservers.End();
943 for(auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
945 if((*iter) == &observer)
947 mLifecycleObservers.Erase(iter);
951 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
954 void TextureManager::LoadOrQueueTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
956 switch(textureInfo.loadState)
958 case LoadState::NOT_STARTED:
959 case LoadState::LOAD_FAILED:
963 QueueLoadTexture(textureInfo, observer);
967 LoadTexture(textureInfo, observer);
971 case LoadState::UPLOADED:
975 QueueLoadTexture(textureInfo, observer);
979 // The Texture has already loaded. The other observers have already been notified.
980 // We need to send a "late" loaded notification for this observer.
981 observer->LoadComplete(true, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied));
985 case LoadState::LOADING:
986 case LoadState::CANCELLED:
987 case LoadState::LOAD_FINISHED:
988 case LoadState::WAITING_FOR_MASK:
989 case LoadState::MASK_APPLYING:
990 case LoadState::MASK_APPLIED:
997 void TextureManager::QueueLoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
999 auto textureId = textureInfo.textureId;
1000 mLoadQueue.PushBack(LoadQueueElement(textureId, observer));
1002 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
1005 void TextureManager::LoadTexture(TextureInfo& textureInfo, TextureUploadObserver* observer)
1007 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1009 textureInfo.loadState = LoadState::LOADING;
1010 if(!textureInfo.loadSynchronously)
1012 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1013 auto loadingHelperIt = loadersContainer.GetNext();
1014 auto premultiplyOnLoad = (textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID) ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1015 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1016 if(textureInfo.animatedImageLoading)
1018 loadingHelperIt->LoadAnimatedImage(textureInfo.textureId, textureInfo.animatedImageLoading, textureInfo.frameIndex);
1022 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url, textureInfo.desiredSize, textureInfo.fittingMode, textureInfo.samplingMode, textureInfo.orientationCorrection, premultiplyOnLoad);
1025 ObserveTexture(textureInfo, observer);
1028 void TextureManager::ProcessQueuedTextures()
1030 for(auto&& element : mLoadQueue)
1032 if(!element.mObserver)
1037 int cacheIndex = GetCacheIndexFromId(element.mTextureId);
1038 if(cacheIndex != INVALID_CACHE_INDEX)
1040 TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1041 if(textureInfo.loadState == LoadState::UPLOADED)
1043 element.mObserver->LoadComplete(true, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, textureInfo.textureId, textureInfo.textureSet, textureInfo.useAtlas, textureInfo.atlasRect, textureInfo.preMultiplied));
1045 else if(textureInfo.loadState == LoadState::LOAD_FINISHED && textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1047 element.mObserver->LoadComplete(true, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, textureInfo.pixelBuffer, textureInfo.url.GetUrl(), textureInfo.preMultiplied));
1051 LoadTexture(textureInfo, element.mObserver);
1058 void TextureManager::ObserveTexture(TextureInfo& textureInfo,
1059 TextureUploadObserver* observer)
1061 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n", textureInfo.url.GetUrl().c_str(), observer);
1065 textureInfo.observerList.PushBack(observer);
1066 observer->DestructionSignal().Connect(this, &TextureManager::ObserverDestroyed);
1070 void TextureManager::AsyncLoadComplete(AsyncLoadingInfoContainerType& loadingContainer, uint32_t id, Devel::PixelBuffer pixelBuffer)
1072 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id);
1074 if(loadingContainer.size() >= 1u)
1076 AsyncLoadingInfo loadingInfo = loadingContainer.front();
1078 if(loadingInfo.loadId == id)
1080 int cacheIndex = GetCacheIndexFromId(loadingInfo.textureId);
1081 if(cacheIndex != INVALID_CACHE_INDEX)
1083 TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1085 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n", textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState);
1087 if(textureInfo.loadState != LoadState::CANCELLED)
1089 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
1090 PostLoad(textureInfo, pixelBuffer);
1094 Remove(textureInfo.textureId, nullptr);
1099 loadingContainer.pop_front();
1103 void TextureManager::PostLoad(TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer)
1105 // Was the load successful?
1106 if(pixelBuffer && (pixelBuffer.GetWidth() != 0) && (pixelBuffer.GetHeight() != 0))
1108 // No atlas support for now
1109 textureInfo.useAtlas = NO_ATLAS;
1110 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1112 if(textureInfo.storageType == StorageType::UPLOAD_TO_TEXTURE)
1114 // If there is a mask texture ID associated with this texture, then apply the mask
1115 // if it's already loaded. If it hasn't, and the mask is still loading,
1116 // wait for the mask to finish loading.
1117 // note, If the texture is already uploaded synchronously during loading,
1118 // we don't need to apply mask.
1119 if(textureInfo.loadState != LoadState::UPLOADED &&
1120 textureInfo.maskTextureId != INVALID_TEXTURE_ID)
1122 if(textureInfo.loadState == LoadState::MASK_APPLYING)
1124 textureInfo.loadState = LoadState::MASK_APPLIED;
1125 UploadTexture(pixelBuffer, textureInfo);
1126 NotifyObservers(textureInfo, true);
1130 LoadState maskLoadState = GetTextureStateInternal(textureInfo.maskTextureId);
1131 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
1132 if(maskLoadState == LoadState::LOADING)
1134 textureInfo.loadState = LoadState::WAITING_FOR_MASK;
1136 else if(maskLoadState == LoadState::LOAD_FINISHED)
1138 // Send New Task to Thread
1139 ApplyMask(textureInfo, textureInfo.maskTextureId);
1145 UploadTexture(pixelBuffer, textureInfo);
1146 NotifyObservers(textureInfo, true);
1151 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
1152 textureInfo.loadState = LoadState::LOAD_FINISHED;
1154 if(textureInfo.storageType == StorageType::RETURN_PIXEL_BUFFER)
1156 NotifyObservers(textureInfo, true);
1160 // Check if there was another texture waiting for this load to complete
1161 // (e.g. if this was an image mask, and its load is on a different thread)
1162 CheckForWaitingTexture(textureInfo);
1168 textureInfo.loadState = LoadState::LOAD_FAILED;
1169 CheckForWaitingTexture(textureInfo);
1170 NotifyObservers(textureInfo, false);
1174 void TextureManager::CheckForWaitingTexture(TextureInfo& maskTextureInfo)
1176 // Search the cache, checking if any texture has this texture id as a
1178 const unsigned int size = mTextureInfoContainer.size();
1180 for(unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex)
1182 if(mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
1183 mTextureInfoContainer[cacheIndex].loadState == LoadState::WAITING_FOR_MASK)
1185 TextureInfo& textureInfo(mTextureInfoContainer[cacheIndex]);
1187 if(maskTextureInfo.loadState == LoadState::LOAD_FINISHED)
1189 // Send New Task to Thread
1190 ApplyMask(textureInfo, maskTextureInfo.textureId);
1194 textureInfo.pixelBuffer.Reset();
1195 textureInfo.loadState = LoadState::LOAD_FAILED;
1196 NotifyObservers(textureInfo, false);
1202 void TextureManager::ApplyMask(TextureInfo& textureInfo, TextureId maskTextureId)
1204 int maskCacheIndex = GetCacheIndexFromId(maskTextureId);
1205 if(maskCacheIndex != INVALID_CACHE_INDEX)
1207 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
1208 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
1209 textureInfo.pixelBuffer.Reset();
1211 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n", textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously ? "T" : "F");
1213 textureInfo.loadState = LoadState::MASK_APPLYING;
1214 auto& loadersContainer = (textureInfo.url.IsLocalResource() || textureInfo.url.IsBufferResource()) ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
1215 auto loadingHelperIt = loadersContainer.GetNext();
1216 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
1217 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
1218 loadingHelperIt->ApplyMask(textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad);
1222 void TextureManager::UploadTexture(Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo)
1224 if(textureInfo.loadState != LoadState::UPLOADED && textureInfo.useAtlas != USE_ATLAS)
1226 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId);
1228 // Check if this pixelBuffer is premultiplied
1229 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
1231 auto& renderingAddOn = RenderingAddOn::Get();
1232 if(renderingAddOn.IsValid())
1234 renderingAddOn.CreateGeometry(textureInfo.textureId, pixelBuffer);
1237 Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(), pixelBuffer.GetWidth(), pixelBuffer.GetHeight());
1239 PixelData pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
1240 texture.Upload(pixelData);
1241 if(!textureInfo.textureSet)
1243 textureInfo.textureSet = TextureSet::New();
1245 textureInfo.textureSet.SetTexture(0u, texture);
1248 // Update the load state.
1249 // Note: This is regardless of success as we care about whether a
1250 // load attempt is in progress or not. If unsuccessful, a broken
1251 // image is still loaded.
1252 textureInfo.loadState = LoadState::UPLOADED;
1255 void TextureManager::NotifyObservers(TextureInfo& textureInfo, bool success)
1257 TextureId textureId = textureInfo.textureId;
1259 // If there is an observer: Notify the load is complete, whether successful or not,
1260 // and erase it from the list
1261 TextureInfo* info = &textureInfo;
1263 mQueueLoadFlag = true;
1265 while(info->observerList.Count())
1267 TextureUploadObserver* observer = info->observerList[0];
1269 // During LoadComplete() a Control ResourceReady() signal is emitted.
1270 // During that signal the app may add remove /add Textures (e.g. via
1272 // It is possible for observers to be removed from the observer list,
1273 // and it is also possible for the mTextureInfoContainer to be modified,
1274 // invalidating the reference to the textureInfo struct.
1275 // Texture load requests for the same URL are deferred until the end of this
1277 DALI_LOG_INFO(gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n", textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState));
1279 // It is possible for the observer to be deleted.
1280 // Disconnect and remove the observer first.
1281 observer->DestructionSignal().Disconnect(this, &TextureManager::ObserverDestroyed);
1283 info->observerList.Erase(info->observerList.begin());
1285 if(info->storageType == StorageType::RETURN_PIXEL_BUFFER)
1287 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::PIXEL_BUFFER, info->pixelBuffer, info->url.GetUrl(), info->preMultiplied));
1291 observer->LoadComplete(success, TextureUploadObserver::TextureInformation(TextureUploadObserver::ReturnType::TEXTURE, info->textureId, info->textureSet, info->useAtlas, info->atlasRect, info->preMultiplied));
1294 // Get the textureInfo from the container again as it may have been invalidated.
1295 int textureInfoIndex = GetCacheIndexFromId(textureId);
1296 if(textureInfoIndex == INVALID_CACHE_INDEX)
1298 break; // texture has been removed - can stop.
1300 info = &mTextureInfoContainer[textureInfoIndex];
1303 mQueueLoadFlag = false;
1304 ProcessQueuedTextures();
1306 if(info->storageType == StorageType::RETURN_PIXEL_BUFFER && info->observerList.Count() == 0)
1308 Remove(info->textureId, nullptr);
1312 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
1314 return mCurrentTextureId++;
1317 int TextureManager::GetCacheIndexFromId(const TextureId textureId)
1319 const unsigned int size = mTextureInfoContainer.size();
1321 for(unsigned int i = 0; i < size; ++i)
1323 if(mTextureInfoContainer[i].textureId == textureId)
1329 return INVALID_CACHE_INDEX;
1332 TextureManager::TextureHash TextureManager::GenerateHash(
1333 const std::string& url,
1334 const ImageDimensions size,
1335 const FittingMode::Type fittingMode,
1336 const Dali::SamplingMode::Type samplingMode,
1337 const UseAtlas useAtlas,
1338 TextureId maskTextureId)
1340 std::string hashTarget(url);
1341 const size_t urlLength = hashTarget.length();
1342 const uint16_t width = size.GetWidth();
1343 const uint16_t height = size.GetWidth();
1345 // If either the width or height has been specified, include the resizing options in the hash
1346 if(width != 0 || height != 0)
1348 // We are appending 5 bytes to the URL to form the hash input.
1349 hashTarget.resize(urlLength + 5u);
1350 char* hashTargetPtr = &(hashTarget[urlLength]);
1352 // Pack the width and height (4 bytes total).
1353 *hashTargetPtr++ = size.GetWidth() & 0xff;
1354 *hashTargetPtr++ = (size.GetWidth() >> 8u) & 0xff;
1355 *hashTargetPtr++ = size.GetHeight() & 0xff;
1356 *hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff;
1358 // Bit-pack the FittingMode, SamplingMode and atlasing.
1359 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1360 *hashTargetPtr = (fittingMode << 4u) | (samplingMode << 1) | useAtlas;
1364 // We are not including sizing information, but we still need an extra byte for atlasing.
1365 hashTarget.resize(urlLength + 1u);
1367 // Add the atlasing to the hash input.
1370 case UseAtlas::NO_ATLAS:
1372 hashTarget[urlLength] = 'f';
1375 case UseAtlas::USE_ATLAS:
1377 hashTarget[urlLength] = 't';
1383 if(maskTextureId != INVALID_TEXTURE_ID)
1385 auto textureIdIndex = hashTarget.length();
1386 hashTarget.resize(hashTarget.length() + sizeof(TextureId));
1387 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&(hashTarget[textureIdIndex]));
1389 // Append the texture id to the end of the URL byte by byte:
1390 // (to avoid SIGBUS / alignment issues)
1391 for(size_t byteIter = 0; byteIter < sizeof(TextureId); ++byteIter)
1393 *hashTargetPtr++ = maskTextureId & 0xff;
1394 maskTextureId >>= 8u;
1398 return Dali::CalculateHash(hashTarget);
1401 int TextureManager::FindCachedTexture(
1402 const TextureManager::TextureHash hash,
1403 const std::string& url,
1404 const ImageDimensions size,
1405 const FittingMode::Type fittingMode,
1406 const Dali::SamplingMode::Type samplingMode,
1407 const bool useAtlas,
1408 TextureId maskTextureId,
1409 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
1411 // Default to an invalid ID, in case we do not find a match.
1412 int cacheIndex = INVALID_CACHE_INDEX;
1414 // Iterate through our hashes to find a match.
1415 const unsigned int count = mTextureInfoContainer.size();
1416 for(unsigned int i = 0u; i < count; ++i)
1418 if(mTextureInfoContainer[i].hash == hash)
1420 // We have a match, now we check all the original parameters in case of a hash collision.
1421 TextureInfo& textureInfo(mTextureInfoContainer[i]);
1423 if((url == textureInfo.url.GetUrl()) &&
1424 (useAtlas == textureInfo.useAtlas) &&
1425 (maskTextureId == textureInfo.maskTextureId) &&
1426 (size == textureInfo.desiredSize) &&
1427 ((size.GetWidth() == 0 && size.GetHeight() == 0) ||
1428 (fittingMode == textureInfo.fittingMode &&
1429 samplingMode == textureInfo.samplingMode)))
1431 // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1432 // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1433 if((preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad) || (preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied))
1435 // The found Texture is a match.
1446 void TextureManager::ObserverDestroyed(TextureUploadObserver* observer)
1448 const unsigned int count = mTextureInfoContainer.size();
1449 for(unsigned int i = 0; i < count; ++i)
1451 TextureInfo& textureInfo(mTextureInfoContainer[i]);
1452 for(TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1453 j != textureInfo.observerList.End();)
1457 j = textureInfo.observerList.Erase(j);
1466 // Remove element from the LoadQueue
1467 for(auto&& element : mLoadQueue)
1469 if(element.mObserver == observer)
1471 element.mObserver = nullptr;
1476 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1477 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager, AsyncLoadingInfoContainerType())
1481 void TextureManager::AsyncLoadingHelper::LoadAnimatedImage(TextureId textureId,
1482 Dali::AnimatedImageLoading animatedImageLoading,
1483 uint32_t frameIndex)
1485 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1486 auto id = GetImplementation(mLoader).LoadAnimatedImage(animatedImageLoading, frameIndex);
1487 mLoadingInfoContainer.back().loadId = id;
1490 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1491 const VisualUrl& url,
1492 ImageDimensions desiredSize,
1493 FittingMode::Type fittingMode,
1494 SamplingMode::Type samplingMode,
1495 bool orientationCorrection,
1496 DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1498 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1499 if(DALI_UNLIKELY(url.IsBufferResource()))
1501 auto id = GetImplementation(mLoader).LoadEncodedImageBuffer(mTextureManager.GetEncodedImageBuffer(url.GetUrl()), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
1502 mLoadingInfoContainer.back().loadId = id;
1506 auto id = GetImplementation(mLoader).Load(url, desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad);
1507 mLoadingInfoContainer.back().loadId = id;
1511 void TextureManager::AsyncLoadingHelper::ApplyMask(TextureId textureId,
1512 Devel::PixelBuffer pixelBuffer,
1513 Devel::PixelBuffer maskPixelBuffer,
1516 DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1518 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1519 auto id = GetImplementation(mLoader).ApplyMask(pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad);
1520 mLoadingInfoContainer.back().loadId = id;
1523 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1524 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1528 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1529 Toolkit::AsyncImageLoader loader,
1530 TextureManager& textureManager,
1531 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1533 mTextureManager(textureManager),
1534 mLoadingInfoContainer(std::move(loadingInfoContainer))
1536 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1537 this, &AsyncLoadingHelper::AsyncLoadComplete);
1540 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1541 Devel::PixelBuffer pixelBuffer)
1543 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1546 Geometry TextureManager::GetRenderGeometry(TextureId textureId, uint32_t& frontElements, uint32_t& backElements)
1548 return RenderingAddOn::Get().IsValid() ? RenderingAddOn::Get().GetGeometry(textureId, frontElements, backElements) : Geometry();
1551 } // namespace Internal
1553 } // namespace Toolkit