From 0f40523c273def2e7015eca6e702b2f2ae92a1e2 Mon Sep 17 00:00:00 2001 From: Jamie Kerber Date: Wed, 22 Oct 2025 06:13:06 +0200 Subject: [PATCH] Removed `filament_view` plugin --- .github/workflows/clang-tidy.yaml | 49 - .github/workflows/codeql.yml | 47 - .github/workflows/ivi-homescreen.yaml | 49 - .../0001-disable-backend-tests-1.65.2.patch | 33 - .../0002-install-required-files.patch | 63 - ...include-contents-to-include-filament.patch | 239 ---- ...ove-libraries-so-they-install-1.65.2.patch | 53 - .../filament/0005-spirv-tools-threads.patch | 54 - ...-shader-type-mobile-for-linux-vulkan.patch | 26 - .../filament/ImportExecutables-Release.cmake | 115 -- docs/source/filament_view.md | 1 - docs/source/index.rst | 1 - plugins/CMakeLists.txt | 2 - plugins/config_plugins.h.in | 5 - plugins/filament_view/.clang-format | 51 - plugins/filament_view/CMakeLists.txt | 162 --- plugins/filament_view/README.md | 61 - .../core/components/base/component.h | 57 - .../core/components/derived/animation.cc | 238 ---- .../core/components/derived/animation.h | 83 -- .../core/components/derived/camera.cc | 93 -- .../core/components/derived/camera.h | 176 --- .../core/components/derived/collider.cc | 257 ---- .../core/components/derived/collider.h | 131 -- .../components/derived/commonrenderable.cc | 44 - .../components/derived/commonrenderable.h | 67 - .../core/components/derived/light.cc | 115 -- .../core/components/derived/light.h | 111 -- .../derived/material_definitions.cc | 255 ---- .../components/derived/material_definitions.h | 112 -- .../core/components/derived/transform.cc | 70 - .../core/components/derived/transform.h | 303 ---- .../core/entity/base/entityobject.cc | 161 --- .../core/entity/base/entityobject.h | 210 --- .../core/entity/derived/model/model.cc | 201 --- .../core/entity/derived/model/model.h | 107 -- .../entity/derived/renderable_entityobject.cc | 113 -- .../entity/derived/renderable_entityobject.h | 104 -- .../core/entity/derived/shapes/baseshape.cc | 309 ---- .../core/entity/derived/shapes/baseshape.h | 128 -- .../core/entity/derived/shapes/cube.cc | 745 ---------- .../core/entity/derived/shapes/cube.h | 58 - .../core/entity/derived/shapes/plane.cc | 249 ---- .../core/entity/derived/shapes/plane.h | 55 - .../core/entity/derived/shapes/sphere.cc | 182 --- .../core/entity/derived/shapes/sphere.h | 68 - .../core/include/additionalmath.h | 19 - plugins/filament_view/core/include/color.h | 95 -- .../filament_view/core/include/file_utils.h | 103 -- plugins/filament_view/core/include/literals.h | 221 --- plugins/filament_view/core/include/resource.h | 59 - .../filament_view/core/include/shapetypes.h | 23 - .../core/lifecycle_participant.h | 83 -- .../core/scene/camera/exposure.cc | 74 - .../core/scene/camera/exposure.h | 72 - .../core/scene/camera/lens_projection.cc | 84 -- .../core/scene/camera/lens_projection.h | 76 - .../core/scene/camera/projection.cc | 147 -- .../core/scene/camera/projection.h | 127 -- .../core/scene/camera/touch_pair.h | 72 - .../core/scene/geometry/direction.h | 25 - .../core/scene/geometry/position.h | 25 - .../filament_view/core/scene/geometry/ray.cc | 37 - .../filament_view/core/scene/geometry/ray.h | 49 - .../filament_view/core/scene/geometry/size.cc | 68 - .../filament_view/core/scene/geometry/size.h | 44 - .../scene/indirect_light/indirect_light.cc | 100 -- .../scene/indirect_light/indirect_light.h | 109 -- .../scene/material/loader/material_loader.cc | 98 -- .../scene/material/loader/material_loader.h | 41 - .../scene/material/loader/texture_loader.cc | 154 -- .../scene/material/loader/texture_loader.h | 54 - .../core/scene/material/material_parameter.cc | 354 ----- .../core/scene/material/material_parameter.h | 190 --- .../scene/material/texture/enums/mag_filter.h | 24 - .../scene/material/texture/enums/min_filter.h | 28 - .../scene/material/texture/enums/wrap_mode.h | 25 - .../material/texture/texture_definitions.cc | 136 -- .../material/texture/texture_definitions.h | 70 - .../scene/material/texture/texture_sampler.cc | 155 -- .../scene/material/texture/texture_sampler.h | 54 - .../serialization/scene_text_deserializer.cc | 427 ------ .../serialization/scene_text_deserializer.h | 70 - .../filament_view/core/scene/skybox/skybox.cc | 86 -- .../filament_view/core/scene/skybox/skybox.h | 108 -- .../filament_view/core/scene/view_target.cc | 804 ----------- .../filament_view/core/scene/view_target.h | 194 --- .../filament_view/core/systems/base/system.cc | 175 --- .../filament_view/core/systems/base/system.h | 110 -- .../core/systems/derived/animation_system.cc | 159 --- .../core/systems/derived/animation_system.h | 55 - .../core/systems/derived/collision_system.cc | 265 ---- .../core/systems/derived/collision_system.h | 79 -- .../systems/derived/debug_lines_system.cc | 180 --- .../core/systems/derived/debug_lines_system.h | 85 -- .../core/systems/derived/filament_system.cc | 69 - .../core/systems/derived/filament_system.h | 53 - .../systems/derived/indirect_light_system.cc | 224 --- .../systems/derived/indirect_light_system.h | 79 -- .../core/systems/derived/light_system.cc | 196 --- .../core/systems/derived/light_system.h | 56 - .../core/systems/derived/material_system.cc | 229 --- .../core/systems/derived/material_system.h | 78 -- .../core/systems/derived/model_system.cc | 715 ---------- .../core/systems/derived/model_system.h | 122 -- .../core/systems/derived/shape_system.cc | 248 ---- .../core/systems/derived/shape_system.h | 79 -- .../core/systems/derived/skybox_system.cc | 361 ----- .../core/systems/derived/skybox_system.h | 79 -- .../core/systems/derived/transform_system.cc | 167 --- .../core/systems/derived/transform_system.h | 109 -- .../systems/derived/view_target_system.cc | 321 ----- .../core/systems/derived/view_target_system.h | 70 - plugins/filament_view/core/systems/ecs.cc | 580 -------- plugins/filament_view/core/systems/ecs.h | 294 ---- .../core/systems/messages/ecs_message.h | 61 - .../core/systems/messages/ecs_message_types.h | 89 -- plugins/filament_view/core/utils/asserts.cc | 18 - plugins/filament_view/core/utils/asserts.h | 17 - .../core/utils/bounding_volumes.h | 32 - .../filament_view/core/utils/deserialize.cc | 199 --- .../filament_view/core/utils/deserialize.h | 183 --- .../filament_view/core/utils/filament_types.h | 20 - .../filament_view/core/utils/hdr_loader.cc | 94 -- plugins/filament_view/core/utils/hdr_loader.h | 50 - .../filament_view/core/utils/ibl_profiler.h | 93 -- .../core/utils/identifiable_type.h | 62 - plugins/filament_view/core/utils/kvtree.cc | 158 --- plugins/filament_view/core/utils/kvtree.h | 96 -- .../core/utils/smarter_pointers.h | 137 -- .../filament_view/core/utils/uuidGenerator.cc | 35 - .../filament_view/core/utils/uuidGenerator.h | 27 - .../filament_view/core/utils/vectorutils.cc | 108 -- .../filament_view/core/utils/vectorutils.h | 144 -- plugins/filament_view/filament_view_plugin.cc | 843 ----------- plugins/filament_view/filament_view_plugin.h | 196 --- .../filament_view_plugin_c_api.cc | 91 -- .../filament_view_plugin_c_api.h | 59 - plugins/filament_view/messages.g.cc | 1246 ----------------- plugins/filament_view/messages.g.h | 220 --- plugins/filament_view/test/mvp.cc | 393 ------ plugins/generated_plugin_registrant.cc | 9 - 142 files changed, 20514 deletions(-) delete mode 100644 .github/workflows/patches/filament/0001-disable-backend-tests-1.65.2.patch delete mode 100644 .github/workflows/patches/filament/0002-install-required-files.patch delete mode 100644 .github/workflows/patches/filament/0003-move-include-contents-to-include-filament.patch delete mode 100644 .github/workflows/patches/filament/0004-move-libraries-so-they-install-1.65.2.patch delete mode 100644 .github/workflows/patches/filament/0005-spirv-tools-threads.patch delete mode 100644 .github/workflows/patches/filament/0006-return-shader-type-mobile-for-linux-vulkan.patch delete mode 100644 .github/workflows/patches/filament/ImportExecutables-Release.cmake delete mode 120000 docs/source/filament_view.md delete mode 100644 plugins/filament_view/.clang-format delete mode 100644 plugins/filament_view/CMakeLists.txt delete mode 100644 plugins/filament_view/README.md delete mode 100644 plugins/filament_view/core/components/base/component.h delete mode 100644 plugins/filament_view/core/components/derived/animation.cc delete mode 100644 plugins/filament_view/core/components/derived/animation.h delete mode 100644 plugins/filament_view/core/components/derived/camera.cc delete mode 100644 plugins/filament_view/core/components/derived/camera.h delete mode 100644 plugins/filament_view/core/components/derived/collider.cc delete mode 100644 plugins/filament_view/core/components/derived/collider.h delete mode 100644 plugins/filament_view/core/components/derived/commonrenderable.cc delete mode 100644 plugins/filament_view/core/components/derived/commonrenderable.h delete mode 100644 plugins/filament_view/core/components/derived/light.cc delete mode 100644 plugins/filament_view/core/components/derived/light.h delete mode 100644 plugins/filament_view/core/components/derived/material_definitions.cc delete mode 100644 plugins/filament_view/core/components/derived/material_definitions.h delete mode 100644 plugins/filament_view/core/components/derived/transform.cc delete mode 100644 plugins/filament_view/core/components/derived/transform.h delete mode 100644 plugins/filament_view/core/entity/base/entityobject.cc delete mode 100644 plugins/filament_view/core/entity/base/entityobject.h delete mode 100644 plugins/filament_view/core/entity/derived/model/model.cc delete mode 100644 plugins/filament_view/core/entity/derived/model/model.h delete mode 100644 plugins/filament_view/core/entity/derived/renderable_entityobject.cc delete mode 100644 plugins/filament_view/core/entity/derived/renderable_entityobject.h delete mode 100644 plugins/filament_view/core/entity/derived/shapes/baseshape.cc delete mode 100644 plugins/filament_view/core/entity/derived/shapes/baseshape.h delete mode 100644 plugins/filament_view/core/entity/derived/shapes/cube.cc delete mode 100644 plugins/filament_view/core/entity/derived/shapes/cube.h delete mode 100644 plugins/filament_view/core/entity/derived/shapes/plane.cc delete mode 100644 plugins/filament_view/core/entity/derived/shapes/plane.h delete mode 100644 plugins/filament_view/core/entity/derived/shapes/sphere.cc delete mode 100644 plugins/filament_view/core/entity/derived/shapes/sphere.h delete mode 100644 plugins/filament_view/core/include/additionalmath.h delete mode 100644 plugins/filament_view/core/include/color.h delete mode 100644 plugins/filament_view/core/include/file_utils.h delete mode 100644 plugins/filament_view/core/include/literals.h delete mode 100644 plugins/filament_view/core/include/resource.h delete mode 100644 plugins/filament_view/core/include/shapetypes.h delete mode 100644 plugins/filament_view/core/lifecycle_participant.h delete mode 100644 plugins/filament_view/core/scene/camera/exposure.cc delete mode 100644 plugins/filament_view/core/scene/camera/exposure.h delete mode 100644 plugins/filament_view/core/scene/camera/lens_projection.cc delete mode 100644 plugins/filament_view/core/scene/camera/lens_projection.h delete mode 100644 plugins/filament_view/core/scene/camera/projection.cc delete mode 100644 plugins/filament_view/core/scene/camera/projection.h delete mode 100644 plugins/filament_view/core/scene/camera/touch_pair.h delete mode 100644 plugins/filament_view/core/scene/geometry/direction.h delete mode 100644 plugins/filament_view/core/scene/geometry/position.h delete mode 100644 plugins/filament_view/core/scene/geometry/ray.cc delete mode 100644 plugins/filament_view/core/scene/geometry/ray.h delete mode 100644 plugins/filament_view/core/scene/geometry/size.cc delete mode 100644 plugins/filament_view/core/scene/geometry/size.h delete mode 100644 plugins/filament_view/core/scene/indirect_light/indirect_light.cc delete mode 100644 plugins/filament_view/core/scene/indirect_light/indirect_light.h delete mode 100644 plugins/filament_view/core/scene/material/loader/material_loader.cc delete mode 100644 plugins/filament_view/core/scene/material/loader/material_loader.h delete mode 100644 plugins/filament_view/core/scene/material/loader/texture_loader.cc delete mode 100644 plugins/filament_view/core/scene/material/loader/texture_loader.h delete mode 100644 plugins/filament_view/core/scene/material/material_parameter.cc delete mode 100644 plugins/filament_view/core/scene/material/material_parameter.h delete mode 100644 plugins/filament_view/core/scene/material/texture/enums/mag_filter.h delete mode 100644 plugins/filament_view/core/scene/material/texture/enums/min_filter.h delete mode 100644 plugins/filament_view/core/scene/material/texture/enums/wrap_mode.h delete mode 100644 plugins/filament_view/core/scene/material/texture/texture_definitions.cc delete mode 100644 plugins/filament_view/core/scene/material/texture/texture_definitions.h delete mode 100644 plugins/filament_view/core/scene/material/texture/texture_sampler.cc delete mode 100644 plugins/filament_view/core/scene/material/texture/texture_sampler.h delete mode 100644 plugins/filament_view/core/scene/serialization/scene_text_deserializer.cc delete mode 100644 plugins/filament_view/core/scene/serialization/scene_text_deserializer.h delete mode 100644 plugins/filament_view/core/scene/skybox/skybox.cc delete mode 100644 plugins/filament_view/core/scene/skybox/skybox.h delete mode 100644 plugins/filament_view/core/scene/view_target.cc delete mode 100644 plugins/filament_view/core/scene/view_target.h delete mode 100644 plugins/filament_view/core/systems/base/system.cc delete mode 100644 plugins/filament_view/core/systems/base/system.h delete mode 100644 plugins/filament_view/core/systems/derived/animation_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/animation_system.h delete mode 100644 plugins/filament_view/core/systems/derived/collision_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/collision_system.h delete mode 100644 plugins/filament_view/core/systems/derived/debug_lines_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/debug_lines_system.h delete mode 100644 plugins/filament_view/core/systems/derived/filament_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/filament_system.h delete mode 100644 plugins/filament_view/core/systems/derived/indirect_light_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/indirect_light_system.h delete mode 100644 plugins/filament_view/core/systems/derived/light_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/light_system.h delete mode 100644 plugins/filament_view/core/systems/derived/material_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/material_system.h delete mode 100644 plugins/filament_view/core/systems/derived/model_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/model_system.h delete mode 100644 plugins/filament_view/core/systems/derived/shape_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/shape_system.h delete mode 100644 plugins/filament_view/core/systems/derived/skybox_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/skybox_system.h delete mode 100644 plugins/filament_view/core/systems/derived/transform_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/transform_system.h delete mode 100644 plugins/filament_view/core/systems/derived/view_target_system.cc delete mode 100644 plugins/filament_view/core/systems/derived/view_target_system.h delete mode 100644 plugins/filament_view/core/systems/ecs.cc delete mode 100644 plugins/filament_view/core/systems/ecs.h delete mode 100644 plugins/filament_view/core/systems/messages/ecs_message.h delete mode 100644 plugins/filament_view/core/systems/messages/ecs_message_types.h delete mode 100644 plugins/filament_view/core/utils/asserts.cc delete mode 100644 plugins/filament_view/core/utils/asserts.h delete mode 100644 plugins/filament_view/core/utils/bounding_volumes.h delete mode 100644 plugins/filament_view/core/utils/deserialize.cc delete mode 100644 plugins/filament_view/core/utils/deserialize.h delete mode 100644 plugins/filament_view/core/utils/filament_types.h delete mode 100644 plugins/filament_view/core/utils/hdr_loader.cc delete mode 100644 plugins/filament_view/core/utils/hdr_loader.h delete mode 100644 plugins/filament_view/core/utils/ibl_profiler.h delete mode 100644 plugins/filament_view/core/utils/identifiable_type.h delete mode 100644 plugins/filament_view/core/utils/kvtree.cc delete mode 100644 plugins/filament_view/core/utils/kvtree.h delete mode 100644 plugins/filament_view/core/utils/smarter_pointers.h delete mode 100644 plugins/filament_view/core/utils/uuidGenerator.cc delete mode 100644 plugins/filament_view/core/utils/uuidGenerator.h delete mode 100644 plugins/filament_view/core/utils/vectorutils.cc delete mode 100644 plugins/filament_view/core/utils/vectorutils.h delete mode 100644 plugins/filament_view/filament_view_plugin.cc delete mode 100644 plugins/filament_view/filament_view_plugin.h delete mode 100644 plugins/filament_view/filament_view_plugin_c_api.cc delete mode 100644 plugins/filament_view/include/filament_view/filament_view_plugin_c_api.h delete mode 100644 plugins/filament_view/messages.g.cc delete mode 100644 plugins/filament_view/messages.g.h delete mode 100644 plugins/filament_view/test/mvp.cc diff --git a/.github/workflows/clang-tidy.yaml b/.github/workflows/clang-tidy.yaml index a8cbdf8d..36681a6a 100644 --- a/.github/workflows/clang-tidy.yaml +++ b/.github/workflows/clang-tidy.yaml @@ -103,49 +103,6 @@ jobs: ninja -C buildDir install ls -laR $LIBCAMERA_STAGING - - name: Cache filament - id: cache-filament-1-65-2 - uses: actions/cache@v4 - with: - key: ${{ runner.os }}-filament-1-65-2 - path: | - ${{github.workspace}}/filament/cmake-build-release/staging/release/* - - - name: Build Filament - if: steps.cache-filament-1-65-2.outputs.cache-hit != 'true' - working-directory: ${{github.workspace}} - run: | - git clone -b release https://github.com/google/filament.git - cd filament - git checkout v1.65.2 - PATCHES=${{github.workspace}}/.github/workflows/patches - git apply $PATCHES/filament/0001-disable-backend-tests-1.65.2.patch - git apply $PATCHES/filament/0002-install-required-files.patch - git apply $PATCHES/filament/0003-move-include-contents-to-include-filament.patch - git apply $PATCHES/filament/0004-move-libraries-so-they-install-1.65.2.patch - git apply $PATCHES/filament/0005-spirv-tools-threads.patch - FILAMENT_BUILD_DIR=$PWD/cmake-build-release - FILAMENT_STAGING_DIR=${FILAMENT_BUILD_DIR}/staging/release - mkdir -p $FILAMENT_BUILD_DIR - cd $FILAMENT_BUILD_DIR - CC=/usr/bin/clang CXX=/usr/bin/clang++ \ - cmake .. -GNinja \ - -DFILAMENT_SUPPORTS_VULKAN=ON \ - -DFILAMENT_ENABLE_LTO=OFF \ - -DFILAMENT_SUPPORTS_OPENGL=OFF \ - -DFILAMENT_USE_EXTERNAL_GLES3=OFF \ - -DFILAMENT_SUPPORTS_WAYLAND=ON \ - -DFILAMENT_SUPPORTS_X11=OFF \ - -DFILAMENT_SUPPORTS_XCB=OFF \ - -DFILAMENT_SUPPORTS_EGL_ON_LINUX=OFF \ - -DFILAMENT_SKIP_SDL2=ON \ - -DFILAMENT_SKIP_SAMPLES=ON \ - -DFILAMENT_USE_SWIFTSHADER=OFF \ - -DBUILD_SHARED_LIBS=OFF \ - -DCMAKE_STAGING_PREFIX=${FILAMENT_STAGING_DIR} \ - -DCMAKE_BUILD_TYPE=Release - ninja -C . install - - name: Configure CMake working-directory: ${{github.workspace}} run: | @@ -176,9 +133,6 @@ jobs: -D BUILD_PLUGIN_COMP_REGION=OFF \ -D BUILD_PLUGIN_COMP_SURF=OFF \ -D BUILD_PLUGIN_DESKTOP_WINDOW_LINUX=ON \ - -D BUILD_PLUGIN_FILAMENT_VIEW=ON \ - -D FILAMENT_INCLUDE_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/include \ - -D FILAMENT_LINK_LIBRARIES_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/lib/x86_64 \ -D BUILD_PLUGIN_FILE_SELECTOR=ON \ -D BUILD_PLUGIN_FIREBASE_AUTH=OFF \ -D BUILD_PLUGIN_FIREBASE_CORE=OFF \ @@ -225,9 +179,6 @@ jobs: -warnings-as-errors='*,-bugprone-macro-parentheses' \ -export-fixes=tidy-results-suggested-fixes.txt \ -extra-arg='-I${{github.workspace}}/ivi-homescreen/build/third_party/waypp/waypp/protocols' \ - -extra-arg='-I${{github.workspace}}/filament/cmake-build-release/staging/release/include' \ - -extra-arg='-I${{github.workspace}}/filament/cmake-build-release/staging/release/include/filament' \ - -extra-arg='-I${{github.workspace}}/filament/lib/utils/include' \ $FILE_LIST > tidy-results-log.txt - name: Show results diff --git a/.github/workflows/codeql.yml b/.github/workflows/codeql.yml index 7014c170..11afd454 100644 --- a/.github/workflows/codeql.yml +++ b/.github/workflows/codeql.yml @@ -141,50 +141,6 @@ jobs: ninja -C buildDir install ls -laR $LIBCAMERA_STAGING - - name: Cache filament - id: cache-filament - uses: actions/cache@v4 - with: - key: ${{ runner.os }}-filament - path: | - ${{github.workspace}}/filament/cmake-build-release/staging/release/* - - - name: Build Filament - if: steps.cache-filament.outputs.cache-hit != 'true' - working-directory: ${{github.workspace}} - run: | - git clone -b release https://github.com/google/filament.git - cd filament - git checkout v1.56.7 - PATCHES=${{github.workspace}}/.github/workflows/patches - git apply $PATCHES/filament/0001-disable-backend-tests.patch - git apply $PATCHES/filament/0002-install-required-files.patch - git apply $PATCHES/filament/0003-move-include-contents-to-include-filament.patch - git apply $PATCHES/filament/0004-move-libraries-so-they-install.patch - git apply $PATCHES/filament/0005-return-shader-type-mobile-for-linux-vulkan.patch - - FILAMENT_BUILD_DIR=$PWD/cmake-build-release - FILAMENT_STAGING_DIR=${FILAMENT_BUILD_DIR}/staging/release - mkdir -p $FILAMENT_BUILD_DIR - cd $FILAMENT_BUILD_DIR - CC=/usr/bin/clang CXX=/usr/bin/clang++ \ - cmake .. -GNinja \ - -DFILAMENT_SUPPORTS_VULKAN=ON \ - -DFILAMENT_ENABLE_LTO=ON \ - -DFILAMENT_SUPPORTS_OPENGL=OFF \ - -DFILAMENT_USE_EXTERNAL_GLES3=OFF \ - -DFILAMENT_SUPPORTS_WAYLAND=ON \ - -DFILAMENT_SUPPORTS_X11=OFF \ - -DFILAMENT_SUPPORTS_XCB=OFF \ - -DFILAMENT_SUPPORTS_EGL_ON_LINUX=OFF \ - -DFILAMENT_SKIP_SDL2=ON \ - -DFILAMENT_SKIP_SAMPLES=ON \ - -DFILAMENT_USE_SWIFTSHADER=OFF \ - -DBUILD_SHARED_LIBS=OFF \ - -DCMAKE_STAGING_PREFIX=${FILAMENT_STAGING_DIR} \ - -DCMAKE_BUILD_TYPE=Release - ninja -C . install - - name: Configure run: | find /usr -iname "llvm-config*" @@ -214,9 +170,6 @@ jobs: -D BUILD_PLUGIN_COMP_REGION=OFF \ -D BUILD_PLUGIN_COMP_SURF=OFF \ -D BUILD_PLUGIN_DESKTOP_WINDOW_LINUX=ON \ - -D BUILD_PLUGIN_FILAMENT_VIEW=ON \ - -D FILAMENT_INCLUDE_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/include \ - -D FILAMENT_LINK_LIBRARIES_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/lib/x86_64 \ -D BUILD_PLUGIN_FILE_SELECTOR=ON \ -D BUILD_PLUGIN_FIREBASE_AUTH=OFF \ -D BUILD_PLUGIN_FIREBASE_CORE=OFF \ diff --git a/.github/workflows/ivi-homescreen.yaml b/.github/workflows/ivi-homescreen.yaml index 0942478b..0be91acf 100644 --- a/.github/workflows/ivi-homescreen.yaml +++ b/.github/workflows/ivi-homescreen.yaml @@ -101,49 +101,6 @@ jobs: ninja -C buildDir install ls -laR $LIBCAMERA_STAGING - - name: Cache filament - id: cache-filament-1-65-2 - uses: actions/cache@v4 - with: - key: ${{ runner.os }}-filament-1-65-2 - path: | - ${{github.workspace}}/filament/cmake-build-release/staging/release/* - - - name: Build Filament - if: steps.cache-filament-1-65-2.outputs.cache-hit != 'true' - working-directory: ${{github.workspace}} - run: | - git clone -b release https://github.com/google/filament.git - cd filament - git checkout v1.65.2 - PATCHES=${{github.workspace}}/.github/workflows/patches - git apply $PATCHES/filament/0001-disable-backend-tests-1.65.2.patch - git apply $PATCHES/filament/0002-install-required-files.patch - git apply $PATCHES/filament/0003-move-include-contents-to-include-filament.patch - git apply $PATCHES/filament/0004-move-libraries-so-they-install-1.65.2.patch - git apply $PATCHES/filament/0005-spirv-tools-threads.patch - FILAMENT_BUILD_DIR=$PWD/cmake-build-release - FILAMENT_STAGING_DIR=${FILAMENT_BUILD_DIR}/staging/release - mkdir -p $FILAMENT_BUILD_DIR - cd $FILAMENT_BUILD_DIR - CC=/usr/bin/clang CXX=/usr/bin/clang++ \ - cmake .. -GNinja \ - -DFILAMENT_SUPPORTS_VULKAN=ON \ - -DFILAMENT_ENABLE_LTO=OFF \ - -DFILAMENT_SUPPORTS_OPENGL=OFF \ - -DFILAMENT_USE_EXTERNAL_GLES3=OFF \ - -DFILAMENT_SUPPORTS_WAYLAND=ON \ - -DFILAMENT_SUPPORTS_X11=OFF \ - -DFILAMENT_SUPPORTS_XCB=OFF \ - -DFILAMENT_SUPPORTS_EGL_ON_LINUX=OFF \ - -DFILAMENT_SKIP_SDL2=ON \ - -DFILAMENT_SKIP_SAMPLES=ON \ - -DFILAMENT_USE_SWIFTSHADER=OFF \ - -DBUILD_SHARED_LIBS=OFF \ - -DCMAKE_STAGING_PREFIX=${FILAMENT_STAGING_DIR} \ - -DCMAKE_BUILD_TYPE=Release - ninja -C . install - - name: Configure Debug run: | mkdir -p ${{github.workspace}}/build/debug @@ -177,9 +134,6 @@ jobs: -D BUILD_PLUGIN_COMP_REGION=OFF \ -D BUILD_PLUGIN_COMP_SURF=OFF \ -D BUILD_PLUGIN_DESKTOP_WINDOW_LINUX=ON \ - -D BUILD_PLUGIN_FILAMENT_VIEW=ON \ - -D FILAMENT_INCLUDE_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/include \ - -D FILAMENT_LINK_LIBRARIES_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/lib/x86_64 \ -D BUILD_PLUGIN_FILE_SELECTOR=ON \ -D BUILD_PLUGIN_FIREBASE_AUTH=OFF \ -D BUILD_PLUGIN_FIREBASE_CORE=OFF \ @@ -254,9 +208,6 @@ jobs: -D BUILD_PLUGIN_COMP_REGION=OFF \ -D BUILD_PLUGIN_COMP_SURF=OFF \ -D BUILD_PLUGIN_DESKTOP_WINDOW_LINUX=ON \ - -D BUILD_PLUGIN_FILAMENT_VIEW=ON \ - -D FILAMENT_INCLUDE_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/include \ - -D FILAMENT_LINK_LIBRARIES_DIR=${{github.workspace}}/filament/cmake-build-release/staging/release/lib/x86_64 \ -D BUILD_PLUGIN_FILE_SELECTOR=ON \ -D BUILD_PLUGIN_FIREBASE_AUTH=OFF \ -D BUILD_PLUGIN_FIREBASE_CORE=OFF \ diff --git a/.github/workflows/patches/filament/0001-disable-backend-tests-1.65.2.patch b/.github/workflows/patches/filament/0001-disable-backend-tests-1.65.2.patch deleted file mode 100644 index 08aed752..00000000 --- a/.github/workflows/patches/filament/0001-disable-backend-tests-1.65.2.patch +++ /dev/null @@ -1,33 +0,0 @@ -From 0c4bc86bbfc883db61b585a21d2653ca8514f2f7 Mon Sep 17 00:00:00 2001 -From: Joel Winarske -Date: Fri, 26 Sep 2025 07:13:07 -0700 -Subject: [PATCH] disable backend tests 1.65.2 - -Signed-off-by: Joel Winarske ---- - filament/backend/CMakeLists.txt | 9 --------- - 1 file changed, 9 deletions(-) - -diff --git a/filament/backend/CMakeLists.txt b/filament/backend/CMakeLists.txt -index 989078622..48c1d0a84 100644 ---- a/filament/backend/CMakeLists.txt -+++ b/filament/backend/CMakeLists.txt -@@ -660,15 +660,6 @@ if (APPLE AND NOT IOS) - endif() - endif() - --if (LINUX) -- add_executable(backend_test_linux test/linux_runner.cpp ${BACKEND_TEST_SRC}) -- target_link_libraries(backend_test_linux PRIVATE ${BACKEND_TEST_LIBS}) -- set_target_properties(backend_test_linux PROPERTIES FOLDER Tests) -- if (FILAMENT_SUPPORTS_WEBGPU) -- target_link_libraries(backend_test_linux PRIVATE webgpu_dawn dawncpp_headers) -- endif() --endif() -- - # ================================================================================================== - # Compute tests - # --- -2.51.0 - diff --git a/.github/workflows/patches/filament/0002-install-required-files.patch b/.github/workflows/patches/filament/0002-install-required-files.patch deleted file mode 100644 index ef6a002f..00000000 --- a/.github/workflows/patches/filament/0002-install-required-files.patch +++ /dev/null @@ -1,63 +0,0 @@ -From e7b701237581835e1267c30b3f5ef9cbd5b447c5 Mon Sep 17 00:00:00 2001 -From: Joel Winarske -Date: Sun, 26 Jan 2025 10:42:12 -0800 -Subject: [PATCH 2/5] install required files - -Signed-off-by: Joel Winarske ---- - libs/imageio/CMakeLists.txt | 6 ++++++ - third_party/libpng/tnt/CMakeLists.txt | 2 ++ - third_party/stb/tnt/CMakeLists.txt | 1 + - third_party/tinyexr/tnt/CMakeLists.txt | 5 ++++- - 4 files changed, 13 insertions(+), 1 deletion(-) - -diff --git a/libs/imageio/CMakeLists.txt b/libs/imageio/CMakeLists.txt -index 47544655b..7169da462 100644 ---- a/libs/imageio/CMakeLists.txt -+++ b/libs/imageio/CMakeLists.txt -@@ -44,3 +44,9 @@ endif() - if (NOT MSVC) - target_compile_options(${TARGET} PRIVATE -Wno-deprecated-register) - endif() -+ -+# ================================================================================================== -+# Installation -+# ================================================================================================== -+install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/imageio DESTINATION include/filament) -diff --git a/third_party/libpng/tnt/CMakeLists.txt b/third_party/libpng/tnt/CMakeLists.txt -index cd5a033f5..4925a0474 100644 ---- a/third_party/libpng/tnt/CMakeLists.txt -+++ b/third_party/libpng/tnt/CMakeLists.txt -@@ -57,3 +57,5 @@ target_link_libraries(${TARGET} PUBLIC z) - # specify where the public headers of this library are - target_include_directories(${TARGET} PUBLIC ${PUBLIC_HDR_DIR}) - set_target_properties(${TARGET} PROPERTIES FOLDER ThirdParty) -+ -+install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) -diff --git a/third_party/stb/tnt/CMakeLists.txt b/third_party/stb/tnt/CMakeLists.txt -index 0c25061c0..563a2604d 100644 ---- a/third_party/stb/tnt/CMakeLists.txt -+++ b/third_party/stb/tnt/CMakeLists.txt -@@ -15,3 +15,4 @@ target_include_directories(${TARGET} PUBLIC ${PUBLIC_HDR_DIR}) - set_target_properties(${TARGET} PROPERTIES FOLDER ThirdParty) - - install(TARGETS stb ARCHIVE DESTINATION lib/${DIST_DIR}) -+install(FILES ${PUBLIC_HDRS} DESTINATION include/filament) -diff --git a/third_party/tinyexr/tnt/CMakeLists.txt b/third_party/tinyexr/tnt/CMakeLists.txt -index 20955b77b..ffe7cdfe1 100644 ---- a/third_party/tinyexr/tnt/CMakeLists.txt -+++ b/third_party/tinyexr/tnt/CMakeLists.txt -@@ -20,4 +20,7 @@ include_directories(${PUBLIC_HDR_DIR}) - add_library(${TARGET} STATIC ${PUBLIC_HDRS} ${SRCS}) - target_include_directories (${TARGET} PUBLIC ${PUBLIC_HDR_DIR}) - target_link_libraries(${TARGET} LINK_PUBLIC z) --set_target_properties(${TARGET} PROPERTIES FOLDER ThirdParty) -\ No newline at end of file -+set_target_properties(${TARGET} PROPERTIES FOLDER ThirdParty) -+ -+install(FILES ${PUBLIC_HDRS} DESTINATION include/filament) -+install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --- -2.48.1 - diff --git a/.github/workflows/patches/filament/0003-move-include-contents-to-include-filament.patch b/.github/workflows/patches/filament/0003-move-include-contents-to-include-filament.patch deleted file mode 100644 index 906833ab..00000000 --- a/.github/workflows/patches/filament/0003-move-include-contents-to-include-filament.patch +++ /dev/null @@ -1,239 +0,0 @@ -diff --git a/filament/CMakeLists.txt b/filament/CMakeLists.txt -index fae6565..3bbb22b 100644 ---- a/filament/CMakeLists.txt -+++ b/filament/CMakeLists.txt -@@ -651,7 +651,7 @@ target_link_libraries(${TARGET} PRIVATE - # ================================================================================================== - set(INSTALL_TYPE ARCHIVE) - install(TARGETS ${TARGET} ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/filament DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/filament DESTINATION include/filament) - install(FILES "README.md" DESTINATION .) - install(FILES "../LICENSE" DESTINATION .) - -diff --git a/filament/backend/CMakeLists.txt b/filament/backend/CMakeLists.txt -index 24cc789..4bfd9c5 100644 ---- a/filament/backend/CMakeLists.txt -+++ b/filament/backend/CMakeLists.txt -@@ -493,7 +493,7 @@ target_link_libraries(${TARGET} PRIVATE - set(INSTALL_TYPE ARCHIVE) - install(TARGETS ${TARGET} ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) - install(TARGETS vkshaders ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/backend DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/backend DESTINATION include/filament) - - if (FILAMENT_SUPPORTS_WEBGPU) - install(TARGETS webgpu_dawn ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) -diff --git a/libs/camutils/CMakeLists.txt b/libs/camutils/CMakeLists.txt -index 541261c..013cbce 100644 ---- a/libs/camutils/CMakeLists.txt -+++ b/libs/camutils/CMakeLists.txt -@@ -45,7 +45,7 @@ endif() - # Installation - # ================================================================================================== - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/camutils DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/camutils DESTINATION include/filament) - - # ================================================================================================== - # Tests -diff --git a/libs/filabridge/CMakeLists.txt b/libs/filabridge/CMakeLists.txt -index 6840ce5..9627713 100644 ---- a/libs/filabridge/CMakeLists.txt -+++ b/libs/filabridge/CMakeLists.txt -@@ -32,5 +32,5 @@ target_link_libraries(${TARGET} backend_headers) - # ================================================================================================== - # Installation - # ================================================================================================== --install(DIRECTORY ${PUBLIC_HDR_DIR}/filament DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/filament DESTINATION include/filament) - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) -diff --git a/libs/filamat/CMakeLists.txt b/libs/filamat/CMakeLists.txt -index 3d790b0..dd397df 100644 ---- a/libs/filamat/CMakeLists.txt -+++ b/libs/filamat/CMakeLists.txt -@@ -144,7 +144,7 @@ combine_static_libs(filamat "${FILAMAT_COMBINED_OUTPUT}" "${FILAMAT_DEPS}") - - set(FILAMAT_LIB_NAME ${CMAKE_STATIC_LIBRARY_PREFIX}filamat${CMAKE_STATIC_LIBRARY_SUFFIX}) - install(FILES "${FILAMAT_COMBINED_OUTPUT}" DESTINATION lib/${DIST_DIR} RENAME ${FILAMAT_LIB_NAME}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/filamat DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/filamat DESTINATION include/filament) - - # Need to install libtint for filamat on Android. - # See libs/filamat/CMakeLists.txt and android/filamat-android/CMakeLists.txt. -diff --git a/libs/filameshio/CMakeLists.txt b/libs/filameshio/CMakeLists.txt -index eab3192..7143002 100644 ---- a/libs/filameshio/CMakeLists.txt -+++ b/libs/filameshio/CMakeLists.txt -@@ -32,7 +32,7 @@ target_link_libraries(${TARGET} - # ================================================================================================== - set(INSTALL_TYPE ARCHIVE) - install(TARGETS ${TARGET} ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) --install(FILES ${DIST_HDRS} DESTINATION include/${TARGET}) -+install(FILES ${DIST_HDRS} DESTINATION include/filament/${TARGET}) - - # ================================================================================================== - # Tests -diff --git a/libs/geometry/CMakeLists.txt b/libs/geometry/CMakeLists.txt -index a7e8f39..5a5bb88 100644 ---- a/libs/geometry/CMakeLists.txt -+++ b/libs/geometry/CMakeLists.txt -@@ -55,7 +55,7 @@ endif() - # No need to install since we're combining this lib and the dependent libs into a combined lib - # install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) - --install(DIRECTORY ${PUBLIC_HDR_DIR}/geometry DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/geometry DESTINATION include/filament) - - set(COMBINED_DEPS - ${TARGET} -diff --git a/libs/gltfio/CMakeLists.txt b/libs/gltfio/CMakeLists.txt -index 373df1f..de289cf 100644 ---- a/libs/gltfio/CMakeLists.txt -+++ b/libs/gltfio/CMakeLists.txt -@@ -265,5 +265,5 @@ endif() - # ================================================================================================== - - install(TARGETS gltfio_core uberarchive ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/gltfio DESTINATION include) --install(FILES ${RESOURCE_DIR}/materials/uberarchive.h DESTINATION include/gltfio/materials) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/gltfio DESTINATION include/filament) -+install(FILES ${RESOURCE_DIR}/materials/uberarchive.h DESTINATION include/filament/gltfio/materials) -diff --git a/libs/iblprefilter/CMakeLists.txt b/libs/iblprefilter/CMakeLists.txt -index c001de6..62066b3 100644 ---- a/libs/iblprefilter/CMakeLists.txt -+++ b/libs/iblprefilter/CMakeLists.txt -@@ -135,4 +135,4 @@ target_link_libraries(${TARGET} PRIVATE - # ================================================================================================== - set(INSTALL_TYPE ARCHIVE) - install(TARGETS ${TARGET} ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/filament-iblprefilter DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/filament-iblprefilter DESTINATION include/filament) - - # ================================================================================================== - # Tests -diff --git a/libs/ktxreader/CMakeLists.txt b/libs/ktxreader/CMakeLists.txt -index a9d5714..039ee6a 100644 ---- a/libs/ktxreader/CMakeLists.txt -+++ b/libs/ktxreader/CMakeLists.txt -@@ -41,7 +41,7 @@ endif() - # Installation - # ================================================================================================== - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/${TARGET} DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/${TARGET} DESTINATION include/filament) - - # ================================================================================================== - # Tests -diff --git a/libs/math/CMakeLists.txt b/libs/math/CMakeLists.txt -index 838aa2d..4256d66 100644 ---- a/libs/math/CMakeLists.txt -+++ b/libs/math/CMakeLists.txt -@@ -47,7 +47,7 @@ set_target_properties(${TARGET} PROPERTIES FOLDER Libs) - # ================================================================================================== - # Installation - # ================================================================================================== --install(DIRECTORY ${PUBLIC_HDR_DIR}/math DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/math DESTINATION include/filament) - - # ================================================================================================== - # Tests -diff --git a/libs/mathio/CMakeLists.txt b/libs/mathio/CMakeLists.txt -index 4ad5126..96b5287 100644 ---- a/libs/mathio/CMakeLists.txt -+++ b/libs/mathio/CMakeLists.txt -@@ -27,5 +27,5 @@ target_link_libraries(${TARGET} PRIVATE math) - # ================================================================================================== - # Installation - # ================================================================================================== --install(DIRECTORY ${PUBLIC_HDR_DIR}/mathio DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/mathio DESTINATION include/filament) - -diff --git a/libs/uberz/CMakeLists.txt b/libs/uberz/CMakeLists.txt -index 47744e2..85569b5 100644 ---- a/libs/uberz/CMakeLists.txt -+++ b/libs/uberz/CMakeLists.txt -@@ -44,4 +44,4 @@ endif() - # Installation - # ================================================================================================== - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/uberz DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/uberz DESTINATION include/filament) -diff --git a/libs/utils/CMakeLists.txt b/libs/utils/CMakeLists.txt -index 3af98d0..ebb02e4 100644 ---- a/libs/utils/CMakeLists.txt -+++ b/libs/utils/CMakeLists.txt -@@ -139,11 +139,11 @@ endif() - # ================================================================================================== - set(INSTALL_TYPE ARCHIVE) - install(TARGETS ${TARGET} ${INSTALL_TYPE} DESTINATION lib/${DIST_DIR}) --install(FILES ${DIST_HDRS} DESTINATION include/${TARGET}) -+install(FILES ${DIST_HDRS} DESTINATION include/filament/${TARGET}) - if (ANDROID) -- install(FILES ${DIST_ANDROID_HDRS} DESTINATION include/${TARGET_LINUX}) -+ install(FILES ${DIST_ANDROID_HDRS} DESTINATION include/filament/${TARGET_LINUX}) - else() -- install(FILES ${DIST_GENERIC_HDRS} DESTINATION include/${TARGET_GENERIC}) -+ install(FILES ${DIST_GENERIC_HDRS} DESTINATION include/filament/${TARGET_GENERIC}) - endif() - - # ================================================================================================== -diff --git a/libs/viewer/CMakeLists.txt b/libs/viewer/CMakeLists.txt -index 3b67fde..5e40ef1 100644 ---- a/libs/viewer/CMakeLists.txt -+++ b/libs/viewer/CMakeLists.txt -@@ -54,7 +54,7 @@ endif() - # Installation - # ================================================================================================== - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/viewer DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/viewer DESTINATION include/filament) - - # ================================================================================================== - # Tests -diff --git a/third_party/libassimp/contrib/zip/CMakeLists.txt b/third_party/libassimp/contrib/zip/CMakeLists.txt -index b46dbb1..368017a 100644 ---- a/third_party/libassimp/contrib/zip/CMakeLists.txt -+++ b/third_party/libassimp/contrib/zip/CMakeLists.txt -@@ -33,7 +33,7 @@ install(TARGETS ${PROJECT_NAME} - ARCHIVE DESTINATION lib - LIBRARY DESTINATION lib - COMPONENT library) --install(FILES ${PROJECT_SOURCE_DIR}/src/zip.h DESTINATION include) -+install(FILES ${PROJECT_SOURCE_DIR}/src/zip.h DESTINATION include/filament) - - # uninstall target (https://gitlab.kitware.com/cmake/community/wikis/FAQ#can-i-do-make-uninstall-with-cmake) - if(NOT TARGET uninstall) -diff --git a/third_party/libsdl2/CMakeLists.txt b/third_party/libsdl2/CMakeLists.txt -index 8f1e828..b1d7cbd 100644 ---- a/third_party/libsdl2/CMakeLists.txt -+++ b/third_party/libsdl2/CMakeLists.txt -@@ -1806,7 +1806,7 @@ foreach(_FNAME ${BIN_INCLUDE_FILES}) - list(REMOVE_ITEM INCLUDE_FILES ${SDL2_SOURCE_DIR}/include/${_INCNAME}) - endforeach() - list(APPEND INCLUDE_FILES ${BIN_INCLUDE_FILES}) --install(FILES ${INCLUDE_FILES} DESTINATION include/SDL2) -+install(FILES ${INCLUDE_FILES} DESTINATION include/filament/SDL2) - - if(NOT (WINDOWS OR CYGWIN)) - if(SDL_SHARED) -diff --git a/third_party/mikktspace/CMakeLists.txt b/third_party/mikktspace/CMakeLists.txt -index 36959ae..6c8fead 100644 ---- a/third_party/mikktspace/CMakeLists.txt -+++ b/third_party/mikktspace/CMakeLists.txt -@@ -26,4 +26,4 @@ endif() - # Installation - # ================================================================================================== - install(TARGETS ${TARGET} ARCHIVE DESTINATION lib/${DIST_DIR}) --install(DIRECTORY ${PUBLIC_HDR_DIR}/mikktspace DESTINATION include) -+install(DIRECTORY ${PUBLIC_HDR_DIR}/mikktspace DESTINATION include/filament) -diff --git a/third_party/robin-map/tnt/CMakeLists.txt b/third_party/robin-map/tnt/CMakeLists.txt -index 300da52..ef5ef82 100644 ---- a/third_party/robin-map/tnt/CMakeLists.txt -+++ b/third_party/robin-map/tnt/CMakeLists.txt -@@ -27,4 +27,4 @@ set_target_properties(${TARGET} PROPERTIES FOLDER ThirdParty) - # ================================================================================================== - # Installation - # ================================================================================================== --install(FILES ${PUBLIC_HDRS} DESTINATION include/${TARGET}) -+install(FILES ${PUBLIC_HDRS} DESTINATION include/filament/${TARGET}) diff --git a/.github/workflows/patches/filament/0004-move-libraries-so-they-install-1.65.2.patch b/.github/workflows/patches/filament/0004-move-libraries-so-they-install-1.65.2.patch deleted file mode 100644 index f46a820e..00000000 --- a/.github/workflows/patches/filament/0004-move-libraries-so-they-install-1.65.2.patch +++ /dev/null @@ -1,53 +0,0 @@ -From 96ddb443dca9a60a53df5acb6f8553d7526892dc Mon Sep 17 00:00:00 2001 -From: Joel Winarske -Date: Fri, 26 Sep 2025 06:35:12 -0700 -Subject: [PATCH] move libraries so they install - -Signed-off-by: Joel Winarske ---- - CMakeLists.txt | 8 ++++---- - 1 file changed, 4 insertions(+), 4 deletions(-) - -diff --git a/CMakeLists.txt b/CMakeLists.txt -index 15f5f52ac5..015fb9e771 100644 ---- a/CMakeLists.txt -+++ b/CMakeLists.txt -@@ -808,6 +808,7 @@ add_subdirectory(${LIBRARIES}/gltfio) - add_subdirectory(${LIBRARIES}/ibl) - add_subdirectory(${LIBRARIES}/iblprefilter) - add_subdirectory(${LIBRARIES}/image) -+add_subdirectory(${LIBRARIES}/imageio) - add_subdirectory(${LIBRARIES}/ktxreader) - add_subdirectory(${LIBRARIES}/math) - add_subdirectory(${LIBRARIES}/mathio) -@@ -829,7 +830,10 @@ add_subdirectory(${EXTERNAL}/draco/tnt) - add_subdirectory(${EXTERNAL}/jsmn/tnt) - add_subdirectory(${EXTERNAL}/stb/tnt) - add_subdirectory(${EXTERNAL}/getopt) -+add_subdirectory(${EXTERNAL}/libpng/tnt) - add_subdirectory(${EXTERNAL}/perfetto/tnt) -+add_subdirectory(${EXTERNAL}/tinyexr/tnt) -+add_subdirectory(${EXTERNAL}/libz/tnt) - add_subdirectory(${EXTERNAL}/zstd/tnt) - - # Note that this has to be placed after mikktspace in order for combine_static_libs to work. -@@ -882,16 +886,12 @@ if (IS_HOST_PLATFORM) - if (NOT FILAMENT_SKIP_SDL2) - add_subdirectory(${LIBRARIES}/filamentapp) - endif() -- add_subdirectory(${LIBRARIES}/imageio) - add_subdirectory(${LIBRARIES}/filament-matp) - - add_subdirectory(${FILAMENT}/samples) - - add_subdirectory(${EXTERNAL}/libassimp/tnt) -- add_subdirectory(${EXTERNAL}/libpng/tnt) - add_subdirectory(${EXTERNAL}/libsdl2/tnt) -- add_subdirectory(${EXTERNAL}/libz/tnt) -- add_subdirectory(${EXTERNAL}/tinyexr/tnt) - - add_subdirectory(${TOOLS}/cmgen) - add_subdirectory(${TOOLS}/cso-lut) --- -2.51.0 - diff --git a/.github/workflows/patches/filament/0005-spirv-tools-threads.patch b/.github/workflows/patches/filament/0005-spirv-tools-threads.patch deleted file mode 100644 index 428ec478..00000000 --- a/.github/workflows/patches/filament/0005-spirv-tools-threads.patch +++ /dev/null @@ -1,54 +0,0 @@ -From a06e514a0ace502163b1a1074871303bafa81903 Mon Sep 17 00:00:00 2001 -From: Joel Winarske -Date: Fri, 26 Sep 2025 14:26:07 -0700 -Subject: [PATCH] spirv-tools threads - -Signed-off-by: Joel Winarske ---- - third_party/spirv-tools/CMakeLists.txt | 2 ++ - third_party/spirv-tools/examples/CMakeLists.txt | 2 +- - third_party/spirv-tools/tools/CMakeLists.txt | 2 +- - 3 files changed, 4 insertions(+), 2 deletions(-) - -diff --git a/third_party/spirv-tools/CMakeLists.txt b/third_party/spirv-tools/CMakeLists.txt -index affc49ed8..7ce7744c9 100644 ---- a/third_party/spirv-tools/CMakeLists.txt -+++ b/third_party/spirv-tools/CMakeLists.txt -@@ -56,6 +56,8 @@ set(CMAKE_CXX_EXTENSIONS OFF) - option(ENABLE_RTTI "Enables RTTI" OFF) - option(SPIRV_ALLOW_TIMERS "Allow timers via clock_gettime on supported platforms" ON) - -+find_package(Threads) -+ - if("${CMAKE_SYSTEM_NAME}" STREQUAL "Linux") - set(SPIRV_TIMER_ENABLED ${SPIRV_ALLOW_TIMERS}) - elseif("${CMAKE_SYSTEM_NAME}" MATCHES "Windows") -diff --git a/third_party/spirv-tools/examples/CMakeLists.txt b/third_party/spirv-tools/examples/CMakeLists.txt -index fd627cbda..7c723897b 100644 ---- a/third_party/spirv-tools/examples/CMakeLists.txt -+++ b/third_party/spirv-tools/examples/CMakeLists.txt -@@ -27,7 +27,7 @@ function(add_spvtools_example) - - add_executable(${ARG_TARGET} ${ARG_SRCS}) - spvtools_default_compile_options(${ARG_TARGET}) -- target_link_libraries(${ARG_TARGET} PRIVATE ${ARG_LIBS}) -+ target_link_libraries(${ARG_TARGET} PRIVATE ${ARG_LIBS} ${CMAKE_THREAD_LIBS_INIT}) - set_property(TARGET ${ARG_TARGET} PROPERTY FOLDER "SPIRV-Tools examples") - endif() - endfunction() -diff --git a/third_party/spirv-tools/tools/CMakeLists.txt b/third_party/spirv-tools/tools/CMakeLists.txt -index f5e830f57..8ad87ca32 100644 ---- a/third_party/spirv-tools/tools/CMakeLists.txt -+++ b/third_party/spirv-tools/tools/CMakeLists.txt -@@ -40,7 +40,7 @@ function(add_spvtools_tool) - endif() - - spvtools_default_compile_options(${ARG_TARGET}) -- target_link_libraries(${ARG_TARGET} PRIVATE ${ARG_LIBS}) -+ target_link_libraries(${ARG_TARGET} PRIVATE ${ARG_LIBS} ${CMAKE_THREAD_LIBS_INIT}) - target_include_directories(${ARG_TARGET} PRIVATE - ${spirv-tools_SOURCE_DIR} - ${spirv-tools_BINARY_DIR} --- -2.51.0 - diff --git a/.github/workflows/patches/filament/0006-return-shader-type-mobile-for-linux-vulkan.patch b/.github/workflows/patches/filament/0006-return-shader-type-mobile-for-linux-vulkan.patch deleted file mode 100644 index eb913fab..00000000 --- a/.github/workflows/patches/filament/0006-return-shader-type-mobile-for-linux-vulkan.patch +++ /dev/null @@ -1,26 +0,0 @@ -From 28ed6e3d6b5df4fc6ce9d11cda04144cce67b653 Mon Sep 17 00:00:00 2001 -From: Joel Winarske -Date: Sun, 26 Jan 2025 11:03:15 -0800 -Subject: [PATCH 5/5] return shader type mobile for linux vulkan - -Signed-off-by: Joel Winarske ---- - filament/backend/src/vulkan/VulkanDriver.cpp | 2 +- - 1 file changed, 1 insertion(+), 1 deletion(-) - -diff --git a/filament/backend/src/vulkan/VulkanDriver.cpp b/filament/backend/src/vulkan/VulkanDriver.cpp -index 520ea22b7..3cb61dd24 100644 ---- a/filament/backend/src/vulkan/VulkanDriver.cpp -+++ b/filament/backend/src/vulkan/VulkanDriver.cpp -@@ -288,7 +288,7 @@ Driver* VulkanDriver::create(VulkanPlatform* platform, VulkanContext const& cont - } - - ShaderModel VulkanDriver::getShaderModel() const noexcept { --#if defined(__ANDROID__) || defined(FILAMENT_IOS) -+#if defined(__ANDROID__) || defined(FILAMENT_IOS) || defined(__linux__) - return ShaderModel::MOBILE; - #else - return ShaderModel::DESKTOP; --- -2.48.1 - diff --git a/.github/workflows/patches/filament/ImportExecutables-Release.cmake b/.github/workflows/patches/filament/ImportExecutables-Release.cmake deleted file mode 100644 index 9cfde4d4..00000000 --- a/.github/workflows/patches/filament/ImportExecutables-Release.cmake +++ /dev/null @@ -1,115 +0,0 @@ -if("${CMAKE_MAJOR_VERSION}.${CMAKE_MINOR_VERSION}" LESS 2.8) - message(FATAL_ERROR "CMake >= 2.8.0 required") -endif() -if(CMAKE_VERSION VERSION_LESS "2.8.3") - message(FATAL_ERROR "CMake >= 2.8.3 required") -endif() -cmake_policy(PUSH) -cmake_policy(VERSION 2.8.3...3.25) -#---------------------------------------------------------------- -# Generated CMake target import file. -#---------------------------------------------------------------- - -# Commands may need to know the format version. -set(CMAKE_IMPORT_FILE_VERSION 1) - -# Protect against multiple inclusion, which would fail when already imported targets are added once more. -set(_cmake_targets_defined "") -set(_cmake_targets_not_defined "") -set(_cmake_expected_targets "") -foreach(_cmake_expected_target IN ITEMS matc cmgen filamesh mipgen resgen uberz glslminifier) - list(APPEND _cmake_expected_targets "${_cmake_expected_target}") - if(TARGET "${_cmake_expected_target}") - list(APPEND _cmake_targets_defined "${_cmake_expected_target}") - else() - list(APPEND _cmake_targets_not_defined "${_cmake_expected_target}") - endif() -endforeach() -unset(_cmake_expected_target) -if(_cmake_targets_defined STREQUAL _cmake_expected_targets) - unset(_cmake_targets_defined) - unset(_cmake_targets_not_defined) - unset(_cmake_expected_targets) - unset(CMAKE_IMPORT_FILE_VERSION) - cmake_policy(POP) - return() -endif() -if(NOT _cmake_targets_defined STREQUAL "") - string(REPLACE ";" ", " _cmake_targets_defined_text "${_cmake_targets_defined}") - string(REPLACE ";" ", " _cmake_targets_not_defined_text "${_cmake_targets_not_defined}") - message(FATAL_ERROR "Some (but not all) targets in this export set were already defined.\nTargets Defined: ${_cmake_targets_defined_text}\nTargets not yet defined: ${_cmake_targets_not_defined_text}\n") -endif() -unset(_cmake_targets_defined) -unset(_cmake_targets_not_defined) -unset(_cmake_expected_targets) - - -# Create imported target matc -add_executable(matc IMPORTED) - -# Create imported target cmgen -add_executable(cmgen IMPORTED) - -# Create imported target filamesh -add_executable(filamesh IMPORTED) - -# Create imported target mipgen -add_executable(mipgen IMPORTED) - -# Create imported target resgen -add_executable(resgen IMPORTED) - -# Create imported target uberz -add_executable(uberz IMPORTED) - -# Create imported target glslminifier -add_executable(glslminifier IMPORTED) - -# Import target "matc" for configuration "Release" -set_property(TARGET matc APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(matc PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/matc" - ) - -# Import target "cmgen" for configuration "Release" -set_property(TARGET cmgen APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(cmgen PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/cmgen" - ) - -# Import target "filamesh" for configuration "Release" -set_property(TARGET filamesh APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(filamesh PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/filamesh" - ) - -# Import target "mipgen" for configuration "Release" -set_property(TARGET mipgen APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(mipgen PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/mipgen" - ) - -# Import target "resgen" for configuration "Release" -set_property(TARGET resgen APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(resgen PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/resgen" - ) - -# Import target "uberz" for configuration "Release" -set_property(TARGET uberz APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(uberz PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/uberz" - ) - -# Import target "glslminifier" for configuration "Release" -set_property(TARGET glslminifier APPEND PROPERTY IMPORTED_CONFIGURATIONS RELEASE) -set_target_properties(glslminifier PROPERTIES - IMPORTED_LOCATION_RELEASE "${FILAMENT_HOST_TOOLS_ROOT}/glslminifier" - ) - -# This file does not depend on other imported targets which have -# been exported from the same project but in a separate export set. - -# Commands beyond this point should not need to know the version. -set(CMAKE_IMPORT_FILE_VERSION) -cmake_policy(POP) \ No newline at end of file diff --git a/docs/source/filament_view.md b/docs/source/filament_view.md deleted file mode 120000 index 1458b7b3..00000000 --- a/docs/source/filament_view.md +++ /dev/null @@ -1 +0,0 @@ -../../plugins/filament_view/README.md \ No newline at end of file diff --git a/docs/source/index.rst b/docs/source/index.rst index 1b0ac246..6b93214b 100644 --- a/docs/source/index.rst +++ b/docs/source/index.rst @@ -11,7 +11,6 @@ Welcome to ivi-homescreen-plugin's documentation! camera cloud_firestore desktop_window_linux - filament_view file_selector firebase_auth firebase_core diff --git a/plugins/CMakeLists.txt b/plugins/CMakeLists.txt index b437ac5a..2265e7cd 100644 --- a/plugins/CMakeLists.txt +++ b/plugins/CMakeLists.txt @@ -125,8 +125,6 @@ PLUGIN_OPTION(webrtc "Include Webrtc plugin" OFF) # Platform View Plugins -PLUGIN_OPTION(filament_view "Include Filament View plugin" OFF) - PLUGIN_OPTION(layer_playground_view "Include Layer Playground View plugin" OFF) PLUGIN_OPTION(nav_render_view "Include Navigation Render View plugin" OFF) diff --git a/plugins/config_plugins.h.in b/plugins/config_plugins.h.in index 445cc4cd..71be4946 100644 --- a/plugins/config_plugins.h.in +++ b/plugins/config_plugins.h.in @@ -114,11 +114,6 @@ #include "webrtc/include/webrtc/webrtc_plugin_c_api.h" #endif -#cmakedefine01 ENABLE_PLUGIN_FILAMENT_VIEW -#if ENABLE_PLUGIN_FILAMENT_VIEW -#include "filament_view/include/filament_view/filament_view_plugin_c_api.h" -#endif - #cmakedefine01 ENABLE_PLUGIN_LAYER_PLAYGROUND_VIEW #if ENABLE_PLUGIN_LAYER_PLAYGROUND_VIEW #include "layer_playground_view/include/layer_playground_view/layer_playground_view_plugin_c_api.h" diff --git a/plugins/filament_view/.clang-format b/plugins/filament_view/.clang-format deleted file mode 100644 index d4501b60..00000000 --- a/plugins/filament_view/.clang-format +++ /dev/null @@ -1,51 +0,0 @@ -# command: -# find plugins -type d -name third_party -prune -false -o -name '*.cc' -o -name '*.hpp' -o -name '*.h' > clang-format-files && clang-format-18 -i --files=clang-format-files - -Language: Cpp -UseTab: Never -TabWidth: 2 -IndentWidth: 2 -ContinuationIndentWidth: 2 -BracedInitializerIndentWidth: 2 -ConstructorInitializerIndentWidth: 2 # broken: llvm/llvm-project#61631 -ColumnLimit: 100 - -SpacesBeforeTrailingComments: 2 -AlignTrailingComments: - Kind: Always - OverEmptyLines: 1 - -IndentCaseLabels: true -AllowShortIfStatementsOnASingleLine: true -BreakBeforeBinaryOperators: NonAssignment - -SpacesInParens: Custom -SpacesInParensOptions: - InConditionalStatements: false - Other: false -SpacesInAngles: Never -SpaceAfterCStyleCast: false -IndentAccessModifiers: true -Cpp11BracedListStyle: true -PointerAlignment: Left -QualifierAlignment: Left - -AlignAfterOpenBracket: BlockIndent -AllowAllArgumentsOnNextLine: true -AllowAllParametersOfDeclarationOnNextLine: false -BinPackArguments: true -BinPackParameters: false -BreakBeforeBraces: Attach -PackConstructorInitializers: Never -# AlignAfterControlStatement: true # waiting for llvm/llvm-project#67738 - -BreakAfterAttributes: Never -AlwaysBreakAfterReturnType: None -PenaltyReturnTypeOnItsOwnLine: 1000 # default: 60 -PenaltyBreakAssignment: 100 -BreakBeforeConceptDeclarations: Always -SpaceAfterTemplateKeyword: false - -PenaltyBreakOpenParenthesis: 0 - -InsertNewlineAtEOF: true \ No newline at end of file diff --git a/plugins/filament_view/CMakeLists.txt b/plugins/filament_view/CMakeLists.txt deleted file mode 100644 index feabfaad..00000000 --- a/plugins/filament_view/CMakeLists.txt +++ /dev/null @@ -1,162 +0,0 @@ -# -# Copyright 2024 Toyota Connected North America -# -# 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. -# - -include_guard() - -if (NOT EXISTS ${FILAMENT_INCLUDE_DIR}) - message(FATAL_ERROR "${FILAMENT_INCLUDE_DIR} does not exist") -endif () -if (NOT EXISTS ${FILAMENT_LINK_LIBRARIES_DIR}) - message(FATAL_ERROR "${FILAMENT_LINK_LIBRARIES_DIR} does not exist") -endif () - -message(STATUS " FILAMENT_INCLUDE_DIR: ${FILAMENT_INCLUDE_DIR}") -message(STATUS " FILAMENT_LINK_LIBRARIES_DIR: ${FILAMENT_LINK_LIBRARIES_DIR}") - -add_library(filament INTERFACE - core/include/shapetypes.h) -target_compile_options(filament INTERFACE -isystem${FILAMENT_INCLUDE_DIR} -isystem${FILAMENT_INCLUDE_DIR}/filament) -target_link_options(filament INTERFACE -L${FILAMENT_LINK_LIBRARIES_DIR}) -target_link_libraries(filament INTERFACE - libbackend.a - libbluevk.a - libdracodec.a - libfilamat.a - libfilameshio.a - libgltfio_core.a - libimage.a - libshaders.a - libuberarchive.a - libviewer.a - libbasis_transcoder.a - libcamutils.a - libfilabridge.a - libfilament.a - libgeometry.a - libibl.a - libimageio.a - libmeshoptimizer.a - libsmol-v.a - libuberzlib.a - libvkshaders.a - libcivetweb.a - libtinyexr.a - libfilaflat.a - libfilament-iblprefilter.a - libgltfio.a - libibl-lite.a - libktxreader.a - libmikktspace.a - libpng.a - libstb.a - libutils.a - libzstd.a - - z - toolchain::toolchain -) -# Include libmatdbg.a for debug builds -if (FILAMENT_BUILD_TYPE STREQUAL "Debug") - target_link_libraries(filament INTERFACE libmatdbg.a) -endif () - -add_library(plugin_filament_view STATIC - filament_view_plugin_c_api.cc - filament_view_plugin.cc - messages.g.cc - - core/scene/serialization/scene_text_deserializer.cc - core/components/derived/transform.cc - core/components/derived/camera.cc - core/components/derived/commonrenderable.cc - core/components/derived/collider.cc - core/components/derived/animation.cc - core/components/derived/light.cc - core/entity/derived/renderable_entityobject.cc - core/systems/base/system.cc - core/systems/ecs.cc - core/systems/derived/filament_system.cc - core/systems/derived/model_system.cc - core/entity/derived/model/model.cc - core/scene/camera/exposure.cc - core/scene/camera/lens_projection.cc - core/scene/camera/projection.cc - core/entity/base/entityobject.cc - core/scene/geometry/ray.cc - core/scene/geometry/size.cc - core/scene/serialization/scene_text_deserializer.cc - core/systems/derived/collision_system.cc - core/systems/derived/debug_lines_system.cc - core/scene/indirect_light/indirect_light.cc - core/systems/derived/indirect_light_system.cc - core/utils/vectorutils.cc - core/utils/hdr_loader.cc - core/systems/derived/light_system.cc - core/scene/material/loader/material_loader.cc - core/scene/material/loader/texture_loader.cc - core/systems/derived/material_system.cc - core/components/derived/material_definitions.cc - core/scene/material/material_parameter.cc - core/scene/material/texture/texture_definitions.cc - core/scene/material/texture/texture_sampler.cc - core/scene/skybox/skybox.cc - core/systems/derived/skybox_system.cc - core/systems/derived/animation_system.cc - core/entity/derived/shapes/baseshape.cc - core/entity/derived/shapes/cube.cc - core/entity/derived/shapes/sphere.cc - core/entity/derived/shapes/plane.cc - core/systems/derived/shape_system.cc - core/utils/deserialize.cc - core/utils/uuidGenerator.cc - core/utils/asserts.cc - core/scene/view_target.cc - core/systems/derived/view_target_system.cc - core/systems/derived/transform_system.cc -) - -target_include_directories(plugin_filament_view PUBLIC - . - include -) - -target_link_libraries(plugin_filament_view PUBLIC - platform_homescreen - plugin_common - plugin_common_curl - filament - flutter - asio - toolchain::toolchain -) - -# -# Filament MVP Example -# -pkg_check_modules(SDL2 IMPORTED_TARGET sdl2) -if (SDL2_FOUND) -if (NOT) - add_executable(filament-mvp test/mvp.cc) - target_link_libraries(filament-mvp PUBLIC - PkgConfig::SDL2 - filament - ${FILAMENT_LINK_LIBRARIES_DIR}/../../../../third_party/spirv-tools/source/opt/libSPIRV-Tools-opt.a - ${FILAMENT_LINK_LIBRARIES_DIR}/../../../../third_party/spirv-cross/tnt/libspirv-cross-msl.a - toolchain::toolchain - ) - add_sanitizers(filament-mvp) -endif () -endif () diff --git a/plugins/filament_view/README.md b/plugins/filament_view/README.md deleted file mode 100644 index c9e5d164..00000000 --- a/plugins/filament_view/README.md +++ /dev/null @@ -1,61 +0,0 @@ -# Filament View - -This plugin is built for use with an AndroidView on the Flutter side. - -## Requirements - -- **System Compatibility:** The target system must support Vulkan -- **Compiler:** Clang - - Note: Filament requires Clang - -## Cloning Filament - -git clone https://github.com/google/filament -b release -git checkout v1.52.3 - -## Building Filament - -Apply patches found here: -https://github.com/meta-flutter/workspace-automation/tree/filament-dev/patches/filament - -_Note: If building for desktop do not apply last patch_ - -Build using these flags: - -``` --DFILAMENT_SUPPORTS_VULKAN=ON --DFILAMENT_ENABLE_LTO=ON --DFILAMENT_SUPPORTS_OPENGL=OFF --DFILAMENT_USE_EXTERNAL_GLES3=OFF --DFILAMENT_SUPPORTS_WAYLAND=ON --DFILAMENT_SUPPORTS_X11=OFF --DFILAMENT_SUPPORTS_XCB=OFF --DFILAMENT_SUPPORTS_EGL_ON_LINUX=OFF --DFILAMENT_SKIP_SDL2=ON --DFILAMENT_SKIP_SAMPLES=ON --DFILAMENT_USE_SWIFTSHADER=OFF --DBUILD_SHARED_LIBS=OFF --DCMAKE_STAGING_PREFIX=/mnt/raid10/filament/out/debug/usr -``` - -Make the install target to stage the required folders. - - ninja -C . install - -Set ivi-homescreen variables to subfolders of the staged install: - - -DFILAMENT_INCLUDE_DIR=/mnt/raid10/filament/out/debug/include - -DFILAMENT_LINK_LIBRARIES_DIR=/mnt/raid10/filament/out/debug/lib/x86_64 - -In above case the staged install is set to: - - /mnt/raid10/filament/out/debug/usr - -## Notes - -Playx3d-scene needs conversion of assets for running on Vulkan+Linux: - -``` -cd filament/cmake-build-debug-clang -./tools/matc/matc --api vulkan -o /home/joel/workspace-automation/app/playx-3d-scene/example/build/flutter_assets/assets/materials/textured_pbr.filamat ../samples/materials/groundShadow.mat -``` \ No newline at end of file diff --git a/plugins/filament_view/core/components/base/component.h b/plugins/filament_view/core/components/base/component.h deleted file mode 100644 index b7e9026d..00000000 --- a/plugins/filament_view/core/components/base/component.h +++ /dev/null @@ -1,57 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include - -#include -#include - -namespace plugin_filament_view { -class EntityObject; -} - -namespace plugin_filament_view { - -class Component : public IdentifiableType { - friend class EntityObject; - - public: - [[nodiscard]] inline const EntityObject* getOwner() const { return entityOwner_; } - - [[nodiscard]] virtual const std::type_info& getType() const { return typeid(*this); } - - virtual void debugPrint(const std::string& tabPrefix) const = 0; - - [[nodiscard]] virtual Component* Clone() const = 0; - - virtual ~Component() = default; - - protected: - explicit Component(std::string name) - : name_(std::move(name)), - entityOwner_(nullptr) {} - - private: - /// @deprecated Instead use getTypeName() - std::string name_; - - public: - EntityObject* entityOwner_ = nullptr; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/animation.cc b/plugins/filament_view/core/components/derived/animation.cc deleted file mode 100644 index ab36f6aa..00000000 --- a/plugins/filament_view/core/components/derived/animation.cc +++ /dev/null @@ -1,238 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "animation.h" - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Animation::Animation(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)) { - Deserialize::DecodeParameterWithDefault(kAutoPlay, &m_bAutoPlay, params, false); - Deserialize::DecodeParameterWithDefault(kIndex, &m_nCurrentPlayingIndex, params, 0); - - Deserialize::DecodeParameterWithDefault(kLoop, &m_bLoop, params, true); - - Deserialize::DecodeParameterWithDefault( - kResetToTPoseOnReset, &m_bResetToTPoseOnReset, params, false - ); - - double speed; - Deserialize::DecodeParameterWithDefault(kPlaybackSpeed, &speed, params, 1.0f); - - m_fPlaybackSpeedScalar = static_cast(speed); - - Deserialize::DecodeParameterWithDefault( - kNotifyOfAnimationEvents, &m_bNotifyOfAnimationEvents, params, false - ); - - m_bPaused = false; -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::update(const double deltaTime) { - if (m_poAnimator == nullptr || m_bPaused) { - return; - } - - if (m_nCurrentPlayingIndex < 0 && !m_queAnimationQueue.empty()) { - // Dequeue the next animation if the current one is finished - m_nCurrentPlayingIndex = m_queAnimationQueue.front(); - m_queAnimationQueue.pop(); - m_fTimeSinceStart = 0.0f; - - if (m_bNotifyOfAnimationEvents) { - const auto animationSystem = ECSManager::GetInstance()->getSystem( - "Animation::update" - ); - animationSystem->NotifyOfAnimationEvent( - getOwner()->getGuid(), eAnimationStarted, std::to_string(m_nCurrentPlayingIndex) - ); - } - } - - if (m_nCurrentPlayingIndex < 0) { - return; - } - - m_fTimeSinceStart += static_cast(deltaTime) * m_fPlaybackSpeedScalar; - - m_poAnimator->applyAnimation(static_cast(m_nCurrentPlayingIndex), m_fTimeSinceStart); - m_poAnimator->updateBoneMatrices(); - - const auto currentAnimDuration = m_poAnimator->getAnimationDuration( - static_cast(m_nCurrentPlayingIndex) - ); - if (m_fTimeSinceStart > currentAnimDuration) { - if (m_bNotifyOfAnimationEvents) { - // send message here to dart - const auto animationSystem = ECSManager::GetInstance()->getSystem( - "Animation::update" - ); - - animationSystem->NotifyOfAnimationEvent( - getOwner()->getGuid(), eAnimationEnded, std::to_string(m_nCurrentPlayingIndex) - ); - } - - // check queue - - // check loop - if (m_bLoop) { - m_fTimeSinceStart -= currentAnimDuration; - - if (m_bNotifyOfAnimationEvents) { - // send message here to dart - const auto animationSystem = ECSManager::GetInstance()->getSystem( - "Animation::update" - ); - - animationSystem->NotifyOfAnimationEvent( - getOwner()->getGuid(), eAnimationStarted, std::to_string(m_nCurrentPlayingIndex) - ); - } - - } else { - m_fTimeSinceStart = 0.0f; - m_nCurrentPlayingIndex = -1; - - if (!m_queAnimationQueue.empty()) { - m_nCurrentPlayingIndex = m_queAnimationQueue.front(); - m_queAnimationQueue.pop(); - } else if (m_bResetToTPoseOnReset) { - m_poAnimator->resetBoneMatrices(); - } - } - } -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::EnqueueAnimation(const int32_t index) { - if (index < 0) { - return; - } - - if (static_cast(index) >= m_mapAnimationNamesToIndex.size()) { - spdlog::warn("Attempting to vEnqueueAnimation that is greater than total count of " - "animations."); - return; - } - - m_queAnimationQueue.push(index); -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::ClearQueue() { - std::queue emptyQueue; - std::swap(m_queAnimationQueue, emptyQueue); // Efficiently clear the queue -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::setAnimator(filament::gltfio::Animator& animator) { - m_poAnimator = &animator; - - setupAnimationNameMapping(); - - if (m_bAutoPlay) { - PlayAnimation(m_nCurrentPlayingIndex); - } -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::PlayAnimation(int32_t index) { - if (index < 0 || static_cast(index) >= m_mapAnimationNamesToIndex.size()) { - spdlog::warn("Invalid animation index: {}", index); - return; - } - - ClearQueue(); - - m_nCurrentPlayingIndex = index; - m_fTimeSinceStart = 0.0f; -} - -//////////////////////////////////////////////////////////////////////////// -bool Animation::bPlayAnimation(const std::string& szName) { - if (const auto foundIter = m_mapAnimationNamesToIndex.find(szName); - foundIter != m_mapAnimationNamesToIndex.end()) { - PlayAnimation(static_cast(foundIter->second)); - return true; - } - - spdlog::warn("Animation string not found in mapping table {}", szName); - return false; -} - -//////////////////////////////////////////////////////////////////////////// -void Animation::setupAnimationNameMapping() { - if (m_poAnimator) { - const auto count = m_poAnimator->getAnimationCount(); - for (size_t i = 0; i < count; i++) { - m_mapAnimationNamesToIndex.insert( - std::make_pair(std::string(m_poAnimator->getAnimationName(i)), i) - ); - } - } -} - -//////////////////////////////////////////////////////////////////////// -void Animation::debugPrint(const std::string& tabPrefix) const { - spdlog::debug("{}m_nCurrentPlayingIndex: {}", tabPrefix, m_nCurrentPlayingIndex); - spdlog::debug("{}m_bPaused: {}", tabPrefix, m_bPaused); - spdlog::debug("{}m_bAutoPlay: {}", tabPrefix, m_bAutoPlay); - spdlog::debug("{}m_bLoop: {}", tabPrefix, m_bLoop); - spdlog::debug("{}m_bResetToTPoseOnReset: {}", tabPrefix, m_bResetToTPoseOnReset); - spdlog::debug("{}m_fPlaybackSpeedScalar: {}", tabPrefix, m_fPlaybackSpeedScalar); - spdlog::debug("{}m_bNotifyOfAnimationEvents: {}", tabPrefix, m_bNotifyOfAnimationEvents); - spdlog::debug("{}m_fTimeSinceStart: {}", tabPrefix, m_fTimeSinceStart); - - if (m_poAnimator) { - const auto count = m_poAnimator->getAnimationCount(); - spdlog::debug("{}Animation Info: count[{}]", tabPrefix, count); - for (size_t i = 0; i < count; i++) { - spdlog::debug( - "{}Anim at [{}]: Name: '{}', Duration: {}", tabPrefix, i, m_poAnimator->getAnimationName(i), - m_poAnimator->getAnimationDuration(i) - ); - } - } else { - spdlog::debug("{}m_poAnimator is nullptr", tabPrefix); - } - - spdlog::debug("{}m_mapAnimationNamesToIndex:", tabPrefix); - for (const auto& [name, index] : m_mapAnimationNamesToIndex) { - spdlog::debug("{} Name: '{}', Index: {}", tabPrefix, name, index); - } - - spdlog::debug("{}m_queAnimationQueue size: {}", tabPrefix, m_queAnimationQueue.size()); - if (!m_queAnimationQueue.empty()) { - std::queue tempQueue = m_queAnimationQueue; // Copy to iterate - spdlog::debug("{}Queue contents:", tabPrefix); - while (!tempQueue.empty()) { - int32_t index = tempQueue.front(); - tempQueue.pop(); - spdlog::debug("{} Animation Index: {}", tabPrefix, index); - } - } -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/animation.h b/plugins/filament_view/core/components/derived/animation.h deleted file mode 100644 index ee6bb717..00000000 --- a/plugins/filament_view/core/components/derived/animation.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include -#include -#include - -namespace plugin_filament_view { - -class Animation final : public Component { - public: - // Constructor - explicit Animation(const flutter::EncodableMap& params); - - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] inline Component* Clone() const override { return new Animation(*this); } - - void setAnimator(filament::gltfio::Animator& animator); - void PlayAnimation(int32_t index); - [[maybe_unused]] bool bPlayAnimation(const std::string& szName); - - void update(double deltaTime); - - [[nodiscard]] inline float getSpeed() const { return m_fPlaybackSpeedScalar; } - - // Setter for m_fPlaybackSpeedScalar - inline void setSpeed(float playbackSpeedScalar) { - m_fPlaybackSpeedScalar = playbackSpeedScalar; - } - - inline void setPaused(bool paused) { m_bPaused = paused; } - - inline void Pause() { m_bPaused = true; } - - inline void Resume() { m_bPaused = false; } - - // Queue management - void EnqueueAnimation(int32_t index); - void ClearQueue(); - - inline void setLooping(bool enable) { m_bLoop = enable; } - - private: - int32_t m_nCurrentPlayingIndex{}; - bool m_bPaused; - bool m_bAutoPlay{}; - bool m_bLoop{}; - bool m_bResetToTPoseOnReset{}; - float m_fPlaybackSpeedScalar{}; - bool m_bNotifyOfAnimationEvents{}; - - float m_fTimeSinceStart{}; - - filament::gltfio::Animator* m_poAnimator{}; - - // Setup when the animator is set. - std::map m_mapAnimationNamesToIndex; - void setupAnimationNameMapping(); - - std::queue m_queAnimationQueue; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/camera.cc b/plugins/filament_view/core/components/derived/camera.cc deleted file mode 100644 index da54eeeb..00000000 --- a/plugins/filament_view/core/components/derived/camera.cc +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "camera.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -Camera::Camera(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)) { - // Camera (head) - auto exposureParams = Deserialize::DecodeOptionalParameter( - kExposure, params - ); - if (exposureParams.has_value()) { - _exposure = Exposure(exposureParams.value()); - _dirtyExposure = true; - } - - auto projectionParams = Deserialize::DecodeOptionalParameter( - kProjection, params - ); - if (projectionParams.has_value()) { - _projection = Projection(projectionParams.value()); - _dirtyProjection = true; - } - - auto lensParams = Deserialize::DecodeOptionalParameter( - kLensProjection, params - ); - if (lensParams.has_value()) { - _lens = LensProjection(lensParams.value()); - _dirtyProjection = true; - - // reset projection if lens is set - if (_projection.has_value()) { - spdlog::warn( - "LensProjection is set, resetting Projection. LensProjection will be used instead." - ); - _projection.reset(); - } - } - - // _ipd = 0; // leave default in header, currently not supported in Dart - _dirtyEyes = false; - - int64_t tmpViewId = 0; - Deserialize::DecodeParameterWithDefaultInt64(kViewId, &tmpViewId, params, kDefaultViewId); - _viewId = static_cast(tmpViewId); - - Deserialize::DecodeParameterWithDefault(kDollyOffset, &dollyOffset, params, kFloat3Zero); - - Deserialize::DecodeParameterWithDefaultInt64( - kOrbitOriginEntity, &orbitOriginEntity, params, kNullGuid - ); - - Deserialize::DecodeParameterWithDefault( - kOrbitRotation, &orbitRotation, params, VectorUtils::kIdentityQuat - ); - - Deserialize::DecodeParameterWithDefaultInt64(kTargetEntity, &targetEntity, params, kNullGuid); - - const bool hasTargetPos = Deserialize::DecodeParameterWithDefault( - kTargetPoint, &targetPoint, params, VectorUtils::kFloat3Zero - ); - - // Check if target position is set, if so, enable targeting - enableTarget = hasTargetPos || targetEntity != kNullGuid; - -} // Camera - -void Camera::debugPrint(const std::string& tabPrefix) const { - spdlog::debug("{}: Camera {{ viewId: {} }", tabPrefix, _viewId); -} // debugPrint - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/camera.h b/plugins/filament_view/core/components/derived/camera.h deleted file mode 100644 index 64c17b4f..00000000 --- a/plugins/filament_view/core/components/derived/camera.h +++ /dev/null @@ -1,176 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { - -class ViewTarget; - -constexpr size_t kDefaultViewId = 0; -constexpr double kDefaultIPD = 0.064; // Default Inter-Pupillary Distance in meters - -class Camera : public Component { - friend class ViewTarget; - - private: - /// ID of the ViewTarget associated with this camera - size_t _viewId = kDefaultViewId; - - /// NOTE: each setting has a 'dirty' flag to - /// Exposure settings - std::optional _exposure = std::nullopt; - bool _dirtyExposure = false; - /// Projection settings - /// Projection and Lens are mutually exclusive, when one is set, the other is reset. - std::optional _projection = std::nullopt; - /// Lens projection settings - /// Projection and Lens are mutually exclusive, when one is set, the other is reset. - std::optional _lens = std::nullopt; - bool _dirtyProjection = false; - - /// Inter-Pupillary Distance (IPD) in meters. - /// Used in stereoscopic rendering, where the distance between the eyes is set to this value. - /// Default value is 0.064 meters (64 mm), which is a common value for human. - double _ipd = kDefaultIPD; - bool _dirtyEyes = true; - - public: - /* - * Orbit - */ - /// Entity that this camera is orbiting around. - /// If not set, the camera will orbit around its own position. - EntityGUID orbitOriginEntity = kNullGuid; - /// Orbit rotation (azimuth and elevation) around the orbit origin. - filament::math::quatf orbitRotation = VectorUtils::kIdentityQuat; - - /* - * Targeting - */ - /// Controls whether targeting is enabled. - bool enableTarget = false; - /// Entity that this camera is looking at. - EntityGUID targetEntity = kNullGuid; - /// The target position in world space. - /// Used only if targetEntity is equal to [kNullGuid]. - filament::math::float3 targetPoint = VectorUtils::kFloat3Zero; - - /* - * Dolly - */ - /// Offset of the camera (head) from its center (rig) - filament::math::float3 dollyOffset = {0.0f, 0.0f, 0.0f}; - - public: - Camera( - std::optional exposure, - std::optional projection, - std::optional lens, - size_t viewId = kDefaultViewId - ) - : Component(std::string(__FUNCTION__)), - _viewId(viewId), - _exposure(std::move(exposure)), - _dirtyExposure(exposure != std::nullopt), - _projection(std::move(projection)), - _lens(std::move(lens)), - _dirtyProjection(projection != std::nullopt || lens != std::nullopt) { - // check projection and lens are not both set - runtime_assert( - !(_projection.has_value() && _lens.has_value()), - "Projection and LensProjection cannot be set at the same time." - ); - } - - /// Constructs a Camera component from the given parameters. - /// TODO(kerberjg): move to deserializer - explicit Camera(const flutter::EncodableMap& params); - - void debugPrint(const std::string& tabPrefix) const override; - - /* - * Settings - */ - [[nodiscard]] inline const Exposure* getExposure() const { - return _exposure.has_value() ? &_exposure.value() : nullptr; - } - - [[nodiscard]] inline const Projection* getProjection() const { - return _projection.has_value() ? &_projection.value() : nullptr; - } - - [[nodiscard]] inline const LensProjection* getLens() const { - return _lens.has_value() ? &_lens.value() : nullptr; - } - - [[nodiscard]] inline float getIPD() const { return _ipd; } - - inline void setExposure(const Exposure& exposure) { - _exposure = exposure; - _dirtyExposure = true; - } - - inline void setProjection(const Projection& projection) { - _projection = projection; - _lens = std::nullopt; // reset lens if projection is set - _dirtyProjection = true; - } - - inline void setLens(const LensProjection& lens) { - _lens = lens; - _projection = std::nullopt; // reset projection if lens is set - _dirtyProjection = true; - } - - inline void setIPD(float ipd) { - _ipd = ipd; - _dirtyEyes = true; - } - - [[nodiscard]] inline bool isDirtyExposure() const { return _dirtyExposure; } - [[nodiscard]] inline bool isDirtyProjection() const { return _dirtyProjection; } - [[nodiscard]] inline bool isDirtyEyes() const { return _dirtyEyes; } - - [[nodiscard]] inline size_t getViewId() const { return _viewId; } - inline void setViewId(size_t viewId) { _viewId = viewId; } - - [[nodiscard]] Component* Clone() const override { return new Camera(*this); } - - protected: - inline void clearDirtyFlags() { - _dirtyExposure = false; - _dirtyProjection = false; - _dirtyEyes = false; - } - -}; // class Camera - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/collider.cc b/plugins/filament_view/core/components/derived/collider.cc deleted file mode 100644 index 69ef1b53..00000000 --- a/plugins/filament_view/core/components/derived/collider.cc +++ /dev/null @@ -1,257 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "collider.h" - -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Collider::Collider(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)), - m_f3StaticPosition({0}), - m_eShapeType(ShapeType::Cube), - _extentSize({1, 1, 1}) { - // Check if the key exists and if the value is an EncodableMap - if (const auto itCollidableSpecific = params.find(flutter::EncodableValue(kCollider)); - itCollidableSpecific != params.end()) { - try { - const auto collidableSpecificParams = std::get( - itCollidableSpecific->second - ); - - // Deserialize the collision layer, defaulting to 0 - Deserialize::DecodeParameterWithDefaultInt64( - kColliderLayer, &m_nCollisionLayer, collidableSpecificParams, 0 - ); - - // Deserialize the collision mask, defaulting to 0xFFFFFFFFu - Deserialize::DecodeParameterWithDefaultInt64( - kColliderMask, &m_nCollisionMask, collidableSpecificParams, 0xFFFFFFFFu - ); - - // Deserialize the flag for matching attached objects, defaulting to - // 'false' - Deserialize::DecodeParameterWithDefault( - kColliderShouldMatchAttachedObject, &m_bShouldMatchAttachedObject, collidableSpecificParams, - false - ); - - Deserialize::DecodeParameterWithDefault( - kColliderExtents, &_extentSize, params, filament::math::float3(1.0f, 1.0f, 1.0f) - ); - - // Deserialize the static flag, defaulting to 'false' - Deserialize::DecodeParameterWithDefault(kColliderIsStatic, &m_bIsStatic, params, false); - - if (!m_bShouldMatchAttachedObject) { - // Deserialize the shape type, defaulting to some default ShapeType - // (replace ShapeType::Default with your actual default) - Deserialize::DecodeEnumParameterWithDefault( - kColliderShapeType, &m_eShapeType, params, ShapeType::Cube - ); - } - - } catch (const std::bad_variant_access&) { - // Handle the case where the cast to EncodableMap fails - // Log error, throw an exception, or handle gracefully - spdlog::error("Failed to get EncodableMap from collider parameter."); - } - } else { - // Handle the missing or invalid type scenario - spdlog::error("Collider parameter not found or is of incorrect type."); - } - - // if (m_bIsStatic) { - // Deserialize::DecodeParameterWithDefault(kPosition, - // &m_f3StaticPosition, params, - // filament::math::float3(0, 0, 0)); - // } - - // if (!m_bShouldMatchAttachedObject) { - // Deserialize::DecodeParameterWithDefault(kPosition, &_extentSize, - // params, - // filament::math::float3(1, 1, 1)); - // } -} - -//////////////////////////////////////////////////////////////////////////// -void Collider::debugPrint(const std::string& tabPrefix) const { - spdlog::debug(tabPrefix + "Collider Debug Info:"); - - // Log whether the object is static - spdlog::debug(tabPrefix + "Is Static: {}", m_bIsStatic); - - if (m_bIsStatic) { - spdlog::debug( - tabPrefix + "Static Position: x={}, y={}, z={}", m_f3StaticPosition.x, m_f3StaticPosition.y, - m_f3StaticPosition.z - ); - } - - // Log the collision layer and mask - spdlog::debug(tabPrefix + "Collision Layer: {}", m_nCollisionLayer); - spdlog::debug(tabPrefix + "Collision Mask: 0x{:X}", m_nCollisionMask); - - // Log the flag for whether it should match the attached object - spdlog::debug(tabPrefix + "Should Match Attached Object: {}", m_bShouldMatchAttachedObject); - - // Log the shape type (you can modify this to log the enum name if needed) - spdlog::debug( - tabPrefix + "Shape Type: {}", - static_cast(m_eShapeType) - ); // assuming ShapeType is an enum - - // Log the extents size (x, y, z) - spdlog::debug( - tabPrefix + "Extents Size: x={}, y={}, z={}", _extentSize.x, _extentSize.y, _extentSize.z - ); -} - -//////////////////////////////////////////////////////////////////////////// -bool Collider::intersects( - const Ray& ray, - filament::math::float3& hitPosition, - const std::shared_ptr& transform -) const { - if (!enabled) { - return false; - } - - // TODO: implement static colliders - if (m_bIsStatic != false) throw std::runtime_error("Static colliders not implemented yet."); - - // Get AABB coordinates (local space!) - filament::math::float3 center = (m_bIsStatic ? m_f3StaticPosition : _aabb.center); - filament::math::float3 extents = - (m_bShouldMatchAttachedObject ? _aabb.halfExtent * 2 : _extentSize); - const filament::math::float3 rayOrigin = ray.f3GetPosition(); - const filament::math::float3 rayDirection = ray.f3GetDirection(); - - // Transform AABB to global space - // TODO: skip if transform has no parent (local = global) - filament::math::mat4f globalMatrix = transform->getGlobalMatrix(); - center = VectorUtils::transformPositionVector(center, globalMatrix); - extents = VectorUtils::transformScaleVector(extents, globalMatrix); - - bool doesIntersect = false; - switch (m_eShapeType) { - case ShapeType::Sphere: { - // Sphere-ray intersection - float radius = extents.x; // Assuming the x component of extents represents the radius - filament::math::float3 oc = rayOrigin - center; // Vector from ray origin to sphere center - float a = dot(rayDirection, rayDirection); - float b = 2.0f * dot(oc, rayDirection); - float c = dot(oc, oc) - radius * radius; - - if (float discriminant = b * b - 4 * a * c; discriminant > 0) { - if (float t = (-b - sqrt(discriminant)) / (2.0f * a); t > 0) { - hitPosition = rayOrigin + t * rayDirection; - SPDLOG_INFO("Collided with sphere {}", getOwner()->getGuid()); - doesIntersect = true; // Ray hits the sphere - } - } - break; - } - - case ShapeType::Cube: { - // Cube-ray intersection (Axis-Aligned Bounding Box, AABB) - filament::math::float3 minBound = center - extents * 0.5f; - filament::math::float3 maxBound = center + extents * 0.5f; - - float tmin = (minBound.x - rayOrigin.x) / rayDirection.x; - float tmax = (maxBound.x - rayOrigin.x) / rayDirection.x; - if (tmin > tmax) std::swap(tmin, tmax); - - float tymin = (minBound.y - rayOrigin.y) / rayDirection.y; - float tymax = (maxBound.y - rayOrigin.y) / rayDirection.y; - if (tymin > tymax) std::swap(tymin, tymax); - - if (tmin > tymax || tymin > tmax) { - return false; - } - - if (tymin > tmin) tmin = tymin; - if (tymax < tmax) tmax = tymax; - - float tzmin = (minBound.z - rayOrigin.z) / rayDirection.z; - float tzmax = (maxBound.z - rayOrigin.z) / rayDirection.z; - if (tzmin > tzmax) std::swap(tzmin, tzmax); - - if (tmin > tzmax || tzmin > tmax) { - return false; - } - - if (tzmin > tmin) tmin = tzmin; - /*if (tzmax < tmax) - tmax = tzmax;*/ - - if (tmin > 0) { - hitPosition = rayOrigin + tmin * rayDirection; - SPDLOG_INFO("Collided with cube {}", getOwner()->getGuid()); - doesIntersect = true; // Ray hits the cube - } - break; - } - - case ShapeType::Plane: { - // Quad-ray intersection - filament::math::float3 planeNormal = { - 0.0f, 1.0f, 0.0f - }; // Assuming quad is aligned with the Y-axis - if (float denom = dot(rayDirection, planeNormal); fabs(denom) > 1e-6) { - // Check if ray is not parallel to the plane - if (float t = dot(center - rayOrigin, planeNormal) / denom; t >= 0) { - // Compute the intersection point - hitPosition = rayOrigin + t * rayDirection; - - // Check if the intersection point is within the quad bounds - // Assuming the quad is axis-aligned and centered at `center` with - // extents `extents` - if (filament::math::float3 localHit = hitPosition - center; - fabs(localHit.x) <= extents.x * 0.5f && fabs(localHit.z) <= extents.z * 0.5f) { - SPDLOG_INFO("Collided with quad {}", getOwner()->getGuid()); - doesIntersect = true; // Ray hits the quad - } - } - } - break; - } - - // Additional cases like Capsule, etc., can be handled here - default: - spdlog::error("Unknown shape type: {}", static_cast(m_eShapeType)); - break; - } - - // Intersection found - if (doesIntersect) { - spdlog::debug("== INTERSECTION FOUND == ({})", getOwner()->getGuid()); - spdlog::debug("AABB.pos: x={}, y={}, z={} (global)", center.x, center.y, center.z); - spdlog::debug("AABB.size: x={}, y={}, z={} (global)", extents.x, extents.y, extents.z); - return true; - } - - return false; // No intersection -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/collider.h b/plugins/filament_view/core/components/derived/collider.h deleted file mode 100644 index b0a36487..00000000 --- a/plugins/filament_view/core/components/derived/collider.h +++ /dev/null @@ -1,131 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -// At the time of checkin - m_bShouldMatchAttachedObject is expected to be -// true at all times, and the IsStatic is not used in the false sense of -// updating geometry. First pass is only static colliders spawning using data -// from the base transform with on overrides. Expected work TBD for future -// improvements. - -namespace shapes { -class BaseShape; -} // namespace shapes - -class CollisionSystem; - -class Collider : public Component { - friend class CollisionSystem; - - public: - // You can turn collision objects on / off during runtime without removing / - // re-adding from the scene. - bool enabled = true; - /// @brief The name of the event to be triggered on collision. - /// This is used to identify the event in the event system. - /// The default value is "click". - std::string eventName = "click"; - /// Bounding box of the collider - AABB _aabb; - - public: - Collider() - : Component(std::string(__FUNCTION__)) {} - - // TODO: make this a more complete constructor - Collider(const ShapeType& shapeType) - : Component(std::string(__FUNCTION__)), - m_eShapeType(shapeType) {} - - explicit Collider(const flutter::EncodableMap& params); - - // Getters - [[nodiscard]] inline bool getIsStatic() const { return m_bIsStatic; } - [[nodiscard]] inline int64_t getCollisionLayer() const { return m_nCollisionLayer; } - [[nodiscard]] inline int64_t getCollisionMask() const { return m_nCollisionMask; } - [[nodiscard]] inline bool getShouldMatchAttachedObject() const { - return m_bShouldMatchAttachedObject; - } - [[nodiscard]] inline ShapeType getShapeType() const { return m_eShapeType; } - [[nodiscard]] inline filament::math::float3 getExtentsSize() const { return _extentSize; } - - // Setters - inline void setIsStatic(bool value) { m_bIsStatic = value; } - inline void setCollisionLayer(int64_t value) { m_nCollisionLayer = value; } - inline void setCollisionMask(int64_t value) { m_nCollisionMask = value; } - inline void setShouldMatchAttachedObject(bool value) { m_bShouldMatchAttachedObject = value; } - inline void setShapeType(ShapeType value) { m_eShapeType = value; } - inline void setExtentsSize(const filament::math::float3& value) { - if (m_bIsStatic) throw std::runtime_error("Cannot set extents size on static collider"); - _extentSize = value; - } - - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] bool bDoesOverlap(const Collider& other) const; - bool intersects( - const Ray& ray, - ::filament::math::float3& hitPosition, - const std::shared_ptr& transform - ) const; - - [[nodiscard]] inline Component* Clone() const override { - return new Collider(*this); // Copy constructor is called here - } - - private: - // If true, the object is static and won't sync move with its renderable - // object once created in place. - bool m_bIsStatic = false; - // if this isStatic, then we need to copy this on creation - // from transform property - filament::math::float3 m_f3StaticPosition = {0, 0, 0}; - - // Layer for collision filtering - // Not actively used in first iteration, but should be in future. - int64_t m_nCollisionLayer = 0; - int64_t m_nCollisionMask = 0xFFFFFFFF; - - // This works hand in hand with shapeType_, upon initialization if this is - // true it will do its best to match the shape object it was sent in with from - // Native. else it will use shapeType_ and extents; - // - // At the time of implementation, models must do their own shapeType_ usage. - bool m_bShouldMatchAttachedObject = true; - - /// Collider shape type (supported values: Cube) - /// TODO: add support for other shapes - ShapeType m_eShapeType = ShapeType::Cube; // default - filament::math::float3 _extentSize = {1, 1, 1}; // default - - /* - * Setup stuff - */ - /// Collider's child wireframe object - std::shared_ptr _wireframe; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/commonrenderable.cc b/plugins/filament_view/core/components/derived/commonrenderable.cc deleted file mode 100644 index ba78bc05..00000000 --- a/plugins/filament_view/core/components/derived/commonrenderable.cc +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "commonrenderable.h" - -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -CommonRenderable::CommonRenderable(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)), - m_bCullingOfObjectEnabled(true), - m_bReceiveShadows(false), - m_bCastShadows(false) { - Deserialize::DecodeParameterWithDefault( - kCullingEnabled, &m_bCullingOfObjectEnabled, params, true - ); - Deserialize::DecodeParameterWithDefault(kReceiveShadows, &m_bReceiveShadows, params, false); - Deserialize::DecodeParameterWithDefault(kCastShadows, &m_bCastShadows, params, false); -} - -//////////////////////////////////////////////////////////////////////////// -void CommonRenderable::debugPrint(const std::string& tabPrefix) const { - spdlog::debug(tabPrefix + "Culling Enabled: {}", m_bCullingOfObjectEnabled); - spdlog::debug(tabPrefix + "Receive Shadows: {}", m_bReceiveShadows); - spdlog::debug(tabPrefix + "Cast Shadows: {}", m_bCastShadows); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/commonrenderable.h b/plugins/filament_view/core/components/derived/commonrenderable.h deleted file mode 100644 index e273e60b..00000000 --- a/plugins/filament_view/core/components/derived/commonrenderable.h +++ /dev/null @@ -1,67 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -namespace plugin_filament_view { - -using FilamentRenderableInstance = utils::EntityInstance; - -class CommonRenderable : public Component { - public: - // Constructor - CommonRenderable() - : Component(std::string(__FUNCTION__)), - m_bCullingOfObjectEnabled(true), - m_bReceiveShadows(true), - m_bCastShadows(true) {} - explicit CommonRenderable(const flutter::EncodableMap& params); - - FilamentRenderableInstance _fInstance; - - // Getters - [[nodiscard]] inline bool IsCullingOfObjectEnabled() const { return m_bCullingOfObjectEnabled; } - - [[nodiscard]] inline bool IsReceiveShadowsEnabled() const { return m_bReceiveShadows; } - - [[nodiscard]] inline bool IsCastShadowsEnabled() const { return m_bCastShadows; } - - // Setters - inline void setCullingOfObjectEnabled(bool enabled) { m_bCullingOfObjectEnabled = enabled; } - - inline void setReceiveShadows(bool enabled) { m_bReceiveShadows = enabled; } - - inline void setCastShadows(bool enabled) { m_bCastShadows = enabled; } - - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] inline Component* Clone() const override { - /// TODO: fix this - // return new CommonRenderable(*this); // Copy constructor is called here - return nullptr; - } - - private: - bool m_bCullingOfObjectEnabled; - bool m_bReceiveShadows; - bool m_bCastShadows; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/light.cc b/plugins/filament_view/core/components/derived/light.cc deleted file mode 100644 index 1deb68f7..00000000 --- a/plugins/filament_view/core/components/derived/light.cc +++ /dev/null @@ -1,115 +0,0 @@ -#include "light.h" - -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Light::Light(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)), - color(1.0f, 1.0f, 1.0f), - m_Type(filament::LightManager::Type::DIRECTIONAL), - m_fColorTemperature(6500.0f), - m_fIntensity(100000.0f), - m_f3Position(0.0f, 0.0f, 0.0f), - m_f3Direction(0.0f, -1.0f, 0.0f), - m_bCastLight(true), - m_bCastShadows(true), - m_fFalloffRadius(100.0f), - m_fSpotLightConeInner(0.0f), - m_fSpotLightConeOuter(0.0f), - m_fSunAngularRadius(0.0f), - m_fSunHaloSize(0.0f), - m_fSunHaloFalloff(0.0f) { - if (const auto it = params.find(flutter::EncodableValue(kType)); it != params.end()) { - if (const auto& snd = it->second; std::holds_alternative(snd)) { - m_Type = textToLightType(std::get(snd)); - } - } - - Deserialize::DecodeColor3WithDefault(kColor, &color, params, filament::math::float3(1, 1, 1)); - Deserialize::DecodeParameterWithDefault(kColorTemperature, &m_fColorTemperature, params, 0.0f); - Deserialize::DecodeParameterWithDefault(kIntensity, &m_fIntensity, params, 100000.0f); - Deserialize::DecodeParameterWithDefault( - kPosition, &m_f3Position, params, filament::math::float3(0, 0, 0) - ); - Deserialize::DecodeParameterWithDefault( - kDirection, &m_f3Direction, params, filament::math::float3(0, -1, 0) - ); - Deserialize::DecodeParameterWithDefault(kCastLight, &m_bCastLight, params, true); - Deserialize::DecodeParameterWithDefault(kCastShadows, &m_bCastShadows, params, true); - Deserialize::DecodeParameterWithDefault(kFalloffRadius, &m_fFalloffRadius, params, 0.0f); - Deserialize::DecodeParameterWithDefault( - kSpotLightConeInner, &m_fSpotLightConeInner, params, 0.0f - ); - Deserialize::DecodeParameterWithDefault( - kSpotLightConeOuter, &m_fSpotLightConeOuter, params, 0.0f - ); - Deserialize::DecodeParameterWithDefault(kSunAngularRadius, &m_fSunAngularRadius, params, 0.0f); - Deserialize::DecodeParameterWithDefault(kSunHaloSize, &m_fSunHaloSize, params, 0.0f); - Deserialize::DecodeParameterWithDefault(kSunHaloFalloff, &m_fSunHaloFalloff, params, 0.0f); -} - -//////////////////////////////////////////////////////////////////////////// -void Light::debugPrint(const std::string& tabPrefix) const { - spdlog::debug(tabPrefix + "Type: {}", static_cast(m_Type)); - spdlog::debug(tabPrefix + "Color: r={}, g={}, b={}", color.r, color.g, color.b); - spdlog::debug(tabPrefix + "Color Temperature: {}", m_fColorTemperature); - spdlog::debug(tabPrefix + "Intensity: {}", m_fIntensity); - spdlog::debug( - tabPrefix + "Position: x={}, y={}, z={}", m_f3Position.x, m_f3Position.y, m_f3Position.z - ); - spdlog::debug( - tabPrefix + "Direction: x={}, y={}, z={}", m_f3Direction.x, m_f3Direction.y, m_f3Direction.z - ); - spdlog::debug(tabPrefix + "Casts Light: {}", m_bCastLight); - spdlog::debug(tabPrefix + "Casts Shadows: {}", m_bCastShadows); - spdlog::debug(tabPrefix + "Falloff Radius: {}", m_fFalloffRadius); - spdlog::debug(tabPrefix + "Spotlight Cone Inner: {}", m_fSpotLightConeInner); - spdlog::debug(tabPrefix + "Spotlight Cone Outer: {}", m_fSpotLightConeOuter); - spdlog::debug(tabPrefix + "Sun Angular Radius: {}", m_fSunAngularRadius); - spdlog::debug(tabPrefix + "Sun Halo Size: {}", m_fSunHaloSize); - spdlog::debug(tabPrefix + "Sun Halo Falloff: {}", m_fSunHaloFalloff); -} - -//////////////////////////////////////////////////////////////////////////// -filament::LightManager::Type Light::textToLightType(const std::string& type) { - static constexpr std::pair typeMap[] = { - {"SUN", filament::LightManager::Type::SUN}, - {"DIRECTIONAL", filament::LightManager::Type::DIRECTIONAL}, - {"POINT", filament::LightManager::Type::POINT}, - {"FOCUSED_SPOT", filament::LightManager::Type::FOCUSED_SPOT}, - {"SPOT", filament::LightManager::Type::SPOT}, - }; - - for (const auto& [text, lightType] : typeMap) { - if (type == text) { - return lightType; - } - } - - return filament::LightManager::Type::DIRECTIONAL; // Default fallback -} - -//////////////////////////////////////////////////////////////////////////// -const char* Light::lightTypeToText(const filament::LightManager::Type type) { - static constexpr std::pair typeMap[] = { - {filament::LightManager::Type::SUN, "SUN"}, - {filament::LightManager::Type::DIRECTIONAL, "DIRECTIONAL"}, - {filament::LightManager::Type::POINT, "POINT"}, - {filament::LightManager::Type::FOCUSED_SPOT, "FOCUSED_SPOT"}, - {filament::LightManager::Type::SPOT, "SPOT"}, - }; - - for (const auto& [lightType, text] : typeMap) { - if (type == lightType) { - return text; - } - } - - return "DIRECTIONAL"; // Default fallback -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/light.h b/plugins/filament_view/core/components/derived/light.h deleted file mode 100644 index 470c99a8..00000000 --- a/plugins/filament_view/core/components/derived/light.h +++ /dev/null @@ -1,111 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -namespace plugin_filament_view { - -class Light : public Component { - friend class LightSystem; - - public: - filament::math::float3 color; - - // Constructors - Light() - : Component(std::string(__FUNCTION__)), - m_Type(filament::LightManager::Type::DIRECTIONAL), - m_fColorTemperature(0.0f), - m_fIntensity(100000.0f), - m_f3Position(0.0f, 1.0f, 0.0f), - m_f3Direction(0.0f, -1.0f, 0.0f), - m_bCastLight(true), - m_bCastShadows(true), - m_fFalloffRadius(1000.0f), - m_fSpotLightConeInner(0.0f), - m_fSpotLightConeOuter(0.0f), - m_fSunAngularRadius(0.0f), - m_fSunHaloSize(0.0f), - m_fSunHaloFalloff(0.0f) {} - - explicit Light(const flutter::EncodableMap& params); - - [[nodiscard]] inline filament::LightManager::Type getLightType() const { return m_Type; } - [[nodiscard]] inline float getColorTemperature() const { return m_fColorTemperature; } - [[nodiscard]] inline float getIntensity() const { return m_fIntensity; } - [[nodiscard]] inline const filament::math::float3& getPosition() const { return m_f3Position; } - [[nodiscard]] inline const filament::math::float3& getDirection() const { - return m_f3Direction; - } - [[nodiscard]] inline bool getCastLight() const { return m_bCastLight; } - [[nodiscard]] inline bool getCastShadows() const { return m_bCastShadows; } - [[nodiscard]] inline float getFalloffRadius() const { return m_fFalloffRadius; } - [[nodiscard]] inline float getSpotLightConeInner() const { return m_fSpotLightConeInner; } - [[nodiscard]] inline float getSpotLightConeOuter() const { return m_fSpotLightConeOuter; } - [[nodiscard]] inline float getSunAngularRadius() const { return m_fSunAngularRadius; } - [[nodiscard]] inline float getSunHaloSize() const { return m_fSunHaloSize; } - [[nodiscard]] inline float getSunHaloFalloff() const { return m_fSunHaloFalloff; } - - inline void setLightType(filament::LightManager::Type type) { m_Type = type; } - inline void setColorTemperature(float temperature) { m_fColorTemperature = temperature; } - inline void setIntensity(float intensity) { m_fIntensity = intensity; } - inline void setPosition(const filament::math::float3& position) { m_f3Position = position; } - inline void setDirection(const filament::math::float3& direction) { m_f3Direction = direction; } - inline void setCastLight(bool castLight) { m_bCastLight = castLight; } - inline void setCastShadows(bool castShadows) { m_bCastShadows = castShadows; } - inline void setFalloffRadius(float radius) { m_fFalloffRadius = radius; } - inline void setSpotLightConeInner(float angle) { m_fSpotLightConeInner = angle; } - inline void setSpotLightConeOuter(float angle) { m_fSpotLightConeOuter = angle; } - inline void setSunAngularRadius(float radius) { m_fSunAngularRadius = radius; } - inline void setSunHaloSize(float size) { m_fSunHaloSize = size; } - inline void setSunHaloFalloff(float falloff) { m_fSunHaloFalloff = falloff; } - - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] inline Component* Clone() const override { return new Light(*this); } - - static ::filament::LightManager::Type textToLightType(const std::string& type); - - static const char* lightTypeToText(::filament::LightManager::Type type); - - private: - FilamentEntity m_poFilamentEntityLight; - - filament::LightManager::Type m_Type; - float m_fColorTemperature; - float m_fIntensity; - - // TODO: refactor to use Transform - filament::math::float3 m_f3Position; - filament::math::float3 m_f3Direction; - - bool m_bCastLight; - bool m_bCastShadows; - float m_fFalloffRadius; - float m_fSpotLightConeInner; - float m_fSpotLightConeOuter; - float m_fSunAngularRadius; - float m_fSunHaloSize; - float m_fSunHaloFalloff; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/material_definitions.cc b/plugins/filament_view/core/components/derived/material_definitions.cc deleted file mode 100644 index c3edb002..00000000 --- a/plugins/filament_view/core/components/derived/material_definitions.cc +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "material_definitions.h" - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -using MinFilter = filament::TextureSampler::MinFilter; -using MagFilter = filament::TextureSampler::MagFilter; - -/////////////////////////////////////////////////////////////////////////////////////////////////// -MaterialDefinitions::MaterialDefinitions(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)) { - SPDLOG_TRACE("++{}", __FUNCTION__); - const auto flutterAssetPath = ECSManager::GetInstance()->getConfigValue(kAssetPath); - - // TODO: rewrite this without the for - for (const auto& [fst, snd] : params) { - auto key = std::get(fst); - SPDLOG_TRACE("Material Param {}", key); - - if (snd.IsNull() && key != "url") { - SPDLOG_WARN("Material Param Second mapping is null {}", key); - continue; - } - - if (snd.IsNull() && key == "url") { - SPDLOG_TRACE("Material Param URL mapping is null {}", key); - continue; - } - - if (key == "assetPath" && std::holds_alternative(snd)) { - assetPath_ = std::get(snd); - } else if (key == "url" && std::holds_alternative(snd)) { - url_ = std::get(snd); - } else if (key == "parameters" && std::holds_alternative(snd)) { - auto list = std::get(snd); - for (const auto& it_ : list) { - auto parameter = MaterialParameter::Deserialize( - flutterAssetPath, std::get(it_) - ); - parameters_.insert(std::pair(parameter->szGetParameterName(), std::move(parameter))); - } - } else if (!snd.IsNull()) { - spdlog::debug("[Material] Unhandled Parameter {}", key.c_str()); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -MaterialDefinitions::~MaterialDefinitions() { - for (auto& [fst, snd] : parameters_) { - snd.reset(); - } - parameters_.clear(); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void MaterialDefinitions::debugPrint(const std::string& tabPrefix) const { - spdlog::debug(tabPrefix + "++++++++ (MaterialDefinitions) ++++++++"); - if (!assetPath_.empty()) { - spdlog::debug(tabPrefix + "assetPath: [{}]", assetPath_); - - const auto flutterAssetPath = ECSManager::GetInstance()->getConfigValue(kAssetPath - ); - - const std::filesystem::path asset_folder(flutterAssetPath); - spdlog::debug( - tabPrefix + "asset_path {} valid", exists(asset_folder / assetPath_) ? "is" : "is not" - ); - } - if (!url_.empty()) { - spdlog::debug(tabPrefix + "url: [{}]", url_); - } - spdlog::debug(tabPrefix + "ParamCount: [{}]", parameters_.size()); - - for (const auto& [fst, param] : parameters_) { - if (param != nullptr) param->debugPrint(std::string(tabPrefix + tabPrefix).c_str()); - } - - spdlog::debug("-------- (MaterialDefinitions) --------"); -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -std::string MaterialDefinitions::szGetMaterialDefinitionLookupName() const { - if (!assetPath_.empty()) { - return assetPath_; - } - if (!url_.empty()) { - return url_; - } - return "Unknown"; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -std::vector MaterialDefinitions::getTextureMaterialParameters() const { - std::vector returnVector; - - for (const auto& [fst, snd] : parameters_) { - // Check if the type is TEXTURE - if (snd->type_ == MaterialParameter::MaterialType::TEXTURE) { - returnVector.push_back(snd.get()); - } - } - - return returnVector; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void MaterialDefinitions::ApplyMaterialParameterToInstance( - filament::MaterialInstance* materialInstance, - const MaterialParameter* param, - const TextureMap& loadedTextures -) { - const std::string paramName = param->szGetParameterName(); - const char* szParamName = paramName.c_str(); - - const float* fVec = param->fVecValue_.has_value() ? param->fVecValue_.value().data() : nullptr; - - switch (param->type_) { - case MaterialParameter::MaterialType::COLOR: { - const auto* f4 = reinterpret_cast(fVec); - materialInstance->setParameter(szParamName, filament::RgbaType::LINEAR, *f4); - } break; - - case MaterialParameter::MaterialType::INT: { - materialInstance->setParameter(szParamName, param->iValue_.value()); - } break; - - case MaterialParameter::MaterialType::FLOAT: { - materialInstance->setParameter(szParamName, param->fValue_.value()); - } break; - - case MaterialParameter::MaterialType::FLOAT2: { - const auto* f2 = reinterpret_cast(fVec); - materialInstance->setParameter(szParamName, *f2); - } break; - - case MaterialParameter::MaterialType::FLOAT3: { - const auto* f3 = reinterpret_cast(fVec); - materialInstance->setParameter(szParamName, *f3); - } break; - - case MaterialParameter::MaterialType::FLOAT4: { - const auto* f4 = reinterpret_cast(fVec); - materialInstance->setParameter(szParamName, *f4); - } break; - - case MaterialParameter::MaterialType::TEXTURE: { - // make sure we have the texture: - const auto foundResource = loadedTextures.find(param->getTextureValueAssetPath()); - - if (foundResource == loadedTextures.end()) { - // log and continue - spdlog::warn("Got to a case where a texture was not loaded before trying to " - "apply to a material."); - return; - } - - // sampler will be on 'our' deserialized - // texturedefinitions->texture_sampler - const auto textureSampler = param->getTextureSampler(); - - filament::TextureSampler sampler(MinFilter::LINEAR, MagFilter::LINEAR); - - if (textureSampler != nullptr) { - // SPDLOG_INFO("Overloading filtering options with set param - // values"); - sampler.setMinFilter(textureSampler->getMinFilter()); - sampler.setMagFilter(textureSampler->getMagFilter()); - sampler.setAnisotropy(static_cast(textureSampler->getAnisotropy())); - - // Currently leaving this commented out, but this is for 3d - // textures, which are not currently expected to be loaded - // as time of writing. - // sampler.setWrapModeR(textureSampler->getWrapModeR()); - - sampler.setWrapModeS(textureSampler->getWrapModeS()); - sampler.setWrapModeT(textureSampler->getWrapModeT()); - } - - if (!foundResource->second.getData().has_value()) { - spdlog::warn("Got to a case where a texture resource data was not loaded " - "before trying to " - "apply to a material."); - return; - } - - const auto texture = foundResource->second.getData().value(); - materialInstance->setParameter(szParamName, texture, sampler); - } break; - - default: { - SPDLOG_WARN("Type template not setup yet, see {}", __FUNCTION__); - } break; - } -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -void MaterialDefinitions::setMaterialInstancePropertiesFromMyPropertyMap( - const filament::Material* materialResult, - filament::MaterialInstance* materialInstance, - const TextureMap& loadedTextures -) const { - const auto count = materialResult->getParameterCount(); - std::vector parameters(count); - - if (const auto actual = materialResult->getParameters(parameters.data(), count); - count != actual || actual != parameters.size()) { - spdlog::warn("Count of parameters from the material instance and loaded material do " - "not match; doesn't technically need to, but not ideal and could leave " - "to undefined results."); - } - - for (const auto& param : parameters) { - if (param.name) { - SPDLOG_TRACE("[Material] name: {}, type: {}", param.name, static_cast(param.type)); - - const auto& iter = parameters_.find(param.name); - if (iter == parameters_.end() || iter->second == nullptr) { - // This can get pretty spammy, but good if needing to debug further into - // parameter values. - SPDLOG_INFO("No default parameter value available for {} {}", __FUNCTION__, param.name); - continue; - } - SPDLOG_TRACE("Setting material param {}", param.name); - - ApplyMaterialParameterToInstance(materialInstance, iter->second.get(), loadedTextures); - } - } -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/material_definitions.h b/plugins/filament_view/core/components/derived/material_definitions.h deleted file mode 100644 index 20734d89..00000000 --- a/plugins/filament_view/core/components/derived/material_definitions.h +++ /dev/null @@ -1,112 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include -#include -#include -#include -#include - -using TextureMap = std::map>; - -namespace plugin_filament_view { - -class MaterialDefinitions : public Component { - public: - explicit MaterialDefinitions(const flutter::EncodableMap& params); - - MaterialDefinitions(const MaterialDefinitions& other) - : Component(std::string(__FUNCTION__)), - assetPath_(other.assetPath_), - url_(other.url_) { - for (const auto& [key, value] : other.parameters_) { - if (value) { - parameters_.emplace(key, value->clone()); - } - } - } - - MaterialDefinitions( - const std::string& assetPath, - const std::map>& parameters - ) - : Component(std::string(__FUNCTION__)), - assetPath_(assetPath), - parameters_(parameters) {} - - ~MaterialDefinitions() override; - - static void ApplyMaterialParameterToInstance( - filament::MaterialInstance* materialInstance, - const MaterialParameter* param, - const TextureMap& loadedTextures - ); - - void setMaterialInstancePropertiesFromMyPropertyMap( - const ::filament::Material* materialResult, - filament::MaterialInstance* materialInstance, - const TextureMap& loadedTextures - ) const; - - // this will either get the assetPath or the url, priority of assetPath - // looking for which is valid. Used to see if we have this loaded in cache. - [[nodiscard]] std::string szGetMaterialDefinitionLookupName() const; - - // This will go through each of the parameters and return only the - // texture_(definitions) so the material manager can load what's not already - // loaded. - [[nodiscard]] std::vector getTextureMaterialParameters() const; - - [[nodiscard]] inline std::string szGetMaterialAssetPath() const { return assetPath_; } - [[nodiscard]] inline std::string szGetMaterialURLPath() const { return url_; } - - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] inline Component* Clone() const override { - return new MaterialDefinitions(*this); // Copy constructor is called here - } - - private: - std::string assetPath_; - std::string url_; - std::map> parameters_; -}; - -const std::shared_ptr kDefaultBaseColor = std::make_unique( - "baseColor", - MaterialParameter::MaterialType::COLOR, - filament::math::float4(1.0f, 1.0f, 1.0f, 1.0f) -); -const std::shared_ptr kDefaultRoughness = - std::make_unique("roughness", MaterialParameter::MaterialType::FLOAT, 0.5f); -const std::shared_ptr kDefaultMetallic = - std::make_unique("metallic", MaterialParameter::MaterialType::FLOAT, 0.0f); - -const std::map> kDefaultMaterialParameters{ - {"baseColor", kDefaultBaseColor}, - {"roughness", kDefaultRoughness}, - {"metallic", kDefaultMetallic}, -}; - -const MaterialDefinitions kDefaultMaterial = - MaterialDefinitions("assets/materials/lit.filamat", kDefaultMaterialParameters); - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/transform.cc b/plugins/filament_view/core/components/derived/transform.cc deleted file mode 100644 index 437f6fc0..00000000 --- a/plugins/filament_view/core/components/derived/transform.cc +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "transform.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Transform::Transform(const flutter::EncodableMap& params) - : Component(std::string(__FUNCTION__)), - _globalVectors({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - local({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - global({kMat4fIdentity}) { - spdlog::trace("Transform::Transform"); - Deserialize::DecodeParameterWithDefault(kPosition, &(local.position), params, kFloat3Zero); - Deserialize::DecodeParameterWithDefault(kScale, &(local.scale), params, kFloat3One); - Deserialize::DecodeParameterWithDefault(kRotation, &(local.rotation), params, kQuatfIdentity); - - Deserialize::DecodeParameterWithDefaultInt64(kParentId, &_parentId, params, kNullGuid); - if (_parentId != kNullGuid) { - _isParentDirty = true; - } -} - -//////////////////////////////////////////////////////////////////////////// -void Transform::debugPrint(const std::string& tabPrefix) const { - spdlog::debug(tabPrefix + "Local transform:"); - spdlog::debug(tabPrefix + "ParentId: {}", _parentId); - spdlog::debug( - tabPrefix + "Pos: x={}, y={}, z={}", local.position.x, local.position.y, local.position.z - ); - spdlog::debug(tabPrefix + "Scl: x={}, y={}, z={}", local.scale.x, local.scale.y, local.scale.z); - spdlog::debug( - tabPrefix + "Rot: x={}, y={}, z={} w={}", local.rotation.x, local.rotation.y, local.rotation.z, - local.rotation.w - ); -} - -void Transform::setTransform(const filament::math::mat4f& localMatrix) { - filament::gltfio::decomposeMatrix(localMatrix, &local.position, &local.rotation, &local.scale); - _isDirty = true; -} - -void Transform::DecomposeGlobalMatrix() { - // Decompose the global matrix into position, scale, and rotation - filament::gltfio::decomposeMatrix( - global.matrix, &_globalVectors.position, &_globalVectors.rotation, &_globalVectors.scale - ); - _isGlobalDirty = false; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/components/derived/transform.h b/plugins/filament_view/core/components/derived/transform.h deleted file mode 100644 index 43671097..00000000 --- a/plugins/filament_view/core/components/derived/transform.h +++ /dev/null @@ -1,303 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class TransformSystem; - -/// @brief TransformVectorData is a struct that holds position/scale/rotation -/// data. -struct TransformVectorData { - union { - filament::math::float3 position; - float position_data[3]; - struct { - float posX = 0; - float posY = 0; - float posZ = 0; - }; - }; - - union { - filament::math::float3 scale; - float scale_data[3]; - struct { - float scaleX = 1; - float scaleY = 1; - float scaleZ = 1; - }; - }; - - union { - filament::math::quatf rotation; - float rotation_data[4]; - struct { - float rotX = 0; - float rotY = 0; - float rotZ = 0; - float rotW = 1; - }; - }; -}; - -/// @brief TransformMatrixData is a struct that holds a computed transform -/// matrix's data. -struct TransformMatrixData { - union { - filament::math::mat4f matrix; - float matrix_data[16]; - }; -}; - -static constexpr filament::math::float3 kFloat3Zero = {0, 0, 0}; -static constexpr filament::math::float3 kFloat3One = {1, 1, 1}; -static constexpr filament::math::quatf kQuatfIdentity = {0, 0, 0, 1}; -static constexpr filament::math::mat4f kMat4fIdentity = filament::math::mat4f(); - -class Transform : public Component { - friend class TransformSystem; - - private: - /// @brief _isDirty is a flag that indicates if the transform has been - /// modified. If true, the transform will be updated by the [TransformSystem] - /// on this frame and the flag will be set to false. It's set to true whenever - /// the transform is modified. - bool _isDirty = true; - EntityGUID _parentId = kNullGuid; - bool _isParentDirty = false; - - TransformVectorData _globalVectors; - bool _isGlobalDirty = true; - - public: - TransformVectorData local; - /// @brief Computed transform matrix in world space. - /// TODO: does this have to be stored as value? Evaluate storing pointer only - TransformMatrixData global; - FilamentTransformInstance _fInstance; - - Transform() - : Component(std::string(__FUNCTION__)), - _globalVectors({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - local({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - global({kMat4fIdentity}) {} - - explicit Transform( - const filament::math::float3& position, - const filament::math::float3& scale, - const filament::math::quatf& rotation - ) - : Component(std::string(__FUNCTION__)), - _globalVectors({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - local({{position}, {scale}, {rotation}}), - global({kMat4fIdentity}) {} - - explicit Transform(const TransformVectorData& localTransform) - : Component(std::string(__FUNCTION__)), - _globalVectors({{kFloat3Zero}, {kFloat3One}, {kQuatfIdentity}}), - local(localTransform), - global({kMat4fIdentity}) {} - - // explicit Transform(const filament::math::float3& position, - // const filament::math::float3& scale) - // : Component(std::string(__FUNCTION__)), - // local({position, scale, kQuatfIdentity}), - // global({kMat4fIdentity}) {} - - // explicit Transform(const filament::math::float3& position) - // : Component(std::string(__FUNCTION__)), - // local({position, kFloat3One, kQuatfIdentity}), - // global({kMat4fIdentity}) {} - - explicit Transform(const flutter::EncodableMap& params); - - /* - * Local - */ - // getters - [[nodiscard]] inline EntityGUID getParentId() const { return _parentId; } - - [[nodiscard]] inline const filament::math::float3& getPosition() const { - return local.position; - } - - [[nodiscard]] inline const filament::math::float3& getScale() const { return local.scale; } - - [[nodiscard]] inline const filament::math::quatf& getRotation() const { return local.rotation; } - - // Setters - inline void setPosition(const filament::math::float3& position) { - local.position = position; - _isDirty = true; - } - - inline void setScale(const filament::math::float3& scale) { - // assert positive scale - /// TODO: if interested in supporting e.g. negative scalings and shear - /// should look at Graphics Gems II §VII.1. - runtime_assert(scale.x >= 0 && scale.y >= 0 && scale.z >= 0, "Scale must be positive"); - - local.scale = scale; - _isDirty = true; - } - - inline void setRotation(const filament::math::quatf& rotation) { - local.rotation = rotation; - _isDirty = true; - } - - /// @brief Sets the rotation of the transform to look at a target point. - /// @param target World-space target position to look at. - /// @param up Up vector to use for the look-at operation. Defaults to Y+. - inline void lookAt(const filament::math::float3& globalTarget) { - setRotation(VectorUtils::lookAt(getGlobalPosition(), globalTarget)); - } - - /// Sets all transform values at once. All params are optional (nullptr) - inline void setTransform( - const filament::math::float3* position = nullptr, - const filament::math::float3* scale = nullptr, - const filament::math::quatf* rotation = nullptr - ) { - if (position) { - local.position = *position; - } - - if (scale) { - local.scale = *scale; - } - - if (rotation) { - local.rotation = *rotation; - } - - _isDirty = true; - } - - inline void setTransform( - const filament::math::float3& position, - const filament::math::float3& scale, - const filament::math::quatf& rotation - ) { - local.position = position; - local.scale = scale; - local.rotation = rotation; - _isDirty = true; - } - - void setTransform(const filament::math::mat4f& localMatrix); - - inline void setParent(EntityGUID parentId) { - _parentId = parentId; - _isParentDirty = true; - } - - inline void setDirty(bool dirty) { _isDirty = dirty; } - - inline void setParentDirty(bool dirty) { _isParentDirty = dirty; } - - /* - * Global - */ - // getters - [[nodiscard]] inline bool IsDirty() const { return _isDirty; } - - [[nodiscard]] inline bool IsParentDirty() const { return _isParentDirty; } - - /// @returns The transform matrix in world space. - [[nodiscard]] inline const filament::math::mat4f& getGlobalMatrix() const { - return global.matrix; - } - - /// @returns the XYZ position vector in global/world space. - /// @note SLOW OPERATION! If the global matrix is dirty, it will be decomposed - /// into position, scale, and rotation. - /// Use this only on as-needed basis. - [[nodiscard]] const filament::math::float3& getGlobalPosition() { - if (_isGlobalDirty) DecomposeGlobalMatrix(); - - return _globalVectors.position; - } - - /// @returns the XYZ scale vector in global/world space. - /// @note SLOW OPERATION! If the global matrix is dirty, it will be decomposed - /// into position, scale, and rotation. - /// Use this only on as-needed basis. - [[nodiscard]] const filament::math::float3& getGlobalScale() { - if (_isGlobalDirty) DecomposeGlobalMatrix(); - - return _globalVectors.scale; - } - - /// @returns the rotation quaternion in global/world space. - /// @note SLOW OPERATION! If the global matrix is dirty, it will be decomposed - /// into position, scale, and rotation. - /// Use this only on as-needed basis. - [[nodiscard]] const filament::math::quatf& getGlobalRotation() { - if (_isGlobalDirty) DecomposeGlobalMatrix(); - - return _globalVectors.rotation; - } - - // Setters - - // TODO - // void setGlobalMatrix(const filament::math::mat4f& matrix) { - // throw std::runtime_error("Not implemented"); - // } - - // TODO - // void setGlobalPosition(const filament::math::float3& position) { - - // } - - // TODO - // void setGlobalScale(const filament::math::float3& scale) { - - // } - - // TODO - // void setGlobalRotation(const filament::math::quatf& rotation) { - - // } - - /* - * Utils - */ - void debugPrint(const std::string& tabPrefix) const override; - - [[nodiscard]] inline Component* Clone() const override { return new Transform(*this); } - - private: - /// Decomposes the global matrix into position, scale, and rotation. - /// @note SLOW OPERATION! Use this only when the global matrix is dirty. - /// This is called automatically when accessing the global position, scale, or rotation. - void DecomposeGlobalMatrix(); -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/base/entityobject.cc b/plugins/filament_view/core/entity/base/entityobject.cc deleted file mode 100644 index 371715e9..00000000 --- a/plugins/filament_view/core/entity/base/entityobject.cc +++ /dev/null @@ -1,161 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "entityobject.h" - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -EntityObject::EntityObject() - : guid_(generateUUID()), - name(std::string()) {} - -EntityObject::EntityObject(std::string name) - : guid_(generateUUID()), - name(std::move(name)) {} - -EntityObject::EntityObject(EntityGUID guid) - : guid_(guid), - name(std::string()) {} - -EntityObject::EntityObject(std::string name, EntityGUID guid) - : guid_(guid), - name(std::move(name)) {} - -EntityObject::EntityObject(const EntityDescriptor& descriptor) - : guid_(descriptor.guid), - name(descriptor.name) {} - -EntityObject::EntityObject(const flutter::EncodableMap& params) - : guid_(kNullGuid), - name(std::string()) { - deserializeFrom(params); - assert(guid_ != kNullGuid); -} - -EntityDescriptor EntityObject::DeserializeNameAndGuid(const flutter::EncodableMap& params) { - EntityDescriptor descriptor; - - // Deserialize name - if (const auto itName = params.find(flutter::EncodableValue(kName)); - itName != params.end() && !itName->second.IsNull()) { - // they're requesting entity be named what they want. - - if (auto requestedName = std::get(itName->second); !requestedName.empty()) { - descriptor.name = requestedName; - } - } - - // Deserialize guid - Deserialize::DecodeParameterWithDefaultInt64(kGuid, &descriptor.guid, params, kNullGuid); - - if (descriptor.guid == kNullGuid) { - spdlog::warn("Failed to deserialize guid, generating new one"); - descriptor.guid = generateUUID(); - } - - return descriptor; -} - -void EntityObject::deserializeFrom(const flutter::EncodableMap& params) { - // Deserialize name and guid - auto descriptor = DeserializeNameAndGuid(params); - name = descriptor.name; - guid_ = descriptor.guid; -} - -///////////////////////////////////////////////////////////////////////////////////////// -void EntityObject::debugPrintComponents() const { - if (!isInitialized()) { - spdlog::debug("EntityObject '{}'({}) is not initialized", name, guid_); - return; - } - - std::vector componentNames; - // get list of component pointers - const auto components = ecs->getComponentsOfEntity(guid_); - for (const auto& component : components) { - if (component == nullptr) { - spdlog::warn("Component is null"); - continue; - } - componentNames.push_back(component->getTypeName()); - } - - std::ostringstream oss; - for (size_t i = 0; i < componentNames.size(); ++i) { - if (i != 0) oss << ", "; - oss << componentNames[i]; - } - spdlog::debug( - "EntityObject '{}'({}) has {} components: {}", name, guid_, componentNames.size(), oss.str() - ); -} - -void EntityObject::debugPrint() const { - spdlog::debug("EntityObject '{}'({}), {}initialized", name, guid_, isInitialized() ? "" : "not "); - debugPrintComponents(); -} - -std::shared_ptr EntityObject::getComponent(size_t staticTypeID) const { - return ecs->getComponent(guid_, staticTypeID); -} - -[[nodiscard]] bool EntityObject::hasComponent(size_t staticTypeID) const { - return ecs->hasComponent(guid_, staticTypeID); -} - -void EntityObject::ShallowCopyComponentToOther(size_t staticTypeID, EntityObject& other) const { - checkInitialized(); - const auto component = ecs->getComponent(guid_, staticTypeID); - if (component == nullptr) { - spdlog::warn("Unable to clone component of {}", staticTypeID); - return; - } - - ecs->addComponent(other.guid_, std::shared_ptr(component->Clone())); -} - -void EntityObject::addComponent(size_t staticTypeID, const std::shared_ptr& component) { - if (isInitialized()) { - ecs->addComponent(guid_, component); - } else { - // batch the component to be added after initialization - _tmpComponents[staticTypeID] = component; - } -} - -void EntityObject::onAddComponent(const std::shared_ptr& component) { - checkInitialized(); - component->entityOwner_ = this; -} - -///////////////////////////////////////////////////////////////////////////////////////// -void EntityObject::onInitialize() { - checkInitialized(); - // add all components that were added before initialization - for (const auto& [staticTypeID, component] : _tmpComponents) { - ecs->addComponent(guid_, component); - } - _tmpComponents.clear(); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/base/entityobject.h b/plugins/filament_view/core/entity/base/entityobject.h deleted file mode 100644 index 160876a6..00000000 --- a/plugins/filament_view/core/entity/base/entityobject.h +++ /dev/null @@ -1,210 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include - -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { -class MaterialParameter; - -// TODO: refactor to `EntityGUID` to `EntityId` -/// @brief EntityGUID is a type alias for the GUID of an entity (currently an -/// int64_t). -using EntityGUID = int64_t; - -/// @brief kNullGuid is a constant that represents a null GUID. -constexpr EntityGUID kNullGuid = 0; - -/// @brief EntityDescriptor is a struct that holds the name and guid of an -/// entity. -struct EntityDescriptor { - std::string name = ""; - EntityGUID guid = kNullGuid; -}; - -class ECSManager; - -/// @brief EntityObject is the base class for all entities in the system. -class EntityObject : public std::enable_shared_from_this { - friend class ECSManager; - // TODO: do we need to expose these? - friend class CollisionSystem; - friend class MaterialSystem; - friend class ModelSystem; - friend class ShapeSystem; - friend class AnimationSystem; - friend class LightSystem; - friend class SceneTextDeserializer; - friend class TransformSystem; - - protected: - smarter_raw_ptr ecs = nullptr; - /// Temporary storage for components that are being added to the entity - /// before it's initialized within ECS. - /// After the entity is initialized, these components are moved to the ECS' - /// memory and the temporary storage is cleared. - std::map> _tmpComponents; - - /// GUID of the entity. - /// This is used for identifying the entity, and must be unique. - /// Also used as a key in the entity object locator system. - EntityGUID guid_; - - public: - FilamentEntity _fEntity; - - /// Name of the entity. - /// This is used only for debugging and logging purposes. - /// It is not used for identifying the entity, and does not need to be unique. - std::string name; - - // Overloading the == operator to compare based on guid_ - bool operator==(const EntityObject& other) const { return guid_ == other.guid_; } - - [[nodiscard]] inline bool isInitialized() const { return _isInitialized; } - - /// @brief Checks if the entity is initialized. Throws an exception if not. - /// @throws std::runtime_error if the entity is not initialized. - void checkInitialized() const { - // TODO: mutex? - - if (!_isInitialized) { - throw std::runtime_error( - // fmt::format("[{}] EntityObject ({}) is not initialized", - // __FUNCTION__, guid_)); - "EntityObject is not initialized" - ); - } - } - - // TODO: remove this, change guid to const and expose as public - [[nodiscard]] EntityGUID getGuid() const { return guid_; } - - EntityObject(const EntityObject&) = delete; - EntityObject& operator=(const EntityObject&) = delete; - - virtual void debugPrint() const; - - /// @brief Constructor for EntityObject. Generates a GUID and has an empty - /// name. - explicit EntityObject(); - /// @brief Constructor for EntityObject with a name. Generates a unique GUID. - explicit EntityObject(std::string name); - /// @brief Constructor for EntityObject with GUID. Name is empty. - explicit EntityObject(EntityGUID guid); - /// @brief Constructor for EntityObject with a name and GUID. - EntityObject(std::string name, EntityGUID guid); - /// @brief Constructor for EntityObject based on an EntityDescriptor, - /// containing a name and GUID. - explicit EntityObject(const EntityDescriptor& descriptor); - /// @brief Constructor for EntityObject based on an EncodableMap. Deserializes - /// the name and GUID. - explicit EntityObject(const flutter::EncodableMap& params); - - virtual ~EntityObject() = default; - - /// Called immediately after the entity is registered in the ECSManager. - /// NOTE: this is a good place to initialize components and children. - virtual void onInitialize(); - /// Called immediately before the entity is unregistered in the ECSManager. - /// NOTE: it doesn't need to deallocate components or children, the ECSManager - /// will do that. - virtual void onDestroy() {}; - - public: - /// @brief Adds a component to the entity. - /// If called before the entity is initialized, the component is batched - /// and added to the entity after initialization. - template inline void addComponent(const T& component) { - addComponent(Component::StaticGetTypeID(), std::make_shared(component)); - } - - /// Called by [ECSManager] when a component is added to the entity. - /// This is called after the entity is initialized. - /// If a component is added before the entity is initialized, this will be - /// called after the entity is initialized. - virtual void onAddComponent(const std::shared_ptr& component); - - template [[nodiscard]] inline std::shared_ptr getComponent() const { - return std::dynamic_pointer_cast(getComponent(Component::StaticGetTypeID())); - } - - template [[nodiscard]] inline bool hasComponent() const { - return hasComponent(Component::StaticGetTypeID()); - } - - void debugPrintComponents() const; - - // finds the size_t staticTypeID in the component list - // and creates a copy and assigns to the others list - void ShallowCopyComponentToOther(size_t staticTypeID, EntityObject& other) const; - - static EntityDescriptor DeserializeNameAndGuid(const flutter::EncodableMap& params); - - /// @brief Deserializes the entity from a map of parameters. - virtual void deserializeFrom(const flutter::EncodableMap& params); - - private: - std::mutex _initMutex; - bool _isInitialized = false; - - /// Called by ECSManager when the entity is registered. - void initialize(ECSManager* ecsManager) { - std::lock_guard lock(_initMutex); - - // Make sure it's not already initialized - assert(_isInitialized == false); - - ecs = ecsManager; - _isInitialized = true; - onInitialize(); - } - - /// Called by ECSManager when the entity is unregistered. - void uninitialize() { - std::lock_guard lock(_initMutex); - - // Make sure it's not already uninitialized - assert(_isInitialized == true); - - onDestroy(); - ecs = nullptr; - _isInitialized = false; - } - - void addComponent(TypeID staticTypeID, const std::shared_ptr& component); - - /// @brief Pass in the Component::StaticGetTypeID() - /// @returns component if valid, nullptr if not found. - [[nodiscard]] std::shared_ptr getComponent(TypeID staticTypeID) const; - - /// @brief Checks if the entity has a component of the given type. - /// @param staticTypeID The static type ID of the component -> - /// [Component::StaticGetTypeID()] - /// @returns true if the entity has the component, false otherwise. - [[nodiscard]] bool hasComponent(TypeID staticTypeID) const; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/model/model.cc b/plugins/filament_view/core/entity/derived/model/model.cc deleted file mode 100644 index a642a896..00000000 --- a/plugins/filament_view/core/entity/derived/model/model.cc +++ /dev/null @@ -1,201 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "model.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -const char* modelInstancingModeToString(ModelInstancingMode mode) { - switch (mode) { - case ModelInstancingMode::none: - return "none"; - case ModelInstancingMode::primary: - return "primary"; - case ModelInstancingMode::secondary: - return "secondary"; - default: - return "unknown"; - } -} - -//////////////////////////////////////////////////////////////////////////// -Model::Model() - : RenderableEntityObject(), - assetPath_(), - m_poAsset(nullptr), - m_poAssetInstance(nullptr) {} - -void Model::deserializeFrom(const flutter::EncodableMap& params) { - RenderableEntityObject::deserializeFrom(params); - - // assetPath_ - assetPath_ = Deserialize::DecodeParameter(kAssetPath, params); - - // is_glb - bool is_glb = Deserialize::DecodeParameter(kIsGlb, params); - runtime_assert(is_glb, "Model::deserializeFrom - is_glb must be true for Model"); - - // _instancingMode - Deserialize::DecodeEnumParameterWithDefault( - kModelInstancingMode, &_instancingMode, params, ModelInstancingMode::none - ); - - spdlog::trace( - "Model({}), instanceMode: {}", assetPath_, modelInstancingModeToString(_instancingMode) - ); - - // Animation (optional) - spdlog::trace("Making Animation..."); - if (Deserialize::HasKey(params, kAnimation)) { - // they're requesting an animation on this object. Make one. - addComponent(Animation(params)); - } else { - spdlog::trace("This entity params has no animation"); - } -} - -//////////////////////////////////////////////////////////////////////////// -std::shared_ptr Model::Deserialize(const flutter::EncodableMap& params) { - std::shared_ptr toReturn = std::make_shared(); - toReturn->deserializeFrom(params); - - return toReturn; -} - -//////////////////////////////////////////////////////////////////////////// -void Model::debugPrint() const { debugPrintComponents(); } - -AABB Model::getAABB() const { - AABB aabb; - filament::Aabb rawBox; - - if (m_poAsset != nullptr) { - rawBox = m_poAsset->getBoundingBox(); - } else if (m_poAssetInstance != nullptr) { - rawBox = m_poAssetInstance->getBoundingBox(); - } else { - spdlog::warn("Model::getAABB - asset and asset instance are null"); - } - - aabb.set(rawBox.min, rawBox.max); - return aabb; -} - -//////////////////////////////////////////////////////////////////////////// -void Model::ChangeMaterialDefinitions( - const flutter::EncodableMap& params, - const TextureMap& /*loadedTextures*/ -) { - // if we have a materialdefinitions component, we need to remove it - // and remake / add a new one. - ecs->removeComponent(guid_); - - // If you want to inspect the params coming in. - /*for (const auto& [fst, snd] : params) { - auto key = std::get(fst); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - }*/ - - auto materialDefinitions = std::make_shared(params); - ecs->addComponent(guid_, std::move(materialDefinitions)); - - m_poMaterialInstance.reset(); - - // then tell material system to load us the correct way once - // we're deserialized. - LoadMaterialDefinitionsToMaterialInstance(); - - if (m_poMaterialInstance.getStatus() != Status::Success) { - spdlog::error("Unable to load material definition to instance, bailing out."); - return; - } - - // now, reload / rebuild the material? - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "BaseShape::ChangeMaterialDefinitions" - ); - - // If your entity has multiple primitives, you’ll need to call - // setMaterialInstanceAt for each primitive you want to update. - auto& renderManager = filamentSystem->getFilamentEngine()->getRenderableManager(); - - if (getAsset()) { - const utils::Slice listOfRenderables{ - getAsset()->getRenderableEntities(), getAsset()->getRenderableEntityCount() - }; - - // Note this will apply to EVERYTHING currently. You might want a custom - // type functionality. - for (const auto entity : listOfRenderables) { - const auto ri = renderManager.getInstance(entity); - - // I dont know about primitive index being non zero if our tree has - // multiple nodes getting from the asset. - renderManager.setMaterialInstanceAt(ri, 0, *m_poMaterialInstance.getData()); - } - } else if (getAssetInstance()) { - const FilamentEntity* instanceEntities = getAssetInstance()->getEntities(); - const size_t instanceEntityCount = getAssetInstance()->getEntityCount(); - - for (size_t i = 0; i < instanceEntityCount; i++) { - // Check if this entity has a Renderable component - if (const FilamentEntity entity = instanceEntities[i]; renderManager.hasComponent(entity)) { - const auto ri = renderManager.getInstance(entity); - - // A Renderable can have multiple primitives (submeshes) - const size_t submeshCount = renderManager.getPrimitiveCount(ri); - for (size_t sm = 0; sm < submeshCount; sm++) { - // Give the submesh our new material instance - renderManager.setMaterialInstanceAt(ri, sm, *m_poMaterialInstance.getData()); - } - } - } - } -} - -//////////////////////////////////////////////////////////////////////////// -void Model::ChangeMaterialInstanceProperty( - const MaterialParameter* materialParam, - const TextureMap& loadedTextures -) { - if (m_poMaterialInstance.getStatus() != Status::Success) { - spdlog::error("No material definition set for model, set one first that's not the " - "uber shader."); - return; - } - - const auto data = m_poMaterialInstance.getData().value(); - - const auto matDefs = getComponent(); - if (matDefs == nullptr) { - return; - } - - MaterialDefinitions::ApplyMaterialParameterToInstance(data, materialParam, loadedTextures); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/model/model.h b/plugins/filament_view/core/entity/derived/model/model.h deleted file mode 100644 index 92cb4500..00000000 --- a/plugins/filament_view/core/entity/derived/model/model.h +++ /dev/null @@ -1,107 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -enum class ModelInstancingMode { - none = 0, - primary = 1, - secondary = 2, -}; - -const char* modelInstancingModeToString(ModelInstancingMode mode); - -class Model : public RenderableEntityObject { - friend class ModelSystem; - - public: - Model(); - ~Model() override = default; - - /// @brief Static deserializer - calls the constructor and deserializeFrom - /// under the hood - static std::shared_ptr Deserialize(const flutter::EncodableMap& params); - - // Disallow copy and assign. - Model(const Model&) = delete; - Model& operator=(const Model&) = delete; - - void setAsset(filament::gltfio::FilamentAsset* poAsset) { m_poAsset = poAsset; } - - void setAssetInstance(filament::gltfio::FilamentInstance* poAssetInstance) { - m_poAssetInstance = poAssetInstance; - } - - [[nodiscard]] filament::gltfio::FilamentAsset* getAsset() const { return m_poAsset; } - - [[nodiscard]] filament::gltfio::FilamentInstance* getAssetInstance() const { - return m_poAssetInstance; - } - - [[nodiscard]] std::shared_ptr getTransform() const { - return getComponent(); - } - [[nodiscard]] std::shared_ptr getCommonRenderable() const { - return getComponent(); - } - - [[nodiscard]] std::string getAssetPath() const { return assetPath_; } - - /// @returns model's instancing mode - [[nodiscard]] ModelInstancingMode getInstancingMode() const { return _instancingMode; } - - /// Returns whether the model is in the scene - [[nodiscard]] bool isInScene() const { return m_isInScene; } - - [[nodiscard]] virtual AABB getAABB() const override; - - protected: - std::string assetPath_; - - filament::gltfio::FilamentAsset* m_poAsset; - filament::gltfio::FilamentInstance* m_poAssetInstance; - std::map _childrenEntities; - - ModelInstancingMode _instancingMode = ModelInstancingMode::none; - /// Whether it's been inserted into the scene - bool m_isInScene = false; - - void debugPrint() const override; - - virtual void deserializeFrom(const flutter::EncodableMap& params) override; - - /// TODO: move to CommonRenderable - void ChangeMaterialDefinitions( - const flutter::EncodableMap& /*params*/, - const TextureMap& /*loadedTextures*/ - ) override; - void ChangeMaterialInstanceProperty( - const MaterialParameter* /*materialParam*/, - const TextureMap& /*loadedTextures*/ - ) override; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/renderable_entityobject.cc b/plugins/filament_view/core/entity/derived/renderable_entityobject.cc deleted file mode 100644 index ff7b99fb..00000000 --- a/plugins/filament_view/core/entity/derived/renderable_entityobject.cc +++ /dev/null @@ -1,113 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "renderable_entityobject.h" -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -////////////////////////////////////////////////////////////////////////////////////////// -void RenderableEntityObject::deserializeFrom(const flutter::EncodableMap& params) { - EntityObject::deserializeFrom(params); - - // Transform (required) - spdlog::trace("Making Transform..."); - addComponent(Transform(params)); - - // CommonRenderable (required) - spdlog::trace("Making CommonRenderable..."); - addComponent(CommonRenderable(params)); - - // Collider (optional) - spdlog::trace("Making Collider..."); - if (const auto it = params.find(flutter::EncodableValue(kCollider)); - it != params.end() && !it->second.IsNull()) { - addComponent(Collider(params)); - } else { - spdlog::trace(" This entity params has no collider"); - } -} // namespace plugin_filament_view - -void RenderableEntityObject::onInitialize() { - // Initialize the base class - EntityObject::onInitialize(); - - // Make sure it has a Transform component - const auto transform = getComponent(); - if (!transform) { - addComponent(Transform()); // init with defaults - } - - // Make sure it has a CommonRenderable component - const auto renderable = getComponent(); - if (!renderable) { - addComponent(CommonRenderable()); // init with defaults - } -} - -//////////////////////////////////////////////////////////////////////////// -void RenderableEntityObject::LoadMaterialDefinitionsToMaterialInstance() { - checkInitialized(); - const auto materialSystem = ecs->getSystem( - "RenderableEntityObject::BuildRenderable" - ); - - // this will also set all the default values of the material instance from - // the material param list - - const auto materialDefinitions = getComponent(); - if (materialDefinitions != nullptr) { - m_poMaterialInstance = materialSystem->getMaterialInstance( - dynamic_cast(materialDefinitions.get()) - ); - } else { - spdlog::error("MaterialDefinitions is null."); - } - - if (m_poMaterialInstance.getStatus() != Status::Success) { - spdlog::error("Failed to get material instance."); - } -} - -AABB RenderableEntityObject::getAABB() const { - // Get renderable component - const auto renderable = getComponent(); - runtime_assert(!!renderable, "Missing CommonRenderable component"); - runtime_assert( - !!renderable->_fInstance, - fmt::format("CommonRenderable not initialized (is {})", renderable->_fInstance.asValue()) - ); - - // Get the FilamentSystem, engine and rcm - const auto filamentSystem = ecs->getSystem("RenderableEntityObject::getAABB"); - runtime_assert(!!filamentSystem, "FilamentSystem not initialized"); - const auto& engine = filamentSystem->getFilamentEngine(); - const auto& rcm = engine->getRenderableManager(); - - auto box = rcm.getAxisAlignedBoundingBox(renderable->_fInstance); - spdlog::trace( - "[{}] Entity({}) has AABB.scale: x={}, y={}, z={}", __FUNCTION__, guid_, box.halfExtent.x * 2, - box.halfExtent.y * 2, box.halfExtent.z * 2 - ); - - return box; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/renderable_entityobject.h b/plugins/filament_view/core/entity/derived/renderable_entityobject.h deleted file mode 100644 index bebc67a6..00000000 --- a/plugins/filament_view/core/entity/derived/renderable_entityobject.h +++ /dev/null @@ -1,104 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class MaterialSystem; -class ModelSystem; - -/// TODO: remove this and refactor specific methods into the Renderable -/// component (CoI, come on) - -// Renderable Entity Objects are intended to have material settings on them -// where NonRenderable EntityObjects do not. Its expected on play Renderable's -// have the ability to show up in the scene as models/shapes/objects -// where NonRenderables are more data without a physical representation -// NonRenderables are great for items like 'Global Light', Camera, hidden -// collision -class RenderableEntityObject : public EntityObject { - friend class MaterialSystem; - friend class ModelSystem; - - public: - RenderableEntityObject() - : EntityObject() {} - explicit RenderableEntityObject(const flutter::EncodableMap& params) - : EntityObject(params) {} - - explicit RenderableEntityObject(const std::string& name) - : EntityObject(name) {} - - explicit RenderableEntityObject(const EntityGUID guid) - : EntityObject(guid) {} - explicit RenderableEntityObject(const std::string& name, const EntityGUID guid) - : EntityObject(name, guid) {} - - virtual void debugPrint() const override {}; - - void onInitialize() override; - - /* - * Deserialization - */ - virtual void deserializeFrom(const flutter::EncodableMap& params) override; - - // These are expected to have Material instances in base class after we go - // from Uber shader to on models. For now these are - // not implemented on Models, but are on BaseShapes. - - // This is a heavy lift function as it will recreate / load a material - // if it doesn't exist and reset everything from scratch. - virtual void ChangeMaterialDefinitions( - const flutter::EncodableMap& /* params */, - const TextureMap& /* loadedTextures */ - ) {}; - virtual void ChangeMaterialInstanceProperty( - const MaterialParameter* /* materialParam */, - const TextureMap& /* loadedTextures */ - ) {}; - - /// material to be used for the renderable - instantiated from material - /// definition Only after a run time request to change has been made. This - /// should probably be on the entity level as renderable would use this in - /// future as well. - Resource m_poMaterialInstance = - Resource::Error("Unset"); - - void LoadMaterialDefinitionsToMaterialInstance(); - - public: - /// TODO: use those in the addCollidable rewrite - /// @returns The AABB of the entity - [[nodiscard]] virtual AABB getAABB() const; - - /// The default implementation just returns a sphere with the max radius - /// covering the AABB - /// @returns The radius of the bounding sphere - [[nodiscard]] inline BoundingSphere getBoundingSphere() const { - return BoundingSphere(getAABB()); - } -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/shapes/baseshape.cc b/plugins/filament_view/core/entity/derived/shapes/baseshape.cc deleted file mode 100644 index 72886562..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/baseshape.cc +++ /dev/null @@ -1,309 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "baseshape.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view::shapes { - -using filament::Aabb; -using filament::IndexBuffer; -using filament::RenderableManager; -using filament::VertexAttribute; -using filament::VertexBuffer; -using filament::math::float3; -using filament::math::mat3f; -using filament::math::mat4f; -using filament::math::packSnorm16; -using filament::math::short4; - -//////////////////////////////////////////////////////////////////////////// - -void BaseShape::deserializeFrom(const flutter::EncodableMap& params) { - RenderableEntityObject::deserializeFrom(params); - - // shapeType - Deserialize::DecodeEnumParameterWithDefault(kShapeType, &type_, params, ShapeType::Unset); - - // normal - Deserialize::DecodeParameterWithDefault(kNormal, &m_f3Normal, params, float3(0, 0, 0)); - - // doubleSided - m_bDoubleSided = Deserialize::DecodeParameterWithDefault(kDoubleSided, params, false); - - // MaterialDefinitions (optional) - if (Deserialize::HasKey(params, kMaterial)) { - auto matdefParams = std::get( - params.find(flutter::EncodableValue(kMaterial))->second - ); - addComponent(MaterialDefinitions(matdefParams)); - } else { - spdlog::debug("This entity params has no material definitions"); - } -} - -void BaseShape::onInitialize() { - RenderableEntityObject::onInitialize(); - - // Make sure it has a MaterialDefinitions component - const auto materialDefinitions = getComponent(); - if (!materialDefinitions) { - spdlog::warn("BaseShape({}) has no material, adding default material", guid_); - addComponent(kDefaultMaterial); // init with defaults - } -} - -//////////////////////////////////////////////////////////////////////////// -BaseShape::~BaseShape() { - RemoveEntityFromScene(); - DestroyBuffers(); -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::DestroyBuffers() { - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "BaseShape::DestroyBuffers" - ); - const auto filamentEngine = filamentSystem->getFilamentEngine(); - - if (m_poMaterialInstance.getStatus() == Status::Success - && m_poMaterialInstance.getData() != nullptr) { - filamentEngine->destroy(m_poMaterialInstance.getData().value()); - m_poMaterialInstance = Resource::Error("Unset"); - } - - if (m_poVertexBuffer) { - filamentEngine->destroy(m_poVertexBuffer); - m_poVertexBuffer = nullptr; - } - if (m_poIndexBuffer) { - filamentEngine->destroy(m_poIndexBuffer); - m_poIndexBuffer = nullptr; - } -} - -//////////////////////////////////////////////////////////////////////////// -// Unique that we don't want to copy all components, as shapes can have -// colliders, which would make a cascading collider chain -// NOTE: We also don't copy material definitions. (Purposefully) -void BaseShape::CloneToOther(BaseShape& other) const { - other.m_f3Normal = m_f3Normal; - other.m_bDoubleSided = m_bDoubleSided; - other.m_bIsWireframe = m_bIsWireframe; - other.type_ = type_; - other.m_bHasTexturedMaterial = m_bHasTexturedMaterial; - - // and now components. - this->ShallowCopyComponentToOther(Component::StaticGetTypeID(), other); - this->ShallowCopyComponentToOther(Component::StaticGetTypeID(), other); - - const std::shared_ptr transformPtr = ecs->getComponent(guid_); - - const std::shared_ptr commonRenderablePtr = ecs->getComponent( - guid_ - ); - - /// TODO: ecs->addComponent -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::BuildRenderable(filament::Engine* engine_) { - checkInitialized(); - // material_manager can and will be null for now on wireframe creation. - - filament::math::float3 aabb; - switch (type_) { - case ShapeType::Cube: - case ShapeType::Sphere: - aabb = {0.5f, 0.5f, 0.5f}; // NOTE: faces forward by default - break; - case ShapeType::Plane: - aabb = {0.5f, 0.5f, 0.005f}; // NOTE: faces sideways by default - break; - default: - aabb = {0, 0, 0}; - spdlog::error("Unknown shape type: {}", static_cast(type_)); - break; - } - - spdlog::trace("[{}] Building shape '{}'({})", __FUNCTION__, name, getGuid()); - - const auto transform = getComponent(); -#if SPDLOG_LEVEL == trace -// transform->debugPrint(" "); -#endif - - spdlog::trace("[{}] AABB.scale: x={}, y={}, z={}", __FUNCTION__, aabb.x, aabb.y, aabb.z); - - const auto renderable = getComponent(); - - if (m_bIsWireframe) { - // We might want to have a specific Material for wireframes in the future. - // m_poMaterialInstance = - // material_manager->getMaterialInstance(m_poMaterialDefinitions->get()); - RenderableManager::Builder(1) - .boundingBox({{}, aabb}) // center, halfExtent - //.material(0, m_poMaterialInstance.getData().value()) - .geometry(0, RenderableManager::PrimitiveType::LINES, m_poVertexBuffer, m_poIndexBuffer) - .culling(renderable->IsCullingOfObjectEnabled()) - .receiveShadows(false) - .castShadows(false) - .build(*engine_, _fEntity); - } else { - LoadMaterialDefinitionsToMaterialInstance(); - - RenderableManager::Builder(1) - .boundingBox({{}, aabb}) - .material(0, m_poMaterialInstance.getData().value()) - .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, m_poVertexBuffer, m_poIndexBuffer) - .culling(renderable->IsCullingOfObjectEnabled()) - .receiveShadows(renderable->IsReceiveShadowsEnabled()) - .castShadows(renderable->IsCastShadowsEnabled()) - .build(*engine_, _fEntity); - } - - transform->_fInstance = engine_->getTransformManager().getInstance(_fEntity); - renderable->_fInstance = engine_->getRenderableManager().getInstance(_fEntity); - - // Get parent entity id - const auto parentId = transform->getParentId(); - - const auto transformSystem = ecs->getSystem("BaseShape::BuildRenderable"); - if (parentId != kNullGuid) { - // Get the parent entity object - auto parentEntity = ecs->getEntity(parentId); - - transform->setParent(parentEntity->getGuid()); - } - - /// NOTE: why is this needed? if this is not called the collider doesn't work, - /// even though it's visible - transformSystem->applyTransform(guid_, true); - - // TODO , need 'its done building callback to delete internal arrays data' - // - note the calls are async built, but doesn't seem to be a method internal - // to filament for when the building is complete. Further R&D is needed. -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::RemoveEntityFromScene() const { - if (!_fEntity) { - spdlog::warn("Attempt to remove uninitialized shape from scene {}", __FUNCTION__); - return; - } - - const auto filamentSystem = ecs->getSystem("BaseShape::RemoveEntityFromScene"); - - filamentSystem->getFilamentScene()->remove(_fEntity); -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::AddEntityToScene() const { - if (!_fEntity) { - spdlog::warn("Attempt to add uninitialized shape to scene {}", __FUNCTION__); - return; - } - - const auto filamentSystem = ecs->getSystem("BaseShape::RemoveEntityFromScene"); - filamentSystem->getFilamentScene()->addEntity(_fEntity); -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::debugPrint() const { debugPrintComponents(); } - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::debugPrint(const char* tag) const { - spdlog::debug("++++++++ (Shape) ++++++++"); - spdlog::debug("Tag {} Type {} Wireframe {}", tag, static_cast(type_), m_bIsWireframe); - spdlog::debug("Normal: x={}, y={}, z={}", m_f3Normal.x, m_f3Normal.y, m_f3Normal.z); - - spdlog::debug("Double Sided: {}", m_bDoubleSided); - - debugPrint(); - - spdlog::debug("-------- (Shape) --------"); -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::ChangeMaterialDefinitions( - const flutter::EncodableMap& params, - const TextureMap& /*loadedTextures*/ -) { - // if we have a materialdefinitions component, we need to remove it - // and remake / add a new one. - if (hasComponent()) { - ecs->removeComponent(guid_, Component::StaticGetTypeID()); - } - - // If you want to inspect the params coming in. - /*for (const auto& [fst, snd] : params) { - auto key = std::get(fst); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - }*/ - - auto materialDefinitions = std::make_shared(params); - ecs->addComponent(guid_, std::move(materialDefinitions)); - - m_poMaterialInstance.reset(); - - // then tell material system to load us the correct way once - // we're deserialized. - LoadMaterialDefinitionsToMaterialInstance(); - - if (m_poMaterialInstance.getStatus() != Status::Success) { - spdlog::error("Unable to load material definition to instance, bailing out."); - return; - } - - // now, reload / rebuild the material? - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "BaseShape::ChangeMaterialDefinitions" - ); - - // If your entity has multiple primitives, you’ll need to call - // setMaterialInstanceAt for each primitive you want to update. - auto& renderManager = filamentSystem->getFilamentEngine()->getRenderableManager(); - const auto instanceToChange = renderManager.getInstance(_fEntity); - renderManager.setMaterialInstanceAt(instanceToChange, 0, *m_poMaterialInstance.getData()); -} - -//////////////////////////////////////////////////////////////////////////// -void BaseShape::ChangeMaterialInstanceProperty( - const MaterialParameter* materialParam, - const TextureMap& loadedTextures -) { - const auto data = m_poMaterialInstance.getData().value(); - - const auto matDefs = dynamic_cast(getComponent().get() - ); - if (matDefs == nullptr) { - return; - } - - MaterialDefinitions::ApplyMaterialParameterToInstance(data, materialParam, loadedTextures); -} - -} // namespace plugin_filament_view::shapes diff --git a/plugins/filament_view/core/entity/derived/shapes/baseshape.h b/plugins/filament_view/core/entity/derived/shapes/baseshape.h deleted file mode 100644 index 668b87a4..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/baseshape.h +++ /dev/null @@ -1,128 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class CollisionSystem; -class ShapeSystem; -class ModelSystem; - -namespace shapes { - -class BaseShape : public RenderableEntityObject { - friend class plugin_filament_view::CollisionSystem; - friend class plugin_filament_view::ShapeSystem; - friend class plugin_filament_view::ModelSystem; - - public: - /// @brief Constructor for BaseShape. Generates a GUID and has an empty - /// name. - BaseShape(ShapeType type) - : RenderableEntityObject(), - type_(type) {} - /// @brief Constructor for BaseShape with a name. Generates a unique GUID. - explicit BaseShape(std::string name, ShapeType type) - : RenderableEntityObject(name), - type_(type) {} - /// @brief Constructor for BaseShape with GUID. Name is empty. - explicit BaseShape(EntityGUID guid, ShapeType type) - : RenderableEntityObject(guid), - type_(type) {} - /// @brief Constructor for BaseShape with a name and GUID. - BaseShape(std::string name, EntityGUID guid, ShapeType type) - : RenderableEntityObject(name, guid), - type_(type) {} - - ~BaseShape() override; - - virtual void debugPrint(const char* tag) const; - - // Disallow copy and assign. - BaseShape(const BaseShape&) = delete; - BaseShape& operator=(const BaseShape&) = delete; - - // will copy over properties, but not 'create' anything. - // similar to a shallow copy. - virtual void CloneToOther(BaseShape& other) const; - - virtual bool bInitAndCreateShape(::filament::Engine* engine_, FilamentEntity entityObject) = 0; - - void RemoveEntityFromScene() const; - void AddEntityToScene() const; - - protected: - ::filament::VertexBuffer* m_poVertexBuffer = nullptr; - ::filament::IndexBuffer* m_poIndexBuffer = nullptr; - - virtual void deserializeFrom(const flutter::EncodableMap& params) override; - - void onInitialize() override; - - void debugPrint() const override; - - // uses Vertex and Index buffer to create the material and geometry - // using all the internal variables. - void BuildRenderable(::filament::Engine* engine_); - - ShapeType type_ = ShapeType::Unset; - - /// direction of the shape rotation in the world space - filament::math::float3 m_f3Normal = filament::math::float3(0, 0, 0); - - // Whether we have winding indexes in both directions. - bool m_bDoubleSided = false; - - // TODO - Note this is backlogged for using value. - // For now this is unimplemented, but would be a savings - // when building as code currently allocates buffers for UVs - bool m_bHasTexturedMaterial = true; - - void ChangeMaterialDefinitions( - const flutter::EncodableMap& params, - const TextureMap& loadedTextures - ) override; - void ChangeMaterialInstanceProperty( - const MaterialParameter* materialParam, - const TextureMap& loadedTextures - ) override; - - private: - void DestroyBuffers(); - - // This does NOT come over as a property (currently), only used by - // CollisionManager when created debug wireframe models for seeing collider - // shapes. - bool m_bIsWireframe = false; -}; - -} // namespace shapes -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/shapes/cube.cc b/plugins/filament_view/core/entity/derived/shapes/cube.cc deleted file mode 100644 index 3c0f7a3c..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/cube.cc +++ /dev/null @@ -1,745 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "cube.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view::shapes { - -using filament::Aabb; -using filament::IndexBuffer; -using filament::RenderableManager; -using filament::VertexAttribute; -using filament::VertexBuffer; -using filament::math::float3; -using filament::math::mat3f; -using filament::math::packSnorm16; -using filament::math::short4; - -//////////////////////////////////////////////////////////////////////////// -bool Cube::bInitAndCreateShape(filament::Engine* engine_, FilamentEntity entityObject) { - _fEntity = entityObject; - - if (m_bDoubleSided) - createDoubleSidedCube(engine_); - else - createSingleSidedCube(engine_); - return true; -} - -//////////////////////////////////////////////////////////////////////////// -void Cube::createDoubleSidedCube(filament::Engine* engine_) { - // Vertices for a cube (24 vertices for outside, 24 for inside) - static constexpr float vertices[] = { - // Outside Front face - -0.5f, -0.5f, 0.5f, // Vertex 0 - 0.5f, -0.5f, 0.5f, // Vertex 1 - 0.5f, 0.5f, 0.5f, // Vertex 2 - -0.5f, 0.5f, 0.5f, // Vertex 3 - - // Outside Back face - 0.5f, -0.5f, -0.5f, // Vertex 4 - -0.5f, -0.5f, -0.5f, // Vertex 5 - -0.5f, 0.5f, -0.5f, // Vertex 6 - 0.5f, 0.5f, -0.5f, // Vertex 7 - - // Outside Right face - 0.5f, -0.5f, 0.5f, // Vertex 8 - 0.5f, -0.5f, -0.5f, // Vertex 9 - 0.5f, 0.5f, -0.5f, // Vertex 10 - 0.5f, 0.5f, 0.5f, // Vertex 11 - - // Outside Left face - -0.5f, -0.5f, -0.5f, // Vertex 12 - -0.5f, -0.5f, 0.5f, // Vertex 13 - -0.5f, 0.5f, 0.5f, // Vertex 14 - -0.5f, 0.5f, -0.5f, // Vertex 15 - - // Outside Top face - -0.5f, 0.5f, 0.5f, // Vertex 16 - 0.5f, 0.5f, 0.5f, // Vertex 17 - 0.5f, 0.5f, -0.5f, // Vertex 18 - -0.5f, 0.5f, -0.5f, // Vertex 19 - - // Outside Bottom face - -0.5f, -0.5f, -0.5f, // Vertex 20 - 0.5f, -0.5f, -0.5f, // Vertex 21 - 0.5f, -0.5f, 0.5f, // Vertex 22 - -0.5f, -0.5f, 0.5f, // Vertex 23 - - // Inside Front face (inverted) - -0.5f, -0.5f, 0.5f, // Vertex 24 - 0.5f, -0.5f, 0.5f, // Vertex 25 - 0.5f, 0.5f, 0.5f, // Vertex 26 - -0.5f, 0.5f, 0.5f, // Vertex 27 - - // Inside Back face (inverted) - 0.5f, -0.5f, -0.5f, // Vertex 28 - -0.5f, -0.5f, -0.5f, // Vertex 29 - -0.5f, 0.5f, -0.5f, // Vertex 30 - 0.5f, 0.5f, -0.5f, // Vertex 31 - - // Inside Right face (inverted) - 0.5f, -0.5f, 0.5f, // Vertex 32 - 0.5f, -0.5f, -0.5f, // Vertex 33 - 0.5f, 0.5f, -0.5f, // Vertex 34 - 0.5f, 0.5f, 0.5f, // Vertex 35 - - // Inside Left face (inverted) - -0.5f, -0.5f, -0.5f, // Vertex 36 - -0.5f, -0.5f, 0.5f, // Vertex 37 - -0.5f, 0.5f, 0.5f, // Vertex 38 - -0.5f, 0.5f, -0.5f, // Vertex 39 - - // Inside Top face (inverted) - -0.5f, 0.5f, 0.5f, // Vertex 40 - 0.5f, 0.5f, 0.5f, // Vertex 41 - 0.5f, 0.5f, -0.5f, // Vertex 42 - -0.5f, 0.5f, -0.5f, // Vertex 43 - - // Inside Bottom face (inverted) - -0.5f, -0.5f, -0.5f, // Vertex 44 - 0.5f, -0.5f, -0.5f, // Vertex 45 - 0.5f, -0.5f, 0.5f, // Vertex 46 - -0.5f, -0.5f, 0.5f // Vertex 47 - }; - - // UV coordinates for each face (same for inside and outside) - static constexpr float uvCoords[] = {// Outside Front face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Outside Back face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Outside Right face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Outside Left face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Outside Top face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Outside Bottom face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - - // Inside Front face (same UVs as outside) - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Inside Back face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Inside Right face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Inside Left face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Inside Top face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f, - // Inside Bottom face - 0.0f, 0.0f, 1.0f, 0.0f, 1.0f, 1.0f, 0.0f, 1.0f - }; - - // Indices for double-sided cube (showing both inside and outside) - static const uint16_t indices[] = { - // Outside faces - 0, 1, 2, 0, 2, 3, // Front - 4, 5, 6, 4, 6, 7, // Back - 8, 9, 10, 8, 10, 11, // Right - 12, 13, 14, 12, 14, 15, // Left - 16, 17, 18, 16, 18, 19, // Top - 20, 21, 22, 20, 22, 23, // Bottom - - // Inside faces (inverted winding order) - 24, 27, 26, 24, 26, 25, // Front - 28, 31, 30, 28, 30, 29, // Back - 32, 35, 34, 32, 34, 33, // Right - 36, 39, 38, 36, 38, 37, // Left - 40, 43, 42, 40, 42, 41, // Top - 44, 47, 46, 44, 46, 45 // Bottom - }; - - const static short4 normals[] = { - // Outer Front face (Z+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - - // Outer Back face (Z-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - - // Outer Right face (X+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Outer Left face (X-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Outer Top face (Y+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - - // Outer Bottom face (Y-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - - // Inner Front face (Z-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - - // Inner Back face (Z+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - - // Inner Right face (X-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Inner Left face (X+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Inner Top face (Y-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - - // Inner Bottom face (Y+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ) - }; - - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(48) // 24 vertices for outside, 24 for inside - .bufferCount(3) - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) - .attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::FLOAT2) - .normalized(VertexAttribute::TANGENTS) - .build(*engine_); - - m_poVertexBuffer->setBufferAt( - *engine_, 0, VertexBuffer::BufferDescriptor(vertices, sizeof(vertices)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 1, VertexBuffer::BufferDescriptor(normals, sizeof(normals)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 2, VertexBuffer::BufferDescriptor(uvCoords, sizeof(uvCoords)) - ); - - constexpr int indexCount = 72 * 2; // 24 triangles * 3 vertices (inside + outside) - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine_); - - m_poIndexBuffer->setBuffer(*engine_, IndexBuffer::BufferDescriptor(indices, sizeof(indices))); - - BuildRenderable(engine_); -} - -//////////////////////////////////////////////////////////////////////////// -void Cube::createSingleSidedCube(filament::Engine* engine_) { - // Vertices for a cube (24 vertices, 4 per face) - static constexpr float vertices[] = { - // Front face - -0.5f, -0.5f, 0.5f, // Vertex 0 - 0.5f, -0.5f, 0.5f, // Vertex 1 - 0.5f, 0.5f, 0.5f, // Vertex 2 - -0.5f, 0.5f, 0.5f, // Vertex 3 - - // Back face - 0.5f, -0.5f, -0.5f, // Vertex 4 - -0.5f, -0.5f, -0.5f, // Vertex 5 - -0.5f, 0.5f, -0.5f, // Vertex 6 - 0.5f, 0.5f, -0.5f, // Vertex 7 - - // Right face - 0.5f, -0.5f, 0.5f, // Vertex 8 - 0.5f, -0.5f, -0.5f, // Vertex 9 - 0.5f, 0.5f, -0.5f, // Vertex 10 - 0.5f, 0.5f, 0.5f, // Vertex 11 - - // Left face - -0.5f, -0.5f, -0.5f, // Vertex 12 - -0.5f, -0.5f, 0.5f, // Vertex 13 - -0.5f, 0.5f, 0.5f, // Vertex 14 - -0.5f, 0.5f, -0.5f, // Vertex 15 - - // Top face - -0.5f, 0.5f, 0.5f, // Vertex 16 - 0.5f, 0.5f, 0.5f, // Vertex 17 - 0.5f, 0.5f, -0.5f, // Vertex 18 - -0.5f, 0.5f, -0.5f, // Vertex 19 - - // Bottom face - -0.5f, -0.5f, -0.5f, // Vertex 20 - 0.5f, -0.5f, -0.5f, // Vertex 21 - 0.5f, -0.5f, 0.5f, // Vertex 22 - -0.5f, -0.5f, 0.5f // Vertex 23 - }; - - // UV coordinates for each face (24 UVs, 4 per face) - static constexpr float uvCoords[] = { - // Front face - 0.0f, 0.0f, // Vertex 0 - 1.0f, 0.0f, // Vertex 1 - 1.0f, 1.0f, // Vertex 2 - 0.0f, 1.0f, // Vertex 3 - - // Back face - 0.0f, 0.0f, // Vertex 4 - 1.0f, 0.0f, // Vertex 5 - 1.0f, 1.0f, // Vertex 6 - 0.0f, 1.0f, // Vertex 7 - - // Right face - 0.0f, 0.0f, // Vertex 8 - 1.0f, 0.0f, // Vertex 9 - 1.0f, 1.0f, // Vertex 10 - 0.0f, 1.0f, // Vertex 11 - - // Left face - 0.0f, 0.0f, // Vertex 12 - 1.0f, 0.0f, // Vertex 13 - 1.0f, 1.0f, // Vertex 14 - 0.0f, 1.0f, // Vertex 15 - - // Top face - 0.0f, 0.0f, // Vertex 16 - 1.0f, 0.0f, // Vertex 17 - 1.0f, 1.0f, // Vertex 18 - 0.0f, 1.0f, // Vertex 19 - - // Bottom face - 0.0f, 0.0f, // Vertex 20 - 1.0f, 0.0f, // Vertex 21 - 1.0f, 1.0f, // Vertex 22 - 0.0f, 1.0f, // Vertex 23 - }; - - // Indices for 12 triangles (6 faces) - static const uint16_t indices[] = {// Front face - 0, 1, 2, 0, 2, 3, - - // Back face (adjusted winding) - 4, 5, 6, 4, 6, 7, - - // Right face - 8, 9, 10, 8, 10, 11, - - // Left face - 12, 13, 14, 12, 14, 15, - - // Top face - 16, 17, 18, 16, 18, 19, - - // Bottom face (adjusted winding) - 20, 21, 22, 20, 22, 23 - }; - - const static short4 normals[] = { - // Front face (normals pointing along Z+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - - // Back face (normals pointing along Z-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - - // Right face (normals pointing along X+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Left face (normals pointing along X-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{0.0f, 0.0f, -1.0f}, float3{0.0f, 1.0f, 0.0f}, float3{-1.0f, 0.0f, 0.0f}} - ).xyzw - ), - - // Top face (normals pointing along Y+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ), - - // Bottom face (normals pointing along Y-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}, float3{0.0f, -1.0f, 0.0f}} - ).xyzw - ) - }; - - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(24) // 4 vertices per face * 6 faces - .bufferCount(3) - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) - .attribute( - VertexAttribute::UV0, 2, - VertexBuffer::AttributeType::FLOAT2 - ) // UVs - .normalized(VertexAttribute::TANGENTS) - .build(*engine_); - - m_poVertexBuffer->setBufferAt( - *engine_, 0, VertexBuffer::BufferDescriptor(vertices, sizeof(vertices)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 1, VertexBuffer::BufferDescriptor(normals, sizeof(normals)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 2, VertexBuffer::BufferDescriptor(uvCoords, sizeof(uvCoords)) - ); - - constexpr int indexCount = 36; - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine_); - - m_poIndexBuffer->setBuffer(*engine_, IndexBuffer::BufferDescriptor(indices, sizeof(indices))); - - BuildRenderable(engine_); -} - -//////////////////////////////////////////////////////////////////////////// -void Cube::debugPrint(const char* tag) const { BaseShape::debugPrint(tag); } - -} // namespace plugin_filament_view::shapes diff --git a/plugins/filament_view/core/entity/derived/shapes/cube.h b/plugins/filament_view/core/entity/derived/shapes/cube.h deleted file mode 100644 index 5fc819cf..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/cube.h +++ /dev/null @@ -1,58 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "baseshape.h" - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -namespace plugin_filament_view { - -namespace shapes { - -class Cube : public BaseShape { - public: - /// @brief Constructor for Cube. Generates a GUID and has an empty name. - Cube() - : BaseShape(ShapeType::Cube) {} - /// @brief Constructor for Cube with a name. Generates a unique GUID. - explicit Cube(std::string name) - : BaseShape(name, ShapeType::Cube) {} - /// @brief Constructor for Cube with GUID. Name is empty. - explicit Cube(EntityGUID guid) - : BaseShape(guid, ShapeType::Cube) {} - /// @brief Constructor for Cube with a name and GUID. - explicit Cube(std::string name, EntityGUID guid) - : BaseShape(name, guid, ShapeType::Cube) {} - ~Cube() override = default; - - // Disallow copy and assign. - Cube(const Cube&) = delete; - Cube& operator=(const Cube&) = delete; - - void debugPrint(const char* tag) const override; - - bool bInitAndCreateShape(::filament::Engine* engine_, FilamentEntity entityObject) override; - - private: - void createDoubleSidedCube(::filament::Engine* engine_); - - void createSingleSidedCube(::filament::Engine* engine_); -}; - -} // namespace shapes -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/shapes/plane.cc b/plugins/filament_view/core/entity/derived/shapes/plane.cc deleted file mode 100644 index 35679838..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/plane.cc +++ /dev/null @@ -1,249 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "plane.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view::shapes { - -using filament::Aabb; -using filament::IndexBuffer; -using filament::RenderableManager; -using filament::VertexAttribute; -using filament::VertexBuffer; -using filament::math::float3; -using filament::math::mat3f; -using filament::math::packSnorm16; -using filament::math::short4; - -//////////////////////////////////////////////////////////////////////////// -bool Plane::bInitAndCreateShape(filament::Engine* engine_, FilamentEntity entityObject) { - _fEntity = entityObject; - - if (m_bDoubleSided) - createDoubleSidedPlane(engine_); - else - createSingleSidedPlane(engine_); - - return true; -} - -//////////////////////////////////////////////////////////////////////////// -void Plane::createDoubleSidedPlane(filament::Engine* engine_) { - // Vertices for a plane (4 vertices for each side, 8 in total) - static constexpr float vertices[] = { - // Front face - -0.5f, -0.5f, 0.0f, // Vertex 0 - 0.5f, -0.5f, 0.0f, // Vertex 1 - 0.5f, 0.5f, 0.0f, // Vertex 2 - -0.5f, 0.5f, 0.0f, // Vertex 3 - - // Back face - -0.5f, -0.5f, 0.0f, // Vertex 4 - 0.5f, -0.5f, 0.0f, // Vertex 5 - 0.5f, 0.5f, 0.0f, // Vertex 6 - -0.5f, 0.5f, 0.0f // Vertex 7 - }; - - // UV coordinates for the plane - static constexpr float uvCoords[] = { - // Front face - 0.0f, 0.0f, // Vertex 0 - 1.0f, 0.0f, // Vertex 1 - 1.0f, 1.0f, // Vertex 2 - 0.0f, 1.0f, // Vertex 3 - - // Back face (same UVs as front) - 0.0f, 0.0f, // Vertex 4 - 1.0f, 0.0f, // Vertex 5 - 1.0f, 1.0f, // Vertex 6 - 0.0f, 1.0f // Vertex 7 - }; - - // Indices for 2 triangles per side (12 indices in total) - static constexpr uint16_t indices[] = {// Front face - 0, 1, 2, 0, 2, 3, - // Back face (inverted winding) - 4, 6, 5, 4, 7, 6 - }; - - const static short4 normals[] = { - // Front face normals (Z+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - - // Back face normals (Z-) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, -1.0f}} - ).xyzw - ) - }; - - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(8) // 4 vertices for each side - .bufferCount(3) // Positions, Normals, UVs - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) - .attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::FLOAT2) - .normalized(VertexAttribute::TANGENTS) - .build(*engine_); - - m_poVertexBuffer->setBufferAt( - *engine_, 0, VertexBuffer::BufferDescriptor(vertices, sizeof(vertices)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 1, VertexBuffer::BufferDescriptor(normals, sizeof(normals)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 2, VertexBuffer::BufferDescriptor(uvCoords, sizeof(uvCoords)) - ); - - constexpr int indexCount = 12; - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine_); - - m_poIndexBuffer->setBuffer(*engine_, IndexBuffer::BufferDescriptor(indices, sizeof(indices))); - - BuildRenderable(engine_); -} - -//////////////////////////////////////////////////////////////////////////// -void Plane::createSingleSidedPlane(filament::Engine* engine_) { - // Vertices for a single-sided plane (4 vertices) - static constexpr float vertices[] = { - -0.5f, -0.5f, 0.0f, // Vertex 0 - 0.5f, -0.5f, 0.0f, // Vertex 1 - 0.5f, 0.5f, 0.0f, // Vertex 2 - -0.5f, 0.5f, 0.0f // Vertex 3 - }; - - // UV coordinates for the plane - static constexpr float uvCoords[] = { - 0.0f, 0.0f, // Vertex 0 - 1.0f, 0.0f, // Vertex 1 - 1.0f, 1.0f, // Vertex 2 - 0.0f, 1.0f // Vertex 3 - }; - - // Indices for 2 triangles - static constexpr uint16_t indices[] = { - 0, 1, 2, // Triangle 1 - 0, 2, 3 // Triangle 2 - }; - - const static short4 normals[] = { - // Normals for the front face (Z+) - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ), - packSnorm16( - mat3f::packTangentFrame( - mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 1.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}} - ).xyzw - ) - }; - - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(4) - .bufferCount(3) // Positions, Normals, UVs - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) - .attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::FLOAT2) - .normalized(VertexAttribute::TANGENTS) - .build(*engine_); - - m_poVertexBuffer->setBufferAt( - *engine_, 0, VertexBuffer::BufferDescriptor(vertices, sizeof(vertices)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 1, VertexBuffer::BufferDescriptor(normals, sizeof(normals)) - ); - - m_poVertexBuffer->setBufferAt( - *engine_, 2, VertexBuffer::BufferDescriptor(uvCoords, sizeof(uvCoords)) - ); - - constexpr int indexCount = 6; - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine_); - - m_poIndexBuffer->setBuffer(*engine_, IndexBuffer::BufferDescriptor(indices, sizeof(indices))); - - BuildRenderable(engine_); -} - -} // namespace plugin_filament_view::shapes diff --git a/plugins/filament_view/core/entity/derived/shapes/plane.h b/plugins/filament_view/core/entity/derived/shapes/plane.h deleted file mode 100644 index 9fb0f580..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/plane.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "baseshape.h" -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -namespace plugin_filament_view { - -namespace shapes { - -class Plane : public BaseShape { - public: - /// @brief Constructor for Plane. Generates a GUID and has an empty name. - Plane() - : BaseShape(ShapeType::Plane) {} - /// @brief Constructor for Plane with a name. Generates a unique GUID. - explicit Plane(std::string name) - : BaseShape(name, ShapeType::Plane) {} - /// @brief Constructor for Plane with GUID. Name is empty. - explicit Plane(EntityGUID guid) - : BaseShape(guid, ShapeType::Plane) {} - /// @brief Constructor for Plane with a name and GUID. - explicit Plane(std::string name, EntityGUID guid) - : BaseShape(name, guid, ShapeType::Plane) {} - ~Plane() override = default; - - // Disallow copy and assign. - Plane(const Plane&) = delete; - Plane& operator=(const Plane&) = delete; - - bool bInitAndCreateShape(::filament::Engine* engine_, FilamentEntity entityObject) override; - - private: - void createDoubleSidedPlane(::filament::Engine* engine_); - - void createSingleSidedPlane(::filament::Engine* engine_); -}; - -} // namespace shapes -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/entity/derived/shapes/sphere.cc b/plugins/filament_view/core/entity/derived/shapes/sphere.cc deleted file mode 100644 index 9927a692..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/sphere.cc +++ /dev/null @@ -1,182 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "sphere.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view::shapes { - -using filament::IndexBuffer; -using filament::RenderableManager; -using filament::VertexAttribute; -using filament::VertexBuffer; -using filament::math::float3; -using filament::math::mat3f; - -//////////////////////////////////////////////////////////////////////////// - -void Sphere::deserializeFrom(const flutter::EncodableMap& params) { - BaseShape::deserializeFrom(params); - - // stacks - stacks_ = Deserialize::DecodeParameterWithDefault(kStacks, params, 20); - - // slices - slices_ = Deserialize::DecodeParameterWithDefault(kSlices, params, 20); -} - -//////////////////////////////////////////////////////////////////////////// -bool Sphere::bInitAndCreateShape(filament::Engine* engine_, FilamentEntity entityObject) { - _fEntity = entityObject; - - m_poVertexBuffer = nullptr; - m_poIndexBuffer = nullptr; - - if (m_bDoubleSided) { - createDoubleSidedSphere(engine_); - } else { - createSingleSidedSphere(engine_); - } - - return true; -} - -//////////////////////////////////////////////////////////////////////////// -void Sphere::createSingleSidedSphere(filament::Engine* engine_) { - const int sectors = slices_; // Longitude, or number of vertical slices - const int stacks = stacks_; // Latitude, or number of horizontal slices - - const float sectorStep = 2.0f * kPif / static_cast(sectors); - const float stackStep = kPif / static_cast(stacks); - - // Generate vertices, normals, and UVs for the outer surface - for (int i = 0; i <= stacks; ++i) { - const float stackAngle = kPif / 2.0f - static_cast(i) * stackStep; // from pi/2 to -pi/2 - const float xy = cosf(stackAngle) * 0.5f; // r * cos(u) - float z = sinf(stackAngle) * 0.5f; // r * sin(u) - float v = static_cast(i) / static_cast(stacks); // Latitude, y-axis UV - - for (int j = 0; j <= sectors; ++j) { - const float sectorAngle = static_cast(j) * sectorStep; // from 0 to 2pi - float x = xy * cosf(sectorAngle); // x = r * cos(u) * cos(v) - float y = xy * sinf(sectorAngle); // y = r * cos(u) * sin(v) - float u = static_cast(j) / static_cast(sectors); // Longitude, x-axis UV - - // Add vertex position - vertices_.emplace_back(x, y, z); - - // Add normal - float length = sqrt(x * x + y * y + z * z); - if (length == 0) length = 0.01f; - normals_.emplace_back(x / length, y / length, z / length); - - // Add UV coordinates - uvs_.emplace_back(u, v); - } - } - - // Generate indices for the outer surface - for (int i = 0; i < stacks; ++i) { - int k1 = i * (sectors + 1); // Beginning of current stack - int k2 = k1 + sectors + 1; // Beginning of next stack - - for (int j = 0; j < sectors; ++j, ++k1, ++k2) { - // Middle area triangles - indices_.push_back(static_cast(k1)); - indices_.push_back(static_cast(k2)); - indices_.push_back(static_cast(k1 + 1)); - - indices_.push_back(static_cast(k1 + 1)); - indices_.push_back(static_cast(k2)); - indices_.push_back(static_cast(k2 + 1)); - } - } - - // Create the vertex buffer - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(static_cast(vertices_.size())) - .bufferCount(3) // Position, Normals, and UVs - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::UV0, 2, VertexBuffer::AttributeType::FLOAT2) - .build(*engine_); - - // Set buffer data - m_poVertexBuffer->setBufferAt( - *engine_, 0, - VertexBuffer::BufferDescriptor(vertices_.data(), vertices_.size() * sizeof(float) * 3) - ); - m_poVertexBuffer->setBufferAt( - *engine_, 1, VertexBuffer::BufferDescriptor(normals_.data(), normals_.size() * sizeof(float3)) - ); - m_poVertexBuffer->setBufferAt( - *engine_, 2, VertexBuffer::BufferDescriptor(uvs_.data(), uvs_.size() * sizeof(float) * 2) - ); - - // Create the index buffer - const auto indexCount = static_cast(indices_.size()); - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine_); - - m_poIndexBuffer->setBuffer( - *engine_, - IndexBuffer::BufferDescriptor(indices_.data(), indices_.size() * sizeof(unsigned short)) - ); - - BuildRenderable(engine_); -} - -//////////////////////////////////////////////////////////////////////////// -void Sphere::createDoubleSidedSphere(filament::Engine* /*engine_*/) { - // createDoubleSidedSphere - Same geometry, but do stack winding opposite and - // positive on indice creation. - throw std::runtime_error("createDoubleSidedSphere not implemented"); -} - -//////////////////////////////////////////////////////////////////////////// -void Sphere::CloneToOther(BaseShape& other) const { - BaseShape::CloneToOther(other); - - const auto otherShape = dynamic_cast(&other); - - otherShape->slices_ = slices_; - otherShape->stacks_ = stacks_; -} - -//////////////////////////////////////////////////////////////////////////// -void Sphere::debugPrint(const char* tag) const { - BaseShape::debugPrint(tag); - - spdlog::debug("++++++++"); - spdlog::debug("{} (Sphere)", tag); - spdlog::debug("{} (Stacks)", stacks_); - spdlog::debug("{} (Slices)", slices_); - spdlog::debug("++++++++"); -} - -} // namespace plugin_filament_view::shapes diff --git a/plugins/filament_view/core/entity/derived/shapes/sphere.h b/plugins/filament_view/core/entity/derived/shapes/sphere.h deleted file mode 100644 index 2b61d6bf..00000000 --- a/plugins/filament_view/core/entity/derived/shapes/sphere.h +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "baseshape.h" -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -namespace plugin_filament_view { - -namespace shapes { - -class Sphere : public BaseShape { - public: - // /// @brief Constructor for Sphere. Generates a GUID and has an empty name. - Sphere() - : BaseShape(ShapeType::Sphere) {} - /// @brief Constructor for Sphere with a name. Generates a unique GUID. - explicit Sphere(std::string name) - : BaseShape(name, ShapeType::Sphere) {} - /// @brief Constructor for Sphere with GUID. Name is empty. - explicit Sphere(EntityGUID guid) - : BaseShape(guid, ShapeType::Sphere) {} - /// @brief Constructor for Sphere with a name and GUID. - explicit Sphere(std::string name, EntityGUID guid) - : BaseShape(name, guid, ShapeType::Sphere) {} - ~Sphere() override = default; - - // Disallow copy and assign. - Sphere(const Sphere&) = delete; - Sphere& operator=(const Sphere&) = delete; - - virtual void deserializeFrom(const flutter::EncodableMap& params) override; - - void debugPrint(const char* tag) const override; - - bool bInitAndCreateShape(::filament::Engine* engine_, FilamentEntity entityObject) override; - void CloneToOther(BaseShape& other) const override; - - private: - static void createDoubleSidedSphere(::filament::Engine* engine_); - - void createSingleSidedSphere(::filament::Engine* engine_); - - int stacks_ = 20; - int slices_ = 20; - - std::vector<::filament::math::float3> vertices_; - std::vector<::filament::math::float3> normals_; - std::vector indices_; - std::vector<::filament::math::float2> uvs_; -}; - -} // namespace shapes -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/include/additionalmath.h b/plugins/filament_view/core/include/additionalmath.h deleted file mode 100644 index 1d9f0713..00000000 --- a/plugins/filament_view/core/include/additionalmath.h +++ /dev/null @@ -1,19 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -namespace plugin_filament_view { -constexpr float degreesToRadians = 3.14159265359f / 180.0f; // Ï€/180 -} diff --git a/plugins/filament_view/core/include/color.h b/plugins/filament_view/core/include/color.h deleted file mode 100644 index 13c65549..00000000 --- a/plugins/filament_view/core/include/color.h +++ /dev/null @@ -1,95 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include - -#include - -namespace plugin_filament_view { -using Color = ::filament::math::float4; - -inline Color colorOf(float r = 0.0f, float g = 0.0f, float b = 0.0f, float a = 1.0f) { - return {r, g, b, a}; -} - -inline Color colorOf(float rgb = 0.0f, float a = 1.0f) { return colorOf(rgb, rgb, rgb, a); } - -inline Color colorOf(unsigned long color) { - unsigned long a = (color >> 24) & 0xff; // or color >>> 24 - unsigned long r = (color >> 16) & 0xff; - unsigned long g = (color >> 8) & 0xff; - unsigned long b = (color) & 0xff; - - return { - static_cast(r) / 255.0f, static_cast(g) / 255.0f, static_cast(b) / 255.0f, - static_cast(a) / 255.0f - }; -}; - -inline Color colorOf(const std::string& hexColorStr) { - // remove '#' if present at the start - const char* hexCode = hexColorStr[0] == '#' ? hexColorStr.c_str() + 1 : hexColorStr.c_str(); - - unsigned long color = std::strtoul(hexCode, nullptr, 16); // convert hex to decimal - return colorOf(color); -} - -/** - * If rendering in linear space, first convert the gray scaled values to - * linear space by rising to the power 2.2 - */ -inline Color toLinearSpace(const Color& inputColor) { - Color outputColor; - outputColor.r = std::pow(inputColor.r, 2.2f); - outputColor.g = std::pow(inputColor.g, 2.2f); - outputColor.b = std::pow(inputColor.b, 2.2f); - outputColor.a = inputColor.a; // alpha remains the same - return outputColor; -} - -inline Color red(const Color& inputColor) { - Color outputColor{}; - outputColor.r = inputColor.r; - return outputColor; -} - -inline Color green(const Color& inputColor) { - Color outputColor{}; - outputColor.g = inputColor.g; - return outputColor; -} - -inline Color blue(const Color& inputColor) { - Color outputColor{}; - outputColor.b = inputColor.b; - return outputColor; -} - -inline Color alpha(const Color& inputColor) { - Color outputColor{}; - outputColor.a = inputColor.a; - return outputColor; -} - -inline Color toColor(::filament::math::float4 inputColor) { - Color outputColor{}; - outputColor.r = inputColor[0]; - outputColor.g = inputColor[1]; - outputColor.b = inputColor[2]; - outputColor.r = inputColor[3] != 0 ? inputColor[3] : 1.0f; - return outputColor; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/include/file_utils.h b/plugins/filament_view/core/include/file_utils.h deleted file mode 100644 index 8a70f9fb..00000000 --- a/plugins/filament_view/core/include/file_utils.h +++ /dev/null @@ -1,103 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -inline std::filesystem::path getAbsolutePath( - const std::string& dependent_path, - const std::string& main_path -) { - std::filesystem::path path(main_path); - path /= dependent_path; - return path; -} - -inline bool isValidFilePath(const std::filesystem::path& path) { - if (path.empty() || !std::filesystem::exists(path)) { - spdlog::error("[readAsset] invalid path: {}", path.c_str()); - return false; - } - return true; -} - -inline std::vector createBuffer(std::ifstream& file, const std::size_t size) { - std::vector buffer(size); - if (!file.read(reinterpret_cast(buffer.data()), static_cast(buffer.size()))) { - buffer.clear(); - } - return buffer; -} - -inline std::optional readFileContent(const std::filesystem::path& path) { - std::ifstream file(path, std::ios::binary | std::ios::ate); - if (!file.is_open()) { - spdlog::error("[{}] Failed to open", path.c_str()); - return {}; - } - return file; -} - -inline std::vector returnErrorMessageAndBuffer( - const std::filesystem::path& path, - const std::string& message -) { - spdlog::error("[{}] {}", path.c_str(), message); - return {}; -} - -inline std::vector readBinaryFile( - const std::string& dependent_path, - const std::string& main_path -) { - const std::filesystem::path filePath = getAbsolutePath(dependent_path, main_path); - - if (!isValidFilePath(filePath)) { - return returnErrorMessageAndBuffer(filePath, "Invalid path"); - } - - std::optional optionalFile = readFileContent(filePath); - if (!optionalFile.has_value()) { - return returnErrorMessageAndBuffer(filePath, "Failed to open"); - } - - SPDLOG_INFO("Reading: {}/{}", main_path, dependent_path); - - std::ifstream& file = optionalFile.value(); - const auto end = file.tellg(); - file.seekg(0, std::ios::beg); - const auto size = static_cast(end - file.tellg()); - - if (size == 0) { - SPDLOG_ERROR("Size was 0 reading {}", filePath.c_str()); - return returnErrorMessageAndBuffer(filePath, "Empty file"); - } - - std::vector buffer = createBuffer(file, size); - if (buffer.empty()) { - SPDLOG_ERROR("buffer was empty reading {}", filePath.c_str()); - return returnErrorMessageAndBuffer(filePath, "Failed to read"); - } - - return buffer; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/include/literals.h b/plugins/filament_view/core/include/literals.h deleted file mode 100644 index 457069ca..00000000 --- a/plugins/filament_view/core/include/literals.h +++ /dev/null @@ -1,221 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -namespace plugin_filament_view { - -// Messages.cc usage from Dart->C++ -static constexpr char kChangeAnimationByIndex[] = "CHANGE_ANIMATION_BY_INDEX"; -static constexpr char kChangeLightTransformByGUID[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID"; -static constexpr char kChangeLightTransformByGUIDPosx[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_POSX"; -static constexpr char kChangeLightTransformByGUIDPosy[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_POSY"; -static constexpr char kChangeLightTransformByGUIDPosz[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_POSZ"; -static constexpr char kChangeLightTransformByGUIDDirx[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_DIRX"; -static constexpr char kChangeLightTransformByGUIDDiry[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_DIRY"; -static constexpr char kChangeLightTransformByGUIDDirz[] = "CHANGE_LIGHT_TRANSFORM_BY_GUID_DIRZ"; - -static constexpr char kChangeLightColorByGUID[] = "CHANGE_LIGHT_COLOR_BY_GUID"; -static constexpr char kChangeLightColorByGUIDColor[] = "CHANGE_LIGHT_COLOR_BY_GUID_COLOR"; -static constexpr char kChangeLightColorByGUIDIntensity[] = "CHANGE_LIGHT_COLOR_BY_GUID_INTENSITY"; - -static constexpr char kToggleShapesInScene[] = "TOGGLE_SHAPES_IN_SCENE"; -static constexpr char kToggleShapesInSceneValue[] = "TOGGLE_SHAPES_IN_SCENE_VALUE"; -static constexpr char kToggleCollidableVisualsInScene[] = "TOGGLE_COLLIDABLE_VISUALS_IN_SCENE"; -static constexpr char kToggleCollidableVisualsInSceneValue[] = - "TOGGLE_COLLIDABLE_VISUALS_IN_SCENE_VALUE"; -static constexpr char kChangeCameraMode[] = "CHANGE_CAMERA_MODE"; -static constexpr char kChangeCameraModeValue[] = "CHANGE_CAMERA_MODE_VALUE"; -static constexpr char kChangeCameraRotation[] = "ROTATE_CAMERA"; -static constexpr char kChangeCameraRotationValue[] = "ROTATE_CAMERA_VALUE"; -static constexpr char kResetInertiaCameraToDefaultValues[] = "RESET_INERTIA_TO_DEFAULTS"; -static constexpr char kChangeQualitySettings[] = "CHANGE_QUALITY_SETTINGS"; - -static constexpr char kAnimationEnqueue[] = "ANIMATION_ENQUEUE"; -static constexpr char kAnimationClearQueue[] = "ANIMATION_CLEAR_QUEUE"; -static constexpr char kAnimationPlay[] = "ANIMATION_PLAY"; -static constexpr char kAnimationChangeSpeed[] = "ANIMATION_CHANGE_SPEED"; -static constexpr char kAnimationChangeSpeedValue[] = "ANIMATION_CHANGE_SPEED_VALUE"; -static constexpr char kAnimationPause[] = "ANIMATION_PAUSE"; -static constexpr char kAnimationResume[] = "ANIMATION_RESUME"; -static constexpr char kAnimationSetLooping[] = "ANIMATION_SET_LOOPING"; -static constexpr char kAnimationSetLoopingValue[] = "ANIMATION_LOOPING_VALUE"; -static constexpr char kEntityGUID[] = "ENTITY_GUID"; - -// Collision Requests -static constexpr char kCollisionRayRequest[] = "COLLISION_RAY_REQUEST"; -static constexpr char kCollisionRayRequestOriginX[] = "COLLISION_RAY_REQUEST_ORIGIN_X"; -static constexpr char kCollisionRayRequestOriginY[] = "COLLISION_RAY_REQUEST_ORIGIN_Y"; -static constexpr char kCollisionRayRequestOriginZ[] = "COLLISION_RAY_REQUEST_ORIGIN_Z"; -static constexpr char kCollisionRayRequestDirectionX[] = "COLLISION_RAY_REQUEST_DIRECTION_X"; -static constexpr char kCollisionRayRequestDirectionY[] = "COLLISION_RAY_REQUEST_DIRECTION_Y"; -static constexpr char kCollisionRayRequestDirectionZ[] = "COLLISION_RAY_REQUEST_DIRECTION_Z"; -static constexpr char kCollisionRayRequestLength[] = "COLLISION_RAY_REQUEST_LENGTH"; -static constexpr char kCollisionRayRequestGUID[] = "COLLISION_RAY_REQUEST_GUID"; - -static constexpr char kChangeMaterialParameter[] = "CHANGE_MATERIAL_PARAMETER"; -static constexpr char kChangeMaterialParameterData[] = "CHANGE_MATERIAL_PARAMETER_DATA"; -static constexpr char kChangeMaterialParameterEntityGuid[] = - "CHANGE_MATERIAL_PARAMETER_ENTITY_GUID"; - -static constexpr char kChangeMaterialDefinition[] = "CHANGE_MATERIAL_DEFINITION"; -static constexpr char kChangeMaterialDefinitionData[] = "CHANGE_MATERIAL_DEFINITION_DATA"; -static constexpr char kChangeMaterialDefinitionEntityGuid[] = - "CHANGE_MATERIAL_DEFINITION_ENTITY_GUID"; - -// Deserialization -static constexpr char kId[] = "id"; -static constexpr char kParentId[] = "parentId"; -static constexpr char kName[] = "name"; -static constexpr char kGuid[] = "guid"; -static constexpr char kShapeType[] = "shapeType"; -static constexpr char kSize[] = "size"; -static constexpr char kPosition[] = "position"; -static constexpr char kStartingPosition[] = "startingPosition"; -static constexpr char kNormal[] = "normal"; -static constexpr char kScale[] = "scale"; -static constexpr char kRotation[] = "rotation"; -static constexpr char kStacks[] = "stacks"; -static constexpr char kSlices[] = "slices"; -static constexpr char kMaterial[] = "material"; -static constexpr char kDoubleSided[] = "doubleSided"; -static constexpr char kCullingEnabled[] = "cullingEnabled"; -static constexpr char kReceiveShadows[] = "receiveShadows"; -static constexpr char kCastShadows[] = "castShadows"; -static constexpr char kDirection[] = "direction"; -static constexpr char kLength[] = "length"; -static constexpr char kModels[] = "models"; -static constexpr char kCameras[] = "cameras"; -static constexpr char kEntities[] = "entities"; -static constexpr char kComponents[] = "components"; -static constexpr char kSystems[] = "systems"; -static constexpr char kFallback[] = "fallback"; -static constexpr char kScene[] = "scene"; -static constexpr char kShapes[] = "shapes"; -static constexpr char kSkybox[] = "skybox"; -static constexpr char kLight[] = "light"; -static constexpr char kLights[] = "lights"; -static constexpr char kIndirectLight[] = "indirectLight"; -static constexpr char kCamera[] = "camera"; -static constexpr char kExposure[] = "exposure"; -static constexpr char kProjection[] = "projection"; -static constexpr char kLensProjection[] = "lensProjection"; -static constexpr char kOrbitOriginEntity[] = "orbitOriginEntity"; -static constexpr char kDollyOffset[] = "dollyOffset"; -static constexpr char kOrbitRotation[] = "orbitRotation"; -static constexpr char kTargetEntity[] = "targetEntity"; -static constexpr char kTargetPoint[] = "targetPoint"; -static constexpr char kViewId[] = "viewId"; -static constexpr char kFlightMaxMoveSpeed[] = "flightMaxMoveSpeed"; -static constexpr char kFlightMoveDamping[] = "flightMoveDamping"; -static constexpr char kFlightSpeedSteps[] = "flightSpeedSteps"; -static constexpr char kFlightStartOrientation[] = "flightStartOrientation"; -static constexpr char kFlightStartPosition[] = "flightStartPosition"; -static constexpr char kFovDirection[] = "fovDirection"; -static constexpr char kFovDegrees[] = "fovDegrees"; -static constexpr char kFarPlane[] = "farPlane"; -static constexpr char kMode[] = "mode"; -static constexpr char kScaling[] = "scaling"; -static constexpr char kShift[] = "shift"; -static constexpr char kUpVector[] = "upVector"; -static constexpr char kZoomSpeed[] = "zoomSpeed"; -static constexpr char kFocalLength[] = "focalLength"; -static constexpr char kAspect[] = "aspect"; -static constexpr char kNear[] = "near"; -static constexpr char kFar[] = "far"; -static constexpr char kAperture[] = "aperture"; -static constexpr char kSensitivity[] = "sensitivity"; -static constexpr char kShutterSpeed[] = "shutterSpeed"; -static constexpr char kLeft[] = "left"; -static constexpr char kRight[] = "right"; -static constexpr char kBottom[] = "bottom"; -static constexpr char kTop[] = "top"; -static constexpr char kFovInDegrees[] = "fovInDegrees"; -static constexpr char kAutoPlay[] = "autoPlay"; -static constexpr char kIndex[] = "index"; -static constexpr char kAnimation[] = "animation"; -static constexpr char kLoop[] = "loop"; -static constexpr char kResetToTPoseOnReset[] = "resetToTPoseOnReset"; -static constexpr char kPlaybackSpeed[] = "playbackSpeed"; -static constexpr char kNotifyOfAnimationEvents[] = "notifyOfAnimationEvents"; -static constexpr char kType[] = "type"; -static constexpr char kColor[] = "color"; -static constexpr char kColorTemperature[] = "colorTemperature"; -static constexpr char kIntensity[] = "intensity"; -static constexpr char kCastLight[] = "castLight"; -static constexpr char kFalloffRadius[] = "falloffRadius"; -static constexpr char kSpotLightConeInner[] = "spotLightConeInner"; -static constexpr char kSpotLightConeOuter[] = "spotLightConeOuter"; -static constexpr char kSunAngularRadius[] = "sunAngularRadius"; -static constexpr char kSunHaloSize[] = "sunHaloSize"; -static constexpr char kSunHaloFalloff[] = "sunHaloFalloff"; - -// specific collider values: -static constexpr char kCollider[] = "collider"; -static constexpr char kColliderShapeType[] = "collider_shapeType"; -static constexpr char kColliderExtents[] = "collider_extentSize"; -static constexpr char kColliderIsStatic[] = "collider_isStatic"; -static constexpr char kColliderLayer[] = "collider_layer"; -static constexpr char kColliderMask[] = "collider_mask"; -static constexpr char kColliderShouldMatchAttachedObject[] = "collider_shouldMatchAttachedObject"; - -// Custom model viewer for sending frames to dart. -static constexpr char kUpdateFrame[] = "updateFrame"; -static constexpr char kPreRenderFrame[] = "preRenderFrame"; -static constexpr char kPostRenderFrame[] = "postRenderFrame"; -static constexpr char kParam_DeltaTime[] = "deltaTime"; -static constexpr char kParam_FPS[] = "fps"; -static constexpr char kParam_ElapsedFrameTime[] = "elapsedFrameTime"; -static constexpr char kParam_cpuFrametime[] = "cpuFt"; -static constexpr char kParam_gpuFrametime[] = "gpuFt"; - -// Collision Manager and uses, sending messages to dart from native -static constexpr char kCollisionEvent[] = "collision_event"; -static constexpr char kCollisionEventSourceGuid[] = "collision_event_source"; -static constexpr char kCollisionEventHitCount[] = "collision_event_hit_count"; -static constexpr char kCollisionEventHitResult[] = "collision_event_hit_result_"; -static constexpr char kCollisionEventType[] = "collision_event_type"; -enum CollisionEventType { - eFromNonNative, - eNativeOnTouchBegin, - eNativeOnTouchHeld, - eNativeOnTouchEnd -}; - -static constexpr char kAnimationEvent[] = "animation_event"; -static constexpr char kAnimationEventType[] = "animation_event_type"; -enum AnimationEventType { - eAnimationStarted, - eAnimationEnded, - // might want paused, un-paused, speed change. -}; -static constexpr char kAnimationEventData[] = "animation_event_data"; - -static constexpr char kCamera_Inertia_RotationSpeed[] = "inertia_rotationSpeed"; -static constexpr char kCamera_Inertia_VelocityFactor[] = "inertia_velocityFactor"; -static constexpr char kCamera_Inertia_DecayFactor[] = "inertia_decayFactor"; - -static constexpr char kCamera_Pan_angleCapX[] = "pan_angleCapX"; -static constexpr char kCamera_Pan_angleCapY[] = "pan_angleCapY"; -static constexpr char kCamera_Zoom_minCap[] = "zoom_minCap"; -static constexpr char kCamera_Zoom_maxCap[] = "zoom_maxCap"; - -// Configuration values stored in ecs for easier lookup -static constexpr char kAssetPath[] = "assetPath"; -static constexpr char kIsGlb[] = "isGlb"; -static constexpr char kModelInstancingMode[] = "instancingMode"; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/include/resource.h b/plugins/filament_view/core/include/resource.h deleted file mode 100644 index d21e7c70..00000000 --- a/plugins/filament_view/core/include/resource.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include - -enum class Status { Success, Error, Loading }; - -template class Resource { - private: - Status status_; - std::string_view message_ = {}; - std::optional data_ = {}; - - public: - Resource(Status status, std::string_view message, std::optional data = std::nullopt) - : status_(status), - message_(message), - data_(std::move(data)) {} - - Resource() - : status_(Status::Success), - message_() {} - - static Resource Success(T data) { return Resource(Status::Success, "", data); } - - static Resource Error(std::string_view message) { - return Resource(Status::Error, message, std::nullopt); - } - - [[nodiscard]] Status getStatus() const { return status_; } - - [[nodiscard]] std::string_view getMessage() const { return message_; } - - [[nodiscard]] std::optional getData() const { return data_; } - - void reset() { - if (getStatus() == Status::Success) { - getData().reset(); - } - - message_ = ""; - status_ = Status::Loading; - } -}; diff --git a/plugins/filament_view/core/include/shapetypes.h b/plugins/filament_view/core/include/shapetypes.h deleted file mode 100644 index 70d77644..00000000 --- a/plugins/filament_view/core/include/shapetypes.h +++ /dev/null @@ -1,23 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -namespace plugin_filament_view { - -// futures to create - capsule, cylinder -enum class ShapeType { Unset = 0, Plane = 1, Cube = 2, Sphere = 3, Max }; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/lifecycle_participant.h b/plugins/filament_view/core/lifecycle_participant.h deleted file mode 100644 index 06e758e3..00000000 --- a/plugins/filament_view/core/lifecycle_participant.h +++ /dev/null @@ -1,83 +0,0 @@ -/* - * Copyright 2025 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include - -namespace plugin_filament_view { - -/// Enum that defines the lifecycle states of a participant -enum class LifecycleState { - /// The participant has never been initialized - Uninitialized, - /// The participant has been initialized and is ready for use - Initialized, - /// The participant has been destroyed and can no longer be used - Destroyed -}; - -template -/// Abstract class including the main lifecycle methods -class LifecycleParticipant { - private: - LifecycleState _state = LifecycleState::Uninitialized; - - public: - virtual ~LifecycleParticipant() = default; - - /// Called when the object is initialized - void initialize(const InitParams& params) { - if (_state != LifecycleState::Uninitialized) { - throw std::runtime_error("LifecycleParticipant is already initialized"); - } - - onInitialize(params); - _state = LifecycleState::Initialized; - } - - inline bool isInitialized() const { return _state == LifecycleState::Initialized; } - - /// @brief Similar to isInitialized, but throws an exception if not initialized - /// @throws std::runtime_error if not initialized - inline void assertInitialized() const { - if (!isInitialized()) { - throw std::runtime_error("LifecycleParticipant is not initialized"); - } - } - - /// Updates the logic of the object for the duration of the frame - virtual void update(double /*deltaTime*/) = 0; - - void destroy() { - if (_state != LifecycleState::Initialized) { - spdlog::warn("LifecycleParticipant is not initialized or already destroyed"); - return; - } - - onDestroy(); - _state = LifecycleState::Destroyed; - } - - protected: - /// Called when the object is initialized. Should set up any resources or state. - virtual void onInitialize(const InitParams& params) = 0; - - /// Called when the object is destroyed. Should free any memory and resources in use - virtual void onDestroy() = 0; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/exposure.cc b/plugins/filament_view/core/scene/camera/exposure.cc deleted file mode 100644 index 68363391..00000000 --- a/plugins/filament_view/core/scene/camera/exposure.cc +++ /dev/null @@ -1,74 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "exposure.h" - -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Exposure::Exposure(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++Exposure::Exposure"); - for (const auto& [fst, snd] : params) { - if (auto key = std::get(fst); key == kAperture) { - if (std::holds_alternative(snd)) { - aperture_ = std::get(snd); - } else if (std::holds_alternative(snd)) { - aperture_ = 16.0f; - } - } else if (key == kSensitivity) { - if (std::holds_alternative(snd)) { - sensitivity_ = std::get(snd); - } else if (std::holds_alternative(snd)) { - sensitivity_ = 100.0f; - } - } else if (key == kShutterSpeed) { - if (std::holds_alternative(snd)) { - shutterSpeed_ = std::get(snd); - } else if (std::holds_alternative(snd)) { - shutterSpeed_ = 1.0f / 125.0f; - } - } else if (key == kExposure) { - if (std::holds_alternative(snd)) { - exposure_ = std::get(snd); - } - } - } - SPDLOG_TRACE("--Exposure::Exposure"); -} - -//////////////////////////////////////////////////////////////////////////// -void Exposure::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (Exposure)", tag); - if (aperture_.has_value()) { - spdlog::debug("\taperture: {}", aperture_.value()); - } - if (sensitivity_.has_value()) { - spdlog::debug("\tsensitivity: {}", sensitivity_.value()); - } - if (shutterSpeed_.has_value()) { - spdlog::debug("\tshutterSpeed: {}", shutterSpeed_.value()); - } - if (exposure_.has_value()) { - spdlog::debug("\texposure: {}", exposure_.value()); - } - spdlog::debug("++++++++"); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/exposure.h b/plugins/filament_view/core/scene/camera/exposure.h deleted file mode 100644 index ae7f46fc..00000000 --- a/plugins/filament_view/core/scene/camera/exposure.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -class ViewTarget; - -namespace plugin_filament_view { - -class Exposure { - friend class ViewTarget; - - public: - explicit Exposure(const flutter::EncodableMap& params); - - void debugPrint(const char* tag); - - Exposure(const Exposure& other) = default; - - Exposure& operator=(const Exposure& other) { - if (this == &other) { - return *this; - } - aperture_ = other.aperture_; - shutterSpeed_ = other.shutterSpeed_; - sensitivity_ = other.sensitivity_; - exposure_ = other.exposure_; - return *this; - } - - [[nodiscard]] std::unique_ptr clone() const { - return std::make_unique(*this); // Calls the copy constructor - } - - private: - /// Aperture in f-stops, clamped between 0.5 and 64. A lower aperture value - /// increases the exposure, leading to a brighter scene. Realistic values are - /// between 0.95 and 32. - std::optional aperture_; - - /// shutterSpeed – Shutter speed in seconds, - /// clamped between 1/25,000 and 60. A lower shutter speed increases the - /// exposure. Realistic values are between 1/8000 and 30. sensitivity - std::optional shutterSpeed_; - - /// Sensitivity in ISO, clamped between 10 and 204,800. - /// A higher sensitivity increases the exposure. Realistic values are between - /// 50 and 25600. - std::optional sensitivity_; - - /// Sets this camera's exposure directly. - std::optional exposure_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/lens_projection.cc b/plugins/filament_view/core/scene/camera/lens_projection.cc deleted file mode 100644 index d2f5abd6..00000000 --- a/plugins/filament_view/core/scene/camera/lens_projection.cc +++ /dev/null @@ -1,84 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "lens_projection.h" - -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -LensProjection::LensProjection(const float cameraFocalLength, float aspect) - : focalLength_(cameraFocalLength), - aspect_(aspect), - near_(0.0f), - far_(0.0f) {} - -//////////////////////////////////////////////////////////////////////////// -LensProjection::LensProjection(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++LensProjection::LensProjection"); - for (const auto& [fst, snd] : params) { - auto key = std::get(fst); - if (key == kFocalLength) { - if (std::holds_alternative(snd)) { - focalLength_ = static_cast(std::get(snd)); - } else if (std::holds_alternative(snd)) { - focalLength_ = 28.0f; - } - } else if (key == kAspect) { - if (std::holds_alternative(snd)) { - aspect_ = std::get(snd); - } - } else if (key == kNear) { - if (std::holds_alternative(snd)) { - near_ = std::get(snd); - } else if (std::holds_alternative(snd)) { - near_ = 0.05; // 5 cm - } - } else if (key == kFar) { - if (std::holds_alternative(snd)) { - far_ = std::get(snd); - } else if (std::holds_alternative(snd)) { - far_ = 1000.0; // 1 km - } - } else if (!snd.IsNull()) { - spdlog::debug("[LensProjection] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - SPDLOG_TRACE("--LensProjection::LensProjection"); -} - -//////////////////////////////////////////////////////////////////////////// -void LensProjection::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (LensProjection)", tag); - spdlog::debug("\tfocalLength: {}", focalLength_); - - if (aspect_.has_value()) { - spdlog::debug("\taspect: {}", aspect_.value()); - } - if (near_.has_value()) { - spdlog::debug("\tnear: {}", near_.value()); - } - if (far_.has_value()) { - spdlog::debug("\tfar: {}", far_.value()); - } - spdlog::debug("++++++++"); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/lens_projection.h b/plugins/filament_view/core/scene/camera/lens_projection.h deleted file mode 100644 index 60489791..00000000 --- a/plugins/filament_view/core/scene/camera/lens_projection.h +++ /dev/null @@ -1,76 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include - -namespace plugin_filament_view { - -class ViewTarget; - -class LensProjection { - friend class ViewTarget; - - public: - LensProjection(float cameraFocalLength, float aspect); - - explicit LensProjection(const flutter::EncodableMap& params); - - void debugPrint(const char* tag); - - [[nodiscard]] float getFocalLength() const { return focalLength_; } - - [[nodiscard]] std::optional getAspect() const { return aspect_; } - - [[nodiscard]] std::optional getNear() const { return near_; } - - [[nodiscard]] std::optional getFar() const { return far_; } - - LensProjection(const LensProjection& other) // NOLINT - : focalLength_(other.focalLength_), - aspect_(other.aspect_), - near_(other.near_), - far_(other.far_) {} - - // Implement the assignment operator for deep copy. - LensProjection& operator=(const LensProjection& other) { - if (this == &other) { - return *this; // Handle self-assignment. - } - focalLength_ = other.focalLength_; - aspect_ = other.aspect_; - near_ = other.near_; - far_ = other.far_; - return *this; - } - - // Add a clone method for creating a deep copy. - [[nodiscard]] std::unique_ptr clone() const { - return std::make_unique(*this); // Calls the copy constructor - } - - private: - float focalLength_; - std::optional aspect_; - std::optional near_; - std::optional far_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/projection.cc b/plugins/filament_view/core/scene/camera/projection.cc deleted file mode 100644 index 6e2328ac..00000000 --- a/plugins/filament_view/core/scene/camera/projection.cc +++ /dev/null @@ -1,147 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "projection.h" - -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Projection::Projection(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++Projection::Projection"); - for (const auto& [fst, snd] : params) { - if (auto key = std::get(fst); key == kProjection) { - if (std::holds_alternative(snd)) { - projection_ = getTypeForText(std::get(snd)); - } else if (std::holds_alternative(snd)) { - projection_ = filament::Camera::Projection::ORTHO; - } - } else if (key == kLeft) { - if (std::holds_alternative(snd)) { - left_ = std::get(snd); - } - } else if (key == kRight) { - if (std::holds_alternative(snd)) { - right_ = std::get(snd); - } - } else if (key == kBottom) { - if (std::holds_alternative(snd)) { - bottom_ = std::get(snd); - } - } else if (key == kTop) { - if (std::holds_alternative(snd)) { - top_ = std::get(snd); - } - } else if (key == kNear) { - if (std::holds_alternative(snd)) { - near_ = std::get(snd); - } - } else if (key == kFar) { - if (std::holds_alternative(snd)) { - far_ = std::get(snd); - } - } else if (key == kFovInDegrees) { - if (std::holds_alternative(snd)) { - fovInDegrees_ = std::get(snd); - } - } else if (key == kAspect) { - if (std::holds_alternative(snd)) { - aspect_ = std::get(snd); - } - } else if (key == kDirection) { - if (std::holds_alternative(snd)) { - fovDirection_ = getFovForText(std::get(snd)); - } else if (std::holds_alternative(snd)) { - fovDirection_ = filament::Camera::Fov::HORIZONTAL; - } - } - } - SPDLOG_TRACE("--Projection::Projection"); -} - -//////////////////////////////////////////////////////////////////////////// -void Projection::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (Projection)", tag); - if (projection_.has_value()) { - spdlog::debug("projection: {}", getTextForType(projection_.value())); - } - if (left_.has_value()) { - spdlog::debug("left: {}", left_.value()); - } - if (right_.has_value()) { - spdlog::debug("right: {}", right_.value()); - } - if (bottom_.has_value()) { - spdlog::debug("bottom: {}", bottom_.value()); - } - if (top_.has_value()) { - spdlog::debug("top: {}", top_.value()); - } - if (near_.has_value()) { - spdlog::debug("near: {}", near_.value()); - } - if (far_.has_value()) { - spdlog::debug("far: {}", far_.value()); - } - if (fovInDegrees_.has_value()) { - spdlog::debug("fovInDegrees: {}", fovInDegrees_.value()); - } - if (aspect_.has_value()) { - spdlog::debug("aspect: {}", aspect_.value()); - } - if (fovDirection_.has_value()) { - spdlog::debug("fovDirection: {}", getTextForFov(fovDirection_.value())); - } - spdlog::debug("++++++++"); -} - -//////////////////////////////////////////////////////////////////////////// -const char* Projection::getTextForType(filament::Camera::Projection type) { - return (const char*[]){ - kTypePerspective, - kTypeOrtho, - }[static_cast(type)]; -} - -//////////////////////////////////////////////////////////////////////////// -filament::Camera::Projection Projection::getTypeForText(const std::string& type) { - if (type == kTypePerspective) return filament::Camera::Projection::PERSPECTIVE; - return filament::Camera::Projection::ORTHO; -} - -//////////////////////////////////////////////////////////////////////////// -const char* Projection::getTextForFov(filament::Camera::Fov fov) { - return (const char*[]){ - kFovVertical, - kFovHorizontal, - }[static_cast(fov)]; -} - -//////////////////////////////////////////////////////////////////////////// -filament::Camera::Fov Projection::getFovForText(const std::string& fov) { - if (fov == kFovVertical) { - return filament::Camera::Fov::VERTICAL; - } - if (fov == kFovHorizontal) { - return filament::Camera::Fov::HORIZONTAL; - } - return filament::Camera::Fov::HORIZONTAL; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/projection.h b/plugins/filament_view/core/scene/camera/projection.h deleted file mode 100644 index f83340d1..00000000 --- a/plugins/filament_view/core/scene/camera/projection.h +++ /dev/null @@ -1,127 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include - -#include - -namespace plugin_filament_view { - -class Camera; -class ViewTarget; - -class Projection { - friend class ViewTarget; - - public: - explicit Projection(const flutter::EncodableMap& params); - - void debugPrint(const char* tag); - - Projection(const Projection& other) // NOLINT - : projection_(other.projection_), - left_(other.left_), - right_(other.right_), - bottom_(other.bottom_), - top_(other.top_), - near_(other.near_), - far_(other.far_), - fovInDegrees_(other.fovInDegrees_), - aspect_(other.aspect_), - fovDirection_(other.fovDirection_) {} - - // Implement the assignment operator for deep copy. - Projection& operator=(const Projection& other) { - if (this == &other) { - return *this; // Handle self-assignment. - } - projection_ = other.projection_; - left_ = other.left_; - right_ = other.right_; - bottom_ = other.bottom_; - top_ = other.top_; - near_ = other.near_; - far_ = other.far_; - fovInDegrees_ = other.fovInDegrees_; - aspect_ = other.aspect_; - fovDirection_ = other.fovDirection_; - return *this; - } - - // Add a clone method for creating a deep copy. - [[nodiscard]] std::unique_ptr clone() const { - return std::make_unique(*this); // Calls the copy constructor - } - - static const char* getTextForType(::filament::Camera::Projection type); - - static ::filament::Camera::Projection getTypeForText(const std::string& type); - - static const char* getTextForFov(::filament::Camera::Fov fov); - - static ::filament::Camera::Fov getFovForText(const std::string& fov); - - private: - static constexpr char kTypePerspective[] = "PERSPECTIVE"; - static constexpr char kTypeOrtho[] = "ORTHO"; - static constexpr char kFovVertical[] = "VERTICAL"; - static constexpr char kFovHorizontal[] = "HORIZONTAL"; - - /// Denotes the projection type used by this camera. - std::optional<::filament::Camera::Projection> projection_; - - /// distance in world units from the camera to the left plane, at the near - /// plane. Precondition: left != right - std::optional left_; - - /// distance in world units from the camera to the right plane, at the near - /// plane. Precondition: left != right - std::optional right_; - - /// distance in world units from the camera to the bottom plane, at the near - /// plane. Precondition: bottom != top - std::optional bottom_; - - /// distance in world units from the camera to the top plane, at the near - /// plane. Precondition: bottom != top - std::optional top_; - - /// distance in world units from the camera to the near plane. - /// The near plane's position in view space is z = -near. - /// Precondition: near > 0 for ProjectionType.PERSPECTIVE or near != far for - /// ProjectionType.ORTHO. - std::optional near_; - - /// distance in world units from the camera to the far plane. - /// The far plane's position in view space is z = -far. - /// Precondition: far > near for ProjectionType.PERSPECTIVE or far != near - /// for ProjectionType.ORTHO. - std::optional far_; - - /// full field-of-view in degrees. 0 < fovInDegrees < 180 - std::optional fovInDegrees_; - - /// aspect ratio width/height. aspect > 0 - std::optional aspect_; - - /// direction of the field-of-view parameter. - std::optional<::filament::Camera::Fov> fovDirection_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/camera/touch_pair.h b/plugins/filament_view/core/scene/camera/touch_pair.h deleted file mode 100644 index d60b553d..00000000 --- a/plugins/filament_view/core/scene/camera/touch_pair.h +++ /dev/null @@ -1,72 +0,0 @@ -/* - * Copyright 2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include - -namespace plugin_filament_view { - -class TouchPair { - public: - TouchPair() - : pt0_(filament::math::float2(0.0f)), - pt1_(filament::math::float2(0.0f)), - count_(0) {}; - - TouchPair( - int32_t pointer_count, - const size_t /* point_data_size */, - const double* point_data, - uint32_t height - ) { - if (pointer_count >= 1) { - pt0_ = filament::math::float2( - static_cast(point_data[7]), - static_cast(height) - static_cast(point_data[8]) - ); - pt1_ = pt0_; - count_++; - } - if (pointer_count >= 2) { - pt1_ = filament::math::float2( - static_cast(point_data[9]), - static_cast(height) - static_cast(point_data[10]) - ); - count_++; - } - }; - - TouchPair(const double x0, const double y0, uint32_t height) { - pt0_ = filament::math::float2( - static_cast(x0), static_cast(height) - static_cast(y0) - ); - pt1_ = pt0_; - count_ = 1; - } - - float separation() { return distance(pt0_, pt1_); }; - [[nodiscard]] filament::math::float2 midpoint() const { return mix(pt0_, pt1_, 0.5f); }; - [[nodiscard]] int x() const { return static_cast(midpoint().x); } - [[nodiscard]] int y() const { return static_cast(midpoint().y); } - - private: - filament::math::float2 pt0_{}; - filament::math::float2 pt1_{}; - uint32_t count_{}; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/direction.h b/plugins/filament_view/core/scene/geometry/direction.h deleted file mode 100644 index a731e6fb..00000000 --- a/plugins/filament_view/core/scene/geometry/direction.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include - -namespace plugin_filament_view { - -typedef ::filament::math::float3 Direction; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/position.h b/plugins/filament_view/core/scene/geometry/position.h deleted file mode 100644 index b94a733d..00000000 --- a/plugins/filament_view/core/scene/geometry/position.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include - -namespace plugin_filament_view { - -typedef ::filament::math::float3 Position; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/ray.cc b/plugins/filament_view/core/scene/geometry/ray.cc deleted file mode 100644 index 41a3bb72..00000000 --- a/plugins/filament_view/core/scene/geometry/ray.cc +++ /dev/null @@ -1,37 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "ray.h" - -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Ray::Ray(const flutter::EncodableMap& params) - : direction_({0, 0, -1}), - position_({0, 0, 0}), - length_(1.0f) { - Deserialize::DecodeParameterWithDefault( - kDirection, &direction_, params, filament::math::float3(0, 0, -1) - ); - Deserialize::DecodeParameterWithDefault( - kStartingPosition, &position_, params, filament::math::float3(0, 0, 0) - ); - Deserialize::DecodeParameterWithDefault(kLength, &length_, params, 1.0f); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/ray.h b/plugins/filament_view/core/scene/geometry/ray.h deleted file mode 100644 index 5c3f4ee8..00000000 --- a/plugins/filament_view/core/scene/geometry/ray.h +++ /dev/null @@ -1,49 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "direction.h" -#include "position.h" -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include - -namespace plugin_filament_view { - -class Ray { - public: - Ray(const Position& pos, const Direction& dir, float length) - : direction_(dir), - position_(pos), - length_(length) {} - explicit Ray(const flutter::EncodableMap& params); - - [[nodiscard]] ::filament::math::float3 f3GetPosition() const { return position_; } - - [[nodiscard]] ::filament::math::float3 f3GetDirection() const { return direction_; } - - [[nodiscard]] double dGetLength() const { return length_; } - - void debugPrint(const char* tag); - - private: - Direction direction_; - Position position_; - double length_; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/size.cc b/plugins/filament_view/core/scene/geometry/size.cc deleted file mode 100644 index 0d463f15..00000000 --- a/plugins/filament_view/core/scene/geometry/size.cc +++ /dev/null @@ -1,68 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "size.h" - -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Size::Size(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++Size::Size"); - for (const auto& [fst, snd] : params) { - if (snd.IsNull() || !std::holds_alternative(snd)) continue; - - auto key = std::get(fst); - auto value = std::get(snd); - if (key == "x") { - x_ = value; - } else if (key == "y") { - y_ = value; - } else if (key == "z") { - z_ = value; - } else if (!snd.IsNull()) { - spdlog::debug("[Size] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - SPDLOG_TRACE("--Size::Size"); -} - -//////////////////////////////////////////////////////////////////////////// -Size::Size(double x, double y, double z) { - x_ = x; - y_ = y; - z_ = z; -} - -//////////////////////////////////////////////////////////////////////////// -void Size::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (Size)", tag); - if (x_.has_value()) { - spdlog::debug("\tx: {}", x_.value()); - } - if (y_.has_value()) { - spdlog::debug("\ty: {}", y_.value()); - } - if (z_.has_value()) { - spdlog::debug("\tz: {}", z_.value()); - } - spdlog::debug("++++++++"); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/geometry/size.h b/plugins/filament_view/core/scene/geometry/size.h deleted file mode 100644 index 7b9e6350..00000000 --- a/plugins/filament_view/core/scene/geometry/size.h +++ /dev/null @@ -1,44 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include - -namespace plugin_filament_view { - -class Size { - public: - explicit Size(const flutter::EncodableMap& params); - - Size(double x, double y, double z); - - void debugPrint(const char* tag); - - // Disallow copy and assign. - Size(const Size&) = delete; - - Size& operator=(const Size&) = delete; - - private: - std::optional x_; - std::optional y_; - std::optional z_; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/indirect_light/indirect_light.cc b/plugins/filament_view/core/scene/indirect_light/indirect_light.cc deleted file mode 100644 index c4398a35..00000000 --- a/plugins/filament_view/core/scene/indirect_light/indirect_light.cc +++ /dev/null @@ -1,100 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "indirect_light.h" - -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -IndirectLight::IndirectLight(std::string assetPath, std::string url, const float intensity) - : assetPath_(std::move(assetPath)), - url_(std::move(url)), - intensity_(intensity) {} - -//////////////////////////////////////////////////////////////////////////// -IndirectLight::~IndirectLight() = default; - -//////////////////////////////////////////////////////////////////////////// -std::unique_ptr IndirectLight::Deserialize(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++IndirectLight::Deserialize"); - - std::optional type; - std::optional assetPath; - std::optional url; - std::optional intensity; - - for (const auto& [fst, snd] : params) { - if (snd.IsNull()) continue; - - if (auto key = std::get(fst); - key == "assetPath" && std::holds_alternative(snd)) { - assetPath = std::get(snd); - } else if (key == "url" && std::holds_alternative(snd)) { - url = std::get(snd); - } else if (key == "intensity" && std::holds_alternative(snd)) { - intensity = std::get(snd); - } else if (key == "lightType" && std::holds_alternative(snd)) { - type = std::get(snd); - } /*else if (!it.second.IsNull()) { - spdlog::debug("[IndirectLight] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), - it.second); - }*/ - } - - if (type.has_value()) { - switch (type.value()) { - case 1: - spdlog::debug("[IndirectLight] Type: KtxIndirectLight"); - return std::make_unique(std::move(assetPath), std::move(url), intensity); - - case 2: - spdlog::debug("[IndirectLight] Type: HdrIndirectLight"); - return std::make_unique(std::move(assetPath), std::move(url), intensity); - - case 3: - spdlog::debug("[IndirectLight] Type: DefaultIndirectLight"); - return std::make_unique(); - - default: - spdlog::error("[IndirectLight] Type: Unknown DefaultIndirectLight"); - break; - } - } else { - spdlog::error("[IndirectLight] No Type Value"); - } - - SPDLOG_TRACE("--IndirectLight::Deserialize"); - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////// -void IndirectLight::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (Light)", tag); - spdlog::debug("\tintensity: {}", intensity_); -} - -//////////////////////////////////////////////////////////////////////////// -void DefaultIndirectLight::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (DefaultIndirectLight)", tag); - spdlog::debug("\tintensity: {}", intensity_); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/indirect_light/indirect_light.h b/plugins/filament_view/core/scene/indirect_light/indirect_light.h deleted file mode 100644 index 38c3672c..00000000 --- a/plugins/filament_view/core/scene/indirect_light/indirect_light.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include -#include -#include - -namespace plugin_filament_view { - -class IndirectLight { - public: - static constexpr float DEFAULT_LIGHT_INTENSITY = 30'000.0; - - IndirectLight(std::string assetPath, std::string url, float intensity); - - virtual ~IndirectLight() = 0; - - static std::unique_ptr Deserialize(const flutter::EncodableMap& params); - - [[nodiscard]] const std::string& getAssetPath() const { return assetPath_; }; - - [[nodiscard]] const std::string& getUrl() const { return url_; }; - - [[nodiscard]] float getIntensity() const { return intensity_; }; - - // still has to run through filament after you set this value. - void setIntensity(float fValue) { intensity_ = fValue; } - virtual void debugPrint(const char* tag); - - protected: - std::string assetPath_; - std::string url_; - float intensity_; -}; - -class DefaultIndirectLight final : public IndirectLight { - public: - explicit DefaultIndirectLight( - float intensity = IndirectLight::DEFAULT_LIGHT_INTENSITY, - std::vector<::filament::math::float3> radiance = {{1.0f, 1.0f, 1.0f}}, - std::vector<::filament::math::float3> irradiance = {{1.0f, 1.0f, 1.0f}} - ) - : IndirectLight("", "", intensity), - radiance_(std::move(radiance)), - irradiance_(std::move(irradiance)) {} - - ~DefaultIndirectLight() override = default; - - friend class IndirectLightSystem; - - void debugPrint(const char* tag) override; - - private: - std::vector<::filament::math::float3> radiance_{}; - std::vector<::filament::math::float3> irradiance_{}; - std::optional<::filament::math::mat3f> rotation_{}; -}; - -class HdrIndirectLight final : public IndirectLight { - public: - explicit HdrIndirectLight( - std::optional assetPath, - std::optional url, - std::optional intensity - ) - : IndirectLight( - assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - intensity.has_value() ? intensity.value() : IndirectLight::DEFAULT_LIGHT_INTENSITY - ) {} - - ~HdrIndirectLight() override = default; -}; - -class KtxIndirectLight final : public IndirectLight { - public: - explicit KtxIndirectLight( - std::optional assetPath, - std::optional url, - std::optional intensity - ) - : IndirectLight( - assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - intensity.has_value() ? intensity.value() : IndirectLight::DEFAULT_LIGHT_INTENSITY - ) {} - - ~KtxIndirectLight() override = default; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/loader/material_loader.cc b/plugins/filament_view/core/scene/material/loader/material_loader.cc deleted file mode 100644 index d3edef11..00000000 --- a/plugins/filament_view/core/scene/material/loader/material_loader.cc +++ /dev/null @@ -1,98 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "material_loader.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -using filament::RgbType; -using filament::math::float3; - -//////////////////////////////////////////////////////////////////////////// -MaterialLoader::MaterialLoader() = default; - -//////////////////////////////////////////////////////////////////////////// -// This function does NOT set default parameter values. -Resource MaterialLoader::loadMaterialFromAsset(const std::string& path) { - const auto assetPath = ECSManager::GetInstance()->getConfigValue(kAssetPath); - const auto buffer = readBinaryFile(path, assetPath); - - if (!buffer.empty()) { - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "loadMaterialFromAsset" - ); - const auto engine = filamentSystem->getFilamentEngine(); - - const auto material = - filament::Material::Builder().package(buffer.data(), buffer.size()).build(*engine); - - return Resource::Success(material); - } - - SPDLOG_ERROR("Could not load material from asset."); - return Resource::Error("Could not load material from asset."); -} - -//////////////////////////////////////////////////////////////////////////// -Resource MaterialLoader::loadMaterialFromUrl(const std::string& url) { - plugin_common_curl::CurlClient client; - // TODO client.Init(url); - const std::vector buffer = client.RetrieveContentAsVector(); - if (client.GetCode() != CURLE_OK) { - return Resource::Error("Failed to load material from " + url); - } - - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "loadMaterialFromUrl" - ); - const auto engine = filamentSystem->getFilamentEngine(); - - if (!buffer.empty()) { - const auto material = - filament::Material::Builder().package(buffer.data(), buffer.size()).build(*engine); - return Resource::Success(material); - } - - return Resource::Error("Could not load material from asset."); -} - -//////////////////////////////////////////////////////////////////////////// -void MaterialLoader::PrintMaterialInformation(const filament::Material* material) { - spdlog::info("Material Informaton {}", material->getName()); - size_t paramCount = material->getParameterCount(); - spdlog::info("Material Informaton {}", paramCount); - - const auto InfoList = new filament::Material::ParameterInfo[paramCount]; - material->getParameters(InfoList, paramCount); - - for (size_t i = 0; i < paramCount; ++i) { - spdlog::info("Param Informaton {}", InfoList[i].name); - } - - spdlog::info("Material isDoubleSided {}", material->isDoubleSided()); - spdlog::info("Material isDepthCullingEnabled {}", material->isDepthCullingEnabled()); - spdlog::info("Material isDepthWriteEnabled {}", material->isDepthWriteEnabled()); - spdlog::info("Material isColorWriteEnabled {}", material->isColorWriteEnabled()); - - delete[] InfoList; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/loader/material_loader.h b/plugins/filament_view/core/scene/material/loader/material_loader.h deleted file mode 100644 index adbf781b..00000000 --- a/plugins/filament_view/core/scene/material/loader/material_loader.h +++ /dev/null @@ -1,41 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include - -namespace plugin_filament_view { - -class MaterialLoader { - public: - MaterialLoader(); - ~MaterialLoader() = default; - - static Resource<::filament::Material*> loadMaterialFromAsset(const std::string& path); - - static Resource<::filament::Material*> loadMaterialFromUrl(const std::string& url); - - // Disallow copy and assign. - MaterialLoader(const MaterialLoader&) = delete; - MaterialLoader& operator=(const MaterialLoader&) = delete; - - static void PrintMaterialInformation(const ::filament::Material* material); - - private: -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/loader/texture_loader.cc b/plugins/filament_view/core/scene/material/loader/texture_loader.cc deleted file mode 100644 index e75d389c..00000000 --- a/plugins/filament_view/core/scene/material/loader/texture_loader.cc +++ /dev/null @@ -1,154 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "texture_loader.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -TextureLoader::TextureLoader() = default; - -//////////////////////////////////////////////////////////////////////////// -inline filament::backend::TextureFormat internalFormat(const TextureDefinitions::TextureType type) { - switch (type) { - case TextureDefinitions::TextureType::COLOR: - return filament::backend::TextureFormat::SRGB8_A8; - case TextureDefinitions::TextureType::NORMAL: - case TextureDefinitions::TextureType::DATA: - return filament::backend::TextureFormat::RGBA8; - default: - throw std::runtime_error("Invalid texture type"); - } -} - -//////////////////////////////////////////////////////////////////////////// -filament::Texture* TextureLoader::createTextureFromImage( - const std::string& file_path, - const TextureDefinitions::TextureType type -) { - int w, h, n; - const unsigned char* data = stbi_load(file_path.c_str(), &w, &h, &n, 4); - - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "createTextureFromImage" - ); - const auto engine = filamentSystem->getFilamentEngine(); - - filament::Texture* texture = - filament::Texture::Builder() - .width(static_cast(w)) - .height(static_cast(h)) - .levels(1) // TODO should be param, backlogged - .format(internalFormat(type)) - .sampler(filament::Texture::Sampler::SAMPLER_2D) - .usage(filament::Texture::Usage::DEFAULT | filament::Texture::Usage::GEN_MIPMAPPABLE) - .build(*engine); - - if (!texture) { - spdlog::error("Unable to create Filament Texture from image."); - return nullptr; - } - - filament::Texture::PixelBufferDescriptor pbd( - data, static_cast(w * h * 4), - filament::Texture::PixelBufferDescriptor::PixelDataFormat::RGBA, - filament::Texture::PixelBufferDescriptor::PixelDataType::UBYTE, - [](void* buffer, size_t /* size */, void* /* user */) { stbi_image_free(buffer); } - ); - - texture->setImage(*engine, 0, std::move(pbd)); - texture->generateMipmaps(*engine); - - return texture; -} - -//////////////////////////////////////////////////////////////////////////// -Resource TextureLoader::loadTexture(const TextureDefinitions* texture) { - if (!texture) { - spdlog::error("Texture not found"); - return Resource::Error( - "Invalid filament_view texture passed into into loadTexture." - ); - } - - if (!texture->assetPath_.empty()) { - const auto assetPath = ECSManager::GetInstance()->getConfigValue(kAssetPath); - - const auto file_path = getAbsolutePath(texture->assetPath_, assetPath); - if (!isValidFilePath(file_path)) { - spdlog::error("Texture Asset path is invalid: {}", file_path.c_str()); - return Resource::Error("Could not load texture from asset."); - } - const auto loadedTexture = loadTextureFromStream(file_path, texture->type_); - if (!loadedTexture) { - return Resource::Error("Could not load texture from asset on disk."); - } - return Resource::Success(loadedTexture); - } - - if (!texture->url_.empty()) { - return Resource::Error("URL Not implemented."); - /*auto loadedTexture = loadTextureFromUrl(texture->url_, texture->type_); - if(!loadedTexture) { - return Resource<::filament::Texture*>::Error( - "Could not load texture asset from url."); - } - return Resource<::filament::Texture*>::Success(loadedTexture);*/ - } - - spdlog::error("You must provide texture images asset path or url"); - return Resource::Error("You must provide texture images asset path or url."); -} - -//////////////////////////////////////////////////////////////////////////// -filament::Texture* TextureLoader::loadTextureFromStream( - const std::string& file_path, - const TextureDefinitions::TextureType type -) { - return createTextureFromImage(file_path, type); -} - -//////////////////////////////////////////////////////////////////////////// -filament::Texture* TextureLoader::loadTextureFromUrl( - const std::string& url, - const TextureDefinitions::TextureType type -) { - (void)url; - (void)type; - spdlog::error("[{}] Not implemented!", __FUNCTION__); -#if 0 // TODO - plugin_common_curl::CurlClient client; - client.Init(url, {}, {}); - std::vector buffer = client.RetrieveContentAsVector(); - if (client.GetCode() != CURLE_OK) { - spdlog::error("Failed to load texture from {}", url); - return nullptr; - } - const std::string str(buffer.begin(), buffer.end()); - return loadTextureFromStream(str, type); -#endif - return nullptr; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/loader/texture_loader.h b/plugins/filament_view/core/scene/material/loader/texture_loader.h deleted file mode 100644 index 9797b259..00000000 --- a/plugins/filament_view/core/scene/material/loader/texture_loader.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include - -namespace plugin_filament_view { - -class TextureDefinitions; - -class TextureLoader { - public: - TextureLoader(); - ~TextureLoader() = default; - - static Resource<::filament::Texture*> loadTexture(const TextureDefinitions* texture); - - // Disallow copy and assign. - TextureLoader(const TextureLoader&) = delete; - TextureLoader& operator=(const TextureLoader&) = delete; - - private: - static ::filament::Texture* createTextureFromImage( - const std::string& file_path, - TextureDefinitions::TextureType type - ); - - static ::filament::Texture* loadTextureFromStream( - const std::string& file_path, - TextureDefinitions::TextureType type - ); - - static ::filament::Texture* loadTextureFromUrl( - const std::string& url, - TextureDefinitions::TextureType type - ); -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/material_parameter.cc b/plugins/filament_view/core/scene/material/material_parameter.cc deleted file mode 100644 index f0c30b35..00000000 --- a/plugins/filament_view/core/scene/material/material_parameter.cc +++ /dev/null @@ -1,354 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "material_parameter.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -MaterialParameter::MaterialParameter( - std::string name, - const MaterialType type, - MaterialTextureValue value -) - : name_(std::move(name)), - type_(type), - textureValue_(std::move(value)) {} - -//////////////////////////////////////////////////////////////////////////// -MaterialParameter::MaterialParameter( - std::string name, - const MaterialType type, - MaterialFloatValue value -) - : name_(std::move(name)), - type_(type), - fValue_(value) {} - -MaterialParameter::MaterialParameter( - std::string name, - const MaterialType type, - MaterialIntValue value -) - : name_(std::move(name)), - type_(type), - iValue_(value) {} - -MaterialParameter::MaterialParameter( - std::string name, - const MaterialType type, - MaterialColorValue value -) - : name_(std::move(name)), - type_(type), - fVecValue_(MaterialFloatVectorValue(4, 0.0f)) { - memcpy(fVecValue_.value().data(), &value, sizeof(float) * 4); -} - -MaterialParameter::MaterialParameter( - std::string name, - const MaterialType type, - MaterialFloatVectorValue value -) - : name_(std::move(name)), - type_(type), - fVecValue_(std::move(value)) {} - -//////////////////////////////////////////////////////////////////////////// -std::unique_ptr MaterialParameter::Deserialize( - const std::string& /* flutter_assets_path */, - const flutter::EncodableMap& params -) { - SPDLOG_TRACE("++{}", __FUNCTION__); - - std::optional name; - std::optional type; - - std::optional encodMapValue; - std::optional encodListValue; - - std::unique_ptr retval = nullptr; - - for (const auto& [fst, snd] : params) { - auto key = std::get(fst); - if (snd.IsNull()) { - SPDLOG_DEBUG("MaterialParameter Param Second mapping is null {} {}", key, __FUNCTION__); - continue; - } - - const _MaterialField field = GetFieldForText(key); - - switch (field) { - case _MaterialField::NAME: - runtime_assert(std::holds_alternative(snd), "name must be a string"); - name = std::get(snd); - break; - case _MaterialField::TYPE: - runtime_assert(name.has_value(), "name is missing or set after type"); - runtime_assert( - std::holds_alternative(snd), - fmt::format("type must be a string (key: {})", key) - ); - type = getTypeForText(std::get(snd)); - break; - - case _MaterialField::VALUE: - runtime_assert( - type.has_value(), - fmt::format("type is missing or set after value (name: {})", name.value()) - ); - switch (type.value()) { - case MaterialType::FLOAT: - runtime_assert(std::holds_alternative(snd), "value must be a double"); - retval = std::make_unique( - name.value(), type.value(), static_cast(std::get(snd)) - ); - break; - case MaterialType::INT: - runtime_assert(std::holds_alternative(snd), "value must be an int"); - retval = std::make_unique( - name.value(), type.value(), std::get(snd) - ); - break; - case MaterialType::FLOAT2: - [[fallthrough]]; - case MaterialType::FLOAT3: - [[fallthrough]]; - case MaterialType::COLOR: - [[fallthrough]]; - case MaterialType::FLOAT4: { - const size_t size = GetVectorSizeForType(type.value()); - - runtime_assert( - std::holds_alternative(snd), - fmt::format( - "value must be a EncodableList (name: {}, type: {})", // - name.value(), getTextForType(type.value()) - ) - ); - // temporarily store in encodListValue - encodListValue = std::get(snd); - const auto& list = encodListValue.value(); - runtime_assert( - list.size() == size, fmt::format("vector value must have {} elements", size) - ); - for (const auto& item : list) { - runtime_assert( - std::holds_alternative(item), "color value elements must be double" - ); - } - - // create vector with correct length - MaterialFloatVectorValue fvec(size, 0.0f); - float* vec = fvec.data(); - for (size_t i = 0; i < size; ++i) { - vec[i] = static_cast(std::get(list[i])); - } - - retval = std::make_unique(name.value(), type.value(), fvec); - } break; - case MaterialType::TEXTURE: - runtime_assert( - std::holds_alternative(snd), "value must be a map" - ); - encodMapValue = std::get(snd); - retval = std::make_unique( - name.value(), type.value(), TextureDefinitions::Deserialize(encodMapValue.value()) - ); - break; - case MaterialType::BOOL: - runtime_assert(std::holds_alternative(snd), "value must be a bool"); - retval = std::make_unique( - name.value(), type.value(), std::get(snd) - ); - break; - default: - throw std::runtime_error(fmt::format( - "[MaterialParameter::Deserialize] Unhandled Parameter value type {}", - getTextForType(type.value()) - )); - } - break; - case _MaterialField::UNKNOWN: - [[fallthrough]]; - default: - SPDLOG_WARN("[MaterialParameter::Deserialize] unknown key {} {}", key, __FUNCTION__); - break; - } - } - - runtime_assert(retval != nullptr, "Failed to deserialize MaterialParameter"); - return retval; -} - -//////////////////////////////////////////////////////////////////////////// -MaterialParameter::~MaterialParameter() = default; - -//////////////////////////////////////////////////////////////////////////// -void MaterialParameter::debugPrint(const char* tag) { - spdlog::debug("{}name: '{}', type: '{}', ", tag, name_, getTextForType(type_)); - - // Print value based on type - switch (type_) { - case MaterialType::COLOR: - spdlog::debug( - "{}value: [{:.3}, {:.3}, {:.3}, {:.3}]", tag, // - fVecValue_.value()[0], fVecValue_.value()[1], fVecValue_.value()[2], fVecValue_.value()[3] - ); - break; - case MaterialType::FLOAT2: - spdlog::debug( - "{}value: [{:.3}, {:.3}]", tag, // - fVecValue_.value()[0], fVecValue_.value()[1] - ); - break; - case MaterialType::FLOAT3: - spdlog::debug( - "{}value: [{:.3}, {:.3}, {:.3}]", tag, // - fVecValue_.value()[0], fVecValue_.value()[1], fVecValue_.value()[2] - ); - break; - case MaterialType::FLOAT4: - spdlog::debug( - "{}value: [{:.3}, {:.3}, {:.3}, {:.3}]", tag, // - fVecValue_.value()[0], fVecValue_.value()[1], fVecValue_.value()[2], fVecValue_.value()[3] - ); - break; - case MaterialType::FLOAT: - spdlog::debug( - "{}value: {:.3}", tag, // - fValue_.value() - ); - break; - case MaterialType::INT: - spdlog::debug( - "{}value: {}", tag, // - iValue_.value() - ); - break; - case MaterialType::TEXTURE: { - if (textureValue_.has_value()) { - const auto texture = - std::get>(textureValue_.value()).get(); - if (texture) { - texture->debugPrint(std::string(tag + std::string(" texture:")).c_str()); - } - } else { - spdlog::debug("{}value: ", tag); - } - } break; - default: - spdlog::debug("{}value: ", tag); - break; - } -} - -//////////////////////////////////////////////////////////////////////////// -const char* MaterialParameter::getTextForType(MaterialType type) { - return (const char*[]){ - "COLOR", "BOOL", "BOOL_VECTOR", "FLOAT", "FLOAT2", "FLOAT3", - "FLOAT4", "INT", "INT_VECTOR", "MAT3", "MAT4", "TEXTURE", - }[static_cast(type)]; -} - -//////////////////////////////////////////////////////////////////////////// -MaterialParameter::MaterialType MaterialParameter::getTypeForText(const std::string& type) { - // TODO Change to map for faster lookup - if (type == "COLOR") { - return MaterialType::COLOR; - } - if (type == "BOOL") { - return MaterialType::BOOL; - } - if (type == "BOOL_VECTOR") { - return MaterialType::BOOL_VECTOR; - } - if (type == "FLOAT") { - return MaterialType::FLOAT; - } - if (type == "FLOAT2") { - return MaterialType::FLOAT2; - } - if (type == "FLOAT3") { - return MaterialType::FLOAT3; - } - if (type == "FLOAT4") { - return MaterialType::FLOAT4; - } - if (type == "INT") { - return MaterialType::INT; - } - if (type == "INT_VECTOR") { - return MaterialType::INT_VECTOR; - } - if (type == "MAT3") { - return MaterialType::MAT3; - } - if (type == "MAT4") { - return MaterialType::MAT4; - } - if (type == "TEXTURE") { - return MaterialType::TEXTURE; - } - return MaterialType::INT; -} - -//////////////////////////////////////////////////////////////////////////// -MaterialColorValue MaterialParameter::HexToColorFloat4(const std::string& hex) { - // Ensure the string starts with '#' and is the correct length - if (hex[0] != '#' || hex.length() != 9) { - throw std::invalid_argument("Invalid hex color format: " + hex); - } - - // Comes across from our dart as ARGB - - // Extract the hex values for each channel - unsigned int r, g, b, a; - std::stringstream ss; - ss << std::hex << hex.substr(1, 2); - ss >> a; - ss.clear(); - ss << std::hex << hex.substr(3, 2); - ss >> r; - ss.clear(); - ss << std::hex << hex.substr(5, 2); - ss >> g; - ss.clear(); - ss << std::hex << hex.substr(7, 2); - ss >> b; - - // Convert to float in the range [0, 1] - MaterialColorValue color; - color.r = static_cast(r) / 255.0f; - color.g = static_cast(g) / 255.0f; - color.b = static_cast(b) / 255.0f; - color.a = static_cast(a) / 255.0f; - - return color; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/material_parameter.h b/plugins/filament_view/core/scene/material/material_parameter.h deleted file mode 100644 index 066240fc..00000000 --- a/plugins/filament_view/core/scene/material/material_parameter.h +++ /dev/null @@ -1,190 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "texture/texture_definitions.h" -#include "texture/texture_sampler.h" - -#include -#include - -#include - -#define _MATPARAM_VEC_MAX_SIZE 4 - -namespace plugin_filament_view { - -class TextureDefinitions; - -class TextureSampler; - -using MaterialTextureValue = std::variant>; -using MaterialFloatValue = float; -using MaterialIntValue = int32_t; -using MaterialBoolValue = bool; -using MaterialColorValue = ::filament::math::vec4; -using MaterialFloatVectorValue = std::vector; - -class MaterialParameter { - private: - enum class _MaterialField { NAME, TYPE, VALUE, UNKNOWN }; - - public: - enum class MaterialType { - // color can be presented by int or Color like Colors.white - COLOR, - BOOL, - BOOL_VECTOR, - FLOAT, - FLOAT2, - FLOAT3, - FLOAT4, - INT, - INT_VECTOR, - MAT3, - MAT4, - TEXTURE, - }; - - MaterialParameter(std::string name, const MaterialType type, MaterialTextureValue value); - MaterialParameter(std::string name, const MaterialType type, MaterialFloatValue value); - MaterialParameter(std::string name, const MaterialType type, MaterialIntValue value); - MaterialParameter(std::string name, const MaterialType type, MaterialColorValue value); - MaterialParameter(std::string name, const MaterialType type, MaterialFloatVectorValue value); - - static std::unique_ptr Deserialize( - const std::string& flutter_assets_path, - const flutter::EncodableMap& params - ); - - ~MaterialParameter(); - - void debugPrint(const char* tag); - - [[nodiscard]] std::string szGetParameterName() const { return name_; } - - friend class Material; - friend class MaterialDefinitions; - - [[nodiscard]] const MaterialTextureValue& getTextureValue() const { - if (textureValue_.has_value()) { - return textureValue_.value(); - } else { - throw std::runtime_error("MaterialParameter does not contain a texture value."); - } - } - - [[nodiscard]] TextureSampler* getTextureSampler() const { - const auto& textureValue = getTextureValue(); - const auto& texturePtr = std::get>(textureValue); - - if (!texturePtr) { - return nullptr; - } - - return texturePtr->getSampler(); - } - - [[nodiscard]] std::string getTextureValueAssetPath() const { - const auto& textureValue = getTextureValue(); - const auto& texturePtr = std::get>(textureValue); - - if (!texturePtr) { - return ""; - } - - return texturePtr->szGetTextureDefinitionLookupName(); - } - - [[nodiscard]] std::unique_ptr clone() const { - switch (type_) { - case MaterialType::FLOAT2: - [[fallthrough]]; - case MaterialType::FLOAT3: - [[fallthrough]]; - case MaterialType::FLOAT4: - [[fallthrough]]; - case MaterialType::COLOR: - return std::make_unique(name_, type_, fVecValue_.value()); - case MaterialType::FLOAT: - return std::make_unique(name_, type_, fValue_.value()); - case MaterialType::TEXTURE: - if (textureValue_.has_value()) { - const auto& textureValue = textureValue_.value(); - const auto& texturePtr = std::get>(textureValue); - if (texturePtr) { - // Assuming TextureDefinitions has a clone method - return std::make_unique(name_, type_, texturePtr->clone()); - } - } - break; - case MaterialType::INT: - break; - // Handle other types (BOOL, BOOL_VECTOR, INT, etc.) - case MaterialType::BOOL: - // TODO: Add cloning logic for these types - default: - throw std::runtime_error("Unsupported MaterialType in clone."); - } - return nullptr; // In case of unsupported type or missing value. - } - - private: - std::string name_; - MaterialType type_; - std::optional textureValue_; - std::optional fValue_; - std::optional fVecValue_; - std::optional iValue_; - std::optional bValue_; - - // TODO delete this, colorOf functionality exists in base filament. - static MaterialColorValue HexToColorFloat4(const std::string& hex); - - static const char* getTextForType(MaterialType type); - - static MaterialType getTypeForText(const std::string& type); - - static _MaterialField GetFieldForText(const std::string& field) { - if (field == "name") { - return _MaterialField::NAME; - } - if (field == "type") { - return _MaterialField::TYPE; - } - if (field == "value") { - return _MaterialField::VALUE; - } - return _MaterialField::UNKNOWN; - } - - static size_t GetVectorSizeForType(MaterialType type) { - switch (type) { - case MaterialType::COLOR: - [[fallthrough]]; - case MaterialType::FLOAT4: - return 4; - case MaterialType::FLOAT3: - return 3; - case MaterialType::FLOAT2: - return 2; - default: - return 1; - } - } -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/enums/mag_filter.h b/plugins/filament_view/core/scene/material/texture/enums/mag_filter.h deleted file mode 100644 index 0c774fed..00000000 --- a/plugins/filament_view/core/scene/material/texture/enums/mag_filter.h +++ /dev/null @@ -1,24 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -namespace plugin_filament_view { - -static constexpr char kMagFilterNearest[] = "NEAREST"; -static constexpr char kMagFilterLinear[] = "LINEAR"; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/enums/min_filter.h b/plugins/filament_view/core/scene/material/texture/enums/min_filter.h deleted file mode 100644 index a0574f2d..00000000 --- a/plugins/filament_view/core/scene/material/texture/enums/min_filter.h +++ /dev/null @@ -1,28 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -namespace plugin_filament_view { - -static constexpr char kMinFilterNearest[] = "NEAREST"; -static constexpr char kMinFilterLinear[] = "LINEAR"; -static constexpr char kMinFilterNearestMipmapNearest[] = "NEAREST_MIPMAP_NEAREST"; -static constexpr char kMinFilterLinearMipmapNearest[] = "LINEAR_MIPMAP_NEAREST"; -static constexpr char kMinFilterNearestMipmapLinear[] = "NEAREST_MIPMAP_LINEAR"; -static constexpr char kMinFilterLinearMipmapLinear[] = "LINEAR_MIPMAP_LINEAR"; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/enums/wrap_mode.h b/plugins/filament_view/core/scene/material/texture/enums/wrap_mode.h deleted file mode 100644 index a60f35ed..00000000 --- a/plugins/filament_view/core/scene/material/texture/enums/wrap_mode.h +++ /dev/null @@ -1,25 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -namespace plugin_filament_view { - -static constexpr char KWrapModeClampToEdge[] = "CLAMP_TO_EDGE"; -static constexpr char KWrapModeRepeat[] = "REPEAT"; -static constexpr char KWrapModeMirroredRepeat[] = "MIRRORED_REPEAT"; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/texture_definitions.cc b/plugins/filament_view/core/scene/material/texture/texture_definitions.cc deleted file mode 100644 index 8c125f8f..00000000 --- a/plugins/filament_view/core/scene/material/texture/texture_definitions.cc +++ /dev/null @@ -1,136 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "texture_definitions.h" - -#include -#include - -namespace plugin_filament_view { - -static constexpr char kTypeColor[] = "COLOR"; -static constexpr char kTypeNormal[] = "NORMAL"; -static constexpr char kTypeData[] = "DATA"; - -//////////////////////////////////////////////////////////////////////////// -TextureDefinitions::TextureDefinitions( - const TextureType type, - std::string assetPath, - std::string url, - TextureSampler* sampler -) - : assetPath_(std::move(assetPath)), - url_(std::move(url)), - type_(type), - sampler_(sampler) {} - -//////////////////////////////////////////////////////////////////////////// -std::string TextureDefinitions::szGetTextureDefinitionLookupName() const { - if (!assetPath_.empty()) { - return assetPath_; - } - if (!url_.empty()) { - return url_; - } - return "Unknown"; -} - -//////////////////////////////////////////////////////////////////////////// -std::unique_ptr TextureDefinitions::Deserialize( - const flutter::EncodableMap& params -) { - SPDLOG_TRACE("++Texture::Texture"); - std::optional assetPath; - std::optional url; - std::optional type; - std::optional> sampler; - - for (const auto& [fst, snd] : params) { - if (snd.IsNull()) continue; - - auto key = std::get(fst); - if (key == "assetPath" && std::holds_alternative(snd)) { - assetPath = std::get(snd); - } else if (key == "url" && std::holds_alternative(snd)) { - url = std::get(snd); - } else if (key == "type" && std::holds_alternative(snd)) { - if (auto decodedType = getType(std::get(snd)); decodedType != UNKNOWN) { - type = decodedType; - } - } else if (key == "sampler" && std::holds_alternative(snd)) { - sampler = std::make_unique(std::get(snd)); - } else if (!snd.IsNull()) { - spdlog::debug("[Texture] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - if (!type.has_value()) { - spdlog::error("[Texture] missing type"); - return nullptr; - } - - SPDLOG_TRACE("--Texture::Texture"); - return std::make_unique( - type.value(), assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - sampler.has_value() ? sampler.value().get() : nullptr - ); -} - -//////////////////////////////////////////////////////////////////////////// -void TextureDefinitions::debugPrint(const char* tag) { - spdlog::debug("++++++++ (Texture) ++++++++"); - spdlog::debug("{} ", tag); - if (!assetPath_.empty()) { - spdlog::debug("assetPath: [{}]", assetPath_); - } - if (!url_.empty()) { - spdlog::debug("url: [{}]", url_); - } - spdlog::debug("type: {}", getTextForType(type_)); - if (sampler_) { - // TODO CRASH - // sampler_->Print("\t\tsampler"); - } - spdlog::debug("-------- (Texture) --------"); -} - -//////////////////////////////////////////////////////////////////////////// -TextureDefinitions::TextureType TextureDefinitions::getType(const std::string& type) { - if (type == kTypeColor) { - return COLOR; - } - if (type == kTypeNormal) { - return NORMAL; - } - if (type == kTypeData) { - return DATA; - } - - spdlog::warn("{}::{} - unknown type {}", __FUNCTION__, __LINE__, type.c_str()); - return UNKNOWN; -} - -//////////////////////////////////////////////////////////////////////////// -const char* TextureDefinitions::getTextForType(const TextureType type) { - return (const char*[]){ - kTypeColor, - kTypeNormal, - kTypeData, - }[type]; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/texture_definitions.h b/plugins/filament_view/core/scene/material/texture/texture_definitions.h deleted file mode 100644 index 7fe5cb4d..00000000 --- a/plugins/filament_view/core/scene/material/texture/texture_definitions.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" -#include "texture_sampler.h" - -#include - -namespace plugin_filament_view { -class TextureDefinitions { - public: - enum TextureType { - UNKNOWN, - COLOR, - NORMAL, - DATA, - }; - - TextureDefinitions( - TextureType type, - std::string assetPath, - std::string url, - TextureSampler* sampler - ); - - ~TextureDefinitions() = default; - - static std::unique_ptr Deserialize(const flutter::EncodableMap& params); - - void debugPrint(const char* tag); - - static TextureType getType(const std::string& type); - - static const char* getTextForType(TextureType type); - - friend class TextureLoader; - friend class MaterialSystem; - - // this will either get the assetPath or the url, priority of assetPath - // looking for which is valid. Used to see if we have this loaded in cache. - [[nodiscard]] std::string szGetTextureDefinitionLookupName() const; - - TextureSampler* getSampler() { return sampler_; } - - [[nodiscard]] std::unique_ptr clone() const { - return std::make_unique(type_, assetPath_, url_, sampler_); - } - - private: - std::string assetPath_; - std::string url_; - TextureType type_; - TextureSampler* sampler_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/texture_sampler.cc b/plugins/filament_view/core/scene/material/texture/texture_sampler.cc deleted file mode 100644 index 19724e04..00000000 --- a/plugins/filament_view/core/scene/material/texture/texture_sampler.cc +++ /dev/null @@ -1,155 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "texture_sampler.h" -#include "enums/mag_filter.h" -#include "enums/min_filter.h" -#include "enums/wrap_mode.h" - -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -TextureSampler::TextureSampler(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++TextureSampler::TextureSampler"); - for (const auto& [fst, snd] : params) { - if (snd.IsNull()) continue; - - auto key = std::get(fst); - if (key == "min" && std::holds_alternative(snd)) { - min_ = std::get(snd); - } else if (key == "mag" && std::holds_alternative(snd)) { - mag_ = std::get(snd); - } else if (key == "wrap" && std::holds_alternative(snd)) { - wrapR_ = std::get(snd); - wrapS_ = std::get(snd); - wrapT_ = std::get(snd); - } else if (key == "wrapR" && std::holds_alternative(snd)) { - wrapR_ = std::get(snd); - } else if (key == "wrapS" && std::holds_alternative(snd)) { - wrapS_ = std::get(snd); - } else if (key == "wrapT" && std::holds_alternative(snd)) { - wrapT_ = std::get(snd); - } else if (key == "anisotropy" && std::holds_alternative(snd)) { - anisotropy_ = std::get(snd); - } else if (!snd.IsNull()) { - spdlog::debug("[TextureSampler] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - SPDLOG_TRACE("--TextureSampler::TextureSampler"); -} - -//////////////////////////////////////////////////////////////////////////// -filament::TextureSampler::MagFilter TextureSampler::getMagFilter() const { - if (mag_ == kMagFilterNearest) { - return filament::TextureSampler::MagFilter::NEAREST; - } - return filament::TextureSampler::MagFilter::LINEAR; -} - -//////////////////////////////////////////////////////////////////////////// -filament::TextureSampler::MinFilter TextureSampler::getMinFilter() const { - if (min_ == kMinFilterNearest) { - return filament::TextureSampler::MinFilter::NEAREST; - } - - if (min_ == kMinFilterLinear) { - return filament::TextureSampler::MinFilter::LINEAR; - } - - if (min_ == kMinFilterNearestMipmapNearest) { - return filament::TextureSampler::MinFilter::NEAREST_MIPMAP_NEAREST; - } - - if (min_ == kMinFilterLinearMipmapNearest) { - return filament::TextureSampler::MinFilter::LINEAR_MIPMAP_NEAREST; - } - - if (min_ == kMinFilterNearestMipmapLinear) { - return filament::TextureSampler::MinFilter::NEAREST_MIPMAP_LINEAR; - } - - // Note: might need to change default in the future. - return filament::TextureSampler::MinFilter::LINEAR_MIPMAP_LINEAR; -} - -//////////////////////////////////////////////////////////////////////////// -filament::TextureSampler::WrapMode TextureSampler::getWrapModeR() const { - if (wrapR_ == KWrapModeClampToEdge) { - return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE; - } - - if (wrapR_ == KWrapModeRepeat) { - return filament::TextureSampler::WrapMode::REPEAT; - } - - return filament::TextureSampler::WrapMode::MIRRORED_REPEAT; -} - -//////////////////////////////////////////////////////////////////////////// -filament::TextureSampler::WrapMode TextureSampler::getWrapModeS() const { - if (wrapS_ == KWrapModeClampToEdge) { - return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE; - } - - if (wrapS_ == KWrapModeRepeat) { - return filament::TextureSampler::WrapMode::REPEAT; - } - - return filament::TextureSampler::WrapMode::MIRRORED_REPEAT; -} - -//////////////////////////////////////////////////////////////////////////// -filament::TextureSampler::WrapMode TextureSampler::getWrapModeT() const { - if (wrapT_ == KWrapModeClampToEdge) { - return filament::TextureSampler::WrapMode::CLAMP_TO_EDGE; - } - - if (wrapT_ == KWrapModeRepeat) { - return filament::TextureSampler::WrapMode::REPEAT; - } - - return filament::TextureSampler::WrapMode::MIRRORED_REPEAT; -} - -//////////////////////////////////////////////////////////////////////////// -void TextureSampler::debugPrint(const char* tag) { - spdlog::debug("++++++++"); - spdlog::debug("{} (TextureSampler)", tag); - if (!min_.empty()) { - spdlog::debug("\tmin: [{}]", min_); - } - if (!mag_.empty()) { - spdlog::debug("\tmag: [{}]", mag_); - } - if (!wrapR_.empty()) { - spdlog::debug("\twrapR: [{}]", wrapR_); - } - if (!wrapS_.empty()) { - spdlog::debug("\twrapS: [{}]", wrapS_); - } - if (!wrapT_.empty()) { - spdlog::debug("\twrapT: [{}]", wrapT_); - } - if (anisotropy_.has_value()) { - spdlog::debug("\tanisotropy: [{}]", anisotropy_.value()); - } - spdlog::debug("++++++++"); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/material/texture/texture_sampler.h b/plugins/filament_view/core/scene/material/texture/texture_sampler.h deleted file mode 100644 index 229212ea..00000000 --- a/plugins/filament_view/core/scene/material/texture/texture_sampler.h +++ /dev/null @@ -1,54 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include -#include - -namespace plugin_filament_view { - -class TextureSampler { - public: - explicit TextureSampler(const flutter::EncodableMap& params); - - void debugPrint(const char* tag); - - // Disallow copy and assign. - TextureSampler(const TextureSampler&) = delete; - - TextureSampler& operator=(const TextureSampler&) = delete; - - [[nodiscard]] ::filament::TextureSampler::MagFilter getMagFilter() const; - [[nodiscard]] ::filament::TextureSampler::MinFilter getMinFilter() const; - [[nodiscard]] ::filament::TextureSampler::WrapMode getWrapModeR() const; - [[nodiscard]] ::filament::TextureSampler::WrapMode getWrapModeS() const; - [[nodiscard]] ::filament::TextureSampler::WrapMode getWrapModeT() const; - [[nodiscard]] double getAnisotropy() const { - return anisotropy_.has_value() ? anisotropy_.value() : 1; - } - - private: - std::string min_; - std::string mag_; - std::string wrapR_; - std::string wrapS_; - std::string wrapT_; - std::optional anisotropy_{}; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/serialization/scene_text_deserializer.cc b/plugins/filament_view/core/scene/serialization/scene_text_deserializer.cc deleted file mode 100644 index a1cddd8a..00000000 --- a/plugins/filament_view/core/scene/serialization/scene_text_deserializer.cc +++ /dev/null @@ -1,427 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "scene_text_deserializer.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include "shell/platform/common/client_wrapper/include/flutter/standard_message_codec.h" - -namespace plugin_filament_view { - -////////////////////////////////////////////////////////////////////////////////////////// -SceneTextDeserializer::SceneTextDeserializer(const std::vector& params) - : _ecs(nullptr) { - _ecs = ECSManager::GetInstance(); - const std::string& flutterAssetsPath = _ecs->getConfigValue(kAssetPath); - - // kick off process... - spdlog::debug("[{}] deserializing root...", __FUNCTION__); - DeserializeRootLevel(params, flutterAssetsPath); - spdlog::debug("[{}] deserializing root done!", __FUNCTION__); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::DeserializeRootLevel( - const std::vector& params, - const std::string& /* flutterAssetsPath */ -) { - auto& codec = flutter::StandardMessageCodec::GetInstance(); - const auto decoded = codec.DecodeMessage(params.data(), params.size()); - const auto& creationParams = std::get_if(decoded.get()); - - for (const auto& [fst, snd] : *creationParams) { - auto key = std::get(fst); - if (snd.IsNull()) { - SPDLOG_DEBUG("DeserializeRootLevel ITER is null {} {}", key.c_str(), __FUNCTION__); - continue; - } - - if (key == kModels && std::holds_alternative(snd)) { - spdlog::debug("===== Deserializing Multiple Models {} ...", key); - - auto list = std::get(snd); - for (const auto& iter : list) { - if (iter.IsNull()) { - spdlog::warn("CreationParamName unable to cast {}", key.c_str()); - continue; - } - auto deserializedModel = Model::Deserialize(std::get(iter)); - if (deserializedModel == nullptr) { - spdlog::error("Unable to load model"); - continue; - } - models_.emplace_back(std::move(deserializedModel)); - } - - spdlog::debug("Deserialized {} models", models_.size()); - } else if (key == kScene) { - spdlog::debug("===== Deserializing Scene {} ...", key); - DeserializeSceneLevel(snd); - } else if (key == kShapes && std::holds_alternative(snd)) { - auto list = std::get(snd); - - spdlog::debug("===== Deserializing multiple Shapes {} ...", key); - for (const auto& iter : list) { - if (iter.IsNull()) { - SPDLOG_DEBUG("CreationParamName unable to cast {}", key.c_str()); - continue; - } - - auto deserializedShape = ShapeSystem::poDeserializeShapeFromData( - std::get(iter) - ); - - shapes_.emplace_back(std::move(deserializedShape)); - } - - spdlog::debug("Deserialized {} shapes", shapes_.size()); - } else if (key == kCameras) { - spdlog::debug("===== Deserializing Cameras {} ...", key); - auto list = std::get(snd); - - for (const auto& iter : list) { - if (iter.IsNull()) { - spdlog::warn("CreationParamName unable to cast {}", key.c_str()); - continue; - } - - // Deserialize entity - auto cameraEntity = std::make_shared(std::get(iter)); - - // Deserialize transform component - cameraEntity->addComponent(Transform(std::get(iter))); - - // Deserialize camera component - cameraEntity->addComponent(Camera(std::get(iter))); - - entities_.emplace_back(std::move(cameraEntity)); - } - - spdlog::debug("Deserialized {} cameras", entities_.size()); - } else if (key == kSkybox) { - skybox_ = Skybox::Deserialize(std::get(snd)); - } else if (key == kIndirectLight) { - indirect_light_ = IndirectLight::Deserialize(std::get(snd)); - } else { - spdlog::warn("[SceneTextDeserializer] Unhandled Parameter {}", key.c_str()); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::DeserializeSceneLevel(const flutter::EncodableValue& params) { - for (const auto& [fst, snd] : std::get(params)) { - auto key = std::get(fst); - if (snd.IsNull()) { - SPDLOG_WARN("DeserializeSceneLevel Param ITER is null key:{} function:{}", key, __FUNCTION__); - continue; - } - - if (key == kLights && std::holds_alternative(snd)) { - auto list = std::get(snd); - for (const auto& iter : list) { - if (iter.IsNull()) { - spdlog::warn("CreationParamName unable to cast {}", key.c_str()); - continue; - } - - auto encodableMap = std::get(iter); - - // This will get placed on an entity - EntityGUID overWriteGuid; - Deserialize::DecodeParameterWithDefaultInt64( - kGuid, &overWriteGuid, encodableMap, kNullGuid - ); - - if (overWriteGuid == kNullGuid) { - spdlog::warn("Light is missing a GUID, will not add to scene"); - continue; - } - - lights_.insert(std::pair(overWriteGuid, std::make_shared(encodableMap))); - } - - continue; - } - - // everything in this loop looks to make sure its a map, we can continue - // on if its not. - if (!std::holds_alternative(snd)) { - continue; - } - - auto encodableMap = std::get(snd); - - SPDLOG_DEBUG("KEY {} ", key); - - if (key == kSkybox) { - skybox_ = Skybox::Deserialize(encodableMap); - } else if (key == kIndirectLight) { - indirect_light_ = IndirectLight::Deserialize(encodableMap); - } else if (!snd.IsNull()) { - spdlog::debug("[SceneTextDeserializer] Unhandled Parameter {}", key.c_str()); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::RunPostSetupLoad() { - spdlog::debug("Running post setup load..."); - - spdlog::trace("setUpLoadingModels"); - setUpLoadingModels(); - spdlog::trace("setUpSkybox"); - setUpSkybox(); - spdlog::trace("setUpLights"); - setUpLights(); - spdlog::trace("setUpIndirectLight"); - setUpIndirectLight(); - spdlog::trace("setUpShapes"); - setUpShapes(); - spdlog::trace("setUpEntities"); - setUpEntities(); - - spdlog::debug("setups done!"); - - indirect_light_.reset(); - skybox_.reset(); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::setUpLoadingModels() { - SPDLOG_TRACE("++{}", __FUNCTION__); - - for (auto& iter : models_) { - // Note: Instancing or prefab of models is not currently supported but might - // affect the loading process here in the future. Backlogged. - // - // This will transfer ownership - loadModel(iter); - } - - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::setUpShapes() { - spdlog::debug("{} {}", __FUNCTION__, __LINE__); - - spdlog::trace("getting systems"); - const auto shapeSystem = _ecs->getSystem("setUpShapes"); - const auto collisionSystem = _ecs->getSystem("setUpShapes"); - - if (shapeSystem == nullptr || collisionSystem == nullptr) { - throw std::runtime_error("[SceneTextDeserializer] Error.ShapeSystem or collisionSystem is null" - ); - } - - for (const auto& shape : shapes_) { - spdlog::trace("Adding shape to scene {}", shape->getGuid()); - _ecs->addEntity(shape); - /// TODO: fix shape colliders - // spdlog::trace("Adding collider..."); - // if (shape->hasComponent()) { - // spdlog::trace("Shape {} has collider! Adding to collision system", - // shape->getGuid()); if (collisionSystem != nullptr) { - // collisionSystem->AddCollidable(shape.get()); - // } - // } - // spdlog::trace("Collider added!"); - } - - spdlog::debug("Shape setup done, adding to scene"); - - shapeSystem->addShapesToScene(&shapes_); - - shapes_.clear(); -} - -void SceneTextDeserializer::setUpEntities() { - spdlog::debug("{} {}", __FUNCTION__, __LINE__); - - const auto viewTargetSystem = _ecs->getSystem("setUpEntities"); - - // For each entity - for (const auto& entity : entities_) { - const auto entityGuid = entity->getGuid(); - // Add the entity to the ECS - spdlog::trace("Adding entity '{}'({}) to ECS", entity->name, entityGuid); - _ecs->addEntity(entity); - - // If camera, use ViewTargetSystem to set it up - if (_ecs->hasComponent(entityGuid)) { - viewTargetSystem->initializeEntity(entityGuid); - spdlog::trace("Camera '{}'({}) initialized", entity->name, entityGuid); - } - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::loadModel(std::shared_ptr& model) { - const auto& strand = *_ecs->getStrand(); - - post(strand, [model = std::move(model)]() mutable { - const auto modelSystem = ECSManager::GetInstance()->getSystem("loadModel"); - - if (modelSystem == nullptr) { - spdlog::error("Unable to find the model system."); - return; - } - - const Model* glb_model = dynamic_cast(model.get()); - if (!glb_model->getAssetPath().empty()) { - modelSystem->queueModelLoad(std::move(model)); - } else { - spdlog::error("Model has no asset path, unable to load"); - } - - spdlog::trace("[loadModel] Model {} queued for loading", glb_model->getAssetPath()); - }); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::setUpSkybox() const { - // Todo move to a message. - - auto skyboxSystem = ECSManager::GetInstance()->getSystem(__FUNCTION__); - - if (!skybox_) { - skyboxSystem->setDefaultSkybox(); - // makeSurfaceViewTransparent(); - } else { - if (const auto skybox = skybox_.get(); dynamic_cast(skybox)) { - if (const auto hdr_skybox = dynamic_cast(skybox); - !hdr_skybox->getAssetPath().empty()) { - const auto shouldUpdateLight = hdr_skybox->getAssetPath() - == indirect_light_->getAssetPath(); - - skyboxSystem->setSkyboxFromHdrAsset( - hdr_skybox->getAssetPath(), hdr_skybox->getShowSun(), shouldUpdateLight, - indirect_light_->getIntensity() - ); - } else if (!skybox->getUrl().empty()) { - const auto shouldUpdateLight = hdr_skybox->szGetURLPath() == indirect_light_->getUrl(); - skyboxSystem->setSkyboxFromHdrUrl( - hdr_skybox->szGetURLPath(), hdr_skybox->getShowSun(), shouldUpdateLight, - indirect_light_->getIntensity() - ); - } - } else if (dynamic_cast(skybox)) { - if (const auto kxt_skybox = dynamic_cast(skybox); - !kxt_skybox->getAssetPath().empty()) { - skyboxSystem->setSkyboxFromKTXAsset(kxt_skybox->getAssetPath()); - } else if (!kxt_skybox->szGetURLPath().empty()) { - skyboxSystem->setSkyboxFromKTXUrl(kxt_skybox->szGetURLPath()); - } - } else if (dynamic_cast(skybox)) { - if (const auto color_skybox = dynamic_cast(skybox); - color_skybox->getColor().w > 0) { - skyboxSystem->setSkyboxFromColor(color_skybox->getColor()); - } - } - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::setUpLights() { - const auto lightSystem = _ecs->getSystem(__FUNCTION__); - - // Note, this introduces a fire and forget functionality for entities - // there's no "one" owner system, but its propagated to whomever cares for it. - for (const auto& [fst, snd] : lights_) { - const auto newEntity = std::make_shared( - "SceneTextDeserializer::setUpLights", fst - ); - - _ecs->addEntity(newEntity); - _ecs->addComponent(newEntity->getGuid(), snd); - - lightSystem->BuildLightAndAddToScene(*snd); - } - - // if a light didnt get deserialized, tell light system to create a default - // one. - if (lights_.empty()) { - SPDLOG_DEBUG("No lights found, creating default light"); - lightSystem->CreateDefaultLight(); - } - - lights_.clear(); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void SceneTextDeserializer::setUpIndirectLight() const { - // Todo move to a message. - auto indirectlightSystem = ECSManager::GetInstance()->getSystem(__FUNCTION__ - ); - - if (!indirect_light_) { - // This was called in the constructor of indirectLightManager_ anyway. - // plugin_filament_view::indirectlightSystem->setDefaultIndirectLight(); - } else { - if (const auto indirectLight = indirect_light_.get(); - dynamic_cast(indirectLight)) { - if (!indirectLight->getAssetPath().empty()) { - indirectlightSystem->setIndirectLightFromKtxAsset( - indirectLight->getAssetPath(), indirectLight->getIntensity() - ); - } else if (!indirectLight->getUrl().empty()) { - indirectlightSystem->setIndirectLightFromKtxUrl( - indirectLight->getAssetPath(), indirectLight->getIntensity() - ); - } - } else if (dynamic_cast(indirectLight)) { - if (!indirectLight->getAssetPath().empty()) { - // val shouldUpdateLight = indirectLight->getAssetPath() != - // scene?.skybox?.assetPath if (shouldUpdateLight) { - indirectlightSystem->setIndirectLightFromHdrAsset( - indirectLight->getAssetPath(), indirectLight->getIntensity() - ); - //} - - } else if (!indirectLight->getUrl().empty()) { - // auto shouldUpdateLight = indirectLight->getUrl() != - // scene?.skybox?.url; - // if (shouldUpdateLight) { - indirectlightSystem->setIndirectLightFromHdrUrl( - indirectLight->getUrl(), indirectLight->getIntensity() - ); - //} - } - } else if (dynamic_cast(indirectLight)) { - indirectlightSystem->setIndirectLight(dynamic_cast(indirectLight)); - } else { - // Already called in the default constructor. - // plugin_filament_view::indirectlightSystem->setDefaultIndirectLight(); - } - } -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/serialization/scene_text_deserializer.h b/plugins/filament_view/core/scene/serialization/scene_text_deserializer.h deleted file mode 100644 index 548a0d31..00000000 --- a/plugins/filament_view/core/scene/serialization/scene_text_deserializer.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#ifndef SCENE_TEXT_DESERIALIZER_H -#define SCENE_TEXT_DESERIALIZER_H - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { -class Light; - -class SceneTextDeserializer { - public: - explicit SceneTextDeserializer(const std::vector& params); - void RunPostSetupLoad(); - - virtual ~SceneTextDeserializer() = default; - - private: - smarter_raw_ptr _ecs; - - std::vector> models_; - std::vector> shapes_; - - std::vector> entities_; - - void DeserializeRootLevel( - const std::vector& params, - const std::string& flutterAssetsPath - ); - // This is called from DeserializeRootLevel function when it hits a 'scene' - // tag - void DeserializeSceneLevel(const flutter::EncodableValue& params); - - void setUpLoadingModels(); - void setUpSkybox() const; - void setUpLights(); - void setUpIndirectLight() const; - void setUpShapes(); - void setUpEntities(); - - void loadModel(std::shared_ptr& model); - - std::unique_ptr skybox_; - std::unique_ptr indirect_light_; - std::map> lights_; -}; - -} // namespace plugin_filament_view - -#endif // SCENE_TEXT_DESERIALIZER_H diff --git a/plugins/filament_view/core/scene/skybox/skybox.cc b/plugins/filament_view/core/scene/skybox/skybox.cc deleted file mode 100644 index 870f52e3..00000000 --- a/plugins/filament_view/core/scene/skybox/skybox.cc +++ /dev/null @@ -1,86 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "skybox.h" - -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -Skybox::Skybox(std::string assetPath, std::string url, filament::math::float4 color) - : assetPath_(std::move(assetPath)), - url_(std::move(url)), - color_(color) {} - -//////////////////////////////////////////////////////////////////////////// -std::unique_ptr Skybox::Deserialize(const flutter::EncodableMap& params) { - SPDLOG_TRACE("++Skybox::Skybox"); - std::optional assetPath; - std::optional url; - std::optional color; - std::optional showSun; - std::optional skyboxType; - - for (const auto& [fst, snd] : params) { - if (snd.IsNull()) continue; - - auto key = std::get(fst); - if (key == "assetPath" && std::holds_alternative(snd)) { - assetPath = std::get(snd); - } else if (key == "url" && std::holds_alternative(snd)) { - url = std::get(snd); - } else if (key == "color" && std::holds_alternative>(snd)) { - const auto& colorList = std::get>(snd); - color = filament::math::float4( - static_cast(colorList[0]), // - static_cast(colorList[1]), // - static_cast(colorList[2]), // - static_cast(colorList[3]) // - ); - } else if (key == "showSun" && std::holds_alternative(snd)) { - showSun = std::get(snd); - } else if (key == "skyboxType" && std::holds_alternative(snd)) { - skyboxType = std::get(snd); - } else if (!snd.IsNull()) { - spdlog::debug("[SkyBox] Unhandled Parameter"); - plugin_common::Encodable::PrintFlutterEncodableValue(key.c_str(), snd); - } - } - - if (skyboxType.has_value()) { - switch (skyboxType.value()) { - case 1: - spdlog::debug("[Skybox] Type: KxtSkybox"); - return std::make_unique(assetPath, url); - case 2: - spdlog::debug("[Skybox] Type: HdrSkybox"); - return std::make_unique(assetPath, url, showSun); - case 3: - spdlog::debug("[Skybox] Type: ColorSkybox"); - return std::make_unique(assetPath, url, color); - default: - spdlog::error("[IndirectLight] Unknown Type: {}", skyboxType.value()); - return nullptr; - } - } - - spdlog::critical("[IndirectLight] Type has no value"); - SPDLOG_TRACE("--Skybox::Skybox"); - return nullptr; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/skybox/skybox.h b/plugins/filament_view/core/scene/skybox/skybox.h deleted file mode 100644 index 0360caca..00000000 --- a/plugins/filament_view/core/scene/skybox/skybox.h +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include - -#include -#include -#include - -namespace plugin_filament_view { - -class Skybox { - public: - Skybox(std::string assetPath, std::string url, filament::math::float4 color); - - virtual ~Skybox() = default; - - static std::unique_ptr Deserialize(const flutter::EncodableMap& params); - - [[nodiscard]] const std::string& getAssetPath() const { return assetPath_; } - - [[nodiscard]] const std::string& getUrl() const { return url_; } - - [[nodiscard]] inline const filament::math::float4& getColor() const { return color_; } - - [[nodiscard]] std::string szGetURLPath() const { return url_; } - - protected: - std::string assetPath_; - std::string url_; - filament::math::float4 color_; -}; - -class HdrSkybox final : public Skybox { - public: - explicit HdrSkybox( - std::optional assetPath, - std::optional url, - std::optional showSun - ) - : Skybox( - assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - filament::math::float4(0.0f, 0.0f, 0.0f, 1.0f) - ), - showSun_(showSun.has_value() ? showSun.value() : false) {} - - ~HdrSkybox() override = default; - - [[nodiscard]] bool getShowSun() const { return showSun_; }; - - friend class SceneController; - - private: - bool showSun_; -}; - -class KxtSkybox final : public Skybox { - public: - explicit KxtSkybox(std::optional assetPath, std::optional url) - : Skybox( - assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - filament::math::float4(0.0f, 0.0f, 0.0f, 1.0f) - ) {} - - ~KxtSkybox() override = default; - - friend class SceneController; -}; - -class ColorSkybox final : public Skybox { - public: - explicit ColorSkybox( - std::optional assetPath, - std::optional url, - std::optional color - ) - : Skybox( - assetPath.has_value() ? std::move(assetPath.value()) : "", - url.has_value() ? std::move(url.value()) : "", - color.has_value() ? std::move(color.value()) - : filament::math::float4{0.0f, 0.0f, 0.0f, 1.0f} - ) {} - - ~ColorSkybox() override = default; - - friend class SceneController; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/view_target.cc b/plugins/filament_view/core/scene/view_target.cc deleted file mode 100644 index feca50f6..00000000 --- a/plugins/filament_view/core/scene/view_target.cc +++ /dev/null @@ -1,804 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "view_target.h" - -#include -#include -#include -#include -#include -#include -#include - -#include - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include - -using flutter::EncodableList; -using flutter::EncodableMap; -using flutter::EncodableValue; -using flutter::MessageReply; -using flutter::MethodCall; -using flutter::MethodResult; - -class Display; -class FlutterView; - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -ViewTarget::ViewTarget( - const size_t id, - const int32_t top, - const int32_t left, - FlutterDesktopEngineState* state -) - : id(id), - state_(state), - left_(left), - top_(top), - callback_(nullptr), - fanimator_(nullptr) { - /* Setup Wayland subsurface */ - setupWaylandSubsurface(); -} - -//////////////////////////////////////////////////////////////////////////// -ViewTarget::~ViewTarget() { - _engine->destroyCameraComponent(cameraEntity_); - - SPDLOG_TRACE("++{}", __FUNCTION__); - - if (callback_) { - wl_callback_destroy(callback_); - callback_ = nullptr; - } - - _engine->destroy(fview_); - _engine->destroy(fswapChain_); - - if (subsurface_) { - wl_subsurface_destroy(subsurface_); - subsurface_ = nullptr; - } - - if (surface_) { - wl_surface_destroy(surface_); - surface_ = nullptr; - } - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -void ViewTarget::_initCamera() { - runtime_assert(fview_, "Filament view must be initialized before setting up the camera"); - - cameraEntity_ = _engine->getEntityManager().create(); - camera_ = _engine->createCamera(cameraEntity_); - - // Set defaults - camera_->setExposure(kDefaultAperture, kDefaultShutterSpeed, kDefaultSensitivity); - camera_->setModelMatrix(filament::math::mat4f()); - fview_->setCamera(camera_); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::setupWaylandSubsurface() { - // Ensure state_ is properly initialized - if (!state_ || !state_->view_controller) { - // Handle error: state_ or view_controller is not initialized - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - return; - } - - const auto flutter_view = state_->view_controller->view; - if (!flutter_view) { - // Handle error: flutter_view is not initialized - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - return; - } - - display_ = flutter_view->GetDisplay()->GetDisplay(); - if (!display_) { - // Handle error: display is not initialized - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - return; - } - - parent_surface_ = flutter_view->GetWindow()->GetBaseSurface(); - if (!parent_surface_) { - // Handle error: parent_surface is not initialized - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - return; - } - - surface_ = wl_compositor_create_surface(flutter_view->GetDisplay()->GetCompositor()); - if (!surface_) { - // Handle error: failed to create surface - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - return; - } - - subsurface_ = wl_subcompositor_get_subsurface( - flutter_view->GetDisplay()->GetSubCompositor(), surface_, parent_surface_ - ); - if (!subsurface_) { - // Handle error: failed to create subsurface - spdlog::error("{}::{}", __FUNCTION__, __LINE__); - wl_surface_destroy(surface_); // Clean up the surface - return; - } - - wl_subsurface_place_below(subsurface_, parent_surface_); - wl_subsurface_set_desync(subsurface_); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::InitializeFilamentInternals(const uint32_t width, const uint32_t height) { - SPDLOG_TRACE("++{}", __FUNCTION__); - - native_window_ = {.display = display_, .surface = surface_, .width = width, .height = height}; - - const auto filamentSystem = ECSManager::GetInstance()->getSystem( - "ViewTarget::Initialize" - ); - - _engine = filamentSystem->getFilamentEngine(); - fswapChain_ = _engine->createSwapChain(&native_window_); - fview_ = _engine->createView(); - - setupView(width, height); - - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::setupView(uint32_t width, uint32_t height) { - SPDLOG_TRACE("++{}", __FUNCTION__); - - const auto filamentSystem = ECSManager::GetInstance()->getSystem(__FUNCTION__); - - fview_->setScene(filamentSystem->getFilamentScene()); - - // this probably needs to change - fview_->setVisibleLayers(0x4, 0x4); - fview_->setViewport({0, 0, width, height}); - - fview_->setBlendMode(filament::View::BlendMode::TRANSLUCENT); - - // on mobile, better use lower quality color buffer - // filament::View::RenderQuality renderQuality{}; - // renderQuality.hdrColorBuffer = filament::View::QualityLevel::MEDIUM; - // fview_->setRenderQuality(renderQuality); - - // dynamic resolution often helps a lot - // fview_->setDynamicResolutionOptions( - // {.enabled = true, .quality = filament::View::QualityLevel::MEDIUM}); - - // MSAA is needed with dynamic resolution MEDIUM - // fview_->setMultiSampleAntiAliasingOptions({.enabled = true}); - // fview_->setMultiSampleAntiAliasingOptions({.enabled = false}); - - // FXAA is pretty economical and helps a lot - // fview_->setAntiAliasing(filament::View::AntiAliasing::FXAA); - // fview_->setAntiAliasing(filament::View::AntiAliasing::NONE); - - // fview_->setShadowingEnabled(false); - // fview_->setScreenSpaceRefractionEnabled(false); - // fview_->setDynamicLightingOptions(0.01, 1000.0f); - - // NOTE: IMPORTANT! Filament doesn't allow stencil buffers on Metal/Vulkan - // with Post-Processing enabled - fview_->setStencilBufferEnabled(false); - - ChangeQualitySettings(ViewTarget::ePredefinedQualitySettings::Ultra); - - _initCamera(); - - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::ChangeQualitySettings(const ePredefinedQualitySettings qualitySettings) { - // reset the settings for each quality setting - filament::viewer::ViewSettings settings = settings_.view; - - switch (qualitySettings) { - case Lowest: - settings.antiAliasing = filament::View::AntiAliasing::NONE; - settings.msaa.enabled = false; - settings.dsr = {.enabled = false}; - settings.screenSpaceReflections.enabled = false; - settings.bloom.enabled = false; - settings.postProcessingEnabled = false; - settings.dynamicLighting.zLightNear = 0.01f; - settings.dynamicLighting.zLightFar = 50.0f; - settings.shadowType = filament::View::ShadowType::PCF; - settings.renderQuality = {.hdrColorBuffer = filament::View::QualityLevel::LOW}; - fview_->setStencilBufferEnabled(false); - fview_->setScreenSpaceRefractionEnabled(false); - break; - - case Low: - settings.antiAliasing = filament::View::AntiAliasing::FXAA; - settings.msaa.enabled = false; - settings.dsr = {.enabled = false}; - settings.screenSpaceReflections.enabled = false; - settings.bloom = {.enabled = false}; - settings.postProcessingEnabled = true; - settings.dynamicLighting.zLightNear = 0.01f; - settings.dynamicLighting.zLightFar = 100.0f; - settings.shadowType = filament::View::ShadowType::PCF; - settings.renderQuality = {.hdrColorBuffer = filament::View::QualityLevel::LOW}; - fview_->setScreenSpaceRefractionEnabled(false); - break; - - case Medium: - settings.antiAliasing = filament::View::AntiAliasing::FXAA; - settings.msaa.enabled = false; - settings.dsr = {.enabled = false}; - settings.screenSpaceReflections.enabled = false; - settings.bloom = {.strength = 0.2f, .enabled = true}; - settings.postProcessingEnabled = true; - settings.dynamicLighting.zLightNear = 0.01f; - settings.dynamicLighting.zLightFar = 250.0f; - settings.shadowType = filament::View::ShadowType::PCF; - settings.renderQuality = {.hdrColorBuffer = filament::View::QualityLevel::HIGH}; - fview_->setScreenSpaceRefractionEnabled(true); - break; - - case High: - settings.antiAliasing = filament::View::AntiAliasing::FXAA; - settings.msaa.enabled = true; - settings.msaa.sampleCount = 2; - settings.dsr = {.enabled = false}; - settings.screenSpaceReflections = { - .thickness = 0.05f, .bias = 0.5f, .maxDistance = 4.0f, .stride = 2.0f, .enabled = true - }; - settings.bloom = {.strength = 0.3f, .enabled = true}; - settings.postProcessingEnabled = true; - settings.dynamicLighting.zLightNear = 0.01f; - settings.dynamicLighting.zLightFar = 500.0f; - settings.shadowType = filament::View::ShadowType::PCF; - settings.renderQuality = {.hdrColorBuffer = filament::View::QualityLevel::HIGH}; - fview_->setScreenSpaceRefractionEnabled(true); - break; - - case Ultra: - settings.antiAliasing = filament::View::AntiAliasing::FXAA; - settings.msaa.enabled = true; - settings.msaa.sampleCount = 4; - settings.dsr = {.enabled = false}; - settings.screenSpaceReflections = { - .thickness = 0.1f, // - .bias = 0.5f, // - .maxDistance = 12.0f, // - .stride = 1.0f, // - .enabled = true // - }; - settings.bloom = {.strength = 0.4f, .enabled = true}; - settings.postProcessingEnabled = true; - settings.dynamicLighting.zLightNear = 0.01f; - settings.dynamicLighting.zLightFar = 1000.0f; - settings.renderQuality = {.hdrColorBuffer = filament::View::QualityLevel::HIGH}; - settings.shadowType = filament::View::ShadowType::PCF; - settings.ssao = {}; - settings.ssao.radius = 1.0f; - settings.ssao.power = 0.7f; - settings.ssao.bias = 0.01f; - settings.ssao.resolution = 1.0f; - settings.ssao.intensity = 2.0f; - settings.ssao.bilateralThreshold = 0.05f; - settings.ssao.quality = filament::View::QualityLevel::HIGH; - settings.ssao.lowPassFilter = filament::View::QualityLevel::HIGH; - settings.ssao.upsampling = filament::View::QualityLevel::HIGH; - settings.ssao.enabled = true; - settings.ssao.bentNormals = true; - settings.ssao.minHorizonAngleRad = 0.523599f; // 30 degrees - settings.ssao.ssct = {.enabled = false}; - fview_->setScreenSpaceRefractionEnabled(true); - break; - } - - // Now apply the settings to the Filament engine and view - applySettings(_engine, settings, fview_); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::setFogOptions(const filament::View::FogOptions& fogOptions) { - fview_->setFogOptions(fogOptions); -} - -void ViewTarget::updateCameraSettings( - Camera& cameraData, - Transform& transform, - Transform* orbitOriginTransform, - const filament::math::float3* targetPosition -) { - // spdlog::debug("Updating camera({}) for view({})", cameraData.getOwner()->getGuid(), id); - - // Update transform - const filament::math::float3* fulcrum = nullptr; - const filament::math::quatf* fulcrumRotation = nullptr; - - // TODO: move to Transform::anchorTo ? - if (orbitOriginTransform) { - // If a target transform is provided, use its position as the fulcrum - fulcrum = &orbitOriginTransform->getGlobalPosition(); - // TODO: should we follow the origin rotation? let's make this optional - fulcrumRotation = &orbitOriginTransform->getGlobalRotation(); - } else { - // Otherwise, use the camera's own position as the fulcrum - fulcrum = &transform.local.position; - fulcrumRotation = &VectorUtils::kIdentityQuat; - } - - // Head position - auto headMatrix = - // Fulcrum position - camera rotates around this point - filament::math::mat4f::translation(*fulcrum) - // Fulcrum rotation - camera rotates around this point - * filament::math::mat4f(*fulcrumRotation) - // Rig rotation - camera rig rotates around fulcrum - * filament::math::mat4f(cameraData.orbitRotation) - // Dolly offset - camera is offset from the rig arm (relative to forward direction) - * filament::math::mat4f::translation(cameraData.dollyOffset); - - // Look at target - if (targetPosition) { - const auto headPosition = VectorUtils::translationFromMatrix(headMatrix); - - // TODO: move to Transform::lookAt ? - // TODO: consider using global rotation - // filament::math::quatf headRotation = transform.local.rotation; - filament::math::quatf headRotation = VectorUtils::lookAt(headPosition, *targetPosition); - - // Recalculate head matrix with look direction - headMatrix = filament::gltfio::composeMatrix( - // Translation: use previous head - headPosition, - // Rotation: look at target - headRotation, - // Scale: none, identity - VectorUtils::kFloat3One - ); - } - // else... - // TODO: consider case where "target" is off - sum orbitRotation + local.rotation - - camera_->setModelMatrix(headMatrix); - - // Update exposure - if (cameraData._dirtyExposure) { - _setExposure(*cameraData.getExposure()); - } - - // Update projection - if (cameraData._dirtyProjection) { - if (cameraData._projection != std::nullopt) { - _setProjection(*cameraData.getProjection()); - } else if (cameraData._lens != std::nullopt) { - _setLens(*cameraData.getLens()); - } else { - throw std::runtime_error("Camera projection or lens must be set before updating the camera."); - } - } - - // Update eyes - // NOTE: currently disabled, unnecessary until we support stereo rendering - // if (cameraData._dirtyEyes) { - // _setEyes(cameraData._ipd); - // } - - cameraData.clearDirtyFlags(); -} - -void ViewTarget::_setExposure(const Exposure& e) { - if (e.exposure_.has_value()) { - SPDLOG_DEBUG("[setExposure] exposure: {}", e.exposure_.value()); - camera_->setExposure(e.exposure_.value()); - } else { - auto aperture = e.aperture_.has_value() ? e.aperture_.value() : kDefaultAperture; - auto shutterSpeed = e.shutterSpeed_.has_value() ? e.shutterSpeed_.value() - : kDefaultShutterSpeed; - auto sensitivity = e.sensitivity_.has_value() ? e.sensitivity_.value() : kDefaultSensitivity; - SPDLOG_DEBUG( - "[setExposure] aperture: {}, shutterSpeed: {}, sensitivity: {}", // - aperture, shutterSpeed, sensitivity - ); - - camera_->setExposure(aperture, shutterSpeed, sensitivity); - } -} - -void ViewTarget::_setProjection(const Projection& p) { - // Sets projection from raw values if present - if (p.projection_.has_value() && p.left_.has_value() && p.right_.has_value() && p.top_.has_value() - && p.bottom_.has_value()) { - const auto project = p.projection_.value(); - auto left = p.left_.value(); - auto right = p.right_.value(); - auto top = p.top_.value(); - auto bottom = p.bottom_.value(); - auto near = p.near_.has_value() ? p.near_.value() : kDefaultNearPlane; - auto far = p.far_.has_value() ? p.far_.value() : kDefaultFarPlane; - SPDLOG_DEBUG( - "[setProjection] left: {}, right: {}, bottom: {}, top: {}, near: {}, far: {}", // - left, right, bottom, top, near, far - ); - camera_->setProjection(project, left, right, bottom, top, near, far); - } - // ...else calculate & set from FOV - else if (p.fovInDegrees_.has_value() && p.fovDirection_.has_value()) { - auto fovInDegrees = p.fovInDegrees_.value(); - auto aspect = p.aspect_.has_value() ? p.aspect_.value() : calculateAspectRatio(); - auto near = p.near_.has_value() ? p.near_.value() : kDefaultNearPlane; - auto far = p.far_.has_value() ? p.far_.value() : kDefaultFarPlane; - const auto fovDirection = p.fovDirection_.value(); - SPDLOG_DEBUG( - "[setProjection] fovInDegress: {}, aspect: {}, near: {}, far: {}, direction: {}", // - fovInDegrees, aspect, near, far, Projection::getTextForFov(fovDirection) - ); - - camera_->setProjection(fovInDegrees, aspect, near, far, fovDirection); - } -} - -void ViewTarget::_setLens(const LensProjection& l) { - const float focalLength = l.getFocalLength(); - - const auto aspect = l.getAspect().has_value() ? l.getAspect().value() : calculateAspectRatio(); - - const auto near = l.getNear().has_value() ? l.getNear().value() : kDefaultNearPlane; - const auto far = l.getFar().has_value() ? l.getFar().value() : kDefaultFarPlane; - SPDLOG_DEBUG( - "[setLens] focalLength: {}, aspect: {}, near: {}, far: {}", // - focalLength, aspect, near, far - ); - - camera_->setLensProjection(focalLength, aspect, near, far); -} - -void ViewTarget::_setEyes(const double ipd) { - // initialized to identity - filament::math::mat4 leftEye = {}; - filament::math::mat4 rightEye = {}; - - if (ipd != 0.0f) { - filament::math::double3 ipdOffset = {ipd / 2.0, 0.0, 0.0}; - - leftEye = filament::math::mat4::translation(ipdOffset); - rightEye = filament::math::mat4::translation(ipdOffset); - // TODO: add support for focus distance (rotate both eyes towards the focal point) - } - - spdlog::trace("[setEyes] ipd: {}m", ipd); - /// TODO: to enable stereo 3D rendering, check Engine for `stereoscopicEyeCount` first - camera_->setEyeModelMatrix(0, leftEye); - camera_->setEyeModelMatrix(1, rightEye); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::SendFrameViewCallback( - const std::string& methodName, - std::initializer_list> args -) { - EncodableMap encodableMap; - encodableMap.insert({EncodableValue("method"), flutter::EncodableValue(methodName)}); - for (const auto& [fst, snd] : args) { - encodableMap[EncodableValue(fst)] = snd; // NOLINT - } - - const auto viewTargetSystem = ECSManager::GetInstance()->getSystem(__FUNCTION__ - ); - - viewTargetSystem->SendDataToEventChannel(encodableMap); -} - -///////////////////////////////////////////////////////////////////////// -const wl_callback_listener ViewTarget::frame_listener = {.done = OnFrame}; - -/** - * Renders the model and updates the Filament camera. - * - * @param time - timestamp of running program - * rendered - */ -void ViewTarget::DrawFrame(const uint32_t time) { - if (m_LastTime == 0) { - m_LastTime = time; - } - - // Future tasking for making a more featured timing / frame info class. - const uint32_t deltaTimeMS = time - m_LastTime; - double deltaTime = static_cast(deltaTimeMS) / 1000.0; - // Note you might want render time and gameplay time to be different - // but for smooth animation you don't. (physics would be simulated w/o - // render) - // - if (deltaTime == 0.0) { - deltaTime += 1.0; - } - - float fps; - if (_last_fps_reset_time == 0) { - _last_fps_reset_time = time; - // calculate from delta time and round to int - _prev_fps_counter = static_cast(1.0f / deltaTime); - } - - _fps_counter++; - - // Second overflown, reset counter - if (time - _last_fps_reset_time >= 1000) { - _last_fps_reset_time = time; - _prev_fps_counter = _fps_counter; - _fps_counter = 0; - } - - fps = static_cast(_prev_fps_counter); - - // spdlog::debug("[{}] deltaTime: {:.2f}ms", __FUNCTION__, deltaTime * 1000.0f); - - const auto ecs = ECSManager::GetInstance(); - const auto filamentSystem = ecs->getSystem("DrawFrame"); - const auto renderer = filamentSystem->getFilamentRenderer(); - - // Frames from Native to dart, currently run in order of - // - updateFrame - Called regardless if a frame is going to be drawn or not - // - preRenderFrame - Called before native , but we know we're - // going to draw a frame - // - renderFrame - Called after native , right before drawing a - // frame - // - postRenderFrame - Called after we've drawn natively, right after - // drawing a frame. - - // ECS Update - const auto cpuUpdateStart = std::chrono::steady_clock::now(); - ecs->update(deltaTime); - double cpuFrametime = std::chrono::duration( - std::chrono::steady_clock::now() - cpuUpdateStart - ) - .count(); - // spdlog::debug( - // "[{}] CPU frametime: {:.2f}ms", __FUNCTION__, - // std::chrono::duration(cpuUpdateDuration).count() - // ); - - // TODO(kerberjg): send kUpdateFrame event, async with wait - - // Render the scene, unless the renderer wants to skip the frame. - const auto gpuDrawStart = std::chrono::steady_clock::now(); - // spdlog::debug("=== BEGIN FRAME ==="); - if (renderer->beginFrame(fswapChain_, time)) { - // Frame is being rendered - // TODO(kerberjg): send kPreRenderFrame event, async with wait - // spdlog::debug("=== RENDER FRAME ==="); - renderer->render(fview_); - // spdlog::debug("=== END FRAME ==="); - renderer->endFrame(); - // TODO(kerberjg): send kPostRenderFrame event, async with wait - } else { - // beginFrame failed, the renderer couldn't render this frame - // spdlog::error("[{}] BEGINFRAME FAILED!", __FUNCTION__); - } - - double gpuFrametime = std::chrono::duration( - std::chrono::steady_clock::now() - gpuDrawStart - ) - .count(); - - // const auto scriptStart = std::chrono::steady_clock::now(); - - // spdlog::debug("[{}] Calling Script event: preRenderFrame", __FUNCTION__); - const auto scriptFuture = FilamentViewPlugin::CallEvent( - kPreRenderFrame, - {// - std::make_pair(kParam_DeltaTime, EncodableValue(deltaTime)), - std::make_pair(kParam_FPS, EncodableValue(fps)), - std::make_pair(kParam_cpuFrametime, EncodableValue(cpuFrametime)), - std::make_pair(kParam_gpuFrametime, EncodableValue(gpuFrametime)) - } - ); - - scriptFuture.wait(); - // const auto scriptDuration = std::chrono::steady_clock::now() - scriptStart; - // spdlog::debug( - // "[{}] Script frametime: {:.2f}ms", __FUNCTION__, - // std::chrono::duration(scriptDuration).count() - // ); - - // spdlog::debug( - // "[{}] GPU frametime: {:.2f}ms", __FUNCTION__, - // std::chrono::duration(gpuDrawDuration).count() - // ); - - m_LastTime = time; -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::OnFrame(void* data, wl_callback* callback, const uint32_t time) { - // lock surface - const auto obj = static_cast(data); - std::lock_guard lock(obj->frameLock_); - - // Wait for previous frame to complete - // NOTE: this HAS to be done here, because the CallEvent above needs to complete on this thread - // so we need to give the event loop a chance to process it - if (!!obj->framePromise) { - // spdlog::debug("[OnFrame], waiting for previous frame to finish...", __FUNCTION__); - obj->framePromise->get_future().wait(); - } else { - // spdlog::debug("[OnFrame], first frame!", __FUNCTION__); - } - - // Post and await promise - const auto promise = std::make_shared>(); - obj->framePromise = promise; - - // TODO: there's a 0.05ms lag when posting the task - SHOULDN'T HAPPEN! - // NOTE: let's use separate strands for work and rendering? - post(*ECSManager::GetInstance()->getStrand(), [data, obj, callback, time, promise] { - // spdlog::debug("[OnFrame] === (wl) callback start ==="); - obj->callback_ = nullptr; - - // std::lock_guard lock(obj->frameLock_); - if (callback) { - wl_callback_destroy(callback); - } - - // spdlog::debug("=== (wl) surface frame ==="); - obj->callback_ = wl_surface_frame(obj->surface_); - wl_callback_add_listener(obj->callback_, &ViewTarget::frame_listener, data); - - obj->DrawFrame(time); - - // Z-Order - // These do not need to need to be called every frame. - // wl_subsurface_place_below(obj->subsurface_, obj->parent_surface_); - // spdlog::debug("=== (wl) subsurface position ==="); - // wl_subsurface_set_position(obj->subsurface_, obj->left_, obj->top_); - - // spdlog::debug("=== (wl) surface commit ==="); - // NOTE: DO NOT CALL wl_surface_commit, it already happens elsewhere - - // spdlog::debug("[OnFrame] === (wl) callback end ==="); - promise->set_value(); - }); - - // DON'T wait for the future here (see above in this method) -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::setOffset(const double left, const double top) { - left_ = static_cast(left); - top_ = static_cast(top); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::resize(const double width, const double height) { - // Will need to determine what bottom should be - fview_->setViewport({left_, 0, static_cast(width), static_cast(height)}); - - // Update lens projection - const auto aspect = calculateAspectRatio(); - const auto focalLength = static_cast(camera_->getFocalLength()); - const LensProjection lensProjection = {focalLength, aspect}; - _setLens(lensProjection); -} - -float ViewTarget::calculateAspectRatio() const { - const auto viewport = fview_->getViewport(); - if (viewport.height == 0) { - return 1.0f; // Avoid division by zero - } - return static_cast(viewport.width) / static_cast(viewport.height); -} - -//////////////////////////////////////////////////////////////////////////// -void ViewTarget::onTouch( - const int32_t action, - const int32_t point_count, - const size_t point_data_size, - const double* point_data -) const { - // if action is 0, then on 'first' touch, cast ray from camera; - const auto viewport = fview_->getViewport(); - const auto touch = TouchPair(point_count, point_data_size, point_data, viewport.height); - - static constexpr int ACTION_DOWN = 0; - - if (action == ACTION_DOWN) { - return onTouch(touch); - } -} - -void ViewTarget::onTouch(const double x, const double y) const { - // Create a TouchPair from the x and y coordinates - const auto viewport = fview_->getViewport(); - const auto touch = TouchPair(x, y, viewport.height); - - // Call the overloaded onTouch method with the TouchPair - onTouch(touch); -} - -void ViewTarget::onTouch(const TouchPair touch) const { - const auto rayInfo = touchToRay(touch); - - ECSMessage rayInformation; - rayInformation.addData(ECSMessageType::DebugLine, rayInfo); - ECSManager::GetInstance()->RouteMessage(rayInformation); - - ECSMessage collisionRequest; - collisionRequest.addData(ECSMessageType::CollisionRequest, rayInfo); - collisionRequest.addData(ECSMessageType::CollisionRequestRequestor, std::string(__FUNCTION__)); - collisionRequest.addData(ECSMessageType::CollisionRequestType, eNativeOnTouchBegin); - ECSManager::GetInstance()->RouteMessage(collisionRequest); -} - -Ray ViewTarget::touchToRay(const TouchPair touch) const { - const auto viewport = fview_->getViewport(); - - // Note at time of writing on a 800*600 resolution this seems like the 10% - // edges aren't super accurate this might need to be looked at more. - float ndcX = (2.0f * static_cast(touch.x())) / // NOLINT - static_cast(viewport.width) - - // NOLINT - 1.0f; - float ndcY = 1.0f - - (2.0f * static_cast(touch.y())) / // NOLINT - static_cast(viewport.height); // NOLINT - ndcY = -ndcY; - - filament::math::vec4 rayClip(ndcX, ndcY, -1.0f, 1.0f); - - // Get inverse projection and view matrices - filament::math::mat4 invProj = inverse(camera_->getProjectionMatrix()); - filament::math::vec4 rayView = invProj * rayClip; - rayView = filament::math::vec4(rayView.x, rayView.y, -1.0f, 0.0f); - - filament::math::mat4 invView = inverse(camera_->getViewMatrix()); - filament::math::vec3 rayDirection = (invView * rayView).xyz; - rayDirection = normalize(rayDirection); - - // Camera position - filament::math::vec3 rayOrigin = invView[3].xyz; - - /// TODO: this should be the real distance to the object - constexpr float defaultLength = 1000.0f; - return { - filament::math::float3(rayOrigin.x, rayOrigin.y, rayOrigin.z), - filament::math::float3(rayDirection.x, rayDirection.y, rayDirection.z), // - defaultLength - }; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/scene/view_target.h b/plugins/filament_view/core/scene/view_target.h deleted file mode 100644 index c2fb8dda..00000000 --- a/plugins/filament_view/core/scene/view_target.h +++ /dev/null @@ -1,194 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class Camera; - -/// TODO: add missing docs on everything here -class ViewTarget { - public: - static constexpr size_t kNullViewId = -1; - const size_t id; - - std::shared_ptr> framePromise; - - ViewTarget(size_t id, int32_t top, int32_t left, FlutterDesktopEngineState* state); - - ~ViewTarget(); - - enum ePredefinedQualitySettings { Lowest, Low, Medium, High, Ultra }; - - // Disallow copy and assign. - ViewTarget(const ViewTarget&) = delete; - ViewTarget& operator=(const ViewTarget&) = delete; - - void setInitialized() { - spdlog::debug( - "ViewTarget::setInitialized (previously {})", initialized_ ? "already true" : "false" - ); - if (initialized_) return; - - initialized_ = true; - spdlog::debug("ViewTarget::setInitialized calling OnFrame for the first time!"); - OnFrame(this, nullptr, 0); - } - - /* - * Filament stuff - */ - void InitializeFilamentInternals(uint32_t width, uint32_t height); - [[nodiscard]] ::filament::View* getFilamentView() const { return fview_; } - filament::gltfio::FilamentAsset* getAsset() { return asset_; } - void setAnimator(filament::gltfio::Animator* animator) { fanimator_ = animator; } - - /* - * Viewport - */ - /// Sets the native window offset for this view target. - void setOffset(double left, double top); - /// Sets the native window size for this view target. - void resize(double width, double height); - [[nodiscard]] float calculateAspectRatio() const; - /// Converts a [TouchPair] to a [Ray] to run a raycast with. - Ray touchToRay(TouchPair touch) const; - - /* - * Camera - */ - /// Called by [ViewTargetSystem] on every frame - void updateCameraSettings( - Camera& cameraData, - Transform& transform, - Transform* orbitOriginTransform = nullptr, - const filament::math::float3* targetPosition = nullptr - ); - - /// Called by Flutter when a touch event occurs. - /// TODO: return touch result directly here, don't do callbacks - void onTouch( - int32_t action, - int32_t point_count, - size_t point_data_size, - const double* point_data - ) const; - - void onTouch(const double x, const double y) const; - - void onTouch(const TouchPair touch) const; - - /* - * Rendering - */ - /// Sets the quality setting preset for the view target. - void ChangeQualitySettings(ePredefinedQualitySettings qualitySettings); - /// Sets the fog options for the view target. - void setFogOptions(const filament::View::FogOptions& fogOptions); - /// Returns the current render settings for the view target. - filament::viewer::Settings& getSettings() { return settings_; } - - private: - /* - * Camera - */ - static constexpr float kDefaultNearPlane = 0.05f; // 5 cm - static constexpr float kDefaultFarPlane = 1000.0f; // 1 km - static constexpr float kDefaultAperture = 16.0f; - static constexpr float kDefaultShutterSpeed = 1.0f / 125; - static constexpr float kDefaultSensitivity = 100.0f; - static constexpr float kDefaultFocalLength = 28.0f; - - filament::Camera* camera_ = nullptr; - utils::Entity cameraEntity_; - filament::Engine* _engine = nullptr; - - /// Initializes the camera - void _initCamera(); - - void _setExposure(const Exposure& exposure); - void _setProjection(const Projection& projection); - void _setLens(const LensProjection& lensProjection); - /// Sets the eyes view matrices for stereoscopic rendering (if applicable). - void _setEyes(const double ipd); - - /* - * Wayland - */ - void setupWaylandSubsurface(); - - FlutterDesktopEngineState* state_; - filament::viewer::Settings settings_; - filament::gltfio::FilamentAsset* asset_{}; - int32_t left_; - int32_t top_; - - bool initialized_{}; - - wl_display* display_{}; - wl_surface* surface_{}; - wl_surface* parent_surface_{}; - wl_callback* callback_; - wl_subsurface* subsurface_{}; - - struct _native_window { - struct wl_display* display; - struct wl_surface* surface; - uint32_t width; - uint32_t height; - } native_window_{}; - - ::filament::SwapChain* fswapChain_{}; - std::mutex frameLock_; - ::filament::View* fview_{}; - - // todo to be moved? - ::filament::gltfio::Animator* fanimator_; - - static void SendFrameViewCallback( - const std::string& methodName, - std::initializer_list> args - ); - - static void OnFrame(void* data, wl_callback* callback, uint32_t time); - - static const wl_callback_listener frame_listener; - int _prev_fps_counter = 0; - int _fps_counter = 0; - uint32_t _last_fps_reset_time = 0; - - void DrawFrame(uint32_t time); - - void setupView(uint32_t width, uint32_t height); - - uint32_t m_LastTime = 0; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/base/system.cc b/plugins/filament_view/core/systems/base/system.cc deleted file mode 100644 index d134bf6f..00000000 --- a/plugins/filament_view/core/systems/base/system.cc +++ /dev/null @@ -1,175 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "system.h" - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -// Send a message to the system -void System::SendMessage(const ECSMessage& msg) { - SPDLOG_TRACE("[SendMessage] Attempting to acquire messagesMutex"); - std::unique_lock lock(messagesMutex); - SPDLOG_TRACE("[SendMessage] messagesMutex acquired"); - messageQueue_.push(msg); - SPDLOG_TRACE("[SendMessage] Message pushed to queue. Queue size: {}", messageQueue_.size()); -} - -//////////////////////////////////////////////////////////////////////////// -// Register a message handler for a specific message type -void System::registerMessageHandler(ECSMessageType type, const ECSMessageHandler& handler) { - SPDLOG_TRACE("[registerMessageHandler] Attempting to acquire handlersMutex"); - std::unique_lock lock(handlersMutex); - SPDLOG_TRACE("[registerMessageHandler] handlersMutex acquired"); - handlers_[type].push_back(handler); - SPDLOG_TRACE( - "[registerMessageHandler] Handler registered for message type {}", static_cast(type) - ); -} - -//////////////////////////////////////////////////////////////////////////// -// Unregister all handlers for a specific message type -void System::UnregisterMessageHandler(ECSMessageType type) { - SPDLOG_TRACE("[UnregisterMessageHandler] Attempting to acquire handlersMutex"); - std::unique_lock lock(handlersMutex); - SPDLOG_TRACE("[UnregisterMessageHandler] handlersMutex acquired"); - handlers_.erase(type); - SPDLOG_TRACE( - "[UnregisterMessageHandler] Handlers unregistered for message type {}", static_cast(type) - ); -} - -//////////////////////////////////////////////////////////////////////////// -// Clear all message handlers -void System::ClearMessageHandlers() { - SPDLOG_TRACE("[ClearMessageHandlers] Attempting to acquire handlersMutex"); - std::unique_lock lock(handlersMutex); - SPDLOG_TRACE("[ClearMessageHandlers] handlersMutex acquired"); - handlers_.clear(); - SPDLOG_TRACE("[ClearMessageHandlers] All handlers cleared"); -} - -//////////////////////////////////////////////////////////////////////////// -// Process incoming messages -void System::ProcessMessages() { - SPDLOG_TRACE("[ProcessMessages] Attempting to acquire messagesMutex"); - std::queue messagesToProcess; - - { - std::unique_lock lock(messagesMutex); - SPDLOG_TRACE("[ProcessMessages] messagesMutex acquired"); - std::swap(messageQueue_, messagesToProcess); - SPDLOG_TRACE( - "[ProcessMessages] Swapped message queues. Messages to process: {}", messagesToProcess.size() - ); - } // messagesMutex is unlocked here - - while (!messagesToProcess.empty()) { - const ECSMessage& msg = messagesToProcess.front(); - SPDLOG_TRACE("[ProcessMessages] Processing message"); - handleMessage(msg); - messagesToProcess.pop(); - SPDLOG_TRACE( - "[ProcessMessages] Message processed. Remaining messages: {}", messagesToProcess.size() - ); - } - - SPDLOG_TRACE("[ProcessMessages] done"); -} - -//////////////////////////////////////////////////////////////////////////// -// Handle a specific message type by invoking the registered handlers -void System::handleMessage(const ECSMessage& msg) { - SPDLOG_TRACE("[handleMessage] Attempting to acquire handlersMutex"); - std::vector handlersToInvoke; - { - std::unique_lock lock(handlersMutex); - SPDLOG_TRACE("[handleMessage] handlersMutex acquired"); - for (const auto& [type, handlerList] : handlers_) { - if (msg.hasData(type)) { - SPDLOG_TRACE("[handleMessage] Message has data for type {}", static_cast(type)); - handlersToInvoke.insert(handlersToInvoke.end(), handlerList.begin(), handlerList.end()); - } - } - } // handlersMutex is unlocked here - SPDLOG_TRACE("[handleMessage] Handlers to invoke: {}", handlersToInvoke.size()); - - for (const auto& handler : handlersToInvoke) { - SPDLOG_TRACE("[handleMessage] Invoking handler"); - try { - handler(msg); - } catch (const std::exception& e) { - spdlog::error("[handleMessage] Exception in handler: {}", e.what()); - } - } - SPDLOG_TRACE("[handleMessage] Handlers invocation completed"); -} - -//////////////////////////////////////////////////////////////////////////////////// -void System::SendDataToEventChannel(const flutter::EncodableMap& oDataMap) const { - if (!event_sink_ || !event_channel_) { - return; - } - - event_sink_->Success(flutter::EncodableValue(oDataMap)); -} - -//////////////////////////////////////////////////////////////////////////////////// -void System::setupMessageChannels( - flutter::PluginRegistrar* poPluginRegistrar, - const std::string& szChannelName -) { - if (event_channel_ != nullptr) { - return; - } - - SPDLOG_DEBUG("Creating Event Channel {}::{}", __FUNCTION__, szChannelName); - - event_channel_ = std::make_unique>( - poPluginRegistrar->messenger(), szChannelName, &flutter::StandardMethodCodec::GetInstance() - ); - - event_channel_->SetStreamHandler(std::make_unique>( - // This lambda is called when the stream is first subscribed to - [&]( - const flutter::EncodableValue* /* arguments */, std::unique_ptr>&& events - ) -> std::unique_ptr> { - event_sink_ = std::move(events); - return nullptr; - }, - // This lambda is called when the stream is cancelled - [&](const flutter::EncodableValue* /* arguments */) - -> std::unique_ptr> { - event_sink_ = nullptr; - return nullptr; - } - )); - - SPDLOG_DEBUG("Event Channel creation Complete for {}", szChannelName); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/base/system.h b/plugins/filament_view/core/systems/base/system.h deleted file mode 100644 index 9bf14051..00000000 --- a/plugins/filament_view/core/systems/base/system.h +++ /dev/null @@ -1,110 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace flutter { -class PluginRegistrar; -class EncodableValue; -} // namespace flutter - -namespace plugin_filament_view { - -class ECSManager; - -using ECSMessageHandler = std::function; - -class System : public IdentifiableType, public LifecycleParticipant { - public: - virtual ~System() = default; - - // Send a message to the system - void SendMessage(const ECSMessage& msg); - - // Register a message handler for a specific message type - void registerMessageHandler(ECSMessageType type, const ECSMessageHandler& handler); - - // Unregister all handlers for a specific message type - void UnregisterMessageHandler(ECSMessageType type); - - // Clear all message handlers - void ClearMessageHandlers(); - - // Process incoming messages - virtual void ProcessMessages(); - - /// @brief Initialize the system with the ECSManager, then calls onSystemInit() - void onInitialize(const ECSManager& params) override { - ecs = const_cast(¶ms); - onSystemInit(); - } - - /// @brief Called after the system is initialized, to perform any additional setup. - /// Must be implemented by derived classes. - virtual void onSystemInit() = 0; - - virtual void update(double /*deltaTime*/) override = 0; - - virtual void onDestroy() override = 0; - - virtual void debugPrint() = 0; - - void setupMessageChannels( - flutter::PluginRegistrar* poPluginRegistrar, - const std::string& szChannelName - ); - - void SendDataToEventChannel(const flutter::EncodableMap& oDataMap) const; - - protected: - smarter_raw_ptr ecs = nullptr; - - // Handle a specific message type by invoking the registered handlers - virtual void handleMessage(const ECSMessage& msg); - - private: - std::queue messageQueue_; // Queue of incoming messages - std::unordered_map< - ECSMessageType, - std::vector, - EnumClassHash> - handlers_; // Registered handlers - - std::mutex messagesMutex; - std::mutex handlersMutex; - - std::unique_ptr> event_channel_; - - // The internal Flutter event sink instance, used to send events to the Dart - // side. - std::unique_ptr> event_sink_; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/animation_system.cc b/plugins/filament_view/core/systems/derived/animation_system.cc deleted file mode 100644 index 0aad89af..00000000 --- a/plugins/filament_view/core/systems/derived/animation_system.cc +++ /dev/null @@ -1,159 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "animation_system.h" - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////////////// -void AnimationSystem::onSystemInit() { - // Handler for AnimationEnqueue - registerMessageHandler(ECSMessageType::AnimationEnqueue, [this](const ECSMessage& msg) { - spdlog::debug("AnimationEnqueue"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - const auto animationIndex = msg.getData(ECSMessageType::AnimationEnqueue); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->EnqueueAnimation(animationIndex); - spdlog::debug("AnimationEnqueue Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationClearQueue - registerMessageHandler(ECSMessageType::AnimationClearQueue, [this](const ECSMessage& msg) { - spdlog::debug("AnimationClearQueue"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->ClearQueue(); - spdlog::debug("AnimationClearQueue Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationPlay - registerMessageHandler(ECSMessageType::AnimationPlay, [this](const ECSMessage& msg) { - spdlog::debug("AnimationPlay"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - const auto animationIndex = msg.getData(ECSMessageType::AnimationPlay); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->PlayAnimation(animationIndex); - spdlog::debug("AnimationPlay Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationChangeSpeed - registerMessageHandler(ECSMessageType::AnimationChangeSpeed, [this](const ECSMessage& msg) { - spdlog::debug("AnimationChangeSpeed"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - const auto newSpeed = msg.getData(ECSMessageType::AnimationChangeSpeed); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->setSpeed(newSpeed); - spdlog::debug("AnimationChangeSpeed Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationPause - registerMessageHandler(ECSMessageType::AnimationPause, [this](const ECSMessage& msg) { - spdlog::debug("AnimationPause"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->Pause(); - spdlog::debug("AnimationPause Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationResume - registerMessageHandler(ECSMessageType::AnimationResume, [this](const ECSMessage& msg) { - spdlog::debug("AnimationResume"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->Resume(); - spdlog::debug("AnimationResume Complete for GUID: {}", guid); - } - }); - - // Handler for AnimationSetLooping - registerMessageHandler(ECSMessageType::AnimationSetLooping, [this](const ECSMessage& msg) { - spdlog::debug("AnimationSetLooping"); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - const auto shouldLoop = msg.getData(ECSMessageType::AnimationSetLooping); - - const auto animationComponent = ecs->getComponent(guid); - if (animationComponent) { - animationComponent->setLooping(shouldLoop); - spdlog::debug("AnimationSetLooping Complete for GUID: {}", guid); - } - }); -} - -//////////////////////////////////////////////////////////////////////////////////// -void AnimationSystem::update(const double deltaTime) { - for (auto& animator : ecs->getComponentsOfType()) { - animator->update(deltaTime); - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void AnimationSystem::onDestroy() {} - -//////////////////////////////////////////////////////////////////////////////////// -void AnimationSystem::debugPrint() { - spdlog::debug("{}", __FUNCTION__); - - // todo list all animators -} - -//////////////////////////////////////////////////////////////////////////////////// -void AnimationSystem::NotifyOfAnimationEvent( - const EntityGUID entityGuid, - const AnimationEventType& eType, - const std::string& eventData -) const { - const auto event = flutter::EncodableMap( - {{flutter::EncodableValue("event"), flutter::EncodableValue(kAnimationEvent)}, - {flutter::EncodableValue(kAnimationEventType), flutter::EncodableValue(static_cast(eType)) - }, - {flutter::EncodableValue(kGuid), flutter::EncodableValue(entityGuid)}, - {flutter::EncodableValue(kAnimationEventData), flutter::EncodableValue(eventData)}} - ); - - SendDataToEventChannel(event); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/animation_system.h b/plugins/filament_view/core/systems/derived/animation_system.h deleted file mode 100644 index 076c6210..00000000 --- a/plugins/filament_view/core/systems/derived/animation_system.h +++ /dev/null @@ -1,55 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include - -#include -#include -#include - -namespace flutter { -class PluginRegistrar; -} - -namespace plugin_filament_view { - -class AnimationSystem : public System { - friend class Animation; - friend class EntityObject; - - public: - AnimationSystem() = default; - - // Disallow copy and assign. - AnimationSystem(const AnimationSystem&) = delete; - AnimationSystem& operator=(const AnimationSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - void NotifyOfAnimationEvent( - const EntityGUID entityGuid, - const AnimationEventType& eType, - const std::string& eventData - ) const; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/collision_system.cc b/plugins/filament_view/core/systems/derived/collision_system.cc deleted file mode 100644 index 8bee1a5c..00000000 --- a/plugins/filament_view/core/systems/derived/collision_system.cc +++ /dev/null @@ -1,265 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "collision_system.h" - -#include "filament_system.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -///////////////////////////////////////////////////////////////////////////////////////// -flutter::EncodableValue HitResult::Encode() const { - // Convert float3 to a list of floats - flutter::EncodableList hitPosition = { - flutter::EncodableValue(hitPosition_.x), flutter::EncodableValue(hitPosition_.y), - flutter::EncodableValue(hitPosition_.z) - }; - - // Create a map to represent the HitResult - flutter::EncodableMap encodableMap = { - {flutter::EncodableValue("guid"), flutter::EncodableValue(guid_)}, - {flutter::EncodableValue("name"), flutter::EncodableValue(name_)}, - {flutter::EncodableValue("hitPosition"), flutter::EncodableValue(hitPosition)} - }; - - return flutter::EncodableValue(encodableMap); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::TurnOnRenderingOfCollidables() const { - const auto colliders = ecs->getComponentsOfType(); - for (const auto& collider : colliders) { - const auto wireframe = collider->_wireframe; - if (!!wireframe) { - wireframe->AddEntityToScene(); - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::TurnOffRenderingOfCollidables() const { - const auto colliders = ecs->getComponentsOfType(); - for (const auto& collider : colliders) { - const auto wireframe = collider->_wireframe; - if (!!wireframe) { - wireframe->RemoveEntityFromScene(); - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::debugPrint() { - spdlog::debug("{}", __FUNCTION__); - - /*for (auto& collider : colliders) { - collider->debugPrint(); - }*/ -} - -///////////////////////////////////////////////////////////////////////////////////////// -inline float fLength2(const filament::math::float3& v) { return v.x * v.x + v.y * v.y + v.z * v.z; } - -///////////////////////////////////////////////////////////////////////////////////////// -std::list CollisionSystem:: - lstCheckForCollidable(Ray& rayCast, int64_t /*collisionLayer*/) const { - std::list hitResults; - - const auto colliders = ecs->getEntitiesWithComponent(); - - // Iterate over all entities. - for (const auto& entity : colliders) { - const EntityGUID guid = entity->getGuid(); - auto collider = ecs->getComponent(guid); - debug_assert(!!collider, ((fmt::format("Collider missing for entity: {}", guid)).data())); - if (!collider->enabled) continue; - - // Check if the collision layer matches (if a specific layer was provided) - // if (collisionLayer != 0 && (collider->getCollisionLayer() & - // collisionLayer) == 0) { - // continue; // Skip if layers don't match - // } - - const auto transform = ecs->getComponent(guid); - - // Perform intersection test with the ray - if (filament::math::float3 hitLocation; collider->intersects(rayCast, hitLocation, transform)) { - // If there is an intersection, create a HitResult - HitResult hitResult; - hitResult.guid_ = guid; - hitResult.name_ = collider->eventName; - hitResult.hitPosition_ = hitLocation; // Set the hit location - - SPDLOG_INFO("HIT RESULT: {}", hitResult.guid_); - - // Add to the hit results - hitResults.push_back(hitResult); - } - } - - // Sort hit results by distance from the ray's origin - hitResults.sort([&rayCast](const HitResult& a, const HitResult& b) { - // Calculate the squared distance to avoid the cost of sqrt - const auto distanceA = fLength2(a.hitPosition_ - rayCast.f3GetPosition()); - const auto distanceB = fLength2(b.hitPosition_ - rayCast.f3GetPosition()); - - // Sort in ascending order (closest hit first) - return distanceA < distanceB; - }); - - // Return the sorted list of hit results - return hitResults; -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::SendCollisionInformationCallback( - const std::list& lstHitResults, - std::string sourceQuery, - const CollisionEventType eType -) const { - flutter::EncodableMap encodableMap; - - // event type - encodableMap[flutter::EncodableValue(kCollisionEventType)] = static_cast(eType); - // source guid - encodableMap[flutter::EncodableValue(kCollisionEventSourceGuid)] = sourceQuery; - // hit count - encodableMap[flutter::EncodableValue(kCollisionEventHitCount)] = static_cast( - lstHitResults.size() - ); - - int iter = 0; - for (const auto& arg : lstHitResults) { - std::ostringstream oss; - oss << kCollisionEventHitResult << iter; - - encodableMap[flutter::EncodableValue(oss.str())] = arg.Encode(); - - ++iter; - } - - SendDataToEventChannel(encodableMap); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::onSystemInit() { - registerMessageHandler(ECSMessageType::CollisionRequest, [this](const ECSMessage& msg) { - auto rayInfo = msg.getData(ECSMessageType::CollisionRequest); - const auto requestor = msg.getData(ECSMessageType::CollisionRequestRequestor); - const auto type = msg.getData(ECSMessageType::CollisionRequestType); - - const auto hitList = lstCheckForCollidable(rayInfo, 0); - - SendCollisionInformationCallback(hitList, requestor, type); - }); - - registerMessageHandler( - ECSMessageType::ToggleDebugCollidableViewsInScene, - [this](const ECSMessage& msg) { - spdlog::debug("ToggleDebugCollidableViewsInScene"); - - const auto value = msg.getData(ECSMessageType::ToggleDebugCollidableViewsInScene); - - if (!value) { - TurnOffRenderingOfCollidables(); - } else { - TurnOnRenderingOfCollidables(); - } - - spdlog::debug("ToggleDebugCollidableViewsInScene Complete"); - } - ); - - registerMessageHandler(ECSMessageType::ToggleCollisionForEntity, [this](const ECSMessage& msg) { - const auto guid = msg.getData(ECSMessageType::ToggleCollisionForEntity); - const auto value = msg.getData(ECSMessageType::BoolValue); - - if (const auto collider = ecs->getComponent(guid); !!collider) { - collider->enabled = value; - } - }); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::update(double /*deltaTime*/) { - - // Iterate over all colliders - const auto colliders = ecs->getComponentsOfType(); - for (const auto& collider : colliders) { - // Check if the collider is enabled - if (collider->enabled) { - // get pointer to collider->_aabb - AABB& aabb = collider->_aabb; - - // Make sure it has an AABB - if (aabb.isEmpty()) { - const auto entity = collider->entityOwner_; - spdlog::trace("Collider entity({}) has no AABB", entity->getGuid()); - // Get AABB if it's a RenderableEntityObject - if (const auto renderableEntity = dynamic_cast(entity)) { - aabb = renderableEntity->getAABB(); - spdlog::trace(" Adding AABB to collider entity({})", entity->getGuid()); - spdlog::trace( - " AABB.pos: x={}, y={}, z={}", aabb.center.x, aabb.center.y, aabb.center.z - ); - spdlog::trace( - " AABB.size: x={}, y={}, z={}", aabb.halfExtent.x * 2, aabb.halfExtent.y * 2, - aabb.halfExtent.z * 2 - ); -#if SPDLOG_LEVEL == trace -// renderableEntity->getComponent()->debugPrint(" "); -#endif - } else { - spdlog::error(" Collider does not have an AABB"); - continue; - } - } - - // Make sure it has a wireframe - if (!collider->_wireframe) { - const auto entity = collider->entityOwner_; - // Create a cube wireframe - auto cubeChild = std::make_shared("(collider wireframe)"); - cubeChild->m_bIsWireframe = true; - cubeChild->addComponent(kDefaultMaterial); - const auto shapeSystem = ecs->getSystem("CollisionSystem::update"); - ecs->addEntity(cubeChild); - shapeSystem->addShapeToScene(cubeChild); - auto childTransform = cubeChild->getComponent(); - childTransform->setTransform(aabb.center, aabb.halfExtent * 2, kQuatfIdentity); - - childTransform->setParent(entity->getGuid()); - - collider->_wireframe = cubeChild; - } - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void CollisionSystem::onDestroy() {} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/collision_system.h b/plugins/filament_view/core/systems/derived/collision_system.h deleted file mode 100644 index 4e67eddd..00000000 --- a/plugins/filament_view/core/systems/derived/collision_system.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class HitResult { - public: - EntityGUID guid_; - std::string name_; - ::filament::math::float3 hitPosition_; - - [[nodiscard]] flutter::EncodableValue Encode() const; -}; - -// Ideally this is replaced by a physics engine eventually that has a scenegraph -// or spatial tree structure in place that makes this type of work more -// efficient. -class CollisionSystem : public System { - friend class ModelSystem; - - public: - CollisionSystem() = default; - - void Cleanup(); - void debugPrint() override; - - // Disallow copy and assign. - CollisionSystem(const CollisionSystem&) = delete; - CollisionSystem& operator=(const CollisionSystem&) = delete; - - void TurnOnRenderingOfCollidables() const; - void TurnOffRenderingOfCollidables() const; - - void update(double deltaTime) override; - - void onSystemInit() override; - void onDestroy() override; - - // send in your ray, get a list of hit results back, collisionLayer not - // actively used - future work. - std::list lstCheckForCollidable(Ray& rayCast, int64_t collisionLayer = 0) const; - - // this will send the hit information sent in to non-native (Dart) code. - void SendCollisionInformationCallback( - const std::list& lstHitResults, - std::string sourceQuery, - CollisionEventType eType - ) const; - - private: - bool currentlyDrawingDebugCollidables = false; - - void MatchCollidablesToRenderingModelsTransforms(); - void MatchCollidablesToDebugDrawingTransforms(); -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/debug_lines_system.cc b/plugins/filament_view/core/systems/derived/debug_lines_system.cc deleted file mode 100644 index 10434c66..00000000 --- a/plugins/filament_view/core/systems/derived/debug_lines_system.cc +++ /dev/null @@ -1,180 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "debug_lines_system.h" -#include "filament_system.h" - -#include -#include -#include -#include -#include -#include -#include -#include - -using filament::IndexBuffer; -using filament::RenderableManager; -using filament::VertexAttribute; -using filament::VertexBuffer; - -namespace plugin_filament_view { - -///////////////////////////////////////////////////////////////////////////////////////// -DebugLine::DebugLine( - filament::math::float3 startingPoint, - filament::math::float3 endingPoint, - filament::Engine* engine, - FilamentEntity entity, - float fTimeToLive -) - : m_fRemainingTime(fTimeToLive), - _fEntity(entity) // Create entity -{ - vertices_.emplace_back(startingPoint); - vertices_.emplace_back(endingPoint); //, - indices_.emplace_back(0); - indices_.emplace_back(1); - - // Initialize the VertexBuffer for the quad - m_poVertexBuffer = VertexBuffer::Builder() - .vertexCount(2) // Four vertices for the quad - .bufferCount(1) // Single buffer for positions - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .build(*engine); - - // Set vertex buffer data - m_poVertexBuffer->setBufferAt( - *engine, 0, - VertexBuffer::BufferDescriptor(vertices_.data(), vertices_.size() * sizeof(float) * 3) - ); - - // Initialize the IndexBuffer for the quad (two triangles) - constexpr int indexCount = 2; - m_poIndexBuffer = IndexBuffer::Builder() - .indexCount(indexCount) - .bufferType(IndexBuffer::IndexType::USHORT) - .build(*engine); - - // Set index buffer data - m_poIndexBuffer->setBuffer( - *engine, - IndexBuffer::BufferDescriptor(indices_.data(), indices_.size() * sizeof(unsigned short)) - ); - - boundingBox_.min = startingPoint; - boundingBox_.max = endingPoint; - - // Build the Renderable with the vertex and index buffers - RenderableManager::Builder(1) - .boundingBox({{}, boundingBox_.extent()}) - .geometry(0, RenderableManager::PrimitiveType::LINES, m_poVertexBuffer, m_poIndexBuffer) - .culling(false) - .receiveShadows(false) - .castShadows(false) - .build(*engine, _fEntity); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLine::Cleanup(filament::Engine* engine) { - if (m_poVertexBuffer) { - engine->destroy(m_poVertexBuffer); - m_poVertexBuffer = nullptr; - } - if (m_poIndexBuffer) { - engine->destroy(m_poIndexBuffer); - m_poIndexBuffer = nullptr; - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::debugPrint() { spdlog::debug("{}", __FUNCTION__); } - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::Cleanup() { - const auto filamentSystem = ecs->getSystem("DebugLinesSystem::Cleanup"); - const auto engine = filamentSystem->getFilamentEngine(); - - for (auto it = ourLines_.begin(); it != ourLines_.end();) { - filamentSystem->getFilamentScene()->remove((*it)->_fEntity); - - // do visual cleanup here - (*it)->Cleanup(engine); - - it = ourLines_.erase(it); - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::update(const double deltaTime) { - const auto filamentSystem = ecs->getSystem("DebugLinesSystem::update"); - const auto engine = filamentSystem->getFilamentEngine(); - - for (auto it = ourLines_.begin(); it != ourLines_.end();) { - (*it)->m_fRemainingTime -= static_cast(deltaTime); - - if ((*it)->m_fRemainingTime < 0) { - filamentSystem->getFilamentScene()->remove((*it)->_fEntity); - - // do visual cleanup here - (*it)->Cleanup(engine); - - it = ourLines_.erase(it); - } else { - ++it; - } - } -} - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::onSystemInit() { - registerMessageHandler(ECSMessageType::DebugLine, [this](const ECSMessage& msg) { - SPDLOG_TRACE("Adding debug line: "); - const auto rayInfo = msg.getData(ECSMessageType::DebugLine); - - AddLine(rayInfo.f3GetPosition(), rayInfo.f3GetDirection() * rayInfo.dGetLength(), 10); - }); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::onDestroy() { Cleanup(); } - -///////////////////////////////////////////////////////////////////////////////////////// -void DebugLinesSystem::AddLine( - filament::math::float3 startPoint, - filament::math::float3 endPoint, - float secondsTimeout -) { - if (m_bCurrentlyDrawingDebugLines == false) { - return; - } - - auto filamentSystem = ecs->getSystem("DebugLinesSystem::AddLine"); - const auto engine = filamentSystem->getFilamentEngine(); - - utils::EntityManager& oEntitymanager = engine->getEntityManager(); - auto oEntity = oEntitymanager.create(); - - auto newDebugLine = std::make_unique( - startPoint, endPoint, engine, oEntity, secondsTimeout - ); - - filamentSystem->getFilamentScene()->addEntity(oEntity); - - ourLines_.emplace_back(std::move(newDebugLine)); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/debug_lines_system.h b/plugins/filament_view/core/systems/derived/debug_lines_system.h deleted file mode 100644 index bfade401..00000000 --- a/plugins/filament_view/core/systems/derived/debug_lines_system.h +++ /dev/null @@ -1,85 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include - -#include -#include -#include -#include - -#include - -namespace plugin_filament_view { - -class DebugLine final { - public: - DebugLine( - filament::math::float3 startingPoint, - filament::math::float3 endingPoint, - filament::Engine* engine, - FilamentEntity entity, - float fTimeToLive - ); - ~DebugLine() = default; - void Cleanup(filament::Engine* engine); - - float m_fRemainingTime; - FilamentEntity _fEntity; - - filament::VertexBuffer* m_poVertexBuffer = nullptr; - filament::IndexBuffer* m_poIndexBuffer = nullptr; - - std::vector<::filament::math::float3> vertices_; - std::vector indices_; - filament::Aabb boundingBox_; -}; - -class DebugLinesSystem final : public System { - public: - DebugLinesSystem() = default; - - void debugPrint() override; - - // Disallow copy and assign. - DebugLinesSystem(const DebugLinesSystem&) = delete; - DebugLinesSystem& operator=(const DebugLinesSystem&) = delete; - - void update(double deltaTime) override; - - void onSystemInit() override; - void onDestroy() override; - - void AddLine( - ::filament::math::float3 startPoint, - ::filament::math::float3 endPoint, - float secondsTimeout - ); - - // called from onDestroy during the systems shutdown routine. - void Cleanup(); - - private: - bool m_bCurrentlyDrawingDebugLines = false; - - std::list> ourLines_; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/filament_system.cc b/plugins/filament_view/core/systems/derived/filament_system.cc deleted file mode 100644 index b1f11699..00000000 --- a/plugins/filament_view/core/systems/derived/filament_system.cc +++ /dev/null @@ -1,69 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "filament_system.h" - -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////////////// -void FilamentSystem::onSystemInit() { - spdlog::debug("Engine creation Filament API thread: 0x{:x}", pthread_self()); - - /* Note; this is checked in for future reference, on some systems this might - be needed. TBD - filament::Engine::Config config; - config.minCommandBufferSizeMB = 10; // Increase from the default (1 MB) to - handle larger workloads config.commandBufferSizeMB = - config.minCommandBufferSizeMB * 3; // Ensure total command buffer size - reflects the minCommandBufferSizeMB - - // Create the Filament Engine with the custom config - fengine_ = filament::Engine::create( - filament::Engine::Backend::VULKAN, // Use the default backend - nullptr, // Use the default platform - nullptr, // No shared context - &config // Pass the custom config - );*/ - - fengine_ = filament::Engine::create(filament::Engine::Backend::VULKAN); - iblProfiler_ = std::make_unique(fengine_); - frenderer_ = fengine_->createRenderer(); - fscene_ = fengine_->createScene(); - - auto clearOptions = frenderer_->getClearOptions(); - clearOptions.clear = true; - frenderer_->setClearOptions(clearOptions); -} - -//////////////////////////////////////////////////////////////////////////////////// -void FilamentSystem::update(double /*deltaTime*/) {} - -//////////////////////////////////////////////////////////////////////////////////// -void FilamentSystem::onDestroy() { - fengine_->destroy(fscene_); - fengine_->destroy(frenderer_); - - iblProfiler_.reset(); - filament::Engine::destroy(&fengine_); -} - -//////////////////////////////////////////////////////////////////////////////////// -void FilamentSystem::debugPrint() { spdlog::debug("{}", __FUNCTION__); } - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/filament_system.h b/plugins/filament_view/core/systems/derived/filament_system.h deleted file mode 100644 index 782c4865..00000000 --- a/plugins/filament_view/core/systems/derived/filament_system.h +++ /dev/null @@ -1,53 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include - -namespace plugin_filament_view { - -class FilamentSystem : public System { - public: - FilamentSystem() = default; - - // Disallow copy and assign. - FilamentSystem(const FilamentSystem&) = delete; - FilamentSystem& operator=(const FilamentSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - [[nodiscard]] ::filament::Engine* getFilamentEngine() const { return fengine_; } - - [[nodiscard]] IBLProfiler* getIBLProfiler() const { return iblProfiler_.get(); } - - [[nodiscard]] ::filament::Scene* getFilamentScene() const { return fscene_; } - - [[nodiscard]] ::filament::Renderer* getFilamentRenderer() const { return frenderer_; } - - private: - ::filament::Engine* fengine_{}; - ::filament::Renderer* frenderer_{}; - ::filament::Scene* fscene_{}; - - std::unique_ptr iblProfiler_{}; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/indirect_light_system.cc b/plugins/filament_view/core/systems/derived/indirect_light_system.cc deleted file mode 100644 index 3170768d..00000000 --- a/plugins/filament_view/core/systems/derived/indirect_light_system.cc +++ /dev/null @@ -1,224 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "indirect_light_system.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////////////// -void IndirectLightSystem::setDefaultIndirectLight() { - SPDLOG_TRACE("++IndirectLightSystem::setDefaultIndirectLight"); - indirect_light_ = std::make_unique(); - setIndirectLight(indirect_light_.get()); -} - -//////////////////////////////////////////////////////////////////////////////////// -IndirectLightSystem::~IndirectLightSystem() = default; - -//////////////////////////////////////////////////////////////////////////////////// -std::future> IndirectLightSystem::setIndirectLight( - DefaultIndirectLight* indirectLight -) { - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - // Note: LightState to custom model viewer was done here. - // todo copy values to internal var. - - if (!indirectLight) { - promise->set_value(Resource::Error("Light is null")); - return future; - } - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise, indirectLight] { - auto builder = filament::IndirectLight::Builder(); - builder.intensity(indirectLight->getIntensity()); - builder.radiance( - static_cast(indirectLight->radiance_.size()), indirectLight->radiance_.data() - ); - builder.irradiance( - static_cast(indirectLight->irradiance_.size()), indirectLight->irradiance_.data() - ); - if (indirectLight->rotation_.has_value()) { - builder.rotation(indirectLight->rotation_.value()); - } - - const auto filamentSystem = ecs->getSystem("setIndirectLight"); - const auto engine = filamentSystem->getFilamentEngine(); - - builder.build(*engine); - - promise->set_value(Resource::Success("changed Light successfully")); - }); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> IndirectLightSystem:: - setIndirectLightFromKtxAsset(const std::string& /*path*/, double /*intensity*/) { - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise /*, intensity*/] { - promise->set_value(Resource::Error("Not implemented")); - }); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> IndirectLightSystem:: - setIndirectLightFromKtxUrl(const std::string& /*url*/, double /*intensity*/) { - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise /*, intensity*/] { - promise->set_value(Resource::Error("Not implemented")); - }); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -Resource IndirectLightSystem::loadIndirectLightHdrFromFile( - const std::string& asset_path, - const double intensity -) { - const auto filamentSystem = ecs->getSystem("loadIndirectLightHdrFromFile"); - const auto engine = filamentSystem->getFilamentEngine(); - - filament::Texture* texture; - try { - texture = HDRLoader::createTexture(engine, asset_path); - } catch (...) { - return Resource::Error("Could not decode HDR file"); - } - const auto skyboxTexture = filamentSystem->getIBLProfiler()->createCubeMapTexture(texture); - engine->destroy(texture); - - const auto reflections = filamentSystem->getIBLProfiler()->getLightReflection(skyboxTexture); - - const auto ibl = filament::IndirectLight::Builder() - .reflections(reflections) - .intensity(static_cast(intensity)) - .build(*engine); - - const auto prevIndirectLight = filamentSystem->getFilamentScene()->getIndirectLight(); - if (prevIndirectLight) { - engine->destroy(prevIndirectLight); - } - - filamentSystem->getFilamentScene()->setIndirectLight(ibl); - - return Resource::Success("loaded Indirect light successfully"); -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> IndirectLightSystem::setIndirectLightFromHdrAsset( - const std::string& path, - double intensity -) { - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - const asio::io_context::strand& strand_(*ecs->getStrand()); - const auto assetPath = ecs->getConfigValue(kAssetPath); - - post(strand_, [&, promise, path = path, intensity, assetPath] { - std::filesystem::path asset_path(assetPath); - asset_path /= path; - - if (path.empty() || !exists(asset_path)) { - promise->set_value(Resource::Error("Asset path not valid")); - } - try { - promise->set_value(loadIndirectLightHdrFromFile(asset_path.c_str(), intensity)); - } catch (...) { - promise->set_value(Resource::Error("Couldn't changed Light from asset")); - } - }); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> IndirectLightSystem:: - setIndirectLightFromHdrUrl(const std::string& /*url*/, double /*intensity*/) { - const auto promise(std::make_shared>>()); - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - auto future(promise->get_future()); - post(strand_, [&, promise /*, intensity*/] { - promise->set_value(Resource::Error("Not implemented")); - }); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -void IndirectLightSystem::onSystemInit() { - setDefaultIndirectLight(); - - registerMessageHandler( - ECSMessageType::ChangeSceneIndirectLightProperties, - [this](const ECSMessage& msg) { - spdlog::debug("ChangeSceneIndirectLightProperties"); - - const auto intensityValue = msg.getData( - ECSMessageType::ChangeSceneIndirectLightPropertiesIntensity - ); - indirect_light_->setIntensity(intensityValue); - setIndirectLight(indirect_light_.get()); - - spdlog::debug("ChangeSceneIndirectLightProperties Complete"); - } - ); -} - -//////////////////////////////////////////////////////////////////////////////////// -void IndirectLightSystem::update(double /*deltaTime*/) {} - -//////////////////////////////////////////////////////////////////////////////////// -void IndirectLightSystem::onDestroy() { - const auto filamentSystem = ecs->getSystem("setIndirectLight"); - const auto engine = filamentSystem->getFilamentEngine(); - - const auto prevIndirectLight = filamentSystem->getFilamentScene()->getIndirectLight(); - if (prevIndirectLight) { - engine->destroy(prevIndirectLight); - } - - indirect_light_.reset(); -} - -//////////////////////////////////////////////////////////////////////////////////// -void IndirectLightSystem::debugPrint() { spdlog::debug("{}", __FUNCTION__); } - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/indirect_light_system.h b/plugins/filament_view/core/systems/derived/indirect_light_system.h deleted file mode 100644 index 1d904b1f..00000000 --- a/plugins/filament_view/core/systems/derived/indirect_light_system.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class IndirectLight; -class DefaultIndirectLight; -class KtxIndirectLight; -class HdrIndirectLight; - -class IndirectLightSystem : public System { - public: - IndirectLightSystem() = default; - - void setDefaultIndirectLight(); - - std::future> setIndirectLightFromKtxAsset( - const std::string& path, - double intensity - ); - - std::future> setIndirectLightFromKtxUrl( - const std::string& url, - double intensity - ); - - std::future> setIndirectLightFromHdrAsset( - const std::string& path, - double intensity - ); - - std::future> setIndirectLightFromHdrUrl( - const std::string& url, - double intensity - ); - - Resource loadIndirectLightHdrFromFile( - const std::string& asset_path, - double intensity - ); - - std::future> setIndirectLight(DefaultIndirectLight* indirectLight); - - // Disallow copy and assign. - IndirectLightSystem(const IndirectLightSystem&) = delete; - IndirectLightSystem& operator=(const IndirectLightSystem&) = delete; - - ~IndirectLightSystem() override; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - std::unique_ptr indirect_light_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/light_system.cc b/plugins/filament_view/core/systems/derived/light_system.cc deleted file mode 100644 index e40aba52..00000000 --- a/plugins/filament_view/core/systems/derived/light_system.cc +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "light_system.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { -using filament::math::float3; -using filament::math::mat3f; -using filament::math::mat4f; - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::CreateDefaultLight() { - SPDLOG_DEBUG("{}", __FUNCTION__); - - m_poDefaultLight = std::make_shared("DefaultLight", generateUUID()); - const auto oLightComp = std::make_shared(); - ecs->addComponent(m_poDefaultLight->getGuid(), oLightComp); - - oLightComp->setIntensity(200); - oLightComp->setDirection({0, -1, 0}); - oLightComp->setPosition({0, 5, 0}); - oLightComp->setCastLight(true); - // if you're in an closed space (IE Garage), it will self shadow cast - oLightComp->setCastShadows(false); - - BuildLightAndAddToScene(*oLightComp); - - ecs->addEntity(m_poDefaultLight); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::BuildLightAndAddToScene(Light& light) { - BuildLight(light); - AddLightToScene(light); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::BuildLight(Light& light) { - const auto filamentSystem = ecs->getSystem("BuildLight"); - const auto engine = filamentSystem->getFilamentEngine(); - - if (!light.m_poFilamentEntityLight) { - light.m_poFilamentEntityLight = engine->getEntityManager().create(); - } else { - RemoveLightFromScene(light); - } - - auto builder = filament::LightManager::Builder(light.getLightType()); - - if (light.getColorTemperature() > 0) { - auto cct = filament::Color::cct(light.getColorTemperature()); - auto red = cct.r; - auto green = cct.g; - auto blue = cct.b; - builder.color({red * 255, green * 255, blue * 255}); - } else { - builder.color({light.color[0], light.color[1], light.color[2]}); - } - - // Note while not all of these vars are used in every scenario - // we're expecting filament to throw away the values that are - // not needed. - builder.intensity(light.getIntensity()); - builder.position(light.getPosition()); - builder.direction(light.getDirection()); - builder.castLight(light.getCastLight()); - builder.castShadows(light.getCastShadows()); - builder.falloff(light.getFalloffRadius()); - - builder.spotLightCone(light.getSpotLightConeInner(), light.getSpotLightConeOuter()); - - builder.sunAngularRadius(light.getSunAngularRadius()); - builder.sunHaloSize(light.getSunHaloSize()); - builder.sunHaloFalloff(light.getSunHaloFalloff()); - - builder.build(*engine, light.m_poFilamentEntityLight); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::RemoveLightFromScene(const Light& light) { - const auto filamentSystem = ecs->getSystem("lightManager::RemoveLightFromScene"); - - const auto scene = filamentSystem->getFilamentScene(); - - scene->remove(light.m_poFilamentEntityLight); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::AddLightToScene(const Light& light) { - const auto filamentSystem = ecs->getSystem("lightManager::AddLightToScene"); - - const auto scene = filamentSystem->getFilamentScene(); - - scene->addEntity(light.m_poFilamentEntityLight); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::onSystemInit() { - registerMessageHandler(ECSMessageType::ChangeSceneLightProperties, [this](const ECSMessage& msg) { - SPDLOG_TRACE("ChangeSceneLightProperties"); - - const auto guid = msg.getData(ECSMessageType::ChangeSceneLightProperties); - - const auto colorValue = msg.getData>(ECSMessageType::floatVec4); - - const auto intensityValue = msg.getData( - ECSMessageType::ChangeSceneLightPropertiesIntensity - ); - - // find the entity in our list: - const auto theLight = ecs->getComponent(guid); - runtime_assert(theLight != nullptr, fmt::format("Entity({}): Light not found", guid)); - - theLight->setIntensity(intensityValue); - theLight->color = float3( - static_cast(colorValue[0]), static_cast(colorValue[1]), - static_cast(colorValue[2]) - ); - // Ignoring alpha channel for now: colorValue[3] - - RemoveLightFromScene(*theLight); - BuildLightAndAddToScene(*theLight); - - SPDLOG_TRACE("ChangeSceneLightProperties Complete"); - }); - - registerMessageHandler(ECSMessageType::ChangeSceneLightTransform, [this](const ECSMessage& msg) { - SPDLOG_TRACE("ChangeSceneLightTransform"); - - const auto guid = msg.getData(ECSMessageType::ChangeSceneLightTransform); - - const auto position = msg.getData(ECSMessageType::Position); - - const auto rotation = msg.getData(ECSMessageType::Direction); - - // find the entity in our list: - const auto theLight = ecs->getComponent(guid); - runtime_assert(theLight != nullptr, fmt::format("Entity({}): Light not found", guid)); - theLight->setPosition(position); - theLight->setDirection(rotation); - - RemoveLightFromScene(*theLight); - BuildLightAndAddToScene(*theLight); - - SPDLOG_TRACE("ChangeSceneLightTransform Complete"); - }); -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::update(double /*deltaTime*/) {} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::onDestroy() { - if (m_poDefaultLight != nullptr) { - const auto component = ecs->getComponent(m_poDefaultLight->getGuid()); - RemoveLightFromScene(*component); - - m_poDefaultLight.reset(); - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void LightSystem::debugPrint() { - spdlog::debug("{}", __FUNCTION__); - - // TODO Update print out list of lights -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/light_system.h b/plugins/filament_view/core/systems/derived/light_system.h deleted file mode 100644 index 2954d6c1..00000000 --- a/plugins/filament_view/core/systems/derived/light_system.h +++ /dev/null @@ -1,56 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include - -#include - -namespace plugin_filament_view { - -class LightSystem : public System { - friend class SceneTextDeserializer; - friend class EntityObject; - - public: - LightSystem() = default; - - // if after deserialization is complete, and there isn't a light made - // this will be called to create a simple direct light - void CreateDefaultLight(); - void BuildLight(Light& light); - void BuildLightAndAddToScene(Light& light); - - // Disallow copy and assign. - LightSystem(const LightSystem&) = delete; - LightSystem& operator=(const LightSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - // These change the lights in filaments scene - void RemoveLightFromScene(const Light& light); - void AddLightToScene(const Light& light); - - std::shared_ptr m_poDefaultLight; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/material_system.cc b/plugins/filament_view/core/systems/derived/material_system.cc deleted file mode 100644 index 3d74dcf5..00000000 --- a/plugins/filament_view/core/systems/derived/material_system.cc +++ /dev/null @@ -1,229 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "material_system.h" -#include "filament_system.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -///////////////////////////////////////////////////////////////////////////////////////// -MaterialSystem::MaterialSystem() { - SPDLOG_TRACE("++{}", __FUNCTION__); - - materialLoader_ = std::make_unique(); - textureLoader_ = std::make_unique(); - - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -///////////////////////////////////////////////////////////////////////////////////////// -MaterialSystem::~MaterialSystem() { SPDLOG_DEBUG("--{}", __FUNCTION__); } - -///////////////////////////////////////////////////////////////////////////////////////// -Resource MaterialSystem::loadMaterialFromResource( - const MaterialDefinitions* materialDefinition -) { - // The Future object for loading Material - if (!materialDefinition->szGetMaterialAssetPath().empty()) { - // THIS does NOT set default a parameter values - return MaterialLoader::loadMaterialFromAsset(materialDefinition->szGetMaterialAssetPath()); - } - - if (!materialDefinition->szGetMaterialURLPath().empty()) { - return MaterialLoader::loadMaterialFromUrl(materialDefinition->szGetMaterialURLPath()); - } - - return Resource::Error("You must provide material asset path or url"); -} - -///////////////////////////////////////////////////////////////////////////////////////// -Resource MaterialSystem::setupMaterialInstance( - const filament::Material* materialResult, - const MaterialDefinitions* materialDefinitions -) const { - if (!materialResult) { - SPDLOG_ERROR("Unable to {}", __FUNCTION__); - return Resource::Error("argument is NULL"); - } - - const auto materialInstance = materialResult->createInstance(); - materialDefinitions->setMaterialInstancePropertiesFromMyPropertyMap( - materialResult, materialInstance, loadedTextures_ - ); - - return Resource::Success(materialInstance); -} - -///////////////////////////////////////////////////////////////////////////////////////// -Resource MaterialSystem::getMaterialInstance( - const MaterialDefinitions* materialDefinitions -) { - SPDLOG_TRACE("++MaterialManager::getMaterialInstance"); - if (!materialDefinitions) { - spdlog::error("--Bad MaterialDefinitions Result " - "MaterialManager::getMaterialInstance"); - return Resource::Error("Material not found"); - } - - Resource materialToInstanceFrom; - - // In case of multi material load on - // we dont want to reload the same material several times and have collision - // in the map - std::lock_guard lock(loadingMaterialsMutex_); - - auto lookupName = materialDefinitions->szGetMaterialDefinitionLookupName(); - if (const auto materialToInstanceFromIter = loadedTemplateMaterials_.find(lookupName); - materialToInstanceFromIter != loadedTemplateMaterials_.end()) { - materialToInstanceFrom = materialToInstanceFromIter->second; - } else { - SPDLOG_TRACE("++MaterialSystem::LoadingMaterial"); - materialDefinitions->debugPrint(" "); - materialToInstanceFrom = loadMaterialFromResource(materialDefinitions); - - if (materialToInstanceFrom.getStatus() != Status::Success) { - spdlog::error("--Bad Material Result MaterialSystem::getMaterialInstance"); - return Resource::Error(materialToInstanceFrom.getMessage()); - } - - // if we got here the material is valid, and we should add it into our map - loadedTemplateMaterials_.insert(std::make_pair(lookupName, materialToInstanceFrom)); - } - - // here we need to see if any & all textures that are requested on the - // material be loaded before we create an instance of it. - const auto materialsRequiredTextures = materialDefinitions->getTextureMaterialParameters(); - for (const auto materialParam : materialsRequiredTextures) { - try { - // Call the getTextureValue method - const auto& textureValue = materialParam->getTextureValue(); - - // Access the Texture pointer from the MaterialTextureValue variant - const auto& texturePtr = std::get>(textureValue); - - if (!texturePtr) { - spdlog::error( - "Unable to access texture point value for {}", materialParam->szGetParameterName() - ); - continue; - } - - // see if the asset path is already in our map of saved textures - const auto assetPath = materialParam->getTextureValueAssetPath(); - if (auto foundAsset = loadedTextures_.find(assetPath); foundAsset != loadedTextures_.end()) { - // it exists already, don't need to load it. - continue; - } - - // its not loaded already, lets load it. - auto loadedTexture = TextureLoader::loadTexture(texturePtr.get()); - - if (loadedTexture.getStatus() != Status::Success) { - spdlog::error("Unable to load texture from {}", assetPath); - Resource::Error(materialToInstanceFrom.getMessage()); - continue; - } - - loadedTextures_.insert(std::pair(assetPath, loadedTexture)); - } catch (const std::bad_variant_access& e) { - spdlog::error("Error: Could not retrieve the texture value. {}", e.what()); - } catch (const std::runtime_error& e) { - spdlog::error("Error: {}", e.what()); - } - } - - const auto materialInstance = setupMaterialInstance( - materialToInstanceFrom.getData().value(), materialDefinitions - ); - - SPDLOG_TRACE("--MaterialManager::getMaterialInstance"); - return materialInstance; -} - -///////////////////////////////////////////////////////////////////////////////////////// -void MaterialSystem::onSystemInit() { - registerMessageHandler(ECSMessageType::ChangeMaterialParameter, [this](const ECSMessage& msg) { - spdlog::trace("ChangeMaterialParameter"); - - const flutter::EncodableMap& params = msg.getData( - ECSMessageType::ChangeMaterialParameter - ); - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - - if (const auto entityObject = ecs->getEntity(guid); entityObject != nullptr) { - spdlog::trace("ChangeMaterialParameter valid entity found."); - - const auto parameter = MaterialParameter::Deserialize("", params); - - const auto renderable = dynamic_cast(entityObject.get()); - renderable->ChangeMaterialInstanceProperty(parameter.get(), loadedTextures_); - } - - spdlog::trace("ChangeMaterialParameter Complete"); - }); - - registerMessageHandler(ECSMessageType::ChangeMaterialDefinitions, [this](const ECSMessage& msg) { - spdlog::trace("ChangeMaterialDefinitions"); - - const flutter::EncodableMap& params = msg.getData( - ECSMessageType::ChangeMaterialDefinitions - ); - - const auto guid = msg.getData(ECSMessageType::EntityToTarget); - - if (const auto entityObject = ecs->getEntity(guid); entityObject != nullptr) { - spdlog::trace("ChangeMaterialDefinitions valid entity found."); - - const auto renderable = dynamic_cast(entityObject.get()); - renderable->ChangeMaterialDefinitions(params, loadedTextures_); - } - - spdlog::trace("ChangeMaterialDefinitions Complete"); - }); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void MaterialSystem::update(double /*deltaTime*/) {} -///////////////////////////////////////////////////////////////////////////////////////// -void MaterialSystem::onDestroy() { - const auto filamentSystem = ecs->getSystem("MaterialSystem::onDestroy"); - const auto engine = filamentSystem->getFilamentEngine(); - - for (const auto& [fst, snd] : loadedTemplateMaterials_) { - engine->destroy(*snd.getData()); - } - - for (const auto& [fst, snd] : loadedTextures_) { - engine->destroy(*snd.getData()); - } - - loadedTemplateMaterials_.clear(); - loadedTextures_.clear(); - - materialLoader_.reset(); - textureLoader_.reset(); -} - -///////////////////////////////////////////////////////////////////////////////////////// -void MaterialSystem::debugPrint() { spdlog::debug("{}", __FUNCTION__); } - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/material_system.h b/plugins/filament_view/core/systems/derived/material_system.h deleted file mode 100644 index 0e1d4111..00000000 --- a/plugins/filament_view/core/systems/derived/material_system.h +++ /dev/null @@ -1,78 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class MaterialDefinitions; -class MaterialLoader; -class TextureLoader; - -using TextureMap = std::map>; - -class MaterialSystem : public System { - public: - MaterialSystem(); - ~MaterialSystem() override; - - Resource<::filament::MaterialInstance*> getMaterialInstance( - const MaterialDefinitions* materialDefinitions - ); - - // Disallow copy and assign. - MaterialSystem(const MaterialSystem&) = delete; - MaterialSystem& operator=(const MaterialSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - std::unique_ptr materialLoader_; - std::unique_ptr textureLoader_; - - static Resource<::filament::Material*> loadMaterialFromResource( - const MaterialDefinitions* materialDefinition - ); - Resource<::filament::MaterialInstance*> setupMaterialInstance( - const ::filament::Material* materialResult, - const MaterialDefinitions* materialDefinitions - ) const; - - // this map contains the loaded materials from disk, that are not actively - // used but instead copies (instances) are made of, then the instances are - // used. Reducing disk reload. - std::map> loadedTemplateMaterials_; - std::mutex loadingMaterialsMutex_; - - // This map is a list of all loaded textures. Multiple materials might - // reference the same texture, and instead of loading them separately; they'll - // be reused here. As of writing 202409 Textures are tied to materials, so it - // makes sense to have a check if a material needs a texture, to load it in - // that stack chain. - TextureMap loadedTextures_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/model_system.cc b/plugins/filament_view/core/systems/derived/model_system.cc deleted file mode 100644 index 8678282b..00000000 --- a/plugins/filament_view/core/systems/derived/model_system.cc +++ /dev/null @@ -1,715 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "model_system.h" -#include "collision_system.h" - -#include // for max -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -// rapidjson -#include -#include -#include -#include - -#include "animation_system.h" - -namespace plugin_filament_view { - -using filament::gltfio::AssetConfiguration; -using filament::gltfio::AssetLoader; -using filament::gltfio::ResourceConfiguration; -using filament::gltfio::ResourceLoader; - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::destroyAllAssetsOnModels() { - for (const auto& [fst, snd] : _models) { - destroyAsset(snd->getAsset()); // NOLINT - } - _models.clear(); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::destroyAsset(const filament::gltfio::FilamentAsset* asset) const { - if (!asset) { - return; - } - - _filament->getFilamentScene()->removeEntities(asset->getEntities(), asset->getEntityCount()); - assetLoader_->destroyAsset(asset); -} - -void ModelSystem::createModelInstance(Model* model) { - assertInitialized(); - debug_assert(assetLoader_ != nullptr, "ModelSystem::createModelInstance - assetLoader_ is null"); - - const auto assetPath = model->getAssetPath(); - spdlog::trace("\nModelSystem::createModelInstance: {}", assetPath); - spdlog::trace("instance mode: {}", modelInstancingModeToString(model->getInstancingMode())); - - // NOTE: if you're creating a lot of instances, this is better to use at the - // start FilamentAsset* createInstancedAsset(const uint8_t* bytes, uint32_t - // numBytes, FilamentInstance **instances, size_t numInstances) - /// NOTE: is it tho? - filament::gltfio::FilamentAsset* asset = nullptr; - filament::gltfio::FilamentInstance* assetInstance = nullptr; - - // check if instanceable (primary) is loaded - const auto instancedModelData = _assets[assetPath]; - if (instancedModelData.state != AssetLoadingState::unset) { - spdlog::trace("Primary confirmed loaded"); - asset = instancedModelData.asset; - runtime_assert(asset != nullptr, "ModelSystem::createModelInstance - asset CANNOT be null"); - - // if the asset is not instanceable, it will return nullptr - assetInstance = assetLoader_->createInstance(asset); - spdlog::trace("Asset instance created!"); - // if not nullptr, it means it's a valid secondary instance - } else { - throw std::runtime_error( - fmt::format("ModelSystem::createModelInstance - asset {} not loaded", assetPath) - ); - } - - // instance / secondary object. - // asset loaded, - spdlog::trace("HAS INSTANCE"); - model->setAssetInstance(assetInstance); - - // by this point we should either have a subinstance, or THE primary instance - runtime_assert(assetInstance != nullptr, "This should NEVER be null!"); -} - -void ModelSystem::addModelToScene(EntityGUID modelGuid) { - assertInitialized(); - - // Get model - std::shared_ptr model = _models[modelGuid]; - runtime_assert( - model != nullptr, - fmt::format("[{}] Can't add model({}) to scene, model is null", __FUNCTION__, modelGuid).c_str() - ); - - // Expects the model to be already loaded - runtime_assert( - _assets[model->getAssetPath()].state == AssetLoadingState::loaded, - fmt::format( - "[{}] Can't add model({}) to scene, asset not loaded (asset " - "state: {})", - __FUNCTION__, modelGuid, modelInstancingModeToString(model->getInstancingMode()) - ) - .c_str() - ); - - const bool isInScene = model->isInScene(); - const ModelInstancingMode instancingMode = model->getInstancingMode(); - - if (isInScene) { - spdlog::warn( - "[{}] model '{}'({}) is already in scene (asset {}), skipping add", __FUNCTION__, // - model->name, modelGuid, model->assetPath_ - ); - return; - } - - FilamentEntity* modelEntities = nullptr; - size_t modelEntityCount = 0; - - // Get the asset instance - const auto asset = model->getAsset(); - const auto assetInstance = model->getAssetInstance(); - - if (instancingMode == ModelInstancingMode::secondary) { - // If it's a secondary instance, we need to get the entities from the asset - // instance - runtime_assert( - assetInstance != nullptr, "ModelSystem::addModelToScene: model asset instance cannot be null" - ); - // runtime_assert( - // asset != nullptr, - // "ModelSystem::addModelToScene: model asset cannot be null" - // ); - - modelEntities = const_cast(assetInstance->getEntities()); - modelEntityCount = assetInstance->getEntityCount(); - } else { - /// If it's non-instanced, we need to get the entities from the asset` - // runtime_assert( - // asset != nullptr, - // "ModelSystem::addModelToScene: model asset cannot be null" - // ); - - if (asset == nullptr) { - spdlog::warn( - "[{}] model({}) asset({}) is null, deferring load till later (are we " - "tho?)", - __FUNCTION__, modelGuid, model->getAssetPath() - ); - return; - } - - modelEntities = const_cast(asset->getRenderableEntities()); - modelEntityCount = asset->getRenderableEntityCount(); - } - - /* - * Renderable setup - */ - spdlog::trace(" Setting up renderables..."); - - const utils::Slice renderables{modelEntities, modelEntityCount}; - - if (instancingMode == ModelInstancingMode::primary) { - spdlog::trace(" Model({}) is primary, not adding to scene", modelGuid); - return; - } - - // Add to ECS - spdlog::trace(" Adding model({}) to ECS", __FUNCTION__, modelGuid); - ecs->addEntity(model); - - FilamentEntity instanceEntity = assetInstance->getRoot(); - model->_fEntity = instanceEntity; - spdlog::trace(" Adding model[{}]->({}) to Filament scene", instanceEntity.getId(), modelGuid); - _filament->getFilamentScene()->addEntity(instanceEntity); - model->_childrenEntities[instanceEntity] = modelGuid; - - for (const auto entity : renderables) { - // const auto entity = modelEntities[i]; - _filament->getFilamentScene()->addEntity(entity); - - setupRenderable( - entity, model.get(), - const_cast(model->getAssetInstance()->getAsset()) - ); - } - - // Set up transform parenting (needs to be done after renderable setup) - spdlog::trace(" Setting up transform parenting for model({})", modelGuid); - for (auto& [childEntity, childGuid] : model->_childrenEntities) { - spdlog::trace( - " child[{}]->({}) {}", childEntity.getId(), childGuid, - childGuid == modelGuid ? "(is model!)" : "" - ); - - // Skip the model itself - if (childGuid == kNullGuid || childGuid == modelGuid) continue; - - const auto childTransform = ecs->getComponent(childGuid); - const FilamentTransformInstance childInstance = _tm->getInstance(childEntity); - const FilamentEntity parentEntity = _tm->getParent(childInstance); - const EntityGUID parentGuid = model->_childrenEntities[parentEntity]; - - spdlog::trace(" has parent[{}]->({})", parentEntity.getId(), parentGuid); - - if (parentGuid != kNullGuid) // safeguard, shouldn't be necessary - childTransform->setParent(parentGuid); - } - - // Set up transform - auto transform = model->getComponent(); - transform->_fInstance = _tm->getInstance(instanceEntity); - transform->setDirty(true); - /// NOTE: why is this needed? if this is not called the collider doesn't work, - // even though it's visible - ecs->getSystem("ModelSystem::addModelToScene") - ->applyTransform(model->getGuid(), true); - - // Set up renderable - auto renderable = model->getComponent(); - renderable->_fInstance = _rcm->getInstance(instanceEntity); - - // Set up collider - // NOTE: no need - CollisionSystem sets up colliders asynchronously on - // update - - // Set up animator - filament::gltfio::Animator* animatorInstance = nullptr; - if (assetInstance != nullptr) { - animatorInstance = assetInstance->getAnimator(); - } else if (asset != nullptr) { - animatorInstance = asset->getInstance()->getAnimator(); - } - if (animatorInstance != nullptr && model->hasComponent()) { - const auto animator = model->getComponent(); - animator->setAnimator(*animatorInstance); - - // Great if you need help with your animation information! - // animationPtr->debugPrint("From ModelSystem::addModelToScene\t"); - } else if (animatorInstance != nullptr && animatorInstance->getAnimationCount() > 0) { - SPDLOG_DEBUG( - "For asset - {} you have a valid set of animations [{}] you can play " - "on this, but you didn't load an animation component, load one if you " - "want that " - "functionality", - model->getAssetPath(), animatorInstance->getAnimationCount() - ); - } - - model->m_isInScene = true; -} - -void ModelSystem::setupRenderable( - const FilamentEntity fEntity, - Model* model, - filament::gltfio::FilamentAsset* asset -) { - const char* name = asset->getName(fEntity); - if (name == nullptr) { - name = "(null)"; - } - - // Create a RenderableEntityObject child - const auto child = std::make_shared(); - child->_fEntity = fEntity; - child->name = asset->getName(fEntity); - spdlog::trace( - " Creating child entity '{}'({})->[{}] of '{}'({})", child->name, child->getGuid(), - fEntity.getId(), model->name, model->getGuid() - ); - model->_childrenEntities[fEntity] = child->getGuid(); - - /* - * Transform - */ - /// NOTE: we set up transform first, even if it might not have a renderable - /// because it's still valid for parenting reasons. - const auto ti = _tm->getInstance(fEntity); - if (!ti.isValid()) { - spdlog::trace( - "[{}] Skipping fentity {} of model({}), has no transform", __FUNCTION__, fEntity.getId(), - model->getGuid() - ); - return; - } - - // Set up Transform component - auto transform = Transform(); - transform._fInstance = ti; - transform.setTransform(_tm->getTransform(ti)); - auto parentEntity = _tm->getParent(ti); - - spdlog::trace(" Parent entity: [{}]", parentEntity.getId()); -#if SPDLOG_LEVEL == trace -// transform.debugPrint(" "); -#endif - - child->addComponent(transform); - - const auto ri = _rcm->getInstance(fEntity); - if (!ri.isValid()) { - spdlog::trace( - "[{}] Skipping fentity {} of model({}), has no renderable", __FUNCTION__, fEntity.getId(), - model->getGuid() - ); - - ecs->addEntity(child); - return; - } - - const auto commonRenderable = model->getCommonRenderable(); - _rcm->setCastShadows(ri, commonRenderable->IsCastShadowsEnabled()); - _rcm->setReceiveShadows(ri, commonRenderable->IsReceiveShadowsEnabled()); - _rcm->setScreenSpaceContactShadows(ri, false); - - // Set up Renderable component - auto renderable = CommonRenderable(); - renderable._fInstance = ri; - child->addComponent(renderable); - - // (optional) Set up Collider component - // Get extras (aka "userData", aka Blender's "Custom Properties"), string - // containing JSON If extras present and have "fs_touchEvent" property, parse - // and setup a Collider component - if (const char* extras = asset->getExtras(fEntity); !!extras) try { - // Parse using RapidJSON - spdlog::debug(" Has extras! Parsing '{}'", extras); - rapidjson::Document doc; - doc.Parse(extras); - if (doc.HasParseError()) { - spdlog::error(rapidjson::GetParseError_En(doc.GetParseError())); - throw std::runtime_error("[ModelSystem::setupCollidableChild] Failed to parse extras JSON"); - } - - // Get the touchEvent property - constexpr char kTouchEventProp[] = "fs_touchEvent"; - if (doc.HasMember(kTouchEventProp)) { - const auto& touchEvent = doc[kTouchEventProp]; - // type: string (event name) - const auto& eventName = touchEvent.GetString(); - spdlog::trace(" Has '{}'! Value: {}", kTouchEventProp, eventName); - - // check if is a perfect cube (with epsilon = 0.01) - // constexpr float epsilon = 0.01f; - // const AABB aabb = renderable.getAABB(); - // const float sizeX = aabb.halfExtent.x * 2; - // const float sizeY = aabb.halfExtent.y * 2; - // const float sizeZ = aabb.halfExtent.z * 2; - // const bool isCube = std::abs(sizeX - sizeY) < epsilon && - // std::abs(sizeY - sizeZ) < epsilon; - // spdlog::trace("isCube: {}", isCube); - - // attach collider - auto collider = Collider(); - collider.setIsStatic(false); - collider.eventName = eventName; - // collider._aabb = aabb; - // NOTE: extents automatically set from AABB by CollisionSystem - // collider.setShapeType(isCube ? ShapeType::Cube : - // ShapeType::Sphere); - child->addComponent(collider); - - spdlog::trace(" Model child collider setup complete"); - } - - } catch (const std::exception& e) { - spdlog::error( - "[{}] Failed to setup collider child({}) with JSON: {}\nReason: {}", __FUNCTION__, - fEntity.getId(), extras, e.what() - ); - } - - ecs->addEntity(child); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::updateAsyncAssetLoading() { - // spdlog::debug( - // "[{}] Updating async asset loading", - // __FUNCTION__ - // ); - - // This does not specify per resource, but a global, best we can do with this - // information is if we're done loading that was marked as async - // load, then load that physics data onto a collider if required. This gives - // us visuals without colliders in a scene with of objects; but would - // eventually settle - resourceLoader_->asyncUpdateLoad(); - const float percentComplete = resourceLoader_->asyncGetLoadProgress(); - if (percentComplete != 1.0f) { - spdlog::trace("[{}] Model async loading progress: {}%", __FUNCTION__, percentComplete * 100.0f); - return; - } else { - // spdlog::info( - // "[{}] Async model loading complete", - // __FUNCTION__ - // ); - } - - // for each AssetDescriptor... - for (auto& [assetPath, assetData] : _assets) { - // if the asset is loaded, mark it as loaded - if (assetData.state == AssetLoadingState::loading) { - assetData.state = AssetLoadingState::loaded; - } - - if (assetData.state == AssetLoadingState::loaded) { - // if the asset is loaded, load the models - for (auto& modelGuid : assetData.loadingInstances) { - // get the model - std::shared_ptr model = _models[modelGuid]; - if (model == nullptr) { - spdlog::error("[{}] Model {} not found", __FUNCTION__, modelGuid); - continue; - } - - if (model->isInScene()) { - spdlog::warn("Model {} is already in scene, skipping load", model->name); - continue; - } - - // Add model to scene - spdlog::debug("Loaded, adding model to scene: '{}'({})", model->getAssetPath(), modelGuid); - - switch (model->getInstancingMode()) { - case ModelInstancingMode::primary: - spdlog::trace("Model is primary, updating transform but not adding to scene"); - break; - case ModelInstancingMode::secondary: - // load the model as an instance - spdlog::trace("Loading model as instance: {}", model->getAssetPath()); - createModelInstance(model.get()); - spdlog::trace("Model instanced, adding to scene..."); - addModelToScene(modelGuid); - spdlog::trace("Model added to scene! Yay!"); - - // Set up collider children - // for (const auto entity : collidableChildren) { - // setupCollidableChild(entity, sharedPtr.get(), asset); - // } - break; - case ModelInstancingMode::none: - // load the model as a single object - spdlog::trace("Loading model as single object: {}", model->getAssetPath()); - addModelToScene(modelGuid); - break; - } - } - - // clear the loading instances - assetData.loadingInstances.clear(); - } - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::queueModelLoad(std::shared_ptr model) { - spdlog::trace( - "Queueing model({}) load (instance mode: {}) -> {}", model->getGuid(), - modelInstancingModeToString(model->getInstancingMode()), model->getAssetPath() - ); - - try { - const auto baseAssetPath = ecs->getConfigValue(kAssetPath); - const auto modelAssetPath = model->getAssetPath(); - const EntityGUID modelGuid = model->getGuid(); - const ModelInstancingMode instanceMode = model->getInstancingMode(); - - AssetDescriptor& assetData = _assets[modelAssetPath]; - - switch (assetData.state) { - /// Unset: not yet in queue - case AssetLoadingState::unset: - // mark as loading, add asset - // assetData.path = &modelAssetPath; - assetData.state = AssetLoadingState::loading; - _models[modelGuid] = std::move(model); - assetData.loadingInstances.emplace_back(modelGuid); - - spdlog::trace(" Asset unset: queued for loading."); - loadModelFromFile(modelGuid, baseAssetPath); - return; - /// Loading: asset already in queue - case AssetLoadingState::loading: - // add model to asset's loading queue - _models[modelGuid] = model; - if (instanceMode == ModelInstancingMode::primary) { - spdlog::warn("Double-load of primary model({}): {}", modelGuid, modelAssetPath); - } else { - assetData.loadingInstances.emplace_back(modelGuid); - } - spdlog::trace(" Asset loading: model queued for loading."); - return; - /// Loaded: asset in memory, can instance - case AssetLoadingState::loaded: - // add model to asset's loading queue - _models[modelGuid] = std::move(model); - assetData.loadingInstances.emplace_back(modelGuid); - spdlog::trace(" Asset loaded: model queued for instancing."); - return; - /// Error: asset failed to load - case AssetLoadingState::error: - /// TODO: make sure this state is being set to begin with - spdlog::error( - "[ModelSystem::queueModelLoad] Asset {} failed to load, cannot " - "queue model({})", - modelAssetPath, modelGuid - ); - /// TODO: actuallly handle the error somehow? - break; - } - } catch (const std::exception& e) { - throw std::runtime_error( - "[ModelSystem::queueModelLoad] Failed to queue model load: " + std::string(e.what()) - ); - } -} - -void ModelSystem::loadModelFromFile(EntityGUID modelGuid, const std::string& baseAssetPath) { - spdlog::trace("++ loadModelFromFile"); - - const auto& strand = *ecs->getStrand(); - post(strand, [&, modelGuid, baseAssetPath]() mutable { - spdlog::trace("++ loadModelFromFile (lambda), model guid: {}", modelGuid); - // Get model - std::shared_ptr model = _models[modelGuid]; - if (model == nullptr) { - throw std::runtime_error(fmt::format("[loadModelFromFile] Model {} not found", modelGuid)); - } - - try { - const auto assetPath = model->getAssetPath(); - spdlog::trace("Loading model from assetPath: {}", assetPath); - - // Read the file and handle buffer - const auto buffer = readBinaryFile(assetPath, baseAssetPath); - spdlog::trace("handleFile"); - if (!buffer.empty()) { - // Load GLB asset - - // Note if you're creating a lot of instances, this is better to use at - // the start FilamentAsset* createInstancedAsset(const uint8_t* bytes, - // uint32_t numBytes, FilamentInstance **instances, size_t numInstances) - filament::gltfio::FilamentAsset* asset = nullptr; - filament::gltfio::FilamentInstance* assetInstance = nullptr; - - asset = assetLoader_->createAsset(buffer.data(), static_cast(buffer.size())); - spdlog::trace("[loadModelFromFile] asyncBeginLoad"); - resourceLoader_->asyncBeginLoad(asset); - model->setAsset(asset); - _assets[assetPath].asset = asset; // important! if not set, secondaries cannot be created - - // release source data - if (model->getInstancingMode() == ModelInstancingMode::none) { - spdlog::trace("[loadModelFromFile] Non-secondary loaded: releasing source " - "data"); - asset->releaseSourceData(); // TODO: do we also call this for - // primaries after instancing? - } - - assetInstance = asset->getInstance(); - runtime_assert( - assetInstance != nullptr, "[loadModelFromFile] Failed to fetch primary asset instance" - ); - - model->setAssetInstance(assetInstance); - - spdlog::debug("Loaded glb model successfully from {}", assetPath); - } else { - spdlog::error("Couldn't load glb model from {}", assetPath); - } - - } catch (const std::exception& e) { - spdlog::error("[ModelSystem::loadModelFromFile] Failed to load: {}", e.what()); - } catch (...) { - spdlog::error("[ModelSystem::loadModelFromFile] Unknown Exception in lambda"); - } - }); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::onSystemInit() { - spdlog::debug("[{}] Initializing ModelSystem", __FUNCTION__); - // TODO: can be removed pending LifecycleParticipant impl. - if (materialProvider_ != nullptr) { - return; - } - - _transforms = ecs->getSystem(__FUNCTION__); - - // Get filament - _filament = ecs->getSystem(__FUNCTION__); - runtime_assert(_filament != nullptr, "ModelSystem::onSystemInit: FilamentSystem not init yet"); - - _engine = _filament->getFilamentEngine(); - runtime_assert(_engine != nullptr, "ModelSystem::onSystemInit: FilamentEngine not found"); - - _rcm = _engine->getRenderableManager(); - _tm = _engine->getTransformManager(); - _em = _engine->getEntityManager(); - - runtime_assert(_rcm != nullptr, "ModelSystem::onSystemInit: RenderableManager not found"); - runtime_assert(_tm != nullptr, "ModelSystem::onSystemInit: TransformManager not found"); - runtime_assert(_em != nullptr, "ModelSystem::onSystemInit: EntityManager not found"); - - spdlog::trace("[{}] loaded filament systems", __FUNCTION__); - - materialProvider_ = filament::gltfio::createUbershaderProvider( - _engine, UBERARCHIVE_DEFAULT_DATA, static_cast(UBERARCHIVE_DEFAULT_SIZE) - ); - - // new NameComponentManager(EntityManager::get()); - names_ = new ::utils::NameComponentManager(::utils::EntityManager::get()); - - SPDLOG_DEBUG("UbershaderProvider MaterialsCount: {}", materialProvider_->getMaterialsCount()); - - AssetConfiguration assetConfiguration{}; - assetConfiguration.engine = _engine; - assetConfiguration.materials = materialProvider_; - assetConfiguration.names = names_; - assetLoader_ = AssetLoader::create(assetConfiguration); - - ResourceConfiguration resourceConfiguration{}; - resourceConfiguration.engine = _engine; - resourceConfiguration.normalizeSkinningWeights = true; - resourceLoader_ = new ResourceLoader(resourceConfiguration); - - const auto decoder = filament::gltfio::createStbProvider(_engine); - resourceLoader_->addTextureProvider("image/png", decoder); - resourceLoader_->addTextureProvider("image/jpeg", decoder); - // TODO: add support for other texture formats here - - registerMessageHandler(ECSMessageType::ToggleVisualForEntity, [this](const ECSMessage& msg) { - spdlog::trace("ToggleVisualForEntity"); - - const auto guid = msg.getData(ECSMessageType::ToggleVisualForEntity); - const auto value = msg.getData(ECSMessageType::BoolValue); - - if (const auto ourEntity = _models.find(guid); ourEntity != _models.end()) { - if (const auto modelAsset = ourEntity->second->getAsset()) { - if (value) { - _filament->getFilamentScene()->addEntities( - modelAsset->getRenderableEntities(), modelAsset->getRenderableEntityCount() - ); - } else { - _filament->getFilamentScene()->removeEntities( - modelAsset->getRenderableEntities(), modelAsset->getRenderableEntityCount() - ); - } - } else if (const auto modelAssetInstance = ourEntity->second->getAssetInstance()) { - if (value) { - _filament->getFilamentScene()->addEntities( - modelAssetInstance->getEntities(), modelAssetInstance->getEntityCount() - ); - } else { - _filament->getFilamentScene()->removeEntities( - modelAssetInstance->getEntities(), modelAssetInstance->getEntityCount() - ); - } - } - } - - spdlog::trace("ToggleVisualForEntity Complete"); - }); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::update(double /*deltaTime*/) { - // Make sure all models are loaded - updateAsyncAssetLoading(); - - // Instance models that have just been loaded - // TODO: see TODOs in `updateAsyncAssetLoading` -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::onDestroy() { - destroyAllAssetsOnModels(); - delete resourceLoader_; - resourceLoader_ = nullptr; - - if (assetLoader_) { - AssetLoader::destroy(&assetLoader_); - assetLoader_ = nullptr; - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void ModelSystem::debugPrint() { SPDLOG_DEBUG("{}", __FUNCTION__); } - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/model_system.h b/plugins/filament_view/core/systems/derived/model_system.h deleted file mode 100644 index aee5f36f..00000000 --- a/plugins/filament_view/core/systems/derived/model_system.h +++ /dev/null @@ -1,122 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -enum class AssetLoadingState { - /// Default value, not set - unset = 0, - /// Used when a model is queued for loading - loading, - /// Used when a model is loaded and is ready to be used - loaded, - /// Used when a model failed to load - error = -1 -}; - -/// @brief Holds the state of an asset being loaded -/// It contains the path to the asset, the loading state, -/// and a list of [Model]s that are waiting for this asset to be loaded -struct AssetDescriptor { - /// assetPath - // std::string* path = nullptr; - /// asset loading state - AssetLoadingState state = AssetLoadingState::unset; - /// list of models that are waiting for this asset to be loaded - /// once the asset is loaded, this list will be used to load the models - /// and then clear the list - std::list loadingInstances = {}; - filament::gltfio::FilamentAsset* asset = nullptr; -}; - -class Model; -class TransformSystem; - -class ModelSystem : public System { - public: - ModelSystem() = default; - - void destroyAllAssetsOnModels(); - void destroyAsset(const filament::gltfio::FilamentAsset* asset) const; - - void createModelInstance(Model* model); - - void queueModelLoad(std::shared_ptr oOurModel); - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - // update steps - /// Every frame, update the status of asset loading - /// and instantiate them where necessary - void updateAsyncAssetLoading(); - /// Every frame, make sure that models with loaded assets are added to the - /// scene - void updateModelsInScene(); - - private: - ::filament::gltfio::AssetLoader* assetLoader_{}; - ::filament::gltfio::MaterialProvider* materialProvider_{}; - ::filament::gltfio::ResourceLoader* resourceLoader_{}; - ::utils::NameComponentManager* names_{}; - - // filamentEngine, RenderableManager, EntityManager, TransformManager - smarter_shared_ptr _transforms; - smarter_shared_ptr _filament; - smarter_raw_ptr _engine; - smarter_raw_ptr _rcm; - smarter_raw_ptr _em; - smarter_raw_ptr _tm; - - /// Map of asset paths to their loading states - std::map _assets{}; - std::map> _models{}; - - /// Creates renderables and adds them to the scene - /// Expects the model to have been loaded first - void addModelToScene(EntityGUID modelGuid); - - void setupRenderable( - const FilamentEntity entity, - Model* model, - filament::gltfio::FilamentAsset* asset - ); - - /// Asynchronously loads a model from a file and returns a future - /// that will be set when the model is loaded - /// Expects model to have been queued first, via [ModelSystem::queueModelLoad] - void loadModelFromFile(EntityGUID modelGuid, const std::string& baseAssetPath); -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/shape_system.cc b/plugins/filament_view/core/systems/derived/shape_system.cc deleted file mode 100644 index 61e4ecb3..00000000 --- a/plugins/filament_view/core/systems/derived/shape_system.cc +++ /dev/null @@ -1,248 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "shape_system.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include "collision_system.h" - -namespace plugin_filament_view { - -using shapes::BaseShape; - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::ToggleAllShapesInScene(const bool enable) const { - if (enable) { - for (const auto& guid : _shapes) { - const auto shape = getShape(guid); - shape->AddEntityToScene(); - } - } else { - for (const auto& guid : _shapes) { - const auto shape = getShape(guid); - shape->RemoveEntityFromScene(); - } - } -} - -bool ShapeSystem::hasShape(const EntityGUID guid) const { - if (std::find(_shapes.begin(), _shapes.end(), guid) != _shapes.end()) { - return true; - } else { - return false; - } -} - -BaseShape* ShapeSystem::getShape(const EntityGUID guid) const { - if (hasShape(guid)) { - return dynamic_cast(ecs->getEntity(guid).get()); - } - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::ToggleSingleShapeInScene(const EntityGUID guid, const bool enable) const { - if (!hasShape(guid)) { - return; - } - - BaseShape* shape = getShape(guid); - if (enable) { - shape->AddEntityToScene(); - } else { - shape->RemoveEntityFromScene(); - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::RemoveAllShapesInScene() { - ToggleAllShapesInScene(false); - - for (const auto& guid : _shapes) { - ecs->removeEntity(guid); - } - - _shapes.clear(); -} - -//////////////////////////////////////////////////////////////////////////////////// -std::unique_ptr ShapeSystem::poDeserializeShapeFromData( - const flutter::EncodableMap& mapData -) { - ShapeType type; - - // Find the "shapeType" key in the mapData - if (const auto it = mapData.find(flutter::EncodableValue("shapeType")); - it != mapData.end() && std::holds_alternative(it->second)) { - // Check if the value is within the valid range of the ShapeType enum - if (int32_t typeValue = std::get(it->second); - typeValue > static_cast(ShapeType::Unset) - && typeValue < static_cast(ShapeType::Max)) { - type = static_cast(typeValue); - } else { - spdlog::error("Invalid shape type value: {}", typeValue); - return nullptr; - } - } else { - spdlog::error("shapeType not found or is of incorrect type"); - return nullptr; - } - - // Based on the type_, create the corresponding shape - switch (type) { - case ShapeType::Plane: { - auto toReturn = std::make_unique(); - toReturn->deserializeFrom(mapData); - return toReturn; - } - case ShapeType::Cube: { - auto toReturn = std::make_unique(); - toReturn->deserializeFrom(mapData); - return toReturn; - } - case ShapeType::Sphere: { - auto toReturn = std::make_unique(); - toReturn->deserializeFrom(mapData); - return toReturn; - } - default: - // Handle unknown shape type - spdlog::error("Unknown shape type: {}", static_cast(type)); - return nullptr; - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::addShapesToScene(std::vector>* shapes) { - SPDLOG_TRACE("++{}", __FUNCTION__); - - // TODO remove this, just debug info print for now; - /*for (auto& shape : *shapes) { - shape->debugPrint("Add shapes to scene"); - }*/ - - for (auto& shape : *shapes) { - addShapeToScene(shape); - } - - SPDLOG_TRACE("--{}", __FUNCTION__); -} - -void ShapeSystem::addShapeToScene(const std::shared_ptr& shape) { - runtime_assert(shape != nullptr, "ShapeSystem::addShapeToScene: shape cannot be null"); - - filament::Scene* filamentScene = _filament->getFilamentScene(); - - spdlog::trace("addShapesToScene: {}", shape->getGuid()); - FilamentEntity oEntity = _em->create(); - filamentScene->addEntity(oEntity); - shape->_fEntity = oEntity; - - shape->bInitAndCreateShape(_engine, oEntity); - - spdlog::trace("Adding entity {} with filament entity {}", shape->getGuid(), oEntity.getId()); - - // To investigate a better system for implementing layer mask - // across dart to here. - // auto instance = _rcm.getInstance(*oEntity.get()); - // To investigate - // _rcm.setLayerMask(instance, 0xff, 0x00); - - _shapes.emplace_back(shape->getGuid()); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::onSystemInit() { - // Get filament - _filament = ecs->getSystem(__FUNCTION__); - runtime_assert(_filament != nullptr, "ModelSystem::onSystemInit: FilamentSystem not init yet"); - - _engine = _filament->getFilamentEngine(); - runtime_assert(_engine != nullptr, "ModelSystem::onSystemInit: FilamentEngine not found"); - - _rcm = _engine->getRenderableManager(); - _tm = _engine->getTransformManager(); - _em = _engine->getEntityManager(); - runtime_assert(_rcm != nullptr, "ModelSystem::onSystemInit: RenderableManager not found"); - runtime_assert(_tm != nullptr, "ModelSystem::onSystemInit: TransformManager not found"); - runtime_assert(_em != nullptr, "ModelSystem::onSystemInit: EntityManager not found"); - - /* - * Register message handlers - */ - registerMessageHandler(ECSMessageType::ToggleShapesInScene, [this](const ECSMessage& msg) { - spdlog::debug("ToggleShapesInScene"); - - const auto value = msg.getData(ECSMessageType::ToggleShapesInScene); - - ToggleAllShapesInScene(value); - - spdlog::trace("ToggleShapesInScene Complete"); - }); - - registerMessageHandler(ECSMessageType::SetShapeTransform, [this](const ECSMessage& msg) { - SPDLOG_TRACE("SetShapeTransform"); - - const auto guid = msg.getData(ECSMessageType::SetShapeTransform); - - const auto position = msg.getData(ECSMessageType::Position); - const auto rotation = msg.getData(ECSMessageType::Rotation); - const auto scale = msg.getData(ECSMessageType::Scale); - - // find the entity in our list: - if (hasShape(guid)) { - const auto entity = getShape(guid); - const auto transform = entity->getComponent(); - const auto collider = entity->getComponent(); - - transform->setTransform(position, scale, rotation); - } - - SPDLOG_TRACE("SetShapeTransform Complete"); - }); - - registerMessageHandler(ECSMessageType::ToggleVisualForEntity, [this](const ECSMessage& msg) { - spdlog::trace("ToggleVisualForEntity"); - - const auto guid = msg.getData(ECSMessageType::ToggleVisualForEntity); - const auto value = msg.getData(ECSMessageType::BoolValue); - - ToggleSingleShapeInScene(guid, value); - - spdlog::trace("ToggleVisualForEntity Complete"); - }); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::update(double /*deltaTime*/) {} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::onDestroy() { - // remove all filament entities. - RemoveAllShapesInScene(); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ShapeSystem::debugPrint() { SPDLOG_DEBUG("{}", __FUNCTION__); } -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/shape_system.h b/plugins/filament_view/core/systems/derived/shape_system.h deleted file mode 100644 index 4988437e..00000000 --- a/plugins/filament_view/core/systems/derived/shape_system.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include "shell/platform/common/client_wrapper/include/flutter/encodable_value.h" - -#include "filament_system.h" -#include -#include - -#include -#include -#include -#include - -namespace plugin_filament_view { - -namespace shapes { -class BaseShape; -} - -class ShapeSystem : public System { - public: - ShapeSystem() = default; - - void addShapesToScene(std::vector>* shapes); - - void addShapeToScene(const std::shared_ptr& shape); - - // Disallow copy and assign. - ShapeSystem(const ShapeSystem&) = delete; - ShapeSystem& operator=(const ShapeSystem&) = delete; - - // will add/remove already made entities to/from the scene - void ToggleAllShapesInScene(bool enable) const; - void ToggleSingleShapeInScene(const EntityGUID guid, bool enable) const; - - void RemoveAllShapesInScene(); - - // Creates the derived class of BaseShape based on the map data sent in, does - // not add it to any list only returns the shape for you, Also does not build - // the data out, only stores it for building when ready. - static std::unique_ptr poDeserializeShapeFromData( - const flutter::EncodableMap& mapData - ); - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - // filamentEngine, RenderableManager, EntityManager, TransformManager - smarter_shared_ptr _filament; - smarter_raw_ptr _engine; - smarter_raw_ptr _rcm; - smarter_raw_ptr _em; - smarter_raw_ptr _tm; - - bool hasShape(const EntityGUID guid) const; - shapes::BaseShape* getShape(const EntityGUID guid) const; - - std::vector _shapes; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/skybox_system.cc b/plugins/filament_view/core/systems/derived/skybox_system.cc deleted file mode 100644 index 0e836b36..00000000 --- a/plugins/filament_view/core/systems/derived/skybox_system.cc +++ /dev/null @@ -1,361 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "skybox_system.h" - -#include -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////////////// -std::future SkyboxSystem::Initialize() { - const auto promise(std::make_shared>()); - auto future(promise->get_future()); - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise] { - const auto filamentSystem = ecs->getSystem("SKyboxManager::Init::Lambda"); - const auto engine = filamentSystem->getFilamentEngine(); - - const auto whiteSkybox = - filament::Skybox::Builder().color({1.0f, 1.0f, 1.0f, 1.0f}).build(*engine); - filamentSystem->getFilamentScene()->setSkybox(whiteSkybox); - - promise->set_value(); - }); - - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::setDefaultSkybox() { - SPDLOG_TRACE("++SkyboxManager::setDefaultSkybox"); - setTransparentSkybox(); - SPDLOG_TRACE("--SkyboxManager::setDefaultSkybox"); -} - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::setTransparentSkybox() { - const auto filamentSystem = ecs->getSystem("setTransparentSkybox"); - - filamentSystem->getFilamentScene()->setSkybox(nullptr); -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> SkyboxSystem::setSkyboxFromHdrAsset( - const std::string& path, - bool showSun, - bool shouldUpdateLight, - float intensity -) { - SPDLOG_TRACE("++SkyboxManager::setSkyboxFromHdrAsset"); - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - const auto assetPath = ecs->getConfigValue(kAssetPath); - - std::filesystem::path asset_path = assetPath; - - asset_path /= path; - if (path.empty() || !exists(asset_path)) { - promise->set_value(Resource::Error("Skybox Asset path is not valid")); - } - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise, asset_path, showSun, shouldUpdateLight, intensity] { - promise->set_value(loadSkyboxFromHdrFile(asset_path, showSun, shouldUpdateLight, intensity)); - }); - - SPDLOG_TRACE("--SkyboxManager::setSkyboxFromHdrAsset"); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> SkyboxSystem::setSkyboxFromHdrUrl( - const std::string& url, - bool showSun, - bool shouldUpdateLight, - float intensity -) { - SPDLOG_TRACE("++SkyboxManager::setSkyboxFromHdrUrl"); - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - if (url.empty()) { - promise->set_value(Resource::Error("URL is empty")); - return future; - } - - const asio::io_context::strand& strand_(*ecs->getStrand()); - - SPDLOG_DEBUG("Skybox downloading HDR Asset: {}", url.c_str()); - post(strand_, [&, promise, url, showSun, shouldUpdateLight, intensity] { - plugin_common_curl::CurlClient client; - // todo client.Init(url, {}, {}); - const auto buffer = client.RetrieveContentAsVector(); - if (client.GetCode() != CURLE_OK) { - promise->set_value(Resource::Error("Couldn't load skybox from " + url)); - } - if (!buffer.empty()) { - promise->set_value(loadSkyboxFromHdrBuffer(buffer, showSun, shouldUpdateLight, intensity)); - } else { - promise->set_value(Resource::Error("Couldn't load HDR file from " + url)); - } - }); - SPDLOG_TRACE("--SkyboxManager::setSkyboxFromHdrUrl"); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> SkyboxSystem::setSkyboxFromKTXAsset(const std::string& path -) { - SPDLOG_TRACE("++SkyboxManager::setSkyboxFromKTXAsset"); - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - const auto assetPath = ecs->getConfigValue(kAssetPath); - - std::filesystem::path asset_path = assetPath; - asset_path /= path; - if (path.empty() || !exists(asset_path)) { - promise->set_value(Resource::Error("KTX Asset path is not valid")); - } - const asio::io_context::strand& strand_(*ecs->getStrand()); - - SPDLOG_DEBUG("Skybox loading KTX Asset: {}", asset_path.c_str()); - post(strand_, [&, promise, asset_path] { - std::ifstream stream(asset_path, std::ios::in | std::ios::binary); - std::vector buffer( - (std::istreambuf_iterator(stream)), std::istreambuf_iterator() - ); - if (!buffer.empty()) { - std::stringstream ss; - ss << "Loaded environment successfully from " << asset_path; - promise->set_value(Resource::Success(ss.str())); - } else { - std::stringstream ss; - ss << "Couldn't change environment from " << asset_path; - promise->set_value(Resource::Error(ss.str())); - } - }); - SPDLOG_TRACE("--SkyboxManager::setSkyboxFromKTXAsset"); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> SkyboxSystem::setSkyboxFromKTXUrl(const std::string& url) { - SPDLOG_TRACE("++SkyboxManager::setSkyboxFromKTXUrl"); - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - if (url.empty()) { - promise->set_value(Resource::Error("URL is empty")); - return future; - } - - const asio::io_context::strand& strand_(*ecs->getStrand()); - post(strand_, [&, promise, url] { - plugin_common_curl::CurlClient client; - - // TODO client.Init(url, {}, {}); - auto buffer = client.RetrieveContentAsVector(); - if (client.GetCode() != CURLE_OK) { - std::stringstream ss; - ss << "Couldn't load skybox from " << url; - promise->set_value(Resource::Error(ss.str())); - } - - if (!buffer.empty()) { - std::stringstream ss; - ss << "Loaded skybox successfully from " << url; - promise->set_value(Resource::Success(ss.str())); - } else { - std::stringstream ss; - ss << "Couldn't load skybox from " << url; - promise->set_value(Resource::Error(ss.str())); - } - }); - - SPDLOG_TRACE("--SkyboxManager::setSkyboxFromKTXUrl"); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -std::future> SkyboxSystem::setSkyboxFromColor( - const filament::math::float4& color -) { - SPDLOG_TRACE("++SkyboxManager::setSkyboxFromColor"); - const auto promise(std::make_shared>>()); - auto future(promise->get_future()); - - if (color.w == 0) { - promise->set_value(Resource::Error("Color is Invalid")); - return future; - } - const asio::io_context::strand& strand_(*ecs->getStrand()); - - post(strand_, [&, promise, color] { - const auto filamentSystem = ecs->getSystem("setSkyboxFromColor"); - const auto engine = filamentSystem->getFilamentEngine(); - - const auto skybox = filament::Skybox::Builder().color(color).build(*engine); - filamentSystem->getFilamentScene()->setSkybox(skybox); - promise->set_value( - Resource::Success("Loaded environment successfully from color") - ); - }); - - SPDLOG_TRACE("--SkyboxManager::setSkyboxFromColor"); - return future; -} - -//////////////////////////////////////////////////////////////////////////////////// -Resource SkyboxSystem::loadSkyboxFromHdrFile( - const std::string& assetPath, - const bool showSun, - const bool shouldUpdateLight, - const float intensity -) { - filament::Texture* texture; - - const auto filamentSystem = ecs->getSystem("loadSkyboxFromHdrFile"); - const auto engine = filamentSystem->getFilamentEngine(); - - try { - texture = HDRLoader::createTexture(engine, assetPath); - } catch (...) { - return Resource::Error("Could not decode HDR buffer"); - } - if (texture) { - const auto skyboxTexture = filamentSystem->getIBLProfiler()->createCubeMapTexture(texture); - engine->destroy(texture); - - if (skyboxTexture) { - const auto sky = - filament::Skybox::Builder().environment(skyboxTexture).showSun(showSun).build(*engine); - - // updates scene light with skybox when loaded with the same hdr file - if (shouldUpdateLight) { - const auto reflections = filamentSystem->getIBLProfiler()->getLightReflection(skyboxTexture - ); - const auto ibl = filament::IndirectLight::Builder() - .reflections(reflections) - .intensity(intensity) - .build(*engine); - // destroy the previous IBl - const auto indirectLight = filamentSystem->getFilamentScene()->getIndirectLight(); - engine->destroy(indirectLight); - filamentSystem->getFilamentScene()->setIndirectLight(ibl); - } - - if (const auto prevSkybox = filamentSystem->getFilamentScene()->getSkybox()) { - engine->destroy(prevSkybox); - } - - filamentSystem->getFilamentScene()->setSkybox(sky); - } - return Resource::Success("Loaded hdr skybox successfully"); - } - - return Resource::Error("Could not decode HDR file"); -} - -//////////////////////////////////////////////////////////////////////////////////// -Resource SkyboxSystem::loadSkyboxFromHdrBuffer( - const std::vector& buffer, - const bool showSun, - const bool shouldUpdateLight, - const float intensity -) { - filament::Texture* texture; - - const auto filamentSystem = ecs->getSystem("loadSkyboxFromHdrBuffer"); - const auto engine = filamentSystem->getFilamentEngine(); - - try { - texture = HDRLoader::createTexture(engine, buffer); - } catch (...) { - return Resource::Error("Could not decode HDR buffer"); - } - if (texture) { - const auto skyboxTexture = filamentSystem->getIBLProfiler()->createCubeMapTexture(texture); - engine->destroy(texture); - - if (skyboxTexture) { - const auto sky = - filament::Skybox::Builder().environment(skyboxTexture).showSun(showSun).build(*engine); - - // updates scene light with skybox when loaded with the same hdr file - if (shouldUpdateLight) { - const auto reflections = filamentSystem->getIBLProfiler()->getLightReflection(skyboxTexture - ); - const auto ibl = filament::IndirectLight::Builder() - .reflections(reflections) - .intensity(intensity) - .build(*engine); - // destroy the previous IBl - const auto indirectLight = filamentSystem->getFilamentScene()->getIndirectLight(); - engine->destroy(indirectLight); - filamentSystem->getFilamentScene()->setIndirectLight(ibl); - } - - if (const auto prevSkybox = filamentSystem->getFilamentScene()->getSkybox()) { - engine->destroy(prevSkybox); - } - - filamentSystem->getFilamentScene()->setSkybox(sky); - } - return Resource::Success("Loaded hdr skybox successfully"); - } - - return Resource::Error("Could not decode HDR file"); -} - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::onSystemInit() { Initialize(); } - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::update(double /*deltaTime*/) {} - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::onDestroy() { - const auto filamentSystem = ecs->getSystem("loadSkyboxFromHdrBuffer"); - const auto engine = filamentSystem->getFilamentEngine(); - - if (const auto prevSkybox = filamentSystem->getFilamentScene()->getSkybox()) { - engine->destroy(prevSkybox); - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void SkyboxSystem::debugPrint() { spdlog::debug("{}", __FUNCTION__); } - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/skybox_system.h b/plugins/filament_view/core/systems/derived/skybox_system.h deleted file mode 100644 index 9666d2b7..00000000 --- a/plugins/filament_view/core/systems/derived/skybox_system.h +++ /dev/null @@ -1,79 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include - -namespace plugin_filament_view { - -class SkyboxSystem : public System { - public: - SkyboxSystem() = default; - - std::future Initialize(); - - void setDefaultSkybox(); - - std::future> setSkyboxFromHdrAsset( - const std::string& path, - bool showSun, - bool shouldUpdateLight, - float intensity - ); - - std::future> setSkyboxFromHdrUrl( - const std::string& url, - bool showSun, - bool shouldUpdateLight, - float intensity - ); - - std::future> setSkyboxFromKTXAsset(const std::string& path); - - std::future> setSkyboxFromKTXUrl(const std::string& url); - - std::future> setSkyboxFromColor(const filament::math::float4& color); - - Resource loadSkyboxFromHdrBuffer( - const std::vector& buffer, - bool showSun, - bool shouldUpdateLight, - float intensity - ); - - Resource loadSkyboxFromHdrFile( - const std::string& assetPath, - bool showSun, - bool shouldUpdateLight, - float intensity - ); - - // Disallow copy and assign. - SkyboxSystem(const SkyboxSystem&) = delete; - SkyboxSystem& operator=(const SkyboxSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - private: - void setTransparentSkybox(); -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/transform_system.cc b/plugins/filament_view/core/systems/derived/transform_system.cc deleted file mode 100644 index 39188753..00000000 --- a/plugins/filament_view/core/systems/derived/transform_system.cc +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "transform_system.h" - -#include - -#include -#include -#include -#include - -namespace plugin_filament_view { - -void TransformSystem::onSystemInit() { - // Get filament - const auto filamentSystem = ecs->getSystem(__FUNCTION__); - const auto engine = filamentSystem->getFilamentEngine(); - - tm = &(engine->getTransformManager()); -} - -void TransformSystem::onDestroy() { - // Shutdown the system - spdlog::debug("TransformSystem shutdown"); -} - -void TransformSystem::ProcessMessages() { - // Process incoming messages - // spdlog::debug("TransformSystem processing messages"); -} - -void TransformSystem::handleMessage(const ECSMessage& /* msg */) { - // Handle incoming messages - // spdlog::debug("TransformSystem handling message"); -} - -void TransformSystem::debugPrint() { spdlog::debug("TransformSystem debugPrint"); } - -// -// Internal logic -// - -void TransformSystem::updateTransforms() { - // Update transforms - const auto transforms = ecs->getComponentsOfType(); - for (const auto& transform : transforms) { - if (!transform->IsDirty()) continue; - applyTransform(*transform, false); - } -} - -void TransformSystem::updateFilamentParentTree() { - // Update Filament parent tree - auto transforms = ecs->getComponentsOfType(); - for (auto& transform : transforms) { - if (!transform->IsParentDirty()) continue; - - // Get the parent transform - const auto parentTransform = ecs->getComponent(transform->getParentId()); - applyParent(*transform, parentTransform.get()); - } -} - -// -// Utility functions -// - -void TransformSystem::applyTransform(const EntityGUID entityId, const bool forceRecalculate) { - // Get the entity and its transform - const auto transform = ecs->getComponent(entityId); - if (transform == nullptr) { - throw std::runtime_error("Entity not found"); - } - - applyTransform(*transform, forceRecalculate); -} - -void TransformSystem::applyTransform(Transform& transform, const bool forceRecalculate) { - // Recalculate the transform only if it's dirty or forced - if (!forceRecalculate && !transform.IsDirty()) { - return; - } - - const EntityGUID entityId = transform.getOwner()->getGuid(); - filament::math::mat4f localMatrix = filament::gltfio::composeMatrix( - transform.local.position, transform.local.rotation, transform.local.scale - ); - - const auto _fInstance = transform._fInstance; - runtime_assert( - _fInstance.isValid(), - fmt::format( - "[{}] Transform({}) instance({}) is not valid", __FUNCTION__, entityId, _fInstance.asValue() - ) - ); - - // Set the transform - tm->setTransform(_fInstance, localMatrix); - transform.global.matrix = tm->getWorldTransform(_fInstance); - transform._isGlobalDirty = true; // mark global as dirty - transform.setDirty(false); // reset -} - -void TransformSystem::applyParent(Transform& child, const Transform* parent) { - // Get the instance of the child and parent - const auto childInstance = child._fInstance; - const auto parentInstance = !!parent ? parent->_fInstance : FilamentTransformInstance(); - - applyParent(childInstance, parentInstance); - child.setParentDirty(false); // reset -} - -void TransformSystem::applyParent(const FilamentEntity& child, const FilamentEntity* parent) { - // Get the instance of the child and parent - const auto childInstance = tm->getInstance(child); - const auto parentInstance = !!parent ? tm->getInstance(*parent) : FilamentTransformInstance(); - - applyParent(childInstance, parentInstance); -} - -void TransformSystem::applyParent( - const FilamentTransformInstance& childInstance, - const FilamentTransformInstance& parentInstance -) { - // Check if the child instance is valid - runtime_assert( - childInstance.isValid(), "womp womp" - // fmt::format( - // "[{}] Child instance {} of {} is not valid.", - // __FUNCTION__, child.getId(), parent->getId() - // ) - ); - // Check if the parent instance is valid (or if null for deparenting) - runtime_assert( - parentInstance.isValid() || parentInstance.asValue() == 0, "womp womp 2" - // fmt::format( - // "[{}] Parent instance {} of {} is not valid.", - // __FUNCTION__, parent->getId(), child.getId() - // ) - ); - // Check if the parent and child are the same - // if (child == *parent) { - // spdlog::warn("[{}] New parent entity is the same as the child entity - // ({}), skipping reparenting.", - // __FUNCTION__, child.getId()); - // return; - // } - - // Set the parent transform - tm->setParent(childInstance, parentInstance); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/transform_system.h b/plugins/filament_view/core/systems/derived/transform_system.h deleted file mode 100644 index fdaef274..00000000 --- a/plugins/filament_view/core/systems/derived/transform_system.h +++ /dev/null @@ -1,109 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include - -namespace plugin_filament_view { - -/** - * TransformSystem is responsible for updating the transforms of entities in the - * scene. It handles: - * - Updating the global transforms after local transforms have been modified - * - Updating Filament's parent tree based on the ECS hierarchy - * - TODO: Asynchronous interpolation of transforms - */ - -class TransformSystem : public System { - public: - TransformSystem() = default; - - void onSystemInit() override; - void ProcessMessages() override; - void onDestroy() override; - void handleMessage(const ECSMessage& msg) override; - void debugPrint() override; - - void update(double /*deltaTime*/) override { - // Filament transform transaction: - // updating the transforms, and the parent tree can be - // quite expensive, so we want to batch them - tm->openLocalTransformTransaction(); - - // interpolateTransforms(deltaTime); - updateTransforms(); - updateFilamentParentTree(); - - // committing calculates the final global transforms - tm->commitLocalTransformTransaction(); - } - - protected: - filament::TransformManager* tm = nullptr; - // - // Internal logic - // - - /** - * Updates the transforms of all entities in the scene. - * - * For each transform marked as "dirty", it commits the transform changes - * to the Filament engine. This includes updating the local transforms - * and updating the global ones wherever needed. - */ - void updateTransforms(); - /** - * Performs reparenting of the Filament parent tree. - * - * Iterates on all transforms, updating the Filament parent tree - * in event of hierarchy changes. - */ - void updateFilamentParentTree(); - - /** - * TODO: implement this - * Performs "async" lerp on transforms. - * - * For each transform marked as "animating", it performs a lerp step - * towards the target transform. - */ - // void interpolateTransforms(double deltaTime); - - public: - /// Applies the transform to the entity with the given ID. - /// - /// \param entityId The ID of the entity to apply the transform to. - /// \param forceRecalculate If true, forces a recalculation of the transform - /// even if it is not marked as dirty. - void applyTransform(const EntityGUID entityId, const bool forceRecalculate = false); - - void applyTransform(Transform& transform, const bool forceRecalculate = false); - - void applyParent(Transform& child, const Transform* parent = nullptr); - - protected: - void applyParent(const FilamentEntity& child, const FilamentEntity* parent = nullptr); - - void applyParent( - const FilamentTransformInstance& child, - const FilamentTransformInstance& parent - ); -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/view_target_system.cc b/plugins/filament_view/core/systems/derived/view_target_system.cc deleted file mode 100644 index d61bf8cd..00000000 --- a/plugins/filament_view/core/systems/derived/view_target_system.cc +++ /dev/null @@ -1,321 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "view_target_system.h" - -#include - -#include -#include -#include -#include -#include -#include - -#include -#include -#include -#include -#include -#include - -#include - -namespace plugin_filament_view { - -// Filament system, engine, entity manager -smarter_shared_ptr _filamentSystem = nullptr; -smarter_raw_ptr _engine = nullptr; -smarter_raw_ptr _em = nullptr; - -//////////////////////////////////////////////////////////////////////////////////// -void ViewTargetSystem::onSystemInit() { - // Get filament engine - _filamentSystem = ecs->getSystem("ViewTargetSystem::onSystemInit"); - _engine = _filamentSystem->getFilamentEngine(); - _em = _engine->getEntityManager(); - - /* - * Message handlers - */ - registerMessageHandler(ECSMessageType::ViewTargetCreateRequest, [this](const ECSMessage& msg) { - spdlog::trace("ViewTargetCreateRequest"); - - const auto state = msg.getData( - ECSMessageType::ViewTargetCreateRequest - ); - const auto top = msg.getData(ECSMessageType::ViewTargetCreateRequestTop); - const auto left = msg.getData(ECSMessageType::ViewTargetCreateRequestLeft); - const auto width = msg.getData(ECSMessageType::ViewTargetCreateRequestWidth); - const auto heigth = msg.getData(ECSMessageType::ViewTargetCreateRequestHeight); - - const auto nWhich = nSetupViewTargetFromDesktopState(top, left, state); - getViewTarget(nWhich)->InitializeFilamentInternals(width, heigth); - - // setCameraFromSerializedData(); - - spdlog::trace("ViewTargetCreateRequest Complete"); - }); - - registerMessageHandler( - ECSMessageType::ViewTargetStartRenderingLoops, - [this](const ECSMessage& /*msg*/) { - spdlog::trace("ViewTargetStartRenderingLoops"); - KickOffFrameRenderingLoops(); - spdlog::trace("ViewTargetStartRenderingLoops Complete"); - } - ); - - registerMessageHandler(ECSMessageType::ChangeViewQualitySettings, [this](const ECSMessage& msg) { - spdlog::trace("ChangeViewQualitySettings"); - - // Not Currently Implemented -- currently will change all view targes. - // ChangeViewQualitySettingsWhichView - auto settingsId = msg.getData(ECSMessageType::ChangeViewQualitySettings); - - spdlog::debug("ChangeViewQualitySettings: {}", settingsId); - for (const auto& viewTarget : _viewTargets) { - viewTarget->ChangeQualitySettings( - static_cast(settingsId) - ); - } - - spdlog::trace("ChangeViewQualitySettings Complete"); - - // setCameraFromSerializedData(); - }); - - // set fog options - registerMessageHandler(ECSMessageType::SetFogOptions, [this](const ECSMessage& msg) { - spdlog::trace("SetFogOptions"); - - const bool enabled = msg.getData(ECSMessageType::SetFogOptions); - - // default values - /// TODO: make constexpr? - const filament::View::FogOptions enabledFogOptions = { - .distance = 20.0f, - // .cutOffDistance = 0.0f, - .maximumOpacity = 1.0f, - .height = 0.0f, - .heightFalloff = 1.0f, - .color = filament::math::float3(1.0f, 1.0f, 1.0f), - .density = 1.5f, - .inScatteringStart = 0.0f, - .inScatteringSize = -1.0f, - .enabled = true, - }; - - /// TODO: make constexpr? - const filament::View::FogOptions disabledFogOptions = { - .enabled = false, - }; - - // Set the fog options - for (const auto& viewTarget : _viewTargets) { - viewTarget->setFogOptions(enabled ? enabledFogOptions : disabledFogOptions); - } - - spdlog::trace("SetFogOptions Complete"); - }); - - registerMessageHandler(ECSMessageType::ResizeWindow, [this](const ECSMessage& msg) { - spdlog::trace("ResizeWindow"); - const auto nWhich = msg.getData(ECSMessageType::ResizeWindow); - const auto fWidth = msg.getData(ECSMessageType::ResizeWindowWidth); - const auto fHeight = msg.getData(ECSMessageType::ResizeWindowHeight); - - getViewTarget(nWhich)->resize(fWidth, fHeight); - - spdlog::trace("ResizeWindow Complete"); - - // setCameraFromSerializedData(); - }); - - registerMessageHandler(ECSMessageType::MoveWindow, [this](const ECSMessage& msg) { - spdlog::trace("MoveWindow"); - const auto nWhich = msg.getData(ECSMessageType::ResizeWindow); - const auto fLeft = msg.getData(ECSMessageType::MoveWindowLeft); - const auto fTop = msg.getData(ECSMessageType::MoveWindowTop); - - getViewTarget(nWhich)->setOffset(fLeft, fTop); - - spdlog::trace("MoveWindow Complete"); - - // setCameraFromSerializedData(); - }); -} - -void ViewTargetSystem::initializeEntity(EntityGUID entityGuid) { - // Get entity and its Camera, Transform components - auto entity = ecs->getEntity(entityGuid); - auto camera = ecs->getComponent(entityGuid); - auto transform = ecs->getComponent(entityGuid); - - // Check requirements: - // - Entity must not have a _fEntity already set - // - Must have a Camera component - // - Must have a Transform component - runtime_assert( - entity != nullptr && !entity->_fEntity && camera != nullptr && transform != nullptr, - (fmt::format( - "[{}] Entity({}) does not match initialization requirements", // - __FUNCTION__, entityGuid - )) - ); - - // Set up entity + camera in Filament - entity->_fEntity = _em->create(); - // Our [Camera] component does not wrap a Filament camera! [ViewTarget] takes care of that - _engine->getTransformManager().create(entity->_fEntity); - transform->_fInstance = _engine->getTransformManager().getInstance(entity->_fEntity); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ViewTargetSystem::update(double /*deltaTime*/) { - // Get all cameras - const auto& cameras = ecs->getComponentsOfType(); - - // Update each camera's view target - // The process is camera-driven, as not every view target might have a Camera entity associated - // with it - // - which is fine! We might want some view targets to have a static camera, - // also this way we're updating the camera in a 'push' manner rather than polling it - - // Keep track of whether a view target has already been set on this frame - std::map viewTargetSetBy; - - for (const auto& camera : cameras) { - const EntityGUID cameraId = camera->getOwner()->getGuid(); - const size_t viewId = camera->getViewId(); - if (viewId == ViewTarget::kNullViewId) - continue; // camera has no view target associated with it, skip it - - auto* viewTarget = getViewTarget(viewId); - if (viewTarget == nullptr) { - spdlog::error("ViewTarget at index {} is null", viewId); - continue; - } - - // Check if this view target has already been set for this frame - if (viewTargetSetBy[viewId]) { - spdlog::warn( - "View target {} has already been set for this frame by camera({}) - another camera({}) is " - "setting it again, skipping", - viewId, viewTargetSetBy[viewId], cameraId - ); - continue; - } - - // Update the camera settings for the view target - const auto transform = ecs->getComponent(cameraId); - const auto orbitOriginTransform = ecs->getComponent(camera->orbitOriginEntity); - const filament::math::float3* targetPosition = nullptr; - - spdlog::trace("Checking camera({}) enableTarget", cameraId); - if (camera->enableTarget) { - // If the camera has a target entity, get its transform - if (camera->targetEntity != kNullGuid) { - spdlog::trace("has target entity: {}", camera->targetEntity); - auto* targetTransform = ecs->getComponent(camera->targetEntity).get(); - - if (targetTransform == nullptr) { - spdlog::warn( - "Camera({}) target entity({}) has no transform, skipping", cameraId, - camera->targetEntity - ); - } else { - // If the target entity has a transform, use its global position - spdlog::trace("Using target entity's global position"); - // Set the target point to the target entity's global position - camera->targetPoint = targetTransform->getGlobalPosition(); - } - } else { - // If no target entity, use the target position directly - spdlog::trace("Using target position directly"); - } - - targetPosition = &camera->targetPoint; - } else { - spdlog::trace("camera enableTarget=false"); - } - - spdlog::trace("Updating camera..."); - viewTarget->updateCameraSettings( - *camera, *transform, orbitOriginTransform.get(), targetPosition - ); - spdlog::trace("Updated camera settings for view target {} by camera {}", viewId, cameraId); - - // Set the flag - viewTargetSetBy[viewId] = cameraId; - } -} - -void ViewTargetSystem::setViewCamera(size_t viewId, EntityGUID cameraId) { - // Get all the cameras - const auto& cameras = ecs->getComponentsOfType(); - for (const auto& camera : cameras) { - // Found the camera, set it as the main camera for the view target - if (camera->getOwner()->getGuid() == cameraId) { - camera->setViewId(viewId); - - spdlog::debug("Setting camera {} as main camera for view target {}", cameraId, viewId); - } - // If found another camera with the same viewId, unset it - else if (camera->getViewId() == viewId) { - camera->setViewId(ViewTarget::kNullViewId); - spdlog::trace( - "Unsetting camera {} from view target {} - not main camera", camera->getOwner()->getGuid(), - viewId - ); - } - } -} - -//////////////////////////////////////////////////////////////////////////////////// -void ViewTargetSystem::onDestroy() {} - -//////////////////////////////////////////////////////////////////////////////////// -void ViewTargetSystem::debugPrint() {} - -ViewTarget* ViewTargetSystem::getViewTarget(size_t index) const { - if (index >= _viewTargets.size()) { - spdlog::error("Invalid view target index: {}", index); - return nullptr; - } - return _viewTargets[index].get(); -} - -//////////////////////////////////////////////////////////////////////////////////// -void ViewTargetSystem::KickOffFrameRenderingLoops() const { - spdlog::debug("Kicking off frame rendering loops for {} view targets", _viewTargets.size()); - for (const auto& viewTarget : _viewTargets) { - viewTarget->setInitialized(); - } -} - -//////////////////////////////////////////////////////////////////////////////////// -size_t ViewTargetSystem::nSetupViewTargetFromDesktopState( - int32_t top, - int32_t left, - FlutterDesktopEngineState* state -) { - size_t id = _viewTargets.size(); - _viewTargets.emplace_back(std::make_unique(id, top, left, state)); - return id; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/derived/view_target_system.h b/plugins/filament_view/core/systems/derived/view_target_system.h deleted file mode 100644 index 1e0e915e..00000000 --- a/plugins/filament_view/core/systems/derived/view_target_system.h +++ /dev/null @@ -1,70 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include -#include -#include - -namespace plugin_filament_view { - -class ViewTarget; -class Camera; - -constexpr size_t kMainViewId = 0; // The main view target is always the first one in the list. - -class ViewTargetSystem : public System { - public: - ViewTargetSystem() = default; - - // Disallow copy and assign. - ViewTargetSystem(const ViewTargetSystem&) = delete; - ViewTargetSystem& operator=(const ViewTargetSystem&) = delete; - - void onSystemInit() override; - void update(double deltaTime) override; - void onDestroy() override; - void debugPrint() override; - - // Returns the current iter that you put into the list. - size_t nSetupViewTargetFromDesktopState( - int32_t top, - int32_t left, - FlutterDesktopEngineState* state - ); - - void KickOffFrameRenderingLoops() const; - - /// Returns the view target at the specified index. - [[nodiscard]] ViewTarget* getViewTarget(size_t index) const; - - /// Returns the main view target, which is the first one in the list. - [[nodiscard]] inline ViewTarget* getMainViewTarget() const { - return getViewTarget(kMainViewId); - } - - /// Sets a camera as the main camera for the given view target. - void setViewCamera(size_t viewId, EntityGUID cameraId); - - /// Initializes a camera entity - void initializeEntity(EntityGUID entityGuid); - - private: - std::vector> _viewTargets; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/ecs.cc b/plugins/filament_view/core/systems/ecs.cc deleted file mode 100644 index 7a08d966..00000000 --- a/plugins/filament_view/core/systems/ecs.cc +++ /dev/null @@ -1,580 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "ecs.h" - -// #include -#include -#include -#include // NOLINT -#include - -namespace plugin_filament_view { - -template class KVTree>; - -//////////////////////////////////////////////////////////////////////////// -ECSManager* ECSManager::m_poInstance = nullptr; - -//////////////////////////////////////////////////////////////////////////// -ECSManager::~ECSManager() { spdlog::trace("ECSManager~"); } - -//////////////////////////////////////////////////////////////////////////// -ECSManager::ECSManager() - : _entitiesMutex(), - _entities(), - _componentsMutex(), - _components(), - _systemsMutex(), - _systems(), - io_context_(std::make_unique(ASIO_CONCURRENCY_HINT_1)), - work_(make_work_guard(io_context_->get_executor())), - strand_(std::make_unique(*io_context_)), - m_eCurrentState(NotInitialized) { - spdlog::trace("++ECSManager++"); - setupThreadingInternals(); -} - -/// NOTE: THIS IS DEPRECATED, temporarily; right now the Wayland callback in ViewTarget calls the -/// main loop -void ECSManager::StartMainLoop() { - if (m_eCurrentState != Initialized) { - return; - } - - spdlog::info("\n\n\n === Starting ECS main loop ===\n"); - m_eCurrentState = Running; - m_bSpawnedThreadFinished = false; - - // Launch MainLoop in a separate thread - loopThread_ = std::thread(&ECSManager::MainLoop, this); -} - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::setupThreadingInternals() { - filament_api_thread_ = std::thread([this] { - // Save this thread's ID as it runs io_context_->run() - filament_api_thread_id_ = pthread_self(); - - // Optionally set the thread name - pthread_setname_np(filament_api_thread_id_, "ECSManagerThreadRunner"); - - spdlog::debug("ECSManager Filament API thread started: 0x{:x}", filament_api_thread_id_); - - io_context_->run(); - }); -} - -std::chrono::duration _sleepOverhead = std::chrono::duration(0.00006); // 0.06ms - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::MainLoop() { - constexpr std::chrono::microseconds frameTime(long(1000000 / 60)); // ~1/60 second - - // Initialize lastFrameTime to the current time - auto lastFrameTime = std::chrono::steady_clock::now(); - - m_eCurrentState = Running; - while (m_eCurrentState == Running) { - auto start = std::chrono::steady_clock::now(); - - // Calculate the time difference between this frame and the last frame - std::chrono::duration elapsedTime = start - lastFrameTime; - - if (!isHandlerExecuting.load()) { - // Use a promise to wait for the work to be done - auto awaiter = std::promise(); - - // Use asio::post to schedule work on the main thread (API thread) - post(*strand_, [elapsedTime = elapsedTime.count(), &awaiter, this]() mutable { - isHandlerExecuting.store(true); - try { - // update(elapsedTime); // Pass elapsed time to the main thread - } catch (...) { - isHandlerExecuting.store(false); - // TODO: Handle exceptions properly - // throw; // Rethrow the exception after resetting the flag - awaiter.set_exception(std::current_exception()); - } - isHandlerExecuting.store(false); - - // Notify that the work is done - awaiter.set_value(); - }); - - // Wait for the work to be done - try { - awaiter.get_future().wait(); - } catch (const std::exception& e) { - spdlog::error("Exception in ECSManager main loop: {}", e.what()); - // Handle the exception as needed - } - } - - // Update the time for the next frame - lastFrameTime = start; - - auto end = std::chrono::steady_clock::now(); - std::chrono::duration elapsed = end - start; - - spdlog::debug("[ECS] Frametime: {:.2f} ms", elapsed.count() * 1000.0); - - // Sleep for the remaining time in the frame - if (elapsed < frameTime) { - auto intendedSleepDuration = frameTime - elapsed; - - auto sleepStart = std::chrono::steady_clock::now(); - std::this_thread::sleep_for(intendedSleepDuration - _sleepOverhead); // 0.06ms sleep overhead - std::chrono::duration sleepDuration = std::chrono::steady_clock::now() - sleepStart; - - _sleepOverhead = sleepDuration - intendedSleepDuration - + _sleepOverhead; // Update the overhead for next time - _sleepOverhead = std::clamp( - _sleepOverhead, std::chrono::duration(-1), std::chrono::duration(1) - ); - - // spdlog::debug("Sleep overhead: {:.2f} ms", _sleepOverhead.count() * 1000.0); - // spdlog::debug("Sleep: {:.2f} ms", sleepDuration.count() * 1000.0); - // spdlog::debug("Total frame time: {:.2f} ms", (elapsed + sleepDuration).count() * 1000.0); - } - } - m_eCurrentState = ShutdownStarted; - - m_bSpawnedThreadFinished = true; -} - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::StopMainLoop() { - m_eCurrentState = ShutdownStarted; - if (loopThread_.joinable()) { - loopThread_.join(); - } - - // Stop the io_context - io_context_->stop(); - - // reset the work guard - work_.reset(); - - // Join the filament_api_thread_ - if (filament_api_thread_.joinable()) { - filament_api_thread_.join(); - } -} - -// -// Entity -// -void ECSManager::checkHasEntity(EntityGUID id) { - std::lock_guard lock(_entitiesMutex); - - spdlog::trace("[{}] Checking if entity with id {} exists", __FUNCTION__, id); - if (id == kNullGuid || _entities.get(id) == nullptr) { - throw std::runtime_error(fmt::format("[{}] Unable to find entity with id {}", __FUNCTION__, id) - ); - } -} - -void ECSManager::addEntity(const std::shared_ptr& entity, const EntityGUID* parent) { - { // lock scope - std::lock_guard lock(_entitiesMutex); - const EntityGUID id = entity->getGuid(); - if (_entities.get(id)) { - spdlog::error("[{}] Entity with GUID {} already exists", __FUNCTION__, id); - return; - } - - _entities.insert(id, entity, parent); - } // unlock here (entity init will lock again) - - // initialize the entity - entity->initialize(this); -} - -void ECSManager::removeEntity(const EntityGUID id) { - // EntityObject* entity = getEntity(id).get(); - - std::lock_guard lock(_entitiesMutex); - - // remove all components belonging to this entity - for (auto& [componentId, componentMap] : _components) { - auto it = componentMap.find(id); - if (it != componentMap.end()) { - // TODO: destroy the component before removing it - componentMap.erase(it); - } - } - - // remove the entity from the tree - _entities.remove(id); - - // TODO: make sure all children are removed too -} - -std::shared_ptr ECSManager::getEntity(EntityGUID id) { - std::lock_guard lock(_entitiesMutex); - - const auto* node = _entities.get(id); - if (!node) { - spdlog::error( - "[{}] Unable to find " - "entity with id {}", - __FUNCTION__, id - ); - return nullptr; - } - return *(node->getValue()); -} - -void ECSManager::reparentEntity( - const std::shared_ptr& entity, - const EntityGUID& parentGuid -) { - try { - _entities.reparent(entity->getGuid(), &parentGuid); - } catch (const std::runtime_error& e) { - spdlog::error("[ECSManager::ReparentEntityObject] {}", e.what()); - } -} - -std::vector ECSManager::getEntityChildrenGuids(EntityGUID id) { - const auto* node = _entities.get(id); - if (!node) { - spdlog::error("[{}] Unable to find entity with id {}", __FUNCTION__, id); - return {}; - } - - std::vector>*> childrenNodes = - node->getChildren(); - - std::vector childrenGuids; - childrenGuids.reserve(childrenNodes.size()); - for (const auto* childNode : childrenNodes) { - childrenGuids.push_back(childNode->getKey()); - } - - return childrenGuids; -} - -std::vector> ECSManager::getEntityChildren(EntityGUID id) { - std::vector childrenGuids = getEntityChildrenGuids(id); - - std::vector> children; - children.reserve(childrenGuids.size()); - for (const auto& childGuid : childrenGuids) { - const auto child = getEntity(childGuid); - if (child) { - children.push_back(child); - } - } - - return children; -} - -std::optional ECSManager::getEntityParentGuid(EntityGUID id) { - const auto* node = _entities.get(id); - if (!node) { - spdlog::error( - "[ECSManager::getEntityParentGuid] Unable to find " - "entity with id {}", - id - ); - return std::nullopt; - } - - const auto* parentNode = node->getParent(); - if (!parentNode) { - return std::nullopt; - } - - return parentNode->getKey(); -} - -std::vector> ECSManager::getEntitiesWithComponent( - TypeID componentTypeId -) { - std::unique_lock lock(_componentsMutex); - std::vector> entitiesWithComponent; - - auto componentMap = _components[componentTypeId]; - for (const auto& [entityGuid, component] : componentMap) { - auto entity = getEntity(entityGuid); - if (entity) { - entitiesWithComponent.emplace_back(entity); - } - } - - return entitiesWithComponent; -} - -// -// Component -// - -std::shared_ptr ECSManager::getComponent( - const EntityGUID& entityGuid, - TypeID componentTypeId -) { - std::unique_lock lock(_componentsMutex); - auto componentMap = _components[componentTypeId]; - auto it = componentMap.find(entityGuid); - if (it != componentMap.end()) { - return it->second; - } else { - return nullptr; - } -} - -std::vector> ECSManager::getComponentsOfType(TypeID componentTypeId) { - std::unique_lock lock(_componentsMutex); - std::vector> componentsOfType; - - /// TODO: this does a memcopy, nuh-uh - auto componentMap = _components[componentTypeId]; - for (const auto& [entityGuid, component] : componentMap) { - componentsOfType.emplace_back(component); - } - - return componentsOfType; -} - -bool ECSManager::hasComponent(const EntityGUID entityGuid, TypeID componentTypeId) { - checkHasEntity(entityGuid); - - std::unique_lock lock(_componentsMutex); - auto componentMap = _components[componentTypeId]; - return componentMap.find(entityGuid) != componentMap.end(); -} - -void ECSManager::addComponent( - const EntityGUID entityGuid, - const std::shared_ptr& component -) { - // Check if the entity exists - checkHasEntity(entityGuid); - EntityObject* entity = getEntity(entityGuid).get(); - - // Add the component to the map - const TypeID componentId = component->getTypeID(); - std::unique_lock lock(_componentsMutex); - - if (_components.find(componentId) == _components.end()) { - _components[componentId] = std::map>(); - } - - auto& componentMap = _components[componentId]; - - // Check if the component already exists for this entity - if (componentMap[entityGuid]) { - spdlog::warn( - "[{}] Component '{}' already exists for entity({}), overwriting", // - __FUNCTION__, component->getTypeName(), entityGuid - ); - } - - // Add the component to the entity - componentMap[entityGuid] = component; - entity->onAddComponent(component); - spdlog::trace( - "[{}] Added component {} to entity with id {}", __FUNCTION__, component->getTypeName(), - entityGuid - ); -} - -std::vector> ECSManager::getComponentsOfEntity( - const EntityGUID& entityGuid -) { - std::unique_lock lock(_componentsMutex); - std::vector> entityComponents; - - for (const auto& [componentId, componentMap] : _components) { - auto it = componentMap.find(entityGuid); - if (it != componentMap.end()) { - entityComponents.push_back(it->second); - } - } - - return entityComponents; -} - -void ECSManager::removeComponent(const EntityGUID& entityGuid, TypeID componentTypeId) { - std::unique_lock lock(_componentsMutex); - auto componentMap = _components[componentTypeId]; - componentMap.erase(entityGuid); -} - -// -// System -// - -void ECSManager::initialize() { - // Note this is currently expected to be called from within - // an already asio post, Leaving this commented out so you know - // that you could change up the routine, but if you do - // it needs to run on the main thread. - // asio::post(*ECSManager::GetInstance()->getStrand(), [&] { - std::string systemName = "(null)"; - for (auto& [systemId, system] : _systems) { - try { - systemName = system->getTypeName(); - spdlog::debug( - "Initializing system {} ({}) at address {}", systemName, systemId, - static_cast(system.get()) - ); - - system->initialize(*const_cast(this)); - } catch (const std::exception& e) { -#ifndef CRASH_ON_INIT - spdlog::error("Failed to initialize system {} ({}): {}", systemName, systemId, e.what()); -#else - throw std::runtime_error( - fmt::format("Failed to initialize system {} ({}): {}", systemName, systemId, e.what()) - ); -#endif - } - } - - spdlog::info("All systems initialized"); - m_eCurrentState = Initialized; -} - -std::shared_ptr ECSManager::getSystem(TypeID systemTypeID, const std::string& where) { - if (const auto callingThread = pthread_self(); callingThread != filament_api_thread_id_) { - // Note we should have a 'log once' base functionality in common - // creating this inline for now. - if (const auto foundIter = m_mapOffThreadCallers.find(where); - foundIter == m_mapOffThreadCallers.end()) { - spdlog::info( - "From {} " - "You're calling to get a system from an off thread, undefined " - "experience!" - " Use a message to do your work or grab the ecsystemmanager strand " - "and " - "do your work.", - where - ); - - m_mapOffThreadCallers.insert(std::pair(where, 0)); - } - } - - std::unique_lock lock(_systemsMutex); - auto it = _systems.find(systemTypeID); - if (it != _systems.end()) { - return it->second; // Return the found system - } else { - return nullptr; // If no matching system found - } -} - -void ECSManager::addSystem(const std::shared_ptr& system) { - std::unique_lock lock(_systemsMutex); - const TypeID systemId = system->getTypeID(); - - // Check if the system is already registered - if (_systems.find(systemId) != _systems.end()) { - throw std::runtime_error( - fmt::format("System {} ({}) is already registered", system->getTypeName(), systemId) - ); - } - - spdlog::trace( - "Adding system {} ({}) at address {}", system->getTypeName(), systemId, - static_cast(system.get()) - ); - - _systems[systemId] = system; -} - -void ECSManager::removeSystem(TypeID systemTypeId) { - std::unique_lock lock(_systemsMutex); - - auto system = getSystem(systemTypeId, __FUNCTION__); - system->onDestroy(); - _systems.erase(systemTypeId); - - spdlog::trace( - "Removed system {} ({}) at address {}", // - system->getTypeName(), systemTypeId, static_cast(system.get()) - ); -} - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::update(const double deltaTime) { - /// NOTE: this is temporary until the main loop gets refactored - m_eCurrentState = Running; - - // Copy systems under mutex - std::map> systemsCopy; - { - std::unique_lock lock(_systemsMutex); - - // Copy the systems map - systemsCopy = _systems; - } // Mutex is unlocked here - - // Iterate over the copy without holding the mutex - for (auto& [id, system] : systemsCopy) { - if (system) { - system->ProcessMessages(); - system->update(deltaTime); - } else { - spdlog::error("Encountered null system pointer!"); - } - } -} - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::debugPrint() const { - for (auto& [id, system] : _systems) { - spdlog::debug( - "[{}] system {} at address {}, " - "use_count={}", - __FUNCTION__, system->getTypeName(), static_cast(system.get()), system.use_count() - ); - } -} - -//////////////////////////////////////////////////////////////////////////// -void ECSManager::destroy() { - post(*this->getStrand(), [&] { - // we shutdown in reverse, until we have a 'system dependency tree' type of - // view, filament system (which is always the first system, needs to be - // shutdown last as its 'engine' varible is used in destruction for other - // systems - // for (auto& [id, system] : _systems) { - // (*it)->onDestroy(); - // } - for (auto it = _systems.rbegin(); it != _systems.rend(); ++it) { - const auto& id = it->first; - const auto& system = it->second; - - if (system) { - spdlog::trace( - "Shutting down system {} ({}) at address {}", system->getTypeName(), id, - static_cast(system.get()) - ); - - removeSystem(id); // Remove the system from the map - } else { - spdlog::error("Encountered null system pointer!"); - } - } - - m_eCurrentState = Shutdown; - }); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/ecs.h b/plugins/filament_view/core/systems/ecs.h deleted file mode 100644 index 68782a9b..00000000 --- a/plugins/filament_view/core/systems/ecs.h +++ /dev/null @@ -1,294 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include -#include -#include - -#define CRASH_ON_INIT // if true, will not continue if any System fails to - // init - -namespace plugin_filament_view { - -class ECSManager { - public: - enum RunState { NotInitialized, Initialized, Running, ShutdownStarted, Shutdown }; - - private: - std::map m_mapConfigurationValues; - - void setupThreadingInternals(); - - void MainLoop(); - - // - // Entity - // - std::mutex _entitiesMutex; - KVTree> _entities; - - // - // Component - // - - std::mutex _componentsMutex; - /// Map of component type IDs to their corresponding entityID->component maps - std::map>> _components; - - // - // System - // - - std::mutex _systemsMutex; - std::map> _systems; - - // - // Threading - // - std::atomic m_bSpawnedThreadFinished{false}; - std::atomic isHandlerExecuting{false}; - - std::thread filament_api_thread_; - pthread_t filament_api_thread_id_{}; - std::unique_ptr io_context_; - asio::executor_work_guardget_executor())> work_; - std::unique_ptr strand_; - std::thread loopThread_; - - std::map m_mapOffThreadCallers; - - std::atomic m_eCurrentState{NotInitialized}; - static ECSManager* m_poInstance; - - ECSManager(); - ~ECSManager(); - - public: - [[nodiscard]] inline static RunState GetRunState() { - if (m_poInstance == nullptr) { - return NotInitialized; - } else { - return m_poInstance->m_eCurrentState; - } - } - - [[nodiscard]] inline RunState getRunState() const { return m_eCurrentState; } - - [[nodiscard]] inline static ECSManager* GetInstance() { - if (m_poInstance == nullptr) { - m_poInstance = new ECSManager(); - } - return m_poInstance; - } - - ECSManager(const ECSManager&) = delete; - ECSManager& operator=(const ECSManager&) = delete; - - void initialize(); - - /** - * @brief Updates the engine logic for the current frame. - * - * It's called once per frame and is responsible for updating - * all engine entities, systems, and logic based on the elapsed time since - * the last frame. - * - * NOTE: must be run on the main thread. - * - * @param deltaTime The time elapsed since the last frame, in seconds. - * This value should be used to make all movement and - * time-based calculations frame rate independent. - */ - void update(double deltaTime); - void destroy(); - - void debugPrint() const; - - void StartMainLoop(); - void StopMainLoop(); - - [[nodiscard]] bool bIsCompletedStopping() const { return m_bSpawnedThreadFinished; } - - // - // Entity - // - void addEntity(const std::shared_ptr& entity, const EntityGUID* parent = nullptr); - void removeEntity(const EntityGUID entityGuid); - [[nodiscard]] std::shared_ptr getEntity(EntityGUID id); - - /// Moves the entity with the given GUID to the parent with the given GUID. - void reparentEntity(const std::shared_ptr& entity, const EntityGUID& parentGuid); - /// Returns the children of the entity with the given GUID. - [[nodiscard]] std::vector> getEntityChildren(EntityGUID id); - /// Returns the GUIDs of the children of the entity with the given GUID. - [[nodiscard]] std::vector getEntityChildrenGuids(EntityGUID id); - - /// Returns the parent of the entity with the given GUID. - [[nodiscard]] std::shared_ptr getEntityParent(EntityGUID id); - /// Returns the GUID of the parent of the entity with the given GUID. - [[nodiscard]] std::optional getEntityParentGuid(EntityGUID id); - - /// Returns all enttities having a component of the given type. - template - [[nodiscard]] std::vector> getEntitiesWithComponent() { - return getEntitiesWithComponent(Component::StaticGetTypeID()); - } - - [[nodiscard]] std::vector> getEntitiesWithComponent( - TypeID componentTypeId - ); - - /// Checks whether the entity with the given GUID exists. - /// @throws std::runtime_error if the entity does not exist. - void checkHasEntity(EntityGUID id); - - // - // Component - // - - /// Adds a component to the entity with the given GUID. - void addComponent(const EntityGUID entityGuid, const std::shared_ptr& component); - - /// Removes a component from the entity with the given GUID. - /// If either the entity or the component does not exist, nothing happens. - template inline void removeComponent(const EntityGUID& entityGuid) { - removeComponent(entityGuid, Component::StaticGetTypeID()); - } - - void removeComponent(const EntityGUID& entityGuid, TypeID componentTypeId); - - /// Returns the component of the given type from the entity with the given - /// GUID. - template - [[nodiscard]] inline std::shared_ptr getComponent(const EntityGUID& entityGuid) { - return std::dynamic_pointer_cast(getComponent(entityGuid, Component::StaticGetTypeID()) - ); - } - - [[nodiscard]] std::shared_ptr getComponent( - const EntityGUID& entityGuid, - TypeID componentTypeId - ); - - /// Returns all the components of the given type - template - [[nodiscard]] inline std::vector> getComponentsOfType() { - // cast vector type - /// TODO: this does a memcopy, nuh-uh - std::vector> components; - auto tmp = getComponentsOfType(Component::StaticGetTypeID()); - components.reserve(tmp.size()); - for (const auto& component : tmp) { - components.push_back(std::dynamic_pointer_cast(component)); - } - return components; - } - - [[nodiscard]] std::vector> getComponentsOfType(TypeID componentTypeId - ); - - /// Returns whether the entity with the given GUID has a component of the - /// given type. - template [[nodiscard]] inline bool hasComponent(const EntityGUID& entityGuid) { - return hasComponent(entityGuid, Component::StaticGetTypeID()); - } - - [[nodiscard]] bool hasComponent(const EntityGUID entityGuid, TypeID componentTypeId); - - /// Returns a vector of pointers to all components of the entity with the - /// given GUID. - [[nodiscard]] std::vector> getComponentsOfEntity( - const EntityGUID& entityGuid - ); - - // - // System - // - template - [[nodiscard]] inline std::shared_ptr getSystem(const std::string& where) { - return std::dynamic_pointer_cast(getSystem(System::StaticGetTypeID(), where)); - } - - [[nodiscard]] std::shared_ptr getSystem(TypeID systemTypeID, const std::string& where); - void addSystem(const std::shared_ptr& system); - - template inline void removeSystem() { removeSystem(System::StaticGetTypeID()); }; - - void removeSystem(TypeID systemTypeId); - - /** - * Send a message to all registered systems - * \deprecated Deprecated in favor of queueTask - */ - void RouteMessage(const ECSMessage& msg) { - std::unique_lock lock(_systemsMutex); - // for (const auto& system : _systems) { - // system->SendMessage(msg); - // } - - // _systems is a map - for (auto& [_, system] : _systems) { - system->SendMessage(msg); - } - } - - // - // Threading - // - - [[nodiscard]] inline pthread_t getFilamentAPIThreadID() const { - return filament_api_thread_id_; - } - - [[nodiscard]] inline const std::thread& getFilamentAPIThread() const { - return filament_api_thread_; - } - - [[nodiscard]] inline std::unique_ptr& getStrand() { return strand_; } - - // - // Global state (configuration) - // - - template void inline setConfigValue(const std::string& key, T value) { - m_mapConfigurationValues[key] = value; - } - - // getter for any type of value - template T getConfigValue(const std::string& key) const { - auto it = m_mapConfigurationValues.find(key); - if (it != m_mapConfigurationValues.end()) { - try { - return std::any_cast(it->second); // Cast the value to the expected type - } catch (const std::bad_any_cast& e) { - throw std::runtime_error("Error: Incorrect type for key: " + key); - } - } else { - throw std::runtime_error("Error: Key not found: " + key); - } - } -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/messages/ecs_message.h b/plugins/filament_view/core/systems/messages/ecs_message.h deleted file mode 100644 index e80198d1..00000000 --- a/plugins/filament_view/core/systems/messages/ecs_message.h +++ /dev/null @@ -1,61 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include "ecs_message_types.h" - -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -struct EnumClassHash { - template std::size_t operator()(T t) const { return static_cast(t); } -}; - -// Message class that can hold variable data amounts -class ECSMessage { - public: - // Add data to the message - template void addData(ECSMessageType type, const T& value) { data_[type] = value; } - - // Get data from the message - template T getData(ECSMessageType type) const { - auto it = data_.find(type); - if (it != data_.end()) { - try { - return std::any_cast(it->second); - } catch (const std::bad_any_cast& e) { - throw std::runtime_error( - "Type mismatch for key. Expected type: " + std::string(typeid(T).name()) - ); - } - } - throw std::runtime_error("Message type not found"); - } - - // Check if the message contains a specific type - [[nodiscard]] bool hasData(ECSMessageType type) const { - return data_.find(type) != data_.end(); - } - - private: - std::unordered_map data_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/systems/messages/ecs_message_types.h b/plugins/filament_view/core/systems/messages/ecs_message_types.h deleted file mode 100644 index 66392c74..00000000 --- a/plugins/filament_view/core/systems/messages/ecs_message_types.h +++ /dev/null @@ -1,89 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once -namespace plugin_filament_view { - -enum class ECSMessageType { - DebugLine, - - CollisionRequest, - CollisionRequestRequestor, - CollisionRequestType, - - ViewTargetCreateRequest, - ViewTargetCreateRequestTop, - ViewTargetCreateRequestLeft, - ViewTargetCreateRequestWidth, - ViewTargetCreateRequestHeight, - - ViewTargetStartRenderingLoops, - - SetCameraFromDeserializedLoad, - - ToggleShapesInScene, - SetShapeTransform, - ToggleDebugCollidableViewsInScene, - - ChangeSceneLightProperties, - ChangeSceneLightPropertiesColorValue, - ChangeSceneLightPropertiesIntensity, - ChangeSceneLightTransform, - Position, - Rotation, - Direction, - Scale, - - ChangeSceneIndirectLightProperties, - ChangeSceneIndirectLightPropertiesIntensity, - - ChangeViewQualitySettings, - ChangeViewQualitySettingsWhichView, - - SetFogOptions, - - ChangeMaterialParameter, - EntityToTarget, - ChangeMaterialDefinitions, - - ResizeWindow, - ResizeWindowWidth, - ResizeWindowHeight, - - MoveWindow, - MoveWindowTop, - MoveWindowLeft, - - AnimationEnqueue, - AnimationClearQueue, - AnimationPlay, - AnimationChangeSpeed, - AnimationPause, - AnimationResume, - AnimationSetLooping, - - floatVec3, - floatVec4, - - ChangeCameraOrbitHomePosition, - ChangeCameraTargetPosition, - ChangeCameraFlightStartPosition, - - ToggleVisualForEntity, - ToggleCollisionForEntity, - BoolValue, -}; - -} diff --git a/plugins/filament_view/core/utils/asserts.cc b/plugins/filament_view/core/utils/asserts.cc deleted file mode 100644 index 62e3b0e8..00000000 --- a/plugins/filament_view/core/utils/asserts.cc +++ /dev/null @@ -1,18 +0,0 @@ -#include - -#include -#include -#include - -namespace plugin_filament_view { - -/// Convenience function to assert a condition at runtime. -/// Throws a runtime_error with a given message if the condition is false. -/// TODO: refactor every `if(x != nullptr) throw ...` to use this -void runtime_assert(bool condition, const char* message) { - if (!condition) { - throw std::runtime_error(message); - } -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/asserts.h b/plugins/filament_view/core/utils/asserts.h deleted file mode 100644 index 661920b4..00000000 --- a/plugins/filament_view/core/utils/asserts.h +++ /dev/null @@ -1,17 +0,0 @@ -#pragma once - -#include - -namespace plugin_filament_view { - -/// Convenience function to assert a condition at runtime. -/// Throws a runtime_error with a given message if the condition is false. -void runtime_assert(bool condition, const char* message); - -inline void runtime_assert(bool condition, const std::string& message) { - runtime_assert(condition, message.c_str()); -} - -#define debug_assert(condition, message) assert(condition&& message); - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/bounding_volumes.h b/plugins/filament_view/core/utils/bounding_volumes.h deleted file mode 100644 index e137df21..00000000 --- a/plugins/filament_view/core/utils/bounding_volumes.h +++ /dev/null @@ -1,32 +0,0 @@ - -#pragma once - -#include - -namespace plugin_filament_view { - -using AABB = filament::Box; - -class BoundingSphere { - public: - filament::math::float3 center; - float radius; - - BoundingSphere() - : center(filament::math::float3(0, 0, 0)), - radius(0) {} - - explicit BoundingSphere(const filament::math::float3& center, float radius) - : center(center), - radius(radius) {} - - explicit BoundingSphere(const AABB& aabb) - : center(aabb.center), - radius(0) { - // Set radius to max half extent - const filament::math::float3 halfExtent = aabb.halfExtent; - radius = std::max({halfExtent.x, halfExtent.y, halfExtent.z}); - } -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/deserialize.cc b/plugins/filament_view/core/utils/deserialize.cc deleted file mode 100644 index 534a3b97..00000000 --- a/plugins/filament_view/core/utils/deserialize.cc +++ /dev/null @@ -1,199 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "deserialize.h" - -namespace plugin_filament_view { - -//////////////////////////////////////////////////////////////////////////// -filament::math::float3 Deserialize::Format3(const flutter::EncodableMap& map) { - double x = 0, y = 0, z = 0.0f; - - for (const auto& [fst, snd] : map) { - if (snd.IsNull() || !std::holds_alternative(snd)) continue; - - const auto currValue = std::get(snd); - - if (auto key = std::get(fst); key == "x") { - x = currValue; - } else if (key == "y") { - y = currValue; - } else if (key == "z") { - z = currValue; - } - } - return {static_cast(x), static_cast(y), static_cast(z)}; -} - -//////////////////////////////////////////////////////////////////////////// -filament::math::quatf Deserialize::Format4(const flutter::EncodableMap& map) { - double x = 0, y = 0, z = 0, w = 0.0f; - w = 1.0f; - - for (const auto& [fst, snd] : map) { - if (snd.IsNull()) continue; - - if (auto key = std::get(fst); key == "x" && std::holds_alternative(snd)) { - x = std::get(snd); - } else if (key == "y" && std::holds_alternative(snd)) { - y = std::get(snd); - } else if (key == "z" && std::holds_alternative(snd)) { - z = std::get(snd); - } else if (key == "w" && std::holds_alternative(snd)) { - w = std::get(snd); - } - } - return { - static_cast(w), static_cast(x), static_cast(y), static_cast(z) - }; -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefault( - const char* key, - std::optional>& out_value, - const flutter::EncodableMap& params -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative(it->second)) { - out_value = std::make_unique(std::get(it->second)); - } else { - out_value.reset(); // or set it to std::nullopt if desired - } -} - -//////////////////////////////////////////////////////////////////////////// -bool Deserialize::DecodeParameterWithDefault( - const char* key, - filament::math::float3* out_value, - const flutter::EncodableMap& params, - const filament::math::float3& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative(it->second)) { - *out_value = Format3(std::get(it->second)); - return true; - } - *out_value = default_value; - return false; -} - -bool Deserialize::DecodeColor3WithDefault( - const char* key, - filament::math::float3* out_value, - const flutter::EncodableMap& params, - const filament::math::float3& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative>(it->second)) { - - const auto& colorList = std::get>(it->second); - if (colorList.size() >= 3) { - *out_value = { - static_cast(colorList[0]), // - static_cast(colorList[1]), // - static_cast(colorList[2]) // - }; - return true; - } else { - spdlog::warn( - "Color list for key '{}' does not have enough elements, it has {}", key, colorList.size() - ); - } - } else { - spdlog::debug("Key '{}' not found or wrong type for color3", key); - } - *out_value = default_value; - return false; -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefault( - const char* key, - filament::math::quatf* out_value, - const flutter::EncodableMap& params, - const filament::math::quatf& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative(it->second)) { - *out_value = Format4(std::get(it->second)); - } else { - *out_value = default_value; - } -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefault( - const char* key, - double* out_value, - const flutter::EncodableMap& params, - const double& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative(it->second)) { - *out_value = std::get(it->second); - } else { - *out_value = default_value; - } -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefault( - const char* key, - float* out_value, - const flutter::EncodableMap& params, - const float& default_value -) { - double dValue = 0.0; - DecodeParameterWithDefault(key, &dValue, params, default_value); - *out_value = static_cast(dValue); -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefault( - const char* key, - std::string* out_value, - const flutter::EncodableMap& params, - const std::string& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it != params.end() && std::holds_alternative(it->second)) { - *out_value = std::get(it->second); - } else { - *out_value = default_value; - } -} - -//////////////////////////////////////////////////////////////////////////// -void Deserialize::DecodeParameterWithDefaultInt64( - const char* key, - int64_t* out_value, - const flutter::EncodableMap& params, - const int64_t& default_value -) { - if (const auto it = params.find(flutter::EncodableValue(key)); - it == params.end() || std::holds_alternative(it->second)) { - *out_value = default_value; - } else if (std::holds_alternative(it->second)) { - *out_value = std::get(it->second); - } else if (std::holds_alternative(it->second)) { - *out_value = std::get(it->second); - } else { - spdlog::debug("Unhandled type for key: {}", key); - *out_value = default_value; - } -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/deserialize.h b/plugins/filament_view/core/utils/deserialize.h deleted file mode 100644 index c9960e6a..00000000 --- a/plugins/filament_view/core/utils/deserialize.h +++ /dev/null @@ -1,183 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include - -#include - -#include -#include - -namespace plugin_filament_view { - -class Deserialize { - public: - Deserialize() = default; - static ::filament::math::float3 Format3(const flutter::EncodableMap& map); - static ::filament::math::quatf Format4(const flutter::EncodableMap& map); - - /// @returns true if the given key exists in the map and is not null. - static bool HasKey(const flutter::EncodableMap& params, const char* key) { - const auto it = params.find(flutter::EncodableValue(key)); - return it != params.end() && !it->second.IsNull(); - } - - /// @brief Decode a parameter from the given map. - /// @throws std::runtime_error if the parameter is not found or is of the - /// wrong type. - template - static T DecodeParameter(const char* key, const flutter::EncodableMap& params) { - auto it = params.find(flutter::EncodableValue(key)); - if (it != params.end() && std::holds_alternative(it->second)) { - return std::get(it->second); - } else { - throw std::runtime_error(fmt::format("Parameter '{}' not found or wrong type", key)); - } - } - - /// @brief Decode an optional parameter from the given map. - /// @returns std::optional containing the value if found, or std::nullopt - /// if not. - template - static std::optional DecodeOptionalParameter( - const char* key, - const flutter::EncodableMap& params - ) { - auto it = params.find(flutter::EncodableValue(key)); - if (it != params.end() && std::holds_alternative(it->second)) { - return std::get(it->second); - } else { - return std::nullopt; - } - } - - /* - * Decoders with default values - */ - - /// @returns true if the parameter was found and set to out_value, - /// false if it was not found and out_value was set to default_value. - template - static bool DecodeParameterWithDefault( - const char* key, - T* out_value, - const flutter::EncodableMap& params, - const T& default_value - ) { - auto it = params.find(flutter::EncodableValue(key)); - if (it != params.end() && std::holds_alternative(it->second)) { - *out_value = std::get(it->second); - return true; - } else { - *out_value = default_value; - return false; - } - } - - template - static T DecodeParameterWithDefault( - const char* key, - const flutter::EncodableMap& params, - const T& default_value - ) { - auto it = params.find(flutter::EncodableValue(key)); - if (it != params.end() && std::holds_alternative(it->second)) { - return std::get(it->second); - } else { - return default_value; - } - } - - // Overload for enum types (e.g., ShapeType) - template - static void DecodeEnumParameterWithDefault( - const char* key, - T* out_value, - const flutter::EncodableMap& params, - const T& default_value, - std::enable_if_t::value>* = nullptr - ) { - using UnderlyingType = typename std::underlying_type::type; - auto it = params.find(flutter::EncodableValue(key)); - if (it != params.end() && std::holds_alternative(it->second)) { - *out_value = static_cast(std::get(it->second)); - } else { - *out_value = default_value; - } - } - - static void DecodeParameterWithDefault( - const char* key, - std::optional>& out_value, - const flutter::EncodableMap& params - ); - - static bool DecodeParameterWithDefault( - const char* key, - filament::math::float3* out_value, - const flutter::EncodableMap& params, - const filament::math::float3& default_value - ); - - static bool DecodeColor3WithDefault( - const char* key, - filament::math::float3* out_value, - const flutter::EncodableMap& params, - const filament::math::float3& default_value - ); - - static void DecodeParameterWithDefault( - const char* key, - filament::math::quatf* out_value, - const flutter::EncodableMap& params, - const filament::math::quatf& default_value - ); - - static void DecodeParameterWithDefault( - const char* key, - double* out_value, - const flutter::EncodableMap& params, - const double& default_value - ); - - static void DecodeParameterWithDefault( - const char* key, - std::string* out_value, - const flutter::EncodableMap& params, - const std::string& default_value - ); - - // Note std::get only supports double, this will take your double - // and cast to float; this of course can truncate your value - static void DecodeParameterWithDefault( - const char* key, - float* out_value, - const flutter::EncodableMap& params, - const float& default_value - ); - - // Takes either int32 or int64 and casts to int64 - static void DecodeParameterWithDefaultInt64( - const char* key, - int64_t* out_value, - const flutter::EncodableMap& params, - const int64_t& default_value - ); -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/filament_types.h b/plugins/filament_view/core/utils/filament_types.h deleted file mode 100644 index d6b13a84..00000000 --- a/plugins/filament_view/core/utils/filament_types.h +++ /dev/null @@ -1,20 +0,0 @@ -#include -#include - -#include -#include - -namespace plugin_filament_view { - -/// Represents an entity in the Filament engine. -/// Lightweight object: can be passed around by value (it's just an ID). -using FilamentEntity = utils::Entity; - -/// Represents a Filament entity instance. -/// Lightweight object: can be passed around by value (it's just an ID). -template using FilamentEntityInstance = utils::EntityInstance; -using FilamentTransformInstance = FilamentEntityInstance; -using FilamentRenderableInstance = FilamentEntityInstance; -using FilamentCameraComponent = filament::Camera; - -}; // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/hdr_loader.cc b/plugins/filament_view/core/utils/hdr_loader.cc deleted file mode 100644 index 8fbee27e..00000000 --- a/plugins/filament_view/core/utils/hdr_loader.cc +++ /dev/null @@ -1,94 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include "hdr_loader.h" - -#include -#include - -#include -#include - -namespace plugin_filament_view { - -using namespace filament; -using namespace image; -using namespace utils; - -//////////////////////////////////////////////////////////////////////////// -Texture* HDRLoader::deleteImageAndLogError(const LinearImage* image) { - spdlog::error("Unable to create Filament Texture from HDR image."); - delete image; - return nullptr; -} - -//////////////////////////////////////////////////////////////////////////// -Texture* HDRLoader::createTextureFromImage(Engine* engine, LinearImage* image) { - if (image->getChannels() != 3) { - return deleteImageAndLogError(image); - } - - Texture* texture = Texture::Builder() - .width(image->getWidth()) - .height(image->getHeight()) - .levels(0xff) - .format(Texture::InternalFormat::R11F_G11F_B10F) - .sampler(Texture::Sampler::SAMPLER_2D) - .usage(Texture::Usage::DEFAULT | Texture::Usage::GEN_MIPMAPPABLE) - .build(*engine); - - if (!texture) { - return deleteImageAndLogError(image); - } - - const Texture::PixelBufferDescriptor::Callback freeCallback = - [](void* /* buf */, size_t, void* userdata) { delete static_cast(userdata); }; - - Texture::PixelBufferDescriptor pbd( - (image->getPixelRef()), - static_cast(image->getWidth()) * image->getHeight() * 3 * sizeof(float), - Texture::PixelBufferDescriptor::PixelDataFormat::RGB, - Texture::PixelBufferDescriptor::PixelDataType::FLOAT, freeCallback, image - ); - - texture->setImage(*engine, 0, std::move(pbd)); - texture->generateMipmaps(*engine); - return texture; -} - -//////////////////////////////////////////////////////////////////////////// -Texture* HDRLoader::createTexture( - Engine* engine, - const std::string& asset_path, - const std::string& name -) { - SPDLOG_DEBUG("Loading {}", asset_path.c_str()); - std::ifstream ins(asset_path, std::ios::binary); - auto* image = new LinearImage(ImageDecoder::decode(ins, name)); - return createTextureFromImage(engine, image); -} - -//////////////////////////////////////////////////////////////////////////// -Texture* HDRLoader::createTexture( - Engine* engine, - const std::vector& buffer, - const std::string& name -) { - const std::string str(buffer.begin(), buffer.end()); - std::istringstream ins(str); - auto* image = new LinearImage(ImageDecoder::decode(ins, name)); - return createTextureFromImage(engine, image); -} -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/hdr_loader.h b/plugins/filament_view/core/utils/hdr_loader.h deleted file mode 100644 index bc1c6d93..00000000 --- a/plugins/filament_view/core/utils/hdr_loader.h +++ /dev/null @@ -1,50 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { - -class HDRLoader { - public: - static ::filament::Texture* createTexture( - ::filament::Engine* engine, - const std::string& asset_path, - const std::string& name = "memory.hdr" - ); - - static ::filament::Texture* createTexture( - ::filament::Engine* engine, - const std::vector& buffer, - const std::string& name = "memory.hdr" - ); - - private: - static ::filament::Texture* deleteImageAndLogError(const image::LinearImage* image); - - static ::filament::Texture* createTextureFromImage( - ::filament::Engine* engine, - image::LinearImage* image - ); -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/ibl_profiler.h b/plugins/filament_view/core/utils/ibl_profiler.h deleted file mode 100644 index 172895d8..00000000 --- a/plugins/filament_view/core/utils/ibl_profiler.h +++ /dev/null @@ -1,93 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#pragma once - -#include -#include - -namespace plugin_filament_view { -/** - * IBLPrefilter creates and initializes GPU state common to all environment map - * filters - * - * Typically, only one instance per filament Engine of this object needs to - * exist. - * - * @see IBLPrefilterContext - */ -class IBLProfiler { - public: - explicit IBLProfiler(::filament::Engine* engine) - : context_(IBLPrefilterContext(*engine)), - equirectangularToCubeMap_(IBLPrefilterContext::EquirectangularToCubemap(context_)), - specularFilter_(IBLPrefilterContext::SpecularFilter(context_)) {} - - /** - * Converts an equirectangular image to a cubemap. - * - * @param equirect Texture to convert to a cubemap. - * - Can't be null. - * - Must be a 2d texture - * - Must have equirectangular geometry, that is width == 2*height. - * - Must be allocated with all mip levels. - * - Must be SAMPLEABLE - * - * @return the cubemap texture - * - * @see IBLPrefilterContext.EquirectangularToCubemap - */ - ::filament::Texture* createCubeMapTexture(const ::filament::Texture* equirect) { - return equirectangularToCubeMap_(equirect); - } - - /** - * Generates a prefiltered cubemap. - * - * SpecularFilter is a GPU based implementation of the specular probe - * pre-integration filter. - * - * ** Launch the heaver computation. Expect 100-100ms on the GPU.** - * - * @param skybox Environment cubemap. - * This cubemap is SAMPLED and have all its levels allocated. - * - * @return the reflections texture - */ - ::filament::Texture* getLightReflection(::filament::Texture* skybox) { - return specularFilter_(skybox); - } - - private: - IBLPrefilterContext context_; - - /** - * EquirectangularToCubemap is use to convert an equirectangular image to a - * cubemap - * - * Creates a EquirectangularToCubemap processor. - */ - IBLPrefilterContext::EquirectangularToCubemap equirectangularToCubeMap_; - - /** - * Created specular (reflections) filter. This operation generates the kernel, - * so it's important to keep it around if it will be reused for several - * cubemaps. An instance of SpecularFilter is needed per filter configuration. - * A filter configuration contains the filter's kernel and sample count. - */ - IBLPrefilterContext::SpecularFilter specularFilter_; -}; -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/identifiable_type.h b/plugins/filament_view/core/utils/identifiable_type.h deleted file mode 100644 index f735d892..00000000 --- a/plugins/filament_view/core/utils/identifiable_type.h +++ /dev/null @@ -1,62 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include - -/// @brief TypeID represents the ID of a type. -using TypeID = size_t; - -/** Base class that keeps track of subclass IDs and provides a way to - * identify them by type ID at runtime. - * Simplified implementation that doesn't require subclasses to override - * anything - */ -class IdentifiableType { - public: - IdentifiableType() = default; - virtual ~IdentifiableType() = default; - - /** Returns the name of the type as a string. */ - [[nodiscard]] virtual std::string getTypeName() { - // Set the type name - if (typeName_.empty()) { - // RTTI type name - // This is a compiler-specific way to get the type name - const char* name = typeid(*this).name(); - - // Demangle the name if possible - int status = -4; - char* demangled = abi::__cxa_demangle(name, nullptr, nullptr, &status); - if (status == 0) { - name = demangled; - } - - typeName_ = std::string(name); - } - - return typeName_; - } - - [[nodiscard]] virtual size_t getTypeID() const { return typeid(*this).hash_code(); } - - template [[nodiscard]] static size_t StaticGetTypeID() { - return typeid(T).hash_code(); - } - - private: - std::string typeName_; -}; diff --git a/plugins/filament_view/core/utils/kvtree.cc b/plugins/filament_view/core/utils/kvtree.cc deleted file mode 100644 index 8e14ca0f..00000000 --- a/plugins/filament_view/core/utils/kvtree.cc +++ /dev/null @@ -1,158 +0,0 @@ -#include "core/utils/kvtree.h" - -namespace plugin_filament_view { - -/* - * KVTree - */ - -template KVTree::~KVTree() { - // TODO -} - -template -KVTreeNode* KVTree::get(const Key& key) const { - auto it = nodeMap.find(key); - if (it != nodeMap.end()) { - return it->second; - } - return nullptr; -} - -template Value* KVTree::getValue(const Key& key) const { - KVTreeNode* node = get(key); - if (!node) { - throw std::runtime_error("Key not found in tree"); - } - return node->getValue(); -} - -template -void KVTree::insert(const Key& key, const Value& value, const Key* parentKey) { - // Ensure the key does not already exist. - if (nodeMap.find(key) != nodeMap.end()) { - throw std::runtime_error("Key already exists in tree"); - } - - // Insert key-value into the tree’s value map. - keyValueMap[key] = value; - - // Create a new node for this key. - auto* newNode = new KVTreeNode(key, this); - nodeMap[key] = newNode; - - // If a parent key is provided, add the new node as a child. - if (parentKey != nullptr) { - auto* parent = get(*parentKey); - // Exception: parent key not found. - if (!parent) { - throw std::runtime_error("Parent key not found"); - } - - parent->addChild(newNode); - newNode->parent = parent; - } -} - -template -void KVTree::reparent(const Key& key, const Key* parentKey) { - auto* node = get(key); - // Exception: key not found. - if (!node) { - throw std::runtime_error("Key not found"); - } - - auto* parent = parentKey ? get(const_cast(key)) - : nullptr; // nullptr if parent not found or is root. - // Exception: parent key not found. - if (parentKey && !parent) { - throw std::runtime_error("Parent key not found"); - } - - // Reparent. - if (node->parent) { - node->parent->removeChild(const_cast(key)); - } - if (parent) { - parent->addChild(node); - } - node->parent = parent; -} - -template void KVTree::remove(const Key& key) { - auto* node = get(key); - - // Exception: key not found. - if (!node) { - throw std::runtime_error("Key not found"); - } - - // Remove the node and its value. - nodeMap.erase(key); - keyValueMap.erase(key); - - // Remove the node from its parent’s children list. - if (node->parent) { - node->parent->removeChild(key); - } - - // Remove the children of the node. - // (this is done last for tail recursion) - for (auto* child : node->getChildren()) { - remove(const_cast(child->getKey())); - } -} - -template void KVTree::clear() { - // Clear the value map. - keyValueMap.clear(); - - // Delete all nodes. - for (auto& [key, node] : nodeMap) { - delete node; - } - nodeMap.clear(); -} - -/* - * KVTreeNode - */ - -template Value* KVTreeNode::getValue() const { - auto it = treePtr->keyValueMap.find(key); - if (it != treePtr->keyValueMap.end()) { - return &(it->second); - } - throw std::runtime_error("Key not found in value map"); -} - -template const Key& KVTreeNode::getKey() const { - return key; -} - -template -KVTreeNode* KVTreeNode::getParent() const { - return parent; -} - -template -const std::vector*>& KVTreeNode::getChildren() const { - // Copy the children vector to prevent modification. - auto* childrenCopy = new std::vector*>(children); - return *childrenCopy; -} - -template void KVTreeNode::addChild(KVTreeNode* child) { - children.push_back(child); -} - -template void KVTreeNode::removeChild(const Key& key) { - children.erase( - std::remove_if( - children.begin(), children.end(), [&](auto& item) { return item->getKey() == key; } - ), - children.end() - ); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/kvtree.h b/plugins/filament_view/core/utils/kvtree.h deleted file mode 100644 index 5fedd8c6..00000000 --- a/plugins/filament_view/core/utils/kvtree.h +++ /dev/null @@ -1,96 +0,0 @@ -#pragma once - -#include -#include -#include - -namespace plugin_filament_view { - -// Forward declaration of KVTree so that KVTreeNode can refer to it. -template class KVTree; - -template class KVTreeNode { - public: - // Retrieves the node’s associated value by looking up the key in the tree’s - // map. - Value* getValue() const; - - // Retrieves the node’s key. - const Key& getKey() const; - - // Retrieves the node’s parent. - KVTreeNode* getParent() const; - - // Retrieves the node’s children. - // The returned vector is a copy and can be modified without affecting the - // node. - const std::vector& getChildren() const; - - private: - Key key; - KVTreeNode* parent; - std::vector children; - KVTree* treePtr; - - // Constructor: only KVTree can create nodes. - KVTreeNode(const Key& key, KVTree* tree, KVTreeNode* parent = nullptr) - : key(key), - parent(parent), - treePtr(tree) {} - - // Add a child to this node. - void addChild(KVTreeNode* child); - - // Remove a child from this node. - // It does not delete - void removeChild(const Key& key); - - // Grant KVTree access to all members of KVTreeNode. - friend class KVTree; - - // Disable copy construction/assignment. - KVTreeNode(const KVTreeNode&) = delete; - KVTreeNode& operator=(const KVTreeNode&) = delete; -}; - -template class KVTree { - public: - KVTree() = default; - ~KVTree(); - - friend class KVTreeNode; - - // Retrieves the node associated with the given key. - // Returns a pointer to the node, or nullptr if not found. - KVTreeNode* get(const Key& key) const; - - // Convenience method that returns the value associated with the node - // identified by key. - Value* getValue(const Key& key) const; - - // Inserts a new node with the given key and value. - // If a parent key is provided (non-null), the new node is added as a child of - // that parent. If the parent key is not found, the new node is added as a - // root node (multiple roots are allowed). - void insert(const Key& key, const Value& value, const Key* parentKey = nullptr); - - // Reparents a node identified by key to a new parent identified by parentKey. - // If parentKey is null, the node becomes a root node. - void reparent(const Key& key, const Key* parentKey = nullptr); - - // Removes the node identified by the given key, all its children and - // associated values. - void remove(const Key& key); - - // Clears the tree of all nodes and values. - void clear(); - - private: - // Stores key-value associations. - std::unordered_map keyValueMap; - - // Stores key-node associations for O(1) node retrieval. - std::unordered_map*> nodeMap; -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/smarter_pointers.h b/plugins/filament_view/core/utils/smarter_pointers.h deleted file mode 100644 index 11f0bbcb..00000000 --- a/plugins/filament_view/core/utils/smarter_pointers.h +++ /dev/null @@ -1,137 +0,0 @@ -#pragma once - -#include -#include -#include -#include - -//============================================================================== -// 1) pointer_access

defines the two abstract operations: -// - get(p): returns a T* (or nullptr) no matter what P is -// - reset(p,r): (re)assigns p from raw pointer r -//============================================================================== - -template struct pointer_access; - -// — raw pointers — -template struct pointer_access { - using element_type = T; - static T* get(T* p) { return p; } - static void reset(T*& p, T* raw) { p = raw; } -}; - -// — std::weak_ptr — -template struct pointer_access> { - using element_type = T; - // lock() -> shared_ptr -> get() - static T* get(const std::weak_ptr& p) { - if (auto sp = p.lock()) return sp.get(); - return nullptr; - } - // reset() simply clears the weak_ptr - static void reset(std::weak_ptr& p, T*) { p.reset(); } -}; - -// — any P that has get() and reset(T*) members — -template -struct pointer_access< - P, - std::void_t< - decltype(std::declval

().get()), - decltype(std::declval

().reset(std::declval()))>> { - using element_type = typename P::element_type; - static element_type* get(const P& p) { return p.get(); } - static void reset(P& p, element_type* raw) { p.reset(raw); } -}; - -/// "Smarter" pointers -/// When calling a method on a smarter pointer, it will check whether the -/// underlying pointer is null and if so, it will throw an exception. -/// -/// I made this because the "real" smart pointers are clearly not smart enough. -template -// Template typename P to indicate the type of pointer, -// so later it can be used with shared_ptr, unique_ptr and weak_ptr -// Template typename T to indicate the type of object that the pointer points to -class smarter_ptr { - static_assert(!std::is_reference_v

, "P must not be a reference"); - // static_assert(std::is_destructible(), "T must be destructible"); - - private: - P _ptr; - - inline void check() const { - if (!pointer_access

::get(_ptr)) throw std::runtime_error("Dereferencing a null pointer"); - } - - public: - // default / null - smarter_ptr() = default; - smarter_ptr(std::nullptr_t) - : _ptr{} {} - - // from raw pointer - explicit smarter_ptr(T* raw) - : _ptr{} { - if (raw) pointer_access

::reset(_ptr, raw); - } - - // from any P - smarter_ptr(const P& other) - : _ptr(other) {} - - // deref / arrow - T& operator*() const { - check(); - return *pointer_access

::get(_ptr); - } - T* operator->() const { - check(); - return pointer_access

::get(_ptr); - } - - // assignment - // smarter_ptr& operator=(const P& other) { - // _ptr = other; - // return *this; - // } - smarter_ptr& operator=(T& raw) { - pointer_access

::reset(_ptr, &raw); - return *this; - } - smarter_ptr& operator=(T* raw) { - pointer_access

::reset(_ptr, raw); - return *this; - } - smarter_ptr& operator=(std::nullptr_t) { - pointer_access

::reset(_ptr, nullptr); - return *this; - } - - // implicit conversion back to P or raw T* - // operator P() const { - // return _ptr; - // } - operator T*() const { return pointer_access

::get(_ptr); } - - // boolean test - explicit operator bool() const { return pointer_access

::get(_ptr) != nullptr; } - - // comparisons - bool operator==(const smarter_ptr& o) const { - return pointer_access

::get(_ptr) == pointer_access

::get(o._ptr); - } - bool operator!=(const smarter_ptr& o) const { return !(*this == o); } - bool operator==(std::nullptr_t) const { return pointer_access

::get(_ptr) == nullptr; } - bool operator!=(std::nullptr_t) const { return pointer_access

::get(_ptr) != nullptr; } -}; - -//============================================================================== -// convenience aliases -//============================================================================== - -// TODO: test those smarter_smart pointers -template using smarter_shared_ptr = smarter_ptr>; -template using smarter_unique_ptr = smarter_ptr>; -template using smarter_weak_ptr = smarter_ptr>; -template using smarter_raw_ptr = smarter_ptr; diff --git a/plugins/filament_view/core/utils/uuidGenerator.cc b/plugins/filament_view/core/utils/uuidGenerator.cc deleted file mode 100644 index b3226913..00000000 --- a/plugins/filament_view/core/utils/uuidGenerator.cc +++ /dev/null @@ -1,35 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#include - -#include -#include - -namespace plugin_filament_view { - -int64_t _counter = 0; -const int64_t _preamble = 1; // odd number for CPP (Dart has even) -const int64_t _increment = 2; - -int64_t generateUUID() { - const int64_t id = ++_counter * _increment + _preamble; - - // spdlog::debug("[generateGuid-cpp] generated ID: {}", id); - - return id; -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/uuidGenerator.h b/plugins/filament_view/core/utils/uuidGenerator.h deleted file mode 100644 index 2444c963..00000000 --- a/plugins/filament_view/core/utils/uuidGenerator.h +++ /dev/null @@ -1,27 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include - -#include - -namespace plugin_filament_view { - -int64_t generateUUID(); - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/vectorutils.cc b/plugins/filament_view/core/utils/vectorutils.cc deleted file mode 100644 index 60fe5463..00000000 --- a/plugins/filament_view/core/utils/vectorutils.cc +++ /dev/null @@ -1,108 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "vectorutils.h" - -#include - -namespace plugin_filament_view { - -filament::math::mat3f VectorUtils::identity3x3() { - return { - filament::math::float3{1.0f, 0.0f, 0.0f}, filament::math::float3{0.0f, 1.0f, 0.0f}, - filament::math::float3{0.0f, 0.0f, 1.0f} - }; -} - -filament::math::mat4f VectorUtils::identity4x4() { - return { - filament::math::float4(1.0f, 0.0f, 0.0f, 0.0f), filament::math::float4(0.0f, 1.0f, 0.0f, 0.0f), - filament::math::float4(0.0f, 0.0f, 1.0f, 0.0f), filament::math::float4(0.0f, 0.0f, 0.0f, 1.0f) - }; -} - -filament::math::float3 VectorUtils::transformPositionVector( - const filament::math::float3& pos, - const filament::math::mat4f& transform -) { - // Apply the transformation matrix to the position vector - return { - transform[0].x * pos.x + transform[1].x * pos.y + transform[2].x * pos.z + transform[3].x, - transform[0].y * pos.x + transform[1].y * pos.y + transform[2].y * pos.z + transform[3].y, - transform[0].z * pos.x + transform[1].z * pos.y + transform[2].z * pos.z + transform[3].z - }; -} - -filament::math::float3 VectorUtils::transformScaleVector( - const filament::math::float3& scale, - const filament::math::mat4f& transform -) { - // Extract the scaling factors from the transformation matrix - // Apply the scaling factors to the scale vector - return { - scale.x * length(transform[0].xyz), scale.y * length(transform[1].xyz), - scale.z * length(transform[2].xyz) - }; -} - -filament::math::quatf VectorUtils::fromEulerAngles(float yaw, float pitch, float roll) { - const float halfYaw = yaw * 0.5f; - const float halfPitch = pitch * 0.5f; - const float halfRoll = roll * 0.5f; - const float cosYaw = cos(halfYaw); - const float sinYaw = sin(halfYaw); - const float cosPitch = cos(halfPitch); - const float sinPitch = sin(halfPitch); - const float cosRoll = cos(halfRoll); - const float sinRoll = sin(halfRoll); - - const float x = cosRoll * sinPitch * cosYaw + sinRoll * cosPitch * sinYaw; - const float y = cosRoll * cosPitch * sinYaw - sinRoll * sinPitch * cosYaw; - const float z = sinRoll * cosPitch * cosYaw - cosRoll * sinPitch * sinYaw; - const float w = cosRoll * cosPitch * cosYaw + sinRoll * sinPitch * sinYaw; - - return {w, x, y, z}; -} - -filament::math::quatf VectorUtils::lookAt( - const filament::math::float3& position, - const filament::math::float3& target -) { - const filament::math::float3 delta = target - position; - - // Calculate the XZ plane direction - filament::math::float2 xzDir = filament::math::float2(delta.z, delta.x); - // Calculate the lY plane direction - filament::math::float2 lYDir = filament::math::float2(length(xzDir), delta.y); - - // normalize vectors first - xzDir = normalize(xzDir); - lYDir = normalize(lYDir); - - // Calculate the rotation angle around the Y axis - float azimuth = atan2(xzDir.y, xzDir.x); - // Calculate the rotation angle around the X axis - float elevation = atan2(lYDir.y, lYDir.x); - - // Create the quaternion representing the rotation - return VectorUtils::fromEulerAngles( - azimuth + kPif, // Yaw (Y-axis rotation) - elevation, // Pitch (X-axis rotation) - 0.0f // Roll (Z-axis rotation, not used here) - ); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/core/utils/vectorutils.h b/plugins/filament_view/core/utils/vectorutils.h deleted file mode 100644 index 84bb17f6..00000000 --- a/plugins/filament_view/core/utils/vectorutils.h +++ /dev/null @@ -1,144 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -namespace plugin_filament_view { - -/// Float version of M_PI -static constexpr float kPif = static_cast(M_PI); - -class VectorUtils { - public: - /// Static identity quaternion - // NOTE: Filament's quaternion constructor takes WXYZ, not XYZW!!! - static constexpr filament::math::quatf kIdentityQuat = - filament::math::quatf(1.0f, 0.0f, 0.0f, 0.0f); - - /// Static identity 3x3 matrix - static constexpr filament::math::mat3f kIdentityMat3f = filament::math::mat3f( - 1.0f, - 0.0f, - 0.0f, // - 0.0f, - 1.0f, - 0.0f, // - 0.0f, - 0.0f, - 1.0f // - ); - - /// Static identity 4x4 matrix - static constexpr filament::math::mat4f kIdentityMat4f = filament::math::mat4f( - 1.0f, - 0.0f, - 0.0f, - 0.0f, // - 0.0f, - 1.0f, - 0.0f, - 0.0f, // - 0.0f, - 0.0f, - 1.0f, - 0.0f, // - 0.0f, - 0.0f, - 0.0f, - 1.0f // - ); - - /// Vector3 zero - static constexpr filament::math::float3 kFloat3Zero = filament::math::float3( - 0.0f, // x - 0.0f, // y - 0.0f // z - ); - - /// Vector3 one - static constexpr filament::math::float3 kFloat3One = filament::math::float3( - 1.0f, // x - 1.0f, // y - 1.0f // z - ); - - /// Vector3 up direction - static constexpr filament::math::float3 kUp3 = filament::math::float3( - 0.0f, // x - 1.0f, // y - 0.0f // z - ); - - /// Vector3 down direction - static constexpr filament::math::float3 kDown3 = filament::math::float3( - 0.0f, // x - -1.0f, // y - 0.0f // z - ); - - /// Vector3 forward direction - static constexpr filament::math::float3 kForward3 = filament::math::float3( - 0.0f, // x - 0.0f, // y - -1.0f // z - ); - - /// Utility function to create an identity 3x3 matrix - - // Utility functions to create identity matrices - static filament::math::mat3f identity3x3(); - static filament::math::mat4f identity4x4(); - - static filament::math::float3 transformPositionVector( - const filament::math::float3& pos, - const filament::math::mat4f& transform - ); - static filament::math::float3 transformScaleVector( - const filament::math::float3& scale, - const filament::math::mat4f& transform - ); - - /// Converts Euler angles (in radians) to a quaternion. - /// @param yaw Yaw angle in radians (Euler angle Y) - /// @param pitch Pitch angle in radians (Euler angle X) - /// @param roll Roll angle in radians (Euler angle Z) - /// @returns Quaternion representing the rotation. - /// @note up always points to Y+ axis. - static filament::math::quatf fromEulerAngles(float yaw, float pitch, float roll); - - static filament::math::quatf lookAt( - const filament::math::float3& position, - const filament::math::float3& target - ); - - /// Returns the translation component of a transformation matrix. - static inline filament::math::float3 translationFromMatrix(const filament::math::mat4f& matrix - ) { - return filament::math::float3(matrix[3].x, matrix[3].y, matrix[3].z); - } -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/filament_view_plugin.cc b/plugins/filament_view/filament_view_plugin.cc deleted file mode 100644 index c2bed59f..00000000 --- a/plugins/filament_view/filament_view_plugin.cc +++ /dev/null @@ -1,843 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include "filament_view_plugin.h" - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -class FlutterView; - -class Display; - -namespace plugin_filament_view { - -std::unique_ptr sceneTextDeserializer; -SceneTextDeserializer* postSetupDeserializer = nullptr; -bool m_bHasSetupRegistrar = false; - -////////////////////////////////////////////////////////////////////////////////////////// -void RunOnceCheckAndInitializeECSystems() { - const auto ecs = ECSManager::GetInstance(); - - // Make sure we only initialize once - if (ecs->getRunState() != ECSManager::RunState::NotInitialized) { - return; - } - - // Get the strand from the ECSManager - const auto& strand = *ecs->getStrand(); - - std::promise initPromise; - const std::future initFuture = initPromise.get_future(); - - // Post the initialization code to the strand - post(strand, [=, &initPromise]() mutable { - // Add systems to the ECSManager - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - ecs->addSystem(std::make_unique()); - // Internal debate whether we auto subscribe to systems on entity creation - // or not. - - ecs->initialize(); - - initPromise.set_value(); - }); - - initFuture.wait(); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void KickOffRenderingLoops() { - ECSMessage viewTargetStartRendering; - viewTargetStartRendering.addData(ECSMessageType::ViewTargetStartRenderingLoops, true); - ECSManager::GetInstance()->RouteMessage(viewTargetStartRendering); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void DeserializeDataAndSetupMessageChannels( - flutter::PluginRegistrar* registrar, - const std::vector& params -) { - const auto ecs = ECSManager::GetInstance(); - - // Get the strand from the ECSManager - const auto& strand = *ecs->getStrand(); - - std::promise initPromise; - const std::future initFuture = initPromise.get_future(); - - // Safeguarded to only be called once no matter how many times this method is - // called. - if (postSetupDeserializer == nullptr) { - post(strand, [=, &initPromise]() mutable { - spdlog::trace("running SceneTextDeserializer"); - sceneTextDeserializer = std::make_unique(params); - postSetupDeserializer = sceneTextDeserializer.get(); - - // making sure this is only called once! - postSetupDeserializer->RunPostSetupLoad(); - - initPromise.set_value(); - }); - - initFuture.wait(); - } - - spdlog::trace("getting systems"); - const auto animationSystem = ecs->getSystem(__FUNCTION__); - - const auto viewTargetSystem = ecs->getSystem(__FUNCTION__); - - const auto collisionSystem = ecs->getSystem(__FUNCTION__); - - collisionSystem->setupMessageChannels(registrar, "plugin.filament_view.collision_info"); - viewTargetSystem->setupMessageChannels(registrar, "plugin.filament_view.frame_view"); - animationSystem->setupMessageChannels(registrar, "plugin.filament_view.animation_info"); -} - -std::future FilamentViewPlugin::CallEvent( - const std::string& eventName, - std::initializer_list> data -) { - int64_t eventId = _eventIdCounter++; - - flutter::EncodableMap encodableMap; - encodableMap.insert( - {flutter::EncodableValue("_internal_eventId"), flutter::EncodableValue(eventId)} - ); - for (const auto& [fst, snd] : data) { - encodableMap[flutter::EncodableValue(fst)] = snd; // NOLINT - } - - // Post and await promise - auto promise = std::make_shared>(); - auto future = promise->get_future(); - - FilamentViewPlugin::_eventCallbacks[eventId] = std::move(promise); - - spdlog::trace("InvokeMethod: calling event {}", eventName); - auto retval = std::make_unique>( // - [&, eventId](const auto* /*result*/) { - spdlog::trace("[EventBus] Event completed successfully"); - auto it = FilamentViewPlugin::_eventCallbacks.find(eventId); - if (it != FilamentViewPlugin::_eventCallbacks.end()) { - it->second->set_value(); - FilamentViewPlugin::_eventCallbacks.erase(it); - } - }, - [&, eventId](const auto& error_code, const auto& error_message, const auto* /*result*/) { - spdlog::error("[EventBus] Event failed with error code {}: {}", error_code, error_message); - auto it = FilamentViewPlugin::_eventCallbacks.find(eventId); - if (it != FilamentViewPlugin::_eventCallbacks.end()) { - it->second->set_value(); - FilamentViewPlugin::_eventCallbacks.erase(it); - } - }, - [&, eventId]() { - spdlog::warn("[EventBus] Event was not implemented"); - auto it = FilamentViewPlugin::_eventCallbacks.find(eventId); - if (it != FilamentViewPlugin::_eventCallbacks.end()) { - it->second->set_value(); - FilamentViewPlugin::_eventCallbacks.erase(it); - } - } - ); - - FilamentViewPlugin::eventBus->InvokeMethod( - "call_" + eventName, - // wrap map in unique_ptr EncodableValue - std::make_unique(encodableMap), std::move(retval) - ); - spdlog::trace("InvokeMethod done! Returning future"); - - return future; -} - -std::unique_ptr> FilamentViewPlugin::eventBus = - nullptr; -int64_t FilamentViewPlugin::_eventIdCounter = 0; -std::map>> FilamentViewPlugin::_eventCallbacks; - -bool _hasLoadedOnce = false; - -////////////////////////////////////////////////////////////////////////////////////////// -void FilamentViewPlugin::RegisterWithRegistrar( - flutter::PluginRegistrar* registrar, - int32_t id, - std::string viewType, - int32_t direction, - double top, - double left, - double width, - double height, - const std::vector& params, - const std::string& assetDirectory, - FlutterDesktopEngineRef engine, - PlatformViewAddListener addListener, - PlatformViewRemoveListener removeListener, - void* platform_view_context -) { - // Make sure we only initialize once - if (_hasLoadedOnce) { - spdlog::warn("FilamentViewPlugin::RegisterWithRegistrar called more than once!"); - return; - } - - _hasLoadedOnce = true; - - pthread_setname_np(pthread_self(), "HomeScreenFilamentViewPlugin"); - - const auto ecs = ECSManager::GetInstance(); - ecs->setConfigValue(kAssetPath, assetDirectory); - - /*bool bDebugAttached = false; - int i = 0; - while (!bDebugAttached) { - int breakhere = 0; - if (i++ == 10000000000) { - bDebugAttached = true; - } - }*/ - - // Safeguarded inside - RunOnceCheckAndInitializeECSystems(); - - // Every time this method is called, we should create a new view target - ECSMessage viewTargetCreationRequest; - viewTargetCreationRequest.addData(ECSMessageType::ViewTargetCreateRequest, engine); - viewTargetCreationRequest.addData( - ECSMessageType::ViewTargetCreateRequestTop, static_cast(top) - ); - viewTargetCreationRequest.addData( - ECSMessageType::ViewTargetCreateRequestLeft, static_cast(left) - ); - viewTargetCreationRequest.addData( - ECSMessageType::ViewTargetCreateRequestWidth, static_cast(width) - ); - viewTargetCreationRequest.addData( - ECSMessageType::ViewTargetCreateRequestHeight, static_cast(height) - ); - - ecs->RouteMessage(viewTargetCreationRequest); - - // Safeguarded to only be called once internal - DeserializeDataAndSetupMessageChannels(registrar, params); - - if (!m_bHasSetupRegistrar) { - m_bHasSetupRegistrar = true; - - // - auto plugin = std::make_unique( - id, std::move(viewType), direction, top, left, width, height, params, assetDirectory, - addListener, removeListener, platform_view_context - ); - - // Set up message channels and APIs - SetUp(registrar->messenger(), plugin.get()); - - registrar->AddPlugin(std::move(plugin)); - - setupMessageChannels(registrar); - } - - // Ok to be called infinite times. - KickOffRenderingLoops(); - - spdlog::debug("Initialization completed"); -} - -////////////////////////////////////////////////////////////////////////////////////////// -FilamentViewPlugin::FilamentViewPlugin( - const int32_t id, - std::string viewType, - const int32_t direction, - const double top, - const double left, - const double width, - const double height, - const std::vector& /*params*/, - const std::string& /*assetDirectory*/, - const PlatformViewAddListener addListener, - const PlatformViewRemoveListener removeListener, - void* platform_view_context -) - : PlatformView(id, std::move(viewType), direction, top, left, width, height), - id_(id), - platformViewsContext_(platform_view_context), - removeListener_(removeListener) { - SPDLOG_TRACE("++FilamentViewPlugin::FilamentViewPlugin"); - - addListener(platformViewsContext_, id, &platform_view_listener_, this); - - SPDLOG_TRACE("--FilamentViewPlugin::FilamentViewPlugin"); -} - -////////////////////////////////////////////////////////////////////////////////////////// -FilamentViewPlugin::~FilamentViewPlugin() { - removeListener_(platformViewsContext_, id_); - - ECSManager::GetInstance()->destroy(); - // wait for thread to stop running. (Should be relatively quick) - while (ECSManager::GetInstance()->bIsCompletedStopping() == false) { - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::unique_ptr> eventSink_; -void FilamentViewPlugin::setupMessageChannels(flutter::PluginRegistrar* registrar -) { // Set up event bus - FilamentViewPlugin::eventBus = std::make_unique>( - registrar->messenger(), // - "plugin.filament_view.event_bus", // - &flutter::StandardMethodCodec::GetInstance() - ); - - FilamentViewPlugin::eventBus->SetMethodCallHandler( - [&](const auto& call, std::unique_ptr> result) { - const std::string& method = call.method_name(); - spdlog::debug("[EventBus] Received method call: {}", method); - - // Handle callbacks - if (method.rfind("ret_") == 0) { - const std::string eventName = method.substr(4); - spdlog::debug("[EventBus] Handling event: {}", eventName); - - // Get event ID (EncodableValue) - const flutter::EncodableValue* callArg = call.arguments(); - int64_t eventId = std::get(*callArg); - spdlog::debug("[EventBus] Event ID: {}", eventId); - // Fetch promise and set value - if (FilamentViewPlugin::_eventCallbacks.find(eventId) - != FilamentViewPlugin::_eventCallbacks.end()) { - FilamentViewPlugin::_eventCallbacks[eventId]->set_value(); - FilamentViewPlugin::_eventCallbacks.erase(eventId); - result->Success(); - } else { - spdlog::warn("[EventBus] Unhandled event ID: {}", eventId); - result->Error("Unhandled event ID"); - } - } else { - spdlog::warn("[EventBus] Unhandled method call: {}", method); - result->Error("Unhandled method call"); - } - } - ); - - // Setup MethodChannel for readiness check - const std::string readinessMethodChannel = "plugin.filament_view.readiness_checker"; - - const auto methodChannel = std::make_unique>( - registrar->messenger(), readinessMethodChannel, &flutter::StandardMethodCodec::GetInstance() - ); - - methodChannel->SetMethodCallHandler( - [&](const flutter::MethodCall<>& call, const std::unique_ptr>& result) { - if (call.method_name() == "isReady") { - // Check readiness and respond - bool isReady = ECSManager::GetRunState() == ECSManager::RunState::Running; - spdlog::debug("Readiness check: {}", static_cast(ECSManager::GetRunState())); - result->Success(flutter::EncodableValue(isReady)); - } else { - result->NotImplemented(); - } - } - ); -} - -////////////////////////////////////////////////////////////////////////////////////////// -void FilamentViewPlugin::sendReadyEvent() { - if (eventSink_) { - eventSink_->Success(flutter::EncodableValue("ready")); - } -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeMaterialParameter( - const flutter::EncodableMap& params, - const int64_t guid -) { - ECSMessage materialData; - materialData.addData(ECSMessageType::ChangeMaterialParameter, params); - materialData.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(materialData); - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeMaterialDefinition( - const flutter::EncodableMap& params, - const int64_t guid -) { - ECSMessage materialData; - materialData.addData(ECSMessageType::ChangeMaterialDefinitions, params); - materialData.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(materialData); - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ToggleShapesInScene(const bool value) { - ECSMessage toggleMessage; - toggleMessage.addData(ECSMessageType::ToggleShapesInScene, value); - ECSManager::GetInstance()->RouteMessage(toggleMessage); - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ToggleDebugCollidableViewsInScene(const bool value -) { - ECSMessage toggleMessage; - toggleMessage.addData(ECSMessageType::ToggleDebugCollidableViewsInScene, value); - ECSManager::GetInstance()->RouteMessage(toggleMessage); - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeViewQualitySettings() { - static int qualitySettingsVal = 0; - ECSMessage qualitySettings; - qualitySettings.addData(ECSMessageType::ChangeViewQualitySettings, qualitySettingsVal); - ECSManager::GetInstance()->RouteMessage(qualitySettings); - - qualitySettingsVal++; - if (qualitySettingsVal > ViewTarget::ePredefinedQualitySettings::Ultra) { - qualitySettingsVal = 0; - } - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::SetFogOptions(const bool enabled) { - ECSMessage fogData; - fogData.addData(ECSMessageType::SetFogOptions, enabled); - ECSManager::GetInstance()->RouteMessage(fogData); - - return std::nullopt; -} - -/* - * Camera - */ -std::optional FilamentViewPlugin::SetCameraOrbit( - int64_t id, - int64_t origin_entity_id, - const std::vector& orbit_rotation -) { - spdlog::trace("SetCameraOrbit"); - - const auto ecs = ECSManager::GetInstance(); - // Get camera component - const auto camera = ecs->getComponent(id); - - const auto oldTarget = camera->orbitOriginEntity; - camera->orbitOriginEntity = origin_entity_id; - camera->orbitRotation = filament::math::quatf( - orbit_rotation[3], orbit_rotation[0], orbit_rotation[1], orbit_rotation[2] - ); - - if (oldTarget != origin_entity_id) { - spdlog::debug("Camera target set to entity: {}", origin_entity_id); - } - - return std::nullopt; -} - -std::optional FilamentViewPlugin::SetCameraTarget( - int64_t id, - int64_t target_entity_id, - const std::vector* target_position -) { - spdlog::trace("SetCameraTarget"); - - const auto ecs = ECSManager::GetInstance(); - // Get camera component - const auto camera = ecs->getComponent(id); - - camera->enableTarget = !!target_position && target_entity_id != kNullGuid; - camera->targetEntity = target_entity_id; - if (target_position) { - camera->targetPoint = filament::math::float3( - (*target_position)[0], (*target_position)[1], (*target_position)[2] - ); - } - - spdlog::debug("Camera target set to entity: {}", target_entity_id); - return std::nullopt; -} - -std::optional FilamentViewPlugin::SetActiveCamera( - const int64_t* view_id, - int64_t camera_id -) { - spdlog::trace("SetActiveCamera"); - - size_t viewIndex = view_id != nullptr ? static_cast(*view_id) : 0; - EntityGUID cameraId = camera_id; - - const auto viewSystem = ECSManager::GetInstance()->getSystem(__FUNCTION__); - viewSystem->setViewCamera(viewIndex, cameraId); - - spdlog::debug("Camera {} set as active for view {}", cameraId, viewIndex); - return std::nullopt; -} - -std::optional FilamentViewPlugin::SetCameraDolly( - int64_t id, - const std::vector& dolly_offset -) { - spdlog::trace("SetCameraDolly"); - - const auto ecs = ECSManager::GetInstance(); - // Get camera component - const auto camera = ecs->getComponent(id); - - camera->dollyOffset = filament::math::float3(dolly_offset[0], dolly_offset[1], dolly_offset[2]); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeLightTransformByGUID( - const int64_t guid, - double posx, - double posy, - double posz, - double dirx, - double diry, - double dirz -) { - filament::math::float3 position( - static_cast(posx), static_cast(posy), static_cast(posz) - ); - filament::math::float3 direction( - static_cast(dirx), static_cast(diry), static_cast(dirz) - ); - - ECSMessage lightData; - lightData.addData(ECSMessageType::ChangeSceneLightTransform, guid); - lightData.addData(ECSMessageType::Position, position); - lightData.addData(ECSMessageType::Direction, direction); - ECSManager::GetInstance()->RouteMessage(lightData); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeLightColorByGUID( - const int64_t guid, - const std::vector& color, - const double intensity -) { - ECSMessage lightData; - lightData.addData(ECSMessageType::ChangeSceneLightProperties, guid); - lightData.addData(ECSMessageType::floatVec4, color); - lightData.addData( - ECSMessageType::ChangeSceneLightPropertiesIntensity, static_cast(intensity) - ); - ECSManager::GetInstance()->RouteMessage(lightData); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::EnqueueAnimation( - const int64_t guid, - const int64_t animation_index -) { - ECSMessage enqueueMessage; - enqueueMessage.addData(ECSMessageType::AnimationEnqueue, static_cast(animation_index)); - enqueueMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(enqueueMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ClearAnimationQueue(const int64_t guid) { - ECSMessage clearQueueMessage; - clearQueueMessage.addData(ECSMessageType::AnimationClearQueue, guid); - clearQueueMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(clearQueueMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::PlayAnimation( - const int64_t guid, - const int64_t animation_index -) { - ECSMessage playMessage; - playMessage.addData(ECSMessageType::AnimationPlay, static_cast(animation_index)); - playMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(playMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ChangeAnimationSpeed( - const int64_t guid, - const double speed -) { - ECSMessage changeSpeedMessage; - changeSpeedMessage.addData(ECSMessageType::AnimationChangeSpeed, static_cast(speed)); - changeSpeedMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(changeSpeedMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::PauseAnimation(const int64_t guid) { - ECSMessage pauseMessage; - pauseMessage.addData(ECSMessageType::AnimationPause, guid); - pauseMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(pauseMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::ResumeAnimation(const int64_t guid) { - ECSMessage resumeMessage; - resumeMessage.addData(ECSMessageType::AnimationResume, guid); - resumeMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(resumeMessage); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::SetAnimationLooping( - const int64_t guid, - const bool looping -) { - ECSMessage setLoopingMessage; - setLoopingMessage.addData(ECSMessageType::AnimationSetLooping, looping); - setLoopingMessage.addData(ECSMessageType::EntityToTarget, guid); - ECSManager::GetInstance()->RouteMessage(setLoopingMessage); - - return std::nullopt; -} - -std::optional FilamentViewPlugin::RaycastFromTap(double x, double y) { - asio::post(*ECSManager::GetInstance()->getStrand(), [&, x, y] { - const auto ecs = ECSManager::GetInstance(); - const auto viewTargetSystem = ecs->getSystem( - "FilamentViewPlugin::RaycastFromTap" - ); - viewTargetSystem->getMainViewTarget()->onTouch(x, y); - }); - - return std::nullopt; -} - -std::optional FilamentViewPlugin::RequestCollisionCheckFromRay( - const std::string& query_id, - double origin_x, - double origin_y, - double origin_z, - double direction_x, - double direction_y, - double direction_z, - double length -) { - filament::math::float3 origin( - static_cast(origin_x), static_cast(origin_y), static_cast(origin_z) - ); - filament::math::float3 direction( - static_cast(direction_x), static_cast(direction_y), - static_cast(direction_z) - ); - - Ray rayInfo(origin, direction, static_cast(length)); - - // Debug line message - ECSMessage rayInformation; - rayInformation.addData(ECSMessageType::DebugLine, rayInfo); - ECSManager::GetInstance()->RouteMessage(rayInformation); - - // Collision request message - ECSMessage collisionRequest; - collisionRequest.addData(ECSMessageType::CollisionRequest, rayInfo); - collisionRequest.addData(ECSMessageType::CollisionRequestRequestor, query_id); - collisionRequest.addData(ECSMessageType::CollisionRequestType, eFromNonNative); - ECSManager::GetInstance()->RouteMessage(collisionRequest); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::SetEntityTransformScale( - const int64_t guid, - const std::vector& scl -) { - ECSManager::GetInstance()->getComponent(guid)->setScale({scl[0], scl[1], scl[2]}); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::SetEntityTransformPosition( - const int64_t guid, - const std::vector& pos -) { - ECSManager::GetInstance()->getComponent(guid)->setPosition({pos[0], pos[1], pos[2]}); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::SetEntityTransformRotation( - const int64_t guid, - const std::vector& rot -) { - ECSManager::GetInstance()->getComponent(guid)->setRotation( - /// NOTE: Filament quat constructor takes WXYZ!!! It's still stored in memory as XYZW. - /// TODO: when Float32List is supported in pigeon, just cast the array to quatf - {rot[3], rot[0], rot[1], rot[2]} - ); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::TurnOffVisualForEntity(const int64_t guid) { - ECSMessage changeRequest; - changeRequest.addData(ECSMessageType::ToggleVisualForEntity, guid); - changeRequest.addData(ECSMessageType::BoolValue, false); - ECSManager::GetInstance()->RouteMessage(changeRequest); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::TurnOnVisualForEntity(const int64_t guid) { - ECSMessage changeRequest; - changeRequest.addData(ECSMessageType::ToggleVisualForEntity, guid); - changeRequest.addData(ECSMessageType::BoolValue, true); - ECSManager::GetInstance()->RouteMessage(changeRequest); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::TurnOffCollisionChecksForEntity(const int64_t guid -) { - ECSMessage changeRequest; - changeRequest.addData(ECSMessageType::ToggleCollisionForEntity, guid); - changeRequest.addData(ECSMessageType::BoolValue, false); - ECSManager::GetInstance()->RouteMessage(changeRequest); - - return std::nullopt; -} - -////////////////////////////////////////////////////////////////////////////////////////// -std::optional FilamentViewPlugin::TurnOnCollisionChecksForEntity(const int64_t guid) { - ECSMessage changeRequest; - changeRequest.addData(ECSMessageType::ToggleCollisionForEntity, guid); - changeRequest.addData(ECSMessageType::BoolValue, true); - ECSManager::GetInstance()->RouteMessage(changeRequest); - - return std::nullopt; -} - -// TODO this function will need to change to say 'which' view is being changed. -void FilamentViewPlugin::on_resize(const double width, const double height, void* /*data*/) { - if (width <= 0 || height <= 0) { - return; - } - - ECSMessage resizeMessage; - resizeMessage.addData(ECSMessageType::ResizeWindow, static_cast(0)); - resizeMessage.addData(ECSMessageType::ResizeWindowWidth, width); - resizeMessage.addData(ECSMessageType::ResizeWindowHeight, height); - ECSManager::GetInstance()->RouteMessage(resizeMessage); -} - -void FilamentViewPlugin::on_set_direction(const int32_t direction, void* data) { - const auto plugin = static_cast(data); - if (plugin) { - plugin->direction_ = direction; - } - SPDLOG_TRACE("SetDirection: {}", plugin->direction_); -} - -// TODO this function will need to change to say 'which' view is being changed. -void FilamentViewPlugin::on_set_offset(const double left, const double top, void* /*data*/) { - ECSMessage moveMessage; - moveMessage.addData(ECSMessageType::MoveWindow, static_cast(0)); - moveMessage.addData(ECSMessageType::MoveWindowLeft, left); - moveMessage.addData(ECSMessageType::MoveWindowTop, top); - ECSManager::GetInstance()->RouteMessage(moveMessage); -} - -void FilamentViewPlugin::on_touch( - const int32_t /*action*/, - const int32_t /*point_count*/, - const size_t /*point_data_size*/, - const double* /*point_data*/, - void* /*data*/ -) { - // NOTE: unused! all touch events are handled by Flutter and passed to handlers as necessary -} - -void FilamentViewPlugin::on_dispose(bool /* hybrid */, void* /* data */) { - spdlog::warn("[FilamentViewPlugin] on_dispose not currently implemented"); -} - -const platform_view_listener FilamentViewPlugin::platform_view_listener_ = { - .resize = on_resize, - .set_direction = on_set_direction, - .set_offset = on_set_offset, - .on_touch = on_touch, - .dispose = on_dispose, - .accept_gesture = nullptr, - .reject_gesture = nullptr, -}; - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/filament_view_plugin.h b/plugins/filament_view/filament_view_plugin.h deleted file mode 100644 index 263aee40..00000000 --- a/plugins/filament_view/filament_view_plugin.h +++ /dev/null @@ -1,196 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once -#ifndef FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_H_ -#define FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_H_ - -#include -#include - -#include -#include -#include -#include -#include -#include - -namespace plugin_filament_view { - -class FilamentViewPlugin : public flutter::Plugin, public FilamentViewApi, public PlatformView { - public: - static std::unique_ptr> eventBus; - static std::map>> _eventCallbacks; - - static int64_t _eventIdCounter; - - static std::future CallEvent( - const std::string& eventName, - std::initializer_list> data - ); - - static void RegisterWithRegistrar( - flutter::PluginRegistrar* registrar, - int32_t id, - std::string viewType, - int32_t direction, - double top, - double left, - double width, - double height, - const std::vector& params, - const std::string& assetDirectory, - FlutterDesktopEngineRef engine, - PlatformViewAddListener addListener, - PlatformViewRemoveListener removeListener, - void* platform_view_context - ); - - FilamentViewPlugin( - int32_t id, - std::string viewType, - int32_t direction, - double top, - double left, - double width, - double height, - const std::vector& params, - const std::string& assetDirectory, - PlatformViewAddListener addListener, - PlatformViewRemoveListener removeListener, - void* platform_view_context - ); - - ~FilamentViewPlugin() override; - - static void setupMessageChannels(flutter::PluginRegistrar* registrar); - static void sendReadyEvent(); - - std::optional ChangeMaterialParameter( - const flutter::EncodableMap& params, - const int64_t guid - ) override; - // Change material definition for the given entity. - std::optional ChangeMaterialDefinition( - const flutter::EncodableMap& params, - const int64_t guid - ) override; - // Toggle shapes visibility in the scene. - std::optional ToggleShapesInScene(bool value) override; - // Toggle debug collider visuals in the scene. - std::optional ToggleDebugCollidableViewsInScene(bool value) override; - // Change view quality settings. - std::optional ChangeViewQualitySettings() override; - // Set fog options - std::optional SetFogOptions(const bool enabled) override; - // Set the camera's orbit's anchoring/origin entity - std::optional SetCameraOrbit( - int64_t id, - int64_t origin_entity_id, - const std::vector& orbit_rotation - ) override; - // Set the camera's look-at target entity. - std::optional SetCameraTarget( - int64_t id, - int64_t target_entity_id, - const std::vector* target_position - ) override; - // Set a given camera as the active camera for a view - std::optional SetActiveCamera(const int64_t* view_id, int64_t camera_id) override; - // Set the camera's dolly offset. - // The dolly offset is the camera's position relative to its target. - std::optional SetCameraDolly(int64_t id, const std::vector& dolly_offset) - override; - std::optional ChangeLightTransformByGUID( - const int64_t guid, - double posx, - double posy, - double posz, - double dirx, - double diry, - double dirz - ) override; - std::optional ChangeLightColorByGUID( - const int64_t guid, - const std::vector& color, - double intensity - ) override; - std::optional EnqueueAnimation(const int64_t guid, int64_t animation_index) - override; - std::optional ClearAnimationQueue(const int64_t guid) override; - std::optional PlayAnimation(const int64_t guid, int64_t animation_index) override; - std::optional ChangeAnimationSpeed(const int64_t guid, double speed) override; - std::optional PauseAnimation(const int64_t guid) override; - std::optional ResumeAnimation(const int64_t guid) override; - std::optional SetAnimationLooping(const int64_t guid, bool looping) override; - std::optional RaycastFromTap(double x, double y) override; - std::optional RequestCollisionCheckFromRay( - const std::string& query_id, - double origin_x, - double origin_y, - double origin_z, - double direction_x, - double direction_y, - double direction_z, - double length - ) override; - - std::optional SetEntityTransformScale( - const int64_t guid, - const std::vector& scl - ) override; - std::optional SetEntityTransformPosition( - const int64_t guid, - const std::vector& pos - ) override; - std::optional SetEntityTransformRotation( - const int64_t guid, - const std::vector& rot - ) override; - - std::optional TurnOffVisualForEntity(const int64_t guid) override; - std::optional TurnOnVisualForEntity(const int64_t guid) override; - std::optional TurnOffCollisionChecksForEntity(const int64_t guid) override; - std::optional TurnOnCollisionChecksForEntity(const int64_t guid) override; - - // Disallow copy and assign. - FilamentViewPlugin(const FilamentViewPlugin&) = delete; - - FilamentViewPlugin& operator=(const FilamentViewPlugin&) = delete; - - private: - int32_t id_; - void* platformViewsContext_; - PlatformViewRemoveListener removeListener_; - - static void on_resize(double width, double height, void* data); - static void on_set_direction(int32_t direction, void* data); - static void on_set_offset(double left, double top, void* data); - /// Called by the embedder when touches are passed to PlatformView in Flutter. - static void on_touch( - int32_t action, - int32_t point_count, - size_t point_data_size, - const double* point_data, - void* data - ); - static void on_dispose(bool hybrid, void* data); - - static const struct platform_view_listener platform_view_listener_; -}; - -} // namespace plugin_filament_view - -#endif // FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_H_ diff --git a/plugins/filament_view/filament_view_plugin_c_api.cc b/plugins/filament_view/filament_view_plugin_c_api.cc deleted file mode 100644 index a9f19d79..00000000 --- a/plugins/filament_view/filament_view_plugin_c_api.cc +++ /dev/null @@ -1,91 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ - -#include -#include - -#include -#include - -#include -#include - -#include - -void FilamentViewPluginCApiRegisterWithRegistrar( - FlutterDesktopPluginRegistrarRef registrar, - const int32_t id, - const std::string& viewType, - const int32_t direction, - const double top, - const double left, - const double width, - const double height, - const std::vector& params, - const std::string& assetDirectory, - FlutterDesktopEngineRef engine, - const PlatformViewAddListener addListener, - const PlatformViewRemoveListener removeListener, - void* platform_view_context -) { - plugin_filament_view::FilamentViewPlugin::RegisterWithRegistrar( - flutter::PluginRegistrarManager::GetInstance()->GetRegistrar(registrar - ), - id, viewType, direction, top, left, width, height, params, assetDirectory, engine, addListener, - removeListener, platform_view_context - ); - - // Uncomment if you want two views. - /*plugin_filament_view::FilamentViewPlugin::RegisterWithRegistrar( - flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar), - id, std::move(viewType), direction, top, 1200, width, height, params, - assetDirectory, engine, addListener, removeListener, - platform_view_context); - - plugin_filament_view::FilamentViewPlugin::RegisterWithRegistrar( - flutter::PluginRegistrarManager::GetInstance() - ->GetRegistrar(registrar), - id, std::move(viewType), direction, top, 800, width, height, params, - assetDirectory, engine, addListener, removeListener, - platform_view_context);*/ - - // after we're done doing setup, kick off the run loops - if (const auto ecs = plugin_filament_view::ECSManager::GetInstance(); - ecs->getRunState() == plugin_filament_view::ECSManager::RunState::Initialized) { - ecs->debugPrint(); - // ecs->StartMainLoop(); - - /* - * Indirectly kicks off the rendering loop by processing ViewTarget init requests - * This has to be done on the rendering thread, so we post a task - */ - // TODO: take care of this as part of https://github.com/toyota-connected/fluorite/issues/10 - auto viewTargetSystem = ecs->getSystem( - "FilamentViewPluginCApiRegisterWithRegistrar" - ); - std::promise startupPromise; - auto startupFuture = startupPromise.get_future(); - post(*ecs->getStrand(), [&viewTargetSystem, &startupPromise] { - spdlog::debug("== Starting ViewTargetSystem frame rendering loops =="); - - viewTargetSystem->ProcessMessages(); - startupPromise.set_value(); - }); - - startupFuture.wait(); - } -} diff --git a/plugins/filament_view/include/filament_view/filament_view_plugin_c_api.h b/plugins/filament_view/include/filament_view/filament_view_plugin_c_api.h deleted file mode 100644 index 47fe67b3..00000000 --- a/plugins/filament_view/include/filament_view/filament_view_plugin_c_api.h +++ /dev/null @@ -1,59 +0,0 @@ -/* - * Copyright 2020-2024 Toyota Connected North America - * - * 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. - */ -#pragma once - -#ifndef FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_C_API_H_ -#define FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_C_API_H_ - -#include "platform_view_listener.h" -#include -#include - -#include -#include - -#ifdef FLUTTER_PLUGIN_IMPL -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#else -#define FLUTTER_PLUGIN_EXPORT __attribute__((visibility("default"))) -#endif - -#if defined(__cplusplus) -extern "C" { -#endif - -FLUTTER_PLUGIN_EXPORT void FilamentViewPluginCApiRegisterWithRegistrar( - FlutterDesktopPluginRegistrar* registrar, - int32_t id, - const std::string& viewType, - int32_t direction, - double top, - double left, - double width, - double height, - const std::vector& params, - const std::string& assetDirectory, - FlutterDesktopEngineRef engine, - PlatformViewAddListener addListener, - PlatformViewRemoveListener removeListener, - void* platform_view_context -); - -#if defined(__cplusplus) -} // extern "C" -#endif - -#endif // FLUTTER_PLUGIN_FILAMENT_VIEW_PLUGIN_C_API_H_ diff --git a/plugins/filament_view/messages.g.cc b/plugins/filament_view/messages.g.cc deleted file mode 100644 index 4ccff6bc..00000000 --- a/plugins/filament_view/messages.g.cc +++ /dev/null @@ -1,1246 +0,0 @@ -// /* -// * Copyright 2025 Toyota Connected North America -// * -// * 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. -// */ -// Autogenerated from Pigeon (v22.7.4), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#undef _HAS_EXCEPTIONS - -#include "messages.g.h" - -#include -#include -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { -using flutter::BasicMessageChannel; -using flutter::CustomEncodableValue; -using flutter::EncodableList; -using flutter::EncodableMap; -using flutter::EncodableValue; - -FlutterError CreateConnectionError(const std::string& channel_name) { - return FlutterError( - "channel-error", "Unable to establish connection on channel: '" + channel_name + "'.", - EncodableValue("") - ); -} - -PigeonInternalCodecSerializer::PigeonInternalCodecSerializer() = default; - -EncodableValue PigeonInternalCodecSerializer::ReadValueOfType( - uint8_t type, - flutter::ByteStreamReader* stream -) const { - return flutter::StandardCodecSerializer::ReadValueOfType(type, stream); -} - -void PigeonInternalCodecSerializer::WriteValue( - const EncodableValue& value, - flutter::ByteStreamWriter* stream -) const { - flutter::StandardCodecSerializer::WriteValue(value, stream); -} - -/// The codec used by FilamentViewApi. -const flutter::StandardMessageCodec& FilamentViewApi::GetCodec() { - return flutter::StandardMessageCodec::GetInstance(&PigeonInternalCodecSerializer::GetInstance()); -} - -// Sets up an instance of `FilamentViewApi` to handle messages through the `binary_messenger`. -void FilamentViewApi::SetUp(flutter::BinaryMessenger* binary_messenger, FilamentViewApi* api) { - FilamentViewApi::SetUp(binary_messenger, api, ""); -} - -void FilamentViewApi::SetUp( - flutter::BinaryMessenger* binary_messenger, - FilamentViewApi* api, - const std::string& message_channel_suffix -) { - const std::string prepended_suffix = !message_channel_suffix.empty() - ? std::string(".") + message_channel_suffix - : ""; - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeMaterialParameter" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_params_arg = args.at(0); - if (encodable_params_arg.IsNull()) { - reply(WrapError("params_arg unexpectedly null.")); - return; - } - const auto& params_arg = std::get(encodable_params_arg); - const auto& encodable_id_arg = args.at(1); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->ChangeMaterialParameter(params_arg, id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeMaterialDefinition" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_params_arg = args.at(0); - if (encodable_params_arg.IsNull()) { - reply(WrapError("params_arg unexpectedly null.")); - return; - } - const auto& params_arg = std::get(encodable_params_arg); - const auto& encodable_id_arg = args.at(1); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->ChangeMaterialDefinition(params_arg, id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.toggleShapesInScene" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_value_arg = args.at(0); - if (encodable_value_arg.IsNull()) { - reply(WrapError("value_arg unexpectedly null.")); - return; - } - const auto& value_arg = std::get(encodable_value_arg); - std::optional output = api->ToggleShapesInScene(value_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeViewQualitySettings" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler([api]( - const EncodableValue& /* message */, - const flutter::MessageReply& reply - ) { - try { - std::optional output = api->ChangeViewQualitySettings(); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - }); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setFogOptions" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_enable_arg = args.at(0); - if (encodable_enable_arg.IsNull()) { - reply(WrapError("enable_arg unexpectedly null.")); - return; - } - const auto& enable_arg = std::get(encodable_enable_arg); - std::optional output = api->SetFogOptions(enable_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setCameraOrbit" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_origin_entity_id_arg = args.at(1); - if (encodable_origin_entity_id_arg.IsNull()) { - reply(WrapError("origin_entity_id_arg unexpectedly null.")); - return; - } - const int64_t origin_entity_id_arg = encodable_origin_entity_id_arg.LongValue(); - const auto& encodable_orbit_rotation_arg = args.at(2); - if (encodable_orbit_rotation_arg.IsNull()) { - reply(WrapError("orbit_rotation_arg unexpectedly null.")); - return; - } - const auto& orbit_rotation_arg = std::get>( - encodable_orbit_rotation_arg - ); - std::optional output = api->SetCameraOrbit( - id_arg, origin_entity_id_arg, orbit_rotation_arg - ); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setCameraTarget" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_target_entity_id_arg = args.at(1); - if (encodable_target_entity_id_arg.IsNull()) { - reply(WrapError("target_entity_id_arg unexpectedly null.")); - return; - } - const int64_t target_entity_id_arg = encodable_target_entity_id_arg.LongValue(); - const auto& encodable_target_position_arg = args.at(2); - const auto* target_position_arg = std::get_if>( - &encodable_target_position_arg - ); - std::optional output = api->SetCameraTarget( - id_arg, target_entity_id_arg, target_position_arg - ); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setActiveCamera" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_view_id_arg = args.at(0); - const auto* view_id_arg = std::get_if(&encodable_view_id_arg); - const auto& encodable_camera_id_arg = args.at(1); - if (encodable_camera_id_arg.IsNull()) { - reply(WrapError("camera_id_arg unexpectedly null.")); - return; - } - const int64_t camera_id_arg = encodable_camera_id_arg.LongValue(); - std::optional output = api->SetActiveCamera(view_id_arg, camera_id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setCameraDolly" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_dolly_offset_arg = args.at(1); - if (encodable_dolly_offset_arg.IsNull()) { - reply(WrapError("dolly_offset_arg unexpectedly null.")); - return; - } - const auto& dolly_offset_arg = std::get>(encodable_dolly_offset_arg - ); - std::optional output = api->SetCameraDolly(id_arg, dolly_offset_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeLightColorByGUID" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_color_arg = args.at(1); - if (encodable_color_arg.IsNull()) { - reply(WrapError("color_arg unexpectedly null.")); - return; - } - - const auto& color_arg = std::get>(encodable_color_arg); - const auto& encodable_intensity_arg = args.at(2); - if (encodable_intensity_arg.IsNull()) { - reply(WrapError("intensity_arg unexpectedly null.")); - return; - } - const double intensity_arg = std::get(encodable_intensity_arg); - std::optional output = api->ChangeLightColorByGUID( - id_arg, color_arg, intensity_arg - ); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeLightTransformByGUID" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_posx_arg = args.at(1); - if (encodable_posx_arg.IsNull()) { - reply(WrapError("posx_arg unexpectedly null.")); - return; - } - const auto& posx_arg = std::get(encodable_posx_arg); - const auto& encodable_posy_arg = args.at(2); - if (encodable_posy_arg.IsNull()) { - reply(WrapError("posy_arg unexpectedly null.")); - return; - } - const auto& posy_arg = std::get(encodable_posy_arg); - const auto& encodable_posz_arg = args.at(3); - if (encodable_posz_arg.IsNull()) { - reply(WrapError("posz_arg unexpectedly null.")); - return; - } - const auto& posz_arg = std::get(encodable_posz_arg); - const auto& encodable_dirx_arg = args.at(4); - if (encodable_dirx_arg.IsNull()) { - reply(WrapError("dirx_arg unexpectedly null.")); - return; - } - const auto& dirx_arg = std::get(encodable_dirx_arg); - const auto& encodable_diry_arg = args.at(5); - if (encodable_diry_arg.IsNull()) { - reply(WrapError("diry_arg unexpectedly null.")); - return; - } - const auto& diry_arg = std::get(encodable_diry_arg); - const auto& encodable_dirz_arg = args.at(6); - if (encodable_dirz_arg.IsNull()) { - reply(WrapError("dirz_arg unexpectedly null.")); - return; - } - const auto& dirz_arg = std::get(encodable_dirz_arg); - std::optional output = api->ChangeLightTransformByGUID( - id_arg, posx_arg, posy_arg, posz_arg, dirx_arg, diry_arg, dirz_arg - ); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.enqueueAnimation" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_animation_index_arg = args.at(1); - if (encodable_animation_index_arg.IsNull()) { - reply(WrapError("animation_index_arg unexpectedly null.")); - return; - } - const int64_t animation_index_arg = encodable_animation_index_arg.LongValue(); - std::optional output = api->EnqueueAnimation(id_arg, animation_index_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.clearAnimationQueue" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->ClearAnimationQueue(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.playAnimation" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_animation_index_arg = args.at(1); - if (encodable_animation_index_arg.IsNull()) { - reply(WrapError("animation_index_arg unexpectedly null.")); - return; - } - const int64_t animation_index_arg = encodable_animation_index_arg.LongValue(); - std::optional output = api->PlayAnimation(id_arg, animation_index_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.changeAnimationSpeed" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_speed_arg = args.at(1); - if (encodable_speed_arg.IsNull()) { - reply(WrapError("speed_arg unexpectedly null.")); - return; - } - const auto& speed_arg = std::get(encodable_speed_arg); - std::optional output = api->ChangeAnimationSpeed(id_arg, speed_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.pauseAnimation" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->PauseAnimation(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.resumeAnimation" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->ResumeAnimation(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setAnimationLooping" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_looping_arg = args.at(1); - if (encodable_looping_arg.IsNull()) { - reply(WrapError("looping_arg unexpectedly null.")); - return; - } - const auto& looping_arg = std::get(encodable_looping_arg); - std::optional output = api->SetAnimationLooping(id_arg, looping_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.raycastFromTap" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_x_arg = args.at(0); - if (encodable_x_arg.IsNull()) { - reply(WrapError("x_arg unexpectedly null.")); - return; - } - const auto& x_arg = std::get(encodable_x_arg); - const auto& encodable_y_arg = args.at(1); - if (encodable_y_arg.IsNull()) { - reply(WrapError("y_arg unexpectedly null.")); - return; - } - const auto& y_arg = std::get(encodable_y_arg); - std::optional output = api->RaycastFromTap(x_arg, y_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.requestCollisionCheckFromRay" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_query_i_d_arg = args.at(0); - if (encodable_query_i_d_arg.IsNull()) { - reply(WrapError("query_i_d_arg unexpectedly null.")); - return; - } - const auto& query_i_d_arg = std::get(encodable_query_i_d_arg); - const auto& encodable_origin_x_arg = args.at(1); - if (encodable_origin_x_arg.IsNull()) { - reply(WrapError("origin_x_arg unexpectedly null.")); - return; - } - const auto& origin_x_arg = std::get(encodable_origin_x_arg); - const auto& encodable_origin_y_arg = args.at(2); - if (encodable_origin_y_arg.IsNull()) { - reply(WrapError("origin_y_arg unexpectedly null.")); - return; - } - const auto& origin_y_arg = std::get(encodable_origin_y_arg); - const auto& encodable_origin_z_arg = args.at(3); - if (encodable_origin_z_arg.IsNull()) { - reply(WrapError("origin_z_arg unexpectedly null.")); - return; - } - const auto& origin_z_arg = std::get(encodable_origin_z_arg); - const auto& encodable_direction_x_arg = args.at(4); - if (encodable_direction_x_arg.IsNull()) { - reply(WrapError("direction_x_arg unexpectedly null.")); - return; - } - const auto& direction_x_arg = std::get(encodable_direction_x_arg); - const auto& encodable_direction_y_arg = args.at(5); - if (encodable_direction_y_arg.IsNull()) { - reply(WrapError("direction_y_arg unexpectedly null.")); - return; - } - const auto& direction_y_arg = std::get(encodable_direction_y_arg); - const auto& encodable_direction_z_arg = args.at(6); - if (encodable_direction_z_arg.IsNull()) { - reply(WrapError("direction_z_arg unexpectedly null.")); - return; - } - const auto& direction_z_arg = std::get(encodable_direction_z_arg); - const auto& encodable_length_arg = args.at(7); - if (encodable_length_arg.IsNull()) { - reply(WrapError("length_arg unexpectedly null.")); - return; - } - const auto& length_arg = std::get(encodable_length_arg); - std::optional output = api->RequestCollisionCheckFromRay( - query_i_d_arg, origin_x_arg, origin_y_arg, origin_z_arg, direction_x_arg, - direction_y_arg, direction_z_arg, length_arg - ); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.turnOffCollisionChecksForEntity" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->TurnOffCollisionChecksForEntity(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.turnOnCollisionChecksForEntity" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->TurnOnCollisionChecksForEntity(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.toggleDebugCollidableViewsInScene" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_value_arg = args.at(0); - if (encodable_value_arg.IsNull()) { - reply(WrapError("value_arg unexpectedly null.")); - return; - } - const auto& value_arg = std::get(encodable_value_arg); - std::optional output = api->ToggleDebugCollidableViewsInScene(value_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setEntityTransformScale" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_scl_arg = args.at(1); - if (encodable_scl_arg.IsNull()) { - reply(WrapError("scl_arg unexpectedly null.")); - return; - } - const auto& scl_arg = std::get>(encodable_scl_arg); - std::optional output = api->SetEntityTransformScale(id_arg, scl_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setEntityTransformPosition" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_pos_arg = args.at(1); - if (encodable_pos_arg.IsNull()) { - reply(WrapError("pos_arg unexpectedly null.")); - return; - } - const auto& pos_arg = std::get>(encodable_pos_arg); - std::optional output = api->SetEntityTransformPosition(id_arg, pos_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.setEntityTransformRotation" - + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - const auto& encodable_rot_arg = args.at(1); - if (encodable_rot_arg.IsNull()) { - reply(WrapError("rot_arg unexpectedly null.")); - return; - } - const auto& rot_arg = std::get>(encodable_rot_arg); - std::optional output = api->SetEntityTransformRotation(id_arg, rot_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.turnOffVisualForEntity" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->TurnOffVisualForEntity(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } - { - BasicMessageChannel<> channel( - binary_messenger, - "dev.flutter.pigeon.filament_scene.FilamentViewApi.turnOnVisualForEntity" + prepended_suffix, - &GetCodec() - ); - if (api != nullptr) { - channel.SetMessageHandler( - [api](const EncodableValue& message, const flutter::MessageReply& reply) { - try { - const auto& args = std::get(message); - const auto& encodable_id_arg = args.at(0); - if (encodable_id_arg.IsNull()) { - reply(WrapError("id_arg unexpectedly null.")); - return; - } - const int64_t id_arg = encodable_id_arg.LongValue(); - std::optional output = api->TurnOnVisualForEntity(id_arg); - if (output.has_value()) { - reply(WrapError(output.value())); - return; - } - EncodableList wrapped; - wrapped.emplace_back(); - reply(EncodableValue(std::move(wrapped))); - } catch (const std::exception& exception) { - reply(WrapError(exception.what())); - } - } - ); - } else { - channel.SetMessageHandler(nullptr); - } - } -} - -EncodableValue FilamentViewApi::WrapError(std::string_view error_message) { - return EncodableValue(EncodableList{ - EncodableValue(std::string(error_message)), EncodableValue("Error"), EncodableValue() - }); -} - -EncodableValue FilamentViewApi::WrapError(const FlutterError& error) { - return EncodableValue( - EncodableList{EncodableValue(error.code()), EncodableValue(error.message()), error.details()} - ); -} - -} // namespace plugin_filament_view diff --git a/plugins/filament_view/messages.g.h b/plugins/filament_view/messages.g.h deleted file mode 100644 index 5086584b..00000000 --- a/plugins/filament_view/messages.g.h +++ /dev/null @@ -1,220 +0,0 @@ -// /* -// * Copyright 2025 Toyota Connected North America -// * -// * 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. -// */ -// Autogenerated from Pigeon (v22.7.4), do not edit directly. -// See also: https://pub.dev/packages/pigeon - -#ifndef PIGEON_MESSAGES_G_H_ -#define PIGEON_MESSAGES_G_H_ -#include -#include -#include -#include - -#include -#include -#include - -namespace plugin_filament_view { - -// Generated class from Pigeon. - -class FlutterError { - public: - explicit FlutterError(const std::string& code) - : code_(code) {} - explicit FlutterError(const std::string& code, const std::string& message) - : code_(code), - message_(message) {} - explicit FlutterError( - const std::string& code, - const std::string& message, - const flutter::EncodableValue& details - ) - : code_(code), - message_(message), - details_(details) {} - - const std::string& code() const { return code_; } - const std::string& message() const { return message_; } - const flutter::EncodableValue& details() const { return details_; } - - private: - std::string code_; - std::string message_; - flutter::EncodableValue details_; -}; - -template class ErrorOr { - public: - ErrorOr(const T& rhs) - : v_(rhs) {} - ErrorOr(const T&& rhs) - : v_(std::move(rhs)) {} - ErrorOr(const FlutterError& rhs) - : v_(rhs) {} - ErrorOr(const FlutterError&& rhs) - : v_(std::move(rhs)) {} - - bool has_error() const { return std::holds_alternative(v_); } - const T& value() const { return std::get(v_); }; - const FlutterError& error() const { return std::get(v_); }; - - private: - friend class FilamentViewApi; - ErrorOr() = default; - T TakeValue() && { return std::get(std::move(v_)); } - - std::variant v_; -}; - -class PigeonInternalCodecSerializer : public flutter::StandardCodecSerializer { - public: - PigeonInternalCodecSerializer(); - inline static PigeonInternalCodecSerializer& GetInstance() { - static PigeonInternalCodecSerializer sInstance; - return sInstance; - } - - void WriteValue(const flutter::EncodableValue& value, flutter::ByteStreamWriter* stream) - const override; - - protected: - flutter::EncodableValue ReadValueOfType(uint8_t type, flutter::ByteStreamReader* stream) - const override; -}; - -// Generated interface from Pigeon that represents a handler of messages from Flutter. -class FilamentViewApi { - public: - FilamentViewApi(const FilamentViewApi&) = delete; - FilamentViewApi& operator=(const FilamentViewApi&) = delete; - virtual ~FilamentViewApi() {} - // Change material parameters for the given entity. - virtual std::optional ChangeMaterialParameter( - const flutter::EncodableMap& params, - int64_t id - ) = 0; - // Change material definition for the given entity. - virtual std::optional ChangeMaterialDefinition( - const flutter::EncodableMap& params, - int64_t id - ) = 0; - // Toggle shapes visibility in the scene. - virtual std::optional ToggleShapesInScene(bool value) = 0; - // Cycle between view quality settings presets. - virtual std::optional ChangeViewQualitySettings() = 0; - // Set fog options - virtual std::optional SetFogOptions(bool enable) = 0; - // Set the camera orbit's anchoring/origin entity - virtual std::optional SetCameraOrbit( - int64_t id, - int64_t origin_entity_id, - const std::vector& orbit_rotation - ) = 0; - // Set the camera's look-at target entity. - virtual std::optional SetCameraTarget( - int64_t id, - int64_t target_entity_id, - const std::vector* target_position - ) = 0; - // Set a given camera as the active camera for a view - virtual std::optional SetActiveCamera( - const int64_t* view_id, - int64_t camera_id - ) = 0; - // Set the camera's dolly offset. - // The dolly offset is the camera's position relative to its target. - virtual std::optional SetCameraDolly( - int64_t id, - const std::vector& dolly_offset - ) = 0; - // TODO(kerberjg): add setCameraIpd to support stereoscopic/VR cameras - // Set a light's color and intensity by GUID. - virtual std::optional ChangeLightColorByGUID( - int64_t id, - const std::vector& color, - double intensity - ) = 0; - // Set a light's transform by GUID. Deprecated. - virtual std::optional ChangeLightTransformByGUID( - int64_t id, - double posx, - double posy, - double posz, - double dirx, - double diry, - double dirz - ) = 0; - virtual std::optional EnqueueAnimation(int64_t id, int64_t animation_index) = 0; - virtual std::optional ClearAnimationQueue(int64_t id) = 0; - virtual std::optional PlayAnimation(int64_t id, int64_t animation_index) = 0; - virtual std::optional ChangeAnimationSpeed(int64_t id, double speed) = 0; - virtual std::optional PauseAnimation(int64_t id) = 0; - virtual std::optional ResumeAnimation(int64_t id) = 0; - virtual std::optional SetAnimationLooping(int64_t id, bool looping) = 0; - virtual std::optional RaycastFromTap(double x, double y) = 0; - // Perform a raycast query. - // The result will be sent back to the client via the collision_info event channel. - virtual std::optional RequestCollisionCheckFromRay( - const std::string& query_i_d, - double origin_x, - double origin_y, - double origin_z, - double direction_x, - double direction_y, - double direction_z, - double length - ) = 0; - // Disable raycast checks for the given entity. - // NOTE: this will not hide the collider debug visual. - virtual std::optional TurnOffCollisionChecksForEntity(int64_t id) = 0; - // Enable raycast checks for the given entity. - // NOTE: this will not show the collider debug visual. - virtual std::optional TurnOnCollisionChecksForEntity(int64_t id) = 0; - // Enable/disable debug collider visuals in the scene. - virtual std::optional ToggleDebugCollidableViewsInScene(bool value) = 0; - virtual std::optional SetEntityTransformScale( - int64_t id, - const std::vector& scl - ) = 0; - virtual std::optional SetEntityTransformPosition( - int64_t id, - const std::vector& pos - ) = 0; - virtual std::optional SetEntityTransformRotation( - int64_t id, - const std::vector& rot - ) = 0; - virtual std::optional TurnOffVisualForEntity(int64_t id) = 0; - virtual std::optional TurnOnVisualForEntity(int64_t id) = 0; - - // The codec used by FilamentViewApi. - static const flutter::StandardMessageCodec& GetCodec(); - // Sets up an instance of `FilamentViewApi` to handle messages through the `binary_messenger`. - static void SetUp(flutter::BinaryMessenger* binary_messenger, FilamentViewApi* api); - static void SetUp( - flutter::BinaryMessenger* binary_messenger, - FilamentViewApi* api, - const std::string& message_channel_suffix - ); - static flutter::EncodableValue WrapError(std::string_view error_message); - static flutter::EncodableValue WrapError(const FlutterError& error); - - protected: - FilamentViewApi() = default; -}; -} // namespace plugin_filament_view -#endif // PIGEON_MESSAGES_G_H_ diff --git a/plugins/filament_view/test/mvp.cc b/plugins/filament_view/test/mvp.cc deleted file mode 100644 index d96c8002..00000000 --- a/plugins/filament_view/test/mvp.cc +++ /dev/null @@ -1,393 +0,0 @@ -#include -#include - -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include -#include - -#include - -#include - -#include -#include - -#include -#include -#include - -using CameraManipulator = ::filament::camutils::Manipulator; - -/// passed into Filament backend. Requires static -static struct { - struct wl_display* display; - struct wl_surface* surface; - uint32_t width; - uint32_t height; -} native_window; - -volatile uint32_t gWidth, gHeight; - -/** - * @brief Callback function for handling resize events. - * - * This function is called when an SDL_WINDOWEVENT_RESIZED event is triggered - * for the specified window. It retrieves the new window size and updates - * the global variables gWidth and gHeight accordingly. - * - * @param data A pointer to user-defined data (in this case, the SDL_Window*). - * @param event A pointer to the SDL_Event structure containing the event data. - * @return Returns 0 on success, or a negative value on failure. - */ -static int OnResize(void* data, SDL_Event* event) { - if (event->type == SDL_WINDOWEVENT && event->window.event == SDL_WINDOWEVENT_RESIZED) { - SDL_Window* win = SDL_GetWindowFromID(event->window.windowID); - if (win == (SDL_Window*)data) { - SDL_GetWindowSize(win, (int*)&gWidth, (int*)&gHeight); - } - } - return 0; -} - -/** - * @brief Retrieve the native window handle associated with an SDL window. - * - * This function returns the native window handle for a given SDL window. - * The native window handle is specific to the underlying windowing subsystem. - * - * @param sdlWindow A pointer to the SDL window for which to retrieve the native - * window handle. - * @return A void pointer to the native window handle. The type of the pointer - * depends on the underlying windowing subsystem. If the native window handle - * cannot be determined, nullptr is returned. - */ -void* getNativeWindow(SDL_Window* sdlWindow) { - SDL_SysWMinfo wmi; - SDL_VERSION(&wmi.version); - SDL_GetWindowWMInfo(sdlWindow, &wmi); - if (wmi.subsystem == SDL_SYSWM_X11) { - auto win = (Window)wmi.info.x11.window; - return (void*)win; - } else if (wmi.subsystem == SDL_SYSWM_WAYLAND) { - // The default Wayland swap chain extent is {0,0} - // hence having to set the size - SDL_GetWindowSize(sdlWindow, (int*)&gWidth, (int*)&gHeight); - native_window = {wmi.info.wl.display, wmi.info.wl.surface, gWidth, gHeight}; - return (void*)&native_window; - } else { - std::cout << "Unknown SDL subsystem"; - return nullptr; - } -} - -/** - * @brief Creates an SDL window with specified properties. - * - * @return SDL_Window* The created window. Returns nullptr in case of failure. - */ -SDL_Window* createWindow() { - const uint32_t windowFlags = SDL_WINDOW_VULKAN | SDL_WINDOW_SHOWN | SDL_WINDOW_RESIZABLE - | SDL_WINDOW_ALLOW_HIGHDPI; - SDL_Window* win = SDL_CreateWindow("Hello Filament!", 0, 0, 800, 600, windowFlags); - if (win == nullptr) { - std::cout << "SDL_CreateWindow Error: " << SDL_GetError() << std::endl; - SDL_Quit(); - return nullptr; - } - SDL_AddEventWatch(OnResize, win); - - return win; -} - -struct { - filament::Engine* engine{}; - filament::SwapChain* swapChain{}; - filament::Renderer* renderer{}; - filament::Scene* scene{}; - filament::View* view{}; - filament::Skybox* skybox{}; - - filament::Camera* camera{}; - CameraManipulator* cameraManipulator{}; - - utils::Entity cameraEntity; - utils::Entity light; - - struct { - utils::Entity renderable; - filament::IndexBuffer* indexBuffer{}; - filament::VertexBuffer* vertexBuffer{}; - filament::MaterialInstance* materialInstance{}; - filament::Material* material{}; - } quad; -} gContext; - -/** - * Adds a quad to the scene. - * This function creates a quad mesh, assigns vertex and index buffers, - * creates a material, sets default material parameters, and adds the - * quad to the scene. - */ -void addQuadToScene() { - using namespace filament; - using namespace math; - - static constexpr uint32_t indices[] = {0, 1, 2, 2, 3, 0}; - - static constexpr math::float3 vertices[] = { - {-10, 0, -10}, - {-10, 0, 10}, - {10, 0, 10}, - {10, 0, -10}, - }; - - short4 tbn = math::packSnorm16( - mat3f::packTangentFrame( - math::mat3f{float3{1.0f, 0.0f, 0.0f}, float3{0.0f, 0.0f, 1.0f}, float3{0.0f, 1.0f, 0.0f}} - ).xyzw - ); - - const static math::short4 normals[]{tbn, tbn, tbn, tbn}; - - auto vertexBuffer = gContext.quad.vertexBuffer = - VertexBuffer::Builder() - .vertexCount(4) - .bufferCount(2) - .attribute(VertexAttribute::POSITION, 0, VertexBuffer::AttributeType::FLOAT3) - .attribute(VertexAttribute::TANGENTS, 1, VertexBuffer::AttributeType::SHORT4) - .normalized(VertexAttribute::TANGENTS) - .build(*gContext.engine); - - vertexBuffer->setBufferAt( - *gContext.engine, 0, - VertexBuffer::BufferDescriptor(vertices, vertexBuffer->getVertexCount() * sizeof(vertices[0])) - ); - vertexBuffer->setBufferAt( - *gContext.engine, 1, - VertexBuffer::BufferDescriptor(normals, vertexBuffer->getVertexCount() * sizeof(normals[0])) - ); - - auto indexBuffer = gContext.quad.indexBuffer = IndexBuffer::Builder().indexCount(6).build( - *gContext.engine - ); - - indexBuffer->setBuffer( - *gContext.engine, - IndexBuffer::BufferDescriptor(indices, indexBuffer->getIndexCount() * sizeof(uint32_t)) - ); - - filamat::MaterialBuilder::init(); - filamat::MaterialBuilder builder; - builder.name("Some material") - .material(" void material(inout MaterialInputs material) {\n" - " prepareMaterial(material);\n" - " material.baseColor.rgb = materialParams.baseColor;\n" - " material.metallic = materialParams.metallic;\n" - " material.roughness = materialParams.roughness;\n" - " material.reflectance = materialParams.reflectance;\n" - " }") - .parameter("baseColor", filament::backend::UniformType::FLOAT3) - .parameter("metallic", filament::backend::UniformType::FLOAT) - .parameter("roughness", filament::backend::UniformType::FLOAT) - .parameter("reflectance", filament::backend::UniformType::FLOAT) - .shading(filamat::MaterialBuilder::Shading::LIT) - .targetApi(filamat::MaterialBuilder::TargetApi::ALL) - .platform(filamat::MaterialBuilder::Platform::ALL); - - filamat::Package package = builder.build(gContext.engine->getJobSystem()); - - gContext.quad.material = - Material::Builder().package(package.getData(), package.getSize()).build(*gContext.engine); - gContext.quad.material->setDefaultParameter("baseColor", RgbType::LINEAR, float3{0, 1, 0}); - gContext.quad.material->setDefaultParameter("metallic", 0.0f); - gContext.quad.material->setDefaultParameter("roughness", 0.4f); - gContext.quad.material->setDefaultParameter("reflectance", 0.5f); - - gContext.quad.materialInstance = gContext.quad.material->createInstance(); - - gContext.quad.renderable = utils::EntityManager::get().create(); - RenderableManager::Builder(1) - .boundingBox({{-1, -1, -1}, {1, 1, 1}}) - .material(0, gContext.quad.materialInstance) - .geometry(0, RenderableManager::PrimitiveType::TRIANGLES, vertexBuffer, indexBuffer, 0, 6) - .culling(false) - .build(*gContext.engine, gContext.quad.renderable); - gContext.scene->addEntity(gContext.quad.renderable); -} - -/** - * @brief Set the default camera for the scene. - * - * This function creates and configures a default camera for the scene. It sets - * the camera's exposure parameters, creates a camera manipulator, and sets the - * camera's viewport, look-at position, projection, and assigns it to the view. - */ -void setDefaultCamera() { - using namespace filament; - using namespace math; - - static constexpr float kAperture = 16.0f; - static constexpr float kShutterSpeed = 1.0f / 125; - static constexpr float kSensitivity = 100.0f; - - auto viewport = gContext.view->getViewport(); - - /// Create camera - gContext.cameraEntity = utils::EntityManager::get().create(); - gContext.camera = gContext.engine->createCamera(gContext.cameraEntity); - - /// With the default parameters, the scene must contain at least one Light of - /// intensity similar to the sun (e.g.: a 100,000 lux directional light). - gContext.camera->setExposure(kAperture, kShutterSpeed, kSensitivity); - - /// Create camera manipulator - gContext.cameraManipulator = - CameraManipulator::Builder() - .viewport(static_cast(viewport.width), static_cast(viewport.height)) - .orbitHomePosition(0, 50.5f, 0) // eye - .targetPosition(0, 0, 0) // center - .upVector(1.f, 0, 0) // up - .zoomSpeed(0.05f) - .orbitSpeed(0.075f, 0.075f) - .viewport(static_cast(viewport.width), static_cast(viewport.height)) - .build(::filament::camutils::Mode::ORBIT); - - filament::math::float3 eye, center, up; - gContext.cameraManipulator->getLookAt(&eye, ¢er, &up); - gContext.camera->lookAt(eye, center, up); - gContext.camera->setProjection( - 60, static_cast(viewport.width) / static_cast(viewport.height), 0.1, 10 - ); - - gContext.view->setCamera(gContext.camera); -} - -/** - * @brief Initializes the SDL video subsystem and creates a window. - * - * It creates a SDL window using SDL_CreateWindow function and sets the window - * flags. The window is resizable and supports Vulkan rendering. - * - * @return A pointer to the created SDL window, or nullptr on error. - */ -int main() { - SDL_Init(SDL_INIT_VIDEO); - - using namespace filament; - using namespace math; - using namespace utils; - - SDL_Window* window = createWindow(); - - /// Core - gContext.engine = Engine::create(filament::backend::Backend::VULKAN); - gContext.swapChain = gContext.engine->createSwapChain(getNativeWindow(window)); - gContext.renderer = gContext.engine->createRenderer(); - - /// Scene - gContext.scene = gContext.engine->createScene(); - - /// View - gContext.view = gContext.engine->createView(); - gContext.view->setViewport({0, 0, gWidth, gHeight}); - gContext.view->setScene(gContext.scene); - - /// Camera - requires valid view - setDefaultCamera(); - - /// Skybox - gContext.skybox = Skybox::Builder().color({0.5, 0.5, 0.5, 1.0}).build(*gContext.engine); - gContext.scene->setSkybox(gContext.skybox); - - /// Direct Lighting - gContext.light = EntityManager::get().create(); - LightManager::Builder(LightManager::Type::SUN) - .color(Color::toLinear(sRGBColor(0.98f, 0.92f, 0.89f))) - .intensity(110000) - .direction({0.7, -1, -0.8}) - .sunAngularRadius(1.9f) - .castShadows(true) - .build(*gContext.engine, gContext.light); - - gContext.scene->addEntity(gContext.light); - - /// Build a quad - addQuadToScene(); - - /// Display loop - volatile uint32_t prev_width = gWidth; - volatile uint32_t prev_height = gHeight; - bool keep_window_open = true; - while (keep_window_open) { - SDL_Event e; - while (SDL_PollEvent(&e) > 0) { - switch (e.type) { - case SDL_QUIT: - keep_window_open = false; - break; - case SDL_MOUSEBUTTONDOWN: - gContext.cameraManipulator->grabBegin(e.button.x, e.button.y, false); - break; - case SDL_MOUSEMOTION: - gContext.cameraManipulator->grabUpdate(e.motion.x, e.motion.y); - break; - case SDL_MOUSEBUTTONUP: - gContext.cameraManipulator->grabEnd(); - break; - } - - if (prev_width != gWidth || prev_height != gHeight) { - prev_width = gWidth; - prev_height = gHeight; - gContext.engine->flushAndWait(); - gContext.engine->destroy(gContext.swapChain); - gContext.swapChain = gContext.engine->createSwapChain(getNativeWindow(window)); - gContext.view->setViewport({0, 0, gWidth, gHeight}); - gContext.cameraManipulator->setViewport((int)gWidth, (int)gHeight); - gContext.camera->setProjection( - 60, static_cast(gWidth) / static_cast(gHeight), 0.1, 10 - ); - } - - float3 eye, center, up; - gContext.cameraManipulator->getLookAt(&eye, ¢er, &up); - gContext.camera->lookAt(eye, center, up); - - // beginFrame() returns false if we need to skip a frame - if (gContext.renderer->beginFrame(gContext.swapChain)) { - // for each View - gContext.renderer->render(gContext.view); - gContext.renderer->endFrame(); - } - SDL_UpdateWindowSurface(window); - SDL_Delay(16); - } - } - - gContext.engine->destroy(gContext.scene); - gContext.engine->destroy(gContext.view); - gContext.engine->destroyCameraComponent(gContext.cameraEntity); - delete gContext.cameraManipulator; - gContext.engine->destroy(gContext.light); - gContext.engine->destroy(gContext.skybox); - gContext.engine->destroy(gContext.quad.renderable); - gContext.engine->destroy(gContext.quad.indexBuffer); - gContext.engine->destroy(gContext.quad.vertexBuffer); - gContext.engine->destroy(gContext.quad.materialInstance); - gContext.engine->destroy(gContext.quad.material); - gContext.engine->destroy(gContext.renderer); - gContext.engine->destroy(gContext.swapChain); - Engine::destroy(gContext.engine); - - SDL_Quit(); - return 0; -} diff --git a/plugins/generated_plugin_registrant.cc b/plugins/generated_plugin_registrant.cc index b30dad44..72c9968b 100644 --- a/plugins/generated_plugin_registrant.cc +++ b/plugins/generated_plugin_registrant.cc @@ -176,15 +176,6 @@ void PluginsAoiPlatformViewCreate( result->Success(flutter::EncodableValue(id)); } else #endif -#if ENABLE_PLUGIN_FILAMENT_VIEW - if (viewType == "com.toyotaconnected.filament_view.channel_3d_scene") { - FilamentViewPluginCApiRegisterWithRegistrar( - registrar, id, viewType, direction, top, left, width, height, params, - flutter_asset_directory, engine, addListener, removeListener, - platform_view_context); - result->Success(flutter::EncodableValue(id)); - } else -#endif #if ENABLE_PLUGIN_LAYER_PLAYGROUND_VIEW if (viewType == "@views/simple-box-view-type") { LayerPlaygroundPluginCApiRegisterWithRegistrar(