Pipeline.cs 48 KB

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