CommandBuffer.h 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446
  1. // Copyright (C) 2009-2023, Panagiotis Christopoulos Charitos and contributors.
  2. // All rights reserved.
  3. // Code licensed under the BSD License.
  4. // http://www.anki3d.org/LICENSE
  5. #pragma once
  6. #include <AnKi/Gr/GrObject.h>
  7. #include <AnKi/Gr/Framebuffer.h>
  8. #include <AnKi/Util/Functions.h>
  9. #include <AnKi/Util/WeakArray.h>
  10. #include <AnKi/Math.h>
  11. namespace anki {
  12. /// @addtogroup graphics
  13. /// @{
  14. class TextureBarrierInfo
  15. {
  16. public:
  17. Texture* m_texture = nullptr;
  18. TextureUsageBit m_previousUsage = TextureUsageBit::kNone;
  19. TextureUsageBit m_nextUsage = TextureUsageBit::kNone;
  20. TextureSubresourceInfo m_subresource;
  21. };
  22. class BufferBarrierInfo
  23. {
  24. public:
  25. Buffer* m_buffer = nullptr;
  26. BufferUsageBit m_previousUsage = BufferUsageBit::kNone;
  27. BufferUsageBit m_nextUsage = BufferUsageBit::kNone;
  28. PtrSize m_offset = 0;
  29. PtrSize m_size = 0;
  30. };
  31. class AccelerationStructureBarrierInfo
  32. {
  33. public:
  34. AccelerationStructure* m_as = nullptr;
  35. AccelerationStructureUsageBit m_previousUsage = AccelerationStructureUsageBit::kNone;
  36. AccelerationStructureUsageBit m_nextUsage = AccelerationStructureUsageBit::kNone;
  37. };
  38. class CopyBufferToBufferInfo
  39. {
  40. public:
  41. PtrSize m_sourceOffset = 0;
  42. PtrSize m_destinationOffset = 0;
  43. PtrSize m_range = 0;
  44. };
  45. /// Command buffer initialization flags.
  46. enum class CommandBufferFlag : U8
  47. {
  48. kNone = 0,
  49. kSecondLevel = 1 << 0,
  50. /// It will contain a handfull of commands.
  51. kSmallBatch = 1 << 3,
  52. /// Will contain graphics, compute and transfer work.
  53. kGeneralWork = 1 << 4,
  54. /// Will contain only compute work. It binds to async compute queues.
  55. kComputeWork = 1 << 5,
  56. };
  57. ANKI_ENUM_ALLOW_NUMERIC_OPERATIONS(CommandBufferFlag)
  58. /// Command buffer init info.
  59. class CommandBufferInitInfo : public GrBaseInitInfo
  60. {
  61. public:
  62. FramebufferPtr m_framebuffer; ///< For second level command buffers.
  63. Array<TextureUsageBit, kMaxColorRenderTargets> m_colorAttachmentUsages = {};
  64. TextureUsageBit m_depthStencilAttachmentUsage = TextureUsageBit::kNone;
  65. CommandBufferFlag m_flags = CommandBufferFlag::kNone;
  66. CommandBufferInitInfo(CString name = {})
  67. : GrBaseInitInfo(name)
  68. {
  69. }
  70. };
  71. /// Command buffer.
  72. class CommandBuffer : public GrObject
  73. {
  74. ANKI_GR_OBJECT
  75. public:
  76. static constexpr GrObjectType kClassType = GrObjectType::kCommandBuffer;
  77. /// Finalize and submit if it's primary command buffer and just finalize if it's second level.
  78. /// @param[in] waitFences Optionally wait for some fences.
  79. /// @param[out] signalFence Optionaly create fence that will be signaled when the submission is done.
  80. void flush(ConstWeakArray<FencePtr> waitFences = {}, FencePtr* signalFence = nullptr);
  81. /// @name State manipulation
  82. /// @{
  83. /// Bind vertex buffer.
  84. void bindVertexBuffer(U32 binding, const BufferPtr& buff, PtrSize offset, PtrSize stride, VertexStepRate stepRate = VertexStepRate::kVertex);
  85. /// Setup a vertex attribute.
  86. void setVertexAttribute(U32 location, U32 buffBinding, Format fmt, PtrSize relativeOffset);
  87. /// Bind index buffer.
  88. void bindIndexBuffer(const BufferPtr& buff, PtrSize offset, IndexType type);
  89. /// Enable primitive restart.
  90. void setPrimitiveRestart(Bool enable);
  91. /// Set the viewport.
  92. void setViewport(U32 minx, U32 miny, U32 width, U32 height);
  93. /// Set the scissor rect. To disable the scissor just set a rect bigger than the viewport. By default it's disabled.
  94. void setScissor(U32 minx, U32 miny, U32 width, U32 height);
  95. /// Set fill mode.
  96. void setFillMode(FillMode mode);
  97. /// Set cull mode.
  98. /// By default it's FaceSelectionBit::BACK.
  99. void setCullMode(FaceSelectionBit mode);
  100. /// Set depth offset and units. Set zeros to both to disable it.
  101. void setPolygonOffset(F32 factor, F32 units);
  102. /// Set stencil operations. To disable stencil test put StencilOperation::KEEP to all operations.
  103. void setStencilOperations(FaceSelectionBit face, StencilOperation stencilFail, StencilOperation stencilPassDepthFail,
  104. StencilOperation stencilPassDepthPass);
  105. /// Set stencil compare operation.
  106. void setStencilCompareOperation(FaceSelectionBit face, CompareOperation comp);
  107. /// Set the stencil compare mask.
  108. void setStencilCompareMask(FaceSelectionBit face, U32 mask);
  109. /// Set the stencil write mask.
  110. void setStencilWriteMask(FaceSelectionBit face, U32 mask);
  111. /// Set the stencil reference.
  112. void setStencilReference(FaceSelectionBit face, U32 ref);
  113. /// Enable/disable depth write. To disable depth testing set depth write to false and depth compare operation to
  114. /// always.
  115. void setDepthWrite(Bool enable);
  116. /// Set depth compare operation. By default it's less.
  117. void setDepthCompareOperation(CompareOperation op);
  118. /// Enable/disable alpha to coverage.
  119. void setAlphaToCoverage(Bool enable);
  120. /// Set color channel write mask.
  121. void setColorChannelWriteMask(U32 attachment, ColorBit mask);
  122. /// Set blend factors seperate.
  123. /// By default the values of srcRgb, dstRgb, srcA and dstA are BlendFactor::ONE, BlendFactor::ZERO,
  124. /// BlendFactor::ONE, BlendFactor::ZERO respectively.
  125. void setBlendFactors(U32 attachment, BlendFactor srcRgb, BlendFactor dstRgb, BlendFactor srcA, BlendFactor dstA);
  126. /// Set blend factors.
  127. void setBlendFactors(U32 attachment, BlendFactor src, BlendFactor dst)
  128. {
  129. setBlendFactors(attachment, src, dst, src, dst);
  130. }
  131. /// Set the blend operation seperate.
  132. /// By default the values of funcRgb and funcA are BlendOperation::ADD, BlendOperation::ADD respectively.
  133. void setBlendOperation(U32 attachment, BlendOperation funcRgb, BlendOperation funcA);
  134. /// Set the blend operation.
  135. void setBlendOperation(U32 attachment, BlendOperation func)
  136. {
  137. setBlendOperation(attachment, func, func);
  138. }
  139. /// Set the rasterizatin order. By default it's RasterizationOrder::ORDERED.
  140. void setRasterizationOrder(RasterizationOrder order);
  141. /// Set the line width. By default it's undefined.
  142. void setLineWidth(F32 lineWidth);
  143. /// Bind texture and sample.
  144. /// @param set The set to bind to.
  145. /// @param binding The binding to bind to.
  146. /// @param texView The texture view to bind.
  147. /// @param sampler The sampler to override the default sampler of the tex.
  148. /// @param arrayIdx The array index if the binding is an array.
  149. void bindTextureAndSampler(U32 set, U32 binding, const TextureViewPtr& texView, const SamplerPtr& sampler, U32 arrayIdx = 0);
  150. /// Bind sampler.
  151. /// @param set The set to bind to.
  152. /// @param binding The binding to bind to.
  153. /// @param sampler The sampler to override the default sampler of the tex.
  154. /// @param arrayIdx The array index if the binding is an array.
  155. void bindSampler(U32 set, U32 binding, const SamplerPtr& sampler, U32 arrayIdx = 0);
  156. /// Bind a texture.
  157. /// @param set The set to bind to.
  158. /// @param binding The binding to bind to.
  159. /// @param texView The texture view to bind.
  160. /// @param arrayIdx The array index if the binding is an array.
  161. void bindTexture(U32 set, U32 binding, const TextureViewPtr& texView, U32 arrayIdx = 0);
  162. /// Bind uniform buffer.
  163. /// @param set The set to bind to.
  164. /// @param binding The binding to bind to.
  165. /// @param[in,out] buff The buffer to bind.
  166. /// @param offset The base of the binding.
  167. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  168. /// of the buffer.
  169. /// @param arrayIdx The array index if the binding is an array.
  170. void bindUniformBuffer(U32 set, U32 binding, const BufferPtr& buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  171. /// Bind storage buffer.
  172. /// @param set The set to bind to.
  173. /// @param binding The binding to bind to.
  174. /// @param[in,out] buff The buffer to bind.
  175. /// @param offset The base of the binding.
  176. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  177. /// of the buffer.
  178. /// @param arrayIdx The array index if the binding is an array.
  179. void bindStorageBuffer(U32 set, U32 binding, const BufferPtr& buff, PtrSize offset, PtrSize range, U32 arrayIdx = 0);
  180. /// Bind load/store image.
  181. /// @param set The set to bind to.
  182. /// @param binding The binding to bind to.
  183. /// @param img The view to bind.
  184. /// @param arrayIdx The array index if the binding is an array.
  185. void bindImage(U32 set, U32 binding, const TextureViewPtr& img, U32 arrayIdx = 0);
  186. /// Bind texture buffer.
  187. /// @param set The set to bind to.
  188. /// @param binding The binding to bind to.
  189. /// @param[in,out] buff The buffer to bind.
  190. /// @param offset The base of the binding.
  191. /// @param range The bytes to bind starting from the offset. If it's kMaxPtrSize then map from offset to the end
  192. /// of the buffer.
  193. /// @param fmt The format of the buffer.
  194. /// @param arrayIdx The array index if the binding is an array.
  195. void bindReadOnlyTextureBuffer(U32 set, U32 binding, const BufferPtr& buff, PtrSize offset, PtrSize range, Format fmt, U32 arrayIdx = 0);
  196. /// Bind an acceleration structure.
  197. /// @param set The set to bind to.
  198. /// @param binding The binding to bind to.
  199. /// @param[in,out] as The AS to bind.
  200. /// @param arrayIdx The array index if the binding is an array.
  201. void bindAccelerationStructure(U32 set, U32 binding, const AccelerationStructurePtr& as, U32 arrayIdx = 0);
  202. /// Bind the bindless descriptor set into a slot.
  203. void bindAllBindless(U32 set);
  204. /// Set push constants.
  205. void setPushConstants(const void* data, U32 dataSize);
  206. /// Bind a program.
  207. void bindShaderProgram(const ShaderProgramPtr& prog);
  208. /// Begin renderpass.
  209. /// The minx, miny, width, height control the area that the load and store operations will happen. If the scissor is
  210. /// bigger than the render area the results are undefined.
  211. void beginRenderPass(const FramebufferPtr& fb, const Array<TextureUsageBit, kMaxColorRenderTargets>& colorAttachmentUsages,
  212. TextureUsageBit depthStencilAttachmentUsage, U32 minx = 0, U32 miny = 0, U32 width = kMaxU32, U32 height = kMaxU32);
  213. /// End renderpass.
  214. void endRenderPass();
  215. /// Set VRS rate of the following drawcalls. By default it's 1x1.
  216. void setVrsRate(VrsRate rate);
  217. /// @}
  218. /// @name Jobs
  219. /// @{
  220. void drawElements(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 firstIndex = 0, U32 baseVertex = 0, U32 baseInstance = 0);
  221. void drawArrays(PrimitiveTopology topology, U32 count, U32 instanceCount = 1, U32 first = 0, U32 baseInstance = 0);
  222. void drawElementsIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, const BufferPtr& indirectBuff);
  223. void drawArraysIndirect(PrimitiveTopology topology, U32 drawCount, PtrSize offset, const BufferPtr& indirectBuff);
  224. void dispatchCompute(U32 groupCountX, U32 groupCountY, U32 groupCountZ);
  225. /// Trace rays.
  226. ///
  227. /// The 1st thing in the sbtBuffer is the ray gen shader group handle:
  228. /// @code RG = RG_offset @endcode
  229. /// The RG_offset is equal to the stbBufferOffset.
  230. ///
  231. /// Then the sbtBuffer contains the miss shader group handles and their data. The indexing is as follows:
  232. /// @code M = M_offset + M_stride * R_miss @endcode
  233. /// The M_offset is equal to stbBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize.
  234. /// The M_stride is equal to GpuDeviceCapabilities::m_sbtRecordSize.
  235. /// The R_miss is defined in the traceRayEXT and it's the "ray type".
  236. ///
  237. /// After the miss shaders the sbtBuffer has the hit group shader group handles and their data. The indexing is:
  238. /// @code HG = HG_offset + (HG_stride * (R_offset + R_stride * G_id + I_offset)) @endcode
  239. /// The HG_offset is equal to sbtBufferOffset + GpuDeviceCapabilities::m_sbtRecordSize * (missShaderCount + 1).
  240. /// The HG_stride is equal GpuDeviceCapabilities::m_sbtRecordSize * rayTypecount.
  241. /// The R_offset and R_stride are provided in traceRayEXT. The R_offset is the "ray type" and R_stride the number of
  242. /// ray types.
  243. /// The G_id is always 0 ATM.
  244. /// The I_offset is the AccelerationStructureInstance::m_hitgroupSbtRecordIndex.
  245. ///
  246. /// @param[in] sbtBuffer The SBT buffer.
  247. /// @param sbtBufferOffset Offset inside the sbtBuffer where SBT records start.
  248. /// @param hitGroupSbtRecordCount The number of SBT records that contain hit groups.
  249. /// @param sbtRecordSize The size of an SBT record
  250. /// @param rayTypecount The number of ray types hosted in the pipeline. See above on how it's been used.
  251. /// @param width Width.
  252. /// @param height Height.
  253. /// @param depth Depth.
  254. void traceRays(const BufferPtr& sbtBuffer, PtrSize sbtBufferOffset, U32 sbtRecordSize, U32 hitGroupSbtRecordCount, U32 rayTypeCount, U32 width,
  255. U32 height, U32 depth);
  256. /// Generate mipmaps for non-3D textures. You have to transition all the mip levels of this face and layer to
  257. /// TextureUsageBit::kGenerateMipmaps before calling this method.
  258. /// @param texView The texture view to generate mips. It should point to a subresource that contains the whole
  259. /// mip chain and only one face and one layer.
  260. void generateMipmaps2d(const TextureViewPtr& texView);
  261. /// Generate mipmaps only for 3D textures.
  262. /// @param texView The texture view to generate mips.
  263. void generateMipmaps3d(const TextureViewPtr& tex);
  264. /// Blit from surface to surface.
  265. /// @param srcView The source view that points to a surface.
  266. /// @param dstView The destination view that points to a surface.
  267. void blitTextureViews(const TextureViewPtr& srcView, const TextureViewPtr& destView);
  268. /// Clear a single texture surface. Can be used for all textures except 3D.
  269. /// @param[in,out] texView The texture view to clear.
  270. /// @param[in] clearValue The value to clear it with.
  271. void clearTextureView(const TextureViewPtr& texView, const ClearValue& clearValue);
  272. /// Copy a buffer to a texture surface or volume.
  273. /// @param buff The source buffer to copy from.
  274. /// @param offset The offset in the buffer to start reading from.
  275. /// @param range The size of the buffer to read.
  276. /// @param texView The texture view that points to a surface or volume to write to.
  277. void copyBufferToTextureView(const BufferPtr& buff, PtrSize offset, PtrSize range, const TextureViewPtr& texView);
  278. /// Fill a buffer with some value.
  279. /// @param[in,out] buff The buffer to fill.
  280. /// @param offset From where to start filling. Must be multiple of 4.
  281. /// @param size The bytes to fill. Must be multiple of 4 or kMaxPtrSize to indicate the whole buffer.
  282. /// @param value The value to fill the buffer with.
  283. void fillBuffer(const BufferPtr& buff, PtrSize offset, PtrSize size, U32 value);
  284. /// Write the occlusion result to buffer.
  285. /// @param[in] queries The queries to write the result of.
  286. /// @param offset The offset inside the buffer to write the result.
  287. /// @param buff The buffer to update.
  288. void writeOcclusionQueriesResultToBuffer(ConstWeakArray<OcclusionQuery*> queries, PtrSize offset, const BufferPtr& buff);
  289. /// Copy buffer to buffer.
  290. /// @param[in] src Source buffer.
  291. /// @param srcOffset Offset in the src buffer.
  292. /// @param[out] dst Destination buffer.
  293. /// @param dstOffset Offset in the destination buffer.
  294. /// @param range Size to copy.
  295. void copyBufferToBuffer(const BufferPtr& src, PtrSize srcOffset, const BufferPtr& dst, PtrSize dstOffset, PtrSize range)
  296. {
  297. Array<CopyBufferToBufferInfo, 1> copies = {{{srcOffset, dstOffset, range}}};
  298. copyBufferToBuffer(src, dst, copies);
  299. }
  300. /// Copy buffer to buffer.
  301. /// @param[in] src Source buffer.
  302. /// @param[out] dst Destination buffer.
  303. /// @param copies Info on the copies.
  304. void copyBufferToBuffer(const BufferPtr& src, const BufferPtr& dst, ConstWeakArray<CopyBufferToBufferInfo> copies);
  305. /// Build the acceleration structure.
  306. void buildAccelerationStructure(const AccelerationStructurePtr& as);
  307. /// Do upscaling by an external upscaler
  308. /// @param[in] upscaler the upscaler to use for upscaling
  309. /// @param[in] inColor Source LowRes RenderTarget.
  310. /// @param[out] outUpscaledColor Destination HighRes RenderTarget
  311. /// @param[in] motionVectors Motion Vectors
  312. /// @param[in] depth Depth attachment
  313. /// @param[in] exposure 1x1 Texture containing exposure
  314. /// @param[in] resetAccumulation Whether to clean or not any temporal history
  315. /// @param[in] jitterOffset Jittering offset that was applied during the generation of sourceTexture
  316. /// @param[in] motionVectorsScale Any scale factor that might need to be applied to the motionVectorsTexture (i.e UV
  317. /// space to Pixel space conversion)
  318. void upscale(const GrUpscalerPtr& upscaler, const TextureViewPtr& inColor, const TextureViewPtr& outUpscaledColor,
  319. const TextureViewPtr& motionVectors, const TextureViewPtr& depth, const TextureViewPtr& exposure, const Bool resetAccumulation,
  320. const Vec2& jitterOffset, const Vec2& motionVectorsScale);
  321. /// @}
  322. /// @name Sync
  323. /// @{
  324. void setPipelineBarrier(ConstWeakArray<TextureBarrierInfo> textures, ConstWeakArray<BufferBarrierInfo> buffers,
  325. ConstWeakArray<AccelerationStructureBarrierInfo> accelerationStructures);
  326. /// @}
  327. /// @name Other
  328. /// @{
  329. /// Reset queries before beginOcclusionQuery.
  330. void resetOcclusionQueries(ConstWeakArray<OcclusionQuery*> queries);
  331. /// Begin query.
  332. void beginOcclusionQuery(const OcclusionQueryPtr& query);
  333. /// End query.
  334. void endOcclusionQuery(const OcclusionQueryPtr& query);
  335. /// Reset timestamp queries before writeTimestamp.
  336. void resetTimestampQueries(ConstWeakArray<TimestampQuery*> queries);
  337. /// Write a timestamp.
  338. void writeTimestamp(const TimestampQueryPtr& query);
  339. /// Append second level command buffers.
  340. void pushSecondLevelCommandBuffers(ConstWeakArray<CommandBuffer*> cmdbs);
  341. Bool isEmpty() const;
  342. /// @}
  343. protected:
  344. /// Construct.
  345. CommandBuffer(CString name)
  346. : GrObject(kClassType, name)
  347. {
  348. }
  349. /// Destroy.
  350. ~CommandBuffer()
  351. {
  352. }
  353. private:
  354. /// Allocate and initialize a new instance.
  355. [[nodiscard]] static CommandBuffer* newInstance(const CommandBufferInitInfo& init);
  356. };
  357. /// @}
  358. } // end namespace anki