Pipeline.cs 40 KB

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