Pipeline.cs 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317
  1. using OpenTK.Graphics.OpenGL;
  2. using Ryujinx.Common.Logging;
  3. using Ryujinx.Graphics.GAL;
  4. using Ryujinx.Graphics.OpenGL.Image;
  5. using Ryujinx.Graphics.OpenGL.Queries;
  6. using Ryujinx.Graphics.Shader;
  7. using System;
  8. namespace Ryujinx.Graphics.OpenGL
  9. {
  10. class Pipeline : IPipeline, IDisposable
  11. {
  12. internal ulong DrawCount { get; private set; }
  13. private Program _program;
  14. private bool _rasterizerDiscard;
  15. private VertexArray _vertexArray;
  16. private Framebuffer _framebuffer;
  17. private IntPtr _indexBaseOffset;
  18. private DrawElementsType _elementsType;
  19. private PrimitiveType _primitiveType;
  20. private int _stencilFrontMask;
  21. private bool _depthMask;
  22. private int _boundDrawFramebuffer;
  23. private int _boundReadFramebuffer;
  24. private int[] _fpIsBgra = new int[8];
  25. private float[] _fpRenderScale = new float[65];
  26. private float[] _cpRenderScale = new float[64];
  27. private TextureBase _unit0Texture;
  28. private FrontFaceDirection _frontFace;
  29. private ClipOrigin _clipOrigin;
  30. private ClipDepthMode _clipDepthMode;
  31. private readonly uint[] _componentMasks;
  32. private bool _scissor0Enable = false;
  33. private bool _tfEnabled;
  34. private TransformFeedbackPrimitiveType _tfTopology;
  35. private readonly BufferHandle[] _tfbs;
  36. private readonly BufferRange[] _tfbTargets;
  37. private ColorF _blendConstant;
  38. internal Pipeline()
  39. {
  40. _rasterizerDiscard = false;
  41. _clipOrigin = ClipOrigin.LowerLeft;
  42. _clipDepthMode = ClipDepthMode.NegativeOneToOne;
  43. _componentMasks = new uint[Constants.MaxRenderTargets];
  44. for (int index = 0; index < Constants.MaxRenderTargets; index++)
  45. {
  46. _componentMasks[index] = 0xf;
  47. }
  48. for (int index = 0; index < _fpRenderScale.Length; index++)
  49. {
  50. _fpRenderScale[index] = 1f;
  51. }
  52. for (int index = 0; index < _cpRenderScale.Length; index++)
  53. {
  54. _cpRenderScale[index] = 1f;
  55. }
  56. _tfbs = new BufferHandle[Constants.MaxTransformFeedbackBuffers];
  57. _tfbTargets = new BufferRange[Constants.MaxTransformFeedbackBuffers];
  58. }
  59. public void Barrier()
  60. {
  61. GL.MemoryBarrier(MemoryBarrierFlags.AllBarrierBits);
  62. }
  63. public void BeginTransformFeedback(PrimitiveTopology topology)
  64. {
  65. GL.BeginTransformFeedback(_tfTopology = topology.ConvertToTfType());
  66. _tfEnabled = true;
  67. }
  68. public void 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. _fpIsBgra[index] = color != null && color.Format.IsBgra8() ? 1 : 0;
  722. }
  723. UpdateFpIsBgra();
  724. TextureView depthStencilView = (TextureView)depthStencil;
  725. _framebuffer.AttachDepthStencil(depthStencilView);
  726. _framebuffer.SetDrawBuffers(colors.Length);
  727. }
  728. public void SetSampler(int binding, ISampler sampler)
  729. {
  730. if (sampler == null)
  731. {
  732. return;
  733. }
  734. ((Sampler)sampler).Bind(binding);
  735. }
  736. public void SetScissorEnable(int index, bool enable)
  737. {
  738. if (enable)
  739. {
  740. GL.Enable(IndexedEnableCap.ScissorTest, index);
  741. }
  742. else
  743. {
  744. GL.Disable(IndexedEnableCap.ScissorTest, index);
  745. }
  746. if (index == 0)
  747. {
  748. _scissor0Enable = enable;
  749. }
  750. }
  751. public void SetScissor(int index, int x, int y, int width, int height)
  752. {
  753. GL.ScissorIndexed(index, x, y, width, height);
  754. }
  755. public void SetStencilTest(StencilTestDescriptor stencilTest)
  756. {
  757. if (!stencilTest.TestEnable)
  758. {
  759. GL.Disable(EnableCap.StencilTest);
  760. return;
  761. }
  762. GL.StencilOpSeparate(
  763. StencilFace.Front,
  764. stencilTest.FrontSFail.Convert(),
  765. stencilTest.FrontDpFail.Convert(),
  766. stencilTest.FrontDpPass.Convert());
  767. GL.StencilFuncSeparate(
  768. StencilFace.Front,
  769. (StencilFunction)stencilTest.FrontFunc.Convert(),
  770. stencilTest.FrontFuncRef,
  771. stencilTest.FrontFuncMask);
  772. GL.StencilMaskSeparate(StencilFace.Front, stencilTest.FrontMask);
  773. GL.StencilOpSeparate(
  774. StencilFace.Back,
  775. stencilTest.BackSFail.Convert(),
  776. stencilTest.BackDpFail.Convert(),
  777. stencilTest.BackDpPass.Convert());
  778. GL.StencilFuncSeparate(
  779. StencilFace.Back,
  780. (StencilFunction)stencilTest.BackFunc.Convert(),
  781. stencilTest.BackFuncRef,
  782. stencilTest.BackFuncMask);
  783. GL.StencilMaskSeparate(StencilFace.Back, stencilTest.BackMask);
  784. GL.Enable(EnableCap.StencilTest);
  785. _stencilFrontMask = stencilTest.FrontMask;
  786. }
  787. public void SetStorageBuffers(ReadOnlySpan<BufferRange> buffers)
  788. {
  789. SetBuffers(buffers, isStorage: true);
  790. }
  791. public void SetTexture(int binding, ITexture texture)
  792. {
  793. if (texture == null)
  794. {
  795. return;
  796. }
  797. if (binding == 0)
  798. {
  799. _unit0Texture = (TextureBase)texture;
  800. }
  801. else
  802. {
  803. ((TextureBase)texture).Bind(binding);
  804. }
  805. }
  806. public void SetTransformFeedbackBuffers(ReadOnlySpan<BufferRange> buffers)
  807. {
  808. if (_tfEnabled)
  809. {
  810. GL.EndTransformFeedback();
  811. }
  812. int count = Math.Min(buffers.Length, Constants.MaxTransformFeedbackBuffers);
  813. for (int i = 0; i < count; i++)
  814. {
  815. BufferRange buffer = buffers[i];
  816. _tfbTargets[i] = buffer;
  817. if (buffer.Handle == BufferHandle.Null)
  818. {
  819. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, 0);
  820. continue;
  821. }
  822. if (_tfbs[i] == BufferHandle.Null)
  823. {
  824. _tfbs[i] = Buffer.Create();
  825. }
  826. Buffer.Resize(_tfbs[i], buffer.Size);
  827. Buffer.Copy(buffer.Handle, _tfbs[i], buffer.Offset, 0, buffer.Size);
  828. GL.BindBufferBase(BufferRangeTarget.TransformFeedbackBuffer, i, _tfbs[i].ToInt32());
  829. }
  830. if (_tfEnabled)
  831. {
  832. GL.BeginTransformFeedback(_tfTopology);
  833. }
  834. }
  835. public void SetUniformBuffers(ReadOnlySpan<BufferRange> buffers)
  836. {
  837. SetBuffers(buffers, isStorage: false);
  838. }
  839. public void SetUserClipDistance(int index, bool enableClip)
  840. {
  841. if (!enableClip)
  842. {
  843. GL.Disable(EnableCap.ClipDistance0 + index);
  844. return;
  845. }
  846. GL.Enable(EnableCap.ClipDistance0 + index);
  847. }
  848. public void SetVertexAttribs(ReadOnlySpan<VertexAttribDescriptor> vertexAttribs)
  849. {
  850. EnsureVertexArray();
  851. _vertexArray.SetVertexAttributes(vertexAttribs);
  852. }
  853. public void SetVertexBuffers(ReadOnlySpan<VertexBufferDescriptor> vertexBuffers)
  854. {
  855. EnsureVertexArray();
  856. _vertexArray.SetVertexBuffers(vertexBuffers);
  857. }
  858. public void SetViewports(int first, ReadOnlySpan<Viewport> viewports)
  859. {
  860. float[] viewportArray = new float[viewports.Length * 4];
  861. double[] depthRangeArray = new double[viewports.Length * 2];
  862. for (int index = 0; index < viewports.Length; index++)
  863. {
  864. int viewportElemIndex = index * 4;
  865. Viewport viewport = viewports[index];
  866. viewportArray[viewportElemIndex + 0] = viewport.Region.X;
  867. viewportArray[viewportElemIndex + 1] = viewport.Region.Y + (viewport.Region.Height < 0 ? viewport.Region.Height : 0);
  868. viewportArray[viewportElemIndex + 2] = viewport.Region.Width;
  869. viewportArray[viewportElemIndex + 3] = MathF.Abs(viewport.Region.Height);
  870. if (HwCapabilities.SupportsViewportSwizzle)
  871. {
  872. GL.NV.ViewportSwizzle(
  873. index,
  874. viewport.SwizzleX.Convert(),
  875. viewport.SwizzleY.Convert(),
  876. viewport.SwizzleZ.Convert(),
  877. viewport.SwizzleW.Convert());
  878. }
  879. depthRangeArray[index * 2 + 0] = viewport.DepthNear;
  880. depthRangeArray[index * 2 + 1] = viewport.DepthFar;
  881. }
  882. bool flipY = viewports.Length != 0 && viewports[0].Region.Height < 0;
  883. SetOrigin(flipY ? ClipOrigin.UpperLeft : ClipOrigin.LowerLeft);
  884. GL.ViewportArray(first, viewports.Length, viewportArray);
  885. GL.DepthRangeArray(first, viewports.Length, depthRangeArray);
  886. }
  887. public void TextureBarrier()
  888. {
  889. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  890. }
  891. public void TextureBarrierTiled()
  892. {
  893. GL.MemoryBarrier(MemoryBarrierFlags.TextureFetchBarrierBit);
  894. }
  895. private void SetBuffers(ReadOnlySpan<BufferRange> buffers, bool isStorage)
  896. {
  897. BufferRangeTarget target = isStorage ? BufferRangeTarget.ShaderStorageBuffer : BufferRangeTarget.UniformBuffer;
  898. for (int index = 0; index < buffers.Length; index++)
  899. {
  900. BufferRange buffer = buffers[index];
  901. if (buffer.Handle == BufferHandle.Null)
  902. {
  903. GL.BindBufferRange(target, index, 0, IntPtr.Zero, 0);
  904. continue;
  905. }
  906. GL.BindBufferRange(target, index, buffer.Handle.ToInt32(), (IntPtr)buffer.Offset, buffer.Size);
  907. }
  908. }
  909. private void SetOrigin(ClipOrigin origin)
  910. {
  911. if (_clipOrigin != origin)
  912. {
  913. _clipOrigin = origin;
  914. GL.ClipControl(origin, _clipDepthMode);
  915. SetFrontFace(_frontFace);
  916. }
  917. }
  918. private void SetFrontFace(FrontFaceDirection frontFace)
  919. {
  920. // Changing clip origin will also change the front face to compensate
  921. // for the flipped viewport, we flip it again here to compensate as
  922. // this effect is undesirable for us.
  923. if (_clipOrigin == ClipOrigin.UpperLeft)
  924. {
  925. frontFace = frontFace == FrontFaceDirection.Ccw ? FrontFaceDirection.Cw : FrontFaceDirection.Ccw;
  926. }
  927. GL.FrontFace(frontFace);
  928. }
  929. private void EnsureVertexArray()
  930. {
  931. if (_vertexArray == null)
  932. {
  933. _vertexArray = new VertexArray();
  934. _vertexArray.Bind();
  935. }
  936. }
  937. private void EnsureFramebuffer()
  938. {
  939. if (_framebuffer == null)
  940. {
  941. _framebuffer = new Framebuffer();
  942. int boundHandle = _framebuffer.Bind();
  943. _boundDrawFramebuffer = _boundReadFramebuffer = boundHandle;
  944. GL.Enable(EnableCap.FramebufferSrgb);
  945. }
  946. }
  947. internal (int drawHandle, int readHandle) GetBoundFramebuffers()
  948. {
  949. if (BackgroundContextWorker.InBackground)
  950. {
  951. return (0, 0);
  952. }
  953. return (_boundDrawFramebuffer, _boundReadFramebuffer);
  954. }
  955. private void UpdateFpIsBgra()
  956. {
  957. if (_program != null)
  958. {
  959. GL.Uniform1(_program.FragmentIsBgraUniform, 8, _fpIsBgra);
  960. }
  961. }
  962. public void UpdateRenderScale(ShaderStage stage, float[] scales, int textureCount, int imageCount)
  963. {
  964. if (_program != null)
  965. {
  966. switch (stage)
  967. {
  968. case ShaderStage.Fragment:
  969. if (_program.FragmentRenderScaleUniform != -1)
  970. {
  971. Array.Copy(scales, 0, _fpRenderScale, 1, textureCount + imageCount);
  972. GL.Uniform1(_program.FragmentRenderScaleUniform, 1 + textureCount + imageCount, _fpRenderScale);
  973. }
  974. break;
  975. case ShaderStage.Compute:
  976. if (_program.ComputeRenderScaleUniform != -1)
  977. {
  978. Array.Copy(scales, 0, _cpRenderScale, 0, textureCount + imageCount);
  979. GL.Uniform1(_program.ComputeRenderScaleUniform, textureCount + imageCount, _cpRenderScale);
  980. }
  981. break;
  982. }
  983. }
  984. }
  985. private void PrepareForDispatch()
  986. {
  987. if (_unit0Texture != null)
  988. {
  989. _unit0Texture.Bind(0);
  990. }
  991. }
  992. private void PreDraw()
  993. {
  994. DrawCount++;
  995. _vertexArray.Validate();
  996. if (_unit0Texture != null)
  997. {
  998. _unit0Texture.Bind(0);
  999. }
  1000. }
  1001. private void PostDraw()
  1002. {
  1003. _framebuffer?.SignalModified();
  1004. if (_tfEnabled)
  1005. {
  1006. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1007. {
  1008. if (_tfbTargets[i].Handle != BufferHandle.Null)
  1009. {
  1010. Buffer.Copy(_tfbs[i], _tfbTargets[i].Handle, 0, _tfbTargets[i].Offset, _tfbTargets[i].Size);
  1011. }
  1012. }
  1013. }
  1014. }
  1015. private void RestoreComponentMask(int index)
  1016. {
  1017. GL.ColorMask(
  1018. index,
  1019. (_componentMasks[index] & 1u) != 0,
  1020. (_componentMasks[index] & 2u) != 0,
  1021. (_componentMasks[index] & 4u) != 0,
  1022. (_componentMasks[index] & 8u) != 0);
  1023. }
  1024. public void RestoreScissor0Enable()
  1025. {
  1026. if (_scissor0Enable)
  1027. {
  1028. GL.Enable(IndexedEnableCap.ScissorTest, 0);
  1029. }
  1030. }
  1031. public void RestoreRasterizerDiscard()
  1032. {
  1033. if (_rasterizerDiscard)
  1034. {
  1035. GL.Enable(EnableCap.RasterizerDiscard);
  1036. }
  1037. }
  1038. public bool TryHostConditionalRendering(ICounterEvent value, ulong compare, bool isEqual)
  1039. {
  1040. if (value is CounterQueueEvent)
  1041. {
  1042. // Compare an event and a constant value.
  1043. CounterQueueEvent evt = (CounterQueueEvent)value;
  1044. // Easy host conditional rendering when the check matches what GL can do:
  1045. // - Event is of type samples passed.
  1046. // - Result is not a combination of multiple queries.
  1047. // - Comparing against 0.
  1048. // - Event has not already been flushed.
  1049. if (evt.Disposed)
  1050. {
  1051. // If the event has been flushed, then just use the values on the CPU.
  1052. // The query object may already be repurposed for another draw (eg. begin + end).
  1053. return false;
  1054. }
  1055. if (compare == 0 && evt.Type == QueryTarget.SamplesPassed && evt.ClearCounter)
  1056. {
  1057. GL.BeginConditionalRender(evt.Query, isEqual ? ConditionalRenderType.QueryNoWaitInverted : ConditionalRenderType.QueryNoWait);
  1058. return true;
  1059. }
  1060. }
  1061. // The GPU will flush the queries to CPU and evaluate the condition there instead.
  1062. GL.Flush(); // The thread will be stalled manually flushing the counter, so flush GL commands now.
  1063. return false;
  1064. }
  1065. public bool TryHostConditionalRendering(ICounterEvent value, ICounterEvent compare, bool isEqual)
  1066. {
  1067. GL.Flush(); // The GPU thread will be stalled manually flushing the counter, so flush GL commands now.
  1068. return false; // We don't currently have a way to compare two counters for conditional rendering.
  1069. }
  1070. public void EndHostConditionalRendering()
  1071. {
  1072. GL.EndConditionalRender();
  1073. }
  1074. public void Dispose()
  1075. {
  1076. for (int i = 0; i < Constants.MaxTransformFeedbackBuffers; i++)
  1077. {
  1078. if (_tfbs[i] != BufferHandle.Null)
  1079. {
  1080. Buffer.Delete(_tfbs[i]);
  1081. _tfbs[i] = BufferHandle.Null;
  1082. }
  1083. }
  1084. _framebuffer?.Dispose();
  1085. _vertexArray?.Dispose();
  1086. }
  1087. }
  1088. }