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