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