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 TextureSet TextureManager::LoadTexture(
124 const VisualUrl& url, Dali::ImageDimensions desiredSize, Dali::FittingMode::Type fittingMode,
125 Dali::SamplingMode::Type samplingMode, const MaskingDataPointer& maskInfo,
126 bool synchronousLoading, TextureManager::TextureId& textureId, Vector4& textureRect,
127 bool& atlasingStatus, bool& loadingStatus, Dali::WrapMode::Type wrapModeU,
128 Dali::WrapMode::Type wrapModeV, TextureUploadObserver* textureObserver,
129 AtlasUploadObserver* atlasObserver, ImageAtlasManagerPtr imageAtlasManager, bool orientationCorrection,
130 TextureManager::ReloadPolicy reloadPolicy, TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
132 TextureSet textureSet;
134 loadingStatus = false;
135 textureRect = FULL_ATLAS_RECT;
137 if( VisualUrl::TEXTURE == url.GetProtocolType())
139 std::string location = url.GetLocation();
140 if( location.size() > 0u )
142 TextureId id = std::stoi( location );
143 for( auto&& elem : mExternalTextures )
145 if( elem.textureId == id )
147 preMultiplyOnLoad = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
148 textureId = elem.textureId;
149 return elem.textureSet;
154 else if( synchronousLoading )
159 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( url.GetUrl(), desiredSize, fittingMode, samplingMode,
160 orientationCorrection );
163 PreMultiply( pixelBuffer, preMultiplyOnLoad );
164 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
170 textureSet = TextureSet::New();
171 Devel::PixelBuffer pixelBuffer = LoadImageFromFile( BROKEN_IMAGE_URL );
174 PreMultiply( pixelBuffer, preMultiplyOnLoad );
175 data = Devel::PixelBuffer::Convert(pixelBuffer); // takes ownership of buffer
177 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
178 data.GetWidth(), data.GetHeight() );
179 texture.Upload( data );
180 textureSet = TextureSet::New();
181 textureSet.SetTexture( 0u, texture );
185 if( atlasingStatus ) // attempt atlasing
187 textureSet = imageAtlasManager->Add( textureRect, data );
189 if( !textureSet ) // big image, no atlasing or atlasing failed
191 atlasingStatus = false;
192 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, data.GetPixelFormat(),
193 data.GetWidth(), data.GetHeight() );
194 texture.Upload( data );
195 textureSet = TextureSet::New();
196 textureSet.SetTexture( 0u, texture );
202 loadingStatus = true;
205 textureSet = imageAtlasManager->Add( textureRect, url.GetUrl(), desiredSize, fittingMode, true, atlasObserver );
207 if( !textureSet ) // big image, no atlasing or atlasing failed
209 atlasingStatus = false;
212 textureId = RequestLoad( url, desiredSize, fittingMode, samplingMode, TextureManager::NO_ATLAS,
213 textureObserver, orientationCorrection, reloadPolicy, preMultiplyOnLoad );
217 textureId = RequestLoad( url,
218 maskInfo->mAlphaMaskId,
219 maskInfo->mContentScaleFactor,
221 fittingMode, samplingMode,
222 TextureManager::NO_ATLAS,
223 maskInfo->mCropToMask,
225 orientationCorrection,
226 reloadPolicy, preMultiplyOnLoad );
229 TextureManager::LoadState loadState = GetTextureStateInternal( textureId );
230 loadingStatus = ( loadState == TextureManager::LOADING );
232 if( loadState == TextureManager::UPLOADED )
234 // UploadComplete has already been called - keep the same texture set
235 textureSet = GetTextureSet( textureId );
240 if( ! atlasingStatus && textureSet )
242 Sampler sampler = Sampler::New();
243 sampler.SetWrapMode( wrapModeU, wrapModeV );
244 textureSet.SetSampler( 0u, sampler );
250 TextureManager::TextureId TextureManager::RequestLoad(
251 const VisualUrl& url,
252 const ImageDimensions desiredSize,
253 FittingMode::Type fittingMode,
254 Dali::SamplingMode::Type samplingMode,
255 const UseAtlas useAtlas,
256 TextureUploadObserver* observer,
257 bool orientationCorrection,
258 TextureManager::ReloadPolicy reloadPolicy,
259 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
261 return RequestLoadInternal( url, INVALID_TEXTURE_ID, 1.0f, desiredSize, fittingMode, samplingMode, useAtlas,
262 false, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
266 TextureManager::TextureId TextureManager::RequestLoad(
267 const VisualUrl& url,
268 TextureId maskTextureId,
270 const ImageDimensions desiredSize,
271 FittingMode::Type fittingMode,
272 Dali::SamplingMode::Type samplingMode,
273 const UseAtlas useAtlas,
275 TextureUploadObserver* observer,
276 bool orientationCorrection,
277 TextureManager::ReloadPolicy reloadPolicy,
278 TextureManager::MultiplyOnLoad& preMultiplyOnLoad )
280 return RequestLoadInternal( url, maskTextureId, contentScale, desiredSize, fittingMode, samplingMode, useAtlas,
281 cropToMask, UPLOAD_TO_TEXTURE, observer, orientationCorrection, reloadPolicy,
285 TextureManager::TextureId TextureManager::RequestMaskLoad( const VisualUrl& maskUrl )
287 // Use the normal load procedure to get the alpha mask.
288 auto preMultiply = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
289 return RequestLoadInternal( maskUrl, INVALID_TEXTURE_ID, 1.0f, ImageDimensions(), FittingMode::SCALE_TO_FILL,
290 SamplingMode::NO_FILTER, NO_ATLAS, false, KEEP_PIXEL_BUFFER, NULL, true,
291 TextureManager::ReloadPolicy::CACHED, preMultiply );
294 TextureManager::TextureId TextureManager::RequestLoadInternal(
295 const VisualUrl& url,
296 TextureId maskTextureId,
298 const ImageDimensions desiredSize,
299 FittingMode::Type fittingMode,
300 Dali::SamplingMode::Type samplingMode,
303 StorageType storageType,
304 TextureUploadObserver* observer,
305 bool orientationCorrection,
306 TextureManager::ReloadPolicy reloadPolicy,
307 TextureManager::MultiplyOnLoad& preMultiplyOnLoad)
309 // First check if the requested Texture is cached.
310 const TextureHash textureHash = GenerateHash( url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
311 maskTextureId, preMultiplyOnLoad );
313 TextureManager::TextureId textureId = INVALID_TEXTURE_ID;
315 // Look up the texture by hash. Note: The extra parameters are used in case of a hash collision.
316 int cacheIndex = FindCachedTexture( textureHash, url.GetUrl(), desiredSize, fittingMode, samplingMode, useAtlas,
317 maskTextureId, preMultiplyOnLoad );
319 // Check if the requested Texture exists in the cache.
320 if( cacheIndex != INVALID_CACHE_INDEX )
322 if ( TextureManager::ReloadPolicy::CACHED == reloadPolicy )
324 // Mark this texture being used by another client resource. Forced reload would replace the current texture
325 // without the need for incrementing the reference count.
326 ++( mTextureInfoContainer[ cacheIndex ].referenceCount );
328 textureId = mTextureInfoContainer[ cacheIndex ].textureId;
329 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) Using cached texture id@%d, textureId=%d\n",
330 url.GetUrl().c_str(), observer, cacheIndex, textureId );
333 if( textureId == INVALID_TEXTURE_ID ) // There was no caching, or caching not required
335 // We need a new Texture.
336 textureId = GenerateUniqueTextureId();
337 bool preMultiply = ( preMultiplyOnLoad == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
338 mTextureInfoContainer.push_back( TextureInfo( textureId, maskTextureId, url.GetUrl(),
339 desiredSize, contentScale, fittingMode, samplingMode,
340 false, cropToMask, useAtlas, textureHash, orientationCorrection,
342 cacheIndex = mTextureInfoContainer.size() - 1u;
344 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::RequestLoad( url=%s observer=%p ) New texture, cacheIndex:%d, textureId=%d\n",
345 url.GetUrl().c_str(), observer, cacheIndex, textureId );
348 // The below code path is common whether we are using the cache or not.
349 // The textureInfoIndex now refers to either a pre-existing cached TextureInfo,
350 // or a new TextureInfo just created.
351 TextureInfo& textureInfo( mTextureInfoContainer[ cacheIndex ] );
352 textureInfo.maskTextureId = maskTextureId;
353 textureInfo.storageType = storageType;
354 textureInfo.orientationCorrection = orientationCorrection;
356 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureInfo loadState:%s\n",
357 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
358 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
359 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
360 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
362 // Force reloading of texture by setting loadState unless already loading or cancelled.
363 if ( TextureManager::ReloadPolicy::FORCED == reloadPolicy && TextureManager::LOADING != textureInfo.loadState &&
364 TextureManager::CANCELLED != textureInfo.loadState )
366 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Verbose, "TextureManager::RequestLoad( url=%s observer=%p ) ForcedReload cacheIndex:%d, textureId=%d\n",
367 url.GetUrl().c_str(), observer, cacheIndex, textureId );
368 textureInfo.loadState = TextureManager::NOT_STARTED;
371 // Check if we should add the observer.
372 // Only do this if we have not loaded yet and it will not have loaded by the end of this method.
373 switch( textureInfo.loadState )
375 case TextureManager::LOAD_FAILED: // Failed notifies observer which then stops observing.
376 case TextureManager::NOT_STARTED:
378 LoadTexture( textureInfo );
379 ObserveTexture( textureInfo, observer );
382 case TextureManager::LOADING:
384 ObserveTexture( textureInfo, observer );
387 case TextureManager::UPLOADED:
391 // The Texture has already loaded. The other observers have already been notified.
392 // We need to send a "late" loaded notification for this observer.
393 observer->UploadComplete( true, textureInfo.textureId, textureInfo.textureSet,
394 textureInfo.useAtlas, textureInfo.atlasRect,
395 textureInfo.preMultiplied );
399 case TextureManager::CANCELLED:
401 // A cancelled texture hasn't finished loading yet. Treat as a loading texture
402 // (it's ref count has already been incremented, above)
403 textureInfo.loadState = TextureManager::LOADING;
404 ObserveTexture( textureInfo, observer );
407 case TextureManager::LOAD_FINISHED:
408 case TextureManager::WAITING_FOR_MASK:
409 // Loading has already completed. Do nothing.
413 // Return the TextureId for which this Texture can now be referenced by externally.
417 void TextureManager::Remove( const TextureManager::TextureId textureId )
419 int textureInfoIndex = GetCacheIndexFromId( textureId );
420 if( textureInfoIndex != INVALID_INDEX )
422 TextureInfo& textureInfo( mTextureInfoContainer[ textureInfoIndex ] );
424 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::Remove(%d) cacheIdx:%d loadState:%s\n",
425 textureId, textureInfoIndex,
426 textureInfo.loadState == TextureManager::NOT_STARTED ? "NOT_STARTED" :
427 textureInfo.loadState == TextureManager::LOADING ? "LOADING" :
428 textureInfo.loadState == TextureManager::UPLOADED ? "UPLOADED" :
429 textureInfo.loadState == TextureManager::CANCELLED ? "CANCELLED" : "Unknown" );
431 // Decrement the reference count and check if this is the last user of this Texture.
432 if( --textureInfo.referenceCount <= 0 )
434 // This is the last remove for this Texture.
435 textureInfo.referenceCount = 0;
436 bool removeTextureInfo = false;
438 // If loaded, we can remove the TextureInfo and the Atlas (if atlased).
439 if( textureInfo.loadState == UPLOADED )
441 if( textureInfo.atlas )
443 textureInfo.atlas.Remove( textureInfo.atlasRect );
445 removeTextureInfo = true;
447 else if( textureInfo.loadState == LOADING )
449 // We mark the textureInfo for removal.
450 // Once the load has completed, this method will be called again.
451 textureInfo.loadState = CANCELLED;
455 // In other states, we are not waiting for a load so we are safe to remove the TextureInfo data.
456 removeTextureInfo = true;
459 // If the state allows us to remove the TextureInfo data, we do so.
460 if( removeTextureInfo )
462 // Permanently remove the textureInfo struct.
463 mTextureInfoContainer.erase( mTextureInfoContainer.begin() + textureInfoIndex );
469 const VisualUrl& TextureManager::GetVisualUrl( TextureId textureId )
471 int cacheIndex = GetCacheIndexFromId( textureId );
472 DALI_ASSERT_DEBUG( cacheIndex != INVALID_CACHE_INDEX && "TextureId out of range");
474 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
475 return cachedTextureInfo.url;
478 TextureManager::LoadState TextureManager::GetTextureState( TextureId textureId )
480 LoadState loadState = TextureManager::NOT_STARTED;
482 int cacheIndex = GetCacheIndexFromId( textureId );
483 if( cacheIndex != INVALID_CACHE_INDEX )
485 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
486 loadState = cachedTextureInfo.loadState;
490 for( auto&& elem : mExternalTextures )
492 if( elem.textureId == textureId )
494 loadState = LoadState::UPLOADED;
502 TextureManager::LoadState TextureManager::GetTextureStateInternal( TextureId textureId )
504 LoadState loadState = TextureManager::NOT_STARTED;
506 int cacheIndex = GetCacheIndexFromId( textureId );
507 if( cacheIndex != INVALID_CACHE_INDEX )
509 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
510 loadState = cachedTextureInfo.loadState;
516 TextureSet TextureManager::GetTextureSet( TextureId textureId )
518 TextureSet textureSet;// empty handle
520 int cacheIndex = GetCacheIndexFromId( textureId );
521 if( cacheIndex != INVALID_CACHE_INDEX )
523 TextureInfo& cachedTextureInfo( mTextureInfoContainer[ cacheIndex ] );
524 textureSet = cachedTextureInfo.textureSet;
528 for( auto&& elem : mExternalTextures )
530 if( elem.textureId == textureId )
532 textureSet = elem.textureSet;
540 std::string TextureManager::AddExternalTexture( TextureSet& textureSet )
542 TextureManager::ExternalTextureInfo info;
543 info.textureId = GenerateUniqueTextureId();
544 info.textureSet = textureSet;
545 mExternalTextures.emplace_back( info );
546 return VisualUrl::CreateTextureUrl( std::to_string( info.textureId ) );
549 TextureSet TextureManager::RemoveExternalTexture( const std::string& url )
551 if( url.size() > 0u )
553 // get the location from the Url
554 VisualUrl parseUrl( url );
555 if( VisualUrl::TEXTURE == parseUrl.GetProtocolType() )
557 std::string location = parseUrl.GetLocation();
558 if( location.size() > 0u )
560 TextureId id = std::stoi( location );
561 const auto end = mExternalTextures.end();
562 for( auto iter = mExternalTextures.begin(); iter != end; ++iter )
564 if( iter->textureId == id )
566 auto textureSet = iter->textureSet;
567 mExternalTextures.erase( iter );
577 bool TextureManager::LoadTexture( TextureInfo& textureInfo )
581 if( textureInfo.loadState == NOT_STARTED )
583 textureInfo.loadState = LOADING;
585 if( !textureInfo.loadSynchronously )
587 auto& loadersContainer = textureInfo.url.IsLocalResource() ? mAsyncLocalLoaders : mAsyncRemoteLoaders;
588 auto loadingHelperIt = loadersContainer.GetNext();
589 DALI_ASSERT_ALWAYS(loadingHelperIt != loadersContainer.End());
590 loadingHelperIt->Load(textureInfo.textureId, textureInfo.url,
591 textureInfo.desiredSize, textureInfo.fittingMode,
592 textureInfo.samplingMode, textureInfo.orientationCorrection );
599 void TextureManager::ObserveTexture( TextureInfo& textureInfo,
600 TextureUploadObserver* observer )
604 textureInfo.observerList.PushBack( observer );
605 observer->DestructionSignal().Connect( this, &TextureManager::ObserverDestroyed );
609 void TextureManager::AsyncLoadComplete( AsyncLoadingInfoContainerType& loadingContainer, uint32_t id,
610 Devel::PixelBuffer pixelBuffer )
612 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, "TextureManager::AsyncLoadComplete( id:%d )\n", id );
614 if( loadingContainer.size() >= 1u )
616 AsyncLoadingInfo loadingInfo = loadingContainer.front();
618 if( loadingInfo.loadId == id )
620 int cacheIndex = GetCacheIndexFromId( loadingInfo.textureId );
621 if( cacheIndex != INVALID_CACHE_INDEX )
623 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
625 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " CacheIndex:%d LoadState: %d\n", cacheIndex, textureInfo.loadState );
627 if( textureInfo.loadState != CANCELLED )
629 // textureInfo can be invalidated after this call (as the mTextureInfoContainer may be modified)
630 PostLoad( textureInfo, pixelBuffer );
634 Remove( textureInfo.textureId );
639 loadingContainer.pop_front();
643 void TextureManager::PostLoad( TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer )
645 // Was the load successful?
646 if( pixelBuffer && ( pixelBuffer.GetWidth() != 0 ) && ( pixelBuffer.GetHeight() != 0 ) )
648 // No atlas support for now
649 textureInfo.useAtlas = NO_ATLAS;
651 if( textureInfo.storageType == UPLOAD_TO_TEXTURE )
653 // If there is a mask texture ID associated with this texture, then apply the mask
654 // if it's already loaded. If it hasn't, and the mask is still loading,
655 // wait for the mask to finish loading.
656 if( textureInfo.maskTextureId != INVALID_TEXTURE_ID )
658 LoadState maskLoadState = GetTextureStateInternal( textureInfo.maskTextureId );
659 if( maskLoadState == LOADING )
661 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel buffer temporarily
662 textureInfo.loadState = WAITING_FOR_MASK;
664 else if( maskLoadState == LOAD_FINISHED )
666 ApplyMask( pixelBuffer, textureInfo.maskTextureId, textureInfo.scaleFactor, textureInfo.cropToMask );
667 UploadTexture( pixelBuffer, textureInfo );
668 NotifyObservers( textureInfo, true );
673 UploadTexture( pixelBuffer, textureInfo );
674 NotifyObservers( textureInfo, true );
679 textureInfo.pixelBuffer = pixelBuffer; // Store the pixel data
680 textureInfo.loadState = LOAD_FINISHED;
682 // Check if there was another texture waiting for this load to complete
683 // (e.g. if this was an image mask, and its load is on a different thread)
684 CheckForWaitingTexture( textureInfo );
689 DALI_LOG_ERROR( "TextureManager::AsyncImageLoad(%s) failed\n", textureInfo.url.GetUrl().c_str() );
690 // @todo If the load was unsuccessful, upload the broken image.
691 textureInfo.loadState = LOAD_FAILED;
692 CheckForWaitingTexture( textureInfo );
693 NotifyObservers( textureInfo, false );
697 void TextureManager::CheckForWaitingTexture( TextureInfo& maskTextureInfo )
699 // Search the cache, checking if any texture has this texture id as a
701 const unsigned int size = mTextureInfoContainer.size();
703 for( unsigned int cacheIndex = 0; cacheIndex < size; ++cacheIndex )
705 if( mTextureInfoContainer[cacheIndex].maskTextureId == maskTextureInfo.textureId &&
706 mTextureInfoContainer[cacheIndex].loadState == WAITING_FOR_MASK )
708 TextureInfo& textureInfo( mTextureInfoContainer[cacheIndex] );
709 Devel::PixelBuffer pixelBuffer = textureInfo.pixelBuffer;
710 textureInfo.pixelBuffer.Reset();
712 if( maskTextureInfo.loadState == LOAD_FINISHED )
714 ApplyMask( pixelBuffer, maskTextureInfo.textureId, textureInfo.scaleFactor, textureInfo.cropToMask );
715 UploadTexture( pixelBuffer, textureInfo );
716 NotifyObservers( textureInfo, true );
720 DALI_LOG_ERROR( "TextureManager::ApplyMask to %s failed\n", textureInfo.url.GetUrl().c_str() );
721 textureInfo.loadState = LOAD_FAILED;
722 NotifyObservers( textureInfo, false );
728 void TextureManager::ApplyMask(
729 Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
730 float contentScale, bool cropToMask )
732 int maskCacheIndex = GetCacheIndexFromId( maskTextureId );
733 Devel::PixelBuffer maskPixelBuffer = mTextureInfoContainer[maskCacheIndex].pixelBuffer;
734 pixelBuffer.ApplyMask( maskPixelBuffer, contentScale, cropToMask );
738 void TextureManager::UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo )
740 if( textureInfo.useAtlas != USE_ATLAS )
742 DALI_LOG_INFO( gTextureManagerLogFilter, Debug::Concise, " TextureManager::UploadTexture() New Texture for textureId:%d\n", textureInfo.textureId );
744 // If the texture doesn't have an alpha channel, can't pre-multiply it.
745 // Ensure that we don't change the load parameter (it's used for hashing), and instead set
746 // the status for use in the observer.
747 auto preMultiply = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
748 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
749 PreMultiply( pixelBuffer, preMultiply );
750 textureInfo.preMultiplied = (preMultiply == TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD );
752 Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, pixelBuffer.GetPixelFormat(),
753 pixelBuffer.GetWidth(), pixelBuffer.GetHeight() );
755 PixelData pixelData = Devel::PixelBuffer::Convert( pixelBuffer );
756 texture.Upload( pixelData );
757 if ( ! textureInfo.textureSet )
759 textureInfo.textureSet = TextureSet::New();
761 textureInfo.textureSet.SetTexture( 0u, texture );
764 // Update the load state.
765 // Note: This is regardless of success as we care about whether a
766 // load attempt is in progress or not. If unsuccessful, a broken
767 // image is still loaded.
768 textureInfo.loadState = UPLOADED;
771 void TextureManager::NotifyObservers( TextureInfo& textureInfo, bool success )
773 TextureId textureId = textureInfo.textureId;
775 // If there is an observer: Notify the load is complete, whether successful or not,
776 // and erase it from the list
777 unsigned int observerCount = textureInfo.observerList.Count();
778 TextureInfo* info = &textureInfo;
780 while( observerCount )
782 TextureUploadObserver* observer = info->observerList[0];
784 // During UploadComplete() a Control ResourceReady() signal is emitted.
785 // During that signal the app may add remove /add Textures (e.g. via
786 // ImageViews). At this point no more observers can be added to the
787 // observerList, because textureInfo.loadState = UPLOADED. However it is
788 // possible for observers to be removed, hence we check the observer list
789 // count every iteration.
791 // The reference to the textureInfo struct can also become invalidated,
792 // because new load requests can modify the mTextureInfoContainer list
793 // (e.g. if more requests are pushed back it can cause the list to be
794 // resized invalidating the reference to the TextureInfo ).
795 observer->UploadComplete( success, info->textureId, info->textureSet, info->useAtlas, info->atlasRect,
796 info->preMultiplied );
797 observer->DestructionSignal().Disconnect( this, &TextureManager::ObserverDestroyed );
799 // Get the textureInfo from the container again as it may have been
802 int textureInfoIndex = GetCacheIndexFromId( textureId );
803 if( textureInfoIndex == INVALID_CACHE_INDEX)
805 return; // texture has been removed - can stop.
808 info = &mTextureInfoContainer[ textureInfoIndex ];
809 observerCount = info->observerList.Count();
810 if ( observerCount > 0 )
812 // remove the observer that was just triggered if it's still in the list
813 for( TextureInfo::ObserverListType::Iterator j = info->observerList.Begin(); j != info->observerList.End(); ++j )
817 info->observerList.Erase( j );
826 TextureManager::TextureId TextureManager::GenerateUniqueTextureId()
828 return mCurrentTextureId++;
831 int TextureManager::GetCacheIndexFromId( const TextureId textureId )
833 const unsigned int size = mTextureInfoContainer.size();
835 for( unsigned int i = 0; i < size; ++i )
837 if( mTextureInfoContainer[i].textureId == textureId )
843 return INVALID_CACHE_INDEX;
846 TextureManager::TextureHash TextureManager::GenerateHash(
847 const std::string& url,
848 const ImageDimensions size,
849 const FittingMode::Type fittingMode,
850 const Dali::SamplingMode::Type samplingMode,
851 const UseAtlas useAtlas,
852 TextureId maskTextureId,
853 TextureManager::MultiplyOnLoad preMultiplyOnLoad)
855 std::string hashTarget( url );
856 const size_t urlLength = hashTarget.length();
857 const uint16_t width = size.GetWidth();
858 const uint16_t height = size.GetWidth();
860 // If either the width or height has been specified, include the resizing options in the hash
861 if( width != 0 || height != 0 )
863 // We are appending 5 bytes to the URL to form the hash input.
864 hashTarget.resize( urlLength + 5u );
865 char* hashTargetPtr = &( hashTarget[ urlLength ] );
867 // Pack the width and height (4 bytes total).
868 *hashTargetPtr++ = size.GetWidth() & 0xff;
869 *hashTargetPtr++ = ( size.GetWidth() >> 8u ) & 0xff;
870 *hashTargetPtr++ = size.GetHeight() & 0xff;
871 *hashTargetPtr++ = ( size.GetHeight() >> 8u ) & 0xff;
873 // Bit-pack the FittingMode, SamplingMode and atlasing.
874 // FittingMode=2bits, SamplingMode=3bits, useAtlas=1bit
875 *hashTargetPtr = ( fittingMode << 4u ) | ( samplingMode << 1 ) | useAtlas;
879 // We are not including sizing information, but we still need an extra byte for atlasing.
880 hashTarget.resize( urlLength + 1u );
881 // Add the atlasing to the hash input.
882 hashTarget[ urlLength ] = useAtlas;
885 if( maskTextureId != INVALID_TEXTURE_ID )
887 auto textureIdIndex = hashTarget.length();
888 hashTarget.resize( hashTarget.length() + sizeof( TextureId ) );
889 unsigned char* hashTargetPtr = reinterpret_cast<unsigned char*>(&( hashTarget[ textureIdIndex ] ));
891 // Append the texture id to the end of the URL byte by byte:
892 // (to avoid SIGBUS / alignment issues)
893 for( size_t byteIter = 0; byteIter < sizeof( TextureId ); ++byteIter )
895 *hashTargetPtr++ = maskTextureId & 0xff;
896 maskTextureId >>= 8u;
900 auto premultipliedIndex = hashTarget.length();
901 hashTarget.resize( premultipliedIndex + 1 );
902 switch( preMultiplyOnLoad )
904 case TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD:
906 hashTarget[ premultipliedIndex ] = 't';
909 case TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY:
911 hashTarget[ premultipliedIndex ] = 'f';
916 return Dali::CalculateHash( hashTarget );
919 int TextureManager::FindCachedTexture(
920 const TextureManager::TextureHash hash,
921 const std::string& url,
922 const ImageDimensions size,
923 const FittingMode::Type fittingMode,
924 const Dali::SamplingMode::Type samplingMode,
926 TextureId maskTextureId,
927 TextureManager::MultiplyOnLoad preMultiplyOnLoad )
929 // Default to an invalid ID, in case we do not find a match.
930 int cacheIndex = INVALID_CACHE_INDEX;
932 // Iterate through our hashes to find a match.
933 const unsigned int count = mTextureInfoContainer.size();
934 for( unsigned int i = 0u; i < count; ++i )
936 if( mTextureInfoContainer[i].hash == hash )
938 // We have a match, now we check all the original parameters in case of a hash collision.
939 TextureInfo& textureInfo( mTextureInfoContainer[i] );
940 auto multiplyOnLoad = textureInfo.preMultiplyOnLoad ? TextureManager::MultiplyOnLoad::MULTIPLY_ON_LOAD :
941 TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
943 if( ( url == textureInfo.url.GetUrl() ) &&
944 ( useAtlas == textureInfo.useAtlas ) &&
945 ( maskTextureId == textureInfo.maskTextureId ) &&
946 ( size == textureInfo.desiredSize ) &&
947 ( preMultiplyOnLoad == multiplyOnLoad ) &&
948 ( ( size.GetWidth() == 0 && size.GetHeight() == 0 ) ||
949 ( fittingMode == textureInfo.fittingMode &&
950 samplingMode == textureInfo.samplingMode ) ) )
952 // The found Texture is a match.
962 void TextureManager::ObserverDestroyed( TextureUploadObserver* observer )
964 const unsigned int count = mTextureInfoContainer.size();
965 for( unsigned int i = 0; i < count; ++i )
967 TextureInfo& textureInfo( mTextureInfoContainer[i] );
968 for( TextureInfo::ObserverListType::Iterator j = textureInfo.observerList.Begin();
969 j != textureInfo.observerList.End(); )
973 j = textureInfo.observerList.Erase( j );
984 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(TextureManager& textureManager)
985 : AsyncLoadingHelper(Toolkit::AsyncImageLoader::New(), textureManager,
986 AsyncLoadingInfoContainerType())
990 void TextureManager::AsyncLoadingHelper::Load(TextureId textureId,
991 const VisualUrl& url,
992 ImageDimensions desiredSize,
993 FittingMode::Type fittingMode,
994 SamplingMode::Type samplingMode,
995 bool orientationCorrection)
997 mLoadingInfoContainer.push_back(AsyncLoadingInfo(textureId));
998 auto id = mLoader.Load(url.GetUrl(), desiredSize, fittingMode, samplingMode, orientationCorrection);
999 mLoadingInfoContainer.back().loadId = id;
1002 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(AsyncLoadingHelper&& rhs)
1003 : AsyncLoadingHelper(rhs.mLoader, rhs.mTextureManager, std::move(rhs.mLoadingInfoContainer))
1007 TextureManager::AsyncLoadingHelper::AsyncLoadingHelper(
1008 Toolkit::AsyncImageLoader loader,
1009 TextureManager& textureManager,
1010 AsyncLoadingInfoContainerType&& loadingInfoContainer)
1012 mTextureManager(textureManager),
1013 mLoadingInfoContainer(std::move(loadingInfoContainer))
1015 DevelAsyncImageLoader::PixelBufferLoadedSignal(mLoader).Connect(
1016 this, &AsyncLoadingHelper::AsyncLoadComplete);
1019 void TextureManager::AsyncLoadingHelper::AsyncLoadComplete(uint32_t id,
1020 Devel::PixelBuffer pixelBuffer)
1022 mTextureManager.AsyncLoadComplete(mLoadingInfoContainer, id, pixelBuffer);
1025 } // namespace Internal
1027 } // namespace Toolkit