DKGL2 sample codes

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. #include <cstddef>
  2. #include "app.h"
  3. #include "util.h"
  4. #define TINYOBJLOADER_IMPLMENTATION
  5. #include "tiny_obj_loader.h"
  6. #include <unordered_map>
  7. class SampleObjMesh
  8. {
  9. public:
  10. struct Vertex
  11. {
  12. DKVector3 inPos;
  13. DKVector3 inColor;
  14. DKVector2 intexCoord;
  15. int Compare(const Vertex& Other) const
  16. {
  17. const float pp[] = { this->inPos.x, this->inPos.y, this->inPos.z,
  18. this->inColor.x, this->inColor.y, this->inColor.z,
  19. this->intexCoord.x, this->intexCoord.y};
  20. const float rr[] = { Other.inPos.x, Other.inPos.y, Other.inPos.z,
  21. Other.inColor.x, Other.inColor.y, Other.inColor.z,
  22. Other.intexCoord.x, Other.intexCoord.y};
  23. for (int i = 0; i < std::size(pp); ++i)
  24. {
  25. auto k = pp[i] - rr[i];
  26. if (abs(k) < 0.0001)
  27. continue;
  28. if (k > 0)
  29. return 1;
  30. else if (k < 0)
  31. return -1;
  32. }
  33. return 0;
  34. }
  35. bool operator > (const Vertex& Other) const
  36. {
  37. return Compare(Other) > 0;
  38. }
  39. bool operator < (const Vertex& Other) const
  40. {
  41. return Compare(Other) < 0;
  42. }
  43. };
  44. SampleObjMesh()
  45. {
  46. vertices.Reserve(100);
  47. indices.Reserve(100);
  48. }
  49. void LoadFromObjFile(const char* InPath)
  50. {
  51. tinyobj::attrib_t attrib;
  52. std::vector<tinyobj::shape_t> shapes;
  53. std::vector<tinyobj::material_t> materials;
  54. std::string err;
  55. if (!tinyobj::LoadObj(&attrib, &shapes, &materials, &err, InPath)) {
  56. throw std::runtime_error(err);
  57. }
  58. DKMap<Vertex, uint32_t> uniqueVertices;
  59. DKLog("Save to Container");
  60. for (const auto& shape : shapes)
  61. {
  62. for (const auto& index : shape.mesh.indices)
  63. {
  64. Vertex vertex = {};
  65. vertex.inPos = {
  66. attrib.vertices[3 * index.vertex_index + 0],
  67. attrib.vertices[3 * index.vertex_index + 1],
  68. attrib.vertices[3 * index.vertex_index + 2]
  69. };
  70. if (attrib.texcoords.size())
  71. {
  72. vertex.intexCoord = {
  73. attrib.texcoords[2 * index.texcoord_index + 0],
  74. 1.0f - attrib.texcoords[2 * index.texcoord_index + 1]
  75. };
  76. }
  77. vertex.inColor = { 1.0f, 1.0f, 1.0f };
  78. if (uniqueVertices.Find(vertex) == nullptr)
  79. {
  80. uniqueVertices.Insert(vertex, static_cast<uint32_t>(vertices.Count()));
  81. vertices.Add(vertex);
  82. }
  83. indices.Add(uniqueVertices.Value(vertex));
  84. aabb.Expand(vertex.inPos);
  85. }
  86. }
  87. }
  88. uint32_t GetVerticesCount() const {
  89. return static_cast<uint32_t>(vertices.Count()); };
  90. uint32_t GetIndicesCount() const {
  91. return static_cast<uint32_t>(indices.Count()); };
  92. const Vertex* GetVerticesData() const {
  93. return vertices; }
  94. const uint32_t* GetIndicesData() const {
  95. return indices; }
  96. DKAabb aabb;
  97. private:
  98. DKArray<Vertex> vertices;
  99. DKArray<uint32_t> indices;
  100. DKSpinLock MeshLock;
  101. };
  102. ///// Template Spealization for DKString. (for DKMap, DKSet)
  103. //template <> struct DKMapKeyComparator<SampleObjMesh::Vertex>
  104. //{
  105. // int operator () (const DKStringW& lhs, const DKStringW& rhs) const
  106. // {
  107. // return lhs.Compare(rhs);
  108. // }
  109. //};
  110. class MeshDemo : public SampleApp
  111. {
  112. DKObject<DKWindow> window;
  113. DKObject<DKThread> renderThread;
  114. DKAtomicNumber32 runningRenderThread;
  115. DKObject<SampleObjMesh> SampleMesh;
  116. public:
  117. void LoadMesh()
  118. {
  119. DKLog("Loading Mesh");
  120. DKString path = resourcePool.ResourceFilePath("meshes/chalet.obj");
  121. SampleMesh->LoadFromObjFile(DKStringU8(path));
  122. }
  123. DKObject<DKTexture> LoadTexture2D(DKCommandQueue* queue, DKData* data)
  124. {
  125. DKObject<DKImage> image = DKImage::Create(data);
  126. if (image)
  127. {
  128. DKGraphicsDevice* device = queue->Device();
  129. DKTextureDescriptor texDesc = {};
  130. texDesc.textureType = DKTexture::Type2D;
  131. texDesc.pixelFormat = DKPixelFormat::RGBA8Unorm;
  132. texDesc.width = image->Width();
  133. texDesc.height = image->Height();
  134. texDesc.depth = 1;
  135. texDesc.mipmapLevels = 1;
  136. texDesc.sampleCount = 1;
  137. texDesc.arrayLength = 1;
  138. texDesc.usage = DKTexture::UsageCopyDestination | DKTexture::UsageSampled;
  139. DKObject<DKTexture> tex = device->CreateTexture(texDesc);
  140. if (tex)
  141. {
  142. size_t bytesPerPixel = image->BytesPerPixel();
  143. DKASSERT_DESC(bytesPerPixel == DKPixelFormatBytesPerPixel(texDesc.pixelFormat), "BytesPerPixel mismatch!");
  144. uint32_t width = image->Width();
  145. uint32_t height = image->Height();
  146. size_t bufferLength = bytesPerPixel * width * height;
  147. DKObject<DKGpuBuffer> stagingBuffer = device->CreateBuffer(bufferLength, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  148. memcpy(stagingBuffer->Contents(), image->Contents(), bufferLength);
  149. stagingBuffer->Flush();
  150. DKObject<DKCommandBuffer> cb = queue->CreateCommandBuffer();
  151. DKObject<DKCopyCommandEncoder> encoder = cb->CreateCopyCommandEncoder();
  152. encoder->CopyFromBufferToTexture(stagingBuffer,
  153. { 0, width, height },
  154. tex,
  155. { 0,0, 0,0,0 },
  156. { width,height,1 });
  157. encoder->EndEncoding();
  158. cb->Commit();
  159. DKLog("Texture created!");
  160. return tex;
  161. }
  162. }
  163. return nullptr;
  164. }
  165. void RenderThread(void)
  166. {
  167. DKObject<DKData> vertData = resourcePool.LoadResourceData("shaders/mesh.vert.spv");
  168. DKObject<DKData> fragData = resourcePool.LoadResourceData("shaders/mesh.frag.spv");
  169. DKShader vertShader(vertData);
  170. DKShader fragShader(fragData);
  171. DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
  172. DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
  173. // create texture
  174. DKObject<DKTexture> texture = LoadTexture2D(queue, resourcePool.LoadResourceData("meshes/chalet.png"));
  175. // create sampler
  176. DKSamplerDescriptor samplerDesc = {};
  177. samplerDesc.magFilter = DKSamplerDescriptor::MinMagFilterLinear;
  178. samplerDesc.minFilter = DKSamplerDescriptor::MinMagFilterLinear;
  179. samplerDesc.addressModeU = DKSamplerDescriptor::AddressModeClampToEdge;
  180. samplerDesc.addressModeV = DKSamplerDescriptor::AddressModeClampToEdge;
  181. samplerDesc.addressModeW = DKSamplerDescriptor::AddressModeClampToEdge;
  182. samplerDesc.maxAnisotropy = 16;
  183. DKObject<DKSamplerState> sampler = device->CreateSamplerState(samplerDesc);
  184. // create shaders
  185. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  186. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  187. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  188. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  189. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  190. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  191. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  192. {
  193. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  194. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  195. }
  196. uint32_t vertexBufferSize = static_cast<uint32_t>(SampleMesh->GetVerticesCount()) * sizeof(SampleObjMesh::Vertex);
  197. uint32_t indexBufferSize = SampleMesh->GetIndicesCount() * sizeof(uint32_t);
  198. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  199. memcpy(vertexBuffer->Contents(), SampleMesh->GetVerticesData(), vertexBufferSize);
  200. vertexBuffer->Flush();
  201. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  202. memcpy(indexBuffer->Contents(), SampleMesh->GetIndicesData(), indexBufferSize);
  203. indexBuffer->Flush();
  204. DKRenderPipelineDescriptor pipelineDescriptor;
  205. // setup shader
  206. pipelineDescriptor.vertexFunction = vertShaderFunction;
  207. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  208. // setup color-attachment render-targets
  209. pipelineDescriptor.colorAttachments.Resize(1);
  210. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  211. pipelineDescriptor.colorAttachments.Value(0).blendingEnabled = false;
  212. pipelineDescriptor.colorAttachments.Value(0).sourceRGBBlendFactor = DKBlendFactor::SourceAlpha;
  213. pipelineDescriptor.colorAttachments.Value(0).destinationRGBBlendFactor = DKBlendFactor::OneMinusSourceAlpha;
  214. // setup depth-stencil
  215. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::D32Float;
  216. pipelineDescriptor.depthStencilDescriptor.depthWriteEnabled = true;
  217. pipelineDescriptor.depthStencilDescriptor.depthCompareFunction = DKCompareFunctionLessEqual;
  218. // setup vertex buffer and attributes
  219. pipelineDescriptor.vertexDescriptor.attributes = {
  220. { DKVertexFormat::Float3, offsetof(SampleObjMesh::Vertex, inPos), 0, 0 },
  221. { DKVertexFormat::Float3, offsetof(SampleObjMesh::Vertex, inColor), 0, 1 },
  222. { DKVertexFormat::Float2, offsetof(SampleObjMesh::Vertex, intexCoord), 0, 2 },
  223. };
  224. pipelineDescriptor.vertexDescriptor.layouts = {
  225. { DKVertexStepRate::Vertex, sizeof(SampleObjMesh::Vertex), 0 },
  226. };
  227. // setup topology and rasterization
  228. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  229. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  230. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  231. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  232. pipelineDescriptor.cullMode = DKCullMode::Back;
  233. pipelineDescriptor.rasterizationEnabled = true;
  234. DKPipelineReflection reflection;
  235. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  236. if (pipelineState)
  237. {
  238. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  239. }
  240. DKShaderBindingSetLayout layout;
  241. if (1)
  242. {
  243. DKShaderBinding bindings[2] = {
  244. {
  245. 0,
  246. DKShader::DescriptorTypeUniformBuffer,
  247. 1,
  248. nullptr
  249. },
  250. {
  251. 1,
  252. DKShader::DescriptorTypeTextureSampler,
  253. 1,
  254. nullptr
  255. },
  256. };
  257. layout.bindings.Add(bindings, 2);
  258. }
  259. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  260. struct UBO
  261. {
  262. DKMatrix4 projectionMatrix;
  263. DKMatrix4 modelMatrix;
  264. DKMatrix4 viewMatrix;
  265. };
  266. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(UBO), DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  267. UBO* ubo = nullptr;
  268. if (bindSet)
  269. {
  270. if (uboBuffer)
  271. {
  272. ubo = reinterpret_cast<UBO*>(uboBuffer->Contents());
  273. ubo->projectionMatrix = DKMatrix4::identity;
  274. ubo->modelMatrix = DKMatrix4::identity;
  275. ubo->viewMatrix = DKMatrix4::identity;
  276. uboBuffer->Flush();
  277. //DKAffineTransform3 trans;
  278. //trans.Multiply(DKLinearTransform3().Scale(0.5).Rotate(DKVector3(0,1,0), DKGL_PI * 0.5));
  279. //ubo.modelMatrix.Multiply(trans.Matrix4());
  280. //memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
  281. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(UBO));
  282. }
  283. bindSet->SetTexture(1, texture);
  284. bindSet->SetSamplerState(1, sampler);
  285. }
  286. DKObject<DKTexture> depthBuffer = nullptr;
  287. DKCamera camera;
  288. DKVector3 cameraPosition = { 0, 5, 10 };
  289. DKVector3 cameraTartget = { 0, 0, 0 };
  290. DKAffineTransform3 tm(DKLinearTransform3().Scale(5).Rotate(DKVector3(-1,0,0), DKGL_PI * 0.5));
  291. DKTimer timer;
  292. timer.Reset();
  293. DKLog("Render thread begin");
  294. while (!runningRenderThread.CompareAndSet(0, 0))
  295. {
  296. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  297. double t = timer.Elapsed();
  298. double waveT = (cos(t) + 1.0) * 0.5;
  299. rpd.colorAttachments.Value(0).clearColor = DKColor(waveT, 0.0, 0.0, 0.0);
  300. int width = rpd.colorAttachments.Value(0).renderTarget->Width();
  301. int height = rpd.colorAttachments.Value(0).renderTarget->Height();
  302. if (depthBuffer)
  303. {
  304. if (depthBuffer->Width() != width ||
  305. depthBuffer->Height() != height )
  306. depthBuffer = nullptr;
  307. }
  308. if (depthBuffer == nullptr)
  309. {
  310. // create depth buffer
  311. DKTextureDescriptor texDesc = {};
  312. texDesc.textureType = DKTexture::Type2D;
  313. texDesc.pixelFormat = DKPixelFormat::D32Float;
  314. texDesc.width = width;
  315. texDesc.height = height;
  316. texDesc.depth = 1;
  317. texDesc.mipmapLevels = 1;
  318. texDesc.sampleCount = 1;
  319. texDesc.arrayLength = 1;
  320. texDesc.usage = DKTexture::UsageRenderTarget;
  321. depthBuffer = device->CreateTexture(texDesc);
  322. }
  323. rpd.depthStencilAttachment.renderTarget = depthBuffer;
  324. rpd.depthStencilAttachment.loadAction = DKRenderPassAttachmentDescriptor::LoadActionClear;
  325. rpd.depthStencilAttachment.storeAction = DKRenderPassAttachmentDescriptor::StoreActionDontCare;
  326. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  327. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  328. if (encoder)
  329. {
  330. if (bindSet && ubo)
  331. {
  332. camera.SetView(cameraPosition, cameraTartget - cameraPosition, DKVector3(0, 1, 0));
  333. camera.SetPerspective(DKGL_DEGREE_TO_RADIAN(90), float(width)/float(height), 1, 1000);
  334. ubo->projectionMatrix = camera.ProjectionMatrix();
  335. ubo->viewMatrix = camera.ViewMatrix();
  336. DKQuaternion quat(DKVector3(0, 1, 0), t);
  337. DKAffineTransform3 trans = tm * DKAffineTransform3(quat);
  338. ubo->modelMatrix = trans.Matrix4();
  339. uboBuffer->Flush();
  340. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(UBO));
  341. }
  342. encoder->SetRenderPipelineState(pipelineState);
  343. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  344. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  345. encoder->SetResources(0, bindSet);
  346. // draw scene!
  347. encoder->DrawIndexed(SampleMesh->GetIndicesCount(), 1, 0, 0, 0);
  348. encoder->EndEncoding();
  349. buffer->Commit();
  350. swapChain->Present();
  351. }
  352. else
  353. {
  354. }
  355. DKThread::Sleep(0.01);
  356. }
  357. DKLog("RenderThread terminating...");
  358. }
  359. void OnInitialize(void) override
  360. {
  361. SampleApp::OnInitialize();
  362. DKLogD("%s", DKGL_FUNCTION_NAME);
  363. // create window
  364. window = DKWindow::Create("DefaultWindow");
  365. window->SetOrigin({ 0, 0 });
  366. window->Resize({ 320, 240 });
  367. window->Activate();
  368. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  369. {
  370. if (e.type == DKWindow::WindowEvent::WindowClosed)
  371. DKApplication::Instance()->Terminate(0);
  372. }), NULL, NULL);
  373. SampleMesh = DKOBJECT_NEW SampleObjMesh();
  374. LoadMesh();
  375. runningRenderThread = 1;
  376. renderThread = DKThread::Create(DKFunction(this, &MeshDemo::RenderThread)->Invocation());
  377. }
  378. void OnTerminate(void) override
  379. {
  380. DKLogD("%s", DKGL_FUNCTION_NAME);
  381. runningRenderThread = 0;
  382. renderThread->WaitTerminate();
  383. renderThread = NULL;
  384. window = NULL;
  385. SampleApp::OnTerminate();
  386. }
  387. };
  388. #ifdef _WIN32
  389. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  390. _In_opt_ HINSTANCE hPrevInstance,
  391. _In_ LPWSTR lpCmdLine,
  392. _In_ int nCmdShow)
  393. #else
  394. int main(int argc, const char * argv[])
  395. #endif
  396. {
  397. MeshDemo app;
  398. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  399. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  400. return app.Run();
  401. }