OpenXRVkCommon_Android.cpp 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. /*
  2. * Copyright (c) Contributors to the Open 3D Engine Project.
  3. * For complete copyright and license terms please see the LICENSE at the root of this distribution.
  4. *
  5. * SPDX-License-Identifier: Apache-2.0 OR MIT
  6. *
  7. */
  8. #include <OpenXRVkCommon.h>
  9. #include <AzCore/Android/AndroidEnv.h>
  10. #include <OpenXRVk/OpenXRVkUtils.h>
  11. namespace OpenXRVk::Platform
  12. {
  13. bool OpenXRInitializeLoader()
  14. {
  15. PFN_xrInitializeLoaderKHR initializeLoader = nullptr;
  16. XrResult result = xrGetInstanceProcAddr(
  17. XR_NULL_HANDLE, "xrInitializeLoaderKHR",
  18. reinterpret_cast<PFN_xrVoidFunction*>(&initializeLoader));
  19. if (IsError(result))
  20. {
  21. return false;
  22. }
  23. AZ::Android::AndroidEnv* androidEnv = AZ::Android::AndroidEnv::Get();
  24. AZ_Assert(androidEnv != nullptr, "Invalid android environment");
  25. JavaVM* javaVM = nullptr;
  26. androidEnv->GetJniEnv()->GetJavaVM(&javaVM);
  27. AZ_Assert(javaVM != nullptr, "Invalid Java VM");
  28. jobject javaActivity = androidEnv->GetActivityRef();
  29. XrLoaderInitInfoAndroidKHR loaderInitInfoAndroid;
  30. memset(&loaderInitInfoAndroid, 0, sizeof(loaderInitInfoAndroid));
  31. loaderInitInfoAndroid.type = XR_TYPE_LOADER_INIT_INFO_ANDROID_KHR;
  32. loaderInitInfoAndroid.next = nullptr;
  33. loaderInitInfoAndroid.applicationVM = javaVM;
  34. loaderInitInfoAndroid.applicationContext = javaActivity;
  35. result = initializeLoader(reinterpret_cast<const XrLoaderInitInfoBaseHeaderKHR*>(&loaderInitInfoAndroid));
  36. if (IsError(result))
  37. {
  38. return false;
  39. }
  40. return true;
  41. }
  42. void OpenXRBeginFrameInternal()
  43. {
  44. }
  45. void OpenXREndFrameInternal()
  46. {
  47. // OpenXR's xrEndFrame function internally uses the application's Java VM (passed in OpenXRInitializeLoader).
  48. // xrEndFrame function is called from the thread related to the presentation queue (not the main thread) and
  49. // that causes to create a temporary JNI Environment for this thread, which is not optimal.
  50. // Calling GetJniEnv() will attach the JNI Environment to this thread.
  51. AZ::Android::AndroidEnv* androidEnv = AZ::Android::AndroidEnv::Get();
  52. AZ_Assert(androidEnv != nullptr, "Invalid android environment");
  53. androidEnv->GetJniEnv();
  54. }
  55. void OpenXRPostFrameInternal()
  56. {
  57. // Now that EndFrame has finished, calling GetJniEnv() again from the main thread
  58. // to attach the JNI Environment back to the main thread.
  59. AZ::Android::AndroidEnv* androidEnv = AZ::Android::AndroidEnv::Get();
  60. AZ_Assert(androidEnv != nullptr, "Invalid android environment");
  61. androidEnv->GetJniEnv();
  62. }
  63. }