Pipeline.cs 41 KB

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