(cd build ; cmake .. -DMODULE=$1 -G "$BUILDSYSTEM" ; $BUILDCMD -j7 )
}
-# Query main build to determine if we are enabling USD loader
-USD_LOADER_ENABLED=0
-(cd ../build/tizen ; cmake -LA -N 2>/dev/null | grep USD_LOADER_ENABLED | grep "\=ON")
-if [ $? -eq 0 ] ; then
- USD_LOADER_ENABLED=1
-fi
-
if [ -n "$1" ] ; then
echo BUILDING ONLY $1
build $1
for mod in `ls -1 src/ | grep -v CMakeList `
do
if [ $mod != 'common' ] && [ $mod != 'manual' ]; then
- if [ $mod != 'dali-usd-loader' ] || [[ $mod == 'dali-usd-loader' && $USD_LOADER_ENABLED == 1 ]]; then
- echo BUILDING $mod
- build $mod
- if [ $? -ne 0 ]; then echo "Build failed" ; exit 1; fi
- fi
+ echo BUILDING $mod
+ build $mod
+ if [ $? -ne 0 ]; then echo "Build failed" ; exit 1; fi
fi
done
fi
EOF
}
-modules=`ls -1 build/src | grep -v CMakeFiles | grep -v cmake_install.cmake | grep -v Makefile`
if [ $opt_modules == 1 ] ; then
modules= get_modules
ASCII_BOLD="\e[1m"
ASCII_RESET="\e[0m"
+modules=`ls -1 src/ | grep -v CMakeList | grep -v common | grep -v manual`
if [ -f summary.xml ] ; then unlink summary.xml ; fi
if [ $opt_tct == 1 ] ; then
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Vector3(0, 0, 1),
true,
false,
- false,
- false,
true,
false,
Scene3D::Material::AlphaModeType::MASK,
Vector3::ONE,
true,
true,
- false,
- false,
true,
false,
Scene3D::Material::AlphaModeType::OPAQUE,
DALI_TEST_EQUAL(md.mSpecularColorFactor, m.mSpecularColorFactor);
DALI_TEST_EQUAL(md.mNeedAlbedoTexture, m.mNeedAlbedoTexture);
DALI_TEST_EQUAL(md.mNeedMetallicRoughnessTexture, m.mNeedMetallicRoughnessTexture);
- DALI_TEST_EQUAL(md.mNeedMetallicTexture, m.mNeedMetallicTexture);
- DALI_TEST_EQUAL(md.mNeedRoughnessTexture, m.mNeedRoughnessTexture);
DALI_TEST_EQUAL(md.mNeedNormalTexture, m.mNeedNormalTexture);
DALI_TEST_EQUAL(md.mAlphaModeType, m.mAlphaModeType);
DALI_TEST_EQUAL(md.mIsOpaque, m.mIsOpaque);
sceneView.UseFramebuffer(true);
DALI_TEST_EQUALS(baseRenderTaskCount + 1u, taskList.GetTaskCount(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(0, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
DALI_TEST_EQUALS(SCENE_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
Scene3D::Light light = Scene3D::Light::New();
Dali::DevelActor::LookAt(light, Vector3(1.0f, 0.0f, 0.0f));
light.EnableShadow(true);
- tet_printf("Do not create rendertask until light is scene on\n");
+ tet_printf("Do not create rendertask until light is scene on");
DALI_TEST_EQUALS(baseRenderTaskCount + 1u, taskList.GetTaskCount(), TEST_LOCATION);
sceneView.Add(light);
- tet_printf("Create shadowmap rendertask after light is scene on\n");
+ tet_printf("Create shadowmap rendertask after light is scene on");
DALI_TEST_EQUALS(baseRenderTaskCount + 2u, taskList.GetTaskCount(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(0, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
DALI_TEST_EQUALS(SCENE_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, taskList.GetTask(baseRenderTaskCount + 1u).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(SHADOW_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount + 1u).GetOrderIndex(), TEST_LOCATION);
application.SendNotification();
- tet_printf("Check render task list sorted\n");
- DALI_TEST_EQUALS(INT32_MIN, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, taskList.GetTask(baseRenderTaskCount + 1u).GetOrderIndex(), TEST_LOCATION);
+ tet_printf("Check render task list sorted");
+ DALI_TEST_EQUALS(SHADOW_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(SCENE_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount + 1u).GetOrderIndex(), TEST_LOCATION);
light.EnableShadow(false);
- tet_printf("Check shadowmap rendertask removed\n");
-
+ tet_printf("Check shadowmap rendertask removed");
DALI_TEST_EQUALS(baseRenderTaskCount + 1u, taskList.GetTaskCount(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(0, taskList.GetTask(baseRenderTaskCount - 1u).GetOrderIndex(), TEST_LOCATION);
+ DALI_TEST_EQUALS(SCENE_ORDER_INDEX, taskList.GetTask(baseRenderTaskCount).GetOrderIndex(), TEST_LOCATION);
END_TEST;
}
\ No newline at end of file
DALI_TEST_EQUALS(panel.IsShadowReceiving(), false, TEST_LOCATION);
END_TEST;
-}
-
-int UtcDaliPanelRenderTaskOrdering(void)
-{
- ToolkitTestApplication application;
- tet_infoline("UtcDaliPanelRenderTaskOrdering");
-
- Integration::Scene scene = application.GetScene();
- RenderTaskList taskList = scene.GetRenderTaskList();
-
- uint32_t defaultTaskCount = taskList.GetTaskCount();
- RenderTask defaultRenderTask = taskList.GetTask(defaultTaskCount - 1);
- tet_printf("default Task Cnt : %d\n", defaultTaskCount);
-
- Scene3D::SceneView sceneView = Scene3D::SceneView::New();
- sceneView.UseFramebuffer(true);
- scene.Add(sceneView);
-
- uint32_t afterSceneViewTaskCount = taskList.GetTaskCount();
- RenderTask sceneViewRenderTask = taskList.GetTask(afterSceneViewTaskCount - 1);
- tet_printf("after SceneView Task cnt : %d\n", afterSceneViewTaskCount);
- DALI_TEST_CHECK(afterSceneViewTaskCount == defaultTaskCount + 1);
-
- Scene3D::Panel panel = Scene3D::Panel::New();
- sceneView.Add(panel);
-
- uint32_t afterPanelTaskCount = taskList.GetTaskCount();
- RenderTask panelRenderTask = taskList.GetTask(afterPanelTaskCount - 1);
- tet_printf("after Panel Task cnt : %d\n", afterPanelTaskCount);
- DALI_TEST_CHECK(afterPanelTaskCount == afterSceneViewTaskCount + 1);
-
- Control control1 = Control::New();
- control1.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- control1.SetProperty(Actor::Property::SIZE, Vector2(1.0f, 1.0f));
- control1.SetRenderEffect(BackgroundBlurEffect::New());
-
- panel.Add(control1);
-
- uint32_t afterBlurEffectTaskCount = taskList.GetTaskCount();
- RenderTask blurSourceRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 3);
- RenderTask blurHorizontalRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 2);
- RenderTask blurVerticalRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 1);
- tet_printf("after blurEffect Task cnt : %d\n", afterBlurEffectTaskCount);
- DALI_TEST_CHECK(afterBlurEffectTaskCount == afterPanelTaskCount + 3);
-
- tet_printf("defaultRenderTask order : %d\n", defaultRenderTask.GetOrderIndex());
- tet_printf("sceneViewRenderTask order : %d\n", sceneViewRenderTask.GetOrderIndex());
- tet_printf("panelRenderTask order : %d\n", panelRenderTask.GetOrderIndex());
- tet_printf("blurSourceRenderTask order : %d\n", blurSourceRenderTask.GetOrderIndex());
- tet_printf("blurHorizontalRenderTask order : %d\n", blurHorizontalRenderTask.GetOrderIndex());
- tet_printf("blurVerticalRenderTask order : %d\n", blurVerticalRenderTask.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, defaultRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, sceneViewRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(90, panelRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurSourceRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurHorizontalRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurVerticalRenderTask.GetOrderIndex(), TEST_LOCATION);
-
- application.SendNotification();
-
- tet_printf("defaultRenderTask order : %d\n", defaultRenderTask.GetOrderIndex());
- tet_printf("sceneViewRenderTask order : %d\n", sceneViewRenderTask.GetOrderIndex());
- tet_printf("panelRenderTask order : %d\n", panelRenderTask.GetOrderIndex());
- tet_printf("blurSourceRenderTask order : %d\n", blurSourceRenderTask.GetOrderIndex());
- tet_printf("blurHorizontalRenderTask order : %d\n", blurHorizontalRenderTask.GetOrderIndex());
- tet_printf("blurVerticalRenderTask order : %d\n", blurVerticalRenderTask.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, defaultRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 4, sceneViewRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 3, panelRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN, blurSourceRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, blurHorizontalRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 2, blurVerticalRenderTask.GetOrderIndex(), TEST_LOCATION);
-
- END_TEST;
-}
+}
\ No newline at end of file
#include <dali-scene3d/public-api/controls/scene-view/scene-view.h>
#include <dali/devel-api/actors/camera-actor-devel.h>
+
using namespace Dali;
using namespace Dali::Toolkit;
END_TEST;
}
-int UtcDaliSceneViewCornerRadius(void)
-{
- ToolkitTestApplication application;
-
- Scene3D::SceneView view = Scene3D::SceneView::New();
- application.GetScene().Add(view);
-
- DALI_TEST_EQUALS(view.GetProperty<Vector4>(Dali::Scene3D::SceneView::Property::CORNER_RADIUS), Vector4::ZERO, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<int>(Dali::Scene3D::SceneView::Property::CORNER_RADIUS_POLICY), static_cast<int>(Visual::Transform::Policy::ABSOLUTE), TEST_LOCATION);
-
- Vector4 expectCornerRadius = Vector4(0.5f, 0.3f, 0.2f, 0.0f);
- int expectCornerRadiusPolicy = static_cast<int>(Visual::Transform::Policy::RELATIVE);
-
- view.UseFramebuffer(true);
- view.SetProperty(Dali::Scene3D::SceneView::Property::CORNER_RADIUS, expectCornerRadius);
- view.SetProperty(Dali::Scene3D::SceneView::Property::CORNER_RADIUS_POLICY, expectCornerRadiusPolicy);
-
- DALI_TEST_EQUALS(view.GetProperty<Vector4>(Dali::Scene3D::SceneView::Property::CORNER_RADIUS), expectCornerRadius, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<int>(Dali::Scene3D::SceneView::Property::CORNER_RADIUS_POLICY), expectCornerRadiusPolicy, TEST_LOCATION);
-
- END_TEST;
-}
-
-int UtcDaliSceneViewBorderline(void)
-{
- ToolkitTestApplication application;
-
- Scene3D::SceneView view = Scene3D::SceneView::New();
- application.GetScene().Add(view);
-
- DALI_TEST_EQUALS(view.GetProperty<float>(Dali::Scene3D::SceneView::Property::BORDERLINE_WIDTH), 0.0f, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<Vector4>(Dali::Scene3D::SceneView::Property::BORDERLINE_COLOR), Color::BLACK, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<float>(Dali::Scene3D::SceneView::Property::BORDERLINE_OFFSET), 0.0f, TEST_LOCATION);
-
- float expectBorderlineWidth = 10.0f;
- Vector4 expectBorderlineColor = Vector4(0.5f, 0.3f, 0.2f, 0.1f);
- float expectBorderlineOffset = -1.0f;
-
- view.UseFramebuffer(true);
- view.SetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_WIDTH, expectBorderlineWidth);
- view.SetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_COLOR, expectBorderlineColor);
- view.SetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_OFFSET, expectBorderlineOffset);
-
- DALI_TEST_EQUALS(view.GetProperty<float>(Dali::Scene3D::SceneView::Property::BORDERLINE_WIDTH), expectBorderlineWidth, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<Vector4>(Dali::Scene3D::SceneView::Property::BORDERLINE_COLOR), expectBorderlineColor, TEST_LOCATION);
- DALI_TEST_EQUALS(view.GetProperty<float>(Dali::Scene3D::SceneView::Property::BORDERLINE_OFFSET), expectBorderlineOffset, TEST_LOCATION);
-
- END_TEST;
-}
-
namespace
{
static bool gCaptureFinishedCalled{false};
gCapturedImageUrl = capturedImageUrl;
}
-static int32_t gCapturedCount{0};
-static std::vector<int32_t> gCaptureIds;
-static std::vector<Toolkit::ImageUrl> gCapturedImageUrls;
+static int32_t gCapturedCount{0};
+static std::vector<int32_t> gCaptureIds;
+static std::vector<Toolkit::ImageUrl> gCapturedImageUrls;
void OnCaptureMultipleFinished(Scene3D::SceneView sceneView, int32_t captureId, const Toolkit::ImageUrl& capturedImageUrl)
{
view.Add(camera);
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
int32_t captureId = view.Capture(camera, Vector2(300, 300));
Toolkit::ImageUrl tempImageUrl = gCapturedImageUrl;
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
int32_t captureId2 = view.Capture(camera, Vector2(400, 400));
gCapturedCount = 0;
gCaptureIds.clear();
gCapturedImageUrls.clear();
- int32_t captureId = view.Capture(camera, Vector2(300, 300));
+ int32_t captureId = view.Capture(camera, Vector2(300, 300));
int32_t captureId2 = view.Capture(camera, Vector2(300, 300));
application.SendNotification();
view.Add(camera);
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
int32_t captureId = view.Capture(camera, Vector2(300, 300));
DALI_TEST_EQUALS(gCaptureId, captureId, TEST_LOCATION);
DALI_TEST_EQUALS(!!gCapturedImageUrl, false, TEST_LOCATION);
+
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
application.SendNotification();
view.Add(camera);
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
int32_t captureId = view.Capture(camera, Vector2(300, 300));
DALI_TEST_EQUALS(!!gCapturedImageUrl, false, TEST_LOCATION);
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
application.SendNotification();
view.Add(camera);
gCaptureFinishedCalled = false;
- gCaptureId = -1;
+ gCaptureId = -1;
gCapturedImageUrl.Reset();
int32_t captureId = view.Capture(camera, Vector2(300, 300));
END_TEST;
}
-
-int UtcDaliSceneViewRenderTaskOrdering(void)
-{
- ToolkitTestApplication application;
- tet_infoline("UtcDaliPanelRenderTaskOrdering");
-
- Integration::Scene scene = application.GetScene();
- RenderTaskList taskList = scene.GetRenderTaskList();
-
- uint32_t defaultTaskCount = taskList.GetTaskCount();
- RenderTask defaultRenderTask = taskList.GetTask(defaultTaskCount - 1);
- tet_printf("default Task Cnt : %d\n", defaultTaskCount);
-
- Scene3D::SceneView sceneView = Scene3D::SceneView::New();
- sceneView.UseFramebuffer(true);
- scene.Add(sceneView);
-
- uint32_t afterSceneViewTaskCount = taskList.GetTaskCount();
- RenderTask sceneViewRenderTask = taskList.GetTask(afterSceneViewTaskCount - 1);
- tet_printf("after SceneView Task cnt : %d\n", afterSceneViewTaskCount);
- DALI_TEST_CHECK(afterSceneViewTaskCount == defaultTaskCount + 1);
-
- Control control1 = Control::New();
- control1.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- control1.SetProperty(Actor::Property::SIZE, Vector2(1.0f, 1.0f));
- control1.SetRenderEffect(BackgroundBlurEffect::New());
-
- sceneView.Add(control1);
-
- uint32_t afterBlurEffectTaskCount = taskList.GetTaskCount();
- RenderTask blurSourceRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 3);
- RenderTask blurHorizontalRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 2);
- RenderTask blurVerticalRenderTask = taskList.GetTask(afterBlurEffectTaskCount - 1);
- tet_printf("after blurEffect Task cnt : %d\n", afterBlurEffectTaskCount);
- DALI_TEST_CHECK(afterBlurEffectTaskCount == afterSceneViewTaskCount + 3);
-
- tet_printf("defaultRenderTask order : %d\n", defaultRenderTask.GetOrderIndex());
- tet_printf("sceneViewRenderTask order : %d\n", sceneViewRenderTask.GetOrderIndex());
- tet_printf("blurSourceRenderTask order : %d\n", blurSourceRenderTask.GetOrderIndex());
- tet_printf("blurHorizontalRenderTask order : %d\n", blurHorizontalRenderTask.GetOrderIndex());
- tet_printf("blurVerticalRenderTask order : %d\n", blurVerticalRenderTask.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, defaultRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, sceneViewRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurSourceRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurHorizontalRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, blurVerticalRenderTask.GetOrderIndex(), TEST_LOCATION);
-
- application.SendNotification();
-
- tet_printf("defaultRenderTask order : %d\n", defaultRenderTask.GetOrderIndex());
- tet_printf("sceneViewRenderTask order : %d\n", sceneViewRenderTask.GetOrderIndex());
- tet_printf("blurSourceRenderTask order : %d\n", blurSourceRenderTask.GetOrderIndex());
- tet_printf("blurHorizontalRenderTask order : %d\n", blurHorizontalRenderTask.GetOrderIndex());
- tet_printf("blurVerticalRenderTask order : %d\n", blurVerticalRenderTask.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, defaultRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 3, sceneViewRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN, blurSourceRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, blurHorizontalRenderTask.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 2, blurVerticalRenderTask.GetOrderIndex(), TEST_LOCATION);
-
- END_TEST;
-}
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
{ShaderOption::Type::THREE_TEXTURE, ShaderOption::Type::BASE_COLOR_TEXTURE}},
{//3
[](ShaderParameters& p) {
- p.materialDefinition.mFlags |= MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS;
p.materialDefinition.mTextureStages.push_back({MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS, {}});
},
{ShaderOption::Type::THREE_TEXTURE, ShaderOption::Type::METALLIC_ROUGHNESS_TEXTURE}},
{
ToolkitTestApplication application;
- auto control = Control::New();
-
- auto role_none = DevelControl::AccessibilityRole::NONE;
+ auto control = Control::New();
auto role_unknown = Dali::Accessibility::Role::UNKNOWN;
auto role_pushbutton = Dali::Accessibility::Role::PUSH_BUTTON;
- DALI_TEST_EQUALS(role_none, control.GetProperty(DevelControl::Property::ACCESSIBILITY_ROLE).Get<DevelControl::AccessibilityRole>(), TEST_LOCATION);
+ DALI_TEST_EQUALS(role_unknown, control.GetProperty(DevelControl::Property::ACCESSIBILITY_ROLE).Get<Dali::Accessibility::Role>(), TEST_LOCATION);
auto accessible = Dali::Accessibility::Accessible::Get(control);
DALI_TEST_EQUALS(role_unknown, accessible->GetRole(), TEST_LOCATION);
DALI_TEST_EQUALS(static_cast<uint32_t>(Dali::Accessibility::Role::PAGE_TAB_LIST), TestGetRole(accessible->GetAddress()), TEST_LOCATION);
control.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::TEXT);
- DALI_TEST_EQUALS(static_cast<uint32_t>(Dali::Accessibility::Role::LABEL), TestGetRole(accessible->GetAddress()), TEST_LOCATION);
+ DALI_TEST_EQUALS(static_cast<uint32_t>(Dali::Accessibility::Role::TEXT), TestGetRole(accessible->GetAddress()), TEST_LOCATION);
control.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::TOGGLE_BUTTON);
DALI_TEST_EQUALS(static_cast<uint32_t>(Dali::Accessibility::Role::TOGGLE_BUTTON), TestGetRole(accessible->GetAddress()), TEST_LOCATION);
highlightable = control.GetProperty<bool>(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE);
DALI_TEST_EQUALS(highlightable, false, TEST_LOCATION);
- auto accessible = Dali::Accessibility::Accessible::Get(control);
+ auto q = Dali::Accessibility::Accessible::Get(control);
Dali::Accessibility::TestEnableSC(true);
- auto states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
+ auto states_by_bridge = Dali::Accessibility::States{TestGetStates(q->GetAddress())};
DALI_TEST_CHECK(!states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
control.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
DALI_TEST_EQUALS(Property::BOOLEAN, control.GetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).GetType(), TEST_LOCATION);
DALI_TEST_EQUALS(true, control.GetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).Get<bool>(), TEST_LOCATION);
- states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
+ states_by_bridge = Dali::Accessibility::States{TestGetStates(q->GetAddress())};
DALI_TEST_CHECK(states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
control.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false);
DALI_TEST_EQUALS(Property::BOOLEAN, control.GetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).GetType(), TEST_LOCATION);
DALI_TEST_EQUALS(false, control.GetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE).Get<bool>(), TEST_LOCATION);
- states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
+ states_by_bridge = Dali::Accessibility::States{TestGetStates(q->GetAddress())};
DALI_TEST_CHECK(!states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
- Dali::Accessibility::TestEnableSC(false);
-
- END_TEST;
-}
-
-int UtcDaliControlAccessibilityHighlightableV2(void)
-{
- ToolkitTestApplication application;
- auto control = Control::New();
- auto accessible = Dali::Accessibility::Accessible::Get(control);
-
- Dali::Accessibility::TestEnableSC(true);
-
- auto states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
- // Is not highlightable if no role is set
- DALI_TEST_CHECK(!states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
-
- // Is highlightable by default if V2 role is set and is not Role::None
+ // Highlightable state is set if V2 role is set and is not Role::None
control.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::CONTAINER);
- states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
- DALI_TEST_CHECK(states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
-
- // Returns explicitly set highlightable property: false
- control.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, false);
- states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
- DALI_TEST_CHECK(!states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
-
- // Returns explicitly set highlightable property: true
- control.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
- states_by_bridge = Dali::Accessibility::States{TestGetStates(accessible->GetAddress())};
+ states_by_bridge = Dali::Accessibility::States{TestGetStates(q->GetAddress())};
DALI_TEST_CHECK(states_by_bridge[Dali::Accessibility::State::HIGHLIGHTABLE]);
Dali::Accessibility::TestEnableSC(false);
END_TEST;
}
-
-enum class MatchType : int32_t
-{
- INVALID,
- ALL,
- ANY,
- NONE,
- EMPTY
-};
-
-enum class SortOrder : uint32_t
-{
- INVALID,
- CANONICAL,
- FLOW,
- TAB,
- REVERSE_CANONICAL,
- REVERSE_FLOW,
- REVERSE_TAB,
- LAST_DEFINED
-};
-
-static bool TestTouchCallback(Actor, const TouchEvent&)
-{
- return true;
-}
-
-class TestMatcheableView
-{
-private:
- Actor MakeClickableActor()
- {
- auto actor = Control::New();
- actor.SetProperty(Actor::Property::SENSITIVE, true);
- actor.SetProperty(DevelActor::Property::USER_INTERACTION_ENABLED, true);
- actor.TouchedSignal().Connect(TestTouchCallback);
- return actor;
- }
-
- Actor MakeNonClickableActor()
- {
- auto actor = Control::New();
- actor.SetProperty(Actor::Property::SENSITIVE, false);
- return actor;
- }
-
- Actor MakeContainer(bool isClickable, std::string label)
- {
- Actor container = isClickable ? MakeClickableActor() : MakeNonClickableActor();
- Vector4 color(0.5f, 0.6f, 0.5f, 1.0f);
- container.SetProperty(Actor::Property::COLOR, color);
- container.SetProperty(Actor::Property::VISIBLE, true);
-
- // button
- auto button = PushButton::New();
- button.SetProperty(Actor::Property::POSITION, Vector2(0.f, 0.f));
- button.SetProperty(Actor::Property::SIZE, Vector2(10.f, 10.f));
- button.SetProperty(Actor::Property::VISIBLE, true);
- container.Add(button);
-
- // text label
- auto text = TextLabel::New(label);
- text.SetProperty(Actor::Property::VISIBLE, true);
- container.Add(text);
-
- return container;
- };
-
-public:
- TestMatcheableView()
- {
- view = TableView::New(N, N); // N by N grid.
- view.SetProperty(Actor::Property::SIZE, Vector2(480.0f, 800.0f)); // full screen
-
- for(int i = 0; i < N; ++i)
- {
- for(int j = 0; j < N; ++j)
- {
- bool isClickable = (i * N + j) % 2;
- std::string label = "test_" + std::to_string(i) + "_" + std::to_string(j);
- view.AddChild(MakeContainer(isClickable, std::move(label)), TableView::CellPosition(i, j));
- }
- }
- }
-
- TableView view;
- static const int N{48};
-};
-
-static Accessibility::Collection::MatchRule GetMatchRule(std::vector<Accessibility::State> states, std::vector<Accessibility::Role> roles)
-{
- Accessibility::States statesRule;
- MatchType stateMatchType = MatchType::INVALID;
- std::array<int32_t, 2> statesConverted{0, 0};
- if(!states.empty())
- {
- for(auto state : states)
- {
- statesRule[state] = true;
- }
- const auto statesRaw = statesRule.GetRawData();
- statesConverted = {static_cast<int32_t>(statesRaw[0]), static_cast<int32_t>(statesRaw[1])};
- stateMatchType = MatchType::ALL;
- }
-
- Accessibility::EnumBitSet<Accessibility::Role, Accessibility::Role::MAX_COUNT> rolesRule;
- MatchType roleMatchType = MatchType::INVALID;
- std::array<int32_t, 4> rolesConverted{0, 0, 0, 0};
- if(!roles.empty())
- {
- for(auto role : roles)
- {
- rolesRule[role] = true;
- }
- const auto rolesRaw = rolesRule.GetRawData();
- rolesConverted = {static_cast<int32_t>(rolesRaw[0]), static_cast<int32_t>(rolesRaw[1]), static_cast<int32_t>(rolesRaw[2]), static_cast<int32_t>(rolesRaw[3])};
- roleMatchType = MatchType::ALL;
- }
-
- return {
- std::move(statesConverted),
- static_cast<int32_t>(stateMatchType),
- {},
- static_cast<int32_t>(MatchType::INVALID),
- std::move(rolesConverted),
- static_cast<int32_t>(roleMatchType),
- {},
- static_cast<int32_t>(MatchType::INVALID),
- false};
-}
-
-int UtcDaliGetMatches(void)
-{
- ToolkitTestApplication application;
-
- Dali::Accessibility::TestEnableSC(true);
-
- application.GetScene().Add(TestMatcheableView().view);
- application.SendNotification();
- application.Render();
-
- auto appAccessible = Accessibility::Bridge::GetCurrentBridge()->GetApplication();
- DALI_TEST_CHECK(appAccessible);
- auto collection = dynamic_cast<Accessibility::Collection*>(appAccessible);
- DALI_TEST_CHECK(collection);
-
- auto rule = GetMatchRule({Accessibility::State::SENSITIVE, Accessibility::State::SHOWING}, {});
- auto results = collection->GetMatches(std::move(rule), static_cast<uint32_t>(SortOrder::CANONICAL), 0);
- const auto numContainers = TestMatcheableView::N * TestMatcheableView::N;
- DALI_TEST_CHECK(results.size() == 1 + numContainers / 2 + numContainers); // 1 (root) + num(half of containers) + num(buttons);
-
- Dali::Accessibility::TestEnableSC(false);
-
- END_TEST;
-}
-
-int UtcDaliGetMatchesInMatches(void)
-{
- ToolkitTestApplication application;
-
- Dali::Accessibility::TestEnableSC(true);
-
- application.GetScene().Add(TestMatcheableView().view);
- application.SendNotification();
- application.Render();
-
- auto appAccessible = Accessibility::Bridge::GetCurrentBridge()->GetApplication();
- DALI_TEST_CHECK(appAccessible);
- auto collection = dynamic_cast<Accessibility::Collection*>(appAccessible);
- DALI_TEST_CHECK(collection);
-
- auto rule1 = GetMatchRule({Accessibility::State::SENSITIVE, Accessibility::State::SHOWING}, {});
- auto rule2 = GetMatchRule({Accessibility::State::SHOWING}, {Accessibility::Role::LABEL});
- auto results = collection->GetMatchesInMatches(std::move(rule1), std::move(rule2), static_cast<uint32_t>(SortOrder::CANONICAL), 0, 0);
-
- const auto numLabels = TestMatcheableView::N * TestMatcheableView::N;
- DALI_TEST_CHECK(results.size() == numLabels); // text labels
-
- Dali::Accessibility::TestEnableSC(false);
-
- END_TEST;
-}
return handle;
}
- OffScreenRenderable::Type GetOffScreenRenderableType() override
- {
- return OffScreenRenderable::Type::NONE;
- }
-
- void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) override
- {}
-
protected:
TestRenderEffectImpl()
: mOnActivated(false)
float expectedHeight = 100.0f;
label.SetProperty(DevelTextLabel::Property::RENDER_MODE, DevelTextLabel::Render::ASYNC_AUTO);
- label.SetProperty(TextLabel::Property::TEXT, "H");
+ label.SetProperty(TextLabel::Property::TEXT, "Hello world Hello world");
label.SetProperty(Actor::Property::SIZE, Vector2(expectedWidth, expectedHeight));
label.SetProperty(TextLabel::Property::POINT_SIZE, 12);
label.SetProperty(TextLabel::Property::MULTI_LINE, true);
expectedHeight = 50.0f;
float dummySize = 100.0f;
- std::string text = "L";
+ std::string text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit.";
dummy1.SetProperty(TextLabel::Property::TEXT, text);
dummy2.SetProperty(TextLabel::Property::TEXT, text);
label.SetProperty(TextLabel::Property::TEXT, text);
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ /*
+ * Copyright (c) 2022 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/devel-api/adaptor-framework/style-monitor.h>
+#include <iostream>
+#include <fstream>
+#include <sstream>
+#include <stdlib.h>
#include <dali-toolkit-test-suite-utils.h>
#include <dali-toolkit/dali-toolkit.h>
+#include <dali/integration-api/events/touch-event-integ.h>
#include <dali-toolkit/devel-api/builder/builder.h>
+#include <test-button.h>
+#include <test-animation-data.h>
+#include <toolkit-style-monitor.h>
+#include <dummy-control.h>
#include <dali-toolkit/devel-api/controls/control-devel.h>
-#include <dali-toolkit/devel-api/styling/style-manager-devel.h>
-#include <dali-toolkit/devel-api/visual-factory/visual-base.h>
#include <dali-toolkit/devel-api/visual-factory/visual-factory.h>
+#include <dali-toolkit/devel-api/visual-factory/visual-base.h>
+#include <dali-toolkit/devel-api/styling/style-manager-devel.h>
#include <dali/integration-api/events/key-event-integ.h>
-#include <dali/integration-api/events/touch-event-integ.h>
-#include <dummy-control.h>
-#include <stdlib.h>
-#include <test-animation-data.h>
-#include <test-button.h>
-#include <toolkit-style-monitor.h>
-#include <fstream>
-#include <iostream>
-#include <sstream>
// for Internal::StyleManager
#include <dali-toolkit/internal/styling/style-manager-impl.h>
} // anonymous namespace
+
+
+
void dali_style_manager_startup(void)
{
test_return_value = TET_UNDEF;
test_return_value = TET_PASS;
}
-namespace
-{
-Visual::Base CheckVisual(Impl::DummyControl& dummyImpl, Property::Index visualId, int type, const char* location)
+
+Visual::Base CheckVisual( Impl::DummyControl& dummyImpl, Property::Index visualId, int type, const char* location )
{
- DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(visualId), true, location);
- Visual::Base visual = dummyImpl.GetVisual(visualId);
- DALI_TEST_EQUALS((bool)visual, true, location);
- Property::Map map;
- visual.CreatePropertyMap(map);
- Property::Value* value = map.Find(Toolkit::Visual::Property::TYPE);
- DALI_TEST_EQUALS(value != NULL, true, location);
-
- int visualType;
- value->Get(visualType);
- DALI_TEST_EQUALS(visualType, type, location);
- return visual;
+ DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(visualId), true, location);
+ Visual::Base visual = dummyImpl.GetVisual(visualId);
+ DALI_TEST_EQUALS( (bool)visual, true, location );
+ Property::Map map;
+ visual.CreatePropertyMap( map );
+ Property::Value* value = map.Find( Toolkit::Visual::Property::TYPE );
+ DALI_TEST_EQUALS( value != NULL, true, location );
+
+ int visualType;
+ value->Get( visualType );
+ DALI_TEST_EQUALS( visualType, type, location );
+ return visual;
}
-Integration::Bitmap* CreateBitmap(unsigned int imageWidth, unsigned int imageHeight, unsigned int initialColor, Pixel::Format pixelFormat)
+
+Integration::Bitmap* CreateBitmap( unsigned int imageWidth, unsigned int imageHeight, unsigned int initialColor, Pixel::Format pixelFormat )
{
- Integration::Bitmap* bitmap = Integration::Bitmap::New(Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_RETAIN);
- Integration::PixelBuffer* pixbuffer = bitmap->GetPackedPixelsProfile()->ReserveBuffer(pixelFormat, imageWidth, imageHeight, imageWidth, imageHeight);
- unsigned int bytesPerPixel = GetBytesPerPixel(pixelFormat);
+ Integration::Bitmap* bitmap = Integration::Bitmap::New( Integration::Bitmap::BITMAP_2D_PACKED_PIXELS, ResourcePolicy::OWNED_RETAIN );
+ Integration::PixelBuffer* pixbuffer = bitmap->GetPackedPixelsProfile()->ReserveBuffer( pixelFormat, imageWidth, imageHeight, imageWidth, imageHeight );
+ unsigned int bytesPerPixel = GetBytesPerPixel( pixelFormat );
- memset(pixbuffer, initialColor, imageHeight * imageWidth * bytesPerPixel);
+ memset( pixbuffer, initialColor, imageHeight * imageWidth * bytesPerPixel );
return bitmap;
}
-Integration::ResourcePointer CustomizeNinePatch(ToolkitTestApplication& application,
- unsigned int ninePatchImageWidth,
- unsigned int ninePatchImageHeight)
+Integration::ResourcePointer CustomizeNinePatch( ToolkitTestApplication& application,
+ unsigned int ninePatchImageWidth,
+ unsigned int ninePatchImageHeight)
{
TestPlatformAbstraction& platform = application.GetPlatform();
Pixel::Format pixelFormat = Pixel::RGBA8888;
tet_infoline("Create Bitmap");
- platform.SetClosestImageSize(Vector2(ninePatchImageWidth, ninePatchImageHeight));
- Integration::Bitmap* bitmap = CreateBitmap(ninePatchImageWidth, ninePatchImageHeight, 0xFF, pixelFormat);
+ platform.SetClosestImageSize(Vector2( ninePatchImageWidth, ninePatchImageHeight));
+ Integration::Bitmap* bitmap = CreateBitmap( ninePatchImageWidth, ninePatchImageHeight, 0xFF, pixelFormat );
tet_infoline("Getting resource");
Integration::ResourcePointer resourcePtr(bitmap);
- platform.SetSynchronouslyLoadedResource(resourcePtr);
+ platform.SetSynchronouslyLoadedResource( resourcePtr);
return resourcePtr;
}
-} // anonymous namespace
int UtcDaliStyleManagerConstructorP(void)
{
tet_infoline(" UtcDaliStyleManagerConstructorP");
StyleManager styleManager;
- DALI_TEST_CHECK(!styleManager);
+ DALI_TEST_CHECK( !styleManager);
END_TEST;
}
ToolkitTestApplication application;
StyleManager styleManager = StyleManager::Get();
- StyleManager copyOfStyleManager(styleManager);
+ StyleManager copyOfStyleManager( styleManager );
- DALI_TEST_CHECK(copyOfStyleManager);
+ DALI_TEST_CHECK( copyOfStyleManager );
END_TEST;
}
{
ToolkitTestApplication application;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
StyleManager copyOfStyleManager = styleManager;
- DALI_TEST_CHECK(copyOfStyleManager);
- DALI_TEST_CHECK(copyOfStyleManager == styleManager);
+ DALI_TEST_CHECK( copyOfStyleManager );
+ DALI_TEST_CHECK( copyOfStyleManager == styleManager );
END_TEST;
}
// Register Type
TypeInfo type;
- type = TypeRegistry::Get().GetTypeInfo("StyleManager");
- DALI_TEST_CHECK(type);
+ type = TypeRegistry::Get().GetTypeInfo( "StyleManager" );
+ DALI_TEST_CHECK( type );
BaseHandle handle = type.CreateInstance();
- DALI_TEST_CHECK(handle);
+ DALI_TEST_CHECK( handle );
StyleManager manager;
END_TEST;
}
+
namespace
{
class StyleChangedSignalChecker : public ConnectionTracker
void Reset()
{
- signalCount = 0;
+ signalCount =0;
}
public:
{
ToolkitTestApplication application;
- tet_infoline("Testing StyleManager ApplyTheme");
+ tet_infoline( "Testing StyleManager ApplyTheme" );
const char* json1 =
"{\n"
"}\n";
// Add 2 buttons to test how many times the signal is sent
- Test::TestButton testButton = Test::TestButton::New();
+ Test::TestButton testButton = Test::TestButton::New();
Test::TestButton testButton2 = Test::TestButton::New();
- application.GetScene().Add(testButton);
- application.GetScene().Add(testButton2);
+ application.GetScene().Add( testButton );
+ application.GetScene().Add( testButton2 );
StyleChangedSignalChecker styleChangedSignalHandler;
StyleChangedSignalChecker styleChangedSignalHandler2;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
// To ensure we make VisualFactory
VisualFactory factory = VisualFactory::Get();
Property::Map propertyMap;
- propertyMap.Insert(Toolkit::Visual::Property::TYPE, Visual::TEXT);
- Visual::Base textVisual = factory.CreateVisual(propertyMap);
+ propertyMap.Insert( Toolkit::Visual::Property::TYPE, Visual::TEXT );
+ Visual::Base textVisual = factory.CreateVisual( propertyMap );
// Render and notify
application.SendNotification();
Test::StyleMonitor::SetThemeFileOutput(themeFile, json1);
StyleManager::Get().ApplyTheme(themeFile);
- Property::Value bgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value fgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
+ Property::Value bgColor( testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR) );
+ Property::Value fgColor( testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR) );
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION );
tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
tet_infoline("Override the background property");
- testButton.SetProperty(Test::TestButton::Property::BACKGROUND_COLOR, Color::GREEN);
+ testButton.SetProperty( Test::TestButton::Property::BACKGROUND_COLOR, Color::GREEN );
bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION );
// Render and notify
application.SendNotification();
fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
tet_infoline("Check that the property is changed");
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION );
tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
- tet_infoline("Load a different stylesheet");
+ tet_infoline( "Load a different stylesheet");
tet_infoline("Apply the new style");
std::string themeFile2("ThemeTwo");
fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
tet_infoline("Check that the properties change, but the signal gets sent only once");
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::RED), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::CYAN), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::RED), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::CYAN), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
END_TEST;
}
-int UtcDaliStyleManagerApplyThemeN(void)
-{
- ToolkitTestApplication application;
-
- tet_infoline("Testing StyleManager ApplyTheme with invalid json");
-
- const char* json1 =
- "{\n"
- " \"constants\":\n"
- " {\n"
- " \"CONFIG_SCRIPT_LOG_LEVEL\":\"Verbose\"\n"
- " },\n"
- " \"styles\":\n"
- " {\n"
- " \"testbutton\":\n"
- " {\n"
- " \"backgroundColor\":[1.0,1.0,0.0,1.0],\n"
- " \"foregroundColor\":[0.0,0.0,1.0,1.0]\n"
- " }\n"
- " }\n"
- "}\n";
-
- const char* jsonInvalid =
- "{\n"
- " \"styles\":\n"
- " {\n"
- " \"testbutton\":\n"
- " {\n"
- " \"backgroundColor\":[1.0,0.0,0.0,1.0],\n"
- " \"foregroundColor\":[0.0,1.0,1.0,1.0],\n" /// Deliberate Error: trailing comma
- " }\n"
- " }\n"
- "}\n";
-
- // Add 2 buttons to test how many times the signal is sent
- Test::TestButton testButton = Test::TestButton::New();
- Test::TestButton testButton2 = Test::TestButton::New();
- application.GetScene().Add(testButton);
- application.GetScene().Add(testButton2);
- StyleChangedSignalChecker styleChangedSignalHandler;
- StyleChangedSignalChecker styleChangedSignalHandler2;
- StyleManager styleManager = StyleManager::Get();
-
- styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
-
- // To ensure we make VisualFactory
- VisualFactory factory = VisualFactory::Get();
- Property::Map propertyMap;
- propertyMap.Insert(Toolkit::Visual::Property::TYPE, Visual::TEXT);
- Visual::Base textVisual = factory.CreateVisual(propertyMap);
-
- // Render and notify
- application.SendNotification();
- application.Render();
-
- tet_infoline("Apply the style");
-
- std::string themeFile("ThemeOne");
- Test::StyleMonitor::SetThemeFileOutput(themeFile, json1);
- StyleManager::Get().ApplyTheme(themeFile);
-
- Property::Value bgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value fgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
-
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
-
- tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
-
- tet_infoline("Override the background property");
- testButton.SetProperty(Test::TestButton::Property::BACKGROUND_COLOR, Color::GREEN);
- bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
- fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
-
- // Render and notify
- application.SendNotification();
- application.Render();
-
- tet_infoline("Apply the style again");
-
- styleChangedSignalHandler.signalCount = 0;
- StyleManager::Get().ApplyTheme(themeFile);
-
- bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
- fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
-
- tet_infoline("Check that the property is changed");
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
- tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
-
- tet_infoline("Load a different stylesheet, with broken json file");
-
- tet_infoline("Apply the new style");
- std::string themeFile2("ThemeTwo");
- Test::StyleMonitor::SetThemeFileOutput(themeFile2, jsonInvalid);
-
- styleChangedSignalHandler.signalCount = 0;
- StyleManager::Get().ApplyTheme(themeFile2);
-
- bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
- fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
-
- tet_infoline("Check that the properties not be change, but the signal gets sent only once (due to the default theme applied)");
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
-
- tet_infoline("Override the background property");
- testButton.SetProperty(Test::TestButton::Property::BACKGROUND_COLOR, Color::GREEN);
- bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
- fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
-
- tet_infoline("Apply the broken style again");
-
- styleChangedSignalHandler.signalCount = 0;
- StyleManager::Get().ApplyTheme(themeFile2);
-
- bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
- fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
-
- tet_infoline("Check that the property is not be changed");
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
- tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 0, TEST_LOCATION);
-
- END_TEST;
-}
int UtcDaliStyleManagerApplyDefaultTheme(void)
{
- tet_infoline("Testing StyleManager ApplyTheme");
+ tet_infoline( "Testing StyleManager ApplyTheme" );
const char* defaultTheme =
"{\n"
std::string filepath(TEST_RESOURCE_DIR "");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme);
ToolkitTestApplication application;
Test::TestButton testButton = Test::TestButton::New();
- application.GetScene().Add(testButton);
+ application.GetScene().Add( testButton );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
application.Render();
// Get the default:
- Property::Value defaultBgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value defaultFgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
+ Property::Value defaultBgColor( testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR) );
+ Property::Value defaultFgColor( testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR) );
tet_infoline("Apply the style");
Test::StyleMonitor::SetThemeFileOutput(themeFile, appTheme);
StyleManager::Get().ApplyTheme(themeFile);
- Property::Value bgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value fgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
+ Property::Value bgColor( testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR) );
+ Property::Value fgColor( testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR) );
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::MAGENTA), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::MAGENTA), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::GREEN), 0.001, TEST_LOCATION );
tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
tet_infoline("Revert the style");
styleChangedSignalHandler.signalCount = 0;
fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
tet_infoline("Check that the property is reverted");
- DALI_TEST_EQUALS(bgColor, defaultBgColor, 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, defaultFgColor, 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, defaultBgColor, 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, defaultFgColor, 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION );
tet_infoline("Testing that the signal handler is called only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
END_TEST;
}
+
int UtcDaliStyleManagerSetStyleConstantP(void)
{
ToolkitTestApplication application;
- tet_infoline(" UtcDaliStyleManagerSetStyleConstantP");
+ tet_infoline( " UtcDaliStyleManagerSetStyleConstantP" );
StyleManager manager = StyleManager::Get();
- std::string key("key");
- Property::Value value(100);
+ std::string key( "key" );
+ Property::Value value( 100 );
- manager.SetStyleConstant(key, value);
+ manager.SetStyleConstant( key, value );
Property::Value returnedValue;
- manager.GetStyleConstant(key, returnedValue);
+ manager.GetStyleConstant( key, returnedValue );
- DALI_TEST_CHECK(value.Get<int>() == returnedValue.Get<int>());
+ DALI_TEST_CHECK( value.Get<int>() == returnedValue.Get<int>() );
END_TEST;
}
+
int UtcDaliStyleManagerGetStyleConstantP(void)
{
ToolkitTestApplication application;
- tet_infoline(" UtcDaliStyleManagerGetStyleConstantP");
+ tet_infoline( " UtcDaliStyleManagerGetStyleConstantP" );
StyleManager manager = StyleManager::Get();
- std::string key("key");
- Property::Value value(100);
+ std::string key( "key" );
+ Property::Value value( 100 );
- manager.SetStyleConstant(key, value);
+ manager.SetStyleConstant( key, value );
Property::Value returnedValue;
- manager.GetStyleConstant(key, returnedValue);
+ manager.GetStyleConstant( key, returnedValue );
- DALI_TEST_CHECK(value.Get<int>() == returnedValue.Get<int>());
+ DALI_TEST_CHECK( value.Get<int>() == returnedValue.Get<int>() );
END_TEST;
}
{
ToolkitTestApplication application;
- tet_infoline(" UtcDaliStyleManagerGetStyleConstantN");
+ tet_infoline( " UtcDaliStyleManagerGetStyleConstantN" );
StyleManager manager = StyleManager::Get();
- std::string key2("key2");
+ std::string key2( "key2" );
Property::Value returnedValue2;
- DALI_TEST_CHECK(!manager.GetStyleConstant(key2, returnedValue2));
+ DALI_TEST_CHECK( !manager.GetStyleConstant( key2, returnedValue2 ) );
END_TEST;
}
{
ToolkitTestApplication application;
- tet_infoline("UtcDaliStyleManagerApplyStyle - test that a style can be applied to a single button");
+ tet_infoline( "UtcDaliStyleManagerApplyStyle - test that a style can be applied to a single button" );
const char* json1 =
"{\n"
"}\n";
// Add 2 buttons
- Test::TestButton testButton = Test::TestButton::New();
+ Test::TestButton testButton = Test::TestButton::New();
Test::TestButton testButton2 = Test::TestButton::New();
- application.GetScene().Add(testButton);
- application.GetScene().Add(testButton2);
+ application.GetScene().Add( testButton );
+ application.GetScene().Add( testButton2 );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
application.SendNotification();
application.Render();
- Property::Value themedBgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value themedFgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
+ Property::Value themedBgColor( testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR) );
+ Property::Value themedFgColor( testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR) );
// Apply the style to the test button:
std::string themeFile2("ThemeTwo");
Test::StyleMonitor::SetThemeFileOutput(themeFile2, json2);
- styleManager.ApplyStyle(testButton, themeFile2, "testbutton");
+ styleManager.ApplyStyle( testButton, themeFile2, "testbutton" );
tet_infoline("Check that the properties change for the first button");
Property::Value bgColor = testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
Property::Value fgColor = testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
- DALI_TEST_EQUALS(bgColor, Property::Value(Color::RED), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, Property::Value(Color::CYAN), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, Property::Value(Color::RED), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, Property::Value(Color::CYAN), 0.001, TEST_LOCATION );
- DALI_TEST_NOT_EQUALS(bgColor, themedBgColor, 0.001, TEST_LOCATION);
- DALI_TEST_NOT_EQUALS(fgColor, themedFgColor, 0.001, TEST_LOCATION);
+ DALI_TEST_NOT_EQUALS( bgColor, themedBgColor, 0.001, TEST_LOCATION );
+ DALI_TEST_NOT_EQUALS( fgColor, themedFgColor, 0.001, TEST_LOCATION );
tet_infoline("Check that the properties remain the same for the second button");
bgColor = testButton2.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR);
fgColor = testButton2.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR);
- DALI_TEST_EQUALS(bgColor, themedBgColor, 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(fgColor, themedFgColor, 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( bgColor, themedBgColor, 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( fgColor, themedFgColor, 0.001, TEST_LOCATION );
END_TEST;
}
+
int UtcDaliStyleManagerIncludeStyleP(void)
{
ToolkitTestApplication application;
- tet_infoline("UtcDaliStyleManagerIncludeStyle - test that style sheet inclusion works");
+ tet_infoline( "UtcDaliStyleManagerIncludeStyle - test that style sheet inclusion works" );
const char* json1 =
"{\n"
"}\n";
// Add 2 buttons
- Test::TestButton testButton = Test::TestButton::New();
+ Test::TestButton testButton = Test::TestButton::New();
Test::TestButton testButton2 = Test::TestButton::New();
- application.GetScene().Add(testButton);
- application.GetScene().Add(testButton2);
+ application.GetScene().Add( testButton );
+ application.GetScene().Add( testButton2 );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
application.SendNotification();
application.Render();
- Property::Value themedBgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value themedFgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
+ Property::Value themedBgColor( testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR) );
+ Property::Value themedFgColor( testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR) );
- DALI_TEST_EQUALS(themedBgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(themedFgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( themedBgColor, Property::Value(Color::YELLOW), 0.001, TEST_LOCATION );
+ DALI_TEST_EQUALS( themedFgColor, Property::Value(Color::BLUE), 0.001, TEST_LOCATION );
END_TEST;
}
+
int UtcDaliStyleManagerIncludeStyleN(void)
{
ToolkitTestApplication application;
- tet_infoline("UtcDaliStyleManagerIncludeStyle - test that style sheet inclusion works, but included stylesheet is bad json");
+ tet_infoline( "UtcDaliStyleManagerIncludeStyle - test that style sheet inclusion works, but included stylesheet is bad json" );
const char* json1 =
"{\n"
"}\n";
// Add 2 buttons
- Test::TestButton testButton = Test::TestButton::New();
+ Test::TestButton testButton = Test::TestButton::New();
Test::TestButton testButton2 = Test::TestButton::New();
-
- // Set some property, to avoid random value returns.
- testButton.SetProperty(Test::TestButton::Property::BACKGROUND_COLOR, Color::WHITE);
- testButton.SetProperty(Test::TestButton::Property::FOREGROUND_COLOR, Color::BLACK);
-
- application.GetScene().Add(testButton);
- application.GetScene().Add(testButton2);
+ application.GetScene().Add( testButton );
+ application.GetScene().Add( testButton2 );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleManager styleManager = StyleManager::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
std::string themeFile("ThemeOne");
Test::StyleMonitor::SetThemeFileOutput(themeFile, json1);
- styleManager.ApplyTheme(themeFile);
-
- // Render and notify
- application.SendNotification();
- application.Render();
-
- Property::Value themedBgColor(testButton.GetProperty(Test::TestButton::Property::BACKGROUND_COLOR));
- Property::Value themedFgColor(testButton.GetProperty(Test::TestButton::Property::FOREGROUND_COLOR));
-
- tet_infoline("Test that broken json didnt' give any effort");
-
- DALI_TEST_EQUALS(themedBgColor, Property::Value(Color::WHITE), 0.001, TEST_LOCATION);
- DALI_TEST_EQUALS(themedFgColor, Property::Value(Color::BLACK), 0.001, TEST_LOCATION);
+ try
+ {
+ styleManager.ApplyTheme(themeFile);
+ }
+ catch( Dali::DaliException& e )
+ {
+ DALI_TEST_ASSERT( e, "!\"Cannot parse JSON\"", TEST_LOCATION );
+ }
END_TEST;
}
+
int UtcDaliStyleManagerStyleChangedSignalFontFamily(void)
{
- tet_infoline("Test that the StyleChange signal is fired when the font family is altered");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Test that the StyleChange signal is fired when the font family is altered" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
- std::string labelStr("Label");
+ std::string labelStr("Label");
Toolkit::TextLabel label = Toolkit::TextLabel::New(labelStr);
- application.GetScene().Add(label);
+ application.GetScene().Add( label );
Toolkit::TextField field = Toolkit::TextField::New();
- application.GetScene().Add(field);
+ application.GetScene().Add( field );
Toolkit::TextEditor editor = Toolkit::TextEditor::New();
- application.GetScene().Add(editor);
+ application.GetScene().Add( editor );
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
Test::StyleMonitor::SetDefaultFontFamily("Times New Roman");
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
// Check that the label's font style has been altered
Property::Value family = label.GetProperty(TextLabel::Property::FONT_FAMILY);
- std::string familyStr;
- family.Get(familyStr);
+ std::string familyStr;
+ family.Get( familyStr );
- DALI_TEST_EQUALS(familyStr, "Times New Roman", TEST_LOCATION);
+ DALI_TEST_EQUALS( familyStr, "Times New Roman", TEST_LOCATION);
// Check that the field's font style has been altered
family = field.GetProperty(TextField::Property::FONT_FAMILY);
- family.Get(familyStr);
+ family.Get( familyStr );
- DALI_TEST_EQUALS(familyStr, "Times New Roman", TEST_LOCATION);
+ DALI_TEST_EQUALS( familyStr, "Times New Roman", TEST_LOCATION);
// Check that the editor's font style has been altered
family = editor.GetProperty(TextEditor::Property::FONT_FAMILY);
- family.Get(familyStr);
+ family.Get( familyStr );
- DALI_TEST_EQUALS(familyStr, "Times New Roman", TEST_LOCATION);
+ DALI_TEST_EQUALS( familyStr, "Times New Roman", TEST_LOCATION);
END_TEST;
}
int UtcDaliStyleManagerStyleChangedSignalFontSize(void)
{
- tet_infoline("Test that the StyleChange signal is fired when the font size is altered");
+ tet_infoline("Test that the StyleChange signal is fired when the font size is altered" );
const char* defaultTheme =
"{\n"
" }\n"
"}\n";
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme);
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme );
ToolkitTestApplication application;
- std::string labelStr("Label");
+ std::string labelStr("Label");
Toolkit::TextLabel label = Toolkit::TextLabel::New(labelStr);
- application.GetScene().Add(label);
+ application.GetScene().Add( label );
Toolkit::TextLabel label2 = Toolkit::TextLabel::New(labelStr);
- application.GetScene().Add(label2);
+ application.GetScene().Add( label2 );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleMonitor styleMonitor = StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ StyleMonitor styleMonitor = StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
label.SetProperty(TextLabel::Property::POINT_SIZE, 10.0f);
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
Test::StyleMonitor::SetDefaultFontSize(2);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
tet_infoline("Test that the label's font size has been altered\n");
Property::Value pointSizeValue = label.GetProperty(TextLabel::Property::POINT_SIZE);
- float pointSize;
- pointSizeValue.Get(pointSize);
+ float pointSize;
+ pointSizeValue.Get( pointSize );
- DALI_TEST_EQUALS(pointSize, 12.0f, 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( pointSize, 12.0f, 0.001, TEST_LOCATION );
styleChangedSignalHandler.signalCount = 0;
Test::StyleMonitor::SetDefaultFontSize(4);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
// Check that the label's font style has been altered
pointSizeValue = label.GetProperty(TextLabel::Property::POINT_SIZE);
- pointSizeValue.Get(pointSize);
+ pointSizeValue.Get( pointSize );
+
+ DALI_TEST_EQUALS( pointSize, 16.0f, 0.001, TEST_LOCATION );
- DALI_TEST_EQUALS(pointSize, 16.0f, 0.001, TEST_LOCATION);
END_TEST;
}
+
int UtcDaliStyleManagerStyleChangedSignalFontSizeTextField(void)
{
- tet_infoline("Test that the StyleChange signal is fired when the font size is altered");
+ tet_infoline("Test that the StyleChange signal is fired when the font size is altered" );
const char* defaultTheme =
"{\n"
" }\n"
"}\n";
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme);
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme );
ToolkitTestApplication application;
- std::string fieldStr("Field");
+ std::string fieldStr("Field");
Toolkit::TextField field = Toolkit::TextField::New();
- field.SetProperty(Toolkit::TextField::Property::TEXT, fieldStr);
- application.GetScene().Add(field);
+ field.SetProperty( Toolkit::TextField::Property::TEXT, fieldStr );
+ application.GetScene().Add( field );
Toolkit::TextField field2 = Toolkit::TextField::New();
- application.GetScene().Add(field2);
- field2.SetProperty(Toolkit::TextField::Property::TEXT, fieldStr);
+ application.GetScene().Add( field2 );
+ field2.SetProperty( Toolkit::TextField::Property::TEXT, fieldStr );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleMonitor styleMonitor = StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ StyleMonitor styleMonitor = StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
field.SetProperty(TextField::Property::POINT_SIZE, 10.0f);
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
Test::StyleMonitor::SetDefaultFontSize(2);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
tet_infoline("Test that the field's font size has been altered\n");
Property::Value pointSizeValue = field.GetProperty(TextField::Property::POINT_SIZE);
- float pointSize;
- pointSizeValue.Get(pointSize);
+ float pointSize;
+ pointSizeValue.Get( pointSize );
- DALI_TEST_EQUALS(pointSize, 12.0f, 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( pointSize, 12.0f, 0.001, TEST_LOCATION );
styleChangedSignalHandler.signalCount = 0;
Test::StyleMonitor::SetDefaultFontSize(4);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
// Check that the field's font style has been altered
pointSizeValue = field.GetProperty(TextField::Property::POINT_SIZE);
- pointSizeValue.Get(pointSize);
+ pointSizeValue.Get( pointSize );
+
+ DALI_TEST_EQUALS( pointSize, 16.0f, 0.001, TEST_LOCATION );
- DALI_TEST_EQUALS(pointSize, 16.0f, 0.001, TEST_LOCATION);
END_TEST;
}
int UtcDaliStyleManagerStyleChangedSignalFontSizeTextEditor(void)
{
- tet_infoline("Test that the StyleChange signal is fired when the font size is altered");
+ tet_infoline("Test that the StyleChange signal is fired when the font size is altered" );
const char* defaultTheme =
"{\n"
" }\n"
"}\n";
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme);
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme );
ToolkitTestApplication application;
- std::string editorStr("Editor");
+ std::string editorStr("Editor");
Toolkit::TextEditor editor = Toolkit::TextEditor::New();
- editor.SetProperty(Toolkit::TextEditor::Property::TEXT, editorStr);
- application.GetScene().Add(editor);
+ editor.SetProperty( Toolkit::TextEditor::Property::TEXT, editorStr );
+ application.GetScene().Add( editor );
Toolkit::TextEditor editor2 = Toolkit::TextEditor::New();
- application.GetScene().Add(editor2);
- editor2.SetProperty(Toolkit::TextEditor::Property::TEXT, editorStr);
+ application.GetScene().Add( editor2 );
+ editor2.SetProperty( Toolkit::TextEditor::Property::TEXT, editorStr );
StyleChangedSignalChecker styleChangedSignalHandler;
- StyleMonitor styleMonitor = StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ StyleMonitor styleMonitor = StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
editor.SetProperty(TextEditor::Property::POINT_SIZE, 10.0f);
styleManager.StyleChangedSignal().Connect(&styleChangedSignalHandler, &StyleChangedSignalChecker::OnStyleChanged);
Test::StyleMonitor::SetDefaultFontSize(2);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
tet_infoline("Test that the editor's font size has been altered\n");
Property::Value pointSizeValue = editor.GetProperty(TextEditor::Property::POINT_SIZE);
- float pointSize;
- pointSizeValue.Get(pointSize);
+ float pointSize;
+ pointSizeValue.Get( pointSize );
- DALI_TEST_EQUALS(pointSize, 14.0f, 0.001, TEST_LOCATION);
+ DALI_TEST_EQUALS( pointSize, 14.0f, 0.001, TEST_LOCATION );
styleChangedSignalHandler.signalCount = 0;
Test::StyleMonitor::SetDefaultFontSize(4);
- styleMonitor.StyleChangeSignal().Emit(styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
+ styleMonitor.StyleChangeSignal().Emit( styleMonitor, StyleChange::DEFAULT_FONT_SIZE_CHANGE);
tet_infoline("Test that the StyleChanged signal is received only once");
- DALI_TEST_EQUALS(styleChangedSignalHandler.signalCount, 1, TEST_LOCATION);
+ DALI_TEST_EQUALS( styleChangedSignalHandler.signalCount, 1, TEST_LOCATION );
// Check that the editor's font style has been altered
pointSizeValue = editor.GetProperty(TextEditor::Property::POINT_SIZE);
- pointSizeValue.Get(pointSize);
+ pointSizeValue.Get( pointSize );
+
+ DALI_TEST_EQUALS( pointSize, 25.0f, 0.001, TEST_LOCATION );
- DALI_TEST_EQUALS(pointSize, 25.0f, 0.001, TEST_LOCATION);
END_TEST;
}
+
int UtcDaliStyleManagerSetState01(void)
{
- tet_infoline("Instantiate dummy control and test state/visual/transition capture");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate dummy control and test state/visual/transition capture" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetStyleName("BasicControl");
application.GetScene().Add(actor);
- Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30);
+ Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
+ Integration::ResourcePointer ninePatch = CustomizeNinePatch( application, 30, 30 );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
- Visual::Base visual1 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
- Visual::Base labelVisual1 = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
+ Visual::Base visual1 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
+ Visual::Base labelVisual1 = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
Property::Map labelMap;
- labelVisual1.CreatePropertyMap(labelMap);
+ labelVisual1.CreatePropertyMap( labelMap );
labelMap[TextVisual::Property::TEXT] = "New text";
- VisualFactory factory = VisualFactory::Get();
- labelVisual1 = factory.CreateVisual(labelMap);
- dummyImpl.UnregisterVisual(DummyControl::Property::LABEL_VISUAL);
- dummyImpl.RegisterVisual(DummyControl::Property::LABEL_VISUAL, labelVisual1);
+ VisualFactory factory = VisualFactory::Get();
+ labelVisual1 = factory.CreateVisual(labelMap);
+ dummyImpl.UnregisterVisual(DummyControl::Property::LABEL_VISUAL );
+ dummyImpl.RegisterVisual(DummyControl::Property::LABEL_VISUAL, labelVisual1 );
- actor.SetProperty(DevelControl::Property::STATE, DevelControl::FOCUSED);
+ actor.SetProperty( DevelControl::Property::STATE, DevelControl::FOCUSED );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOCUS_VISUAL), true, TEST_LOCATION);
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::LABEL_VISUAL), true, TEST_LOCATION);
- Visual::Base visual2 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
+ Visual::Base visual2 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
Visual::Base labelVisual2 = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
- DALI_TEST_CHECK(visual1 != visual2);
- DALI_TEST_CHECK(labelVisual1 != labelVisual2);
+ DALI_TEST_CHECK( visual1 != visual2 );
+ DALI_TEST_CHECK( labelVisual1 != labelVisual2 );
labelMap.Clear();
- labelVisual2.CreatePropertyMap(labelMap);
- Property::Value* textValue = labelMap.Find(Toolkit::TextVisual::Property::TEXT, "text");
- DALI_TEST_CHECK(textValue);
- Property::Value* pointSizeValue = labelMap.Find(Toolkit::TextVisual::Property::POINT_SIZE, "pointSize");
- tet_infoline("Check that the instance data has been copied to the new text visual\n");
- DALI_TEST_EQUALS(textValue->Get<std::string>(), "New text", TEST_LOCATION);
- DALI_TEST_EQUALS(pointSizeValue->Get<int>(), 10, TEST_LOCATION);
+ labelVisual2.CreatePropertyMap( labelMap );
+ Property::Value* textValue = labelMap.Find( Toolkit::TextVisual::Property::TEXT, "text");
+ DALI_TEST_CHECK( textValue );
+ Property::Value* pointSizeValue = labelMap.Find( Toolkit::TextVisual::Property::POINT_SIZE, "pointSize");
+ tet_infoline( "Check that the instance data has been copied to the new text visual\n");
+ DALI_TEST_EQUALS( textValue->Get<std::string>(), "New text", TEST_LOCATION );
+ DALI_TEST_EQUALS( pointSizeValue->Get<int>(), 10, TEST_LOCATION );
- actor.SetProperty(DevelControl::Property::STATE, DevelControl::DISABLED);
+
+ actor.SetProperty( DevelControl::Property::STATE, DevelControl::DISABLED );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
- Visual::Base visual3 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
+ Visual::Base visual3 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
Visual::Base focusVisual = dummyImpl.GetVisual(DummyControl::Property::FOCUS_VISUAL);
- DALI_TEST_CHECK(!focusVisual);
+ DALI_TEST_CHECK( !focusVisual );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOCUS_VISUAL), false, TEST_LOCATION);
- DALI_TEST_CHECK(visual1 != visual3);
- DALI_TEST_CHECK(visual2 != visual3);
+ DALI_TEST_CHECK( visual1 != visual3 );
+ DALI_TEST_CHECK( visual2 != visual3 );
Visual::Base labelVisual3 = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
- DALI_TEST_CHECK(labelVisual2 != labelVisual3);
+ DALI_TEST_CHECK( labelVisual2 != labelVisual3 );
- labelVisual2.CreatePropertyMap(labelMap);
+ labelVisual2.CreatePropertyMap( labelMap );
textValue = labelMap.Find(Toolkit::TextVisual::Property::TEXT, "text");
- DALI_TEST_CHECK(textValue);
+ DALI_TEST_CHECK( textValue );
pointSizeValue = labelMap.Find(Toolkit::TextVisual::Property::POINT_SIZE, "pointSize");
- tet_infoline("Check that the instance data has been copied to the new text visual\n");
- DALI_TEST_EQUALS(textValue->Get<std::string>(), "New text", TEST_LOCATION);
- DALI_TEST_EQUALS(pointSizeValue->Get<int>(), 10, TEST_LOCATION);
+ tet_infoline( "Check that the instance data has been copied to the new text visual\n");
+ DALI_TEST_EQUALS( textValue->Get<std::string>(), "New text", TEST_LOCATION );
+ DALI_TEST_EQUALS( pointSizeValue->Get<int>(), 10, TEST_LOCATION );
END_TEST;
}
int UtcDaliStyleManagerSetState02(void)
{
- tet_infoline("Instantiate dummy control and test state/visual/transition capture");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate dummy control and test state/visual/transition capture" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetStyleName("BasicControl");
application.GetScene().Add(actor);
- Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30);
+ Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
+ Integration::ResourcePointer ninePatch = CustomizeNinePatch( application, 30, 30 );
- int state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION);
+ int state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::NORMAL, TEST_LOCATION );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
Visual::Base visual1 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "FOCUSED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "FOCUSED" ).Add("withTransitions", false));
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::FOCUSED, TEST_LOCATION );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOCUS_VISUAL), true, TEST_LOCATION);
Visual::Base visual2 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
- DALI_TEST_CHECK(visual1 != visual2);
+ DALI_TEST_CHECK( visual1 != visual2 );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "DISABLED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "DISABLED" ).Add("withTransitions", false));
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::DISABLED, TEST_LOCATION );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
Visual::Base visual3 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
Visual::Base testVisual = dummyImpl.GetVisual(DummyControl::Property::FOCUS_VISUAL);
- DALI_TEST_CHECK(!testVisual);
+ DALI_TEST_CHECK( !testVisual );
testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL);
- DALI_TEST_CHECK(!testVisual);
+ DALI_TEST_CHECK( !testVisual );
testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL2);
- DALI_TEST_CHECK(!testVisual);
+ DALI_TEST_CHECK( !testVisual );
testVisual = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
- DALI_TEST_CHECK(testVisual);
+ DALI_TEST_CHECK( testVisual );
+
- DALI_TEST_CHECK(visual1 != visual3);
- DALI_TEST_CHECK(visual2 != visual3);
+ DALI_TEST_CHECK( visual1 != visual3 );
+ DALI_TEST_CHECK( visual2 != visual3 );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "NORMAL").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "NORMAL" ).Add("withTransitions", false));
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::NORMAL, TEST_LOCATION );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOREGROUND_VISUAL), true, TEST_LOCATION);
visual1 = dummyImpl.GetVisual(DummyControl::Property::FOREGROUND_VISUAL);
- DALI_TEST_CHECK(visual1);
+ DALI_TEST_CHECK( visual1 );
Visual::Base focusVisual = dummyImpl.GetVisual(DummyControl::Property::FOCUS_VISUAL);
- DALI_TEST_CHECK(!focusVisual);
+ DALI_TEST_CHECK( !focusVisual );
DALI_TEST_EQUALS(dummyImpl.IsVisualEnabled(DummyControl::Property::FOCUS_VISUAL), false, TEST_LOCATION);
+
END_TEST;
}
+
int UtcDaliStyleManagerSetState03N(void)
{
- tet_infoline("Instantiate dummy control and test state transition without state style");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate dummy control and test state transition without state style" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetStyleName("NoStyles");
application.GetScene().Add(actor);
Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- Property::Map propertyMap;
- propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR);
- propertyMap.Insert(ColorVisual::Property::MIX_COLOR, Color::BLUE);
+ Property::Map propertyMap;
+ propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR);
+ propertyMap.Insert(ColorVisual::Property::MIX_COLOR, Color::BLUE);
VisualFactory factory = VisualFactory::Get();
- Visual::Base visual = factory.CreateVisual(propertyMap);
- dummyImpl.RegisterVisual(DummyControl::Property::TEST_VISUAL, visual);
+ Visual::Base visual = factory.CreateVisual( propertyMap );
+ dummyImpl.RegisterVisual( DummyControl::Property::TEST_VISUAL, visual );
- int state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION);
+ int state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::NORMAL, TEST_LOCATION );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "FOCUSED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "FOCUSED" ).Add("withTransitions", false));
Visual::Base testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL);
- DALI_TEST_CHECK(testVisual = visual);
+ DALI_TEST_CHECK( testVisual = visual );
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::FOCUSED, TEST_LOCATION );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "DISABLED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "DISABLED" ).Add("withTransitions", false));
testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL);
- DALI_TEST_CHECK(testVisual = visual);
+ DALI_TEST_CHECK( testVisual = visual );
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::DISABLED, TEST_LOCATION );
END_TEST;
}
+
int UtcDaliStyleManagerSetState04N(void)
{
- tet_infoline("Instantiate dummy control and test state transition with style without state");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate dummy control and test state transition with style without state" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetStyleName("NoStateStyle");
application.GetScene().Add(actor);
Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- Property::Map propertyMap;
- propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR);
- propertyMap.Insert(ColorVisual::Property::MIX_COLOR, Color::BLUE);
+ Property::Map propertyMap;
+ propertyMap.Insert(Visual::Property::TYPE, Visual::COLOR);
+ propertyMap.Insert(ColorVisual::Property::MIX_COLOR, Color::BLUE);
VisualFactory factory = VisualFactory::Get();
- Visual::Base visual = factory.CreateVisual(propertyMap);
- dummyImpl.RegisterVisual(DummyControl::Property::TEST_VISUAL, visual);
+ Visual::Base visual = factory.CreateVisual( propertyMap );
+ dummyImpl.RegisterVisual( DummyControl::Property::TEST_VISUAL, visual );
- int state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION);
+ int state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::NORMAL, TEST_LOCATION );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "FOCUSED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "FOCUSED" ).Add("withTransitions", false));
Visual::Base testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL);
- DALI_TEST_CHECK(testVisual = visual);
+ DALI_TEST_CHECK( testVisual = visual );
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::FOCUSED, TEST_LOCATION );
- actor.SetProperty(DevelControl::Property::STATE,
- Property::Map().Add("state", "DISABLED").Add("withTransitions", false));
+ actor.SetProperty( DevelControl::Property::STATE,
+ Property::Map().Add( "state", "DISABLED" ).Add("withTransitions", false));
testVisual = dummyImpl.GetVisual(DummyControl::Property::TEST_VISUAL);
- DALI_TEST_CHECK(testVisual = visual);
+ DALI_TEST_CHECK( testVisual = visual );
- state = actor.GetProperty<int>(DevelControl::Property::STATE);
- DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION);
+ state = actor.GetProperty<int>( DevelControl::Property::STATE );
+ DALI_TEST_EQUALS( state, (int) DevelControl::DISABLED, TEST_LOCATION );
END_TEST;
}
int UtcDaliStyleManagerSetSubState01(void)
{
- tet_infoline("Instantiate dummy control and test state/visual/transition capture");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate dummy control and test state/visual/transition capture" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetProperty(DevelControl::Property::STATE, "NORMAL");
actor.SetStyleName("ComplexControl");
application.GetScene().Add(actor);
- Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30);
+ Integration::ResourcePointer ninePatch = CustomizeNinePatch( application, 30, 30 );
Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
actor.SetProperty(DevelControl::Property::SUB_STATE, "UNSELECTED");
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::COLOR, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::COLOR, TEST_LOCATION);
actor.SetProperty(DevelControl::Property::SUB_STATE, "SELECTED");
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
END_TEST;
}
+
int UtcDaliStyleManagerSetSubState02(void)
{
- tet_infoline("Instantiate complex control and test state/substate change");
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json",
- defaultTheme);
+ tet_infoline("Instantiate complex control and test state/substate change" );
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json",
+ defaultTheme );
ToolkitTestApplication application;
StyleChangedSignalChecker styleChangedSignalHandler;
- Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
- StyleManager styleManager = StyleManager::Get();
+ Dali::StyleMonitor styleMonitor = Dali::StyleMonitor::Get();
+ StyleManager styleManager = StyleManager::Get();
DummyControl actor = DummyControl::New(true);
actor.SetProperty(DevelControl::Property::STATE, "NORMAL");
actor.SetProperty(DevelControl::Property::SUB_STATE, "SELECTED");
- tet_infoline("Setting state to NORMAL/SELECTED before re-styling\n");
+ tet_infoline( "Setting state to NORMAL/SELECTED before re-styling\n");
actor.SetStyleName("ComplexControl");
application.GetScene().Add(actor);
- Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30);
+ Integration::ResourcePointer ninePatch = CustomizeNinePatch( application, 30, 30 );
Impl::DummyControl& dummyImpl = static_cast<Impl::DummyControl&>(actor.GetImplementation());
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
actor.SetProperty(DevelControl::Property::SUB_STATE, "UNSELECTED");
- tet_infoline("Changing substate to UNSELECTED - check visual changes\n");
+ tet_infoline( "Changing substate to UNSELECTED - check visual changes\n");
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::COLOR, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::COLOR, TEST_LOCATION);
actor.SetProperty(DevelControl::Property::STATE, "FOCUSED");
- tet_infoline("Changing state to FOCUSED - check visual changes\n");
+ tet_infoline( "Changing state to FOCUSED - check visual changes\n");
- Visual::Base fgVisual1 = CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::GRADIENT, TEST_LOCATION);
- Visual::Base focusVisual1 = CheckVisual(dummyImpl, DummyControl::Property::FOCUS_VISUAL, Toolkit::Visual::N_PATCH, TEST_LOCATION);
+ Visual::Base fgVisual1 = CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ Visual::Base focusVisual1 = CheckVisual( dummyImpl, DummyControl::Property::FOCUS_VISUAL, Toolkit::Visual::N_PATCH, TEST_LOCATION);
actor.SetProperty(DevelControl::Property::SUB_STATE, "SELECTED");
- tet_infoline("Changing substate to SELECTED - Expect no change\n");
+ tet_infoline( "Changing substate to SELECTED - Expect no change\n");
- Visual::Base fgVisual2 = CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::GRADIENT, TEST_LOCATION);
- Visual::Base focusVisual2 = CheckVisual(dummyImpl, DummyControl::Property::FOCUS_VISUAL, Toolkit::Visual::N_PATCH, TEST_LOCATION);
+ Visual::Base fgVisual2 = CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ Visual::Base focusVisual2 = CheckVisual( dummyImpl, DummyControl::Property::FOCUS_VISUAL, Toolkit::Visual::N_PATCH, TEST_LOCATION);
- DALI_TEST_CHECK(fgVisual1 == fgVisual2);
- DALI_TEST_CHECK(focusVisual1 == focusVisual2);
+ DALI_TEST_CHECK( fgVisual1 == fgVisual2 );
+ DALI_TEST_CHECK( focusVisual1 == focusVisual2 );
actor.SetProperty(DevelControl::Property::STATE, "NORMAL");
- tet_infoline("Changing state to NORMAL - Expect to change to NORMAL/SELECTED \n");
+ tet_infoline( "Changing state to NORMAL - Expect to change to NORMAL/SELECTED \n");
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL2, Toolkit::Visual::GRADIENT, TEST_LOCATION);
Visual::Base focusVisual = dummyImpl.GetVisual(DummyControl::Property::FOCUS_VISUAL);
- DALI_TEST_CHECK(!focusVisual);
+ DALI_TEST_CHECK( ! focusVisual );
actor.SetProperty(DevelControl::Property::STATE, "DISABLED");
- tet_infoline("Changing state to DISABLED - Expect to change to DISABLED/SELECTED \n");
+ tet_infoline( "Changing state to DISABLED - Expect to change to DISABLED/SELECTED \n");
- CheckVisual(dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::COLOR, TEST_LOCATION);
- CheckVisual(dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::FOREGROUND_VISUAL, Toolkit::Visual::COLOR, TEST_LOCATION);
+ CheckVisual( dummyImpl, DummyControl::Property::TEST_VISUAL, Toolkit::Visual::IMAGE, TEST_LOCATION);
Visual::Base testVisual = dummyImpl.GetVisual(DummyControl::Property::FOCUS_VISUAL);
- DALI_TEST_CHECK(!testVisual);
+ DALI_TEST_CHECK( ! testVisual );
testVisual = dummyImpl.GetVisual(DummyControl::Property::LABEL_VISUAL);
- DALI_TEST_CHECK(!testVisual);
+ DALI_TEST_CHECK( ! testVisual );
END_TEST;
}
+
int UtcDaliStyleManagerConfigSectionTest(void)
{
- tet_infoline("Test that the properties in config section are works");
+ tet_infoline("Test that the properties in config section are works" );
const char* defaultTheme =
"{\n"
" }\n"
"}\n";
- Test::StyleMonitor::SetThemeFileOutput(DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme);
+ Test::StyleMonitor::SetThemeFileOutput( DALI_STYLE_DIR "dali-toolkit-default-theme.json", defaultTheme );
ToolkitTestApplication application;
Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- Property::Map config = Toolkit::DevelStyleManager::GetConfigurations(styleManager);
- bool alwaysShowFocus = config["alwaysShowFocus"].Get<bool>();
- DALI_TEST_CHECK(!alwaysShowFocus);
+ Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager );
+ bool alwaysShowFocus = config["alwaysShowFocus"].Get<bool>();
+ DALI_TEST_CHECK( !alwaysShowFocus );
bool clearFocusOnEscape = config["clearFocusOnEscape"].Get<bool>();
- DALI_TEST_CHECK(!clearFocusOnEscape);
+ DALI_TEST_CHECK( !clearFocusOnEscape );
std::string brokenImageUrl = config["brokenImageUrl"].Get<std::string>();
- DALI_TEST_CHECK(brokenImageUrl.compare("broken|broken|{TEST|TEST.png") == 0);
+ DALI_TEST_CHECK( brokenImageUrl.compare( "broken|broken|{TEST|TEST.png" ) == 0 );
// For coverage
Toolkit::TextEditor editor = Toolkit::TextEditor::New();
- editor.SetProperty(Actor::Property::KEYBOARD_FOCUSABLE, true);
- application.GetScene().Add(editor);
+ editor.SetProperty( Actor::Property::KEYBOARD_FOCUSABLE, true );
+ application.GetScene().Add( editor );
- Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor(editor);
+ Toolkit::KeyboardFocusManager::Get().SetCurrentFocusActor( editor );
- application.ProcessEvent(Integration::KeyEvent("", "", "", DALI_KEY_ESCAPE, 0, 0, Integration::KeyEvent::DOWN, "", "", Device::Class::NONE, Device::Subclass::NONE));
+ application.ProcessEvent( Integration::KeyEvent( "", "", "", DALI_KEY_ESCAPE, 0, 0, Integration::KeyEvent::DOWN, "", "", Device::Class::NONE, Device::Subclass::NONE ) );
application.SendNotification();
application.Render();
END_TEST;
}
+
int UtcDaliStyleManagerNewWithAdditionalBehavior(void)
{
ToolkitTestApplication application;
Toolkit::StyleManager styleManager = StyleManager::Get();
Toolkit::Internal::StyleManager& styleManagerImpl = GetImpl(styleManager);
- auto checkup = [&styleManagerImpl](int enableStyleChangeSignal, const Control& control) {
- DALI_TEST_EQUALS(enableStyleChangeSignal, styleManagerImpl.ControlStyleChangeSignal().GetConnectionCount(), TEST_LOCATION);
+ auto checkup = [&styleManagerImpl](int enableStyleChangeSignal, const Control& control){
+ DALI_TEST_EQUALS( enableStyleChangeSignal, styleManagerImpl.ControlStyleChangeSignal().GetConnectionCount(), TEST_LOCATION );
};
// Default New
// Note: TextField and TextEditor have TextSelectionPopup
- tet_infoline("Check whether ControlStyleChangeSignal connected in default New\n");
+ tet_infoline( "Check whether ControlStyleChangeSignal connected in default New\n");
checkup(1, Control::New());
checkup(1, ImageView::New());
checkup(1, ImageView::New("url"));
checkup(2, TextEditor::New());
// New with additional behaviour, but enable style change signals
- tet_infoline("Check whether ControlStyleChangeSignal connected in non-disable style change signals\n");
+ tet_infoline( "Check whether ControlStyleChangeSignal connected in non-disable style change signals\n");
checkup(1, Control::New(Toolkit::Control::ControlBehaviour::CONTROL_BEHAVIOUR_DEFAULT));
checkup(1, Control::New(Toolkit::Control::ControlBehaviour::DISABLE_SIZE_NEGOTIATION));
checkup(1, Control::New(Toolkit::Control::ControlBehaviour::REQUIRES_KEYBOARD_NAVIGATION_SUPPORT));
checkup(2, TextEditor::New(Toolkit::Control::ControlBehaviour::DISABLE_SIZE_NEGOTIATION));
// New with additional behaviour, so disable style change signals
- tet_infoline("Check whether ControlStyleChangeSignal did not connected\n");
+ tet_infoline( "Check whether ControlStyleChangeSignal did not connected\n");
checkup(0, Control::New(Toolkit::Control::ControlBehaviour::DISABLE_STYLE_CHANGE_SIGNALS));
checkup(0, Control::New(Toolkit::Control::ControlBehaviour(Toolkit::Control::ControlBehaviour::DISABLE_STYLE_CHANGE_SIGNALS | Toolkit::Control::ControlBehaviour::DISABLE_SIZE_NEGOTIATION)));
checkup(0, ImageView::New(Toolkit::Control::ControlBehaviour::DISABLE_STYLE_CHANGE_SIGNALS));
return texture;
}
-bool TestGraphicsController::HasClipMatrix() const
-{
- return true;
-}
-
-const Matrix& TestGraphicsController::GetClipMatrix() const
-{
- // This matrix transforms from GL -> Vulkan clip space
- constexpr float VULKAN_CLIP_MATRIX_DATA[] = {
- 1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -1.0f, 0.0f, 0.0f, 0.0f, 0.0f, -0.5f, 0.0f, 0.0f, 0.0f, 0.5f, 1.0f};
- static const Matrix VULKAN_CLIP_MATRIX(VULKAN_CLIP_MATRIX_DATA);
- static const Matrix IDENTITY = Matrix::IDENTITY;
-
- // For now, return IDENTITY to stay in GL clip space.
- // @todo Add test toggle
- return IDENTITY;
-}
-
} // namespace Dali
*/
Graphics::UniquePtr<Graphics::Texture> ReleaseTextureFromResourceId(uint32_t resourceId) override;
- bool HasClipMatrix() const override;
- const Matrix& GetClipMatrix() const override;
-
public: // Test Functions
void SetAutoAttrCreation(bool v)
{
uint32_t elementStrideInBytes)
{
TestGraphicsReflection::TestUniformInfo info;
- info.name = std::move(name);
- info.type = type;
- info.uniformClass = Graphics::UniformClass::UNIFORM;
- info.numElements = elementCount;
- info.locations = {0};
- info.bufferIndex = 0; // this will update when AddCustomUniformBlock called
-
- auto retval = GetUniformBufferArrayStrideAndTypeSize(info, elementStrideInBytes);
+ info.name = std::move(name);
+ info.type = type;
+ info.uniformClass = Graphics::UniformClass::UNIFORM;
+ info.numElements = elementCount;
+ info.locations = {0};
+ info.bufferIndex = 0; // this will update when AddCustomUniformBlock called
+
+ auto retval= GetUniformBufferArrayStrideAndTypeSize(info, elementStrideInBytes);
info.elementStride = std::max(retval.first, retval.second);
info.offsets = {blockInfo.size};
blockInfo.size += (elementCount == 0 ? 1 : elementCount) * std::max(retval.first, retval.second);
} // namespace Dali
-#endif // TEST_GRAPHICS_CONTROLLER_H
+#endif //TEST_GRAPHICS_CONTROLLER_H
#include <string.h>
#include <toolkit-application.h>
#include <memory>
-#include <dali/devel-api/adaptor-framework/web-engine/web-engine-user-media-permission-request.h>
namespace Dali
{
void GetPlainTextAsynchronously(PlainTextReceivedCallback callback) override
{
}
- void WebAuthenticationCancel() override
- {
- }
- void RegisterWebAuthDisplayQRCallback(WebEngineWebAuthDisplayQRCallback callback) override
- {
- }
- void RegisterWebAuthResponseCallback(WebEngineWebAuthResponseCallback callback) override
- {
- }
- void RegisterUserMediaPermissionRequestCallback(WebEngineUserMediaPermissionRequestCallback callback) override
- {
- }
private:
MockWebEngineSettings settings;
mTextFoundCallback = callback;
}
- void WebAuthenticationCancel()
- {
- mWebAuthenticationCancel = true;
- }
-
- void RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback)
- {
- mWebAuthDisplayQRCallback = callback;
- }
-
- void RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback)
- {
- mWebAuthResponseCallback = callback;
- }
-
- void RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback)
- {
- mUserMediaPermissionRequestCallback = callback;
- }
-
std::string mUrl;
std::vector<std::string> mHistory;
size_t mCurrentPlusOnePos;
Dali::WebEnginePlugin::WebEngineFullscreenEnteredCallback mFullscreenEnteredCallback;
Dali::WebEnginePlugin::WebEngineFullscreenExitedCallback mFullscreenExitedCallback;
Dali::WebEnginePlugin::WebEngineTextFoundCallback mTextFoundCallback;
- bool mWebAuthenticationCancel;
- Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback mWebAuthDisplayQRCallback;
- Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback mWebAuthResponseCallback;
- Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback mUserMediaPermissionRequestCallback;
-};
-
-class MockUserMediaPermissionRequest : public Dali::WebEngineUserMediaPermissionRequest
-{
-public:
- MockUserMediaPermissionRequest()
- {
- }
- void Set(bool allowed) const override
- {
- }
- bool Suspend() const override
- {
- return true;
- }
};
namespace
{
gInstance->mTextFoundCallback(1);
}
- if(gInstance->mWebAuthDisplayQRCallback)
- {
- gInstance->mWebAuthDisplayQRCallback("test-string");
- }
- if(gInstance->mWebAuthResponseCallback)
- {
- gInstance->mWebAuthResponseCallback();
- }
- if(gInstance->mUserMediaPermissionRequestCallback)
- {
- std::unique_ptr<Dali::WebEngineUserMediaPermissionRequest> request(new MockUserMediaPermissionRequest());
- gInstance->mUserMediaPermissionRequestCallback(std::move(request), "message");
- }
}
return false;
}
return WebEngine(baseObject);
}
-WebEngine WebEngine::New(int32_t type)
-{
- //type is used for actual target
- Internal::Adaptor::WebEngine* baseObject = new Internal::Adaptor::WebEngine();
-
- return WebEngine(baseObject);
-}
-
Dali::WebEngineContext* WebEngine::GetContext()
{
return Internal::Adaptor::GetContext();
Internal::Adaptor::GetImplementation(*this).RegisterTextFoundCallback(callback);
}
-void WebEngine::WebAuthenticationCancel()
-{
- Internal::Adaptor::GetImplementation(*this).WebAuthenticationCancel();
-}
-
-void WebEngine::RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback)
-{
- Internal::Adaptor::GetImplementation(*this).RegisterWebAuthDisplayQRCallback(callback);
-}
-
-void WebEngine::RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback)
-{
- Internal::Adaptor::GetImplementation(*this).RegisterWebAuthResponseCallback(callback);
-}
-
-void WebEngine::RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback)
-{
- Internal::Adaptor::GetImplementation(*this).RegisterUserMediaPermissionRequestCallback(callback);
-}
-
} // namespace Dali
END_TEST;
}
-
-int UtcDaliRenderEffectRenderTaskOrdering(void)
-{
- ToolkitTestApplication application;
- tet_infoline("UtcDaliRenderEffectRenderTaskOrdering");
-
- Integration::Scene scene = application.GetScene();
- RenderTaskList taskList = scene.GetRenderTaskList();
-
- Control control1 = Control::New();
- control1.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- control1.SetProperty(Actor::Property::SIZE, Vector2(1.0f, 1.0f));
-
- tet_printf("render task cnt : %d\n", taskList.GetTaskCount());
-
- // Add render effect during scene on.
- control1.SetRenderEffect(BackgroundBlurEffect::New());
-
- tet_printf("render task cnt after set : %d\n", taskList.GetTaskCount());
- DALI_TEST_EQUALS(1, taskList.GetTaskCount(), TEST_LOCATION);
-
- scene.Add(control1);
-
- tet_printf("render task cnt after add : %d\n", taskList.GetTaskCount());
- DALI_TEST_EQUALS(4, taskList.GetTaskCount(), TEST_LOCATION);
-
- Dali::RenderTask sourceTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 3);
- Dali::RenderTask horizontalBlurTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 2);
- Dali::RenderTask verticalBlurTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 1);
-
- tet_printf("order : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- DALI_TEST_EQUALS(0, sourceTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, horizontalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, verticalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
-
- application.SendNotification();
-
- tet_printf("order af : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order af : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order af : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, sourceTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, horizontalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 2, verticalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
-
- Control control2 = Control::New();
- control2.SetProperty(Actor::Property::PARENT_ORIGIN, ParentOrigin::CENTER);
- control2.SetProperty(Actor::Property::SIZE, Vector2(1.0f, 1.0f));
-
- tet_printf("render task cnt : %d\n", taskList.GetTaskCount());
-
- // Add render effect during scene on.
- control2.SetRenderEffect(BackgroundBlurEffect::New());
-
- tet_printf("render task cnt after set : %d\n", taskList.GetTaskCount());
-
- scene.Add(control2);
-
- DALI_TEST_EQUALS(7, taskList.GetTaskCount(), TEST_LOCATION);
-
- tet_printf("render task cnt after add : %d\n", taskList.GetTaskCount());
-
- Dali::RenderTask sourceTaskControl2 = taskList.GetTask(taskList.GetTaskCount() - 3);
- Dali::RenderTask horizontalBlurTaskControl2 = taskList.GetTask(taskList.GetTaskCount() - 2);
- Dali::RenderTask verticalBlurTaskControl2 = taskList.GetTask(taskList.GetTaskCount() - 1);
-
-
- tet_printf("order after1 : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order after1 : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order after1 : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- tet_printf("order after1 : %d\n", sourceTaskControl2.GetOrderIndex());
- tet_printf("order after1 : %d\n", horizontalBlurTaskControl2.GetOrderIndex());
- tet_printf("order after1 : %d\n", verticalBlurTaskControl2.GetOrderIndex());
-
- DALI_TEST_EQUALS(0, sourceTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, horizontalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, verticalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
-
- application.SendNotification();
-
- tet_printf("order after2 : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order after2 : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order after2 : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- tet_printf("order after2 : %d\n", sourceTaskControl2.GetOrderIndex());
- tet_printf("order after2 : %d\n", horizontalBlurTaskControl2.GetOrderIndex());
- tet_printf("order after2 : %d\n", verticalBlurTaskControl2.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN, sourceTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, horizontalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 2, verticalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
-
- DALI_TEST_EQUALS(INT32_MIN + 3, sourceTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 4, horizontalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 5, verticalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
-
- control2.Add(control1);
-
- sourceTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 3);
- horizontalBlurTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 2);
- verticalBlurTaskControl1 = taskList.GetTask(taskList.GetTaskCount() - 1);
-
- tet_printf("order after3 : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order after3 : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order after3 : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- tet_printf("order after3 : %d\n", sourceTaskControl2.GetOrderIndex());
- tet_printf("order after3 : %d\n", horizontalBlurTaskControl2.GetOrderIndex());
- tet_printf("order after3 : %d\n", verticalBlurTaskControl2.GetOrderIndex());
-
- DALI_TEST_EQUALS(0, sourceTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, horizontalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(0, verticalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
-
- DALI_TEST_EQUALS(INT32_MIN + 3, sourceTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 4, horizontalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 5, verticalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
-
- application.SendNotification();
-
- tet_printf("order after4 : %d\n", sourceTaskControl1.GetOrderIndex());
- tet_printf("order after4 : %d\n", horizontalBlurTaskControl1.GetOrderIndex());
- tet_printf("order after4 : %d\n", verticalBlurTaskControl1.GetOrderIndex());
-
- tet_printf("order after4 : %d\n", sourceTaskControl2.GetOrderIndex());
- tet_printf("order after4 : %d\n", horizontalBlurTaskControl2.GetOrderIndex());
- tet_printf("order after4 : %d\n", verticalBlurTaskControl2.GetOrderIndex());
-
- DALI_TEST_EQUALS(INT32_MIN + 3, sourceTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 4, horizontalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 5, verticalBlurTaskControl1.GetOrderIndex(), TEST_LOCATION);
-
- DALI_TEST_EQUALS(INT32_MIN, sourceTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 1, horizontalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
- DALI_TEST_EQUALS(INT32_MIN + 2, verticalBlurTaskControl2.GetOrderIndex(), TEST_LOCATION);
-
- END_TEST;
-}
-
{
typedef Toolkit::NPatchUtility::StretchRanges StretchRanges;
-constexpr uint32_t PLATFORM_DEFAULT_PRECOMPILED_SHADER_COUNT = 5u;
-
const char* TEST_9_PATCH_FILE_NAME = TEST_RESOURCE_DIR "/demo-tile-texture-focused.9.png";
const char* TEST_NPATCH_FILE_NAME = TEST_RESOURCE_DIR "/heartsframe.9.png";
const char* TEST_SVG_FILE_NAME = TEST_RESOURCE_DIR "/svg1.svg";
ToolkitTestApplication application;
tet_infoline("UtcDaliVisualFactoryUsePreCompiledShader: Test a UsePreCompiledShader fucntion");
- ShaderPreCompiler::RawShaderDataList precompiledShaderList;
+ std::vector<RawShaderData> precompiledShaderList;
DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // before Get Shader
ShaderPreCompiler::Get().GetPreCompileShaderList(precompiledShaderList);
DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // after Get Shader
npatchShader2["xStretchCount"] = 4;
npatchShader2["yStretchCount"] = 3;
- Property::Map customShader;
- customShader["shaderType"] = "custom";
- customShader["shaderName"] = "myShader";
- customShader["vertexShader"] = VertexSource;
- customShader["fragmentShader"] = FragmentSource;
+ Property::Map customSHader;
+ customSHader["shaderType"] = "custom";
+ customSHader["shaderName"] = "myShader";
+ customSHader["vertexShader"] = VertexSource;
+ customSHader["fragmentShader"] = FragmentSource;
factory.AddPrecompileShader(imageShader);
factory.AddPrecompileShader(imageShader); // use same shader, because check line coverage
factory.AddPrecompileShader(imageShader2);
factory.AddPrecompileShader(imageShader3);
factory.AddPrecompileShader(imageShader4);
- factory.AddPrecompileShader(imageShader4); // use same shader, because check line coverage
factory.AddPrecompileShader(imageShader5);
factory.AddPrecompileShader(textShader);
- factory.AddPrecompileShader(textShader); // use same shader, because check line coverage
factory.AddPrecompileShader(textShader2);
factory.AddPrecompileShader(colorShader);
- factory.AddPrecompileShader(colorShader); // use same shader, because check line coverage
factory.AddPrecompileShader(colorShader2);
factory.AddPrecompileShader(npatchShader);
factory.AddPrecompileShader(npatchShader2);
- factory.AddPrecompileShader(customShader);
+ factory.AddPrecompileShader(customSHader);
factory.UsePreCompiledShader();
ShaderPreCompiler::Get().GetPreCompileShaderList(precompiledShaderList);
-
- DALI_TEST_EQUALS(precompiledShaderList.size(), PLATFORM_DEFAULT_PRECOMPILED_SHADER_COUNT, TEST_LOCATION);
+ DALI_TEST_CHECK(precompiledShaderList.size() != 0u); // after Get Shader
Property::Map propertyMap;
propertyMap.Insert(Toolkit::Visual::Property::TYPE, Visual::IMAGE);
END_TEST;
}
-
-int UtcDaliVisualFactoryUsePreCompiledShaderN(void)
-{
- ToolkitTestApplication application;
- tet_infoline("UtcDaliVisualFactoryUsePreCompiledShader: Test a UsePreCompiledShader fucntion with invalid options");
-
- ShaderPreCompiler::RawShaderDataList precompiledShaderList;
- DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // before Get Shader
- ShaderPreCompiler::Get().GetPreCompileShaderList(precompiledShaderList);
- DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // after Get Shader
-
- VisualFactory factory = VisualFactory::Get();
- DALI_TEST_CHECK(factory);
-
- Property::Map invalidShaderType;
- invalidShaderType["shaderType"] = "invalid";
-
- Property::Map invalidShaderFlag;
- invalidShaderFlag["shaderType"] = "image";
- invalidShaderFlag["shaderOption"] = Property::Map().Add("INVALID", true);
-
- Property::Map invalidShaderFlag2;
- invalidShaderFlag2["shaderType"] = "image";
- invalidShaderFlag2["shaderOption"] = Property::Map().Add("ROUNDED_CORNER", false).Add("INVALID", false);
-
- Property::Map unmatchedShaderOption;
- unmatchedShaderOption["shaderType"] = "image";
- unmatchedShaderOption["shaderOption"] = Property::Map().Add("CUTOUT", true);
-
- Property::Map unmatchedShaderOption2;
- unmatchedShaderOption2["shaderType"] = "text";
- unmatchedShaderOption2["shaderOption"] = Property::Map().Add("ROUNDED_CORNER", true);
-
- Property::Map unmatchedShaderOption3;
- unmatchedShaderOption3["shaderType"] = "color";
- unmatchedShaderOption3["shaderOption"] = Property::Map().Add("EMOJI", true);
-
- factory.AddPrecompileShader(invalidShaderType);
- factory.AddPrecompileShader(invalidShaderFlag);
- factory.AddPrecompileShader(invalidShaderFlag2);
- factory.AddPrecompileShader(unmatchedShaderOption);
- factory.AddPrecompileShader(unmatchedShaderOption2);
- factory.AddPrecompileShader(unmatchedShaderOption3);
-
- factory.UsePreCompiledShader();
-
- ShaderPreCompiler::Get().GetPreCompileShaderList(precompiledShaderList);
-
- DALI_TEST_EQUALS(precompiledShaderList.size(), PLATFORM_DEFAULT_PRECOMPILED_SHADER_COUNT, TEST_LOCATION);
-
- END_TEST;
-}
#include <dali/integration-api/events/touch-event-integ.h>
#include <dali/integration-api/events/wheel-event-integ.h>
#include <dali/public-api/images/pixel-data.h>
-#include <dali/devel-api/adaptor-framework/web-engine/web-engine-user-media-permission-request.h>
using namespace Dali;
using namespace Toolkit;
static int gFullscreenEnteredCallbackCalled = 0;
static int gFullscreenExitedCallbackCalled = 0;
static int gTextFoundCallbackCalled = 0;
-static int gWebAuthDisplayQRCalled = 0;
-static int gWebAuthDisplayResponseCalled = 0;
-static int gUserMediaPermissionRequestCalled = 0;
struct CallbackFunctor
{
gTextFoundCallbackCalled++;
}
-static void OnWebAuthDisplayQR(const std::string&)
-{
- gWebAuthDisplayQRCalled++;
-}
-
-static void OnWebAuthResponse()
-{
- gWebAuthDisplayResponseCalled++;
-}
-
-static void OnUserMediaPermissionRequest(std::unique_ptr<Dali::WebEngineUserMediaPermissionRequest> request, const std::string& msg)
-{
- gUserMediaPermissionRequestCalled++;
-}
-
} // namespace
void web_view_startup(void)
ToolkitTestApplication application;
char argv[] = "--test";
- WebView view = WebView::New(1, (char**)&argv, 0);
+ WebView view = WebView::New(1, (char**)&argv);
DALI_TEST_CHECK(view);
// Check GetScreenshot
DALI_TEST_EQUALS(gTextFoundCallbackCalled, 1, TEST_LOCATION);
END_TEST;
}
-
-int UtcDaliWebViewRegisterWebAuthDisplayQRCallback(void)
-{
- ToolkitTestApplication application;
-
- WebView view = WebView::New();
- DALI_TEST_CHECK(view);
-
- view.RegisterWebAuthDisplayQRCallback(&OnWebAuthDisplayQR);
- DALI_TEST_EQUALS(gWebAuthDisplayQRCalled, 0, TEST_LOCATION);
-
- view.LoadUrl(TEST_URL1);
- Test::EmitGlobalTimerSignal();
- DALI_TEST_EQUALS(gWebAuthDisplayQRCalled, 1, TEST_LOCATION);
- END_TEST;
-}
-
-int UtcDaliWebViewRegisterWebAuthResponseCallback(void)
-{
- ToolkitTestApplication application;
-
- WebView view = WebView::New();
- DALI_TEST_CHECK(view);
-
- view.RegisterWebAuthResponseCallback(&OnWebAuthResponse);
- DALI_TEST_EQUALS(gWebAuthDisplayResponseCalled, 0, TEST_LOCATION);
-
- view.LoadUrl(TEST_URL1);
- Test::EmitGlobalTimerSignal();
- DALI_TEST_EQUALS(gWebAuthDisplayResponseCalled, 1, TEST_LOCATION);
- END_TEST;
-}
-
-int UtcDaliWebViewRegisterUserMediaPermissionRequestCallback(void)
-{
- ToolkitTestApplication application;
-
- WebView view = WebView::New();
- DALI_TEST_CHECK(view);
-
- view.RegisterUserMediaPermissionRequestCallback(&OnUserMediaPermissionRequest);
- DALI_TEST_EQUALS(gUserMediaPermissionRequestCalled, 0, TEST_LOCATION);
-
- view.LoadUrl(TEST_URL1);
- Test::EmitGlobalTimerSignal();
- DALI_TEST_EQUALS(gUserMediaPermissionRequestCalled, 1, TEST_LOCATION);
- END_TEST;
-}
-
-int UtcDaliWebViewWebAuthenticationCancel(void)
-{
- ToolkitTestApplication application;
-
- WebView view = WebView::New();
- DALI_TEST_CHECK(view);
-
- try
- {
- // Just call API and exception check.
- view.WebAuthenticationCancel();
- tet_result(TET_PASS);
- }
- catch(...)
- {
- // Should not throw exception
- tet_result(TET_FAIL);
- }
-
- END_TEST;
-}
+++ /dev/null
-SET(PKG_NAME "dali-usd-loader-dynamic-lib-func-override")
-
-SET(EXEC_NAME "tct-${PKG_NAME}-core")
-SET(RPM_NAME "core-${PKG_NAME}-tests")
-
-SET(CAPI_LIB "dali-usd-loader-dynamic-lib-func-override")
-
-# List of test case sources (Only these get parsed for test cases)
-SET(TC_SOURCES
- utc-Dali-UsdLoaderDynamicLibFuncOverride.cpp
- )
-
-# List of test harness files (Won't get parsed for test cases)
-SET(TEST_HARNESS_DIR "../dali-toolkit/dali-toolkit-test-utils")
-
-SET(TEST_HARNESS_SOURCES
- ${TEST_HARNESS_DIR}/toolkit-adaptor.cpp
- ${TEST_HARNESS_DIR}/toolkit-application.cpp
- ${TEST_HARNESS_DIR}/toolkit-async-task-manager.cpp
- ${TEST_HARNESS_DIR}/toolkit-event-thread-callback.cpp
- ${TEST_HARNESS_DIR}/toolkit-environment-variable.cpp
- ${TEST_HARNESS_DIR}/toolkit-input-method-context.cpp
- ${TEST_HARNESS_DIR}/toolkit-input-method-options.cpp
- ${TEST_HARNESS_DIR}/toolkit-lifecycle-controller.cpp
- ${TEST_HARNESS_DIR}/toolkit-orientation.cpp
- ${TEST_HARNESS_DIR}/toolkit-style-monitor.cpp
- ${TEST_HARNESS_DIR}/toolkit-test-application.cpp
- ${TEST_HARNESS_DIR}/toolkit-timer.cpp
- ${TEST_HARNESS_DIR}/toolkit-trigger-event-factory.cpp
- ${TEST_HARNESS_DIR}/toolkit-window.cpp
- ${TEST_HARNESS_DIR}/toolkit-scene-holder.cpp
- ${TEST_HARNESS_DIR}/dali-test-suite-utils.cpp
- ${TEST_HARNESS_DIR}/dali-toolkit-test-suite-utils.cpp
- ${TEST_HARNESS_DIR}/dummy-control.cpp
- ${TEST_HARNESS_DIR}/mesh-builder.cpp
- ${TEST_HARNESS_DIR}/test-actor-utils.cpp
- ${TEST_HARNESS_DIR}/test-animation-data.cpp
- ${TEST_HARNESS_DIR}/test-application.cpp
- ${TEST_HARNESS_DIR}/test-button.cpp
- ${TEST_HARNESS_DIR}/test-harness.cpp
- ${TEST_HARNESS_DIR}/test-gesture-generator.cpp
- ${TEST_HARNESS_DIR}/test-gl-abstraction.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sync-impl.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sync-object.cpp
- ${TEST_HARNESS_DIR}/test-graphics-buffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-command-buffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-framebuffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-controller.cpp
- ${TEST_HARNESS_DIR}/test-graphics-texture.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sampler.cpp
- ${TEST_HARNESS_DIR}/test-graphics-program.cpp
- ${TEST_HARNESS_DIR}/test-graphics-pipeline.cpp
- ${TEST_HARNESS_DIR}/test-graphics-shader.cpp
- ${TEST_HARNESS_DIR}/test-graphics-reflection.cpp
- ${TEST_HARNESS_DIR}/test-platform-abstraction.cpp
- ${TEST_HARNESS_DIR}/test-render-controller.cpp
- ${TEST_HARNESS_DIR}/test-render-surface.cpp
- ${TEST_HARNESS_DIR}/test-trace-call-stack.cpp
-)
-
-PKG_CHECK_MODULES(${CAPI_LIB} REQUIRED
- dali2-core
- dali2-adaptor
- dali2-toolkit
- dali2-scene3d
-)
-
-ADD_COMPILE_OPTIONS( -O0 -ggdb --coverage -Wall -Werror -DDEBUG_ENABLED)
-ADD_COMPILE_OPTIONS( ${${CAPI_LIB}_CFLAGS_OTHER} )
-
-ADD_DEFINITIONS(-DTEST_RESOURCE_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/../../resources\" )
-
-FOREACH(directory ${${CAPI_LIB}_LIBRARY_DIRS})
- SET(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -L${directory}")
-ENDFOREACH(directory ${CAPI_LIB_LIBRARY_DIRS})
-
-INCLUDE_DIRECTORIES(
- ../../../
- ${${CAPI_LIB}_INCLUDE_DIRS}
- ../dali-toolkit/dali-toolkit-test-utils
-)
-
-ADD_CUSTOM_COMMAND(
- COMMAND ${SCRIPT_DIR}/tcheadgen.sh ${EXEC_NAME}.h ${TC_SOURCES}
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- OUTPUT ${EXEC_NAME}.h
- COMMENT "Generating test tables"
- )
-
-ADD_EXECUTABLE(${EXEC_NAME} ${EXEC_NAME}.h ${EXEC_NAME}.cpp ${TC_SOURCES} ${TEST_HARNESS_SOURCES})
-TARGET_LINK_LIBRARIES(${EXEC_NAME}
- ${${CAPI_LIB}_LIBRARIES}
- -lpthread -ldl --coverage
-)
-
-INSTALL(PROGRAMS ${EXEC_NAME}
- DESTINATION ${BIN_DIR}/${EXEC_NAME}
-)
+++ /dev/null
-#include <test-harness.h>
-
-// Must come second
-#include "tct-dali-usd-loader-dynamic-lib-func-override-core.h"
-
-int main(int argc, char* const argv[])
-{
- return TestHarness::RunTests(argc, argv, tc_array);
-}
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// Enable debug log for test coverage
-#define DEBUG_ENABLED 1
-
-#include <dali-scene3d/public-api/loader/load-result.h>
-#include <dali-scene3d/public-api/loader/model-loader.h>
-#include <dali-scene3d/public-api/loader/resource-bundle.h>
-#include <dali-scene3d/public-api/loader/scene-definition.h>
-#include <dali-test-suite-utils.h>
-#include <dlfcn.h>
-#include <string_view>
-
-using namespace Dali;
-using namespace Dali::Scene3D::Loader;
-
-namespace
-{
-struct Context
-{
- ResourceBundle::PathProvider pathProvider = [](ResourceType::Value type) {
- return TEST_RESOURCE_DIR "/";
- };
-
- ResourceBundle resources;
- SceneDefinition scene;
- SceneMetadata metaData;
-
- std::vector<AnimationDefinition> animations;
- std::vector<AnimationGroupDefinition> animationGroups;
- std::vector<CameraParameters> cameras;
- std::vector<LightParameters> lights;
-
- LoadResult loadResult{
- resources,
- scene,
- metaData,
- animations,
- animationGroups,
- cameras,
- lights};
-
- Dali::Scene3D::Loader::ModelLoader* loader;
-};
-
-bool gDlopenOverrideEnabled = false;
-bool gDlsymOverrideEnabled = false;
-
-extern "C" void* DlopenProxy(const char* filename, int flag)
-{
- if(gDlopenOverrideEnabled)
- {
- return nullptr;
- }
- else
- {
- return dlopen("libdali2-scene3d.so", RTLD_LAZY);
- }
-}
-
-extern "C" void* DlsymProxy(void* handle, const char* symbol)
-{
- if(gDlsymOverrideEnabled)
- {
- return nullptr;
- }
- else
- {
- return dlsym(handle, symbol);
- }
-}
-
-} // namespace
-
-int UtcDaliUsdLoaderDlopenFail(void)
-{
- // Only make dlopen fail
- gDlopenOverrideEnabled = true;
- gDlsymOverrideEnabled = false;
-
- Context ctx;
-
- ctx.loader = new Dali::Scene3D::Loader::ModelLoader(TEST_RESOURCE_DIR "/usd/CesiumMan.usdz", ctx.pathProvider(ResourceType::Mesh) + "/", ctx.loadResult);
- DALI_TEST_EQUAL(ctx.loader->LoadModel(ctx.pathProvider, true), false);
-
- DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
- DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
-
- DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
- DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
- DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
-
- DALI_TEST_EQUAL(0, ctx.cameras.size());
- DALI_TEST_EQUAL(0, ctx.lights.size());
- DALI_TEST_EQUAL(0, ctx.animations.size());
- DALI_TEST_EQUAL(0, ctx.animationGroups.size());
-
- delete ctx.loader;
-
- END_TEST;
-}
-
-int UtcDaliUsdLoaderDlsymFail(void)
-{
- // Only make dlsym fail
- gDlopenOverrideEnabled = false;
- gDlsymOverrideEnabled = true;
-
- Context ctx;
-
- ctx.loader = new Dali::Scene3D::Loader::ModelLoader(TEST_RESOURCE_DIR "/usd/CesiumMan.usdz", ctx.pathProvider(ResourceType::Mesh) + "/", ctx.loadResult);
- DALI_TEST_EQUAL(ctx.loader->LoadModel(ctx.pathProvider, true), false);
-
- DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
- DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
-
- DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
- DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
- DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
-
- DALI_TEST_EQUAL(0, ctx.cameras.size());
- DALI_TEST_EQUAL(0, ctx.lights.size());
- DALI_TEST_EQUAL(0, ctx.animations.size());
- DALI_TEST_EQUAL(0, ctx.animationGroups.size());
-
- delete ctx.loader;
-
- END_TEST;
-}
+++ /dev/null
-SET(PKG_NAME "dali-usd-loader")
-
-SET(EXEC_NAME "tct-${PKG_NAME}-core")
-SET(RPM_NAME "core-${PKG_NAME}-tests")
-
-SET(CAPI_LIB "dali-usd-loader")
-
-# List of test case sources (Only these get parsed for test cases)
-SET(TC_SOURCES
- utc-Dali-UsdLoader.cpp
- )
-
-# List of test harness files (Won't get parsed for test cases)
-SET(TEST_HARNESS_DIR "../dali-toolkit/dali-toolkit-test-utils")
-
-SET(TEST_HARNESS_SOURCES
- ${TEST_HARNESS_DIR}/toolkit-adaptor.cpp
- ${TEST_HARNESS_DIR}/toolkit-application.cpp
- ${TEST_HARNESS_DIR}/toolkit-async-task-manager.cpp
- ${TEST_HARNESS_DIR}/toolkit-event-thread-callback.cpp
- ${TEST_HARNESS_DIR}/toolkit-environment-variable.cpp
- ${TEST_HARNESS_DIR}/toolkit-input-method-context.cpp
- ${TEST_HARNESS_DIR}/toolkit-input-method-options.cpp
- ${TEST_HARNESS_DIR}/toolkit-lifecycle-controller.cpp
- ${TEST_HARNESS_DIR}/toolkit-orientation.cpp
- ${TEST_HARNESS_DIR}/toolkit-style-monitor.cpp
- ${TEST_HARNESS_DIR}/toolkit-test-application.cpp
- ${TEST_HARNESS_DIR}/toolkit-timer.cpp
- ${TEST_HARNESS_DIR}/toolkit-trigger-event-factory.cpp
- ${TEST_HARNESS_DIR}/toolkit-window.cpp
- ${TEST_HARNESS_DIR}/toolkit-scene-holder.cpp
- ${TEST_HARNESS_DIR}/dali-test-suite-utils.cpp
- ${TEST_HARNESS_DIR}/dali-toolkit-test-suite-utils.cpp
- ${TEST_HARNESS_DIR}/dummy-control.cpp
- ${TEST_HARNESS_DIR}/mesh-builder.cpp
- ${TEST_HARNESS_DIR}/test-actor-utils.cpp
- ${TEST_HARNESS_DIR}/test-animation-data.cpp
- ${TEST_HARNESS_DIR}/test-application.cpp
- ${TEST_HARNESS_DIR}/test-button.cpp
- ${TEST_HARNESS_DIR}/test-harness.cpp
- ${TEST_HARNESS_DIR}/test-gesture-generator.cpp
- ${TEST_HARNESS_DIR}/test-gl-abstraction.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sync-impl.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sync-object.cpp
- ${TEST_HARNESS_DIR}/test-graphics-buffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-command-buffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-framebuffer.cpp
- ${TEST_HARNESS_DIR}/test-graphics-controller.cpp
- ${TEST_HARNESS_DIR}/test-graphics-texture.cpp
- ${TEST_HARNESS_DIR}/test-graphics-sampler.cpp
- ${TEST_HARNESS_DIR}/test-graphics-program.cpp
- ${TEST_HARNESS_DIR}/test-graphics-pipeline.cpp
- ${TEST_HARNESS_DIR}/test-graphics-shader.cpp
- ${TEST_HARNESS_DIR}/test-graphics-reflection.cpp
- ${TEST_HARNESS_DIR}/test-platform-abstraction.cpp
- ${TEST_HARNESS_DIR}/test-render-controller.cpp
- ${TEST_HARNESS_DIR}/test-render-surface.cpp
- ${TEST_HARNESS_DIR}/test-trace-call-stack.cpp
-)
-
-PKG_CHECK_MODULES(${CAPI_LIB} REQUIRED
- dali2-core
- dali2-adaptor
- dali2-toolkit
- dali2-scene3d
- dali2-usd-loader
-)
-
-ADD_COMPILE_OPTIONS( -O0 -ggdb --coverage -Wall -Werror -DDEBUG_ENABLED)
-ADD_COMPILE_OPTIONS( ${${CAPI_LIB}_CFLAGS_OTHER} )
-
-ADD_DEFINITIONS(-DTEST_RESOURCE_DIR=\"${CMAKE_CURRENT_SOURCE_DIR}/../../resources\" )
-
-FOREACH(directory ${${CAPI_LIB}_LIBRARY_DIRS})
- SET(CMAKE_CXX_LINK_FLAGS "${CMAKE_CXX_LINK_FLAGS} -L${directory}")
-ENDFOREACH(directory ${CAPI_LIB_LIBRARY_DIRS})
-
-INCLUDE_DIRECTORIES(
- ../../../
- ${${CAPI_LIB}_INCLUDE_DIRS}
- ../dali-toolkit/dali-toolkit-test-utils
-)
-
-ADD_CUSTOM_COMMAND(
- COMMAND ${SCRIPT_DIR}/tcheadgen.sh ${EXEC_NAME}.h ${TC_SOURCES}
- WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}
- OUTPUT ${EXEC_NAME}.h
- COMMENT "Generating test tables"
- )
-
-ADD_EXECUTABLE(${EXEC_NAME} ${EXEC_NAME}.h ${EXEC_NAME}.cpp ${TC_SOURCES} ${TEST_HARNESS_SOURCES})
-TARGET_LINK_LIBRARIES(${EXEC_NAME}
- ${${CAPI_LIB}_LIBRARIES}
- -lpthread -ldl --coverage
-)
-
-INSTALL(PROGRAMS ${EXEC_NAME}
- DESTINATION ${BIN_DIR}/${EXEC_NAME}
-)
+++ /dev/null
-#include <test-harness.h>
-
-// Must come second
-#include "tct-dali-usd-loader-core.h"
-
-int main(int argc, char* const argv[])
-{
- return TestHarness::RunTests(argc, argv, tc_array);
-}
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// Enable debug log for test coverage
-#define DEBUG_ENABLED 1
-
-#include <dali-scene3d/public-api/loader/load-result.h>
-#include <dali-scene3d/public-api/loader/model-loader.h>
-#include <dali-scene3d/public-api/loader/resource-bundle.h>
-#include <dali-scene3d/public-api/loader/scene-definition.h>
-#include <dali-scene3d/public-api/loader/shader-manager.h>
-#include <dali-test-suite-utils.h>
-#include <string_view>
-
-using namespace Dali;
-using namespace Dali::Scene3D::Loader;
-
-namespace
-{
-struct Context
-{
- ResourceBundle::PathProvider pathProvider = [](ResourceType::Value type) {
- return TEST_RESOURCE_DIR "/";
- };
-
- ResourceBundle resources;
- SceneDefinition scene;
- SceneMetadata metaData;
-
- std::vector<AnimationDefinition> animations;
- std::vector<AnimationGroupDefinition> animationGroups;
- std::vector<CameraParameters> cameras;
- std::vector<LightParameters> lights;
-
- LoadResult loadResult{
- resources,
- scene,
- metaData,
- animations,
- animationGroups,
- cameras,
- lights};
-
- Dali::Scene3D::Loader::ModelLoader* loader;
-};
-
-struct ExceptionMessageStartsWith
-{
- const std::string_view expected;
-
- bool operator()(const std::runtime_error& e)
- {
- const bool success = (0 == strncmp(e.what(), expected.data(), expected.size()));
- if(!success)
- {
- printf("Expected: %s, got: %s.\n", expected.data(), e.what());
- }
- return success;
- }
-};
-
-} // namespace
-
-int UtcDaliUsdLoaderFailedToLoad(void)
-{
- Context ctx;
-
- ctx.loader = new Dali::Scene3D::Loader::ModelLoader(TEST_RESOURCE_DIR "non-existent.usdz", ctx.pathProvider(ResourceType::Mesh) + "/", ctx.loadResult);
- DALI_TEST_EQUAL(ctx.loader->LoadModel(ctx.pathProvider, true), false);
-
- DALI_TEST_EQUAL(0, ctx.scene.GetRoots().size());
- DALI_TEST_EQUAL(0, ctx.scene.GetNodeCount());
-
- DALI_TEST_EQUAL(0, ctx.resources.mEnvironmentMaps.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMaterials.size());
- DALI_TEST_EQUAL(0, ctx.resources.mMeshes.size());
- DALI_TEST_EQUAL(0, ctx.resources.mShaders.size());
- DALI_TEST_EQUAL(0, ctx.resources.mSkeletons.size());
-
- DALI_TEST_EQUAL(0, ctx.cameras.size());
- DALI_TEST_EQUAL(0, ctx.lights.size());
- DALI_TEST_EQUAL(0, ctx.animations.size());
- DALI_TEST_EQUAL(0, ctx.animationGroups.size());
-
- delete ctx.loader;
-
- END_TEST;
-}
-
-int UtcDaliUsdLoaderSuccess1(void)
-{
- TestApplication app;
-
- Context ctx;
-
- /**
- * Converted from the CesiumMan glTF file and its Assets
- * Donated by Cesium for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/CesiumMan
- */
- ctx.loader = new Dali::Scene3D::Loader::ModelLoader(TEST_RESOURCE_DIR "/usd/CesiumMan.usdz", ctx.pathProvider(ResourceType::Mesh) + "/", ctx.loadResult);
- DALI_TEST_EQUAL(ctx.loader->LoadModel(ctx.pathProvider, true), true);
-
- auto& resources = ctx.resources;
- resources.GenerateResources();
-
- auto& scene = ctx.scene;
- auto& roots = scene.GetRoots();
-
- DALI_TEST_EQUAL(1u, roots.size());
- DALI_TEST_EQUAL(7u, scene.GetNodeCount());
-
- // Default envmap is used
- DALI_TEST_EQUAL(1u, resources.mEnvironmentMaps.size());
-
- // Check meshes
- auto& meshes = resources.mMeshes;
- DALI_TEST_EQUAL(1u, meshes.size());
- {
- auto& md = meshes[0u].first;
- DALI_TEST_EQUAL(md.mFlags, uint32_t(MeshDefinition::U32_INDICES));
- DALI_TEST_EQUAL(md.mPrimitiveType, Geometry::TRIANGLES);
- DALI_TEST_CHECK(md.mRawData);
- DALI_TEST_EQUAL(md.mRawData->mIndices.size(), 28032u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs.size(), 5u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[0].mName, "aPosition");
- DALI_TEST_EQUAL(md.mRawData->mAttribs[0].mType, Property::VECTOR3);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[0].mNumElements, 14016u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[0].mData.size(), 168192u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[1].mName, "aNormal");
- DALI_TEST_EQUAL(md.mRawData->mAttribs[1].mType, Property::VECTOR3);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[1].mNumElements, 14016u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[1].mData.size(), 168192u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[2].mName, "aTexCoord");
- DALI_TEST_EQUAL(md.mRawData->mAttribs[2].mType, Property::VECTOR2);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[2].mNumElements, 14016u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[2].mData.size(), 112128u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[3].mName, "aTangent");
- DALI_TEST_EQUAL(md.mRawData->mAttribs[3].mType, Property::VECTOR3);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[3].mNumElements, 14016u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[3].mData.size(), 168192u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[4].mName, "aVertexColor");
- DALI_TEST_EQUAL(md.mRawData->mAttribs[4].mType, Property::VECTOR4);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[4].mNumElements, 14016u);
- DALI_TEST_EQUAL(md.mRawData->mAttribs[4].mData.size(), 224256u);
- DALI_TEST_CHECK(meshes[0u].second.geometry);
- }
-
- // Check materials
- auto& materials = resources.mMaterials;
- DALI_TEST_EQUAL(1u, materials.size());
- {
- auto& md = materials[0u].first;
- DALI_TEST_EQUAL(md.mFlags, MaterialDefinition::ALBEDO | MaterialDefinition::GLTF_CHANNELS);
- DALI_TEST_EQUAL(md.mEnvironmentIdx, 0);
- DALI_TEST_EQUAL(md.mColor, Color::WHITE);
- DALI_TEST_EQUAL(md.mMetallic, 1.0f);
- DALI_TEST_EQUAL(md.mRoughness, 1.0f);
- DALI_TEST_EQUAL(md.mBaseColorFactor, Vector4::ONE);
- DALI_TEST_EQUAL(md.mNormalScale, 1.0f);
- DALI_TEST_EQUAL(md.mOcclusionStrength, 1.0f);
- DALI_TEST_EQUAL(md.mEmissiveFactor, Vector3::ZERO);
- DALI_TEST_EQUAL(md.mIor, -1.0f);
- DALI_TEST_EQUAL(md.mDielectricSpecular, 0.04f);
- DALI_TEST_EQUAL(md.mSpecularFactor, 1.0f);
- DALI_TEST_EQUAL(md.mSpecularColorFactor, Vector3::ONE);
- DALI_TEST_EQUAL(md.mNeedAlbedoTexture, true);
- DALI_TEST_EQUAL(md.mNeedMetallicRoughnessTexture, false);
- DALI_TEST_EQUAL(md.mNeedMetallicTexture, false);
- DALI_TEST_EQUAL(md.mNeedRoughnessTexture, false);
- DALI_TEST_EQUAL(md.mNeedNormalTexture, false);
- DALI_TEST_EQUAL(md.mAlphaModeType, Scene3D::Material::AlphaModeType::OPAQUE);
- DALI_TEST_EQUAL(md.mIsOpaque, true);
- DALI_TEST_EQUAL(md.mIsMask, false);
-
- DALI_TEST_EQUAL(md.mTextureStages.size(), 1u);
-
- auto iTexture = md.mTextureStages.begin();
- DALI_TEST_EQUAL(iTexture->mSemantic, uint32_t(MaterialDefinition::ALBEDO));
- DALI_TEST_EQUAL(iTexture->mTexture.mImageUri, "");
- DALI_TEST_EQUAL(uint32_t(iTexture->mTexture.mSamplerFlags), uint32_t(SamplerFlags::DEFAULT)); // don't interpret it as a character
- DALI_TEST_EQUAL(iTexture->mTexture.mMinImageDimensions, ImageDimensions());
- DALI_TEST_EQUAL(iTexture->mTexture.mSamplingMode, SamplingMode::BOX_THEN_LINEAR);
- DALI_TEST_EQUAL(iTexture->mTexture.mTextureBuffer.size(), 209908u);
-
- auto& ts = materials[0u].second;
- DALI_TEST_EQUAL(ts.GetTextureCount(), 5u);
- DALI_TEST_EQUAL(ts.GetTexture(0).GetWidth(), 1024);
- DALI_TEST_EQUAL(ts.GetTexture(0).GetHeight(), 1024);
- DALI_TEST_EQUAL(ts.GetTexture(1).GetWidth(), 1);
- DALI_TEST_EQUAL(ts.GetTexture(1).GetHeight(), 1);
- DALI_TEST_EQUAL(ts.GetTexture(2).GetWidth(), 256);
- DALI_TEST_EQUAL(ts.GetTexture(2).GetHeight(), 256);
- DALI_TEST_EQUAL(ts.GetTexture(3).GetWidth(), 1);
- DALI_TEST_EQUAL(ts.GetTexture(3).GetHeight(), 1);
- DALI_TEST_EQUAL(ts.GetTexture(4).GetWidth(), 1);
- DALI_TEST_EQUAL(ts.GetTexture(4).GetHeight(), 1);
- }
-
- DALI_TEST_EQUAL(0u, resources.mShaders.size());
- DALI_TEST_EQUAL(0u, resources.mSkeletons.size());
-
- Scene3D::Loader::ShaderManagerPtr shaderManager = new Scene3D::Loader::ShaderManager();
- ViewProjection viewProjection;
- Transforms xforms{
- MatrixStack{},
- viewProjection};
- NodeDefinition::CreateParams nodeParams{
- resources,
- xforms,
- shaderManager,
- };
-
- Customization::Choices choices;
-
- // Create DALi actors
- Actor root = Actor::New();
- SetActorCentered(root);
- for(auto iRoot : roots)
- {
- if(auto actor = scene.CreateNodes(iRoot, choices, nodeParams))
- {
- scene.ConfigureSkinningShaders(resources, actor, std::move(nodeParams.mSkinnables));
- scene.ApplyConstraints(actor, std::move(nodeParams.mConstrainables));
- root.Add(actor);
- }
- }
-
- DALI_TEST_CHECK(root.FindChildByName("Z_UP"));
- DALI_TEST_CHECK(root.FindChildByName("Armature"));
-
- delete ctx.loader;
-
- END_TEST;
-}
-
-int UtcDaliUsdLoaderSuccess2(void)
-{
- TestApplication app;
-
- Customization::Choices choices;
- for(auto modelName : {
- /**
- * Converted from the AntiqueCamera glTF file and its Assets
- * Donated by UX3D for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/AntiqueCamera
- */
- "AntiqueCamera",
- /**
- * Converted from the Avocado glTF file and its Assets
- * Donated by Microsoft for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Avocado
- */
- "Avocado",
- /**
- * Converted from the BoomBox glTF file and its Assets
- * Donated by Microsoft for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/BoomBox
- */
- "BoomBox",
- /**
- * Converted from the BarramundiFish glTF file and its Assets
- * Donated by Microsoft for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/BarramundiFish
- */
- "BarramundiFish",
- /**
- * Converted from the CesiumMan glTF file and its Assets
- * Donated by Cesium for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/CesiumMan
- */
- "CesiumMan",
- /**
- * Converted from the CesiumMilkTruck glTF file and its Assets
- * Donated by Cesium for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/CesiumMilkTruck
- */
- "CesiumMilkTruck",
- /**
- * Converted from the DamagedHelmet glTF file and its Assets
- * By theblueturtle, published under a Creative Commons Attribution-NonCommercial license
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/DamagedHelmet
- */
- "DamagedHelmet",
- /**
- * Converted from the Fox glTF file and its Assets
- * By PixelMannen, published under CC-BY 4.0 license
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Fox
- */
- "Fox",
- /**
- * Converted from the Lantern glTF file and its Assets
- * Donated by Microsoft for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/Lantern
- */
- "Lantern",
- /**
- * Converted from the MetalRoughSpheresNoTextures glTF file and its Assets
- * Donated by Kirill Gavrilov for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/MetalRoughSpheresNoTextures
- */
- "MetalRoughSpheresNoTextures",
- /**
- * Converted from the WaterBottle glTF file and its Assets
- * Donated by Microsoft for glTF testing
- * Take from https://github.com/KhronosGroup/glTF-Sample-Models/blob/master/2.0/WaterBottle
- */
- "WaterBottle",
- })
- {
- Context ctx;
-
- auto& resources = ctx.resources;
- resources.mEnvironmentMaps.push_back({});
-
- const std::string resourcePath = TEST_RESOURCE_DIR "/usd/";
-
- ctx.loader = new Dali::Scene3D::Loader::ModelLoader(resourcePath + modelName + ".usdz", ctx.pathProvider(ResourceType::Mesh) + "/", ctx.loadResult);
- DALI_TEST_EQUAL(ctx.loader->LoadModel(ctx.pathProvider, true), true);
-
- auto& scene = ctx.scene;
- DALI_TEST_CHECK(scene.GetNodeCount() > 0);
-
- resources.GenerateResources();
-
- DALI_TEST_CHECK(resources.mMaterials.size() > 0);
-
- for(auto iRoot : scene.GetRoots())
- {
- struct Visitor : NodeDefinition::IVisitor
- {
- struct ResourceReceiver : IResourceReceiver
- {
- std::vector<bool> mCounts;
-
- void Register(ResourceType::Value type, Index id) override
- {
- if(type == ResourceType::Mesh)
- {
- mCounts[id] = true;
- }
- }
- } receiver;
-
- void Start(NodeDefinition& n) override
- {
- for(auto& renderable : n.mRenderables)
- {
- renderable->RegisterResources(receiver);
- }
- }
-
- void Finish(NodeDefinition& n) override
- {
- }
- } visitor;
-
- visitor.receiver.mCounts.resize(resources.mMeshes.size(), false);
-
- scene.Visit(iRoot, choices, visitor);
-
- for(uint32_t i0 = 0, i1 = resources.mMeshes.size(); i0 < i1; ++i0)
- {
- if(visitor.receiver.mCounts[i0])
- {
- DALI_TEST_CHECK(!resources.mMeshes[i0].first.mRawData->mAttribs.empty());
- DALI_TEST_CHECK(resources.mMeshes[i0].second.geometry);
- }
- }
- }
-
- delete ctx.loader;
- }
-
- END_TEST;
-}
OPTION(USE_DEFAULT_RESOURCE_DIR "Whether to use the default resource folders. Otherwise set environment variables for DALI_IMAGE_DIR, DALI_SOUND_DIR, DALI_STYLE_DIR, DALI_STYLE_IMAGE_DIR and DALI_DATA_READ_ONLY_DIR" ON)
OPTION(BUILD_SCENE3D "Whether to build dali-scene3d." ON)
OPTION(BUILD_PHYSICS "Whether to build dali-physics." ON)
-OPTION(BUILD_USD_LOADER "Whether to build dali-usd-loader." OFF)
-
-# Search for OpenUSD headers and libraries
-find_path(OpenUSD_INCLUDE_DIR pxr/usd/usd/stage.h
- PATHS ${CMAKE_INSTALL_PREFIX}/ /usr/local/USD /usr/USD
- PATH_SUFFIXES include)
-
-find_library(OpenUSD_LIB usd_usd
- PATHS ${CMAKE_INSTALL_PREFIX}/ /usr/local/USD /usr/USD
- PATH_SUFFIXES lib)
-
-# Check if both include and library are found
-if(OpenUSD_INCLUDE_DIR AND OpenUSD_LIB)
- SET( BUILD_USD_LOADER ON )
- get_filename_component(USD_ROOT_DIR ${OpenUSD_INCLUDE_DIR} DIRECTORY)
- message(STATUS "OpenUSD found at: ${USD_ROOT_DIR}")
-else()
- message(WARNING "OpenUSD not found. Skipping the compilation of usd-loader files.")
-endif()
-
-if( BUILD_USD_LOADER )
- OPTION(USD_LOADER_ENABLED "Whether dali-usd-loader is enabled." ON)
-endif()
IF( ENABLE_PKG_CONFIGURE )
FIND_PACKAGE( PkgConfig REQUIRED )
ADD_SUBDIRECTORY( ${CMAKE_CURRENT_SOURCE_DIR}/dali-physics )
ENDIF()
-IF ( BUILD_USD_LOADER )
- ADD_SUBDIRECTORY( ${CMAKE_CURRENT_SOURCE_DIR}/dali-usd-loader )
-ENDIF()
-
# Build documentation if doxygen tool is available
SET( doxygenEnabled OFF )
IF( DOXYGEN_FOUND )
MESSAGE( STATUS "Configure automated tests: " ${CONFIGURE_AUTOMATED_TESTS} )
MESSAGE( STATUS "Build Dali Scene3D: " ${BUILD_SCENE3D} )
MESSAGE( STATUS "Build Dali Physics: " ${BUILD_PHYSICS} )
-MESSAGE( STATUS "Build Dali USD Loader: " ${BUILD_USD_LOADER} )
MESSAGE( STATUS "CXXFLAGS: " ${CMAKE_CXX_FLAGS} )
MESSAGE( STATUS "LDFLAGS: " ${CMAKE_SHARED_LINKER_FLAGS_INIT}${CMAKE_SHARED_LINKER_FLAGS} )
+++ /dev/null
-CMAKE_MINIMUM_REQUIRED(VERSION 3.8.2)
-set(name "dali2-usd-loader")
-
-project(${name} CXX)
-
-set(${name}_VERSION_MAJOR 2)
-set(${name}_VERSION_MINOR 0)
-set(${name}_VERSION_PATCH 0)
-set(${name}_VERSION ${${name}_VERSION_MAJOR}.${${name}_VERSION_MINOR}.${${name}_VERSION_PATCH} )
-
-SET(DALI_USD_LOADER_VERSION ${${name}_VERSION} )
-
-if(CMAKE_BUILD_TYPE MATCHES Debug)
- add_definitions("-DDEBUG_ENABLED")
-endif()
-
-add_definitions("-DBUILDING_DALI_USD_LOADER")
-
-foreach(flag ${PKGS_CFLAGS})
- set(extra_flags "${extra_flags} ${flag}")
-endforeach(flag)
-
-# The -fPIC option used here is to generate position-independent code (PIC) suitable for use in shared libraries.
-# Unlike the -fPIE option which generates position-independent executables (PIE) suitable for use in executable binaries.
-set(prj_cxx_std c++17)
-if(CMAKE_CXX_COMPILER_ID MATCHES "GNU")
- set(extra_flags "${extra_flags} -fPIC -std=${prj_cxx_std}")
-elseif(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
- set(extra_flags "${extra_flags} -fPIC -std=${prj_cxx_std}")
-elseif(CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
- set(extra_flags "${extra_flags} /std:${prj_cxx_std} /vmg /D_USE_MATH_DEFINES /D_CRT_SECURE_NO_WARNINGS /MP /GS /Oi /GL /EHsc")
-endif()
-
-set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${extra_flags} -Wno-deprecated")
-
-set(prefix ${CMAKE_INSTALL_PREFIX})
-
-set(repo_root_dir "${CMAKE_CURRENT_LIST_DIR}/../../..")
-set(usd_loader_dir "${repo_root_dir}/dali-usd-loader")
-
-option(ENABLE_PKG_CONFIGURE "Use pkgconfig" ON)
-option(ENABLE_COVERAGE "Coverage" OFF)
-
-if (ENABLE_PKG_CONFIGURE)
- find_package(PkgConfig REQUIRED)
-
- pkg_check_modules(DALICORE REQUIRED dali2-core)
- pkg_check_modules(DALIADAPTOR REQUIRED dali2-adaptor)
-
- # Configure the pkg-config file
- # Requires the following variables to be setup:
- # @PREFIX@ @EXEC_PREFIX@ @DALI_VERSION@ @LIB_DIR@ @DEV_INCLUDE_PATH@
- set( LIB_DIR $ENV{libdir} )
- if( NOT LIB_DIR )
- set( LIB_DIR ${CMAKE_INSTALL_LIBDIR} )
- endif()
- if( NOT LIB_DIR )
- set( LIB_DIR ${prefix}/lib )
- endif()
-
- set(PREFIX ${prefix})
- set(EXEC_PREFIX ${CMAKE_INSTALL_PREFIX})
- set(DEV_INCLUDE_PATH ${INCLUDE_DIR})
-
- set(core_pkg_cfg_file dali2-usd-loader.pc)
- configure_file(${CMAKE_CURRENT_LIST_DIR}/${core_pkg_cfg_file}.in ${core_pkg_cfg_file} @ONLY)
-endif()
-
-set(usd_loader_src_files "")
-include(${usd_loader_dir}/internal/file.list)
-
-set(prefix_include_dir "${prefix}/include")
-
-include_directories(BEFORE
- ${repo_root_dir}
- ${USD_ROOT_DIR}/include
-)
-
-include_directories(AFTER "${prefix_include_dir}")
-
-MESSAGE(STATUS "USD Loader sources: ${usd_loader_src_files}")
-
-ADD_LIBRARY("${name}" SHARED ${usd_loader_src_files} )
-
-TARGET_LINK_LIBRARIES("${name}" ${DALICORE_LDFLAGS} "-L${USD_ROOT_DIR}/lib"
- dali2-toolkit
- dali2-scene3d
- -lusd_usd -lusd_sdf -lusd_tf -lusd_usdGeom -lusd_usdShade -lusd_usdSkel -lusd_gf -lusd_vt
- ${COVERAGE})
-TARGET_COMPILE_OPTIONS("${name}" PUBLIC "-I${repo_root_dir}/dali-usd-loader/include")
-
-IF (ENABLE_PKG_CONFIGURE)
- INSTALL(FILES
- ${CMAKE_CURRENT_BINARY_DIR}/${core_pkg_cfg_file}
- DESTINATION ${LIB_DIR}/pkgconfig )
-ENDIF()
-
-IF( INSTALL_CMAKE_MODULES )
- MESSAGE(STATUS "Installing cmake modules & libs")
- SET_TARGET_PROPERTIES( ${name}
- PROPERTIES
- VERSION ${DALI_USD_LOADER_VERSION}
- SOVERSION ${${name}_VERSION_MAJOR}
- CLEAN_DIRECT_OUPUT 1
- )
-
- IF( ENABLE_DEBUG )
- SET( BIN_DIR "${BIN_DIR}/debug" )
- SET( LIB_DIR "${LIB_DIR}/debug" )
- ENDIF()
-
- # Install library
- INSTALL( TARGETS ${name}
- EXPORT ${name}-targets
- LIBRARY DESTINATION ${LIB_DIR}
- ARCHIVE DESTINATION ${LIB_DIR}
- RUNTIME DESTINATION ${BIN_DIR}
- )
-
- # Install the cmake modules.
- INSTALL(
- EXPORT ${name}-targets
- NAMESPACE ${name}::
- FILE ${name}-targets.cmake
- DESTINATION share/${name}
- )
-
- FILE(WRITE ${CMAKE_CURRENT_BINARY_DIR}/${name}-config.cmake "
- include(CMakeFindDependencyMacro)
- include(\${CMAKE_CURRENT_LIST_DIR}/${name}-targets.cmake)
- ")
- INSTALL(FILES ${CMAKE_CURRENT_BINARY_DIR}/${name}-config.cmake DESTINATION share/${name})
-
-ELSE()
- MESSAGE(STATUS "Installing libs")
- INSTALL( TARGETS ${name} DESTINATION ${LIB_DIR} )
-
-ENDIF()
+++ /dev/null
-prefix=@PREFIX@
-exec_prefix=@EXEC_PREFIX@
-apiversion=@DALI_USD_LOADER_VERSION@
-libdir=@LIB_DIR@
-includedir=@DEV_INCLUDE_PATH@
-
-Name: DALi Engine Usd Loader Library
-Description: Dali Usd Loader library
-Version: ${apiversion}
-Requires: dali2-scene3d
-Libs: -L${libdir} -ldali2-usd-loader
-Cflags: -I${includedir}
{
ImageInformation(const std::string url,
const Dali::ImageDimensions dimensions,
- Dali::SamplingMode::Type samplingMode)
+ Dali::FittingMode::Type fittingMode,
+ Dali::SamplingMode::Type samplingMode,
+ bool orientationCorrection)
: mUrl(url),
mDimensions(dimensions),
- mSamplingMode(samplingMode)
+ mFittingMode(fittingMode),
+ mSamplingMode(samplingMode),
+ mOrientationCorrection(orientationCorrection)
{
}
bool operator==(const ImageInformation& rhs) const
{
- return (mUrl == rhs.mUrl) && (mDimensions == rhs.mDimensions) && (mSamplingMode == rhs.mSamplingMode);
+ // Check url and orientation correction is enough.
+ return (mUrl == rhs.mUrl) && (mOrientationCorrection == rhs.mOrientationCorrection);
}
std::string mUrl;
Dali::ImageDimensions mDimensions;
- Dali::SamplingMode::Type mSamplingMode : 5;
+ Dali::FittingMode::Type mFittingMode;
+ Dali::SamplingMode::Type mSamplingMode;
+ bool mOrientationCorrection;
};
// Hash functor list
*hashTargetPtr++ = info.mDimensions.GetHeight() & 0xff;
*hashTargetPtr++ = (info.mDimensions.GetHeight() >> 8u) & 0xff;
- // Bit-pack the SamplingMode.
- *hashTargetPtr = (info.mSamplingMode);
+ // Bit-pack the FittingMode, SamplingMode and orientation correction.
+ // FittingMode=2bits, SamplingMode=3bits, orientationCorrection=1bit
+ *hashTargetPtr = (info.mFittingMode << 4u) | (info.mSamplingMode << 1) | (info.mOrientationCorrection ? 1 : 0);
+ }
+ else
+ {
+ // We are not including sizing information, but we still need an extra byte for orientationCorrection.
+ hashTarget.resize(1u);
+ hashTarget[0u] = info.mOrientationCorrection ? 't' : 'f';
}
return Dali::CalculateHash(info.mUrl) ^ Dali::CalculateHash(hashTarget);
{
oss << "d:" << info.mDimensions.GetWidth() << "x" << info.mDimensions.GetHeight() << " ";
}
- oss << "s:" << info.mSamplingMode << " ";
+ oss << "f:" << info.mFittingMode << " s:" << info.mSamplingMode << " c:" << info.mOrientationCorrection << " ";
oss << "u:" << info.mUrl << "]";
});
// Load the image synchronously (block the thread here).
- Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromFile(info.mUrl, info.mDimensions, Dali::FittingMode::DEFAULT, info.mSamplingMode, true);
+ Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromFile(info.mUrl, info.mDimensions, info.mFittingMode, info.mSamplingMode, info.mOrientationCorrection);
if(pixelBuffer)
{
pixelData = Dali::Devel::PixelBuffer::Convert(pixelBuffer, releasePixelData);
Dali::PixelData GetCachedPixelData(const std::string& url)
{
- return GetCachedPixelData(url, ImageDimensions(), SamplingMode::BOX_THEN_LINEAR);
+ return GetCachedPixelData(url, ImageDimensions(), FittingMode::DEFAULT, SamplingMode::BOX_THEN_LINEAR, true);
}
Dali::PixelData GetCachedPixelData(const std::string& url,
ImageDimensions dimensions,
- SamplingMode::Type samplingMode)
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection)
{
- ImageInformation info(url, dimensions, samplingMode);
+ ImageInformation info(url, dimensions, fittingMode, samplingMode, orientationCorrection);
if(gCacheImpl == nullptr)
{
DALI_LOG_INFO(gLogFilter, Debug::Verbose, "CacheImpl not prepared! load PixelData without cache.\n");
* @note If cache handler is not created yet, or destroyed due to app terminated, it will load image synchronously without cache.
* @param[in] url The URL of the image file to load
* @param[in] dimensions The width and height to fit the loaded image to
+ * @param[in] fittingMode The method used to fit the shape of the image before loading to the shape defined by the size parameter
* @param[in] samplingMode The filtering method used when sampling pixels from the input image while fitting it to desired size
+ * @param[in] orientationCorrection Reorient the image to respect any orientation metadata in its header
* @return A PixelData object containing the image, or an invalid object on failure
*/
Dali::PixelData GetCachedPixelData(const std::string& url,
ImageDimensions dimensions,
- SamplingMode::Type samplingMode);
+ FittingMode::Type fittingMode,
+ SamplingMode::Type samplingMode,
+ bool orientationCorrection);
} // namespace ImageResourceLoader
} // namespace Internal
if(gTraceFilter && gTraceFilter->IsTraceEnabled())
{
mStartTimeNanoSceonds = GetNanoseconds();
- DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOADING_TASK", [&](std::ostringstream& oss) { oss << "[u:" << mModelUrl << ",dir:" << mResourceDirectoryUrl << "]"; });
+ DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOADING_TASK", [&](std::ostringstream& oss)
+ { oss << "[u:" << mModelUrl << ",dir:" << mResourceDirectoryUrl << "]"; });
}
#endif
mResourceDirectoryUrl = std::string(modelUrl.parent_path()) + "/";
}
- Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type) {
+ Dali::Scene3D::Loader::ResourceBundle::PathProvider pathProvider = [&](Dali::Scene3D::Loader::ResourceType::Value type)
+ {
return mResourceDirectoryUrl;
};
- mModelLoader = std::make_unique<Dali::Scene3D::Loader::ModelLoader>(mModelUrl, mResourceDirectoryUrl, mLoadResult);
+ mModelLoader = std::make_shared<Dali::Scene3D::Loader::ModelLoader>(mModelUrl, mResourceDirectoryUrl, mLoadResult);
bool loadSucceeded = false;
if(gTraceFilter && gTraceFilter->IsTraceEnabled())
{
mEndTimeNanoSceonds = GetNanoseconds();
- DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOADING_TASK", [&](std::ostringstream& oss) {
+ DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOADING_TASK", [&](std::ostringstream& oss)
+ {
oss << std::fixed << std::setprecision(3);
oss << "[";
oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
#define DALI_SCENE3D_MODEL_LOAD_TASK_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// Undefined
ModelLoadTask& operator=(const ModelLoadTask& task) = delete;
- using ModelLoaderUniquePtr = std::unique_ptr<Dali::Scene3D::Loader::ModelLoader>;
-
- std::string mModelUrl;
- std::string mResourceDirectoryUrl;
- ModelLoaderUniquePtr mModelLoader;
- ModelCacheManager mModelCacheManager;
- Dali::Scene3D::Loader::LoadResult mLoadResult;
- bool mHasSucceeded;
+ std::string mModelUrl;
+ std::string mResourceDirectoryUrl;
+ std::shared_ptr<Dali::Scene3D::Loader::ModelLoader> mModelLoader;
+ ModelCacheManager mModelCacheManager;
+ Dali::Scene3D::Loader::LoadResult mLoadResult;
+ bool mHasSucceeded;
};
} // namespace Internal
#include <dali-toolkit/public-api/controls/control-impl.h>
#include <dali/devel-api/actors/actor-devel.h>
#include <dali/integration-api/adaptor-framework/adaptor.h>
+#include <dali/integration-api/debug.h>
#include <dali/public-api/math/math-utils.h>
#include <dali/public-api/object/type-registry-helper.h>
#include <dali/public-api/object/type-registry.h>
return value;
}
-Dali::Actor Panel::GetOffScreenRenderableSourceActor()
-{
- return (mRootLayer) ? mRootLayer : Dali::Actor();
-}
-
-bool Panel::IsOffScreenRenderTaskExclusive()
-{
- return (mRenderTask) ? mRenderTask.IsExclusive() : false;
-}
-
///////////////////////////////////////////////////////////
//
// Private methods
scaleConstraint.Apply();
UpdateProperties();
- SetOffScreenRenderableType(OffScreenRenderable::Type::FORWARD);
}
void Panel::OnSceneConnection(int depth)
Control::OnSceneDisconnection();
}
-void Panel::GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward)
-{
- tasks.clear();
- if(isForward)
- {
- if(mRenderTask)
- {
- tasks.push_back(mRenderTask);
- }
- }
-}
-
void Panel::SetTransparent(bool transparent)
{
if(mIsTransparent != transparent)
*/
static Property::Value GetProperty(BaseObject* object, Property::Index index);
- /**
- * @copydoc Toolkit::Internal::Control::GetOffScreenRenderableSourceActor
- */
- Dali::Actor GetOffScreenRenderableSourceActor() override;
-
- /**
- * @copydoc Toolkit::Internal::Control::IsOffScreenRenderTaskExclusive
- */
- bool IsOffScreenRenderTaskExclusive() override;
-
protected:
/**
* @brief Constructs a new Panel.
*/
void OnSceneDisconnection() override;
- /**
- * @copydoc CustomActorImpl::SetFirstOrderIndex()
- */
- void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) override;
-
private:
/**
* @brief Sets whether the plane is transparent or not.
DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "AlphaMaskUrl", STRING, ALPHA_MASK_URL)
DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "MaskContentScale", FLOAT, MASK_CONTENT_SCALE)
DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "CropToMask", BOOLEAN, CROP_TO_MASK)
-DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "CornerRadius", VECTOR4, CORNER_RADIUS)
-DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "CornerRadiusPolicy", FLOAT, CORNER_RADIUS_POLICY)
-DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "BorderlineWidth", FLOAT, BORDERLINE_WIDTH)
-DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "BorderlineColor", VECTOR4, BORDERLINE_COLOR)
-DALI_PROPERTY_REGISTRATION(Scene3D, SceneView, "BorderlineOffset", FLOAT, BORDERLINE_OFFSET)
DALI_TYPE_REGISTRATION_END()
-Property::Index RENDERING_BUFFER = Dali::Toolkit::Control::CONTROL_PROPERTY_END_INDEX + 1;
+Property::Index RENDERING_BUFFER = Dali::Toolkit::Control::CONTROL_PROPERTY_END_INDEX + 1;
static constexpr float MIM_CAPTURE_SIZE = 1.0f;
static constexpr int32_t DEFAULT_ORIENTATION = 0;
static constexpr int32_t INVALID_INDEX = -1;
// Compute ViewProjectionMatrix and store it to "tempViewProjectionMatrix" property
auto tempViewProjectionMatrixIndex = shadowLightCamera.RegisterProperty("tempViewProjectionMatrix", Matrix::IDENTITY);
- Constraint projectionMatrixConstraint = Constraint::New<Matrix>(shadowLightCamera, tempViewProjectionMatrixIndex, [](Matrix& output, const PropertyInputContainer& inputs) {
+ Constraint projectionMatrixConstraint = Constraint::New<Matrix>(shadowLightCamera, tempViewProjectionMatrixIndex, [](Matrix& output, const PropertyInputContainer& inputs)
+ {
Matrix worldMatrix = inputs[0]->GetMatrix();
float tangentFov_2 = tanf(inputs[4]->GetFloat());
float nearDistance = inputs[5]->GetFloat();
mSkyboxIntensity(1.0f),
mFailedCaptureCallbacks(nullptr),
mLightObservers(),
- mCornerRadiusPolicy(static_cast<int>(Toolkit::Visual::Transform::Policy::ABSOLUTE)),
mShaderManager(new Scene3D::Loader::ShaderManager())
{
}
return;
}
- auto foundLight = std::find_if(mLights.begin(), mLights.end(), [light](std::pair<Scene3D::Light, bool> lightEntity) -> bool { return (lightEntity.second && lightEntity.first == light); });
+ auto foundLight = std::find_if(mLights.begin(), mLights.end(), [light](std::pair<Scene3D::Light, bool> lightEntity) -> bool
+ { return (lightEntity.second && lightEntity.first == light); });
if(foundLight == mLights.end())
{
if(mUseFrameBuffer != useFramebuffer)
{
mUseFrameBuffer = useFramebuffer;
- SetOffScreenRenderableType((mUseFrameBuffer) ? OffScreenRenderable::Type::FORWARD : OffScreenRenderable::Type::NONE);
UpdateRenderTask();
- RequestRenderTaskReorder();
}
}
capturePossible = false;
}
- uint32_t width = std::max(1u, unsigned(size.width));
+ uint32_t width = std::max(1u, unsigned(size.width));
uint32_t height = std::max(1u, unsigned(size.height));
if(width > Dali::GetMaxTextureSize() || height > Dali::GetMaxTextureSize())
{
{
if(mAlphaMaskUrl != alphaMaskUrl)
{
- mAlphaMaskUrl = alphaMaskUrl;
- if(mUseFrameBuffer)
- {
- mMaskingPropertyChanged = true;
- UpdateRenderTask();
- }
+ mAlphaMaskUrl = alphaMaskUrl;
+ mMaskingPropertyChanged = true;
+ UpdateRenderTask();
}
}
if(mMaskContentScaleFactor != maskContentScaleFactor)
{
mMaskContentScaleFactor = maskContentScaleFactor;
- if(mUseFrameBuffer)
- {
- mMaskingPropertyChanged = true;
- UpdateRenderTask();
- }
+ mMaskingPropertyChanged = true;
+ UpdateRenderTask();
}
}
{
if(mCropToMask != enableCropToMask)
{
- mCropToMask = enableCropToMask;
- if(mUseFrameBuffer)
- {
- mMaskingPropertyChanged = true;
- UpdateRenderTask();
- }
+ mCropToMask = enableCropToMask;
+ mMaskingPropertyChanged = true;
+ UpdateRenderTask();
}
}
return mCropToMask;
}
-void SceneView::SetCornerRadius(Vector4 cornerRadius)
-{
- if(mCornerRadius != cornerRadius)
- {
- mCornerRadius = cornerRadius;
- if(mUseFrameBuffer)
- {
- mDecoratedVisualPropertyChanged = true;
- UpdateRenderTask();
- }
- }
-}
-
-Vector4 SceneView::GetCornerRadius() const
-{
- return mCornerRadius;
-}
-
-void SceneView::SetCornerRadiusPolicy(int cornerRadiusPolicy)
-{
- if(mCornerRadiusPolicy != cornerRadiusPolicy)
- {
- mCornerRadiusPolicy = cornerRadiusPolicy;
- if(mUseFrameBuffer)
- {
- mDecoratedVisualPropertyChanged = true;
- UpdateRenderTask();
- }
- }
-}
-
-int SceneView::GetCornerRadiusPolicy() const
-{
- return mCornerRadiusPolicy;
-}
-
-void SceneView::SetBorderlineWidth(float borderlineWidth)
-{
- if(!Dali::Equals(mBorderlineWidth, borderlineWidth))
- {
- mBorderlineWidth = borderlineWidth;
- if(mUseFrameBuffer)
- {
- mDecoratedVisualPropertyChanged = true;
- UpdateRenderTask();
- }
- }
-}
-
-float SceneView::GetBorderlineWidth() const
-{
- return mBorderlineWidth;
-}
-
-void SceneView::SetBorderlineColor(Vector4 borderlineColor)
-{
- if(mBorderlineColor != borderlineColor)
- {
- mBorderlineColor = borderlineColor;
- if(mUseFrameBuffer)
- {
- mDecoratedVisualPropertyChanged = true;
- UpdateRenderTask();
- }
- }
-}
-
-Vector4 SceneView::GetBorderlineColor() const
-{
- return mBorderlineColor;
-}
-
-void SceneView::SetBorderlineOffset(float borderlineOffset)
-{
- if(!Dali::Equals(mBorderlineOffset, borderlineOffset))
- {
- mBorderlineOffset = borderlineOffset;
- if(mUseFrameBuffer)
- {
- mDecoratedVisualPropertyChanged = true;
- UpdateRenderTask();
- }
- }
-}
-
-float SceneView::GetBorderlineOffset() const
-{
- return mBorderlineOffset;
-}
-
Dali::RenderTask SceneView::GetRenderTask()
{
return mRenderTask;
sceneViewImpl.EnableCropToMask(value.Get<bool>());
break;
}
- case Scene3D::SceneView::Property::CORNER_RADIUS:
- {
- sceneViewImpl.SetCornerRadius(value.Get<Vector4>());
- break;
- }
- case Scene3D::SceneView::Property::CORNER_RADIUS_POLICY:
- {
- sceneViewImpl.SetCornerRadiusPolicy(value.Get<int>());
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_WIDTH:
- {
- sceneViewImpl.SetBorderlineWidth(value.Get<float>());
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_COLOR:
- {
- sceneViewImpl.SetBorderlineColor(value.Get<Vector4>());
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_OFFSET:
- {
- sceneViewImpl.SetBorderlineOffset(value.Get<float>());
- break;
- }
}
}
}
value = sceneViewImpl.IsEnabledCropToMask();
break;
}
- case Scene3D::SceneView::Property::CORNER_RADIUS:
- {
- value = sceneViewImpl.GetCornerRadius();
- break;
- }
- case Scene3D::SceneView::Property::CORNER_RADIUS_POLICY:
- {
- value = sceneViewImpl.GetCornerRadiusPolicy();
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_WIDTH:
- {
- value = sceneViewImpl.GetBorderlineWidth();
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_COLOR:
- {
- value = sceneViewImpl.GetBorderlineColor();
- break;
- }
- case Scene3D::SceneView::Property::BORDERLINE_OFFSET:
- {
- value = sceneViewImpl.GetBorderlineOffset();
- break;
- }
}
}
return value;
}
-Dali::Actor SceneView::GetOffScreenRenderableSourceActor()
-{
- return (mRootLayer) ? mRootLayer : Dali::Actor();
-}
-
-bool SceneView::IsOffScreenRenderTaskExclusive()
-{
- return (mRenderTask) ? mRenderTask.IsExclusive() : false;
-}
-
///////////////////////////////////////////////////////////
//
// Private methods
mRenderTask.SetExclusive(true);
mRenderTask.SetInputEnabled(true);
mRenderTask.SetCullMode(false);
+ mRenderTask.SetOrderIndex(SCENE_ORDER_INDEX);
mRenderTask.SetScreenToFrameBufferMappingActor(Self());
UpdateRenderTask();
}
CameraActor selectedCamera = GetSelectedCamera();
- selectedCamera = selectedCamera ? selectedCamera : mDefaultCamera;
+ selectedCamera = selectedCamera ? selectedCamera : mDefaultCamera;
if(selectedCamera)
{
UpdateCamera(selectedCamera);
}
tempContainer.clear();
- for(auto&& capture : mCaptureContainer)
+ for(auto && capture : mCaptureContainer)
{
ResetCaptureData(capture.second);
}
Control::OnSceneDisconnection();
}
-void SceneView::GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward)
-{
- tasks.clear();
- if(isForward)
- {
- if(mShadowMapRenderTask)
- {
- tasks.push_back(mShadowMapRenderTask);
- }
- if(mRenderTask)
- {
- tasks.push_back(mRenderTask);
- }
- }
-}
-
void SceneView::OnInitialize()
{
Actor self = Self();
mDefaultCamera.SetProperty(Dali::Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER);
AddCamera(mDefaultCamera);
UpdateCamera(mDefaultCamera);
-
- if(mUseFrameBuffer)
- {
- SetOffScreenRenderableType(OffScreenRenderable::Type::FORWARD);
- }
}
void SceneView::OnChildAdd(Actor& child)
!Dali::Equals(currentFrameBuffer.GetColorTexture().GetWidth(), width) ||
!Dali::Equals(currentFrameBuffer.GetColorTexture().GetHeight(), height) ||
mMaskingPropertyChanged ||
- mDecoratedVisualPropertyChanged ||
mWindowSizeChanged)
{
mRootLayer.SetProperty(Dali::Actor::Property::COLOR_MODE, ColorMode::USE_OWN_COLOR);
imagePropertyMap.Insert(Toolkit::DevelImageVisual::Property::MASKING_TYPE, Toolkit::DevelImageVisual::MaskingType::MASKING_ON_RENDERING);
Self().RegisterProperty(Y_FLIP_MASK_TEXTURE, FLIP_MASK_TEXTURE);
}
- if(mCornerRadius != Vector4::ZERO)
- {
- imagePropertyMap.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS, mCornerRadius);
- imagePropertyMap.Insert(Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, mCornerRadiusPolicy);
- }
- if(!Dali::EqualsZero(mBorderlineWidth))
- {
- imagePropertyMap.Insert(Toolkit::DevelVisual::Property::BORDERLINE_WIDTH, mBorderlineWidth);
- imagePropertyMap.Insert(Toolkit::DevelVisual::Property::BORDERLINE_COLOR, mBorderlineColor);
- imagePropertyMap.Insert(Toolkit::DevelVisual::Property::BORDERLINE_OFFSET, mBorderlineOffset);
- }
mVisual = Toolkit::VisualFactory::Get().CreateVisual(imagePropertyMap);
Toolkit::DevelControl::RegisterVisual(*this, RENDERING_BUFFER, mVisual);
mRenderTask.SetClearEnabled(true);
mRenderTask.SetClearColor(Color::TRANSPARENT);
- mMaskingPropertyChanged = false;
- mDecoratedVisualPropertyChanged = false;
- mWindowSizeChanged = false;
+ mMaskingPropertyChanged = false;
+ mWindowSizeChanged = false;
}
}
else
{
- mRenderTask.SetOrderIndex(SCENE_ORDER_INDEX);
-
mRenderTask.SetViewportGuideActor(Self());
if(mRenderTask.GetFrameBuffer())
{
mShadowMapRenderTask.SetClearColor(Color::WHITE);
mShadowMapRenderTask.SetRenderPassTag(10);
mShadowMapRenderTask.SetCameraActor(GetImplementation(mShadowLight).GetCamera());
- }
-
- if(!mUseFrameBuffer)
- {
mShadowMapRenderTask.SetOrderIndex(SHADOW_ORDER_INDEX);
}
void SceneView::OnCaptureFinished(Dali::RenderTask& task)
{
- auto iter = std::find_if(mCaptureContainer.begin(), mCaptureContainer.end(), [task](std::pair<Dali::RenderTask, std::shared_ptr<CaptureData>> item) { return item.first == task; });
+ auto iter = std::find_if(mCaptureContainer.begin(), mCaptureContainer.end(), [task](std::pair<Dali::RenderTask, std::shared_ptr<CaptureData>> item)
+ { return item.first == task; });
if(iter != mCaptureContainer.end())
{
bool SceneView::OnTimeOut()
{
mTimerTickCount++;
- auto self = Self();
- Dali::Scene3D::SceneView handle(Dali::Scene3D::SceneView::DownCast(self));
+ auto self = Self();
+ Dali::Scene3D::SceneView handle(Dali::Scene3D::SceneView::DownCast(self));
std::vector<std::pair<Dali::RenderTask, std::shared_ptr<CaptureData>>> tempContainer;
for(auto&& capture : mCaptureContainer)
{
mCaptureFinishedSignal.Emit(handle, capture.second->mCaptureId, Dali::Toolkit::ImageUrl());
}
- for(auto&& capture : tempContainer)
+ for(auto && capture : tempContainer)
{
ResetCaptureData(capture.second);
}
tempContainer.clear();
int32_t tickCount = mTimerTickCount;
- auto it = std::remove_if(mCaptureContainer.begin(), mCaptureContainer.end(), [tickCount](std::pair<Dali::RenderTask, std::shared_ptr<CaptureData>> item) {
+ auto it = std::remove_if(mCaptureContainer.begin(), mCaptureContainer.end(), [tickCount](std::pair<Dali::RenderTask, std::shared_ptr<CaptureData>> item) {
return item.second->mStartTick + 1 < tickCount;
});
mCaptureContainer.erase(it, mCaptureContainer.end());
{
if(mTransitionSourceCamera && mTransitionDestinationCamera && !(mTransitionSourceCamera == mTransitionDestinationCamera))
{
- Vector3 sourceWorldPosition = mTransitionSourceCamera.GetProperty<Vector3>(Dali::Actor::Property::WORLD_POSITION);
+ Vector3 sourceWorldPosition = mTransitionSourceCamera.GetProperty<Vector3>(Dali::Actor::Property::WORLD_POSITION);
Quaternion sourceWorldOrientation = mTransitionSourceCamera.GetProperty<Quaternion>(Dali::Actor::Property::WORLD_ORIENTATION);
if(!CheckInside(mRootLayer, mTransitionDestinationCamera))
mRootLayer.Add(mTransitionDestinationCamera);
}
- Vector3 destinationWorldPosition;
- Quaternion destinationWorldOrientation;
- Vector3 destinationWorldScale;
+ Vector3 destinationWorldPosition;
+ Quaternion destinationWorldOrientation;
+ Vector3 destinationWorldScale;
Dali::Matrix destinationWorldTransform = Dali::DevelActor::GetWorldTransform(mTransitionDestinationCamera);
destinationWorldTransform.GetTransformComponents(destinationWorldPosition, destinationWorldOrientation, destinationWorldScale);
Dali::DevelCameraActor::ProjectionDirection destinationProjectionDirection = mTransitionDestinationCamera.GetProperty<Dali::DevelCameraActor::ProjectionDirection>(Dali::DevelCameraActor::Property::PROJECTION_DIRECTION);
if(mTransitionDestinationCamera.GetProjectionMode() == Dali::Camera::ProjectionMode::PERSPECTIVE_PROJECTION)
{
- float sourceFieldOfView = mTransitionSourceCamera.GetFieldOfView();
+ float sourceFieldOfView = mTransitionSourceCamera.GetFieldOfView();
float destinationFieldOfView = mTransitionDestinationCamera.GetFieldOfView();
if(sourceProjectionDirection != destinationProjectionDirection)
}
else
{
- float sourceOrthographicSize = mTransitionSourceCamera.GetProperty<float>(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE);
+ float sourceOrthographicSize = mTransitionSourceCamera.GetProperty<float>(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE);
float destinationOrthographicSize = mTransitionDestinationCamera.GetProperty<float>(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE);
if(sourceProjectionDirection != destinationProjectionDirection)
}
float destinationNearPlaneDistance = mTransitionDestinationCamera.GetNearClippingPlane();
- float destinationFarPlaneDistance = mTransitionDestinationCamera.GetFarClippingPlane();
+ float destinationFarPlaneDistance = mTransitionDestinationCamera.GetFarClippingPlane();
mTransitionCamera.SetNearClippingPlane(std::min(mTransitionSourceCamera.GetNearClippingPlane(), destinationNearPlaneDistance));
mTransitionCamera.SetFarClippingPlane(std::max(mTransitionSourceCamera.GetFarClippingPlane(), destinationFarPlaneDistance));
*/
bool IsEnabledCropToMask();
- /**
- * @brief Sets the radius value of each corner.
- * @param[in] cornerRadius Radius value of each corner.
- */
- void SetCornerRadius(Vector4 cornerRadius);
-
- /**
- * @brief Retrieves the radius value of each corner.
- * @return The radius value of each corner.
- */
- Vector4 GetCornerRadius() const;
-
- /**
- * @brief Sets the policy of corner radius value.
- * @param[in] cornerRadiusPolicy Policy of corner radius value.
- */
- void SetCornerRadiusPolicy(int cornerRadiusPolicy);
-
- /**
- * @brief Retrieves the policy of corner radius value.
- * @return The policy of corner radius value.
- */
- int GetCornerRadiusPolicy() const;
-
- /**
- * @brief Sets the width of borderline.
- * @param[in] borderlineWidth The width of borderline.
- */
- void SetBorderlineWidth(float borderlineWidth);
-
- /**
- * @brief Retrieves the width of borderline.
- * @return The width of borderline.
- */
- float GetBorderlineWidth() const;
-
- /**
- * @brief Sets the color of borderline.
- * @param[in] borderlineColor The color of borderline.
- */
- void SetBorderlineColor(Vector4 borderlineColor);
-
- /**
- * @brief Retrieves the color of borderline.
- * @return The color of borderline.
- */
- Vector4 GetBorderlineColor() const;
-
- /**
- * @brief Sets the offset of borderline.
- * @param[in] borderlineOffset The offset of borderline.
- */
- void SetBorderlineOffset(float borderlineOffset);
-
- /**
- * @brief Retrieves the offset of borderline.
- * @return The offset of borderline.
- */
- float GetBorderlineOffset() const;
-
/**
* @brief Gets current RenderTask
*/
*/
static Property::Value GetProperty(BaseObject* object, Property::Index index);
- /**
- * @copydoc Toolkit::Internal::Control::GetOffScreenRenderableSourceActor
- */
- Dali::Actor GetOffScreenRenderableSourceActor() override;
-
- /**
- * @copydoc Toolkit::Internal::Control::IsOffScreenRenderTaskExclusive
- */
- bool IsOffScreenRenderTaskExclusive() override;
-
protected:
/**
* @brief Constructs a new SceneView.
*/
void OnSceneDisconnection() override;
- /**
- * @copydoc CustomActorImpl::GetOffScreenRenderTasks()
- */
- void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) override;
-
/**
* @copydoc Toolkit::Control::OnInitialize()
*/
bool mCropToMask{true};
bool mMaskingPropertyChanged{false};
- // Corner Radius
- Vector4 mCornerRadius{Vector4::ZERO};
- int mCornerRadiusPolicy; ///< Should be initialize at .cpp
-
- // Borderline
- float mBorderlineWidth{0.0f};
- Vector4 mBorderlineColor{Color::BLACK};
- float mBorderlineOffset{0.0f};
-
- bool mDecoratedVisualPropertyChanged{false};
-
// Shader Factory
Dali::Scene3D::Loader::ShaderManagerPtr mShaderManager;
exposureFactor *= kInvSampleCount;
// Blend filtered shadow and shadow from fragment normal to allow soft filtering nearby where the NdotL is zero.
- highp float shadowFactor = clamp((NdotL + 0.5) * 2.0, 0.0, 1.0);
+ highp float shadowFactor = clamp((NdotL + 0.5) * 2.0, 0.0f, 1.0);
exposureFactor = mix(0.0, exposureFactor, shadowFactor);
}
else
#ifndef DALI_SCENE3D_LOADER_DLI_LOADER_IMPL_H
#define DALI_SCENE3D_LOADER_DLI_LOADER_IMPL_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali/public-api/common/vector-wrapper.h>
// INTERNAL INCLUDES
+#include <dali-scene3d/internal/loader/model-loader-impl.h>
#include <dali-scene3d/public-api/api.h>
#include <dali-scene3d/public-api/loader/animation-definition.h>
#include <dali-scene3d/public-api/loader/customization.h>
#include <dali-scene3d/public-api/loader/dli-input-parameter.h>
#include <dali-scene3d/public-api/loader/index.h>
-#include <dali-scene3d/public-api/loader/model-loader-impl.h>
#include <dali-scene3d/public-api/loader/node-definition.h>
#include <dali-scene3d/public-api/loader/string-callback.h>
void SetErrorCallback(StringCallback onError);
/**
- * @copydoc Dali::Scene3D::Loader::ModelLoaderImpl::LoadMode()
+ * @copydoc Dali::Scene3D::Loader::Internal::ModelLoaderImpl::LoadMode()
*/
bool LoadModel(const std::string& uri, Dali::Scene3D::Loader::LoadResult& result) override;
#ifndef DALI_SCENE3D_LOADER_GLB_LOADER_IMPL_H
#define DALI_SCENE3D_LOADER_GLB_LOADER_IMPL_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <string>
// INTERNAL INCLUDES
+#include <dali-scene3d/internal/loader/model-loader-impl.h>
#include <dali-scene3d/public-api/api.h>
-#include <dali-scene3d/public-api/loader/model-loader-impl.h>
namespace Dali::Scene3D::Loader::Internal
{
{
public:
/**
- * @copydoc Dali::Scene3D::Loader::ModelLoaderImpl::LoadMode()
+ * @copydoc Dali::Scene3D::Loader::Internal::ModelLoaderImpl::LoadMode()
*/
bool LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result) override;
};
#ifndef DALI_SCENE3D_LOADER_GLTF2_LOADER_IMPL_H
#define DALI_SCENE3D_LOADER_GLTF2_LOADER_IMPL_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <string>
// INTERNAL INCLUDES
+#include <dali-scene3d/internal/loader/model-loader-impl.h>
#include <dali-scene3d/public-api/api.h>
-#include <dali-scene3d/public-api/loader/model-loader-impl.h>
namespace Dali::Scene3D::Loader::Internal
{
{
public:
/**
- * @copydoc Dali::Scene3D::Loader::odelLoaderImpl::LoadMode()
+ * @copydoc Dali::Scene3D::Loader::Internal::ModelLoaderImpl::LoadMode()
*/
bool LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result) override;
};
--- /dev/null
+#ifndef DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
+#define DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
+/*
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ */
+
+// INTERNAL INCLUDES
+#include <dali-scene3d/public-api/api.h>
+#include <dali-scene3d/public-api/loader/load-result.h>
+#include <dali-scene3d/public-api/loader/model-loader.h>
+#include <dali-scene3d/public-api/loader/resource-bundle.h>
+
+// EXTERNAL INCLUDES
+#include <string>
+
+namespace Dali
+{
+namespace Scene3D
+{
+namespace Loader
+{
+namespace Internal
+{
+class ModelLoaderImpl
+{
+public:
+ ModelLoaderImpl() = default;
+
+ /**
+ * @brief Set InputParameter.
+ * Thie method store only a pointer of InputParameter.
+ * The object of InputParameter should not be deleted until it is no longer used.
+ * @param[in] inputParameter Input parameters those can be used for model loading.
+ */
+ void SetInputParameter(Dali::Scene3D::Loader::ModelLoader::InputParameter& inputParameter)
+ {
+ mInputParameter = &inputParameter;
+ }
+
+ /**
+ * @brief Request to load model from url.
+ * @param[in] url model file url.
+ * @param[out] result loaded model data.
+ * @return True if model loading is successfully finished.
+ */
+ virtual bool LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result) = 0;
+
+protected:
+ Dali::Scene3D::Loader::ModelLoader::InputParameter* mInputParameter{nullptr};
+};
+} // namespace Internal
+} // namespace Loader
+} // namespace Scene3D
+} // namespace Dali
+
+#endif // DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
* @note If this is false, then the mask is scaled to fit the rendered result before being applied.
*/
CROP_TO_MASK,
-
- /**
- * @brief The radius for the rounded corners of the scene view.
- * @details Name "cornerRadius", type Prooperty::VECTOR4, The radius for the rounded corners of the scene view.
- * @note By default, it is Vector::ZERO.
- * @note Corner radius is only available when framebuffer is used.
- * @note Each radius will clamp internally to the half of smaller of the SceneView width and height.
- * @note Radius value are used in clockwise order from top-left-corner to bottom-left-corner.
- * When radius is Vector4(x, y, z, w)
- * x y
- * +--+
- * | |
- * +--+
- * w z
- */
- CORNER_RADIUS,
-
- /**
- * @brief Whether the corner radius value is relative (percentage [0.0f to 0.5f] of the SceneView size) or absolute (in world units).
- * @details Name "cornerRadiusPolicy", type Property::INTEGER.
- * @see Dali::Visual::Transform::Policy::Type
- * @note By default, it is ABSOLUTE to the SceneView's size.
- * If it it RELATIVE, the corner radius value is relative to the smaller of the SceneView width and height.
- */
- CORNER_RADIUS_POLICY,
-
- /**
- * @brief The width for the borderline of the scene view.
- * @details Name "borderlineWidth", type Property::FLOAT.
- * @note Optional. Default value is 0.0f.
- * @note Borderline is only available when framebuffer is used.
- */
- BORDERLINE_WIDTH,
-
- /**
- * @brief The color for the borderline of the scene view.
- * @details Name "borderlineColor", type Property::VECTOR4.
- * @note Default value is Color::BLACK.
- */
- BORDERLINE_COLOR,
-
- /**
- * @brief The offset from the scene view borderline (recommend [-1.0f to 1.0f]).
- * @details Name "borderlineOffset", type Property::FLOAT
- * @note Default value is 0.0f.
- * @note This value will clamp internally to [-1.0f to 1.0f].
- */
- BORDERLINE_OFFSET,
};
};
public:
+
/**
* @brief Typedef for capture finished signals sent by this class.
*
/*\r
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.\r
+ * Copyright (c) 2022 Samsung Electronics Co., Ltd.\r
*\r
* Licensed under the Apache License, Version 2.0 (the "License");\r
* you may not use this file except in compliance with the License.\r
BOX_THEN_NEAREST = Dali::SamplingMode::BOX_THEN_NEAREST,\r
BOX_THEN_LINEAR = Dali::SamplingMode::BOX_THEN_LINEAR,\r
NO_FILTER = Dali::SamplingMode::NO_FILTER,\r
- DONT_CARE = Dali::SamplingMode::DONT_CARE,\r
- LANCZOS = Dali::SamplingMode::LANCZOS,\r
- BOX_THEN_LANCZOS = Dali::SamplingMode::BOX_THEN_LANCZOS,\r
+ DONT_CARE = Dali::SamplingMode::DONT_CARE\r
};\r
\r
static Type FromString(const char* s, size_t len);\r
ENUM_STRING_MAPPING(ImageData::SamplingMode, BOX_THEN_LINEAR),\r
ENUM_STRING_MAPPING(ImageData::SamplingMode, NO_FILTER),\r
ENUM_STRING_MAPPING(ImageData::SamplingMode, DONT_CARE),\r
- ENUM_STRING_MAPPING(ImageData::SamplingMode, LANCZOS),\r
- ENUM_STRING_MAPPING(ImageData::SamplingMode, BOX_THEN_LANCZOS),\r
};\r
return SAMPLING_MODE_TYPES;\r
}\r
const js::Reader<ImageData>& GetImageMetaDataReader()\r
{\r
static const auto IMAGE_METADATA_READER = std::move(js::Reader<ImageData>()\r
- .Register(*js::MakeProperty("uri", js::Read::String, &ImageData::mImageUri))\r
- .Register(*js::MakeProperty("minWidth", js::Read::Number, &ImageData::mMinWidth))\r
- .Register(*js::MakeProperty("minHeight", js::Read::Number, &ImageData::mMinHeight))\r
- .Register(*js::MakeProperty("samplingMode", gt::ReadStringEnum<ImageData::SamplingMode>, &ImageData::mSamplingMode)));\r
+ .Register(*js::MakeProperty("uri", js::Read::String, &ImageData::mImageUri))\r
+ .Register(*js::MakeProperty("minWidth", js::Read::Number, &ImageData::mMinWidth))\r
+ .Register(*js::MakeProperty("minHeight", js::Read::Number, &ImageData::mMinHeight))\r
+ .Register(*js::MakeProperty("samplingMode", gt::ReadStringEnum<ImageData::SamplingMode>, &ImageData::mSamplingMode)));\r
return IMAGE_METADATA_READER;\r
}\r
\r
const js::Reader<MetaData>& GetMetaDataReader()\r
{\r
static const auto METADATA_READER = std::move(js::Reader<MetaData>()\r
- .Register(*js::MakeProperty("images", js::Read::Array<ImageData, js::ObjectReader<ImageData>::Read>, &MetaData::mImageData)));\r
+ .Register(*js::MakeProperty("images", js::Read::Array<ImageData, js::ObjectReader<ImageData>::Read>, &MetaData::mImageData)));\r
return METADATA_READER;\r
}\r
} // namespace\r
static constexpr std::string_view EMBEDDED_DATA_BASE64_ENCODING_TYPE = "base64,";
Dali::PixelData LoadImageResource(const std::string& resourcePath,
- TextureDefinition& textureDefinition)
+ TextureDefinition& textureDefinition,
+ FittingMode::Type fittingMode,
+ bool orientationCorrection)
{
Dali::PixelData pixelData;
if(!textureDefinition.mTextureBuffer.empty())
{
- DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss) { oss << "[s:" << textureDefinition.mTextureBuffer.size() << "]"; });
- Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(textureDefinition.mTextureBuffer.data(), textureDefinition.mTextureBuffer.size(), textureDefinition.mMinImageDimensions, FittingMode::DEFAULT, textureDefinition.mSamplingMode, true);
+ DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss)
+ { oss << "[s:" << textureDefinition.mTextureBuffer.size() << "]"; });
+ Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(textureDefinition.mTextureBuffer.data(), textureDefinition.mTextureBuffer.size(), textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
if(pixelBuffer)
{
pixelData = Devel::PixelBuffer::Convert(pixelBuffer);
}
- DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss) {
+ DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss)
+ {
oss << "[";
if(pixelData)
{
Dali::Toolkit::DecodeBase64FromString(data, buffer);
uint32_t bufferSize = buffer.size();
- DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss) { oss << "[embedded s:" << bufferSize << "]"; });
- Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(reinterpret_cast<uint8_t*>(buffer.data()), bufferSize, textureDefinition.mMinImageDimensions, FittingMode::DEFAULT, textureDefinition.mSamplingMode, true);
+ DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss)
+ { oss << "[embedded s:" << bufferSize << "]"; });
+ Dali::Devel::PixelBuffer pixelBuffer = Dali::LoadImageFromBuffer(reinterpret_cast<uint8_t*>(buffer.data()), bufferSize, textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
if(pixelBuffer)
{
pixelData = Dali::Devel::PixelBuffer::Convert(pixelBuffer, true);
}
- DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss) {
+ DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_MODEL_LOAD_IMAGE_FROM_BUFFER", [&](std::ostringstream& oss)
+ {
oss << "[";
if(pixelData)
{
else
{
textureDefinition.mDirectoryPath = resourcePath;
- pixelData = Internal::ImageResourceLoader::GetCachedPixelData(resourcePath + textureDefinition.mImageUri, textureDefinition.mMinImageDimensions, textureDefinition.mSamplingMode);
+ pixelData = Internal::ImageResourceLoader::GetCachedPixelData(resourcePath + textureDefinition.mImageUri, textureDefinition.mMinImageDimensions, fittingMode, textureDefinition.mSamplingMode, orientationCorrection);
}
return pixelData;
}
-
-uint32_t CombineMetallicRoughnessTextures(Dali::Devel::PixelBuffer& metallicTexture, Dali::Devel::PixelBuffer& roughnessTexture, Dali::Devel::PixelBuffer& metallicRoughnessTexture)
-{
- if(metallicTexture.GetWidth() != roughnessTexture.GetWidth() || metallicTexture.GetHeight() != roughnessTexture.GetHeight())
- {
- // Resize the metallic texture to match the size of the roughness texture
- metallicTexture.Resize(roughnessTexture.GetWidth(), roughnessTexture.GetHeight());
- }
-
- // Combine the two textures together
- uint32_t metallicRoughnessWidth = roughnessTexture.GetWidth();
- uint32_t metallicRoughnessHeight = roughnessTexture.GetHeight();
- Pixel::Format pixelFormatMetallicRoughness = Pixel::RGBA8888;
- const unsigned int bytesPerPixelMetallicRoughness = Pixel::GetBytesPerPixel(pixelFormatMetallicRoughness);
- uint32_t combinedBufferSize = metallicRoughnessWidth * metallicRoughnessHeight * bytesPerPixelMetallicRoughness;
-
- metallicRoughnessTexture = Dali::Devel::PixelBuffer::New(metallicRoughnessWidth,
- metallicRoughnessHeight,
- pixelFormatMetallicRoughness);
-
- const uint8_t* metallicBufferPtr = metallicTexture.GetBuffer();
- const uint8_t* roughnessBufferPtr = roughnessTexture.GetBuffer();
- uint8_t* metallicRoughnessBufferPtr = metallicRoughnessTexture.GetBuffer();
-
- const uint32_t bytesPerPixelMetallic = Pixel::GetBytesPerPixel(metallicTexture.GetPixelFormat());
- const uint32_t bytesPerPixelRoughness = Pixel::GetBytesPerPixel(roughnessTexture.GetPixelFormat());
-
- for(uint32_t y = 0; y < metallicRoughnessHeight; ++y)
- {
- for(uint32_t x = 0; x < metallicRoughnessWidth; ++x)
- {
- // Go through each pixel from the top to the bottom row by row
- uint32_t pixelIndex = y * metallicRoughnessWidth + x;
-
- uint32_t metallicBufferIndex = pixelIndex * bytesPerPixelMetallic;
- uint32_t roughnessBufferIndex = pixelIndex * bytesPerPixelRoughness;
- uint32_t metallicRoughnessBufferIndex = pixelIndex * bytesPerPixelMetallicRoughness;
-
- uint8_t metallicValue = metallicBufferPtr[metallicBufferIndex];
- uint8_t roughnessValue = roughnessBufferPtr[roughnessBufferIndex];
-
- // Fill the combined texture buffer
- metallicRoughnessBufferPtr[metallicRoughnessBufferIndex + 0] = 0u; // R channel
- metallicRoughnessBufferPtr[metallicRoughnessBufferIndex + 1] = roughnessValue; // G channel
- metallicRoughnessBufferPtr[metallicRoughnessBufferIndex + 2] = metallicValue; // B channel
- metallicRoughnessBufferPtr[metallicRoughnessBufferIndex + 3] = 0u; // A channel
- }
- }
-
- return combinedBufferSize;
-}
-
} // namespace
SamplerFlags::Type SamplerFlags::Encode(FilterMode::Type minFilter, FilterMode::Type magFilter, WrapMode::Type wrapS, WrapMode::Type wrapT)
// Load textures
auto iTexture = mTextureStages.begin();
- auto checkStage = [&](uint32_t flags) {
+ auto checkStage = [&](uint32_t flags)
+ {
return iTexture != mTextureStages.end() && MaskMatch(iTexture->mSemantic, flags);
};
// Check for compulsory textures: Albedo, Metallic, Roughness, Normal
if(checkStage(ALBEDO | METALLIC))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
if(checkStage(NORMAL | ROUGHNESS))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else // single value normal-roughness
{
if(checkStage(ALBEDO))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else if(mNeedAlbedoTexture) // single value albedo, albedo-alpha or albedo-metallic
const bool createMetallicRoughnessAndNormal = hasTransparency || std::distance(mTextureStages.begin(), iTexture) > 0;
if(checkStage(METALLIC | ROUGHNESS))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
- else if(checkStage(METALLIC) || checkStage(ROUGHNESS))
- {
- // In some cases (e.g. USD model) it could have metallic texture and roughness texture separately,
- // but what we want is a combined texture for both metallic and roughness.
-
- Dali::Devel::PixelBuffer metallicTexture;
- Dali::Devel::PixelBuffer roughnessTexture;
- SamplerFlags::Type mMetallicSamplerFlags = SamplerFlags::DEFAULT;
- SamplerFlags::Type mRoughnessSamplerFlags = SamplerFlags::DEFAULT;
-
- if(checkStage(METALLIC))
- {
- if(!iTexture->mTexture.mTextureBuffer.empty())
- {
- metallicTexture = Dali::LoadImageFromBuffer(iTexture->mTexture.mTextureBuffer.data(), iTexture->mTexture.mTextureBuffer.size(), iTexture->mTexture.mMinImageDimensions, FittingMode::DEFAULT, iTexture->mTexture.mSamplingMode, true);
- mMetallicSamplerFlags = iTexture->mTexture.mSamplingMode;
- }
-
- iTexture = mTextureStages.erase(iTexture);
- }
-
- if(checkStage(ROUGHNESS))
- {
- if(!iTexture->mTexture.mTextureBuffer.empty())
- {
- roughnessTexture = Dali::LoadImageFromBuffer(iTexture->mTexture.mTextureBuffer.data(), iTexture->mTexture.mTextureBuffer.size(), iTexture->mTexture.mMinImageDimensions, FittingMode::DEFAULT, iTexture->mTexture.mSamplingMode, true);
- mRoughnessSamplerFlags = iTexture->mTexture.mSamplingMode;
- }
-
- iTexture = mTextureStages.erase(iTexture);
- }
-
- if(metallicTexture && roughnessTexture)
- {
- // If we have both metallic texture and roughness texture, combine them together as one metallic-roughness texture
- // with roughness value in G channel and metallic value in B channel (to match what we support in our PBR shader).
-
- Dali::Devel::PixelBuffer metallicRoughnessTexture;
- uint32_t combinedBufferSize = CombineMetallicRoughnessTextures(metallicTexture, roughnessTexture, metallicRoughnessTexture);
-
- uint8_t* metallicRoughnessBufferPtr = metallicRoughnessTexture.GetBuffer();
- iTexture = mTextureStages.insert(iTexture, {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS, TextureDefinition{std::vector<uint8_t>(metallicRoughnessBufferPtr, metallicRoughnessBufferPtr + combinedBufferSize)}});
- ++iTexture;
-
- raw.mTextures.push_back({Devel::PixelBuffer::Convert(metallicRoughnessTexture), mRoughnessSamplerFlags});
- }
- else
- {
- if(metallicTexture)
- {
- const uint8_t* metallicBufferPtr = metallicTexture.GetBuffer();
- iTexture = mTextureStages.insert(iTexture, {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS, TextureDefinition{std::vector<uint8_t>(metallicBufferPtr, metallicBufferPtr + metallicTexture.GetWidth() * metallicTexture.GetHeight() * Pixel::GetBytesPerPixel(metallicTexture.GetPixelFormat()))}});
- ++iTexture;
-
- raw.mTextures.push_back({Devel::PixelBuffer::Convert(metallicTexture), mMetallicSamplerFlags});
- }
- else if(roughnessTexture)
- {
- const uint8_t* roughnessBufferPtr = roughnessTexture.GetBuffer();
- iTexture = mTextureStages.insert(iTexture, {MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS, TextureDefinition{std::vector<uint8_t>(roughnessBufferPtr, roughnessBufferPtr + roughnessTexture.GetWidth() * roughnessTexture.GetHeight() * Pixel::GetBytesPerPixel(roughnessTexture.GetPixelFormat()))}});
- ++iTexture;
-
- raw.mTextures.push_back({Devel::PixelBuffer::Convert(roughnessTexture), mRoughnessSamplerFlags});
- }
- }
- }
else if(createMetallicRoughnessAndNormal && mNeedMetallicRoughnessTexture)
{
// NOTE: we want to set both metallic and roughness to 1.0; dli uses the R & A channels,
if(checkStage(NORMAL))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
else if(mNeedNormalTexture)
// Extra textures.
if(checkStage(SUBSURFACE))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
if(checkStage(OCCLUSION))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
if(checkStage(EMISSIVE))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
if(checkStage(SPECULAR))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
if(checkStage(SPECULAR_COLOR))
{
- raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture), iTexture->mTexture.mSamplerFlags});
+ raw.mTextures.push_back({LoadImageResource(imagesPath, iTexture->mTexture, FittingMode::DEFAULT, true), iTexture->mTexture.mSamplerFlags});
++iTexture;
}
bool MaterialDefinition::CheckTextures(uint32_t flags) const
{
- return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts) { return MaskMatch(ts.mSemantic, flags); }) != mTextureStages.end();
+ return std::find_if(mTextureStages.begin(), mTextureStages.end(), [flags](const TextureStage& ts)
+ { return MaskMatch(ts.mSemantic, flags); }) != mTextureStages.end();
}
} // namespace Loader
#ifndef DALI_SCENE3D_LOADER_MATERIAL_DEFINITION_H
#define DALI_SCENE3D_LOADER_MATERIAL_DEFINITION_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
METALLIC = NthBit(1),
ROUGHNESS = NthBit(2),
NORMAL = NthBit(3),
- OCCLUSION = NthBit(4),
- EMISSIVE = NthBit(5),
+ EMISSIVE = NthBit(4),
+ OCCLUSION = NthBit(5),
SPECULAR = NthBit(6),
SPECULAR_COLOR = NthBit(7),
SUBSURFACE = NthBit(8), // Note: dli-only
float mSpecularFactor = 1.0f;
Vector3 mSpecularColorFactor = Vector3::ONE;
- // For the glTF or USD models, each of albedo, metallic, roughness, normal textures are not essential.
+ // For the glTF, each of albedo, metallicRoughness, normal textures are not essential.
bool mNeedAlbedoTexture = true;
bool mNeedMetallicRoughnessTexture = true;
- bool mNeedMetallicTexture = false;
- bool mNeedRoughnessTexture = false;
bool mNeedNormalTexture = true;
bool mDoubleSided = false;
+++ /dev/null
-#ifndef DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
-#define DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// INTERNAL INCLUDES
-#include <dali-scene3d/public-api/api.h>
-#include <dali-scene3d/public-api/loader/load-result.h>
-#include <dali-scene3d/public-api/loader/model-loader.h>
-#include <dali-scene3d/public-api/loader/resource-bundle.h>
-
-// EXTERNAL INCLUDES
-#include <string>
-
-namespace Dali
-{
-namespace Scene3D
-{
-namespace Loader
-{
-class ModelLoaderImpl
-{
-public:
- ModelLoaderImpl() = default;
-
- virtual ~ModelLoaderImpl() = default;
-
- /**
- * @brief Set InputParameter.
- * Thie method store only a pointer of InputParameter.
- * The object of InputParameter should not be deleted until it is no longer used.
- * @param[in] inputParameter Input parameters those can be used for model loading.
- */
- void SetInputParameter(Dali::Scene3D::Loader::ModelLoader::InputParameter& inputParameter)
- {
- mInputParameter = &inputParameter;
- }
-
- /**
- * @brief Request to load model from url.
- * @param[in] url model file url.
- * @param[out] result loaded model data.
- * @return True if model loading is successfully finished.
- */
- virtual bool LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result) = 0;
-
-protected:
- Dali::Scene3D::Loader::ModelLoader::InputParameter* mInputParameter{nullptr};
-};
-} // namespace Loader
-} // namespace Scene3D
-} // namespace Dali
-
-#endif // DALI_SCENE3D_LOADER_MODEL_LOADER_IMPL_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*/
// FILE HEADER
-#include <dali-scene3d/public-api/loader/model-loader-impl.h>
#include <dali-scene3d/public-api/loader/model-loader.h>
// EXTERNAL INCLUDES
#include <dali/integration-api/debug.h>
-#include <dlfcn.h>
#include <filesystem>
#include <memory>
#include <dali-scene3d/internal/loader/dli-loader-impl.h>
#include <dali-scene3d/internal/loader/glb-loader-impl.h>
#include <dali-scene3d/internal/loader/gltf2-loader-impl.h>
+#include <dali-scene3d/internal/loader/model-loader-impl.h>
namespace Dali::Scene3D::Loader
{
namespace
{
-constexpr std::string_view OBJ_EXTENSION = ".obj";
-constexpr std::string_view GLTF_EXTENSION = ".gltf";
-constexpr std::string_view GLB_EXTENSION = ".glb";
-constexpr std::string_view DLI_EXTENSION = ".dli";
-constexpr std::string_view USD_EXTENSION = ".usd";
-constexpr std::string_view USDZ_EXTENSION = ".usdz";
-constexpr std::string_view USDA_EXTENSION = ".usda";
-constexpr std::string_view USDC_EXTENSION = ".usdc";
-constexpr std::string_view METADATA_EXTENSION = "metadata";
-
-const char* USD_LOADER_SO("libdali2-usd-loader.so");
-const char* CREATE_USD_LOADER_SYMBOL("CreateUsdLoader");
-
-// Custom deleter for dlopen handles
-void DlcloseDeleter(void* handle)
-{
- if(handle)
- {
- dlclose(handle);
- }
-}
-
-// Static shared pointer to store a pointer to the dlopen handle
-std::shared_ptr<void*> gUsdLoaderHandle(nullptr, DlcloseDeleter);
-
-using CreateUsdLoaderFunc = ModelLoaderImpl* (*)();
-CreateUsdLoaderFunc gCreateUsdLoaderFunc(nullptr);
-
-// Poxy function for `dlopen` to allow easy overriding in test environments.
-extern "C" void* DlopenProxy(const char* filename, int flag)
-{
- // Calls the real dlopen
- return dlopen(filename, flag);
-}
-
-// Poxy function for `dlsym` to allow easy overriding in test environments.
-extern "C" void* DlsymProxy(void* handle, const char* name)
-{
- // Calls the real dlsym
- return dlsym(handle, name);
-}
-
+static constexpr std::string_view OBJ_EXTENSION = ".obj";
+static constexpr std::string_view GLTF_EXTENSION = ".gltf";
+static constexpr std::string_view GLB_EXTENSION = ".glb";
+static constexpr std::string_view DLI_EXTENSION = ".dli";
+static constexpr std::string_view METADATA_EXTENSION = "metadata";
} // namespace
ModelLoader::ModelLoader(const std::string& modelUrl, const std::string& resourceDirectoryUrl, Dali::Scene3D::Loader::LoadResult& loadResult)
CreateModelLoader();
}
-ModelLoader::~ModelLoader()
-{
-}
-
bool ModelLoader::LoadModel(Dali::Scene3D::Loader::ResourceBundle::PathProvider& pathProvider, bool loadOnlyRawResource)
{
if(!mImpl)
if(extension == DLI_EXTENSION)
{
- mImpl = std::make_unique<Dali::Scene3D::Loader::Internal::DliLoaderImpl>();
+ mImpl = std::make_shared<Dali::Scene3D::Loader::Internal::DliLoaderImpl>();
}
else if(extension == GLTF_EXTENSION)
{
- mImpl = std::make_unique<Dali::Scene3D::Loader::Internal::Gltf2LoaderImpl>();
+ mImpl = std::make_shared<Dali::Scene3D::Loader::Internal::Gltf2LoaderImpl>();
}
else if(extension == GLB_EXTENSION)
{
- mImpl = std::make_unique<Dali::Scene3D::Loader::Internal::GlbLoaderImpl>();
- }
- else if(extension == USD_EXTENSION || extension == USDZ_EXTENSION || extension == USDA_EXTENSION || extension == USDC_EXTENSION)
- {
- // Attempt to load the USD loader library dynamically
- // Once loaded we will keep it open so that any subsequent loading of USD models
- // doesn't require loading the same library repeatedly.
- if(!gUsdLoaderHandle || !(*gUsdLoaderHandle))
- {
- void* handle = DlopenProxy(USD_LOADER_SO, RTLD_LAZY);
-
- if(!handle)
- {
- // The shared library failed to load
- DALI_LOG_ERROR("ModelLoader::CreateModelLoader, dlopen error: %s\n", dlerror());
- return;
- }
-
- // Store the handle in the shared_ptr (passing the handle and the custom deleter)
- gUsdLoaderHandle = std::shared_ptr<void*>(new void*(handle), [](void* ptr) {
- if(ptr)
- {
- DlcloseDeleter(*(static_cast<void**>(ptr))); // Call custom deleter
- delete static_cast<void**>(ptr); // Clean up dynamically allocated memory
- }
- });
-
- // Dynamically link to the CreateUsdLoader function in the shared library at runtime.
- // Cache the function pointer only if it hasn't been loaded yet
- if(!gCreateUsdLoaderFunc)
- {
- gCreateUsdLoaderFunc = reinterpret_cast<CreateUsdLoaderFunc>(DlsymProxy(*gUsdLoaderHandle.get(), CREATE_USD_LOADER_SYMBOL));
- if(!gCreateUsdLoaderFunc)
- {
- // If the symbol couldn't be found, reset the shared_ptr to invoke the custom deleter
- gUsdLoaderHandle.reset(); // This will automatically call dlclose via the custom deleter
-
- DALI_LOG_ERROR("Cannot find CreateUsdLoader function: %s\n", dlerror());
-
- return;
- }
- }
- }
-
- // Create an instance of USD loader
- mImpl = ModelLoaderImplUniquePtr(gCreateUsdLoaderFunc());
+ mImpl = std::make_shared<Dali::Scene3D::Loader::Internal::GlbLoaderImpl>();
}
else
{
GetResources().LoadResources(pathProvider);
}
}
+
} // namespace Dali::Scene3D::Loader
#ifndef DALI_SCENE3D_LOADER_MODEL_LOADER_H
#define DALI_SCENE3D_LOADER_MODEL_LOADER_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2023 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
namespace Dali::Scene3D::Loader
{
+namespace Internal
+{
class ModelLoaderImpl;
+}
class DALI_SCENE3D_API ModelLoader
{
*/
ModelLoader(const std::string& modelUrl, const std::string& resourceDirectoryUrl, Dali::Scene3D::Loader::LoadResult& loadResult);
- /**
- * @brief ModelLoader Destructor
- * @SINCE_2_3.43
- */
- ~ModelLoader();
-
/**
* @brief Request to load model from model url.
* @SINCE_2_2.17
Dali::Scene3D::Loader::LoadResult mLoadResult;
Dali::Scene3D::Loader::Customization::Choices mResourceChoices;
- using ModelLoaderImplUniquePtr = std::unique_ptr<Dali::Scene3D::Loader::ModelLoaderImpl>;
- ModelLoaderImplUniquePtr mImpl;
+ std::shared_ptr<Internal::ModelLoaderImpl> mImpl;
};
} // namespace Dali::Scene3D::Loader
option.AddOption(ShaderOption::Type::BASE_COLOR_TEXTURE);
}
- if(MaskMatch(materialDef.mFlags, MaterialDefinition::METALLIC) || MaskMatch(materialDef.mFlags, MaterialDefinition::ROUGHNESS))
+ if(materialDef.CheckTextures(MaterialDefinition::METALLIC | MaterialDefinition::ROUGHNESS))
{
option.AddOption(ShaderOption::Type::METALLIC_ROUGHNESS_TEXTURE);
}
TO_SAME_ROLE_TYPE(SPIN_BUTTON)
TO_V1_ROLE_TYPE(TAB, PAGE_TAB)
TO_V1_ROLE_TYPE(TAB_LIST, PAGE_TAB_LIST)
- TO_V1_ROLE_TYPE(TEXT, LABEL)
+ TO_SAME_ROLE_TYPE(TEXT)
TO_SAME_ROLE_TYPE(TOGGLE_BUTTON)
TO_SAME_ROLE_TYPE(TOOL_BAR)
default:
return IsRoleV2(rawRole) && static_cast<AccessibilityRole>(rawRole) != AccessibilityRole::NONE;
}
-using Dali::Toolkit::Internal::TriStateProperty;
-bool IsHighlightable(TriStateProperty highlightable, int32_t rawRole)
-{
- switch(highlightable)
- {
- case TriStateProperty::AUTO:
- {
- return IsHighlightableRole(rawRole);
- }
- case TriStateProperty::TRUE:
- {
- return true;
- }
- default:
- {
- return false;
- }
- }
-}
-
} // unnamed namespace
ControlAccessible::ControlAccessible(Dali::Actor self)
// Apply traits
states[State::MODAL] = props.isModal || IsModalRole(props.role);
- states[State::HIGHLIGHTABLE] = IsHighlightable(props.isHighlightable, props.role);
+ states[State::HIGHLIGHTABLE] = props.isHighlightable || IsHighlightableRole(props.role);
}
Dali::Accessibility::States ControlAccessible::CalculateStates()
WebView WebView::New(uint32_t argc, char** argv)
{
- return Internal::WebView::New(argc, argv, -1);
-}
-
-WebView WebView::New(uint32_t argc, char** argv, int32_t type)
-{
- return Internal::WebView::New(argc, argv, type);
+ return Internal::WebView::New(argc, argv);
}
Toolkit::WebView WebView::FindWebView(Dali::WebEnginePlugin* plugin)
Dali::Toolkit::GetImpl(*this).GetPlainTextAsynchronously(callback);
}
-void WebView::WebAuthenticationCancel()
-{
- Dali::Toolkit::GetImpl(*this).WebAuthenticationCancel();
-}
-
-void WebView::RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback)
-{
- Dali::Toolkit::GetImpl(*this).RegisterWebAuthDisplayQRCallback(callback);
-}
-
-void WebView::RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback)
-{
- Dali::Toolkit::GetImpl(*this).RegisterWebAuthResponseCallback(callback);
-}
-
-void WebView::RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback)
-{
- Dali::Toolkit::GetImpl(*this).RegisterUserMediaPermissionRequestCallback(callback);
-}
-
-
WebView::WebView(Internal::WebView& implementation)
: Control(implementation)
{
*/
static WebView New(uint32_t argc, char** argv);
- /**
- * @brief Create an initialized WebView with web engine type.
- *
- * @param [in] argc The count of arguments of Applications
- * @param [in] argv The string array of arguments of Applications
- * @param [in] type The web engine type (0: Chromium, 1: LWE, otherwise: depend on system environment)
- */
- static WebView New(uint32_t argc, char** argv, int32_t type);
-
/**
* @brief Find web view by web engine plugin.
*/
*/
void GetPlainTextAsynchronously(Dali::WebEnginePlugin::PlainTextReceivedCallback callback);
- /**
- * @brief Cancel WebAuthentication(cancel in progress passkey operation).
- */
- void WebAuthenticationCancel();
-
- /**
- * @brief Register WebAuthDisplayQR callback.
- *
- * @param[in] callback The callback informs browser app to display QR code popup for passkey scenario.
- */
- void RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback);
-
- /**
- * @brief Register WebAuthResponse callback.
- *
- * @param[in] callback The callback informs browser app that the passkey registration and authentication has been successful and app can close QR popup.
- */
- void RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback);
-
- /**
- * @brief Register UserMediaPermissionRequest callback.
- *
- * @param[in] callback The callback to be called for handling user media permission.
- */
- void RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback);
-
public: // Not intended for application developers
/// @cond internal
/**
#include <dali-toolkit/devel-api/visual-factory/precompile-shader-option.h>
// EXTERNAL INCLUDES
-#include <dali/devel-api/scripting/enum-helper.h>
#include <dali/integration-api/debug.h>
namespace
{
-// TYPE
-const char* TOKEN_TYPE("shaderType");
-const char* TOKEN_TYPE_IMAGE("image");
-const char* TOKEN_TYPE_TEXT("text");
-const char* TOKEN_TYPE_COLOR("color");
-const char* TOKEN_TYPE_MODEL_3D("3d");
-const char* TOKEN_TYPE_NPATCH("npatch");
-const char* TOKEN_TYPE_CUSTOM("custom");
-
-// OPTION
-const char* TOKEN_OPTION("shaderOption");
-const char* TOKEN_OPTION_ROUNDED_CORNER("ROUNDED_CORNER");
-const char* TOKEN_OPTION_BORDERLINE("BORDERLINE");
-const char* TOKEN_OPTION_BLUR_EDGE("BLUR_EDGE");
-const char* TOKEN_OPTION_CUTOUT("CUTOUT");
-const char* TOKEN_OPTION_ATLAS_DEFAULT("ATLAS_DEFAULT");
-const char* TOKEN_OPTION_ATLAS_CUSTOM("ATLAS_CUSTOM");
-const char* TOKEN_OPTION_MASKING("MASKING");
-const char* TOKEN_OPTION_YUV_TO_RGB("YUV_TO_RGB");
-const char* TOKEN_OPTION_YUV_AND_RGB("YUV_AND_RGB");
-const char* TOKEN_OPTION_MULTI_COLOR("MULTI_COLOR");
-const char* TOKEN_OPTION_STYLES("STYLES");
-const char* TOKEN_OPTION_OVERLAY("OVERLAY");
-const char* TOKEN_OPTION_EMOJI("EMOJI");
-const char* TOKEN_OPTION_STRETCH_X("xStretchCount");
-const char* TOKEN_OPTION_STRETCH_Y("yStretchCount");
-
-// CUSTOM
-const char* TOKEN_CUSTOM_VERTEX("vertexShader");
-const char* TOKEN_CUSTOM_FRAMENT("fragmentShader");
-const char* TOKEN_CUSTOM_NAME("shaderName");
-
-// String to enum table
-// clang-format off
-DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADER_TYPE)
- {TOKEN_TYPE_IMAGE, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::IMAGE)},
- {TOKEN_TYPE_TEXT, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::TEXT)},
- {TOKEN_TYPE_COLOR, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::COLOR)},
- {TOKEN_TYPE_MODEL_3D, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::MODEL_3D)},
- {TOKEN_TYPE_NPATCH, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::NPATCH)},
- {TOKEN_TYPE_CUSTOM, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::ShaderType::CUSTOM)},
-DALI_ENUM_TO_STRING_TABLE_END(SHADER_TYPE);
-
-DALI_ENUM_TO_STRING_TABLE_BEGIN(SHADER_OPTION_FLAG)
- {TOKEN_OPTION_ROUNDED_CORNER, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::ROUNDED_CORNER)},
- {TOKEN_OPTION_BORDERLINE, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::BORDERLINE)},
- {TOKEN_OPTION_BLUR_EDGE, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::BLUR_EDGE)},
- {TOKEN_OPTION_CUTOUT, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::CUTOUT)},
- {TOKEN_OPTION_ATLAS_DEFAULT, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::ATLAS_DEFAULT)},
- {TOKEN_OPTION_ATLAS_CUSTOM, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::ATLAS_CUSTOM)},
- {TOKEN_OPTION_MASKING, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::MASKING)},
- {TOKEN_OPTION_YUV_TO_RGB, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::YUV_TO_RGB)},
- {TOKEN_OPTION_YUV_AND_RGB, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::YUV_AND_RGB)},
- {TOKEN_OPTION_MULTI_COLOR, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::MULTI_COLOR)},
- {TOKEN_OPTION_STYLES, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::STYLES)},
- {TOKEN_OPTION_OVERLAY, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::OVERLAY)},
- {TOKEN_OPTION_EMOJI, static_cast<int32_t>(Dali::Toolkit::PrecompileShaderOption::Flag::EMOJI)},
-DALI_ENUM_TO_STRING_TABLE_END(SHADER_OPTION_FLAG);
-// clang-format on
-} // namespace
+ // TYPE
+ const char* TOKEN_TYPE("shaderType");
+ const char* TOKEN_TYPE_IMAGE("image");
+ const char* TOKEN_TYPE_TEXT("text");
+ const char* TOKEN_TYPE_COLOR("color");
+ const char* TOKEN_TYPE_MODEL_3D("3d");
+ const char* TOKEN_TYPE_NPATCH("npatch");
+ const char* TOKEN_TYPE_CUSTOM("custom");
+
+ // OPTION
+ const char* TOKEN_OPTION("shaderOption");
+ const char* TOKEN_OPTION_ROUNDED_CORNER("ROUNDED_CORNER");
+ const char* TOKEN_OPTION_BORDERLINE("BORDERLINE");
+ const char* TOKEN_OPTION_BLUR_EDGE("BLUR_EDGE");
+ const char* TOKEN_OPTION_CUTOUT("CUTOUT");
+ const char* TOKEN_OPTION_ATLAS_DEFAULT("ATLAS_DEFAULT");
+ const char* TOKEN_OPTION_ATLAS_CUSTOM("ATLAS_CUSTOM");
+ const char* TOKEN_OPTION_MASKING("MASKING");
+ const char* TOKEN_OPTION_YUV_TO_RGB("YUV_TO_RGB");
+ const char* TOKEN_OPTION_YUV_AND_RGB("YUV_AND_RGB");
+ const char* TOKEN_OPTION_MULTI_COLOR("MULTI_COLOR");
+ const char* TOKEN_OPTION_STYLES("STYLES");
+ const char* TOKEN_OPTION_OVERLAY("OVERLAY");
+ const char* TOKEN_OPTION_EMOJI("EMOJI");
+ const char* TOKEN_OPTION_STRETCH_X("xStretchCount");
+ const char* TOKEN_OPTION_STRETCH_Y("yStretchCount");
+
+
+ // CUSTOM
+ const char* TOKEN_CUSTOM_VERTEX("vertexShader");
+ const char* TOKEN_CUSTOM_FRAMENT("fragmentShader");
+ const char* TOKEN_CUSTOM_NAME("shaderName");
+}
namespace Dali
{
+
namespace Toolkit
{
+
PrecompileShaderOption::PrecompileShaderOption(const Property::Map& shaderOption)
: mShaderType(ShaderType::UNKNOWN),
mShaderOptions(),
const KeyValuePair pair(shaderOption.GetKeyValue(shaderIdx));
if(pair.first.type == Property::Key::INDEX)
{
- continue; // We don't consider index keys.
+ continue; // We don't consider index keys.
}
const std::string& key(pair.first.stringKey);
if(key == TOKEN_TYPE)
{
- if(!GetEnumerationProperty(value, SHADER_TYPE_TABLE, SHADER_TYPE_TABLE_COUNT, mShaderType) || mShaderType == ShaderType::UNKNOWN)
+ if(value.GetType() == Property::STRING)
{
- DALI_LOG_ERROR("Can't find proper type[%s]\n", value.Get<std::string>().c_str());
- continue;
+ auto shaderType = value.Get<std::string>();
+ if(shaderType == TOKEN_TYPE_IMAGE)
+ {
+ mShaderType = ShaderType::IMAGE;
+ }
+ else if(shaderType == TOKEN_TYPE_TEXT)
+ {
+ mShaderType = ShaderType::TEXT;
+ }
+ else if(shaderType == TOKEN_TYPE_COLOR)
+ {
+ mShaderType = ShaderType::COLOR;
+ }
+ else if(shaderType == TOKEN_TYPE_MODEL_3D)
+ {
+ mShaderType = ShaderType::MODEL_3D;
+ }
+ else if(shaderType == TOKEN_TYPE_NPATCH)
+ {
+ mShaderType = ShaderType::NPATCH;
+ }
+ else if(shaderType == TOKEN_TYPE_CUSTOM)
+ {
+ mShaderType = ShaderType::CUSTOM;
+ }
+ else
+ {
+ mShaderType = ShaderType::UNKNOWN;
+ }
+ }
+
+ if(mShaderType == ShaderType::UNKNOWN)
+ {
+ DALI_LOG_ERROR("Can't find proper type.");
+ break;
}
}
else if(key == TOKEN_OPTION)
continue; // We don't consider index keys.
}
- Flag flag = Flag::UNKNOWN;
- const std::string& optionKey(optionPair.first.stringKey);
- if(GetEnumeration(optionKey.c_str(), SHADER_OPTION_FLAG_TABLE, SHADER_OPTION_FLAG_TABLE_COUNT, flag) && flag != Flag::UNKNOWN)
+ const std::string& optionKey(optionPair.first.stringKey);
+
+ if(optionKey == TOKEN_OPTION_ROUNDED_CORNER)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::ROUNDED_CORNER);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_BORDERLINE)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::BORDERLINE);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_CUTOUT)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::CUTOUT);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_ATLAS_DEFAULT)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::ATLAS_DEFAULT);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_ATLAS_CUSTOM)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::ATLAS_CUSTOM);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_BLUR_EDGE)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::BLUR_EDGE);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_MASKING)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::MASKING);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_YUV_TO_RGB)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::YUV_TO_RGB);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_YUV_AND_RGB)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::YUV_AND_RGB);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_MULTI_COLOR)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::MULTI_COLOR);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_STYLES)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::STYLES);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_OVERLAY)
+ {
+ if(optionPair.second.Get<bool>())
+ {
+ mShaderOptions.push_back(Flag::OVERLAY);
+ }
+ }
+ else if(optionKey == TOKEN_OPTION_EMOJI)
{
if(optionPair.second.Get<bool>())
{
- mShaderOptions.push_back(flag);
+ mShaderOptions.push_back(Flag::EMOJI);
}
}
else
{
- DALI_LOG_WARNING("Can't find this flag[%s]\n", optionKey.c_str());
- continue;
+ DALI_LOG_WARNING("Can't find this flag[%s] \n",optionKey.c_str());
}
}
}
return mNpatchXStretchCount;
}
-uint32_t PrecompileShaderOption::GetNpatchYStretchCount() const
+uint32_t PrecompileShaderOption::GetNpatchYStretchCount() const
{
return mNpatchYStretchCount;
}
*/
// EXTERNAL INCLUDES
-#include <dali/public-api/common/vector-wrapper.h>
#include <dali/public-api/images/image-operations.h>
#include <dali/public-api/object/property-map.h>
+#include <dali/public-api/common/vector-wrapper.h>
#include <memory>
#include <string>
#include <string_view>
{
namespace Toolkit
{
+
/**
* @brief PrecompiledShaderOption is a class for precompiled shader option.
*
enum class Flag
{
- UNKNOWN = 0,
- ROUNDED_CORNER,
+ ROUNDED_CORNER = 0,
BORDERLINE,
BLUR_EDGE,
CUTOUT,
PrecompileShaderOption(const PrecompileShaderOption& rhs);
PrecompileShaderOption& operator=(const PrecompileShaderOption& rhs);
- using ShaderOptions = std::vector<Flag>;
+ using ShaderOptions= std::vector<Flag>;
public:
/**
*/
uint32_t GetNpatchXStretchCount() const;
- /**
+ /**
* @brief Get the YStretchCount for npatch
*
* @return The NpatchYStretchCount
uint32_t GetNpatchYStretchCount() const;
private:
- ShaderType mShaderType;
- ShaderOptions mShaderOptions;
- std::string mShaderName;
- std::string mVertexShader;
- std::string mFragmentShader;
- uint32_t mNpatchXStretchCount;
- uint32_t mNpatchYStretchCount;
+ ShaderType mShaderType;
+ std::vector<Flag> mShaderOptions;
+ std::string mShaderName;
+ std::string mVertexShader;
+ std::string mFragmentShader;
+ uint32_t mNpatchXStretchCount;
+ uint32_t mNpatchYStretchCount;
};
} // namespace Toolkit
bool highlightable;
if(value.Get(highlightable))
{
- controlImpl.mImpl->mAccessibilityProps.isHighlightable = highlightable ? TriStateProperty::TRUE : TriStateProperty::FALSE;
+ controlImpl.mImpl->mAccessibilityProps.isHighlightable = highlightable;
}
break;
}
case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE:
{
- value = controlImpl.mImpl->mAccessibilityProps.isHighlightable == TriStateProperty::TRUE ? true : false;
+ value = controlImpl.mImpl->mAccessibilityProps.isHighlightable;
break;
}
typedef Dali::OwnerContainer<RegisteredVisual*> RegisteredVisualContainer;
-enum class TriStateProperty
-{
- AUTO = 0,
- TRUE,
- FALSE
-};
-
/**
* @brief Holds the Implementation for the internal control class
*/
std::string description{};
std::string value{};
std::string automationId{};
- int32_t role{static_cast<int32_t>(DevelControl::AccessibilityRole::NONE)};
+ int32_t role{static_cast<int32_t>(Dali::Accessibility::Role::UNKNOWN)};
DevelControl::AccessibilityStates states{};
std::map<Dali::Accessibility::RelationType, std::set<Accessibility::Accessible*>> relations;
Property::Map extraAttributes{};
- TriStateProperty isHighlightable{TriStateProperty::AUTO};
+ bool isHighlightable{false};
bool isHidden{false};
bool isScrollable{false};
bool isModal{false};
#include <dali/devel-api/actors/actor-devel.h>
#include <dali/devel-api/adaptor-framework/image-loading.h>
#include <dali/integration-api/debug.h>
-#include <dali/public-api/images/image-operations.h>
#include <dali/public-api/render-tasks/render-task-list.h>
#include <dali/public-api/rendering/renderer.h>
#include <dali/public-api/rendering/shader.h>
-#include <dali/public-api/actors/custom-actor-impl.h>
-// INTERNAL INCLUDES
+//INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/control-depth-index-ranges.h>
#include <dali-toolkit/devel-api/visuals/visual-properties-devel.h>
#include <dali-toolkit/internal/controls/control/control-renderers.h>
#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
-#include <dali-toolkit/public-api/controls/control-impl.h>
namespace
{
// Default values
static constexpr float BLUR_EFFECT_DOWNSCALE_FACTOR = 0.4f;
static constexpr uint32_t BLUR_EFFECT_PIXEL_RADIUS = 10u;
+static constexpr int32_t BLUR_EFFECT_ORDER_INDEX = 101;
static constexpr float MINIMUM_DOWNSCALE_FACTOR = 0.1f;
static constexpr float MAXIMUM_DOWNSCALE_FACTOR = 1.0f;
-static constexpr uint32_t MINIMUM_GPU_ARRAY_SIZE = 2u; // GPU cannot handle array size smaller than 2.
-static constexpr uint32_t MAXIMUM_BLUR_RADIUS = 500u; ///< Maximum pixel radius for blur effect. (GL_MAX_FRAGMENT_UNIFORM_COMPONENTS(Usually 1024) - 19 (vertex shader used)) / 3 float
-
-static constexpr float MAXIMUM_BELL_CURVE_WIDTH = 171.352f; ///< bell curve width for MAXIMUM_BLUR_RADIUS case
-static constexpr int32_t MAXIMUM_BELL_CURVE_LOOP_TRIAL_COUNT = 50;
+static constexpr uint32_t MINIMUM_BLUR_RADIUS = 3u; ///< 1-pixel blur(No blur). Blur radius will be compressed to half size(mPixelRadius / 2 >= 1).
+static constexpr uint32_t MAXIMUM_BLUR_RADIUS = 500u; ///< Maximum pixel radius for blur effect. (GL_MAX_FRAGMENT_UNIFORM_COMPONENTS(Usually 1024) - 19 (vertex shader used)) / 3 float
/**
* @brief Calculates gaussian weight
mDownscaleFactor(BLUR_EFFECT_DOWNSCALE_FACTOR),
mPixelRadius(BLUR_EFFECT_PIXEL_RADIUS),
mBellCurveWidth(Math::MACHINE_EPSILON_1),
- mSkipBlur(false),
mIsBackground(isBackground)
{
}
mDownscaleFactor(downscaleFactor),
mPixelRadius(blurRadius),
mBellCurveWidth(Math::MACHINE_EPSILON_1),
- mSkipBlur(false),
mIsBackground(isBackground)
{
- if(DALI_UNLIKELY(mDownscaleFactor < MINIMUM_DOWNSCALE_FACTOR || mDownscaleFactor > MAXIMUM_DOWNSCALE_FACTOR))
- {
- mDownscaleFactor = Dali::Clamp(mDownscaleFactor, MINIMUM_DOWNSCALE_FACTOR, MAXIMUM_DOWNSCALE_FACTOR);
- }
-
- if(DALI_UNLIKELY(blurRadius > MAXIMUM_BLUR_RADIUS))
- {
- const uint32_t fixedBlurRadius = MAXIMUM_BLUR_RADIUS;
- const float fixedDownScaleFactor = Dali::Clamp(
- mDownscaleFactor * static_cast<float>(fixedBlurRadius) / static_cast<float>(blurRadius),
- MINIMUM_DOWNSCALE_FACTOR,
- MAXIMUM_DOWNSCALE_FACTOR);
-
- DALI_LOG_ERROR("Blur radius is out of bound: %u. Use %u and make downscale factor %f to %f.\n",
- blurRadius,
- fixedBlurRadius,
- mDownscaleFactor,
- fixedDownScaleFactor);
-
- mDownscaleFactor = fixedDownScaleFactor;
- mPixelRadius = fixedBlurRadius;
- }
+ mDownscaleFactor = Dali::Clamp(mDownscaleFactor, MINIMUM_DOWNSCALE_FACTOR, MAXIMUM_DOWNSCALE_FACTOR);
+ mPixelRadius = Dali::Clamp(mPixelRadius, MINIMUM_BLUR_RADIUS, MAXIMUM_BLUR_RADIUS);
mPixelRadius = static_cast<uint32_t>(mPixelRadius * mDownscaleFactor);
-
- if(DALI_UNLIKELY((mPixelRadius >> 1) < MINIMUM_GPU_ARRAY_SIZE))
+ if(mPixelRadius <= MINIMUM_BLUR_RADIUS)
{
- mSkipBlur = true;
- DALI_LOG_ERROR("Blur radius is too small. This blur will be ignored.\n");
+ DALI_LOG_ERROR("Downscaled pixel radius %u is too small. Ignore blur.", mPixelRadius);
+ mDownscaleFactor = MAXIMUM_DOWNSCALE_FACTOR;
+ mPixelRadius = MINIMUM_BLUR_RADIUS;
}
}
return handle;
}
-OffScreenRenderable::Type BlurEffectImpl::GetOffScreenRenderableType()
-{
- return mSkipBlur ? OffScreenRenderable::NONE : OffScreenRenderable::BACKWARD;
-}
-
-void BlurEffectImpl::GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward)
-{
- tasks.clear();
- if(!isForward && mIsBackground)
- {
- bool isExclusiveRequired = false;
- Dali::Actor sourceActor = GetOwnerControl();
- while(sourceActor.GetParent())
- {
- sourceActor = sourceActor.GetParent();
- Toolkit::Control control = Toolkit::Control::DownCast(sourceActor);
- if(control && GetImplementation(control).GetOffScreenRenderableType() == OffScreenRenderable::Type::FORWARD)
- {
- sourceActor = GetImplementation(control).GetOffScreenRenderableSourceActor();
- isExclusiveRequired = GetImplementation(control).IsOffScreenRenderTaskExclusive();
- break;
- }
- }
- mSourceRenderTask.SetSourceActor(sourceActor);
- mSourceRenderTask.SetExclusive(isExclusiveRequired);
-
- if(mSourceRenderTask)
- {
- tasks.push_back(mSourceRenderTask);
- }
- if(mHorizontalBlurTask)
- {
- tasks.push_back(mHorizontalBlurTask);
- }
- if(mVerticalBlurTask)
- {
- tasks.push_back(mVerticalBlurTask);
- }
- }
-}
-
void BlurEffectImpl::OnInitialize()
{
- if(DALI_UNLIKELY(mSkipBlur))
- {
- return;
- }
-
// Create CameraActors
{
mRenderFullSizeCamera = CameraActor::New();
const float epsilon = 1e-2f / (mPixelRadius * 2);
const float localOffset = (mPixelRadius * 2) - 1;
- float lowerBoundBellCurveWidth = Math::MACHINE_EPSILON_10000;
- float upperBoundBellCurveWidth = MAXIMUM_BELL_CURVE_WIDTH;
+ float lowerBoundBellCurveWidth = 0.001f;
+ float upperBoundBellCurveWidth = 171.352f; ///< bell curve width for MAXIMUM_BLUR_RADIUS case
- int trialCount = 0;
- while(trialCount++ < MAXIMUM_BELL_CURVE_LOOP_TRIAL_COUNT && upperBoundBellCurveWidth - lowerBoundBellCurveWidth > Math::MACHINE_EPSILON_10000)
+ int trialCount = 0;
+ const int maximumTrialCount = 50;
+ while(trialCount++ < maximumTrialCount && upperBoundBellCurveWidth - lowerBoundBellCurveWidth > Math::MACHINE_EPSILON_10000)
{
- mBellCurveWidth = (lowerBoundBellCurveWidth + upperBoundBellCurveWidth) * 0.5f;
- if(CalculateGaussianWeight(localOffset, mBellCurveWidth) < epsilon)
+ const float bellCurveWidth = (lowerBoundBellCurveWidth + upperBoundBellCurveWidth) * 0.5f;
+ if(CalculateGaussianWeight(localOffset, bellCurveWidth) < epsilon)
{
- lowerBoundBellCurveWidth = mBellCurveWidth;
+ lowerBoundBellCurveWidth = bellCurveWidth;
}
else
{
- upperBoundBellCurveWidth = mBellCurveWidth;
+ upperBoundBellCurveWidth = bellCurveWidth;
}
}
+
+ mBellCurveWidth = (lowerBoundBellCurveWidth + upperBoundBellCurveWidth) * 0.5f;
}
- DALI_LOG_INFO(gRenderEffectLogFilter, Debug::Verbose, "[BlurEffect:%p] mBellCurveWidth calculated! [mPixelRadius:%u][mBellCurveWidth:%f]\n", this, mPixelRadius, mBellCurveWidth);
+ DALI_LOG_INFO(gRenderEffectLogFilter, Debug::Verbose, "[BlurEffect:%p] mBellCurveWidth calculated! [radius:%u][bellCurveWidth:%f]\n", this, mPixelRadius, mBellCurveWidth);
// Create blur actors
{
void BlurEffectImpl::OnActivate()
{
- if(DALI_UNLIKELY(mSkipBlur))
- {
- return;
- }
-
Toolkit::Control ownerControl = GetOwnerControl();
DALI_ASSERT_ALWAYS(ownerControl && "Set the owner of RenderEffect before you activate.");
mPlacementSceneHolder = sceneHolder;
// Set blur
- CreateFrameBuffers(size, ImageDimensions(downsampledWidth, downsampledHeight));
+ CreateFrameBuffers(size, Size(downsampledWidth, downsampledHeight));
CreateRenderTasks(sceneHolder, ownerControl);
SetShaderConstants(downsampledWidth, downsampledHeight);
void BlurEffectImpl::OnDeactivate()
{
- if(DALI_UNLIKELY(mSkipBlur))
- {
- return;
- }
-
auto ownerControl = GetOwnerControl();
if(DALI_LIKELY(ownerControl))
{
mSourceRenderTask.Reset();
}
-void BlurEffectImpl::CreateFrameBuffers(const Vector2 size, const ImageDimensions downsampledSize)
+void BlurEffectImpl::CreateFrameBuffers(const Size size, const Size downsampledSize)
{
- uint32_t downsampledWidth = downsampledSize.GetWidth();
- uint32_t downsampledHeight = downsampledSize.GetHeight();
+ uint32_t downsampledWidth = downsampledSize.width;
+ uint32_t downsampledHeight = downsampledSize.height;
// buffer to draw input texture
mInputBackgroundFrameBuffer = FrameBuffer::New(downsampledWidth, downsampledHeight, FrameBuffer::Attachment::DEPTH_STENCIL);
{
mSourceRenderTask.SetSourceActor(sourceControl);
}
+ mSourceRenderTask.SetOrderIndex(BLUR_EFFECT_ORDER_INDEX);
mSourceRenderTask.SetCameraActor(mRenderFullSizeCamera);
mSourceRenderTask.SetFrameBuffer(mInputBackgroundFrameBuffer);
mSourceRenderTask.SetInputEnabled(false);
SetRendererTexture(mHorizontalBlurActor.GetRendererAt(0), mInputBackgroundFrameBuffer);
mHorizontalBlurTask = taskList.CreateTask();
mHorizontalBlurTask.SetSourceActor(mHorizontalBlurActor);
+ mHorizontalBlurTask.SetOrderIndex(BLUR_EFFECT_ORDER_INDEX + 1);
mHorizontalBlurTask.SetExclusive(true);
mHorizontalBlurTask.SetInputEnabled(false);
mHorizontalBlurTask.SetCameraActor(mRenderDownsampledCamera);
SetRendererTexture(mVerticalBlurActor.GetRendererAt(0), mTemporaryFrameBuffer);
mVerticalBlurTask = taskList.CreateTask();
mVerticalBlurTask.SetSourceActor(mVerticalBlurActor);
+ mVerticalBlurTask.SetOrderIndex(BLUR_EFFECT_ORDER_INDEX + 2);
mVerticalBlurTask.SetExclusive(true);
mVerticalBlurTask.SetInputEnabled(false);
mVerticalBlurTask.SetCameraActor(mRenderDownsampledCamera);
return size;
}
-void BlurEffectImpl::SetShaderConstants(uint32_t downsampledWidth, uint32_t downsampledHeight)
+void BlurEffectImpl::SetShaderConstants(float downsampledWidth, float downsampledHeight)
{
const uint32_t sampleCount = mPixelRadius >> 1; // compression
const uint32_t kernelSize = sampleCount * 4 - 1;
- const uint32_t halfKernelSize = kernelSize / 2 + 1; // Gaussian curve is symmetric
+ const uint32_t halfKernelSize = kernelSize / 2; // Gaussian curve is symmetric
// Output: Gaussian kernel compressed to half size
std::vector<float> uvOffsets(sampleCount);
#include <dali/integration-api/adaptor-framework/scene-holder.h>
#include <dali/public-api/actors/actor.h>
#include <dali/public-api/actors/camera-actor.h>
-#include <dali/public-api/images/image-operations.h>
#include <dali/public-api/object/weak-handle.h>
#include <dali/public-api/render-tasks/render-task.h>
#include <dali/public-api/rendering/frame-buffer.h>
*/
static BlurEffectImplPtr New(float downscaleFactor, uint32_t blurRadius, bool isBackground);
- /**
- * @copydoc Toolkit::Internal::RenderEffectImpl::GetOffScreenRenderableType
- */
- OffScreenRenderable::Type GetOffScreenRenderableType() override;
-
- /**
- * @copydoc Toolkit::Internal::RenderEffectImpl::GetOffScreenRenderTasks
- */
- void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) override;
-
protected:
/**
* @brief Creates an uninitialized blur effect implementation
* @param[in] size Full size of input.
* @param[in] downsampledSize Downsampled size for performance.
*/
- void CreateFrameBuffers(const Vector2 size, const ImageDimensions downsampledSize);
+ void CreateFrameBuffers(const Size size, const Size downsampledSize);
/**
* @brief Sets blur render tasks.
* @param[in] downsampledWidth Downsized width of input texture.
* @param[in] downsampledHeight Downsized height of input texture.
*/
- void SetShaderConstants(uint32_t downsampledWidth, uint32_t downsampledHeight);
+ void SetShaderConstants(float downsampledWidth, float downsampledHeight);
/**
* @brief Get an offset property in std::string format
uint32_t mPixelRadius;
float mBellCurveWidth;
- bool mSkipBlur : 1;
bool mIsBackground : 1;
};
} // namespace Internal
*/
bool IsActivated() const;
- /**
- * @brief Retrieves OffScreenRenderableType of this RenderEffect.
- *
- * @return OffScreenRenderableType for this RenderEffect.
- */
- virtual OffScreenRenderable::Type GetOffScreenRenderableType() = 0;
-
- /**
- * @brief Retrieves the off-screen RenderTasks associated with the RenderEffect.
- * This method returns the internal RenderTasks held by the RenderEffect. This tasks are
- * used for off-screen rendering, and the system will assign order index to each
- * tasks based on the render order.
- *
- * RenderEffect with a non-NONE OffScreenRenderableType should override this method to
- * provide their render tasks.
- *
- * @param[out] tasks A list of RenderTasks to be populated with the RenderEffect's forward
- * or backward off-screen RenderTask.
- * @param[in] isForward Indicates whether to retrieve forward (true) or backward (false)
- * RenderTasks.
- */
- virtual void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) = 0;
-
protected:
/**
* @copydoc Dali::Toolkit::RenderEffect::RenderEffect
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
Actor self = Self();
// Accessibility
- self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::LINK);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::LINK);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
}
DevelControl::ControlAccessible* TextAnchor::CreateAccessibleObject()
self.Add(mStencil);
// Accessibility
- self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::ENTRY);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::ENTRY);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
Accessibility::Bridge::EnabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
Accessibility::Bridge::DisabledSignal().Connect(this, &TextEditor::OnAccessibilityStatusChanged);
}
// Accessibility
- self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::ENTRY);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::ENTRY);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
Accessibility::Bridge::EnabledSignal().Connect(this, &TextField::OnAccessibilityStatusChanged);
Accessibility::Bridge::DisabledSignal().Connect(this, &TextField::OnAccessibilityStatusChanged);
return true;
}
- else if((Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode() && KEY_RETURN_NAME == event.GetKeyName()) ||
- Dali::DevelKey::DALI_KEY_KP_ENTER == event.GetKeyCode())
+ else if(Dali::DevelKey::DALI_KEY_RETURN == event.GetKeyCode() && KEY_RETURN_NAME == event.GetKeyName())
{
// Do nothing when enter is comming.
return false;
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2022 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
#include <dali-toolkit/devel-api/focus-manager/keyinput-focus-manager.h>
#include <dali-toolkit/devel-api/text/rendering-backend.h>
-#include <dali-toolkit/internal/text/controller/text-controller.h>
#include <dali-toolkit/internal/text/decorator/text-decorator.h>
+#include <dali-toolkit/internal/text/controller/text-controller.h>
#include <dali-toolkit/internal/text/text-effects-style.h>
#include <dali-toolkit/internal/text/text-enumerations-impl.h>
#include <dali-toolkit/internal/text/text-font-style.h>
auto mode = map->Find(Toolkit::HiddenInput::Property::MODE);
if(mode && (mode->Get<int>() != Toolkit::HiddenInput::Mode::HIDE_NONE))
{
- textField.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::PASSWORD_TEXT);
+ textField.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Accessibility::Role::PASSWORD_TEXT);
}
else
{
- textField.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::ENTRY);
+ textField.SetProperty(Toolkit::DevelControl::Property::ACCESSIBILITY_ROLE, Accessibility::Role::ENTRY);
}
}
break;
engine.SetCursorWidth(0u); // Do not layout space for the cursor.
// Accessibility
- self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::TEXT);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, Dali::Accessibility::Role::LABEL);
+ self.SetProperty(DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE, true);
Accessibility::Bridge::EnabledSignal().Connect(this, &TextLabel::OnAccessibilityStatusChanged);
Accessibility::Bridge::DisabledSignal().Connect(this, &TextLabel::OnAccessibilityStatusChanged);
}
}
-WebView::WebView(uint32_t argc, char** argv, int32_t type)
+WebView::WebView(uint32_t argc, char** argv)
: Control(ControlBehaviour(ACTOR_BEHAVIOUR_DEFAULT | DISABLE_STYLE_CHANGE_SIGNALS)),
mVisual(),
mWebViewSize(Stage::GetCurrent().GetSize()),
mCornerRadius(Vector4::ZERO),
mCornerRadiusPolicy(1.0f)
{
- mWebEngine = Dali::WebEngine::New(type);
+ mWebEngine = Dali::WebEngine::New();
// WebEngine is empty when it is not properly initialized.
if(mWebEngine)
return handle;
}
-Toolkit::WebView WebView::New(uint32_t argc, char** argv, int32_t type)
+Toolkit::WebView WebView::New(uint32_t argc, char** argv)
{
- WebView* impl = new WebView(argc, argv, type);
+ WebView* impl = new WebView(argc, argv);
Toolkit::WebView handle = Toolkit::WebView(*impl);
if(impl->GetPlugin())
{
}
}
-void WebView::WebAuthenticationCancel()
-{
- if(mWebEngine)
- {
- mWebEngine.WebAuthenticationCancel();
- }
-}
-
-void WebView::RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback)
-{
- if(mWebEngine)
- {
- mWebEngine.RegisterWebAuthDisplayQRCallback(std::move(callback));
- }
-}
-
-void WebView::RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback)
-{
- if(mWebEngine)
- {
- mWebEngine.RegisterWebAuthResponseCallback(std::move(callback));
- }
-}
-
-void WebView::RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback)
-{
- if(mWebEngine)
- {
- mWebEngine.RegisterUserMediaPermissionRequestCallback(std::move(callback));
- }
-}
-
void WebView::OnFrameRendered()
{
if(mFrameRenderedCallback)
}
// Make sure that mVisual is created only once.
- if(!mVisualChangeRequired && mVisual)
- {
+ if (mVisual)
return;
- }
// Get webVisual for checking corner radius
Toolkit::Visual::Base webVisual = Dali::Toolkit::DevelControl::GetVisual(*this, Toolkit::WebView::Property::URL);
- Property::Map webMap;
+ Property::Map webMap;
webVisual.CreatePropertyMap(webMap);
- Property::Value* cornerRadiusValue = webMap.Find(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS);
+ Property::Value* cornerRadiusValue = webMap.Find(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS);
if(cornerRadiusValue)
{
mCornerRadius = cornerRadiusValue->Get<Vector4>();
}
- Property::Value* cornerRadiusValuePolicy = webMap.Find(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY);
+ Property::Value* cornerRadiusValuePolicy = webMap.Find(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY);
if(cornerRadiusValuePolicy)
{
mCornerRadiusPolicy = cornerRadiusValuePolicy->Get<int>();
}
- // Reset flag
- mVisualChangeRequired = false;
+ Dali::Toolkit::ImageUrl nativeImageUrl = Dali::Toolkit::Image::GenerateUrl(mWebEngine.GetNativeImageSource());
+ Property::Map propertyMap;
+ propertyMap.Insert(Dali::Toolkit::Visual::Property::TYPE, Dali::Toolkit::Visual::IMAGE);
+ propertyMap.Insert(Dali::Toolkit::ImageVisual::Property::URL, nativeImageUrl.GetUrl());
+ propertyMap.Insert(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS, mCornerRadius);
+ propertyMap.Insert(Dali::Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, mCornerRadiusPolicy);
+ mVisual = Toolkit::VisualFactory::Get().CreateVisual(propertyMap);
+ if(mVisual)
+ {
+ // Reset flag
+ mVisualChangeRequired = false;
- auto nativeImageSourcePtr = mWebEngine.GetNativeImageSource();
+ auto nativeImageSourcePtr = mWebEngine.GetNativeImageSource();
- mLastRenderedNativeImageWidth = nativeImageSourcePtr->GetWidth();
- mLastRenderedNativeImageHeight = nativeImageSourcePtr->GetHeight();
+ mLastRenderedNativeImageWidth = nativeImageSourcePtr->GetWidth();
+ mLastRenderedNativeImageHeight = nativeImageSourcePtr->GetHeight();
- Dali::Toolkit::ImageUrl nativeImageUrl = Dali::Toolkit::Image::GenerateUrl(nativeImageSourcePtr);
+ Dali::Toolkit::ImageUrl nativeImageUrl = Dali::Toolkit::Image::GenerateUrl(nativeImageSourcePtr);
- mVisual = Toolkit::VisualFactory::Get().CreateVisual(
- {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE},
- {Toolkit::ImageVisual::Property::URL, nativeImageUrl.GetUrl()},
- {Toolkit::ImageVisual::Property::PIXEL_AREA, FULL_TEXTURE_RECT},
- {Toolkit::ImageVisual::Property::WRAP_MODE_U, Dali::WrapMode::CLAMP_TO_EDGE},
- {Toolkit::ImageVisual::Property::WRAP_MODE_V, Dali::WrapMode::CLAMP_TO_EDGE},
- {Toolkit::DevelVisual::Property::CORNER_RADIUS, mCornerRadius},
- {Toolkit::DevelVisual::Property::CORNER_RADIUS_POLICY, mCornerRadiusPolicy}});
+ mVisual = Toolkit::VisualFactory::Get().CreateVisual(
+ {{Toolkit::Visual::Property::TYPE, Toolkit::Visual::IMAGE},
+ {Toolkit::ImageVisual::Property::URL, nativeImageUrl.GetUrl()},
+ {Toolkit::ImageVisual::Property::PIXEL_AREA, FULL_TEXTURE_RECT},
+ {Toolkit::ImageVisual::Property::WRAP_MODE_U, Dali::WrapMode::CLAMP_TO_EDGE},
+ {Toolkit::ImageVisual::Property::WRAP_MODE_V, Dali::WrapMode::CLAMP_TO_EDGE}});
- if(mVisual)
- {
- DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual, DepthIndex::CONTENT);
- EnableBlendMode(!mVideoHoleEnabled);
+ if(mVisual)
+ {
+ DevelControl::RegisterVisual(*this, Toolkit::WebView::Property::URL, mVisual, DepthIndex::CONTENT);
+ EnableBlendMode(!mVideoHoleEnabled);
+ }
}
}
WebView(const std::string& locale, const std::string& timezoneId);
- WebView(uint32_t argc, char** argv, int32_t type);
+ WebView(uint32_t argc, char** argv);
virtual ~WebView();
static Toolkit::WebView New(const std::string& locale, const std::string& timezoneId);
/**
- * @copydoc Dali::Toolkit::WebView::New( uint32_t, char**, int32_t )
+ * @copydoc Dali::Toolkit::WebView::New( uint32_t, char** )
*/
- static Toolkit::WebView New(uint32_t argc, char** argv, int32_t type);
+ static Toolkit::WebView New(uint32_t argc, char** argv);
/**
* @copydoc Dali::Toolkit::WebView::FindWebView()
*/
void GetPlainTextAsynchronously(Dali::WebEnginePlugin::PlainTextReceivedCallback callback);
- /**
- * @copydoc Dali::Toolkit::WebView::WebAuthenticationCancel()
- */
- void WebAuthenticationCancel();
-
- /**
- * @copydoc Dali::Toolkit::WebView::RegisterWebAuthDisplayQRCallback()
- */
- void RegisterWebAuthDisplayQRCallback(Dali::WebEnginePlugin::WebEngineWebAuthDisplayQRCallback callback);
-
- /**
- * @copydoc Dali::Toolkit::WebView::RegisterWebAuthResponseCallback()
- */
- void RegisterWebAuthResponseCallback(Dali::WebEnginePlugin::WebEngineWebAuthResponseCallback callback);
-
- /**
- * @copydoc Dali::Toolkit::WebView::RegisterUserMediaPermissionRequestCallback()
- */
- void RegisterUserMediaPermissionRequestCallback(Dali::WebEnginePlugin::WebEngineUserMediaPermissionRequestCallback callback);
-
public: // Properties
/**
* @brief Called when a property of an object of this type is set.
${toolkit_src_dir}/visuals/color/color-visual-shader-factory.cpp
${toolkit_src_dir}/visuals/color/color-visual.cpp
${toolkit_src_dir}/visuals/custom-shader-factory.cpp
+ ${toolkit_src_dir}/visuals/npatch-shader-factory.cpp
${toolkit_src_dir}/visuals/gradient/gradient-visual.cpp
${toolkit_src_dir}/visuals/gradient/gradient.cpp
${toolkit_src_dir}/visuals/gradient/linear-gradient.cpp
${toolkit_src_dir}/visuals/mesh/mesh-visual.cpp
${toolkit_src_dir}/visuals/npatch/npatch-data.cpp
${toolkit_src_dir}/visuals/npatch/npatch-loader.cpp
- ${toolkit_src_dir}/visuals/npatch/npatch-shader-factory.cpp
${toolkit_src_dir}/visuals/npatch/npatch-visual.cpp
${toolkit_src_dir}/visuals/primitive/primitive-visual.cpp
${toolkit_src_dir}/visuals/svg/svg-loader-observer.cpp
${toolkit_src_dir}/text/rendering/atlas/atlas-mesh-factory.cpp
${toolkit_src_dir}/text/rendering/text-backend-impl.cpp
${toolkit_src_dir}/text/rendering/text-typesetter.cpp
- ${toolkit_src_dir}/text/rendering/text-typesetter-impl.cpp
${toolkit_src_dir}/text/rendering/view-model.cpp
${toolkit_src_dir}/text/rendering/styles/underline-helper-functions.cpp
${toolkit_src_dir}/text/rendering/styles/strikethrough-helper-functions.cpp
}
#endif
- lowp float y = TEXTURE(sTexture, texCoord).r;
- lowp float u = TEXTURE(sTextureU, texCoord).r - 0.5;
- lowp float v = TEXTURE(sTextureV, texCoord).r - 0.5;
+ lowp float y = texture(sTexture, texCoord).r;
+ lowp float u = texture(sTextureU, texCoord).r - 0.5;
+ lowp float v = texture(sTextureV, texCoord).r - 0.5;
lowp vec4 rgba;
rgba.r = y + (1.403 * v);
rgba.g = y - (0.344 * u) - (0.714 * v);
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2022 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
std::string fileString;
if(LoadFile(jsonFilePath, fileString))
{
- try
- {
- builder.LoadFromString(fileString);
- }
- catch(...)
- {
- DALI_LOG_WARNING("Error during parse JSON file '%s'\n", jsonFilePath.c_str());
- return false;
- }
+ builder.LoadFromString(fileString);
return true;
}
else
const bool isVerticalScrollEnabled = mEventData->mDecorator->IsVerticalScrollEnabled();
if(isHorizontalScrollEnabled || isVerticalScrollEnabled)
{
- const Vector2& targetSize = mModel->mVisualModel->mControlSize;
- const Vector2& layoutSize = mModel->mVisualModel->GetLayoutSize();
+ const Vector2& targetSize = mModel->mVisualModel->mControlSize;
+ const Vector2& layoutSize = mModel->mVisualModel->GetLayoutSize();
if(isHorizontalScrollEnabled)
{
return it == mModel->mLogicalModel->mAnchors.End() ? -1 : it - mModel->mLogicalModel->mAnchors.Begin();
}
-bool Controller::Impl::ShouldClearFocusOnEscape() const
-{
- if(DALI_UNLIKELY(mShouldClearFocusOnEscape == ClearFocusOnEscapeState::UNKNOWN))
- {
- mShouldClearFocusOnEscape = ClearFocusOnEscapeState::ENABLE;
-
- Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
- if(styleManager)
- {
- const auto clearFocusOnEscapeValue = Toolkit::DevelStyleManager::GetConfigurations(styleManager).Find("clearFocusOnEscape", Property::Type::BOOLEAN);
-
- // Default is ENABLE. If config don't have "clearFocusOnEscape" property, make it ENABLE.
- mShouldClearFocusOnEscape = (!clearFocusOnEscapeValue || clearFocusOnEscapeValue->Get<bool>()) ? ClearFocusOnEscapeState::ENABLE : ClearFocusOnEscapeState::DISABLE;
- }
- }
- DALI_ASSERT_DEBUG(mShouldClearFocusOnEscape != ClearFocusOnEscapeState::UNKNOWN && "mShouldClearFocusOnEscape Should be set now");
-
- return (mShouldClearFocusOnEscape == ClearFocusOnEscapeState::ENABLE);
-}
-
void Controller::Impl::CopyUnderlinedFromLogicalToVisualModels(bool shouldClearPreUnderlineRuns)
{
//Underlined character runs for markup-processor
struct Controller::Impl
{
-public:
- enum class ClearFocusOnEscapeState
- {
- UNKNOWN = -1, ///< Unknown state
- ENABLE = 0,
- DISABLE = 1,
- };
-
-public:
Impl(ControlInterface* controlInterface,
EditableControlInterface* editableControlInterface,
SelectableControlInterface* selectableControlInterface,
mOutlineSetByString(false),
mFontStyleSetByString(false),
mStrikethroughSetByString(false),
- mShouldClearFocusOnEscape(ClearFocusOnEscapeState::UNKNOWN),
+ mShouldClearFocusOnEscape(true),
mLayoutDirection(LayoutDirection::LEFT_TO_RIGHT),
mCurrentLineSize(0.f),
mTextFitMinSize(DEFAULT_TEXTFIT_MIN),
// Set the text properties to default
mModel->mVisualModel->SetUnderlineEnabled(false);
mModel->mVisualModel->SetUnderlineHeight(0.0f);
+
+ Toolkit::StyleManager styleManager = Toolkit::StyleManager::Get();
+ if(styleManager)
+ {
+ const auto clearFocusOnEscapeValue = Toolkit::DevelStyleManager::GetConfigurations(styleManager).Find("clearFocusOnEscape", Property::Type::BOOLEAN);
+
+ // Default is true. If config don't have "clearFocusOnEscape" property, make it true.
+ mShouldClearFocusOnEscape = (!clearFocusOnEscapeValue || clearFocusOnEscapeValue->Get<bool>());
+ }
}
~Impl()
*/
Toolkit::TextAnchor CreateAnchorActor(Anchor anchor);
- /**
- * @brief Return true when text control should clear key input focus when escape key is pressed.
- *
- * @note We ask to style manager configurations, and store the option.
- * @note Default is true. Mean, without any options, text control should clear key input focus when escape key is pressed.
- *
- * @return Whether text control should clear key input focus or not when escape key is pressed.
- */
- bool ShouldClearFocusOnEscape() const;
-
public:
/**
* @brief Gets implementation from the controller handle.
std::vector<Toolkit::DevelTextLabel::FitOption> mTextFitArray; ///< List of FitOption for TextFitArray operation.
- bool mRecalculateNaturalSize : 1; ///< Whether the natural size needs to be recalculated.
- bool mMarkupProcessorEnabled : 1; ///< Whether the mark-up procesor is enabled.
- bool mClipboardHideEnabled : 1; ///< Whether the ClipboardHide function work or not
- bool mIsAutoScrollEnabled : 1; ///< Whether auto text scrolling is enabled.
- bool mIsAutoScrollMaxTextureExceeded : 1; ///< Whether auto text scrolling is exceed max texture size.
- bool mUpdateTextDirection : 1; ///< Whether the text direction needs to be updated.
-
- CharacterDirection mIsTextDirectionRTL : 1; ///< Whether the text direction is right to left or not
-
- bool mUnderlineSetByString : 1; ///< Set when underline is set by string (legacy) instead of map
- bool mShadowSetByString : 1; ///< Set when shadow is set by string (legacy) instead of map
- bool mOutlineSetByString : 1; ///< Set when outline is set by string (legacy) instead of map
- bool mFontStyleSetByString : 1; ///< Set when font style is set by string (legacy) instead of map
- bool mStrikethroughSetByString : 1; ///< Set when strikethrough is set by string (legacy) instead of map
-
- mutable ClearFocusOnEscapeState mShouldClearFocusOnEscape : 3; ///< Whether text control should clear key input focus.
- ///< Make it mutable so we can update it at const method.
-
- LayoutDirection::Type mLayoutDirection; ///< Current system language direction
+ bool mRecalculateNaturalSize : 1; ///< Whether the natural size needs to be recalculated.
+ bool mMarkupProcessorEnabled : 1; ///< Whether the mark-up procesor is enabled.
+ bool mClipboardHideEnabled : 1; ///< Whether the ClipboardHide function work or not
+ bool mIsAutoScrollEnabled : 1; ///< Whether auto text scrolling is enabled.
+ bool mIsAutoScrollMaxTextureExceeded : 1; ///< Whether auto text scrolling is exceed max texture size.
+ bool mUpdateTextDirection : 1; ///< Whether the text direction needs to be updated.
+ CharacterDirection mIsTextDirectionRTL : 1; ///< Whether the text direction is right to left or not
+
+ bool mUnderlineSetByString : 1; ///< Set when underline is set by string (legacy) instead of map
+ bool mShadowSetByString : 1; ///< Set when shadow is set by string (legacy) instead of map
+ bool mOutlineSetByString : 1; ///< Set when outline is set by string (legacy) instead of map
+ bool mFontStyleSetByString : 1; ///< Set when font style is set by string (legacy) instead of map
+ bool mStrikethroughSetByString : 1; ///< Set when strikethrough is set by string (legacy) instead of map
+ bool mShouldClearFocusOnEscape : 1; ///< Whether text control should clear key input focus
+ LayoutDirection::Type mLayoutDirection; ///< Current system language direction
Shader mShaderBackground; ///< The shader for text background.
bool Controller::ShouldClearFocusOnEscape() const
{
- return mImpl->ShouldClearFocusOnEscape();
+ return mImpl->mShouldClearFocusOnEscape;
}
Actor Controller::CreateBackgroundActor()
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// CLASS HEADER
-#include <dali-toolkit/internal/text/rendering/text-typesetter-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/devel-api/text-abstraction/font-client.h>
-#include <dali/integration-api/debug.h>
-#include <dali/integration-api/trace.h>
-#include <dali/public-api/common/constants.h>
-#include <dali/public-api/math/math-utils.h>
-#include <memory.h>
-#include <cmath>
-
-// INTERNAL INCLUDES
-#include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h>
-#include <dali-toolkit/internal/text/character-spacing-glyph-run.h>
-#include <dali-toolkit/internal/text/glyph-metrics-helper.h>
-#include <dali-toolkit/internal/text/line-helper-functions.h>
-#include <dali-toolkit/internal/text/line-run.h>
-#include <dali-toolkit/internal/text/rendering/styles/character-spacing-helper-functions.h>
-#include <dali-toolkit/internal/text/rendering/styles/strikethrough-helper-functions.h>
-#include <dali-toolkit/internal/text/rendering/styles/underline-helper-functions.h>
-#include <dali-toolkit/internal/text/rendering/view-model.h>
-#include <dali-toolkit/internal/text/strikethrough-glyph-run.h>
-#include <dali-toolkit/internal/text/text-definitions.h>
-#include <dali-toolkit/internal/text/underlined-glyph-run.h>
-
-namespace Dali
-{
-namespace Toolkit
-{
-namespace Text
-{
-namespace
-{
-DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
-
-const float HALF(0.5f);
-const float ONE_AND_A_HALF(1.5f);
-
-/**
- * @brief Fast multiply & divide by 255. It wiil be useful when we applying alpha value in color
- *
- * @param x The value between [0..255]
- * @param y The value between [0..255]
- * @return (x*y)/255
- */
-inline uint8_t MultiplyAndNormalizeColor(const uint8_t x, const uint8_t y) noexcept
-{
- const uint32_t xy = static_cast<const uint32_t>(x) * y;
- return ((xy << 15) + (xy << 7) + xy) >> 23;
-}
-
-/// Helper macro define for glyph typesetter. It will reduce some duplicated code line.
-// clang-format off
-/**
- * @brief Prepare decode glyph bitmap data. It must be call END_GLYPH_BITMAP end of same scope.
- */
-#define BEGIN_GLYPH_BITMAP(data) \
-{ \
- uint32_t glyphOffet = 0u; \
- const bool useLocalScanline = data.glyphBitmap.compressionType != TextAbstraction::GlyphBufferData::CompressionType::NO_COMPRESSION; \
- uint8_t* __restrict__ glyphScanline = useLocalScanline ? (uint8_t*)malloc(data.glyphBitmap.width * glyphPixelSize) : data.glyphBitmap.buffer; \
- DALI_ASSERT_ALWAYS(glyphScanline && "Glyph scanline for buffer is nullptr!");
-
-/**
- * @brief Macro to skip useless line fast.
- */
-#define SKIP_GLYPH_SCANLINE(skipLine) \
-if(useLocalScanline) \
-{ \
- for(int32_t lineIndex = 0; lineIndex < skipLine; ++lineIndex) \
- { \
- TextAbstraction::GlyphBufferData::DecompressScanline(data.glyphBitmap, glyphScanline, glyphOffet); \
- } \
-} \
-else \
-{ \
- glyphScanline += skipLine * static_cast<int32_t>(data.glyphBitmap.width * glyphPixelSize); \
-}
-
-/**
- * @brief Prepare scanline of glyph bitmap data per each lines. It must be call END_GLYPH_SCANLINE_DECODE end of same scope.
- */
-#define BEGIN_GLYPH_SCANLINE_DECODE(data) \
-{ \
- if(useLocalScanline) \
- { \
- TextAbstraction::GlyphBufferData::DecompressScanline(data.glyphBitmap, glyphScanline, glyphOffet); \
- }
-
-/**
- * @brief Finalize scanline of glyph bitmap data per each lines.
- */
-#define END_GLYPH_SCANLINE_DECODE(data) \
- if(!useLocalScanline) \
- { \
- glyphScanline += data.glyphBitmap.width * glyphPixelSize; \
- } \
-} // For ensure that we call BEGIN_GLYPH_SCANLINE_DECODE before
-
-/**
- * @brief Finalize decode glyph bitmap data.
- */
-#define END_GLYPH_BITMAP() \
- if(useLocalScanline) \
- { \
- free(glyphScanline); \
- } \
-} // For ensure that we call BEGIN_GLYPH_BITMAP before
-
-// clang-format on
-/// Helper macro define end.
-
-/**
- * @brief Data struct used to set the buffer of the glyph's bitmap into the final bitmap's buffer.
- */
-struct GlyphData
-{
- Devel::PixelBuffer bitmapBuffer; ///< The buffer of the whole bitmap. The format is RGBA8888.
- Vector2* position; ///< The position of the glyph.
- TextAbstraction::GlyphBufferData glyphBitmap; ///< The glyph's bitmap.
- uint32_t width; ///< The bitmap's width.
- uint32_t height; ///< The bitmap's height.
- int32_t horizontalOffset; ///< The horizontal offset to be added to the 'x' glyph's position.
- int32_t verticalOffset; ///< The vertical offset to be added to the 'y' glyph's position.
-};
-
-/**
- * @brief Sets the glyph's buffer into the bitmap's buffer.
- *
- * @param[in, out] data Struct which contains the glyph's data and the bitmap's data.
- * @param[in] position The position of the glyph.
- * @param[in] color The color of the glyph.
- * @param[in] style The style of the text.
- * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
- */
-void TypesetGlyph(GlyphData& __restrict__ data,
- const Vector2* const __restrict__ position,
- const Vector4* const __restrict__ color,
- const Typesetter::Style style,
- const Pixel::Format pixelFormat)
-{
- if((0u == data.glyphBitmap.width) || (0u == data.glyphBitmap.height))
- {
- // Nothing to do if the width or height of the buffer is zero.
- return;
- }
-
- // Initial vertical / horizontal offset.
- const int32_t yOffset = data.verticalOffset + position->y;
- const int32_t xOffset = data.horizontalOffset + position->x;
-
- // Whether the given glyph is a color one.
- const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
- const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format);
- const uint32_t glyphAlphaIndex = (glyphPixelSize > 0u) ? glyphPixelSize - 1u : 0u;
-
- // Determinate iterator range.
- const int32_t lineIndexRangeMin = std::max(0, -yOffset);
- const int32_t lineIndexRangeMax = std::min(static_cast<int32_t>(data.glyphBitmap.height), static_cast<int32_t>(data.height) - yOffset);
- const int32_t indexRangeMin = std::max(0, -xOffset);
- const int32_t indexRangeMax = std::min(static_cast<int32_t>(data.glyphBitmap.width), static_cast<int32_t>(data.width) - xOffset);
-
- // If current glyph don't need to be rendered, just ignore.
- if(lineIndexRangeMax <= lineIndexRangeMin || indexRangeMax <= indexRangeMin)
- {
- return;
- }
-
- if(Pixel::RGBA8888 == pixelFormat)
- {
- uint32_t* __restrict__ bitmapBuffer = reinterpret_cast<uint32_t*>(data.bitmapBuffer.GetBuffer());
- // Skip basic line.
- bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast<int32_t>(data.width);
-
- // Fast-cut if style is MASK or OUTLINE. Outline not shown for color glyph.
- // Just overwrite transparent color and return.
- if(isColorGlyph && (Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style))
- {
- for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
- {
- // We can use memset here.
- memset(bitmapBuffer + xOffset + indexRangeMin, 0, (indexRangeMax - indexRangeMin) * sizeof(uint32_t));
- bitmapBuffer += data.width;
- }
- return;
- }
-
- const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format;
-
- // Precalculate input color's packed result.
- uint32_t packedInputColor = 0u;
- uint8_t* __restrict__ packedInputColorBuffer = reinterpret_cast<uint8_t*>(&packedInputColor);
-
- *(packedInputColorBuffer + 3u) = static_cast<uint8_t>(color->a * 255);
- *(packedInputColorBuffer + 2u) = static_cast<uint8_t>(color->b * 255);
- *(packedInputColorBuffer + 1u) = static_cast<uint8_t>(color->g * 255);
- *(packedInputColorBuffer) = static_cast<uint8_t>(color->r * 255);
-
- // Prepare glyph bitmap
- BEGIN_GLYPH_BITMAP(data);
-
- // Skip basic line of glyph.
- SKIP_GLYPH_SCANLINE(lineIndexRangeMin);
-
- // Traverse the pixels of the glyph line per line.
- if(isColorGlyph)
- {
- for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
- {
- BEGIN_GLYPH_SCANLINE_DECODE(data);
-
- for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
- {
- const int32_t xOffsetIndex = xOffset + index;
-
- // Retrieves the color from the color glyph.
- uint32_t packedColorGlyph = *(reinterpret_cast<const uint32_t*>(glyphScanline + (index << 2)));
- uint8_t* __restrict__ packedColorGlyphBuffer = reinterpret_cast<uint8_t*>(&packedColorGlyph);
-
- // Update the alpha channel.
- const uint8_t colorAlpha = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 3u), *(packedColorGlyphBuffer + 3u));
- *(packedColorGlyphBuffer + 3u) = colorAlpha;
-
- if(Typesetter::STYLE_SHADOW == style)
- {
- // The shadow of color glyph needs to have the shadow color.
- *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), colorAlpha);
- *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), colorAlpha);
- *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedInputColorBuffer, colorAlpha);
- }
- else
- {
- if(swapChannelsBR)
- {
- std::swap(*packedColorGlyphBuffer, *(packedColorGlyphBuffer + 2u)); // Swap B and R.
- }
-
- *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedColorGlyphBuffer + 2u), colorAlpha);
- *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedColorGlyphBuffer + 1u), colorAlpha);
- *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedColorGlyphBuffer, colorAlpha);
-
- if(data.glyphBitmap.isColorBitmap)
- {
- *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), *(packedColorGlyphBuffer + 2u));
- *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), *(packedColorGlyphBuffer + 1u));
- *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedInputColorBuffer, *packedColorGlyphBuffer);
- }
- }
-
- // Set the color into the final pixel buffer.
- *(bitmapBuffer + xOffsetIndex) = packedColorGlyph;
- }
-
- bitmapBuffer += data.width;
-
- END_GLYPH_SCANLINE_DECODE(data);
- }
- }
- else
- {
- for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
- {
- BEGIN_GLYPH_SCANLINE_DECODE(data);
-
- for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
- {
- // Update the alpha channel.
- const uint8_t alpha = *(glyphScanline + index * glyphPixelSize + glyphAlphaIndex);
-
- // Copy non-transparent pixels only
- if(alpha > 0u)
- {
- const int32_t xOffsetIndex = xOffset + index;
-
- // Check alpha of overlapped pixels
- uint32_t& currentColor = *(bitmapBuffer + xOffsetIndex);
- uint8_t* packedCurrentColorBuffer = reinterpret_cast<uint8_t*>(¤tColor);
-
- // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
- // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
- // semi-transparent gaps between joint glyphs with overlapped pixels, which could
- // happen, for example, in the RTL text when we copy glyphs from right to left).
- uint8_t currentAlpha = *(packedCurrentColorBuffer + 3u);
- currentAlpha = std::max(currentAlpha, alpha);
- if(currentAlpha == 255)
- {
- // Fast-cut to avoid float type operation.
- currentColor = packedInputColor;
- }
- else
- {
- // Pack the given color into a 32bit buffer. The alpha channel will be updated later for each pixel.
- // The format is RGBA8888.
- uint32_t packedColor = 0u;
- uint8_t* __restrict__ packedColorBuffer = reinterpret_cast<uint8_t*>(&packedColor);
-
- // Color is pre-muliplied with its alpha.
- *(packedColorBuffer + 3u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 3u), currentAlpha);
- *(packedColorBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), currentAlpha);
- *(packedColorBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), currentAlpha);
- *(packedColorBuffer) = MultiplyAndNormalizeColor(*packedInputColorBuffer, currentAlpha);
-
- // Set the color into the final pixel buffer.
- currentColor = packedColor;
- }
- }
- }
-
- bitmapBuffer += data.width;
-
- END_GLYPH_SCANLINE_DECODE(data);
- }
- }
-
- END_GLYPH_BITMAP();
- }
- else // Pixel::L8
- {
- // Below codes required only if not color glyph.
- if(!isColorGlyph)
- {
- uint8_t* __restrict__ bitmapBuffer = data.bitmapBuffer.GetBuffer();
- // Skip basic line.
- bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast<int32_t>(data.width);
-
- // Prepare glyph bitmap
- BEGIN_GLYPH_BITMAP(data);
-
- // Skip basic line of glyph.
- SKIP_GLYPH_SCANLINE(lineIndexRangeMin);
-
- // Traverse the pixels of the glyph line per line.
- for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
- {
- BEGIN_GLYPH_SCANLINE_DECODE(data);
-
- for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
- {
- const int32_t xOffsetIndex = xOffset + index;
-
- // Update the alpha channel.
- const uint8_t alpha = *(glyphScanline + index * glyphPixelSize + glyphAlphaIndex);
-
- // Copy non-transparent pixels only
- if(alpha > 0u)
- {
- // Check alpha of overlapped pixels
- uint8_t& currentAlpha = *(bitmapBuffer + xOffsetIndex);
-
- // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
- // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
- // semi-transparent gaps between joint glyphs with overlapped pixels, which could
- // happen, for example, in the RTL text when we copy glyphs from right to left).
- currentAlpha = std::max(currentAlpha, alpha);
- }
- }
-
- bitmapBuffer += data.width;
-
- END_GLYPH_SCANLINE_DECODE(data);
- }
-
- END_GLYPH_BITMAP();
- }
- }
-}
-
-/// Draws the background color to the buffer
-void DrawBackgroundColor(
- Vector4 backgroundColor,
- const uint32_t bufferWidth,
- const uint32_t bufferHeight,
- GlyphData& glyphData,
- const float baseline,
- const LineRun& line,
- const float lineExtentLeft,
- const float lineExtentRight)
-{
- const int32_t yRangeMin = std::max(0, static_cast<int32_t>(glyphData.verticalOffset + baseline - line.ascender));
- const int32_t yRangeMax = std::min(static_cast<int32_t>(bufferHeight), static_cast<int32_t>(glyphData.verticalOffset + baseline - line.descender));
- const int32_t xRangeMin = std::max(0, static_cast<int32_t>(glyphData.horizontalOffset + lineExtentLeft));
- const int32_t xRangeMax = std::min(static_cast<int32_t>(bufferWidth), static_cast<int32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
-
- // If current glyph don't need to be rendered, just ignore.
- if(yRangeMax <= yRangeMin || xRangeMax <= xRangeMin)
- {
- return;
- }
-
- // We can optimize by memset when backgroundColor.a is near zero
- uint8_t backgroundColorAlpha = static_cast<uint8_t>(backgroundColor.a * 255.f);
-
- uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
-
- // Skip yRangeMin line.
- bitmapBuffer += yRangeMin * glyphData.width;
-
- if(backgroundColorAlpha == 0)
- {
- for(int32_t y = yRangeMin; y < yRangeMax; y++)
- {
- // We can use memset.
- memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
- bitmapBuffer += glyphData.width;
- }
- }
- else
- {
- uint32_t packedBackgroundColor = 0u;
- uint8_t* packedBackgroundColorBuffer = reinterpret_cast<uint8_t*>(&packedBackgroundColor);
-
- // Write the color to the pixel buffer
- *(packedBackgroundColorBuffer + 3u) = backgroundColorAlpha;
- *(packedBackgroundColorBuffer + 2u) = static_cast<uint8_t>(backgroundColor.b * backgroundColorAlpha);
- *(packedBackgroundColorBuffer + 1u) = static_cast<uint8_t>(backgroundColor.g * backgroundColorAlpha);
- *(packedBackgroundColorBuffer) = static_cast<uint8_t>(backgroundColor.r * backgroundColorAlpha);
-
- for(int32_t y = yRangeMin; y < yRangeMax; y++)
- {
- for(int32_t x = xRangeMin; x < xRangeMax; x++)
- {
- // Note : this is same logic as bitmap[y][x] = backgroundColor;
- *(bitmapBuffer + x) = packedBackgroundColor;
- }
- bitmapBuffer += glyphData.width;
- }
- }
-}
-
-/// Draws the specified underline color to the buffer
-void DrawUnderline(
- const uint32_t bufferWidth,
- const uint32_t bufferHeight,
- GlyphData& glyphData,
- const float baseline,
- const float currentUnderlinePosition,
- const float maxUnderlineHeight,
- const float lineExtentLeft,
- const float lineExtentRight,
- const UnderlineStyleProperties& commonUnderlineProperties,
- const UnderlineStyleProperties& currentUnderlineProperties,
- const LineRun& line)
-{
- const Vector4& underlineColor = currentUnderlineProperties.colorDefined ? currentUnderlineProperties.color : commonUnderlineProperties.color;
- const Text::Underline::Type underlineType = currentUnderlineProperties.typeDefined ? currentUnderlineProperties.type : commonUnderlineProperties.type;
- const float dashedUnderlineWidth = currentUnderlineProperties.dashWidthDefined ? currentUnderlineProperties.dashWidth : commonUnderlineProperties.dashWidth;
- const float dashedUnderlineGap = currentUnderlineProperties.dashGapDefined ? currentUnderlineProperties.dashGap : commonUnderlineProperties.dashGap;
-
- int32_t underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
-
- const uint32_t yRangeMin = underlineYOffset;
- const uint32_t yRangeMax = std::min(bufferHeight, underlineYOffset + static_cast<uint32_t>(maxUnderlineHeight));
- const uint32_t xRangeMin = static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentLeft);
- const uint32_t xRangeMax = std::min(bufferWidth, static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
-
- // If current glyph don't need to be rendered, just ignore.
- if((underlineType != Text::Underline::DOUBLE && yRangeMax <= yRangeMin) || xRangeMax <= xRangeMin)
- {
- return;
- }
-
- // We can optimize by memset when underlineColor.a is near zero
- uint8_t underlineColorAlpha = static_cast<uint8_t>(underlineColor.a * 255.f);
-
- uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
-
- // Skip yRangeMin line.
- bitmapBuffer += yRangeMin * glyphData.width;
-
- // Note if underlineType is DASHED, we cannot setup color by memset.
- if(underlineType != Text::Underline::DASHED && underlineColorAlpha == 0)
- {
- for(uint32_t y = yRangeMin; y < yRangeMax; y++)
- {
- // We can use memset.
- memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
- bitmapBuffer += glyphData.width;
- }
- if(underlineType == Text::Underline::DOUBLE)
- {
- int32_t secondUnderlineYOffset = underlineYOffset - ONE_AND_A_HALF * maxUnderlineHeight;
- const uint32_t secondYRangeMin = static_cast<uint32_t>(std::max(0, secondUnderlineYOffset));
- const uint32_t secondYRangeMax = static_cast<uint32_t>(std::max(0, std::min(static_cast<int32_t>(bufferHeight), secondUnderlineYOffset + static_cast<int32_t>(maxUnderlineHeight))));
-
- // Rewind bitmapBuffer pointer, and skip secondYRangeMin line.
- bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer()) + yRangeMin * glyphData.width;
-
- for(uint32_t y = secondYRangeMin; y < secondYRangeMax; y++)
- {
- // We can use memset.
- memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
- bitmapBuffer += glyphData.width;
- }
- }
- }
- else
- {
- uint32_t packedUnderlineColor = 0u;
- uint8_t* packedUnderlineColorBuffer = reinterpret_cast<uint8_t*>(&packedUnderlineColor);
-
- // Write the color to the pixel buffer
- *(packedUnderlineColorBuffer + 3u) = underlineColorAlpha;
- *(packedUnderlineColorBuffer + 2u) = static_cast<uint8_t>(underlineColor.b * underlineColorAlpha);
- *(packedUnderlineColorBuffer + 1u) = static_cast<uint8_t>(underlineColor.g * underlineColorAlpha);
- *(packedUnderlineColorBuffer) = static_cast<uint8_t>(underlineColor.r * underlineColorAlpha);
-
- for(uint32_t y = yRangeMin; y < yRangeMax; y++)
- {
- if(underlineType == Text::Underline::DASHED)
- {
- float dashWidth = dashedUnderlineWidth;
- float dashGap = 0;
-
- for(uint32_t x = xRangeMin; x < xRangeMax; x++)
- {
- if(Dali::EqualsZero(dashGap) && dashWidth > 0)
- {
- // Note : this is same logic as bitmap[y][x] = underlineColor;
- *(bitmapBuffer + x) = packedUnderlineColor;
- dashWidth--;
- }
- else if(dashGap < dashedUnderlineGap)
- {
- dashGap++;
- }
- else
- {
- //reset
- dashWidth = dashedUnderlineWidth;
- dashGap = 0;
- }
- }
- }
- else
- {
- for(uint32_t x = xRangeMin; x < xRangeMax; x++)
- {
- // Note : this is same logic as bitmap[y][x] = underlineColor;
- *(bitmapBuffer + x) = packedUnderlineColor;
- }
- }
- bitmapBuffer += glyphData.width;
- }
- if(underlineType == Text::Underline::DOUBLE)
- {
- int32_t secondUnderlineYOffset = underlineYOffset - ONE_AND_A_HALF * maxUnderlineHeight;
- const uint32_t secondYRangeMin = static_cast<uint32_t>(std::max(0, secondUnderlineYOffset));
- const uint32_t secondYRangeMax = static_cast<uint32_t>(std::max(0, std::min(static_cast<int32_t>(bufferHeight), secondUnderlineYOffset + static_cast<int32_t>(maxUnderlineHeight))));
-
- // Rewind bitmapBuffer pointer, and skip secondYRangeMin line.
- bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer()) + yRangeMin * glyphData.width;
-
- for(uint32_t y = secondYRangeMin; y < secondYRangeMax; y++)
- {
- for(uint32_t x = xRangeMin; x < xRangeMax; x++)
- {
- // Note : this is same logic as bitmap[y][x] = underlineColor;
- *(bitmapBuffer + x) = packedUnderlineColor;
- }
- bitmapBuffer += glyphData.width;
- }
- }
- }
-}
-
-/// Draws the specified strikethrough color to the buffer
-void DrawStrikethrough(const uint32_t bufferWidth,
- const uint32_t bufferHeight,
- GlyphData& glyphData,
- const float baseline,
- const float strikethroughStartingYPosition,
- const float maxStrikethroughHeight,
- const float lineExtentLeft,
- const float lineExtentRight,
- const StrikethroughStyleProperties& commonStrikethroughProperties,
- const StrikethroughStyleProperties& currentStrikethroughProperties,
- const LineRun& line)
-{
- const Vector4& strikethroughColor = currentStrikethroughProperties.colorDefined ? currentStrikethroughProperties.color : commonStrikethroughProperties.color;
-
- const uint32_t yRangeMin = static_cast<uint32_t>(strikethroughStartingYPosition);
- const uint32_t yRangeMax = std::min(bufferHeight, static_cast<uint32_t>(strikethroughStartingYPosition + maxStrikethroughHeight));
- const uint32_t xRangeMin = static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentLeft);
- const uint32_t xRangeMax = std::min(bufferWidth, static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
-
- // If current glyph don't need to be rendered, just ignore.
- if(yRangeMax <= yRangeMin || xRangeMax <= xRangeMin)
- {
- return;
- }
-
- // We can optimize by memset when strikethroughColor.a is near zero
- uint8_t strikethroughColorAlpha = static_cast<uint8_t>(strikethroughColor.a * 255.f);
-
- uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
-
- // Skip yRangeMin line.
- bitmapBuffer += yRangeMin * glyphData.width;
-
- if(strikethroughColorAlpha == 0)
- {
- for(uint32_t y = yRangeMin; y < yRangeMax; y++)
- {
- // We can use memset.
- memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
- bitmapBuffer += glyphData.width;
- }
- }
- else
- {
- uint32_t packedStrikethroughColor = 0u;
- uint8_t* packedStrikethroughColorBuffer = reinterpret_cast<uint8_t*>(&packedStrikethroughColor);
-
- // Write the color to the pixel buffer
- *(packedStrikethroughColorBuffer + 3u) = strikethroughColorAlpha;
- *(packedStrikethroughColorBuffer + 2u) = static_cast<uint8_t>(strikethroughColor.b * strikethroughColorAlpha);
- *(packedStrikethroughColorBuffer + 1u) = static_cast<uint8_t>(strikethroughColor.g * strikethroughColorAlpha);
- *(packedStrikethroughColorBuffer) = static_cast<uint8_t>(strikethroughColor.r * strikethroughColorAlpha);
-
- for(uint32_t y = yRangeMin; y < yRangeMax; y++)
- {
- for(uint32_t x = xRangeMin; x < xRangeMax; x++)
- {
- // Note : this is same logic as bitmap[y][x] = strikethroughColor;
- *(bitmapBuffer + x) = packedStrikethroughColor;
- }
- bitmapBuffer += glyphData.width;
- }
- }
-}
-
-/// Helper functions to create image buffer
-
-struct InputParameterForEachLine
-{
- const uint32_t bufferWidth;
- const uint32_t bufferHeight;
- const int32_t horizontalOffset;
-
- const Vector2& styleOffset; ///< If style is STYLE_OUTLINE, outline offset. If style is STYLE_SHADOW, shadow offset. Otherwise, zero.
-
- const GlyphIndex fromGlyphIndex;
- const GlyphIndex toGlyphIndex;
-
- // Elide text info
- const GlyphIndex startIndexOfGlyphs;
- const GlyphIndex endIndexOfGlyphs;
- const GlyphIndex firstMiddleIndexOfElidedGlyphs;
- const GlyphIndex secondMiddleIndexOfElidedGlyphs;
-
- const DevelText::VerticalLineAlignment::Type verticalLineAlignType;
- const DevelText::EllipsisPosition::Type ellipsisPosition;
-
- const GlyphInfo* __restrict__ hyphens;
- const Length* __restrict__ hyphenIndices;
- const Length hyphensCount;
-
- const bool ignoreHorizontalAlignment : 1;
-};
-
-struct InputParameterForEachGlyph
-{
- const Typesetter::Style style;
- const Pixel::Format pixelFormat;
-
- const float outlineWidth;
-
- const float modelCharacterSpacing;
-
- const Vector4& defaultColor; ///< The default color for the text.
- /// Or some color which depends on style value. (e.g. ShadowColor if style is STYLE_SHADOW)
-
- const Vector<UnderlinedGlyphRun>& underlineRuns;
- const Vector<StrikethroughGlyphRun>& strikethroughRuns;
- const Vector<CharacterSpacingGlyphRun>& characterSpacingGlyphRuns;
-
- const GlyphInfo* const __restrict__ glyphsBuffer;
- const Character* __restrict__ textBuffer;
- const CharacterIndex* __restrict__ glyphToCharacterMapBuffer;
-
- const Vector2* const __restrict__ positionBuffer;
-
- const Vector4* const __restrict__ colorsBuffer;
- const TextAbstraction::ColorIndex* const __restrict__ colorIndexBuffer;
-
- const UnderlineStyleProperties modelUnderlineProperties;
- const StrikethroughStyleProperties modelStrikethroughProperties;
-
- const bool underlineEnabled : 1;
- const bool strikethroughEnabled : 1;
- const bool cutoutEnabled : 1;
-
- const bool removeFrontInset : 1;
- const bool removeBackInset : 1;
-
- const bool useDefaultColor : 1;
-};
-
-struct OutputParameterForEachGlyph
-{
- UnderlineStyleProperties& currentUnderlineProperties;
-
- float& maxUnderlineHeight;
- bool& thereAreUnderlinedGlyphs;
-
- StrikethroughStyleProperties& currentStrikethroughProperties;
-
- float& maxStrikethroughHeight;
- bool& thereAreStrikethroughGlyphs;
-
- float& currentUnderlinePosition;
-
- float& baseline;
- float& lineExtentLeft;
- float& lineExtentRight;
-
- FontId& lastFontId;
-};
-
-void CreateImageBufferForEachGlyph(TextAbstraction::FontClient fontClient, GlyphData& glyphData, GlyphIndex& glyphIndex, const GlyphIndex elidedGlyphIndex, const GlyphInfo* glyphInfo, const bool addHyphen, const InputParameterForEachGlyph& inputParamsForGlyph, OutputParameterForEachGlyph& outputParamsForGlyph)
-{
- Vector<UnderlinedGlyphRun>::ConstIterator currentUnderlinedGlyphRunIt = inputParamsForGlyph.underlineRuns.End();
- const bool underlineGlyph = inputParamsForGlyph.underlineEnabled || IsGlyphUnderlined(glyphIndex, inputParamsForGlyph.underlineRuns, currentUnderlinedGlyphRunIt);
- outputParamsForGlyph.currentUnderlineProperties = GetCurrentUnderlineProperties(glyphIndex, underlineGlyph, inputParamsForGlyph.underlineRuns, currentUnderlinedGlyphRunIt, inputParamsForGlyph.modelUnderlineProperties);
- float currentUnderlineHeight = outputParamsForGlyph.currentUnderlineProperties.height;
-
- outputParamsForGlyph.thereAreUnderlinedGlyphs = outputParamsForGlyph.thereAreUnderlinedGlyphs || underlineGlyph;
-
- Vector<StrikethroughGlyphRun>::ConstIterator currentStrikethroughGlyphRunIt = inputParamsForGlyph.strikethroughRuns.End();
- const bool strikethroughGlyph = inputParamsForGlyph.strikethroughEnabled || IsGlyphStrikethrough(glyphIndex, inputParamsForGlyph.strikethroughRuns, currentStrikethroughGlyphRunIt);
- outputParamsForGlyph.currentStrikethroughProperties = GetCurrentStrikethroughProperties(glyphIndex, strikethroughGlyph, inputParamsForGlyph.strikethroughRuns, currentStrikethroughGlyphRunIt, inputParamsForGlyph.modelStrikethroughProperties);
- float currentStrikethroughHeight = outputParamsForGlyph.currentStrikethroughProperties.height;
-
- outputParamsForGlyph.thereAreStrikethroughGlyphs = outputParamsForGlyph.thereAreStrikethroughGlyphs || strikethroughGlyph;
-
- // Are we still using the same fontId as previous
- if((glyphInfo->fontId != outputParamsForGlyph.lastFontId) && (strikethroughGlyph || underlineGlyph))
- {
- // We need to fetch fresh font underline metrics
- FontMetrics fontMetrics;
- fontClient.GetFontMetrics(glyphInfo->fontId, fontMetrics);
-
- //The currentUnderlinePosition will be used for both Underline and/or Strikethrough
- outputParamsForGlyph.currentUnderlinePosition = FetchUnderlinePositionFromFontMetrics(fontMetrics);
-
- if(underlineGlyph)
- {
- CalcualteUnderlineHeight(fontMetrics, currentUnderlineHeight, outputParamsForGlyph.maxUnderlineHeight);
- }
-
- if(strikethroughGlyph)
- {
- CalcualteStrikethroughHeight(currentStrikethroughHeight, outputParamsForGlyph.maxStrikethroughHeight);
- }
-
- // Update lastFontId because fontId is changed
- outputParamsForGlyph.lastFontId = glyphInfo->fontId; // Prevents searching for existing blocksizes when string of the same fontId.
- }
-
- // Retrieves the glyph's position.
- Vector2 position = *(inputParamsForGlyph.positionBuffer + elidedGlyphIndex);
-
- if(addHyphen)
- {
- GlyphInfo tempInfo = *(inputParamsForGlyph.glyphsBuffer + elidedGlyphIndex);
- const float characterSpacing = GetGlyphCharacterSpacing(glyphIndex, inputParamsForGlyph.characterSpacingGlyphRuns, inputParamsForGlyph.modelCharacterSpacing);
- const float calculatedAdvance = GetCalculatedAdvance(*(inputParamsForGlyph.textBuffer + (*(inputParamsForGlyph.glyphToCharacterMapBuffer + elidedGlyphIndex))), characterSpacing, tempInfo.advance);
- position.x = position.x + calculatedAdvance - tempInfo.xBearing + glyphInfo->xBearing;
- position.y = -glyphInfo->yBearing;
- }
-
- if(outputParamsForGlyph.baseline < position.y + glyphInfo->yBearing)
- {
- outputParamsForGlyph.baseline = position.y + glyphInfo->yBearing;
- }
-
- // Calculate the positions of leftmost and rightmost glyphs in the current line
- if(inputParamsForGlyph.removeFrontInset)
- {
- if(position.x < outputParamsForGlyph.lineExtentLeft)
- {
- outputParamsForGlyph.lineExtentLeft = position.x;
- }
- }
- else
- {
- const float originPositionLeft = position.x - glyphInfo->xBearing;
- if(originPositionLeft < outputParamsForGlyph.lineExtentLeft)
- {
- outputParamsForGlyph.lineExtentLeft = originPositionLeft;
- }
- }
-
- if(inputParamsForGlyph.removeBackInset)
- {
- if(position.x + glyphInfo->width > outputParamsForGlyph.lineExtentRight)
- {
- outputParamsForGlyph.lineExtentRight = position.x + glyphInfo->width;
- }
- }
- else
- {
- const float originPositionRight = position.x - glyphInfo->xBearing + glyphInfo->advance;
- if(originPositionRight > outputParamsForGlyph.lineExtentRight)
- {
- outputParamsForGlyph.lineExtentRight = originPositionRight;
- }
- }
-
- // Retrieves the glyph's color.
- const ColorIndex colorIndex = inputParamsForGlyph.useDefaultColor ? 0u : *(inputParamsForGlyph.colorIndexBuffer + glyphIndex);
-
- Vector4 color;
- if(inputParamsForGlyph.style == Typesetter::STYLE_SHADOW)
- {
- color = inputParamsForGlyph.defaultColor;
- }
- else if(inputParamsForGlyph.style == Typesetter::STYLE_OUTLINE)
- {
- color = inputParamsForGlyph.defaultColor;
- }
- else
- {
- color = (inputParamsForGlyph.useDefaultColor || (0u == colorIndex)) ? inputParamsForGlyph.defaultColor : *(inputParamsForGlyph.colorsBuffer + (colorIndex - 1u));
- }
-
- if(inputParamsForGlyph.style == Typesetter::STYLE_NONE && inputParamsForGlyph.cutoutEnabled)
- {
- // Temporarily adjust the transparency to 1.f
- color.a = 1.f;
- }
-
- // Premultiply alpha
- color.r *= color.a;
- color.g *= color.a;
- color.b *= color.a;
-
- // Retrieves the glyph's bitmap.
- glyphData.glyphBitmap.buffer = nullptr;
- glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height.
- glyphData.glyphBitmap.height = glyphInfo->height;
-
- float outlineWidth = inputParamsForGlyph.outlineWidth;
-
- if(inputParamsForGlyph.style != Typesetter::STYLE_OUTLINE && inputParamsForGlyph.style != Typesetter::STYLE_SHADOW)
- {
- // Don't render outline for other styles
- outlineWidth = 0.0f;
- }
-
- if(inputParamsForGlyph.style != Typesetter::STYLE_UNDERLINE && inputParamsForGlyph.style != Typesetter::STYLE_STRIKETHROUGH)
- {
- fontClient.CreateBitmap(glyphInfo->fontId,
- glyphInfo->index,
- glyphInfo->isItalicRequired,
- glyphInfo->isBoldRequired,
- glyphData.glyphBitmap,
- static_cast<int32_t>(outlineWidth));
- }
-
- // Sets the glyph's bitmap into the bitmap of the whole text.
- if(nullptr != glyphData.glyphBitmap.buffer)
- {
- if(inputParamsForGlyph.style == Typesetter::STYLE_OUTLINE)
- {
- // Set the position offset for the current glyph
- glyphData.horizontalOffset -= glyphData.glyphBitmap.outlineOffsetX;
- glyphData.verticalOffset -= glyphData.glyphBitmap.outlineOffsetY;
- }
-
- // Set the buffer of the glyph's bitmap into the final bitmap's buffer
- TypesetGlyph(glyphData,
- &position,
- &color,
- inputParamsForGlyph.style,
- inputParamsForGlyph.pixelFormat);
-
- if(inputParamsForGlyph.style == Typesetter::STYLE_OUTLINE)
- {
- // Reset the position offset for the next glyph
- glyphData.horizontalOffset += glyphData.glyphBitmap.outlineOffsetX;
- glyphData.verticalOffset += glyphData.glyphBitmap.outlineOffsetY;
- }
-
- // free the glyphBitmap.buffer if it is owner of buffer
- if(glyphData.glyphBitmap.isBufferOwned)
- {
- free(glyphData.glyphBitmap.buffer);
- glyphData.glyphBitmap.isBufferOwned = false;
- }
- glyphData.glyphBitmap.buffer = nullptr;
- }
-}
-
-void CreateImageBufferForEachLine(TextAbstraction::FontClient fontClient, GlyphData& glyphData, Length& hyphenIndex, const LineRun& line, const bool isFirstLine, const InputParameterForEachLine& inputParamsForLine, const InputParameterForEachGlyph& inputParamsForGlyph)
-{
- // Sets the horizontal offset of the line.
- glyphData.horizontalOffset = inputParamsForLine.ignoreHorizontalAlignment ? 0 : static_cast<int32_t>(line.alignmentOffset);
- glyphData.horizontalOffset += inputParamsForLine.horizontalOffset;
-
- // Increases the vertical offset with the line's ascender.
- glyphData.verticalOffset += static_cast<int32_t>(line.ascender + GetPreOffsetVerticalLineAlignment(line, inputParamsForLine.verticalLineAlignType));
-
- if(inputParamsForGlyph.style == Typesetter::STYLE_OUTLINE)
- {
- glyphData.horizontalOffset -= inputParamsForGlyph.outlineWidth;
- glyphData.horizontalOffset += inputParamsForLine.styleOffset.x;
- if(isFirstLine)
- {
- // Only need to add the vertical outline offset for the first line
- glyphData.verticalOffset -= inputParamsForGlyph.outlineWidth;
- glyphData.verticalOffset += inputParamsForLine.styleOffset.y;
- }
- }
- else if(inputParamsForGlyph.style == Typesetter::STYLE_SHADOW)
- {
- glyphData.horizontalOffset += inputParamsForLine.styleOffset.x - inputParamsForGlyph.outlineWidth; // if outline enabled then shadow should offset from outline
-
- if(isFirstLine)
- {
- // Only need to add the vertical shadow offset for first line
- glyphData.verticalOffset += inputParamsForLine.styleOffset.y - inputParamsForGlyph.outlineWidth;
- }
- }
-
- bool thereAreUnderlinedGlyphs = false;
- bool thereAreStrikethroughGlyphs = false;
-
- float currentUnderlinePosition = 0.0f;
- auto currentUnderlineProperties = inputParamsForGlyph.modelUnderlineProperties;
- float maxUnderlineHeight = currentUnderlineProperties.height;
-
- auto currentStrikethroughProperties = inputParamsForGlyph.modelStrikethroughProperties;
- float maxStrikethroughHeight = currentStrikethroughProperties.height;
-
- FontId lastFontId = 0;
-
- float lineExtentLeft = inputParamsForLine.bufferWidth;
- float lineExtentRight = 0.0f;
- float baseline = 0.0f;
- bool addHyphen = false;
-
- // Traverses the glyphs of the line.
- const GlyphIndex startGlyphIndex = std::max(std::max(line.glyphRun.glyphIndex, inputParamsForLine.startIndexOfGlyphs), inputParamsForLine.fromGlyphIndex);
- GlyphIndex endGlyphIndex = (line.isSplitToTwoHalves ? line.glyphRunSecondHalf.glyphIndex + line.glyphRunSecondHalf.numberOfGlyphs : line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs) - 1u;
- endGlyphIndex = std::min(std::min(endGlyphIndex, inputParamsForLine.endIndexOfGlyphs), inputParamsForLine.toGlyphIndex);
-
- for(GlyphIndex glyphIndex = startGlyphIndex; glyphIndex <= endGlyphIndex; ++glyphIndex)
- {
- //To handle START case of ellipsis, the first glyph has been shifted
- //glyphIndex represent indices in whole glyphs but elidedGlyphIndex represents indices in elided Glyphs
- GlyphIndex elidedGlyphIndex = glyphIndex - inputParamsForLine.startIndexOfGlyphs;
-
- //To handle MIDDLE case of ellipsis, the first glyph in the second half of line has been shifted and skip the removed glyph from middle.
- if(inputParamsForLine.ellipsisPosition == DevelText::EllipsisPosition::MIDDLE)
- {
- if(glyphIndex > inputParamsForLine.firstMiddleIndexOfElidedGlyphs &&
- glyphIndex < inputParamsForLine.secondMiddleIndexOfElidedGlyphs)
- {
- // Ignore any glyph that removed for MIDDLE ellipsis
- continue;
- }
- if(glyphIndex >= inputParamsForLine.secondMiddleIndexOfElidedGlyphs)
- {
- elidedGlyphIndex -= (inputParamsForLine.secondMiddleIndexOfElidedGlyphs - inputParamsForLine.firstMiddleIndexOfElidedGlyphs - 1u);
- }
- }
-
- // Retrieve the glyph's info.
- const GlyphInfo* glyphInfo;
-
- if(addHyphen && inputParamsForLine.hyphens)
- {
- glyphInfo = inputParamsForLine.hyphens + hyphenIndex;
- hyphenIndex++;
- }
- else
- {
- glyphInfo = inputParamsForGlyph.glyphsBuffer + elidedGlyphIndex;
- }
-
- if((glyphInfo->width < Math::MACHINE_EPSILON_1000) ||
- (glyphInfo->height < Math::MACHINE_EPSILON_1000))
- {
- // Nothing to do if the glyph's width or height is zero.
- continue;
- }
-
- // Collect output l-values
- // clang-format off
- OutputParameterForEachGlyph outputParamsForGlyph{currentUnderlineProperties,
-
- maxUnderlineHeight,
- thereAreUnderlinedGlyphs,
-
- currentStrikethroughProperties,
-
- maxStrikethroughHeight,
- thereAreStrikethroughGlyphs,
-
- currentUnderlinePosition,
-
- baseline,
- lineExtentLeft,
- lineExtentRight,
-
- lastFontId};
- // clang-format on
-
- CreateImageBufferForEachGlyph(fontClient, glyphData, glyphIndex, elidedGlyphIndex, glyphInfo, addHyphen, inputParamsForGlyph, outputParamsForGlyph);
-
- if(inputParamsForLine.hyphenIndices)
- {
- while((hyphenIndex < inputParamsForLine.hyphensCount) && (glyphIndex > inputParamsForLine.hyphenIndices[hyphenIndex]))
- {
- hyphenIndex++;
- }
-
- addHyphen = ((hyphenIndex < inputParamsForLine.hyphensCount) && ((glyphIndex + 1) == inputParamsForLine.hyphenIndices[hyphenIndex]));
- if(addHyphen)
- {
- glyphIndex--;
- }
- }
- }
-
- // Draw the underline from the leftmost glyph to the rightmost glyph
- if(thereAreUnderlinedGlyphs && inputParamsForGlyph.style == Typesetter::STYLE_UNDERLINE)
- {
- DrawUnderline(inputParamsForLine.bufferWidth, inputParamsForLine.bufferHeight, glyphData, baseline, currentUnderlinePosition, maxUnderlineHeight, lineExtentLeft, lineExtentRight, inputParamsForGlyph.modelUnderlineProperties, currentUnderlineProperties, line);
- }
-
- // Draw the background color from the leftmost glyph to the rightmost glyph
- if(inputParamsForGlyph.style == Typesetter::STYLE_BACKGROUND)
- {
- DrawBackgroundColor(inputParamsForGlyph.defaultColor, inputParamsForLine.bufferWidth, inputParamsForLine.bufferHeight, glyphData, baseline, line, lineExtentLeft, lineExtentRight);
- }
-
- // Draw the strikethrough from the leftmost glyph to the rightmost glyph
- if(thereAreStrikethroughGlyphs && inputParamsForGlyph.style == Typesetter::STYLE_STRIKETHROUGH)
- {
- //TODO : The currently implemented strikethrough creates a strikethrough on the line level. We need to create different strikethroughs the case of glyphs with different sizes.
- const float strikethroughStartingYPosition = (glyphData.verticalOffset + baseline + currentUnderlinePosition) - ((line.ascender) * HALF); // Since Free Type font doesn't contain the strikethrough-position property, strikethrough position will be calculated by moving the underline position upwards by half the value of the line height.
- DrawStrikethrough(inputParamsForLine.bufferWidth, inputParamsForLine.bufferHeight, glyphData, baseline, strikethroughStartingYPosition, maxStrikethroughHeight, lineExtentLeft, lineExtentRight, inputParamsForGlyph.modelStrikethroughProperties, currentStrikethroughProperties, line);
- }
-
- // Increases the vertical offset with the line's descender & line spacing.
- glyphData.verticalOffset += static_cast<int32_t>(-line.descender + GetPostOffsetVerticalLineAlignment(line, inputParamsForLine.verticalLineAlignType));
-}
-
-/// Helper functions to create image buffer end
-
-/**
- * @brief Create an initialized image buffer filled with transparent color.
- *
- * Creates the pixel data used to generate the final image with the given size.
- *
- * @param[in] bufferWidth The width of the image buffer.
- * @param[in] bufferHeight The height of the image buffer.
- * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
- *
- * @return An image buffer.
- */
-inline Devel::PixelBuffer CreateTransparentImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Pixel::Format pixelFormat)
-{
- Devel::PixelBuffer imageBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat);
-
- if(Pixel::RGBA8888 == pixelFormat)
- {
- const uint32_t bufferSizeInt = bufferWidth * bufferHeight;
- const size_t bufferSizeChar = sizeof(uint32_t) * static_cast<std::size_t>(bufferSizeInt);
- memset(imageBuffer.GetBuffer(), 0, bufferSizeChar);
- }
- else
- {
- memset(imageBuffer.GetBuffer(), 0, static_cast<std::size_t>(bufferWidth * bufferHeight));
- }
-
- return imageBuffer;
-}
-
-} // namespace
-
-ViewModel* Typesetter::Impl::GetViewModel()
-{
- return mModel.get();
-}
-
-void Typesetter::Impl::SetFontClient(TextAbstraction::FontClient& fontClient)
-{
- mFontClient = fontClient;
-}
-
-TextAbstraction::FontClient& Typesetter::Impl::GetFontClient()
-{
- return mFontClient;
-}
-
-Devel::PixelBuffer Typesetter::Impl::CreateTransparentImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Pixel::Format pixelFormat)
-{
- return Dali::Toolkit::Text::CreateTransparentImageBuffer(bufferWidth, bufferHeight, pixelFormat);
-}
-
-void Typesetter::Impl::DrawGlyphsBackground(Devel::PixelBuffer& buffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const int32_t horizontalOffset, const int32_t verticalOffset)
-{
- // Use l-value to make ensure it is not nullptr, so compiler happy.
- auto& viewModel = *(mModel.get());
-
- // Retrieve lines, glyphs, positions and colors from the view model.
- const Length modelNumberOfLines = viewModel.GetNumberOfLines();
- const LineRun* const modelLinesBuffer = viewModel.GetLines();
- const Length numberOfGlyphs = viewModel.GetNumberOfGlyphs();
- const GlyphInfo* const glyphsBuffer = viewModel.GetGlyphs();
- const Vector2* const positionBuffer = viewModel.GetLayout();
- const Vector4* const backgroundColorsBuffer = viewModel.GetBackgroundColors();
- const ColorIndex* const backgroundColorIndicesBuffer = viewModel.GetBackgroundColorIndices();
- const bool removeFrontInset = viewModel.IsRemoveFrontInset();
- const bool removeBackInset = viewModel.IsRemoveBackInset();
-
- const DevelText::VerticalLineAlignment::Type verticalLineAlignType = viewModel.GetVerticalLineAlignment();
-
- // Create and initialize the pixel buffer.
- GlyphData glyphData;
- glyphData.verticalOffset = verticalOffset;
- glyphData.width = bufferWidth;
- glyphData.height = bufferHeight;
- glyphData.bitmapBuffer = buffer;
- glyphData.horizontalOffset = 0;
-
- ColorIndex prevBackgroundColorIndex = 0;
- ColorIndex backgroundColorIndex = 0;
-
- // Traverses the lines of the text.
- for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex)
- {
- const LineRun& line = *(modelLinesBuffer + lineIndex);
-
- // Sets the horizontal offset of the line.
- glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int32_t>(line.alignmentOffset);
- glyphData.horizontalOffset += horizontalOffset;
-
- // Increases the vertical offset with the line's ascender.
- glyphData.verticalOffset += static_cast<int32_t>(line.ascender + GetPreOffsetVerticalLineAlignment(line, verticalLineAlignType));
-
- float left = bufferWidth;
- float right = 0.0f;
- float baseline = 0.0f;
-
- // Traverses the glyphs of the line.
- const GlyphIndex endGlyphIndex = std::min(numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs);
- for(GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex)
- {
- // Retrieve the glyph's info.
- const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
-
- if((glyphInfo->width < Math::MACHINE_EPSILON_1000) ||
- (glyphInfo->height < Math::MACHINE_EPSILON_1000))
- {
- // Nothing to do if default background color, the glyph's width or height is zero.
- continue;
- }
-
- backgroundColorIndex = (nullptr == backgroundColorsBuffer) ? 0u : *(backgroundColorIndicesBuffer + glyphIndex);
-
- if((backgroundColorIndex != prevBackgroundColorIndex) &&
- (prevBackgroundColorIndex != 0u))
- {
- const Vector4& backgroundColor = *(backgroundColorsBuffer + prevBackgroundColorIndex - 1u);
- DrawBackgroundColor(backgroundColor, bufferWidth, bufferHeight, glyphData, baseline, line, left, right);
- }
-
- if(backgroundColorIndex == 0u)
- {
- prevBackgroundColorIndex = backgroundColorIndex;
- //if background color is the default do nothing
- continue;
- }
-
- // Retrieves the glyph's position.
- const Vector2* const position = positionBuffer + glyphIndex;
-
- if(baseline < position->y + glyphInfo->yBearing)
- {
- baseline = position->y + glyphInfo->yBearing;
- }
-
- // Calculate the positions of leftmost and rightmost glyphs in the current line
- if(removeFrontInset)
- {
- if((position->x < left) || (backgroundColorIndex != prevBackgroundColorIndex))
- {
- left = position->x;
- }
- }
- else
- {
- const float originPositionLeft = position->x - glyphInfo->xBearing;
- if((originPositionLeft < left) || (backgroundColorIndex != prevBackgroundColorIndex))
- {
- left = originPositionLeft;
- }
- }
-
- if(removeBackInset)
- {
- if(position->x + glyphInfo->width > right)
- {
- right = position->x + glyphInfo->width;
- }
- }
- else
- {
- const float originPositionRight = position->x - glyphInfo->xBearing + glyphInfo->advance;
- if(originPositionRight > right)
- {
- right = originPositionRight;
- }
- }
-
- prevBackgroundColorIndex = backgroundColorIndex;
- }
-
- //draw last background at line end if not default
- if(backgroundColorIndex != 0u)
- {
- const Vector4& backgroundColor = *(backgroundColorsBuffer + backgroundColorIndex - 1u);
- DrawBackgroundColor(backgroundColor, bufferWidth, bufferHeight, glyphData, baseline, line, left, right);
- }
-
- // Increases the vertical offset with the line's descender.
- glyphData.verticalOffset += static_cast<int32_t>(-line.descender + GetPostOffsetVerticalLineAlignment(line, verticalLineAlignType));
- }
-}
-
-Devel::PixelBuffer Typesetter::Impl::CreateImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Typesetter::Style style, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset, const GlyphIndex fromGlyphIndex, const GlyphIndex toGlyphIndex)
-{
- // Use l-value to make ensure it is not nullptr, so compiler happy.
- auto& viewModel = *(mModel.get());
-
- // Retrieve lines, glyphs, positions and colors from the view model.
- const Length modelNumberOfLines = viewModel.GetNumberOfLines();
- const LineRun* const __restrict__ modelLinesBuffer = viewModel.GetLines();
- const GlyphInfo* const __restrict__ glyphsBuffer = viewModel.GetGlyphs();
- const Vector2* const __restrict__ positionBuffer = viewModel.GetLayout();
- const Vector4* const __restrict__ colorsBuffer = viewModel.GetColors();
- const ColorIndex* const __restrict__ colorIndexBuffer = viewModel.GetColorIndices();
- const GlyphInfo* __restrict__ hyphens = viewModel.GetHyphens();
- const Length* __restrict__ hyphenIndices = viewModel.GetHyphenIndices();
- const Length hyphensCount = viewModel.GetHyphensCount();
-
- // Create and initialize the pixel buffer.
- GlyphData glyphData;
- glyphData.verticalOffset = verticalOffset;
- glyphData.width = bufferWidth;
- glyphData.height = bufferHeight;
- glyphData.bitmapBuffer = CreateTransparentImageBuffer(bufferWidth, bufferHeight, pixelFormat);
- glyphData.horizontalOffset = 0;
-
- Length hyphenIndex = 0;
-
- const Character* __restrict__ textBuffer = viewModel.GetTextBuffer();
- const Vector<CharacterIndex>& __restrict__ glyphToCharacterMap = viewModel.GetGlyphsToCharacters();
- const CharacterIndex* __restrict__ glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
-
- // Get the underline runs.
- const Length numberOfUnderlineRuns = viewModel.GetNumberOfUnderlineRuns();
- Vector<UnderlinedGlyphRun> underlineRuns;
- underlineRuns.Resize(numberOfUnderlineRuns);
- viewModel.GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
-
- // Get the strikethrough runs.
- const Length numberOfStrikethroughRuns = viewModel.GetNumberOfStrikethroughRuns();
- Vector<StrikethroughGlyphRun> strikethroughRuns;
- strikethroughRuns.Resize(numberOfStrikethroughRuns);
- viewModel.GetStrikethroughRuns(strikethroughRuns.Begin(), 0u, numberOfStrikethroughRuns);
-
- // Get the character-spacing runs.
- const Vector<CharacterSpacingGlyphRun>& __restrict__ characterSpacingGlyphRuns = viewModel.GetCharacterSpacingGlyphRuns();
-
- // clang-format off
- // Aggregate input parameter for each line from mModel
- const InputParameterForEachLine inputParamsForLine{bufferWidth,
- bufferHeight,
- horizontalOffset,
-
- (style == Typesetter::STYLE_OUTLINE) ? viewModel.GetOutlineOffset() :
- (style == Typesetter::STYLE_SHADOW) ? viewModel.GetShadowOffset() :
- Vector2::ZERO,
-
- fromGlyphIndex,
- toGlyphIndex,
-
- // Elided text info. Indices according to elided text and Ellipsis position.
- viewModel.GetStartIndexOfElidedGlyphs(),
- viewModel.GetEndIndexOfElidedGlyphs(),
- viewModel.GetFirstMiddleIndexOfElidedGlyphs(),
- viewModel.GetSecondMiddleIndexOfElidedGlyphs(),
-
- viewModel.GetVerticalLineAlignment(),
- viewModel.GetEllipsisPosition(),
-
- hyphens,
- hyphenIndices,
- hyphensCount,
-
- ignoreHorizontalAlignment};
-
- // Aggregate underline-style-properties from mModel
- const UnderlineStyleProperties modelUnderlineProperties{viewModel.GetUnderlineType(),
- viewModel.GetUnderlineColor(),
- viewModel.GetUnderlineHeight(),
- viewModel.GetDashedUnderlineGap(),
- viewModel.GetDashedUnderlineWidth(),
- true,
- true,
- true,
- true,
- true};
-
- // Aggregate strikethrough-style-properties from mModel
- const StrikethroughStyleProperties modelStrikethroughProperties{viewModel.GetStrikethroughColor(),
- viewModel.GetStrikethroughHeight(),
- true,
- true};
-
-
- // Aggregate input parameter for each glyph from mModel
- const InputParameterForEachGlyph inputParamsForGlyph{style,
- pixelFormat,
-
- // Retrieves the glyph's outline width
- static_cast<float>(viewModel.GetOutlineWidth()),
-
- viewModel.GetCharacterSpacing(),
-
- (style == Typesetter::STYLE_OUTLINE) ? viewModel.GetOutlineColor() :
- (style == Typesetter::STYLE_SHADOW) ? viewModel.GetShadowColor() :
- (style == Typesetter::STYLE_BACKGROUND) ? viewModel.GetBackgroundColor() :
- viewModel.GetDefaultColor(),
-
- underlineRuns,
- strikethroughRuns,
- characterSpacingGlyphRuns,
-
- glyphsBuffer,
- textBuffer,
- glyphToCharacterMapBuffer,
-
- positionBuffer,
-
- colorsBuffer,
- colorIndexBuffer,
-
- modelUnderlineProperties,
- modelStrikethroughProperties,
-
- viewModel.IsUnderlineEnabled(),
- viewModel.IsStrikethroughEnabled(),
- viewModel.IsCutoutEnabled(),
-
- viewModel.IsRemoveFrontInset(),
- viewModel.IsRemoveBackInset(),
-
- // Whether to use the default color.
- (nullptr == colorsBuffer)};
- // clang-format on
-
- // Traverses the lines of the text.
- for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex)
- {
- const LineRun& line = *(modelLinesBuffer + lineIndex);
- CreateImageBufferForEachLine(mFontClient, glyphData, hyphenIndex, line, (lineIndex == 0u), inputParamsForLine, inputParamsForGlyph);
- }
-
- return glyphData.bitmapBuffer;
-}
-
-Typesetter::Impl::Impl(const ModelInterface* const model)
-: mModel(std::make_unique<ViewModel>(model))
-{
- // Default font client set.
- mFontClient = TextAbstraction::FontClient::Get();
-}
-
-Typesetter::Impl::~Impl() = default;
-
-} // namespace Text
-
-} // namespace Toolkit
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_TOOLKIT_TEXT_TYPESETTER_IMPL_H
-#define DALI_TOOLKIT_TEXT_TYPESETTER_IMPL_H
-
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
-#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
-#include <dali/devel-api/text-abstraction/font-client.h>
-#include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
-#include <dali/public-api/common/intrusive-ptr.h>
-#include <dali/public-api/images/pixel.h>
-#include <dali/public-api/object/ref-object.h>
-#include <memory> ///< for std::unique_ptr
-
-// INTERNAL INCLUDES
-#include <dali-toolkit/internal/text/rendering/text-typesetter.h>
-
-namespace Dali
-{
-namespace Toolkit
-{
-namespace Text
-{
-class ModelInterface;
-class ViewModel;
-
-/**
- * @brief This class is seperated logics for TypeSetter.
- * It will reduce the complexicy of typesetter logic.
- */
-struct Typesetter::Impl
-{
-public:
- /**
- * @brief Create an initialized image buffer filled with transparent color.
- *
- * Creates the pixel data used to generate the final image with the given size.
- *
- * @param[in] bufferWidth The width of the image buffer.
- * @param[in] bufferHeight The height of the image buffer.
- * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
- *
- * @return An image buffer.
- */
- static Devel::PixelBuffer CreateTransparentImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Pixel::Format pixelFormat);
-
-public: // Constructor & Destructor
- /**
- * @brief Creates a Typesetter impl instance.
- */
- Impl(const ModelInterface* const model);
-
- ~Impl();
-
-public:
- /**
- * @brief Retrieves the pointer to the view model.
- *
- * @return A pointer to the view model.
- */
- ViewModel* GetViewModel();
-
- /**
- * @brief Set the font client.
- *
- * Set the font client used in the update/render process of the text model.
- *
- * @param[in] fontClient The font client used by the Typesetter.
- */
- void SetFontClient(TextAbstraction::FontClient& fontClient);
-
- /**
- * @brief Get the font client.
- *
- * @return The font client used by the Typesetter.
- */
- TextAbstraction::FontClient& GetFontClient();
-
-public: // Image buffer creation
- void DrawGlyphsBackground(Devel::PixelBuffer& buffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const int32_t horizontalOffset, const int32_t verticalOffset);
-
- /**
- * @brief Create & draw the image buffer for the given range of the glyphs in the given style.
- *
- * Does the following operations:
- * - Retrieves the data buffers from the text model.
- * - Creates the pixel data used to generate the final image with the given size.
- * - Traverse the visible glyphs, retrieve their bitmaps and compose the final pixel data.
- *
- * @param[in] bufferWidth The width of the image buffer.
- * @param[in] bufferHeight The height of the image buffer.
- * @param[in] style The style of the text.
- * @param[in] ignoreHorizontalAlignment Whether to ignore the horizontal alignment, not ignored by default.
- * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
- * @param[in] horizontalOffset The horizontal offset to be added to the glyph's position.
- * @param[in] verticalOffset The vertical offset to be added to the glyph's position.
- * @param[in] fromGlyphIndex The index of the first glyph within the text to be drawn
- * @param[in] toGlyphIndex The index of the last glyph within the text to be drawn
- *
- * @return An image buffer with the text.
- */
- Devel::PixelBuffer CreateImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Typesetter::Style style, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset, const TextAbstraction::GlyphIndex fromGlyphIndex, const TextAbstraction::GlyphIndex toGlyphIndex);
-
-private:
- std::unique_ptr<ViewModel> mModel;
- TextAbstraction::FontClient mFontClient;
-};
-
-} // namespace Text
-
-} // namespace Toolkit
-
-} // namespace Dali
-
-#endif // DALI_TOOLKIT_TEXT_TYPESETTER_IMPL_H
#include <dali-toolkit/internal/text/rendering/text-typesetter.h>
// EXTERNAL INCLUDES
+#include <cmath>
#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/integration-api/debug.h>
#include <dali/integration-api/trace.h>
#include <dali/public-api/common/constants.h>
#include <dali/public-api/math/math-utils.h>
#include <memory.h>
-#include <cmath>
// INTERNAL INCLUDES
#include <dali-toolkit/devel-api/controls/text-controls/text-label-devel.h>
#include <dali-toolkit/internal/text/rendering/styles/character-spacing-helper-functions.h>
#include <dali-toolkit/internal/text/rendering/styles/strikethrough-helper-functions.h>
#include <dali-toolkit/internal/text/rendering/styles/underline-helper-functions.h>
-#include <dali-toolkit/internal/text/rendering/text-typesetter-impl.h>
#include <dali-toolkit/internal/text/rendering/view-model.h>
namespace Dali
{
DALI_INIT_TRACE_FILTER(gTraceFilter, DALI_TRACE_TEXT_PERFORMANCE_MARKER, false);
+const float HALF(0.5f);
+const float ONE_AND_A_HALF(1.5f);
+
/**
* @brief Fast multiply & divide by 255. It wiil be useful when we applying alpha value in color
*
const uint32_t xy1 = static_cast<const uint32_t>(x1) * y1;
const uint32_t xy2 = static_cast<const uint32_t>(x2) * y2;
const uint32_t res = std::min(65025u, xy1 + xy2); // 65025 is 255 * 255.
- return ((res + ((res + 257) >> 8)) >> 8); // fast divide by 255.
+ return ((res + ((res + 257) >> 8)) >> 8); // fast divide by 255.
+}
+
+/// Helper macro define for glyph typesetter. It will reduce some duplicated code line.
+// clang-format off
+/**
+ * @brief Prepare decode glyph bitmap data. It must be call END_GLYPH_BITMAP end of same scope.
+ */
+#define BEGIN_GLYPH_BITMAP(data) \
+{ \
+ uint32_t glyphOffet = 0u; \
+ const bool useLocalScanline = data.glyphBitmap.compressionType != TextAbstraction::GlyphBufferData::CompressionType::NO_COMPRESSION; \
+ uint8_t* __restrict__ glyphScanline = useLocalScanline ? (uint8_t*)malloc(data.glyphBitmap.width * glyphPixelSize) : data.glyphBitmap.buffer; \
+ DALI_ASSERT_ALWAYS(glyphScanline && "Glyph scanline for buffer is null!");
+
+/**
+ * @brief Macro to skip useless line fast.
+ */
+#define SKIP_GLYPH_SCANLINE(skipLine) \
+if(useLocalScanline) \
+{ \
+ for(int32_t lineIndex = 0; lineIndex < skipLine; ++lineIndex) \
+ { \
+ TextAbstraction::GlyphBufferData::DecompressScanline(data.glyphBitmap, glyphScanline, glyphOffet); \
+ } \
+} \
+else \
+{ \
+ glyphScanline += skipLine * static_cast<int32_t>(data.glyphBitmap.width * glyphPixelSize); \
+}
+
+/**
+ * @brief Prepare scanline of glyph bitmap data per each lines. It must be call END_GLYPH_SCANLINE_DECODE end of same scope.
+ */
+#define BEGIN_GLYPH_SCANLINE_DECODE(data) \
+{ \
+ if(useLocalScanline) \
+ { \
+ TextAbstraction::GlyphBufferData::DecompressScanline(data.glyphBitmap, glyphScanline, glyphOffet); \
+ }
+
+/**
+ * @brief Finalize scanline of glyph bitmap data per each lines.
+ */
+#define END_GLYPH_SCANLINE_DECODE(data) \
+ if(!useLocalScanline) \
+ { \
+ glyphScanline += data.glyphBitmap.width * glyphPixelSize; \
+ } \
+} // For ensure that we call BEGIN_GLYPH_SCANLINE_DECODE before
+
+/**
+ * @brief Finalize decode glyph bitmap data.
+ */
+#define END_GLYPH_BITMAP() \
+ if(useLocalScanline) \
+ { \
+ free(glyphScanline); \
+ } \
+} // For ensure that we call BEGIN_GLYPH_BITMAP before
+
+// clang-format on
+/// Helper macro define end.
+
+/**
+ * @brief Data struct used to set the buffer of the glyph's bitmap into the final bitmap's buffer.
+ */
+struct GlyphData
+{
+ Devel::PixelBuffer bitmapBuffer; ///< The buffer of the whole bitmap. The format is RGBA8888.
+ Vector2* position; ///< The position of the glyph.
+ TextAbstraction::GlyphBufferData glyphBitmap; ///< The glyph's bitmap.
+ uint32_t width; ///< The bitmap's width.
+ uint32_t height; ///< The bitmap's height.
+ int32_t horizontalOffset; ///< The horizontal offset to be added to the 'x' glyph's position.
+ int32_t verticalOffset; ///< The vertical offset to be added to the 'y' glyph's position.
+};
+
+/**
+ * @brief Sets the glyph's buffer into the bitmap's buffer.
+ *
+ * @param[in, out] data Struct which contains the glyph's data and the bitmap's data.
+ * @param[in] position The position of the glyph.
+ * @param[in] color The color of the glyph.
+ * @param[in] style The style of the text.
+ * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
+ */
+void TypesetGlyph(GlyphData& __restrict__ data,
+ const Vector2* const __restrict__ position,
+ const Vector4* const __restrict__ color,
+ const Typesetter::Style style,
+ const Pixel::Format pixelFormat)
+{
+ if((0u == data.glyphBitmap.width) || (0u == data.glyphBitmap.height))
+ {
+ // Nothing to do if the width or height of the buffer is zero.
+ return;
+ }
+
+ // Initial vertical / horizontal offset.
+ const int32_t yOffset = data.verticalOffset + position->y;
+ const int32_t xOffset = data.horizontalOffset + position->x;
+
+ // Whether the given glyph is a color one.
+ const bool isColorGlyph = data.glyphBitmap.isColorEmoji || data.glyphBitmap.isColorBitmap;
+ const uint32_t glyphPixelSize = Pixel::GetBytesPerPixel(data.glyphBitmap.format);
+ const uint32_t glyphAlphaIndex = (glyphPixelSize > 0u) ? glyphPixelSize - 1u : 0u;
+
+ // Determinate iterator range.
+ const int32_t lineIndexRangeMin = std::max(0, -yOffset);
+ const int32_t lineIndexRangeMax = std::min(static_cast<int32_t>(data.glyphBitmap.height), static_cast<int32_t>(data.height) - yOffset);
+ const int32_t indexRangeMin = std::max(0, -xOffset);
+ const int32_t indexRangeMax = std::min(static_cast<int32_t>(data.glyphBitmap.width), static_cast<int32_t>(data.width) - xOffset);
+
+ // If current glyph don't need to be rendered, just ignore.
+ if(lineIndexRangeMax <= lineIndexRangeMin || indexRangeMax <= indexRangeMin)
+ {
+ return;
+ }
+
+ if(Pixel::RGBA8888 == pixelFormat)
+ {
+ uint32_t* __restrict__ bitmapBuffer = reinterpret_cast<uint32_t*>(data.bitmapBuffer.GetBuffer());
+ // Skip basic line.
+ bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast<int32_t>(data.width);
+
+ // Fast-cut if style is MASK or OUTLINE. Outline not shown for color glyph.
+ // Just overwrite transparent color and return.
+ if(isColorGlyph && (Typesetter::STYLE_MASK == style || Typesetter::STYLE_OUTLINE == style))
+ {
+ for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
+ {
+ // We can use memset here.
+ memset(bitmapBuffer + xOffset + indexRangeMin, 0, (indexRangeMax - indexRangeMin) * sizeof(uint32_t));
+ bitmapBuffer += data.width;
+ }
+ return;
+ }
+
+ const bool swapChannelsBR = Pixel::BGRA8888 == data.glyphBitmap.format;
+
+ // Precalculate input color's packed result.
+ uint32_t packedInputColor = 0u;
+ uint8_t* __restrict__ packedInputColorBuffer = reinterpret_cast<uint8_t*>(&packedInputColor);
+
+ *(packedInputColorBuffer + 3u) = static_cast<uint8_t>(color->a * 255);
+ *(packedInputColorBuffer + 2u) = static_cast<uint8_t>(color->b * 255);
+ *(packedInputColorBuffer + 1u) = static_cast<uint8_t>(color->g * 255);
+ *(packedInputColorBuffer) = static_cast<uint8_t>(color->r * 255);
+
+ // Prepare glyph bitmap
+ BEGIN_GLYPH_BITMAP(data);
+
+ // Skip basic line of glyph.
+ SKIP_GLYPH_SCANLINE(lineIndexRangeMin);
+
+ // Traverse the pixels of the glyph line per line.
+ if(isColorGlyph)
+ {
+ for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
+ {
+ BEGIN_GLYPH_SCANLINE_DECODE(data);
+
+ for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
+ {
+ const int32_t xOffsetIndex = xOffset + index;
+
+ // Retrieves the color from the color glyph.
+ uint32_t packedColorGlyph = *(reinterpret_cast<const uint32_t*>(glyphScanline + (index << 2)));
+ uint8_t* __restrict__ packedColorGlyphBuffer = reinterpret_cast<uint8_t*>(&packedColorGlyph);
+
+ // Update the alpha channel.
+ const uint8_t colorAlpha = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 3u), *(packedColorGlyphBuffer + 3u));
+ *(packedColorGlyphBuffer + 3u) = colorAlpha;
+
+ if(Typesetter::STYLE_SHADOW == style)
+ {
+ // The shadow of color glyph needs to have the shadow color.
+ *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), colorAlpha);
+ *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), colorAlpha);
+ *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedInputColorBuffer, colorAlpha);
+ }
+ else
+ {
+ if(swapChannelsBR)
+ {
+ std::swap(*packedColorGlyphBuffer, *(packedColorGlyphBuffer + 2u)); // Swap B and R.
+ }
+
+ *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedColorGlyphBuffer + 2u), colorAlpha);
+ *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedColorGlyphBuffer + 1u), colorAlpha);
+ *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedColorGlyphBuffer, colorAlpha);
+
+ if(data.glyphBitmap.isColorBitmap)
+ {
+ *(packedColorGlyphBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), *(packedColorGlyphBuffer + 2u));
+ *(packedColorGlyphBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), *(packedColorGlyphBuffer + 1u));
+ *packedColorGlyphBuffer = MultiplyAndNormalizeColor(*packedInputColorBuffer, *packedColorGlyphBuffer);
+ }
+ }
+
+ // Set the color into the final pixel buffer.
+ *(bitmapBuffer + xOffsetIndex) = packedColorGlyph;
+ }
+
+ bitmapBuffer += data.width;
+
+ END_GLYPH_SCANLINE_DECODE(data);
+ }
+ }
+ else
+ {
+ for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
+ {
+ BEGIN_GLYPH_SCANLINE_DECODE(data);
+
+ for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
+ {
+ // Update the alpha channel.
+ const uint8_t alpha = *(glyphScanline + index * glyphPixelSize + glyphAlphaIndex);
+
+ // Copy non-transparent pixels only
+ if(alpha > 0u)
+ {
+ const int32_t xOffsetIndex = xOffset + index;
+
+ // Check alpha of overlapped pixels
+ uint32_t& currentColor = *(bitmapBuffer + xOffsetIndex);
+ uint8_t* packedCurrentColorBuffer = reinterpret_cast<uint8_t*>(¤tColor);
+
+ // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
+ // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
+ // semi-transparent gaps between joint glyphs with overlapped pixels, which could
+ // happen, for example, in the RTL text when we copy glyphs from right to left).
+ uint8_t currentAlpha = *(packedCurrentColorBuffer + 3u);
+ currentAlpha = std::max(currentAlpha, alpha);
+ if(currentAlpha == 255)
+ {
+ // Fast-cut to avoid float type operation.
+ currentColor = packedInputColor;
+ }
+ else
+ {
+ // Pack the given color into a 32bit buffer. The alpha channel will be updated later for each pixel.
+ // The format is RGBA8888.
+ uint32_t packedColor = 0u;
+ uint8_t* __restrict__ packedColorBuffer = reinterpret_cast<uint8_t*>(&packedColor);
+
+ // Color is pre-muliplied with its alpha.
+ *(packedColorBuffer + 3u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 3u), currentAlpha);
+ *(packedColorBuffer + 2u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 2u), currentAlpha);
+ *(packedColorBuffer + 1u) = MultiplyAndNormalizeColor(*(packedInputColorBuffer + 1u), currentAlpha);
+ *(packedColorBuffer) = MultiplyAndNormalizeColor(*packedInputColorBuffer, currentAlpha);
+
+ // Set the color into the final pixel buffer.
+ currentColor = packedColor;
+ }
+ }
+ }
+
+ bitmapBuffer += data.width;
+
+ END_GLYPH_SCANLINE_DECODE(data);
+ }
+ }
+
+ END_GLYPH_BITMAP();
+ }
+ else // Pixel::L8
+ {
+ // Below codes required only if not color glyph.
+ if(!isColorGlyph)
+ {
+ uint8_t* __restrict__ bitmapBuffer = data.bitmapBuffer.GetBuffer();
+ // Skip basic line.
+ bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast<int32_t>(data.width);
+
+ // Prepare glyph bitmap
+ BEGIN_GLYPH_BITMAP(data);
+
+ // Skip basic line of glyph.
+ SKIP_GLYPH_SCANLINE(lineIndexRangeMin);
+
+ // Traverse the pixels of the glyph line per line.
+ for(int32_t lineIndex = lineIndexRangeMin; lineIndex < lineIndexRangeMax; ++lineIndex)
+ {
+ BEGIN_GLYPH_SCANLINE_DECODE(data);
+
+ for(int32_t index = indexRangeMin; index < indexRangeMax; ++index)
+ {
+ const int32_t xOffsetIndex = xOffset + index;
+
+ // Update the alpha channel.
+ const uint8_t alpha = *(glyphScanline + index * glyphPixelSize + glyphAlphaIndex);
+
+ // Copy non-transparent pixels only
+ if(alpha > 0u)
+ {
+ // Check alpha of overlapped pixels
+ uint8_t& currentAlpha = *(bitmapBuffer + xOffsetIndex);
+
+ // For any pixel overlapped with the pixel in previous glyphs, make sure we don't
+ // overwrite a previous bigger alpha with a smaller alpha (in order to avoid
+ // semi-transparent gaps between joint glyphs with overlapped pixels, which could
+ // happen, for example, in the RTL text when we copy glyphs from right to left).
+ currentAlpha = std::max(currentAlpha, alpha);
+ }
+ }
+
+ bitmapBuffer += data.width;
+
+ END_GLYPH_SCANLINE_DECODE(data);
+ }
+
+ END_GLYPH_BITMAP();
+ }
+ }
+}
+
+/// Draws the specified underline color to the buffer
+void DrawUnderline(
+ const uint32_t bufferWidth,
+ const uint32_t bufferHeight,
+ GlyphData& glyphData,
+ const float baseline,
+ const float currentUnderlinePosition,
+ const float maxUnderlineHeight,
+ const float lineExtentLeft,
+ const float lineExtentRight,
+ const UnderlineStyleProperties& commonUnderlineProperties,
+ const UnderlineStyleProperties& currentUnderlineProperties,
+ const LineRun& line)
+{
+ const Vector4& underlineColor = currentUnderlineProperties.colorDefined ? currentUnderlineProperties.color : commonUnderlineProperties.color;
+ const Text::Underline::Type underlineType = currentUnderlineProperties.typeDefined ? currentUnderlineProperties.type : commonUnderlineProperties.type;
+ const float dashedUnderlineWidth = currentUnderlineProperties.dashWidthDefined ? currentUnderlineProperties.dashWidth : commonUnderlineProperties.dashWidth;
+ const float dashedUnderlineGap = currentUnderlineProperties.dashGapDefined ? currentUnderlineProperties.dashGap : commonUnderlineProperties.dashGap;
+
+ int32_t underlineYOffset = glyphData.verticalOffset + baseline + currentUnderlinePosition;
+
+ const uint32_t yRangeMin = underlineYOffset;
+ const uint32_t yRangeMax = std::min(bufferHeight, underlineYOffset + static_cast<uint32_t>(maxUnderlineHeight));
+ const uint32_t xRangeMin = static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentLeft);
+ const uint32_t xRangeMax = std::min(bufferWidth, static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
+
+ // If current glyph don't need to be rendered, just ignore.
+ if((underlineType != Text::Underline::DOUBLE && yRangeMax <= yRangeMin) || xRangeMax <= xRangeMin)
+ {
+ return;
+ }
+
+ // We can optimize by memset when underlineColor.a is near zero
+ uint8_t underlineColorAlpha = static_cast<uint8_t>(underlineColor.a * 255.f);
+
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
+
+ // Skip yRangeMin line.
+ bitmapBuffer += yRangeMin * glyphData.width;
+
+ // Note if underlineType is DASHED, we cannot setup color by memset.
+ if(underlineType != Text::Underline::DASHED && underlineColorAlpha == 0)
+ {
+ for(uint32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ // We can use memset.
+ memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
+ bitmapBuffer += glyphData.width;
+ }
+ if(underlineType == Text::Underline::DOUBLE)
+ {
+ int32_t secondUnderlineYOffset = underlineYOffset - ONE_AND_A_HALF * maxUnderlineHeight;
+ const uint32_t secondYRangeMin = static_cast<uint32_t>(std::max(0, secondUnderlineYOffset));
+ const uint32_t secondYRangeMax = static_cast<uint32_t>(std::max(0, std::min(static_cast<int32_t>(bufferHeight), secondUnderlineYOffset + static_cast<int32_t>(maxUnderlineHeight))));
+
+ // Rewind bitmapBuffer pointer, and skip secondYRangeMin line.
+ bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer()) + yRangeMin * glyphData.width;
+
+ for(uint32_t y = secondYRangeMin; y < secondYRangeMax; y++)
+ {
+ // We can use memset.
+ memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
+ bitmapBuffer += glyphData.width;
+ }
+ }
+ }
+ else
+ {
+ uint32_t packedUnderlineColor = 0u;
+ uint8_t* packedUnderlineColorBuffer = reinterpret_cast<uint8_t*>(&packedUnderlineColor);
+
+ // Write the color to the pixel buffer
+ *(packedUnderlineColorBuffer + 3u) = underlineColorAlpha;
+ *(packedUnderlineColorBuffer + 2u) = static_cast<uint8_t>(underlineColor.b * underlineColorAlpha);
+ *(packedUnderlineColorBuffer + 1u) = static_cast<uint8_t>(underlineColor.g * underlineColorAlpha);
+ *(packedUnderlineColorBuffer) = static_cast<uint8_t>(underlineColor.r * underlineColorAlpha);
+
+ for(uint32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ if(underlineType == Text::Underline::DASHED)
+ {
+ float dashWidth = dashedUnderlineWidth;
+ float dashGap = 0;
+
+ for(uint32_t x = xRangeMin; x < xRangeMax; x++)
+ {
+ if(Dali::EqualsZero(dashGap) && dashWidth > 0)
+ {
+ // Note : this is same logic as bitmap[y][x] = underlineColor;
+ *(bitmapBuffer + x) = packedUnderlineColor;
+ dashWidth--;
+ }
+ else if(dashGap < dashedUnderlineGap)
+ {
+ dashGap++;
+ }
+ else
+ {
+ //reset
+ dashWidth = dashedUnderlineWidth;
+ dashGap = 0;
+ }
+ }
+ }
+ else
+ {
+ for(uint32_t x = xRangeMin; x < xRangeMax; x++)
+ {
+ // Note : this is same logic as bitmap[y][x] = underlineColor;
+ *(bitmapBuffer + x) = packedUnderlineColor;
+ }
+ }
+ bitmapBuffer += glyphData.width;
+ }
+ if(underlineType == Text::Underline::DOUBLE)
+ {
+ int32_t secondUnderlineYOffset = underlineYOffset - ONE_AND_A_HALF * maxUnderlineHeight;
+ const uint32_t secondYRangeMin = static_cast<uint32_t>(std::max(0, secondUnderlineYOffset));
+ const uint32_t secondYRangeMax = static_cast<uint32_t>(std::max(0, std::min(static_cast<int32_t>(bufferHeight), secondUnderlineYOffset + static_cast<int32_t>(maxUnderlineHeight))));
+
+ // Rewind bitmapBuffer pointer, and skip secondYRangeMin line.
+ bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer()) + yRangeMin * glyphData.width;
+
+ for(uint32_t y = secondYRangeMin; y < secondYRangeMax; y++)
+ {
+ for(uint32_t x = xRangeMin; x < xRangeMax; x++)
+ {
+ // Note : this is same logic as bitmap[y][x] = underlineColor;
+ *(bitmapBuffer + x) = packedUnderlineColor;
+ }
+ bitmapBuffer += glyphData.width;
+ }
+ }
+ }
+}
+
+/// Draws the background color to the buffer
+void DrawBackgroundColor(
+ Vector4 backgroundColor,
+ const uint32_t bufferWidth,
+ const uint32_t bufferHeight,
+ GlyphData& glyphData,
+ const float baseline,
+ const LineRun& line,
+ const float lineExtentLeft,
+ const float lineExtentRight)
+{
+ const int32_t yRangeMin = std::max(0, static_cast<int32_t>(glyphData.verticalOffset + baseline - line.ascender));
+ const int32_t yRangeMax = std::min(static_cast<int32_t>(bufferHeight), static_cast<int32_t>(glyphData.verticalOffset + baseline - line.descender));
+ const int32_t xRangeMin = std::max(0, static_cast<int32_t>(glyphData.horizontalOffset + lineExtentLeft));
+ const int32_t xRangeMax = std::min(static_cast<int32_t>(bufferWidth), static_cast<int32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
+
+ // If current glyph don't need to be rendered, just ignore.
+ if(yRangeMax <= yRangeMin || xRangeMax <= xRangeMin)
+ {
+ return;
+ }
+
+ // We can optimize by memset when backgroundColor.a is near zero
+ uint8_t backgroundColorAlpha = static_cast<uint8_t>(backgroundColor.a * 255.f);
+
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
+
+ // Skip yRangeMin line.
+ bitmapBuffer += yRangeMin * glyphData.width;
+
+ if(backgroundColorAlpha == 0)
+ {
+ for(int32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ // We can use memset.
+ memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
+ bitmapBuffer += glyphData.width;
+ }
+ }
+ else
+ {
+ uint32_t packedBackgroundColor = 0u;
+ uint8_t* packedBackgroundColorBuffer = reinterpret_cast<uint8_t*>(&packedBackgroundColor);
+
+ // Write the color to the pixel buffer
+ *(packedBackgroundColorBuffer + 3u) = backgroundColorAlpha;
+ *(packedBackgroundColorBuffer + 2u) = static_cast<uint8_t>(backgroundColor.b * backgroundColorAlpha);
+ *(packedBackgroundColorBuffer + 1u) = static_cast<uint8_t>(backgroundColor.g * backgroundColorAlpha);
+ *(packedBackgroundColorBuffer) = static_cast<uint8_t>(backgroundColor.r * backgroundColorAlpha);
+
+ for(int32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ for(int32_t x = xRangeMin; x < xRangeMax; x++)
+ {
+ // Note : this is same logic as bitmap[y][x] = backgroundColor;
+ *(bitmapBuffer + x) = packedBackgroundColor;
+ }
+ bitmapBuffer += glyphData.width;
+ }
+ }
+}
+
+Devel::PixelBuffer DrawGlyphsBackground(const ViewModel* model, Devel::PixelBuffer& buffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const int32_t horizontalOffset, const int32_t verticalOffset)
+{
+ // Retrieve lines, glyphs, positions and colors from the view model.
+ const Length modelNumberOfLines = model->GetNumberOfLines();
+ const LineRun* const modelLinesBuffer = model->GetLines();
+ const Length numberOfGlyphs = model->GetNumberOfGlyphs();
+ const GlyphInfo* const glyphsBuffer = model->GetGlyphs();
+ const Vector2* const positionBuffer = model->GetLayout();
+ const Vector4* const backgroundColorsBuffer = model->GetBackgroundColors();
+ const ColorIndex* const backgroundColorIndicesBuffer = model->GetBackgroundColorIndices();
+ const bool removeFrontInset = model->IsRemoveFrontInset();
+ const bool removeBackInset = model->IsRemoveBackInset();
+
+ const DevelText::VerticalLineAlignment::Type verLineAlign = model->GetVerticalLineAlignment();
+
+ // Create and initialize the pixel buffer.
+ GlyphData glyphData;
+ glyphData.verticalOffset = verticalOffset;
+ glyphData.width = bufferWidth;
+ glyphData.height = bufferHeight;
+ glyphData.bitmapBuffer = buffer;
+ glyphData.horizontalOffset = 0;
+
+ ColorIndex prevBackgroundColorIndex = 0;
+ ColorIndex backgroundColorIndex = 0;
+
+ // Traverses the lines of the text.
+ for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex)
+ {
+ const LineRun& line = *(modelLinesBuffer + lineIndex);
+
+ // Sets the horizontal offset of the line.
+ glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int32_t>(line.alignmentOffset);
+ glyphData.horizontalOffset += horizontalOffset;
+
+ // Increases the vertical offset with the line's ascender.
+ glyphData.verticalOffset += static_cast<int32_t>(line.ascender + GetPreOffsetVerticalLineAlignment(line, verLineAlign));
+
+ float left = bufferWidth;
+ float right = 0.0f;
+ float baseline = 0.0f;
+
+ // Traverses the glyphs of the line.
+ const GlyphIndex endGlyphIndex = std::min(numberOfGlyphs, line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs);
+ for(GlyphIndex glyphIndex = line.glyphRun.glyphIndex; glyphIndex < endGlyphIndex; ++glyphIndex)
+ {
+ // Retrieve the glyph's info.
+ const GlyphInfo* const glyphInfo = glyphsBuffer + glyphIndex;
+
+ if((glyphInfo->width < Math::MACHINE_EPSILON_1000) ||
+ (glyphInfo->height < Math::MACHINE_EPSILON_1000))
+ {
+ // Nothing to do if default background color, the glyph's width or height is zero.
+ continue;
+ }
+
+ backgroundColorIndex = (nullptr == backgroundColorsBuffer) ? 0u : *(backgroundColorIndicesBuffer + glyphIndex);
+
+ if((backgroundColorIndex != prevBackgroundColorIndex) &&
+ (prevBackgroundColorIndex != 0u))
+ {
+ const Vector4& backgroundColor = *(backgroundColorsBuffer + prevBackgroundColorIndex - 1u);
+ DrawBackgroundColor(backgroundColor, bufferWidth, bufferHeight, glyphData, baseline, line, left, right);
+ }
+
+ if(backgroundColorIndex == 0u)
+ {
+ prevBackgroundColorIndex = backgroundColorIndex;
+ //if background color is the default do nothing
+ continue;
+ }
+
+ // Retrieves the glyph's position.
+ const Vector2* const position = positionBuffer + glyphIndex;
+
+ if(baseline < position->y + glyphInfo->yBearing)
+ {
+ baseline = position->y + glyphInfo->yBearing;
+ }
+
+ // Calculate the positions of leftmost and rightmost glyphs in the current line
+ if(removeFrontInset)
+ {
+ if((position->x < left) || (backgroundColorIndex != prevBackgroundColorIndex))
+ {
+ left = position->x;
+ }
+ }
+ else
+ {
+ const float originPositionLeft = position->x - glyphInfo->xBearing;
+ if((originPositionLeft < left) || (backgroundColorIndex != prevBackgroundColorIndex))
+ {
+ left = originPositionLeft;
+ }
+ }
+
+ if(removeBackInset)
+ {
+ if(position->x + glyphInfo->width > right)
+ {
+ right = position->x + glyphInfo->width;
+ }
+ }
+ else
+ {
+ const float originPositionRight = position->x - glyphInfo->xBearing + glyphInfo->advance;
+ if(originPositionRight > right)
+ {
+ right = originPositionRight;
+ }
+ }
+
+ prevBackgroundColorIndex = backgroundColorIndex;
+ }
+
+ //draw last background at line end if not default
+ if(backgroundColorIndex != 0u)
+ {
+ const Vector4& backgroundColor = *(backgroundColorsBuffer + backgroundColorIndex - 1u);
+ DrawBackgroundColor(backgroundColor, bufferWidth, bufferHeight, glyphData, baseline, line, left, right);
+ }
+
+ // Increases the vertical offset with the line's descender.
+ glyphData.verticalOffset += static_cast<int32_t>(-line.descender + GetPostOffsetVerticalLineAlignment(line, verLineAlign));
+ }
+
+ return glyphData.bitmapBuffer;
+}
+
+/// Draws the specified strikethrough color to the buffer
+void DrawStrikethrough(const uint32_t bufferWidth,
+ const uint32_t bufferHeight,
+ GlyphData& glyphData,
+ const float baseline,
+ const float strikethroughStartingYPosition,
+ const float maxStrikethroughHeight,
+ const float lineExtentLeft,
+ const float lineExtentRight,
+ const StrikethroughStyleProperties& commonStrikethroughProperties,
+ const StrikethroughStyleProperties& currentStrikethroughProperties,
+ const LineRun& line)
+{
+ const Vector4& strikethroughColor = currentStrikethroughProperties.colorDefined ? currentStrikethroughProperties.color : commonStrikethroughProperties.color;
+
+ const uint32_t yRangeMin = static_cast<uint32_t>(strikethroughStartingYPosition);
+ const uint32_t yRangeMax = std::min(bufferHeight, static_cast<uint32_t>(strikethroughStartingYPosition + maxStrikethroughHeight));
+ const uint32_t xRangeMin = static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentLeft);
+ const uint32_t xRangeMax = std::min(bufferWidth, static_cast<uint32_t>(glyphData.horizontalOffset + lineExtentRight + 1)); // Due to include last point, we add 1 here
+
+ // If current glyph don't need to be rendered, just ignore.
+ if(yRangeMax <= yRangeMin || xRangeMax <= xRangeMin)
+ {
+ return;
+ }
+
+ // We can optimize by memset when strikethroughColor.a is near zero
+ uint8_t strikethroughColorAlpha = static_cast<uint8_t>(strikethroughColor.a * 255.f);
+
+ uint32_t* bitmapBuffer = reinterpret_cast<uint32_t*>(glyphData.bitmapBuffer.GetBuffer());
+
+ // Skip yRangeMin line.
+ bitmapBuffer += yRangeMin * glyphData.width;
+
+ if(strikethroughColorAlpha == 0)
+ {
+ for(uint32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ // We can use memset.
+ memset(bitmapBuffer + xRangeMin, 0, (xRangeMax - xRangeMin) * sizeof(uint32_t));
+ bitmapBuffer += glyphData.width;
+ }
+ }
+ else
+ {
+ uint32_t packedStrikethroughColor = 0u;
+ uint8_t* packedStrikethroughColorBuffer = reinterpret_cast<uint8_t*>(&packedStrikethroughColor);
+
+ // Write the color to the pixel buffer
+ *(packedStrikethroughColorBuffer + 3u) = strikethroughColorAlpha;
+ *(packedStrikethroughColorBuffer + 2u) = static_cast<uint8_t>(strikethroughColor.b * strikethroughColorAlpha);
+ *(packedStrikethroughColorBuffer + 1u) = static_cast<uint8_t>(strikethroughColor.g * strikethroughColorAlpha);
+ *(packedStrikethroughColorBuffer) = static_cast<uint8_t>(strikethroughColor.r * strikethroughColorAlpha);
+
+ for(uint32_t y = yRangeMin; y < yRangeMax; y++)
+ {
+ for(uint32_t x = xRangeMin; x < xRangeMax; x++)
+ {
+ // Note : this is same logic as bitmap[y][x] = strikethroughColor;
+ *(bitmapBuffer + x) = packedStrikethroughColor;
+ }
+ bitmapBuffer += glyphData.width;
+ }
+ }
+}
+
+/**
+ * @brief Create an initialized image buffer filled with transparent color.
+ *
+ * Creates the pixel data used to generate the final image with the given size.
+ *
+ * @param[in] bufferWidth The width of the image buffer.
+ * @param[in] bufferHeight The height of the image buffer.
+ * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
+ *
+ * @return An image buffer.
+ */
+inline Devel::PixelBuffer CreateTransparentImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Pixel::Format pixelFormat)
+{
+ Devel::PixelBuffer imageBuffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, pixelFormat);
+
+ if(Pixel::RGBA8888 == pixelFormat)
+ {
+ const uint32_t bufferSizeInt = bufferWidth * bufferHeight;
+ const size_t bufferSizeChar = sizeof(uint32_t) * static_cast<std::size_t>(bufferSizeInt);
+ memset(imageBuffer.GetBuffer(), 0, bufferSizeChar);
+ }
+ else
+ {
+ memset(imageBuffer.GetBuffer(), 0, static_cast<std::size_t>(bufferWidth * bufferHeight));
+ }
+
+ return imageBuffer;
}
/**
uint32_t* topBuffer = reinterpret_cast<uint32_t*>(topPixelBuffer.GetBuffer());
uint32_t* bottomBuffer = reinterpret_cast<uint32_t*>(bottomPixelBuffer.GetBuffer());
- if(topBuffer == nullptr && bottomBuffer == nullptr)
+ if(topBuffer == NULL && bottomBuffer == NULL)
{
// Nothing to do if both buffers are empty.
return;
}
- if(topBuffer == nullptr)
+ if(topBuffer == NULL)
{
// Nothing to do if topBuffer is empty.
// If we need to store the result into top, change topPixelBuffer as bottomPixelBuffer.
return;
}
- if(bottomBuffer == nullptr)
+ if(bottomBuffer == NULL)
{
// Nothing to do if bottomBuffer is empty.
// If we need to store the result into bottom, change bottomPixelBuffer as topPixelBuffer.
ViewModel* Typesetter::GetViewModel()
{
- return mImpl->GetViewModel();
+ return mModel;
}
void Typesetter::SetFontClient(TextAbstraction::FontClient& fontClient)
{
- mImpl->SetFontClient(fontClient);
+ mFontClient = fontClient;
}
PixelData Typesetter::Render(const Vector2& size, Toolkit::DevelText::TextDirection::Type textDirection, RenderBehaviour behaviour, bool ignoreHorizontalAlignment, Pixel::Format pixelFormat)
{
- Devel::PixelBuffer result = RenderWithPixelBuffer(size, textDirection, behaviour, ignoreHorizontalAlignment, pixelFormat);
- PixelData pixelData = Devel::PixelBuffer::Convert(result);
+ Devel::PixelBuffer result = RenderWithPixelBuffer(size, textDirection, behaviour, ignoreHorizontalAlignment, pixelFormat);
+ PixelData pixelData = Devel::PixelBuffer::Convert(result);
return pixelData;
}
DALI_TRACE_SCOPE(gTraceFilter, "DALI_TEXT_RENDERING_TYPESETTER");
// @todo. This initial implementation for a TextLabel has only one visible page.
- // Use l-value to make ensure it is not nullptr, so compiler happy.
- auto& viewModel = *(mImpl->GetViewModel());
-
// Elides the text if needed.
- viewModel.ElideGlyphs(mImpl->GetFontClient());
+ mModel->ElideGlyphs(mFontClient);
// Retrieves the layout size.
- const Size& layoutSize = viewModel.GetLayoutSize();
- const int32_t outlineWidth = static_cast<int32_t>(viewModel.GetOutlineWidth());
+ const Size& layoutSize = mModel->GetLayoutSize();
+ const int32_t outlineWidth = static_cast<int32_t>(mModel->GetOutlineWidth());
// Set the offset for the horizontal alignment according to the text direction and outline width.
int32_t penX = 0;
- switch(viewModel.GetHorizontalAlignment())
+ switch(mModel->GetHorizontalAlignment())
{
case HorizontalAlignment::BEGIN:
{
// Set the offset for the vertical alignment.
int32_t penY = 0u;
- switch(viewModel.GetVerticalAlignment())
+ switch(mModel->GetVerticalAlignment())
{
case VerticalAlignment::TOP:
{
}
}
- const bool isCutoutEnabled = viewModel.IsCutoutEnabled();
+ const bool isCutoutEnabled = mModel->IsCutoutEnabled();
if(isCutoutEnabled)
{
- Vector2 offset = viewModel.GetOffsetWithCutout();
- penX = offset.x;
- penY = offset.y;
+ Vector2 offset = mModel->GetOffsetWithCutout();
+ penX = offset.x;
+ penY = offset.y;
}
// Generate the image buffers of the text for each different style first,
const size_t bufferSizeChar = sizeof(uint32_t) * static_cast<std::size_t>(bufferSizeInt);
//Elided text in ellipsis at START could start on index greater than 0
- auto startIndexOfGlyphs = viewModel.GetStartIndexOfElidedGlyphs();
- auto endIndexOfGlyphs = viewModel.GetEndIndexOfElidedGlyphs();
+ auto startIndexOfGlyphs = mModel->GetStartIndexOfElidedGlyphs();
+ auto endIndexOfGlyphs = mModel->GetEndIndexOfElidedGlyphs();
Devel::PixelBuffer imageBuffer;
if(RENDER_MASK == behaviour)
{
// Generate the image buffer as an alpha mask for color glyphs.
- imageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_MASK, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
}
else if(RENDER_NO_TEXT == behaviour || RENDER_OVERLAY_STYLE == behaviour)
{
else
{
// Generate the image buffer for the text with no style.
- imageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ imageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_NONE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
}
if((RENDER_NO_STYLES != behaviour) && (RENDER_MASK != behaviour))
{
// Generate the outline if enabled
- const uint16_t outlineWidth = viewModel.GetOutlineWidth();
- const float outlineAlpha = viewModel.GetOutlineColor().a;
+ const uint16_t outlineWidth = mModel->GetOutlineWidth();
+ const float outlineAlpha = mModel->GetOutlineColor().a;
if(outlineWidth != 0u && fabsf(outlineAlpha) > Math::MACHINE_EPSILON_1 && RENDER_OVERLAY_STYLE != behaviour)
{
// Create the image buffer for outline
- Devel::PixelBuffer outlineImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ Devel::PixelBuffer outlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_OUTLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
- const float& blurRadius = viewModel.GetOutlineBlurRadius();
+ const float& blurRadius = mModel->GetOutlineBlurRadius();
if(blurRadius > Math::MACHINE_EPSILON_1)
{
// @todo. Support shadow for partial text later on.
// Generate the shadow if enabled
- const Vector2& shadowOffset = viewModel.GetShadowOffset();
- const float shadowAlpha = viewModel.GetShadowColor().a;
+ const Vector2& shadowOffset = mModel->GetShadowOffset();
+ const float shadowAlpha = mModel->GetShadowColor().a;
if(RENDER_OVERLAY_STYLE != behaviour && fabsf(shadowAlpha) > Math::MACHINE_EPSILON_1 && (fabsf(shadowOffset.x) > Math::MACHINE_EPSILON_1 || fabsf(shadowOffset.y) > Math::MACHINE_EPSILON_1))
{
// Create the image buffer for shadow
- Devel::PixelBuffer shadowImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ Devel::PixelBuffer shadowImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_SHADOW, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
// Check whether it will be a soft shadow
- const float& blurRadius = viewModel.GetShadowBlurRadius();
+ const float& blurRadius = mModel->GetShadowBlurRadius();
if(blurRadius > Math::MACHINE_EPSILON_1)
{
}
// Generate the background if enabled
- const bool backgroundEnabled = viewModel.IsBackgroundEnabled();
- const bool backgroundMarkupSet = viewModel.IsMarkupBackgroundColorSet();
+ const bool backgroundEnabled = mModel->IsBackgroundEnabled();
+ const bool backgroundMarkupSet = mModel->IsMarkupBackgroundColorSet();
if((backgroundEnabled || backgroundMarkupSet) && RENDER_OVERLAY_STYLE != behaviour)
{
Devel::PixelBuffer backgroundImageBuffer;
if(backgroundEnabled)
{
- backgroundImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ backgroundImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_BACKGROUND, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
}
else
{
- backgroundImageBuffer = Impl::CreateTransparentImageBuffer(bufferWidth, bufferHeight, pixelFormat);
+ backgroundImageBuffer = CreateTransparentImageBuffer(bufferWidth, bufferHeight, pixelFormat);
}
if(backgroundMarkupSet)
{
- mImpl->DrawGlyphsBackground(backgroundImageBuffer, bufferWidth, bufferHeight, ignoreHorizontalAlignment, penX, penY);
+ DrawGlyphsBackground(mModel, backgroundImageBuffer, bufferWidth, bufferHeight, ignoreHorizontalAlignment, penX, penY);
}
// Combine the two buffers
}
// Generate the background_with_mask if enabled
- const bool backgroundWithCutoutEnabled = viewModel.IsBackgroundWithCutoutEnabled();
+ const bool backgroundWithCutoutEnabled = mModel->IsBackgroundWithCutoutEnabled();
if((backgroundWithCutoutEnabled) && RENDER_OVERLAY_STYLE != behaviour)
{
Devel::PixelBuffer backgroundImageBuffer;
- backgroundImageBuffer = CreateFullBackgroundBuffer(bufferWidth, bufferHeight, viewModel.GetBackgroundColorWithCutout());
+ backgroundImageBuffer = CreateFullBackgroundBuffer(bufferWidth, bufferHeight, mModel->GetBackgroundColorWithCutout());
// Combine the two buffers
CombineImageBuffer(imageBuffer, backgroundImageBuffer, bufferWidth, bufferHeight, true);
if(RENDER_OVERLAY_STYLE == behaviour)
{
- if(viewModel.IsUnderlineEnabled())
+ if(mModel->IsUnderlineEnabled())
{
// Create the image buffer for underline
- Devel::PixelBuffer underlineImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
+ Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, penX, penY, startIndexOfGlyphs, endIndexOfGlyphs);
// Combine the two buffers
CombineImageBuffer(imageBuffer, underlineImageBuffer, bufferWidth, bufferHeight, true);
}
- if(viewModel.IsStrikethroughEnabled())
+ if(mModel->IsStrikethroughEnabled())
{
// Create the image buffer for strikethrough
- Devel::PixelBuffer strikethroughImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_STRIKETHROUGH, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, endIndexOfGlyphs);
+ Devel::PixelBuffer strikethroughImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_STRIKETHROUGH, ignoreHorizontalAlignment, pixelFormat, penX, penY, 0u, endIndexOfGlyphs);
// Combine the two buffers
CombineImageBuffer(imageBuffer, strikethroughImageBuffer, bufferWidth, bufferHeight, true);
}
// Markup-Processor for overlay styles
- if(viewModel.IsMarkupProcessorEnabled() || viewModel.IsSpannedTextPlaced())
+ if(mModel->IsMarkupProcessorEnabled() || mModel->IsSpannedTextPlaced())
{
- if(viewModel.IsMarkupUnderlineSet())
+ if(mModel->IsMarkupUnderlineSet())
{
imageBuffer = ApplyUnderlineMarkupImageBuffer(imageBuffer, bufferWidth, bufferHeight, ignoreHorizontalAlignment, pixelFormat, penX, penY);
}
- if(viewModel.IsMarkupStrikethroughSet())
+ if(mModel->IsMarkupStrikethroughSet())
{
imageBuffer = ApplyStrikethroughMarkupImageBuffer(imageBuffer, bufferWidth, bufferHeight, ignoreHorizontalAlignment, pixelFormat, penX, penY);
}
Devel::PixelBuffer Typesetter::CreateFullBackgroundBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Vector4& backgroundColor)
{
- const uint32_t bufferSizeInt = bufferWidth * bufferHeight;
- uint8_t backgroundColorAlpha = static_cast<uint8_t>(backgroundColor.a * 255.f);
+ const uint32_t bufferSizeInt = bufferWidth * bufferHeight;
+ uint8_t backgroundColorAlpha = static_cast<uint8_t>(backgroundColor.a * 255.f);
Devel::PixelBuffer buffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888);
return buffer;
}
-Devel::PixelBuffer Typesetter::ApplyUnderlineMarkupImageBuffer(Devel::PixelBuffer topPixelBuffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset)
+Devel::PixelBuffer Typesetter::CreateImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Typesetter::Style style, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset, const GlyphIndex fromGlyphIndex, const GlyphIndex toGlyphIndex)
{
- // Use l-value to make ensure it is not nullptr, so compiler happy.
- auto& viewModel = *(mImpl->GetViewModel());
+ // Retrieve lines, glyphs, positions and colors from the view model.
+ const Length modelNumberOfLines = mModel->GetNumberOfLines();
+ const LineRun* const __restrict__ modelLinesBuffer = mModel->GetLines();
+ const GlyphInfo* const __restrict__ glyphsBuffer = mModel->GetGlyphs();
+ const Vector2* const __restrict__ positionBuffer = mModel->GetLayout();
+ const Vector4* const __restrict__ colorsBuffer = mModel->GetColors();
+ const ColorIndex* const __restrict__ colorIndexBuffer = mModel->GetColorIndices();
+ const GlyphInfo* __restrict__ hyphens = mModel->GetHyphens();
+ const Length* __restrict__ hyphenIndices = mModel->GetHyphenIndices();
+ const Length hyphensCount = mModel->GetHyphensCount();
+ const bool removeFrontInset = mModel->IsRemoveFrontInset();
+ const bool removeBackInset = mModel->IsRemoveBackInset();
+ const bool cutoutEnabled = mModel->IsCutoutEnabled();
+
+ // Elided text info. Indices according to elided text and Ellipsis position.
+ const auto startIndexOfGlyphs = mModel->GetStartIndexOfElidedGlyphs();
+ const auto endIndexOfGlyphs = mModel->GetEndIndexOfElidedGlyphs();
+ const auto firstMiddleIndexOfElidedGlyphs = mModel->GetFirstMiddleIndexOfElidedGlyphs();
+ const auto secondMiddleIndexOfElidedGlyphs = mModel->GetSecondMiddleIndexOfElidedGlyphs();
+ const auto ellipsisPosition = mModel->GetEllipsisPosition();
+
+ // Whether to use the default color.
+ const bool useDefaultColor = (NULL == colorsBuffer);
+ const Vector4& defaultColor = mModel->GetDefaultColor();
+
+ // Create and initialize the pixel buffer.
+ GlyphData glyphData;
+ glyphData.verticalOffset = verticalOffset;
+ glyphData.width = bufferWidth;
+ glyphData.height = bufferHeight;
+ glyphData.bitmapBuffer = CreateTransparentImageBuffer(bufferWidth, bufferHeight, pixelFormat);
+ glyphData.horizontalOffset = 0;
+
+ // Get a handle of the font client. Used to retrieve the bitmaps of the glyphs.
+ Length hyphenIndex = 0;
+
+ const Character* __restrict__ textBuffer = mModel->GetTextBuffer();
+ float calculatedAdvance = 0.f;
+ const Vector<CharacterIndex>& __restrict__ glyphToCharacterMap = mModel->GetGlyphsToCharacters();
+ const CharacterIndex* __restrict__ glyphToCharacterMapBuffer = glyphToCharacterMap.Begin();
+
+ const DevelText::VerticalLineAlignment::Type verLineAlign = mModel->GetVerticalLineAlignment();
+
+ // Traverses the lines of the text.
+ for(LineIndex lineIndex = 0u; lineIndex < modelNumberOfLines; ++lineIndex)
+ {
+ const LineRun& line = *(modelLinesBuffer + lineIndex);
+
+ // Sets the horizontal offset of the line.
+ glyphData.horizontalOffset = ignoreHorizontalAlignment ? 0 : static_cast<int32_t>(line.alignmentOffset);
+ glyphData.horizontalOffset += horizontalOffset;
+
+ // Increases the vertical offset with the line's ascender.
+ glyphData.verticalOffset += static_cast<int32_t>(line.ascender + GetPreOffsetVerticalLineAlignment(line, verLineAlign));
+
+ // Retrieves the glyph's outline width
+ float outlineWidth = static_cast<float>(mModel->GetOutlineWidth());
+
+ if(style == Typesetter::STYLE_OUTLINE)
+ {
+ const Vector2& outlineOffset = mModel->GetOutlineOffset();
+
+ glyphData.horizontalOffset -= outlineWidth;
+ glyphData.horizontalOffset += outlineOffset.x;
+ if(lineIndex == 0u)
+ {
+ // Only need to add the vertical outline offset for the first line
+ glyphData.verticalOffset -= outlineWidth;
+ glyphData.verticalOffset += outlineOffset.y;
+ }
+ }
+ else if(style == Typesetter::STYLE_SHADOW)
+ {
+ const Vector2& shadowOffset = mModel->GetShadowOffset();
+ glyphData.horizontalOffset += shadowOffset.x - outlineWidth; // if outline enabled then shadow should offset from outline
+
+ if(lineIndex == 0u)
+ {
+ // Only need to add the vertical shadow offset for first line
+ glyphData.verticalOffset += shadowOffset.y - outlineWidth;
+ }
+ }
+
+ const bool underlineEnabled = mModel->IsUnderlineEnabled();
+ const bool strikethroughEnabled = mModel->IsStrikethroughEnabled();
+ const float modelCharacterSpacing = mModel->GetCharacterSpacing();
+
+ // Get the character-spacing runs.
+ const Vector<CharacterSpacingGlyphRun>& __restrict__ characterSpacingGlyphRuns = mModel->GetCharacterSpacingGlyphRuns();
+
+ // Aggregate underline-style-properties from mModel
+ const UnderlineStyleProperties modelUnderlineProperties{mModel->GetUnderlineType(),
+ mModel->GetUnderlineColor(),
+ mModel->GetUnderlineHeight(),
+ mModel->GetDashedUnderlineGap(),
+ mModel->GetDashedUnderlineWidth(),
+ true,
+ true,
+ true,
+ true,
+ true};
+
+ // Aggregate strikethrough-style-properties from mModel
+ const StrikethroughStyleProperties modelStrikethroughProperties{mModel->GetStrikethroughColor(),
+ mModel->GetStrikethroughHeight(),
+ true,
+ true};
+
+ // Get the underline runs.
+ const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
+ Vector<UnderlinedGlyphRun> underlineRuns;
+ underlineRuns.Resize(numberOfUnderlineRuns);
+ mModel->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
+
+ // Get the strikethrough runs.
+ const Length numberOfStrikethroughRuns = mModel->GetNumberOfStrikethroughRuns();
+ Vector<StrikethroughGlyphRun> strikethroughRuns;
+ strikethroughRuns.Resize(numberOfStrikethroughRuns);
+ mModel->GetStrikethroughRuns(strikethroughRuns.Begin(), 0u, numberOfStrikethroughRuns);
+
+ bool thereAreUnderlinedGlyphs = false;
+ bool thereAreStrikethroughGlyphs = false;
+
+ float currentUnderlinePosition = 0.0f;
+ float currentUnderlineHeight = modelUnderlineProperties.height;
+ float maxUnderlineHeight = currentUnderlineHeight;
+ auto currentUnderlineProperties = modelUnderlineProperties;
+
+ float currentStrikethroughHeight = modelStrikethroughProperties.height;
+ float maxStrikethroughHeight = currentStrikethroughHeight;
+ auto currentStrikethroughProperties = modelStrikethroughProperties;
+ float strikethroughStartingYPosition = 0.0f;
+
+ FontId lastFontId = 0;
+
+ float lineExtentLeft = bufferWidth;
+ float lineExtentRight = 0.0f;
+ float baseline = 0.0f;
+ bool addHyphen = false;
+
+ // Traverses the glyphs of the line.
+ const GlyphIndex startGlyphIndex = std::max(std::max(line.glyphRun.glyphIndex, startIndexOfGlyphs), fromGlyphIndex);
+ GlyphIndex endGlyphIndex = (line.isSplitToTwoHalves ? line.glyphRunSecondHalf.glyphIndex + line.glyphRunSecondHalf.numberOfGlyphs : line.glyphRun.glyphIndex + line.glyphRun.numberOfGlyphs) - 1u;
+ endGlyphIndex = std::min(std::min(endGlyphIndex, endIndexOfGlyphs), toGlyphIndex);
+
+ for(GlyphIndex glyphIndex = startGlyphIndex; glyphIndex <= endGlyphIndex; ++glyphIndex)
+ {
+ //To handle START case of ellipsis, the first glyph has been shifted
+ //glyphIndex represent indices in whole glyphs but elidedGlyphIndex represents indices in elided Glyphs
+ GlyphIndex elidedGlyphIndex = glyphIndex - startIndexOfGlyphs;
+
+ //To handle MIDDLE case of ellipsis, the first glyph in the second half of line has been shifted and skip the removed glyph from middle.
+ if(ellipsisPosition == DevelText::EllipsisPosition::MIDDLE)
+ {
+ if(glyphIndex > firstMiddleIndexOfElidedGlyphs &&
+ glyphIndex < secondMiddleIndexOfElidedGlyphs)
+ {
+ // Ignore any glyph that removed for MIDDLE ellipsis
+ continue;
+ }
+ if(glyphIndex >= secondMiddleIndexOfElidedGlyphs)
+ {
+ elidedGlyphIndex -= (secondMiddleIndexOfElidedGlyphs - firstMiddleIndexOfElidedGlyphs - 1u);
+ }
+ }
+
+ // Retrieve the glyph's info.
+ const GlyphInfo* glyphInfo;
+
+ if(addHyphen && hyphens)
+ {
+ glyphInfo = hyphens + hyphenIndex;
+ hyphenIndex++;
+ }
+ else
+ {
+ glyphInfo = glyphsBuffer + elidedGlyphIndex;
+ }
+
+ if((glyphInfo->width < Math::MACHINE_EPSILON_1000) ||
+ (glyphInfo->height < Math::MACHINE_EPSILON_1000))
+ {
+ // Nothing to do if the glyph's width or height is zero.
+ continue;
+ }
+
+ Vector<UnderlinedGlyphRun>::ConstIterator currentUnderlinedGlyphRunIt = underlineRuns.End();
+ const bool underlineGlyph = underlineEnabled || IsGlyphUnderlined(glyphIndex, underlineRuns, currentUnderlinedGlyphRunIt);
+ currentUnderlineProperties = GetCurrentUnderlineProperties(glyphIndex, underlineGlyph, underlineRuns, currentUnderlinedGlyphRunIt, modelUnderlineProperties);
+ currentUnderlineHeight = currentUnderlineProperties.height;
+ thereAreUnderlinedGlyphs = thereAreUnderlinedGlyphs || underlineGlyph;
+ Vector<StrikethroughGlyphRun>::ConstIterator currentStrikethroughGlyphRunIt = strikethroughRuns.End();
+ const bool strikethroughGlyph = strikethroughEnabled || IsGlyphStrikethrough(glyphIndex, strikethroughRuns, currentStrikethroughGlyphRunIt);
+ currentStrikethroughProperties = GetCurrentStrikethroughProperties(glyphIndex, strikethroughGlyph, strikethroughRuns, currentStrikethroughGlyphRunIt, modelStrikethroughProperties);
+ currentStrikethroughHeight = currentStrikethroughProperties.height;
+ thereAreStrikethroughGlyphs = thereAreStrikethroughGlyphs || strikethroughGlyph;
+
+ // Are we still using the same fontId as previous
+ if((glyphInfo->fontId != lastFontId) && (strikethroughGlyph || underlineGlyph))
+ {
+ // We need to fetch fresh font underline metrics
+ FontMetrics fontMetrics;
+ mFontClient.GetFontMetrics(glyphInfo->fontId, fontMetrics);
+
+ //The currentUnderlinePosition will be used for both Underline and/or Strikethrough
+ currentUnderlinePosition = FetchUnderlinePositionFromFontMetrics(fontMetrics);
+
+ if(underlineGlyph)
+ {
+ CalcualteUnderlineHeight(fontMetrics, currentUnderlineHeight, maxUnderlineHeight);
+ }
+
+ if(strikethroughGlyph)
+ {
+ CalcualteStrikethroughHeight(currentStrikethroughHeight, maxStrikethroughHeight);
+ }
+
+ // Update lastFontId because fontId is changed
+ lastFontId = glyphInfo->fontId; // Prevents searching for existing blocksizes when string of the same fontId.
+ }
+
+ // Retrieves the glyph's position.
+ Vector2 position = *(positionBuffer + elidedGlyphIndex);
+
+ if(addHyphen)
+ {
+ GlyphInfo tempInfo = *(glyphsBuffer + elidedGlyphIndex);
+ const float characterSpacing = GetGlyphCharacterSpacing(glyphIndex, characterSpacingGlyphRuns, modelCharacterSpacing);
+ calculatedAdvance = GetCalculatedAdvance(*(textBuffer + (*(glyphToCharacterMapBuffer + elidedGlyphIndex))), characterSpacing, tempInfo.advance);
+ position.x = position.x + calculatedAdvance - tempInfo.xBearing + glyphInfo->xBearing;
+ position.y = -glyphInfo->yBearing;
+ }
+
+ if(baseline < position.y + glyphInfo->yBearing)
+ {
+ baseline = position.y + glyphInfo->yBearing;
+ }
+
+ // Calculate the positions of leftmost and rightmost glyphs in the current line
+ if(removeFrontInset)
+ {
+ if(position.x < lineExtentLeft)
+ {
+ lineExtentLeft = position.x;
+ }
+ }
+ else
+ {
+ const float originPositionLeft = position.x - glyphInfo->xBearing;
+ if(originPositionLeft < lineExtentLeft)
+ {
+ lineExtentLeft = originPositionLeft;
+ }
+ }
+
+ if(removeBackInset)
+ {
+ if(position.x + glyphInfo->width > lineExtentRight)
+ {
+ lineExtentRight = position.x + glyphInfo->width;
+ }
+ }
+ else
+ {
+ const float originPositionRight = position.x - glyphInfo->xBearing + glyphInfo->advance;
+ if(originPositionRight > lineExtentRight)
+ {
+ lineExtentRight = originPositionRight;
+ }
+ }
+
+ // Retrieves the glyph's color.
+ const ColorIndex colorIndex = useDefaultColor ? 0u : *(colorIndexBuffer + glyphIndex);
+
+ Vector4 color;
+ if(style == Typesetter::STYLE_SHADOW)
+ {
+ color = mModel->GetShadowColor();
+ }
+ else if(style == Typesetter::STYLE_OUTLINE)
+ {
+ color = mModel->GetOutlineColor();
+ }
+ else
+ {
+ color = (useDefaultColor || (0u == colorIndex)) ? defaultColor : *(colorsBuffer + (colorIndex - 1u));
+ }
+
+ if(style == Typesetter::STYLE_NONE && cutoutEnabled)
+ {
+ // Temporarily adjust the transparency to 1.f
+ color.a = 1.f;
+ }
+
+ // Premultiply alpha
+ color.r *= color.a;
+ color.g *= color.a;
+ color.b *= color.a;
+
+ // Retrieves the glyph's bitmap.
+ glyphData.glyphBitmap.buffer = NULL;
+ glyphData.glyphBitmap.width = glyphInfo->width; // Desired width and height.
+ glyphData.glyphBitmap.height = glyphInfo->height;
+
+ if(style != Typesetter::STYLE_OUTLINE && style != Typesetter::STYLE_SHADOW)
+ {
+ // Don't render outline for other styles
+ outlineWidth = 0.0f;
+ }
+
+ if(style != Typesetter::STYLE_UNDERLINE && style != Typesetter::STYLE_STRIKETHROUGH)
+ {
+ mFontClient.CreateBitmap(glyphInfo->fontId,
+ glyphInfo->index,
+ glyphInfo->isItalicRequired,
+ glyphInfo->isBoldRequired,
+ glyphData.glyphBitmap,
+ static_cast<int32_t>(outlineWidth));
+ }
+
+ // Sets the glyph's bitmap into the bitmap of the whole text.
+ if(NULL != glyphData.glyphBitmap.buffer)
+ {
+ if(style == Typesetter::STYLE_OUTLINE)
+ {
+ // Set the position offset for the current glyph
+ glyphData.horizontalOffset -= glyphData.glyphBitmap.outlineOffsetX;
+ glyphData.verticalOffset -= glyphData.glyphBitmap.outlineOffsetY;
+ }
+
+ // Set the buffer of the glyph's bitmap into the final bitmap's buffer
+ TypesetGlyph(glyphData,
+ &position,
+ &color,
+ style,
+ pixelFormat);
+
+ if(style == Typesetter::STYLE_OUTLINE)
+ {
+ // Reset the position offset for the next glyph
+ glyphData.horizontalOffset += glyphData.glyphBitmap.outlineOffsetX;
+ glyphData.verticalOffset += glyphData.glyphBitmap.outlineOffsetY;
+ }
+
+ // free the glyphBitmap.buffer if it is owner of buffer
+ if(glyphData.glyphBitmap.isBufferOwned)
+ {
+ free(glyphData.glyphBitmap.buffer);
+ glyphData.glyphBitmap.isBufferOwned = false;
+ }
+ glyphData.glyphBitmap.buffer = NULL;
+ }
+
+ if(hyphenIndices)
+ {
+ while((hyphenIndex < hyphensCount) && (glyphIndex > hyphenIndices[hyphenIndex]))
+ {
+ hyphenIndex++;
+ }
+
+ addHyphen = ((hyphenIndex < hyphensCount) && ((glyphIndex + 1) == hyphenIndices[hyphenIndex]));
+ if(addHyphen)
+ {
+ glyphIndex--;
+ }
+ }
+ }
+
+ // Draw the underline from the leftmost glyph to the rightmost glyph
+ if(thereAreUnderlinedGlyphs && style == Typesetter::STYLE_UNDERLINE)
+ {
+ DrawUnderline(bufferWidth, bufferHeight, glyphData, baseline, currentUnderlinePosition, maxUnderlineHeight, lineExtentLeft, lineExtentRight, modelUnderlineProperties, currentUnderlineProperties, line);
+ }
+
+ // Draw the background color from the leftmost glyph to the rightmost glyph
+ if(style == Typesetter::STYLE_BACKGROUND)
+ {
+ DrawBackgroundColor(mModel->GetBackgroundColor(), bufferWidth, bufferHeight, glyphData, baseline, line, lineExtentLeft, lineExtentRight);
+ }
+
+ // Draw the strikethrough from the leftmost glyph to the rightmost glyph
+ if(thereAreStrikethroughGlyphs && style == Typesetter::STYLE_STRIKETHROUGH)
+ {
+ //TODO : The currently implemented strikethrough creates a strikethrough on the line level. We need to create different strikethroughs the case of glyphs with different sizes.
+ strikethroughStartingYPosition = (glyphData.verticalOffset + baseline + currentUnderlinePosition) - ((line.ascender) * HALF); // Since Free Type font doesn't contain the strikethrough-position property, strikethrough position will be calculated by moving the underline position upwards by half the value of the line height.
+ DrawStrikethrough(bufferWidth, bufferHeight, glyphData, baseline, strikethroughStartingYPosition, maxStrikethroughHeight, lineExtentLeft, lineExtentRight, modelStrikethroughProperties, currentStrikethroughProperties, line);
+ }
+
+ // Increases the vertical offset with the line's descender & line spacing.
+ glyphData.verticalOffset += static_cast<int32_t>(-line.descender + GetPostOffsetVerticalLineAlignment(line, verLineAlign));
+ }
+
+ return glyphData.bitmapBuffer;
+}
+
+Devel::PixelBuffer Typesetter::ApplyUnderlineMarkupImageBuffer(Devel::PixelBuffer topPixelBuffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset)
+{
// Underline-tags (this is for Markup case)
// Get the underline runs.
- const Length numberOfUnderlineRuns = viewModel.GetNumberOfUnderlineRuns();
+ const Length numberOfUnderlineRuns = mModel->GetNumberOfUnderlineRuns();
Vector<UnderlinedGlyphRun> underlineRuns;
underlineRuns.Resize(numberOfUnderlineRuns);
- viewModel.GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
+ mModel->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns);
// Iterate on the consecutive underlined glyph run and connect them into one chunk of underlined characters.
Vector<UnderlinedGlyphRun>::ConstIterator itGlyphRun = underlineRuns.Begin();
endGlyphIndex = startGlyphIndex + itGlyphRun->glyphRun.numberOfGlyphs - 1;
// Create the image buffer for underline
- Devel::PixelBuffer underlineImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, horizontalOffset, verticalOffset, startGlyphIndex, endGlyphIndex);
+ Devel::PixelBuffer underlineImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_UNDERLINE, ignoreHorizontalAlignment, pixelFormat, horizontalOffset, verticalOffset, startGlyphIndex, endGlyphIndex);
// Combine the two buffers
// Result pixel buffer will be stored into topPixelBuffer.
CombineImageBuffer(underlineImageBuffer, topPixelBuffer, bufferWidth, bufferHeight, false);
Devel::PixelBuffer Typesetter::ApplyStrikethroughMarkupImageBuffer(Devel::PixelBuffer topPixelBuffer, const uint32_t bufferWidth, const uint32_t bufferHeight, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset)
{
- // Use l-value to make ensure it is not nullptr, so compiler happy.
- auto& viewModel = *(mImpl->GetViewModel());
-
// strikethrough-tags (this is for Markup case)
// Get the strikethrough runs.
- const Length numberOfStrikethroughRuns = viewModel.GetNumberOfStrikethroughRuns();
+ const Length numberOfStrikethroughRuns = mModel->GetNumberOfStrikethroughRuns();
Vector<StrikethroughGlyphRun> strikethroughRuns;
strikethroughRuns.Resize(numberOfStrikethroughRuns);
- viewModel.GetStrikethroughRuns(strikethroughRuns.Begin(), 0u, numberOfStrikethroughRuns);
+ mModel->GetStrikethroughRuns(strikethroughRuns.Begin(), 0u, numberOfStrikethroughRuns);
// Iterate on the consecutive strikethrough glyph run and connect them into one chunk of strikethrough characters.
Vector<StrikethroughGlyphRun>::ConstIterator itGlyphRun = strikethroughRuns.Begin();
endGlyphIndex = startGlyphIndex + itGlyphRun->glyphRun.numberOfGlyphs - 1;
// Create the image buffer for strikethrough
- Devel::PixelBuffer strikethroughImageBuffer = mImpl->CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_STRIKETHROUGH, ignoreHorizontalAlignment, pixelFormat, horizontalOffset, verticalOffset, startGlyphIndex, endGlyphIndex);
+ Devel::PixelBuffer strikethroughImageBuffer = CreateImageBuffer(bufferWidth, bufferHeight, Typesetter::STYLE_STRIKETHROUGH, ignoreHorizontalAlignment, pixelFormat, horizontalOffset, verticalOffset, startGlyphIndex, endGlyphIndex);
// Combine the two buffers
// Result pixel buffer will be stored into topPixelBuffer.
CombineImageBuffer(strikethroughImageBuffer, topPixelBuffer, bufferWidth, bufferHeight, false);
uint32_t* topBuffer = reinterpret_cast<uint32_t*>(topPixelBuffer.GetBuffer());
uint32_t* bottomBuffer = reinterpret_cast<uint32_t*>(bottomPixelBuffer.GetBuffer());
- if(topBuffer == nullptr || bottomBuffer == nullptr)
+ if(topBuffer == NULL || bottomBuffer == NULL)
{
// Nothing to do if one of both buffers are empty.
return;
for(uint32_t pixelIndex = 0; pixelIndex < bufferSizeInt; ++pixelIndex)
{
- uint32_t topBufferColor = *(topBuffer);
- uint32_t bottomBufferColor = *(bottomBuffer);
- uint8_t* __restrict__ topBufferColorBuffer = reinterpret_cast<uint8_t*>(&topBufferColor);
+ uint32_t topBufferColor = *(topBuffer);
+ uint32_t bottomBufferColor = *(bottomBuffer);
+ uint8_t* __restrict__ topBufferColorBuffer = reinterpret_cast<uint8_t*>(&topBufferColor);
uint8_t* __restrict__ bottomBufferColorBuffer = reinterpret_cast<uint8_t*>(&bottomBufferColor);
// Return the transparency of the text to original.
uint8_t originAlphaInt = originAlpha * 255;
- uint8_t topAlpha = topBufferColorBuffer[3];
+ uint8_t topAlpha = topBufferColorBuffer[3];
uint8_t bottomAlpha = 255 - topAlpha;
// Manual blending.
}
Typesetter::Typesetter(const ModelInterface* const model)
-: mImpl{std::make_unique<Impl>(model)}
+: mModel(new ViewModel(model)),
+ mFontClient()
{
+ // Default font client set.
+ mFontClient = TextAbstraction::FontClient::Get();
}
-Typesetter::~Typesetter() = default;
+Typesetter::~Typesetter()
+{
+ delete mModel;
+}
} // namespace Text
#define DALI_TOOLKIT_TEXT_TYPESETTER_H
/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ * Copyright (c) 2022 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
// EXTERNAL INCLUDES
#include <dali-toolkit/devel-api/text/text-enumerations-devel.h>
#include <dali/devel-api/adaptor-framework/pixel-buffer.h>
-#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/devel-api/text-abstraction/text-abstraction-definitions.h>
+#include <dali/devel-api/text-abstraction/font-client.h>
#include <dali/public-api/common/intrusive-ptr.h>
#include <dali/public-api/images/pixel-data.h>
#include <dali/public-api/images/pixel.h>
#include <dali/public-api/object/ref-object.h>
-#include <memory> ///< for std::unique_ptr
namespace Dali
{
// Declared private and left undefined to avoid copies.
Typesetter& operator=(const Typesetter& handle);
+ /**
+ * @brief Create & draw the image buffer for the given range of the glyphs in the given style.
+ *
+ * Does the following operations:
+ * - Retrieves the data buffers from the text model.
+ * - Creates the pixel data used to generate the final image with the given size.
+ * - Traverse the visible glyphs, retrieve their bitmaps and compose the final pixel data.
+ *
+ * @param[in] bufferWidth The width of the image buffer.
+ * @param[in] bufferHeight The height of the image buffer.
+ * @param[in] style The style of the text.
+ * @param[in] ignoreHorizontalAlignment Whether to ignore the horizontal alignment, not ignored by default.
+ * @param[in] pixelFormat The format of the pixel in the image that the text is rendered as (i.e. either Pixel::BGRA8888 or Pixel::L8).
+ * @param[in] horizontalOffset The horizontal offset to be added to the glyph's position.
+ * @param[in] verticalOffset The vertical offset to be added to the glyph's position.
+ * @param[in] fromGlyphIndex The index of the first glyph within the text to be drawn
+ * @param[in] toGlyphIndex The index of the last glyph within the text to be drawn
+ *
+ * @return An image buffer with the text.
+ */
+ Devel::PixelBuffer CreateImageBuffer(const uint32_t bufferWidth, const uint32_t bufferHeight, const Typesetter::Style style, const bool ignoreHorizontalAlignment, const Pixel::Format pixelFormat, const int32_t horizontalOffset, const int32_t verticalOffset, const TextAbstraction::GlyphIndex fromGlyphIndex, const TextAbstraction::GlyphIndex toGlyphIndex);
+
/**
* @brief Apply markup underline tags.
*
virtual ~Typesetter();
private:
- struct Impl;
- std::unique_ptr<Impl> mImpl;
+ ViewModel* mModel;
+ TextAbstraction::FontClient mFontClient;
};
} // namespace Text
*hashTargetPtr++ = (size.GetHeight() >> 8u) & 0xff;
// Bit-pack the FittingMode, SamplingMode.
- // FittingMode=3bits, SamplingMode=4bits
- *hashTargetPtr = (fittingMode << 4u) | (samplingMode);
+ // FittingMode=2bits, SamplingMode=3bits
+ *hashTargetPtr = (fittingMode << 3u) | (samplingMode);
}
// Append whether we will not correction orientation. We don't do additional job when it is true, the general cases.
float scaleFactor; ///< The scale factor to apply to the Texture when masking
int32_t referenceCount; ///< The reference count of clients using this Texture
LoadState loadState; ///< The load state showing the load progress of the Texture
- Dali::FittingMode::Type fittingMode : 4; ///< The requested FittingMode
- Dali::SamplingMode::Type samplingMode : 5; ///< The requested SamplingMode
+ Dali::FittingMode::Type fittingMode : 3; ///< The requested FittingMode
+ Dali::SamplingMode::Type samplingMode : 3; ///< The requested SamplingMode
StorageType storageType; ///< CPU storage / GPU upload;
Dali::AnimatedImageLoading animatedImageLoading; ///< AnimatedImageLoading that contains animated image information.
uint32_t frameIndex; ///< Frame index that be loaded, in case of animated image
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, SCALE_TO_FILL)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_WIDTH)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, FIT_HEIGHT)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, VISUAL_FITTING)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::FittingMode, DEFAULT)
DALI_ENUM_TO_STRING_TABLE_END(FITTING_MODE)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LINEAR)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NO_FILTER)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DONT_CARE)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, LANCZOS)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LANCZOS)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DEFAULT)
DALI_ENUM_TO_STRING_TABLE_END(SAMPLING_MODE)
// stop behavior
mActionStatus(DevelAnimatedImageVisual::Action::PLAY),
mWrapModeU(WrapMode::DEFAULT),
mWrapModeV(WrapMode::DEFAULT),
- mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
mFittingMode(FittingMode::VISUAL_FITTING),
mSamplingMode(SamplingMode::BOX_THEN_LINEAR),
+ mStopBehavior(DevelImageVisual::StopBehavior::CURRENT_FRAME),
mStartFirstFrame(false),
mIsJumpTo(false)
{
Dali::WrapMode::Type mWrapModeU : 3;
Dali::WrapMode::Type mWrapModeV : 3;
+ Dali::FittingMode::Type mFittingMode : 3;
+ Dali::SamplingMode::Type mSamplingMode : 4;
DevelImageVisual::StopBehavior::Type mStopBehavior : 2;
- Dali::FittingMode::Type mFittingMode : 4;
- Dali::SamplingMode::Type mSamplingMode : 5;
bool mStartFirstFrame : 1;
bool mIsJumpTo : 1;
};
mObserver(observer),
mMaskingData(maskingData),
mDesiredSize(size),
+ mFittingMode(fittingMode),
+ mSamplingMode(samplingMode),
mBatchSize(batchSize),
mInterval(interval),
mLoadState(TextureManager::LoadState::NOT_STARTED),
- mFittingMode(fittingMode),
- mSamplingMode(samplingMode),
mRequestingLoad(false),
mPreMultiplyOnLoad(preMultiplyOnLoad)
{
FrameReadyObserver& mObserver;
TextureManager::MaskingDataPointer& mMaskingData;
Dali::ImageDimensions mDesiredSize;
+ Dali::FittingMode::Type mFittingMode : 3;
+ Dali::SamplingMode::Type mSamplingMode : 4;
uint32_t mBatchSize;
uint32_t mInterval;
TextureManager::LoadState mLoadState;
- Dali::FittingMode::Type mFittingMode : 4;
- Dali::SamplingMode::Type mSamplingMode : 5;
bool mRequestingLoad : 1;
bool mPreMultiplyOnLoad : 1;
};
oss << "[";
oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
oss << "s:" << mWidth << "x" << mHeight << " ";
- oss << "f:" << mCurrentFrame;
- if(mDroppedFrames > 0)
- {
- oss << "(+" << mDroppedFrames << ")";
- }
- oss << " ";
+ oss << "f:" << mCurrentFrame << " ";
oss << "l:" << mCurrentLoop << " ";
oss << "p:" << mPlayState << " ";
oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
}
else
{
- uint32_t droppedFrames = 0;
const auto durationMicroSeconds = std::chrono::microseconds(mFrameDurationMicroSeconds);
mNextFrameStartTime = std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + durationMicroSeconds);
if(mNextFrameStartTime < current)
{
+ uint32_t droppedFrames = 0;
+
while(current > std::chrono::time_point_cast<TimePoint::duration>(mNextFrameStartTime + durationMicroSeconds) && droppedFrames < mTotalFrame)
{
droppedFrames++;
}
mNextFrameStartTime = current;
+ mDroppedFrames = droppedFrames;
}
- mDroppedFrames = droppedFrames;
}
return mNextFrameStartTime;
if(DALI_LIKELY(!mDestroyThread))
{
- if(mSleepTimePoint != timeToSleepUntil) ///< Trigger only if new time point is changed.
- {
- mSleepTimePoint = timeToSleepUntil;
- mNeedToSleep = true;
- mConditionalWait.Notify(lock);
- }
+ mSleepTimePoint = timeToSleepUntil;
+ mNeedToSleep = true;
+ mConditionalWait.Notify(lock);
}
}
{
bool needToSleep = false;
+ std::chrono::time_point<std::chrono::steady_clock> sleepTimePoint;
+
{
ConditionalWait::ScopedLock lock(mConditionalWait);
+ Mutex::ScopedLock sleepLock(mSleepRequestMutex);
- ConditionalWait::TimePoint sleepTimePoint;
-
+ if(DALI_LIKELY(!mDestroyThread))
{
- Mutex::ScopedLock sleepLock(mSleepRequestMutex);
+ needToSleep = mNeedToSleep;
+ sleepTimePoint = mSleepTimePoint;
- if(DALI_LIKELY(!mDestroyThread))
- {
- needToSleep = mNeedToSleep;
- sleepTimePoint = mSleepTimePoint;
- mNeedToSleep = false;
- }
+ mNeedToSleep = false;
}
+ }
- if(DALI_LIKELY(!mDestroyThread))
- {
- DALI_TRACE_BEGIN_WITH_MESSAGE_GENERATOR(gTraceFilter, "VECTOR_ANIMATION_SLEEP_THREAD", [&](std::ostringstream& oss) {
- oss << "[";
- if(needToSleep)
- {
- auto currentTime = std::chrono::steady_clock::now();
- auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(sleepTimePoint - currentTime);
- oss << duration.count() << " ms]";
- }
- else
- {
- oss << "until notify]";
- }
- });
+ if(needToSleep)
+ {
+ DALI_TRACE_SCOPE(gTraceFilter, "VECTOR_ANIMATION_SLEEP_THREAD");
- if(needToSleep)
- {
- mConditionalWait.WaitUntil(lock, sleepTimePoint);
- }
- else
+ std::this_thread::sleep_until(sleepTimePoint);
+
+ {
+ Mutex::ScopedLock awakeLock(mAwakeCallbackMutex);
+ if(DALI_LIKELY(mAwakeCallback))
{
- mConditionalWait.Wait(lock);
+ CallbackBase::Execute(*mAwakeCallback);
}
-
- DALI_TRACE_END(gTraceFilter, "VECTOR_ANIMATION_SLEEP_THREAD");
}
}
- if(DALI_LIKELY(!mDestroyThread) && needToSleep)
{
- Mutex::ScopedLock awakeLock(mAwakeCallbackMutex);
- if(DALI_LIKELY(mAwakeCallback))
+ ConditionalWait::ScopedLock lock(mConditionalWait);
+ if(DALI_LIKELY(!mDestroyThread) && !mNeedToSleep)
{
- // Awake out of ConditionalWait::ScopedLock to avoid deadlock.
- CallbackBase::Execute(*mAwakeCallback);
+ DALI_TRACE_SCOPE(gTraceFilter, "VECTOR_ANIMATION_SLEEP_THREAD_WAIT");
+ mConditionalWait.Wait(lock);
}
}
}
{
namespace Internal
{
+
namespace
{
+
constexpr VisualFactoryCache::ShaderType SHADER_TYPE_TABLE[] = {
VisualFactoryCache::COLOR_SHADER,
VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER,
VisualFactoryCache::ShaderType::COLOR_SHADER,
VisualFactoryCache::ShaderType::COLOR_SHADER_ROUNDED_CORNER,
};
-} // namespace
+}
namespace ColorVisualShaderFeature
{
+
FeatureBuilder::FeatureBuilder()
: mColorRoundCorner(RoundedCorner::DISABLED),
mColorBorderline(Borderline::DISABLED),
VisualFactoryCache::ShaderType FeatureBuilder::GetShaderType() const
{
- VisualFactoryCache::ShaderType shaderType = VisualFactoryCache::COLOR_SHADER;
- uint32_t shaderTypeFlag = ColorVisualRequireFlag::DEFAULT;
+ VisualFactoryCache::ShaderType shaderType = VisualFactoryCache::COLOR_SHADER;
+ uint32_t shaderTypeFlag = ColorVisualRequireFlag::DEFAULT;
if(mColorBlur)
{
shaderTypeFlag |= ColorVisualRequireFlag::BLUR;
{
vertexShaderPrefixList += "#define IS_REQUIRED_BLUR\n";
}
- if(mColorBorderline == Borderline::ENABLED && mColorBlur == Blur::DISABLED)
+ if(mColorBorderline == Borderline::ENABLED && mColorBlur == RoundedCorner::DISABLED)
{
vertexShaderPrefixList += "#define IS_REQUIRED_BORDERLINE\n";
}
fragmentShaderPrefixList += "#define SL_VERSION_LOW\n";
}
}
- if(mColorBorderline == Borderline::ENABLED && mColorBlur == Blur::DISABLED)
+ if(mColorBorderline == Borderline::ENABLED && mColorBlur == RoundedCorner::DISABLED)
{
fragmentShaderPrefixList += "#define IS_REQUIRED_BORDERLINE\n";
}
Shader ColorVisualShaderFactory::GetShader(VisualFactoryCache& factoryCache, const ColorVisualShaderFeature::FeatureBuilder& featureBuilder)
{
Shader shader;
- VisualFactoryCache::ShaderType shaderType = featureBuilder.GetShaderType();
- shader = factoryCache.GetShader(shaderType);
+ VisualFactoryCache::ShaderType shaderType = featureBuilder.GetShaderType();
+ shader = factoryCache.GetShader(shaderType);
if(!shader)
{
shader = factoryCache.GenerateAndSaveShader(shaderType, vertexShader, fragmentShader);
}
return shader;
+
}
bool ColorVisualShaderFactory::AddPrecompiledShader(PrecompileShaderOption& option)
{
ShaderFlagList shaderOption = option.GetShaderOptions();
- auto featureBuilder = ColorVisualShaderFeature::FeatureBuilder();
+ auto featureBuilder = ColorVisualShaderFeature::FeatureBuilder();
std::string vertexPrefixList;
std::string fragmentPrefixList;
CreatePrecompileShader(featureBuilder, shaderOption);
VisualFactoryCache::ShaderType type = featureBuilder.GetShaderType();
featureBuilder.GetVertexShaderPrefixList(vertexPrefixList);
featureBuilder.GetFragmentShaderPrefixList(fragmentPrefixList);
- return SavePrecompileShader(type, std::move(vertexPrefixList), std::move(fragmentPrefixList));
+ return SavePrecompileShader(type, vertexPrefixList, fragmentPrefixList );
}
-void ColorVisualShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders)
+void ColorVisualShaderFactory::GetPreCompiledShader(RawShaderData& shaders)
{
- std::vector<std::string> vertexPrefix;
- std::vector<std::string> fragmentPrefix;
- std::vector<std::string> shaderName;
-
- uint32_t shaderCount = 0;
-
- shaders.shaderCount = 0;
+ std::vector<std::string_view> vertexPrefix;
+ std::vector<std::string_view> fragmentPrefix;
+ std::vector<std::string_view> shaderName;
+ int shaderCount = 0;
+ shaders.shaderCount = 0;
// precompile requested shader first
- for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++ )
{
- vertexPrefix.push_back(std::move(mRequestedPrecompileShader[i].vertexPrefix));
- fragmentPrefix.push_back(std::move(mRequestedPrecompileShader[i].fragmentPrefix));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(mRequestedPrecompileShader[i].vertexPrefix);
+ fragmentPrefix.push_back(mRequestedPrecompileShader[i].fragmentPrefix);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
- // Clean up requested precompile shader list
- mRequestedPrecompileShader.clear();
-
for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; ++i)
{
- vertexPrefix.push_back(std::string(VertexPredefines[i]));
- fragmentPrefix.push_back(std::string(FragmentPredefines[i]));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(VertexPredefines[i]);
+ fragmentPrefix.push_back(FragmentPredefines[i]);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
shaders.vertexShader = SHADER_COLOR_VISUAL_SHADER_VERT;
shaders.fragmentShader = SHADER_COLOR_VISUAL_SHADER_FRAG;
shaders.shaderCount = shaderCount;
- shaders.custom = false;
+ shaders.custom = false;
}
void ColorVisualShaderFactory::CreatePrecompileShader(ColorVisualShaderFeature::FeatureBuilder& builder, const ShaderFlagList& option)
{
for(uint32_t i = 0; i < option.size(); ++i)
{
- switch(option[i])
+ if(option[i] == PrecompileShaderOption::Flag::ROUNDED_CORNER)
+ {
+ builder.EnableRoundCorner(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::BORDERLINE)
+ {
+ builder.EnableBorderLine(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::BLUR_EDGE)
+ {
+ builder.EnableBlur(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::CUTOUT)
{
- case PrecompileShaderOption::Flag::ROUNDED_CORNER:
- {
- builder.EnableRoundCorner(true);
- break;
- }
- case PrecompileShaderOption::Flag::BORDERLINE:
- {
- builder.EnableBorderLine(true);
- break;
- }
- case PrecompileShaderOption::Flag::BLUR_EDGE:
- {
- builder.EnableBlur(true);
- break;
- }
- case PrecompileShaderOption::Flag::CUTOUT:
- {
- builder.EnableCutout(true);
- break;
- }
- default:
- {
- DALI_LOG_WARNING("Unknown option[%d]. maybe this type can't use this flag\n", static_cast<int>(option[i]));
- break;
- }
+ builder.EnableCutout(true);
}
}
}
-bool ColorVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix)
+bool ColorVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix)
{
- for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; i++)
+ for(uint32_t i = 0u; i< PREDEFINED_SHADER_TYPE_COUNT; i++)
{
if(ShaderTypePredefines[i] == shader)
{
- DALI_LOG_WARNING("This shader already added list(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
- for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0u; i< mRequestedPrecompileShader.size(); i++)
{
if(mRequestedPrecompileShader[i].type == shader)
{
- DALI_LOG_WARNING("This shader already requsted(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
RequestShaderInfo info;
- info.type = shader;
- info.vertexPrefix = std::move(vertexPrefix);
- info.fragmentPrefix = std::move(fragmentPrefix);
- mRequestedPrecompileShader.emplace_back(std::move(info));
- DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ info.type = shader;
+ info.vertexPrefix = vertexPrefix;
+ info.fragmentPrefix = fragmentPrefix;
+ mRequestedPrecompileShader.push_back(info);
+ DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)",Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return true;
}
{
namespace Internal
{
+
namespace ColorVisualShaderFeature
{
namespace RoundedCorner
FeatureBuilder& EnableCutout(bool enableCutout);
VisualFactoryCache::ShaderType GetShaderType() const;
- void GetVertexShaderPrefixList(std::string& vertexShaderPrefixList) const;
- void GetFragmentShaderPrefixList(std::string& fragmentShaderPrefixList) const;
+ void GetVertexShaderPrefixList(std::string& vertexShaderPrefixList) const;
+ void GetFragmentShaderPrefixList(std::string& fragmentShaderPrefixList) const;
bool IsEnabledRoundCorner() const
{
/**
* @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
*/
- void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override;
+ void GetPreCompiledShader(RawShaderData& shaders) override;
private:
/**
/**
* @brief Check if cached hash value is valid or not.
*/
- bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix);
+ bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix);
protected:
/**
{
namespace Internal
{
+
CustomShaderFactory::CustomShaderFactory()
{
}
bool CustomShaderFactory::AddPrecompiledShader(PrecompileShaderOption& option)
{
- auto shaderName = option.GetShaderName();
- auto vertexShader = option.GetVertexShader();
+ auto shaderName = option.GetShaderName();
+ auto vertexShader = option.GetVertexShader();
auto fragmentShader = option.GetFragmentShader();
- return SavePrecompileShader(std::move(shaderName), std::move(vertexShader), std::move(fragmentShader));
+ return SavePrecompileShader(shaderName, vertexShader, fragmentShader);
}
-void CustomShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders)
+void CustomShaderFactory::GetPreCompiledShader(RawShaderData& shaders)
{
- std::vector<std::string> vertexPrefix;
- std::vector<std::string> fragmentPrefix;
- std::vector<std::string> shaderName;
-
- uint32_t shaderCount = 0;
-
- shaders.shaderCount = 0;
+ std::vector<std::string_view> vertexPrefix;
+ std::vector<std::string_view> fragmentPrefix;
+ std::vector<std::string_view> shaderName;
+ int shaderCount = 0;
+ shaders.shaderCount = 0;
// precompile requested shader first
- for(uint32_t i = 0; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0; i < mRequestedPrecompileShader.size(); i++ )
{
- vertexPrefix.push_back(std::move(mRequestedPrecompileShader[i].vertexPrefix));
- fragmentPrefix.push_back(std::move(mRequestedPrecompileShader[i].fragmentPrefix));
- shaderName.push_back(std::move(mRequestedPrecompileShader[i].name));
+ vertexPrefix.push_back(mRequestedPrecompileShader[i].vertexPrefix);
+ fragmentPrefix.push_back(mRequestedPrecompileShader[i].fragmentPrefix);
+ shaderName.push_back(mRequestedPrecompileShader[i].name);
shaderCount++;
}
- // Clean up requested precompile shader list
- mRequestedPrecompileShader.clear();
-
shaders.vertexPrefix = std::move(vertexPrefix);
shaders.fragmentPrefix = std::move(fragmentPrefix);
shaders.shaderName = std::move(shaderName);
shaders.vertexShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
shaders.fragmentShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
- shaders.shaderCount = shaderCount;
- shaders.custom = true;
+ shaders.shaderCount = std::move(shaderCount);
+ shaders.custom = true;
}
-bool CustomShaderFactory::SavePrecompileShader(std::string&& shaderName, std::string&& vertexShader, std::string&& fragmentShader)
+bool CustomShaderFactory::SavePrecompileShader(std::string& shaderName, std::string& vertexShader, std::string& fragmentShader)
{
- DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)", shaderName.c_str());
-
RequestShaderInfo info;
- info.type = VisualFactoryCache::SHADER_TYPE_MAX; ///< Not be used
- info.name = std::move(shaderName);
- info.vertexPrefix = std::move(vertexShader);
- info.fragmentPrefix = std::move(fragmentShader);
- mRequestedPrecompileShader.emplace_back(std::move(info));
+ info.name = shaderName;
+ info.vertexPrefix = vertexShader;
+ info.fragmentPrefix = fragmentShader;
+ mRequestedPrecompileShader.push_back(info);
+ DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)",shaderName.c_str());
return true;
}
{
namespace Internal
{
+
/**
* CustomShaderFactory is an object that provides custom shader
*/
/**
* @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
*/
- void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override;
+ void GetPreCompiledShader(RawShaderData& shaders) override;
private:
/**
* @brief Save the custom shader
*/
- bool SavePrecompileShader(std::string&& shaderName, std::string&& vertexPrefix, std::string&& fragmentPrefix);
+ bool SavePrecompileShader(std::string& shaderName, std::string& vertexPrefix, std::string& fragmentPrefix);
protected:
/**
VisualFactoryCache::ShaderType type = featureBuilder.GetShaderType();
featureBuilder.GetVertexShaderPrefixList(vertexPrefixList);
featureBuilder.GetFragmentShaderPrefixList(fragmentPrefixList);
- return SavePrecompileShader(type, std::move(vertexPrefixList), std::move(fragmentPrefixList));
+ return SavePrecompileShader(type, vertexPrefixList, fragmentPrefixList);
}
-void ImageVisualShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders)
+void ImageVisualShaderFactory::GetPreCompiledShader(RawShaderData& shaders)
{
- std::vector<std::string> vertexPrefix;
- std::vector<std::string> fragmentPrefix;
- std::vector<std::string> shaderName;
-
- uint32_t shaderCount = 0;
-
+ std::vector<std::string_view> vertexPrefix;
+ std::vector<std::string_view> fragmentPrefix;
+ std::vector<std::string_view> shaderName;
shaders.shaderCount = 0;
+ int shaderCount = 0;
- // precompile requested shader first
- for(uint32_t i = 0; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
{
- vertexPrefix.push_back(std::move(mRequestedPrecompileShader[i].vertexPrefix));
- fragmentPrefix.push_back(std::move(mRequestedPrecompileShader[i].fragmentPrefix));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(mRequestedPrecompileShader[i].vertexPrefix);
+ fragmentPrefix.push_back(mRequestedPrecompileShader[i].fragmentPrefix);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
- // Clean up requested precompile shader list
- mRequestedPrecompileShader.clear();
-
for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; ++i)
{
- vertexPrefix.push_back(std::string(VertexPredefines[i]));
- fragmentPrefix.push_back(std::string(FragmentPredefines[i]));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(VertexPredefines[i]);
+ fragmentPrefix.push_back(FragmentPredefines[i]);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
{
for(uint32_t i = 0; i < option.size(); ++i)
{
- switch(option[i])
+ if(option[i] == PrecompileShaderOption::Flag::ATLAS_DEFAULT)
{
- case PrecompileShaderOption::Flag::ATLAS_DEFAULT:
- {
- builder.EnableTextureAtlas(true);
- builder.ApplyDefaultTextureWrapMode(true);
- break;
- }
- case PrecompileShaderOption::Flag::ATLAS_CUSTOM:
- {
- builder.EnableTextureAtlas(true);
- builder.ApplyDefaultTextureWrapMode(false);
- break;
- }
- case PrecompileShaderOption::Flag::ROUNDED_CORNER:
- {
- builder.EnableRoundedCorner(true);
- break;
- }
- case PrecompileShaderOption::Flag::BORDERLINE:
- {
- builder.EnableBorderline(true);
- break;
- }
- case PrecompileShaderOption::Flag::MASKING:
- {
- builder.EnableAlphaMaskingOnRendering(true);
- break;
- }
- case PrecompileShaderOption::Flag::YUV_TO_RGB:
- {
- builder.EnableYuvToRgb(true, false);
- break;
- }
- case PrecompileShaderOption::Flag::YUV_AND_RGB:
- {
- builder.EnableYuvToRgb(false, true);
- break;
- }
- default:
- {
- DALI_LOG_WARNING("Unknown option[%d]. maybe this type can't use this flag\n", static_cast<int>(option[i]));
- break;
- }
+ builder.EnableTextureAtlas(true);
+ builder.ApplyDefaultTextureWrapMode(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::ATLAS_CUSTOM)
+ {
+ builder.EnableTextureAtlas(true);
+ builder.ApplyDefaultTextureWrapMode(false);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::ROUNDED_CORNER)
+ {
+ builder.EnableRoundedCorner(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::BORDERLINE)
+ {
+ builder.EnableBorderline(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::MASKING)
+ {
+ builder.EnableAlphaMaskingOnRendering(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::YUV_TO_RGB)
+ {
+ builder.EnableYuvToRgb(true, false);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::YUV_AND_RGB)
+ {
+ builder.EnableYuvToRgb(false, true);
}
}
}
-bool ImageVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix)
+bool ImageVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix)
{
for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; i++)
{
if(ShaderTypePredefines[i] == shader)
{
- DALI_LOG_WARNING("This shader already added list(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
{
if(mRequestedPrecompileShader[i].type == shader)
{
- DALI_LOG_WARNING("This shader already requsted(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
RequestShaderInfo info;
info.type = shader;
- info.vertexPrefix = std::move(vertexPrefix);
- info.fragmentPrefix = std::move(fragmentPrefix);
- mRequestedPrecompileShader.emplace_back(std::move(info));
- DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ info.vertexPrefix = vertexPrefix;
+ info.fragmentPrefix = fragmentPrefix;
+ mRequestedPrecompileShader.push_back(info);
+ DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return true;
}
{
namespace Internal
{
+
/**
* ImageVisualShaderFactory is an object that provides and shares shaders between image visuals
*/
/**
* @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
*/
- void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override;
+ void GetPreCompiledShader(RawShaderData& shaders) override;
private:
/**
/**
* @brief Check if cached hash value is valid or not.
*/
- bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix);
+ bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix);
protected:
/**
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LINEAR)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, NO_FILTER)
DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DONT_CARE)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, LANCZOS)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, BOX_THEN_LANCZOS)
- DALI_ENUM_TO_STRING_WITH_SCOPE(Dali::SamplingMode, DEFAULT)
DALI_ENUM_TO_STRING_TABLE_END(SAMPLING_MODE)
// wrap modes
constexpr uint32_t TEXTURE_COUNT_FOR_GPU_ALPHA_MASK = 2u;
-constexpr uint32_t MINIMUM_SHADER_VERSION_SUPPORT_UNIFIED_YUV_AND_RGB = 300;
-
struct NameIndexMatch
{
const char* const name;
!mUseSynchronousSizing &&
!atlasing &&
!mImpl->mCustomShader &&
- !(mMaskingData && mMaskingData->mAlphaMaskUrl.IsValid()) &&
- !(DALI_UNLIKELY(Dali::Shader::GetShaderLanguageVersion() < MINIMUM_SHADER_VERSION_SUPPORT_UNIFIED_YUV_AND_RGB)))
+ !(mMaskingData && mMaskingData->mAlphaMaskUrl.IsValid()))
{
return true;
}
else if(mUseFastTrackUploading)
{
- DALI_LOG_DEBUG_INFO("FastTrack : Fail to load fast track. mUrl : [%s]%s%s%s%s%s%s%s%s%s%s\n",
+ DALI_LOG_DEBUG_INFO("FastTrack : Fail to load fast track. mUrl : [%s]%s%s%s%s%s%s%s%s%s\n",
mImageUrl.GetEllipsedUrl().c_str(),
(mLoadPolicy != Toolkit::ImageVisual::LoadPolicy::ATTACHED) ? "/ mLoadPolicy != ATTACHED" : "",
(mReleasePolicy != Toolkit::ImageVisual::ReleasePolicy::DETACHED) ? "/ mReleasePolicy != DETACHED" : "",
(mUseSynchronousSizing) ? "/ useSynchronousSizing " : "",
(atlasing) ? "/ atlasing" : "",
(mImpl->mCustomShader) ? "/ use customs shader" : "",
- (mMaskingData && mMaskingData->mAlphaMaskUrl.IsValid()) ? "/ use masking url" : "",
- (Dali::Shader::GetShaderLanguageVersion() < MINIMUM_SHADER_VERSION_SUPPORT_UNIFIED_YUV_AND_RGB) ? "/ gles version is low" : "");
+ (mMaskingData && mMaskingData->mAlphaMaskUrl.IsValid()) ? "/ use masking url" : "");
}
return false;
};
}
}
}
+ else if(createForce)
+ {
+ // Create default quad geometry now
+ geometry = CreateGeometry(mFactoryCache, ImageDimensions(1, 1));
+ }
}
}
- if(!geometry && createForce)
- {
- // Create default quad geometry now
- geometry = CreateGeometry(mFactoryCache, ImageDimensions(1, 1));
- }
-
return geometry;
}
* "BOX_THEN_LINEAR"
* "NO_FILTER"
* "DONT_CARE"
- * "LANCZOS"
- * "BOX_THEN_LANCZOS"
* "DEFAULT"
*
* where loadPolicy should be one of the following image loading modes
ImageVisualShaderFactory& mImageVisualShaderFactory;
- Dali::FittingMode::Type mFittingMode : 4;
- Dali::SamplingMode::Type mSamplingMode : 5;
+ Dali::FittingMode::Type mFittingMode : 3;
+ Dali::SamplingMode::Type mSamplingMode : 4;
Dali::WrapMode::Type mWrapModeU : 3;
Dali::WrapMode::Type mWrapModeV : 3;
Dali::Toolkit::ImageVisual::LoadPolicy::Type mLoadPolicy;
--- /dev/null
+/*
+ * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// CLASS HEADER
+#include <dali-toolkit/internal/visuals/npatch-shader-factory.h>
+
+// INTERNAL INCLUDES
+#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
+#include <dali-toolkit/internal/visuals/visual-string-constants.h>
+#include <dali/integration-api/debug.h>
+
+namespace Dali
+{
+namespace Toolkit
+{
+namespace Internal
+{
+
+NpatchShaderFactory::NpatchShaderFactory()
+: mNpatchXStretchCount(0),
+ mNpatchYStretchCount(0),
+ mNpatchMaskingEnable(false)
+{
+}
+
+NpatchShaderFactory::~NpatchShaderFactory()
+{
+}
+
+bool NpatchShaderFactory::AddPrecompiledShader(PrecompileShaderOption& option)
+{
+ ShaderFlagList shaderOption = option.GetShaderOptions();
+
+ // Find Masking flag
+ for(uint32_t i = 0; i < shaderOption.size(); ++i)
+ {
+ if(shaderOption[i] == PrecompileShaderOption::Flag::MASKING)
+ {
+ mNpatchMaskingEnable = true;
+ }
+ }
+
+ mNpatchXStretchCount = option.GetNpatchXStretchCount();
+ mNpatchYStretchCount = option.GetNpatchYStretchCount();
+
+ std::string vertexShader;
+ std::string fragmentShader;
+ GetVertexShader(vertexShader);
+ GetFragmentShader(fragmentShader);
+
+ VisualFactoryCache::ShaderType shaderType = mNpatchMaskingEnable? VisualFactoryCache::ShaderType::NINE_PATCH_MASK_SHADER : VisualFactoryCache::ShaderType::NINE_PATCH_SHADER;
+ return SavePrecompileShader(shaderType, vertexShader, fragmentShader);
+}
+
+void NpatchShaderFactory::GetPreCompiledShader(RawShaderData& shaders)
+{
+ std::vector<std::string_view> vertexPrefix;
+ std::vector<std::string_view> fragmentPrefix;
+ std::vector<std::string_view> shaderName;
+ int shaderCount = 0;
+ shaders.shaderCount = 0;
+
+ // precompile requested shader first
+ for(uint32_t i = 0; i < mRequestedPrecompileShader.size(); i++ )
+ {
+ vertexPrefix.push_back(mRequestedPrecompileShader[i].vertexPrefix);
+ fragmentPrefix.push_back(mRequestedPrecompileShader[i].fragmentPrefix);
+ shaderName.push_back(mRequestedPrecompileShader[i].name);
+ shaderCount++;
+ }
+
+ shaders.vertexPrefix = std::move(vertexPrefix);
+ shaders.fragmentPrefix = std::move(fragmentPrefix);
+ shaders.shaderName = std::move(shaderName);
+ shaders.vertexShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
+ shaders.fragmentShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
+ shaders.shaderCount = std::move(shaderCount);
+ shaders.custom = true;
+}
+
+void NpatchShaderFactory::GetVertexShader(std::string& vertexShader) const
+{
+ if(DALI_LIKELY((mNpatchXStretchCount == 1 && mNpatchYStretchCount == 1) ||
+ (mNpatchXStretchCount == 0 && mNpatchYStretchCount == 0)))
+ {
+ vertexShader += SHADER_NPATCH_VISUAL_3X3_SHADER_VERT;
+ }
+ else if(mNpatchXStretchCount > 0 || mNpatchYStretchCount > 0)
+ {
+ std::stringstream vertextShaderStream;
+ vertextShaderStream << "#define FACTOR_SIZE_X " << mNpatchXStretchCount + 2 << "\n"
+ << "#define FACTOR_SIZE_Y " << mNpatchYStretchCount + 2 << "\n"
+ << SHADER_NPATCH_VISUAL_SHADER_VERT;
+ vertexShader += vertextShaderStream.str();
+ }
+}
+
+void NpatchShaderFactory::GetFragmentShader(std::string& fragmentShader) const
+{
+ fragmentShader += (mNpatchMaskingEnable ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG : SHADER_NPATCH_VISUAL_SHADER_FRAG);
+}
+
+bool NpatchShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexShader, std::string& fragmentShader)
+{
+ for(uint32_t i = 0u; i< mRequestedPrecompileShader.size(); i++)
+ {
+ if(mRequestedPrecompileShader[i].type == shader)
+ {
+ DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ return false;
+ }
+ }
+
+ std::string shaderName = Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT);
+ if(!((mNpatchXStretchCount == 1 && mNpatchYStretchCount == 1) || (mNpatchXStretchCount == 0 && mNpatchYStretchCount == 0)))
+ {
+ if(mNpatchXStretchCount > 0 || mNpatchYStretchCount > 0)
+ {
+ std::stringstream shaderNameStream;
+ shaderNameStream << "NINE_PATCH_SHADER_" << mNpatchXStretchCount << "x" << mNpatchYStretchCount;
+ shaderName = shaderNameStream.str();
+ }
+ }
+
+ RequestShaderInfo info;
+ info.type = shader;
+ info.name = shaderName;
+ info.vertexPrefix = vertexShader;
+ info.fragmentPrefix = fragmentShader;
+ mRequestedPrecompileShader.push_back(info);
+ DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)",Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ return true;
+}
+
+
+} // namespace Internal
+
+} // namespace Toolkit
+
+} // namespace Dali
--- /dev/null
+#ifndef DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
+#define DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
+
+/*
+ * Copyright (c) 2024 Samsung Electronics Co., Ltd.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+// EXTERNAL INCLUDES
+#include <dali/integration-api/adaptor-framework/shader-precompiler.h>
+
+// INTERNAL INCLUDES
+#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
+#include <dali-toolkit/internal/visuals/visual-shader-factory-interface.h>
+#include <string_view>
+
+namespace Dali
+{
+namespace Toolkit
+{
+namespace Internal
+{
+
+/**
+ * NpatchShaderFactory is an object that provides custom shader
+ */
+class NpatchShaderFactory : public VisualShaderFactoryInterface
+{
+public:
+ /**
+ * @brief Constructor
+ */
+ NpatchShaderFactory();
+
+ /**
+ * @brief Destructor
+ */
+ ~NpatchShaderFactory() override;
+
+public: // Implementation of VisualShaderFactoryInterface
+ /**
+ * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::AddPrecompiledShader
+ */
+ bool AddPrecompiledShader(PrecompileShaderOption& option) override;
+
+ /**
+ * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
+ */
+ void GetPreCompiledShader(RawShaderData& shaders) override;
+
+private:
+ /**
+ * @brief Get the NPatch vertex shader. this is used for generating pre-compiled shader.
+ */
+ void GetVertexShader(std::string& vertexShader) const;
+
+ /**
+ * @brief Get the NPatch fragment shader. this is used for generating pre-compiled shader
+ */
+ void GetFragmentShader(std::string& fragmentShader) const;
+
+ /**
+ * @brief Save the npatch shader
+ */
+ bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix);
+
+protected:
+ /**
+ * Undefined copy constructor.
+ */
+ NpatchShaderFactory(const NpatchShaderFactory&) = delete;
+
+ /**
+ * Undefined assignment operator.
+ */
+ NpatchShaderFactory& operator=(const NpatchShaderFactory& rhs) = delete;
+
+private:
+ // For Npatch
+ uint32_t mNpatchXStretchCount;
+ uint32_t mNpatchYStretchCount;
+ bool mNpatchMaskingEnable;
+};
+
+} // namespace Internal
+
+} // namespace Toolkit
+
+} // namespace Dali
+
+#endif // DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// CLASS HEADER
-#include <dali-toolkit/internal/visuals/npatch/npatch-shader-factory.h>
-
-// INTERNAL INCLUDES
-#include <dali-toolkit/internal/graphics/builtin-shader-extern-gen.h>
-#include <dali-toolkit/internal/visuals/visual-string-constants.h>
-#include <dali/integration-api/debug.h>
-
-namespace Dali
-{
-namespace Toolkit
-{
-namespace Internal
-{
-NpatchShaderFactory::NpatchShaderFactory()
-: mNpatchXStretchCount(0),
- mNpatchYStretchCount(0),
- mNpatchMaskingEnable(false)
-{
-}
-
-NpatchShaderFactory::~NpatchShaderFactory()
-{
-}
-
-bool NpatchShaderFactory::AddPrecompiledShader(PrecompileShaderOption& option)
-{
- ShaderFlagList shaderOption = option.GetShaderOptions();
-
- // Find Masking flag
- for(uint32_t i = 0; i < shaderOption.size(); ++i)
- {
- if(shaderOption[i] == PrecompileShaderOption::Flag::MASKING)
- {
- mNpatchMaskingEnable = true;
- }
- }
-
- mNpatchXStretchCount = option.GetNpatchXStretchCount();
- mNpatchYStretchCount = option.GetNpatchYStretchCount();
-
- std::string vertexShader;
- std::string fragmentShader;
- GetVertexShader(vertexShader);
- GetFragmentShader(fragmentShader);
-
- VisualFactoryCache::ShaderType shaderType = mNpatchMaskingEnable ? VisualFactoryCache::ShaderType::NINE_PATCH_MASK_SHADER : VisualFactoryCache::ShaderType::NINE_PATCH_SHADER;
- return SavePrecompileShader(shaderType, std::move(vertexShader), std::move(fragmentShader));
-}
-
-void NpatchShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders)
-{
- std::vector<std::string> vertexPrefix;
- std::vector<std::string> fragmentPrefix;
- std::vector<std::string> shaderName;
-
- uint32_t shaderCount = 0;
-
- shaders.shaderCount = 0;
-
- // precompile requested shader first
- for(uint32_t i = 0; i < mRequestedPrecompileShader.size(); i++)
- {
- vertexPrefix.push_back(std::move(mRequestedPrecompileShader[i].vertexPrefix));
- fragmentPrefix.push_back(std::move(mRequestedPrecompileShader[i].fragmentPrefix));
- shaderName.push_back(std::move(mRequestedPrecompileShader[i].name));
- shaderCount++;
- }
-
- // Clean up requested precompile shader list
- mRequestedPrecompileShader.clear();
-
- shaders.vertexPrefix = std::move(vertexPrefix);
- shaders.fragmentPrefix = std::move(fragmentPrefix);
- shaders.shaderName = std::move(shaderName);
- shaders.vertexShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
- shaders.fragmentShader = ""; // Custom shader use prefix shader only. No need to set vertexShader and fragmentShader.
- shaders.shaderCount = shaderCount;
- shaders.custom = true; ///< Note that npatch shader is kind of custom shader.
-}
-
-void NpatchShaderFactory::GetVertexShader(std::string& vertexShader) const
-{
- if(DALI_LIKELY((mNpatchXStretchCount == 1 && mNpatchYStretchCount == 1) ||
- (mNpatchXStretchCount == 0 && mNpatchYStretchCount == 0)))
- {
- vertexShader += SHADER_NPATCH_VISUAL_3X3_SHADER_VERT;
- }
- else if(mNpatchXStretchCount > 0 || mNpatchYStretchCount > 0)
- {
- std::stringstream vertextShaderStream;
- vertextShaderStream << "#define FACTOR_SIZE_X " << mNpatchXStretchCount + 2 << "\n"
- << "#define FACTOR_SIZE_Y " << mNpatchYStretchCount + 2 << "\n"
- << SHADER_NPATCH_VISUAL_SHADER_VERT;
- vertexShader += vertextShaderStream.str();
- }
-}
-
-void NpatchShaderFactory::GetFragmentShader(std::string& fragmentShader) const
-{
- fragmentShader += (mNpatchMaskingEnable ? SHADER_NPATCH_VISUAL_MASK_SHADER_FRAG : SHADER_NPATCH_VISUAL_SHADER_FRAG);
-}
-
-bool NpatchShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexShader, std::string&& fragmentShader)
-{
- for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
- {
- if(mRequestedPrecompileShader[i].type == shader)
- {
- DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
- return false;
- }
- }
-
- std::string shaderName = Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT);
- if(!((mNpatchXStretchCount == 1 && mNpatchYStretchCount == 1) || (mNpatchXStretchCount == 0 && mNpatchYStretchCount == 0)))
- {
- if(mNpatchXStretchCount > 0 || mNpatchYStretchCount > 0)
- {
- std::stringstream shaderNameStream;
- shaderNameStream << "NINE_PATCH_SHADER_" << mNpatchXStretchCount << "x" << mNpatchYStretchCount;
- shaderName = shaderNameStream.str();
- }
- }
-
- DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)", shaderName.c_str());
-
- RequestShaderInfo info;
- info.type = shader;
- info.name = std::move(shaderName);
- info.vertexPrefix = std::move(vertexShader);
- info.fragmentPrefix = std::move(fragmentShader);
- mRequestedPrecompileShader.emplace_back(std::move(info));
- return true;
-}
-
-} // namespace Internal
-
-} // namespace Toolkit
-
-} // namespace Dali
+++ /dev/null
-#ifndef DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
-#define DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
-
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- */
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/adaptor-framework/shader-precompiler.h>
-
-// INTERNAL INCLUDES
-#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/internal/visuals/visual-shader-factory-interface.h>
-#include <string_view>
-
-namespace Dali
-{
-namespace Toolkit
-{
-namespace Internal
-{
-/**
- * NpatchShaderFactory is an object that provides custom shader
- */
-class NpatchShaderFactory : public VisualShaderFactoryInterface
-{
-public:
- /**
- * @brief Constructor
- */
- NpatchShaderFactory();
-
- /**
- * @brief Destructor
- */
- ~NpatchShaderFactory() override;
-
-public: // Implementation of VisualShaderFactoryInterface
- /**
- * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::AddPrecompiledShader
- */
- bool AddPrecompiledShader(PrecompileShaderOption& option) override;
-
- /**
- * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
- */
- void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override;
-
-private:
- /**
- * @brief Get the NPatch vertex shader. this is used for generating pre-compiled shader.
- */
- void GetVertexShader(std::string& vertexShader) const;
-
- /**
- * @brief Get the NPatch fragment shader. this is used for generating pre-compiled shader
- */
- void GetFragmentShader(std::string& fragmentShader) const;
-
- /**
- * @brief Save the npatch shader
- */
- bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix);
-
-protected:
- /**
- * Undefined copy constructor.
- */
- NpatchShaderFactory(const NpatchShaderFactory&) = delete;
-
- /**
- * Undefined assignment operator.
- */
- NpatchShaderFactory& operator=(const NpatchShaderFactory& rhs) = delete;
-
-private:
- // For Npatch
- uint32_t mNpatchXStretchCount;
- uint32_t mNpatchYStretchCount;
- bool mNpatchMaskingEnable;
-};
-
-} // namespace Internal
-
-} // namespace Toolkit
-
-} // namespace Dali
-
-#endif // DALI_TOOLKIT_NPATCH_SHADER_FACTORY_H
DALI_LOG_ERROR("Rasterize is failed!\n");
DALI_TRACE_END_WITH_MESSAGE_GENERATOR(gTraceFilter, "DALI_SVG_RASTERIZE_TASK", [&](std::ostringstream& oss) {
mEndTimeNanoSceonds = GetNanoseconds();
- oss << std::fixed << std::setprecision(3);
- oss << "[failed/";
+ oss << "[";
oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
oss << "s:" << mWidth << "x" << mHeight << " ";
oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
oss << "[";
oss << "d:" << static_cast<float>(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms ";
oss << "s:" << mWidth << "x" << mHeight << " ";
- if(mPixelData.GetWidth() != mWidth || mPixelData.GetHeight() != mHeight)
- {
- oss << "p:" << mPixelData.GetWidth() << "x" << mPixelData.GetHeight() << " ";
- }
oss << "u:" << mImageUrl.GetEllipsedUrl() << "]";
});
}
if(DALI_LIKELY(vectorImageRenderer))
{
vectorImageRenderer.GetDefaultSize(mDefaultWidth, mDefaultHeight);
- if(mImpl->mEventObserver && mImpl->mFittingMode != DevelVisual::FittingMode::DONT_CARE)
- {
- // Need teo call ApplyFittingMode once again, after load completed.
- mImpl->mEventObserver->RelayoutRequest(*this);
- }
}
else if(!mLoadFailed)
{
Shader TextVisualShaderFactory::GetShader(VisualFactoryCache& factoryCache, const TextVisualShaderFeature::FeatureBuilder& featureBuilder)
{
Shader shader;
- VisualFactoryCache::ShaderType shaderType = featureBuilder.GetShaderType();
- shader = factoryCache.GetShader(shaderType);
+ VisualFactoryCache::ShaderType shaderType = featureBuilder.GetShaderType();
+ shader = factoryCache.GetShader(shaderType);
if(!shader)
{
{
ShaderFlagList shaderOption = option.GetShaderOptions();
- auto featureBuilder = TextVisualShaderFeature::FeatureBuilder();
+ auto featureBuilder = TextVisualShaderFeature::FeatureBuilder();
std::string vertexPrefixList;
std::string fragmentPrefixList;
CreatePrecompileShader(featureBuilder, shaderOption);
VisualFactoryCache::ShaderType type = featureBuilder.GetShaderType();
featureBuilder.GetVertexShaderPrefixList(vertexPrefixList);
featureBuilder.GetFragmentShaderPrefixList(fragmentPrefixList);
- return SavePrecompileShader(type, std::move(vertexPrefixList), std::move(fragmentPrefixList));
+ return SavePrecompileShader(type, vertexPrefixList, fragmentPrefixList );
}
-void TextVisualShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders)
-{
- std::vector<std::string> vertexPrefix;
- std::vector<std::string> fragmentPrefix;
- std::vector<std::string> shaderName;
- uint32_t shaderCount = 0;
+void TextVisualShaderFactory::GetPreCompiledShader(RawShaderData& shaders)
+{
+ std::vector<std::string_view> vertexPrefix;
+ std::vector<std::string_view> fragmentPrefix;
+ std::vector<std::string_view> shaderName;
+ int shaderCount = 0;
// precompile requested shader first
- for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++ )
{
- vertexPrefix.push_back(std::move(mRequestedPrecompileShader[i].vertexPrefix));
- fragmentPrefix.push_back(std::move(mRequestedPrecompileShader[i].fragmentPrefix));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(mRequestedPrecompileShader[i].vertexPrefix);
+ fragmentPrefix.push_back(mRequestedPrecompileShader[i].fragmentPrefix);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
- // Clean up requested precompile shader list
- mRequestedPrecompileShader.clear();
-
for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; ++i)
{
- vertexPrefix.push_back(std::string(VertexPredefines[i]));
- fragmentPrefix.push_back(std::string(FragmentPredefines[i]));
- shaderName.push_back(std::string(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)));
+ vertexPrefix.push_back(VertexPredefines[i]);
+ fragmentPrefix.push_back(FragmentPredefines[i]);
+ shaderName.push_back(Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
shaderCount++;
}
shaders.vertexShader = SHADER_TEXT_VISUAL_SHADER_VERT;
shaders.fragmentShader = SHADER_TEXT_VISUAL_SHADER_FRAG;
shaders.shaderCount = shaderCount;
- shaders.custom = false;
+ shaders.custom = false;
}
void TextVisualShaderFactory::CreatePrecompileShader(TextVisualShaderFeature::FeatureBuilder& builder, const ShaderFlagList& option)
{
for(uint32_t i = 0; i < option.size(); ++i)
{
- switch(option[i])
+ if(option[i] == PrecompileShaderOption::Flag::STYLES)
+ {
+ builder.EnableStyle(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::OVERLAY)
+ {
+ builder.EnableOverlay(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::EMOJI)
+ {
+ builder.EnableEmoji(true);
+ }
+ else if(option[i] == PrecompileShaderOption::Flag::MULTI_COLOR)
+ {
+ builder.EnableMultiColor(true);
+ }
+ else
{
- case PrecompileShaderOption::Flag::STYLES:
- {
- builder.EnableStyle(true);
- break;
- }
- case PrecompileShaderOption::Flag::OVERLAY:
- {
- builder.EnableOverlay(true);
- break;
- }
- case PrecompileShaderOption::Flag::EMOJI:
- {
- builder.EnableEmoji(true);
- break;
- }
- case PrecompileShaderOption::Flag::MULTI_COLOR:
- {
- builder.EnableMultiColor(true);
- break;
- }
- default:
- {
- DALI_LOG_WARNING("Unknown option[%d]. maybe this type can't use this flag\n", static_cast<int>(option[i]));
- break;
- }
+ DALI_LOG_WARNING("Unknown option[%d]. maybe this type can't use this flag \n", option[i]);
}
}
}
-bool TextVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix)
+bool TextVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix)
{
- for(uint32_t i = 0u; i < PREDEFINED_SHADER_TYPE_COUNT; i++)
+ for(uint32_t i = 0u; i< PREDEFINED_SHADER_TYPE_COUNT; i++)
{
if(ShaderTypePredefines[i] == shader)
{
- DALI_LOG_WARNING("This shader already added list(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
- for(uint32_t i = 0u; i < mRequestedPrecompileShader.size(); i++)
+ for(uint32_t i = 0u; i< mRequestedPrecompileShader.size(); i++)
{
if(mRequestedPrecompileShader[i].type == shader)
{
- DALI_LOG_WARNING("This shader already requsted(%s).\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return false;
}
}
RequestShaderInfo info;
- info.type = shader;
- info.vertexPrefix = std::move(vertexPrefix);
- info.fragmentPrefix = std::move(fragmentPrefix);
- mRequestedPrecompileShader.emplace_back(std::move(info));
- DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)\n", Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
+ info.type = shader;
+ info.vertexPrefix = vertexPrefix;
+ info.fragmentPrefix = fragmentPrefix;
+ mRequestedPrecompileShader.push_back(info);
+ DALI_LOG_RELEASE_INFO("Add precompile shader success!!(%s)",Scripting::GetLinearEnumerationName<VisualFactoryCache::ShaderType>(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT));
return true;
}
} // namespace Internal
FeatureBuilder& EnableOverlay(bool enableOverlay);
VisualFactoryCache::ShaderType GetShaderType() const;
- void GetVertexShaderPrefixList(std::string& vertexShaderPrefixList) const;
- void GetFragmentShaderPrefixList(std::string& fragmentShaderPrefixList) const;
+ void GetVertexShaderPrefixList(std::string& vertexShaderPrefixList) const;
+ void GetFragmentShaderPrefixList(std::string& fragmentShaderPrefixList) const;
bool IsEnabledMultiColor() const
{
/**
* @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader
*/
- void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override;
+ void GetPreCompiledShader(RawShaderData& shaders) override;
private:
/**
/**
* @brief Check if cached hash value is valid or not.
*/
- bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string&& vertexPrefix, std::string&& fragmentPrefix);
+ bool SavePrecompileShader(VisualFactoryCache::ShaderType shader, std::string& vertexPrefix, std::string& fragmentPrefix);
protected:
/**
WIREFRAME_SHADER,
ARC_BUTT_CAP_SHADER,
ARC_ROUND_CAP_SHADER,
- SHADER_TYPE_MAX
+ SHADER_TYPE_MAX = ARC_ROUND_CAP_SHADER
};
/**
NINE_PATCH_GEOMETRY,
NINE_PATCH_BORDER_GEOMETRY,
WIREFRAME_GEOMETRY,
- GEOMETRY_TYPE_MAX
+ GEOMETRY_TYPE_MAX = WIREFRAME_GEOMETRY
};
public:
uint32_t height;
};
- Geometry mGeometry[GEOMETRY_TYPE_MAX];
- Shader mShader[SHADER_TYPE_MAX];
+ Geometry mGeometry[GEOMETRY_TYPE_MAX + 1];
+ Shader mShader[SHADER_TYPE_MAX + 1];
bool mLoadYuvPlanes; ///< A global flag to specify if the image should be loaded as yuv planes
#include <dali-toolkit/internal/visuals/color/color-visual-shader-factory.h>
#include <dali-toolkit/internal/visuals/color/color-visual.h>
#include <dali-toolkit/internal/visuals/custom-shader-factory.h>
+#include <dali-toolkit/internal/visuals/npatch-shader-factory.h>
#include <dali-toolkit/internal/visuals/gradient/gradient-visual.h>
#include <dali-toolkit/internal/visuals/image/image-visual-shader-factory.h>
#include <dali-toolkit/internal/visuals/image/image-visual.h>
#include <dali-toolkit/internal/visuals/mesh/mesh-visual.h>
-#include <dali-toolkit/internal/visuals/npatch/npatch-shader-factory.h>
#include <dali-toolkit/internal/visuals/npatch/npatch-visual.h>
#include <dali-toolkit/internal/visuals/primitive/primitive-visual.h>
#include <dali-toolkit/internal/visuals/svg/svg-visual.h>
bool VisualFactory::AddPrecompileShader(const Property::Map& map)
{
PrecompileShaderOption shaderOption(map);
- auto type = shaderOption.GetShaderType();
+ auto type = shaderOption.GetShaderType();
if(type == PrecompileShaderOption::ShaderType::UNKNOWN)
{
- DALI_LOG_ERROR("AddPrecompileShader is failed. we can't find shader type\n");
+ DALI_LOG_ERROR("AddPrecompileShader is failed. we can't find shader type");
return false;
}
}
mPrecompiledShaderRequested = true;
- ShaderPreCompiler::Get().Enable(true);
+ ShaderPreCompiler::Get().Enable();
// Get image shader
- ShaderPreCompiler::RawShaderDataList rawShaderList;
- ShaderPreCompiler::RawShaderData imageShaderData;
+ std::vector<RawShaderData> rawShaderList;
+ RawShaderData imageShaderData;
GetImageVisualShaderFactory().GetPreCompiledShader(imageShaderData);
- rawShaderList.emplace_back(std::move(imageShaderData));
+ rawShaderList.push_back(imageShaderData);
// Get text shader
- ShaderPreCompiler::RawShaderData textShaderData;
+ RawShaderData textShaderData;
GetTextVisualShaderFactory().GetPreCompiledShader(textShaderData);
- rawShaderList.emplace_back(std::move(textShaderData));
+ rawShaderList.push_back(textShaderData);
// Get color shader
- ShaderPreCompiler::RawShaderData colorShaderData;
+ RawShaderData colorShaderData;
GetColorVisualShaderFactory().GetPreCompiledShader(colorShaderData);
- rawShaderList.emplace_back(std::move(colorShaderData));
+ rawShaderList.push_back(colorShaderData);
- // Get npatch shader
- ShaderPreCompiler::RawShaderData npatchShaderData;
+ RawShaderData npatchShaderData;
GetNpatchShaderFactory().GetPreCompiledShader(npatchShaderData);
- rawShaderList.emplace_back(std::move(npatchShaderData));
+ rawShaderList.push_back(npatchShaderData);
// Get 3D shader
- // TODO
-
// Get Custom shader
- ShaderPreCompiler::RawShaderData customShaderData;
+ RawShaderData customShaderData;
GetCustomShaderFactory().GetPreCompiledShader(customShaderData);
- rawShaderList.emplace_back(std::move(customShaderData));
+ rawShaderList.push_back(customShaderData);
// Save all shader
- ShaderPreCompiler::Get().SavePreCompileShaderList(std::move(rawShaderList));
+ ShaderPreCompiler::Get().SavePreCompileShaderList(rawShaderList);
}
Internal::TextureManager& VisualFactory::GetTextureManager()
bool VisualFactory::AddPrecompileShader(PrecompileShaderOption& option)
{
auto type = option.GetShaderType();
- bool ret = false;
+ bool ret = false;
switch(type)
{
case PrecompileShaderOption::ShaderType::COLOR:
case PrecompileShaderOption::ShaderType::NPATCH:
{
ret = GetNpatchShaderFactory().AddPrecompiledShader(option);
- break;
}
case PrecompileShaderOption::ShaderType::MODEL_3D:
{
}
default:
{
- DALI_LOG_ERROR("AddPrecompileShader is failed. we can't find shader factory type:%d\n", type);
+ DALI_LOG_ERROR("AddPrecompileShader is failed. we can't find shader factory type:%d",type);
break;
}
}
#include <dali/integration-api/adaptor-framework/shader-precompiler.h>
// INTERNAL INCLUDES
+#include <dali-toolkit/public-api/dali-toolkit-common.h>
#include <dali-toolkit/devel-api/visual-factory/precompile-shader-option.h>
#include <dali-toolkit/internal/visuals/visual-factory-cache.h>
-#include <dali-toolkit/public-api/dali-toolkit-common.h>
namespace Dali
{
namespace Toolkit
{
-using HashType = uint64_t;
+
+using HashType = uint64_t;
using ShaderFlagList = std::vector<PrecompileShaderOption::Flag>;
namespace Internal
class VisualShaderFactoryInterface
{
public:
+
/**
* @brief Structure to request shader info from visual shader factory.
*/
struct RequestShaderInfo
{
- VisualFactoryCache::ShaderType type{VisualFactoryCache::ShaderType::SHADER_TYPE_MAX};
- std::string name{};
- std::string vertexPrefix{};
- std::string fragmentPrefix{};
+ VisualFactoryCache::ShaderType type;
+ std::string name;
+ std::string vertexPrefix;
+ std::string fragmentPrefix;
};
- VisualShaderFactoryInterface() = default;
+ VisualShaderFactoryInterface() = default;
virtual ~VisualShaderFactoryInterface() = default;
/**
* @brief Get precompiled shader for precompile
* @param[out] shaders shaderList for precompile
*/
- virtual void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) = 0;
+ virtual void GetPreCompiledShader(RawShaderData& shaders) = 0;
protected:
std::vector<RequestShaderInfo> mRequestedPrecompileShader;
Dali::Toolkit::Control ownerControl(GetOwner());
object->SetOwnerControl(ownerControl);
-
- SetOffScreenRenderableType(object->GetOffScreenRenderableType());
}
}
}
}
mImpl->mRenderEffect.Reset();
}
- SetOffScreenRenderableType(OffScreenRenderable::NONE);
}
void Control::SetResourceReady()
controlDataImpl.ResourceReady();
}
-Dali::Actor Control::GetOffScreenRenderableSourceActor()
-{
- // Need to override this in FORWARD OffScreenRenderable
- return Dali::Actor();
-}
-
-bool Control::IsOffScreenRenderTaskExclusive()
-{
- return false;
-}
-
std::shared_ptr<Toolkit::DevelControl::ControlAccessible> Control::GetAccessibleObject()
{
return mImpl->GetAccessibleObject();
}
break;
}
+ case Actor::Property::VISIBLE:
+ {
+ auto accessible = GetAccessibleObject();
+ if(DALI_LIKELY(accessible) && accessible->IsHighlighted())
+ {
+ accessible->EmitVisible(Self().GetProperty<bool>(Actor::Property::VISIBLE));
+ }
+ break;
+ }
case DevelActor::Property::USER_INTERACTION_ENABLED:
{
const bool enabled = propertyValue.Get<bool>();
// @todo size negotiate background to new size, animate as well?
}
-void Control::GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward)
-{
- if(mImpl->mRenderEffect)
- {
- Toolkit::Internal::RenderEffectImpl* object = dynamic_cast<Toolkit::Internal::RenderEffectImpl*>(mImpl->mRenderEffect.GetObjectPtr());
-
- if(object)
- {
- object->GetOffScreenRenderTasks(tasks, isForward);
- }
- }
-}
-
bool Control::OnKeyEvent(const KeyEvent& event)
{
return false; // Do not consume
*/
void SetResourceReady();
- /**
- * @brief Retrieves SourceActor of the OffScreenRenderable.
- *
- * @SINCE_2_3.43
- * @return SourceActor of the OffScreenRenderable.
- */
- virtual Dali::Actor GetOffScreenRenderableSourceActor();
-
- /**
- * @brief Retrieves whether the OffScreen RenderTasks is exclusive or not.
- * The SourceActor of an OffScreen RenderTask can also become the SourceActor of another Actor's OffScreen RenderTask.
- * To draw the SourceActor multitimes, the exclusive information is required.
- *
- * @SINCE_2_3.43
- * @return True if the RenderTask is exclusive.
- */
- virtual bool IsOffScreenRenderTaskExclusive();
-
// Accessibility
/**
*/
void OnSizeAnimation(Animation& animation, const Vector3& targetSize) override;
- /**
- * @copydoc CustomActorImpl::GetOffScreenRenderTasks()
- */
- void GetOffScreenRenderTasks(std::vector<Dali::RenderTask>& tasks, bool isForward) override;
-
/**
* @copydoc CustomActorImpl::OnRelayout()
*/
{
const unsigned int TOOLKIT_MAJOR_VERSION = 2;
const unsigned int TOOLKIT_MINOR_VERSION = 3;
-const unsigned int TOOLKIT_MICRO_VERSION = 44;
+const unsigned int TOOLKIT_MICRO_VERSION = 41;
const char* const TOOLKIT_BUILD_DATE = __DATE__ " " __TIME__;
#ifdef DEBUG_ENABLED
+++ /dev/null
-<manifest>
- <request>
- <domain name="_" />
- </request>
-</manifest>
+++ /dev/null
-<manifest>
- <assign>
- <filesystem path="/usr/lib/*" label="_" />
- </assign>
- <request>
- <domain name="dali"/>
- </request>
-</manifest>
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <dali-toolkit/public-api/dali-toolkit-common.h>
-
-// INTERNAL INCLUDES
-#include <dali-usd-loader/internal/usd-loader-impl.h>
-
-namespace Dali::Scene3D::Loader
-{
-extern "C" DALI_TOOLKIT_API Dali::Scene3D::Loader::ModelLoaderImpl* CreateUsdLoader()
-{
- return new UsdLoaderImpl();
-}
-} // namespace Dali::Scene3D::Loader
+++ /dev/null
-set(usd_loader_internal_dir ${usd_loader_dir}/internal)
-
-set(usd_loader_src_files ${usd_loader_src_files}
- ${usd_loader_internal_dir}/usd-loader-impl.cpp
- ${usd_loader_internal_dir}/create-usd-loader.cpp
-)
+++ /dev/null
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// FILE HEADER
-#include <dali-usd-loader/internal/usd-loader-impl.h>
-
-// EXTERNAL INCLUDES
-#include <dali/integration-api/debug.h>
-
-#include <pxr/usd/ar/asset.h>
-#include <pxr/usd/ar/resolvedPath.h>
-#include <pxr/usd/ar/resolver.h>
-#include <pxr/usd/usd/prim.h>
-#include <pxr/usd/usd/primRange.h>
-#include <pxr/usd/usd/stage.h>
-#include <pxr/usd/usdGeom/camera.h>
-#include <pxr/usd/usdGeom/mesh.h>
-#include <pxr/usd/usdGeom/primvarsAPI.h>
-#include <pxr/usd/usdGeom/xformCommonAPI.h>
-#include <pxr/usd/usdGeom/xformable.h>
-#include <pxr/usd/usdShade/material.h>
-#include <pxr/usd/usdShade/materialBindingAPI.h>
-#include <pxr/usd/usdSkel/animation.h>
-#include <pxr/usd/usdSkel/bindingAPI.h>
-#include <pxr/usd/usdSkel/root.h>
-#include <pxr/usd/usdSkel/skeleton.h>
-#include <pxr/usd/usdSkel/utils.h>
-
-// INTERNAL INCLUDES
-#include <dali-scene3d/public-api/loader/load-result.h>
-#include <dali-scene3d/public-api/loader/utils.h>
-
-using namespace Dali;
-using namespace pxr;
-using namespace Dali::Scene3D::Loader;
-
-namespace Dali::Scene3D::Loader
-{
-namespace
-{
-const Vector3 CAMERA_DEFAULT_POSITION(0.0f, 0.0f, 3.5f);
-
-#ifdef DEBUG_ENABLED
-Debug::Filter* gLogFilter = Debug::Filter::New(Debug::NoLogging, false, "LOG_USD_LOADER");
-#endif
-
-// Utility function to print a specific number of indentation levels
-void PrintLevel(int level)
-{
- for(int i = 0; i < level; i++)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " ");
- }
-}
-
-// Convert a USD matrix to a DALi Matrix
-Matrix ConvertUsdMatrix(const GfMatrix4d& gfMat)
-{
- std::vector<float> matData(gfMat.data(), gfMat.data() + 16);
- return Matrix(matData.data());
-}
-
-// Template function to retrieve the value of a USD attribute, handling time samples if available
-template<typename T>
-T GetAttributeValue(UsdAttribute attribute, T& value)
-{
- std::vector<double> times;
- attribute.GetTimeSamples(×);
- if(times.size() > 0u)
- {
- attribute.Get<T>(&value, times[0]);
- }
- else
- {
- attribute.Get<T>(&value, UsdTimeCode::Default());
- }
-
- return value;
-}
-
-// Template function to retrieve the flattened value of a USD geometry primvar (e.g., color, normals)
-template<typename T>
-VtArray<T> GetFlattenedPrimvarValue(UsdGeomPrimvar primvar, VtArray<T>& value)
-{
- std::vector<double> times;
- primvar.GetAttr().GetTimeSamples(×);
-
- if(times.size() > 0u)
- {
- primvar.ComputeFlattened<T>(&value, times[0]);
- }
- else
- {
- primvar.ComputeFlattened<T>(&value, UsdTimeCode::Default());
- }
-
- return value;
-}
-
-// Recursively traverses connected shader inputs to collect all relevant shaders
-std::vector<UsdShadeShader> TraverseShaderInputs(const UsdShadeShader& shader)
-{
- std::vector<UsdShadeShader> matches;
-
- for(const auto& i : shader.GetInputs())
- {
- if(i.HasConnectedSource())
- {
- for(const auto& s : i.GetConnectedSources())
- {
- if(s)
- {
- matches.push_back(s.source);
- auto nestedMatches = TraverseShaderInputs(s.source);
- matches.insert(matches.end(), nestedMatches.begin(), nestedMatches.end());
- }
- }
- }
- }
-
- return matches;
-}
-
-// Triangulates polygonal faces based on their vertex indices, converting them into triangles.
-//
-// USD can store mesh data in polygons with more than three sides (n-gons). When preparing for
-// rendering, these n-gons must be converted into triangles. This function takes an array of
-// vertex counts per face (e.g., quads, pentagons) and converts these faces into triangles by
-// generating new vertex indices that represent the triangulated mesh.
-//
-// The process of triangulation involves breaking down these polygons (which may have 4, 5,
-// or more vertices) into a set of triangles. Each n-sided polygon is split into n-2 triangles.
-// For example, a quad (4 vertices) is split into two triangles. Triangulation also considers
-// the coordinate system's handedness (left-handed or right-handed), which affects the winding
-// order of vertices in the triangles.
-template<typename T>
-VtArray<T> GetTriangulatedAttribute(const VtArray<int>& countArray, const VtArray<T>& indexArray, bool isLeftHanded)
-{
- VtArray<T> returnArray;
- int j = 0;
-
- // Iterate over each polygon in the count array
- for(int count : countArray)
- {
- // Extract the indices for the current polygon
- const VtArray<T> poly(indexArray.begin() + j, indexArray.begin() + j + count);
-
- // Triangulate the polygon (assumes convex polygons)
- for(int i = 0; i < count - 2; ++i)
- {
- // Append triangulated indices to the return array
- if(isLeftHanded)
- {
- // Left-handed winding order
- returnArray.push_back(poly[0]);
- returnArray.push_back(poly[i + 2]);
- returnArray.push_back(poly[i + 1]);
- }
- else
- {
- // Right-handed winding order
- returnArray.push_back(poly[0]);
- returnArray.push_back(poly[i + 1]);
- returnArray.push_back(poly[i + 2]);
- }
- }
-
- // Move to the next polygon
- j += count;
- }
-
- return returnArray;
-}
-
-// Converts a USD image path to a standard path format
-std::string ConvertImagePath(const std::string& input)
-{
- std::string result = input;
-
- // Find the position of '[' and ']'
- size_t startPos = result.find('[');
- size_t endPos = result.find(']');
-
- if(startPos != std::string::npos && endPos != std::string::npos)
- {
- // Extract the substring between '[' and ']'
- std::string extracted = result.substr(startPos + 1, endPos - startPos - 1);
-
- // Find the last '/' in the extracted string between '[' and ']'
- size_t lastSlashPosInExtracted = extracted.rfind('/', endPos);
- if(lastSlashPosInExtracted != std::string::npos)
- {
- extracted.erase(0, lastSlashPosInExtracted + 1);
- }
-
- // Find the last '/' before '[' in the original path
- size_t lastSlashPos = result.rfind('/', startPos);
- if(lastSlashPos != std::string::npos)
- {
- result.erase(lastSlashPos + 1, endPos - lastSlashPos + 1);
- result.insert(lastSlashPos + 1, extracted);
- }
- }
-
- return result;
-}
-
-// Loads a USD asset file as a memory buffer (vector of uint8_t)
-std::vector<uint8_t> LoadAssetFileAsBuffer(const std::string resolvedAssetPath)
-{
- std::shared_ptr<ArAsset> const asset = ArGetResolver().OpenAsset(ArResolvedPath(resolvedAssetPath));
-
- if(asset)
- {
- std::shared_ptr<const char> const buffer = asset->GetBuffer();
- if(buffer)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "LoadAssetFileAsBuffer: %s, size: %lu", ArResolvedPath(resolvedAssetPath).GetPathString().c_str(), asset->GetSize());
-
- // Convert the buffer to a vector of uint8_t
- return std::vector<uint8_t>(buffer.get(), buffer.get() + asset->GetSize());
- }
- }
-
- // Return an empty vector if loading fails
- return std::vector<uint8_t>();
-}
-
-} // namespace
-
-struct UsdLoaderImpl::Impl
-{
-public:
- /**
- * @brief Traverses materials in the USD scene and populate the output.
- * @param[in, out] output The load result.
- */
- void TraverseMaterials(LoadResult& output);
-
- /**
- * @brief Traverses prims in the USD scene and populate the output.
- * @param[in, out] output The load result.
- * @param[in] prim The current USD prim being traversed.
- * @param[in] parentIndex The index of the parent node in the hierarchy.
- * @param[in] level The level of nesting in the hierarchy.
- */
- void TraversePrims(LoadResult& output, const UsdPrim& prim, Index parentIndex, int level);
-
-private:
- /**
- * @brief Converts a mesh prim to the internal representation.
- * @param[in, out] output The load result.
- * @param[in] prim The USD prim representing the mesh.
- * @param[in, out] nodeIndex The index of the current node.
- * @param[in] parentIndex The index of the parent node.
- */
- void ConvertMesh(LoadResult& output, const UsdPrim& prim, Index& nodeIndex, Index parentIndex);
-
- /**
- * @brief Converts a node prim to the internal representation.
- * @param[in, out] output The load result.
- * @param[in] prim The USD prim representing the node.
- * @param[in, out] nodeIndex The index of the current node.
- * @param[in] parentIndex The index of the parent node.
- */
- void ConvertNode(LoadResult& output, const UsdPrim& prim, Index& nodeIndex, Index parentIndex);
-
- /**
- * @brief Converts a camera prim to the internal representation.
- * @param[in, out] output The load result.
- * @param[in] prim The USD prim representing the camera.
- */
- void ConvertCamera(LoadResult& output, const UsdPrim& prim);
-
- /**
- * @brief Converts a texture associated with a material to the internal representation.
- * @param[in] usdMaterial The USD material.
- * @param[in] usdUvTexture The USD UV texture.
- * @param[in, out] materialDefinition The material definition.
- * @param[in] semantic The semantic information of the texture.
- * @return True if conversion successful, false otherwise.
- */
- bool ConvertTexture(const UsdShadeMaterial& usdMaterial, const UsdShadeShader& usdUvTexture, MaterialDefinition& materialDefinition, uint32_t semantic = 0u);
-
- /**
- * @brief Extracts the transformation (position, rotation, scale) of a given USD primitive.
- *
- * This function retrieves the local transformation matrix of a USD prim and decomposes it into
- * position, rotation, and scale components.
- *
- * @param[in] prim The USD primitive from which to extract the transformation.
- * @param[out] position The extracted position vector.
- * @param[out] rotation The extracted rotation quaternion.
- * @param[out] scale The extracted scale vector.
- * @param[in] time The time at which to sample the transformation.
- */
- void GetXformableTransformation(const UsdPrim& prim, Vector3& position, Quaternion& rotation, Vector3& scale, const UsdTimeCode time = UsdTimeCode::Default());
-
- /**
- * @brief Adds a node to the scene graph and optionally sets its transformation.
- *
- * This function creates a new node based on a USD primitive and adds it to the scene graph.
- * Optionally, it can set the transformation of the node (position, rotation, scale).
- *
- * @param[in,out] scene The scene definition to which the node will be added.
- * @param[in] nodeName The name of the node to be added.
- * @param[in] parentIndex The index of the parent node in the scene graph.
- * @param[in] position The position of the node (if setting transformation).
- * @param[in] rotation The rotation of the node (if setting transformation).
- * @param[in] scale The scale of the node (if setting transformation).
- * @param[in] setTransformation Whether to apply the transformation to the node.
- * @return A pointer to the created node definition.
- */
- NodeDefinition* AddNodeToScene(SceneDefinition& scene, const std::string nodeName, const Index parentIndex, const Vector3& position, const Quaternion& rotation, const Vector3& scale, bool setTransformation);
-
- /**
- * @brief Retrieves geometric primitive variables from a USD prim.
- *
- * This function extracts texture coordinates (texcoords), vertex colors, and tangent attributes
- * from a USD primitive and categorizes them into separate vectors.
- *
- * @param[in] prim The USD primitive from which to retrieve the primvars.
- * @param[out] texcoords A vector to store the retrieved texture coordinate primvars.
- * @param[out] colors A vector to store the retrieved color primvars.
- * @param[out] tangents A vector to store the retrieved tangent primvars.
- */
- void RetrieveGeomPrimvars(const UsdPrim& prim, std::vector<UsdGeomPrimvar>& texcoords, std::vector<UsdGeomPrimvar>& colors, std::vector<UsdGeomPrimvar>& tangents);
-
- /**
- * @brief Processes and stores mesh indices in the mesh definition.
- *
- * This function processes the triangulated face indices of a mesh, including handling subset indices,
- * and stores them in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition to store the processed indices.
- * @param[in] indexMap A map of the original to triangulated indices.
- * @param[in] subsetIdcs The indices belonging to the current subset.
- * @param[in] triangulatedIndex The triangulated indices for the entire mesh.
- * @param[out] subIndexArray A vector to store the processed subset indices.
- * @param[out] flattenedSubTriangulatedIndices A vector to store the flattened triangulated indices.
- */
- void ProcessMeshIndices(MeshDefinition& meshDefinition, std::map<int, VtArray<int>>& indexMap, VtIntArray& subsetIdcs, VtArray<int>& triangulatedIndex, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices);
-
- /**
- * @brief Processes and stores vertex positions in the mesh definition.
- *
- * This function processes the vertex positions based on the subset indices and stores them
- * in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition to store the processed vertex positions.
- * @param[in] points The original vertex positions.
- * @param[out] worldPosition A vector to store the processed world positions.
- * @param[in] subIndexArray The subset indices used to extract the relevant positions.
- */
- void ProcessMeshPositions(MeshDefinition& meshDefinition, const VtArray<GfVec3f>& points, VtArray<GfVec3f>& worldPosition, std::vector<uint32_t>& subIndexArray);
-
- /**
- * @brief Processes and stores vertex normals in the mesh definition.
- *
- * This function processes the vertex normals, handling both face-varying and vertex-based normals,
- * and stores them in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition to store the processed normals.
- * @param[in] usdMesh The USD mesh primitive.
- * @param[out] normals A vector to store the processed normals.
- * @param[in] subIndexArray The subset indices used to extract the relevant normals.
- * @param[in] flattenedSubTriangulatedIndices The flattened triangulated indices for face-varying normals.
- * @param[in] faceVertexCounts The number of vertices per face.
- * @param[in] isLeftHanded A flag indicating whether the coordinate system is left-handed.
- */
- void ProcessMeshNormals(MeshDefinition& meshDefinition, UsdGeomMesh& usdMesh, VtArray<GfVec3f>& normals, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded);
-
- /**
- * @brief Generates normals for a mesh if none are provided.
- *
- * This function generates normals for a mesh by computing the cross product of adjacent
- * edges for each face. The generated normals are then stored in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition where the generated normals will be stored.
- */
- void GenerateNormal(MeshDefinition& meshDefinition);
-
- /**
- * @brief Processes and stores texture coordinates (UVs) in the mesh definition.
- *
- * This function processes the texture coordinates, handling both face-varying and vertex-based UVs,
- * and stores them in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition to store the processed texture coordinates.
- * @param[in] texcoords A vector of texture coordinate primvars to process.
- * @param[in] subIndexArray The subset indices used to extract the relevant UVs.
- * @param[in] flattenedSubTriangulatedIndices The flattened triangulated indices for face-varying UVs.
- * @param[in] faceVertexCounts The number of vertices per face.
- * @param[in] isLeftHanded A flag indicating whether the coordinate system is left-handed.
- */
- void ProcessMeshTexcoords(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& texcoords, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded);
-
- /**
- * @brief Generates tangent vectors for a mesh.
- *
- * This function generates tangent vectors for a mesh based on its texture coordinates (UVs)
- * and stores them in the mesh definition.
- *
- * @param[in,out] meshDefinition The mesh definition where the generated tangents will be stored.
- * @param[in] texcoords A vector of texture coordinate primvars to assist in tangent generation.
- */
- void GenerateTangents(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& texcoords);
-
- /**
- * @brief Processes and stores vertex colors in the mesh definition.
- *
- * This function processes the vertex colors, handling different interpolation types (constant, vertex, face-varying),
- * and stores them in the mesh definition. If no colors are provided, a default white color is assigned.
- *
- * @param[in,out] meshDefinition The mesh definition to store the processed vertex colors.
- * @param[in] colors A vector of color primvars to process.
- * @param[in] worldPosition The vertex positions to match with colors.
- * @param[in] subIndexArray The subset indices used to extract the relevant colors.
- * @param[in] flattenedSubTriangulatedIndices The flattened triangulated indices for face-varying colors.
- * @param[in] faceVertexCounts The number of vertices per face.
- * @param[in] isLeftHanded A flag indicating whether the coordinate system is left-handed.
- */
- void ProcessMeshColors(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& colors, VtArray<GfVec3f>& worldPosition, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded);
-
- /**
- * @brief Processes and binds materials to a mesh subset within a USD prim.
- *
- * This function retrieves and assigns the appropriate material to a specific subset of a mesh
- * within the USD primitive. It updates the material ID used by the mesh subset in the output data.
- *
- * @param[in,out] output The load result where the material binding will be stored.
- * @param[in] prim The USD primitive containing the mesh and its subsets.
- * @param[in] subsets A vector of geometric subsets (parts of the mesh) within the USD primitive.
- * @param[in] subIndex The index of the subset within the mesh for which the material is being processed.
- * @param[out] meshSubMaterialId The material ID that is associated with the subset. It is updated with the correct ID after processing.
- */
- void ProcessMaterialBinding(LoadResult& output, const UsdPrim& prim, std::vector<UsdGeomSubset>& subsets, size_t subIndex, int& meshSubMaterialId);
-
-public:
- UsdStageRefPtr mUsdStage; ///< Pointer to the USD stage.
-
- std::map<std::string, int> mMaterialMap; ///< Maps prim paths to material IDs.
-
- Index mNodeIndex; ///< Index of the current node being processed.
- int mMeshCount; ///< Count of mesh objects encountered during traversal.
-
- Index mDefaultMaterial; ///< Index of the default material.
-};
-
-UsdLoaderImpl::UsdLoaderImpl()
-: mImpl{new Impl}
-{
-}
-
-UsdLoaderImpl::~UsdLoaderImpl() = default;
-
-bool UsdLoaderImpl::LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result)
-{
- // Open the stage of the USD scene from the specified URL
- mImpl->mUsdStage = UsdStage::Open(url);
- if(!mImpl->mUsdStage)
- {
- DALI_LOG_ERROR("Failed to open %s\n", url.c_str());
- return false;
- }
-
- mImpl->mMeshCount = 0;
- mImpl->mNodeIndex = INVALID_INDEX;
- mImpl->mDefaultMaterial = INVALID_INDEX;
-
- // Traverse materials in the USD scene and populate the result
- mImpl->TraverseMaterials(result);
-
- // Get the index of the root node in the result scene
- Index rootIndex = result.mScene.GetNodeCount();
-
- // Create a node definition for the scene root
- std::unique_ptr<NodeDefinition> sceneRoot{new NodeDefinition()};
- sceneRoot->mName = "USD_SCENE_ROOT_NODE";
-
- // Add the scene root node to the result scene
- result.mScene.AddNode(std::move(sceneRoot));
- result.mScene.AddRootNode(rootIndex);
-
- // Traverse prims in the USD scene and populate the result
- UsdPrim rootPrim = mImpl->mUsdStage->GetPseudoRoot();
- mImpl->TraversePrims(result, rootPrim, rootIndex, 0);
-
- // Set default environment map
- EnvironmentDefinition environmentDefinition;
- environmentDefinition.mUseBrdfTexture = true;
- environmentDefinition.mIblIntensity = Scene3D::Loader::EnvironmentDefinition::GetDefaultIntensity();
- result.mResources.mEnvironmentMaps.push_back({std::move(environmentDefinition), EnvironmentDefinition::Textures()});
-
- return true;
-}
-
-void UsdLoaderImpl::Impl::TraverseMaterials(LoadResult& output)
-{
- auto& outMaterials = output.mResources.mMaterials;
-
- int materialId = 0; // Initialize material ID counter
-
- // Traverse all prims (nodes) in the USD stage
- UsdPrimRange prims = mUsdStage->Traverse();
- for(auto prim : prims)
- {
- // Check if the current prim is a material
- if(prim.IsA<UsdShadeMaterial>())
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdShadeMaterial: %d: %s\n ", materialId, prim.GetPrimPath().GetText());
-
- UsdShadeMaterial material = UsdShadeMaterial(prim);
- UsdShadeOutput surf = material.GetSurfaceOutput();
-
- // If no valid connected sources are found, skip this material
- if(surf.GetConnectedSources().size() == 0)
- {
- DALI_LOG_ERROR("No valid connected sources, ");
- continue;
- }
-
- UsdShadeConnectableAPI previewSurface = surf.GetConnectedSources()[0].source;
- std::vector<UsdShadeInput> inputs = previewSurface.GetInputs();
-
- // Initialize the material definition with default values
- MaterialDefinition materialDefinition;
-
- materialDefinition.mFlags |= MaterialDefinition::GLTF_CHANNELS;
- materialDefinition.mShadowAvailable = true;
-
- materialDefinition.mBaseColorFactor = Vector4::ONE;
- materialDefinition.mEmissiveFactor = Vector3::ZERO;
- materialDefinition.mSpecularFactor = 1.0f;
- materialDefinition.mSpecularColorFactor = Dali::Vector3::ONE;
-
- materialDefinition.mMetallic = 1.0f;
- materialDefinition.mRoughness = 1.0f;
- materialDefinition.mNormalScale = 1.0f;
-
- materialDefinition.mShadowAvailable = true;
- materialDefinition.mDoubleSided = false;
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mMaterialMap[%s] = %d, ", prim.GetPrimPath().GetAsString().c_str(), materialId);
-
- // Map the material path to the material ID
- mMaterialMap[prim.GetPrimPath().GetAsString()] = materialId;
- materialId++;
-
- // Flags to track different material properties
- bool hasAlpha = false;
- bool hasThreshold = false;
- bool needMetallicRoughnessTexture = false;
- bool needMetallicTexture = false;
- bool needRoughnessTexture = false;
- bool needNormalTexture = false;
- bool needAlbedoTexture = false;
-
- float opacityThreshold(0.0f);
-
- std::map<uint32_t, UsdShadeInput> shaderInputMap; // Map of texture semantic and shader input
-
- // Loop through all inputs of the surface shader and sort them to
- // match with the order of texture loading in MaterialDefinition.
- for(auto input : inputs)
- {
- std::string baseName = input.GetBaseName().GetString();
-
- // Handle opacity input
- if(baseName == "opacity")
- {
- UsdAttribute opacityAttr = input.GetAttr();
- float opacity(1.0f);
- if(opacityAttr.HasAuthoredValue())
- {
- GetAttributeValue<float>(opacityAttr, opacity);
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "opacity: %f, ", opacity);
-
- // Set the alpha value in the base color factor
- materialDefinition.mBaseColorFactor.a = opacity;
-
- // Check if the material has transparency
- if(opacity < 1.0f || input.HasConnectedSource())
- {
- hasAlpha = true;
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "hasAlpha: %d, ", hasAlpha);
- }
- else if(baseName == "opacityThreshold")
- {
- // Handle opacity threshold input (for alpha masking)
- UsdAttribute opacityThresholdAttr = input.GetAttr();
- if(opacityThresholdAttr.HasAuthoredValue())
- {
- GetAttributeValue<float>(opacityThresholdAttr, opacityThreshold);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "opacityThreshold: %.7f, ", opacityThreshold);
- }
-
- if(opacityThreshold > 0.0f)
- {
- hasThreshold = true;
- }
- }
- else if(baseName == "ior")
- {
- // Handle index of refraction (ior)
- UsdAttribute iorAttr = input.GetAttr();
- float ior(1.5f);
- if(iorAttr.HasAuthoredValue())
- {
- GetAttributeValue<float>(iorAttr, ior);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "ior: %.7f, ", ior);
-
- materialDefinition.mIor = ior;
- materialDefinition.mDielectricSpecular = powf((materialDefinition.mIor - 1.0f) / (materialDefinition.mIor + 1.0f), 2.0f);
- }
- }
- else if(baseName == "diffuseColor")
- {
- shaderInputMap[MaterialDefinition::ALBEDO] = input;
- }
- else if(baseName == "metallic")
- {
- shaderInputMap[MaterialDefinition::METALLIC] = input;
- }
- else if(baseName == "roughness")
- {
- shaderInputMap[MaterialDefinition::ROUGHNESS] = input;
- }
- else if(baseName == "normal")
- {
- shaderInputMap[MaterialDefinition::NORMAL] = input;
- }
- else if(baseName == "occlusion")
- {
- shaderInputMap[MaterialDefinition::OCCLUSION] = input;
- }
- else if(baseName == "emissiveColor")
- {
- shaderInputMap[MaterialDefinition::EMISSIVE] = input;
- }
- else if(baseName == "specularColor")
- {
- shaderInputMap[MaterialDefinition::SPECULAR_COLOR] = input;
- }
- else if(baseName == "useSpecularWorkflow")
- {
- UsdAttribute useSpecularWorkflowAttr = input.GetAttr();
- int useSpecularWorkflow(0);
- if(useSpecularWorkflowAttr.HasAuthoredValue())
- {
- GetAttributeValue<int>(useSpecularWorkflowAttr, useSpecularWorkflow);
- }
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "useSpecularWorkflow: %d, ", useSpecularWorkflow);
- }
- }
-
- // Process each mapped shader input
- for(auto iter : shaderInputMap)
- {
- UsdShadeInput input = iter.second;
-
- // Check if the input has a connected texture source
- UsdShadeShader uvTexture;
- if(input.HasConnectedSource())
- {
- uvTexture = UsdShadeShader(input.GetConnectedSources()[0].source);
- }
-
- std::string baseName = input.GetBaseName().GetString();
-
- if(baseName == "diffuseColor")
- {
- // Process diffuse color (albedo)
- UsdAttribute diffuseAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "diffuseColorTexture: ");
- needAlbedoTexture = ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::ALBEDO);
- if(needAlbedoTexture)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::ALBEDO, ");
- }
- }
- }
- else
- {
- GfVec3f diffuseColor(0.18f, 0.18f, 0.18f);
- if(diffuseAttr.HasAuthoredValue())
- {
- GetAttributeValue<GfVec3f>(diffuseAttr, diffuseColor);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "diffuseColor: %.7f, %.7f, %.7f, ", diffuseColor[0], diffuseColor[1], diffuseColor[2]);
- }
-
- // Set the base color factor of the material
- materialDefinition.mBaseColorFactor.r = diffuseColor[0];
- materialDefinition.mBaseColorFactor.g = diffuseColor[1];
- materialDefinition.mBaseColorFactor.b = diffuseColor[2];
- }
- }
- else if(baseName == "metallic")
- {
- // Process metallic input
- UsdAttribute metallicAttr = input.GetAttr();
-
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "metallicTexture: ");
- needMetallicTexture = ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::METALLIC);
- if(needMetallicTexture)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::METALLIC, ");
- }
- }
- }
- else if(metallicAttr.HasAuthoredValue())
- {
- float metallicFactor(0.0f);
- GetAttributeValue<float>(metallicAttr, metallicFactor);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "metallicFactor: %.7f, ", metallicFactor);
-
- // Set the metallic factor of the material
- materialDefinition.mMetallic = metallicFactor;
- }
- }
- else if(baseName == "roughness")
- {
- // Process roughness input
- UsdAttribute roughnessAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "roughnessTexture: ");
- needRoughnessTexture = ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::ROUGHNESS);
- if(needRoughnessTexture)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::MaterialDefinition::ROUGHNESS, ");
- }
- }
- }
- else if(roughnessAttr.HasAuthoredValue())
- {
- float roughnessFactor(0.5f);
- GetAttributeValue<float>(roughnessAttr, roughnessFactor);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "roughnessFactor: %.7f, ", roughnessFactor);
-
- // Set the roughness factor of the material
- materialDefinition.mRoughness = roughnessFactor;
- }
- }
- else if(baseName == "normal")
- {
- // Process normal map input
- UsdAttribute normalAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normalTexture: ");
- needNormalTexture = ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::NORMAL);
- if(needNormalTexture)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::NORMAL, ");
- }
- }
- }
- else if(normalAttr.HasAuthoredValue())
- {
- GfVec3f normal;
- GetAttributeValue<GfVec3f>(normalAttr, normal);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normal: %.7f, %.7f, %.7f, ", normal[0], normal[1], normal[2]);
- }
- }
- else if(baseName == "occlusion")
- {
- // Process occlusion map input
- UsdAttribute occlusionAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "occlusionTexture: ");
- if(ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::OCCLUSION))
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::OCCLUSION, ");
- }
- }
- }
- else if(occlusionAttr.HasAuthoredValue())
- {
- float occlusion(1.0f);
- GetAttributeValue<float>(occlusionAttr, occlusion);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "occlusion: %.7f, ", occlusion);
- }
- }
- else if(baseName == "emissiveColor")
- {
- // Process emissive color input
- UsdAttribute emissiveAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "emissiveColorTexture: ");
- if(ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::EMISSIVE))
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::EMISSIVE, ");
- materialDefinition.mEmissiveFactor = Vector3::ONE;
- }
-
- // Handle emissive color scale
- UsdShadeInput scaleInput = uvTexture.GetInput(TfToken("scale"));
- if(scaleInput)
- {
- GfVec4d scale;
- scaleInput.Get<GfVec4d>(&scale);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "emissiveColorScale: %.7f, %.7f, %.7f, %.7f, ", scale[0], scale[1], scale[2], scale[3]);
- }
- }
- }
-
- if(emissiveAttr.HasAuthoredValue())
- {
- GfVec3f emissiveFactor;
- GetAttributeValue<GfVec3f>(emissiveAttr, emissiveFactor);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "emissiveFactor: %.7f, %.7f, %.7f, ", emissiveFactor[0], emissiveFactor[1], emissiveFactor[2]);
-
- // Set the emissive factor of the material
- materialDefinition.mEmissiveFactor = Vector3(emissiveFactor[0], emissiveFactor[1], emissiveFactor[2]);
- }
- }
- else if(baseName == "specularColor")
- {
- // Process specular color input
- UsdAttribute specularAttr = input.GetAttr();
- if(input.HasConnectedSource())
- {
- TfToken id;
- if(uvTexture.GetShaderId(&id) && id.GetString() == "UsdUVTexture")
- {
- // Convert the texture and associate it with the material
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "specularColorTexture: ");
- if(ConvertTexture(material, uvTexture, materialDefinition, MaterialDefinition::SPECULAR_COLOR))
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: MaterialDefinition::SPECULAR_COLOR, ");
- }
- }
- }
- else if(specularAttr.HasAuthoredValue())
- {
- GfVec3f specularColor;
- GetAttributeValue<GfVec3f>(specularAttr, specularColor);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "specularColor: %.7f, %.7f, %.7f, ", specularColor[0], specularColor[1], specularColor[2]);
-
- // Set the specular color factor of the material
- materialDefinition.mSpecularColorFactor = Vector3(specularColor[0], specularColor[1], specularColor[2]);
- }
- }
- }
-
- // Set alpha mode based on transparency and threshold values
- if(hasAlpha)
- {
- if(hasThreshold)
- {
- materialDefinition.mAlphaModeType = Scene3D::Material::AlphaModeType::MASK;
- materialDefinition.mIsMask = true;
- materialDefinition.SetAlphaCutoff(std::min(1.f, std::max(0.f, opacityThreshold)));
- }
- else
- {
- materialDefinition.mAlphaModeType = Scene3D::Material::AlphaModeType::BLEND;
- materialDefinition.mIsOpaque = false;
- materialDefinition.mFlags |= MaterialDefinition::TRANSPARENCY;
- }
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraverseMaterials: materialDefinition.mFlags: %u. needAlbedoTexture: %d, needMetallicRoughnessTexture: %d, needNormalTexture: %d\n", materialDefinition.mFlags, needAlbedoTexture, needMetallicRoughnessTexture, needNormalTexture);
-
- // Set texture needs in the material definition
- materialDefinition.mNeedAlbedoTexture = needAlbedoTexture;
- materialDefinition.mNeedMetallicRoughnessTexture = needMetallicRoughnessTexture;
- materialDefinition.mNeedMetallicTexture = needMetallicTexture;
- materialDefinition.mNeedRoughnessTexture = needRoughnessTexture;
- materialDefinition.mNeedNormalTexture = needNormalTexture;
-
- // Add the processed material to the output materials list
- outMaterials.emplace_back(std::move(materialDefinition), TextureSet());
- }
- }
-}
-
-void UsdLoaderImpl::Impl::TraversePrims(LoadResult& output, const UsdPrim& prim, Index parentIndex, int level)
-{
- PrintLevel(level);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "%s\n", prim.GetName().GetText());
-
- auto& scene = output.mScene;
-
- Index nodeIndex = scene.GetNodeCount() - 1;
-
- if(prim.IsA<UsdGeomMesh>())
- {
- ConvertMesh(output, prim, nodeIndex, parentIndex);
- }
- else if(prim.IsA<UsdGeomXformable>())
- {
- ConvertNode(output, prim, nodeIndex, parentIndex);
- }
- else if(prim.IsA<UsdGeomCamera>())
- {
- ConvertCamera(output, prim);
- }
- else if(prim.IsA<UsdSkelRoot>())
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdSkelRoot\n");
- }
- else if(prim.IsA<UsdSkelSkeleton>())
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdSkelSkeleton\n");
- }
- else
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "\n");
- }
-
- level++;
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "TraversePrims: nodeIndex: %d, ", nodeIndex);
-
- // Recursively traverse child prims
- for(const UsdPrim& child : prim.GetChildren())
- {
- TraversePrims(output, child, nodeIndex, level);
- }
-
- level--;
-}
-
-bool UsdLoaderImpl::Impl::ConvertTexture(const UsdShadeMaterial& usdMaterial, const UsdShadeShader& usdUvTexture, MaterialDefinition& materialDefinition, uint32_t semantic)
-{
- bool transformOffsetAuthored = false;
- GfVec2f uvTransformOffset(0.0f, 0.0f);
- float uvTransformRotation = 0.0f;
- GfVec2f uvTransformScale(0.0f, 0.0f);
-
- // Get all inputs (primvar reader, transform, etc)
- std::vector<UsdShadeShader> deps = TraverseShaderInputs(usdUvTexture);
- deps.push_back(UsdShadeShader(usdUvTexture.GetPrim()));
-
- for(const auto& d : deps)
- {
- TfToken tokenId;
- d.GetShaderId(&tokenId);
- std::string depsId = tokenId.GetString();
-
- // Check if it is a primvar reader (for UV channels)
- if(depsId == "UsdPrimvarReader_float2")
- {
- TfToken tokenVarName("varname");
- // Handle UV channel
- UsdShadeInput shaderInput = UsdShadeShader(d).GetInput(tokenVarName);
- if(shaderInput)
- {
- std::string uvMapName;
- shaderInput.Get<std::string>(&uvMapName);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "uvMapName: %s, ", uvMapName.c_str());
- }
- }
- else if(depsId == "UsdTransform2d") // Check if it is a 2D transform
- {
- // Extract transformation attributes (translation, scale, rotation)
- for(auto input : UsdShadeShader(d).GetInputs())
- {
- transformOffsetAuthored = true;
-
- std::string baseName = input.GetBaseName().GetString();
- if(baseName == "translation")
- {
- TfToken tokenTranslation(baseName);
- UsdShadeInput translationInput = UsdShadeShader(d).GetInput(tokenTranslation);
- if(translationInput)
- {
- translationInput.Get<GfVec2f>(&uvTransformOffset);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "uvTransformOffset: %.7f, %.7f, ", uvTransformOffset[0], uvTransformOffset[1]);
- }
- }
- else if(baseName == "scale")
- {
- TfToken tokenScale(baseName);
- UsdShadeInput scaleInput = UsdShadeShader(d).GetInput(tokenScale);
- if(scaleInput)
- {
- scaleInput.Get<GfVec2f>(&uvTransformScale);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "uvTransformScale: %.7f, %.7f, ", uvTransformScale[0], uvTransformScale[1]);
- }
- }
- else if(baseName == "rotation")
- {
- TfToken tokenRotation(baseName);
- UsdShadeInput rotationInput = UsdShadeShader(d).GetInput(tokenRotation);
- if(rotationInput)
- {
- rotationInput.Get<float>(&uvTransformRotation); // in Degree, need to convert it to Radian
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "uvTransformRotation: %.7f, ", uvTransformRotation);
- }
- }
- }
- }
- else if(depsId == "UsdUVTexture")
- {
- // Handle UV texture
-
- std::string imagePath;
- std::vector<uint8_t> imageBuffer;
-
- // Extract various texture attributes (file, wrapS, wrapT, scale, bias, st, fallback)
- std::vector<UsdShadeInput> inputs = usdUvTexture.GetInputs();
- for(auto input : inputs)
- {
- std::string baseName = input.GetBaseName().GetString();
- if(baseName == "file")
- {
- // Get the asset path of the texture
- SdfAssetPath fileInput;
- input.Get<SdfAssetPath>(&fileInput);
-
- std::string resolvedAssetPath = fileInput.GetResolvedPath();
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "File: %s, ", resolvedAssetPath.c_str());
-
- imagePath = ConvertImagePath(resolvedAssetPath);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Converted File Path: %s, ", imagePath.c_str());
-
- // Load the texture image data as a buffer
- imageBuffer = LoadAssetFileAsBuffer(resolvedAssetPath);
- }
- else if(baseName == "wrapS")
- {
- // Handle texture wrapping in S direction
- TfToken tokenWrapS(baseName);
- UsdShadeInput wrapSInput = UsdShadeShader(d).GetInput(tokenWrapS);
- if(wrapSInput)
- {
- TfToken wrapS;
- wrapSInput.Get<TfToken>(&wrapS);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "wrapS: %s, ", wrapS.GetText());
- }
- }
- else if(baseName == "wrapT")
- {
- // Handle texture wrapping in T direction
- TfToken tokenWrapT(baseName);
- UsdShadeInput wrapTInput = UsdShadeShader(d).GetInput(tokenWrapT);
- if(wrapTInput)
- {
- TfToken wrapT;
- wrapTInput.Get<TfToken>(&wrapT);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "wrapT: %s, ", wrapT.GetText());
- }
- }
- else if(baseName == "scale")
- {
- // Handle texture scale
- TfToken tokenScale(baseName);
- UsdShadeInput scaleInput = UsdShadeShader(d).GetInput(tokenScale);
- if(scaleInput)
- {
- GfVec4f scale;
- scaleInput.Get<GfVec4f>(&scale);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "scale: %.7f, %.7f, %.7f, %.7f, ", scale[0], scale[1], scale[2], scale[3]);
- }
- }
- else if(baseName == "bias")
- {
- // Handle texture bias
- TfToken tokenBias(baseName);
- UsdShadeInput biasInput = UsdShadeShader(d).GetInput(tokenBias);
- if(biasInput)
- {
- GfVec4f bias;
- biasInput.Get<GfVec4f>(&bias);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "bias: %.7f, %.7f, %.7f, %.7f, ", bias[0], bias[1], bias[2], bias[3]);
- }
- }
- else if(baseName == "st")
- {
- // Handle texture ST (UV) coordinates
- TfToken tokenSt(baseName);
- UsdShadeInput stInput = UsdShadeShader(d).GetInput(tokenSt);
- if(stInput)
- {
- GfVec2f st;
- stInput.Get<GfVec2f>(&st);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "st: %.7f, %.7f, ", st[0], st[1]);
- }
- }
- else if(baseName == "fallback")
- {
- // Handle fallback color for the texture
- TfToken tokenFallback(baseName);
- UsdShadeInput fallbackInput = UsdShadeShader(d).GetInput(tokenFallback);
- if(fallbackInput)
- {
- GfVec4f fallback;
- fallbackInput.Get<GfVec4f>(&fallback);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "fallback: %.7f, %.7f, %.7f, %.7f, ", fallback[0], fallback[1], fallback[2], fallback[3]);
- }
- }
- }
-
- if(imageBuffer.size() > 0)
- {
- // If the texture is loaded as an image buffer, add the buffer to the material definition
- materialDefinition.mTextureStages.push_back({semantic, TextureDefinition{std::move(imageBuffer)}});
- materialDefinition.mFlags |= semantic;
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mTextureStages.push_back: semantic: %u, mFlags: %u, imageBuffer: %ld, ", semantic, materialDefinition.mFlags, imageBuffer.size());
-
- return true;
- }
- else if(!imagePath.empty())
- {
- // Otherwise, add the image file path to the material definition
- materialDefinition.mTextureStages.push_back({semantic, TextureDefinition{std::move(imagePath)}});
- materialDefinition.mFlags |= semantic;
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "mTextureStages.push_back: semantic: %u, mFlags: %u, imagePath: %s, ", semantic, materialDefinition.mFlags, imagePath.c_str());
-
- return true;
- }
- }
- }
-
- if(transformOffsetAuthored)
- {
- // @TODO: Process texture transform (similar to KHR_texture_transform) (future work)
- }
-
- return false; // Return false if texture conversion fails
-}
-
-void UsdLoaderImpl::Impl::GetXformableTransformation(const UsdPrim& prim, Vector3& position, Quaternion& rotation, Vector3& scale, const UsdTimeCode time)
-{
- // Retrieve the local transformation matrix of the xformable prim
- auto xformable = UsdGeomXformable(prim);
- GfMatrix4d result(1);
- bool resetsXformStack;
- xformable.GetLocalTransformation(&result, &resetsXformStack, time);
-
- // Decompose the matrix into position, rotation, and scale components
- Matrix transformMatrix = ConvertUsdMatrix(result);
- transformMatrix.GetTransformComponents(position, rotation, scale);
-
- if(transformMatrix == Dali::Matrix::IDENTITY)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "IDENTITY, ");
- }
- else
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Position: %.7f, %.7f, %.7f, ", position.x, position.y, position.z);
-
- if(rotation == Quaternion::IDENTITY)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Rotation: IDENTITY, ");
- }
- else
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Rotation: %.7f, %.7f, %.7f, %.7f, ", rotation.AsVector().x, rotation.AsVector().y, rotation.AsVector().z, rotation.AsVector().w);
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "Scale: %.7f, %.7f, %.7f, ", scale.x, scale.y, scale.z);
- }
-}
-
-NodeDefinition* UsdLoaderImpl::Impl::AddNodeToScene(SceneDefinition& scene, const std::string nodeName, const Index parentIndex, const Vector3& position, const Quaternion& rotation, const Vector3& scale, bool setTransformation)
-{
- // Add the node to the scene graph
- auto weakNode = scene.AddNode([&]() {
- std::unique_ptr<NodeDefinition> nodeDefinition{new NodeDefinition()};
-
- nodeDefinition->mParentIdx = parentIndex;
- nodeDefinition->mName = nodeName;
- if(nodeDefinition->mName.empty())
- {
- nodeDefinition->mName = std::to_string(reinterpret_cast<uintptr_t>(nodeDefinition.get()));
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "scene.AddNode (ConvertNode): %s, parentIndex: %d\n", nodeDefinition->mName.c_str(), parentIndex);
-
- if (setTransformation)
- {
- nodeDefinition->mPosition = position;
- nodeDefinition->mOrientation = rotation;
- nodeDefinition->mScale = scale;
- }
-
- return nodeDefinition; }());
-
- if(!weakNode)
- {
- DALI_LOG_ERROR("Failed to create Node %s!\n", nodeName.c_str());
- }
-
- return weakNode;
-}
-
-void UsdLoaderImpl::Impl::RetrieveGeomPrimvars(const UsdPrim& prim, std::vector<UsdGeomPrimvar>& texcoords, std::vector<UsdGeomPrimvar>& colors, std::vector<UsdGeomPrimvar>& tangents)
-{
- UsdGeomPrimvarsAPI pvAPI(prim);
- std::vector<UsdGeomPrimvar> primvars = pvAPI.GetPrimvars();
-
- for(auto p : primvars)
- {
- if(p.HasAuthoredValue())
- {
- // Collect texture coordinates (UVs), assuming all UVs are stored in one of these primvar types
- if(p.GetTypeName() == SdfValueTypeNames->TexCoord2hArray || p.GetTypeName() == SdfValueTypeNames->TexCoord2fArray || p.GetTypeName() == SdfValueTypeNames->TexCoord2dArray || (p.GetPrimvarName() == "st" && p.GetTypeName() == SdfValueTypeNames->Float2Array))
- {
- texcoords.push_back(p);
- }
- else if(p.GetTypeName().GetRole() == SdfValueRoleNames->Color)
- {
- // Collect color attributes
- std::string colorName;
- size_t pos = p.GetName().GetString().find(":");
- if(pos != std::string::npos)
- {
- colorName = p.GetName().GetString().substr(pos + 1);
- }
-
- if(colorName == "displayColor")
- {
- // Add "displayColor" at the front
- colors.insert(colors.begin(), p);
- }
- else
- {
- colors.push_back(p);
- }
- }
-
- // Collect tangent attributes
- if(p.GetName().GetString().find("tangents") != std::string::npos)
- {
- tangents.push_back(p);
- }
- }
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "texcoords: %lu, colors: %lu, tangents: %lu, ", texcoords.size(), colors.size(), tangents.size());
-}
-
-void UsdLoaderImpl::Impl::ProcessMeshIndices(MeshDefinition& meshDefinition, std::map<int, VtArray<int>>& indexMap, VtIntArray& subsetIdcs, VtArray<int>& triangulatedIndex, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices)
-{
- std::vector<VtArray<int>> subTriangulatedIndices;
-
- // Get indices for each subset
- for(int index : subsetIdcs)
- {
- subTriangulatedIndices.push_back(indexMap[index]);
- }
-
- // Flatten and store the triangulated indices for the current subset
- for(auto sublist : subTriangulatedIndices)
- {
- for(auto item : sublist)
- {
- flattenedSubTriangulatedIndices.push_back(item);
- }
- }
-
- for(int index : flattenedSubTriangulatedIndices)
- {
- subIndexArray.push_back(triangulatedIndex[index * 3]);
- subIndexArray.push_back(triangulatedIndex[index * 3 + 1]);
- subIndexArray.push_back(triangulatedIndex[index * 3 + 2]);
- }
-
- std::vector<uint32_t> indexArrayTriangulated;
- for(size_t k = 0; k < subIndexArray.size(); ++k)
- {
- indexArrayTriangulated.push_back(k);
- }
-
- // To store the final triangulated indices, we need space for uint32_t.
- meshDefinition.mRawData->mIndices.resize(indexArrayTriangulated.size() * 2);
-
- auto indicesData = reinterpret_cast<uint32_t*>(meshDefinition.mRawData->mIndices.data());
- for(size_t i = 0; i < indexArrayTriangulated.size(); i++)
- {
- indicesData[i] = indexArrayTriangulated[i];
- }
-}
-
-void UsdLoaderImpl::Impl::ProcessMeshPositions(MeshDefinition& meshDefinition, const VtArray<GfVec3f>& points, VtArray<GfVec3f>& worldPosition, std::vector<uint32_t>& subIndexArray)
-{
- // Process vertex positions
- for(uint32_t index : subIndexArray)
- {
- worldPosition.push_back(points[index]);
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "subIndexArray: %lu, worldPosition: %lu, ", subIndexArray.size(), worldPosition.size());
-
- // Add vertex positions into the mesh definition
- std::vector<uint8_t> bufferPositions(worldPosition.size() * sizeof(GfVec3f));
-
- std::copy(reinterpret_cast<const uint8_t*>(worldPosition.data()),
- reinterpret_cast<const uint8_t*>(worldPosition.data() + worldPosition.size()),
- bufferPositions.begin());
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "bufferPositions.size: %lu, ", bufferPositions.size());
-
- meshDefinition.mRawData->mAttribs.push_back({"aPosition", Property::VECTOR3, static_cast<uint32_t>(worldPosition.size()), std::move(bufferPositions)});
-}
-
-void UsdLoaderImpl::Impl::ProcessMeshNormals(MeshDefinition& meshDefinition, UsdGeomMesh& usdMesh, VtArray<GfVec3f>& normals, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded)
-{
- UsdAttribute normalsAttr = usdMesh.GetNormalsAttr();
- if(normalsAttr.HasValue())
- {
- VtVec3fArray rawNormals;
- GetAttributeValue<VtVec3fArray>(normalsAttr, rawNormals);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawNormals: %lu, ", rawNormals.size());
-
- if(usdMesh.GetNormalsInterpolation().GetString() == "faceVarying")
- {
- // Handle face-varying normals (one normal per face vertex)
- VtArray<GfVec3f> triangulatedNormal = GetTriangulatedAttribute<GfVec3f>(faceVertexCounts, rawNormals, isLeftHanded);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normals: faceVarying, triangulatedNormal: %lu, flattenedSubTriangulatedIndices: %lu, ", triangulatedNormal.size(), flattenedSubTriangulatedIndices.size());
-
- for(int index : flattenedSubTriangulatedIndices)
- {
- normals.push_back(static_cast<GfVec3f>(triangulatedNormal[index * 3]));
- normals.push_back(static_cast<GfVec3f>(triangulatedNormal[index * 3 + 1]));
- normals.push_back(static_cast<GfVec3f>(triangulatedNormal[index * 3 + 2]));
- }
- }
- else if(usdMesh.GetNormalsInterpolation().GetString() == "vertex")
- {
- // Handle vertex-based normals (one normal per vertex)
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normals: vertex, subIndexArray: %lu, ", subIndexArray.size());
- for(auto x : subIndexArray)
- {
- normals.push_back(static_cast<GfVec3f>(rawNormals[x]));
- }
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normals: size = %lu, value: ", normals.size());
-
- if(normals.size() > 0)
- {
- std::vector<uint8_t> bufferNormals(normals.size() * sizeof(GfVec3f));
-
- std::copy(reinterpret_cast<const uint8_t*>(normals.data()),
- reinterpret_cast<const uint8_t*>(normals.data() + normals.size()),
- bufferNormals.begin());
-
- // Add normal attribute to the mesh definition
- meshDefinition.mRawData->mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast<uint32_t>(normals.size()), std::move(bufferNormals)});
- }
- }
-}
-
-void UsdLoaderImpl::Impl::GenerateNormal(MeshDefinition& meshDefinition)
-{
- auto& attribs = meshDefinition.mRawData->mAttribs;
-
- // Determine the number of indices. If indices are not defined, use the number of vertices in the position attribute.
- const uint32_t numIndices = meshDefinition.mRawData->mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(meshDefinition.mRawData->mIndices.size() / 2);
-
- // Pointer to the vertex positions
- auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
-
- std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto normals = reinterpret_cast<Vector3*>(buffer.data());
-
- // Pointer to the index data
- auto indicesData = reinterpret_cast<uint32_t*>(meshDefinition.mRawData->mIndices.data());
-
- // Loop through each triangle (3 indices at a time)
- for(uint32_t i = 0; i < numIndices; i += 3)
- {
- // Get the positions of the three vertices of the triangle
- Vector3 pos[]{positions[indicesData[i]], positions[indicesData[i + 1]], positions[indicesData[i + 2]]};
-
- // Compute the edge vectors of the triangle
- Vector3 a = pos[1] - pos[0]; // Edge from vertex 0 to vertex 1
- Vector3 b = pos[2] - pos[0]; // Edge from vertex 0 to vertex 2
-
- // Compute the normal using the cross product of the two edge vectors
- Vector3 normal(a.Cross(b));
-
- // Accumulate the normal for each vertex of the triangle
- normals[indicesData[i]] += normal;
- normals[indicesData[i + 1]] += normal;
- normals[indicesData[i + 2]] += normal;
- }
-
- // Normalize the accumulated normals to ensure they are unit vectors
- auto iEnd = normals + attribs[0].mNumElements;
- while(normals != iEnd)
- {
- normals->Normalize();
- ++normals;
- }
-
- // Add generated normals to the mesh definition
- attribs.push_back({"aNormal", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
-}
-
-void UsdLoaderImpl::Impl::ProcessMeshTexcoords(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& texcoords, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded)
-{
- if(texcoords.size() > 0 && texcoords.size() <= 2)
- {
- // Support up to two texture coordinate sets
- for(size_t i = 0; i < texcoords.size(); i++)
- {
- UsdGeomPrimvar stCoords = texcoords[i];
- std::string stCoordsPrimvarName = stCoords.GetName().GetString();
- std::string txName = stCoordsPrimvarName.substr(stCoordsPrimvarName.find(":") + 1, std::string::npos);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "texcoords[%lu]: %s, %s, ", i, stCoordsPrimvarName.c_str(), txName.c_str());
-
- if(stCoords.IsDefined())
- {
- VtVec2fArray rawUVs;
- GetFlattenedPrimvarValue<GfVec2f>(stCoords, rawUVs);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawUVs: %lu, value: ", rawUVs.size());
-
- VtVec2fArray UVs;
- TfToken interpolation = stCoords.GetInterpolation();
- if(interpolation.GetString() == "faceVarying")
- {
- // Handle face-varying UVs
- VtVec2fArray triangulatedUV = GetTriangulatedAttribute<GfVec2f>(faceVertexCounts, rawUVs, isLeftHanded);
-
- for(int index : flattenedSubTriangulatedIndices)
- {
- UVs.push_back(static_cast<GfVec2f>(triangulatedUV[index * 3]));
- UVs.push_back(static_cast<GfVec2f>(triangulatedUV[index * 3 + 1]));
- UVs.push_back(static_cast<GfVec2f>(triangulatedUV[index * 3 + 2]));
- }
- }
- else if(interpolation.GetString() == "vertex")
- {
- // Handle vertex-based UVs
- for(auto x : subIndexArray)
- {
- UVs.push_back(static_cast<GfVec2f>(rawUVs[x]));
- }
- }
- else
- {
- DALI_LOG_ERROR("Unexpected interpolation type %s for UV, ", interpolation.GetString().c_str());
- continue;
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "UVs: size = %lu, value: ", UVs.size());
-
- // Flip UVs vertically to match the texture coordinate system in DALi
- VtVec2fArray flipyUVs;
- for(const auto& uv : UVs)
- {
- flipyUVs.push_back(GfVec2f(uv[0], 1.0f - uv[1]));
- }
-
- std::vector<uint8_t> bufferTexCoords(flipyUVs.size() * sizeof(GfVec2f));
-
- std::copy(reinterpret_cast<const uint8_t*>(flipyUVs.data()),
- reinterpret_cast<const uint8_t*>(flipyUVs.data() + flipyUVs.size()),
- bufferTexCoords.begin());
-
- // Add texcoord attribute to the mesh definition
- meshDefinition.mRawData->mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast<uint32_t>(flipyUVs.size()), std::move(bufferTexCoords)});
- }
- }
- }
-}
-
-void UsdLoaderImpl::Impl::GenerateTangents(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& texcoords)
-{
- auto& attribs = meshDefinition.mRawData->mAttribs;
-
- // Required positions, normals, uvs (if we have them).
- std::vector<uint8_t> buffer(attribs[0].mNumElements * sizeof(Vector3));
- auto tangentsData = reinterpret_cast<Vector3*>(buffer.data());
-
- // Check if UVs are present. Tangents require UV coordinates for calculation.
- bool hasUVs = texcoords.size() > 0 && attribs.size() == 3;
-
- if(hasUVs)
- {
- // Number of indices (each triangle face has 3 indices).
- const uint32_t numIndices = meshDefinition.mRawData->mIndices.empty() ? attribs[0].mNumElements : static_cast<uint32_t>(meshDefinition.mRawData->mIndices.size() / 2);
-
- // Pointers to the vertex positions and UV coordinates.
- auto* positions = reinterpret_cast<const Vector3*>(attribs[0].mData.data());
- auto* uvs = reinterpret_cast<const Vector2*>(attribs[2].mData.data());
-
- // Pointer to the index data.
- auto indicesData = reinterpret_cast<uint32_t*>(meshDefinition.mRawData->mIndices.data());
-
- // Loop over each triangle (three indices at a time).
- for(uint32_t i = 0; i < numIndices; i += 3)
- {
- // Get the positions of the triangle vertices.
- Vector3 pos[]{positions[indicesData[i]], positions[indicesData[i + 1]], positions[indicesData[i + 2]]};
-
- // Get the UV coordinates of the triangle vertices.
- Vector2 uv[]{uvs[indicesData[i]], uvs[indicesData[i + 1]], uvs[indicesData[i + 2]]};
-
- // Calculate the edge vectors in 3D space.
- float x0 = pos[1].x - pos[0].x;
- float y0 = pos[1].y - pos[0].y;
- float z0 = pos[1].z - pos[0].z;
-
- float x1 = pos[2].x - pos[0].x;
- float y1 = pos[2].y - pos[0].y;
- float z1 = pos[2].z - pos[0].z;
-
- // Calculate the edge vectors in UV space.
- float s0 = uv[1].x - uv[0].x;
- float t0 = uv[1].y - uv[0].y;
-
- float s1 = uv[2].x - uv[0].x;
- float t1 = uv[2].y - uv[0].y;
-
- // Calculate the determinant of the matrix formed by the UV edges.
- float det = (s0 * t1 - t0 * s1);
-
- // To avoid division by zero, check the determinant against a small epsilon value.
- float r = 1.f / ((std::abs(det) < Dali::Epsilon<1000>::value) ? (Dali::Epsilon<1000>::value * (det > 0.0f ? 1.f : -1.f)) : det);
-
- // Compute the tangent vector using the positions and UVs.
- Vector3 tangent((x0 * t1 - t0 * x1) * r, (y0 * t1 - t0 * y1) * r, (z0 * t1 - t0 * z1) * r);
-
- // Accumulate the tangent for each vertex of the triangle.
- tangentsData[indicesData[i]] += Vector3(tangent);
- tangentsData[indicesData[i + 1]] += Vector3(tangent);
- tangentsData[indicesData[i + 2]] += Vector3(tangent);
- }
- }
-
- // Normalize the accumulated tangents.
- auto* normalsData = reinterpret_cast<const Vector3*>(attribs[1].mData.data());
- auto iEnd = normalsData + attribs[1].mNumElements;
- while(normalsData != iEnd)
- {
- Vector3 tangentVec3;
- if(hasUVs)
- {
- // Tangent is calculated from the accumulated data.
- tangentVec3 = Vector3((*tangentsData).x, (*tangentsData).y, (*tangentsData).z);
- }
- else
- {
- // Fallback: generate tangent using the cross product of the normal with the X or Y axis.
- Vector3 t[]{normalsData->Cross(Vector3::XAXIS), normalsData->Cross(Vector3::YAXIS)};
- tangentVec3 = t[t[1].LengthSquared() > t[0].LengthSquared()];
- }
-
- // Orthogonalize the tangent by subtracting the component in the direction of the normal.
- tangentVec3 -= *normalsData * normalsData->Dot(tangentVec3);
- tangentVec3.Normalize();
-
- // Store the calculated tangent.
- if(hasUVs)
- {
- *tangentsData = tangentVec3;
- }
- else
- {
- *tangentsData = Vector4(tangentVec3.x, tangentVec3.y, tangentVec3.z, 1.0f);
- }
-
- ++tangentsData;
- ++normalsData;
- }
-
- // Add tangent attribute to the mesh definition
- attribs.push_back({"aTangent", Property::VECTOR3, attribs[0].mNumElements, std::move(buffer)});
-}
-
-void UsdLoaderImpl::Impl::ProcessMeshColors(MeshDefinition& meshDefinition, std::vector<UsdGeomPrimvar>& colors, VtArray<GfVec3f>& worldPosition, std::vector<uint32_t>& subIndexArray, std::vector<uint32_t>& flattenedSubTriangulatedIndices, VtArray<int>& faceVertexCounts, bool isLeftHanded)
-{
- if(colors.size() > 0)
- {
- // We only support up to one color attribute
- UsdGeomPrimvar displayColor = colors[0];
-
- std::string colorPrimvarName = displayColor.GetName().GetString();
- std::string colorName = colorPrimvarName.substr(colorPrimvarName.find(":") + 1, std::string::npos);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "displayColor: %s, %s, ", colorPrimvarName.c_str(), colorName.c_str());
-
- if(displayColor.IsDefined() && displayColor.HasAuthoredValue())
- {
- VtVec3fArray rawColors;
- GetAttributeValue<VtVec3fArray>(displayColor.GetAttr(), rawColors);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawColors: %lu, ", rawColors.size());
-
- VtArray<GfVec3f> convertedColors;
-
- TfToken interpolation = displayColor.GetInterpolation();
- if(interpolation.GetString() == "constant")
- {
- // Handle constant color (same color for all vertices)
- convertedColors = VtArray<GfVec3f>(subIndexArray.size(), rawColors[0]);
- }
- else if(interpolation.GetString() == "faceVarying")
- {
- // Handle face-varying colors
- VtVec3fArray triangulatedColors = GetTriangulatedAttribute<GfVec3f>(faceVertexCounts, rawColors, isLeftHanded);
-
- for(int index : flattenedSubTriangulatedIndices)
- {
- convertedColors.push_back(static_cast<GfVec3f>(triangulatedColors[index * 3]));
- convertedColors.push_back(static_cast<GfVec3f>(triangulatedColors[index * 3 + 1]));
- convertedColors.push_back(static_cast<GfVec3f>(triangulatedColors[index * 3 + 2]));
- }
- }
- else if(interpolation.GetString() == "vertex")
- {
- // Handle vertex colors
- for(auto x : subIndexArray)
- {
- convertedColors.push_back(static_cast<GfVec3f>(rawColors[x]));
- }
- }
- else if(interpolation.GetString() == "uniform")
- {
- // Handle uniform colors
- GetFlattenedPrimvarValue<GfVec3f>(displayColor, rawColors);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawColors (uniform): %lu, value: ", rawColors.size());
-
- for(auto x : subIndexArray)
- {
- convertedColors.push_back(static_cast<GfVec3f>(rawColors[x]));
- }
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "convertedColors: size = %lu, value: ", convertedColors.size());
-
- // COLOR_0
-
- std::vector<uint8_t> bufferColors(convertedColors.size() * sizeof(GfVec3f));
-
- std::copy(reinterpret_cast<const uint8_t*>(convertedColors.data()),
- reinterpret_cast<const uint8_t*>(convertedColors.data() + convertedColors.size()),
- bufferColors.begin());
-
- // Add color attribute to the mesh definition
- meshDefinition.mRawData->mAttribs.push_back({"aVertexColor", Property::VECTOR3, static_cast<uint32_t>(convertedColors.size()), std::move(bufferColors)});
- }
- }
- else if(worldPosition.size() > 0)
- {
- // If no colors are defined, use white color (Vector4::ONE)
- std::vector<uint8_t> buffer(worldPosition.size() * sizeof(Vector4));
- auto bufferColors = reinterpret_cast<Vector4*>(buffer.data());
-
- for(uint32_t i = 0; i < worldPosition.size(); i++)
- {
- bufferColors[i] = Vector4::ONE;
- }
-
- // Add default white color attribute
- meshDefinition.mRawData->mAttribs.push_back({"aVertexColor", Property::VECTOR4, static_cast<uint32_t>(worldPosition.size()), std::move(buffer)});
- }
-}
-
-void UsdLoaderImpl::Impl::ProcessMaterialBinding(LoadResult& output, const UsdPrim& prim, std::vector<UsdGeomSubset>& subsets, size_t subIndex, int& meshSubMaterialId)
-{
- auto& outMaterials = output.mResources.mMaterials;
-
- int meshMaterialId = INVALID_INDEX;
-
- UsdShadeMaterialBindingAPI materialAPI = UsdShadeMaterialBindingAPI(prim);
- std::string materialPath = materialAPI.ComputeBoundMaterial().GetPrim().GetPath().GetString();
-
- if(auto material = mMaterialMap.find(materialPath); material != mMaterialMap.end())
- {
- meshMaterialId = material->second;
- }
-
- bool doubleSided(false);
- if(prim.HasAttribute(TfToken("doubleSided")) && meshMaterialId >= 0)
- {
- // Handle double sidedness
- UsdAttribute doubleSidedAttr = UsdGeomMesh(prim).GetDoubleSidedAttr();
- GetAttributeValue<bool>(doubleSidedAttr, doubleSided);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "doubleSided: %d, ", doubleSided);
-
- outMaterials[meshMaterialId].first.mDoubleSided = doubleSided;
- }
-
- // Set default mesh material if no material is bound
- if(meshMaterialId >= 0)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "meshMaterialId: %d, materialPath: %s, ", meshMaterialId, materialPath.c_str());
- }
- else
- {
- // The default material is used when a mesh does not specify a material
- if(mDefaultMaterial == INVALID_INDEX)
- {
- mDefaultMaterial = outMaterials.size();
-
- MaterialDefinition materialDefinition;
- materialDefinition.mFlags |= MaterialDefinition::GLTF_CHANNELS;
- materialDefinition.mShadowAvailable = true;
- materialDefinition.mNeedAlbedoTexture = false;
- materialDefinition.mNeedMetallicRoughnessTexture = false;
- materialDefinition.mNeedNormalTexture = false;
-
- outMaterials.emplace_back(std::move(materialDefinition), TextureSet());
- }
-
- meshMaterialId = mDefaultMaterial;
- }
-
- meshSubMaterialId = meshMaterialId;
-
- std::string subsetMaterialPath;
-
- // Set material for the subset of the mesh
- auto subset = subsets[subIndex];
- UsdShadeMaterialBindingAPI subsetMaterialAPI = UsdShadeMaterialBindingAPI(subset.GetPrim());
- subsetMaterialPath = subsetMaterialAPI.ComputeBoundMaterial().GetPath().GetString();
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "subsetMaterialPath: %s, ", subsetMaterialPath.c_str());
-
- if(auto subMaterial = mMaterialMap.find(subsetMaterialPath); subMaterial != mMaterialMap.end())
- {
- meshSubMaterialId = subMaterial->second;
- }
-
- if(meshSubMaterialId >= 0)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "meshSubMaterialId: %d, subsetMaterialPath: %s, ", meshSubMaterialId, subsetMaterialPath.c_str());
-
- // Set double-sided property if applicable
- outMaterials[meshSubMaterialId].first.mDoubleSided = doubleSided;
- }
- else
- {
- meshSubMaterialId = mDefaultMaterial;
- }
-}
-
-void UsdLoaderImpl::Impl::ConvertMesh(LoadResult& output, const UsdPrim& prim, Index& nodeIndex, Index parentIndex)
-{
- auto& scene = output.mScene;
-
- nodeIndex = scene.GetNodeCount();
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdGeomMesh %d, nodeIndex: %d, parentIndex: %d, ", mMeshCount, nodeIndex, parentIndex);
- mMeshCount++;
-
- Vector3 position;
- Quaternion rotation;
- Vector3 scale;
- Matrix transformMatrix;
-
- // Handle transformation for non-skeleton mesh nodes
- bool isNonSkeletonMeshNode = prim.IsA<UsdGeomXformable>() && !prim.IsA<UsdSkelSkeleton>();
- if(isNonSkeletonMeshNode)
- {
- GetXformableTransformation(prim, position, rotation, scale);
- }
-
- // Create a new node for the mesh in the scene graph
- nodeIndex = scene.GetNodeCount();
- NodeDefinition* weakNode = AddNodeToScene(scene, prim.GetName().GetString(), parentIndex, position, rotation, scale, isNonSkeletonMeshNode);
-
- // @TODO: Handle xform animation (future work)
-
- // Start processing the mesh geometry
- UsdGeomMesh usdMesh = UsdGeomMesh(prim);
-
- // Retrieve the mesh's vertices (points)
- UsdAttribute pointsAttr = usdMesh.GetPointsAttr();
- VtArray<GfVec3f> points;
- GetAttributeValue<VtArray<GfVec3f>>(pointsAttr, points);
-
- if(points.empty())
- {
- DALI_LOG_ERROR("No points in mesh, ");
- mMeshCount--;
- }
- else
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "PointsCount: %lu, ", points.size());
-
- auto& outMeshes = output.mResources.mMeshes;
-
- // Get Face Vertex Counts (number of vertices per face)
- VtArray<int> faceVertexCounts;
- UsdAttribute facesAttr = usdMesh.GetFaceVertexCountsAttr();
- GetAttributeValue<VtArray<int>>(facesAttr, faceVertexCounts);
-
- // Get Face Vertex Indices (index of vertices for each face)
- VtArray<int> faceVertexIndices;
- UsdAttribute indicesAttr = usdMesh.GetFaceVertexIndicesAttr();
- GetAttributeValue<VtArray<int>>(indicesAttr, faceVertexIndices);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FaceVertexCounts: %lu, FaceVertexIndices: %lu, ", faceVertexCounts.size(), faceVertexIndices.size());
-
- std::vector<UsdGeomPrimvar> texcoords;
- std::vector<UsdGeomPrimvar> colors;
- std::vector<UsdGeomPrimvar> tangents;
-
- // Check for UV, color, and tangent attributes
- RetrieveGeomPrimvars(prim, texcoords, colors, tangents);
-
- // Determine if the mesh uses left-handed or right-handed coordinates
- TfToken orientation;
- UsdAttribute orientationAttr = usdMesh.GetOrientationAttr();
- GetAttributeValue<TfToken>(orientationAttr, orientation);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "orientation: %s, ", orientation.GetText());
-
- bool isLeftHanded = orientation.GetString() != "rightHanded";
-
- // Maps triangulated indices
- std::map<int, VtArray<int>> indexMap;
- int j = 0;
- for(size_t i = 0; i < faceVertexCounts.size(); ++i)
- {
- VtArray<int> tmp;
- for(int k = 0; k < faceVertexCounts[i] - 2; ++k)
- {
- tmp.push_back(j);
- j++;
- }
- indexMap[i] = tmp;
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "indexMap: %lu, ", indexMap.size());
-
- // Triangulate face indices
- VtArray<int> triangulatedIndex = GetTriangulatedAttribute<int>(faceVertexCounts, faceVertexIndices, isLeftHanded);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "triangulatedIndex: %lu, ", triangulatedIndex.size());
-
- // Get mesh subsets (i.e. the group of faces sharing the same material)
- std::vector<UsdGeomSubset> subsets = UsdGeomSubset::GetAllGeomSubsets(usdMesh);
- VtIntArray remainingIndices = UsdGeomSubset::GetUnassignedIndices(subsets, faceVertexCounts.size());
- if(remainingIndices.size() > 0)
- {
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "extra subset: remainingIndices: %lu, ", remainingIndices.size());
-
- // Handle the case where a prim is an instance and therefore cannot be modified
- UsdPrim p = prim;
- while(p.IsInstance())
- {
- p = p.GetParent();
- }
-
- // Create a subset for unassigned faces
- subsets.emplace_back(UsdGeomSubset::CreateGeomSubset(UsdGeomImageable(p), UsdGeomTokens->partition, UsdGeomTokens->face, remainingIndices));
- }
-
- size_t numSubsets = subsets.size();
-
- // Reserve space for the mesh renderables
- weakNode->mRenderables.reserve(numSubsets);
-
- // Prepare subset indices
- std::vector<VtIntArray> subsetIndices(numSubsets, VtIntArray());
- for(size_t i = 0; i < numSubsets; ++i)
- {
- VtIntArray indices;
- GetAttributeValue<VtIntArray>(subsets[i].GetIndicesAttr(), indices);
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "indices[%lu]: %lu, ", i, indices.size());
-
- if(indices == remainingIndices)
- {
- subsetIndices[i] = remainingIndices;
- }
- else
- {
- subsetIndices[i] = indices;
- }
- }
-
- // Process each subset of the mesh
- for(size_t subIndex = 0; subIndex < numSubsets; ++subIndex)
- {
- // Initialize a mesh definition for each subset
- MeshDefinition meshDefinition;
- meshDefinition.mRawData = std::make_shared<MeshDefinition::RawData>();
- meshDefinition.mFlags |= MeshDefinition::U32_INDICES;
- meshDefinition.mSkeletonIdx = INVALID_INDEX;
-
- // Process indices
- auto& subsetIdcs = subsetIndices[subIndex];
- std::vector<uint32_t> subIndexArray;
- std::vector<uint32_t> flattenedSubTriangulatedIndices;
-
- ProcessMeshIndices(meshDefinition, indexMap, subsetIdcs, triangulatedIndex, subIndexArray, flattenedSubTriangulatedIndices);
-
- // Process vertex positions
- VtArray<GfVec3f> worldPosition;
- ProcessMeshPositions(meshDefinition, points, worldPosition, subIndexArray);
-
- // Process normals
- VtArray<GfVec3f> normals;
- ProcessMeshNormals(meshDefinition, usdMesh, normals, subIndexArray, flattenedSubTriangulatedIndices, faceVertexCounts, isLeftHanded);
-
- // Generate normals if not provided
- if(normals.size() == 0 && meshDefinition.mRawData->mAttribs.size() > 0) // Check if normals are missing but positions are available
- {
- GenerateNormal(meshDefinition);
- }
-
- // Process texture coordinates (texcoords)
- ProcessMeshTexcoords(meshDefinition, texcoords, subIndexArray, flattenedSubTriangulatedIndices, faceVertexCounts, isLeftHanded);
-
- // Generate Tangents
- GenerateTangents(meshDefinition, texcoords);
-
- // Process vertex colors
- ProcessMeshColors(meshDefinition, colors, worldPosition, subIndexArray, flattenedSubTriangulatedIndices, faceVertexCounts, isLeftHanded);
-
- // Add the processed meshes to the output meshes list
- outMeshes.emplace_back(std::move(meshDefinition), MeshGeometry{});
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "outMeshes: mIndices: %lu, mAttribs: %lu, ", outMeshes.back().first.mRawData->mIndices.size(), outMeshes.back().first.mRawData->mAttribs.size());
-
- // Process material binding
- int meshSubMaterialId;
- ProcessMaterialBinding(output, prim, subsets, subIndex, meshSubMaterialId);
-
- // Create a renderable object for the model and associate the mesh and material with the renderable
- std::unique_ptr<NodeDefinition::Renderable> renderable;
-
- auto modelRenderable = new ModelRenderable();
- modelRenderable->mMeshIdx = mMeshCount - 1 + subIndex;
-
- modelRenderable->mMaterialIdx = meshSubMaterialId;
-
- renderable.reset(modelRenderable);
- weakNode->mRenderables.push_back(std::move(renderable));
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "weakNode %s->mRenderables.push_back, ", weakNode->mName.c_str());
- }
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "\n");
-}
-
-void UsdLoaderImpl::Impl::ConvertNode(LoadResult& output, const UsdPrim& prim, Index& nodeIndex, Index parentIndex)
-{
- auto& scene = output.mScene;
-
- nodeIndex = scene.GetNodeCount();
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdGeomXformable %d: parentIndex: %d, ", nodeIndex, parentIndex);
-
- // Retrieve the local transformation matrix for the node
- Vector3 position;
- Quaternion rotation;
- Vector3 scale;
- GetXformableTransformation(prim, position, rotation, scale);
-
- // Create a new node for the prim in the scene graph
- nodeIndex = scene.GetNodeCount();
- AddNodeToScene(scene, prim.GetName().GetString(), parentIndex, position, rotation, scale, true);
-
- // @TODO: Handle xform animation (future work)
-}
-
-void UsdLoaderImpl::Impl::ConvertCamera(LoadResult& output, const UsdPrim& prim)
-{
- auto& cameraParameters = output.mCameraParameters;
-
- // Initialize camera parameters with default values if not present
- if(cameraParameters.empty())
- {
- cameraParameters.push_back(CameraParameters());
- cameraParameters[0].matrix.SetTranslation(CAMERA_DEFAULT_POSITION);
- }
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdGeomCamera: ");
-
- // Convert camera properties from USD to internal representation
- UsdGeomCamera camera = UsdGeomCamera(prim);
- UsdAttribute projectionAttr = camera.GetProjectionAttr();
- if(projectionAttr.HasValue())
- {
- TfToken projection("");
- GetAttributeValue<TfToken>(projectionAttr, projection);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "projection: %s, ", projection.GetText());
-
- if(projection.GetString() == "perspective")
- {
- cameraParameters[0].isPerspective = true;
- }
- else if(projection.GetString() == "orthographic")
- {
- cameraParameters[0].isPerspective = false;
- }
- }
-
- GfCamera gfCamera = camera.GetCamera(UsdTimeCode::Default());
- UsdAttribute clippingRangeAttr = camera.GetClippingRangeAttr();
- if(clippingRangeAttr.HasValue())
- {
- GfVec2f clippingRange(0.0f, 0.0f);
- GetAttributeValue<GfVec2f>(clippingRangeAttr, clippingRange);
-
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "zNear: %.7f, zFar: %.7f, ", clippingRange[0], clippingRange[1]);
-
- cameraParameters[0].zNear = clippingRange[0];
- cameraParameters[0].zFar = clippingRange[1];
- }
-
- Radian yFOV = Radian(gfCamera.GetFieldOfView(GfCamera::FOVVertical));
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "yFOV: %f, ", yFOV.radian);
- cameraParameters[0].yFovDegree = Degree(gfCamera.GetFieldOfView(GfCamera::FOVVertical));
-
- float aspectRatio = gfCamera.GetAspectRatio();
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "aspectRatio: %.7f, ", aspectRatio);
- cameraParameters[0].aspectRatio = aspectRatio;
-
- float apertureX = gfCamera.GetHorizontalAperture() / 10.0f;
- float apertureY = gfCamera.GetVerticalAperture() / 10.0f;
- DALI_LOG_INFO(gLogFilter, Debug::Verbose, "apertureX: %.7f, apertureY: %.7f\n", apertureX, apertureY);
-
- // Apply the camera's transform matrix to the camera parameters
- GfMatrix4d matrix = gfCamera.GetTransform();
- cameraParameters[0].matrix = ConvertUsdMatrix(matrix);
-}
-
-} // namespace Dali::Scene3D::Loader
+++ /dev/null
-#ifndef DALI_SCENE3D_LOADER_USD_LOADER_IMPL_H
-#define DALI_SCENE3D_LOADER_USD_LOADER_IMPL_H
-/*
- * Copyright (c) 2024 Samsung Electronics Co., Ltd.
- *
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- *
- */
-
-// EXTERNAL INCLUDES
-#include <string>
-
-// INTERNAL INCLUDES
-#include <dali-scene3d/public-api/loader/model-loader-impl.h>
-
-namespace Dali::Scene3D::Loader
-{
-class UsdLoaderImpl : public ModelLoaderImpl
-{
-public:
- UsdLoaderImpl();
- ~UsdLoaderImpl();
-
- /**
- * @copydoc Dali::Scene3D::Loader::Internal::ModelLoaderImpl::LoadMode()
- */
- bool LoadModel(const std::string& url, Dali::Scene3D::Loader::LoadResult& result) override;
-
-private:
- struct Impl;
- const std::unique_ptr<Impl> mImpl;
-};
-
-} // namespace Dali::Scene3D::Loader
-
-#endif // DALI_SCENE3D_LOADER_USD_LOADER_IMPL_H
Name: dali2-toolkit
Summary: Dali 3D engine Toolkit
-Version: 2.3.44
+Version: 2.3.41
Release: 1
Group: System/Libraries
License: Apache-2.0 and BSD-3-Clause and MIT
BuildRequires: gettext
BuildRequires: pkgconfig(libtzplatform-config)
-%if 0%{?enable_usd_loader}
-BuildRequires: openusd-devel
-%endif
-
# For ASAN test
%if "%{vd_asan}" == "1" || "%{asan}" == "1"
BuildRequires: asan-force-options
%description -n %{dali2_physics3d}-devel
Development components for dali2-physics-3d.
-%if 0%{?enable_usd_loader}
-##############################
-# dali-usd-loader
-##############################
-%define dali2_usdloader dali2-usd-loader
-%package -n %{dali2_usdloader}
-Summary: USD model loading library
-Group: System/Libraries
-License: Apache-2.0
-Requires: %{dali2_scene3d}
-Requires: openusd
-
-%description -n %{dali2_usdloader}
-Provides functionality for loading and rendering USD models. See README.md for more details.
-
-%package -n %{dali2_usdloader}-devel
-Summary: Development components for dali-usd-loader
-Group: Development/Building
-Requires: %{dali2_usdloader} = %{version}-%{release}
-Requires: %{dali2_scene3d}-devel
-
-%description -n %{dali2_usdloader}-devel
-Development components for dali-usd-loader.
-%endif
-
%define dali_data_rw_dir %TZ_SYS_SHARE/dali/
%define dali_data_ro_dir %TZ_SYS_RO_SHARE/dali/
for FILE in *; do mv ./"${FILE}" ../"${FILE}"; done
popd
-%if 0%{?enable_usd_loader}
-%post -n %{dali2_usdloader}
-/sbin/ldconfig
-exit 0
-%endif
-
##############################
# Pre Uninstall
##############################
;;
esac
-%if 0%{?enable_usd_loader}
-%postun -n %{dali2_usdloader}
-/sbin/ldconfig
-exit 0
-%endif
-
##############################
# Files in Binary Packages
##############################
%{_includedir}/bullet/*
%{_libdir}/pkgconfig/dali2-physics-3d.pc
%{_libdir}/pkgconfig/bullet3.pc
-
-%if 0%{?enable_usd_loader}
-%files -n %{dali2_usdloader}
-%if 0%{?enable_dali_smack_rules}
-%manifest dali-usd-loader.manifest-smack
-%else
-%manifest dali-usd-loader.manifest
-%endif
-%defattr(-,root,root,-)
-%{_libdir}/lib%{dali2_usdloader}.so
-%license LICENSE
-
-%files -n %{dali2_usdloader}-devel
-%defattr(-,root,root,-)
-%{_libdir}/pkgconfig/dali2-usd-loader.pc
-%endif
\ No newline at end of file