Graphics.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959
  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 <vector>
  8. #include <cstring>
  9. #include <set>
  10. #include <fstream>
  11. #include <iostream>
  12. namespace love {
  13. namespace graphics {
  14. namespace vulkan {
  15. const std::vector<const char*> validationLayers = {
  16. "VK_LAYER_KHRONOS_validation"
  17. };
  18. const std::vector<const char*> deviceExtensions = {
  19. VK_KHR_SWAPCHAIN_EXTENSION_NAME
  20. };
  21. #ifdef NDEBUG
  22. const bool enableValidationLayers = false;
  23. #else
  24. const bool enableValidationLayers = true;
  25. #endif
  26. const int MAX_FRAMES_IN_FLIGHT = 2;
  27. static std::vector<char> readFile(const std::string& filename) {
  28. std::ifstream file(filename, std::ios::ate | std::ios::binary);
  29. if (!file.is_open()) {
  30. throw std::runtime_error("failed to open file!");
  31. }
  32. size_t fileSize = (size_t)file.tellg();
  33. std::vector<char> buffer(fileSize);
  34. file.seekg(0);
  35. file.read(buffer.data(), fileSize);
  36. file.close();
  37. return buffer;
  38. }
  39. const char* Graphics::getName() const {
  40. return "love.graphics.vulkan";
  41. }
  42. Graphics::Graphics() {
  43. }
  44. void Graphics::initVulkan() {
  45. if (!init) {
  46. init = true;
  47. createVulkanInstance();
  48. createSurface();
  49. pickPhysicalDevice();
  50. createLogicalDevice();
  51. createSwapChain();
  52. createImageViews();
  53. createRenderPass();
  54. createGraphicsPipeline();
  55. createFramebuffers();
  56. createCommandPool();
  57. createCommandBuffers();
  58. createSyncObjects();
  59. startRecordingGraphicsCommands();
  60. }
  61. }
  62. Graphics::~Graphics() {
  63. cleanup();
  64. }
  65. // START OVERRIDEN FUNCTIONS
  66. 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) {
  67. std::cout << "newBuffer ";
  68. return nullptr;
  69. }
  70. void Graphics::startRecordingGraphicsCommands() {
  71. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  72. while (true) {
  73. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  74. if (result == VK_ERROR_OUT_OF_DATE_KHR) {
  75. recreateSwapChain();
  76. continue;
  77. }
  78. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR) {
  79. throw love::Exception("failed to acquire swap chain image");
  80. }
  81. break;
  82. }
  83. VkCommandBufferBeginInfo beginInfo{};
  84. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  85. beginInfo.flags = 0;
  86. beginInfo.pInheritanceInfo = nullptr;
  87. std::cout << "beginCommandBuffer(imageIndex=" << imageIndex << ") ";
  88. if (vkBeginCommandBuffer(commandBuffers.at(imageIndex), &beginInfo) != VK_SUCCESS) {
  89. throw love::Exception("failed to begin recording command buffer");
  90. }
  91. VkRenderPassBeginInfo renderPassInfo{};
  92. renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  93. renderPassInfo.renderPass = renderPass;
  94. renderPassInfo.framebuffer = swapChainFramBuffers.at(imageIndex);
  95. renderPassInfo.renderArea.offset = { 0, 0 };
  96. renderPassInfo.renderArea.extent = swapChainExtent;
  97. renderPassInfo.clearValueCount = 1;
  98. renderPassInfo.pClearValues = &clearColor;
  99. const auto& commandBuffer = commandBuffers.at(imageIndex);
  100. vkCmdBeginRenderPass(commandBuffers.at(imageIndex), &renderPassInfo, VK_SUBPASS_CONTENTS_INLINE);
  101. vkCmdBindPipeline(commandBuffers.at(imageIndex), VK_PIPELINE_BIND_POINT_GRAPHICS, graphicsPipeline);
  102. }
  103. void Graphics::endRecordingGraphicsCommands() {
  104. const auto& commandBuffer = commandBuffers.at(imageIndex);
  105. std::cout << "endCommandBuffer(imageIndex=" << imageIndex << ") ";
  106. vkCmdEndRenderPass(commandBuffers.at(imageIndex));
  107. if (vkEndCommandBuffer(commandBuffers.at(imageIndex)) != VK_SUCCESS) {
  108. throw love::Exception("failed to record command buffer");
  109. }
  110. }
  111. void Graphics::present(void* screenshotCallbackdata) {
  112. flushBatchedDraws();
  113. endRecordingGraphicsCommands();
  114. if (imagesInFlight[imageIndex] != VK_NULL_HANDLE) {
  115. vkWaitForFences(device, 1, &imagesInFlight.at(imageIndex), VK_TRUE, UINT64_MAX);
  116. }
  117. imagesInFlight[imageIndex] = inFlightFences[currentFrame];
  118. VkSubmitInfo submitInfo{};
  119. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  120. VkSemaphore waitSemaphores[] = { imageAvailableSemaphores.at(currentFrame) };
  121. VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT };
  122. submitInfo.waitSemaphoreCount = 1;
  123. submitInfo.pWaitSemaphores = waitSemaphores;
  124. submitInfo.pWaitDstStageMask = waitStages;
  125. submitInfo.commandBufferCount = 1;
  126. submitInfo.pCommandBuffers = &commandBuffers[imageIndex];
  127. VkSemaphore signalSemaphores[] = { renderFinishedSemaphores.at(currentFrame) };
  128. submitInfo.signalSemaphoreCount = 1;
  129. submitInfo.pSignalSemaphores = signalSemaphores;
  130. vkResetFences(device, 1, &inFlightFences[currentFrame]);
  131. if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, inFlightFences.at(currentFrame)) != VK_SUCCESS) {
  132. throw love::Exception("failed to submit draw command buffer");
  133. }
  134. VkPresentInfoKHR presentInfo{};
  135. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  136. presentInfo.waitSemaphoreCount = 1;
  137. presentInfo.pWaitSemaphores = signalSemaphores;
  138. VkSwapchainKHR swapChains[] = { swapChain };
  139. presentInfo.swapchainCount = 1;
  140. presentInfo.pSwapchains = swapChains;
  141. presentInfo.pImageIndices = &imageIndex;
  142. VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
  143. if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || framebufferResized) {
  144. framebufferResized = false;
  145. recreateSwapChain();
  146. }
  147. else if (result != VK_SUCCESS) {
  148. throw love::Exception("failed to present swap chain image");
  149. }
  150. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  151. std::cout << "present" << std::endl;
  152. startRecordingGraphicsCommands();
  153. }
  154. void Graphics::setViewportSize(int width, int height, int pixelwidth, int pixelheight) {
  155. std::cout << "setViewPortSize";
  156. recreateSwapChain();
  157. }
  158. bool Graphics::setMode(void* context, int width, int height, int pixelwidth, int pixelheight, bool windowhasstencil, int msaa) {
  159. std::cout << "setMode ";
  160. if (batchedDrawState.vb[0] == nullptr)
  161. {
  162. // Initial sizes that should be good enough for most cases. It will
  163. // resize to fit if needed, later.
  164. batchedDrawState.vb[0] = new StreamBuffer(this, device, physicalDevice, BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  165. batchedDrawState.vb[1] = new StreamBuffer(this, device, physicalDevice, BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  166. batchedDrawState.indexBuffer = new StreamBuffer(this, device, physicalDevice, BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  167. }
  168. return true;
  169. }
  170. void Graphics::draw(const DrawIndexedCommand& cmd) {
  171. std::cout << "drawIndexed ";
  172. std::vector<VkBuffer> buffers;
  173. std::vector<VkDeviceSize> offsets;
  174. buffers.push_back((VkBuffer)cmd.buffers->info[0].buffer->getHandle());
  175. offsets.push_back((VkDeviceSize)cmd.buffers->info[0].offset);
  176. buffers.push_back((VkBuffer)cmd.buffers->info[1].buffer->getHandle());
  177. offsets.push_back((VkDeviceSize)cmd.buffers->info[1].offset);
  178. vkCmdDraw(commandBuffers.at(imageIndex), 3, 1, 0, 0); // todo adjust
  179. }
  180. graphics::StreamBuffer* Graphics::newStreamBuffer(BufferUsage type, size_t size) {
  181. std::cout << "newStreamBuffer ";
  182. return new StreamBuffer(this, device, physicalDevice, type, size);
  183. }
  184. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  185. void Graphics::createVulkanInstance() {
  186. if (enableValidationLayers && !checkValidationSupport()) {
  187. throw love::Exception("validation layers requested, but not available");
  188. }
  189. VkApplicationInfo appInfo{};
  190. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  191. appInfo.pApplicationName = "LOVE";
  192. appInfo.applicationVersion = VK_MAKE_VERSION(1, 0, 0); //todo, get this version from somewhere else?
  193. appInfo.pEngineName = "LOVE Engine";
  194. appInfo.engineVersion = VK_MAKE_VERSION(1, 0, 0); //todo, same as above
  195. appInfo.apiVersion = VK_API_VERSION_1_0;
  196. VkInstanceCreateInfo createInfo{};
  197. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  198. createInfo.pApplicationInfo = &appInfo;
  199. createInfo.pNext = nullptr;
  200. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  201. const void* handle = window->getHandle();
  202. unsigned int count;
  203. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, nullptr) != SDL_TRUE) {
  204. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  205. }
  206. std::vector<const char*> extensions = {}; // can add more here
  207. size_t addition_extension_count = extensions.size();
  208. extensions.resize(addition_extension_count + count);
  209. if (SDL_Vulkan_GetInstanceExtensions((SDL_Window*)handle, &count, extensions.data() + addition_extension_count) != SDL_TRUE) {
  210. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  211. }
  212. createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
  213. createInfo.ppEnabledExtensionNames = extensions.data();
  214. if (enableValidationLayers) {
  215. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  216. createInfo.ppEnabledLayerNames = validationLayers.data();
  217. }
  218. else {
  219. createInfo.enabledLayerCount = 0;
  220. createInfo.ppEnabledLayerNames = nullptr;
  221. }
  222. if (vkCreateInstance(
  223. &createInfo,
  224. nullptr,
  225. &instance) != VK_SUCCESS) {
  226. throw love::Exception("couldn't create vulkan instance");
  227. }
  228. }
  229. bool Graphics::checkValidationSupport() {
  230. uint32_t layerCount;
  231. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  232. std::vector<VkLayerProperties> availableLayers(layerCount);
  233. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  234. for (const char* layerName : validationLayers) {
  235. bool layerFound = false;
  236. for (const auto& layerProperties : availableLayers) {
  237. if (strcmp(layerName, layerProperties.layerName) == 0) {
  238. layerFound = true;
  239. break;
  240. }
  241. }
  242. if (!layerFound) {
  243. return false;
  244. }
  245. }
  246. return true;
  247. }
  248. void Graphics::pickPhysicalDevice() {
  249. uint32_t deviceCount = 0;
  250. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  251. if (deviceCount == 0) {
  252. throw love::Exception("failed to find GPUs with Vulkan support");
  253. }
  254. std::vector<VkPhysicalDevice> devices(deviceCount);
  255. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  256. std::multimap<int, VkPhysicalDevice> candidates;
  257. for (const auto& device : devices) {
  258. int score = rateDeviceSuitability(device);
  259. candidates.insert(std::make_pair(score, device));
  260. }
  261. if (candidates.rbegin()->first > 0) {
  262. physicalDevice = candidates.rbegin()->second;
  263. }
  264. else {
  265. throw love::Exception("failed to find a suitable gpu");
  266. }
  267. }
  268. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device) {
  269. uint32_t extensionCount;
  270. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  271. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  272. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  273. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  274. for (const auto& extension : availableExtensions) {
  275. requiredExtensions.erase(extension.extensionName);
  276. }
  277. return requiredExtensions.empty();
  278. }
  279. int Graphics::rateDeviceSuitability(VkPhysicalDevice device) {
  280. VkPhysicalDeviceProperties deviceProperties;
  281. VkPhysicalDeviceFeatures deviceFeatures;
  282. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  283. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  284. int score = 1;
  285. // optional
  286. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU) {
  287. score += 1000;
  288. }
  289. // definitely needed
  290. QueueFamilyIndices indices = findQueueFamilies(device);
  291. if (!indices.isComplete()) {
  292. score = 0;
  293. }
  294. bool extensionsSupported = checkDeviceExtensionSupport(device);
  295. if (!extensionsSupported) {
  296. score = 0;
  297. }
  298. if (extensionsSupported) {
  299. auto swapChainSupport = querySwapChainSupport(device);
  300. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  301. if (!swapChainAdequate) {
  302. score = 0;
  303. }
  304. }
  305. return score;
  306. }
  307. Graphics::QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device) {
  308. QueueFamilyIndices indices;
  309. uint32_t queueFamilyCount = 0;
  310. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  311. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  312. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  313. int i = 0;
  314. for (const auto& queueFamily : queueFamilies) {
  315. if (queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) {
  316. indices.graphicsFamily = i;
  317. }
  318. VkBool32 presentSupport = false;
  319. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  320. if (presentSupport) {
  321. indices.presentFamily = i;
  322. }
  323. if (indices.isComplete()) {
  324. break;
  325. }
  326. i++;
  327. }
  328. return indices;
  329. }
  330. void Graphics::createLogicalDevice() {
  331. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  332. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  333. std::set<uint32_t> uniqueQueueFamilies = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  334. float queuePriority = 1.0f;
  335. for (uint32_t queueFamily : uniqueQueueFamilies) {
  336. VkDeviceQueueCreateInfo queueCreateInfo{};
  337. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  338. queueCreateInfo.queueFamilyIndex = queueFamily;
  339. queueCreateInfo.queueCount = 1;
  340. queueCreateInfo.pQueuePriorities = &queuePriority;
  341. queueCreateInfos.push_back(queueCreateInfo);
  342. }
  343. VkPhysicalDeviceFeatures deviceFeatures{};
  344. VkDeviceCreateInfo createInfo{};
  345. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  346. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  347. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  348. createInfo.pEnabledFeatures = &deviceFeatures;
  349. createInfo.enabledExtensionCount = static_cast<uint32_t>(deviceExtensions.size());
  350. createInfo.ppEnabledExtensionNames = deviceExtensions.data();
  351. // can this be removed?
  352. if (enableValidationLayers) {
  353. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  354. createInfo.ppEnabledLayerNames = validationLayers.data();
  355. }
  356. else {
  357. createInfo.enabledLayerCount = 0;
  358. }
  359. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS) {
  360. throw love::Exception("failed to create logical device");
  361. }
  362. vkGetDeviceQueue(device, indices.graphicsFamily.value(), 0, &graphicsQueue);
  363. vkGetDeviceQueue(device, indices.presentFamily.value(), 0, &presentQueue);
  364. }
  365. void Graphics::createSurface() {
  366. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  367. const void* handle = window->getHandle();
  368. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE) {
  369. throw love::Exception("failed to create window surface");
  370. }
  371. }
  372. Graphics::SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device) {
  373. SwapChainSupportDetails details;
  374. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  375. uint32_t formatCount;
  376. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  377. if (formatCount != 0) {
  378. details.formats.resize(formatCount);
  379. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  380. }
  381. uint32_t presentModeCount;
  382. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  383. if (presentModeCount != 0) {
  384. details.presentModes.resize(presentModeCount);
  385. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  386. }
  387. return details;
  388. }
  389. void Graphics::createSwapChain() {
  390. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  391. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  392. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  393. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  394. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  395. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount) {
  396. imageCount = swapChainSupport.capabilities.maxImageCount;
  397. }
  398. VkSwapchainCreateInfoKHR createInfo{};
  399. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  400. createInfo.surface = surface;
  401. createInfo.minImageCount = imageCount;
  402. createInfo.imageFormat = surfaceFormat.format;
  403. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  404. createInfo.imageExtent = extent;
  405. createInfo.imageArrayLayers = 1;
  406. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  407. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  408. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value(), indices.presentFamily.value() };
  409. if (indices.graphicsFamily != indices.presentFamily) {
  410. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  411. createInfo.queueFamilyIndexCount = 2;
  412. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  413. }
  414. else {
  415. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  416. createInfo.queueFamilyIndexCount = 0;
  417. createInfo.pQueueFamilyIndices = nullptr;
  418. }
  419. createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
  420. createInfo.compositeAlpha = VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  421. createInfo.presentMode = presentMode;
  422. createInfo.clipped = VK_TRUE;
  423. createInfo.oldSwapchain = VK_NULL_HANDLE;
  424. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS) {
  425. throw love::Exception("failed to create swap chain");
  426. }
  427. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  428. swapChainImages.resize(imageCount);
  429. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  430. swapChainImageFormat = surfaceFormat.format;
  431. swapChainExtent = extent;
  432. }
  433. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR>& availableFormats) {
  434. for (const auto& availableFormat : availableFormats) {
  435. if (availableFormat.format == VK_FORMAT_B8G8R8A8_SRGB && availableFormat.colorSpace == VK_COLOR_SPACE_SRGB_NONLINEAR_KHR) {
  436. return availableFormat;
  437. }
  438. }
  439. return availableFormats[0];
  440. }
  441. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR>& availablePresentModes) {
  442. // needed ?
  443. for (const auto& availablePresentMode : availablePresentModes) {
  444. if (availablePresentMode == VK_PRESENT_MODE_MAILBOX_KHR) {
  445. return availablePresentMode;
  446. }
  447. }
  448. return VK_PRESENT_MODE_FIFO_KHR;
  449. }
  450. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR& capabilities) {
  451. if (capabilities.currentExtent.width != UINT32_MAX) {
  452. return capabilities.currentExtent;
  453. }
  454. else {
  455. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  456. const void* handle = window->getHandle();
  457. int width, height;
  458. // is this the equivalent of glfwGetFramebufferSize ?
  459. SDL_Vulkan_GetDrawableSize((SDL_Window*)handle, &width, &height);
  460. VkExtent2D actualExtent = {
  461. static_cast<uint32_t>(width),
  462. static_cast<uint32_t>(height)
  463. };
  464. actualExtent.width = std::clamp(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  465. actualExtent.height = std::clamp(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  466. return actualExtent;
  467. }
  468. }
  469. void Graphics::createImageViews() {
  470. swapChainImageViews.resize(swapChainImages.size());
  471. for (size_t i = 0; i < swapChainImages.size(); i++) {
  472. VkImageViewCreateInfo createInfo{};
  473. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  474. createInfo.image = swapChainImages.at(i);
  475. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  476. createInfo.format = swapChainImageFormat;
  477. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  478. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  479. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  480. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  481. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  482. createInfo.subresourceRange.baseMipLevel = 0;
  483. createInfo.subresourceRange.levelCount = 1;
  484. createInfo.subresourceRange.baseArrayLayer = 0;
  485. createInfo.subresourceRange.layerCount = 1;
  486. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS) {
  487. throw love::Exception("failed to create image views");
  488. }
  489. }
  490. }
  491. void Graphics::createRenderPass() {
  492. VkAttachmentDescription colorAttachment{};
  493. colorAttachment.format = swapChainImageFormat;
  494. colorAttachment.samples = VK_SAMPLE_COUNT_1_BIT;
  495. colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  496. colorAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  497. colorAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  498. colorAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  499. colorAttachment.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  500. colorAttachment.finalLayout = VK_IMAGE_LAYOUT_PRESENT_SRC_KHR;
  501. VkAttachmentReference colorAttachmentRef{};
  502. colorAttachmentRef.attachment = 0;
  503. colorAttachmentRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  504. VkSubpassDescription subpass{};
  505. subpass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  506. subpass.colorAttachmentCount = 1;
  507. subpass.pColorAttachments = &colorAttachmentRef;
  508. VkSubpassDependency dependency{};
  509. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  510. dependency.dstSubpass = 0;
  511. dependency.srcStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  512. dependency.srcAccessMask = 0;
  513. dependency.dstStageMask = VK_PIPELINE_STAGE_COLOR_ATTACHMENT_OUTPUT_BIT;
  514. dependency.dstAccessMask = VK_ACCESS_COLOR_ATTACHMENT_WRITE_BIT;
  515. VkRenderPassCreateInfo renderPassInfo{};
  516. renderPassInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  517. renderPassInfo.attachmentCount = 1;
  518. renderPassInfo.pAttachments = &colorAttachment;
  519. renderPassInfo.subpassCount = 1;
  520. renderPassInfo.pSubpasses = &subpass;
  521. renderPassInfo.dependencyCount = 1;
  522. renderPassInfo.pDependencies = &dependency;
  523. if (vkCreateRenderPass(device, &renderPassInfo, nullptr, &renderPass) != VK_SUCCESS) {
  524. throw love::Exception("failed to create render pass");
  525. }
  526. }
  527. static VkShaderModule createShaderModule(VkDevice device, const std::vector<char>& code) {
  528. VkShaderModuleCreateInfo createInfo{};
  529. createInfo.sType = VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO;
  530. createInfo.codeSize = code.size();
  531. createInfo.pCode = reinterpret_cast<const uint32_t*>(code.data());
  532. VkShaderModule shaderModule;
  533. if (vkCreateShaderModule(device, &createInfo, nullptr, &shaderModule) != VK_SUCCESS) {
  534. throw love::Exception("failed to create shader module");
  535. }
  536. return shaderModule;
  537. }
  538. void Graphics::createGraphicsPipeline() {
  539. // love::graphics::vulkan::Shader* shader = dynamic_cast<love::graphics::vulkan::Shader*>(getShader());
  540. // auto shaderStages = shader->getShaderStages();
  541. auto vertShaderCode = readFile("vert.spv");
  542. auto fragShaderCode = readFile("frag.spv");
  543. VkShaderModule vertShaderModule = createShaderModule(device, vertShaderCode);
  544. VkShaderModule fragShaderModule = createShaderModule(device, fragShaderCode);
  545. VkPipelineShaderStageCreateInfo vertShaderStageInfo{};
  546. vertShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  547. vertShaderStageInfo.stage = VK_SHADER_STAGE_VERTEX_BIT;
  548. vertShaderStageInfo.module = vertShaderModule;
  549. vertShaderStageInfo.pName = "main";
  550. VkPipelineShaderStageCreateInfo fragShaderStageInfo{};
  551. fragShaderStageInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO;
  552. fragShaderStageInfo.stage = VK_SHADER_STAGE_FRAGMENT_BIT;
  553. fragShaderStageInfo.module = fragShaderModule;
  554. fragShaderStageInfo.pName = "main";
  555. VkPipelineShaderStageCreateInfo shaderStages[] = { vertShaderStageInfo, fragShaderStageInfo };
  556. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  557. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  558. VkVertexInputBindingDescription vertexBindingDescription;
  559. vertexBindingDescription.binding = 0;
  560. vertexBindingDescription.stride = 2 * sizeof(float); // just position for now
  561. vertexBindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  562. // todo later
  563. VkVertexInputAttributeDescription positionInputAttributeDescription;
  564. positionInputAttributeDescription.binding = 0;
  565. positionInputAttributeDescription.location = 0;
  566. positionInputAttributeDescription.format = VK_FORMAT_R32G32_SFLOAT;
  567. positionInputAttributeDescription.offset = 0;
  568. vertexInputInfo.vertexBindingDescriptionCount = 0;
  569. vertexInputInfo.pVertexBindingDescriptions = &vertexBindingDescription;
  570. vertexInputInfo.vertexAttributeDescriptionCount = 0;
  571. vertexInputInfo.pVertexAttributeDescriptions = &positionInputAttributeDescription;
  572. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  573. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  574. inputAssembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST;
  575. inputAssembly.primitiveRestartEnable = VK_FALSE;
  576. VkViewport viewport{};
  577. viewport.x = 0.0f;
  578. viewport.y = 0.0f;
  579. viewport.width = (float)swapChainExtent.width;
  580. viewport.height = (float)swapChainExtent.height;
  581. viewport.minDepth = 0.0f;
  582. viewport.maxDepth = 1.0f;
  583. VkRect2D scissor{};
  584. scissor.offset = { 0, 0 };
  585. scissor.extent = swapChainExtent;
  586. VkPipelineViewportStateCreateInfo viewportState{};
  587. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  588. viewportState.viewportCount = 1;
  589. viewportState.pViewports = &viewport;
  590. viewportState.scissorCount = 1;
  591. viewportState.pScissors = &scissor;
  592. VkPipelineRasterizationStateCreateInfo rasterizer{};
  593. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  594. rasterizer.depthClampEnable = VK_FALSE;
  595. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  596. rasterizer.polygonMode = VK_POLYGON_MODE_FILL;
  597. rasterizer.lineWidth = 1.0f;
  598. rasterizer.cullMode = VK_CULL_MODE_BACK_BIT;
  599. rasterizer.frontFace = VK_FRONT_FACE_CLOCKWISE;
  600. rasterizer.depthBiasEnable = VK_FALSE;
  601. rasterizer.depthBiasConstantFactor = 0.0f;
  602. rasterizer.depthBiasClamp = 0.0f;
  603. rasterizer.depthBiasSlopeFactor = 0.0f;
  604. VkPipelineMultisampleStateCreateInfo multisampling{};
  605. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  606. multisampling.sampleShadingEnable = VK_FALSE;
  607. multisampling.rasterizationSamples = VK_SAMPLE_COUNT_1_BIT;
  608. multisampling.minSampleShading = 1.0f; // Optional
  609. multisampling.pSampleMask = nullptr; // Optional
  610. multisampling.alphaToCoverageEnable = VK_FALSE; // Optional
  611. multisampling.alphaToOneEnable = VK_FALSE; // Optional
  612. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  613. colorBlendAttachment.colorWriteMask = VK_COLOR_COMPONENT_R_BIT | VK_COLOR_COMPONENT_G_BIT | VK_COLOR_COMPONENT_B_BIT | VK_COLOR_COMPONENT_A_BIT;
  614. colorBlendAttachment.blendEnable = VK_FALSE;
  615. VkPipelineColorBlendStateCreateInfo colorBlending{};
  616. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  617. colorBlending.logicOpEnable = VK_FALSE;
  618. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  619. colorBlending.attachmentCount = 1;
  620. colorBlending.pAttachments = &colorBlendAttachment;
  621. colorBlending.blendConstants[0] = 0.0f;
  622. colorBlending.blendConstants[1] = 0.0f;
  623. colorBlending.blendConstants[2] = 0.0f;
  624. colorBlending.blendConstants[3] = 0.0f;
  625. VkPipelineLayoutCreateInfo pipelineLayoutInfo{};
  626. pipelineLayoutInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO;
  627. pipelineLayoutInfo.setLayoutCount = 0;
  628. pipelineLayoutInfo.pushConstantRangeCount = 0;
  629. if (vkCreatePipelineLayout(device, &pipelineLayoutInfo, nullptr, &pipelineLayout) != VK_SUCCESS) {
  630. throw love::Exception("failed to create pipeline layout");
  631. }
  632. VkGraphicsPipelineCreateInfo pipelineInfo{};
  633. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  634. // pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  635. // pipelineInfo.pStages = shaderStages.data();
  636. pipelineInfo.stageCount = 2;
  637. pipelineInfo.pStages = shaderStages;
  638. pipelineInfo.pVertexInputState = &vertexInputInfo;
  639. pipelineInfo.pInputAssemblyState = &inputAssembly;
  640. pipelineInfo.pViewportState = &viewportState;
  641. pipelineInfo.pRasterizationState = &rasterizer;
  642. pipelineInfo.pMultisampleState = &multisampling;
  643. pipelineInfo.pDepthStencilState = nullptr;
  644. pipelineInfo.pColorBlendState = &colorBlending;
  645. pipelineInfo.pDynamicState = nullptr;
  646. pipelineInfo.layout = pipelineLayout;
  647. pipelineInfo.renderPass = renderPass;
  648. pipelineInfo.subpass = 0;
  649. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  650. pipelineInfo.basePipelineIndex = -1;
  651. if (vkCreateGraphicsPipelines(device, VK_NULL_HANDLE, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS) {
  652. throw love::Exception("failed to create graphics pipeline");
  653. }
  654. vkDestroyShaderModule(device, vertShaderModule, nullptr);
  655. vkDestroyShaderModule(device, fragShaderModule, nullptr);
  656. }
  657. void Graphics::createFramebuffers() {
  658. swapChainFramBuffers.resize(swapChainImageViews.size());
  659. for (size_t i = 0; i < swapChainImageViews.size(); i++) {
  660. VkImageView attachments[] = {
  661. swapChainImageViews.at(i)
  662. };
  663. VkFramebufferCreateInfo framebufferInfo{};
  664. framebufferInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  665. framebufferInfo.renderPass = renderPass;
  666. framebufferInfo.attachmentCount = 1;
  667. framebufferInfo.pAttachments = attachments;
  668. framebufferInfo.width = swapChainExtent.width;
  669. framebufferInfo.height = swapChainExtent.height;
  670. framebufferInfo.layers = 1;
  671. if (vkCreateFramebuffer(device, &framebufferInfo, nullptr, &swapChainFramBuffers.at(i)) != VK_SUCCESS) {
  672. throw love::Exception("failed to create framebuffers");
  673. }
  674. }
  675. }
  676. void Graphics::createCommandPool() {
  677. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  678. VkCommandPoolCreateInfo poolInfo{};
  679. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  680. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value();
  681. poolInfo.flags = 0;
  682. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS) {
  683. throw love::Exception("failed to create command pool");
  684. }
  685. }
  686. void Graphics::createCommandBuffers() {
  687. commandBuffers.resize(swapChainFramBuffers.size());
  688. VkCommandBufferAllocateInfo allocInfo{};
  689. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  690. allocInfo.commandPool = commandPool;
  691. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  692. allocInfo.commandBufferCount = (uint32_t)commandBuffers.size();
  693. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS) {
  694. throw love::Exception("failed to allocate command buffers");
  695. }
  696. }
  697. void Graphics::createSyncObjects() {
  698. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  699. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  700. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  701. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  702. VkSemaphoreCreateInfo semaphoreInfo{};
  703. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  704. VkFenceCreateInfo fenceInfo{};
  705. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  706. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  707. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  708. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  709. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  710. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS) {
  711. throw love::Exception("failed to create synchronization objects for a frame!");
  712. }
  713. }
  714. }
  715. void Graphics::cleanup() {
  716. vkDeviceWaitIdle(device);
  717. cleanupSwapChain();
  718. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++) {
  719. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  720. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  721. vkDestroyFence(device, inFlightFences[i], nullptr);
  722. }
  723. vkDestroyCommandPool(device, commandPool, nullptr);
  724. vkDestroyDevice(device, nullptr);
  725. vkDestroySurfaceKHR(instance, surface, nullptr);
  726. vkDestroyInstance(instance, nullptr);
  727. }
  728. void Graphics::cleanupSwapChain() {
  729. for (size_t i = 0; i < swapChainFramBuffers.size(); i++) {
  730. vkDestroyFramebuffer(device, swapChainFramBuffers[i], nullptr);
  731. }
  732. vkFreeCommandBuffers(device, commandPool, static_cast<uint32_t>(commandBuffers.size()), commandBuffers.data());
  733. vkDestroyPipeline(device, graphicsPipeline, nullptr);
  734. vkDestroyPipelineLayout(device, pipelineLayout, nullptr);
  735. vkDestroyRenderPass(device, renderPass, nullptr);
  736. for (size_t i = 0; i < swapChainImageViews.size(); i++) {
  737. vkDestroyImageView(device, swapChainImageViews[i], nullptr);
  738. }
  739. vkDestroySwapchainKHR(device, swapChain, nullptr);
  740. }
  741. void Graphics::recreateSwapChain() {
  742. vkDeviceWaitIdle(device);
  743. cleanupSwapChain();
  744. createSwapChain();
  745. createImageViews();
  746. createRenderPass();
  747. createGraphicsPipeline();
  748. createFramebuffers();
  749. createCommandBuffers();
  750. startRecordingGraphicsCommands();
  751. }
  752. love::graphics::Graphics* createInstance() {
  753. love::graphics::Graphics* instance = nullptr;
  754. try {
  755. instance = new Graphics();
  756. }
  757. catch (love::Exception& e) {
  758. printf("Cannot create Vulkan renderer: %s\n", e.what());
  759. }
  760. return instance;
  761. }
  762. }
  763. }
  764. }