PipelineBase.cs 59 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635
  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. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex + (FramebufferParams.HasDepthStencil ? 1 : 0);
  1088. for (int i = FramebufferParams.AttachmentFormats.Length; i <= maxAttachmentIndex; i++)
  1089. {
  1090. dstAttachmentFormats[i] = 0;
  1091. }
  1092. _newState.ColorBlendAttachmentStateCount = (uint)(FramebufferParams.MaxColorAttachmentIndex + 1);
  1093. _newState.HasDepthStencil = FramebufferParams.HasDepthStencil;
  1094. _newState.SamplesCount = FramebufferParams.AttachmentSamples.Length != 0 ? FramebufferParams.AttachmentSamples[0] : 1;
  1095. }
  1096. protected unsafe void CreateRenderPass()
  1097. {
  1098. const int MaxAttachments = Constants.MaxRenderTargets + 1;
  1099. AttachmentDescription[] attachmentDescs = null;
  1100. var subpass = new SubpassDescription()
  1101. {
  1102. PipelineBindPoint = PipelineBindPoint.Graphics
  1103. };
  1104. AttachmentReference* attachmentReferences = stackalloc AttachmentReference[MaxAttachments];
  1105. var hasFramebuffer = FramebufferParams != null;
  1106. if (hasFramebuffer && FramebufferParams.AttachmentsCount != 0)
  1107. {
  1108. attachmentDescs = new AttachmentDescription[FramebufferParams.AttachmentsCount];
  1109. for (int i = 0; i < FramebufferParams.AttachmentsCount; i++)
  1110. {
  1111. int bindIndex = FramebufferParams.AttachmentIndices[i];
  1112. attachmentDescs[i] = new AttachmentDescription(
  1113. 0,
  1114. FramebufferParams.AttachmentFormats[i],
  1115. TextureStorage.ConvertToSampleCountFlags(Gd.Capabilities.SupportedSampleCounts, FramebufferParams.AttachmentSamples[i]),
  1116. AttachmentLoadOp.Load,
  1117. AttachmentStoreOp.Store,
  1118. AttachmentLoadOp.Load,
  1119. AttachmentStoreOp.Store,
  1120. ImageLayout.General,
  1121. ImageLayout.General);
  1122. }
  1123. int colorAttachmentsCount = FramebufferParams.ColorAttachmentsCount;
  1124. if (colorAttachmentsCount > MaxAttachments - 1)
  1125. {
  1126. colorAttachmentsCount = MaxAttachments - 1;
  1127. }
  1128. if (colorAttachmentsCount != 0)
  1129. {
  1130. int maxAttachmentIndex = FramebufferParams.MaxColorAttachmentIndex;
  1131. subpass.ColorAttachmentCount = (uint)maxAttachmentIndex + 1;
  1132. subpass.PColorAttachments = &attachmentReferences[0];
  1133. // Fill with VK_ATTACHMENT_UNUSED to cover any gaps.
  1134. for (int i = 0; i <= maxAttachmentIndex; i++)
  1135. {
  1136. subpass.PColorAttachments[i] = new AttachmentReference(Vk.AttachmentUnused, ImageLayout.Undefined);
  1137. }
  1138. for (int i = 0; i < colorAttachmentsCount; i++)
  1139. {
  1140. int bindIndex = FramebufferParams.AttachmentIndices[i];
  1141. subpass.PColorAttachments[bindIndex] = new AttachmentReference((uint)i, ImageLayout.General);
  1142. }
  1143. }
  1144. if (FramebufferParams.HasDepthStencil)
  1145. {
  1146. uint dsIndex = (uint)FramebufferParams.AttachmentsCount - 1;
  1147. subpass.PDepthStencilAttachment = &attachmentReferences[MaxAttachments - 1];
  1148. *subpass.PDepthStencilAttachment = new AttachmentReference(dsIndex, ImageLayout.General);
  1149. }
  1150. }
  1151. var subpassDependency = PipelineConverter.CreateSubpassDependency();
  1152. fixed (AttachmentDescription* pAttachmentDescs = attachmentDescs)
  1153. {
  1154. var renderPassCreateInfo = new RenderPassCreateInfo()
  1155. {
  1156. SType = StructureType.RenderPassCreateInfo,
  1157. PAttachments = pAttachmentDescs,
  1158. AttachmentCount = attachmentDescs != null ? (uint)attachmentDescs.Length : 0,
  1159. PSubpasses = &subpass,
  1160. SubpassCount = 1,
  1161. PDependencies = &subpassDependency,
  1162. DependencyCount = 1
  1163. };
  1164. Gd.Api.CreateRenderPass(Device, renderPassCreateInfo, null, out var renderPass).ThrowOnError();
  1165. _renderPass?.Dispose();
  1166. _renderPass = new Auto<DisposableRenderPass>(new DisposableRenderPass(Gd.Api, Device, renderPass));
  1167. }
  1168. EndRenderPass();
  1169. _framebuffer?.Dispose();
  1170. _framebuffer = hasFramebuffer ? FramebufferParams.Create(Gd.Api, Cbs, _renderPass) : null;
  1171. }
  1172. protected void SignalStateChange()
  1173. {
  1174. _stateDirty = true;
  1175. }
  1176. private void RecreatePipelineIfNeeded(PipelineBindPoint pbp)
  1177. {
  1178. DynamicState.ReplayIfDirty(Gd.Api, CommandBuffer);
  1179. // Commit changes to the support buffer before drawing.
  1180. SupportBufferUpdater.Commit();
  1181. if (_needsIndexBufferRebind && _indexBufferPattern == null)
  1182. {
  1183. _indexBuffer.BindIndexBuffer(Gd, Cbs);
  1184. _needsIndexBufferRebind = false;
  1185. }
  1186. if (_needsTransformFeedbackBuffersRebind)
  1187. {
  1188. PauseTransformFeedbackInternal();
  1189. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1190. {
  1191. _transformFeedbackBuffers[i].BindTransformFeedbackBuffer(Gd, Cbs, (uint)i);
  1192. }
  1193. _needsTransformFeedbackBuffersRebind = false;
  1194. }
  1195. if (_vertexBuffersDirty != 0)
  1196. {
  1197. while (_vertexBuffersDirty != 0)
  1198. {
  1199. int i = BitOperations.TrailingZeroCount(_vertexBuffersDirty);
  1200. _vertexBuffers[i].BindVertexBuffer(Gd, Cbs, (uint)i, ref _newState);
  1201. _vertexBuffersDirty &= ~(1UL << i);
  1202. }
  1203. }
  1204. if (_stateDirty || Pbp != pbp)
  1205. {
  1206. CreatePipeline(pbp);
  1207. _stateDirty = false;
  1208. Pbp = pbp;
  1209. }
  1210. _descriptorSetUpdater.UpdateAndBindDescriptorSets(Cbs, pbp);
  1211. }
  1212. private void CreatePipeline(PipelineBindPoint pbp)
  1213. {
  1214. // We can only create a pipeline if the have the shader stages set.
  1215. if (_newState.Stages != null)
  1216. {
  1217. if (pbp == PipelineBindPoint.Graphics && _renderPass == null)
  1218. {
  1219. CreateRenderPass();
  1220. }
  1221. var pipeline = pbp == PipelineBindPoint.Compute
  1222. ? _newState.CreateComputePipeline(Gd, Device, _program, PipelineCache)
  1223. : _newState.CreateGraphicsPipeline(Gd, Device, _program, PipelineCache, _renderPass.Get(Cbs).Value);
  1224. ulong pipelineHandle = pipeline.GetUnsafe().Value.Handle;
  1225. if (_currentPipelineHandle != pipelineHandle)
  1226. {
  1227. _currentPipelineHandle = pipelineHandle;
  1228. Pipeline = pipeline;
  1229. PauseTransformFeedbackInternal();
  1230. Gd.Api.CmdBindPipeline(CommandBuffer, pbp, Pipeline.Get(Cbs).Value);
  1231. }
  1232. }
  1233. }
  1234. private unsafe void BeginRenderPass()
  1235. {
  1236. if (!RenderPassActive)
  1237. {
  1238. var renderArea = new Rect2D(null, new Extent2D(FramebufferParams.Width, FramebufferParams.Height));
  1239. var clearValue = new ClearValue();
  1240. var renderPassBeginInfo = new RenderPassBeginInfo()
  1241. {
  1242. SType = StructureType.RenderPassBeginInfo,
  1243. RenderPass = _renderPass.Get(Cbs).Value,
  1244. Framebuffer = _framebuffer.Get(Cbs).Value,
  1245. RenderArea = renderArea,
  1246. PClearValues = &clearValue,
  1247. ClearValueCount = 1
  1248. };
  1249. Gd.Api.CmdBeginRenderPass(CommandBuffer, renderPassBeginInfo, SubpassContents.Inline);
  1250. RenderPassActive = true;
  1251. }
  1252. }
  1253. public void EndRenderPass()
  1254. {
  1255. if (RenderPassActive)
  1256. {
  1257. PauseTransformFeedbackInternal();
  1258. Gd.Api.CmdEndRenderPass(CommandBuffer);
  1259. SignalRenderPassEnd();
  1260. RenderPassActive = false;
  1261. }
  1262. }
  1263. protected virtual void SignalRenderPassEnd()
  1264. {
  1265. }
  1266. private void PauseTransformFeedbackInternal()
  1267. {
  1268. if (_tfEnabled && _tfActive)
  1269. {
  1270. EndTransformFeedbackInternal();
  1271. _tfActive = false;
  1272. }
  1273. }
  1274. private void ResumeTransformFeedbackInternal()
  1275. {
  1276. if (_tfEnabled && !_tfActive)
  1277. {
  1278. BeginTransformFeedbackInternal();
  1279. _tfActive = true;
  1280. }
  1281. }
  1282. private unsafe void BeginTransformFeedbackInternal()
  1283. {
  1284. Gd.TransformFeedbackApi.CmdBeginTransformFeedback(CommandBuffer, 0, 0, null, null);
  1285. }
  1286. private unsafe void EndTransformFeedbackInternal()
  1287. {
  1288. Gd.TransformFeedbackApi.CmdEndTransformFeedback(CommandBuffer, 0, 0, null, null);
  1289. }
  1290. protected virtual void Dispose(bool disposing)
  1291. {
  1292. if (disposing)
  1293. {
  1294. _renderPass?.Dispose();
  1295. _framebuffer?.Dispose();
  1296. _newState.Dispose();
  1297. _descriptorSetUpdater.Dispose();
  1298. for (int i = 0; i < _vertexBuffers.Length; i++)
  1299. {
  1300. _vertexBuffers[i].Dispose();
  1301. }
  1302. for (int i = 0; i < _transformFeedbackBuffers.Length; i++)
  1303. {
  1304. _transformFeedbackBuffers[i].Dispose();
  1305. }
  1306. Pipeline?.Dispose();
  1307. unsafe
  1308. {
  1309. Gd.Api.DestroyPipelineCache(Device, PipelineCache, null);
  1310. }
  1311. SupportBufferUpdater.Dispose();
  1312. }
  1313. }
  1314. public void Dispose()
  1315. {
  1316. Dispose(true);
  1317. }
  1318. }
  1319. }