PipelineBase.cs 62 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Shader;
  4. using Silk.NET.Vulkan;
  5. using System;
  6. using System.Linq;
  7. using System.Numerics;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.Vulkan
  11. {
  12. class PipelineBase : IDisposable
  13. {
  14. public const int DescriptorSetLayouts = 4;
  15. public const int UniformSetIndex = 0;
  16. public const int StorageSetIndex = 1;
  17. public const int TextureSetIndex = 2;
  18. public const int ImageSetIndex = 3;
  19. protected readonly VulkanRenderer Gd;
  20. protected readonly Device Device;
  21. public readonly PipelineCache PipelineCache;
  22. public readonly AutoFlushCounter AutoFlush;
  23. protected PipelineDynamicState DynamicState;
  24. private PipelineState _newState;
  25. private bool _stateDirty;
  26. private GAL.PrimitiveTopology _topology;
  27. private ulong _currentPipelineHandle;
  28. protected Auto<DisposablePipeline> Pipeline;
  29. protected PipelineBindPoint Pbp;
  30. protected CommandBufferScoped Cbs;
  31. protected CommandBufferScoped? PreloadCbs;
  32. protected CommandBuffer CommandBuffer;
  33. public CommandBufferScoped CurrentCommandBuffer => Cbs;
  34. private ShaderCollection _program;
  35. private Vector4<float>[] _renderScale = new Vector4<float>[73];
  36. private int _fragmentScaleCount;
  37. protected FramebufferParams FramebufferParams;
  38. private Auto<DisposableFramebuffer> _framebuffer;
  39. private Auto<DisposableRenderPass> _renderPass;
  40. private int _writtenAttachmentCount;
  41. private bool _framebufferUsingColorWriteMask;
  42. private ITexture[] _preMaskColors;
  43. private ITexture _preMaskDepthStencil;
  44. private readonly DescriptorSetUpdater _descriptorSetUpdater;
  45. private IndexBufferState _indexBuffer;
  46. private IndexBufferPattern _indexBufferPattern;
  47. private readonly BufferState[] _transformFeedbackBuffers;
  48. private readonly VertexBufferState[] _vertexBuffers;
  49. private ulong _vertexBuffersDirty;
  50. protected Rectangle<int> ClearScissor;
  51. public SupportBufferUpdater SupportBufferUpdater;
  52. public IndexBufferPattern QuadsToTrisPattern;
  53. public IndexBufferPattern TriFanToTrisPattern;
  54. private bool _needsIndexBufferRebind;
  55. private bool _needsTransformFeedbackBuffersRebind;
  56. private bool _tfEnabled;
  57. private bool _tfActive;
  58. private PipelineColorBlendAttachmentState[] _storedBlend;
  59. public ulong DrawCount { get; private set; }
  60. public bool RenderPassActive { get; private set; }
  61. public unsafe PipelineBase(VulkanRenderer gd, Device device)
  62. {
  63. Gd = gd;
  64. Device = device;
  65. AutoFlush = new AutoFlushCounter();
  66. var pipelineCacheCreateInfo = new PipelineCacheCreateInfo()
  67. {
  68. SType = StructureType.PipelineCacheCreateInfo
  69. };
  70. gd.Api.CreatePipelineCache(device, pipelineCacheCreateInfo, null, out PipelineCache).ThrowOnError();
  71. _descriptorSetUpdater = new DescriptorSetUpdater(gd, this);
  72. _transformFeedbackBuffers = new BufferState[Constants.MaxTransformFeedbackBuffers];
  73. _vertexBuffers = new VertexBufferState[Constants.MaxVertexBuffers + 1];
  74. const int EmptyVbSize = 16;
  75. using var emptyVb = gd.BufferManager.Create(gd, EmptyVbSize);
  76. emptyVb.SetData(0, new byte[EmptyVbSize]);
  77. _vertexBuffers[0] = new VertexBufferState(emptyVb.GetBuffer(), 0, 0, EmptyVbSize, 0);
  78. _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length);
  79. ClearScissor = new Rectangle<int>(0, 0, 0xffff, 0xffff);
  80. var defaultScale = new Vector4<float> { X = 1f, Y = 0f, Z = 0f, W = 0f };
  81. new Span<Vector4<float>>(_renderScale).Fill(defaultScale);
  82. _storedBlend = new PipelineColorBlendAttachmentState[Constants.MaxRenderTargets];
  83. _newState.Initialize();
  84. }
  85. public void Initialize()
  86. {
  87. _descriptorSetUpdater.Initialize();
  88. SupportBufferUpdater = new SupportBufferUpdater(Gd);
  89. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, SupportBuffer.RenderScaleMaxCount);
  90. QuadsToTrisPattern = new IndexBufferPattern(Gd, 4, 6, 0, new[] { 0, 1, 2, 0, 2, 3 }, 4, false);
  91. TriFanToTrisPattern = new IndexBufferPattern(Gd, 3, 3, 2, new[] { int.MinValue, -1, 0 }, 1, true);
  92. }
  93. public unsafe void Barrier()
  94. {
  95. MemoryBarrier memoryBarrier = new MemoryBarrier()
  96. {
  97. SType = StructureType.MemoryBarrier,
  98. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  99. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  100. };
  101. Gd.Api.CmdPipelineBarrier(
  102. CommandBuffer,
  103. PipelineStageFlags.FragmentShaderBit,
  104. PipelineStageFlags.FragmentShaderBit,
  105. 0,
  106. 1,
  107. memoryBarrier,
  108. 0,
  109. null,
  110. 0,
  111. null);
  112. }
  113. public void ComputeBarrier()
  114. {
  115. MemoryBarrier memoryBarrier = new MemoryBarrier()
  116. {
  117. SType = StructureType.MemoryBarrier,
  118. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  119. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  120. };
  121. Gd.Api.CmdPipelineBarrier(
  122. CommandBuffer,
  123. PipelineStageFlags.ComputeShaderBit,
  124. PipelineStageFlags.AllCommandsBit,
  125. 0,
  126. 1,
  127. new ReadOnlySpan<MemoryBarrier>(memoryBarrier),
  128. 0,
  129. ReadOnlySpan<BufferMemoryBarrier>.Empty,
  130. 0,
  131. ReadOnlySpan<ImageMemoryBarrier>.Empty);
  132. }
  133. public void BeginTransformFeedback(GAL.PrimitiveTopology topology)
  134. {
  135. _tfEnabled = true;
  136. }
  137. public void ClearBuffer(BufferHandle destination, int offset, int size, uint value)
  138. {
  139. EndRenderPass();
  140. var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, offset, size, true).Get(Cbs, offset, size).Value;
  141. BufferHolder.InsertBufferBarrier(
  142. Gd,
  143. Cbs.CommandBuffer,
  144. dst,
  145. BufferHolder.DefaultAccessFlags,
  146. AccessFlags.TransferWriteBit,
  147. PipelineStageFlags.AllCommandsBit,
  148. PipelineStageFlags.TransferBit,
  149. offset,
  150. size);
  151. Gd.Api.CmdFillBuffer(CommandBuffer, dst, (ulong)offset, (ulong)size, value);
  152. BufferHolder.InsertBufferBarrier(
  153. Gd,
  154. Cbs.CommandBuffer,
  155. dst,
  156. AccessFlags.TransferWriteBit,
  157. BufferHolder.DefaultAccessFlags,
  158. PipelineStageFlags.TransferBit,
  159. PipelineStageFlags.AllCommandsBit,
  160. offset,
  161. size);
  162. }
  163. public unsafe void ClearRenderTargetColor(int index, int layer, int layerCount, ColorF color)
  164. {
  165. if (FramebufferParams == null || !FramebufferParams.IsValidColorAttachment(index))
  166. {
  167. return;
  168. }
  169. if (_renderPass == null)
  170. {
  171. CreateRenderPass();
  172. }
  173. BeginRenderPass();
  174. var clearValue = new ClearValue(new ClearColorValue(color.Red, color.Green, color.Blue, color.Alpha));
  175. var attachment = new ClearAttachment(ImageAspectFlags.ColorBit, (uint)index, clearValue);
  176. var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);
  177. Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
  178. }
  179. public unsafe void ClearRenderTargetDepthStencil(int layer, int layerCount, float depthValue, bool depthMask, int stencilValue, int stencilMask)
  180. {
  181. // TODO: Use stencilMask (fully)
  182. if (FramebufferParams == null || !FramebufferParams.HasDepthStencil)
  183. {
  184. return;
  185. }
  186. if (_renderPass == null)
  187. {
  188. CreateRenderPass();
  189. }
  190. BeginRenderPass();
  191. var clearValue = new ClearValue(null, new ClearDepthStencilValue(depthValue, (uint)stencilValue));
  192. var flags = depthMask ? ImageAspectFlags.DepthBit : 0;
  193. if (stencilMask != 0)
  194. {
  195. flags |= ImageAspectFlags.StencilBit;
  196. }
  197. var attachment = new ClearAttachment(flags, 0, clearValue);
  198. var clearRect = FramebufferParams.GetClearRect(ClearScissor, layer, layerCount);
  199. Gd.Api.CmdClearAttachments(CommandBuffer, 1, &attachment, 1, &clearRect);
  200. }
  201. public unsafe void CommandBufferBarrier()
  202. {
  203. MemoryBarrier memoryBarrier = new MemoryBarrier()
  204. {
  205. SType = StructureType.MemoryBarrier,
  206. SrcAccessMask = BufferHolder.DefaultAccessFlags,
  207. DstAccessMask = AccessFlags.IndirectCommandReadBit
  208. };
  209. Gd.Api.CmdPipelineBarrier(
  210. CommandBuffer,
  211. PipelineStageFlags.AllCommandsBit,
  212. PipelineStageFlags.DrawIndirectBit,
  213. 0,
  214. 1,
  215. memoryBarrier,
  216. 0,
  217. null,
  218. 0,
  219. null);
  220. }
  221. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  222. {
  223. EndRenderPass();
  224. var src = Gd.BufferManager.GetBuffer(CommandBuffer, source, srcOffset, size, false);
  225. var dst = Gd.BufferManager.GetBuffer(CommandBuffer, destination, dstOffset, size, true);
  226. BufferHolder.Copy(Gd, Cbs, src, dst, srcOffset, dstOffset, size);
  227. }
  228. public void DirtyVertexBuffer(Auto<DisposableBuffer> buffer)
  229. {
  230. for (int i = 0; i < _vertexBuffers.Length; i++)
  231. {
  232. if (_vertexBuffers[i].BoundEquals(buffer))
  233. {
  234. _vertexBuffersDirty |= 1UL << i;
  235. }
  236. }
  237. }
  238. public void DirtyIndexBuffer(Auto<DisposableBuffer> buffer)
  239. {
  240. if (_indexBuffer.BoundEquals(buffer))
  241. {
  242. _needsIndexBufferRebind = true;
  243. }
  244. }
  245. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  246. {
  247. if (!_program.IsLinked)
  248. {
  249. return;
  250. }
  251. EndRenderPass();
  252. RecreatePipelineIfNeeded(PipelineBindPoint.Compute);
  253. Gd.Api.CmdDispatch(CommandBuffer, (uint)groupsX, (uint)groupsY, (uint)groupsZ);
  254. }
  255. public void DispatchComputeIndirect(Auto<DisposableBuffer> indirectBuffer, int indirectBufferOffset)
  256. {
  257. if (!_program.IsLinked)
  258. {
  259. return;
  260. }
  261. EndRenderPass();
  262. RecreatePipelineIfNeeded(PipelineBindPoint.Compute);
  263. Gd.Api.CmdDispatchIndirect(CommandBuffer, indirectBuffer.Get(Cbs, indirectBufferOffset, 12).Value, (ulong)indirectBufferOffset);
  264. }
  265. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  266. {
  267. if (!_program.IsLinked)
  268. {
  269. return;
  270. }
  271. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  272. BeginRenderPass();
  273. DrawCount++;
  274. if (Gd.TopologyUnsupported(_topology))
  275. {
  276. // Temporarily bind a conversion pattern as an index buffer.
  277. _needsIndexBufferRebind = true;
  278. IndexBufferPattern pattern = _topology switch
  279. {
  280. GAL.PrimitiveTopology.Quads => QuadsToTrisPattern,
  281. GAL.PrimitiveTopology.TriangleFan or
  282. GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern,
  283. _ => throw new NotSupportedException($"Unsupported topology: {_topology}")
  284. };
  285. BufferHandle handle = pattern.GetRepeatingBuffer(vertexCount, out int indexCount);
  286. var buffer = Gd.BufferManager.GetBuffer(CommandBuffer, handle, false);
  287. Gd.Api.CmdBindIndexBuffer(CommandBuffer, buffer.Get(Cbs, 0, indexCount * sizeof(int)).Value, 0, Silk.NET.Vulkan.IndexType.Uint32);
  288. BeginRenderPass(); // May have been interrupted to set buffer data.
  289. ResumeTransformFeedbackInternal();
  290. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)indexCount, (uint)instanceCount, 0, firstVertex, (uint)firstInstance);
  291. }
  292. else
  293. {
  294. ResumeTransformFeedbackInternal();
  295. Gd.Api.CmdDraw(CommandBuffer, (uint)vertexCount, (uint)instanceCount, (uint)firstVertex, (uint)firstInstance);
  296. }
  297. }
  298. private void UpdateIndexBufferPattern()
  299. {
  300. IndexBufferPattern pattern = null;
  301. if (Gd.TopologyUnsupported(_topology))
  302. {
  303. pattern = _topology switch
  304. {
  305. GAL.PrimitiveTopology.Quads => QuadsToTrisPattern,
  306. GAL.PrimitiveTopology.TriangleFan or
  307. GAL.PrimitiveTopology.Polygon => TriFanToTrisPattern,
  308. _ => throw new NotSupportedException($"Unsupported topology: {_topology}")
  309. };
  310. }
  311. if (_indexBufferPattern != pattern)
  312. {
  313. _indexBufferPattern = pattern;
  314. _needsIndexBufferRebind = true;
  315. }
  316. }
  317. public void DrawIndexed(int indexCount, int instanceCount, int firstIndex, int firstVertex, int firstInstance)
  318. {
  319. if (!_program.IsLinked)
  320. {
  321. return;
  322. }
  323. UpdateIndexBufferPattern();
  324. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  325. BeginRenderPass();
  326. DrawCount++;
  327. if (_indexBufferPattern != null)
  328. {
  329. // Convert the index buffer into a supported topology.
  330. IndexBufferPattern pattern = _indexBufferPattern;
  331. int convertedCount = pattern.GetConvertedCount(indexCount);
  332. if (_needsIndexBufferRebind)
  333. {
  334. _indexBuffer.BindConvertedIndexBuffer(Gd, Cbs, firstIndex, indexCount, convertedCount, pattern);
  335. _needsIndexBufferRebind = false;
  336. }
  337. BeginRenderPass(); // May have been interrupted to set buffer data.
  338. ResumeTransformFeedbackInternal();
  339. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)convertedCount, (uint)instanceCount, 0, firstVertex, (uint)firstInstance);
  340. }
  341. else
  342. {
  343. ResumeTransformFeedbackInternal();
  344. Gd.Api.CmdDrawIndexed(CommandBuffer, (uint)indexCount, (uint)instanceCount, (uint)firstIndex, firstVertex, (uint)firstInstance);
  345. }
  346. }
  347. public void DrawIndexedIndirect(BufferRange indirectBuffer)
  348. {
  349. if (!_program.IsLinked)
  350. {
  351. return;
  352. }
  353. UpdateIndexBufferPattern();
  354. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  355. BeginRenderPass();
  356. DrawCount++;
  357. if (_indexBufferPattern != null)
  358. {
  359. // Convert the index buffer into a supported topology.
  360. IndexBufferPattern pattern = _indexBufferPattern;
  361. Auto<DisposableBuffer> indirectBufferAuto = _indexBuffer.BindConvertedIndexBufferIndirect(
  362. Gd,
  363. Cbs,
  364. indirectBuffer,
  365. BufferRange.Empty,
  366. pattern,
  367. false,
  368. 1,
  369. indirectBuffer.Size);
  370. _needsIndexBufferRebind = false;
  371. BeginRenderPass(); // May have been interrupted to set buffer data.
  372. ResumeTransformFeedbackInternal();
  373. Gd.Api.CmdDrawIndexedIndirect(CommandBuffer, indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value, 0, 1, (uint)indirectBuffer.Size);
  374. }
  375. else
  376. {
  377. var buffer = Gd.BufferManager
  378. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  379. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  380. ResumeTransformFeedbackInternal();
  381. Gd.Api.CmdDrawIndexedIndirect(CommandBuffer, buffer, (ulong)indirectBuffer.Offset, 1, (uint)indirectBuffer.Size);
  382. }
  383. }
  384. public void DrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  385. {
  386. if (!_program.IsLinked)
  387. {
  388. return;
  389. }
  390. UpdateIndexBufferPattern();
  391. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  392. BeginRenderPass();
  393. DrawCount++;
  394. var countBuffer = Gd.BufferManager
  395. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false)
  396. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  397. if (_indexBufferPattern != null)
  398. {
  399. // Convert the index buffer into a supported topology.
  400. IndexBufferPattern pattern = _indexBufferPattern;
  401. Auto<DisposableBuffer> indirectBufferAuto = _indexBuffer.BindConvertedIndexBufferIndirect(
  402. Gd,
  403. Cbs,
  404. indirectBuffer,
  405. parameterBuffer,
  406. pattern,
  407. true,
  408. maxDrawCount,
  409. stride);
  410. _needsIndexBufferRebind = false;
  411. BeginRenderPass(); // May have been interrupted to set buffer data.
  412. ResumeTransformFeedbackInternal();
  413. if (Gd.Capabilities.SupportsIndirectParameters)
  414. {
  415. Gd.DrawIndirectCountApi.CmdDrawIndexedIndirectCount(
  416. CommandBuffer,
  417. indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value,
  418. 0,
  419. countBuffer,
  420. (ulong)parameterBuffer.Offset,
  421. (uint)maxDrawCount,
  422. (uint)stride);
  423. }
  424. else
  425. {
  426. // This is also fine because the indirect data conversion always zeros
  427. // the entries that are past the current draw count.
  428. Gd.Api.CmdDrawIndexedIndirect(
  429. CommandBuffer,
  430. indirectBufferAuto.Get(Cbs, 0, indirectBuffer.Size).Value,
  431. 0,
  432. (uint)maxDrawCount,
  433. (uint)stride);
  434. }
  435. }
  436. else
  437. {
  438. var buffer = Gd.BufferManager
  439. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  440. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  441. ResumeTransformFeedbackInternal();
  442. if (Gd.Capabilities.SupportsIndirectParameters)
  443. {
  444. Gd.DrawIndirectCountApi.CmdDrawIndexedIndirectCount(
  445. CommandBuffer,
  446. buffer,
  447. (ulong)indirectBuffer.Offset,
  448. countBuffer,
  449. (ulong)parameterBuffer.Offset,
  450. (uint)maxDrawCount,
  451. (uint)stride);
  452. }
  453. else
  454. {
  455. // Not fully correct, but we can't do much better if the host does not support indirect count.
  456. Gd.Api.CmdDrawIndexedIndirect(
  457. CommandBuffer,
  458. buffer,
  459. (ulong)indirectBuffer.Offset,
  460. (uint)maxDrawCount,
  461. (uint)stride);
  462. }
  463. }
  464. }
  465. public void DrawIndirect(BufferRange indirectBuffer)
  466. {
  467. if (!_program.IsLinked)
  468. {
  469. return;
  470. }
  471. // TODO: Support quads and other unsupported topologies.
  472. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  473. BeginRenderPass();
  474. ResumeTransformFeedbackInternal();
  475. DrawCount++;
  476. var buffer = Gd.BufferManager
  477. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  478. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  479. Gd.Api.CmdDrawIndirect(CommandBuffer, buffer, (ulong)indirectBuffer.Offset, 1, (uint)indirectBuffer.Size);
  480. }
  481. public void DrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  482. {
  483. if (!Gd.Capabilities.SupportsIndirectParameters)
  484. {
  485. // TODO: Fallback for when this is not supported.
  486. throw new NotSupportedException();
  487. }
  488. if (!_program.IsLinked)
  489. {
  490. return;
  491. }
  492. // TODO: Support quads and other unsupported topologies.
  493. RecreatePipelineIfNeeded(PipelineBindPoint.Graphics);
  494. BeginRenderPass();
  495. ResumeTransformFeedbackInternal();
  496. DrawCount++;
  497. var buffer = Gd.BufferManager
  498. .GetBuffer(CommandBuffer, indirectBuffer.Handle, indirectBuffer.Offset, indirectBuffer.Size, false)
  499. .Get(Cbs, indirectBuffer.Offset, indirectBuffer.Size).Value;
  500. var countBuffer = Gd.BufferManager
  501. .GetBuffer(CommandBuffer, parameterBuffer.Handle, parameterBuffer.Offset, parameterBuffer.Size, false)
  502. .Get(Cbs, parameterBuffer.Offset, parameterBuffer.Size).Value;
  503. Gd.DrawIndirectCountApi.CmdDrawIndirectCount(
  504. CommandBuffer,
  505. buffer,
  506. (ulong)indirectBuffer.Offset,
  507. countBuffer,
  508. (ulong)parameterBuffer.Offset,
  509. (uint)maxDrawCount,
  510. (uint)stride);
  511. }
  512. public void DrawTexture(ITexture texture, ISampler sampler, Extents2DF srcRegion, Extents2DF dstRegion)
  513. {
  514. if (texture is TextureView srcTexture)
  515. {
  516. SupportBufferUpdater.Commit();
  517. var oldCullMode = _newState.CullMode;
  518. var oldStencilTestEnable = _newState.StencilTestEnable;
  519. var oldDepthTestEnable = _newState.DepthTestEnable;
  520. var oldDepthWriteEnable = _newState.DepthWriteEnable;
  521. var oldTopology = _newState.Topology;
  522. var oldViewports = DynamicState.Viewports;
  523. var oldViewportsCount = _newState.ViewportsCount;
  524. _newState.CullMode = CullModeFlags.None;
  525. _newState.StencilTestEnable = false;
  526. _newState.DepthTestEnable = false;
  527. _newState.DepthWriteEnable = false;
  528. SignalStateChange();
  529. Gd.HelperShader.DrawTexture(
  530. Gd,
  531. this,
  532. srcTexture,
  533. sampler,
  534. srcRegion,
  535. dstRegion);
  536. _newState.CullMode = oldCullMode;
  537. _newState.StencilTestEnable = oldStencilTestEnable;
  538. _newState.DepthTestEnable = oldDepthTestEnable;
  539. _newState.DepthWriteEnable = oldDepthWriteEnable;
  540. _newState.Topology = oldTopology;
  541. DynamicState.SetViewports(ref oldViewports, oldViewportsCount);
  542. _newState.ViewportsCount = oldViewportsCount;
  543. SignalStateChange();
  544. }
  545. }
  546. public void EndTransformFeedback()
  547. {
  548. PauseTransformFeedbackInternal();
  549. _tfEnabled = false;
  550. }
  551. public double GetCounterDivisor(CounterType type)
  552. {
  553. if (type == CounterType.SamplesPassed)
  554. {
  555. return _renderScale[0].X * _renderScale[0].X;
  556. }
  557. return 1;
  558. }
  559. public bool IsCommandBufferActive(CommandBuffer cb)
  560. {
  561. return CommandBuffer.Handle == cb.Handle;
  562. }
  563. public void SetAlphaTest(bool enable, float reference, GAL.CompareOp op)
  564. {
  565. // This is currently handled using shader specialization, as Vulkan does not support alpha test.
  566. // In the future, we may want to use this to write the reference value into the support buffer,
  567. // to avoid creating one version of the shader per reference value used.
  568. }
  569. public void SetBlendState(AdvancedBlendDescriptor blend)
  570. {
  571. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  572. {
  573. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index];
  574. if (index == 0)
  575. {
  576. var blendOp = blend.Op.Convert();
  577. vkBlend = new PipelineColorBlendAttachmentState(
  578. blendEnable: true,
  579. colorBlendOp: blendOp,
  580. alphaBlendOp: blendOp,
  581. colorWriteMask: vkBlend.ColorWriteMask);
  582. if (Gd.Capabilities.SupportsBlendEquationAdvancedNonPreMultipliedSrcColor)
  583. {
  584. _newState.AdvancedBlendSrcPreMultiplied = blend.SrcPreMultiplied;
  585. }
  586. if (Gd.Capabilities.SupportsBlendEquationAdvancedCorrelatedOverlap)
  587. {
  588. _newState.AdvancedBlendOverlap = blend.Overlap.Convert();
  589. }
  590. }
  591. else
  592. {
  593. vkBlend = new PipelineColorBlendAttachmentState(
  594. colorWriteMask: vkBlend.ColorWriteMask);
  595. }
  596. if (vkBlend.ColorWriteMask == 0)
  597. {
  598. _storedBlend[index] = vkBlend;
  599. vkBlend = new PipelineColorBlendAttachmentState();
  600. }
  601. }
  602. SignalStateChange();
  603. }
  604. public void SetBlendState(int index, BlendDescriptor blend)
  605. {
  606. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[index];
  607. if (blend.Enable)
  608. {
  609. vkBlend.BlendEnable = blend.Enable;
  610. vkBlend.SrcColorBlendFactor = blend.ColorSrcFactor.Convert();
  611. vkBlend.DstColorBlendFactor = blend.ColorDstFactor.Convert();
  612. vkBlend.ColorBlendOp = blend.ColorOp.Convert();
  613. vkBlend.SrcAlphaBlendFactor = blend.AlphaSrcFactor.Convert();
  614. vkBlend.DstAlphaBlendFactor = blend.AlphaDstFactor.Convert();
  615. vkBlend.AlphaBlendOp = blend.AlphaOp.Convert();
  616. }
  617. else
  618. {
  619. vkBlend = new PipelineColorBlendAttachmentState(
  620. colorWriteMask: vkBlend.ColorWriteMask);
  621. }
  622. if (vkBlend.ColorWriteMask == 0)
  623. {
  624. _storedBlend[index] = vkBlend;
  625. vkBlend = new PipelineColorBlendAttachmentState();
  626. }
  627. DynamicState.SetBlendConstants(
  628. blend.BlendConstant.Red,
  629. blend.BlendConstant.Green,
  630. blend.BlendConstant.Blue,
  631. blend.BlendConstant.Alpha);
  632. // Reset advanced blend state back defaults to the cache to help the pipeline cache.
  633. _newState.AdvancedBlendSrcPreMultiplied = true;
  634. _newState.AdvancedBlendDstPreMultiplied = true;
  635. _newState.AdvancedBlendOverlap = BlendOverlapEXT.UncorrelatedExt;
  636. SignalStateChange();
  637. }
  638. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  639. {
  640. DynamicState.SetDepthBias(factor, units, clamp);
  641. _newState.DepthBiasEnable = enables != 0;
  642. SignalStateChange();
  643. }
  644. public void SetDepthClamp(bool clamp)
  645. {
  646. _newState.DepthClampEnable = clamp;
  647. SignalStateChange();
  648. }
  649. public void SetDepthMode(DepthMode mode)
  650. {
  651. // Currently this is emulated on the shader, because Vulkan had no support for changing the depth mode.
  652. // In the future, we may want to use the VK_EXT_depth_clip_control extension to change it here.
  653. }
  654. public void SetDepthTest(DepthTestDescriptor depthTest)
  655. {
  656. _newState.DepthTestEnable = depthTest.TestEnable;
  657. _newState.DepthWriteEnable = depthTest.WriteEnable;
  658. _newState.DepthCompareOp = depthTest.Func.Convert();
  659. SignalStateChange();
  660. }
  661. public void SetFaceCulling(bool enable, Face face)
  662. {
  663. _newState.CullMode = enable ? face.Convert() : CullModeFlags.None;
  664. SignalStateChange();
  665. }
  666. public void SetFrontFace(GAL.FrontFace frontFace)
  667. {
  668. _newState.FrontFace = frontFace.Convert();
  669. SignalStateChange();
  670. }
  671. public void SetImage(int binding, ITexture image, GAL.Format imageFormat)
  672. {
  673. _descriptorSetUpdater.SetImage(binding, image, imageFormat);
  674. }
  675. public void SetImage(int binding, Auto<DisposableImageView> image)
  676. {
  677. _descriptorSetUpdater.SetImage(binding, image);
  678. }
  679. public void SetIndexBuffer(BufferRange buffer, GAL.IndexType type)
  680. {
  681. if (buffer.Handle != BufferHandle.Null)
  682. {
  683. _indexBuffer = new IndexBufferState(buffer.Handle, buffer.Offset, buffer.Size, type.Convert());
  684. }
  685. else
  686. {
  687. _indexBuffer = IndexBufferState.Null;
  688. }
  689. _needsIndexBufferRebind = true;
  690. }
  691. public void SetLineParameters(float width, bool smooth)
  692. {
  693. _newState.LineWidth = width;
  694. SignalStateChange();
  695. }
  696. public void SetLogicOpState(bool enable, LogicalOp op)
  697. {
  698. _newState.LogicOpEnable = enable;
  699. _newState.LogicOp = op.Convert();
  700. SignalStateChange();
  701. }
  702. public void SetMultisampleState(MultisampleDescriptor multisample)
  703. {
  704. _newState.AlphaToCoverageEnable = multisample.AlphaToCoverageEnable;
  705. _newState.AlphaToOneEnable = multisample.AlphaToOneEnable;
  706. SignalStateChange();
  707. }
  708. public void SetOrigin(Origin origin)
  709. {
  710. // TODO.
  711. }
  712. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  713. {
  714. _newState.PatchControlPoints = (uint)vertices;
  715. SignalStateChange();
  716. // TODO: Default levels (likely needs emulation on shaders?)
  717. }
  718. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  719. {
  720. // TODO.
  721. }
  722. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  723. {
  724. // TODO.
  725. }
  726. public void SetPrimitiveRestart(bool enable, int index)
  727. {
  728. _newState.PrimitiveRestartEnable = enable;
  729. // TODO: What to do about the index?
  730. SignalStateChange();
  731. }
  732. public void SetPrimitiveTopology(GAL.PrimitiveTopology topology)
  733. {
  734. _topology = topology;
  735. var vkTopology = Gd.TopologyRemap(topology).Convert();
  736. _newState.Topology = vkTopology;
  737. SignalStateChange();
  738. }
  739. public void SetProgram(IProgram program)
  740. {
  741. var internalProgram = (ShaderCollection)program;
  742. var stages = internalProgram.GetInfos();
  743. _program = internalProgram;
  744. _descriptorSetUpdater.SetProgram(internalProgram);
  745. _newState.PipelineLayout = internalProgram.PipelineLayout;
  746. _newState.StagesCount = (uint)stages.Length;
  747. stages.CopyTo(_newState.Stages.AsSpan().Slice(0, stages.Length));
  748. SignalStateChange();
  749. if (_program.IsCompute)
  750. {
  751. EndRenderPass();
  752. }
  753. }
  754. public void Specialize<T>(in T data) where T : unmanaged
  755. {
  756. var dataSpan = MemoryMarshal.AsBytes(MemoryMarshal.CreateReadOnlySpan(ref Unsafe.AsRef(in data), 1));
  757. if (!dataSpan.SequenceEqual(_newState.SpecializationData.Span))
  758. {
  759. _newState.SpecializationData = new SpecData(dataSpan);
  760. SignalStateChange();
  761. }
  762. }
  763. protected virtual void SignalAttachmentChange()
  764. {
  765. }
  766. public void SetRasterizerDiscard(bool discard)
  767. {
  768. _newState.RasterizerDiscardEnable = discard;
  769. SignalStateChange();
  770. }
  771. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMask)
  772. {
  773. int count = Math.Min(Constants.MaxRenderTargets, componentMask.Length);
  774. int writtenAttachments = 0;
  775. for (int i = 0; i < count; i++)
  776. {
  777. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i];
  778. var newMask = (ColorComponentFlags)componentMask[i];
  779. // When color write mask is 0, remove all blend state to help the pipeline cache.
  780. // Restore it when the mask becomes non-zero.
  781. if (vkBlend.ColorWriteMask != newMask)
  782. {
  783. if (newMask == 0)
  784. {
  785. _storedBlend[i] = vkBlend;
  786. vkBlend = new PipelineColorBlendAttachmentState();
  787. }
  788. else if (vkBlend.ColorWriteMask == 0)
  789. {
  790. vkBlend = _storedBlend[i];
  791. }
  792. }
  793. vkBlend.ColorWriteMask = newMask;
  794. if (componentMask[i] != 0)
  795. {
  796. writtenAttachments++;
  797. }
  798. }
  799. if (_framebufferUsingColorWriteMask)
  800. {
  801. SetRenderTargetsInternal(_preMaskColors, _preMaskDepthStencil, true);
  802. }
  803. else
  804. {
  805. SignalStateChange();
  806. if (writtenAttachments != _writtenAttachmentCount)
  807. {
  808. SignalAttachmentChange();
  809. _writtenAttachmentCount = writtenAttachments;
  810. }
  811. }
  812. }
  813. private void SetRenderTargetsInternal(ITexture[] colors, ITexture depthStencil, bool filterWriteMasked)
  814. {
  815. FramebufferParams?.UpdateModifications();
  816. CreateFramebuffer(colors, depthStencil, filterWriteMasked);
  817. CreateRenderPass();
  818. SignalStateChange();
  819. SignalAttachmentChange();
  820. }
  821. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  822. {
  823. _framebufferUsingColorWriteMask = false;
  824. SetRenderTargetsInternal(colors, depthStencil, Gd.IsTBDR);
  825. }
  826. public void SetRenderTargetScale(float scale)
  827. {
  828. _renderScale[0].X = scale;
  829. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  830. }
  831. public void SetScissors(ReadOnlySpan<Rectangle<int>> regions)
  832. {
  833. int maxScissors = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  834. int count = Math.Min(maxScissors, regions.Length);
  835. if (count > 0)
  836. {
  837. ClearScissor = regions[0];
  838. }
  839. for (int i = 0; i < count; i++)
  840. {
  841. var region = regions[i];
  842. var offset = new Offset2D(region.X, region.Y);
  843. var extent = new Extent2D((uint)region.Width, (uint)region.Height);
  844. DynamicState.SetScissor(i, new Rect2D(offset, extent));
  845. }
  846. DynamicState.ScissorsCount = count;
  847. _newState.ScissorsCount = (uint)count;
  848. SignalStateChange();
  849. }
  850. public void SetStencilTest(StencilTestDescriptor stencilTest)
  851. {
  852. DynamicState.SetStencilMasks(
  853. (uint)stencilTest.BackFuncMask,
  854. (uint)stencilTest.BackMask,
  855. (uint)stencilTest.BackFuncRef,
  856. (uint)stencilTest.FrontFuncMask,
  857. (uint)stencilTest.FrontMask,
  858. (uint)stencilTest.FrontFuncRef);
  859. _newState.StencilTestEnable = stencilTest.TestEnable;
  860. _newState.StencilBackFailOp = stencilTest.BackSFail.Convert();
  861. _newState.StencilBackPassOp = stencilTest.BackDpPass.Convert();
  862. _newState.StencilBackDepthFailOp = stencilTest.BackDpFail.Convert();
  863. _newState.StencilBackCompareOp = stencilTest.BackFunc.Convert();
  864. _newState.StencilFrontFailOp = stencilTest.FrontSFail.Convert();
  865. _newState.StencilFrontPassOp = stencilTest.FrontDpPass.Convert();
  866. _newState.StencilFrontDepthFailOp = stencilTest.FrontDpFail.Convert();
  867. _newState.StencilFrontCompareOp = stencilTest.FrontFunc.Convert();
  868. SignalStateChange();
  869. }
  870. public void SetStorageBuffers(ReadOnlySpan<BufferAssignment> buffers)
  871. {
  872. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, buffers);
  873. }
  874. public void SetStorageBuffers(int first, ReadOnlySpan<Auto<DisposableBuffer>> buffers)
  875. {
  876. _descriptorSetUpdater.SetStorageBuffers(CommandBuffer, first, buffers);
  877. }
  878. public void SetTextureAndSampler(ShaderStage stage, int binding, ITexture texture, ISampler sampler)
  879. {
  880. _descriptorSetUpdater.SetTextureAndSampler(Cbs, stage, binding, texture, sampler);
  881. }
  882. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  883. {
  884. PauseTransformFeedbackInternal();
  885. int count = Math.Min(Constants.MaxTransformFeedbackBuffers, buffers.Length);
  886. for (int i = 0; i < count; i++)
  887. {
  888. var range = buffers[i];
  889. _transformFeedbackBuffers[i].Dispose();
  890. if (range.Handle != BufferHandle.Null)
  891. {
  892. _transformFeedbackBuffers[i] =
  893. new BufferState(Gd.BufferManager.GetBuffer(CommandBuffer, range.Handle, range.Offset, range.Size, true), range.Offset, range.Size);
  894. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  895. }
  896. else
  897. {
  898. _transformFeedbackBuffers[i] = BufferState.Null;
  899. }
  900. }
  901. }
  902. public void SetUniformBuffers(ReadOnlySpan<BufferAssignment> buffers)
  903. {
  904. _descriptorSetUpdater.SetUniformBuffers(CommandBuffer, buffers);
  905. }
  906. public void SetUserClipDistance(int index, bool enableClip)
  907. {
  908. // TODO.
  909. }
  910. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  911. {
  912. var formatCapabilities = Gd.FormatCapabilities;
  913. Span<int> newVbScalarSizes = stackalloc int[Constants.MaxVertexBuffers];
  914. int count = Math.Min(Constants.MaxVertexAttributes, vertexAttribs.Length);
  915. uint dirtyVbSizes = 0;
  916. for (int i = 0; i < count; i++)
  917. {
  918. var attribute = vertexAttribs[i];
  919. var rawIndex = attribute.BufferIndex;
  920. var bufferIndex = attribute.IsZero ? 0 : rawIndex + 1;
  921. if (!attribute.IsZero)
  922. {
  923. newVbScalarSizes[rawIndex] = Math.Max(newVbScalarSizes[rawIndex], attribute.Format.GetScalarSize());
  924. dirtyVbSizes |= 1u << rawIndex;
  925. }
  926. _newState.Internal.VertexAttributeDescriptions[i] = new VertexInputAttributeDescription(
  927. (uint)i,
  928. (uint)bufferIndex,
  929. formatCapabilities.ConvertToVertexVkFormat(attribute.Format),
  930. (uint)attribute.Offset);
  931. }
  932. while (dirtyVbSizes != 0)
  933. {
  934. int dirtyBit = BitOperations.TrailingZeroCount(dirtyVbSizes);
  935. ref var buffer = ref _vertexBuffers[dirtyBit + 1];
  936. if (buffer.AttributeScalarAlignment != newVbScalarSizes[dirtyBit])
  937. {
  938. _vertexBuffersDirty |= 1UL << (dirtyBit + 1);
  939. buffer.AttributeScalarAlignment = newVbScalarSizes[dirtyBit];
  940. }
  941. dirtyVbSizes &= ~(1u << dirtyBit);
  942. }
  943. _newState.VertexAttributeDescriptionsCount = (uint)count;
  944. SignalStateChange();
  945. }
  946. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  947. {
  948. int count = Math.Min(Constants.MaxVertexBuffers, vertexBuffers.Length);
  949. _newState.Internal.VertexBindingDescriptions[0] = new VertexInputBindingDescription(0, 0, VertexInputRate.Vertex);
  950. int validCount = 1;
  951. for (int i = 0; i < count; i++)
  952. {
  953. var vertexBuffer = vertexBuffers[i];
  954. // TODO: Support divisor > 1
  955. var inputRate = vertexBuffer.Divisor != 0 ? VertexInputRate.Instance : VertexInputRate.Vertex;
  956. if (vertexBuffer.Buffer.Handle != BufferHandle.Null)
  957. {
  958. var vb = Gd.BufferManager.GetBuffer(CommandBuffer, vertexBuffer.Buffer.Handle, false);
  959. if (vb != null)
  960. {
  961. int binding = i + 1;
  962. int descriptorIndex = validCount++;
  963. _newState.Internal.VertexBindingDescriptions[descriptorIndex] = new VertexInputBindingDescription(
  964. (uint)binding,
  965. (uint)vertexBuffer.Stride,
  966. inputRate);
  967. int vbSize = vertexBuffer.Buffer.Size;
  968. if (Gd.Vendor == Vendor.Amd && !Gd.IsMoltenVk && vertexBuffer.Stride > 0)
  969. {
  970. // AMD has a bug where if offset + stride * count is greater than
  971. // the size, then the last attribute will have the wrong value.
  972. // As a workaround, simply use the full buffer size.
  973. int remainder = vbSize % vertexBuffer.Stride;
  974. if (remainder != 0)
  975. {
  976. vbSize += vertexBuffer.Stride - remainder;
  977. }
  978. }
  979. ref var buffer = ref _vertexBuffers[binding];
  980. int oldScalarAlign = buffer.AttributeScalarAlignment;
  981. buffer.Dispose();
  982. if (Gd.Capabilities.VertexBufferAlignment < 2 &&
  983. (vertexBuffer.Stride % FormatExtensions.MaxBufferFormatScalarSize) == 0)
  984. {
  985. buffer = new VertexBufferState(
  986. vb,
  987. descriptorIndex,
  988. vertexBuffer.Buffer.Offset,
  989. vbSize,
  990. vertexBuffer.Stride);
  991. buffer.BindVertexBuffer(Gd, Cbs, (uint)binding, ref _newState);
  992. }
  993. else
  994. {
  995. // May need to be rewritten. Bind this buffer before draw.
  996. buffer = new VertexBufferState(
  997. vertexBuffer.Buffer.Handle,
  998. descriptorIndex,
  999. vertexBuffer.Buffer.Offset,
  1000. vbSize,
  1001. vertexBuffer.Stride);
  1002. _vertexBuffersDirty |= 1UL << binding;
  1003. }
  1004. buffer.AttributeScalarAlignment = oldScalarAlign;
  1005. }
  1006. }
  1007. }
  1008. _newState.VertexBindingDescriptionsCount = (uint)validCount;
  1009. SignalStateChange();
  1010. }
  1011. public void SetViewports(ReadOnlySpan<GAL.Viewport> viewports, bool disableTransform)
  1012. {
  1013. int maxViewports = Gd.Capabilities.SupportsMultiView ? Constants.MaxViewports : 1;
  1014. int count = Math.Min(maxViewports, viewports.Length);
  1015. static float Clamp(float value)
  1016. {
  1017. return Math.Clamp(value, 0f, 1f);
  1018. }
  1019. DynamicState.ViewportsCount = (uint)count;
  1020. for (int i = 0; i < count; i++)
  1021. {
  1022. var viewport = viewports[i];
  1023. DynamicState.SetViewport(i, new Silk.NET.Vulkan.Viewport(
  1024. viewport.Region.X,
  1025. viewport.Region.Y,
  1026. viewport.Region.Width == 0f ? 1f : viewport.Region.Width,
  1027. viewport.Region.Height == 0f ? 1f : viewport.Region.Height,
  1028. Clamp(viewport.DepthNear),
  1029. Clamp(viewport.DepthFar)));
  1030. }
  1031. float disableTransformF = disableTransform ? 1.0f : 0.0f;
  1032. if (SupportBufferUpdater.Data.ViewportInverse.W != disableTransformF || disableTransform)
  1033. {
  1034. float scale = _renderScale[0].X;
  1035. SupportBufferUpdater.UpdateViewportInverse(new Vector4<float>
  1036. {
  1037. X = scale * 2f / viewports[0].Region.Width,
  1038. Y = scale * 2f / viewports[0].Region.Height,
  1039. Z = 1,
  1040. W = disableTransformF
  1041. });
  1042. }
  1043. _newState.ViewportsCount = (uint)count;
  1044. SignalStateChange();
  1045. }
  1046. public void SwapBuffer(Auto<DisposableBuffer> from, Auto<DisposableBuffer> to)
  1047. {
  1048. _indexBuffer.Swap(from, to);
  1049. for (int i = 0; i < _vertexBuffers.Length; i++)
  1050. {
  1051. _vertexBuffers[i].Swap(from, to);
  1052. }
  1053. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1054. {
  1055. _transformFeedbackBuffers[i].Swap(from, to);
  1056. }
  1057. _descriptorSetUpdater.SwapBuffer(from, to);
  1058. SignalCommandBufferChange();
  1059. }
  1060. public unsafe void TextureBarrier()
  1061. {
  1062. MemoryBarrier memoryBarrier = new MemoryBarrier()
  1063. {
  1064. SType = StructureType.MemoryBarrier,
  1065. SrcAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit,
  1066. DstAccessMask = AccessFlags.MemoryReadBit | AccessFlags.MemoryWriteBit
  1067. };
  1068. Gd.Api.CmdPipelineBarrier(
  1069. CommandBuffer,
  1070. PipelineStageFlags.FragmentShaderBit,
  1071. PipelineStageFlags.FragmentShaderBit,
  1072. 0,
  1073. 1,
  1074. memoryBarrier,
  1075. 0,
  1076. null,
  1077. 0,
  1078. null);
  1079. }
  1080. public void TextureBarrierTiled()
  1081. {
  1082. TextureBarrier();
  1083. }
  1084. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  1085. {
  1086. bool changed = false;
  1087. for (int index = 0; index < totalCount; index++)
  1088. {
  1089. if (_renderScale[1 + index].X != scales[index])
  1090. {
  1091. _renderScale[1 + index].X = scales[index];
  1092. changed = true;
  1093. }
  1094. }
  1095. // Only update fragment count if there are scales after it for the vertex stage.
  1096. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  1097. {
  1098. _fragmentScaleCount = fragmentCount;
  1099. SupportBufferUpdater.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  1100. }
  1101. if (changed)
  1102. {
  1103. SupportBufferUpdater.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  1104. }
  1105. }
  1106. protected void SignalCommandBufferChange()
  1107. {
  1108. _needsIndexBufferRebind = true;
  1109. _needsTransformFeedbackBuffersRebind = true;
  1110. _vertexBuffersDirty = ulong.MaxValue >> (64 - _vertexBuffers.Length);
  1111. _descriptorSetUpdater.SignalCommandBufferChange();
  1112. DynamicState.ForceAllDirty();
  1113. _currentPipelineHandle = 0;
  1114. }
  1115. private void CreateFramebuffer(ITexture[] colors, ITexture depthStencil, bool filterWriteMasked)
  1116. {
  1117. if (filterWriteMasked)
  1118. {
  1119. // TBDR GPUs don't work properly if the same attachment is bound to multiple targets,
  1120. // due to each attachment being a copy of the real attachment, rather than a direct write.
  1121. // Just try to remove duplicate attachments.
  1122. // Save a copy of the array to rebind when mask changes.
  1123. void maskOut()
  1124. {
  1125. if (!_framebufferUsingColorWriteMask)
  1126. {
  1127. _preMaskColors = colors.ToArray();
  1128. _preMaskDepthStencil = depthStencil;
  1129. }
  1130. // If true, then the framebuffer must be recreated when the mask changes.
  1131. _framebufferUsingColorWriteMask = true;
  1132. }
  1133. // Look for textures that are masked out.
  1134. for (int i = 0; i < colors.Length; i++)
  1135. {
  1136. if (colors[i] == null)
  1137. {
  1138. continue;
  1139. }
  1140. ref var vkBlend = ref _newState.Internal.ColorBlendAttachmentState[i];
  1141. for (int j = 0; j < i; j++)
  1142. {
  1143. // Check each binding for a duplicate binding before it.
  1144. if (colors[i] == colors[j])
  1145. {
  1146. // Prefer the binding with no write mask.
  1147. ref var vkBlend2 = ref _newState.Internal.ColorBlendAttachmentState[j];
  1148. if (vkBlend.ColorWriteMask == 0)
  1149. {
  1150. colors[i] = null;
  1151. maskOut();
  1152. }
  1153. else if (vkBlend2.ColorWriteMask == 0)
  1154. {
  1155. colors[j] = null;
  1156. maskOut();
  1157. }
  1158. }
  1159. }
  1160. }
  1161. }
  1162. FramebufferParams = new FramebufferParams(Device, colors, depthStencil);
  1163. UpdatePipelineAttachmentFormats();
  1164. }
  1165. protected void UpdatePipelineAttachmentFormats()
  1166. {
  1167. var dstAttachmentFormats = _newState.Internal.AttachmentFormats.AsSpan();
  1168. FramebufferParams.AttachmentFormats.CopyTo(dstAttachmentFormats);
  1169. for (int i = FramebufferParams.AttachmentFormats.Length; i < dstAttachmentFormats.Length; i++)
  1170. {
  1171. dstAttachmentFormats[i] = 0;
  1172. }
  1173. _newState.ColorBlendAttachmentStateCount = (uint)(FramebufferParams.MaxColorAttachmentIndex + 1);
  1174. _newState.HasDepthStencil = FramebufferParams.HasDepthStencil;
  1175. _newState.SamplesCount = FramebufferParams.AttachmentSamples.Length != 0 ? FramebufferParams.AttachmentSamples[0] : 1;
  1176. }
  1177. protected unsafe void CreateRenderPass()
  1178. {
  1179. const int MaxAttachments = Constants.MaxRenderTargets + 1;
  1180. AttachmentDescription[] attachmentDescs = null;
  1181. var subpass = new SubpassDescription()
  1182. {
  1183. PipelineBindPoint = PipelineBindPoint.Graphics
  1184. };
  1185. AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments];
  1186. var hasFramebuffer = FramebufferParams != null;
  1187. if (hasFramebuffer && FramebufferParams.AttachmentsCount != 0)
  1188. {
  1189. attachmentDescs = new AttachmentDescription[FramebufferParams.AttachmentsCount];
  1190. for (int i = 0; i < FramebufferParams.AttachmentsCount; i++)
  1191. {
  1192. attachmentDescs[i] = new AttachmentDescription(
  1193. 0,
  1194. FramebufferParams.AttachmentFormats[i],
  1195. TextureStorage.ConvertToSampleCountFlags(Gd.Capabilities.SupportedSampleCounts, FramebufferParams.AttachmentSamples[i]),
  1196. AttachmentLoadOp.Load,
  1197. AttachmentStoreOp.Store,
  1198. AttachmentLoadOp.Load,
  1199. AttachmentStoreOp.Store,
  1200. ImageLayout.General,
  1201. ImageLayout.General);
  1202. }
  1203. int colorAttachmentsCount = FramebufferParams.ColorAttachmentsCount;
  1204. if (colorAttachmentsCount > MaxAttachments - 1)
  1205. {
  1206. colorAttachmentsCount = MaxAttachments - 1;
  1207. }
  1208. if (colorAttachmentsCount != 0)
  1209. {
  1210. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex;
  1211. subpass.ColorAttachmentCount = (uint)maxAttachmentIndex + 1;
  1212. subpass.PColorAttachments = &attachmentReferences[0];
  1213. // Fill with VK_ATTACHMENT_UNUSED to cover any gaps.
  1214. for (int i = 0; i <= maxAttachmentIndex; i++)
  1215. {
  1216. subpass.PColorAttachments[i] = new AttachmentReference(Vk.AttachmentUnused, ImageLayout.Undefined);
  1217. }
  1218. for (int i = 0; i < colorAttachmentsCount; i++)
  1219. {
  1220. int bindIndex = FramebufferParams.AttachmentIndices[i];
  1221. subpass.PColorAttachments[bindIndex] = new AttachmentReference((uint)i, ImageLayout.General);
  1222. }
  1223. }
  1224. if (FramebufferParams.HasDepthStencil)
  1225. {
  1226. uint dsIndex = (uint)FramebufferParams.AttachmentsCount - 1;
  1227. subpass.PDepthStencilAttachment = &attachmentReferences[MaxAttachments - 1];
  1228. *subpass.PDepthStencilAttachment = new AttachmentReference(dsIndex, ImageLayout.General);
  1229. }
  1230. }
  1231. var subpassDependency = PipelineConverter.CreateSubpassDependency();
  1232. fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs)
  1233. {
  1234. var renderPassCreateInfo = new RenderPassCreateInfo()
  1235. {
  1236. SType = StructureType.RenderPassCreateInfo,
  1237. PAttachments = pAttachmentDescs,
  1238. AttachmentCount = attachmentDescs != null ? (uint)attachmentDescs.Length : 0,
  1239. PSubpasses = &subpass,
  1240. SubpassCount = 1,
  1241. PDependencies = &subpassDependency,
  1242. DependencyCount = 1
  1243. };
  1244. Gd.Api.CreateRenderPass(Device, renderPassCreateInfo, null, out var renderPass).ThrowOnError();
  1245. _renderPass?.Dispose();
  1246. _renderPass = new Auto<DisposableRenderPass>(new DisposableRenderPass(Gd.Api, Device, renderPass));
  1247. }
  1248. EndRenderPass();
  1249. _framebuffer?.Dispose();
  1250. _framebuffer = hasFramebuffer ? FramebufferParams.Create(Gd.Api, Cbs, _renderPass) : null;
  1251. }
  1252. protected void SignalStateChange()
  1253. {
  1254. _stateDirty = true;
  1255. }
  1256. private void RecreatePipelineIfNeeded(PipelineBindPoint pbp)
  1257. {
  1258. DynamicState.ReplayIfDirty(Gd.Api, CommandBuffer);
  1259. // Commit changes to the support buffer before drawing.
  1260. SupportBufferUpdater.Commit();
  1261. if (_needsIndexBufferRebind && _indexBufferPattern == null)
  1262. {
  1263. _indexBuffer.BindIndexBuffer(Gd, Cbs);
  1264. _needsIndexBufferRebind = false;
  1265. }
  1266. if (_needsTransformFeedbackBuffersRebind)
  1267. {
  1268. PauseTransformFeedbackInternal();
  1269. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1270. {
  1271. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  1272. }
  1273. _needsTransformFeedbackBuffersRebind = false;
  1274. }
  1275. if (_vertexBuffersDirty != 0)
  1276. {
  1277. while (_vertexBuffersDirty != 0)
  1278. {
  1279. int i = BitOperations.TrailingZeroCount(_vertexBuffersDirty);
  1280. _vertexBuffers[i].BindVertexBuffer(Gd, Cbs, (uint)i, ref _newState);
  1281. _vertexBuffersDirty &= ~(1UL << i);
  1282. }
  1283. }
  1284. if (_stateDirty || Pbp != pbp)
  1285. {
  1286. CreatePipeline(pbp);
  1287. _stateDirty = false;
  1288. Pbp = pbp;
  1289. }
  1290. _descriptorSetUpdater.UpdateAndBindDescriptorSets(Cbs, pbp);
  1291. }
  1292. private void CreatePipeline(PipelineBindPoint pbp)
  1293. {
  1294. // We can only create a pipeline if the have the shader stages set.
  1295. if (_newState.Stages != null)
  1296. {
  1297. if (pbp == PipelineBindPoint.Graphics && _renderPass == null)
  1298. {
  1299. CreateRenderPass();
  1300. }
  1301. var pipeline = pbp == PipelineBindPoint.Compute
  1302. ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache)
  1303. : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass.Get(Cbs).Value);
  1304. ulong pipelineHandle = pipeline.GetUnsafe().Value.Handle;
  1305. if (_currentPipelineHandle != pipelineHandle)
  1306. {
  1307. _currentPipelineHandle = pipelineHandle;
  1308. Pipeline = pipeline;
  1309. PauseTransformFeedbackInternal();
  1310. Gd.Api.CmdBindPipeline(CommandBuffer, pbp, Pipeline.Get(Cbs).Value);
  1311. }
  1312. }
  1313. }
  1314. private unsafe void BeginRenderPass()
  1315. {
  1316. if (!RenderPassActive)
  1317. {
  1318. var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height));
  1319. var clearValue = new ClearValue();
  1320. var renderPassBeginInfo = new RenderPassBeginInfo()
  1321. {
  1322. SType = StructureType.RenderPassBeginInfo,
  1323. RenderPass = _renderPass.Get(Cbs).Value,
  1324. Framebuffer = _framebuffer.Get(Cbs).Value,
  1325. RenderArea = renderArea,
  1326. PClearValues = &clearValue,
  1327. ClearValueCount = 1
  1328. };
  1329. Gd.Api.CmdBeginRenderPass(CommandBuffer, renderPassBeginInfo, SubpassContents.Inline);
  1330. RenderPassActive = true;
  1331. }
  1332. }
  1333. public void EndRenderPass()
  1334. {
  1335. if (RenderPassActive)
  1336. {
  1337. PauseTransformFeedbackInternal();
  1338. Gd.Api.CmdEndRenderPass(CommandBuffer);
  1339. SignalRenderPassEnd();
  1340. RenderPassActive = false;
  1341. }
  1342. }
  1343. protected virtual void SignalRenderPassEnd()
  1344. {
  1345. }
  1346. private void PauseTransformFeedbackInternal()
  1347. {
  1348. if (_tfEnabled && _tfActive)
  1349. {
  1350. EndTransformFeedbackInternal();
  1351. _tfActive = false;
  1352. }
  1353. }
  1354. private void ResumeTransformFeedbackInternal()
  1355. {
  1356. if (_tfEnabled && !_tfActive)
  1357. {
  1358. BeginTransformFeedbackInternal();
  1359. _tfActive = true;
  1360. }
  1361. }
  1362. private unsafe void BeginTransformFeedbackInternal()
  1363. {
  1364. Gd.TransformFeedbackApi.CmdBeginTransformFeedback(CommandBuffer, 0, 0, null, null);
  1365. }
  1366. private unsafe void EndTransformFeedbackInternal()
  1367. {
  1368. Gd.TransformFeedbackApi.CmdEndTransformFeedback(CommandBuffer, 0, 0, null, null);
  1369. }
  1370. protected virtual void Dispose(bool disposing)
  1371. {
  1372. if (disposing)
  1373. {
  1374. _renderPass?.Dispose();
  1375. _framebuffer?.Dispose();
  1376. _newState.Dispose();
  1377. _descriptorSetUpdater.Dispose();
  1378. for (int i = 0; i < _vertexBuffers.Length; i++)
  1379. {
  1380. _vertexBuffers[i].Dispose();
  1381. }
  1382. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1383. {
  1384. _transformFeedbackBuffers[i].Dispose();
  1385. }
  1386. Pipeline?.Dispose();
  1387. unsafe
  1388. {
  1389. Gd.Api.DestroyPipelineCache(Device, PipelineCache, null);
  1390. }
  1391. SupportBufferUpdater.Dispose();
  1392. }
  1393. }
  1394. public void Dispose()
  1395. {
  1396. Dispose(true);
  1397. }
  1398. }
  1399. }