BufferManager.cs 39 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025
  1. using Ryujinx.Common;
  2. using Ryujinx.Graphics.GAL;
  3. using Ryujinx.Graphics.Gpu.Image;
  4. using Ryujinx.Graphics.Gpu.State;
  5. using Ryujinx.Graphics.Shader;
  6. using Ryujinx.Memory.Range;
  7. using System;
  8. using System.Collections.Generic;
  9. using System.Collections.ObjectModel;
  10. using System.Linq;
  11. namespace Ryujinx.Graphics.Gpu.Memory
  12. {
  13. /// <summary>
  14. /// Buffer manager.
  15. /// </summary>
  16. class BufferManager
  17. {
  18. private const int StackToHeapThreshold = 16;
  19. private const int OverlapsBufferInitialCapacity = 10;
  20. private const int OverlapsBufferMaxCapacity = 10000;
  21. private const ulong BufferAlignmentSize = 0x1000;
  22. private const ulong BufferAlignmentMask = BufferAlignmentSize - 1;
  23. private GpuContext _context;
  24. private RangeList<Buffer> _buffers;
  25. private Buffer[] _bufferOverlaps;
  26. private IndexBuffer _indexBuffer;
  27. private VertexBuffer[] _vertexBuffers;
  28. private BufferBounds[] _transformFeedbackBuffers;
  29. private List<BufferTextureBinding> _bufferTextures;
  30. /// <summary>
  31. /// Holds shader stage buffer state and binding information.
  32. /// </summary>
  33. private class BuffersPerStage
  34. {
  35. /// <summary>
  36. /// Shader buffer binding information.
  37. /// </summary>
  38. public BufferDescriptor[] Bindings { get; }
  39. /// <summary>
  40. /// Buffer regions.
  41. /// </summary>
  42. public BufferBounds[] Buffers { get; }
  43. /// <summary>
  44. /// Total amount of buffers used on the shader.
  45. /// </summary>
  46. public int Count { get; private set; }
  47. /// <summary>
  48. /// Creates a new instance of the shader stage buffer information.
  49. /// </summary>
  50. /// <param name="count">Maximum amount of buffers that the shader stage can use</param>
  51. public BuffersPerStage(int count)
  52. {
  53. Bindings = new BufferDescriptor[count];
  54. Buffers = new BufferBounds[count];
  55. }
  56. /// <summary>
  57. /// Sets the region of a buffer at a given slot.
  58. /// </summary>
  59. /// <param name="index">Buffer slot</param>
  60. /// <param name="address">Region virtual address</param>
  61. /// <param name="size">Region size in bytes</param>
  62. /// <param name="flags">Buffer usage flags</param>
  63. public void SetBounds(int index, ulong address, ulong size, BufferUsageFlags flags = BufferUsageFlags.None)
  64. {
  65. Buffers[index] = new BufferBounds(address, size, flags);
  66. }
  67. /// <summary>
  68. /// Sets shader buffer binding information.
  69. /// </summary>
  70. /// <param name="descriptors">Buffer binding information</param>
  71. public void SetBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  72. {
  73. if (descriptors == null)
  74. {
  75. Count = 0;
  76. return;
  77. }
  78. descriptors.CopyTo(Bindings, 0);
  79. Count = descriptors.Count;
  80. }
  81. }
  82. private BuffersPerStage _cpStorageBuffers;
  83. private BuffersPerStage _cpUniformBuffers;
  84. private BuffersPerStage[] _gpStorageBuffers;
  85. private BuffersPerStage[] _gpUniformBuffers;
  86. private int _cpStorageBufferBindings;
  87. private int _cpUniformBufferBindings;
  88. private int _gpStorageBufferBindings;
  89. private int _gpUniformBufferBindings;
  90. private bool _gpStorageBuffersDirty;
  91. private bool _gpUniformBuffersDirty;
  92. private bool _indexBufferDirty;
  93. private bool _vertexBuffersDirty;
  94. private uint _vertexBuffersEnableMask;
  95. private bool _transformFeedbackBuffersDirty;
  96. private bool _rebind;
  97. /// <summary>
  98. /// Creates a new instance of the buffer manager.
  99. /// </summary>
  100. /// <param name="context">The GPU context that the buffer manager belongs to</param>
  101. public BufferManager(GpuContext context)
  102. {
  103. _context = context;
  104. _buffers = new RangeList<Buffer>();
  105. _bufferOverlaps = new Buffer[OverlapsBufferInitialCapacity];
  106. _vertexBuffers = new VertexBuffer[Constants.TotalVertexBuffers];
  107. _transformFeedbackBuffers = new BufferBounds[Constants.TotalTransformFeedbackBuffers];
  108. _cpStorageBuffers = new BuffersPerStage(Constants.TotalCpStorageBuffers);
  109. _cpUniformBuffers = new BuffersPerStage(Constants.TotalCpUniformBuffers);
  110. _gpStorageBuffers = new BuffersPerStage[Constants.ShaderStages];
  111. _gpUniformBuffers = new BuffersPerStage[Constants.ShaderStages];
  112. for (int index = 0; index < Constants.ShaderStages; index++)
  113. {
  114. _gpStorageBuffers[index] = new BuffersPerStage(Constants.TotalGpStorageBuffers);
  115. _gpUniformBuffers[index] = new BuffersPerStage(Constants.TotalGpUniformBuffers);
  116. }
  117. _bufferTextures = new List<BufferTextureBinding>();
  118. }
  119. /// <summary>
  120. /// Sets the memory range with the index buffer data, to be used for subsequent draw calls.
  121. /// </summary>
  122. /// <param name="gpuVa">Start GPU virtual address of the index buffer</param>
  123. /// <param name="size">Size, in bytes, of the index buffer</param>
  124. /// <param name="type">Type of each index buffer element</param>
  125. public void SetIndexBuffer(ulong gpuVa, ulong size, IndexType type)
  126. {
  127. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  128. _indexBuffer.Address = address;
  129. _indexBuffer.Size = size;
  130. _indexBuffer.Type = type;
  131. _indexBufferDirty = true;
  132. }
  133. /// <summary>
  134. /// Sets a new index buffer that overrides the one set on the call to <see cref="CommitGraphicsBindings"/>.
  135. /// </summary>
  136. /// <param name="buffer">Buffer to be used as index buffer</param>
  137. /// <param name="type">Type of each index buffer element</param>
  138. public void SetIndexBuffer(BufferRange buffer, IndexType type)
  139. {
  140. _context.Renderer.Pipeline.SetIndexBuffer(buffer, type);
  141. _indexBufferDirty = true;
  142. }
  143. /// <summary>
  144. /// Sets the memory range with vertex buffer data, to be used for subsequent draw calls.
  145. /// </summary>
  146. /// <param name="index">Index of the vertex buffer (up to 16)</param>
  147. /// <param name="gpuVa">GPU virtual address of the buffer</param>
  148. /// <param name="size">Size in bytes of the buffer</param>
  149. /// <param name="stride">Stride of the buffer, defined as the number of bytes of each vertex</param>
  150. /// <param name="divisor">Vertex divisor of the buffer, for instanced draws</param>
  151. public void SetVertexBuffer(int index, ulong gpuVa, ulong size, int stride, int divisor)
  152. {
  153. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  154. _vertexBuffers[index].Address = address;
  155. _vertexBuffers[index].Size = size;
  156. _vertexBuffers[index].Stride = stride;
  157. _vertexBuffers[index].Divisor = divisor;
  158. _vertexBuffersDirty = true;
  159. if (address != 0)
  160. {
  161. _vertexBuffersEnableMask |= 1u << index;
  162. }
  163. else
  164. {
  165. _vertexBuffersEnableMask &= ~(1u << index);
  166. }
  167. }
  168. /// <summary>
  169. /// Sets a transform feedback buffer on the graphics pipeline.
  170. /// The output from the vertex transformation stages are written into the feedback buffer.
  171. /// </summary>
  172. /// <param name="index">Index of the transform feedback buffer</param>
  173. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  174. /// <param name="size">Size in bytes of the transform feedback buffer</param>
  175. public void SetTransformFeedbackBuffer(int index, ulong gpuVa, ulong size)
  176. {
  177. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  178. _transformFeedbackBuffers[index] = new BufferBounds(address, size);
  179. _transformFeedbackBuffersDirty = true;
  180. }
  181. /// <summary>
  182. /// Sets a storage buffer on the compute pipeline.
  183. /// Storage buffers can be read and written to on shaders.
  184. /// </summary>
  185. /// <param name="index">Index of the storage buffer</param>
  186. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  187. /// <param name="size">Size in bytes of the storage buffer</param>
  188. /// <param name="flags">Buffer usage flags</param>
  189. public void SetComputeStorageBuffer(int index, ulong gpuVa, ulong size, BufferUsageFlags flags)
  190. {
  191. size += gpuVa & ((ulong)_context.Capabilities.StorageBufferOffsetAlignment - 1);
  192. gpuVa = BitUtils.AlignDown(gpuVa, _context.Capabilities.StorageBufferOffsetAlignment);
  193. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  194. _cpStorageBuffers.SetBounds(index, address, size, flags);
  195. }
  196. /// <summary>
  197. /// Sets a storage buffer on the graphics pipeline.
  198. /// Storage buffers can be read and written to on shaders.
  199. /// </summary>
  200. /// <param name="stage">Index of the shader stage</param>
  201. /// <param name="index">Index of the storage buffer</param>
  202. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  203. /// <param name="size">Size in bytes of the storage buffer</param>
  204. /// <param name="flags">Buffer usage flags</param>
  205. public void SetGraphicsStorageBuffer(int stage, int index, ulong gpuVa, ulong size, BufferUsageFlags flags)
  206. {
  207. size += gpuVa & ((ulong)_context.Capabilities.StorageBufferOffsetAlignment - 1);
  208. gpuVa = BitUtils.AlignDown(gpuVa, _context.Capabilities.StorageBufferOffsetAlignment);
  209. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  210. if (_gpStorageBuffers[stage].Buffers[index].Address != address ||
  211. _gpStorageBuffers[stage].Buffers[index].Size != size)
  212. {
  213. _gpStorageBuffersDirty = true;
  214. }
  215. _gpStorageBuffers[stage].SetBounds(index, address, size, flags);
  216. }
  217. /// <summary>
  218. /// Sets a uniform buffer on the compute pipeline.
  219. /// Uniform buffers are read-only from shaders, and have a small capacity.
  220. /// </summary>
  221. /// <param name="index">Index of the uniform buffer</param>
  222. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  223. /// <param name="size">Size in bytes of the storage buffer</param>
  224. public void SetComputeUniformBuffer(int index, ulong gpuVa, ulong size)
  225. {
  226. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  227. _cpUniformBuffers.SetBounds(index, address, size);
  228. }
  229. /// <summary>
  230. /// Sets a uniform buffer on the graphics pipeline.
  231. /// Uniform buffers are read-only from shaders, and have a small capacity.
  232. /// </summary>
  233. /// <param name="stage">Index of the shader stage</param>
  234. /// <param name="index">Index of the uniform buffer</param>
  235. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  236. /// <param name="size">Size in bytes of the storage buffer</param>
  237. public void SetGraphicsUniformBuffer(int stage, int index, ulong gpuVa, ulong size)
  238. {
  239. ulong address = TranslateAndCreateBuffer(gpuVa, size);
  240. _gpUniformBuffers[stage].SetBounds(index, address, size);
  241. _gpUniformBuffersDirty = true;
  242. }
  243. /// <summary>
  244. /// Sets the binding points for the storage buffers bound on the compute pipeline.
  245. /// </summary>
  246. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  247. public void SetComputeStorageBufferBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  248. {
  249. _cpStorageBuffers.SetBindings(descriptors);
  250. _cpStorageBufferBindings = descriptors.Count != 0 ? descriptors.Max(x => x.Binding) + 1 : 0;
  251. }
  252. /// <summary>
  253. /// Sets the binding points for the storage buffers bound on the graphics pipeline.
  254. /// </summary>
  255. /// <param name="stage">Index of the shader stage</param>
  256. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  257. public void SetGraphicsStorageBufferBindings(int stage, ReadOnlyCollection<BufferDescriptor> descriptors)
  258. {
  259. _gpStorageBuffers[stage].SetBindings(descriptors);
  260. _gpStorageBuffersDirty = true;
  261. }
  262. /// <summary>
  263. /// Sets the total number of storage buffer bindings used.
  264. /// </summary>
  265. /// <param name="count">Number of storage buffer bindings used</param>
  266. public void SetGraphicsStorageBufferBindingsCount(int count)
  267. {
  268. _gpStorageBufferBindings = count;
  269. }
  270. /// <summary>
  271. /// Sets the binding points for the uniform buffers bound on the compute pipeline.
  272. /// </summary>
  273. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  274. public void SetComputeUniformBufferBindings(ReadOnlyCollection<BufferDescriptor> descriptors)
  275. {
  276. _cpUniformBuffers.SetBindings(descriptors);
  277. _cpUniformBufferBindings = descriptors.Count != 0 ? descriptors.Max(x => x.Binding) + 1 : 0;
  278. }
  279. /// <summary>
  280. /// Sets the enabled uniform buffers mask on the graphics pipeline.
  281. /// Each bit set on the mask indicates that the respective buffer index is enabled.
  282. /// </summary>
  283. /// <param name="stage">Index of the shader stage</param>
  284. /// <param name="descriptors">Buffer descriptors with the binding point values</param>
  285. public void SetGraphicsUniformBufferBindings(int stage, ReadOnlyCollection<BufferDescriptor> descriptors)
  286. {
  287. _gpUniformBuffers[stage].SetBindings(descriptors);
  288. _gpUniformBuffersDirty = true;
  289. }
  290. /// <summary>
  291. /// Sets the total number of uniform buffer bindings used.
  292. /// </summary>
  293. /// <param name="count">Number of uniform buffer bindings used</param>
  294. public void SetGraphicsUniformBufferBindingsCount(int count)
  295. {
  296. _gpUniformBufferBindings = count;
  297. }
  298. /// <summary>
  299. /// Gets a bit mask indicating which compute uniform buffers are currently bound.
  300. /// </summary>
  301. /// <returns>Mask where each bit set indicates a bound constant buffer</returns>
  302. public uint GetComputeUniformBufferUseMask()
  303. {
  304. uint mask = 0;
  305. for (int i = 0; i < _cpUniformBuffers.Buffers.Length; i++)
  306. {
  307. if (_cpUniformBuffers.Buffers[i].Address != 0)
  308. {
  309. mask |= 1u << i;
  310. }
  311. }
  312. return mask;
  313. }
  314. /// <summary>
  315. /// Gets a bit mask indicating which graphics uniform buffers are currently bound.
  316. /// </summary>
  317. /// <param name="stage">Index of the shader stage</param>
  318. /// <returns>Mask where each bit set indicates a bound constant buffer</returns>
  319. public uint GetGraphicsUniformBufferUseMask(int stage)
  320. {
  321. uint mask = 0;
  322. for (int i = 0; i < _gpUniformBuffers[stage].Buffers.Length; i++)
  323. {
  324. if (_gpUniformBuffers[stage].Buffers[i].Address != 0)
  325. {
  326. mask |= 1u << i;
  327. }
  328. }
  329. return mask;
  330. }
  331. /// <summary>
  332. /// Handles removal of buffers written to a memory region being unmapped.
  333. /// </summary>
  334. /// <param name="sender">Sender object</param>
  335. /// <param name="e">Event arguments</param>
  336. public void MemoryUnmappedHandler(object sender, UnmapEventArgs e)
  337. {
  338. Buffer[] overlaps = new Buffer[10];
  339. int overlapCount;
  340. ulong address = _context.MemoryManager.Translate(e.Address);
  341. ulong size = e.Size;
  342. lock (_buffers)
  343. {
  344. overlapCount = _buffers.FindOverlaps(address, size, ref overlaps);
  345. }
  346. for (int i = 0; i < overlapCount; i++)
  347. {
  348. overlaps[i].Unmapped(address, size);
  349. }
  350. }
  351. /// <summary>
  352. /// Performs address translation of the GPU virtual address, and creates a
  353. /// new buffer, if needed, for the specified range.
  354. /// </summary>
  355. /// <param name="gpuVa">Start GPU virtual address of the buffer</param>
  356. /// <param name="size">Size in bytes of the buffer</param>
  357. /// <returns>CPU virtual address of the buffer, after address translation</returns>
  358. private ulong TranslateAndCreateBuffer(ulong gpuVa, ulong size)
  359. {
  360. if (gpuVa == 0)
  361. {
  362. return 0;
  363. }
  364. ulong address = _context.MemoryManager.Translate(gpuVa);
  365. if (address == MemoryManager.PteUnmapped)
  366. {
  367. return 0;
  368. }
  369. CreateBuffer(address, size);
  370. return address;
  371. }
  372. /// <summary>
  373. /// Creates a new buffer for the specified range, if it does not yet exist.
  374. /// This can be used to ensure the existance of a buffer.
  375. /// </summary>
  376. /// <param name="address">Address of the buffer in memory</param>
  377. /// <param name="size">Size of the buffer in bytes</param>
  378. public void CreateBuffer(ulong address, ulong size)
  379. {
  380. ulong endAddress = address + size;
  381. ulong alignedAddress = address & ~BufferAlignmentMask;
  382. ulong alignedEndAddress = (endAddress + BufferAlignmentMask) & ~BufferAlignmentMask;
  383. // The buffer must have the size of at least one page.
  384. if (alignedEndAddress == alignedAddress)
  385. {
  386. alignedEndAddress += BufferAlignmentSize;
  387. }
  388. CreateBufferAligned(alignedAddress, alignedEndAddress - alignedAddress);
  389. }
  390. /// <summary>
  391. /// Creates a new buffer for the specified range, if needed.
  392. /// If a buffer where this range can be fully contained already exists,
  393. /// then the creation of a new buffer is not necessary.
  394. /// </summary>
  395. /// <param name="address">Address of the buffer in guest memory</param>
  396. /// <param name="size">Size in bytes of the buffer</param>
  397. private void CreateBufferAligned(ulong address, ulong size)
  398. {
  399. int overlapsCount;
  400. lock (_buffers)
  401. {
  402. overlapsCount = _buffers.FindOverlapsNonOverlapping(address, size, ref _bufferOverlaps);
  403. }
  404. if (overlapsCount != 0)
  405. {
  406. // The buffer already exists. We can just return the existing buffer
  407. // if the buffer we need is fully contained inside the overlapping buffer.
  408. // Otherwise, we must delete the overlapping buffers and create a bigger buffer
  409. // that fits all the data we need. We also need to copy the contents from the
  410. // old buffer(s) to the new buffer.
  411. ulong endAddress = address + size;
  412. if (_bufferOverlaps[0].Address > address || _bufferOverlaps[0].EndAddress < endAddress)
  413. {
  414. for (int index = 0; index < overlapsCount; index++)
  415. {
  416. Buffer buffer = _bufferOverlaps[index];
  417. address = Math.Min(address, buffer.Address);
  418. endAddress = Math.Max(endAddress, buffer.EndAddress);
  419. lock (_buffers)
  420. {
  421. _buffers.Remove(buffer);
  422. }
  423. }
  424. Buffer newBuffer = new Buffer(_context, address, endAddress - address);
  425. newBuffer.SynchronizeMemory(address, endAddress - address);
  426. lock (_buffers)
  427. {
  428. _buffers.Add(newBuffer);
  429. }
  430. for (int index = 0; index < overlapsCount; index++)
  431. {
  432. Buffer buffer = _bufferOverlaps[index];
  433. int dstOffset = (int)(buffer.Address - newBuffer.Address);
  434. buffer.SynchronizeMemory(buffer.Address, buffer.Size);
  435. buffer.CopyTo(newBuffer, dstOffset);
  436. newBuffer.InheritModifiedRanges(buffer);
  437. buffer.Dispose();
  438. }
  439. // Existing buffers were modified, we need to rebind everything.
  440. _rebind = true;
  441. }
  442. }
  443. else
  444. {
  445. // No overlap, just create a new buffer.
  446. Buffer buffer = new Buffer(_context, address, size);
  447. lock (_buffers)
  448. {
  449. _buffers.Add(buffer);
  450. }
  451. }
  452. ShrinkOverlapsBufferIfNeeded();
  453. }
  454. /// <summary>
  455. /// Resizes the temporary buffer used for range list intersection results, if it has grown too much.
  456. /// </summary>
  457. private void ShrinkOverlapsBufferIfNeeded()
  458. {
  459. if (_bufferOverlaps.Length > OverlapsBufferMaxCapacity)
  460. {
  461. Array.Resize(ref _bufferOverlaps, OverlapsBufferMaxCapacity);
  462. }
  463. }
  464. /// <summary>
  465. /// Gets the address of the compute uniform buffer currently bound at the given index.
  466. /// </summary>
  467. /// <param name="index">Index of the uniform buffer binding</param>
  468. /// <returns>The uniform buffer address, or an undefined value if the buffer is not currently bound</returns>
  469. public ulong GetComputeUniformBufferAddress(int index)
  470. {
  471. return _cpUniformBuffers.Buffers[index].Address;
  472. }
  473. /// <summary>
  474. /// Gets the address of the graphics uniform buffer currently bound at the given index.
  475. /// </summary>
  476. /// <param name="stage">Index of the shader stage</param>
  477. /// <param name="index">Index of the uniform buffer binding</param>
  478. /// <returns>The uniform buffer address, or an undefined value if the buffer is not currently bound</returns>
  479. public ulong GetGraphicsUniformBufferAddress(int stage, int index)
  480. {
  481. return _gpUniformBuffers[stage].Buffers[index].Address;
  482. }
  483. /// <summary>
  484. /// Ensures that the compute engine bindings are visible to the host GPU.
  485. /// Note: this actually performs the binding using the host graphics API.
  486. /// </summary>
  487. public void CommitComputeBindings()
  488. {
  489. int sCount = _cpStorageBufferBindings;
  490. Span<BufferRange> sRanges = sCount < StackToHeapThreshold ? stackalloc BufferRange[sCount] : new BufferRange[sCount];
  491. for (int index = 0; index < _cpStorageBuffers.Count; index++)
  492. {
  493. ref var bindingInfo = ref _cpStorageBuffers.Bindings[index];
  494. BufferBounds bounds = _cpStorageBuffers.Buffers[bindingInfo.Slot];
  495. if (bounds.Address != 0)
  496. {
  497. // The storage buffer size is not reliable (it might be lower than the actual size),
  498. // so we bind the entire buffer to allow otherwise out of range accesses to work.
  499. sRanges[bindingInfo.Binding] = GetBufferRangeTillEnd(
  500. bounds.Address,
  501. bounds.Size,
  502. bounds.Flags.HasFlag(BufferUsageFlags.Write));
  503. }
  504. }
  505. _context.Renderer.Pipeline.SetStorageBuffers(sRanges);
  506. int uCount = _cpUniformBufferBindings;
  507. Span<BufferRange> uRanges = uCount < StackToHeapThreshold ? stackalloc BufferRange[uCount] : new BufferRange[uCount];
  508. for (int index = 0; index < _cpUniformBuffers.Count; index++)
  509. {
  510. ref var bindingInfo = ref _cpUniformBuffers.Bindings[index];
  511. BufferBounds bounds = _cpUniformBuffers.Buffers[bindingInfo.Slot];
  512. if (bounds.Address != 0)
  513. {
  514. uRanges[bindingInfo.Binding] = GetBufferRange(bounds.Address, bounds.Size);
  515. }
  516. }
  517. _context.Renderer.Pipeline.SetUniformBuffers(uRanges);
  518. CommitBufferTextureBindings();
  519. // Force rebind after doing compute work.
  520. _rebind = true;
  521. }
  522. /// <summary>
  523. /// Commit any queued buffer texture bindings.
  524. /// </summary>
  525. private void CommitBufferTextureBindings()
  526. {
  527. if (_bufferTextures.Count > 0)
  528. {
  529. foreach (var binding in _bufferTextures)
  530. {
  531. binding.Texture.SetStorage(GetBufferRange(binding.Address, binding.Size, binding.BindingInfo.Flags.HasFlag(TextureUsageFlags.ImageStore)));
  532. // The texture must be rebound to use the new storage if it was updated.
  533. if (binding.IsImage)
  534. {
  535. _context.Renderer.Pipeline.SetImage(binding.BindingInfo.Binding, binding.Texture, binding.Format);
  536. }
  537. else
  538. {
  539. _context.Renderer.Pipeline.SetTexture(binding.BindingInfo.Binding, binding.Texture);
  540. }
  541. }
  542. _bufferTextures.Clear();
  543. }
  544. }
  545. /// <summary>
  546. /// Ensures that the graphics engine bindings are visible to the host GPU.
  547. /// Note: this actually performs the binding using the host graphics API.
  548. /// </summary>
  549. public void CommitGraphicsBindings()
  550. {
  551. if (_indexBufferDirty || _rebind)
  552. {
  553. _indexBufferDirty = false;
  554. if (_indexBuffer.Address != 0)
  555. {
  556. BufferRange buffer = GetBufferRange(_indexBuffer.Address, _indexBuffer.Size);
  557. _context.Renderer.Pipeline.SetIndexBuffer(buffer, _indexBuffer.Type);
  558. }
  559. }
  560. else if (_indexBuffer.Address != 0)
  561. {
  562. SynchronizeBufferRange(_indexBuffer.Address, _indexBuffer.Size);
  563. }
  564. uint vbEnableMask = _vertexBuffersEnableMask;
  565. if (_vertexBuffersDirty || _rebind)
  566. {
  567. _vertexBuffersDirty = false;
  568. Span<VertexBufferDescriptor> vertexBuffers = stackalloc VertexBufferDescriptor[Constants.TotalVertexBuffers];
  569. for (int index = 0; (vbEnableMask >> index) != 0; index++)
  570. {
  571. VertexBuffer vb = _vertexBuffers[index];
  572. if (vb.Address == 0)
  573. {
  574. continue;
  575. }
  576. BufferRange buffer = GetBufferRange(vb.Address, vb.Size);
  577. vertexBuffers[index] = new VertexBufferDescriptor(buffer, vb.Stride, vb.Divisor);
  578. }
  579. _context.Renderer.Pipeline.SetVertexBuffers(vertexBuffers);
  580. }
  581. else
  582. {
  583. for (int index = 0; (vbEnableMask >> index) != 0; index++)
  584. {
  585. VertexBuffer vb = _vertexBuffers[index];
  586. if (vb.Address == 0)
  587. {
  588. continue;
  589. }
  590. SynchronizeBufferRange(vb.Address, vb.Size);
  591. }
  592. }
  593. if (_transformFeedbackBuffersDirty || _rebind)
  594. {
  595. _transformFeedbackBuffersDirty = false;
  596. Span<BufferRange> tfbs = stackalloc BufferRange[Constants.TotalTransformFeedbackBuffers];
  597. for (int index = 0; index < Constants.TotalTransformFeedbackBuffers; index++)
  598. {
  599. BufferBounds tfb = _transformFeedbackBuffers[index];
  600. if (tfb.Address == 0)
  601. {
  602. tfbs[index] = BufferRange.Empty;
  603. continue;
  604. }
  605. tfbs[index] = GetBufferRange(tfb.Address, tfb.Size);
  606. }
  607. _context.Renderer.Pipeline.SetTransformFeedbackBuffers(tfbs);
  608. }
  609. else
  610. {
  611. for (int index = 0; index < Constants.TotalTransformFeedbackBuffers; index++)
  612. {
  613. BufferBounds tfb = _transformFeedbackBuffers[index];
  614. if (tfb.Address == 0)
  615. {
  616. continue;
  617. }
  618. SynchronizeBufferRange(tfb.Address, tfb.Size);
  619. }
  620. }
  621. if (_gpStorageBuffersDirty || _rebind)
  622. {
  623. _gpStorageBuffersDirty = false;
  624. BindBuffers(_gpStorageBuffers, isStorage: true);
  625. }
  626. else
  627. {
  628. UpdateBuffers(_gpStorageBuffers);
  629. }
  630. if (_gpUniformBuffersDirty || _rebind)
  631. {
  632. _gpUniformBuffersDirty = false;
  633. BindBuffers(_gpUniformBuffers, isStorage: false);
  634. }
  635. else
  636. {
  637. UpdateBuffers(_gpUniformBuffers);
  638. }
  639. CommitBufferTextureBindings();
  640. _rebind = false;
  641. }
  642. /// <summary>
  643. /// Bind respective buffer bindings on the host API.
  644. /// </summary>
  645. /// <param name="bindings">Bindings to bind</param>
  646. /// <param name="isStorage">True to bind as storage buffer, false to bind as uniform buffers</param>
  647. private void BindBuffers(BuffersPerStage[] bindings, bool isStorage)
  648. {
  649. int count = isStorage ? _gpStorageBufferBindings : _gpUniformBufferBindings;
  650. Span<BufferRange> ranges = count < StackToHeapThreshold ? stackalloc BufferRange[count] : new BufferRange[count];
  651. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  652. {
  653. ref var buffers = ref bindings[(int)stage - 1];
  654. for (int index = 0; index < buffers.Count; index++)
  655. {
  656. ref var bindingInfo = ref buffers.Bindings[index];
  657. BufferBounds bounds = buffers.Buffers[bindingInfo.Slot];
  658. if (bounds.Address != 0)
  659. {
  660. ranges[bindingInfo.Binding] = isStorage
  661. ? GetBufferRangeTillEnd(bounds.Address, bounds.Size, bounds.Flags.HasFlag(BufferUsageFlags.Write))
  662. : GetBufferRange(bounds.Address, bounds.Size, bounds.Flags.HasFlag(BufferUsageFlags.Write));
  663. }
  664. }
  665. }
  666. if (isStorage)
  667. {
  668. _context.Renderer.Pipeline.SetStorageBuffers(ranges);
  669. }
  670. else
  671. {
  672. _context.Renderer.Pipeline.SetUniformBuffers(ranges);
  673. }
  674. }
  675. /// <summary>
  676. /// Updates data for the already bound buffer bindings.
  677. /// </summary>
  678. /// <param name="bindings">Bindings to update</param>
  679. private void UpdateBuffers(BuffersPerStage[] bindings)
  680. {
  681. for (ShaderStage stage = ShaderStage.Vertex; stage <= ShaderStage.Fragment; stage++)
  682. {
  683. ref var buffers = ref bindings[(int)stage - 1];
  684. for (int index = 0; index < buffers.Count; index++)
  685. {
  686. ref var binding = ref buffers.Bindings[index];
  687. BufferBounds bounds = buffers.Buffers[binding.Slot];
  688. if (bounds.Address == 0)
  689. {
  690. continue;
  691. }
  692. SynchronizeBufferRange(bounds.Address, bounds.Size);
  693. }
  694. }
  695. }
  696. /// <summary>
  697. /// Sets the buffer storage of a buffer texture. This will be bound when the buffer manager commits bindings.
  698. /// </summary>
  699. /// <param name="texture">Buffer texture</param>
  700. /// <param name="address">Address of the buffer in memory</param>
  701. /// <param name="size">Size of the buffer in bytes</param>
  702. /// <param name="bindingInfo">Binding info for the buffer texture</param>
  703. /// <param name="format">Format of the buffer texture</param>
  704. /// <param name="isImage">Whether the binding is for an image or a sampler</param>
  705. public void SetBufferTextureStorage(ITexture texture, ulong address, ulong size, TextureBindingInfo bindingInfo, Format format, bool isImage)
  706. {
  707. CreateBuffer(address, size);
  708. _bufferTextures.Add(new BufferTextureBinding(texture, address, size, bindingInfo, format, isImage));
  709. }
  710. /// <summary>
  711. /// Copy a buffer data from a given address to another.
  712. /// </summary>
  713. /// <remarks>
  714. /// This does a GPU side copy.
  715. /// </remarks>
  716. /// <param name="srcVa">GPU virtual address of the copy source</param>
  717. /// <param name="dstVa">GPU virtual address of the copy destination</param>
  718. /// <param name="size">Size in bytes of the copy</param>
  719. public void CopyBuffer(GpuVa srcVa, GpuVa dstVa, ulong size)
  720. {
  721. ulong srcAddress = TranslateAndCreateBuffer(srcVa.Pack(), size);
  722. ulong dstAddress = TranslateAndCreateBuffer(dstVa.Pack(), size);
  723. Buffer srcBuffer = GetBuffer(srcAddress, size);
  724. Buffer dstBuffer = GetBuffer(dstAddress, size);
  725. int srcOffset = (int)(srcAddress - srcBuffer.Address);
  726. int dstOffset = (int)(dstAddress - dstBuffer.Address);
  727. _context.Renderer.Pipeline.CopyBuffer(
  728. srcBuffer.Handle,
  729. dstBuffer.Handle,
  730. srcOffset,
  731. dstOffset,
  732. (int)size);
  733. if (srcBuffer.IsModified(srcAddress, size))
  734. {
  735. dstBuffer.SignalModified(dstAddress, size);
  736. }
  737. else
  738. {
  739. // Optimization: If the data being copied is already in memory, then copy it directly instead of flushing from GPU.
  740. dstBuffer.ClearModified(dstAddress, size);
  741. _context.PhysicalMemory.WriteUntracked(dstAddress, _context.PhysicalMemory.GetSpan(srcAddress, (int)size));
  742. }
  743. }
  744. /// <summary>
  745. /// Clears a buffer at a given address with the specified value.
  746. /// </summary>
  747. /// <remarks>
  748. /// Both the address and size must be aligned to 4 bytes.
  749. /// </remarks>
  750. /// <param name="gpuVa">GPU virtual address of the region to clear</param>
  751. /// <param name="size">Number of bytes to clear</param>
  752. /// <param name="value">Value to be written into the buffer</param>
  753. public void ClearBuffer(GpuVa gpuVa, ulong size, uint value)
  754. {
  755. ulong address = TranslateAndCreateBuffer(gpuVa.Pack(), size);
  756. Buffer buffer = GetBuffer(address, size);
  757. int offset = (int)(address - buffer.Address);
  758. _context.Renderer.Pipeline.ClearBuffer(buffer.Handle, offset, (int)size, value);
  759. buffer.SignalModified(address, size);
  760. }
  761. /// <summary>
  762. /// Gets a buffer sub-range starting at a given memory address.
  763. /// </summary>
  764. /// <param name="address">Start address of the memory range</param>
  765. /// <param name="size">Size in bytes of the memory range</param>
  766. /// <param name="write">Whether the buffer will be written to by this use</param>
  767. /// <returns>The buffer sub-range starting at the given memory address</returns>
  768. private BufferRange GetBufferRangeTillEnd(ulong address, ulong size, bool write = false)
  769. {
  770. return GetBuffer(address, size, write).GetRange(address);
  771. }
  772. /// <summary>
  773. /// Gets a buffer sub-range for a given memory range.
  774. /// </summary>
  775. /// <param name="address">Start address of the memory range</param>
  776. /// <param name="size">Size in bytes of the memory range</param>
  777. /// <param name="write">Whether the buffer will be written to by this use</param>
  778. /// <returns>The buffer sub-range for the given range</returns>
  779. private BufferRange GetBufferRange(ulong address, ulong size, bool write = false)
  780. {
  781. return GetBuffer(address, size, write).GetRange(address, size);
  782. }
  783. /// <summary>
  784. /// Gets a buffer for a given memory range.
  785. /// A buffer overlapping with the specified range is assumed to already exist on the cache.
  786. /// </summary>
  787. /// <param name="address">Start address of the memory range</param>
  788. /// <param name="size">Size in bytes of the memory range</param>
  789. /// <param name="write">Whether the buffer will be written to by this use</param>
  790. /// <returns>The buffer where the range is fully contained</returns>
  791. private Buffer GetBuffer(ulong address, ulong size, bool write = false)
  792. {
  793. Buffer buffer;
  794. if (size != 0)
  795. {
  796. lock (_buffers)
  797. {
  798. buffer = _buffers.FindFirstOverlap(address, size);
  799. }
  800. buffer.SynchronizeMemory(address, size);
  801. if (write)
  802. {
  803. buffer.SignalModified(address, size);
  804. }
  805. }
  806. else
  807. {
  808. lock (_buffers)
  809. {
  810. buffer = _buffers.FindFirstOverlap(address, 1);
  811. }
  812. }
  813. return buffer;
  814. }
  815. /// <summary>
  816. /// Performs guest to host memory synchronization of a given memory range.
  817. /// </summary>
  818. /// <param name="address">Start address of the memory range</param>
  819. /// <param name="size">Size in bytes of the memory range</param>
  820. private void SynchronizeBufferRange(ulong address, ulong size)
  821. {
  822. if (size != 0)
  823. {
  824. Buffer buffer;
  825. lock (_buffers)
  826. {
  827. buffer = _buffers.FindFirstOverlap(address, size);
  828. }
  829. buffer.SynchronizeMemory(address, size);
  830. }
  831. }
  832. /// <summary>
  833. /// Disposes all buffers in the cache.
  834. /// It's an error to use the buffer manager after disposal.
  835. /// </summary>
  836. public void Dispose()
  837. {
  838. lock (_buffers)
  839. {
  840. foreach (Buffer buffer in _buffers)
  841. {
  842. buffer.Dispose();
  843. }
  844. }
  845. }
  846. }
  847. }