DKGL2 sample codes

Texture.cpp 10KB

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