HeightFieldShapeTest.cpp 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185
  1. // SPDX-FileCopyrightText: 2021 Jorrit Rouwe
  2. // SPDX-License-Identifier: MIT
  3. #include <TestFramework.h>
  4. #include <Tests/Shapes/HeightFieldShapeTest.h>
  5. #include <Math/Perlin.h>
  6. #include <Physics/Collision/Shape/BoxShape.h>
  7. #include <Physics/Body/BodyCreationSettings.h>
  8. #include <Physics/Collision/PhysicsMaterialSimple.h>
  9. #include <Physics/Collision/CastResult.h>
  10. #include <Physics/Collision/RayCast.h>
  11. #include <Renderer/DebugRendererImp.h>
  12. #include <Application/DebugUI.h>
  13. #include <Utils/ReadData.h>
  14. #include <Utils/Log.h>
  15. #include <Layers.h>
  16. JPH_IMPLEMENT_RTTI_VIRTUAL(HeightFieldShapeTest)
  17. {
  18. JPH_ADD_BASE_CLASS(HeightFieldShapeTest, Test)
  19. }
  20. static int sTerrainType = 0;
  21. static const char *sTerrainTypes[] = {
  22. "Procedural Terrain",
  23. "Heightfield 1"
  24. };
  25. static void sValidateHeightField(const float *inUncompressedHeights, uint inSize, const HeightFieldShape *inShape)
  26. {
  27. float max_diff = -1.0f;
  28. uint max_diff_x = 0, max_diff_y = 0;
  29. float min_height = FLT_MAX, max_height = -FLT_MAX;
  30. for (uint y = 0; y < inSize; ++y)
  31. for (uint x = 0; x < inSize; ++x)
  32. {
  33. float h1 = inUncompressedHeights[y * inSize + x];
  34. if (h1 != HeightFieldShapeConstants::cNoCollisionValue)
  35. {
  36. if (inShape->IsNoCollision(x, y))
  37. FatalError("No collision where there should be");
  38. float h2 = inShape->GetPosition(x, y).GetY();
  39. float diff = abs(h2 - h1);
  40. if (diff > max_diff)
  41. {
  42. max_diff = diff;
  43. max_diff_x = x;
  44. max_diff_y = y;
  45. }
  46. min_height = min(min_height, h1);
  47. max_height = max(max_height, h1);
  48. }
  49. else
  50. {
  51. if (!inShape->IsNoCollision(x, y))
  52. FatalError("Collision where there shouldn't be");
  53. }
  54. }
  55. // Calculate relative error compared to 8-bit compression (error should be below 1)
  56. float rel_error = 255.0f * max_diff / (max_height - min_height);
  57. Trace("Min height: %g, max height: %g", (double)min_height, (double)max_height);
  58. Trace("Max diff: %g at (%d, %d), relative error: %g", (double)max_diff, max_diff_x, max_diff_y, (double)rel_error);
  59. if (rel_error > 1.0f)
  60. FatalError("Error too big!");
  61. }
  62. void HeightFieldShapeTest::Initialize()
  63. {
  64. if (sTerrainType == 0)
  65. {
  66. const int n = 128;
  67. const float cell_size = 1.0f;
  68. const float max_height = 5.0f;
  69. // Create height samples
  70. float heights[n * n];
  71. for (int y = 0; y < n; ++y)
  72. for (int x = 0; x < n; ++x)
  73. heights[y * n + x] = max_height * PerlinNoise3(float(x) * 8.0f / n, 0, float(y) * 8.0f / n, 256, 256, 256);
  74. // Make some holes
  75. heights[2 * n + 2] = HeightFieldShapeConstants::cNoCollisionValue;
  76. for (int y = 4; y < 33; ++y)
  77. for (int x = 4; x < 33; ++x)
  78. heights[y * n + x] = HeightFieldShapeConstants::cNoCollisionValue;
  79. // Make material indices
  80. uint8 max_material_index = 0;
  81. uint8 material_indices[Square(n - 1)];
  82. for (int y = 0; y < n - 1; ++y)
  83. for (int x = 0; x < n - 1; ++x)
  84. {
  85. uint8 material_index = uint8(round((Vec3(x * cell_size, 0, y * cell_size) - Vec3(n * cell_size / 2, 0, n * cell_size / 2)).Length() / 10.0f));
  86. max_material_index = max(max_material_index, material_index);
  87. material_indices[y * (n - 1) + x] = material_index;
  88. }
  89. // Mark the corners to validate that materials and heights match
  90. heights[0] = 0.0f;
  91. heights[n - 1] = 10.0f;
  92. heights[(n - 1) * n] = 20.0f;
  93. heights[n * n - 1] = 30.0f;
  94. material_indices[0] = 0;
  95. material_indices[n - 2] = 1;
  96. material_indices[(n - 2) * (n - 1)] = 2;
  97. material_indices[Square(n - 1) - 1] = 3;
  98. // Create materials
  99. PhysicsMaterialList materials;
  100. for (uint8 i = 0; i <= max_material_index; ++i)
  101. materials.push_back(new PhysicsMaterialSimple("Material " + ConvertToString(uint(i)), Color::sGetDistinctColor(i)));
  102. // Create height field
  103. mHeightField = static_cast<const HeightFieldShape *>(HeightFieldShapeSettings(heights, Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n), Vec3(cell_size, 1.0f, cell_size), n, material_indices, materials).Create().Get().GetPtr());
  104. Body &terrain = *mBodyInterface->CreateBody(BodyCreationSettings(mHeightField, Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  105. mBodyInterface->AddBody(terrain.GetID(), EActivation::DontActivate);
  106. sValidateHeightField(heights, n, mHeightField);
  107. }
  108. else if (sTerrainType == 1)
  109. {
  110. const int n = 1024;
  111. const float cell_size = 0.5f;
  112. // Get height samples
  113. vector<uint8> data = ReadData("Assets/heightfield1.bin");
  114. if (data.size() != sizeof(float) * n * n)
  115. FatalError("Invalid file size");
  116. const float *heights = (float *)&data[0];
  117. // Create height field
  118. mHeightField = static_cast<const HeightFieldShape *>(HeightFieldShapeSettings(heights, Vec3(-0.5f * cell_size * n, 0.0f, -0.5f * cell_size * n), Vec3(cell_size, 1.0f, cell_size), n).Create().Get().GetPtr());
  119. Body &terrain = *mBodyInterface->CreateBody(BodyCreationSettings(mHeightField, Vec3::sZero(), Quat::sIdentity(), EMotionType::Static, Layers::NON_MOVING));
  120. mBodyInterface->AddBody(terrain.GetID(), EActivation::DontActivate);
  121. sValidateHeightField(heights, n, mHeightField);
  122. }
  123. // Determine terrain height
  124. RayCastResult result;
  125. Vec3 start(0, 1000, 0);
  126. Vec3 direction(0, -2000, 0);
  127. RayCast ray { start, direction };
  128. if (mPhysicsSystem->GetNarrowPhaseQuery().CastRay(ray, result, SpecifiedBroadPhaseLayerFilter(BroadPhaseLayers::NON_MOVING), SpecifiedObjectLayerFilter(Layers::NON_MOVING)))
  129. mHitPos = start + result.mFraction * direction;
  130. // Dynamic body
  131. Body &body1 = *mBodyInterface->CreateBody(BodyCreationSettings(new BoxShape(Vec3(0.5f, 1.0f, 2.0f)), mHitPos + Vec3(0, 10, 0), Quat::sIdentity(), EMotionType::Dynamic, Layers::MOVING));
  132. mBodyInterface->AddBody(body1.GetID(), EActivation::Activate);
  133. }
  134. void HeightFieldShapeTest::PrePhysicsUpdate(const PreUpdateParams &inParams)
  135. {
  136. // Test the 'GetHeight' function and draw a marker on the surface
  137. Vec3 test_pos = inParams.mCameraState.mPos + 10.0f * inParams.mCameraState.mForward, surface_pos;
  138. SubShapeID sub_shape_id;
  139. if (mHeightField->ProjectOntoSurface(test_pos, surface_pos, sub_shape_id))
  140. {
  141. Vec3 surface_normal = mHeightField->GetSurfaceNormal(sub_shape_id, surface_pos);
  142. mDebugRenderer->DrawMarker(surface_pos, Color::sWhite, 1.0f);
  143. mDebugRenderer->DrawArrow(surface_pos, surface_pos + surface_normal, Color::sRed, 0.1f);
  144. }
  145. }
  146. void HeightFieldShapeTest::GetInitialCamera(CameraState &ioState) const
  147. {
  148. // Correct camera pos for hit position
  149. ioState.mPos += mHitPos;
  150. }
  151. void HeightFieldShapeTest::CreateSettingsMenu(DebugUI *inUI, UIElement *inSubMenu)
  152. {
  153. inUI->CreateTextButton(inSubMenu, "Select Terrain", [this, inUI]() {
  154. UIElement *terrain_name = inUI->CreateMenu();
  155. for (uint i = 0; i < size(sTerrainTypes); ++i)
  156. inUI->CreateTextButton(terrain_name, sTerrainTypes[i], [this, i]() { sTerrainType = i; RestartTest(); });
  157. inUI->ShowMenu(terrain_name);
  158. });
  159. }