2 * Copyright (c) 2018 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" );
84 const uint32_t DEFAULT_ATLAS_SIZE( 1024u ); ///< This size can fit 8 by 8 images of average size 128 * 128
85 const Vector4 FULL_ATLAS_RECT( 0.0f, 0.0f, 1.0f, 1.0f ); ///< UV Rectangle that covers the full Texture
86 const char * const BROKEN_IMAGE_URL( DALI_IMAGE_DIR "broken.png" ); ///< URL For the broken image placeholder
87 const int INVALID_INDEX( -1 ); ///< Invalid index used to represent a non-existant TextureInfo struct
88 const int INVALID_CACHE_INDEX( -1 ); ///< Invalid Cache index
91 void PreMultiply( Devel::PixelBuffer pixelBuffer, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
93 if( Pixel::HasAlpha( pixelBuffer.GetPixelFormat() ) )
95 if( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD )
97 pixelBuffer.MultiplyColorByAlpha();
102 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
106 } // Anonymous namespace
108 TextureManager::MaskingData::MaskingData()
110 mAlphaMaskId( INVALID_TEXTURE_ID ),
111 mContentScaleFactor( 1.0f ),
116 TextureManager::TextureManager()
117 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
118 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
119 mCurrentTextureId( 0 )
123 TextureManager::~TextureManager()
125 for( auto iter = mLifecycleObservers.Begin(), endIter = mLifecycleObservers.End(); iter != endIter; ++iter)
127 (*iter)->TextureManagerDestroyed();
131 TextureSet TextureManager::LoadTexture(
132 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
133 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
134 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
135 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
136 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
137 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
138 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
140 TextureSet textureSet;
142 loadingStatus = false;
143 textureRect = FULL_ATLAS_RECT;
145 if( VisualUrl::TEXTURE == url.GetProtocolType())
147 std::string location = url.GetLocation();
148 if( location.size() > 0u )
150 TextureId id = std::stoi( location );
151 for( auto&& elem : mExternalTextures )
153 if( elem.textureId == id )
155 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
156 textureId = elem.textureId;
157 return elem.textureSet;
162 else if( synchronousLoading )
167 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
168 orientationCorrection );
171 PreMultiply( pixelBuffer, preMultiplyOnLoad );
172 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
178 textureSet = TextureSet::New();
179 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
182 PreMultiply( pixelBuffer, preMultiplyOnLoad );
183 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
185 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
186 data.GetWidth(), data.GetHeight() );
187 texture.Upload( data );
188 textureSet = TextureSet::New();
189 textureSet.SetTexture( 0u, texture );
193 if( atlasingStatus ) // attempt atlasing
195 textureSet = imageAtlasManager->Add( textureRect, data );
197 if( !textureSet ) // big image, no atlasing or atlasing failed
199 atlasingStatus = false;
200 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
201 data.GetWidth(), data.GetHeight() );
202 texture.Upload( data );
203 textureSet = TextureSet::New();
204 textureSet.SetTexture( 0u, texture );
210 loadingStatus = true;
213 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
215 if( !textureSet ) // big image, no atlasing or atlasing failed
217 atlasingStatus = false;
220 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
221 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
225 textureId = RequestLoad( url,
226 maskInfo->mAlphaMaskId,
227 maskInfo->mContentScaleFactor,
229 fittingMode, samplingMode,
230 TextureManager::NO_ATLAS,
231 maskInfo->mCropToMask,
233 orientationCorrection,
234 reloadPolicy, preMultiplyOnLoad );
237 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
238 loadingStatus = ( loadState == TextureManager::LOADING );
240 if( loadState == TextureManager::UPLOADED )
242 // UploadComplete has already been called - keep the same texture set
243 textureSet = GetTextureSet( textureId );
248 if( ! atlasingStatus && textureSet )
250 Sampler sampler = Sampler::New();
251 sampler.SetWrapMode( wrapModeU, wrapModeV );
252 textureSet.SetSampler( 0u, sampler );
258 TextureManager::TextureId TextureManager::RequestLoad(
259 const VisualUrl& url,
260 const ImageDimensions desiredSize,
261 FittingMode::Type fittingMode,
262 Dali::SamplingMode::Type samplingMode,
263 const UseAtlas useAtlas,
264 TextureUploadObserver* observer,
265 bool orientationCorrection,
266 TextureManager::ReloadPolicy reloadPolicy,
267 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
269 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
270 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
274 TextureManager::TextureId TextureManager::RequestLoad(
275 const VisualUrl& url,
276 TextureId maskTextureId,
278 const ImageDimensions desiredSize,
279 FittingMode::Type fittingMode,
280 Dali::SamplingMode::Type samplingMode,
281 const UseAtlas useAtlas,
283 TextureUploadObserver* observer,
284 bool orientationCorrection,
285 TextureManager::ReloadPolicy reloadPolicy,
286 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
288 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
289 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
293 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
295 // Use the normal load procedure to get the alpha mask.
296 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
297 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
298 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
299 TextureManager::ReloadPolicy::CACHED, preMultiply );
302 TextureManager::TextureId TextureManager::RequestLoadInternal(
303 const VisualUrl& url,
304 TextureId maskTextureId,
306 const ImageDimensions desiredSize,
307 FittingMode::Type fittingMode,
308 Dali::SamplingMode::Type samplingMode,
311 StorageType storageType,
312 TextureUploadObserver* observer,
313 bool orientationCorrection,
314 TextureManager::ReloadPolicy reloadPolicy,
315 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
317 // First check if the requested Texture is cached.
318 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
319 maskTextureId, preMultiplyOnLoad );
321 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
323 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
324 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
325 maskTextureId, preMultiplyOnLoad );
327 // Check if the requested Texture exists in the cache.
328 if( cacheIndex != INVALID_CACHE_INDEX )
330 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
332 // Mark this texture being used by another client resource. Forced reload would replace the current texture
333 // without the need for incrementing the reference count.
334 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
336 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
337 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
338 url.GetUrl().c_str(), observer, cacheIndex, textureId );
341 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
343 // We need a new Texture.
344 textureId = GenerateUniqueTextureId();
345 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
346 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
347 desiredSize, contentScale, fittingMode, samplingMode,
348 false, cropToMask, useAtlas, textureHash, orientationCorrection,
350 cacheIndex = mTextureInfoContainer.size() - 1u;
352 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
353 url.GetUrl().c_str(), observer, cacheIndex, textureId );
356 // The below code path is common whether we are using the cache or not.
357 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
358 // or a new TextureInfo just created.
359 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
360 textureInfo.maskTextureId = maskTextureId;
361 textureInfo.storageType = storageType;
362 textureInfo.orientationCorrection = orientationCorrection;
364 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
365 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
366 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
367 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
368 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
370 // Force reloading of texture by setting loadState unless already loading or cancelled.
371 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
372 TextureManager::CANCELLED != textureInfo.loadState )
374 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
375 url.GetUrl().c_str(), observer, cacheIndex, textureId );
376 textureInfo.loadState = TextureManager::NOT_STARTED;
379 // Check if we should add the observer.
380 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
381 switch( textureInfo.loadState )
383 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
384 case TextureManager::NOT_STARTED:
386 LoadTexture( textureInfo );
387 ObserveTexture( textureInfo, observer );
390 case TextureManager::LOADING:
392 ObserveTexture( textureInfo, observer );
395 case TextureManager::UPLOADED:
399 // The Texture has already loaded. The other observers have already been notified.
400 // We need to send a "late" loaded notification for this observer.
401 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
402 textureInfo.useAtlas, textureInfo.atlasRect,
403 textureInfo.preMultiplied );
407 case TextureManager::CANCELLED:
409 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
410 // (it's ref count has already been incremented, above)
411 textureInfo.loadState = TextureManager::LOADING;
412 ObserveTexture( textureInfo, observer );
415 case TextureManager::LOAD_FINISHED:
416 case TextureManager::WAITING_FOR_MASK:
417 // Loading has already completed. Do nothing.
421 // Return the TextureId for which this Texture can now be referenced by externally.
425 void TextureManager::Remove( const TextureManager::TextureId textureId )
427 int textureInfoIndex = GetCacheIndexFromId( textureId );
428 if( textureInfoIndex != INVALID_INDEX )
430 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
432 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
433 textureId, textureInfoIndex,
434 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
435 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
436 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
437 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
439 // Decrement the reference count and check if this is the last user of this Texture.
440 if( --textureInfo.referenceCount <= 0 )
442 // This is the last remove for this Texture.
443 textureInfo.referenceCount = 0;
444 bool removeTextureInfo = false;
446 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
447 if( textureInfo.loadState == UPLOADED )
449 if( textureInfo.atlas )
451 textureInfo.atlas.Remove( textureInfo.atlasRect );
453 removeTextureInfo = true;
455 else if( textureInfo.loadState == LOADING )
457 // We mark the textureInfo for removal.
458 // Once the load has completed, this method will be called again.
459 textureInfo.loadState = CANCELLED;
463 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
464 removeTextureInfo = true;
467 // If the state allows us to remove the TextureInfo data, we do so.
468 if( removeTextureInfo )
470 // Permanently remove the textureInfo struct.
471 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
477 VisualUrl TextureManager::GetVisualUrl( TextureId textureId )
479 VisualUrl visualUrl("");
480 int cacheIndex = GetCacheIndexFromId( textureId );
482 if( cacheIndex != INVALID_CACHE_INDEX )
484 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::GetVisualUrl. Using cached texture id=%d, textureId=%d\n",
485 cacheIndex, textureId );
487 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
488 visualUrl = cachedTextureInfo.url;
493 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
495 LoadState loadState = TextureManager::NOT_STARTED;
497 int cacheIndex = GetCacheIndexFromId( textureId );
498 if( cacheIndex != INVALID_CACHE_INDEX )
500 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
501 loadState = cachedTextureInfo.loadState;
505 for( auto&& elem : mExternalTextures )
507 if( elem.textureId == textureId )
509 loadState = LoadState::UPLOADED;
517 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
519 LoadState loadState = TextureManager::NOT_STARTED;
521 int cacheIndex = GetCacheIndexFromId( textureId );
522 if( cacheIndex != INVALID_CACHE_INDEX )
524 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
525 loadState = cachedTextureInfo.loadState;
531 TextureSet TextureManager::GetTextureSet( TextureId textureId )
533 TextureSet textureSet;// empty handle
535 int cacheIndex = GetCacheIndexFromId( textureId );
536 if( cacheIndex != INVALID_CACHE_INDEX )
538 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
539 textureSet = cachedTextureInfo.textureSet;
543 for( auto&& elem : mExternalTextures )
545 if( elem.textureId == textureId )
547 textureSet = elem.textureSet;
555 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
557 TextureManager::ExternalTextureInfo info;
558 info.textureId = GenerateUniqueTextureId();
559 info.textureSet = textureSet;
560 mExternalTextures.emplace_back( info );
561 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
564 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
566 if( url.size() > 0u )
568 // get the location from the Url
569 VisualUrl parseUrl( url );
570 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
572 std::string location = parseUrl.GetLocation();
573 if( location.size() > 0u )
575 TextureId id = std::stoi( location );
576 const auto end = mExternalTextures.end();
577 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
579 if( iter->textureId == id )
581 auto textureSet = iter->textureSet;
582 mExternalTextures.erase( iter );
593 void TextureManager::AddObserver( TextureManager::LifecycleObserver& observer )
595 // make sure an observer doesn't observe the same object twice
596 // otherwise it will get multiple calls to ObjectDestroyed()
597 DALI_ASSERT_DEBUG( mLifecycleObservers.End() == std::find( mLifecycleObservers.Begin(), mLifecycleObservers.End(), &observer));
598 mLifecycleObservers.PushBack( &observer );
601 void TextureManager::RemoveObserver( TextureManager::LifecycleObserver& observer)
603 // Find the observer...
604 auto endIter = mLifecycleObservers.End();
605 for( auto iter = mLifecycleObservers.Begin(); iter != endIter; ++iter)
607 if( (*iter) == &observer)
609 mLifecycleObservers.Erase( iter );
613 DALI_ASSERT_DEBUG(endIter != mLifecycleObservers.End());
617 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
621 if( textureInfo.loadState == NOT_STARTED )
623 textureInfo.loadState = LOADING;
625 if( !textureInfo.loadSynchronously )
627 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
628 auto loadingHelperIt = loadersContainer.GetNext();
629 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
630 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
631 textureInfo.desiredSize, textureInfo.fittingMode,
632 textureInfo.samplingMode, textureInfo.orientationCorrection );
639 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
640 TextureUploadObserver* observer )
644 textureInfo.observerList.PushBack( observer );
645 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
649 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
650 Devel::PixelBuffer pixelBuffer )
652 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
654 if( loadingContainer.size() >= 1u )
656 AsyncLoadingInfo loadingInfo = loadingContainer.front();
658 if( loadingInfo.loadId == id )
660 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
661 if( cacheIndex != INVALID_CACHE_INDEX )
663 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
665 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
667 if( textureInfo.loadState != CANCELLED )
669 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
670 PostLoad( textureInfo, pixelBuffer );
674 Remove( textureInfo.textureId );
679 loadingContainer.pop_front();
683 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
685 // Was the load successful?
686 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
688 // No atlas support for now
689 textureInfo.useAtlas = NO_ATLAS;
691 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
693 // If there is a mask texture ID associated with this texture, then apply the mask
694 // if it's already loaded. If it hasn't, and the mask is still loading,
695 // wait for the mask to finish loading.
696 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
698 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
699 if( maskLoadState == LOADING )
701 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
702 textureInfo.loadState = WAITING_FOR_MASK;
704 else if( maskLoadState == LOAD_FINISHED )
706 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
707 UploadTexture( pixelBuffer, textureInfo );
708 NotifyObservers( textureInfo, true );
713 UploadTexture( pixelBuffer, textureInfo );
714 NotifyObservers( textureInfo, true );
719 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
720 textureInfo.loadState = LOAD_FINISHED;
722 // Check if there was another texture waiting for this load to complete
723 // (e.g. if this was an image mask, and its load is on a different thread)
724 CheckForWaitingTexture( textureInfo );
729 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
730 // @todo If the load was unsuccessful, upload the broken image.
731 textureInfo.loadState = LOAD_FAILED;
732 CheckForWaitingTexture( textureInfo );
733 NotifyObservers( textureInfo, false );
737 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
739 // Search the cache, checking if any texture has this texture id as a
741 const unsigned int size = mTextureInfoContainer.size();
743 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
745 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
746 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
748 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
749 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
750 textureInfo.pixelBuffer.Reset();
752 if( maskTextureInfo.loadState == LOAD_FINISHED )
754 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
755 UploadTexture( pixelBuffer, textureInfo );
756 NotifyObservers( textureInfo, true );
760 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
761 textureInfo.loadState = LOAD_FAILED;
762 NotifyObservers( textureInfo, false );
768 void TextureManager::ApplyMask(
769 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
770 float contentScale, bool cropToMask )
772 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
773 if( maskCacheIndex != INVALID_CACHE_INDEX )
775 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
776 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
781 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
783 if( textureInfo.useAtlas != USE_ATLAS )
785 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
787 // If the texture doesn't have an alpha channel, can't pre-multiply it.
788 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
789 // the status for use in the observer.
790 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
791 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
792 PreMultiply( pixelBuffer, preMultiply );
793 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
795 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
796 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
798 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
799 texture.Upload( pixelData );
800 if ( ! textureInfo.textureSet )
802 textureInfo.textureSet = TextureSet::New();
804 textureInfo.textureSet.SetTexture( 0u, texture );
807 // Update the load state.
808 // Note: This is regardless of success as we care about whether a
809 // load attempt is in progress or not. If unsuccessful, a broken
810 // image is still loaded.
811 textureInfo.loadState = UPLOADED;
814 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
816 TextureId textureId = textureInfo.textureId;
818 // If there is an observer: Notify the load is complete, whether successful or not,
819 // and erase it from the list
820 unsigned int observerCount = textureInfo.observerList.Count();
821 TextureInfo* info = &textureInfo;
823 while( observerCount )
825 TextureUploadObserver* observer = info->observerList[0];
827 // During UploadComplete() a Control ResourceReady() signal is emitted.
828 // During that signal the app may add remove /add Textures (e.g. via
829 // ImageViews). At this point no more observers can be added to the
830 // observerList, because textureInfo.loadState = UPLOADED. However it is
831 // possible for observers to be removed, hence we check the observer list
832 // count every iteration.
834 // The reference to the textureInfo struct can also become invalidated,
835 // because new load requests can modify the mTextureInfoContainer list
836 // (e.g. if more requests are pushed back it can cause the list to be
837 // resized invalidating the reference to the TextureInfo ).
838 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
839 info->preMultiplied );
840 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
842 // Get the textureInfo from the container again as it may have been
845 int textureInfoIndex = GetCacheIndexFromId( textureId );
846 if( textureInfoIndex == INVALID_CACHE_INDEX)
848 return; // texture has been removed - can stop.
851 info = &mTextureInfoContainer[ textureInfoIndex ];
852 observerCount = info->observerList.Count();
853 if ( observerCount > 0 )
855 // remove the observer that was just triggered if it's still in the list
856 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
860 info->observerList.Erase( j );
869 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
871 return mCurrentTextureId++;
874 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
876 const unsigned int size = mTextureInfoContainer.size();
878 for( unsigned int i = 0; i < size; ++i )
880 if( mTextureInfoContainer[i].textureId == textureId )
886 return INVALID_CACHE_INDEX;
889 TextureManager::TextureHash TextureManager::GenerateHash(
890 const std::string& url,
891 const ImageDimensions size,
892 const FittingMode::Type fittingMode,
893 const Dali::SamplingMode::Type samplingMode,
894 const UseAtlas useAtlas,
895 TextureId maskTextureId,
896 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
898 std::string hashTarget( url );
899 const size_t urlLength = hashTarget.length();
900 const uint16_t width = size.GetWidth();
901 const uint16_t height = size.GetWidth();
903 // If either the width or height has been specified, include the resizing options in the hash
904 if( width != 0 || height != 0 )
906 // We are appending 5 bytes to the URL to form the hash input.
907 hashTarget.resize( urlLength + 5u );
908 char* hashTargetPtr = &( hashTarget[ urlLength ] );
910 // Pack the width and height (4 bytes total).
911 *hashTargetPtr++ = size.GetWidth() & 0xff;
912 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
913 *hashTargetPtr++ = size.GetHeight() & 0xff;
914 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
916 // Bit-pack the FittingMode, SamplingMode and atlasing.
917 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
918 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
922 // We are not including sizing information, but we still need an extra byte for atlasing.
923 hashTarget.resize( urlLength + 1u );
924 // Add the atlasing to the hash input.
925 hashTarget[ urlLength ] = useAtlas;
928 if( maskTextureId != INVALID_TEXTURE_ID )
930 auto textureIdIndex = hashTarget.length();
931 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
932 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
934 // Append the texture id to the end of the URL byte by byte:
935 // (to avoid SIGBUS / alignment issues)
936 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
938 *hashTargetPtr++ = maskTextureId & 0xff;
939 maskTextureId >>= 8u;
943 auto premultipliedIndex = hashTarget.length();
944 hashTarget.resize( premultipliedIndex + 1 );
945 switch( preMultiplyOnLoad )
947 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
949 hashTarget[ premultipliedIndex ] = 't';
952 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
954 hashTarget[ premultipliedIndex ] = 'f';
959 return Dali::CalculateHash( hashTarget );
962 int TextureManager::FindCachedTexture(
963 const TextureManager::TextureHash hash,
964 const std::string& url,
965 const ImageDimensions size,
966 const FittingMode::Type fittingMode,
967 const Dali::SamplingMode::Type samplingMode,
969 TextureId maskTextureId,
970 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
972 // Default to an invalid ID, in case we do not find a match.
973 int cacheIndex = INVALID_CACHE_INDEX;
975 // Iterate through our hashes to find a match.
976 const unsigned int count = mTextureInfoContainer.size();
977 for( unsigned int i = 0u; i < count; ++i )
979 if( mTextureInfoContainer[i].hash == hash )
981 // We have a match, now we check all the original parameters in case of a hash collision.
982 TextureInfo& textureInfo( mTextureInfoContainer[i] );
983 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
984 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
986 if( ( url == textureInfo.url.GetUrl() ) &&
987 ( useAtlas == textureInfo.useAtlas ) &&
988 ( maskTextureId == textureInfo.maskTextureId ) &&
989 ( size == textureInfo.desiredSize ) &&
990 ( preMultiplyOnLoad == multiplyOnLoad ) &&
991 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
992 ( fittingMode == textureInfo.fittingMode &&
993 samplingMode == textureInfo.samplingMode ) ) )
995 // The found Texture is a match.
1005 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
1007 const unsigned int count = mTextureInfoContainer.size();
1008 for( unsigned int i = 0; i < count; ++i )
1010 TextureInfo& textureInfo( mTextureInfoContainer[i] );
1011 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
1012 j != textureInfo.observerList.End(); )
1014 if( *j == observer )
1016 j = textureInfo.observerList.Erase( j );
1027 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
1028 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
1029 AsyncLoadingInfoContainerType())
1033 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
1034 const VisualUrl& url,
1035 ImageDimensions desiredSize,
1036 FittingMode::Type fittingMode,
1037 SamplingMode::Type samplingMode,
1038 bool orientationCorrection)
1040 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
1041 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
1042 mLoadingInfoContainer.back().loadId = id;
1045 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1046 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1050 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1051 Toolkit::AsyncImageLoader loader,
1052 TextureManager& textureManager,
1053 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1055 mTextureManager(textureManager),
1056 mLoadingInfoContainer(std::move(loadingInfoContainer))
1058 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1059 this, &AsyncLoadingHelper::AsyncLoadComplete);
1062 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1063 Devel::PixelBuffer pixelBuffer)
1065 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1068 } // namespace Internal
1070 } // namespace Toolkit