Pipeline.cs 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.OpenGL.Image;
  5. using Ryujinx.Graphics.OpenGL.Queries;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. using System.Runtime.CompilerServices;
  9. using System.Runtime.InteropServices;
  10. namespace Ryujinx.Graphics.OpenGL
  11. {
  12. class Pipeline : IPipeline, IDisposable
  13. {
  14. private readonly DrawTextureEmulation _drawTexture;
  15. internal ulong DrawCount { get; private set; }
  16. private Program _program;
  17. private bool _rasterizerDiscard;
  18. private VertexArray _vertexArray;
  19. private Framebuffer _framebuffer;
  20. private IntPtr _indexBaseOffset;
  21. private DrawElementsType _elementsType;
  22. private PrimitiveType _primitiveType;
  23. private int _stencilFrontMask;
  24. private bool _depthMask;
  25. private bool _depthTestEnable;
  26. private bool _stencilTestEnable;
  27. private bool _cullEnable;
  28. private float[] _viewportArray = Array.Empty<float>();
  29. private double[] _depthRangeArray = Array.Empty<double>();
  30. private int _boundDrawFramebuffer;
  31. private int _boundReadFramebuffer;
  32. private CounterQueueEvent _activeConditionalRender;
  33. private Vector4<int>[] _fpIsBgra = new Vector4<int>[SupportBuffer.FragmentIsBgraCount];
  34. private Vector4<float>[] _renderScale = new Vector4<float>[65];
  35. private int _fragmentScaleCount;
  36. private TextureBase _unit0Texture;
  37. private Sampler _unit0Sampler;
  38. private FrontFaceDirection _frontFace;
  39. private ClipOrigin _clipOrigin;
  40. private ClipDepthMode _clipDepthMode;
  41. private readonly uint[] _componentMasks;
  42. private uint _scissorEnables;
  43. private bool _tfEnabled;
  44. private TransformFeedbackPrimitiveType _tfTopology;
  45. private SupportBufferUpdater _supportBuffer;
  46. private readonly BufferHandle[] _tfbs;
  47. private readonly BufferRange[] _tfbTargets;
  48. private ColorF _blendConstant;
  49. internal Pipeline()
  50. {
  51. _drawTexture = new DrawTextureEmulation();
  52. _rasterizerDiscard = false;
  53. _clipOrigin = ClipOrigin.LowerLeft;
  54. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  55. _componentMasks = new uint[Constants.MaxRenderTargets];
  56. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  57. {
  58. _componentMasks[index] = 0xf;
  59. }
  60. var defaultScale = new Vector4<float> { X = 1f, Y = 0f, Z = 0f, W = 0f };
  61. new Span<Vector4<float>>(_renderScale).Fill(defaultScale);
  62. _tfbs = new BufferHandle[Constants.MaxTransformFeedbackBuffers];
  63. _tfbTargets = new BufferRange[Constants.MaxTransformFeedbackBuffers];
  64. }
  65. public void Initialize(Renderer renderer)
  66. {
  67. _supportBuffer = new SupportBufferUpdater(renderer);
  68. GL.BindBufferBase(BufferRangeTarget.UniformBuffer, 0, Unsafe.As<BufferHandle, int>(ref _supportBuffer.Handle));
  69. _supportBuffer.UpdateFragmentIsBgra(_fpIsBgra, 0, SupportBuffer.FragmentIsBgraCount);
  70. _supportBuffer.UpdateRenderScale(_renderScale, 0, SupportBuffer.RenderScaleMaxCount);
  71. }
  72. public void Barrier()
  73. {
  74. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  75. }
  76. public void BeginTransformFeedback(PrimitiveTopology topology)
  77. {
  78. GL.BeginTransformFeedback(_tfTopology = topology.ConvertToTfType());
  79. _tfEnabled = true;
  80. }
  81. public void ClearBuffer(BufferHandle destination, int offset, int size, uint value)
  82. {
  83. Buffer.Clear(destination, offset, size, value);
  84. }
  85. public void ClearRenderTargetColor(int index, uint componentMask, ColorF color)
  86. {
  87. GL.ColorMask(
  88. index,
  89. (componentMask & 1) != 0,
  90. (componentMask & 2) != 0,
  91. (componentMask & 4) != 0,
  92. (componentMask & 8) != 0);
  93. float[] colors = new float[] { color.Red, color.Green, color.Blue, color.Alpha };
  94. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Color, index, colors);
  95. RestoreComponentMask(index);
  96. }
  97. public void ClearRenderTargetDepthStencil(float depthValue, bool depthMask, int stencilValue, int stencilMask)
  98. {
  99. bool stencilMaskChanged =
  100. stencilMask != 0 &&
  101. stencilMask != _stencilFrontMask;
  102. bool depthMaskChanged = depthMask && depthMask != _depthMask;
  103. if (stencilMaskChanged)
  104. {
  105. GL.StencilMaskSeparate(StencilFace.Front, stencilMask);
  106. }
  107. if (depthMaskChanged)
  108. {
  109. GL.DepthMask(depthMask);
  110. }
  111. if (depthMask && stencilMask != 0)
  112. {
  113. GL.ClearBuffer(ClearBufferCombined.DepthStencil, 0, depthValue, stencilValue);
  114. }
  115. else if (depthMask)
  116. {
  117. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Depth, 0, ref depthValue);
  118. }
  119. else if (stencilMask != 0)
  120. {
  121. GL.ClearBuffer(OpenTK.Graphics.OpenGL.ClearBuffer.Stencil, 0, ref stencilValue);
  122. }
  123. if (stencilMaskChanged)
  124. {
  125. GL.StencilMaskSeparate(StencilFace.Front, _stencilFrontMask);
  126. }
  127. if (depthMaskChanged)
  128. {
  129. GL.DepthMask(_depthMask);
  130. }
  131. }
  132. public void CommandBufferBarrier()
  133. {
  134. GL.MemoryBarrier(MemoryBarrierFlags.CommandBarrierBit);
  135. }
  136. public void CopyBuffer(BufferHandle source, BufferHandle destination, int srcOffset, int dstOffset, int size)
  137. {
  138. Buffer.Copy(source, destination, srcOffset, dstOffset, size);
  139. }
  140. public void DispatchCompute(int groupsX, int groupsY, int groupsZ)
  141. {
  142. if (!_program.IsLinked)
  143. {
  144. Logger.Debug?.Print(LogClass.Gpu, "Dispatch error, shader not linked.");
  145. return;
  146. }
  147. PrepareForDispatch();
  148. GL.DispatchCompute(groupsX, groupsY, groupsZ);
  149. }
  150. public void Draw(int vertexCount, int instanceCount, int firstVertex, int firstInstance)
  151. {
  152. if (!_program.IsLinked)
  153. {
  154. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  155. return;
  156. }
  157. PreDraw();
  158. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  159. {
  160. DrawQuadsImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  161. }
  162. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  163. {
  164. DrawQuadStripImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  165. }
  166. else
  167. {
  168. DrawImpl(vertexCount, instanceCount, firstVertex, firstInstance);
  169. }
  170. PostDraw();
  171. }
  172. private void DrawQuadsImpl(
  173. int vertexCount,
  174. int instanceCount,
  175. int firstVertex,
  176. int firstInstance)
  177. {
  178. // TODO: Instanced rendering.
  179. int quadsCount = vertexCount / 4;
  180. int[] firsts = new int[quadsCount];
  181. int[] counts = new int[quadsCount];
  182. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  183. {
  184. firsts[quadIndex] = firstVertex + quadIndex * 4;
  185. counts[quadIndex] = 4;
  186. }
  187. GL.MultiDrawArrays(
  188. PrimitiveType.TriangleFan,
  189. firsts,
  190. counts,
  191. quadsCount);
  192. }
  193. private void DrawQuadStripImpl(
  194. int vertexCount,
  195. int instanceCount,
  196. int firstVertex,
  197. int firstInstance)
  198. {
  199. int quadsCount = (vertexCount - 2) / 2;
  200. if (firstInstance != 0 || instanceCount != 1)
  201. {
  202. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  203. {
  204. GL.DrawArraysInstancedBaseInstance(PrimitiveType.TriangleFan, firstVertex + quadIndex * 2, 4, instanceCount, firstInstance);
  205. }
  206. }
  207. else
  208. {
  209. int[] firsts = new int[quadsCount];
  210. int[] counts = new int[quadsCount];
  211. firsts[0] = firstVertex;
  212. counts[0] = 4;
  213. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  214. {
  215. firsts[quadIndex] = firstVertex + quadIndex * 2;
  216. counts[quadIndex] = 4;
  217. }
  218. GL.MultiDrawArrays(
  219. PrimitiveType.TriangleFan,
  220. firsts,
  221. counts,
  222. quadsCount);
  223. }
  224. }
  225. private void DrawImpl(
  226. int vertexCount,
  227. int instanceCount,
  228. int firstVertex,
  229. int firstInstance)
  230. {
  231. if (firstInstance == 0 && instanceCount == 1)
  232. {
  233. GL.DrawArrays(_primitiveType, firstVertex, vertexCount);
  234. }
  235. else if (firstInstance == 0)
  236. {
  237. GL.DrawArraysInstanced(_primitiveType, firstVertex, vertexCount, instanceCount);
  238. }
  239. else
  240. {
  241. GL.DrawArraysInstancedBaseInstance(
  242. _primitiveType,
  243. firstVertex,
  244. vertexCount,
  245. instanceCount,
  246. firstInstance);
  247. }
  248. }
  249. public void DrawIndexed(
  250. int indexCount,
  251. int instanceCount,
  252. int firstIndex,
  253. int firstVertex,
  254. int firstInstance)
  255. {
  256. if (!_program.IsLinked)
  257. {
  258. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  259. return;
  260. }
  261. PreDraw();
  262. int indexElemSize = 1;
  263. switch (_elementsType)
  264. {
  265. case DrawElementsType.UnsignedShort: indexElemSize = 2; break;
  266. case DrawElementsType.UnsignedInt: indexElemSize = 4; break;
  267. }
  268. IntPtr indexBaseOffset = _indexBaseOffset + firstIndex * indexElemSize;
  269. if (_primitiveType == PrimitiveType.Quads && !HwCapabilities.SupportsQuads)
  270. {
  271. DrawQuadsIndexedImpl(
  272. indexCount,
  273. instanceCount,
  274. indexBaseOffset,
  275. indexElemSize,
  276. firstVertex,
  277. firstInstance);
  278. }
  279. else if (_primitiveType == PrimitiveType.QuadStrip && !HwCapabilities.SupportsQuads)
  280. {
  281. DrawQuadStripIndexedImpl(
  282. indexCount,
  283. instanceCount,
  284. indexBaseOffset,
  285. indexElemSize,
  286. firstVertex,
  287. firstInstance);
  288. }
  289. else
  290. {
  291. DrawIndexedImpl(
  292. indexCount,
  293. instanceCount,
  294. indexBaseOffset,
  295. firstVertex,
  296. firstInstance);
  297. }
  298. PostDraw();
  299. }
  300. private void DrawQuadsIndexedImpl(
  301. int indexCount,
  302. int instanceCount,
  303. IntPtr indexBaseOffset,
  304. int indexElemSize,
  305. int firstVertex,
  306. int firstInstance)
  307. {
  308. int quadsCount = indexCount / 4;
  309. if (firstInstance != 0 || instanceCount != 1)
  310. {
  311. if (firstVertex != 0 && firstInstance != 0)
  312. {
  313. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  314. {
  315. GL.DrawElementsInstancedBaseVertexBaseInstance(
  316. PrimitiveType.TriangleFan,
  317. 4,
  318. _elementsType,
  319. indexBaseOffset + quadIndex * 4 * indexElemSize,
  320. instanceCount,
  321. firstVertex,
  322. firstInstance);
  323. }
  324. }
  325. else if (firstInstance != 0)
  326. {
  327. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  328. {
  329. GL.DrawElementsInstancedBaseInstance(
  330. PrimitiveType.TriangleFan,
  331. 4,
  332. _elementsType,
  333. indexBaseOffset + quadIndex * 4 * indexElemSize,
  334. instanceCount,
  335. firstInstance);
  336. }
  337. }
  338. else
  339. {
  340. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  341. {
  342. GL.DrawElementsInstanced(
  343. PrimitiveType.TriangleFan,
  344. 4,
  345. _elementsType,
  346. indexBaseOffset + quadIndex * 4 * indexElemSize,
  347. instanceCount);
  348. }
  349. }
  350. }
  351. else
  352. {
  353. IntPtr[] indices = new IntPtr[quadsCount];
  354. int[] counts = new int[quadsCount];
  355. int[] baseVertices = new int[quadsCount];
  356. for (int quadIndex = 0; quadIndex < quadsCount; quadIndex++)
  357. {
  358. indices[quadIndex] = indexBaseOffset + quadIndex * 4 * indexElemSize;
  359. counts[quadIndex] = 4;
  360. baseVertices[quadIndex] = firstVertex;
  361. }
  362. GL.MultiDrawElementsBaseVertex(
  363. PrimitiveType.TriangleFan,
  364. counts,
  365. _elementsType,
  366. indices,
  367. quadsCount,
  368. baseVertices);
  369. }
  370. }
  371. private void DrawQuadStripIndexedImpl(
  372. int indexCount,
  373. int instanceCount,
  374. IntPtr indexBaseOffset,
  375. int indexElemSize,
  376. int firstVertex,
  377. int firstInstance)
  378. {
  379. // TODO: Instanced rendering.
  380. int quadsCount = (indexCount - 2) / 2;
  381. IntPtr[] indices = new IntPtr[quadsCount];
  382. int[] counts = new int[quadsCount];
  383. int[] baseVertices = new int[quadsCount];
  384. indices[0] = indexBaseOffset;
  385. counts[0] = 4;
  386. baseVertices[0] = firstVertex;
  387. for (int quadIndex = 1; quadIndex < quadsCount; quadIndex++)
  388. {
  389. indices[quadIndex] = indexBaseOffset + quadIndex * 2 * indexElemSize;
  390. counts[quadIndex] = 4;
  391. baseVertices[quadIndex] = firstVertex;
  392. }
  393. GL.MultiDrawElementsBaseVertex(
  394. PrimitiveType.TriangleFan,
  395. counts,
  396. _elementsType,
  397. indices,
  398. quadsCount,
  399. baseVertices);
  400. }
  401. private void DrawIndexedImpl(
  402. int indexCount,
  403. int instanceCount,
  404. IntPtr indexBaseOffset,
  405. int firstVertex,
  406. int firstInstance)
  407. {
  408. if (firstInstance == 0 && firstVertex == 0 && instanceCount == 1)
  409. {
  410. GL.DrawElements(_primitiveType, indexCount, _elementsType, indexBaseOffset);
  411. }
  412. else if (firstInstance == 0 && instanceCount == 1)
  413. {
  414. GL.DrawElementsBaseVertex(
  415. _primitiveType,
  416. indexCount,
  417. _elementsType,
  418. indexBaseOffset,
  419. firstVertex);
  420. }
  421. else if (firstInstance == 0 && firstVertex == 0)
  422. {
  423. GL.DrawElementsInstanced(
  424. _primitiveType,
  425. indexCount,
  426. _elementsType,
  427. indexBaseOffset,
  428. instanceCount);
  429. }
  430. else if (firstInstance == 0)
  431. {
  432. GL.DrawElementsInstancedBaseVertex(
  433. _primitiveType,
  434. indexCount,
  435. _elementsType,
  436. indexBaseOffset,
  437. instanceCount,
  438. firstVertex);
  439. }
  440. else if (firstVertex == 0)
  441. {
  442. GL.DrawElementsInstancedBaseInstance(
  443. _primitiveType,
  444. indexCount,
  445. _elementsType,
  446. indexBaseOffset,
  447. instanceCount,
  448. firstInstance);
  449. }
  450. else
  451. {
  452. GL.DrawElementsInstancedBaseVertexBaseInstance(
  453. _primitiveType,
  454. indexCount,
  455. _elementsType,
  456. indexBaseOffset,
  457. instanceCount,
  458. firstVertex,
  459. firstInstance);
  460. }
  461. }
  462. public void DrawTexture(ITexture texture, ISampler sampler, Extents2DF srcRegion, Extents2DF dstRegion)
  463. {
  464. if (texture is TextureView view && sampler is Sampler samp)
  465. {
  466. _supportBuffer.Commit();
  467. if (HwCapabilities.SupportsDrawTexture)
  468. {
  469. GL.NV.DrawTexture(
  470. view.Handle,
  471. samp.Handle,
  472. dstRegion.X1,
  473. dstRegion.Y1,
  474. dstRegion.X2,
  475. dstRegion.Y2,
  476. 0,
  477. srcRegion.X1 / view.Width,
  478. srcRegion.Y1 / view.Height,
  479. srcRegion.X2 / view.Width,
  480. srcRegion.Y2 / view.Height);
  481. }
  482. else
  483. {
  484. static void Disable(EnableCap cap, bool enabled)
  485. {
  486. if (enabled)
  487. {
  488. GL.Disable(cap);
  489. }
  490. }
  491. static void Enable(EnableCap cap, bool enabled)
  492. {
  493. if (enabled)
  494. {
  495. GL.Enable(cap);
  496. }
  497. }
  498. Disable(EnableCap.CullFace, _cullEnable);
  499. Disable(EnableCap.StencilTest, _stencilTestEnable);
  500. Disable(EnableCap.DepthTest, _depthTestEnable);
  501. if (_depthMask)
  502. {
  503. GL.DepthMask(false);
  504. }
  505. if (_tfEnabled)
  506. {
  507. GL.EndTransformFeedback();
  508. }
  509. _drawTexture.Draw(
  510. view,
  511. samp,
  512. dstRegion.X1,
  513. dstRegion.Y1,
  514. dstRegion.X2,
  515. dstRegion.Y2,
  516. srcRegion.X1 / view.Width,
  517. srcRegion.Y1 / view.Height,
  518. srcRegion.X2 / view.Width,
  519. srcRegion.Y2 / view.Height);
  520. _program?.Bind();
  521. _unit0Sampler?.Bind(0);
  522. GL.ViewportArray(0, 1, _viewportArray);
  523. Enable(EnableCap.CullFace, _cullEnable);
  524. Enable(EnableCap.StencilTest, _stencilTestEnable);
  525. Enable(EnableCap.DepthTest, _depthTestEnable);
  526. if (_depthMask)
  527. {
  528. GL.DepthMask(true);
  529. }
  530. if (_tfEnabled)
  531. {
  532. GL.BeginTransformFeedback(_tfTopology);
  533. }
  534. }
  535. }
  536. }
  537. public void EndTransformFeedback()
  538. {
  539. GL.EndTransformFeedback();
  540. _tfEnabled = false;
  541. }
  542. public void MultiDrawIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  543. {
  544. if (!_program.IsLinked)
  545. {
  546. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  547. return;
  548. }
  549. PreDraw();
  550. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  551. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  552. GL.MultiDrawArraysIndirectCount(
  553. _primitiveType,
  554. (IntPtr)indirectBuffer.Offset,
  555. (IntPtr)parameterBuffer.Offset,
  556. maxDrawCount,
  557. stride);
  558. PostDraw();
  559. }
  560. public void MultiDrawIndexedIndirectCount(BufferRange indirectBuffer, BufferRange parameterBuffer, int maxDrawCount, int stride)
  561. {
  562. if (!_program.IsLinked)
  563. {
  564. Logger.Debug?.Print(LogClass.Gpu, "Draw error, shader not linked.");
  565. return;
  566. }
  567. PreDraw();
  568. _vertexArray.SetRangeOfIndexBuffer();
  569. GL.BindBuffer((BufferTarget)All.DrawIndirectBuffer, indirectBuffer.Handle.ToInt32());
  570. GL.BindBuffer((BufferTarget)All.ParameterBuffer, parameterBuffer.Handle.ToInt32());
  571. GL.MultiDrawElementsIndirectCount(
  572. _primitiveType,
  573. (Version46)_elementsType,
  574. (IntPtr)indirectBuffer.Offset,
  575. (IntPtr)parameterBuffer.Offset,
  576. maxDrawCount,
  577. stride);
  578. _vertexArray.RestoreIndexBuffer();
  579. PostDraw();
  580. }
  581. public void SetAlphaTest(bool enable, float reference, CompareOp op)
  582. {
  583. if (!enable)
  584. {
  585. GL.Disable(EnableCap.AlphaTest);
  586. return;
  587. }
  588. GL.AlphaFunc((AlphaFunction)op.Convert(), reference);
  589. GL.Enable(EnableCap.AlphaTest);
  590. }
  591. public void SetBlendState(int index, BlendDescriptor blend)
  592. {
  593. if (!blend.Enable)
  594. {
  595. GL.Disable(IndexedEnableCap.Blend, index);
  596. return;
  597. }
  598. GL.BlendEquationSeparate(
  599. index,
  600. blend.ColorOp.Convert(),
  601. blend.AlphaOp.Convert());
  602. GL.BlendFuncSeparate(
  603. index,
  604. (BlendingFactorSrc)blend.ColorSrcFactor.Convert(),
  605. (BlendingFactorDest)blend.ColorDstFactor.Convert(),
  606. (BlendingFactorSrc)blend.AlphaSrcFactor.Convert(),
  607. (BlendingFactorDest)blend.AlphaDstFactor.Convert());
  608. static bool IsDualSource(BlendFactor factor)
  609. {
  610. switch (factor)
  611. {
  612. case BlendFactor.Src1Color:
  613. case BlendFactor.Src1ColorGl:
  614. case BlendFactor.Src1Alpha:
  615. case BlendFactor.Src1AlphaGl:
  616. case BlendFactor.OneMinusSrc1Color:
  617. case BlendFactor.OneMinusSrc1ColorGl:
  618. case BlendFactor.OneMinusSrc1Alpha:
  619. case BlendFactor.OneMinusSrc1AlphaGl:
  620. return true;
  621. }
  622. return false;
  623. }
  624. EnsureFramebuffer();
  625. _framebuffer.SetDualSourceBlend(
  626. IsDualSource(blend.ColorSrcFactor) ||
  627. IsDualSource(blend.ColorDstFactor) ||
  628. IsDualSource(blend.AlphaSrcFactor) ||
  629. IsDualSource(blend.AlphaDstFactor));
  630. if (_blendConstant != blend.BlendConstant)
  631. {
  632. _blendConstant = blend.BlendConstant;
  633. GL.BlendColor(
  634. blend.BlendConstant.Red,
  635. blend.BlendConstant.Green,
  636. blend.BlendConstant.Blue,
  637. blend.BlendConstant.Alpha);
  638. }
  639. GL.Enable(IndexedEnableCap.Blend, index);
  640. }
  641. public void SetDepthBias(PolygonModeMask enables, float factor, float units, float clamp)
  642. {
  643. if ((enables & PolygonModeMask.Point) != 0)
  644. {
  645. GL.Enable(EnableCap.PolygonOffsetPoint);
  646. }
  647. else
  648. {
  649. GL.Disable(EnableCap.PolygonOffsetPoint);
  650. }
  651. if ((enables & PolygonModeMask.Line) != 0)
  652. {
  653. GL.Enable(EnableCap.PolygonOffsetLine);
  654. }
  655. else
  656. {
  657. GL.Disable(EnableCap.PolygonOffsetLine);
  658. }
  659. if ((enables & PolygonModeMask.Fill) != 0)
  660. {
  661. GL.Enable(EnableCap.PolygonOffsetFill);
  662. }
  663. else
  664. {
  665. GL.Disable(EnableCap.PolygonOffsetFill);
  666. }
  667. if (enables == 0)
  668. {
  669. return;
  670. }
  671. if (HwCapabilities.SupportsPolygonOffsetClamp)
  672. {
  673. GL.PolygonOffsetClamp(factor, units, clamp);
  674. }
  675. else
  676. {
  677. GL.PolygonOffset(factor, units);
  678. }
  679. }
  680. public void SetDepthClamp(bool clamp)
  681. {
  682. if (!clamp)
  683. {
  684. GL.Disable(EnableCap.DepthClamp);
  685. return;
  686. }
  687. GL.Enable(EnableCap.DepthClamp);
  688. }
  689. public void SetDepthMode(DepthMode mode)
  690. {
  691. ClipDepthMode depthMode = mode.Convert();
  692. if (_clipDepthMode != depthMode)
  693. {
  694. _clipDepthMode = depthMode;
  695. GL.ClipControl(_clipOrigin, depthMode);
  696. }
  697. }
  698. public void SetDepthTest(DepthTestDescriptor depthTest)
  699. {
  700. if (depthTest.TestEnable)
  701. {
  702. GL.Enable(EnableCap.DepthTest);
  703. GL.DepthFunc((DepthFunction)depthTest.Func.Convert());
  704. }
  705. else
  706. {
  707. GL.Disable(EnableCap.DepthTest);
  708. }
  709. GL.DepthMask(depthTest.WriteEnable);
  710. _depthMask = depthTest.WriteEnable;
  711. _depthTestEnable = depthTest.TestEnable;
  712. }
  713. public void SetFaceCulling(bool enable, Face face)
  714. {
  715. _cullEnable = enable;
  716. if (!enable)
  717. {
  718. GL.Disable(EnableCap.CullFace);
  719. return;
  720. }
  721. GL.CullFace(face.Convert());
  722. GL.Enable(EnableCap.CullFace);
  723. }
  724. public void SetFrontFace(FrontFace frontFace)
  725. {
  726. SetFrontFace(_frontFace = frontFace.Convert());
  727. }
  728. public void SetImage(int binding, ITexture texture, Format imageFormat)
  729. {
  730. if (texture == null)
  731. {
  732. return;
  733. }
  734. TextureBase texBase = (TextureBase)texture;
  735. SizedInternalFormat format = FormatTable.GetImageFormat(imageFormat);
  736. if (format != 0)
  737. {
  738. GL.BindImageTexture(binding, texBase.Handle, 0, true, 0, TextureAccess.ReadWrite, format);
  739. }
  740. }
  741. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  742. {
  743. _elementsType = type.Convert();
  744. _indexBaseOffset = (IntPtr)buffer.Offset;
  745. EnsureVertexArray();
  746. _vertexArray.SetIndexBuffer(buffer);
  747. }
  748. public void SetLogicOpState(bool enable, LogicalOp op)
  749. {
  750. if (enable)
  751. {
  752. GL.Enable(EnableCap.ColorLogicOp);
  753. GL.LogicOp((LogicOp)op.Convert());
  754. }
  755. else
  756. {
  757. GL.Disable(EnableCap.ColorLogicOp);
  758. }
  759. }
  760. public void SetLineParameters(float width, bool smooth)
  761. {
  762. if (smooth)
  763. {
  764. GL.Enable(EnableCap.LineSmooth);
  765. }
  766. else
  767. {
  768. GL.Disable(EnableCap.LineSmooth);
  769. }
  770. GL.LineWidth(width);
  771. }
  772. public unsafe void SetPatchParameters(int vertices, ReadOnlySpan<float> defaultOuterLevel, ReadOnlySpan<float> defaultInnerLevel)
  773. {
  774. GL.PatchParameter(PatchParameterInt.PatchVertices, vertices);
  775. fixed (float* pOuterLevel = defaultOuterLevel)
  776. {
  777. GL.PatchParameter(PatchParameterFloat.PatchDefaultOuterLevel, pOuterLevel);
  778. }
  779. fixed (float* pInnerLevel = defaultInnerLevel)
  780. {
  781. GL.PatchParameter(PatchParameterFloat.PatchDefaultInnerLevel, pInnerLevel);
  782. }
  783. }
  784. public void SetPointParameters(float size, bool isProgramPointSize, bool enablePointSprite, Origin origin)
  785. {
  786. // GL_POINT_SPRITE was deprecated in core profile 3.2+ and causes GL_INVALID_ENUM when set.
  787. // As we don't know if the current context is core or compat, it's safer to keep this code.
  788. if (enablePointSprite)
  789. {
  790. GL.Enable(EnableCap.PointSprite);
  791. }
  792. else
  793. {
  794. GL.Disable(EnableCap.PointSprite);
  795. }
  796. if (isProgramPointSize)
  797. {
  798. GL.Enable(EnableCap.ProgramPointSize);
  799. }
  800. else
  801. {
  802. GL.Disable(EnableCap.ProgramPointSize);
  803. }
  804. GL.PointParameter(origin == Origin.LowerLeft
  805. ? PointSpriteCoordOriginParameter.LowerLeft
  806. : PointSpriteCoordOriginParameter.UpperLeft);
  807. // Games seem to set point size to 0 which generates a GL_INVALID_VALUE
  808. // From the spec, GL_INVALID_VALUE is generated if size is less than or equal to 0.
  809. GL.PointSize(Math.Max(float.Epsilon, size));
  810. }
  811. public void SetPolygonMode(GAL.PolygonMode frontMode, GAL.PolygonMode backMode)
  812. {
  813. if (frontMode == backMode)
  814. {
  815. GL.PolygonMode(MaterialFace.FrontAndBack, frontMode.Convert());
  816. }
  817. else
  818. {
  819. GL.PolygonMode(MaterialFace.Front, frontMode.Convert());
  820. GL.PolygonMode(MaterialFace.Back, backMode.Convert());
  821. }
  822. }
  823. public void SetPrimitiveRestart(bool enable, int index)
  824. {
  825. if (!enable)
  826. {
  827. GL.Disable(EnableCap.PrimitiveRestart);
  828. return;
  829. }
  830. GL.PrimitiveRestartIndex(index);
  831. GL.Enable(EnableCap.PrimitiveRestart);
  832. }
  833. public void SetPrimitiveTopology(PrimitiveTopology topology)
  834. {
  835. _primitiveType = topology.Convert();
  836. }
  837. public void SetProgram(IProgram program)
  838. {
  839. _program = (Program)program;
  840. if (_tfEnabled)
  841. {
  842. GL.EndTransformFeedback();
  843. _program.Bind();
  844. GL.BeginTransformFeedback(_tfTopology);
  845. }
  846. else
  847. {
  848. _program.Bind();
  849. }
  850. }
  851. public void SetRasterizerDiscard(bool discard)
  852. {
  853. if (discard)
  854. {
  855. GL.Enable(EnableCap.RasterizerDiscard);
  856. }
  857. else
  858. {
  859. GL.Disable(EnableCap.RasterizerDiscard);
  860. }
  861. _rasterizerDiscard = discard;
  862. }
  863. public void SetRenderTargetScale(float scale)
  864. {
  865. _renderScale[0].X = scale;
  866. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1); // Just the first element.
  867. }
  868. public void SetRenderTargetColorMasks(ReadOnlySpan<uint> componentMasks)
  869. {
  870. for (int index = 0; index < componentMasks.Length; index++)
  871. {
  872. _componentMasks[index] = componentMasks[index];
  873. RestoreComponentMask(index);
  874. }
  875. }
  876. public void SetRenderTargets(ITexture[] colors, ITexture depthStencil)
  877. {
  878. EnsureFramebuffer();
  879. bool isBgraChanged = false;
  880. for (int index = 0; index < colors.Length; index++)
  881. {
  882. TextureView color = (TextureView)colors[index];
  883. _framebuffer.AttachColor(index, color);
  884. int isBgra = color != null && color.Format.IsBgr() ? 1 : 0;
  885. if (_fpIsBgra[index].X != isBgra)
  886. {
  887. _fpIsBgra[index].X = isBgra;
  888. isBgraChanged = true;
  889. RestoreComponentMask(index);
  890. }
  891. }
  892. if (isBgraChanged)
  893. {
  894. _supportBuffer.UpdateFragmentIsBgra(_fpIsBgra, 0, SupportBuffer.FragmentIsBgraCount);
  895. }
  896. TextureView depthStencilView = (TextureView)depthStencil;
  897. _framebuffer.AttachDepthStencil(depthStencilView);
  898. _framebuffer.SetDrawBuffers(colors.Length);
  899. }
  900. public void SetSampler(int binding, ISampler sampler)
  901. {
  902. if (sampler == null)
  903. {
  904. return;
  905. }
  906. Sampler samp = (Sampler)sampler;
  907. if (binding == 0)
  908. {
  909. _unit0Sampler = samp;
  910. }
  911. samp.Bind(binding);
  912. }
  913. public void SetScissor(int index, bool enable, int x, int y, int width, int height)
  914. {
  915. uint mask = 1u << index;
  916. if (!enable)
  917. {
  918. if ((_scissorEnables & mask) != 0)
  919. {
  920. _scissorEnables &= ~mask;
  921. GL.Disable(IndexedEnableCap.ScissorTest, index);
  922. }
  923. return;
  924. }
  925. if ((_scissorEnables & mask) == 0)
  926. {
  927. _scissorEnables |= mask;
  928. GL.Enable(IndexedEnableCap.ScissorTest, index);
  929. }
  930. GL.ScissorIndexed(index, x, y, width, height);
  931. }
  932. public void SetStencilTest(StencilTestDescriptor stencilTest)
  933. {
  934. _stencilTestEnable = stencilTest.TestEnable;
  935. if (!stencilTest.TestEnable)
  936. {
  937. GL.Disable(EnableCap.StencilTest);
  938. return;
  939. }
  940. GL.StencilOpSeparate(
  941. StencilFace.Front,
  942. stencilTest.FrontSFail.Convert(),
  943. stencilTest.FrontDpFail.Convert(),
  944. stencilTest.FrontDpPass.Convert());
  945. GL.StencilFuncSeparate(
  946. StencilFace.Front,
  947. (StencilFunction)stencilTest.FrontFunc.Convert(),
  948. stencilTest.FrontFuncRef,
  949. stencilTest.FrontFuncMask);
  950. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  951. GL.StencilOpSeparate(
  952. StencilFace.Back,
  953. stencilTest.BackSFail.Convert(),
  954. stencilTest.BackDpFail.Convert(),
  955. stencilTest.BackDpPass.Convert());
  956. GL.StencilFuncSeparate(
  957. StencilFace.Back,
  958. (StencilFunction)stencilTest.BackFunc.Convert(),
  959. stencilTest.BackFuncRef,
  960. stencilTest.BackFuncMask);
  961. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  962. GL.Enable(EnableCap.StencilTest);
  963. _stencilFrontMask = stencilTest.FrontMask;
  964. }
  965. public void SetStorageBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  966. {
  967. SetBuffers(first, buffers, isStorage: true);
  968. }
  969. public void SetTexture(int binding, ITexture texture)
  970. {
  971. if (texture == null)
  972. {
  973. return;
  974. }
  975. if (binding == 0)
  976. {
  977. _unit0Texture = (TextureBase)texture;
  978. }
  979. else
  980. {
  981. ((TextureBase)texture).Bind(binding);
  982. }
  983. }
  984. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  985. {
  986. if (_tfEnabled)
  987. {
  988. GL.EndTransformFeedback();
  989. }
  990. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  991. for (int i = 0; i < count; i++)
  992. {
  993. BufferRange buffer = buffers[i];
  994. _tfbTargets[i] = buffer;
  995. if (buffer.Handle == BufferHandle.Null)
  996. {
  997. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  998. continue;
  999. }
  1000. if (_tfbs[i] == BufferHandle.Null)
  1001. {
  1002. _tfbs[i] = Buffer.Create();
  1003. }
  1004. Buffer.Resize(_tfbs[i], buffer.Size);
  1005. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  1006. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  1007. }
  1008. if (_tfEnabled)
  1009. {
  1010. GL.BeginTransformFeedback(_tfTopology);
  1011. }
  1012. }
  1013. public void SetUniformBuffers(int first, ReadOnlySpan<BufferRange> buffers)
  1014. {
  1015. SetBuffers(first, buffers, isStorage: false);
  1016. }
  1017. public void SetUserClipDistance(int index, bool enableClip)
  1018. {
  1019. if (!enableClip)
  1020. {
  1021. GL.Disable(EnableCap.ClipDistance0 + index);
  1022. return;
  1023. }
  1024. GL.Enable(EnableCap.ClipDistance0 + index);
  1025. }
  1026. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  1027. {
  1028. EnsureVertexArray();
  1029. _vertexArray.SetVertexAttributes(vertexAttribs);
  1030. }
  1031. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  1032. {
  1033. EnsureVertexArray();
  1034. _vertexArray.SetVertexBuffers(vertexBuffers);
  1035. }
  1036. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  1037. {
  1038. Array.Resize(ref _viewportArray, viewports.Length * 4);
  1039. Array.Resize(ref _depthRangeArray, viewports.Length * 2);
  1040. float[] viewportArray = _viewportArray;
  1041. double[] depthRangeArray = _depthRangeArray;
  1042. for (int index = 0; index < viewports.Length; index++)
  1043. {
  1044. int viewportElemIndex = index * 4;
  1045. Viewport viewport = viewports[index];
  1046. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  1047. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  1048. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  1049. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  1050. if (HwCapabilities.SupportsViewportSwizzle)
  1051. {
  1052. GL.NV.ViewportSwizzle(
  1053. index,
  1054. viewport.SwizzleX.Convert(),
  1055. viewport.SwizzleY.Convert(),
  1056. viewport.SwizzleZ.Convert(),
  1057. viewport.SwizzleW.Convert());
  1058. }
  1059. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  1060. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  1061. }
  1062. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  1063. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  1064. GL.ViewportArray(first, viewports.Length, viewportArray);
  1065. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  1066. }
  1067. public void TextureBarrier()
  1068. {
  1069. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1070. }
  1071. public void TextureBarrierTiled()
  1072. {
  1073. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  1074. }
  1075. private void SetBuffers(int first, ReadOnlySpan<BufferRange> buffers, bool isStorage)
  1076. {
  1077. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  1078. for (int index = 0; index < buffers.Length; index++)
  1079. {
  1080. BufferRange buffer = buffers[index];
  1081. if (buffer.Handle == BufferHandle.Null)
  1082. {
  1083. GL.BindBufferRange(target, first + index, 0, IntPtr.Zero, 0);
  1084. continue;
  1085. }
  1086. GL.BindBufferRange(target, first + index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  1087. }
  1088. }
  1089. private void SetOrigin(ClipOrigin origin)
  1090. {
  1091. if (_clipOrigin != origin)
  1092. {
  1093. _clipOrigin = origin;
  1094. GL.ClipControl(origin, _clipDepthMode);
  1095. SetFrontFace(_frontFace);
  1096. }
  1097. }
  1098. private void SetFrontFace(FrontFaceDirection frontFace)
  1099. {
  1100. // Changing clip origin will also change the front face to compensate
  1101. // for the flipped viewport, we flip it again here to compensate as
  1102. // this effect is undesirable for us.
  1103. if (_clipOrigin == ClipOrigin.UpperLeft)
  1104. {
  1105. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  1106. }
  1107. GL.FrontFace(frontFace);
  1108. }
  1109. private void EnsureVertexArray()
  1110. {
  1111. if (_vertexArray == null)
  1112. {
  1113. _vertexArray = new VertexArray();
  1114. _vertexArray.Bind();
  1115. }
  1116. }
  1117. private void EnsureFramebuffer()
  1118. {
  1119. if (_framebuffer == null)
  1120. {
  1121. _framebuffer = new Framebuffer();
  1122. int boundHandle = _framebuffer.Bind();
  1123. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  1124. GL.Enable(EnableCap.FramebufferSrgb);
  1125. }
  1126. }
  1127. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  1128. {
  1129. if (BackgroundContextWorker.InBackground)
  1130. {
  1131. return (0, 0);
  1132. }
  1133. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  1134. }
  1135. public void UpdateRenderScale(ReadOnlySpan<float> scales, int totalCount, int fragmentCount)
  1136. {
  1137. bool changed = false;
  1138. for (int index = 0; index < totalCount; index++)
  1139. {
  1140. if (_renderScale[1 + index].X != scales[index])
  1141. {
  1142. _renderScale[1 + index].X = scales[index];
  1143. changed = true;
  1144. }
  1145. }
  1146. // Only update fragment count if there are scales after it for the vertex stage.
  1147. if (fragmentCount != totalCount && fragmentCount != _fragmentScaleCount)
  1148. {
  1149. _fragmentScaleCount = fragmentCount;
  1150. _supportBuffer.UpdateFragmentRenderScaleCount(_fragmentScaleCount);
  1151. }
  1152. if (changed)
  1153. {
  1154. _supportBuffer.UpdateRenderScale(_renderScale, 0, 1 + totalCount);
  1155. }
  1156. }
  1157. private void PrepareForDispatch()
  1158. {
  1159. _unit0Texture?.Bind(0);
  1160. _supportBuffer.Commit();
  1161. }
  1162. private void PreDraw()
  1163. {
  1164. DrawCount++;
  1165. _vertexArray.Validate();
  1166. _unit0Texture?.Bind(0);
  1167. _supportBuffer.Commit();
  1168. }
  1169. private void PostDraw()
  1170. {
  1171. if (_tfEnabled)
  1172. {
  1173. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1174. {
  1175. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1176. {
  1177. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1178. }
  1179. }
  1180. }
  1181. }
  1182. public void RestoreComponentMask(int index)
  1183. {
  1184. // If the bound render target is bgra, swap the red and blue masks.
  1185. uint redMask = _fpIsBgra[index].X == 0 ? 1u : 4u;
  1186. uint blueMask = _fpIsBgra[index].X == 0 ? 4u : 1u;
  1187. GL.ColorMask(
  1188. index,
  1189. (_componentMasks[index] & redMask) != 0,
  1190. (_componentMasks[index] & 2u) != 0,
  1191. (_componentMasks[index] & blueMask) != 0,
  1192. (_componentMasks[index] & 8u) != 0);
  1193. }
  1194. public void RestoreScissor0Enable()
  1195. {
  1196. if ((_scissorEnables & 1u) != 0)
  1197. {
  1198. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1199. }
  1200. }
  1201. public void RestoreRasterizerDiscard()
  1202. {
  1203. if (_rasterizerDiscard)
  1204. {
  1205. GL.Enable(EnableCap.RasterizerDiscard);
  1206. }
  1207. }
  1208. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1209. {
  1210. if (value is CounterQueueEvent)
  1211. {
  1212. // Compare an event and a constant value.
  1213. CounterQueueEvent evt = (CounterQueueEvent)value;
  1214. // Easy host conditional rendering when the check matches what GL can do:
  1215. // - Event is of type samples passed.
  1216. // - Result is not a combination of multiple queries.
  1217. // - Comparing against 0.
  1218. // - Event has not already been flushed.
  1219. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1220. {
  1221. if (!value.ReserveForHostAccess())
  1222. {
  1223. // If the event has been flushed, then just use the values on the CPU.
  1224. // The query object may already be repurposed for another draw (eg. begin + end).
  1225. return false;
  1226. }
  1227. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1228. _activeConditionalRender = evt;
  1229. return true;
  1230. }
  1231. }
  1232. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1233. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1234. return false;
  1235. }
  1236. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1237. {
  1238. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1239. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1240. }
  1241. public void EndHostConditionalRendering()
  1242. {
  1243. GL.EndConditionalRender();
  1244. _activeConditionalRender?.ReleaseHostAccess();
  1245. _activeConditionalRender = null;
  1246. }
  1247. public void Dispose()
  1248. {
  1249. _supportBuffer?.Dispose();
  1250. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1251. {
  1252. if (_tfbs[i] != BufferHandle.Null)
  1253. {
  1254. Buffer.Delete(_tfbs[i]);
  1255. _tfbs[i] = BufferHandle.Null;
  1256. }
  1257. }
  1258. _activeConditionalRender?.ReleaseHostAccess();
  1259. _framebuffer?.Dispose();
  1260. _vertexArray?.Dispose();
  1261. _drawTexture.Dispose();
  1262. }
  1263. }
  1264. }