Pipeline.cs 41 KB

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