DKGL2 sample codes

Texture.cpp 9.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. #include <cstddef>
  2. #include "app.h"
  3. #include "util.h"
  4. class TextureDemo : public SampleApp
  5. {
  6. DKObject<DKWindow> window;
  7. DKObject<DKThread> renderThread;
  8. DKAtomicNumber32 runningRenderThread;
  9. public:
  10. DKObject<DKTexture> LoadTexture2D(DKCommandQueue* queue, DKData* data)
  11. {
  12. DKObject<DKImage> image = DKImage::Create(data);
  13. if (image)
  14. {
  15. DKGraphicsDevice* device = queue->Device();
  16. DKTextureDescriptor texDesc = {};
  17. texDesc.textureType = DKTexture::Type2D;
  18. texDesc.pixelFormat = DKPixelFormat::RGBA8Unorm;
  19. texDesc.width = image->Width();
  20. texDesc.height = image->Height();
  21. texDesc.depth = 1;
  22. texDesc.mipmapLevels = 1;
  23. texDesc.sampleCount = 1;
  24. texDesc.arrayLength = 1;
  25. texDesc.usage = DKTexture::UsageCopyDestination | DKTexture::UsageSampled;
  26. DKObject<DKTexture> tex = device->CreateTexture(texDesc);
  27. if (tex)
  28. {
  29. size_t bytesPerPixel = image->BytesPerPixel();
  30. uint32_t width = image->Width();
  31. uint32_t height = image->Height();
  32. size_t bufferLength = bytesPerPixel * width * height;
  33. DKObject<DKGpuBuffer> stagingBuffer = device->CreateBuffer(bufferLength, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  34. memcpy(stagingBuffer->Contents(), image->Contents(), bufferLength);
  35. stagingBuffer->Flush();
  36. DKObject<DKCommandBuffer> cb = queue->CreateCommandBuffer();
  37. DKObject<DKCopyCommandEncoder> encoder = cb->CreateCopyCommandEncoder();
  38. encoder->CopyFromBufferToTexture(stagingBuffer,
  39. { 0, width, height },
  40. tex,
  41. { 0,0, 0,0,0 },
  42. { width,height,1 });
  43. encoder->EndEncoding();
  44. cb->Commit();
  45. DKLog("Texture created!");
  46. return tex;
  47. }
  48. }
  49. return nullptr;
  50. }
  51. void RenderThread(void)
  52. {
  53. DKObject<DKData> vertData = resourcePool.LoadResourceData("shaders/texture.vert.spv");
  54. DKObject<DKData> fragData = resourcePool.LoadResourceData("shaders/texture.frag.spv");
  55. DKShader vertShader(vertData);
  56. DKShader fragShader(fragData);
  57. DKObject<DKGraphicsDevice> device = DKGraphicsDevice::SharedInstance();
  58. DKObject<DKCommandQueue> queue = device->CreateCommandQueue(DKCommandQueue::Graphics);
  59. // create texture
  60. DKObject<DKTexture> texture = LoadTexture2D(queue, resourcePool.LoadResourceData("textures/deathstar3.png"));
  61. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  62. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  63. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  64. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  65. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  66. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  67. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  68. {
  69. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  70. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  71. }
  72. struct Vertex
  73. {
  74. DKVector3 inPos;
  75. DKVector2 inUV;
  76. DKVector3 inNormal;
  77. };
  78. DKArray<Vertex> vertexData =
  79. {
  80. { { 1.0f, 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  81. { { -1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  82. { { -1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } },
  83. { { 1.0f, -1.0f, 0.0f }, { 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }
  84. };
  85. uint32_t vertexBufferSize = static_cast<uint32_t>(vertexData.Count()) * sizeof(Vertex);
  86. DKArray<uint32_t> indexData = { 0, 1, 2, 2, 3, 0 };
  87. uint32_t indexBufferSize = indexData.Count() * sizeof(uint32_t);
  88. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  89. memcpy(vertexBuffer->Contents(), vertexData, vertexBufferSize);
  90. vertexBuffer->Flush();
  91. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  92. memcpy(indexBuffer->Contents(), indexData, indexBufferSize);
  93. indexBuffer->Flush();
  94. DKRenderPipelineDescriptor pipelineDescriptor;
  95. pipelineDescriptor.vertexFunction = vertShaderFunction;
  96. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  97. pipelineDescriptor.colorAttachments.Resize(1);
  98. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  99. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::Invalid; // no depth buffer
  100. pipelineDescriptor.vertexDescriptor.attributes = {
  101. { DKVertexFormat::Float3, 0, 0, 0 },
  102. { DKVertexFormat::Float2, offsetof(Vertex, inUV), 0, 1 },
  103. { DKVertexFormat::Float3, offsetof(Vertex, inNormal), 0, 2 },
  104. };
  105. pipelineDescriptor.vertexDescriptor.layouts = {
  106. { DKVertexStepRate::Vertex, sizeof(Vertex), 0 },
  107. };
  108. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  109. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  110. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  111. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  112. pipelineDescriptor.cullMode = DKCullMode::None;
  113. pipelineDescriptor.rasterizationEnabled = true;
  114. DKPipelineReflection reflection;
  115. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  116. if (pipelineState)
  117. {
  118. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  119. }
  120. DKShaderBindingSetLayout layout;
  121. if (1)
  122. {
  123. DKShaderBinding binding = {
  124. 0,
  125. DKShader::DescriptorTypeUniformBuffer,
  126. 1,
  127. nullptr
  128. };
  129. layout.bindings.Add(binding);
  130. }
  131. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  132. if (bindSet)
  133. {
  134. struct
  135. {
  136. DKMatrix4 projectionMatrix;
  137. DKMatrix4 modelMatrix;
  138. DKMatrix4 viewMatrix;
  139. } ubo;
  140. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(ubo), DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  141. if (uboBuffer)
  142. {
  143. ubo.projectionMatrix = DKMatrix4::identity;
  144. ubo.modelMatrix = DKMatrix4::identity;
  145. ubo.viewMatrix = DKMatrix4::identity;
  146. memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
  147. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(ubo));
  148. uboBuffer->Flush();
  149. }
  150. }
  151. DKTimer timer;
  152. timer.Reset();
  153. DKLog("Render thread begin");
  154. while (!runningRenderThread.CompareAndSet(0, 0))
  155. {
  156. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  157. double t = timer.Elapsed();
  158. t = (cos(t) + 1.0) * 0.5;
  159. rpd.colorAttachments.Value(0).clearColor = DKColor(t, 0.0, 0.0, 0.0);
  160. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  161. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  162. if (encoder)
  163. {
  164. encoder->SetRenderPipelineState(pipelineState);
  165. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  166. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  167. encoder->SetResources(0, bindSet);
  168. // draw scene!
  169. encoder->DrawIndexed(indexData.Count(), 1, 0, 0, 0);
  170. encoder->EndEncoding();
  171. buffer->Commit();
  172. swapChain->Present();
  173. }
  174. else
  175. {
  176. }
  177. DKThread::Sleep(0.01);
  178. }
  179. DKLog("RenderThread terminating...");
  180. }
  181. void OnInitialize(void) override
  182. {
  183. SampleApp::OnInitialize();
  184. DKLogD("%s", DKGL_FUNCTION_NAME);
  185. // create window
  186. window = DKWindow::Create("DefaultWindow");
  187. window->SetOrigin({ 0, 0 });
  188. window->Resize({ 320, 240 });
  189. window->Activate();
  190. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  191. {
  192. if (e.type == DKWindow::WindowEvent::WindowClosed)
  193. DKApplication::Instance()->Terminate(0);
  194. }), NULL, NULL);
  195. runningRenderThread = 1;
  196. renderThread = DKThread::Create(DKFunction(this, &TextureDemo::RenderThread)->Invocation());
  197. }
  198. void OnTerminate(void) override
  199. {
  200. DKLogD("%s", DKGL_FUNCTION_NAME);
  201. runningRenderThread = 0;
  202. renderThread->WaitTerminate();
  203. renderThread = NULL;
  204. window = NULL;
  205. SampleApp::OnTerminate();
  206. }
  207. };
  208. #ifdef _WIN32
  209. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  210. _In_opt_ HINSTANCE hPrevInstance,
  211. _In_ LPWSTR lpCmdLine,
  212. _In_ int nCmdShow)
  213. #else
  214. int main(int argc, const char * argv[])
  215. #endif
  216. {
  217. TextureDemo app;
  218. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  219. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  220. return app.Run();
  221. }