PipelineBase.cs 56 KB

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