ComputeTests.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. // Jolt Physics Library (https://github.com/jrouwe/JoltPhysics)
  2. // SPDX-FileCopyrightText: 2025 Jorrit Rouwe
  3. // SPDX-License-Identifier: MIT
  4. #include "UnitTestFramework.h"
  5. #include <Jolt/Compute/ComputeSystem.h>
  6. #include <Jolt/Compute/CPU/ComputeSystemCPU.h>
  7. #include <Jolt/Shaders/TestComputeBindings.h>
  8. #include <Jolt/Shaders/TestCompute2Bindings.h>
  9. #include <Jolt/Core/IncludeWindows.h>
  10. #include <Jolt/Core/RTTI.h>
  11. JPH_SUPPRESS_WARNINGS_STD_BEGIN
  12. #include <fstream>
  13. #include <filesystem>
  14. #ifdef JPH_PLATFORM_LINUX
  15. #include <unistd.h>
  16. #endif
  17. JPH_SUPPRESS_WARNINGS_STD_END
  18. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  19. #include <CoreFoundation/CoreFoundation.h>
  20. #endif
  21. JPH_DECLARE_REGISTER_SHADER(TestCompute)
  22. JPH_DECLARE_REGISTER_SHADER(TestCompute2)
  23. TEST_SUITE("ComputeTests")
  24. {
  25. static const char *cInvalidShaderName = "InvalidShader";
  26. static const char *cInvalidShaderCode = "invalid_shader_code";
  27. static void RunTests(ComputeSystem *inComputeSystem)
  28. {
  29. inComputeSystem->mShaderLoader = [](const char *inName, Array<uint8> &outData, String &outError) {
  30. // Special case to test what happens when an invalid file is returned
  31. if (strstr(inName, cInvalidShaderName) != nullptr)
  32. {
  33. outData.assign(cInvalidShaderCode, cInvalidShaderCode + strlen(cInvalidShaderCode));
  34. return true;
  35. }
  36. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  37. // In macOS the shaders are copied to the bundle
  38. CFBundleRef bundle = CFBundleGetMainBundle();
  39. CFURLRef resources = CFBundleCopyResourcesDirectoryURL(bundle);
  40. CFURLRef absolute = CFURLCopyAbsoluteURL(resources);
  41. CFRelease(resources);
  42. CFStringRef path_string = CFURLCopyFileSystemPath(absolute, kCFURLPOSIXPathStyle);
  43. CFRelease(absolute);
  44. char path[PATH_MAX];
  45. CFStringGetCString(path_string, path, PATH_MAX, kCFStringEncodingUTF8);
  46. CFRelease(path_string);
  47. String base_path = String(path) + "/Jolt/Shaders/";
  48. #else
  49. // On other platforms, start searching up from the application path
  50. #ifdef JPH_PLATFORM_WINDOWS
  51. char application_path[MAX_PATH] = { 0 };
  52. GetModuleFileName(nullptr, application_path, MAX_PATH);
  53. #elif defined(JPH_PLATFORM_LINUX)
  54. char application_path[PATH_MAX] = { 0 };
  55. int count = readlink("/proc/self/exe", application_path, PATH_MAX);
  56. if (count > 0)
  57. application_path[count] = 0;
  58. #else
  59. // Not implemented
  60. const char *application_path = "";
  61. #endif
  62. String base_path;
  63. filesystem::path shader_path(application_path);
  64. while (!shader_path.empty())
  65. {
  66. filesystem::path parent_path = shader_path.parent_path();
  67. if (parent_path == shader_path)
  68. break;
  69. shader_path = parent_path;
  70. filesystem::path full_path = shader_path / "Jolt" / "Shaders" / "";
  71. if (filesystem::exists(full_path))
  72. {
  73. base_path = String(full_path.string());
  74. break;
  75. }
  76. }
  77. #endif
  78. // Open file
  79. std::ifstream input((base_path + inName).c_str(), std::ios::in | std::ios::binary);
  80. if (!input.is_open())
  81. {
  82. outError = String("Could not open shader file: ") + base_path + inName;
  83. #if defined(JPH_PLATFORM_MACOS) || defined(JPH_PLATFORM_IOS)
  84. outError += "\nThis can fail on macOS when dxc or spirv-cross could not be found so the shaders could not be compiled.";
  85. #endif
  86. return false;
  87. }
  88. // Read contents of file
  89. input.seekg(0, ios_base::end);
  90. ifstream::pos_type length = input.tellg();
  91. input.seekg(0, ios_base::beg);
  92. outData.resize(size_t(length));
  93. if (length == 0)
  94. return true;
  95. input.read((char *)&outData[0], length);
  96. return true;
  97. };
  98. // Create a queue
  99. ComputeQueueResult queue_result = inComputeSystem->CreateComputeQueue();
  100. CHECK(!queue_result.HasError());
  101. Ref<ComputeQueue> queue = queue_result.Get();
  102. CHECK(queue != nullptr);
  103. // Test failing shader creation
  104. {
  105. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("NonExistingShader", 64);
  106. CHECK(shader_result.HasError());
  107. }
  108. {
  109. constexpr uint32 cNumElements = 1234; // Not a multiple of cTestComputeGroupSize
  110. constexpr uint32 cNumIterations = 10;
  111. constexpr JPH_float3 cFloat3Value = JPH_float3(0, 0, 0);
  112. constexpr JPH_float3 cFloat3Value2 = JPH_float3(0, 13, 0);
  113. constexpr uint32 cUIntValue = 7;
  114. constexpr uint32 cUploadValue = 42;
  115. // Can't change context buffer while commands are queued, so create multiple constant buffers
  116. Ref<ComputeBuffer> context[cNumIterations];
  117. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  118. {
  119. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::ConstantBuffer, 1, sizeof(TestComputeContext));
  120. CHECK(!buffer_result.HasError());
  121. context[iter] = buffer_result.Get();
  122. }
  123. CHECK(context != nullptr);
  124. // Create an upload buffer
  125. ComputeBufferResult upload_buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::UploadBuffer, 1, sizeof(uint32));
  126. CHECK(!upload_buffer_result.HasError());
  127. Ref<ComputeBuffer> upload_buffer = upload_buffer_result.Get();
  128. CHECK(upload_buffer != nullptr);
  129. uint32 *upload_data = upload_buffer->Map<uint32>(ComputeBuffer::EMode::Write);
  130. upload_data[0] = cUploadValue;
  131. upload_buffer->Unmap();
  132. // Create a read buffer
  133. UnitTestRandom rnd;
  134. Array<uint32> optional_data(cNumElements);
  135. for (uint32 &d : optional_data)
  136. d = rnd();
  137. ComputeBufferResult optional_buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::Buffer, cNumElements, sizeof(uint32), optional_data.data());
  138. CHECK(!optional_buffer_result.HasError());
  139. Ref<ComputeBuffer> optional_buffer = optional_buffer_result.Get();
  140. CHECK(optional_buffer != nullptr);
  141. // Create a read-write buffer
  142. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::RWBuffer, cNumElements, sizeof(uint32));
  143. CHECK(!buffer_result.HasError());
  144. Ref<ComputeBuffer> buffer = buffer_result.Get();
  145. CHECK(buffer != nullptr);
  146. // Create a read back buffer
  147. ComputeBufferResult readback_buffer_result = buffer->CreateReadBackBuffer();
  148. CHECK(!readback_buffer_result.HasError());
  149. Ref<ComputeBuffer> readback_buffer = readback_buffer_result.Get();
  150. CHECK(readback_buffer != nullptr);
  151. // Create the shader
  152. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("TestCompute", cTestComputeGroupSize);
  153. if (shader_result.HasError())
  154. {
  155. Trace("Shader could not be created: %s", shader_result.GetError().c_str());
  156. return;
  157. }
  158. Ref<ComputeShader> shader = shader_result.Get();
  159. CHECK(shader != nullptr);
  160. // Schedule work
  161. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  162. {
  163. // Fill in the context
  164. TestComputeContext *value = context[iter]->Map<TestComputeContext>(ComputeBuffer::EMode::Write);
  165. value->cFloat3Value = cFloat3Value;
  166. value->cUIntValue = cUIntValue;
  167. value->cFloat3Value2 = cFloat3Value2;
  168. value->cUIntValue2 = iter;
  169. value->cNumElements = cNumElements;
  170. context[iter]->Unmap();
  171. queue->SetShader(shader);
  172. queue->SetConstantBuffer("gContext", context[iter]);
  173. context[iter] = nullptr; // Release the reference to ensure the queue keeps ownership
  174. queue->SetBuffer("gOptionalData", optional_buffer);
  175. optional_buffer = nullptr; // Release the reference so we test that the queue keeps ownership and that in the 2nd iteration we can set a null buffer
  176. queue->SetBuffer("gUploadData", upload_buffer);
  177. queue->SetRWBuffer("gData", buffer);
  178. queue->Dispatch((cNumElements + cTestComputeGroupSize - 1) / cTestComputeGroupSize);
  179. }
  180. // Run all queued commands
  181. queue->ScheduleReadback(readback_buffer, buffer);
  182. queue->ExecuteAndWait();
  183. // Calculate the expected result
  184. Array<uint32> expected_data(cNumElements);
  185. for (uint32 iter = 0; iter < cNumIterations; ++iter)
  186. {
  187. // Copy of the shader logic
  188. uint cUIntValue2 = iter;
  189. if (cUIntValue2 == 0)
  190. {
  191. // First write, uses optional data and tests that the packing of float3/uint3's works
  192. for (uint32 i = 0; i < cNumElements; ++i)
  193. expected_data[i] = optional_data[i] + int(cFloat3Value2.y) + cUploadValue;
  194. }
  195. else
  196. {
  197. // Read-modify-write gData
  198. for (uint32 i = 0; i < cNumElements; ++i)
  199. expected_data[i] = (expected_data[i] + cUIntValue) * cUIntValue2;
  200. }
  201. }
  202. // Compare computed data with expected data
  203. uint32 *data = readback_buffer->Map<uint32>(ComputeBuffer::EMode::Read);
  204. for (uint32 i = 0; i < cNumElements; ++i)
  205. CHECK(data[i] == expected_data[i]);
  206. readback_buffer->Unmap();
  207. }
  208. // Test helper functions
  209. {
  210. // Create the shader
  211. ComputeShaderResult shader_result = inComputeSystem->CreateComputeShader("TestCompute2", cTestCompute2GroupSize);
  212. if (shader_result.HasError())
  213. {
  214. Trace("Shader could not be created: %s", shader_result.GetError().c_str());
  215. return;
  216. }
  217. Ref<ComputeShader> shader = shader_result.Get();
  218. CHECK(shader != nullptr);
  219. const Mat44 cMat44Value(Vec4(2, 3, 5, 0), Vec4(7, 11, 13, 0), Vec4(13, 15, 17, 0), Vec4(17, 19, 23, 0));
  220. const Vec3 cMat44MulValue(29, 31, 37);
  221. const Vec3 cDecompressedVec3(Vec3(-2, 3, -5).Normalized());
  222. const uint32 cCompressedVec3 = cDecompressedVec3.CompressUnitVector();
  223. const Quat cDecompressedQuat(Vec4(2, -3, 5, -7).Normalized());
  224. const uint32 cCompressedQuat = cDecompressedQuat.CompressUnitQuat();
  225. // Generate input data
  226. TestCompute2Input input;
  227. cMat44Value.StoreFloat4x4(input.mMat44Value);
  228. cMat44MulValue.StoreFloat3(&input.mMat44MulValue);
  229. input.mCompressedVec3 = cCompressedVec3;
  230. input.mCompressedQuat = cCompressedQuat;
  231. // Create input buffer
  232. ComputeBufferResult buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::Buffer, 1, sizeof(TestCompute2Input), &input);
  233. CHECK(!buffer_result.HasError());
  234. Ref<ComputeBuffer> input_buffer = buffer_result.Get();
  235. // Create a read-write buffer for the output
  236. buffer_result = inComputeSystem->CreateComputeBuffer(ComputeBuffer::EType::RWBuffer, 1, sizeof(TestCompute2Output));
  237. CHECK(!buffer_result.HasError());
  238. Ref<ComputeBuffer> output_buffer = buffer_result.Get();
  239. CHECK(output_buffer != nullptr);
  240. // Create a read back buffer
  241. buffer_result = output_buffer->CreateReadBackBuffer();
  242. CHECK(!buffer_result.HasError());
  243. Ref<ComputeBuffer> readback_buffer = buffer_result.Get();
  244. CHECK(readback_buffer != nullptr);
  245. // Execute the shader
  246. queue->SetShader(shader);
  247. queue->SetBuffer("gInput", input_buffer);
  248. queue->SetRWBuffer("gOutput", output_buffer);
  249. queue->Dispatch(1);
  250. queue->ScheduleReadback(readback_buffer, output_buffer);
  251. queue->ExecuteAndWait();
  252. // Verify the output
  253. TestCompute2Output *output = readback_buffer->Map<TestCompute2Output>(ComputeBuffer::EMode::Read);
  254. const Vec3 expected_mul3x4 = cMat44Value * cMat44MulValue;
  255. CHECK(Vec3(output->mMul3x4Output) == expected_mul3x4);
  256. const Vec3 expected_mul3x3 = cMat44Value.Multiply3x3(cMat44MulValue);
  257. CHECK(Vec3(output->mMul3x3Output) == expected_mul3x3);
  258. const Vec3 expected_decompressed_vec3 = Vec3::sDecompressUnitVector(cCompressedVec3);
  259. CHECK(Vec3(output->mDecompressedVec3).IsClose(expected_decompressed_vec3));
  260. const Quat expected_decompressed_quat = Quat::sDecompressUnitQuat(cCompressedQuat);
  261. CHECK(Quat(output->mDecompressedQuat).IsClose(expected_decompressed_quat));
  262. readback_buffer->Unmap();
  263. }
  264. }
  265. #ifdef JPH_USE_DX12
  266. TEST_CASE("TestComputeDX12")
  267. {
  268. ComputeSystemResult compute_system = CreateComputeSystemDX12();
  269. CHECK(!compute_system.HasError());
  270. if (!compute_system.HasError())
  271. {
  272. CHECK(compute_system.Get() != nullptr);
  273. RunTests(compute_system.Get());
  274. // Test failing shader compilation
  275. {
  276. ComputeShaderResult shader_result = compute_system.Get()->CreateComputeShader(cInvalidShaderName, 64);
  277. CHECK(shader_result.HasError());
  278. CHECK(strstr(shader_result.GetError().c_str(), cInvalidShaderCode) != nullptr); // Assume that the error message contains the invalid code
  279. }
  280. }
  281. }
  282. #endif // JPH_USE_DX12
  283. #ifdef JPH_USE_MTL
  284. TEST_CASE("TestComputeMTL")
  285. {
  286. ComputeSystemResult compute_system = CreateComputeSystemMTL();
  287. CHECK(!compute_system.HasError());
  288. if (!compute_system.HasError())
  289. {
  290. CHECK(compute_system.Get() != nullptr);
  291. RunTests(compute_system.Get());
  292. }
  293. }
  294. #endif // JPH_USE_MTL
  295. #ifdef JPH_USE_VK
  296. TEST_CASE("TestComputeVK")
  297. {
  298. ComputeSystemResult compute_system = CreateComputeSystemVK();
  299. CHECK(!compute_system.HasError());
  300. if (!compute_system.HasError())
  301. {
  302. CHECK(compute_system.Get() != nullptr);
  303. RunTests(compute_system.Get());
  304. }
  305. }
  306. #endif // JPH_USE_VK
  307. TEST_CASE("TestComputeCPU")
  308. {
  309. ComputeSystemResult compute_system = CreateComputeSystemCPU();
  310. CHECK(!compute_system.HasError());
  311. if (!compute_system.HasError())
  312. {
  313. CHECK(compute_system.Get() != nullptr);
  314. JPH_REGISTER_SHADER(StaticCast<ComputeSystemCPU>(compute_system.Get()), TestCompute);
  315. JPH_REGISTER_SHADER(StaticCast<ComputeSystemCPU>(compute_system.Get()), TestCompute2);
  316. RunTests(compute_system.Get());
  317. }
  318. }
  319. }