2 * Copyright (c) 2020 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>
24 #include <dali/public-api/math/vector4.h>
25 #include <dali/devel-api/adaptor-framework/environment-variable.h>
26 #include <dali/devel-api/adaptor-framework/image-loading.h>
27 #include <dali/devel-api/common/hash.h>
28 #include <dali/devel-api/images/texture-set-image.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30 #include <dali/integration-api/debug.h>
33 #include <dali-toolkit/internal/image-loader/image-atlas-impl.h>
34 #include <dali-toolkit/public-api/image-loader/sync-image-loader.h>
35 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
40 constexpr auto DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS = size_t{4u};
41 constexpr auto DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS = size_t{8u};
43 constexpr auto NUMBER_OF_LOCAL_LOADER_THREADS_ENV = "DALI_TEXTURE_LOCAL_THREADS";
44 constexpr auto NUMBER_OF_REMOTE_LOADER_THREADS_ENV = "DALI_TEXTURE_REMOTE_THREADS";
46 size_t GetNumberOfThreads(const char* environmentVariable, size_t defaultValue)
48 using Dali::EnvironmentVariable::GetEnvironmentVariable;
49 auto numberString = GetEnvironmentVariable(environmentVariable);
50 auto numberOfThreads = numberString ? std::strtoul(numberString, nullptr, 10) : 0;
51 constexpr auto MAX_NUMBER_OF_THREADS = 100u;
52 DALI_ASSERT_DEBUG( numberOfThreads < MAX_NUMBER_OF_THREADS );
53 return ( numberOfThreads > 0 && numberOfThreads < MAX_NUMBER_OF_THREADS ) ? numberOfThreads : defaultValue;
56 size_t GetNumberOfLocalLoaderThreads()
58 return GetNumberOfThreads(NUMBER_OF_LOCAL_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_LOCAL_LOADER_THREADS);
61 size_t GetNumberOfRemoteLoaderThreads()
63 return GetNumberOfThreads(NUMBER_OF_REMOTE_LOADER_THREADS_ENV, DEFAULT_NUMBER_OF_REMOTE_LOADER_THREADS);
81 Debug::Filter* gTextureManagerLogFilter = Debug::Filter::New( Debug::NoLogging, false, "LOG_TEXTURE_MANAGER" );
83 #define GET_LOAD_STATE_STRING( loadState ) \
84 loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" : \
85 loadState == TextureManager::LOADING ? "LOADING" : \
86 loadState == TextureManager::LOAD_FINISHED ? "LOAD_FINISHED" : \
87 loadState == TextureManager::WAITING_FOR_MASK ? "WAITING_FOR_MASK" : \
88 loadState == TextureManager::MASK_APPLYING ? "MASK_APPLYING" : \
89 loadState == TextureManager::MASK_APPLIED ? "MASK_APPLIED" : \
90 loadState == TextureManager::UPLOADED ? "UPLOADED" : \
91 loadState == TextureManager::CANCELLED ? "CANCELLED" : \
92 loadState == TextureManager::LOAD_FAILED ? "LOAD_FAILED" : "Unknown"
96 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
97 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
98 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
99 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
102 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
104 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
106 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
108 pixelBuffer.MultiplyColorByAlpha();
113 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
117 } // Anonymous namespace
119 TextureManager::MaskingData::MaskingData()
121 mAlphaMaskId( INVALID_TEXTURE_ID ),
122 mContentScaleFactor( 1.0f ),
127 TextureManager::TextureManager()
128 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
129 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
131 mLifecycleObservers(),
134 mCurrentTextureId( 0 ),
135 mQueueLoadFlag(false)
139 TextureManager::~TextureManager()
141 for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
143 (*iter)->TextureManagerDestroyed();
147 TextureSet TextureManager::LoadTexture(
148 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
149 Dali::SamplingMode::Type samplingMode, MaskingDataPointer& maskInfo,
150 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
151 Dali::ImageDimensions& textureRectSize, bool& atlasingStatus, bool& loadingStatus,
152 Dali::WrapMode::Type wrapModeU, Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
153 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
154 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
156 TextureSet textureSet;
158 loadingStatus = false;
159 textureRect = FULL_ATLAS_RECT;
161 if( VisualUrl::TEXTURE == url.GetProtocolType())
163 std::string location = url.GetLocation();
164 if( location.size() > 0u )
166 TextureId id = std::stoi( location );
167 for( auto&& elem : mExternalTextures )
169 if( elem.textureId == id )
171 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
172 textureId = elem.textureId;
173 return elem.textureSet;
178 else if( synchronousLoading )
183 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
184 orientationCorrection );
187 Devel::PixelBuffer maskPixelBuffer = LoadImageFromFile( maskInfo->mAlphaMaskUrl.GetUrl(), ImageDimensions(),
188 FittingMode::SCALE_TO_FILL, SamplingMode::NO_FILTER, true );
189 if( maskPixelBuffer )
191 pixelBuffer.ApplyMask( maskPixelBuffer, maskInfo->mContentScaleFactor, maskInfo->mCropToMask );
196 PreMultiply( pixelBuffer, preMultiplyOnLoad );
197 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
203 textureSet = TextureSet::New();
204 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( mBrokenImageUrl );
207 PreMultiply( pixelBuffer, preMultiplyOnLoad );
208 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
210 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
211 data.GetWidth(), data.GetHeight() );
212 texture.Upload( data );
213 textureSet = TextureSet::New();
214 textureSet.SetTexture( 0u, texture );
218 if( atlasingStatus ) // attempt atlasing
220 textureSet = imageAtlasManager->Add( textureRect, data );
222 if( !textureSet ) // big image, no atlasing or atlasing failed
224 atlasingStatus = false;
225 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
226 data.GetWidth(), data.GetHeight() );
227 texture.Upload( data );
228 textureSet = TextureSet::New();
229 textureSet.SetTexture( 0u, texture );
233 textureRectSize.SetWidth(data.GetWidth());
234 textureRectSize.SetHeight(data.GetHeight());
240 loadingStatus = true;
243 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver);
245 if( !textureSet ) // big image, no atlasing or atlasing failed
247 atlasingStatus = false;
250 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
251 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
255 maskInfo->mAlphaMaskId = RequestMaskLoad( maskInfo->mAlphaMaskUrl );
256 textureId = RequestLoad( url,
257 maskInfo->mAlphaMaskId,
258 maskInfo->mContentScaleFactor,
260 fittingMode, samplingMode,
261 TextureManager::NO_ATLAS,
262 maskInfo->mCropToMask,
264 orientationCorrection,
265 reloadPolicy, preMultiplyOnLoad );
268 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
269 if( loadState == TextureManager::UPLOADED )
271 // UploadComplete has already been called - keep the same texture set
272 textureSet = GetTextureSet( textureId );
275 // If we are loading the texture, or waiting for the ready signal handler to complete, inform
276 // caller that they need to wait.
277 loadingStatus = ( loadState == TextureManager::LOADING ||
278 loadState == TextureManager::WAITING_FOR_MASK ||
279 loadState == TextureManager::MASK_APPLYING ||
280 loadState == TextureManager::MASK_APPLIED ||
281 loadState == TextureManager::NOT_STARTED ||
287 textureRectSize = desiredSize;
291 if( ! atlasingStatus && textureSet )
293 Sampler sampler = Sampler::New();
294 sampler.SetWrapMode( wrapModeU, wrapModeV );
295 textureSet.SetSampler( 0u, sampler );
301 TextureManager::TextureId TextureManager::RequestLoad(
302 const VisualUrl& url,
303 const ImageDimensions desiredSize,
304 FittingMode::Type fittingMode,
305 Dali::SamplingMode::Type samplingMode,
306 const UseAtlas useAtlas,
307 TextureUploadObserver* observer,
308 bool orientationCorrection,
309 TextureManager::ReloadPolicy reloadPolicy,
310 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
312 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
313 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
317 TextureManager::TextureId TextureManager::RequestLoad(
318 const VisualUrl& url,
319 TextureId maskTextureId,
321 const ImageDimensions desiredSize,
322 FittingMode::Type fittingMode,
323 Dali::SamplingMode::Type samplingMode,
324 const UseAtlas useAtlas,
326 TextureUploadObserver* observer,
327 bool orientationCorrection,
328 TextureManager::ReloadPolicy reloadPolicy,
329 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
331 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
332 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
336 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
338 // Use the normal load procedure to get the alpha mask.
339 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
340 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
341 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
342 TextureManager::ReloadPolicy::CACHED, preMultiply );
345 TextureManager::TextureId TextureManager::RequestLoadInternal(
346 const VisualUrl& url,
347 TextureId maskTextureId,
349 const ImageDimensions desiredSize,
350 FittingMode::Type fittingMode,
351 Dali::SamplingMode::Type samplingMode,
354 StorageType storageType,
355 TextureUploadObserver* observer,
356 bool orientationCorrection,
357 TextureManager::ReloadPolicy reloadPolicy,
358 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
360 // First check if the requested Texture is cached.
361 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
364 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
366 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
367 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
368 maskTextureId, preMultiplyOnLoad );
370 // Check if the requested Texture exists in the cache.
371 if( cacheIndex != INVALID_CACHE_INDEX )
373 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
375 // Mark this texture being used by another client resource. Forced reload would replace the current texture
376 // without the need for incrementing the reference count.
377 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
379 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
381 // Update preMultiplyOnLoad value. It should be changed according to preMultiplied value of the cached info.
382 preMultiplyOnLoad = mTextureInfoContainer[ cacheIndex ].preMultiplied ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD : TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
384 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
385 url.GetUrl().c_str(), observer, cacheIndex, textureId );
388 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
390 // We need a new Texture.
391 textureId = GenerateUniqueTextureId();
392 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
393 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
394 desiredSize, contentScale, fittingMode, samplingMode,
395 false, cropToMask, useAtlas, textureHash, orientationCorrection,
397 cacheIndex = mTextureInfoContainer.size() - 1u;
399 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
400 url.GetUrl().c_str(), observer, cacheIndex, textureId );
403 // The below code path is common whether we are using the cache or not.
404 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
405 // or a new TextureInfo just created.
406 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
407 textureInfo.maskTextureId = maskTextureId;
408 textureInfo.storageType = storageType;
409 textureInfo.orientationCorrection = orientationCorrection;
411 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, "TextureInfo loadState:%s\n",
412 GET_LOAD_STATE_STRING(textureInfo.loadState ) );
414 // Force reloading of texture by setting loadState unless already loading or cancelled.
415 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy &&
416 TextureManager::LOADING != textureInfo.loadState &&
417 TextureManager::WAITING_FOR_MASK != textureInfo.loadState &&
418 TextureManager::MASK_APPLYING != textureInfo.loadState &&
419 TextureManager::MASK_APPLIED != textureInfo.loadState &&
420 TextureManager::CANCELLED != textureInfo.loadState )
422 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
423 url.GetUrl().c_str(), observer, cacheIndex, textureId );
424 textureInfo.loadState = TextureManager::NOT_STARTED;
427 // Check if we should add the observer.
428 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
429 switch( textureInfo.loadState )
431 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
432 case TextureManager::NOT_STARTED:
434 LoadOrQueueTexture( textureInfo, observer ); // If called inside NotifyObservers, queues until afterwards
437 case TextureManager::LOADING:
438 case TextureManager::WAITING_FOR_MASK:
439 case TextureManager::MASK_APPLYING:
440 case TextureManager::MASK_APPLIED:
442 ObserveTexture( textureInfo, observer );
445 case TextureManager::UPLOADED:
449 LoadOrQueueTexture( textureInfo, observer );
453 case TextureManager::CANCELLED:
455 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
456 // (it's ref count has already been incremented, above)
457 textureInfo.loadState = TextureManager::LOADING;
458 ObserveTexture( textureInfo, observer );
461 case TextureManager::LOAD_FINISHED:
462 // Loading has already completed. Do nothing.
466 // Return the TextureId for which this Texture can now be referenced by externally.
470 void TextureManager::Remove( const TextureManager::TextureId textureId )
472 int textureInfoIndex = GetCacheIndexFromId( textureId );
473 if( textureInfoIndex != INVALID_INDEX )
475 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
477 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
478 "TextureManager::Remove(%d) url:%s\n cacheIdx:%d loadState:%s\n",
479 textureId, textureInfo.url.GetUrl().c_str(),
480 textureInfoIndex, GET_LOAD_STATE_STRING( textureInfo.loadState ) );
482 // Decrement the reference count and check if this is the last user of this Texture.
483 if( --textureInfo.referenceCount <= 0 )
485 // This is the last remove for this Texture.
486 textureInfo.referenceCount = 0;
487 bool removeTextureInfo = false;
489 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
490 if( textureInfo.loadState == UPLOADED )
492 if( textureInfo.atlas )
494 textureInfo.atlas.Remove( textureInfo.atlasRect );
496 removeTextureInfo = true;
498 else if( textureInfo.loadState == LOADING )
500 // We mark the textureInfo for removal.
501 // Once the load has completed, this method will be called again.
502 textureInfo.loadState = CANCELLED;
506 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
507 removeTextureInfo = true;
510 // If the state allows us to remove the TextureInfo data, we do so.
511 if( removeTextureInfo )
513 // Permanently remove the textureInfo struct.
514 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
520 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
522 VisualUrl visualUrl("");
523 int cacheIndex = GetCacheIndexFromId( textureId );
525 if( cacheIndex != INVALID_CACHE_INDEX )
527 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
528 cacheIndex, textureId );
530 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
531 visualUrl = cachedTextureInfo.url;
536 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
538 LoadState loadState = TextureManager::NOT_STARTED;
540 int cacheIndex = GetCacheIndexFromId( textureId );
541 if( cacheIndex != INVALID_CACHE_INDEX )
543 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
544 loadState = cachedTextureInfo.loadState;
548 for( auto&& elem : mExternalTextures )
550 if( elem.textureId == textureId )
552 loadState = LoadState::UPLOADED;
560 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
562 LoadState loadState = TextureManager::NOT_STARTED;
564 int cacheIndex = GetCacheIndexFromId( textureId );
565 if( cacheIndex != INVALID_CACHE_INDEX )
567 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
568 loadState = cachedTextureInfo.loadState;
574 TextureSet TextureManager::GetTextureSet( TextureId textureId )
576 TextureSet textureSet;// empty handle
578 int cacheIndex = GetCacheIndexFromId( textureId );
579 if( cacheIndex != INVALID_CACHE_INDEX )
581 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
582 textureSet = cachedTextureInfo.textureSet;
586 for( auto&& elem : mExternalTextures )
588 if( elem.textureId == textureId )
590 textureSet = elem.textureSet;
598 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
600 TextureManager::ExternalTextureInfo info;
601 info.textureId = GenerateUniqueTextureId();
602 info.textureSet = textureSet;
603 mExternalTextures.emplace_back( info );
604 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
607 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
609 if( url.size() > 0u )
611 // get the location from the Url
612 VisualUrl parseUrl( url );
613 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
615 std::string location = parseUrl.GetLocation();
616 if( location.size() > 0u )
618 TextureId id = std::stoi( location );
619 const auto end = mExternalTextures.end();
620 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
622 if( iter->textureId == id )
624 auto textureSet = iter->textureSet;
625 mExternalTextures.erase( iter );
636 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
638 // make sure an observer doesn't observe the same object twice
639 // otherwise it will get multiple calls to ObjectDestroyed()
640 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
641 mLifecycleObservers.PushBack( &observer );
644 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
646 // Find the observer...
647 auto endIter = mLifecycleObservers.End();
648 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
650 if( (*iter) == &observer)
652 mLifecycleObservers.Erase( iter );
656 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
659 void TextureManager::LoadOrQueueTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
661 switch( textureInfo.loadState )
668 QueueLoadTexture( textureInfo, observer );
672 LoadTexture( textureInfo, observer );
680 QueueLoadTexture( textureInfo, observer );
684 // The Texture has already loaded. The other observers have already been notified.
685 // We need to send a "late" loaded notification for this observer.
686 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
687 textureInfo.useAtlas, textureInfo.atlasRect,
688 textureInfo.preMultiplied );
695 case WAITING_FOR_MASK:
704 void TextureManager::QueueLoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
706 auto textureId = textureInfo.textureId;
707 mLoadQueue.PushBack( LoadQueueElement( textureId, observer) );
710 void TextureManager::LoadTexture( TextureInfo& textureInfo, TextureUploadObserver* observer )
712 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::LoadTexture(): url:%s sync:%s\n",
713 textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
715 textureInfo.loadState = LOADING;
716 if( !textureInfo.loadSynchronously )
718 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
719 auto loadingHelperIt = loadersContainer.GetNext();
720 auto premultiplyOnLoad = ( textureInfo.preMultiplyOnLoad && textureInfo.maskTextureId == INVALID_TEXTURE_ID ) ?
721 DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
722 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
723 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
724 textureInfo.desiredSize, textureInfo.fittingMode,
725 textureInfo.samplingMode, textureInfo.orientationCorrection,
728 ObserveTexture( textureInfo, observer );
731 void TextureManager::ProcessQueuedTextures()
733 for( auto&& element : mLoadQueue )
735 int cacheIndex = GetCacheIndexFromId( element.mTextureId );
736 if( cacheIndex != INVALID_CACHE_INDEX )
738 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
739 if( textureInfo.loadState == UPLOADED )
741 element.mObserver->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
742 textureInfo.useAtlas, textureInfo.atlasRect,
743 textureInfo.preMultiplied );
747 LoadTexture( textureInfo, element.mObserver );
754 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
755 TextureUploadObserver* observer )
757 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ObserveTexture(): url:%s observer:%p\n",
758 textureInfo.url.GetUrl().c_str(), observer );
762 textureInfo.observerList.PushBack( observer );
763 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
767 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
768 Devel::PixelBuffer pixelBuffer )
770 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
772 if( loadingContainer.size() >= 1u )
774 AsyncLoadingInfo loadingInfo = loadingContainer.front();
776 if( loadingInfo.loadId == id )
778 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
779 if( cacheIndex != INVALID_CACHE_INDEX )
781 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
783 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise,
784 " textureId:%d Url:%s CacheIndex:%d LoadState: %d\n",
785 textureInfo.textureId, textureInfo.url.GetUrl().c_str(), cacheIndex, textureInfo.loadState );
787 if( textureInfo.loadState != CANCELLED )
789 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
790 PostLoad( textureInfo, pixelBuffer );
794 Remove( textureInfo.textureId );
799 loadingContainer.pop_front();
803 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
805 // Was the load successful?
806 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
808 // No atlas support for now
809 textureInfo.useAtlas = NO_ATLAS;
811 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
813 // If there is a mask texture ID associated with this texture, then apply the mask
814 // if it's already loaded. If it hasn't, and the mask is still loading,
815 // wait for the mask to finish loading.
816 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
818 if( textureInfo.loadState == MASK_APPLYING )
820 textureInfo.loadState = MASK_APPLIED;
821 UploadTexture( pixelBuffer, textureInfo );
822 NotifyObservers( textureInfo, true );
826 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
827 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
828 if( maskLoadState == LOADING )
830 textureInfo.loadState = WAITING_FOR_MASK;
832 else if( maskLoadState == LOAD_FINISHED )
834 // Send New Task to Thread
835 ApplyMask( textureInfo, textureInfo.maskTextureId );
841 UploadTexture( pixelBuffer, textureInfo );
842 NotifyObservers( textureInfo, true );
847 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
848 textureInfo.loadState = LOAD_FINISHED;
850 // Check if there was another texture waiting for this load to complete
851 // (e.g. if this was an image mask, and its load is on a different thread)
852 CheckForWaitingTexture( textureInfo );
857 // @todo If the load was unsuccessful, upload the broken image.
858 textureInfo.loadState = LOAD_FAILED;
859 CheckForWaitingTexture( textureInfo );
860 NotifyObservers( textureInfo, false );
864 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
866 // Search the cache, checking if any texture has this texture id as a
868 const unsigned int size = mTextureInfoContainer.size();
870 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
872 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
873 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
875 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
877 if( maskTextureInfo.loadState == LOAD_FINISHED )
879 // Send New Task to Thread
880 ApplyMask( textureInfo, maskTextureInfo.textureId );
884 textureInfo.pixelBuffer.Reset();
885 textureInfo.loadState = LOAD_FAILED;
886 NotifyObservers( textureInfo, false );
892 void TextureManager::ApplyMask( TextureInfo& textureInfo, TextureId maskTextureId )
894 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
895 if( maskCacheIndex != INVALID_CACHE_INDEX )
897 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
898 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
899 textureInfo.pixelBuffer.Reset();
901 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::ApplyMask(): url:%s sync:%s\n",
902 textureInfo.url.GetUrl().c_str(), textureInfo.loadSynchronously?"T":"F" );
904 textureInfo.loadState = MASK_APPLYING;
905 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
906 auto loadingHelperIt = loadersContainer.GetNext();
907 auto premultiplyOnLoad = textureInfo.preMultiplyOnLoad ? DevelAsyncImageLoader::PreMultiplyOnLoad::ON : DevelAsyncImageLoader::PreMultiplyOnLoad::OFF;
908 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
909 loadingHelperIt->ApplyMask( textureInfo.textureId, pixelBuffer, maskPixelBuffer, textureInfo.scaleFactor, textureInfo.cropToMask, premultiplyOnLoad );
913 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
915 if( textureInfo.useAtlas != USE_ATLAS )
917 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::General, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
919 // Check if this pixelBuffer is premultiplied
920 textureInfo.preMultiplied = pixelBuffer.IsAlphaPreMultiplied();
922 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
923 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
925 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
926 texture.Upload( pixelData );
927 if ( ! textureInfo.textureSet )
929 textureInfo.textureSet = TextureSet::New();
931 textureInfo.textureSet.SetTexture( 0u, texture );
934 // Update the load state.
935 // Note: This is regardless of success as we care about whether a
936 // load attempt is in progress or not. If unsuccessful, a broken
937 // image is still loaded.
938 textureInfo.loadState = UPLOADED;
941 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
943 TextureId textureId = textureInfo.textureId;
945 // If there is an observer: Notify the load is complete, whether successful or not,
946 // and erase it from the list
947 TextureInfo* info = &textureInfo;
949 mQueueLoadFlag = true;
951 while( info->observerList.Count() )
953 TextureUploadObserver* observer = info->observerList[0];
955 // During UploadComplete() a Control ResourceReady() signal is emitted.
956 // During that signal the app may add remove /add Textures (e.g. via
958 // It is possible for observers to be removed from the observer list,
959 // and it is also possible for the mTextureInfoContainer to be modified,
960 // invalidating the reference to the textureInfo struct.
961 // Texture load requests for the same URL are deferred until the end of this
963 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "NotifyObservers() url:%s loadState:%s\n",
964 textureInfo.url.GetUrl().c_str(), GET_LOAD_STATE_STRING(textureInfo.loadState ) );
966 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
967 info->preMultiplied );
968 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
970 // Get the textureInfo from the container again as it may have been invalidated.
971 int textureInfoIndex = GetCacheIndexFromId( textureId );
972 if( textureInfoIndex == INVALID_CACHE_INDEX)
974 break; // texture has been removed - can stop.
976 info = &mTextureInfoContainer[ textureInfoIndex ];
978 // remove the observer that was just triggered if it's still in the list
979 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
983 info->observerList.Erase( j );
989 mQueueLoadFlag = false;
990 ProcessQueuedTextures();
993 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
995 return mCurrentTextureId++;
998 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
1000 const unsigned int size = mTextureInfoContainer.size();
1002 for( unsigned int i = 0; i < size; ++i )
1004 if( mTextureInfoContainer[i].textureId == textureId )
1010 return INVALID_CACHE_INDEX;
1013 TextureManager::TextureHash TextureManager::GenerateHash(
1014 const std::string& url,
1015 const ImageDimensions size,
1016 const FittingMode::Type fittingMode,
1017 const Dali::SamplingMode::Type samplingMode,
1018 const UseAtlas useAtlas,
1019 TextureId maskTextureId )
1021 std::string hashTarget( url );
1022 const size_t urlLength = hashTarget.length();
1023 const uint16_t width = size.GetWidth();
1024 const uint16_t height = size.GetWidth();
1026 // If either the width or height has been specified, include the resizing options in the hash
1027 if( width != 0 || height != 0 )
1029 // We are appending 5 bytes to the URL to form the hash input.
1030 hashTarget.resize( urlLength + 5u );
1031 char* hashTargetPtr = &( hashTarget[ urlLength ] );
1033 // Pack the width and height (4 bytes total).
1034 *hashTargetPtr++ = size.GetWidth() & 0xff;
1035 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
1036 *hashTargetPtr++ = size.GetHeight() & 0xff;
1037 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
1039 // Bit-pack the FittingMode, SamplingMode and atlasing.
1040 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
1041 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
1045 // We are not including sizing information, but we still need an extra byte for atlasing.
1046 hashTarget.resize( urlLength + 1u );
1048 // Add the atlasing to the hash input.
1051 case UseAtlas::NO_ATLAS:
1053 hashTarget[ urlLength ] = 'f';
1056 case UseAtlas::USE_ATLAS:
1058 hashTarget[ urlLength ] = 't';
1064 if( maskTextureId != INVALID_TEXTURE_ID )
1066 auto textureIdIndex = hashTarget.length();
1067 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
1068 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
1070 // Append the texture id to the end of the URL byte by byte:
1071 // (to avoid SIGBUS / alignment issues)
1072 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
1074 *hashTargetPtr++ = maskTextureId & 0xff;
1075 maskTextureId >>= 8u;
1079 return Dali::CalculateHash( hashTarget );
1082 int TextureManager::FindCachedTexture(
1083 const TextureManager::TextureHash hash,
1084 const std::string& url,
1085 const ImageDimensions size,
1086 const FittingMode::Type fittingMode,
1087 const Dali::SamplingMode::Type samplingMode,
1088 const bool useAtlas,
1089 TextureId maskTextureId,
1090 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
1092 // Default to an invalid ID, in case we do not find a match.
1093 int cacheIndex = INVALID_CACHE_INDEX;
1095 // Iterate through our hashes to find a match.
1096 const unsigned int count = mTextureInfoContainer.size();
1097 for( unsigned int i = 0u; i < count; ++i )
1099 if( mTextureInfoContainer[i].hash == hash )
1101 // We have a match, now we check all the original parameters in case of a hash collision.
1102 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1104 if( ( url == textureInfo.url.GetUrl() ) &&
1105 ( useAtlas == textureInfo.useAtlas ) &&
1106 ( maskTextureId == textureInfo.maskTextureId ) &&
1107 ( size == textureInfo.desiredSize ) &&
1108 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
1109 ( fittingMode == textureInfo.fittingMode &&
1110 samplingMode == textureInfo.samplingMode ) ) )
1112 // 1. If preMultiplyOnLoad is MULTIPLY_ON_LOAD, then textureInfo.preMultiplyOnLoad should be true. The premultiplication result can be different.
1113 // 2. If preMultiplyOnLoad is LOAD_WITHOUT_MULTIPLY, then textureInfo.preMultiplied should be false.
1114 if( ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD && textureInfo.preMultiplyOnLoad )
1115 || ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY && !textureInfo.preMultiplied ) )
1117 // The found Texture is a match.
1128 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1130 const unsigned int count = mTextureInfoContainer.size();
1131 for( unsigned int i = 0; i < count; ++i )
1133 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1134 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1135 j != textureInfo.observerList.End(); )
1137 if( *j == observer )
1139 j = textureInfo.observerList.Erase( j );
1150 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1151 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1152 AsyncLoadingInfoContainerType())
1156 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1157 const VisualUrl& url,
1158 ImageDimensions desiredSize,
1159 FittingMode::Type fittingMode,
1160 SamplingMode::Type samplingMode,
1161 bool orientationCorrection,
1162 DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad)
1164 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1165 auto id = DevelAsyncImageLoader::Load( mLoader, url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection, preMultiplyOnLoad );
1166 mLoadingInfoContainer.back().loadId = id;
1169 void TextureManager::AsyncLoadingHelper::ApplyMask( TextureId textureId,
1170 Devel::PixelBuffer pixelBuffer,
1171 Devel::PixelBuffer maskPixelBuffer,
1174 DevelAsyncImageLoader::PreMultiplyOnLoad preMultiplyOnLoad )
1176 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1177 auto id = DevelAsyncImageLoader::ApplyMask( mLoader, pixelBuffer, maskPixelBuffer, contentScale, cropToMask, preMultiplyOnLoad );
1178 mLoadingInfoContainer.back().loadId = id;
1181 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1182 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1186 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1187 Toolkit::AsyncImageLoader loader,
1188 TextureManager& textureManager,
1189 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1191 mTextureManager(textureManager),
1192 mLoadingInfoContainer(std::move(loadingInfoContainer))
1194 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1195 this, &AsyncLoadingHelper::AsyncLoadComplete);
1198 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1199 Devel::PixelBuffer pixelBuffer )
1201 mTextureManager.AsyncLoadComplete( mLoadingInfoContainer, id, pixelBuffer );
1204 void TextureManager::SetBrokenImageUrl(const std::string& brokenImageUrl)
1206 mBrokenImageUrl = brokenImageUrl;
1209 } // namespace Internal
1211 } // namespace Toolkit