2 * Copyright (c) 2017 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
90 } // Anonymous namespace
92 TextureManager::MaskingData::MaskingData()
94 mAlphaMaskId( INVALID_TEXTURE_ID ),
95 mContentScaleFactor( 1.0f ),
100 TextureManager::TextureManager()
101 : mAsyncLocalLoaders( GetNumberOfLocalLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
102 mAsyncRemoteLoaders( GetNumberOfRemoteLoaderThreads(), [&]() { return AsyncLoadingHelper(*this); } ),
103 mCurrentTextureId( 0 )
107 TextureSet TextureManager::LoadTexture(
108 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
109 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
110 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
111 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
112 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
113 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
114 TextureManager::ReloadPolicy reloadPolicy )
116 TextureSet textureSet;
118 loadingStatus = false;
119 textureRect = FULL_ATLAS_RECT;
121 if( VisualUrl::TEXTURE == url.GetProtocolType())
123 std::string location = url.GetLocation();
124 if( location.size() > 0u )
126 TextureId id = std::stoi( location );
127 for( auto&& elem : mExternalTextures )
129 if( elem.textureId == id )
131 textureId = elem.textureId;
132 return elem.textureSet;
137 else if( synchronousLoading )
142 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
143 orientationCorrection );
146 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
152 textureSet = TextureSet::New();
153 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
156 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
158 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
159 data.GetWidth(), data.GetHeight() );
160 texture.Upload( data );
161 textureSet = TextureSet::New();
162 textureSet.SetTexture( 0u, texture );
166 if( atlasingStatus ) // attempt atlasing
168 textureSet = imageAtlasManager->Add( textureRect, data );
170 if( !textureSet ) // big image, no atlasing or atlasing failed
172 atlasingStatus = false;
173 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
174 data.GetWidth(), data.GetHeight() );
175 texture.Upload( data );
176 textureSet = TextureSet::New();
177 textureSet.SetTexture( 0u, texture );
183 loadingStatus = true;
186 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
188 if( !textureSet ) // big image, no atlasing or atlasing failed
190 atlasingStatus = false;
193 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
194 textureObserver, orientationCorrection, reloadPolicy );
198 textureId = RequestLoad( url,
199 maskInfo->mAlphaMaskId,
200 maskInfo->mContentScaleFactor,
202 fittingMode, samplingMode,
203 TextureManager::NO_ATLAS,
204 maskInfo->mCropToMask,
206 orientationCorrection,
210 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
211 loadingStatus = ( loadState == TextureManager::LOADING );
213 if( loadState == TextureManager::UPLOADED )
215 // UploadComplete has already been called - keep the same texture set
216 textureSet = GetTextureSet( textureId );
221 if( ! atlasingStatus && textureSet )
223 Sampler sampler = Sampler::New();
224 sampler.SetWrapMode( wrapModeU, wrapModeV );
225 textureSet.SetSampler( 0u, sampler );
231 TextureManager::TextureId TextureManager::RequestLoad(
232 const VisualUrl& url,
233 const ImageDimensions desiredSize,
234 FittingMode::Type fittingMode,
235 Dali::SamplingMode::Type samplingMode,
236 const UseAtlas useAtlas,
237 TextureUploadObserver* observer,
238 bool orientationCorrection,
239 TextureManager::ReloadPolicy reloadPolicy )
241 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
242 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
245 TextureManager::TextureId TextureManager::RequestLoad(
246 const VisualUrl& url,
247 TextureId maskTextureId,
249 const ImageDimensions desiredSize,
250 FittingMode::Type fittingMode,
251 Dali::SamplingMode::Type samplingMode,
252 const UseAtlas useAtlas,
254 TextureUploadObserver* observer,
255 bool orientationCorrection,
256 TextureManager::ReloadPolicy reloadPolicy )
258 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
259 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy );
262 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
264 // Use the normal load procedure to get the alpha mask.
265 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
266 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
267 TextureManager::ReloadPolicy::CACHED );
270 TextureManager::TextureId TextureManager::RequestLoadInternal(
271 const VisualUrl& url,
272 TextureId maskTextureId,
274 const ImageDimensions desiredSize,
275 FittingMode::Type fittingMode,
276 Dali::SamplingMode::Type samplingMode,
279 StorageType storageType,
280 TextureUploadObserver* observer,
281 bool orientationCorrection,
282 TextureManager::ReloadPolicy reloadPolicy )
284 // First check if the requested Texture is cached.
285 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
288 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
290 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
291 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
294 // Check if the requested Texture exists in the cache.
295 if( cacheIndex != INVALID_CACHE_INDEX )
297 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
299 // Mark this texture being used by another client resource. Forced reload would replace the current texture
300 // without the need for incrementing the reference count.
301 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
303 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
304 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
305 url.GetUrl().c_str(), observer, cacheIndex, textureId );
308 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
310 // We need a new Texture.
311 textureId = GenerateUniqueTextureId();
312 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
313 desiredSize, contentScale, fittingMode, samplingMode,
314 false, cropToMask, useAtlas, textureHash, orientationCorrection ) );
315 cacheIndex = mTextureInfoContainer.size() - 1u;
317 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
318 url.GetUrl().c_str(), observer, cacheIndex, textureId );
321 // The below code path is common whether we are using the cache or not.
322 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
323 // or a new TextureInfo just created.
324 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
325 textureInfo.maskTextureId = maskTextureId;
326 textureInfo.storageType = storageType;
327 textureInfo.orientationCorrection = orientationCorrection;
329 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
330 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
331 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
332 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
333 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
335 // Force reloading of texture by setting loadState unless already loading or cancelled.
336 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
337 TextureManager::CANCELLED != textureInfo.loadState )
339 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
340 url.GetUrl().c_str(), observer, cacheIndex, textureId );
341 textureInfo.loadState = TextureManager::NOT_STARTED;
344 // Check if we should add the observer.
345 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
346 switch( textureInfo.loadState )
348 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
349 case TextureManager::NOT_STARTED:
351 LoadTexture( textureInfo );
352 ObserveTexture( textureInfo, observer );
355 case TextureManager::LOADING:
357 ObserveTexture( textureInfo, observer );
360 case TextureManager::UPLOADED:
364 // The Texture has already loaded. The other observers have already been notified.
365 // We need to send a "late" loaded notification for this observer.
366 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
367 textureInfo.useAtlas, textureInfo.atlasRect );
371 case TextureManager::CANCELLED:
373 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
374 // (it's ref count has already been incremented, above)
375 textureInfo.loadState = TextureManager::LOADING;
376 ObserveTexture( textureInfo, observer );
379 case TextureManager::LOAD_FINISHED:
380 case TextureManager::WAITING_FOR_MASK:
381 // Loading has already completed. Do nothing.
385 // Return the TextureId for which this Texture can now be referenced by externally.
389 void TextureManager::Remove( const TextureManager::TextureId textureId )
391 int textureInfoIndex = GetCacheIndexFromId( textureId );
392 if( textureInfoIndex != INVALID_INDEX )
394 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
396 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
397 textureId, textureInfoIndex,
398 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
399 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
400 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
401 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
403 // Decrement the reference count and check if this is the last user of this Texture.
404 if( --textureInfo.referenceCount <= 0 )
406 // This is the last remove for this Texture.
407 textureInfo.referenceCount = 0;
408 bool removeTextureInfo = false;
410 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
411 if( textureInfo.loadState == UPLOADED )
413 if( textureInfo.atlas )
415 textureInfo.atlas.Remove( textureInfo.atlasRect );
417 removeTextureInfo = true;
419 else if( textureInfo.loadState == LOADING )
421 // We mark the textureInfo for removal.
422 // Once the load has completed, this method will be called again.
423 textureInfo.loadState = CANCELLED;
427 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
428 removeTextureInfo = true;
431 // If the state allows us to remove the TextureInfo data, we do so.
432 if( removeTextureInfo )
434 // Permanently remove the textureInfo struct.
435 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
441 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
443 int cacheIndex = GetCacheIndexFromId( textureId );
444 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
446 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
447 return cachedTextureInfo.url;
450 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
452 LoadState loadState = TextureManager::NOT_STARTED;
454 int cacheIndex = GetCacheIndexFromId( textureId );
455 if( cacheIndex != INVALID_CACHE_INDEX )
457 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
458 loadState = cachedTextureInfo.loadState;
462 for( auto&& elem : mExternalTextures )
464 if( elem.textureId == textureId )
466 loadState = LoadState::UPLOADED;
474 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
476 LoadState loadState = TextureManager::NOT_STARTED;
478 int cacheIndex = GetCacheIndexFromId( textureId );
479 if( cacheIndex != INVALID_CACHE_INDEX )
481 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
482 loadState = cachedTextureInfo.loadState;
488 TextureSet TextureManager::GetTextureSet( TextureId textureId )
490 TextureSet textureSet;// empty handle
492 int cacheIndex = GetCacheIndexFromId( textureId );
493 if( cacheIndex != INVALID_CACHE_INDEX )
495 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
496 textureSet = cachedTextureInfo.textureSet;
500 for( auto&& elem : mExternalTextures )
502 if( elem.textureId == textureId )
504 textureSet = elem.textureSet;
512 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
514 TextureManager::ExternalTextureInfo info;
515 info.textureId = GenerateUniqueTextureId();
516 info.textureSet = textureSet;
517 mExternalTextures.emplace_back( info );
518 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
521 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
523 if( url.size() > 0u )
525 // get the location from the Url
526 VisualUrl parseUrl( url );
527 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
529 std::string location = parseUrl.GetLocation();
530 if( location.size() > 0u )
532 TextureId id = std::stoi( location );
533 const auto end = mExternalTextures.end();
534 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
536 if( iter->textureId == id )
538 auto textureSet = iter->textureSet;
539 mExternalTextures.erase( iter );
549 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
553 if( textureInfo.loadState == NOT_STARTED )
555 textureInfo.loadState = LOADING;
557 if( !textureInfo.loadSynchronously )
559 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
560 auto loadingHelperIt = loadersContainer.GetNext();
561 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
562 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
563 textureInfo.desiredSize, textureInfo.fittingMode,
564 textureInfo.samplingMode, textureInfo.orientationCorrection );
571 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
572 TextureUploadObserver* observer )
576 textureInfo.observerList.PushBack( observer );
577 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
581 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
582 Devel::PixelBuffer pixelBuffer )
584 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
586 if( loadingContainer.size() >= 1u )
588 AsyncLoadingInfo loadingInfo = loadingContainer.front();
590 if( loadingInfo.loadId == id )
592 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
593 if( cacheIndex != INVALID_CACHE_INDEX )
595 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
597 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
599 if( textureInfo.loadState != CANCELLED )
601 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
602 PostLoad( textureInfo, pixelBuffer );
606 Remove( textureInfo.textureId );
611 loadingContainer.pop_front();
615 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
617 // Was the load successful?
618 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
620 // No atlas support for now
621 textureInfo.useAtlas = NO_ATLAS;
623 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
625 // If there is a mask texture ID associated with this texture, then apply the mask
626 // if it's already loaded. If it hasn't, and the mask is still loading,
627 // wait for the mask to finish loading.
628 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
630 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
631 if( maskLoadState == LOADING )
633 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
634 textureInfo.loadState = WAITING_FOR_MASK;
636 else if( maskLoadState == LOAD_FINISHED )
638 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
639 UploadTexture( pixelBuffer, textureInfo );
640 NotifyObservers( textureInfo, true );
645 UploadTexture( pixelBuffer, textureInfo );
646 NotifyObservers( textureInfo, true );
651 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
652 textureInfo.loadState = LOAD_FINISHED;
654 // Check if there was another texture waiting for this load to complete
655 // (e.g. if this was an image mask, and its load is on a different thread)
656 CheckForWaitingTexture( textureInfo );
661 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
662 // @todo If the load was unsuccessful, upload the broken image.
663 textureInfo.loadState = LOAD_FAILED;
664 CheckForWaitingTexture( textureInfo );
665 NotifyObservers( textureInfo, false );
669 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
671 // Search the cache, checking if any texture has this texture id as a
673 const unsigned int size = mTextureInfoContainer.size();
675 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
677 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
678 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
680 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
681 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
682 textureInfo.pixelBuffer.Reset();
684 if( maskTextureInfo.loadState == LOAD_FINISHED )
686 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
687 UploadTexture( pixelBuffer, textureInfo );
688 NotifyObservers( textureInfo, true );
692 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
693 textureInfo.loadState = LOAD_FAILED;
694 NotifyObservers( textureInfo, false );
700 void TextureManager::ApplyMask(
701 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
702 float contentScale, bool cropToMask )
704 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
705 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
706 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
709 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
711 if( textureInfo.useAtlas != USE_ATLAS )
713 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
715 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
716 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
717 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
718 texture.Upload( pixelData );
719 if ( ! textureInfo.textureSet )
721 textureInfo.textureSet = TextureSet::New();
723 textureInfo.textureSet.SetTexture( 0u, texture );
726 // Update the load state.
727 // Note: This is regardless of success as we care about whether a
728 // load attempt is in progress or not. If unsuccessful, a broken
729 // image is still loaded.
730 textureInfo.loadState = UPLOADED;
733 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
735 TextureId textureId = textureInfo.textureId;
737 // If there is an observer: Notify the load is complete, whether successful or not,
738 // and erase it from the list
739 unsigned int observerCount = textureInfo.observerList.Count();
740 TextureInfo* info = &textureInfo;
742 while( observerCount )
744 TextureUploadObserver* observer = info->observerList[0];
746 // During UploadComplete() a Control ResourceReady() signal is emitted.
747 // During that signal the app may add remove /add Textures (e.g. via
748 // ImageViews). At this point no more observers can be added to the
749 // observerList, because textureInfo.loadState = UPLOADED. However it is
750 // possible for observers to be removed, hence we check the observer list
751 // count every iteration.
753 // The reference to the textureInfo struct can also become invalidated,
754 // because new load requests can modify the mTextureInfoContainer list
755 // (e.g. if more requests are pushed back it can cause the list to be
756 // resized invalidating the reference to the TextureInfo ).
757 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect );
758 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
760 // Get the textureInfo from the container again as it may have been
763 int textureInfoIndex = GetCacheIndexFromId( textureId );
764 if( textureInfoIndex == INVALID_CACHE_INDEX)
766 return; // texture has been removed - can stop.
769 info = &mTextureInfoContainer[ textureInfoIndex ];
770 observerCount = info->observerList.Count();
771 if ( observerCount > 0 )
773 // remove the observer that was just triggered if it's still in the list
774 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
778 info->observerList.Erase( j );
787 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
789 return mCurrentTextureId++;
792 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
794 const unsigned int size = mTextureInfoContainer.size();
796 for( unsigned int i = 0; i < size; ++i )
798 if( mTextureInfoContainer[i].textureId == textureId )
804 return INVALID_CACHE_INDEX;
807 TextureManager::TextureHash TextureManager::GenerateHash(
808 const std::string& url,
809 const ImageDimensions size,
810 const FittingMode::Type fittingMode,
811 const Dali::SamplingMode::Type samplingMode,
812 const UseAtlas useAtlas,
813 TextureId maskTextureId )
815 std::string hashTarget( url );
816 const size_t urlLength = hashTarget.length();
817 const uint16_t width = size.GetWidth();
818 const uint16_t height = size.GetWidth();
820 // If either the width or height has been specified, include the resizing options in the hash
821 if( width != 0 || height != 0 )
823 // We are appending 5 bytes to the URL to form the hash input.
824 hashTarget.resize( urlLength + 5u );
825 char* hashTargetPtr = &( hashTarget[ urlLength ] );
827 // Pack the width and height (4 bytes total).
828 *hashTargetPtr++ = size.GetWidth() & 0xff;
829 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
830 *hashTargetPtr++ = size.GetHeight() & 0xff;
831 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
833 // Bit-pack the FittingMode, SamplingMode and atlasing.
834 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
835 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
839 // We are not including sizing information, but we still need an extra byte for atlasing.
840 hashTarget.resize( urlLength + 1u );
841 // Add the atlasing to the hash input.
842 hashTarget[ urlLength ] = useAtlas;
845 if( maskTextureId != INVALID_TEXTURE_ID )
847 hashTarget.resize( urlLength + sizeof( TextureId ) );
848 TextureId* hashTargetPtr = reinterpret_cast<TextureId*>(&( hashTarget[ urlLength ] ));
850 // Append the hash target to the end of the URL byte by byte:
851 // (to avoid SIGBUS / alignment issues)
852 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
854 *hashTargetPtr++ = maskTextureId & 0xff;
855 maskTextureId >>= 8u;
859 return Dali::CalculateHash( hashTarget );
862 int TextureManager::FindCachedTexture(
863 const TextureManager::TextureHash hash,
864 const std::string& url,
865 const ImageDimensions size,
866 const FittingMode::Type fittingMode,
867 const Dali::SamplingMode::Type samplingMode,
869 TextureId maskTextureId)
871 // Default to an invalid ID, in case we do not find a match.
872 int cacheIndex = INVALID_CACHE_INDEX;
874 // Iterate through our hashes to find a match.
875 const unsigned int count = mTextureInfoContainer.size();
876 for( unsigned int i = 0u; i < count; ++i )
878 if( mTextureInfoContainer[i].hash == hash )
880 // We have a match, now we check all the original parameters in case of a hash collision.
881 TextureInfo& textureInfo( mTextureInfoContainer[i] );
883 if( ( url == textureInfo.url.GetUrl() ) &&
884 ( useAtlas == textureInfo.useAtlas ) &&
885 ( maskTextureId == textureInfo.maskTextureId ) &&
886 ( size == textureInfo.desiredSize ) &&
887 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
888 ( fittingMode == textureInfo.fittingMode &&
889 samplingMode == textureInfo.samplingMode ) ) )
891 // The found Texture is a match.
901 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
903 const unsigned int count = mTextureInfoContainer.size();
904 for( unsigned int i = 0; i < count; ++i )
906 TextureInfo& textureInfo( mTextureInfoContainer[i] );
907 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
908 j != textureInfo.observerList.End(); )
912 j = textureInfo.observerList.Erase( j );
922 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
923 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
924 AsyncLoadingInfoContainerType())
928 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
929 const VisualUrl& url,
930 ImageDimensions desiredSize,
931 FittingMode::Type fittingMode,
932 SamplingMode::Type samplingMode,
933 bool orientationCorrection)
935 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
936 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
937 mLoadingInfoContainer.back().loadId = id;
940 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
941 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
945 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
946 Toolkit::AsyncImageLoader loader,
947 TextureManager& textureManager,
948 AsyncLoadingInfoContainerType&& loadingInfoContainer)
950 mTextureManager(textureManager),
951 mLoadingInfoContainer(std::move(loadingInfoContainer))
953 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
954 this, &AsyncLoadingHelper::AsyncLoadComplete);
957 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
958 Devel::PixelBuffer pixelBuffer)
960 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
963 } // namespace Internal
965 } // namespace Toolkit