Aucune description

TestApp1.cpp 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. // TestApp1.cpp : Defines the entry point for the application.
  2. //
  3. #ifdef _WIN32
  4. #include "Win32/stdafx.h"
  5. #endif
  6. #include <DK.h>
  7. DKString ShaderStageNames(uint32_t s)
  8. {
  9. DKArray<const char*> stages;
  10. if (s & (uint32_t)DKShaderStage::Vertex)
  11. stages.Add("Vertex");
  12. if (s & (uint32_t)DKShaderStage::TessellationControl)
  13. stages.Add("TessCtrl");
  14. if (s & (uint32_t)DKShaderStage::TessellationEvaluation)
  15. stages.Add("TessEval");
  16. if (s & (uint32_t)DKShaderStage::Geometry)
  17. stages.Add("Geometry");
  18. if (s & (uint32_t)DKShaderStage::Fragment)
  19. stages.Add("Fragment");
  20. if (s & (uint32_t)DKShaderStage::Compute)
  21. stages.Add("Compute");
  22. if (stages.IsEmpty())
  23. return "";
  24. DKString str = stages.Value(0);
  25. for (int i = 1; i < stages.Count(); ++i)
  26. str += DKString::Format(", %ls", stages.Value(i));
  27. return str;
  28. }
  29. const char* ShaderDataTypeStr(DKShaderDataType t)
  30. {
  31. switch (t) {
  32. case DKShaderDataType::Unknown: return "Unknown";
  33. case DKShaderDataType::None: return "None";
  34. case DKShaderDataType::Struct: return "Struct";
  35. case DKShaderDataType::Texture: return "Texture";
  36. case DKShaderDataType::Sampler: return "Sampler";
  37. case DKShaderDataType::Float: return "Float";
  38. case DKShaderDataType::Float2: return "Float2";
  39. case DKShaderDataType::Float3: return "Float3";
  40. case DKShaderDataType::Float4: return "Float4";
  41. case DKShaderDataType::Float2x2: return "Float2x2";
  42. case DKShaderDataType::Float2x3: return "Float2x3";
  43. case DKShaderDataType::Float2x4: return "Float2x4";
  44. case DKShaderDataType::Float3x2: return "Float3x2";
  45. case DKShaderDataType::Float3x3: return "Float3x3";
  46. case DKShaderDataType::Float3x4: return "Float3x4";
  47. case DKShaderDataType::Float4x2: return "Float4x2";
  48. case DKShaderDataType::Float4x3: return "Float4x3";
  49. case DKShaderDataType::Float4x4: return "Float4x4";
  50. case DKShaderDataType::Half: return "Half";
  51. case DKShaderDataType::Half2: return "Half2";
  52. case DKShaderDataType::Half3: return "Half3";
  53. case DKShaderDataType::Half4: return "Half4";
  54. case DKShaderDataType::Half2x2: return "Half2x2";
  55. case DKShaderDataType::Half2x3: return "Half2x3";
  56. case DKShaderDataType::Half2x4: return "Half2x4";
  57. case DKShaderDataType::Half3x2: return "Half3x2";
  58. case DKShaderDataType::Half3x3: return "Half3x3";
  59. case DKShaderDataType::Half3x4: return "Half3x4";
  60. case DKShaderDataType::Half4x2: return "Half4x2";
  61. case DKShaderDataType::Half4x3: return "Half4x3";
  62. case DKShaderDataType::Half4x4: return "Half4x4";
  63. case DKShaderDataType::Int: return "Int";
  64. case DKShaderDataType::Int2: return "Int2";
  65. case DKShaderDataType::Int3: return "Int3";
  66. case DKShaderDataType::Int4: return "Int4";
  67. case DKShaderDataType::UInt: return "UInt";
  68. case DKShaderDataType::UInt2: return "UInt2";
  69. case DKShaderDataType::UInt3: return "UInt3";
  70. case DKShaderDataType::UInt4: return "UInt4";
  71. case DKShaderDataType::Short: return "Short";
  72. case DKShaderDataType::Short2: return "Short2";
  73. case DKShaderDataType::Short3: return "Short3";
  74. case DKShaderDataType::Short4: return "Short4";
  75. case DKShaderDataType::UShort: return "UShort";
  76. case DKShaderDataType::UShort2: return "UShort2";
  77. case DKShaderDataType::UShort3: return "UShort3";
  78. case DKShaderDataType::UShort4: return "UShort4";
  79. case DKShaderDataType::Char: return "Char";
  80. case DKShaderDataType::Char2: return "Char2";
  81. case DKShaderDataType::Char3: return "Char3";
  82. case DKShaderDataType::Char4: return "Char4";
  83. case DKShaderDataType::UChar: return "UChar";
  84. case DKShaderDataType::UChar2: return "UChar2";
  85. case DKShaderDataType::UChar3: return "UChar3";
  86. case DKShaderDataType::UChar4: return "UChar4";
  87. case DKShaderDataType::Bool: return "Bool";
  88. case DKShaderDataType::Bool2: return "Bool2";
  89. case DKShaderDataType::Bool3: return "Bool3";
  90. case DKShaderDataType::Bool4: return "Bool4";
  91. }
  92. return "Error";
  93. }
  94. void PrintShaderResource(const DKShaderResource& res, DKLogCategory c = DKLogCategory::Info)
  95. {
  96. struct MemberPrinter
  97. {
  98. const DKShaderResource& res;
  99. int indent;
  100. DKLogCategory c;
  101. void operator()(const DKShaderResourceStruct& str) const
  102. {
  103. DKString indentStr = "";
  104. for (int i = 0; i < indent; ++i)
  105. {
  106. indentStr += " ";
  107. }
  108. for (const DKShaderResourceStructMember& mem : str.members)
  109. {
  110. if (mem.count > 1)
  111. {
  112. DKLog(c, " %ls+ %ls[%d] (%s, Offset: %d, Stride: %d)",
  113. (const wchar_t*)indentStr,
  114. (const wchar_t*)mem.name,
  115. mem.count,
  116. ShaderDataTypeStr(mem.dataType),
  117. mem.offset, mem.stride);
  118. }
  119. else
  120. {
  121. DKLog(c, " %ls+ %ls (%s, Offset: %d)",
  122. (const wchar_t*)indentStr,
  123. (const wchar_t*)mem.name,
  124. ShaderDataTypeStr(mem.dataType),
  125. mem.offset);
  126. }
  127. auto* p = res.structTypeMemberMap.Find(mem.typeInfoKey);
  128. if (p)
  129. {
  130. DKLog(c, " %ls Struct \"%ls\"",
  131. (const wchar_t*)indentStr,
  132. (const wchar_t*)mem.typeInfoKey);
  133. MemberPrinter{ res, indent + 1, c}.operator()(p->value);
  134. }
  135. }
  136. }
  137. };
  138. if (res.count > 1)
  139. DKLog(c, "ShaderResource: %ls[%d] (set=%d, binding=%d, stages=%ls)",
  140. (const wchar_t*)res.name, res.count, res.set, res.binding,
  141. (const wchar_t*)ShaderStageNames(res.stages));
  142. else
  143. DKLog(c, "ShaderResource: %ls (set=%d, binding=%d, stages=%ls)",
  144. (const wchar_t*)res.name, res.set, res.binding,
  145. (const wchar_t*)ShaderStageNames(res.stages));
  146. const char* type = "Unknown (ERROR)";
  147. switch (res.type)
  148. {
  149. case DKShaderResource::TypeBuffer: type = "Buffer"; break;
  150. case DKShaderResource::TypeTexture: type = "Texture"; break;
  151. case DKShaderResource::TypeSampler: type = "Sampler"; break;
  152. case DKShaderResource::TypeTextureSampler: type = "SampledTexture"; break;
  153. }
  154. const char* access = "Unknown (ERROR)";
  155. switch (res.access)
  156. {
  157. case DKShaderResource::AccessReadOnly: access = "ReadOnly"; break;
  158. case DKShaderResource::AccessWriteOnly: access = "WriteOnly"; break;
  159. case DKShaderResource::AccessReadWrite: access = "ReadWrite"; break;
  160. }
  161. if (res.type == DKShaderResource::TypeBuffer)
  162. {
  163. DKLog(c, " Type:%s, Access:%s, Enabled:%d, Size:%d",
  164. type,
  165. access,
  166. int(res.enabled),
  167. res.typeInfo.buffer.size);
  168. }
  169. else
  170. {
  171. DKLog(c, " Type:%s, Access:%s, Enabled:%d",
  172. type,
  173. access,
  174. int(res.enabled));
  175. }
  176. if (res.typeInfoKey.Length() > 0)
  177. DKLog(c, " Struct \"%ls\"", (const wchar_t*)res.typeInfoKey);
  178. if (res.type == DKShaderResource::TypeBuffer)
  179. {
  180. auto p = res.structTypeMemberMap.Find(res.typeInfoKey);
  181. if (p)
  182. MemberPrinter{ res, 1 , c}.operator()(p->value);
  183. }
  184. }
  185. void PrintPipelineReflection(const DKPipelineReflection* reflection, DKLogCategory c = DKLogCategory::Error)
  186. {
  187. DKLog(c, "=========================================================");
  188. DKLog(c, "PipelineReflection.InputAttributes: %d", reflection->inputAttributes.Count());
  189. for (int i = 0; i < reflection->inputAttributes.Count(); ++i)
  190. {
  191. const DKShaderAttribute& attr = reflection->inputAttributes.Value(i);
  192. DKLog(c, " [in] ShaderAttribute[%d]: \"%ls\" (location:%u)",
  193. i, (const wchar_t*)attr.name, attr.location);
  194. }
  195. DKLog(c, "---------------------------------------------------------");
  196. DKLog(c, "PipelineReflection.Resources: %d", reflection->resources.Count());
  197. for (auto& arg : reflection->resources)
  198. PrintShaderResource(arg, c);
  199. for (int i = 0; i < reflection->pushConstantLayouts.Count(); ++i)
  200. {
  201. const DKShaderPushConstantLayout& layout = reflection->pushConstantLayouts.Value(i);
  202. DKLog(c, " PushConstant:%d \"%ls\" (offset:%u, size:%u, stages:%ls)",
  203. i, (const wchar_t*)layout.name, layout.offset, layout.size,
  204. (const wchar_t*)ShaderStageNames(layout.stages));
  205. }
  206. DKLog(c, "=========================================================");
  207. }
  208. class TestApp1 : public DKApplication
  209. {
  210. DKObject<DKWindow> window;
  211. DKObject<DKThread> renderThread;
  212. DKResourcePool resourcePool;
  213. DKAtomicNumber32 runningRenderThread;
  214. public:
  215. void RenderThread(void)
  216. {
  217. DKObject<DKData> vertData = resourcePool.LoadResourceData("triangle.vert.spv");
  218. DKObject<DKData> fragData = resourcePool.LoadResourceData("triangle.frag.spv");
  219. DKShader vertShader(vertData);
  220. DKShader fragShader(fragData);
  221. DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
  222. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  223. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  224. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  225. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  226. DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
  227. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  228. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  229. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  230. {
  231. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  232. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  233. }
  234. struct Vertex
  235. {
  236. DKVector3 position;
  237. DKVector3 color;
  238. };
  239. DKArray<Vertex> vertexData =
  240. {
  241. { { 0.0f, -0.5f, 0.0f },{ 1.0f, 1.0f, 1.0f } },
  242. { { 0.5f, 0.5f, 0.0f },{ 0.0f, 1.0f, 0.0f } },
  243. { { -0.5f, 0.5f, 0.0f },{ 0.0f, 0.0f, 1.0f } }
  244. };
  245. uint32_t vertexBufferSize = static_cast<uint32_t>(vertexData.Count()) * sizeof(Vertex);
  246. DKArray<uint32_t> indexData = { 0, 1, 2 };
  247. uint32_t indexBufferSize = indexData.Count() * sizeof(uint32_t);
  248. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  249. memcpy(vertexBuffer->Lock(), vertexData, vertexBufferSize);
  250. vertexBuffer->Unlock();
  251. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  252. memcpy(indexBuffer->Lock(), indexData, indexBufferSize);
  253. indexBuffer->Unlock();
  254. DKRenderPipelineDescriptor pipelineDescriptor;
  255. pipelineDescriptor.vertexFunction = vertShaderFunction;
  256. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  257. pipelineDescriptor.colorAttachments.Resize(1);
  258. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  259. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::Invalid; // no depth buffer
  260. pipelineDescriptor.vertexDescriptor.attributes = {
  261. { DKVertexFormat::Float3, 0, 0, 0 },
  262. { DKVertexFormat::Float3, sizeof(DKVector3), 0, 1 },
  263. };
  264. pipelineDescriptor.vertexDescriptor.layouts = {
  265. { DKVertexStepRate::Vertex, sizeof(Vertex), 0 },
  266. };
  267. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  268. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  269. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  270. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  271. pipelineDescriptor.cullMode = DKCullMode::None;
  272. pipelineDescriptor.rasterizationEnabled = true;
  273. DKPipelineReflection reflection;
  274. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  275. if (pipelineState)
  276. {
  277. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  278. }
  279. DKShaderBindingSetLayout layout;
  280. if (1)
  281. {
  282. DKShaderBinding binding = {
  283. 0,
  284. DKShader::DescriptorTypeUniformBuffer,
  285. 1,
  286. nullptr
  287. };
  288. layout.bindings.Add(binding);
  289. }
  290. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  291. if (bindSet)
  292. {
  293. struct
  294. {
  295. DKMatrix4 projectionMatrix;
  296. DKMatrix4 modelMatrix;
  297. DKMatrix4 viewMatrix;
  298. } ubo;
  299. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(ubo), DKGpuBuffer::StorageModeShared, DKCpuCacheModeDefault);
  300. if (uboBuffer)
  301. {
  302. ubo.projectionMatrix = DKMatrix4::identity;
  303. ubo.modelMatrix = DKMatrix4::identity;
  304. ubo.viewMatrix = DKMatrix4::identity;
  305. void* p = uboBuffer->Lock(0);
  306. if (p)
  307. {
  308. memcpy(p, &ubo, sizeof(ubo));
  309. uboBuffer->Unlock();
  310. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(ubo));
  311. }
  312. else
  313. {
  314. DKLogE("GpuBuffer Lock failed!");
  315. }
  316. }
  317. }
  318. DKTimer timer;
  319. timer.Reset();
  320. DKLog("Render thread begin");
  321. while (!runningRenderThread.CompareAndSet(0, 0))
  322. {
  323. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  324. double t = timer.Elapsed();
  325. t = (cos(t) + 1.0) * 0.5;
  326. rpd.colorAttachments.Value(0).clearColor = DKColor(t, 0.0, 0.0, 0.0);
  327. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  328. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  329. if (encoder)
  330. {
  331. encoder->SetRenderPipelineState(pipelineState);
  332. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  333. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  334. encoder->SetResources(0, bindSet);
  335. // draw scene!
  336. encoder->DrawIndexed(indexData.Count(), 1, 0, 0, 1);
  337. encoder->EndEncoding();
  338. buffer->Commit();
  339. swapChain->Present();
  340. }
  341. else
  342. {
  343. }
  344. DKThread::Sleep(0.01);
  345. }
  346. DKLog("RenderThread terminating...");
  347. }
  348. void OnInitialize(void) override
  349. {
  350. DKLogD("%s", DKGL_FUNCTION_NAME);
  351. DKString resPath = DefaultPath(SystemPath::AppResource);
  352. resPath = resPath.FilePathStringByAppendingPath("Data");
  353. DKLog("resPath: %ls", (const wchar_t*)resPath);
  354. resourcePool.AddLocatorForPath(resPath);
  355. window = DKWindow::Create("DefaultWindow");
  356. window->SetOrigin({ 0, 0 });
  357. window->Resize({ 320, 240 });
  358. window->Activate();
  359. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  360. {
  361. if (e.type == DKWindow::WindowEvent::WindowClosed)
  362. DKApplication::Instance()->Terminate(0);
  363. }), NULL, NULL);
  364. runningRenderThread = 1;
  365. renderThread = DKThread::Create(DKFunction(this, &TestApp1::RenderThread)->Invocation());
  366. }
  367. void OnTerminate(void) override
  368. {
  369. DKLogD("%s", DKGL_FUNCTION_NAME);
  370. runningRenderThread = 0;
  371. renderThread->WaitTerminate();
  372. renderThread = NULL;
  373. window = NULL;
  374. DKLogI("Memory Pool Statistics");
  375. size_t numBuckets = DKMemoryPoolNumberOfBuckets();
  376. DKMemoryPoolBucketStatus* buckets = new DKMemoryPoolBucketStatus[numBuckets];
  377. DKMemoryPoolQueryAllocationStatus(buckets, numBuckets);
  378. size_t usedBytes = 0;
  379. for (int i = 0; i < numBuckets; ++i)
  380. {
  381. if (buckets[i].totalChunks > 0)
  382. {
  383. DKLogI("--> %5lu: %5lu/%5lu, usage: %.1f%%, used: %.1fKB, total: %.1fKB",
  384. buckets[i].chunkSize,
  385. buckets[i].usedChunks, buckets[i].totalChunks,
  386. double(buckets[i].usedChunks) / double(buckets[i].totalChunks) * 100.0,
  387. double(buckets[i].chunkSize * buckets[i].usedChunks) / 1024.0,
  388. double(buckets[i].chunkSize * buckets[i].totalChunks) / 1024.0
  389. );
  390. usedBytes += buckets[i].chunkSize * buckets[i].usedChunks;
  391. }
  392. }
  393. DKLogI("MemoryPool Usage: %.1fMB / %.1fMB", double(usedBytes) / (1024 * 1024), double(DKMemoryPoolSize()) / (1024 * 1024));
  394. delete[] buckets;
  395. }
  396. };
  397. #ifdef _WIN32
  398. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  399. _In_opt_ HINSTANCE hPrevInstance,
  400. _In_ LPWSTR lpCmdLine,
  401. _In_ int nCmdShow)
  402. #else
  403. int main(int argc, const char * argv[])
  404. #endif
  405. {
  406. TestApp1 app;
  407. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  408. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  409. return app.Run();
  410. }