[dali_2.3.21] Merge branch 'devel/master'
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / image / image-visual.h
1 #ifndef DALI_TOOLKIT_INTERNAL_IMAGE_VISUAL_H
2 #define DALI_TOOLKIT_INTERNAL_IMAGE_VISUAL_H
3
4 /*
5  * Copyright (c) 2024 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
21 // EXTERNAL INCLUDES
22 #include <memory>
23
24 #include <dali/public-api/common/intrusive-ptr.h>
25 #include <dali/public-api/images/image-operations.h>
26 #include <dali/public-api/object/weak-handle.h>
27 #include <dali/public-api/rendering/visual-renderer.h>
28
29 // INTERNAL INCLUDES
30 #include <dali-toolkit/devel-api/image-loader/atlas-upload-observer.h>
31 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
32 #include <dali-toolkit/internal/image-loader/fast-track-loading-task.h>
33 #include <dali-toolkit/internal/texture-manager/texture-upload-observer.h>
34 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-url.h>
36 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
37
38 namespace Dali
39 {
40 class NativeImage;
41
42 namespace Toolkit
43 {
44 namespace Internal
45 {
46 class ImageVisualShaderFactory;
47 class ImageVisual;
48 typedef IntrusivePtr<ImageVisual> ImageVisualPtr;
49
50 /**
51  * The visual which renders an image to a quad geometry
52  *
53  * The following properties are optional
54  *
55  * | %Property Name        | Type              |
56  * |-----------------------|-------------------|
57  * | url                   | STRING            |
58  * | alphaMaskUrl          | STRING            |
59  * | fittingMode           | INTEGER OR STRING |
60  * | samplingMode          | INTEGER OR STRING |
61  * | desiredWidth          | INTEGER           |
62  * | desiredHeight         | INTEGER           |
63  * | synchronousLoading    | BOOLEAN           |
64  * | pixelArea             | VECTOR4           |
65  * | wrapModeU             | INTEGER OR STRING |
66  * | wrapModeV             | INTEGER OR STRING |
67  * | loadPolicy            | INTEGER OR STRING |
68  * | releasePolicy         | INTEGER OR STRING |
69  * | orientationCorrection | BOOLEAN           |
70  *
71  * where pixelArea is a rectangular area.
72  * In its Vector4 value, the first two elements indicate the top-left position of the area,
73  * and the last two elements are the area width and height respectively.
74  * If not specified, the default value is [0.0, 0.0, 1.0, 1.0], i.e. the entire area of the image.
75  *
76  * where wrapModeU and wrapModeV separately decide how the texture should be sampled when the u and v coordinate exceeds the range of 0.0 to 1.0.
77  * Its value should be one of the following wrap mode:
78  *   "DEFAULT"
79  *   "CLAMP_TO_EDGE"
80  *   "REPEAT"
81  *   "MIRRORED_REPEAT"
82  *
83  * where imageFittingMode should be one of the following fitting modes:
84  *   "SHRINK_TO_FIT"
85  *   "SCALE_TO_FILL"
86  *   "FIT_WIDTH"
87  *   "FIT_HEIGHT"
88  *   "DEFAULT"
89  *
90  * where imageSamplingMode should be one of the following sampling modes:
91  *   "BOX"
92  *   "NEAREST"
93  *   "LINEAR"
94  *   "BOX_THEN_NEAREST"
95  *   "BOX_THEN_LINEAR"
96  *   "NO_FILTER"
97  *   "DONT_CARE"
98  *   "DEFAULT"
99  *
100  * where loadPolicy should be one of the following image loading modes
101  *   "IMMEDIATE"   // Loads image even if visual not attached to stage yet
102  *   "ATTACHED"    // Only loads image once visual is attached to stage
103  *
104  * where releasePolicy should be one of the following policies for when to cache the image
105  *   "DETACHED"    //  Release image from cache when visual detached from stage
106  *   "DESTROYED"   //  Keep image in cache until the visual is destroyed
107  *   "NEVER"       //  Keep image in cache until application ends.
108  *
109  * If the Visual is in a LayerUI it will pixel align the image, using a Layer3D will disable pixel alignment.
110  * Changing layer behaviour between LayerUI to Layer3D whilst the visual is already staged will not have an effect.
111  */
112 class ImageVisual : public Visual::Base, public ConnectionTracker, public AtlasUploadObserver, public TextureUploadObserver
113 {
114 public:
115   /**
116    * @brief Create a new image visual with a URL.
117    *
118    * The visual will load the Image asynchronously when the associated actor is put on stage, and destroy the image when it is off stage
119    *
120    * @param[in] factoryCache The VisualFactoryCache object
121    * @param[in] shaderFactory The ImageVisualShaderFactory object
122    * @param[in] imageUrl The URL of the image resource to use
123    * @param[in] properties A Property::Map containing settings for this visual
124    * @param[in] size The width and height to fit the loaded image to.
125    * @param[in] fittingMode The FittingMode of the resource to load
126    * @param[in] samplingMode The SamplingMode of the resource to load
127    * @return A smart-pointer to the newly allocated visual.
128    */
129   static ImageVisualPtr New(VisualFactoryCache&       factoryCache,
130                             ImageVisualShaderFactory& shaderFactory,
131                             const VisualUrl&          imageUrl,
132                             const Property::Map&      properties,
133                             ImageDimensions           size         = ImageDimensions(),
134                             FittingMode::Type         fittingMode  = FittingMode::DEFAULT,
135                             Dali::SamplingMode::Type  samplingMode = SamplingMode::BOX_THEN_LINEAR);
136
137   /**
138    * @brief Create a new image visual with a URL.
139    *
140    * The visual will load the Image asynchronously when the associated actor is put on stage, and destroy the image when it is off stage
141    *
142    * @param[in] factoryCache The VisualFactoryCache object
143    * @param[in] shaderFactory The ImageVisualShaderFactory object
144    * @param[in] imageUrl The URL of the image resource to use
145    * @param[in] size The width and height to fit the loaded image to.
146    * @param[in] fittingMode The FittingMode of the resource to load
147    * @param[in] samplingMode The SamplingMode of the resource to load
148    * @return A smart-pointer to the newly allocated visual.
149    */
150   static ImageVisualPtr New(VisualFactoryCache&       factoryCache,
151                             ImageVisualShaderFactory& shaderFactory,
152                             const VisualUrl&          imageUrl,
153                             ImageDimensions           size         = ImageDimensions(),
154                             FittingMode::Type         fittingMode  = FittingMode::DEFAULT,
155                             Dali::SamplingMode::Type  samplingMode = SamplingMode::BOX_THEN_LINEAR);
156
157 public: // from Visual
158   /**
159    * @copydoc Visual::Base::GetNaturalSize
160    */
161   void GetNaturalSize(Vector2& naturalSize) override;
162
163   /**
164    * @copydoc Visual::Base::CreatePropertyMap
165    */
166   void DoCreatePropertyMap(Property::Map& map) const override;
167
168   /**
169    * @copydoc Visual::Base::CreateInstancePropertyMap
170    */
171   void DoCreateInstancePropertyMap(Property::Map& map) const override;
172
173   /**
174    * @copydoc Visual::Base::OnDoAction
175    */
176   void OnDoAction(const Dali::Property::Index actionId, const Dali::Property::Value& attributes) override;
177
178 protected:
179   /**
180    * @brief Constructor with a URL.
181    *
182    * The visual will load the Image asynchronously when the associated actor is put on stage, and destroy the image when it is off stage
183    *
184    * @param[in] factoryCache The VisualFactoryCache object
185    * @param[in] shaderFactory The ImageVisualShaderFactory object
186    * @param[in] imageUrl The URL of the image resource to use
187    * @param[in] size The width and height to fit the loaded image to.
188    * @param[in] fittingMode The FittingMode of the resource to load
189    * @param[in] samplingMode The SamplingMode of the resource to load
190    */
191   ImageVisual(VisualFactoryCache&       factoryCache,
192               ImageVisualShaderFactory& shaderFactory,
193               const VisualUrl&          imageUrl,
194               ImageDimensions           size,
195               FittingMode::Type         fittingMode,
196               Dali::SamplingMode::Type  samplingMode);
197
198   /**
199    * @brief A reference counted object may only be deleted by calling Unreference().
200    */
201   virtual ~ImageVisual();
202
203   /**
204    * @copydoc Visual::Base::OnInitialize
205    */
206   void OnInitialize() override;
207
208   /**
209    * @copydoc Visual::Base::DoSetProperties
210    */
211   void DoSetProperties(const Property::Map& propertyMap) override;
212
213   /**
214    * @copydoc Visual::Base::DoSetOnScene
215    */
216   void DoSetOnScene(Actor& actor) override;
217
218   /**
219    * @copydoc Visual::Base::DoSetOffScene
220    */
221   void DoSetOffScene(Actor& actor) override;
222
223   /**
224    * @copydoc Visual::Base::OnSetTransform
225    */
226   void OnSetTransform() override;
227
228   /**
229    * @copydoc Visual::Base::UpdateShader
230    */
231   void UpdateShader() override;
232
233   /**
234    * @copydoc Visual::Base::GenerateShader
235    */
236   Shader GenerateShader() const override;
237
238   /**
239    * @copydoc Visual::Base::OnGetPropertyObject
240    */
241   Dali::Property OnGetPropertyObject(Dali::Property::Key key) override;
242
243 public:
244   /**
245    * @copydoc AtlasUploadObserver::UploadCompleted
246    *
247    * To avoid rendering garbage pixels, renderer should be added to actor after the resources are ready.
248    * This callback is the place to add the renderer as it would be called once the loading is finished.
249    */
250   void UploadCompleted() override;
251
252   /**
253    * @copydoc TextureUploadObserver::LoadCompleted
254    *
255    * To avoid rendering garbage pixels, renderer should be added to actor after the resources are ready.
256    * This callback is the place to add the renderer as it would be called once the loading is finished.
257    */
258   void LoadComplete(bool success, TextureInformation textureInformation) override;
259
260   /**
261    * @brief Test callback for FastTrackLoadingTask
262    *
263    * @param[in] task The pointer of task who call this callback.
264    */
265   void FastLoadComplete(FastTrackLoadingTaskPtr task);
266
267 private:
268   /**
269    * Allocate the mask data when a masking property is defined in the property map
270    */
271   void AllocateMaskData();
272
273   /**
274    * @brief Load the texture, will try to atlas unless unable or param set to false.
275    * @param[in, out] atlasing flag if the image has been put in a atlas (true), passing false will not atlas even if possible.
276    * @param[out] atlasRect if atlasing is used this the texture area of the image in the atlas.
277    * @param[out] textures resulting texture set from the image loading.
278    * @param[in] orientationCorrection flag determines if orientation correction should be performed
279    * @param[in] forceReload flag determines if the texture should be reloaded from its source or use the cached texture.
280    */
281   void LoadTexture(bool& atlasing, Vector4& atlasRect, TextureSet& textures, bool orientationCorrection, TextureManager::ReloadPolicy forceReload);
282
283   /**
284    * @brief Checks if atlasing should be attempted
285    * @return bool returns true if atlasing can be attempted.
286    */
287   bool AttemptAtlasing();
288
289   /**
290    * @brief Initializes the Dali::Renderer from the image url
291    */
292   void InitializeRenderer();
293
294   /**
295    * Creates the texture set and adds the texture to it
296    * @param[out] textureRect The texture area of the texture in the atlas.
297    * @param[in] url The URL of the image resource to use.
298    * @param[in] synchronousLoading If true, the resource is loaded synchronously, otherwise asynchronously.
299    * @param[in] attemptAtlasing If true will attempt atlasing, otherwise create unique texture
300    * @return the texture set to use
301    */
302   TextureSet CreateTextureSet(Vector4& textureRect, bool synchronousLoading, bool attemptAtlasing);
303
304   /**
305    * Set the value to the uTextureRect uniform
306    * @param[in] textureRect The texture rectangular area.
307    */
308   void SetTextureRectUniform(const Vector4& textureRect);
309
310   /**
311    * Remove texture with valid TextureId
312    */
313   void RemoveTexture();
314
315   /**
316    * @brief Compute texture size
317    */
318   void ComputeTextureSize();
319
320   /**
321    * @brief Compute mask texture ratio
322    * @return The Mask Texture Ratio
323    */
324   Vector2 ComputeMaskTextureRatio();
325
326   /**
327    * Helper method to set individual values by index key.
328    * @param[in] index The index key of the value
329    * @param[in] value The value
330    */
331   void DoSetProperty(Property::Index index, const Property::Value& value);
332
333   /**
334    * @brief Check whether the mask texture is loaded or not.
335    * If MaskingType is MASKING_ON_LOADING and mask texture is failed to load, update shader.
336    */
337   void CheckMaskTexture();
338
339   /**
340    * @brief Reset Renderer using empty texture
341    * For drawing empty visual, reset the renderer.
342    */
343   void ResetRenderer();
344
345   /**
346    * @brief Show broken image when image loading is failed.
347    */
348   void ShowBrokenImage();
349
350   /**
351    * @brief Remove current added fast track upload task.
352    */
353   void ResetFastTrackLoadingTask();
354
355   /**
356    * @brief Update geometry information and get the generated result.
357    *
358    * @param[in] textureId Id of texture. It will be used when we use AddOn.
359    * @param[in] createForce True if we need to create geometry forcely. False if we don't re-generate geometry.
360    * @return Generated geometry, or empty handle if we don't need to update geometry.
361    */
362   Geometry GenerateGeometry(TextureManager::TextureId textureId, bool createForce);
363
364 private:
365   Vector4                            mPixelArea;
366   Property::Index                    mPixelAreaIndex;
367   WeakHandle<Actor>                  mPlacementActor;
368   VisualUrl                          mImageUrl;
369   TextureManager::MaskingDataPointer mMaskingData;
370
371   Dali::ImageDimensions     mDesiredSize;
372   TextureManager::TextureId mTextureId;
373   TextureSet                mTextures;
374   Vector2                   mTextureSize;
375   Vector2                   mPlacementActorSize;
376
377   FastTrackLoadingTaskPtr mFastTrackLoadingTask; ///< For fast track uploading.
378
379   ImageVisualShaderFactory& mImageVisualShaderFactory;
380
381   Dali::FittingMode::Type                         mFittingMode : 3;
382   Dali::SamplingMode::Type                        mSamplingMode : 4;
383   Dali::WrapMode::Type                            mWrapModeU : 3;
384   Dali::WrapMode::Type                            mWrapModeV : 3;
385   Dali::Toolkit::ImageVisual::LoadPolicy::Type    mLoadPolicy;
386   Dali::Toolkit::ImageVisual::ReleasePolicy::Type mReleasePolicy;
387   Vector4                                         mAtlasRect;
388   Dali::ImageDimensions                           mAtlasRectSize;
389   TextureManager::LoadState                       mLoadState;                     ///< The texture loading state
390   bool                                            mAttemptAtlasing;               ///< If true will attempt atlasing, otherwise create unique texture
391   bool                                            mOrientationCorrection;         ///< true if the image will have it's orientation corrected.
392   bool                                            mNeedYuvToRgb{false};           ///< true if we need to convert yuv to rgb.
393   bool                                            mNeedUnifiedYuvAndRgb{false};   ///< true if we need to support both yuv and rgb.
394   bool                                            mEnableBrokenImage{true};       ///< true if enable broken image.
395   bool                                            mUseFastTrackUploading{false};  ///< True if we use fast tack feature.
396   bool                                            mRendererAdded{false};          ///< True if renderer added into actor.
397   bool                                            mUseBrokenImageRenderer{false}; ///< True if renderer changed as broken image.
398 };
399
400 } // namespace Internal
401
402 } // namespace Toolkit
403
404 } // namespace Dali
405
406 #endif /* DALI_TOOLKIT_INTERNAL_IMAGE_VISUAL_H */