PipelineBase.cs 50 KB

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