BufferManager.cs 38 KB

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