From: Seungho Baek Date: Fri, 11 Oct 2024 02:32:33 +0000 (+0900) Subject: [Tizen] Reset To 2.3.41 X-Git-Tag: accepted/tizen/unified/20241015.153129~5 X-Git-Url: http://review.tizen.org/git/?a=commitdiff_plain;h=12d2e022137bf36f775ff48f9ef93a3fb5ed5ca9;p=platform%2Fcore%2Fuifw%2Fdali-toolkit.git [Tizen] Reset To 2.3.41 Change-Id: I5f1b1f1184344cfaef341527069b009467cde18a Signed-off-by: Seungho Baek --- diff --git a/automated-tests/build.sh b/automated-tests/build.sh index 1fd56b5670..a56cd87e1c 100755 --- a/automated-tests/build.sh +++ b/automated-tests/build.sh @@ -41,13 +41,6 @@ function build (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 @@ -55,11 +48,9 @@ else 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 diff --git a/automated-tests/execute.sh b/automated-tests/execute.sh index bcc899a2ec..152b0524e6 100755 --- a/automated-tests/execute.sh +++ b/automated-tests/execute.sh @@ -97,7 +97,6 @@ function output_end 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 @@ -117,6 +116,7 @@ find build \( -name "*.gcda" \) -exec rm '{}' \; 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 diff --git a/automated-tests/resources/usd/AntiqueCamera.usdz b/automated-tests/resources/usd/AntiqueCamera.usdz deleted file mode 100644 index 32aa478c82..0000000000 Binary files a/automated-tests/resources/usd/AntiqueCamera.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/Avocado.usdz b/automated-tests/resources/usd/Avocado.usdz deleted file mode 100644 index 2142bf19d1..0000000000 Binary files a/automated-tests/resources/usd/Avocado.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/BarramundiFish.usdz b/automated-tests/resources/usd/BarramundiFish.usdz deleted file mode 100644 index 4f7b53f3c2..0000000000 Binary files a/automated-tests/resources/usd/BarramundiFish.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/BoomBox.usdz b/automated-tests/resources/usd/BoomBox.usdz deleted file mode 100644 index 954588d34c..0000000000 Binary files a/automated-tests/resources/usd/BoomBox.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/CesiumMan.usdz b/automated-tests/resources/usd/CesiumMan.usdz deleted file mode 100644 index 9c6e54c9dc..0000000000 Binary files a/automated-tests/resources/usd/CesiumMan.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/CesiumMilkTruck.usdz b/automated-tests/resources/usd/CesiumMilkTruck.usdz deleted file mode 100644 index 7023881c29..0000000000 Binary files a/automated-tests/resources/usd/CesiumMilkTruck.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/Corset.usdz b/automated-tests/resources/usd/Corset.usdz deleted file mode 100644 index 11cb11a266..0000000000 Binary files a/automated-tests/resources/usd/Corset.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/DamagedHelmet.usdz b/automated-tests/resources/usd/DamagedHelmet.usdz deleted file mode 100644 index fc9e14afbf..0000000000 Binary files a/automated-tests/resources/usd/DamagedHelmet.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/Fox.usdz b/automated-tests/resources/usd/Fox.usdz deleted file mode 100644 index c78557131d..0000000000 Binary files a/automated-tests/resources/usd/Fox.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/Lantern.usdz b/automated-tests/resources/usd/Lantern.usdz deleted file mode 100644 index adb100bd92..0000000000 Binary files a/automated-tests/resources/usd/Lantern.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/MetalRoughSpheresNoTextures.usdz b/automated-tests/resources/usd/MetalRoughSpheresNoTextures.usdz deleted file mode 100644 index 671aa655da..0000000000 Binary files a/automated-tests/resources/usd/MetalRoughSpheresNoTextures.usdz and /dev/null differ diff --git a/automated-tests/resources/usd/WaterBottle.usdz b/automated-tests/resources/usd/WaterBottle.usdz deleted file mode 100644 index 0d65e12b9b..0000000000 Binary files a/automated-tests/resources/usd/WaterBottle.usdz and /dev/null differ diff --git a/automated-tests/src/dali-scene3d-internal/utc-Dali-Gltf2LoaderImpl.cpp b/automated-tests/src/dali-scene3d-internal/utc-Dali-Gltf2LoaderImpl.cpp index 4f36882987..069941c75c 100644 --- a/automated-tests/src/dali-scene3d-internal/utc-Dali-Gltf2LoaderImpl.cpp +++ b/automated-tests/src/dali-scene3d-internal/utc-Dali-Gltf2LoaderImpl.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -232,8 +232,6 @@ int UtcDaliGltfLoaderSuccess1(void) Vector3(0, 0, 1), true, false, - false, - false, true, false, Scene3D::Material::AlphaModeType::MASK, @@ -316,8 +314,6 @@ int UtcDaliGltfLoaderSuccess1(void) Vector3::ONE, true, true, - false, - false, true, false, Scene3D::Material::AlphaModeType::OPAQUE, @@ -396,8 +392,6 @@ int UtcDaliGltfLoaderSuccess1(void) 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); diff --git a/automated-tests/src/dali-scene3d/utc-Dali-Light.cpp b/automated-tests/src/dali-scene3d/utc-Dali-Light.cpp index 02741869e9..88b0f56887 100644 --- a/automated-tests/src/dali-scene3d/utc-Dali-Light.cpp +++ b/automated-tests/src/dali-scene3d/utc-Dali-Light.cpp @@ -1219,7 +1219,7 @@ int UtcDaliLightShadowRenderTask(void) 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(); @@ -1227,30 +1227,29 @@ int UtcDaliLightShadowRenderTask(void) 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 diff --git a/automated-tests/src/dali-scene3d/utc-Dali-Panel.cpp b/automated-tests/src/dali-scene3d/utc-Dali-Panel.cpp index f7b035cefd..197c1e82df 100644 --- a/automated-tests/src/dali-scene3d/utc-Dali-Panel.cpp +++ b/automated-tests/src/dali-scene3d/utc-Dali-Panel.cpp @@ -746,80 +746,4 @@ int UtcDaliPanelSetGetShadow(void) 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 diff --git a/automated-tests/src/dali-scene3d/utc-Dali-SceneView.cpp b/automated-tests/src/dali-scene3d/utc-Dali-SceneView.cpp index dfb44addaa..4e77816043 100644 --- a/automated-tests/src/dali-scene3d/utc-Dali-SceneView.cpp +++ b/automated-tests/src/dali-scene3d/utc-Dali-SceneView.cpp @@ -27,6 +27,7 @@ #include #include + using namespace Dali; using namespace Dali::Toolkit; @@ -1199,56 +1200,6 @@ int UtcDaliSceneViewMasking(void) END_TEST; } -int UtcDaliSceneViewCornerRadius(void) -{ - ToolkitTestApplication application; - - Scene3D::SceneView view = Scene3D::SceneView::New(); - application.GetScene().Add(view); - - DALI_TEST_EQUALS(view.GetProperty(Dali::Scene3D::SceneView::Property::CORNER_RADIUS), Vector4::ZERO, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(Dali::Scene3D::SceneView::Property::CORNER_RADIUS_POLICY), static_cast(Visual::Transform::Policy::ABSOLUTE), TEST_LOCATION); - - Vector4 expectCornerRadius = Vector4(0.5f, 0.3f, 0.2f, 0.0f); - int expectCornerRadiusPolicy = static_cast(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(Dali::Scene3D::SceneView::Property::CORNER_RADIUS), expectCornerRadius, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(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(Dali::Scene3D::SceneView::Property::BORDERLINE_WIDTH), 0.0f, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_COLOR), Color::BLACK, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(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(Dali::Scene3D::SceneView::Property::BORDERLINE_WIDTH), expectBorderlineWidth, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_COLOR), expectBorderlineColor, TEST_LOCATION); - DALI_TEST_EQUALS(view.GetProperty(Dali::Scene3D::SceneView::Property::BORDERLINE_OFFSET), expectBorderlineOffset, TEST_LOCATION); - - END_TEST; -} - namespace { static bool gCaptureFinishedCalled{false}; @@ -1262,9 +1213,9 @@ void OnCaptureFinished(Scene3D::SceneView sceneView, int32_t captureId, const To gCapturedImageUrl = capturedImageUrl; } -static int32_t gCapturedCount{0}; -static std::vector gCaptureIds; -static std::vector gCapturedImageUrls; +static int32_t gCapturedCount{0}; +static std::vector gCaptureIds; +static std::vector gCapturedImageUrls; void OnCaptureMultipleFinished(Scene3D::SceneView sceneView, int32_t captureId, const Toolkit::ImageUrl& capturedImageUrl) { @@ -1308,7 +1259,7 @@ int UtcDaliSceneViewCapture01(void) view.Add(camera); gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); int32_t captureId = view.Capture(camera, Vector2(300, 300)); @@ -1326,7 +1277,7 @@ int UtcDaliSceneViewCapture01(void) Toolkit::ImageUrl tempImageUrl = gCapturedImageUrl; gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); int32_t captureId2 = view.Capture(camera, Vector2(400, 400)); @@ -1382,7 +1333,7 @@ int UtcDaliSceneViewCapture02(void) 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(); @@ -1442,7 +1393,7 @@ int UtcDaliSceneViewCaptureCancel(void) view.Add(camera); gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); int32_t captureId = view.Capture(camera, Vector2(300, 300)); @@ -1452,8 +1403,9 @@ int UtcDaliSceneViewCaptureCancel(void) DALI_TEST_EQUALS(gCaptureId, captureId, TEST_LOCATION); DALI_TEST_EQUALS(!!gCapturedImageUrl, false, TEST_LOCATION); + gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); application.SendNotification(); @@ -1501,7 +1453,7 @@ int UtcDaliSceneViewCaptureFailed(void) view.Add(camera); gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); int32_t captureId = view.Capture(camera, Vector2(300, 300)); @@ -1514,7 +1466,7 @@ int UtcDaliSceneViewCaptureFailed(void) DALI_TEST_EQUALS(!!gCapturedImageUrl, false, TEST_LOCATION); gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); application.SendNotification(); @@ -1553,7 +1505,7 @@ int UtcDaliSceneViewCaptureFailed2(void) view.Add(camera); gCaptureFinishedCalled = false; - gCaptureId = -1; + gCaptureId = -1; gCapturedImageUrl.Reset(); int32_t captureId = view.Capture(camera, Vector2(300, 300)); @@ -1619,67 +1571,3 @@ int UtcDaliSceneViewSelectCamera(void) 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; -} diff --git a/automated-tests/src/dali-scene3d/utc-Dali-ShaderManager.cpp b/automated-tests/src/dali-scene3d/utc-Dali-ShaderManager.cpp index 8736f8a5f9..f17dcb331a 100644 --- a/automated-tests/src/dali-scene3d/utc-Dali-ShaderManager.cpp +++ b/automated-tests/src/dali-scene3d/utc-Dali-ShaderManager.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -89,7 +89,6 @@ int UtcDaliShaderManagerProduceShader(void) {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}}, diff --git a/automated-tests/src/dali-toolkit-internal/utc-Dali-Accessibility-Controls-BridgeUp.cpp b/automated-tests/src/dali-toolkit-internal/utc-Dali-Accessibility-Controls-BridgeUp.cpp index 0e2fa6181f..6d5acf5acd 100644 --- a/automated-tests/src/dali-toolkit-internal/utc-Dali-Accessibility-Controls-BridgeUp.cpp +++ b/automated-tests/src/dali-toolkit-internal/utc-Dali-Accessibility-Controls-BridgeUp.cpp @@ -225,13 +225,11 @@ int UtcDaliControlAccessibilityRole(void) { 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(), TEST_LOCATION); + DALI_TEST_EQUALS(role_unknown, control.GetProperty(DevelControl::Property::ACCESSIBILITY_ROLE).Get(), TEST_LOCATION); auto accessible = Dali::Accessibility::Accessible::Get(control); DALI_TEST_EQUALS(role_unknown, accessible->GetRole(), TEST_LOCATION); @@ -324,7 +322,7 @@ int UtcDaliControlAccessibilityRole(void) DALI_TEST_EQUALS(static_cast(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(Dali::Accessibility::Role::LABEL), TestGetRole(accessible->GetAddress()), TEST_LOCATION); + DALI_TEST_EQUALS(static_cast(Dali::Accessibility::Role::TEXT), TestGetRole(accessible->GetAddress()), TEST_LOCATION); control.SetProperty(DevelControl::Property::ACCESSIBILITY_ROLE, DevelControl::AccessibilityRole::TOGGLE_BUTTON); DALI_TEST_EQUALS(static_cast(Dali::Accessibility::Role::TOGGLE_BUTTON), TestGetRole(accessible->GetAddress()), TEST_LOCATION); @@ -613,57 +611,30 @@ int UtcDaliControlAccessibilityHighlightable(void) highlightable = control.GetProperty(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(), 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(), 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); @@ -2089,185 +2060,3 @@ int UtcDaliIncludeHidden(void) 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 states, std::vector roles) -{ - Accessibility::States statesRule; - MatchType stateMatchType = MatchType::INVALID; - std::array statesConverted{0, 0}; - if(!states.empty()) - { - for(auto state : states) - { - statesRule[state] = true; - } - const auto statesRaw = statesRule.GetRawData(); - statesConverted = {static_cast(statesRaw[0]), static_cast(statesRaw[1])}; - stateMatchType = MatchType::ALL; - } - - Accessibility::EnumBitSet rolesRule; - MatchType roleMatchType = MatchType::INVALID; - std::array rolesConverted{0, 0, 0, 0}; - if(!roles.empty()) - { - for(auto role : roles) - { - rolesRule[role] = true; - } - const auto rolesRaw = rolesRule.GetRawData(); - rolesConverted = {static_cast(rolesRaw[0]), static_cast(rolesRaw[1]), static_cast(rolesRaw[2]), static_cast(rolesRaw[3])}; - roleMatchType = MatchType::ALL; - } - - return { - std::move(statesConverted), - static_cast(stateMatchType), - {}, - static_cast(MatchType::INVALID), - std::move(rolesConverted), - static_cast(roleMatchType), - {}, - static_cast(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(appAccessible); - DALI_TEST_CHECK(collection); - - auto rule = GetMatchRule({Accessibility::State::SENSITIVE, Accessibility::State::SHOWING}, {}); - auto results = collection->GetMatches(std::move(rule), static_cast(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(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(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; -} diff --git a/automated-tests/src/dali-toolkit-internal/utc-Dali-RenderEffect-internal.cpp b/automated-tests/src/dali-toolkit-internal/utc-Dali-RenderEffect-internal.cpp index d468ac765e..9a3bbc6e06 100644 --- a/automated-tests/src/dali-toolkit-internal/utc-Dali-RenderEffect-internal.cpp +++ b/automated-tests/src/dali-toolkit-internal/utc-Dali-RenderEffect-internal.cpp @@ -62,14 +62,6 @@ public: return handle; } - OffScreenRenderable::Type GetOffScreenRenderableType() override - { - return OffScreenRenderable::Type::NONE; - } - - void GetOffScreenRenderTasks(std::vector& tasks, bool isForward) override - {} - protected: TestRenderEffectImpl() : mOnActivated(false) diff --git a/automated-tests/src/dali-toolkit-internal/utc-Dali-TextLabel-internal.cpp b/automated-tests/src/dali-toolkit-internal/utc-Dali-TextLabel-internal.cpp index 12575d30bc..47237f80d8 100644 --- a/automated-tests/src/dali-toolkit-internal/utc-Dali-TextLabel-internal.cpp +++ b/automated-tests/src/dali-toolkit-internal/utc-Dali-TextLabel-internal.cpp @@ -1411,7 +1411,7 @@ int UtcDaliTextLabelLocaleChange02(void) 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); @@ -1478,7 +1478,7 @@ int UtcDaliTextLabelLocaleChange02(void) 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); diff --git a/automated-tests/src/dali-toolkit-styling/utc-Dali-StyleManager.cpp b/automated-tests/src/dali-toolkit-styling/utc-Dali-StyleManager.cpp index 523c9c6f38..0d6c4ae5cf 100644 --- a/automated-tests/src/dali-toolkit-styling/utc-Dali-StyleManager.cpp +++ b/automated-tests/src/dali-toolkit-styling/utc-Dali-StyleManager.cpp @@ -1,5 +1,5 @@ -/* - * 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. @@ -16,23 +16,23 @@ #include +#include +#include +#include +#include #include #include +#include #include +#include +#include +#include +#include #include -#include -#include #include +#include +#include #include -#include -#include -#include -#include -#include -#include -#include -#include -#include // for Internal::StyleManager #include @@ -46,6 +46,9 @@ std::string defaultTheme; } // anonymous namespace + + + void dali_style_manager_startup(void) { test_return_value = TET_UNDEF; @@ -59,54 +62,53 @@ void dali_style_manager_cleanup(void) 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) { @@ -114,7 +116,7 @@ int UtcDaliStyleManagerConstructorP(void) tet_infoline(" UtcDaliStyleManagerConstructorP"); StyleManager styleManager; - DALI_TEST_CHECK(!styleManager); + DALI_TEST_CHECK( !styleManager); END_TEST; } @@ -123,9 +125,9 @@ int UtcDaliStyleManagerCopyConstructorP(void) ToolkitTestApplication application; StyleManager styleManager = StyleManager::Get(); - StyleManager copyOfStyleManager(styleManager); + StyleManager copyOfStyleManager( styleManager ); - DALI_TEST_CHECK(copyOfStyleManager); + DALI_TEST_CHECK( copyOfStyleManager ); END_TEST; } @@ -133,11 +135,11 @@ int UtcDaliStyleManagerAssignmentOperatorP(void) { 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; } @@ -149,10 +151,10 @@ int UtcDaliStyleManagerGet(void) // 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; @@ -167,6 +169,7 @@ int UtcDaliStyleManagerGet(void) END_TEST; } + namespace { class StyleChangedSignalChecker : public ConnectionTracker @@ -184,7 +187,7 @@ public: void Reset() { - signalCount = 0; + signalCount =0; } public: @@ -197,7 +200,7 @@ int UtcDaliStyleManagerApplyTheme(void) { ToolkitTestApplication application; - tet_infoline("Testing StyleManager ApplyTheme"); + tet_infoline( "Testing StyleManager ApplyTheme" ); const char* json1 = "{\n" @@ -228,21 +231,21 @@ int UtcDaliStyleManagerApplyTheme(void) "}\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(); @@ -254,21 +257,21 @@ int UtcDaliStyleManagerApplyTheme(void) 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(); @@ -283,12 +286,12 @@ int UtcDaliStyleManagerApplyTheme(void) 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"); @@ -301,152 +304,17 @@ int UtcDaliStyleManagerApplyTheme(void) 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" @@ -480,14 +348,14 @@ int UtcDaliStyleManagerApplyDefaultTheme(void) 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); @@ -496,8 +364,8 @@ int UtcDaliStyleManagerApplyDefaultTheme(void) 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"); @@ -505,14 +373,14 @@ int UtcDaliStyleManagerApplyDefaultTheme(void) 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; @@ -522,53 +390,55 @@ int UtcDaliStyleManagerApplyDefaultTheme(void) 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() == returnedValue.Get()); + DALI_TEST_CHECK( value.Get() == returnedValue.Get() ); 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() == returnedValue.Get()); + DALI_TEST_CHECK( value.Get() == returnedValue.Get() ); END_TEST; } @@ -576,13 +446,13 @@ int UtcDaliStyleManagerGetStyleConstantN(void) { 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; } @@ -591,7 +461,7 @@ int UtcDaliStyleManagerApplyStyle(void) { 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" @@ -622,12 +492,12 @@ int UtcDaliStyleManagerApplyStyle(void) "}\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); @@ -641,37 +511,38 @@ int UtcDaliStyleManagerApplyStyle(void) 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" @@ -689,12 +560,12 @@ int UtcDaliStyleManagerIncludeStyleP(void) "}\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); @@ -709,20 +580,21 @@ int UtcDaliStyleManagerIncludeStyleP(void) 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" @@ -740,17 +612,12 @@ int UtcDaliStyleManagerIncludeStyleN(void) "}\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); @@ -759,80 +626,76 @@ int UtcDaliStyleManagerIncludeStyleN(void) 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" @@ -861,58 +724,60 @@ int UtcDaliStyleManagerStyleChangedSignalFontSize(void) " }\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" @@ -941,60 +806,61 @@ int UtcDaliStyleManagerStyleChangedSignalFontSizeTextField(void) " }\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" @@ -1023,316 +889,323 @@ int UtcDaliStyleManagerStyleChangedSignalFontSizeTextEditor(void) " }\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(actor.GetImplementation()); - Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30); + Impl::DummyControl& dummyImpl = static_cast(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(), "New text", TEST_LOCATION); - DALI_TEST_EQUALS(pointSizeValue->Get(), 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(), "New text", TEST_LOCATION ); + DALI_TEST_EQUALS( pointSizeValue->Get(), 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(), "New text", TEST_LOCATION); - DALI_TEST_EQUALS(pointSizeValue->Get(), 10, TEST_LOCATION); + tet_infoline( "Check that the instance data has been copied to the new text visual\n"); + DALI_TEST_EQUALS( textValue->Get(), "New text", TEST_LOCATION ); + DALI_TEST_EQUALS( pointSizeValue->Get(), 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(actor.GetImplementation()); - Integration::ResourcePointer ninePatch = CustomizeNinePatch(application, 30, 30); + Impl::DummyControl& dummyImpl = static_cast(actor.GetImplementation()); + Integration::ResourcePointer ninePatch = CustomizeNinePatch( application, 30, 30 ); - int state = actor.GetProperty(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION); + int state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION); + state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION); + state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION); + state = actor.GetProperty( 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(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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION); + int state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION); + state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION); + state = actor.GetProperty( 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(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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::NORMAL, TEST_LOCATION); + int state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::FOCUSED, TEST_LOCATION); + state = actor.GetProperty( 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(DevelControl::Property::STATE); - DALI_TEST_EQUALS(state, (int)DevelControl::DISABLED, TEST_LOCATION); + state = actor.GetProperty( 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"); @@ -1340,103 +1213,105 @@ int UtcDaliStyleManagerSetSubState01(void) 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(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(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" @@ -1455,34 +1330,35 @@ int UtcDaliStyleManagerConfigSectionTest(void) " }\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(); - DALI_TEST_CHECK(!alwaysShowFocus); + Property::Map config = Toolkit::DevelStyleManager::GetConfigurations( styleManager ); + bool alwaysShowFocus = config["alwaysShowFocus"].Get(); + DALI_TEST_CHECK( !alwaysShowFocus ); bool clearFocusOnEscape = config["clearFocusOnEscape"].Get(); - DALI_TEST_CHECK(!clearFocusOnEscape); + DALI_TEST_CHECK( !clearFocusOnEscape ); std::string brokenImageUrl = config["brokenImageUrl"].Get(); - 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; @@ -1490,13 +1366,13 @@ int UtcDaliStyleManagerNewWithAdditionalBehavior(void) 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")); @@ -1507,7 +1383,7 @@ int UtcDaliStyleManagerNewWithAdditionalBehavior(void) 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)); @@ -1527,7 +1403,7 @@ int UtcDaliStyleManagerNewWithAdditionalBehavior(void) 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)); diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.cpp b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.cpp index 114879fb4f..f0bc4d6d5d 100644 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.cpp +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.cpp @@ -1505,22 +1505,4 @@ Graphics::UniquePtr TestGraphicsController::ReleaseTextureFro 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 diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.h b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.h index 2b0a9b97aa..e21c30400f 100644 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.h +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/test-graphics-controller.h @@ -422,9 +422,6 @@ public: // ResourceId relative API. */ Graphics::UniquePtr ReleaseTextureFromResourceId(uint32_t resourceId) override; - bool HasClipMatrix() const override; - const Matrix& GetClipMatrix() const override; - public: // Test Functions void SetAutoAttrCreation(bool v) { @@ -502,14 +499,14 @@ public: // Test Functions 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); @@ -570,4 +567,4 @@ public: } // namespace Dali -#endif // TEST_GRAPHICS_CONTROLLER_H +#endif //TEST_GRAPHICS_CONTROLLER_H diff --git a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp index 61e9d3ebd1..71436e8a05 100644 --- a/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp +++ b/automated-tests/src/dali-toolkit/dali-toolkit-test-utils/toolkit-web-engine.cpp @@ -43,7 +43,6 @@ #include #include #include -#include namespace Dali { @@ -1509,18 +1508,6 @@ public: 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; @@ -2010,26 +1997,6 @@ public: 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 mHistory; size_t mCurrentPlusOnePos; @@ -2079,25 +2046,6 @@ public: 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 @@ -2228,19 +2176,6 @@ bool OnLoadUrl() { gInstance->mTextFoundCallback(1); } - if(gInstance->mWebAuthDisplayQRCallback) - { - gInstance->mWebAuthDisplayQRCallback("test-string"); - } - if(gInstance->mWebAuthResponseCallback) - { - gInstance->mWebAuthResponseCallback(); - } - if(gInstance->mUserMediaPermissionRequestCallback) - { - std::unique_ptr request(new MockUserMediaPermissionRequest()); - gInstance->mUserMediaPermissionRequestCallback(std::move(request), "message"); - } } return false; } @@ -2492,14 +2427,6 @@ WebEngine WebEngine::New() 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(); @@ -3023,25 +2950,5 @@ void WebEngine::RegisterTextFoundCallback(Dali::WebEnginePlugin::WebEngineTextFo 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 diff --git a/automated-tests/src/dali-toolkit/utc-Dali-RenderEffect.cpp b/automated-tests/src/dali-toolkit/utc-Dali-RenderEffect.cpp index f283741f25..8e95732a10 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-RenderEffect.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-RenderEffect.cpp @@ -525,146 +525,3 @@ int UtcDaliRenderEffectControlVisiblityChanged02(void) 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; -} - diff --git a/automated-tests/src/dali-toolkit/utc-Dali-VisualFactory.cpp b/automated-tests/src/dali-toolkit/utc-Dali-VisualFactory.cpp index d22f9f0888..2bbc07e0e9 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-VisualFactory.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-VisualFactory.cpp @@ -38,8 +38,6 @@ namespace { 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"; @@ -2884,7 +2882,7 @@ int UtcDaliVisualFactoryUsePreCompiledShader(void) ToolkitTestApplication application; tet_infoline("UtcDaliVisualFactoryUsePreCompiledShader: Test a UsePreCompiledShader fucntion"); - ShaderPreCompiler::RawShaderDataList precompiledShaderList; + std::vector precompiledShaderList; DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // before Get Shader ShaderPreCompiler::Get().GetPreCompileShaderList(precompiledShaderList); DALI_TEST_CHECK(precompiledShaderList.size() == 0u); // after Get Shader @@ -2949,34 +2947,30 @@ int UtcDaliVisualFactoryUsePreCompiledShader(void) 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); @@ -2995,55 +2989,3 @@ int UtcDaliVisualFactoryUsePreCompiledShader(void) 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; -} diff --git a/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp b/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp index a35a4eabc0..6946a93009 100644 --- a/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp +++ b/automated-tests/src/dali-toolkit/utc-Dali-WebView.cpp @@ -46,7 +46,6 @@ #include #include #include -#include using namespace Dali; using namespace Toolkit; @@ -108,9 +107,6 @@ static int gNewWi 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 { @@ -353,21 +349,6 @@ static void OnTextFound(uint32_t arg) gTextFoundCallbackCalled++; } -static void OnWebAuthDisplayQR(const std::string&) -{ - gWebAuthDisplayQRCalled++; -} - -static void OnWebAuthResponse() -{ - gWebAuthDisplayResponseCalled++; -} - -static void OnUserMediaPermissionRequest(std::unique_ptr request, const std::string& msg) -{ - gUserMediaPermissionRequestCalled++; -} - } // namespace void web_view_startup(void) @@ -1230,7 +1211,7 @@ int UtcDaliWebViewGetScreenshotSyncAndAsync(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 @@ -2563,73 +2544,3 @@ int UtcDaliWebViewRegisterTextFoundCallback(void) 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; -} diff --git a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/CMakeLists.txt b/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/CMakeLists.txt deleted file mode 100644 index f60432a7b8..0000000000 --- a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/CMakeLists.txt +++ /dev/null @@ -1,98 +0,0 @@ -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} -) diff --git a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/tct-dali-usd-loader-dynamic-lib-func-override-core.cpp b/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/tct-dali-usd-loader-dynamic-lib-func-override-core.cpp deleted file mode 100644 index e479c8e387..0000000000 --- a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/tct-dali-usd-loader-dynamic-lib-func-override-core.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include - -// 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); -} diff --git a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/utc-Dali-UsdLoaderDynamicLibFuncOverride.cpp b/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/utc-Dali-UsdLoaderDynamicLibFuncOverride.cpp deleted file mode 100644 index 556cc9a1d8..0000000000 --- a/automated-tests/src/dali-usd-loader-dynamic-lib-func-override/utc-Dali-UsdLoaderDynamicLibFuncOverride.cpp +++ /dev/null @@ -1,148 +0,0 @@ -/* - * 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 -#include -#include -#include -#include -#include -#include - -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 animations; - std::vector animationGroups; - std::vector cameras; - std::vector 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; -} diff --git a/automated-tests/src/dali-usd-loader/CMakeLists.txt b/automated-tests/src/dali-usd-loader/CMakeLists.txt deleted file mode 100644 index fce3bd134f..0000000000 --- a/automated-tests/src/dali-usd-loader/CMakeLists.txt +++ /dev/null @@ -1,99 +0,0 @@ -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} -) diff --git a/automated-tests/src/dali-usd-loader/tct-dali-usd-loader-core.cpp b/automated-tests/src/dali-usd-loader/tct-dali-usd-loader-core.cpp deleted file mode 100644 index e4a7ee0e0f..0000000000 --- a/automated-tests/src/dali-usd-loader/tct-dali-usd-loader-core.cpp +++ /dev/null @@ -1,9 +0,0 @@ -#include - -// Must come second -#include "tct-dali-usd-loader-core.h" - -int main(int argc, char* const argv[]) -{ - return TestHarness::RunTests(argc, argv, tc_array); -} diff --git a/automated-tests/src/dali-usd-loader/utc-Dali-UsdLoader.cpp b/automated-tests/src/dali-usd-loader/utc-Dali-UsdLoader.cpp deleted file mode 100644 index f29fb800a4..0000000000 --- a/automated-tests/src/dali-usd-loader/utc-Dali-UsdLoader.cpp +++ /dev/null @@ -1,390 +0,0 @@ -/* - * 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 -#include -#include -#include -#include -#include -#include - -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 animations; - std::vector animationGroups; - std::vector cameras; - std::vector 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 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; -} diff --git a/build/tizen/CMakeLists.txt b/build/tizen/CMakeLists.txt index 805d86f07e..9cd1e6b28f 100644 --- a/build/tizen/CMakeLists.txt +++ b/build/tizen/CMakeLists.txt @@ -37,29 +37,6 @@ OPTION(CONFIGURE_AUTOMATED_TESTS "Configure automated tests" ON) 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 ) @@ -601,10 +578,6 @@ IF ( BUILD_PHYSICS ) 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 ) @@ -700,7 +673,6 @@ MESSAGE( STATUS "Enable link test: " ${ENABLE_LINK_TEST} ) 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} ) diff --git a/build/tizen/dali-usd-loader/CMakeLists.txt b/build/tizen/dali-usd-loader/CMakeLists.txt deleted file mode 100644 index e64535a82d..0000000000 --- a/build/tizen/dali-usd-loader/CMakeLists.txt +++ /dev/null @@ -1,138 +0,0 @@ -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() diff --git a/build/tizen/dali-usd-loader/dali2-usd-loader.pc.in b/build/tizen/dali-usd-loader/dali2-usd-loader.pc.in deleted file mode 100644 index 895736dc31..0000000000 --- a/build/tizen/dali-usd-loader/dali2-usd-loader.pc.in +++ /dev/null @@ -1,12 +0,0 @@ -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} diff --git a/dali-scene3d/internal/common/image-resource-loader.cpp b/dali-scene3d/internal/common/image-resource-loader.cpp index a930054641..7b2f45fa04 100644 --- a/dali-scene3d/internal/common/image-resource-loader.cpp +++ b/dali-scene3d/internal/common/image-resource-loader.cpp @@ -90,21 +90,28 @@ struct ImageInformation { 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 @@ -127,8 +134,15 @@ std::size_t GenerateHash(const ImageInformation& info) *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); @@ -151,11 +165,11 @@ Dali::PixelData CreatePixelDataFromImageInfo(const ImageInformation& info, bool { 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); @@ -649,14 +663,16 @@ Dali::PixelData GetDefaultBrdfPixelData() 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"); diff --git a/dali-scene3d/internal/common/image-resource-loader.h b/dali-scene3d/internal/common/image-resource-loader.h index df5f02607a..b498b30d40 100644 --- a/dali-scene3d/internal/common/image-resource-loader.h +++ b/dali-scene3d/internal/common/image-resource-loader.h @@ -123,12 +123,16 @@ Dali::PixelData GetCachedPixelData(const std::string& url); * @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 diff --git a/dali-scene3d/internal/common/model-load-task.cpp b/dali-scene3d/internal/common/model-load-task.cpp index 75df573277..fd634f85c1 100644 --- a/dali-scene3d/internal/common/model-load-task.cpp +++ b/dali-scene3d/internal/common/model-load-task.cpp @@ -77,7 +77,8 @@ void ModelLoadTask::Process() 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 @@ -87,11 +88,12 @@ void ModelLoadTask::Process() 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(mModelUrl, mResourceDirectoryUrl, mLoadResult); + mModelLoader = std::make_shared(mModelUrl, mResourceDirectoryUrl, mLoadResult); bool loadSucceeded = false; @@ -133,7 +135,8 @@ void ModelLoadTask::Process() 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(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms "; diff --git a/dali-scene3d/internal/common/model-load-task.h b/dali-scene3d/internal/common/model-load-task.h index eca66e5962..c2baead5b9 100644 --- a/dali-scene3d/internal/common/model-load-task.h +++ b/dali-scene3d/internal/common/model-load-task.h @@ -2,7 +2,7 @@ #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. @@ -118,14 +118,12 @@ private: // Undefined ModelLoadTask& operator=(const ModelLoadTask& task) = delete; - using ModelLoaderUniquePtr = std::unique_ptr; - - 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 mModelLoader; + ModelCacheManager mModelCacheManager; + Dali::Scene3D::Loader::LoadResult mLoadResult; + bool mHasSucceeded; }; } // namespace Internal diff --git a/dali-scene3d/internal/controls/panel/panel-impl.cpp b/dali-scene3d/internal/controls/panel/panel-impl.cpp index bdb66c8fdc..c84fd499d5 100644 --- a/dali-scene3d/internal/controls/panel/panel-impl.cpp +++ b/dali-scene3d/internal/controls/panel/panel-impl.cpp @@ -24,6 +24,7 @@ #include #include #include +#include #include #include #include @@ -275,16 +276,6 @@ Property::Value Panel::GetProperty(BaseObject* object, Property::Index index) return value; } -Dali::Actor Panel::GetOffScreenRenderableSourceActor() -{ - return (mRootLayer) ? mRootLayer : Dali::Actor(); -} - -bool Panel::IsOffScreenRenderTaskExclusive() -{ - return (mRenderTask) ? mRenderTask.IsExclusive() : false; -} - /////////////////////////////////////////////////////////// // // Private methods @@ -394,7 +385,6 @@ void Panel::OnInitialize() scaleConstraint.Apply(); UpdateProperties(); - SetOffScreenRenderableType(OffScreenRenderable::Type::FORWARD); } void Panel::OnSceneConnection(int depth) @@ -467,18 +457,6 @@ void Panel::OnSceneDisconnection() Control::OnSceneDisconnection(); } -void Panel::GetOffScreenRenderTasks(std::vector& tasks, bool isForward) -{ - tasks.clear(); - if(isForward) - { - if(mRenderTask) - { - tasks.push_back(mRenderTask); - } - } -} - void Panel::SetTransparent(bool transparent) { if(mIsTransparent != transparent) diff --git a/dali-scene3d/internal/controls/panel/panel-impl.h b/dali-scene3d/internal/controls/panel/panel-impl.h index 5147bdeca4..769d866096 100644 --- a/dali-scene3d/internal/controls/panel/panel-impl.h +++ b/dali-scene3d/internal/controls/panel/panel-impl.h @@ -121,16 +121,6 @@ public: */ 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. @@ -158,11 +148,6 @@ private: */ void OnSceneDisconnection() override; - /** - * @copydoc CustomActorImpl::SetFirstOrderIndex() - */ - void GetOffScreenRenderTasks(std::vector& tasks, bool isForward) override; - private: /** * @brief Sets whether the plane is transparent or not. diff --git a/dali-scene3d/internal/controls/scene-view/scene-view-impl.cpp b/dali-scene3d/internal/controls/scene-view/scene-view-impl.cpp index b142f9ff74..f570010e69 100644 --- a/dali-scene3d/internal/controls/scene-view/scene-view-impl.cpp +++ b/dali-scene3d/internal/controls/scene-view/scene-view-impl.cpp @@ -64,14 +64,9 @@ DALI_TYPE_REGISTRATION_BEGIN(Scene3D::SceneView, Toolkit::Control, Create); 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; @@ -176,7 +171,8 @@ void SetShadowLightConstraint(Dali::CameraActor selectedCamera, Dali::CameraActo // Compute ViewProjectionMatrix and store it to "tempViewProjectionMatrix" property auto tempViewProjectionMatrixIndex = shadowLightCamera.RegisterProperty("tempViewProjectionMatrix", Matrix::IDENTITY); - Constraint projectionMatrixConstraint = Constraint::New(shadowLightCamera, tempViewProjectionMatrixIndex, [](Matrix& output, const PropertyInputContainer& inputs) { + Constraint projectionMatrixConstraint = Constraint::New(shadowLightCamera, tempViewProjectionMatrixIndex, [](Matrix& output, const PropertyInputContainer& inputs) + { Matrix worldMatrix = inputs[0]->GetMatrix(); float tangentFov_2 = tanf(inputs[4]->GetFloat()); float nearDistance = inputs[5]->GetFloat(); @@ -337,7 +333,6 @@ SceneView::SceneView() mSkyboxIntensity(1.0f), mFailedCaptureCallbacks(nullptr), mLightObservers(), - mCornerRadiusPolicy(static_cast(Toolkit::Visual::Transform::Policy::ABSOLUTE)), mShaderManager(new Scene3D::Loader::ShaderManager()) { } @@ -714,7 +709,8 @@ void SceneView::SetShadow(Scene3D::Light light) return; } - auto foundLight = std::find_if(mLights.begin(), mLights.end(), [light](std::pair lightEntity) -> bool { return (lightEntity.second && lightEntity.first == light); }); + auto foundLight = std::find_if(mLights.begin(), mLights.end(), [light](std::pair lightEntity) -> bool + { return (lightEntity.second && lightEntity.first == light); }); if(foundLight == mLights.end()) { @@ -800,9 +796,7 @@ void SceneView::UseFramebuffer(bool useFramebuffer) if(mUseFrameBuffer != useFramebuffer) { mUseFrameBuffer = useFramebuffer; - SetOffScreenRenderableType((mUseFrameBuffer) ? OffScreenRenderable::Type::FORWARD : OffScreenRenderable::Type::NONE); UpdateRenderTask(); - RequestRenderTaskReorder(); } } @@ -931,7 +925,7 @@ int32_t SceneView::Capture(Dali::CameraActor camera, const Vector2& size) 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()) { @@ -1055,12 +1049,9 @@ void SceneView::SetAlphaMaskUrl(std::string& alphaMaskUrl) { if(mAlphaMaskUrl != alphaMaskUrl) { - mAlphaMaskUrl = alphaMaskUrl; - if(mUseFrameBuffer) - { - mMaskingPropertyChanged = true; - UpdateRenderTask(); - } + mAlphaMaskUrl = alphaMaskUrl; + mMaskingPropertyChanged = true; + UpdateRenderTask(); } } @@ -1074,11 +1065,8 @@ void SceneView::SetMaskContentScaleFactor(float maskContentScaleFactor) if(mMaskContentScaleFactor != maskContentScaleFactor) { mMaskContentScaleFactor = maskContentScaleFactor; - if(mUseFrameBuffer) - { - mMaskingPropertyChanged = true; - UpdateRenderTask(); - } + mMaskingPropertyChanged = true; + UpdateRenderTask(); } } @@ -1091,12 +1079,9 @@ void SceneView::EnableCropToMask(bool enableCropToMask) { if(mCropToMask != enableCropToMask) { - mCropToMask = enableCropToMask; - if(mUseFrameBuffer) - { - mMaskingPropertyChanged = true; - UpdateRenderTask(); - } + mCropToMask = enableCropToMask; + mMaskingPropertyChanged = true; + UpdateRenderTask(); } } @@ -1105,96 +1090,6 @@ bool SceneView::IsEnabledCropToMask() 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; @@ -1226,31 +1121,6 @@ void SceneView::SetProperty(BaseObject* object, Property::Index index, const Pro sceneViewImpl.EnableCropToMask(value.Get()); break; } - case Scene3D::SceneView::Property::CORNER_RADIUS: - { - sceneViewImpl.SetCornerRadius(value.Get()); - break; - } - case Scene3D::SceneView::Property::CORNER_RADIUS_POLICY: - { - sceneViewImpl.SetCornerRadiusPolicy(value.Get()); - break; - } - case Scene3D::SceneView::Property::BORDERLINE_WIDTH: - { - sceneViewImpl.SetBorderlineWidth(value.Get()); - break; - } - case Scene3D::SceneView::Property::BORDERLINE_COLOR: - { - sceneViewImpl.SetBorderlineColor(value.Get()); - break; - } - case Scene3D::SceneView::Property::BORDERLINE_OFFSET: - { - sceneViewImpl.SetBorderlineOffset(value.Get()); - break; - } } } } @@ -1282,46 +1152,11 @@ Property::Value SceneView::GetProperty(BaseObject* object, Property::Index index 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 @@ -1360,13 +1195,14 @@ void SceneView::OnSceneConnection(int depth) 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); @@ -1395,7 +1231,7 @@ void SceneView::OnSceneDisconnection() } tempContainer.clear(); - for(auto&& capture : mCaptureContainer) + for(auto && capture : mCaptureContainer) { ResetCaptureData(capture.second); } @@ -1433,22 +1269,6 @@ void SceneView::OnSceneDisconnection() Control::OnSceneDisconnection(); } -void SceneView::GetOffScreenRenderTasks(std::vector& 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(); @@ -1466,11 +1286,6 @@ void SceneView::OnInitialize() mDefaultCamera.SetProperty(Dali::Actor::Property::ANCHOR_POINT, AnchorPoint::CENTER); AddCamera(mDefaultCamera); UpdateCamera(mDefaultCamera); - - if(mUseFrameBuffer) - { - SetOffScreenRenderableType(OffScreenRenderable::Type::FORWARD); - } } void SceneView::OnChildAdd(Actor& child) @@ -1564,7 +1379,6 @@ void SceneView::UpdateRenderTask() !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); @@ -1592,17 +1406,6 @@ void SceneView::UpdateRenderTask() 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); @@ -1611,15 +1414,12 @@ void SceneView::UpdateRenderTask() 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()) { @@ -1825,10 +1625,6 @@ void SceneView::UpdateShadowMapBuffer(uint32_t shadowMapSize) mShadowMapRenderTask.SetClearColor(Color::WHITE); mShadowMapRenderTask.SetRenderPassTag(10); mShadowMapRenderTask.SetCameraActor(GetImplementation(mShadowLight).GetCamera()); - } - - if(!mUseFrameBuffer) - { mShadowMapRenderTask.SetOrderIndex(SHADOW_ORDER_INDEX); } @@ -1855,7 +1651,8 @@ void SceneView::UpdateShadowMapBuffer(uint32_t shadowMapSize) void SceneView::OnCaptureFinished(Dali::RenderTask& task) { - auto iter = std::find_if(mCaptureContainer.begin(), mCaptureContainer.end(), [task](std::pair> item) { return item.first == task; }); + auto iter = std::find_if(mCaptureContainer.begin(), mCaptureContainer.end(), [task](std::pair> item) + { return item.first == task; }); if(iter != mCaptureContainer.end()) { @@ -1876,8 +1673,8 @@ void SceneView::OnCaptureFinished(Dali::RenderTask& task) 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>> tempContainer; for(auto&& capture : mCaptureContainer) { @@ -1892,14 +1689,14 @@ bool SceneView::OnTimeOut() 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> item) { + auto it = std::remove_if(mCaptureContainer.begin(), mCaptureContainer.end(), [tickCount](std::pair> item) { return item.second->mStartTick + 1 < tickCount; }); mCaptureContainer.erase(it, mCaptureContainer.end()); @@ -1944,7 +1741,7 @@ void SceneView::RequestCameraTransition() { if(mTransitionSourceCamera && mTransitionDestinationCamera && !(mTransitionSourceCamera == mTransitionDestinationCamera)) { - Vector3 sourceWorldPosition = mTransitionSourceCamera.GetProperty(Dali::Actor::Property::WORLD_POSITION); + Vector3 sourceWorldPosition = mTransitionSourceCamera.GetProperty(Dali::Actor::Property::WORLD_POSITION); Quaternion sourceWorldOrientation = mTransitionSourceCamera.GetProperty(Dali::Actor::Property::WORLD_ORIENTATION); if(!CheckInside(mRootLayer, mTransitionDestinationCamera)) @@ -1952,9 +1749,9 @@ void SceneView::RequestCameraTransition() 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); @@ -1989,7 +1786,7 @@ void SceneView::RequestCameraTransition() Dali::DevelCameraActor::ProjectionDirection destinationProjectionDirection = mTransitionDestinationCamera.GetProperty(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) @@ -2012,7 +1809,7 @@ void SceneView::RequestCameraTransition() } else { - float sourceOrthographicSize = mTransitionSourceCamera.GetProperty(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE); + float sourceOrthographicSize = mTransitionSourceCamera.GetProperty(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE); float destinationOrthographicSize = mTransitionDestinationCamera.GetProperty(Dali::DevelCameraActor::Property::ORTHOGRAPHIC_SIZE); if(sourceProjectionDirection != destinationProjectionDirection) @@ -2035,7 +1832,7 @@ void SceneView::RequestCameraTransition() } 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)); diff --git a/dali-scene3d/internal/controls/scene-view/scene-view-impl.h b/dali-scene3d/internal/controls/scene-view/scene-view-impl.h index c436a252c2..694594d93d 100644 --- a/dali-scene3d/internal/controls/scene-view/scene-view-impl.h +++ b/dali-scene3d/internal/controls/scene-view/scene-view-impl.h @@ -338,66 +338,6 @@ public: */ 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 */ @@ -421,16 +361,6 @@ public: */ 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. @@ -453,11 +383,6 @@ private: */ void OnSceneDisconnection() override; - /** - * @copydoc CustomActorImpl::GetOffScreenRenderTasks() - */ - void GetOffScreenRenderTasks(std::vector& tasks, bool isForward) override; - /** * @copydoc Toolkit::Control::OnInitialize() */ @@ -677,17 +602,6 @@ private: // Implementation of Processor 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; diff --git a/dali-scene3d/internal/graphics/shaders/default-physically-based-shader.frag b/dali-scene3d/internal/graphics/shaders/default-physically-based-shader.frag index e9d48648ca..a9e704bf9c 100644 --- a/dali-scene3d/internal/graphics/shaders/default-physically-based-shader.frag +++ b/dali-scene3d/internal/graphics/shaders/default-physically-based-shader.frag @@ -328,7 +328,7 @@ void main() 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 diff --git a/dali-scene3d/internal/loader/dli-loader-impl.h b/dali-scene3d/internal/loader/dli-loader-impl.h index d94dbbf6e9..ba6b1179a9 100644 --- a/dali-scene3d/internal/loader/dli-loader-impl.h +++ b/dali-scene3d/internal/loader/dli-loader-impl.h @@ -1,7 +1,7 @@ #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. @@ -21,12 +21,12 @@ #include // INTERNAL INCLUDES +#include #include #include #include #include #include -#include #include #include @@ -56,7 +56,7 @@ public: 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; diff --git a/dali-scene3d/internal/loader/glb-loader-impl.h b/dali-scene3d/internal/loader/glb-loader-impl.h index b2610aaf76..05c9d9c52a 100644 --- a/dali-scene3d/internal/loader/glb-loader-impl.h +++ b/dali-scene3d/internal/loader/glb-loader-impl.h @@ -1,7 +1,7 @@ #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. @@ -22,8 +22,8 @@ #include // INTERNAL INCLUDES +#include #include -#include namespace Dali::Scene3D::Loader::Internal { @@ -31,7 +31,7 @@ class GlbLoaderImpl : public ModelLoaderImpl { 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; }; diff --git a/dali-scene3d/internal/loader/gltf2-loader-impl.h b/dali-scene3d/internal/loader/gltf2-loader-impl.h index 47f46606a0..a4dfc6e5c4 100644 --- a/dali-scene3d/internal/loader/gltf2-loader-impl.h +++ b/dali-scene3d/internal/loader/gltf2-loader-impl.h @@ -1,7 +1,7 @@ #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. @@ -22,8 +22,8 @@ #include // INTERNAL INCLUDES +#include #include -#include namespace Dali::Scene3D::Loader::Internal { @@ -31,7 +31,7 @@ class Gltf2LoaderImpl : public ModelLoaderImpl { 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; }; diff --git a/dali-scene3d/internal/loader/model-loader-impl.h b/dali-scene3d/internal/loader/model-loader-impl.h new file mode 100644 index 0000000000..619cacb689 --- /dev/null +++ b/dali-scene3d/internal/loader/model-loader-impl.h @@ -0,0 +1,69 @@ +#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 +#include +#include +#include + +// EXTERNAL INCLUDES +#include + +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 diff --git a/dali-scene3d/public-api/controls/scene-view/scene-view.h b/dali-scene3d/public-api/controls/scene-view/scene-view.h index d9ff7ff655..4e72412cbb 100644 --- a/dali-scene3d/public-api/controls/scene-view/scene-view.h +++ b/dali-scene3d/public-api/controls/scene-view/scene-view.h @@ -149,58 +149,11 @@ public: * @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. * diff --git a/dali-scene3d/public-api/loader/load-scene-metadata.cpp b/dali-scene3d/public-api/loader/load-scene-metadata.cpp index 5da6faf163..826e7133fd 100644 --- a/dali-scene3d/public-api/loader/load-scene-metadata.cpp +++ b/dali-scene3d/public-api/loader/load-scene-metadata.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -41,9 +41,7 @@ struct ImageData BOX_THEN_NEAREST = Dali::SamplingMode::BOX_THEN_NEAREST, BOX_THEN_LINEAR = Dali::SamplingMode::BOX_THEN_LINEAR, NO_FILTER = Dali::SamplingMode::NO_FILTER, - DONT_CARE = Dali::SamplingMode::DONT_CARE, - LANCZOS = Dali::SamplingMode::LANCZOS, - BOX_THEN_LANCZOS = Dali::SamplingMode::BOX_THEN_LANCZOS, + DONT_CARE = Dali::SamplingMode::DONT_CARE }; static Type FromString(const char* s, size_t len); @@ -66,8 +64,6 @@ const std::map& GetStringSampli ENUM_STRING_MAPPING(ImageData::SamplingMode, BOX_THEN_LINEAR), ENUM_STRING_MAPPING(ImageData::SamplingMode, NO_FILTER), ENUM_STRING_MAPPING(ImageData::SamplingMode, DONT_CARE), - ENUM_STRING_MAPPING(ImageData::SamplingMode, LANCZOS), - ENUM_STRING_MAPPING(ImageData::SamplingMode, BOX_THEN_LANCZOS), }; return SAMPLING_MODE_TYPES; } @@ -82,17 +78,17 @@ struct MetaData const js::Reader& GetImageMetaDataReader() { static const auto IMAGE_METADATA_READER = std::move(js::Reader() - .Register(*js::MakeProperty("uri", js::Read::String, &ImageData::mImageUri)) - .Register(*js::MakeProperty("minWidth", js::Read::Number, &ImageData::mMinWidth)) - .Register(*js::MakeProperty("minHeight", js::Read::Number, &ImageData::mMinHeight)) - .Register(*js::MakeProperty("samplingMode", gt::ReadStringEnum, &ImageData::mSamplingMode))); + .Register(*js::MakeProperty("uri", js::Read::String, &ImageData::mImageUri)) + .Register(*js::MakeProperty("minWidth", js::Read::Number, &ImageData::mMinWidth)) + .Register(*js::MakeProperty("minHeight", js::Read::Number, &ImageData::mMinHeight)) + .Register(*js::MakeProperty("samplingMode", gt::ReadStringEnum, &ImageData::mSamplingMode))); return IMAGE_METADATA_READER; } const js::Reader& GetMetaDataReader() { static const auto METADATA_READER = std::move(js::Reader() - .Register(*js::MakeProperty("images", js::Read::Array::Read>, &MetaData::mImageData))); + .Register(*js::MakeProperty("images", js::Read::Array::Read>, &MetaData::mImageData))); return METADATA_READER; } } // namespace diff --git a/dali-scene3d/public-api/loader/material-definition.cpp b/dali-scene3d/public-api/loader/material-definition.cpp index 31f14b11b4..27a460b394 100644 --- a/dali-scene3d/public-api/loader/material-definition.cpp +++ b/dali-scene3d/public-api/loader/material-definition.cpp @@ -86,18 +86,22 @@ static constexpr std::string_view EMBEDDED_DATA_IMAGE_MEDIA_TYPE = "image/"; 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) { @@ -116,13 +120,15 @@ Dali::PixelData LoadImageResource(const std::string& resourcePath, 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(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(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) { @@ -134,62 +140,10 @@ Dali::PixelData LoadImageResource(const std::string& resourcePath, 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) @@ -271,19 +225,20 @@ MaterialDefinition::LoadRaw(const std::string& imagesPath) // 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 @@ -295,7 +250,7 @@ MaterialDefinition::LoadRaw(const std::string& imagesPath) { 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 @@ -329,75 +284,9 @@ MaterialDefinition::LoadRaw(const std::string& imagesPath) 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(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(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(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, @@ -407,7 +296,7 @@ MaterialDefinition::LoadRaw(const std::string& imagesPath) 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) @@ -426,31 +315,31 @@ MaterialDefinition::LoadRaw(const std::string& imagesPath) // 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; } @@ -520,7 +409,8 @@ TextureSet MaterialDefinition::Load(const EnvironmentDefinition::Vector& environ 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 diff --git a/dali-scene3d/public-api/loader/material-definition.h b/dali-scene3d/public-api/loader/material-definition.h index 121d835bec..fcd942d0f0 100644 --- a/dali-scene3d/public-api/loader/material-definition.h +++ b/dali-scene3d/public-api/loader/material-definition.h @@ -1,7 +1,7 @@ #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. @@ -151,8 +151,8 @@ struct DALI_SCENE3D_API MaterialDefinition 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 @@ -260,11 +260,9 @@ public: // DATA 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; diff --git a/dali-scene3d/public-api/loader/model-loader-impl.h b/dali-scene3d/public-api/loader/model-loader-impl.h deleted file mode 100644 index ba55ff07b1..0000000000 --- a/dali-scene3d/public-api/loader/model-loader-impl.h +++ /dev/null @@ -1,68 +0,0 @@ -#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 -#include -#include -#include - -// EXTERNAL INCLUDES -#include - -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 diff --git a/dali-scene3d/public-api/loader/model-loader.cpp b/dali-scene3d/public-api/loader/model-loader.cpp index 939a438f01..211b0e0ae0 100644 --- a/dali-scene3d/public-api/loader/model-loader.cpp +++ b/dali-scene3d/public-api/loader/model-loader.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -16,12 +16,10 @@ */ // FILE HEADER -#include #include // EXTERNAL INCLUDES #include -#include #include #include @@ -29,53 +27,17 @@ #include #include #include +#include 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 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) @@ -86,10 +48,6 @@ ModelLoader::ModelLoader(const std::string& modelUrl, const std::string& resourc CreateModelLoader(); } -ModelLoader::~ModelLoader() -{ -} - bool ModelLoader::LoadModel(Dali::Scene3D::Loader::ResourceBundle::PathProvider& pathProvider, bool loadOnlyRawResource) { if(!mImpl) @@ -152,60 +110,15 @@ void ModelLoader::CreateModelLoader() if(extension == DLI_EXTENSION) { - mImpl = std::make_unique(); + mImpl = std::make_shared(); } else if(extension == GLTF_EXTENSION) { - mImpl = std::make_unique(); + mImpl = std::make_shared(); } else if(extension == GLB_EXTENSION) { - mImpl = std::make_unique(); - } - 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(new void*(handle), [](void* ptr) { - if(ptr) - { - DlcloseDeleter(*(static_cast(ptr))); // Call custom deleter - delete static_cast(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(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(); } else { @@ -238,4 +151,5 @@ void ModelLoader::LoadResource(Dali::Scene3D::Loader::ResourceBundle::PathProvid GetResources().LoadResources(pathProvider); } } + } // namespace Dali::Scene3D::Loader diff --git a/dali-scene3d/public-api/loader/model-loader.h b/dali-scene3d/public-api/loader/model-loader.h index 64aa8ff87e..8a660deec8 100644 --- a/dali-scene3d/public-api/loader/model-loader.h +++ b/dali-scene3d/public-api/loader/model-loader.h @@ -1,7 +1,7 @@ #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. @@ -27,7 +27,10 @@ namespace Dali::Scene3D::Loader { +namespace Internal +{ class ModelLoaderImpl; +} class DALI_SCENE3D_API ModelLoader { @@ -45,12 +48,6 @@ public: */ 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 @@ -127,8 +124,7 @@ private: Dali::Scene3D::Loader::LoadResult mLoadResult; Dali::Scene3D::Loader::Customization::Choices mResourceChoices; - using ModelLoaderImplUniquePtr = std::unique_ptr; - ModelLoaderImplUniquePtr mImpl; + std::shared_ptr mImpl; }; } // namespace Dali::Scene3D::Loader diff --git a/dali-scene3d/public-api/loader/shader-manager.cpp b/dali-scene3d/public-api/loader/shader-manager.cpp index 57d112a851..4625e18b2e 100644 --- a/dali-scene3d/public-api/loader/shader-manager.cpp +++ b/dali-scene3d/public-api/loader/shader-manager.cpp @@ -69,7 +69,7 @@ ShaderOption MakeOption(const MaterialDefinition& materialDef, const MeshDefinit 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); } diff --git a/dali-toolkit/devel-api/controls/control-accessible.cpp b/dali-toolkit/devel-api/controls/control-accessible.cpp index 497aaf210c..66ddc33af7 100644 --- a/dali-toolkit/devel-api/controls/control-accessible.cpp +++ b/dali-toolkit/devel-api/controls/control-accessible.cpp @@ -163,7 +163,7 @@ Dali::Accessibility::Role ConvertV2RoleToAtspiRole(AccessibilityRole role) 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: @@ -201,26 +201,6 @@ bool IsHighlightableRole(int32_t rawRole) return IsRoleV2(rawRole) && static_cast(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) @@ -352,7 +332,7 @@ void ControlAccessible::ApplyAccessibilityProps(Dali::Accessibility::States& sta // 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() diff --git a/dali-toolkit/devel-api/controls/web-view/web-view.cpp b/dali-toolkit/devel-api/controls/web-view/web-view.cpp index 05d5a7be7e..7900fc1d53 100755 --- a/dali-toolkit/devel-api/controls/web-view/web-view.cpp +++ b/dali-toolkit/devel-api/controls/web-view/web-view.cpp @@ -61,12 +61,7 @@ WebView WebView::New(const std::string& locale, const std::string& timezoneId) 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) @@ -454,27 +449,6 @@ void WebView::GetPlainTextAsynchronously(Dali::WebEnginePlugin::PlainTextReceive 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) { diff --git a/dali-toolkit/devel-api/controls/web-view/web-view.h b/dali-toolkit/devel-api/controls/web-view/web-view.h index cacec24671..6b5c5dd545 100755 --- a/dali-toolkit/devel-api/controls/web-view/web-view.h +++ b/dali-toolkit/devel-api/controls/web-view/web-view.h @@ -216,15 +216,6 @@ public: */ 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. */ @@ -813,32 +804,6 @@ public: */ 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 /** diff --git a/dali-toolkit/devel-api/visual-factory/precompile-shader-option.cpp b/dali-toolkit/devel-api/visual-factory/precompile-shader-option.cpp index b43fd0c594..39e924a251 100644 --- a/dali-toolkit/devel-api/visual-factory/precompile-shader-option.cpp +++ b/dali-toolkit/devel-api/visual-factory/precompile-shader-option.cpp @@ -19,76 +19,50 @@ #include // EXTERNAL INCLUDES -#include #include 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(Dali::Toolkit::PrecompileShaderOption::ShaderType::IMAGE)}, - {TOKEN_TYPE_TEXT, static_cast(Dali::Toolkit::PrecompileShaderOption::ShaderType::TEXT)}, - {TOKEN_TYPE_COLOR, static_cast(Dali::Toolkit::PrecompileShaderOption::ShaderType::COLOR)}, - {TOKEN_TYPE_MODEL_3D, static_cast(Dali::Toolkit::PrecompileShaderOption::ShaderType::MODEL_3D)}, - {TOKEN_TYPE_NPATCH, static_cast(Dali::Toolkit::PrecompileShaderOption::ShaderType::NPATCH)}, - {TOKEN_TYPE_CUSTOM, static_cast(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(Dali::Toolkit::PrecompileShaderOption::Flag::ROUNDED_CORNER)}, - {TOKEN_OPTION_BORDERLINE, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::BORDERLINE)}, - {TOKEN_OPTION_BLUR_EDGE, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::BLUR_EDGE)}, - {TOKEN_OPTION_CUTOUT, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::CUTOUT)}, - {TOKEN_OPTION_ATLAS_DEFAULT, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::ATLAS_DEFAULT)}, - {TOKEN_OPTION_ATLAS_CUSTOM, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::ATLAS_CUSTOM)}, - {TOKEN_OPTION_MASKING, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::MASKING)}, - {TOKEN_OPTION_YUV_TO_RGB, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::YUV_TO_RGB)}, - {TOKEN_OPTION_YUV_AND_RGB, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::YUV_AND_RGB)}, - {TOKEN_OPTION_MULTI_COLOR, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::MULTI_COLOR)}, - {TOKEN_OPTION_STYLES, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::STYLES)}, - {TOKEN_OPTION_OVERLAY, static_cast(Dali::Toolkit::PrecompileShaderOption::Flag::OVERLAY)}, - {TOKEN_OPTION_EMOJI, static_cast(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(), @@ -108,7 +82,7 @@ void PrecompileShaderOption::ConvertShaderMap(const Property::Map& shaderOption) 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); @@ -116,10 +90,43 @@ void PrecompileShaderOption::ConvertShaderMap(const Property::Map& shaderOption) 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().c_str()); - continue; + auto shaderType = value.Get(); + 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) @@ -134,19 +141,102 @@ void PrecompileShaderOption::ConvertShaderMap(const Property::Map& shaderOption) 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()) + { + mShaderOptions.push_back(Flag::ROUNDED_CORNER); + } + } + else if(optionKey == TOKEN_OPTION_BORDERLINE) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::BORDERLINE); + } + } + else if(optionKey == TOKEN_OPTION_CUTOUT) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::CUTOUT); + } + } + else if(optionKey == TOKEN_OPTION_ATLAS_DEFAULT) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::ATLAS_DEFAULT); + } + } + else if(optionKey == TOKEN_OPTION_ATLAS_CUSTOM) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::ATLAS_CUSTOM); + } + } + else if(optionKey == TOKEN_OPTION_BLUR_EDGE) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::BLUR_EDGE); + } + } + else if(optionKey == TOKEN_OPTION_MASKING) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::MASKING); + } + } + else if(optionKey == TOKEN_OPTION_YUV_TO_RGB) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::YUV_TO_RGB); + } + } + else if(optionKey == TOKEN_OPTION_YUV_AND_RGB) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::YUV_AND_RGB); + } + } + else if(optionKey == TOKEN_OPTION_MULTI_COLOR) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::MULTI_COLOR); + } + } + else if(optionKey == TOKEN_OPTION_STYLES) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::STYLES); + } + } + else if(optionKey == TOKEN_OPTION_OVERLAY) + { + if(optionPair.second.Get()) + { + mShaderOptions.push_back(Flag::OVERLAY); + } + } + else if(optionKey == TOKEN_OPTION_EMOJI) { if(optionPair.second.Get()) { - 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()); } } } @@ -218,7 +308,7 @@ uint32_t PrecompileShaderOption::GetNpatchXStretchCount() const return mNpatchXStretchCount; } -uint32_t PrecompileShaderOption::GetNpatchYStretchCount() const +uint32_t PrecompileShaderOption::GetNpatchYStretchCount() const { return mNpatchYStretchCount; } diff --git a/dali-toolkit/devel-api/visual-factory/precompile-shader-option.h b/dali-toolkit/devel-api/visual-factory/precompile-shader-option.h index 2a1a65a63a..4dc46e0df6 100644 --- a/dali-toolkit/devel-api/visual-factory/precompile-shader-option.h +++ b/dali-toolkit/devel-api/visual-factory/precompile-shader-option.h @@ -19,9 +19,9 @@ */ // EXTERNAL INCLUDES -#include #include #include +#include #include #include #include @@ -33,6 +33,7 @@ namespace Dali { namespace Toolkit { + /** * @brief PrecompiledShaderOption is a class for precompiled shader option. * @@ -112,8 +113,7 @@ public: enum class Flag { - UNKNOWN = 0, - ROUNDED_CORNER, + ROUNDED_CORNER = 0, BORDERLINE, BLUR_EDGE, CUTOUT, @@ -136,7 +136,7 @@ public: PrecompileShaderOption(const PrecompileShaderOption& rhs); PrecompileShaderOption& operator=(const PrecompileShaderOption& rhs); - using ShaderOptions = std::vector; + using ShaderOptions= std::vector; public: /** @@ -186,7 +186,7 @@ public: */ uint32_t GetNpatchXStretchCount() const; - /** + /** * @brief Get the YStretchCount for npatch * * @return The NpatchYStretchCount @@ -194,13 +194,13 @@ public: 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 mShaderOptions; + std::string mShaderName; + std::string mVertexShader; + std::string mFragmentShader; + uint32_t mNpatchXStretchCount; + uint32_t mNpatchYStretchCount; }; } // namespace Toolkit diff --git a/dali-toolkit/internal/controls/control/control-data-impl.cpp b/dali-toolkit/internal/controls/control/control-data-impl.cpp index fe933d9ee6..9ded0d25b6 100644 --- a/dali-toolkit/internal/controls/control/control-data-impl.cpp +++ b/dali-toolkit/internal/controls/control/control-data-impl.cpp @@ -1588,7 +1588,7 @@ void Control::Impl::SetProperty(BaseObject* object, Property::Index index, const bool highlightable; if(value.Get(highlightable)) { - controlImpl.mImpl->mAccessibilityProps.isHighlightable = highlightable ? TriStateProperty::TRUE : TriStateProperty::FALSE; + controlImpl.mImpl->mAccessibilityProps.isHighlightable = highlightable; } break; } @@ -1835,7 +1835,7 @@ Property::Value Control::Impl::GetProperty(BaseObject* object, Property::Index i case Toolkit::DevelControl::Property::ACCESSIBILITY_HIGHLIGHTABLE: { - value = controlImpl.mImpl->mAccessibilityProps.isHighlightable == TriStateProperty::TRUE ? true : false; + value = controlImpl.mImpl->mAccessibilityProps.isHighlightable; break; } diff --git a/dali-toolkit/internal/controls/control/control-data-impl.h b/dali-toolkit/internal/controls/control/control-data-impl.h index f3ce3d264d..71c6d3c69c 100644 --- a/dali-toolkit/internal/controls/control/control-data-impl.h +++ b/dali-toolkit/internal/controls/control/control-data-impl.h @@ -71,13 +71,6 @@ struct RegisteredVisual typedef Dali::OwnerContainer RegisteredVisualContainer; -enum class TriStateProperty -{ - AUTO = 0, - TRUE, - FALSE -}; - /** * @brief Holds the Implementation for the internal control class */ @@ -638,11 +631,11 @@ public: std::string description{}; std::string value{}; std::string automationId{}; - int32_t role{static_cast(DevelControl::AccessibilityRole::NONE)}; + int32_t role{static_cast(Dali::Accessibility::Role::UNKNOWN)}; DevelControl::AccessibilityStates states{}; std::map> relations; Property::Map extraAttributes{}; - TriStateProperty isHighlightable{TriStateProperty::AUTO}; + bool isHighlightable{false}; bool isHidden{false}; bool isScrollable{false}; bool isModal{false}; diff --git a/dali-toolkit/internal/controls/render-effects/blur-effect-impl.cpp b/dali-toolkit/internal/controls/render-effects/blur-effect-impl.cpp index fa64963d37..e360d31435 100644 --- a/dali-toolkit/internal/controls/render-effects/blur-effect-impl.cpp +++ b/dali-toolkit/internal/controls/render-effects/blur-effect-impl.cpp @@ -22,33 +22,28 @@ #include #include #include -#include #include #include #include -#include -// INTERNAL INCLUDES +//INTERNAL INCLUDES #include #include #include #include -#include 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 @@ -78,7 +73,6 @@ BlurEffectImpl::BlurEffectImpl(bool isBackground) mDownscaleFactor(BLUR_EFFECT_DOWNSCALE_FACTOR), mPixelRadius(BLUR_EFFECT_PIXEL_RADIUS), mBellCurveWidth(Math::MACHINE_EPSILON_1), - mSkipBlur(false), mIsBackground(isBackground) { } @@ -89,38 +83,17 @@ BlurEffectImpl::BlurEffectImpl(float downscaleFactor, uint32_t blurRadius, bool 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(fixedBlurRadius) / static_cast(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(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; } } @@ -142,54 +115,8 @@ BlurEffectImplPtr BlurEffectImpl::New(float downscaleFactor, uint32_t blurRadius return handle; } -OffScreenRenderable::Type BlurEffectImpl::GetOffScreenRenderableType() -{ - return mSkipBlur ? OffScreenRenderable::NONE : OffScreenRenderable::BACKWARD; -} - -void BlurEffectImpl::GetOffScreenRenderTasks(std::vector& 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(); @@ -212,25 +139,28 @@ void BlurEffectImpl::OnInitialize() 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 { @@ -262,11 +192,6 @@ void BlurEffectImpl::OnInitialize() void BlurEffectImpl::OnActivate() { - if(DALI_UNLIKELY(mSkipBlur)) - { - return; - } - Toolkit::Control ownerControl = GetOwnerControl(); DALI_ASSERT_ALWAYS(ownerControl && "Set the owner of RenderEffect before you activate."); @@ -298,7 +223,7 @@ void BlurEffectImpl::OnActivate() mPlacementSceneHolder = sceneHolder; // Set blur - CreateFrameBuffers(size, ImageDimensions(downsampledWidth, downsampledHeight)); + CreateFrameBuffers(size, Size(downsampledWidth, downsampledHeight)); CreateRenderTasks(sceneHolder, ownerControl); SetShaderConstants(downsampledWidth, downsampledHeight); @@ -320,11 +245,6 @@ void BlurEffectImpl::OnActivate() void BlurEffectImpl::OnDeactivate() { - if(DALI_UNLIKELY(mSkipBlur)) - { - return; - } - auto ownerControl = GetOwnerControl(); if(DALI_LIKELY(ownerControl)) { @@ -354,10 +274,10 @@ void BlurEffectImpl::OnDeactivate() 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); @@ -390,6 +310,7 @@ void BlurEffectImpl::CreateRenderTasks(Integration::SceneHolder sceneHolder, con { mSourceRenderTask.SetSourceActor(sourceControl); } + mSourceRenderTask.SetOrderIndex(BLUR_EFFECT_ORDER_INDEX); mSourceRenderTask.SetCameraActor(mRenderFullSizeCamera); mSourceRenderTask.SetFrameBuffer(mInputBackgroundFrameBuffer); mSourceRenderTask.SetInputEnabled(false); @@ -403,6 +324,7 @@ void BlurEffectImpl::CreateRenderTasks(Integration::SceneHolder sceneHolder, con 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); @@ -416,6 +338,7 @@ void BlurEffectImpl::CreateRenderTasks(Integration::SceneHolder sceneHolder, con 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); @@ -449,11 +372,11 @@ Vector2 BlurEffectImpl::GetTargetSizeForValidTexture() const 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 uvOffsets(sampleCount); diff --git a/dali-toolkit/internal/controls/render-effects/blur-effect-impl.h b/dali-toolkit/internal/controls/render-effects/blur-effect-impl.h index def332405b..4331255c67 100644 --- a/dali-toolkit/internal/controls/render-effects/blur-effect-impl.h +++ b/dali-toolkit/internal/controls/render-effects/blur-effect-impl.h @@ -22,7 +22,6 @@ #include #include #include -#include #include #include #include @@ -69,16 +68,6 @@ public: */ 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& tasks, bool isForward) override; - protected: /** * @brief Creates an uninitialized blur effect implementation @@ -121,7 +110,7 @@ private: * @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. @@ -144,7 +133,7 @@ private: * @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 @@ -195,7 +184,6 @@ private: uint32_t mPixelRadius; float mBellCurveWidth; - bool mSkipBlur : 1; bool mIsBackground : 1; }; } // namespace Internal diff --git a/dali-toolkit/internal/controls/render-effects/render-effect-impl.h b/dali-toolkit/internal/controls/render-effects/render-effect-impl.h index 39a7abde00..3913bcbdcd 100644 --- a/dali-toolkit/internal/controls/render-effects/render-effect-impl.h +++ b/dali-toolkit/internal/controls/render-effects/render-effect-impl.h @@ -60,29 +60,6 @@ public: */ 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& tasks, bool isForward) = 0; - protected: /** * @copydoc Dali::Toolkit::RenderEffect::RenderEffect diff --git a/dali-toolkit/internal/controls/text-controls/text-anchor-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-anchor-impl.cpp index 2bc12b01a3..8abb0aeaac 100644 --- a/dali-toolkit/internal/controls/text-controls/text-anchor-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-anchor-impl.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -146,7 +146,8 @@ void TextAnchor::OnInitialize() 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() diff --git a/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp index 04b3a431df..33deefc46e 100644 --- a/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-editor-impl.cpp @@ -632,7 +632,8 @@ void TextEditor::OnInitialize() 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); diff --git a/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp index b4fd8d73a5..cd098c84f4 100644 --- a/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-field-impl.cpp @@ -540,7 +540,8 @@ void TextField::OnInitialize() } // 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); @@ -862,8 +863,7 @@ bool TextField::OnKeyEvent(const KeyEvent& event) 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; diff --git a/dali-toolkit/internal/controls/text-controls/text-field-property-handler.cpp b/dali-toolkit/internal/controls/text-controls/text-field-property-handler.cpp index 91b6f2523d..5151ef1c68 100644 --- a/dali-toolkit/internal/controls/text-controls/text-field-property-handler.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-field-property-handler.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -20,8 +20,8 @@ #include #include -#include #include +#include #include #include #include @@ -512,11 +512,11 @@ void TextField::PropertyHandler::SetProperty(Toolkit::TextField textField, Prope auto mode = map->Find(Toolkit::HiddenInput::Property::MODE); if(mode && (mode->Get() != 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; diff --git a/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp b/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp index 02405a87c5..d66cfc0398 100644 --- a/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp +++ b/dali-toolkit/internal/controls/text-controls/text-label-impl.cpp @@ -1110,7 +1110,8 @@ void TextLabel::OnInitialize() 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); diff --git a/dali-toolkit/internal/controls/web-view/web-view-impl.cpp b/dali-toolkit/internal/controls/web-view/web-view-impl.cpp index 6457270424..ff4665e71c 100644 --- a/dali-toolkit/internal/controls/web-view/web-view-impl.cpp +++ b/dali-toolkit/internal/controls/web-view/web-view-impl.cpp @@ -179,7 +179,7 @@ WebView::WebView(const std::string& locale, const std::string& timezoneId) } } -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()), @@ -196,7 +196,7 @@ WebView::WebView(uint32_t argc, char** argv, int32_t type) 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) @@ -247,9 +247,9 @@ Toolkit::WebView WebView::New(const std::string& locale, const std::string& time 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()) { @@ -913,38 +913,6 @@ void WebView::GetPlainTextAsynchronously(Dali::WebEnginePlugin::PlainTextReceive } } -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) @@ -953,49 +921,55 @@ void WebView::OnFrameRendered() } // 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(); } - 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(); } - // 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); + } } } diff --git a/dali-toolkit/internal/controls/web-view/web-view-impl.h b/dali-toolkit/internal/controls/web-view/web-view-impl.h index ef66fd3db8..3a7ee88206 100644 --- a/dali-toolkit/internal/controls/web-view/web-view-impl.h +++ b/dali-toolkit/internal/controls/web-view/web-view-impl.h @@ -52,7 +52,7 @@ protected: 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(); @@ -68,9 +68,9 @@ public: 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() @@ -447,26 +447,6 @@ public: */ 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. diff --git a/dali-toolkit/internal/file.list b/dali-toolkit/internal/file.list index 0753d01aae..4464dbb594 100644 --- a/dali-toolkit/internal/file.list +++ b/dali-toolkit/internal/file.list @@ -38,6 +38,7 @@ SET( toolkit_src_files ${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 @@ -51,7 +52,6 @@ SET( toolkit_src_files ${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 @@ -243,7 +243,6 @@ SET( toolkit_src_files ${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 diff --git a/dali-toolkit/internal/graphics/shaders/image-visual-shader.frag b/dali-toolkit/internal/graphics/shaders/image-visual-shader.frag index 2a3e2c7d06..13ebeb972a 100644 --- a/dali-toolkit/internal/graphics/shaders/image-visual-shader.frag +++ b/dali-toolkit/internal/graphics/shaders/image-visual-shader.frag @@ -238,9 +238,9 @@ lowp vec4 ConvertYuvToRgba(mediump vec2 texCoord) } #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); diff --git a/dali-toolkit/internal/styling/style-manager-impl.cpp b/dali-toolkit/internal/styling/style-manager-impl.cpp index 8903bc1ecb..8cd7ba5a5f 100644 --- a/dali-toolkit/internal/styling/style-manager-impl.cpp +++ b/dali-toolkit/internal/styling/style-manager-impl.cpp @@ -1,5 +1,5 @@ /* - * 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. @@ -369,15 +369,7 @@ bool StyleManager::LoadJSON(Toolkit::Builder builder, const std::string& jsonFil 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 diff --git a/dali-toolkit/internal/text/controller/text-controller-impl.cpp b/dali-toolkit/internal/text/controller/text-controller-impl.cpp index 5e7a5b3d9f..a33ebe3e78 100644 --- a/dali-toolkit/internal/text/controller/text-controller-impl.cpp +++ b/dali-toolkit/internal/text/controller/text-controller-impl.cpp @@ -1675,8 +1675,8 @@ bool Controller::Impl::IsScrollable(const Vector2& displacement) 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) { @@ -1768,26 +1768,6 @@ int32_t Controller::Impl::GetAnchorIndex(size_t characterOffset) const 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()) ? 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 diff --git a/dali-toolkit/internal/text/controller/text-controller-impl.h b/dali-toolkit/internal/text/controller/text-controller-impl.h index 1861fdd1a3..f172b17c9a 100644 --- a/dali-toolkit/internal/text/controller/text-controller-impl.h +++ b/dali-toolkit/internal/text/controller/text-controller-impl.h @@ -316,15 +316,6 @@ struct OutlineDefaults struct Controller::Impl { -public: - enum class ClearFocusOnEscapeState - { - UNKNOWN = -1, ///< Unknown state - ENABLE = 0, - DISABLE = 1, - }; - -public: Impl(ControlInterface* controlInterface, EditableControlInterface* editableControlInterface, SelectableControlInterface* selectableControlInterface, @@ -369,7 +360,7 @@ public: mOutlineSetByString(false), mFontStyleSetByString(false), mStrikethroughSetByString(false), - mShouldClearFocusOnEscape(ClearFocusOnEscapeState::UNKNOWN), + mShouldClearFocusOnEscape(true), mLayoutDirection(LayoutDirection::LEFT_TO_RIGHT), mCurrentLineSize(0.f), mTextFitMinSize(DEFAULT_TEXTFIT_MIN), @@ -406,6 +397,15 @@ public: // 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()); + } } ~Impl() @@ -1012,16 +1012,6 @@ public: */ 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. @@ -1090,25 +1080,21 @@ public: std::vector 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. diff --git a/dali-toolkit/internal/text/controller/text-controller.cpp b/dali-toolkit/internal/text/controller/text-controller.cpp index 0b398ecd6e..dfeed9eee9 100644 --- a/dali-toolkit/internal/text/controller/text-controller.cpp +++ b/dali-toolkit/internal/text/controller/text-controller.cpp @@ -1961,7 +1961,7 @@ void Controller::SetAnchorControlInterface(AnchorControlInterface* anchorControl bool Controller::ShouldClearFocusOnEscape() const { - return mImpl->ShouldClearFocusOnEscape(); + return mImpl->mShouldClearFocusOnEscape; } Actor Controller::CreateBackgroundActor() diff --git a/dali-toolkit/internal/text/rendering/text-typesetter-impl.cpp b/dali-toolkit/internal/text/rendering/text-typesetter-impl.cpp deleted file mode 100644 index fcf2c56fbb..0000000000 --- a/dali-toolkit/internal/text/rendering/text-typesetter-impl.cpp +++ /dev/null @@ -1,1409 +0,0 @@ -/* - * 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 - -// EXTERNAL INCLUDES -#include -#include -#include -#include -#include -#include -#include - -// INTERNAL INCLUDES -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -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(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(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(data.glyphBitmap.height), static_cast(data.height) - yOffset); - const int32_t indexRangeMin = std::max(0, -xOffset); - const int32_t indexRangeMax = std::min(static_cast(data.glyphBitmap.width), static_cast(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(data.bitmapBuffer.GetBuffer()); - // Skip basic line. - bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast(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(&packedInputColor); - - *(packedInputColorBuffer + 3u) = static_cast(color->a * 255); - *(packedInputColorBuffer + 2u) = static_cast(color->b * 255); - *(packedInputColorBuffer + 1u) = static_cast(color->g * 255); - *(packedInputColorBuffer) = static_cast(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(glyphScanline + (index << 2))); - uint8_t* __restrict__ packedColorGlyphBuffer = reinterpret_cast(&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(¤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(&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(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(glyphData.verticalOffset + baseline - line.ascender)); - const int32_t yRangeMax = std::min(static_cast(bufferHeight), static_cast(glyphData.verticalOffset + baseline - line.descender)); - const int32_t xRangeMin = std::max(0, static_cast(glyphData.horizontalOffset + lineExtentLeft)); - const int32_t xRangeMax = std::min(static_cast(bufferWidth), static_cast(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(backgroundColor.a * 255.f); - - uint32_t* bitmapBuffer = reinterpret_cast(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(&packedBackgroundColor); - - // Write the color to the pixel buffer - *(packedBackgroundColorBuffer + 3u) = backgroundColorAlpha; - *(packedBackgroundColorBuffer + 2u) = static_cast(backgroundColor.b * backgroundColorAlpha); - *(packedBackgroundColorBuffer + 1u) = static_cast(backgroundColor.g * backgroundColorAlpha); - *(packedBackgroundColorBuffer) = static_cast(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(maxUnderlineHeight)); - const uint32_t xRangeMin = static_cast(glyphData.horizontalOffset + lineExtentLeft); - const uint32_t xRangeMax = std::min(bufferWidth, static_cast(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(underlineColor.a * 255.f); - - uint32_t* bitmapBuffer = reinterpret_cast(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(std::max(0, secondUnderlineYOffset)); - const uint32_t secondYRangeMax = static_cast(std::max(0, std::min(static_cast(bufferHeight), secondUnderlineYOffset + static_cast(maxUnderlineHeight)))); - - // Rewind bitmapBuffer pointer, and skip secondYRangeMin line. - bitmapBuffer = reinterpret_cast(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(&packedUnderlineColor); - - // Write the color to the pixel buffer - *(packedUnderlineColorBuffer + 3u) = underlineColorAlpha; - *(packedUnderlineColorBuffer + 2u) = static_cast(underlineColor.b * underlineColorAlpha); - *(packedUnderlineColorBuffer + 1u) = static_cast(underlineColor.g * underlineColorAlpha); - *(packedUnderlineColorBuffer) = static_cast(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(std::max(0, secondUnderlineYOffset)); - const uint32_t secondYRangeMax = static_cast(std::max(0, std::min(static_cast(bufferHeight), secondUnderlineYOffset + static_cast(maxUnderlineHeight)))); - - // Rewind bitmapBuffer pointer, and skip secondYRangeMin line. - bitmapBuffer = reinterpret_cast(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(strikethroughStartingYPosition); - const uint32_t yRangeMax = std::min(bufferHeight, static_cast(strikethroughStartingYPosition + maxStrikethroughHeight)); - const uint32_t xRangeMin = static_cast(glyphData.horizontalOffset + lineExtentLeft); - const uint32_t xRangeMax = std::min(bufferWidth, static_cast(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(strikethroughColor.a * 255.f); - - uint32_t* bitmapBuffer = reinterpret_cast(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(&packedStrikethroughColor); - - // Write the color to the pixel buffer - *(packedStrikethroughColorBuffer + 3u) = strikethroughColorAlpha; - *(packedStrikethroughColorBuffer + 2u) = static_cast(strikethroughColor.b * strikethroughColorAlpha); - *(packedStrikethroughColorBuffer + 1u) = static_cast(strikethroughColor.g * strikethroughColorAlpha); - *(packedStrikethroughColorBuffer) = static_cast(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& underlineRuns; - const Vector& strikethroughRuns; - const Vector& 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::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::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(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(line.alignmentOffset); - glyphData.horizontalOffset += inputParamsForLine.horizontalOffset; - - // Increases the vertical offset with the line's ascender. - glyphData.verticalOffset += static_cast(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(-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(bufferSizeInt); - memset(imageBuffer.GetBuffer(), 0, bufferSizeChar); - } - else - { - memset(imageBuffer.GetBuffer(), 0, static_cast(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(line.alignmentOffset); - glyphData.horizontalOffset += horizontalOffset; - - // Increases the vertical offset with the line's ascender. - glyphData.verticalOffset += static_cast(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(-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& __restrict__ glyphToCharacterMap = viewModel.GetGlyphsToCharacters(); - const CharacterIndex* __restrict__ glyphToCharacterMapBuffer = glyphToCharacterMap.Begin(); - - // Get the underline runs. - const Length numberOfUnderlineRuns = viewModel.GetNumberOfUnderlineRuns(); - Vector underlineRuns; - underlineRuns.Resize(numberOfUnderlineRuns); - viewModel.GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns); - - // Get the strikethrough runs. - const Length numberOfStrikethroughRuns = viewModel.GetNumberOfStrikethroughRuns(); - Vector strikethroughRuns; - strikethroughRuns.Resize(numberOfStrikethroughRuns); - viewModel.GetStrikethroughRuns(strikethroughRuns.Begin(), 0u, numberOfStrikethroughRuns); - - // Get the character-spacing runs. - const Vector& __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(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(model)) -{ - // Default font client set. - mFontClient = TextAbstraction::FontClient::Get(); -} - -Typesetter::Impl::~Impl() = default; - -} // namespace Text - -} // namespace Toolkit - -} // namespace Dali diff --git a/dali-toolkit/internal/text/rendering/text-typesetter-impl.h b/dali-toolkit/internal/text/rendering/text-typesetter-impl.h deleted file mode 100644 index d0d7a3e126..0000000000 --- a/dali-toolkit/internal/text/rendering/text-typesetter-impl.h +++ /dev/null @@ -1,131 +0,0 @@ -#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 -#include -#include -#include -#include -#include -#include -#include ///< for std::unique_ptr - -// INTERNAL INCLUDES -#include - -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 mModel; - TextAbstraction::FontClient mFontClient; -}; - -} // namespace Text - -} // namespace Toolkit - -} // namespace Dali - -#endif // DALI_TOOLKIT_TEXT_TYPESETTER_IMPL_H diff --git a/dali-toolkit/internal/text/rendering/text-typesetter.cpp b/dali-toolkit/internal/text/rendering/text-typesetter.cpp index 52747a3ccd..503b39438a 100644 --- a/dali-toolkit/internal/text/rendering/text-typesetter.cpp +++ b/dali-toolkit/internal/text/rendering/text-typesetter.cpp @@ -19,13 +19,13 @@ #include // EXTERNAL INCLUDES +#include #include #include #include #include #include #include -#include // INTERNAL INCLUDES #include @@ -34,7 +34,6 @@ #include #include #include -#include #include namespace Dali @@ -47,6 +46,9 @@ 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 * @@ -74,7 +76,746 @@ inline uint8_t MultiplyAndSummationAndNormalizeColor(const uint8_t x1, const uin const uint32_t xy1 = static_cast(x1) * y1; const uint32_t xy2 = static_cast(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(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(data.glyphBitmap.height), static_cast(data.height) - yOffset); + const int32_t indexRangeMin = std::max(0, -xOffset); + const int32_t indexRangeMax = std::min(static_cast(data.glyphBitmap.width), static_cast(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(data.bitmapBuffer.GetBuffer()); + // Skip basic line. + bitmapBuffer += (lineIndexRangeMin + yOffset) * static_cast(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(&packedInputColor); + + *(packedInputColorBuffer + 3u) = static_cast(color->a * 255); + *(packedInputColorBuffer + 2u) = static_cast(color->b * 255); + *(packedInputColorBuffer + 1u) = static_cast(color->g * 255); + *(packedInputColorBuffer) = static_cast(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(glyphScanline + (index << 2))); + uint8_t* __restrict__ packedColorGlyphBuffer = reinterpret_cast(&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(¤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(&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(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(maxUnderlineHeight)); + const uint32_t xRangeMin = static_cast(glyphData.horizontalOffset + lineExtentLeft); + const uint32_t xRangeMax = std::min(bufferWidth, static_cast(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(underlineColor.a * 255.f); + + uint32_t* bitmapBuffer = reinterpret_cast(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(std::max(0, secondUnderlineYOffset)); + const uint32_t secondYRangeMax = static_cast(std::max(0, std::min(static_cast(bufferHeight), secondUnderlineYOffset + static_cast(maxUnderlineHeight)))); + + // Rewind bitmapBuffer pointer, and skip secondYRangeMin line. + bitmapBuffer = reinterpret_cast(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(&packedUnderlineColor); + + // Write the color to the pixel buffer + *(packedUnderlineColorBuffer + 3u) = underlineColorAlpha; + *(packedUnderlineColorBuffer + 2u) = static_cast(underlineColor.b * underlineColorAlpha); + *(packedUnderlineColorBuffer + 1u) = static_cast(underlineColor.g * underlineColorAlpha); + *(packedUnderlineColorBuffer) = static_cast(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(std::max(0, secondUnderlineYOffset)); + const uint32_t secondYRangeMax = static_cast(std::max(0, std::min(static_cast(bufferHeight), secondUnderlineYOffset + static_cast(maxUnderlineHeight)))); + + // Rewind bitmapBuffer pointer, and skip secondYRangeMin line. + bitmapBuffer = reinterpret_cast(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(glyphData.verticalOffset + baseline - line.ascender)); + const int32_t yRangeMax = std::min(static_cast(bufferHeight), static_cast(glyphData.verticalOffset + baseline - line.descender)); + const int32_t xRangeMin = std::max(0, static_cast(glyphData.horizontalOffset + lineExtentLeft)); + const int32_t xRangeMax = std::min(static_cast(bufferWidth), static_cast(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(backgroundColor.a * 255.f); + + uint32_t* bitmapBuffer = reinterpret_cast(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(&packedBackgroundColor); + + // Write the color to the pixel buffer + *(packedBackgroundColorBuffer + 3u) = backgroundColorAlpha; + *(packedBackgroundColorBuffer + 2u) = static_cast(backgroundColor.b * backgroundColorAlpha); + *(packedBackgroundColorBuffer + 1u) = static_cast(backgroundColor.g * backgroundColorAlpha); + *(packedBackgroundColorBuffer) = static_cast(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(line.alignmentOffset); + glyphData.horizontalOffset += horizontalOffset; + + // Increases the vertical offset with the line's ascender. + glyphData.verticalOffset += static_cast(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(-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(strikethroughStartingYPosition); + const uint32_t yRangeMax = std::min(bufferHeight, static_cast(strikethroughStartingYPosition + maxStrikethroughHeight)); + const uint32_t xRangeMin = static_cast(glyphData.horizontalOffset + lineExtentLeft); + const uint32_t xRangeMax = std::min(bufferWidth, static_cast(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(strikethroughColor.a * 255.f); + + uint32_t* bitmapBuffer = reinterpret_cast(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(&packedStrikethroughColor); + + // Write the color to the pixel buffer + *(packedStrikethroughColorBuffer + 3u) = strikethroughColorAlpha; + *(packedStrikethroughColorBuffer + 2u) = static_cast(strikethroughColor.b * strikethroughColorAlpha); + *(packedStrikethroughColorBuffer + 1u) = static_cast(strikethroughColor.g * strikethroughColorAlpha); + *(packedStrikethroughColorBuffer) = static_cast(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(bufferSizeInt); + memset(imageBuffer.GetBuffer(), 0, bufferSizeChar); + } + else + { + memset(imageBuffer.GetBuffer(), 0, static_cast(bufferWidth * bufferHeight)); + } + + return imageBuffer; } /** @@ -104,13 +845,13 @@ void CombineImageBuffer(Devel::PixelBuffer& __restrict__ topPixelBuffer, Devel:: uint32_t* topBuffer = reinterpret_cast(topPixelBuffer.GetBuffer()); uint32_t* bottomBuffer = reinterpret_cast(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. @@ -121,7 +862,7 @@ void CombineImageBuffer(Devel::PixelBuffer& __restrict__ topPixelBuffer, Devel:: 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. @@ -193,18 +934,18 @@ TypesetterPtr Typesetter::New(const ModelInterface* const model) 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; } @@ -224,19 +965,16 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki 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(viewModel.GetOutlineWidth()); + const Size& layoutSize = mModel->GetLayoutSize(); + const int32_t outlineWidth = static_cast(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: { @@ -257,7 +995,7 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki // Set the offset for the vertical alignment. int32_t penY = 0u; - switch(viewModel.GetVerticalAlignment()) + switch(mModel->GetVerticalAlignment()) { case VerticalAlignment::TOP: { @@ -278,12 +1016,12 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki } } - 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, @@ -298,15 +1036,15 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki const size_t bufferSizeChar = sizeof(uint32_t) * static_cast(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) { @@ -317,20 +1055,20 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki 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) { @@ -344,15 +1082,15 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki // @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) { @@ -364,24 +1102,24 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki } // 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 @@ -389,12 +1127,12 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki } // 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); @@ -402,33 +1140,33 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki 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); } @@ -441,8 +1179,8 @@ Devel::PixelBuffer Typesetter::RenderWithPixelBuffer(const Vector2& size, Toolki 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(backgroundColor.a * 255.f); + const uint32_t bufferSizeInt = bufferWidth * bufferHeight; + uint8_t backgroundColorAlpha = static_cast(backgroundColor.a * 255.f); Devel::PixelBuffer buffer = Devel::PixelBuffer::New(bufferWidth, bufferHeight, Pixel::RGBA8888); @@ -462,17 +1200,412 @@ Devel::PixelBuffer Typesetter::CreateFullBackgroundBuffer(const uint32_t bufferW 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& __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(line.alignmentOffset); + glyphData.horizontalOffset += horizontalOffset; + + // Increases the vertical offset with the line's ascender. + glyphData.verticalOffset += static_cast(line.ascender + GetPreOffsetVerticalLineAlignment(line, verLineAlign)); + + // Retrieves the glyph's outline width + float outlineWidth = static_cast(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& __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 underlineRuns; + underlineRuns.Resize(numberOfUnderlineRuns); + mModel->GetUnderlineRuns(underlineRuns.Begin(), 0u, numberOfUnderlineRuns); + + // Get the strikethrough runs. + const Length numberOfStrikethroughRuns = mModel->GetNumberOfStrikethroughRuns(); + Vector 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::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::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(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(-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 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::ConstIterator itGlyphRun = underlineRuns.Begin(); @@ -486,7 +1619,7 @@ Devel::PixelBuffer Typesetter::ApplyUnderlineMarkupImageBuffer(Devel::PixelBuffe 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); @@ -499,15 +1632,12 @@ Devel::PixelBuffer Typesetter::ApplyUnderlineMarkupImageBuffer(Devel::PixelBuffe 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 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::ConstIterator itGlyphRun = strikethroughRuns.Begin(); @@ -521,7 +1651,7 @@ Devel::PixelBuffer Typesetter::ApplyStrikethroughMarkupImageBuffer(Devel::PixelB 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); @@ -539,7 +1669,7 @@ void Typesetter::SetMaskForImageBuffer(Devel::PixelBuffer& __restrict__ topPixel uint32_t* topBuffer = reinterpret_cast(topPixelBuffer.GetBuffer()); uint32_t* bottomBuffer = reinterpret_cast(bottomPixelBuffer.GetBuffer()); - if(topBuffer == nullptr || bottomBuffer == nullptr) + if(topBuffer == NULL || bottomBuffer == NULL) { // Nothing to do if one of both buffers are empty. return; @@ -549,15 +1679,15 @@ void Typesetter::SetMaskForImageBuffer(Devel::PixelBuffer& __restrict__ topPixel for(uint32_t pixelIndex = 0; pixelIndex < bufferSizeInt; ++pixelIndex) { - uint32_t topBufferColor = *(topBuffer); - uint32_t bottomBufferColor = *(bottomBuffer); - uint8_t* __restrict__ topBufferColorBuffer = reinterpret_cast(&topBufferColor); + uint32_t topBufferColor = *(topBuffer); + uint32_t bottomBufferColor = *(bottomBuffer); + uint8_t* __restrict__ topBufferColorBuffer = reinterpret_cast(&topBufferColor); uint8_t* __restrict__ bottomBufferColorBuffer = reinterpret_cast(&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. @@ -575,11 +1705,17 @@ void Typesetter::SetMaskForImageBuffer(Devel::PixelBuffer& __restrict__ topPixel } Typesetter::Typesetter(const ModelInterface* const model) -: mImpl{std::make_unique(model)} +: mModel(new ViewModel(model)), + mFontClient() { + // Default font client set. + mFontClient = TextAbstraction::FontClient::Get(); } -Typesetter::~Typesetter() = default; +Typesetter::~Typesetter() +{ + delete mModel; +} } // namespace Text diff --git a/dali-toolkit/internal/text/rendering/text-typesetter.h b/dali-toolkit/internal/text/rendering/text-typesetter.h index bdbd598d4f..88d73f59b1 100644 --- a/dali-toolkit/internal/text/rendering/text-typesetter.h +++ b/dali-toolkit/internal/text/rendering/text-typesetter.h @@ -2,7 +2,7 @@ #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. @@ -21,13 +21,12 @@ // EXTERNAL INCLUDES #include #include -#include #include +#include #include #include #include #include -#include ///< for std::unique_ptr namespace Dali { @@ -190,6 +189,28 @@ private: // 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. * @@ -241,8 +262,8 @@ protected: virtual ~Typesetter(); private: - struct Impl; - std::unique_ptr mImpl; + ViewModel* mModel; + TextAbstraction::FontClient mFontClient; }; } // namespace Text diff --git a/dali-toolkit/internal/texture-manager/texture-cache-manager.cpp b/dali-toolkit/internal/texture-manager/texture-cache-manager.cpp index 0d8925704a..19c19bf318 100644 --- a/dali-toolkit/internal/texture-manager/texture-cache-manager.cpp +++ b/dali-toolkit/internal/texture-manager/texture-cache-manager.cpp @@ -525,8 +525,8 @@ TextureCacheManager::TextureHash TextureCacheManager::GenerateHash( *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. diff --git a/dali-toolkit/internal/texture-manager/texture-manager-type.h b/dali-toolkit/internal/texture-manager/texture-manager-type.h index 10f0cec5de..1f54fb7cbe 100644 --- a/dali-toolkit/internal/texture-manager/texture-manager-type.h +++ b/dali-toolkit/internal/texture-manager/texture-manager-type.h @@ -270,8 +270,8 @@ struct TextureInfo 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 diff --git a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp index a643e0153c..4ccaa6641d 100644 --- a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp +++ b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.cpp @@ -57,7 +57,6 @@ DALI_ENUM_TO_STRING_TABLE_BEGIN(FITTING_MODE) 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) @@ -70,9 +69,6 @@ DALI_ENUM_TO_STRING_TABLE_BEGIN(SAMPLING_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 @@ -286,9 +282,9 @@ AnimatedImageVisual::AnimatedImageVisual(VisualFactoryCache& factoryCache, Image 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) { diff --git a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.h b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.h index e65cd7a142..63e87aeb15 100644 --- a/dali-toolkit/internal/visuals/animated-image/animated-image-visual.h +++ b/dali-toolkit/internal/visuals/animated-image/animated-image-visual.h @@ -314,9 +314,9 @@ private: 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; }; diff --git a/dali-toolkit/internal/visuals/animated-image/image-cache.cpp b/dali-toolkit/internal/visuals/animated-image/image-cache.cpp index 4574e01535..ece9014ea7 100644 --- a/dali-toolkit/internal/visuals/animated-image/image-cache.cpp +++ b/dali-toolkit/internal/visuals/animated-image/image-cache.cpp @@ -36,11 +36,11 @@ ImageCache::ImageCache(TextureManager& textureManager, 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) { diff --git a/dali-toolkit/internal/visuals/animated-image/image-cache.h b/dali-toolkit/internal/visuals/animated-image/image-cache.h index 84c4d1e311..aee80b2751 100644 --- a/dali-toolkit/internal/visuals/animated-image/image-cache.h +++ b/dali-toolkit/internal/visuals/animated-image/image-cache.h @@ -144,11 +144,11 @@ protected: 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; }; diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp index 8727a1514e..08a37f6cfb 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-task.cpp @@ -747,12 +747,7 @@ bool VectorAnimationTask::Rasterize() oss << "["; oss << "d:" << static_cast(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() << "]"; @@ -809,12 +804,13 @@ VectorAnimationTask::TimePoint VectorAnimationTask::CalculateNextFrameTime(bool } else { - uint32_t droppedFrames = 0; const auto durationMicroSeconds = std::chrono::microseconds(mFrameDurationMicroSeconds); mNextFrameStartTime = std::chrono::time_point_cast(mNextFrameStartTime + durationMicroSeconds); if(mNextFrameStartTime < current) { + uint32_t droppedFrames = 0; + while(current > std::chrono::time_point_cast(mNextFrameStartTime + durationMicroSeconds) && droppedFrames < mTotalFrame) { droppedFrames++; @@ -822,8 +818,8 @@ VectorAnimationTask::TimePoint VectorAnimationTask::CalculateNextFrameTime(bool } mNextFrameStartTime = current; + mDroppedFrames = droppedFrames; } - mDroppedFrames = droppedFrames; } return mNextFrameStartTime; diff --git a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp index 633a28d1bf..ff9b7770fb 100644 --- a/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp +++ b/dali-toolkit/internal/visuals/animated-vector-image/vector-animation-thread.cpp @@ -509,12 +509,9 @@ void VectorAnimationThread::SleepThread::SleepUntil(std::chrono::time_point 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(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); } } } diff --git a/dali-toolkit/internal/visuals/color/color-visual-shader-factory.cpp b/dali-toolkit/internal/visuals/color/color-visual-shader-factory.cpp index 54dd9f62a2..c4ca4e9e38 100644 --- a/dali-toolkit/internal/visuals/color/color-visual-shader-factory.cpp +++ b/dali-toolkit/internal/visuals/color/color-visual-shader-factory.cpp @@ -28,8 +28,10 @@ namespace Toolkit { namespace Internal { + namespace { + constexpr VisualFactoryCache::ShaderType SHADER_TYPE_TABLE[] = { VisualFactoryCache::COLOR_SHADER, VisualFactoryCache::COLOR_SHADER_ROUNDED_CORNER, @@ -73,10 +75,11 @@ constexpr VisualFactoryCache::ShaderType ShaderTypePredefines[PREDEFINED_SHADER_ VisualFactoryCache::ShaderType::COLOR_SHADER, VisualFactoryCache::ShaderType::COLOR_SHADER_ROUNDED_CORNER, }; -} // namespace +} namespace ColorVisualShaderFeature { + FeatureBuilder::FeatureBuilder() : mColorRoundCorner(RoundedCorner::DISABLED), mColorBorderline(Borderline::DISABLED), @@ -111,8 +114,8 @@ FeatureBuilder& FeatureBuilder::EnableCutout(bool enableCutout) 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; @@ -141,7 +144,7 @@ void FeatureBuilder::GetVertexShaderPrefixList(std::string& vertexShaderPrefixLi { 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"; } @@ -166,7 +169,7 @@ void FeatureBuilder::GetFragmentShaderPrefixList(std::string& fragmentShaderPref 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"; } @@ -189,8 +192,8 @@ ColorVisualShaderFactory::~ColorVisualShaderFactory() 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) { @@ -205,13 +208,14 @@ Shader ColorVisualShaderFactory::GetShader(VisualFactoryCache& factoryCache, con 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); @@ -219,36 +223,31 @@ bool ColorVisualShaderFactory::AddPrecompiledShader(PrecompileShaderOption& opti 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 vertexPrefix; - std::vector fragmentPrefix; - std::vector shaderName; - - uint32_t shaderCount = 0; - - shaders.shaderCount = 0; + std::vector vertexPrefix; + std::vector fragmentPrefix; + std::vector 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(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(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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); shaderCount++; } @@ -258,70 +257,58 @@ void ColorVisualShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShader 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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName(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(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName(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(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(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); return true; } diff --git a/dali-toolkit/internal/visuals/color/color-visual-shader-factory.h b/dali-toolkit/internal/visuals/color/color-visual-shader-factory.h index f3964bcc4d..7ef6f5658f 100644 --- a/dali-toolkit/internal/visuals/color/color-visual-shader-factory.h +++ b/dali-toolkit/internal/visuals/color/color-visual-shader-factory.h @@ -31,6 +31,7 @@ namespace Toolkit { namespace Internal { + namespace ColorVisualShaderFeature { namespace RoundedCorner @@ -91,8 +92,8 @@ public: 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 { @@ -153,7 +154,7 @@ public: // Implementation of VisualShaderFactoryInterface /** * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader */ - void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override; + void GetPreCompiledShader(RawShaderData& shaders) override; private: /** @@ -163,7 +164,7 @@ 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: /** diff --git a/dali-toolkit/internal/visuals/custom-shader-factory.cpp b/dali-toolkit/internal/visuals/custom-shader-factory.cpp index 791da47847..e0b345cf0d 100644 --- a/dali-toolkit/internal/visuals/custom-shader-factory.cpp +++ b/dali-toolkit/internal/visuals/custom-shader-factory.cpp @@ -28,6 +28,7 @@ namespace Toolkit { namespace Internal { + CustomShaderFactory::CustomShaderFactory() { } @@ -38,53 +39,46 @@ 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 vertexPrefix; - std::vector fragmentPrefix; - std::vector shaderName; - - uint32_t shaderCount = 0; - - shaders.shaderCount = 0; + std::vector vertexPrefix; + std::vector fragmentPrefix; + std::vector 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; } diff --git a/dali-toolkit/internal/visuals/custom-shader-factory.h b/dali-toolkit/internal/visuals/custom-shader-factory.h index fb39a9b1e3..5401c731e3 100644 --- a/dali-toolkit/internal/visuals/custom-shader-factory.h +++ b/dali-toolkit/internal/visuals/custom-shader-factory.h @@ -31,6 +31,7 @@ namespace Toolkit { namespace Internal { + /** * CustomShaderFactory is an object that provides custom shader */ @@ -56,13 +57,13 @@ public: // Implementation of VisualShaderFactoryInterface /** * @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: /** diff --git a/dali-toolkit/internal/visuals/image/image-visual-shader-factory.cpp b/dali-toolkit/internal/visuals/image/image-visual-shader-factory.cpp index 23ceddf15c..fb25597856 100644 --- a/dali-toolkit/internal/visuals/image/image-visual-shader-factory.cpp +++ b/dali-toolkit/internal/visuals/image/image-visual-shader-factory.cpp @@ -199,36 +199,30 @@ bool ImageVisualShaderFactory::AddPrecompiledShader(PrecompileShaderOption& opti 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 vertexPrefix; - std::vector fragmentPrefix; - std::vector shaderName; - - uint32_t shaderCount = 0; - + std::vector vertexPrefix; + std::vector fragmentPrefix; + std::vector 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(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(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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); shaderCount++; } @@ -245,61 +239,46 @@ void ImageVisualShaderFactory::CreatePrecompileShader(ImageVisualShaderFeature:: { 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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); return false; } } @@ -308,17 +287,17 @@ bool ImageVisualShaderFactory::SavePrecompileShader(VisualFactoryCache::ShaderTy { if(mRequestedPrecompileShader[i].type == shader) { - DALI_LOG_WARNING("This shader already requsted(%s).\n", Scripting::GetLinearEnumerationName(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName(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(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(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); return true; } diff --git a/dali-toolkit/internal/visuals/image/image-visual-shader-factory.h b/dali-toolkit/internal/visuals/image/image-visual-shader-factory.h index 408695d153..e7af94a2a3 100644 --- a/dali-toolkit/internal/visuals/image/image-visual-shader-factory.h +++ b/dali-toolkit/internal/visuals/image/image-visual-shader-factory.h @@ -32,6 +32,7 @@ namespace Toolkit { namespace Internal { + /** * ImageVisualShaderFactory is an object that provides and shares shaders between image visuals */ @@ -76,7 +77,7 @@ public: // Implementation of VisualShaderFactoryInterface /** * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader */ - void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override; + void GetPreCompiledShader(RawShaderData& shaders) override; private: /** @@ -86,7 +87,7 @@ 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: /** diff --git a/dali-toolkit/internal/visuals/image/image-visual.cpp b/dali-toolkit/internal/visuals/image/image-visual.cpp index ed3383cdcd..f299975907 100644 --- a/dali-toolkit/internal/visuals/image/image-visual.cpp +++ b/dali-toolkit/internal/visuals/image/image-visual.cpp @@ -76,9 +76,6 @@ DALI_ENUM_TO_STRING_TABLE_BEGIN(SAMPLING_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) // wrap modes @@ -106,8 +103,6 @@ const Vector4 FULL_TEXTURE_RECT(0.f, 0.f, 1.f, 1.f); 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; @@ -686,14 +681,13 @@ void ImageVisual::LoadTexture(bool& atlasing, Vector4& atlasRect, TextureSet& te !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" : "", @@ -703,8 +697,7 @@ void ImageVisual::LoadTexture(bool& atlasing, Vector4& atlasRect, TextureSet& te (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; }; @@ -1558,15 +1551,14 @@ Geometry ImageVisual::GenerateGeometry(TextureManager::TextureId textureId, bool } } } + 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; } diff --git a/dali-toolkit/internal/visuals/image/image-visual.h b/dali-toolkit/internal/visuals/image/image-visual.h index e5060af685..690624ce91 100644 --- a/dali-toolkit/internal/visuals/image/image-visual.h +++ b/dali-toolkit/internal/visuals/image/image-visual.h @@ -95,8 +95,6 @@ typedef IntrusivePtr ImageVisualPtr; * "BOX_THEN_LINEAR" * "NO_FILTER" * "DONT_CARE" - * "LANCZOS" - * "BOX_THEN_LANCZOS" * "DEFAULT" * * where loadPolicy should be one of the following image loading modes @@ -388,8 +386,8 @@ private: 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; diff --git a/dali-toolkit/internal/visuals/npatch-shader-factory.cpp b/dali-toolkit/internal/visuals/npatch-shader-factory.cpp new file mode 100644 index 0000000000..26fa64c6d3 --- /dev/null +++ b/dali-toolkit/internal/visuals/npatch-shader-factory.cpp @@ -0,0 +1,153 @@ +/* + * 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 + +// INTERNAL INCLUDES +#include +#include +#include + +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 vertexPrefix; + std::vector fragmentPrefix; + std::vector 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(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + return false; + } + } + + std::string shaderName = Scripting::GetLinearEnumerationName(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(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + return true; +} + + +} // namespace Internal + +} // namespace Toolkit + +} // namespace Dali diff --git a/dali-toolkit/internal/visuals/npatch-shader-factory.h b/dali-toolkit/internal/visuals/npatch-shader-factory.h new file mode 100644 index 0000000000..c3c42f47f6 --- /dev/null +++ b/dali-toolkit/internal/visuals/npatch-shader-factory.h @@ -0,0 +1,102 @@ +#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 + +// INTERNAL INCLUDES +#include +#include +#include + +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 diff --git a/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.cpp b/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.cpp deleted file mode 100644 index ddbc49aa68..0000000000 --- a/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.cpp +++ /dev/null @@ -1,157 +0,0 @@ -/* - * 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 - -// INTERNAL INCLUDES -#include -#include -#include - -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 vertexPrefix; - std::vector fragmentPrefix; - std::vector 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(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); - return false; - } - } - - std::string shaderName = Scripting::GetLinearEnumerationName(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 diff --git a/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.h b/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.h deleted file mode 100644 index 975ea9dd3a..0000000000 --- a/dali-toolkit/internal/visuals/npatch/npatch-shader-factory.h +++ /dev/null @@ -1,101 +0,0 @@ -#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 - -// INTERNAL INCLUDES -#include -#include -#include - -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 diff --git a/dali-toolkit/internal/visuals/svg/svg-task.cpp b/dali-toolkit/internal/visuals/svg/svg-task.cpp index 55df62e9f0..f088a8a881 100644 --- a/dali-toolkit/internal/visuals/svg/svg-task.cpp +++ b/dali-toolkit/internal/visuals/svg/svg-task.cpp @@ -203,8 +203,7 @@ void SvgRasterizingTask::Process() 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(mEndTimeNanoSceonds - mStartTimeNanoSceonds) / 1000000.0f << "ms "; oss << "s:" << mWidth << "x" << mHeight << " "; oss << "u:" << mImageUrl.GetEllipsedUrl() << "]"; @@ -221,10 +220,6 @@ void SvgRasterizingTask::Process() oss << "["; oss << "d:" << static_cast(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() << "]"; }); } diff --git a/dali-toolkit/internal/visuals/svg/svg-visual.cpp b/dali-toolkit/internal/visuals/svg/svg-visual.cpp index 7728733811..1bc9b075e8 100644 --- a/dali-toolkit/internal/visuals/svg/svg-visual.cpp +++ b/dali-toolkit/internal/visuals/svg/svg-visual.cpp @@ -347,11 +347,6 @@ void SvgVisual::LoadComplete(int32_t loadId, Dali::VectorImageRenderer vectorIma 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) { diff --git a/dali-toolkit/internal/visuals/text/text-visual-shader-factory.cpp b/dali-toolkit/internal/visuals/text/text-visual-shader-factory.cpp index d08c41154c..269754e27d 100644 --- a/dali-toolkit/internal/visuals/text/text-visual-shader-factory.cpp +++ b/dali-toolkit/internal/visuals/text/text-visual-shader-factory.cpp @@ -166,8 +166,8 @@ TextVisualShaderFactory::~TextVisualShaderFactory() 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) { @@ -188,7 +188,7 @@ bool TextVisualShaderFactory::AddPrecompiledShader(PrecompileShaderOption& optio { ShaderFlagList shaderOption = option.GetShaderOptions(); - auto featureBuilder = TextVisualShaderFeature::FeatureBuilder(); + auto featureBuilder = TextVisualShaderFeature::FeatureBuilder(); std::string vertexPrefixList; std::string fragmentPrefixList; CreatePrecompileShader(featureBuilder, shaderOption); @@ -196,34 +196,31 @@ bool TextVisualShaderFactory::AddPrecompiledShader(PrecompileShaderOption& optio 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 vertexPrefix; - std::vector fragmentPrefix; - std::vector shaderName; - uint32_t shaderCount = 0; +void TextVisualShaderFactory::GetPreCompiledShader(RawShaderData& shaders) +{ + std::vector vertexPrefix; + std::vector fragmentPrefix; + std::vector 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(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(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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); shaderCount++; } @@ -233,70 +230,62 @@ void TextVisualShaderFactory::GetPreCompiledShader(ShaderPreCompiler::RawShaderD 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(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(ShaderTypePredefines[i], VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already added list(%s).", Scripting::GetLinearEnumerationName(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(mRequestedPrecompileShader[i].type, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); + DALI_LOG_WARNING("This shader already requsted(%s).", Scripting::GetLinearEnumerationName(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(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(shader, VISUAL_SHADER_TYPE_TABLE, VISUAL_SHADER_TYPE_TABLE_COUNT)); return true; } } // namespace Internal diff --git a/dali-toolkit/internal/visuals/text/text-visual-shader-factory.h b/dali-toolkit/internal/visuals/text/text-visual-shader-factory.h index 14d4962183..183f149938 100644 --- a/dali-toolkit/internal/visuals/text/text-visual-shader-factory.h +++ b/dali-toolkit/internal/visuals/text/text-visual-shader-factory.h @@ -97,8 +97,8 @@ public: 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 { @@ -159,7 +159,7 @@ public: // Implementation of VisualShaderFactoryInterface /** * @copydoc Dali::Toolkit::VisualShaderFactoryInterface::GetPreCompiledShader */ - void GetPreCompiledShader(ShaderPreCompiler::RawShaderData& shaders) override; + void GetPreCompiledShader(RawShaderData& shaders) override; private: /** @@ -170,7 +170,7 @@ 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: /** diff --git a/dali-toolkit/internal/visuals/visual-factory-cache.h b/dali-toolkit/internal/visuals/visual-factory-cache.h index cc59ea7081..7270b349b6 100644 --- a/dali-toolkit/internal/visuals/visual-factory-cache.h +++ b/dali-toolkit/internal/visuals/visual-factory-cache.h @@ -143,7 +143,7 @@ public: WIREFRAME_SHADER, ARC_BUTT_CAP_SHADER, ARC_ROUND_CAP_SHADER, - SHADER_TYPE_MAX + SHADER_TYPE_MAX = ARC_ROUND_CAP_SHADER }; /** @@ -156,7 +156,7 @@ public: NINE_PATCH_GEOMETRY, NINE_PATCH_BORDER_GEOMETRY, WIREFRAME_GEOMETRY, - GEOMETRY_TYPE_MAX + GEOMETRY_TYPE_MAX = WIREFRAME_GEOMETRY }; public: @@ -368,8 +368,8 @@ private: 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 diff --git a/dali-toolkit/internal/visuals/visual-factory-impl.cpp b/dali-toolkit/internal/visuals/visual-factory-impl.cpp index 803c5d6592..8242f75054 100644 --- a/dali-toolkit/internal/visuals/visual-factory-impl.cpp +++ b/dali-toolkit/internal/visuals/visual-factory-impl.cpp @@ -39,11 +39,11 @@ #include #include #include +#include #include #include #include #include -#include #include #include #include @@ -422,10 +422,10 @@ void VisualFactory::DiscardVisual(Toolkit::Visual::Base visual) 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; } @@ -440,39 +440,36 @@ void VisualFactory::UsePreCompiledShader() } mPrecompiledShaderRequested = true; - ShaderPreCompiler::Get().Enable(true); + ShaderPreCompiler::Get().Enable(); // Get image shader - ShaderPreCompiler::RawShaderDataList rawShaderList; - ShaderPreCompiler::RawShaderData imageShaderData; + std::vector 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() @@ -570,7 +567,7 @@ CustomShaderFactory& VisualFactory::GetCustomShaderFactory() bool VisualFactory::AddPrecompileShader(PrecompileShaderOption& option) { auto type = option.GetShaderType(); - bool ret = false; + bool ret = false; switch(type) { case PrecompileShaderOption::ShaderType::COLOR: @@ -591,7 +588,6 @@ bool VisualFactory::AddPrecompileShader(PrecompileShaderOption& option) case PrecompileShaderOption::ShaderType::NPATCH: { ret = GetNpatchShaderFactory().AddPrecompiledShader(option); - break; } case PrecompileShaderOption::ShaderType::MODEL_3D: { @@ -605,7 +601,7 @@ bool VisualFactory::AddPrecompileShader(PrecompileShaderOption& option) } 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; } } diff --git a/dali-toolkit/internal/visuals/visual-shader-factory-interface.h b/dali-toolkit/internal/visuals/visual-shader-factory-interface.h index cfc4df1720..704be912b9 100644 --- a/dali-toolkit/internal/visuals/visual-shader-factory-interface.h +++ b/dali-toolkit/internal/visuals/visual-shader-factory-interface.h @@ -22,15 +22,16 @@ #include // INTERNAL INCLUDES +#include #include #include -#include namespace Dali { namespace Toolkit { -using HashType = uint64_t; + +using HashType = uint64_t; using ShaderFlagList = std::vector; namespace Internal @@ -41,18 +42,19 @@ 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; /** @@ -65,7 +67,7 @@ public: * @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 mRequestedPrecompileShader; diff --git a/dali-toolkit/public-api/controls/control-impl.cpp b/dali-toolkit/public-api/controls/control-impl.cpp index f96731c46f..068fb03503 100644 --- a/dali-toolkit/public-api/controls/control-impl.cpp +++ b/dali-toolkit/public-api/controls/control-impl.cpp @@ -181,8 +181,6 @@ void Control::SetRenderEffect(Toolkit::RenderEffect effect) Dali::Toolkit::Control ownerControl(GetOwner()); object->SetOwnerControl(ownerControl); - - SetOffScreenRenderableType(object->GetOffScreenRenderableType()); } } } @@ -199,7 +197,6 @@ void Control::ClearRenderEffect() } mImpl->mRenderEffect.Reset(); } - SetOffScreenRenderableType(OffScreenRenderable::NONE); } void Control::SetResourceReady() @@ -208,17 +205,6 @@ 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 Control::GetAccessibleObject() { return mImpl->GetAccessibleObject(); @@ -629,6 +615,15 @@ void Control::OnPropertySet(Property::Index index, const Property::Value& proper } break; } + case Actor::Property::VISIBLE: + { + auto accessible = GetAccessibleObject(); + if(DALI_LIKELY(accessible) && accessible->IsHighlighted()) + { + accessible->EmitVisible(Self().GetProperty(Actor::Property::VISIBLE)); + } + break; + } case DevelActor::Property::USER_INTERACTION_ENABLED: { const bool enabled = propertyValue.Get(); @@ -660,19 +655,6 @@ void Control::OnSizeAnimation(Animation& animation, const Vector3& targetSize) // @todo size negotiate background to new size, animate as well? } -void Control::GetOffScreenRenderTasks(std::vector& tasks, bool isForward) -{ - if(mImpl->mRenderEffect) - { - Toolkit::Internal::RenderEffectImpl* object = dynamic_cast(mImpl->mRenderEffect.GetObjectPtr()); - - if(object) - { - object->GetOffScreenRenderTasks(tasks, isForward); - } - } -} - bool Control::OnKeyEvent(const KeyEvent& event) { return false; // Do not consume diff --git a/dali-toolkit/public-api/controls/control-impl.h b/dali-toolkit/public-api/controls/control-impl.h index 616aa4897d..76991aa0a0 100644 --- a/dali-toolkit/public-api/controls/control-impl.h +++ b/dali-toolkit/public-api/controls/control-impl.h @@ -129,24 +129,6 @@ public: */ 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 /** @@ -380,11 +362,6 @@ protected: // From CustomActorImpl */ void OnSizeAnimation(Animation& animation, const Vector3& targetSize) override; - /** - * @copydoc CustomActorImpl::GetOffScreenRenderTasks() - */ - void GetOffScreenRenderTasks(std::vector& tasks, bool isForward) override; - /** * @copydoc CustomActorImpl::OnRelayout() */ diff --git a/dali-toolkit/public-api/dali-toolkit-version.cpp b/dali-toolkit/public-api/dali-toolkit-version.cpp index 295f35362b..0767a72478 100644 --- a/dali-toolkit/public-api/dali-toolkit-version.cpp +++ b/dali-toolkit/public-api/dali-toolkit-version.cpp @@ -29,7 +29,7 @@ namespace Toolkit { 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 diff --git a/dali-usd-loader.manifest b/dali-usd-loader.manifest deleted file mode 100644 index a76fdbae7d..0000000000 --- a/dali-usd-loader.manifest +++ /dev/null @@ -1,5 +0,0 @@ - - - - - diff --git a/dali-usd-loader.manifest-smack b/dali-usd-loader.manifest-smack deleted file mode 100644 index 08561d6145..0000000000 --- a/dali-usd-loader.manifest-smack +++ /dev/null @@ -1,8 +0,0 @@ - - - - - - - - diff --git a/dali-usd-loader/internal/create-usd-loader.cpp b/dali-usd-loader/internal/create-usd-loader.cpp deleted file mode 100644 index c2da4dc6ee..0000000000 --- a/dali-usd-loader/internal/create-usd-loader.cpp +++ /dev/null @@ -1,30 +0,0 @@ -/* - * 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 - -// INTERNAL INCLUDES -#include - -namespace Dali::Scene3D::Loader -{ -extern "C" DALI_TOOLKIT_API Dali::Scene3D::Loader::ModelLoaderImpl* CreateUsdLoader() -{ - return new UsdLoaderImpl(); -} -} // namespace Dali::Scene3D::Loader diff --git a/dali-usd-loader/internal/file.list b/dali-usd-loader/internal/file.list deleted file mode 100644 index 7bd08c0f28..0000000000 --- a/dali-usd-loader/internal/file.list +++ /dev/null @@ -1,6 +0,0 @@ -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 -) diff --git a/dali-usd-loader/internal/usd-loader-impl.cpp b/dali-usd-loader/internal/usd-loader-impl.cpp deleted file mode 100644 index fbbdc39f81..0000000000 --- a/dali-usd-loader/internal/usd-loader-impl.cpp +++ /dev/null @@ -1,2071 +0,0 @@ -/* - * 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 - -// EXTERNAL INCLUDES -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// INTERNAL INCLUDES -#include -#include - -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 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 -T GetAttributeValue(UsdAttribute attribute, T& value) -{ - std::vector times; - attribute.GetTimeSamples(×); - if(times.size() > 0u) - { - attribute.Get(&value, times[0]); - } - else - { - attribute.Get(&value, UsdTimeCode::Default()); - } - - return value; -} - -// Template function to retrieve the flattened value of a USD geometry primvar (e.g., color, normals) -template -VtArray GetFlattenedPrimvarValue(UsdGeomPrimvar primvar, VtArray& value) -{ - std::vector times; - primvar.GetAttr().GetTimeSamples(×); - - if(times.size() > 0u) - { - primvar.ComputeFlattened(&value, times[0]); - } - else - { - primvar.ComputeFlattened(&value, UsdTimeCode::Default()); - } - - return value; -} - -// Recursively traverses connected shader inputs to collect all relevant shaders -std::vector TraverseShaderInputs(const UsdShadeShader& shader) -{ - std::vector 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 -VtArray GetTriangulatedAttribute(const VtArray& countArray, const VtArray& indexArray, bool isLeftHanded) -{ - VtArray 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 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 LoadAssetFileAsBuffer(const std::string resolvedAssetPath) -{ - std::shared_ptr const asset = ArGetResolver().OpenAsset(ArResolvedPath(resolvedAssetPath)); - - if(asset) - { - std::shared_ptr 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(buffer.get(), buffer.get() + asset->GetSize()); - } - } - - // Return an empty vector if loading fails - return std::vector(); -} - -} // 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& texcoords, std::vector& colors, std::vector& 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>& indexMap, VtIntArray& subsetIdcs, VtArray& triangulatedIndex, std::vector& subIndexArray, std::vector& 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& points, VtArray& worldPosition, std::vector& 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& normals, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& 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& texcoords, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& 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& 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& colors, VtArray& worldPosition, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& 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& subsets, size_t subIndex, int& meshSubMaterialId); - -public: - UsdStageRefPtr mUsdStage; ///< Pointer to the USD stage. - - std::map 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 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()) - { - 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 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 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(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(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(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(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(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(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(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(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(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(&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(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(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()) - { - ConvertMesh(output, prim, nodeIndex, parentIndex); - } - else if(prim.IsA()) - { - ConvertNode(output, prim, nodeIndex, parentIndex); - } - else if(prim.IsA()) - { - ConvertCamera(output, prim); - } - else if(prim.IsA()) - { - DALI_LOG_INFO(gLogFilter, Debug::Verbose, " => UsdSkelRoot\n"); - } - else if(prim.IsA()) - { - 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 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(&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(&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(&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(&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 imageBuffer; - - // Extract various texture attributes (file, wrapS, wrapT, scale, bias, st, fallback) - std::vector 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(&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(&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(&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(&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(&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(&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(&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{new NodeDefinition()}; - - nodeDefinition->mParentIdx = parentIndex; - nodeDefinition->mName = nodeName; - if(nodeDefinition->mName.empty()) - { - nodeDefinition->mName = std::to_string(reinterpret_cast(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& texcoords, std::vector& colors, std::vector& tangents) -{ - UsdGeomPrimvarsAPI pvAPI(prim); - std::vector 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>& indexMap, VtIntArray& subsetIdcs, VtArray& triangulatedIndex, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices) -{ - std::vector> 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 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(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& points, VtArray& worldPosition, std::vector& 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 bufferPositions(worldPosition.size() * sizeof(GfVec3f)); - - std::copy(reinterpret_cast(worldPosition.data()), - reinterpret_cast(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(worldPosition.size()), std::move(bufferPositions)}); -} - -void UsdLoaderImpl::Impl::ProcessMeshNormals(MeshDefinition& meshDefinition, UsdGeomMesh& usdMesh, VtArray& normals, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& faceVertexCounts, bool isLeftHanded) -{ - UsdAttribute normalsAttr = usdMesh.GetNormalsAttr(); - if(normalsAttr.HasValue()) - { - VtVec3fArray rawNormals; - GetAttributeValue(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 triangulatedNormal = GetTriangulatedAttribute(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(triangulatedNormal[index * 3])); - normals.push_back(static_cast(triangulatedNormal[index * 3 + 1])); - normals.push_back(static_cast(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(rawNormals[x])); - } - } - - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "normals: size = %lu, value: ", normals.size()); - - if(normals.size() > 0) - { - std::vector bufferNormals(normals.size() * sizeof(GfVec3f)); - - std::copy(reinterpret_cast(normals.data()), - reinterpret_cast(normals.data() + normals.size()), - bufferNormals.begin()); - - // Add normal attribute to the mesh definition - meshDefinition.mRawData->mAttribs.push_back({"aNormal", Property::VECTOR3, static_cast(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(meshDefinition.mRawData->mIndices.size() / 2); - - // Pointer to the vertex positions - auto* positions = reinterpret_cast(attribs[0].mData.data()); - - std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto normals = reinterpret_cast(buffer.data()); - - // Pointer to the index data - auto indicesData = reinterpret_cast(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& texcoords, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& 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(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(faceVertexCounts, rawUVs, isLeftHanded); - - for(int index : flattenedSubTriangulatedIndices) - { - UVs.push_back(static_cast(triangulatedUV[index * 3])); - UVs.push_back(static_cast(triangulatedUV[index * 3 + 1])); - UVs.push_back(static_cast(triangulatedUV[index * 3 + 2])); - } - } - else if(interpolation.GetString() == "vertex") - { - // Handle vertex-based UVs - for(auto x : subIndexArray) - { - UVs.push_back(static_cast(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 bufferTexCoords(flipyUVs.size() * sizeof(GfVec2f)); - - std::copy(reinterpret_cast(flipyUVs.data()), - reinterpret_cast(flipyUVs.data() + flipyUVs.size()), - bufferTexCoords.begin()); - - // Add texcoord attribute to the mesh definition - meshDefinition.mRawData->mAttribs.push_back({"aTexCoord", Property::VECTOR2, static_cast(flipyUVs.size()), std::move(bufferTexCoords)}); - } - } - } -} - -void UsdLoaderImpl::Impl::GenerateTangents(MeshDefinition& meshDefinition, std::vector& texcoords) -{ - auto& attribs = meshDefinition.mRawData->mAttribs; - - // Required positions, normals, uvs (if we have them). - std::vector buffer(attribs[0].mNumElements * sizeof(Vector3)); - auto tangentsData = reinterpret_cast(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(meshDefinition.mRawData->mIndices.size() / 2); - - // Pointers to the vertex positions and UV coordinates. - auto* positions = reinterpret_cast(attribs[0].mData.data()); - auto* uvs = reinterpret_cast(attribs[2].mData.data()); - - // Pointer to the index data. - auto indicesData = reinterpret_cast(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(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& colors, VtArray& worldPosition, std::vector& subIndexArray, std::vector& flattenedSubTriangulatedIndices, VtArray& 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(displayColor.GetAttr(), rawColors); - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawColors: %lu, ", rawColors.size()); - - VtArray convertedColors; - - TfToken interpolation = displayColor.GetInterpolation(); - if(interpolation.GetString() == "constant") - { - // Handle constant color (same color for all vertices) - convertedColors = VtArray(subIndexArray.size(), rawColors[0]); - } - else if(interpolation.GetString() == "faceVarying") - { - // Handle face-varying colors - VtVec3fArray triangulatedColors = GetTriangulatedAttribute(faceVertexCounts, rawColors, isLeftHanded); - - for(int index : flattenedSubTriangulatedIndices) - { - convertedColors.push_back(static_cast(triangulatedColors[index * 3])); - convertedColors.push_back(static_cast(triangulatedColors[index * 3 + 1])); - convertedColors.push_back(static_cast(triangulatedColors[index * 3 + 2])); - } - } - else if(interpolation.GetString() == "vertex") - { - // Handle vertex colors - for(auto x : subIndexArray) - { - convertedColors.push_back(static_cast(rawColors[x])); - } - } - else if(interpolation.GetString() == "uniform") - { - // Handle uniform colors - GetFlattenedPrimvarValue(displayColor, rawColors); - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "rawColors (uniform): %lu, value: ", rawColors.size()); - - for(auto x : subIndexArray) - { - convertedColors.push_back(static_cast(rawColors[x])); - } - } - - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "convertedColors: size = %lu, value: ", convertedColors.size()); - - // COLOR_0 - - std::vector bufferColors(convertedColors.size() * sizeof(GfVec3f)); - - std::copy(reinterpret_cast(convertedColors.data()), - reinterpret_cast(convertedColors.data() + convertedColors.size()), - bufferColors.begin()); - - // Add color attribute to the mesh definition - meshDefinition.mRawData->mAttribs.push_back({"aVertexColor", Property::VECTOR3, static_cast(convertedColors.size()), std::move(bufferColors)}); - } - } - else if(worldPosition.size() > 0) - { - // If no colors are defined, use white color (Vector4::ONE) - std::vector buffer(worldPosition.size() * sizeof(Vector4)); - auto bufferColors = reinterpret_cast(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(worldPosition.size()), std::move(buffer)}); - } -} - -void UsdLoaderImpl::Impl::ProcessMaterialBinding(LoadResult& output, const UsdPrim& prim, std::vector& 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(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() && !prim.IsA(); - 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 points; - GetAttributeValue>(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 faceVertexCounts; - UsdAttribute facesAttr = usdMesh.GetFaceVertexCountsAttr(); - GetAttributeValue>(facesAttr, faceVertexCounts); - - // Get Face Vertex Indices (index of vertices for each face) - VtArray faceVertexIndices; - UsdAttribute indicesAttr = usdMesh.GetFaceVertexIndicesAttr(); - GetAttributeValue>(indicesAttr, faceVertexIndices); - - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "FaceVertexCounts: %lu, FaceVertexIndices: %lu, ", faceVertexCounts.size(), faceVertexIndices.size()); - - std::vector texcoords; - std::vector colors; - std::vector 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(orientationAttr, orientation); - - DALI_LOG_INFO(gLogFilter, Debug::Verbose, "orientation: %s, ", orientation.GetText()); - - bool isLeftHanded = orientation.GetString() != "rightHanded"; - - // Maps triangulated indices - std::map> indexMap; - int j = 0; - for(size_t i = 0; i < faceVertexCounts.size(); ++i) - { - VtArray 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 triangulatedIndex = GetTriangulatedAttribute(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 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 subsetIndices(numSubsets, VtIntArray()); - for(size_t i = 0; i < numSubsets; ++i) - { - VtIntArray indices; - GetAttributeValue(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.mFlags |= MeshDefinition::U32_INDICES; - meshDefinition.mSkeletonIdx = INVALID_INDEX; - - // Process indices - auto& subsetIdcs = subsetIndices[subIndex]; - std::vector subIndexArray; - std::vector flattenedSubTriangulatedIndices; - - ProcessMeshIndices(meshDefinition, indexMap, subsetIdcs, triangulatedIndex, subIndexArray, flattenedSubTriangulatedIndices); - - // Process vertex positions - VtArray worldPosition; - ProcessMeshPositions(meshDefinition, points, worldPosition, subIndexArray); - - // Process normals - VtArray 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 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(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(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 diff --git a/dali-usd-loader/internal/usd-loader-impl.h b/dali-usd-loader/internal/usd-loader-impl.h deleted file mode 100644 index e53b71465d..0000000000 --- a/dali-usd-loader/internal/usd-loader-impl.h +++ /dev/null @@ -1,46 +0,0 @@ -#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 - -// INTERNAL INCLUDES -#include - -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 mImpl; -}; - -} // namespace Dali::Scene3D::Loader - -#endif // DALI_SCENE3D_LOADER_USD_LOADER_IMPL_H diff --git a/packaging/dali-toolkit.spec b/packaging/dali-toolkit.spec index 8c4bf4f9bf..e0672214d4 100644 --- a/packaging/dali-toolkit.spec +++ b/packaging/dali-toolkit.spec @@ -1,6 +1,6 @@ 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 @@ -21,10 +21,6 @@ BuildRequires: pkgconfig(egl) 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 @@ -171,31 +167,6 @@ Requires: %{dali2_physics3d} = %{version}-%{release} %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/ @@ -390,12 +361,6 @@ pushd %{dali_toolkit_style_files}/1920x1080_rpi 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 ############################## @@ -507,12 +472,6 @@ case "$1" in ;; esac -%if 0%{?enable_usd_loader} -%postun -n %{dali2_usdloader} -/sbin/ldconfig -exit 0 -%endif - ############################## # Files in Binary Packages ############################## @@ -637,19 +596,3 @@ exit 0 %{_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