BufferManager.cs 40 KB

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