Pipeline.cs 38 KB

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