5b6a98e010baca79f04e4fb39d2c371c67d861c1
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / texture-manager-impl.h
1 #ifndef DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H
2 #define DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H
3
4 /*
5  * Copyright (c) 2017 Samsung Electronics Co., Ltd.
6  *
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  * http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  */
19
20 // EXTERNAL INCLUDES
21 #include <deque>
22 #include <functional>
23 #include <string>
24 #include <memory>
25 #include <dali/public-api/common/dali-vector.h>
26 #include <dali/public-api/object/ref-object.h>
27 #include <dali/public-api/rendering/texture-set.h>
28 #include <dali/devel-api/common/owner-container.h>
29 #include <dali/devel-api/adaptor-framework/pixel-buffer.h>
30
31 // INTERNAL INCLUDES
32 #include <dali-toolkit/devel-api/image-loader/async-image-loader-devel.h>
33 #include <dali-toolkit/devel-api/image-loader/image-atlas.h>
34 #include <dali-toolkit/public-api/image-loader/async-image-loader.h>
35 #include <dali-toolkit/internal/visuals/texture-upload-observer.h>
36 #include <dali-toolkit/internal/visuals/visual-url.h>
37 #include <dali-toolkit/internal/helpers/round-robin-container-view.h>
38 #include <dali-toolkit/internal/image-loader/async-image-loader-impl.h>
39
40
41 namespace Dali
42 {
43
44 namespace Toolkit
45 {
46
47 namespace Internal
48 {
49 class ImageAtlasManager;
50 typedef IntrusivePtr<ImageAtlasManager> ImageAtlasManagerPtr;
51
52 /**
53  * The TextureManager provides a common Image loading API for Visuals.
54  *
55  * The TextureManager is responsible for providing sync, async, atlased and non-atlased loads.
56  * Texture caching is provided and performed when possible.
57  * Broken Images are automatically provided on load failure.
58  */
59 class TextureManager : public ConnectionTracker
60 {
61 public:
62
63   typedef int32_t TextureId;       ///< The TextureId type. This is used as a handle to refer to a particular Texture.
64   static const int INVALID_TEXTURE_ID = -1; ///< Used to represent a null TextureId or error
65
66   /**
67    * Whether the texture should be atlased or uploaded into it's own GPU texture
68    */
69   enum UseAtlas
70   {
71     NO_ATLAS,
72     USE_ATLAS
73   };
74
75   /**
76    * Whether the pixel data should be kept in TextureManager, or uploaded for rendering
77    */
78   enum StorageType
79   {
80     KEEP_PIXEL_BUFFER,
81     UPLOAD_TO_TEXTURE
82   };
83
84   /**
85    * Whether the texture should be loaded synchronously or asynchronously.
86    */
87   enum LoadType
88   {
89     LOAD_ASYNCHRONOUSLY,
90     LOAD_SYNCHRONOUSLY
91   };
92
93   /**
94    * @brief The LoadState Enumeration represents the current state of a particular Texture's life-cycle.
95    */
96   enum LoadState
97   {
98     NOT_STARTED,     ///< Default
99     LOADING,         ///< Loading has been started, but not finished.
100     LOAD_FINISHED,   ///< Loading has finished. (for CPU storage only)
101     WAITING_FOR_MASK,///< Loading has finished, but waiting for mask image
102     UPLOADED,        ///< Uploaded and ready. (For GPU upload only)
103     CANCELLED,       ///< Removed before loading completed
104     LOAD_FAILED      ///< Async loading failed, e.g. connection problem
105   };
106
107   /**
108    * @brief Types of reloading policies
109    */
110   enum class ReloadPolicy
111   {
112     CACHED = 0,             ///< Loads cached texture if it exists.
113     FORCED                  ///< Forces reloading of texture.
114   };
115
116   /**
117    * @brief Whether to multiply alpha into color channels on load
118    */
119   enum class MultiplyOnLoad
120   {
121     LOAD_WITHOUT_MULTIPLY = 0, ///< Don't modify the image
122     MULTIPLY_ON_LOAD           ///< Multiply alpha into color channels on load
123   };
124
125 public:
126
127   struct MaskingData
128   {
129     MaskingData();
130     ~MaskingData() = default;
131
132     VisualUrl mAlphaMaskUrl;
133     TextureManager::TextureId mAlphaMaskId;
134     float mContentScaleFactor;
135     bool mCropToMask;
136   };
137   using MaskingDataPointer = std::unique_ptr<MaskingData>;
138
139   /**
140    * Constructor.
141    */
142   TextureManager();
143
144   /**
145    * Destructor.
146    */
147   ~TextureManager() = default;
148
149
150   // TextureManager Main API:
151
152   /**
153    * @brief Requests an image load of the given URL.
154    *
155    * The parameters are used to specify how the image is loaded.
156    * The observer has the UploadComplete method called when the load is ready.
157    *
158    * When the client has finished with the Texture, Remove() should be called.
159    *
160    * @param[in] url                   The URL of the image to load
161    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
162    * @param[in] fittingMode           The FittingMode to use
163    * @param[in] samplingMode          The SamplingMode to use
164    * @param[in] maskInfo              Mask info structure
165    * @param[in] synchronousLoading    true if the URL should be loaded synchronously
166    * @param[out] textureId,           The textureId of the URL
167    * @param[out] textureRect          The rectangle within the texture atlas that this URL occupies
168    * @param[in,out] atlasingStatus    Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still
169    *                                  be loaded, and marked successful, but this will be set to false.
170    *                                  If atlasing succeeds, this will be set to true.
171    * @param[out] loadingStatus        The loading status of the texture
172    * @param[in] wrapModeU             Horizontal Wrap mode
173    * @param[in] wrapModeV             Vertical Wrap mode
174    * @param[in] textureObserver       The client object should inherit from this and provide the "UploadCompleted" virtual.
175    *                                  This is called when an image load completes (or fails).
176    * @param[in] atlasObserver         This is used if the texture is atlased, and will be called instead of
177    *                                  textureObserver.UploadCompleted
178    * @param[in] imageAtlasManager     The atlas manager to use for atlasing textures
179    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
180    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
181    * @param[in,out] preMultiplyOnLoad True if the image color should be multiplied by it's alpha. Set to false if the
182    *                                  image has no alpha channel
183    *
184    * @return                          The texture set containing the image, or empty if still loading.
185    */
186
187   TextureSet LoadTexture( const VisualUrl&             url,
188                           Dali::ImageDimensions        desiredSize,
189                           Dali::FittingMode::Type      fittingMode,
190                           Dali::SamplingMode::Type     samplingMode,
191                           const MaskingDataPointer&    maskInfo,
192                           bool                         synchronousLoading,
193                           TextureManager::TextureId&   textureId,
194                           Vector4&                     textureRect,
195                           bool&                        atlasingStatus,
196                           bool&                        loadingStatus,
197                           Dali::WrapMode::Type         wrapModeU,
198                           Dali::WrapMode::Type         wrapModeV,
199                           TextureUploadObserver*       textureObserver,
200                           AtlasUploadObserver*         atlasObserver,
201                           ImageAtlasManagerPtr         imageAtlasManager,
202                           bool                         orientationCorrection,
203                           TextureManager::ReloadPolicy reloadPolicy,
204                           MultiplyOnLoad&              preMultiplyOnLoad );
205
206   /**
207    * @brief Requests an image load of the given URL.
208    *
209    * The parameters are used to specify how the image is loaded.
210    * The observer has the UploadComplete method called when the load is ready.
211    *
212    * When the client has finished with the Texture, Remove() should be called.
213    *
214    * @param[in] url                   The URL of the image to load
215    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
216    * @param[in] fittingMode           The FittingMode to use
217    * @param[in] samplingMode          The SamplingMode to use
218    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still be loaded, and marked successful,
219    *                                  but "useAtlasing" will be set to false in the "UploadCompleted" callback from the TextureManagerUploadObserver.
220    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted" virtual.
221    *                                  This is called when an image load completes (or fails).
222    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
223    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
224    * @param[in,out] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if the image has no alpha channel
225    * @return                          A TextureId to use as a handle to reference this Texture
226    */
227   TextureId RequestLoad( const VisualUrl&                   url,
228                          const ImageDimensions              desiredSize,
229                          FittingMode::Type                  fittingMode,
230                          Dali::SamplingMode::Type           samplingMode,
231                          const UseAtlas                     useAtlasing,
232                          TextureUploadObserver*             observer,
233                          bool                               orientationCorrection,
234                          TextureManager::ReloadPolicy       reloadPolicy,
235                          MultiplyOnLoad&                    preMultiplyOnLoad );
236
237   /**
238    * @brief Requests an image load of the given URL, when the texture has
239    * have loaded, it will perform a blend with the image mask, and upload
240    * the blended texture.
241    *
242    * The parameters are used to specify how the image is loaded.
243    * The observer has the UploadComplete method called when the load is ready.
244    *
245    * When the client has finished with the Texture, Remove() should be called.
246    *
247    * @param[in] url                   The URL of the image to load
248    * @param[in] maskTextureId         The texture id of an image to mask this with
249    *                                  (can be INVALID if no masking required)
250    * @param[in] contentScale          The scale factor to apply to the image before masking
251    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
252    * @param[in] fittingMode           The FittingMode to use
253    * @param[in] samplingMode          The SamplingMode to use
254    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still
255    *                                  be loaded, and marked successful,
256    *                                  but "useAtlasing" will be set to false in the "UploadCompleted" callback from
257    *                                  the TextureManagerUploadObserver.
258    * @param[in] cropToMask            Only used with masking, this will crop the scaled image to the mask size.
259    *                                  If false, then the mask will be scaled to fit the image before being applied.
260    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted"
261    *                                  virtual.
262    *                                  This is called when an image load completes (or fails).
263    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
264    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
265    * @param[in] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if the
266    *                                  image has no alpha channel
267    * @return                          A TextureId to use as a handle to reference this Texture
268    */
269   TextureId RequestLoad( const VisualUrl&                   url,
270                          TextureId                          maskTextureId,
271                          float                              contentScale,
272                          const ImageDimensions              desiredSize,
273                          FittingMode::Type                  fittingMode,
274                          Dali::SamplingMode::Type           samplingMode,
275                          const UseAtlas                     useAtlasing,
276                          bool                               cropToMask,
277                          TextureUploadObserver*             observer,
278                          bool                               orientationCorrection,
279                          TextureManager::ReloadPolicy       reloadPolicy,
280                          MultiplyOnLoad&                    preMultiplyOnLoad );
281
282   /**
283    * Requests a masking image to be loaded. This mask is not uploaded to GL,
284    * instead, it is stored in CPU memory, and can be used for CPU blending.
285    */
286   TextureId RequestMaskLoad( const VisualUrl& maskUrl );
287
288   /**
289    * @brief Remove a Texture from the TextureManager.
290    *
291    * Textures are cached and therefore only the removal of the last
292    * occurrence of a Texture will cause its removal internally.
293    *
294    * @param[in] textureId The ID of the Texture to remove.
295    */
296   void Remove( const TextureManager::TextureId textureId );
297
298   /**
299    * Get the visualUrl associated with the texture id
300    */
301   const VisualUrl& GetVisualUrl( TextureId textureId );
302
303   /**
304    * @brief Get the current state of a texture
305    * @param[in] textureId The texture id to query
306    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
307    * is not valid.
308    */
309   LoadState GetTextureState( TextureId textureId );
310
311   /**
312    * @brief Get the associated texture set if the texture id is valid
313    * @param[in] textureId The texture Id to look up
314    * @return the associated texture set, or an empty handle if textureId is not valid
315    */
316   TextureSet GetTextureSet( TextureId textureId );
317
318   /**
319    * Adds an external texture to the texture manager
320    * @param[in] texture The texture to add
321    * @return string containing the URL for the texture
322    */
323   std::string AddExternalTexture( TextureSet& texture );
324
325   /**
326    * Removes an external texture from texture manager
327    * @param[in] url The string containing the texture to remove
328    * @return handle to the texture
329    */
330   TextureSet RemoveExternalTexture( const std::string& url );
331
332 private:
333
334   /**
335    * @brief Requests an image load of the given URL, when the texture has
336    * have loaded, if there is a valid maskTextureId, it will perform a
337    * CPU blend with the mask, and upload the blend texture.
338    *
339    * The parameters are used to specify how the image is loaded.
340    * The observer has the UploadComplete method called when the load is ready.
341    *
342    * When the client has finished with the Texture, Remove() should be called.
343    *
344    * @param[in] url                   The URL of the image to load
345    * @param[in] maskTextureId         The texture id of an image to use as a mask. If no mask is required, then set
346    *                                  to INVALID_TEXTURE_ID
347    * @param[in] contentScale          The scaling factor to apply to the content when masking
348    * @param[in] desiredSize           The size the image is likely to appear at. This can be set to 0,0 for automatic
349    * @param[in] fittingMode           The FittingMode to use
350    * @param[in] samplingMode          The SamplingMode to use
351    * @param[in] useAtlasing           Set to USE_ATLAS to attempt atlasing. If atlasing fails, the image will still be
352    *                                  loaded, and marked successful, but "useAtlasing" will be set to false in the
353    *                                  "UploadCompleted" callback from the TextureManagerUploadObserver.
354    * @param[in] cropToMask            Whether to crop the target after masking, or scale the mask to the image before
355    *                                  masking.
356    * @param[in] storageType,          Whether the pixel data is stored in the cache or uploaded to the GPU
357    * @param[in] observer              The client object should inherit from this and provide the "UploadCompleted"
358    *                                  virtual.
359    *                                  This is called when an image load completes (or fails).
360    * @param[in] orientationCorrection Whether to rotate image to match embedded orientation data
361    * @param[in] reloadPolicy          Forces a reload of the texture even if already cached
362    * @param[in] preMultiplyOnLoad     True if the image color should be multiplied by it's alpha. Set to false if
363    *                                  there is no alpha
364    * @return                          A TextureId to use as a handle to reference this Texture
365    */
366   TextureId RequestLoadInternal(
367     const VisualUrl&                    url,
368     TextureId                           maskTextureId,
369     float                               contentScale,
370     const ImageDimensions               desiredSize,
371     FittingMode::Type                   fittingMode,
372     Dali::SamplingMode::Type            samplingMode,
373     UseAtlas                            useAtlas,
374     bool                                cropToMask,
375     StorageType                         storageType,
376     TextureUploadObserver*              observer,
377     bool                                orientationCorrection,
378     TextureManager::ReloadPolicy        reloadPolicy,
379     MultiplyOnLoad&                     preMultiplyOnLoad );
380
381   /**
382    * @brief Get the current state of a texture
383    * @param[in] textureId The texture id to query
384    * @return The loading state if the texture is valid, or NOT_STARTED if the textureId
385    * is not valid.
386    */
387   LoadState GetTextureStateInternal( TextureId textureId );
388
389   typedef size_t TextureHash; ///< The type used to store the hash used for Texture caching.
390
391   /**
392    * @brief This struct is used to manage the life-cycle of Texture loading and caching.
393    */
394   struct TextureInfo
395   {
396     TextureInfo( TextureId textureId,
397                  TextureId maskTextureId,
398                  const VisualUrl& url,
399                  ImageDimensions desiredSize,
400                  float scaleFactor,
401                  FittingMode::Type fittingMode,
402                  Dali::SamplingMode::Type samplingMode,
403                  bool loadSynchronously,
404                  bool cropToMask,
405                  UseAtlas useAtlas,
406                  TextureManager::TextureHash hash,
407                  bool orientationCorrection,
408                  bool preMultiplyOnLoad )
409     : url( url ),
410       desiredSize( desiredSize ),
411       useSize( desiredSize ),
412       atlasRect( 0.0f, 0.0f, 1.0f, 1.0f ), // Full atlas rectangle
413       textureId( textureId ),
414       maskTextureId( maskTextureId ),
415       hash( hash ),
416       scaleFactor( scaleFactor ),
417       referenceCount( 1u ),
418       loadState( NOT_STARTED ),
419       fittingMode( fittingMode ),
420       samplingMode( samplingMode ),
421       storageType( UPLOAD_TO_TEXTURE ),
422       loadSynchronously( loadSynchronously ),
423       useAtlas( useAtlas ),
424       cropToMask( cropToMask ),
425       orientationCorrection( true ),
426       preMultiplyOnLoad( preMultiplyOnLoad ),
427       preMultiplied( false )
428     {
429     }
430
431     /**
432      * Container type used to store all observer clients of this Texture
433      */
434     typedef Dali::Vector< TextureUploadObserver* > ObserverListType;
435
436     ObserverListType observerList; ///< Container used to store all observer clients of this Texture
437     Toolkit::ImageAtlas atlas;     ///< The atlas this Texture lays within (if any)
438     Devel::PixelBuffer pixelBuffer;///< The PixelBuffer holding the image data (May be empty after upload)
439     TextureSet textureSet;         ///< The TextureSet holding the Texture
440     VisualUrl url;                 ///< The URL of the image
441     ImageDimensions desiredSize;   ///< The size requested
442     ImageDimensions useSize;       ///< The size used
443     Vector4 atlasRect;             ///< The atlas rect used if atlased
444     TextureId textureId;           ///< The TextureId associated with this Texture
445     TextureId maskTextureId;       ///< The mask TextureId to be applied on load
446     TextureManager::TextureHash hash; ///< The hash used to cache this Texture
447     float scaleFactor;             ///< The scale factor to apply to the Texture when masking
448     int16_t referenceCount;        ///< The reference count of clients using this Texture
449     LoadState loadState:3;         ///< The load state showing the load progress of the Texture
450     FittingMode::Type fittingMode:2; ///< The requested FittingMode
451     Dali::SamplingMode::Type samplingMode:3; ///< The requested SamplingMode
452     StorageType storageType:1;     ///< CPU storage / GPU upload;
453     bool loadSynchronously:1;      ///< True if synchronous loading was requested
454     UseAtlas useAtlas:1;           ///< USE_ATLAS if an atlas was requested.
455                                    ///< This is updated to false if atlas is not used
456     bool cropToMask:1;             ///< true if the image should be cropped to the mask size.
457     bool orientationCorrection:1;  ///< true if the image should be rotated to match exif orientation data
458     bool preMultiplyOnLoad:1;      ///< true if the image's color should be multiplied by it's alpha
459     bool preMultiplied:1;          ///< true if the image's color was multiplied by it's alpha
460   };
461
462   // Structs:
463
464   /**
465    * Struct to hold information about a requested Async load.
466    * This is used to look up a TextureManager::TextureId from the returned AsyncLoad Id.
467    */
468   struct AsyncLoadingInfo
469   {
470     AsyncLoadingInfo( TextureId textureId )
471     : textureId( textureId ),
472       loadId( 0 )
473     {
474     }
475
476     TextureId           textureId;   ///< The external Texture Id assigned to this load
477     uint32_t            loadId;      ///< The load Id used by the async loader to reference this load
478   };
479
480   // Private typedefs:
481
482   typedef std::deque<AsyncLoadingInfo>  AsyncLoadingInfoContainerType;  ///< The container type used to manage Asynchronous loads in progress
483   typedef std::vector<TextureInfo>      TextureInfoContainerType;       ///< The container type used to manage the life-cycle and caching of Textures
484
485   /**
486    * @brief Used internally to initiate a load.
487    * @param[in] textureInfo The TextureInfo struct associated with the Texture
488    * @return                True if the load was initiated
489    */
490   bool LoadTexture( TextureInfo& textureInfo );
491
492   /**
493    * Add the observer to the observer list
494    * @param[in] textureInfo The TextureInfo struct associated with the texture
495    * observer The observer wishing to observe the texture upload
496    */
497   void ObserveTexture( TextureInfo & textureInfo, TextureUploadObserver* observer );
498
499   /**
500    * @brief This signal handler is called when the async local loader finishes loading.
501    * @param[in] id        This is the async image loaders Id
502    * @param[in] pixelBuffer The loaded image data
503    */
504   void AsyncLocalLoadComplete( uint32_t id, Devel::PixelBuffer pixelBuffer );
505
506   /**
507    * @brief This signal handler is called when the async local loader finishes loading.
508    * @param[in] id        This is the async image loaders Id
509    * @param[in] pixelBuffer The loaded image data
510    */
511   void AsyncRemoteLoadComplete( uint32_t id, Devel::PixelBuffer pixelBuffer );
512
513   /**
514    * Common method to handle loading completion
515    * @param[in] container The Async loading container
516    * @param[in] id        This is the async image loaders Id
517    * @param[in] pixelBuffer The loaded image data
518    */
519   void AsyncLoadComplete( AsyncLoadingInfoContainerType& container, uint32_t id, Devel::PixelBuffer pixelBuffer );
520
521   /**
522    * @brief Performs Post-Load steps including atlasing.
523    * @param[in] textureInfo The struct associated with this Texture
524    * @param[in] pixelBuffer The image pixelBuffer
525    * @return    True if successful
526    */
527   void PostLoad( TextureManager::TextureInfo& textureInfo, Devel::PixelBuffer& pixelBuffer );
528
529   /**
530    * Check if there is a texture waiting to be masked. If there
531    * is then apply this mask and upload it.
532    * @param[in] maskTextureInfo The texture info of the mask that has just loaded.
533    */
534   void CheckForWaitingTexture( TextureInfo& maskTextureInfo );
535
536   /**
537    * Apply the mask to the pixelBuffer.
538    * @param[in] pixelBuffer The pixelBuffer to apply the mask to
539    * @param[in] maskTextureId The texture id of the mask.
540    * @param[in] contentScale The factor to scale the content
541    * @param[in] cropToMask Whether to crop the content to the mask size
542    */
543   void ApplyMask( Devel::PixelBuffer& pixelBuffer, TextureId maskTextureId,
544                   float contentScale, bool cropToMask );
545
546   /**
547    * Upload the texture specified in pixelBuffer to the appropriate location
548    * @param[in] pixelBuffer The image data to upload
549    * @param[in] textureInfo The texture info containing the location to
550    * store the data to.
551    */
552   void UploadTexture( Devel::PixelBuffer& pixelBuffer, TextureInfo& textureInfo );
553
554   /**
555    * Mark the texture as complete, and inform observers
556    * @param[in] textureInfo The struct associated with this Texture
557    */
558   void UploadComplete( TextureInfo& textureInfo );
559
560   /**
561    * Notify the current observers that the texture upload is complete,
562    * then remove the observers from the list.
563    * @param[in] textureInfo The struct associated with this Texture
564    * @param[in] success If the pixel data was retrieved successfully and uploaded to GPU
565    */
566   void NotifyObservers( TextureInfo& textureInfo, bool success );
567
568   /**
569    * @brief Generates a new, unique TextureId
570    * @return A unique TextureId
571    */
572   TextureManager::TextureId GenerateUniqueTextureId();
573
574   /**
575    * @brief Used to lookup an index into the TextureInfoContainer from a TextureId
576    * @param[in] textureId The TextureId to look up
577    * @return              The cache index
578    */
579   int GetCacheIndexFromId( TextureId textureId );
580
581
582   /**
583    * @brief Generates a hash for caching based on the input parameters.
584    * Only applies size, fitting mode andsampling mode if the size is specified.
585    * Only applies maskTextureId if it isn't INVALID_TEXTURE_ID
586    * Always applies useAtlas.
587    * @param[in] url          The URL of the image to load
588    * @param[in] size         The image size
589    * @param[in] fittingMode  The FittingMode to use
590    * @param[in] samplingMode The SamplingMode to use
591    * @param[in] useAtlas     True if atlased
592    * @param[in] maskTextureId The masking texture id (or INVALID_TEXTURE_ID)
593    * @return                 A hash of the provided data for caching.
594    */
595   TextureHash GenerateHash( const std::string& url, const ImageDimensions size,
596                             const FittingMode::Type fittingMode,
597                             const Dali::SamplingMode::Type samplingMode, const UseAtlas useAtlas,
598                             TextureId maskTextureId,
599                             MultiplyOnLoad preMultiplyOnLoad);
600   /**
601    * @brief Looks up a cached texture by its hash.
602    * If found, the given parameters are used to check there is no hash-collision.
603    * @param[in] hash          The hash to look up
604    * @param[in] url           The URL of the image to load
605    * @param[in] size          The image size
606    * @param[in] fittingMode   The FittingMode to use
607    * @param[in] samplingMode  The SamplingMode to use
608    * @param[in] useAtlas      True if atlased
609    * @param[in] maskTextureId Optional texture ID to use to mask this image
610    * @return A TextureId of a cached Texture if found. Or INVALID_TEXTURE_ID if not found.
611    */
612   TextureManager::TextureId FindCachedTexture(
613     const TextureManager::TextureHash hash,
614     const std::string& url,
615     const ImageDimensions size,
616     const FittingMode::Type fittingMode,
617     const Dali::SamplingMode::Type samplingMode,
618     const bool useAtlas,
619     TextureId maskTextureId,
620     MultiplyOnLoad preMultiplyOnLoad);
621
622 private:
623
624   /**
625    * @brief Helper class to keep the relation between AsyncImageLoader and corresponding LoadingInfo container
626    */
627   class AsyncLoadingHelper : public ConnectionTracker
628   {
629   public:
630     /**
631      * @brief Create an AsyncLoadingHelper.
632      * @param[in] textureManager Reference to the texture manager
633      */
634     AsyncLoadingHelper(TextureManager& textureManager);
635
636     /**
637      * @brief Load a new texture.
638      * @param[in] textureId             TextureId to reference the texture that will be loaded
639      * @param[in] url                   The URL of the image to load
640      * @param[in] desiredSize           The size the image is likely to appear at.
641      *                                  This can be set to 0,0 for automatic
642      * @param[in] fittingMode           The FittingMode to use
643      * @param[in] samplingMode          The SamplingMode to use
644      * @param[in] orientationCorrection Whether to use image metadata to rotate or flip the image,
645      *                                  e.g., from portrait to landscape
646      */
647     void Load(TextureId textureId,
648               const VisualUrl& url,
649               ImageDimensions desiredSize,
650               FittingMode::Type fittingMode,
651               SamplingMode::Type samplingMode,
652               bool orientationCorrection);
653
654   public:
655     AsyncLoadingHelper(const AsyncLoadingHelper&) = delete;
656     AsyncLoadingHelper& operator=(const AsyncLoadingHelper&) = delete;
657
658     AsyncLoadingHelper(AsyncLoadingHelper&& rhs);
659     AsyncLoadingHelper& operator=(AsyncLoadingHelper&&rhs) = delete;
660
661   private:
662     /**
663      * @brief Main constructor that used by all other constructors
664      */
665     AsyncLoadingHelper(Toolkit::AsyncImageLoader loader,
666                        TextureManager& textureManager,
667                        AsyncLoadingInfoContainerType&& loadingInfoContainer);
668
669     /**
670      * @brief Callback to be called when texture loading is complete, it passes the pixel buffer on to texture manager.
671      * @param[in] id          Loader id
672      * @param[in] pixelBuffer Image data
673      */
674     void AsyncLoadComplete(uint32_t id, Devel::PixelBuffer pixelBuffer);
675
676   private:
677     Toolkit::AsyncImageLoader     mLoader;
678     TextureManager&               mTextureManager;
679     AsyncLoadingInfoContainerType mLoadingInfoContainer;
680   };
681
682   struct ExternalTextureInfo
683   {
684     TextureId textureId;
685     TextureSet textureSet;
686   };
687
688 private:
689
690   /**
691    * Deleted copy constructor.
692    */
693   TextureManager( const TextureManager& ) = delete;
694
695   /**
696    * Deleted assignment operator.
697    */
698   TextureManager& operator=( const TextureManager& rhs ) = delete;
699
700   /**
701    * This is called by the TextureManagerUploadObserver when an observer is destroyed.
702    * We use the callback to know when to remove an observer from our notify list.
703    * @param[in] observer The observer that generated the callback
704    */
705   void ObserverDestroyed( TextureUploadObserver* observer );
706
707 private:  // Member Variables:
708
709   TextureInfoContainerType                      mTextureInfoContainer; ///< Used to manage the life-cycle and caching of Textures
710   RoundRobinContainerView< AsyncLoadingHelper > mAsyncLocalLoaders;    ///< The Asynchronous image loaders used to provide all local async loads
711   RoundRobinContainerView< AsyncLoadingHelper > mAsyncRemoteLoaders;   ///< The Asynchronous image loaders used to provide all remote async loads
712   std::vector< ExternalTextureInfo >            mExternalTextures;     ///< Externally provided textures
713   TextureId                                     mCurrentTextureId;     ///< The current value used for the unique Texture Id generation
714 };
715
716
717 } // name Internal
718
719 } // namespace Toolkit
720
721 } // namespace Dali
722
723 #endif // DALI_TOOLKIT_TEXTURE_MANAGER_IMPL_H