Pipeline.cs 39 KB

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