Pipeline.cs 40 KB

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