Pipeline.cs 49 KB

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