NvGpuEngine3d.cs 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967
  1. using Ryujinx.Graphics.Gal;
  2. using Ryujinx.Graphics.Memory;
  3. using Ryujinx.Graphics.Texture;
  4. using System;
  5. using System.Collections.Generic;
  6. namespace Ryujinx.Graphics
  7. {
  8. public class NvGpuEngine3d : INvGpuEngine
  9. {
  10. public int[] Registers { get; private set; }
  11. private NvGpu Gpu;
  12. private Dictionary<int, NvGpuMethod> Methods;
  13. private struct ConstBuffer
  14. {
  15. public bool Enabled;
  16. public long Position;
  17. public int Size;
  18. }
  19. private ConstBuffer[][] ConstBuffers;
  20. private List<long>[] UploadedKeys;
  21. private int CurrentInstance = 0;
  22. public NvGpuEngine3d(NvGpu Gpu)
  23. {
  24. this.Gpu = Gpu;
  25. Registers = new int[0xe00];
  26. Methods = new Dictionary<int, NvGpuMethod>();
  27. void AddMethod(int Meth, int Count, int Stride, NvGpuMethod Method)
  28. {
  29. while (Count-- > 0)
  30. {
  31. Methods.Add(Meth, Method);
  32. Meth += Stride;
  33. }
  34. }
  35. AddMethod(0x585, 1, 1, VertexEndGl);
  36. AddMethod(0x674, 1, 1, ClearBuffers);
  37. AddMethod(0x6c3, 1, 1, QueryControl);
  38. AddMethod(0x8e4, 16, 1, CbData);
  39. AddMethod(0x904, 5, 8, CbBind);
  40. ConstBuffers = new ConstBuffer[6][];
  41. for (int Index = 0; Index < ConstBuffers.Length; Index++)
  42. {
  43. ConstBuffers[Index] = new ConstBuffer[18];
  44. }
  45. UploadedKeys = new List<long>[(int)NvGpuBufferType.Count];
  46. for (int i = 0; i < UploadedKeys.Length; i++)
  47. {
  48. UploadedKeys[i] = new List<long>();
  49. }
  50. }
  51. public void CallMethod(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  52. {
  53. if (Methods.TryGetValue(PBEntry.Method, out NvGpuMethod Method))
  54. {
  55. Method(Vmm, PBEntry);
  56. }
  57. else
  58. {
  59. WriteRegister(PBEntry);
  60. }
  61. }
  62. public void ResetCache()
  63. {
  64. foreach (List<long> Uploaded in UploadedKeys)
  65. {
  66. Uploaded.Clear();
  67. }
  68. }
  69. private void VertexEndGl(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  70. {
  71. LockCaches();
  72. GalPipelineState State = new GalPipelineState();
  73. SetFrameBuffer(State);
  74. SetFrontFace(State);
  75. SetCullFace(State);
  76. SetDepth(State);
  77. SetStencil(State);
  78. SetBlending(State);
  79. SetColorMask(State);
  80. SetPrimitiveRestart(State);
  81. for (int FbIndex = 0; FbIndex < 8; FbIndex++)
  82. {
  83. SetFrameBuffer(Vmm, FbIndex);
  84. }
  85. SetZeta(Vmm);
  86. SetRenderTargets();
  87. long[] Keys = UploadShaders(Vmm);
  88. Gpu.Renderer.Shader.BindProgram();
  89. UploadTextures(Vmm, State, Keys);
  90. UploadConstBuffers(Vmm, State, Keys);
  91. UploadVertexArrays(Vmm, State);
  92. DispatchRender(Vmm, State);
  93. UnlockCaches();
  94. }
  95. private void LockCaches()
  96. {
  97. Gpu.Renderer.Buffer.LockCache();
  98. Gpu.Renderer.Rasterizer.LockCaches();
  99. Gpu.Renderer.Texture.LockCache();
  100. }
  101. private void UnlockCaches()
  102. {
  103. Gpu.Renderer.Buffer.UnlockCache();
  104. Gpu.Renderer.Rasterizer.UnlockCaches();
  105. Gpu.Renderer.Texture.UnlockCache();
  106. }
  107. private void ClearBuffers(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  108. {
  109. int Arg0 = PBEntry.Arguments[0];
  110. int Attachment = (Arg0 >> 6) & 0xf;
  111. GalClearBufferFlags Flags = (GalClearBufferFlags)(Arg0 & 0x3f);
  112. float Red = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 0);
  113. float Green = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 1);
  114. float Blue = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 2);
  115. float Alpha = ReadRegisterFloat(NvGpuEngine3dReg.ClearNColor + 3);
  116. float Depth = ReadRegisterFloat(NvGpuEngine3dReg.ClearDepth);
  117. int Stencil = ReadRegister(NvGpuEngine3dReg.ClearStencil);
  118. SetFrameBuffer(Vmm, Attachment);
  119. SetZeta(Vmm);
  120. SetRenderTargets();
  121. Gpu.Renderer.RenderTarget.Bind();
  122. Gpu.Renderer.Rasterizer.ClearBuffers(Flags, Attachment, Red, Green, Blue, Alpha, Depth, Stencil);
  123. Gpu.Renderer.Pipeline.ResetDepthMask();
  124. Gpu.Renderer.Pipeline.ResetColorMask(Attachment);
  125. }
  126. private void SetFrameBuffer(NvGpuVmm Vmm, int FbIndex)
  127. {
  128. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.FrameBufferNAddress + FbIndex * 0x10);
  129. int SurfFormat = ReadRegister(NvGpuEngine3dReg.FrameBufferNFormat + FbIndex * 0x10);
  130. if (VA == 0 || SurfFormat == 0)
  131. {
  132. Gpu.Renderer.RenderTarget.UnbindColor(FbIndex);
  133. return;
  134. }
  135. long Key = Vmm.GetPhysicalAddress(VA);
  136. int Width = ReadRegister(NvGpuEngine3dReg.FrameBufferNWidth + FbIndex * 0x10);
  137. int Height = ReadRegister(NvGpuEngine3dReg.FrameBufferNHeight + FbIndex * 0x10);
  138. int BlockDim = ReadRegister(NvGpuEngine3dReg.FrameBufferNBlockDim + FbIndex * 0x10);
  139. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  140. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1);
  141. float TX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateX + FbIndex * 8);
  142. float TY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNTranslateY + FbIndex * 8);
  143. float SX = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleX + FbIndex * 8);
  144. float SY = ReadRegisterFloat(NvGpuEngine3dReg.ViewportNScaleY + FbIndex * 8);
  145. int VpX = (int)MathF.Max(0, TX - MathF.Abs(SX));
  146. int VpY = (int)MathF.Max(0, TY - MathF.Abs(SY));
  147. int VpW = (int)(TX + MathF.Abs(SX)) - VpX;
  148. int VpH = (int)(TY + MathF.Abs(SY)) - VpY;
  149. GalImageFormat Format = ImageUtils.ConvertSurface((GalSurfaceFormat)SurfFormat);
  150. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  151. Gpu.ResourceManager.SendColorBuffer(Vmm, Key, FbIndex, Image);
  152. Gpu.Renderer.RenderTarget.SetViewport(FbIndex, VpX, VpY, VpW, VpH);
  153. }
  154. private void SetFrameBuffer(GalPipelineState State)
  155. {
  156. State.FramebufferSrgb = ReadRegisterBool(NvGpuEngine3dReg.FrameBufferSrgb);
  157. State.FlipX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  158. State.FlipY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  159. }
  160. private void SetZeta(NvGpuVmm Vmm)
  161. {
  162. long VA = MakeInt64From2xInt32(NvGpuEngine3dReg.ZetaAddress);
  163. int ZetaFormat = ReadRegister(NvGpuEngine3dReg.ZetaFormat);
  164. int BlockDim = ReadRegister(NvGpuEngine3dReg.ZetaBlockDimensions);
  165. int GobBlockHeight = 1 << ((BlockDim >> 4) & 7);
  166. GalMemoryLayout Layout = (GalMemoryLayout)((BlockDim >> 12) & 1); //?
  167. bool ZetaEnable = ReadRegisterBool(NvGpuEngine3dReg.ZetaEnable);
  168. if (VA == 0 || ZetaFormat == 0 || !ZetaEnable)
  169. {
  170. Gpu.Renderer.RenderTarget.UnbindZeta();
  171. return;
  172. }
  173. long Key = Vmm.GetPhysicalAddress(VA);
  174. int Width = ReadRegister(NvGpuEngine3dReg.ZetaHoriz);
  175. int Height = ReadRegister(NvGpuEngine3dReg.ZetaVert);
  176. GalImageFormat Format = ImageUtils.ConvertZeta((GalZetaFormat)ZetaFormat);
  177. GalImage Image = new GalImage(Width, Height, 1, GobBlockHeight, Layout, Format);
  178. Gpu.ResourceManager.SendZetaBuffer(Vmm, Key, Image);
  179. }
  180. private long[] UploadShaders(NvGpuVmm Vmm)
  181. {
  182. long[] Keys = new long[5];
  183. long BasePosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  184. int Index = 1;
  185. int VpAControl = ReadRegister(NvGpuEngine3dReg.ShaderNControl);
  186. bool VpAEnable = (VpAControl & 1) != 0;
  187. if (VpAEnable)
  188. {
  189. //Note: The maxwell supports 2 vertex programs, usually
  190. //only VP B is used, but in some cases VP A is also used.
  191. //In this case, it seems to function as an extra vertex
  192. //shader stage.
  193. //The graphics abstraction layer has a special overload for this
  194. //case, which should merge the two shaders into one vertex shader.
  195. int VpAOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset);
  196. int VpBOffset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + 0x10);
  197. long VpAPos = BasePosition + (uint)VpAOffset;
  198. long VpBPos = BasePosition + (uint)VpBOffset;
  199. Keys[(int)GalShaderType.Vertex] = VpBPos;
  200. Gpu.Renderer.Shader.Create(Vmm, VpAPos, VpBPos, GalShaderType.Vertex);
  201. Gpu.Renderer.Shader.Bind(VpBPos);
  202. Index = 2;
  203. }
  204. for (; Index < 6; Index++)
  205. {
  206. GalShaderType Type = GetTypeFromProgram(Index);
  207. int Control = ReadRegister(NvGpuEngine3dReg.ShaderNControl + Index * 0x10);
  208. int Offset = ReadRegister(NvGpuEngine3dReg.ShaderNOffset + Index * 0x10);
  209. //Note: Vertex Program (B) is always enabled.
  210. bool Enable = (Control & 1) != 0 || Index == 1;
  211. if (!Enable)
  212. {
  213. Gpu.Renderer.Shader.Unbind(Type);
  214. continue;
  215. }
  216. long Key = BasePosition + (uint)Offset;
  217. Keys[(int)Type] = Key;
  218. Gpu.Renderer.Shader.Create(Vmm, Key, Type);
  219. Gpu.Renderer.Shader.Bind(Key);
  220. }
  221. return Keys;
  222. }
  223. private static GalShaderType GetTypeFromProgram(int Program)
  224. {
  225. switch (Program)
  226. {
  227. case 0:
  228. case 1: return GalShaderType.Vertex;
  229. case 2: return GalShaderType.TessControl;
  230. case 3: return GalShaderType.TessEvaluation;
  231. case 4: return GalShaderType.Geometry;
  232. case 5: return GalShaderType.Fragment;
  233. }
  234. throw new ArgumentOutOfRangeException(nameof(Program));
  235. }
  236. private void SetFrontFace(GalPipelineState State)
  237. {
  238. float SignX = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleX);
  239. float SignY = GetFlipSign(NvGpuEngine3dReg.ViewportNScaleY);
  240. GalFrontFace FrontFace = (GalFrontFace)ReadRegister(NvGpuEngine3dReg.FrontFace);
  241. //Flipping breaks facing. Flipping front facing too fixes it
  242. if (SignX != SignY)
  243. {
  244. switch (FrontFace)
  245. {
  246. case GalFrontFace.CW: FrontFace = GalFrontFace.CCW; break;
  247. case GalFrontFace.CCW: FrontFace = GalFrontFace.CW; break;
  248. }
  249. }
  250. State.FrontFace = FrontFace;
  251. }
  252. private void SetCullFace(GalPipelineState State)
  253. {
  254. State.CullFaceEnabled = ReadRegisterBool(NvGpuEngine3dReg.CullFaceEnable);
  255. if (State.CullFaceEnabled)
  256. {
  257. State.CullFace = (GalCullFace)ReadRegister(NvGpuEngine3dReg.CullFace);
  258. }
  259. }
  260. private void SetDepth(GalPipelineState State)
  261. {
  262. State.DepthTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthTestEnable);
  263. State.DepthWriteEnabled = ReadRegisterBool(NvGpuEngine3dReg.DepthWriteEnable);
  264. if (State.DepthTestEnabled)
  265. {
  266. State.DepthFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.DepthTestFunction);
  267. }
  268. }
  269. private void SetStencil(GalPipelineState State)
  270. {
  271. State.StencilTestEnabled = ReadRegisterBool(NvGpuEngine3dReg.StencilEnable);
  272. if (State.StencilTestEnabled)
  273. {
  274. State.StencilBackFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilBackFuncFunc);
  275. State.StencilBackFuncRef = ReadRegister(NvGpuEngine3dReg.StencilBackFuncRef);
  276. State.StencilBackFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackFuncMask);
  277. State.StencilBackOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpFail);
  278. State.StencilBackOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZFail);
  279. State.StencilBackOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilBackOpZPass);
  280. State.StencilBackMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilBackMask);
  281. State.StencilFrontFuncFunc = (GalComparisonOp)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncFunc);
  282. State.StencilFrontFuncRef = ReadRegister(NvGpuEngine3dReg.StencilFrontFuncRef);
  283. State.StencilFrontFuncMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontFuncMask);
  284. State.StencilFrontOpFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpFail);
  285. State.StencilFrontOpZFail = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZFail);
  286. State.StencilFrontOpZPass = (GalStencilOp)ReadRegister(NvGpuEngine3dReg.StencilFrontOpZPass);
  287. State.StencilFrontMask = (uint)ReadRegister(NvGpuEngine3dReg.StencilFrontMask);
  288. }
  289. }
  290. private void SetBlending(GalPipelineState State)
  291. {
  292. //TODO: Support independent blend properly.
  293. State.BlendEnabled = ReadRegisterBool(NvGpuEngine3dReg.IBlendNEnable);
  294. if (State.BlendEnabled)
  295. {
  296. State.BlendSeparateAlpha = ReadRegisterBool(NvGpuEngine3dReg.IBlendNSeparateAlpha);
  297. State.BlendEquationRgb = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationRgb);
  298. State.BlendFuncSrcRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcRgb);
  299. State.BlendFuncDstRgb = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstRgb);
  300. State.BlendEquationAlpha = (GalBlendEquation)ReadRegister(NvGpuEngine3dReg.IBlendNEquationAlpha);
  301. State.BlendFuncSrcAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncSrcAlpha);
  302. State.BlendFuncDstAlpha = (GalBlendFactor)ReadRegister(NvGpuEngine3dReg.IBlendNFuncDstAlpha);
  303. }
  304. }
  305. private void SetColorMask(GalPipelineState State)
  306. {
  307. int ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMask);
  308. State.ColorMask.Red = ((ColorMask >> 0) & 0xf) != 0;
  309. State.ColorMask.Green = ((ColorMask >> 4) & 0xf) != 0;
  310. State.ColorMask.Blue = ((ColorMask >> 8) & 0xf) != 0;
  311. State.ColorMask.Alpha = ((ColorMask >> 12) & 0xf) != 0;
  312. for (int Index = 0; Index < GalPipelineState.RenderTargetsCount; Index++)
  313. {
  314. ColorMask = ReadRegister(NvGpuEngine3dReg.ColorMaskN + Index);
  315. State.ColorMasks[Index].Red = ((ColorMask >> 0) & 0xf) != 0;
  316. State.ColorMasks[Index].Green = ((ColorMask >> 4) & 0xf) != 0;
  317. State.ColorMasks[Index].Blue = ((ColorMask >> 8) & 0xf) != 0;
  318. State.ColorMasks[Index].Alpha = ((ColorMask >> 12) & 0xf) != 0;
  319. }
  320. }
  321. private void SetPrimitiveRestart(GalPipelineState State)
  322. {
  323. State.PrimitiveRestartEnabled = ReadRegisterBool(NvGpuEngine3dReg.PrimRestartEnable);
  324. if (State.PrimitiveRestartEnabled)
  325. {
  326. State.PrimitiveRestartIndex = (uint)ReadRegister(NvGpuEngine3dReg.PrimRestartIndex);
  327. }
  328. }
  329. private void SetRenderTargets()
  330. {
  331. //Commercial games do not seem to
  332. //bool SeparateFragData = ReadRegisterBool(NvGpuEngine3dReg.RTSeparateFragData);
  333. uint Control = (uint)(ReadRegister(NvGpuEngine3dReg.RTControl));
  334. uint Count = Control & 0xf;
  335. if (Count > 0)
  336. {
  337. int[] Map = new int[Count];
  338. for (int Index = 0; Index < Count; Index++)
  339. {
  340. int Shift = 4 + Index * 3;
  341. Map[Index] = (int)((Control >> Shift) & 7);
  342. }
  343. Gpu.Renderer.RenderTarget.SetMap(Map);
  344. }
  345. else
  346. {
  347. Gpu.Renderer.RenderTarget.SetMap(null);
  348. }
  349. }
  350. private void UploadTextures(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  351. {
  352. long BaseShPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.ShaderAddress);
  353. int TextureCbIndex = ReadRegister(NvGpuEngine3dReg.TextureCbIndex);
  354. int TexIndex = 0;
  355. for (int Index = 0; Index < Keys.Length; Index++)
  356. {
  357. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetTextureUsage(Keys[Index]))
  358. {
  359. long Position;
  360. if (DeclInfo.IsCb)
  361. {
  362. Position = ConstBuffers[Index][DeclInfo.Cbuf].Position;
  363. }
  364. else
  365. {
  366. Position = ConstBuffers[Index][TextureCbIndex].Position;
  367. }
  368. int TextureHandle = Vmm.ReadInt32(Position + DeclInfo.Index * 4);
  369. UploadTexture(Vmm, TexIndex, TextureHandle);
  370. TexIndex++;
  371. }
  372. }
  373. }
  374. private void UploadTexture(NvGpuVmm Vmm, int TexIndex, int TextureHandle)
  375. {
  376. if (TextureHandle == 0)
  377. {
  378. //TODO: Is this correct?
  379. //Some games like puyo puyo will have 0 handles.
  380. //It may be just normal behaviour or a bug caused by sync issues.
  381. //The game does initialize the value properly after through.
  382. return;
  383. }
  384. int TicIndex = (TextureHandle >> 0) & 0xfffff;
  385. int TscIndex = (TextureHandle >> 20) & 0xfff;
  386. long TicPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexHeaderPoolOffset);
  387. long TscPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.TexSamplerPoolOffset);
  388. TicPosition += TicIndex * 0x20;
  389. TscPosition += TscIndex * 0x20;
  390. GalImage Image = TextureFactory.MakeTexture(Vmm, TicPosition);
  391. GalTextureSampler Sampler = TextureFactory.MakeSampler(Gpu, Vmm, TscPosition);
  392. long Key = Vmm.ReadInt64(TicPosition + 4) & 0xffffffffffff;
  393. if (Image.Layout == GalMemoryLayout.BlockLinear)
  394. {
  395. Key &= ~0x1ffL;
  396. }
  397. else if (Image.Layout == GalMemoryLayout.Pitch)
  398. {
  399. Key &= ~0x1fL;
  400. }
  401. Key = Vmm.GetPhysicalAddress(Key);
  402. if (Key == -1)
  403. {
  404. //FIXME: Shouldn't ignore invalid addresses.
  405. return;
  406. }
  407. Gpu.ResourceManager.SendTexture(Vmm, Key, Image, TexIndex);
  408. Gpu.Renderer.Texture.SetSampler(Sampler);
  409. }
  410. private void UploadConstBuffers(NvGpuVmm Vmm, GalPipelineState State, long[] Keys)
  411. {
  412. for (int Stage = 0; Stage < Keys.Length; Stage++)
  413. {
  414. foreach (ShaderDeclInfo DeclInfo in Gpu.Renderer.Shader.GetConstBufferUsage(Keys[Stage]))
  415. {
  416. ConstBuffer Cb = ConstBuffers[Stage][DeclInfo.Cbuf];
  417. if (!Cb.Enabled)
  418. {
  419. continue;
  420. }
  421. long Key = Vmm.GetPhysicalAddress(Cb.Position);
  422. if (QueryKeyUpload(Vmm, Key, Cb.Size, NvGpuBufferType.ConstBuffer))
  423. {
  424. IntPtr Source = Vmm.GetHostAddress(Cb.Position, Cb.Size);
  425. Gpu.Renderer.Buffer.SetData(Key, Cb.Size, Source);
  426. }
  427. State.ConstBufferKeys[Stage][DeclInfo.Cbuf] = Key;
  428. }
  429. }
  430. }
  431. private void UploadVertexArrays(NvGpuVmm Vmm, GalPipelineState State)
  432. {
  433. long IbPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  434. long IboKey = Vmm.GetPhysicalAddress(IbPosition);
  435. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  436. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  437. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  438. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  439. GalIndexFormat IndexFormat = (GalIndexFormat)IndexEntryFmt;
  440. int IndexEntrySize = 1 << IndexEntryFmt;
  441. if (IndexEntrySize > 4)
  442. {
  443. throw new InvalidOperationException();
  444. }
  445. if (IndexCount != 0)
  446. {
  447. int IbSize = IndexCount * IndexEntrySize;
  448. bool IboCached = Gpu.Renderer.Rasterizer.IsIboCached(IboKey, (uint)IbSize);
  449. bool UsesLegacyQuads =
  450. PrimType == GalPrimitiveType.Quads ||
  451. PrimType == GalPrimitiveType.QuadStrip;
  452. if (!IboCached || QueryKeyUpload(Vmm, IboKey, (uint)IbSize, NvGpuBufferType.Index))
  453. {
  454. if (!UsesLegacyQuads)
  455. {
  456. IntPtr DataAddress = Vmm.GetHostAddress(IbPosition, IbSize);
  457. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, DataAddress);
  458. }
  459. else
  460. {
  461. byte[] Buffer = Vmm.ReadBytes(IbPosition, IbSize);
  462. if (PrimType == GalPrimitiveType.Quads)
  463. {
  464. Buffer = QuadHelper.ConvertIbQuadsToTris(Buffer, IndexEntrySize, IndexCount);
  465. }
  466. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  467. {
  468. Buffer = QuadHelper.ConvertIbQuadStripToTris(Buffer, IndexEntrySize, IndexCount);
  469. }
  470. Gpu.Renderer.Rasterizer.CreateIbo(IboKey, IbSize, Buffer);
  471. }
  472. }
  473. if (!UsesLegacyQuads)
  474. {
  475. Gpu.Renderer.Rasterizer.SetIndexArray(IbSize, IndexFormat);
  476. }
  477. else
  478. {
  479. if (PrimType == GalPrimitiveType.Quads)
  480. {
  481. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadsToTris(IbSize), IndexFormat);
  482. }
  483. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  484. {
  485. Gpu.Renderer.Rasterizer.SetIndexArray(QuadHelper.ConvertIbSizeQuadStripToTris(IbSize), IndexFormat);
  486. }
  487. }
  488. }
  489. List<GalVertexAttrib>[] Attribs = new List<GalVertexAttrib>[32];
  490. for (int Attr = 0; Attr < 16; Attr++)
  491. {
  492. int Packed = ReadRegister(NvGpuEngine3dReg.VertexAttribNFormat + Attr);
  493. int ArrayIndex = Packed & 0x1f;
  494. if (Attribs[ArrayIndex] == null)
  495. {
  496. Attribs[ArrayIndex] = new List<GalVertexAttrib>();
  497. }
  498. long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + ArrayIndex * 4);
  499. int Offset = (Packed >> 7) & 0x3fff;
  500. //Note: 16 is the maximum size of an attribute,
  501. //having a component size of 32-bits with 4 elements (a vec4).
  502. IntPtr Pointer = Vmm.GetHostAddress(VertexPosition + Offset, 16);
  503. Attribs[ArrayIndex].Add(new GalVertexAttrib(
  504. Attr,
  505. ((Packed >> 6) & 0x1) != 0,
  506. Offset,
  507. Pointer,
  508. (GalVertexAttribSize)((Packed >> 21) & 0x3f),
  509. (GalVertexAttribType)((Packed >> 27) & 0x7),
  510. ((Packed >> 31) & 0x1) != 0));
  511. }
  512. State.VertexBindings = new GalVertexBinding[32];
  513. for (int Index = 0; Index < 32; Index++)
  514. {
  515. if (Attribs[Index] == null)
  516. {
  517. continue;
  518. }
  519. int Control = ReadRegister(NvGpuEngine3dReg.VertexArrayNControl + Index * 4);
  520. bool Enable = (Control & 0x1000) != 0;
  521. if (!Enable)
  522. {
  523. continue;
  524. }
  525. long VertexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNAddress + Index * 4);
  526. long VertexEndPos = MakeInt64From2xInt32(NvGpuEngine3dReg.VertexArrayNEndAddr + Index * 2);
  527. int VertexDivisor = ReadRegister(NvGpuEngine3dReg.VertexArrayNDivisor + Index * 4);
  528. bool Instanced = ReadRegisterBool(NvGpuEngine3dReg.VertexArrayNInstance + Index);
  529. int Stride = Control & 0xfff;
  530. if (Instanced && VertexDivisor != 0)
  531. {
  532. VertexPosition += Stride * (CurrentInstance / VertexDivisor);
  533. }
  534. if (VertexPosition > VertexEndPos)
  535. {
  536. //Instance is invalid, ignore the draw call
  537. continue;
  538. }
  539. long VboKey = Vmm.GetPhysicalAddress(VertexPosition);
  540. long VbSize = (VertexEndPos - VertexPosition) + 1;
  541. bool VboCached = Gpu.Renderer.Rasterizer.IsVboCached(VboKey, VbSize);
  542. if (!VboCached || QueryKeyUpload(Vmm, VboKey, VbSize, NvGpuBufferType.Vertex))
  543. {
  544. IntPtr DataAddress = Vmm.GetHostAddress(VertexPosition, VbSize);
  545. Gpu.Renderer.Rasterizer.CreateVbo(VboKey, (int)VbSize, DataAddress);
  546. }
  547. State.VertexBindings[Index].Enabled = true;
  548. State.VertexBindings[Index].Stride = Stride;
  549. State.VertexBindings[Index].VboKey = VboKey;
  550. State.VertexBindings[Index].Instanced = Instanced;
  551. State.VertexBindings[Index].Divisor = VertexDivisor;
  552. State.VertexBindings[Index].Attribs = Attribs[Index].ToArray();
  553. }
  554. }
  555. private void DispatchRender(NvGpuVmm Vmm, GalPipelineState State)
  556. {
  557. int IndexCount = ReadRegister(NvGpuEngine3dReg.IndexBatchCount);
  558. int PrimCtrl = ReadRegister(NvGpuEngine3dReg.VertexBeginGl);
  559. GalPrimitiveType PrimType = (GalPrimitiveType)(PrimCtrl & 0xffff);
  560. bool InstanceNext = ((PrimCtrl >> 26) & 1) != 0;
  561. bool InstanceCont = ((PrimCtrl >> 27) & 1) != 0;
  562. if (InstanceNext && InstanceCont)
  563. {
  564. throw new InvalidOperationException("GPU tried to increase and reset instance count at the same time");
  565. }
  566. if (InstanceNext)
  567. {
  568. CurrentInstance++;
  569. }
  570. else if (!InstanceCont)
  571. {
  572. CurrentInstance = 0;
  573. }
  574. State.Instance = CurrentInstance;
  575. Gpu.Renderer.Pipeline.Bind(State);
  576. Gpu.Renderer.RenderTarget.Bind();
  577. if (IndexCount != 0)
  578. {
  579. int IndexEntryFmt = ReadRegister(NvGpuEngine3dReg.IndexArrayFormat);
  580. int IndexFirst = ReadRegister(NvGpuEngine3dReg.IndexBatchFirst);
  581. int VertexBase = ReadRegister(NvGpuEngine3dReg.VertexArrayElemBase);
  582. long IndexPosition = MakeInt64From2xInt32(NvGpuEngine3dReg.IndexArrayAddress);
  583. long IboKey = Vmm.GetPhysicalAddress(IndexPosition);
  584. //Quad primitive types were deprecated on OpenGL 3.x,
  585. //they are converted to a triangles index buffer on IB creation,
  586. //so we should use the triangles type here too.
  587. if (PrimType == GalPrimitiveType.Quads ||
  588. PrimType == GalPrimitiveType.QuadStrip)
  589. {
  590. PrimType = GalPrimitiveType.Triangles;
  591. //Note: We assume that index first points to the first
  592. //vertex of a quad, if it points to the middle of a
  593. //quad (First % 4 != 0 for Quads) then it will not work properly.
  594. if (PrimType == GalPrimitiveType.Quads)
  595. {
  596. IndexFirst = QuadHelper.ConvertIbSizeQuadsToTris(IndexFirst);
  597. }
  598. else /* if (PrimType == GalPrimitiveType.QuadStrip) */
  599. {
  600. IndexFirst = QuadHelper.ConvertIbSizeQuadStripToTris(IndexFirst);
  601. }
  602. }
  603. Gpu.Renderer.Rasterizer.DrawElements(IboKey, IndexFirst, VertexBase, PrimType);
  604. }
  605. else
  606. {
  607. int VertexFirst = ReadRegister(NvGpuEngine3dReg.VertexArrayFirst);
  608. int VertexCount = ReadRegister(NvGpuEngine3dReg.VertexArrayCount);
  609. Gpu.Renderer.Rasterizer.DrawArrays(VertexFirst, VertexCount, PrimType);
  610. }
  611. //Is the GPU really clearing those registers after draw?
  612. WriteRegister(NvGpuEngine3dReg.IndexBatchFirst, 0);
  613. WriteRegister(NvGpuEngine3dReg.IndexBatchCount, 0);
  614. }
  615. private enum QueryMode
  616. {
  617. WriteSeq,
  618. Sync,
  619. WriteCounterAndTimestamp
  620. }
  621. private void QueryControl(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  622. {
  623. WriteRegister(PBEntry);
  624. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.QueryAddress);
  625. int Seq = Registers[(int)NvGpuEngine3dReg.QuerySequence];
  626. int Ctrl = Registers[(int)NvGpuEngine3dReg.QueryControl];
  627. QueryMode Mode = (QueryMode)(Ctrl & 3);
  628. switch (Mode)
  629. {
  630. case QueryMode.WriteSeq: Vmm.WriteInt32(Position, Seq); break;
  631. case QueryMode.WriteCounterAndTimestamp:
  632. {
  633. //TODO: Implement counters.
  634. long Counter = 1;
  635. long Timestamp = (uint)Environment.TickCount;
  636. Timestamp = (long)(Timestamp * 615384.615385);
  637. Vmm.WriteInt64(Position + 0, Counter);
  638. Vmm.WriteInt64(Position + 8, Timestamp);
  639. break;
  640. }
  641. }
  642. }
  643. private void CbData(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  644. {
  645. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  646. int Offset = ReadRegister(NvGpuEngine3dReg.ConstBufferOffset);
  647. foreach (int Arg in PBEntry.Arguments)
  648. {
  649. Vmm.WriteInt32(Position + Offset, Arg);
  650. Offset += 4;
  651. }
  652. WriteRegister(NvGpuEngine3dReg.ConstBufferOffset, Offset);
  653. UploadedKeys[(int)NvGpuBufferType.ConstBuffer].Clear();
  654. }
  655. private void CbBind(NvGpuVmm Vmm, NvGpuPBEntry PBEntry)
  656. {
  657. int Stage = (PBEntry.Method - 0x904) >> 3;
  658. int Index = PBEntry.Arguments[0];
  659. bool Enabled = (Index & 1) != 0;
  660. Index = (Index >> 4) & 0x1f;
  661. long Position = MakeInt64From2xInt32(NvGpuEngine3dReg.ConstBufferAddress);
  662. long CbKey = Vmm.GetPhysicalAddress(Position);
  663. int Size = ReadRegister(NvGpuEngine3dReg.ConstBufferSize);
  664. if (!Gpu.Renderer.Buffer.IsCached(CbKey, Size))
  665. {
  666. Gpu.Renderer.Buffer.Create(CbKey, Size);
  667. }
  668. ConstBuffer Cb = ConstBuffers[Stage][Index];
  669. if (Cb.Position != Position || Cb.Enabled != Enabled || Cb.Size != Size)
  670. {
  671. ConstBuffers[Stage][Index].Position = Position;
  672. ConstBuffers[Stage][Index].Enabled = Enabled;
  673. ConstBuffers[Stage][Index].Size = Size;
  674. }
  675. }
  676. private float GetFlipSign(NvGpuEngine3dReg Reg)
  677. {
  678. return MathF.Sign(ReadRegisterFloat(Reg));
  679. }
  680. private long MakeInt64From2xInt32(NvGpuEngine3dReg Reg)
  681. {
  682. return
  683. (long)Registers[(int)Reg + 0] << 32 |
  684. (uint)Registers[(int)Reg + 1];
  685. }
  686. private void WriteRegister(NvGpuPBEntry PBEntry)
  687. {
  688. int ArgsCount = PBEntry.Arguments.Count;
  689. if (ArgsCount > 0)
  690. {
  691. Registers[PBEntry.Method] = PBEntry.Arguments[ArgsCount - 1];
  692. }
  693. }
  694. private int ReadRegister(NvGpuEngine3dReg Reg)
  695. {
  696. return Registers[(int)Reg];
  697. }
  698. private float ReadRegisterFloat(NvGpuEngine3dReg Reg)
  699. {
  700. return BitConverter.Int32BitsToSingle(ReadRegister(Reg));
  701. }
  702. private bool ReadRegisterBool(NvGpuEngine3dReg Reg)
  703. {
  704. return (ReadRegister(Reg) & 1) != 0;
  705. }
  706. private void WriteRegister(NvGpuEngine3dReg Reg, int Value)
  707. {
  708. Registers[(int)Reg] = Value;
  709. }
  710. private bool QueryKeyUpload(NvGpuVmm Vmm, long Key, long Size, NvGpuBufferType Type)
  711. {
  712. List<long> Uploaded = UploadedKeys[(int)Type];
  713. if (Uploaded.Contains(Key))
  714. {
  715. return false;
  716. }
  717. Uploaded.Add(Key);
  718. return Vmm.IsRegionModified(Key, Size, Type);
  719. }
  720. }
  721. }