8ccb63b0ba72e60ae4541e9e2c4d8715ee84f4aa
[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   mLoaded( false ),
76   mPlacementActor(),
77   mVisualSize(Vector2::ZERO),
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   // SVG visual needs it's size set before it can be rasterized hence set ResourceReady once on stage
175   ResourceReady( Toolkit::Visual::ResourceStatus::READY );
176 }
177
178 void SvgVisual::DoSetOffScene( Actor& actor )
179 {
180   mFactoryCache.GetSVGRasterizationThread()->RemoveTask( this );
181
182   actor.RemoveRenderer( mImpl->mRenderer );
183   mPlacementActor.Reset();
184
185   // Reset the visual size to zero so that when adding the actor back to stage the SVG rasterization is forced
186   mVisualSize = Vector2::ZERO;
187 }
188
189 void SvgVisual::GetNaturalSize( Vector2& naturalSize )
190 {
191   if(mLoaded)
192   {
193     naturalSize.x = mDefaultWidth;
194     naturalSize.y = mDefaultHeight;
195   }
196   else
197   {
198     naturalSize = Vector2::ZERO;
199   }
200 }
201
202 void SvgVisual::DoCreatePropertyMap( Property::Map& map ) const
203 {
204   map.Clear();
205   map.Insert( Toolkit::Visual::Property::TYPE, Toolkit::Visual::SVG );
206   if( mImageUrl.IsValid() )
207   {
208     map.Insert( Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl() );
209     map.Insert( Toolkit::ImageVisual::Property::ATLASING, mAttemptAtlasing );
210   }
211   map.Insert( Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, IsSynchronousLoadingRequired() );
212 }
213
214 void SvgVisual::DoCreateInstancePropertyMap( Property::Map& map ) const
215 {
216   // Do nothing
217 }
218
219 void SvgVisual::Load()
220 {
221   // load remote resource on svg rasterize thread.
222   if(!mLoaded && mImageUrl.IsLocalResource())
223   {
224     Dali::Vector<uint8_t> buffer;
225     if(Dali::FileLoader::ReadFile(mImageUrl.GetUrl(), buffer))
226     {
227       buffer.PushBack('\0');
228
229       Vector2 dpi = Stage::GetCurrent().GetDpi();
230       float meanDpi = (dpi.height + dpi.width) * 0.5f;
231       if(!mVectorRenderer.Load(buffer, meanDpi))
232       {
233         DALI_LOG_ERROR("SvgVisual::Load: Failed to load file! [%s]\n", mImageUrl.GetUrl().c_str());
234         return;
235       }
236       mVectorRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
237       mLoaded = true;
238     }
239     else
240     {
241       DALI_LOG_ERROR("SvgVisual::Load: Failed to read file! [%s]\n", mImageUrl.GetUrl().c_str());
242     }
243   }
244 }
245
246 void SvgVisual::AddRasterizationTask( const Vector2& size )
247 {
248   if( mImpl->mRenderer )
249   {
250     unsigned int width = static_cast<unsigned int>(size.width);
251     unsigned int height = static_cast<unsigned int>( size.height );
252
253     Vector2 dpi = Stage::GetCurrent().GetDpi();
254     float meanDpi = ( dpi.height + dpi.width ) * 0.5f;
255
256     RasterizingTaskPtr newTask = new RasterizingTask(this, mVectorRenderer, mImageUrl, meanDpi, width, height, mLoaded);
257     if(IsSynchronousLoadingRequired())
258     {
259       newTask->Load();
260       newTask->Rasterize();
261       ApplyRasterizedImage(newTask->GetVectorRenderer(), newTask->GetPixelData(), newTask->IsLoaded());
262     }
263     else
264     {
265       mFactoryCache.GetSVGRasterizationThread()->AddTask( newTask );
266     }
267   }
268 }
269
270 void SvgVisual::ApplyRasterizedImage( VectorImageRenderer vectorRenderer, PixelData rasterizedPixelData, bool isLoaded )
271 {
272   mLoaded = isLoaded;
273
274   if(isLoaded && rasterizedPixelData && IsOnScene())
275   {
276     TextureSet currentTextureSet = mImpl->mRenderer.GetTextures();
277     if( mImpl->mFlags & Impl::IS_ATLASING_APPLIED )
278     {
279       mFactoryCache.GetAtlasManager()->Remove( currentTextureSet, mAtlasRect );
280     }
281
282     TextureSet textureSet;
283
284     if( mAttemptAtlasing && !mImpl->mCustomShader )
285     {
286       Vector4 atlasRect;
287       textureSet = mFactoryCache.GetAtlasManager()->Add(atlasRect, rasterizedPixelData );
288       if( textureSet ) // atlasing
289       {
290         if( textureSet != currentTextureSet )
291         {
292           mImpl->mRenderer.SetTextures( textureSet );
293         }
294         mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, atlasRect );
295         mAtlasRect = atlasRect;
296         mImpl->mFlags |= Impl::IS_ATLASING_APPLIED;
297       }
298     }
299
300     if( !textureSet ) // no atlasing - mAttemptAtlasing is false or adding to atlas is failed
301     {
302       Texture texture = Texture::New( Dali::TextureType::TEXTURE_2D, Pixel::RGBA8888,
303                                       rasterizedPixelData.GetWidth(), rasterizedPixelData.GetHeight() );
304       texture.Upload( rasterizedPixelData );
305       mImpl->mFlags &= ~Impl::IS_ATLASING_APPLIED;
306
307       if( mAtlasRect == FULL_TEXTURE_RECT )
308       {
309         textureSet = currentTextureSet;
310       }
311       else
312       {
313         textureSet = TextureSet::New();
314         mImpl->mRenderer.SetTextures( textureSet );
315
316         mImpl->mRenderer.RegisterProperty( ATLAS_RECT_UNIFORM_NAME, FULL_TEXTURE_RECT );
317         mAtlasRect = FULL_TEXTURE_RECT;
318       }
319
320       if( textureSet )
321       {
322         textureSet.SetTexture( 0, texture );
323       }
324     }
325
326     // Rasterized pixels are uploaded to texture. If weak handle is holding a placement actor, it is the time to add the renderer to actor.
327     Actor actor = mPlacementActor.GetHandle();
328     if( actor )
329     {
330       actor.AddRenderer( mImpl->mRenderer );
331       // reset the weak handle so that the renderer only get added to actor once
332       mPlacementActor.Reset();
333     }
334
335     // Svg loaded and ready to display
336     ResourceReady( Toolkit::Visual::ResourceStatus::READY );
337   }
338   else if(!isLoaded || !rasterizedPixelData)
339   {
340     ResourceReady( Toolkit::Visual::ResourceStatus::FAILED );
341   }
342 }
343
344 void SvgVisual::OnSetTransform()
345 {
346   Vector2 visualSize = mImpl->mTransform.GetVisualSize( mImpl->mControlSize );
347
348   if( IsOnScene() )
349   {
350     if( visualSize != mVisualSize )
351     {
352       AddRasterizationTask( visualSize );
353       mVisualSize = visualSize;
354     }
355   }
356
357   if(mImpl->mRenderer)
358   {
359     mImpl->mTransform.RegisterUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
360   }
361 }
362
363 bool SvgVisual::IsResourceReady() const
364 {
365   return ( mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
366            mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED );
367 }
368
369 } // namespace Internal
370
371 } // namespace Toolkit
372
373 } // namespace Dali