Graphics.cpp 105 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128
  1. /**
  2. * Copyright (c) 2006-2024 LOVE Development Team
  3. *
  4. * This software is provided 'as-is', without any express or implied
  5. * warranty. In no event will the authors be held liable for any damages
  6. * arising from the use of this software.
  7. *
  8. * Permission is granted to anyone to use this software for any purpose,
  9. * including commercial applications, and to alter it and redistribute it
  10. * freely, subject to the following restrictions:
  11. *
  12. * 1. The origin of this software must not be misrepresented; you must not
  13. * claim that you wrote the original software. If you use this software
  14. * in a product, an acknowledgment in the product documentation would be
  15. * appreciated but is not required.
  16. * 2. Altered source versions must be plainly marked as such, and must not be
  17. * misrepresented as being the original software.
  18. * 3. This notice may not be removed or altered from any source distribution.
  19. **/
  20. #include "common/Exception.h"
  21. #include "common/pixelformat.h"
  22. #include "common/version.h"
  23. #include "window/Window.h"
  24. #include "Buffer.h"
  25. #include "Graphics.h"
  26. #include "GraphicsReadback.h"
  27. #include "Shader.h"
  28. #include "Vulkan.h"
  29. #include <SDL_vulkan.h>
  30. #include <algorithm>
  31. #include <vector>
  32. #include <cstring>
  33. #include <set>
  34. #include <sstream>
  35. #include <array>
  36. #define VOLK_IMPLEMENTATION
  37. #include "libraries/volk/volk.h"
  38. #define VMA_IMPLEMENTATION
  39. #include "libraries/vma/vk_mem_alloc.h"
  40. namespace love
  41. {
  42. namespace graphics
  43. {
  44. namespace vulkan
  45. {
  46. static const std::vector<const char*> validationLayers = {
  47. "VK_LAYER_KHRONOS_validation"
  48. };
  49. static const std::vector<const char*> deviceExtensions = {
  50. VK_KHR_SWAPCHAIN_EXTENSION_NAME,
  51. };
  52. constexpr uint32_t USAGES_POLL_INTERVAL = 5000;
  53. VkDevice Graphics::getDevice() const
  54. {
  55. return device;
  56. }
  57. VmaAllocator Graphics::getVmaAllocator() const
  58. {
  59. return vmaAllocator;
  60. }
  61. static void checkOptionalInstanceExtensions(OptionalInstanceExtensions& ext)
  62. {
  63. uint32_t count;
  64. vkEnumerateInstanceExtensionProperties(nullptr, &count, nullptr);
  65. std::vector<VkExtensionProperties> extensions(count);
  66. vkEnumerateInstanceExtensionProperties(nullptr, &count, extensions.data());
  67. for (const auto& extension : extensions)
  68. {
  69. if (strcmp(extension.extensionName, VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME) == 0)
  70. ext.physicalDeviceProperties2 = true;
  71. if (strcmp(extension.extensionName, VK_EXT_DEBUG_UTILS_EXTENSION_NAME) == 0)
  72. ext.debugInfo = true;
  73. }
  74. }
  75. Graphics::Graphics()
  76. : love::graphics::Graphics("love.graphics.vulkan")
  77. {
  78. if (SDL_Vulkan_LoadLibrary(nullptr))
  79. throw love::Exception("could not find vulkan");
  80. volkInitializeCustom((PFN_vkGetInstanceProcAddr)SDL_Vulkan_GetVkGetInstanceProcAddr());
  81. if (isDebugEnabled() && !checkValidationSupport())
  82. throw love::Exception("validation layers requested, but not available");
  83. VkApplicationInfo appInfo{};
  84. appInfo.sType = VK_STRUCTURE_TYPE_APPLICATION_INFO;
  85. appInfo.pApplicationName = "LOVE";
  86. appInfo.applicationVersion = VK_MAKE_API_VERSION(0, 1, 0, 0); // get this version from somewhere else?
  87. appInfo.pEngineName = "LOVE Game Framework";
  88. appInfo.engineVersion = VK_MAKE_API_VERSION(0, VERSION_MAJOR, VERSION_MINOR, VERSION_REV);
  89. appInfo.apiVersion = VK_API_VERSION_1_3;
  90. VkInstanceCreateInfo createInfo{};
  91. createInfo.sType = VK_STRUCTURE_TYPE_INSTANCE_CREATE_INFO;
  92. createInfo.pApplicationInfo = &appInfo;
  93. createInfo.pNext = nullptr;
  94. // GetInstanceExtensions works with a null window parameter as long as
  95. // SDL_Vulkan_LoadLibrary has been called (which we do earlier).
  96. unsigned int count;
  97. if (SDL_Vulkan_GetInstanceExtensions(nullptr, &count, nullptr) != SDL_TRUE)
  98. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  99. std::vector<const char*> extensions = {};
  100. checkOptionalInstanceExtensions(optionalInstanceExtensions);
  101. if (optionalInstanceExtensions.physicalDeviceProperties2)
  102. extensions.push_back(VK_KHR_GET_PHYSICAL_DEVICE_PROPERTIES_2_EXTENSION_NAME);
  103. if (optionalInstanceExtensions.debugInfo)
  104. extensions.push_back(VK_EXT_DEBUG_UTILS_EXTENSION_NAME);
  105. size_t additional_extension_count = extensions.size();
  106. extensions.resize(additional_extension_count + count);
  107. if (SDL_Vulkan_GetInstanceExtensions(nullptr, &count, extensions.data() + additional_extension_count) != SDL_TRUE)
  108. throw love::Exception("couldn't retrieve sdl vulkan extensions");
  109. createInfo.enabledExtensionCount = static_cast<uint32_t>(extensions.size());
  110. createInfo.ppEnabledExtensionNames = extensions.data();
  111. if (isDebugEnabled())
  112. {
  113. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  114. createInfo.ppEnabledLayerNames = validationLayers.data();
  115. }
  116. if (vkCreateInstance(&createInfo, nullptr, &instance) != VK_SUCCESS)
  117. throw love::Exception("couldn't create vulkan instance");
  118. volkLoadInstance(instance);
  119. }
  120. Graphics::~Graphics()
  121. {
  122. defaultConstantTexCoord.set(nullptr);
  123. defaultConstantColor.set(nullptr);
  124. Volatile::unloadAll();
  125. cleanup();
  126. vkDestroyInstance(instance, nullptr);
  127. SDL_Vulkan_UnloadLibrary();
  128. }
  129. // START OVERRIDEN FUNCTIONS
  130. love::graphics::Texture *Graphics::newTexture(const love::graphics::Texture::Settings &settings, const love::graphics::Texture::Slices *data)
  131. {
  132. return new Texture(this, settings, data);
  133. }
  134. 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)
  135. {
  136. return new Buffer(this, settings, format, data, size, arraylength);
  137. }
  138. void Graphics::clear(OptionalColorD color, OptionalInt stencil, OptionalDouble depth)
  139. {
  140. if (!color.hasValue && !stencil.hasValue && !depth.hasValue)
  141. return;
  142. flushBatchedDraws();
  143. if (renderPassState.active)
  144. {
  145. VkClearAttachment attachment{};
  146. if (color.hasValue)
  147. {
  148. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  149. gammaCorrectColor(cf);
  150. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  151. attachment.clearValue.color.float32[0] = static_cast<float>(cf.r);
  152. attachment.clearValue.color.float32[1] = static_cast<float>(cf.g);
  153. attachment.clearValue.color.float32[2] = static_cast<float>(cf.b);
  154. attachment.clearValue.color.float32[3] = static_cast<float>(cf.a);
  155. }
  156. VkClearAttachment depthStencilAttachment{};
  157. if (stencil.hasValue)
  158. {
  159. depthStencilAttachment.aspectMask = VK_IMAGE_ASPECT_STENCIL_BIT;
  160. depthStencilAttachment.clearValue.depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  161. }
  162. if (depth.hasValue)
  163. {
  164. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  165. depthStencilAttachment.clearValue.depthStencil.depth = static_cast<float>(depth.value);
  166. }
  167. std::array<VkClearAttachment, 2> attachments = {
  168. attachment,
  169. depthStencilAttachment
  170. };
  171. VkClearRect rect{};
  172. rect.layerCount = 1;
  173. rect.rect.extent.width = static_cast<uint32_t>(renderPassState.width);
  174. rect.rect.extent.height = static_cast<uint32_t>(renderPassState.height);
  175. vkCmdClearAttachments(
  176. commandBuffers[currentFrame],
  177. static_cast<uint32_t>(attachments.size()), attachments.data(),
  178. 1, &rect);
  179. }
  180. else
  181. {
  182. if (color.hasValue)
  183. {
  184. renderPassState.renderPassConfiguration.colorAttachments[0].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  185. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  186. gammaCorrectColor(cf);
  187. renderPassState.clearColors[0].color.float32[0] = static_cast<float>(cf.r);
  188. renderPassState.clearColors[0].color.float32[1] = static_cast<float>(cf.g);
  189. renderPassState.clearColors[0].color.float32[2] = static_cast<float>(cf.b);
  190. renderPassState.clearColors[0].color.float32[3] = static_cast<float>(cf.a);
  191. }
  192. if (depth.hasValue)
  193. {
  194. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  195. renderPassState.clearColors[1].depthStencil.depth = static_cast<float>(depth.value);
  196. }
  197. if (stencil.hasValue)
  198. {
  199. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  200. renderPassState.clearColors[1].depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  201. }
  202. if (renderPassState.isWindow)
  203. {
  204. renderPassState.windowClearRequested = true;
  205. renderPassState.mainWindowClearColorValue = color;
  206. renderPassState.mainWindowClearDepthValue = depth;
  207. renderPassState.mainWindowClearStencilValue = stencil;
  208. }
  209. else
  210. startRenderPass();
  211. }
  212. }
  213. void Graphics::clear(const std::vector<OptionalColorD> &colors, OptionalInt stencil, OptionalDouble depth)
  214. {
  215. if (colors.empty() && !stencil.hasValue && !depth.hasValue)
  216. return;
  217. flushBatchedDraws();
  218. if (renderPassState.active)
  219. {
  220. std::vector<VkClearAttachment> attachments;
  221. for (const auto &color : colors)
  222. {
  223. VkClearAttachment attachment{};
  224. if (color.hasValue)
  225. {
  226. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  227. gammaCorrectColor(cf);
  228. attachment.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  229. attachment.clearValue.color.float32[0] = static_cast<float>(cf.r);
  230. attachment.clearValue.color.float32[1] = static_cast<float>(cf.g);
  231. attachment.clearValue.color.float32[2] = static_cast<float>(cf.b);
  232. attachment.clearValue.color.float32[3] = static_cast<float>(cf.a);
  233. }
  234. attachments.push_back(attachment);
  235. }
  236. VkClearAttachment depthStencilAttachment{};
  237. if (stencil.hasValue)
  238. {
  239. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  240. depthStencilAttachment.clearValue.depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  241. }
  242. if (depth.hasValue)
  243. {
  244. depthStencilAttachment.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  245. depthStencilAttachment.clearValue.depthStencil.depth = static_cast<float>(depth.value);
  246. }
  247. attachments.push_back(depthStencilAttachment);
  248. VkClearRect rect{};
  249. rect.layerCount = 1;
  250. rect.rect.extent.width = static_cast<uint32_t>(renderPassState.width);
  251. rect.rect.extent.height = static_cast<uint32_t>(renderPassState.height);
  252. vkCmdClearAttachments(
  253. commandBuffers[currentFrame],
  254. static_cast<uint32_t>(attachments.size()), attachments.data(),
  255. 1, &rect);
  256. }
  257. else
  258. {
  259. for (size_t i = 0; i < colors.size(); i++)
  260. {
  261. if (colors[i].hasValue)
  262. {
  263. renderPassState.renderPassConfiguration.colorAttachments[i].loadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  264. auto &color = colors[i];
  265. Colorf cf((float)color.value.r, (float)color.value.g, (float)color.value.b, (float)color.value.a);
  266. gammaCorrectColor(cf);
  267. renderPassState.clearColors[i].color.float32[0] = static_cast<float>(cf.r);
  268. renderPassState.clearColors[i].color.float32[1] = static_cast<float>(cf.g);
  269. renderPassState.clearColors[i].color.float32[2] = static_cast<float>(cf.b);
  270. renderPassState.clearColors[i].color.float32[3] = static_cast<float>(cf.a);
  271. }
  272. }
  273. if (depth.hasValue)
  274. {
  275. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  276. renderPassState.clearColors[colors.size()].depthStencil.depth = static_cast<float>(depth.value);
  277. }
  278. if (stencil.hasValue)
  279. {
  280. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_CLEAR;
  281. renderPassState.clearColors[colors.size()].depthStencil.stencil = static_cast<uint32_t>(stencil.value);
  282. }
  283. startRenderPass();
  284. }
  285. }
  286. void Graphics::discard(const std::vector<bool> &colorbuffers, bool depthstencil)
  287. {
  288. if (renderPassState.active)
  289. endRenderPass();
  290. auto &renderPassConfiguration = renderPassState.renderPassConfiguration;
  291. for (size_t i = 0; i < colorbuffers.size(); i++)
  292. {
  293. if (colorbuffers[i])
  294. renderPassConfiguration.colorAttachments[i].loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  295. }
  296. if (depthstencil)
  297. {
  298. renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  299. renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  300. }
  301. startRenderPass();
  302. }
  303. void Graphics::submitGpuCommands(SubmitMode submitMode, void *screenshotCallbackData)
  304. {
  305. flushBatchedDraws();
  306. if (renderPassState.active)
  307. endRenderPass();
  308. if (submitMode == SUBMIT_PRESENT)
  309. {
  310. if (pendingScreenshotCallbacks.empty())
  311. Vulkan::cmdTransitionImageLayout(
  312. commandBuffers.at(currentFrame),
  313. swapChainImages.at(imageIndex),
  314. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  315. VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
  316. else
  317. {
  318. Vulkan::cmdTransitionImageLayout(
  319. commandBuffers.at(currentFrame),
  320. swapChainImages.at(imageIndex),
  321. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL,
  322. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
  323. Vulkan::cmdTransitionImageLayout(
  324. commandBuffers.at(currentFrame),
  325. screenshotReadbackBuffers.at(currentFrame).image,
  326. VK_IMAGE_LAYOUT_UNDEFINED,
  327. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL);
  328. VkImageBlit blit{};
  329. blit.srcSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  330. blit.srcSubresource.layerCount = 1;
  331. blit.srcOffsets[1] = {
  332. static_cast<int>(swapChainExtent.width),
  333. static_cast<int>(swapChainExtent.height),
  334. 1
  335. };
  336. blit.dstSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  337. blit.dstSubresource.layerCount = 1;
  338. blit.dstOffsets[1] = {
  339. static_cast<int>(swapChainExtent.width),
  340. static_cast<int>(swapChainExtent.height),
  341. 1
  342. };
  343. vkCmdBlitImage(
  344. commandBuffers.at(currentFrame),
  345. swapChainImages.at(imageIndex), VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  346. screenshotReadbackBuffers.at(currentFrame).image, VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  347. 1, &blit,
  348. VK_FILTER_NEAREST);
  349. Vulkan::cmdTransitionImageLayout(
  350. commandBuffers.at(currentFrame),
  351. swapChainImages.at(imageIndex),
  352. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  353. VK_IMAGE_LAYOUT_PRESENT_SRC_KHR);
  354. Vulkan::cmdTransitionImageLayout(
  355. commandBuffers.at(currentFrame),
  356. screenshotReadbackBuffers.at(currentFrame).image,
  357. VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL,
  358. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL);
  359. VkBufferImageCopy region{};
  360. region.imageSubresource.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  361. region.imageSubresource.layerCount = 1;
  362. region.imageExtent = {
  363. swapChainExtent.width,
  364. swapChainExtent.height,
  365. 1
  366. };
  367. vkCmdCopyImageToBuffer(
  368. commandBuffers.at(currentFrame),
  369. screenshotReadbackBuffers.at(currentFrame).image,
  370. VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL,
  371. screenshotReadbackBuffers.at(currentFrame).buffer,
  372. 1, &region);
  373. addReadbackCallback([
  374. w = swapChainExtent.width,
  375. h = swapChainExtent.height,
  376. pendingScreenshotCallbacks = pendingScreenshotCallbacks,
  377. screenShotReadbackBuffer = screenshotReadbackBuffers.at(currentFrame),
  378. screenshotCallbackData = screenshotCallbackData]() {
  379. auto imageModule = Module::getInstance<love::image::Image>(M_IMAGE);
  380. for (const auto &info : pendingScreenshotCallbacks)
  381. {
  382. image::ImageData *img = imageModule->newImageData(
  383. w,
  384. h,
  385. PIXELFORMAT_RGBA8_UNORM,
  386. screenShotReadbackBuffer.allocationInfo.pMappedData);
  387. info.callback(&info, img, screenshotCallbackData);
  388. img->release();
  389. }
  390. });
  391. pendingScreenshotCallbacks.clear();
  392. }
  393. }
  394. endRecordingGraphicsCommands();
  395. if (imagesInFlight[imageIndex] != VK_NULL_HANDLE)
  396. vkWaitForFences(device, 1, &imagesInFlight.at(imageIndex), VK_TRUE, UINT64_MAX);
  397. imagesInFlight[imageIndex] = inFlightFences[currentFrame];
  398. std::array<VkCommandBuffer, 1> submitCommandbuffers = { commandBuffers.at(currentFrame) };
  399. VkSubmitInfo submitInfo{};
  400. submitInfo.sType = VK_STRUCTURE_TYPE_SUBMIT_INFO;
  401. VkSemaphore waitSemaphores[] = { imageAvailableSemaphores.at(currentFrame) };
  402. VkPipelineStageFlags waitStages[] = { VK_PIPELINE_STAGE_TOP_OF_PIPE_BIT };
  403. if (imageRequested)
  404. {
  405. submitInfo.waitSemaphoreCount = 1;
  406. submitInfo.pWaitSemaphores = waitSemaphores;
  407. submitInfo.pWaitDstStageMask = waitStages;
  408. imageRequested = false;
  409. }
  410. submitInfo.commandBufferCount = static_cast<uint32_t>(submitCommandbuffers.size());
  411. submitInfo.pCommandBuffers = submitCommandbuffers.data();
  412. VkSemaphore signalSemaphores[] = { renderFinishedSemaphores.at(currentFrame) };
  413. VkFence fence = VK_NULL_HANDLE;
  414. if (submitMode == SUBMIT_PRESENT)
  415. {
  416. submitInfo.signalSemaphoreCount = 1;
  417. submitInfo.pSignalSemaphores = signalSemaphores;
  418. vkResetFences(device, 1, &inFlightFences[currentFrame]);
  419. fence = inFlightFences[currentFrame];
  420. }
  421. if (vkQueueSubmit(graphicsQueue, 1, &submitInfo, fence) != VK_SUCCESS)
  422. throw love::Exception("failed to submit draw command buffer");
  423. if (submitMode == SUBMIT_NOPRESENT || submitMode == SUBMIT_RESTART)
  424. {
  425. vkQueueWaitIdle(graphicsQueue);
  426. for (auto &callbacks : readbackCallbacks)
  427. {
  428. for (const auto &callback : callbacks)
  429. callback();
  430. callbacks.clear();
  431. }
  432. if (submitMode == SUBMIT_RESTART)
  433. startRecordingGraphicsCommands();
  434. }
  435. }
  436. void Graphics::present(void *screenshotCallbackdata)
  437. {
  438. if (!isActive())
  439. return;
  440. if (isRenderTargetActive())
  441. throw love::Exception("present cannot be called while a render target is active.");
  442. if (!renderPassState.active && renderPassState.windowClearRequested)
  443. startRenderPass();
  444. deprecations.draw(this);
  445. submitGpuCommands(SUBMIT_PRESENT, screenshotCallbackdata);
  446. VkPresentInfoKHR presentInfo{};
  447. presentInfo.sType = VK_STRUCTURE_TYPE_PRESENT_INFO_KHR;
  448. presentInfo.waitSemaphoreCount = 1;
  449. presentInfo.pWaitSemaphores = &renderFinishedSemaphores.at(currentFrame);
  450. presentInfo.swapchainCount = 1;
  451. presentInfo.pSwapchains = &swapChain;
  452. presentInfo.pImageIndices = &imageIndex;
  453. VkResult result = vkQueuePresentKHR(presentQueue, &presentInfo);
  454. if (result == VK_ERROR_OUT_OF_DATE_KHR || result == VK_SUBOPTIMAL_KHR || swapChainRecreationRequested)
  455. {
  456. swapChainRecreationRequested = false;
  457. recreateSwapChain();
  458. }
  459. else if (result != VK_SUCCESS)
  460. throw love::Exception("failed to present swap chain image");
  461. for (love::graphics::StreamBuffer *buffer : batchedDrawState.vb)
  462. buffer->nextFrame();
  463. batchedDrawState.indexBuffer->nextFrame();
  464. drawCalls = 0;
  465. renderTargetSwitchCount = 0;
  466. drawCallsBatched = 0;
  467. updatePendingReadbacks();
  468. updateTemporaryResources();
  469. frameCounter++;
  470. currentFrame = (currentFrame + 1) % MAX_FRAMES_IN_FLIGHT;
  471. beginFrame();
  472. }
  473. void Graphics::backbufferChanged(int width, int height, int pixelwidth, int pixelheight, bool backbufferstencil, bool backbufferdepth, int msaa)
  474. {
  475. if (swapChain != VK_NULL_HANDLE && (pixelwidth != this->pixelWidth || pixelheight != this->pixelHeight || width != this->width || height != this->height
  476. || backbufferstencil != this->backbufferHasStencil || backbufferdepth != this->backbufferHasDepth || msaa != requestedMsaa))
  477. requestSwapchainRecreation();
  478. this->width = width;
  479. this->height = height;
  480. this->pixelWidth = pixelwidth;
  481. this->pixelHeight = pixelheight;
  482. this->backbufferHasStencil = backbufferstencil;
  483. this->backbufferHasDepth = backbufferdepth;
  484. this->requestedMsaa = msaa;
  485. if (!isRenderTargetActive())
  486. resetProjection();
  487. if (swapChain != VK_NULL_HANDLE)
  488. msaaSamples = getMsaaCount(requestedMsaa);
  489. }
  490. bool Graphics::setMode(void *context, int width, int height, int pixelwidth, int pixelheight, bool backbufferstencil, bool backbufferdepth, int msaa)
  491. {
  492. // Must be called before the swapchain is created.
  493. backbufferChanged(width, height, pixelwidth, pixelheight, backbufferstencil, backbufferdepth, msaa);
  494. cleanUpFunctions.clear();
  495. cleanUpFunctions.resize(MAX_FRAMES_IN_FLIGHT);
  496. readbackCallbacks.clear();
  497. readbackCallbacks.resize(MAX_FRAMES_IN_FLIGHT);
  498. bool createBaseObjects = physicalDevice == VK_NULL_HANDLE;
  499. createSurface();
  500. if (createBaseObjects)
  501. {
  502. pickPhysicalDevice();
  503. createLogicalDevice();
  504. createPipelineCache();
  505. initVMA();
  506. initCapabilities();
  507. }
  508. msaaSamples = getMsaaCount(requestedMsaa);
  509. createSwapChain();
  510. createImageViews();
  511. createScreenshotCallbackBuffers();
  512. createColorResources();
  513. createDepthResources();
  514. transitionColorDepthLayouts = true;
  515. if (createBaseObjects)
  516. {
  517. createCommandPool();
  518. createCommandBuffers();
  519. createSyncObjects();
  520. }
  521. beginFrame();
  522. if (createBaseObjects)
  523. {
  524. if (batchedDrawState.vb[0] == nullptr)
  525. {
  526. // Initial sizes that should be good enough for most cases. It will
  527. // resize to fit if needed, later.
  528. batchedDrawState.vb[0] = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 1024 * 1024 * 1);
  529. batchedDrawState.vb[1] = new StreamBuffer(this, BUFFERUSAGE_VERTEX, 256 * 1024 * 1);
  530. batchedDrawState.indexBuffer = new StreamBuffer(this, BUFFERUSAGE_INDEX, sizeof(uint16) * LOVE_UINT16_MAX);
  531. }
  532. // sometimes the VertexTexCoord is not set, so we manually adjust it to (0, 0)
  533. if (defaultConstantTexCoord == nullptr)
  534. {
  535. float zeroTexCoord[2] = { 0.0f, 0.0f };
  536. Buffer::DataDeclaration format("ConstantTexCoord", DATAFORMAT_FLOAT_VEC2);
  537. Buffer::Settings settings(BUFFERUSAGEFLAG_VERTEX, BUFFERDATAUSAGE_STATIC);
  538. defaultConstantTexCoord = newBuffer(settings, { format }, zeroTexCoord, sizeof(zeroTexCoord), 1);
  539. }
  540. // sometimes the VertexColor is not set, so we manually adjust it to white color
  541. if (defaultConstantColor == nullptr)
  542. {
  543. uint8 whiteColor[] = { 255, 255, 255, 255 };
  544. Buffer::DataDeclaration format("ConstantColor", DATAFORMAT_UNORM8_VEC4);
  545. Buffer::Settings settings(BUFFERUSAGEFLAG_VERTEX, BUFFERDATAUSAGE_STATIC);
  546. defaultConstantColor = newBuffer(settings, { format }, whiteColor, sizeof(whiteColor), 1);
  547. }
  548. createDefaultShaders();
  549. Shader::current = Shader::standardShaders[Shader::StandardShader::STANDARD_DEFAULT];
  550. createQuadIndexBuffer();
  551. createFanIndexBuffer();
  552. frameCounter = 0;
  553. currentFrame = 0;
  554. }
  555. restoreState(states.back());
  556. Vulkan::resetShaderSwitches();
  557. created = true;
  558. drawCalls = 0;
  559. drawCallsBatched = 0;
  560. return true;
  561. }
  562. void Graphics::initCapabilities()
  563. {
  564. capabilities.features[FEATURE_MULTI_RENDER_TARGET_FORMATS] = true;
  565. capabilities.features[FEATURE_CLAMP_ZERO] = true;
  566. capabilities.features[FEATURE_CLAMP_ONE] = true;
  567. capabilities.features[FEATURE_BLEND_MINMAX] = true;
  568. capabilities.features[FEATURE_LIGHTEN] = true;
  569. capabilities.features[FEATURE_FULL_NPOT] = true;
  570. capabilities.features[FEATURE_PIXEL_SHADER_HIGHP] = true;
  571. capabilities.features[FEATURE_SHADER_DERIVATIVES] = true;
  572. capabilities.features[FEATURE_GLSL3] = true;
  573. capabilities.features[FEATURE_GLSL4] = true;
  574. capabilities.features[FEATURE_INSTANCING] = true;
  575. capabilities.features[FEATURE_TEXEL_BUFFER] = true;
  576. capabilities.features[FEATURE_INDEX_BUFFER_32BIT] = true;
  577. capabilities.features[FEATURE_COPY_BUFFER] = true;
  578. capabilities.features[FEATURE_COPY_BUFFER_TO_TEXTURE] = true;
  579. capabilities.features[FEATURE_COPY_TEXTURE_TO_BUFFER] = true;
  580. capabilities.features[FEATURE_COPY_RENDER_TARGET_TO_BUFFER] = true;
  581. capabilities.features[FEATURE_MIPMAP_RANGE] = true;
  582. capabilities.features[FEATURE_INDIRECT_DRAW] = true;
  583. static_assert(FEATURE_MAX_ENUM == 19, "Graphics::initCapabilities must be updated when adding a new graphics feature!");
  584. VkPhysicalDeviceProperties properties;
  585. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  586. capabilities.limits[LIMIT_POINT_SIZE] = properties.limits.pointSizeRange[1];
  587. capabilities.limits[LIMIT_TEXTURE_SIZE] = properties.limits.maxImageDimension2D;
  588. capabilities.limits[LIMIT_TEXTURE_LAYERS] = properties.limits.maxImageArrayLayers;
  589. capabilities.limits[LIMIT_VOLUME_TEXTURE_SIZE] = properties.limits.maxImageDimension3D;
  590. capabilities.limits[LIMIT_CUBE_TEXTURE_SIZE] = properties.limits.maxImageDimensionCube;
  591. capabilities.limits[LIMIT_TEXEL_BUFFER_SIZE] = properties.limits.maxTexelBufferElements;
  592. capabilities.limits[LIMIT_SHADER_STORAGE_BUFFER_SIZE] = properties.limits.maxStorageBufferRange;
  593. capabilities.limits[LIMIT_THREADGROUPS_X] = properties.limits.maxComputeWorkGroupCount[0];
  594. capabilities.limits[LIMIT_THREADGROUPS_Y] = properties.limits.maxComputeWorkGroupCount[1];
  595. capabilities.limits[LIMIT_THREADGROUPS_Z] = properties.limits.maxComputeWorkGroupCount[2];
  596. capabilities.limits[LIMIT_RENDER_TARGETS] = properties.limits.maxColorAttachments;
  597. capabilities.limits[LIMIT_TEXTURE_MSAA] = static_cast<double>(getMsaaCount(64));
  598. capabilities.limits[LIMIT_ANISOTROPY] = properties.limits.maxSamplerAnisotropy;
  599. static_assert(LIMIT_MAX_ENUM == 13, "Graphics::initCapabilities must be updated when adding a new system limit!");
  600. capabilities.textureTypes[TEXTURE_2D] = true;
  601. capabilities.textureTypes[TEXTURE_2D_ARRAY] = true;
  602. capabilities.textureTypes[TEXTURE_VOLUME] = true;
  603. capabilities.textureTypes[TEXTURE_CUBE] = true;
  604. }
  605. void Graphics::getAPIStats(int &shaderswitches) const
  606. {
  607. shaderswitches = static_cast<int>(Vulkan::getNumShaderSwitches());
  608. }
  609. void Graphics::unSetMode()
  610. {
  611. submitGpuCommands(SUBMIT_NOPRESENT);
  612. created = false;
  613. cleanupSwapChain();
  614. vkDestroySurfaceKHR(instance, surface, nullptr);
  615. }
  616. void Graphics::setActive(bool enable)
  617. {
  618. flushBatchedDraws();
  619. active = enable;
  620. }
  621. int Graphics::getRequestedBackbufferMSAA() const
  622. {
  623. return requestedMsaa;
  624. }
  625. int Graphics::getBackbufferMSAA() const
  626. {
  627. return static_cast<int>(msaaSamples);
  628. }
  629. void Graphics::setFrontFaceWinding(Winding winding)
  630. {
  631. const auto& currentState = states.back();
  632. if (currentState.winding == winding)
  633. return;
  634. flushBatchedDraws();
  635. states.back().winding = winding;
  636. if (optionalDeviceExtensions.extendedDynamicState)
  637. vkCmdSetFrontFaceEXT(
  638. commandBuffers.at(currentFrame),
  639. Vulkan::getFrontFace(winding));
  640. }
  641. void Graphics::setColorMask(ColorChannelMask mask)
  642. {
  643. flushBatchedDraws();
  644. states.back().colorMask = mask;
  645. }
  646. void Graphics::setBlendState(const BlendState &blend)
  647. {
  648. flushBatchedDraws();
  649. states.back().blend = blend;
  650. }
  651. void Graphics::setPointSize(float size)
  652. {
  653. if (size != states.back().pointSize)
  654. flushBatchedDraws();
  655. states.back().pointSize = size;
  656. }
  657. bool Graphics::usesGLSLES() const
  658. {
  659. return false;
  660. }
  661. Graphics::RendererInfo Graphics::getRendererInfo() const
  662. {
  663. VkPhysicalDeviceProperties deviceProperties;
  664. vkGetPhysicalDeviceProperties(physicalDevice, &deviceProperties);
  665. Graphics::RendererInfo info;
  666. info.name = "Vulkan";
  667. info.device = deviceProperties.deviceName;
  668. info.vendor = Vulkan::getVendorName(deviceProperties.vendorID);
  669. info.version = Vulkan::getVulkanApiVersion(deviceProperties.apiVersion);
  670. return info;
  671. }
  672. void Graphics::draw(const DrawCommand &cmd)
  673. {
  674. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  675. if (cmd.indirectBuffer != nullptr)
  676. {
  677. vkCmdDrawIndirect(
  678. commandBuffers.at(currentFrame),
  679. (VkBuffer) cmd.indirectBuffer->getHandle(),
  680. cmd.indirectBufferOffset,
  681. 1,
  682. 0);
  683. }
  684. else
  685. {
  686. vkCmdDraw(
  687. commandBuffers.at(currentFrame),
  688. (uint32) cmd.vertexCount,
  689. (uint32) cmd.instanceCount,
  690. (uint32) cmd.vertexStart,
  691. 0);
  692. }
  693. drawCalls++;
  694. }
  695. void Graphics::draw(const DrawIndexedCommand &cmd)
  696. {
  697. prepareDraw(*cmd.attributes, *cmd.buffers, cmd.texture, cmd.primitiveType, cmd.cullMode);
  698. vkCmdBindIndexBuffer(
  699. commandBuffers.at(currentFrame),
  700. (VkBuffer) cmd.indexBuffer->getHandle(),
  701. (VkDeviceSize) cmd.indexBufferOffset,
  702. Vulkan::getVulkanIndexBufferType(cmd.indexType));
  703. if (cmd.indirectBuffer != nullptr)
  704. {
  705. vkCmdDrawIndexedIndirect(
  706. commandBuffers.at(currentFrame),
  707. (VkBuffer) cmd.indirectBuffer->getHandle(),
  708. cmd.indirectBufferOffset,
  709. 1,
  710. 0);
  711. }
  712. else
  713. {
  714. vkCmdDrawIndexed(
  715. commandBuffers.at(currentFrame),
  716. (uint32) cmd.indexCount,
  717. (uint32) cmd.instanceCount,
  718. 0,
  719. 0,
  720. 0);
  721. }
  722. drawCalls++;
  723. }
  724. void Graphics::drawQuads(int start, int count, const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture)
  725. {
  726. const int MAX_VERTICES_PER_DRAW = LOVE_UINT16_MAX;
  727. const int MAX_QUADS_PER_DRAW = MAX_VERTICES_PER_DRAW / 4;
  728. prepareDraw(attributes, buffers, texture, PRIMITIVE_TRIANGLES, CULL_BACK);
  729. vkCmdBindIndexBuffer(
  730. commandBuffers.at(currentFrame),
  731. (VkBuffer)quadIndexBuffer->getHandle(),
  732. 0,
  733. Vulkan::getVulkanIndexBufferType(INDEX_UINT16));
  734. int baseVertex = start * 4;
  735. for (int quadindex = 0; quadindex < count; quadindex += MAX_QUADS_PER_DRAW)
  736. {
  737. int quadcount = std::min(MAX_QUADS_PER_DRAW, count - quadindex);
  738. vkCmdDrawIndexed(
  739. commandBuffers.at(currentFrame),
  740. static_cast<uint32_t>(quadcount * 6),
  741. 1,
  742. 0,
  743. baseVertex,
  744. 0);
  745. baseVertex += quadcount * 4;
  746. drawCalls++;
  747. }
  748. }
  749. void Graphics::setColor(Colorf c)
  750. {
  751. c.r = std::min(std::max(c.r, 0.0f), 1.0f);
  752. c.g = std::min(std::max(c.g, 0.0f), 1.0f);
  753. c.b = std::min(std::max(c.b, 0.0f), 1.0f);
  754. c.a = std::min(std::max(c.a, 0.0f), 1.0f);
  755. states.back().color = c;
  756. }
  757. static VkRect2D computeScissor(const Rect &r, double bufferWidth, double bufferHeight, double dpiScale, VkSurfaceTransformFlagBitsKHR preTransform)
  758. {
  759. double x = static_cast<double>(r.x) * dpiScale;
  760. double y = static_cast<double>(r.y) * dpiScale;
  761. double w = static_cast<double>(r.w) * dpiScale;
  762. double h = static_cast<double>(r.h) * dpiScale;
  763. double scissorX, scissorY, scissorW, scissorH;
  764. switch (preTransform)
  765. {
  766. case VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR:
  767. scissorX = bufferWidth - h - y;
  768. scissorY = x;
  769. scissorW = h;
  770. scissorH = w;
  771. break;
  772. case VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR:
  773. scissorX = bufferWidth - w - x;
  774. scissorY = bufferHeight - h - y;
  775. scissorW = w;
  776. scissorH = h;
  777. break;
  778. case VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR:
  779. scissorX = y;
  780. scissorY = bufferHeight - w - x;
  781. scissorW = h;
  782. scissorH = w;
  783. break;
  784. default:
  785. scissorX = x;
  786. scissorY = y;
  787. scissorW = w;
  788. scissorH = h;
  789. break;
  790. }
  791. VkRect2D scissor = {
  792. {static_cast<int32_t>(scissorX), static_cast<int32_t>(scissorY)},
  793. {static_cast<uint32_t>(scissorW), static_cast<uint32_t>(scissorH)}
  794. };
  795. return scissor;
  796. }
  797. void Graphics::setScissor(const Rect &rect)
  798. {
  799. flushBatchedDraws();
  800. VkRect2D scissor = computeScissor(rect, static_cast<double>(swapChainExtent.width), static_cast<double>(swapChainExtent.height), getCurrentDPIScale(), preTransform);
  801. vkCmdSetScissor(commandBuffers.at(currentFrame), 0, 1, &scissor);
  802. states.back().scissor = true;
  803. states.back().scissorRect = rect;
  804. }
  805. void Graphics::setScissor()
  806. {
  807. flushBatchedDraws();
  808. states.back().scissor = false;
  809. VkRect2D scissor{};
  810. scissor.offset = { 0, 0 };
  811. scissor.extent = swapChainExtent;
  812. vkCmdSetScissor(commandBuffers.at(currentFrame), 0, 1, &scissor);
  813. }
  814. void Graphics::setStencilState(const StencilState &s)
  815. {
  816. validateStencilState(s);
  817. flushBatchedDraws();
  818. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.writeMask);
  819. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.readMask);
  820. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, s.value);
  821. if (optionalDeviceExtensions.extendedDynamicState)
  822. vkCmdSetStencilOpEXT(
  823. commandBuffers.at(currentFrame),
  824. VK_STENCIL_FRONT_AND_BACK,
  825. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(s.action),
  826. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(s.compare)));
  827. states.back().stencil = s;
  828. }
  829. void Graphics::setDepthMode(CompareMode compare, bool write)
  830. {
  831. validateDepthState(write);
  832. flushBatchedDraws();
  833. if (optionalDeviceExtensions.extendedDynamicState)
  834. {
  835. vkCmdSetDepthCompareOpEXT(
  836. commandBuffers.at(currentFrame), Vulkan::getCompareOp(compare));
  837. vkCmdSetDepthWriteEnableEXT(
  838. commandBuffers.at(currentFrame), Vulkan::getBool(write));
  839. }
  840. states.back().depthTest = compare;
  841. states.back().depthWrite = write;
  842. }
  843. void Graphics::setWireframe(bool enable)
  844. {
  845. flushBatchedDraws();
  846. states.back().wireframe = enable;
  847. }
  848. bool Graphics::isPixelFormatSupported(PixelFormat format, uint32 usage)
  849. {
  850. format = getSizedFormat(format);
  851. auto vulkanFormat = Vulkan::getTextureFormat(format);
  852. VkFormatProperties formatProperties;
  853. vkGetPhysicalDeviceFormatProperties(physicalDevice, vulkanFormat.internalFormat, &formatProperties);
  854. VkFormatFeatureFlags featureFlags = formatProperties.optimalTilingFeatures;
  855. VkImageUsageFlags usageFlags = 0;
  856. if (!featureFlags)
  857. return false;
  858. if (usage & PIXELFORMATUSAGEFLAGS_SAMPLE)
  859. {
  860. usageFlags |= VK_IMAGE_USAGE_SAMPLED_BIT;
  861. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT))
  862. return false;
  863. }
  864. if (usage & PIXELFORMATUSAGE_LINEAR)
  865. {
  866. if (!(featureFlags & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT))
  867. return false;
  868. }
  869. if (usage & PIXELFORMATUSAGEFLAGS_RENDERTARGET)
  870. {
  871. if (isPixelFormatDepth(format) || isPixelFormatDepthStencil(format))
  872. {
  873. usageFlags |= VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  874. if (!(featureFlags & VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT))
  875. return false;
  876. }
  877. else
  878. {
  879. usageFlags |= VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  880. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT))
  881. return false;
  882. }
  883. }
  884. if (usage & PIXELFORMATUSAGEFLAGS_BLEND)
  885. {
  886. if (!(featureFlags & VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT))
  887. return false;
  888. }
  889. if (usage & PIXELFORMATUSAGEFLAGS_COMPUTEWRITE)
  890. {
  891. usageFlags |= VK_IMAGE_USAGE_STORAGE_BIT;
  892. if (!(featureFlags & VK_FORMAT_FEATURE_STORAGE_IMAGE_BIT))
  893. return false;
  894. }
  895. if (usage & PIXELFORMATUSAGEFLAGS_MSAA)
  896. {
  897. VkImageFormatProperties properties;
  898. if (vkGetPhysicalDeviceImageFormatProperties(physicalDevice, vulkanFormat.internalFormat, VK_IMAGE_TYPE_2D, VK_IMAGE_TILING_OPTIMAL, usageFlags, 0, &properties) != VK_SUCCESS)
  899. return false;
  900. if (static_cast<uint32_t>(properties.sampleCounts) == 1)
  901. return false;
  902. }
  903. return true;
  904. }
  905. Renderer Graphics::getRenderer() const
  906. {
  907. return RENDERER_VULKAN;
  908. }
  909. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Buffer *buffer, size_t offset, size_t size, data::ByteData *dest, size_t destoffset)
  910. {
  911. return new GraphicsReadback(this, method, buffer, offset, size, dest, destoffset);
  912. }
  913. graphics::GraphicsReadback *Graphics::newReadbackInternal(ReadbackMethod method, love::graphics::Texture *texture, int slice, int mipmap, const Rect &rect, image::ImageData *dest, int destx, int desty)
  914. {
  915. return new GraphicsReadback(this, method, texture, slice, mipmap, rect, dest, destx, desty);
  916. }
  917. graphics::ShaderStage *Graphics::newShaderStageInternal(ShaderStageType stage, const std::string &cachekey, const std::string &source, bool gles)
  918. {
  919. return new ShaderStage(this, stage, source, gles, cachekey);
  920. }
  921. graphics::Shader *Graphics::newShaderInternal(StrongRef<love::graphics::ShaderStage> stages[SHADERSTAGE_MAX_ENUM], const Shader::CompileOptions &options)
  922. {
  923. return new Shader(stages, options);
  924. }
  925. graphics::StreamBuffer *Graphics::newStreamBuffer(BufferUsage type, size_t size)
  926. {
  927. return new StreamBuffer(this, type, size);
  928. }
  929. bool Graphics::dispatch(love::graphics::Shader *shader, int x, int y, int z)
  930. {
  931. usedShadersInFrame.insert(computeShader);
  932. if (renderPassState.active)
  933. endRenderPass();
  934. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  935. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  936. // TODO: does this need any layout transitions?
  937. vkCmdDispatch(commandBuffers.at(currentFrame), (uint32) x, (uint32) y, (uint32) z);
  938. return true;
  939. }
  940. bool Graphics::dispatch(love::graphics::Shader *shader, love::graphics::Buffer *indirectargs, size_t argsoffset)
  941. {
  942. usedShadersInFrame.insert(computeShader);
  943. if (renderPassState.active)
  944. endRenderPass();
  945. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE, computeShader->getComputePipeline());
  946. computeShader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_COMPUTE);
  947. // TODO: does this need any layout transitions?
  948. vkCmdDispatchIndirect(commandBuffers.at(currentFrame), (VkBuffer) indirectargs->getHandle(), argsoffset);
  949. return true;
  950. }
  951. Matrix4 Graphics::computeDeviceProjection(const Matrix4 &projection, bool rendertotexture) const
  952. {
  953. uint32 flags = DEVICE_PROJECTION_DEFAULT;
  954. return calculateDeviceProjection(projection, flags);
  955. }
  956. void Graphics::setRenderTargetsInternal(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  957. {
  958. if (renderPassState.active)
  959. endRenderPass();
  960. bool isWindow = rts.getFirstTarget().texture == nullptr;
  961. if (isWindow)
  962. setDefaultRenderPass();
  963. else
  964. setRenderPass(rts, pixelw, pixelh, hasSRGBtexture);
  965. }
  966. // END IMPLEMENTATION OVERRIDDEN FUNCTIONS
  967. void Graphics::initDynamicState()
  968. {
  969. if (states.back().scissor)
  970. setScissor(states.back().scissorRect);
  971. else
  972. setScissor();
  973. vkCmdSetStencilWriteMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.writeMask);
  974. vkCmdSetStencilCompareMask(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.readMask);
  975. vkCmdSetStencilReference(commandBuffers.at(currentFrame), VK_STENCIL_FRONT_AND_BACK, states.back().stencil.value);
  976. if (optionalDeviceExtensions.extendedDynamicState)
  977. {
  978. vkCmdSetStencilOpEXT(
  979. commandBuffers.at(currentFrame),
  980. VK_STENCIL_FRONT_AND_BACK,
  981. VK_STENCIL_OP_KEEP, Vulkan::getStencilOp(states.back().stencil.action),
  982. VK_STENCIL_OP_KEEP, Vulkan::getCompareOp(getReversedCompareMode(states.back().stencil.compare)));
  983. vkCmdSetDepthCompareOpEXT(
  984. commandBuffers.at(currentFrame), Vulkan::getCompareOp(states.back().depthTest));
  985. vkCmdSetDepthWriteEnableEXT(
  986. commandBuffers.at(currentFrame), Vulkan::getBool(states.back().depthWrite));
  987. vkCmdSetFrontFaceEXT(
  988. commandBuffers.at(currentFrame), Vulkan::getFrontFace(states.back().winding));
  989. }
  990. }
  991. void Graphics::beginFrame()
  992. {
  993. vkWaitForFences(device, 1, &inFlightFences[currentFrame], VK_TRUE, UINT64_MAX);
  994. if (frameCounter >= USAGES_POLL_INTERVAL)
  995. {
  996. cleanupUnusedObjects();
  997. frameCounter = 0;
  998. }
  999. while (true)
  1000. {
  1001. VkResult result = vkAcquireNextImageKHR(device, swapChain, UINT64_MAX, imageAvailableSemaphores[currentFrame], VK_NULL_HANDLE, &imageIndex);
  1002. if (result == VK_ERROR_OUT_OF_DATE_KHR)
  1003. {
  1004. recreateSwapChain();
  1005. continue;
  1006. }
  1007. else if (result != VK_SUCCESS && result != VK_SUBOPTIMAL_KHR)
  1008. throw love::Exception("failed to acquire swap chain image");
  1009. break;
  1010. }
  1011. imageRequested = true;
  1012. for (auto &readbackCallback : readbackCallbacks.at(currentFrame))
  1013. readbackCallback();
  1014. readbackCallbacks.at(currentFrame).clear();
  1015. for (auto &cleanUpFn : cleanUpFunctions.at(currentFrame))
  1016. cleanUpFn();
  1017. cleanUpFunctions.at(currentFrame).clear();
  1018. startRecordingGraphicsCommands();
  1019. Vulkan::cmdTransitionImageLayout(
  1020. commandBuffers.at(currentFrame),
  1021. swapChainImages[imageIndex],
  1022. VK_IMAGE_LAYOUT_UNDEFINED,
  1023. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  1024. if (transitionColorDepthLayouts)
  1025. {
  1026. if (depthImage)
  1027. Vulkan::cmdTransitionImageLayout(
  1028. commandBuffers.at(currentFrame),
  1029. depthImage,
  1030. VK_IMAGE_LAYOUT_UNDEFINED,
  1031. VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL);
  1032. if (colorImage)
  1033. Vulkan::cmdTransitionImageLayout(
  1034. commandBuffers.at(currentFrame),
  1035. colorImage,
  1036. VK_IMAGE_LAYOUT_UNDEFINED,
  1037. VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  1038. transitionColorDepthLayouts = false;
  1039. }
  1040. Vulkan::resetShaderSwitches();
  1041. for (const auto shader : usedShadersInFrame)
  1042. shader->newFrame();
  1043. usedShadersInFrame.clear();
  1044. }
  1045. void Graphics::startRecordingGraphicsCommands()
  1046. {
  1047. VkCommandBufferBeginInfo beginInfo{};
  1048. beginInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_BEGIN_INFO;
  1049. beginInfo.flags = VK_COMMAND_BUFFER_USAGE_ONE_TIME_SUBMIT_BIT;
  1050. beginInfo.pInheritanceInfo = nullptr;
  1051. if (vkBeginCommandBuffer(commandBuffers.at(currentFrame), &beginInfo) != VK_SUCCESS)
  1052. throw love::Exception("failed to begin recording command buffer");
  1053. initDynamicState();
  1054. setDefaultRenderPass();
  1055. }
  1056. void Graphics::endRecordingGraphicsCommands() {
  1057. if (renderPassState.active)
  1058. endRenderPass();
  1059. if (vkEndCommandBuffer(commandBuffers.at(currentFrame)) != VK_SUCCESS)
  1060. throw love::Exception("failed to record command buffer");
  1061. }
  1062. const VkDeviceSize Graphics::getMinUniformBufferOffsetAlignment() const
  1063. {
  1064. return minUniformBufferOffsetAlignment;
  1065. }
  1066. VkCommandBuffer Graphics::getCommandBufferForDataTransfer()
  1067. {
  1068. if (renderPassState.active)
  1069. endRenderPass();
  1070. return commandBuffers.at(currentFrame);
  1071. }
  1072. void Graphics::queueCleanUp(std::function<void()> cleanUp)
  1073. {
  1074. cleanUpFunctions.at(currentFrame).push_back(cleanUp);
  1075. }
  1076. void Graphics::addReadbackCallback(std::function<void()> callback)
  1077. {
  1078. readbackCallbacks.at(currentFrame).push_back(callback);
  1079. }
  1080. graphics::Shader::BuiltinUniformData Graphics::getCurrentBuiltinUniformData()
  1081. {
  1082. love::graphics::Shader::BuiltinUniformData data;
  1083. data.transformMatrix = getTransform();
  1084. data.projectionMatrix = displayRotation * getDeviceProjection();
  1085. // The normal matrix is the transpose of the inverse of the rotation portion
  1086. // (top-left 3x3) of the transform matrix.
  1087. {
  1088. Matrix3 normalmatrix = Matrix3(data.transformMatrix).transposedInverse();
  1089. const float *e = normalmatrix.getElements();
  1090. for (int i = 0; i < 3; i++)
  1091. {
  1092. data.normalMatrix[i].x = e[i * 3 + 0];
  1093. data.normalMatrix[i].y = e[i * 3 + 1];
  1094. data.normalMatrix[i].z = e[i * 3 + 2];
  1095. data.normalMatrix[i].w = 0.0f;
  1096. }
  1097. }
  1098. // Store DPI scale in an unused component of another vector.
  1099. data.normalMatrix[0].w = (float)getCurrentDPIScale();
  1100. // Same with point size.
  1101. data.normalMatrix[1].w = getPointSize();
  1102. data.screenSizeParams.x = static_cast<float>(swapChainExtent.width);
  1103. data.screenSizeParams.y = static_cast<float>(swapChainExtent.height);
  1104. data.screenSizeParams.z = 1.0f;
  1105. data.screenSizeParams.w = 0.0f;
  1106. data.constantColor = getColor();
  1107. gammaCorrectColor(data.constantColor);
  1108. return data;
  1109. }
  1110. const OptionalDeviceExtensions &Graphics::getEnabledOptionalDeviceExtensions() const
  1111. {
  1112. return optionalDeviceExtensions;
  1113. }
  1114. const OptionalInstanceExtensions &Graphics::getEnabledOptionalInstanceExtensions() const
  1115. {
  1116. return optionalInstanceExtensions;
  1117. }
  1118. bool Graphics::checkValidationSupport()
  1119. {
  1120. uint32_t layerCount;
  1121. vkEnumerateInstanceLayerProperties(&layerCount, nullptr);
  1122. std::vector<VkLayerProperties> availableLayers(layerCount);
  1123. vkEnumerateInstanceLayerProperties(&layerCount, availableLayers.data());
  1124. for (const char *layerName : validationLayers)
  1125. {
  1126. bool layerFound = false;
  1127. for (const auto &layerProperties : availableLayers)
  1128. {
  1129. if (strcmp(layerName, layerProperties.layerName) == 0)
  1130. {
  1131. layerFound = true;
  1132. break;
  1133. }
  1134. }
  1135. if (!layerFound)
  1136. return false;
  1137. }
  1138. return true;
  1139. }
  1140. void Graphics::pickPhysicalDevice()
  1141. {
  1142. uint32_t deviceCount = 0;
  1143. vkEnumeratePhysicalDevices(instance, &deviceCount, nullptr);
  1144. if (deviceCount == 0)
  1145. throw love::Exception("failed to find GPUs with Vulkan support");
  1146. std::vector<VkPhysicalDevice> devices(deviceCount);
  1147. vkEnumeratePhysicalDevices(instance, &deviceCount, devices.data());
  1148. std::multimap<int, VkPhysicalDevice> candidates;
  1149. for (const auto &device : devices)
  1150. {
  1151. int score = rateDeviceSuitability(device);
  1152. candidates.insert(std::make_pair(score, device));
  1153. }
  1154. if (candidates.rbegin()->first > 0)
  1155. physicalDevice = candidates.rbegin()->second;
  1156. else
  1157. throw love::Exception("failed to find a suitable gpu");
  1158. VkPhysicalDeviceProperties properties;
  1159. vkGetPhysicalDeviceProperties(physicalDevice, &properties);
  1160. minUniformBufferOffsetAlignment = properties.limits.minUniformBufferOffsetAlignment;
  1161. deviceApiVersion = properties.apiVersion;
  1162. depthStencilFormat = findDepthFormat();
  1163. }
  1164. bool Graphics::checkDeviceExtensionSupport(VkPhysicalDevice device)
  1165. {
  1166. uint32_t extensionCount;
  1167. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, nullptr);
  1168. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1169. vkEnumerateDeviceExtensionProperties(device, nullptr, &extensionCount, availableExtensions.data());
  1170. std::set<std::string> requiredExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1171. for (const auto &extension : availableExtensions)
  1172. requiredExtensions.erase(extension.extensionName);
  1173. return requiredExtensions.empty();
  1174. }
  1175. // if the score is nonzero then the device is suitable.
  1176. // A higher rating means generally better performance
  1177. // if the score is 0 the device is unsuitable
  1178. int Graphics::rateDeviceSuitability(VkPhysicalDevice device)
  1179. {
  1180. VkPhysicalDeviceProperties deviceProperties;
  1181. VkPhysicalDeviceFeatures deviceFeatures;
  1182. vkGetPhysicalDeviceProperties(device, &deviceProperties);
  1183. vkGetPhysicalDeviceFeatures(device, &deviceFeatures);
  1184. int score = 1;
  1185. // optional
  1186. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_DISCRETE_GPU)
  1187. score += 1000;
  1188. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU)
  1189. score += 100;
  1190. if (deviceProperties.deviceType == VK_PHYSICAL_DEVICE_TYPE_VIRTUAL_GPU)
  1191. score += 10;
  1192. // definitely needed
  1193. QueueFamilyIndices indices = findQueueFamilies(device);
  1194. if (!indices.isComplete())
  1195. score = 0;
  1196. bool extensionsSupported = checkDeviceExtensionSupport(device);
  1197. if (!extensionsSupported)
  1198. score = 0;
  1199. if (extensionsSupported)
  1200. {
  1201. auto swapChainSupport = querySwapChainSupport(device);
  1202. bool swapChainAdequate = !swapChainSupport.formats.empty() && !swapChainSupport.presentModes.empty();
  1203. if (!swapChainAdequate)
  1204. score = 0;
  1205. }
  1206. if (!deviceFeatures.samplerAnisotropy)
  1207. score = 0;
  1208. if (!deviceFeatures.fillModeNonSolid)
  1209. score = 0;
  1210. return score;
  1211. }
  1212. QueueFamilyIndices Graphics::findQueueFamilies(VkPhysicalDevice device)
  1213. {
  1214. QueueFamilyIndices indices;
  1215. uint32_t queueFamilyCount = 0;
  1216. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, nullptr);
  1217. std::vector<VkQueueFamilyProperties> queueFamilies(queueFamilyCount);
  1218. vkGetPhysicalDeviceQueueFamilyProperties(device, &queueFamilyCount, queueFamilies.data());
  1219. int i = 0;
  1220. for (const auto &queueFamily : queueFamilies)
  1221. {
  1222. if ((queueFamily.queueFlags & VK_QUEUE_GRAPHICS_BIT) && (queueFamily.queueFlags & VK_QUEUE_COMPUTE_BIT))
  1223. indices.graphicsFamily = i;
  1224. VkBool32 presentSupport = false;
  1225. vkGetPhysicalDeviceSurfaceSupportKHR(device, i, surface, &presentSupport);
  1226. if (presentSupport)
  1227. indices.presentFamily = i;
  1228. if (indices.isComplete())
  1229. break;
  1230. i++;
  1231. }
  1232. return indices;
  1233. }
  1234. static void findOptionalDeviceExtensions(VkPhysicalDevice physicalDevice, OptionalDeviceExtensions &optionalDeviceExtensions)
  1235. {
  1236. uint32_t extensionCount;
  1237. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, nullptr);
  1238. std::vector<VkExtensionProperties> availableExtensions(extensionCount);
  1239. vkEnumerateDeviceExtensionProperties(physicalDevice, nullptr, &extensionCount, availableExtensions.data());
  1240. for (const auto &extension : availableExtensions)
  1241. {
  1242. if (strcmp(extension.extensionName, VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME) == 0)
  1243. optionalDeviceExtensions.extendedDynamicState = true;
  1244. if (strcmp(extension.extensionName, VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME) == 0)
  1245. optionalDeviceExtensions.memoryRequirements2 = true;
  1246. if (strcmp(extension.extensionName, VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME) == 0)
  1247. optionalDeviceExtensions.dedicatedAllocation = true;
  1248. if (strcmp(extension.extensionName, VK_EXT_MEMORY_BUDGET_EXTENSION_NAME) == 0)
  1249. optionalDeviceExtensions.memoryBudget = true;
  1250. if (strcmp(extension.extensionName, VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME) == 0)
  1251. optionalDeviceExtensions.shaderFloatControls = true;
  1252. if (strcmp(extension.extensionName, VK_KHR_SPIRV_1_4_EXTENSION_NAME) == 0)
  1253. optionalDeviceExtensions.spirv14 = true;
  1254. }
  1255. }
  1256. void Graphics::createLogicalDevice()
  1257. {
  1258. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1259. std::vector<VkDeviceQueueCreateInfo> queueCreateInfos;
  1260. std::set<uint32_t> uniqueQueueFamilies = {
  1261. indices.graphicsFamily.value,
  1262. indices.presentFamily.value
  1263. };
  1264. float queuePriority = 1.0f;
  1265. for (uint32_t queueFamily : uniqueQueueFamilies)
  1266. {
  1267. VkDeviceQueueCreateInfo queueCreateInfo{};
  1268. queueCreateInfo.sType = VK_STRUCTURE_TYPE_DEVICE_QUEUE_CREATE_INFO;
  1269. queueCreateInfo.queueFamilyIndex = queueFamily;
  1270. queueCreateInfo.queueCount = 1;
  1271. queueCreateInfo.pQueuePriorities = &queuePriority;
  1272. queueCreateInfos.push_back(queueCreateInfo);
  1273. }
  1274. findOptionalDeviceExtensions(physicalDevice, optionalDeviceExtensions);
  1275. // sanity check for dependencies.
  1276. if (optionalDeviceExtensions.extendedDynamicState && !optionalInstanceExtensions.physicalDeviceProperties2)
  1277. optionalDeviceExtensions.extendedDynamicState = false;
  1278. if (optionalDeviceExtensions.dedicatedAllocation && !optionalDeviceExtensions.memoryRequirements2)
  1279. optionalDeviceExtensions.dedicatedAllocation = false;
  1280. if (optionalDeviceExtensions.memoryBudget && !optionalInstanceExtensions.physicalDeviceProperties2)
  1281. optionalDeviceExtensions.memoryBudget = false;
  1282. if (optionalDeviceExtensions.spirv14 && !optionalDeviceExtensions.shaderFloatControls)
  1283. optionalDeviceExtensions.spirv14 = false;
  1284. if (optionalDeviceExtensions.spirv14 && deviceApiVersion < VK_API_VERSION_1_1)
  1285. optionalDeviceExtensions.spirv14 = false;
  1286. VkPhysicalDeviceFeatures deviceFeatures{};
  1287. deviceFeatures.samplerAnisotropy = VK_TRUE;
  1288. deviceFeatures.fillModeNonSolid = VK_TRUE;
  1289. VkDeviceCreateInfo createInfo{};
  1290. createInfo.sType = VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO;
  1291. createInfo.queueCreateInfoCount = static_cast<uint32_t>(queueCreateInfos.size());
  1292. createInfo.pQueueCreateInfos = queueCreateInfos.data();
  1293. createInfo.pEnabledFeatures = &deviceFeatures;
  1294. std::vector<const char*> enabledExtensions(deviceExtensions.begin(), deviceExtensions.end());
  1295. if (optionalDeviceExtensions.extendedDynamicState)
  1296. enabledExtensions.push_back(VK_EXT_EXTENDED_DYNAMIC_STATE_EXTENSION_NAME);
  1297. if (optionalDeviceExtensions.memoryRequirements2)
  1298. enabledExtensions.push_back(VK_KHR_GET_MEMORY_REQUIREMENTS_2_EXTENSION_NAME);
  1299. if (optionalDeviceExtensions.dedicatedAllocation)
  1300. enabledExtensions.push_back(VK_KHR_DEDICATED_ALLOCATION_EXTENSION_NAME);
  1301. if (optionalDeviceExtensions.memoryBudget)
  1302. enabledExtensions.push_back(VK_EXT_MEMORY_BUDGET_EXTENSION_NAME);
  1303. if (optionalDeviceExtensions.shaderFloatControls)
  1304. enabledExtensions.push_back(VK_KHR_SHADER_FLOAT_CONTROLS_EXTENSION_NAME);
  1305. if (optionalDeviceExtensions.spirv14)
  1306. enabledExtensions.push_back(VK_KHR_SPIRV_1_4_EXTENSION_NAME);
  1307. if (deviceApiVersion >= VK_API_VERSION_1_1)
  1308. enabledExtensions.push_back(VK_KHR_BIND_MEMORY_2_EXTENSION_NAME);
  1309. createInfo.enabledExtensionCount = static_cast<uint32_t>(enabledExtensions.size());
  1310. createInfo.ppEnabledExtensionNames = enabledExtensions.data();
  1311. if (isDebugEnabled())
  1312. {
  1313. createInfo.enabledLayerCount = static_cast<uint32_t>(validationLayers.size());
  1314. createInfo.ppEnabledLayerNames = validationLayers.data();
  1315. }
  1316. VkPhysicalDeviceExtendedDynamicStateFeaturesEXT extendedDynamicStateFeatures{};
  1317. extendedDynamicStateFeatures.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTENDED_DYNAMIC_STATE_FEATURES_EXT;
  1318. extendedDynamicStateFeatures.extendedDynamicState = VK_TRUE;
  1319. extendedDynamicStateFeatures.pNext = nullptr;
  1320. if (optionalDeviceExtensions.extendedDynamicState)
  1321. createInfo.pNext = &extendedDynamicStateFeatures;
  1322. if (vkCreateDevice(physicalDevice, &createInfo, nullptr, &device) != VK_SUCCESS)
  1323. throw love::Exception("failed to create logical device");
  1324. volkLoadDevice(device);
  1325. vkGetDeviceQueue(device, indices.graphicsFamily.value, 0, &graphicsQueue);
  1326. vkGetDeviceQueue(device, indices.presentFamily.value, 0, &presentQueue);
  1327. }
  1328. void Graphics::createPipelineCache()
  1329. {
  1330. VkPipelineCacheCreateInfo cacheInfo{};
  1331. cacheInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO;
  1332. if (vkCreatePipelineCache(device, &cacheInfo, nullptr, &pipelineCache) != VK_SUCCESS)
  1333. throw love::Exception("could not create pipeline cache");
  1334. }
  1335. void Graphics::initVMA()
  1336. {
  1337. VmaAllocatorCreateInfo allocatorCreateInfo = {};
  1338. allocatorCreateInfo.vulkanApiVersion = deviceApiVersion;
  1339. allocatorCreateInfo.physicalDevice = physicalDevice;
  1340. allocatorCreateInfo.device = device;
  1341. allocatorCreateInfo.instance = instance;
  1342. VmaVulkanFunctions vulkanFunctions{};
  1343. vulkanFunctions.vkGetInstanceProcAddr = vkGetInstanceProcAddr;
  1344. vulkanFunctions.vkGetDeviceProcAddr = vkGetDeviceProcAddr;
  1345. vulkanFunctions.vkGetPhysicalDeviceProperties = vkGetPhysicalDeviceProperties;
  1346. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties = vkGetPhysicalDeviceMemoryProperties;
  1347. vulkanFunctions.vkAllocateMemory = vkAllocateMemory;
  1348. vulkanFunctions.vkFreeMemory = vkFreeMemory;
  1349. vulkanFunctions.vkMapMemory = vkMapMemory;
  1350. vulkanFunctions.vkUnmapMemory = vkUnmapMemory;
  1351. vulkanFunctions.vkFlushMappedMemoryRanges = vkFlushMappedMemoryRanges;
  1352. vulkanFunctions.vkInvalidateMappedMemoryRanges = vkInvalidateMappedMemoryRanges;
  1353. vulkanFunctions.vkBindBufferMemory = vkBindBufferMemory;
  1354. vulkanFunctions.vkBindImageMemory = vkBindImageMemory;
  1355. vulkanFunctions.vkGetBufferMemoryRequirements = vkGetBufferMemoryRequirements;
  1356. vulkanFunctions.vkGetImageMemoryRequirements = vkGetImageMemoryRequirements;
  1357. vulkanFunctions.vkCreateBuffer = vkCreateBuffer;
  1358. vulkanFunctions.vkCreateImage = vkCreateImage;
  1359. vulkanFunctions.vkDestroyBuffer = vkDestroyBuffer;
  1360. vulkanFunctions.vkDestroyImage = vkDestroyImage;
  1361. vulkanFunctions.vkCmdCopyBuffer = vkCmdCopyBuffer;
  1362. vulkanFunctions.vkGetBufferMemoryRequirements2KHR = vkGetBufferMemoryRequirements2KHR;
  1363. vulkanFunctions.vkGetImageMemoryRequirements2KHR = vkGetImageMemoryRequirements2KHR;
  1364. vulkanFunctions.vkBindBufferMemory2KHR = vkBindBufferMemory2KHR;
  1365. vulkanFunctions.vkBindImageMemory2KHR = vkBindImageMemory2KHR;
  1366. vulkanFunctions.vkGetPhysicalDeviceMemoryProperties2KHR = vkGetPhysicalDeviceMemoryProperties2KHR;
  1367. vulkanFunctions.vkGetDeviceBufferMemoryRequirements = vkGetDeviceBufferMemoryRequirements;
  1368. vulkanFunctions.vkGetDeviceImageMemoryRequirements = vkGetDeviceImageMemoryRequirements;
  1369. allocatorCreateInfo.pVulkanFunctions = &vulkanFunctions;
  1370. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXTERNALLY_SYNCHRONIZED_BIT;
  1371. if (optionalDeviceExtensions.dedicatedAllocation)
  1372. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_KHR_DEDICATED_ALLOCATION_BIT;
  1373. if (optionalDeviceExtensions.memoryBudget)
  1374. allocatorCreateInfo.flags |= VMA_ALLOCATOR_CREATE_EXT_MEMORY_BUDGET_BIT;
  1375. if (vmaCreateAllocator(&allocatorCreateInfo, &vmaAllocator) != VK_SUCCESS)
  1376. throw love::Exception("failed to create vma allocator");
  1377. }
  1378. void Graphics::createSurface()
  1379. {
  1380. auto window = Module::getInstance<love::window::Window>(M_WINDOW);
  1381. const void *handle = window->getHandle();
  1382. if (SDL_Vulkan_CreateSurface((SDL_Window*)handle, instance, &surface) != SDL_TRUE)
  1383. throw love::Exception("failed to create window surface");
  1384. }
  1385. SwapChainSupportDetails Graphics::querySwapChainSupport(VkPhysicalDevice device)
  1386. {
  1387. SwapChainSupportDetails details;
  1388. vkGetPhysicalDeviceSurfaceCapabilitiesKHR(device, surface, &details.capabilities);
  1389. uint32_t formatCount;
  1390. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, nullptr);
  1391. if (formatCount != 0)
  1392. {
  1393. details.formats.resize(formatCount);
  1394. vkGetPhysicalDeviceSurfaceFormatsKHR(device, surface, &formatCount, details.formats.data());
  1395. }
  1396. uint32_t presentModeCount;
  1397. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, nullptr);
  1398. if (presentModeCount != 0)
  1399. {
  1400. details.presentModes.resize(presentModeCount);
  1401. vkGetPhysicalDeviceSurfacePresentModesKHR(device, surface, &presentModeCount, details.presentModes.data());
  1402. }
  1403. return details;
  1404. }
  1405. void Graphics::createSwapChain()
  1406. {
  1407. SwapChainSupportDetails swapChainSupport = querySwapChainSupport(physicalDevice);
  1408. VkSurfaceFormatKHR surfaceFormat = chooseSwapSurfaceFormat(swapChainSupport.formats);
  1409. VkPresentModeKHR presentMode = chooseSwapPresentMode(swapChainSupport.presentModes);
  1410. VkExtent2D extent = chooseSwapExtent(swapChainSupport.capabilities);
  1411. if ((swapChainSupport.capabilities.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR) ||
  1412. (swapChainSupport.capabilities.currentTransform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR))
  1413. {
  1414. uint32_t width, height;
  1415. width = extent.width;
  1416. height = extent.height;
  1417. extent.width = height;
  1418. extent.height = width;
  1419. }
  1420. auto currentTransform = swapChainSupport.capabilities.currentTransform;
  1421. constexpr float PI = 3.14159265358979323846f;
  1422. float angle = 0.0f;
  1423. if (currentTransform & VK_SURFACE_TRANSFORM_IDENTITY_BIT_KHR)
  1424. angle = 0.0f;
  1425. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_90_BIT_KHR)
  1426. angle = -PI / 2.0f;
  1427. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_180_BIT_KHR)
  1428. angle = -PI;
  1429. else if (currentTransform & VK_SURFACE_TRANSFORM_ROTATE_270_BIT_KHR)
  1430. angle = -3.0f * PI / 2.0f;
  1431. float data[] = {
  1432. cosf(angle), -sinf(angle), 0.0f, 0.0f,
  1433. sinf(angle), cosf(angle), 0.0f, 0.0f,
  1434. 0.0f, 0.0f, 1.0f, 0.0f,
  1435. 0.0f, 0.0f, 0.0f, 1.0f,
  1436. };
  1437. displayRotation = Matrix4(data);
  1438. uint32_t imageCount = swapChainSupport.capabilities.minImageCount + 1;
  1439. if (swapChainSupport.capabilities.maxImageCount > 0 && imageCount > swapChainSupport.capabilities.maxImageCount)
  1440. imageCount = swapChainSupport.capabilities.maxImageCount;
  1441. VkSwapchainCreateInfoKHR createInfo{};
  1442. createInfo.sType = VK_STRUCTURE_TYPE_SWAPCHAIN_CREATE_INFO_KHR;
  1443. createInfo.surface = surface;
  1444. createInfo.minImageCount = imageCount;
  1445. createInfo.imageFormat = surfaceFormat.format;
  1446. createInfo.imageColorSpace = surfaceFormat.colorSpace;
  1447. createInfo.imageExtent = extent;
  1448. createInfo.imageArrayLayers = 1;
  1449. createInfo.imageUsage = VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT | VK_IMAGE_USAGE_TRANSFER_SRC_BIT;
  1450. QueueFamilyIndices indices = findQueueFamilies(physicalDevice);
  1451. uint32_t queueFamilyIndices[] = { indices.graphicsFamily.value, indices.presentFamily.value };
  1452. if (indices.graphicsFamily.value != indices.presentFamily.value)
  1453. {
  1454. createInfo.imageSharingMode = VK_SHARING_MODE_CONCURRENT;
  1455. createInfo.queueFamilyIndexCount = 2;
  1456. createInfo.pQueueFamilyIndices = queueFamilyIndices;
  1457. }
  1458. else
  1459. {
  1460. createInfo.imageSharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1461. createInfo.queueFamilyIndexCount = 0;
  1462. createInfo.pQueueFamilyIndices = nullptr;
  1463. }
  1464. createInfo.preTransform = swapChainSupport.capabilities.currentTransform;
  1465. createInfo.compositeAlpha = chooseCompositeAlpha(swapChainSupport.capabilities);
  1466. createInfo.presentMode = presentMode;
  1467. createInfo.clipped = VK_TRUE;
  1468. createInfo.oldSwapchain = VK_NULL_HANDLE;
  1469. if (vkCreateSwapchainKHR(device, &createInfo, nullptr, &swapChain) != VK_SUCCESS)
  1470. throw love::Exception("failed to create swap chain");
  1471. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, nullptr);
  1472. swapChainImages.resize(imageCount);
  1473. vkGetSwapchainImagesKHR(device, swapChain, &imageCount, swapChainImages.data());
  1474. swapChainImageFormat = surfaceFormat.format;
  1475. swapChainExtent = extent;
  1476. preTransform = swapChainSupport.capabilities.currentTransform;
  1477. }
  1478. VkSurfaceFormatKHR Graphics::chooseSwapSurfaceFormat(const std::vector<VkSurfaceFormatKHR> &availableFormats)
  1479. {
  1480. std::vector<VkFormat> formatOrder;
  1481. // TODO: turn off GammaCorrect if a sRGB format can't be found?
  1482. // TODO: does every platform have these formats?
  1483. if (isGammaCorrect())
  1484. {
  1485. formatOrder = {
  1486. VK_FORMAT_B8G8R8A8_SRGB,
  1487. VK_FORMAT_R8G8B8A8_SRGB,
  1488. };
  1489. }
  1490. else
  1491. {
  1492. formatOrder = {
  1493. VK_FORMAT_B8G8R8A8_UNORM,
  1494. VK_FORMAT_R8G8B8A8_SNORM,
  1495. };
  1496. }
  1497. for (const auto format : formatOrder)
  1498. {
  1499. for (const auto &availableFormat : availableFormats)
  1500. {
  1501. if (availableFormat.format == format && availableFormat.colorSpace == VK_COLORSPACE_SRGB_NONLINEAR_KHR)
  1502. return availableFormat;
  1503. }
  1504. }
  1505. return availableFormats[0];
  1506. }
  1507. VkPresentModeKHR Graphics::chooseSwapPresentMode(const std::vector<VkPresentModeKHR> &availablePresentModes)
  1508. {
  1509. const auto begin = availablePresentModes.begin();
  1510. const auto end = availablePresentModes.end();
  1511. switch (vsync)
  1512. {
  1513. case -1:
  1514. if (std::find(begin, end, VK_PRESENT_MODE_FIFO_RELAXED_KHR) != end)
  1515. return VK_PRESENT_MODE_FIFO_RELAXED_KHR;
  1516. else
  1517. return VK_PRESENT_MODE_FIFO_KHR;
  1518. case 0:
  1519. // Mailbox mode might be better than immediate mode for a lot of people.
  1520. // But on at least some systems it acts as if vsync is enabled
  1521. // https://github.com/love2d/love/issues/1852
  1522. // TODO: is that a bug in love's code or the graphics driver / compositor?
  1523. // Should love expose mailbox mode in an API to users in some manner,
  1524. // instead of trying to guess what to do?
  1525. if (std::find(begin, end, VK_PRESENT_MODE_IMMEDIATE_KHR) != end)
  1526. return VK_PRESENT_MODE_IMMEDIATE_KHR;
  1527. else if (std::find(begin, end, VK_PRESENT_MODE_MAILBOX_KHR) != end)
  1528. return VK_PRESENT_MODE_MAILBOX_KHR;
  1529. else
  1530. return VK_PRESENT_MODE_FIFO_KHR;
  1531. default:
  1532. // TODO: support for swap interval = 2, etc?
  1533. return VK_PRESENT_MODE_FIFO_KHR;
  1534. }
  1535. }
  1536. static uint32_t clampuint32_t(uint32_t value, uint32_t min, uint32_t max)
  1537. {
  1538. if (value < min)
  1539. return min;
  1540. if (value > max)
  1541. return max;
  1542. return value;
  1543. }
  1544. VkExtent2D Graphics::chooseSwapExtent(const VkSurfaceCapabilitiesKHR &capabilities)
  1545. {
  1546. if (capabilities.currentExtent.width != UINT32_MAX)
  1547. return capabilities.currentExtent;
  1548. else
  1549. {
  1550. VkExtent2D actualExtent = {
  1551. static_cast<uint32_t>(pixelWidth),
  1552. static_cast<uint32_t>(pixelHeight)
  1553. };
  1554. actualExtent.width = clampuint32_t(actualExtent.width, capabilities.minImageExtent.width, capabilities.maxImageExtent.width);
  1555. actualExtent.height = clampuint32_t(actualExtent.height, capabilities.minImageExtent.height, capabilities.maxImageExtent.height);
  1556. return actualExtent;
  1557. }
  1558. }
  1559. VkCompositeAlphaFlagBitsKHR Graphics::chooseCompositeAlpha(const VkSurfaceCapabilitiesKHR &capabilities)
  1560. {
  1561. if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR)
  1562. return VK_COMPOSITE_ALPHA_OPAQUE_BIT_KHR;
  1563. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR)
  1564. return VK_COMPOSITE_ALPHA_INHERIT_BIT_KHR;
  1565. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR)
  1566. return VK_COMPOSITE_ALPHA_PRE_MULTIPLIED_BIT_KHR;
  1567. else if (capabilities.supportedCompositeAlpha & VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR)
  1568. return VK_COMPOSITE_ALPHA_POST_MULTIPLIED_BIT_KHR;
  1569. else
  1570. throw love::Exception("failed to find composite alpha");
  1571. }
  1572. void Graphics::createImageViews()
  1573. {
  1574. swapChainImageViews.resize(swapChainImages.size());
  1575. for (size_t i = 0; i < swapChainImages.size(); i++)
  1576. {
  1577. VkImageViewCreateInfo createInfo{};
  1578. createInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  1579. createInfo.image = swapChainImages.at(i);
  1580. createInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  1581. createInfo.format = swapChainImageFormat;
  1582. createInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  1583. createInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  1584. createInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  1585. createInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  1586. createInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  1587. createInfo.subresourceRange.baseMipLevel = 0;
  1588. createInfo.subresourceRange.levelCount = 1;
  1589. createInfo.subresourceRange.baseArrayLayer = 0;
  1590. createInfo.subresourceRange.layerCount = 1;
  1591. if (vkCreateImageView(device, &createInfo, nullptr, &swapChainImageViews.at(i)) != VK_SUCCESS)
  1592. throw love::Exception("failed to create image views");
  1593. }
  1594. }
  1595. void Graphics::createScreenshotCallbackBuffers()
  1596. {
  1597. screenshotReadbackBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  1598. for (uint32_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  1599. {
  1600. VkBufferCreateInfo bufferInfo{};
  1601. bufferInfo.sType = VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO;
  1602. bufferInfo.size = 4ll * swapChainExtent.width * swapChainExtent.height;
  1603. bufferInfo.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT;
  1604. bufferInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1605. VmaAllocationCreateInfo allocCreateInfo{};
  1606. allocCreateInfo.usage = VMA_MEMORY_USAGE_AUTO;
  1607. allocCreateInfo.flags = VMA_ALLOCATION_CREATE_HOST_ACCESS_RANDOM_BIT | VMA_ALLOCATION_CREATE_MAPPED_BIT;
  1608. auto result = vmaCreateBuffer(
  1609. vmaAllocator,
  1610. &bufferInfo,
  1611. &allocCreateInfo,
  1612. &screenshotReadbackBuffers.at(i).buffer,
  1613. &screenshotReadbackBuffers.at(i).allocation,
  1614. &screenshotReadbackBuffers.at(i).allocationInfo);
  1615. if (result != VK_SUCCESS)
  1616. throw love::Exception("failed to create screenshot readback buffer");
  1617. VkImageCreateInfo imageInfo{};
  1618. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  1619. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  1620. imageInfo.format = VK_FORMAT_R8G8B8A8_SRGB;
  1621. imageInfo.extent = {
  1622. swapChainExtent.width,
  1623. swapChainExtent.height,
  1624. 1
  1625. };
  1626. imageInfo.mipLevels = 1;
  1627. imageInfo.arrayLayers = 1;
  1628. imageInfo.samples = VK_SAMPLE_COUNT_1_BIT;
  1629. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  1630. imageInfo.usage = VK_IMAGE_USAGE_TRANSFER_SRC_BIT | VK_IMAGE_USAGE_TRANSFER_DST_BIT;
  1631. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  1632. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  1633. VmaAllocationCreateInfo imageAllocCreateInfo{};
  1634. result = vmaCreateImage(
  1635. vmaAllocator,
  1636. &imageInfo,
  1637. &imageAllocCreateInfo,
  1638. &screenshotReadbackBuffers.at(i).image,
  1639. &screenshotReadbackBuffers.at(i).imageAllocation,
  1640. nullptr);
  1641. if (result != VK_SUCCESS)
  1642. throw love::Exception("failed to create screenshot readback image");
  1643. }
  1644. }
  1645. VkFramebuffer Graphics::createFramebuffer(FramebufferConfiguration &configuration)
  1646. {
  1647. std::vector<VkImageView> attachments;
  1648. for (const auto &colorView : configuration.colorViews)
  1649. attachments.push_back(colorView);
  1650. if (configuration.staticData.depthView)
  1651. attachments.push_back(configuration.staticData.depthView);
  1652. if (configuration.staticData.resolveView)
  1653. attachments.push_back(configuration.staticData.resolveView);
  1654. VkFramebufferCreateInfo createInfo{};
  1655. createInfo.sType = VK_STRUCTURE_TYPE_FRAMEBUFFER_CREATE_INFO;
  1656. createInfo.renderPass = configuration.staticData.renderPass;
  1657. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1658. createInfo.pAttachments = attachments.data();
  1659. createInfo.width = configuration.staticData.width;
  1660. createInfo.height = configuration.staticData.height;
  1661. createInfo.layers = 1;
  1662. VkFramebuffer frameBuffer;
  1663. if (vkCreateFramebuffer(device, &createInfo, nullptr, &frameBuffer) != VK_SUCCESS)
  1664. throw love::Exception("failed to create framebuffer");
  1665. return frameBuffer;
  1666. }
  1667. VkFramebuffer Graphics::getFramebuffer(FramebufferConfiguration &configuration)
  1668. {
  1669. VkFramebuffer framebuffer;
  1670. auto it = framebuffers.find(configuration);
  1671. if (it != framebuffers.end())
  1672. framebuffer = it->second;
  1673. else
  1674. {
  1675. framebuffer = createFramebuffer(configuration);
  1676. framebuffers[configuration] = framebuffer;
  1677. }
  1678. framebufferUsages[framebuffer] = true;
  1679. return framebuffer;
  1680. }
  1681. void Graphics::createDefaultShaders()
  1682. {
  1683. for (int i = 0; i < Shader::STANDARD_MAX_ENUM; i++)
  1684. {
  1685. auto stype = (Shader::StandardShader)i;
  1686. if (!Shader::standardShaders[i])
  1687. {
  1688. std::vector<std::string> stages;
  1689. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_VERTEX));
  1690. stages.push_back(Shader::getDefaultCode(stype, SHADERSTAGE_PIXEL));
  1691. Shader::standardShaders[i] = newShader(stages, {});
  1692. }
  1693. }
  1694. }
  1695. VkRenderPass Graphics::createRenderPass(RenderPassConfiguration &configuration)
  1696. {
  1697. VkSubpassDescription subPass{};
  1698. subPass.pipelineBindPoint = VK_PIPELINE_BIND_POINT_GRAPHICS;
  1699. std::vector<VkAttachmentDescription> attachments;
  1700. std::vector<VkAttachmentReference> colorAttachmentRefs;
  1701. uint32_t attachment = 0;
  1702. for (const auto &colorAttachment : configuration.colorAttachments)
  1703. {
  1704. VkAttachmentReference reference{};
  1705. reference.attachment = attachment++;
  1706. reference.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1707. colorAttachmentRefs.push_back(reference);
  1708. VkAttachmentDescription colorDescription{};
  1709. colorDescription.format = colorAttachment.format;
  1710. colorDescription.samples = colorAttachment.msaaSamples;
  1711. colorDescription.loadOp = colorAttachment.loadOp;
  1712. colorDescription.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1713. colorDescription.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1714. colorDescription.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1715. colorDescription.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1716. colorDescription.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1717. attachments.push_back(colorDescription);
  1718. }
  1719. subPass.colorAttachmentCount = static_cast<uint32_t>(colorAttachmentRefs.size());
  1720. subPass.pColorAttachments = colorAttachmentRefs.data();
  1721. VkAttachmentReference depthStencilAttachmentRef{};
  1722. if (configuration.staticData.depthStencilAttachment.format != VK_FORMAT_UNDEFINED)
  1723. {
  1724. depthStencilAttachmentRef.attachment = attachment++;
  1725. depthStencilAttachmentRef.layout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1726. subPass.pDepthStencilAttachment = &depthStencilAttachmentRef;
  1727. VkAttachmentDescription depthStencilAttachment{};
  1728. depthStencilAttachment.format = configuration.staticData.depthStencilAttachment.format;
  1729. depthStencilAttachment.samples = configuration.staticData.depthStencilAttachment.msaaSamples;
  1730. depthStencilAttachment.loadOp = configuration.staticData.depthStencilAttachment.depthLoadOp;
  1731. depthStencilAttachment.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1732. depthStencilAttachment.stencilLoadOp = configuration.staticData.depthStencilAttachment.stencilLoadOp;
  1733. depthStencilAttachment.stencilStoreOp = VK_ATTACHMENT_STORE_OP_STORE;
  1734. depthStencilAttachment.initialLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1735. depthStencilAttachment.finalLayout = VK_IMAGE_LAYOUT_DEPTH_STENCIL_ATTACHMENT_OPTIMAL;
  1736. attachments.push_back(depthStencilAttachment);
  1737. }
  1738. VkAttachmentReference colorAttachmentResolveRef{};
  1739. if (configuration.staticData.resolve)
  1740. {
  1741. colorAttachmentResolveRef.attachment = attachment++;
  1742. colorAttachmentResolveRef.layout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1743. subPass.pResolveAttachments = &colorAttachmentResolveRef;
  1744. VkAttachmentDescription colorAttachmentResolve{};
  1745. colorAttachmentResolve.format = configuration.colorAttachments.at(0).format;
  1746. colorAttachmentResolve.samples = VK_SAMPLE_COUNT_1_BIT;
  1747. colorAttachmentResolve.loadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1748. colorAttachmentResolve.storeOp = VK_ATTACHMENT_STORE_OP_STORE;
  1749. colorAttachmentResolve.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_DONT_CARE;
  1750. colorAttachmentResolve.stencilStoreOp = VK_ATTACHMENT_STORE_OP_DONT_CARE;
  1751. colorAttachmentResolve.initialLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1752. colorAttachmentResolve.finalLayout = VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL;
  1753. attachments.push_back(colorAttachmentResolve);
  1754. }
  1755. VkSubpassDependency dependency{};
  1756. dependency.srcSubpass = VK_SUBPASS_EXTERNAL;
  1757. dependency.dstSubpass = 0;
  1758. dependency.srcStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT | VK_PIPELINE_STAGE_TRANSFER_BIT;
  1759. dependency.srcAccessMask = VK_ACCESS_TRANSFER_WRITE_BIT;
  1760. dependency.dstStageMask = VK_PIPELINE_STAGE_EARLY_FRAGMENT_TESTS_BIT;
  1761. dependency.dstAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1762. VkSubpassDependency readbackDependency{};
  1763. readbackDependency.srcSubpass = 0;
  1764. readbackDependency.dstSubpass = VK_SUBPASS_EXTERNAL;
  1765. readbackDependency.srcStageMask = VK_PIPELINE_STAGE_LATE_FRAGMENT_TESTS_BIT;
  1766. readbackDependency.srcAccessMask = VK_ACCESS_DEPTH_STENCIL_ATTACHMENT_WRITE_BIT;
  1767. readbackDependency.dstStageMask = VK_PIPELINE_STAGE_TRANSFER_BIT;
  1768. readbackDependency.dstAccessMask = VK_ACCESS_TRANSFER_READ_BIT;
  1769. std::array<VkSubpassDependency, 2> dependencies = { dependency, readbackDependency };
  1770. VkRenderPassCreateInfo createInfo{};
  1771. createInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_CREATE_INFO;
  1772. createInfo.attachmentCount = static_cast<uint32_t>(attachments.size());
  1773. createInfo.pAttachments = attachments.data();
  1774. createInfo.subpassCount = 1;
  1775. createInfo.pSubpasses = &subPass;
  1776. createInfo.dependencyCount = static_cast<uint32_t>(dependencies.size());
  1777. createInfo.pDependencies = dependencies.data();
  1778. VkRenderPass renderPass;
  1779. if (vkCreateRenderPass(device, &createInfo, nullptr, &renderPass) != VK_SUCCESS)
  1780. throw love::Exception("failed to create render pass");
  1781. return renderPass;
  1782. }
  1783. VkRenderPass Graphics::getRenderPass(RenderPassConfiguration &configuration)
  1784. {
  1785. VkRenderPass renderPass;
  1786. auto it = renderPasses.find(configuration);
  1787. if (it != renderPasses.end())
  1788. renderPass = it->second;
  1789. else
  1790. {
  1791. renderPass = createRenderPass(configuration);
  1792. renderPasses[configuration] = renderPass;
  1793. }
  1794. renderPassUsages[renderPass] = true;
  1795. return renderPass;
  1796. }
  1797. void Graphics::createVulkanVertexFormat(
  1798. VertexAttributes vertexAttributes,
  1799. std::vector<VkVertexInputBindingDescription> &bindingDescriptions,
  1800. std::vector<VkVertexInputAttributeDescription> &attributeDescriptions)
  1801. {
  1802. std::set<uint32_t> usedBuffers;
  1803. auto enableBits = vertexAttributes.enableBits;
  1804. auto allBits = enableBits;
  1805. bool usesColor = false;
  1806. bool usesTexCoord = false;
  1807. uint8_t highestBufferBinding = 0;
  1808. uint32_t i = 0;
  1809. while (allBits)
  1810. {
  1811. uint32 bit = 1u << i;
  1812. if (enableBits & bit)
  1813. {
  1814. if (i == ATTRIB_TEXCOORD)
  1815. usesTexCoord = true;
  1816. if (i == ATTRIB_COLOR)
  1817. usesColor = true;
  1818. auto attrib = vertexAttributes.attribs[i];
  1819. auto bufferBinding = attrib.bufferIndex;
  1820. if (usedBuffers.find(bufferBinding) == usedBuffers.end())
  1821. {
  1822. usedBuffers.insert(bufferBinding);
  1823. VkVertexInputBindingDescription bindingDescription{};
  1824. bindingDescription.binding = bufferBinding;
  1825. if (vertexAttributes.instanceBits & (1u << bufferBinding))
  1826. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_INSTANCE;
  1827. else
  1828. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1829. bindingDescription.stride = vertexAttributes.bufferLayouts[bufferBinding].stride;
  1830. bindingDescriptions.push_back(bindingDescription);
  1831. highestBufferBinding = std::max(highestBufferBinding, bufferBinding);
  1832. }
  1833. VkVertexInputAttributeDescription attributeDescription{};
  1834. attributeDescription.location = i;
  1835. attributeDescription.binding = bufferBinding;
  1836. attributeDescription.offset = attrib.offsetFromVertex;
  1837. attributeDescription.format = Vulkan::getVulkanVertexFormat(attrib.format);
  1838. attributeDescriptions.push_back(attributeDescription);
  1839. }
  1840. i++;
  1841. allBits >>= 1;
  1842. }
  1843. if (!usesTexCoord)
  1844. {
  1845. // FIXME: is there a case where gaps happen between buffer bindings?
  1846. // then this doesn't work. We might need to enable null buffers again.
  1847. const auto constantTexCoordBufferBinding = ++highestBufferBinding;
  1848. VkVertexInputBindingDescription bindingDescription{};
  1849. bindingDescription.binding = constantTexCoordBufferBinding;
  1850. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1851. bindingDescription.stride = 0; // no stride, will always read the same coord multiple times.
  1852. bindingDescriptions.push_back(bindingDescription);
  1853. VkVertexInputAttributeDescription attributeDescription{};
  1854. attributeDescription.binding = constantTexCoordBufferBinding;
  1855. attributeDescription.location = ATTRIB_TEXCOORD;
  1856. attributeDescription.offset = 0;
  1857. attributeDescription.format = VK_FORMAT_R32G32_SFLOAT;
  1858. attributeDescriptions.push_back(attributeDescription);
  1859. }
  1860. if (!usesColor)
  1861. {
  1862. // FIXME: is there a case where gaps happen between buffer bindings?
  1863. // then this doesn't work. We might need to enable null buffers again.
  1864. const auto constantColorBufferBinding = ++highestBufferBinding;
  1865. VkVertexInputBindingDescription bindingDescription{};
  1866. bindingDescription.binding = constantColorBufferBinding;
  1867. bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
  1868. bindingDescription.stride = 0; // no stride, will always read the same color multiple times.
  1869. bindingDescriptions.push_back(bindingDescription);
  1870. VkVertexInputAttributeDescription attributeDescription{};
  1871. attributeDescription.binding = constantColorBufferBinding;
  1872. attributeDescription.location = ATTRIB_COLOR;
  1873. attributeDescription.offset = 0;
  1874. attributeDescription.format = VK_FORMAT_R32G32B32A32_SFLOAT;
  1875. attributeDescriptions.push_back(attributeDescription);
  1876. }
  1877. }
  1878. void Graphics::prepareDraw(const VertexAttributes &attributes, const BufferBindings &buffers, graphics::Texture *texture, PrimitiveType primitiveType, CullMode cullmode)
  1879. {
  1880. if (!renderPassState.active)
  1881. startRenderPass();
  1882. usedShadersInFrame.insert((dynamic_cast<Shader*>(Shader::current)));
  1883. GraphicsPipelineConfiguration configuration{};
  1884. configuration.renderPass = renderPassState.beginInfo.renderPass;
  1885. configuration.vertexAttributes = attributes;
  1886. configuration.shader = (Shader*)Shader::current;
  1887. configuration.wireFrame = states.back().wireframe;
  1888. configuration.blendState = states.back().blend;
  1889. configuration.colorChannelMask = states.back().colorMask;
  1890. configuration.msaaSamples = renderPassState.msaa;
  1891. configuration.numColorAttachments = renderPassState.numColorAttachments;
  1892. configuration.primitiveType = primitiveType;
  1893. if (optionalDeviceExtensions.extendedDynamicState)
  1894. vkCmdSetCullModeEXT(commandBuffers.at(currentFrame), Vulkan::getCullMode(cullmode));
  1895. else
  1896. {
  1897. configuration.dynamicState.winding = states.back().winding;
  1898. configuration.dynamicState.depthState.compare = states.back().depthTest;
  1899. configuration.dynamicState.depthState.write = states.back().depthWrite;
  1900. configuration.dynamicState.stencilAction = states.back().stencil.action;
  1901. configuration.dynamicState.stencilCompare = states.back().stencil.compare;
  1902. configuration.dynamicState.cullmode = cullmode;
  1903. }
  1904. std::vector<VkBuffer> bufferVector;
  1905. std::vector<VkDeviceSize> offsets;
  1906. for (uint32_t i = 0; i < VertexAttributes::MAX; i++)
  1907. {
  1908. if (buffers.useBits & (1u << i))
  1909. {
  1910. bufferVector.push_back((VkBuffer)buffers.info[i].buffer->getHandle());
  1911. offsets.push_back((VkDeviceSize)buffers.info[i].offset);
  1912. }
  1913. }
  1914. if (!(attributes.enableBits & (1u << ATTRIB_TEXCOORD)))
  1915. {
  1916. bufferVector.push_back((VkBuffer)defaultConstantTexCoord->getHandle());
  1917. offsets.push_back((VkDeviceSize)0);
  1918. }
  1919. if (!(attributes.enableBits & (1u << ATTRIB_COLOR)))
  1920. {
  1921. bufferVector.push_back((VkBuffer)defaultConstantColor->getHandle());
  1922. offsets.push_back((VkDeviceSize)0);
  1923. }
  1924. configuration.shader->setMainTex(texture);
  1925. ensureGraphicsPipelineConfiguration(configuration);
  1926. configuration.shader->cmdPushDescriptorSets(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS);
  1927. vkCmdBindVertexBuffers(commandBuffers.at(currentFrame), 0, static_cast<uint32_t>(bufferVector.size()), bufferVector.data(), offsets.data());
  1928. }
  1929. void Graphics::setDefaultRenderPass()
  1930. {
  1931. uint32_t numClearValues = 2;
  1932. renderPassState.clearColors.resize(numClearValues);
  1933. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  1934. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  1935. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  1936. renderPassState.beginInfo.renderArea.offset = { 0, 0 };
  1937. renderPassState.beginInfo.renderArea.extent = swapChainExtent;
  1938. renderPassState.beginInfo.clearValueCount = numClearValues;
  1939. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  1940. renderPassState.isWindow = true;
  1941. renderPassState.pipeline = VK_NULL_HANDLE;
  1942. renderPassState.width = static_cast<float>(swapChainExtent.width);
  1943. renderPassState.height = static_cast<float>(swapChainExtent.height);
  1944. renderPassState.msaa = msaaSamples;
  1945. renderPassState.numColorAttachments = 1;
  1946. renderPassState.transitionImages.clear();
  1947. RenderPassConfiguration renderPassConfiguration{};
  1948. renderPassConfiguration.colorAttachments.push_back({ swapChainImageFormat, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples });
  1949. renderPassConfiguration.staticData.depthStencilAttachment = { depthStencilFormat, VK_ATTACHMENT_LOAD_OP_LOAD, VK_ATTACHMENT_LOAD_OP_LOAD, msaaSamples };
  1950. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1951. renderPassConfiguration.staticData.resolve = false;
  1952. else
  1953. renderPassConfiguration.staticData.resolve = true;
  1954. FramebufferConfiguration framebufferConfiguration{};
  1955. framebufferConfiguration.staticData.depthView = depthImageView;
  1956. framebufferConfiguration.staticData.width = swapChainExtent.width;
  1957. framebufferConfiguration.staticData.height = swapChainExtent.height;
  1958. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  1959. {
  1960. framebufferConfiguration.colorViews.push_back(swapChainImageViews.at(imageIndex));
  1961. framebufferConfiguration.staticData.resolveView = VK_NULL_HANDLE;
  1962. }
  1963. else
  1964. {
  1965. framebufferConfiguration.colorViews.push_back(colorImageView);
  1966. framebufferConfiguration.staticData.resolveView = swapChainImageViews.at(imageIndex);
  1967. }
  1968. renderPassState.renderPassConfiguration = std::move(renderPassConfiguration);
  1969. renderPassState.framebufferConfiguration = std::move(framebufferConfiguration);
  1970. if (renderPassState.windowClearRequested)
  1971. clear(renderPassState.mainWindowClearColorValue, renderPassState.mainWindowClearStencilValue, renderPassState.mainWindowClearDepthValue);
  1972. }
  1973. void Graphics::setRenderPass(const RenderTargets &rts, int pixelw, int pixelh, bool hasSRGBtexture)
  1974. {
  1975. // fixme: hasSRGBtexture
  1976. RenderPassConfiguration renderPassConfiguration{};
  1977. for (const auto &color : rts.colors)
  1978. renderPassConfiguration.colorAttachments.push_back({
  1979. Vulkan::getTextureFormat(color.texture->getPixelFormat()).internalFormat,
  1980. VK_ATTACHMENT_LOAD_OP_LOAD,
  1981. dynamic_cast<Texture*>(color.texture)->getMsaaSamples() });
  1982. if (rts.depthStencil.texture != nullptr)
  1983. renderPassConfiguration.staticData.depthStencilAttachment = {
  1984. Vulkan::getTextureFormat(rts.depthStencil.texture->getPixelFormat()).internalFormat,
  1985. VK_ATTACHMENT_LOAD_OP_LOAD,
  1986. VK_ATTACHMENT_LOAD_OP_LOAD,
  1987. dynamic_cast<Texture*>(rts.depthStencil.texture)->getMsaaSamples() };
  1988. FramebufferConfiguration configuration{};
  1989. std::vector<VkImage> transitionImages;
  1990. for (const auto &color : rts.colors)
  1991. {
  1992. configuration.colorViews.push_back(dynamic_cast<Texture*>(color.texture)->getRenderTargetView(color.mipmap, color.slice));
  1993. transitionImages.push_back((VkImage) color.texture->getHandle());
  1994. }
  1995. if (rts.depthStencil.texture != nullptr)
  1996. configuration.staticData.depthView = dynamic_cast<Texture*>(rts.depthStencil.texture)->getRenderTargetView(rts.depthStencil.mipmap, rts.depthStencil.slice);
  1997. configuration.staticData.width = static_cast<uint32_t>(pixelw);
  1998. configuration.staticData.height = static_cast<uint32_t>(pixelh);
  1999. uint32_t numClearValues = static_cast<uint32_t>(rts.colors.size() + 1);
  2000. renderPassState.clearColors.resize(numClearValues);
  2001. renderPassState.beginInfo.sType = VK_STRUCTURE_TYPE_RENDER_PASS_BEGIN_INFO;
  2002. renderPassState.beginInfo.renderPass = VK_NULL_HANDLE;
  2003. renderPassState.beginInfo.framebuffer = VK_NULL_HANDLE;
  2004. renderPassState.beginInfo.renderArea.offset = {0, 0};
  2005. renderPassState.beginInfo.renderArea.extent.width = static_cast<uint32_t>(pixelw);
  2006. renderPassState.beginInfo.renderArea.extent.height = static_cast<uint32_t>(pixelh);
  2007. renderPassState.beginInfo.clearValueCount = numClearValues;
  2008. renderPassState.beginInfo.pClearValues = renderPassState.clearColors.data();
  2009. renderPassState.isWindow = false;
  2010. renderPassState.renderPassConfiguration = renderPassConfiguration;
  2011. renderPassState.framebufferConfiguration = configuration;
  2012. renderPassState.pipeline = VK_NULL_HANDLE;
  2013. renderPassState.width = static_cast<float>(pixelw);
  2014. renderPassState.height = static_cast<float>(pixelh);
  2015. renderPassState.msaa = VK_SAMPLE_COUNT_1_BIT;
  2016. renderPassState.numColorAttachments = static_cast<uint32_t>(rts.colors.size());
  2017. renderPassState.transitionImages = std::move(transitionImages);
  2018. }
  2019. void Graphics::startRenderPass()
  2020. {
  2021. renderPassState.active = true;
  2022. if (renderPassState.isWindow && renderPassState.windowClearRequested)
  2023. renderPassState.windowClearRequested = false;
  2024. VkViewport viewport{};
  2025. viewport.x = 0.0f;
  2026. viewport.y = 0.0f;
  2027. viewport.width = renderPassState.width;
  2028. viewport.height = renderPassState.height;
  2029. viewport.minDepth = 0.0f;
  2030. viewport.maxDepth = 1.0f;
  2031. vkCmdSetViewport(commandBuffers.at(currentFrame), 0, 1, &viewport);
  2032. renderPassState.beginInfo.renderPass = getRenderPass(renderPassState.renderPassConfiguration);
  2033. renderPassState.framebufferConfiguration.staticData.renderPass = renderPassState.beginInfo.renderPass;
  2034. renderPassState.beginInfo.framebuffer = getFramebuffer(renderPassState.framebufferConfiguration);
  2035. for (const auto &image : renderPassState.transitionImages)
  2036. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL);
  2037. vkCmdBeginRenderPass(commandBuffers.at(currentFrame), &renderPassState.beginInfo, VK_SUBPASS_CONTENTS_INLINE);
  2038. }
  2039. void Graphics::endRenderPass()
  2040. {
  2041. renderPassState.active = false;
  2042. vkCmdEndRenderPass(commandBuffers.at(currentFrame));
  2043. for (const auto &image : renderPassState.transitionImages)
  2044. Vulkan::cmdTransitionImageLayout(commandBuffers.at(currentFrame), image, VK_IMAGE_LAYOUT_COLOR_ATTACHMENT_OPTIMAL, VK_IMAGE_LAYOUT_SHADER_READ_ONLY_OPTIMAL);
  2045. for (auto &colorAttachment : renderPassState.renderPassConfiguration.colorAttachments)
  2046. colorAttachment.loadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2047. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.depthLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2048. renderPassState.renderPassConfiguration.staticData.depthStencilAttachment.stencilLoadOp = VK_ATTACHMENT_LOAD_OP_LOAD;
  2049. }
  2050. VkSampler Graphics::createSampler(const SamplerState &samplerState)
  2051. {
  2052. VkSamplerCreateInfo samplerInfo{};
  2053. samplerInfo.sType = VK_STRUCTURE_TYPE_SAMPLER_CREATE_INFO;
  2054. samplerInfo.magFilter = Vulkan::getFilter(samplerState.magFilter);
  2055. samplerInfo.minFilter = Vulkan::getFilter(samplerState.minFilter);
  2056. samplerInfo.addressModeU = Vulkan::getWrapMode(samplerState.wrapU);
  2057. samplerInfo.addressModeV = Vulkan::getWrapMode(samplerState.wrapV);
  2058. samplerInfo.addressModeW = Vulkan::getWrapMode(samplerState.wrapW);
  2059. samplerInfo.anisotropyEnable = VK_TRUE;
  2060. samplerInfo.maxAnisotropy = static_cast<float>(samplerState.maxAnisotropy);
  2061. // TODO: This probably needs to branch on a pixel format to determine whether
  2062. // it should be float vs int, and opaque vs transparent.
  2063. bool clampone = samplerState.wrapU == SamplerState::WRAP_CLAMP_ONE
  2064. || samplerState.wrapV == SamplerState::WRAP_CLAMP_ONE
  2065. || samplerState.wrapW == SamplerState::WRAP_CLAMP_ONE;
  2066. samplerInfo.borderColor = clampone ? VK_BORDER_COLOR_INT_OPAQUE_WHITE : VK_BORDER_COLOR_INT_OPAQUE_BLACK;
  2067. samplerInfo.unnormalizedCoordinates = VK_FALSE;
  2068. if (samplerState.depthSampleMode.hasValue)
  2069. {
  2070. samplerInfo.compareEnable = VK_TRUE;
  2071. samplerInfo.compareOp = Vulkan::getCompareOp(samplerState.depthSampleMode.value);
  2072. }
  2073. else
  2074. {
  2075. samplerInfo.compareEnable = VK_FALSE;
  2076. samplerInfo.compareOp = VK_COMPARE_OP_ALWAYS;
  2077. }
  2078. samplerInfo.compareEnable = VK_FALSE;
  2079. samplerInfo.mipmapMode = Vulkan::getMipMapMode(samplerState.mipmapFilter);
  2080. samplerInfo.mipLodBias = samplerState.lodBias;
  2081. samplerInfo.minLod = static_cast<float>(samplerState.minLod);
  2082. samplerInfo.maxLod = static_cast<float>(samplerState.maxLod);
  2083. VkSampler sampler;
  2084. if (vkCreateSampler(device, &samplerInfo, nullptr, &sampler) != VK_SUCCESS)
  2085. throw love::Exception("failed to create sampler");
  2086. return sampler;
  2087. }
  2088. template<typename Configuration, typename ObjectHandle, typename ConfigurationHasher, typename Deleter>
  2089. static void eraseUnusedObjects(
  2090. std::unordered_map<Configuration, ObjectHandle, ConfigurationHasher> &objects,
  2091. std::unordered_map<ObjectHandle, bool> &usages,
  2092. Deleter deleter,
  2093. VkDevice device)
  2094. {
  2095. std::vector<Configuration> deletionKeys;
  2096. for (const auto &entry : objects)
  2097. {
  2098. if (!usages[entry.second])
  2099. {
  2100. deletionKeys.push_back(entry.first);
  2101. usages.erase(entry.second);
  2102. deleter(device, entry.second, nullptr);
  2103. }
  2104. else
  2105. usages[entry.second] = false;
  2106. }
  2107. for (const auto &key : deletionKeys)
  2108. objects.erase(key);
  2109. }
  2110. void Graphics::cleanupUnusedObjects()
  2111. {
  2112. eraseUnusedObjects(renderPasses, renderPassUsages, vkDestroyRenderPass, device);
  2113. eraseUnusedObjects(framebuffers, framebufferUsages, vkDestroyFramebuffer, device);
  2114. eraseUnusedObjects(graphicsPipelines, pipelineUsages, vkDestroyPipeline, device);
  2115. }
  2116. void Graphics::requestSwapchainRecreation()
  2117. {
  2118. if (swapChain != VK_NULL_HANDLE)
  2119. {
  2120. swapChainRecreationRequested = true;
  2121. }
  2122. }
  2123. void Graphics::setComputeShader(Shader *shader)
  2124. {
  2125. computeShader = shader;
  2126. }
  2127. VkSampler Graphics::getCachedSampler(const SamplerState &samplerState)
  2128. {
  2129. auto samplerkey = samplerState.toKey();
  2130. auto it = samplers.find(samplerkey);
  2131. if (it != samplers.end())
  2132. return it->second;
  2133. else
  2134. {
  2135. VkSampler sampler = createSampler(samplerState);
  2136. samplers.insert({ samplerkey, sampler });
  2137. return sampler;
  2138. }
  2139. }
  2140. VkPipeline Graphics::createGraphicsPipeline(GraphicsPipelineConfiguration &configuration)
  2141. {
  2142. VkGraphicsPipelineCreateInfo pipelineInfo{};
  2143. pipelineInfo.sType = VK_STRUCTURE_TYPE_GRAPHICS_PIPELINE_CREATE_INFO;
  2144. auto &shaderStages = configuration.shader->getShaderStages();
  2145. std::vector<VkVertexInputBindingDescription> bindingDescriptions;
  2146. std::vector<VkVertexInputAttributeDescription> attributeDescriptions;
  2147. createVulkanVertexFormat(configuration.vertexAttributes, bindingDescriptions, attributeDescriptions);
  2148. VkPipelineVertexInputStateCreateInfo vertexInputInfo{};
  2149. vertexInputInfo.sType = VK_STRUCTURE_TYPE_PIPELINE_VERTEX_INPUT_STATE_CREATE_INFO;
  2150. vertexInputInfo.vertexBindingDescriptionCount = static_cast<uint32_t>(bindingDescriptions.size());
  2151. vertexInputInfo.pVertexBindingDescriptions = bindingDescriptions.data();
  2152. vertexInputInfo.vertexAttributeDescriptionCount = static_cast<uint32_t>(attributeDescriptions.size());
  2153. vertexInputInfo.pVertexAttributeDescriptions = attributeDescriptions.data();
  2154. VkPipelineViewportStateCreateInfo viewportState{};
  2155. viewportState.sType = VK_STRUCTURE_TYPE_PIPELINE_VIEWPORT_STATE_CREATE_INFO;
  2156. viewportState.viewportCount = 1;
  2157. viewportState.scissorCount = 1;
  2158. VkPipelineMultisampleStateCreateInfo multisampling{};
  2159. multisampling.sType = VK_STRUCTURE_TYPE_PIPELINE_MULTISAMPLE_STATE_CREATE_INFO;
  2160. multisampling.sampleShadingEnable = VK_FALSE;
  2161. multisampling.rasterizationSamples = configuration.msaaSamples;
  2162. VkPipelineRasterizationStateCreateInfo rasterizer{};
  2163. rasterizer.sType = VK_STRUCTURE_TYPE_PIPELINE_RASTERIZATION_STATE_CREATE_INFO;
  2164. rasterizer.depthClampEnable = VK_FALSE;
  2165. rasterizer.rasterizerDiscardEnable = VK_FALSE;
  2166. rasterizer.polygonMode = Vulkan::getPolygonMode(configuration.wireFrame);
  2167. rasterizer.lineWidth = 1.0f;
  2168. if (!optionalDeviceExtensions.extendedDynamicState)
  2169. {
  2170. rasterizer.cullMode = Vulkan::getCullMode(configuration.dynamicState.cullmode);
  2171. rasterizer.frontFace = Vulkan::getFrontFace(configuration.dynamicState.winding);
  2172. }
  2173. rasterizer.depthBiasEnable = VK_FALSE;
  2174. rasterizer.depthBiasConstantFactor = 0.0f;
  2175. rasterizer.depthBiasClamp = 0.0f;
  2176. rasterizer.depthBiasSlopeFactor = 0.0f;
  2177. VkPipelineInputAssemblyStateCreateInfo inputAssembly{};
  2178. inputAssembly.sType = VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO;
  2179. inputAssembly.topology = Vulkan::getPrimitiveTypeTopology(configuration.primitiveType);
  2180. inputAssembly.primitiveRestartEnable = VK_FALSE;
  2181. VkPipelineDepthStencilStateCreateInfo depthStencil{};
  2182. depthStencil.sType = VK_STRUCTURE_TYPE_PIPELINE_DEPTH_STENCIL_STATE_CREATE_INFO;
  2183. depthStencil.depthTestEnable = VK_TRUE;
  2184. if (!optionalDeviceExtensions.extendedDynamicState)
  2185. {
  2186. depthStencil.depthWriteEnable = Vulkan::getBool(configuration.dynamicState.depthState.write);
  2187. depthStencil.depthCompareOp = Vulkan::getCompareOp(configuration.dynamicState.depthState.compare);
  2188. }
  2189. depthStencil.depthBoundsTestEnable = VK_FALSE;
  2190. depthStencil.minDepthBounds = 0.0f;
  2191. depthStencil.maxDepthBounds = 1.0f;
  2192. depthStencil.stencilTestEnable = VK_TRUE;
  2193. if (!optionalDeviceExtensions.extendedDynamicState)
  2194. {
  2195. depthStencil.front.failOp = VK_STENCIL_OP_KEEP;
  2196. depthStencil.front.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2197. depthStencil.front.depthFailOp = VK_STENCIL_OP_KEEP;
  2198. depthStencil.front.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2199. depthStencil.back.failOp = VK_STENCIL_OP_KEEP;
  2200. depthStencil.back.passOp = Vulkan::getStencilOp(configuration.dynamicState.stencilAction);
  2201. depthStencil.back.depthFailOp = VK_STENCIL_OP_KEEP;
  2202. depthStencil.back.compareOp = Vulkan::getCompareOp(getReversedCompareMode(configuration.dynamicState.stencilCompare));
  2203. }
  2204. pipelineInfo.pDepthStencilState = &depthStencil;
  2205. VkPipelineColorBlendAttachmentState colorBlendAttachment{};
  2206. colorBlendAttachment.colorWriteMask = Vulkan::getColorMask(configuration.colorChannelMask);
  2207. colorBlendAttachment.blendEnable = Vulkan::getBool(configuration.blendState.enable);
  2208. colorBlendAttachment.srcColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorRGB);
  2209. colorBlendAttachment.dstColorBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorRGB);
  2210. colorBlendAttachment.colorBlendOp = Vulkan::getBlendOp(configuration.blendState.operationRGB);
  2211. colorBlendAttachment.srcAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.srcFactorA);
  2212. colorBlendAttachment.dstAlphaBlendFactor = Vulkan::getBlendFactor(configuration.blendState.dstFactorA);
  2213. colorBlendAttachment.alphaBlendOp = Vulkan::getBlendOp(configuration.blendState.operationA);
  2214. std::vector<VkPipelineColorBlendAttachmentState> colorBlendAttachments(configuration.numColorAttachments, colorBlendAttachment);
  2215. VkPipelineColorBlendStateCreateInfo colorBlending{};
  2216. colorBlending.sType = VK_STRUCTURE_TYPE_PIPELINE_COLOR_BLEND_STATE_CREATE_INFO;
  2217. colorBlending.logicOpEnable = VK_FALSE;
  2218. colorBlending.logicOp = VK_LOGIC_OP_COPY;
  2219. colorBlending.attachmentCount = static_cast<uint32_t>(colorBlendAttachments.size());
  2220. colorBlending.pAttachments = colorBlendAttachments.data();
  2221. colorBlending.blendConstants[0] = 0.0f;
  2222. colorBlending.blendConstants[1] = 0.0f;
  2223. colorBlending.blendConstants[2] = 0.0f;
  2224. colorBlending.blendConstants[3] = 0.0f;
  2225. std::vector<VkDynamicState> dynamicStates;
  2226. if (optionalDeviceExtensions.extendedDynamicState)
  2227. dynamicStates = {
  2228. VK_DYNAMIC_STATE_SCISSOR,
  2229. VK_DYNAMIC_STATE_VIEWPORT,
  2230. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2231. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2232. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2233. VK_DYNAMIC_STATE_CULL_MODE_EXT,
  2234. VK_DYNAMIC_STATE_FRONT_FACE_EXT,
  2235. VK_DYNAMIC_STATE_DEPTH_WRITE_ENABLE_EXT,
  2236. VK_DYNAMIC_STATE_DEPTH_COMPARE_OP_EXT,
  2237. VK_DYNAMIC_STATE_STENCIL_OP_EXT,
  2238. };
  2239. else
  2240. dynamicStates = {
  2241. VK_DYNAMIC_STATE_SCISSOR,
  2242. VK_DYNAMIC_STATE_VIEWPORT,
  2243. VK_DYNAMIC_STATE_STENCIL_WRITE_MASK,
  2244. VK_DYNAMIC_STATE_STENCIL_COMPARE_MASK,
  2245. VK_DYNAMIC_STATE_STENCIL_REFERENCE,
  2246. };
  2247. VkPipelineDynamicStateCreateInfo dynamicState{};
  2248. dynamicState.sType = VK_STRUCTURE_TYPE_PIPELINE_DYNAMIC_STATE_CREATE_INFO;
  2249. dynamicState.dynamicStateCount = static_cast<uint32_t>(dynamicStates.size());
  2250. dynamicState.pDynamicStates = dynamicStates.data();
  2251. pipelineInfo.stageCount = static_cast<uint32_t>(shaderStages.size());
  2252. pipelineInfo.pStages = shaderStages.data();
  2253. pipelineInfo.pVertexInputState = &vertexInputInfo;
  2254. pipelineInfo.pInputAssemblyState = &inputAssembly;
  2255. pipelineInfo.pViewportState = &viewportState;
  2256. pipelineInfo.pRasterizationState = &rasterizer;
  2257. pipelineInfo.pMultisampleState = &multisampling;
  2258. pipelineInfo.pColorBlendState = &colorBlending;
  2259. pipelineInfo.pDynamicState = &dynamicState;
  2260. pipelineInfo.layout = configuration.shader->getGraphicsPipelineLayout();
  2261. pipelineInfo.subpass = 0;
  2262. pipelineInfo.basePipelineHandle = VK_NULL_HANDLE;
  2263. pipelineInfo.basePipelineIndex = -1;
  2264. pipelineInfo.renderPass = configuration.renderPass;
  2265. VkPipeline graphicsPipeline;
  2266. if (vkCreateGraphicsPipelines(device, pipelineCache, 1, &pipelineInfo, nullptr, &graphicsPipeline) != VK_SUCCESS)
  2267. throw love::Exception("failed to create graphics pipeline");
  2268. return graphicsPipeline;
  2269. }
  2270. void Graphics::ensureGraphicsPipelineConfiguration(GraphicsPipelineConfiguration &configuration) {
  2271. auto it = graphicsPipelines.find(configuration);
  2272. if (it != graphicsPipelines.end())
  2273. {
  2274. if (it->second != renderPassState.pipeline)
  2275. {
  2276. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS, it->second);
  2277. renderPassState.pipeline = it->second;
  2278. pipelineUsages[it->second] = true;
  2279. }
  2280. }
  2281. else
  2282. {
  2283. VkPipeline pipeline = createGraphicsPipeline(configuration);
  2284. graphicsPipelines.insert({configuration, pipeline});
  2285. vkCmdBindPipeline(commandBuffers.at(currentFrame), VK_PIPELINE_BIND_POINT_GRAPHICS, pipeline);
  2286. renderPassState.pipeline = pipeline;
  2287. pipelineUsages[pipeline] = true;
  2288. }
  2289. }
  2290. VkSampleCountFlagBits Graphics::getMsaaCount(int requestedMsaa) const
  2291. {
  2292. VkPhysicalDeviceProperties physicalDeviceProperties;
  2293. vkGetPhysicalDeviceProperties(physicalDevice, &physicalDeviceProperties);
  2294. VkSampleCountFlags counts = physicalDeviceProperties.limits.framebufferColorSampleCounts & physicalDeviceProperties.limits.framebufferDepthSampleCounts;
  2295. if (counts & VK_SAMPLE_COUNT_64_BIT && requestedMsaa >= 64)
  2296. return VK_SAMPLE_COUNT_64_BIT;
  2297. else if (counts & VK_SAMPLE_COUNT_32_BIT && requestedMsaa >= 32)
  2298. return VK_SAMPLE_COUNT_32_BIT;
  2299. else if (counts & VK_SAMPLE_COUNT_16_BIT && requestedMsaa >= 16)
  2300. return VK_SAMPLE_COUNT_16_BIT;
  2301. else if (counts & VK_SAMPLE_COUNT_8_BIT && requestedMsaa >= 8)
  2302. return VK_SAMPLE_COUNT_8_BIT;
  2303. else if (counts & VK_SAMPLE_COUNT_4_BIT && requestedMsaa >= 4)
  2304. return VK_SAMPLE_COUNT_4_BIT;
  2305. else if (counts & VK_SAMPLE_COUNT_2_BIT && requestedMsaa >= 2)
  2306. return VK_SAMPLE_COUNT_2_BIT;
  2307. else
  2308. return VK_SAMPLE_COUNT_1_BIT;
  2309. }
  2310. void Graphics::setVsync(int vsync)
  2311. {
  2312. if (vsync != this->vsync)
  2313. {
  2314. this->vsync = vsync;
  2315. // With the extension VK_EXT_swapchain_maintenance1 a swapchain recreation might not be needed
  2316. // https://github.com/KhronosGroup/Vulkan-Docs/blob/main/proposals/VK_EXT_swapchain_maintenance1.adoc
  2317. // However, there are not any drivers that support it, yet.
  2318. // Reevaluate again in the future.
  2319. requestSwapchainRecreation();
  2320. }
  2321. }
  2322. int Graphics::getVsync() const
  2323. {
  2324. return vsync;
  2325. }
  2326. void Graphics::createColorResources()
  2327. {
  2328. if (msaaSamples & VK_SAMPLE_COUNT_1_BIT)
  2329. {
  2330. colorImage = VK_NULL_HANDLE;
  2331. colorImageView = VK_NULL_HANDLE;
  2332. }
  2333. else
  2334. {
  2335. VkFormat colorFormat = swapChainImageFormat;
  2336. VkImageCreateInfo imageInfo{};
  2337. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2338. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2339. imageInfo.format = colorFormat;
  2340. imageInfo.extent.width = swapChainExtent.width;
  2341. imageInfo.extent.height = swapChainExtent.height;
  2342. imageInfo.extent.depth = 1;
  2343. imageInfo.mipLevels = 1;
  2344. imageInfo.arrayLayers = 1;
  2345. imageInfo.samples = msaaSamples;
  2346. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2347. imageInfo.usage = VK_IMAGE_USAGE_TRANSIENT_ATTACHMENT_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT;
  2348. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2349. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2350. VmaAllocationCreateInfo allocationInfo{};
  2351. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2352. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2353. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &colorImage, &colorImageAllocation, nullptr))
  2354. throw love::Exception("failed to create color image");
  2355. VkImageViewCreateInfo imageViewInfo{};
  2356. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2357. imageViewInfo.image = colorImage;
  2358. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2359. imageViewInfo.format = colorFormat;
  2360. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2361. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2362. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2363. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2364. imageViewInfo.subresourceRange.aspectMask = VK_IMAGE_ASPECT_COLOR_BIT;
  2365. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2366. imageViewInfo.subresourceRange.levelCount = 1;
  2367. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2368. imageViewInfo.subresourceRange.layerCount = 1;
  2369. if (vkCreateImageView(device, &imageViewInfo, nullptr, &colorImageView) != VK_SUCCESS)
  2370. throw love::Exception("failed to create color image view");
  2371. }
  2372. }
  2373. VkFormat Graphics::findSupportedFormat(const std::vector<VkFormat> &candidates, VkImageTiling tiling, VkFormatFeatureFlags features)
  2374. {
  2375. for (auto format : candidates)
  2376. {
  2377. VkFormatProperties properties;
  2378. vkGetPhysicalDeviceFormatProperties(physicalDevice, format, &properties);
  2379. if (tiling == VK_IMAGE_TILING_LINEAR && (properties.linearTilingFeatures & features) == features)
  2380. return format;
  2381. else if (tiling == VK_IMAGE_TILING_OPTIMAL && (properties.optimalTilingFeatures & features) == features)
  2382. return format;
  2383. }
  2384. throw love::Exception("failed to find supported format");
  2385. }
  2386. VkFormat Graphics::findDepthFormat()
  2387. {
  2388. return findSupportedFormat(
  2389. { VK_FORMAT_D32_SFLOAT_S8_UINT, VK_FORMAT_D24_UNORM_S8_UINT },
  2390. VK_IMAGE_TILING_OPTIMAL,
  2391. VK_FORMAT_FEATURE_DEPTH_STENCIL_ATTACHMENT_BIT
  2392. );
  2393. }
  2394. void Graphics::createDepthResources()
  2395. {
  2396. if (!backbufferHasDepth && !backbufferHasStencil)
  2397. {
  2398. depthImage = VK_NULL_HANDLE;
  2399. depthImageView = VK_NULL_HANDLE;
  2400. return;
  2401. }
  2402. VkImageCreateInfo imageInfo{};
  2403. imageInfo.sType = VK_STRUCTURE_TYPE_IMAGE_CREATE_INFO;
  2404. imageInfo.imageType = VK_IMAGE_TYPE_2D;
  2405. imageInfo.format = depthStencilFormat;
  2406. imageInfo.extent.width = swapChainExtent.width;
  2407. imageInfo.extent.height = swapChainExtent.height;
  2408. imageInfo.extent.depth = 1;
  2409. imageInfo.mipLevels = 1;
  2410. imageInfo.arrayLayers = 1;
  2411. imageInfo.samples = msaaSamples;
  2412. imageInfo.tiling = VK_IMAGE_TILING_OPTIMAL;
  2413. imageInfo.usage = VK_IMAGE_USAGE_DEPTH_STENCIL_ATTACHMENT_BIT;
  2414. imageInfo.sharingMode = VK_SHARING_MODE_EXCLUSIVE;
  2415. imageInfo.initialLayout = VK_IMAGE_LAYOUT_UNDEFINED;
  2416. VmaAllocationCreateInfo allocationInfo{};
  2417. allocationInfo.usage = VMA_MEMORY_USAGE_AUTO;
  2418. allocationInfo.flags = VMA_ALLOCATION_CREATE_DEDICATED_MEMORY_BIT;
  2419. if (vmaCreateImage(vmaAllocator, &imageInfo, &allocationInfo, &depthImage, &depthImageAllocation, nullptr) != VK_SUCCESS)
  2420. throw love::Exception("failed to create depth image");
  2421. VkImageViewCreateInfo imageViewInfo{};
  2422. imageViewInfo.sType = VK_STRUCTURE_TYPE_IMAGE_VIEW_CREATE_INFO;
  2423. imageViewInfo.image = depthImage;
  2424. imageViewInfo.viewType = VK_IMAGE_VIEW_TYPE_2D;
  2425. imageViewInfo.format = depthStencilFormat;
  2426. imageViewInfo.components.r = VK_COMPONENT_SWIZZLE_IDENTITY;
  2427. imageViewInfo.components.g = VK_COMPONENT_SWIZZLE_IDENTITY;
  2428. imageViewInfo.components.b = VK_COMPONENT_SWIZZLE_IDENTITY;
  2429. imageViewInfo.components.a = VK_COMPONENT_SWIZZLE_IDENTITY;
  2430. if (backbufferHasDepth)
  2431. imageViewInfo.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_DEPTH_BIT;
  2432. if (backbufferHasStencil)
  2433. imageViewInfo.subresourceRange.aspectMask |= VK_IMAGE_ASPECT_STENCIL_BIT;
  2434. imageViewInfo.subresourceRange.baseMipLevel = 0;
  2435. imageViewInfo.subresourceRange.levelCount = 1;
  2436. imageViewInfo.subresourceRange.baseArrayLayer = 0;
  2437. imageViewInfo.subresourceRange.layerCount = 1;
  2438. if (vkCreateImageView(device, &imageViewInfo, nullptr, &depthImageView) != VK_SUCCESS)
  2439. throw love::Exception("failed to create depth image view");
  2440. }
  2441. void Graphics::createCommandPool()
  2442. {
  2443. QueueFamilyIndices queueFamilyIndices = findQueueFamilies(physicalDevice);
  2444. VkCommandPoolCreateInfo poolInfo{};
  2445. poolInfo.sType = VK_STRUCTURE_TYPE_COMMAND_POOL_CREATE_INFO;
  2446. poolInfo.queueFamilyIndex = queueFamilyIndices.graphicsFamily.value;
  2447. poolInfo.flags = VK_COMMAND_POOL_CREATE_RESET_COMMAND_BUFFER_BIT | VK_COMMAND_POOL_CREATE_TRANSIENT_BIT;
  2448. if (vkCreateCommandPool(device, &poolInfo, nullptr, &commandPool) != VK_SUCCESS)
  2449. throw love::Exception("failed to create command pool");
  2450. }
  2451. void Graphics::createCommandBuffers()
  2452. {
  2453. commandBuffers.resize(MAX_FRAMES_IN_FLIGHT);
  2454. VkCommandBufferAllocateInfo allocInfo{};
  2455. allocInfo.sType = VK_STRUCTURE_TYPE_COMMAND_BUFFER_ALLOCATE_INFO;
  2456. allocInfo.commandPool = commandPool;
  2457. allocInfo.level = VK_COMMAND_BUFFER_LEVEL_PRIMARY;
  2458. allocInfo.commandBufferCount = static_cast<uint32_t>(MAX_FRAMES_IN_FLIGHT);
  2459. if (vkAllocateCommandBuffers(device, &allocInfo, commandBuffers.data()) != VK_SUCCESS)
  2460. throw love::Exception("failed to allocate command buffers");
  2461. }
  2462. void Graphics::createSyncObjects()
  2463. {
  2464. imageAvailableSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2465. renderFinishedSemaphores.resize(MAX_FRAMES_IN_FLIGHT);
  2466. inFlightFences.resize(MAX_FRAMES_IN_FLIGHT);
  2467. imagesInFlight.resize(swapChainImages.size(), VK_NULL_HANDLE);
  2468. VkSemaphoreCreateInfo semaphoreInfo{};
  2469. semaphoreInfo.sType = VK_STRUCTURE_TYPE_SEMAPHORE_CREATE_INFO;
  2470. VkFenceCreateInfo fenceInfo{};
  2471. fenceInfo.sType = VK_STRUCTURE_TYPE_FENCE_CREATE_INFO;
  2472. fenceInfo.flags = VK_FENCE_CREATE_SIGNALED_BIT;
  2473. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2474. if (vkCreateSemaphore(device, &semaphoreInfo, nullptr, &imageAvailableSemaphores.at(i)) != VK_SUCCESS ||
  2475. vkCreateSemaphore(device, &semaphoreInfo, nullptr, &renderFinishedSemaphores.at(i)) != VK_SUCCESS ||
  2476. vkCreateFence(device, &fenceInfo, nullptr, &inFlightFences.at(i)) != VK_SUCCESS)
  2477. throw love::Exception("failed to create synchronization objects for a frame!");
  2478. }
  2479. void Graphics::cleanup()
  2480. {
  2481. for (auto &cleanUpFns : cleanUpFunctions)
  2482. for (auto &cleanUpFn : cleanUpFns)
  2483. cleanUpFn();
  2484. cleanUpFunctions.clear();
  2485. vmaDestroyAllocator(vmaAllocator);
  2486. for (size_t i = 0; i < MAX_FRAMES_IN_FLIGHT; i++)
  2487. {
  2488. vkDestroySemaphore(device, renderFinishedSemaphores[i], nullptr);
  2489. vkDestroySemaphore(device, imageAvailableSemaphores[i], nullptr);
  2490. vkDestroyFence(device, inFlightFences[i], nullptr);
  2491. }
  2492. vkFreeCommandBuffers(device, commandPool, MAX_FRAMES_IN_FLIGHT, commandBuffers.data());
  2493. for (auto const &p : samplers)
  2494. vkDestroySampler(device, p.second, nullptr);
  2495. samplers.clear();
  2496. for (const auto &entry : renderPasses)
  2497. vkDestroyRenderPass(device, entry.second, nullptr);
  2498. renderPasses.clear();
  2499. for (const auto &entry : framebuffers)
  2500. vkDestroyFramebuffer(device, entry.second, nullptr);
  2501. framebuffers.clear();
  2502. for (auto const &p : graphicsPipelines)
  2503. vkDestroyPipeline(device, p.second, nullptr);
  2504. graphicsPipelines.clear();
  2505. vkDestroyCommandPool(device, commandPool, nullptr);
  2506. vkDestroyPipelineCache(device, pipelineCache, nullptr);
  2507. vkDestroyDevice(device, nullptr);
  2508. }
  2509. void Graphics::cleanupSwapChain()
  2510. {
  2511. for (const auto &readbackBuffer : screenshotReadbackBuffers)
  2512. {
  2513. vmaDestroyBuffer(vmaAllocator, readbackBuffer.buffer, readbackBuffer.allocation);
  2514. vmaDestroyImage(vmaAllocator, readbackBuffer.image, readbackBuffer.imageAllocation);
  2515. }
  2516. if (colorImage)
  2517. {
  2518. vkDestroyImageView(device, colorImageView, nullptr);
  2519. vmaDestroyImage(vmaAllocator, colorImage, colorImageAllocation);
  2520. }
  2521. if (depthImage)
  2522. {
  2523. vkDestroyImageView(device, depthImageView, nullptr);
  2524. vmaDestroyImage(vmaAllocator, depthImage, depthImageAllocation);
  2525. }
  2526. for (const auto &swapChainImageView : swapChainImageViews)
  2527. vkDestroyImageView(device, swapChainImageView, nullptr);
  2528. swapChainImageViews.clear();
  2529. vkDestroySwapchainKHR(device, swapChain, nullptr);
  2530. swapChain = VK_NULL_HANDLE;
  2531. }
  2532. void Graphics::recreateSwapChain()
  2533. {
  2534. vkDeviceWaitIdle(device);
  2535. cleanupSwapChain();
  2536. createSwapChain();
  2537. createImageViews();
  2538. createScreenshotCallbackBuffers();
  2539. createColorResources();
  2540. createDepthResources();
  2541. transitionColorDepthLayouts = true;
  2542. }
  2543. love::graphics::Graphics *createInstance()
  2544. {
  2545. love::graphics::Graphics *instance = nullptr;
  2546. try
  2547. {
  2548. instance = new Graphics();
  2549. }
  2550. catch (love::Exception &e)
  2551. {
  2552. printf("Cannot create Vulkan renderer: %s\n", e.what());
  2553. }
  2554. return instance;
  2555. }
  2556. } // vulkan
  2557. } // graphics
  2558. } // love