Graphics.cpp 109 KB

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