SurfaceDataUtility.cpp 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  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 <SurfaceDataProfiler.h>
  9. #include <SurfaceData/Utility/SurfaceDataUtility.h>
  10. #include <Atom/RPI.Reflect/Model/ModelAssetCreator.h>
  11. namespace SurfaceData
  12. {
  13. bool GetMeshRayIntersection(
  14. const AZ::RPI::ModelAsset& meshAsset, const AZ::Transform& meshTransform,
  15. const AZ::Transform& meshTransformInverse, const AZ::Vector3& nonUniformScale,
  16. const AZ::Vector3& rayStart, const AZ::Vector3& rayEnd,
  17. AZ::Vector3& outPosition, AZ::Vector3& outNormal)
  18. {
  19. SURFACE_DATA_PROFILE_FUNCTION_VERBOSE
  20. const AZ::Vector3 clampedScale = nonUniformScale.GetMax(AZ::Vector3(AZ::MinTransformScale));
  21. // Transform everything into model space
  22. const AZ::Vector3 rayStartLocal = meshTransformInverse.TransformPoint(rayStart) / clampedScale;
  23. const AZ::Vector3 rayEndLocal = meshTransformInverse.TransformPoint(rayEnd) / clampedScale;
  24. // LocalRayIntersectionAgainstModel expects the direction to contain both the direction and the distance of the raycast,
  25. // so it's important not to normalize this value.
  26. const AZ::Vector3 rayDirectionLocal = (rayEndLocal - rayStartLocal);
  27. float normalizedDistance = 0.0f;
  28. AZ::Vector3 normalLocal;
  29. constexpr bool AllowBruteForce = true;
  30. if (meshAsset.LocalRayIntersectionAgainstModel(rayStartLocal, rayDirectionLocal, AllowBruteForce, normalizedDistance, normalLocal))
  31. {
  32. // Transform everything back to world space
  33. // The distance that's returned is normalized from 0-1, so multiplying with the rayDirectionLocal gives the
  34. // actual collision point.
  35. outPosition = meshTransform.TransformPoint((rayStartLocal + (rayDirectionLocal * normalizedDistance)) * clampedScale);
  36. outNormal = meshTransform.TransformVector(normalLocal).GetNormalized();
  37. return true;
  38. }
  39. return false;
  40. }
  41. }