Updated visuals to use VisualRenderer
[platform/core/uifw/dali-toolkit.git] / dali-toolkit / internal / visuals / svg / svg-visual.cpp
1 /*
2  * Copyright (c) 2022 Samsung Electronics Co., Ltd.
3  *
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
7  *
8  * http://www.apache.org/licenses/LICENSE-2.0
9  *
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.
15  *
16  */
17
18 // CLASS HEADER
19 #include "svg-visual.h"
20
21 // INTERNAL INCLUDES
22 #include <dali-toolkit/internal/visuals/image-atlas-manager.h>
23 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
24 #include <dali-toolkit/internal/visuals/svg/svg-rasterize-thread.h>
25 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
26 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
27 #include <dali-toolkit/public-api/visuals/image-visual-properties.h>
28
29 // EXTERNAL INCLUDES
30 #include <dali/devel-api/adaptor-framework/file-loader.h>
31 #include <dali/devel-api/common/stage.h>
32 #include <dali/integration-api/debug.h>
33
34 namespace Dali
35 {
36 namespace Toolkit
37 {
38 namespace Internal
39 {
40 namespace
41 {
42 const int CUSTOM_PROPERTY_COUNT(6); // atlas + corner/border
43
44 // property name
45 const Dali::Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f);
46
47 } // namespace
48
49 SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
50 {
51   SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
52   svgVisual->Load();
53   svgVisual->SetProperties(properties);
54   svgVisual->Initialize();
55   return svgVisual;
56 }
57
58 SvgVisualPtr SvgVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
59 {
60   SvgVisualPtr svgVisual(new SvgVisual(factoryCache, shaderFactory, imageUrl));
61   svgVisual->Load();
62   svgVisual->Initialize();
63   return svgVisual;
64 }
65
66 SvgVisual::SvgVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
67 : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::SVG),
68   mImageVisualShaderFactory(shaderFactory),
69   mAtlasRect(FULL_TEXTURE_RECT),
70   mImageUrl(imageUrl),
71   mVectorRenderer(VectorImageRenderer::New()),
72   mDefaultWidth(0),
73   mDefaultHeight(0),
74   mPlacementActor(),
75   mVisualSize(Vector2::ZERO),
76   mLoadFailed(false),
77   mAttemptAtlasing(false)
78 {
79   // the rasterized image is with pre-multiplied alpha format
80   mImpl->mFlags |= Impl::IS_PREMULTIPLIED_ALPHA;
81 }
82
83 SvgVisual::~SvgVisual()
84 {
85 }
86
87 void SvgVisual::OnInitialize()
88 {
89   Shader   shader   = GenerateShader();
90   Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
91   mImpl->mRenderer  = VisualRenderer::New(geometry, shader);
92   mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
93 }
94
95 void SvgVisual::DoSetProperties(const Property::Map& propertyMap)
96 {
97   // url already passed in from constructor
98   for(Property::Map::SizeType iter = 0; iter < propertyMap.Count(); ++iter)
99   {
100     KeyValuePair keyValue = propertyMap.GetKeyValue(iter);
101     if(keyValue.first.type == Property::Key::INDEX)
102     {
103       DoSetProperty(keyValue.first.indexKey, keyValue.second);
104     }
105     else if(keyValue.first == IMAGE_ATLASING)
106     {
107       DoSetProperty(Toolkit::ImageVisual::Property::ATLASING, keyValue.second);
108     }
109     else if(keyValue.first == SYNCHRONOUS_LOADING)
110     {
111       DoSetProperty(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, keyValue.second);
112     }
113   }
114 }
115
116 void SvgVisual::DoSetProperty(Property::Index index, const Property::Value& value)
117 {
118   switch(index)
119   {
120     case Toolkit::ImageVisual::Property::ATLASING:
121     {
122       value.Get(mAttemptAtlasing);
123       break;
124     }
125     case Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING:
126     {
127       bool sync = false;
128       if(value.Get(sync))
129       {
130         if(sync)
131         {
132           mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
133         }
134         else
135         {
136           mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
137         }
138       }
139       else
140       {
141         DALI_LOG_ERROR("ImageVisual: synchronousLoading property has incorrect type\n");
142       }
143       break;
144     }
145   }
146 }
147
148 void SvgVisual::DoSetOnScene(Actor& actor)
149 {
150   TextureSet textureSet = TextureSet::New();
151   mImpl->mRenderer.SetTextures(textureSet);
152
153   // Register transform properties
154   mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
155
156   // Defer the rasterisation task until we get given a size (by Size Negotiation algorithm)
157
158   // Hold the weak handle of the placement actor and delay the adding of renderer until the svg rasterization is finished.
159   mPlacementActor = actor;
160
161   if(mLoadFailed)
162   {
163     Vector2 imageSize = Vector2::ZERO;
164     imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
165     mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
166     actor.AddRenderer(mImpl->mRenderer);
167
168     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
169   }
170   else
171   {
172     // SVG visual needs it's size set before it can be rasterized hence set ResourceReady once on stage
173     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
174   }
175 }
176
177 void SvgVisual::DoSetOffScene(Actor& actor)
178 {
179   mFactoryCache.GetSVGRasterizationThread()->RemoveTask(this);
180
181   actor.RemoveRenderer(mImpl->mRenderer);
182   mPlacementActor.Reset();
183
184   // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
185   mVisualSize = Vector2::ZERO;
186 }
187
188 void SvgVisual::GetNaturalSize(Vector2& naturalSize)
189 {
190   naturalSize.x = mDefaultWidth;
191   naturalSize.y = mDefaultHeight;
192 }
193
194 void SvgVisual::DoCreatePropertyMap(Property::Map& map) const
195 {
196   map.Clear();
197   map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG);
198   if(mImageUrl.IsValid())
199   {
200     map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
201     map.Insert(Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing);
202   }
203   map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired());
204 }
205
206 void SvgVisual::DoCreateInstancePropertyMap(Property::Map& map) const
207 {
208   // Do nothing
209 }
210
211 void SvgVisual::Load()
212 {
213   // load remote resource on svg rasterize thread.
214   if(mImageUrl.IsLocalResource())
215   {
216     Dali::Vector<uint8_t> buffer;
217     if(Dali::FileLoader::ReadFile(mImageUrl.GetUrl(), buffer))
218     {
219       buffer.PushBack('\0');
220
221       Vector2 dpi     = Stage::GetCurrent().GetDpi();
222       float   meanDpi = (dpi.height + dpi.width) * 0.5f;
223       if(!mVectorRenderer.Load(buffer, meanDpi))
224       {
225         mLoadFailed = true;
226         DALI_LOG_ERROR("SvgVisual::Load: Failed to load file! [%s]\n", mImageUrl.GetUrl().c_str());
227         return;
228       }
229       mVectorRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
230     }
231     else
232     {
233       mLoadFailed = true;
234       DALI_LOG_ERROR("SvgVisual::Load: Failed to read file! [%s]\n", mImageUrl.GetUrl().c_str());
235     }
236   }
237 }
238
239 void SvgVisual::AddRasterizationTask(const Vector2& size)
240 {
241   if(mImpl->mRenderer)
242   {
243     unsigned int width  = static_cast<unsigned int>(size.width);
244     unsigned int height = static_cast<unsigned int>(size.height);
245
246     Vector2 dpi     = Stage::GetCurrent().GetDpi();
247     float   meanDpi = (dpi.height + dpi.width) * 0.5f;
248
249     RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height);
250     if(IsSynchronousLoadingRequired() && mImageUrl.IsLocalResource())
251     {
252       newTask->Load();
253       newTask->Rasterize();
254       ApplyRasterizedImage(newTask->GetVectorRenderer(), newTask->GetPixelData(), newTask->IsLoaded());
255     }
256     else
257     {
258       mFactoryCache.GetSVGRasterizationThread()->AddTask(newTask);
259     }
260   }
261 }
262
263 void SvgVisual::ApplyRasterizedImage(VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded)
264 {
265   if(isLoaded && rasterizedPixelData && IsOnScene())
266   {
267     TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
268     if(mImpl->mFlags & Impl::IS_ATLASING_APPLIED)
269     {
270       mFactoryCache.GetAtlasManager()->Remove(currentTextureSet, mAtlasRect);
271     }
272
273     TextureSet textureSet;
274
275     if(mAttemptAtlasing && !mImpl->mCustomShader)
276     {
277       Vector4 atlasRect;
278       textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData);
279       if(textureSet) // atlasing
280       {
281         if(textureSet != currentTextureSet)
282         {
283           mImpl->mRenderer.SetTextures(textureSet);
284         }
285         mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, atlasRect);
286         mAtlasRect = atlasRect;
287         mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
288       }
289     }
290
291     if(!textureSet) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
292     {
293       Texture texture = Texture::New(Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888, rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight());
294       texture.Upload(rasterizedPixelData);
295       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
296
297       if(mAtlasRect == FULL_TEXTURE_RECT)
298       {
299         textureSet = currentTextureSet;
300       }
301       else
302       {
303         textureSet = TextureSet::New();
304         mImpl->mRenderer.SetTextures(textureSet);
305
306         mImpl->mRenderer.RegisterProperty(ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT);
307         mAtlasRect = FULL_TEXTURE_RECT;
308       }
309
310       if(textureSet)
311       {
312         textureSet.SetTexture(0, texture);
313       }
314     }
315
316     // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
317     Actor actor = mPlacementActor.GetHandle();
318     if(actor)
319     {
320       actor.AddRenderer(mImpl->mRenderer);
321       // reset the weak handle so that the renderer only get added to actor once
322       mPlacementActor.Reset();
323     }
324
325     // Svg loaded and ready to display
326     ResourceReady(Toolkit::Visual::ResourceStatus::READY);
327   }
328   else if(!isLoaded || !rasterizedPixelData)
329   {
330     Actor actor = mPlacementActor.GetHandle();
331     if(actor)
332     {
333       Vector2 imageSize = Vector2::ZERO;
334       imageSize         = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
335       mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize);
336       actor.AddRenderer(mImpl->mRenderer);
337     }
338
339     ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
340   }
341 }
342
343 void SvgVisual::OnSetTransform()
344 {
345   Vector2 visualSize = mImpl->mTransform.GetVisualSize(mImpl->mControlSize);
346
347   if(IsOnScene() && !mLoadFailed)
348   {
349     if(visualSize != mVisualSize)
350     {
351       AddRasterizationTask(visualSize);
352       mVisualSize = visualSize;
353     }
354   }
355
356   if(mImpl->mRenderer)
357   {
358     mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
359   }
360 }
361
362 bool SvgVisual::IsResourceReady() const
363 {
364   return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
365           mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED);
366 }
367
368 void SvgVisual::UpdateShader()
369 {
370   if(mImpl->mRenderer)
371   {
372     Shader shader = GenerateShader();
373     mImpl->mRenderer.SetShader(shader);
374   }
375 }
376
377 Shader SvgVisual::GenerateShader() const
378 {
379   Shader shader;
380   if(!mImpl->mCustomShader)
381   {
382     shader = mImageVisualShaderFactory.GetShader(
383       mFactoryCache,
384       ImageVisualShaderFeature::FeatureBuilder()
385         .EnableTextureAtlas(mAttemptAtlasing)
386         .EnableRoundedCorner(IsRoundedCornerRequired())
387         .EnableBorderline(IsBorderlineRequired()));
388   }
389   else
390   {
391     shader = Shader::New(mImpl->mCustomShader->mVertexShader.empty() ? mImageVisualShaderFactory.GetVertexShaderSource().data() : mImpl->mCustomShader->mVertexShader,
392                          mImpl->mCustomShader->mFragmentShader.empty() ? mImageVisualShaderFactory.GetFragmentShaderSource().data() : mImpl->mCustomShader->mFragmentShader,
393                          mImpl->mCustomShader->mHints);
394
395     shader.RegisterProperty(PIXEL_AREA_UNIFORM_NAME, FULL_TEXTURE_RECT);
396   }
397   return shader;
398 }
399
400 } // namespace Internal
401
402 } // namespace Toolkit
403
404 } // namespace Dali