DKGL2 sample codes

Texture.cpp 9.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. // create sampler
  62. DKSamplerDescriptor samplerDesc = {};
  63. DKObject<DKSamplerState> sampler = device->CreateSamplerState(samplerDesc);
  64. // create shaders
  65. DKObject<DKShaderModule> vertShaderModule = device->CreateShaderModule(&vertShader);
  66. DKObject<DKShaderModule> fragShaderModule = device->CreateShaderModule(&fragShader);
  67. DKObject<DKShaderFunction> vertShaderFunction = vertShaderModule->CreateFunction(vertShaderModule->FunctionNames().Value(0));
  68. DKObject<DKShaderFunction> fragShaderFunction = fragShaderModule->CreateFunction(fragShaderModule->FunctionNames().Value(0));
  69. DKObject<DKSwapChain> swapChain = queue->CreateSwapChain(window);
  70. DKLog("VertexFunction.VertexAttributes: %d", vertShaderFunction->StageInputAttributes().Count());
  71. for (int i = 0; i < vertShaderFunction->StageInputAttributes().Count(); ++i)
  72. {
  73. const DKShaderAttribute& attr = vertShaderFunction->StageInputAttributes().Value(i);
  74. DKLog(" --> VertexAttribute[%d]: \"%ls\" (location:%u)", i, (const wchar_t*)attr.name, attr.location);
  75. }
  76. struct Vertex
  77. {
  78. DKVector3 inPos;
  79. DKVector2 inUV;
  80. DKVector3 inNormal;
  81. };
  82. DKArray<Vertex> vertexData =
  83. {
  84. { { 1.0f, 1.0f, 0.0f }, { 1.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  85. { { -1.0f, 1.0f, 0.0f }, { 0.0f, 1.0f }, { 0.0f, 0.0f, 1.0f } },
  86. { { -1.0f, -1.0f, 0.0f }, { 0.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } },
  87. { { 1.0f, -1.0f, 0.0f }, { 1.0f, 0.0f }, { 0.0f, 0.0f, 1.0f } }
  88. };
  89. uint32_t vertexBufferSize = static_cast<uint32_t>(vertexData.Count()) * sizeof(Vertex);
  90. DKArray<uint32_t> indexData = { 0, 1, 2, 2, 3, 0 };
  91. uint32_t indexBufferSize = indexData.Count() * sizeof(uint32_t);
  92. DKObject<DKGpuBuffer> vertexBuffer = device->CreateBuffer(vertexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  93. memcpy(vertexBuffer->Contents(), vertexData, vertexBufferSize);
  94. vertexBuffer->Flush();
  95. DKObject<DKGpuBuffer> indexBuffer = device->CreateBuffer(indexBufferSize, DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  96. memcpy(indexBuffer->Contents(), indexData, indexBufferSize);
  97. indexBuffer->Flush();
  98. DKRenderPipelineDescriptor pipelineDescriptor;
  99. pipelineDescriptor.vertexFunction = vertShaderFunction;
  100. pipelineDescriptor.fragmentFunction = fragShaderFunction;
  101. pipelineDescriptor.colorAttachments.Resize(1);
  102. pipelineDescriptor.colorAttachments.Value(0).pixelFormat = swapChain->ColorPixelFormat();
  103. pipelineDescriptor.depthStencilAttachmentPixelFormat = DKPixelFormat::Invalid; // no depth buffer
  104. pipelineDescriptor.vertexDescriptor.attributes = {
  105. { DKVertexFormat::Float3, 0, 0, 0 },
  106. { DKVertexFormat::Float2, offsetof(Vertex, inUV), 0, 1 },
  107. { DKVertexFormat::Float3, offsetof(Vertex, inNormal), 0, 2 },
  108. };
  109. pipelineDescriptor.vertexDescriptor.layouts = {
  110. { DKVertexStepRate::Vertex, sizeof(Vertex), 0 },
  111. };
  112. pipelineDescriptor.primitiveTopology = DKPrimitiveType::Triangle;
  113. pipelineDescriptor.frontFace = DKFrontFace::CCW;
  114. pipelineDescriptor.triangleFillMode = DKTriangleFillMode::Fill;
  115. pipelineDescriptor.depthClipMode = DKDepthClipMode::Clip;
  116. pipelineDescriptor.cullMode = DKCullMode::None;
  117. pipelineDescriptor.rasterizationEnabled = true;
  118. DKPipelineReflection reflection;
  119. DKObject<DKRenderPipelineState> pipelineState = device->CreateRenderPipeline(pipelineDescriptor, &reflection);
  120. if (pipelineState)
  121. {
  122. PrintPipelineReflection(&reflection, DKLogCategory::Verbose);
  123. }
  124. DKShaderBindingSetLayout layout;
  125. if (1)
  126. {
  127. DKShaderBinding binding = {
  128. 0,
  129. DKShader::DescriptorTypeUniformBuffer,
  130. 1,
  131. nullptr
  132. };
  133. layout.bindings.Add(binding);
  134. }
  135. DKObject<DKShaderBindingSet> bindSet = device->CreateShaderBindingSet(layout);
  136. if (bindSet)
  137. {
  138. struct
  139. {
  140. DKMatrix4 projectionMatrix;
  141. DKMatrix4 modelMatrix;
  142. DKMatrix4 viewMatrix;
  143. } ubo;
  144. DKObject<DKGpuBuffer> uboBuffer = device->CreateBuffer(sizeof(ubo), DKGpuBuffer::StorageModeShared, DKCpuCacheModeReadWrite);
  145. if (uboBuffer)
  146. {
  147. ubo.projectionMatrix = DKMatrix4::identity;
  148. ubo.modelMatrix = DKMatrix4::identity;
  149. ubo.viewMatrix = DKMatrix4::identity;
  150. memcpy(uboBuffer->Contents(), &ubo, sizeof(ubo));
  151. bindSet->SetBuffer(0, uboBuffer, 0, sizeof(ubo));
  152. uboBuffer->Flush();
  153. }
  154. }
  155. DKTimer timer;
  156. timer.Reset();
  157. DKLog("Render thread begin");
  158. while (!runningRenderThread.CompareAndSet(0, 0))
  159. {
  160. DKRenderPassDescriptor rpd = swapChain->CurrentRenderPassDescriptor();
  161. double t = timer.Elapsed();
  162. t = (cos(t) + 1.0) * 0.5;
  163. rpd.colorAttachments.Value(0).clearColor = DKColor(t, 0.0, 0.0, 0.0);
  164. DKObject<DKCommandBuffer> buffer = queue->CreateCommandBuffer();
  165. DKObject<DKRenderCommandEncoder> encoder = buffer->CreateRenderCommandEncoder(rpd);
  166. if (encoder)
  167. {
  168. encoder->SetRenderPipelineState(pipelineState);
  169. encoder->SetVertexBuffer(vertexBuffer, 0, 0);
  170. encoder->SetIndexBuffer(indexBuffer, 0, DKIndexType::UInt32);
  171. encoder->SetResources(0, bindSet);
  172. // draw scene!
  173. encoder->DrawIndexed(indexData.Count(), 1, 0, 0, 0);
  174. encoder->EndEncoding();
  175. buffer->Commit();
  176. swapChain->Present();
  177. }
  178. else
  179. {
  180. }
  181. DKThread::Sleep(0.01);
  182. }
  183. DKLog("RenderThread terminating...");
  184. }
  185. void OnInitialize(void) override
  186. {
  187. SampleApp::OnInitialize();
  188. DKLogD("%s", DKGL_FUNCTION_NAME);
  189. // create window
  190. window = DKWindow::Create("DefaultWindow");
  191. window->SetOrigin({ 0, 0 });
  192. window->Resize({ 320, 240 });
  193. window->Activate();
  194. window->AddEventHandler(this, DKFunction([this](const DKWindow::WindowEvent& e)
  195. {
  196. if (e.type == DKWindow::WindowEvent::WindowClosed)
  197. DKApplication::Instance()->Terminate(0);
  198. }), NULL, NULL);
  199. runningRenderThread = 1;
  200. renderThread = DKThread::Create(DKFunction(this, &TextureDemo::RenderThread)->Invocation());
  201. }
  202. void OnTerminate(void) override
  203. {
  204. DKLogD("%s", DKGL_FUNCTION_NAME);
  205. runningRenderThread = 0;
  206. renderThread->WaitTerminate();
  207. renderThread = NULL;
  208. window = NULL;
  209. SampleApp::OnTerminate();
  210. }
  211. };
  212. #ifdef _WIN32
  213. int APIENTRY wWinMain(_In_ HINSTANCE hInstance,
  214. _In_opt_ HINSTANCE hPrevInstance,
  215. _In_ LPWSTR lpCmdLine,
  216. _In_ int nCmdShow)
  217. #else
  218. int main(int argc, const char * argv[])
  219. #endif
  220. {
  221. TextureDemo app;
  222. DKPropertySet::SystemConfig().SetValue("AppDelegate", "AppDelegate");
  223. DKPropertySet::SystemConfig().SetValue("GraphicsAPI", "Vulkan");
  224. return app.Run();
  225. }