PipelineBase.cs 43 KB

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