2 * Copyright (c) 2022 Samsung Electronics Co., Ltd.
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 #include "npatch-visual.h"
22 #include <dali/devel-api/adaptor-framework/image-loading.h>
23 #include <dali/devel-api/common/stage.h>
24 #include <dali/devel-api/rendering/renderer-devel.h>
25 #include <dali/integration-api/debug.h>
28 #include <dali-toolkit/devel-api/utility/npatch-helper.h>
29 #include <dali-toolkit/devel-api/visuals/image-visual-properties-devel.h>
30 #include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
31 #include <dali-toolkit/internal/visuals/image-visual-shader-factory.h>
32 #include <dali-toolkit/internal/visuals/npatch-loader.h>
33 #include <dali-toolkit/internal/visuals/rendering-addon.h>
34 #include <dali-toolkit/internal/visuals/visual-base-data-impl.h>
35 #include <dali-toolkit/internal/visuals/visual-base-impl.h>
36 #include <dali-toolkit/internal/visuals/visual-factory-cache.h>
37 #include <dali-toolkit/internal/visuals/visual-factory-impl.h>
38 #include <dali-toolkit/internal/visuals/visual-string-constants.h>
39 #include <dali-toolkit/public-api/visuals/visual-properties.h>
49 const int CUSTOM_PROPERTY_COUNT(5); // fixed(3),stretch,aux
52 /////////////////NPatchVisual////////////////
54 NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl, const Property::Map& properties)
56 NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory));
57 nPatchVisual->mImageUrl = imageUrl;
58 nPatchVisual->SetProperties(properties);
59 nPatchVisual->Initialize();
63 NPatchVisualPtr NPatchVisual::New(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory, const VisualUrl& imageUrl)
65 NPatchVisualPtr nPatchVisual(new NPatchVisual(factoryCache, shaderFactory));
66 nPatchVisual->mImageUrl = imageUrl;
67 nPatchVisual->Initialize();
71 void NPatchVisual::LoadImages()
73 TextureManager& textureManager = mFactoryCache.GetTextureManager();
74 bool synchronousLoading = mImpl->mFlags & Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
76 if(mId == NPatchData::INVALID_NPATCH_DATA_ID && (mImageUrl.IsLocalResource() || mImageUrl.IsBufferResource()))
78 bool preMultiplyOnLoad = IsPreMultipliedAlphaEnabled() && !mImpl->mCustomShader ? true : false;
79 mId = mLoader.Load(textureManager, this, mImageUrl, mBorder, preMultiplyOnLoad, synchronousLoading);
81 const NPatchData* data;
82 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
84 EnablePreMultipliedAlpha(data->IsPreMultiplied());
88 if(!mAuxiliaryPixelBuffer && mAuxiliaryUrl.IsValid() && (mAuxiliaryUrl.IsLocalResource() || mAuxiliaryUrl.IsBufferResource()))
90 // Load the auxiliary image
91 auto preMultiplyOnLoading = TextureManager::MultiplyOnLoad::LOAD_WITHOUT_MULTIPLY;
92 mAuxiliaryPixelBuffer = textureManager.LoadPixelBuffer(mAuxiliaryUrl, Dali::ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, synchronousLoading, this, true, preMultiplyOnLoading);
94 // If synchronousLoading is true, we can check the auxiliaryResource's statue now.
95 if(synchronousLoading)
97 mAuxiliaryResourceStatus = mAuxiliaryPixelBuffer ? Toolkit::Visual::ResourceStatus::READY : Toolkit::Visual::ResourceStatus::FAILED;
102 void NPatchVisual::GetNaturalSize(Vector2& naturalSize)
107 // load now if not already loaded
108 const NPatchData* data;
109 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING)
111 naturalSize.x = data->GetCroppedWidth();
112 naturalSize.y = data->GetCroppedHeight();
116 if(mImageUrl.IsValid())
118 ImageDimensions dimensions = Dali::GetOriginalImageSize(mImageUrl.GetUrl());
119 if(dimensions != ImageDimensions(0, 0))
121 naturalSize.x = dimensions.GetWidth();
122 naturalSize.y = dimensions.GetHeight();
127 if(mAuxiliaryPixelBuffer)
129 naturalSize.x = std::max(naturalSize.x, float(mAuxiliaryPixelBuffer.GetWidth()));
130 naturalSize.y = std::max(naturalSize.y, float(mAuxiliaryPixelBuffer.GetHeight()));
134 void NPatchVisual::DoSetProperties(const Property::Map& propertyMap)
136 // URL is already passed in via constructor
138 Property::Value* borderOnlyValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER_ONLY, BORDER_ONLY);
141 borderOnlyValue->Get(mBorderOnly);
144 Property::Value* borderValue = propertyMap.Find(Toolkit::ImageVisual::Property::BORDER, BORDER);
145 if(borderValue && !borderValue->Get(mBorder)) // If value exists and is rect, just set mBorder
147 // Not a rect so try vector4
149 if(borderValue->Get(border))
151 mBorder.left = static_cast<int>(border.x);
152 mBorder.right = static_cast<int>(border.y);
153 mBorder.bottom = static_cast<int>(border.z);
154 mBorder.top = static_cast<int>(border.w);
158 Property::Value* auxImage = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, AUXILIARY_IMAGE_NAME);
162 if(auxImage->Get(url))
168 Property::Value* auxImageAlpha = propertyMap.Find(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, AUXILIARY_IMAGE_ALPHA_NAME);
171 auxImageAlpha->Get(mAuxiliaryImageAlpha);
174 Property::Value* synchronousLoading = propertyMap.Find(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, SYNCHRONOUS_LOADING);
175 if(synchronousLoading)
178 synchronousLoading->Get(sync);
181 mImpl->mFlags |= Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
185 mImpl->mFlags &= ~Impl::IS_SYNCHRONOUS_RESOURCE_LOADING;
189 Property::Value* releasePolicy = propertyMap.Find(Toolkit::ImageVisual::Property::RELEASE_POLICY, RELEASE_POLICY_NAME);
192 releasePolicy->Get(mReleasePolicy);
196 void NPatchVisual::DoSetOnScene(Actor& actor)
198 // load when first go on stage
201 // Set mPlacementActor now, because some case, LoadImages can use this information in LoadComplete API.
202 // at this case, we try to SetResouce to mPlaceActor twice. so, we should avoid that case.
203 mPlacementActor = actor;
205 const NPatchData* data;
206 if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING)
208 // If mAuxiliaryUrl need to be loaded, we should wait it until LoadComplete called.
209 if(!mAuxiliaryUrl.IsValid() || mAuxiliaryResourceStatus != Toolkit::Visual::ResourceStatus::PREPARING)
216 void NPatchVisual::DoSetOffScene(Actor& actor)
218 if((mId != NPatchData::INVALID_NPATCH_DATA_ID) && mReleasePolicy == Toolkit::ImageVisual::ReleasePolicy::DETACHED)
220 mLoader.Remove(mId, this);
221 mImpl->mResourceStatus = Toolkit::Visual::ResourceStatus::PREPARING;
222 mId = NPatchData::INVALID_NPATCH_DATA_ID;
225 actor.RemoveRenderer(mImpl->mRenderer);
226 mPlacementActor.Reset();
229 void NPatchVisual::OnSetTransform()
233 mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
237 bool NPatchVisual::IsResourceReady() const
239 return (mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::READY ||
240 mImpl->mResourceStatus == Toolkit::Visual::ResourceStatus::FAILED);
243 void NPatchVisual::DoCreatePropertyMap(Property::Map& map) const
246 bool sync = IsSynchronousLoadingRequired();
247 map.Insert(Toolkit::ImageVisual::Property::SYNCHRONOUS_LOADING, sync);
248 map.Insert(Toolkit::Visual::Property::TYPE, Toolkit::Visual::N_PATCH);
249 map.Insert(Toolkit::ImageVisual::Property::URL, mImageUrl.GetUrl());
250 map.Insert(Toolkit::ImageVisual::Property::BORDER_ONLY, mBorderOnly);
251 map.Insert(Toolkit::ImageVisual::Property::BORDER, mBorder);
252 map.Insert(Toolkit::ImageVisual::Property::RELEASE_POLICY, mReleasePolicy);
254 if(mAuxiliaryUrl.IsValid())
256 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
257 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
261 void NPatchVisual::DoCreateInstancePropertyMap(Property::Map& map) const
263 if(mAuxiliaryUrl.IsValid())
265 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE, mAuxiliaryUrl.GetUrl());
266 map.Insert(Toolkit::DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA, mAuxiliaryImageAlpha);
270 NPatchVisual::NPatchVisual(VisualFactoryCache& factoryCache, ImageVisualShaderFactory& shaderFactory)
271 : Visual::Base(factoryCache, Visual::FittingMode::FILL, Toolkit::Visual::N_PATCH),
273 mLoader(factoryCache.GetNPatchLoader()),
274 mImageVisualShaderFactory(shaderFactory),
277 mId(NPatchData::INVALID_NPATCH_DATA_ID),
278 mAuxiliaryResourceStatus(Toolkit::Visual::ResourceStatus::PREPARING),
281 mAuxiliaryImageAlpha(0.0f),
282 mReleasePolicy(Toolkit::ImageVisual::ReleasePolicy::DETACHED)
284 EnablePreMultipliedAlpha(mFactoryCache.GetPreMultiplyOnLoad());
287 NPatchVisual::~NPatchVisual()
289 if(Stage::IsInstalled() && (mId != NPatchData::INVALID_NPATCH_DATA_ID) && (mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::NEVER))
291 mLoader.Remove(mId, this);
292 mId = NPatchData::INVALID_NPATCH_DATA_ID;
296 void NPatchVisual::OnInitialize()
298 // Get basic geometry and shader
299 Geometry geometry = mFactoryCache.GetGeometry(VisualFactoryCache::QUAD_GEOMETRY);
300 Shader shader = mImageVisualShaderFactory.GetShader(
302 ImageVisualShaderFeature::FeatureBuilder());
304 mImpl->mRenderer = VisualRenderer::New(geometry, shader);
305 mImpl->mRenderer.ReserveCustomProperties(CUSTOM_PROPERTY_COUNT);
307 //Register transform properties
308 mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
311 Geometry NPatchVisual::CreateGeometry()
314 const NPatchData* data;
315 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
317 if(data->GetStretchPixelsX().Size() == 1 && data->GetStretchPixelsY().Size() == 1)
319 if(DALI_UNLIKELY(mBorderOnly))
321 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY);
325 if(data->GetRenderingMap())
327 uint32_t elementCount[2];
328 geometry = RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), Uint16Pair(3, 3), elementCount);
331 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
336 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
340 else if(data->GetStretchPixelsX().Size() > 0 || data->GetStretchPixelsY().Size() > 0)
342 Uint16Pair gridSize(2 * data->GetStretchPixelsX().Size() + 1, 2 * data->GetStretchPixelsY().Size() + 1);
343 if(!data->GetRenderingMap())
345 geometry = !mBorderOnly ? NPatchHelper::CreateGridGeometry(gridSize) : NPatchHelper::CreateBorderGeometry(gridSize);
349 uint32_t elementCount[2];
350 geometry = !mBorderOnly ? RenderingAddOn::Get().CreateGeometryGrid(data->GetRenderingMap(), gridSize, elementCount) : NPatchHelper::CreateBorderGeometry(gridSize);
353 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
360 // no N patch data so use default geometry
361 geometry = GetNinePatchGeometry(VisualFactoryCache::NINE_PATCH_GEOMETRY);
366 Shader NPatchVisual::CreateShader()
369 const NPatchData* data;
370 // 0 is either no data (load failed?) or no stretch regions on image
371 // for both cases we use the default shader
372 NPatchUtility::StretchRanges::SizeType xStretchCount = 0;
373 NPatchUtility::StretchRanges::SizeType yStretchCount = 0;
375 auto fragmentShader = mAuxiliaryPixelBuffer ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG
376 : SHADER_NPATCH_VISUAL_SHADER_FRAG;
377 auto shaderType = mAuxiliaryPixelBuffer ? VisualFactoryCache::NINE_PATCH_MASK_SHADER
378 : VisualFactoryCache::NINE_PATCH_SHADER;
380 // ask loader for the regions
381 if(mLoader.GetNPatchData(mId, data))
383 xStretchCount = data->GetStretchPixelsX().Count();
384 yStretchCount = data->GetStretchPixelsY().Count();
387 if(DALI_LIKELY(!mImpl->mCustomShader))
389 if(DALI_LIKELY((xStretchCount == 1 && yStretchCount == 1) ||
390 (xStretchCount == 0 && yStretchCount == 0)))
392 shader = mFactoryCache.GetShader(shaderType);
393 if(DALI_UNLIKELY(!shader))
395 shader = Shader::New(SHADER_NPATCH_VISUAL_3X3_SHADER_VERT, fragmentShader);
396 // Only cache vanilla 9 patch shaders
397 mFactoryCache.SaveShader(shaderType, shader);
400 else if(xStretchCount > 0 || yStretchCount > 0)
402 std::stringstream vertexShader;
403 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
404 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
405 << SHADER_NPATCH_VISUAL_SHADER_VERT;
407 shader = Shader::New(vertexShader.str(), fragmentShader);
412 Dali::Shader::Hint::Value hints = Dali::Shader::Hint::NONE;
414 if(!mImpl->mCustomShader->mFragmentShader.empty())
416 fragmentShader = mImpl->mCustomShader->mFragmentShader.c_str();
418 hints = mImpl->mCustomShader->mHints;
420 /* Apply Custom Vertex Shader only if image is 9-patch */
421 if((xStretchCount == 1 && yStretchCount == 1) ||
422 (xStretchCount == 0 && yStretchCount == 0))
424 const char* vertexShader = SHADER_NPATCH_VISUAL_3X3_SHADER_VERT.data();
426 if(!mImpl->mCustomShader->mVertexShader.empty())
428 vertexShader = mImpl->mCustomShader->mVertexShader.c_str();
430 shader = Shader::New(vertexShader, fragmentShader, hints);
432 else if(xStretchCount > 0 || yStretchCount > 0)
434 std::stringstream vertexShader;
435 vertexShader << "#define FACTOR_SIZE_X " << xStretchCount + 2 << "\n"
436 << "#define FACTOR_SIZE_Y " << yStretchCount + 2 << "\n"
437 << SHADER_NPATCH_VISUAL_SHADER_VERT;
439 shader = Shader::New(vertexShader.str(), fragmentShader, hints);
446 void NPatchVisual::ApplyTextureAndUniforms()
448 const NPatchData* data;
449 TextureSet textureSet;
451 if(mLoader.GetNPatchData(mId, data) && data->GetLoadingState() == NPatchData::LoadingState::LOAD_COMPLETE)
453 textureSet = data->GetTextures();
454 NPatchHelper::ApplyTextureAndUniforms(mImpl->mRenderer, data);
456 if(mAuxiliaryPixelBuffer)
458 // If the auxiliary image is smaller than the un-stretched NPatch, use CPU resizing to enlarge it to the
459 // same size as the unstretched NPatch. This will give slightly higher quality results than just relying
460 // on GL interpolation alone.
461 if(mAuxiliaryPixelBuffer.GetWidth() < data->GetCroppedWidth() &&
462 mAuxiliaryPixelBuffer.GetHeight() < data->GetCroppedHeight())
464 mAuxiliaryPixelBuffer.Resize(data->GetCroppedWidth(), data->GetCroppedHeight());
467 // Note, this resets mAuxiliaryPixelBuffer handle
468 auto auxiliaryPixelData = Devel::PixelBuffer::Convert(mAuxiliaryPixelBuffer);
470 auto texture = Texture::New(TextureType::TEXTURE_2D,
471 auxiliaryPixelData.GetPixelFormat(),
472 auxiliaryPixelData.GetWidth(),
473 auxiliaryPixelData.GetHeight());
474 texture.Upload(auxiliaryPixelData);
476 // TODO : This code exist due to the texture cache manager hold TextureSet, not Texture.
477 // If we call textureSet.SetTexture(1, texture) directly, the cached TextureSet also be changed.
478 // We should make pass utc-Dali-VisualFactory.cpp UtcDaliNPatchVisualAuxiliaryImage02().
479 TextureSet tempTextureSet = TextureSet::New();
480 tempTextureSet.SetTexture(0, textureSet.GetTexture(0));
481 tempTextureSet.SetTexture(1, texture);
482 textureSet = tempTextureSet;
484 mImpl->mRenderer.RegisterProperty(DevelImageVisual::Property::AUXILIARY_IMAGE_ALPHA,
485 AUXILIARY_IMAGE_ALPHA_NAME,
486 mAuxiliaryImageAlpha);
488 mImpl->mRenderer.SetTextures(textureSet);
492 DALI_LOG_ERROR("The N patch image '%s' is not a valid N patch image\n", mImageUrl.GetUrl().c_str());
493 Actor actor = mPlacementActor.GetHandle();
494 Vector2 imageSize = Vector2::ZERO;
497 imageSize = actor.GetProperty(Actor::Property::SIZE).Get<Vector2>();
499 mFactoryCache.UpdateBrokenImageRenderer(mImpl->mRenderer, imageSize, false);
502 // Register transform properties
503 mImpl->mTransform.SetUniforms(mImpl->mRenderer, Direction::LEFT_TO_RIGHT);
506 Geometry NPatchVisual::GetNinePatchGeometry(VisualFactoryCache::GeometryType subType)
508 Geometry geometry = mFactoryCache.GetGeometry(subType);
511 if(DALI_LIKELY(VisualFactoryCache::NINE_PATCH_GEOMETRY == subType))
513 geometry = NPatchHelper::CreateGridGeometry(Uint16Pair(3, 3));
515 else if(VisualFactoryCache::NINE_PATCH_BORDER_GEOMETRY == subType)
517 geometry = NPatchHelper::CreateBorderGeometry(Uint16Pair(3, 3));
519 mFactoryCache.SaveGeometry(subType, geometry);
524 void NPatchVisual::SetResource()
526 const NPatchData* data;
527 if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data))
529 Geometry geometry = CreateGeometry();
530 Shader shader = CreateShader();
532 mImpl->mRenderer.SetGeometry(geometry);
533 mImpl->mRenderer.SetShader(shader);
535 if(RenderingAddOn::Get().IsValid())
537 RenderingAddOn::Get().SubmitRenderTask(mImpl->mRenderer, data->GetRenderingMap());
539 Actor actor = mPlacementActor.GetHandle();
542 ApplyTextureAndUniforms();
543 actor.AddRenderer(mImpl->mRenderer);
544 mPlacementActor.Reset();
547 // npatch loaded and ready to display
548 if(data->GetLoadingState() != NPatchData::LoadingState::LOAD_COMPLETE)
550 ResourceReady(Toolkit::Visual::ResourceStatus::FAILED);
554 ResourceReady(Toolkit::Visual::ResourceStatus::READY);
559 void NPatchVisual::LoadComplete(bool loadSuccess, TextureInformation textureInformation)
561 if(textureInformation.returnType == TextureUploadObserver::ReturnType::TEXTURE) // For the Url.
563 if(textureInformation.textureId != TextureManager::INVALID_TEXTURE_ID)
565 if(mId == NPatchData::INVALID_NPATCH_DATA_ID)
567 // Special case when mLoader.Load call LoadComplete function before mId setup.
568 // We can overwrite mId.
569 mId = static_cast<NPatchData::NPatchDataId>(textureInformation.textureId);
574 EnablePreMultipliedAlpha(textureInformation.preMultiplied);
577 else // For the AuxiliaryUrl : ReturnType::PIXEL_BUFFER
579 if(loadSuccess && textureInformation.url == mAuxiliaryUrl.GetUrl())
581 mAuxiliaryPixelBuffer = textureInformation.pixelBuffer;
582 mAuxiliaryResourceStatus = Toolkit::Visual::ResourceStatus::READY;
586 mAuxiliaryResourceStatus = Toolkit::Visual::ResourceStatus::FAILED;
589 // If auxiliaryUrl didn't required OR auxiliaryUrl load done.
590 if(!mAuxiliaryUrl.IsValid() || mAuxiliaryResourceStatus != Toolkit::Visual::ResourceStatus::PREPARING)
592 const NPatchData* data;
593 // and.. If Url loading done.
594 if(mImpl->mRenderer && mLoader.GetNPatchData(mId, data) && data->GetLoadingState() != NPatchData::LoadingState::LOADING)
601 } // namespace Internal
603 } // namespace Toolkit