PipelineBase.cs 58 KB

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