Graphics.cpp 57 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524
  1. #include "Graphics.h"
  2. #include "Buffer.h"
  3. #include "SDL_vulkan.h"
  4. #include "window/Window.h"
  5. #include "common/Exception.h"
  6. #include "Shader.h"
  7. #include "graphics/Texture.h"
  8. #include "Vulkan.h"
  9. #include "common/version.h"
  10. #include <vector>
  11. #include <cstring>
  12. #include <set>
  13. #include <fstream>
  14. #include <iostream>
  15. #include <array>
  16. namespace love {
  17. namespace graphics {
  18. namespace vulkan {
  19. static VkIndexType getVulkanIndexBufferType(IndexDataType type) {
  20. switch (type) {
  21. case INDEX_UINT16: return VK_INDEX_TYPE_UINT16;
  22. case INDEX_UINT32: return VK_INDEX_TYPE_UINT32;
  23. default:
  24. throw love::Exception("unknown Index Data type");
  25. }
  26. }
  27. const std::vector<const char*> validationLayers = {
  28. "VK_LAYER_KHRONOS_validation"
  29. };
  30. const std::vector<const char*> deviceExtensions = {
  31. VK_KHR_SWAPCHAIN_EXTENSION_NAME
  32. };
  33. #ifdef NDEBUG
  34. const bool enableValidationLayers = false;
  35. #else
  36. const bool enableValidationLayers = true;
  37. #endif
  38. const int MAX_FRAMES_IN_FLIGHT = 2;
  39. const char* Graphics::getName() const {
  40. return "love.graphics.vulkan";
  41. }
  42. Graphics::Graphics() {
  43. }
  44. Graphics::~Graphics() {
  45. // FIXME: most resources that are allocated dynamically need proper cleanup.
  46. batchedDrawState.vb[0] = nullptr;
  47. batchedDrawState.vb[1] = nullptr;
  48. batchedDrawState.indexBuffer = nullptr;
  49. }
  50. // START OVERRIDEN FUNCTIONS
  51. love::graphics::Buffer* Graphics::newBuffer(const love::graphics::Buffer::Settings& settings, const std::vector<love::graphics::Buffer::DataDeclaration>& format, const void* data, size_t size, size_t arraylength) {
  52. std::cout << "newBuffer ";
  53. return new Buffer(vmaAllocator, this, settings, format, data, size, arraylength);
  54. }
  55. void Graphics::startRecordingGraphicsCommands() {
  56. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  57. while (true) {
  58. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  59. if (result == VK_ERROR_OUT_OF_DATE_KHR) {
  60. recreateSwapChain();
  61. continue;
  62. }
  63. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
  64. throw love::Exception("failed to acquire swap chain image");
  65. }
  66. break;
  67. }
  68. VkCommandBufferBeginInfo beginInfo{};
  69. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  70. beginInfo.flags = 0;
  71. beginInfo.pInheritanceInfo = nullptr;
  72. std::cout << "beginCommandBuffer(imageIndex=" << imageIndex << ") ";
  73. if (vkBeginCommandBuffer(commandBuffers.at(imageIndex), &beginInfo) != VK_SUCCESS) {
  74. throw love::Exception("failed to begin recording command buffer");
  75. }
  76. VkRenderPassBeginInfo renderPassInfo{};
  77. renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  78. renderPassInfo.renderPass = renderPass;
  79. renderPassInfo.framebuffer = swapChainFramBuffers.at(imageIndex);
  80. renderPassInfo.renderArea.offset = { 0, 0 };
  81. renderPassInfo.renderArea.extent = swapChainExtent;
  82. renderPassInfo.clearValueCount = 1;
  83. renderPassInfo.pClearValues = &clearColor;
  84. const auto& commandBuffer = commandBuffers.at(imageIndex);
  85. vkCmdBeginRenderPass(commandBuffers.at(imageIndex), &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
  86. currentGraphicsPipeline = VK_NULL_HANDLE;
  87. }
  88. void Graphics::endRecordingGraphicsCommands() {
  89. const auto& commandBuffer = commandBuffers.at(imageIndex);
  90. std::cout << "endCommandBuffer(imageIndex=" << imageIndex << ") ";
  91. vkCmdEndRenderPass(commandBuffers.at(imageIndex));
  92. if (vkEndCommandBuffer(commandBuffers.at(imageIndex)) != VK_SUCCESS) {
  93. throw love::Exception("failed to record command buffer");
  94. }
  95. }
  96. void Graphics::present(void* screenshotCallbackdata) {
  97. flushBatchedDraws();
  98. endRecordingGraphicsCommands();
  99. if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
  100. vkWaitForFences(device, 1, &imagesInFlight.at(imageIndex), VK_TRUE, UINT64_MAX);
  101. }
  102. imagesInFlight[imageIndex] = inFlightFences[currentFrame];
  103. VkSubmitInfo submitInfo{};
  104. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  105. VkSemaphore waitSemaphores[] = { imageAvailableSemaphores.at(currentFrame) };
  106. VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
  107. submitInfo.waitSemaphoreCount = 1;
  108. submitInfo.pWaitSemaphores = waitSemaphores;
  109. submitInfo.pWaitDstStageMask = waitStages;
  110. submitInfo.commandBufferCount = 1;
  111. submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
  112. VkSemaphore signalSemaphores[] = { renderFinishedSemaphores.at(currentFrame) };
  113. submitInfo.signalSemaphoreCount = 1;
  114. submitInfo.pSignalSemaphores = signalSemaphores;
  115. vkResetFences(device, 1, &inFlightFences[currentFrame]);
  116. if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences.at(currentFrame)) != VK_SUCCESS) {
  117. throw love::Exception("failed to submit draw command buffer");
  118. }
  119. VkPresentInfoKHR presentInfo{};
  120. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  121. presentInfo.waitSemaphoreCount = 1;
  122. presentInfo.pWaitSemaphores = signalSemaphores;
  123. VkSwapchainKHR swapChains[] = { swapChain };
  124. presentInfo.swapchainCount = 1;
  125. presentInfo.pSwapchains = swapChains;
  126. presentInfo.pImageIndices = &imageIndex;
  127. VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
  128. if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
  129. framebufferResized = false;
  130. recreateSwapChain();
  131. }
  132. else if (result != VK_SUCCESS) {
  133. throw love::Exception("failed to present swap chain image");
  134. }
  135. std::cout << "present" << std::endl;
  136. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  137. updatedBatchedDrawBuffers();
  138. startRecordingGraphicsCommands();
  139. }
  140. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight) {
  141. std::cout << "setViewPortSize ";
  142. this->width = width;
  143. this->height = height;
  144. this->pixelWidth = pixelwidth;
  145. this->pixelHeight = pixelheight;
  146. resetProjection();
  147. recreateSwapChain();
  148. }
  149. bool Graphics::setMode(void* context, int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa) {
  150. std::cout << "setMode ";
  151. createVulkanInstance();
  152. createSurface();
  153. pickPhysicalDevice();
  154. createLogicalDevice();
  155. initVMA();
  156. initCapabilities();
  157. createSwapChain();
  158. createImageViews();
  159. createRenderPass();
  160. createDefaultShaders();
  161. createDescriptorSetLayout();
  162. createFramebuffers();
  163. createCommandPool();
  164. createCommandBuffers();
  165. createDefaultTexture();
  166. createQuadIndexBuffer();
  167. createDescriptorPool();
  168. createSyncObjects();
  169. startRecordingGraphicsCommands();
  170. currentFrame = 0;
  171. created = true;
  172. float whiteColor[] = { 1.0f, 1.0f, 1.0f, 1.0f };
  173. batchedDrawBuffers.clear();
  174. batchedDrawBuffers.reserve(MAX_FRAMES_IN_FLIGHT);
  175. for (int i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  176. batchedDrawBuffers.emplace_back();
  177. // Initial sizes that should be good enough for most cases. It will
  178. // resize to fit if needed, later.
  179. batchedDrawBuffers[i].vertexBuffer1 = new StreamBuffer(vmaAllocator, BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  180. batchedDrawBuffers[i].vertexBuffer2 = new StreamBuffer(vmaAllocator, BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  181. batchedDrawBuffers[i].indexBuffer = new StreamBuffer(vmaAllocator, BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  182. // sometimes the VertexColor is not set, so we manually adjust it to white color
  183. batchedDrawBuffers[i].constantColorBuffer = new StreamBuffer(vmaAllocator, BUFFERUSAGE_VERTEX, sizeof(whiteColor));
  184. auto mapInfo = batchedDrawBuffers[i].constantColorBuffer->map(sizeof(whiteColor));
  185. memcpy(mapInfo.data, whiteColor, sizeof(whiteColor));
  186. batchedDrawBuffers[i].constantColorBuffer->unmap(sizeof(whiteColor));
  187. batchedDrawBuffers[i].constantColorBuffer->markUsed(sizeof(whiteColor));
  188. }
  189. updatedBatchedDrawBuffers();
  190. return true;
  191. }
  192. void Graphics::initCapabilities() {
  193. std::cout << "initCapabilities ";
  194. // todo
  195. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = false;
  196. capabilities.features[FEATURE_CLAMP_ZERO] = false;
  197. capabilities.features[FEATURE_CLAMP_ONE] = false;
  198. capabilities.features[FEATURE_BLEND_MINMAX] = false;
  199. capabilities.features[FEATURE_LIGHTEN] = false;
  200. capabilities.features[FEATURE_FULL_NPOT] = false;
  201. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = false;
  202. capabilities.features[FEATURE_SHADER_DERIVATIVES] = false;
  203. capabilities.features[FEATURE_GLSL3] = false;
  204. capabilities.features[FEATURE_GLSL4] = false;
  205. capabilities.features[FEATURE_INSTANCING] = false;
  206. capabilities.features[FEATURE_TEXEL_BUFFER] = false;
  207. capabilities.features[FEATURE_INDEX_BUFFER_32BIT] = true;
  208. capabilities.features[FEATURE_COPY_BUFFER] = false;
  209. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = false;
  210. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = false;
  211. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = false;
  212. static_assert(FEATURE_MAX_ENUM == 17, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  213. VkPhysicalDeviceProperties properties;
  214. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  215. capabilities.limits[LIMIT_POINT_SIZE] = properties.limits.pointSizeRange[1];
  216. capabilities.limits[LIMIT_TEXTURE_SIZE] = properties.limits.maxImageDimension2D;
  217. capabilities.limits[LIMIT_TEXTURE_LAYERS] = properties.limits.maxImageArrayLayers;
  218. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = properties.limits.maxImageDimension3D;
  219. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = properties.limits.maxImageDimensionCube;
  220. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = properties.limits.maxTexelBufferElements; // ?
  221. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = properties.limits.maxStorageBufferRange; // ?
  222. capabilities.limits[LIMIT_THREADGROUPS_X] = 0; // todo
  223. capabilities.limits[LIMIT_THREADGROUPS_Y] = 0; // todo
  224. capabilities.limits[LIMIT_THREADGROUPS_Z] = 0; // todo
  225. capabilities.limits[LIMIT_RENDER_TARGETS] = 1; // todo
  226. capabilities.limits[LIMIT_TEXTURE_MSAA] = 1; // todo
  227. capabilities.limits[LIMIT_ANISOTROPY] = 1.0f; // todo
  228. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  229. capabilities.textureTypes[TEXTURE_2D] = true;
  230. capabilities.textureTypes[TEXTURE_VOLUME] = false;
  231. capabilities.textureTypes[TEXTURE_2D_ARRAY] = false;
  232. capabilities.textureTypes[TEXTURE_CUBE] = false;
  233. }
  234. void Graphics::unSetMode() {
  235. std::cout << "unSetMode ";
  236. created = false;
  237. cleanup();
  238. }
  239. void Graphics::draw(const DrawIndexedCommand& cmd) {
  240. std::cout << "drawIndexed ";
  241. std::vector<VkBuffer> buffers;
  242. std::vector<VkDeviceSize> offsets;
  243. bool useConstantColorBuffer;
  244. GraphicsPipelineConfiguration configuration;
  245. createVulkanVertexFormat(*cmd.attributes, useConstantColorBuffer, configuration);
  246. for (uint32_t i = 0; i < 2; i++) {
  247. if (cmd.buffers->useBits & (1u << i)) {
  248. buffers.push_back((VkBuffer)cmd.buffers->info[i].buffer->getHandle());
  249. offsets.push_back((VkDeviceSize)cmd.buffers->info[i].offset);
  250. }
  251. else {
  252. buffers.push_back(VK_NULL_HANDLE);
  253. offsets.push_back(0);
  254. }
  255. }
  256. if (useConstantColorBuffer) {
  257. buffers.push_back((VkBuffer)batchedDrawBuffers[currentFrame].constantColorBuffer->getHandle());
  258. offsets.push_back((VkDeviceSize)0);
  259. }
  260. if (cmd.texture == nullptr) {
  261. setTexture(standardTexture);
  262. }
  263. else {
  264. setTexture(cmd.texture);
  265. }
  266. ensureGraphicsPipelineConfiguration(configuration);
  267. auto descriptorSets = getDescriptorSet(currentFrame);
  268. auto descriptorSet = *descriptorSets;
  269. vkCmdBindDescriptorSets(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, descriptorSets, 0, nullptr);
  270. vkCmdBindVertexBuffers(commandBuffers.at(imageIndex), 0, buffers.size(), buffers.data(), offsets.data());
  271. vkCmdBindIndexBuffer(commandBuffers.at(imageIndex), (VkBuffer)cmd.indexBuffer->getHandle(), 0, getVulkanIndexBufferType(cmd.indexType));
  272. vkCmdDrawIndexed(commandBuffers.at(imageIndex), static_cast<uint32_t>(cmd.indexCount), 1, 0, 0, 0);
  273. }
  274. PixelFormat Graphics::getSizedFormat(PixelFormat format, bool rendertarget, bool readable) const {
  275. std::cout << "getSizedFormat ";
  276. switch (format) {
  277. PIXELFORMAT_NORMAL:
  278. if (isGammaCorrect()) {
  279. return PIXELFORMAT_RGBA8_UNORM_sRGB;
  280. }
  281. else {
  282. return PIXELFORMAT_RGBA8_UNORM;
  283. }
  284. case PIXELFORMAT_HDR:
  285. return PIXELFORMAT_RGBA16_FLOAT;
  286. default:
  287. return format;
  288. }
  289. }
  290. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage, bool sRGB) {
  291. std::cout << "isPixelFormatSupported ";
  292. switch (format) {
  293. case PIXELFORMAT_LA8_UNORM:
  294. return false;
  295. default:
  296. return true;
  297. }
  298. }
  299. void Graphics::drawQuads(int start, int count, const VertexAttributes& attributes, const BufferBindings& buffers, graphics::Texture* texture) {
  300. std::cout << "drawQuads ";
  301. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  302. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  303. std::vector<VkBuffer> bufferVector;
  304. std::vector<VkDeviceSize> offsets;
  305. bool useConstantColorBuffer;
  306. GraphicsPipelineConfiguration configuration;
  307. createVulkanVertexFormat(attributes, useConstantColorBuffer, configuration);
  308. for (uint32_t i = 0; i < 2; i++) {
  309. if (buffers.useBits & (1u << i)) {
  310. bufferVector.push_back((VkBuffer)buffers.info[i].buffer->getHandle());
  311. offsets.push_back((VkDeviceSize)buffers.info[i].offset);
  312. }
  313. else {
  314. if (useConstantColorBuffer) {
  315. bufferVector.push_back(VK_NULL_HANDLE);
  316. offsets.push_back(0);
  317. }
  318. }
  319. }
  320. if (useConstantColorBuffer) {
  321. bufferVector.push_back((VkBuffer)batchedDrawBuffers[currentFrame].constantColorBuffer->getHandle());
  322. offsets.push_back((VkDeviceSize)0);
  323. }
  324. if (texture == nullptr) {
  325. setTexture(standardTexture);
  326. }
  327. else {
  328. setTexture(texture);
  329. }
  330. ensureGraphicsPipelineConfiguration(configuration);
  331. vkCmdBindDescriptorSets(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, pipelineLayout, 0, 1, getDescriptorSet(currentFrame), 0, nullptr);
  332. vkCmdBindIndexBuffer(commandBuffers.at(imageIndex), (VkBuffer)quadIndexBuffer->getHandle(), 0, getVulkanIndexBufferType(INDEX_UINT16));
  333. vkCmdBindVertexBuffers(commandBuffers.at(imageIndex), 0, bufferVector.size(), bufferVector.data(), offsets.data());
  334. vkCmdDrawIndexed(commandBuffers.at(imageIndex), static_cast<uint32_t>(count * 6), 1, 0, 0, 0);
  335. int baseVertex = start * 4;
  336. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW) {
  337. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  338. // vkCmdDrawIndexed(commandBuffers.at(imageIndex), static_cast<uint32_t>(quadcount * 6), 1, 0, baseVertex, 0);
  339. baseVertex += quadcount * 4;
  340. }
  341. }
  342. graphics::StreamBuffer* Graphics::newStreamBuffer(BufferUsage type, size_t size) {
  343. std::cout << "newStreamBuffer ";
  344. return new StreamBuffer(vmaAllocator, type, size);
  345. }
  346. Matrix4 Graphics::computeDeviceProjection(const Matrix4& projection, bool rendertotexture) const {
  347. uint32 flags = DEVICE_PROJECTION_DEFAULT;
  348. return calculateDeviceProjection(projection, 0);
  349. }
  350. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  351. void Graphics::updatedBatchedDrawBuffers() {
  352. batchedDrawState.vb[0] = batchedDrawBuffers[currentFrame].vertexBuffer1;
  353. batchedDrawState.vb[0]->nextFrame();
  354. batchedDrawState.vb[1] = batchedDrawBuffers[currentFrame].vertexBuffer2;
  355. batchedDrawState.vb[1]->nextFrame();
  356. batchedDrawState.indexBuffer = batchedDrawBuffers[currentFrame].indexBuffer;
  357. batchedDrawState.indexBuffer->nextFrame();
  358. }
  359. VkDescriptorSet* Graphics::getDescriptorSet(int currentFrame) {
  360. DecriptorSetConfiguration config;
  361. config.texture = currentTexture;
  362. config.buffer = getUniformBuffer();
  363. for (auto i = 0; i < descriptorSetsMap.size(); i++) {
  364. if (descriptorSetsMap[i].first == config) {
  365. return &descriptorSetsMap[i].second[currentFrame];
  366. }
  367. }
  368. auto descriptorSets = createDescriptorSets(config);
  369. descriptorSetsMap.push_back(std::make_pair(config, descriptorSets));
  370. return &descriptorSetsMap.back().second[currentFrame];
  371. }
  372. graphics::StreamBuffer* Graphics::getUniformBuffer() {
  373. auto data = getCurrentBuiltinUniformData();
  374. for (auto it : uniformBufferMap) {
  375. if (it.first == data) {
  376. return it.second;
  377. }
  378. }
  379. auto buffer = createUniformBufferFromData(data);
  380. uniformBufferMap.push_back(std::make_pair(data, buffer));
  381. return buffer;
  382. }
  383. VkCommandBuffer Graphics::beginSingleTimeCommands() {
  384. VkCommandBufferAllocateInfo allocInfo{};
  385. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  386. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  387. allocInfo.commandPool = commandPool;
  388. allocInfo.commandBufferCount = 1;
  389. VkCommandBuffer commandBuffer;
  390. vkAllocateCommandBuffers(device, &allocInfo, &commandBuffer);
  391. VkCommandBufferBeginInfo beginInfo{};
  392. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  393. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  394. vkBeginCommandBuffer(commandBuffer, &beginInfo);
  395. return commandBuffer;
  396. }
  397. void Graphics::endSingleTimeCommands(VkCommandBuffer commandBuffer) {
  398. vkEndCommandBuffer(commandBuffer);
  399. VkSubmitInfo submitInfo{};
  400. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  401. submitInfo.commandBufferCount = 1;
  402. submitInfo.pCommandBuffers = &commandBuffer;
  403. vkQueueSubmit(graphicsQueue, 1, &submitInfo, VK_NULL_HANDLE);
  404. vkQueueWaitIdle(graphicsQueue);
  405. vkFreeCommandBuffers(device, commandPool, 1, &commandBuffer);
  406. }
  407. graphics::Shader::BuiltinUniformData Graphics::getCurrentBuiltinUniformData() {
  408. love::graphics::Shader::BuiltinUniformData data;
  409. data.transformMatrix = getTransform();
  410. data.projectionMatrix = getDeviceProjection();
  411. // The normal matrix is the transpose of the inverse of the rotation portion
  412. // (top-left 3x3) of the transform matrix.
  413. {
  414. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  415. const float* e = normalmatrix.getElements();
  416. for (int i = 0; i < 3; i++)
  417. {
  418. data.normalMatrix[i].x = e[i * 3 + 0];
  419. data.normalMatrix[i].y = e[i * 3 + 1];
  420. data.normalMatrix[i].z = e[i * 3 + 2];
  421. data.normalMatrix[i].w = 0.0f;
  422. }
  423. }
  424. // Store DPI scale in an unused component of another vector.
  425. data.normalMatrix[0].w = (float)getCurrentDPIScale();
  426. // Same with point size.
  427. data.normalMatrix[1].w = getPointSize();
  428. data.screenSizeParams.x = swapChainExtent.width;
  429. data.screenSizeParams.y = swapChainExtent.height;
  430. data.screenSizeParams.z = 1.0f;
  431. data.screenSizeParams.w = 0.0f;
  432. data.constantColor = getColor();
  433. gammaCorrectColor(data.constantColor);
  434. return data;
  435. }
  436. graphics::StreamBuffer* Graphics::createUniformBufferFromData(graphics::Shader::BuiltinUniformData data) {
  437. auto buffer = newStreamBuffer(BUFFERUSAGE_UNIFORM, sizeof(data));
  438. auto mappedInfo = buffer->map(0);
  439. memcpy(mappedInfo.data, &data, sizeof(data));
  440. buffer->unmap(0);
  441. return buffer;
  442. }
  443. void Graphics::createVulkanInstance() {
  444. if (enableValidationLayers && !checkValidationSupport()) {
  445. throw love::Exception("validation layers requested, but not available");
  446. }
  447. VkApplicationInfo appInfo{};
  448. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  449. appInfo.pApplicationName = "LOVE";
  450. appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); //todo, get this version from somewhere else?
  451. appInfo.pEngineName = "LOVE Engine";
  452. appInfo.engineVersion = VK_MAKE_VERSION(VERSION_MAJOR, VERSION_MINOR, VERSION_REV);
  453. appInfo.apiVersion = VK_API_VERSION_1_0;
  454. VkInstanceCreateInfo createInfo{};
  455. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  456. createInfo.pApplicationInfo = &appInfo;
  457. createInfo.pNext = nullptr;
  458. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  459. const void* handle = window->getHandle();
  460. unsigned int count;
  461. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, nullptr) != SDL_TRUE) {
  462. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  463. }
  464. std::vector<const char*> extensions = {}; // can add more here
  465. size_t addition_extension_count = extensions.size();
  466. extensions.resize(addition_extension_count + count);
  467. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, extensions.data() + addition_extension_count) != SDL_TRUE) {
  468. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  469. }
  470. createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
  471. createInfo.ppEnabledExtensionNames = extensions.data();
  472. if (enableValidationLayers) {
  473. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  474. createInfo.ppEnabledLayerNames = validationLayers.data();
  475. }
  476. else {
  477. createInfo.enabledLayerCount = 0;
  478. createInfo.ppEnabledLayerNames = nullptr;
  479. }
  480. if (vkCreateInstance(
  481. &createInfo,
  482. nullptr,
  483. &instance) != VK_SUCCESS) {
  484. throw love::Exception("couldn't create vulkan instance");
  485. }
  486. }
  487. bool Graphics::checkValidationSupport() {
  488. uint32_t layerCount;
  489. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  490. std::vector<VkLayerProperties> availableLayers(layerCount);
  491. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  492. for (const char* layerName : validationLayers) {
  493. bool layerFound = false;
  494. for (const auto& layerProperties : availableLayers) {
  495. if (strcmp(layerName, layerProperties.layerName) == 0) {
  496. layerFound = true;
  497. break;
  498. }
  499. }
  500. if (!layerFound) {
  501. return false;
  502. }
  503. }
  504. return true;
  505. }
  506. void Graphics::pickPhysicalDevice() {
  507. uint32_t deviceCount = 0;
  508. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  509. if (deviceCount == 0) {
  510. throw love::Exception("failed to find GPUs with Vulkan support");
  511. }
  512. std::vector<VkPhysicalDevice> devices(deviceCount);
  513. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  514. std::multimap<int, VkPhysicalDevice> candidates;
  515. for (const auto& device : devices) {
  516. int score = rateDeviceSuitability(device);
  517. candidates.insert(std::make_pair(score, device));
  518. }
  519. if (candidates.rbegin()->first > 0) {
  520. physicalDevice = candidates.rbegin()->second;
  521. }
  522. else {
  523. throw love::Exception("failed to find a suitable gpu");
  524. }
  525. }
  526. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device) {
  527. uint32_t extensionCount;
  528. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  529. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  530. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  531. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  532. for (const auto& extension : availableExtensions) {
  533. requiredExtensions.erase(extension.extensionName);
  534. }
  535. return requiredExtensions.empty();
  536. }
  537. // if the score is nonzero then the device is suitable.
  538. // A higher rating means generally better performance
  539. // if the score is 0 the device is unsuitable
  540. int Graphics::rateDeviceSuitability(VkPhysicalDevice device) {
  541. VkPhysicalDeviceProperties deviceProperties;
  542. VkPhysicalDeviceFeatures deviceFeatures;
  543. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  544. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  545. int score = 1;
  546. // optional
  547. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
  548. score += 1000;
  549. }
  550. // definitely needed
  551. QueueFamilyIndices indices = findQueueFamilies(device);
  552. if (!indices.isComplete()) {
  553. score = 0;
  554. }
  555. bool extensionsSupported = checkDeviceExtensionSupport(device);
  556. if (!extensionsSupported) {
  557. score = 0;
  558. }
  559. if (extensionsSupported) {
  560. auto swapChainSupport = querySwapChainSupport(device);
  561. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  562. if (!swapChainAdequate) {
  563. score = 0;
  564. }
  565. }
  566. if (!deviceFeatures.samplerAnisotropy) {
  567. score = 0;
  568. }
  569. return score;
  570. }
  571. Graphics::QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device) {
  572. QueueFamilyIndices indices;
  573. uint32_t queueFamilyCount = 0;
  574. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  575. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  576. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  577. int i = 0;
  578. for (const auto& queueFamily : queueFamilies) {
  579. if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
  580. indices.graphicsFamily = i;
  581. }
  582. VkBool32 presentSupport = false;
  583. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  584. if (presentSupport) {
  585. indices.presentFamily = i;
  586. }
  587. if (indices.isComplete()) {
  588. break;
  589. }
  590. i++;
  591. }
  592. return indices;
  593. }
  594. void Graphics::createLogicalDevice() {
  595. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  596. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  597. std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  598. float queuePriority = 1.0f;
  599. for (uint32_t queueFamily : uniqueQueueFamilies) {
  600. VkDeviceQueueCreateInfo queueCreateInfo{};
  601. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  602. queueCreateInfo.queueFamilyIndex = queueFamily;
  603. queueCreateInfo.queueCount = 1;
  604. queueCreateInfo.pQueuePriorities = &queuePriority;
  605. queueCreateInfos.push_back(queueCreateInfo);
  606. }
  607. VkPhysicalDeviceFeatures deviceFeatures{};
  608. deviceFeatures.samplerAnisotropy = VK_TRUE;
  609. VkPhysicalDeviceFeatures2 deviceFeatures2{};
  610. deviceFeatures2.features.robustBufferAccess = VK_TRUE;
  611. deviceFeatures2.pNext = nullptr;
  612. VkDeviceCreateInfo createInfo{};
  613. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  614. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  615. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  616. createInfo.pEnabledFeatures = &deviceFeatures;
  617. createInfo.pNext = &deviceFeatures2;
  618. createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
  619. createInfo.ppEnabledExtensionNames = deviceExtensions.data();
  620. // can this be removed?
  621. if (enableValidationLayers) {
  622. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  623. createInfo.ppEnabledLayerNames = validationLayers.data();
  624. }
  625. else {
  626. createInfo.enabledLayerCount = 0;
  627. }
  628. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
  629. throw love::Exception("failed to create logical device");
  630. }
  631. vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
  632. vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
  633. }
  634. void Graphics::initVMA() {
  635. VmaVulkanFunctions vulkanFunctions = {};
  636. vulkanFunctions.vkGetInstanceProcAddr = &vkGetInstanceProcAddr;
  637. vulkanFunctions.vkGetDeviceProcAddr = &vkGetDeviceProcAddr;
  638. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  639. allocatorCreateInfo.vulkanApiVersion = VK_API_VERSION_1_2;
  640. allocatorCreateInfo.physicalDevice = physicalDevice;
  641. allocatorCreateInfo.device = device;
  642. allocatorCreateInfo.instance = instance;
  643. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  644. vmaCreateAllocator(&allocatorCreateInfo, &vmaAllocator);
  645. }
  646. void Graphics::createSurface() {
  647. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  648. const void* handle = window->getHandle();
  649. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE) {
  650. throw love::Exception("failed to create window surface");
  651. }
  652. }
  653. Graphics::SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device) {
  654. SwapChainSupportDetails details;
  655. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  656. uint32_t formatCount;
  657. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  658. if (formatCount != 0) {
  659. details.formats.resize(formatCount);
  660. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  661. }
  662. uint32_t presentModeCount;
  663. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  664. if (presentModeCount != 0) {
  665. details.presentModes.resize(presentModeCount);
  666. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  667. }
  668. return details;
  669. }
  670. void Graphics::createSwapChain() {
  671. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  672. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  673. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  674. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  675. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  676. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
  677. imageCount = swapChainSupport.capabilities.maxImageCount;
  678. }
  679. VkSwapchainCreateInfoKHR createInfo{};
  680. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  681. createInfo.surface = surface;
  682. createInfo.minImageCount = imageCount;
  683. createInfo.imageFormat = surfaceFormat.format;
  684. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  685. createInfo.imageExtent = extent;
  686. createInfo.imageArrayLayers = 1;
  687. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  688. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  689. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  690. if (indices.graphicsFamily != indices.presentFamily) {
  691. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  692. createInfo.queueFamilyIndexCount = 2;
  693. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  694. }
  695. else {
  696. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  697. createInfo.queueFamilyIndexCount = 0;
  698. createInfo.pQueueFamilyIndices = nullptr;
  699. }
  700. createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
  701. createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  702. createInfo.presentMode = presentMode;
  703. createInfo.clipped = VK_TRUE;
  704. createInfo.oldSwapchain = VK_NULL_HANDLE;
  705. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
  706. throw love::Exception("failed to create swap chain");
  707. }
  708. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  709. swapChainImages.resize(imageCount);
  710. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  711. swapChainImageFormat = surfaceFormat.format;
  712. swapChainExtent = extent;
  713. }
  714. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
  715. for (const auto& availableFormat : availableFormats) {
  716. if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
  717. return availableFormat;
  718. }
  719. }
  720. return availableFormats[0];
  721. }
  722. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) {
  723. // needed ?
  724. for (const auto& availablePresentMode : availablePresentModes) {
  725. if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
  726. return availablePresentMode;
  727. }
  728. }
  729. return VK_PRESENT_MODE_FIFO_KHR;
  730. }
  731. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
  732. if (capabilities.currentExtent.width != UINT32_MAX) {
  733. return capabilities.currentExtent;
  734. }
  735. else {
  736. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  737. const void* handle = window->getHandle();
  738. int width, height;
  739. // is this the equivalent of glfwGetFramebufferSize ?
  740. SDL_Vulkan_GetDrawableSize((SDL_Window*)handle, &width, &height);
  741. VkExtent2D actualExtent = {
  742. static_cast<uint32_t>(width),
  743. static_cast<uint32_t>(height)
  744. };
  745. actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  746. actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  747. return actualExtent;
  748. }
  749. }
  750. void Graphics::createImageViews() {
  751. swapChainImageViews.resize(swapChainImages.size());
  752. for (size_t i = 0; i < swapChainImages.size(); i++) {
  753. VkImageViewCreateInfo createInfo{};
  754. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  755. createInfo.image = swapChainImages.at(i);
  756. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  757. createInfo.format = swapChainImageFormat;
  758. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  759. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  760. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  761. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  762. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  763. createInfo.subresourceRange.baseMipLevel = 0;
  764. createInfo.subresourceRange.levelCount = 1;
  765. createInfo.subresourceRange.baseArrayLayer = 0;
  766. createInfo.subresourceRange.layerCount = 1;
  767. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS) {
  768. throw love::Exception("failed to create image views");
  769. }
  770. }
  771. }
  772. void Graphics::createRenderPass() {
  773. VkAttachmentDescription colorAttachment{};
  774. colorAttachment.format = swapChainImageFormat;
  775. colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
  776. colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  777. colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  778. colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  779. colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  780. colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  781. colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  782. VkAttachmentReference colorAttachmentRef{};
  783. colorAttachmentRef.attachment = 0;
  784. colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  785. VkSubpassDescription subpass{};
  786. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  787. subpass.colorAttachmentCount = 1;
  788. subpass.pColorAttachments = &colorAttachmentRef;
  789. VkSubpassDependency dependency{};
  790. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  791. dependency.dstSubpass = 0;
  792. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  793. dependency.srcAccessMask = 0;
  794. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  795. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  796. VkRenderPassCreateInfo renderPassInfo{};
  797. renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  798. renderPassInfo.attachmentCount = 1;
  799. renderPassInfo.pAttachments = &colorAttachment;
  800. renderPassInfo.subpassCount = 1;
  801. renderPassInfo.pSubpasses = &subpass;
  802. renderPassInfo.dependencyCount = 1;
  803. renderPassInfo.pDependencies = &dependency;
  804. if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
  805. throw love::Exception("failed to create render pass");
  806. }
  807. }
  808. void Graphics::createDefaultShaders() {
  809. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++) {
  810. auto stype = (Shader::StandardShader)i;
  811. if (!Shader::standardShaders[i]) {
  812. std::vector<std::string> stages;
  813. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  814. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  815. Shader::standardShaders[i] = newShader(stages, { { {"vulkan", "1"} } });
  816. }
  817. }
  818. }
  819. void Graphics::createDescriptorSetLayout() {
  820. VkDescriptorSetLayoutBinding uboLayoutBinding{};
  821. uboLayoutBinding.binding = 0;
  822. uboLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  823. uboLayoutBinding.descriptorCount = 1;
  824. uboLayoutBinding.stageFlags = VK_SHADER_STAGE_VERTEX_BIT | VK_SHADER_STAGE_FRAGMENT_BIT;
  825. VkDescriptorSetLayoutBinding samplerLayoutBinding{};
  826. samplerLayoutBinding.binding = 1;
  827. samplerLayoutBinding.descriptorCount = 1;
  828. samplerLayoutBinding.descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  829. samplerLayoutBinding.pImmutableSamplers = nullptr;
  830. samplerLayoutBinding.stageFlags = VK_SHADER_STAGE_FRAGMENT_BIT;
  831. std::array<VkDescriptorSetLayoutBinding, 2> bindings = { uboLayoutBinding, samplerLayoutBinding };
  832. VkDescriptorSetLayoutCreateInfo layoutInfo{};
  833. layoutInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_LAYOUT_CREATE_INFO;
  834. layoutInfo.bindingCount = static_cast<uint32_t>(bindings.size());
  835. layoutInfo.pBindings = bindings.data();
  836. if (vkCreateDescriptorSetLayout(device, &layoutInfo, nullptr, &descriptorSetLayout) != VK_SUCCESS) {
  837. throw love::Exception("failed to create descriptor set layout");
  838. }
  839. }
  840. void Graphics::createDescriptorPool() {
  841. std::array<VkDescriptorPoolSize, 2> poolSizes{};
  842. poolSizes[0].type = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  843. poolSizes[0].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  844. poolSizes[1].type = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  845. poolSizes[1].descriptorCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  846. VkDescriptorPoolCreateInfo poolInfo{};
  847. poolInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_POOL_CREATE_INFO;
  848. poolInfo.poolSizeCount = static_cast<uint32_t>(poolSizes.size());
  849. poolInfo.pPoolSizes = poolSizes.data();
  850. // FIXME: When using more than 128 textures at once we will run out of memory.
  851. // we probably want to reuse descriptors per flight image
  852. // and use multiple pools in case of too many allocations
  853. poolInfo.maxSets = 128 * static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  854. if (vkCreateDescriptorPool(device, &poolInfo, nullptr, &descriptorPool) != VK_SUCCESS) {
  855. throw love::Exception("failed to create descriptor pool");
  856. }
  857. }
  858. std::vector<VkDescriptorSet> Graphics::createDescriptorSets(DecriptorSetConfiguration config) {
  859. std::vector<VkDescriptorSetLayout> layouts(MAX_FRAMES_IN_FLIGHT, descriptorSetLayout);
  860. VkDescriptorSetAllocateInfo allocInfo{};
  861. allocInfo.sType = VK_STRUCTURE_TYPE_DESCRIPTOR_SET_ALLOCATE_INFO;
  862. allocInfo.descriptorPool = descriptorPool;
  863. allocInfo.descriptorSetCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  864. allocInfo.pSetLayouts = layouts.data();
  865. std::vector<VkDescriptorSet> newDescriptorSets;
  866. newDescriptorSets.resize(MAX_FRAMES_IN_FLIGHT);
  867. VkResult result = vkAllocateDescriptorSets(device, &allocInfo, newDescriptorSets.data());
  868. if (result != VK_SUCCESS) {
  869. switch (result) {
  870. case VK_ERROR_OUT_OF_HOST_MEMORY:
  871. throw love::Exception("failed to allocate descriptor sets: out of host memory");
  872. case VK_ERROR_OUT_OF_DEVICE_MEMORY:
  873. throw love::Exception("failed to allocate descriptor sets: out of device memory");
  874. case VK_ERROR_FRAGMENTED_POOL:
  875. throw love::Exception("failed to allocate descriptor sets: fragmented pool");
  876. case VK_ERROR_OUT_OF_POOL_MEMORY:
  877. throw love::Exception("failed to allocate descriptor sets: out of pool memory");
  878. default:
  879. throw love::Exception("failed to allocate descriptor sets");
  880. }
  881. }
  882. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  883. VkDescriptorBufferInfo bufferInfo{};
  884. bufferInfo.buffer = (VkBuffer)config.buffer->getHandle();
  885. bufferInfo.offset = 0;
  886. bufferInfo.range = sizeof(graphics::Shader::BuiltinUniformData);
  887. VkDescriptorImageInfo imageInfo{};
  888. imageInfo.imageLayout = VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL;
  889. Texture* vkTexture = (Texture*)config.texture;
  890. imageInfo.imageView = vkTexture->getImageView();
  891. imageInfo.sampler = vkTexture->getSampler();
  892. std::array<VkWriteDescriptorSet, 2> descriptorWrite{};
  893. descriptorWrite[0].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  894. descriptorWrite[0].dstSet = newDescriptorSets[i];
  895. descriptorWrite[0].dstBinding = 0;
  896. descriptorWrite[0].dstArrayElement = 0;
  897. descriptorWrite[0].descriptorType = VK_DESCRIPTOR_TYPE_UNIFORM_BUFFER;
  898. descriptorWrite[0].descriptorCount = 1;
  899. descriptorWrite[0].pBufferInfo = &bufferInfo;
  900. descriptorWrite[1].sType = VK_STRUCTURE_TYPE_WRITE_DESCRIPTOR_SET;
  901. descriptorWrite[1].dstSet = newDescriptorSets[i];
  902. descriptorWrite[1].dstBinding = 1;
  903. descriptorWrite[1].dstArrayElement = 0;
  904. descriptorWrite[1].descriptorType = VK_DESCRIPTOR_TYPE_COMBINED_IMAGE_SAMPLER;
  905. descriptorWrite[1].descriptorCount = 1;
  906. descriptorWrite[1].pImageInfo = &imageInfo;
  907. vkUpdateDescriptorSets(device, static_cast<uint32_t>(descriptorWrite.size()), descriptorWrite.data(), 0, nullptr);
  908. }
  909. return newDescriptorSets;
  910. }
  911. void Graphics::createVulkanVertexFormat(
  912. VertexAttributes vertexAttributes,
  913. bool& useConstantVertexColor,
  914. GraphicsPipelineConfiguration& configuration) {
  915. std::set<uint32_t> usedBuffers;
  916. std::vector<VkVertexInputBindingDescription> bindingDescriptions;
  917. std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
  918. auto allBits = vertexAttributes.enableBits;
  919. bool usesColor = false;
  920. for (uint32_t i = 0; i < VertexAttributes::MAX; i++) { // change to loop like in opengl implementation ?
  921. uint32 bit = 1u << i;
  922. if (allBits & bit) {
  923. if (i == ATTRIB_COLOR) {
  924. usesColor = true;
  925. }
  926. auto attrib = vertexAttributes.attribs[i];
  927. auto bufferBinding = attrib.bufferIndex;
  928. if (usedBuffers.find(bufferBinding) == usedBuffers.end()) { // use .contains() when c++20 is enabled
  929. usedBuffers.insert(bufferBinding);
  930. VkVertexInputBindingDescription bindingDescription{};
  931. bindingDescription.binding = bufferBinding;
  932. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  933. bindingDescription.stride = vertexAttributes.bufferLayouts[bufferBinding].stride;
  934. bindingDescriptions.push_back(bindingDescription);
  935. }
  936. VkVertexInputAttributeDescription attributeDescription{};
  937. attributeDescription.location = i;
  938. attributeDescription.binding = bufferBinding;
  939. attributeDescription.offset = attrib.offsetFromVertex;
  940. attributeDescription.format = Vulkan::getVulkanVertexFormat(attrib.format);
  941. attributeDescriptions.push_back(attributeDescription);
  942. }
  943. }
  944. // do we need to use a constant VertexColor?
  945. if (!usesColor) {
  946. constexpr uint32_t constantColorBufferBinding = 2;
  947. VkVertexInputBindingDescription bindingDescription{};
  948. bindingDescription.binding = constantColorBufferBinding;
  949. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  950. bindingDescription.stride = 0; // no stride, will always read the same color multiple times.
  951. bindingDescriptions.push_back(bindingDescription);
  952. VkVertexInputAttributeDescription attributeDescription{};
  953. attributeDescription.binding = constantColorBufferBinding;
  954. attributeDescription.location = ATTRIB_COLOR;
  955. attributeDescription.offset = 0;
  956. attributeDescription.format = VK_FORMAT_R32G32B32A32_SFLOAT;
  957. useConstantVertexColor = true;
  958. }
  959. else {
  960. useConstantVertexColor = false;
  961. }
  962. configuration.vertexInputBindingDescriptions = bindingDescriptions;
  963. configuration.vertexInputAttributeDescriptions = attributeDescriptions;
  964. }
  965. VkPipeline Graphics::createGraphicsPipeline(GraphicsPipelineConfiguration configuration) {
  966. auto shader = reinterpret_cast<love::graphics::vulkan::Shader*>(love::graphics::vulkan::Shader::standardShaders[Shader::STANDARD_DEFAULT]);
  967. auto shaderStages = shader->getShaderStages();
  968. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  969. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  970. vertexInputInfo.vertexBindingDescriptionCount = configuration.vertexInputBindingDescriptions.size();
  971. vertexInputInfo.pVertexBindingDescriptions = configuration.vertexInputBindingDescriptions.data();
  972. vertexInputInfo.vertexAttributeDescriptionCount = configuration.vertexInputAttributeDescriptions.size();
  973. vertexInputInfo.pVertexAttributeDescriptions = configuration.vertexInputAttributeDescriptions.data();
  974. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  975. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  976. inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  977. inputAssembly.primitiveRestartEnable = VK_FALSE;
  978. VkViewport viewport{};
  979. viewport.x = 0.0f;
  980. viewport.y = 0.0f;
  981. viewport.width = (float)swapChainExtent.width;
  982. viewport.height = (float)swapChainExtent.height;
  983. viewport.minDepth = 0.0f;
  984. viewport.maxDepth = 1.0f;
  985. VkRect2D scissor{};
  986. scissor.offset = { 0, 0 };
  987. scissor.extent = swapChainExtent;
  988. VkPipelineViewportStateCreateInfo viewportState{};
  989. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  990. viewportState.viewportCount = 1;
  991. viewportState.pViewports = &viewport;
  992. viewportState.scissorCount = 1;
  993. viewportState.pScissors = &scissor;
  994. VkPipelineRasterizationStateCreateInfo rasterizer{};
  995. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  996. rasterizer.depthClampEnable = VK_FALSE;
  997. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  998. rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
  999. rasterizer.lineWidth = 1.0f;
  1000. rasterizer.cullMode = VK_CULL_MODE_FRONT_BIT;
  1001. rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
  1002. rasterizer.depthBiasEnable = VK_FALSE;
  1003. rasterizer.depthBiasConstantFactor = 0.0f;
  1004. rasterizer.depthBiasClamp = 0.0f;
  1005. rasterizer.depthBiasSlopeFactor = 0.0f;
  1006. VkPipelineMultisampleStateCreateInfo multisampling{};
  1007. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  1008. multisampling.sampleShadingEnable = VK_FALSE;
  1009. multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  1010. multisampling.minSampleShading = 1.0f; // Optional
  1011. multisampling.pSampleMask = nullptr; // Optional
  1012. multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
  1013. multisampling.alphaToOneEnable = VK_FALSE; // Optional
  1014. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  1015. colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  1016. colorBlendAttachment.blendEnable = VK_FALSE;
  1017. VkPipelineColorBlendStateCreateInfo colorBlending{};
  1018. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  1019. colorBlending.logicOpEnable = VK_FALSE;
  1020. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  1021. colorBlending.attachmentCount = 1;
  1022. colorBlending.pAttachments = &colorBlendAttachment;
  1023. colorBlending.blendConstants[0] = 0.0f;
  1024. colorBlending.blendConstants[1] = 0.0f;
  1025. colorBlending.blendConstants[2] = 0.0f;
  1026. colorBlending.blendConstants[3] = 0.0f;
  1027. VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
  1028. pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  1029. pipelineLayoutInfo.setLayoutCount = 1;
  1030. pipelineLayoutInfo.pSetLayouts = &descriptorSetLayout;
  1031. pipelineLayoutInfo.pushConstantRangeCount = 0;
  1032. if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
  1033. throw love::Exception("failed to create pipeline layout");
  1034. }
  1035. VkGraphicsPipelineCreateInfo pipelineInfo{};
  1036. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  1037. pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  1038. pipelineInfo.pStages = shaderStages.data();
  1039. pipelineInfo.pVertexInputState = &vertexInputInfo;
  1040. pipelineInfo.pInputAssemblyState = &inputAssembly;
  1041. pipelineInfo.pViewportState = &viewportState;
  1042. pipelineInfo.pRasterizationState = &rasterizer;
  1043. pipelineInfo.pMultisampleState = &multisampling;
  1044. pipelineInfo.pDepthStencilState = nullptr;
  1045. pipelineInfo.pColorBlendState = &colorBlending;
  1046. pipelineInfo.pDynamicState = nullptr;
  1047. pipelineInfo.layout = pipelineLayout;
  1048. pipelineInfo.renderPass = renderPass;
  1049. pipelineInfo.subpass = 0;
  1050. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  1051. pipelineInfo.basePipelineIndex = -1;
  1052. VkPipeline graphicsPipeline;
  1053. if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
  1054. throw love::Exception("failed to create graphics pipeline");
  1055. }
  1056. return graphicsPipeline;
  1057. }
  1058. void Graphics::ensureGraphicsPipelineConfiguration(GraphicsPipelineConfiguration configuration) {
  1059. VkPipeline pipeline = VK_NULL_HANDLE;
  1060. for (auto const& p : graphicsPipelines) {
  1061. if (p.first == configuration) {
  1062. pipeline = p.second;
  1063. break;
  1064. }
  1065. }
  1066. if (pipeline != VK_NULL_HANDLE) {
  1067. if (currentGraphicsPipeline != pipeline) {
  1068. vkCmdBindPipeline(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  1069. currentGraphicsPipeline = pipeline;
  1070. }
  1071. } else {
  1072. VkPipeline newPipeLine = createGraphicsPipeline(configuration);
  1073. graphicsPipelines.push_back(std::make_pair(configuration, newPipeLine));
  1074. vkCmdBindPipeline(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, newPipeLine);
  1075. currentGraphicsPipeline = newPipeLine;
  1076. }
  1077. }
  1078. void Graphics::createFramebuffers() {
  1079. swapChainFramBuffers.resize(swapChainImageViews.size());
  1080. for (size_t i = 0; i < swapChainImageViews.size(); i++) {
  1081. VkImageView attachments[] = {
  1082. swapChainImageViews.at(i)
  1083. };
  1084. VkFramebufferCreateInfo framebufferInfo{};
  1085. framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1086. framebufferInfo.renderPass = renderPass;
  1087. framebufferInfo.attachmentCount = 1;
  1088. framebufferInfo.pAttachments = attachments;
  1089. framebufferInfo.width = swapChainExtent.width;
  1090. framebufferInfo.height = swapChainExtent.height;
  1091. framebufferInfo.layers = 1;
  1092. if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramBuffers.at(i)) != VK_SUCCESS) {
  1093. throw love::Exception("failed to create framebuffers");
  1094. }
  1095. }
  1096. }
  1097. void Graphics::createCommandPool() {
  1098. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  1099. VkCommandPoolCreateInfo poolInfo{};
  1100. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  1101. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
  1102. poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT;
  1103. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
  1104. throw love::Exception("failed to create command pool");
  1105. }
  1106. }
  1107. void Graphics::createCommandBuffers() {
  1108. commandBuffers.resize(swapChainFramBuffers.size());
  1109. VkCommandBufferAllocateInfo allocInfo{};
  1110. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  1111. allocInfo.commandPool = commandPool;
  1112. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  1113. allocInfo.commandBufferCount = (uint32_t)commandBuffers.size();
  1114. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
  1115. throw love::Exception("failed to allocate command buffers");
  1116. }
  1117. }
  1118. void Graphics::createSyncObjects() {
  1119. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  1120. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  1121. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  1122. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  1123. VkSemaphoreCreateInfo semaphoreInfo{};
  1124. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  1125. VkFenceCreateInfo fenceInfo{};
  1126. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  1127. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  1128. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  1129. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  1130. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  1131. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS) {
  1132. throw love::Exception("failed to create synchronization objects for a frame!");
  1133. }
  1134. }
  1135. }
  1136. void Graphics::createDefaultTexture() {
  1137. Texture::Settings settings;
  1138. standardTexture = newTexture(settings);
  1139. }
  1140. void Graphics::createQuadIndexBuffer() {
  1141. if (quadIndexBuffer != nullptr)
  1142. return;
  1143. size_t size = sizeof(uint16) * getIndexCount(TRIANGLEINDEX_QUADS, LOVE_UINT16_MAX);
  1144. quadIndexBuffer = static_cast<StreamBuffer*>(newStreamBuffer(BUFFERUSAGE_INDEX, size));
  1145. auto map = quadIndexBuffer->map(size);
  1146. fillIndices(TRIANGLEINDEX_QUADS, 0, LOVE_UINT16_MAX, (uint16*)map.data);
  1147. quadIndexBuffer->unmap(size);
  1148. }
  1149. bool operator==(const Graphics::GraphicsPipelineConfiguration& first, const Graphics::GraphicsPipelineConfiguration& other) {
  1150. if (first.vertexInputAttributeDescriptions.size() != other.vertexInputAttributeDescriptions.size()) {
  1151. return false;
  1152. }
  1153. if (first.vertexInputBindingDescriptions.size() != other.vertexInputBindingDescriptions.size()) {
  1154. return false;
  1155. }
  1156. for (uint32_t i = 0; i < first.vertexInputAttributeDescriptions.size(); i++) {
  1157. const VkVertexInputAttributeDescription& x = first.vertexInputAttributeDescriptions[i];
  1158. const VkVertexInputAttributeDescription& y = other.vertexInputAttributeDescriptions[i];
  1159. if (x.binding != y.binding) {
  1160. return false;
  1161. }
  1162. if (x.location != y.location) {
  1163. return false;
  1164. }
  1165. if (x.offset != y.offset) {
  1166. return false;
  1167. }
  1168. if (x.format != y.format) {
  1169. return false;
  1170. }
  1171. }
  1172. for (uint32_t i = 0; i < first.vertexInputBindingDescriptions.size(); i++) {
  1173. const VkVertexInputBindingDescription& x = first.vertexInputBindingDescriptions[i];
  1174. const VkVertexInputBindingDescription& y = other.vertexInputBindingDescriptions[i];
  1175. if (x.binding != y.binding) {
  1176. return false;
  1177. }
  1178. if (x.inputRate != y.inputRate) {
  1179. return false;
  1180. }
  1181. if (x.stride != y.stride) {
  1182. return false;
  1183. }
  1184. }
  1185. return true;
  1186. }
  1187. void Graphics::cleanup() {
  1188. vkDeviceWaitIdle(device);
  1189. cleanupSwapChain();
  1190. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  1191. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  1192. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  1193. vkDestroyFence(device, inFlightFences[i], nullptr);
  1194. }
  1195. vkDestroyDescriptorPool(device, descriptorPool, nullptr);
  1196. vkDestroyDescriptorSetLayout(device, descriptorSetLayout, nullptr);
  1197. vkDestroyCommandPool(device, commandPool, nullptr);
  1198. vkDestroyDevice(device, nullptr);
  1199. vkDestroySurfaceKHR(instance, surface, nullptr);
  1200. vkDestroyInstance(instance, nullptr);
  1201. }
  1202. void Graphics::cleanupSwapChain() {
  1203. std::cout << "cleanupSwapChain ";
  1204. for (size_t i = 0; i < swapChainFramBuffers.size(); i++) {
  1205. vkDestroyFramebuffer(device, swapChainFramBuffers[i], nullptr);
  1206. }
  1207. vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
  1208. for (auto const& p : graphicsPipelines) {
  1209. vkDestroyPipeline(device, p.second, nullptr);
  1210. }
  1211. graphicsPipelines.clear();
  1212. currentGraphicsPipeline = VK_NULL_HANDLE;
  1213. // vkDestroyPipelineLayout(device, pipelineLayout, nullptr); FIXME
  1214. vkDestroyRenderPass(device, renderPass, nullptr);
  1215. for (size_t i = 0; i < swapChainImageViews.size(); i++) {
  1216. vkDestroyImageView(device, swapChainImageViews[i], nullptr);
  1217. }
  1218. vkDestroySwapchainKHR(device, swapChain, nullptr);
  1219. uniformBufferMap.clear();
  1220. descriptorSetsMap.clear();
  1221. }
  1222. void Graphics::recreateSwapChain() {
  1223. vkDeviceWaitIdle(device);
  1224. cleanupSwapChain();
  1225. createSwapChain();
  1226. createImageViews();
  1227. createRenderPass();
  1228. createFramebuffers();
  1229. createDescriptorPool();
  1230. createCommandBuffers();
  1231. startRecordingGraphicsCommands();
  1232. }
  1233. love::graphics::Graphics* createInstance() {
  1234. love::graphics::Graphics* instance = nullptr;
  1235. try {
  1236. instance = new Graphics();
  1237. }
  1238. catch (love::Exception& e) {
  1239. printf("Cannot create Vulkan renderer: %s\n", e.what());
  1240. }
  1241. return instance;
  1242. }
  1243. }
  1244. }
  1245. }