Graphics.cpp 105 KB

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